# KMES

---

# Overview

_Peios Kernel / Internals / KMES_

> KMES is the sole event emission path in Peios, used by kernel subsystems and userspace alike, and the terms this chapter uses for it.

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

The Kernel Mediated Event Subsystem (KMES) is the sole event emission path in
Peios. Kernel subsystems and userspace processes alike emit events
exclusively through KMES — there is no alternative path. KMES stamps
each event with trusted metadata at emission time, buffers it in
per-CPU shared memory ring buffers, and delivers it to userspace
consumers that map those buffers directly. It does not persist, index,
or query events, and it imposes no schema or naming convention on them;
those are consumer concerns, handled by eventd.

KMES serves a similar role to ETW in the Windows kernel and auditd in
Linux, but is compatible with neither at the wire, format, or API
level. The design — structured events with a fixed binary header and a
msgpack payload, shared memory delivery, one emission path for kernel
and userspace — was chosen for unified observability with
kernel-trusted metadata.

The consumer-facing contract — the event header layout, the mapped
ring buffer regions, and the protocols a consumer follows to drain,
sleep, and survive buffer swaps — is specified in PSPK's KMES event
stream chapter. This chapter describes the kernel side: how events are
constructed and stamped ([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)), the in-kernel emission API ([Emission API](</kernel/internals/kmes/emission-api.md#trm-2-3>)), the
syscall surface ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)), how the ring buffers are organised and written
([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)), self-configuration through the registry ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)), behaviour
under failure ([Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)), and the emission policy that decides which of
the kernel's own event types are written ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

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

## Terminology

An **event** is an indivisible record: a packed binary **header**
carrying KMES-intrinsic metadata, followed by a msgpack-encoded
**payload** whose structure is defined by the emitter. Header and
payload are produced, stored, and consumed together as one contiguous
byte sequence; neither is meaningful alone. KMES treats the payload as
opaque.

The **stamp** fields are the header fields KMES populates itself at
emission time: the timestamp, sequence number, CPU identifier, and
origin class, plus three identity GUIDs captured from KACS — the
**effective token GUID** (the token governing the emitting thread's
access rights, which is the impersonation token when the thread is
impersonating), the **true token GUID** (the process's primary token,
regardless of impersonation), and the **process GUID** (assigned by
KACS at fork and unchanged across exec). The **null GUID** — sixteen
zero bytes — stamps an identity field whose value is unavailable. <a id="cite-event.null-guid-means-unavailable"></a>

The **sequence number** is a per-CPU, per-boot monotonic 64-bit
counter. Each CPU counts independently; the counter starts at zero
when PKM loads and is incremented before its value is taken, so the
first event on each CPU carries sequence number 1 and sequence 0 is
never assigned. <a id="cite-event.sequence-starts-at-one"></a> A gap in one CPU's sequence indicates lost events. The
pair (`cpu_id`, `sequence`) uniquely identifies an event within a
boot; there is no global sequence. <a id="cite-event.sequence-scoped-per-cpu"></a>

The **origin class** is a header byte identifying the emission path:
userspace (0), KMES itself (1), KACS (2), or LCS (3). Values 4–255 are
unassigned. <a id="cite-event.origin-classes-assigned"></a>

The **event type** is a length-prefixed UTF-8 string in the header
identifying the kind of event. KMES imposes no structure on it and
compares nothing against it; types are consumer vocabulary. <a id="cite-event.type-opaque"></a>

A **ring buffer** is a per-CPU shared memory region — producer
metadata page, consumer metadata page, and a data region — created
and managed by KMES and mapped by consumers. A **consumer** is a
userspace process that maps one or more ring buffers and drains events
from them, typically with one thread per CPU. **Boot-time ring
buffers** are the ordinary per-CPU buffers created at module load
using compiled-in defaults; they are the live consumer-facing buffers
from the first instant, not a separate class. <a id="cite-ring.boot-buffers-ordinary"></a>

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

## Build configuration <a id="cite-build.config-security-pkm"></a>

KMES is built by `CONFIG_SECURITY_PKM`, a boolean option, so it is
linked into `vmlinux` rather than loaded. `CONFIG_RUST=y` is required:
the MessagePack validator is Rust. The subsystem lives in
`security/pkm/kmes`, with tracepoint declarations in
`include/trace/events/kmes.h`.

The three syscall numbers are registered in
`arch/x86/entry/syscalls/syscall_64.tbl` and the corresponding table
under `tools/perf/`. They are registered `common` in the table, but the
kernel is built without `CONFIG_X86_X32_ABI`, so the only entry point
that exists is x86-64: an x32 invocation (the number with bit 30 set)
fails `ENOSYS` like any other x32 syscall on this
kernel. <a id="cite-build.syscalls-registered-common"></a>

`CONFIG_SECURITY_PKM_KUNIT` compiles in the in-kernel test harness.

## Related explanations

- [Self-configuration](</kernel/internals/kmes/self-configuration.md>)
- [ABI semantics and limits](</kernel/userspace/native/kmes/abi-semantics-and-limits.md>)

## Calling the subsystem

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

---

# Event Model

_Peios Kernel / Internals / KMES_

> What an event is on the wire — the packed header, the stamps the kernel applies, ordering, the msgpack payload and the size limits.

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

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

## Structure <a id="cite-event.wire-structure"></a>

An event is a packed binary header followed immediately by its msgpack
payload, written and delivered as a single contiguous byte sequence
with no padding or alignment gaps anywhere. The header is never
represented as a C struct in the kernel; it is serialised field by
field, in order, directly into the ring buffer. The field-by-field
layout — offsets, sizes, and endianness — is part of the consumer
contract and is defined in the PSPK event stream specification. In
summary: all fields before the event type string sit at fixed offsets,
the event type string begins at offset 77 with its `u16` length at
offset 75, the header is exactly `77 + type_len` bytes, the payload
occupies the bytes from `header_size` to `event_size`, and the next
event begins at offset `event_size` from the start of the current one.
All multi-byte header integers are little-endian; the identity GUIDs
are copied as opaque 16-byte values.

`event_size`, `header_size`, and `type_len` are structural fields
computed by KMES during construction. The emitter supplies only the
event type string and the payload, and KMES copies both verbatim. <a id="cite-event.emitter-bytes-verbatim"></a>

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

## Intrinsic stamps <a id="cite-event.stamps-unconditional"></a>

KMES populates four intrinsic stamp fields at emission time,
unconditionally; the emitter cannot supply them.

- **`timestamp`** — wall clock time (`CLOCK_REALTIME`, via
  `ktime_get_real_ns()`) at the moment KMES accepts the event, in
  nanoseconds since the Unix epoch. <a id="cite-event.stamp.timestamp-realtime"></a>
- **`sequence`** — the emitting CPU's per-boot counter, incremented
  and then read, so the first event on each CPU gets 1. <a id="cite-event.stamp.sequence-increment-then-read"></a>
- **`cpu_id`** — the CPU on which the ring buffer write occurs, which
  identifies the per-CPU buffer holding the event. <a id="cite-event.stamp.cpu-id-of-write"></a>
- **`origin_class`** — for syscall emission, set unconditionally to 0
  (userspace); the caller cannot influence it. For kernel emission,
  the value the calling subsystem passed, written to the header
  without validation — kernel emitters are trusted to pass an
  assigned value. <a id="cite-event.stamp.origin-class-trust"></a>

