# StrataFS

> Peios kernel stratafs documentation.

---

# Overview

_Peios Kernel / Internals / StrataFS / Start here_

> stratafs presents an ordered set of existing directories as one tree — where it sits, the model it follows, and what it delegates.

<a id="trm-4-1"></a>

stratafs presents an ordered set of existing directories — its
**strata**, or layers, which give it its name — as one merged
directory tree. Each stratum is an ordinary
directory on an ordinary filesystem, owned and written by whatever
agent owns it, with no coordination with stratafs and no notification
to it. The merged view reflects changes to any stratum without a
remount. <a id="cite-mount.reflects-stratum-changes"></a>

It is a stacking filesystem in the strict sense: it stores no file
data, no directory entries, and no security descriptors. Every object
reachable through a stratafs mount is a real object on a real stratum,
and every data and metadata operation is performed against that object. <a id="cite-model.every-object-is-real"></a>
stratafs inodes carry no address-space operations, so there is no
second page cache to keep coherent; reads, writes, mappings and splices
are forwarded to a backing file opened on the provider.

Unlike overlayfs, stratafs has **no whiteouts and no opaque-directory
markers**. There is no mechanism anywhere in the filesystem for
recording that a name should be absent. That single omission accounts
for most of what is unusual about it: removing a name can leave the
name visible, some names cannot be removed at all, and several
operations that succeed on an ordinary filesystem are refused here
rather than faked. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) collects the consequences.

<a id="trm-4-1-1"></a>

## Where it sits <a id="cite-mount.superblock-identity"></a>

stratafs lives in `fs/stratafs`, alongside PKM. It is built by `CONFIG_STRATAFS_FS` — a boolean option, so it
is linked into `vmlinux` — and registered by an `fs_initcall`. The
option depends on `CONFIG_SECURITY_PKM`, because stratafs reaches KACS
for every access decision and for the whole of the copy-up context.
That reach is through `<linux/kacs_stratafs.h>`, a kernel-private
header in `include/linux` whose symbols are deliberately not exported
to modules. This is a private in-kernel integration interface, not a
userspace API.

The filesystem type registers under the name `stratafs`, with the
superblock magic `0x53545241` — ASCII `STRA` — and the flags
`FS_USERNS_MOUNT` and `FS_RENAME_DOES_D_MOVE`. It takes no device;
superblocks come from `get_tree_nodev`, so the device identifier
reported for every object in a mount is an anonymous one belonging to
the mount rather than to any stratum.

A small part of the filesystem is written in Rust. The crate
`stratafs-core` compiles the sources in `security/pkm/stratafs_core`
and holds three pure, allocation-free decisions: validating the
stack-wide flag rules, selecting the provider from a presence bitmap,
and routing one modifying operation. Everything else — the VFS glue,
resolution, enumeration, copy-up — is C.

<a id="trm-4-1-2"></a>

## The model <a id="cite-strata.identified-by-path"></a>

A mount is defined by its **stratum stack**: an ordered list of strata,
highest-precedence first, fixed for the life of the mount. A stratum is
identified by its **path**, not by the directory that path resolved to
at mount time, which is what allows a package transaction to replace a
whole stratum by renaming trees around underneath a live mount.

For a given name in a given directory, the **provider** is the
highest-precedence stratum that holds it. A name whose provider is a
directory, and which lower strata also hold as a directory, resolves to
a **merged directory** whose entries are the union of theirs. A name
whose provider is anything else masks every lower entry of that name
completely, subtree and all.

At most one stratum carries the `create` flag. That **create stratum**
receives newly created objects and is the destination of **copy-up** —
the replication of an object into the create stratum so that a
modification can be applied without touching the stratum that provides
it. A stack may have no create stratum, in which case nothing can be
created and nothing copied up.

Routing a modification is a decision about strata alone. It happens
when the modifying operation is performed, never at open, and it never
consults the caller: by the time an operation reaches stratafs, KACS
has already decided the caller was entitled to perform it. [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) sets
out why no other formulation is implementable.

<a id="trm-4-1-3"></a>

## What it delegates

stratafs holds no security descriptors, so it makes no access
decisions of its own about the objects it presents. The descriptor
evaluated for an operation is the one on the object the operation will
be performed against, and KACS reads it through the ordinary
extended-attribute path, which the stacking layer forwards down to the
provider. A stratafs mount cannot grant access its provider stratum
would refuse.

A merged directory is the exception, because it stands for several
real directories with several descriptors and forwarding yields only
the provider's. Those checks stratafs performs itself, against every
participating directory, requiring all of them to succeed ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)).

Copy-up is the other exception, in the opposite direction. It is
machinery serving an operation that was already authorised, not an
operation a caller requests, so it must introduce no new checks against
whichever task happens to execute it. KACS provides a kernel-internal
copy-up context for exactly this, described in full at [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>); [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)
covers the stratafs half.

<a id="trm-4-1-4"></a>

## This chapter

[The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>) covers the stack, the mount options that define it, what a
mounter must be entitled to, and absent strata. [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>) covers resolution:
providers, merging, type conflicts, and enumeration. [The Coherency Model](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-1>) covers
coherency — how uncoordinated change is observed, and the inode
identity presented over it. [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) covers mutation: routing, copy-up,
creation, removal, rename, links, locking and durability. [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>) covers
the security seam with KACS, and [The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>) the one interface stratafs
synthesises for userspace. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) collects the failure modes, including
the divergences from ordinary filesystem behaviour that follow from
having no whiteouts, and [Constants](</kernel/internals/stratafs/start-here/generated-constants.md#trm-4-a>) the constants.

## Mounting and testing

See [StrataFS mount options](</kernel/administration/stratafs/mount-options.md>) for operation, and [StrataFS test hooks](</kernel/development/native-subsystems/stratafs-test-hooks.md>) for development.

## Topics

- [Security](</kernel/internals/stratafs/security/overview.md>)
- [Mutation](</kernel/internals/stratafs/mutation/overview.md>)
- [Strata and mounting](</kernel/internals/stratafs/strata-and-mounting/overview.md>)
- [Name resolution](</kernel/internals/stratafs/name-resolution/overview.md>)
- [Coherency](</kernel/internals/stratafs/coherency/overview.md>)

---

# The Origin Attribute

_Peios Kernel / Internals / StrataFS / Start here_

> The one synthetic extended attribute that reveals which stratum provided a merged path — its value, constraints and access rules.

<a id="trm-4-7"></a>

A merged path does not reveal which stratum provided it. stratafs
exposes that through one synthetic extended attribute,
`system.stratafs.origin`, and deliberately through nothing else — a
tool that instead re-implemented [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>)'s resolution rules against the
strata would be a second implementation of them, and would eventually
disagree with the first.

Together with the mount table ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)), which gives the stratum stack,
it is enough to explain any path in a mount without privilege beyond
what reading the path itself requires.

<a id="trm-4-7-1"></a>

## The value

Reading the attribute returns the absolute path of the object that
provides it:

- For a **non-directory**, the provider's path in its stratum. <a id="cite-origin.value.non-directory"></a>
- For a **merged directory**, the paths of every participating
  directory in precedence order, separated by newlines. <a id="cite-origin.value.merged-directory"></a>

Each element is the stratum's own path, then a `/` where the relative
part is non-empty and the base does not already end in one, then the
relative path. <a id="cite-origin.value.element-format"></a> Within a path, a newline or a backslash is escaped by a
preceding backslash; those two are the whole escape set, and the `/`
stratafs itself inserts is not escaped. <a id="cite-origin.value.escaping"></a> Stratum paths are absolute
because the mount parser required them to be ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)).

There is no trailing newline and no trailing NUL. <a id="cite-origin.value.no-trailing-terminator"></a> A null buffer returns
the length required; an undersized one returns `ERANGE`. <a id="cite-origin.value.sizing"></a>

The value is synthesised at each read from the current resolution. It
is not stored, and it is not the value of any attribute on any stratum. <a id="cite-origin.value.synthesised-per-read"></a>
Because non-root dentries are always invalidated ([Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>)), a read by
path always reflects a fresh resolution.

<a id="trm-4-7-2"></a>

## Constraints

The attribute is not settable. Any set or removal in the reserved
namespace fails with `EPERM`, before the provider is reached at all. <a id="cite-origin.not-settable"></a>

It is not reported by an attribute listing. The listing handler filters
reserved names out of both its sizing pass and its copy pass, and the
synthetic name is never added to any listing. <a id="cite-origin.hidden-from-listing"></a> Hiding it keeps
archivers, copy tools and backup software from discovering it,
attempting to preserve it, and failing.

The whole `system.stratafs.` namespace is reserved. No read, write or
removal of any name in it is forwarded to the provider: a read of any
name other than `origin` returns `ENODATA`, and a write or removal
returns `EPERM`. <a id="cite-origin.namespace-reserved"></a> Where a provider object carries a real attribute of
one of these names, it is masked — the synthesised value is returned
instead, and the provider's attribute is absent from listings through
the mount. <a id="cite-origin.masks-provider-attribute"></a>

Two details of the implementation are worth stating exactly. The
namespace test is a fixed-length prefix comparison against
`system.stratafs.` including the trailing dot, so the bare name
`system.stratafs` is *not* reserved and would be forwarded to the
provider. <a id="cite-origin.bare-name-not-reserved"></a> And the reserved set is one name wider than the namespace
suggests: the staging marker attribute,
`security.peios.stratafs_staging`, receives the same treatment —
`EPERM` to write, `ENODATA` to read, hidden from listings, masked from
providers — despite lying outside the `system.stratafs.` namespace. <a id="cite-origin.staging-marker-reserved"></a>

<a id="trm-4-7-3"></a>

## Access

Reading the attribute requires the access that reading an extended
attribute of the object requires, and is refused where that would be
refused. <a id="cite-origin.requires-read-ea"></a> The right to read the object's stat attributes is not
sufficient: the request is for the read-EA right, which KACS's
`getxattr` hook demands on the stratafs dentry before stratafs's own
handler runs.

For a merged directory the value names every participating directory,
so it discloses more than any one of them. Reading it requires that
access on **every** participating directory and is refused where any
refuses — the same intersection [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) applies to enumeration, and for
the same reason: a caller who may not know a restricted directory
participates must not learn it from this attribute. <a id="cite-origin.merged-requires-all-participants"></a>

Where the attribute is read **through a directory descriptor**, the
participating set is the one settled when that descriptor was opened
([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)), and the value names that set rather than the current one. <a id="cite-origin.fd.settled-participant-set"></a> The
access decision was likewise made at open and is recorded on the
dentry, so the read consults a stored verdict rather than re-checking. <a id="cite-origin.fd.access-decided-at-open"></a>
A stratum that has joined since is not disclosed, because the check
that would have covered it was never run; a settled participant that
has since ceased to hold the directory is still named, for the same
reason.

Where it is read **by path**, the participating set is the current one,
resolved afresh, and the read-EA right is required against each of its
members at that moment. <a id="cite-origin.by-path.current-participant-set"></a>

---

# Failure Modes

_Peios Kernel / Internals / StrataFS / Start here_

> Every condition under which a stratafs operation fails and the error it produces, from mount time through resolution and mutation.

<a id="trm-4-8"></a>

This section consolidates the conditions under which a stratafs
operation fails and the error each produces. The sections above remain
authoritative for the conditions themselves.

<a id="trm-4-8-1"></a>

## Mount-time

| Condition | Error |
|---|---|
| Caller lacks the access to resolve a stratum path or read its attributes | `EACCES` |
| Empty stratum stack, or `strata=` absent | `EINVAL` |
| Stack longer than 16 strata | `EINVAL` |
| More than one stratum carries `create` | `EINVAL` |
| A stratum carries both `create` and `ro` | `EINVAL` |
| The same directory appears twice in the stack | `EINVAL` |
| Any malformed `strata=` value ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` |
| A remount's `strata=` differs from the mounted stack ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` |
| An allocation failure while parsing | `ENOMEM` |
| A create-bearing stack established outside the initial user namespace, or without `CAP_SYS_ADMIN` there | `EPERM` |
| A stratum path names a non-directory | `ENOTDIR` |
| A stratum is absent without `am` | `ENOENT` |
| A stratum lies within the mount point, or within another stratafs mount whose strata include this mount point | `ELOOP` |
| The composed stack reaches the kernel's maximum stacking depth | `ELOOP` |
| Sixteen consecutive collisions allocating a mount cookie | `EAGAIN` |

The option-only conditions are decided before any path is touched, and
the `EPERM` admission test before any path is resolved. <a id="cite-failure.mount.option-checks-precede-path-checks"></a> The per-path
conditions follow. [Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>) records the one place the specified ordering
is not achieved.

<a id="trm-4-8-2"></a>

## Resolution

| Condition | Error |
|---|---|
| No participating stratum holds the name | `ENOENT` |
| An ancestor of the path is masked by a non-directory provider | `ENOTDIR` |
| Operation requires a non-directory; provider is a directory | `EISDIR` |
| Traverse or list refused on any participating directory | `EACCES` |
| A stratum walk fails for a reason other than absence | that error |
| A joined stratum path or child relative path exceeds `PATH_MAX` | `ENAMETOOLONG` |
| A task re-enters the same superblock while resolving | `ELOOP` |

<a id="trm-4-8-3"></a>

## Mutation

| Condition | Error |
|---|---|
| Provider will not accept modification, and no create stratum has higher precedence | `EROFS` |
| Any mutation on a read-only-mounted stratafs | `EROFS` |
| Creation, unnamed-file creation, or unnamed-file link with no create stratum, or it absent | `EROFS` |
| Create stratum holds a path component as a non-directory | `ENOTDIR` |
| Exclusive creation where any stratum holds the name | `EEXIST` |
| Copy-up cannot preserve an extended attribute | `EIO` |
| Copy-up cannot preserve the descriptor | `EACCES`, `EOPNOTSUPP`, `EINVAL`, `ESTALE` or `ENOMEM`, as KACS reported it |
| Copy-up for a descriptor whose object is no longer the provider, or whose target name is taken at publication | `ESTALE` |
| Copy-up of a device node, FIFO or socket | `EROFS` |
| Unlink where the provider will not accept modification | `EROFS`, or `EPERM` where the provider inode is immutable |
| Rmdir where another stratum holds entries within | `ENOTEMPTY` |
| Rmdir or directory rename where list is refused on a participant | `EACCES` |
| Modifying a special file's mode, descriptor or extended attributes where its provider will not accept modification | `EROFS` |
| Establishing a shared write-capable mapping where routing yields read-only | `EROFS` |
| A route change after shared mapping preparation could require another copy-up | `EAGAIN`; retry the whole `mmap` call |
| StrataFS or FUSE passthrough layers exceed the supported stacking depth during shared mapping preparation | `ELOOP` |
| Replacing disposition where [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) would refuse the removal, or where a stratum above the create stratum would still hold the name | `EROFS` |
| Replacing disposition on anything but a regular file | `EOPNOTSUPP` |
| Rename where the source's provider will not accept modification | `EROFS` |
| Rename where a stratum above the source's provider provides the destination | `EROFS` |
| Rename where the source's provider does not hold the destination's directory | `EXDEV` |
| Rename of a directory containing entries from other strata | `EXDEV` |
| Rename of a non-directory onto a directory provider | `EISDIR` |
| Rename of a directory onto a non-directory provider | `ENOTDIR` |
| Rename onto a destination directory not empty across every stratum | `ENOTEMPTY` |
| `RENAME_NOREPLACE` where any stratum holds the destination | `EEXIST` |
| `RENAME_EXCHANGE` where the two names are not provided by one stratum that accepts modification | `EROFS` |
| `RENAME_EXCHANGE` where another stratum holds entries under either directory name | `EXDEV` |
| `RENAME_WHITEOUT` | `EINVAL` |
| Hard link whose source's provider will not accept modification, or does not hold the destination's directory | `EXDEV` |
| Hard link where any stratum holds the destination | `EEXIST` |
| Linking an unnamed file into a different mount | `EXDEV` |
| A dentry whose private state is missing, or whose provider identity no longer matches | `ESTALE` |
| `ioctl` on a regular file | `ENOTTY`, or `ENOIOCTLCMD` for the compat form |
| `remap_file_range` with flags outside dedupe and advisory | `EINVAL` |

Shared mapping preparation can publish a copy-up before a later mapping
check fails. That copy remains published; the mapping failure does not
restore the earlier provider. Copies completed by earlier layers also
remain if preparation fails deeper in the backing chain.

<a id="trm-4-8-4"></a>

## Interface

| Condition | Error |
|---|---|
| Set or remove of any reserved attribute | `EPERM` |
| Read of a reserved attribute other than `origin` | `ENODATA` |
| Origin read where read-EA is refused on any participant | `EACCES` |
| Origin read into an undersized buffer | `ERANGE` |
| Freezing the filesystem | `EOPNOTSUPP` |
| Reading a mount's policy without TCB privilege | refused by KACS |

<a id="trm-4-8-5"></a>

## Intended divergences

None of the following is a defect. Each is described above, and each
follows from stratafs having no way to record that a name should be
absent, or from a merged path standing for objects in more than one
stratum.

- **Removing a name may not remove it from the view.** Where a lower
  stratum also holds the name, it becomes the provider and the name
  remains, now resolving to different content ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)).
- **A name may be unremovable.** Where the provider will not accept
  modification, removal fails however the caller is privileged
  ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)).
- **Rename may be refused for an unmodified file.** Where the source's
  provider will not accept modification, rename fails rather than
  silently copying ([Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>)).
- **Hard links may be refused within one directory.** Where the
  source's provider will not accept modification, linking fails with
  `EXDEV` ([Links](</kernel/internals/stratafs/mutation/links.md#trm-4-5-6>)).
- **An object's inode number may change.** Where the provider for a
  path changes, a new inode is presented ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **Two callers may hold non-contending locks on one path.** Locks are
  held on the object a descriptor resolved to, so callers who opened
  either side of a change of provider — including one caused by a
  copy-up neither of them performed — have locked different objects
  ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).
- **Copy-up severs hard links.** Two names that shared an object in a
  lower stratum, and compared equal by inode number, refer to different
  objects once one of them is written through the mount; only the
  written one is copied up ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
- **An open may succeed where the first write then fails.** Routing
  happens when a modifying operation is performed, not at open, so an
  open for writing against a provider that will not accept modification
  succeeds and the `EROFS` arrives at the write, the truncate, or the
  attempt to establish a shared writable mapping ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).
- **A copy-up moves an object out from under descriptors already open
  on it.** Only the descriptor whose operation caused the copy-up refers
  to the copy; others continue to refer to the original, and locks held
  on it stay there ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>), [Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).
- **A write may fail `ESTALE` on a descriptor that was valid when
  opened.** Where another descriptor, another mount, or a direct writer
  has since caused that name to be provided by a different object, a
  copy-up cannot proceed and the caller must reopen ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
- **`fstat` and `stat` may report different inode numbers for one
  file.** After a copy-up, the descriptor that caused it keeps the inode
  it was opened against while a fresh resolution of the path yields a
  new one, so the two disagree for as long as that descriptor lives —
  though both name the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **A directory's link count is always 1.** The true count of
  subdirectories spans strata and cannot be maintained ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **Directory positions do not survive a reopen.** A `readdir` offset
  is an ordinal into a per-descriptor capture, carrying no provider
  cookie ([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)).

Every one of the first four is the result of refusing to invent a
hidden record — a whiteout — that would make an entry in someone else's
directory unreachable without their knowledge. The alternative buys
POSIX fidelity at the cost of a stratum no longer meaning what its
owner wrote in it, which is the property [The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>) exists to protect.

---

# Generated constants

_Peios Kernel / Internals / StrataFS / Start here_

> Every stratafs constant — filesystem identity, stratum flags, extended attributes, copy-up and staging markers — generated from the source.

<a id="trm-4-a"></a>

Every value below is generated from the source by
`tools/docs/peios-reference/generators/gen-stratafs-constants.py`. Nothing here is transcribed by
hand, and the generator's `--check` mode fails if the two drift apart. <a id="cite-const.generated-from-source"></a>

<a id="trm-4-a-1"></a>

## Filesystem identity <a id="cite-const.magic-alias-shared-with-kacs"></a>

| Constant              | Value        | Meaning                                         |
|-----------------------|--------------|-------------------------------------------------|
| `STRATAFS_MAGIC`      | `0x53545241` | Superblock magic, reported by `statfs` ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) |
| `STRATAFS_NAME`       | `"stratafs"` | The name the filesystem registers under         |
| `STRATAFS_MAX_STRATA` | `16`         | Longest stratum stack accepted ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>))         |

`STRATAFS_MAGIC` is an alias for `STRATAFS_SUPER_MAGIC`, which is
declared in the header stratafs shares with KACS so that the mount
policy class keyed on it cannot drift ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)).

<a id="trm-4-a-2"></a>

## Stratum flags

| Constant            | Value | Meaning                    |
|---------------------|-------|----------------------------|
| `STRATAFS_F_CREATE` | `0x1` | The `create` flag ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)) |
| `STRATAFS_F_RO`     | `0x2` | The `ro` flag              |
| `STRATAFS_F_AM`     | `0x4` | The `am` flag              |

<a id="trm-4-a-3"></a>

## Extended attributes

| Constant                 | Value                               | Meaning                                                  |
|--------------------------|-------------------------------------|----------------------------------------------------------|
| `STRATAFS_XATTR_PREFIX`  | `"system.stratafs."`                | Reserved namespace; never forwarded to a provider ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) |
| `STRATAFS_XATTR_ORIGIN`  | `"system.stratafs.origin"`          | Synthetic, read-only, hidden from listings ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>))        |
| `STRATAFS_XATTR_STAGING` | `"security.peios.stratafs_staging"` | Copy-up staging marker; also reserved ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>))           |

`STRATAFS_XATTR_STAGING` is an alias for `STRATAFS_STAGING_XATTR`,
declared in the shared header. Note the name it resolves to lies
outside the reserved `system.stratafs.` namespace, yet receives the
same treatment ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)).

The canonical security-descriptor attribute is KACS's, not
stratafs's; stratafs only detects it in order to exclude it from
copy-up replication ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)).

<a id="trm-4-a-4"></a>

## Copy-up and staging

