# Boot and Shutdown

---

# Boot and Boot Modes

_Peios / Using Peios / Boot and Shutdown_

> Check the current boot, understand Full, Safe and Recovery modes, and plan console access before repairing a failed boot.

On a running machine, use `svctl boot` or **System Settings › Startup &
Shutdown** to see the mode, why it was chosen, and whether the boot has been
confirmed successful.

- **Full** starts the normal boot-triggered set.
- **Safe** starts a reduced boot-triggered set. Use the reported graph error
  or requested-mode reason to decide what to repair.
- **Recovery** provides an unrestricted SYSTEM shell on the console and skips
  Phase 2 services. `svctl boot` is not available there.

> [!IMPORTANT]
> Recovery needs physical, IPMI, or serial console access; there is no remote
> recovery service. Confirm that access before a change that can leave the
> machine unable to boot. Recovery offers no TCB guarantee.

## How this boot went

`svctl boot` asks peinit, and so does **System Settings**, at the top of its
**Startup & Shutdown** section:

```text
$ svctl boot
boot: full
reason: normal
unconfirmed boots before this one: 0 (recovery at 3)
confirmed: yes
grace: 30s
```

- **boot** is the mode, and **reason** why: `normal`, `requested`
  (`peios.safemode=1`), or a Safe mode peinit chose itself because a full boot
  couldn't be planned, with what stopped it.
- **unconfirmed boots before this one** is the boot-attempt counter as this
  boot found it, and the threshold at which the machine starts in Recovery.
- **confirmed** says whether this boot has counted as a success yet: every
  Critical service holding for `BootSuccessGrace`, and the counter put back
  to 0. Until then it names what it is waiting for.

Recovery mode never answers: it runs a recovery shell and no Phase 2 services
or peinit control interface. Registryd can already be running, but there is no
control socket to ask. Anyone signed in can ask; see [who can manage a
service](/peios/using-peios/services-and-jobs/who-can-manage-a-service.md) for the
descriptor.

## The three boot modes

The three modes form an escalation path from normal operation to last-resort
maintenance.

```mermaid
flowchart TD
    F["Full boot"] -->|success| OK["operational<br/>counter reset"]
    F -->|cycle/conflict w/ Critical| S["Safe mode<br/>(no reboot)"]
    F -->|Critical failure| RB["sync + reboot"]
    S -->|success| OKS["operational (reduced)<br/>counter reset"]
    S -->|Critical failure| RB
    RB --> CNT["counter increments"]
    CNT -->|counter ≥ N| REC["Recovery mode"]
    F -.->|Phase 1 failure| REC
```

### Full mode

