Skip to main content

starnix_core/fs/fuchsia/
remote.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::fs::fuchsia::RemoteUnixDomainSocket;
6use crate::fs::fuchsia::remote_volume::RemoteVolume;
7use crate::fs::fuchsia::sync_file::{SyncFence, SyncFile, SyncPoint, Timeline};
8use crate::fs::fuchsia::zxio::{zxio_query_events, zxio_wait_async};
9use crate::mm::memory::MemoryObject;
10use crate::mm::{ProtectionFlags, VMEX_RESOURCE};
11use crate::security;
12use crate::task::{CurrentTask, EventHandler, Kernel, WaitCanceler, Waiter};
13use crate::vfs::buffers::{InputBuffer, OutputBuffer, with_iovec_segments};
14use crate::vfs::file_server::serve_file_tagged;
15use crate::vfs::fs_args::MountParams;
16use crate::vfs::fsverity::FsVerityState;
17use crate::vfs::pipe::new_pipe_file;
18use crate::vfs::socket::{Socket, SocketFile, SocketHandle, ZxioBackedSocket};
19use crate::vfs::{
20    Anon, AppendLockWriteGuard, CacheMode, DEFAULT_BYTES_PER_BLOCK, DirEntry, DirectoryEntryType,
21    DirentSink, FallocMode, FileHandle, FileObject, FileOps, FileSystem, FileSystemHandle,
22    FileSystemOps, FileSystemOptions, FsNode, FsNodeFlags, FsNodeHandle, FsNodeInfo, FsNodeOps,
23    FsStr, FsString, LookupVec, MemoryRegularFile, NamespaceNode, RenameContext, SeekTarget,
24    StatxFlags, SymlinkTarget, XattrOp, XattrStorage, default_seek, fileops_impl_directory,
25    fileops_impl_nonseekable, fileops_impl_noop_sync, fileops_impl_seekable, fs_node_impl_not_dir,
26    fs_node_impl_symlink, fs_node_impl_xattr_delegate,
27};
28use bstr::ByteSlice;
29use fidl::endpoints::DiscoverableProtocolMarker as _;
30use fidl_fuchsia_io as fio;
31use fidl_fuchsia_starnix_binder as fbinder;
32use fidl_fuchsia_unknown as funknown;
33use fuchsia_runtime::UtcInstant;
34use linux_uapi::SYNC_IOC_MAGIC;
35use once_cell::sync::OnceCell;
36use smallvec::{SmallVec, smallvec};
37use starnix_crypt::EncryptionKeyId;
38use starnix_logging::{CATEGORY_STARNIX_MM, impossible_error, log_warn, track_stub};
39use starnix_sync::{
40    DynamicLockDepRwLock, FuchsiaRemoteTargetLock, LockDepReadGuard, LockDepRwLock,
41    LockDepWriteGuard,
42};
43use starnix_syscalls::{SyscallArg, SyscallResult};
44use starnix_types::vfs::default_statfs;
45use starnix_uapi::auth::{Credentials, FsCred};
46use starnix_uapi::device_id::DeviceId;
47use starnix_uapi::errors::Errno;
48use starnix_uapi::file_mode::FileMode;
49use starnix_uapi::mount_flags::FileSystemFlags;
50use starnix_uapi::open_flags::OpenFlags;
51use starnix_uapi::vfs::FdEvents;
52use starnix_uapi::{
53    __kernel_fsid_t, XATTR_NAME_SELINUX, errno, error, from_status_like_fdio, fsverity_descriptor,
54    mode, off_t, statfs,
55};
56use std::ops::ControlFlow;
57use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
58use std::sync::{Arc, LazyLock};
59use sync_io_client::{RemoteDirectory, RemoteIo, SyncIo, SyncIoDirectory};
60use syncio::zxio::{
61    ZXIO_OBJECT_TYPE_DATAGRAM_SOCKET, ZXIO_OBJECT_TYPE_NONE, ZXIO_OBJECT_TYPE_PACKET_SOCKET,
62    ZXIO_OBJECT_TYPE_RAW_SOCKET, ZXIO_OBJECT_TYPE_STREAM_SOCKET,
63    ZXIO_OBJECT_TYPE_SYNCHRONOUS_DATAGRAM_SOCKET,
64};
65use syncio::{
66    AllocateMode, XattrSetMode, Zxio, zxio_fsverity_descriptor_t, zxio_node_attr_has_t,
67    zxio_node_attributes_t,
68};
69use zx::Counter;
70
71fn is_special(file_info: &fio::FileInfo) -> bool {
72    matches!(
73        file_info,
74        fio::FileInfo {
75            attributes:
76                Some(fio::NodeAttributes2 {
77                    mutable_attributes: fio::MutableNodeAttributes { mode: Some(mode), .. },
78                    ..
79                }),
80            ..
81        } if {
82            let mode = FileMode::from_bits(*mode);
83            mode.is_chr() || mode.is_blk() || mode.is_fifo() || mode.is_sock()
84        }
85    )
86}
87
88pub fn new_remote_fs(
89    current_task: &CurrentTask,
90    options: FileSystemOptions,
91) -> Result<FileSystemHandle, Errno> {
92    let kernel = current_task.kernel();
93    let requested_path = std::str::from_utf8(&options.source)
94        .map_err(|_| errno!(EINVAL, "source path is not utf8"))?;
95    let mut create_flags =
96        fio::PERM_READABLE | fio::Flags::FLAG_MAYBE_CREATE | fio::Flags::PROTOCOL_DIRECTORY;
97    if !options.flags.load(Ordering::Relaxed).contains(FileSystemFlags::RDONLY) {
98        create_flags |= fio::PERM_WRITABLE;
99    }
100    let (root_proxy, subdir) = kernel.open_ns_dir(requested_path, create_flags)?;
101
102    let subdir = if subdir.is_empty() { ".".to_string() } else { subdir };
103    let mut open_rights = fio::PERM_READABLE;
104    if !options.flags.load(Ordering::Relaxed).contains(FileSystemFlags::RDONLY) {
105        open_rights |= fio::PERM_WRITABLE;
106    }
107    let mut subdir_options = options;
108    subdir_options.source = subdir.into();
109    new_remotefs_in_root(kernel, &root_proxy, subdir_options, open_rights)
110}
111
112/// Create a filesystem to access the content of the fuchsia directory available
113/// at `options.source` inside `root`.
114pub fn new_remotefs_in_root(
115    kernel: &Kernel,
116    root: &fio::DirectorySynchronousProxy,
117    options: FileSystemOptions,
118    rights: fio::Flags,
119) -> Result<FileSystemHandle, Errno> {
120    let root = syncio::directory_open_directory_async(
121        root,
122        std::str::from_utf8(&options.source)
123            .map_err(|_| errno!(EINVAL, "source path is not utf8"))?,
124        rights,
125    )
126    .map_err(|e| errno!(EIO, format!("Failed to open root: {e}")))?;
127    RemoteFs::new_fs(kernel, root.into_channel(), options, rights)
128}
129
130pub struct RemoteFs<I> {
131    // If true, trust the remote file system's IDs (which requires that the remote file system does
132    // not span mounts).  This must be true to properly support hard links.  If this is false, the
133    // same node can end up having different IDs as it leaves and reenters the node cache.
134    // TODO(https://fxbug.dev/42081972): At the time of writing, package directories do not have
135    // unique IDs so this *must* be false in that case.
136    use_remote_ids: bool,
137
138    root_io: I,
139
140    // The rights used for the root node.
141    root_rights: fio::Flags,
142
143    /// Casefold support is only assumed if QueryFilesystem exists and fs_type is Fxfs.
144    casefold: bool,
145
146    name: &'static str,
147}
148
149impl<I: 'static> RemoteFs<I> {
150    /// Returns a reference to a RemoteFs given a reference to a FileSystem.
151    ///
152    /// # Panics
153    ///
154    /// This will panic if `fs`'s ops aren't `RemoteFs`, so this should only be called when this is
155    /// known to be the case.
156    fn from_fs(fs: &FileSystem) -> &RemoteFs<I> {
157        if let Some(remote_vol) = fs.downcast_ops::<RemoteVolume<I>>() {
158            remote_vol.remotefs()
159        } else {
160            fs.downcast_ops::<RemoteFs<I>>().unwrap()
161        }
162    }
163}
164
165const REMOTE_FS_MAGIC: u32 = u32::from_be_bytes(*b"f.io");
166const DYNAMIC_FS_BYTES_PER_INODE_FALLBACK: u64 = 16384; // 16 KiB
167const SYNC_IOC_FILE_INFO: u8 = 4;
168const SYNC_IOC_MERGE: u8 = 3;
169
170impl<I: SyncIo> FileSystemOps for RemoteFs<I> {
171    fn statfs(&self, _fs: &FileSystem, _current_task: &CurrentTask) -> Result<statfs, Errno> {
172        if let Ok(info) = self.root_io.query_filesystem() {
173            let (total_blocks, free_blocks) = if info.block_size > 0 {
174                (
175                    (info.total_bytes / u64::from(info.block_size)).try_into().unwrap_or(i64::MAX),
176                    ((info.total_bytes.saturating_sub(info.used_bytes))
177                        / u64::from(info.block_size))
178                    .try_into()
179                    .unwrap_or(i64::MAX),
180                )
181            } else {
182                (0, 0)
183            };
184
185            let total_nodes = std::cmp::min(
186                info.total_nodes,
187                info.total_bytes / DYNAMIC_FS_BYTES_PER_INODE_FALLBACK,
188            );
189            let free_nodes = total_nodes.saturating_sub(info.used_nodes);
190
191            let fsid = __kernel_fsid_t {
192                val: [(info.fs_id & 0xffffffff) as i32, ((info.fs_id >> 32) & 0xffffffff) as i32],
193            };
194
195            return Ok(statfs {
196                f_type: info.fs_type as i64,
197                f_bsize: info.block_size.into(),
198                f_blocks: total_blocks,
199                f_bfree: free_blocks,
200                f_bavail: free_blocks,
201                f_files: total_nodes.try_into().unwrap_or(i64::MAX),
202                f_ffree: free_nodes.try_into().unwrap_or(i64::MAX),
203                f_fsid: fsid,
204                f_namelen: info.max_filename_size.try_into().unwrap_or(0),
205                f_frsize: info.block_size.into(),
206                ..statfs::default()
207            });
208        }
209        Ok(default_statfs(REMOTE_FS_MAGIC))
210    }
211
212    fn name(&self) -> &'static FsStr {
213        self.name.into()
214    }
215
216    fn uses_external_node_ids(&self) -> bool {
217        self.use_remote_ids
218    }
219
220    fn has_casefold_support(&self) -> bool {
221        self.casefold
222    }
223
224    fn rename(
225        &self,
226        _fs: &FileSystem,
227        current_task: &CurrentTask,
228        context: &mut RenameContext<'_>,
229        old_name: &FsStr,
230        new_name: &FsStr,
231    ) -> Result<(), Errno> {
232        let renamed = &context.renamed.node;
233        let replaced = context.replaced.map(|r| &r.node);
234        let old_parent = &context.old_parent().node;
235        let new_parent = &context.new_parent().node;
236        let old_parent_info = context.old_parent_info();
237        let new_parent_info = context.new_parent_info();
238        // Renames should fail if the src or target directory is
239        // encrypted and locked.
240        old_parent.fail_if_locked(current_task, old_parent_info)?;
241        if let Some(info) = new_parent_info {
242            new_parent.fail_if_locked(current_task, info)?;
243        }
244
245        let Some((old_parent_ops, new_parent_ops)) = old_parent
246            .downcast_ops::<RemoteNode<I>>()
247            .zip(new_parent.downcast_ops::<RemoteNode<I>>())
248        else {
249            return error!(EXDEV);
250        };
251
252        let mut nodes: SmallVec<[&FsNode; 4]> =
253            smallvec![&***old_parent, &***new_parent, &***renamed];
254        if let Some(r) = replaced {
255            nodes.push(r);
256        }
257
258        will_dirty::<I, _, _>(&nodes, || {
259            old_parent_ops
260                .node
261                .io
262                .rename(get_name_str(old_name)?, &new_parent_ops.node.io, get_name_str(new_name)?)
263                .map_err(|status| match status {
264                    zx::Status::BAD_STATE => errno!(EXDEV),
265                    zx::Status::ACCESS_DENIED => errno!(ENOKEY),
266                    s => map_sync_io_client_error(s),
267                })
268        })
269    }
270
271    fn sync(&self, _fs: &FileSystem, _current_task: &CurrentTask) -> Result<(), Errno> {
272        self.root_io.sync().map_err(map_sync_error)
273    }
274
275    fn manages_timestamps(&self) -> bool {
276        true
277    }
278
279    fn reconfigure(
280        &self,
281        fs: &FileSystem,
282        _current_task: &CurrentTask,
283        mut flags: FileSystemFlags,
284        params: &MountParams,
285    ) -> Result<(), Errno> {
286        if !params.is_empty() {
287            track_stub!(TODO("https://fxbug.dev/322875506"), "MS_REMOUNT: Updating data");
288        }
289        if !self.root_rights.contains(fio::PERM_WRITABLE) {
290            flags |= FileSystemFlags::RDONLY;
291        }
292        fs.options.flags.store(flags, Ordering::Relaxed);
293        Ok(())
294    }
295}
296
297/// Factory is a helper that creates the appropriate node type when creating a node.  See
298/// LookupFactory below for a helper that is specialised for the lookup case.  Nodes are created
299/// clean if attributes are returned in `OnRepresentation`, or dirty otherwise.
300struct Factory<'a> {
301    node_info: &'a mut FsNodeInfo,
302    assume_special: bool,
303}
304
305impl<'a> Factory<'a> {
306    fn new(node_info: &'a mut FsNodeInfo, assume_special: bool) -> Self {
307        Self { node_info, assume_special }
308    }
309}
310
311impl<'a, I: SyncIo> sync_io_client::Factory<I> for Factory<'a> {
312    type Result = (Box<dyn FsNodeOps>, u64);
313
314    fn create_node(self, io: I, info: fio::NodeInfo) -> Self::Result {
315        let dirty = info.attributes.is_none();
316        let attrs = get_attributes(&info.attributes);
317        let id = attrs.immutable_attributes.id.unwrap_or(fio::INO_UNKNOWN);
318        update_info_from_fidl(
319            self.node_info,
320            &attrs.mutable_attributes,
321            &attrs.immutable_attributes,
322        );
323        (Box::new(RemoteNode::new(io, dirty)), id)
324    }
325
326    fn create_directory(self, io: I, info: fio::DirectoryInfo) -> Self::Result {
327        let dirty = info.attributes.is_none();
328        let attrs = get_attributes(&info.attributes);
329        let id = attrs.immutable_attributes.id.unwrap_or(fio::INO_UNKNOWN);
330        if let Some(mode) = attrs.mutable_attributes.mode {
331            let mode = FileMode::from_bits(mode);
332            if mode.is_dir() {
333                self.node_info.mode = mode;
334            }
335        }
336        if let Some(uid) = attrs.mutable_attributes.uid {
337            self.node_info.uid = uid;
338        }
339        if let Some(gid) = attrs.mutable_attributes.gid {
340            self.node_info.gid = gid;
341        }
342        update_info_from_fidl(
343            self.node_info,
344            &attrs.mutable_attributes,
345            &attrs.immutable_attributes,
346        );
347        (Box::new(RemoteNode::new(io, dirty)), id)
348    }
349
350    fn create_file(self, io: I, info: fio::FileInfo) -> Self::Result {
351        let dirty = info.attributes.is_none();
352        let is_special_node = self.assume_special || is_special(&info);
353        let attrs = get_attributes(&info.attributes);
354        let id = attrs.immutable_attributes.id.unwrap_or(fio::INO_UNKNOWN);
355        let ops: Box<dyn FsNodeOps> = if is_special_node {
356            Box::new(RemoteSpecialNode { node: BaseNode::new(io, dirty) })
357        } else {
358            Box::new(RemoteNode::new(io, dirty))
359        };
360        update_info_from_fidl(
361            self.node_info,
362            &attrs.mutable_attributes,
363            &attrs.immutable_attributes,
364        );
365        (ops, id)
366    }
367
368    fn create_symlink(self, io: I, info: fio::SymlinkInfo) -> Self::Result {
369        let dirty = info.attributes.is_none();
370        let attrs = get_attributes(&info.attributes);
371        let id = attrs.immutable_attributes.id.unwrap_or(fio::INO_UNKNOWN);
372        let target = info.target.unwrap_or_default();
373        update_info_from_fidl(
374            self.node_info,
375            &attrs.mutable_attributes,
376            &attrs.immutable_attributes,
377        );
378        (Box::new(RemoteSymlink::new(BaseNode::new(io, dirty), target)), id)
379    }
380}
381
382/// LookupFactory is an optimised version of Factory which is used only for lookup.  All the
383/// functions will create nodes that are initially clean, which works because lookup always requests
384/// all attributes.
385struct LookupFactory<'a> {
386    fs: &'a FileSystemHandle,
387    current_task: &'a CurrentTask,
388}
389
390impl<'a> LookupFactory<'a> {
391    fn new(fs: &'a FileSystemHandle, current_task: &'a CurrentTask) -> Self {
392        Self { fs, current_task }
393    }
394
395    fn get_node<I: SyncIo>(
396        &self,
397        io: I,
398        attributes: &fio::NodeAttributes2,
399        create_ops: impl FnOnce(I) -> Box<dyn FsNodeOps>,
400    ) -> Result<FsNodeHandle, Errno> {
401        let fs = self.fs;
402        let fs_ops = RemoteFs::<I>::from_fs(fs);
403        let fio::NodeAttributes2 { mutable_attributes: mutable, immutable_attributes: immutable } =
404            attributes;
405
406        let id = immutable.id.unwrap_or(fio::INO_UNKNOWN);
407        let node_id = if fs_ops.use_remote_ids {
408            if id == fio::INO_UNKNOWN {
409                return error!(ENOTSUP);
410            }
411            id
412        } else {
413            fs.allocate_ino()
414        };
415
416        let node = fs.get_or_create_node(node_id, || {
417            let uid = mutable.uid.unwrap_or(0);
418            let gid = mutable.gid.unwrap_or(0);
419            let owner = FsCred { uid, gid };
420            let rdev = DeviceId::from_bits(mutable.rdev.unwrap_or(0));
421            let fsverity_enabled = immutable.verity_enabled.unwrap_or(false);
422            let protocols = immutable.protocols.unwrap_or(fio::NodeProtocolKinds::empty());
423            // fsverity should not be enabled for non-file nodes.
424            if fsverity_enabled && !protocols.contains(fio::NodeProtocolKinds::FILE) {
425                return error!(EINVAL);
426            }
427
428            let ops = create_ops(io);
429            let child = FsNode::new_uncached(
430                node_id,
431                ops,
432                fs,
433                FsNodeInfo {
434                    rdev,
435                    ..FsNodeInfo::new(
436                        get_mode_from_fidl(mutable, immutable, fs_ops.root_rights),
437                        owner,
438                    )
439                },
440                FsNodeFlags::empty(),
441            );
442            if fsverity_enabled {
443                *child.fsverity.lock() = FsVerityState::FsVerity;
444            }
445            if let Some(fio::SelinuxContext::Data(data)) = mutable.selinux_context.as_ref() {
446                security::fs_node_notify_security_context(
447                    self.current_task,
448                    &child,
449                    FsStr::new(data),
450                );
451            }
452            Ok(child)
453        })?;
454
455        node.update_info(|info| update_info_from_fidl(info, mutable, immutable));
456
457        Ok(node)
458    }
459}
460
461impl<'a, I: SyncIo> sync_io_client::Factory<I> for LookupFactory<'a> {
462    type Result = Result<FsNodeHandle, Errno>;
463
464    fn create_node(self, io: I, info: fio::NodeInfo) -> Self::Result {
465        self.get_node(io, get_attributes(&info.attributes), |io| {
466            Box::new(RemoteNode::new(io, false))
467        })
468    }
469
470    fn create_directory(self, io: I, info: fio::DirectoryInfo) -> Self::Result {
471        self.get_node(io, get_attributes(&info.attributes), |io| {
472            Box::new(RemoteNode::new(io, false))
473        })
474    }
475
476    fn create_file(self, io: I, info: fio::FileInfo) -> Self::Result {
477        let is_special_node = is_special(&info);
478        self.get_node(io, get_attributes(&info.attributes), |io| {
479            if is_special_node {
480                Box::new(RemoteSpecialNode { node: BaseNode::new(io, false) })
481            } else {
482                Box::new(RemoteNode::new(io, false))
483            }
484        })
485    }
486
487    fn create_symlink(self, io: I, mut info: fio::SymlinkInfo) -> Self::Result {
488        let mut target = info.target.take();
489        if target.is_none() {
490            return error!(EIO);
491        }
492        let node = self.get_node(io, get_attributes(&info.attributes), |io| {
493            Box::new(RemoteSymlink::new(BaseNode::new(io, false), target.take().unwrap()))
494        })?;
495        // Encrypted symlinks that use fscrypt can be read as encrypted links when no key is
496        // available.  When no key is available, directories will not cache their entries.  When,
497        // the key is subsequently provided, the next time the symlink is read, we will come through
498        // here, but since the node is cached, `get_or_create_node` will not create a new node
499        // which, if we were to do nothing, would mean we'd keep the encrypted value for the target.
500        // To address this, if no new node was created, we update the target of the existing node
501        // here.  Once the key has been provided, the entry will be cached with the directory and
502        // whilst the entry remains cached, `lookup` will not be called.
503        if let Some(target) = target
504            && let Some(symlink) = node.downcast_ops::<RemoteSymlink<I>>()
505        {
506            *symlink.target.write() = target.into_boxed_slice();
507        }
508        Ok(node)
509    }
510}
511
512// A helper that makes it easy to deal with the rare case where no FIDL attributes are returned.
513fn get_attributes(attrs: &Option<fio::NodeAttributes2>) -> &fio::NodeAttributes2 {
514    static DEFAULT_NODE_ATTRIBUTES: LazyLock<fio::NodeAttributes2> =
515        LazyLock::new(|| fio::NodeAttributes2 {
516            mutable_attributes: Default::default(),
517            immutable_attributes: Default::default(),
518        });
519    attrs.as_ref().unwrap_or_else(|| &*DEFAULT_NODE_ATTRIBUTES)
520}
521
522impl<I: SyncIo> RemoteFs<I> {
523    pub fn new_with_io(
524        root_io: I,
525        root_rights: fio::Flags,
526        name: &'static str,
527    ) -> Result<(RemoteFs<I>, Box<dyn FsNodeOps>, FsNodeInfo, u64), Errno> {
528        let vfs_type = root_io
529            .query_filesystem()
530            .ok()
531            .and_then(|i| fidl_fuchsia_fs::VfsType::from_primitive(i.fs_type));
532        let (use_remote_ids, casefold) = match vfs_type {
533            Some(fidl_fuchsia_fs::VfsType::Fxfs) => (true, true),
534            Some(fidl_fuchsia_fs::VfsType::Erofs) => (true, false),
535            _ => (false, false),
536        };
537
538        // The OnRepresentation response will return an initial set of `attrs`.
539        let default_mode = if root_rights.contains(fio::PERM_WRITABLE) {
540            mode!(IFDIR, 0o777)
541        } else {
542            mode!(IFDIR, 0o555)
543        };
544        let mut node_info = FsNodeInfo::new(default_mode, FsCred::root());
545        let (remote_node, node_id) = root_io
546            .open(
547                ".",
548                fio::Flags::PROTOCOL_DIRECTORY
549                    | fio::PERM_READABLE
550                    | fio::Flags::PERM_INHERIT_WRITE
551                    | fio::Flags::PERM_INHERIT_EXECUTE,
552                None,
553                NODE_INFO_ATTRIBUTES
554                    | fio::NodeAttributesQuery::ID
555                    | fio::NodeAttributesQuery::ENCRYPTION_POLICY
556                    | fio::NodeAttributesQuery::MODE
557                    | fio::NodeAttributesQuery::UID
558                    | fio::NodeAttributesQuery::GID,
559                Factory::new(&mut node_info, false),
560            )
561            .map_err(map_sync_io_client_error)?;
562
563        Ok((
564            RemoteFs { use_remote_ids, root_io, root_rights, casefold, name },
565            remote_node,
566            node_info,
567            node_id,
568        ))
569    }
570
571    pub(super) fn use_remote_ids(&self) -> bool {
572        self.use_remote_ids
573    }
574}
575
576impl RemoteFs<RemoteIo> {
577    pub fn new(
578        root: zx::Channel,
579        root_rights: fio::Flags,
580        name: &'static str,
581    ) -> Result<(RemoteFs<RemoteIo>, Box<dyn FsNodeOps>, FsNodeInfo, u64), Errno> {
582        let root_io = RemoteIo::new(fio::NodeSynchronousProxy::new(root));
583        Self::new_with_io(root_io, root_rights, name)
584    }
585
586    pub fn new_fs(
587        kernel: &Kernel,
588        root: zx::Channel,
589        options: FileSystemOptions,
590        rights: fio::Flags,
591    ) -> Result<FileSystemHandle, Errno> {
592        let (remotefs, root_node, info, node_id) = RemoteFs::new(root, rights, "remotefs")?;
593
594        if !rights.contains(fio::PERM_WRITABLE) {
595            options.flags.fetch_or(FileSystemFlags::RDONLY, Ordering::Relaxed);
596        }
597        let use_remote_ids = remotefs.use_remote_ids;
598        let fs = FileSystem::new(
599            kernel,
600            CacheMode::Cached(kernel.fs_cache_config()),
601            remotefs,
602            options,
603        )?;
604
605        let node_id = if use_remote_ids { node_id } else { fs.allocate_ino() };
606        fs.create_root_with_info(node_id, root_node, info);
607
608        Ok(fs)
609    }
610}
611
612/// All nodes compose `BaseNode`.
613///
614/// NOTE: If new node types are created, the `TryFrom` implementation needs updating below.
615struct BaseNode<I> {
616    /// The underlying I/O object for this remote node.
617    io: I,
618
619    /// The number of active dirty operations on this node and whether the node info is in sync.
620    /// See the `will_dirty` function for semantics.
621    info_state: InfoState,
622}
623
624impl<I> BaseNode<I> {
625    fn new(io: I, dirty: bool) -> Self {
626        Self { io, info_state: InfoState::new(dirty) }
627    }
628}
629
630impl<I: SyncIo> BaseNode<I> {
631    fn fetch_and_refresh_info<'a>(
632        &self,
633        info: &'a DynamicLockDepRwLock<FsNodeInfo>,
634    ) -> Result<LockDepReadGuard<'a, FsNodeInfo>, Errno> {
635        self.info_state.maybe_refresh(
636            info,
637            |info| {
638                let mut query = NODE_INFO_ATTRIBUTES;
639                if info.read().pending_time_access_update {
640                    query |= fio::NodeAttributesQuery::PENDING_ACCESS_TIME_UPDATE;
641                }
642                let (mutable, immutable) =
643                    self.io.attr_get(query).map_err(map_sync_io_client_error)?;
644                let mut info = info.write();
645                info.pending_time_access_update = false;
646                update_info_from_fidl(&mut info, &mutable, &immutable);
647                Ok(LockDepWriteGuard::downgrade(info))
648            },
649            |info| Ok(info.read()),
650        )
651    }
652
653    fn update_attributes(&self, info: &FsNodeInfo, has: zxio_node_attr_has_t) -> Result<(), Errno> {
654        // Omit updating creation_time. By definition, there shouldn't be a change in creation_time.
655        will_dirty(&[self], || {
656            let res = self.io.attr_set(fio::MutableNodeAttributes {
657                modification_time: has
658                    .modification_time
659                    .then_some(info.time_modify.into_nanos() as u64),
660                access_time: has.access_time.then_some(info.time_access.into_nanos() as u64),
661                mode: has.mode.then_some(info.mode.bits()),
662                uid: has.uid.then_some(info.uid),
663                gid: has.gid.then_some(info.gid),
664                rdev: has.rdev.then_some(info.rdev.bits()),
665                casefold: has.casefold.then_some(info.casefold),
666                encryption_policy: if has.encryption_policy {
667                    info.encryption_policy.map(|p| fio::FscryptPolicy {
668                        key_identifier: p.key_identifier,
669                        flags: fio::FscryptPolicyFlags::from_bits_retain(p.flags.bits()),
670                    })
671                } else {
672                    None
673                },
674                ..Default::default()
675            });
676            res.map_err(|status| from_status_like_fdio!(status))
677        })
678    }
679}
680
681impl<'a, I: SyncIo> TryFrom<&'a FsNode> for &'a BaseNode<I> {
682    type Error = ();
683    fn try_from(value: &'a FsNode) -> Result<&'a BaseNode<I>, ()> {
684        value
685            .downcast_ops::<RemoteNode<I>>()
686            .map(|n| &n.node)
687            .or_else(|| value.downcast_ops::<RemoteSpecialNode<I>>().map(|n| &n.node))
688            .or_else(|| value.downcast_ops::<RemoteSymlink<I>>().map(|n| &n.node))
689            .ok_or(())
690    }
691}
692
693/// This is the most common type of node.  It is used for files and directories.  Symlinks and
694/// special nodes use RemoteSymlink and RemoteSpecialNode respectively.
695struct RemoteNode<I> {
696    node: BaseNode<I>,
697
698    /// Cached read-only VMO handle shared across all open `RemoteFileObject`s for this inode.
699    read_only_memory: OnceCell<Arc<MemoryObject>>,
700
701    /// Cached read/exec VMO handle shared across all open `RemoteFileObject`s for this inode.
702    read_exec_memory: OnceCell<Arc<MemoryObject>>,
703}
704
705impl<I> RemoteNode<I> {
706    fn new(io: I, dirty: bool) -> Self {
707        Self {
708            node: BaseNode::new(io, dirty),
709            read_only_memory: OnceCell::new(),
710            read_exec_memory: OnceCell::new(),
711        }
712    }
713}
714
715impl<I: SyncIo> RemoteNode<I> {
716    fn get_memory(
717        &self,
718        file: &FileObject,
719        prot: ProtectionFlags,
720    ) -> Result<Arc<MemoryObject>, Errno> {
721        get_or_init_remote_memory(file, &self.read_only_memory, &self.read_exec_memory, prot, |p| {
722            self.node.io.fetch_remote_memory(p)
723        })
724    }
725
726    /// Shared implementation of `mknod()` and `mkdir()`.
727    ///
728    /// Creates a child of this directory named `name` with the given `protocol` (file or
729    /// directory), supplying its mode, ownership, `extra_attributes`, and (if the file-system is
730    /// xattr-labeled) its security context inline with the creation request, so that no separate
731    /// `UpdateAttributes` or `SetExtendedAttribute` round-trips are needed afterwards.
732    fn create_child(
733        &self,
734        node: &FsNode,
735        current_task: &CurrentTask,
736        name: Option<&FsStr>,
737        mut node_info: FsNodeInfo,
738        create_flags: fio::Flags,
739        extra_attributes: fio::MutableNodeAttributes,
740    ) -> Result<FsNodeHandle, Errno> {
741        let name_str = if let Some(name) = name {
742            node.fail_if_locked(current_task, &node.info())?;
743            get_name_str(name)?
744        } else {
745            "."
746        };
747
748        let fs = node.fs();
749        let fs_ops = RemoteFs::<I>::from_fs(&fs);
750        let mode = node_info.mode;
751
752        // Ask the LSM for the label the new node should receive, so that it can be applied by the
753        // remote file-system as part of creation.
754        let security_xattr =
755            security::dentry_init_security(current_task, node, mode, name.unwrap_or_default())?;
756        // `fio::MutableNodeAttributes::selinux_context` carries specifically the SELinux label (up
757        // to `MAX_SELINUX_CONTEXT_ATTRIBUTE_LEN` bytes); any other or larger security xattr is left
758        // to be applied by the VFS via `SetExtendedAttribute`.
759        let selinux_context = security_xattr
760            .as_ref()
761            .filter(|xattr| {
762                xattr.name.as_bytes() == XATTR_NAME_SELINUX.to_bytes()
763                    && xattr.value.len() <= fio::MAX_SELINUX_CONTEXT_ATTRIBUTE_LEN as usize
764            })
765            .map(|xattr| xattr.value.clone());
766
767        let (ops, node_id) = will_dirty(&[&self.node], || {
768            self.node
769                .io
770                .open(
771                    name_str,
772                    create_flags | fio::PERM_READABLE | fio::PERM_WRITABLE,
773                    Some(fio::MutableNodeAttributes {
774                        mode: Some(mode.bits()),
775                        uid: Some(node_info.uid),
776                        gid: Some(node_info.gid),
777                        selinux_context: selinux_context
778                            .as_deref()
779                            .map(|ctx| fio::SelinuxContext::Data(ctx.to_vec())),
780                        ..extra_attributes
781                    }),
782                    NODE_INFO_ATTRIBUTES
783                        | fio::NodeAttributesQuery::ID
784                        | fio::NodeAttributesQuery::ENCRYPTION_POLICY,
785                    Factory::new(&mut node_info, !(mode.is_reg() || mode.is_dir())),
786                )
787                .map_err(|status| from_status_like_fdio!(status, name_str))
788        })?;
789
790        let node_id = if fs_ops.use_remote_ids { node_id } else { fs.allocate_ino() };
791
792        let child = fs.create_node(node_id, ops, node_info);
793        if let Some(context) = selinux_context {
794            let _ = security::fs_node_notify_security_context(
795                current_task,
796                &child,
797                FsStr::new(&context),
798            );
799        }
800        Ok(child)
801    }
802}
803
804/// Classified Fuchsia handle representation returned by [`classify_remote_handle`].
805enum RemoteHandle {
806    Socket(SocketHandle),
807    File(RemoteIo),
808    Directory(RemoteIo),
809    Counter(RemoteCounter),
810    Zxio { zxio: Zxio, handle_type: zx::ObjectType, content_size: Option<u64> },
811}
812
813/// Inspects `handle` and constructs the corresponding [`RemoteHandle`] variant.
814fn classify_remote_handle(
815    current_task: &CurrentTask,
816    mut handle: zx::NullableHandle,
817    creds: Arc<Credentials>,
818) -> Result<RemoteHandle, Errno> {
819    let handle_type =
820        handle.basic_info().map_err(|status| from_status_like_fdio!(status))?.object_type;
821
822    if handle_type == zx::ObjectType::CHANNEL {
823        let channel = zx::Channel::from(handle);
824        let queryable = funknown::QueryableSynchronousProxy::new(channel);
825        let protocol = queryable.query(zx::MonotonicInstant::INFINITE).map_err(|_| errno!(EIO))?;
826        const UNIX_DOMAIN_SOCKET_PROTOCOL: &[u8] =
827            fbinder::UnixDomainSocketMarker::PROTOCOL_NAME.as_bytes();
828        const FILE_PROTOCOL: &[u8] = fio::FileMarker::PROTOCOL_NAME.as_bytes();
829        const DIRECTORY_PROTOCOL: &[u8] = fio::DirectoryMarker::PROTOCOL_NAME.as_bytes();
830        match &protocol[..] {
831            UNIX_DOMAIN_SOCKET_PROTOCOL => {
832                let socket_ops = RemoteUnixDomainSocket::new(queryable.into_channel(), creds)?;
833                let socket = Socket::new_with_ops(Box::new(socket_ops))?;
834                return Ok(RemoteHandle::Socket(socket));
835            }
836            FILE_PROTOCOL => {
837                let file_proxy = fio::FileSynchronousProxy::from(queryable.into_channel());
838                let info =
839                    file_proxy.describe(zx::MonotonicInstant::INFINITE).map_err(|_| errno!(EIO))?;
840                let io = RemoteIo::with_stream(
841                    file_proxy.into_channel().into(),
842                    info.stream.unwrap_or_else(|| zx::NullableHandle::invalid().into()),
843                );
844                return Ok(RemoteHandle::File(io));
845            }
846            DIRECTORY_PROTOCOL => {
847                let io = RemoteIo::new(queryable.into_channel().into());
848                return Ok(RemoteHandle::Directory(io));
849            }
850            _ => {
851                handle = queryable.into_channel().into_handle();
852                // Fall through for zxio.
853            }
854        }
855    } else if handle_type == zx::ObjectType::COUNTER {
856        return Ok(RemoteHandle::Counter(RemoteCounter::new(handle.into())));
857    }
858
859    // Otherwise, use zxio based objects.
860
861    // NOTE: If it's a channel, this will repeat the query, which is something we can optimize if we
862    // need to.
863    let zxio = Zxio::create(handle).map_err(|status| from_status_like_fdio!(status))?;
864    let attrs = zxio
865        .attr_get(zxio_node_attr_has_t {
866            protocols: true,
867            content_size: true,
868            storage_size: true,
869            link_count: true,
870            object_type: true,
871            ..Default::default()
872        })
873        .map_err(|status| from_status_like_fdio!(status))?;
874    match (handle_type, attrs.object_type) {
875        (zx::ObjectType::VMO, _) | (zx::ObjectType::DEBUGLOG, _) | (_, ZXIO_OBJECT_TYPE_NONE) => {
876            Ok(RemoteHandle::Zxio {
877                zxio,
878                handle_type,
879                content_size: attrs.has.content_size.then_some(attrs.content_size),
880            })
881        }
882        (zx::ObjectType::SOCKET, _)
883        | (_, ZXIO_OBJECT_TYPE_SYNCHRONOUS_DATAGRAM_SOCKET)
884        | (_, ZXIO_OBJECT_TYPE_DATAGRAM_SOCKET)
885        | (_, ZXIO_OBJECT_TYPE_STREAM_SOCKET)
886        | (_, ZXIO_OBJECT_TYPE_RAW_SOCKET)
887        | (_, ZXIO_OBJECT_TYPE_PACKET_SOCKET) => {
888            let socket_ops = ZxioBackedSocket::new_with_zxio(current_task, zxio);
889            let socket = Socket::new_with_ops(Box::new(socket_ops))?;
890            Ok(RemoteHandle::Socket(socket))
891        }
892        _ => error!(ENOTSUP),
893    }
894}
895
896/// Creates a [`FileHandle`] from a [`zx::NullableHandle`].
897///
898/// The handle must be a channel, socket, vmo, debuglog, or counter object. If the handle is a
899/// channel, then the channel must implement the `fuchsia.unknown/Queryable` protocol. Not all
900/// protocols are supported; files, directories, and sockets are, but symlinks are not.
901///
902/// The resulting object will be owned by root, and will have permissions derived from the `flags`
903/// used to open this object. This is not the same as the permissions set if the object was created
904/// using Starnix itself. We use this mainly for interfacing with objects created outside of Starnix
905/// where these flags represent the desired permissions already.
906pub fn new_remote_file(
907    current_task: &CurrentTask,
908    handle: zx::NullableHandle,
909    flags: OpenFlags,
910) -> Result<FileHandle, Errno> {
911    let creds = current_task.current_creds().clone();
912    match classify_remote_handle(current_task, handle, creds)? {
913        RemoteHandle::Socket(socket) => {
914            SocketFile::from_socket(current_task, socket, flags, /* kernel_private = */ false)
915        }
916        RemoteHandle::File(io) => {
917            new_remote_fs_node_file(current_task, io, /* is_dir = */ false, flags)
918        }
919        RemoteHandle::Directory(io) => {
920            new_remote_fs_node_file(current_task, io, /* is_dir = */ true, flags)
921        }
922        RemoteHandle::Counter(counter) => {
923            Ok(Anon::new_private_file(current_task, Box::new(counter), flags, "[fuchsia:counter]"))
924        }
925        RemoteHandle::Zxio { zxio, handle_type, content_size } => {
926            let size = content_size.map(|s| usize::try_from(s).unwrap_or(usize::MAX)).unwrap_or(0);
927            let ops = Box::new(RemoteZxioFileObject::new(zxio));
928            let name = match handle_type {
929                zx::ObjectType::VMO => "[fuchsia:vmo]",
930                zx::ObjectType::DEBUGLOG => "[fuchsia:debuglog]",
931                _ => "[fuchsia:remote]",
932            };
933            Ok(MemoryRegularFile::new_private_file_with_ops(current_task, ops, size, flags, name))
934        }
935    }
936}
937
938/// Unrooted [`FsNodeOps`] implementation for remote Fuchsia channels wrapped via
939/// [`new_remote_file`].
940struct AnonymousRemoteNode;
941
942impl FsNodeOps for AnonymousRemoteNode {
943    fs_node_impl_not_dir!();
944
945    fn create_file_ops(
946        &self,
947        _node: &FsNode,
948        _current_task: &CurrentTask,
949        _flags: OpenFlags,
950    ) -> Result<Box<dyn FileOps>, Errno> {
951        error!(ENOSYS)
952    }
953}
954
955/// [`FileSystemOps`] for the kernel-singleton `remotefs` instance hosting unrooted remote nodes.
956struct RemoteNullFs;
957
958impl FileSystemOps for RemoteNullFs {
959    fn statfs(&self, _fs: &FileSystem, _current_task: &CurrentTask) -> Result<statfs, Errno> {
960        Ok(default_statfs(0))
961    }
962
963    fn name(&self) -> &'static FsStr {
964        "remotefs".into()
965    }
966}
967
968/// Returns the kernel-singleton `remotefs` [`FileSystemHandle`] used for unrooted remote nodes.
969fn remote_null_fs(current_task: &CurrentTask) -> Result<FileSystemHandle, Errno> {
970    struct RemoteNullFsHandle {
971        fs: FileSystemHandle,
972    }
973
974    let kernel = current_task.kernel();
975    let fs = kernel
976        .expando
977        .get_or_init(|| RemoteNullFsHandle {
978            fs: FileSystem::new(
979                kernel,
980                CacheMode::Uncached,
981                RemoteNullFs,
982                FileSystemOptions::default(),
983            )
984            .expect("remotefs constructed with valid options"),
985        })
986        .fs
987        .clone();
988    security::file_system_resolve_security(current_task, &fs)?;
989    Ok(fs)
990}
991
992/// Creates a [`FileHandle`] backed by an unrooted [`FsNode`] in [`remote_null_fs`].
993fn new_remote_fs_node_file(
994    current_task: &CurrentTask,
995    io: RemoteIo,
996    is_dir: bool,
997    flags: OpenFlags,
998) -> Result<FileHandle, Errno> {
999    let fs = remote_null_fs(current_task)?;
1000    let is_xattr_labeled = security::fs_is_xattr_labeled(fs.clone());
1001    let mut query = MODE_ATTRIBUTES | NODE_INFO_ATTRIBUTES;
1002    if is_xattr_labeled {
1003        query |= fio::NodeAttributesQuery::SELINUX_CONTEXT;
1004    }
1005    let (mutable, mut immutable) = io.attr_get(query).map_err(map_sync_io_client_error)?;
1006    immutable.protocols.get_or_insert(if is_dir {
1007        fio::NodeProtocolKinds::DIRECTORY
1008    } else {
1009        fio::NodeProtocolKinds::FILE
1010    });
1011    let mut rights = fio::Flags::empty();
1012    if flags.can_read() {
1013        rights |= fio::PERM_READABLE;
1014    }
1015    if flags.can_write() {
1016        rights |= fio::PERM_WRITABLE;
1017    }
1018    let mode = get_mode_from_fidl(&mutable, &immutable, rights);
1019    let mut info = FsNodeInfo::new(mode, FsCred::root());
1020    update_info_from_fidl(&mut info, &mutable, &immutable);
1021    let selinux_context = match mutable.selinux_context {
1022        Some(fio::SelinuxContext::Data(data)) => Some(data),
1023        Some(fio::SelinuxContext::UseExtendedAttributes(_)) => {
1024            io.xattr_get(XATTR_NAME_SELINUX.to_bytes().into()).ok()
1025        }
1026        _ => None,
1027    };
1028    let ops: Box<dyn FileOps> = if is_dir {
1029        Box::new(RemoteDirectoryObject::new(RemoteDirectory::new(
1030            io.into_proxy().into_channel().into(),
1031        )))
1032    } else {
1033        Box::new(AnonymousRemoteFileObject::new(io))
1034    };
1035
1036    let node = fs.create_node_and_allocate_node_id(AnonymousRemoteNode, info);
1037    if let Some(data) = selinux_context {
1038        security::fs_node_notify_security_context(current_task, &node, FsStr::new(&data));
1039    }
1040    let dir_entry = DirEntry::new_unrooted(node);
1041    security::fs_node_init_with_dentry(current_task, &dir_entry)?;
1042    FileObject::new(current_task, ops, NamespaceNode::new_anonymous(dir_entry), flags)
1043}
1044
1045/// Creates a [`FileOps`] from a [`zx::NullableHandle`].
1046pub fn new_remote_file_ops(
1047    current_task: &CurrentTask,
1048    handle: zx::NullableHandle,
1049    creds: Arc<Credentials>,
1050) -> Result<Box<dyn FileOps>, Errno> {
1051    match classify_remote_handle(current_task, handle, creds)? {
1052        RemoteHandle::Socket(socket) => Ok(SocketFile::new(socket)),
1053        RemoteHandle::File(io) => Ok(Box::new(AnonymousRemoteFileObject::new(io))),
1054        RemoteHandle::Directory(io) => Ok(Box::new(RemoteDirectoryObject::new(
1055            RemoteDirectory::new(io.into_proxy().into_channel().into()),
1056        ))),
1057        RemoteHandle::Counter(counter) => Ok(Box::new(counter)),
1058        RemoteHandle::Zxio { zxio, .. } => Ok(Box::new(RemoteZxioFileObject::new(zxio))),
1059    }
1060}
1061
1062/// Creates a `pipefs`-backed [`FileHandle`] (`S_IFIFO`) from a [`zx::Socket`].
1063pub fn create_fuchsia_pipe(
1064    current_task: &CurrentTask,
1065    socket: zx::Socket,
1066    flags: OpenFlags,
1067) -> Result<FileHandle, Errno> {
1068    let zxio = Zxio::create(socket.into()).map_err(|status| from_status_like_fdio!(status))?;
1069    new_pipe_file(current_task, Box::new(RemotePipeObject::new(zxio)), flags)
1070}
1071
1072// This only needs to include attributes that can be out of date.  There are other attributes that
1073// we read when we first look up the node (see `lookup`).
1074const NODE_INFO_ATTRIBUTES: fio::NodeAttributesQuery = fio::NodeAttributesQuery::CONTENT_SIZE
1075    .union(fio::NodeAttributesQuery::STORAGE_SIZE)
1076    .union(fio::NodeAttributesQuery::LINK_COUNT)
1077    .union(fio::NodeAttributesQuery::MODIFICATION_TIME)
1078    .union(fio::NodeAttributesQuery::CHANGE_TIME)
1079    .union(fio::NodeAttributesQuery::ACCESS_TIME);
1080
1081/// Updates info from attrs if they are set.
1082///
1083// Keep in sync with `NODE_INFO_ATTRIBUTES`.
1084pub(super) fn update_info_from_attrs(info: &mut FsNodeInfo, attrs: &zxio_node_attributes_t) {
1085    // TODO - store these in FsNodeState and convert on fstat
1086    if attrs.has.content_size {
1087        info.size = attrs.content_size.try_into().unwrap_or(usize::MAX);
1088    }
1089    if attrs.has.storage_size {
1090        info.blocks = usize::try_from(attrs.storage_size)
1091            .unwrap_or(usize::MAX)
1092            .div_ceil(DEFAULT_BYTES_PER_BLOCK)
1093    }
1094    info.blksize = DEFAULT_BYTES_PER_BLOCK;
1095    if attrs.has.link_count {
1096        info.link_count = attrs.link_count.try_into().unwrap_or(usize::MAX);
1097    }
1098    if attrs.has.modification_time {
1099        info.time_modify =
1100            UtcInstant::from_nanos(attrs.modification_time.try_into().unwrap_or(i64::MAX));
1101    }
1102    if attrs.has.change_time {
1103        info.time_status_change =
1104            UtcInstant::from_nanos(attrs.change_time.try_into().unwrap_or(i64::MAX));
1105    }
1106    if attrs.has.access_time {
1107        info.time_access = UtcInstant::from_nanos(attrs.access_time.try_into().unwrap_or(i64::MAX));
1108    }
1109    // The following are only read once so they're not included in `NODE_INFO_ATTRIBUTES`.
1110    if attrs.has.casefold {
1111        info.casefold = attrs.casefold;
1112    }
1113}
1114
1115/// Same as `update_info_from_attr` but uses FIDL.
1116fn update_info_from_fidl(
1117    info: &mut FsNodeInfo,
1118    mutable: &fio::MutableNodeAttributes,
1119    immutable: &fio::ImmutableNodeAttributes,
1120) {
1121    if let Some(content_size) = immutable.content_size {
1122        info.size = content_size.try_into().unwrap_or(usize::MAX);
1123    }
1124    if let Some(storage_size) = immutable.storage_size {
1125        info.blocks =
1126            usize::try_from(storage_size).unwrap_or(usize::MAX).div_ceil(DEFAULT_BYTES_PER_BLOCK);
1127    }
1128    info.blksize = DEFAULT_BYTES_PER_BLOCK;
1129    if let Some(link_count) = immutable.link_count {
1130        info.link_count = link_count.try_into().unwrap_or(usize::MAX);
1131    }
1132    if let Some(modification_time) = mutable.modification_time {
1133        info.time_modify = UtcInstant::from_nanos(modification_time.try_into().unwrap_or(i64::MAX));
1134    }
1135    if let Some(change_time) = immutable.change_time {
1136        info.time_status_change =
1137            UtcInstant::from_nanos(change_time.try_into().unwrap_or(i64::MAX));
1138    }
1139    if !info.pending_time_access_update
1140        && let Some(access_time) = mutable.access_time
1141    {
1142        info.time_access = UtcInstant::from_nanos(access_time.try_into().unwrap_or(i64::MAX));
1143    }
1144    // The following are only read once so they're not included in `NODE_INFO_ATTRIBUTES`.
1145    if let Some(casefold) = mutable.casefold {
1146        info.casefold = casefold;
1147    }
1148    if let Some(policy) = mutable.encryption_policy {
1149        info.encryption_policy = Some(crate::vfs::FscryptNodePolicy {
1150            key_identifier: policy.key_identifier,
1151            flags: crate::vfs::FscryptPolicyFlags::from_bits_retain(policy.flags.bits()),
1152        });
1153    }
1154}
1155
1156/// The attributes we need to request to compute the right mode.
1157const MODE_ATTRIBUTES: fio::NodeAttributesQuery =
1158    fio::NodeAttributesQuery::PROTOCOLS.union(fio::NodeAttributesQuery::MODE);
1159
1160// NOTE: Keep in sync with `MODE_ATTRIBUTES`.
1161fn get_mode_from_fidl(
1162    mutable: &fio::MutableNodeAttributes,
1163    immutable: &fio::ImmutableNodeAttributes,
1164    rights: fio::Flags,
1165) -> FileMode {
1166    let protocols = immutable.protocols.unwrap_or(fio::NodeProtocolKinds::empty());
1167    if protocols.contains(fio::NodeProtocolKinds::SYMLINK) {
1168        // We don't set the mode for symbolic links , so we synthesize it instead.
1169        FileMode::IFLNK | FileMode::ALLOW_ALL
1170    } else if let Some(mode) = mutable.mode {
1171        // If the filesystem supports POSIX mode bits, use that directly.
1172        FileMode::from_bits(mode)
1173    } else {
1174        // The filesystem doesn't support the `mode` attribute, so synthesize it from the protocols
1175        // this node supports, and the rights used to open it.
1176        let is_directory = protocols.contains(fio::NodeProtocolKinds::DIRECTORY);
1177        let mode = if is_directory { FileMode::IFDIR } else { FileMode::IFREG };
1178        let mut permissions = FileMode::EMPTY;
1179        if rights.contains(fio::PERM_READABLE) {
1180            permissions |= FileMode::IRUSR;
1181        }
1182        if rights.contains(fio::PERM_WRITABLE) {
1183            permissions |= FileMode::IWUSR;
1184        }
1185        if rights.contains(fio::PERM_EXECUTABLE) {
1186            permissions |= FileMode::IXUSR;
1187        }
1188        // Make sure the same permissions are granted to user, group, and other.
1189        permissions |= FileMode::from_bits((permissions.bits() >> 3) | (permissions.bits() >> 6));
1190        mode | permissions
1191    }
1192}
1193
1194fn get_name_str<'a>(name_bytes: &'a FsStr) -> Result<&'a str, Errno> {
1195    std::str::from_utf8(name_bytes.as_ref()).map_err(|_| {
1196        log_warn!("bad utf8 in pathname! remote filesystems can't handle this");
1197        errno!(EINVAL)
1198    })
1199}
1200
1201impl<I: SyncIo> XattrStorage for BaseNode<I> {
1202    fn get_xattr(&self, name: &FsStr) -> Result<Box<[u8]>, Errno> {
1203        self.io.xattr_get(name).map(Vec::into_boxed_slice).map_err(|status| match status {
1204            zx::Status::NOT_FOUND => errno!(ENODATA),
1205            status => from_status_like_fdio!(status),
1206        })
1207    }
1208
1209    fn set_xattr(&self, name: &FsStr, value: &[u8], op: XattrOp) -> Result<(), Errno> {
1210        let mode = match op {
1211            XattrOp::Set => XattrSetMode::Set,
1212            XattrOp::Create => XattrSetMode::Create,
1213            XattrOp::Replace => XattrSetMode::Replace,
1214        };
1215
1216        will_dirty(&[self], || {
1217            self.io.xattr_set(name, value, mode).map_err(|status| match status {
1218                zx::Status::NOT_FOUND => errno!(ENODATA),
1219                status => from_status_like_fdio!(status),
1220            })
1221        })
1222    }
1223
1224    fn remove_xattr(&self, name: &FsStr) -> Result<(), Errno> {
1225        will_dirty(&[self], || {
1226            self.io.xattr_remove(name).map_err(|status| match status {
1227                zx::Status::NOT_FOUND => errno!(ENODATA),
1228                _ => from_status_like_fdio!(status),
1229            })
1230        })
1231    }
1232
1233    fn list_xattrs(&self) -> Result<Vec<FsString>, Errno> {
1234        self.io
1235            .xattr_list()
1236            .map(|attrs| attrs.into_iter().map(FsString::new).collect::<Vec<_>>())
1237            .map_err(map_sync_io_client_error)
1238    }
1239}
1240
1241impl<I: SyncIo> FsNodeOps for RemoteNode<I> {
1242    fs_node_impl_xattr_delegate!(self, self.node);
1243
1244    fn create_file_ops(
1245        &self,
1246        node: &FsNode,
1247        current_task: &CurrentTask,
1248        flags: OpenFlags,
1249    ) -> Result<Box<dyn FileOps>, Errno> {
1250        {
1251            // It is safe to read the cached node info here because the `encryption_policy` is
1252            // fetched when the node is first opened, and updated when set. We don't expect this to
1253            // change out from under Starnix.
1254            let node_info = node.info();
1255            if node_info.mode.is_dir() {
1256                if let Some(policy) = node_info.encryption_policy {
1257                    if flags.can_write() {
1258                        // Locked encrypted directories cannot be opened with write access.
1259                        let crypt_service =
1260                            node.fs().crypt_service().ok_or_else(|| errno!(ENOKEY))?;
1261                        if !crypt_service.contains_key(EncryptionKeyId::from(policy.key_identifier))
1262                        {
1263                            return error!(ENOKEY);
1264                        }
1265                    }
1266                }
1267                // For directories we need to clone the connection because we rely on the seek
1268                // offset.
1269                return Ok(Box::new(RemoteDirectoryObject::new(
1270                    self.node.io.open_directory().map_err(map_sync_io_client_error)?,
1271                )));
1272            }
1273        }
1274
1275        // Locked encrypted files cannot be opened.
1276        node.fail_if_locked(current_task, &node.info())?;
1277
1278        // fsverity files cannot be opened in write mode, including while building.
1279        if flags.can_write() {
1280            node.fsverity.lock().check_writable()?;
1281        }
1282
1283        Ok(Box::new(RemoteFileObject::<I>::default()))
1284    }
1285
1286    fn sync(&self, _node: &FsNode, _current_task: &CurrentTask) -> Result<(), Errno> {
1287        self.node.io.sync().map_err(map_sync_io_client_error)
1288    }
1289
1290    fn mknod(
1291        &self,
1292        node: &FsNode,
1293        current_task: &CurrentTask,
1294        name: &FsStr,
1295        mode: FileMode,
1296        dev: DeviceId,
1297        owner: FsCred,
1298    ) -> Result<FsNodeHandle, Errno> {
1299        if !(mode.is_reg() || mode.is_chr() || mode.is_blk() || mode.is_fifo() || mode.is_sock()) {
1300            return error!(EINVAL, name);
1301        }
1302        self.create_child(
1303            node,
1304            current_task,
1305            Some(name),
1306            FsNodeInfo { rdev: dev, ..FsNodeInfo::new(mode, owner) },
1307            fio::Flags::FLAG_MUST_CREATE | fio::Flags::PROTOCOL_FILE,
1308            fio::MutableNodeAttributes { rdev: Some(dev.bits()), ..Default::default() },
1309        )
1310    }
1311
1312    fn mkdir(
1313        &self,
1314        node: &FsNode,
1315        current_task: &CurrentTask,
1316        name: &FsStr,
1317        mode: FileMode,
1318        owner: FsCred,
1319    ) -> Result<FsNodeHandle, Errno> {
1320        self.create_child(
1321            node,
1322            current_task,
1323            Some(name),
1324            FsNodeInfo::new(mode, owner),
1325            fio::Flags::FLAG_MUST_CREATE | fio::Flags::PROTOCOL_DIRECTORY,
1326            fio::MutableNodeAttributes::default(),
1327        )
1328    }
1329
1330    fn lookup(
1331        &self,
1332        entry: &DirEntry,
1333        current_task: &CurrentTask,
1334        name: &FsStr,
1335    ) -> Result<FsNodeHandle, Errno> {
1336        let name = get_name_str(name)?;
1337
1338        let fs = entry.node.fs();
1339        let fs_ops = RemoteFs::<I>::from_fs(&fs);
1340
1341        let mut query = MODE_ATTRIBUTES
1342            | NODE_INFO_ATTRIBUTES
1343            | fio::NodeAttributesQuery::ID
1344            | fio::NodeAttributesQuery::UID
1345            | fio::NodeAttributesQuery::GID
1346            | fio::NodeAttributesQuery::RDEV
1347            | fio::NodeAttributesQuery::ENCRYPTION_POLICY
1348            | fio::NodeAttributesQuery::VERITY_ENABLED
1349            | fio::NodeAttributesQuery::CASEFOLD;
1350
1351        if security::fs_is_xattr_labeled(fs.clone()) {
1352            query |= fio::NodeAttributesQuery::SELINUX_CONTEXT;
1353        }
1354
1355        self.node
1356            .io
1357            .open(name, fs_ops.root_rights, None, query, LookupFactory::new(&fs, current_task))
1358            .map_err(|status| from_status_like_fdio!(status, name))?
1359    }
1360
1361    fn has_lookup_pipelined(&self) -> bool {
1362        true
1363    }
1364
1365    fn lookup_pipelined(
1366        &self,
1367        entry: &DirEntry,
1368        current_task: &CurrentTask,
1369        names: &[&FsStr],
1370    ) -> LookupVec<Result<FsNodeHandle, Errno>> {
1371        let fs = entry.node.fs();
1372        let fs_ops = RemoteFs::<I>::from_fs(&fs);
1373
1374        let mut query = MODE_ATTRIBUTES
1375            | NODE_INFO_ATTRIBUTES
1376            | fio::NodeAttributesQuery::ID
1377            | fio::NodeAttributesQuery::UID
1378            | fio::NodeAttributesQuery::GID
1379            | fio::NodeAttributesQuery::RDEV
1380            | fio::NodeAttributesQuery::ENCRYPTION_POLICY
1381            | fio::NodeAttributesQuery::VERITY_ENABLED
1382            | fio::NodeAttributesQuery::CASEFOLD;
1383
1384        if security::fs_is_xattr_labeled(fs.clone()) {
1385            query |= fio::NodeAttributesQuery::SELINUX_CONTEXT;
1386        }
1387
1388        let names_str =
1389            match names.iter().map(|n| get_name_str(n)).collect::<Result<LookupVec<_>, Errno>>() {
1390                Ok(names_str) => names_str,
1391                Err(e) => return vec![Err(e)].into(),
1392            };
1393
1394        self.node
1395            .io
1396            .open_pipelined(&names_str, fs_ops.root_rights, query, || {
1397                LookupFactory::new(&fs, current_task)
1398            })
1399            .map(|r| r.map_err(|status| from_status_like_fdio!(status)).flatten())
1400            .collect()
1401    }
1402
1403    fn truncate(
1404        &self,
1405        _guard: &AppendLockWriteGuard<'_>,
1406        node: &FsNode,
1407        current_task: &CurrentTask,
1408        length: u64,
1409    ) -> Result<(), Errno> {
1410        node.fail_if_locked(current_task, &node.info())?;
1411
1412        let _guard = self.node.info_state.dirty_op_guard(true);
1413
1414        self.node.io.truncate(length).map_err(|status| from_status_like_fdio!(status))
1415    }
1416
1417    fn allocate(
1418        &self,
1419        _guard: &AppendLockWriteGuard<'_>,
1420        node: &FsNode,
1421        current_task: &CurrentTask,
1422        mode: FallocMode,
1423        offset: u64,
1424        length: u64,
1425    ) -> Result<(), Errno> {
1426        match mode {
1427            FallocMode::Allocate { keep_size } => {
1428                node.fail_if_locked(current_task, &node.info())?;
1429
1430                let allocate_mode =
1431                    if keep_size { AllocateMode::KEEP_SIZE } else { AllocateMode::empty() };
1432
1433                will_dirty(&[&self.node], || {
1434                    self.node
1435                        .io
1436                        .allocate(offset, length, allocate_mode)
1437                        .map_err(|status| from_status_like_fdio!(status))
1438                })?;
1439                Ok(())
1440            }
1441            FallocMode::PunchHole => {
1442                node.fail_if_locked(current_task, &node.info())?;
1443
1444                will_dirty(&[&self.node], || {
1445                    match self.node.io.allocate(
1446                        offset,
1447                        length,
1448                        AllocateMode::PUNCH_HOLE | AllocateMode::KEEP_SIZE,
1449                    ) {
1450                        Ok(()) => Ok(()),
1451                        Err(zx::Status::NOT_SUPPORTED) => Ok(()),
1452                        Err(status) => Err(from_status_like_fdio!(status)),
1453                    }
1454                })?;
1455                Ok(())
1456            }
1457            _ => error!(EINVAL),
1458        }
1459    }
1460
1461    fn fetch_and_refresh_info<'a>(
1462        &self,
1463        _node: &FsNode,
1464        _current_task: &CurrentTask,
1465        info: &'a DynamicLockDepRwLock<FsNodeInfo>,
1466        flags: StatxFlags,
1467    ) -> Result<LockDepReadGuard<'a, FsNodeInfo>, Errno> {
1468        if flags.contains(StatxFlags::AT_STATX_DONT_SYNC) {
1469            return Ok(info.read());
1470        }
1471        self.node.fetch_and_refresh_info(info)
1472    }
1473
1474    fn update_attributes(
1475        &self,
1476        _node: &FsNode,
1477        _current_task: &CurrentTask,
1478        info: &FsNodeInfo,
1479        has: zxio_node_attr_has_t,
1480    ) -> Result<(), Errno> {
1481        // Attributes of regular remote nodes (files, directory) are valid to update.
1482        // Their metadata is stored and managed by the underlying Fuchsia filesystem.
1483        self.node.update_attributes(info, has)
1484    }
1485
1486    fn unlink(
1487        &self,
1488        node: &FsNode,
1489        _current_task: &CurrentTask,
1490        name: &FsStr,
1491        child: &FsNodeHandle,
1492    ) -> Result<(), Errno> {
1493        // We don't care about the child argument because 1. unlinking already takes the parent's
1494        // children lock, so we don't have to worry about conflicts on this path, and 2. the remote
1495        // filesystem tracks the link counts so we don't need to update them here.
1496        let name = get_name_str(name)?;
1497        will_dirty::<I, _, _>(&[node, child], || {
1498            self.node
1499                .io
1500                .unlink(name, fio::UnlinkFlags::empty())
1501                .map_err(|status| from_status_like_fdio!(status))
1502        })
1503    }
1504
1505    fn create_symlink(
1506        &self,
1507        node: &FsNode,
1508        current_task: &CurrentTask,
1509        name: &FsStr,
1510        target: &FsStr,
1511        owner: FsCred,
1512    ) -> Result<FsNodeHandle, Errno> {
1513        node.fail_if_locked(current_task, &node.info())?;
1514
1515        let name = get_name_str(name)?;
1516        let io = will_dirty(&[&self.node], || {
1517            self.node
1518                .io
1519                .create_symlink(name, target)
1520                .map_err(|status| from_status_like_fdio!(status))
1521        })?;
1522
1523        let fs = node.fs();
1524        let fs_ops = RemoteFs::<I>::from_fs(&fs);
1525
1526        let node_id = if fs_ops.use_remote_ids {
1527            io.attr_get(fio::NodeAttributesQuery::ID)
1528                .map_err(|status| from_status_like_fdio!(status))?
1529                .1
1530                .id
1531                .unwrap_or_default()
1532        } else {
1533            fs.allocate_ino()
1534        };
1535        Ok(fs.create_node(
1536            node_id,
1537            RemoteSymlink::new(BaseNode::new(io, true), target.as_bytes()),
1538            FsNodeInfo {
1539                size: target.len(),
1540                ..FsNodeInfo::new(FileMode::IFLNK | FileMode::ALLOW_ALL, owner)
1541            },
1542        ))
1543    }
1544
1545    fn create_tmpfile(
1546        &self,
1547        node: &FsNode,
1548        current_task: &CurrentTask,
1549        mode: FileMode,
1550        owner: FsCred,
1551    ) -> Result<FsNodeHandle, Errno> {
1552        if !mode.is_reg() {
1553            return error!(EINVAL);
1554        }
1555
1556        // `create_tmpfile` is used by O_TMPFILE. Note that
1557        // <https://man7.org/linux/man-pages/man2/open.2.html> states that if O_EXCL is specified
1558        // with O_TMPFILE, the temporary file created cannot be linked into the filesystem. Although
1559        // there exist fuchsia flags `fio::FLAG_TEMPORARY_AS_NOT_LINKABLE`, the starnix vfs already
1560        // handles this case and makes sure that the created file is not linkable. There is also no
1561        // way of passing the open flags to this function.
1562        self.create_child(
1563            node,
1564            current_task,
1565            None,
1566            FsNodeInfo::new(mode, owner),
1567            fio::Flags::FLAG_CREATE_AS_UNNAMED_TEMPORARY | fio::Flags::PROTOCOL_FILE,
1568            fio::MutableNodeAttributes::default(),
1569        )
1570    }
1571
1572    fn link(
1573        &self,
1574        node: &FsNode,
1575        _current_task: &CurrentTask,
1576        name: &FsStr,
1577        child: &FsNodeHandle,
1578    ) -> Result<(), Errno> {
1579        if !RemoteFs::<I>::from_fs(&node.fs()).use_remote_ids {
1580            return error!(EPERM);
1581        }
1582        let name = get_name_str(name)?;
1583
1584        will_dirty::<I, _, _>(&[node, child], || {
1585            if let Some(child) = child.downcast_ops::<RemoteNode<I>>() {
1586                child.node.io.link_into(&self.node.io, name).map_err(|status| match status {
1587                    zx::Status::BAD_STATE => errno!(EXDEV),
1588                    zx::Status::ACCESS_DENIED => errno!(ENOKEY),
1589                    s => from_status_like_fdio!(s),
1590                })
1591            } else if let Some(child) = child.downcast_ops::<RemoteSymlink<I>>() {
1592                child.node.io.link_into(&self.node.io, name).map_err(|status| match status {
1593                    zx::Status::BAD_STATE => errno!(EXDEV),
1594                    zx::Status::ACCESS_DENIED => errno!(ENOKEY),
1595                    s => from_status_like_fdio!(s),
1596                })
1597            } else {
1598                error!(EXDEV)
1599            }
1600        })
1601    }
1602
1603    fn forget(self: Box<Self>, _current_task: &CurrentTask, info: FsNodeInfo) -> Result<(), Errno> {
1604        // Before forgetting this node, update atime if we need to.
1605        if info.pending_time_access_update {
1606            self.node
1607                .io
1608                .attr_get(fio::NodeAttributesQuery::PENDING_ACCESS_TIME_UPDATE)
1609                .map_err(|status| from_status_like_fdio!(status))?;
1610        }
1611        Ok(())
1612    }
1613
1614    fn enable_fsverity(
1615        &self,
1616        _node: &FsNode,
1617        _current_task: &CurrentTask,
1618        descriptor: &fsverity_descriptor,
1619    ) -> Result<(), Errno> {
1620        let descr = zxio_fsverity_descriptor_t {
1621            hash_algorithm: descriptor.hash_algorithm,
1622            salt_size: descriptor.salt_size,
1623            salt: descriptor.salt,
1624        };
1625        will_dirty(&[&self.node], || {
1626            self.node.io.enable_verity(&descr).map_err(|status| from_status_like_fdio!(status))
1627        })
1628    }
1629
1630    fn get_fsverity_descriptor(&self, log_blocksize: u8) -> Result<fsverity_descriptor, Errno> {
1631        let (_, attrs) = self
1632            .node
1633            .io
1634            .attr_get(
1635                fio::NodeAttributesQuery::CONTENT_SIZE
1636                    | fio::NodeAttributesQuery::OPTIONS
1637                    | fio::NodeAttributesQuery::ROOT_HASH,
1638            )
1639            .map_err(|status| from_status_like_fdio!(status))?;
1640        let fio::ImmutableNodeAttributes {
1641            content_size: Some(data_size),
1642            options:
1643                Some(fio::VerificationOptions {
1644                    hash_algorithm: Some(hash_algorithm),
1645                    salt: Some(salt),
1646                    ..
1647                }),
1648            root_hash: Some(root_hash),
1649            ..
1650        } = attrs
1651        else {
1652            return error!(ENODATA);
1653        };
1654        let mut descriptor = fsverity_descriptor {
1655            version: 1,
1656            hash_algorithm: hash_algorithm.into_primitive(),
1657            log_blocksize,
1658            __reserved_0x04: 0u32,
1659            data_size,
1660            ..Default::default()
1661        };
1662        if salt.len() > std::mem::size_of_val(&descriptor.salt)
1663            || root_hash.len() > std::mem::size_of_val(&descriptor.root_hash)
1664        {
1665            return error!(EIO);
1666        }
1667        descriptor.salt_size = salt.len() as u8;
1668        descriptor.salt[..salt.len()].copy_from_slice(&salt);
1669        descriptor.root_hash[..root_hash.len()].copy_from_slice(&root_hash);
1670        Ok(descriptor)
1671    }
1672
1673    fn get_size(&self, node: &FsNode, current_task: &CurrentTask) -> Result<usize, Errno> {
1674        if self.node.info_state.is_size_accurate() {
1675            node.info()
1676        } else {
1677            node.fetch_and_refresh_info(current_task)?
1678        }
1679        .size
1680        .try_into()
1681        .map_err(|_| errno!(EINVAL))
1682    }
1683}
1684
1685struct RemoteSpecialNode<I> {
1686    node: BaseNode<I>,
1687}
1688
1689impl<I: SyncIo> FsNodeOps for RemoteSpecialNode<I> {
1690    fs_node_impl_not_dir!();
1691    fs_node_impl_xattr_delegate!(self, self.node);
1692
1693    fn create_file_ops(
1694        &self,
1695        _node: &FsNode,
1696        _current_task: &CurrentTask,
1697        _flags: OpenFlags,
1698    ) -> Result<Box<dyn FileOps>, Errno> {
1699        unreachable!("Special nodes cannot be opened.");
1700    }
1701
1702    fn update_attributes(
1703        &self,
1704        _node: &FsNode,
1705        _current_task: &CurrentTask,
1706        info: &FsNodeInfo,
1707        has: zxio_node_attr_has_t,
1708    ) -> Result<(), Errno> {
1709        // Attributes of special remote nodes (sockets, devices, etc.) are valid to update.
1710        // Their metadata is stored and managed by the underlying Fuchsia filesystem.
1711        self.node.update_attributes(info, has)
1712    }
1713}
1714
1715struct RemoteDirectoryObject<D>(D);
1716
1717impl<D> RemoteDirectoryObject<D> {
1718    fn new(dir: D) -> Self {
1719        Self(dir)
1720    }
1721}
1722
1723impl<D: SyncIoDirectory> FileOps for RemoteDirectoryObject<D> {
1724    fileops_impl_directory!();
1725
1726    fn seek(
1727        &self,
1728        _file: &FileObject,
1729        _current_task: &CurrentTask,
1730        current_offset: off_t,
1731        target: SeekTarget,
1732    ) -> Result<off_t, Errno> {
1733        Ok(self
1734            .0
1735            .seek(default_seek(current_offset, target, || error!(EINVAL))? as u64)
1736            .map_err(map_sync_io_client_error)? as i64)
1737    }
1738
1739    fn readdir(
1740        &self,
1741        file: &FileObject,
1742        _current_task: &CurrentTask,
1743        sink: &mut dyn DirentSink,
1744    ) -> Result<(), Errno> {
1745        match self
1746            .0
1747            .readdir(|mut inode_num, entry_type, name| {
1748                if name == b"." {
1749                    inode_num = file.name.entry.node.ino;
1750                } else if name == b".." {
1751                    inode_num = if let Some(parent) = file.name.parent_within_mount() {
1752                        parent.node.ino
1753                    } else {
1754                        // For the root .. should have the same inode number as .
1755                        file.name.entry.node.ino
1756                    };
1757                }
1758                let entry_type = match entry_type {
1759                    fio::DirentType::Directory => DirectoryEntryType::DIR,
1760                    fio::DirentType::File => DirectoryEntryType::REG,
1761                    fio::DirentType::Symlink => DirectoryEntryType::LNK,
1762                    _ => DirectoryEntryType::UNKNOWN,
1763                };
1764                match sink.add(inode_num, sink.offset() + 1, entry_type, name.into()) {
1765                    Ok(()) => ControlFlow::Continue(()),
1766                    Err(e) => ControlFlow::Break(e),
1767                }
1768            })
1769            .map_err(map_sync_io_client_error)?
1770        {
1771            None => Ok(()),
1772            Some(e) => Err(e),
1773        }
1774    }
1775
1776    fn sync(&self, _file: &FileObject, _current_task: &CurrentTask) -> Result<(), Errno> {
1777        self.0.sync().map_err(map_sync_error)
1778    }
1779
1780    fn to_handle(
1781        &self,
1782        file: &FileObject,
1783        current_task: &CurrentTask,
1784    ) -> Result<Option<zx::NullableHandle>, Errno> {
1785        // If expose a handle to a directory to a Fuchsia component, we trust that it will not
1786        // modify the directory in a way that will confuse Starnix.
1787        match self.0.clone_proxy().map_err(map_sync_io_client_error)? {
1788            Some(proxy) => Ok(Some(proxy.into_channel().into())),
1789            None => serve_file_tagged(
1790                current_task,
1791                file,
1792                current_task.current_creds().clone(),
1793                "remote_files",
1794            )
1795            .map(|c| Some(c.0.into_channel().into())),
1796        }
1797    }
1798}
1799
1800fn get_or_init_remote_memory(
1801    file: &FileObject,
1802    read_only_memory: &OnceCell<Arc<MemoryObject>>,
1803    read_exec_memory: &OnceCell<Arc<MemoryObject>>,
1804    prot: ProtectionFlags,
1805    fetch: impl Fn(ProtectionFlags) -> Result<Arc<MemoryObject>, Errno>,
1806) -> Result<Arc<MemoryObject>, Errno> {
1807    fuchsia_trace::duration!(
1808        CATEGORY_STARNIX_MM,
1809        "RemoteFileGetVmo",
1810        "fs" => std::str::from_utf8(file.fs.name()).unwrap_or("<non-utf8>"),
1811        "source" => std::str::from_utf8(file.fs.options.source_for_display()).unwrap_or("<non-utf8>"),
1812        "ino" => file.node().ino,
1813        "prot" => prot.bits(),
1814        "cached" => if prot == ProtectionFlags::READ {
1815            read_only_memory.get().is_some()
1816        } else if prot == (ProtectionFlags::READ | ProtectionFlags::EXEC) {
1817            // The executable handle can be derived locally from a cached read-only handle, so
1818            // either cache being populated means the FIDL round-trip is avoided.
1819            read_exec_memory.get().is_some() || read_only_memory.get().is_some()
1820        } else {
1821            false
1822        },
1823    );
1824    if prot == ProtectionFlags::READ {
1825        read_only_memory.get_or_try_init(|| fetch(ProtectionFlags::READ)).cloned()
1826    } else if prot == (ProtectionFlags::READ | ProtectionFlags::EXEC) {
1827        read_exec_memory
1828            .get_or_try_init(|| {
1829                // If a read-only handle has already been fetched, derive the executable handle
1830                // from it rather than making another GetBackingMemory round-trip. The server is
1831                // not required to grant ZX_RIGHT_DUPLICATE on the returned VMO, so fall back to
1832                // fetching if the handle cannot be duplicated.
1833                if let Some(read_only) = read_only_memory.get()
1834                    && let Ok(exec_mem) = read_only
1835                        .duplicate_handle(zx::Rights::SAME_RIGHTS)
1836                        .and_then(|m| m.replace_as_executable(&VMEX_RESOURCE))
1837                {
1838                    return Ok(Arc::new(exec_mem));
1839                }
1840                fetch(prot)
1841            })
1842            .cloned()
1843    } else {
1844        fetch(prot)
1845    }
1846}
1847
1848struct RemoteFileObject<I> {
1849    was_written: AtomicBool,
1850
1851    _phantom: std::marker::PhantomData<fn() -> I>,
1852}
1853
1854impl<I> Default for RemoteFileObject<I> {
1855    fn default() -> Self {
1856        Self { was_written: AtomicBool::new(false), _phantom: std::marker::PhantomData }
1857    }
1858}
1859
1860impl<I: SyncIo> RemoteFileObject<I> {
1861    /// # Panics
1862    ///
1863    /// This will panic if the node's ops are not `RemoteNode`; `AnonymousRemoteFileObject` should
1864    /// be used if this won't be the case.
1865    fn remote_node(file: &FileObject) -> &RemoteNode<I> {
1866        file.node().downcast_ops::<RemoteNode<I>>().unwrap()
1867    }
1868
1869    fn io(file: &FileObject) -> &I {
1870        &Self::remote_node(file).node.io
1871    }
1872}
1873
1874trait RemoteIoExt {
1875    fn read_to_output_buffer(
1876        &self,
1877        offset: u64,
1878        buffer: &mut dyn OutputBuffer,
1879    ) -> Result<usize, Errno>;
1880    fn write_from_input_buffer(
1881        &self,
1882        offset: u64,
1883        buffer: &mut dyn InputBuffer,
1884    ) -> Result<usize, Errno>;
1885    fn fetch_remote_memory(&self, prot: ProtectionFlags) -> Result<Arc<MemoryObject>, Errno>;
1886}
1887
1888impl<T: SyncIo> RemoteIoExt for T {
1889    fn read_to_output_buffer(
1890        &self,
1891        offset: u64,
1892        buffer: &mut dyn OutputBuffer,
1893    ) -> Result<usize, Errno> {
1894        if self.supports_vectored()
1895            && let Some(actual) = with_iovec_segments(buffer, |iovecs| {
1896                // SAFETY: The iovecs are known to point to userspace, so any damage we do here is
1897                // limited to userspace.  Zircon will catch faults and return an error.
1898                unsafe { self.readv(offset, iovecs).map_err(map_stream_error) }
1899            })
1900        {
1901            let actual = actual?;
1902            // SAFETY: we successfully read `actual` bytes directly to the user's buffer
1903            // segments.
1904            unsafe { buffer.advance(actual) }?;
1905            Ok(actual)
1906        } else {
1907            self.read(
1908                offset,
1909                buffer.available(),
1910                |data| buffer.write(&data),
1911                map_sync_io_client_error,
1912            )
1913        }
1914    }
1915
1916    fn write_from_input_buffer(
1917        &self,
1918        offset: u64,
1919        buffer: &mut dyn InputBuffer,
1920    ) -> Result<usize, Errno> {
1921        let actual = if self.supports_vectored()
1922            && let Some(actual) = with_iovec_segments(buffer, |iovecs| {
1923                self.writev(offset, iovecs).map_err(map_stream_error)
1924            }) {
1925            actual?
1926        } else {
1927            self.write(offset as u64, &buffer.peek_all()?).map_err(map_sync_io_client_error)?
1928        };
1929        buffer.advance(actual)?;
1930        Ok(actual)
1931    }
1932
1933    fn fetch_remote_memory(&self, prot: ProtectionFlags) -> Result<Arc<MemoryObject>, Errno> {
1934        let without_exec = self
1935            .vmo_get(prot.to_vmar_flags() - zx::VmarFlags::PERM_EXECUTE)
1936            .map_err(|status| from_status_like_fdio!(status))?;
1937        let all_flags = if prot.contains(ProtectionFlags::EXEC) {
1938            without_exec.replace_as_executable(&VMEX_RESOURCE).map_err(impossible_error)?
1939        } else {
1940            without_exec
1941        };
1942        Ok(Arc::new(MemoryObject::from(all_flags)))
1943    }
1944}
1945
1946impl<I: SyncIo> FileOps for RemoteFileObject<I> {
1947    fileops_impl_seekable!();
1948
1949    fn flush(&self, file: &FileObject, _current_task: &CurrentTask) {
1950        if self.was_written.swap(false, Ordering::Relaxed)
1951            && let Some(node) = file.node().downcast_ops::<RemoteNode<RemoteIo>>()
1952            && let Ok(proxy) = node.node.io.clone_proxy()
1953        {
1954            let _ = proxy.close(zx::MonotonicInstant::INFINITE);
1955        }
1956    }
1957
1958    fn read(
1959        &self,
1960        file: &FileObject,
1961        _current_task: &CurrentTask,
1962        offset: usize,
1963        data: &mut dyn OutputBuffer,
1964    ) -> Result<usize, Errno> {
1965        Self::io(file).read_to_output_buffer(offset as u64, data)
1966    }
1967
1968    fn write(
1969        &self,
1970        file: &FileObject,
1971        _current_task: &CurrentTask,
1972        offset: usize,
1973        data: &mut dyn InputBuffer,
1974    ) -> Result<usize, Errno> {
1975        will_dirty::<I, _, _>(&[&***file.node()], || {
1976            let written = Self::io(file).write_from_input_buffer(offset as u64, data)?;
1977
1978            // If we increased the file size, we need to update that here so that `NodeInfo::size`
1979            // is accurate.  This is done so that we can optimize `get_size`.  If the file has been
1980            // truncated, then the size might not be accurate, but we track that separately and
1981            // `get_size` will fetch the file size from the remote end in that case.
1982            if written > 0 {
1983                self.was_written.store(true, Ordering::Relaxed);
1984                file.node().update_info(|info| {
1985                    if offset + written > info.size {
1986                        info.size = offset + written;
1987                    }
1988                });
1989            }
1990
1991            Ok(written)
1992        })
1993    }
1994
1995    fn get_memory(
1996        &self,
1997        file: &FileObject,
1998        _current_task: &CurrentTask,
1999        _length: Option<usize>,
2000        prot: ProtectionFlags,
2001    ) -> Result<Arc<MemoryObject>, Errno> {
2002        Self::remote_node(file).get_memory(file, prot)
2003    }
2004
2005    fn to_handle(
2006        &self,
2007        file: &FileObject,
2008        current_task: &CurrentTask,
2009    ) -> Result<Option<zx::NullableHandle>, Errno> {
2010        // To avoid cache coherency and security issues, we proxy remote files via the Starnix file
2011        // server.  This will incur a performance penalty which we can optimize later if we need to.
2012        serve_file_tagged(current_task, file, current_task.current_creds().clone(), "remote_files")
2013            .map(|c| Some(c.0.into_channel().into()))
2014    }
2015}
2016
2017/// A file object that is not attached to a `RemoteFs`, which means it stores its own `RemoteIo`.
2018pub struct AnonymousRemoteFileObject {
2019    io: RemoteIo,
2020
2021    /// Cached read-only VMO handle.
2022    read_only_memory: OnceCell<Arc<MemoryObject>>,
2023
2024    /// Cached read/exec VMO handle.
2025    read_exec_memory: OnceCell<Arc<MemoryObject>>,
2026}
2027
2028impl AnonymousRemoteFileObject {
2029    fn new(io: RemoteIo) -> Self {
2030        Self { io, read_only_memory: Default::default(), read_exec_memory: Default::default() }
2031    }
2032}
2033
2034impl FileOps for AnonymousRemoteFileObject {
2035    fileops_impl_seekable!();
2036
2037    fn read(
2038        &self,
2039        _file: &FileObject,
2040        _current_task: &CurrentTask,
2041        offset: usize,
2042        data: &mut dyn OutputBuffer,
2043    ) -> Result<usize, Errno> {
2044        self.io.read_to_output_buffer(offset as u64, data)
2045    }
2046
2047    fn write(
2048        &self,
2049        _file: &FileObject,
2050        _current_task: &CurrentTask,
2051        offset: usize,
2052        data: &mut dyn InputBuffer,
2053    ) -> Result<usize, Errno> {
2054        // As this is an anonymous file, there's no point marking the node info dirty because this
2055        // isn't backed by `RemoteNode` or `RemoteSymlink`.
2056        self.io.write_from_input_buffer(offset as u64, data)
2057    }
2058
2059    fn get_memory(
2060        &self,
2061        file: &FileObject,
2062        _current_task: &CurrentTask,
2063        _length: Option<usize>,
2064        prot: ProtectionFlags,
2065    ) -> Result<Arc<MemoryObject>, Errno> {
2066        get_or_init_remote_memory(file, &self.read_only_memory, &self.read_exec_memory, prot, |p| {
2067            self.io.fetch_remote_memory(p)
2068        })
2069    }
2070
2071    fn to_handle(
2072        &self,
2073        _file: &FileObject,
2074        _current_task: &CurrentTask,
2075    ) -> Result<Option<zx::NullableHandle>, Errno> {
2076        // This is an anonymous file (not backed by `RemoteNode`).  Any external updates to the
2077        // file's attributes will not be tracked by Starnix.
2078        self.io
2079            .clone_proxy()
2080            .map_err(map_sync_io_client_error)
2081            .map(|p| Some(p.into_channel().into()))
2082    }
2083
2084    fn sync(&self, _file: &FileObject, _current_task: &CurrentTask) -> Result<(), Errno> {
2085        self.io.sync().map_err(map_sync_io_client_error)
2086    }
2087}
2088
2089pub struct RemoteZxioFileObject {
2090    /// The underlying Zircon I/O object.  This is shared, so we must take care not to use any
2091    /// stateful methods on the underlying object (reading and writing is fine).
2092    zxio: Zxio,
2093
2094    /// Cached read-only VMO handle.
2095    read_only_memory: OnceCell<Arc<MemoryObject>>,
2096
2097    /// Cached read/exec VMO handle.
2098    read_exec_memory: OnceCell<Arc<MemoryObject>>,
2099}
2100
2101impl RemoteZxioFileObject {
2102    fn new(zxio: Zxio) -> RemoteZxioFileObject {
2103        RemoteZxioFileObject {
2104            zxio,
2105            read_only_memory: Default::default(),
2106            read_exec_memory: Default::default(),
2107        }
2108    }
2109
2110    fn fetch_remote_memory(&self, prot: ProtectionFlags) -> Result<Arc<MemoryObject>, Errno> {
2111        let without_exec = self
2112            .zxio
2113            .vmo_get(prot.to_vmar_flags() - zx::VmarFlags::PERM_EXECUTE)
2114            .map_err(|status| from_status_like_fdio!(status))?;
2115        let all_flags = if prot.contains(ProtectionFlags::EXEC) {
2116            without_exec.replace_as_executable(&VMEX_RESOURCE).map_err(impossible_error)?
2117        } else {
2118            without_exec
2119        };
2120        Ok(Arc::new(MemoryObject::from(all_flags)))
2121    }
2122}
2123
2124impl FileOps for RemoteZxioFileObject {
2125    fileops_impl_seekable!();
2126
2127    fn read(
2128        &self,
2129        _file: &FileObject,
2130        _current_task: &CurrentTask,
2131        offset: usize,
2132        data: &mut dyn OutputBuffer,
2133    ) -> Result<usize, Errno> {
2134        let offset = offset as u64;
2135        let read_bytes = with_iovec_segments::<_, syncio::zxio::zx_iovec, _>(data, |iovecs| {
2136            // SAFETY: The iovecs are valid for writing because they come from OutputBuffer.
2137            unsafe { self.zxio.readv_at(offset, iovecs).map_err(map_stream_error) }
2138        });
2139
2140        match read_bytes {
2141            Some(actual) => {
2142                let actual = actual?;
2143                // SAFETY: we successfully read `actual` bytes
2144                // directly to the user's buffer segments.
2145                unsafe { data.advance(actual) }?;
2146                Ok(actual)
2147            }
2148            None => {
2149                // Perform the (slower) operation by using an intermediate buffer.
2150                let total = data.available();
2151                let mut bytes = vec![0u8; total];
2152                let actual = self
2153                    .zxio
2154                    .read_at(offset, &mut bytes)
2155                    .map_err(|status| from_status_like_fdio!(status))?;
2156                data.write_all(&bytes[0..actual])
2157            }
2158        }
2159    }
2160
2161    fn write(
2162        &self,
2163        _file: &FileObject,
2164        _current_task: &CurrentTask,
2165        offset: usize,
2166        data: &mut dyn InputBuffer,
2167    ) -> Result<usize, Errno> {
2168        let offset = offset as u64;
2169        let write_bytes = with_iovec_segments::<_, syncio::zxio::zx_iovec, _>(data, |iovecs| {
2170            // SAFETY: The iovecs are valid for reading because they come from InputBuffer.
2171            unsafe { self.zxio.writev_at(offset, iovecs).map_err(map_stream_error) }
2172        });
2173
2174        match write_bytes {
2175            Some(actual) => {
2176                let actual = actual?;
2177                data.advance(actual)?;
2178                Ok(actual)
2179            }
2180            None => {
2181                // Perform the (slower) operation by using an intermediate buffer.
2182                let bytes = data.peek_all()?;
2183                let actual = self
2184                    .zxio
2185                    .write_at(offset, &bytes)
2186                    .map_err(|status| from_status_like_fdio!(status))?;
2187                data.advance(actual)?;
2188                Ok(actual)
2189            }
2190        }
2191    }
2192
2193    fn get_memory(
2194        &self,
2195        file: &FileObject,
2196        _current_task: &CurrentTask,
2197        _length: Option<usize>,
2198        prot: ProtectionFlags,
2199    ) -> Result<Arc<MemoryObject>, Errno> {
2200        get_or_init_remote_memory(file, &self.read_only_memory, &self.read_exec_memory, prot, |p| {
2201            self.fetch_remote_memory(p)
2202        })
2203    }
2204
2205    fn to_handle(
2206        &self,
2207        _file: &FileObject,
2208        _current_task: &CurrentTask,
2209    ) -> Result<Option<zx::NullableHandle>, Errno> {
2210        self.zxio.clone_handle().map(Some).map_err(|status| from_status_like_fdio!(status))
2211    }
2212
2213    fn sync(&self, _file: &FileObject, _current_task: &CurrentTask) -> Result<(), Errno> {
2214        self.zxio.sync().map_err(map_sync_error)
2215    }
2216}
2217
2218/// Returns true if `file` is a `RemoteFileObject`.
2219pub fn is_remote_file(file: &FileObject) -> bool {
2220    file.downcast_file::<RemoteFileObject<RemoteIo>>().is_some()
2221}
2222
2223/// [`FileOps`] implementation for Fuchsia stream/datagram pipes backed by [`Zxio`].
2224struct RemotePipeObject {
2225    zxio: Zxio,
2226}
2227
2228impl RemotePipeObject {
2229    fn new(zxio: Zxio) -> Self {
2230        Self { zxio }
2231    }
2232}
2233
2234impl FileOps for RemotePipeObject {
2235    fileops_impl_nonseekable!();
2236    fileops_impl_noop_sync!();
2237
2238    fn read(
2239        &self,
2240        file: &FileObject,
2241        current_task: &CurrentTask,
2242        offset: usize,
2243        data: &mut dyn OutputBuffer,
2244    ) -> Result<usize, Errno> {
2245        debug_assert!(offset == 0);
2246        if data.available() == 0 {
2247            return Ok(0);
2248        }
2249        file.blocking_op(current_task, FdEvents::POLLIN | FdEvents::POLLHUP, None, || {
2250            let read_bytes = with_iovec_segments(data, |iovecs| {
2251                // SAFETY: The `iovecs` are valid for writing because they come from `OutputBuffer`.
2252                match unsafe { self.zxio.readv(iovecs) } {
2253                    Ok(actual) => Ok(actual),
2254                    Err(zx::Status::PEER_CLOSED | zx::Status::BAD_STATE) => Ok(0),
2255                    Err(status) => Err(map_stream_error(status)),
2256                }
2257            });
2258            match read_bytes {
2259                Some(actual) => {
2260                    let actual = actual?;
2261                    // SAFETY: We successfully read `actual` bytes directly to the buffer segments.
2262                    unsafe { data.advance(actual) }?;
2263                    Ok(actual)
2264                }
2265                None => {
2266                    // Perform the (slower) operation by using an intermediate buffer.
2267                    let total = data.available();
2268                    let mut bytes = vec![0u8; total];
2269                    let actual = match self.zxio.read(&mut bytes) {
2270                        Ok(actual) => actual,
2271                        Err(zx::Status::PEER_CLOSED | zx::Status::BAD_STATE) => return Ok(0),
2272                        Err(status) => return Err(from_status_like_fdio!(status)),
2273                    };
2274                    data.write_all(&bytes[0..actual])
2275                }
2276            }
2277        })
2278    }
2279
2280    fn write(
2281        &self,
2282        file: &FileObject,
2283        current_task: &CurrentTask,
2284        offset: usize,
2285        data: &mut dyn InputBuffer,
2286    ) -> Result<usize, Errno> {
2287        debug_assert!(offset == 0);
2288        file.blocking_op(current_task, FdEvents::POLLOUT | FdEvents::POLLHUP, None, || {
2289            let actual = match with_iovec_segments(data, |iovecs| {
2290                if iovecs.is_empty() {
2291                    return self.zxio.write(&[]).map_err(|status| from_status_like_fdio!(status));
2292                }
2293                // SAFETY: The `iovecs` are valid for reading because they come from `InputBuffer`.
2294                unsafe { self.zxio.writev(iovecs).map_err(map_stream_error) }
2295            }) {
2296                Some(actual) => actual?,
2297                None => {
2298                    // Perform the (slower) operation by using an intermediate buffer.
2299                    let bytes = data.peek_all()?;
2300                    self.zxio.write(&bytes).map_err(|status| from_status_like_fdio!(status))?
2301                }
2302            };
2303            data.advance(actual)?;
2304            Ok(actual)
2305        })
2306    }
2307
2308    fn wait_async(
2309        &self,
2310        _file: &FileObject,
2311        _current_task: &CurrentTask,
2312        waiter: &Waiter,
2313        events: FdEvents,
2314        handler: EventHandler,
2315    ) -> Option<WaitCanceler> {
2316        Some(zxio_wait_async(&self.zxio, waiter, events, handler))
2317    }
2318
2319    fn query_events(
2320        &self,
2321        _file: &FileObject,
2322        _current_task: &CurrentTask,
2323    ) -> Result<FdEvents, Errno> {
2324        zxio_query_events(&self.zxio)
2325    }
2326
2327    fn to_handle(
2328        &self,
2329        _file: &FileObject,
2330        _current_task: &CurrentTask,
2331    ) -> Result<Option<zx::NullableHandle>, Errno> {
2332        self.zxio
2333            .deep_clone()
2334            .and_then(Zxio::release)
2335            .map(Some)
2336            .map_err(|status| from_status_like_fdio!(status))
2337    }
2338}
2339
2340struct RemoteSymlink<I> {
2341    node: BaseNode<I>,
2342    target: LockDepRwLock<Box<[u8]>, FuchsiaRemoteTargetLock>,
2343}
2344
2345impl<I> RemoteSymlink<I> {
2346    fn new(node: BaseNode<I>, target: impl Into<Box<[u8]>>) -> Self {
2347        Self { node, target: LockDepRwLock::new(target.into()) }
2348    }
2349}
2350
2351impl<I: SyncIo> FsNodeOps for RemoteSymlink<I> {
2352    fs_node_impl_symlink!();
2353    fs_node_impl_xattr_delegate!(self, self.node);
2354
2355    fn readlink(
2356        &self,
2357        _node: &FsNode,
2358        _current_task: &CurrentTask,
2359    ) -> Result<SymlinkTarget, Errno> {
2360        Ok(SymlinkTarget::Path(FsString::new(self.target.read().to_vec())))
2361    }
2362
2363    fn fetch_and_refresh_info<'a>(
2364        &self,
2365        _node: &FsNode,
2366        _current_task: &CurrentTask,
2367        info: &'a DynamicLockDepRwLock<FsNodeInfo>,
2368        flags: StatxFlags,
2369    ) -> Result<LockDepReadGuard<'a, FsNodeInfo>, Errno> {
2370        if flags.contains(StatxFlags::AT_STATX_DONT_SYNC) {
2371            return Ok(info.read());
2372        }
2373        self.node.fetch_and_refresh_info(info)
2374    }
2375
2376    fn forget(self: Box<Self>, _current_task: &CurrentTask, info: FsNodeInfo) -> Result<(), Errno> {
2377        // Before forgetting this node, update atime if we need to.
2378        if info.pending_time_access_update {
2379            self.node
2380                .io
2381                .attr_get(fio::NodeAttributesQuery::PENDING_ACCESS_TIME_UPDATE)
2382                .map_err(|status| from_status_like_fdio!(status))?;
2383        }
2384        Ok(())
2385    }
2386}
2387
2388pub struct RemoteCounter {
2389    counter: Counter,
2390    koid: std::sync::OnceLock<zx::Koid>,
2391}
2392
2393impl RemoteCounter {
2394    fn new(counter: Counter) -> Self {
2395        Self { counter, koid: std::sync::OnceLock::new() }
2396    }
2397
2398    pub fn duplicate_handle(&self) -> Result<Counter, Errno> {
2399        self.counter.duplicate_handle(zx::Rights::SAME_RIGHTS).map_err(impossible_error)
2400    }
2401
2402    pub fn koid(&self) -> zx::Koid {
2403        *self.koid.get_or_init(|| self.counter.koid().unwrap())
2404    }
2405}
2406
2407impl FileOps for RemoteCounter {
2408    fileops_impl_nonseekable!();
2409    fileops_impl_noop_sync!();
2410
2411    fn read(
2412        &self,
2413        _file: &FileObject,
2414        _current_task: &CurrentTask,
2415        _offset: usize,
2416        _data: &mut dyn OutputBuffer,
2417    ) -> Result<usize, Errno> {
2418        error!(ENOTSUP)
2419    }
2420
2421    fn write(
2422        &self,
2423        _file: &FileObject,
2424        _current_task: &CurrentTask,
2425        _offset: usize,
2426        _data: &mut dyn InputBuffer,
2427    ) -> Result<usize, Errno> {
2428        error!(ENOTSUP)
2429    }
2430
2431    fn ioctl(
2432        &self,
2433        file: &FileObject,
2434        current_task: &CurrentTask,
2435        request: u32,
2436        arg: SyscallArg,
2437    ) -> Result<SyscallResult, Errno> {
2438        let ioctl_type = (request >> 8) as u8;
2439        let ioctl_number = request as u8;
2440        if ioctl_type == SYNC_IOC_MAGIC
2441            && (ioctl_number == SYNC_IOC_FILE_INFO || ioctl_number == SYNC_IOC_MERGE)
2442        {
2443            let mut sync_points = Vec::with_capacity(1);
2444            let counter = self.duplicate_handle()?;
2445            // For other calls than SYNC_IOC_MERGE, the koid is never used, so we construct it
2446            // without fetching it, saving a Zircon syscall.
2447            let sp = if ioctl_number == SYNC_IOC_MERGE {
2448                SyncPoint::with_koid(Timeline::Hwc, counter.into(), self.koid())
2449            } else {
2450                SyncPoint::new(Timeline::Hwc, counter.into())
2451            };
2452            sync_points.push(sp);
2453            let sync_file_name: &[u8; 32] = b"remote counter\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
2454            let sync_file = SyncFile::new(*sync_file_name, SyncFence { sync_points });
2455            return sync_file.ioctl(file, current_task, request, arg);
2456        }
2457
2458        error!(EINVAL)
2459    }
2460}
2461
2462#[track_caller]
2463fn map_sync_error(status: zx::Status) -> Errno {
2464    match status {
2465        zx::Status::NO_RESOURCES | zx::Status::NO_MEMORY | zx::Status::NO_SPACE => {
2466            errno!(ENOSPC)
2467        }
2468        zx::Status::INVALID_ARGS | zx::Status::NOT_FILE => errno!(EINVAL),
2469        zx::Status::BAD_HANDLE => errno!(EBADFD),
2470        zx::Status::NOT_SUPPORTED => errno!(ENOTSUP),
2471        zx::Status::INTERRUPTED_RETRY => errno!(EINTR),
2472        _ => errno!(EIO),
2473    }
2474}
2475
2476#[track_caller]
2477fn map_stream_error(status: zx::Status) -> Errno {
2478    match status {
2479        // zx::Stream may return invalid args or not found error because of invalid zx_iovec buffer
2480        // pointers.
2481        zx::Status::INVALID_ARGS | zx::Status::NOT_FOUND => errno!(EFAULT),
2482        status => from_status_like_fdio!(status),
2483    }
2484}
2485
2486#[track_caller]
2487fn map_sync_io_client_error(status: zx::Status) -> Errno {
2488    from_status_like_fdio!(status)
2489}
2490
2491/// Used to keep track of whether node info is in sync or dirty so that we can avoid communicating
2492/// exernally if we think the node information is in sync.
2493// The two top bits are special (see below).  The remaining bits are a count of the number of
2494// in-flight dirty operations.
2495struct InfoState(AtomicU32);
2496
2497impl InfoState {
2498    /// When this bit is set and the PENDING_REFRESH bit is *not* set, the node information is in
2499    /// sync with the external node.
2500    const IN_SYNC: u32 = 0x8000_0000;
2501
2502    /// When this bit is set in `info_state`, it means the node information is currently being
2503    /// refreshed.
2504    const PENDING_REFRESH: u32 = 0x4000_0000;
2505
2506    /// When this bit is set, it means the node has been truncated and so the size might not be
2507    /// accurate.
2508    const TRUNCATED: u32 = 0x2000_0000;
2509
2510    /// The remaining bits are used to track a count of the number of in-flight dirty operations.
2511    const COUNT_MASK: u32 = Self::TRUNCATED - 1;
2512
2513    fn new(dirty: bool) -> Self {
2514        Self(AtomicU32::new(if dirty { 0 } else { Self::IN_SYNC }))
2515    }
2516
2517    /// This guard should be taken whilst an operation that might result in dirty node information
2518    /// is in flight.  If `for_truncate` is true, this will also set the `TRUNCATED` bit.
2519    fn dirty_op_guard(&self, for_truncate: bool) -> DirtyOpGuard<'_> {
2520        // Increment the count indicating a dirty operation is in flight and also clear the
2521        // `IN_SYNC` bit to indicate the node information will need refreshing from its external
2522        // source.
2523        let mut current = self.0.load(Ordering::Relaxed);
2524        let for_truncate = if for_truncate { Self::TRUNCATED } else { 0 };
2525        loop {
2526            assert!(current & Self::COUNT_MASK != Self::COUNT_MASK); // Check overflow
2527            match self.0.compare_exchange_weak(
2528                current,
2529                ((current & !Self::IN_SYNC) + 1) | for_truncate,
2530                Ordering::Relaxed,
2531                Ordering::Relaxed,
2532            ) {
2533                Ok(_) => break,
2534                Err(old) => current = old,
2535            }
2536        }
2537        DirtyOpGuard(self)
2538    }
2539
2540    /// Calls `refresh` if node information needs to be refreshed, or `not_needed` if node
2541    /// information does not need refreshing.
2542    fn maybe_refresh<'a, T: 'a>(
2543        &self,
2544        info: &'a DynamicLockDepRwLock<FsNodeInfo>,
2545        refresh: impl FnOnce(&'a DynamicLockDepRwLock<FsNodeInfo>) -> Result<T, Errno>,
2546        not_needed: impl FnOnce(&'a DynamicLockDepRwLock<FsNodeInfo>) -> Result<T, Errno>,
2547    ) -> Result<T, Errno> {
2548        let mut current = self.0.load(Ordering::Relaxed);
2549
2550        // If node information is dirty, and there are no pending dirty operations, and there is no
2551        // other thread currently refreshing node information, we can set the bits indicating that a
2552        // refresh is pending.  We want to set the `IN_SYNC` bit here in case `will_dirty` runs
2553        // before we're done.
2554        //
2555        // NOTE: Multiple threads can be refreshing at the same time, but only one of them will
2556        // succeed in setting the `PENDING_REFRESH` bit.
2557        let mut did_set_pending_refresh = false;
2558        while current & !Self::TRUNCATED == 0 {
2559            match self.0.compare_exchange_weak(
2560                current,
2561                current | Self::IN_SYNC | Self::PENDING_REFRESH,
2562                Ordering::Relaxed,
2563                Ordering::Relaxed,
2564            ) {
2565                Ok(_) => {
2566                    did_set_pending_refresh = true;
2567                    break;
2568                }
2569                Err(old) => current = old,
2570            }
2571        }
2572
2573        // Skip the update if the cached information is in sync and there are no pending dirty
2574        // operations.  If there's a pending atime update, we'll skip updating that now; it
2575        // shouldn't be necessary and we can do it later.
2576        if current == Self::IN_SYNC {
2577            return not_needed(info);
2578        }
2579
2580        let result = refresh(info);
2581
2582        if did_set_pending_refresh {
2583            if result.is_ok() {
2584                // If the TRUNCATED bit was set, we can clear it now so long as no other dirty
2585                // operations took place.
2586                if current & Self::TRUNCATED != 0 {
2587                    // Assuming no other thread has changed the state, this is what we
2588                    // expect the current value to be.
2589                    let mut current = Self::TRUNCATED | Self::IN_SYNC | Self::PENDING_REFRESH;
2590                    while current == Self::TRUNCATED | Self::IN_SYNC | Self::PENDING_REFRESH {
2591                        match self.0.compare_exchange_weak(
2592                            current,
2593                            Self::IN_SYNC,
2594                            Ordering::Relaxed,
2595                            Ordering::Relaxed,
2596                        ) {
2597                            Ok(_) => return result,
2598                            Err(old) => current = old,
2599                        }
2600                    }
2601                    // In this case, we fall through and just clear the PENDING_REFRESH bit, but we
2602                    // leave the TRUNCATED bit untouched.
2603                }
2604                self.0.fetch_and(!Self::PENDING_REFRESH, Ordering::Relaxed);
2605            } else {
2606                // If there was an error, we should also clear the IN_SYNC bit to indicate the node
2607                // information is still dirty.
2608                self.0.fetch_and(!(Self::IN_SYNC | Self::PENDING_REFRESH), Ordering::Relaxed);
2609            }
2610        }
2611
2612        result
2613    }
2614
2615    /// Returns true if the size is accurate.
2616    fn is_size_accurate(&self) -> bool {
2617        // The size returned by `get_size` is accurate so long as the file hasn't been truncated.
2618        // If there are writes currently outstanding, then it's also not safe to return the current
2619        // size.  To understand why, consider the following scenario:
2620        //
2621        //    1. Thread A issues a write.
2622        //    2. Thread B performs a read which sees the write from thread A.
2623        //    3. Thread B now tries to seek to the end of the file.  It should be consistent with
2624        //       the read in #2.
2625        //
2626        // #3 needs to see the end-of-file as it is after the write, but it's possible that thread A
2627        // hasn't updated the size yet even though the write has been completed at the remote end.
2628        // For that reason, whilst there are potential writes outstanding, we must ask the remote
2629        // end for the size.
2630        let state = self.0.load(Ordering::Relaxed);
2631        state & (Self::TRUNCATED | Self::COUNT_MASK) == 0
2632    }
2633}
2634
2635struct DirtyOpGuard<'a>(&'a InfoState);
2636
2637impl Drop for DirtyOpGuard<'_> {
2638    fn drop(&mut self) {
2639        // Decrement the count we took when we created the guard.
2640        self.0.0.fetch_sub(1, Ordering::Relaxed);
2641    }
2642}
2643
2644/// A wrapper to be used around calls that will end up making node info dirty.
2645fn will_dirty<'a, I: SyncIo, N: TryInto<&'a BaseNode<I>> + Copy, T>(
2646    nodes: &[N],
2647    f: impl FnOnce() -> T,
2648) -> T {
2649    // We are about to execute an operation that will make the cached information for one or more
2650    // nodes out of date, and we must deal with races.  If we mark the node as dirty first, another
2651    // thread could sneak in and refresh the node information before this operation has finished,
2652    // and then the information would be out of date.  If we only mark the node as dirty afterwards,
2653    // there is a window between when the operation completes and when we mark the node as dirty
2654    // where another thread could observe the changes caused by this operation, but still see old
2655    // node information.  So, the approach we take is to mark the node as dirty before the operation
2656    // starts, but indicate that this operation is ongoing.  Any threads that try and retrieve node
2657    // information will fetch fresh information, but, importantly, they'll leave the node marked as
2658    // dirty.  Once this operation has finished, we'll indicate this operation is no longer
2659    // in-flight, and then the next time information is refreshed, we'll mark the node information
2660    // as being in sync.
2661
2662    let _guards: SmallVec<[_; 4]> = nodes
2663        .iter()
2664        .filter_map(|n| N::try_into(*n).ok())
2665        .map(|n| n.info_state.dirty_op_guard(false))
2666        .collect();
2667
2668    f()
2669}
2670
2671#[cfg(test)]
2672mod test {
2673    use super::*;
2674    use crate::mm::PAGE_SIZE;
2675    use crate::task::dynamic_thread_spawner::SpawnRequestBuilder;
2676    use crate::testing::*;
2677    use crate::vfs::buffers::{VecInputBuffer, VecOutputBuffer};
2678    use crate::vfs::socket::{SocketFile, SocketMessageFlags};
2679    use crate::vfs::{EpollFileObject, LookupContext, Namespace, SymlinkMode, TimeUpdateType};
2680    use assert_matches::assert_matches;
2681    use fidl::endpoints::{ServerEnd, create_request_stream};
2682    use fidl_fuchsia_io as fio;
2683    use flyweights::FlyByteStr;
2684    use fuchsia_async as fasync;
2685    use fuchsia_runtime::UtcDuration;
2686    use futures::{FutureExt, StreamExt};
2687    use fxfs_testing::{TestFixture, TestFixtureOptions};
2688    use starnix_sync::{FsNodeInfoLevel, Mutex};
2689    use starnix_uapi::auth::Credentials;
2690    use starnix_uapi::errors::EINVAL;
2691    use starnix_uapi::file_mode::mode;
2692    use starnix_uapi::ino_t;
2693    use starnix_uapi::mount_flags::MountpointFlags;
2694    use starnix_uapi::open_flags::OpenFlags;
2695    use starnix_uapi::vfs::{EpollEvent, FdEvents};
2696    use std::collections::BTreeMap;
2697    use std::sync::Barrier;
2698    use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
2699    use storage_device::DeviceHolder;
2700    use storage_device::fake_device::FakeDevice;
2701
2702    #[::fuchsia::test]
2703    async fn test_remote_uds() {
2704        spawn_kernel_and_run(async |current_task| {
2705            let (s1, s2) = zx::Socket::create_datagram();
2706            s2.write(&vec![0]).expect("write");
2707            let file = new_remote_file(&current_task, s1.into(), OpenFlags::RDWR)
2708                .expect("new_remote_file");
2709            assert!(file.node().is_sock());
2710            let socket_ops = file.downcast_file::<SocketFile>().unwrap();
2711            let flags = SocketMessageFlags::CTRUNC
2712                | SocketMessageFlags::TRUNC
2713                | SocketMessageFlags::NOSIGNAL
2714                | SocketMessageFlags::CMSG_CLOEXEC;
2715            let mut buffer = VecOutputBuffer::new(1024);
2716            let info = socket_ops
2717                .recvmsg(&current_task, &file, &mut buffer, flags, None)
2718                .expect("recvmsg");
2719            assert!(info.ancillary_data.is_empty());
2720            assert_eq!(info.message_length, 1);
2721        })
2722        .await;
2723    }
2724
2725    #[::fuchsia::test]
2726    async fn test_tree() {
2727        spawn_kernel_and_run(async |current_task| {
2728            let kernel = current_task.kernel();
2729            let rights = fio::PERM_READABLE | fio::PERM_EXECUTABLE;
2730            let (server, client) = zx::Channel::create();
2731            fdio::open("/pkg", rights, server).expect("failed to open /pkg");
2732            let fs = RemoteFs::new_fs(
2733                &kernel,
2734                client,
2735                FileSystemOptions { source: FlyByteStr::new(b"/pkg"), ..Default::default() },
2736                rights,
2737            )
2738            .unwrap();
2739            let ns = Namespace::new(fs);
2740            let root = ns.root();
2741            let mut context = LookupContext::default();
2742            assert_eq!(
2743                root.lookup_child(&current_task, &mut context, "nib".into()).err(),
2744                Some(errno!(ENOENT))
2745            );
2746            let mut context = LookupContext::default();
2747            root.lookup_child(&current_task, &mut context, "lib".into()).unwrap();
2748
2749            let mut context = LookupContext::default();
2750            let _test_file = root
2751                .lookup_child(&current_task, &mut context, "data/tests/hello_starnix".into())
2752                .unwrap()
2753                .open(&current_task, OpenFlags::RDONLY)
2754                .unwrap();
2755        })
2756        .await;
2757    }
2758
2759    #[::fuchsia::test]
2760    async fn test_blocking_io() {
2761        spawn_kernel_and_run(async |current_task| {
2762            let (client, server) = zx::Socket::create_stream();
2763            let pipe = create_fuchsia_pipe(&current_task, client, OpenFlags::RDWR).unwrap();
2764            assert!(pipe.node().is_fifo());
2765
2766            let bytes = [0u8; 64];
2767            assert_eq!(bytes.len(), server.write(&bytes).unwrap());
2768
2769            // Spawn a kthread to get the right lock context.
2770            let bytes_read = pipe.read(&current_task, &mut VecOutputBuffer::new(64)).unwrap();
2771
2772            assert_eq!(bytes_read, bytes.len());
2773            assert_eq!(pipe.read(&current_task, &mut VecOutputBuffer::new(0)).unwrap(), 0);
2774
2775            assert_eq!(
2776                pipe.write(&current_task, &mut VecInputBuffer::new(&bytes)).unwrap(),
2777                bytes.len()
2778            );
2779            let mut server_buf = [0u8; 64];
2780            assert_eq!(server.read(&mut server_buf).unwrap(), bytes.len());
2781
2782            std::mem::drop(server);
2783            assert_eq!(pipe.read(&current_task, &mut VecOutputBuffer::new(64)).unwrap(), 0);
2784        })
2785        .await;
2786    }
2787
2788    #[::fuchsia::test]
2789    async fn test_poll() {
2790        spawn_kernel_and_run(async |current_task| {
2791            let (client, server) = zx::Socket::create_stream();
2792            let pipe = create_fuchsia_pipe(&current_task, client, OpenFlags::RDWR)
2793                .expect("create_fuchsia_pipe");
2794            let server_zxio = Zxio::create(server.into_handle()).expect("Zxio::create");
2795
2796            assert_eq!(
2797                pipe.query_events(&current_task),
2798                Ok(FdEvents::POLLOUT | FdEvents::POLLWRNORM)
2799            );
2800
2801            let epoll_object = EpollFileObject::new_file(&current_task);
2802            let epoll_file = epoll_object.downcast_file::<EpollFileObject>().unwrap();
2803            let event = EpollEvent::new(FdEvents::POLLIN, 0);
2804            epoll_file.add(&current_task, &pipe, &epoll_object, event).expect("poll_file.add");
2805
2806            let fds = epoll_file.wait(&current_task, 1, zx::MonotonicInstant::ZERO).expect("wait");
2807            assert!(fds.is_empty());
2808
2809            assert_eq!(server_zxio.write(&[0]).expect("write"), 1);
2810
2811            assert_eq!(
2812                pipe.query_events(&current_task),
2813                Ok(FdEvents::POLLOUT
2814                    | FdEvents::POLLWRNORM
2815                    | FdEvents::POLLIN
2816                    | FdEvents::POLLRDNORM)
2817            );
2818            let fds = epoll_file.wait(&current_task, 1, zx::MonotonicInstant::ZERO).expect("wait");
2819            assert_eq!(fds.len(), 1);
2820
2821            assert_eq!(pipe.read(&current_task, &mut VecOutputBuffer::new(64)).expect("read"), 1);
2822
2823            assert_eq!(
2824                pipe.query_events(&current_task),
2825                Ok(FdEvents::POLLOUT | FdEvents::POLLWRNORM)
2826            );
2827            let fds = epoll_file.wait(&current_task, 1, zx::MonotonicInstant::ZERO).expect("wait");
2828            assert!(fds.is_empty());
2829        })
2830        .await;
2831    }
2832
2833    #[::fuchsia::test]
2834    async fn test_new_remote_directory() {
2835        spawn_kernel_and_run(async |current_task| {
2836            let (server, client) = zx::Channel::create();
2837            fdio::open("/pkg", fio::PERM_READABLE | fio::PERM_EXECUTABLE, server)
2838                .expect("failed to open /pkg");
2839
2840            let fd = new_remote_file(&current_task, client.into(), OpenFlags::RDWR)
2841                .expect("new_remote_file");
2842            assert!(fd.node().is_dir());
2843            assert!(fd.to_handle(&current_task).expect("to_handle").is_some());
2844        })
2845        .await;
2846    }
2847
2848    #[::fuchsia::test]
2849    async fn test_new_remote_file() {
2850        spawn_kernel_and_run(async |current_task| {
2851            let (server, client) = zx::Channel::create();
2852            fdio::open("/pkg/meta/contents", fio::PERM_READABLE, server)
2853                .expect("failed to open /pkg/meta/contents");
2854
2855            let fd = new_remote_file(&current_task, client.into(), OpenFlags::RDONLY)
2856                .expect("new_remote_file");
2857            assert!(fd.node().is_reg());
2858            assert!(fd.to_handle(&current_task).expect("to_handle").is_some());
2859        })
2860        .await;
2861    }
2862
2863    #[::fuchsia::test]
2864    async fn test_new_remote_counter() {
2865        spawn_kernel_and_run(async |current_task| {
2866            let counter = zx::Counter::create();
2867
2868            let fd = new_remote_file(&current_task, counter.into(), OpenFlags::RDONLY)
2869                .expect("new_remote_file");
2870            assert!(fd.node().is_private());
2871            assert!(fd.to_handle(&current_task).expect("to_handle").is_some());
2872        })
2873        .await;
2874    }
2875
2876    #[::fuchsia::test]
2877    async fn test_new_remote_vmo() {
2878        spawn_kernel_and_run(async |current_task| {
2879            let vmo = zx::Vmo::create(*PAGE_SIZE).expect("Vmo::create");
2880            let fd = new_remote_file(&current_task, vmo.into(), OpenFlags::RDWR)
2881                .expect("new_remote_file");
2882            assert!(fd.node().is_reg());
2883            assert!(fd.node().is_private());
2884            assert_eq!(fd.node().info().size, *PAGE_SIZE as usize);
2885            assert!(fd.to_handle(&current_task).expect("to_handle").is_some());
2886        })
2887        .await;
2888    }
2889
2890    #[::fuchsia::test(threads = 2)]
2891    async fn test_symlink() {
2892        let fixture = TestFixture::new().await;
2893        let (server, client) = zx::Channel::create();
2894        fixture.root().clone(server.into()).expect("clone failed");
2895
2896        const LINK_PATH: &'static str = "symlink";
2897        const LINK_TARGET: &'static str = "私は「UTF8」です";
2898        // We expect the reported size of the symlink to be the length of the target, in bytes,
2899        // *without* a null terminator. Most Linux systems assume UTF-8 encoding.
2900        const LINK_SIZE: usize = 22;
2901        assert_eq!(LINK_SIZE, LINK_TARGET.len());
2902
2903        spawn_kernel_and_run(async move |current_task| {
2904            let kernel = current_task.kernel();
2905            let fs = RemoteFs::new_fs(
2906                &kernel,
2907                client,
2908                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
2909                fio::PERM_READABLE | fio::PERM_WRITABLE,
2910            )
2911            .expect("new_fs failed");
2912            let ns = Namespace::new(fs);
2913            let root = ns.root();
2914            let symlink_node = root
2915                .create_symlink(&current_task, LINK_PATH.into(), LINK_TARGET.into())
2916                .expect("symlink failed");
2917            assert_matches!(&*symlink_node.entry.node.info(), FsNodeInfo { size: LINK_SIZE, .. });
2918
2919            let mut context = LookupContext::new(SymlinkMode::NoFollow);
2920            let child = root
2921                .lookup_child(&current_task, &mut context, "symlink".into())
2922                .expect("lookup_child failed");
2923
2924            match child.readlink(&current_task).expect("readlink failed") {
2925                SymlinkTarget::Path(path) => assert_eq!(path, LINK_TARGET),
2926                SymlinkTarget::Node(_) => panic!("readlink returned SymlinkTarget::Node"),
2927            }
2928            // Ensure the size stat reports matches what is expected.
2929            let stat_result = child.entry.node.stat(&current_task).expect("stat failed");
2930            assert_eq!(stat_result.st_size as usize, LINK_SIZE);
2931        })
2932        .await;
2933
2934        // Simulate a second run to ensure the symlink was persisted correctly.
2935        let fixture = TestFixture::open(
2936            fixture.close().await,
2937            TestFixtureOptions { format: false, ..Default::default() },
2938        )
2939        .await;
2940        let (server, client) = zx::Channel::create();
2941        fixture.root().clone(server.into()).expect("clone failed after remount");
2942
2943        spawn_kernel_and_run(async move |current_task| {
2944            let kernel = current_task.kernel();
2945            let fs = RemoteFs::new_fs(
2946                &kernel,
2947                client,
2948                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
2949                fio::PERM_READABLE | fio::PERM_WRITABLE,
2950            )
2951            .expect("new_fs failed after remount");
2952            let ns = Namespace::new(fs);
2953            let root = ns.root();
2954            let mut context = LookupContext::new(SymlinkMode::NoFollow);
2955            let child = root
2956                .lookup_child(&current_task, &mut context, "symlink".into())
2957                .expect("lookup_child failed after remount");
2958
2959            match child.readlink(&current_task).expect("readlink failed after remount") {
2960                SymlinkTarget::Path(path) => assert_eq!(path, LINK_TARGET),
2961                SymlinkTarget::Node(_) => {
2962                    panic!("readlink returned SymlinkTarget::Node after remount")
2963                }
2964            }
2965            // Ensure the size stat reports matches what is expected.
2966            let stat_result =
2967                child.entry.node.stat(&current_task).expect("stat failed after remount");
2968            assert_eq!(stat_result.st_size as usize, LINK_SIZE);
2969        })
2970        .await;
2971
2972        fixture.close().await;
2973    }
2974
2975    #[::fuchsia::test]
2976    async fn test_mode_uid_gid_and_dev_persists() {
2977        const FILE_MODE: FileMode = mode!(IFREG, 0o467);
2978        const DIR_MODE: FileMode = mode!(IFDIR, 0o647);
2979        const BLK_MODE: FileMode = mode!(IFBLK, 0o746);
2980
2981        let fixture = TestFixture::new().await;
2982        let (server, client) = zx::Channel::create();
2983        fixture.root().clone(server.into()).expect("clone failed");
2984
2985        // Simulate a first run of starnix.
2986        spawn_kernel_and_run(async move |current_task| {
2987            let kernel = current_task.kernel();
2988            let creds = Credentials::clone(&current_task.current_creds());
2989            current_task.set_creds(Credentials { euid: 1, fsuid: 1, egid: 2, fsgid: 2, ..creds });
2990            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
2991            let fs = RemoteFs::new_fs(
2992                &kernel,
2993                client,
2994                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
2995                rights,
2996            )
2997            .expect("new_fs failed");
2998            let ns = Namespace::new(fs);
2999            current_task.fs().set_umask(FileMode::from_bits(0));
3000            ns.root()
3001                .create_node(&current_task, "file".into(), FILE_MODE, DeviceId::NONE)
3002                .expect("create_node failed");
3003            ns.root()
3004                .create_node(&current_task, "dir".into(), DIR_MODE, DeviceId::NONE)
3005                .expect("create_node failed");
3006            ns.root()
3007                .create_node(&current_task, "dev".into(), BLK_MODE, DeviceId::RANDOM)
3008                .expect("create_node failed");
3009        })
3010        .await;
3011
3012        // Simulate a second run.
3013        let fixture = TestFixture::open(
3014            fixture.close().await,
3015            TestFixtureOptions { format: false, ..Default::default() },
3016        )
3017        .await;
3018
3019        let (server, client) = zx::Channel::create();
3020        fixture.root().clone(server.into()).expect("clone failed");
3021
3022        spawn_kernel_and_run(async move |current_task| {
3023            let kernel = current_task.kernel();
3024            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3025            let fs = RemoteFs::new_fs(
3026                &kernel,
3027                client,
3028                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3029                rights,
3030            )
3031            .expect("new_fs failed");
3032            let ns = Namespace::new(fs);
3033            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3034            let child = ns
3035                .root()
3036                .lookup_child(&current_task, &mut context, "file".into())
3037                .expect("lookup_child failed");
3038            assert_matches!(
3039                &*child.entry.node.info(),
3040                FsNodeInfo { mode: FILE_MODE, uid: 1, gid: 2, rdev: DeviceId::NONE, .. }
3041            );
3042            let child = ns
3043                .root()
3044                .lookup_child(&current_task, &mut context, "dir".into())
3045                .expect("lookup_child failed");
3046            assert_matches!(
3047                &*child.entry.node.info(),
3048                FsNodeInfo { mode: DIR_MODE, uid: 1, gid: 2, rdev: DeviceId::NONE, .. }
3049            );
3050            let child = ns
3051                .root()
3052                .lookup_child(&current_task, &mut context, "dev".into())
3053                .expect("lookup_child failed");
3054            assert_matches!(
3055                &*child.entry.node.info(),
3056                FsNodeInfo { mode: BLK_MODE, uid: 1, gid: 2, rdev: DeviceId::RANDOM, .. }
3057            );
3058        })
3059        .await;
3060        fixture.close().await;
3061    }
3062
3063    #[::fuchsia::test]
3064    async fn test_dot_dot_inode_numbers() {
3065        let fixture = TestFixture::new().await;
3066        let (server, client) = zx::Channel::create();
3067        fixture.root().clone(server.into()).expect("clone failed");
3068
3069        const MODE: FileMode = FileMode::from_bits(FileMode::IFDIR.bits() | 0o777);
3070
3071        spawn_kernel_and_run(async |current_task| {
3072            let kernel = current_task.kernel();
3073            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3074            let fs = RemoteFs::new_fs(
3075                &kernel,
3076                client,
3077                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3078                rights,
3079            )
3080            .expect("new_fs failed");
3081            let ns = Namespace::new(fs);
3082            current_task.fs().set_umask(FileMode::from_bits(0));
3083            let sub_dir1 = ns
3084                .root()
3085                .create_node(&current_task, "dir".into(), MODE, DeviceId::NONE)
3086                .expect("create_node failed");
3087            let sub_dir2 = sub_dir1
3088                .create_node(&current_task, "dir".into(), MODE, DeviceId::NONE)
3089                .expect("create_node failed");
3090
3091            let dir_handle = ns
3092                .root()
3093                .entry
3094                .open_anonymous(&current_task, OpenFlags::RDONLY)
3095                .expect("open failed");
3096
3097            #[derive(Default)]
3098            struct Sink {
3099                offset: off_t,
3100                dot_inode_num: u64,
3101                dot_dot_inode_num: u64,
3102            }
3103            impl DirentSink for Sink {
3104                fn add(
3105                    &mut self,
3106                    inode_num: ino_t,
3107                    offset: off_t,
3108                    entry_type: DirectoryEntryType,
3109                    name: &FsStr,
3110                ) -> Result<(), Errno> {
3111                    if name == "." {
3112                        self.dot_inode_num = inode_num;
3113                        assert_eq!(entry_type, DirectoryEntryType::DIR);
3114                    } else if name == ".." {
3115                        self.dot_dot_inode_num = inode_num;
3116                        assert_eq!(entry_type, DirectoryEntryType::DIR);
3117                    }
3118                    self.offset = offset;
3119                    Ok(())
3120                }
3121                fn offset(&self) -> off_t {
3122                    self.offset
3123                }
3124            }
3125            let mut sink = Sink::default();
3126            dir_handle.readdir(&current_task, &mut sink).expect("readdir failed");
3127
3128            // inode_num for . and .. for the root should be the same as root.
3129            assert_eq!(sink.dot_inode_num, ns.root().entry.node.ino);
3130            assert_eq!(sink.dot_dot_inode_num, ns.root().entry.node.ino);
3131
3132            let dir_handle = sub_dir1
3133                .entry
3134                .open_anonymous(&current_task, OpenFlags::RDONLY)
3135                .expect("open failed");
3136            let mut sink = Sink::default();
3137            dir_handle.readdir(&current_task, &mut sink).expect("readdir failed");
3138
3139            // inode_num for . should be sub_dir1, and .. should be root.
3140            assert_eq!(sink.dot_inode_num, sub_dir1.entry.node.ino);
3141            assert_eq!(sink.dot_dot_inode_num, ns.root().entry.node.ino);
3142
3143            let dir_handle = sub_dir2
3144                .entry
3145                .open_anonymous(&current_task, OpenFlags::RDONLY)
3146                .expect("open failed");
3147            let mut sink = Sink::default();
3148            dir_handle.readdir(&current_task, &mut sink).expect("readdir failed");
3149
3150            // inode_num for . should be sub_dir2, and .. should be sub_dir1.
3151            assert_eq!(sink.dot_inode_num, sub_dir2.entry.node.ino);
3152            assert_eq!(sink.dot_dot_inode_num, sub_dir1.entry.node.ino);
3153        })
3154        .await;
3155        fixture.close().await;
3156    }
3157
3158    #[::fuchsia::test]
3159    async fn test_remote_special_node() {
3160        let fixture = TestFixture::new().await;
3161        let (server, client) = zx::Channel::create();
3162        fixture.root().clone(server.into()).expect("clone failed");
3163
3164        const FIFO_MODE: FileMode = FileMode::from_bits(FileMode::IFIFO.bits() | 0o777);
3165        const REG_MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits());
3166
3167        spawn_kernel_and_run(async |current_task| {
3168            let kernel = current_task.kernel();
3169            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3170            let fs = RemoteFs::new_fs(
3171                &kernel,
3172                client,
3173                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3174                rights,
3175            )
3176            .expect("new_fs failed");
3177            let ns = Namespace::new(fs);
3178            current_task.fs().set_umask(FileMode::from_bits(0));
3179            let root = ns.root();
3180
3181            // Create RemoteSpecialNode (e.g. FIFO)
3182            root.create_node(&current_task, "fifo".into(), FIFO_MODE, DeviceId::NONE)
3183                .expect("create_node failed");
3184            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3185            let fifo_node = root
3186                .lookup_child(&current_task, &mut context, "fifo".into())
3187                .expect("lookup_child failed");
3188
3189            // Test that we get expected behaviour for RemoteSpecialNode operation, e.g.
3190            // test that truncate should return EINVAL
3191            match fifo_node.truncate(&current_task, 0) {
3192                Ok(_) => {
3193                    panic!("truncate passed for special node")
3194                }
3195                Err(errno) if errno == EINVAL => {}
3196                Err(e) => {
3197                    panic!("truncate failed with error {:?}", e)
3198                }
3199            };
3200
3201            // Create regular RemoteNode
3202            root.create_node(&current_task, "file".into(), REG_MODE, DeviceId::NONE)
3203                .expect("create_node failed");
3204            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3205            let reg_node = root
3206                .lookup_child(&current_task, &mut context, "file".into())
3207                .expect("lookup_child failed");
3208
3209            // We should be able to perform truncate on regular files
3210            reg_node.truncate(&current_task, 0).expect("truncate failed");
3211        })
3212        .await;
3213        fixture.close().await;
3214    }
3215
3216    #[::fuchsia::test]
3217    async fn test_hard_link() {
3218        let fixture = TestFixture::new().await;
3219        let (server, client) = zx::Channel::create();
3220        fixture.root().clone(server.into()).expect("clone failed");
3221
3222        spawn_kernel_and_run(async move |current_task| {
3223            let kernel = current_task.kernel();
3224            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3225            let fs = RemoteFs::new_fs(
3226                &kernel,
3227                client,
3228                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3229                rights,
3230            )
3231            .expect("new_fs failed");
3232            let ns = Namespace::new(fs);
3233            current_task.fs().set_umask(FileMode::from_bits(0));
3234            let node = ns
3235                .root()
3236                .create_node(&current_task, "file1".into(), mode!(IFREG, 0o666), DeviceId::NONE)
3237                .expect("create_node failed");
3238            ns.root()
3239                .entry
3240                .node
3241                .link(&current_task, &ns.root().mount, "file2".into(), &node.entry.node)
3242                .expect("link failed");
3243        })
3244        .await;
3245
3246        let fixture = TestFixture::open(
3247            fixture.close().await,
3248            TestFixtureOptions { format: false, ..Default::default() },
3249        )
3250        .await;
3251
3252        let (server, client) = zx::Channel::create();
3253        fixture.root().clone(server.into()).expect("clone failed");
3254
3255        spawn_kernel_and_run(async move |current_task| {
3256            let kernel = current_task.kernel();
3257            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3258            let fs = RemoteFs::new_fs(
3259                &kernel,
3260                client,
3261                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3262                rights,
3263            )
3264            .expect("new_fs failed");
3265            let ns = Namespace::new(fs);
3266            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3267            let child1 = ns
3268                .root()
3269                .lookup_child(&current_task, &mut context, "file1".into())
3270                .expect("lookup_child failed");
3271            let child2 = ns
3272                .root()
3273                .lookup_child(&current_task, &mut context, "file2".into())
3274                .expect("lookup_child failed");
3275            assert!(Arc::ptr_eq(&child1.entry.node, &child2.entry.node));
3276        })
3277        .await;
3278        fixture.close().await;
3279    }
3280
3281    #[::fuchsia::test]
3282    async fn test_lookup_on_fsverity_enabled_file() {
3283        let fixture = TestFixture::new().await;
3284        let (server, client) = zx::Channel::create();
3285        fixture.root().clone(server.into()).expect("clone failed");
3286
3287        const MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o467);
3288
3289        spawn_kernel_and_run(async move |current_task| {
3290            let kernel = current_task.kernel();
3291            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3292            let fs = RemoteFs::new_fs(
3293                &kernel,
3294                client,
3295                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3296                rights,
3297            )
3298            .expect("new_fs failed");
3299            let ns = Namespace::new(fs);
3300            current_task.fs().set_umask(FileMode::from_bits(0));
3301            let file = ns
3302                .root()
3303                .create_node(&current_task, "file".into(), MODE, DeviceId::NONE)
3304                .expect("create_node failed");
3305            // Enable verity on the file.
3306            let desc = fsverity_descriptor {
3307                version: 1,
3308                hash_algorithm: 1,
3309                salt_size: 32,
3310                log_blocksize: 12,
3311                ..Default::default()
3312            };
3313            file.entry.node.enable_fsverity(current_task, &desc).expect("enable fsverity failed");
3314        })
3315        .await;
3316
3317        // Tear down the kernel and open the file again. The file should no longer be cached.
3318        // Test that lookup works as expected for an fsverity-enabled file.
3319        let fixture = TestFixture::open(
3320            fixture.close().await,
3321            TestFixtureOptions { format: false, ..Default::default() },
3322        )
3323        .await;
3324        let (server, client) = zx::Channel::create();
3325        fixture.root().clone(server.into()).expect("clone failed");
3326
3327        spawn_kernel_and_run(async move |current_task| {
3328            let kernel = current_task.kernel();
3329            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3330            let fs = RemoteFs::new_fs(
3331                &kernel,
3332                client,
3333                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3334                rights,
3335            )
3336            .expect("new_fs failed");
3337            let ns = Namespace::new(fs);
3338            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3339            let _child = ns
3340                .root()
3341                .lookup_child(&current_task, &mut context, "file".into())
3342                .expect("lookup_child failed");
3343        })
3344        .await;
3345        fixture.close().await;
3346    }
3347
3348    #[::fuchsia::test]
3349    async fn test_update_attributes_persists() {
3350        let fixture = TestFixture::new().await;
3351        let (server, client) = zx::Channel::create();
3352        fixture.root().clone(server.into()).expect("clone failed");
3353
3354        const MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o467);
3355
3356        spawn_kernel_and_run(async move |current_task| {
3357            let kernel = current_task.kernel();
3358            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3359            let fs = RemoteFs::new_fs(
3360                &kernel,
3361                client,
3362                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3363                rights,
3364            )
3365            .expect("new_fs failed");
3366            let ns = Namespace::new(fs);
3367            current_task.fs().set_umask(FileMode::from_bits(0));
3368            let file = ns
3369                .root()
3370                .create_node(&current_task, "file".into(), MODE, DeviceId::NONE)
3371                .expect("create_node failed");
3372            // Change the mode, this change should persist
3373            file.entry
3374                .node
3375                .chmod(&current_task, &file.mount, MODE | FileMode::ALLOW_ALL)
3376                .expect("chmod failed");
3377        })
3378        .await;
3379
3380        // Tear down the kernel and open the file again. Check that changes persisted.
3381        let fixture = TestFixture::open(
3382            fixture.close().await,
3383            TestFixtureOptions { format: false, ..Default::default() },
3384        )
3385        .await;
3386        let (server, client) = zx::Channel::create();
3387        fixture.root().clone(server.into()).expect("clone failed");
3388
3389        spawn_kernel_and_run(async move |current_task| {
3390            let kernel = current_task.kernel();
3391            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3392            let fs = RemoteFs::new_fs(
3393                &kernel,
3394                client,
3395                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3396                rights,
3397            )
3398            .expect("new_fs failed");
3399            let ns = Namespace::new(fs);
3400            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3401            let child = ns
3402                .root()
3403                .lookup_child(&current_task, &mut context, "file".into())
3404                .expect("lookup_child failed");
3405            assert_eq!(child.entry.node.info().mode, MODE | FileMode::ALLOW_ALL);
3406        })
3407        .await;
3408        fixture.close().await;
3409    }
3410
3411    #[::fuchsia::test]
3412    async fn test_statfs() {
3413        let fixture = TestFixture::new().await;
3414        let (server, client) = zx::Channel::create();
3415        fixture.root().clone(server.into()).expect("clone failed");
3416
3417        spawn_kernel_and_run(async move |current_task| {
3418            let kernel = current_task.kernel();
3419            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3420            let fs = RemoteFs::new_fs(
3421                &kernel,
3422                client,
3423                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3424                rights,
3425            )
3426            .expect("new_fs failed");
3427
3428            let statfs = fs.statfs(&current_task).expect("statfs failed");
3429            assert!(statfs.f_type != 0);
3430            assert!(statfs.f_bsize > 0);
3431            assert!(statfs.f_blocks > 0);
3432            assert!(statfs.f_bfree > 0 && statfs.f_bfree <= statfs.f_blocks);
3433            assert!(statfs.f_files > 0);
3434            assert!(statfs.f_ffree > 0 && statfs.f_ffree <= statfs.f_files);
3435            assert!(statfs.f_fsid.val[0] != 0 || statfs.f_fsid.val[1] != 0);
3436            assert!(statfs.f_namelen > 0);
3437            assert!(statfs.f_frsize > 0);
3438        })
3439        .await;
3440
3441        fixture.close().await;
3442    }
3443
3444    #[::fuchsia::test]
3445    async fn test_allocate() {
3446        let fixture = TestFixture::new().await;
3447        let (server, client) = zx::Channel::create();
3448        fixture.root().clone(server.into()).expect("clone failed");
3449
3450        spawn_kernel_and_run(async move |current_task| {
3451            let kernel = current_task.kernel();
3452            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3453            let fs = RemoteFs::new_fs(
3454                &kernel,
3455                client,
3456                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3457                rights,
3458            )
3459            .expect("new_fs failed");
3460            let ns = Namespace::new(fs);
3461            current_task.fs().set_umask(FileMode::from_bits(0));
3462            let root = ns.root();
3463
3464            const REG_MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits());
3465            root.create_node(&current_task, "file".into(), REG_MODE, DeviceId::NONE)
3466                .expect("create_node failed");
3467            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3468            let reg_node = root
3469                .lookup_child(&current_task, &mut context, "file".into())
3470                .expect("lookup_child failed");
3471
3472            reg_node
3473                .entry
3474                .node
3475                .fallocate(&current_task, FallocMode::Allocate { keep_size: false }, 0, 20)
3476                .expect("truncate failed");
3477        })
3478        .await;
3479        fixture.close().await;
3480    }
3481
3482    #[::fuchsia::test]
3483    async fn test_allocate_overflow() {
3484        let fixture = TestFixture::new().await;
3485        let (server, client) = zx::Channel::create();
3486        fixture.root().clone(server.into()).expect("clone failed");
3487
3488        spawn_kernel_and_run(async move |current_task| {
3489            let kernel = current_task.kernel();
3490            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3491            let fs = RemoteFs::new_fs(
3492                &kernel,
3493                client,
3494                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3495                rights,
3496            )
3497            .expect("new_fs failed");
3498            let ns = Namespace::new(fs);
3499            current_task.fs().set_umask(FileMode::from_bits(0));
3500            let root = ns.root();
3501
3502            const REG_MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits());
3503            root.create_node(&current_task, "file".into(), REG_MODE, DeviceId::NONE)
3504                .expect("create_node failed");
3505            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3506            let reg_node = root
3507                .lookup_child(&current_task, &mut context, "file".into())
3508                .expect("lookup_child failed");
3509
3510            reg_node
3511                .entry
3512                .node
3513                .fallocate(&current_task, FallocMode::Allocate { keep_size: false }, 1, u64::MAX)
3514                .expect_err("truncate unexpectedly passed");
3515        })
3516        .await;
3517        fixture.close().await;
3518    }
3519
3520    #[::fuchsia::test]
3521    async fn test_time_modify_persists() {
3522        let fixture = TestFixture::new().await;
3523        let (server, client) = zx::Channel::create();
3524        fixture.root().clone(server.into()).expect("clone failed");
3525
3526        const MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o467);
3527
3528        let last_modified = spawn_kernel_and_run(async move |current_task| {
3529            let kernel = current_task.kernel();
3530            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3531            let fs = RemoteFs::new_fs(
3532                &kernel,
3533                client,
3534                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3535                rights,
3536            )
3537            .expect("new_fs failed");
3538            let ns: Arc<Namespace> = Namespace::new(fs);
3539            current_task.fs().set_umask(FileMode::from_bits(0));
3540            let child = ns
3541                .root()
3542                .create_node(&current_task, "file".into(), MODE, DeviceId::NONE)
3543                .expect("create_node failed");
3544            // Write to file (this should update mtime (time_modify))
3545            let file = child.open(&current_task, OpenFlags::RDWR).expect("open failed");
3546            // Call `fetch_and_refresh_info(..)` to refresh `time_modify` with the time managed by the
3547            // underlying filesystem
3548            let time_before_write = child
3549                .entry
3550                .node
3551                .fetch_and_refresh_info(&current_task)
3552                .expect("fetch_and_refresh_info failed")
3553                .time_modify;
3554            let write_bytes: [u8; 5] = [1, 2, 3, 4, 5];
3555            let written = file
3556                .write(&current_task, &mut VecInputBuffer::new(&write_bytes))
3557                .expect("write failed");
3558            assert_eq!(written, write_bytes.len());
3559            let last_modified = child
3560                .entry
3561                .node
3562                .fetch_and_refresh_info(&current_task)
3563                .expect("fetch_and_refresh_info failed")
3564                .time_modify;
3565            assert!(last_modified > time_before_write);
3566            last_modified
3567        })
3568        .await;
3569
3570        // Tear down the kernel and open the file again. Check that modification time is when we
3571        // last modified the contents of the file
3572        let fixture = TestFixture::open(
3573            fixture.close().await,
3574            TestFixtureOptions { format: false, ..Default::default() },
3575        )
3576        .await;
3577        let (server, client) = zx::Channel::create();
3578        fixture.root().clone(server.into()).expect("clone failed");
3579        let refreshed_modified_time = spawn_kernel_and_run(async move |current_task| {
3580            let kernel = current_task.kernel();
3581            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3582            let fs = RemoteFs::new_fs(
3583                &kernel,
3584                client,
3585                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3586                rights,
3587            )
3588            .expect("new_fs failed");
3589            let ns = Namespace::new(fs);
3590            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3591            let child = ns
3592                .root()
3593                .lookup_child(&current_task, &mut context, "file".into())
3594                .expect("lookup_child failed");
3595            let last_modified = child
3596                .entry
3597                .node
3598                .fetch_and_refresh_info(&current_task)
3599                .expect("fetch_and_refresh_info failed")
3600                .time_modify;
3601            last_modified
3602        })
3603        .await;
3604        assert_eq!(last_modified, refreshed_modified_time);
3605
3606        fixture.close().await;
3607    }
3608
3609    #[::fuchsia::test]
3610    async fn test_update_atime_mtime() {
3611        let fixture = TestFixture::new().await;
3612        let (server, client) = zx::Channel::create();
3613        fixture.root().clone(server.into()).expect("clone failed");
3614
3615        const MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o467);
3616
3617        spawn_kernel_and_run(async move |current_task| {
3618            let kernel = current_task.kernel();
3619            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3620            let fs = RemoteFs::new_fs(
3621                &kernel,
3622                client,
3623                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3624                rights,
3625            )
3626            .expect("new_fs failed");
3627            let ns: Arc<Namespace> = Namespace::new(fs);
3628            current_task.fs().set_umask(FileMode::from_bits(0));
3629            let child = ns
3630                .root()
3631                .create_node(&current_task, "file".into(), MODE, DeviceId::NONE)
3632                .expect("create_node failed");
3633
3634            let info_original = child
3635                .entry
3636                .node
3637                .fetch_and_refresh_info(&current_task)
3638                .expect("fetch_and_refresh_info failed")
3639                .clone();
3640
3641            child
3642                .entry
3643                .node
3644                .update_atime_mtime(
3645                    &current_task,
3646                    &child.mount,
3647                    TimeUpdateType::Time(UtcInstant::from_nanos(30)),
3648                    TimeUpdateType::Omit,
3649                )
3650                .expect("update_atime_mtime failed");
3651            let info_after_update = child
3652                .entry
3653                .node
3654                .fetch_and_refresh_info(&current_task)
3655                .expect("fetch_and_refresh_info failed")
3656                .clone();
3657            assert_eq!(info_after_update.time_modify, info_original.time_modify);
3658            assert_eq!(info_after_update.time_access, UtcInstant::from_nanos(30));
3659
3660            child
3661                .entry
3662                .node
3663                .update_atime_mtime(
3664                    &current_task,
3665                    &child.mount,
3666                    TimeUpdateType::Omit,
3667                    TimeUpdateType::Time(UtcInstant::from_nanos(50)),
3668                )
3669                .expect("update_atime_mtime failed");
3670            let info_after_update2 = child
3671                .entry
3672                .node
3673                .fetch_and_refresh_info(&current_task)
3674                .expect("fetch_and_refresh_info failed")
3675                .clone();
3676            assert_eq!(info_after_update2.time_modify, UtcInstant::from_nanos(50));
3677            assert_eq!(info_after_update2.time_access, UtcInstant::from_nanos(30));
3678        })
3679        .await;
3680        fixture.close().await;
3681    }
3682
3683    #[::fuchsia::test]
3684    async fn test_write_updates_mtime_ctime() {
3685        let fixture = TestFixture::new().await;
3686        let (server, client) = zx::Channel::create();
3687        fixture.root().clone(server.into()).expect("clone failed");
3688
3689        const MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o467);
3690
3691        spawn_kernel_and_run(async move |current_task| {
3692            let kernel = current_task.kernel();
3693            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3694            let fs = RemoteFs::new_fs(
3695                &kernel,
3696                client,
3697                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3698                rights,
3699            )
3700            .expect("new_fs failed");
3701            let ns: Arc<Namespace> = Namespace::new(fs);
3702            current_task.fs().set_umask(FileMode::from_bits(0));
3703            let child = ns
3704                .root()
3705                .create_node(&current_task, "file".into(), MODE, DeviceId::NONE)
3706                .expect("create_node failed");
3707            let file = child.open(&current_task, OpenFlags::RDWR).expect("open failed");
3708            // Call `fetch_and_refresh_info(..)` to refresh ctime and mtime with the time managed by the
3709            // underlying filesystem
3710            let (ctime_before_write, mtime_before_write) = {
3711                let info = child
3712                    .entry
3713                    .node
3714                    .fetch_and_refresh_info(&current_task)
3715                    .expect("fetch_and_refresh_info failed");
3716                (info.time_status_change, info.time_modify)
3717            };
3718
3719            // Writing to a file should update ctime and mtime
3720            let write_bytes: [u8; 5] = [1, 2, 3, 4, 5];
3721            let written = file
3722                .write(&current_task, &mut VecInputBuffer::new(&write_bytes))
3723                .expect("write failed");
3724            assert_eq!(written, write_bytes.len());
3725
3726            // As Fxfs, the underlying filesystem in this test, can manage file timestamps,
3727            // we should not see an update in mtime and ctime without first refreshing the node with
3728            // the metadata from Fxfs.
3729            let (ctime_after_write_no_refresh, mtime_after_write_no_refresh) = {
3730                let info = child.entry.node.info();
3731                (info.time_status_change, info.time_modify)
3732            };
3733            assert_eq!(ctime_after_write_no_refresh, ctime_before_write);
3734            assert_eq!(mtime_after_write_no_refresh, mtime_before_write);
3735
3736            // Refresh information, we should see `info` with mtime and ctime from the remote
3737            // filesystem (assume this is true if the new timestamp values are greater than the ones
3738            // without the refresh).
3739            let (ctime_after_write_refresh, mtime_after_write_refresh) = {
3740                let info = child
3741                    .entry
3742                    .node
3743                    .fetch_and_refresh_info(&current_task)
3744                    .expect("fetch_and_refresh_info failed");
3745                (info.time_status_change, info.time_modify)
3746            };
3747            assert_eq!(ctime_after_write_refresh, mtime_after_write_refresh);
3748            assert!(ctime_after_write_refresh > ctime_after_write_no_refresh);
3749        })
3750        .await;
3751        fixture.close().await;
3752    }
3753
3754    #[::fuchsia::test]
3755    async fn test_casefold_persists() {
3756        let fixture = TestFixture::new().await;
3757        let (server, client) = zx::Channel::create();
3758        fixture.root().clone(server.into()).expect("clone failed");
3759
3760        spawn_kernel_and_run(async move |current_task| {
3761            let kernel = current_task.kernel();
3762            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3763            let fs = RemoteFs::new_fs(
3764                &kernel,
3765                client,
3766                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3767                rights,
3768            )
3769            .expect("new_fs failed");
3770            let ns: Arc<Namespace> = Namespace::new(fs);
3771            let child = ns
3772                .root()
3773                .create_node(
3774                    &current_task,
3775                    "dir".into(),
3776                    FileMode::ALLOW_ALL.with_type(FileMode::IFDIR),
3777                    DeviceId::NONE,
3778                )
3779                .expect("create_node failed");
3780            child
3781                .entry
3782                .node
3783                .update_attributes(&current_task, |info| {
3784                    info.casefold = true;
3785                    Ok(())
3786                })
3787                .expect("enable casefold")
3788        })
3789        .await;
3790
3791        // Tear down the kernel and open the dir again. Check that casefold is preserved.
3792        let fixture = TestFixture::open(
3793            fixture.close().await,
3794            TestFixtureOptions { format: false, ..Default::default() },
3795        )
3796        .await;
3797        let (server, client) = zx::Channel::create();
3798        fixture.root().clone(server.into()).expect("clone failed");
3799        let casefold = spawn_kernel_and_run(async move |current_task| {
3800            let kernel = current_task.kernel();
3801            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
3802            let fs = RemoteFs::new_fs(
3803                &kernel,
3804                client,
3805                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
3806                rights,
3807            )
3808            .expect("new_fs failed");
3809            let ns = Namespace::new(fs);
3810            let mut context = LookupContext::new(SymlinkMode::NoFollow);
3811            let child = ns
3812                .root()
3813                .lookup_child(&current_task, &mut context, "dir".into())
3814                .expect("lookup_child failed");
3815            let casefold = child
3816                .entry
3817                .node
3818                .fetch_and_refresh_info(&current_task)
3819                .expect("fetch_and_refresh_info failed")
3820                .casefold;
3821            casefold
3822        })
3823        .await;
3824        assert!(casefold);
3825
3826        fixture.close().await;
3827    }
3828
3829    #[::fuchsia::test]
3830    async fn test_pending_access_time() {
3831        const TEST_FILE: &str = "test_file";
3832
3833        let fixture = TestFixture::new().await;
3834        let (server, client) = zx::Channel::create();
3835        fixture.root().clone(server.into()).expect("clone failed");
3836        let (server, client2) = zx::Channel::create();
3837        fixture.root().clone(server.into()).expect("clone failed");
3838
3839        spawn_kernel_and_run(async move |current_task| {
3840            let kernel = current_task.kernel.clone();
3841
3842            let atime3 = {
3843                let fs = RemoteFs::new_fs(
3844                    &kernel,
3845                    client,
3846                    FileSystemOptions {
3847                        source: FlyByteStr::new(b"/"),
3848                        flags: FileSystemFlags::empty().into(),
3849                        ..Default::default()
3850                    },
3851                    fio::PERM_READABLE | fio::PERM_WRITABLE,
3852                )
3853                .expect("new_fs failed");
3854
3855                let ns = Namespace::new_with_flags(fs, MountpointFlags::RELATIME);
3856                let (child, _status) = ns
3857                    .root()
3858                    .open_create_node(
3859                        &current_task,
3860                        TEST_FILE.into(),
3861                        FileMode::ALLOW_ALL.with_type(FileMode::IFREG),
3862                        DeviceId::NONE,
3863                    )
3864                    .expect("create_node failed");
3865
3866                let atime1 = child.entry.node.info().time_access;
3867
3868                std::thread::sleep(std::time::Duration::from_micros(1));
3869
3870                let file_handle = child.open(&current_task, OpenFlags::RDWR).expect("open failed");
3871
3872                file_handle
3873                    .read(&current_task, &mut VecOutputBuffer::new(10))
3874                    .expect("read failed");
3875
3876                // Expect atime to have changed.
3877                let atime2 = child.entry.node.info().time_access;
3878                assert!(atime2 > atime1);
3879
3880                std::thread::sleep(std::time::Duration::from_micros(1));
3881
3882                file_handle
3883                    .read(&current_task, &mut VecOutputBuffer::new(10))
3884                    .expect("read failed");
3885
3886                // And again.
3887                let atime3 = child.entry.node.info().time_access;
3888                assert!(atime3 > atime2);
3889
3890                atime3
3891            };
3892
3893            kernel.delayed_releaser.apply(current_task);
3894
3895            // After dropping the filesystem, the atime should have been persistently updated.
3896            let fs = RemoteFs::new_fs(
3897                &kernel,
3898                client2,
3899                FileSystemOptions {
3900                    source: FlyByteStr::new(b"/"),
3901                    flags: FileSystemFlags::empty().into(),
3902                    ..Default::default()
3903                },
3904                fio::PERM_READABLE | fio::PERM_WRITABLE,
3905            )
3906            .expect("new_fs failed");
3907
3908            let ns = Namespace::new_with_flags(fs, MountpointFlags::RELATIME);
3909            let child = ns
3910                .root()
3911                .lookup_child(
3912                    &current_task,
3913                    &mut LookupContext::new(Default::default()),
3914                    TEST_FILE.into(),
3915                )
3916                .expect("lookup_child failed");
3917
3918            let atime4 = child.entry.node.info().time_access;
3919
3920            assert!(atime4 >= atime3);
3921        })
3922        .await;
3923
3924        fixture.close().await;
3925    }
3926
3927    #[::fuchsia::test]
3928    async fn test_read_chunking() {
3929        use futures::StreamExt;
3930        let (client, mut stream) = create_request_stream::<fio::FileMarker>();
3931        let content = vec![0xAB; (fio::MAX_TRANSFER_SIZE + 100) as usize];
3932        let content_clone = content.clone();
3933
3934        let _server_task = fasync::Task::spawn(async move {
3935            while let Some(Ok(request)) = stream.next().await {
3936                match request {
3937                    fio::FileRequest::ReadAt { count, offset, responder } => {
3938                        let start = offset as usize;
3939                        let end = std::cmp::min(start + count as usize, content_clone.len());
3940                        let data = if start < content_clone.len() {
3941                            &content_clone[start..end]
3942                        } else {
3943                            &[]
3944                        };
3945                        responder.send(Ok(data)).unwrap();
3946                    }
3947                    _ => panic!("Unexpected request: {:?}", request),
3948                }
3949            }
3950        });
3951
3952        fasync::unblock(move || {
3953            let io = RemoteIo::new(client.into_channel().into());
3954            let mut buffer = VecOutputBuffer::new(content.len());
3955            assert_eq!(
3956                io.read_to_output_buffer(0, &mut buffer).expect("read_at failed"),
3957                content.len()
3958            );
3959            assert_eq!(buffer.data(), content.as_slice());
3960        })
3961        .await;
3962    }
3963
3964    #[::fuchsia::test]
3965    async fn test_write_chunking() {
3966        let (client, mut stream) = create_request_stream::<fio::FileMarker>();
3967        let content = vec![0xCD; (fio::MAX_TRANSFER_SIZE + 100) as usize];
3968        let content2 = content.clone();
3969
3970        let server_task = fasync::Task::spawn(async move {
3971            let mut written = vec![0; content2.len()];
3972            while let Some(Ok(request)) = stream.next().await {
3973                match request {
3974                    fio::FileRequest::WriteAt { offset, data, responder, .. } => {
3975                        let offset = offset as usize;
3976                        written[offset..offset + data.len()].copy_from_slice(&data);
3977                        responder.send(Ok(data.len() as u64)).unwrap();
3978                    }
3979                    _ => panic!("Unexpected request: {:?}", request),
3980                }
3981            }
3982            assert_eq!(written, content2);
3983        });
3984
3985        fasync::unblock(move || {
3986            let io = RemoteIo::new(client.into_channel().into());
3987            let mut buffer = VecInputBuffer::new(&content);
3988            assert_eq!(
3989                io.write_from_input_buffer(0, &mut buffer).expect("write_at failed"),
3990                content.len()
3991            );
3992        })
3993        .await;
3994
3995        server_task.await;
3996    }
3997
3998    #[::fuchsia::test]
3999    async fn test_cached_attribute_refresh_behavior() {
4000        let (client, mut stream) = create_request_stream::<fio::FileMarker>();
4001        let barrier = Arc::new(Barrier::new(2));
4002        let barrier_clone = barrier.clone();
4003        let get_attrs_count = Arc::new(AtomicU32::new(0));
4004        let get_attrs_count_clone = get_attrs_count.clone();
4005
4006        let server_task = fasync::Task::spawn(async move {
4007            while let Some(Ok(request)) = stream.next().await {
4008                match request {
4009                    fio::FileRequest::GetAttributes { query: _, responder } => {
4010                        get_attrs_count_clone.fetch_add(1, Ordering::SeqCst);
4011                        let mutable_attrs = fio::MutableNodeAttributes { ..Default::default() };
4012                        let immutable_attrs = fio::ImmutableNodeAttributes {
4013                            id: Some(1),
4014                            link_count: Some(1),
4015                            ..Default::default()
4016                        };
4017                        responder.send(Ok((&mutable_attrs, &immutable_attrs))).unwrap();
4018                    }
4019                    fio::FileRequest::Resize { length: _, responder } => {
4020                        let barrier_clone = barrier_clone.clone();
4021                        fasync::Task::spawn(async move {
4022                            barrier_clone.async_wait().await;
4023                            barrier_clone.async_wait().await;
4024                            responder.send(Ok(())).unwrap();
4025                        })
4026                        .detach();
4027                    }
4028                    fio::FileRequest::Close { responder } => {
4029                        responder.send(Ok(())).unwrap();
4030                    }
4031                    _ => panic!("Unexpected request: {:?}", request),
4032                }
4033            }
4034        });
4035
4036        fasync::unblock(move || {
4037            let io = RemoteIo::new(client.into_channel().into());
4038            let node = BaseNode::new(io, false);
4039            let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
4040
4041            // 1. Initial fetch. Should return cached info immediately.
4042            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 0);
4043            {
4044                let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4045            }
4046            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 0);
4047
4048            // 2. Spawn a thread to perform a dirty operation.
4049            std::thread::scope(|s| {
4050                s.spawn(|| {
4051                    will_dirty(&[&node], || {
4052                        node.io.truncate(0).expect("truncate failed");
4053                    });
4054                });
4055
4056                // Wait for the operation to start.
4057                barrier.wait();
4058
4059                // Now the node is dirty. Fetching attributes should trigger a request.
4060                {
4061                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4062                }
4063                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 1);
4064
4065                // A second fetch should trigger another request.
4066                {
4067                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4068                }
4069                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 2);
4070
4071                // Let the operation finish.
4072                barrier.wait();
4073            });
4074
4075            // 3. Operation finished. The next fetch should trigger a request.
4076            {
4077                let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4078            }
4079            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 3);
4080
4081            // 4. Subsequent fetch should return cached info.
4082            {
4083                let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4084            }
4085            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 3);
4086        })
4087        .await;
4088
4089        server_task.await;
4090    }
4091
4092    #[::fuchsia::test]
4093    async fn test_attribute_refresh_during_concurrent_dirty_operation() {
4094        let (client, mut stream) = create_request_stream::<fio::FileMarker>();
4095        let get_attrs_started = Arc::new(Barrier::new(2));
4096        let get_attrs_started_clone = get_attrs_started.clone();
4097        let finish_get_attrs = Arc::new(Barrier::new(2));
4098        let finish_get_attrs_clone = finish_get_attrs.clone();
4099
4100        let resize_started = Arc::new(Barrier::new(2));
4101        let resize_started_clone = resize_started.clone();
4102        let finish_resize = Arc::new(Barrier::new(2));
4103        let finish_resize_clone = finish_resize.clone();
4104
4105        let get_attrs_count = Arc::new(AtomicU32::new(0));
4106        let get_attrs_count_clone = get_attrs_count.clone();
4107
4108        let server_task = fasync::Task::spawn(async move {
4109            while let Some(Ok(request)) = stream.next().await {
4110                match request {
4111                    fio::FileRequest::GetAttributes { query: _, responder } => {
4112                        let count = get_attrs_count_clone.fetch_add(1, Ordering::SeqCst);
4113                        let finish_get_attrs_clone = finish_get_attrs_clone.clone();
4114                        let get_attrs_started_clone = get_attrs_started_clone.clone();
4115
4116                        fasync::Task::spawn(async move {
4117                            if count == 0 {
4118                                fasync::unblock(move || {
4119                                    get_attrs_started_clone.wait();
4120                                    finish_get_attrs_clone.wait();
4121                                })
4122                                .await;
4123                            }
4124                            let mutable_attrs = fio::MutableNodeAttributes { ..Default::default() };
4125                            let immutable_attrs = fio::ImmutableNodeAttributes {
4126                                id: Some(1),
4127                                link_count: Some(1),
4128                                ..Default::default()
4129                            };
4130                            responder.send(Ok((&mutable_attrs, &immutable_attrs))).unwrap();
4131                        })
4132                        .detach();
4133                    }
4134                    fio::FileRequest::Resize { length: _, responder } => {
4135                        let resize_started_clone = resize_started_clone.clone();
4136                        let finish_resize_clone = finish_resize_clone.clone();
4137                        fasync::Task::spawn(async move {
4138                            fasync::unblock(move || {
4139                                resize_started_clone.wait();
4140                                finish_resize_clone.wait();
4141                            })
4142                            .await;
4143                            responder.send(Ok(())).unwrap();
4144                        })
4145                        .detach();
4146                    }
4147                    fio::FileRequest::Close { responder } => {
4148                        responder.send(Ok(())).unwrap();
4149                    }
4150                    _ => panic!("Unexpected request: {:?}", request),
4151                }
4152            }
4153        });
4154
4155        fasync::unblock(move || {
4156            let io = RemoteIo::new(client.into_channel().into());
4157            let node = BaseNode::new(io, true);
4158            let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
4159
4160            std::thread::scope(|s| {
4161                // 1. Start Refresh Thread
4162                let refresh_thread = s.spawn(|| {
4163                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4164                });
4165
4166                get_attrs_started.wait();
4167
4168                // 2. Start Dirty Thread
4169                let dirty_thread = s.spawn(|| {
4170                    will_dirty(&[&node], || {
4171                        node.io.truncate(0).expect("truncate failed");
4172                    });
4173                });
4174
4175                resize_started.wait();
4176
4177                // 3. Allow GetAttributes to finish
4178                finish_get_attrs.wait();
4179                refresh_thread.join().unwrap();
4180                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 1);
4181
4182                // 4. Refresh #2 (Should fetch because dirty op is in flight)
4183                {
4184                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4185                }
4186                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 2);
4187
4188                // 5. Allow Dirty Op to finish
4189                finish_resize.wait();
4190                dirty_thread.join().unwrap();
4191
4192                // 6. Refresh #3 (Should fetch because dirty op finished, but state was 0)
4193                {
4194                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4195                }
4196                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 3);
4197
4198                // 7. Refresh #4 (Should be cached)
4199                {
4200                    let _info = node.fetch_and_refresh_info(&info).expect("fetch failed");
4201                }
4202                assert_eq!(get_attrs_count.load(Ordering::SeqCst), 3);
4203            });
4204        })
4205        .await;
4206
4207        server_task.await;
4208    }
4209
4210    #[::fuchsia::test]
4211    async fn test_update_attributes_invalidates_cache() {
4212        let (client, mut stream) = create_request_stream::<fio::DirectoryMarker>();
4213        let get_attrs_count = Arc::new(AtomicU32::new(0));
4214        let get_attrs_count_clone = get_attrs_count.clone();
4215
4216        let server_task = fasync::Task::spawn(async move {
4217            let mut sub_tasks = Vec::new();
4218            while let Some(Ok(request)) = stream.next().await {
4219                match request {
4220                    fio::DirectoryRequest::Open { path, object, flags, .. } => {
4221                        assert_eq!(path, ".", "Unexpected open() for non-self");
4222                        let get_attrs_count = get_attrs_count_clone.clone();
4223                        sub_tasks.push(fasync::Task::spawn(async move {
4224                            let (mut stream, control_handle) =
4225                                ServerEnd::<fio::DirectoryMarker>::new(object)
4226                                    .into_stream_and_control_handle();
4227                            assert!(flags.contains(fio::Flags::FLAG_SEND_REPRESENTATION));
4228
4229                            // The Representation provides the initial attributes to cache.
4230                            let mutable_attributes =
4231                                fio::MutableNodeAttributes { ..Default::default() };
4232                            let immutable_attributes = fio::ImmutableNodeAttributes {
4233                                id: Some(1),
4234                                link_count: Some(1),
4235                                ..Default::default()
4236                            };
4237                            let info = fio::DirectoryInfo {
4238                                attributes: Some(fio::NodeAttributes2 {
4239                                    mutable_attributes,
4240                                    immutable_attributes,
4241                                }),
4242                                ..Default::default()
4243                            };
4244                            let _ = control_handle
4245                                .send_on_representation(fio::Representation::Directory(info));
4246
4247                            while let Some(Ok(request)) = stream.next().await {
4248                                match request {
4249                                    fio::DirectoryRequest::GetAttributes {
4250                                        query: _,
4251                                        responder,
4252                                    } => {
4253                                        get_attrs_count.fetch_add(1, Ordering::SeqCst);
4254                                        let mutable_attrs =
4255                                            fio::MutableNodeAttributes { ..Default::default() };
4256                                        let immutable_attrs = fio::ImmutableNodeAttributes {
4257                                            id: Some(1),
4258                                            link_count: Some(1),
4259                                            ..Default::default()
4260                                        };
4261                                        responder
4262                                            .send(Ok((&mutable_attrs, &immutable_attrs)))
4263                                            .unwrap();
4264                                    }
4265                                    fio::DirectoryRequest::UpdateAttributes {
4266                                        payload: _,
4267                                        responder,
4268                                    } => {
4269                                        responder.send(Ok(())).unwrap();
4270                                    }
4271                                    fio::DirectoryRequest::Close { responder } => {
4272                                        responder.send(Ok(())).unwrap();
4273                                    }
4274                                    _ => {
4275                                        panic!("Unexpected request: {:?}", request)
4276                                    }
4277                                }
4278                            }
4279                        }));
4280                    }
4281                    fio::DirectoryRequest::Close { responder } => {
4282                        responder.send(Ok(())).unwrap();
4283                    }
4284                    fio::DirectoryRequest::QueryFilesystem { responder } => {
4285                        responder.send(0i32, None).unwrap();
4286                    }
4287                    _ => panic!("Unexpected request: {:?}", request),
4288                }
4289            }
4290
4291            for sub_task in sub_tasks {
4292                let _ = sub_task.await;
4293            }
4294        });
4295
4296        spawn_kernel_and_run(async move |current_task| {
4297            let fs = RemoteFs::new_fs(
4298                &current_task.kernel(),
4299                client.into_channel(),
4300                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
4301                fio::PERM_READABLE | fio::PERM_WRITABLE,
4302            )
4303            .expect("failed to mount test remote FS");
4304
4305            // 1. Initial fetch. Should use cached information from OnRepresentation.
4306            {
4307                let _info =
4308                    fs.root().node.fetch_and_refresh_info(current_task).expect("fetch failed");
4309            }
4310            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 0);
4311
4312            // 2. Update attributes. This should dirty the node.
4313            fs.root()
4314                .node
4315                .update_attributes(current_task, |attrs| {
4316                    attrs.time_modify += UtcDuration::from_seconds(1);
4317                    Ok(())
4318                })
4319                .expect("update_attributes failed");
4320
4321            // 3. Fetch again. Should trigger a request.
4322            {
4323                let _info =
4324                    fs.root().node.fetch_and_refresh_info(current_task).expect("fetch failed");
4325            }
4326            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 1);
4327
4328            // 4. Subsequent fetch should use cached information.
4329            {
4330                let _info =
4331                    fs.root().node.fetch_and_refresh_info(current_task).expect("fetch failed");
4332            }
4333            assert_eq!(get_attrs_count.load(Ordering::SeqCst), 1);
4334        })
4335        .await;
4336
4337        server_task.await;
4338    }
4339
4340    trait AsyncBarrier {
4341        async fn async_wait(&self);
4342    }
4343
4344    impl AsyncBarrier for Arc<Barrier> {
4345        async fn async_wait(&self) {
4346            let this = self.clone();
4347            fasync::unblock(move || this.wait()).await;
4348        }
4349    }
4350
4351    #[derive(Default)]
4352    struct MockRemoteFs {
4353        get_attrs_count: AtomicU32,
4354        get_backing_memory_count: AtomicU32,
4355        get_xattr_count: AtomicU32,
4356        set_xattr_count: AtomicU32,
4357        file_size: AtomicUsize,
4358        write_offsets: Mutex<Vec<u64>>,
4359        open_paths: Mutex<Vec<String>>,
4360        create_selinux_contexts: Mutex<Vec<(String, Option<Vec<u8>>)>>,
4361        xattrs: Mutex<BTreeMap<Vec<u8>, Vec<u8>>>,
4362        data: Mutex<Vec<u8>>,
4363        get_attrs_hook: Mutex<Option<futures::future::BoxFuture<'static, ()>>>,
4364        write_hook: Mutex<Option<futures::future::BoxFuture<'static, ()>>>,
4365    }
4366
4367    impl MockRemoteFs {
4368        async fn handle_file_requests(
4369            self: Arc<Self>,
4370            mut stream: fio::FileRequestStream,
4371            control_handle: fio::FileControlHandle,
4372            attributes_query: fio::NodeAttributesQuery,
4373        ) {
4374            let size = self.file_size.load(Ordering::SeqCst) as u64;
4375            let selinux_context =
4376                if attributes_query.contains(fio::NodeAttributesQuery::SELINUX_CONTEXT) {
4377                    self.xattrs
4378                        .lock()
4379                        .get(b"security.selinux".as_slice())
4380                        .cloned()
4381                        .map(fio::SelinuxContext::Data)
4382                } else {
4383                    None
4384                };
4385            let info = fio::FileInfo {
4386                attributes: Some(fio::NodeAttributes2 {
4387                    mutable_attributes: fio::MutableNodeAttributes {
4388                        selinux_context,
4389                        ..Default::default()
4390                    },
4391                    immutable_attributes: fio::ImmutableNodeAttributes {
4392                        id: Some(2),
4393                        link_count: Some(1),
4394                        content_size: Some(size),
4395                        storage_size: Some(size),
4396                        ..Default::default()
4397                    },
4398                }),
4399                ..Default::default()
4400            };
4401            let _ = control_handle.send_on_representation(fio::Representation::File(info));
4402            while let Some(Ok(request)) = stream.next().await {
4403                match request {
4404                    fio::FileRequest::GetAttributes { responder, .. } => {
4405                        // Spawn a separate task so that we can handle concurrent calls.
4406                        let this = self.clone();
4407                        fasync::Task::spawn(async move {
4408                            this.get_attrs_count.fetch_add(1, Ordering::SeqCst);
4409                            let size = this.file_size.load(Ordering::SeqCst) as u64;
4410                            let hook = this.get_attrs_hook.lock().take();
4411                            if let Some(hook) = hook {
4412                                hook.await;
4413                            }
4414                            responder
4415                                .send(Ok((
4416                                    &fio::MutableNodeAttributes { ..Default::default() },
4417                                    &fio::ImmutableNodeAttributes {
4418                                        id: Some(2),
4419                                        link_count: Some(1),
4420                                        content_size: Some(size),
4421                                        storage_size: Some(size),
4422                                        ..Default::default()
4423                                    },
4424                                )))
4425                                .unwrap();
4426                        })
4427                        .detach();
4428                    }
4429                    fio::FileRequest::GetExtendedAttribute { name, responder } => {
4430                        self.get_xattr_count.fetch_add(1, Ordering::SeqCst);
4431                        match self.xattrs.lock().get(&name).cloned() {
4432                            Some(val) => {
4433                                responder.send(Ok(fio::ExtendedAttributeValue::Bytes(val))).unwrap()
4434                            }
4435                            None => responder.send(Err(zx::Status::NOT_FOUND.into_raw())).unwrap(),
4436                        }
4437                    }
4438                    fio::FileRequest::SetExtendedAttribute { name, value, responder, .. } => {
4439                        self.set_xattr_count.fetch_add(1, Ordering::SeqCst);
4440                        if let fio::ExtendedAttributeValue::Bytes(bytes) = value {
4441                            self.xattrs.lock().insert(name, bytes);
4442                        }
4443                        responder.send(Ok(())).unwrap();
4444                    }
4445                    fio::FileRequest::RemoveExtendedAttribute { name, responder } => {
4446                        if self.xattrs.lock().remove(&name).is_some() {
4447                            responder.send(Ok(())).unwrap();
4448                        } else {
4449                            responder.send(Err(zx::Status::NOT_FOUND.into_raw())).unwrap();
4450                        }
4451                    }
4452                    fio::FileRequest::ReadAt { count, offset, responder } => {
4453                        let data = self.data.lock();
4454                        let start = std::cmp::min(offset as usize, data.len());
4455                        let end = std::cmp::min(start + count as usize, data.len());
4456                        responder.send(Ok(&data[start..end])).unwrap();
4457                    }
4458                    fio::FileRequest::WriteAt { offset, data, responder, .. } => {
4459                        // Spawn a separate task so that we can test concurrent writes.
4460                        let self_clone = Arc::clone(&self);
4461                        fasync::Task::spawn(async move {
4462                            self_clone.write_offsets.lock().push(offset);
4463                            let end = offset as usize + data.len();
4464                            {
4465                                let mut mock_data = self_clone.data.lock();
4466                                if end > mock_data.len() {
4467                                    mock_data.resize(end, 0);
4468                                }
4469                                mock_data[offset as usize..end].copy_from_slice(&data);
4470                            }
4471                            let mut current_size = self_clone.file_size.load(Ordering::SeqCst);
4472                            while end > current_size {
4473                                match self_clone.file_size.compare_exchange_weak(
4474                                    current_size,
4475                                    end,
4476                                    Ordering::SeqCst,
4477                                    Ordering::SeqCst,
4478                                ) {
4479                                    Ok(_) => break,
4480                                    Err(actual) => current_size = actual,
4481                                }
4482                            }
4483                            let hook = self_clone.write_hook.lock().take();
4484                            if let Some(hook) = hook {
4485                                hook.await;
4486                            }
4487                            responder.send(Ok(data.len() as u64)).unwrap();
4488                        })
4489                        .detach();
4490                    }
4491                    fio::FileRequest::Resize { length, responder, .. } => {
4492                        self.file_size.store(length as usize, Ordering::SeqCst);
4493                        responder.send(Ok(())).unwrap();
4494                    }
4495                    fio::FileRequest::Seek { origin, offset, responder } => {
4496                        let new_offset = match origin {
4497                            fio::SeekOrigin::Start => offset as u64,
4498                            fio::SeekOrigin::Current => 0,
4499                            fio::SeekOrigin::End => {
4500                                (self.file_size.load(Ordering::SeqCst) as i64 + offset) as u64
4501                            }
4502                        };
4503                        responder.send(Ok(new_offset)).unwrap();
4504                    }
4505                    fio::FileRequest::GetBackingMemory { flags, responder } => {
4506                        self.get_backing_memory_count.fetch_add(1, Ordering::SeqCst);
4507                        let vmo = zx::Vmo::create(4096).unwrap();
4508                        // Mirror fuchsia.io servers: only grant WRITE if it was requested.
4509                        let vmo = if flags.contains(fio::VmoFlags::WRITE) {
4510                            vmo
4511                        } else {
4512                            vmo.replace_handle(zx::Rights::VMO_DEFAULT - zx::Rights::WRITE).unwrap()
4513                        };
4514                        responder.send(Ok(vmo)).unwrap();
4515                    }
4516                    fio::FileRequest::Close { responder } => {
4517                        responder.send(Ok(())).unwrap();
4518                    }
4519                    _ => {}
4520                }
4521            }
4522        }
4523
4524        fn handle_directory_requests(
4525            self: Arc<Self>,
4526            mut stream: fio::DirectoryRequestStream,
4527            control_handle: fio::DirectoryControlHandle,
4528            attributes_query: fio::NodeAttributesQuery,
4529        ) -> futures::future::BoxFuture<'static, ()> {
4530            async move {
4531                let selinux_context =
4532                    if attributes_query.contains(fio::NodeAttributesQuery::SELINUX_CONTEXT) {
4533                        self.xattrs
4534                            .lock()
4535                            .get(b"security.selinux".as_slice())
4536                            .cloned()
4537                            .map(fio::SelinuxContext::Data)
4538                    } else {
4539                        None
4540                    };
4541                let info = fio::DirectoryInfo {
4542                    attributes: Some(fio::NodeAttributes2 {
4543                        mutable_attributes: fio::MutableNodeAttributes {
4544                            selinux_context,
4545                            ..Default::default()
4546                        },
4547                        immutable_attributes: fio::ImmutableNodeAttributes {
4548                            id: Some(1),
4549                            link_count: Some(1),
4550                            protocols: Some(fio::NodeProtocolKinds::DIRECTORY),
4551                            ..Default::default()
4552                        },
4553                    }),
4554                    ..Default::default()
4555                };
4556                let _ = control_handle.send_on_representation(fio::Representation::Directory(info));
4557                let mut sub_tasks = Vec::new();
4558                while let Some(Ok(request)) = stream.next().await {
4559                    match request {
4560                        fio::DirectoryRequest::Open { path, flags, options, object, .. } => {
4561                            self.open_paths.lock().push(path.clone());
4562                            let query = options.attributes.unwrap_or_default();
4563                            if flags.intersects(
4564                                fio::Flags::FLAG_MUST_CREATE
4565                                    | fio::Flags::FLAG_CREATE_AS_UNNAMED_TEMPORARY,
4566                            ) {
4567                                let selinux_ctx = options
4568                                    .create_attributes
4569                                    .as_ref()
4570                                    .and_then(|attrs| attrs.selinux_context.as_ref())
4571                                    .and_then(|ctx| match ctx {
4572                                        fio::SelinuxContext::Data(d) => Some(d.clone()),
4573                                        _ => None,
4574                                    });
4575                                self.create_selinux_contexts
4576                                    .lock()
4577                                    .push((path.clone(), selinux_ctx));
4578                                let self_clone = Arc::clone(&self);
4579                                if flags.contains(fio::Flags::PROTOCOL_DIRECTORY) {
4580                                    sub_tasks.push(fasync::Task::spawn(async move {
4581                                        let (stream, control_handle) =
4582                                            ServerEnd::<fio::DirectoryMarker>::new(object)
4583                                                .into_stream_and_control_handle();
4584                                        self_clone
4585                                            .handle_directory_requests(
4586                                                stream,
4587                                                control_handle,
4588                                                query,
4589                                            )
4590                                            .await;
4591                                    }));
4592                                } else {
4593                                    sub_tasks.push(fasync::Task::spawn(async move {
4594                                        let (stream, control_handle) =
4595                                            ServerEnd::<fio::FileMarker>::new(object)
4596                                                .into_stream_and_control_handle();
4597                                        self_clone
4598                                            .handle_file_requests(stream, control_handle, query)
4599                                            .await;
4600                                    }));
4601                                }
4602                            } else if path == "file" {
4603                                let self_clone = Arc::clone(&self);
4604                                sub_tasks.push(fasync::Task::spawn(async move {
4605                                    let (stream, control_handle) =
4606                                        ServerEnd::<fio::FileMarker>::new(object)
4607                                            .into_stream_and_control_handle();
4608                                    self_clone
4609                                        .handle_file_requests(stream, control_handle, query)
4610                                        .await;
4611                                }));
4612                            } else if path == "dir" || path == "dir2" || path == "sub" {
4613                                let self_clone = Arc::clone(&self);
4614                                sub_tasks.push(fasync::Task::spawn(async move {
4615                                    let (stream, control_handle) =
4616                                        ServerEnd::<fio::DirectoryMarker>::new(object)
4617                                            .into_stream_and_control_handle();
4618                                    self_clone
4619                                        .handle_directory_requests(stream, control_handle, query)
4620                                        .await;
4621                                }));
4622                            } else {
4623                                let _ = ServerEnd::<fio::NodeMarker>::new(object)
4624                                    .close_with_epitaph(zx::Status::NOT_FOUND);
4625                            }
4626                        }
4627                        fio::DirectoryRequest::GetAttributes { responder, .. } => {
4628                            self.get_attrs_count.fetch_add(1, Ordering::SeqCst);
4629                            responder
4630                                .send(Ok((
4631                                    &fio::MutableNodeAttributes { ..Default::default() },
4632                                    &fio::ImmutableNodeAttributes {
4633                                        id: Some(1),
4634                                        link_count: Some(1),
4635                                        protocols: Some(fio::NodeProtocolKinds::DIRECTORY),
4636                                        ..Default::default()
4637                                    },
4638                                )))
4639                                .unwrap();
4640                        }
4641                        fio::DirectoryRequest::GetExtendedAttribute { name, responder } => {
4642                            self.get_xattr_count.fetch_add(1, Ordering::SeqCst);
4643                            match self.xattrs.lock().get(&name).cloned() {
4644                                Some(val) => responder
4645                                    .send(Ok(fio::ExtendedAttributeValue::Bytes(val)))
4646                                    .unwrap(),
4647                                None => {
4648                                    responder.send(Err(zx::Status::NOT_FOUND.into_raw())).unwrap()
4649                                }
4650                            }
4651                        }
4652                        fio::DirectoryRequest::SetExtendedAttribute {
4653                            name,
4654                            value,
4655                            responder,
4656                            ..
4657                        } => {
4658                            self.set_xattr_count.fetch_add(1, Ordering::SeqCst);
4659                            if let fio::ExtendedAttributeValue::Bytes(bytes) = value {
4660                                self.xattrs.lock().insert(name, bytes);
4661                            }
4662                            responder.send(Ok(())).unwrap();
4663                        }
4664                        fio::DirectoryRequest::RemoveExtendedAttribute { name, responder } => {
4665                            if self.xattrs.lock().remove(&name).is_some() {
4666                                responder.send(Ok(())).unwrap();
4667                            } else {
4668                                responder.send(Err(zx::Status::NOT_FOUND.into_raw())).unwrap();
4669                            }
4670                        }
4671                        fio::DirectoryRequest::Close { responder } => {
4672                            responder.send(Ok(())).unwrap();
4673                        }
4674                        _ => {}
4675                    }
4676                }
4677                for task in sub_tasks {
4678                    let _ = task.await;
4679                }
4680            }
4681            .boxed()
4682        }
4683
4684        async fn run(self: Arc<Self>, mut stream: fio::DirectoryRequestStream) {
4685            let mut sub_tasks = Vec::new();
4686            while let Some(Ok(request)) = stream.next().await {
4687                match request {
4688                    fio::DirectoryRequest::Open { path, options, object, .. } => {
4689                        if path == "." {
4690                            let query = options.attributes.unwrap_or_default();
4691                            let self_clone = Arc::clone(&self);
4692                            sub_tasks.push(fasync::Task::spawn(async move {
4693                                let (stream, control_handle) =
4694                                    ServerEnd::<fio::DirectoryMarker>::new(object)
4695                                        .into_stream_and_control_handle();
4696                                self_clone
4697                                    .handle_directory_requests(stream, control_handle, query)
4698                                    .await;
4699                            }));
4700                        }
4701                    }
4702                    fio::DirectoryRequest::Close { responder } => {
4703                        responder.send(Ok(())).unwrap();
4704                    }
4705                    fio::DirectoryRequest::QueryFilesystem { responder } => {
4706                        responder.send(0i32, None).unwrap();
4707                    }
4708                    _ => {}
4709                }
4710            }
4711            for sub_task in sub_tasks {
4712                let _ = sub_task.await;
4713            }
4714        }
4715    }
4716
4717    #[::fuchsia::test]
4718    async fn test_mknod_and_mkdir_pass_selinux_context_inline() {
4719        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
4720        let state = Arc::new(MockRemoteFs::default());
4721
4722        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
4723
4724        const TEST_POLICY: &[u8] = include_bytes!(
4725            "../../../../lib/selinux/testdata/composite_policies/compiled/bounded_transition_policy"
4726        );
4727
4728        spawn_kernel_with_selinux_and_run(async move |current_task, security_server| {
4729            security_server.set_enforcing(false);
4730            security_server.load_policy(TEST_POLICY.to_vec()).expect("policy load failed");
4731            security::selinuxfs_policy_loaded(current_task);
4732
4733            let fs = RemoteFs::new_fs(
4734                &current_task.kernel(),
4735                client.into_channel(),
4736                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
4737                fio::PERM_READABLE | fio::PERM_WRITABLE,
4738            )
4739            .expect("failed to mount test remote FS");
4740            security::file_system_resolve_security(current_task, &fs).expect("resolve fs security");
4741
4742            let ns = Namespace::new(fs);
4743            let root = ns.root();
4744
4745            let file_node = root
4746                .create_node(current_task, "new_file".into(), mode!(IFREG, 0o644), DeviceId::NONE)
4747                .expect("create_node file failed");
4748            {
4749                let _info = file_node
4750                    .entry
4751                    .node
4752                    .fetch_and_refresh_info(current_task)
4753                    .expect("fetch file info");
4754            }
4755
4756            let dir_node = root
4757                .create_node(current_task, "new_dir".into(), mode!(IFDIR, 0o755), DeviceId::NONE)
4758                .expect("create_node dir failed");
4759            {
4760                let _info = dir_node
4761                    .entry
4762                    .node
4763                    .fetch_and_refresh_info(current_task)
4764                    .expect("fetch dir info");
4765            }
4766
4767            let tmp_node = root
4768                .create_tmpfile(current_task, mode!(IFREG, 0o644), OpenFlags::RDWR)
4769                .expect("create_tmpfile failed");
4770            {
4771                let _info = tmp_node
4772                    .entry
4773                    .node
4774                    .fetch_and_refresh_info(current_task)
4775                    .expect("fetch tmpfile info");
4776            }
4777
4778            // mknod, mkdir, and create_tmpfile should all pass selinux_context inline in
4779            // create_attributes, with 0 SetExtendedAttribute RPCs and 0 GetAttributes RPCs!
4780            let created = state.create_selinux_contexts.lock().clone();
4781            assert_eq!(created.len(), 3);
4782            assert_eq!(created[0].0, "new_file");
4783            assert!(created[0].1.is_some(), "expected inline selinux_context for new_file");
4784            assert_eq!(created[1].0, "new_dir");
4785            assert!(created[1].1.is_some(), "expected inline selinux_context for new_dir");
4786            assert_eq!(created[2].0, ".");
4787            assert!(created[2].1.is_some(), "expected inline selinux_context for tmpfile");
4788            assert_eq!(state.set_xattr_count.load(Ordering::SeqCst), 0);
4789            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4790        })
4791        .await;
4792
4793        server_task.await;
4794    }
4795
4796    #[::fuchsia::test]
4797    async fn test_mknod_and_mkdir_do_not_trigger_get_attributes() {
4798        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
4799        let state = Arc::new(MockRemoteFs::default());
4800
4801        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
4802
4803        spawn_kernel_and_run(async move |current_task| {
4804            let fs = RemoteFs::new_fs(
4805                &current_task.kernel(),
4806                client.into_channel(),
4807                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
4808                fio::PERM_READABLE | fio::PERM_WRITABLE,
4809            )
4810            .expect("failed to mount test remote FS");
4811
4812            let ns = Namespace::new(fs);
4813            let root = ns.root();
4814
4815            // 1. Fetching attributes on the freshly mounted root directory should not trigger GetAttributes.
4816            {
4817                let _info =
4818                    root.entry.node.fetch_and_refresh_info(current_task).expect("fetch root info");
4819            }
4820            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4821
4822            // 2. Creating a regular file (mknod) and fetching its attributes should not trigger GetAttributes.
4823            let file_node = root
4824                .create_node(current_task, "new_file".into(), mode!(IFREG, 0o644), DeviceId::NONE)
4825                .expect("create_node file failed");
4826            {
4827                let _info = file_node
4828                    .entry
4829                    .node
4830                    .fetch_and_refresh_info(current_task)
4831                    .expect("fetch file info");
4832            }
4833            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4834
4835            // 3. Creating a directory (mkdir) and fetching its attributes should not trigger GetAttributes.
4836            let dir_node = root
4837                .create_node(current_task, "new_dir".into(), mode!(IFDIR, 0o755), DeviceId::NONE)
4838                .expect("create_node dir failed");
4839            {
4840                let _info = dir_node
4841                    .entry
4842                    .node
4843                    .fetch_and_refresh_info(current_task)
4844                    .expect("fetch dir info");
4845            }
4846            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4847
4848            // 4. Creating an unnamed temporary file (create_tmpfile) and fetching its attributes should not trigger GetAttributes.
4849            let tmp_node = root
4850                .create_tmpfile(current_task, mode!(IFREG, 0o644), OpenFlags::RDWR)
4851                .expect("create_tmpfile failed");
4852            {
4853                let _info = tmp_node
4854                    .entry
4855                    .node
4856                    .fetch_and_refresh_info(current_task)
4857                    .expect("fetch tmpfile info");
4858            }
4859            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4860        })
4861        .await;
4862
4863        server_task.await;
4864    }
4865
4866    #[::fuchsia::test]
4867    async fn test_lookup_open_counts() {
4868        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
4869        let state = Arc::new(MockRemoteFs::default());
4870
4871        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
4872
4873        spawn_kernel_and_run(async move |current_task| {
4874            let fs = RemoteFs::new_fs(
4875                &current_task.kernel(),
4876                client.into_channel(),
4877                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
4878                fio::PERM_READABLE | fio::PERM_WRITABLE,
4879            )
4880            .expect("failed to mount test remote FS");
4881
4882            let ns = Namespace::new(fs);
4883            let root = ns.root();
4884
4885            // 1. Non-existent component_lookup sends only 1 Open request (not 2).
4886            let mut context = LookupContext::default();
4887            assert_eq!(
4888                root.lookup_child(current_task, &mut context, "nonexistent".into())
4889                    .expect_err("lookup should fail with ENOENT"),
4890                errno!(ENOENT)
4891            );
4892            assert_eq!(*state.open_paths.lock(), vec!["nonexistent"]);
4893            state.open_paths.lock().clear();
4894
4895            // 2. Multi-component get_children_pipelined sends 1 pipelined Open per component.
4896            let results = root.entry.get_children_pipelined(
4897                current_task,
4898                &root.mount,
4899                &["dir".into(), "sub".into(), "file".into()],
4900            );
4901            assert_eq!(results.len(), 3);
4902            for res in &results {
4903                assert!(res.is_ok(), "expected Ok, got {res:?}");
4904            }
4905            assert_eq!(*state.open_paths.lock(), vec!["dir", "sub", "file"]);
4906            state.open_paths.lock().clear();
4907
4908            // 3. Pipelined lookup encountering ENOENT does not send duplicate Open requests.
4909            let results = root.entry.get_children_pipelined(
4910                current_task,
4911                &root.mount,
4912                &["dir2".into(), "missing".into()],
4913            );
4914            assert_eq!(results.len(), 2);
4915            assert!(results[0].is_ok());
4916            assert_eq!(results[1].as_ref().expect_err("expected ENOENT"), &errno!(ENOENT));
4917            assert_eq!(*state.open_paths.lock(), vec!["dir2", "missing"]);
4918            state.open_paths.lock().clear();
4919
4920            // 4. Re-querying a previously resolved path is served from the cache and sends no Open
4921            // requests.
4922            let results = root.entry.get_children_pipelined(
4923                current_task,
4924                &root.mount,
4925                &["dir".into(), "sub".into(), "file".into()],
4926            );
4927            assert_eq!(results.len(), 3);
4928            for res in &results {
4929                assert!(res.is_ok(), "expected Ok, got {res:?}");
4930            }
4931            assert_eq!(*state.open_paths.lock(), Vec::<String>::new());
4932        })
4933        .await;
4934
4935        server_task.await;
4936    }
4937
4938    #[::fuchsia::test]
4939    async fn test_get_size_uses_cache_unless_truncated() {
4940        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
4941        let state = Arc::new(MockRemoteFs::default());
4942
4943        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
4944
4945        spawn_kernel_and_run(async move |current_task| {
4946            let fs = RemoteFs::new_fs(
4947                &current_task.kernel(),
4948                client.into_channel(),
4949                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
4950                fio::PERM_READABLE | fio::PERM_WRITABLE,
4951            )
4952            .expect("failed to mount test remote FS");
4953
4954            let ns = Namespace::new(fs);
4955            let root = ns.root();
4956
4957            let mut context = LookupContext::default();
4958            let file_node = root
4959                .lookup_child(current_task, &mut context, "file".into())
4960                .expect("lookup failed");
4961
4962            // 1. Initial get_size.
4963            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4964            {
4965                let _size = file_node.entry.node.get_size(current_task).expect("get_size failed");
4966            }
4967            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4968
4969            // 2. Open in append mode and write.
4970            let file_handle = file_node
4971                .open(current_task, OpenFlags::RDWR | OpenFlags::APPEND)
4972                .expect("open failed");
4973
4974            {
4975                let mut data = VecInputBuffer::new(b"foo");
4976                let written = file_handle.write(current_task, &mut data).expect("write failed");
4977                assert_eq!(written, 3);
4978            }
4979            assert_eq!(file_node.entry.node.get_size(current_task).expect("get_size failed"), 3);
4980            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 0);
4981            assert_eq!(*state.write_offsets.lock(), vec![0]);
4982
4983            // 3. Truncate. This should invalidate the cache.
4984            file_node
4985                .entry
4986                .node
4987                .truncate(current_task, &file_node.mount, 0)
4988                .expect("truncate failed");
4989            assert_eq!(state.file_size.load(Ordering::SeqCst), 0);
4990
4991            // 4. get_size again. Should trigger a request.
4992            {
4993                let size = file_node.entry.node.get_size(current_task).expect("get_size failed");
4994                assert_eq!(size, 0);
4995            }
4996            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 1);
4997
4998            // 5. Append again. It should append at offset 0.
4999            {
5000                let mut data = VecInputBuffer::new(b"bar");
5001                let written = file_handle.write(current_task, &mut data).expect("write failed");
5002                assert_eq!(written, 3);
5003            }
5004            assert_eq!(file_node.entry.node.get_size(current_task).expect("get_size failed"), 3);
5005            // write calls seek(End, 0) which calls get_size, which uses the cache if it was just
5006            // refreshed.
5007            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 1);
5008            assert_eq!(*state.write_offsets.lock(), vec![0, 0]);
5009
5010            // 6. Truncate to 10 and append.
5011            file_node
5012                .entry
5013                .node
5014                .truncate(current_task, &file_node.mount, 10)
5015                .expect("truncate failed");
5016            {
5017                let mut data = VecInputBuffer::new(b"baz");
5018                let written = file_handle.write(current_task, &mut data).expect("write failed");
5019                assert_eq!(written, 3);
5020            }
5021            // write calls seek(End, 0). Since truncate was called, cache is invalid.
5022            assert_eq!(state.get_attrs_count.load(Ordering::SeqCst), 2);
5023            assert_eq!(file_node.entry.node.get_size(current_task).expect("get_size failed"), 13);
5024            assert_eq!(*state.write_offsets.lock(), vec![0, 0, 10]);
5025        })
5026        .await;
5027
5028        server_task.await;
5029    }
5030
5031    #[::fuchsia::test]
5032    async fn test_get_size_during_refresh_after_truncate() {
5033        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
5034        let state = Arc::new(MockRemoteFs::default());
5035
5036        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
5037
5038        spawn_kernel_and_run(async move |current_task| {
5039            let fs = RemoteFs::new_fs(
5040                &current_task.kernel(),
5041                client.into_channel(),
5042                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
5043                fio::PERM_READABLE | fio::PERM_WRITABLE,
5044            )
5045            .expect("failed to mount test remote FS");
5046
5047            let ns = Namespace::new(fs);
5048            let root = ns.root();
5049
5050            let mut context = LookupContext::default();
5051            let file_node = root
5052                .lookup_child(current_task, &mut context, "file".into())
5053                .expect("lookup failed");
5054
5055            // Fill cache.
5056            assert_eq!(file_node.entry.node.get_size(current_task).expect("get_size failed"), 0);
5057
5058            // Truncate to 10.
5059            file_node
5060                .entry
5061                .node
5062                .truncate(current_task, &file_node.mount, 10)
5063                .expect("truncate failed");
5064
5065            // Set barrier to pause GetAttributes.
5066            let barrier = Arc::new(Barrier::new(2));
5067            {
5068                let barrier = barrier.clone();
5069                *state.get_attrs_hook.lock() = Some(Box::pin(async move {
5070                    barrier.async_wait().await;
5071                    barrier.async_wait().await;
5072                }));
5073            }
5074
5075            // Spawn thread to call get_size. It will pause when it hits the first barrier.
5076            let file_node_clone = file_node.clone();
5077            let (result1, request) = SpawnRequestBuilder::new()
5078                .with_sync_closure(move |current_task| {
5079                    let size =
5080                        file_node_clone.entry.node.get_size(current_task).expect("get_size failed");
5081                    assert_eq!(size, 10);
5082                })
5083                .build_with_async_result();
5084            current_task.kernel().kthreads.spawner().spawn_from_request(request);
5085
5086            // Wait for the first barrier to be reached.
5087            barrier.async_wait().await;
5088
5089            // Set up the next request so it unblocks the first request.
5090            *state.get_attrs_hook.lock() =
5091                Some(Box::pin(async move { barrier.async_wait().await }));
5092
5093            // Another get_size call should not use cached size (0) while refresh is in progress.
5094            let (result2, request) = SpawnRequestBuilder::new()
5095                .with_sync_closure(move |current_task| {
5096                    let size =
5097                        file_node.entry.node.get_size(current_task).expect("get_size failed");
5098                    assert_eq!(size, 10);
5099                })
5100                .build_with_async_result();
5101            current_task.kernel().kthreads.spawner().spawn_from_request(request);
5102
5103            result1.await.unwrap();
5104            result2.await.unwrap();
5105        })
5106        .await;
5107
5108        server_task.await;
5109    }
5110
5111    #[::fuchsia::test]
5112    async fn test_get_size_during_outstanding_write() {
5113        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
5114        let state = Arc::new(MockRemoteFs::default());
5115
5116        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
5117
5118        spawn_kernel_and_run(async move |current_task| {
5119            let fs = RemoteFs::new_fs(
5120                &current_task.kernel(),
5121                client.into_channel(),
5122                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
5123                fio::PERM_READABLE | fio::PERM_WRITABLE,
5124            )
5125            .expect("failed to mount test remote FS");
5126
5127            let ns = Namespace::new(fs);
5128            let root = ns.root();
5129
5130            let mut context = LookupContext::default();
5131            let file_node = root
5132                .lookup_child(current_task, &mut context, "file".into())
5133                .expect("lookup failed");
5134
5135            // Open the file.
5136            let file_handle = file_node.open(current_task, OpenFlags::RDWR).expect("open failed");
5137
5138            // Set hook to stall the write response.
5139            let barrier = Arc::new(Barrier::new(2));
5140            {
5141                let barrier = barrier.clone();
5142                *state.write_hook.lock() = Some(Box::pin(async move {
5143                    barrier.async_wait().await;
5144                    barrier.async_wait().await;
5145                }));
5146            }
5147
5148            // Start write in another thread.
5149            let file_handle_clone = file_handle.clone();
5150            current_task.kernel().kthreads.spawner().spawn_from_request(
5151                SpawnRequestBuilder::new()
5152                    .with_sync_closure(move |current_task| {
5153                        let mut data = VecInputBuffer::new(b"hello");
5154                        file_handle_clone.write(current_task, &mut data).expect("write failed");
5155                    })
5156                    .build(),
5157            );
5158
5159            // Wait until the mock has processed the write and hit the hook.
5160            barrier.async_wait().await;
5161
5162            // On this thread, verify that a read sees the new data.
5163            {
5164                let mut data = VecOutputBuffer::new(5);
5165                let read = file_handle.read_at(current_task, 0, &mut data).expect("read failed");
5166                assert_eq!(read, 5);
5167                assert_eq!(data.data(), b"hello");
5168            }
5169
5170            // Now call get_size and it should see the correct size.
5171            let size = file_node.entry.node.get_size(current_task).expect("get_size failed");
5172            assert_eq!(
5173                size, 5,
5174                "get_size should return the updated size even if a write is outstanding"
5175            );
5176
5177            // Unblock the write.
5178            barrier.async_wait().await;
5179        })
5180        .await;
5181
5182        server_task.await;
5183    }
5184
5185    #[test]
5186    fn test_info_state_initial_state() {
5187        let state = InfoState::new(true); // dirty
5188        assert_eq!(state.0.load(Ordering::Relaxed), 0);
5189
5190        let state = InfoState::new(false); // in sync
5191        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::IN_SYNC);
5192    }
5193
5194    #[test]
5195    fn test_info_state_dirty_op_guard() {
5196        let state = InfoState::new(false);
5197        {
5198            let _guard = state.dirty_op_guard(false);
5199            assert_eq!(state.0.load(Ordering::Relaxed), 1); // IN_SYNC bit cleared, count 1
5200            assert!(!state.is_size_accurate());
5201        }
5202        assert_eq!(state.0.load(Ordering::Relaxed), 0);
5203        assert!(state.is_size_accurate());
5204
5205        {
5206            let _guard = state.dirty_op_guard(true);
5207            assert_eq!(state.0.load(Ordering::Relaxed), InfoState::TRUNCATED | 1);
5208            assert!(!state.is_size_accurate());
5209        }
5210        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::TRUNCATED);
5211        assert!(!state.is_size_accurate());
5212
5213        {
5214            let _guard1 = state.dirty_op_guard(true);
5215            let _guard2 = state.dirty_op_guard(true);
5216            assert_eq!(state.0.load(Ordering::Relaxed), InfoState::TRUNCATED | 2);
5217            assert!(!state.is_size_accurate());
5218        }
5219        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::TRUNCATED);
5220        assert!(!state.is_size_accurate());
5221    }
5222
5223    #[test]
5224    fn test_info_state_refresh_clears_truncated() {
5225        let state = InfoState::new(true);
5226        // Set TRUNCATED bit.
5227        {
5228            let _guard = state.dirty_op_guard(true);
5229        }
5230        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::TRUNCATED);
5231
5232        let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
5233        state.maybe_refresh(&info, |_| Ok(()), |_| unreachable!()).unwrap();
5234
5235        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::IN_SYNC);
5236        assert!(state.is_size_accurate());
5237    }
5238
5239    #[test]
5240    fn test_info_state_maybe_refresh_success() {
5241        let state = InfoState::new(true);
5242        let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
5243
5244        let res = state.maybe_refresh(&info, |_| Ok(42), |_| unreachable!());
5245        assert_eq!(res.unwrap(), 42);
5246        assert_eq!(state.0.load(Ordering::Relaxed), InfoState::IN_SYNC);
5247    }
5248
5249    #[test]
5250    fn test_info_state_maybe_refresh_error() {
5251        let state = InfoState::new(true);
5252        let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
5253
5254        let res: Result<u32, Errno> =
5255            state.maybe_refresh(&info, |_| error!(EIO), |_| unreachable!());
5256        assert!(res.is_err());
5257        assert_eq!(state.0.load(Ordering::Relaxed), 0); // Still dirty
5258    }
5259
5260    #[test]
5261    fn test_info_state_maybe_refresh_not_needed() {
5262        let state = InfoState::new(false); // in sync
5263        let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
5264        let res = state.maybe_refresh(&info, |_| unreachable!(), |_| Ok(123));
5265        assert_eq!(res.unwrap(), 123);
5266    }
5267
5268    #[test]
5269    fn test_info_state_concurrent_dirty_op_during_refresh() {
5270        let state = InfoState::new(true);
5271        let info = DynamicLockDepRwLock::new::<FsNodeInfoLevel>(FsNodeInfo::default());
5272
5273        state
5274            .maybe_refresh(
5275                &info,
5276                |_| {
5277                    // Simulate a dirty op starting while refresh is in progress
5278                    let _guard = state.dirty_op_guard(false);
5279                    assert_eq!(state.0.load(Ordering::Relaxed), InfoState::PENDING_REFRESH | 1);
5280                    Ok(())
5281                },
5282                |_| unreachable!(),
5283            )
5284            .unwrap();
5285
5286        assert_eq!(state.0.load(Ordering::Relaxed), 0);
5287    }
5288
5289    #[::fuchsia::test]
5290    async fn test_sync() {
5291        let fixture = TestFixture::new().await;
5292        let (server, client) = zx::Channel::create();
5293        fixture.root().clone(server.into()).expect("clone failed");
5294
5295        spawn_kernel_and_run(async move |current_task| {
5296            let kernel = current_task.kernel();
5297            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
5298            let fs = RemoteFs::new_fs(
5299                &kernel,
5300                client,
5301                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
5302                rights,
5303            )
5304            .expect("new_fs failed");
5305            let ns = Namespace::new(fs);
5306            current_task.fs().set_umask(FileMode::from_bits(0));
5307            let root = ns.root();
5308
5309            const REG_MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits());
5310            root.create_node(&current_task, "file".into(), REG_MODE, DeviceId::NONE)
5311                .expect("create_node failed");
5312            let mut context = LookupContext::new(SymlinkMode::NoFollow);
5313            let reg_node = root
5314                .lookup_child(&current_task, &mut context, "file".into())
5315                .expect("lookup_child failed");
5316
5317            // sync should delegate to zxio and succeed
5318            reg_node
5319                .entry
5320                .node
5321                .ops()
5322                .sync(&reg_node.entry.node, &current_task)
5323                .expect("sync failed");
5324        })
5325        .await;
5326        fixture.close().await;
5327    }
5328
5329    #[::fuchsia::test]
5330    async fn test_msync_propagates_to_fxfs() {
5331        use crate::mm::MemoryAccessor;
5332        use crate::mm::syscalls::{sys_mmap, sys_msync};
5333        use crate::vfs::FdFlags;
5334        use starnix_uapi::user_address::UserAddress;
5335        use starnix_uapi::{MAP_SHARED, MS_SYNC, PROT_READ, PROT_WRITE};
5336
5337        // Counter to track Fxfs transactions
5338        let commit_count = Arc::new(AtomicUsize::new(0));
5339        let commit_count_clone = commit_count.clone();
5340
5341        let (mut hooks, fs_hooks) = fxfs_testing::Hooks::new();
5342        hooks.set_pre_commit(move |_transaction| {
5343            commit_count_clone.fetch_add(1, Ordering::SeqCst);
5344            Ok(())
5345        });
5346
5347        // Open fixture with hooks
5348        let fixture = TestFixture::open(
5349            DeviceHolder::new(FakeDevice::new(1024 * 1024, 512)),
5350            TestFixtureOptions {
5351                format: true,
5352                as_blob: false,
5353                encrypted: true,
5354                hooks: Some(fs_hooks),
5355                ..Default::default()
5356            },
5357        )
5358        .await;
5359
5360        let (server, client) = zx::Channel::create();
5361        fixture.root().clone(server.into()).expect("clone channel");
5362
5363        spawn_kernel_and_run(async move |current_task| {
5364            // Setup RemoteFs
5365            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
5366            let fs = RemoteFs::new_fs(
5367                current_task.kernel(),
5368                client,
5369                FileSystemOptions { source: FlyByteStr::new(b"/test"), ..Default::default() },
5370                rights,
5371            )
5372            .expect("new_fs");
5373            let ns = Namespace::new(fs);
5374            let root = ns.root();
5375
5376            // Create and Open a file
5377            let node = root
5378                .create_node(&current_task, "test_file".into(), mode!(IFREG, 0o666), DeviceId::NONE)
5379                .expect("create_node");
5380            let file_handle = node.open(&current_task, OpenFlags::RDWR).expect("open");
5381            let fd = current_task.add_file(file_handle, FdFlags::empty()).expect("add file");
5382
5383            // Do mmap
5384            let len = *PAGE_SIZE as usize * 4;
5385            let mmap_addr = sys_mmap(
5386                current_task,
5387                UserAddress::default(),
5388                len,
5389                PROT_READ | PROT_WRITE,
5390                MAP_SHARED,
5391                fd,
5392                0,
5393            )
5394            .expect("mmap");
5395
5396            // Modify memory (multiple pages)
5397            for i in 0..4 {
5398                let data = [0xAAu8; 1];
5399                current_task
5400                    .write_memory((mmap_addr + (i * *PAGE_SIZE as usize)).unwrap(), &data)
5401                    .expect("write memory");
5402            }
5403
5404            // Capture commit count before msync
5405            let commits_before_msync = commit_count.load(Ordering::SeqCst);
5406
5407            // invoke msync()
5408            sys_msync(current_task, mmap_addr, len, MS_SYNC).expect("msync");
5409
5410            // Verify msync results
5411            let final_commits = commit_count.load(Ordering::SeqCst);
5412            assert!(
5413                final_commits > commits_before_msync,
5414                "msync should trigger Fxfs transaction. commits: {} -> {}",
5415                commits_before_msync,
5416                final_commits
5417            );
5418        })
5419        .await;
5420
5421        fixture.close().await;
5422    }
5423
5424    #[::fuchsia::test]
5425    async fn test_get_size() {
5426        let fixture = TestFixture::new().await;
5427        let (server, client) = zx::Channel::create();
5428        fixture.root().clone(server.into()).expect("clone failed");
5429
5430        spawn_kernel_and_run(async move |current_task| {
5431            let kernel = current_task.kernel();
5432            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
5433            let fs = RemoteFs::new_fs(
5434                &kernel,
5435                client,
5436                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
5437                rights,
5438            )
5439            .expect("new_fs failed");
5440            let ns = Namespace::new(fs);
5441            let root = ns.root();
5442
5443            const REG_MODE: FileMode = FileMode::from_bits(FileMode::IFREG.bits() | 0o666);
5444            let node = root
5445                .create_node(&current_task, "file".into(), REG_MODE, DeviceId::NONE)
5446                .expect("create_node failed");
5447            let file = node.open(&current_task, OpenFlags::RDWR).expect("open failed");
5448
5449            // Initial size should be 0.
5450            assert_eq!(node.entry.node.get_size(&current_task).expect("get_size failed"), 0);
5451
5452            // Write some data.
5453            let mut data = VecInputBuffer::new(b"hello");
5454            file.write(&current_task, &mut data).expect("write failed");
5455
5456            // Size should be 5.
5457            assert_eq!(node.entry.node.get_size(&current_task).expect("get_size failed"), 5);
5458
5459            // Truncate to 10.
5460            node.truncate(&current_task, 10).expect("truncate failed");
5461
5462            // Size should be 10.
5463            assert_eq!(node.entry.node.get_size(&current_task).expect("get_size failed"), 10);
5464
5465            // Truncate to 3.
5466            node.truncate(&current_task, 3).expect("truncate failed");
5467
5468            // Size should be 3.
5469            assert_eq!(node.entry.node.get_size(&current_task).expect("get_size failed"), 3);
5470        })
5471        .await;
5472        fixture.close().await;
5473    }
5474
5475    #[fuchsia::test]
5476    async fn test_remote_fs_casefold_not_supported_on_non_fxfs() {
5477        spawn_kernel_and_run(async |current_task| {
5478            let kernel = current_task.kernel();
5479            let rights = fio::PERM_READABLE | fio::PERM_EXECUTABLE;
5480            let (server, client) = zx::Channel::create();
5481            fdio::open("/pkg", rights, server).expect("failed to open /pkg");
5482            let fs = RemoteFs::new_fs(
5483                &kernel,
5484                client,
5485                FileSystemOptions { source: FlyByteStr::new(b"/pkg"), ..Default::default() },
5486                rights,
5487            )
5488            .unwrap();
5489            let ns = Namespace::new(fs);
5490            let root = ns.root();
5491
5492            assert!(!root.entry.node.fs().has_casefold_support());
5493            assert_eq!(
5494                root.entry.node.update_attributes(&current_task, |info| {
5495                    info.casefold = true;
5496                    Ok(())
5497                }),
5498                error!(ENOTSUP)
5499            );
5500            assert_eq!(root.entry.set_casefold(&current_task, true), error!(ENOTSUP));
5501        })
5502        .await;
5503    }
5504
5505    #[fuchsia::test]
5506    async fn test_remote_fs_casefold_supported_on_fxfs() {
5507        let fixture = TestFixture::new().await;
5508        let (server, client) = zx::Channel::create();
5509        fixture.root().clone(server.into()).expect("clone failed");
5510
5511        spawn_kernel_and_run(async move |current_task| {
5512            let kernel = current_task.kernel();
5513            let rights = fio::PERM_READABLE | fio::PERM_WRITABLE;
5514            let fs = RemoteFs::new_fs(
5515                &kernel,
5516                client,
5517                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
5518                rights,
5519            )
5520            .expect("new_fs failed");
5521            let ns = Namespace::new(fs);
5522            let root = ns.root();
5523
5524            assert!(root.entry.node.fs().has_casefold_support());
5525
5526            // Casefold can be enabled on an empty directory.
5527            assert_eq!(root.entry.set_casefold(&current_task, true), Ok(()));
5528            assert!(root.entry.node.info().casefold);
5529
5530            // Enabling casefold when already enabled is idempotent.
5531            assert_eq!(root.entry.set_casefold(&current_task, true), Ok(()));
5532
5533            // Adding a child makes the directory non-empty.
5534            root.create_node(&current_task, "child".into(), FileMode::IFREG, DeviceId::NONE)
5535                .expect("create child");
5536
5537            // Toggling casefold on a non-empty directory returns ENOTEMPTY.
5538            assert_eq!(root.entry.set_casefold(&current_task, false), error!(ENOTEMPTY));
5539        })
5540        .await;
5541
5542        fixture.close().await;
5543    }
5544
5545    #[::fuchsia::test]
5546    async fn test_close_flushes_written_file() {
5547        use crate::vfs::FdFlags;
5548
5549        let commits = Arc::new(AtomicUsize::new(0));
5550        let commits_clone = commits.clone();
5551        let (mut hooks, fs_hooks) = fxfs_testing::Hooks::new();
5552        hooks.set_pre_commit(move |_transaction| {
5553            commits_clone.fetch_add(1, Ordering::SeqCst);
5554            Ok(())
5555        });
5556        let fixture = TestFixture::open(
5557            DeviceHolder::new(FakeDevice::new(16384, 512)),
5558            TestFixtureOptions { hooks: Some(fs_hooks), ..Default::default() },
5559        )
5560        .await;
5561        let (server, client) = zx::Channel::create();
5562        fixture.root().clone(server.into()).expect("clone failed");
5563
5564        spawn_kernel_and_run(async move |current_task| {
5565            let fs = RemoteFs::new_fs(
5566                current_task.kernel(),
5567                client,
5568                FileSystemOptions { source: FlyByteStr::new(b"/"), ..Default::default() },
5569                fio::PERM_READABLE | fio::PERM_WRITABLE,
5570            )
5571            .expect("new_fs failed");
5572            let ns = Namespace::new(fs);
5573            let file = ns
5574                .root()
5575                .create_node(&current_task, "file".into(), mode!(IFREG, 0o666), DeviceId::NONE)
5576                .expect("create_node failed")
5577                .open(&current_task, OpenFlags::RDWR)
5578                .expect("open failed");
5579            file.write(&current_task, &mut VecInputBuffer::new(b"hello")).expect("write failed");
5580            let fd = current_task.add_file(file, FdFlags::empty()).expect("add_file failed");
5581
5582            // close(2), without fsync, should make Fxfs flush (commit) the file's data.
5583            let commits_before_close = commits.load(Ordering::SeqCst);
5584            current_task.files().close(fd).expect("close failed");
5585            current_task.trigger_delayed_releaser();
5586            assert!(commits.load(Ordering::SeqCst) > commits_before_close);
5587        })
5588        .await;
5589        fixture.close().await;
5590    }
5591
5592    #[derive(Clone, Default)]
5593    struct MockSyncDirectory;
5594
5595    impl SyncIoDirectory for MockSyncDirectory {
5596        fn seek(&self, _new_index: u64) -> Result<u64, zx::Status> {
5597            Ok(0)
5598        }
5599        fn readdir<B, S: FnMut(u64, fio::DirentType, &[u8]) -> ControlFlow<B, ()>>(
5600            &self,
5601            _sink: S,
5602        ) -> Result<Option<B>, zx::Status> {
5603            Ok(None)
5604        }
5605        fn sync(&self) -> Result<(), zx::Status> {
5606            Ok(())
5607        }
5608        fn clone_proxy(&self) -> Result<Option<fio::DirectorySynchronousProxy>, zx::Status> {
5609            Ok(None)
5610        }
5611    }
5612
5613    #[derive(Clone, Default)]
5614    struct MockSyncIo {
5615        id: u64,
5616    }
5617
5618    impl SyncIo for MockSyncIo {
5619        type Directory = MockSyncDirectory;
5620
5621        fn attr_get(
5622            &self,
5623            _query: fio::NodeAttributesQuery,
5624        ) -> Result<(fio::MutableNodeAttributes, fio::ImmutableNodeAttributes), zx::Status>
5625        {
5626            Ok((
5627                fio::MutableNodeAttributes {
5628                    mode: Some(FileMode::IFDIR.bits() | 0o755),
5629                    ..Default::default()
5630                },
5631                fio::ImmutableNodeAttributes {
5632                    id: Some(self.id),
5633                    protocols: Some(fio::NodeProtocolKinds::DIRECTORY),
5634                    ..Default::default()
5635                },
5636            ))
5637        }
5638
5639        fn attr_set(&self, _attributes: fio::MutableNodeAttributes) -> Result<(), zx::Status> {
5640            Ok(())
5641        }
5642
5643        fn query_filesystem(&self) -> Result<fio::FilesystemInfo, zx::Status> {
5644            Ok(fio::FilesystemInfo {
5645                total_bytes: 1024 * 1024,
5646                used_bytes: 4096,
5647                total_nodes: 1000,
5648                used_nodes: 10,
5649                free_shared_pool_bytes: 0,
5650                fs_id: 42,
5651                block_size: 4096,
5652                max_filename_size: 255,
5653                fs_type: fidl_fuchsia_fs::VfsType::Fxfs.into_primitive(),
5654                padding: 0,
5655                name: [0; 32],
5656            })
5657        }
5658
5659        fn open<F: sync_io_client::Factory<Self>>(
5660            &self,
5661            _path: &str,
5662            _flags: fio::Flags,
5663            _attributes: Option<fio::MutableNodeAttributes>,
5664            _query: fio::NodeAttributesQuery,
5665            factory: F,
5666        ) -> Result<F::Result, zx::Status> {
5667            Ok(factory.create_directory(
5668                MockSyncIo { id: self.id },
5669                fio::DirectoryInfo {
5670                    attributes: Some(fio::NodeAttributes2 {
5671                        mutable_attributes: fio::MutableNodeAttributes {
5672                            mode: Some(FileMode::IFDIR.bits() | 0o755),
5673                            ..Default::default()
5674                        },
5675                        immutable_attributes: fio::ImmutableNodeAttributes {
5676                            id: Some(self.id),
5677                            protocols: Some(fio::NodeProtocolKinds::DIRECTORY),
5678                            ..Default::default()
5679                        },
5680                    }),
5681                    ..Default::default()
5682                },
5683            ))
5684        }
5685
5686        fn open_pipelined<F: sync_io_client::Factory<Self>>(
5687            &self,
5688            _paths: &[&str],
5689            _flags: fio::Flags,
5690            _query: fio::NodeAttributesQuery,
5691            _create_factory: impl FnMut() -> F,
5692        ) -> impl Iterator<Item = Result<F::Result, zx::Status>> {
5693            std::iter::empty()
5694        }
5695
5696        fn link_into(&self, _target_dir: &Self, _name: &str) -> Result<(), zx::Status> {
5697            Err(zx::Status::NOT_SUPPORTED)
5698        }
5699
5700        fn unlink(&self, _name: &str, _flags: fio::UnlinkFlags) -> Result<(), zx::Status> {
5701            Err(zx::Status::NOT_SUPPORTED)
5702        }
5703
5704        fn rename(
5705            &self,
5706            _old_path: &str,
5707            _new_dir: &Self,
5708            _new_path: &str,
5709        ) -> Result<(), zx::Status> {
5710            Err(zx::Status::NOT_SUPPORTED)
5711        }
5712
5713        fn create_symlink(&self, _name: &str, _target: &[u8]) -> Result<Self, zx::Status> {
5714            Err(zx::Status::NOT_SUPPORTED)
5715        }
5716
5717        fn read_partial(&self, _offset: u64, _max: usize) -> Result<(Vec<u8>, bool), zx::Status> {
5718            Err(zx::Status::NOT_SUPPORTED)
5719        }
5720
5721        fn write(&self, _offset: u64, _data: &[u8]) -> Result<usize, zx::Status> {
5722            Err(zx::Status::NOT_SUPPORTED)
5723        }
5724
5725        fn supports_vectored(&self) -> bool {
5726            false
5727        }
5728
5729        unsafe fn readv(
5730            &self,
5731            _offset: u64,
5732            _iovecs: &mut [zx::sys::zx_iovec_t],
5733        ) -> Result<usize, zx::Status> {
5734            Err(zx::Status::NOT_SUPPORTED)
5735        }
5736
5737        fn writev(
5738            &self,
5739            _offset: u64,
5740            _iovecs: &[zx::sys::zx_iovec_t],
5741        ) -> Result<usize, zx::Status> {
5742            Err(zx::Status::NOT_SUPPORTED)
5743        }
5744
5745        fn truncate(&self, _length: u64) -> Result<(), zx::Status> {
5746            Err(zx::Status::NOT_SUPPORTED)
5747        }
5748
5749        fn vmo_get(&self, _flags: zx::VmarFlags) -> Result<zx::Vmo, zx::Status> {
5750            Err(zx::Status::NOT_SUPPORTED)
5751        }
5752
5753        fn sync(&self) -> Result<(), zx::Status> {
5754            Ok(())
5755        }
5756
5757        fn enable_verity(
5758            &self,
5759            _descriptor: &zxio_fsverity_descriptor_t,
5760        ) -> Result<(), zx::Status> {
5761            Err(zx::Status::NOT_SUPPORTED)
5762        }
5763
5764        fn allocate(
5765            &self,
5766            _offset: u64,
5767            _length: u64,
5768            _mode: syncio::AllocateMode,
5769        ) -> Result<(), zx::Status> {
5770            Err(zx::Status::NOT_SUPPORTED)
5771        }
5772
5773        fn xattr_get(&self, _name: &[u8]) -> Result<Vec<u8>, zx::Status> {
5774            Err(zx::Status::NOT_SUPPORTED)
5775        }
5776
5777        fn xattr_set(
5778            &self,
5779            _name: &[u8],
5780            _value: &[u8],
5781            _mode: syncio::XattrSetMode,
5782        ) -> Result<(), zx::Status> {
5783            Err(zx::Status::NOT_SUPPORTED)
5784        }
5785
5786        fn xattr_remove(&self, _name: &[u8]) -> Result<(), zx::Status> {
5787            Err(zx::Status::NOT_SUPPORTED)
5788        }
5789
5790        fn xattr_list(&self) -> Result<Vec<Vec<u8>>, zx::Status> {
5791            Ok(vec![])
5792        }
5793
5794        fn open_directory(&self) -> Result<Self::Directory, zx::Status> {
5795            Ok(MockSyncDirectory)
5796        }
5797    }
5798
5799    #[::fuchsia::test]
5800    async fn test_remote_fs_new_with_mock_sync_io() {
5801        spawn_kernel_and_run(async |current_task| {
5802            let kernel = current_task.kernel();
5803            let mock_io = MockSyncIo { id: 1001 };
5804            let (remotefs, root_node, info, node_id) = RemoteFs::new_with_io(
5805                mock_io,
5806                fio::PERM_READABLE | fio::PERM_WRITABLE,
5807                "mock_remotefs",
5808            )
5809            .expect("new_with_io failed");
5810            assert_eq!(node_id, 1001);
5811            assert!(remotefs.use_remote_ids());
5812            assert_eq!(remotefs.name(), "mock_remotefs");
5813
5814            let fs = FileSystem::new(
5815                kernel,
5816                CacheMode::Uncached,
5817                remotefs,
5818                FileSystemOptions::default(),
5819            )
5820            .expect("FileSystem::new failed");
5821            fs.create_root_with_info(node_id, root_node, info);
5822
5823            let root_entry = fs.root();
5824            let file =
5825                root_entry.open_anonymous(&current_task, OpenFlags::RDONLY).expect("open failed");
5826            let stat = fs.statfs(&current_task).expect("statfs failed");
5827            assert_eq!(stat.f_bsize as u64, 4096);
5828            assert_eq!(stat.f_blocks, 256); // 1024 * 1024 / 4096
5829
5830            // Check to_handle falls back when clone_proxy returns None
5831            let handle = file.to_handle(&current_task).expect("to_handle failed");
5832            assert!(handle.is_some());
5833        })
5834        .await;
5835    }
5836
5837    #[::fuchsia::test]
5838    async fn test_get_memory_cached_across_opens_and_exec() {
5839        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
5840        let state = Arc::new(MockRemoteFs::default());
5841
5842        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
5843
5844        spawn_kernel_and_run(async move |current_task| {
5845            let fs = RemoteFs::new_fs(
5846                &current_task.kernel(),
5847                client.into_channel(),
5848                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
5849                fio::PERM_READABLE | fio::PERM_WRITABLE,
5850            )
5851            .expect("failed to mount test remote FS");
5852
5853            let ns = Namespace::new(fs);
5854            let root = ns.root();
5855
5856            let mut context = LookupContext::default();
5857            let file_node = root
5858                .lookup_child(current_task, &mut context, "file".into())
5859                .expect("lookup failed");
5860
5861            let file1 = file_node.open(current_task, OpenFlags::RDONLY).expect("open 1 failed");
5862            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 0);
5863
5864            let ro_mem1 = file1
5865                .get_memory(current_task, None, ProtectionFlags::READ)
5866                .expect("get_memory READ failed");
5867            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 1);
5868
5869            // Requesting READ | EXEC should derive the executable VMO from the cached READ VMO
5870            // without making another GetBackingMemory FIDL call.
5871            let rx_mem1 = file1
5872                .get_memory(current_task, None, ProtectionFlags::READ | ProtectionFlags::EXEC)
5873                .expect("get_memory READ|EXEC failed");
5874            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 1);
5875            assert!(rx_mem1.get_rights().contains(zx::Rights::EXECUTE));
5876            assert!(!rx_mem1.get_rights().contains(zx::Rights::WRITE));
5877
5878            drop(file1);
5879
5880            // Opening the same file node again should reuse the cached VMOs on RemoteNode.
5881            let file2 = file_node.open(current_task, OpenFlags::RDONLY).expect("open 2 failed");
5882            let ro_mem2 = file2
5883                .get_memory(current_task, None, ProtectionFlags::READ)
5884                .expect("get_memory READ 2 failed");
5885            let rx_mem2 = file2
5886                .get_memory(current_task, None, ProtectionFlags::READ | ProtectionFlags::EXEC)
5887                .expect("get_memory READ|EXEC 2 failed");
5888            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 1);
5889            assert!(Arc::ptr_eq(&ro_mem1, &ro_mem2));
5890            assert!(Arc::ptr_eq(&rx_mem1, &rx_mem2));
5891        })
5892        .await;
5893
5894        server_task.await;
5895    }
5896
5897    #[::fuchsia::test]
5898    async fn test_get_memory_exec_first_fetches_directly() {
5899        let (client, stream) = create_request_stream::<fio::DirectoryMarker>();
5900        let state = Arc::new(MockRemoteFs::default());
5901
5902        let server_task = fasync::Task::spawn(Arc::clone(&state).run(stream));
5903
5904        spawn_kernel_and_run(async move |current_task| {
5905            let fs = RemoteFs::new_fs(
5906                &current_task.kernel(),
5907                client.into_channel(),
5908                FileSystemOptions { source: FlyByteStr::new(b"."), ..Default::default() },
5909                fio::PERM_READABLE | fio::PERM_WRITABLE,
5910            )
5911            .expect("failed to mount test remote FS");
5912
5913            let ns = Namespace::new(fs);
5914            let root = ns.root();
5915
5916            let mut context = LookupContext::default();
5917            let file_node = root
5918                .lookup_child(current_task, &mut context, "file".into())
5919                .expect("lookup failed");
5920            let file = file_node.open(current_task, OpenFlags::RDONLY).expect("open failed");
5921
5922            // With no cached READ VMO to derive from, READ | EXEC is fetched directly and does
5923            // not populate the READ cache (so exec-only files hold a single VMO handle).
5924            let rx_mem = file
5925                .get_memory(current_task, None, ProtectionFlags::READ | ProtectionFlags::EXEC)
5926                .expect("get_memory READ|EXEC failed");
5927            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 1);
5928            assert!(rx_mem.get_rights().contains(zx::Rights::EXECUTE));
5929            assert!(!rx_mem.get_rights().contains(zx::Rights::WRITE));
5930
5931            let ro_mem = file
5932                .get_memory(current_task, None, ProtectionFlags::READ)
5933                .expect("get_memory READ failed");
5934            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 2);
5935            assert!(!ro_mem.get_rights().contains(zx::Rights::EXECUTE));
5936
5937            // Both handles are now cached on the node.
5938            let rx_mem2 = file
5939                .get_memory(current_task, None, ProtectionFlags::READ | ProtectionFlags::EXEC)
5940                .expect("get_memory READ|EXEC 2 failed");
5941            let ro_mem2 = file
5942                .get_memory(current_task, None, ProtectionFlags::READ)
5943                .expect("get_memory READ 2 failed");
5944            assert_eq!(state.get_backing_memory_count.load(Ordering::SeqCst), 2);
5945            assert!(Arc::ptr_eq(&rx_mem, &rx_mem2));
5946            assert!(Arc::ptr_eq(&ro_mem, &ro_mem2));
5947        })
5948        .await;
5949
5950        server_task.await;
5951    }
5952}