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

Sources

Single-page view · as markdown

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.

Peios Learn — documentation for Peios software.

Built with Trail.