The default. All boot-triggered services start in dependency order. A boot is
**successful** — and the [boot-attempt counter](#the-boot-attempt-counter)
resets to 0 — when every Critical service has reached and *held* a
dependent-satisfying state (Active, Completed, or Skipped) for a grace period
(`BootSuccessGrace`, default 30 s). The criterion is "satisfying," not
"Active," so that a Critical Oneshot that reaches Completed can still mark the
boot good.

### Safe mode

Safe mode starts a **reduced** set of boot-triggered services and rebuilds the
graph from scratch using only those, dropping dependencies on excluded
services. Two categories are eligible:

- **Critical services** (`ErrorControl=Critical`) — must start; a Critical
  failure here still follows the normal reboot path.
- **SafeMode services** (`SafeMode=1`) — best-effort; if they fail, Safe mode
  carries on without them.

Everything else is skipped. Safe mode is entered when:

- graph validation finds a **cycle involving a Critical service**, or
- an **unresolvable conflict involving a Critical service**, or
- the kernel command line says `peios.safemode=1`.

The first two are *configuration* errors — rebooting would hit them again
— so peinit downgrades **without** rebooting. Safe mode is **not** entered by
a Critical service *crashing at runtime*; that follows the reboot path. And it
is purely a boot-sequencing concern: once booted, you can start any service by
hand exactly as in Full mode. It is the mode for "the configuration is broken
but the TCB is healthy."

> [!NOTE]
> `SafeMode=1` and `ErrorControl=Critical` are *filters within the
> boot-triggered set*. They do not make a demand-only service auto-start in
> Safe mode — a service with no `boot` trigger stays demand-only regardless.

On a machine with the dynamic-boot feature, **System Settings › Startup &
Shutdown › Always Start in Safe Mode** puts `peios.safemode=1` on the command
line the next boot image is made from. Its next-boot effect depends on a
successful rebuild to the intended boot partition; verify the activation
chain.
Once present in the booted image it holds until changed there, and while the
machine is in Safe mode because of it, System Settings says so.

### Recovery mode

Recovery mode is the last resort, and it offers **no TCB guarantee** — the
administrator gets an unrestricted SYSTEM shell on the console and must treat
it with corresponding care. It is a maintenance *environment*, not a degraded
boot.

In Recovery, peinit completes the Phase 1 basics and starts registryd only if
that boot has not already attempted it; a failed registryd start is not
repeated. Registryd failure does not prevent the shell. peinit skips all Phase
2 services and execs a SYSTEM shell on `/dev/console` (`/bin/recsh` if
present, else `/bin/sh`), respawning it if it exits. It is entered when:

- the **boot-attempt counter reaches N** (default 3),
- the kernel command line says `peios.recovery=1`, or
- **registryd fails during Phase 1** — entered immediately, without rebooting,
  because there is no Phase 2 to attempt. The counter has already been
  incremented for this attempt.

Preserve the console failure reason and any source startup diagnostics first.
Identify the installed [registryd provider](#registryd), its
version, hive declarations and database paths. Recovery does not establish
that the registry source is stopped: a source started or attempted earlier in
the boot can still be active. **Do not start a second source against the same
hive files.**

Offline inspection or repair needs a procedure supported by that provider and
version. The [source-checked loregd
implementation](/peios/reference/loregd/startup/command-line.md#unsupported-recovery-switches)
has no offline repair switches and [does not create an automatic startup
backup](/peios/reference/loregd/startup/startup-sequence.md#backup-and-repair-limits). Its
orphan cleanup is not corruption repair or backup restoration; the references
identify the checked revision. Verify the existence and coverage of any
recovery copy before planning to replace data.

Follow [Recovery
troubleshooting](/peios/using-peios/services-and-jobs/troubleshooting.md#recovery)
for the evidence to collect and the point to involve the administrator or
provider. If the source can serve the required operations, the supported
[Backup and restore](/kernel/internals/lcs/backup-and-restore/overview.md)
workflow can recover a subtree; it depends on that working source and is not
offline source repair. Restore replaces data and permissions. Role definitions
can re-supply service configuration but do not restore all registry data.

> [!IMPORTANT]
> Recovery mode requires console access — physical, IPMI, or serial. There is
> no remote recovery in the current design (emergency SSH and registry
> historical reversion are noted as post-v1 work). Plan console access for any
> machine you need to be able to recover.

## The boot-attempt counter

The counter can escalate repeated unconfirmed boots to Recovery when peinit
reaches the increment and can persist it. It is a plain integer in a file at
`/.peinit/boot-attempts` — *not* in the registry, because the registry can be
the very thing that is broken. A confirmed boot resets the count; the counter
does not guarantee that every reboot loop ends in Recovery.

- peinit **reads** it at startup, before choosing a mode. The Recovery
  threshold (`counter ≥ N`) is checked against this pre-increment value, so
  the default N of 3 admits exactly three attempts before Recovery. A missing
  file counts as 0; a corrupt or unreadable one → Recovery. Override N with
  `peios.bootattempts=N` on the kernel command line, or set it to `0` to
  disable the check when the counter is itself the fault.
- peinit **increments** it once per boot after the root, mount, seed,
  machine-ID and clock steps, before registryd starts. A registryd startup
  failure therefore still consumes an attempt. An earlier failure that enters
  Recovery before this point does not increment it.
- `peios.recovery=1` forces Recovery but does not suppress the increment once
  that point is reached.
- The counter is **reset to 0** on a successful Full or Safe boot (after the
  grace period).
- If the counter file cannot be *written* (disk full), peinit treats it as 0
  and continues — a write failure must not by itself trigger Recovery.

A [Critical service](/peios/using-peios/services-and-jobs/supervision.md) exhausting its
restart budget — at boot or at runtime — triggers a sync and reboot. Repeated
boots that never complete the success grace accumulate attempts until the
counter reaches N and peinit enters Recovery. A failure after a confirmed boot
still reboots the machine, but that boot already reset the counter: repeated
late failures can therefore continue without reaching the Recovery threshold.
Use `svctl boot` to distinguish these cases. The counter deliberately does
*not* try to catch a peinit too broken to reach its own increment; that is a
binary-integrity problem, not a boot-loop problem. See the [TRM counter
cycle](/peios/reference/peinit/boot/the-boot-attempt-counter.md#the-cycle)
for the exact increment boundary.

## Boot configuration

| Key | Default | Controls |
|---|---|---|
| `Machine\System\Boot\MaxParallelStarts` | 10 | Services starting concurrently (must be > 0; invalid → Recovery). |
| `Machine\System\Boot\BootSuccessGrace` | 30 | Seconds a Critical service must hold a satisfying state before boot counts as successful. |
| `Machine\System\Boot\ShutdownTimeout` | 90 | Maximum seconds for the whole [shutdown](/peios/using-peios/boot/shutdown.md) sequence. |
| `Machine\System\Boot\PostKillTimeout` | 5 | Seconds a service cgroup can take to drain after SIGKILL before it counts as stuck. |
| `Machine\System\Boot\SettleTimeout` | 5 | Seconds peinit waits for the boot service set to settle before starting `boot:settled` services anyway. |

All but `ShutdownTimeout` are read at boot, so a change applies at the next
one; `ShutdownTimeout` applies the next time peinit re-reads its configuration
(`svctl reload-config`). **System Settings** shows and changes them in its
**Startup & Shutdown** section, under **Timeouts**: **Apply** and **Undo**
appear once one has been edited. Changing them needs write access to
`Machine\System\Boot` — as shipped, Administrators.

## The kernel command line

peinit reads the following `peios.*` tokens. They are deliberately few:
everything peinit can read *after* registryd is serving belongs in the
registry instead, where it can be inspected, secured and changed without
editing a boot entry. What is left is either a per-boot mode decision or a
Phase 1 value — one peinit needs before there is a registry to ask.

| Token | Effect |
|---|---|
| `peios.safemode=1` | Force [Safe mode](#safe-mode). |
| `peios.recovery=1` | Force [Recovery mode](#recovery-mode), whatever the counter says. |
| `peios.bootattempts=N` | Override the boot-attempt threshold; `0` disables the check. |
| `peios.notifysocket=PATH` | Move the sd_notify socket. Phase 1, because registryd is the first service to use it and it must be bound before registryd starts. |
| `peios.quiet=N` | How much peinit can write to the console: `0` write everything, `1` (default) stay out of a terminal a service owns, `2` also drop ordinary progress. See below. |

### Console noise: `peios.quiet`

peinit reports its progress to `/dev/console`, and so does any service that
claims that terminal with
[`TTYPath`](/peios/using-peios/services-and-jobs/execution-environment.md). Two writers, one
device: a sign-in prompt started while peinit is still narrating gets written
over, and the reader cannot tell input from log. `peios.quiet` decides who
yields.

It sets **two independent rules**, which is why it is a level and not a flag:

| | Terminal a service owns | Everywhere else |
|---|---|---|
| `peios.quiet=0` | peinit writes anyway | everything |
| `peios.quiet=1` *(default)* | only messages that mean the machine is about to be lost | everything |
| `peios.quiet=2` | only messages that mean the machine is about to be lost | errors only |

The rules **stack rather than scale**: errors are never less visible at `2`
than at `1`. An error overrides a requested blackout — silence was a
preference, and an error is news — but it does not override terminal
ownership, which is not peinit's to override. Only losing the machine
(dropping to [Recovery](#recovery-mode), halting with no shell, a Critical
service about to force a reboot) is worth one corrupted line of somebody
else's session.

[prelude](/peios/reference/peinit/boot/the-initramfs-contract.md) honors
`peios.quiet=2` as well, since it writes to the same console. The other two
levels mean nothing there — prelude exits before the first service starts, so
no terminal has an owner yet.

> [!WARNING]
> Suppressed messages are **dropped, not stored**. Until peinit can forward
> them to [eventd](/kernel/internals/kacs/auditing/overview.md), `peios.quiet=1` means you lose
> peinit's narrative from the moment a sign-in prompt appears. On a machine
> you
> are debugging, boot with `peios.quiet=0`.

A few lines escape all of this: whatever peinit and prelude print *before*
they have read the command line. Neither can honor a preference it has not
seen yet, and those lines are also the only evidence either started at all.

> [!NOTE]
> `peios.quiet` governs what **peinit** writes, and nothing else. The
> **kernel's** own console output is governed separately by the standard
> `loglevel` parameter, which shipped images set to `4` — errors and worse —
> so that peinit's narrative is not buried under the kernel's. The two are
> independent: setting `peios.quiet=0` to debug a boot does not bring the
> kernel's messages back, and `loglevel=7 ignore_loglevel` does not make
> peinit any louder. Note also that raising `loglevel` alone will not undo a
> shipped `ignore_loglevel`, and that the image ships no `dmesg`, so at the
> default a kernel warning is not recoverable after the fact.

### Seeing and changing it

**System Settings** shows the command line this boot was started with, under
**Kernel Command Line** in the **Startup & Shutdown** section, and the one the
next boot image will be made from, `/lcl/etc/boot/cmdline`, where they
differ.

On an installed machine the command line is part of the boot image, so editing
that file changes nothing on its own. Dynamic Boot supplies `mkuki-watch`,
but package delivery or feature enablement alone does not mean it is running
or rebuilding successfully. Check its selected input, output filesystem, and
completed rebuild using the activation
checklist.
With the feature installed, System Settings offers `peios.bootattempts` and
`peios.quiet` as choices — how many boots can fail before Recovery, and what
peinit writes on the console — and writes them into the file with **Apply at
Next Boot**, which appears once one has been changed. Nothing else on the line
is offered: a mistake there can leave a machine that doesn't boot. Writing the
file needs write access to it, which as shipped only Administrators have.

Unknown `peios.*` tokens are ignored, as is a malformed value on a valued
token — this parser runs before anything exists to report a diagnostic to, and
refusing to boot over a typo in a tuning knob is the worse outcome.

> [!NOTE]
> There is no token that selects services. Which services start is decided
> entirely by what is defined under `Machine\System\Services` — see [Defining
> a service](/peios/using-peios/services-and-jobs/defining-a-service.md). A console shell or
> a sign-in prompt is an ordinary service definition with a
> [`TTYPath`](/peios/using-peios/services-and-jobs/execution-environment.md), not a boot
> flag.

## Where peinit takes over

peinit is PID 1, but it is not the *first* thing that runs. The
[initramfs](/peios/reference/peinit/boot/the-initramfs-contract.md) assembles and
mounts the real root — decryption, RAID/LVM, the root filesystem itself — and
then hands control to peinit. The contract peinit relies on is narrow:

- The real root is already mounted **read-write**, and `/proc`, `/sys`,
  `/dev` are mounted and moved into it.
- peinit is exec'd as PID 1 from a fixed path on the real root.

peinit **does not** assemble, decrypt, repair, or even re-mount the root —
those need tools and configuration that belong to the initramfs. It also does
not `fsck` the root or mount non-root storage (a data partition is mounted by
an ordinary Oneshot service, not by peinit). For the trust and identity side
of this handoff — signatures, the SYSTEM token peinit inherits — see [peinit
at PID 1](/peios/reference/peinit/boot/phase-1.md).

## Phase 1: the hardcoded bootstrap

Phase 1 is compiled into peinit. It cannot change at runtime and touches no
registry. It does the minimum to make Phase 2 possible:

1. **Confirm the root is writable** with a single probe write. registryd's
   storage needs a writable root even for reads, so a read-only root cannot
   support Phase 2 → Recovery.
2. **Mount the remaining virtual filesystems** — `/dev/pts`, `/dev/shm`,
   `/run`, `/sys/fs/cgroup` — mounting each only if absent. A failure here →
   Recovery.
3. **Restore the persisted random seed** from `/var/state/peinit/random-seed`
   , mixing it into the kernel's entropy pool early so anything that needs
   randomness during boot gets it. A missing seed is normal — first boots and
   stateless live boots have none — so peinit carries on; a seed problem
   is never fatal and never sends boot to Recovery.
4. **Establish the machine-id** from `/lcl/etc/machine-id` — a stable, opaque
   identifier for this install (used for log correlation, instance identity,
   and software compatibility). It is *not* a security principal: it is not a
   SID, an account, or a credential, and no authorization decision depends on
   it. If the file is missing, empty, or malformed, peinit generates a fresh
   128-bit ID. If it cannot persist the ID, boot continues with a warning and
   an ID valid only for this boot; failure to obtain random bytes sends boot
   to Recovery.
5. **Set the clock from the hardware RTC**, so early timestamps and the boot
   counter are meaningful. A failure here → Recovery.
6. **Start registryd** and wait for it to signal readiness, then
   **probe-read** the schema-version key to confirm it is actually serving
   reads. Any failure → Recovery — there is no Phase 2 without a registry.
7. **Provision boot-time paths.** With registryd up and before Phase 2 starts,
   peinit applies the entries under `Machine\System\Init\ProvisionedPaths\` —
   the registry-driven equivalent of tmpfiles.d, creating directories, and
   files (with Peios security descriptors) that no single service owns.
   Best-effort entries that fail are logged and skipped, but an entry marked
   `Required=1` that cannot be provisioned sends boot → Recovery. The
   individual keys are cataloged in the [registry key
   reference](/peios/using-peios/services-and-jobs/registry-key-reference.md).
8. **Infrastructure setup** — create the [control
   socket](/peios/using-peios/services-and-jobs/controlling-services.md) and the [jobs
   socket](/peios/using-peios/services-and-jobs/jobs-and-operations.md), and bring up the
   loopback interface. A control-socket or jobs-socket failure → Recovery; a
   loopback failure is logged as a warning and boot continues.

Most Phase 1 failures are fatal to a normal boot, because none of the later
machinery can run without this foundation — the only outcome is [Recovery
mode](#recovery-mode). The exceptions are the fail-soft steps called out
above: a missing or unusable random seed, a regenerated machine-id, and
best-effort provisioned paths all let boot continue.

> [!CAUTION]
> Packaged images, VM templates, and live ISOs must not ship a populated
> `/lcl/etc/machine-id` or a `/var/state/peinit/random-seed` file. A shipped
> machine-id gives every clone the same identity, and a shipped seed is a
> public value that is not acceptable entropy. Clone and reset tooling should
> remove or truncate `/lcl/etc/machine-id` so peinit generates a fresh ID on
> the next boot, and should never bake a seed into the image — if you need
> strong first-boot randomness for a stateless image, provide a real kernel
> entropy source (hardware RNG or virtio-rng) instead.

### registryd

`registryd` is an **interface**, not a specific program. It is the path peinit
execs to get a registry source daemon — the component that implements the
registry's persistent storage and answers peinit's reads. The *implementation*
behind that interface can vary; by default it is **loregd**.

The distinction matters when diagnosing source failures: peinit's `registryd`
role does not define a storage-repair interface. Check which provider and
version the installation uses before choosing recovery instructions. The
default provider's database paths come from its startup hive declarations, not
registry settings. See [LCS and
sources](/peios/developing-for-peios/registry-sources/overview.md) for source
availability checks and the [Recovery-mode limits](#recovery-mode) before
direct storage work.

## Phase 2: the registry-driven boot

With registryd serving reads, peinit boots the rest of the system from the
registry:

1. **Read all definitions** under `Machine\System\Services\`. (A registry
   read timing out here → Recovery.)
2. **Build and validate the dependency graph** from the boot-triggered
   services and their transitive [dependency
   closure](/peios/using-peios/services-and-jobs/dependencies.md). Validation runs *before*
   anything starts.
3. **Start services in dependency order**, in
   [parallel](/peios/using-peios/services-and-jobs/dependencies.md) up to `MaxParallelStarts`
   , with [readiness gating](/peios/using-peios/services-and-jobs/the-service-lifecycle.md)
   releasing each service's dependents as it becomes satisfied.

Only services with a `boot` trigger are start candidates; demand-only services
are pulled in only if something boot-triggered depends on them, and
[Disabled](/peios/using-peios/services-and-jobs/triggers-and-timers.md) services are excluded
from the graph (but kept in the model for on-demand start). The whole boot
runs against one [snapshot](/peios/using-peios/services-and-jobs/defining-a-service.md) —
mid-boot registry edits do not perturb it.

The installed service graph determines the platform order. `registryd` and
`authd` use the SYSTEM bootstrap path; standard eventd and lpsd deployments
use `Identity=Service` and obtain tokens through authd. See [Service
identity](/peios/using-peios/services-and-jobs/identity-and-privileges.md). A non-SYSTEM
service's authority dependency is derived from its identity rather than left
to an administrator to remember.

Do not infer readiness or shutdown order from a fixed list of daemon names.
Check the installed definitions and the service status. The [boot
implementation](/peios/reference/peinit/boot/phase-2.md) describes graph
construction and validation.

## Where to start

To understand the graph validation and parallel start that drive Phase 2, read
[Dependencies and ordering](/peios/using-peios/services-and-jobs/dependencies.md).

To understand the Critical-failure reboot path that feeds the boot counter,
read [Keeping services running](/peios/using-peios/services-and-jobs/supervision.md).

For the trust and token side of early boot, read [peinit at PID
1](/peios/reference/peinit/boot/phase-1.md).

---

# Prelude

_Peios / Using Peios / Boot and Shutdown_

> How Prelude prepares the temporary boot environment and hands control to the init on the real root filesystem.

Prelude starts the userspace part of Peios boot. It runs inside the
initramfs, a small filesystem unpacked into memory, until boot hooks have
made the real root filesystem available. It then replaces itself with the
init that manages the running system.

The two programs keep the same process number, 1, but have different jobs.
Prelude prepares one handoff. The real-root init manages services after it.
Storage discovery, unlocking, and root mounting belong to hooks supplied by
the image's packages.

## From temporary root to real root

Prelude mounts the kernel's process, system, and device filesystems. It
seeds access control on existing device nodes, then reads the sequence of
hooks written by `mkirf`. The sequence tells it which hooks can run and
which capabilities each hook needs.

A hook mounts the real root at `/mnt/rootfs`. Prelude checks that this is a
different filesystem from the temporary root, moves the kernel filesystems
into it, removes the old temporary files where possible, and changes its
root directory. A successful exec transfers control to the selected init.
The complete parameter and path reference is `prelude(8)`.

## Why hook outcomes matter

A hook can finish its work, decline because it does not apply to this
machine, or defer because an input is not ready. Deferral is safe only when
the hook has made no changes. Prelude retries deferred work after another
hook makes progress; it does not retry a failed hook that might have left
partial changes.

Capabilities let a hook depend on a result instead of another hook's name.
For example, several storage hooks can contribute toward preparing storage.
A later hook waits for their contributions before using it. The runtime
format and precise outcome rules are described in `prelude-hooks(5)`.

Hooks can source `/usr/libexec/prelude/hook-log.sh` for consistent status
messages. The helper prints message text literally, so a backslash in a
filename keeps its meaning when color is enabled.

## Access control during boot

The initial device policy grants full access to SYSTEM and Administrators.
An inherit-only CREATOR OWNER entry gives a creator control over the
objects it creates. The policy does not grant Everyone access: a broad
inherited grant could expose raw disks as well as ordinary device nodes.

A failure to seed device descriptors produces a warning and boot continues.
A hook failure or missing real root stops the handoff. Those outcomes need
different responses; a completed boot does not prove every device received
its intended descriptor.

## Assembling and updating the temporary root

The conventional source tree is `/boot/initramfs`. It must contain Prelude,
its interpreter and helper dependencies, the hook sequence, and the drivers
needed to reach the target root. The `mkirf` build resolves hook ordering;
Prelude consumes that result. An ordinary source-tree edit does not change an
already-built initramfs or UKI. Rebuild the artifact, deploy it through the
image's boot workflow, and verify which artifact the next boot actually loads.

The temporary root is independent of the installed root. A helper available
under the installed `/usr` is not thereby available before handoff. Include
its dynamic loader and libraries, or use an appropriate static build. Do not
assume runtime `/bin` and `/lib` views exist before their topology hook runs.

Module availability, dependency closure, loading, and root readiness are
separate checks. Include modules matching the booted kernel and their
required providers. A package-supplied coldplug hook can scan modaliases in a
bounded settling window; Prelude itself is not a hotplug manager. A module
loading failure matters according to whether a later hook can still prepare
the root. Hardware that appears after that window needs the real-root device
manager or an explicit boot design.

For storage changes, preserve a known bootable artifact and test the intended
hardware or recorded VM image. Do not infer that every firmware-dependent or
network-root configuration fits a generic storage-only module set. The exact
init selection, fallback paths, and root-switch behavior are in `prelude(8)`;
the supplied image decides which candidates and tools exist.

## Authoring hooks

For capability declarations, runtime outcomes, and console reporting, read
[Writing Boot Hooks](/peios/using-peios/boot/writing-boot-hooks.md).

---

# Bootstrap Descriptors

_Peios / Using Peios / Boot and Shutdown_

> Why seed-sd uses a narrow initial access policy and why runtime trees can need a different descriptor.

A newly mounted filesystem needs access control before boot tools can use
it. The `seed-sd` helper establishes that initial security descriptor. Its
bootstrap policy gives SYSTEM and Administrators full access and adds an
inherit-only rule for the creator of each new object.

## A template reaches later objects

Inheritance applies the directory's template when a child is created.
Changing the directory later does not rewrite every existing child.
Prelude therefore calls `seed-sd` recursively on `/dev`, covering the nodes
already present as well as the directory that supplies later inheritance.

The walker writes a node's descriptor before inspecting its descendants.
That order allows it to enter a directory whose missing descriptor would
otherwise deny access. Symlinks receive their own descriptor; the walker
does not follow their targets.

## Bootstrap policy has a limited purpose

The default is suitable for making a fresh tree administrable. It is not a
complete access policy for a running system. Granting Everyone read access
at the device root would also reach newly created raw disk nodes, where
reading the disk can bypass file-level access control.

A caller that prepares a different tree can supply an explicit descriptor
with `seed-sd --sddl`. That caller owns the broader policy and its scope.
The command's options, required privileges, and exit statuses are recorded
in `seed-sd(8)`.

## Partial failure is visible

Recursive seeding continues after errors where traversal remains possible.
It reports failures and returns an unsuccessful status, but it does not
undo descriptors already written. An installer or hook must use that
status when deciding whether its own work succeeded.

The helper rejects command-line arguments containing invalid UTF-8 before
applying any descriptor. During a recursive walk, a descendant name that
cannot be represented as UTF-8 is reported as a failure and skipped.

---

# Debugging Initramfs Boot

_Peios / Using Peios / Boot and Shutdown_

> Pause Prelude at a hook or inspect a failed boot from its recovery shell.

Use Prelude's recovery shell to inspect a boot that fails before the
real-root init starts. A breakpoint lets you inspect or repair the temporary
environment and then continue the same boot.

## Before you start

- Use a disposable test image or a machine you can recover independently.
- Have access to its boot parameters and boot console.
- Include `/usr/bin/sh` and the inspection tools you need in the image.
- Treat the recovery shell as privileged access to the boot environment.

## Stop before the hooks

1. Add `rd.break` to the image's kernel command line and boot it.
2. Wait for Prelude's breakpoint message and shell.
3. Inspect `/system/prelude` and the hook scripts named by its sequence.
   This breakpoint occurs before Prelude reads that sequence, so an edit
   made here takes effect when you resume.
4. Exit the shell to continue boot.

To stop before one hook instead, use `rd.break=` followed by its filename
or complete path. For example, `rd.break=mount-root` matches a hook whose
final path component is `mount-root`. Use the name present in your image.
The full syntax is in `prelude(8)`.

## Inspect a failure

1. Add `rd.shell` to the kernel command line and boot the image.
2. Read the failure message before using the shell. A hook error identifies
   the failed hook; an unsatisfied capability identifies pending work.
3. Inspect the files and mounts that remain at the point of failure. Before
   handoff, the intended real root is `/mnt/rootfs`. After a root switch,
   paths resolve inside the new root.
4. Exit when finished. A failure shell continues to the halt path, not back
   to the failed boot operation.

## Check the result

A successful breakpoint recovery reaches the real-root init. A failure
shell ends at the halt path after you exit. If no shell starts, look for the
reported exec error and check that `/usr/bin/sh` exists in the filesystem
visible at that stage.

Do not start the Prelude executable from an ordinary terminal to reproduce
a boot problem. Its operations include mount changes and removal of files
from the old root.

---

# Writing Boot Hooks

_Peios / Using Peios / Boot and Shutdown_

> Prepare the real root through explicit hook capabilities, outcomes, and console reporting.

A boot hook performs a deployment-specific part of early boot, such as
unlocking storage or mounting the real root at `/mnt/rootfs`. Prelude runs
the generated hook sequence before handing control to the real init process.
Put service startup and ongoing supervision in Peinit instead.

## Before you start

- Prepare an initramfs source tree and a disposable boot environment.
- Include each hook's interpreter, tools, and required drivers in that tree.
- Read `mkirf(1)` for image construction and hook metadata syntax.
- Arrange the access policy required by the storage operations you perform.

Hooks run under the bootstrap SYSTEM token. That authority does not remove
kernel access checks or replace the security descriptors needed during boot.
See [Prelude](/peios/using-peios/boot/prelude.md) for the stage's
responsibilities and handoff checks.

## Choose a location and declare dependencies

1. Put a packaged hook under `usr/libexec/prelude/hooks.d/` in the image tree.
   Put an operator-owned hook under `lcl/libexec/prelude/hooks.d/` instead.
2. Give it a distinct filename, an available interpreter in its shebang,
   and executable permissions. An operator hook with the same filename
   replaces the packaged hook at image construction.
3. Declare its capabilities in a comment block:

   ```sh
   #!/usr/bin/sh
   # /// hook
   # contributes = ["rootfs-ready"]
   # ///
   ```

This example declares part of the work needed for the real root. It is not a
complete hook: append the required checks and operation before including it
in an image. File extensions have no special meaning, and numeric prefixes
are only filename tie-breakers, not a dependency mechanism.

## Express what the hook needs and supplies

The metadata distinguishes alternatives from work that must all complete:

| Declaration | Meaning |
|---|---|
| `provides` | Any successful provider can satisfy the capability |
| `contributes` | All contributors must complete their part |
| `requires` | The capability must be achieved before this hook runs |
| `after` | If supplied, wait for the capability's suppliers to settle |

`after` allows an optional milestone to be absent. It does not assert that
the milestone succeeded. Use `requires` when running without the achieved
capability would be incorrect. A capability cannot mix `provides` and
`contributes` suppliers.

Three shared milestones connect independently packaged hooks:

| Capability | Meaning |
|---|---|
| `initramfs-ready` | The initramfs topology and console are usable |
| `rootfs-ready` | The real root is mounted at `/mnt/rootfs` and ready for work |
| `rootfs-strata-ready` | The StrataFS topology exists inside that root |

The builder orders declaring hooks after `initramfs-ready` unless they
supply it or already declare a dependency on it. An image without a supplier
does not gain a missing requirement from this implicit ordering. An explicit
`requires` retains its stronger meaning.

For example, an unlock hook and a root-mount hook can both contribute to
`rootfs-ready`. The mount hook can defer until the unlocked device exists.
This allows independent storage layers to compose without naming every
other hook. Where a prerequisite is known, declare it explicitly.

## Return the right outcome

| Exit | Meaning | Scheduler action |
|---|---|---|
| `0` | The hook completed its work | Record success |
| `69` | The hook has no applicable work | Record a deliberate decline |
| `75` | Inputs are not ready and nothing changed | Retry after other progress |
| Other | An attempted operation failed | Stop boot with the hook's failure |

A declining contributor has completed its part. A declining provider has
not achieved its capability; another provider must succeed if a dependent
hook requires it. Do not report success merely because the hook does not
recognize the machine.

Check for readiness before making changes. Returning `75` promises that
retrying the hook does not repeat a partially completed operation. Once an
operation has been attempted and failed, return a failure instead of hiding
it as a deferral. Prelude stops when a full pass makes no progress while
work remains.

A hook killed by a signal fails. A hook stopped by job control is killed and
reported as stopped; the boot environment does not provide an interactive
job-control session to resume it. Failure does not roll back earlier hooks.

Selected root strategies should diagnose missing required inputs. The
retained live-boot and disk-boot package recipes select one strategy through
conflicting packages; they do not use runtime decline to choose between two
broken configurations. A custom image needs its own explicit selection.

## Report progress and failures

Standard output and standard error go directly to the console. Prelude does
not capture and relabel each line. If the image supplies the level-three
`prelude-hook-abi` helper, source it and use your hook's own name:

```sh
. /usr/libexec/prelude/hook-log.sh
hook_log_init example-root
log "checking root device"
log_ok "root device checked"
log_skip "optional device absent"
log_warn "optional device unavailable"
log_fail "root device check failed"
```

Declare a dependency on `prelude-hook-abi >= 3` when using this helper.
`log_warn` and `log_fail` write to standard error; the other functions write
to standard output. The helper observes the console color convention,
including `TERM=dumb` in the kernel command line.

Use a progress verb for work about to happen and a completed verb only after
success. Logging failure does not itself replace returning a failure status.
Do not log secrets used to unlock storage.

## Build and check the result

1. Check shell syntax with the interpreter used by the image, then build the
   archive with `mkirf`. Resolve warnings about replaced or undeclared hooks.
2. Inspect the generated `/system/prelude/hooks.seq.<n>` files in the image.
   Confirm the chosen paths and capabilities. Do not edit generated sequences.
3. Boot the disposable image. Exercise success, inapplicable hardware,
   missing inputs, deferred work, and operation failure.
4. Confirm that `/mnt/rootfs` is a separate mounted filesystem and that the
   expected init process starts after handoff.

Prelude reads the newest supported sequence version. An unsupported version
produces a warning when a supported fallback exists, or an error when none
exists. The warning remains visible at `peios.quiet=2`. A missing sequence
is an error; an intentionally empty manifest is distinct from a missing one.
Malformed selected manifests also fail rather than silently rescanning hooks.

For discovery and dependency validation during image construction, see
[Building an Initial RAM Filesystem](https://learn.peios.org/peios/using-peios/boot/mkirf/).
A successful archive build does not establish that its tools, policy, or
storage configuration can boot.

---

# Building an Initial RAM Filesystem

_Peios / Using Peios / Boot and Shutdown_

> Understand how a source tree becomes a deterministic early-boot archive.

`mkirf` builds an initial RAM filesystem, or initramfs, from a source
directory. The kernel unpacks that archive to provide files needed before the
final root filesystem is ready.

## Source files and generated order

Source-tree contents map onto the archive's root. The tree needs an executable
`init` and supported entry types. Sockets and preexisting generated
hook-sequence files are rejected.

Packaged hooks and operator-provided hooks can declare dependencies. Operator
hooks take precedence when filenames match. The builder resolves those
declarations into a valid order and emits versioned sequence files under
`/system/prelude` without writing them into the source tree.

A missing required capability or a cycle prevents a valid order. A hook
without metadata is handled separately, with a warning and a defined
late-order position. Do not mistake that compatibility path for dependency
validation.

## Determinism is an archive property

The builder sorts entries and normalizes metadata that would otherwise vary
between runs. Regular-file executability remains significant, while ownership,
timestamps, and archive inode numbers are normalized.

Compression settings also form part of the result. The default uses zstd; gzip
is available for a kernel without support for the default format. Compare
builds made with the same inputs, settings, and implementation. A
deterministic archive does not itself prove a bootable or trusted image.

## Early segments precede compression

The kernel reads some content before it decompresses the main archive: CPU
microcode and ACPI table overrides. This content forms the early part of the
initramfs. Packages place it in `/usr/lib/earlyirf/`, and an administrator
can place it in `/lcl/lib/earlyirf/`. Each child directory is one segment,
and its contents map onto the archive root. For example,
`/usr/lib/earlyirf/intel-ucode/kernel/x86/microcode/GenuineIntel.bin`
becomes `kernel/x86/microcode/GenuineIntel.bin`.

A segment in `/lcl/lib/earlyirf/` replaces the segment of the same name in
`/usr/lib/earlyirf/`, and mkirf warns about the replacement. mkirf still
reads segments from the old `++` directory at the root of the tree and warns
about each one.

The segments are combined into an uncompressed early archive ahead of the
main archive, which does not hold them. Conflicting entries are rejected
rather than silently choosing a copy.

## Watch mode is a build loop

Watch mode builds once, then waits for source changes to settle before
rebuilding. A failed rebuild is reported while the watcher remains available
for a later correction. Keep the output outside the watched tree to avoid
triggering a rebuild with its own output.

Successful writing replaces the output through a sibling temporary file. That
protects against presenting a partial assembled archive; it is not a boot test
or a full power-loss durability guarantee.

`mkirf(1)` defines source layout, hook rules, metadata normalization,
compression, exclusions, and watch behavior. Validate the resulting image in
the boot environment before selecting it for deployment.

## Hook discovery and validation

The builder scans regular files directly inside `usr/libexec/prelude/hooks.d`
and `lcl/libexec/prelude/hooks.d` in the source tree. It does not recurse into
subdirectories or select a particular extension. A filename identifies one
hook; an operator copy wins over the vendor copy, with a diagnostic naming
the replacement. The legacy root-level `hooks` directory is accepted with
migration warnings.

A hook's metadata opens with exactly `# /// hook` and closes with `# ///`.
Between those lines, each line is a comment. The supported keys are
`provides`, `contributes`, `requires`, and `after`, each holding a list of
double-quoted capability names. Empty lists and trailing commas are accepted.
This is a restricted declaration format, not arbitrary TOML.

Unknown keys, malformed lists, duplicate or unclosed blocks, missing required
capabilities, dependency cycles, and mixed provider/contributor definitions
are build errors. A declared empty block differs from having no metadata.
Undeclared hooks are warned about and placed after declaring hooks.

Dependency edges place suppliers before consumers. Filename order breaks
ties between unrelated hooks. The builder materializes implicit
`initramfs-ready` ordering in the generated manifest, retaining an explicit
`requires` instead of weakening it to `after`. Prelude then consumes that
manifest; it does not rediscover or reorder the source directories at boot.

[Writing Boot Hooks](/peios/using-peios/boot/writing-boot-hooks.md)
explains capability achievement, decline, deferral, and console reporting.
Image construction checks declarations; boot testing checks whether those
claims match the hook's behavior.

---

# Assembling a Unified Kernel Image

_Peios / Using Peios / Boot and Shutdown_

> Understand how the kernel, initramfs, and command line become one firmware executable.

`mkuki` assembles a unified kernel image (UKI). It appends a kernel, an
initramfs, and a command line to a firmware executable stub so that the boot
payload travels as one file.

## Three payloads and a stub

The command line, kernel, and initramfs occupy separate named sections in the
executable. The stub reads those sections at boot. The default stub is bundled
into the utility; its provenance can be inspected separately.

Command-line input can come from a literal value or a file. Trailing line
endings are removed and a terminator is added. Embedded zero bytes are
rejected rather than silently shortening the command line.

## Select a kernel image

A concrete image path selects exactly that file. Directory selection reads
`vmlinuz` directly in the selected directory, normally `/usr/lib/modules`.
A Peios system closure has one kernel, at `/usr/lib/modules/vmlinuz`, with
modules in the same directory and no release subdirectory.

Directory selection reads the image again after a directory changes. A
missing image makes that rebuild fail while leaving the watcher available to
retry.

## Publication and signing are separate

The assembled image is written through an exclusively created sibling
temporary file and then replaces the output. A failed staging write does not
replace the accepted output with a partial assembly.

The command does not sign the image. A complete firmware executable is not
proof that its payloads are trusted or bootable. Signing, trust policy, and
boot qualification are separate steps.

## Watch the inputs without watching the output

Concrete input files are observed through their parent directories so that
atomic file replacement is visible. Directory selection watches the selected
directory nonrecursively. Output paths that feed back into those watched
locations are rejected.

After changes settle, the watcher rebuilds. Failure is logged rather than
ending the loop, so the last output can remain older than the inputs. Monitor
diagnostics instead of treating the existence of an output file as proof of a
successful latest build.

`mkuki(1)` defines section construction, kernel selection, stub inspection,
watching, and output failures.

---

# Applying a Root Skeleton

_Peios / Using Peios / Boot and Shutdown_

> Understand how a new root gets the directories and links outside /usr that no package can ship.

`skeleton apply` makes the directories and links a root needs outside `/usr`.
Packages only install under `/usr`, so `/var`, `/lcl`, `/tmp` and the `/lib64`
link to the dynamic loader come from a root skeleton file instead. The
`dev.peios.fsbase` package ships that file at `/usr/share/skeleton`, and
whatever builds a root applies the copy in that root's own `/usr`.

```sh
skeleton apply /mnt/root
```

The live-boot hook runs this after composing the live root. An installer or an
upgrade tool runs it against the root it builds. `--file` applies another file
instead of the root's own, and `--verbose` prints each entry it makes.

## Making what is missing

`skeleton` reads and checks the whole file, including every security
descriptor, before it changes anything. A file with an error changes nothing.

It then works through the entries in order. It makes each missing directory or
link, and leaves each existing one alone, even if its security descriptor
differs from the file's. Running it again makes nothing new.

It stops with an error when something of another kind is in an entry's place,
such as a file where a directory belongs, or a link with a different target.
It never follows a link to reach an entry. Entries made before the error stay,
so you can run it again after removing what was in the way.

## Descriptors at creation

A directory with a descriptor in the file is created with that descriptor in
the same native create call. It never exists with an inherited descriptor
first. A directory without one inherits from its parent.

A descriptor doesn't need to grant whoever applies the skeleton any access.
The create succeeds even if the new descriptor would deny its creator.

The file's format is specified in PSPU 11.

---

# Shutting Down and Rebooting

_Peios / Using Peios / Boot and Shutdown_

> Power off or reboot through peinit, understand graceful timeouts, and reserve forced shutdown for a stuck system.

Use `svctl shutdown` when you intend to stop the machine. Choose one action:

```sh
svctl shutdown poweroff
svctl shutdown reboot
svctl shutdown halt
```

These are alternatives, not a sequence. Each interrupts running services and
jobs and requires `SYSTEM_SHUTDOWN`. Save work and account for other users
before issuing one. `halt` stops the CPU but leaves power on.

A normal shutdown stops dependents before their dependencies, gives running
services time to exit, then unmounts, syncs, and performs the selected action.
Forced shutdown skips that opportunity to finish work.

## How shutdown is triggered

There are four paths into shutdown, and they are not equal — three are
graceful, one is not.

**A control command.** An administrator with `SYSTEM_SHUTDOWN` runs
`svctl shutdown <type>` (the familiar `reboot`, `poweroff` and `halt`
commands, and `shutdown -r now`, are the same client under other names):

| Type | Result |
|---|---|
| `poweroff` | Stop everything, unmount, power off. |
| `reboot` | Stop everything, unmount, reboot. |
| `halt` | Stop everything, unmount, halt (CPU stopped, power stays on). |

**Signals.** As PID 1, peinit treats a handful of signals as shutdown
requests:

| Signal | Meaning |
|---|---|
| SIGINT | Reboot — the kernel sends this on Ctrl-Alt-Del. |
| SIGTERM | Poweroff. |
| SIGPWR | Poweroff — a compatibility path for environments that surface power failure or power-button policy as a signal. |

**The power button.** On Linux, a physical power-button press is a graceful
`poweroff` — peinit watches the machine's input devices under `/dev/input` and
treats a `KEY_POWER` press (the key going down, not its release or
auto-repeat) as a shutdown request. This path is deliberately minimal and
**fail-soft**: if `/dev/input` is missing, an input device cannot be opened,
or a device stops responding, peinit keeps running and drops that device
— the button quietly stops working, but the machine stays up and you can still
shut down over the control socket or with a signal. It is not a full
power-management policy engine; a separate power-management daemon can add
richer policy on top by sending control-socket commands.

**A Critical service failure** — the ungraceful path. When an
`ErrorControl=Critical` service exhausts its [restart
budget](/peios/using-peios/services-and-jobs/supervision.md), peinit **syncs and reboots
immediately**. There is no service-stop ordering: the system is in an
undefined state and the fastest route to a known one is a reboot. This is what
feeds the [boot-attempt
counter](/peios/using-peios/boot/boot-and-boot-modes.md), and a Critical service
that fails identically every boot becomes a reboot loop that the counter
eventually breaks by escalating to Recovery.

## The graceful sequence

For a `poweroff`, `reboot`, or `halt`, peinit runs an ordered sequence:

1. **Enter the shutdown state.** A flag is set, and while it holds: **no new
   services can start**, timer triggers are disarmed, and new lifecycle
   commands are rejected with `INVALID_STATE`. Status, list,
   operation-status, boot, and job query/stop commands remain available so you
   can watch progress or stop a job sooner.
2. **Suspend Critical-failure semantics.** If a Critical service fails
   *during* shutdown, it is logged but does **not** trigger a reboot — the
   system is already going down, and rebooting would loop.
3. **Clear Completed services.** Oneshot services sitting in
   [Completed](/peios/using-peios/services-and-jobs/the-service-lifecycle.md) (with
   `RemainAfterExit`) have no process; peinit moves them to Inactive so their
   dependents can be stopped cleanly.
4. **Stop every live [submitted
   job](/peios/using-peios/services-and-jobs/jobs-and-operations.md) at once** — SIGTERM,
   then SIGKILL of the job's cgroup after its own `stop_timeout` — and cancel
   any job still queued to launch, both with cause `shutdown`. Jobs have no
   dependencies, so there is no order among them and nothing waits for them to
   finish before the service waves begin; but shutdown does not complete while
   a live job remains, within the same global timeout.
5. **Stop services in reverse dependency order**, in waves. Each
   graceful-stop-eligible service (those in Active or Reloading) gets SIGTERM
   and `StopTimeout` seconds to exit; if it does not, peinit SIGKILLs its
   whole cgroup. A service is never stopped until everything that `Requires`
   or `BindsTo` it has already stopped. Services that are Starting are not
   stopped gracefully — their startup is canceled and the cgroup SIGKILLed.
6. **Enforce the global timeout.** The whole sequence is bounded by
   `ShutdownTimeout` (default 90 s). When it expires, all remaining services
   are SIGKILLed; any whose cgroups do not empty within the post-kill timeout
   (default 5 s) become
   [Abandoned](/peios/using-peios/services-and-jobs/the-service-lifecycle.md) (leaked), and
   shutdown continues regardless.
7. **Save the random seed.** With every service stopped and before any
   filesystem is touched, peinit writes a fresh seed drawn from the kernel's
   CSPRNG to `/var/state/peinit/random-seed` — this is the entropy the *next*
   boot starts from. The write is crash-conscious (written to a temporary
   file, flushed, then atomically swapped in), and it is best-effort: if it
   fails, peinit logs it and carries on. Shutdown never stalls on it, and the
   forced and Critical-reboot paths skip it entirely in favor of getting the
   machine down fast.
8. **Unmount filesystems.** peinit snapshots the mount table and tries to
   unmount **every** remaining non-root mount in its namespace — not only the
   ones it mounted itself — working from the deepest mount points outward.
   That includes the Phase 1 set (`/proc`, `/sys`, `/dev`, `/dev/pts`,
   `/dev/shm`, `/run`, `/sys/fs/cgroup`) wherever those are still mounted.
   A mount that is already gone counts as done. If one won't unmount because
   it is busy, peinit falls back to remounting it read-only; anything it still
   can't clean up is logged and left for the final `sync()` and the kernel,
   never blocking shutdown. The root filesystem (`/`) is never unmounted —
   once the rest are handled, peinit remounts root read-only.
9. **Sync and finish.** `sync()` to flush pending writes, then the final
   action — power off, reboot, or halt.

The reverse ordering falls straight out of the [dependency
graph](/peios/using-peios/services-and-jobs/dependencies.md); there is no separate stop-order
configuration. Shared platform services stop after their dependents, with
`registryd` last. The exact order is derived from the installed graph.

## STOPPING=1 and timeout extension

A service that begins shutting down on its own — say, in response to an
internal error — can tell peinit by sending `STOPPING=1` through
[sd_notify](/peios/using-peios/services-and-jobs/service-types.md). peinit acknowledges it
and, importantly, **stops sending SIGTERM** to that service: it is already on
its way down, and a redundant signal could interfere.

`STOPPING=1` is a courtesy, **not** a timeout extension. The `StopTimeout`
keeps running; if the process has not exited when it expires, peinit escalates
to SIGKILL regardless. A service that genuinely needs longer must say so with
`EXTEND_TIMEOUT_USEC` (see [Keeping services
running](/peios/using-peios/services-and-jobs/supervision.md)) — and during shutdown those
extensions are capped not only by the per-service `StopTimeout` × 4 but also
by the remaining global `ShutdownTimeout`, whichever is smaller.

## Forced shutdown

> [!WARNING]
> Forced shutdown kills processes without waiting for graceful completion.
> Unfinished application work can be lost. Use it only when the normal
> shutdown cannot finish.

When the machine must be stopped despite a stuck graceful shutdown, **repeated
SIGINT** forces it: three Ctrl-Alt-Del presses within five seconds skip the
graceful sequence entirely — SIGKILL everything, sync, reboot. It is the
escape hatch for a graceful shutdown that is itself stuck behind an
unresponsive service.

## Shutdown during boot

A shutdown requested while peinit is still in Phase 2 boot takes effect
immediately: services still Starting are SIGKILLed (they never reached Active,
so there is nothing to stop gracefully), services that did reach Active are
stopped per the normal sequence, and the boot is abandoned.

## How peinit handles signals

peinit handles **all** signals through a `signalfd` read from its event loop —
every signal is blocked and read as data, so there are no async signal
handlers and no async-safety hazards. PID 1 cannot be killed by any signal;
the kernel protects it.

| Signal | Behavior |
|---|---|
| SIGCHLD | Reap children; match exits to services and submitted jobs. Also reaps orphaned processes the system reparented to PID 1. |
| SIGINT | Reboot request. Repeated within the window → forced reboot. |
| SIGTERM | Poweroff request. |
| SIGPWR | Poweroff request — compatibility path for power-button/power-failure policy. |
| SIGHUP | Ignored — PID 1 has no controlling terminal. |
| SIGPIPE | Ignored — a broken control-socket pipe must never crash PID 1. |

All other signals are ignored.

> [!NOTE]
> Reaping orphans matters: when any process anywhere on the system dies
> leaving children, those children are reparented to PID 1. peinit reaps them
> so they do not accumulate as zombies — even though they were never its
> services. This is part of the job of being PID 1, distinct from supervising
> services.

## Where to start

To understand the reverse ordering and which relationships gate it, read
[Dependencies and ordering](/peios/using-peios/services-and-jobs/dependencies.md).

To understand the Critical-failure path that bypasses graceful shutdown, read
[Keeping services running](/peios/using-peios/services-and-jobs/supervision.md).

For the boot side of the lifecycle and the reboot/recovery escalation, read
[Boot and boot modes](/peios/using-peios/boot/boot-and-boot-modes.md).
