# LCS

> Peios kernel lcs documentation.

---

# Overview

_Peios Kernel / Internals / LCS / Start here_

> LCS is the kernel half of the Peios registry — where it sits, its semantic core, what is layered and what is not, and where the model diverges.

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

LCS — the Layered Configuration Subsystem — is the kernel half of the
Peios registry: a hierarchical, access-controlled configuration store
modelled on the Windows registry. It owns the namespace, the security
model, change observation, transactions, and the layer system that
gives the registry its name. It owns no storage at all.

Storage belongs to **sources**: userspace processes that hold registry
data and answer questions about it over the Registry Source Interface.
A source stores what it is told and returns everything it holds; it
never resolves layers, never filters by visibility, never sees the
identity of a caller, and never interprets a path beyond the parent and
child names it is given. Every decision about what a caller may see or
do is made in the kernel. loregd is the first source, and the one that
provides `Machine\` and `Users\` at boot, but nothing in LCS knows that:
hive routing is built entirely from what registers.

Userspace never talks to a source. Processes reach the registry through
three syscalls and eighteen ioctls, and the fd those syscalls return is
a capability — an open key carries the access mask it was granted, and
carries it wherever the fd goes.

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

## Where it sits

LCS is a subsystem of PKM, peer to KACS and KMES, implemented in
`security/pkm/lcs` and built by `CONFIG_SECURITY_PKM` — a
boolean option, so it is linked into `vmlinux` rather than loaded. Its
three syscalls occupy 1100–1102 in the PKM range, registered in
`arch/x86/entry/syscalls/syscall_64.tbl`.

It depends on KACS and KACS does not depend on it. Every access
decision LCS makes is a call into the KACS AccessCheck function against
a Security Descriptor the source returned; LCS defines no access
control mechanism of its own. Security Descriptor inheritance at key
creation is likewise KACS's computation, not LCS's. Audit events go to
KMES.

A substantial part of LCS is Rust. The `lcs-core` implementation lives
in `security/pkm/lcs/lcs_core` and holds
the parts where correctness is a matter of pure decision rather than
kernel plumbing: layer resolution, the RSI wire codec, the backup
stream serialiser, the transaction mutation log, watch dispatch, case
folding, and configuration validation. The C half owns fds, the char
device, memory, locking, and the syscall boundary.

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

## The semantic core

Six rules generate the rest of the model. Every behaviour described in
this chapter is a consequence of one of them.

1. **Names are layered.** A key's presence at a path is per-layer.
   Different layers can name different keys at the same path, and
   removing a layer removes its names.
2. **Values are layered.** Every write is tagged with a layer; the
   effective value is the highest-precedence entry. Tombstones can
   actively mask lower layers.
3. **Key identity is not layered.** A key's GUID, Security Descriptor,
   volatile flag, symlink flag and last write time belong to the key
   object, not to any layer, and are never automatically reverted.
4. **Security is key-bound, not layer-bound.** Modifying a Security
   Descriptor is a permanent change to the key. Removing a layer does
   not revert it. Security policy is operational state, not
   configuration overlay.
5. **Handles are capabilities granted at open.** An open key fd carries
   an access mask computed once, by AccessCheck, at open time. Later
   operations test the mask, not the descriptor. Changing a descriptor
   does not affect an fd that already exists.
6. **Sources persist, the kernel decides meaning.** A source stores
   path entries, key records and value entries and returns all of them.
   Everything else is the kernel's.

The consequence that surprises people most often is the fourth. A
layer is a configuration overlay and reverts cleanly; an access control
change is not configuration and does not.

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

## What is layered and what is not

| Property | Layered | Resolved by | Survives layer deletion |
|---|---|---|---|
| Path existence | Yes | Highest precedence, then highest sequence | No |
| Values | Yes | Highest precedence, then highest sequence | No |
| Value tombstones | Yes | Masking lower precedence | No |
| Blanket tombstones | Yes | Masking all lower-precedence values on the key | No |
| Key hiding | Yes | Masking lower precedence | No |
| Key GUID | No | Direct on the key object | Yes |
| Security Descriptor | No | Direct on the key object | Yes |
| Volatile flag | No | Direct on the key object | Yes |
| Symlink flag | No | Direct on the key object | Yes |
| Last write time | No | Direct on the key object | Yes |

A watch is bound to the key object rather than to either, and stays on
that object whatever happens to the name ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

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

## registry.pol

One external format constrains the design. `registry.pol` is the binary
format Active Directory Group Policy uses to deliver configuration to
domain-joined machines, and the registry exists so that Peios can
consume it without loss. Everything `registry.pol` can express, the
registry can represent.

Three consequences run all the way through:

- The **full Windows value type set** is supported, including the three
  hardware-resource types that carry no Peios semantics at all. They
  behave exactly as `REG_BINARY`; they exist so a value copied from a
  Windows hive round-trips with its type tag intact ([Values](</kernel/internals/lcs/data-model/values.md#trm-5-2-6>)).
- **Paths are backslash-separated, case-preserving and
  case-insensitive.** This is not negotiable and it is the reason case
  folding appears in the kernel at all ([Names and Case](</kernel/internals/lcs/data-model/names-and-case.md#trm-5-2-8>)).
- **Registry access rights occupy the Windows bit positions**, so a
  Security Descriptor containing registry ACEs is binary-compatible
  ([Access Rights](</kernel/internals/lcs/security/access-rights.md#trm-5-4-2>)).

Tombstones and blanket tombstones exist for the same reason: the
`**Del.ValueName` and `**DelVals` directives express *absence*, which a
purely additive overlay cannot ([Tombstones](</kernel/internals/lcs/data-model/tombstones.md#trm-5-2-7>)).

LCS does not parse `registry.pol`. Parsing is a userspace concern; LCS
provides the model that makes a faithful translation possible.

No other parity with Windows is claimed. The binary compatibility of a
Security Descriptor is a KACS guarantee, not an LCS one.

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

## Where the model diverges from Windows

LCS is modelled on the Windows Configuration Manager, and departs from
it in seven places. All seven are decisions rather than gaps.

| | Windows | LCS |
|---|---|---|
| Backing store | Kernel-internal hive files | Userspace sources over the RSI, so a storage backend is not a kernel change |
| Hive routing | A fixed set of predefined hives | Any source may register any name at runtime |
| Layers | None; `registry.pol` is applied by flattening values | Precedence-ordered layers with tombstones, resolved at query time, so removal reverts rather than tattoos |
| Change observation | `RegNotifyChangeKeyValue`, single-shot | Persistent watches, closing the re-registration race |
| Key identity | Hive cell offsets | GUIDs, stable across storage reorganisation |
| Forward slash | Not accepted | Accepted on input, normalised to backslash |
| Case comparison | `RtlCompareUnicodeString` | Unicode Simple Case Folding, pinned to a version |

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

## Windows features that are absent

Four have been evaluated and deliberately excluded.

**Key classes.** The `class` parameter of `RegCreateKeyEx` is
documented by Microsoft as reserved, and no consumer of it is known.

**`RegOverridePredefKey`.** Per-process key redirection, and specific
to COM. It would require unbounded per-process state in the kernel, and
private hives and private layers cover the uses that are legitimate.

**WoW64 redirection.** Splitting keys by pointer width. Peios has no
32-bit compatibility concern to split for.

**The `HKEY_CLASSES_ROOT` merged overlay.** A merge of `HKLM` and
`HKCU` `Software\Classes`, again COM-specific, with no Peios
equivalent.

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

## This chapter

[Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>) covers the data model — hives, keys, path entries, values,
tombstones, names, and what happens to a key that loses its last name.
[The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>) covers layers: the model, the base layer, where layer metadata
lives and the circularity that implies, who may write into a layer, and
the resolution algorithm and the sequence counter that drives it. [The Access Flow](</kernel/internals/lcs/security/the-access-flow.md#trm-5-4-1>)
covers security: the access flow, the rights, inheritance, and the audit
events LCS emits. [The Fd Model](</kernel/userspace/native/lcs/file-descriptors-and-buffer-conventions.md#trm-5-5-1>) covers the syscall and ioctl interface and the
error model. [The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md#trm-5-6-1>) covers watches, [Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>) transactions, and [The Source Model](</kernel/internals/lcs/sources/the-source-model.md#trm-5-8-1>) the source
model — registration, dispatch, validation, and the intricate business
of what a late response means. [The Stream](</kernel/internals/lcs/backup-and-restore/the-stream.md#trm-5-9-1>) covers backup and restore, [The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>) how
LCS configures itself out of the registry it is serving, and [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>) the
ABI.

Two contracts extracted from LCS are specified rather than described,
because a third party implements the other side of each: the Registry
Source Interface and the registry backup format. Both are chapters of
PSPK.

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

## Build configuration

LCS is built by `CONFIG_SECURITY_PKM`, a boolean option, so it is linked
into `vmlinux` rather than loaded. <a id="cite-lcs-abi-notes.built-in-by-config-security-pkm"></a>

`CONFIG_RUST=y` is required: the resolution core, the RSI codec, the
backup serialiser and the transaction log are Rust, implemented in
`security/pkm/lcs/lcs_core`. <a id="cite-lcs-abi-notes.requires-config-rust"></a>

`CONFIG_SECURITY_PKM_KUNIT` compiles in the in-kernel test
harness. <a id="cite-lcs-abi-notes.kunit-option-compiles-test-harness"></a>

The three syscall numbers are registered in
`arch/x86/entry/syscalls/syscall_64.tbl` and the corresponding table
under `tools/perf/`. <a id="cite-lcs-abi-notes.syscall-numbers-added-by-patch"></a>

They are registered `common`, so the same row serves the x32 ABI
wherever that ABI is built in; the Peios kernel does not build it. <a id="cite-lcs-abi-notes.syscalls-registered-common"></a>

## Related explanations

- [File descriptors and buffer conventions](</kernel/userspace/native/lcs/file-descriptors-and-buffer-conventions.md>)

## Calling the subsystem

The [native LCS interface reference](</kernel/userspace/native/lcs/overview.md>) collects the caller contracts and generated ABI tables.

## Topics

- [Data model](</kernel/internals/lcs/data-model/overview.md>)
- [Layers](</kernel/internals/lcs/layers/overview.md>)
- [Security](</kernel/internals/lcs/security/overview.md>)
- [Watches](</kernel/internals/lcs/watches/overview.md>)
- [Transactions](</kernel/internals/lcs/transactions/overview.md>)
- [Sources](</kernel/internals/lcs/sources/overview.md>)
- [Backup and restore](</kernel/internals/lcs/backup-and-restore/overview.md>)
- [Bootstrap](</kernel/internals/lcs/bootstrap/overview.md>)

---

# Data model

_Peios Kernel / Internals / LCS / Data model_

> Find the Peios kernel articles about data model.

Use these articles to understand data model in the Peios kernel.

- [Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md>)
- [Private Hives](</kernel/internals/lcs/data-model/private-hives.md>)
- [Keys](</kernel/internals/lcs/data-model/keys.md>)
- [Symlinks](</kernel/internals/lcs/data-model/symlinks.md>)
- [Path Entries](</kernel/internals/lcs/data-model/path-entries.md>)
- [Values](</kernel/internals/lcs/data-model/values.md>)
- [Tombstones](</kernel/internals/lcs/data-model/tombstones.md>)
- [Names and Case](</kernel/internals/lcs/data-model/names-and-case.md>)
- [Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md>)

---

# Hives and Routing

_Peios Kernel / Internals / LCS / Data model_

> A hive is the first component of every path — the routing table that maps hive names to sources, and the two names the kernel knows itself.

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

A hive is a top-level namespace — the first component of every registry
path. LCS keeps a routing table mapping hive names to registered
sources, and that table is built entirely from what registers. There is
no static configuration. <a id="cite-hive.routing-table.built-from-registrations"></a>

| Field | Description |
|---|---|
| Name | The hive name, e.g. `Machine`, `Users`. Case-preserving, compared case-insensitively. <a id="cite-hive.field.name-case-insensitive"></a> |
| Root GUID | The GUID of the hive's root key, supplied by the source at registration. <a id="cite-hive.field.root-guid-supplied-by-source"></a> |
| Source | The source slot backing this hive. |
| Status | Active or Unavailable, tracking source connectivity. <a id="cite-hive.field.status-active-or-unavailable"></a> |

Status is a property of the source slot rather than of the individual
hive, which amounts to the same thing: a slot's hives are exactly one
source's, and they go Down together. <a id="cite-hive.status-is-per-source-slot"></a>

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

## Route identity

A hive route is identified by the pair **(case-folded name, scope)**,
where the scope is either the global namespace or one private scope
GUID. <a id="cite-hive.route-identity.name-and-scope"></a>

That pair must be unique across every registered source; a source
claiming one another source already holds is rejected. <a id="cite-hive.route-identity.must-be-unique"></a>

The same name may appear in different scopes, which is precisely how a
private hive shadows a global one without colliding with it. <a id="cite-hive.route-identity.same-name-in-different-scopes"></a>

A hive is backed by exactly one source. A source may back many. <a id="cite-hive.one-source-per-hive"></a>

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

## Routing a path

LCS takes the first component of a path — everything before the first
separator — and looks it up. <a id="cite-hive.routing.uses-first-component"></a>

- Registered and active routes to the backing source. <a id="cite-hive.routing.active-routes-to-source"></a>
- Not registered is `ENOENT`. <a id="cite-hive.routing.unregistered-is-enoent"></a>
- Registered but Down is `EIO`. <a id="cite-hive.routing.down-is-eio"></a>

Before any source registers, the table is empty and every path yields
`ENOENT` ([The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>)).

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

## `CurrentUser` is not a hive

`CurrentUser\` is a kernel-level alias. When a caller-supplied absolute
path starts with it, LCS reads the user SID from the calling thread's
effective token and rewrites the path to `Users\<SID>\...` before
routing. <a id="cite-hive.currentuser.rewrites-to-users-sid"></a>

The rewritten path is re-checked against the total-length limit, since
a textual SID is longer than the alias it replaced. <a id="cite-hive.currentuser.rewritten-path-rechecked-for-length"></a>

Three constraints keep this safe.

It applies **only to the first component** of a path, and only to a
caller-supplied absolute one. <a id="cite-hive.currentuser.first-component-of-caller-path-only"></a>

It does **not** apply to symlink targets: a target beginning with
`CurrentUser\` is followed literally, routes as a hive of that name,
and finds nothing. <a id="cite-hive.currentuser.not-applied-to-symlink-targets"></a> Without that rule, a symlink
containing `CurrentUser\` would redirect a privileged service into the
service's own user hive — a confused deputy.

And `CurrentUser` cannot be registered as a hive name. LCS rejects the
registration with `EINVAL`, so the alias can never collide with a real
hive. <a id="cite-hive.currentuser.cannot-be-registered-einval"></a>

Symlink targets *are* subject to ordinary hive routing, private hives
included. <a id="cite-hive.symlink-targets-use-ordinary-routing"></a> A sandboxed process resolving a symlink sees the same
registry through it that it sees directly, which is the point of
sandboxing it.

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

## Two names the kernel knows

LCS is source-agnostic about routing but not entirely ignorant of
names. `Users` is compiled in as the target of `CurrentUser\`
rewriting. `Machine` is matched, case-insensitively and only for a
global hive, to decide when to run the bootstrap refresh that reads
LCS's own configuration ([The Boot Sequence](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-2>)).

Neither is a routing decision — an unregistered `Machine` routes
nowhere like any other name — but the two names do exist in the kernel. <a id="cite-hive.known-names.get-no-routing-privilege"></a>

In practice loregd registers `Machine` and `Users` at boot. Other
sources may register other hives at any time.

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

## Names

Hive names follow the same rules as key name components: no backslash,
no forward slash, no null byte, valid UTF-8, non-empty, and no longer
than `MaxPathComponentLength`. <a id="cite-hive.name.follows-key-component-rules"></a> They are case-preserving and compared
case-insensitively ([Names and Case](</kernel/internals/lcs/data-model/names-and-case.md#trm-5-2-8>)).

---

# Private Hives

_Peios Kernel / Internals / LCS / Data model_

> Hives invisible in the global namespace, reachable only through a scope GUID on the calling token — routing, lifecycle and registration rules.

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

A private hive is registered with the `RSI_HIVE_PRIVATE` flag and a
scope GUID. <a id="cite-private-hive.registered-with-flag-and-scope-guid"></a>

It is invisible in the global namespace and reachable only by a thread
whose token carries that scope GUID. <a id="cite-private-hive.invisible-globally-and-scope-gated"></a>

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

## Routing

Private hives are checked **before** global ones. <a id="cite-private-hive.routing.checked-before-global"></a>

For each scope GUID on the calling thread's token, in the order the
token carries them, LCS looks for a private hive with the path's name
and that scope. The first match wins. Only if none matches is the
global table consulted. <a id="cite-private-hive.routing.token-order-first-match-wins"></a>

A private hive can therefore shadow a global one, and no name is exempt
— a thread with a private `Machine\` sees the private one. <a id="cite-private-hive.routing.shadows-any-global-name"></a> That is what
makes complete registry isolation possible for a container or a
sandbox without giving it a differently-named hive to notice.

`MaxScopeGUIDsPerToken`, default 8, bounds the per-syscall iteration
cost; a token above the cap fails every registry operation with `E2BIG`
([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-private-hive.scope.max-guids-per-token"></a> Duplicate scope GUIDs on a token are rejected.

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

## Scope GUIDs on a token

Scope GUIDs reach a thread through the KACS token's LCS credential
extension: a versioned block in the token specification carrying the
thread's scope GUIDs and its private layer names ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). It parses at
a fixed offset, and:

- rejects a nil scope GUID; <a id="cite-private-hive.credential.rejects-nil-guid"></a>
- rejects duplicate scope GUIDs; <a id="cite-private-hive.credential.rejects-duplicate-guids"></a>
- caps the count at 256 — a hard KACS limit, above the configurable
  LCS one. <a id="cite-private-hive.credential.caps-count-at-256"></a>

The credentials propagate across fork, duplication and impersonation
like the rest of the token. <a id="cite-private-hive.credential.propagates-across-fork-and-impersonation"></a>

Attaching them is gated by `SeCreateTokenPrivilege`, because scope
GUIDs can only enter a token when the token is created. <a id="cite-private-hive.scope.attaching-gated-by-secreatetokenprivilege"></a> That is a
blanket privilege rather than a per-scope authorisation: a caller that
can create tokens at all can create one claiming any scope. Isolation
between private hives therefore rests on who may create tokens, not on
who owns a scope.

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

## Scope lifecycle

A scope GUID is an opaque 128-bit value with no lifecycle. LCS neither
creates nor tracks one; it only compares. <a id="cite-private-hive.scope.opaque-and-untracked-by-lcs"></a> A scope exists as long as
some private hive or some token references it, and when the last
reference goes it is simply a number nobody uses.

Nothing in the kernel generates scope GUIDs. <a id="cite-private-hive.scope.not-generated-by-kernel"></a> Key GUIDs and token GUIDs
come from the kernel's UUIDv4 generator; scope GUIDs are supplied by
userspace, and choosing them unpredictably is userspace's
responsibility.

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

## Registration rules

Registration enforces more than the route-identity uniqueness of
[Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>) — the full list is [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>), and the rules that exist for private
hives are these:

- A hive's root GUID may not be nil.
- The root GUIDs within one registration request must be
  distinct.
- A hive without the `RSI_HIVE_PRIVATE` flag may not carry a non-nil
  scope GUID.
- A hive **with** the flag may not carry a nil one. <a id="cite-private-hive.registration.private-hive-requires-scope-guid"></a> No token
  can carry a nil scope GUID, so such a hive would be registrable and
  then permanently unroutable — holding its name against other sources
  in that scope while every lookup returned `ENOENT`.
- Unknown flag bits are rejected.
- Opening `/dev/pkm_registry` at all requires an **enabled**
  `SeTcbPrivilege`, checked in the device's `open()` handler
  ([Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>)).

---

# Keys

_Peios Kernel / Internals / LCS / Data model_

> A key is a container of subkeys and values — its identity, its properties, volatile keys, and the rules for naming one.

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

A key is a node in the hierarchy: a container holding subkeys and
values. The filesystem analogy is an inode. A key carries identity and
properties; naming lives in path entries ([Path Entries](</kernel/internals/lcs/data-model/path-entries.md#trm-5-2-5>)).

| Field | Mutable | Layered | Description |
|---|---|---|---|
| GUID | No | No | Identity, assigned by LCS at creation, persisted by the source. |
| Name | No | No | The key's own name component. Informational; the path entry resolves the identity. `QUERY_KEY_INFO` preserves this spelling only when it folds to that resolved leaf, and audits and refuses a mismatch with `EIO`. <a id="cite-key.field.name-is-informational"></a> |
| Parent GUID | No | No | The parent key. Nil for a hive root. <a id="cite-key.field.parent-guid-nil-for-hive-root"></a> |
| Security Descriptor | Yes | No | Computed from the parent at creation; changed at runtime with `WRITE_DAC` / `WRITE_OWNER`. <a id="cite-key.field.security-descriptor-computed-from-parent"></a> |
| Last write time | Yes | No | Updated when a value is written or deleted or the descriptor changes. <a id="cite-key.field.last-write-time-updates"></a> |
| Volatile | No | No | The source stores this key in non-persistent storage only. |
| Symlink | No | No | This key is a symbolic link ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)). |

**No key property is layer-qualified.** Properties belong to the object. <a id="cite-key.no-property-is-layer-qualified"></a>
Changing a key's structural type through a layer is not a matter of
setting a flag; the layer hides the original key and creates a new one
at the same path, which is the ordinary overlay pattern.

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

## Identity

A key's identity is its GUID, not its path. Two keys occupying the same
path at different times are different objects with different GUIDs. <a id="cite-key.identity.is-guid-not-path"></a> A
path is a name that maps to an identity; the identity outlives the
name.

GUIDs are assigned by LCS — never by a source — and pushed to the
source at creation, where they become the primary key of its
storage. <a id="cite-key.identity.guid-assigned-by-lcs-not-source"></a>

Once a path has been resolved to a GUID at open time, every subsequent
RSI operation uses the GUID directly. <a id="cite-key.identity.rsi-uses-guid-after-open"></a>

The generator is the kernel's version-4 GUID generator: random bytes
from the kernel CSPRNG with the version and variant bits set in the
PCDS layout — the version nibble in the high nibble of byte 7, because
`Data3` is little-endian in bytes 6–7, and the variant bits in byte 8. <a id="cite-key.identity.guid-generator-is-uuidv4"></a>

Freshness is the collision resistance of UUIDv4 plus a check against
the keys LCS currently tracks, with a bounded retry. <a id="cite-key.identity.freshness-checked-against-tracked-keys"></a>

There is **no persistent retired-GUID catalogue**, and no code anywhere
that would maintain one. A GUID dropped by orphan cleanup is not
remembered. <a id="cite-key.identity.no-retired-guid-catalogue"></a>

If a source answers `RSI_CREATE_KEY` for a freshly generated GUID with
`RSI_ALREADY_EXISTS`, that is not a race to retry — the kernel believes
the GUID is unused and the source disagrees. LCS treats it as source
inconsistency and fails closed with `EIO`. <a id="cite-key.identity.create-key-already-exists-is-eio"></a>

It is never retried as an open and `EEXIST` never reaches userspace
from `reg_create_key`. <a id="cite-key.identity.no-eexist-from-reg-create-key"></a>

A GUID appears at exactly one canonical location. LCS validates that
and rejects a source that reports otherwise.

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

## Volatile keys

Volatile is a flag LCS carries and forwards. Storing a volatile key in
non-persistent storage is the source's obligation; nothing in the
kernel enforces it. <a id="cite-key.volatile.storage-is-the-source-obligation"></a>

What the kernel does enforce is the containment rule: **a non-volatile
key may not be created under a volatile parent** (`EINVAL`). <a id="cite-key.volatile.non-volatile-under-volatile-parent-is-einval"></a>

The converse is allowed — a volatile key under a persistent parent is
ordinary. <a id="cite-key.volatile.volatile-under-persistent-parent-allowed"></a>

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

## Naming

Three bytes are forbidden in a key name component: backslash and
forward slash, both of which are separators, and the null
byte. <a id="cite-key.name.three-forbidden-bytes"></a>

Every other valid UTF-8 sequence is permitted, spaces and arbitrary
Unicode included. <a id="cite-key.name.any-other-utf8-permitted"></a>

Empty components are forbidden, which rules out a leading separator and
consecutive separators (`Machine\\System`). <a id="cite-key.name.empty-components-forbidden"></a>

A trailing separator (`Machine\System\`) is likewise
invalid. <a id="cite-key.name.trailing-separator-invalid"></a>

Length limits are byte counts: `MaxPathComponentLength` per component,
`MaxTotalPathLength` for the whole path, `MaxKeyDepth` for nesting.

Forward slash normalisation is achieved by treating `/` as a separator
wherever a separator is recognised, rather than by rewriting the string
— so a materialised component never contains either separator, and the
canonical form is per-component rather than a canonicalised string.

---

# Symlinks

_Peios Kernel / Internals / LCS / Data model_

> The two load-bearing mechanisms behind a symlink key — the structural flag and the target value — plus resolution, depth and opening the link itself.

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

A symlink key uses two mechanisms, and both are load-bearing.

The **symlink flag** on the key record marks the key's structural type.
It is set at creation by `REG_OPTION_CREATE_LINK` and is immutable
afterwards. <a id="cite-symlink.flag.set-at-creation-and-immutable"></a>

`RSI_WRITE_KEY` can update only the descriptor and the last write time,
so there is no operation that could change it. <a id="cite-symlink.flag.rsi-write-key-cannot-change-it"></a>

The **default value, of type `REG_LINK`,** supplies the target
path. <a id="cite-symlink.target.is-the-reg-link-default-value"></a>

It is an ordinary layered value, which means a higher-precedence layer
can redirect a symlink by writing a different `REG_LINK` default value,
and removing that layer restores the original target. <a id="cite-symlink.target.layer-can-redirect-and-revert"></a>

The flag marks identity; the value provides the target.

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

## Resolution

LCS follows symlinks during path resolution and the fd it returns
refers to the resolved target — its GUID, its position in the tree, its
ancestor chain — not to the link. <a id="cite-symlink.resolution.fd-refers-to-the-target"></a>

The target is resolved by issuing a separate `RSI_QUERY_VALUES` for the
key's default value (the empty name) and applying ordinary layer
resolution to the result, so the target participates in the layer
system exactly as any other value does. <a id="cite-symlink.resolution.target-read-with-layer-resolution"></a>

If the effective default value is missing, or is not of type
`REG_LINK`, resolution fails with `EINVAL`. <a id="cite-symlink.resolution.missing-or-wrong-type-is-einval"></a>

LCS does **not** validate the type at write time: a layer that writes a
`REG_SZ` default value over a symlink's target breaks resolution at the
next open, and removing that layer fixes it. <a id="cite-symlink.resolution.target-type-not-validated-at-write-time"></a>

The offending value stays in the registry; a failed resolution writes
nothing. <a id="cite-symlink.resolution.failed-resolution-writes-nothing"></a>

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

## The target path

The `REG_LINK` payload is a length-delimited UTF-8 registry path. No
trailing null is required or permitted — the length delimits it, and a
null byte inside that length is rejected like any
other. <a id="cite-symlink.target-path.length-delimited-no-trailing-null"></a> Forward
slashes are handled as separators as everywhere else.

The target is validated with exactly the same rules as a syscall path:
UTF-8, no null bytes, per-component and total length, no empty
components, no trailing separator, maximum depth. <a id="cite-symlink.target-path.validated-like-a-syscall-path"></a> The only difference
is that a syscall path arrives null-terminated and has its terminator
stripped first.

A target is always interpreted as absolute — its first component is
routed as a hive name. <a id="cite-symlink.target-path.always-absolute"></a>

Resolution has no check that rejects a relative-looking target as
malformed. A target of `Sub\Key` is not an error; it is a request for a
hive named `Sub`, and it yields `ENOENT` unless such a hive happens to
be registered, in which case it resolves there. <a id="cite-symlink.target-path.relative-looking-target-not-rejected"></a>

Writing one is different. `REG_IOC_SET_VALUE` of a `REG_LINK` value
routes the target's first component at write time, with the writer's
scope GUIDs, and answers `EINVAL` if it names no registered hive. That
is what stops a dangling target being captured later by whoever
registers a private hive of that name: a target that cannot be written
cannot be captured, and the failure lands on whoever authored it. The
cost is that a symlink cannot forward-reference a hive registered after
it. A target that arrives in source data or a backup stream is not
gated, which is why resolution still has to treat the shape as a hive
request. <a id="cite-symlink.target-path.write-time-routing-gate"></a>

`CurrentUser\` rewriting is not applied ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)), so a target beginning
with `CurrentUser\` routes as a hive of that name and cannot be
registered, and therefore always fails. Ordinary hive routing does
apply, private hives included, for the resolving thread.

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

## Depth

Symlink resolution is bounded by `SymlinkDepthLimit`, default 16,
configurable from 1 to 64. Exceeding it is `ELOOP`. <a id="cite-symlink.depth.exceeding-the-limit-is-eloop"></a>

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

## Opening the link itself

`REG_OPEN_LINK` on `reg_open_key` opens the symlink key rather than
following it, which is how a symlink is managed at all — deleted,
retargeted, inspected. <a id="cite-symlink.open-link.opens-the-link-not-the-target"></a>

It applies to the **final path component only**. A symlink encountered
part-way along a path is followed whether or not the flag is
set. <a id="cite-symlink.open-link.final-component-only"></a>

The access check follows the same rule: with `REG_OPEN_LINK` the check
is against the link, otherwise against the target. <a id="cite-symlink.open-link.access-check-follows-the-flag"></a>

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

## Creation

Creating a symlink needs all of:

- `KEY_CREATE_SUB_KEY` on the parent, as for any key; <a id="cite-symlink.create.requires-key-create-sub-key"></a>
- `KEY_CREATE_LINK` on the parent; <a id="cite-symlink.create.requires-key-create-link"></a>
- either an enabled `SeTcbPrivilege` or membership of Administrators. <a id="cite-symlink.create.requires-setcbprivilege-or-administrators"></a>

The last is a genuine disjunction — either satisfies it — and the
privilege branch marks the privilege used. <a id="cite-symlink.create.privilege-branch-marks-privilege-used"></a>

Failing it is `EPERM`. <a id="cite-symlink.create.failure-is-eperm"></a>

---

# Path Entries

_Peios Kernel / Internals / LCS / Data model_

> Key existence and naming are layer-qualified while key identity is not — the per-layer path entry that separates them, and hiding.

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

Key existence and naming are layer-qualified; key identity is not. The
source stores a **path entry** per layer, which separates the two. <a id="cite-path-entry.existence-and-naming-are-layer-qualified"></a> The
overlay-filesystem analogy is exact: directory entries are per-layer,
inodes are shared.

| Field | Description |
|---|---|
| Parent GUID | The parent key. |
| Child name | The key's name under that parent — one component, not a path. <a id="cite-path-entry.field.child-name-is-one-component"></a> |
| Layer | The layer this entry belongs to. |
| Target | The GUID of the key at this path in this layer, or HIDDEN. <a id="cite-path-entry.field.target-is-a-guid-or-hidden"></a> |
| Sequence | A monotonic number assigned by LCS at creation, used for tiebreaking within a precedence tier. |

On the wire a HIDDEN entry is a target type of 1 with an all-zero GUID
([LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>)). <a id="cite-path-entry.hidden.wire-form-is-type-1-and-zero-guid"></a>

A source returning a non-zero GUID on a HIDDEN entry is returning
malformed data. <a id="cite-path-entry.hidden.non-zero-guid-is-malformed"></a>

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

## Creating a key

Creating a key in a layer always assigns a fresh GUID and produces two
records: a path entry `(parent, name, layer) → GUID` with a new
sequence number, and a key record carrying that GUID. <a id="cite-path-entry.create.fresh-guid-and-two-records"></a>

LCS sends `RSI_CREATE_ENTRY` first and `RSI_CREATE_KEY`
second. <a id="cite-path-entry.create.entry-before-key"></a>

That order matters for the race: if another caller got there first, the
entry creation returns `RSI_ALREADY_EXISTS` and LCS retries the whole
thing as an open, reporting `REG_OPENED_EXISTING`. <a id="cite-path-entry.create.entry-already-exists-retries-as-open"></a> Failure on the
*second* call, for a GUID LCS just minted, is not a race and fails
closed ([Keys](</kernel/internals/lcs/data-model/keys.md#trm-5-2-3>)).

If a different layer already has a key at that path, the new layer gets
its own distinct GUID. Each layer has its own key object, and
resolution decides which is visible. <a id="cite-path-entry.create.other-layer-gets-a-distinct-guid"></a>

**No operation creates a path entry pointing at an existing GUID.**
`reg_create_key` always mints a new one. The namespace is a tree, never
a graph. <a id="cite-path-entry.create.never-points-at-an-existing-guid"></a>

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

## No GUID sharing across layers

The path table's shape would technically permit two entries referencing
one GUID, which would be a hard link. No API exposes it. <a id="cite-path-entry.no-hard-links.no-api-exposes-guid-sharing"></a>

Every key has exactly one canonical parent and name, and LCS validates
that a source is not reporting otherwise: the key record's parent must
be the parent the key was reached through, and its name must fold to the
component the key was reached by. A record that says otherwise is
malformed key metadata — `REG_IOC_QUERY_KEY_INFO` answers
`EIO` and the source-data validation failure is audited. <a id="cite-path-entry.no-hard-links.one-canonical-parent-and-name"></a>

Aliasing has an explicit, visible mechanism, and it is symlinks. Hard
links would make parent-GUID semantics, descriptor inheritance, subtree
enumeration and watch dispatch all ambiguous at once.

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

## Hiding

A layer can create a HIDDEN entry at a path, making the key invisible
regardless of what lower-precedence layers say. <a id="cite-path-entry.hiding.hidden-entry-makes-a-key-invisible"></a>

It is the path-level equivalent of a value tombstone, and when the
hiding layer is removed the lower key reappears. <a id="cite-path-entry.hiding.removing-the-layer-restores-the-lower-key"></a>

A HIDDEN entry gets a sequence number like any other entry, so a
conflict between a GUID entry in one layer and a HIDDEN entry in
another at the same precedence resolves deterministically: the higher
sequence number wins. <a id="cite-path-entry.hiding.hidden-entry-carries-a-sequence-number"></a>

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

## Hide and replace

A single layer can hide an existing key and put a new one at the same
path, and no special mechanism is needed for it. The layer creates its
own path entry pointing at its own new GUID; lower-precedence entries
for the same `(parent, name)` are masked because this layer's entry
wins on precedence. <a id="cite-path-entry.hide-and-replace.layer-entry-masks-lower-entries"></a>

Removing the layer removes both the new key and its masking effect, and
the lower key comes back. <a id="cite-path-entry.hide-and-replace.removing-the-layer-restores-the-lower-key"></a>

This falls out of per-layer path entries and precedence ordering
without a line of code that knows about it.

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

## Hive roots

A hive root has no parent GUID and no child name, so there is no
`(parent, name, layer)` tuple to remove or mask. <a id="cite-path-entry.hive-root.has-no-parent-or-child-name"></a>

Deleting or hiding a hive root fd is `EINVAL`, rejected before source
dispatch, before transaction enlistment, before sequence allocation and
before any watch event is generated. <a id="cite-path-entry.hive-root.delete-or-hide-is-einval"></a>

---

# Values

_Peios Kernel / Internals / LCS / Data model_

> A named, typed datum inside a key — one name with many layer entries, the type set, REG_TOMBSTONE, naming and size.

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

A value is a named, typed datum inside a key. Values hold the
configuration data; keys hold values.

| Field | Description |
|---|---|
| Key GUID | The key this value belongs to. |
| Name | The value's name; the empty string is the default value. Case-preserving, compared case-insensitively. <a id="cite-value.field.empty-name-is-the-default-value"></a> |
| Type | A registry value type. |
| Data | An opaque byte array, up to `MaxValueSize` (default 1 MB). <a id="cite-value.field.data-bounded-by-max-value-size"></a> |
| Layer | The layer this entry belongs to. Every write is tagged. <a id="cite-value.field.every-write-is-layer-tagged"></a> |
| Sequence | Assigned by LCS at write time, for tiebreaking within a precedence tier. |

A key holds many values with distinct names, and at most one unnamed
one. <a id="cite-value.at-most-one-unnamed-value-per-key"></a>

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

## One name, many entries

A single `(key GUID, value name)` pair can have several entries in the
source — one per layer that has written to it. <a id="cite-value.one-name-many-entries.one-entry-per-writing-layer"></a>

The source stores them all and returns them all. <a id="cite-value.one-name-many-entries.source-returns-every-entry"></a>

LCS resolves the effective value at read time ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

That is the mechanism that makes layer deletion revert configuration
automatically. Delete the layer, its entries go, and the
next-highest-precedence entry becomes effective. Nothing has to be
recomputed or rewritten.

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

## Types

The full Windows type set is supported, for `registry.pol` fidelity:
`REG_NONE`, `REG_SZ`, `REG_EXPAND_SZ`, `REG_BINARY`, `REG_DWORD`,
`REG_DWORD_BIG_ENDIAN`, `REG_LINK`, `REG_MULTI_SZ`,
`REG_RESOURCE_LIST`, `REG_FULL_RESOURCE_DESCRIPTOR`,
`REG_RESOURCE_REQUIREMENTS_LIST` and `REG_QWORD`, numbered 0 to 11. <a id="cite-value.types.full-windows-set-numbered-0-to-11"></a>
Values are in [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>).

LCS stores the type tag and returns it on read but does not interpret
the data. <a id="cite-value.types.tag-stored-and-returned-uninterpreted"></a> The single exception is `REG_LINK` read as a symlink key's
default value, which triggers target resolution ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)).

The three hardware-resource types, 8 to 10, describe device resource
assignments in the Windows `HKLM\HARDWARE` hive, which the Windows
kernel rebuilds at every boot. Peios has no equivalent: hardware
enumeration belongs to the Linux device model, sysfs and `/proc/iomem`,
not to the registry. LCS accepts these tags only so a value carrying
one round-trips without loss. They have no semantics, LCS never
produces one, and for every operation they behave as `REG_BINARY`. <a id="cite-value.types.hardware-resource-types-behave-as-reg-binary"></a>
Rejecting a faithfully-copied value would break the fidelity guarantee
that is the reason the registry exists.

Type tags are validated at every write boundary, before sequence
allocation, transaction enlistment or source dispatch. An unknown code
is `EINVAL`. <a id="cite-value.types.unknown-type-code-is-einval"></a>

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

## `REG_TOMBSTONE`

One further type, `REG_TOMBSTONE` (`0xFFFF`), is internal. It is never
returned to a caller reading a value — a caller whose effective entry
is a tombstone gets `ENOENT`, which is exactly what a tombstone
means. <a id="cite-value.reg-tombstone.never-returned-to-a-caller"></a>

There is no separate tombstone flag in the `REG_IOC_SET_VALUE`
argument. Writing type `REG_TOMBSTONE` **is** the explicit tombstone
operation. <a id="cite-value.reg-tombstone.written-by-setting-the-type"></a>

It must carry zero-length data; non-empty tombstone data is `EINVAL`,
again before sequence allocation, enlistment or dispatch. <a id="cite-value.reg-tombstone.non-empty-data-is-einval"></a>

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

## Naming

Value names use the same case rules as key names: Unicode Simple Case
Folding, case-preserving, case-insensitive. <a id="cite-value.name.same-case-rules-as-key-names"></a>

They differ in one respect. **Backslash and forward slash are permitted
in a value name.** Value names are not hierarchical, so a separator has
no meaning in one. <a id="cite-value.name.separators-are-permitted"></a>

Only the null byte is forbidden, and invalid UTF-8 is rejected. The
empty string is reserved for the default value. <a id="cite-value.name.only-the-null-byte-is-forbidden"></a>

That difference is why watch event path components are length-prefixed
rather than joined by a separator ([Event Records](</kernel/internals/lcs/watches/event-records.md#trm-5-6-2>)) — a value name can contain
the separator.

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

## Size

`MaxValueSize` defaults to 1 MB and is configurable from 4 KB to 64 MB
([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)).

Value data is opaque bytes and is not subject to the UTF-8 validation
that applies to every string in the interface. <a id="cite-value.data.opaque-and-not-utf8-validated"></a>

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

## Tool value encodings

`reg`, Registry Editor and the `peios` Rust crate use these representations:

- `REG_SZ` and `REG_EXPAND_SZ`: UTF-8 ending in one null byte, rather than
  Windows' UTF-16 representation.
- `REG_LINK`: the absolute target path in UTF-8, with no null byte. Its
  length determines its end; a target containing a null is not followed.
- `REG_MULTI_SZ`: each string followed by a null byte, with one additional
  null byte ending the list.
- Integers: little-endian, except for `REG_DWORD_BIG_ENDIAN`.

These are data conventions shared by tools. LCS still treats ordinary
value payloads as opaque bytes; its special handling of a link key's
`REG_LINK` default value is described in [Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>). For choosing and entering
a type as an operator, see
[Keys, values, and types](https://learn.peios.org/peios/using-peios/registry/reg/).

---

# Tombstones

_Peios Kernel / Internals / LCS / Data model_

> An overlay that can only add is not enough — value and blanket tombstones, how they compete, and what a watcher sees.

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

An overlay that can only add is not enough. `registry.pol` expresses
*absence* — `**Del.ValueName` deletes a specific value,
`**DelVals` deletes every value in a key before applying new ones — and
a higher-precedence layer that can only override cannot say "this value
must not be configured". Tombstones are how absence is expressed.

Both kinds are per-layer, and both vanish with their layer, restoring
whatever they were masking. <a id="cite-tombstone.per-layer-and-vanish-with-the-layer"></a>

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

## Value tombstones

A value tombstone is a layer entry that says the value does not exist
in this layer and lower-precedence layers are masked. <a id="cite-tombstone.value.masks-lower-precedence-layers"></a>

Resolution treats a winning tombstone as "not found" without falling
through. <a id="cite-tombstone.value.winning-tombstone-does-not-fall-through"></a>

In the source's storage it is an entry of type `REG_TOMBSTONE` with no
data. A caller who wins with one gets `ENOENT`.

Removing the tombstone's layer makes the lower-precedence value
effective again, which is the whole point.

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

## Blanket tombstones

A blanket tombstone is a per-layer marker on a **key** that masks every
value from lower-precedence layers, whatever its name. <a id="cite-tombstone.blanket.masks-every-value-name"></a>

Where a value tombstone names one value, a blanket names none and
covers all — including values whose names were not known when the
blanket was written, which is exactly what `**DelVals`
requires. <a id="cite-tombstone.blanket.covers-names-unknown-when-written"></a>

It is stored as a flag on the `(key GUID, layer)` relationship and
occupies no per-name entry. It has its own sequence
number. <a id="cite-tombstone.blanket.stored-as-a-flag-with-its-own-sequence"></a>

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

### How it competes

A blanket does not short-circuit resolution. It enters the candidate
pool as a tombstone candidate **for every value name**, at its own
`(precedence, sequence)`, <a id="cite-tombstone.blanket.enters-the-candidate-pool-for-every-name"></a> and the ordinary rule picks the winner
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

So a per-value entry that beats the blanket on the tuple overrides it,
and one that loses is masked. <a id="cite-tombstone.blanket.per-value-entry-wins-or-loses-on-the-tuple"></a>

A layer can write a blanket *and* write specific values in the same
layer: the specific values are visible because they were written
afterwards and carry higher sequence numbers, and everything else from
below is masked. <a id="cite-tombstone.blanket.same-layer-writes-after-a-blanket-stay-visible"></a> That is `**DelVals` followed by new writes,
expressed without a special case.

An exact tie — same precedence *and* same sequence — between a blanket
and a per-value entry is not resolved in the blanket's favour or
anyone's. It is malformed source data and the operation fails with
`EIO` ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

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

### Enumeration

Enumerating a key with a blanket applies the same per-name rule to each
name, so what a caller sees is the set of names whose winning candidate
is not the blanket. <a id="cite-tombstone.blanket.enumeration-applies-the-per-name-rule"></a>

It is not simply "the blanket's layer and above": a different layer at
the *same* precedence with a higher sequence number surfaces, and one
with a lower sequence number does not. <a id="cite-tombstone.blanket.enumeration-surfaces-higher-sequence-at-same-precedence"></a>

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

### Removal

Removing a blanket, or the layer holding it, unmasks everything it was
hiding. <a id="cite-tombstone.blanket.removal-unmasks-everything-it-hid"></a>

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

## What a watcher sees

Nothing about tombstones. Writing a blanket produces one
`VALUE_DELETED` per name it newly masks; removing one produces one
`VALUE_SET` per name that became visible. A watcher sees per-value
effective state and never has to know the mechanism ([The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md#trm-5-6-1>)).

---

# Names and Case

_Peios Kernel / Internals / LCS / Data model_

> Every string in the LCS interface is UTF-8 — length as byte count, separators, and how case folding works.

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

Every string in the LCS interface — key names, value names, hive names,
layer names, paths — is UTF-8. Invalid UTF-8 is rejected with `EINVAL`
before parsing, routing, folding, layer resolution or source
dispatch. <a id="cite-name.utf8.invalid-utf8-is-einval-before-any-other-work"></a>

Null bytes are rejected in all of them. <a id="cite-name.utf8.null-bytes-rejected-in-every-string"></a>
The rejection is `EINVAL` where the string is length-delimited — ioctl
and RSI strings — because there the null byte sits inside the counted
length. A syscall argument (a path or `reg_create_key`'s layer name) is
a C string, and a null byte there is its terminator: the name the
kernel validates ends at it, and nothing after it is read. <a id="cite-name.utf8.syscall-strings-end-at-the-null"></a>

The one thing that is not a string is value data, which is opaque
bytes.

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

## Lengths are byte counts

Every configured length limit is measured in UTF-8 bytes, not Unicode
scalar values and not display characters. <a id="cite-name.length.measured-in-utf8-bytes"></a>

- `MaxPathComponentLength` (default 255) bounds one component or one
  value or layer name. <a id="cite-name.length.max-path-component-length-bounds-a-component"></a>
- `MaxTotalPathLength` (default 16383) bounds a whole
  path. <a id="cite-name.length.max-total-path-length-bounds-a-path"></a>
- `MaxKeyDepth` (default 512) bounds nesting. <a id="cite-name.length.max-key-depth-bounds-nesting"></a>

A syscall path arrives as a null-terminated C string, is copied under a
hard bound, and has its terminator stripped before anything is
measured — so the terminator is not part of the
length. <a id="cite-name.length.syscall-path-terminator-is-not-counted"></a>

Ioctl and RSI strings are length-delimited and need no terminator; a
terminator byte included in the length is a null byte and is therefore
invalid. <a id="cite-name.length.ioctl-and-rsi-strings-are-length-delimited"></a>

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

## Separators

Backslash is canonical. Forward slash is accepted on input and treated
as a separator wherever a separator is recognised, so a component can
never contain either. <a id="cite-name.separator.forward-slash-is-a-separator"></a>

There is no string-rewriting step: normalisation is a property of how
paths are split rather than a transformation applied to
them. <a id="cite-name.separator.no-string-rewriting-step"></a>

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

## Case folding

Comparison is case-insensitive and storage is
case-preserving. <a id="cite-name.case.insensitive-comparison-preserving-storage"></a>

The algorithm is **Unicode Simple Case Folding** — the `C` and `S`
status entries of `CaseFolding.txt`, with the full (`F`) and Turkic
(`T`) entries excluded. <a id="cite-name.case.simple-case-folding-c-and-s-entries-only"></a>

It is a fixed one-to-one codepoint mapping with no locale input,
applied after decoding from UTF-8, never to raw
bytes. <a id="cite-name.case.folding-applied-to-codepoints-not-bytes"></a>

The Unicode version is **pinned at 16.0**. <a id="cite-name.case.unicode-version-pinned-at-16-0"></a> The table is generated by
`peios/generate-casefold-table.py` and checked in with the
digest of the source data, so adopting a newer Unicode version means
regenerating the table deliberately. It is not something that happens
by updating a dependency.

This gives practical compatibility with Windows'
`RtlCompareUnicodeString` without claiming byte-identical behaviour in
every edge case.

**Unicode normalisation is not performed.** NFC and NFD forms of the
same visual character are different names, matching
Windows. <a id="cite-name.case.no-unicode-normalisation"></a>

Case folding is what "identity" means throughout: a layer's identity is
its folded name, a hive route's identity includes its folded name, and
a duplicate is a folded-equal duplicate. `RoleA` and `rolea` are one
layer, not two. <a id="cite-name.case.identity-is-the-folded-name"></a>

Every comparison folds, on both sides of the kernel boundary. The
Kernel Access Control Subsystem (KACS) parses private layer names into
a token and rejects a duplicate with `EINVAL`; that duplicate check
uses the same folding routine and the same table as LCS, so a pair
that LCS treats as one layer cannot occupy two of a token's slots.
There were two ASCII-only comparators, the `base` check on two of its
call sites and this KACS check, and both are gone ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>) for
`base`). <a id="cite-name.case.every-comparison-folds"></a>

---

# Deletion and Orphans

_Peios Kernel / Internals / LCS / Data model_

> Deletion works on two levels because naming and identity are separate — layer deletion, orphaned keys, and what happens to their watches.

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

Deletion operates on two levels, because naming and identity are
separate things.

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

## Deleting a key

`REG_IOC_DELETE_KEY` removes **one layer's path entry**. The key's data
— its GUID, descriptor and values — is untouched; only a name is
removed. <a id="cite-orphan.delete-key.removes-one-layer-path-entry"></a>

LCS derives the parent GUID from the fd's ancestor chain and the child
name from the last component of its resolved path, and sends
`RSI_DELETE_ENTRY`. <a id="cite-orphan.delete-key.parent-and-name-derived-from-the-fd"></a>

If path entries remain in other layers, the key is still visible
through them. <a id="cite-orphan.delete-key.remaining-entries-keep-the-key-visible"></a>

If none remain anywhere, the key is orphaned. <a id="cite-orphan.delete-key.last-entry-removed-orphans-the-key"></a>

A key with **visible children** cannot be deleted:
`ENOTEMPTY`. <a id="cite-orphan.delete-key.visible-children-is-enotempty"></a>

Visibility is evaluated globally, across all enabled layers, and
deliberately ignores the caller's private layer set — so whether a
deletion succeeds does not depend on who is asking. <a id="cite-orphan.delete-key.visibility-ignores-the-callers-private-layers"></a>

Recursive deletion is a client-side tree walk, not a kernel
primitive. <a id="cite-orphan.delete-key.no-recursive-delete-primitive"></a>

Deleting a key does not delete its values. Values belong to the GUID,
not to the path entry, and go when the GUID goes. <a id="cite-orphan.delete-key.values-survive-entry-deletion"></a>

Hive roots cannot be deleted or hidden ([Path Entries](</kernel/internals/lcs/data-model/path-entries.md#trm-5-2-5>)).

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

## Layer deletion

Deleting a layer removes all of its path entries, value entries and
blanket tombstones, across every source. <a id="cite-orphan.layer-delete.removes-every-entry-across-all-sources"></a>

LCS broadcasts `RSI_DELETE_LAYER` and each source returns the GUIDs
that lost their last path entry as a
result. <a id="cite-orphan.layer-delete.sources-report-newly-orphaned-guids"></a>

Effects on live state follow from the model with no special cases:

- keys named only by that layer become
  orphaned; <a id="cite-orphan.layer-delete.keys-named-only-by-it-become-orphaned"></a>
- where the layer held the winning value entry, the next layer's value
  becomes effective; <a id="cite-orphan.layer-delete.next-layers-value-becomes-effective"></a>
- blanket tombstones it held are removed and unmask what they were
  hiding;
- and Security Descriptors are unchanged, because they were never
  layered. <a id="cite-orphan.layer-delete.security-descriptors-unchanged"></a>

Watchers are notified by whatever recovery mechanism applies —
per-key events for the orphaned keys, and a source-wide `OVERFLOW` for
the rest ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Before sending `RSI_DELETE_LAYER`, LCS aborts every bound transaction
whose mutation log touched that layer. <a id="cite-orphan.layer-delete.aborts-transactions-touching-the-layer"></a> Otherwise a transaction could
commit writes into a layer that no longer exists.

Those transactions return `EINVAL` on their next operation or commit
attempt. <a id="cite-orphan.layer-delete.aborted-transactions-return-einval"></a>

Layer deletion is what role uninstallation and Group Policy removal
are.

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

## Orphaned keys

An orphaned key is a GUID with no path entry in any layer. It follows
the Linux unlink model: alive but unnamed. <a id="cite-orphan.definition.guid-with-no-path-entry-anywhere"></a>

Existing fds keep working. Operations that address the key by GUID
proceed normally:

- querying, setting and deleting values; <a id="cite-orphan.allowed.value-operations"></a>
- setting and removing blanket tombstones; <a id="cite-orphan.allowed.blanket-tombstone-operations"></a>
- querying and setting the Security Descriptor; <a id="cite-orphan.allowed.security-descriptor-operations"></a>
- querying key metadata; <a id="cite-orphan.allowed.query-key-metadata"></a>
- flushing the key's hive; <a id="cite-orphan.allowed.flush-the-hive"></a>
- closing the fd. <a id="cite-orphan.allowed.close-the-fd"></a>

Namespace operations return `ENOENT`:

- creating a child key under it; <a id="cite-orphan.refused.create-a-child-key"></a>
- opening or creating anything relative to it; <a id="cite-orphan.refused.relative-open-or-create"></a>
- deleting its path entry; <a id="cite-orphan.refused.delete-its-path-entry"></a>
- hiding it; <a id="cite-orphan.refused.hide-it"></a>
- backing it up. <a id="cite-orphan.refused.back-it-up"></a>

The reason is that an orphaned key is no longer a reachable subtree
root. Allowing new names beneath an unnamed key would build a subgraph
nothing can reach.

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

## Watches on an orphaned key

A watch armed before the key was orphaned stays armed, and the
transition delivers `KEY_DELETED`. <a id="cite-orphan.watch.stays-armed-and-delivers-key-deleted"></a>

After that the watch may still observe GUID-local changes made through
the surviving fds, though the subtree is no longer expanded through the
orphaned key. <a id="cite-orphan.watch.still-sees-guid-local-changes"></a>

Arming a *new* watch on an already-orphaned key is
`ENOENT`. <a id="cite-orphan.watch.arming-a-new-watch-is-enoent"></a>

Re-arming one that is already armed is allowed. <a id="cite-orphan.watch.re-arming-an-armed-watch-is-allowed"></a>

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

## Dropping the GUID

When the last fd to an orphaned key closes and the source is Active,
LCS sends `RSI_DROP_KEY`, which purges the key record, every value
entry across every layer, and any remaining blanket
tombstones. <a id="cite-orphan.drop.last-close-sends-rsi-drop-key"></a>

It is dispatched **before** the in-kernel key state is
released. <a id="cite-orphan.drop.dispatched-before-state-is-released"></a>

The request is asynchronous: nothing waits for the answer, and a valid
response is processed as an ordinary response rather than as a late
one ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)). <a id="cite-orphan.drop.request-is-asynchronous"></a> That distinction is load-bearing — `RSI_DROP_KEY` is a
mutating operation, and without it the arrival of a perfectly normal
answer to a caller-less request would look like an unaccounted
mutation and tear the source down.

If the source is Down, LCS releases its in-kernel state and does **not**
queue a deferred drop. There is no deferred-drop
queue. <a id="cite-orphan.drop.down-source-queues-no-deferred-drop"></a> Recovering the
key record then falls to the source's own startup obligation, under
the Registry Source Interface specification in PSPK, to purge records
with no path entries before it becomes Active.

`close()` never reports orphan cleanup failure to userspace, and never
can: it returns 0 unconditionally. <a id="cite-orphan.drop.close-always-returns-zero"></a>

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

## A new key at the same path

A layer can create a new key where another layer's key already exists.
Each layer has its own path entry pointing at its own GUID, and
resolution decides which is visible.

Fds referencing the other GUID are completely isolated from it:
different identity, different data, different value entries. Nothing
observable connects two keys that merely share a name. <a id="cite-orphan.same-path.fds-to-the-other-guid-stay-isolated"></a>

---

# 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>)).

---

# Security

_Peios Kernel / Internals / LCS / Security_

> Find the Peios kernel articles about security.

Use these articles to understand security in the Peios kernel.

- [The Access Flow](</kernel/internals/lcs/security/the-access-flow.md>)
- [Access Rights](</kernel/internals/lcs/security/access-rights.md>)
- [Inheritance and Hive Roots](</kernel/internals/lcs/security/inheritance-and-hive-roots.md>)
- [Audit](</kernel/internals/lcs/security/audit.md>)

---

# The Access Flow

_Peios Kernel / Internals / LCS / Security_

> The registry's security model is KACS applied to keys — no traverse checking, symlink handling, and why an fd is a capability.

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

The registry's security model is KACS applied to keys. LCS defines no
access control mechanism of its own: the same AccessCheck, the same
Security Descriptors, the same tokens and SIDs that every other Peios
subsystem uses. What this section describes is how those primitives
attach to registry operations.

Every open follows the same five steps.

1. **Token capture.** LCS takes the calling thread's effective token —
   the impersonation token if one is set, otherwise the process primary
   token. This is the same capture KACS performs for every syscall. <a id="cite-access-flow.effective-token-capture"></a>

2. **Path resolution.** LCS walks the path through the layer stack,
   following symlinks. **No access check happens during the walk.**
   Intermediate keys are not evaluated; only the final key matters. <a id="cite-access-flow.no-check-during-walk"></a>

3. **AccessCheck.** LCS calls KACS AccessCheck with the captured token,
   the final key's Security Descriptor as returned by the source, and
   the desired access mask. Every requested right must be granted or
   the open fails with `EACCES`. There is no partial grant: the caller
   gets what it asked for or nothing. <a id="cite-access-flow.all-or-nothing-or-eacces"></a>

   `MAXIMUM_ALLOWED` is the exception, and the only way to ask for
   whatever is available. AccessCheck computes the full allowed set and
   that becomes the granted mask. <a id="cite-access-flow.maximum-allowed-grants-what-is-available"></a>

4. **The granted mask is stored on the fd.** It never changes. <a id="cite-access-flow.granted-mask-fixed-at-open"></a>

5. **Per-ioctl checks are bitmask tests.** Each ioctl has a required
   right; LCS tests the fd's granted mask against it and returns
   `EACCES` without contacting the source if it is absent. The
   Security Descriptor is not re-read and AccessCheck is not
   re-evaluated. <a id="cite-access-flow.per-ioctl-bitmask-test"></a>

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

## No traverse checking

LCS checks nothing on the way down. A process can open
`Machine\System\Services\Jellyfin` without holding any access to
`Machine\System\Services` or `Machine\System`.

This matches the Windows registry and is a deliberate difference from
filesystem path semantics, where every directory in a path is checked
for traverse. It means a key's Security Descriptor is the whole story
about who can reach it, and that an ancestor's descriptor confers no
protection on its descendants.

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

## Symlinks

Opening a symlink follows it, and AccessCheck runs on the **target**
key, not the link. `REG_OPEN_LINK` opens the link itself instead — but
only for the final path component. A symlink encountered part-way
through a path is followed regardless.

Creating a symlink is privileged: `KEY_CREATE_SUB_KEY` and
`KEY_CREATE_LINK` on the parent, plus either `SeTcbPrivilege` or
membership of Administrators ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)).

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

## Fds are capabilities

A key fd can be passed over a Unix socket with `SCM_RIGHTS`, and it
carries its granted mask with it. The recipient gets the access the
original opener was granted, whether or not its own token would have
passed AccessCheck. <a id="cite-access-flow.fd-passing-carries-granted-mask"></a>

This is explicit delegation and it is consistent with how fds work
everywhere else in Peios. Passing a `KEY_WRITE` fd hands over write
access.

Opening relative to a parent fd skips path parsing and AccessCheck for
the parent portion — the caller already proved its access when it
obtained the parent fd. This is the ordinary way to traverse a subtree. <a id="cite-access-flow.parent-fd-skips-check"></a>

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

## Changing a descriptor does not revoke a handle

A Security Descriptor change takes effect for future opens. An fd that
already exists keeps the mask it was granted at open, because that is
what semantic rule 5 says ([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>)). <a id="cite-access-flow.descriptor-change-does-not-revoke-fd"></a> The recourse for genuinely revoking
access is to restart the process holding the fd.

Descriptor changes are also not layer-qualified. They are direct
mutations on the key object, and deleting a layer does not undo one
([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>), rule 4).

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

## The second check nobody expects

Every layer-qualified mutation runs a **second** AccessCheck, against a
different object: the metadata key of the layer being written to. That
check is for `KEY_SET_VALUE` and it is in addition to the fd's granted
mask on the target key. Both must pass. [Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>) covers it.

---

# Access Rights

_Peios Kernel / Internals / LCS / Security_

> Registry rights at their Windows bit positions — the convenience masks, generic mapping, and validation of what a caller asks and a source returns.

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

Registry rights occupy the Windows bit positions, so a Security
Descriptor carrying registry ACEs is binary-compatible with one written
by Windows tooling. <a id="cite-right.windows-bit-positions"></a> That is a `registry.pol` and Samba requirement, not
an aesthetic choice.

The values are in [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>). In summary: six specific rights in bits 0–5
(`KEY_QUERY_VALUE`, `KEY_SET_VALUE`, `KEY_CREATE_SUB_KEY`,
`KEY_ENUMERATE_SUB_KEYS`, `KEY_NOTIFY`, `KEY_CREATE_LINK`), the four
standard rights `DELETE`, `READ_CONTROL`, `WRITE_DAC` and
`WRITE_OWNER`, and `ACCESS_SYSTEM_SECURITY` for the SACL, which is
itself gated by `SeSecurityPrivilege`.

There is no execute right on a key. <a id="cite-right.no-execute-right"></a>

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

## Convenience masks and generic mapping

`KEY_READ`, `KEY_WRITE` and `KEY_ALL_ACCESS` are concrete masks, not
generic bits — they are unions of the rights above and are usable
directly. <a id="cite-right.convenience-masks-are-concrete"></a>

Separately, LCS accepts the raw KACS generic bits `GENERIC_READ`,
`GENERIC_WRITE`, `GENERIC_EXECUTE` and `GENERIC_ALL` in a caller's
`desired_access` and in ACE masks in a Security Descriptor. Those are
mapped through the registry generic mapping before AccessCheck sees
them. <a id="cite-right.generic-bits-accepted-and-mapped"></a>

`GENERIC_READ` maps to `KEY_READ`, `GENERIC_WRITE` to
`KEY_WRITE`, `GENERIC_ALL` to `KEY_ALL_ACCESS`, and **`GENERIC_EXECUTE`
maps to zero**, because there is nothing to execute. <a id="cite-right.generic-mapping"></a>

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

## Validating what a caller asks for

`desired_access` is validated before path resolution or AccessCheck. <a id="cite-right.desired-access-validated-first"></a>

- Zero is `EINVAL`. A caller must ask for something. <a id="cite-right.zero-desired-access-is-einval"></a>
- Any bit outside the valid caller mask is `EINVAL`. <a id="cite-right.unknown-desired-access-bit-is-einval"></a>
- `MAXIMUM_ALLOWED` may appear alone or combined with anything else. <a id="cite-right.maximum-allowed-may-combine"></a>
- `SYNCHRONIZE` (`0x00100000`) is not a registry right, so it is an
  unknown bit and fails `EINVAL`. <a id="cite-right.synchronize-is-not-a-registry-right"></a>

The valid caller mask is a single constant, `REG_VALID_DESIRED_ACCESS_MASK`
([LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>)): the six specific rights, the four standard rights,
`ACCESS_SYSTEM_SECURITY`, `MAXIMUM_ALLOWED` and the four generic bits. <a id="cite-right.valid-desired-access-mask-contents"></a>

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

## Validating what a source returns

Source-supplied Security Descriptors are validated too, because a
source is trusted for its data but not for its arithmetic ([Validation](</kernel/internals/lcs/sources/validation.md#trm-5-8-4>)).

An ACE mask may contain concrete registry rights and raw generic bits.
It **may not** contain `MAXIMUM_ALLOWED` — that is a request, not a
grant, and it is meaningless in an ACE. <a id="cite-right.ace-mask-rejects-maximum-allowed"></a>

After generic mapping, an ACE
mask must be a subset of the concrete registry rights plus
`ACCESS_SYSTEM_SECURITY`. <a id="cite-right.ace-mask-subset-after-mapping"></a>

A descriptor that breaks either rule is malformed source data: the
operation fails closed with `EIO` and an
`lcs.source.response.rejected` audit event is emitted ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-right.malformed-descriptor-is-eio"></a>

Two further constants, `REG_VALID_MAPPED_ACCESS_MASK` and
`REG_VALID_ACE_ACCESS_MASK`, express those two bounds.

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

## Which right each operation needs

| Operation | Required |
|---|---|
| `REG_IOC_QUERY_VALUE`, `QUERY_VALUES_BATCH`, `ENUM_VALUES` | `KEY_QUERY_VALUE` <a id="cite-right.query-value"></a> |
| `REG_IOC_SET_VALUE`, `DELETE_VALUE`, `BLANKET_TOMBSTONE`, `FLUSH` | `KEY_SET_VALUE` <a id="cite-right.set-value"></a> |
| `REG_IOC_ENUM_SUBKEYS` | `KEY_ENUMERATE_SUB_KEYS` <a id="cite-right.enum-subkeys"></a> |
| `REG_IOC_QUERY_KEY_INFO` | `READ_CONTROL` <a id="cite-right.query-key-info"></a> |
| `REG_IOC_DELETE_KEY`, `HIDE_KEY` | `DELETE` <a id="cite-right.delete-key"></a> |
| `REG_IOC_NOTIFY` | `KEY_NOTIFY` <a id="cite-right.notify"></a> |
| `REG_IOC_GET_SECURITY` | `READ_CONTROL` for owner, group, DACL and label; `ACCESS_SYSTEM_SECURITY` for the SACL <a id="cite-right.get-security"></a> |
| `REG_IOC_SET_SECURITY` | `WRITE_OWNER` for owner, group or label; `WRITE_DAC` for the DACL; `ACCESS_SYSTEM_SECURITY` for the SACL; raising a label above the caller additionally requires enabled `SeRelabelPrivilege` <a id="cite-right.set-security"></a> |
| `REG_IOC_BACKUP` | `SeBackupPrivilege`, no per-key check |
| `REG_IOC_RESTORE` | `SeRestorePrivilege`, no per-key check |
| creating a key | `KEY_CREATE_SUB_KEY` on the parent <a id="cite-right.create-key"></a> |
| creating a symlink key | `KEY_CREATE_SUB_KEY` and `KEY_CREATE_LINK` on the parent, plus `SeTcbPrivilege` or Administrators |

Where a `REG_IOC_SET_SECURITY` or `GET_SECURITY` request names several
components, every right those components imply must be present before
the source is contacted. <a id="cite-right.security-info-needs-every-implied-right"></a>

`REG_IOC_FLUSH` requires `KEY_SET_VALUE` because a flush is only
meaningful to a caller that wrote something and wants it durable.
Requiring a write right stops an unprivileged reader using flush as a
disk-I/O amplifier.

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

## Enumeration exposes names, not contents

`REG_IOC_ENUM_SUBKEYS` performs no per-child access check. Every
visible child is returned, whatever the caller's access to it. The
caller learns names, and must open each child separately — with a real
AccessCheck — to read anything. <a id="cite-right.enum-subkeys-no-per-child-check"></a>

Subtree watches work the same way: a watcher is told a descendant was
created without a check on that descendant. <a id="cite-right.subtree-watch-no-per-descendant-check"></a> Structure visibility is
deliberately weaker than content visibility, matching
`RegNotifyChangeKeyValue` and `RegEnumKeyEx`.

---

# Inheritance and Hive Roots

_Peios Kernel / Internals / LCS / Security_

> A new key's descriptor is computed from its parent by the KACS inheritance algorithm — plus hive roots and reading or writing a descriptor.

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

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

## Inheritance at creation

When `reg_create_key` creates a key, its initial Security Descriptor is
computed from the parent's by the KACS inheritance algorithm. LCS
supplies the parent descriptor, the creating token, the registry
generic mapping and the valid-mask bound, and hands the result to the
source to persist. It implements no inheritance logic of its own. <a id="cite-inherit.kacs-computes-lcs-persists"></a>

Three things about registry inheritance are worth stating.

**It is static.** The computation happens once, at creation. A later
change to the parent's descriptor does not propagate to children that
already exist. <a id="cite-inherit.static-no-repropagation"></a> Re-propagating is an explicit administrative action — a
client-side tree walk — not a kernel operation, and there is no code
anywhere in LCS that walks a tree to re-propagate.

**Only `CONTAINER_INHERIT_ACE` matters.** Every registry object is a
container: keys hold subkeys and values. Values are not independent
security objects and have no descriptors of their own; they inherit
their key's access control. <a id="cite-inherit.values-have-no-descriptor-of-their-own"></a>

`OBJECT_INHERIT_ACE` is never used to
select an ACE for inheritance. <a id="cite-inherit.object-inherit-ace-never-selects"></a> The child copy clears `OBJECT_INHERIT_ACE`,
`CONTAINER_INHERIT_ACE` and `NO_PROPAGATE_INHERIT_ACE` when
`NO_PROPAGATE_INHERIT_ACE` applies. <a id="cite-inherit.no-propagate-clears-object-inherit"></a>

**A parent with no inheritable ACEs falls back to the creating token's
default DACL.** <a id="cite-inherit.no-inheritable-aces-uses-token-default-dacl"></a>

That fallback covers the DACL only; there is no default
SACL. <a id="cite-inherit.no-default-sacl"></a>

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

### Creator SIDs and generic rights survive to the next generation

An inheritable ACE naming `CREATOR OWNER` or `CREATOR GROUP`, or carrying
generic rights, is resolved for each new key. When it also propagates to
further subkeys, the child receives two ACEs:

- An effective copy with the child's owner/group substituted and generic
  rights mapped to registry rights. It has `INHERITED_ACE` and no propagation
  flags.
- An inherit-only copy retaining the original SID and generic mask, with
  `INHERITED_ACE` and its propagation flags. This copy resolves afresh when
  the next subkey is created.

This applies to both DACL and SACL entries. An ordinary concrete ACE remains
one copy. `NO_PROPAGATE_INHERIT_ACE` ends the rule at the immediate child,
so it receives only the effective copy. Existing stored descriptors are not
rewritten by upgrading the kernel; an explicit propagation operation is
needed to repair an already-created subtree.

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

## Hive roots

A hive root has no parent, so it is the top of every inheritance chain
below it and cannot inherit anything itself. <a id="cite-inherit.hive-root-inherits-nothing"></a> Its descriptor is created
by the **source**, on first boot, and LCS enforces whatever the source
stored. <a id="cite-inherit.hive-root-descriptor-comes-from-the-source"></a>

LCS holds no template. There are no hardcoded SIDs, no default hive
root descriptors, and no code that would construct one — searching for
them finds nothing. The defaults that follow are what loregd writes;
they are conventions of the source, not properties of the kernel.

**`Machine\`:** <a id="cite-inherit.machine-root-default-descriptor"></a>

| Principal | Rights | Inheritance |
|---|---|---|
| SYSTEM | `KEY_ALL_ACCESS` | Container-inherit |
| Administrators | `KEY_ALL_ACCESS` | Container-inherit |
| Authenticated Users | `KEY_READ` | Container-inherit |

**`Users\<SID>\`:** <a id="cite-inherit.user-root-default-descriptor"></a>

| Principal | Rights | Inheritance |
|---|---|---|
| the user's SID | `KEY_ALL_ACCESS` | Container-inherit |
| SYSTEM | `KEY_ALL_ACCESS` | Container-inherit |
| Administrators | `KEY_ALL_ACCESS` | Container-inherit |

These mirror Windows HKLM and HKU. A subsystem needing something
tighter — `Machine\Security\`, say — sets an explicit descriptor on its
own subtree root at creation, overriding what it inherited.

Because there is no traverse checking ([The Access Flow](</kernel/internals/lcs/security/the-access-flow.md#trm-5-4-1>)), a restrictive
descriptor high in the tree protects only the key it is on. Protection
of a subtree comes from the descriptors its keys inherited at creation,
which is exactly why an administrator changing a parent's descriptor
and expecting the subtree to follow will be disappointed.

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

## Reading and writing descriptors

`REG_IOC_GET_SECURITY` and `REG_IOC_SET_SECURITY` take a
`security_info` bitmask naming which components to act on: owner,
group, DACL, SACL, or mandatory integrity label (`LABEL_SECURITY_INFORMATION`). <a id="cite-inherit.security-info-selects-components"></a>

Zero is `EINVAL`, and so is any unknown flag; both
are rejected before the source is contacted, before transaction
enlistment and before any mutation. <a id="cite-inherit.security-info-zero-or-unknown-is-einval"></a>

The rights required are computed from every component named. Reading
owner, group, the DACL or the label needs `READ_CONTROL`; reading the SACL needs
`ACCESS_SYSTEM_SECURITY`. Setting owner **or group** needs
`WRITE_OWNER`, as does setting the label; setting the DACL needs `WRITE_DAC`; setting the SACL
needs `ACCESS_SYSTEM_SECURITY`. A request naming several components
must hold all the corresponding rights.

A set is a merge, not a replacement. LCS reads only the components
`security_info` names from the supplied self-relative descriptor and
preserves the existing ones. <a id="cite-inherit.set-security-is-a-merge"></a>

Component selection includes its control flags even when the component
has no bytes. A null ACL remains `PRESENT` clear, but its defaulted,
inheritance and protection flags survive a query or an update to another
component. Replacing a selected DACL or SACL takes that ACL's flags from
the input descriptor, including for a null ACL; unselected component
flags are preserved. An empty ACL remains present with zero ACEs and is
not converted to null. The same preservation rule applies to a defaulted
null group. <a id="cite-inherit.null-acl-control-flags"></a>

`LABEL_SECURITY_INFORMATION` reads only the first effective mandatory-label
ACE from the SACL, omitting inherit-only labels and every non-label ACE.
If there is no effective label, the returned subset has no SACL. Reading
this subset needs `READ_CONTROL`; writing it needs `WRITE_OWNER`. Neither
operation needs `ACCESS_SYSTEM_SECURITY` or `SeSecurityPrivilege`.
<a id="cite-inherit.label-access-and-projection"></a>

A label update removes the existing mandatory-label ACEs and inserts the
supplied label before the remaining SACL entries. An input descriptor
with no SACL clears the explicit label. Non-label SACL entries, SACL
inheritance and protection flags, and all unselected descriptor components
are preserved, including flags on a null DACL. Clearing the last SACL
entry clears `SE_SACL_PRESENT` while retaining the other SACL flags.
<a id="cite-inherit.label-merge-preserves-other-security"></a>

For a label-only subset, a supplied SACL must contain exactly one
mandatory-label ACE with an `S-1-16-<level>` SID and without
`INHERIT_ONLY_ACE`; an empty ACL, an audit ACE, or multiple labels is
`EINVAL`. `SACL_SECURITY_INFORMATION` and `LABEL_SECURITY_INFORMATION`
cannot be combined. These input errors are rejected before source contact
or transaction enlistment. <a id="cite-inherit.label-input-validation"></a>

An explicit label above the current caller's integrity level requires
enabled `SeRelabelPrivilege`, checked before source contact or transaction
enlistment; otherwise the update fails with `EACCES`. Labels at or below
the caller's level do not require that privilege. The same rule applies
to an explicit label inside a whole-SACL write: `SeSecurityPrivilege`
does not substitute for `SeRelabelPrivilege`. Existing fd rights remain
cached, but this privilege check uses the caller performing the update.
<a id="cite-inherit.label-level-constraint"></a>

The result must still have an owner; a
merge that would leave the descriptor ownerless is `EINVAL`. <a id="cite-inherit.merge-must-leave-an-owner"></a>

A null
group SID stays valid. <a id="cite-inherit.null-group-sid-is-valid"></a>

Enlisting a descriptor change in a transaction gives it atomicity with
the rest of the transaction's operations. It does not make it
layer-qualified: the change is still a direct mutation on the key, is
still not reverted by deleting a layer, and is simply not applied at
all if the transaction aborts. <a id="cite-inherit.descriptor-change-in-a-transaction"></a>

---

# Audit

_Peios Kernel / Internals / LCS / Security_

> The fifteen audit events LCS emits, which are unconditional, how registry writes are audited through a key handle's alarm mask, and what happens when emission itself fails.

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

LCS emits audit events through KMES. Fifteen events exist. <a id="cite-lcs-audit.events-through-kmes"></a>

| Event | Emitted when |
|---|---|
| `lcs.audit.key.opened` | A key open matched a SACL audit ACE. <a id="cite-lcs-audit.key-open.on-sacl-match"></a> |
| `lcs.audit.value.set` | A value write through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.value.deleted` | A value delete through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.key.tombstoned` | A blanket tombstone set or cleared through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.key.deleted` | A key deleted through a handle whose audit mask covers `DELETE`. |
| `lcs.audit.key.hidden` | A key hidden through a handle whose audit mask covers `DELETE`. |
| `lcs.audit.key.created` | A key create that made a key matched a SACL audit ACE on the parent. |
| `lcs.audit.key.descriptor.changed` | A descriptor change included the SACL, or its right is covered by the handle's audit mask. |
| `lcs.audit.transaction.committed` | A transaction that staged an audited write ended. |
| `lcs.audit.backup.started` | After admission checks and before `REG_IOC_BACKUP` requests its read-only snapshot or reads any subtree data. <a id="cite-lcs-audit.backup-start.before-any-read"></a> |
| `lcs.audit.backup.ended` | After a backup completes or fails after starting. <a id="cite-lcs-audit.backup-complete.after-finish-or-failure"></a> |
| `lcs.audit.restore.started` | Before `REG_IOC_RESTORE` modifies any source state. <a id="cite-lcs-audit.restore-start.before-any-mutation"></a> |
| `lcs.audit.restore.ended` | After a restore completes or fails after starting. <a id="cite-lcs-audit.restore-complete.after-finish-or-failure"></a> |
| `lcs.source.response.rejected` | LCS rejected malformed source data. <a id="cite-lcs-audit.validation-failure.on-malformed-source-data"></a> |
| `lcs.config.value.rejected` | LCS rejected an invalid self-configuration value. <a id="cite-lcs-audit.self-config-invalid.on-invalid-value"></a> |

