Scheduling and CPU accounting¶
Single-level dispatch¶
The first full scheduler replaces the boot runtime’s FIFO dispatch with one system-wide policy over runnable kernel threads with per-CPU run queues. All CPUs use the same class ordering, and placement and migration respect thread affinity. The kernel owns dispatch, preemption, and CPU accounting. Native pthreads remain 1:1 with kernel threads.
On a CPU, the kernel selects eligible work in the following order. Hard interrupt handling occurs outside this ordering. Threaded IRQ handlers and userspace completion workers follow their assigned class.
Dispatch order |
Policy |
|---|---|
Deadline |
Admitted reservations with remaining CPU budget, ordered by earliest absolute scheduling deadline. |
Fixed-priority real time |
POSIX |
Timeshare |
Weighted EEVDF by default. Choose the earliest virtual deadline among eligible threads. Eligibility and CPU share come from the thread’s service lag and weight. |
User idle |
Explicitly selected background work that runs when higher classes have no eligible thread on the CPU. |
Kernel idle |
The per-CPU idle thread waits for an interrupt or the next timer when the CPU has no eligible work. |
Require scheduler administration authority for real-time promotion and deadline admission. Expose fixed-priority policies through the native POSIX scheduling interfaces. Bound the aggregate CPU time available to fixed-priority real-time work so timesharing and essential maintenance can make progress. Define the throttle and replenishment rules explicitly and preserve FIFO and RR ordering within the eligible real-time band.
Keep a shared internal sched_* contract inspired by FreeBSD’s scheduler
interface. Policy code owns runnable ordering and its run-queue state.
The common scheduler owns thread lifetime, clock accounting, IPC timeouts,
class precedence, affinity, and reservation enforcement. Extend the
contract for preemption, changes in scheduling parameters, and migration
as those operations are introduced. Start with EEVDF and add ULE and 4BSD
as boot-selectable timeshare policies. Keep userspace scheduling calls
independent of the internal policy hooks. A boot selects its policy for
the lifetime of that boot.
The boot dispatcher uses sched_runq_t for ready ordering.
The queue owns its links. The dispatcher owns thread state and accounts
for each execution interval before placing a yielding thread back on the
queue. Reading CPU time on the owning CPU includes the current execution
interval. Ready and blocked time contribute no ticks. The boot check
exercises FIFO handoff, accounting while running, thread joins, and IPC
deadlines.
The resident runtime defaults to EEVDF on its boot CPU. The Xmake
--scheduler option sets the compiled default. A firmware command-line
word system.scheduler=eevdf, system.scheduler=ule,
system.scheduler=4bsd, or system.scheduler=fifo overrides that
default. FIFO is the diagnostic policy.
EEVDF measures virtual runtime in reference-weight ticks and uses the weighted mean of runnable threads, including the dispatched thread, as virtual time. A thread becomes eligible when its virtual runtime reaches or falls behind that mean. Enqueueing an existing request preserves its deadline until the thread consumes its real-time slice. Sleeping threads retain bounded lag and return with the unfinished part of their slice. The first implementation scans the bounded resident run queue. Its hosted tests exercise eligibility, weighted service and sleeper lag.
The ULE policy uses bounded histories of execution and blocked time to score interactivity. Time spent ready contributes no blocked time. Ready threads take turns across two run-queue generations. An interactive wake can join the current generation, and consuming a slice moves the thread to the next one. The 4BSD policy lowers the priority of threads with higher recent CPU usage. It decays the estimate over elapsed seconds using the runnable load and updates an inactive thread when it wakes. Both policies use the same bounded resident queue and the same kernel accounting. The hosted tests cover ULE interactive wakeup and generation rotation, and 4BSD usage decay. Resident timeshare threads currently enter at equal weight. Native processes can select a scheduling class through the process supervisor.
The kernel’s internal thread admission also supports fixed-priority FIFO
and round-robin and a lower-priority idle class. FIFO keeps its position
across interrupt preemption. Round-robin rotates an equal-priority peer
after exhausting its slice. A shared fixed-priority allowance limits
execution to half of each 100 ms period on the resident CPU. The
dispatcher runs timeshare or idle work while that allowance is depleted.
The boot test checks class precedence, FIFO position, and round-robin
rotation. The native process interfaces expose SCHED_OTHER,
SCHED_FIFO, SCHED_RR, and the System SCHED_IDLE extension.
A caller can switch its own process between unprivileged classes. The
supervisor requires effective UID 0 for real-time placement or to change
another process. The kernel checks the supervisor’s task capability and
validates every live worker before committing a class change. The base
policy applies to the process and its native workers, and follows fork,
spawn and exec. The round-robin interval is the configured resident
quantum. See Native processes, loading, and the C runtime for the process IPC contract.
-
class kthread_t¶
A caller-owned thread and saved stack, with one scheduler owner.
-
enum class sched_policy¶
Values:
-
enumerator fifo¶
-
enumerator eevdf¶
-
enumerator ule¶
-
enumerator bsd4¶
-
enumerator fifo¶
-
enum class sched_enqueue_reason¶
Values:
-
enumerator start¶
-
enumerator wake¶
-
enumerator yield¶
-
enumerator preempt¶
-
enumerator migrate¶
-
enumerator start¶
-
enum class sched_class¶
Values:
-
enumerator fifo¶
-
enumerator round_robin¶
-
enumerator idle¶
-
enumerator deadline¶
-
enumerator fifo¶
-
constexpr unsigned sched_default_weight = 1024¶
-
class sched_runq_t¶
Intrusive ready ordering. The dispatcher owns serialization.
Public Functions
-
void sched_enqueue(kthread_t &thread, sched_enqueue_reason reason, unsigned weight = sched_default_weight)¶
Insert a thread that is not linked to any run queue.
-
bool sched_detach(kthread_t &thread)¶
Detach a ready thread and retain policy state for a different queue.
-
void sched_attach_running(kthread_t &thread)¶
Reattach the current thread’s accounted interval to this class.
-
kthread_t *sched_dequeue(bool by_priority = false)¶
Remove the next runnable thread, or return nullptr when empty.
-
kthread_t *sched_dequeue_deadline(uint64_t now)¶
Select the earliest admitted deadline with remaining CPU time.
-
uint64_t sched_replenishment(uint64_t now) const¶
First time a queued reservation can run, or zero for an empty queue.
-
void sched_charge(kthread_t &thread, uint64_t elapsed)¶
Charge the dispatched thread’s elapsed service to its policy.
-
void sched_finish(kthread_t &thread, bool blocked)¶
Release the dispatched slot and optionally retain the sleeper’s lag.
-
inline void sched_clock(uint64_t now)¶
Set elapsed-clock time before processing readiness or accounting.
-
inline bool sched_runnable() const¶
Report whether this queue has ready work.
-
inline unsigned sched_count() const¶
Number of ready threads, excluding the dispatched thread.
-
void sched_enqueue(kthread_t &thread, sched_enqueue_reason reason, unsigned weight = sched_default_weight)¶
Hardware topology and placement¶
Represent SMT siblings, cores, shared caches, dies, packages, NUMA nodes, and performance domains as CPU sets. The sets can overlap. For example, one package can have several last-level cache groups and several NUMA nodes, while performance domains describe shared frequency controls. Map firmware processor identifiers to the kernel’s CPU IDs before publishing topology. Validate CPU register data and the available firmware descriptions, including ACPI PPTT, SRAT and SLIT or device tree. Use the known topology when firmware supplies only part of the model.
AMD64 boot publishes CPU sets from the CPUID topology and deterministic cache leaves. It records enabled APIC and x2APIC proximity domains from SRAT when the firmware provides them. The boot CPU validates hardware IDs against the firmware CPU records after secondary startup. Missing or rejected locality data yields singleton groups. Hosted fixtures exercise Intel and AMD enumeration, overlapping cache and NUMA sets, and invalid SRAT data. The QEMU NUMA fixture places two CPUs in separate memory localities and checks the published CPU set.
ARM64 ACPI boot resolves each online MPIDR to its enabled MADT GICC processor UID. It uses that UID for SRAT locality and the PPTT processor hierarchy. A hardware thread shares its parent core, the package comes from the physical package node, and the last-level data cache comes from resolved cache references. Missing entries keep the unknown groups as singletons. Hosted fixtures cover disabled and ambiguous affinities, shared cores and caches, invalid references, and cyclic cache descriptions. See the ACPI table specification.
Limine boots using a device tree match enabled /cpus records by
firmware CPU ID. The kernel follows validated next-level-cache links
to the shared last-level cache and reads numa-node-id where present.
A uniquely resolved operating-points-v2 reference to an enabled
table with opp-shared publishes a shared performance domain. CPUs
with independently controlled clocks keep separate domains.
ARM firmware can also describe relative per-clock efficiency through
capacity-dmips-mhz. Publish those values only when every online CPU
supplies one. These values describe work per clock and do not measure
maximum capacity across different frequencies. Unresolved and cyclic
cache chains yield singleton cache groups. The fixtures cover reordered
CPU IDs, shared caches, incomplete efficiency data and duplicate IDs.
The ARM64 QEMU NUMA fixture checks the firmware CPU-ID mapping.
The bindings are defined in the Devicetree Specification and the
CPU capacity binding. Shared clock domains follow the OPP binding.
-
enum class cpu_domain¶
Values:
-
enumerator core¶
-
enumerator llc¶
-
enumerator die¶
-
enumerator package¶
-
enumerator numa¶
-
enumerator performance¶
-
enumerator core¶
-
struct cpu_location_t¶
Hardware identity and independently discovered locality groups.
-
class cpu_topology_t¶
A boot-built topology that becomes immutable once CPUs are published.
Public Functions
-
bool init(cpu_location_t *records, unsigned count)¶
Supply inventory-sized storage before publishing the first CPU.
-
bool add(unsigned cpu, const cpu_location_t &location)¶
Publish one logical CPU. Reject duplicate IDs and occupied slots.
-
cpu_mask_t group(unsigned cpu, cpu_domain domain) const¶
Return the CPU set for the selected locality group.
-
cpu_relation relation(unsigned cpu, unsigned peer, cpu_domain domain) const¶
Compare records while distinguishing separate and undiscovered groups.
-
uint32_t efficiency(unsigned cpu) const¶
Return the relative firmware efficiency, or zero without complete data.
-
uint64_t nominal_work(unsigned cpu) const¶
Return the boot firmware’s relative throughput score at its stated clock.
-
bool operating_points(unsigned cpu, uint32_t &table, uint64_t &clock) const¶
Report the processor’s firmware operating-point table and stated clock.
-
void set_distances(const uint8_t *matrix, unsigned domains)¶
Borrow a validated square matrix which stays mapped while in use.
-
uint64_t numa_node(unsigned cpu) const¶
Return the firmware NUMA identity, or cpu_group_unknown.
-
unsigned distance(unsigned from, unsigned to) const¶
Return the directional NUMA distance, or zero without matching data.
-
inline const cpu_mask_t &online() const¶
Return the set of logical CPUs with a published record.
-
bool init(cpu_location_t *records, unsigned count)¶
-
class fdt_cpu_topology_t¶
Enumerate CPU locations and shared caches from a flattened device tree.
Public Functions
-
cpu_location_t location(uint64_t hardware_id) const¶
Find a CPU by its firmware ID, or return an unknown location.
-
cpu_location_t location(uint64_t hardware_id) const¶
First restrict placement to online CPUs allowed by affinity, class and resource domains. Retain a thread’s previous CPU when it has capacity and useful cache locality. Prefer shared-cache placement for frequently communicating threads and avoid piling sustained compute onto SMT siblings while physical cores in the eligible set are idle. Balance local groups before considering remote groups. Require a larger benefit for migrations across an LLC or NUMA boundary, and bound migration frequency to preserve hot caches and limit rescheduling interrupts. Coordinate first-touch and memory placement with the VM server using the same NUMA node identities and distances.
The placement selector accepts directional distances from a validated ACPI SLIT, indexed by the SRAT proximity domains associated with logical CPUs. An absent or invalid SLIT falls back to the standard cross-node penalty. Hosted fixtures verify asymmetric distances and a QEMU AMD64 boot verifies the firmware table with CPUs in separate proximity domains.
SMP load balancing¶
Keep load tracking and placement in the common scheduler so EEVDF, ULE, and 4BSD can share them. Each policy still owns ready ordering and the state it needs to preserve service credit across a migration. Establish one dispatcher and ready queue per CPU before enabling balancing for resident workloads. Start with equal capacity and validate migration before enabling placement based on heterogeneous capacity or energy.
Online secondary CPUs accept bounded kernel work through a CPU-owned
mailbox. Publication uses release/acquire ordering and the platform IPI
path wakes the owner. The receiver runs callbacks outside the interrupt
handler with local IRQ delivery masked. The synchronous boot and TLB
fixtures keep their arguments live until the receiver acknowledges
completion. Asynchronous submissions give the caller a completion ticket
and allow it to dispatch independent work while the recipient runs. The
boot test checks simultaneous kernel dispatch using a two-way handshake.
An explicitly migratable kernel thread may move while ready
and free of CPU-local waits or reply rights. The source detaches its
stack and scheduling state before publishing the transfer, and the
destination attaches it on its own CPU. A rejected transfer restores
the source queue. EEVDF rebases bounded lag against destination peers,
ULE rebases its queue generation, and 4BSD retains recent usage. The
source CPU examines up to 16 ready threads per pass and attempts one
eligible migration. A moved thread waits one thirty-second of a second
before it can move again. A thread_migrate record carries the thread
identity in subject, and the source and destination CPU IDs in the upper
and lower halves of value. Its hart identifies the CPU making the move.
The boot check resumes a migrated stack on a secondary, parks it, and
wakes it through the owning CPU. The AMD64 and ARM64 boot checks enter userspace
on a secondary, verify syscall and fault return, and preempt a spinning
user context with the local timer before restoring its prior address
space. Two isolated address spaces share a fixture page. Each userspace
context must see the other CPU’s write before its timer interrupts it.
The boot CPU then remaps a page after the secondary has left its
address space. Re-entry must read the replacement frame at the same
virtual address.
AMD64 keeps the privilege-transition stack, task state descriptor,
and APIC timer calibration private to each logical CPU. ARM64 enables
the timer PPI on each CPU’s interrupt interface.
AMD64 derives the TSC frequency from its architectural ratio when available and measures it against the ACPI PM timer otherwise. Each logical CPU calibrates its own APIC timer over a millisecond of TSC time to limit the effect of individual register accesses on the clock ratio.
Resident dispatch¶
Every admitted resident CPU owns a dispatcher stack and class-specific
ready queues. Application threads and ordinary timeshare server threads
run and resume their kernel continuations on those CPUs. The boot CPU
keeps the root supervisor and external device interrupt service. See Synchronization and SMP coordination for the lock order
and the CPU call and rendezvous contracts.
--smp-users=n changes the build default. UEFI accepts
system.no-smp-users and system.smp-users as boot overrides.
Secondary CPU startup is independent of this setting.
Secondary CPUs run their local dispatcher between mailbox callbacks. A remote enqueue publishes the thread on the destination’s inbound list. The first pending thread rings the destination’s doorbell and the owner accepts arrivals before selecting work. An owner with no runnable work arms its next deadline and returns to the platform idle loop. The boot dispatcher polls briefly while only remote work remains and runs the periodic balancing pass. When its own run queue is empty, it also claims pending device interrupts so remote drivers can complete I/O while the supervisor is blocked. Teardown removes each secondary dispatch callback through that CPU’s mailbox before freeing the group.
The resident dispatch lock protects compound scheduler transitions and frame references. Endpoint wait lists and the capability graph have their own lock domains. Reply lookup and publication can proceed while another CPU holds the dispatch lock. A continuation keeps the lock across a switch to its dispatcher. The dispatcher releases it before idling. Each CPU releases it during protected userspace execution and reacquires it before handling the trap. Saved registers are published first so an authorized stop can wait for the user entry to end while holding the lock.
An endpoint resolves its caller in the executing CPU’s dispatcher. A match, cancellation, or reply removes the waiter from its endpoint. Reply publication can precede removal. The first scheduler transition that retires a published reply uses its recorded outcome. The owner removes its deadline before inserting the continuation into its ready queue. Deferred replies and join edges remain valid until removed under the same lock. A task keeps its authority and stacks until its continuations stop and join. An authorized donor can bring a matched, blocked receiver to its CPU if the receiver’s affinity permits it. The admitted budget stays on the donor’s CPU. A receiver that is already running on another CPU can complete the exchange with its own scheduling budget.
User entry pins its address space through restoration of the prior translation root. Writers drain the affected pins before updating the table and invalidating translations. Other address spaces can keep executing user code during the update. The boot fixtures verify mapping replacement with a pinned secondary, plus cross-CPU call, reply, capability revocation, and affinity-aware scheduling donation.
PowerPC tracks active segment mappings per CPU. PowerVM uses the partition’s hash table. PowerNV borrows its shared table on each secondary and restores the firmware registers between dispatch passes.
Load estimation¶
Track two exponentially decayed signals per thread. Delivered service measures execution, expressed in units of work on a reference CPU where capacity scaling is available. Ready pressure measures wall-clock time eligible to run while waiting for a CPU. A running interval adds only service. A waiting interval adds only pressure. A blocked interval decays both signals. Ready pressure and the current ready count expose contention when measured service alone is low because a thread rarely gets dispatched. Dispatch and admission retain ownership of weights and budgets.
Use a common elapsed-time basis with an initial 32 ms half-life. For an
interval of length dt with constant input sample, update the
average as avg * decay + sample * (1 - decay), where
decay = 2**(-dt / half_life). Use bounded fixed-point arithmetic and
derive the coefficients from this formula. Advance the previous state
before recording a wake, block, dispatch, preemption, or migration.
Charge time once, on the owning CPU. Keep each thread’s history across
queue changes and decay it to a common timestamp before comparison.
Keep a bounded estimate from recent activations for waking threads whose
service average has decayed during sleep. For a new thread, use a small
initial estimate and revise it from the first measured activation.
Each resident dispatcher accounts running and waiting intervals on its queue. The fixed-point filter interpolates independently derived coefficients across one half-life and handles whole half-lives by shifting. Hosted tests cover changing state, long idle gaps, bounded arithmetic, and updates split across dispatch boundaries.
-
struct sched_load_value_t¶
Independent service and waiting-work averages in fixed-point units.
Track per-CPU execution, waiting work, and runnable count under the local queue lock. Use only current runnable work in the placement load. A blocked thread retains its history for its next wakeup. Publish compact per-CPU snapshots for remote readers, including a timestamp, available capacity, and ready pressure. Update local accounting on scheduling events and use bounded balancing passes to refresh older snapshots. Leave idle CPUs tickless when there is no work to balance.
This design takes the decaying service and runnable signals in Linux’s PELT description as a behavioral reference. Implement the estimator, coefficient generation, and balancing code independently under the kernel’s BSD-2-Clause or MIT licensing rule.
Placement and migration¶
The shared selector compares projected load in reference-capacity units. Its initial estimate combines recent timeshare service, waiting pressure, and a floor based on the number of currently ready threads. It subtracts admitted deadline bandwidth from timeshare capacity. The migration rule compares the busiest CPU before and after the proposed move and requires an improvement after charging topology and SMT costs. The boot fixture feeds this rule its source queue’s live sample and transfers a ready thread to an idle secondary. Hosted fixtures exercise affinity, SMT, unequal capacity, reservation headroom, and small imbalances.
-
struct sched_cpu_sample_t¶
When an eligible timeshare continuation wakes into a queue with other ready work, its owner checks the current load, capacity and locality within its allowed CPU set. The old owner retires any IPC or word-wait deadline before transferring ownership. The chosen CPU applies the wake policy to the continuation with its accumulated service credit. Explicitly pinned, reserved, donated and reply-owning continuations keep their owner. The selector does not refresh hardware feedback while a waiter is being detached.
On wakeup, check the previous CPU and its local cache group first. Use the thread’s predicted work and each candidate’s available capacity to compare projected occupancy. Include ready pressure and current queue depth when an estimate lags a burst. Account for higher-class capacity commitments and measured interrupt load when estimating headroom for timeshare. Prefer an idle physical core over an already busy SMT sibling for sustained compute. A successful synchronous rendezvous or reply records the other thread’s current CPU. The location expires after 1/32 second. Periodic balancing includes the cost of moving away from that CPU in its score. Within its bounded scan, an idle pull prefers work that would stay as close to its last peer and can take other eligible work if there is no such candidate. The hint leaves the thread’s allowed CPU set and scheduling class intact.
Expand the search across dies, packages and NUMA nodes when local CPUs cannot absorb the load. An idle dispatcher searches its shared cache group before considering other queues. A periodic pass every 1/32 second samples the ready load and attempts one move between the selected source and destination. Both paths bound the candidate scan and skip recently migrated threads.
Require the predicted relief in normalized occupancy or queue delay to exceed a migration threshold. Raise the threshold across LLC and NUMA boundaries, and apply a cooldown after a move to avoid oscillation. Bound the candidate scan and the number of migrations per pass. Use affinity, class, online state, and placement constraints as eligibility checks. Keep deadline reservations on their admitted CPUs. Start with ready timeshare threads and keep CPU-local or pinned dependencies on their owners. NUMA placement combines the scheduler’s firmware distances with the pager’s preference for memory local to the faulting CPU on systems with SRAT or device-tree memory affinities. See Virtual memory.
Treat remote load snapshots as advisory. Balancers probe a bounded number of ready entries and post migration requests to sources with eligible work. The source dispatcher revalidates eligibility and accounts for the candidate’s last execution interval before detaching it. An idle pull is dropped if ready work has reached the destination. The scheduling group serializes ownership changes, and the destination links the thread into its own run queue. Move queue membership and pending wakeup ownership together, and preserve its policy’s service credit and remaining slice. Allow threads with CPU-owned IPC, timer, or address-space state to move only once those paths support a synchronized transfer or remain valid on the destination. Signal a remote idle CPU or request preemption after the destination queue has accepted the work. A thread has one dispatch owner throughout the transfer. A concurrent wakeup must resolve to the committed owner.
Host-test decay and fixed-point bounds, long sleeps, wakeup estimates, and accounting across a move. In QEMU, verify that oversubscribed and bursty workloads use eligible idle CPUs, pinned work stays in its CPU set, equal-weight work retains its share, and weak imbalances do not cause repeated migrations. Exercise wakeup and affinity changes during migration, plus IPC and reservation progress under contention. Compare throughput, queue delay and p99 wake-to-run latency with balancing disabled under the same dispatch policy. Record migration counts by topology boundary, rescheduling interrupts, and LLC misses where counters are available. See Performance design and measurement for the measurement method.
The boot option system.no-smp-balance disables resident idle pulling,
wakeup redistribution, and periodic redistribution. Initial placement, per-CPU dispatch, remote
wakeups, and explicit affinity changes remain available. An A/B run can
use the same SMP configuration and a fixed system.scheduler value.
When a source has several ready threads, the periodic pass first offers
work to idle CPUs, preferring a shared last-level cache. This wakes a
destination that has gone to sleep with no pending timer. The source
rechecks that the destination is idle before detaching a thread.
Balancing between busy CPUs continues to use the load and locality
thresholds.
CPU capacity and energy¶
Keep maximum capacity, effective capacity under frequency or thermal limits, utilization, and power cost as distinct inputs. First choose CPUs that fit the thread’s demand. Where a power model is available, compare the incremental cost across eligible performance domains, including raising a shared clock or waking an idle CPU. Fall back to capacity and locality when feedback becomes invalid or the power model is unavailable. Treat vendor efficiency scores as relative rankings. Keep CPU budgets in elapsed execution time. Use conservative CPU capacity for deadline admission and keep an admitted reservation on its CPU until another CPU admits it.
The capacity store publishes effective capacity and a separate maximum
and efficiency rank. Complete device-tree capacity-dmips-mhz and
clock-frequency properties establish a static relative estimate at
the supplied frequencies. Missing data on any online CPU means equal
static capacity. The store accepts a complete, newer, expiring snapshot
from the designated provider generation. Revocation, expiry, and
replacement recover the static estimate. A synthetic guest provider
changes placement through available headroom and verifies fallback in
the SMP boot test. The hosted test also rejects partial, out-of-order,
and out-of-range submissions.
-
class sched_capacity_t¶
Store a complete snapshot from one kernel-authorized provider.
Firmware and power-policy services can supply samples through authorized asynchronous transport. They cannot change thread affinity or dispatch class. Hardware provider registration and runtime feedback consumers still follow the adapter design below.
The optional AMD64
system.hfiprovider reads Intel capabilities from one kernel-owned, physically contiguous table per package. CPUID enumeration selects the row and bounds the table. The kernel captures the initial sample on the package that owns the table. An unused x2APIC thermal vector can notify the resident dispatcher of a table update. The handler masks its vector and records a notice. The collector reads the package table, acknowledges the update and restores delivery. Firmware thermal users retain their vectors. The dispatcher polls at 100 ms intervals as a fallback, including when balancing is disabled. The boot CPU reads its own package and uses asynchronous mailbox work for the others. Placement uses a complete sample and returns to static capacity if a package stops responding or no longer owns the registered table. Live samples expire after a second. Table allocations stay pinned until hardware acknowledges disablement. A synthetic QEMU check exercises masking and acknowledgement of the interrupt vector. Hardware notification and feedback delivery require suitable Intel CPUs.Thread Director extends that table when the online CPUs support a common class layout and the kernel can allocate the score tables. AMD64 enables classification on each logical CPU at user entry and resets hardware history when the resident thread identity changes. It uses HRESET where enumerated and the local classification enable bit otherwise. The return path saves only an in-range class with a valid hardware bit. A short interval without a fresh classification retains the thread’s last class. Thread reuse starts unclassified. The kernel restores the local controls when it stops the provider.
Class-zero capacity still describes queued CPU load. The classified request uses its own relative performance score when the scheduler compares a wakeup or migration, and its efficiency rank breaks equal-score placement ties. Affinity, reservation limits, and migration bounds still apply. A zero class score steers the request away from that CPU when another eligible CPU is available. Wakeups fall back to the ordinary score when every allowed CPU has an unusable class score. Missing class support leaves ordinary HFI available. Expired feedback restores static capacity and retires the class scores together. The hosted checks cover table geometry, classification validity, and placement. The guest fixture verifies a real cross-CPU wakeup with synthetic scores. See the Intel HFI reference.
AMD HFI uses a userspace ACPI PCC driver to parse firmware-provided rankings and publish snapshots. The architecture context-switch code reads the logical CPU’s workload class and resets hardware history where supported. Keep CPPC preferred-core ranks, available capacity, and workload-class ranks as distinct inputs. The live PCC driver depends on the firmware region authority in the native ACPI service described in Platforms, device drivers, and virtualization.
ARM big.LITTLE uses architecture and firmware capacity data. A platform service can supply validated operating points and costs from firmware, device tree, or SCMI and own frequency and power policy. Resident placement can use a complete static device-tree model once the stated clocks agree with the fastest non-turbo operating points. It normalizes
opp-hzwithin each clock domain and sums the declaredopp-microwattvalues for each point. Incomplete data or operating points gated by an unverified hardware mask keep capacity and locality placement. The static model uses a zero fixed domain cost because this binding provides only operating-point power.
The optional power model requires complete coverage of online CPU clock domains. Each domain supplies ordered operating points and the fixed cost of keeping the domain active. Placement estimates the domain’s peak per-CPU demand before and after adding a thread and selects the lowest operating point that can cover that peak. It compares the incremental cost across candidates that fit, within one eighth of a fully occupied CPU’s placement score of the locality and capacity choice. The hosted fixture exercises activation, shared clock changes, affinity, headroom, and fallback when domain data is incomplete.
-
class sched_power_t¶
Validated read-only clock-domain table borrowed from a platform provider.
Intel’s HFI pages stay pinned for the hardware registration lifetime. An AMD PCC driver maps only its authorized firmware communication region. Use scoped mappings and notifications for feedback. PCI device DMA continues to use the IOMMU-backed device interfaces in Platforms, device drivers, and virtualization.
Use synthetic topology and capacity fixtures to verify affinity, load distribution, migration bounds, admission, and fallback after provider failure. Compare wake-to-run, IPC and fault tail latency, throughput, remote migrations, and LLC misses with an unmodified baseline. Use physical hybrid and NUMA systems to validate hardware feedback and measure energy per completed workload.
Deadline reservations and service progress¶
The kernel’s internal admission path supports periodic implicit-deadline reservations. Their aggregate admitted load is capped at 40 percent per CPU. The dispatcher selects the earliest admitted deadline with remaining budget and throttles a depleted thread until its next period. A thread releases its admitted share on exit. The boot test verifies EDF ordering, rejection above the ceiling, and reuse of a released share. The hosted budget test covers exhaustion, replenishment, and charging across a period boundary. Lower-class userspace slices end by the earliest replenishment of queued higher-class work, so ready reservations can preempt a timeshare or idle thread when their budgets return.
Use earliest-deadline-first dispatch with hard Constant Bandwidth Server budget enforcement. Start with implicit deadlines, where the relative deadline equals the period. On wake, retain the remaining budget and absolute deadline if the remaining budget divided by time to that deadline fits the admitted bandwidth. Otherwise refill with a deadline one period from the wake. A depleted budget stays throttled until the replenishment boundary. Assign each reservation to one CPU and admit it only when that CPU has capacity below its configured reservation ceiling. Account for interrupt and kernel overhead and leave capacity for other classes. Changing the reservation’s CPU requires admission on the new CPU. Throttle depleted reservations until replenishment. Trace admission, depletion, replenishment, and missed deadlines separately from ordinary timeshare latency and IPC wait timeouts.
Run general VM, VFS, and filesystem workers in timeshare. The resident
supervisor reserves 1 ms per 20 ms for each wired vm-io worker to
submit page I/O and publish completion. The kernel accepts the request
before task startup for a single-threaded task in the recovery pool.
Reaping the old thread releases its share so restart can admit the
replacement. A worker can block on its storage or zram provider without
blocking the pager. Further candidates include wired reclaim, storage
completion, and supervisor recovery workers. Admit only work with bounded CPU demand and a validated
dependency path. Keep essential code, stacks, buffers, and IPC state wired
and reserve the resources needed for progress under memory pressure.
Account for the time of all workers participating in the reservation.
A CPU reservation covers execution time. End-to-end fault or I/O latency
also depends on device service and the behavior of every dependency.
See Virtual memory and Native server activation and supervision.
IPC scheduling contexts¶
Use bounded priority inheritance for synchronous IPC and pass a client’s scheduling context to an authorized server when an endpoint accepts donation. Start with same-CPU handoff. The current holder executes using the donated context’s remaining budget, class, and accounting identity. Charge the client once for work performed on its behalf. Charge interrupts, shared housekeeping, and unrelated requests to their own service or system accounts. A nested call can pass the same context along one chain, with one active holder and one budget. It cannot mint another reservation.
Same-CPU calls opt in through the scheduling right on both capability
slots. A fixed-priority or deadline caller can lend its context to an
eligible timeshare or idle receiver. Nested calls can pass the context
through up to eight edges. The dispatcher charges the original deadline
reservation or shared real-time allowance while running the holder.
The normal class ordering still applies. Deferring a reply ends the loan
before the server accepts more requests. The dispatcher revalidates
both capabilities at scheduling boundaries, and releases the loan when
either authority is revoked. The wired vm-io workers and their
dedicated swap providers use this path. The boot fixture exercises
authorized nesting, ordinary IPC fallback, and revocation during a
nested call.
An authorized call that finds its receiver waiting finishes the caller’s dispatch interval and runs the ordinary eligibility selection. When a thread can run immediately, the kernel switches directly to its saved kernel stack. If the reservation is depleted and no thread is eligible, the dispatcher handles the wait and replenishment. The boot fixture parks both receivers before the authorized call so it exercises the direct handoff through two nested endpoints.
Release an inherited priority or donated context on reply, cancellation, timeout, revocation, or exit. A blocked context remains accountable to its owner when the server restarts. The handoff must satisfy both the receiver’s affinity and the donor’s resource constraints. A path that cannot accept the donation can use ordinary IPC with its usual scheduling behavior. Completion workers required for forward progress retain their admitted service budgets when a client depletes its own. Benchmark wake-to-run, IPC and fault latency under mixed workloads, including a high-priority client blocked behind lower-priority service work.
Keep disk request dispatch in the storage services. The block provider’s queue discipline can use priority, batching, and device locality while respecting the limits in Resource domain controls.
Hierarchical dispatch¶
A later scheduler can represent an authorized process group or zone as one runnable entity in its parent’s scheduler. A node can contain threads, child scheduling groups, or both. Dispatch descends through eligible children until a policy selects a runnable thread. Each level can choose its own scheduling policy within the CPU set, budget, and class authority granted by its parent. Execution is charged to every ancestor on the selected path. If an ancestor exhausts its budget, its subtree becomes ineligible until replenishment. A child’s internal priorities and deadline keys apply within the CPU time granted to that child.
For example, system-wide EEVDF can schedule native processes and two zone entities together. A Linux-branded zone can use EEVDF internally and a FreeBSD-branded zone can use ULE internally. Inside that FreeBSD zone, an administrator can give a build workload its own scheduling group and CPU budget. The system policy selects the zone, ULE selects the build group, and the group’s policy selects a build thread. An administrator selects child policies through native configuration. A brand can supply a default for its zone. IPC inheritance and direct handoff across domains must respect the same ancestor budgets and effective affinity as ordinary dispatch. Native resource domains supply the accounting and authority.
Userspace server scheduling¶
Offer participating servers a Go-style userspace task scheduler. A task represents work such as handling a client request. A bounded pool of kernel threads runs those tasks, with a configurable limit on CPU parallelism. The runtime owns ready queues and task state. The kernel preempts and accounts for the workers as ordinary threads. Task identity is local to the server and worker TLS follows the underlying thread.
The native server runtime provides a bounded queue of eight request tasks. A task advances in short, explicit steps and returns a park result while waiting for an asynchronous operation. A completion resumes the task by generation token. The queue records an early completion while its worker still owns the current step. Cancellation schedules cleanup on a worker and takes precedence over later notifications. A task owns its slot until its final step releases it. Completion callbacks run outside the queue lock, and a full queue reports backpressure to the caller.
Participating servers supply user stacks and a notification endpoint for their native worker threads. Idle workers block on that endpoint with a bounded receive timeout. Producers notify workers after submitting, resuming, or cancelling a task. The runtime fixture starts two native workers and verifies progress past an asynchronous park, cancellation, stale-token rejection, and queue exhaustion. Hosted tests cover completion and cancellation during an active step.
-
class server_tasks_t¶
Queue and ownership for cooperative tasks running on kernel workers.
The VM pager uses this queue for reads from swap providers. The pager’s request thread owns the task steps and mapping metadata. A bounded set of wired I/O workers carries out the blocking reads while the pager handles other faults. Each provider has one in-flight read. Its completion resumes the matching task, which checks that the mapping and saved page still match. Timeout and worker replacement cancel the task. A timed-out worker retains its transfer buffer until it returns or the supervisor replaces it.
An asynchronous IPC or I/O operation parks its task and frees the worker to run another task. A completion makes the parked task runnable. Associate the request and its cancellation with a single owner so a timeout, client exit, or service replacement can race with completion without double replying or reusing stale authority. Bound runnable and pending requests. When a queue is full, defer intake or return the service’s defined overload error. Assign unavoidable blocking calls to a bounded worker pool, with capacity reserved for essential completion work where needed.
Begin with task switches at explicit yield and wait points. A CPU-bound task must reach those points within the server’s latency budget. Charge worker CPU time through the kernel scheduler. Use any donated context only while executing on its request’s behalf. Export task and request IDs alongside kernel thread IDs for tracing and debugging. Measure queue depth, throughput, CPU cost, and tail latency against an ordinary worker pool under mixed load when evaluating other service paths.