The timestamp is captured before the sequence number is assigned, so
two events with the same timestamp on the same CPU are ordered by
sequence. <a id="cite-event.stamp.timestamp-before-sequence"></a>

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

## Identity stamps <a id="cite-event.identity-at-write-time"></a>

The three identity GUIDs are captured by calling KACS accessors during
the preemption-disabled ring buffer write phase, after the sequence
number is taken and before the header is built. All three accessors
are safe with preemption disabled — each is a handful of pointer
dereferences and a 16-byte copy, with no allocation and no sleeping.
The stamps therefore reflect the thread's identity at the moment of
the ring buffer write, not at syscall entry.

- `kacs_effective_token_guid()` reads the thread's *subjective*
  credentials (`current_cred()`), so during impersonation — which
  installs the impersonation token via `override_creds()` — it yields
  the impersonation token's GUID. Otherwise it equals the true token
  GUID. <a id="cite-event.identity.effective-follows-impersonation"></a>
- `kacs_primary_token_guid()` reads the *real* credentials
  (`current_real_cred()`), which impersonation leaves untouched, so it
  always yields the process's primary token GUID. <a id="cite-event.identity.true-ignores-impersonation"></a>
- `kacs_process_guid()` reads the process GUID KACS assigned when the
  process's security state was created at fork. Threads created with
  `CLONE_THREAD` share the process state, and no exec path writes the
  field, so the GUID is stable for the process's lifetime. <a id="cite-event.identity.process-guid-stable"></a>

All three accessors return the null GUID when there is no task context
(`!current` or not `in_task()`), and the token accessors also return it
when the token cannot be resolved. A fully null identity triple
therefore indicates emission before KACS initialisation, from a kernel
thread, or from interrupt or softirq context. No event is ever stamped
with the identity of a task that merely happened to be interrupted. <a id="cite-event.identity.null-without-task-context"></a>

For batch emission, the timestamp and the three identity GUIDs are
captured once, before the per-event loop, and shared by every event in
the batch: the batch executes with preemption disabled on one CPU, so
the emitting thread's identity cannot change mid-batch. Each event
still receives its own sequence number. <a id="cite-event.identity.batch-captured-once"></a>

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

## Ordering <a id="cite-event.ordering-contract"></a>

Within one CPU, `sequence` is the reliable ordering primitive, monotonic
even across wall-clock discontinuities. Keep the CPU and boot context with
it. A consumer can sort records from different CPUs by `timestamp`, but
wall-clock timestamps do not establish a total causal order. Equal timestamps
do not prove that operations were simultaneous or independent.

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

## Catalog field names

Consumers expose header information through the catalog's field names:

| Catalog field | Header member |
|---|---|
| `event.type` | `type`, supplied by the emitter |
| `event.time` | `timestamp` |
| `event.sequence` | `sequence` |
| `event.cpu` | `cpu_id` |
| `emitter.class` | `origin_class` |
| `emitter.token.guid` | `effective_token_guid` |
| `emitter.true-token.guid` | `true_token_guid` |
| `emitter.process.guid` | `process_guid` |

`event.boot.guid` is consumer-supplied boot context, not a header member.
The structural sizes are framing information, not catalog payload fields.
The platform definitions live in `peios/packages/data/evman/kernel.evman`.
A conforming payload does not repeat header information.

The origin class describes the emission path, not the event type's prefix.
Userspace emits with class 0. StrataFS records emitted through KACS carry the
KACS class. Null identity stamps do not establish an actor; interpret them
using the identity-stamp rules in this article.

## Payload

The payload is a single msgpack value. KMES neither interprets nor
modifies it — buffering and delivery are content-blind — and it
performs no payload validation at all for kernel emitters, which are
trusted callers inside PKM. <a id="cite-event.payload.kernel-not-validated"></a>

Payloads arriving through the syscall interface are validated before
acceptance by an iterative (non-recursive) msgpack walker implemented
in Rust, operating on the kernel's staged copy of the payload:

- The payload is exactly one well-formed top-level msgpack value.
  Trailing bytes after it are rejected, as is the never-used `0xc1`
  type byte. <a id="cite-event.payload.exactly-one-value"></a> A zero-length payload is rejected — an empty byte
  sequence is not a msgpack value — so syscall events always carry a
  payload. <a id="cite-event.payload.empty-rejected"></a> (Kernel emitters can emit header-only events with
  `event_size == header_size`.)
- Nesting depth is bounded by the configured `MaxNestingDepth`
  ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). Depth counts from 1 at the top-level value; each child of an
  array or map sits one deeper than its container. A non-empty
  container at the maximum depth is invalid, because its children
  would exceed the limit; an empty array or map at the maximum depth
  is valid, consuming no depth. Map keys and values each occupy a
  child slot, so a map contributes twice its entry count of children. <a id="cite-event.payload.depth-model"></a>
- The walker's own stack is 256 frames, matching the upper bound of
  the `MaxNestingDepth` range; a configured depth outside 1–256 causes
  every payload to be rejected rather than any to be waved through. <a id="cite-event.payload.bad-depth-config-rejects-all"></a>
- Length prefixes inside msgpack are big-endian, per the MessagePack
  specification — the one big-endian ingredient in an otherwise
  little-endian event.

A rejected payload fails the syscall with `EINVAL` and nothing is
written to the ring buffer. <a id="cite-event.payload.reject-writes-nothing"></a>

The event type string is validated as UTF-8 on the syscall path by the
same staged-copy pass; kernel emitters' type strings are trusted and
copied as given. Types are compared by consumers as raw bytes — no
case folding or normalisation is applied anywhere. <a id="cite-event.type-utf8-on-syscall-path"></a>

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

## Size limits <a id="cite-event.size-limits"></a>

Three structural bounds apply to every event, and one configurable
policy bound applies to syscall emitters only:

- The event type length fits the header's `u16` `type_len` field and
  is nonzero. Syscall emitters cannot express an overlong type — the
  ABI length field is already `u16` — but the kernel emission API
  takes a `size_t` and enforces the bound itself. <a id="cite-event.limits.type-len-u16-nonzero"></a>
- The total event size (header + payload) fits a `u32`, checked with
  overflow-safe arithmetic on the declared lengths. <a id="cite-event.limits.total-fits-u32"></a>
- The total event size does not exceed 50% of the per-CPU ring buffer
  capacity — a fixed ratio, not configurable, protecting a CPU's
  event history from a single giant event. An event of exactly half
  the capacity is accepted. Capacity is always a power of two, so the
  halving is exact. <a id="cite-event.limits.half-capacity"></a>
- Syscall events are additionally bounded by the registry-configurable
  `MaxEventSize` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)), rejected with `ENOSPC` when exceeded. Kernel
  emitters are exempt from this policy limit. <a id="cite-event.limits.max-event-size-syscall-only"></a>

---

# Emission API

_Peios Kernel / Internals / KMES_

> The in-kernel emission interface — single and batch emission, the structural checks that drop an event, and what happens when a ring is full.

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

