# Backup and restore

---

# Backup and restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Find the Peios kernel articles about backup and restore.

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

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

---

# The Stream

_Peios Kernel / Internals / LCS / Backup and restore_

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

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

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

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

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

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

## What the design buys

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

**Full layer fidelity.** Every path entry, value, tombstone and blanket
tombstone is stored with its layer tag, so restoring reconstructs the
layered state rather than a flattened snapshot of it. <a id="cite-backup.stream.entries-carry-their-layer-tag"></a>

**Depth-first pre-order.** A parent always appears before its children,
so a restore can create keys top-down without buffering a tree. <a id="cite-backup.stream.depth-first-pre-order"></a>

**Descriptors inline.** Each key record carries its own descriptor with
no deduplication. <a id="cite-backup.stream.descriptors-inline-without-dedup"></a> Redundancy is external compression's problem; piping
through zstd handles it.

**Self-verifying.** A trailer carries a record count and a SHA-256 over
everything before it, so truncation and corruption are detected. <a id="cite-backup.stream.trailer-carries-count-and-sha256"></a>

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

## Versioning

The header carries a format version and a **minimum reader version**. A
writer that used only older features sets a lower minimum, letting
older readers restore the stream. <a id="cite-backup.stream.header-carries-version-and-minimum-reader"></a>

A reader that finds a minimum above its own supported version rejects
the stream outright, before touching anything. <a id="cite-backup.stream.rejects-minimum-above-supported-version"></a>

Both are 21 in the current implementation, and the reader supports 21. <a id="cite-backup.stream.current-version-is-21"></a>

Unknown record types are skipped when the minimum reader version allows
it, and they still count toward the record count and the checksum. <a id="cite-backup.stream.unknown-records-skipped-but-counted"></a> A
writer that adds a record type a restore genuinely needs must raise the
minimum reader version, so that an older reader refuses the stream
rather than restoring an incomplete one.

Extension is by new **record types** only. Existing record payloads
must be consumed exactly; trailing bytes inside a known record are an
error. <a id="cite-backup.stream.trailing-bytes-in-a-record-are-an-error"></a> This is the opposite of the RSI's request convention ([Validation](</kernel/internals/lcs/sources/validation.md#trm-5-8-4>)),
and the difference is deliberate: a stream is replayed into mutations
long after it was written, and a field silently ignored there is data
silently lost.

---

# Backup

_Peios Kernel / Internals / LCS / Backup and restore_

> Writing a subtree to a stream under SeBackupPrivilege with no per-key access check — the snapshot, the audit, and what is written.

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

`REG_IOC_BACKUP` exports the key on the fd and its entire subtree to
another fd, preserving parent/child relationships even when traversal
must grow its internal storage. <a id="cite-backup.exports-the-key-and-its-subtree"></a>

It requires `SeBackupPrivilege` and performs **no per-key AccessCheck**
whatsoever. <a id="cite-backup.requires-sebackupprivilege-and-checks-no-key"></a> The privilege is the whole authorisation, which is
why the operation is audited unconditionally ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)).

The output fd must be writable, or `EBADF`. <a id="cite-backup.output-fd-must-be-writable"></a>

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

## The snapshot

Before reading anything, LCS opens a **read-only** source transaction —
`RSI_BEGIN_TRANSACTION` with mode `RSI_TXN_READ_ONLY` — so that the
whole export is a point-in-time snapshot. Concurrent mutations do not
appear part-way through the stream. <a id="cite-backup.opens-a-read-only-snapshot-transaction"></a>

That transaction is **released with `RSI_ABORT_TRANSACTION` and never
committed**. There is no commit call anywhere in the backup path; a
read-only transaction has nothing to commit. <a id="cite-backup.snapshot-released-with-abort-never-committed"></a>

A source that does not support read-only snapshots answers
`RSI_TXN_NOT_SUPPORTED` and the backup fails `ENOTSUP`. <a id="cite-backup.unsupported-snapshot-is-enotsup"></a>

A source already holding `MaxReadOnlyTransactionsPerSource` snapshots
(default 16) yields `EBUSY` — which bounds snapshot-holding without
treating backups as write-lock holders, since they are not. <a id="cite-backup.snapshot-limit-is-ebusy"></a>

Backing up an orphaned key is `ENOENT`: it is no longer a reachable
subtree root ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)). <a id="cite-backup.orphaned-key-is-enoent"></a>

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

## Audit

`lcs.audit.backup.started` is emitted **before any subtree data is read**, and
if it cannot be emitted the backup returns `EIO` and does not start. <a id="cite-backup.start-event-precedes-any-data-or-eio"></a>

After privilege, output-fd and key validation, START precedes the request for
the read-only snapshot. A refused or failed snapshot therefore emits both
START and END, with END carrying the failure errno; no subtree is exported
and no unopened snapshot is released. A START emission failure prevents the
snapshot request itself. <a id="cite-backup.snapshot-refusal-is-audited"></a>

