Kernel mechanisms and IPC

Architecture bring-up

The UEFI ports share the table allocation and page-table walk in packages/kernel/mm/pmap.cc. Each architecture encodes its own entries and owns root activation and invalidation. AMD64 preserves the upper kernel mappings when creating a new CR3 root. ARM64 retains the separate TTBR1 kernel mappings and switches TTBR0. Both ports use boot-CPU-local translations during the early checks. RISC-V retains remote invalidation for its running native threads.

ARM64 UEFI supports a 16 KiB native granule on CPUs that advertise it. The kernel switches TTBR0 geometry when entering a native address space and restores the previous geometry on return. The allocator rescales usable firmware ranges to complete native pages. Boot modules can still arrive on 4 KiB boundaries. The kernel copies module data that cannot be mapped directly with the chosen granule and clears the unused tail of each copied page.

PowerPC spreads the virtual segment IDs of consecutive address spaces across the small boot hash table. The high bits retain the space ID, while the low bits mix it with the segment number to keep resident services and forked processes at the same virtual addresses from concentrating their translations in the same groups.

AMD64, ARM64, and both PPC64 byte orders have assembly switch frames for their integer callee-saved registers and first-entry trampolines for new kernel stacks. Their early checks switch to a private stack, suspend, and resume. The UEFI builds also run an isolated userspace probe. AMD64 installs a boot TSS and enters ring 3. ARM64 sets the EL0 stack pointer and returns through the lower exception level. The probe traps into the kernel, resumes, and records the faulting address on an unmapped read. The synchronous trap and local timer handlers mark interrupted frames with DWARF signal-frame records in the retained .eh_frame.

Authority and lifetime

Capabilities convey a reference to a typed kernel object and a set of rights. The common lookup checks slot generation, object type, and rights before using the object. Derivation can reduce rights and delegates only authority held by the source. Revocation invalidates descended slots. A slot generation distinguishes stale handles from the new occupant of a reused slot. The storage owner retains an object until references are gone, and synchronization must protect capability trees shared by tasks.

using cap_handle_t = uint64_t
enum class object_kind

Values:

enumerator endpoint
enumerator notification
enumerator thread
enumerator address_space
enumerator frame
enumerator memory_pool
enumerator console
enumerator interrupt
enumerator power
enumerator device
enumerator trace_stream
enumerator debug_session
class kobject_t

The object’s owner retains its storage while slots reference it.

Subclassed by endpoint_t, notification_t

class cap_space_t

The capability graph serializes slot and derivation operations across spaces.

Public Types

using visitor_t = void (*)(kobject_t&, uint32_t badge, void *argument)

Use an authorized object while its slot blocks graph mutations.

Public Functions

cap_handle_t grant(kobject_t &object, unsigned rights)

Install a root capability during privileged bootstrap.

cap_handle_t derive(cap_handle_t source, cap_space_t &target, unsigned rights, uint32_t badge = 0)

A receive-owning endpoint capability can mint a labelled sender.

kobject_t *resolve(cap_handle_t handle, object_kind kind, unsigned required, uint32_t *badge = nullptr) const

A returned pointer needs an owner-held lifetime after this lookup.

bool revoke_tree(cap_handle_t handle)

Remove all descendants and the selected slot in one operation.

A mapping and its backing frame have a lifetime separate from a handle that can operate on them. Releasing an individual handle does not implicitly destroy a live mapping. Task destruction must coordinate pending IPC, endpoints, mappings, active page tables, and outstanding device access. The initial runtime uses bounded pools for tasks, address spaces, frames, and endpoints. Exhaustion and stale authority have defined failure paths.

Calls, replies, and faults

The native short-message ABI uses four register words. Synchronous sends match a receiver, calls expect a reply, and replies use a single-use token bound to the receiving thread. Endpoint destruction or task exit completes blocked operations with an error. Revocation can remove the right needed to finish an operation even after it has begun. Asynchronous notifications coalesce pending bits and require active receive authority to wake a waiter.