| Constant                        | Value                | Meaning                                     |
|---------------------------------|----------------------|---------------------------------------------|
| `STRATAFS_STAGE_MARKER_MAGIC`   | `0x53544731`         | Marker magic                                |
| `STRATAFS_STAGE_MARKER_VERSION` | `1`                  | Marker version                              |
| `STRATAFS_COPY_BUFFER_SIZE`     | `65536`              | Copy-up read/write chunk, in bytes ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)) |
| `STRATAFS_STAGE_PREFIX`         | `".stratafs-stage-"` | Staged-name prefix                          |
| `STRATAFS_RECOVERY_BATCH`       | `128`                | Names scanned per staging-recovery pass     |

<a id="trm-4-a-4-1"></a>

### The staging marker <a id="cite-const.stage-marker-layout"></a>

`struct stratafs_stage_marker` is packed and 24 bytes, all fields
little-endian. It is the value of the staging attribute above.

| Offset | Size | Field          | Type     |
|--------|------|----------------|----------|
| 0      | 4    | `magic`        | `__le32` |
| 4      | 2    | `version`      | `__le16` |
| 6      | 2    | `size`         | `__le16` |
| 8      | 8    | `boot_cookie`  | `__le64` |
| 16     | 8    | `mount_cookie` | `__le64` |

<a id="trm-4-a-5"></a>

## Routing <a id="cite-const.route-discriminants-match-rust"></a>

The value `route_existing` returns ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), as the Rust decision
core names it and as the C glue mirrors it. The discriminants match.

| C enumerator               | Value | Rust       |
|----------------------------|-------|------------|
| `STRATAFS_ROUTE_IN_PLACE`  | `0`   | `InPlace`  |
| `STRATAFS_ROUTE_COPY_UP`   | `1`   | `CopyUp`   |
| `STRATAFS_ROUTE_READ_ONLY` | `2`   | `ReadOnly` |

<a id="trm-4-a-6"></a>

## The decision core

`stratafs-core` holds the stack-wide flag rules, provider selection,
and routing. Its flag bits match the C ones above exactly. <a id="cite-const.core-flag-bits-match-c"></a>

| Constant          | Value |
|-------------------|-------|
| `MAX_STRATA`      | `16`  |
| `FLAG_CREATE`     | `0x1` |
| `FLAG_READ_ONLY`  | `0x2` |
| `FLAG_ABSENT_MAY` | `0x4` |
| `FLAG_MASK`       | `0x7` |

The crate distinguishes these configuration errors. The C boundary
collapses all of them to `EINVAL`, so the distinction is not
observable to a caller ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)). <a id="cite-const.config-errors-collapse-to-einval"></a>

| Error            | Discriminant |
|------------------|--------------|
| `Empty`          | `1`          |
| `TooMany`        | `2`          |
| `UnknownFlag`    | `3`          |
| `RepeatedCreate` | `4`          |
| `CreateReadOnly` | `5`          |

<a id="trm-4-a-7"></a>

## Build configuration <a id="cite-const.build-kconfig-option"></a>

stratafs is built by `CONFIG_STRATAFS_FS`, a boolean option, so what it
builds is linked into `vmlinux` rather than loaded. It depends on
`CONFIG_SECURITY_PKM` and selects `FS_STACK`. Its sources are staged
into the kernel tree as `fs/stratafs`, separate from PKM's own
`security/pkm`. `CONFIG_STRATAFS_FS_TEST_HOOKS` compiles the test rendezvous and fail points ([Stratum flags](</kernel/internals/stratafs/start-here/generated-constants.md#trm-4-a-2>)),
inert unless the kernel is booted with `stratafs.test_hooks=1`. `CONFIG_STRATAFS_KUNIT_TEST` builds the in-kernel unit tests.

The translation units are:

- `super.o`
- `lookup.o`
- `inode.o`
- `file.o`
- `dir.o`
- `dir_cache.o`
- `xattr.o`
- `copy_up.o`

---

# Security

_Peios Kernel / Internals / StrataFS / Security_

> Find the Peios kernel articles about security.

Use these articles to understand security in the Peios kernel.

- [KACS admission and object phases](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md>)
- [Copy-up descriptors](</kernel/internals/stratafs/security/copy-up-descriptors.md>)
- [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md>)
- [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md>)
- [Mount Policy](</kernel/internals/stratafs/security/mount-policy.md>)
- [Audit](</kernel/internals/stratafs/security/audit.md>)

---

# KACS admission and object phases

_Peios Kernel / Internals / StrataFS / Security_

> KACS admission and object phases: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7"></a>

StrataFS copy-up is the internal realisation of an operation already
authorized against a StrataFS handle — not a second caller-requested
operation. KACS therefore provides a kernel-internal context so that
the mechanics of copy-up introduce no new rights checks against the
task that happens to execute them.

The context exempts **KACS caller authorization only**. It does not
replace credentials, borrow an identity, grant a privilege, bypass
another LSM, neutralise an underlying filesystem check, make a
read-only mount writable, or suppress immutable, append-only, quota,
space, I/O or format errors. <a id="cite-facs.stratafs-copy-up.exempts-kacs-only"></a> Every exemption is a return before the
authorize call, and every mutation still goes through the ordinary
`vfs_*` path under `mnt_want_write()`. <a id="cite-facs.stratafs-copy-up.mutations-via-vfs"></a>

<a id="trm-3-9-7-1"></a>

## Admission and lifetime

Only the in-kernel StrataFS implementation can create or enter a
context. There is no userspace surface of any kind — no ABI, file
descriptor, token, ioctl, syscall or securityfs control — and the
copy-up API is declared in a kernel-private header with no exported
symbols. <a id="cite-facs.stratafs-copy-up.no-userspace-surface"></a>

A context is created only after the StrataFS operation requiring
copy-up has passed its complete outer authorization. KACS does not
verify that: the context creation call performs no check, and the
ordering is satisfied by StrataFS calling in the right order. <a id="cite-facs.stratafs-copy-up.creation-performs-no-check"></a> The
context is not itself an alternative authorization path.

The exemption covers namespace creation the outer handle authorises
without an add-entry right on the create stratum, so the context is
reachable only from a create-enabled mount established by a caller
holding `CAP_SYS_ADMIN` in the **initial** user namespace. That
closure rests on an explicit test of the mounter's user namespace at
stack establishment — the capability half contributes nothing to it,
because the KACS switchboard discards the target namespace and answers
from `SeTcbPrivilege` alone ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)). The check is made when the
immutable stack is established rather than when a copy-up runs, so
descriptor delegation cannot reintroduce acting-task authorization.
Reconfiguration cannot re-supply the strata list.

A context attaches to at most one task, and a task carries at most
one. <a id="cite-facs.stratafs-copy-up.one-context-per-task"></a> It is not inherited by `fork()`, `clone()` or `execve()` — exec
explicitly clears it. <a id="cite-facs.stratafs-copy-up.not-inherited"></a> A refcounted context can be transferred to a
kernel worker, but the originating task leaves it first. <a id="cite-facs.stratafs-copy-up.worker-transfer"></a> Leaving,
task exit, every error path, and completion all remove the attachment
and clear any armed phase. <a id="cite-facs.stratafs-copy-up.detach-clears-phase"></a>

The interface fails closed on nesting, concurrent attachment, a stale
phase, or an object mismatch. <a id="cite-facs.stratafs-copy-up.fails-closed-on-misuse"></a> A mismatched operation is evaluated
normally and neither consumes nor broadens the armed exemption. <a id="cite-facs.stratafs-copy-up.mismatch-evaluated-normally"></a>

<a id="trm-3-9-7-2"></a>

## Object and phase binding

Creation pins the exact provider path, its current inode, a complete
validated copy of its effective descriptor, and the provider-visible
`security.capability` value or its absence. <a id="cite-facs.stratafs-copy-up.creation-pins-provider"></a> Every later positive path
is paired with a pinned inode as well — retaining a dentry alone is
insufficient, because an unlink followed by recreation can
reinstantiate it over a different inode. <a id="cite-facs.stratafs-copy-up.paths-paired-with-inode"></a>

One phase is armed at a time: <a id="cite-facs.stratafs-copy-up.one-phase-armed"></a>

| Phase | Objects admitted |
|---|---|
| Source read | The pinned provider only. |
| Create | One pinned provider, one destination parent, and either one named negative dentry or one anonymous creation in that parent. Used for both parent materialisation and the staged object. |
| Populate | The pinned provider and the one staged object bound to the context. |
| Publish by link | The bound staged object, one destination parent, one absent destination dentry. |
| Publish by rename | The bound staged object and its parent, one destination parent, one absent destination dentry. |
| Cleanup | One bound staging or materialisation dentry and its exact parent. |
| Orphan cleanup | One positive provider dentry carrying an authenticated stale staging marker, and its exact parent. |
| Orphan-marker cleanup | The exact positive provider dentry whose authenticated stale marker is being removed after publication. |

Path, dentry, inode, parent, object type and operation kind are all
compared wherever the hook supplies them — and path comparison
includes the mount, so the same dentry reached through a different
mount of the same superblock does not match. <a id="cite-facs.stratafs-copy-up.match-includes-mount"></a> An inode-only hook can
match the pinned inode, but that does not authorize a pathname
operation on another dentry, and a phase never acts as a wildcard for
other objects of the same filesystem or directory. <a id="cite-facs.stratafs-copy-up.no-wildcard-matching"></a>

The staged binding stays valid only while its dentry names the pinned
inode under the pinned staging parent, and that parent still names its
own pinned inode. A rename or parent substitution invalidates the
populate, protected-metadata and publish exemptions even when the
staged dentry and inode are themselves unchanged. <a id="cite-facs.stratafs-copy-up.rename-invalidates-binding"></a>

Named creation is bound to the exact final component. <a id="cite-facs.stratafs-copy-up.named-creation-exact-component"></a> Anonymous
creation is bound to its parent, expected object type, the attached
task, and the single armed create phase — and once created, the
anonymous object has to be bound as the staged object before populate,
publish or cleanup can use it. <a id="cite-facs.stratafs-copy-up.anonymous-must-be-bound"></a>

Where the destination is a stacking filesystem creating a real inode
below the armed destination dentry, the transition is authenticated at
the exact outer dentry, and only the one subsequent real-inode
security initialisation of the expected type receives the pinned
provider descriptor. <a id="cite-facs.stratafs-copy-up.stacking-transition-authenticated"></a> The real inode is not the staged binding: the
outer inode is separately anchored, through the matching post-create
event for an anonymous object or an explicit confirmation of the exact
positive outer dentry for a named one. A missing, repeated, mismatched
or out-of-order transition fails closed, and an inner post-create
event from the real filesystem is rejected as the outer anchor by
superblock comparison. <a id="cite-facs.stratafs-copy-up.transition-out-of-order-fails"></a>

KACS retains the exact path, inode, parent path and parent inode of
every named object whose creation it admits. Cleanup can be armed only
for one of those or for the exact bound staging object; an unrelated
positive dentry fails with `ESTALE`. <a id="cite-facs.stratafs-copy-up.cleanup-victim-restricted"></a> The cleanup setup call is not
itself authority to choose a deletion victim.

After an atomic rename or link publishes the staged inode, the staging
identity can be rebound to the published path, but only while mount,
inode, parent dentry and pinned parent inode all still match. <a id="cite-facs.stratafs-copy-up.rebind-conditions"></a> The
rebind API exists and is **not called** by StrataFS: the link case is
rebound internally by the publish path, and the rename case relies on
publish preserving the dentry. <a id="cite-facs.stratafs-copy-up.rebind-unused"></a> That holds because publication always
renames within a single parent. A cross-directory publish rename would
silently invalidate the staging binding, since the rename-publish
entry point does not require the destination parent to equal the
staging parent — currently unreachable, but the guard is the caller's
discipline rather than the interface's.

Named staging entries carry `security.peios.stratafs_staging`.
Caller-originated writes and removals of it are denied. <a id="cite-facs.stratafs-copy-up.staging-marker-writes-denied"></a> A write or
removal is admitted only on the exact bound staging inode during
populate, or on the exact orphan-marker object during authenticated
recovery — where the predicate admits a *write* as well as a removal,
being shared between the setxattr and removexattr hooks. <a id="cite-facs.stratafs-copy-up.staging-marker-admission"></a> Probing the
marker for recovery is a kernel-only raw read conveying no caller
authority, and orphan deletion is bound to the exact dentry, inode,
parent dentry and parent inode supplied when the phase was armed, so
an arbitrary name sharing the staging prefix never matches. <a id="cite-facs.stratafs-copy-up.orphan-deletion-exact-binding"></a> Recovery
processes at most 128 entries per batch.

<a id="trm-3-9-7-3"></a>

## Exempt operations <a id="cite-facs.stratafs-copy-up.exempt-operations"></a>

For a matching object in a matching phase, the ordinary AccessCheck,
cached-grant check, privilege check and caller-access audit decision
are omitted at these points:

| Copy-up action | Enforcement points |
|---|---|
| Open and read provider data or a symlink target | `security_inode_permission`, `security_file_open`, `security_file_permission`, `security_inode_readlink` |
| Read provider attributes and extended attributes | the inode and file getattr, setattr-preflight, getxattr and listxattr paths as applicable |
| Create a staged file, directory or symlink, and materialise parents | `security_inode_permission`, `security_inode_create`, `security_inode_mkdir`, `security_inode_symlink`, `security_inode_init_security`; for a stacking destination also `security_dentry_create_files_as` and, for an anonymous object, `security_inode_post_create_tmpfile` |
| Populate staged data, attributes and eligible non-descriptor xattrs | `security_inode_permission`, `security_file_open`, `security_file_permission`, the inode and file setattr paths, setxattr and removexattr. `security.capability` uses only the dedicated clone call below. |
| Publish | `security_inode_permission` on the exact staged object or destination parent, then `security_inode_link` or `security_inode_rename` |
| Remove staging or roll back materialised entries | `security_inode_permission` on the exact parent, then `security_inode_unlink` or `security_inode_rmdir` |

A `security_inode_permission` or `security_file_permission` match also
matches the requested mask. <a id="cite-facs.stratafs-copy-up.mask-must-match"></a> Provider access is
read-only — write, append and non-directory execute requests never
match it. <a id="cite-facs.stratafs-copy-up.provider-read-only"></a> Staging access is limited to the read, write and append
masks population needs, plus execute and chdir for directories, and
namespace parents to the write and traverse masks the one armed action
needs, plus open and chdir. <a id="cite-facs.stratafs-copy-up.staging-mask-limits"></a> Unknown mask bits fail closed. <a id="cite-facs.stratafs-copy-up.unknown-mask-fails-closed"></a>

The list is exhaustive. The context does not exempt execution, memory
mapping, ioctl, locking, arbitrary `fcntl`, device access, process
access, socket access, mount operations, or operations on a descriptor
installed into a userspace file table — each verified by the absence
of any copy-up branch on those paths. <a id="cite-facs.stratafs-copy-up.list-exhaustive"></a> Internal copy-up files are
additionally denied `statfs`, `truncate`, `fsync` and `fallocate`. <a id="cite-facs.stratafs-copy-up.internal-file-denied-ops"></a>

A file opened internally under the exemption is marked
copy-up-internal in its blob and carries a granted mask of zero. <a id="cite-facs.stratafs-copy-up.internal-file-zero-mask"></a> It is
usable without a cached caller grant only while the same context is
attached and its phase admits that exact file. Use after phase
completion, from another task, or after transfer through `SCM_RIGHTS`
fails closed. <a id="cite-facs.stratafs-copy-up.internal-file-scope"></a> Each armed phase has a distinct monotonically increasing
generation — overflowing it fails closed — and an internal file is
sealed to the generation it was opened in, so a later phase of the
same kind after a worker transfer cannot reactivate an older file. <a id="cite-facs.stratafs-copy-up.generation-seal"></a>
Final release drops the context reference.

The one exception is the read-only provider-directory cursor used by
bounded staging recovery. StrataFS may retain that file while it
leaves the context to clean one captured batch, then resume it after
re-entering the same context and arming a new source-read phase. Only
a directory file already marked internal for that exact context, still
naming the pinned provider path and inode, opened for read without
write, execute or path-only mode, and inside that attached
source-read phase, resumes; it is then resealed to the new generation. <a id="cite-facs.stratafs-copy-up.directory-cursor-resume"></a>
Between phases it is unusable and conveys no deletion authority.

<a id="trm-3-9-7-4"></a>

## Backing-file adoption <a id="cite-facs.stratafs-copy-up.backing-adoption"></a>

Before a regular-file copy is published, one exact copy-up-internal
backing file can become the backing file for the outer StrataFS open
description. The staging binding is verified, and the backing file's
recorded user path is confirmed to be that same outer description;
the outer description's immutable granted and continuous-audit
snapshot is then copied across and the internal marker removed. <a id="cite-facs.stratafs-copy-up.adoption-copies-snapshot"></a> This
is a transfer of authority already attached to the descriptor, not a
new AccessCheck against the task that caused the copy-up, which is
what preserves descriptor delegation when that task is not the opener.
It is one-shot, and requires the backing file mode. <a id="cite-facs.stratafs-copy-up.adoption-one-shot"></a>

StrataFS performs adoption after opening the staged file and **before**
publishing the anonymous staged object. KACS verifies the still-bound
staging object while the owned context has no armed phase.
<a id="cite-facs.stratafs-copy-up.adoption-before-publish"></a>

If the staged file belongs to OverlayFS, adoption also follows its exact
private backing files. Each child must be the parent's stored real file,
name that parent's upper object on its upper mount, and record the parent
as its user path. Matching a path alone does not establish this relationship.
The child must have an ordinary managed grant, no copy-up context or phase
generation, and no inherited backing grant.

KACS pins and validates the entire bounded chain before changing any file's
snapshot. A stale association, repeated file, or excessive depth rejects the
handoff without changing those snapshots. Once validation succeeds, every
admitted file receives the original outer description's granted and
continuous-audit masks in both security blobs. This preserves delegated
authority without consulting the task's credentials or weakening phase
precedence.

<a id="trm-3-9-7-7"></a>

## Auditing <a id="cite-facs.stratafs-copy-up.auditing"></a>

The outer authorized handle operation remains subject to ordinary
audit. No second caller AccessCheck or privilege-use audit is emitted
for an exempt internal sub-operation, since that would attribute
StrataFS mechanics to a caller decision that never happened — and
internal files carry a continuous-audit mask of zero, so they generate
no per-operation events either. <a id="cite-facs.stratafs-copy-up.no-second-audit"></a> The `CAP_SETFCAP` satisfaction path
returns before the capability check that would record privilege use.

StrataFS decides when its own copy-up lifecycle and failure events —
`stratafs.file.copied-up` and `stratafs.mutation.refused` ([Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>)) —
occur; KACS supplies the kernel-only emitter, so KMES stamps each
event with the effective token of the task whose operation caused it
([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)). Two of those emissions are best-effort: an allocation failure,
or an operation string that is empty or over 64 bytes, drops the event
silently. <a id="cite-facs.stratafs-copy-up.emission-best-effort"></a>

Denied mismatches, and operations performed with no active matching
context, follow the ordinary authorization and audit paths.

## Related explanations

- [Deferred deletion](</kernel/internals/stratafs/mutation/deferred-deletion.md>)
- [Copy-up descriptors](</kernel/internals/stratafs/security/copy-up-descriptors.md>)

---

# Copy-up descriptors

_Peios Kernel / Internals / StrataFS / Security_

> Copy-up descriptors: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7-6"></a>

## Exact protected-metadata cloning <a id="cite-facs.stratafs-copy-up.descriptor-cloning"></a>

KACS owns descriptor cloning rather than StrataFS raw-xattr code.
Before a create phase is armed, the provider's complete effective
descriptor is resolved and pinned using the ordinary mount-policy and
corrupt-descriptor rules ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). A missing, corrupt, unresolvable,
oversized or unsupported descriptor fails the phase before the
destination is created. <a id="cite-facs.stratafs-copy-up.unresolvable-descriptor-fails-phase"></a>

For a matching inode security initialisation, an exact byte-for-byte
copy of the pinned descriptor is installed instead of inheritance
running. <a id="cite-facs.stratafs-copy-up.exact-copy-not-inheritance"></a> The canonical xattr is installed as part of inode creation
and the inode's validated parsed cache is seeded from identical bytes
before the inode becomes usable. <a id="cite-facs.stratafs-copy-up.xattr-and-cache-seeded"></a> Failure to allocate, validate or
install either representation fails creation — there is no window in
which a named staging inode carries an inherited or otherwise weaker
descriptor. <a id="cite-facs.stratafs-copy-up.no-weak-window"></a>

On a stacking destination the same applies to the real inode created
below the outer dentry, with the authenticated outer transition as the
only authority to redirect installation there. The pinned bytes are
installed and cached during the real inode's creation, before the
outer object is confirmed or bound; inheriting the parent's descriptor
and repairing it afterwards would not be conforming. <a id="cite-facs.stratafs-copy-up.stacking-real-inode-install"></a>

The canonical descriptor is not copied by ordinary xattr enumeration —
it is reported as cancelled so a stacking filesystem discards it — and
raw canonical getxattr and setxattr stay denied even inside the
context, with the hook-side denial evaluated before any phase match. <a id="cite-facs.stratafs-copy-up.canonical-xattr-cancelled"></a>
The context does not override the unconditional denial of POSIX ACL
mutation either. <a id="cite-facs.stratafs-copy-up.posix-acl-still-denied"></a>

Raw setxattr, including through an internal copy-up file, remains
unable to install `security.capability`. <a id="cite-facs.stratafs-copy-up.raw-setcap-denied"></a> Where the provider has one,
StrataFS calls the dedicated clone entry point during populate, after
any operation that might clear file capabilities. That call accepts
only a kernel buffer exactly matching the pinned value, under the same
user namespace it was pinned in, for the still-bound staged inode. <a id="cite-facs.stratafs-copy-up.clone-call-preconditions"></a> It
re-reads the provider immediately before installing and fails with
`ESTALE` if the value or its presence changed. <a id="cite-facs.stratafs-copy-up.clone-estale-on-change"></a>