`lcs.audit.backup.ended` is emitted afterwards, carrying the result, and a
failure to emit it cannot change a result that has already happened. <a id="cite-backup.complete-event-cannot-change-the-result"></a>

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

## What is written

The stream is a header, the layer manifest, then each key in
depth-first pre-order with its path entries, values and blanket
tombstones, then the trailer. The exact shapes are in the PSPK chapter.

Two things about the exporter are worth stating here, because they
constrain a reader more tightly than the format does.

The exporter writes **no GUID-bearing path entries for the backup
root**. The root's section contains only its hidden entries. <a id="cite-backup.root-section-has-no-guid-path-entries"></a>

A reader tolerates and skips them if some other writer produces them,
but this one does not emit them, because on restore the target key's
existing name is authoritative and they would be discarded anyway. <a id="cite-backup.reader-skips-root-path-entries"></a>

Hidden entries belong to the **parent's** section, not to a section of
their own — a hidden entry has no key to have a section for. <a id="cite-backup.hidden-entries-live-in-the-parent-section"></a>

A hidden entry masking a name where no key exists in any layer is still
valid; it expresses "this layer hides this name" whether or not
anything is there to hide. <a id="cite-backup.hidden-entry-without-a-key-is-valid"></a>

The layer manifest is written from the live layer table, and it is a
manifest: it records what the layers looked like at backup time so that
a restore can validate the stream against them. It is not a backup of
the layer definitions. <a id="cite-backup.manifest-is-written-from-the-live-layer-table"></a>

