Skip to main content

virtual_file_system/file_system/
mod.rs

1mod utilities;
2
3use crate::pipe::Pipe;
4use crate::{Directory, File, IoErrorKind, ItemStatic, Result, ResultExt, poll};
5use alloc::borrow::ToOwned;
6use alloc::vec;
7use alloc::{boxed::Box, collections::BTreeMap};
8use core::cell::RefCell;
9use core::ptr;
10use exported_file_system::{BlockDevice, CharacterDevice, CreateFlags, Permission, Permissions};
11use file_system::{
12    AccessFlags, AttributeFlags, AttributeOperations, Attributes, BaseOperations, Context,
13    FileSystemOperations, Flags, Inode, Kind, Path, PathOwned, StateFlags, Statistics,
14};
15use synchronization::{
16    blocking_mutex::{Mutex as BlockingMutex, raw::CriticalSectionRawMutex},
17    rwlock::RwLock,
18};
19use task::TaskIdentifier;
20use users::{GroupIdentifier, UserIdentifier};
21use utilities::*;
22
23/// Maximum bytes stored in a symbolic-link target.
24const MAX_SYMLINK_TARGET_LENGTH: usize = 4096;
25
26/// Policy controlling when read operations update a mounted file system's access time.
27///
28/// The policy applies to read-only opens: reads through a read-write handle
29/// do not update the access time, so a read-write open that writes nothing
30/// costs no metadata commit.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum AccessTimePolicy {
33    /// Never update the access time on read. Writes update the modification
34    /// and status times on the first write of more than zero bytes after an
35    /// open or a flush.
36    Never,
37    /// Update the access time on read only when it is older than the modification or status time, or older than 24 hours.
38    #[default]
39    Relative,
40    /// Always update the access time on read, including directory opens.
41    Always,
42}
43
44/// Mount-time options for a file system.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub struct MountOptions {
47    pub access_time_policy: AccessTimePolicy,
48}
49
50impl MountOptions {
51    pub const fn new() -> Self {
52        Self {
53            access_time_policy: AccessTimePolicy::Relative,
54        }
55    }
56
57    pub const fn with_access_time_policy(mut self, access_time_policy: AccessTimePolicy) -> Self {
58        self.access_time_policy = access_time_policy;
59        self
60    }
61}
62
63pub fn initialize(
64    task_manager: &'static task::Manager,
65    users_manager: &'static users::Manager,
66    time_manager: &'static time::Manager<'static>,
67    root_file_system: impl FileSystemOperations + 'static,
68) -> Result<VirtualFileSystem> {
69    initialize_with_options(
70        task_manager,
71        users_manager,
72        time_manager,
73        root_file_system,
74        MountOptions::default(),
75    )
76}
77
78pub fn initialize_with_options(
79    task_manager: &'static task::Manager,
80    users_manager: &'static users::Manager,
81    time_manager: &'static time::Manager<'static>,
82    root_file_system: impl FileSystemOperations + 'static,
83    options: MountOptions,
84) -> Result<VirtualFileSystem> {
85    Ok(VirtualFileSystem::new_with_options(
86        task_manager,
87        users_manager,
88        time_manager,
89        root_file_system,
90        options,
91    ))
92}
93
94/// The virtual file system.
95///
96pub struct VirtualFileSystem {
97    task_manager: &'static task::Manager,
98    users_manager: &'static users::Manager,
99    time_manager: &'static time::Manager<'static>,
100    /// Mounted file systems.
101    file_systems: RwLock<CriticalSectionRawMutex, FileSystemsArray>,
102    /// Character devices.
103    character_device: RwLock<CriticalSectionRawMutex, CharacterDevicesMap>,
104    /// Block devices.
105    block_device: RwLock<CriticalSectionRawMutex, BlockDevicesMap>,
106    /// Pipes.
107    pipes: RwLock<CriticalSectionRawMutex, PipeMap>,
108    /// Set by [`Self::shutdown_storage`]; never cleared.
109    writes_frozen: portable_atomic::AtomicBool,
110    /// References that closes which could not wait for their lock still owe (see
111    /// [`Self::close_without_waiting`]). Given back by whoever takes that lock next to
112    /// look at the counts. The mutex is never held across a wait.
113    owed: BlockingMutex<CriticalSectionRawMutex, RefCell<alloc::vec::Vec<Owed>>>,
114}
115
116/// One reference a close gave back without its lock: a file system by address, as
117/// `ptr::eq` on the registered object compares it, or a device by the inode of the entry
118/// its opening took the reference on (two mounted devices may share a pointer).
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Owed {
121    FileSystem(usize),
122    BlockDevice(Inode),
123    CharacterDevice(Inode),
124}
125
126impl Owed {
127    /// What closing `item` gives back, if anything (a pipe owes nothing). A device needs
128    /// the inode its opening took the reference on.
129    fn of(item: &ItemStatic, device_inode: Option<Inode>) -> Result<Option<Self>> {
130        Ok(match item {
131            ItemStatic::File(file_system) | ItemStatic::Directory(file_system) => Some(
132                Self::FileSystem(ptr::from_ref(*file_system).cast::<()>().addr()),
133            ),
134            ItemStatic::BlockDevice(_) => Some(Self::BlockDevice(
135                device_inode.ok_or(IoErrorKind::BadDescriptor)?,
136            )),
137            ItemStatic::CharacterDevice(_) => Some(Self::CharacterDevice(
138                device_inode.ok_or(IoErrorKind::BadDescriptor)?,
139            )),
140            ItemStatic::Pipe(_) => None,
141            ItemStatic::FileSystem(_) => return Err(IoErrorKind::BadDescriptor),
142        })
143    }
144}
145
146/// Give back one reference to the file system at `address`. False if it is not mounted.
147fn release_file_system(file_systems: &mut FileSystemsArray, address: usize) -> bool {
148    file_systems
149        .iter_mut()
150        .find(|file_system| ptr::from_ref(file_system.file_system).cast::<()>().addr() == address)
151        .map(|file_system| {
152            file_system.reference_count = file_system.reference_count.saturating_sub(1)
153        })
154        .is_some()
155}
156
157fn release_block_device(devices: &mut BlockDevicesMap, inode: Inode) -> bool {
158    devices
159        .get_mut(&inode)
160        .map(|device| device.reference_count = device.reference_count.saturating_sub(1))
161        .is_some()
162}
163
164fn release_character_device(devices: &mut CharacterDevicesMap, inode: Inode) -> bool {
165    devices
166        .get_mut(&inode)
167        .map(|device| device.reference_count = device.reference_count.saturating_sub(1))
168        .is_some()
169}
170
171impl VirtualFileSystem {
172    pub fn task_manager(&self) -> &'static task::Manager {
173        self.task_manager
174    }
175
176    pub fn users_manager(&self) -> &'static users::Manager {
177        self.users_manager
178    }
179
180    pub fn new(
181        task_manager: &'static task::Manager,
182        users_manager: &'static users::Manager,
183        time_manager: &'static time::Manager<'static>,
184        root_file_system: impl FileSystemOperations + 'static,
185    ) -> Self {
186        Self::new_with_options(
187            task_manager,
188            users_manager,
189            time_manager,
190            root_file_system,
191            MountOptions::default(),
192        )
193    }
194
195    pub fn new_with_options(
196        task_manager: &'static task::Manager,
197        users_manager: &'static users::Manager,
198        time_manager: &'static time::Manager<'static>,
199        root_file_system: impl FileSystemOperations + 'static,
200        options: MountOptions,
201    ) -> Self {
202        let file_systems = vec![InternalFileSystem {
203            reference_count: 1,
204            is_mounted: true,
205            mount_point: Path::ROOT.to_owned(),
206            access_time_policy: options.access_time_policy,
207            file_system: Box::leak(Box::new(root_file_system)),
208        }];
209
210        Self {
211            task_manager,
212            users_manager,
213            time_manager,
214            file_systems: RwLock::new(file_systems),
215            character_device: RwLock::new(BTreeMap::new()),
216            block_device: RwLock::new(BTreeMap::new()),
217            pipes: RwLock::new(BTreeMap::new()),
218            writes_frozen: portable_atomic::AtomicBool::new(false),
219            owed: BlockingMutex::new(RefCell::new(alloc::vec::Vec::new())),
220        }
221    }
222
223    fn settle_file_systems(&self, file_systems: &mut FileSystemsArray) {
224        self.settle_kind(|entry| match entry {
225            Owed::FileSystem(address) => Some(release_file_system(file_systems, address)),
226            _ => None,
227        });
228    }
229
230    fn settle_block_devices(&self, devices: &mut BlockDevicesMap) {
231        self.settle_kind(|entry| match entry {
232            Owed::BlockDevice(address) => Some(release_block_device(devices, address)),
233            _ => None,
234        });
235    }
236
237    fn settle_character_devices(&self, devices: &mut CharacterDevicesMap) {
238        self.settle_kind(|entry| match entry {
239            Owed::CharacterDevice(address) => Some(release_character_device(devices, address)),
240            _ => None,
241        });
242    }
243
244    /// Give back the owed references `release` handles (it returns `Some` for those), keep
245    /// the others, and free the queue once it is empty.
246    fn settle_kind(&self, mut release: impl FnMut(Owed) -> Option<bool>) {
247        self.owed.lock(|owed| {
248            let mut owed = owed.borrow_mut();
249            if owed.is_empty() {
250                return;
251            }
252            // A reference whose object was unmounted meanwhile has nothing left to give.
253            owed.retain(|entry| release(*entry).is_none());
254            if owed.is_empty() {
255                *owed = alloc::vec::Vec::new();
256            }
257        });
258    }
259
260    /// Hold the namespace lock, the one path-based calls take, until `release` completes,
261    /// and return its output. Tests use it to suspend a task with the lock held, as an open
262    /// does while it waits for the task or user managers.
263    #[cfg(feature = "test_harness")]
264    pub async fn hold_namespace_lock<F: core::future::Future>(&self, release: F) -> F::Output {
265        let _file_systems = self.file_systems.write().await;
266        release.await
267    }
268
269    /// Hold the character device lock until `release` completes, and return its output.
270    /// An open of a character device takes it while it holds the namespace lock, so tests
271    /// use it to suspend a real open with the namespace lock held.
272    #[cfg(feature = "test_harness")]
273    pub async fn hold_character_device_lock<F: core::future::Future>(
274        &self,
275        release: F,
276    ) -> F::Output {
277        let _character_devices = self.character_device.write().await;
278        release.await
279    }
280
281    pub async fn uninitialize(&self) {
282        let mut file_systems = self.file_systems.write().await;
283
284        for internal_file_system in file_systems.drain(..) {
285            let _: Box<dyn FileSystemOperations> =
286                unsafe { Box::from_raw(internal_file_system.file_system as *const _ as *mut _) };
287        }
288    }
289
290    /// Commit and unmount every mounted filesystem for a system shutdown.
291    ///
292    /// Requires quiescence: if any filesystem still has an open file or
293    /// directory, nothing changes and `ResourceBusy` is returned. Otherwise
294    /// new writes are frozen for good, then mounts are unmounted deepest first
295    /// with the root last; each filesystem flushes its backing device. The
296    /// first failure is returned and the remaining mounts stay mounted (and
297    /// readable) for diagnosis. Nothing is deallocated: tasks that still hold
298    /// static references keep valid memory.
299    pub async fn shutdown_storage(&self) -> Result<()> {
300        let mut file_systems = self.file_systems.write().await;
301        self.settle_file_systems(&mut file_systems);
302        if file_systems
303            .iter()
304            .any(|file_system| file_system.reference_count > 1)
305        {
306            return Err(IoErrorKind::ResourceBusy);
307        }
308        self.writes_frozen
309            .store(true, portable_atomic::Ordering::Release);
310        // A nested mount point is always longer than the mount containing it.
311        let mut order: alloc::vec::Vec<usize> = (0..file_systems.len()).collect();
312        // Keep mount order for equal lengths so a failure leaves the same mounts readable.
313        order.sort_unstable_by_key(|&index| {
314            (
315                core::cmp::Reverse(file_systems[index].mount_point.as_str().len()),
316                index,
317            )
318        });
319        for index in order {
320            let file_system = &mut file_systems[index];
321            if file_system.is_mounted {
322                file_system.file_system.unmount()?;
323                file_system.is_mounted = false;
324            }
325        }
326        Ok(())
327    }
328
329    /// Mount a file system at a given mount point.
330    pub async fn mount_file_system(
331        &'static self,
332        file_system: impl FileSystemOperations + 'static,
333        path: impl AsRef<Path>,
334        task: TaskIdentifier,
335    ) -> Result<()> {
336        self.mount_file_system_with_options(file_system, path, task, MountOptions::default())
337            .await
338    }
339
340    /// Mount a file system at a given mount point with explicit mount options.
341    pub async fn mount_file_system_with_options(
342        &self,
343        file_system: impl FileSystemOperations + 'static,
344        path: impl AsRef<Path>,
345        task: TaskIdentifier,
346        options: MountOptions,
347    ) -> Result<()> {
348        let item = ItemStatic::FileSystem(Box::leak(Box::new(file_system)));
349        self.mount_static_with_permissions_and_options(
350            task,
351            path.as_ref(),
352            item,
353            Permissions::DEVICE_DEFAULT,
354            options,
355        )
356        .await
357    }
358
359    pub async fn unmount(&self, path: impl AsRef<Path>, force: bool) -> Result<()> {
360        self.unmount_inner(path.as_ref(), force).await
361    }
362
363    async fn unmount_inner(&self, path: &Path, force: bool) -> Result<()> {
364        if !path.is_valid() || !path.is_absolute() || path.is_root() {
365            return Err(IoErrorKind::InvalidPath);
366        }
367
368        let mut file_systems = self.file_systems.write().await;
369        self.settle_file_systems(&mut file_systems);
370
371        if Self::protects_mount(&file_systems, path, false) {
372            return Err(IoErrorKind::ResourceBusy);
373        }
374
375        let parent_path = path.go_parent().ok_or(IoErrorKind::InvalidPath)?;
376
377        let (underlying_file_system, _, _) =
378            Self::get_file_system_from_path(&file_systems, parent_path)?; // Get the file system identifier and the relative path
379        let relative_path = path
380            .strip_prefix_absolute(&underlying_file_system.mount_point)
381            .ok_or(IoErrorKind::InvalidPath)?;
382
383        let mut attributes =
384            Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Inode);
385        Self::get_attributes(
386            underlying_file_system.file_system,
387            relative_path,
388            &mut attributes,
389        )
390        .await?;
391
392        let kind = attributes.get_kind().ok_or(IoErrorKind::InputOutput)?;
393        let inode = *attributes.get_inode().ok_or(IoErrorKind::InputOutput)?;
394
395        match kind {
396            Kind::Directory => {
397                let mountpoint_index = file_systems
398                    .iter()
399                    .position(|file_system| {
400                        let mount_point: &Path = file_system.mount_point.as_ref();
401                        file_system.is_mounted && mount_point == path
402                    })
403                    .ok_or(IoErrorKind::InvalidPath)?;
404                let file_system = &file_systems[mountpoint_index];
405
406                if file_system.reference_count > 1 && !force {
407                    return Err(IoErrorKind::ResourceBusy);
408                }
409
410                // Unmount only removes the overlay; the original directory
411                // (including hidden contents) belongs to the underlying namespace.
412                file_system.file_system.unmount()?;
413                file_systems[mountpoint_index].is_mounted = false;
414            }
415            Kind::BlockDevice => {
416                let mut block_devices = self.block_device.write().await;
417                self.settle_block_devices(&mut block_devices);
418                let device = block_devices
419                    .get_mut(&inode)
420                    .ok_or(IoErrorKind::StaleHandle)?;
421
422                if device.reference_count > 1 && !force {
423                    return Err(IoErrorKind::ResourceBusy);
424                }
425
426                underlying_file_system.file_system.remove(relative_path)?;
427                device.device.unmount()?;
428            }
429            Kind::CharacterDevice => {
430                let mut character_devices = self.character_device.write().await;
431                self.settle_character_devices(&mut character_devices);
432                let device = character_devices
433                    .get_mut(&inode)
434                    .ok_or(IoErrorKind::StaleHandle)?;
435
436                if device.reference_count > 1 && !force {
437                    return Err(IoErrorKind::ResourceBusy);
438                }
439
440                underlying_file_system.file_system.remove(relative_path)?;
441                device.device.unmount()?;
442            }
443            _ => {
444                return Err(IoErrorKind::Unsupported);
445            }
446        }
447
448        Ok(())
449    }
450
451    pub async fn unmount_all(&self) -> Result<()> {
452        let mut file_systems = self.file_systems.write().await;
453        let mut block_devices = self.block_device.write().await;
454        let mut character_devices = self.character_device.write().await;
455
456        for file_system in file_systems.drain(..) {
457            if file_system.is_mounted {
458                file_system.file_system.unmount()?;
459            }
460            let _: Box<dyn FileSystemOperations> =
461                unsafe { Box::from_raw(file_system.file_system as *const _ as *mut _) };
462        }
463
464        for block_device in block_devices.values_mut() {
465            block_device.device.unmount()?;
466            let _: Box<dyn BlockDevice> =
467                unsafe { Box::from_raw(block_device.device as *const _ as *mut _) };
468        }
469        block_devices.clear();
470
471        for character_device in character_devices.values_mut() {
472            character_device.device.unmount()?;
473            let _: Box<dyn CharacterDevice> =
474                unsafe { Box::from_raw(character_device.device as *const _ as *mut _) };
475        }
476        character_devices.clear();
477
478        Ok(())
479    }
480
481    /// Resolve a directory path once, following symbolic links and verifying
482    /// that it names an accessible directory on a mount with confined namespace
483    /// guarantees.
484    ///
485    /// Callers can keep the returned canonical path as the `root` argument to
486    /// `*_beneath` operations; subsequent revalidation of that `root` does not
487    /// follow symbolic links.
488    pub async fn resolve_directory_root(
489        &self,
490        task: TaskIdentifier,
491        path: impl AsRef<Path>,
492    ) -> Result<PathOwned> {
493        let file_systems = self.file_systems.read().await;
494        let user = self.task_manager.get_user(task).await.map_io_error()?;
495        let mut resolved = self
496            .resolve_path(&file_systems, path.as_ref(), true, false, user, task)
497            .await?;
498        if !file_systems[resolved.mount_index]
499            .file_system
500            .supports_confined_namespace()
501        {
502            return Err(IoErrorKind::PathEscapesRoot);
503        }
504        let mut attributes = Attributes::new().set_mask(
505            AttributeFlags::Kind
506                | AttributeFlags::User
507                | AttributeFlags::Group
508                | AttributeFlags::Permissions,
509        );
510        Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await?;
511        if attributes.get_kind() != Some(&Kind::Directory) {
512            return Err(IoErrorKind::NotADirectory);
513        }
514        self.check_attributes_permissions(&attributes, Permission::Execute, user)
515            .await?;
516        self.validate_confined_root(&file_systems, &resolved.path, user, task)
517            .await?;
518        Ok(resolved.path.as_ref().to_owned())
519    }
520
521    pub async fn open_directory<'a>(
522        &'a self,
523        task: TaskIdentifier,
524        path: &impl AsRef<Path>,
525    ) -> Result<Directory<'a>> {
526        self.open_directory_with_root(task, path.as_ref(), None, true)
527            .await
528    }
529
530    /// Open a directory, controlling whether a final symbolic link is followed.
531    pub async fn open_directory_with_lookup<'a>(
532        &'a self,
533        task: TaskIdentifier,
534        path: &impl AsRef<Path>,
535        follow_final: bool,
536    ) -> Result<Directory<'a>> {
537        self.open_directory_with_root(task, path.as_ref(), None, follow_final)
538            .await
539    }
540
541    /// Resolve relative paths beneath the supplied root directory.
542    pub async fn open_directory_beneath<'a>(
543        &'a self,
544        task: TaskIdentifier,
545        path: &impl AsRef<Path>,
546        root: &Path,
547    ) -> Result<Directory<'a>> {
548        self.open_directory_with_root(task, path.as_ref(), Some(root), true)
549            .await
550    }
551
552    /// Resolve relative paths beneath the supplied root directory, controlling
553    /// whether a final symbolic link is followed.
554    pub async fn open_directory_beneath_with_lookup<'a>(
555        &'a self,
556        task: TaskIdentifier,
557        path: &impl AsRef<Path>,
558        root: &Path,
559        follow_final: bool,
560    ) -> Result<Directory<'a>> {
561        self.open_directory_with_root(task, path.as_ref(), Some(root), follow_final)
562            .await
563    }
564
565    async fn open_directory_with_root<'a>(
566        &'a self,
567        task: TaskIdentifier,
568        path: &Path,
569        root: Option<&Path>,
570        follow_final: bool,
571    ) -> Result<Directory<'a>> {
572        let mut file_systems = self.file_systems.write().await;
573
574        let user = self.task_manager.get_user(task).await.map_io_error()?;
575        let mut resolved = self
576            .resolve_path_with_root(&file_systems, path, follow_final, false, user, task, root)
577            .await?;
578
579        let mut attributes = Attributes::new().set_mask(
580            AttributeFlags::Kind
581                | AttributeFlags::User
582                | AttributeFlags::Group
583                | AttributeFlags::Permissions,
584        );
585        Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await?;
586        let kind = *attributes.get_kind().ok_or(IoErrorKind::InputOutput)?;
587
588        if kind == Kind::SymbolicLink {
589            return Err(IoErrorKind::SymlinkLoop);
590        }
591        if kind != Kind::Directory {
592            return Err(IoErrorKind::NotADirectory);
593        }
594
595        if !resolved.path.is_root() {
596            self.check_target_parent_permissions(
597                &file_systems,
598                &mut resolved,
599                Permission::Execute,
600                user,
601                task,
602            )
603            .await?;
604        }
605        self.check_attributes_permissions(&attributes, Permission::Read, user)
606            .await?;
607
608        if file_systems[resolved.mount_index].access_time_policy == AccessTimePolicy::Always {
609            // An unsynchronized or unrepresentable UTC must not prevent reading
610            // existing storage. Keep its previous access timestamp in that case.
611            if let Ok(time) = self.get_time() {
612                let attributes = Attributes::new().set_access(time);
613                let mask = attributes.get_mask().intersection(
614                    file_systems[resolved.mount_index]
615                        .file_system
616                        .writable_attributes(),
617                );
618                Self::set_target_attributes(
619                    &file_systems,
620                    &mut resolved,
621                    &attributes.set_mask(mask),
622                )
623                .await?;
624            }
625        }
626
627        let context = if let Some(directory_handle) = resolved.current_directory.take() {
628            directory_handle.into_context()
629        } else if let Some(parent) = resolved.parent_directory.as_ref() {
630            let entry_name = resolved.entry_name(&file_systems)?;
631            let mut context = Context::new_empty();
632            poll(|| {
633                file_systems[resolved.mount_index]
634                    .file_system
635                    .lookup_directory_entry(parent.context(), entry_name, &mut context)
636            })
637            .await?;
638            context
639        } else {
640            let mut context = Context::new_empty();
641            let relative_path = resolved.relative_path(&file_systems)?;
642            poll(|| {
643                file_systems[resolved.mount_index]
644                    .file_system
645                    .lookup_directory(&mut context, relative_path)
646            })
647            .await?;
648            context
649        };
650
651        let internal_file_system = &mut file_systems[resolved.mount_index];
652        internal_file_system.reference_count += 1;
653
654        Ok(Directory::new(
655            self,
656            internal_file_system.file_system,
657            Flags::new(AccessFlags::Read, None, None),
658            context,
659        ))
660    }
661
662    /// Check the caller's parent-directory authorization for creating a file.
663    /// Resolves paths exactly as a nonexclusive create would, without creating
664    /// or opening a file. This is a UI preflight, not a reservation: the actual
665    /// create must still enforce access when it executes.
666    pub async fn check_create_file_access(
667        &self,
668        task: TaskIdentifier,
669        path: &impl AsRef<Path>,
670    ) -> Result<()> {
671        self.check_create_file_access_inner(task, path.as_ref())
672            .await
673    }
674
675    async fn check_create_file_access_inner(
676        &self,
677        task: TaskIdentifier,
678        path: &Path,
679    ) -> Result<()> {
680        let user = self.task_manager.get_user(task).await.map_io_error()?;
681        let file_systems = self.file_systems.read().await;
682        let mut resolved = self
683            .resolve_path(&file_systems, path, true, true, user, task)
684            .await?;
685        if resolved.path.is_root() {
686            return Err(IoErrorKind::InvalidPath);
687        }
688        self.check_target_parent_permissions(
689            &file_systems,
690            &mut resolved,
691            Permission::Write | Permission::Execute,
692            user,
693            task,
694        )
695        .await
696    }
697
698    pub async fn open<'a>(
699        &'a self,
700        path: &impl AsRef<Path>,
701        flags: Flags,
702        task: TaskIdentifier,
703    ) -> Result<File<'a>> {
704        self.open_with_root(
705            path.as_ref(),
706            flags,
707            task,
708            None,
709            true,
710            Permissions::FILE_DEFAULT,
711        )
712        .await
713    }
714
715    /// Open a file; a file that the call creates gets `permissions` instead of
716    /// `Permissions::FILE_DEFAULT`, from its creation on. An existing file
717    /// keeps its permissions.
718    pub async fn open_with_permissions<'a>(
719        &'a self,
720        path: &impl AsRef<Path>,
721        flags: Flags,
722        task: TaskIdentifier,
723        permissions: Permissions,
724    ) -> Result<File<'a>> {
725        self.open_with_root(path.as_ref(), flags, task, None, true, permissions)
726            .await
727    }
728
729    /// Open a file, controlling whether a final symbolic link is followed.
730    pub async fn open_with_lookup<'a>(
731        &'a self,
732        path: &impl AsRef<Path>,
733        flags: Flags,
734        task: TaskIdentifier,
735        follow_final: bool,
736    ) -> Result<File<'a>> {
737        self.open_with_root(
738            path.as_ref(),
739            flags,
740            task,
741            None,
742            follow_final,
743            Permissions::FILE_DEFAULT,
744        )
745        .await
746    }
747
748    /// Resolve relative paths beneath the supplied root directory.
749    pub async fn open_beneath<'a>(
750        &'a self,
751        path: &impl AsRef<Path>,
752        flags: Flags,
753        task: TaskIdentifier,
754        root: &Path,
755    ) -> Result<File<'a>> {
756        self.open_with_root(
757            path.as_ref(),
758            flags,
759            task,
760            Some(root),
761            true,
762            Permissions::FILE_DEFAULT,
763        )
764        .await
765    }
766
767    /// Resolve relative paths beneath the supplied root directory, atomically
768    /// enforcing `follow_final` for the final component under the namespace lock.
769    pub async fn open_beneath_with_lookup<'a>(
770        &'a self,
771        path: &impl AsRef<Path>,
772        flags: Flags,
773        task: TaskIdentifier,
774        root: &Path,
775        follow_final: bool,
776    ) -> Result<File<'a>> {
777        self.open_with_root(
778            path.as_ref(),
779            flags,
780            task,
781            Some(root),
782            follow_final,
783            Permissions::FILE_DEFAULT,
784        )
785        .await
786    }
787
788    async fn open_with_root<'a>(
789        &'a self,
790        requested_path: &Path,
791        flags: Flags,
792        task: TaskIdentifier,
793        root: Option<&Path>,
794        follow_final: bool,
795        create_permissions: Permissions,
796    ) -> Result<File<'a>> {
797        let authority = self.task_manager.authority(task).await.map_io_error()?;
798
799        let mut file_systems = self.file_systems.write().await;
800
801        let user = self.task_manager.get_user(task).await.map_io_error()?;
802        let group = self
803            .users_manager
804            .get_user_primary_group(user)
805            .await
806            .map_io_error()?;
807        let time = self.get_time();
808        let (mode, open, _) = flags.split();
809
810        if (open.contains(CreateFlags::Truncate) || flags.get_state().contains(StateFlags::Append))
811            && !mode.contains(AccessFlags::Write)
812        {
813            return Err(IoErrorKind::InvalidFlags);
814        }
815        let exclusive_create =
816            open.contains(CreateFlags::Create) && open.contains(CreateFlags::Exclusive);
817        let mut resolved = self
818            .resolve_path_with_root(
819                &file_systems,
820                requested_path,
821                follow_final && !exclusive_create,
822                open.contains(CreateFlags::Create),
823                user,
824                task,
825                root,
826            )
827            .await?;
828
829        let mut attributes = Attributes::new().set_mask(AttributeFlags::Kind);
830        // An entry left without attributes by a power loss during creation is
831        // replaced by a create, after the parent write permission check below,
832        // instead of failing the name until a reformat.
833        let mut replace_attribute_less = false;
834        let mut exists =
835            match Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await {
836                Ok(()) => true,
837                Err(IoErrorKind::NotFound) => false,
838                Err(IoErrorKind::MissingAttribute) if open.contains(CreateFlags::Create) => {
839                    replace_attribute_less = true;
840                    false
841                }
842                Err(error) => return Err(error),
843            };
844        if exists && exclusive_create {
845            // Distinguish a complete entry from an attribute-less one (whose
846            // kind the backend can still report from the directory entry):
847            // the former is reported as existing, the latter is replaced.
848            let mut probe = Attributes::new().set_mask(AttributeFlags::User);
849            match Self::target_attributes(&file_systems, &mut resolved, &mut probe).await {
850                Ok(()) => return Err(IoErrorKind::AlreadyExists),
851                Err(IoErrorKind::MissingAttribute) => {
852                    replace_attribute_less = true;
853                    exists = false;
854                }
855                Err(error) => return Err(error),
856            }
857        }
858        if exists {
859            if attributes.get_kind() == Some(&Kind::SymbolicLink) {
860                return Err(IoErrorKind::SymlinkLoop);
861            }
862            self.check_target_permissions_with_parent(
863                &file_systems,
864                &mut resolved,
865                mode.into_permission(),
866                Permission::Execute,
867                user,
868                task,
869            )
870            .await?;
871        } else if open.contains(CreateFlags::Create) {
872            if requested_path.as_str().len() > 1 && requested_path.as_str().ends_with('/') {
873                return Err(IoErrorKind::NotADirectory);
874            }
875            // Authorize before mutating the filesystem, including failed redirections.
876            self.check_target_parent_permissions(
877                &file_systems,
878                &mut resolved,
879                Permission::Write | Permission::Execute,
880                user,
881                task,
882            )
883            .await?;
884            if replace_attribute_less {
885                // Remove the attribute-less entry left by the interrupted
886                // creation; the create below replaces it. The sticky-bit check
887                // of a plain remove does not apply here: an attribute-less
888                // entry has no readable owner, so on a sticky parent the
889                // replace is allowed for anyone with write permission on the
890                // parent, exactly like the remove path for root and the
891                // parent owner.
892                let target_file_system = file_systems[resolved.mount_index].file_system;
893                if let Some(parent) = resolved.parent_directory.as_ref() {
894                    let entry_name = resolved.entry_name(&file_systems)?;
895                    poll(|| target_file_system.remove_entry(parent.context(), entry_name)).await?;
896                } else {
897                    let relative_path = resolved.relative_path(&file_systems)?;
898                    poll(|| target_file_system.remove(relative_path)).await?;
899                }
900            }
901            let time = time?;
902            // The backend persists these attributes with the new entry itself
903            // (LittleFS commits them atomically with the file), so no separate
904            // metadata commit follows the creation.
905            let attributes = Attributes::new()
906                .set_user(user)
907                .set_group(group)
908                .set_creation(time)
909                .set_modification(time)
910                .set_status(time)
911                .set_access(time)
912                .set_permissions(create_permissions)
913                .set_kind(Kind::File);
914            let mask = attributes.get_mask().intersection(
915                file_systems[resolved.mount_index]
916                    .file_system
917                    .writable_attributes(),
918            );
919            let attributes = attributes.set_mask(mask);
920            if let Some(parent) = resolved.parent_directory.as_ref() {
921                let entry_name = resolved.entry_name(&file_systems)?;
922                let target_file_system = file_systems[resolved.mount_index].file_system;
923                poll(|| {
924                    target_file_system.create_file_entry(parent.context(), entry_name, &attributes)
925                })
926                .await?;
927            } else {
928                let target_file_system = file_systems[resolved.mount_index].file_system;
929                let relative_path = resolved.relative_path(&file_systems)?;
930                poll(|| target_file_system.create_file(relative_path, &attributes)).await?;
931            }
932        } else {
933            return Err(IoErrorKind::NotFound);
934        }
935
936        // Preserve previous timestamps while UTC is unavailable; never publish
937        // uptime or wrap a signed epoch into unsigned filesystem metadata.
938        // Opening for writing changes no time by itself: the modification and
939        // status times follow the first write of more than zero bytes and any
940        // truncate, and the access time follows reads per the mount policy.
941        // Only read-only opens update the access time: reads through a
942        // read-write handle that writes nothing keep the previous access time,
943        // so an idle read-write open costs no metadata commit.
944        if exists
945            && !mode.contains(AccessFlags::Write)
946            && let Ok(time) = time
947        {
948            Self::update_target_read_access_time(&file_systems, &mut resolved, time).await?;
949        }
950
951        let mut attributes =
952            Attributes::new().set_mask(AttributeFlags::Inode | AttributeFlags::Kind);
953        Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await?;
954
955        let kind = attributes.get_kind().ok_or(IoErrorKind::InputOutput)?;
956        let inode = *attributes.get_inode().ok_or(IoErrorKind::InputOutput)?;
957
958        let mut context = Context::new_empty();
959
960        let file = match kind {
961            Kind::CharacterDevice => {
962                let mut devices = self.character_device.write().await;
963
964                let device = devices.get_mut(&inode).ok_or(IoErrorKind::StaleHandle)?;
965
966                poll(|| device.device.open(&mut context)).await?;
967                device.reference_count += 1;
968
969                File::new(
970                    self,
971                    ItemStatic::CharacterDevice(device.device),
972                    flags,
973                    context,
974                )
975                .with_device_inode(inode)
976            }
977            Kind::BlockDevice => {
978                let mut devices = self.block_device.write().await;
979
980                let device = devices.get_mut(&inode).ok_or(IoErrorKind::StaleHandle)?;
981
982                poll(|| device.device.open(&mut context)).await?;
983                device.reference_count += 1;
984
985                File::new(self, ItemStatic::BlockDevice(device.device), flags, context)
986                    .with_device_inode(inode)
987            }
988            Kind::Pipe => {
989                let mut pipes = self.pipes.write().await;
990                let pipe = pipes.get_mut(&inode).ok_or(IoErrorKind::StaleHandle)?;
991
992                context = pipe.pipe.open_context(flags.get_access())?;
993                File::new(self, ItemStatic::Pipe(pipe.pipe.clone()), flags, context)
994            }
995            Kind::File => {
996                // A file just created by this open is already empty: passing
997                // Truncate again would only cost an extra commit on close.
998                let truncate = flags.get_create().contains(CreateFlags::Truncate) && exists;
999                let lookup_flags = Flags::new(
1000                    flags.get_access(),
1001                    Some(if truncate {
1002                        CreateFlags::Truncate
1003                    } else {
1004                        CreateFlags::from_bits_truncate(0)
1005                    }),
1006                    Some(flags.get_state()),
1007                );
1008                if let Some(parent) = resolved.parent_directory.as_ref() {
1009                    let entry_name = resolved.entry_name(&file_systems)?;
1010                    let target_file_system = file_systems[resolved.mount_index].file_system;
1011                    poll(|| {
1012                        target_file_system.lookup_file_entry(
1013                            parent.context(),
1014                            entry_name,
1015                            &mut context,
1016                            lookup_flags,
1017                        )
1018                    })
1019                    .await?;
1020                } else {
1021                    let target_file_system = file_systems[resolved.mount_index].file_system;
1022                    let relative_path = resolved.relative_path(&file_systems)?;
1023                    poll(|| {
1024                        target_file_system.lookup_file(&mut context, relative_path, lookup_flags)
1025                    })
1026                    .await?;
1027                }
1028
1029                // O_TRUNC mutates the file: record the modification and status
1030                // times on the handle. The backend commits them atomically with
1031                // the truncation on sync or close.
1032                if truncate && mode.contains(AccessFlags::Write) {
1033                    let target_file_system = file_systems[resolved.mount_index].file_system;
1034                    if let Ok(time) = time {
1035                        Self::set_handle_times(target_file_system, &mut context, time)?;
1036                    }
1037                }
1038
1039                let internal_file_system = &mut file_systems[resolved.mount_index];
1040                internal_file_system.reference_count += 1;
1041
1042                File::new(
1043                    self,
1044                    ItemStatic::File(internal_file_system.file_system),
1045                    flags,
1046                    context,
1047                )
1048            }
1049            Kind::SymbolicLink => return Err(IoErrorKind::SymlinkLoop),
1050            _ => Err(IoErrorKind::Unsupported)?,
1051        };
1052
1053        Ok(file.with_authority(authority))
1054    }
1055
1056    /// Drop the device or pipe registration taken for a mount whose backing
1057    /// entry creation failed. File system mounts register nothing.
1058    async fn unregister_mounted_item(&self, item: &ItemStatic, inode: Inode) {
1059        match item {
1060            ItemStatic::BlockDevice(_) => {
1061                self.block_device.write().await.remove(&inode);
1062            }
1063            ItemStatic::CharacterDevice(_) => {
1064                self.character_device.write().await.remove(&inode);
1065            }
1066            ItemStatic::Pipe(_) => {
1067                self.pipes.write().await.remove(&inode);
1068            }
1069            _ => {}
1070        }
1071    }
1072
1073    pub async fn mount_static(
1074        &self,
1075        task: TaskIdentifier,
1076        path: impl AsRef<Path>,
1077        item: ItemStatic,
1078    ) -> Result<()> {
1079        self.mount_static_with_permissions(task, path, item, Permissions::DEVICE_DEFAULT)
1080            .await
1081    }
1082
1083    /// Publish a mount with its final permissions under the namespace lock.
1084    /// Sensitive devices must not become briefly accessible with default modes.
1085    pub async fn mount_static_with_permissions(
1086        &self,
1087        task: TaskIdentifier,
1088        path: impl AsRef<Path>,
1089        item: ItemStatic,
1090        permissions: Permissions,
1091    ) -> Result<()> {
1092        self.mount_static_with_permissions_and_options(
1093            task,
1094            path.as_ref(),
1095            item,
1096            permissions,
1097            MountOptions::default(),
1098        )
1099        .await
1100    }
1101
1102    async fn mount_static_with_permissions_and_options(
1103        &self,
1104        task: TaskIdentifier,
1105        path: &Path,
1106        item: ItemStatic,
1107        permissions: Permissions,
1108        options: MountOptions,
1109    ) -> Result<()> {
1110        if !path.is_valid() || !path.is_absolute() || path.is_root() {
1111            return Err(IoErrorKind::InvalidPath);
1112        }
1113
1114        let mut file_systems = self.file_systems.write().await; // Get the file systems
1115
1116        if file_systems.iter().any(|file_system| {
1117            let mount_point: &Path = file_system.mount_point.as_ref();
1118            file_system.is_mounted && mount_point == path
1119        }) {
1120            return Err(IoErrorKind::AlreadyExists);
1121        }
1122
1123        let (parent_file_system, relative_path, _) =
1124            Self::get_mutable_file_system_from_path(&mut file_systems, path)?; // Get the file system identifier and the relative path
1125
1126        let (time, user, group) = self.get_time_user_group(task).await?;
1127
1128        self.check_permissions(
1129            parent_file_system.file_system,
1130            relative_path.go_parent().ok_or(IoErrorKind::InvalidPath)?,
1131            Permission::Write,
1132            user,
1133            task,
1134        )
1135        .await?;
1136
1137        // The inode and kind are known before the entry is created, so the
1138        // backend can persist the full attribute set with the new entry in
1139        // one commit instead of rewriting it afterwards.
1140        let inode = match item {
1141            ItemStatic::BlockDevice(device) => {
1142                let mut block_devices = self.block_device.write().await;
1143                let inode = Self::get_new_inode(&*block_devices).ok_or(IoErrorKind::NoSpace)?;
1144                block_devices.insert(
1145                    inode,
1146                    InternalBlockDevice {
1147                        reference_count: 1,
1148                        device,
1149                    },
1150                );
1151                inode
1152            }
1153            ItemStatic::CharacterDevice(device) => {
1154                let mut character_devices = self.character_device.write().await;
1155                let inode = Self::get_new_inode(&*character_devices).ok_or(IoErrorKind::NoSpace)?;
1156                character_devices.insert(
1157                    inode,
1158                    InternalCharacterDevice {
1159                        reference_count: 1,
1160                        device,
1161                    },
1162                );
1163                inode
1164            }
1165            ItemStatic::FileSystem(_) => 0,
1166            ItemStatic::Pipe(ref pipe) => {
1167                let mut pipes = self.pipes.write().await;
1168                let inode = Self::get_new_inode(&*pipes).ok_or(IoErrorKind::NoSpace)?;
1169                pipes.insert(inode, InternalPipe { pipe: pipe.clone() });
1170                inode
1171            }
1172            _ => {
1173                return Err(IoErrorKind::BadDescriptor);
1174            }
1175        };
1176
1177        let underlying_kind = match &item {
1178            ItemStatic::FileSystem(_) => Kind::Directory,
1179            ItemStatic::BlockDevice(_) => Kind::BlockDevice,
1180            ItemStatic::CharacterDevice(_) => Kind::CharacterDevice,
1181            ItemStatic::Pipe(_) => Kind::Pipe,
1182            _ => {
1183                return Err(IoErrorKind::BadDescriptor);
1184            }
1185        };
1186
1187        let attributes = Attributes::new()
1188            .set_user(user)
1189            .set_group(group)
1190            .set_creation(time)
1191            .set_modification(time)
1192            .set_access(time)
1193            .set_status(time)
1194            .set_kind(underlying_kind)
1195            .set_permissions(permissions)
1196            .set_inode(inode);
1197        let mask = attributes
1198            .get_mask()
1199            .intersection(parent_file_system.file_system.writable_attributes());
1200        let attributes = attributes.set_mask(mask);
1201
1202        // An existing mount point directory keeps its attributes, as on Linux:
1203        // rewriting them at every boot would wear flash for nothing. New
1204        // entries are created with their final attributes in one commit.
1205        if let ItemStatic::FileSystem(_) = item {
1206            match parent_file_system
1207                .file_system
1208                .create_directory(relative_path, &attributes)
1209            {
1210                Ok(()) => {}
1211                Err(IoErrorKind::AlreadyExists) => {
1212                    let mut kind_attributes = Attributes::new().set_mask(AttributeFlags::Kind);
1213                    Self::get_attributes(
1214                        parent_file_system.file_system,
1215                        relative_path,
1216                        &mut kind_attributes,
1217                    )
1218                    .await?;
1219                    if kind_attributes.get_kind() != Some(&Kind::Directory) {
1220                        return Err(IoErrorKind::AlreadyExists);
1221                    }
1222                }
1223                Err(error) => {
1224                    self.unregister_mounted_item(&item, inode).await;
1225                    return Err(error);
1226                }
1227            }
1228        } else {
1229            if let Err(error) = parent_file_system
1230                .file_system
1231                .create_file(relative_path, &attributes)
1232            {
1233                self.unregister_mounted_item(&item, inode).await;
1234                return Err(error);
1235            }
1236        }
1237
1238        poll(|| {
1239            item.as_mount_operations()
1240                .ok_or(IoErrorKind::Unsupported)?
1241                .mount()
1242        })
1243        .await?;
1244
1245        if let ItemStatic::FileSystem(file_system) = item {
1246            file_systems.push(InternalFileSystem {
1247                reference_count: 1,
1248                is_mounted: true,
1249                mount_point: path.to_owned(),
1250                access_time_policy: options.access_time_policy,
1251                file_system,
1252            });
1253        }
1254
1255        Ok(())
1256    }
1257
1258    pub async fn mount_block_device(
1259        &self,
1260        task: TaskIdentifier,
1261        path: impl AsRef<Path>,
1262        device: impl BlockDevice + 'static,
1263    ) -> Result<()> {
1264        self.mount_static(
1265            task,
1266            path,
1267            ItemStatic::BlockDevice(Box::leak(Box::new(device))),
1268        )
1269        .await
1270    }
1271
1272    pub async fn mount_character_device(
1273        &self,
1274        task: TaskIdentifier,
1275        path: impl AsRef<Path>,
1276        device: impl CharacterDevice + 'static,
1277    ) -> Result<()> {
1278        self.mount_static(
1279            task,
1280            path,
1281            ItemStatic::CharacterDevice(Box::leak(Box::new(device))),
1282        )
1283        .await
1284    }
1285
1286    pub async fn create_named_pipe(
1287        &self,
1288        path: &impl AsRef<Path>,
1289        size: usize,
1290        task: TaskIdentifier,
1291    ) -> Result<()> {
1292        self.create_named_pipe_inner(path.as_ref(), size, task)
1293            .await
1294    }
1295
1296    async fn create_named_pipe_inner(
1297        &self,
1298        path: &Path,
1299        size: usize,
1300        task: TaskIdentifier,
1301    ) -> Result<()> {
1302        if size == 0 {
1303            return Err(IoErrorKind::InvalidArgument);
1304        }
1305        self.mount_static(
1306            task,
1307            path,
1308            ItemStatic::Pipe(synchronization::Arc::new(Pipe::new(size))),
1309        )
1310        .await
1311    }
1312
1313    pub async fn create_unnamed_pipe<'a>(
1314        &'a self,
1315        size: usize,
1316        status: StateFlags,
1317    ) -> Result<(File<'a>, File<'a>)> {
1318        if size == 0 {
1319            return Err(IoErrorKind::InvalidArgument);
1320        }
1321        let pipe = synchronization::Arc::new(Pipe::new(size));
1322
1323        let writer = File::new(
1324            self,
1325            ItemStatic::Pipe(pipe.clone()),
1326            Flags::new(AccessFlags::Write, None, Some(status)),
1327            pipe.open_context(AccessFlags::Write)?,
1328        );
1329
1330        let reader = File::new(
1331            self,
1332            ItemStatic::Pipe(pipe.clone()),
1333            Flags::new(AccessFlags::Read, None, Some(status)),
1334            pipe.open_context(AccessFlags::Read)?,
1335        );
1336
1337        Ok((reader, writer))
1338    }
1339
1340    pub async fn remove(&self, task: TaskIdentifier, path: impl AsRef<Path>) -> Result<()> {
1341        self.remove_with_root(task, path.as_ref(), None).await
1342    }
1343
1344    /// Resolve relative paths beneath the supplied root directory.
1345    pub async fn remove_beneath(
1346        &self,
1347        task: TaskIdentifier,
1348        path: impl AsRef<Path>,
1349        root: &Path,
1350    ) -> Result<()> {
1351        self.remove_with_root(task, path.as_ref(), Some(root)).await
1352    }
1353
1354    async fn remove_with_root(
1355        &self,
1356        task: TaskIdentifier,
1357        path: &Path,
1358        root: Option<&Path>,
1359    ) -> Result<()> {
1360        let file_systems = self.file_systems.write().await; // Serialize path resolution with removal.
1361        let user = self.task_manager.get_user(task).await.map_io_error()?;
1362        let mut resolved = self
1363            .resolve_path_with_root(&file_systems, path, false, false, user, task, root)
1364            .await?;
1365        if root.is_some_and(|root| resolved.path.as_str() == root.as_str())
1366            || Self::protects_mount(&file_systems, &resolved.path, true)
1367        {
1368            return Err(IoErrorKind::ResourceBusy);
1369        }
1370
1371        self.check_target_parent_permissions(
1372            &file_systems,
1373            &mut resolved,
1374            Permission::Write | Permission::Execute,
1375            user,
1376            task,
1377        )
1378        .await?;
1379
1380        self.check_target_sticky_permissions(&file_systems, &mut resolved, user)
1381            .await?;
1382
1383        let mut attributes =
1384            Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Inode);
1385        // An entry left without attributes by a power loss during creation is
1386        // not a pipe (those are VFS-created and always carry attributes), so
1387        // removal proceeds with a regular-file kind and inode 0. Backends that
1388        // report the kind from the directory entry itself (LittleFS) answer
1389        // this request directly.
1390        let (inode, kind) =
1391            match Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await {
1392                Ok(()) => (
1393                    *attributes.get_inode().ok_or(IoErrorKind::InputOutput)?,
1394                    *attributes.get_kind().ok_or(IoErrorKind::InputOutput)?,
1395                ),
1396                Err(IoErrorKind::MissingAttribute) => (0, Kind::File),
1397                Err(error) => return Err(error),
1398            };
1399
1400        if kind == Kind::Pipe {
1401            let mut named_pipes = self.pipes.write().await;
1402
1403            named_pipes.remove(&inode);
1404        }
1405
1406        let target_file_system = file_systems[resolved.mount_index].file_system;
1407        if let Some(parent) = resolved.parent_directory.as_ref() {
1408            let entry_name = resolved.entry_name(&file_systems)?;
1409            poll(|| target_file_system.remove_entry(parent.context(), entry_name)).await?;
1410        } else {
1411            let relative_path = resolved.relative_path(&file_systems)?;
1412            poll(|| target_file_system.remove(relative_path)).await?;
1413        }
1414
1415        Ok(())
1416    }
1417
1418    pub async fn create_directory(
1419        &self,
1420        task: TaskIdentifier,
1421        path: &impl AsRef<Path>,
1422    ) -> Result<()> {
1423        self.create_directory_with_permissions(task, path, Permissions::DIRECTORY_DEFAULT)
1424            .await
1425    }
1426
1427    /// Create a directory with the specified permissions from the start.
1428    pub async fn create_directory_with_permissions(
1429        &self,
1430        task: TaskIdentifier,
1431        path: &impl AsRef<Path>,
1432        permissions: Permissions,
1433    ) -> Result<()> {
1434        self.create_directory_with_root(task, path.as_ref(), None, permissions)
1435            .await
1436    }
1437
1438    /// Resolve relative paths beneath the supplied root directory.
1439    pub async fn create_directory_beneath(
1440        &self,
1441        task: TaskIdentifier,
1442        path: &impl AsRef<Path>,
1443        root: &Path,
1444    ) -> Result<()> {
1445        self.create_directory_with_root(
1446            task,
1447            path.as_ref(),
1448            Some(root),
1449            Permissions::DIRECTORY_DEFAULT,
1450        )
1451        .await
1452    }
1453
1454    async fn create_directory_with_root(
1455        &self,
1456        task: TaskIdentifier,
1457        path: &Path,
1458        root: Option<&Path>,
1459        permissions: Permissions,
1460    ) -> Result<()> {
1461        let file_systems = self.file_systems.write().await; // Serialize path resolution with creation.
1462        let (time, user, group) = self.get_time_user_group(task).await?;
1463        let mut resolved = self
1464            .resolve_path_with_root(&file_systems, path, false, true, user, task, root)
1465            .await?;
1466
1467        // A mount point or confinement root always exists.
1468        if resolved.path.is_root()
1469            || root.is_some_and(|root| resolved.path.as_str() == root.as_str())
1470            || resolved.relative_path(&file_systems)?.is_root()
1471        {
1472            return Err(IoErrorKind::AlreadyExists);
1473        }
1474
1475        // Like POSIX mkdir, an existing entry is reported before the parent
1476        // write check: resolution already required search permission on the
1477        // parent, so this reveals nothing a lookup would not. An entry left
1478        // without attributes by a power loss during creation is replaced
1479        // after the parent write check instead of failing the name.
1480        let mut attributes = Attributes::new().set_mask(AttributeFlags::Kind);
1481        let mut replace_attribute_less = false;
1482        match Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await {
1483            Ok(()) => {
1484                // Distinguish a complete entry from an attribute-less one:
1485                // the former is reported as existing, the latter is replaced.
1486                let mut probe = Attributes::new().set_mask(AttributeFlags::User);
1487                match Self::target_attributes(&file_systems, &mut resolved, &mut probe).await {
1488                    Ok(()) => return Err(IoErrorKind::AlreadyExists),
1489                    Err(IoErrorKind::MissingAttribute) => replace_attribute_less = true,
1490                    Err(error) => return Err(error),
1491                }
1492            }
1493            Err(IoErrorKind::NotFound) => {}
1494            Err(IoErrorKind::MissingAttribute) => replace_attribute_less = true,
1495            Err(error) => return Err(error),
1496        }
1497
1498        self.check_target_parent_permissions(
1499            &file_systems,
1500            &mut resolved,
1501            Permission::Write | Permission::Execute,
1502            user,
1503            task,
1504        )
1505        .await?;
1506
1507        if replace_attribute_less {
1508            // Remove the attribute-less entry left by the interrupted
1509            // creation; the create below replaces it. The sticky-bit check of
1510            // a plain remove does not apply here: an attribute-less entry has
1511            // no readable owner, so on a sticky parent the replace is allowed
1512            // for anyone with write permission on the parent, exactly like
1513            // the remove path for root and the parent owner.
1514            let target_file_system = file_systems[resolved.mount_index].file_system;
1515            if let Some(parent) = resolved.parent_directory.as_ref() {
1516                let entry_name = resolved.entry_name(&file_systems)?;
1517                poll(|| target_file_system.remove_entry(parent.context(), entry_name)).await?;
1518            } else {
1519                let relative_path = resolved.relative_path(&file_systems)?;
1520                poll(|| target_file_system.remove(relative_path)).await?;
1521            }
1522        }
1523
1524        let target_file_system = file_systems[resolved.mount_index].file_system;
1525        // The backend persists these attributes with the new directory entry
1526        // itself, so no separate metadata commit follows the creation.
1527        let attributes = Attributes::new()
1528            .set_inode(0)
1529            .set_links(1)
1530            .set_user(user)
1531            .set_group(group)
1532            .set_creation(time)
1533            .set_modification(time)
1534            .set_access(time)
1535            .set_status(time)
1536            .set_kind(Kind::Directory)
1537            .set_permissions(permissions);
1538        let mask = attributes
1539            .get_mask()
1540            .intersection(target_file_system.writable_attributes());
1541        let attributes = attributes.set_mask(mask);
1542
1543        if let Some(parent) = resolved.parent_directory.as_ref() {
1544            let entry_name = resolved.entry_name(&file_systems)?;
1545            poll(|| {
1546                target_file_system.create_directory_entry(parent.context(), entry_name, &attributes)
1547            })
1548            .await?;
1549        } else {
1550            let relative_path = resolved.relative_path(&file_systems)?;
1551            poll(|| target_file_system.create_directory(relative_path, &attributes)).await?;
1552        }
1553
1554        Ok(())
1555    }
1556
1557    /// Create a symbolic link at `link` whose target is interpreted in the
1558    /// caller's virtual namespace. The target may be dangling or cross mounts.
1559    ///
1560    /// Invalid caller input is reported as `InvalidPath` (unusable target or
1561    /// link path), `NameTooLong` (target over the link limit) and `NotFound`
1562    /// for an empty target, which is POSIX `symlink("")` failing with ENOENT.
1563    pub async fn create_symlink(
1564        &self,
1565        task: TaskIdentifier,
1566        target: &Path,
1567        link: &Path,
1568    ) -> Result<()> {
1569        self.create_symlink_with_root(task, target, link, None)
1570            .await
1571    }
1572
1573    /// Resolve relative paths beneath the supplied root directory.
1574    pub async fn create_symlink_beneath(
1575        &self,
1576        task: TaskIdentifier,
1577        target: &Path,
1578        link: &Path,
1579        root: &Path,
1580    ) -> Result<()> {
1581        self.create_symlink_with_root(task, target, link, Some(root))
1582            .await
1583    }
1584
1585    async fn create_symlink_with_root(
1586        &self,
1587        task: TaskIdentifier,
1588        target: &Path,
1589        link: &Path,
1590        root: Option<&Path>,
1591    ) -> Result<()> {
1592        // Caller input is validated first and reported with the kind that
1593        // describes the argument; `CorruptData` is reserved for stored link
1594        // targets that cannot be used.
1595        if target.is_empty() {
1596            // POSIX `symlink("", link)` fails with ENOENT.
1597            return Err(IoErrorKind::NotFound);
1598        }
1599        if target.get_length() > MAX_SYMLINK_TARGET_LENGTH {
1600            return Err(IoErrorKind::NameTooLong);
1601        }
1602        if !target.is_valid()
1603            || !link.is_valid()
1604            || (root.is_none() && !link.is_absolute())
1605            || link.is_root()
1606            || link.as_str().ends_with('/')
1607        {
1608            return Err(IoErrorKind::InvalidPath);
1609        }
1610
1611        let user = self.task_manager.get_user(task).await.map_io_error()?;
1612        // Serialize staging and publication against other VFS namespace
1613        // mutations, so temporary entries are never opened through the VFS.
1614        let file_systems = self.file_systems.write().await;
1615        let mut resolved_link = self
1616            .resolve_path_with_root(&file_systems, link, false, true, user, task, root)
1617            .await?;
1618        if resolved_link.path.is_root() || resolved_link.relative_path(&file_systems)?.is_root() {
1619            return Err(IoErrorKind::InvalidPath);
1620        }
1621        if root.is_some_and(|root| resolved_link.path.as_str() == root.as_str()) {
1622            return Err(IoErrorKind::AlreadyExists);
1623        }
1624        self.check_target_parent_permissions(
1625            &file_systems,
1626            &mut resolved_link,
1627            Permission::Write | Permission::Execute,
1628            user,
1629            task,
1630        )
1631        .await?;
1632
1633        let target_file_system = file_systems[resolved_link.mount_index].file_system;
1634        if target_file_system
1635            .persistent_attributes()
1636            .contains(AttributeFlags::Kind)
1637        {
1638            let mut existing = Attributes::new().set_mask(AttributeFlags::Kind);
1639            match Self::target_attributes(&file_systems, &mut resolved_link, &mut existing).await {
1640                Ok(()) => return Err(IoErrorKind::AlreadyExists),
1641                Err(IoErrorKind::NotFound) => {}
1642                Err(error) => return Err(error),
1643            }
1644
1645            let relative_link = resolved_link.relative_path(&file_systems)?;
1646            let stage_parent = relative_link.go_parent().ok_or(IoErrorKind::InvalidPath)?;
1647            let (time, _, _) = self.get_time_user_group(task).await?;
1648            let attributes = Attributes::new()
1649                .set_kind(Kind::SymbolicLink)
1650                .set_user(user)
1651                .set_group(self.task_manager.get_group(task).await.map_io_error()?)
1652                .set_permissions(Permissions::ALL_FULL)
1653                .set_creation(time)
1654                .set_modification(time)
1655                .set_access(time)
1656                .set_status(time);
1657
1658            let mut published = false;
1659            let mut last_error = IoErrorKind::AlreadyExists;
1660            for attempt in 0..64 {
1661                // The first candidates stay deterministic for simple
1662                // collision handling. Time-qualified candidates make stale
1663                // names left by interrupted boots unlikely to exhaust the
1664                // bounded retry set, without deleting an entry we did not
1665                // create.
1666                let stage_name = if attempt < 8 {
1667                    alloc::format!(".xila-link-stage-{attempt}")
1668                } else {
1669                    alloc::format!(".xila-link-stage-{}-{}", time.as_u64(), attempt - 8)
1670                };
1671                if let Some(parent) = resolved_link.parent_directory.as_ref() {
1672                    let entry_name = resolved_link.entry_name(&file_systems)?;
1673                    let stage_attributes = attributes.clone().set_mask(
1674                        attributes
1675                            .get_mask()
1676                            .intersection(target_file_system.writable_attributes()),
1677                    );
1678                    match poll(|| {
1679                        target_file_system.create_file_entry(
1680                            parent.context(),
1681                            &stage_name,
1682                            &stage_attributes,
1683                        )
1684                    })
1685                    .await
1686                    {
1687                        Ok(()) => {}
1688                        Err(IoErrorKind::AlreadyExists) => continue,
1689                        Err(error) => return Err(error),
1690                    }
1691                    let result = async {
1692                        let mut context = Context::new_empty();
1693                        poll(|| {
1694                            target_file_system.lookup_file_entry(
1695                                parent.context(),
1696                                &stage_name,
1697                                &mut context,
1698                                Flags::from(AccessFlags::Write),
1699                            )
1700                        })
1701                        .await?;
1702                        let write = target_file_system.write_sync(
1703                            &mut context,
1704                            target.as_str().as_bytes(),
1705                            0,
1706                        );
1707                        let flush = target_file_system.flush_sync(&mut context);
1708                        let close = BaseOperations::close(target_file_system, &mut context);
1709                        let written = write?;
1710                        flush?;
1711                        close?;
1712                        if written != target.get_length() {
1713                            return Err(IoErrorKind::InputOutput);
1714                        }
1715                        // The stage entry was created with the final attributes
1716                        // already persisted, so no second metadata commit here.
1717                        poll(|| {
1718                            target_file_system.rename_entry(
1719                                parent.context(),
1720                                &stage_name,
1721                                parent.context(),
1722                                entry_name,
1723                            )
1724                        })
1725                        .await
1726                    }
1727                    .await;
1728                    match result {
1729                        Ok(()) => {
1730                            published = true;
1731                            break;
1732                        }
1733                        Err(error) => {
1734                            last_error = error;
1735                            let _ = poll(|| {
1736                                target_file_system.remove_entry(parent.context(), &stage_name)
1737                            })
1738                            .await;
1739                            break;
1740                        }
1741                    }
1742                } else {
1743                    let stage_path = stage_parent
1744                        .to_owned()
1745                        .join(Path::from_str(&stage_name))
1746                        .ok_or(IoErrorKind::InvalidPath)?;
1747                    let stage_attributes = attributes.clone().set_mask(
1748                        attributes
1749                            .get_mask()
1750                            .intersection(target_file_system.writable_attributes()),
1751                    );
1752                    match poll(|| target_file_system.create_file(&stage_path, &stage_attributes))
1753                        .await
1754                    {
1755                        Ok(()) => {}
1756                        Err(IoErrorKind::AlreadyExists) => continue,
1757                        Err(error) => return Err(error),
1758                    }
1759
1760                    let result = async {
1761                        let mut context = Context::new_empty();
1762                        poll(|| {
1763                            target_file_system.lookup_file(
1764                                &mut context,
1765                                &stage_path,
1766                                Flags::from(AccessFlags::Write),
1767                            )
1768                        })
1769                        .await?;
1770                        let write = target_file_system.write_sync(
1771                            &mut context,
1772                            target.as_str().as_bytes(),
1773                            0,
1774                        );
1775                        let flush = target_file_system.flush_sync(&mut context);
1776                        let close = BaseOperations::close(target_file_system, &mut context);
1777                        let written = write?;
1778                        flush?;
1779                        close?;
1780                        if written != target.get_length() {
1781                            return Err(IoErrorKind::InputOutput);
1782                        }
1783
1784                        // The stage entry was created with the final attributes
1785                        // already persisted, so no second metadata commit here.
1786                        poll(|| target_file_system.rename(&stage_path, relative_link)).await
1787                    }
1788                    .await;
1789
1790                    match result {
1791                        Ok(()) => {
1792                            published = true;
1793                            break;
1794                        }
1795                        Err(error) => {
1796                            last_error = error;
1797                            let _ = poll(|| target_file_system.remove(&stage_path)).await;
1798                            break;
1799                        }
1800                    }
1801                }
1802            }
1803            if !published {
1804                return Err(last_error);
1805            }
1806        } else {
1807            // Native symlink support is an adapter detail for filesystems such
1808            // as HostFS that cannot persist Xila Kind metadata on ordinary files.
1809            let native_target_owned = if target.is_absolute() {
1810                let parent = resolved_link
1811                    .path
1812                    .go_parent()
1813                    .ok_or(IoErrorKind::InvalidPath)?;
1814                let parent_depth = parent
1815                    .get_components()
1816                    .filter(|component| matches!(component, file_system::Component::Normal(_)))
1817                    .count();
1818                let mut relative = alloc::string::String::with_capacity(
1819                    parent_depth.saturating_mul(3) + target.get_length(),
1820                );
1821                for _ in 0..parent_depth {
1822                    relative.push_str("../");
1823                }
1824                let target_text = target.as_str().trim_start_matches('/');
1825                if target_text.is_empty() && relative.is_empty() {
1826                    relative.push('.');
1827                } else {
1828                    relative.push_str(target_text);
1829                }
1830                Some(relative)
1831            } else {
1832                None
1833            };
1834            let native_target = native_target_owned
1835                .as_deref()
1836                .map(Path::from_str)
1837                .unwrap_or(target);
1838            let symlink_attributes = Attributes::new()
1839                .set_kind(Kind::SymbolicLink)
1840                .set_user(user)
1841                .set_group(self.task_manager.get_group(task).await.map_io_error()?)
1842                .set_permissions(Permissions::ALL_FULL)
1843                .set_mask(
1844                    AttributeFlags::Kind
1845                        | AttributeFlags::User
1846                        | AttributeFlags::Group
1847                        | AttributeFlags::Permissions,
1848                );
1849            if let Some(parent) = resolved_link.parent_directory.as_ref() {
1850                let entry_name = resolved_link.entry_name(&file_systems)?;
1851                poll(|| {
1852                    target_file_system.create_symlink_entry(
1853                        native_target,
1854                        parent.context(),
1855                        entry_name,
1856                        &symlink_attributes,
1857                    )
1858                })
1859                .await?;
1860            } else {
1861                let relative_link = resolved_link.relative_path(&file_systems)?;
1862                poll(|| {
1863                    target_file_system.create_symlink(
1864                        native_target,
1865                        relative_link,
1866                        &symlink_attributes,
1867                    )
1868                })
1869                .await?;
1870            }
1871        }
1872        Ok(())
1873    }
1874
1875    /// Read a symbolic link target without following it into caller-owned,
1876    /// bounded storage. Returns the number of bytes written.
1877    pub async fn read_symlink(
1878        &self,
1879        task: TaskIdentifier,
1880        link: &Path,
1881        buffer: &mut [u8],
1882    ) -> Result<usize> {
1883        self.read_symlink_with_root(task, link, buffer, None).await
1884    }
1885
1886    /// Resolve relative paths beneath the supplied root directory.
1887    pub async fn read_symlink_beneath(
1888        &self,
1889        task: TaskIdentifier,
1890        link: &Path,
1891        buffer: &mut [u8],
1892        root: &Path,
1893    ) -> Result<usize> {
1894        self.read_symlink_with_root(task, link, buffer, Some(root))
1895            .await
1896    }
1897
1898    async fn read_symlink_with_root(
1899        &self,
1900        task: TaskIdentifier,
1901        link: &Path,
1902        buffer: &mut [u8],
1903        root: Option<&Path>,
1904    ) -> Result<usize> {
1905        if !link.is_valid() || (root.is_none() && !link.is_absolute()) || link.is_root() {
1906            return Err(IoErrorKind::InvalidPath);
1907        }
1908
1909        let user = self.task_manager.get_user(task).await.map_io_error()?;
1910        let file_systems = self.file_systems.read().await;
1911        let mut resolved_link = self
1912            .resolve_path_with_root(&file_systems, link, false, false, user, task, root)
1913            .await?;
1914        if resolved_link.path.is_root() || resolved_link.relative_path(&file_systems)?.is_root() {
1915            return Err(IoErrorKind::InvalidArgument);
1916        }
1917        self.check_target_parent_permissions(
1918            &file_systems,
1919            &mut resolved_link,
1920            Permission::Execute,
1921            user,
1922            task,
1923        )
1924        .await?;
1925        let mut attributes =
1926            Attributes::new().set_mask(AttributeFlags::Kind | AttributeFlags::Size);
1927        Self::target_attributes(&file_systems, &mut resolved_link, &mut attributes).await?;
1928        if attributes.get_kind() != Some(&Kind::SymbolicLink) {
1929            // POSIX `readlink` on something that is not a link: EINVAL.
1930            return Err(IoErrorKind::InvalidArgument);
1931        }
1932        let size = *attributes.get_size().ok_or(IoErrorKind::InputOutput)? as usize;
1933        if size > MAX_SYMLINK_TARGET_LENGTH || size > buffer.len() {
1934            return Err(IoErrorKind::NameTooLong);
1935        }
1936        let target_file_system = file_systems[resolved_link.mount_index].file_system;
1937        if let Some(parent) = resolved_link.parent_directory.as_ref() {
1938            let entry_name = resolved_link.entry_name(&file_systems)?;
1939            match poll(|| {
1940                target_file_system.read_symlink_entry(parent.context(), entry_name, buffer)
1941            })
1942            .await
1943            {
1944                Ok(read) => Ok(read),
1945                Err(IoErrorKind::Unsupported) => {
1946                    let mut context = Context::new_empty();
1947                    poll(|| {
1948                        target_file_system.lookup_file_entry(
1949                            parent.context(),
1950                            entry_name,
1951                            &mut context,
1952                            Flags::from(AccessFlags::Read),
1953                        )
1954                    })
1955                    .await?;
1956                    let read = target_file_system.read_sync(&mut context, &mut buffer[..size], 0);
1957                    let close = BaseOperations::close(target_file_system, &mut context);
1958                    let read = read?;
1959                    close?;
1960                    if read != size {
1961                        return Err(IoErrorKind::CorruptData);
1962                    }
1963                    Ok(read)
1964                }
1965                Err(error) => Err(error),
1966            }
1967        } else {
1968            let relative_link = resolved_link.relative_path(&file_systems)?;
1969            match poll(|| target_file_system.read_symlink(relative_link, buffer)).await {
1970                Ok(read) => Ok(read),
1971                Err(IoErrorKind::Unsupported) => {
1972                    let mut context = Context::new_empty();
1973                    poll(|| {
1974                        target_file_system.lookup_file(
1975                            &mut context,
1976                            relative_link,
1977                            Flags::from(AccessFlags::Read),
1978                        )
1979                    })
1980                    .await?;
1981                    let read = target_file_system.read_sync(&mut context, &mut buffer[..size], 0);
1982                    let close = BaseOperations::close(target_file_system, &mut context);
1983                    let read = read?;
1984                    close?;
1985                    if read != size {
1986                        return Err(IoErrorKind::CorruptData);
1987                    }
1988                    Ok(read)
1989                }
1990                Err(error) => Err(error),
1991            }
1992        }
1993    }
1994
1995    pub async fn rename(
1996        &self,
1997        task: TaskIdentifier,
1998        old_path: &impl AsRef<Path>,
1999        new_path: &impl AsRef<Path>,
2000    ) -> Result<()> {
2001        self.rename_with_root(task, old_path.as_ref(), new_path.as_ref(), None, None)
2002            .await
2003    }
2004
2005    /// Resolve relative paths beneath the supplied root directory.
2006    pub async fn rename_beneath(
2007        &self,
2008        task: TaskIdentifier,
2009        old_path: &impl AsRef<Path>,
2010        new_path: &impl AsRef<Path>,
2011        old_root: &Path,
2012        new_root: &Path,
2013    ) -> Result<()> {
2014        self.rename_with_root(
2015            task,
2016            old_path.as_ref(),
2017            new_path.as_ref(),
2018            Some(old_root),
2019            Some(new_root),
2020        )
2021        .await
2022    }
2023
2024    async fn rename_with_root(
2025        &self,
2026        task: TaskIdentifier,
2027        old_path: &Path,
2028        new_path: &Path,
2029        old_root: Option<&Path>,
2030        new_root: Option<&Path>,
2031    ) -> Result<()> {
2032        let file_systems = self.file_systems.write().await; // Serialize source/destination resolution with rename.
2033        let user = self.task_manager.get_user(task).await.map_io_error()?;
2034        let mut old_resolved = self
2035            .resolve_path_with_root(&file_systems, old_path, false, false, user, task, old_root)
2036            .await?;
2037        let mut new_resolved = self
2038            .resolve_path_with_root(&file_systems, new_path, false, true, user, task, new_root)
2039            .await?;
2040        if old_root.is_some_and(|root| old_resolved.path.as_str() == root.as_str())
2041            || new_root.is_some_and(|root| new_resolved.path.as_str() == root.as_str())
2042            || Self::protects_mount(&file_systems, &old_resolved.path, true)
2043            || Self::protects_mount(&file_systems, &new_resolved.path, true)
2044        {
2045            return Err(IoErrorKind::ResourceBusy);
2046        }
2047        // A directory cannot move beneath itself. The backends do not check:
2048        // LittleFS would detach the whole subtree from the hierarchy.
2049        let source = old_resolved.path.as_str().trim_end_matches('/');
2050        if new_resolved.path.as_str().len() > source.len()
2051            && new_resolved.path.as_str().starts_with(source)
2052            && new_resolved.path.as_str().as_bytes()[source.len()] == b'/'
2053        {
2054            return Err(IoErrorKind::InvalidArgument);
2055        }
2056
2057        if old_resolved.mount_index != new_resolved.mount_index {
2058            return Err(IoErrorKind::CrossDevice);
2059        }
2060
2061        self.check_target_parent_permissions(
2062            &file_systems,
2063            &mut old_resolved,
2064            Permission::Write | Permission::Execute,
2065            user,
2066            task,
2067        )
2068        .await?;
2069        self.check_target_parent_permissions(
2070            &file_systems,
2071            &mut new_resolved,
2072            Permission::Write | Permission::Execute,
2073            user,
2074            task,
2075        )
2076        .await?;
2077
2078        self.check_target_sticky_permissions(&file_systems, &mut old_resolved, user)
2079            .await?;
2080
2081        match self
2082            .check_target_sticky_permissions(&file_systems, &mut new_resolved, user)
2083            .await
2084        {
2085            Ok(()) | Err(IoErrorKind::NotFound) => {}
2086            Err(error) => return Err(error),
2087        }
2088
2089        let target_file_system = file_systems[old_resolved.mount_index].file_system;
2090        if let (Some(old_parent), Some(new_parent)) = (
2091            old_resolved.parent_directory.as_ref(),
2092            new_resolved.parent_directory.as_ref(),
2093        ) {
2094            let old_name = old_resolved.entry_name(&file_systems)?;
2095            let new_name = new_resolved.entry_name(&file_systems)?;
2096            poll(|| {
2097                target_file_system.rename_entry(
2098                    old_parent.context(),
2099                    old_name,
2100                    new_parent.context(),
2101                    new_name,
2102                )
2103            })
2104            .await?;
2105        } else {
2106            let old_relative = old_resolved.relative_path(&file_systems)?;
2107            let new_relative = new_resolved.relative_path(&file_systems)?;
2108            poll(|| target_file_system.rename(old_relative, new_relative)).await?;
2109        }
2110
2111        Ok(())
2112    }
2113
2114    /// Create `new_path` as a hard link to the non-directory object at `existing`.
2115    pub async fn link(
2116        &self,
2117        task: TaskIdentifier,
2118        existing: &impl AsRef<Path>,
2119        follow_existing: bool,
2120        new_path: &impl AsRef<Path>,
2121    ) -> Result<()> {
2122        self.link_with_root(
2123            task,
2124            existing.as_ref(),
2125            follow_existing,
2126            new_path.as_ref(),
2127            None,
2128            None,
2129        )
2130        .await
2131    }
2132
2133    /// Resolve both paths beneath their supplied root directories.
2134    pub async fn link_beneath(
2135        &self,
2136        task: TaskIdentifier,
2137        existing: &impl AsRef<Path>,
2138        follow_existing: bool,
2139        new_path: &impl AsRef<Path>,
2140        existing_root: &Path,
2141        new_root: &Path,
2142    ) -> Result<()> {
2143        self.link_with_root(
2144            task,
2145            existing.as_ref(),
2146            follow_existing,
2147            new_path.as_ref(),
2148            Some(existing_root),
2149            Some(new_root),
2150        )
2151        .await
2152    }
2153
2154    async fn link_with_root(
2155        &self,
2156        task: TaskIdentifier,
2157        existing: &Path,
2158        follow_existing: bool,
2159        new_path: &Path,
2160        existing_root: Option<&Path>,
2161        new_root: Option<&Path>,
2162    ) -> Result<()> {
2163        let file_systems = self.file_systems.write().await; // Serialize source/destination resolution with the link.
2164        let user = self.task_manager.get_user(task).await.map_io_error()?;
2165        let mut existing_resolved = self
2166            .resolve_path_with_root(
2167                &file_systems,
2168                existing,
2169                follow_existing,
2170                false,
2171                user,
2172                task,
2173                existing_root,
2174            )
2175            .await?;
2176        let mut new_resolved = self
2177            .resolve_path_with_root(&file_systems, new_path, false, true, user, task, new_root)
2178            .await?;
2179        if Self::protects_mount(&file_systems, &new_resolved.path, true) {
2180            return Err(IoErrorKind::ResourceBusy);
2181        }
2182
2183        if existing_resolved.mount_index != new_resolved.mount_index {
2184            return Err(IoErrorKind::CrossDevice);
2185        }
2186
2187        let mut kind = Attributes::new().set_mask(AttributeFlags::Kind);
2188        Self::target_attributes(&file_systems, &mut existing_resolved, &mut kind).await?;
2189        if kind.get_kind() == Some(&Kind::Directory) {
2190            return Err(IoErrorKind::IsADirectory);
2191        }
2192        let mut destination = Attributes::new().set_mask(AttributeFlags::Kind);
2193        match Self::target_attributes(&file_systems, &mut new_resolved, &mut destination).await {
2194            Ok(()) => return Err(IoErrorKind::AlreadyExists),
2195            Err(IoErrorKind::NotFound) => {}
2196            Err(error) => return Err(error),
2197        }
2198        self.check_target_parent_permissions(
2199            &file_systems,
2200            &mut new_resolved,
2201            Permission::Write | Permission::Execute,
2202            user,
2203            task,
2204        )
2205        .await?;
2206
2207        let target_file_system = file_systems[new_resolved.mount_index].file_system;
2208        if let (Some(existing_parent), Some(new_parent)) = (
2209            existing_resolved.parent_directory.as_ref(),
2210            new_resolved.parent_directory.as_ref(),
2211        ) {
2212            let existing_name = existing_resolved.entry_name(&file_systems)?;
2213            let new_name = new_resolved.entry_name(&file_systems)?;
2214            poll(|| {
2215                target_file_system.link_entry(
2216                    existing_parent.context(),
2217                    existing_name,
2218                    new_parent.context(),
2219                    new_name,
2220                )
2221            })
2222            .await
2223        } else {
2224            let existing_relative = existing_resolved.relative_path(&file_systems)?;
2225            let new_relative = new_resolved.relative_path(&file_systems)?;
2226            poll(|| target_file_system.link(existing_relative, new_relative)).await
2227        }
2228    }
2229
2230    pub async fn get_statistics(&self, path: &impl AsRef<Path>) -> Result<Statistics> {
2231        let task = self
2232            .task_manager
2233            .try_get_current_task_identifier()
2234            .await
2235            .map_io_error()?;
2236        self.get_statistics_for_task(task, path).await
2237    }
2238
2239    /// Read path metadata for an explicit task, including from synchronous adapters
2240    /// whose polling context does not carry an Embassy task waker.
2241    pub async fn get_statistics_for_task(
2242        &self,
2243        task: TaskIdentifier,
2244        path: &impl AsRef<Path>,
2245    ) -> Result<Statistics> {
2246        self.get_statistics_for_task_with_follow_with_root(task, path.as_ref(), true, None)
2247            .await
2248    }
2249
2250    /// Read metadata for the directory entry itself without following its final link.
2251    pub async fn get_link_statistics_for_task(
2252        &self,
2253        task: TaskIdentifier,
2254        path: &impl AsRef<Path>,
2255    ) -> Result<Statistics> {
2256        self.get_statistics_for_task_with_follow_with_root(task, path.as_ref(), false, None)
2257            .await
2258    }
2259
2260    /// Return metadata for the directory entry itself without following a final symbolic link.
2261    pub async fn get_link_statistics(&self, path: &impl AsRef<Path>) -> Result<Statistics> {
2262        let task = self
2263            .task_manager
2264            .try_get_current_task_identifier()
2265            .await
2266            .map_io_error()?;
2267        self.get_link_statistics_for_task(task, path).await
2268    }
2269
2270    /// Resolve relative paths beneath the supplied root directory.
2271    pub async fn get_statistics_beneath(
2272        &self,
2273        task: TaskIdentifier,
2274        path: &impl AsRef<Path>,
2275        follow_final: bool,
2276        root: &Path,
2277    ) -> Result<Statistics> {
2278        self.get_statistics_for_task_with_follow_with_root(
2279            task,
2280            path.as_ref(),
2281            follow_final,
2282            Some(root),
2283        )
2284        .await
2285    }
2286
2287    async fn get_statistics_for_task_with_follow_with_root(
2288        &self,
2289        task: TaskIdentifier,
2290        path: &Path,
2291        follow_final: bool,
2292        root: Option<&Path>,
2293    ) -> Result<Statistics> {
2294        let file_systems = self.file_systems.read().await;
2295        let user = self.task_manager.get_user(task).await.map_io_error()?;
2296        let mut resolved = self
2297            .resolve_path_with_root(&file_systems, path, follow_final, false, user, task, root)
2298            .await?;
2299
2300        let mut attributes = Attributes::new().set_mask(AttributeFlags::all());
2301        Self::target_attributes(&file_systems, &mut resolved, &mut attributes).await?;
2302        Statistics::from_attributes(&attributes).ok_or(IoErrorKind::InputOutput)
2303    }
2304
2305    /// Take one more reference on the entry `item` was opened on.
2306    ///
2307    /// `device_inode` is the inode a device opening took its reference on; it
2308    /// is required for devices, because two mounted devices may share a pointer.
2309    pub(crate) async fn retain(
2310        &self,
2311        item: &ItemStatic,
2312        device_inode: Option<Inode>,
2313    ) -> Result<()> {
2314        match item {
2315            ItemStatic::File(file_system) | ItemStatic::Directory(file_system) => {
2316                self.file_systems
2317                    .write()
2318                    .await
2319                    .iter_mut()
2320                    .find_map(|fs| {
2321                        if ptr::eq(fs.file_system, *file_system) {
2322                            fs.reference_count += 1;
2323                            Some(())
2324                        } else {
2325                            None
2326                        }
2327                    })
2328                    .ok_or(IoErrorKind::BadDescriptor)?;
2329            }
2330            ItemStatic::Pipe(_) => {}
2331            ItemStatic::BlockDevice(_) => {
2332                let inode = device_inode.ok_or(IoErrorKind::BadDescriptor)?;
2333                self.block_device
2334                    .write()
2335                    .await
2336                    .get_mut(&inode)
2337                    .ok_or(IoErrorKind::BadDescriptor)?
2338                    .reference_count += 1;
2339            }
2340            ItemStatic::CharacterDevice(_) => {
2341                let inode = device_inode.ok_or(IoErrorKind::BadDescriptor)?;
2342                self.character_device
2343                    .write()
2344                    .await
2345                    .get_mut(&inode)
2346                    .ok_or(IoErrorKind::BadDescriptor)?
2347                    .reference_count += 1;
2348            }
2349            _ => {
2350                return Err(IoErrorKind::BadDescriptor);
2351            }
2352        }
2353
2354        Ok(())
2355    }
2356
2357    /// Release the reference `item` took when it was opened, then close it.
2358    ///
2359    /// `device_inode` is the inode a device opening took its reference on; it
2360    /// is required for devices, because two mounted devices may share a pointer.
2361    pub async fn close(
2362        &self,
2363        item: &ItemStatic,
2364        device_inode: Option<Inode>,
2365        context: &mut Context,
2366    ) -> Result<()> {
2367        let released = match Owed::of(item, device_inode)? {
2368            None => true,
2369            Some(Owed::FileSystem(address)) => {
2370                let mut file_systems = self.file_systems.write().await;
2371                self.settle_file_systems(&mut file_systems);
2372                release_file_system(&mut file_systems, address)
2373            }
2374            Some(Owed::BlockDevice(inode)) => {
2375                let mut devices = self.block_device.write().await;
2376                self.settle_block_devices(&mut devices);
2377                release_block_device(&mut devices, inode)
2378            }
2379            Some(Owed::CharacterDevice(inode)) => {
2380                let mut devices = self.character_device.write().await;
2381                self.settle_character_devices(&mut devices);
2382                release_character_device(&mut devices, inode)
2383            }
2384        };
2385        if !released {
2386            return Err(IoErrorKind::BadDescriptor);
2387        }
2388        Self::close_context(item, context)
2389    }
2390
2391    /// Close like [`Self::close`], but without ever waiting, for a destructor: closing in a
2392    /// drop must not suspend, or a cancellation could abandon it halfway. The item's own
2393    /// context is closed at once. Its reference is given back at once if the lock it is
2394    /// counted under is free, and otherwise owed: whoever takes that lock next to look at
2395    /// the counts (a close, an unmount, the storage shutdown) gives it back first.
2396    pub fn close_without_waiting(
2397        &self,
2398        item: &ItemStatic,
2399        device_inode: Option<Inode>,
2400        context: &mut Context,
2401    ) -> Result<()> {
2402        if let Some(entry) = Owed::of(item, device_inode)? {
2403            let released = match entry {
2404                Owed::FileSystem(address) => self.file_systems.try_write().map(|mut locked| {
2405                    self.settle_file_systems(&mut locked);
2406                    release_file_system(&mut locked, address)
2407                }),
2408                Owed::BlockDevice(inode) => self.block_device.try_write().map(|mut locked| {
2409                    self.settle_block_devices(&mut locked);
2410                    release_block_device(&mut locked, inode)
2411                }),
2412                Owed::CharacterDevice(inode) => {
2413                    self.character_device.try_write().map(|mut locked| {
2414                        self.settle_character_devices(&mut locked);
2415                        release_character_device(&mut locked, inode)
2416                    })
2417                }
2418            };
2419            match released {
2420                Ok(true) => {}
2421                Ok(false) => return Err(IoErrorKind::BadDescriptor),
2422                Err(_) => {
2423                    let queued = self.owed.lock(|owed| {
2424                        let mut owed = owed.borrow_mut();
2425                        let reserved = owed.try_reserve(1).is_ok();
2426                        if reserved {
2427                            owed.push(entry);
2428                        }
2429                        reserved
2430                    });
2431                    if !queued {
2432                        log::warning!("Out of memory: a closed item stays counted as open");
2433                    }
2434                }
2435            }
2436        }
2437        Self::close_context(item, context)
2438    }
2439
2440    /// Close the item's own context: the part of a close that never waits.
2441    fn close_context(item: &ItemStatic, context: &mut Context) -> Result<()> {
2442        if let Some(operations) = item.as_directory_operations() {
2443            operations.close(context)
2444        } else {
2445            item.as_base_operations()
2446                .ok_or(IoErrorKind::Unsupported)?
2447                .close(context)
2448        }
2449    }
2450
2451    /// Record a mutation timestamp (modification and status change time) on an
2452    /// open file handle.
2453    ///
2454    /// The backend stores the times in the handle's pending metadata, so they
2455    /// are committed atomically with the file data on the next sync or close
2456    /// of the handle instead of costing a separate metadata commit. A backend
2457    /// that cannot persist times reports `Unsupported`, which is not an error
2458    /// here.
2459    pub(crate) fn set_handle_times(
2460        file_system: &dyn FileSystemOperations,
2461        context: &mut Context,
2462        time: file_system::Time,
2463    ) -> Result<()> {
2464        let attributes = Attributes::new().set_modification(time).set_status(time);
2465        let mask = attributes
2466            .get_mask()
2467            .intersection(file_system.writable_attributes());
2468        if mask.is_empty() {
2469            return Ok(());
2470        }
2471        match AttributeOperations::set_attributes(file_system, context, &attributes.set_mask(mask))
2472        {
2473            Err(IoErrorKind::Unsupported) => Ok(()),
2474            result => result.map(|_| ()),
2475        }
2476    }
2477
2478    /// Current UTC time when the clock is synchronized.
2479    pub(crate) fn current_time(&self) -> Result<file_system::Time> {
2480        self.get_time()
2481    }
2482
2483    /// Record a mutation timestamp on an open handle of a regular file, using
2484    /// the current UTC time. When UTC is unavailable the previous timestamps
2485    /// are kept, as on open.
2486    pub(crate) fn touch_handle_modification_time(
2487        &self,
2488        item: &ItemStatic,
2489        context: &mut Context,
2490    ) -> Result<()> {
2491        let ItemStatic::File(file_system) = item else {
2492            return Ok(());
2493        };
2494        let Ok(time) = self.get_time() else {
2495            return Ok(());
2496        };
2497        Self::set_handle_times(*file_system, context, time)
2498    }
2499
2500    /// Single-attempt metadata adapter: never block an executor waiting for a
2501    /// namespace guard held by another task. Path mutations use the same guard.
2502    pub(crate) fn set_handle_attributes(
2503        &self,
2504        authority: &task::TaskAuthority<'_>,
2505        item: &ItemStatic,
2506        context: &mut Context,
2507        attributes: &Attributes,
2508    ) -> Result<()> {
2509        if attributes.get_mask().is_empty() {
2510            return Ok(());
2511        }
2512        let _namespace = self
2513            .file_systems
2514            .try_write()
2515            .map_err(|_| IoErrorKind::WouldBlock)?;
2516        let user = authority
2517            .try_user()
2518            .map_io_error()?
2519            .ok_or(IoErrorKind::WouldBlock)?;
2520        let operations = item
2521            .as_attributes_operations()
2522            .ok_or(IoErrorKind::Unsupported)?;
2523        let mut current = Attributes::new().set_mask(attributes.get_mask() | AttributeFlags::User);
2524        operations.get_attributes(context, &mut current)?;
2525        Self::authorize_metadata_change(
2526            user,
2527            *current.get_user().ok_or(IoErrorKind::InputOutput)?,
2528            attributes,
2529        )?;
2530        if attributes
2531            .get_mask()
2532            .intersects(AttributeFlags::User | AttributeFlags::Group)
2533        {
2534            return Err(IoErrorKind::Unsupported);
2535        }
2536        let current_mask = current.get_mask().intersection(attributes.get_mask());
2537        let current_for_mask = current.set_mask(current_mask);
2538        if attributes_equal(&current_for_mask, attributes) {
2539            return Ok(());
2540        }
2541        operations.set_attributes(context, attributes)?;
2542        Ok(())
2543    }
2544
2545    /// Update timestamps after resolving beneath an immutable preopen authority.
2546    pub async fn set_times_beneath(
2547        &self,
2548        task: TaskIdentifier,
2549        path: &impl AsRef<Path>,
2550        follow_final: bool,
2551        root: &Path,
2552        access: Option<file_system::Time>,
2553        modification: Option<file_system::Time>,
2554    ) -> Result<()> {
2555        self.set_times_beneath_inner(
2556            task,
2557            path.as_ref(),
2558            follow_final,
2559            root,
2560            access,
2561            modification,
2562        )
2563        .await
2564    }
2565
2566    async fn set_times_beneath_inner(
2567        &self,
2568        task: TaskIdentifier,
2569        path: &Path,
2570        follow_final: bool,
2571        root: &Path,
2572        access: Option<file_system::Time>,
2573        modification: Option<file_system::Time>,
2574    ) -> Result<()> {
2575        let file_systems = self.file_systems.write().await;
2576        let user = self.task_manager.get_user(task).await.map_io_error()?;
2577        let mut resolved = self
2578            .resolve_path_with_root(
2579                &file_systems,
2580                path,
2581                follow_final,
2582                false,
2583                user,
2584                task,
2585                Some(root),
2586            )
2587            .await?;
2588        let mut attributes = Attributes::new();
2589        if let Some(time) = access {
2590            attributes = attributes.set_access(time);
2591        }
2592        if let Some(time) = modification {
2593            attributes = attributes.set_modification(time);
2594        }
2595        let mut owner = Attributes::new().set_mask(AttributeFlags::User);
2596        Self::target_attributes(&file_systems, &mut resolved, &mut owner).await?;
2597        Self::authorize_metadata_change(
2598            user,
2599            *owner.get_user().ok_or(IoErrorKind::InputOutput)?,
2600            &attributes,
2601        )?;
2602        Self::set_target_attributes(&file_systems, &mut resolved, &attributes).await
2603    }
2604
2605    pub async fn set_ownership(
2606        &self,
2607        task: TaskIdentifier,
2608        path: impl AsRef<Path>,
2609        user: Option<UserIdentifier>,
2610        group: Option<GroupIdentifier>,
2611    ) -> Result<()> {
2612        self.set_ownership_inner(task, path.as_ref(), user, group)
2613            .await
2614    }
2615
2616    async fn set_ownership_inner(
2617        &self,
2618        task: TaskIdentifier,
2619        path: &Path,
2620        user: Option<UserIdentifier>,
2621        group: Option<GroupIdentifier>,
2622    ) -> Result<()> {
2623        let file_systems = self.file_systems.write().await; // Serialize metadata authority with mutation.
2624        let current_user = self.task_manager.get_user(task).await.map_io_error()?;
2625        let mut resolved = self
2626            .resolve_path(&file_systems, path, true, false, current_user, task)
2627            .await?;
2628
2629        let mut attributes = Attributes::new();
2630        if let Some(user) = user {
2631            attributes = attributes.set_user(user);
2632        }
2633        if let Some(group) = group {
2634            attributes = attributes.set_group(group);
2635        }
2636        let mut owner = Attributes::new().set_mask(AttributeFlags::User);
2637        Self::target_attributes(&file_systems, &mut resolved, &mut owner).await?;
2638        Self::authorize_metadata_change(
2639            current_user,
2640            *owner.get_user().ok_or(IoErrorKind::InputOutput)?,
2641            &attributes,
2642        )?;
2643        Self::set_target_attributes(&file_systems, &mut resolved, &attributes).await
2644    }
2645
2646    pub async fn set_permissions(
2647        &self,
2648        task: TaskIdentifier,
2649        path: impl AsRef<Path>,
2650        permissions: Permissions,
2651    ) -> Result<()> {
2652        self.set_permissions_inner(task, path.as_ref(), permissions)
2653            .await
2654    }
2655
2656    async fn set_permissions_inner(
2657        &self,
2658        task: TaskIdentifier,
2659        path: &Path,
2660        permissions: Permissions,
2661    ) -> Result<()> {
2662        let file_systems = self.file_systems.write().await; // Get the file systems
2663        let current_user = self.task_manager.get_user(task).await.map_io_error()?;
2664        let mut resolved = self
2665            .resolve_path(&file_systems, path, true, false, current_user, task)
2666            .await?;
2667
2668        let attributes = Attributes::new().set_permissions(permissions);
2669        let mut owner = Attributes::new().set_mask(AttributeFlags::User);
2670        Self::target_attributes(&file_systems, &mut resolved, &mut owner).await?;
2671        Self::authorize_metadata_change(
2672            current_user,
2673            *owner.get_user().ok_or(IoErrorKind::InputOutput)?,
2674            &attributes,
2675        )?;
2676        Self::set_target_attributes(&file_systems, &mut resolved, &attributes).await
2677    }
2678}