Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

LCS

Peios kernel lcs documentation.

Single-page view · as markdown

Overview

Peios Kernel / Internals / LCS / Start here

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.

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.

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.

What is layered and what is not #

PropertyLayeredResolved bySurvives layer deletion
Path existenceYesHighest precedence, then highest sequenceNo
ValuesYesHighest precedence, then highest sequenceNo
Value tombstonesYesMasking lower precedenceNo
Blanket tombstonesYesMasking all lower-precedence values on the keyNo
Key hidingYesMasking lower precedenceNo
Key GUIDNoDirect on the key objectYes
Security DescriptorNoDirect on the key objectYes
Volatile flagNoDirect on the key objectYes
Symlink flagNoDirect on the key objectYes
Last write timeNoDirect on the key objectYes

A watch is bound to the key object rather than to either, and stays on that object whatever happens to the name (Dispatch).

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).
  • 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).
  • Registry access rights occupy the Windows bit positions, so a Security Descriptor containing registry ACEs is binary-compatible (Access Rights).

Tombstones and blanket tombstones exist for the same reason: the **Del.ValueName and **DelVals directives express absence, which a purely additive overlay cannot (Tombstones).

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.

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.

WindowsLCS
Backing storeKernel-internal hive filesUserspace sources over the RSI, so a storage backend is not a kernel change
Hive routingA fixed set of predefined hivesAny source may register any name at runtime
LayersNone; registry.pol is applied by flattening valuesPrecedence-ordered layers with tombstones, resolved at query time, so removal reverts rather than tattoos
Change observationRegNotifyChangeKeyValue, single-shotPersistent watches, closing the re-registration race
Key identityHive cell offsetsGUIDs, stable across storage reorganisation
Forward slashNot acceptedAccepted on input, normalised to backslash
Case comparisonRtlCompareUnicodeStringUnicode Simple Case Folding, pinned to a version

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.

This chapter #

Hives and Routing 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 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 covers security: the access flow, the rights, inheritance, and the audit events LCS emits. The Fd Model covers the syscall and ioctl interface and the error model. The Watch Model covers watches, Scope and Lifetime transactions, and The Source Model the source model — registration, dispatch, validation, and the intricate business of what a late response means. The Stream covers backup and restore, The Bootstrap Problem how LCS configures itself out of the registry it is serving, and LCS ABI Reference 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.

Build configuration #

LCS is built by CONFIG_SECURITY_PKM, a boolean option, so it is linked into vmlinux rather than loaded.

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.

CONFIG_SECURITY_PKM_KUNIT compiles in the in-kernel test harness.

The three syscall numbers are registered in arch/x86/entry/syscalls/syscall_64.tbl and the corresponding table under tools/perf/.

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.

Related explanations #

  • File descriptors and buffer conventions

Calling the subsystem #

The native LCS interface reference collects the caller contracts and generated ABI tables.

Topics #

  • Data model
  • Layers
  • Security
  • Watches
  • Transactions
  • Sources
  • Backup and restore
  • Bootstrap

Data model

Peios Kernel / Internals / LCS / Data model

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

  • Hives and Routing
  • Private Hives
  • Keys
  • Symlinks
  • Path Entries
  • Values
  • Tombstones
  • Names and Case
  • Deletion and Orphans

Hives and Routing

Peios Kernel / Internals / LCS / Data model

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.

FieldDescription
NameThe hive name, e.g. Machine, Users. Case-preserving, compared case-insensitively.
Root GUIDThe GUID of the hive's root key, supplied by the source at registration.
SourceThe source slot backing this hive.
StatusActive or Unavailable, tracking source connectivity.

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.

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.

That pair must be unique across every registered source; a source claiming one another source already holds is rejected.

The same name may appear in different scopes, which is precisely how a private hive shadows a global one without colliding with it.

A hive is backed by exactly one source. A source may back many.

Routing a path #

LCS takes the first component of a path — everything before the first separator — and looks it up.

  • Registered and active routes to the backing source.
  • Not registered is ENOENT.
  • Registered but Down is EIO.

Before any source registers, the table is empty and every path yields ENOENT (The Bootstrap Problem).

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.

The rewritten path is re-checked against the total-length limit, since a textual SID is longer than the alias it replaced.

Three constraints keep this safe.

It applies only to the first component of a path, and only to a caller-supplied absolute one.

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

Symlink targets are subject to ordinary hive routing, private hives included. A sandboxed process resolving a symlink sees the same registry through it that it sees directly, which is the point of sandboxing it.

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

Neither is a routing decision — an unregistered Machine routes nowhere like any other name — but the two names do exist in the kernel.

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

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. They are case-preserving and compared case-insensitively (Names and Case).

Private Hives

Peios Kernel / Internals / LCS / Data model

A private hive is registered with the RSI_HIVE_PRIVATE flag and a scope GUID.

It is invisible in the global namespace and reachable only by a thread whose token carries that scope GUID.

Routing #

Private hives are checked before global ones.

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 private hive can therefore shadow a global one, and no name is exempt — a thread with a private Machine\ sees the private one. 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). Duplicate scope GUIDs on a token are rejected.

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). It parses at a fixed offset, and:

  • rejects a nil scope GUID;
  • rejects duplicate scope GUIDs;
  • caps the count at 256 — a hard KACS limit, above the configurable LCS one.

The credentials propagate across fork, duplication and impersonation like the rest of the token.

Attaching them is gated by SeCreateTokenPrivilege, because scope GUIDs can only enter a token when the token is created. 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.

Scope lifecycle #

A scope GUID is an opaque 128-bit value with no lifecycle. LCS neither creates nor tracks one; it only compares. 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. 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.

Registration rules #

Registration enforces more than the route-identity uniqueness of Hives and Routing — the full list is Registration and Slots, 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. 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).

Keys

Peios Kernel / Internals / LCS / Data model

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

FieldMutableLayeredDescription
GUIDNoNoIdentity, assigned by LCS at creation, persisted by the source.
NameNoNoThe 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.
Parent GUIDNoNoThe parent key. Nil for a hive root.
Security DescriptorYesNoComputed from the parent at creation; changed at runtime with WRITE_DAC / WRITE_OWNER.
Last write timeYesNoUpdated when a value is written or deleted or the descriptor changes.
VolatileNoNoThe source stores this key in non-persistent storage only.
SymlinkNoNoThis key is a symbolic link (Symlinks).

No key property is layer-qualified. Properties belong to the object. 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.

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

Once a path has been resolved to a GUID at open time, every subsequent RSI operation uses the GUID directly.

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.

Freshness is the collision resistance of UUIDv4 plus a check against the keys LCS currently tracks, with a bounded retry.

There is no persistent retired-GUID catalogue, and no code anywhere that would maintain one. A GUID dropped by orphan cleanup is not remembered.

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.

It is never retried as an open and EEXIST never reaches userspace from reg_create_key.

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

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.

What the kernel does enforce is the containment rule: a non-volatile key may not be created under a volatile parent (EINVAL).

The converse is allowed — a volatile key under a persistent parent is ordinary.

Naming #

Three bytes are forbidden in a key name component: backslash and forward slash, both of which are separators, and the null byte.

Every other valid UTF-8 sequence is permitted, spaces and arbitrary Unicode included.

Empty components are forbidden, which rules out a leading separator and consecutive separators (Machine\\System).

A trailing separator (Machine\System\) is likewise invalid.

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

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.