The call copies the caller's buffer before comparing, and installs
with `XATTR_CREATE` through the ordinary VFS path, so mount-idmap
conversion, xattr validation, filesystem permission and format checks
and other LSM checks all still apply. <a id="cite-facs.stratafs-copy-up.clone-through-vfs"></a> The otherwise-dead
`CAP_SETFCAP` gate is satisfied only synchronously inside that
validated call, and the corresponding setxattr re-entry is admitted
only after the first hook matches the exact staged inode. <a id="cite-facs.stratafs-copy-up.setfcap-synchronous-only"></a> The
capability answer targets only the pinned caller namespace or the
staged inode's filesystem namespace, and the condition is cleared on
every return. Nothing is installed when the provider had no attribute,
a different one, or an unreadable or invalid one. <a id="cite-facs.stratafs-copy-up.no-install-on-mismatch"></a> The exception does
not revive exec-time file-capability grants.

There is one asymmetry here: the removal path does not reject
`security.capability` the way the set path does, so an internal
copy-up descriptor can remove it from the staged object during
populate. <a id="cite-facs.stratafs-copy-up.removal-path-asymmetry"></a>

Other eligible provider xattrs follow StrataFS's replication rules
while KACS's caller checks on their source and staging objects are
exempted as above. An ineligible xattr that cannot be replicated
triggers StrataFS's ordinary copy-up failure rule rather than being
silently omitted.

<a id="trm-4-6-3"></a>

Copy-up produces a second instance of an existing object. Its security
descriptor is the source's — owner, group, discretionary list, system
list and integrity label alike — and it is KACS that carries it, not
stratafs. <a id="cite-security.copy-up-descriptor-preserved"></a>

<a id="trm-4-6-3-1"></a>

## How it is carried <a id="cite-security.copy-up-never-inherits-descriptor"></a>

When a copy-up context is created, the provider's complete effective
descriptor is resolved and pinned as a byte string on the context. Each
create phase copies those bytes into the phase, and the inode security
initialisation for the created object installs them verbatim instead of
running inheritance. Nothing is reconstructed field by field: it is a
copy of the source bytes, so all five components are preserved together.

The canonical descriptor attribute is deliberately excluded from
stratafs's own extended-attribute replication, precisely so that the
two mechanisms cannot disagree.

The separation inside KACS is clean and explicit. The inode security
initialisation takes the copy-up branch first, and taking it
short-circuits the inheritance builder entirely. Ordinary creation in a
create stratum inherits from its parent ([Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>)); copy-up preserves.
There is no path on which a copied-up object receives an inherited
descriptor.

<a id="trm-4-6-3-1-1"></a>

### Descriptors of materialised parents <a id="cite-security.materialised-parents-use-provider-descriptor"></a>

Directories materialised in the create stratum to hold a copied-up
object are handled the same way, each carrying the descriptor of the
corresponding **provider** directory — the merged provider of that same
relative path, which is what the pre-check of [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) evaluated against.

<a id="trm-4-6-3-2"></a>

## Failure <a id="cite-security.copy-up-descriptor-failure-fails-operation"></a>

Where the source descriptor cannot be replicated, the copy-up fails and
the operation that required it fails. A missing, corrupt, unresolvable,
oversized or unsupported descriptor fails the phase before the
destination is created, and an absent pinned descriptor at install time
fails the create.

<a id="trm-4-6-3-2-1"></a>

### Protection precedes publication <a id="cite-security.descriptor-installed-before-publication"></a>

Nothing publishes a copied-up object carrying any
other descriptor: the descriptor is installed at inode creation, before
any content, and publication is a link or rename of an object already
stamped, so there is no window in which a differently-protected object
is reachable.

The failure errno is not the specified one. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>)'s table pairs
descriptor failure with `EIO` alongside extended-attribute failure, and
the extended-attribute half does report `EIO`. The descriptor half is
carried by KACS, whose failures surface as `EACCES`, `EOPNOTSUPP`,
`EINVAL`, `ESTALE` or `ENOMEM`; there is no `EIO` anywhere on that
path. This is tracked as a defect.

<a id="trm-4-6-3-3"></a>

## Why preservation rather than inheritance

Copy-up is reachable by any caller with the right to modify the source
object. That right does not include the right to modify the source's
descriptor, which is a separate right.

Were a copied-up object to receive an inherited descriptor, a caller
holding only write access to a restrictively protected object could
cause a copy of it to exist carrying the create stratum directory's
inheritable entries — and that copy, having higher precedence, would
become what the merged path resolves to. The object's confinement would
have been replaced by the directory's, through an operation the caller
was entitled to perform, without their ever holding the right to alter
a descriptor.

Preserving the source descriptor closes that: a copy is exactly as
reachable as its original, and copy-up changes which stratum holds an
object without changing who may reach it.

<a id="trm-4-6-3-4"></a>

## Provenance <a id="cite-security.copy-up-descriptor-owner-is-source"></a>

Because the descriptor is preserved, the copy's descriptor-level owner
is the owner of the object it was copied from, not the caller who
caused the copy. Ownership therefore does not record who created the
copy and cannot be relied on to; the audit record of [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) is where
that is available.

Setting the copying caller as the descriptor owner would have preserved
provenance, and was rejected: an owner holds implicit rights over an
object's descriptor, so making the caller the owner would reintroduce
the escalation this section exists to prevent by a slightly longer
route.

The POSIX owner is preserved separately and for a different reason —
[Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>) covers the chown and [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md#trm-4-5-8>) what it means for accounting.

<a id="trm-4-6-3-5"></a>

## What "the source's descriptor" means <a id="cite-security.copy-up-pins-effective-descriptor"></a>

The descriptor pinned at the start of a copy-up is the provider's
**effective** descriptor rather than its raw stored attribute. On a
provider mount whose own policy class synthesises, that would be the
synthesised value. In practice that case is unreachable: reaching the
object through the stratafs mount at all requires a real descriptor,
under stratafs's own deny-missing class ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)). A provider on an
unmanaged mount is refused outright.

---

# Access Check Delegation

_Peios Kernel / Internals / StrataFS / Security_

> stratafs stores no descriptors and allocates its inodes bare — who performs which access check, and when.

<a id="trm-4-6-1"></a>

stratafs stores no security descriptors. It allocates its outer inodes
bare and never runs the inode security initialisation over them, and
neither its inode state nor its superblock state has anywhere to put a
descriptor. Every object reachable through a mount has its descriptor
on its own stratum, and that descriptor is what governs access to it. <a id="cite-security.descriptor-on-provider-stratum"></a>

<a id="trm-4-6-1-1"></a>

## The rule <a id="cite-security.check-evaluates-target-descriptor"></a>

An access check for an operation on an object reachable through a
stratafs mount evaluates the security descriptor of the object the
operation will be performed against. For an operation on a
non-directory, that is the provider's object; for a merged directory,
[Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) defines which participants' descriptors apply.

stratafs synthesises no descriptor, supplies none of its own, and
applies no mount-level template. It could not: constructing one would
require a synthesising mount policy class, and stratafs is pinned to
the class that denies where a descriptor is missing ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)).

Because the descriptor evaluated is the provider's own, a stratafs
mount cannot grant access that the provider's stratum would refuse.
That property is structural rather than a matter of care in
implementation: there is no descriptor for stratafs to get wrong,
because it holds none.

The guarantee is one-directional, which is the direction that matters.
Where the provider carries no descriptor there is nothing to evaluate
and the mount's own policy decides, which is to refuse — so such an
object is unreachable through the mount even where its own filesystem's
policy would have admitted it.

<a id="trm-4-6-1-2"></a>

## Who performs which check <a id="cite-security.merged-checks-are-stratafs-own"></a>

For an object with a single provider, the descriptor comes back through
ordinary forwarding. KACS reads the canonical descriptor attribute the
same way it does for any file, the stacking layer forwards the
`getxattr` down to the provider, and the descriptor that comes back is
the provider's. For metadata and extended-attribute operations, stratafs
re-targets the pending one-shot KACS decision onto the provider inode,
so the check is made against the object the operation will reach.

A merged directory is not that case. It stands for several directories
with several descriptors, and forwarding yields only the provider's.
Those checks are **stratafs's own**: it walks every present
participating directory and evaluates each one's descriptor, failing on
the first refusal.

KACS cooperates by standing down on stratafs inodes entirely. Its
`inode_permission` hook, and its create, mkdir, mknod, symlink, link,
unlink, rmdir and rename hooks, all return success immediately for a
superblock carrying the stratafs magic. The checks that matter are made
by stratafs against the real objects, or by KACS against the real
objects once stratafs has resolved them.

<a id="trm-4-6-1-3"></a>

## Timing <a id="cite-security.open-grant-frozen"></a>

The descriptor evaluated is the provider's at the time the check runs,
and the open-time grant is frozen into the file's KACS state — the
check-at-open principle applies unchanged, and copy-up transfers that
immutable snapshot to the new backing file rather than deciding again.

For merged-directory checks, stratafs reads each participant's descriptor
attribute on every check. KACS also refreshes an outer stratafs inode's
parsed descriptor whenever a check or descriptor query needs it. A writer
using the stratum directly therefore needs no invalidation protocol with
the merged view. Missing and corrupt descriptors are re-read too, so a
subsequent repair can take effect.

This refresh applies to retained handles as well as new pathname operations.
An `O_PATH` handle performs its live access check against the refreshed
descriptor. An ordinary file handle retains its granted access, but a
permitted descriptor query returns the provider's current descriptor, not
the one present when the file opened.

When copy-up rebinds a file's inode to the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), stratafs explicitly
invalidates the parsed descriptor. Subsequent descriptor queries follow the
new provider. The file's frozen grant remains unchanged; invalidating the
inode cache does not authorise or revoke access on an already-open file.

---

# Checks on Merged Directories

_Peios Kernel / Internals / StrataFS / Security_

> An operation on a merged directory is checked against every participating directory — including where the create stratum's directory does not exist.

<a id="trm-4-6-2"></a>

A merged directory stands for several real directories, each with its
own security descriptor. An operation on one is checked against every
participating directory whose contents it depends on, and against the
directory it modifies. Where more than one applies, **all** must
succeed: the check walks participants in order and returns on the first
refusal, and nothing degrades an operation to the subset of strata the
caller may reach.

Two composite rights recur:

- **Search** — traverse on every participating directory, since every
  one is searched to resolve a name. The permission hook maps the
  kernel's execute intent onto it. <a id="cite-security.merged-search-right"></a>
- **Enumerate** — Search plus list on every participating directory.
  The permission hook maps the read intent onto the list right, and
  directory open demands both together. <a id="cite-security.merged-enumerate-right"></a>

| Operation | Checked against |
|---|---|
| Resolving a name | Search <a id="cite-security.rights.resolve"></a> |
| Enumerating | Enumerate, before the listing is captured <a id="cite-security.rights.enumerate"></a> |
| Reading an object's attributes | Search, plus whatever the object's own descriptor requires <a id="cite-security.rights.read-attributes"></a> |
| Reading the origin attribute on a merged directory | Search, plus read-EA on **every** participant ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) <a id="cite-security.rights.read-origin"></a> |
| Creating a name | Search, plus add-file or add-subdirectory on the **create stratum's** directory <a id="cite-security.rights.create"></a> |
| Copy-up | Nothing beyond what the operation it serves already required <a id="cite-security.rights.copy-up"></a> |
| Removing a name | Search, plus delete-child on the **provider's** directory <a id="cite-security.rights.remove"></a> |
| Removing a directory | Enumerate — emptiness is judged across every participant — plus delete-child on the provider's directory <a id="cite-security.rights.rmdir"></a> |
| Rename, source | Search, plus delete-child on the source **provider's** directory <a id="cite-security.rights.rename-source"></a> |
| Rename, destination | Search, plus add-entry on the source provider's directory, which [Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>) requires to hold the destination, plus delete-child where that directory already holds the name <a id="cite-security.rights.rename-destination"></a> |
| Rename of a directory | Both of the above, plus Enumerate on the object being renamed, and Enumerate on the destination where its provider is a directory <a id="cite-security.rights.rename-directory"></a> |
| `RENAME_EXCHANGE` | Search on both, plus add-entry and delete-child on the directory of the stratum providing both names <a id="cite-security.rights.rename-exchange"></a> |
| Link | Search on both, plus add-file on the source provider's directory <a id="cite-security.rights.link"></a> |
| Creating or linking an unnamed file | Search, plus add-file on the **create stratum's** directory <a id="cite-security.rights.unnamed-file"></a> |

The mutating rights land on the directory that actually changes, which
follows from [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>): an entry appears in the create stratum's directory
and disappears from the provider's, so in each case it is that
directory's descriptor that decides. The two coincide whenever the
create stratum is also the provider. <a id="cite-security.mutating-right-on-modified-directory"></a>

One right the table does not name is required anyway: the underlying
`vfs_link` makes KACS demand write-attributes on the **source object**,
which is an object-descriptor right outside the directory scope this
section covers. <a id="cite-security.link-requires-write-attributes-on-source"></a> Linking an unnamed file is exempt, since stratafs marks
the source for that purpose. <a id="cite-security.unnamed-link-exempt-from-source-check"></a>

The effective rights on a merged directory are therefore the
intersection of the rights on its participants, with mutating rights
additionally required on the directory that is actually modified.
Requiring the intersection is fail-closed and admits no partial
results: the alternative would let the names held by a restrictively
protected directory be enumerated by a caller who could not enumerate
it directly, because a permissive directory of higher precedence
happened to provide the merged path.

One consequence is worth stating plainly. Because creation is governed
by the create stratum's directory descriptor, and a created name
shadows the same name in every lower stratum, the right to create in
the create stratum's directory is the right to determine what every
lower stratum's entry of that name resolves to.

<a id="trm-4-6-2-1"></a>

## Where the create stratum's directory does not exist <a id="cite-security.create-check-falls-back-to-provider-directory"></a>

A merged directory has a create stratum whether or not that
subdirectory exists ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)), so a check naming "the create stratum's
directory" has to be evaluated against a directory that is not there
yet.

Every such check is performed before any part of the operation is
carried out, and in particular before any directory is materialised:
the authorisation call strictly precedes parent materialisation in
creation, in tmpfile creation, and in the unnamed-link path. Where the
checks fail, nothing has been created, so the create stratum is left
exactly as it was.

Where the create stratum does not hold the path, the check falls back
to the **corresponding provider directory** — the merged provider of
that same relative path — which is the descriptor the directory will
carry once materialised ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)). It is never skipped, and never
substituted with an ancestor's descriptor. Where no provider exists
either, the result is `EROFS`.

Materialising the intervening directories is part of the operation, not
a separate one. No per-ancestor authorisation is taken; the mkdirs are
exempted by the copy-up context. Checking against the descriptor the
directory will have keeps the answer independent of how much of the
create stratum happens to have been materialised already: the first
caller to write into a deep path and the hundredth face the same check,
against the same descriptor.

A create that fails *after* materialisation for a reason other than a
check — `EEXIST`, `ENOSPC` — does leave the intervening directories in
place.

<a id="trm-4-6-2-2"></a>

## Copy-up carries no separate authority <a id="cite-security.copy-up-requires-no-extra-right"></a>

A copy-up requires no right beyond those the operation that provoked it
already required. In particular it does not require the caller to hold
the right to read the provider's object, nor the right to add an entry
to the create stratum's directory. Neither copy-up path takes any
authorisation at all.

Copy-up is the mechanism by which an authorised modification is
realised, not an operation a caller requests. The read of the provider
is stratafs's own, and the copy carries the source's descriptor
unchanged ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so the caller obtains nothing they did not already
have: the same content, under the same descriptor, at the same path.

The alternative cannot be expressed. Routing happens when a
modification is performed ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), and by then the authority that
governed the open is a mask cached on the descriptor, immutable and
carrying no token — so there is nothing to evaluate a fresh right
against. Checking the *acting* token instead would break descriptor
delegation, since a descriptor passed to another process would stop
working there.

What remains is a resource consideration rather than an access one: a
caller entitled to write a file in a stratum that will not accept
modification can cause an entry to appear in the create stratum without
holding rights over that directory. They gain neither access nor space
by it: [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md#trm-4-5-8>) records that the copy is accounted to the preserved owner
rather than to them.

That exemption is only enforceable because KACS provides a copy-up
context; without it the access-control layer would check the caller
against the create stratum's directory at exactly the point where the
authority to check no longer exists. [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>) describes the context, its
phase binding and its exhaustive list of exempt operations. What
matters here is what stratafs must hold up its end of: the context
exempts caller authorisation only, so every mutation still goes through
the ordinary VFS path under write access on the target mount, a
read-only filesystem still refuses, and filesystem errors still
propagate. Nothing is performed under a borrowed or elevated identity —
every copy-up mutation runs with the calling task's own credentials.

<a id="trm-4-6-2-2-1"></a>

### Recovery retains the mounter’s file credentials <a id="cite-security.staging-recovery-uses-mounter"></a>

The stale-staging recovery scan passes the **mounter's** credentials
to the internal directory open, which retains them as the file’s
credentials. That does not switch the calling task’s current
credentials or select a different KACS token. The scan runs in a
source-read copy-up context bound to that exact directory, so the
context admits its read before an ordinary token access check.

Consequently, neither the caller nor the mounter needs a directory-list
grant for that scoped recovery read. An ordinary open requesting list
access remains subject to the directory’s descriptor. Path resolution
separately uses the captured mounter credentials; the file-credential
argument is not itself an authority switch.

---

# Mount Policy

_Peios Kernel / Internals / StrataFS / Security_

> Every stratafs mount carries the FACS policy class that denies access to an object with no readable descriptor, and what follows from that.

<a id="trm-4-6-4"></a>

A stratafs mount carries the FACS mount policy class that denies access
to an object with no readable security descriptor. The class is derived
from the filesystem magic, not from an administrative choice: the
policy resolver maps the stratafs magic to the deny-missing class, and
falls back to that mapping whenever a cached policy value is not one of
the valid ones. <a id="cite-security.mount-policy-is-deny-missing"></a>

<a id="trm-4-6-4-1"></a>

## Policy changes are refused before validation <a id="cite-security.mount-policy-cannot-be-set"></a>

It cannot be set to anything else. The set path rejects a superblock
carrying the stratafs magic with `EOPNOTSUPP` **before** it validates
its arguments or checks privilege, and there is no mount option to
choose one — stratafs's parameter table holds exactly one entry, and
anything else is refused. Reading a mount's policy is itself privileged,
requiring TCB privilege, though for stratafs the answer is fixed.

Two classes are excluded for distinct reasons.

**The unmanaged class** declares that FACS does not apply to a mount and
that the kernel governs it by rules particular to that filesystem.
stratafs has no such rules: it delegates every decision to the provider
([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)). An unmanaged stratafs mount would therefore have no access
control at all — not delegated control, but none — for every object
reachable through it. That is not theoretical: enforcement points
consult the mount policy of the superblock an object belongs to before
performing their check, and treat an unmanaged mount as requiring none.
For a mount established over a directory of executables, that would
place every program on the system beyond the execute check.

**The synthesising classes** would have stratafs supply a descriptor of
its own for an object whose provider has none. Either consequence is
disqualifying: the mount would grant access to an object that is
unreachable through its own stratum, falsifying the guarantee the whole
of [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>) rests on; and the class that persists a synthesised descriptor
would write it back onto the provider's object, which stratafs may not
do to any stratum and certainly not to one carrying `ro`.

<a id="trm-4-6-4-2"></a>

## Missing descriptors <a id="cite-security.missing-descriptor-denied"></a>

Where a provider object has no descriptor, access through the stratafs
mount is denied under the mount's own policy, and the provider
filesystem's policy is not consulted. Both paths implement this:
stratafs's own merged-directory check turns `ENODATA` or `EOPNOTSUPP`
straight into `EACCES` rather than asking the provider's superblock to
synthesise, and an object open resolves the missing-descriptor policy
against the **stratafs** superblock, yielding a missing-descriptor
cache entry and then `EACCES`.

<a id="trm-4-6-4-2-1"></a>

### Corrupt is not missing <a id="cite-security.corrupt-descriptor-does-not-use-mount-policy"></a>

A descriptor that is present but cannot be interpreted is a distinct
case and is not routed to mount policy. It takes the ordinary
corrupt-descriptor outcome: a corrupt cache entry and an emitted event
on the open path, and a validation failure on the merged-directory
path. The two produce the same errno by different routes, and mount
policy is consulted in neither.

<a id="trm-4-6-4-3"></a>

## Consequence <a id="cite-security.merge-never-widens-access"></a>

A stratafs mount is uniform in the sense a mount policy requires: every
object reached through it is subject to the same policy, which is the
mount's own. What varies between objects is the descriptor evaluated,
which is a property of the object rather than of the policy.

Because the policy denies where a descriptor is absent, the divergence
from direct access is always in the refusing direction. An object with
no descriptor on a stratum whose own filesystem would synthesise one is
refused through the stratafs mount while remaining reachable through
its stratum path. An object reachable through its stratum path is never
made *more* reachable by being merged. The same holds for a stratum on
an unmanaged filesystem, whose objects carry no descriptors at all:
merging one is permitted but yields nothing readable, and is not a
useful arrangement.

---

# Audit

_Peios Kernel / Internals / StrataFS / Security_

> The two stratafs events recorded because the information cannot be recovered afterwards — plus two gaps and what is not audited at all.

<a id="trm-4-6-5"></a>

Two classes of stratafs event carry information that cannot be
recovered from the filesystem afterwards, and are recorded when they
happen. Both are emitted through KACS's kernel-only emitter, so KMES
stamps each with the effective token of the task whose operation caused
it. <a id="cite-audit.events-stamped-with-effective-token"></a>

<a id="trm-4-6-5-1"></a>

## Copy-up <a id="cite-audit.copy-up-always-emitted"></a>

Every copy-up emits a `stratafs.file.copied-up` record, successful or
not. Its payload carries these fields, each a path of nested maps:

| Field | |
|---|---|
| `object.file.path-relative` | The relative path within the mount, `/`-prefixed |
| `source.stratum.index` | The stratum the object was copied from |
| `source.stratum.path` | That stratum's path |
| `destination.stratum.index` | The stratum it was copied into |
| `destination.stratum.path` | That stratum's path |
| `outcome.success` | Whether the copy-up succeeded |
| `outcome.errno` | The failure, as a negative errno; absent on success |

The caller's identity is not in this payload. It does not need to be:
KMES stamps the effective, true and process token GUIDs onto every event
header at ring-write time, and because copy-up runs in the caller's own
context those are the caller's. The identity is carried in the
**envelope**, once, for every event — duplicating it into the payload
would give a reader a second copy that could disagree with the first.

Recording it matters because [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>) preserves the source's descriptor,
so nothing about the resulting object records who caused it to exist.
A reader of these records must take the identity from the event header,
not look for it among the fields.

The `ENOTDIR` of parent materialisation is reported through this event
in its `outcome.errno` rather than through the refusal event below;
the required fields are all present, under a different event type.

<a id="trm-4-6-5-2"></a>

## Refused mutation <a id="cite-audit.arrangement-refusal-emitted"></a>

A mutation refused because of how the mount is arranged emits a
`stratafs.mutation.refused` record carrying the relative path
(`object.file.path-relative`), the operation (`operation.name`), the
providing stratum (`source.stratum.index` and `source.stratum.path`),
the error (`outcome.errno`, negative) and whether the refusal was
deferred (`outcome.deferred`). The `source.stratum` fields are present
only where a provider is known; see below.

What counts as an arrangement refusal is one explicit list — `EROFS`,
`EXDEV`, `ENOTDIR`, `EISDIR`, `ENOTEMPTY`, `EEXIST`, `EINVAL`. Call
sites cover
every mutating path: writes, mappings, truncation, `fallocate`, splice,
`copy_file_range`, `remap_file_range`, `setattr`, `setxattr` and
`removexattr`, creation, tmpfile, unlink and rmdir, link, supersede,
and rename.

`EACCES` is deliberately absent from that list. A refusal produced by an
access check is audited by the mechanism that performed it, and
stratafs does not duplicate those records.

These refusals report a mismatch between what a caller attempted and
how the mount is arranged — software writing where it cannot, or an
arrangement that does not admit an operation someone expected. That is
diagnostic information about the system's configuration, and it is
otherwise visible only as an error returned to a caller that may
discard it.

Rollbacks are audited under the same event with the deferred flag set:
a create or link whose outer bookkeeping failed and whose lower object
could not be removed again, and a failed publication rollback after a
copy-up.

A refusal raised before a provider is known — creation, tmpfile, the
heads of link and rename — has no stratum to name. Its record has no
`source` map at all: `source.stratum.index` and `source.stratum.path`
are both absent, never `-1`, nil or an empty string, so a reader can
tell "no provider was involved" from "the provider's path is empty".

<a id="trm-4-6-5-2-1"></a>

### One exception <a id="cite-audit.deferred-deletion-audited-on-any-error"></a>

A refused **deferred deletion** is audited on *any* non-zero result, not
only the arrangement errors, so one refused by an access check does get
a stratafs record. That is the right resolution of the two rules, since
the requirement to audit a deferred deletion is unconditional — nobody
is left to receive the error — but it is a deliberate exception to the
`EACCES` exclusion above.

The record is stratafs's whether or not stratafs was entered. The
delete-child check on the merged parent runs before `->unlink`, so a
directory whose descriptor tightened between the arm and the close
refuses the deletion before the filesystem sees it; KACS then raises
the stratafs record itself, with no `source.stratum` fields, since no
stratum was consulted.

<a id="trm-4-6-5-3"></a>

## What is not audited <a id="cite-audit.lookup-not-audited"></a>

Resolution, revalidation and enumeration emit no records of their own.
They occur on every path operation, they reveal nothing the resulting
access check does not, and recording them would produce volume out of
all proportion to their significance. There is no audit call anywhere
in the lookup path.

Access checks performed against provider objects are audited by KACS,
under its own rules.

---

# Mutation

_Peios Kernel / Internals / StrataFS / Mutation_

> Find the Peios kernel articles about mutation.

Use these articles to understand mutation in the Peios kernel.

- [Deferred deletion](</kernel/internals/stratafs/mutation/deferred-deletion.md>)
- [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md>)
- [Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md>)
- [Creation](</kernel/internals/stratafs/mutation/creation.md>)
- [Removal](</kernel/internals/stratafs/mutation/removal.md>)
- [Rename](</kernel/internals/stratafs/mutation/rename.md>)
- [Links](</kernel/internals/stratafs/mutation/links.md>)
- [Locking](</kernel/internals/stratafs/mutation/locking.md>)
- [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md>)

---

# Deferred deletion

_Peios Kernel / Internals / StrataFS / Mutation_

> Deferred deletion: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7-5"></a>

## Deferred deletion <a id="cite-facs.stratafs-copy-up.deferred-deletion"></a>

A delete-pending mark is authorized when it is set, and the setting
open's token is recorded with it ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-3>)). At the
last close there is no re-authorization against the closing task. <a id="cite-facs.stratafs-copy-up.close-no-reauth"></a> Instead a synchronous, non-nesting internal
deletion scope is armed for the outer path the marking open named, captured
when the mark was set, and StrataFS binds
it once to the exact provider parent, dentry and inode selected from
the descriptor's settled provider. <a id="cite-facs.stratafs-copy-up.deletion-scope-binding"></a> Only the corresponding outer and
lower unlink calls match, and the scope is cleared on every return.

The mechanism never turns an ordinary close into deletion authority,
never admits a different provider entry, and never permits unlinking
an entry that no longer names the descriptor's inode. <a id="cite-facs.stratafs-copy-up.deletion-identity-check"></a> If the original
entry has disappeared or changed identity, the deletion is already
complete and no exemption is used.

<a id="trm-4-5-3-3"></a>

## Deferred deletion <a id="cite-create.deferred-delete-targets-resolved-object"></a>

A request to delete an object when the last descriptor to it is closed
applies to the object the descriptor resolved to, not to whatever
provides that name at close time. Because removal ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)) is defined
over the current provider of a name, the deferred case has its own
path.

