# Layers

---

# Layers

_Peios Kernel / Internals / LCS / Layers_

> Find the Peios kernel articles about layers.

Use these articles to understand layers in the Peios kernel.

- [The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md>)
- [The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md>)
- [Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md>)
- [Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md>)
- [Private Layers](</kernel/internals/lcs/layers/private-layers.md>)
- [Resolution](</kernel/internals/lcs/layers/resolution.md>)
- [The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md>)

---

# The Layer Model

_Peios Kernel / Internals / LCS / Layers_

> A named collection of registry writes managed as a unit — precedence tiers, caps, and why layers are global while entries are per-source.

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

A layer is a named collection of registry writes that can be managed as
a unit. Layers have precedence, and the highest-precedence entry wins.
They are how role installation, Group Policy and configuration revert
all work, and they are the reason removing a role does not leave its
settings behind.

| Field | Mutable | Description |
|---|---|---|
| Name | No | The layer's identity — not a GUID, not an integer. Case-preserving, compared with Unicode Simple Case Folding. Bounded by `MaxPathComponentLength`. <a id="cite-layer.model.name-is-the-identity"></a> |
| Precedence | Yes | Higher wins. Default 0. |
| Enabled | Yes | A disabled layer is invisible during resolution unless it is attached to the resolving thread's credentials ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). Default true. |
| Owner | — | The SID of the principal that created the layer. Informational only. |

The name being the identity is deliberate. Layer names are
code-generated and meaningful by construction —
`role-jellyfin`, `gpo-security-baseline` — so there is nothing an
opaque identifier would add.

`Owner` is never used for an access check; authorisation is the
descriptor on the layer's metadata key ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). <a id="cite-layer.model.owner-never-used-for-an-access-check"></a>

It is also not quite immutable as a field: a refresh re-reads the
`Owner` value and re-selects it, so rewriting the value does change what
is cached. <a id="cite-layer.model.owner-re-selected-by-refresh"></a> Because nothing
consults it, that has no effect on anything.

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

## Precedence tiers

The base layer and role layers all sit at precedence 0. Within one
tier, the most recent write wins — the highest sequence number. Group
Policy layers sit above 0 and override both.

Establishing or raising a layer's precedence above 0 requires
`SeTcbPrivilege` ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). That is what keeps the tier boundary
meaningful.

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

## Caps

`MaxTotalLayers`, default 1024, bounds the in-memory layer table, the
base layer included: a table holding that many entries admits no more. <a id="cite-layer.model.max-total-layers-default-1024"></a>