RSI_WRITE_KEY can update only the descriptor and the last write time, so there is no operation that could change it.

The default value, of type REG_LINK, supplies the target path.

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.

The flag marks identity; the value provides the target.

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.

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.

If the effective default value is missing, or is not of type REG_LINK, resolution fails with EINVAL.

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.

The offending value stays in the registry; a failed resolution writes nothing.

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

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.

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.

CurrentUser\ rewriting is not applied (Hives and Routing), 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.

Depth #

Symlink resolution is bounded by SymlinkDepthLimit, default 16, configurable from 1 to 64. Exceeding it is ELOOP.

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.

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.

The access check follows the same rule: with REG_OPEN_LINK the check is against the link, otherwise against the target.

Creation #

Creating a symlink needs all of:

  • KEY_CREATE_SUB_KEY on the parent, as for any key;
  • KEY_CREATE_LINK on the parent;
  • either an enabled SeTcbPrivilege or membership of Administrators.

The last is a genuine disjunction — either satisfies it — and the privilege branch marks the privilege used.

Failing it is EPERM.

Path Entries

Peios Kernel / Internals / LCS / Data model

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

FieldDescription
Parent GUIDThe parent key.
Child nameThe key's name under that parent — one component, not a path.
LayerThe layer this entry belongs to.
TargetThe GUID of the key at this path in this layer, or HIDDEN.
SequenceA 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).

A source returning a non-zero GUID on a HIDDEN entry is returning malformed data.

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.

LCS sends RSI_CREATE_ENTRY first and RSI_CREATE_KEY second.

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. Failure on the second call, for a GUID LCS just minted, is not a race and fails closed (Keys).

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.

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.

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.

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.

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.

Hiding #

A layer can create a HIDDEN entry at a path, making the key invisible regardless of what lower-precedence layers say.

It is the path-level equivalent of a value tombstone, and when the hiding layer is removed the lower key reappears.

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.

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.

Removing the layer removes both the new key and its masking effect, and the lower key comes back.

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

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.

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.

Values

Peios Kernel / Internals / LCS / Data model

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

FieldDescription
Key GUIDThe key this value belongs to.
NameThe value's name; the empty string is the default value. Case-preserving, compared case-insensitively.
TypeA registry value type.
DataAn opaque byte array, up to MaxValueSize (default 1 MB).
LayerThe layer this entry belongs to. Every write is tagged.
SequenceAssigned 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.

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.

The source stores them all and returns them all.

LCS resolves the effective value at read time (Resolution).

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.

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. Values are in LCS ABI Reference.

LCS stores the type tag and returns it on read but does not interpret the data. The single exception is REG_LINK read as a symlink key's default value, which triggers target resolution (Symlinks).

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

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.

There is no separate tombstone flag in the REG_IOC_SET_VALUE argument. Writing type REG_TOMBSTONE is the explicit tombstone operation.

It must carry zero-length data; non-empty tombstone data is EINVAL, again before sequence allocation, enlistment or dispatch.

Naming #

Value names use the same case rules as key names: Unicode Simple Case Folding, case-preserving, case-insensitive.

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.

Only the null byte is forbidden, and invalid UTF-8 is rejected. The empty string is reserved for the default value.

That difference is why watch event path components are length-prefixed rather than joined by a separator (Event Records) — a value name can contain the separator.

Size #

MaxValueSize defaults to 1 MB and is configurable from 4 KB to 64 MB (Operational Parameters).

Value data is opaque bytes and is not subject to the UTF-8 validation that applies to every string in the interface.

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. For choosing and entering a type as an operator, see Keys, values, and types.

Tombstones

Peios Kernel / Internals / LCS / Data model

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.

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.

Resolution treats a winning tombstone as "not found" without falling through.

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.

Blanket tombstones #

A blanket tombstone is a per-layer marker on a key that masks every value from lower-precedence layers, whatever its name.

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.

It is stored as a flag on the (key GUID, layer) relationship and occupies no per-name entry. It has its own sequence number.

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), and the ordinary rule picks the winner (Resolution).

So a per-value entry that beats the blanket on the tuple overrides it, and one that loses is masked.

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

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.

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.

Removal #

Removing a blanket, or the layer holding it, unmasks everything it was hiding.

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

Names and Case

Peios Kernel / Internals / LCS / Data model

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.

Null bytes are rejected in all of them. 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.

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

Lengths are byte counts #

Every configured length limit is measured in UTF-8 bytes, not Unicode scalar values and not display characters.

  • MaxPathComponentLength (default 255) bounds one component or one value or layer name.
  • MaxTotalPathLength (default 16383) bounds a whole path.
  • MaxKeyDepth (default 512) bounds nesting.

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.

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.

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.

There is no string-rewriting step: normalisation is a property of how paths are split rather than a transformation applied to them.

Case folding #

Comparison is case-insensitive and storage is case-preserving.

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.

It is a fixed one-to-one codepoint mapping with no locale input, applied after decoding from UTF-8, never to raw bytes.

The Unicode version is pinned at 16.0. 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.

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.

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 for base).

Deletion and Orphans

Peios Kernel / Internals / LCS / Data model

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

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.

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.

If path entries remain in other layers, the key is still visible through them.

If none remain anywhere, the key is orphaned.

A key with visible children cannot be deleted: ENOTEMPTY.

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.

Recursive deletion is a client-side tree walk, not a kernel primitive.

Deleting a key does not delete its values. Values belong to the GUID, not to the path entry, and go when the GUID goes.

Hive roots cannot be deleted or hidden (Path Entries).

Layer deletion #

Deleting a layer removes all of its path entries, value entries and blanket tombstones, across every source.

LCS broadcasts RSI_DELETE_LAYER and each source returns the GUIDs that lost their last path entry as a result.

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

  • keys named only by that layer become orphaned;
  • where the layer held the winning value entry, the next layer's value becomes effective;
  • blanket tombstones it held are removed and unmask what they were hiding;
  • and Security Descriptors are unchanged, because they were never layered.

Watchers are notified by whatever recovery mechanism applies — per-key events for the orphaned keys, and a source-wide OVERFLOW for the rest (Dispatch).

Before sending RSI_DELETE_LAYER, LCS aborts every bound transaction whose mutation log touched that layer. Otherwise a transaction could commit writes into a layer that no longer exists.

Those transactions return EINVAL on their next operation or commit attempt.

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

Orphaned keys #

An orphaned key is a GUID with no path entry in any layer. It follows the Linux unlink model: alive but unnamed.

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

  • querying, setting and deleting values;
  • setting and removing blanket tombstones;
  • querying and setting the Security Descriptor;
  • querying key metadata;
  • flushing the key's hive;
  • closing the fd.

Namespace operations return ENOENT:

  • creating a child key under it;
  • opening or creating anything relative to it;
  • deleting its path entry;
  • hiding it;
  • backing it up.

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.

Watches on an orphaned key #

A watch armed before the key was orphaned stays armed, and the transition delivers KEY_DELETED.

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.

Arming a new watch on an already-orphaned key is ENOENT.

Re-arming one that is already armed is allowed.

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.

It is dispatched before the in-kernel key state is released.

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

Layers

Peios Kernel / Internals / LCS / Layers

Use these articles to understand layers in the Peios kernel.

  • The Layer Model
  • The Base Layer
  • Layer Metadata
  • Writing Into a Layer
  • Private Layers
  • Resolution
  • The Sequence Counter

The Layer Model