The emission API is the internal kernel interface through which PKM
subsystems emit events — an ordinary function call inside the module,
not a syscall. Userspace emission goes through the syscall interface
([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)). There are two entry points: single emission
(`pkm_kmes_emit_kernel`) and batch emission
(`pkm_kmes_emit_kernel_batch`). Both return nothing: kernel emission
is fire-and-forget, and the emitting subsystem is never notified of a
drop. <a id="cite-kernel-emit.fire-and-forget"></a>

Neither entry point consults the emission policy. Whether a type is
switched on is decided by the emitter before it builds the event, with
the check described in [Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>); an event that reaches the emission API is
written.

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

## Single emission

A kernel emitter passes an origin class, an event type (pointer and
length), and a payload (pointer and length). It does not choose a CPU
or buffer: KMES writes the event to the ring buffer of the CPU the
calling code is executing on. <a id="cite-kernel-emit.executing-cpu"></a>

The entire emission path runs with preemption and bottom halves
disabled — from before the current CPU is determined until after the
ring buffer write — which guarantees the emitting thread cannot
migrate mid-write and preserves the single-writer-per-buffer
invariant. For kernel emitters this covers the full path, timestamp
capture through ring write; the payloads are small and trusted, and
the window is a few hundred nanoseconds.

Bottom halves matter because rings are written from softirq context as
well as from tasks: the packet engine reports from the network receive
path, and RCU callbacks run in softirq. With only preemption disabled,
a softirq taken on interrupt exit could write the same CPU's ring
between a task writer's sequence increment and its `write_pos`
publication, interleaving two events in one reservation. Every ring
writer — single, kernel batch and the emit syscalls — therefore holds
bottom halves off across its reservation and write. A writer that runs
with interrupts already disabled needs no more: neither a softirq nor
a hard interrupt can reach its CPU. <a id="cite-kernel-emit.bottom-halves-held"></a>

Emission from hard interrupt or NMI context is refused. Bottom halves
cannot be held off there, and such a writer could interrupt one
holding the ring, so the event is dropped before any ring is touched:
no sequence number is consumed, no ring drop is counted, and KMES
tallies it in a private counter and logs the first such drop once. No
kernel emitter runs in hard interrupt context. <a id="cite-kernel-emit.hardirq-refused"></a>

The consumer wake that follows a write takes the futex hash bucket
lock, which the futex core takes with bottom halves enabled; a softirq
taking it while a task on the same CPU held it would spin forever. A
writer outside task context therefore does not wake consumers itself:
the write still advances the futex counter, and the wake is handed to
a work item on the ring, which holds a reference to the ring until it
has run in process context. <a id="cite-kernel-emit.softirq-wake-deferred"></a>

Construction proceeds in order: capture the wall clock timestamp;
increment the CPU's sequence counter and take the new value; capture
the three identity GUIDs from KACS; build the packed header; write
header and payload contiguously into the ring. The ordering
consequences of these steps are described in [Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>).

KMES trusts kernel emitters. It does not validate the origin class,
the type string's encoding, or the payload — only the structural
checks below run. A null event-type pointer is not checked on the
single-emission path; passing one faults. <a id="cite-kernel-emit.trusted-unvalidated"></a>

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

## Structural checks and drops <a id="cite-kernel-emit.structural-checks"></a>

Every kernel emission is checked for: nonzero event type length; type
length within `u16`; total event size within `u32` (overflow-checked);
and total event size within 50% of the per-CPU ring capacity.

A failing event is not written — but its sequence number has already
been consumed, so the drop is visible to consumers as a gap in that
CPU's sequence, and an internal per-CPU dropped-event counter is
incremented. <a id="cite-kernel-emit.drop-consumes-sequence"></a> That counter also aggregates events discarded by
overwrite when the buffer wraps; it is not exposed in the ring buffer
metadata and is readable only by the KUnit test harness. <a id="cite-kernel-emit.drop-counter-internal"></a>

Two further situations discard kernel events entirely outside this
accounting:

- Before KMES initialisation completes, emission is a silent no-op: no
  sequence number is consumed, the drop counter is not incremented,
  and no gap is visible. Events emitted in this window are simply
  gone. KMES tallies them in a private counter and logs the total once
  when the rings come up. <a id="cite-kernel-emit.pre-init-silent"></a>
- If the ring's recorded CPU identity does not match the executing
  CPU, the ring selection itself is untrustworthy, so every emission
  path — single, kernel batch and syscall — returns early without
  consuming a sequence number or counting a drop. <a id="cite-kernel-emit.cpu-mismatch-discard"></a>

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

## Ring buffer full <a id="cite-kernel-emit.never-blocks"></a>

Each per-CPU buffer is circular. When it is full, KMES overwrites the
oldest events to make room; the write position advances
unconditionally, and emission never blocks and never fails from buffer
pressure. Consumers detect the overwritten events as sequence gaps,
and a consumer whose read position has been overtaken re-anchors to
the oldest surviving event, as specified in the PSPK event stream
chapter. The overwrite mechanics are described with the write protocol
in [Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>).

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

## Batch emission

The batch API emits multiple events in one operation: an origin class
applied to the whole batch, an array of event descriptors (type
pointer and length, payload pointer and length each), and a count.
There is no upper bound on the kernel batch count — unlike the syscall
batch, which caps at 256 entries — so the non-preemptible window is
bounded only by the caller's restraint.

The batch executes as one section with preemption and bottom halves
disabled:

1. One wall clock timestamp is captured; every event in the batch
   shares it.
2. The three identity GUIDs are captured once and shared.
3. Each event, in order: structural checks, sequence assignment,
   header build, ring write. The batch structural check is slightly
   stronger than the single-emission one — it also rejects a null
   type pointer, a null payload pointer with a nonzero length, and a
   header size beyond `u32`. <a id="cite-kernel-emit.batch-stronger-checks"></a> A failing event is dropped exactly as in
   single emission (sequence consumed, gap visible, counter
   incremented) and the batch continues with the next event — kernel
   emitters are trusted, and an individual structural failure
   indicates a kernel bug rather than hostile input. <a id="cite-kernel-emit.batch-continues-past-failure"></a> This differs
   deliberately from the syscall batch, which stops at the first
   failure so the untrusted caller learns which entry was bad.
4. After the loop, provided at least one event was actually written,
   the new tail position and then the new write position are published
   with release stores — one publication for the whole batch — and
   the consumer wake flag is checked once, incrementing the futex
   counter if a consumer is asleep. A batch in which every event
   failed publishes nothing and performs no wake check. <a id="cite-kernel-emit.batch-publishes-once"></a>
5. Preemption and bottom halves are re-enabled, and only then is the
   futex wake performed, outside the window — or, outside task
   context, handed to the ring's work item.

Deferring publication gives batch atomicity: consumers observe either
none of the batch or all of it, since the data is fully written before
the single `write_pos` release store. <a id="cite-kernel-emit.batch-atomic-visibility"></a> During the batch, the overwrite
check runs against an internal running write offset — the consumer-
visible `write_pos` stays untouched until the end. The tail position
is likewise kept local and published only at the end.

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

## Write atomicity <a id="cite-event.write-atomicity"></a>