Creating a layer when it is full returns `ENOSPC`. The refusal happens
at the creation of the metadata key under `Layers\`, before anything
reaches the source, so a full table never leaves a metadata key behind
that the table cannot publish. <a id="cite-layer.model.layer-table-full-is-enospc"></a>

The table is sized to `MaxTotalLayers` rather than fixed at build. It
is allocated on the first publication and grows, under the table lock,
whenever a publication finds every slot taken while the configured
bound still admits one more; it never shrinks. <a id="cite-layer.model.table-grows-to-max-total-layers"></a>

So a value anywhere in the configurable range, 16 to 65536, binds.
Raising `MaxTotalLayers` above the default admits layers past 1024;
lowering it below the current occupancy admits no new layer until
enough have been deleted, and discards nothing. <a id="cite-layer.model.max-total-layers-binds-across-the-range"></a>

`MaxLayersPerValue`, default 128, bounds how many layers may write to
the same `(key GUID, value name)` pair. <a id="cite-layer.model.max-layers-per-value-default-128"></a> It is a guard against
amplification — every read of that value has to resolve every entry —
not an access control boundary.

It is enforced at `REG_IOC_SET_VALUE` time, before the source is
contacted, by querying the source for the current entry count. <a id="cite-layer.model.max-layers-per-value-checked-at-set-value"></a>

A write that replaces an existing entry in the *same* layer does not
increase the count and is not checked. <a id="cite-layer.model.max-layers-per-value-same-layer-replace-exempt"></a>
Exceeding the cap is `ENOSPC`. <a id="cite-layer.model.max-layers-per-value-exceeded-is-enospc"></a>

The check is deliberately **best-effort admission control**, not a
storage invariant. <a id="cite-layer.model.max-layers-per-value-is-best-effort"></a> It queries and then dispatches without holding
anything, so concurrent writers can both observe room and both proceed.
Sources are not required to enforce it atomically.

Once LCS observes a count at or above the cap, further new-layer writes
are refused. <a id="cite-layer.model.max-layers-per-value-refuses-once-observed-full"></a>

Blanket tombstones and value deletions are not subject to it. <a id="cite-layer.model.max-layers-per-value-exempts-blankets-and-deletions"></a>

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

## Layers are global; entries are per-source <a id="cite-layer.model.table-is-global-entries-are-per-source"></a>

There is one authoritative layer table, held by the kernel. Each source
stores layer *entries* — path entries and value writes tagged with
layer name strings — for its own hives. Layer *metadata* is global and
lives in one place.

A source never needs the layer table. It stores what it is told, tagged
with whatever name it is given, and returns everything on request. A
source that has never seen a particular layer name simply stores
entries carrying it. Resolution — precedence, enabled state, tombstone
evaluation — happens entirely in the kernel, and the layer snapshot is
passed into each operation rather than pushed to sources. There is no
RSI operation that hands a source the layer list. <a id="cite-layer.model.no-rsi-operation-sends-the-layer-list"></a>

---

# The Base Layer

_Peios Kernel / Internals / LCS / Layers_

> The kernel-reserved layer that exists unconditionally before any source registers — its persisted metadata and the two ways it is matched.

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

The base layer, named `base`, is a kernel-reserved implicit layer. It
exists unconditionally, before any source registers and whether or not
any metadata has ever been persisted for it. <a id="cite-layer.base.exists-unconditionally"></a>

It is a static constant in the kernel: precedence 0, enabled. <a id="cite-layer.base.is-precedence-zero-and-enabled"></a> It is
never stored in the dynamic layer table. <a id="cite-layer.base.not-in-the-dynamic-layer-table"></a>

It is always emitted first in every layer snapshot, and is handed out
even when the dynamic table is empty. <a id="cite-layer.base.emitted-first-in-every-snapshot"></a> A source that registers with a
completely empty database is therefore immediately usable, because the
one layer that writes need is not in the database.

Four things cannot happen to it:

- it cannot be deleted; <a id="cite-layer.base.cannot-be-deleted"></a>
- it cannot be disabled; <a id="cite-layer.base.cannot-be-disabled"></a>
- its precedence cannot be changed; <a id="cite-layer.base.precedence-cannot-be-changed"></a>
- a layer table row for it cannot be published at all. <a id="cite-layer.base.row-cannot-be-published"></a>

Each of those is enforced in more than one place. Deletion is refused by
the layer table, by the resolution core, by the `RSI_DELETE_LAYER`
dispatch path, and by the transaction layer-abort path. Publication of a
`base` row is rejected outright, and the refresh path short-circuits for
`base` **before** it would read `Precedence` or `Enabled`, so persisted
values for those are never even consulted.

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

## Persisted metadata

`Machine\System\Registry\Layers\base\` may exist, though nothing in a
Peios system creates it, and where it does it decorates the base layer
rather than defining it. What LCS takes
from it is the metadata key's GUID and its cached Security Descriptor —
which is to say, who may write into the base layer ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). <a id="cite-layer.base.metadata-key-supplies-guid-and-descriptor"></a>

Its `Precedence` and `Enabled` values are ignored. <a id="cite-layer.base.persisted-precedence-and-enabled-ignored"></a>

The internal self-watch also ignores a `SUBKEY_DELETED` for `base`: if a
higher-precedence HIDDEN entry masks the base layer's metadata key, that
is not a layer deletion and is not processed as one. <a id="cite-layer.base.subkey-deleted-is-ignored"></a> The base layer's
existence is hardcoded and layer mechanics cannot reach it.

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

## The default target

A write that names no layer targets the base layer. <a id="cite-layer.base.is-the-default-write-target"></a> That is the default
for manual administration, for system initialisation, and for what a
person keeps under their own `Users\<SID>\`.

While the base layer's metadata key does not exist, LCS uses a
compiled-in default descriptor granting SYSTEM and Administrators
`KEY_ALL_ACCESS` and Authenticated Users `KEY_SET_VALUE`, so writes into
the base layer are possible from the very beginning, by anyone who has
authenticated, to whatever the target key's own descriptor lets them
write. The compiled-in default is replaced by the key's descriptor as
soon as the key is created ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

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

## `base` is matched like every other layer name <a id="cite-layer.base.name-matched-by-case-folding"></a>

The reserved name is recognised with Unicode Simple Case Folding, the
same algorithm and the same table used for every other layer-name
comparison.

There was a second, ASCII case-insensitive comparator beside it, used on
two call sites. For the literal string `base` the two agreed — a length
pre-check made a non-ASCII case pair fail before folding could matter —
so the divergence was latent rather than absent, and would have become
live the moment anything about the reserved name changed. It is gone;
both call sites now take the folding comparator and propagate its error
rather than collapsing it into a `bool`.

---

# Layer Metadata

_Peios Kernel / Internals / LCS / Layers_

> Layer metadata lives in the registry it configures — the circularity that creates, why publication is atomic, and when the refresh runs.

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

Layer metadata lives in the registry, under
`Machine\System\Registry\Layers\<LayerName>\`. <a id="cite-layer.metadata.lives-under-the-layers-key"></a> Each layer's key holds
three values:

| Value | Type | Default if missing |
|---|---|---|
| `Precedence` | `REG_DWORD` | 0 <a id="cite-layer.metadata.precedence-is-dword-default-0"></a> |
| `Enabled` | `REG_DWORD`, 0 or 1 | true <a id="cite-layer.metadata.enabled-is-dword-default-true"></a> |
| `Owner` | `REG_BINARY`, a SID | the creating token's SID for a new layer <a id="cite-layer.metadata.owner-is-binary-sid"></a> |

Three things are malformed metadata, and are rejected rather than
coerced:

- a value of the wrong type; <a id="cite-layer.metadata.wrong-type-is-malformed"></a>
- a `REG_DWORD` that is not exactly four bytes; <a id="cite-layer.metadata.dword-must-be-exactly-four-bytes"></a>
- an `Enabled` greater than 1. <a id="cite-layer.metadata.enabled-above-one-is-malformed"></a>

`Owner` selection has a fallback chain: the metadata value; failing
that, the creator's SID for a newly created layer; failing that, the
previous known-good owner; failing that, the owner SID from the
metadata key's own descriptor. <a id="cite-layer.metadata.owner-fallback-chain"></a>

If none of those is available the layer cannot be published. <a id="cite-layer.metadata.unresolvable-owner-blocks-publication"></a> Every one
of these is informational and none grants access.

There is no "create layer" or "delete layer" syscall. Creating a key
under `Layers\` creates a layer; deleting that key deletes it. <a id="cite-layer.metadata.key-creation-and-deletion-are-the-lifecycle"></a>
Creation should be done inside a transaction so that all three values
are present when the refresh runs.

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

## Circularity

Layer metadata is stored in the registry, which is itself layered.
That is circular, and it is safe, because resolution never re-enters
itself.

LCS always resolves using its **currently published** layer table —
including when resolving layer metadata values. <a id="cite-layer.metadata.resolved-with-the-published-table"></a> When a write to the
metadata subtree commits, the refresh reads the affected metadata using
the current table and then publishes an updated one.

The table is never re-resolved mid-operation; each operation takes one
snapshot and uses it throughout. <a id="cite-layer.metadata.one-snapshot-per-operation"></a>

So a high-precedence layer can override another layer's precedence, and
that is useful and intended. It simply takes effect at the next
publication rather than recursively. <a id="cite-layer.metadata.override-takes-effect-at-next-publication"></a>

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

## Publication is atomic

A layer is not merely a name and a precedence. The published unit is
three things together: the layer table entry, the metadata key's GUID,
and the cached Security Descriptor of that key. <a id="cite-layer.metadata.published-unit-is-three-things"></a>

All three are written under one lock, and a snapshot reader that finds
them incomplete returns `EIO` rather than a half-populated layer. <a id="cite-layer.metadata.incomplete-publication-is-eio"></a>

A layer that has no metadata key GUID and no authorisation descriptor
is not visible in the table at all. <a id="cite-layer.metadata.layer-without-guid-or-descriptor-is-invisible"></a> There is no window in which a layer
exists but nobody can be authorised against it.

Creating the metadata key is ordinary key creation, so LCS computes its
descriptor from parent inheritance through KACS before the source
persists it. <a id="cite-layer.metadata.descriptor-computed-by-inheritance-before-persist"></a> On the normal path the key therefore has a descriptor
before the layer can be published.

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

## When the refresh runs

Changes under `Layers\` mark the affected layer names dirty. After the
mutating operation commits, and **before the syscall returns to
userspace**, LCS runs a bounded refresh for those names: it reads the
committed metadata key, its values and its descriptor, and publishes
the new entry atomically. <a id="cite-layer.metadata.refresh-runs-before-the-syscall-returns"></a>

For a transaction the refresh runs once, after the source commit
succeeds and before `REG_IOC_COMMIT` returns. <a id="cite-layer.metadata.transaction-refresh-runs-once-before-commit-returns"></a>

The internal self-watch is what notices the subtree changed, but the
watch callback is not the atomicity boundary and must never publish a
partial entry. LCS does not perform source round trips while holding
the watch-map or layer-table publication locks. <a id="cite-layer.metadata.no-source-round-trips-under-publication-locks"></a>

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

## When the metadata descriptor will not parse

If the metadata key's descriptor cannot be read or parsed during a
refresh, the source has returned malformed data. LCS emits an audit
event, does not publish or update that layer's entry, and keeps the
previous known-good one. <a id="cite-layer.metadata.unparseable-descriptor-keeps-previous-entry"></a>

The same isolation holds at bootstrap. The refresh that runs on source
registration visits every layer under `Layers\` in turn, and one whose
metadata will not parse — the descriptor, or any of the three values —
is skipped, unpublished and counted, while its siblings publish as they
would have without it. Only a failure of the source itself, rather than
of one layer's data, fails the refresh. <a id="cite-layer.metadata.bootstrap-isolates-a-malformed-layer"></a>

If the refresh was required to complete the operation in hand —
creating a layer, say, or exposing one — the syscall fails with `EIO`. <a id="cite-layer.metadata.required-refresh-failure-is-eio"></a>

---

# Writing Into a Layer

_Peios Kernel / Internals / LCS / Layers_

> Every mutation targeting a layer requires layer write access — the base layer before it exists, the precedence gate, and deleting a layer.

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

Every mutating operation that targets a layer — value writes, value
deletions, tombstones, key hides, blanket tombstones, key creation —
requires **layer write authorization**: `KEY_SET_VALUE` on the layer's
metadata key at `Machine\System\Registry\Layers\<LayerName>\`. <a id="cite-layer.authz.write-requires-key-set-value-on-metadata-key"></a>

This is a second AccessCheck, against a different object, and it is in
addition to the fd's granted mask on the target key. Both must pass. <a id="cite-layer.authz.is-a-second-check-additional-to-the-fd-mask"></a>

The descriptor on a layer's metadata key is therefore the answer to
"who may write into this layer". The base layer's, where the key has
been created, is the one inheritance computes from the `Machine` hive
root, like any other key's. <a id="cite-layer.authz.base-descriptor-inherits-from-the-machine-root"></a>
Group Policy layers get restrictive descriptors from the GP client at
creation; role layers get theirs from the role installer.

That closes two escalation paths at once. An unprivileged process
cannot write into a GP layer, and one role's service cannot write into
another role's.

The base layer is the one layer meant to be written by everybody. It
is where a write goes that names no layer, a person's own settings
under `Users\<SID>\` included, so its descriptor lets in anyone who has
authenticated and leaves what they may write to the descriptor of the
key they are writing. A layer check that refused them would make every
key read-only to everyone but SYSTEM and Administrators, whatever the
key's own descriptor said.

The layer metadata descriptors are cached alongside the layer table and
invalidated by the same self-watch ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)). A layer that is not in the
table is `ENOENT` for any operation naming it. <a id="cite-layer.authz.unknown-layer-is-enoent"></a>

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

## The base layer before it exists

While `Layers\base\` does not exist, LCS falls back to a compiled-in
default descriptor, so base-layer writes work from the start. It is
owned by SYSTEM and grants `KEY_ALL_ACCESS` to SYSTEM and
Administrators and `KEY_SET_VALUE`, the one right this check asks for,
to Authenticated Users. Nobody else is granted anything: a principal
that has not authenticated cannot write into the base layer, whatever
the target key allows. <a id="cite-layer.authz.base-falls-back-to-a-compiled-in-descriptor"></a>

Nothing in a Peios system creates `Layers\base\`, so on a system as
shipped the compiled-in default is the descriptor in force for as long
as the system runs.

It is replaced by the persisted descriptor the moment the key is
created. <a id="cite-layer.authz.base-fallback-replaced-at-seed-restore"></a>

> [!WARNING]
> Creating `Layers\base\` changes who may write the registry. The new
> key inherits from the `Machine` hive root, which grants Authenticated
> Users `KEY_READ` and not `KEY_SET_VALUE`, so from that moment no
> ordinary principal can write anything, its own `Users\<SID>\`
> included. Whoever creates the key has to give it a descriptor that
> says what they mean, in the transaction that creates it.

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

## Layer lifecycle

| Operation | Requirement |
|---|---|
| Create a layer at precedence 0 | `KEY_CREATE_SUB_KEY` on `Layers\` <a id="cite-layer.authz.create-requires-create-sub-key"></a> |
| Create a layer above precedence 0 | `KEY_CREATE_SUB_KEY` on `Layers\` **and** `SeTcbPrivilege` |
| Write into a layer | `KEY_SET_VALUE` on the layer's metadata key |
| Modify layer metadata | `KEY_SET_VALUE` on the metadata key; raising precedence above 0 additionally requires `SeTcbPrivilege` <a id="cite-layer.authz.modify-metadata-requires-key-set-value"></a> |
| Delete a layer | `DELETE` on the metadata key's fd <a id="cite-layer.authz.delete-requires-delete-on-the-metadata-fd"></a> |

Everything except the precedence rule is controlled purely by the
descriptor on the metadata key. <a id="cite-layer.authz.only-precedence-needs-a-privilege"></a>

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

## The precedence gate

`SeTcbPrivilege` is required specifically to establish or raise a
layer's precedence above 0. <a id="cite-layer.authz.precedence-above-zero-requires-setcbprivilege"></a> It is defence in depth: compromising the
descriptor on `Layers\` is not enough to create a Group Policy-tier
layer.

The check is synchronous and inline at `REG_IOC_SET_VALUE` time, and it
happens early — before sequence allocation, before transaction
enlistment, before the source is contacted. <a id="cite-layer.authz.precedence-gate-runs-before-sequence-and-dispatch"></a>

It runs when three things hold: the target key is a layer metadata key,
the value name folds equal to `Precedence` under the same Unicode
folding used for every other value name, and the data is a positive
`REG_DWORD`. <a id="cite-layer.authz.precedence-gate-trigger-conditions"></a> A key
is a layer metadata key by its path — a direct child of
`Machine\System\Registry\Layers` — or by already being in the set of
published layer metadata keys. The path test is what covers the
recommended creation flow ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)), where `Precedence` is written inside
the transaction that creates the metadata key, before the layer has
been published at all. <a id="cite-layer.authz.precedence-gate-keys-on-the-path"></a>

Failing the privilege check is `EPERM`. <a id="cite-layer.authz.precedence-gate-denial-is-eperm"></a>

The gate tests for a four-byte `REG_DWORD` specifically. A `Precedence`
written with some other type slips past it — and then fails at the
refresh, which rejects a non-`REG_DWORD` `Precedence` as malformed
metadata. The precedence never actually rises. <a id="cite-layer.authz.non-dword-precedence-slips-the-gate-and-fails-at-refresh"></a>

`REG_IOC_RESTORE` has its own equivalent gate, applied to the backup
stream's layer manifest before anything is written ([Restore](</kernel/internals/lcs/backup-and-restore/restore.md#trm-5-9-3>)).

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

## Deleting a layer

Deleting the metadata key fires a `SUBKEY_DELETED` on the internal
self-watch. LCS removes the layer from the table and broadcasts
`RSI_DELETE_LAYER` to every registered source, each of which purges
every entry tagged with that name and reports the GUIDs that lost their
last path entry. <a id="cite-layer.authz.deleting-the-metadata-key-removes-the-layer-from-the-table"></a>

Before the broadcast, LCS aborts every bound transaction whose mutation
log touched that layer ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)).

A `SUBKEY_DELETED` for `base` is ignored ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)).

---

# Private Layers

_Peios Kernel / Internals / LCS / Layers_

> A disabled layer attached to a thread's credentials — how it resolves, how it is attached, and the authority retained from its creator.

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

A private layer is a **disabled** layer attached to a thread's
credentials. It is invisible during ordinary resolution and treated as
enabled when resolving on behalf of a thread whose token names it. <a id="cite-layer.private.disabled-layer-active-for-a-naming-thread"></a>

That covers three things a shared registry otherwise cannot do: giving
one session experimental settings without affecting others; injecting
test configuration without touching the shared tree; and giving a
container a different view of the registry without a separate hive.

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

## Resolution

A private layer participates in normal precedence ordering. <a id="cite-layer.private.participates-in-normal-precedence"></a> A disabled
layer with precedence 5 attached to a thread resolves at precedence 5,
competing with everything else at that level. It is not an overlay on
top; it is a layer that only that thread can see.

After private-attachment authorization succeeds, a layer is active for a
thread if it is globally enabled, or its name appears in that thread's
private layer set. <a id="cite-layer.private.activity-test"></a>

Name matching uses Unicode Simple Case Folding, like every other layer
name comparison. <a id="cite-layer.private.names-matched-by-case-folding"></a>

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

## Attachment

Private layer names reach a thread through the KACS token's LCS
credential extension — the same versioned block that carries scope
GUIDs for private hives ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-layer.private.names-come-from-the-token-credential-extension"></a>

LCS reads the credentials from the effective token on each operation
and passes them into resolution. <a id="cite-layer.private.credentials-read-from-the-effective-token-per-operation"></a>

Private layers are therefore **per-thread, not per-process**: threads
in one process can hold different private layer sets through different
impersonation tokens. <a id="cite-layer.private.are-per-thread-not-per-process"></a>

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

## Two things about the caps

`MaxPrivateLayersPerToken`, default 16, is described as a limit on
attachment. <a id="cite-layer.private.max-private-layers-per-token-default-16"></a> It is not enforced there. <a id="cite-layer.private.cap-not-enforced-at-attachment"></a>

KACS applies its own hard cap of 256 names when it parses the token
specification. <a id="cite-layer.private.kacs-hard-cap-of-256-at-parse"></a> The configurable LCS limit is applied later, when
LCS acquires a thread's private credentials for an operation. <a id="cite-layer.private.lcs-cap-applied-at-credential-acquisition"></a>

The consequence is that a token carrying seventeen private layers is
accepted by KACS and then fails every LCS operation, rather than being
refused when it was built. <a id="cite-layer.private.over-cap-token-accepted-then-fails-every-operation"></a> Reading LCS's configured limits from KACS
would invert the dependency between the two, so the cap stays where it
can be read.

The failure is `E2BIG`. <a id="cite-layer.private.over-cap-is-e2big"></a> It was `EACCES`, which read as an access-control
denial and sent anyone debugging it towards descriptors and privileges
rather than towards a count that was fixed when the token was assembled,
possibly in another process.

`MaxScopeGUIDsPerToken` shares the check and the errno. <a id="cite-layer.private.max-scope-guids-shares-the-check-and-errno"></a> A missing token
is still `EACCES`, because that one is an access decision. <a id="cite-layer.private.missing-token-is-eacces"></a>

KACS deduplicates the private layer names it parses with the same
Unicode Simple Case Folding LCS matches them by, so a name that LCS
treats as one layer is one layer here too. <a id="cite-layer.private.kacs-dedupes-names-by-case-folding"></a>

It did not always: an ASCII case-insensitive comparison let two names
differing only in a non-ASCII case relation — `ROLEs` and `roles`, since
U+017F folds to `s` — both sit on one token, spending two of the token's
`MaxPrivateLayersPerToken` slots on a single layer. Resolution still
folded correctly on the LCS side, so the layer activated once, but the
two sides of one identity contract disagreed.

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

## Attachment authority

Private-layer names can enter a token only at creation, which requires
`SeCreateTokenPrivilege`. <a id="cite-layer.private.attachment-gated-by-secreatetokenprivilege"></a>
Attaching a known layer above precedence 0 additionally requires enabled
`SeTcbPrivilege` on the **creator**. Without it, creation fails with `EPERM`,
even when the requested child token itself includes TCB privilege. A present
but disabled privilege does not authorize attachment.

The kernel retains the creator's authorization as immutable token state.
A trusted creator can delegate a private high-precedence view to an ordinary
token without giving the consumer TCB privilege. Duplication, restriction,
process propagation and impersonation preserve that attachment authority;
they do not obtain new authority from the duplicating caller.
<a id="cite-layer.private.tcb-authorized-attachment-can-be-delegated"></a>

Layer names need not exist when attached, and precedence can change later.
For each operation acquiring private credentials, LCS checks the retained
authority against the **same layer snapshot** used for resolution. If an
attachment made without TCB authorization now names a layer above precedence
0, the operation fails with `EPERM`. It does not silently choose a lower
layer. This applies to queries through already-open key handles as well as
new opens; a later promotion or creation cannot upgrade the attachment.
Returning the layer to precedence 0 makes the original attachment usable
again. Ordinary key and layer access checks still apply.

KACS invokes an LCS-supplied validator before exposing a newly created token.
The callback is installed during kernel initialization and then read-only;
a private extension cannot be published without its validator. LCS owns the
layer lookup, so KACS does not interpret the layer table. Use-time validation
closes the race between the creation check and a concurrent metadata change.
Successful TCB authorization marks the privilege used on the creator.

This is the PEI-268 behavior; older kernels lack the attachment check.

---

# Resolution

_Peios Kernel / Internals / LCS / Layers_

> Turning several per-layer entries into one effective answer — the rule, why unknown layers are latent rather than wrong, and enumeration.

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

Layer resolution turns several per-layer entries into one effective
answer. It is the mechanism that makes the registry layered, and it is
the same algorithm for path entries and for values — one resolves
existence claims, the other resolves data. <a id="cite-layer.resolution.same-algorithm-for-path-entries-and-values"></a>

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

## The rule

Every candidate is a tuple `(precedence, sequence, entry)`. The winner
is the maximum, ordered by precedence first and sequence second. <a id="cite-layer.resolution.winner-is-highest-precedence-then-highest-sequence"></a>

Building the candidate list:

1. For each entry the source returned, look up its layer in the current
   layer table. An entry naming a layer that is not in the table is
   **skipped**, not rejected. <a id="cite-layer.resolution.entry-for-an-unknown-layer-is-skipped"></a>
2. Discard entries from layers that are not active for this thread — a
   layer is active if it is globally enabled or its name is in the
   thread's private layer set ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-layer.resolution.inactive-layers-are-discarded"></a>
3. For values, add every blanket tombstone on the key as a tombstone
   candidate for the requested name, at its own precedence and
   sequence ([Tombstones](</kernel/internals/lcs/data-model/tombstones.md#trm-5-2-7>)). <a id="cite-layer.resolution.blanket-tombstones-join-the-candidate-list"></a>
4. If there are no candidates, the answer is not-found. <a id="cite-layer.resolution.no-candidates-is-not-found"></a>
5. Take the maximum. A winning HIDDEN path entry, a winning
   `REG_TOMBSTONE` value entry, and a winning blanket all mean
   not-found. <a id="cite-layer.resolution.winning-hidden-tombstone-or-blanket-is-not-found"></a>

That is the whole algorithm. Everything the layer system does —
override, revert, mask, hide, hide-and-replace — is a consequence of
it.

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

## Unknown layers are latent, not wrong

An entry tagged with a well-formed layer name that is not currently in
the table is a valid **latent** entry. <a id="cite-layer.resolution.latent-entry-is-valid"></a>

It is ignored while the layer is absent, and if a layer with the same
folded identity is later created, that entry becomes eligible for
resolution under the new metadata. <a id="cite-layer.resolution.latent-entry-becomes-eligible-when-the-layer-appears"></a>

This is what makes restore, import and boot ordering work: source
storage can legitimately hold entries before their metadata has been
loaded. It also follows the core rule — sources persist entries, LCS
decides their meaning.

Normal operations do not create such entries. <a id="cite-layer.resolution.normal-operations-do-not-create-latent-entries"></a> A layer-targeting ioctl
naming a layer that is not in the table returns `ENOENT`. Latent
entries come from existing storage, from a restore or import, from a
previous boot, or from source behaviour. Since sources are trusted,
a well-formed latent entry is not malformed merely because its layer is
absent right now.

An entry whose layer *name* is malformed is a different matter, and is
rejected as malformed source data. <a id="cite-layer.resolution.malformed-layer-name-is-rejected"></a>

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

## Enumeration

Enumerating values collects the unique names across all layers and
resolves each one, returning only those whose answer is not not-found. <a id="cite-layer.resolution.enum-values-returns-only-resolved-names"></a>

Enumerating subkeys collects the unique child names and resolves each,
returning those that map to a GUID rather than HIDDEN. <a id="cite-layer.resolution.enum-subkeys-skips-hidden-children"></a>

"Unique" means folded-unique. Two entries whose names differ only in
case are one name, which is the only reading consistent with names
being case-insensitive. <a id="cite-layer.resolution.enumeration-uniqueness-is-folded"></a>

A caller sees effective state only. <a id="cite-layer.resolution.callers-see-effective-state-only"></a> Tombstoned values, blanket-masked
values and hidden keys are simply absent. Per-layer raw data is never
visible through a normal operation.

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

## Enumeration is index-based, and that has a cost

`REG_IOC_ENUM_VALUES` and `REG_IOC_ENUM_SUBKEYS` return one entry at an
index. Each call re-resolves the full set and returns the entry at that
position, so walking `0..N-1` performs N full resolutions — O(n²) work
overall. <a id="cite-layer.resolution.enumeration-re-resolves-at-every-index"></a>

For a key with a handful of values that does not matter.
`REG_IOC_QUERY_VALUES_BATCH` exists for when it does: one call, the
whole effective value set, one resolution. <a id="cite-layer.resolution.batch-query-resolves-the-whole-set-once"></a>

Enumeration order is not defined, and the index-to-entry mapping can
change between calls if the effective set changes. <a id="cite-layer.resolution.enumeration-order-is-undefined"></a> Indices must not be
cached across mutations. The batch call is also the way to get a
consistent snapshot.

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

## Neither party can lie about ordering

Two rules stop a source manipulating the outcome.

A source-returned entry whose sequence number is greater than or equal
to the next sequence LCS would allocate is **malformed data**. <a id="cite-layer.resolution.future-sequence-number-is-malformed"></a> Sources
store the numbers LCS assigns them; they cannot legitimately hold a
future one. Without this, a compromised source could fabricate a
sequence number and win every tie in its own hive.

Every entry in a response is validated this way, whatever layer it
names. <a id="cite-layer.resolution.every-entry-in-a-response-is-sequence-checked"></a>

Duplicate sequence numbers at the same precedence, where they would
actually have to be compared to pick a winner, are also malformed. LCS
rejects the response rather than making an arbitrary choice. <a id="cite-layer.resolution.compared-duplicate-sequences-are-malformed"></a>

Duplicates that never get compared are not an error. <a id="cite-layer.resolution.uncompared-duplicate-sequences-are-not-an-error"></a>

Both produce `EIO` and an `lcs.source.response.rejected` audit event
([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-layer.resolution.sequence-validation-failure-is-eio"></a>

---

# The Sequence Counter

_Peios Kernel / Internals / LCS / Layers_

> The single global monotonic counter stamped on every layer-qualified entry — allocation, initialisation, and what it is not.

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

LCS keeps one global monotonic counter. Every mutation that creates a
layer-qualified entry — a path entry, a value write, a key hide, a
blanket tombstone — takes the next number from it. <a id="cite-layer.sequence.every-layer-qualified-mutation-takes-the-next-number"></a>

The counter is never decremented and never reset. <a id="cite-layer.sequence.never-decremented-or-reset"></a>

It provides deterministic tiebreaking within a precedence tier
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). Wall-clock time is tracked separately, as each key's last
write time, for humans.

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

## Allocation

Allocating a number increments the counter. **Allocated numbers are
never reused**, even if the operation later fails, times out, or is
part of a transaction that aborts. <a id="cite-layer.sequence.allocated-numbers-are-never-reused"></a>

Gaps in the sequence space are normal and carry no meaning. <a id="cite-layer.sequence.gaps-are-normal"></a>

A transactional mutation is assigned its number when the operation is
**accepted into the transaction**, not at commit. <a id="cite-layer.sequence.transactional-number-assigned-at-accept-not-commit"></a> That preserves the
order in which the caller performed the operations, which is what layer
tiebreaking and watch ordering need if it commits ([Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md#trm-5-7-2>)).

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

## Initialisation

Each source reports the highest sequence number it has persisted in its
registration handshake, and LCS raises the counter to one above the
maximum reported. <a id="cite-layer.sequence.counter-raised-above-the-reported-source-maximum"></a> New writes therefore always outrank anything
already in storage, even after a restart. <a id="cite-layer.sequence.new-writes-outrank-stored-entries"></a>

A source registering later advances the counter the same way, to
`max(current, source_max + 1)`. <a id="cite-layer.sequence.late-registration-advances-the-counter"></a>

If that addition would overflow 64 bits the registration fails with
`EOVERFLOW` and the source is not made Active — the failure happens
before the slot becomes usable. <a id="cite-layer.sequence.registration-overflow-is-eoverflow"></a>

The counter itself refuses to hand out `U64_MAX`, so the value is never
allocated. <a id="cite-layer.sequence.u64-max-is-never-allocated"></a>

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

## What a sequence number is not

A sequence number is not a hive generation number.

A **sequence number** orders layer-qualified entries for resolution and
is persisted by sources.

A **hive generation number** is a volatile, per-hive, kernel-owned
change epoch, exposed by `REG_IOC_QUERY_KEY_INFO` ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) so that a
watcher recovering from `OVERFLOW` can tell whether it actually missed
anything. Sources never see it and never persist it. <a id="cite-layer.sequence.generation-number-never-reaches-sources"></a>

Its baseline is initialised from the source's reported maximum sequence
at registration, purely so that observed generations are monotonic
relative to persisted entries; after that the two are unrelated. <a id="cite-layer.sequence.generation-baseline-from-the-reported-source-maximum"></a>

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

## Restore

A restore does not write the backup's sequence numbers. It reserves a
fresh range and remaps into it, so restored entries are newer than
everything that was there before while keeping their relative order
from the backup ([Restore](</kernel/internals/lcs/backup-and-restore/restore.md#trm-5-9-3>)).