Peios Kernel / Internals / LCS / Layers

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

FieldMutableDescription
NameNoThe layer's identity — not a GUID, not an integer. Case-preserving, compared with Unicode Simple Case Folding. Bounded by MaxPathComponentLength.
PrecedenceYesHigher wins. Default 0.
EnabledYesA disabled layer is invisible during resolution unless it is attached to the resolving thread's credentials (Private Layers). Default true.
Owner—The SID of the principal that created the layer. Informational only.

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

Owner is never used for an access check; authorisation is the descriptor on the layer's metadata key (Writing Into a Layer).

It is also not quite immutable as a field: a refresh re-reads the Owner value and re-selects it, so rewriting the value does change what is cached. Because nothing consults it, that has no effect on anything.

Precedence tiers #

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

Establishing or raising a layer's precedence above 0 requires SeTcbPrivilege (Writing Into a Layer). That is what keeps the tier boundary meaningful.

Caps #

MaxTotalLayers, default 1024, bounds the in-memory layer table, the base layer included: a table holding that many entries admits no more.

Creating a layer when it is full returns ENOSPC. The refusal happens at the creation of the metadata key under Layers\, before anything reaches the source, so a full table never leaves a metadata key behind that the table cannot publish.

The table is sized to MaxTotalLayers rather than fixed at build. It is allocated on the first publication and grows, under the table lock, whenever a publication finds every slot taken while the configured bound still admits one more; it never shrinks.

So a value anywhere in the configurable range, 16 to 65536, binds. Raising MaxTotalLayers above the default admits layers past 1024; lowering it below the current occupancy admits no new layer until enough have been deleted, and discards nothing.

MaxLayersPerValue, default 128, bounds how many layers may write to the same (key GUID, value name) pair. It is a guard against amplification — every read of that value has to resolve every entry — not an access control boundary.

It is enforced at REG_IOC_SET_VALUE time, before the source is contacted, by querying the source for the current entry count.

A write that replaces an existing entry in the same layer does not increase the count and is not checked. Exceeding the cap is ENOSPC.

The check is deliberately best-effort admission control, not a storage invariant. It queries and then dispatches without holding anything, so concurrent writers can both observe room and both proceed. Sources are not required to enforce it atomically.

Once LCS observes a count at or above the cap, further new-layer writes are refused.

Blanket tombstones and value deletions are not subject to it.

Layers are global; entries are per-source #

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

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

The Base Layer

Peios Kernel / Internals / LCS / Layers

The base layer, named base, is a kernel-reserved implicit layer. It exists unconditionally, before any source registers and whether or not any metadata has ever been persisted for it.

It is a static constant in the kernel: precedence 0, enabled. It is never stored in the dynamic layer table.

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

Four things cannot happen to it:

  • it cannot be deleted;
  • it cannot be disabled;
  • its precedence cannot be changed;
  • a layer table row for it cannot be published at all.

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

Persisted metadata #

Machine\System\Registry\Layers\base\ may exist, though nothing in a Peios system creates it, and where it does it decorates the base layer rather than defining it. What LCS takes from it is the metadata key's GUID and its cached Security Descriptor — which is to say, who may write into the base layer (Writing Into a Layer).

Its Precedence and Enabled values are ignored.

The internal self-watch also ignores a SUBKEY_DELETED for base: if a higher-precedence HIDDEN entry masks the base layer's metadata key, that is not a layer deletion and is not processed as one. The base layer's existence is hardcoded and layer mechanics cannot reach it.

The default target #

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

While the base layer's metadata key does not exist, LCS uses a compiled-in default descriptor granting SYSTEM and Administrators KEY_ALL_ACCESS and Authenticated Users KEY_SET_VALUE, so writes into the base layer are possible from the very beginning, by anyone who has authenticated, to whatever the target key's own descriptor lets them write. The compiled-in default is replaced by the key's descriptor as soon as the key is created (Writing Into a Layer).

base is matched like every other layer name #

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

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

Layer Metadata

Peios Kernel / Internals / LCS / Layers

Layer metadata lives in the registry, under Machine\System\Registry\Layers\<LayerName>\. Each layer's key holds three values:

ValueTypeDefault if missing
PrecedenceREG_DWORD0
EnabledREG_DWORD, 0 or 1true
OwnerREG_BINARY, a SIDthe creating token's SID for a new layer

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

  • a value of the wrong type;
  • a REG_DWORD that is not exactly four bytes;
  • an Enabled greater than 1.

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

If none of those is available the layer cannot be published. Every one of these is informational and none grants access.

There is no "create layer" or "delete layer" syscall. Creating a key under Layers\ creates a layer; deleting that key deletes it. Creation should be done inside a transaction so that all three values are present when the refresh runs.

Circularity #

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

LCS always resolves using its currently published layer table — including when resolving layer metadata values. When a write to the metadata subtree commits, the refresh reads the affected metadata using the current table and then publishes an updated one.

The table is never re-resolved mid-operation; each operation takes one snapshot and uses it throughout.

So a high-precedence layer can override another layer's precedence, and that is useful and intended. It simply takes effect at the next publication rather than recursively.

Publication is atomic #

A layer is not merely a name and a precedence. The published unit is three things together: the layer table entry, the metadata key's GUID, and the cached Security Descriptor of that key.

All three are written under one lock, and a snapshot reader that finds them incomplete returns EIO rather than a half-populated layer.

A layer that has no metadata key GUID and no authorisation descriptor is not visible in the table at all. There is no window in which a layer exists but nobody can be authorised against it.

Creating the metadata key is ordinary key creation, so LCS computes its descriptor from parent inheritance through KACS before the source persists it. On the normal path the key therefore has a descriptor before the layer can be published.

When the refresh runs #

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

For a transaction the refresh runs once, after the source commit succeeds and before REG_IOC_COMMIT returns.

The internal self-watch is what notices the subtree changed, but the watch callback is not the atomicity boundary and must never publish a partial entry. LCS does not perform source round trips while holding the watch-map or layer-table publication locks.

When the metadata descriptor will not parse #

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

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

If the refresh was required to complete the operation in hand — creating a layer, say, or exposing one — the syscall fails with EIO.

Writing Into a Layer

Peios Kernel / Internals / LCS / Layers

Every mutating operation that targets a layer — value writes, value deletions, tombstones, key hides, blanket tombstones, key creation — requires layer write authorization: KEY_SET_VALUE on the layer's metadata key at Machine\System\Registry\Layers\<LayerName>\.

This is a second AccessCheck, against a different object, and it is in addition to the fd's granted mask on the target key. Both must pass.

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

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

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

The layer metadata descriptors are cached alongside the layer table and invalidated by the same self-watch (Layer Metadata). A layer that is not in the table is ENOENT for any operation naming it.

The base layer before it exists #

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

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

It is replaced by the persisted descriptor the moment the key is created.

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.

Layer lifecycle #

OperationRequirement
Create a layer at precedence 0KEY_CREATE_SUB_KEY on Layers\
Create a layer above precedence 0KEY_CREATE_SUB_KEY on Layers\ and SeTcbPrivilege
Write into a layerKEY_SET_VALUE on the layer's metadata key
Modify layer metadataKEY_SET_VALUE on the metadata key; raising precedence above 0 additionally requires SeTcbPrivilege
Delete a layerDELETE on the metadata key's fd

Everything except the precedence rule is controlled purely by the descriptor on the metadata key.

The precedence gate #