<a id="trm-4-5-3-3-1"></a>

### An entry already gone <a id="cite-create.deferred-delete-already-gone-succeeds"></a>

When the deletion is attempted, stratafs locates the entry at the path
the descriptor was opened against, in the stratum that provided it at
that time — the descriptor's private dentry carries both — and resolves
the parent in that same stratum. Four conditions end the attempt
quietly, reporting success because the deletion is already complete:
the parent is gone, the name is gone, the name now identifies a
different inode, or the unlink raced.

The merged parent can disappear or become a non-directory before the
VFS reaches stratafs’s unlink handler. An `ENOENT` or `ENOTDIR` from
that earlier check is also a successful no-op, but only after a lookup
in the descriptor’s original providing stratum confirms that its
recorded name is absent or identifies a different inode. A higher
stratum masking a still-live backing target does not satisfy that
condition: the deletion still fails and is audited. Other errors keep
their ordinary failure and audit behavior.

<a id="trm-4-5-3-3-2"></a>

### The original stratum must accept removal <a id="cite-create.deferred-delete-requires-writable-stratum"></a>

That stratum must accept modification, or the deletion fails with
`EROFS`. Then the entry is removed, and no other. In particular, where
another caller's copy-up has published a new object at that name in a
higher stratum, that object is not the one being deleted and is left
alone.

<a id="trm-4-5-3-3-3"></a>

### Failures are audited <a id="cite-create.deferred-delete-audits-failure"></a>

Because the attempt has no caller to report to, any failure is audited
— and for a deferred deletion, *every* non-zero result is audited, not
only the arrangement errors [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) covers for ordinary refusals. The
object is left in place.

<a id="trm-4-5-3-3-4"></a>

### Authority at deletion time <a id="cite-create.deferred-delete-checked-against-the-providing-stratum"></a>

The right to delete the entry is checked against the directory of the
**stratum where the entry lives**, not against the merged parent, and
it is checked at deletion time rather than only at arm.

Arm time could not do it. The authorizer there holds a `struct file`,
and which stratum provides the entry is stratafs-internal — the
provider index and the parent's relative path are not visible to KACS.
stratafs computes that directory before removing anything, so the check
happens there, where the answer exists.

<a id="trm-4-5-3-3-5"></a>

### The requesting token outlives the arm <a id="cite-create.deferred-delete-token-outlives-the-arm"></a>

The token is the one that requested the deferred deletion, not the
credentials of whoever closes the descriptor. That requires it to
outlive the arm: the file's blob takes a reference when armed and
releases it in `->file_release`, on both the armed and unarmed exits.
The file is the thing that was armed, so its lifetime is the right
one — arm and close may be far apart and in different tasks.

<a id="trm-4-5-3-3-6"></a>

### Supported object types <a id="cite-create.deferred-delete-non-directories"></a>

Deferred deletion is restricted to non-directories, and at arm time to
regular files on a managed mount.

## Related explanations

- [Creation](</kernel/internals/stratafs/mutation/creation.md>)

---

# Write Routing

_Peios Kernel / Internals / StrataFS / Mutation_

> Which single stratum a modification is performed against, when that decision is made, and what shared writable mappings do to it.

<a id="trm-4-5-1"></a>

An operation that modifies an existing object is performed against
exactly one stratum. This section covers which, and when the decision
is made.

<a id="trm-4-5-1-1"></a>

## Accepting modification <a id="cite-write.accepts-modification"></a>

A stratum **accepts modification** of an object it provides when all
three of the following hold:

- the stratum does not carry `ro`;
- the provider's mount is not read-only;
- the provider's inode is not marked immutable.

<a id="trm-4-5-1-1-1"></a>

### Independence from the caller’s rights <a id="cite-write.routing-does-not-use-caller-rights"></a>

The predicate is a property of the stratum and the object alone. It
takes the superblock, the stratum index and the provider path, and
nothing else — no credentials, no security descriptor, no access
check.

That restriction is load-bearing. Were the predicate to take the
caller's rights into account, a caller *refused* write access by the
provider's descriptor could still provoke a copy-up: the write would
fail, but the copy would have been published, and from then on the
merged path would resolve to a snapshot the provider's legitimate
writer could no longer update. A caller with no write access at all
could freeze any file in the mount.

Note the third term is the immutable inode flag specifically, not
unwritability in general. A file that is unwritable by its mode bits is
routed in place and refused by the underlying filesystem.

<a id="trm-4-5-1-2"></a>

## The rule

The decision itself is `route_existing` in `stratafs-core`, which takes
the provider index, whether it accepts modification, the create index
and whether the create stratum is present, whether the object is of a
copyable type, and whether the stratafs mount itself is read-only. It
selects in-place modification, copy-up, or read-only through the following
ordered checks.

1. If the **mount** is read-only, the route is read-only. This term
   short-circuits everything else. <a id="cite-write.read-only-mount-short-circuits"></a>
2. If the provider accepts modification, the operation is performed
   against the provider's object. <a id="cite-write.in-place-when-provider-accepts"></a>
3. Otherwise, if the object is copyable, a create stratum exists, is
   present, and has **strictly higher precedence than the provider**,
   the object is copied up and the operation performed against the
   copy. <a id="cite-write.copy-up-when-create-outranks"></a>
4. Otherwise the route is read-only and the operation fails with
   `EROFS`. <a id="cite-write.erofs-when-no-writable-stratum"></a>

The strict `create_index < provider` comparison is what stops a
modification being placed where something already present would shadow
it. Where a high-precedence stratum provides a name it will not accept
a write for, there is no lower stratum that can take the write without
the result vanishing behind the provider, so `EROFS` is the honest
answer — reported at the moment of the write rather than discovered
later.

Where the name is held by no stratum, the operation is a creation and
[Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) applies instead.

<a id="trm-4-5-1-3"></a>

## When the decision is made

Routing happens as part of a modifying operation, not an ordinary open.
Most mutating entry points call `route_existing` afresh against their
selected provider. Shared write-capable mappings prepare the route before
the memory mapping lock is taken and recheck the selected provider in the
mapping callback. Opening a descriptor does not reserve a writable route.
<a id="cite-write.routed-per-operation"></a>

| Operation | Routes |
|---|---|
| Writing or appending | Yes <a id="cite-write.routes.write"></a> |
| Truncating, or any other `setattr` | Yes <a id="cite-write.routes.setattr"></a> |
| Changing mode, owner, timestamps, or the security descriptor | Yes <a id="cite-write.routes.metadata"></a> |
| Setting or removing an extended attribute | Yes <a id="cite-write.routes.xattr"></a> |
| `fallocate` | Yes <a id="cite-write.routes.fallocate"></a> |
| `splice` into the file | Yes <a id="cite-write.routes.splice"></a> |
| `copy_file_range` and `remap_file_range` | Yes <a id="cite-write.routes.copy-range"></a> |
| Establishing a shared writable mapping | Yes <a id="cite-write.routes.shared-mapping"></a> |
| Reading contents, attributes, or extended attributes | No <a id="cite-write.routes.read-does-not"></a> |
| Opening, for any access | No <a id="cite-write.routes.open-does-not"></a> |
| Taking or releasing a lock, or a lease | No <a id="cite-write.routes.lock-does-not"></a> |

The security descriptor and the system access control list are both
reached as extended attributes, so both route through the `setxattr`
path like any other attribute; there is no descriptor-specific code in
stratafs at all. <a id="cite-write.descriptor-routes-as-xattr"></a>

An open is not itself a routing trigger. `open` computes a route, but
uses it only to decide the flags of the backing open — a non-in-place
route downgrades the provider open to read-only and strips `O_TRUNC`,
deferring rather than deciding. <a id="cite-write.open-defers-routing"></a> The one case in which an open acts is
`O_TRUNC` on a regular file: that is a modification, so it routes, and
copies up or fails with `EROFS` there and then. The truncation itself
is applied afterwards by the VFS through `setattr`, which routes again
and lands on the copy. <a id="cite-write.o-trunc-routes-at-open"></a>

Writes to regular files use the open file description's current
`O_APPEND` setting, including changes made with `F_SETFL` after open or
copy-up. Clearing the flag restores writes at the selected offset and
allows `splice` and range-copy operations to use their explicit offsets.
The provider's append-only restrictions and flag checks still apply.

Routing at operation time rather than at open is what makes the rule
implementable. A filesystem cannot see what an open asked for in
access-mask terms — the caller's descriptor is stamped by KACS before
the filesystem's own open method runs, and its mask lives in a private
blob a filesystem cannot reach. Nor does it need to: the access check
has already happened by the time an operation reaches stratafs, so a
modifying operation arriving here is one its caller was entitled to
perform, and routing it is a decision about strata alone.

<a id="trm-4-5-1-4"></a>

## Shared writable mappings <a id="cite-write.mmap-routes-on-maywrite"></a>

Establishing a shared mapping that can become writable routes before any
bytes are written. Stores through the mapping can then modify its backing
object without another filesystem operation that could perform copy-up.

Preparation applies to regular files mapped with `MAP_SHARED` or
`MAP_SHARED_VALIDATE` through a readable, writable open file description.
This includes `PROT_READ`: the shared mapping retains `VM_MAYWRITE` and can
later gain write access through `mprotect`. Private mappings and shared
mappings that cannot gain write access do not trigger preparation.
Ordinary writable opens remain lazy; opening alone does not copy up a file.

The existing KACS mapping checks run before preparation. Preparation
follows direct StrataFS providers and the selected backing file of FUSE
passthrough mappings. It completes routing and any required copy-up for
each StrataFS layer before the VFS acquires `mmap_lock`. It grants no
additional access, and the backing file's mapping checks still apply.

The mapping callback pins the selected provider and forwards only an
in-place route. If a route change after preparation could require another
copy-up, the mapping fails with `EAGAIN`. Retry the whole `mmap`
call so that preparation runs again. Definitive read-only conditions still
fail with `EROFS`.

A completed copy-up remains published if a later mapping check or provider
callback fails. The same applies if an earlier layer completes copy-up
before preparation fails in a deeper layer. Preparation does not roll back
copies that another operation could already have observed.

<a id="trm-4-5-1-5"></a>

## What a copy-up does to an open descriptor <a id="cite-write.copying-descriptor-follows-copy"></a>

A copy-up performed for one descriptor changes which object provides
the name. That descriptor refers to the copy from then on: it keeps the
inode it was opened against while the inode's backing object becomes
the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), and its backing file is replaced.

Every other descriptor already open against the original continues to
refer to the original, and any fresh resolution of the path yields a
new inode standing for the copy. The pre-copy-up file is not closed —
it is retained so that locks and leases taken before the copy-up keep
working ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).

<a id="trm-4-5-1-6"></a>

## Special files <a id="cite-write.special-files-never-copied-up"></a>

A FIFO, socket, or device node is opened and written without the
filesystem object being modified: what is written passes to a pipe, a
socket, or a driver, not to the object's contents. Writing to such an
object therefore does not route, and such an object is never copied up
— every routing site gates on the object being a regular file, and the
copyable flag excludes anything that is not a regular file, directory
or symlink.

Copying up a FIFO would sever it: a reader holding the original and a
writer that arrived after the copy would hold two unrelated pipes. A
device node survives copying only by the accident that the copy names
the same device.

Opens, reads and writes are forwarded to the provider whether or not it
accepts modification, since the write-mode downgrade and the `O_TRUNC`
refusal both apply to regular files only. Operations that modify the
object itself — its mode, its descriptor, its extended attributes — do
route, and where the provider does not accept modification they fail
with `EROFS`, because the copy-up branch cannot apply to an object that
is never copied up.

<a id="trm-4-5-1-7"></a>

## `ioctl` <a id="cite-write.ioctl-regular-file-refused"></a>

`ioctl` on a regular file is refused unconditionally with `ENOTTY`, and
its compat form with `ENOIOCTLCMD`. Stored-file `ioctl`s can mutate
data and would need command-by-command routing, which is not
implemented; refusing is the conservative stand-in. `ioctl` on a
non-regular file is forwarded to the provider.

---

# Copy-Up

_Peios Kernel / Internals / StrataFS / Mutation_

> Replicating an object from its provider into the create stratum — parents, what is replicated, staging and atomicity.

<a id="trm-4-5-2"></a>

Copy-up replicates an object from its provider stratum into the create
stratum, at the same path relative to the mount root, so that a
modification can be applied without modifying the provider. <a id="cite-copy-up.replicates-into-create-stratum"></a>

Every step runs inside a KACS copy-up context, which exempts the
mechanics from caller authorisation without granting anything. [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)
describes that context in full; [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>) covers the stratafs side of the
bargain.

<a id="trm-4-5-2-1"></a>

## Parents <a id="cite-copy-up.materialises-missing-parents"></a>

Where the create stratum does not hold the directories containing the
object's path, they are created first, walking the relative path
component by component from the create-stratum root downwards. Each is
created as an empty directory with the mode of the corresponding
**merged provider** directory, and with that directory's security
descriptor, installed by KACS during the create phase rather than
inherited.

Contents are not copied. The directories exist to hold the copied
object; the entries they hold in lower strata continue to be reached by
merging.

Where the create stratum holds one of those components as something
other than a directory, the copy-up fails with `ENOTDIR` and the
operation requiring it fails. The blocking entry is not removed or
replaced — there is no `unlink`, `rmdir` or `rename` anywhere on the
parent-materialisation path.

Materialised parents receive a mode and a descriptor, and nothing else:
no extended attributes and no timestamp preservation.

<a id="trm-4-5-2-2"></a>

## What is replicated

| Provider type | Result in the create stratum |
|---|---|
| Regular file | A regular file with the same contents and mode <a id="cite-copy-up.result.regular-file"></a> |
| Symbolic link | A symbolic link with the same target <a id="cite-copy-up.result.symlink"></a> |
| Directory | An empty directory with the same mode; contents are not copied <a id="cite-copy-up.result.directory"></a> |

A device node, FIFO, or socket is never copied up. Anything that is not
a regular file, directory or symlink is refused with `EROFS` before a
copy-up begins. <a id="cite-copy-up.non-copyable-refused"></a>

The security descriptor is carried by KACS rather than replicated as an
attribute ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)). Every other extended attribute is copied, with
three exclusions: the canonical descriptor attribute, anything in the
`system.stratafs.` namespace, and the staging marker attribute. Each
is copied with `XATTR_CREATE`, and `security.capability` goes through a
dedicated KACS entry point rather than a raw write. <a id="cite-copy-up.xattrs-copied-with-exclusions"></a>

No attribute is silently discarded. Any per-attribute failure aborts
the copy-up, as does a listing that fails or exceeds `XATTR_LIST_MAX`;
in every case the error reported is `EIO`, whatever the underlying one
was. <a id="cite-copy-up.xattr-failure-aborts-with-eio"></a>

Modification timestamps are preserved for every type, symbolic links
included. <a id="cite-copy-up.mtime-preserved"></a> The mode is carried across too, except for a symbolic
link, whose mode is fixed by the VFS and not the caller's to set. <a id="cite-copy-up.mode-preserved-except-symlinks"></a>
Access and change times are not preserved for any type. <a id="cite-copy-up.atime-ctime-not-preserved"></a>

**Ownership is preserved.** The staged object is created with the
calling task's credentials, so it begins owned by the caller; where
that differs from the source's uid or gid, a second `notify_change`
sets both to the source's. <a id="cite-copy-up.posix-ownership-preserved"></a> The KACS security descriptor, including
its owner SID, is preserved as well ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so both notions of owner
name the object's owner rather than whoever provoked the copy.

The chown runs under the **mount's own credential** — the same
resolution context stratafs uses to reach providers the caller cannot
([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)) — because setting another uid needs authority the caller does
not have. <a id="cite-copy-up.ownership-chown-runs-under-resolution-credential"></a> It is a separate change from the mode and timestamp
above, which are the caller's to set and stay that way.

Because disk quota keys on the POSIX owner, a copy is accounted to the
owner of the object it was copied from and not to the caller. <a id="cite-copy-up.accounted-to-preserved-owner"></a> That is
what makes [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)'s exemption sound: a caller who may write a file in a
stratum that will not accept modification can cause an entry to appear
in the create stratum without holding rights over it, gaining neither
access nor space.

Hard links are not preserved: an object with several links in its
stratum is copied up as a single independent object, and the other
links continue to refer to the original. <a id="cite-copy-up.hard-links-not-preserved"></a>