native_ipc_call_timeout bounds both rendezvous and reply with one nonzero delay in platform time counter ticks. It returns native_ipc_timed_out when the deadline expires and preserves the caller’s message. The scheduler removes a queued request or invalidates its reply token before waking the caller. A request that was already delivered may have changed server state. Callers must account for this before retrying. The RISC-V scheduler checks deadlines at IPC and scheduling boundaries and wakes at the earliest deadline when all threads are blocked. native_ipc_receive_timeout uses the same scheduler mechanism to bound time spent waiting for a sender. On expiry it removes the receiver from the endpoint and leaves the receive buffer untouched.

A receiver can defer an active reply with ipc_defer_reply and continue receiving while that caller waits. One receiver can retain multiple deferred tokens on the same endpoint. Each token is single-use and stays bound to the original receiving thread and endpoint. Each reply retains its own deadline, rights checks, and cancellation on thread exit and endpoint closure. The root supervisor uses deferred replies for child waits and console reads while it services faults and exit events.

An endpoint’s receive-owning capability can mint a send capability with a badge. Descendants inherit it and cannot change it. The kernel delivers the badge as receive metadata, separate from both the message words and the kernel-event flag. A reply has no sender badge. Use badges to identify delegated service sessions. The root supervisor uses distinct badges for shell requests, driver notices, and runtime test clients.

An endpoint also has a slot for one pending badge from a capability with the notify right. Posting delivers an empty message to a waiting receiver or records the badge and returns immediately. Repeated posts of the same badge coalesce. A different badge returns native_ipc_busy while the slot is occupied. Receiving consumes the pending badge before servicing queued synchronous senders. The message carries neither a reply token nor a kernel-event flag. Use this operation as a hint to read current state from its owner. Revoking a capability prevents further posts with that capability. Closing the endpoint discards the pending badge.

class endpoint_t : public kobject_t

The endpoint owns its wait lists. The scheduling group serializes changes to continuations and donated budgets. The object owner retains storage until capabilities, queued waiters, and active users are gone.

class notification_t : public kobject_t
struct native_message_t

Payload and metadata for a native IPC exchange.

A userspace page fault or foreign syscall suspends the originating thread and delivers the relevant state to an authorized userspace endpoint. The kernel translates missing data pages into read or write requests for the pager. Other exceptions are identified as unhandled. The raw exception cause remains available to the supervisor and the trace stream. An authorized fault reply can report that a mapped file no longer covers the page. The kernel records a bus error and preserves the original trap registers for inspection. Other services continue on the same scheduled execution path while the originator waits. A reply can resume or fail the operation subject to the kernel’s context and mapping rules. Provide authorized inspection and modification of suspended contexts for debugging, signal delivery, and foreign ABI setup. Native dispatch and foreign syscall numbers use distinct dispatch paths. See Native processes, loading, and the C runtime and Foreign executable and application ABIs.

The task supervisor can derive one badged notification-only capability alongside a child task’s ordinary endpoint capability. It can delegate that badge with notification rights into a second task. The kernel revokes the notification capability when the child is destroyed. The native pager uses that capability and a notification-only capability for the supervisor endpoint to signal progress on a wired mailbox. See Virtual memory.

The supervisor can delegate management of a particular address space and memory pool. Frame creation resolves the pool in the caller’s capability space and copies initialized bytes from that caller’s mappings. Mapping requires authority over both the target address space and the frame, and the frame must ordinarily belong to the target’s pool. The supervisor alone can use frame_map_wired to establish a non-executable shared mapping across pools, such as the VM and GPT swap buffer. The supervisor uses frame_map_shared to map a data frame in the application VM arena with sharing across fork. The operation retains the same frame even when the caller requests an initially inaccessible alias. Anonymous swap snapshots exclude these frames. mapping_rights returns the protection bits of an aligned user page to a caller with address-space authority. It can support recovery when a pager’s mapping succeeded before its reply was lost. pool_available reports the free page count to a caller with management rights to the selected memory pool.

The RISC-V bootstrap runtime keeps inline records for small tasks and allocates additional pages of mapping and frame records as required. The records are charged to the corresponding physical memory pool. Ordinary frame allocations cannot consume the pager recovery pool. Mapping records are reused after unmap and released on task teardown. Unused frame-record pages are collected during task teardown.