SeTcbPrivilege is required specifically to establish or raise a layer's precedence above 0. It is defence in depth: compromising the descriptor on Layers\ is not enough to create a Group Policy-tier layer.

The check is synchronous and inline at REG_IOC_SET_VALUE time, and it happens early — before sequence allocation, before transaction enlistment, before the source is contacted.

It runs when three things hold: the target key is a layer metadata key, the value name folds equal to Precedence under the same Unicode folding used for every other value name, and the data is a positive REG_DWORD. A key is a layer metadata key by its path — a direct child of Machine\System\Registry\Layers — or by already being in the set of published layer metadata keys. The path test is what covers the recommended creation flow (Layer Metadata), where Precedence is written inside the transaction that creates the metadata key, before the layer has been published at all.

Failing the privilege check is EPERM.

The gate tests for a four-byte REG_DWORD specifically. A Precedence written with some other type slips past it — and then fails at the refresh, which rejects a non-REG_DWORD Precedence as malformed metadata. The precedence never actually rises.

REG_IOC_RESTORE has its own equivalent gate, applied to the backup stream's layer manifest before anything is written (Restore).

Deleting a layer #

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

Before the broadcast, LCS aborts every bound transaction whose mutation log touched that layer (Deletion and Orphans).

A SUBKEY_DELETED for base is ignored (The Base Layer).

Private Layers

Peios Kernel / Internals / LCS / Layers

A private layer is a disabled layer attached to a thread's credentials. It is invisible during ordinary resolution and treated as enabled when resolving on behalf of a thread whose token names it.

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

Resolution #

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

After private-attachment authorization succeeds, a layer is active for a thread if it is globally enabled, or its name appears in that thread's private layer set.

Name matching uses Unicode Simple Case Folding, like every other layer name comparison.

Attachment #

Private layer names reach a thread through the KACS token's LCS credential extension — the same versioned block that carries scope GUIDs for private hives (Private Hives).

LCS reads the credentials from the effective token on each operation and passes them into resolution.

Private layers are therefore per-thread, not per-process: threads in one process can hold different private layer sets through different impersonation tokens.

Two things about the caps #

MaxPrivateLayersPerToken, default 16, is described as a limit on attachment. It is not enforced there.

KACS applies its own hard cap of 256 names when it parses the token specification. The configurable LCS limit is applied later, when LCS acquires a thread's private credentials for an operation.

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

The failure is E2BIG. It was EACCES, which read as an access-control denial and sent anyone debugging it towards descriptors and privileges rather than towards a count that was fixed when the token was assembled, possibly in another process.

MaxScopeGUIDsPerToken shares the check and the errno. A missing token is still EACCES, because that one is an access decision.

KACS deduplicates the private layer names it parses with the same Unicode Simple Case Folding LCS matches them by, so a name that LCS treats as one layer is one layer here too.

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

Attachment authority #

Private-layer names can enter a token only at creation, which requires SeCreateTokenPrivilege. Attaching a known layer above precedence 0 additionally requires enabled SeTcbPrivilege on the creator. Without it, creation fails with EPERM, even when the requested child token itself includes TCB privilege. A present but disabled privilege does not authorize attachment.

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

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

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

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

Resolution

Peios Kernel / Internals / LCS / Layers

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

The rule #

Every candidate is a tuple (precedence, sequence, entry). The winner is the maximum, ordered by precedence first and sequence second.

Building the candidate list:

  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.
  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).
  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).
  4. If there are no candidates, the answer is not-found.
  5. Take the maximum. A winning HIDDEN path entry, a winning REG_TOMBSTONE value entry, and a winning blanket all mean not-found.

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

Unknown layers are latent, not wrong #

An entry tagged with a well-formed layer name that is not currently in the table is a valid latent entry.

It is ignored while the layer is absent, and if a layer with the same folded identity is later created, that entry becomes eligible for resolution under the new metadata.

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

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

An entry whose layer name is malformed is a different matter, and is rejected as malformed source data.

Enumeration #

Enumerating values collects the unique names across all layers and resolves each one, returning only those whose answer is not not-found.

Enumerating subkeys collects the unique child names and resolves each, returning those that map to a GUID rather than HIDDEN.

"Unique" means folded-unique. Two entries whose names differ only in case are one name, which is the only reading consistent with names being case-insensitive.

A caller sees effective state only. Tombstoned values, blanket-masked values and hidden keys are simply absent. Per-layer raw data is never visible through a normal operation.

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

REG_IOC_ENUM_VALUES and REG_IOC_ENUM_SUBKEYS return one entry at an index. Each call re-resolves the full set and returns the entry at that position, so walking 0..N-1 performs N full resolutions — O(n²) work overall.

For a key with a handful of values that does not matter. REG_IOC_QUERY_VALUES_BATCH exists for when it does: one call, the whole effective value set, one resolution.

Enumeration order is not defined, and the index-to-entry mapping can change between calls if the effective set changes. Indices must not be cached across mutations. The batch call is also the way to get a consistent snapshot.

Neither party can lie about ordering #

Two rules stop a source manipulating the outcome.

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

Every entry in a response is validated this way, whatever layer it names.

Duplicate sequence numbers at the same precedence, where they would actually have to be compared to pick a winner, are also malformed. LCS rejects the response rather than making an arbitrary choice.

Duplicates that never get compared are not an error.

Both produce EIO and an lcs.source.response.rejected audit event (Audit).

The Sequence Counter

Peios Kernel / Internals / LCS / Layers

LCS keeps one global monotonic counter. Every mutation that creates a layer-qualified entry — a path entry, a value write, a key hide, a blanket tombstone — takes the next number from it.

The counter is never decremented and never reset.

It provides deterministic tiebreaking within a precedence tier (Resolution). Wall-clock time is tracked separately, as each key's last write time, for humans.

Allocation #

Allocating a number increments the counter. Allocated numbers are never reused, even if the operation later fails, times out, or is part of a transaction that aborts.

Gaps in the sequence space are normal and carry no meaning.

A transactional mutation is assigned its number when the operation is accepted into the transaction, not at commit. That preserves the order in which the caller performed the operations, which is what layer tiebreaking and watch ordering need if it commits (Isolation and the Mutation Log).

Initialisation #

Each source reports the highest sequence number it has persisted in its registration handshake, and LCS raises the counter to one above the maximum reported. New writes therefore always outrank anything already in storage, even after a restart.

A source registering later advances the counter the same way, to max(current, source_max + 1).

If that addition would overflow 64 bits the registration fails with EOVERFLOW and the source is not made Active — the failure happens before the slot becomes usable.

The counter itself refuses to hand out U64_MAX, so the value is never allocated.

What a sequence number is not #

A sequence number is not a hive generation number.

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

A hive generation number is a volatile, per-hive, kernel-owned change epoch, exposed by REG_IOC_QUERY_KEY_INFO (Key Ioctls) so that a watcher recovering from OVERFLOW can tell whether it actually missed anything. Sources never see it and never persist it.

Its baseline is initialised from the source's reported maximum sequence at registration, purely so that observed generations are monotonic relative to persisted entries; after that the two are unrelated.

Restore #

A restore does not write the backup's sequence numbers. It reserves a fresh range and remaps into it, so restored entries are newer than everything that was there before while keeping their relative order from the backup (Restore).

Security

Peios Kernel / Internals / LCS / Security

Use these articles to understand security in the Peios kernel.

  • The Access Flow
  • Access Rights
  • Inheritance and Hive Roots
  • Audit