Contents are copied through a 64 KiB buffer, one read and one write per
iteration, with the inner write loop retrying short writes. Where the
copy-up was provoked by a path rather than a descriptor, the source is
reopened for each chunk; the staged file is reopened for each chunk
either way.

<a id="trm-4-5-2-3"></a>

## The source must still be the provider <a id="cite-copy-up.source-must-still-be-provider"></a>

Before beginning a copy-up on behalf of a descriptor, the object the
descriptor refers to is verified still to be the provider of that name,
comparing both the path and the provider inode. Where it is not, the
copy-up is not performed and the operation fails with `ESTALE`.

The verification is repeated immediately before publication, under the
create directory's lock, and publication itself uses an operation that
fails if the target name already exists: linking an anonymous object
into place, or a `RENAME_NOREPLACE`. Both additionally test the target
dentry explicitly, and an `EEXIST` from either is normalised to
`ESTALE`.

That is decisive for the case that matters. A competing copy-up
publishes into the same create-stratum directory, where the
filesystem's own atomicity applies, so exactly one of two racing
copy-ups succeeds and the other fails `ESTALE`.

It cannot extend further, and nothing tries to. Strata may be on
different filesystems, and stratafs can neither lock them together nor
inspect them at one instant. A change in some *other* stratum after the
second verification — a direct writer creating the name in a
higher-precedence stratum, say — is an ordinary concurrent structural
change, visible to the next resolution, and is neither an error nor
detected.

This is not a rare case. Every descriptor other than the one that
caused a copy-up still refers to the original object, so a second
descriptor opened before the copy-up meets this rule the first time it
writes. A caller therefore has to be prepared for a write to fail
`ESTALE` on a descriptor that was valid when it was opened and has done
nothing wrong. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records it.

<a id="trm-4-5-2-4"></a>

## Staging and atomicity <a id="cite-copy-up.never-partially-observable"></a>

A copy-up is never observable in a partial state. All content,
attribute and metadata work happens on an object that is not reachable
through the mount, and publication is a single step.

Two arrangements are used, chosen by type:

- A **regular file** is staged as an anonymous object on the create
  stratum's filesystem — a kernel tmpfile — and linked into place when
  complete. No reader can reach it.
- A **directory or symlink** is staged under a name in the create
  stratum, since neither has an anonymous form, and published by a
  no-replace rename.

A staged name is `.stratafs-stage-` followed by the mount cookie and a
per-stage identifier, in a 64-byte buffer, with up to eight retries on
collision. It is excluded from resolution and from enumeration for the
mount that owns it, and removed if the copy-up fails. The exclusion is
local: a second stratafs mount sharing the create stratum, and every
direct reader of that directory, sees an ordinary entry containing a
partial copy.

<a id="trm-4-5-2-4-1"></a>

### Identifying staging entries <a id="cite-copy-up.orphan-recovery-checks-marker"></a>

A staged name alone is not proof of ownership, so each staged object
also carries a marker in the extended attribute
`security.peios.stratafs_staging`. The marker is a 24-byte
little-endian structure: a magic of `0x53544731` — ASCII `STG1` — a
version, its own size, a per-boot cookie, and the cookie of the mount
that created it.

Recovery of an orphan is therefore precise. A staged entry whose marker
is valid and whose owning mount is not live is removed; one belonging to
a live mount is left alone, and so is one whose marker is missing,
short, or carries the wrong magic, version or size. That matters
because two mounts may share a create stratum, and an unqualified
cleanup would have each new mount destroy the other's copy-up in
flight.

The scan runs in batches of 128 names, with resume, and is triggered
from five places: mounting, opening a directory, looking up a name
beginning with the staging prefix, copying up into a directory, and the
emptiness test of [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) before it scans the create stratum's participating
directory, after the caller's traverse/list access has been checked.

The fifth exists because the other four only reach directories somebody
visits. An orphan in a directory that is never opened, looked up, or
copied into would otherwise block `rmdir`: a dead mount's stages are not
in the current mount's in-flight list and would be counted as ordinary
entries. Recovery before that scan reaches the affected directory
without recursively visiting every directory at mount time. It also
means the create directory is scanned for recovery when its merged
emptiness is tested, even if it ultimately proves nonempty.

The marker is removed after publication. A failure to remove it is only
warned about, leaving the marker on the published copy until a later
lookup cleans it.

<a id="trm-4-5-2-5"></a>

## Failed copy-up and rollback <a id="cite-copy-up.failure-leaves-no-entry"></a>

Where a copy-up fails for any reason, the create stratum is left with
no new entry at the target path and the operation fails. Nothing falls
back to a weaker replication: an object whose descriptor or extended
attributes could not be preserved is never published. A published copy
whose descriptor handoff then fails is rolled back.

<a id="trm-4-5-2-6"></a>

## Concurrent modification <a id="cite-copy-up.no-source-snapshot"></a>

The provider may be modified while it is being copied, by a writer that
does not know stratafs exists.

Copy-up reads the provider as any reader would, with no locking of the
source and no snapshot, and offers no stronger consistency than an
ordinary read of that object. Where the provider is modified during the
copy, the copy may contain bytes from more than one state of the
source, exactly as a concurrent `read` of the same object may.

Nothing detects that and restarts — there is no retry loop, no
generation check. Equally, nothing blocks waiting for a quiescent
source, and nothing fails a copy-up merely because the source is being
written.

What *is* guaranteed is that the published object never appears in a
partial state, because staging and publication are properties of the
create stratum's filesystem, which stratafs does control.

<a id="trm-4-5-2-6-1"></a>

### Independence after publication <a id="cite-copy-up.published-copy-independent"></a>

Once published, the copy is independent of its source. Subsequent
modifications to the object it was copied from are not reflected in it,
and are not visible through the mount for as long as the copy provides
the name.

---

# Creation

_Peios Kernel / Internals / StrataFS / Mutation_

> Creation: behaviour and implementation of the Peios kernel.

<a id="trm-4-5-3"></a>

Creating a name held by no participating stratum places it in the
create stratum. <a id="cite-create.lands-in-create-stratum"></a>

1. If there is no create stratum, or it is absent, the operation fails
   with `EROFS`. <a id="cite-create.erofs-without-create-stratum"></a>
2. Any directories of the create stratum containing the name's path
   that do not exist are materialised as [Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>) requires for copy-up
   parents. Where the create stratum holds one of those components as
   something other than a directory, the operation fails with
   `ENOTDIR`; the blocking entry is not removed or replaced. <a id="cite-create.parent-conflict-enotdir"></a>
3. The name is created there.

All six kinds of creation — regular file, directory, symbolic link,
device node, FIFO, socket — go through one helper and one path.

The `ENOTDIR` case arises because creation routes positionally, into
the create stratum's subdirectory at the same path whether or not it
exists ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)). Where the create stratum holds that path as a file,
and a higher-precedence stratum provides it as a directory, the merged
directory exists and is reachable while its create-stratum counterpart
is blocked.

<a id="trm-4-5-3-1"></a>

## The security descriptor <a id="cite-create.descriptor-inherited-from-parent"></a>

A created object has no provider to inherit from, so its descriptor is
established by the ordinary creation semantics of the create stratum's
filesystem — by inheritance from the directory it is created in,
exactly as if it had been created there directly. The create is an
ordinary `vfs_create`, `vfs_mkdir`, `vfs_symlink` or `vfs_mknod`
against the real create-stratum parent, with the KACS creation decision
bound to that same parent.

This is cleanly separated from copy-up inside KACS: the copy-up branch
of the inode security initialisation is taken first and short-circuits
the inheritance builder entirely. Ordinary creation in a create stratum
inherits; copy-up preserves.

Where the creating interface lets the caller supply a descriptor — the
native open path does — it is honoured rather than replaced by an
inherited one. That is entirely KACS's doing; stratafs has no
descriptor parameter and cannot express it. All stratafs contributes is
re-anchoring the pending native create request onto the create-stratum
parent.

<a id="trm-4-5-3-2"></a>

## Dispositions that delete <a id="cite-create.supersede-is-removal-then-creation"></a>

A creating interface may offer a disposition that replaces an existing
object rather than opening it. In Peios that is the supersede
disposition of the native open path: KACS creates a temporary file
through the mount, opens it, and renames it onto the target, at which
point stratafs diverts the rename into a dedicated supersede path.

Such a disposition requires both removal and creation authority. This
does not prescribe their publication order. Before anything is created,
the removal is validated: the
target's provider must accept modification, or the operation fails with
`EROFS`. Before anything is removed, the replacement is checked for
reachability: if any stratum strictly above the create stratum, other
than the provider being removed, holds the name, the operation fails
with `EROFS`.

Without that guard the disposition could report success while leaving
the caller's new object invisible. The removal takes the name out of
the stratum that provided it; the creation puts the replacement in the
create stratum; and if some stratum between the two also holds the
name, it now outranks the replacement.

The creation half is treated as a creation throughout. It is never
reclassified as a modification of a newly-surfaced provider and never
copies one up: the caller asked for a new object, and its descriptor is
derived as above.

<a id="trm-4-5-3-2-1"></a>

### Implementation restrictions

Three restrictions are implementation choices rather than consequences
of the model:

1. Supersede applies to regular files only, and anything else is refused
   with `EOPNOTSUPP`. <a id="cite-create.supersede-regular-files-only"></a>
2. The source must be in the create stratum, and source and destination
   must share a parent. <a id="cite-create.supersede-source-and-parent-restrictions"></a>
3. Across distinct strata the two halves are **not** atomic. The staged
   file is renamed into place in the create stratum **before** the old
   provider is unlinked. Between those operations both backing names
   exist: ordinary precedence selects the replacement if the create
   stratum is higher, or retains the original until its removal if it is
   higher. A failure to publish leaves the original untouched, rather
   than exposing a still-lower provider. <a id="cite-create.supersede-is-not-atomic"></a>

   Write access to the original provider is probed before publication,
   then released while the replacement is published. It is reacquired
   for removal; a provider remounted read-only in between therefore fails
   with `EROFS` after publication. The two backing mounts never have
   simultaneous freeze-protection holds, even when they share a superblock.

   A later removal failure is returned to the caller and recorded as
   `supersede-removal`. Native-open cleanup then attempts to remove the
   newly published object, following its final name rather than its old
   temporary name. If the original still has its name, successful
   cleanup restores its visibility; concurrent provider changes are
   preserved. Cleanup is itself a filesystem operation and can fail;
   in that case both entries can remain, with ordinary precedence
   deciding which is visible. A crash between publication and removal
   can likewise leave both. This ordering narrows the destructive
   failure window; it does not promise a transaction or crash recovery.

   When both objects are in the create stratum, replacement uses one
   backing-filesystem rename and needs no separate provider unlink.

<a id="trm-4-5-3-4"></a>

## Exclusive creation <a id="cite-create.exclusive-eexist-from-any-stratum"></a>

Where creation is requested exclusively, the name must not exist in
**any** participating stratum, and a name provided by a lower stratum
causes `EEXIST` even though the create stratum does not hold it.

Nothing in stratafs implements this, and nothing needs to. The merged
lookup instantiates a positive dentry whenever any stratum holds the
name, and the VFS refuses `O_EXCL` on a dentry it did not create. The
`excl` argument stratafs receives is ignored. There is a race backstop
in the create path — a positive dentry appearing in the create stratum
yields `EEXIST` — but it sees only that one stratum.

Exclusive creation asks whether the name is free, and through this
mount it is not: a caller that created it anyway would find their
object shadowing a file they did not know was there, or masking a whole
subtree.

<a id="trm-4-5-3-5"></a>

## Non-exclusive creation over a shadowed name <a id="cite-create.shadowed-non-exclusive-is-open"></a>

Where creation is not exclusive and a lower stratum provides the name,
the merged dentry is positive, so the VFS never calls the create path
at all. The operation is an open, and [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) routes it.

Where the provider is a regular file that does not accept modification
and the create stratum has higher precedence, the result is a copy-up
followed by the requested modification, including truncation where
`O_TRUNC` was requested. `O_TRUNC` is stripped from the backing open on
a non-in-place route precisely so that the copy-up source is not
destroyed before it is read.

Where the provider is a FIFO, socket, or device node, no copy-up occurs
and the open is forwarded to the provider. Such an open succeeds
whether or not the provider accepts modification: opening a special
file does not modify it.

<a id="trm-4-5-3-6"></a>

## Unnamed files <a id="cite-create.unnamed-file-in-create-stratum"></a>

A file may be created without a name, for later linking into place. In
a merged directory this is supported, and the file is created on the
create stratum's filesystem, recorded with the create stratum's index
and marked unnamed.

Where the mount has no create stratum, or it is absent, the operation
fails with `EROFS`. Parent materialisation applies as for a named
creation: the create stratum's counterpart of the directory the
operation named is materialised, and the new file's descriptor is
derived by inheritance from it, because that directory is what the
descriptor must come from. Linking such a file into the mount is
governed by [Links](</kernel/internals/stratafs/mutation/links.md#trm-4-5-6>).

---

# Removal

_Peios Kernel / Internals / StrataFS / Mutation_

> stratafs has no whiteouts, so removal can only remove an entry that is really there — and what removal therefore never does.

<a id="trm-4-5-4"></a>

stratafs has no whiteouts and cannot record that a name should be
absent. Removal can therefore only remove an entry that is actually
there, in a stratum it may write to.

<a id="trm-4-5-4-1"></a>

## Unlinking <a id="cite-remove.unlink-in-provider"></a>

To remove a non-directory name from a merged directory: if the provider
accepts modification ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), the entry is removed from the provider;
otherwise the operation fails with `EROFS`. The parent is resolved in
the provider's stratum, and the unlink is performed there.

The provider need not be the create stratum. Any stratum that accepts
modification may have an entry removed from it, by the same rule that
allows an object it provides to be modified in place.

Where a lower-precedence stratum also holds the name, that entry
becomes the provider once the higher one is removed, and the name
remains visible, now resolving to the lower stratum's object. That is
not an error and is not reported as one: the removal succeeded, and the
entry it removed is gone. The dentry is dropped on success, so the next
lookup finds the lower entry.

Removing an object that a lower stratum also provides is how a
modification is undone. Where a file was copied up in order to be
edited, removing it through the mount discards the edit and restores
the original, which remained untouched in its own stratum throughout.
Callers expecting POSIX removal will find the name still present
afterwards; [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records this as an intended divergence.

Refusal because the provider does not accept modification is `EROFS`,
with one exception: where the provider's inode is immutable it is
`EPERM`. The outer inode carries the provider's inode flags, so the VFS
refuses the removal before stratafs's own `EROFS` test is reached — and
`EPERM` is what every filesystem returns for an immutable file, so the
distinction is the useful one rather than an accident worth papering
over. The `ro` flag and a read-only provider mount both still produce
`EROFS`.

<a id="trm-4-5-4-2"></a>

## Removing directories <a id="cite-remove.rmdir-merged-emptiness"></a>

The same rule applies, with one additional condition: the **merged**
directory must be empty. A directory is empty for this purpose only if
no participating stratum holds any entry within it, so a directory that
is empty in the provider but not in another participant fails with
`ENOTEMPTY`.

<a id="trm-4-5-4-2-1"></a>

### Access checks precede the emptiness scan <a id="cite-remove.access-before-emptiness"></a>

Because determining this reads the contents of every participating
stratum, the caller must hold traverse and list rights on each of them.
That check completes over all participants before any of them is
enumerated, so a refusal yields `EACCES` without disclosing whether the
directory was empty. Without that ordering the emptiness test would be
a disclosure channel: a caller who may not enumerate a protected
participant could learn whether it contains anything by attempting
`rmdir` and distinguishing `ENOTEMPTY` from success.

The emptiness scan filters this mount's in-flight staging entries, as
enumeration does. That does not authorise removing a live stage: the
provider can still refuse the physical removal with `ENOTEMPTY`.

<a id="trm-4-5-4-2-2"></a>

### Orphan recovery before inspection <a id="cite-remove.rmdir-staging-recovery"></a>

After the traverse/list checks complete, the emptiness test runs orphan
recovery on the create stratum's participating directory **before**
enumerating its contents ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)). A dead mount's entries are not in the
current mount's in-flight list, so waiting until that list has filtered
them would reject the directory before recovery could run. A directory
containing only recoverable orphan files or empty orphan directories can
therefore be removed without first opening or listing it.

Recovery requires the staging prefix, a valid marker, and an owner that
is no longer live. Missing or malformed markers, ordinary published
names, and stages belonging to a live mount remain untouched; they can
still make removal fail with `ENOTEMPTY`. The scan is local to the
participating create directory, not a recursive walk of the stratum.

Where the directory is removed and lower strata hold the same name as a
directory, the name remains visible as a merged directory of the
remaining strata — which, by the emptiness condition, is empty.

<a id="trm-4-5-4-3"></a>

## What removal never does <a id="cite-remove.touches-only-the-provider"></a>

Removal touches exactly one stratum, the provider's. The other strata
are opened read-only for the emptiness scan and nothing else. No entry,
marker, or object is created in any stratum to suppress a lower entry;
no whiteout machinery exists anywhere in the filesystem.

Success is never reported for a name whose provider entry was not
removed. The one place zero is returned without a removal is the
deferred path of [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>), where the entry the descriptor named is
already gone and the deletion is genuinely complete.

---

# Rename

_Peios Kernel / Internals / StrataFS / Mutation_

> Rename both removes and creates, so the source is bound by the removal constraint — atomic replacement, flags and RENAME_NOREPLACE ordering.

<a id="trm-4-5-5"></a>

Rename both removes a name and creates one. Because stratafs cannot
make a name disappear ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)), the constraint on the source is the
same as for removal, and the constraint on the destination follows from
the read-after-write direction of [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>).

For a rename of a source to a destination within one mount, letting `P`
be the source's provider:

1. `P` must accept modification. Otherwise `EROFS` — the source cannot
   be removed, so the rename would leave it still visible and amount to
   a copy. <a id="cite-rename.source-provider-must-be-writable"></a>
2. The destination must not be provided by a stratum of **higher**
   precedence than `P`. Otherwise `EROFS` — the renamed object would be
   shadowed at its destination and unreadable through the path it was
   renamed to. <a id="cite-rename.destination-not-higher-precedence"></a>
3. `P` must hold the directory containing the destination. Otherwise
   `EXDEV`. That directory is not created to satisfy the condition,
   whether or not `P` is the create stratum: parent materialisation
   exists to receive a copy-up, and a rename is not one. <a id="cite-rename.destination-parent-in-provider"></a>
4. Where the source is a directory, the merged directory must contain
   no entries provided by a stratum other than `P`. Otherwise `EXDEV`,
   since those entries cannot move with it. Determining this reads
   every participating stratum, so traverse and list rights are
   required on each, checked before any enumeration begins; where that
   is refused the rename fails with `EACCES` without disclosing whether
   other strata contributed. <a id="cite-rename.directory-source-must-not-strand-entries"></a>
5. Where the destination is provided, its type must match the source's.
   A non-directory onto a directory provider fails with `EISDIR`; a
   directory onto anything else fails with `ENOTDIR`. Only the
   provider's type is compared, since a lower stratum's entry of a
   different type is masked and contributes no inode. <a id="cite-rename.destination-type-must-match"></a>
6. Where the destination's provider is a directory, that merged
   directory must contain no entries at all — the same merged-emptiness
   test `rmdir` uses, with the same access requirement. Otherwise
   `ENOTEMPTY`. <a id="cite-rename.destination-directory-must-be-empty"></a>
7. The rename is performed within `P`: both parents are resolved at the
   provider's index, and a single `vfs_rename` is issued there. <a id="cite-rename.performed-within-the-provider"></a>

Where the destination is provided by a stratum of lower precedence than
`P` and both are non-directories, the rename succeeds and the renamed
object shadows it. Where the destination is held by `P` itself, it is
replaced, as on any filesystem. <a id="cite-rename.lower-destination-is-shadowed"></a>

Where the renamed object and the destination are both directories, the
result is not a shadowing: by [Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>) the renamed directory merges with
the lower strata's directories of that name. <a id="cite-rename.directory-destination-merges"></a> Condition 6 is what keeps
that tolerable — those directories are empty, so the merged result is
the renamed directory's own contents.

`P` need not be the create stratum. A rename is performed in whichever
stratum provides the source, provided that stratum accepts
modification. A rename whose source and destination are in different
mounts fails with `EXDEV`, refused by the VFS before stratafs is
consulted, and stratafs additionally refuses one spanning two mounts
inside the provider stratum. <a id="cite-rename.cross-mount-exdev"></a>

The immutable-provider caveat of [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) applies to condition 1 as well:
an immutable source yields `EPERM` from the VFS rather than `EROFS`. <a id="cite-rename.immutable-source-eperm"></a>

<a id="trm-4-5-5-1"></a>

## Replacing atomically <a id="cite-rename.replace-is-atomic"></a>

A rename onto an existing destination is the operation by which most
software replaces a file safely, and it works through a stratafs mount
for a destination provided by a lower stratum. That case is permitted
by condition 2: the destination is shadowed by the renamed object
rather than removed, so no whiteout is required, and the replacement is
a single `vfs_rename` within one directory pair of one stratum — atomic
on the filesystem holding `P`.

Where the source of such a rename is a temporary file the caller
created in the same directory, [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) placed it in the create stratum,
which never carries `ro`. Conditions 1 and 3 are then satisfied.

The contrast with the supersede disposition ([Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>)) is worth noticing:
that spans two strata and is not atomic.

<a id="trm-4-5-5-2"></a>

## Flags

Conditions 1 and 4 concern whether the source can be moved at all, and
apply under every flag. Conditions 2, 3, 5 and 6 concern the
destination.