Individual event writes are atomic from the consumer's perspective: an
event's bytes are fully written into the data region before the
`write_pos` release store makes them reachable, so a consumer bounded
by `write_pos` can never observe a partially written event. The
memory-ordering contract this rests on is part of the PSPK event
stream specification; the kernel-side implementation of the write
protocol is described in [Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>).

---

# Ring Buffers

_Peios Kernel / Internals / KMES_

> One ring per logical CPU — how they are organised, the two producer metadata pages, wrap handling, the write protocol and notification.

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

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

## Organisation

KMES maintains one ring buffer per logical CPU, created for every CPU
in the kernel's possible-CPU set when the module initialises — before
LCS exists, using the compiled-in default capacity — and buffering
events from that first instant. These boot-time buffers are ordinary
buffers: same layout, same overwrite semantics, same generation
model, immediately attachable. If LCS never becomes available they
simply remain the live buffers indefinitely. <a id="cite-ring.created-at-init-for-possible-cpus"></a>

Each ring is an independent, reference-counted object holding its
capacity, generation, sequence counter, write and tail positions,
futex counter, dropped-event counter, two metadata pages, and the data
region. There is no shared state between rings on the write path: each
CPU writes only to its own ring, using plain non-atomic fields under
preemption disablement, and the only ordering machinery is a set of
release stores at publication points. Fds taken by consumers hold
references, so a ring — including a superseded generation — survives
until the last consumer releases it. <a id="cite-ring.independent-refcounted"></a>

The data region is a `vzalloc` allocation of exactly `capacity` bytes,
zeroed once at creation and never scrubbed afterwards; overwritten
regions retain stale bytes, which is why the consumer contract forbids
reading beyond an event's `event_size`. <a id="cite-ring.data-zeroed-once-not-scrubbed"></a> Capacity is always a power of
two — enforced at every entry point — so position wrap is a bitwise
AND with `capacity - 1`. The permitted range is 64 KB to 256 MB, with
a 4 MB default. <a id="cite-ring.capacity-range"></a>

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

## The two producer metadata pages <a id="cite-ring.mirrored-metadata-stores"></a>

Producer metadata exists twice. The kernel writes its working copy to
a private page allocated with the ring, and mirrors every store to a
second, consumer-visible page. The consumer-visible page is
shmem-backed and allocated lazily at the first `kmes_attach` for the
ring; shmem backing is what makes the notification futex work, since
a shared (inode-keyed) futex needs a page-backed mapping. <a id="cite-ring.shared-page-lazy-shmem"></a> Every
producer store — `write_pos`, `tail_pos`, `futex_counter`,
`generation` — is a release store performed to both pages; the static
fields are initialised at ring creation and re-stamped when the shared
page appears. The mmap handler exposes only the shared page. The field
offsets on the page are part of the consumer contract, defined in the
PSPK event stream chapter.

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

## Consumer mapping permissions <a id="cite-consumer.mapping-permissions"></a>

The producer metadata page and both aliases of the data region are read-only
to consumers. The consumer metadata page is read-write: ordinary stores and
authorised `process_vm_writev` writes can set `need_wake`. A consumer can remove
write permission from that page with `mprotect` and restore it later.

A write-enabling `mprotect` covering any producer or data byte fails with
`EACCES`, including requests spanning the consumer page and a protected region.
Write faults and writable page pins must not upgrade the protected pages.
These boundaries follow the original mapping offsets when `mprotect` splits a
VMA; a new VMA start does not move the consumer page. Process access gates for
remote writes still apply.

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

## Wrap handling <a id="cite-ring.consumer-sees-contiguous-wrap"></a>

The consumer's data region is double virtual mapped — the same
physical pages appear twice consecutively — so a consumer reads an
event that crosses the physical end of the buffer as one contiguous
byte sequence. The producer side has no such mapping: kernel writes
into the `vzalloc` region are wrap-aware, splitting a byte-range copy
that crosses the boundary into two `memcpy` calls and masking scalar
stores per byte. The contiguity guarantee is a property of the
consumer's view, produced by the mmap layout rather than by the
writer.

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

## Write protocol