The Access Flow

Peios Kernel / Internals / LCS / Security

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.

  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.

  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.

    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.

  4. The granted mask is stored on the fd. It never changes.

  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.

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.

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

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.

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.

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). 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, rule 4).

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 covers it.

Access Rights

Peios Kernel / Internals / LCS / Security

Registry rights occupy the Windows bit positions, so a Security Descriptor carrying registry ACEs is binary-compatible with one written by Windows tooling. That is a registry.pol and Samba requirement, not an aesthetic choice.

The values are in LCS ABI Reference. 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.

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.

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.

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.

Validating what a caller asks for #

desired_access is validated before path resolution or AccessCheck.

  • Zero is EINVAL. A caller must ask for something.
  • Any bit outside the valid caller mask is EINVAL.
  • MAXIMUM_ALLOWED may appear alone or combined with anything else.
  • SYNCHRONIZE (0x00100000) is not a registry right, so it is an unknown bit and fails EINVAL.

The valid caller mask is a single constant, REG_VALID_DESIRED_ACCESS_MASK (LCS ABI Reference): the six specific rights, the four standard rights, ACCESS_SYSTEM_SECURITY, MAXIMUM_ALLOWED and the four generic bits.

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

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.

After generic mapping, an ACE mask must be a subset of the concrete registry rights plus ACCESS_SYSTEM_SECURITY.

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

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

Which right each operation needs #

OperationRequired
REG_IOC_QUERY_VALUE, QUERY_VALUES_BATCH, ENUM_VALUESKEY_QUERY_VALUE
REG_IOC_SET_VALUE, DELETE_VALUE, BLANKET_TOMBSTONE, FLUSHKEY_SET_VALUE
REG_IOC_ENUM_SUBKEYSKEY_ENUMERATE_SUB_KEYS
REG_IOC_QUERY_KEY_INFOREAD_CONTROL
REG_IOC_DELETE_KEY, HIDE_KEYDELETE
REG_IOC_NOTIFYKEY_NOTIFY
REG_IOC_GET_SECURITYREAD_CONTROL for owner, group, DACL and label; ACCESS_SYSTEM_SECURITY for the SACL
REG_IOC_SET_SECURITYWRITE_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
REG_IOC_BACKUPSeBackupPrivilege, no per-key check
REG_IOC_RESTORESeRestorePrivilege, no per-key check
creating a keyKEY_CREATE_SUB_KEY on the parent
creating a symlink keyKEY_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.

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.

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.

Subtree watches work the same way: a watcher is told a descendant was created without a check on that descendant. Structure visibility is deliberately weaker than content visibility, matching RegNotifyChangeKeyValue and RegEnumKeyEx.

Inheritance and Hive Roots

Peios Kernel / Internals / LCS / Security

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.

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

OBJECT_INHERIT_ACE is never used to select an ACE for inheritance. The child copy clears OBJECT_INHERIT_ACE, CONTAINER_INHERIT_ACE and NO_PROPAGATE_INHERIT_ACE when NO_PROPAGATE_INHERIT_ACE applies.

A parent with no inheritable ACEs falls back to the creating token's default DACL.

That fallback covers the DACL only; there is no default SACL.

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.

Hive roots #

A hive root has no parent, so it is the top of every inheritance chain below it and cannot inherit anything itself. Its descriptor is created by the source, on first boot, and LCS enforces whatever the source stored.

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\:

PrincipalRightsInheritance
SYSTEMKEY_ALL_ACCESSContainer-inherit
AdministratorsKEY_ALL_ACCESSContainer-inherit
Authenticated UsersKEY_READContainer-inherit

Users\<SID>\:

PrincipalRightsInheritance
the user's SIDKEY_ALL_ACCESSContainer-inherit
SYSTEMKEY_ALL_ACCESSContainer-inherit
AdministratorsKEY_ALL_ACCESSContainer-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), 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.

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

Zero is EINVAL, and so is any unknown flag; both are rejected before the source is contacted, before transaction enlistment and before any mutation.

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.

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.

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

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.

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.

The result must still have an owner; a merge that would leave the descriptor ownerless is EINVAL.

A null group SID stays valid.

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.

Audit

Peios Kernel / Internals / LCS / Security

LCS emits audit events through KMES. Fifteen events exist.

EventEmitted when
lcs.audit.key.openedA key open matched a SACL audit ACE.
lcs.audit.value.setA value write through a handle whose audit mask covers KEY_SET_VALUE.
lcs.audit.value.deletedA value delete through a handle whose audit mask covers KEY_SET_VALUE.
lcs.audit.key.tombstonedA blanket tombstone set or cleared through a handle whose audit mask covers KEY_SET_VALUE.
lcs.audit.key.deletedA key deleted through a handle whose audit mask covers DELETE.
lcs.audit.key.hiddenA key hidden through a handle whose audit mask covers DELETE.
lcs.audit.key.createdA key create that made a key matched a SACL audit ACE on the parent.
lcs.audit.key.descriptor.changedA descriptor change included the SACL, or its right is covered by the handle's audit mask.
lcs.audit.transaction.committedA transaction that staged an audited write ended.
lcs.audit.backup.startedAfter admission checks and before REG_IOC_BACKUP requests its read-only snapshot or reads any subtree data.
lcs.audit.backup.endedAfter a backup completes or fails after starting.
lcs.audit.restore.startedBefore REG_IOC_RESTORE modifies any source state.
lcs.audit.restore.endedAfter a restore completes or fails after starting.
lcs.source.response.rejectedLCS rejected malformed source data.
lcs.config.value.rejectedLCS rejected an invalid self-configuration value.

A registry open that a privilege contributed to is also recorded, as KACS's kacs.audit.privilege.used; see Privilege use on opens.

Backup and restore are audited unconditionally, whatever the SACL on the target key says. 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. 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).

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.

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.

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. An Anonymous impersonation token also reports 0, which is why subject.token.type is recorded beside it.

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.

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.

access.requested is the mask after registry generic mapping, with MAXIMUM_ALLOWED re-added if the caller asked for it.

SACL evaluation follows the KACS AccessCheck algorithm — the SACL is evaluated alongside the DACL, not separately.

Reading or modifying a SACL requires ACCESS_SYSTEM_SECURITY, which is itself gated by SeSecurityPrivilege.

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

An ACE naming a right the caller did not receive still does not match.

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. Success and failure SYSTEM_AUDIT ACEs do not contribute; they govern the open itself. This is the continuous auditing of Auditing in AccessCheck 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 write through the handle is recorded when the right it needs overlaps the mask, and not otherwise. The right is the one the handle's own gate checks:

EventOperationRight
lcs.audit.value.setREG_IOC_SET_VALUEKEY_SET_VALUE
lcs.audit.value.deletedREG_IOC_DELETE_VALUEKEY_SET_VALUE
lcs.audit.key.tombstonedREG_IOC_BLANKET_TOMBSTONEKEY_SET_VALUE
lcs.audit.key.deletedREG_IOC_DELETE_KEYDELETE
lcs.audit.key.hiddenREG_IOC_HIDE_KEYDELETE

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.

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

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.

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.

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

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.

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.

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.

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.

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.

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.

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.

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.

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