| Flag | Behaviour |
|---|---|
| `RENAME_NOREPLACE` | The destination must not be held by **any** participating stratum, not merely by `P`. Conditions 2, 5 and 6 are not evaluated, since each presupposes a destination that exists; where any stratum holds the destination the rename fails with `EEXIST`. <a id="cite-rename.noreplace-checks-every-stratum"></a> |
| `RENAME_EXCHANGE` | Both names must be provided by the **same** stratum, and that stratum must accept modification; otherwise `EROFS`. Conditions 1 and 4 apply to both names. Conditions 2, 5 and 6 are not evaluated: an exchange swaps two names that both already exist, so neither type matching nor emptiness is required of either, exactly as on any filesystem. Condition 3 is subsumed. Where either name is a directory, no stratum other than the providing one may hold entries under either name; otherwise `EXDEV`. <a id="cite-rename.exchange-needs-one-stratum"></a> |
| `RENAME_WHITEOUT` | Fails with `EINVAL`, checked before everything else. stratafs has no whiteouts and cannot represent one. <a id="cite-rename.whiteout-flag-einval"></a> |

Exempting `RENAME_EXCHANGE` from conditions 5 and 6 is what leaves the
flag usable. Its ordinary purpose is to swap two populated directories
atomically, which condition 6 would refuse outright and condition 5
would refuse whenever the two differ in type. The stranded-entries
condition is the only destination constraint an exchange genuinely
needs, because it is the only one that arises from the names spanning
strata rather than from what the names hold.

<a id="trm-4-5-5-2-1"></a>

### The `RENAME_NOREPLACE` ordering <a id="cite-rename.noreplace-eexist-takes-precedence"></a>

A `RENAME_NOREPLACE` whose destination is held by any participating
stratum fails with `EEXIST`, and that `EEXIST` takes precedence over
conditions 1, 3 and 4. It is not stratafs that decides this. For
`RENAME_NOREPLACE` the VFS looks the destination up with `LOOKUP_EXCL`
and returns `EEXIST` for a positive dentry before `vfs_rename` runs at
all, and stratafs's merged lookup makes the dentry positive whenever any
stratum holds the name. `namei.c` is unpatched, so there is no point
inside `->rename` from which the order could be changed.

stratafs nonetheless evaluates conditions 1, 3 and 4 first, and the code
says so. That ordering is reachable only as a race backstop — where the
destination appeared between the VFS lookup and the rename — so a caller
should not expect `EROFS`, `EXDEV` or `EACCES` from a `RENAME_NOREPLACE`
whose destination already existed.

<a id="trm-4-5-5-3"></a>

## Other behaviour

Unknown `flags` bits are neither rejected nor masked; they pass through
to the VFS. <a id="cite-rename.unknown-flags-pass-through"></a> Where the two provider-level names resolve to one inode the
rename is a no-op returning success. <a id="cite-rename.same-inode-is-a-noop"></a> A dentry whose private state is
missing, or whose provider identity no longer matches, yields `ESTALE`. <a id="cite-rename.stale-dentry-estale"></a>
That refusal is per attempt, and the VFS heals it: `ESTALE` from a
rename makes the syscall retry once with a fresh walk, whose rebuilt
dentry carries the current provider identity, so the caller usually
observes the retry's outcome — a rename of the object now at the name —
rather than the errno. The refusal itself is recorded at the
`stratafs:stratafs_rename_stale` tracepoint, with the walk-time and
found inode numbers.
Because the filesystem sets `FS_RENAME_DOES_D_MOVE`, stratafs performs
the `d_move` or `d_exchange` itself, together with swapping the
dentries' recorded relative paths.

---

# Links

_Peios Kernel / Internals / StrataFS / Mutation_

> Hard links within one mount, linking an unnamed file, and how symbolic links are created.

<a id="trm-4-5-6"></a>

<a id="trm-4-5-6-1"></a>

## Hard links

To create a hard link from an existing name to a new name within one
mount, letting `P` be the source's provider:

1. `P` must accept modification. Otherwise `EXDEV`. <a id="cite-link.source-provider-must-be-writable"></a>
2. The destination must not be held by any participating stratum.
   Otherwise `EEXIST`. <a id="cite-link.destination-must-not-be-held"></a>
3. `P` must hold the directory containing the destination. Otherwise
   `EXDEV`. That directory is not created to satisfy the condition,
   whether or not `P` is the create stratum. <a id="cite-link.destination-parent-in-provider"></a>
4. The link is created in `P`. <a id="cite-link.created-in-the-provider"></a>

`P` need not be the create stratum: a link is made in whichever stratum
provides the source, since that is the only stratum in which the two
names can share an object. Condition 2 ensures the new link is not
shadowed at its destination, since no stratum — above `P` or below it —
holds that name.

Condition 2 is enforced by the VFS rather than by stratafs for a named
source: the link path looks the destination up with `LOOKUP_EXCL`, and
stratafs's merged lookup makes the dentry positive whenever any stratum
holds the name. stratafs's own test covers only the provider stratum
and is a race backstop. For an unnamed source it does check every
stratum explicitly.

A link request is never satisfied by copying the source up. <a id="cite-link.never-copies-up"></a> The result
would be a link to the copy rather than to the object named by the
source, so the two names would not share an object — which is the whole
of what a hard link is for. Refusing is the only correct answer.

`EXDEV` is used rather than `EROFS` because it is the error callers
already handle when a link cannot be made between two locations, and
because it is accurate: the link would have to span two strata, which
through this mount are two filesystems.

Where installing the outer inode fails after the lower link succeeded,
the link is rolled back; a failed rollback is audited. <a id="cite-link.rolled-back-on-install-failure"></a>

<a id="trm-4-5-6-2"></a>

## Linking an unnamed file <a id="cite-link.unnamed-goes-to-create-stratum"></a>

An unnamed file created under [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) is linked into the mount by the
rules for creation, not by those above: it has no provider, so
conditions 1 and 3 have no subject.

The link is created in the create stratum — a source recorded with any
other index is refused with `EXDEV` — and the operation follows [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>):
the name must not be held by any participating stratum, parent
directories are materialised in the create stratum, and a create
stratum that is absent or does not exist fails with `EROFS`.

<a id="trm-4-5-6-2-1"></a>

### Unnamed files cannot cross mounts <a id="cite-link.unnamed-cross-mount-exdev"></a>

Linking an unnamed file into a different mount fails with `EXDEV`,
checked both by superblock and by mount, and by the VFS as well.

<a id="trm-4-5-6-3"></a>

## Symbolic links <a id="cite-link.symlink-target-verbatim"></a>

Creating a symbolic link is an ordinary creation and follows [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>):
the link is created in the create stratum, with a security descriptor
established by inheritance there.

A symbolic link's target is stored and returned verbatim. The target
string is passed through untouched on creation, and on read the outer
inode's `get_link` calls the provider inode's own and returns its
result unmodified. No rewriting exists anywhere: a target naming a path
inside a stratum is not rewritten to name the corresponding path inside
the mount, nor the reverse.

Resolution of a symbolic link found in a stratum follows [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>). The
raw string goes back to the VFS, which interprets it as any filesystem's
target is interpreted, so an absolute target resolves from the process's
root and may re-enter this mount, a different stratafs mount, or none.
A link created directly in a stratum by that stratum's owner is
followed as written; the rule constrains only what stratafs itself
does, which is nothing.

---

# Locking

_Peios Kernel / Internals / StrataFS / Mutation_

> Advisory locks across a stack of independently writable directories — the rule, a changing provider, the retired provider, and leases.

<a id="trm-4-5-7"></a>

Advisory file locks — whole-file and record locks alike — exist so that
several writers of one file can coordinate. A stratafs mount is
established over directories that have their own writers, so a lock
taken through the mount and a lock taken directly on the same object
must be the same lock.

<a id="trm-4-5-7-1"></a>

## The rule <a id="cite-lock.taken-on-the-provider-object"></a>

A lock taken through a stratafs mount is held on the provider's object,
in the same lock space as a lock taken on that object by any other
path. Both the POSIX and the `flock` paths retarget the request onto
the descriptor's provider file, so the lock lands on the provider
inode's own lock context.

stratafs maintains no lock space of its own. There is no lock list, no
fallback onto the outer inode, and no per-inode lock state. Two callers
that lock the same provider object — one through the mount, one through
the stratum directly, or two through different stratafs mounts sharing
that stratum — contend with each other. Open-file-description locks are
re-owned onto the provider file so that their per-description semantics
are preserved.

<a id="trm-4-5-7-1-1"></a>

### Locking does not copy up <a id="cite-lock.no-copy-up-and-facs-rights-still-apply"></a>

Taking a lock does not modify an object, so it does not route ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>))
and cannot itself cause a copy-up. FACS still checks the descriptor's
granted rights ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)): a shared lock requires `FILE_READ_DATA`, and an
exclusive lock requires `FILE_WRITE_DATA` or `FILE_APPEND_DATA`. A
read-only descriptor can therefore carry a shared lock, but not an
exclusive lock without a write grant.

<a id="trm-4-5-7-2"></a>

## Locks and a changing provider <a id="cite-lock.not-transferred-on-provider-change"></a>

A lock is held on the object a descriptor resolved to. That object may
cease to be the provider afterwards — because a higher-precedence
stratum gains the name, because the object is removed from its stratum,
or because a copy-up produced a new object.

In every such case the lock remains held on the object it was taken on.
It is not transferred, and it does not begin to guard the new provider.

**Two callers may therefore hold exclusive locks on one merged path
without contending**, whenever they opened it either side of a change of
provider. Neither is wrong about the object it locked; they locked
different objects, and each lock is honoured by everything else holding
that object. The merged path is what stopped naming one thing. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>)
records it.

A caller that must be sure it holds a lock on the current provider has
to reopen and re-take it, which is the same discipline required of
anything that locks a path another process may replace by rename. The
exposure here is that a copy-up is a replacement the caller did not
perform and cannot see.

<a id="trm-4-5-7-3"></a>

## The retired provider

Copy-up does not close the file it copied from. The pre-copy-up
provider file is moved aside into the descriptor's private state
specifically to keep locks and leases taken before the copy-up alive,
and the fan-out that follows is invisible to the specification but
visible in behaviour:

- A POSIX or `flock` **unlock** is applied to both the retired file and
  the copy; a non-unlock request goes only to the copy. <a id="cite-lock.unlock-reaches-the-retired-file"></a>
- A lease release is applied to both. A lease *acquisition* is
  redirected to the retired file when that file already holds a lease
  of the same flavour. <a id="cite-lock.lease-acquisition-redirected"></a>
- Querying a lease returns the stronger of the two files' lease types,
  ordering write above read above none. <a id="cite-lock.lease-query-returns-the-stronger"></a>
- Closing the descriptor runs the underlying flush and removes POSIX
  locks on both files, and releasing it breaks leases on both, using
  the outer file as the owner identity. <a id="cite-lock.close-clears-both-files"></a>

All of it is serialised by the descriptor's mutation lock.

<a id="trm-4-5-7-4"></a>

## Leases and mandatory locking <a id="cite-lock.leases-are-the-providers"></a>

Leases are established on the provider's object, in that object's own
lock space, and every result is the provider's own, returned unchanged.
stratafs neither adds to nor removes from whatever semantics the
provider's filesystem gives them, and never reports a lock as
established where the provider's filesystem refused it.

Mandatory locking has no subject here: the platform does not offer it,
and stratafs contains nothing that would obstruct it. The outer inode
copies the provider's inode flags wholesale.

<a id="trm-4-5-7-5"></a>

## Internal locks

The specification names no internal lock and fixes no acquisition
order. The implementation's hierarchy, outermost first:

1. The per-open-file **mutation lock**, taken by every operation that
   may copy up.
2. The per-outer-inode **rebind lock**, taken inside it whenever an
   inode's provider is swapped.
3. The dentry lock or the inode lock, taken inside the rebind lock and
   never overlapping each other.

The superblock's identity lock and staging lock are each taken alone.
`copy_file_range` and `remap_file_range` deliberately do not nest the
two files' mutation locks: the input file's is taken, a reference
grabbed, and released before the output file's is taken.

StrataFS assigns inode and per-file lockdep classes during initialization,
before publication. The inode's `i_rwsem` and the file's mutation lock use
classes based on the mount's admitted stacking depth. Directory and
non-directory inodes use separate classes.

Dynamic path resolution can reach a different depth, so these classes do
not guarantee descending acquisition order. Lockdep still records
dependencies and detects reverse-order cycles across depths.

Reads and writes select and retain a reference to their backing file
under the mutation lock. Writes finish routing, any copy-up, and append
flag synchronization before releasing it. The data transfer runs without
the mutation lock because faults on user buffers can acquire the memory
mapping lock. An operation finishes against its selected provider even if a
concurrent operation copies up the descriptor. Writes that complete
successfully before forwarding returns refresh the outer inode from its
current provider under the mutation lock.

Shared write-capable mapping preparation follows the backing chain through
StrataFS and FUSE passthrough. It takes each StrataFS layer's mutation lock
before the VFS acquires `mmap_lock`, then releases it before preparing the
next layer. Each forwarding step uses the credentials that its backing
mapping would use.

StrataFS does not take the mutation lock, resolve paths, perform copy-up,
or acquire provider freeze protection in its mapping callback.

A separate leaf spinlock protects the backing file and matching provider
index. Copy-up publishes this pair while holding the mutation lock. The
mapping callback takes a reference to the selected file under the leaf
lock, then releases the lock before checking the route, auditing a refusal,
or forwarding to the backing filesystem. The reference preserves identity
and lifetime, not the provider's read-only or immutable state. A changed
route can require the caller to retry the whole mapping operation.

For mutations the ordering is: the KACS decision, then parent
materialisation, then write access on the target mount, then the
parent's directory lock through the VFS's create, remove or rename
helpers. Refusal auditing takes the dentry lock with an atomic
allocation first and falls back to the rebind lock only if that fails,
so the two are never nested.

Backing-filesystem freeze protection is held for one mutation stage at a
time. Regular-file copy-up releases its creation-stage mount write hold
while copying contents: reads and writes keep their ordinary permission
and pre-content notification checks, and each write acquires its own
freeze protection. It reacquires the mount write hold before copying
metadata or publishing the anonymous stage; failure to reacquire aborts
the copy without publishing it. This permits a pending filesystem freeze
to complete between stages without a writer waiting on itself.
<a id="cite-lock.copy-up-content-without-outer-writer"></a>

Supersede releases the create mount's write hold before acquiring
the original provider's hold for removal. Rename's merged-destination
emptiness scan, which can recover orphan staging objects, runs without a
backing write hold retained by rename; recovery acquires its own. An early
write-access probe preserves the read-only refusal, and the mutation
reacquires write access before taking its backing directory locks.

---

# Durability and Accounting

_Peios Kernel / Internals / StrataFS / Mutation_

> stratafs holds no storage, so durability and accounting belong to the providers — except where a merged directory needs a rule of its own.

<a id="trm-4-5-8"></a>

stratafs holds no storage, so durability is the providers' and the
accounting is theirs too. Two operations nonetheless need a rule,
because a merged directory has no single provider to forward to.

<a id="trm-4-5-8-1"></a>

## Synchronising an object <a id="cite-durability.fsync-follows-the-descriptor"></a>

Synchronising a non-directory is forwarded to the object the descriptor
resolved to — the descriptor's own provider file — and reports what
that object's filesystem reports. No path re-resolution happens, so it
is never forwarded to whichever object currently provides the path.
Where the two differ, the data the caller wrote is on the object it
opened, and synchronising anything else would report success while
leaving that data unsynchronised.

Where a copy-up has occurred through this descriptor, the descriptor's
object is the copy, and it is the copy that is synchronised. The
retired pre-copy-up file ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)) is not.

<a id="trm-4-5-8-2"></a>

## Synchronising a merged directory <a id="cite-durability.dirsync-covers-every-stratum-at-call-time"></a>

Synchronising a merged directory synchronises the corresponding
directory in **every** stratum of the mount that holds it at the time
of the call, and fails if any of them fails. The loop continues past a
failure, so every stratum is still attempted, and the first error is
what is returned.

The set is evaluated when the operation runs, not when the descriptor
was opened: the directory is re-resolved across all strata rather than
read from the participant set settled at open ([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)). Both halves of
that matter:

- Evaluating at call time catches a directory the create stratum did
  not hold when the descriptor was opened and does now — which is
  exactly what happens when a file is created through that descriptor
  and [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) materialises its parent.
- Covering every stratum rather than the provider alone is required by
  the atomic-replace pattern of [Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>), whose rename is performed in
  the stratum that provided the *source*, which need not be the stratum
  providing the merged directory.

Durability is a question about what is on disk now, which is why this
is the one place a merged directory is treated as its current set of
real directories rather than as the thing a descriptor was opened
against.

<a id="trm-4-5-8-3"></a>

## Freezing <a id="cite-durability.freeze-eopnotsupp"></a>

A stratafs mount has no storage to quiesce. Freezing returns
`EOPNOTSUPP` and propagates nothing to any stratum's filesystem; no
unfreeze, freeze-super or thaw-super operation is registered at all.
Freezing the filesystem a stratum lives on is done through that
filesystem, and affects the merged view as it affects any other reader
of that stratum.

<a id="trm-4-5-8-4"></a>

## Storage accounting

Storage consumed by an object created through the mount, or copied up
into the create stratum, is consumed on the create stratum's filesystem
and accounted there. <a id="cite-durability.storage-charged-to-create-stratum"></a>

<a id="trm-4-5-8-4-1"></a>

### The principal charged by quota <a id="cite-durability.copy-up-accounted-to-preserved-owner"></a>

Disk quota keys on the POSIX owner, and copy-up preserves it ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)):
the staged object is created with the calling task's credentials, and
the ownership is then set to the source's under the mount's own
credential. <a id="cite-durability.copy-up-preserves-posix-owner"></a> A copy is therefore accounted to the owner of the object
it was copied from, not to the caller who caused it.

The KACS security descriptor, including its owner SID ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), is
preserved alongside it. <a id="cite-durability.copy-up-preserves-owner-sid"></a> The two notions of owner agree, and both
name the object rather than whoever provoked the copy — which is what
[Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) relies on when it permits a caller to cause a copy into a
directory they hold no rights over.

Ownership is what accounting follows; the caller who caused the copy is
recorded in the audit record of [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) instead.

---

# Strata and mounting

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> Find the Peios kernel articles about strata and mounting.

Use these articles to understand strata and mounting in the Peios kernel.

- [The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md>)
- [Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md>)
- [Absent Strata](</kernel/internals/stratafs/strata-and-mounting/absent-strata.md>)

---

# The Stratum Stack

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> A mount is its stratum stack — an ordered, non-empty list fixed for the mount's life — plus the resolution context and the create stratum.

<a id="trm-4-2-1"></a>

A mount is defined by its stratum stack: an ordered, non-empty list of
strata, highest-precedence first. The stack is fixed for the life of
the mount. Nothing reorders it, and precedence never varies by path, by
caller, or by operation. <a id="cite-strata.stack-fixed-and-ordered"></a>

Index 0 is the highest-precedence stratum. That convention runs all the
way through: strata are stored in a fixed array in mount-option order,
presence across the stack is a `u64` bitmap indexed by the same
position, and selecting the provider is the trailing-zero count of that
bitmap — the lowest set index, which is the highest-precedence stratum
that holds the name.

The array is `STRATAFS_MAX_STRATA` entries, which is **16**. A stack
longer than that is refused at parse time. <a id="cite-strata.max-sixteen"></a> Absence never renumbers
anything: an absent stratum simply has its bit clear, keeping its slot
and its precedence.

<a id="trm-4-2-1-1"></a>

## A stratum is a path <a id="cite-strata.no-cached-resolution"></a>

What is stored for each stratum is a string and a flag word — nothing
else. No reference is held on a stratum's directory, and no resolution
result is retained across operations. Every time a name is resolved,
the stratum's path string is joined with the relative path of the name
and walked from scratch.

This is what makes a stratum follow a wholesale replacement. A package
transaction that renames the old tree aside and the new tree into place
leaves the original directory object intact and referenced by anything
that held it; a stratum defined as that object would go on serving the
replaced tree. Defined as a path, it follows.

The cost is that every lookup does the walk. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers what that
means in practice, because the implementation does not cache
resolutions at all.

<a id="trm-4-2-1-2"></a>

## The resolution context <a id="cite-mount.resolution-context-pinned"></a>

Stratum paths are joined absolute and walked from a root captured when
the mount was created — the creating process's own filesystem root —
under credentials captured at the same moment. Both are pinned for the
life of the mount and released only when the superblock is freed.

The credential override matters as much as the root. A stratum path is
resolved with the mounter's credentials, not with those of whatever
process later touches the mount, so a caller in a different mount
namespace cannot shift what a stratum denotes, and the paths reported
by the origin attribute ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) always name the same things.

Symbolic links and mounts along a stratum's path are followed as they
stand at the moment of resolution, since the walk is an ordinary
`filename_lookup` with no restricting flags. A mount established inside
a stratum is therefore part of that stratum's tree, and one stratum can
span several filesystems — which [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>) has to account for when
deriving inode numbers.

<a id="trm-4-2-1-3"></a>

## What a stratum's filesystem must provide <a id="cite-strata.mount-time-checks"></a>

Nothing beyond ordinary directory and file operations. stratafs probes
no capability at mount time: it checks only that each stratum path
resolves, names a directory, is not a duplicate of another stratum, and
does not push the composed stack past the kernel's maximum stacking
depth. There is no test for a usable directory version value, because
nothing in the implementation would use one.

<a id="trm-4-2-1-4"></a>

## Flags <a id="cite-strata.stack-errors-are-einval"></a>

Each stratum carries zero or more flags, declared with it in the mount
options and stored as a bit field.

| Flag | Bit | Meaning |
|---|---|---|
| `create` | `STRATAFS_F_CREATE` | This stratum receives newly created objects and is the destination of copy-up. |
| `ro` | `STRATAFS_F_RO` | stratafs does not modify this stratum. |
| `am` | `STRATAFS_F_AM` | This stratum's directory may be absent. |

The stack-wide rules are decided in Rust, in `stratafs-core`: the stack
must be non-empty, must not exceed 16 strata, must contain no
unrecognised flag bit, must not carry `create` twice, and must not
carry `create` and `ro` on one stratum. The crate distinguishes five
error cases, but the C boundary collapses all of them to `EINVAL`, so
the distinction is not observable to a caller.

<a id="trm-4-2-1-4-1"></a>

### `create` <a id="cite-strata.create-designates-creation-and-copy-up-destination"></a>