Each ring has exactly one writer — its CPU — and the write path takes
no locks and performs no cross-CPU atomics. For a single kernel
emission: capture the timestamp; take the next sequence number; if
the event fails a structural check, count the drop and stop ([Emission API](</kernel/internals/kmes/emission-api.md#trm-2-3>));
otherwise make room, write the event at `write_pos & (capacity - 1)`,
publish the new `write_pos` (old value plus event size) with a
release store, and check `need_wake`. The release store is what makes
the event atomic from the consumer's side: the bytes are complete
before the position that makes them reachable moves.

Making room is the overwrite walk. While the live span
(`write_pos - tail_pos`) plus the incoming event exceeds capacity,
KMES reads the `event_size` of the event at the tail and advances
`tail_pos` past it, counting each overwritten event in the internal
dropped-event counter, and publishes the advanced tail with a release
store before the new data lands on top of it. <a id="cite-ring.overwrite-advances-tail-first"></a> Walking the tail is
sequential and possibly cache-cold — the tail can be megabytes from
the write position — a cost accepted in preference to maintaining an
index of event offsets on the hot write path.

The walk carries a corruption guard: if the size field read at the
tail is zero, larger than the capacity, or larger than the live span,
KMES abandons the walk and resynchronises by jumping `tail_pos`
straight to `write_pos`, discarding the entire surviving window in
one step (the discarded span is not itemised in the drop counter) and
emitting a tracepoint. <a id="cite-ring.tail-resync-guard"></a>

For a batch, KMES first walks the reservations for every accepted event
using local write and tail positions. It publishes the resulting tail
with one release store **before writing any event bytes**, so a
concurrent consumer can detect that the record it was reading has been
overwritten. Publishing the tail only after the writes would allow the
consumer's tail re-check to accept torn data.

After writing the events, KMES publishes the final write position with
one release store and checks `need_wake` once, provided at least one
event was written. New batch records become available at that final
write-position store; the tail still transitions once per batch rather
than once per overwritten event. <a id="cite-ring.batch-one-tail-transition"></a>

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

## Notification <a id="cite-ring.need-wake-protocol"></a>

The wake path reads the consumer page's `need_wake` byte — the single
consumer-writable byte KMES ever reads, treated as a boolean and
trusted for nothing else. If it is zero, notification costs that one
read. If set, KMES increments the futex counter with a release store
and wakes every thread waiting on it. The futex is a shared,
inode-keyed futex on the shmem producer page at the counter's offset —
a consequence a consumer must match: a `FUTEX_PRIVATE_FLAG` wait on
the mapped address is never woken. <a id="cite-ring.futex-is-shared-inode-keyed"></a> Before any consumer has attached,
the shared page does not exist and the wake is skipped entirely,
though the private counter still advances. <a id="cite-ring.wake-skipped-before-attach"></a>

The `futex_wake` call itself is issued after preemption is re-enabled,
outside the write window; only the counter increment happens inside
it. Waking a thread that is already awake is a harmless no-op, which
is also why the consumer's relaxed clearing of `need_wake` is safe.

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

## Capacity swaps <a id="cite-ring.swap-under-stop-machine"></a>

A valid `BufferCapacity` configuration change replaces every ring.
New rings are allocated first, at the old generation plus one, fully
initialised before any CPU can see them. The switch itself runs under
`stop_machine`: with every CPU quiesced, each ring's surviving events
are migrated to its replacement, the per-CPU live pointers are
switched, and each old ring's published generation is bumped to the
new value — signalling consumers on the old mapping to re-attach. <a id="cite-ring.swap.generation-bump-signals-reattach"></a> If
an old ring's `need_wake` is set, its futex counter is bumped inside
the quiesced section and the wake is issued after it, so consumers
asleep on a dead generation do not sleep forever. <a id="cite-ring.swap.wakes-stale-sleepers"></a>

The outgoing live references remain held until `stop_machine` returns.
They are released after the pending wakes, in a context where cleanup
can sleep. The quiesced callback never performs the final release of
an old ring, which can unmap and free its pages.

Migration copies the surviving span in sequence order, re-compacted
contiguously from position zero: the new ring starts with
`tail_pos = 0` and `write_pos` equal to the bytes copied, and the
sequence and dropped-event counters carry over, so sequence numbers
are continuous across a swap. <a id="cite-ring.swap.migration-recompacts"></a> When the new capacity is smaller than
the surviving span, the oldest events are skipped from the tail
forward until the suffix fits — loss is bounded to the oldest prefix,
traced but not counted as drops. <a id="cite-ring.swap.shrink-skips-oldest"></a> Old positions are meaningless in the
new ring; a consumer re-locates by sequence number, per the PSPK
protocol.

If allocating the new rings fails, the old rings stay live at their
size, no generation changes, and the failure is reported through a
`kmes.buffer.swap.failed` event ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). <a id="cite-ring.swap.alloc-failure-keeps-old"></a> A migration abort — a corrupt
size field encountered inside the quiesced section — abandons the
swap the same way and is reported the same way, with `-EIO` as the
error. <a id="cite-ring.swap.abort-emits-event"></a> There is no automatic retry;
the next configuration write or reboot tries again. A superseded
generation's pages stay valid for as long as any consumer keeps them
mapped, so during and after a swap old and new rings coexist until
the last old fd closes. <a id="cite-ring.swap.generations-coexist"></a>

---

# Self-configuration

_Peios Kernel / Internals / KMES_

> The four parameters KMES reads from the registry, how it bootstraps before LCS exists, and the watch that keeps them current.

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

KMES reads four operational parameters from the registry under
`Machine\System\KMES\`. Compiled-in defaults carry it from module load
until LCS becomes available; from then on a persistent kernel-internal
watch keeps it current. The key names, types, defaults, and ranges are
in [KMES ABI Reference](</kernel/userspace/native/kmes/generated-abi-tables.md#trm-2-a>).

At no point does KMES wait for configuration. The defaults are always
sufficient, and if LCS never appears KMES runs on them indefinitely. <a id="cite-config.defaults-carry-until-lcs"></a>

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

## Reading and validating

Value names are matched with LCS's value-name comparison rules —
Unicode Simple Case Folding, case-preserving and case-insensitive.
Names in the subtree that do not fold to one of the four canonical
names are unknown keys: they are counted and ignored. <a id="cite-config.names-case-folded-unknown-ignored"></a>

A `REG_DWORD` value carries exactly four little-endian payload bytes
and a `REG_QWORD` exactly eight. A value whose type tag is right but
whose payload length is wrong is not a malformed number — it is
classified as a wrong-type value, and reported as such. <a id="cite-config.wrong-length-is-wrong-type"></a>

Values are never clamped or silently corrected. A value outside its
range, of the wrong type, of the wrong payload length, absent, or (for
`BufferCapacity`) not a power of two is rejected outright and the
previously active value is retained — the compiled-in default, or the
last accepted value. The registry write itself succeeds, because the
source does not enforce kernel semantics; the registry therefore shows
what was written while the event log shows what KMES is actually
using. <a id="cite-config.invalid-rejected-not-clamped"></a> Validation happens twice: once when the change plan is built,
and again in C before the plan is applied, so an out-of-range field
reaching the second gate fails the whole application with `EINVAL`. <a id="cite-config.validated-twice"></a>

The capacity swap runs first, and a `BufferCapacity` change that
cannot be applied rolls back the capacity and nothing else:
`MaxEventSize`, `MaxNestingDepth`, and `MaxEmitRatePerProcess` still
commit in the same pass, against the capacity that is actually live,
so the stored configuration describes the running system rather than
the requested one. The situation that makes a swap fail — memory
pressure — is exactly the one in which an administrator raising
`MaxEventSize` and `BufferCapacity` together needs the `MaxEventSize`
change to survive. <a id="cite-config.swap-failure-rolls-back-capacity-only"></a> A
`MaxEmitRatePerProcess` change additionally reconfigures every live
rate bucket, clamping any bucket holding more tokens than the new
capacity ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)).

A valid `BufferCapacity` different from the current one triggers a
ring buffer swap ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)). <a id="cite-config.capacity-change-swaps"></a>

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

## Self-configuration events <a id="cite-config.self-events-origin-kmes"></a>

KMES reports its own configuration handling through KMES, with origin
class 1. These events are best-effort diagnostics: emission runs
before the configuration is applied and its result is discarded, so a
failed emission neither rolls back a valid application nor activates
an invalid value. Each event's payload is built by a small in-kernel
msgpack writer into a 768-byte buffer; a payload that would exceed it
is silently skipped. <a id="cite-config.self-events-best-effort"></a>

`kmes.config.value.rejected` reports one missing or invalid value. Its
payload follows the event-field rules of PGSS [Overview](</kernel/internals/ntfe/overview.md#trm-6-1>): each dotted field
path is a nested msgpack map, one per segment, and a field that does
not apply is absent rather than nil. Every field lives under a single
top-level `config` map of five keys, in order:

- `config.key.path` — always `Machine\System\KMES`.
- `config.name` — the canonical value name.
- `config.expected.type`, `config.expected.min` and
  `config.expected.max` — the registry type code and range from the
  key's definition.
- `config.received.kind` — one of `missing`, `wrong-type` or
  `out-of-range`. A malformed payload length reports `wrong-type`. A
  `REG_DWORD` and a `REG_QWORD` value out of range both report
  `out-of-range`, since `config.expected.type` already gives the
  width. `config.received.type` (the actual registry type code) is
  present exactly when the kind is `wrong-type`, and
  `config.received.value` (the number received) exactly when it is
  `out-of-range`. A missing value carries the kind alone.
- `config.value` — the value KMES continues to use, read before any
  part of the plan was applied. <a id="cite-config.invalid-event-nine-keys"></a>

One read reports at most four of these events, which is exactly the
number of configuration keys. A plan that would need more is rejected
before anything is applied, and the entire configuration read is
abandoned. <a id="cite-config.at-most-four-reports"></a>

On a first boot where the KMES key exists but is empty, all four keys
are missing, so the read emits four `kmes.config.value.rejected`
events and retains all four defaults. <a id="cite-config.empty-key-emits-four"></a>

`kmes.buffer.swap.failed` reports a valid `BufferCapacity` change that
could not be applied. Its payload is two maps: `buffer`, holding
`buffer.capacity-requested` (the capacity asked for) and
`buffer.capacity` (the capacity kept), and `outcome`, holding
`outcome.errno` as a negative signed integer — `-ENOMEM` when the
replacement rings could not be allocated, which is the usual case.
The swap is system-wide, so no CPU or ring is named. <a id="cite-config.swap-failed-event"></a>
Every failure is reported, not only allocation: a swap abandoned
because migration met a corrupt size field reports `-EIO`, and one the
kernel could not quiesce the CPUs for reports what `stop_machine`
returned. <a id="cite-config.swap-failed-every-errno"></a>

`kmes.config.applied` records a read of `Machine\System\KMES` that
reached the commit, after the rejection reports and the commit
itself. Its payload is three maps: `config`, holding `config.key.path`
and `config.counts` with the four counts `applied`, `retained-missing`,
`retained-invalid` and `ignored-unknown`; `buffer`, holding
`buffer.capacity`; and `emission`, holding `emission.rate-limit`. The
capacity and rate are read back after the commit, so they are what is
in force rather than what the plan asked for. <a id="cite-config.applied-event"></a>
A read whose capacity swap failed still reaches the commit — the other
three settings commit without it — so it is recorded as applied too,
with the capacity kept, beside the `kmes.buffer.swap.failed` that says
why. <a id="cite-config.applied-after-failed-swap"></a> `MaxEventSize` and
`MaxNestingDepth` in force are not in the record: the catalogue has no
field for either yet.

`kmes.config.refresh.failed` records a re-read, after the watch saw a
change, that failed: the source did not answer, answered with
something malformed, or the plan was refused (more than four rejection
reports, or a configuration the second gate rejects). Its payload is
`config`, holding `config.key.path`, and `outcome`, holding
`outcome.errno`. The configuration in force stays as it was. The
record is `essential`: the registry and the running kernel disagree
until the next change, and it is the only sign. A failed capacity swap
is not a failed read and does not produce one. <a id="cite-config.refresh-failed-event"></a>
A read that fails during the bootstrap refresh is not recorded this
way: it fails that refresh, which is traced and leaves the machine-root
fallback armed to try again (LCS [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)). The emission policy reports
a failed walk of `Machine\Generic\Events` with the same record ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

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

## Bootstrap and watching <a id="cite-config.bootstrap-sequence"></a>

1. PKM loads. KMES initialises with compiled-in defaults and creates
   per-CPU rings at the default capacity. They are live immediately.
2. The first Machine-hive source registers, making LCS usable. KMES
   enumerates every value under `Machine\System\KMES\`.
3. Valid values are applied. A `BufferCapacity` differing from the
   current one drives a swap; a matching or absent one changes
   nothing.
4. KMES arms a persistent watch on the key through LCS's internal
   watch mechanism — a kernel-internal registration, not a
   userspace fd-based watch. Delivery is filtered to value-set and
   value-deleted notifications on the key itself, so changes in keys
   below `Machine\System\KMES` do not trigger a re-read. <a id="cite-config.watch-filtered-to-key"></a>
5. If the key does not exist yet, the fallback watch is armed on the
   Machine hive root and fires on subkey creation at any depth. When
   it fires, KMES re-runs the whole bootstrap: discover the key, read
   it, and re-arm the targeted watch. Deleting the key afterwards
   does not re-arm the fallback. <a id="cite-config.fallback-watch-on-hive-root"></a>
6. On subsequent changes — administrator edit, or a Group Policy push
   at a higher-precedence layer — the watch fires and KMES re-reads,
   validates, and applies or rejects.

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

## Access to the configuration

The configuration keys inherit the Machine hive root security
descriptor, which grants `KEY_ALL_ACCESS` to SYSTEM and
Administrators and `KEY_READ` to Authenticated Users, so unprivileged processes cannot
change KMES's operational parameters. Enforcement is LCS's, not
KMES's — KMES reads values that LCS has already decided the caller
was entitled to write. Domain policy at a higher-precedence layer
provides defence against a compromised local administrator, since
creating a layer above precedence 0 requires SeTcbPrivilege.

The boot-time capacity is the compiled-in default and is not
separately configurable: making it so would need a channel to deliver
a value to the kernel before the registry exists. Once LCS is
available, capacity changes go through the ordinary swap. <a id="cite-config.boot-capacity-compiled-in"></a>

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

## Configuration keys

Registry path `Machine\System\KMES\`. The type codes, defaults and
ranges are in [KMES ABI Reference](</kernel/userspace/native/kmes/generated-abi-tables.md#trm-2-a>); what each key does is here.

| Key | Effect |
|---|---|
| `BufferCapacity` | Per-CPU ring size in bytes. Must be a power of two. Changing it swaps every ring; see [Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>). |
| `MaxEventSize` | Largest event a syscall emitter may produce. |
| `MaxNestingDepth` | Deepest MessagePack container nesting the validator will accept. |
| `MaxEmitRatePerProcess` | Token-bucket rate, events per second, per process. |

`MaxEventSize`, `MaxNestingDepth` and `MaxEmitRatePerProcess` apply only
to syscall emitters. A kernel emitter is not rate-limited and its payload
is not parsed as MessagePack, but it is still checked structurally —
non-empty type string within `PKM_KMES_MAX_KERNEL_TYPE_LEN`, a payload
pointer if the length is non-zero, no size arithmetic overflow, and the
50% bound. A kernel event that fails is dropped with
`KMES_DROP_VALIDATE`, not emitted.

A key that is missing, of the wrong type, or out of range does not fail
the read: the previous value is retained and the disagreement is
recorded as an audit intent. At most four such intents are carried out
of one read, so a configuration with five bad keys reports four.

---

# Failure Modes

_Peios Kernel / Internals / KMES_

> Ring overrun, event drops, consumer crashes, buffer swap failure, LCS unavailability and clock discontinuity — what each does.

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

KMES has no external trust boundary on the write path: kernel emitters
are trusted, and userspace emitters are validated at the syscall
boundary ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)). Its failure semantics are correspondingly simpler
than a subsystem like LCS that spans the kernel-userspace boundary in
both directions.

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

## Ring overrun <a id="cite-failure.overrun-is-normal"></a>

When events are emitted faster than consumers drain them, the buffer
fills and KMES overwrites the oldest events. The write path is never
blocked and emission never fails from buffer pressure. Consumers see
the loss as gaps in the per-CPU sequence, and a consumer whose read
position has been overtaken re-anchors to the oldest surviving event.

Overrun is a normal operating condition under load, not an error: the
system degrades by keeping recent events, losing old ones, and telling
consumers that it did.

Two bulk-loss cases sit outside that model. The tail resynchronisation
guard ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)) can discard an entire surviving window at once when a
size field reads back implausibly, and a shrinking capacity swap drops
the oldest events that do not fit the new ring. Neither itemises the
discarded events in the drop counter, though both are traced. <a id="cite-failure.bulk-loss-outside-drop-counter"></a>

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

## Event drop

An event is dropped without reaching the buffer when a structural
limit is exceeded — an event type length that cannot be encoded in the
header's `u16` field, or an event larger than half the ring capacity —
and, for syscall emitters only, when the event exceeds `MaxEventSize`
or the payload fails msgpack validation.

The two paths differ in what a consumer sees. For kernel emitters the
sequence number is consumed before the structural checks run, so the
drop appears as a sequence gap; the emitting subsystem is not
notified, since emission is fire-and-forget. For syscall emitters
validation completes before the write phase, so no sequence number is
consumed and no gap appears — the drop is visible only to the caller,
as the syscall's error return. <a id="cite-failure.drop-visibility-differs"></a>

Events emitted before KMES initialisation completes are discarded with
no sequence consumed and no counter incremented, and are therefore
invisible to consumers in both ways.

The internal per-CPU dropped-event counter aggregates structural drops
and overwrite losses together. It is not exposed in the ring metadata
and is reachable only through the KUnit test interface.

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

## Consumer crash <a id="cite-failure.consumer-crash-contained"></a>

A crashed consumer's mappings are cleaned up by the ordinary kernel
path when its file descriptors close on process exit, and the rings
themselves are reference-counted, so they survive until the last
reference goes. KMES is unaffected and keeps writing regardless of
whether any consumer is attached — a system with no consumers behaves
identically to one with consumers, events simply being stamped,
buffered, and eventually overwritten. A restarted consumer re-attaches
and sees every surviving event, with the outage visible as a sequence
gap.

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

## Buffer swap failure

If replacement rings cannot be allocated, or the migration meets a
corrupt ring, the existing rings stay live at their current size, the
capacity change is not applied, no generation changes, and consumers
are unaffected. A `kmes.buffer.swap.failed` event records the
requested and retained capacities as `buffer.capacity-requested` and
`buffer.capacity`, and the error as `outcome.errno` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). KMES does
not retry; the next configuration write or a reboot triggers another
attempt.

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

## Configuration that cannot be read

A re-read of `Machine\System\KMES` that fails keeps the configuration
in force, and a walk of the emission policy that fails keeps the mask
in force; each is recorded as `kmes.config.refresh.failed` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>),
[Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)). Nothing retries on its own: the next change under the key reads
it again.

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

## LCS unavailable <a id="cite-failure.lcs-never-required"></a>

If no source ever registers, KMES runs indefinitely on compiled-in
defaults with the boot-time rings live and the configuration watch
never armed. This is a valid operating mode, not a failure — the only
consequence is that the parameters cannot be tuned.

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

## Clock discontinuity <a id="cite-failure.clock-jump-reorders-timestamps-only"></a>

Timestamps come from `CLOCK_REALTIME`, so an NTP adjustment can move
them forward or backward and consumers sorting by timestamp will see
an apparent reordering. Sequence numbers are unaffected: they are
independent monotonic counters, never derived from the clock, and
remain the reliable ordering primitive within a CPU. KMES neither
detects nor compensates for discontinuities. Cross-CPU ordering near a
jump is best-effort — an inherent cost of wall-clock timestamps,
accepted for their readability and cross-boot comparability. Rate
limiting is immune, being driven by the monotonic clock.

System suspend and hibernate are special cases of the same thing. Ring
contents survive suspend to RAM, and are restored from the hibernate
image on resume; in both cases the clock jumps forward by the sleep
duration, so consumers see a wall-clock gap with no sequence gap. <a id="cite-failure.suspend-no-sequence-gap"></a>

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

## CPU topology <a id="cite-failure.topology-fixed-at-init"></a>

The set of rings is fixed at initialisation from the kernel's
possible-CPU set, and topology changes are not handled dynamically.

A CPU that was possible but offline at initialisation already has a
ring: if it comes online later, its events go to that ring, and
consumers can attach to it throughout. A CPU whose logical index was
outside the possible-CPU set has no ring, and `kmes_attach` rejects
that index; KMES neither creates rings for such CPUs nor publishes
topology-change notifications. A CPU taken offline through `cpu_online` keeps its ring,
and a consumer draining it simply sleeps indefinitely, unable to
distinguish a quiet CPU from a departed one. <a id="cite-failure.offline-cpu-ring-quiet"></a> Hot-add is the realistic
case — hypervisors adding vCPUs to a running guest — while hot-remove
is rare outside mainframes.

Anything that fixes this is additive: a topology-change notification,
whether a generation bump meaning "re-enumerate", a dedicated
descriptor, or a status field in the metadata page, fits the existing
attach-per-CPU design without changing the ring format, the event
format, or the emission API.

One structural caveat applies to attach discovery. The index bound is
the count of rings successfully created, while rings are indexed by
logical CPU id. On a system whose possible-CPU mask has holes, the two
differ: the "attach with incrementing indexes until `EINVAL`" loop
stops early, and rings at high logical indexes are unreachable.

Each logical CPU — each hardware thread under SMT — gets its own ring,
so ring memory scales with threads rather than cores: at the 4 MB
default a 64-core, 128-thread machine holds 512 MB of ring buffers.
This follows from events being emitted per logical CPU and `cpu_id`
naming the logical CPU.

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

## Memory bounding

Ring memory in steady state is `num_cpus × BufferCapacity` for the
fixed CPU count fixed at initialisation, plus two metadata pages per CPU and one shmem page
per ring that has ever been attached. During a capacity swap old and
new rings coexist until every mapping of the old generation is
released.

Transient allocation during emission is bounded by the event size for
a single emit and freed as soon as the event is written. A batch is
different: every entry is staged in kernel memory simultaneously, so a
batch holds up to `count × MaxEventSize` — 256 entries at a 4 MB
maximum event size — until its write phase completes.

Each `kmes_attach` creates one file descriptor, bounded by
`RLIMIT_NOFILE` and by the SeSecurityPrivilege requirement. No
KMES-specific global memory cap exists; the capacity configuration and
standard Linux resource limits are the bounds.

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

## Allocation and timing choices

The data region is a plain `vzalloc` allocation of 4 KB pages, and the
mmap handler inserts pages one at a time, so hugepage backing is not
available to it. The difference is substantial for TLB coverage: a 4 MB
ring needs 1024 standard pages against 2 hugepages, and because the
double mapping doubles the virtual range, 2048 standard pages against
4 hugepages. Allocation is not NUMA-aware: pages come from the
general allocator with no attempt to place a ring on the node local to
its CPU, so writes on a CPU whose ring landed on a remote node cross
the interconnect — roughly 100-150 ns against about 70 ns for a local
node. Timestamps use the full `ktime_get_real_ns()` rather
than `ktime_get_real_fast_ns()`, which avoids the timekeeper seqlock
and costs roughly 15-25 ns less per event at the price of being up to
one tick stale when a timer interrupt is updating the timekeeper
concurrently. Headers are built field by field
on every event with no precomputed per-CPU template, msgpack
validation is scalar, and each staged syscall event takes its own
`kvmalloc` rather than drawing on a per-CPU staging buffer.

None of these choices affects the ring format, the event header, or
the consumer protocol.

---

# Emission Policy

_Peios Kernel / Internals / KMES_

> How the kernel decides which of its own event types are switched on — the generated type table, the cached enabled mask, the walk of Machine\Generic\Events, the watch that keeps it current, and the tier defaults it runs on until the registry can be read.

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

An event type that is switched off is never written. PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>) defines
the policy: a tree of keys under `Machine\Generic\Events`, one per
event-type segment, any of which may hold an `Enabled` `REG_DWORD` of
0 or 1, where the deepest value on a type's path decides and the
type's tier decides when there is none. This section is how the kernel
applies that policy to the event types it writes itself. Userspace
components apply it to their own types through libpeios, peios-rs and
libp-go; KMES does not enforce the policy on what userspace emits.

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

## The kernel's event types

The kernel writes a closed set of event types, fixed when it is built.
They are generated from the kernel's own evman fragments
(`peios/packages/data/evman/*.evman`) by `peios/gen-kmes-event-table.py` into a C
header and a matching Rust module, each type with an id, its type
string and its tier. The generator has a `--check` mode, so a type
cannot change tier in its fragment without the kernel's table
following. <a id="cite-policy.closed-kernel-type-table"></a>

The policy is cached as a 64-bit mask with one bit per kernel type:
bit *i* set means type *i* is switched on. A walk of the registry
computes a whole new mask and publishes it with a single store, and an
emitter reads it with a single load, so a decision is a load and a bit
test and no lock is taken on any emission path. A mask is never
published half-computed. <a id="cite-policy.mask-one-bit-per-type"></a>

An emitter asks before it builds a payload, with
`pkm_kmes_event_enabled(id)`, and Rust emitters through the generated
module's `enabled()`. An `essential` type's tier is a compile-time
constant, so the check for it folds to *on* when the emitter is
compiled and never reads the mask: no policy can switch an essential
type off, whatever the tree holds. <a id="cite-policy.essential-never-consults"></a>
The policy and an event type's own gating — a SACL, an alarm mask, a
`REPORT` level — combine by AND, the policy first because it is the
cheaper of the two.

Every kernel emitter makes the check, and makes it first: before it
resolves the subject, looks up a path, sizes the payload or allocates
anything. A type that is switched off therefore costs one check and
nothing else, and the emitter carries on as though the record had been
written. Each emitter names its type with the generated table's string
rather than one of its own, so the type written and the type the policy
decided on cannot drift apart.

> [!NOTE]
> `kacs.impersonation.reverted` is the kernel's one `verbose` type, so on
> a machine whose policy says nothing about it, it is not written. An
> administrator who wants each revert recorded sets `Enabled` to 1 on
> `Machine\Generic\Events\kacs\impersonation\reverted`, or on a key
> above it.

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

## Before the policy can be read

From the moment PKM initialises until a registry source for the
`Machine` hive has registered and the first walk has finished, the
mask holds the tier defaults: every `essential` and `standard` type on,
every `verbose` and `debug` type off. That is PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s rule for an
emitter that cannot read the policy, and the kernel writes events from
long before any source exists, so it is the policy the kernel runs on
for the whole of early boot. No event is ever held back to wait for
the registry. <a id="cite-policy.early-boot-tier-defaults"></a>

A `verbose` type the registry switches on is therefore not written
before the walk, and a `standard` type the registry switches off is. A
boot-time event that must be written whatever the policy says has the
`essential` tier and nothing else.

If `Machine\Generic\Events` does not exist, no `Enabled` value can be
found anywhere and the tier decides for every type: the kernel
publishes the tier defaults. A bootstrap refresh that finds the key
gone after it existed does the same, so deleting the key undoes the
policy it held. <a id="cite-policy.absent-key-is-tier-defaults"></a>

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

## The walk

One walk resolves every kernel type at once. It reads `Enabled` on
`Machine\Generic\Events` itself, then descends the trie of the kernel
types' segments — `kacs`, `kacs\audit`, `kacs\audit\access` and so on
— looking up only the keys some kernel type's path passes through.
Each key that exists costs one `RSI_LOOKUP` and one `RSI_QUERY_VALUES`.
<a id="cite-policy.walk-follows-kernel-types"></a>

A key that does not exist ends the walk down that path, and nothing
beneath it is asked for: an empty `Events` key costs one query and one
lookup per root. A key that is a link is not followed and ends the
walk the same way. <a id="cite-policy.missing-key-ends-walk"></a>

Only an `Enabled` value that is a `REG_DWORD` holding 0 or 1 is a
setting. A value of another type, of the wrong length, or holding any
other number is ignored as though it were absent, and the setting
found above it stands. Nothing reports the ignored value. Value names
compare ignoring case, as the registry does.
<a id="cite-policy.enabled-dword-only"></a>

From what it read the walk computes the mask by PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s procedure:
for each type, the `Enabled` on the deepest existing key on its path
decides; with none, the tier decides; an essential type is on. The
mask is then published. <a id="cite-policy.resolution"></a> <a id="cite-policy.walk-publishes"></a>

A walk that fails — the source does not answer in time, or answers
with something malformed — publishes nothing. The mask in force stays,
whether that is the tier defaults or the last mask a walk computed,
and a `kmes.config.refresh.failed` record names
`Machine\Generic\Events` and the error. <a id="cite-policy.failed-walk-keeps-mask"></a>

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

## Noticing a change

At bootstrap, after the KMES, layer, port reservation and network
policy keys, LCS discovers `Machine\Generic\Events` and walks it. If
it exists it gets an internal watch of its own; if not, the machine
root fallback watch stays armed (LCS [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)), and creating the key —
`Generic` and `Events` two levels below `Machine`, with or without
`Generic` already there — re-runs the bootstrap, which then walks it
and watches it. <a id="cite-policy.discovered-at-bootstrap"></a>

The watch covers the whole subtree at any depth, but it passes on only
what can change a kernel type: a change on `Events` itself, a change
beneath one of the kernel's five roots (`kacs`, `kmes`, `lcs`, `ntfe`,
`stratafs`), and among value changes only those to a value named
`Enabled`. A vendor writing under `Events\org\…`, which PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)
lets an emitter ignore, costs the kernel nothing.
<a id="cite-policy.watch-filtered-to-kernel-roots"></a>

What the watch passes on is coalesced. The first change of a burst
schedules one re-walk 50 ms later; changes that arrive before it runs
join it rather than postponing it, and a change that arrives while a
walk is running schedules the next one. **A change to the policy
applies within about 50 ms plus one walk** of the write that made it —
or, when a walk is already in progress, after that walk and one more —
however busy the tree is, which is inside PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s one second.
<a id="cite-policy.change-applies-within-50ms-plus-one-walk"></a>

A change is not retroactive. An event already written stays written,
and a decision made before the walk publishes stays made.

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

## The shipped seed

The kernel package ships a registry seed, `event-policy.reg` in
`/usr/share/regim/`, that creates `Machine\Generic\Events` and sets no
`Enabled` anywhere: with nothing set, the tiers decide, which is the
policy a machine ships with. The key is there so the policy has a home
for an administrator to write beneath. Like every seed it is inert
until an image names it in `[registry] autoapply`, and until then
every emitter decides by tier just the same. <a id="cite-policy.seed-creates-key-without-enabled"></a>

The seed gives the key the SACL PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>) asks for, one that audits
writes: `S:(AL;CI;0x10002;;;WD)`, a `SYSTEM_ALARM` ACE for Everyone,
inherited by every key beneath, over `KEY_SET_VALUE | DELETE`. A handle
opened for writing anywhere in the policy tree carries that
continuous-audit mask, so each change to what is recorded can itself be
recorded. Only the SACL is set; the owner and DACL stay inherited from
the `Machine` hive. <a id="cite-policy.seed-sacl-audits-writes"></a>