A registry open that a privilege contributed to is also recorded, as KACS's
`kacs.audit.privilege.used`; see [Privilege use on opens](#privilege-use-on-opens).

Backup and restore are audited **unconditionally**, whatever the SACL
on the target key says. <a id="cite-lcs-audit.backup-and-restore-unconditional"></a> They are privilege-gated bulk operations that
bypass per-key access checks entirely, so the audit trail is the only
record that they happened.

Every payload is a single MessagePack map with string keys. <a id="cite-lcs-audit.payload-is-a-msgpack-map"></a>
Each field path is written as nested maps, one per segment, so
`object.key.guid` is `{object: {key: {guid: …}}}`. A value LCS does not
have is left out rather than written as nil, and every map counts only
the keys actually written (PGSS [Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)).

The key GUID, `object.key.guid`, is a 16-byte binary value, and the
caller's SID is a binary KACS encoding. The token and process GUIDs
are not payload fields at all: they ride in the KMES event header, so
the payload never repeats them. <a id="cite-lcs-audit.payload-guid-and-sid-encoding"></a>

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

## The caller summary

Every event except `lcs.source.response.rejected` and
`lcs.config.value.rejected` describes the effective token used for the
operation under `subject.token`. It has six fields and no more: `sid`,
`integrity`, `id` (the token's LUID), `auth-id` (its logon session's
LUID), `type` (`primary` or `impersonation`) and `impersonation`, the
impersonation level. <a id="cite-lcs-audit.caller-summary-nine-fields"></a>

The bound is deliberate. Group lists, privilege arrays, claims and
default DACLs are unbounded and are never included. The summary carries
enough to correlate an event with a caller, and nothing that could make
one event arbitrarily large. `lcs.source.response.rejected` and
`lcs.config.value.rejected` carry no caller: neither is a principal
acting.

A primary token reports an impersonation
level of 0. <a id="cite-lcs-audit.primary-token-impersonation-level-zero"></a> An Anonymous impersonation token also
reports 0, which is why `subject.token.type` is recorded beside it.

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

## Key opens

`lcs.audit.key.opened` carries the caller summary, then
`object.kind` (always `key`, which names the table the masks decode
against), `object.key.guid`, the requested and granted masks as
`access.requested` and `access.granted`, `outcome.success` (`true`
when the open was allowed), and `trigger.sacl-match` — bit 0 for a
success-audit match, bit 1 for a failure-audit match, no other
bits. <a id="cite-lcs-audit.key-open.payload-fields"></a>

`access.granted` is forced to zero on a denial, and that is enforced
rather than merely intended: a denied event carrying a non-zero granted
mask is rejected as a malformed payload. <a id="cite-lcs-audit.key-open.denied-event-has-zero-granted"></a>

`access.requested` is the mask
after registry generic mapping, with `MAXIMUM_ALLOWED` re-added if the
caller asked for it. <a id="cite-lcs-audit.key-open.requested-access-is-post-mapping"></a>

SACL evaluation follows the KACS AccessCheck algorithm — the SACL is
evaluated alongside the DACL, not separately. <a id="cite-lcs-audit.sacl-evaluated-with-the-dacl"></a>

Reading or modifying a
SACL requires `ACCESS_SYSTEM_SECURITY`, which is itself gated by
`SeSecurityPrivilege`. <a id="cite-lcs-audit.sacl-access-gated-by-sesecurityprivilege"></a>

A request of `MAXIMUM_ALLOWED` **alone** maps to a desired mask of zero,
so AccessCheck's SACL walk matches each audit ACE against the *granted*
mask instead. <a id="cite-lcs-audit.key-open.maximum-allowed-matches-granted-mask"></a> An audit ACE says "audit when someone gets this right",
and with `MAXIMUM_ALLOWED` they did get it.

Such an open therefore
always audits as a success, which is correct: `MAXIMUM_ALLOWED` returns
whatever is available and never fails, so a failure ACE has nothing to
record. <a id="cite-lcs-audit.key-open.maximum-allowed-always-audits-success"></a>

An ACE naming a right the caller did not receive still does not
match. <a id="cite-lcs-audit.key-open.ace-for-ungranted-right-does-not-match"></a>

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

## Registry writes

Writes are audited through the key handle, as file operations are
through a file handle. When a key is opened, the access check evaluates
the key's `SYSTEM_ALARM*` ACEs against the caller, and the union of the
masks of the ones that match becomes the handle's **continuous-audit
mask**. <a id="cite-lcs-audit.write.alarm-mask-cached-at-open"></a> Success and failure
`SYSTEM_AUDIT` ACEs do not contribute; they govern the open itself. This
is the continuous auditing of [Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>) with LCS as the enforcement point,
except in two respects: LCS writes records named for the operation
rather than `kacs.audit.handle.used`, and a record it cannot write does
not fail the operation (see below).

The mask is fixed for the life of the handle. A later change to the
key's SACL neither adds to it nor takes from it, so a handle that removes
the alarm ACE is still audited for the change it makes, and handles
opened before an alarm ACE was added are not. <a id="cite-lcs-audit.write.mask-fixed-for-handle-life"></a>

A write through the handle is recorded when the right it needs overlaps
the mask, and not otherwise. <a id="cite-lcs-audit.write.recorded-when-right-overlaps-mask"></a>
The right is the one the handle's own gate checks:

| Event | Operation | Right |
|---|---|---|
| `lcs.audit.value.set` | `REG_IOC_SET_VALUE` | `KEY_SET_VALUE` |
| `lcs.audit.value.deleted` | `REG_IOC_DELETE_VALUE` | `KEY_SET_VALUE` |
| `lcs.audit.key.tombstoned` | `REG_IOC_BLANKET_TOMBSTONE` | `KEY_SET_VALUE` |
| `lcs.audit.key.deleted` | `REG_IOC_DELETE_KEY` | `DELETE` |
| `lcs.audit.key.hidden` | `REG_IOC_HIDE_KEY` | `DELETE` |

<a id="cite-lcs-audit.write.rights-per-event"></a>

A write that fails is recorded too, with `outcome.success` false and
`outcome.errno` the negative errno the caller received. That includes a
write the handle's own gate refuses because the handle lacks the right:
the mask comes from the SACL, not the grant, so it can cover rights the
handle was not given. <a id="cite-lcs-audit.write.failures-recorded"></a>

Every write record carries the caller summary; `object.kind` (`key`),
`object.key.guid` and `object.key.path`, the handle's key and its
resolved path; `object.key.layer.name`, the layer written; the masks
`access.requested` (the right above), `access.granted` (the handle's
grant), `access.matched` and `access.audit-mask`; `transaction.id` when
the write was staged in a transaction; and `outcome.success`, with
`outcome.errno` on a failure. A failure also carries `request.timed-out`.
Value records add `object.key.value.name`; a value write adds the value's
type and length and a digest of its data, and `mutation.sequence`, with
`mutation.sequence-expected` on a compare-and-swap; a tombstone change
adds `operation.name` (`set` or `clear`); a hide adds `mutation.sequence`.
A field the operation had not reached when it failed is left out. <a id="cite-lcs-audit.write.payload-fields"></a>

A value's data is never recorded. In its place a record carries the data's
type, its length and its SHA-256 digest, so two records can be compared
without either holding the data. Every digest LCS records, of a value or
of a security descriptor, is SHA-256. <a id="cite-lcs-audit.write.data-recorded-as-sha256-digest"></a>

A value write outside a transaction also records the value it replaced, as
`object.key.value.type-previous`, `.length-previous` and
`.digest-previous`: the effective value before the write, across every
layer. A value delete records the value it removed the same way. <a id="cite-lcs-audit.write.previous-value-recorded"></a>

A write whose source does not answer before the request timeout fails
with `ETIMEDOUT`, and its record carries `request.timed-out` true. The
source is not told to cancel, so the change may still land; for a value
write or descriptor change outside a transaction, LCS also applies the
write's kernel-side effects when the late reply arrives, and nothing
records who made the write then. Read a timed-out record as "may have
been applied later". <a id="cite-lcs-audit.write.timed-out-may-apply-later"></a>

A write made in a transaction is recorded when it is staged, with
`transaction.id`. Its `outcome.success` then says the source accepted it
into the transaction, not that it took effect. <a id="cite-lcs-audit.write.transacted-recorded-when-staged"></a>

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

### Transaction ends

A transaction that staged at least one recorded write — a write or a key
creation whose record was emitted — writes one
`lcs.audit.transaction.committed` when it ends, and only one: at a
`REG_IOC_COMMIT` that leaves it committed or otherwise finished, at its
timeout, or when its fd is closed without a commit. A commit that fails
and leaves the transaction open writes nothing yet. <a id="cite-lcs-audit.txn-committed.once-per-recorded-transaction"></a>

It carries the caller summary, `transaction.id` and `transaction.state`,
the state it ended in, and `outcome.success`, true only for `committed`.
A failure adds `transaction.commit-outstanding` and `outcome.reason`:
`aborted` (closed without a commit, or a layer it wrote was deleted),
`timed-out` or `source-error`; and `outcome.errno` when a
`REG_IOC_COMMIT` call failed. <a id="cite-lcs-audit.txn-committed.payload-fields"></a>

On `REG_IOC_COMMIT` the subject is the caller who committed, not the one
who staged the writes. A transaction that ended by timeout or by its fd
closing has nobody acting, and names the subject that staged its first
recorded write. The timer that ends a transaction runs in softirq context,
which cannot build a record; the record is written from the work item
that aborts the transaction at the source. <a id="cite-lcs-audit.txn-committed.subject"></a>

A commit whose reply does not arrive in time reports `timed-out` with
`transaction.commit-outstanding` true: the source may have committed it
before the reply was lost.

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

## Key creation

`lcs.audit.key.created` records a key a create made. Creating a key
checks only `KEY_CREATE_SUB_KEY` on its parent, so the parent's SACL
decides, by the rule that decides `lcs.audit.key.opened`: a success audit
ACE on the parent that matches the caller. <a id="cite-lcs-audit.key-created.on-parent-sacl-match"></a>

Only a key that was made is recorded. A create that found the key already
present and opened it instead writes nothing here. The record is written
once the key exists, or is staged in a transaction, so a create whose
handle then fails to reach the caller is still recorded. <a id="cite-lcs-audit.key-created.only-made-keys"></a>

It carries the caller summary; `object.kind`; the new key's
`object.key.guid`, `object.key.path` and `object.key.layer.name`;
`object.key.created` (true), `object.key.volatile`,
`object.key.volatile-requested` and `object.key.symlink`; the new key's
descriptor as `object.sd.length` and `object.sd.owner`; `access.requested`
(`KEY_CREATE_SUB_KEY`) and `access.granted`, from the parent check;
`transaction.id` when staged; and `outcome.success`. <a id="cite-lcs-audit.key-created.payload-fields"></a>

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

## Descriptor changes

`lcs.audit.key.descriptor.changed` records `REG_IOC_SET_SECURITY` through
a key handle.

A change that includes the SACL is recorded whatever the handle's mask
says. It is recorded once the handle's own gate has admitted it, which
takes `ACCESS_SYSTEM_SECURITY`: a handle without that right is refused
first, and asking for a SACL change writes no record. <a id="cite-lcs-audit.descriptor-changed.sacl-change-always-recorded"></a>

Any other change is recorded when the right it needs — `WRITE_OWNER` for
the owner or group, `WRITE_DAC` for the DACL — overlaps the handle's
mask, and then failures are recorded as writes' are. <a id="cite-lcs-audit.descriptor-changed.other-changes-follow-mask"></a>

The record carries what a write record does, without a layer, and the
descriptors: `object.sd.components`, the `security_info` bits asked for;
and for the descriptor written and the one it replaced, `object.sd.length`
and `object.sd.length-previous`, their SHA-256 digests `object.sd.digest`
and `object.sd.digest-previous`, and their owners `object.sd.owner` and
`object.sd.owner-previous`. `access.requested` is every right the change
needs, and `access.matched` is zero when only the SACL made the record
exist. <a id="cite-lcs-audit.descriptor-changed.payload-fields"></a>

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

## Privilege use on opens

A registry open whose access check used a privilege — `SeSecurityPrivilege`
for `ACCESS_SYSTEM_SECURITY`, `SeTakeOwnershipPrivilege` for
`WRITE_OWNER` — writes KACS's `kacs.audit.privilege.used` when the
caller's token audit policy asks for privilege use, in the shape KACS
uses for its own access checks, with `object.kind` `key`. The key's
identity is not carried. The checks LCS makes for layer writes and on a
create's parent record none. <a id="cite-lcs-audit.open.privilege-use-recorded"></a>

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

## Backup and restore

`lcs.audit.backup.started` and `lcs.audit.restore.started` carry the
caller summary, `object.key.guid` for the subtree root, and
`operation.fd`, the descriptor the stream is written to or read from.

`lcs.audit.backup.ended` and `lcs.audit.restore.ended` carry the
caller summary, `object.key.guid` and `outcome.success`. When the
operation failed they also carry `outcome.errno`, the error as a
negative errno; on success it is absent.

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

## Source validation failures

`lcs.source.response.rejected` carries the source slot as
`source.rsi.slot` and then, where each is known, the hive name as
`source.rsi.hive`, the RSI request id and operation code as
`request.id` and `request.op-code`, and the key GUID as
`object.key.guid`. <a id="cite-lcs-audit.validation-failure.payload-fields"></a> `outcome.reason` names what was wrong.
There are twelve:

`malformed-security-descriptor`, `malformed-layer-name`,
`unknown-rsi-status-code`, `future-sequence-number`,
`duplicate-winning-sequence-tie`,
`malformed-layer-metadata-security-descriptor`,
`malformed-key-name`, `malformed-value-name`,
`malformed-response-payload`, `malformed-key-metadata`,
`malformed-value-payload`, `malformed-delete-layer-orphan-list`. <a id="cite-lcs-audit.validation-failure.twelve-classes"></a>

The three name classes are field-specific: layer-name fields, key
component or child-name fields, and value-name fields respectively. <a id="cite-lcs-audit.validation-failure.name-classes"></a>

The structural classes cover a response whose operation-specific
payload has the wrong shape or trailing bytes; a lookup or
enumeration whose metadata block is incomplete, duplicated,
unreferenced or nil; a value payload with an invalid type, a
tombstone/data mismatch or oversized data; and an invalid orphan GUID
array from `RSI_DELETE_LAYER`. <a id="cite-lcs-audit.validation-failure.structural-classes"></a>

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

## Configuration

`lcs.config.value.rejected` has the same shape as KMES's
`kmes.config.value.rejected`, with every field under one `config`
map. It carries the offending parameter's key and name as
`config.key.path` and `config.name`; the expected type and numeric
range as `config.expected.type`, `config.expected.min` and
`config.expected.max`; what was actually received as
`config.received.kind` — one of `missing`, `wrong-type` or
`out-of-range` — with `config.received.type` for a value of the wrong
type or `config.received.value` for one out of range; and, as
`config.value`, the value LCS retained instead. <a id="cite-lcs-audit.self-config.payload-fields"></a>

Because `missing` counts as invalid, a first boot before seed restore
emits one of these per parameter on each refresh: nineteen events
against an empty `Registry\` key. <a id="cite-lcs-audit.self-config.missing-counts-as-invalid"></a> That is correct and expected, but it
is a noticeable share of the boot audit stream.

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

## What happens when emission fails

The policy differs per event, and the differences are the point.

- **`lcs.audit.key.opened`.** If LCS cannot *construct* a valid payload —
  corrupt internal state, allocation failure, anything on the LCS side
  — the open fails with `EIO` and no key fd is published. <a id="cite-lcs-audit.emit-failure.key-open-construct-failure-fails-the-open"></a> If the
  payload is valid but KMES cannot *retain* the event — unavailable,
  ring drops, capacity pressure, no consumer — the access decision and
  the fd publication are unaffected. Loss accounting is KMES's problem. <a id="cite-lcs-audit.emit-failure.key-open-retain-failure-is-harmless"></a>
- **`lcs.audit.backup.started`, `lcs.audit.restore.started`.** Emission
  failure returns `EIO` and the operation does not start. Nothing is
  read and nothing is written. <a id="cite-lcs-audit.emit-failure.start-events-block-the-operation"></a>
- **`lcs.audit.backup.ended`, `lcs.audit.restore.ended`.** The operation
  has already finished. Emission is attempted; failure does not change
  the result. <a id="cite-lcs-audit.emit-failure.complete-events-are-best-effort"></a>
- **`lcs.source.response.rejected`.** The triggering operation is
  already failing with `EIO`. Emission is attempted; failure does not
  change that. <a id="cite-lcs-audit.emit-failure.validation-failure-is-best-effort"></a>
- **`lcs.config.value.rejected`.** The invalid value has already been
  ignored and the previous known-good value retained. Emission is
  attempted; failure leaves the retained configuration in force. <a id="cite-lcs-audit.emit-failure.self-config-is-best-effort"></a>
- **The write, creation, descriptor-change and transaction records.**
  Each is written after the source has applied or refused the operation,
  or after the transaction's state is final. Emission is attempted; a
  record that cannot be built or retained leaves the caller's result as
  it was. <a id="cite-lcs-audit.emit-failure.write-records-preserve-result"></a>
  These records fire no `lcs:lcs_audit_emit` or `lcs:lcs_audit_emit_failed`
  tracepoint; the tracepoints' event-type codes cover the other seven.

The rule underneath them all: an audit failure blocks an operation only
where the audit record is the *point* of the operation being permitted.
A privileged bulk export whose start could not be recorded does not
happen. A key open whose decision could not be recorded does not
happen. Everything downstream of an already-determined outcome records
what it can.

LCS constructs the payload and attempts to enqueue it before
continuing past the audit point. It never waits for a userspace
consumer to observe or retain the event. <a id="cite-lcs-audit.enqueue-without-awaiting-a-consumer"></a>

---

# Watches

_Peios Kernel / Internals / LCS / Watches_

> Find the Peios kernel articles about watches.

Use these articles to understand watches in the Peios kernel.

- [The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md>)
- [Event Records](</kernel/internals/lcs/watches/event-records.md>)
- [Dispatch](</kernel/internals/lcs/watches/dispatch.md>)
- [Queues and Overflow](</kernel/internals/lcs/watches/queues-and-overflow.md>)

---

# The Watch Model

_Peios Kernel / Internals / LCS / Watches_

> A persistent subscription to changes on an open key, following inotify rather than the Windows model — what it observes, its event types and filters.

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

A watch is a persistent subscription to changes on an open key. It
follows the inotify model rather than the Windows one: once armed, it
stays armed until the fd closes, and events keep arriving without
re-registration. <a id="cite-watch.model.persistent-until-fd-close"></a>
`RegNotifyChangeKeyValue` is single-shot, and the window between
receiving a notification and re-registering is a window in which
changes are missed; a persistent watch has no such window.

A watch is armed by `REG_IOC_NOTIFY` on a key fd, which requires
`KEY_NOTIFY` in the fd's granted mask. Arming takes a filter — a bitmask
of event categories — and a subtree flag. After arming, the fd is
pollable: `EPOLLIN` reports pending events, and `read()` returns
structured records. <a id="cite-watch.model.armed-fd-is-pollable"></a>

Each fd carries at most one watch. <a id="cite-watch.model.one-watch-per-fd"></a>

Arming an already-armed fd replaces the filter and the subtree setting
and leaves queued events in place. <a id="cite-watch.model.rearm-replaces-filter-and-keeps-queue"></a>

Arming with a filter of zero disarms: the watch is removed and every
pending event is discarded. <a id="cite-watch.model.zero-filter-disarms-and-discards"></a>
To watch one key under two different filters, open it twice.

Arming a watch on a key that is already orphaned fails with `ENOENT`. A
watch armed before the key was orphaned stays armed ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)).

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

## What a watch observes

Events describe changes to **effective** state, not to layer mechanics.
A watcher sees that a value changed; it does not see which layer won,
or that a layer was deleted. <a id="cite-watch.model.reports-effective-state-not-layer-mechanics"></a>
Removing a hiding entry that was concealing a lower-precedence key
produces `SUBKEY_CREATED`. Removing a whole layer is recovery dispatch
rather than a diff, and reaches a watcher as `OVERFLOW` ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). The layer
system is not visible through a watch at all.

The events are computed by diffing the effective state before the
mutation against the effective state after it, which is what makes this
true by construction rather than by careful case analysis. <a id="cite-watch.model.computed-by-diffing-effective-state"></a>

A change that replaces the key at a child name with a different key
object — different GUID, same name — produces `SUBKEY_DELETED` followed
by `SUBKEY_CREATED`, because that is what the diff says happened. <a id="cite-watch.model.key-replacement-is-delete-then-create"></a>

Only committed state is observable. Operations inside an uncommitted
transaction produce nothing; the whole set fires at commit ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

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

## Event types

| Event | Code | Name field | Meaning |
|---|---|---|---|
| `REG_WATCH_VALUE_SET` | 1 | value name | The effective value at this name changed or appeared. <a id="cite-watch.model.event-value-set"></a> |
| `REG_WATCH_VALUE_DELETED` | 2 | value name | The effective value at this name disappeared. <a id="cite-watch.model.event-value-deleted"></a> |
| `REG_WATCH_SUBKEY_CREATED` | 3 | subkey name | A child key became visible. <a id="cite-watch.model.event-subkey-created"></a> |
| `REG_WATCH_SUBKEY_DELETED` | 4 | subkey name | A child key became invisible. <a id="cite-watch.model.event-subkey-deleted"></a> |
| `REG_WATCH_SD_CHANGED` | 5 | empty | The watched key's Security Descriptor was modified. <a id="cite-watch.model.event-sd-changed"></a> |
| `REG_WATCH_KEY_DELETED` | 6 | empty | The watched key itself became invisible. <a id="cite-watch.model.event-key-deleted"></a> |
| `REG_WATCH_OVERFLOW` | 7 | empty | Events were dropped; re-read to recover. <a id="cite-watch.model.event-overflow"></a> |

`VALUE_SET` fires when a value is written, and when a tombstone or
blanket tombstone is removed and a lower-precedence value surfaces. <a id="cite-watch.model.value-set-fires-on-write-unmask-or-layer-deletion"></a>

`VALUE_DELETED` fires when the last entry for a name goes away, when a
tombstone masks every entry, and when a blanket tombstone masks this
name. <a id="cite-watch.model.value-deleted-fires-on-last-entry-gone-or-masked"></a>

`SUBKEY_CREATED` and `SUBKEY_DELETED` cover both halves of the naming
model: a path entry appearing or being removed, and a hiding entry
being removed or created. <a id="cite-watch.model.subkey-events-cover-path-and-hiding-entries"></a>

The three no-name events carry no name, and that is enforced: a record
constructed with a name for `SD_CHANGED`, `KEY_DELETED` or `OVERFLOW`
is rejected rather than emitted. <a id="cite-watch.model.no-name-events-reject-a-name"></a>

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

## Filters

The filter selects event *categories*, not individual event types. <a id="cite-watch.model.filter-selects-categories"></a>

| Filter bit | Value | Admits |
|---|---|---|
| `REG_NOTIFY_VALUE` | `0x01` | `VALUE_SET`, `VALUE_DELETED` <a id="cite-watch.model.filter-value-admits-value-events"></a> |
| `REG_NOTIFY_SUBKEY` | `0x02` | `SUBKEY_CREATED`, `SUBKEY_DELETED` <a id="cite-watch.model.filter-subkey-admits-subkey-events"></a> |
| `REG_NOTIFY_SD` | `0x04` | `SD_CHANGED` <a id="cite-watch.model.filter-sd-admits-sd-changed"></a> |
| `REG_NOTIFY_ALL` | `0x07` | all three of the above <a id="cite-watch.model.filter-all-admits-all-three-categories"></a> |

`KEY_DELETED` and `OVERFLOW` are delivered unconditionally. They are
not in any category and no filter suppresses them. <a id="cite-watch.model.key-deleted-and-overflow-bypass-the-filter"></a>
The first tells a watcher its key is gone, and the second tells it that
what it has been told is incomplete. Neither is something a watcher can
usefully opt out of.

A filter containing an undefined bit is rejected. <a id="cite-watch.model.undefined-filter-bit-rejected"></a>

A subtree flag other than 0 or 1, or a non-zero padding byte in the
argument structure, is rejected the same way. <a id="cite-watch.model.subtree-flag-must-be-zero-or-one"></a>

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

## Blanket tombstones

A watcher never learns that a blanket tombstone exists. <a id="cite-watch.model.blanket-tombstone-never-surfaces-as-such"></a>

When one is written, LCS works out which values it newly masks and
emits one `VALUE_DELETED` per name; when one is removed, one
`VALUE_SET` per name that became visible. <a id="cite-watch.model.blanket-tombstone-expands-to-per-value-events"></a>
The per-value view is the only view.

---

# Event Records

_Peios Kernel / Internals / LCS / Watches_

> Events read from the key fd with read() — the record layout, why not every subtree record carries a path, and forward compatibility.

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

These registry watch records are notifications, not KMES events. They have
no MessagePack payload, KMES envelope, or kernel-stamped emitter identity.
Use them to discover changes that require a fresh read, not as an audit
trail. The `.evman` event catalog does not define this binary interface.

Events are read from the key fd with `read()`. A single call returns as
many complete events as fit in the caller's buffer; an event is never
split across two calls. <a id="cite-watch.record.read-returns-whole-events-only"></a>

If the buffer cannot hold even the first queued event, `read()` fails
with `EINVAL` — the buffer is too small to make progress, and the caller
has to try again with a larger one. <a id="cite-watch.record.buffer-too-small-is-einval"></a>

On an armed fd with an empty queue, `read()` blocks, or returns
`EAGAIN` under `O_NONBLOCK`. <a id="cite-watch.record.empty-queue-blocks-or-eagain"></a>

Only events that were copied out in full are dequeued. <a id="cite-watch.record.only-fully-copied-events-dequeued"></a>

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

## Layout

Every record begins with the same four fields. <a id="cite-watch.record.common-header-fields"></a>

| Offset | Size | Field |
|---|---|---|
| 0 | 4 | `total_len` |
| 4 | 2 | `event_type` |
| 6 | 2 | `name_len` |
| 8 | `name_len` | `name`, UTF-8 |

All integers are little-endian. <a id="cite-watch.record.integers-are-little-endian"></a>

`total_len` is the whole record including this header; it is how a
consumer advances to the next event, and it is the only safe way to do
so. <a id="cite-watch.record.total-len-covers-whole-record"></a>

A subtree watch's records carry additional fields after the name,
locating the key the change happened on relative to the watched key: <a id="cite-watch.record.subtree-records-carry-relative-path"></a>

| Size | Field |
|---|---|
| 2 | `path_depth` |
| `2 + n` each | `path_components`: `len` (u16) then that many UTF-8 bytes |

`path_depth` is the number of components from the watched key down to
the changed key; zero means the change was on the watched key itself. <a id="cite-watch.record.path-depth-counts-from-watched-key"></a>

The components are length-prefixed rather than joined with a separator,
because registry names can contain any Unicode character and value
names can contain backslashes — a concatenated path string would be
ambiguous. <a id="cite-watch.record.path-components-are-length-prefixed"></a>

The header offsets are ABI, named in `include/uapi/pkm/lcs.h` and listed in
[LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>).

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

## Not every record on a subtree watch has a path

`OVERFLOW` records are emitted in the bare eight-byte form, on every
watch, whether or not that watch is a subtree watch. <a id="cite-watch.record.overflow-is-always-the-bare-form"></a>

`KEY_DELETED` is not: a subtree watcher receives it in the subtree
form, with a `path_depth` of its own. <a id="cite-watch.record.key-deleted-uses-the-subtree-form"></a>

A consumer of a subtree watch therefore cannot assume the subtree
fields are present on every record it reads. `total_len` is the cursor;
`path_depth` is read only when the record is long enough to hold it.

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

## Length limits

`name_len` and each component length are 16-bit. <a id="cite-watch.record.length-fields-are-16-bit"></a>

If an event's name or one of its path components is too long to be
represented, LCS does not emit a truncated or malformed record: it
substitutes or preserves an `OVERFLOW` for that watcher instead, which
is a statement the consumer already knows how to act on. <a id="cite-watch.record.unrepresentable-length-becomes-overflow"></a>

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

## Forward compatibility <a id="cite-watch.record.appended-fields-are-skipped-by-total-len"></a>

Future versions may append fields after `path_components`. An existing
consumer skips them, because it advances by `total_len`; a newer one
compares `total_len` against what it has parsed to discover whether the
optional fields are present. This is the whole extension mechanism, and
it is why the length field comes first.

---

# Dispatch

_Peios Kernel / Internals / LCS / Watches_

> Given a mutation, which armed watches hear about it — computed from object identity and ancestry, with depth, batching and recovery.

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

Dispatch answers one question: given a mutation on a key, which armed
watches hear about it? The answer is computed from object identity and
from ancestry captured at open time, never from a path string resolved
at the moment of the event. <a id="cite-watch.dispatch.computed-from-identity-and-captured-ancestry"></a>

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

## A watch is bound to an object

A watch is registered against the GUID on the fd it was armed through.
It fires for changes to *that object*. <a id="cite-watch.dispatch.registered-against-the-fd-guid"></a>

If a layer change causes a different key to become visible at the same
path, the watch does not move: the new key is a different object with a
different GUID, and nothing about the old watch refers to a name. <a id="cite-watch.dispatch.watch-does-not-follow-the-path"></a>

To follow the path rather than the object, a process detects the change
— through `KEY_DELETED` on the old object, or a subtree watch on the
parent — re-opens the path, and arms a new watch. This is the fd model
applied consistently: an fd is a capability bound to one identity.

The converse also holds. If a watched key is hidden, `KEY_DELETED` is
delivered, but the watch is not removed. <a id="cite-watch.dispatch.hiding-keeps-the-watch-armed"></a>

Should the hiding layer later be deleted, the key reappears at its
original path with the same GUID, and events resume. <a id="cite-watch.dispatch.events-resume-when-the-key-reappears"></a>
There is no re-emergence event; the watcher simply observes the key
being active again. <a id="cite-watch.dispatch.no-re-emergence-event"></a>

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

## The ancestor chain

Subtree dispatch needs to know where a key sits in the tree, and it
learns that once, at open.

Resolving a path walks it component by component, and the GUID at each
level is retained on the resulting fd as the **ancestor chain** —
root GUID through parent GUID to the key itself. <a id="cite-watch.dispatch.ancestor-chain-captured-at-open"></a>
It costs nothing extra: the walk had to resolve those components
anyway.

A relative open copies the parent fd's chain and extends it with the
components the relative walk resolved. <a id="cite-watch.dispatch.relative-open-extends-the-parent-chain"></a>

An open that followed a symlink records the chain of the *resolved*
path, so the fd's ancestry reflects the target's real position in the
tree, not the link's. <a id="cite-watch.dispatch.symlink-open-records-the-resolved-chain"></a>

Dispatch uses that captured chain and never re-resolves it. If an
ancestor in the chain is later hidden, deleted, orphaned, or replaced
at the same path by a different key, watches on the original ancestor
GUID still receive subtree events from descendants mutated through fds
opened through that chain. <a id="cite-watch.dispatch.stale-ancestor-still-receives-subtree-events"></a>

Watches on a new key that later appears at the same path receive
nothing from the old one. <a id="cite-watch.dispatch.new-key-at-the-same-path-receives-nothing"></a>

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

## The algorithm

Two structures back dispatch. The **watch map** is a hash map from GUID
to the watchers armed on it. The **subtree watch set** is a refcounted
hash set of the GUIDs that have at least one subtree watch, maintained
as watches are armed, re-armed, disarmed and closed.

For a mutation on key *B*, with *B*'s ancestor chain in hand:

1. Look up *B*'s GUID in the watch map and queue the event, with
   `path_depth` 0, to every watcher whose filter admits it. <a id="cite-watch.dispatch.direct-watchers-receive-depth-zero"></a>
2. Walk the ancestor chain outward from *B*'s parent. At each ancestor,
   skip it unless it is in the subtree watch set — that test is what
   makes the walk cheap. For an ancestor that is, queue the event to
   each of its watchers that armed with the subtree flag and whose
   filter admits it, with the path from that ancestor down to *B*. <a id="cite-watch.dispatch.subtree-watchers-receive-the-relative-path"></a>

The cost is O(depth) hash lookups, with no RSI round trips, no trie and
no string comparison. <a id="cite-watch.dispatch.costs-o-depth-hash-lookups-and-no-source-io"></a>
The path components handed to a subtree watcher are sliced out of the
resolved path already stored on the mutating fd.

Dispatch runs under a single global registry lock, so it is serialised
across the whole system rather than per hive or per source.

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

## Depth

`MaxSubtreeWatchDepth` bounds how far below a watched key a subtree
watch is told about. The default is 0, meaning unlimited. <a id="cite-watch.dispatch.depth-zero-means-unlimited"></a>

A non-zero value suppresses events whose path is longer than it,
limiting both noise and dispatch cost for a watch armed high in a
tree. <a id="cite-watch.dispatch.depth-limit-suppresses-deeper-events"></a>

The limit applies to watches held by userspace. LCS's own internal
watches are collected before the depth test and are not subject to it
([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

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

## Transaction batches

Nothing inside an uncommitted transaction dispatches. <a id="cite-watch.dispatch.uncommitted-transaction-dispatches-nothing"></a>

At commit, and only when the source reports success, the transaction's
mutation log is walked in operation order and the whole set of events
is queued as one batch, under a single hold of the registry lock, so no
other operation interleaves with it. <a id="cite-watch.dispatch.commit-batch-queued-in-operation-order-without-interleaving"></a>

An aborted or failed transaction dispatches nothing and its log is
released. A transaction that timed out after its commit was dispatched
keeps its log, and a late `RSI_OK` still emits the batch ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

A large transaction — a role installation writing thousands of values —
could otherwise fill a watcher's queue atomically. So the batch is
counted per watcher first: any watcher whose share exceeds
`MaxTransactionWatchEventBurst`, default 4096, receives exactly one
`OVERFLOW` and none of its individual events. <a id="cite-watch.dispatch.burst-cap-replaces-a-watchers-batch-with-one-overflow"></a>

That `OVERFLOW` is queued ahead of the batch, so it arrives before
whatever else that watcher is still owed. <a id="cite-watch.dispatch.burst-overflow-queued-ahead-of-the-batch"></a>

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

## Recovery dispatch

Some changes alter effective state for keys whose fds nobody holds and
whose descendants the kernel is retaining no context for. Deleting a
layer, changing its precedence, enabling or disabling it, and restoring
a subtree from a stream are all of this kind. <a id="cite-watch.dispatch.recovery-triggering-operations"></a>
Computing an exact diff would mean walking arbitrary parts of the tree
through the source.

LCS does not attempt it. It increments the generation number of every
hive the affected source backs and then queues a no-name `OVERFLOW` to
every armed watch on that source, which is the notification for those
changes. <a id="cite-watch.dispatch.recovery-bumps-generation-and-queues-overflow"></a>
The watcher re-reads, and can compare the generation number it last saw
against the current one ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) to tell whether an *ordinary* write
happened in between; after a recovery it cannot, because the bump is
deliberately conservative. The kernel does not know which hives a layer
operation touched — the source's delete-layer answer names only the
keys it orphaned, and a layer holding hiding or masked entries changes
effective state without orphaning anything — so it bumps every hive
rather than risk a watcher skipping a re-read its hive needed. The
consequence is always a spurious re-read, never a missed change.
<a id="cite-watch.dispatch.recovery-generation-bump-is-source-wide"></a>

Two properties of this delivery are worth stating. It is object-
semantic like every other dispatch — it walks the watch map, resolves
no paths — and it bypasses the filter, because `OVERFLOW` always does.
It does not disarm anything. <a id="cite-watch.dispatch.recovery-does-not-disarm"></a>

The scope is the **source**, not the hive. A source backing several
hives delivers `OVERFLOW` to watches on all of them, including hives
the operation did not touch, and bumps all of their generation
counters. <a id="cite-watch.dispatch.recovery-scope-is-the-source-not-the-hive"></a>
The generation counters are maintained per hive for ordinary writes;
recovery treats the source as the unit.

For a restore, recovery is published only after the source commit
succeeds. A restore that fails or aborts before commit emits nothing. <a id="cite-watch.dispatch.restore-recovery-published-only-after-commit"></a>

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

## Source restart

When a source disconnects, watches stay armed and nothing is delivered;
operations needing the source return `EIO`. <a id="cite-watch.dispatch.disconnect-keeps-watches-armed-and-silent"></a>

`OVERFLOW` arrives on **re-registration**, not on disconnect, which is
the only ordering that works: a watcher told to re-read needs the
source to be there when it does. <a id="cite-watch.dispatch.overflow-arrives-on-re-registration"></a>

Existing fds resume without re-opening, and no watcher has to
re-arm. <a id="cite-watch.dispatch.fds-resume-without-re-arming"></a>

---

# Queues and Overflow

_Peios Kernel / Internals / LCS / Watches_

> Each armed fd has its own bounded queue and delivery is best-effort — what a full queue does, and what a watcher does about it.

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

Each armed fd has its own event queue, bounded by
`NotificationQueueSize` — default 256 events, configurable between 16
and 65536 ([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)). <a id="cite-watch.overflow.each-fd-has-its-own-bounded-queue"></a>

Delivery is best-effort. A watcher that reads promptly sees every
change; one that falls behind is told that it has, rather than being
given a partial history it cannot distinguish from a complete one. <a id="cite-watch.overflow.delivery-is-best-effort"></a>

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

## What happens when the queue is full

When an event arrives for a full queue and no `OVERFLOW` is present:

1. The oldest queued event is dropped. <a id="cite-watch.overflow.full-queue-drops-the-oldest-event"></a>
2. An `OVERFLOW` record is queued in its place. <a id="cite-watch.overflow.full-queue-queues-an-overflow"></a>
3. The event that triggered this is **discarded**, not queued. <a id="cite-watch.overflow.triggering-event-is-discarded"></a>

Once an `OVERFLOW` is in the queue, subsequent events queue normally:
the oldest non-`OVERFLOW` event is dropped to make room and the new
event is added, so the single `OVERFLOW` is preserved and the queue
continues to carry the most recent history behind it. <a id="cite-watch.overflow.later-events-drop-the-oldest-and-preserve-the-overflow"></a>

A queue therefore holds at most one `OVERFLOW` at a time, and that is
an enforced invariant rather than a convention — an attempt to queue a
second is rejected as a bug. <a id="cite-watch.overflow.at-most-one-overflow-per-queue"></a>

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

## What a watcher does about it

`OVERFLOW` means the record it has is incomplete. There is no way to
learn what was dropped, and no attempt is made to describe it. <a id="cite-watch.overflow.dropped-events-are-not-described"></a>

The watcher re-reads the watched key, and its subtree if the watch is a
subtree watch, and continues from the state it finds. Events after the
`OVERFLOW` are complete again. <a id="cite-watch.overflow.events-after-an-overflow-are-complete"></a>

`REG_IOC_QUERY_KEY_INFO` reports a per-hive generation number
([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) that makes this cheaper than it sounds: a watcher that
recorded the generation at its last full read can compare it with the
current one and skip the re-read entirely if nothing committed in
between.

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

## Memory

There is no registry-specific global cap on watch memory, and none is
needed. A watch costs at most `NotificationQueueSize` queued events, a
watch requires an fd, and a process holds at most `RLIMIT_NOFILE` fds.
The product of the two is the bound, and it is enforced by machinery
that already exists. <a id="cite-watch.overflow.no-global-cap-beyond-queue-size-times-fd-limit"></a>

The same reasoning covers open key state: per-fd overhead — GUID,
granted mask, ancestor chain, watch state — multiplied by the fd limit.

LCS's own internal watches are outside this. They are delivered
synchronously through a kernel callback rather than queued, so the
queue limit does not apply to them ([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

---

# Transactions

_Peios Kernel / Internals / LCS / Transactions_

> Find the Peios kernel articles about transactions.

Use these articles to understand transactions in the Peios kernel.

- [Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md>)
- [Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md>)
- [Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md>)

---

# Scope and Lifetime

_Peios Kernel / Internals / LCS / Transactions_

> Grouping registry operations so they commit together or not at all — binding, states, timeout, and sources that do not support them.

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

A transaction groups registry operations so that they commit together
or not at all. <a id="cite-txn.lifetime.commit-together-or-not-at-all"></a>
Installing a role writes service definitions, defaults and registry
entries; a transaction is what makes that one event rather than a
sequence of partially-applied ones.

`reg_begin_transaction` takes no arguments and returns a transaction
fd. It contacts no source: it allocates an id, creates an anonymous
inode, starts the lifetime timer, and returns. <a id="cite-txn.lifetime.begin-contacts-no-source"></a>

A transaction begins in the state `REG_TXN_ACTIVE_UNBOUND`. <a id="cite-txn.lifetime.begins-active-unbound"></a>

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

## Binding

A write transaction binds to a source on its first **mutating** operation. <a id="cite-txn.lifetime.binds-on-first-mutating-operation"></a>

There are seven: writing a value, deleting a value entry, setting or
removing a blanket tombstone, creating a key, deleting a key's path
entry, hiding a key, and changing a Security Descriptor. <a id="cite-txn.lifetime.the-seven-binding-operations"></a>

Reads never bind a write transaction. <a id="cite-txn.lifetime.reads-never-bind"></a>

A read passed an unbound write transaction fd is sent to the source with a
transaction id of zero and behaves as an ordinary non-transactional
read. <a id="cite-txn.lifetime.unbound-read-is-non-transactional"></a>

`reg_begin_read_transaction` creates a read-only transaction. Its first read
binds the source/hive and fixes the persistent and volatile data snapshot and
layer view. It uses the ordinary lifetime timer and read-only source quota.
The kernel rejects mutations with `EROFS`. Snapshot capture overlapping a
publication returns `EAGAIN`; the caller retries its whole read using a fresh
transaction. Writers continue while an established read snapshot exists.

Once bound, every operation on that fd must target the same hive.
One that does not fails with `EXDEV`, and it fails in the kernel,
before anything reaches a source — a source never sees a cross-hive
operation inside a transaction. <a id="cite-txn.lifetime.cross-hive-operation-is-exdev-in-the-kernel"></a>
Cross-source atomicity would require two-phase commit and is not
supported.

Binding identity is the pair of source and hive root GUID carried on
the transaction object, which identifies the hive exactly. <a id="cite-txn.lifetime.binding-identity-is-source-and-hive-root"></a>

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

## Sources that do not support transactions

Because `reg_begin_transaction` chooses no source, it cannot fail for
lack of transaction support. The failure surfaces on the operation that
would have bound: LCS sends `RSI_BEGIN_TRANSACTION`, the source answers
`RSI_TXN_NOT_SUPPORTED`, and the operation returns `ENOTSUP`. <a id="cite-txn.lifetime.unsupported-source-binds-with-enotsup"></a>

The transaction stays `ACTIVE_UNBOUND`, its source binding untouched,
and the caller can use the fd against a different hive. <a id="cite-txn.lifetime.failed-bind-leaves-the-transaction-unbound"></a>

There is no advance check of whether a source supports transactions.
The answer comes from the source, on the attempt.

If the source is Down before the first bind, the binding operation
fails `EIO` under the ordinary rules and the transaction likewise
remains unbound. <a id="cite-txn.lifetime.source-down-before-bind-is-eio"></a>
If a source goes Down after binding, the transaction becomes
`REG_TXN_SOURCE_DOWN` ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

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

## States <a id="cite-txn.lifetime.the-six-transaction-states"></a>

| State | Value | Meaning |
|---|---|---|
| `REG_TXN_ACTIVE_UNBOUND` | 0 | Active, no source chosen. |
| `REG_TXN_ACTIVE_BOUND` | 1 | Active, bound to a source. |
| `REG_TXN_COMMITTED` | 2 | Commit completed. |
| `REG_TXN_ABORTED` | 3 | Explicitly or implicitly aborted. |
| `REG_TXN_TIMED_OUT` | 4 | The lifetime timer fired. |
| `REG_TXN_SOURCE_DOWN` | 5 | The bound source went Down. |

`REG_IOC_TXN_STATUS` reports the state and a `terminal_errno`: 0 for
`COMMITTED`, `EINVAL` for `ABORTED`, `ETIMEDOUT` for `TIMED_OUT`, `EIO`
for `SOURCE_DOWN`, and 0 while active.

For `COMMITTED`, `terminal_errno` is not the errno that a further
operation would return. A committed transaction reports 0, but using
its fd again returns `EINVAL`.

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

## Reaching a terminal state

- **Commit.** `REG_IOC_COMMIT` on the transaction fd. The source
  applies everything atomically, watch events fire, and the object
  becomes `COMMITTED`. Later use of the fd returns `EINVAL`. The fd
  should be closed. <a id="cite-txn.lifetime.use-after-commit-is-einval"></a>
- **Explicit abort.** `close()` without committing. The source is told
  to discard, and the object becomes `ABORTED` during release. No
  events. <a id="cite-txn.lifetime.close-without-commit-aborts"></a>
- **Implicit abort.** Process death closes the fd, which aborts it.
  There are no orphaned transactions. <a id="cite-txn.lifetime.process-death-aborts-no-orphans"></a>
- **Timeout.** The lifetime timer fires. See below.

The object stays addressable after reaching a terminal state, until the
fd is closed. <a id="cite-txn.lifetime.terminal-object-stays-addressable-until-close"></a>
That is what makes `REG_IOC_TXN_STATUS` useful.

Transaction fds are pollable. Any terminal transition wakes poll
waiters with `POLLERR | POLLHUP`. <a id="cite-txn.lifetime.terminal-transition-wakes-poll-with-pollerr-pollhup"></a>
A caller that needs a race-free reason for the wakeup queries the
status.

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

## Timeout

The lifetime timer starts when the fd is created — not at the first
operation — and runs for `TransactionTimeoutMs`, default 30 seconds. <a id="cite-txn.lifetime.timer-starts-at-fd-creation"></a>

When it fires, the object becomes `TIMED_OUT`, poll waiters are woken,
and further use of the fd returns `ETIMEDOUT`. <a id="cite-txn.lifetime.timeout-makes-further-use-etimedout"></a>

The timer updates transaction state from softirq context. Task and
workqueue callers disable bottom halves while holding the shared state
spinlock, so the timer cannot interrupt a holder on the same CPU and
wait for that holder to release it. Synchronous timer cancellation runs
outside the state lock. <a id="cite-txn.lifetime.timer-state-lock-softirq-safe"></a>

If the transaction was bound and no commit is already in flight,
`RSI_ABORT_TRANSACTION` is sent to the source. <a id="cite-txn.lifetime.timeout-aborts-a-bound-transaction-at-the-source"></a>

The fd is not removed from the caller's table; `close()` still releases
it normally. <a id="cite-txn.lifetime.timeout-leaves-the-fd-in-the-table"></a>

The timeout is not a convenience. Sources serialise writers — loregd
does so through SQLite's WAL — so a stalled transaction blocks every
other write to that source. The timer is what bounds the starvation
window, and `MaxBoundTransactionsPerSource` (default 16) is what stops
colluding processes from extending it indefinitely by binding fresh
transactions at each timeout boundary. An operation that would bind
past that cap returns `EBUSY`. <a id="cite-txn.lifetime.bind-past-the-cap-returns-ebusy"></a>

The cap is tested before the source is contacted, but after the
transaction's mutation-log entry has been allocated; that entry is
freed on the way out. <a id="cite-txn.lifetime.cap-tested-after-log-entry-allocation"></a>

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

## Constraints

- **No nesting.** Transactions are flat: no savepoints, no
  sub-transactions. The transaction fd accepts only `REG_IOC_COMMIT`
  and `REG_IOC_TXN_STATUS`; every other ioctl is `ENOTTY`. <a id="cite-txn.lifetime.transactions-are-flat"></a>
- **One transaction per fd.** A process may hold many transaction fds
  at once, but each is exactly one transaction. <a id="cite-txn.lifetime.one-transaction-per-fd"></a>
- **Reads are permitted.** A transaction is not write-only, which is
  what makes verify-then-write possible. <a id="cite-txn.lifetime.reads-are-permitted"></a>

---

# Isolation and the Mutation Log

_Peios Kernel / Internals / LCS / Transactions_

> Read-your-own-writes inside a transaction, implemented by the source rather than LCS — the mutation log, sequence numbers and conflicts.

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

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

## Read-your-own-writes

Within a bound write transaction, reads see the transaction's own uncommitted
writes. <a id="cite-txn.isolation.read-your-own-writes"></a>
LCS does not implement this; the source does. A read tagged with the
transaction id is executed by the source inside its open transaction,
which naturally includes the pending writes.

No uncommitted registry data is cached in the kernel for the purpose of
resolving reads. <a id="cite-txn.isolation.no-uncommitted-data-cached-in-the-kernel"></a>

Externally, only committed state is visible. A transaction's writes are
invisible to other threads and processes until commit. <a id="cite-txn.isolation.uncommitted-writes-are-invisible-externally"></a>

Read-only transactions preserve their first-read data and layer selection.
The kernel verifies that capture did not overlap a pending mutation or its
completion effects; this includes requests whose original caller timed out.
An overlap fails with `EAGAIN`, rather than mixing a source commit with an
earlier kernel layer table. The fence covers capture only and never holds a
writer lock for the lifetime of a read transaction.

Security descriptors read through `REG_IOC_GET_SECURITY_TRANSACTED` are
historical data, subject to the key fd's granted rights. New transacted opens
check the current descriptor of the historical target GUID and the actual
caller. The snapshot does not preserve an earlier permission to open a key.

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

## The mutation log

LCS does keep something: a per-transaction **mutation log**, holding
what the kernel needs to know after a successful commit and cannot ask
the source for afterwards. Each accepted mutating operation records the
affected key, value or layer name, its assigned sequence number, the
ancestor chain for watch dispatch, and enough context to compute
effective-state changes. <a id="cite-txn.isolation.log-records-per-operation-context"></a>

The log is not the source of truth for reads and it is not a rollback
journal — the source's own transaction state is authoritative for
uncommitted data. <a id="cite-txn.isolation.log-is-not-a-rollback-journal"></a>
The log exists so that when the source says "yes", LCS can produce the
hive generation updates and the watch events that correspond to what
was just committed.

It is bounded at 4096 entries. That bound is a compile-time constant
rather than one of the self-configuration parameters. <a id="cite-txn.isolation.log-bounded-at-4096-entries"></a>

Exceeding it fails the operation with `ENOMEM`. <a id="cite-txn.isolation.log-full-fails-the-operation-with-enomem"></a>

An operation whose log entry cannot be allocated fails **before it is
sent to the source**. <a id="cite-txn.isolation.log-allocation-failure-precedes-the-source-send"></a>
That ordering is deliberate: an operation the source applied but the
kernel cannot account for is exactly the state the log exists to
prevent.

The log is released, with no events emitted, on explicit abort, on a
lifetime timeout that fires before a commit is dispatched, on
source-down cancellation, on a late commit error, and on source
teardown while a post-dispatch commit response is still retained. <a id="cite-txn.isolation.log-release-conditions"></a>

It is **retained** across a post-dispatch commit timeout, because the
source may still answer. <a id="cite-txn.isolation.log-retained-across-a-post-dispatch-timeout"></a>

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

## Sequence numbers

A transactional mutation is assigned its sequence number when it is
accepted into the transaction, not at commit. <a id="cite-txn.isolation.sequence-assigned-on-accept-not-at-commit"></a>
This preserves the order in which the caller performed the operations,
which is what layer tiebreaking and watch ordering need.

If the transaction aborts, those numbers are simply never used. <a id="cite-txn.isolation.aborted-sequence-numbers-are-never-used"></a>
Gaps in the sequence space are normal and mean nothing ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

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

## Layer precedence coherency

Layer metadata lives in the registry, so a transaction can write to it —
and that raises the question of whether a precedence change takes
effect inside the transaction that made it. It does not. <a id="cite-txn.isolation.precedence-change-does-not-take-effect-in-its-own-transaction"></a>

Resolution always uses the published layer cache, which is refreshed
only at commit. <a id="cite-txn.isolation.resolution-uses-the-published-layer-cache"></a>

Reading the `Precedence` value back inside the transaction shows the
new number, because that is an ordinary read-your-own-writes read from
the source. <a id="cite-txn.isolation.precedence-value-reads-back-as-the-new-number"></a>

Resolving any *other* value in the same transaction still uses the old
precedence order. <a id="cite-txn.isolation.other-values-resolve-under-the-old-precedence"></a>
The two are consistent with each other and with the rule that a
transaction's effects become real at commit.

The refresh is deferred to commit, dropped on abort, and performed
before `REG_IOC_COMMIT` returns on success. <a id="cite-txn.isolation.layer-cache-refresh-completes-before-commit-returns"></a>

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

## Conflicts

Transactions are atomic. They are not conflict-detecting. <a id="cite-txn.isolation.no-conflict-detection"></a>

If two transactions write the same value, both commits succeed and the
one that committed second wins, because its write carries the higher
sequence number. <a id="cite-txn.isolation.second-committer-wins"></a>
There is no read set, no version check, and no per-key validation
anywhere in the commit path.

Serialising concurrent writers is the source's responsibility, not
LCS's. The RSI requires only that commits are atomic, that writes
within a transaction are ordered, and that concurrent commits are
serialised. <a id="cite-txn.isolation.rsi-requires-atomic-ordered-serialised-commits"></a>

Conditional writes are the mechanism for the cases where losing an
update matters. `REG_IOC_SET_VALUE` takes an `expected_sequence`, the
source verifies it atomically against the layer's own entry, and a
mismatch returns `EAGAIN` ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)).

That is a per-operation check, not a transaction-level one, and it is
deliberately scoped to a single layer: a higher-precedence layer
overriding a value is not a conflict, it is the layer system
working. <a id="cite-txn.isolation.conditional-write-is-per-operation-and-single-layer"></a>

---

# Commit and Failure

_Peios Kernel / Internals / LCS / Transactions_

> What a commit triggers in order, the failures that leave a transaction open, and what happens when the watch events cannot be delivered.

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

`REG_IOC_COMMIT` marks the transaction as having a commit in flight and
sends `RSI_COMMIT_TRANSACTION`. <a id="cite-txn.commit.marks-in-flight-and-sends-rsi-commit"></a>
What happens next depends on the answer.

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

## Success

The source's `RSI_OK` triggers, in order: the layer metadata cache
refresh for any layer names the transaction touched, the hive
generation increment, orphan tracking for keys that lost their last
path entry, and the watch event batch derived from the mutation log. <a id="cite-txn.commit.post-commit-step-order"></a>

The object then becomes `COMMITTED`, the log is released, poll waiters
are woken, and the ioctl returns 0. <a id="cite-txn.commit.success-finalises-and-returns-zero"></a>

The hive generation is incremented once per committed transaction per
affected hive, however many operations the transaction contained. <a id="cite-txn.commit.generation-incremented-once-per-transaction-per-hive"></a>

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

## Failure that leaves the transaction open

A source that cannot take the write lock answers `RSI_TXN_BUSY`, which
becomes `EBUSY`; a synchronous commit failure becomes `EIO`. <a id="cite-txn.commit.busy-is-ebusy-and-commit-failure-is-eio"></a>

In both cases the transaction stays `ACTIVE_BOUND`: <a id="cite-txn.commit.failed-commit-stays-active-bound"></a>

- the mutation log is retained; <a id="cite-txn.commit.failed-commit-retains-the-log"></a>
- no watch events are emitted; <a id="cite-txn.commit.failed-commit-emits-no-events"></a>
- poll waiters are **not** woken as though the transaction had become
  terminal. <a id="cite-txn.commit.failed-commit-does-not-wake-poll-waiters"></a>

The in-flight marker is cleared, so the caller may simply retry
`REG_IOC_COMMIT`, or close the fd to abort. Nothing has been lost. <a id="cite-txn.commit.in-flight-marker-cleared-so-retry-is-allowed"></a>

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

## Timeout after dispatch

If the request timeout expires after the commit was dispatched, the
caller receives `ETIMEDOUT` and the object becomes `TIMED_OUT`, but the
mutation log is kept and the request record stays in the source's
in-flight table. The source may still answer. <a id="cite-txn.commit.post-dispatch-timeout-keeps-log-and-request"></a>

`ETIMEDOUT` on a commit means *may or may not have committed*. A caller
that needs certainty checks state before retrying. <a id="cite-txn.commit.etimedout-is-indeterminate"></a>

A late `RSI_OK` applies the full set of kernel-side effects from the
retained log — the same generation updates and the same watch events an
on-time commit would have produced. Watchers may therefore observe the
effects of a transaction whose caller was told it timed out. <a id="cite-txn.commit.late-ok-applies-the-full-effects"></a>

A late error releases the log with no effects. <a id="cite-txn.commit.late-error-releases-the-log-with-no-effects"></a>

The transaction object does **not** move to `COMMITTED` when a late
success arrives. It stays `TIMED_OUT`, so a caller that queries
`REG_IOC_TXN_STATUS` afterwards is told `TIMED_OUT` with a
`terminal_errno` of `ETIMEDOUT`, even though the writes are durable and
the watch events have gone out. <a id="cite-txn.commit.late-success-leaves-the-state-timed-out"></a>
The state reflects what the caller was told, not what the source did.

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

## When the watch events cannot be derived

Two of the post-commit steps query the source. Working out which keys
were orphaned by a key deletion needs a lookup that can only be made
after the commit, and expanding a blanket tombstone into per-value
events needs the value set.

If that derivation cannot complete exactly, LCS does not reinterpret a
successful commit as a failed one and does not emit a partial set of
events. It delivers `OVERFLOW` to the affected watchers instead,
releases the retained replay state, and reports the commit as
successful, which it was. <a id="cite-txn.commit.underivable-events-become-overflow"></a>

A late response arriving afterwards does not resurrect the individual
events once overflow recovery has been chosen. <a id="cite-txn.commit.overflow-recovery-is-not-undone-by-a-late-response"></a>

The carve-out is narrower than it might appear. It covers the orphan
lookup and the watch batch. <a id="cite-txn.commit.carve-out-covers-only-orphan-lookup-and-watch-batch"></a>

The other two post-commit steps — publishing the layer metadata cache
and recording the hive generation — are state updates rather than event
derivation, and a failure in either returns `EIO` and marks the source
Down. <a id="cite-txn.commit.cache-or-generation-failure-is-eio-and-marks-the-source-down"></a>

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

## Abort

Aborting generates no events, ever, and releases the log. <a id="cite-txn.commit.abort-emits-no-events-and-releases-the-log"></a>

The source is told to roll back with `RSI_ABORT_TRANSACTION` if the
transaction was bound. <a id="cite-txn.commit.abort-sends-rsi-abort-when-bound"></a>

Process death is the same path: closing the fd aborts.

---

# Sources

_Peios Kernel / Internals / LCS / Sources_

> Find the Peios kernel articles about sources.

Use these articles to understand sources in the Peios kernel.

- [The Source Model](</kernel/internals/lcs/sources/the-source-model.md>)
- [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md>)
- [Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md>)
- [Validation](</kernel/internals/lcs/sources/validation.md>)
- [Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md>)

---

# The Source Model

_Peios Kernel / Internals / LCS / Sources_

> A source is a userspace process holding registry data and answering LCS over RSI — the trust boundary, and why loregd is not special.

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

A source is a userspace process that holds registry data and answers
LCS's questions about it over the Registry Source Interface. LCS is
source-agnostic: it does not know or care how a source stores anything.

The division is the sixth semantic rule ([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>)). A source stores path
entries, key records, value entries and blanket tombstones, and returns
**all** of them on request. <a id="cite-source.model.returns-all-entries"></a>

It does not evaluate access, resolve layers, dispatch watches, interpret
paths beyond the parent and child names it is given, or see the identity
of any caller. LCS does all of that. <a id="cite-source.model.does-no-policy"></a>

A source may back several hives; a hive is backed by exactly one source
([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)).

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

## The interface is specified elsewhere

The RSI — its channel, framing, operations, error vocabulary, and the
obligations binding on a conforming source — is a normative
specification, because the userspace side is a role a third party can
implement. It is a chapter of PSPK, and it is where the wire format
lives.

This section covers the kernel's side: how LCS admits a source, how it
dispatches requests and accounts for them, what it refuses to believe,
and what it does when a source dies or answers late.

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

## The trust boundary

Sources are in the TCB. LCS trusts the data a source returns —
descriptors, values, symlink targets, key metadata — because it has no
independent copy of any of it. <a id="cite-source.model.lcs-trusts-source-data"></a>

A compromised source therefore has complete control over access
decisions for its hives. It can return a permissive descriptor for any
key and AccessCheck will grant access that should have been denied. LCS
validates that responses are structurally correct, but it cannot detect
data that is well-formed and wrong: a descriptor granting Everyone
`KEY_ALL_ACCESS` on a sensitive key is a perfectly valid descriptor.

Three consequences are worth naming specifically.

**Layer table poisoning.** A compromised source backing `Machine\` can
fabricate the `Precedence` and `Enabled` values under
`Machine\System\Registry\Layers\`, and so control which layer wins
every resolution contest system-wide. The `SeTcbPrivilege` check at
write time does nothing about a fabricated read.

**Layer authorization bypass.** The same source can return permissive
descriptors for layer metadata keys, granting any process write access
to any layer ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

**`SeRestorePrivilege` implies descriptor control.** Restore replaces a
subtree including every descriptor in it, so granting
`SeRestorePrivilege` effectively grants `WRITE_DAC` and `WRITE_OWNER`
over everything in reach of a restore. <a id="cite-source.model.restore-implies-descriptor-control"></a> Operators should
understand it that way.

The mitigations are operational rather than architectural: sources run
with tightly scoped privileges, protected by descriptors on their
service definitions, and managed by peinit with Process Integrity
Protection where available. LCS emits audit events for every source
data validation failure. A harder guarantee — checksumming descriptors
LCS computed during inheritance and verifying them on retrieval — is
possible but not implemented.

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

## loregd is not special <a id="cite-source.model.loregd-is-not-special"></a>

loregd is the first source and the one that provides `Machine\` and
`Users\` at boot, which puts it on the critical path to a running
system. Nothing in LCS knows that. Its details are its own manual's
business; what LCS requires of it is exactly what it requires of any
source.

---

# Registration and Slots

_Peios Kernel / Internals / LCS / Sources_

> Reaching LCS through /dev/pkm_registry — what registration validates, how source slots work, and resuming one that went Down.

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

A source reaches LCS through `/dev/pkm_registry`. The device's `open()`
handler checks the calling thread's effective token for an **enabled**
`SeTcbPrivilege` and returns `EPERM` without it, so an unprivileged
process cannot obtain an fd to the device at all. <a id="cite-source.register.open-requires-enabled-setcbprivilege"></a>

Having opened it, the source issues `REG_SRC_REGISTER`, naming the
hives it backs, the root GUID of each, the highest sequence number it
has persisted, and per-hive flags and scope GUID. On success it enters
the request loop: `read()` for requests, `write()` for responses.

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

## What registration validates

- Every hive name is valid and is not the reserved `CurrentUser`
  ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)). <a id="cite-source.register.hive-name-valid-and-not-currentuser"></a>
- No route identity — the folded name paired with its scope — collides
  with one held by another **Active** source. <a id="cite-source.register.no-route-identity-collision"></a>
- Private hive collisions are scoped: the same name in different scopes
  is fine ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-source.register.private-hive-collisions-are-scoped"></a>
- A hive's root GUID is not nil. <a id="cite-source.register.root-guid-not-nil"></a>
- The root GUIDs within one request are distinct from each other. <a id="cite-source.register.root-guids-distinct-within-request"></a>
- A hive without `RSI_HIVE_PRIVATE` carries no scope GUID. <a id="cite-source.register.scope-guid-only-for-private-hive"></a>
- No unknown flag bits are set. <a id="cite-source.register.no-unknown-flag-bits"></a>
- The hive count is within `MaxHivesPerSource` (64), and the source
  count is within `MaxRegisteredSources` (32). Either limit is `ENOSPC`;
  a zero hive count is `EINVAL`. <a id="cite-source.register.hive-and-source-counts-are-enospc"></a>
- The reported maximum sequence can be advanced past without
  overflowing 64 bits, or registration fails `EOVERFLOW` and the source
  is never made Active ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)). <a id="cite-source.register.max-sequence-overflow-is-eoverflow"></a>

Root GUIDs are checked for uniqueness within one request, and against
every existing slot, Active or Down: a request whose root GUID is
already the root of a differently-named hive is refused `EEXIST`. A
same-named hive is decided by the identity rules above instead. The
already-registered state is also checked for consistency, and a table
that ever held two hives with one root would fail that check on every
later registration and path walk, which is why admission refuses it. <a id="cite-source.register.root-guids-compared-across-slots"></a>

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

## Source slots

Successful registration creates a **source slot**: the kernel object
owning one connection and the hive set registered on it. <a id="cite-source.register.success-creates-a-slot"></a>

Each registered hive has a stable identity — its folded name, its
visibility, its scope GUID for a private hive, and its root GUID. <a id="cite-source.register.hive-identity-fields"></a>

**Down slots keep their identities reserved.** A crash or an fd close
marks the slot Down; it does not unregister anything and does not
retire any hive identity. <a id="cite-source.register.down-slot-keeps-its-identities"></a>

Slots are never freed, and collision checks see Down slots as well as
Active ones. <a id="cite-source.register.collision-checks-see-down-slots"></a>

Status is a property of the slot, not of an individual hive. A source's
hives go Down together. <a id="cite-source.register.status-is-per-slot"></a>

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

## Resuming a Down slot

A new process may take over a Down slot if it holds `SeTcbPrivilege`
and registers **exactly the same hive set**: the same folded name,
visibility, scope GUID and root GUID for every hive, and the same
number of them. Partial resume is rejected. <a id="cite-source.register.resume-requires-exact-hive-set"></a>

The distinction between the failures matters. A request whose only
mismatch is stale identity data — a different root GUID for an
otherwise-matching hive — fails `ESTALE`. <a id="cite-source.register.stale-root-guid-is-estale"></a>

Other partial or malformed resume attempts fail `EINVAL`. <a id="cite-source.register.other-resume-mismatch-is-einval"></a>

`EEXIST` is reserved for a collision with an **Active** slot; it never
comes from a Down-slot collision. <a id="cite-source.register.eexist-only-from-active-collision"></a>

When both an Active collision and a stale Down slot apply, `EEXIST`
wins. <a id="cite-source.register.eexist-wins-over-estale"></a>

New hives cannot be added by mutating a Down slot during a resume — the
hive set has to match exactly, so a superset simply fails, and a new
hive needs a new slot. There is no implicit retirement of a Down slot;
retiring one would need an explicit administrative operation, and none
exists. <a id="cite-source.register.no-implicit-down-slot-retirement"></a>

A replacement source is authenticated by `SeTcbPrivilege`, not by
process identity. Nothing records a pid, and nothing could usefully:
process identity does not survive a crash and restart. <a id="cite-source.register.resume-authenticated-by-privilege-not-pid"></a>

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

## Coming back

On a successful resume the slot becomes Active, its restart generation
advances, and LCS replays any layer deletions that were pending. <a id="cite-source.register.resume-activates-slot-and-replays"></a>

LCS then delivers `OVERFLOW` to every armed watch on that source
([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Existing key fds resume working without being reopened. Each carries
the restart generation it last saw; when it notices a change it
re-reads its key and continues. <a id="cite-source.register.key-fds-survive-a-resume"></a>

If the key's GUID no longer exists in the restarted source — the
database was restored from an older backup, say — that first operation
returns `ENOENT` and the fd is marked orphaned. <a id="cite-source.register.missing-guid-after-resume-orphans-fd"></a>

---

# Request Dispatch

_Peios Kernel / Internals / LCS / Sources_

> The RSI is multiplexed — request ids and matching, the single deadline covering three waits, and requests with no caller.

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

The RSI is multiplexed. LCS sends concurrent requests tagged with
request ids and matches responses back to the kernel threads waiting on
them. A source may process requests in any order. <a id="cite-source.dispatch.responses-may-arrive-in-any-order"></a>

Request ids are allocated per connection, strictly increasing, and
**never reused** while the connection lives — including after a
timeout. <a id="cite-source.dispatch.request-ids-never-reused"></a>

The id is allocated inside the queue lock, after the in-flight limit has
been checked, so a caller queued waiting for a slot does not hold one
yet. <a id="cite-source.dispatch.id-allocated-after-the-limit-check"></a>

`MaxConcurrentRSIRequests`, default 256, bounds how many requests may
be dispatched and awaiting a response at once. <a id="cite-source.dispatch.max-concurrent-bounds-in-flight"></a> It is back-pressure for
a slow source.

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

## One deadline covers three waits

`RequestTimeoutMs`, default 30 seconds, is measured from the point a
kernel operation first attempts to **reserve an in-flight slot**, after
local validation and access checks have already passed. One deadline is
computed there and reused for all three legs: waiting for a slot,
waiting for the source to read the queued request, and waiting for the
response. <a id="cite-source.dispatch.one-deadline-covers-three-waits"></a>

If the deadline expires before a slot is reserved, the caller gets
`ETIMEDOUT` and **no request is sent**. <a id="cite-source.dispatch.timeout-before-a-slot-sends-nothing"></a>

If it expires after dispatch, the caller gets `ETIMEDOUT` and
late-response handling applies ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)). <a id="cite-source.dispatch.timeout-after-dispatch-is-etimedout"></a>

The deadline is checked before admission is attempted, not only after a
contention round is lost. <a id="cite-source.dispatch.deadline-checked-before-admission"></a> It used to be the latter, which meant a request
finding a slot immediately free was dispatched with an already-expired
deadline and timed out in the wait leg instead — so the rule above held
only under contention, the one case where it is hardest to observe.

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

## Timed-out requests keep their slot

For every dispatched request LCS keeps a **request record** until a
matching response is processed or the connection is torn down. <a id="cite-source.dispatch.record-kept-until-response-or-teardown"></a>

The record holds the request id, the operation code, the transaction
id, the key GUID it concerns, the runtime limits in force, and any
retained effect the kernel will need if the source later reports
success. <a id="cite-source.dispatch.record-contents"></a>

When the deadline expires after dispatch, LCS detaches the waiting
caller from the record and returns `ETIMEDOUT`. <a id="cite-source.dispatch.timeout-detaches-caller-from-record"></a>

A signal that interrupts the wait after dispatch detaches the caller
the same way, and the call fails with `EINTR` or is restarted. As after
a timeout, the source may still apply the request when it answers. A
response that completed before the caller could be detached wins: the
caller gets that response's result, with the signal still pending. <a id="cite-source.dispatch.completion-beats-a-signal"></a>

**The record stays in the in-flight table and keeps counting against
`MaxConcurrentRSIRequests`.** A timeout does not free a slot; only a
response or a teardown does. <a id="cite-source.dispatch.timeout-does-not-free-a-slot"></a>

A source that accumulates timed-out requests can therefore exhaust its
own in-flight slots until it answers or disconnects. That is the
intended shape: a source that stops answering stops being usable.

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

## Requests with no caller

LCS dispatches some requests with nobody waiting: `RSI_DROP_KEY` after
the last fd to an orphaned key closes ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)), and
`RSI_ABORT_TRANSACTION` cleaning up source transaction state. <a id="cite-source.dispatch.callerless-requests-are-dispatched"></a>

Such a record occupies an in-flight slot and is retained like any
other, and its response is validated normally and released normally. <a id="cite-source.dispatch.callerless-record-occupies-a-slot"></a>

But it is **not** a late response, and the retained-effect recovery
rules do not apply to it merely because nobody is waiting. <a id="cite-source.dispatch.callerless-is-not-a-late-response"></a>

The kernel tracks the difference explicitly, with two booleans: whether
a waiter is attached now, and whether one was ever attached. A record
that never had a caller is not a timed-out request; only one whose
caller was detached after its deadline is. <a id="cite-source.dispatch.timed-out-means-caller-detached-after-deadline"></a>

This is load-bearing rather than pedantic. `RSI_DROP_KEY` is a mutating
operation, so without the distinction a perfectly ordinary answer to a
caller-less cleanup request would look like a mutation the kernel could
not account for, and would tear the source down.

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

## The channel

`/dev/pkm_registry` is message-oriented. One `read()` returns exactly
one complete request; a buffer too small for the next one returns
`EMSGSIZE` **without consuming it**. <a id="cite-source.dispatch.read-returns-one-request-or-emsgsize"></a>

An empty queue blocks, or returns `EAGAIN` under `O_NONBLOCK`, or
returns 0 if the fd is closing. <a id="cite-source.dispatch.empty-queue-blocks-or-eagain"></a>

One `write()` submits exactly one complete response, and its length
must equal the response's own `total_len` exactly. <a id="cite-source.dispatch.write-submits-one-response-of-exact-length"></a>

`poll` reports the fd readable when a request is queued, writable while
the slot is Active, and `POLLHUP | POLLERR` when the slot is Down or
the fd is closing. <a id="cite-source.dispatch.poll-reports-queue-and-slot-state"></a>

An fd that is open but has not yet registered reports nothing at all. <a id="cite-source.dispatch.unregistered-fd-polls-nothing"></a>

Any rejected `write()` — short, over-long, an unknown or duplicate
request id, an operation code that does not match the request, a
response for another connection — returns `EINVAL` **and tears the
connection down**. <a id="cite-source.dispatch.rejected-write-is-einval-and-tears-down"></a> A source that cannot speak the protocol correctly is
not one whose other answers are worth believing.

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

## Negotiated lifetime control

Sources may negotiate lifetime extension version 1 with `REG_SRC_NEGOTIATE`
before `REG_SRC_REGISTER`. Pass version 1, zero flags and zero session; the
kernel returns a nonzero session identifier unique to the open source file.
The RSI request and response frame layouts are unchanged. Sources that do not
negotiate retain the legacy protocol; current loregd requires this extension.
<a id="cite-source.dispatch.lifetime-extension-is-negotiated-before-registration"></a>

After reading a request and before responding, `REG_SRC_REQUEST_CONTEXT` takes
that session and request id and returns three absolute `CLOCK_MONOTONIC`
nanosecond timestamps: the request deadline, transaction lifetime deadline and
cleanup lease deadline. Zero lifetime means an operation-owned transaction
with no separate lifetime ceiling. Zero lease means there is no live transaction
owner. Request metadata remains queryable after caller detachment until the
response is accepted, so cleanup and late-response handling still work.
<a id="cite-source.dispatch.context-preserves-the-original-request-deadline"></a>

`REG_SRC_RENEW` takes the session and transaction id and returns the original
lifetime deadline plus a renewed cleanup deadline, at most five seconds from
now and never beyond the lifetime deadline. It succeeds only for an existing,
nonterminal transaction owned by a live file object or kernel operation on
this source session. Unknown, released, expired and foreign-session identities
return `ESTALE`. Once a lease expires, renewal cannot resurrect it. These
control ioctls consume no ordinary request slots, so request-queue saturation
does not starve renewal.
<a id="cite-source.dispatch.lease-renewal-requires-a-live-owner-and-session"></a>

Final owner release and abort prevent renewal before abort-message delivery.
Client lifetime expiration also prevents renewal. Sources must reject new
operations after expiry and serialize rollback with operations and commit;
an already-admitted commit must resolve its actual outcome. Lease cleanup
does not change the kernel's treatment of late commit responses ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).
<a id="cite-source.dispatch.lease-expiry-does-not-infer-a-commit-outcome"></a>

---

# Validation

_Peios Kernel / Internals / LCS / Sources_

> LCS validates every response before using it — malformed data against malformed protocol, and the asymmetric extensibility between them.

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

LCS validates every response before using it, and the failures split
into two categories with very different consequences. <a id="cite-source.validate.every-response-is-validated"></a>

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

## Malformed data

The RSI message is structurally valid but its content is not: a
descriptor that will not parse, a value type that does not exist, a
sequence number that cannot be real, a metadata block that does not
cover the GUIDs it should.

- The request returns `EIO` to its caller. <a id="cite-source.validate.malformed-data-returns-eio"></a>
- An `lcs.source.response.rejected` audit event is emitted, naming the
  source slot and — where known — the hive, the request id, the
  operation code, the key GUID, and which of the twelve validation
  classes applies ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-source.validate.malformed-data-emits-an-audit-event"></a>
- **The source stays alive.** Corruption may be localised, and one bad
  key is not a reason to take a hive offline. <a id="cite-source.validate.malformed-data-keeps-the-source-alive"></a>

What is checked, by category:

- **Security Descriptors**, from lookups and from layer metadata
  refreshes, must parse and must satisfy the ACE mask rules of [Access Rights](</kernel/internals/lcs/security/access-rights.md#trm-5-4-2>). <a id="cite-source.validate.descriptors-must-parse"></a>
  A malformed layer metadata descriptor additionally leaves the
  previous known-good one cached ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)).
- **Names** — layer names, key and child names, value names — must be
  valid under the ordinary rules for their kind. <a id="cite-source.validate.names-must-be-valid"></a>
- **Sequence numbers** must be below the next number LCS would
  allocate, and must not duplicate at the same precedence in a way that
  would decide a winner ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-source.validate.sequence-number-checks"></a>
- **Payload shape** — an otherwise-matched response whose
  operation-specific payload is the wrong shape, carries trailing
  bytes, or encodes a path target invalidly. <a id="cite-source.validate.payload-shape-checks"></a>
- **Metadata closure** — a lookup or enumeration whose per-GUID
  metadata block has missing, duplicate, unreferenced or nil entries. <a id="cite-source.validate.metadata-closure-checks"></a>
  A HIDDEN entry must carry an all-zero GUID and contributes no
  metadata. <a id="cite-source.validate.hidden-entry-carries-a-zero-guid"></a>
- **Value payloads** — invalid types, a tombstone carrying data, data
  above `MaxValueSize`. <a id="cite-source.validate.value-payload-checks"></a>
- **Orphan lists** — a nil or duplicated GUID in an `RSI_DELETE_LAYER`
  response. <a id="cite-source.validate.orphan-list-checks"></a>
- **Status codes** outside the defined vocabulary. <a id="cite-source.validate.unknown-status-code"></a>

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

## Malformed protocol

The message itself is structurally invalid: bad framing, a truncated
response, an unknown request id, a duplicate response, an operation
code that does not match the request.

This is treated as a source crash. The connection is torn down, the
in-flight table is destroyed with every waiter completed `EIO`, the
slot is marked Down, its hives become unavailable, and bound
transactions enter `SOURCE_DOWN`. <a id="cite-source.validate.malformed-protocol-is-treated-as-a-crash"></a>

There is one case where malformed *data* also takes the source down:
when the caller had already timed out and the operation was a commit or
a replayable mutation. At that point LCS cannot establish whether a
mutation was applied, and it cannot account for one it cannot describe
([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

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

## Asymmetric extensibility

Requests and responses do not extend the same way.

A **request** may carry trailing fields a source does not recognise; a
source skips them using `total_len`. <a id="cite-source.validate.requests-may-carry-trailing-fields"></a> That is how a new optional field
is added without an RSI version bump.

A **response** may not. LCS rejects any trailing bytes in a response
payload as malformed data. Forward compatibility on the response side
comes from new operations, not from extending existing payloads.

---

# Failure and Late Responses

_Peios Kernel / Internals / LCS / Sources_

> What happens when a source dies, and the late-response problem — a late error, a late successful read, and a late successful write.

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

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

## When a source dies

The connection closes unexpectedly, and:

1. The slot is marked Down and its hives become unavailable. <a id="cite-source.failure.slot-marked-down-hives-unavailable"></a>
2. Every pending request fails `EIO`, including ones queued but not yet
   delivered. <a id="cite-source.failure.pending-requests-fail-eio"></a>
3. **Open key fds stay valid.** An fd holds a GUID and a granted mask,
   and neither depends on the source. Operations needing a round trip
   return `EIO` until the source comes back. <a id="cite-source.failure.key-fds-stay-valid-round-trips-eio"></a>
4. Bound transactions enter `REG_TXN_SOURCE_DOWN`, their poll waiters
   are woken with `POLLERR | POLLHUP`, their mutation logs are
   released, and further use of those fds returns `EIO`. <a id="cite-source.failure.bound-transactions-enter-source-down"></a>
5. **Watches stay armed.** Watch state is kernel-side and does not
   depend on the source at all. <a id="cite-source.failure.watches-stay-armed"></a> Nothing is delivered during the window,
   and `OVERFLOW` arrives on re-registration rather than on disconnect
   ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Coming back is covered in [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>).

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

## The late response problem

A caller that times out after its request was dispatched is gone, but
the request is not. The source may still apply the operation and answer
minutes later, and by then there is nobody to return a value to — while
the *kernel* still has work to do, because a mutation that succeeded
has to produce its generation increment and its watch events.

This is the most intricate part of LCS and the part with the most ways
to be subtly wrong.

A late response is validated exactly like an on-time one. <a id="cite-source.late.validated-like-an-on-time-response"></a> The rules
that follow apply **only** to a request whose caller was detached after
its deadline, never to one that never had a caller ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)).

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

### A late error <a id="cite-source.late.error-has-no-effects"></a>

The record is released. No watch events, no generation change, nothing.

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

### A late successful read <a id="cite-source.late.read-is-validated-then-discarded"></a>

Validated, then discarded. There is nobody to give it to and nothing
about it changes kernel state.

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

### A late successful mutation

The kernel-side effects that correspond to the mutation are applied
from the retained record: the hive generation increment, watch
dispatch, the layer metadata cache refresh, and — for a commit — the
transaction's batch effects and orphan tracking. <a id="cite-source.late.mutation-applies-retained-effects"></a>
The watch dispatch takes the recovery form: a watcher receives an
`OVERFLOW` ahead of the event itself ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Which mutations can actually be replayed is narrower than the set of
operations that count as mutating. A replayable effect is recorded for
`RSI_SET_VALUE` and `RSI_WRITE_KEY`, and only for non-transactional
calls. <a id="cite-source.late.replayable-effects-only-for-set-value-and-write-key"></a>

For the other mutating operations — creating, hiding or deleting a path
entry, creating or dropping a key, deleting a value entry, setting a
blanket tombstone, deleting a layer — no effect was retained, so a late
success is a mutation the kernel cannot account for. LCS tears the
source down and returns `EIO` rather than silently ignoring it. <a id="cite-source.late.unreplayable-mutation-tears-source-down"></a>

That is the conservative direction, and deliberately so: the
alternative is a committed change with no watch event and a stale
generation number, which nothing downstream could detect.

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

### A late successful transaction operation

A late `RSI_BEGIN_TRANSACTION` has created transaction state in the
source that nobody will ever use, so LCS enqueues an
`RSI_ABORT_TRANSACTION` for that id. <a id="cite-source.late.begin-transaction-enqueues-an-abort"></a>

A late `RSI_ABORT_TRANSACTION` or `RSI_FLUSH` releases the record with
no effects. <a id="cite-source.late.abort-or-flush-releases-the-record"></a>

A late `RSI_COMMIT_TRANSACTION` is a mutating response and applies the
retained commit effects — the same generation update and the same watch
events an on-time commit would have produced. <a id="cite-source.late.commit-applies-retained-commit-effects"></a> Watchers may therefore
observe the effects of a transaction whose caller was told it timed
out ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

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

### A malformed late response

The ordinary malformed-data and malformed-protocol rules apply. But if
LCS cannot safely process the kernel-side effects of a
possibly-applied mutation because the request metadata it needs is
missing or invalid, it tears the source down and marks it Down rather
than ignoring the response. <a id="cite-source.late.unprocessable-effects-tear-source-down"></a>

A malformed late commit response takes the source down for the same
reason. <a id="cite-source.late.malformed-commit-tears-source-down"></a>

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

## What a caller should conclude

`ETIMEDOUT` means *may or may not have completed*. A caller that needs
certainty reads state back before retrying. That applies to every
operation and, especially, to a transaction commit.

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

## Fd lifecycle

Key fds and transaction fds are ordinary file descriptors, subject to
`RLIMIT_NOFILE`. There is no registry-specific fd accounting and no
registry-specific leak protection. <a id="cite-source.failure.no-registry-specific-fd-accounting"></a>

Process exit closes them through normal kernel cleanup: key fds
released and their watches removed, transactions aborted. <a id="cite-source.failure.process-exit-releases-fds"></a>

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

## Memory

Registry kernel memory needs no global cap, because everything is
bounded by limits that already exist.

- **Watch queues:** `NotificationQueueSize` per queue, times
  `RLIMIT_NOFILE` queues per process.
- **Open key state:** per-fd overhead — GUID, granted mask, ancestor
  chain, watch state — times the same fd limit.
- **Layer table:** bounded by `MaxTotalLayers`, and per-value
  resolution cost by `MaxLayersPerValue`.
- **In-flight requests:** bounded per source by
  `MaxConcurrentRSIRequests`, and separately by the number of threads
  blocked on registry syscalls.

---

# Backup and restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Find the Peios kernel articles about backup and restore.

Use these articles to understand backup and restore in the Peios kernel.

- [The Stream](</kernel/internals/lcs/backup-and-restore/the-stream.md>)
- [Backup](</kernel/internals/lcs/backup-and-restore/backup.md>)
- [Restore](</kernel/internals/lcs/backup-and-restore/restore.md>)

---

# The Stream

_Peios Kernel / Internals / LCS / Backup and restore_

> The streamable binary representation of a key and everything beneath it with full layer fidelity — what the design buys, and how it is versioned.

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

The registry backup format is a streamable binary representation of a
key and everything beneath it, with full layer fidelity. It is used by
`REG_IOC_BACKUP` and `REG_IOC_RESTORE`, by first-boot seeding, by
disaster recovery and by offline migration.

It is an **LCS-level** format. Sources never see it: LCS serialises
from source data on the way out and deserialises into RSI operations on
the way in. <a id="cite-backup.stream.lcs-level-sources-never-see-it"></a>

Because a third party writes and reads these streams directly — that is
what migration and recovery mean — the format is a normative
specification rather than a description. It is a chapter of PSPK, and
every byte layout, record type, ordering rule and validation
requirement lives there. This section covers what LCS does with it.

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

## What the design buys

**Streamable.** It is written to an arbitrary fd — a file, a pipe, a
socket — with no seeking, in a single pass, and read back the same way. <a id="cite-backup.stream.written-and-read-without-seeking"></a>

**Full layer fidelity.** Every path entry, value, tombstone and blanket
tombstone is stored with its layer tag, so restoring reconstructs the
layered state rather than a flattened snapshot of it. <a id="cite-backup.stream.entries-carry-their-layer-tag"></a>

**Depth-first pre-order.** A parent always appears before its children,
so a restore can create keys top-down without buffering a tree. <a id="cite-backup.stream.depth-first-pre-order"></a>

**Descriptors inline.** Each key record carries its own descriptor with
no deduplication. <a id="cite-backup.stream.descriptors-inline-without-dedup"></a> Redundancy is external compression's problem; piping
through zstd handles it.

**Self-verifying.** A trailer carries a record count and a SHA-256 over
everything before it, so truncation and corruption are detected. <a id="cite-backup.stream.trailer-carries-count-and-sha256"></a>

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

## Versioning

The header carries a format version and a **minimum reader version**. A
writer that used only older features sets a lower minimum, letting
older readers restore the stream. <a id="cite-backup.stream.header-carries-version-and-minimum-reader"></a>

A reader that finds a minimum above its own supported version rejects
the stream outright, before touching anything. <a id="cite-backup.stream.rejects-minimum-above-supported-version"></a>

Both are 21 in the current implementation, and the reader supports 21. <a id="cite-backup.stream.current-version-is-21"></a>

Unknown record types are skipped when the minimum reader version allows
it, and they still count toward the record count and the checksum. <a id="cite-backup.stream.unknown-records-skipped-but-counted"></a> A
writer that adds a record type a restore genuinely needs must raise the
minimum reader version, so that an older reader refuses the stream
rather than restoring an incomplete one.

Extension is by new **record types** only. Existing record payloads
must be consumed exactly; trailing bytes inside a known record are an
error. <a id="cite-backup.stream.trailing-bytes-in-a-record-are-an-error"></a> This is the opposite of the RSI's request convention ([Validation](</kernel/internals/lcs/sources/validation.md#trm-5-8-4>)),
and the difference is deliberate: a stream is replayed into mutations
long after it was written, and a field silently ignored there is data
silently lost.

---

# Backup

_Peios Kernel / Internals / LCS / Backup and restore_

> Writing a subtree to a stream under SeBackupPrivilege with no per-key access check — the snapshot, the audit, and what is written.

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

`REG_IOC_BACKUP` exports the key on the fd and its entire subtree to
another fd, preserving parent/child relationships even when traversal
must grow its internal storage. <a id="cite-backup.exports-the-key-and-its-subtree"></a>

It requires `SeBackupPrivilege` and performs **no per-key AccessCheck**
whatsoever. <a id="cite-backup.requires-sebackupprivilege-and-checks-no-key"></a> The privilege is the whole authorisation, which is
why the operation is audited unconditionally ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)).

The output fd must be writable, or `EBADF`. <a id="cite-backup.output-fd-must-be-writable"></a>

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

## The snapshot

Before reading anything, LCS opens a **read-only** source transaction —
`RSI_BEGIN_TRANSACTION` with mode `RSI_TXN_READ_ONLY` — so that the
whole export is a point-in-time snapshot. Concurrent mutations do not
appear part-way through the stream. <a id="cite-backup.opens-a-read-only-snapshot-transaction"></a>

That transaction is **released with `RSI_ABORT_TRANSACTION` and never
committed**. There is no commit call anywhere in the backup path; a
read-only transaction has nothing to commit. <a id="cite-backup.snapshot-released-with-abort-never-committed"></a>

A source that does not support read-only snapshots answers
`RSI_TXN_NOT_SUPPORTED` and the backup fails `ENOTSUP`. <a id="cite-backup.unsupported-snapshot-is-enotsup"></a>

A source already holding `MaxReadOnlyTransactionsPerSource` snapshots
(default 16) yields `EBUSY` — which bounds snapshot-holding without
treating backups as write-lock holders, since they are not. <a id="cite-backup.snapshot-limit-is-ebusy"></a>

Backing up an orphaned key is `ENOENT`: it is no longer a reachable
subtree root ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)). <a id="cite-backup.orphaned-key-is-enoent"></a>

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

## Audit

`lcs.audit.backup.started` is emitted **before any subtree data is read**, and
if it cannot be emitted the backup returns `EIO` and does not start. <a id="cite-backup.start-event-precedes-any-data-or-eio"></a>

After privilege, output-fd and key validation, START precedes the request for
the read-only snapshot. A refused or failed snapshot therefore emits both
START and END, with END carrying the failure errno; no subtree is exported
and no unopened snapshot is released. A START emission failure prevents the
snapshot request itself. <a id="cite-backup.snapshot-refusal-is-audited"></a>

`lcs.audit.backup.ended` is emitted afterwards, carrying the result, and a
failure to emit it cannot change a result that has already happened. <a id="cite-backup.complete-event-cannot-change-the-result"></a>

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

## What is written

The stream is a header, the layer manifest, then each key in
depth-first pre-order with its path entries, values and blanket
tombstones, then the trailer. The exact shapes are in the PSPK chapter.

Two things about the exporter are worth stating here, because they
constrain a reader more tightly than the format does.

The exporter writes **no GUID-bearing path entries for the backup
root**. The root's section contains only its hidden entries. <a id="cite-backup.root-section-has-no-guid-path-entries"></a>

A reader tolerates and skips them if some other writer produces them,
but this one does not emit them, because on restore the target key's
existing name is authoritative and they would be discarded anyway. <a id="cite-backup.reader-skips-root-path-entries"></a>

Hidden entries belong to the **parent's** section, not to a section of
their own — a hidden entry has no key to have a section for. <a id="cite-backup.hidden-entries-live-in-the-parent-section"></a>

A hidden entry masking a name where no key exists in any layer is still
valid; it expresses "this layer hides this name" whether or not
anything is there to hide. <a id="cite-backup.hidden-entry-without-a-key-is-valid"></a>

The layer manifest is written from the live layer table, and it is a
manifest: it records what the layers looked like at backup time so that
a restore can validate the stream against them. It is not a backup of
the layer definitions. <a id="cite-backup.manifest-is-written-from-the-live-layer-table"></a>

A layer definition is backed up only when
`Machine\System\Registry\Layers\<Name>\` is itself inside the subtree
being exported, in which case it is ordinary key and value data like
anything else. <a id="cite-backup.layer-definition-backed-up-only-if-inside-the-subtree"></a>

This includes definitions for unused layers in a whole-hive export.
Their metadata remains ordinary registry data; an unused definition
does not by itself require an entry in the layer manifest.

---

# Restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Restore is a replace rather than a merge — one transaction, the surviving target key, the order of operations, and the precedence gate.

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

`REG_IOC_RESTORE` **replaces** the key on the fd and its entire subtree
from a stream. It is not a merge: the target's contents and descendants
are torn down before the stream's contents are written. <a id="cite-restore.replaces-rather-than-merges"></a>

It requires `SeRestorePrivilege` and, like backup, performs no per-key
AccessCheck and is audited unconditionally. <a id="cite-restore.requires-serestoreprivilege-and-checks-no-key"></a>

The input fd must be readable, or `EBADF`. <a id="cite-restore.input-fd-must-be-readable"></a> Restoring onto an orphaned
key is `ENOENT`. <a id="cite-restore.orphaned-target-is-enoent"></a>

Because restore rewrites every descriptor in the subtree,
`SeRestorePrivilege` effectively confers `WRITE_DAC` and `WRITE_OWNER`
over everything within reach of one ([The Source Model](</kernel/internals/lcs/sources/the-source-model.md#trm-5-8-1>)).

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

## One transaction

The entire restore — teardown and rebuild together — is wrapped in a
single read-write source transaction. <a id="cite-restore.wrapped-in-one-read-write-transaction"></a>

A source that answers `RSI_TXN_NOT_SUPPORTED` for `RSI_TXN_READ_WRITE`
cannot be a restore target: restore requires atomicity and there is no
partial-restore mode. <a id="cite-restore.requires-read-write-transaction-support"></a>

Every failure path aborts the transaction, so a failed restore rolls
back the teardown as well. <a id="cite-restore.failure-rolls-back-the-teardown"></a>

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

## The target key survives

The stream's header names a root GUID, and that GUID is **remapped** to
the already-open target key everywhere it appears — in parent
references, in child references, in value key references — before
anything is validated or dispatched. <a id="cite-restore.root-guid-remapped-to-the-target"></a>

The target key **object** is not replaced. Its GUID, parent, name,
volatile flag and symlink flag remain what they were; they are never
taken from the stream. <a id="cite-restore.target-key-object-is-not-replaced"></a>

What the stream's root record supplies is the mutable part: the
Security Descriptor and the last write time, written to the target with
`RSI_WRITE_KEY` inside the transaction. <a id="cite-restore.root-record-supplies-descriptor-and-write-time"></a>

The root record's immutable flags must **match** the target's. A backup
of a volatile key restored onto a non-volatile one, or a symlink onto a
non-symlink, is `EINVAL`. <a id="cite-restore.immutable-flag-mismatch-is-einval"></a>

Descendants keep their backup GUIDs. Those are written into the target
verbatim. <a id="cite-restore.descendants-keep-their-backup-guids"></a>

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

## Order of operations

1. Validate the whole stream, including the trailer's record count and
   checksum, and retain every replayable record. <a id="cite-restore.validates-the-whole-stream-first"></a>
2. Read the layer manifest and apply the precedence gate (below).
3. Verify the root record and its immutable flags against the live
   target.
4. Tear down the target's contents and descendants — path entries,
   values, blanket tombstones, and descendant key records — inside the
   transaction. <a id="cite-restore.tears-down-the-target-inside-the-transaction"></a>
5. Write the root's mutable fields, then replay its section's values
   and blanket tombstones. <a id="cite-restore.writes-root-mutable-fields-then-its-section"></a>
6. For each non-root key in stream order: create it, write its last
   write time, then replay its path entries, values and blanket
   tombstones. <a id="cite-restore.replays-non-root-keys-in-stream-order"></a>
7. Commit.

The stream is read from the fd exactly once, sequentially. Nothing
seeks, so a pipe is a valid input. <a id="cite-restore.stream-read-once-sequentially"></a>

Validating the whole stream first is stronger than the format requires:
a checksum failure aborts before any source mutation rather than after
some. The cost is memory rather than seeking — the replayable records
are retained in kernel memory across the teardown.

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

## The precedence gate

Before any key record is written, LCS checks the layer manifest. If any
declared layer has a precedence above 0, **or** any existing cached
layer table entry with the same folded identity does, and the caller
does not hold `SeTcbPrivilege`, the restore aborts with `EPERM` before
a single byte reaches the source. <a id="cite-restore.precedence-gate-is-eperm-without-setcbprivilege"></a>

And if the stream contains ordinary key and value records for
`Machine\System\Registry\Layers\<Name>\`, writes that create or raise
persisted metadata above precedence 0 hit the ordinary inline
`SeTcbPrivilege` check as well ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

Both exist so that `SeRestorePrivilege` cannot be used to smuggle a
Group Policy-tier layer past the defence in depth that guards
precedence.

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

## Layers in a restored stream

Manifest records create, update, delete, enable, disable and authorise
nothing. <a id="cite-restore.manifest-records-change-no-layers"></a>

If restored entries reference a layer that is not in the current table,
and the stream does not also restore that layer's metadata subtree as
ordinary registry data, those entries become latent unknown-layer
entries and are ignored during resolution until real metadata exists
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-restore.unknown-layer-entries-become-latent"></a>

If the metadata subtree *is* included, it is restored through the
ordinary path, and those records — not the manifest — are what define
the layer. <a id="cite-restore.included-metadata-subtree-defines-the-layer"></a>

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

## Sequence remapping

Backup sequence numbers preserve the backup's internal ordering, but a
restore is a new mutation and its entries must outrank everything
already present. So the numbers are remapped rather than written
through. <a id="cite-restore.sequences-are-remapped-not-written-through"></a>

Before dispatching the first layer-qualified record, LCS takes the
global sequence-allocation gate and records the current next sequence
as the offset. <a id="cite-restore.takes-the-sequence-gate-before-the-first-record"></a>

Every restored record is then written with `offset + backup_sequence`,
which preserves relative order while placing the whole set above
pre-restore state. <a id="cite-restore.remapped-sequence-is-offset-plus-backup"></a>

The gate is held until the restore reaches a terminal state. Other
sequence-allocating mutations wait; reads are not blocked. <a id="cite-restore.gate-blocks-mutations-not-reads"></a>

A restore with no layer-qualified records at all never takes it. <a id="cite-restore.no-layer-records-never-takes-the-gate"></a>

If a remapped value would overflow, the restore fails `EOVERFLOW` — and
it fails at validation, before teardown, rather than part-way through. <a id="cite-restore.sequence-remap-overflow-is-eoverflow"></a>
The valid remapped range stops just below `U64_MAX`, which is never
handed out ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

When the restore reaches any terminal state — commit, abort, failure or
cancellation — LCS advances the global counter past the highest number
it dispatched, and **does not roll that back**. <a id="cite-restore.counter-advanced-at-any-terminal-state"></a> Sequence numbers a
failed restore dispatched become unused gaps, exactly like those of any
other failed write.

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

## GUID collisions

A GUID that appears twice in one stream, other than the root, is
`EINVAL`. <a id="cite-restore.duplicate-guid-in-the-stream-is-einval"></a> So is a non-root GUID equal to the target root's. <a id="cite-restore.non-root-guid-equal-to-the-root-is-einval"></a>

A non-root GUID that already exists **outside** the subtree being
replaced is `EEXIST` — but it is discovered by the source rejecting the
create during replay, not by a check beforehand. LCS has no index of
which GUIDs exist elsewhere, so the collision surfaces mid-restore, and
the transaction rolls back. <a id="cite-restore.external-guid-collision-is-eexist-mid-restore"></a>

The parent of every path entry, after remapping, must be either the
restore root or a key record already processed earlier in the stream. <a id="cite-restore.path-entry-parent-must-be-in-the-stream"></a>
That check *is* made up front, and it is what stops a crafted backup
injecting path entries into arbitrary parts of the existing namespace
outside the subtree being replaced.

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

## Watches

A restore is an arbitrary subtree replacement and LCS retains no exact
before-and-after diff for it. On a successful commit it publishes the
affected hive's generation increment and dispatches a no-name
`OVERFLOW` to the armed watches on that source ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-restore.commit-publishes-generation-and-overflow"></a>

A restore that fails or aborts before commit emits nothing. <a id="cite-restore.failed-restore-emits-nothing"></a>

---

# Bootstrap

_Peios Kernel / Internals / LCS / Bootstrap_

> Find the Peios kernel articles about bootstrap.

Use these articles to understand bootstrap in the Peios kernel.

- [Dependencies and boot sequence](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md>)
- [Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md>)
- [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md>)

---

# Dependencies and boot sequence

_Peios Kernel / Internals / LCS / Bootstrap_

> The registry has to configure itself — the three circular dependencies, and the three rules that break them.

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

The registry is the configuration store for the whole system, and it
has to configure itself. Three circular dependencies have to be broken
before it can serve anyone.

**peinit needs the registry to start services, but the registry source
is a service.** Service definitions live in the registry, and the
process that would serve them has not started.

**LCS needs operational parameters from the registry, but the registry
needs LCS.** Timeouts, caps and limits live under
`Machine\System\Registry\`, in a hive LCS itself routes.

**A fresh install has no data at all.** The source's database is empty;
there is nothing to read.

Three rules break all three.

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

## Rule 1: compiled-in defaults

Every operational parameter has a compiled-in default, and LCS runs on
those defaults from the moment PKM initialises. <a id="cite-boot.defaults-active-from-init"></a>

There is no "waiting for configuration" state, no flag, and no wait
queue: the limits structure is statically initialised at load, the
source char device is registered without consulting configuration, and
the first attempt to read configuration happens on a workqueue after a
source has already registered. <a id="cite-boot.no-waiting-for-configuration-state"></a>

Before any source registers, the routing table is empty, so every
operation that names a hive returns `ENOENT`. <a id="cite-boot.empty-routing-table-enoent"></a>
That is the only sense in which LCS is not yet useful, and it is not a
distinct state — it is just an empty table.

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

## Rule 2: the base layer exists unconditionally

The base layer is a static constant in the kernel: name `base`,
precedence 0, enabled. It is handed out whenever the dynamic layer
table is empty and is always written first into every layer snapshot.

A source that registers with an entirely empty database is fully
functional, because the one layer that writes need is not in the
database. Persisted metadata under
`Machine\System\Registry\Layers\base\` may exist and may decorate the
base layer, but it is not required and cannot contradict it ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)).

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

## Rule 3: hot-swap, not restart <a id="cite-boot.hot-swap-not-restart"></a>

When configuration becomes available, LCS reads it, validates it, and
swaps the values in place. It does not restart, re-initialise, or
block. The whole transition from compiled-in defaults to registry-backed
configuration is driven by the internal self-watch ([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

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

## Source dependencies are the source's problem <a id="cite-boot.source-dependencies-not-lcs-concern"></a>

LCS neither knows nor cares what a source depends on. A source that
needs the root filesystem, a SYSTEM token, or a particular kernel
feature arranges that for itself. LCS's only requirement is that the
process can open `/dev/pkm_registry` and speak RSI.

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

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

## Normal boot <a id="cite-boot.normal-sequence"></a>

```
Kernel boots
  → PKM initialises; LCS runs on compiled-in defaults
  → /dev/pkm_registry registered
  → the base layer exists in memory

A source registers — loregd, started by peinit
  → opens /dev/pkm_registry (SeTcbPrivilege checked at open)
  → REG_SRC_REGISTER: hive names, root GUIDs, max persisted sequence
  → LCS initialises or advances next_sequence to max + 1

Bootstrap refresh is queued
  → resolve Machine\System\Registry     → read and hot-swap parameters
  → resolve Machine\System\Registry\Layers → populate the layer table
  → arm internal subtree watches
```

The bootstrap refresh runs on a workqueue after `REG_SRC_REGISTER`
returns, so registration never blocks on configuration and a source
that registers can start answering immediately. <a id="cite-boot.refresh-on-workqueue-after-register"></a>

The refresh is triggered by the arrival of a **global hive named
`Machine`**. <a id="cite-boot.refresh-triggered-by-machine-hive"></a> That name is matched case-insensitively in the
kernel and is one of the two hive names LCS knows about; the other is
`Users`, the target of `CurrentUser\` rewriting ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)). Neither is a
routing decision — routing is entirely dynamic — but the claim that the
kernel holds no hive names at all would not be true.

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

## First boot <a id="cite-boot.first-boot-retains-defaults"></a>

An empty source has no `Machine\System\Registry` to read.

```
Source detects an empty database on first startup
  → generates root GUIDs for the hives it backs
  → creates root key records with their default SDs
  → persists them, then registers with LCS

LCS resolves Machine\System\Registry → does not exist
  → compiled-in defaults retained
  → subtree watch armed on the Machine\ hive root instead

peinit notices the registry is empty and restores the seed backup.
That is peinit's decision, not LCS's.

Seed restore populates Machine\ through REG_IOC_RESTORE
  → the fallback subtree watch fires
  → LCS re-runs the bootstrap refresh: resolves the specific GUIDs,
    re-arms targeted watches, validates and hot-swaps the seed values,
    and re-reads layer metadata
```

Hive root Security Descriptors are set by the source, not by LCS. LCS
holds no template for them and enforces whatever the source stores
([Inheritance and Hive Roots](</kernel/internals/lcs/security/inheritance-and-hive-roots.md#trm-5-4-3>)).

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

## Watch arming in practice

The spec-level description above says the fallback watch is armed
*instead of* the targeted ones. What the kernel actually arms is a
**mixed** set: targeted watches on whichever of the two roots exist,
*plus* the `Machine\` root fallback. The fallback is a superset rather
than a substitute, and it stays armed until a refresh finds both roots
present.

A third internal watch is armed by the same sequence, on
`Machine\System\KMES`, which is not LCS configuration at all — it is
how KMES picks up its own parameters from the registry LCS serves.

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

## The bootstrap contract

Four properties hold throughout and are relied on elsewhere:

1. **LCS is always operational with compiled-in defaults.** It accepts
   syscalls from the moment PKM initialises.
2. **The base layer requires no persisted state.**
3. **Hot-swap is the only configuration transition.** LCS never blocks,
   restarts, or re-initialises.
4. **Source dependencies are the source's concern.**

---

# Operational Parameters

_Peios Kernel / Internals / LCS / Bootstrap_

> The nineteen parameters LCS reads from the registry, how they are validated, and what hot-swapping one does to in-flight operations.

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

LCS reads nineteen parameters from `Machine\System\Registry\`. <a id="cite-param.nineteen-under-registry-key"></a>

All are `REG_DWORD`. <a id="cite-param.all-are-reg-dword"></a> Each has a compiled-in default and a valid
range, and LCS runs on the defaults until the registry says otherwise.

| Value | Default | Range | Bounds |
|---|---:|---|---|
| `RequestTimeoutMs` | 30000 | 1000–600000 | A source round trip ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)). <a id="cite-param.request-timeout-ms"></a> |
| `TransactionTimeoutMs` | 30000 | 1000–600000 | The lifetime of an open transaction ([Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>)). <a id="cite-param.transaction-timeout-ms"></a> |
| `NotificationQueueSize` | 256 | 16–65536 | Queued events per watcher before overflow ([Queues and Overflow](</kernel/internals/lcs/watches/queues-and-overflow.md#trm-5-6-4>)). <a id="cite-param.notification-queue-size"></a> |
| `SymlinkDepthLimit` | 16 | 1–64 | Symlink resolution depth ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)). <a id="cite-param.symlink-depth-limit"></a> |
| `MaxValueSize` | 1048576 | 4096–67108864 | One value's data, in bytes. <a id="cite-param.max-value-size"></a> |
| `MaxKeyDepth` | 512 | 32–4096 | Key hierarchy nesting. <a id="cite-param.max-key-depth"></a> |
| `MaxPathComponentLength` | 255 | 64–1024 | One key, value or layer name, in UTF-8 bytes. <a id="cite-param.max-path-component-length"></a> |
| `MaxTotalPathLength` | 16383 | 1024–65535 | A whole path, in UTF-8 bytes. <a id="cite-param.max-total-path-length"></a> |
| `MaxLayersPerValue` | 128 | 1–1024 | Layers writing to one `(key, value name)` ([The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>)). <a id="cite-param.max-layers-per-value"></a> |
| `MaxBoundTransactionsPerSource` | 16 | 1–256 | Concurrently bound transactions per source ([Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>)). <a id="cite-param.max-bound-transactions-per-source"></a> |
| `MaxReadOnlyTransactionsPerSource` | 16 | 1–256 | Concurrent public read transactions and backup snapshots per source ([Backup](</kernel/internals/lcs/backup-and-restore/backup.md#trm-5-9-2>)). <a id="cite-param.max-read-only-transactions-per-source"></a> |
| `MaxTotalLayers` | 1024 | 16–65536 | Distinct layers in the in-memory table ([The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>)). <a id="cite-param.max-total-layers"></a> |
| `MaxRegisteredSources` | 32 | 1–256 | Concurrently registered sources. <a id="cite-param.max-registered-sources"></a> |
| `MaxHivesPerSource` | 64 | 1–1024 | Hives one source may register. <a id="cite-param.max-hives-per-source"></a> |
| `MaxConcurrentRSIRequests` | 256 | 8–4096 | In-flight RSI requests per source ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)). <a id="cite-param.max-concurrent-rsi-requests"></a> |
| `MaxScopeGUIDsPerToken` | 8 | 1–256 | Private hive scope GUIDs on a token ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-param.max-scope-guids-per-token"></a> |
| `MaxPrivateLayersPerToken` | 16 | 1–256 | Private layer names on a token ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-param.max-private-layers-per-token"></a> |
| `MaxSubtreeWatchDepth` | 0 | 0–4096 | Subtree watch depth; 0 is unlimited ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-param.max-subtree-watch-depth"></a> |
| `MaxTransactionWatchEventBurst` | 4096 | 256–65536 | Watch events per watcher from one commit ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-param.max-transaction-watch-event-burst"></a> |

Unknown values under this key are ignored. <a id="cite-param.unknown-values-ignored"></a> There are exactly
nineteen parameters and no undocumented ones; a separate set under
`Machine\System\KMES\` belongs to KMES.

Two limits are not among them. The **transaction mutation log** is
capped at 4096 entries by a compile-time constant ([Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md#trm-5-7-2>)), and hard
ceilings on total path length and key depth exist independently of
configuration — set equal to the range maxima above, so they never
conflict. <a id="cite-param.hard-ceilings-match-range-maxima"></a>

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

## Where a configured value does not fully bind

One of the nineteen does not do everything its range suggests.

`MaxPrivateLayersPerToken` is described as an attachment-time limit but
is not enforced at attachment. KACS applies its own hard cap of 256 and
LCS applies the configured value later, at use, with `E2BIG` ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)).
`MaxScopeGUIDsPerToken` behaves the same way.

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

## Validation

A value is checked against its range when it is read.

- **Valid** — hot-swapped into the in-memory configuration and used by
  new operations. <a id="cite-param.validation.valid-is-hot-swapped"></a>
- **Invalid** — out of range, the wrong type, or missing — the value is
  **ignored** and the previously active one is kept: the compiled-in
  default or the last known-good. <a id="cite-param.validation.invalid-is-ignored-previous-kept"></a>
  An `lcs.config.value.rejected` audit event is emitted naming the
  parameter, what was wrong, and the value being retained ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)).

**Values are never clamped or silently corrected.** <a id="cite-param.validation.never-clamped"></a> There is no
`min`/`max` on any configuration path. A write to the registry
succeeds, because the source does not enforce kernel semantics, and LCS
simply refuses to use it. The registry shows what was written; the
audit log shows what LCS is running on.

Because "missing" is invalid, a first boot before seed restore emits
nineteen of these events per refresh — provided `Machine\System\Registry`
itself exists. If the key is absent there is nothing to read and
nothing is reported; the fallback watch of [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>) waits for it.

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

## Hot-swap and in-flight operations

Configuration is published as a whole structure under a seqlock, and a
reader takes a complete copy of it. <a id="cite-param.hot-swap.published-as-one-structure"></a>

A syscall entry point snapshots it once and threads that snapshot
through the operation, so in-flight work uses the values that were
current when it started and new work uses the updated ones. <a id="cite-param.hot-swap.syscall-snapshots-once"></a>

That is the rule, and mostly the practice. Some deeper paths take a
second snapshot part-way through, and a few call sites read a single
live value rather than a snapshot — `reg_begin_transaction`'s timeout,
the bound-transaction cap, and the in-flight request cap among them.
For those, a hot-swap can be observed mid-operation. <a id="cite-param.hot-swap.some-call-sites-read-live-values"></a>

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

## Security

`Machine\System\Registry\` inherits the `Machine` hive root descriptor
— SYSTEM and Administrators with `KEY_ALL_ACCESS`, Authenticated Users
with `KEY_READ` — so an unprivileged process cannot change any of
this. <a id="cite-param.security.unprivileged-cannot-change"></a>

Domain policy at a higher-precedence layer defends against a
compromised local administrator, which is the reason `SeTcbPrivilege`
guards precedence above 0 ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

## Operator verification

Inspect the stored configuration and installed manual before tuning LCS:

```sh
reg get Machine/System/Registry
regman 'Machine\System\Registry'
```

Keep a recovery value. A successful write confirms storage, not adoption;
inspect `lcs.config.value.rejected` events as well. Deleting a parameter does
not reset an already accepted running value. Write the intended valid value
and verify it at the documented application point.

An unavailable hive is a source problem, distinct from an absent parameter.
For loregd, inspect the output captured by Peinit before readiness and the
stored service logs after logging starts. Missing configuration alone is not
evidence that a database needs replacement or reseeding.

---

# The Self-Watch

_Peios Kernel / Internals / LCS / Bootstrap_

> LCS watches its own configuration through the same machinery userspace uses — what it drives, how it is armed, and why the callback is not the atomicity boundary.

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

LCS watches its own configuration and layer metadata subtrees, and it
does so through the same machinery userspace uses — but not through the
same interface.

An internal watch is an entry in the same watch map, taking a reference
on the same subtree watch set, distinguished only by a kind marker. It
has **no fd, no granted access mask and no filter**. <a id="cite-self-watch.no-fd-mask-or-filter"></a>

Events reach it through a kernel callback rather than being queued for
a `read()`, and it is therefore not subject to
`NotificationQueueSize`. <a id="cite-self-watch.exempt-from-notification-queue-size"></a>

It is also not subject to `MaxSubtreeWatchDepth`, nor to the
transaction burst suppressor: internal collection happens before either
test. <a id="cite-self-watch.exempt-from-depth-and-burst-limits"></a>

Because there is no filter, deliverability is decided per target rather
than by a bitmask. Each internal target admits only the event types it
cares about: value events on the watched key itself for the
configuration subtrees, and subkey events at depth 0 or value and
descriptor events at depth 1 for the layer metadata subtree. <a id="cite-self-watch.admits-event-types-per-target"></a>

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

## What it drives

**Self-configuration.** A change under `Machine\System\Registry\`
triggers a re-read and validation of the parameters ([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)). <a id="cite-self-watch.drives.parameter-re-read"></a>

**The layer table.** A change under `Machine\System\Registry\Layers\`
marks the affected layer names dirty and drives a bounded refresh of
their precedence, enabled state, owner and cached descriptor. Within
one delivery — a transaction's commit, say, whose batch creates a
layer and then writes its three values — each dirty layer is refreshed
once, however many of the batch's events named it. <a id="cite-self-watch.layer-refreshed-once-per-delivery"></a>

**Layer lifecycle.** `SUBKEY_CREATED` and `SUBKEY_DELETED` under
`Layers\` add and remove layers, except for `base`, which is ignored
([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)). <a id="cite-self-watch.drives.layer-lifecycle-from-subkey-events"></a>

**KMES configuration.** A third internal watch, on
`Machine\System\KMES\`, exists for KMES's own parameters. <a id="cite-self-watch.drives.kmes-configuration"></a> It is not
LCS configuration, but the registry is where it lives and this is the
mechanism that notices it change.

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

## The callback is not the atomicity boundary

For layer metadata, internal delivery identifies which layer names are
dirty. It does not itself publish anything, and it must not: publishing
a layer means publishing its table entry, metadata key GUID and cached
descriptor together ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)), and a callback that published a partial
entry would create a window in which a layer exists and nobody can be
authorised against it. <a id="cite-self-watch.callback-does-not-publish"></a>

LCS also does not perform source round trips while holding the
watch-map or layer-table publication locks. <a id="cite-self-watch.no-source-round-trip-under-locks"></a> The refresh runs outside
them, after the mutating operation commits and before the syscall
returns.

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

## Arming

At bootstrap, LCS resolves the GUIDs for `Machine\System\Registry\` and
`Machine\System\Registry\Layers\` through `RSI_LOOKUP` and arms
targeted subtree watches. <a id="cite-self-watch.arming.targeted-via-rsi-lookup"></a>

If either does not exist — first boot, empty database — it arms a
subtree watch on the `Machine\` hive root instead, so that seed restore
creating the subtree is noticed. <a id="cite-self-watch.arming.fallback-on-machine-root"></a>

That fallback event re-enters the whole bootstrap refresh, which
resolves the specific GUIDs and arms the targeted watches. <a id="cite-self-watch.arming.fallback-event-re-enters-refresh"></a>

In practice the kernel arms both: targeted watches for whichever roots
exist, **plus** the `Machine\` root fallback, until a refresh finds
everything present. <a id="cite-self-watch.arming.mixed-superset"></a> It is a superset of what is needed rather
than a substitute for it.

The same arming covers every key the kernel reads for itself, not only
LCS's own: KMES configuration, the port reservation table
(`Machine\System\Network\TcpIp\PortReservations\`, see the KACS
chapter on network objects), the network policy key
(`Machine\System\Network\`, whose rules and inventory the packet
engine reads — see the network policy chapter) and the event emission
policy (`Machine\Generic\Events\`, see the KMES chapter) are
discovered in the same refresh and get the same targeted-or-fallback
treatment. <a id="cite-self-watch.arming.covers-every-kernel-read-key"></a>

The two policy watches are the depth-unbounded, every-mutation ones.
For the network policy, rules are keys and exceptions are subkeys, so
anything written anywhere beneath the key may be policy. <a id="cite-self-watch.arming.policy-watch-is-depth-unbounded"></a>
The emission policy has a key per event-type segment at any depth, and
its watch passes on only changes on `Events` itself, beneath the
kernel's own roots, and to `Enabled` values (KMES [Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

**A refresh that fails still arms the fallback.** A stage can fail
transiently — a source answering a lookup while a concurrent write has
half-created a key was the case that found this — and if the refresh
simply returned, no watch would exist and no kernel-read key would load
for the life of the boot. So when any stage before arming fails, LCS
arms the `Machine\` root fallback alone: the next subkey creation under
the hive re-enters the refresh, which then arms the targeted watches as
above. <a id="cite-self-watch.arming.failed-refresh-arms-fallback-alone"></a>

The failure and the fallback arm are both traced by
`lcs:lcs_bootstrap_refresh`. <a id="cite-self-watch.arming.failure-is-traced"></a>

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

## Bootstrap interaction

1. A source registers. LCS reads `Machine\System\Registry\*`; the keys
   do not exist; compiled-in defaults are retained.
2. Seed restore populates them. The subtree watch fires, LCS validates
   and hot-swaps to the seed values.
3. Subsequent administrative changes fire the watch again, and LCS
   validates and hot-swaps, or rejects with an audit event.

At no point is there a state in which LCS is waiting for
configuration.