At most one stratum carries `create`, and a stack may carry none, in
which case `create_index` is `-1` and every creation and every copy-up
is refused with `EROFS`. Modification of an object provided by a
stratum that accepts modification is unaffected, because routing tests
the provider before it consults the create stratum at all ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).

`create` does not mean "writable", and it is not the only stratum
stratafs writes to. It designates where objects that do not yet exist
in any stratum are created, and where an object is copied when its
provider will not accept a modification. A stratum carrying neither
`create` nor `ro` is modified in place, and any number of such strata
may sit above the create stratum, below it, or both.

<a id="trm-4-2-1-4-2"></a>

### `ro` <a id="cite-strata.ro-is-independent-of-filesystem"></a>

`ro` is a stratafs-level assertion, independent of whether the
stratum's filesystem is itself read-only. It is one of three terms in
the predicate that decides whether a stratum **accepts modification**
of an object it provides:

- the stratum does not carry `ro`;
- the provider's mount is not read-only;
- the provider's inode is not marked immutable.

The predicate takes only the superblock, the stratum index, and the
provider path. It reads no credentials, consults no security
descriptor, and calls into KACS not at all — which is what stops a
caller who has been *refused* write access from provoking a copy-up
([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).

Note the third term is specifically the immutable inode flag. A file
that is unwritable by its mode bits is not excluded by this predicate;
the write is routed in place and the underlying filesystem refuses it.

<a id="trm-4-2-1-4-3"></a>

### `am` <a id="cite-strata.am-governs-mount-time-only"></a>

Without `am`, a stratum's directory must exist when the mount is
created, and a mount whose stratum directory is absent fails with
`ENOENT`. With `am`, an absent directory is accepted at mount time.

The flag governs mount time only. At runtime the resolver never
consults it: a stratum whose directory has gone is skipped exactly the
same way whether or not it carries `am`. [Absent Strata](</kernel/internals/stratafs/strata-and-mounting/absent-strata.md#trm-4-2-4>) covers what absence
means once the mount is live.

---

# Mount Admission

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> What a caller must be entitled to and what a configuration must satisfy — evaluation order, loop detection, and mount immutability.

<a id="trm-4-2-3"></a>

A stratafs mount is configured entirely at mount time. This section
covers what the caller must be entitled to, the conditions a
configuration has to satisfy, and the order in which those conditions
are evaluated.

<a id="trm-4-2-3-1"></a>

## Entitlement <a id="cite-mount.create-requires-init-userns-cap"></a>

Establishing a mount with no create stratum takes no privilege of its
own. The filesystem type carries `FS_USERNS_MOUNT`, and stratafs is on
the allowlist of types a mount namespace's descriptor may admit
([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)), so a caller may establish one in a mount namespace it created
without the mount privilege; what the caller needs beyond that is only
the access that resolving the stratum paths already requires, which
falls out of the resolution itself. A user namespace by itself confers
nothing here, as everywhere under KACS.

A stack that carries `create` is different. Copy-up is authorised by
the outer handle and deliberately requires no add-entry right on the
create stratum ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)), so the mount configuration carries authority
to materialise names in a real directory outside the mount. The caller
establishing such a stack must be operating in the **initial** user
namespace and hold `CAP_SYS_ADMIN` there; anything else fails with
`EPERM`.

The test is made in `get_tree`, before the tree is built and therefore
before any stratum path is resolved, and it is stricter than requiring
the capability alone: the credential's own user namespace must *be* the
initial one, not merely a namespace in which the capability resolves.
This is the closure the KACS copy-up context depends on. The check is
made once, when the immutable stack is established, rather than at each
copy-up, so descriptor delegation cannot reintroduce authorisation
against the acting task, and no reconfiguration can re-supply the
strata list.

There is no explicit per-stratum entitlement check in the mount path.
Both halves come out of the ordinary machinery: traverse rights are
enforced by the path walk, which runs under the mounting caller's
credentials, and the right to read a stratum directory's attributes is
enforced by using the security-checking `vfs_getattr` rather than its
unchecked variant, which reaches KACS's `getattr` hook and demands
`FILE_READ_ATTRIBUTES`.

One seam is worth recording: the path walk uses the credentials
captured on the filesystem context, while `vfs_getattr` runs outside
that override and so uses the acting task's. For a mount established
the ordinary way the two are the same task. For one established with
`fsopen` and `fsconfig` from different tasks they need not be.

Nothing re-checks entitlement if a stratum directory later appears.
That is sound because every access through the mount is checked against
the providing object in any case ([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)), so a caller who mounts a
stratum they cannot read still cannot read it.

<a id="trm-4-2-3-2"></a>

## Validity