mapping_protect uses a separate delegation right. It can reduce protections on existing user mappings in the authorized address space. It grants no authority to inspect, create, or remove mappings. The runtime linker receives this right for its own address space to seal ELF relocation data after startup.

VM uses the management right for anonymous data mappings in the native arena. The kernel can resolve an anonymous copy-on-write fault, make a data page inaccessible while retaining its backing frame, and copy a frozen page into the caller’s wired buffer. The kernel validates the address, permissions, and capability before applying any of these operations. See Virtual memory for how VM sequences them for pageout and recovery.

SMP, scheduling, and machine mechanisms

The kernel handles context switches, timers, preemption, interrupt delivery, and CPU-local state. The boot adapter describes and releases secondary CPUs. Architecture code installs per-CPU state and implements interprocessor calls and targeted TLB invalidation. Keep CPU-specific register and page-table operations under the architecture include root.

CPU inventory and per-CPU storage

Use dense logical CPU IDs for scheduling and per-CPU storage. The firmware adapter retains the mapping to hardware IDs, which may be sparse. Size CPU tables from the validated firmware inventory and track possible, present, and online CPUs separately. The possible set has storage reserved for it. A present CPU has been enumerated. An online CPU has completed interrupt setup and can accept work. Keep a published logical ID stable through an offline/online cycle. Inventory growth and live CPU removal require a CPU lifecycle protocol before storage can grow or be reclaimed while readers are active.

Use --nr-cpus=platform or a build-time ceiling from 1 through 2048. The boot CPU takes logical ID 0. The adapter enrolls secondaries in firmware order up to the ceiling. The platform defaults are 64 on AMD64, 512 on ARM64, 256 on RV64, and 2048 on PPC64 in either byte order. The PPC64 default follows Linux’s PowerNV configuration. A platform may impose a lower limit through its CPU bring-up or interrupt controller. Arrays indexed by logical CPU are sized from the boot inventory. Keep the configured ceiling out of userspace ABI types. See the upstream AMD64 Kconfig, ARM64 Kconfig, RV64 Kconfig, and PowerNV defconfig.

The kernel supports two forms of per-CPU allocation.

  • PERCPU_DEFINE(type, name) = initializer puts a trivially copyable, constant-initialized object in the linker template. Each boot profile instantiates that template once per possible CPU before releasing secondaries. The template has a read-only mapping. percpu::on uses the symbol’s offset to address a CPU’s mutable copy. percpu::local selects the calling CPU. AMD64 secondary CPU descriptor tables and timer calibration, PPC64’s active hash space, and RISC-V hart state use the linker template. Initialize machine-dependent pointer fields per CPU after startup if they depend on the relocated kernel address.

  • percpu_allocation_t::allocate is the runtime equivalent of Linux’s alloc_percpu. It reserves zeroed, aligned storage for each possible CPU from the kernel physical-page allocator. Small instances occupy distinct 128-byte-aligned slots within pages. Larger instances get their own contiguous page runs. A directory indexes the runs, so the entire allocation can span discontiguous physical memory. get(cpu) returns the instance by logical ID. Interprocessor mailboxes, trace rings, and benchmark counters use this form. Failed allocations release all pages they claimed. The owner publishes a fully initialized handle and calls release only after readers and pending interprocessor work have quiesced.

Keep the current CPU pinned while using a local pointer. A remote pointer only selects the storage. Its reader must follow the owning subsystem’s locking or acquire/release protocol. Allocate and free from a context permitted to use the physical-page allocator. Hosted fixtures exercise static initialization, dynamic allocation, isolation across the 64-bit CPU boundary, and rollback under exhaustion. For the interface models, see FreeBSD dpcpu(9) and Linux per-CPU operations.

class percpu_allocation_t

Own zero-filled, cache-aligned storage for a boot-discovered CPU set. Publish the handle only after allocation. Quiesce all users before freeing.

class cpu_mask_t

A kernel CPU set. Scalars used by early boot fixtures supply the low word.