The three name classes are field-specific: layer-name fields, key component or child-name fields, and value-name fields respectively.

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.

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.

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. That is correct and expected, but it is a noticeable share of the boot audit stream.

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. 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.
  • 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.
  • lcs.audit.backup.ended, lcs.audit.restore.ended. The operation has already finished. Emission is attempted; failure does not change the result.
  • lcs.source.response.rejected. The triggering operation is already failing with EIO. Emission is attempted; failure does not change that.
  • 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.
  • 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. 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.

Watches

Peios Kernel / Internals / LCS / Watches

Use these articles to understand watches in the Peios kernel.

  • The Watch Model
  • Event Records
  • Dispatch
  • Queues and Overflow

The Watch Model

Peios Kernel / Internals / LCS / Watches

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

Each fd carries at most one watch.

Arming an already-armed fd replaces the filter and the subtree setting and leaves queued events in place.

Arming with a filter of zero disarms: the watch is removed and every pending event is discarded. 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).

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

Only committed state is observable. Operations inside an uncommitted transaction produce nothing; the whole set fires at commit (Dispatch).

Event types #

EventCodeName fieldMeaning
REG_WATCH_VALUE_SET1value nameThe effective value at this name changed or appeared.
REG_WATCH_VALUE_DELETED2value nameThe effective value at this name disappeared.
REG_WATCH_SUBKEY_CREATED3subkey nameA child key became visible.
REG_WATCH_SUBKEY_DELETED4subkey nameA child key became invisible.
REG_WATCH_SD_CHANGED5emptyThe watched key's Security Descriptor was modified.
REG_WATCH_KEY_DELETED6emptyThe watched key itself became invisible.
REG_WATCH_OVERFLOW7emptyEvents were dropped; re-read to recover.

VALUE_SET fires when a value is written, and when a tombstone or blanket tombstone is removed and a lower-precedence value surfaces.

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.

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.

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.

Filters #

The filter selects event categories, not individual event types.

Filter bitValueAdmits
REG_NOTIFY_VALUE0x01VALUE_SET, VALUE_DELETED
REG_NOTIFY_SUBKEY0x02SUBKEY_CREATED, SUBKEY_DELETED
REG_NOTIFY_SD0x04SD_CHANGED
REG_NOTIFY_ALL0x07all three of the above

KEY_DELETED and OVERFLOW are delivered unconditionally. They are not in any category and no filter suppresses them. 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 subtree flag other than 0 or 1, or a non-zero padding byte in the argument structure, is rejected the same way.

Blanket tombstones #

A watcher never learns that a blanket tombstone exists.

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. The per-value view is the only view.

Event Records

Peios Kernel / Internals / LCS / Watches

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.

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.

On an armed fd with an empty queue, read() blocks, or returns EAGAIN under O_NONBLOCK.

Only events that were copied out in full are dequeued.

Layout #

Every record begins with the same four fields.

OffsetSizeField
04total_len
42event_type
62name_len
8name_lenname, UTF-8

All integers are little-endian.

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 subtree watch's records carry additional fields after the name, locating the key the change happened on relative to the watched key:

SizeField
2path_depth
2 + n eachpath_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.

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.

The header offsets are ABI, named in include/uapi/pkm/lcs.h and listed in LCS ABI Reference.

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.

KEY_DELETED is not: a subtree watcher receives it in the subtree form, with a path_depth of its own.

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.

Length limits #

name_len and each component length are 16-bit.

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.

Forward compatibility #

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

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

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.

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.

Should the hiding layer later be deleted, the key reappears at its original path with the same GUID, and events resume. There is no re-emergence event; the watcher simply observes the key being active again.

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

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.

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.

Watches on a new key that later appears at the same path receive nothing from the old one.

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

The cost is O(depth) hash lookups, with no RSI round trips, no trie and no string comparison. 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.

Depth #

MaxSubtreeWatchDepth bounds how far below a watched key a subtree watch is told about. The default is 0, meaning unlimited.

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.

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

Transaction batches #

Nothing inside an uncommitted transaction dispatches.

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.

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

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.

That OVERFLOW is queued ahead of the batch, so it arrives before whatever else that watcher is still owed.

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. 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. The watcher re-reads, and can compare the generation number it last saw against the current one (Key Ioctls) 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.

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.

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

Source restart #

When a source disconnects, watches stay armed and nothing is delivered; operations needing the source return EIO.

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.

Existing fds resume without re-opening, and no watcher has to re-arm.

Queues and Overflow

Peios Kernel / Internals / LCS / Watches

Each armed fd has its own event queue, bounded by NotificationQueueSize — default 256 events, configurable between 16 and 65536 (Operational Parameters).

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.

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.
  2. An OVERFLOW record is queued in its place.
  3. The event that triggered this is discarded, not queued.

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

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.

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.

REG_IOC_QUERY_KEY_INFO reports a per-hive generation number (Key Ioctls) 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.

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.

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

Transactions

Peios Kernel / Internals / LCS / Transactions

Use these articles to understand transactions in the Peios kernel.

  • Scope and Lifetime
  • Isolation and the Mutation Log
  • Commit and Failure

Scope and Lifetime

Peios Kernel / Internals / LCS / Transactions

A transaction groups registry operations so that they commit together or not at all. 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 transaction begins in the state REG_TXN_ACTIVE_UNBOUND.

Binding #

A write transaction binds to a source on its first mutating operation.

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.

Reads never bind a write transaction.

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.

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

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.

The transaction stays ACTIVE_UNBOUND, its source binding untouched, and the caller can use the fd against a different hive.

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. If a source goes Down after binding, the transaction becomes REG_TXN_SOURCE_DOWN (Failure and Late Responses).

States #

StateValueMeaning
REG_TXN_ACTIVE_UNBOUND0Active, no source chosen.
REG_TXN_ACTIVE_BOUND1Active, bound to a source.
REG_TXN_COMMITTED2Commit completed.
REG_TXN_ABORTED3Explicitly or implicitly aborted.
REG_TXN_TIMED_OUT4The lifetime timer fired.
REG_TXN_SOURCE_DOWN5The 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.

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.
  • Explicit abort. close() without committing. The source is told to discard, and the object becomes ABORTED during release. No events.
  • Implicit abort. Process death closes the fd, which aborts it. There are no orphaned transactions.
  • Timeout. The lifetime timer fires. See below.

The object stays addressable after reaching a terminal state, until the fd is closed. That is what makes REG_IOC_TXN_STATUS useful.

Transaction fds are pollable. Any terminal transition wakes poll waiters with POLLERR | POLLHUP. A caller that needs a race-free reason for the wakeup queries the status.

Timeout #

The lifetime timer starts when the fd is created — not at the first operation — and runs for TransactionTimeoutMs, default 30 seconds.

When it fires, the object becomes TIMED_OUT, poll waiters are woken, and further use of the fd returns ETIMEDOUT.

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.

If the transaction was bound and no commit is already in flight, RSI_ABORT_TRANSACTION is sent to the source.

The fd is not removed from the caller's table; close() still releases it normally.

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.

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.

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.
  • One transaction per fd. A process may hold many transaction fds at once, but each is exactly one transaction.
  • Reads are permitted. A transaction is not write-only, which is what makes verify-then-write possible.

Isolation and the Mutation Log

Peios Kernel / Internals / LCS / Transactions

Read-your-own-writes #

Within a bound write transaction, reads see the transaction's own uncommitted writes. 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.

Externally, only committed state is visible. A transaction's writes are invisible to other threads and processes until commit.

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.

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.

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

Exceeding it fails the operation with ENOMEM.