A layer definition is backed up only when
`Machine\System\Registry\Layers\<Name>\` is itself inside the subtree
being exported, in which case it is ordinary key and value data like
anything else. <a id="cite-backup.layer-definition-backed-up-only-if-inside-the-subtree"></a>

This includes definitions for unused layers in a whole-hive export.
Their metadata remains ordinary registry data; an unused definition
does not by itself require an entry in the layer manifest.

---

# Restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Restore is a replace rather than a merge — one transaction, the surviving target key, the order of operations, and the precedence gate.

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

`REG_IOC_RESTORE` **replaces** the key on the fd and its entire subtree
from a stream. It is not a merge: the target's contents and descendants
are torn down before the stream's contents are written. <a id="cite-restore.replaces-rather-than-merges"></a>

It requires `SeRestorePrivilege` and, like backup, performs no per-key
AccessCheck and is audited unconditionally. <a id="cite-restore.requires-serestoreprivilege-and-checks-no-key"></a>

The input fd must be readable, or `EBADF`. <a id="cite-restore.input-fd-must-be-readable"></a> Restoring onto an orphaned
key is `ENOENT`. <a id="cite-restore.orphaned-target-is-enoent"></a>

Because restore rewrites every descriptor in the subtree,
`SeRestorePrivilege` effectively confers `WRITE_DAC` and `WRITE_OWNER`
over everything within reach of one ([The Source Model](</kernel/internals/lcs/sources/the-source-model.md#trm-5-8-1>)).

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

## One transaction

The entire restore — teardown and rebuild together — is wrapped in a
single read-write source transaction. <a id="cite-restore.wrapped-in-one-read-write-transaction"></a>

A source that answers `RSI_TXN_NOT_SUPPORTED` for `RSI_TXN_READ_WRITE`
cannot be a restore target: restore requires atomicity and there is no
partial-restore mode. <a id="cite-restore.requires-read-write-transaction-support"></a>

Every failure path aborts the transaction, so a failed restore rolls
back the teardown as well. <a id="cite-restore.failure-rolls-back-the-teardown"></a>

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

## The target key survives

The stream's header names a root GUID, and that GUID is **remapped** to
the already-open target key everywhere it appears — in parent
references, in child references, in value key references — before
anything is validated or dispatched. <a id="cite-restore.root-guid-remapped-to-the-target"></a>

The target key **object** is not replaced. Its GUID, parent, name,
volatile flag and symlink flag remain what they were; they are never
taken from the stream. <a id="cite-restore.target-key-object-is-not-replaced"></a>

What the stream's root record supplies is the mutable part: the
Security Descriptor and the last write time, written to the target with
`RSI_WRITE_KEY` inside the transaction. <a id="cite-restore.root-record-supplies-descriptor-and-write-time"></a>

The root record's immutable flags must **match** the target's. A backup
of a volatile key restored onto a non-volatile one, or a symlink onto a
non-symlink, is `EINVAL`. <a id="cite-restore.immutable-flag-mismatch-is-einval"></a>

Descendants keep their backup GUIDs. Those are written into the target
verbatim. <a id="cite-restore.descendants-keep-their-backup-guids"></a>

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

## Order of operations

1. Validate the whole stream, including the trailer's record count and
   checksum, and retain every replayable record. <a id="cite-restore.validates-the-whole-stream-first"></a>
2. Read the layer manifest and apply the precedence gate (below).
3. Verify the root record and its immutable flags against the live
   target.
4. Tear down the target's contents and descendants — path entries,
   values, blanket tombstones, and descendant key records — inside the
   transaction. <a id="cite-restore.tears-down-the-target-inside-the-transaction"></a>
5. Write the root's mutable fields, then replay its section's values
   and blanket tombstones. <a id="cite-restore.writes-root-mutable-fields-then-its-section"></a>
6. For each non-root key in stream order: create it, write its last
   write time, then replay its path entries, values and blanket
   tombstones. <a id="cite-restore.replays-non-root-keys-in-stream-order"></a>
7. Commit.

The stream is read from the fd exactly once, sequentially. Nothing
seeks, so a pipe is a valid input. <a id="cite-restore.stream-read-once-sequentially"></a>

Validating the whole stream first is stronger than the format requires:
a checksum failure aborts before any source mutation rather than after
some. The cost is memory rather than seeking — the replayable records
are retained in kernel memory across the teardown.

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

## The precedence gate

Before any key record is written, LCS checks the layer manifest. If any
declared layer has a precedence above 0, **or** any existing cached
layer table entry with the same folded identity does, and the caller
does not hold `SeTcbPrivilege`, the restore aborts with `EPERM` before
a single byte reaches the source. <a id="cite-restore.precedence-gate-is-eperm-without-setcbprivilege"></a>

And if the stream contains ordinary key and value records for
`Machine\System\Registry\Layers\<Name>\`, writes that create or raise
persisted metadata above precedence 0 hit the ordinary inline
`SeTcbPrivilege` check as well ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

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

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

## Layers in a restored stream

Manifest records create, update, delete, enable, disable and authorise
nothing. <a id="cite-restore.manifest-records-change-no-layers"></a>

If restored entries reference a layer that is not in the current table,
and the stream does not also restore that layer's metadata subtree as
ordinary registry data, those entries become latent unknown-layer
entries and are ignored during resolution until real metadata exists
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-restore.unknown-layer-entries-become-latent"></a>

If the metadata subtree *is* included, it is restored through the
ordinary path, and those records — not the manifest — are what define
the layer. <a id="cite-restore.included-metadata-subtree-defines-the-layer"></a>

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

## Sequence remapping

Backup sequence numbers preserve the backup's internal ordering, but a
restore is a new mutation and its entries must outrank everything
already present. So the numbers are remapped rather than written
through. <a id="cite-restore.sequences-are-remapped-not-written-through"></a>

Before dispatching the first layer-qualified record, LCS takes the
global sequence-allocation gate and records the current next sequence
as the offset. <a id="cite-restore.takes-the-sequence-gate-before-the-first-record"></a>

Every restored record is then written with `offset + backup_sequence`,
which preserves relative order while placing the whole set above
pre-restore state. <a id="cite-restore.remapped-sequence-is-offset-plus-backup"></a>

The gate is held until the restore reaches a terminal state. Other
sequence-allocating mutations wait; reads are not blocked. <a id="cite-restore.gate-blocks-mutations-not-reads"></a>

A restore with no layer-qualified records at all never takes it. <a id="cite-restore.no-layer-records-never-takes-the-gate"></a>

If a remapped value would overflow, the restore fails `EOVERFLOW` — and
it fails at validation, before teardown, rather than part-way through. <a id="cite-restore.sequence-remap-overflow-is-eoverflow"></a>
The valid remapped range stops just below `U64_MAX`, which is never
handed out ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

When the restore reaches any terminal state — commit, abort, failure or
cancellation — LCS advances the global counter past the highest number
it dispatched, and **does not roll that back**. <a id="cite-restore.counter-advanced-at-any-terminal-state"></a> Sequence numbers a
failed restore dispatched become unused gaps, exactly like those of any
other failed write.

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

## GUID collisions

A GUID that appears twice in one stream, other than the root, is
`EINVAL`. <a id="cite-restore.duplicate-guid-in-the-stream-is-einval"></a> So is a non-root GUID equal to the target root's. <a id="cite-restore.non-root-guid-equal-to-the-root-is-einval"></a>

A non-root GUID that already exists **outside** the subtree being
replaced is `EEXIST` — but it is discovered by the source rejecting the
create during replay, not by a check beforehand. LCS has no index of
which GUIDs exist elsewhere, so the collision surfaces mid-restore, and
the transaction rolls back. <a id="cite-restore.external-guid-collision-is-eexist-mid-restore"></a>

The parent of every path entry, after remapping, must be either the
restore root or a key record already processed earlier in the stream. <a id="cite-restore.path-entry-parent-must-be-in-the-stream"></a>
That check *is* made up front, and it is what stops a crafted backup
injecting path entries into arbitrary parts of the existing namespace
outside the subtree being replaced.

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

## Watches

A restore is an arbitrary subtree replacement and LCS retains no exact
before-and-after diff for it. On a successful commit it publishes the
affected hive's generation increment and dispatches a no-name
`OVERFLOW` to the armed watches on that source ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-restore.commit-publishes-generation-and-overflow"></a>

A restore that fails or aborts before commit emits nothing. <a id="cite-restore.failed-restore-emits-nothing"></a>
