Layers
Single-page view · as markdown
Layers
Peios Kernel / Internals / LCS / Layers
Use these articles to understand layers in the Peios kernel.
The Layer Model
Peios Kernel / Internals / LCS / Layers
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. |
| 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). 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).
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. Because nothing
consults it, that has no effect on anything.
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). That is what keeps the tier boundary
meaningful.
Caps #
MaxTotalLayers, default 1024, bounds the in-memory layer table, the
base layer included: a table holding that many entries admits no more.
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.
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.
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.
MaxLayersPerValue, default 128, bounds how many layers may write to
the same (key GUID, value name) pair. 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 write that replaces an existing entry in the same layer does not
increase the count and is not checked.
Exceeding the cap is ENOSPC.
The check is deliberately best-effort admission control, not a storage invariant. 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.
Blanket tombstones and value deletions are not subject to it.
Layers are global; entries are per-source #
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.
The Base Layer
Peios Kernel / Internals / LCS / Layers
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.
It is a static constant in the kernel: precedence 0, enabled. It is never stored in the dynamic layer table.
It is always emitted first in every layer snapshot, and is handed out even when the dynamic table is empty. 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;
- it cannot be disabled;
- its precedence cannot be changed;
- a layer table row for it cannot be published at all.
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.
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).
Its Precedence and Enabled values are ignored.
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. The base layer's
existence is hardcoded and layer mechanics cannot reach it.
The default target #
A write that names no layer targets the base layer. 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).
base is matched like every other layer name #
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, under
Machine\System\Registry\Layers\<LayerName>\. Each layer's key holds
three values:
| Value | Type | Default if missing |
|---|---|---|
Precedence | REG_DWORD | 0 |
Enabled | REG_DWORD, 0 or 1 | true |
Owner | REG_BINARY, a SID | the creating token's SID for a new layer |
Three things are malformed metadata, and are rejected rather than coerced:
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.
If none of those is available the layer cannot be published. 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.
Creation should be done inside a transaction so that all three values
are present when the refresh runs.
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. 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.
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.
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.
All three are written under one lock, and a snapshot reader that finds
them incomplete returns EIO rather than a half-populated layer.
A layer that has no metadata key GUID and no authorisation descriptor is not visible in the table at all. 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. On the normal path the key therefore has a descriptor before the layer can be published.
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.
For a transaction the refresh runs once, after the source commit
succeeds and before REG_IOC_COMMIT returns.
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.
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.
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.
If the refresh was required to complete the operation in hand —
creating a layer, say, or exposing one — the syscall fails with EIO.
Writing Into a Layer
Peios Kernel / Internals / LCS / Layers
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>\.
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.
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.
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). A layer that is not in the
table is ENOENT for any operation naming it.
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.
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.
Layer lifecycle #
Everything except the precedence rule is controlled purely by the descriptor on the metadata key.
The precedence gate #
SeTcbPrivilege is required specifically to establish or raise a
layer's precedence above 0. 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.
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 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), where Precedence is written inside
the transaction that creates the metadata key, before the layer has
been published at all.
Failing the privilege check is EPERM.
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.
REG_IOC_RESTORE has its own equivalent gate, applied to the backup
stream's layer manifest before anything is written (Restore).
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.
Before the broadcast, LCS aborts every bound transaction whose mutation log touched that layer (Deletion and Orphans).
A SUBKEY_DELETED for base is ignored (The Base Layer).
Private Layers
Peios Kernel / Internals / LCS / Layers
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.
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.
Resolution #
A private layer participates in normal precedence ordering. 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.
Name matching uses Unicode Simple Case Folding, like every other layer name comparison.
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).
LCS reads the credentials from the effective token on each operation and passes them into resolution.
Private layers are therefore per-thread, not per-process: threads in one process can hold different private layer sets through different impersonation tokens.
Two things about the caps #
MaxPrivateLayersPerToken, default 16, is described as a limit on
attachment. It is not enforced there.
KACS applies its own hard cap of 256 names when it parses the token specification. The configurable LCS limit is applied later, when LCS acquires a thread's private credentials for an operation.
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. 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. 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 missing token
is still EACCES, because that one is an access decision.
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.
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.
Attachment authority #
Private-layer names can enter a token only at creation, which requires
SeCreateTokenPrivilege.
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.
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
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.
The rule #
Every candidate is a tuple (precedence, sequence, entry). The winner
is the maximum, ordered by precedence first and sequence second.
Building the candidate list:
- 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.
- 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).
- For values, add every blanket tombstone on the key as a tombstone candidate for the requested name, at its own precedence and sequence (Tombstones).
- If there are no candidates, the answer is not-found.
- Take the maximum. A winning HIDDEN path entry, a winning
REG_TOMBSTONEvalue entry, and a winning blanket all mean not-found.
That is the whole algorithm. Everything the layer system does — override, revert, mask, hide, hide-and-replace — is a consequence of it.
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.
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.
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 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.
Enumeration #
Enumerating values collects the unique names across all layers and resolves each one, returning only those whose answer is not not-found.
Enumerating subkeys collects the unique child names and resolves each, returning those that map to a GUID rather than HIDDEN.
"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 caller sees effective state only. Tombstoned values, blanket-masked values and hidden keys are simply absent. Per-layer raw data is never visible through a normal operation.
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.
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.
Enumeration order is not defined, and the index-to-entry mapping can change between calls if the effective set changes. Indices must not be cached across mutations. The batch call is also the way to get a consistent snapshot.
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. 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.
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.
Duplicates that never get compared are not an error.
Both produce EIO and an lcs.source.response.rejected audit event
(Audit).
The Sequence Counter
Peios Kernel / Internals / LCS / Layers
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.
The counter is never decremented and never reset.
It provides deterministic tiebreaking within a precedence tier (Resolution). Wall-clock time is tracked separately, as each key's last write time, for humans.
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.
Gaps in the sequence space are normal and carry no meaning.
A transactional mutation is assigned its number when the operation is accepted into the transaction, not at commit. 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).
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. New writes therefore always outrank anything already in storage, even after a restart.
A source registering later advances the counter the same way, to
max(current, source_max + 1).
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.
The counter itself refuses to hand out U64_MAX, so the value is never
allocated.
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) so that a
watcher recovering from OVERFLOW can tell whether it actually missed
anything. Sources never see it and never persist it.
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.
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).