An operation whose log entry cannot be allocated fails before it is sent to the source. 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.

It is retained across a post-dispatch commit timeout, because the source may still answer.

Sequence numbers #

A transactional mutation is assigned its sequence number when it is accepted into the transaction, not at commit. 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. Gaps in the sequence space are normal and mean nothing (The Sequence Counter).

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.

Resolution always uses the published layer cache, which is refreshed only at commit.

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.

Resolving any other value in the same transaction still uses the old precedence order. 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.

Conflicts #

Transactions are atomic. They are not conflict-detecting.

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

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

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.

Commit and Failure

Peios Kernel / Internals / LCS / Transactions

REG_IOC_COMMIT marks the transaction as having a commit in flight and sends RSI_COMMIT_TRANSACTION. What happens next depends on the answer.

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.

The object then becomes COMMITTED, the log is released, poll waiters are woken, and the ioctl returns 0.

The hive generation is incremented once per committed transaction per affected hive, however many operations the transaction contained.

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.

In both cases the transaction stays ACTIVE_BOUND:

  • the mutation log is retained;
  • no watch events are emitted;
  • poll waiters are not woken as though the transaction had become terminal.

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.

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.

ETIMEDOUT on a commit means may or may not have committed. A caller that needs certainty checks state before retrying.

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 late error releases the log with no effects.

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. The state reflects what the caller was told, not what the source did.

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 late response arriving afterwards does not resurrect the individual events once overflow recovery has been chosen.

The carve-out is narrower than it might appear. It covers the orphan lookup and the watch batch.

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.

Abort #

Aborting generates no events, ever, and releases the log.

The source is told to roll back with RSI_ABORT_TRANSACTION if the transaction was bound.

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

Sources

Peios Kernel / Internals / LCS / Sources

Use these articles to understand sources in the Peios kernel.

  • The Source Model
  • Registration and Slots
  • Request Dispatch
  • Validation
  • Failure and Late Responses

The Source Model

Peios Kernel / Internals / LCS / Sources

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). A source stores path entries, key records, value entries and blanket tombstones, and returns all of them on request.

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 source may back several hives; a hive is backed by exactly one source (Hives and Routing).

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.

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

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

loregd is not special #

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

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.

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.

What registration validates #

  • Every hive name is valid and is not the reserved CurrentUser (Hives and Routing).
  • No route identity — the folded name paired with its scope — collides with one held by another Active source.
  • Private hive collisions are scoped: the same name in different scopes is fine (Private Hives).
  • A hive's root GUID is not nil.
  • The root GUIDs within one request are distinct from each other.
  • A hive without RSI_HIVE_PRIVATE carries no scope GUID.
  • No unknown flag bits are set.
  • 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.
  • 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).

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.

Source slots #

Successful registration creates a source slot: the kernel object owning one connection and the hive set registered on it.

Each registered hive has a stable identity — its folded name, its visibility, its scope GUID for a private hive, and its root GUID.

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.

Slots are never freed, and collision checks see Down slots as well as Active ones.

Status is a property of the slot, not of an individual hive. A source's hives go Down together.

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.

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.

Other partial or malformed resume attempts fail EINVAL.

EEXIST is reserved for a collision with an Active slot; it never comes from a Down-slot collision.

When both an Active collision and a stale Down slot apply, EEXIST wins.

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

Coming back #

On a successful resume the slot becomes Active, its restart generation advances, and LCS replays any layer deletions that were pending.

LCS then delivers OVERFLOW to every armed watch on that source (Dispatch).

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.

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.

Request Dispatch

Peios Kernel / Internals / LCS / Sources

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.

Request ids are allocated per connection, strictly increasing, and never reused while the connection lives — including after a timeout.

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.

MaxConcurrentRSIRequests, default 256, bounds how many requests may be dispatched and awaiting a response at once. It is back-pressure for a slow source.

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.

If the deadline expires before a slot is reserved, the caller gets ETIMEDOUT and no request is sent.

If it expires after dispatch, the caller gets ETIMEDOUT and late-response handling applies (Failure and Late Responses).

The deadline is checked before admission is attempted, not only after a contention round is lost. 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.

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.

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.

When the deadline expires after dispatch, LCS detaches the waiting caller from the record and returns ETIMEDOUT.

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.

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

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), and RSI_ABORT_TRANSACTION cleaning up source transaction state.

Such a record occupies an in-flight slot and is retained like any other, and its response is validated normally and released normally.

But it is not a late response, and the retained-effect recovery rules do not apply to it merely because nobody is waiting.

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.

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.

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.

An empty queue blocks, or returns EAGAIN under O_NONBLOCK, or returns 0 if the fd is closing.

One write() submits exactly one complete response, and its length must equal the response's own total_len exactly.

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.

An fd that is open but has not yet registered reports nothing at all.

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 source that cannot speak the protocol correctly is not one whose other answers are worth believing.

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.

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.

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.

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

Validation

Peios Kernel / Internals / LCS / Sources

LCS validates every response before using it, and the failures split into two categories with very different consequences.

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.
  • 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).
  • The source stays alive. Corruption may be localised, and one bad key is not a reason to take a hive offline.

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. A malformed layer metadata descriptor additionally leaves the previous known-good one cached (Layer Metadata).
  • Names — layer names, key and child names, value names — must be valid under the ordinary rules for their kind.
  • 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).
  • Payload shape — an otherwise-matched response whose operation-specific payload is the wrong shape, carries trailing bytes, or encodes a path target invalidly.
  • Metadata closure — a lookup or enumeration whose per-GUID metadata block has missing, duplicate, unreferenced or nil entries. A HIDDEN entry must carry an all-zero GUID and contributes no metadata.
  • Value payloads — invalid types, a tombstone carrying data, data above MaxValueSize.
  • Orphan lists — a nil or duplicated GUID in an RSI_DELETE_LAYER response.
  • Status codes outside the defined vocabulary.

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.

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

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

When a source dies #

The connection closes unexpectedly, and:

  1. The slot is marked Down and its hives become unavailable.
  2. Every pending request fails EIO, including ones queued but not yet delivered.
  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.
  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.
  5. Watches stay armed. Watch state is kernel-side and does not depend on the source at all. Nothing is delivered during the window, and OVERFLOW arrives on re-registration rather than on disconnect (Dispatch).

Coming back is covered in Registration and Slots.

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

A late error #

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

A late successful read #

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

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. The watch dispatch takes the recovery form: a watcher receives an OVERFLOW ahead of the event itself (Dispatch).

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.

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.

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 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 late RSI_ABORT_TRANSACTION or RSI_FLUSH releases the record with no effects.

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. Watchers may therefore observe the effects of a transaction whose caller was told it timed out (Commit and Failure).

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 malformed late commit response takes the source down for the same reason.

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.

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.

Process exit closes them through normal kernel cleanup: key fds released and their watches removed, transactions aborted.

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

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

  • The Stream
  • Backup
  • Restore

The Stream

Peios Kernel / Internals / LCS / Backup and restore

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.

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.

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.

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.

Depth-first pre-order. A parent always appears before its children, so a restore can create keys top-down without buffering a tree.

Descriptors inline. Each key record carries its own descriptor with no deduplication. 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.

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 reader that finds a minimum above its own supported version rejects the stream outright, before touching anything.

Both are 21 in the current implementation, and the reader supports 21.