| Condition | Error |
|---|---|
| The stratum stack is empty | `EINVAL` <a id="cite-mount.admit.empty-stack-einval"></a> |
| The stack exceeds 16 strata | `EINVAL` <a id="cite-mount.admit.too-many-strata-einval"></a> |
| More than one stratum carries `create` | `EINVAL` <a id="cite-mount.admit.multiple-create-einval"></a> |
| A stratum carries both `create` and `ro` | `EINVAL` <a id="cite-mount.admit.create-with-ro-einval"></a> |
| The same directory appears as more than one stratum | `EINVAL` <a id="cite-mount.admit.duplicate-stratum-einval"></a> |
| A malformed `strata=` value ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` <a id="cite-mount.admit.malformed-value-einval"></a> |
| A create-bearing stack from outside the initial user namespace, or without `CAP_SYS_ADMIN` there | `EPERM` <a id="cite-mount.admit.create-requires-privilege-eperm"></a> |
| A stratum's path names something other than a directory | `ENOTDIR` <a id="cite-mount.admit.not-a-directory-enotdir"></a> |
| A stratum's directory is absent and the stratum does not carry `am` | `ENOENT` <a id="cite-mount.admit.absent-without-am-enoent"></a> |
| The composed stack reaches the kernel's maximum stacking depth | `ELOOP` <a id="cite-mount.admit.stacking-depth-eloop"></a> |
| A stratum lies within the mount point, or within another stratafs mount whose strata include this mount point | `ELOOP` <a id="cite-mount.admit.recursive-stratum-eloop"></a> |
| Sixteen consecutive collisions allocating a mount cookie | `EAGAIN` <a id="cite-mount.admit.cookie-exhaustion-eagain"></a> |

Two strata are the same directory when they resolve to the same
directory object, not merely when their paths are equal as strings: the
comparison is on resolved inodes, so two paths reaching one directory
through different symbolic links or bind mounts are caught. Absent
strata are skipped and never compared. <a id="cite-mount.duplicate-strata-by-inode"></a>

<a id="trm-4-2-3-3"></a>

## Evaluation order <a id="cite-mount.admission-evaluation-order"></a>

The conditions that depend on nothing but the option string are decided
first, during parsing and stack-wide validation, and are reported
whatever the caller's access. The `EPERM` admission test comes next, in
`get_tree`, still before any path is touched. Only then are the strata
resolved.

The purpose of that ordering is to stop the validity conditions being
an oracle: a caller with no right to traverse a directory should not be
able to name it as a stratum and learn from the errno whether it exists
and whether it is a directory.

The path walk and the attribute read both run under the caller's
credentials, so a path the caller cannot resolve returns `EACCES` from
the walk itself, and the `EACCES` is propagated unchanged.

The check is stack-wide because it runs in two passes. The first
resolves and stats every stratum; an `EACCES` from any of them is the
answer, whatever an earlier stratum reported. Only when every stratum
has passed entitlement does the second pass apply the type, duplicate
and depth conditions. A caller who names a readable non-directory first
and an unreadable path second is told `EACCES`, not `ENOTDIR`.
<a id="cite-mount.entitlement-is-decided-in-two-passes"></a>

The mount-point loop condition is evaluated in a different call
entirely, after the tree has been built, and so always follows every
entitlement check.

<a id="trm-4-2-3-4"></a>

## Loops <a id="cite-mount.loop-detected-at-mount"></a>

A stratum inside the mount point is detected directly. The indirect
case — a stratum inside *another* stratafs mount whose own strata
include this mount point — is detected by recursing into any stratum
whose superblock carries the stratafs magic, bounded by a visited-
superblock set and by the kernel's maximum stacking depth. This runs
through a Peios-added `super_operations` hook, `validate_mountpoint`,
wired into the new-mount, bind and move-mount paths by the patch series;
it is not an upstream interface.

That check cannot bind after the fact: a mount established within a
stratum, or a bind mount of this mount into one of its own strata, can
create a cycle later. Resolution is guarded separately, and differently
— not by a depth counter but by a per-task, per-superblock re-entrancy
list. A task that is already resolving in a superblock and re-enters it
gets `ELOOP` immediately, so a cycle spanning any number of stratafs
mounts terminates the moment it returns to one it is already inside.

<a id="trm-4-2-3-5"></a>

## Immutability and mount identity <a id="cite-mount.strata-shared-between-mounts"></a>

The stack is fixed for the life of the mount; changing one is expressed
by unmounting and mounting again ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)).

Two stratafs mounts may name the same directory as a stratum. Each
resolves independently and neither is aware of the other; where both
have a create stratum in common they mutate the same objects, with the
same result as any two writers of one directory. There is no registry
of stratum paths to make them aware of each other.

There is a registry of *mounts*, but it exists for a different purpose.
Each mount draws a random non-zero cookie and inserts itself into a
global table, retrying up to sixteen times on collision; a second
random non-zero cookie is drawn once per boot. The pair identifies
which live mount owns a staging entry, so that a mount sharing a create
stratum can distinguish another mount's copy-up in flight from an
orphan left by a crash ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).

<a id="trm-4-2-3-6"></a>

## An all-absent stack <a id="cite-mount.all-absent-stack-is-legal"></a>

A mount succeeds even when no stratum root is present at all — a stack
whose only strata are absent `am` strata is legal. The root inode is
constructed with no provider, and reports mode `S_IFDIR` with no
permission bits.

Such a root still carries a security descriptor, since an object with
none would refuse every access check made on the mount root and the
provider-less root could never be observed. stratafs synthesises it:
owned by the mounter, with read and traverse for everyone, and nothing
more — there is nothing beneath such a root to write. The moment a
stratum root appears the root's descriptor is that root's own, and
when it goes again the synthesised one returns; KACS never caches a
StrataFS root's descriptor, so no access is decided against a root that
has since gained or lost its provider. <a id="cite-mount.all-absent-root-serves-a-synthesised-descriptor"></a>

---

# Absent Strata

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> A stratum's directory may not exist — what happens while it is absent, and what appearing, disappearing and reappearing do.

<a id="trm-4-2-4"></a>

A stratum's directory may not exist. It may be absent when the mount is
created — which requires `am` ([Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>)) — or exist at mount time and be
removed while the mount is live, which nothing prevents for any
stratum.

<a id="trm-4-2-4-1"></a>

## While absent <a id="cite-strata.absent-contributes-nothing"></a>

An absent stratum holds no names, participates in no merged directory,
and contributes no entries to any enumeration. It keeps its position
and its precedence; only its presence bit is clear.

The mechanism is a single test in the resolver. Resolving one stratum
either succeeds, or fails with `ENOENT` or `ENOTDIR`, in which case the
stratum is skipped and its bit is left clear. Any other error —
`EACCES`, `EIO`, `ELOOP`, `ENAMETOOLONG`, `ESTALE` — is not treated as
absence and fails the whole resolution instead. So a stratum that is
unreadable for a reason other than not being there masks the name for
every stratum, rather than being passed over.

An absent create stratum additionally causes every operation that would
create or copy up to fail with `EROFS`. The create stratum's root is
re-resolved at the point of use and its `ENOENT` is mapped to `EROFS`
by each of the paths that needs it — the copy-up parent walk, the
creation authorisation pre-check, and the routing decision, which
computes create-stratum presence live and requires the result to be a
directory. stratafs does not create the stratum's own directory to
satisfy such an operation: establishing that directory, with the
security descriptor it should have, belongs to whatever provisions the
system, and a mount that minted it would be choosing that descriptor.

<a id="trm-4-2-4-2"></a>

## Appearing and disappearing <a id="cite-strata.appearance-observed-on-next-lookup"></a>

Neither event is detected. Both are simply observed, because there is
nothing to invalidate.

A stratum's directory is never held; only its path string is. Every
resolution walks that string afresh, so a directory that comes into
existence is picked up by the very next lookup, and one that is
removed, renamed away, or replaced by another directory is picked up
just as immediately — the walk finds nothing, or finds the replacement.

The specification describes this in terms of a version tuple recorded
over the nearest existing ancestor of an absent stratum's path, and an
identity comparison for a stratum that disappears. Neither exists in
the implementation, and neither is needed: they are the machinery for
knowing when a *cached* resolution has gone stale, and nothing is
cached. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers the trade that represents.

The `am` flag is not consulted at runtime at all. It governs whether
the mount is allowed to be established with the directory missing, and
nothing more; a stratum without it that vanishes afterwards behaves
exactly like one with it.

<a id="trm-4-2-4-3"></a>

## Reappearance <a id="cite-strata.reappearance-preserves-inode-number"></a>

A stratum that disappears and reappears is the same stratum in the same
stack position, and nothing about the old directory is remembered.
Resolutions are recomputed against whatever the new directory holds.

Provider identity does survive the gap, though it is not resolution
memory. The derived inode number ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)) identifies the provider's
filesystem and inode number. If the same underlying object is reached
again — because the directory was renamed away and back rather than
replaced — it receives the same number it had before, without a
mount-lifetime pin on ordinary provider inodes. Only identities that
cannot be derived use the pinned fallback map. That is exactly what
the identity rule requires: equal numbers for one provider object,
whatever path reached it.

---

# Name resolution

_Peios Kernel / Internals / StrataFS / Name resolution_

> Find the Peios kernel articles about name resolution.

Use these articles to understand name resolution in the Peios kernel.

- [Lookup and type conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md>)
- [Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md>)
- [Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md>)

---

# Lookup and type conflicts

_Peios Kernel / Internals / StrataFS / Name resolution_

> Resolving one name in one directory — the provider, ancestors, independence from the caller, and staging entries.

<a id="trm-4-3-1"></a>

Resolution is defined for one name in one directory. Every path
operation is a sequence of such resolutions, each independent of the
last.

<a id="trm-4-3-1-1"></a>

## The provider <a id="cite-resolution.provider-is-highest-stratum"></a>

To resolve a name in a stratafs directory, the corresponding directory
of each stratum is examined in precedence order, and the first stratum
holding an entry of that name is its **provider**. If no stratum holds
it, the resolution produces a negative dentry and the VFS reports
`ENOENT`.

Mechanically, each stratum's path string is joined with the relative
path of the name and walked in full, once per stratum. A walk that
succeeds sets that stratum's bit in a presence bitmap; a walk that
fails with `ENOENT` or `ENOTDIR` leaves it clear and the stratum is
skipped. Selecting the provider is then the trailing-zero count of the
bitmap, computed in `stratafs-core`.

Any other error from a stratum's walk — `EACCES`, `EIO`, `ELOOP`,
`ENAMETOOLONG`, `ESTALE` — is not treated as absence. It fails the
whole resolution, so a stratum that is unreadable for a reason other
than not being there masks the name entirely rather than being passed
over.

A joined stratum path, or a child relative path, that would exceed
`PATH_MAX` fails with `ENAMETOOLONG`.

<a id="trm-4-3-1-2"></a>

## Ancestors <a id="cite-resolution.provider-chosen-per-component"></a>

Resolution does not consult a parent's provider to find a child's. A
name's provider is chosen afresh across all strata, so if `/a` is
provided by stratum 2, `/a/b` may still be provided by stratum 1 —
provided stratum 1 also holds `/a` as a directory and the two therefore
merge ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)).

What resolution does consult is whether any ancestor of the path is
masked. Before resolving the final component, every proper prefix of
the relative path is resolved across all strata and its merged provider
computed; a prefix whose provider is not a directory aborts the whole
resolution with `ENOTDIR`. That is what makes masking total ([Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>)),
and it is why a lookup costs one full walk per stratum for the name
itself plus one merged resolution per path component above it.

<a id="trm-4-3-1-3"></a>

## Independence from the caller <a id="cite-resolution.independent-of-caller"></a>

Resolution runs under the credentials captured at mount, against the
root captured at mount, and takes no operation argument. It does not
depend on the calling token, on what the caller is trying to do, or on
whether the operation will ultimately be permitted.

A name whose provider the caller may not access therefore resolves
normally and is then refused. It does not fall through to a lower
stratum — which would let a caller's rights change which file they
read, a considerably worse property than a denial.

<a id="trm-4-3-1-4"></a>

## Reaching the object <a id="cite-resolution.non-directory-forwarded"></a>

Once a name resolves to a non-directory provider, the object is the
provider's object and stratafs does not interpose on its contents. The
outer inode takes the provider's mode and, from it, the operations
tables for a regular file, symlink or special file; reads, writes,
mappings, splices, locks and `ioctl`s are forwarded to a backing file
opened on the provider.

Symbolic links are forwarded rather than followed. The outer inode's
`get_link` calls the provider inode's own and returns the raw target
verbatim; stratafs deliberately does not use `vfs_get_link`, which
would demand a read right the caller need not hold to traverse a link.
The VFS then interprets the target in the caller's own namespace, so an
absolute target resolves from the process's root and may re-enter this
mount, another stratafs mount, or none.

Where a mount is established at a path within a stratum, stratafs
follows it: the stratum walk is an ordinary `filename_lookup` with no
flag restricting it to one filesystem, and everything downstream
operates on the inner mount it returns.

<a id="trm-4-3-1-5"></a>

## Staging entries <a id="cite-resolution.staged-names-hidden"></a>

One class of name is invisible to resolution. While a copy-up is in
flight, its staged object may exist under a name in the create stratum;
that name is dropped from resolution for the mount that owns it, so an
incomplete copy is never reachable through the merged view ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
The suppression applies only to the create stratum, and only within the
owning mount — a second stratafs mount sharing that directory, and any
direct reader of it, sees an ordinary entry.

<a id="trm-4-3-1-5-1"></a>

### Recovery triggered by lookup <a id="cite-resolution.staging-prefix-triggers-recovery"></a>

Staged names begin with `.stratafs-stage-`, and a lookup of any name
with that prefix triggers a recovery scan of the create-stratum parent
before resolving. A resolution can therefore have the side effect of
removing orphaned staging entries from the create stratum.

<a id="trm-4-3-1-6"></a>

## Recursion <a id="cite-resolution.reentrant-superblock-eloop"></a>

A task that is already resolving inside a superblock and re-enters the
same superblock fails immediately with `ELOOP`. The guard is a global
list of task-and-superblock pairs, not a depth counter, so a cycle
formed after mount — a stratafs mount established inside one of its own
strata, or bind-mounted into one — terminates the moment resolution
returns to a mount it is already inside.

<a id="trm-4-3-3"></a>

Two strata may hold the same name with different types — a directory in
one, a regular file in another. The provider's type is the type of the
resolved object, and the outer inode is given the provider's mode and
the operations tables that follow from it. <a id="cite-resolution.conflict-provider-type-wins"></a>

- Where the provider is a **directory**, lower-precedence strata that
  hold the name as a directory participate in a merged directory
  ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)). Lower-precedence strata that hold the name as anything else
  are masked. <a id="cite-resolution.conflict-directory-merges-only-directories"></a>
- Where the provider is **not** a directory, every lower-precedence
  entry of that name is masked, whatever its type. <a id="cite-resolution.non-directory-masks-lower"></a> Only the provider's
  path is retained on the dentry; the other strata's references are
  released as soon as the provider is chosen.

<a id="trm-4-3-3-1"></a>

## Masking is total <a id="cite-resolution.masking-hides-whole-subtree"></a>

A masked entry is unreachable through the mount. Where the masked entry
is a directory, its entire subtree is unreachable: no path beneath the
masked name resolves, regardless of what the masked directory contains
and regardless of whether some other stratum holds part of that
subtree.

This is enforced by the ancestor pass described in [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>). Each proper
prefix of a relative path is resolved across every stratum and its
merged provider computed; a prefix whose merged provider is not a
directory returns `ENOTDIR` before the final component is considered.
Because the test uses the merged answer rather than a per-stratum one,
another stratum holding the subtree cannot rescue it.

A regular file at `/x` in a high-precedence stratum therefore hides a
whole `/x/…` tree in a lower one. That is severe, and deliberate: the
alternative — resolving `/x` as a file but `/x/y` through the masked
directory — would make a path's meaning depend on how far along it the
caller looked.

<a id="trm-4-3-3-1-1"></a>

### Masking leaves the strata unchanged <a id="cite-resolution.masking-does-not-modify-strata"></a>

Masking modifies nothing. Resolution and enumeration are read-only
throughout, no marker is written to any stratum, and the masked entry
remains present and unchanged in its own stratum, reachable by any path
that does not traverse the mount.

<a id="trm-4-3-3-2"></a>

## Stability <a id="cite-resolution.conflict-operation-fails-against-provider"></a>

Type conflicts resolve identically for every caller and every
operation, because provider selection is a pure function of the
presence bitmap and consults neither.

An operation that would only be valid against the masked type does not
cause the masked entry to be selected. It fails against the provider
instead, with whatever error that type produces — typically `ENOTDIR`
from the ancestor pass, or `EISDIR` raised by the generic VFS against
an outer inode carrying the provider's mode.

---

# Directory Merge

_Peios Kernel / Internals / StrataFS / Name resolution_

> When lower strata hold the same name as a directory the result is a merged directory — participation, its create stratum, and symlinks.

<a id="trm-4-3-2"></a>

Where a name's provider is a directory, and lower-precedence strata
hold the same name as a directory, the resolved object is a **merged
directory**.

<a id="trm-4-3-2-1"></a>

## Participation <a id="cite-resolution.merge-participants"></a>

The strata participating in a merged directory are, in precedence
order, those whose corresponding directory both exists and is a
directory. A stratum holding the name as a non-directory does not
participate and is masked entirely ([Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>)); a stratum not holding the
name simply does not participate.

Every consumer of a merged directory applies the same two-part filter —
the presence bit is set, and the resolved dentry is a directory — in a
single ascending loop over stratum indices with a `continue` for
non-participants. Nothing compacts or re-sorts, so relative precedence
within a merged directory is always the relative precedence in the
stack.

Merging is recursive, and it is recomputed rather than cached: there is
no merged-directory object anywhere. Each lookup and each directory
open rebuilds the full per-stratum path set from the relative path
string, so any child that is a directory in more than one stratum
merges at its own level by the same rule.

<a id="trm-4-3-2-1-1"></a>

### Participation at the mount root <a id="cite-resolution.root-participation"></a>

The root of a mount is a merged directory whose participants are the
mount's strata. The root has one special case: where the ordinary
provider rule would pick a stratum root that is present but not a
directory, the root instead takes the first stratum that is both
present and a directory, so an absent or non-directory stratum root
cannot change the synthetic root's type. A mount whose stratum roots
are all absent still has a root inode, with no provider and no
permission bits.

<a id="trm-4-3-2-2"></a>

## The create stratum of a merged directory <a id="cite-resolution.merge-create-stratum-is-positional"></a>

A merged directory's create stratum is the correspondingly-named
subdirectory of the mount's create stratum, at the same path relative
to the mount root — whether or not that subdirectory currently exists.
It follows that a merged directory has a create stratum even when the
mount's create stratum holds no part of that path, and creation still
routes there.

The derivation is positional and mount-wide: `create_index` is a single
integer on the superblock, fixed at mount, and every creation and
copy-up site reads it directly. Nothing re-derives it from which strata
happen to participate.

That matters because the alternative — taking the create stratum to be
the highest-precedence participating writable directory — would make
the destination of a write depend on which directories happened to
exist, so creating a file in a subdirectory could land in a different
stratum from creating one beside it.

Where the create stratum's counterpart of a merged directory does not
exist, the path is materialised on demand, from the mount root
downwards, at the point an operation first needs it ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)). The
authorisation for creating into it is evaluated against the descriptor
that directory will carry once materialised, which is the corresponding
provider directory's ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)).

<a id="trm-4-3-2-3"></a>

## Symbolic links and participation <a id="cite-resolution.merge-participant-set-resolves-like-lookup"></a>

Two resolution entry points disagree about the final component of a
stratum path, and the difference is visible.

Ordinary lookup resolves without following the final component, so a
symbolic link at a name resolves to the link itself and the VFS follows
it. Every site that builds the participant set resolves the same way —
the set itself, the emptiness scan, the foreign-entry scan, the
permission check and directory `fsync`.

A symlink is a non-directory, so a stratum holding a name as one is
masked entirely, exactly as [Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>) has it: it does not participate,
contributes no entries to the merged listing or to emptiness tests, and
masks whatever the strata below hold at that name. A dangling symlink
is the same, and for the same reason. <a id="cite-resolution.symlink-masks-like-any-non-directory"></a>

The two views agreeing is what closes a confused-deputy shape. Were the
participant set to follow the final component while lookup did not, a
stratum owner who replaced a directory with a symlink would change
which real directory contributed entries to another stratum's merged
view, and the permission check would run against a target the mounter
never named.

---

# Enumeration

_Peios Kernel / Internals / StrataFS / Name resolution_

> The union of names across participating strata, each appearing once — captured at open, with consistency and position rules.

<a id="trm-4-3-4"></a>

Enumerating a merged directory yields the union of the names held by
its participating strata, with each distinct name appearing exactly
once. <a id="cite-resolution.merged-directory-is-union"></a>

<a id="trm-4-3-4-1"></a>

## Capture at open

The whole listing is built when the directory is opened, and the
enumeration is served from that capture for the life of the descriptor.
Each participant is opened and iterated in ascending stratum order, and
its entries are appended to one list. <a id="cite-enumerate.captured-at-open"></a>

Deduplication is global rather than per-stratum: before an entry is
recorded, the whole accumulated list is scanned for the same name, and
a match causes the entry to be dropped. Because participants are
visited highest-precedence first, the entry that survives is always the
provider's. <a id="cite-enumerate.duplicate-name-resolves-to-provider"></a> `.` and `..` are dropped from every participant and
synthesised once. <a id="cite-enumerate.dot-entries-synthesised-once"></a>

Each surviving entry carries the name, its length, the directory entry
type reported by the providing participant, and an inode number
obtained by looking the child up in that same participant and deriving
its identity, with allocation only as a fallback ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), so `getdents` and
`stat` agree. <a id="cite-enumerate.entry-inode-matches-stat"></a> The final component is not followed during that lookup,
so a symlink entry reports its own identity rather than its target's. <a id="cite-enumerate.symlink-entry-reports-itself"></a>

Two details of that: an entry that vanishes between the participant's
own `readdir` and the follow-up lookup is silently dropped, which is
ordinary provider behaviour; and a participant filesystem that reports
`DT_UNKNOWN` has that propagated unchanged, even though the child path
is in hand and the real type could be derived. <a id="cite-enumerate.dt-unknown-propagated"></a>

Shadowed entries are neither reported nor otherwise detectable. No
second record is ever allocated, so nothing about them survives into
the listing, and the entry count reflects distinct names only. <a id="cite-enumerate.shadowed-entries-invisible"></a>

The order in which names are reported is stratum-ascending and then
each stratum's own `readdir` order — deterministic for one capture, and
not otherwise specified. <a id="cite-enumerate.order-stratum-then-readdir"></a>

The implementation uses a temporary, per-open name hash while capturing
entries, then an immutable position index for enumeration. Growing the
hash does not reorder entries or change which provider wins a duplicate.
The hash buckets are released before the open succeeds. Capture remains
eager under the opener's authority; the index does not defer any part of
that authorisation to a later reader or descriptor recipient.

Deduplication takes expected linear work in the number of names offered
by the participants. Resuming enumeration or seeking to an ordinal does
not scan earlier entries again. Provider enumeration, child lookup and
access checks still contribute their own costs. Each independent open
retains its own names and position index, so memory use still grows with
the number of distinct captured names and simultaneously open file
descriptions. These are implementation properties, not time or memory
limits promised to callers.

<a id="trm-4-3-4-2"></a>

## Consistency <a id="cite-enumerate.changes-after-open-invisible"></a>

There is exactly one capture per descriptor. Nothing appends to the
list after the directory is opened, and nothing re-captures — a
rewind replays the original capture, since the directory uses the
generic `llseek`. A change to any participating stratum after the open
is therefore invisible to that descriptor for its lifetime.

What that bounds is only what stratafs itself contributes. Each
participating directory is enumerated by its own filesystem, with
whatever consistency that filesystem offers its own callers, and
participants are read sequentially with no cross-stratum lock or
barrier. A merged listing is no better than the listings it is
assembled from, and nothing claims otherwise.

<a id="trm-4-3-4-3"></a>

## The settled participant set <a id="cite-enumerate.participant-set-settled-at-open"></a>

For the purpose of enumeration, the participating set is settled when
the directory is opened and does not change for the life of the
descriptor. What is settled is the set of participating **directory
objects**, not the set of stratum positions: the descriptor holds a
`struct path` reference on each participant, pinned until release, and
nothing re-resolves those positions by path. A participant that has
since been removed and replaced by another directory at the same path
is a different object and contributes nothing.

The settled set has exactly three consumers: the enumeration itself,
the access check performed when the directory is opened ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)), and
the origin attribute read through that descriptor ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)). It extends to
nothing else. Resolving a name relative to the descriptor — opening,
removing, renaming, linking — is an ordinary live resolution under
[Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>), performed against the strata as they are at that moment.

So a descriptor opened before a stratum began to hold the directory
will not list that stratum's names, but `openat` through the same
descriptor will resolve them. The two answers differ deliberately:
enumeration is a bulk disclosure whose authorisation was decided once,
when the descriptor was opened; a resolution is a fresh operation that
carries its own check.

Freezing the participant set is what keeps that open-time check
meaningful. Were a later re-read free to admit a stratum that joined
afterwards, its names would reach the caller without its directory's
descriptor ever having been consulted — and a stratum owner could make
a directory participate precisely to expose it. A caller that wants the
current participant set reopens.

<a id="trm-4-3-4-4"></a>

## Positions <a id="cite-enumerate.offsets-are-plain-ordinals"></a>

Offsets 0 and 1 are `.` and `..`. Offset `2 + k` is the k-th element of
the captured list — a plain ordinal. The offset each participant
filesystem supplies is discarded: no provider cookie, no stratum index,
and no name hash is encoded.

A position is therefore meaningful only within one open file
description. On close and reopen — and so across a remount or a reboot —
the capture is rebuilt from each stratum's current contents and current
`readdir` order, and ordinal `2 + k` may name a different entry or
none. `telldir` and `seekdir` across descriptors are unreliable on a
stratafs directory, as is NFS re-export of one.

<a id="trm-4-3-4-5"></a>

## Access <a id="cite-enumerate.requires-rights-on-every-participant"></a>

Enumeration requires traverse and list rights on **every** participating
directory, checked before the capture is built. The check returns on
the first refusal, and a refusal aborts the open entirely, so no
partial listing covering only the readable strata can be produced.

---

# Coherency

_Peios Kernel / Internals / StrataFS / Coherency_

> Find the Peios kernel articles about coherency.

Use these articles to understand coherency in the Peios kernel.

- [Model and revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md>)
- [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md>)

---

# Model and revalidation

_Peios Kernel / Internals / StrataFS / Coherency_

> Strata change underneath stratafs without telling it — what can change a resolution, and the guarantee that survives it.

<a id="trm-4-4-1"></a>

Every stratum of a mount may be modified at any time by an agent that
does not know stratafs exists. stratafs observes such changes without
being told of them.

<a id="trm-4-4-1-1"></a>

## No coordination <a id="cite-coherency.no-notification-protocol"></a>

There is no notification machinery anywhere in the filesystem — no
`fsnotify` registration, no `inotify`, nothing a stratum's filesystem
is expected to report. No writer announces a change, quiesces, or
participates in any protocol. Every resolution is performed from
scratch by re-walking the stratum path string, so nothing has to be
told anything.

<a id="trm-4-4-1-2"></a>

## What can change a resolution <a id="cite-coherency.resolution-depends-on-names-not-contents"></a>

A resolution depends only on which names each participating stratum
directory holds and what type each entry has. It does not depend on the
contents of any file.

A change to an object's **contents** therefore requires no action at
all. stratafs inodes carry no address-space operations; there is no
second page cache, and every data operation is forwarded to a backing
file opened on the provider. A change to that object is observed
through the mount immediately and by construction, because there is
nothing to invalidate.

A change to the **structure** of a participating stratum directory — an
entry created, removed, renamed, or replaced by one of another type —
may change which stratum provides a name. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers how that is
handled, which is by not caching anything.

<a id="trm-4-4-1-3"></a>

## The guarantee <a id="cite-coherency.structural-change-visible-to-next-resolution"></a>

A structural change in a stratum becomes visible to any resolution
begun after the stratum's own filesystem exposes that change to an
ordinary lookup. stratafs adds no delay of its own: there is no
timeout, no jiffies comparison, no generation counter, and no
resolution cache to serve a stale answer from.

It cannot anticipate a change the underlying filesystem is not yet
reporting. A network filesystem holding an attribute cache does not
show a change to stratafs any sooner than to any other caller, and
nothing claims otherwise.

Resolutions already completed are not revisited. Every regular-file
open is detached onto a descriptor-private dentry and inode holding
their own reference to the provider, and I/O runs against the file
opened at that time, so later masking or removal in any stratum cannot
reach that descriptor. It is not re-pointed and it does not fail. A
process holding a configuration file open across a package upgrade
continues to read the file it opened.

The one exception is copy-up, which [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>) covers: a descriptor whose
own write caused a copy-up keeps its inode while that inode's backing
object becomes the copy.

The open file description retains its sequential file position across
copy-up. `read` and `write` advance that position, and `lseek` with
`SEEK_CUR` uses it even after the backing file changes. Positioned I/O
through `pread` or `pwrite` leaves it unchanged.

<a id="trm-4-4-1-4"></a>

## Live strata <a id="cite-coherency.stratum-replaceable-while-mounted"></a>

Because resolutions are made against current state, and because a
stratum is a path rather than a directory object ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)), a stratum's
directory may be replaced wholesale — by a package transaction, by a
reconciler, by an administrator — while the mount is live, with no
remount and no interruption to callers. That is the requirement the
filesystem exists to satisfy, and [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) is the whole of its cost.

<a id="trm-4-4-2"></a>

The specification permits an implementation to cache resolutions,
subject to a version tuple recorded per stratum and an identity
comparison on reuse. This implementation caches nothing, and so
implements neither.

<a id="trm-4-4-2-1"></a>

## Always invalidate <a id="cite-coherency.revalidate.always-invalidates"></a>

`d_revalidate` returns 0 for every dentry except the mount root. The
VFS therefore discards the dentry and re-enters `lookup` on every path
walk, and the lookup re-resolves the parent and the child from their
relative path strings across every stratum.

Nothing is memoised. No version value is recorded, no directory
identity is retained for comparison, no nearest-existing-ancestor walk
happens, and no `i_version` is read anywhere in the filesystem. The
per-dentry provider path that is retained is not a cache of a
resolution: it is dropped when the dentry is released, and the dentry
is released on the next walk.

The specification's machinery exists to know when a cached resolution
has gone stale. With no cached resolution, the questions it answers do
not arise:

| What the tuple would detect | Why it is unnecessary here |
|---|---|
| A stratum gaining or losing a name | The next walk resolves the name afresh |
| A stratum's directory appearing | The next walk finds it |
| A stratum's directory removed, renamed away, or renamed over | The next walk finds nothing, or finds the replacement |

The result is strictly stronger than the specification requires, in the
safe direction. The internal filesystem-domain, fallback-inode and
staging-name counters do not validate cached resolutions.

<a id="trm-4-4-2-2"></a>

## What it costs <a id="cite-coherency.revalidate.rcu-walk-refused"></a>

The cost is real and lands on the hottest path in the kernel.

`d_revalidate` refuses RCU-walk unconditionally: a lookup in RCU mode
returns `ECHILD` and the walk is retried in ref-walk mode, and the
directory permission check does the same. RCU-walk is therefore never
used on a stratafs mount, and the fallback is taken always rather than
only where it genuinely cannot proceed.

The refusal, invisible to the caller by design, is visible at two
tracepoints. `stratafs:stratafs_rcu_walk_refused` marks the directory
permission check turning a walk back under `MAY_NOT_BLOCK` — in
practice the first stratafs directory a walk must traverse does this,
so it is the point that actually takes every walk out of RCU mode.
`stratafs:stratafs_d_revalidate` records each revalidation verdict —
mount cookie, merged inode number (zero for a negative entry), whether
the call was in RCU mode, and the return value — and because the
permission check fires first, every recorded call arrives already in
ref-walk mode; its `-ECHILD` branch is the backstop. Like every PKM
tracepoint, neither records a pathname.

What replaces it, per path component, is one full `filename_lookup` per
stratum — up to sixteen — plus one merged resolution per proper prefix
of the path, for the ancestor-masking test of [Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>). Where a mount is
established over a directory of executables, that lies on the path of
every program execution, and there is no dentry cache hit to avoid it.

This is the one part of the filesystem whose cost is worth measuring
rather than assuming, and closing the gap — recording enough per
resolution to reuse one safely, and making the comparison RCU-safe — is
tracked as work in its own right.

---

# Inode Identity and Lifecycle

_Peios Kernel / Internals / StrataFS / Coherency_

> stratafs allocates its own inodes standing for provider objects — the identity it reports, the mount root, and what a provider change does.

<a id="trm-4-4-3"></a>

stratafs presents its own inodes, allocated from its own superblock.
Each stands for a provider object and forwards operations to it; none
holds file data, directory entries, or a security descriptor.

<a id="trm-4-4-3-1"></a>

## Reported identity <a id="cite-inode.number-derived-from-provider"></a>

The device identifier reported for any object in a mount is the
stratafs superblock's own anonymous device, not the provider's.
`getattr` calls the provider's directly and then overrides `dev`, `ino`
and, for directories, `nlink`; all four inode-operations tables install
that same `getattr`.

The inode number is derived from the provider filesystem's reported
inode number and a small mount-local identifier for its reported device.
The device identifier distinguishes filesystem domains, not stratum
positions: a stratum can cross mount points. The reported device also
distinguishes Btrfs subvolumes, which can share a kernel superblock and
inode numbers. Two paths to the same provider identity, including hard
links and bind-mounted aliases, therefore report the same number.

Derivation reserves the high bit for allocated fallback numbers. A
self-delimiting tag in the low bits identifies the filesystem domain;
the provider inode number occupies the remaining bits. Small provider
numbers stay small enough to derive again through nested stratafs views.
Neither the bit layout nor the mount-local domain assignment is a
persistent identifier or an ABI that callers should decode. Numbers
may differ between mounts; within a mount, reloading the same provider
identity after cache eviction produces the same number.

Only identities that cannot fit, or providers that do not report a
usable inode number, use the fallback map. It allocates a distinct
number and holds a reference on the provider inode until unmount to
prevent address reuse. Repeated encounters with that provider reuse its
allocation. Synthetic provider-less roots use the same allocated number
space without a provider reference. Exhaustion returns `EOVERFLOW`
rather than wrapping, including on 32-bit builds. An attribute lookup
error is returned to the caller instead of silently assigning a new
identity.

<a id="trm-4-4-3-1-1"></a>

### The mount root <a id="cite-inode.root.follows-live-provider"></a>

The root inode is created once, when the superblock is filled, and the
root dentry is never replaced — `d_revalidate` returns 1 for it. Its
provider is nevertheless re-resolved live on every use, and the number
follows: resolving the root's provider derives or looks up its identity
and writes the result to the root inode's number.
Mode, owner, timestamps and number are therefore all current.

That the number follows is what keeps [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)'s identity rule true at
the root. Identity belongs to the provider, so the number the root
reports is the number every other merged path to that same provider
reports; without it, a root whose provider is also reachable elsewhere
would report a different number from that other path — two paths naming
one object, unequal. <a id="cite-inode.root.agrees-with-other-paths-to-its-provider"></a> That is the false-inequality direction, the one
that breaks hard-link detection.

Where no stratum root exists at mount time, the root receives a stable
synthetic number, distinct from derived provider numbers. If a provider
later appears, the root's number follows that provider.
<a id="cite-inode.root.synthetic-without-a-provider"></a>

<a id="trm-4-4-3-2"></a>

## Attributes of merged directories <a id="cite-inode.merged-dir.attributes-from-provider"></a>

A merged directory's owner, group, mode and timestamps are its
provider's — the highest-precedence participating directory — taken
straight from a `getattr` on the provider path, so what is reported is
a real directory's attributes rather than a composite.

The security descriptor of a merged directory is not a single
descriptor; [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) defines which participating directory's descriptor
governs each operation.

<a id="trm-4-4-3-2-1"></a>

### The synthetic link count <a id="cite-inode.merged-dir.nlink-forced-to-1"></a>

Its link count is forced to 1, both in the cached inode and in the
reported `stat`. The true count of subdirectories spans strata and
cannot be maintained, so the value carries no meaning beyond indicating
that the object is a directory. Nothing should infer a subdirectory
count from it.

<a id="trm-4-4-3-3"></a>

## Provider change <a id="cite-inode.never-rebound-by-resolution"></a>

When the provider for a path changes — because a higher-precedence
stratum gained the name, because the previous provider's entry was
removed, or because copy-up produced a new object — a **resolution** of
that path yields a new inode. An inode reached by resolution is never
re-associated with a different provider.

That is required because per-inode state is populated from the provider
the inode was resolved against and is not in general re-derivable. In
particular KACS caches a security descriptor against the outer stratafs
inode; applying it to a different provider's object would govern access
to one object by another object's descriptor.

The implementation enforces this bluntly. The one function that
re-associates an inode with a new provider is reachable from exactly
one call site, on the descriptor-private dentry created at open, and
never on a hashed dentry reached by resolution. A copy-up performed for
a path rather than a descriptor drops the dentry instead of rebinding
it. Provider change by masking or removal needs no special handling at
all, because the unconditional invalidation of [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) forces a fresh
lookup and a fresh inode.

An object's reported inode number therefore changes when its provider
changes. That is expected: it is the same change a caller would observe
if the file had been replaced, which is what has happened.

<a id="trm-4-4-3-3-1"></a>

### Descriptors already open <a id="cite-inode.copy-up.descriptor-keeps-inode"></a>

A descriptor open at the moment its own operation copies its object up
is not re-pointed. It keeps the inode it was opened against, and that
inode's backing object becomes the copy: the provider path and provider
inode are swapped in place under a per-inode lock, the attributes are
refreshed, and the backing file is replaced, so subsequent operations
through the descriptor reach the copy.

This is the one case in which an inode's backing object changes, and it
is safe for the reason the general rule exists: copy-up preserves the
source's security descriptor exactly ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so the descriptor cached
on that inode remains correct for the copy.

At open, the descriptor-private inode is deliberately given the path
inode's number, so before any copy-up `fstat` and `stat` agree. After
one they do not: the descriptor keeps the number assigned to the
pre-copy-up provider, while a fresh resolution of the path derives or
allocates a number for the copy. Both name the copy; the numbers disagree for as
long as that descriptor lives. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records it.

<a id="trm-4-4-3-4"></a>

## Lifetime <a id="cite-inode.provider-reclaim-with-live-mount"></a>

A stratafs inode holds a reference on its provider inode for as long as
it lives, released on eviction. The dentry additionally holds a full
path reference. Ordinary derived identities add no provider reference
and no per-inode entry to the identity map. Walking a persistent-backed
view and dropping caches can therefore reclaim the provider inodes while
the stratafs mount remains live. The per-mount device-domain table stays
until unmount; its size tracks encountered filesystem domains rather
than the number of files walked.

The fallback alone adds a provider reference held until unmount. That
cost applies only to identities that could not be derived.

Renaming a provider out of the view and back, or evicting and reloading
its cached inode, preserves its derived identity. <a id="cite-inode.stable-across-cache-reclaim"></a>
Ordinary inode-number reuse by the provider after deletion remains
possible, just as it is when accessing that filesystem directly.

Releasing the last reference to a stratafs inode modifies nothing:
eviction truncates its own empty mapping, clears the inode, drops the
provider reference, and frees its private state.