Topology, scheduler placement, and affinity use multiword CPU sets. The AMD64, RV64, and ARM64 GICv3 fixtures boot 65 CPUs and exercise an application pinned to logical CPU 64. ARM64 allocates its GICv3 redistributor records for the enrolled CPUs and uses the SGI range selector where supported. The boot-time device-tree decoder measures the CPU, SMT, cache, and operating-point records before allocating scratch space. It translates hardware IDs into scheduler groups and releases the firmware inventory after publication. Firmware energy domains and Intel HFI packages use multiword CPU sets. Placement indexes energy domains by logical CPU. Intel’s row IDs and page limits come from CPUID.

The PowerVM and PowerNV adapters currently start the boot CPU and one secondary. Raspberry Pi enrolls up to its four cores. Interrupt routing on each platform follows the hardware controller’s addressability.

Userspace CPU locality

Expose CPU discovery through the configured and online processor counts in sysconf and expose a snapshot of the calling thread’s logical CPU through sched_getcpu(). The current-thread sched_getaffinity and sched_setaffinity forms take PID 0 and a byte length. The kernel intersects requested CPUs with the available execution set and rejects an empty result. New pthreads inherit their creator’s mask. PID-directed operations need process authority and the later CPU-resource controls. A thread’s mask applies to its userspace and kernel continuation. A timeshare thread whose new mask excludes its current CPU switches to its dispatcher, transfers queue ownership, and resumes on an eligible CPU. Fixed-priority and reserved threads retain their dispatch owner.

Applications use thread-local storage for state owned by a thread. Drivers and services may allocate their own state per queue or per CPU and use affinity to place their workers. The kernel’s per-CPU template and allocator stay private. DMA buffers use the device mapping interface. A CPU ID query is a snapshot and can become stale on migration. Use thread-owned state, synchronization, or a worker pinned to one CPU for updates that must stay on one CPU. A restartable-sequence ABI can be added if measured workloads need CPU-local updates on migratable threads.

Resident dispatch

The runtime preempts user tasks and supports stopping tasks that spin or block. Each enabled CPU dispatches eligible applications and servers and handles their syscalls and faults. A dispatch lock protects shared runtime pools and scheduler transitions that span continuations. Endpoint wait lists and capability derivation have their own locks. User entry pins the current address space until the CPU restores its prior translations. Writers drain the pins and complete invalidation before releasing old frames. See Scheduling and CPU accounting for queue ownership, IPC wakeups, and scheduling donation, and Synchronization and SMP coordination for word waits and remote CPU calls.

The boot hart constructs the runtime tables in reserved kernel storage. The task and capability tables can grow independently of the firmware bootstrap stack.

The boot runtime separates the task’s address space and capabilities from each worker’s register state, deadline, and kernel stack. The supervisor enables worker creation at task launch. An enabled task can use thread_create to start a worker at an executable address with its own mapped stack, optional TLS pointer, and argument. The kernel applies the target’s C ABI when setting up the worker’s initial context. The boot scheduler has six worker slots shared by enabled tasks. Worker IDs belong to their owning task and are never reused within the boot runtime.

thread_exit completes a worker with a full register-width result. native_thread_join waits on the same scheduler and collects that result once. The scheduler rejects self joins, cycles, and a second waiter for the same worker. Task exit cancels worker IPC and join waits, drains the workers, and releases their kernel stacks before reporting the task ready to reap. A fatal worker exception ends the task using that worker’s trap status. The caller owns the workers’ userspace stacks and TLS mappings.

thread_exit_call relinquishes a worker’s user context and attempts one bounded IPC call under the task’s endpoint authority. The receiver can reclaim userspace storage while the worker is on its kernel stack. The worker cannot be joined once the call is accepted. The scheduler runs its cleanup from the dispatcher stack and releases the worker slot, except when a task-exit waiter owns it.

int64_t native_thread_join(uint64_t thread, uint64_t &result)

Wait for a worker in the current task and collect its full-width result.

Use native in-memory representations for private state. Specify the byte order and layout of external ABIs, files, and device data explicitly. Check these boundaries on both little- and big-endian 64-bit targets.