Unknown record types are skipped when the minimum reader version allows it, and they still count toward the record count and the checksum. 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. This is the opposite of the RSI's request convention (Validation), 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

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.

It requires SeBackupPrivilege and performs no per-key AccessCheck whatsoever. The privilege is the whole authorisation, which is why the operation is audited unconditionally (Audit).

The output fd must be writable, or EBADF.

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.

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 source that does not support read-only snapshots answers RSI_TXN_NOT_SUPPORTED and the backup fails ENOTSUP.

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.

Backing up an orphaned key is ENOENT: it is no longer a reachable subtree root (Deletion and Orphans).

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.

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.

lcs.audit.backup.ended is emitted afterwards, carrying the result, and a failure to emit it cannot change a result that has already happened.

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

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

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

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

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.

It requires SeRestorePrivilege and, like backup, performs no per-key AccessCheck and is audited unconditionally.

The input fd must be readable, or EBADF. Restoring onto an orphaned key is ENOENT.

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

One transaction #

The entire restore — teardown and rebuild together — is wrapped in a single read-write source transaction.

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.

Every failure path aborts the transaction, so a failed restore rolls back the teardown as well.

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.

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.

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.

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.

Descendants keep their backup GUIDs. Those are written into the target verbatim.

Order of operations #

  1. Validate the whole stream, including the trailer's record count and checksum, and retain every replayable record.
  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.
  5. Write the root's mutable fields, then replay its section's values and blanket tombstones.
  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.
  7. Commit.

The stream is read from the fd exactly once, sequentially. Nothing seeks, so a pipe is a valid input.

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.

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.

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

Both exist so that SeRestorePrivilege cannot be used to smuggle a Group Policy-tier layer past the defence in depth that guards precedence.

Layers in a restored stream #

Manifest records create, update, delete, enable, disable and authorise nothing.

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

If the metadata subtree is included, it is restored through the ordinary path, and those records — not the manifest — are what define the layer.

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.

Before dispatching the first layer-qualified record, LCS takes the global sequence-allocation gate and records the current next sequence as the offset.

Every restored record is then written with offset + backup_sequence, which preserves relative order while placing the whole set above pre-restore state.

The gate is held until the restore reaches a terminal state. Other sequence-allocating mutations wait; reads are not blocked.

A restore with no layer-qualified records at all never takes it.

If a remapped value would overflow, the restore fails EOVERFLOW — and it fails at validation, before teardown, rather than part-way through. The valid remapped range stops just below U64_MAX, which is never handed out (The Sequence Counter).

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. Sequence numbers a failed restore dispatched become unused gaps, exactly like those of any other failed write.

GUID collisions #

A GUID that appears twice in one stream, other than the root, is EINVAL. So is a non-root GUID equal to the target root's.

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.

The parent of every path entry, after remapping, must be either the restore root or a key record already processed earlier in the stream. 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.

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

A restore that fails or aborts before commit emits nothing.

Bootstrap

Peios Kernel / Internals / LCS / Bootstrap

Use these articles to understand bootstrap in the Peios kernel.

  • Dependencies and boot sequence
  • Operational Parameters
  • The Self-Watch

Dependencies and boot sequence

Peios Kernel / Internals / LCS / Bootstrap

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.

Rule 1: compiled-in defaults #

Every operational parameter has a compiled-in default, and LCS runs on those defaults from the moment PKM initialises.

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.

Before any source registers, the routing table is empty, so every operation that names a hive returns ENOENT. 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.

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

Rule 3: hot-swap, not restart #

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

Source dependencies are the source's problem #

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.

Normal boot #

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.

The refresh is triggered by the arrival of a global hive named Machine. 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). 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.

First boot #

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

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.

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

LCS reads nineteen parameters from Machine\System\Registry\.

All are REG_DWORD. Each has a compiled-in default and a valid range, and LCS runs on the defaults until the registry says otherwise.

ValueDefaultRangeBounds
RequestTimeoutMs300001000–600000A source round trip (Request Dispatch).
TransactionTimeoutMs300001000–600000The lifetime of an open transaction (Scope and Lifetime).
NotificationQueueSize25616–65536Queued events per watcher before overflow (Queues and Overflow).
SymlinkDepthLimit161–64Symlink resolution depth (Symlinks).
MaxValueSize10485764096–67108864One value's data, in bytes.
MaxKeyDepth51232–4096Key hierarchy nesting.
MaxPathComponentLength25564–1024One key, value or layer name, in UTF-8 bytes.
MaxTotalPathLength163831024–65535A whole path, in UTF-8 bytes.
MaxLayersPerValue1281–1024Layers writing to one (key, value name) (The Layer Model).
MaxBoundTransactionsPerSource161–256Concurrently bound transactions per source (Scope and Lifetime).
MaxReadOnlyTransactionsPerSource161–256Concurrent public read transactions and backup snapshots per source (Backup).
MaxTotalLayers102416–65536Distinct layers in the in-memory table (The Layer Model).
MaxRegisteredSources321–256Concurrently registered sources.
MaxHivesPerSource641–1024Hives one source may register.
MaxConcurrentRSIRequests2568–4096In-flight RSI requests per source (Request Dispatch).
MaxScopeGUIDsPerToken81–256Private hive scope GUIDs on a token (Private Hives).
MaxPrivateLayersPerToken161–256Private layer names on a token (Private Layers).
MaxSubtreeWatchDepth00–4096Subtree watch depth; 0 is unlimited (Dispatch).
MaxTransactionWatchEventBurst4096256–65536Watch events per watcher from one commit (Dispatch).

Unknown values under this key are ignored. 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), 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.

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). MaxScopeGUIDsPerToken behaves the same way.

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.
  • 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. An lcs.config.value.rejected audit event is emitted naming the parameter, what was wrong, and the value being retained (Audit).

Values are never clamped or silently corrected. 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 waits for it.

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

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.

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.

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

Operator verification #

Inspect the stored configuration and installed manual before tuning LCS:

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

Events reach it through a kernel callback rather than being queued for a read(), and it is therefore not subject to NotificationQueueSize.

It is also not subject to MaxSubtreeWatchDepth, nor to the transaction burst suppressor: internal collection happens before either test.

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.

What it drives #

Self-configuration. A change under Machine\System\Registry\ triggers a re-read and validation of the parameters (Operational Parameters).

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.

Layer lifecycle. SUBKEY_CREATED and SUBKEY_DELETED under Layers\ add and remove layers, except for base, which is ignored (The Base Layer).

KMES configuration. A third internal watch, on Machine\System\KMES\, exists for KMES's own parameters. It is not LCS configuration, but the registry is where it lives and this is the mechanism that notices it change.

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), and a callback that published a partial entry would create a window in which a layer exists and nobody can be authorised against it.

LCS also does not perform source round trips while holding the watch-map or layer-table publication locks. The refresh runs outside them, after the mutating operation commits and before the syscall returns.

Arming #

At bootstrap, LCS resolves the GUIDs for Machine\System\Registry\ and Machine\System\Registry\Layers\ through RSI_LOOKUP and arms targeted subtree watches.

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.

That fallback event re-enters the whole bootstrap refresh, which resolves the specific GUIDs and arms the targeted watches.

In practice the kernel arms both: targeted watches for whichever roots exist, plus the Machine\ root fallback, until a refresh finds everything present. 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.

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

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.

The failure and the fallback arm are both traced by lcs:lcs_bootstrap_refresh.

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.

Peios Learn — documentation for Peios software.

Built with Trail.