756 Commits
Author SHA1 Message Date
Garvit Surana 78052d244c docs(readme): what's next after 0.6.2 (laptop battery, lid and keys in testing; AMD and Intel already in the main download), and the experimental Wi-Fi chips in the requirements
ci / format (push) Waiting to run
ci / check (macos) (push) Waiting to run
ci / check (linux) (push) Waiting to run
ci / check (windows) (push) Waiting to run
2026-12-01 00:25:40 +05:30
Garvit Surana fc1ea681ea docs(readme): Stambha 0.6.2 is out, one download for NVIDIA, AMD and Intel graphics, with AX211 and MT7925 Wi-Fi experimental 2026-12-01 00:03:58 +05:30
Garvit Surana 6534091473 style(xtask): read a symbolized function's words as 4-byte arrays (as_chunks), where clippy 1.99's chunks_exact_to_as_chunks failed xtask's lane on the forward-branch scan 2026-11-30 16:36:45 +00:00
Garvit Surana a83916afc6 test(gpu): the ANV sampler cap's bounds hold at compile time, where clippy's test lane refused an assertion on constants 2026-11-30 16:36:45 +00:00
Garvit Surana 570e6a050a fix(wifi): the BIOS reads PR #48 takes at probe are kept only for the 51f1 bring-up with an ACPI companion, and its tests build them as the gate holds them, where the gate's first form left driver-net's native-acpi test lane unbuilt 2026-11-30 16:36:45 +00:00
Garvit Surana 2f1291f95c merge: stambha main (its README front page, CONTRIBUTING, SECURITY, issue and PR templates, and assets) into release/0.6.2, keeping main's README, so 0.6.2 reaches main as a fast-forward, where main never held 0.6.0 or 0.6.1's code and a push of the release would have replaced its front page 2026-11-30 16:04:26 +00:00
Garvit Surana 3a1b52d0c8 style: format the 0.6.2 additions as rustfmt does (#47's firmware recipe test, #38's pkgconf choice and sampler test, #48's tests and its AX211 gate, the I219 state line test), where cargo fmt --check failed 2026-11-30 16:03:22 +00:00
Garvit Surana c9dd9c0d84 fix(wifi): PR #48's Intel CNVi bring-up runs on the AX211 at 8086:51f1 alone (its APM link bits set unread, its BIOS tables read at probe, attach waiting for its NVM address, setup past AX200's, the country, scan, queue and link changes after it), and every other Intel card takes the path it had, where the PR changed them for every Intel family
The AX211 stopped at Power(Rejected { register: 256, mask: 8388608 }); rqffael's PR takes it through association on his Latitude 5340. The predicate is identity::cnvi_bring_up, one PCI device, carried on the profile; tests of other models take it through a test-only hook, and new tests pin an AX210 still refused at setup and the masks off for every other device. The PR's later revision moves the address wait into GuestNetwork::open for every adapter with no address yet, which would change other cards, so the wait stays in attach, for 51f1 alone.
2026-11-30 16:02:37 +00:00
Garvit Surana e25309ac5e test: declare candidate 2's four by-hand engine timings and replays in the oracle manifest (fetch_path_cost, the Finder window's parts and nursery and two-slides replays, and the kept-forms replay), fetch_path_cost's ignore reason the canonical manual one, where xtask's manifest test failed on the first unbound ignored test 2026-11-30 15:51:19 +00:00
rqffael 8ed7b415c7 wifi: mask EHT and pre-assoc HE flags in Intel MLD LINK_CONFIG_CMD (PR #48) 2026-11-30 15:46:26 +00:00
rqffael 56a874489a wifi: accept TX_QUEUE_CFG_ENABLE_QUEUE flag bit in Intel SCD_QUEUE_CONFIG_CMD reply (PR #48) 2026-11-30 15:46:26 +00:00
rqffael 402a052b1f wifi: set beacon interval in Intel MLD LINK_CONFIG_CMD before activation (PR #48) 2026-11-30 15:46:26 +00:00
rqffael 92cf419fc7 wifi: defer LAR country-update notifications during Intel scan and PHY setup (PR #48) 2026-11-30 15:46:26 +00:00
rqffael f2de37cb77 wifi: adopt matching firmware MCC and handle world-domain MCC_RESP_ILLEGAL (PR #48) 2026-11-30 15:46:26 +00:00
rqffael f0c7654b9c wifi: allow AX210 and newer Intel families through setup and management queue (PR #48) 2026-11-30 15:46:26 +00:00
rqffael 64e3ad81e1 wifi: report iwlwifi bring-up phase and error via Link::diagnostic (PR #48) 2026-11-30 15:46:26 +00:00
rqffael 6c0beaed81 wifi: prefetch Intel ACPI BIOS tables during probe inside ACPICA continuation (PR #48) 2026-11-30 15:46:26 +00:00
rqffael e5ee1b07b0 wifi: wait for Intel NVM MAC address during attach before returning Link (PR #48) 2026-11-30 15:46:26 +00:00
rqffael dca606762a wifi: match Linux iwl_trans_set_bit without readback for APM link workaround CSRs (PR #48) 2026-11-30 15:46:26 +00:00
Garvit Surana d719b795d4 feat(boot): the GPU's own Linux backlight takes the brightness keys, and a dark panel is raised at the display's start, only with --panel-backlight, off unless given, where PR #40 sent every laptop's keys to the first Linux raw backlight, nouveau's among them, ahead of ACPI's _BCM 2026-11-30 15:46:13 +00:00
Federico Bricca cb10003d43 feat(gpu): drive native Linux DRM panel backlight from hardware brightness keys (PR #40) 2026-11-30 15:44:46 +00:00
rqffael 6231e73524 xtask: prefer host pkgconf over pkg-config wrapper for mesa_clc (PR #38) 2026-11-30 15:44:21 +00:00
rqffael 56f2f00aa2 metal: cap ANV's bindless sampler descriptors at 4096, twice Metal tier 2's 2048 and past NVK's 4000, where ANV's 65,536 kept a pool most of which no app reaches in the integrated GPU's share; other drivers keep their own counts (PR #38) 2026-11-30 15:44:21 +00:00
Garvit Surana ac39fbf462 fix(e1000e): the I219's register dump names how many sent frames the MAC wrote back with a collision or underrun flag, for the SPT/CNP I219s whose guest DHCP goes unanswered (italiano, Diamond Master) 2026-11-30 15:44:21 +00:00
Garvit Surana ba4a30e67b test(cli): the built bundle holds 471 files and 246.6 MiB, as the AX211 Bluetooth firmware and its DDC (2 files, 721,061 bytes) add to every build's count, where four setup tests still expected 469 files and 245.9 MiB 2026-11-30 15:42:45 +00:00
Garvit Surana d7cd4c3c1c test(cli): a stick that refuses the shorter log file holds the NVIDIA loader its free room was counted without, so the larger loader's update shrinks the 32 MiB log to 8 MiB and the refusal is what keeps it, where with no loader on the stick the log was kept before the write and the test failed wherever the folder really refuses writes (CI, not root) 2026-11-30 15:42:45 +00:00
Garvit Surana c772346d32 fix(xtask): the hosted RADV corpus run's loader names no system-memory placement, where the merge of candidate 2's NVK system-memory reopen and test 7's first-submission check left its initializer without the field and xtask did not compile 2026-11-30 15:42:45 +00:00
BluePhi09 f7e7b755d7 fix(boot): the PC's devices start sooner, as a PC with no software-managed USB4 host no longer waits 700 ms for USB4 domains to go quiet and an xHCI's connected root ports are enumerated before its empty ones wait out the connect settle time, where the boot stick waited 400 ms more than its debounce; the boot log names USB Bluetooth firmware loads and the ACPI platform devices, whose time it charged to the last controller started, and the startup choices' help text says a key pressed right away opens them too 2026-11-30 14:10:52 +00:00
MGKFN 02e1291365 fix(boot): the performance summary names the balanced preference and the boot processor's new minimum
Review fixes for --cpu-balanced: the HOST PERFORMANCE line said
preference=performance even when the Intel requests took the balanced
preference, and the boot processor's second request added its new
minimum to the range beside its first, so requested_minimum read
lowest-highest. request_again now replaces that processor's minimum
(Tally::replace_minimum) without counting it again, while it is the only
processor recorded; the line names preference=balanced under
INTEL_BALANCED where a processor took an HWP request.

(PR #53)
2026-11-30 13:31:38 +00:00
MGKFN feebe6223a feat(boot): --cpu-balanced lets Intel cores slow down, where a power-limited laptop starves its GPU
On a 15 W Intel laptop (i5-1235U, Iris Xe) every core is held at its
highest HWP level, so the package sits at PL1 and the integrated GPU
runs at 100 MHz. WindowServer then fills its GPU memory budget and is
killed during Setup Assistant (as in #35).

--cpu-balanced keeps each core's highest level but sets the minimum to
its lowest and the energy preference to 0x80 (balanced), so idle cores
drop their clocks and the package budget reaches the GPU. The boot
processor asks again once the options are read; the APs take the
balanced request from the start. Off unless given.

(PR #53)
2026-11-30 13:31:38 +00:00
Garvit Surana d80d69f760 release: Stambha 0.6.2 2026-11-30 13:24:03 +00:00
Garvit Surana 3089d6d843 fix(gpu): a posted call no Linux task has taken is withdrawn after 400 ms, still under XNU's half second and past the 200 ms a held fence wait keeps, where at 300 ms the boot processor's GPU pump, held 350 to 364 ms on a UHD 630 and an Iris Xe, had GPU call 0x40086409 withdrawn with ETIMEDOUT and WindowServer crashed after the Language Chooser (antuneddu and rqffael, issue #52) 2026-11-30 13:21:55 +00:00
Garvit Surana 6c7d35c14c fix(soc): the stop for a USB-C port controller image that neither the boot bundle nor the board's flash holds says the flash is in the machine-state area a copied disk or a reset of it lacks, that macOS would have no keyboard, pointer, USB network or Bluetooth without it, and that Install macOS writes it again and erases that disk, where it said only that an install fills the flash and okakatel228's copied disk stopped at every boot with no way forward 2026-11-30 13:18:14 +00:00
Garvit Surana 611cd2cfec fix(memory): the memory plan leaves out an NVIDIA GPU older than Turing that the firmware catalog has no chip for, which the claim refuses, so the integrated GPU beside it is planned as the GPU that draws with its full share of RAM, where an i5-1035G1 laptop's UHD Graphics drew beside a refused GeForce MX330 as its fallback, budgeted to 2248M of heap pages with 1605M for Metal, ran out at 1080p and WindowServer died (android_artisan) 2026-11-30 13:13:04 +00:00
rqffael 8243769072 bluetooth: accept Intel WRITE_DDC completion payload matching Linux btintel_load_ddc_config 2026-11-30 13:06:39 +00:00
rqffael c8d5b785f1 bluetooth: accept Intel bootup notification payload matching Linux btintel_bootup 2026-11-30 13:06:39 +00:00
rqffael b38276efcc firmware: bundle Intel TLV Bluetooth firmware for AX211 (ibt-0040-0041) 2026-11-30 13:06:39 +00:00
rqffael a21723dd95 bluetooth: allow Intel TLV bootloaders to omit optional CNVR_BT (0x13), DEV_REV_ID (0x16), and Debug Lock (0x2c) 2026-11-30 13:06:39 +00:00
Federico Bricca d11c88cf51 feat(hle): report PES HLE summary on shutdown when --hle is active 2026-11-30 13:06:34 +00:00
Federico Bricca e81adba3c4 feat(hle): extend forward-branching functions in xtask and add oracle-verified bzero for 26B123 2026-11-30 13:06:34 +00:00
Federico Bricca 866ea1d327 feat(hle): add oracle-verified __platform_memmove signature for macOS 26B123 2026-11-30 13:06:33 +00:00
Federico Bricca 02a0910176 fix(hle): match __platform_* symbols, allow dst==src memmove in oracle, and support 16 KiB guest leaves 2026-11-30 13:06:33 +00:00
Federico Bricca 5905646972 fix(acpi): enter loader root before clock/dispatch checks in call_owned so guest-loop ACPI polling works 2026-11-30 13:06:33 +00:00
Federico Bricca 4ba29ab465 fix(ioapic): skip Unit-claimed pins during verify_contained so --acpi-hardware SCI does not block PCI/GPU bring-up 2026-11-30 13:06:33 +00:00
Federico Bricca 641bec4f11 fix(smc): mark little-endian battery keys with SMC_ATTR_LITTLE_ENDIAN and notify on state changes 2026-11-30 13:06:33 +00:00
Federico Bricca 1fe07ab181 fix(wifi): drop WrongPeer/WrongChannel/Unsupported station frames in MediaTek policy link 2026-11-30 13:06:33 +00:00
Garvit Surana 740703f15f feat(app): the macOS app shows itself as Stambha, with the pillar icon, in its name, window, menus, dialogs and report, and keeps its bundle identifier and executable, so an installed copy updates in place, where it still showed Stela and Stela's icon 2026-11-30 13:06:03 +00:00
Garvit Surana e6d9a9ac0c merge fork/062-intel-test7 (Intel tests 3 to 7: i915 and xe with ANV beside NVK and amdgpu with RADV, the iGPU memory share, GuC and CCS controls) into release/0.6.2, keeping candidate 2's --share-aliases, --host-cursor and NVK system-memory placement beside test 7's --i915-guc and first-submission check 2026-11-30 13:05:49 +00:00
Garvit Surana 02ccd767e9 fix(gpu): run ANV with Gen12's CCS aux compression off (INTEL_DEBUG=noccs), as RADV runs without DCC, with --intel-ccs to keep it on and a boot log line saying which, where CCS under the Metal device's unified image layouts drew garbled UI on Iris Xe and ended in 10 s context resets for GPU hang (found by rqffael, issue #35)
rqffael's Latitude 5340 (i7-1365U, Iris Xe 8086:a7a1) drew corrupted UI
and lost its GPU to "context reset due to GPU hang" until he set
INTEL_DEBUG=noccs in the C library's environment beside
ANV_SYS_MEM_LIMIT; after it the session ran more than 13 minutes and
8,465 submissions with no hang, ENOMEM or crash. RADV already runs with
DCC off for the same unified layouts, where an image a copy fills and a
shader samples read back blank.

getenv now answers INTEL_DEBUG=noccs unless the boot keeps CCS on
(stela_libc_intel_ccs, from the hand-written --intel-ccs option); nothing
else sets INTEL_DEBUG. The display's scanout buffers and the shared
IOSurface images are linear-modifier images, so nothing assumes a CCS
modifier. The kernel fixes his issue lists are in the series already:
0236 takes the guc_id before the lock and 0237 the i915_active node
before the tree's lock, as his patches do.

Reported-by: rqffael <https://github.com/rqffael>
2026-11-27 18:47:23 +00:00
Garvit Surana cf2fb49d08 fix(boot): say after the chosen startup choice that its line in choices.cfg runs in place of stela.cfg's, where test 6's instructions had dev64 add --gpu-strict-families to stela.cfg, which a boot through choices.cfg never reads, and his strict boot still claimed Apple4
With \EFI\stela\choices.cfg on the stick, stela.efi boots the chosen
entry's options line (NAME, a tab, the options) and reads none of
stela.cfg's; stela.cfg holds the default entry for a boot without
choices. The boot log now says which line ran, and test 7's instructions
name choices.cfg.
2026-11-27 18:47:23 +00:00
Garvit Surana 7764acbe4f fix(i915): a kernel built with CONFIG_STELA says the GPU's clock against what RPS asked for and GT0_PERF_LIMIT_REASONS, every 30 s while the render engine is awake and at each heartbeat that finds it stuck, where only a reset said how fast the GPU ran and a power or thermal limit could not be told from a hang
MGKFN's i5-1235U Iris Xe hung with the GPU at 400 MHz of the 1200 RPS
asked for, which only the reset's line said. The render engine's
heartbeat now reads the actual and requested frequency, the RPS range and
the package's limit reasons (PROCHOT, thermal, RATL, VR thermal alert,
VR TDC, PL4, PL1, PL2 and the sticky log above them) and says them in one
line: at most every 30 s while it beats, and at each beat that finds a
heartbeat request stuck. Engines other than render say nothing.
2026-11-27 18:47:23 +00:00
Garvit Surana e8e575d03b feat(gpu): name in the log line of a render pipeline whose fragment inputs do not link each unlinked input with its type and components, the output of its identifier, and every vertex or mesh output, once per pipeline, where dev64's RenderBox pipeline plane__vertex + uber_resolve_fragment was refused in test 6 with only "fragment input without a matching vertex or mesh output"
link_varyings links an input to an output of the same identifier, scalar
type and component count. Its refusal now carries, once for each pipeline
line, VARYINGS unlinked fragment inputs [identifier:TypexN (the output of
its identifier is ... | no output of its identifier)] of N inputs; vertex
or mesh outputs [...]. The matching is unchanged: whether Metal links a
half output to a float input, or a fragment input with fewer components,
is not established, so nothing new links until a log shows what RenderBox
asks for.
2026-11-27 18:47:23 +00:00
Garvit Surana 3e1c5510c6 feat(gpu): claim Apple5 on a GPU without multisampled storage images, refusing alone the pass whose stencil resolve follows a min or max depth resolve, let Apple6 hold by its own checks, and say after the family line what the GPU claims without them and the first of Apple4 to Apple6 it is out of, where RenderBox, which climbs from Apple4 and stops at the first refusal, stopped at Apple5 on dev64's Iris Xe in test 6 and his Default style icons still drew blank
The stencil resolve that follows a min or max depth resolve resolves
copies of the stencil's samples, which take multisampled storage images,
which ANV reports on no Intel GPU. Unless the boot asks for the strict
families, Apple5 now takes the stencil resolve alone, as Apple4 and Apple1
already went without their multisampled parts; render_pass refuses a
pass that asks for the following resolve, which a test holds on ANV's
capabilities.

Apple6 takes sparse textures, vertex amplification, function pointers
and dynamic libraries in render pipelines, texture atomics and ASTC HDR
sampling, none of which takes multisampled storage, so it holds or not by
its own checks. On i915, ANV has sparse residency through TR-TT on Gen12
and multiview; ASTC HDR is sampled decoded. The ANV fixture holds Apple6,
and Apple7 still takes Metal3. The boot log's family note names what is
claimed without multisampled storage images and the first family the
GPU is out of, with what it lacks of it. NVIDIA and AMD derive what they
did.
2026-11-27 18:47:23 +00:00
Garvit Surana c0c5aea8a4 fix(gpu): reopen a lost device at the next connection or close even while connections of the lost epoch still hold objects, which stay with the lost device while their calls but releases are refused, and say so in one line, where MGKFN's setup screen held 47 objects of a lost Iris Xe, no device reopened and every WindowServer after it was refused and crashed six times with the screen frozen
recover() reopened a lost device only once no connection held an object
of it. MGKFN's test 6 boot lost its Iris Xe at 414 s; a connection of the
lost epoch, likely the Language Chooser, kept 47 objects of 227 MiB, the
device never reopened, and WindowServer crashed in a loop until the end.
dev64 recovered only because his clients closed.

The next connection or close after a loss now reopens. A connection of
the lost epoch keeps its objects with the lost device, which the
reopened one replaces: its calls but releases are refused as before, a
release lets go of its handle alone, and its close leaves the reopened
device untouched. The lost device retires as before: one whose backend
cannot prove its queue idle keeps every handle and its memory, so no DMA
reaches freed memory. A reopen despite held objects says how many
connections and objects stayed with the lost device.
2026-11-27 18:47:23 +00:00
Garvit Surana e0de0a3a77 feat(gpu): say in the memory line how many lost devices are still retiring and how many were let go with what they allocated kept, and its size, where dev64's test 4 lost 3.5 GB of the Iris Xe's share to the device lost at 22 minutes and the log never said so
After test 4's GPU loss the reopened device held 0 MiB, yet Linux held
3500 MiB of the GPU's 7598 MiB share and the memory the guest works in
fell from 5590 MiB to 2949 MiB. A replaced lost device whose backend
cannot prove its queue idle, as a lost Vulkan device's idle wait cannot,
is dropped with every handle and its memory kept, so that no DMA the
GPU may still run reaches freed memory. That stays as it is; the GPU
MEMORY line now says lost_devices=retiring:N/kept:N/MiB.
2026-11-27 16:51:18 +00:00
Garvit Surana ec0bffcc72 fix(gpu): clear a texture an automatic heap places as a new texture is, unless the next submission's first commands write it whole, and count those clears in the memory line, where it kept the bytes an earlier texture of the heap left in its range, and a fresh heap's zero bytes, which are not zero texels in a compressed layout
New and recycled textures are cleared at the start of the next
submission, and a heap's memory is filled with zero bytes when the heap
takes it, but a texture placed in an automatic heap was neither: a range
freed by an earlier texture of the heap reached the next one with its
bytes, and in a layout the driver compresses (AMD's DCC, NVIDIA's
compression tags, Intel's CCS) zero bytes do not read as zero texels.
Testers on AMD and NVIDIA see dark or garbage rectangles around round
elements such as the login avatar where they should be transparent;
that this is their cause is not proven.

A placement heap's textures stay as they were: they alias what the
client placed there, as on a Mac. The GPU MEMORY line counts the clears
(heap_cleared=), one per texture an automatic heap places.
2026-11-27 16:51:18 +00:00
Garvit Surana 299f0ed322 feat(gpu): name the process of a heap's nil in its log line, as its connection's first report named it, where the line gave a connection number alone and which process asked could only be guessed from the order they opened the GPU
The bundle opens each report with getprogname()[getpid()]; the service
keeps the first one each connection sends, and GPU HEAP NIL lines say
process=name[pid], or process=unnamed before the connection reported
anything.
2026-11-27 16:51:18 +00:00
Garvit Surana aaff377e8c feat(gpu): claim Apple4 on a GPU without multisampled storage images, refusing alone the pipelines and textures that need them, with --gpu-strict-families to keep such a GPU in Apple3, where ANV on every Intel GPU stayed in Apple3 and RenderBox, which asks for Apple4, drew dev64's Dock and Settings icons as blank squares in the Default icon style
RenderBox asks for Apple4 in com.apple.dock.extra, iconservicesagent,
ControlCenter and SecurityAgent on dev64's Iris Xe in tests 4 and 5, and
the device said it was not in it. dev64's icons draw in the Clear and
Tinted styles and stay blank in Default.

ANV reports shaderStorageImageMultisample on no Intel GPU. Apple4 took
multisampled framebuffer reads, which take multisampled storage views,
and Apple1 took multisampled 16-bit packed render targets, which a
driver that cannot render a packed format itself writes through
multisampled storage views of its raw texels. Unless the boot asks for
the strict families, such a device now claims Apple1, Apple2 and Apple4
with single-sample framebuffer reads and packed targets, as Apple3
already reads single-sample framebuffers; a pipeline that reads or tiles
a multisampled framebuffer (framebuffer_reads_at) and a multisampled
texture of a packed format without MSAA are refused one at a time, as
before. Apple5 still takes the stencil resolve that follows a depth
resolve, which takes multisampled storage images, so ANV stops at
Apple4.

The boot log names the claim, or what keeps a device in Apple3 out of
Apple4, after the family line, and --gpu-strict-families, a hand-written
stela.cfg option setup never writes, restores the strict families. A
device with multisampled storage images derives what it did.
2026-11-27 16:51:18 +00:00
Garvit Surana fd50cb0ddb fix(gpu): let a GPU call its kernel driver still performs run 30 s before the boot stops, past i915's slowest GuC reset of a hung Gen12 render context, so the reset fails the call, the device is lost and WindowServer restarts, where test 5's 10 s stop came first in both of dev64's boots while i915 had reset nothing yet
dev64's Iris Xe hung in an execbuffer (0x40406469) once in test 4 and
twice in test 5. In test 4, i915 printed "context reset due to GPU hang"
5.6 s after the call was first reported; the call failed, the device was
lost and WindowServer restarted. In both test 5 boots the 10 s stop came
first, with no i915 line between the report and the stop, and "Fence
expiration time out" only after it.

i915 with GuC submission finds a stuck engine at a heartbeat (2.5 s),
raises its priority at the next one, and GuC then waits the Gen12 render
engine's preemption timeout (DRM_I915_PREEMPT_TIMEOUT_COMPUTE, 7.5 s)
before it resets the context: up to 12.5 s, longer than the stop. The
stop is now 30 s, twice that, and a test keeps it so. The waiting PE's
report says how long it waits, and a call that ends after the report
says when and with what result. i915's timeouts are unchanged.
2026-11-27 16:51:18 +00:00
Garvit Surana 10c2e62b5b test: declare test 4's unbound ignored tests in the oracle manifest (tlbi_keep_cost and the tier 2 bench as manual opt-in timings, the T602x DeviceTree checks as oracles of STELA_TEST_M2_DT_DIR), where xtask's manifest test failed on them 2026-11-27 13:41:09 +00:00
Garvit Surana 1d411824b9 test(gpu): a lost device takes none of a display's scanout buffers and keeps its generation until a reopened device serves, which the display's composition waits for before sharing them again 2026-11-27 13:07:32 +00:00
Garvit Surana 3168b12bba fix(gpu): make newBufferWithBytesNoCopy: of an address within a page over the pages around it, starting the buffer that far in (wire minor 1, NewImportedBufferAt), where its nil crashed mediaanalysisd every few minutes on dev64 and each crash ran ReportCrash
Espresso, which mediaanalysisd runs its models with when there is no
Neural Engine, makes 16-byte no-copy buffers 8 bytes into a page
(0x781827ff58 at 725.9 s of dev64's test 4 boot). The frontend wired
[bytes, bytes + 16 KiB), the gate refused ranges that are not whole
pages, Metal answered nil and mediaanalysisd crashed 0.5 s later. It
crashed five times in 30 minutes, ReportCrashService restarting eleven
times to report them.

The frontend now imports the whole pages around the bytes and asks for a
buffer offset bytes into them. The VkBuffer starts at the driver's buffer
alignment below the bytes and the Metal buffer where they are: commands
take the start as the buffer's offset in its VkBuffer, as they do for
upload suballocations, and its address is the bytes'. Textures over such
a buffer are refused, as their rows are addressed from the VkBuffer's
start. A page-aligned address imports as before.
2026-11-27 11:51:04 +00:00
Garvit Surana 74a81a5ad4 feat(gpu): say in a lost device's fault dump which span of each unfinished command buffer started and never ended, with its kind of work, indirect draws and the pipelines it bound, and mark 62 passes a command buffer instead of 30 (Mesa patch 0045), where dev64's dump named all 68 pipelines of the frame a 10.5 s hang was in and none of them as the one
dev64's test 4 boot lost its device at 1362.8 s: the GuC reset rcs0 for a
request queued 10543 ms before, at 1500 MHz, so a request that ran and
did not yield rather than a slow clock. The dump named command buffer
29382 and its 68 pipelines but could not say which pass hung, and with
30 marks WindowServer's Liquid Glass frames already spent their longest
spans after the 30th pass.

Each command buffer's timestamps (its start, the end of each pass and
dispatch group up to the mark limit, its end) are now read at the loss
without waiting: the first span whose start the GPU wrote and whose end
it did not is the work it was in. ANV answered every query read of a lost
device with VK_ERROR_DEVICE_LOST; Mesa patch 0045 lets a read that does
not wait return what the GPU wrote, from the pool's memory, which stays
mapped. A driver that answers nothing is named so. The line also counts
the span's indirect draws and dispatches, whose counts the GPU reads.
2026-11-27 11:51:04 +00:00
Garvit Surana 46cc162509 fix(gpu): let fragment functions run the fragment tests themselves on single-sample attachments where the device has no multisampled storage images, refusing only multisampled ones, where ANV ran none and RenderBox's accumulator_coverage_fragment_depth was refused on dev64's Iris Xe in every boot, the Dock's icons staying grey squares
A function that reads its color attachment and writes depth cannot have
its pipeline test fragments before it runs, so it tests them itself in
its interlock section on storage copies of the depth and stencil
attachments. Those copies were gated on shaderStorageImageMultisample,
which ANV reports on no Intel GPU, so on Intel every such pipeline was
refused ("attachments accessed as storage by a function that writes
depth, stencil or coverage"). dev64's tests 2, 3 and 4 each refuse
plane__vertex + accumulator_coverage_fragment_depth, RenderBox's path
coverage shader, and no other tester's logs do; dev64 is the machine
whose Dock icons are grey.

Commit 8ee5d9019 already lets ANV read single-sample framebuffers without
multisampled storage. This does the same for the fragment tests: the
single-sample copies need maintenance8 and formatless storage reads,
which ANV has, and a pipeline that would test multisampled attachments
itself is refused ("fragment tests of multisampled attachments"), as a
multisampled framebuffer read already is. The stencil resolve that
follows a depth resolve still takes multisampled storage images.
2026-11-27 11:48:55 +00:00
Garvit Surana 9256788088 fix(display): compose the display's frames on the GPU again once a reopened device replaces the lost one, where one GPU loss left the CPU composing for the rest of the boot and dev64's cursor flickered after WindowServer restarted
At 1362.9 s of dev64's test 4 boot the service's device was lost to a GPU
hang. The display composition forgot its shared scanout buffers and, at
the next frame, shared them again with the still-lost device:
share_scanouts answered DeviceLost, and that error took the path of a
driver that cannot import the buffers at all, refuse(), which no later
frame undoes. The service reopened a device for the restarted
WindowServer within seconds, but every DCP PACING line of the remaining
520 s says composed=gpu:0, with turnarounds of 100 ms and more and the
cursor's input-to-present at 284 ms.

The composition now remembers the generation of the device that was
lost holding the buffers (SharedService::generation, which advances when
a reopened device serves) and shares nothing while it is the one served,
without exporting the buffers again. A lost device answers share_scanouts
before importing any descriptor, so they are closed. Once the generation
changes the buffers are shared with the new device and the log says
"composes the display's frames into its shared scanout buffers again".
Other import failures still refuse for the boot.
2026-11-27 11:48:55 +00:00
Garvit Surana 3c34d1f892 style: format test 4's GuC and descriptor heap lines as rustfmt does 2026-11-27 11:48:55 +00:00
Garvit Surana 8696ec7796 merge fork/062-host-cursor into fork/062-candidate2 2026-11-27 09:46:32 +00:00
Garvit Surana e1a76a255b feat(display): show the pointer where the host's is at each vblank with --host-cursor on, giving the guest's absolute pointer the host-accelerated mouse position and learning the hotspot from the guest's own placements, where the pointer moved only when WindowServer's cursor client swapped, 3-20 times a second and 35-950 ms behind the mouse on a 165 Hz panel (boot 35)
The guest draws its pointer as layer 1, a 128x128 surface its cursor client
places at position - hotspot; each move is a full HID -> WindowServer -> swap
round trip under translation. With --host-cursor on (off unless given):

- the input service accelerates mouse and touchpad-as-mouse motion on the
  host and gives the guest the position on its tablet interface, so macOS
  takes it as it is and a click lands where the host shows the pointer; the
  mouse's first three buttons go with the tablet, its side buttons stay on
  the mouse;
- the DCP model matches each guest placement against the last 512 positions
  given to learn the hotspot (at rest: the newest position less the origin;
  moving: the one candidate two placements share), shows layer 1 at the
  host's position in every present while it holds, and presents a vblank
  the host's pointer moved at with no swap (damage: the rows it left and
  reached), completing and pacing nothing;
- a placement no position explains drops back to the guest's own placement;
  one at rest that no hotspot inside the surface explains is a warp the
  host adopts;
- each CURSOR beat adds a HOST CURSOR line: positions given, host-drawn
  presents and guest moves a wall second, the guest's distance from the
  host's pointer while locked, the hotspot, locks, unlocks, shapes, warps.

Not with --trackpad, whose touch frames move the guest's pointer itself.
Needs a hardware boot before it can default on.
2026-11-27 09:43:51 +00:00
Garvit Surana 546035750a fix(compiler): compile paired_return only for the Linux x86-64 tests that call it, where the macOS cross clippy of the lib tests found it never used once --share-aliases moved the code it served to paired_return_for 2026-11-27 08:52:27 +00:00
Garvit Surana d751da1d8e fix(gpu): say what a reset Intel render engine ran and how the GPU was clocked (Linux patch 0240), where dev64's and MGKFN's resets for a 7.5 s preemption timeout left no line naming the request, its batch or the GPU's frequency 2026-11-27 07:57:29 +00:00
Garvit Surana f95b5b231f fix(gpu): start Alder Lake P and Raptor Lake P or U with i915's GuC again in test 4 (--i915-guc auto), a failed GuC still sending the next start to execlists, where test 3's execlists lost both Alder Lake P testers' GPU to an engine reset after minutes of the desktop
dev64-2 started these platforms without the GuC because each of Mesa's
submissions failed with -ENOMEM under it in dev64-1. That failure was an
i915_active node taken with GFP_ATOMIC that Stela's slab never served,
and Linux patch 0237 removed it in the same build, so the GuC never ran
with it. Under execlists dev64's a7a0 and MGKFN's 46a8 then each lost the
Metal device to "Resetting rcs0 for preemption time out" with GPU
latencies rising to hundreds of milliseconds first. The GuC's SLPC sets
the GPU's frequency in place of i915's own RPS, so test 4 tries it.

The record's build is now test4, so a record dev64-1 or dev64-2 wrote is
passed over. A boot whose GuC fails writes one, and the next start goes
without it; `--i915-guc off` still starts without it by hand.
2026-11-27 07:57:29 +00:00
Garvit Surana c439f5053b merge stambha release/0.6.1-gpu-experimental (PRs #11, #18, #24, #25) into fork/062-intel-test4 2026-11-27 07:49:53 +00:00
Federico Bricca 59e5596fe6 fix(wifi): stop MediaTek bring-up retries once the start budget expires (#25)
Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
(cherry picked from commit 2ecb66f4f8ac97e6c1f0b6de581aafcb0facca01)
2026-11-27 07:49:41 +00:00
Federico Bricca 4e3d8a4f5e fix(wifi): encode Connac3 MT_TXD1_HDR_FORMAT at bit 14 for MT7925 MCU commands (#24)
Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
(cherry picked from commit 295f81797da7100933fde4f4695af6d5f1cc21b2)
2026-11-27 07:49:41 +00:00
Federico Bricca aa9f736345 fix(boot): wait on a contended heap lock in GFP_ATOMIC allocations, fixing amdgpu vblank ENOMEM (#18)
Linux's kmalloc(GFP_ATOMIC) (mm/slub.c) does not sleep or reclaim, but still waits on its spinlock. Registering Heap::try_allocate_zeroed for the Linux GPU heap returned NULL on a single contended lock attempt, causing amdgpu_dm_crtc_set_vblank (amdgpu_dm_crtc.c:370) to fail with -ENOMEM and triggering drm_vblank_put underflow warnings (drm_vblank.c:1271) when dm_arm_vblank_event_pre_programming (amdgpu_dm.c:10491) ignores drm_crtc_vblank_get's return value.

Add Heap::allocate_atomic_zeroed, which serves small size classes from the per-CPU cache when cores are tagged and otherwise waits on the heap spinlock with local interrupts masked, and wire stela-boot's Linux GPU heap callback to it.

Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
(cherry picked from commit 0ad94f8900feb245663a2c5299ef902ff6634cd0)
2026-11-27 07:49:41 +00:00
Android-Artisan 738b71c4d5 fix(i915): name the ENOMEM that fails an execbuf or a VMA pin, with the execbuf's buffer count and flags and the pin's size, alignment and flags, rate limited (Linux patch 0238), where a boot whose Mesa submissions failed for memory said no allocation that refused
From PR #23, without its i915_vma_pin retry loop: its i915_gem_shrink
asked for a target of 0 pages, so it reclaimed nothing, and execbuf pins
through i915_vma_pin_ww, which the loop never reached.
2026-11-27 07:49:01 +00:00
Android-Artisan c73034ccc7 fix(usb): acknowledge any SET_IDLE rate a HID interface is sent, still repeating no unchanged report, where a nonzero rate stalled and macOS 26's DriverKit HID driver, waiting for its status stage, left three IOUSBHostInterface objects busy and the guest panicked 60 s into a userspace reboot
GET_IDLE still answers zero, so the host never expects idle repetitions.

From PR #23.
2026-11-27 07:48:48 +00:00
Garvit SuranaandAndroid-Artisan adb42736fa fix(gpu): cap each image array of the Metal descriptor heap at 1,048,576 descriptors, texel buffers included, three quarters of which still hold Metal tier 2's 500,000, where 4,194,304 left ANV a descriptor buffer of tens of MiB in an integrated GPU's small share of RAM
The heap's sampled and storage arrays now take 786,432 images and
262,144 texel buffers each, and ANV's pool keeps about 99 MiB of host
records for them where it kept 291 MiB. PR #23 capped each source count
at 666,666 for Ice Lake; this keeps the one cap test 3 added and lowers it.

Co-authored-by: Android-Artisan <romartisan2025@gmail.com>
2026-11-27 07:48:33 +00:00
Android-Artisan 6e8e413809 fix(gpu): settle ANV's execbuf ENOMEM as a refused command buffer, not a lost device, and bound Mesa's execbuf retries to about 0.3 s (Mesa patch 0044), where an ENOMEM ANV returns without making the submission's signals lost the Metal device and Mesa's retry loop held a processor for up to 17 s
ANV's execbuf can fail with ENOMEM without making any of the
submission's signals. The Metal device took every failed submission as a
loss. submit_and_settle now loses the device only for DeviceLost; another
failure fails just its command buffer: with no earlier segment submitted
its event signals are reached at once, and otherwise the flight stays
pinned until the submitted part completes, when Stela makes the signals
ANV never made, so nothing the GPU still reads is freed early.

Mesa patch 0044 lowers the execbuf ioctl wrapper's retries from 80
(about 16.7 s of sleeps) to 20 (about 0.3 s), and ANV answers a
persistent ENOMEM with VK_ERROR_OUT_OF_DEVICE_MEMORY after three tries
instead of marking its queue lost.

From PR #23, without its single-sample framebuffer check and its 4 MiB
heap headroom test.
2026-11-27 07:46:49 +00:00
Federico BriccaandFederico Bricca 534aa972e5 fix(wifi): stop MediaTek bring-up retries once the start budget expires (#25)
Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
2026-11-27 13:15:59 +05:30
Federico BriccaandFederico Bricca 9cc6c68bc0 fix(wifi): encode Connac3 MT_TXD1_HDR_FORMAT at bit 14 for MT7925 MCU commands (#24)
Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
2026-11-27 13:15:54 +05:30
Federico BriccaandFederico Bricca a0c70c65e6 fix(boot): wait on a contended heap lock in GFP_ATOMIC allocations, fixing amdgpu vblank ENOMEM (#18)
Linux's kmalloc(GFP_ATOMIC) (mm/slub.c) does not sleep or reclaim, but still waits on its spinlock. Registering Heap::try_allocate_zeroed for the Linux GPU heap returned NULL on a single contended lock attempt, causing amdgpu_dm_crtc_set_vblank (amdgpu_dm_crtc.c:370) to fail with -ENOMEM and triggering drm_vblank_put underflow warnings (drm_vblank.c:1271) when dm_arm_vblank_event_pre_programming (amdgpu_dm.c:10491) ignores drm_crtc_vblank_get's return value.

Add Heap::allocate_atomic_zeroed, which serves small size classes from the per-CPU cache when cores are tagged and otherwise waits on the heap spinlock with local interrupts masked, and wire stela-boot's Linux GPU heap callback to it.

Co-authored-by: Federico Bricca <177528604+Cheering19@users.noreply.github.com>
2026-11-27 13:15:47 +05:30
Garvit Surana 123c990507 merge fork/062-code-alias into fork/062-candidate2 2026-11-27 07:39:18 +00:00
Garvit Surana bca513e49a merge fork/062-fetch-path into fork/062-candidate2 2026-11-27 07:39:18 +00:00
Garvit Surana 72423c15c4 merge fork/062-download-reuse into fork/062-candidate2 2026-11-27 07:39:18 +00:00
Garvit Surana db8e4f0d6f merge fork/062-net-irq into fork/062-candidate2 2026-11-27 07:39:18 +00:00
Garvit Surana 36240b21be merge fork/062-ada-sph into fork/062-candidate2 2026-11-27 07:39:18 +00:00
Garvit Surana d53177c465 merge fork/062-download-reuse into fork/062-intel-test4 2026-11-27 07:37:20 +00:00
Garvit Surana 8a069854c1 merge fork/062-net-irq into fork/062-intel-test4 2026-11-27 07:37:20 +00:00
Garvit Surana 4503eba4d5 merge fork/062-candidate (0.6.2 candidate 1) into fork/062-intel-test4 2026-11-27 07:37:10 +00:00
Garvit Surana f810df7b64 feat(engine): with --share-aliases on, run one translation at every virtual alias of its physical code: a fetch the index misses at another address of an independent block's frame and variant takes an alias slot of its code (successors and fault rows moved to its page, in its owner's part list, no compile or install), each native call sets the page base, a run ending in shared code at another page base names that page's alias, shared code links only through its owner's record, within its page only into shared code and out of it only through relative lookup tails, an owner the index drops takes its aliases with it, and each beat logs PES SHARE ALIASES checks= mismatches=; the corpus at two slides compiles one copy with rows and exits moved, the replay installs 48% fewer blocks and 67% fewer again for 664 aliases a beat 2026-11-26 19:26:48 +00:00
Garvit Surana 8dfae49c49 feat(compiler): compile a system-mode block position independent when Options::with_position_independent asks (no region, no System or PAC terminal, which the engine completes through its own address), its direct exits relative ones that load the target from GuestState::page_base, a paired call only to its own page, and give the probes, jump cache, stamped tails and paired returns a sharing form that sets the page base to the target's page at every entry from another page, plus a relative lookup tail for shared code's exits out of its page and PackedRecovery::rebased; off, every tail and the tier-1 golden set are byte for byte as before 2026-11-26 19:26:48 +00:00
Garvit Surana 72e454c5df feat(boot-core): add --share-aliases on|off, off unless given, a hand-written opt-in like --tlbi-keep that the options revision leaves at 13, with its parse, duplicate and bad-value errors and its fork-line round trip 2026-11-26 19:26:48 +00:00
Garvit Surana c12c0e5079 merge fork/062-fetch-path into fork/062-code-alias 2026-11-26 18:29:51 +00:00
Garvit Surana 53890f73ad feat(compiler): emit a system-mode block position independent, each guest address it holds the page base native code runs at (GuestState::page_base, appended after every offset the ABI had) plus its offset from the block's page, by a MOV from the frame and a LEA that leave RFLAGS as MOVABS does: one copy then runs at every address its page is mapped at, a test running one copy at the shared cache's two slides 0xdf88000 apart and a third as the block compiled at each runs it (ADRP, ADR, BL's link, a conditional and a cross-page exit), where a block at each address held its own; an offset past 32 bits or code appended from another page leaves the block to the plain compile, and nothing installs such code yet 2026-11-26 18:28:32 +00:00
Garvit Surana d5ee7f8bef test(engine): group the replay's run number before its once bit, which clippy took for an unclear precedence 2026-11-26 18:28:32 +00:00
Garvit Surana ead114f77f style(engine): compile the variant-taking context and translate_leaf only for the tests that call them, now that fetches number their variant first, and format the fetch path's new code, where clippy refused both as dead code 2026-11-26 18:05:45 +00:00
Garvit Surana 2daadb1ed2 fix(setup): keep what create downloads in the per-user cache, an Offline installer's whole macOS image too when the computer has room for it with 16 GiB left over, reuse an image whose receipt names the same build and checksum though Apple moved it or listed another Mac for it, check and keep an image a stop left without its receipt, and say where each download is and why one was not reused, where every Offline create streamed all of macOS onto the stick again, an erase or a second stick downloading it anew, and a finished create removed the boot files it had downloaded
A tester's `stambha.exe create` downloaded the same file three times across runs without --ipsw. An Offline installer, the default on a stick of 32 GB or more, wrote the whole image straight onto the stick and kept none of it on the computer, so every create that erased the stick (the wizard always does) downloaded all of it again; its boot files went to images/setup and were downloaded again on every run, and a finished create removed that directory. A stopped create that goes on from its stick still streams, so the pieces on the stick are resumed rather than downloaded to the computer.

A stopped whole-image download already resumed by range; it now resumes too when the catalog entry lists more Macs for the same object, and says so. A stop between publishing the image and writing its receipt left an image that the next run refused; it is now checked against Apple's SHA-1 and kept. A receipt left beside an image removed by hand no longer blocks the download.
2026-11-26 18:02:35 +00:00
Garvit Surana d73a1fb7f2 fix(net): pass an Intel PCH adapter's state line on, which no adapter did, and give it the rings, the MAC's frame counts since the last line (good_tx among them), RCTL, TCTL, MANC and whether the station address is valid, and say an adapter that raises no receive signal is polled, where an I219 whose macOS sent 3473 lookups and its DHCP discovers for 37 minutes with no answer logged no adapter state, and every adapter but a virtio one logged "receive signal stays: no MSI-X entry for processor apic=..." for a processor the boot runs 2026-11-26 17:45:20 +00:00
Garvit Surana 3c86f415d8 test(engine): replay the Finder window with the shared cache at two slides, each address installed apart or both sharing one install: at 26 thousand hot copies (scaled a hundredfold) 64% of them pairs, as boot 35 of the 0.6.1 profile ran it, a 27 thousand block window installs 48% fewer blocks and 67% fewer again with one install per page, its hot runs finding their block 96% of the time where they found it 90% 2026-11-26 17:40:28 +00:00
Garvit Surana 8b970e33a9 perf(engine): keep a fetch's variant and its number while the memory checks, native System features, FP trap, SVCR.SM and timing tier they derive from hold, and give every page a fetch and its refills take the fetch's number in that page's guard unless a page set gives it a variant of its own, where each fetch built its variant anew and found its number by a whole-variant compare, and each page taken, its leaf's other pages and each refilled page compared their variant again (fetch_path_cost with 16 variants: 58 to 43 ns a fetch held by the table, 220 to 206 ns with a TLBI of everything every 840 fetches; tlbi_keep_cost refill 804 to 753 us a TLBI) 2026-11-26 17:29:58 +00:00
Garvit Surana f4d843273f perf(engine): keep the stored form of each block of a page installed at two addresses at once, at its first PC too, and none for a block only because the ring took it away, where those forms came back a tenured turn later, long after an 87 MiB bound had turned over, and pushed out the forms of pages two slides ran
On the laptop's profile boot the kept forms never relocated more installs
than those at a page offset another PC held (182-340 thousand forms kept a
heartbeat for blocks the ring took away), and in its Finder window only
11-20% of those alias installs relocated, 95% before it. A replay of the
window on the real ring, ghosts and kept forms keeps a third fewer forms and
relocates more; either way it relocates a few installs in a hundred once the
window turns over, so the window's own parts are what cut compiles there.
2026-11-26 17:23:44 +00:00
Garvit Surana cc863b243c perf(engine): cut the board's code window into 64 ring parts with young code a sixteenth of them, so the parts kept open, going and settling and the nursery leave their room to code the guest keeps running: a replay of a 16 GiB laptop's Finder window (hot code about the window's size, the shared cache at two slides) installs 37-40% fewer blocks again, where its tenured parts took back the hot code they held
The laptop's profile boot (8 PEs, 1280 MiB window, 2.7 million blocks)
installed 430-620 thousand blocks a heartbeat in its Finder window, 30-40%
of them blocks evicted within the last 10 s; 1093 of its sampled user pages
ran at two shared-cache slides 0xdf88000 apart, 64% of its user samples.
On the real ring, about 95% of a window-sized pool's re-installs come from
its own tenured "cold" retirements: every tenured part holds the same mix,
so the part entered least still holds hot code. A third generation for code
that came back from a tenured part made it 5-10% worse; finer parts and a
smaller nursery are what the replay rewards.
2026-11-26 17:23:44 +00:00
Garvit Surana acfc7c2c0e fix(gpu): check that the GPU sees what the CPU writes through a mapping of its own memory before a Metal device serves, and open an NVK device again with every allocation in system memory when it does not, where an RTX 4060 Laptop GPU on a Meteor Lake laptop read invalid program headers, illegal instructions and zeroed launch descriptors from what NVK wrote through its BAR and lost the device at WindowServer's first draw
On an MSI laptop with an RTX 4060 Laptop GPU (AD107, 8 GiB BAR1, GSP-RM
570.144, Meteor Lake host), every WindowServer start lost the device at
the first command buffer with a draw: nouveau logged Xid 13 "Shader
Program Header 11/18 Error" (ESR 0x405840 = 0xa0040800, 0xa2040800 or
0x82040000), a 0.6.0 boot "Illegal Instruction Encoding" on every SM at
one PC, and compute dispatches SKEDCHECK06_REGISTER_COUNT with
SKEDCHECK16_CTA_THREAD_DIMENSION_ZERO, which a launch descriptor of zeros
gives. Nothing was ever presented.

The fault dump showed valid SPH words and SASS as NAK wrote them, all
"upload=mapped": with a BAR as large as VRAM, NVK writes each shader
through a CPU mapping of the shader heap in VRAM, and command buffers
upload launch descriptors and constants the same way, while push buffers
live in system memory and ran. The pipeline store was ignored and
recompiled for this GPU, so no binary from another GPU was reused. The
same GPU with the same BAR and firmware draws on two other testers'
laptops. Everything the GPU read wrong is what the CPU wrote through the
BAR.

mapped_memory::check writes 64 KiB through a mapping of device-local
memory, has the copy engine copy it to mapped system memory and fill a
second 64 KiB, and compares both ways by 64-byte line, before the device
serves. One "GPU DRIVER mapped device memory: ..." line gives the lines
each side saw, the first differing word and how many unseen lines read
zero. When the GPU missed lines and the driver can place memory
elsewhere (Loader::system_memory, NVK only), the device is released and
opened again with NVK_DEBUG=gart, which the compat C library now answers
once stela_nvk_place_in_system_memory() is called, and checked again. A
driver that may hang runs its first submission before the check.
2026-11-26 17:11:07 +00:00
Garvit Surana 4d689f4a55 perf(engine): number a fetch's variant once through a four-entry memo per PE and keep each half's recent contexts by that number, where every fetch compared its variant field by field with each recent context of both halves and every take of a page searched the board's registry from its first variant, a few hundred bytes a compare (fetch_path_cost with 16 variants: 100 to 58 ns a fetch held by the table, 370 to 220 ns with a TLBI of everything every 840 fetches) 2026-11-26 17:09:54 +00:00
Garvit Surana 1c24f45121 fix(gpu): give ANV a system heap of all the RAM i915 reports (ANV_SYS_MEM_LIMIT=100), the integrated GPU's share the Metal device already budgets, where ANV kept half of a share of 4 GiB or less and a UHD 630's 1280 MiB heap, which the guest memory it imports counts in too, filled with Linux holding 1017 of 2560 MiB, every later allocation and import was refused and WindowServer died
aeosxii's test 2 boot (i5-10500, 16 GB, share 2560 MiB): "driver heaps
use/budget/size: 1275/1280/1280M" from 144 s on, 672 refused allocations
("GPU OUT OF MEMORY ... heap memory of 6291456 bytes failed"), every
newBufferWithBytesNoCopy of 40-64 MiB refused ("out of memory in an
import of 4082 ranges", answered to the guest as the kext not wiring the
memory, 0xe00002bd), and WindowServer's crash at 403 s. ANV's rule keeps
half of 4 GiB or less and three quarters above for the rest of a Linux
system; here that RAM is the share alone, held from the guest for the GPU,
and the dma-bufs of guest memory ANV imports count in its heap though
they take none of the share.
2026-11-26 10:29:44 +00:00
Garvit Surana 35f4fae9a8 fix(linux): give an i915 object's shmem pages in large folios, the largest naturally aligned block of up to 2 MiB inside the file that holds no cached page, cached at each of its indices, where every 4 KiB page was its own allocation, pin and DMA mapping and the first submission naming a new 64 MiB block took 350 to 900 ms
Test build 2's Intel logs (UHD 630, Iris Xe) put every slow commit
(`most=submit`, 320-941 ms, `GPU call 0x40406469 still running after 300
ms`) at the first use of new device memory: each came with the GPU's share
growing by one 64 MiB block (GPU SHARED MEMORY 90M, 166M, 232M, 306M at
105.4-107.4 s), and a 1x1 texture that opened a block bound in 430 ms. i915
fills an object's pages at its first execbuffer, one shmem_read_folio per
page, and each page went through the page catalog, the platform's
allocator and write-back check, a pin and a DMA mapping of its own.

shmem_read_folio_gfp now takes order 9 down to 4 when that block starts at
the page asked, lies inside the file and holds no cached page, and order
0 otherwise or when the large allocation fails (tried without reclaim).
i915's own loop and drm_gem take folios whole; a truncation drops a
folio it covers whole and zeroes the pages of one it covers in part;
writes and partial zeroing find their page inside the folio. The pages
come from the Linux page arenas, where runs of one size tile.

The file test's owner now names the slab's "nonblocking allocation with
no ready slot" notice instead of trapping on it (an xarray's first try at
a node, which then retries blocking): since the 0237 i915_active change
reports that notice, the test trapped before its shmem part. The test
page provider gives runs aligned to their size, as Linux's allocator does.
2026-11-26 10:29:44 +00:00
Garvit Surana 6a55519bc2 fix(boot): allocate nothing under the Linux page arenas' spin lock, growing their list and taking a new arena's block and bitmaps outside it, where a heap allocation under the lock could end a GPU job's slice there and leave every other processor asking Linux for a page spinning until the job ran again
The heap's allocation hook may suspend a job's slice at any allocation,
and the arenas' raw spin lock is not counted as a held lock. A new arena
now gets its bitmaps and its 32 MiB block first; the list grows by a
replacement allocated outside the lock and swapped in under it.
2026-11-26 10:29:44 +00:00
G-Nug85 ceff327af1 fix(boot): give Linux's page runs arenas where runs of one size tile, where an integrated GPU's 4 MiB TTM runs, each stranding almost its size behind its heap boundary tag, left 1.7 GiB free in no extent over 6 MiB
Linux's page allocator returns runs aligned to their size. From the heap
each was a block with its boundary tag just before the aligned payload, so
two runs of one size could never lie side by side. A ThinkPad T14 Gen 2
(Cezanne) whose TTM held 339 runs of 4 MiB had a 6400 MiB heap with 1.7 GiB
free in no extent larger than 6 MiB, 270 s into macOS's setup, and a 4 MiB
allocation of the Metal device failed.

Runs now come from 32 MiB arenas the heap gives whole, split by a buddy
allocator into runs of up to 4 MiB with no header between them; a freed run
joins its buddy, and a wholly free arena goes back to the heap but for one
kept. A run no arena can serve comes from the heap as before. HEAP OWNERS
reports the runs, the arenas' bytes and those fallbacks.

(cherry picked from commit d58e59c15ced2ddfc9939ff538ec9a3e5272f5af)
2026-11-26 09:36:38 +00:00
Garvit Surana 20ca03a343 merge fork/062-gpt-layout into fork/062-candidate (needs review and a Check-mode boot; revert this merge to drop it) 2026-11-26 09:35:13 +00:00
Garvit Surana 42f731bc8e fix(boot): time the step watchdog's limit by the time-stamp counter, the core cycle counter overflowing every 5 s of cycles at its rate and each overflow before the limit counting again for what is left of it from a returning NMI, so a step that never returns stops within half a second of 30 s on a core at or above its nominal clock, where the counter counted three limits' cycles at once and stopped after 45 to 90 s (65 s on an i5-10500) while saying 30 s 2026-11-26 09:34:58 +00:00
Garvit Surana ee377c3167 test(net): an address and gateway set by hand with no --dns ask the public resolvers 1.1.1.1 and 9.9.9.9 and the log says so, and one without a gateway keeps its plain failure, pinning the case where a tester's I219 install set up with stambha settings --ipv4 ... --ipv4-gateway ... stopped on 0.6.1 with Dns("updates-http.cdn-apple.com: Failed") 2026-11-26 09:34:58 +00:00
Garvit Surana 3ba1dc2226 merge fork/062-network-fixes into fork/062-candidate 2026-11-26 09:24:26 +00:00
Garvit Surana 806dbaca42 merge fork/062-input-latency into fork/062-candidate 2026-11-26 09:23:29 +00:00
Garvit Surana 739a6fdd12 merge fork/062-i2c-bar into fork/062-candidate 2026-11-26 09:23:29 +00:00
Garvit Surana 55293cebee merge fork/062-hang-visibility into fork/062-candidate 2026-11-26 09:23:29 +00:00
Garvit Surana cc1438bfd1 merge fork/062-gpu-loss into fork/062-candidate 2026-11-26 09:23:29 +00:00
Garvit Surana 642273be85 merge fork/062-gpu-firmware-read into fork/062-candidate 2026-11-26 09:23:29 +00:00
Garvit Surana 5c9ee89f1f merge fork/062-gpt-zero-disk into fork/062-candidate 2026-11-26 09:23:28 +00:00
Garvit Surana f374b06c50 merge fork/062-adapter-choice into fork/062-candidate 2026-11-26 09:23:28 +00:00
Garvit Surana bb44df447e merge fork/062-input-latency into fork/062-intel-test3 2026-11-26 09:16:41 +00:00
Garvit Surana c40a24b2a9 merge fork/062-i2c-bar into fork/062-intel-test3 2026-11-26 09:16:41 +00:00
Garvit Surana be12849cc6 merge fork/062-igpu-memory into fork/062-intel-test3 2026-11-26 09:16:41 +00:00
Garvit Surana e07cbe98e9 fix(input): poll a moving touchpad at its report rate and wait for the host drivers' lock once a poll is 2 ms late, after the GPU pump's step, where reads that delivered input counted as look cost and held an I2C touchpad to one read every 32 ms (TRACKPAD rate 24-31 Hz) and a busy lock was waited for only 32 ms late; INPUT TIMES adds each device's late= and gap= p50+p95+max 2026-11-25 20:04:09 +00:00
Garvit Surana c76aa50a3a fix(drivers): place an Intel LPSS I2C controller's BAR the firmware left at zero before mapping it, from the PCI census's BARs and windows, the memory map, the namespace's _CRS memory and the mount's reservations, write it with decoding off, check it reads back and log where it went, where a Dell's touchpad controller at \_SB_.PC00.I2C1 stayed unmapped and its touchpad dead 2026-11-25 19:08:06 +00:00
Garvit Surana fca87f2403 feat(pci): place a memory BAR the firmware left at zero in the lowest free aligned span of its root bridge's _CRS windows and the bridges above it, clear of every claimed range, with an assigned BAR bounded by its alignment and never moved, _CRS and DMAR, IVRS, MCFG, APIC and HPET memory read as claims, and any doubt a refusal, where nothing could place one 2026-11-25 19:08:06 +00:00
Garvit Surana 8ee5d90192 fix(gpu): read single-sample framebuffers without multisampled storage images, refusing only multisampled framebuffer reads and tile pipelines and making no multisampled texture storage there, and leave a Metal device still in no Apple GPU family unused as AMD's GFX8 is, where ANV, which has no multisampled storage images on any Intel GPU, put the Metal device in no Apple GPU family, Core Animation drew no desktop (a black screen under the cursor) and WindowServer ended at its first InPlaceSover pipeline 2026-11-25 18:30:23 +00:00
Garvit Surana 3ff9b16d94 fix(network): give macOS's network only a host adapter with a usable station address, driving a Wi-Fi chip up to 10 s for its own, count a saved Wi-Fi network as configured when choosing it, and place no USB Ethernet adapter for an address that is not unicast, where a laptop with no cable and an Intel AX200 stopped at "Setting up the Mac's hardware" with "the USB Ethernet address must be a unicast address"
The guest network chose the AX200 because a Wi-Fi network was set, before
its firmware had read the address from its NVM, so the guest's USB Ethernet
adapter got all zeros and placing the board failed. The chosen Wi-Fi chip's
link is now polled until it names its address; an adapter that has none
then is put back and the next one is chosen, and with none left macOS
starts without a network. The board also places no USB Ethernet adapter
for an address that is not a usable unicast one instead of stopping.

With saved networks and no --wifi, the guest took the first adapter, an
Ethernet port with no cable, and macOS had no network although the boot
menu had joined Wi-Fi; a saved network now counts as configured.
2026-11-25 17:29:59 +00:00
Garvit Surana 9a0bc0b532 fix(net): ask the public resolvers 1.1.1.1 and 9.9.9.9 (2606:4700:4700::1111 and 2620:fe::fe over IPv6 alone) when the network names no DNS server or its servers give no address and no --dns is set, say whether a failed lookup's server never replied or answered SERVFAIL, NXDOMAIN or REFUSED, wait out DHCPv4 before taking IPv6 alone without a DNS server or with only a 6to4 or Teredo address, prefer IPv4 to those, and log the DHCPv4 exchange of an adapter taken on IPv6 alone, where two I219 online installs died with Dns(... Failed) or "no DNS server from DHCPv4 or IPv6 router advertisements" after 8 to 13 minutes of silent retries
The fallback is a resolver of its own beside the network's, since smoltcp
keeps at most three servers in one. It is asked once per lookup, after
the network's servers (or the 15 s wait for one) and the AAAA-then-A
retry, and each use is noted ("asking the public resolvers ... instead",
"resolved by the public resolver ..."). A --dns setting is never replaced.

smoltcp's Failed is the same for a server that never answered, one that
answered with an error code or no address, and a reply from an address it
did not ask. The stack now reads DNS replies off the wire beside it and a
failure says which: "no reply from 192.168.137.1 in 10 s to the A query",
"10.0.2.3 answered SERVFAIL with 0 answer records and no A address", or a
reply that came from another address and was dropped. The no-server text
stays as it was where no public resolver is reachable.

The address wait took a 2002:: (6to4) address that passed DAD 37 s in, with
no DNS server, and never waited for the DHCPv4 lease. IPv6 alone is now
taken at once only with a native global address and a DNS server; else at
the end of the 60 s DHCPv4 wait. Lookups ask A before AAAA when the only
global IPv6 address is 6to4 or Teredo (RFC 6724 ranks them below IPv4).
2026-11-25 17:29:59 +00:00
G-Nug85 be32514663 fix(input): drain a PS/2 touchpad's observation queues on the host's poll and deliver its TrackPoint, where 32 Synaptics packets stopped the i8042 reading its keyboard and touchpad (#11)
The host polled the i8042 with poll(), which leaves a Synaptics engine's
raw frames, advanced-gesture and pass-through records, and its pass-through
pointer's input, queued for poll_synaptics. Nothing drained them, and a
full queue backpressures the controller, which then reads neither port: a
ThinkPad T14 Gen 2's keyboard, touchpad and TrackPoint went silent at the
touchpad's 32nd packet (192 bytes), before macOS had finished loading.

poll_host drops the observation records, adds the TrackPoint's motion,
buttons and horizontal scroll to the controller's input, and drops an
Elantech engine's raw frames the same way. The host's PS/2 device polls
with it.

Porting onto Stambha 0.6.1: its own byte counters replace the traffic
ones this used, which their commits had added.
2026-11-25 22:43:33 +05:30
Garvit Surana dc52f0f6c2 fix(gpu): end the session once a lost GPU's driver said it stopped answering, without waiting for a reopen to fail, where a client that kept 82 MB of the lost device kept every reopen from being tried and WindowServer was refused for 10 minutes until macOS's watchdog panicked
The session ended only from watch_losses(), which ran only after a
reopen failed, and a reopen runs only once no connection holds an
object of the lost device. On a Yoga Slim 7 Pro whose RTX 3050 left
the bus, one client held two objects to the end, so no reopen was
tried. A kernel driver's line that its GPU stopped answering, after
which no reopen can work, now has the next pump look, and a lost GPU
with such a line counts as gone with no reopen tried; until its device
is lost too, each pump looks again. The stop is the one a boot without
a GPU makes, "The graphics card stopped working", with the driver's
line. A GPU its driver said nothing of still ends the session only
after its reopens failed over REOPEN_SPAN_MS.
2026-11-25 16:44:11 +00:00
Garvit Surana 36a06c6360 fix(linux): jiffies follow each clock read and udelay(), so a task spinning on a jiffies bound sees its time pass and returns within its step, where jiffies moved only in a service pass or when a task resumed and such a spin never ended
A Linux task that waits on a jiffies bound without blocking, as a
driver's busy wait does, held jiffies still for its whole step: they
moved only in a service pass (service.c) and in finish_prepared() when
a task resumed. Nouveau's busy fence wait at a stop after its GPU left
the bus spun until the 30 s step watchdog. ktime_get() now brings
jiffies forward to each sample it reads, and udelay(), ndelay() and
__const_udelay() bring them up to the clock after each delay, as
Linux's tick would have during the spin. cpu_relax() is left as it is:
stela_linux_enter() also waits with it on a context that runs no Linux
code, which cannot tell that it holds the entry. A loop that polls
jiffies alone, reading neither the clock nor a delay, still waits on
them (nouveau's gf100_gr_wait_idle() and nvkm_falcon_cmdq_write(), off
the GSP path).

The jiffies test spins on a jiffies bound reading a clock that moves
only when read, and fails at its read limit without the clock's
refresh. A hosted fixture spins a Linux task on two jiffies bounds,
through udelay() and then through clock reads only, and must return
within its step; the hosted runtime needs a kernel that answers
ARCH_SHSTK_STATUS, so it runs on such hosts.
2026-11-25 16:44:11 +00:00
Garvit Surana 68da5075ce fix(nouveau): bound a busy fence wait by the clock and look whether its GPU still answers each 10 ms of it, where a channel idle on a GPU off the bus spun until the step watchdog stopped it, as neither its 15 s timeout nor its once-a-tick look ever came due on jiffies that did not move
nouveau_fence_wait_busy() never blocks, and on Stela's Linux layer
jiffies move only when a task resumes or a service pass runs, so its
jiffies timeout and patch 0218's "once a tick" nvkm_device_gone() look
never fired inside one step. At a stop after an RTX 3050 Mobile left
the bus, nouveau_drm_shutdown() idled each channel through this wait
and the step watchdog ended it after 30 s, losing the end of the boot
log. The wait now also ends once what was left of the fence's timeout
has passed by ktime_get(), and looks at the device at once and then
each NOUVEAU_FENCE_GONE_MS of that clock, as r535_gsp_gone() does.
2026-11-25 16:44:10 +00:00
Garvit Surana 6408108f24 fix(installer): offer free space only in the blocks a disk's GPT headers give partitions, where the picker offered the geometry's and a header that names fewer made a plan the check refuses 2026-11-25 16:11:18 +00:00
Garvit Surana 28fcdecbd6 fix(install): keep the disk's own GPT headers in a rewrite, but for their two checksums, accept any usable range inside the one a rewrite would lay out, name the field and its values when a header is refused, and refuse a disk whose partitions overlap, where a GPT Linux's fdisk made, its usable blocks from 1 MiB, was refused at Check on both of a tester's disks 2026-11-25 16:11:18 +00:00
Garvit Surana 5afea7c236 fix(boot): say the USB lacks a GPU's firmware file that the bundle's manifest names and its volume does not have, and that stambha repair writes it again, where the screen said the USB held the firmware and reading it failed
A Dell laptop with an RTX 3060 (10de:2560, ga106) stopped at "macOS cannot
run without a GPU" on every normal boot. Its stick's bundle manifest named
98 files and the volume held none of them: every selected file logged "the
bundle names a missing file" and the bundle line read used=0 bytes=0. The
boot recorded those files as failed reads, so the GPU was refused with "the
USB holds the GPU's firmware, but reading it before the firmware's exit
failed", which pointed at the PC and the GPU rather than at the stick.

A file the manifest names and the volume lacks is now its own state,
Held::Missing, recorded as 'm' in the handoff record. Absent::of counts it
with the files the manifest leaves out, so the GPU is refused with the
missing-firmware reason, whose screen line already tells the user to plug
the USB into another computer and run `stambha repair`. The LACKS line for
such a file and the GPU's own log line name `stambha repair` too.
2026-11-25 16:00:45 +00:00
Garvit Surana 335f4ea6d6 fix(gpu): take i915's EINVAL to Mesa's empty userptr object as the answer to its probe, where every Intel boot logged I915_GEM_USERPTR as refused 2026-11-25 15:46:24 +00:00
Garvit Surana 32dc3ddebe fix(loader): select a discovered AMD GPU's files by the block versions amdgpu takes, DCN 4.0.1 for a table's 4.1.0, where Navi 48 (RX 9070 and 9070 XT) and Navi 44 got no dcn_4_0_1_dmcub.bin, their display block failed early_init with -19 and amdgpu started no GPU 2026-11-25 15:46:24 +00:00
Garvit Surana 71eb800ff8 fix(gpu): cap each image array of the Metal descriptor heap at 4,194,304 descriptors, texel buffers included, where ANV on Gen9 to Gen12.0 Intel GPUs reported 201 million images, the heap's one pool asked for 203 million descriptors (9.1 GiB of host memory) and Metal could not open with OutOfMemory 2026-11-25 15:46:24 +00:00
Garvit Surana dc2355fcf7 fix(gpu): take an i915_active node before its IRQs-off lock (Linux patch 0237), hand the engine the earlier boot's GuC record, start Alder and Raptor Lake P without the GuC unless --i915-guc on, and turn off panel self refresh and framebuffer compression, where every Mesa submission failed with -ENOMEM, the GuC fallback never ran and the stop never reached the panel
dev64-2, a second test build for the Raptor Lake P tester (8086:a7a0).

dev64-1's GuC started, then each of ANV's first EXECBUFFER2 calls failed
with -ENOMEM, 80 times over Mesa's 16.7 s retry budget (100 us times the
retry squared), and ANV reported VK_ERROR_DEVICE_LOST: no hang check, no
completed request. eb_move_to_gpu's _i915_vma_move_to_active reaches
i915_active_add_request, whose active_instance takes a new node with
GFP_ATOMIC under the tree's IRQs-off lock. Stela's slab serves a
nonblocking request only from a slot it holds ready and never grows a
cache for one, and the only blocking allocation from i915's active_node
cache, a barrier's preallocation, is skipped under GuC submission
(intel_context_active_acquire), so the cache never had a slot. Ashu's
a7ab failed the same way. Execlists would only have grown the few slots
its barriers take, short of an execbuf naming many buffers. Patch 0237
takes the node with GFP_KERNEL before the lock where the caller may
sleep, and says where an execbuf fails, its first passes and the first
user requests that complete. Stela's slab now says, once a cache, a
nonblocking allocation it finds no slot for and a growth with no backing.

The record dev64-1's boot 22 wrote was read by the loader in boot 23, but
the engine runs a copy of the image taken before any static was set, so
its log_file::earlier_guc was empty and the GuC started again. The record
now goes to the engine in the handoff, as serial_present does, and the
loader says the record it read. A test reads the record from boot 22's
own bytes.

On Alder Lake P (Raptor Lake P and U, Alder Lake N), --i915-guc auto, the
default, now starts i915 with enable_guc=0 ("INTEL GUC off (dev64-2)"),
so one boot tests execlists; --i915-guc on asks for the GuC and still
falls back the boot after a failure. Records of dev64-1 are passed over.

The stop's reason never showed: after i915 took the eDP panel the console
drew its front buffer with the CPU and sent no DIRTYFB, which panel self
refresh and framebuffer compression need to show a write. i915 and xe
now start with enable_psr, enable_panel_replay and enable_fbc 0.

--i915-guc is a hand-written override setup never writes, so the options
revision stays 13; the bundle revision stays 39 and the translator id is
unchanged.
2026-11-24 21:19:52 +00:00
Garvit Surana fa26324bb5 fix(gpu): wait up to 250 ms for the work in flight to retire before refusing an allocation as out of memory, and note each save, where memory released behind ten command buffers stayed counted and a WindowServer commit was refused
When freeing recycled textures and free upload chunks is not enough, the
Metal device waits on its timeline for the newest command buffer the GPU
was given whole (held work is never waited for), retires what finished,
frees again and retries. The share's and a test build's caps still refuse
what they would not hold. A saved allocation leaves an
"OUT OF MEMORY AVERTED n" note at the first and each power of two.
2026-11-24 20:11:28 +00:00
Garvit Surana 67f10affed fix(memory): give an integrated GPU a quarter of the free RAM, where a sixth left a 16 GB PC with a 512 MiB carve-out on the 2.5 GiB floor and its Metal device 1534 MiB, which Setup's Liquid Glass UI ran out of and WindowServer died with
A 16 GB Renoir laptop (14842 MiB free) now gets a 3710 MiB share and tells
Metal 2398 MiB; a nominal 16 GiB host 3968 / 2592. The share comes out of
the heap's growth past its floor while the guest keeps its 6 GiB room;
12 GB hosts grow by 150-400 MiB and 8 GB hosts, whose share is what the
guest's floor leaves, are unchanged, as is the 7 GB minimum.
2026-11-24 20:11:27 +00:00
Garvit Surana 8627d52bfc fix(network): move macOS's network to a started wired adapter whose link held while its own has none, record a wired network only once its link held for 10 s, and give the AX88179/178A a state line, where 0.6.0 kept the adapter chosen at the start for the whole boot and a 107 ms link closed the next boot's Wi-Fi page
The guest network chose its host adapter once, from one carrier read, and
kept it with or without a link. The other wired adapters were stopped.
Now every started wired adapter whose driver writes its station address
(the RTL8168 family's MAC0/MAC4 as rtl_set_mac_address does, the
AX88179/178A's node ID as ax88179_set_mac_addr does) stays started as a
spare. Once the guest's adapter has had no carrier for 2 s and a spare's
link has held for 1 s, the spare takes the guest's station address and
the guest's network, and the old adapter becomes a spare
(network_link::guest_switch).

The Wired record for the next boot's menu now needs the link to have held
for 10 s. A 0.6.0 log of an IdeaPad Gaming 3 had its broken RTL8168G
port up for 410 ms and then 5.6 s, and its AX88179A up for 107 ms. 0.6.1
would record each of those as a wired network and close the Wi-Fi page.

The USB vendor Ethernet link now has a Link::diagnostic line, made from
state it already keeps: the work under way, whether a failure closed the
link and which failure, the carrier, checks, losses and the last PHY
status. In that log the AX88179A's link went down 107 ms after it came up
and never came back, and nothing said why.
2026-11-24 19:32:01 +00:00
Garvit Surana c571085f29 fix(gpu): take an i915 context's guc_id before submission_state's lock (Linux patch 0236), and start i915 without its GuC the boot after one whose GuC failed, or with --i915-guc off, where Raptor Lake P's GuC submission enable failed with -EAGAIN and left a wedged GT and no Metal device
A test build for one Raptor Lake P tester (Iris Xe 8086:a7a0). Its 0.6.1
boot logged "LINUX unsupported: cache allocation policy or context", then
"GT0: GuC initialization failed -11": new_guc_id's ida_alloc_range with
GFP_KERNEL under submission_state's IRQs-off spinlock needed a new IDA
bitmap and xarray node, the slab refused a blocking request there, and
steal_guc_id's -EAGAIN failed guc_init_submission on each of pin_guc_id's
four tries. Patch 0236 reserves the guc_id before the lock, where
pin_guc_id may sleep.

Any other GuC failure falls back by itself. i915 cannot be unbound and
probed again in the same boot (its unload is never run, and a failed
probe's IRQ line is retired), so the boot writes one record line,
"INTEL GUC RECORD failed device=XXXX cause=... build=dev64-1", the moment
i915 prints a GuC error (its start, a wedged GT, a CT error) or, at the
stop for want of a Metal device, as the Metal device's; and that stop
says "Intel graphics needs a second start; restart the PC". The next
boot reads the record back from the log as the Wi-Fi page's record is
read, and for the same device on Alder Lake P (Raptor Lake P and U,
Alder Lake N), Raptor Lake S or DG1 adds i915.enable_guc=0 (execlists,
host RPS and RC6), writing a kept-off record so the boots after it stay
without the GuC. A record of another device or build is passed over.
Each boot with such a GPU prints one INTEL GUC on, off or fallback line.

--i915-guc auto|off, auto unless given, is a hand-written override that
setup never writes, so the options revision stays 13; the bundle
revision stays 39 and no fingerprinted engine file changes.
2026-11-24 19:06:54 +00:00
Garvit Surana 20464bd756 fix(install): open a remote install image under its own step that stores the log at each wait and failure, give up before the guest after two minutes without a byte or six failed tries with a plain reason, and keep the boot processor's step watchdog on until the machine starts, where a tester's Ethernet install sat after "Setting up the Mac's hardware" for ten minutes with nothing on the screen or in the log
A Ryzen 5600X with an RTL8111H (XID 541) got its DHCP lease in 2 s and
logged the IPSW's REMOTE IMAGE line, then nothing: no RESTORE PROXY
wiring, no range line, no installer. The reads before the guest
(Store::open and prepare in Experiment::new) had no time limit and the
install's 20-try budget (about a quarter of an hour), nothing stored the
log between "Setting up the Mac's hardware" and "Starting the macOS
installer", and nothing watched: the other processors look at the boot
processor's steps only between guest slices.

- Ranges::before_guest: reads before the first bound give up after
  QUIET_BEFORE_GUEST_MS (120 s) without a byte, ATTEMPTS_BEFORE_GUEST (6)
  failed tries at one range, or a refusal no try mends, and keep the
  reason (GaveUp). A slow server that keeps sending is waited for. The
  first bound (the guest's restore host) restores the 20-try budget.
- RangeSource::waiting hears each wait before the guest; Waiting::screen
  is the step's line ("try 3/6 in 4 s, no data for 45 s").
- Each range's end is logged with its HTTP status, bytes, first byte and
  open time; a response that is not the partial range names its status.
- stela.efi: "Opening the macOS install image from Apple" is its own step.
  Before the guest each wait stores the logs when due (flush_due), each
  range line and failure stores them at once with the adapter's frame
  counts and state line (resyncs=/skipped= on a Realtek), and every 10 s
  of silence logs them. A give-up stops with "Couldn't download macOS from
  Apple: no data for 2 minutes. Check the network, or put the install
  files on the USB with stambha." and the technical error in the log.
- step_watchdog: the boot processor's counter is retired when the machine
  starts instead of when the other processors start (they stay parked and
  look at nothing before), and the image's reads run in a watched segment
  whose waits report progress, so a call that never returns stops the
  boot with a named stage. The boot processor still stops running alone
  (its dispatcher halts while idle) where it did.

The translator id, options revision 13 and bundle revision 39 are
unchanged.
2026-11-24 19:01:23 +00:00
Garvit Surana a3cff24c1e fix(installer): show a disk that reports no size, or too few blocks for a GPT, as refused and never lay out a GPT on it, and make the GPT geometry total, where a 0-byte UFS logical unit divided by zero in Disk::entry_blocks when the picker drew it
The disk picker drew every listed disk's bar through segments_of, which took
first_usable and last_usable of the firmware's geometry. A Lenovo 500w Gen 5's
second UFS logical unit reported 0 bytes, so ENTRY_ARRAY_BYTES.div_ceil(0)
stopped stela.efi with "attempt to divide by zero" at gpt.rs:205 as soon as
Install macOS opened. last_usable also underflowed on a disk of fewer blocks
than a GPT takes.

gpt::Disk now has Disk::new, which accepts only a geometry the reader and
encoder accept, and usable(), which gives the usable range or None for a disk
that reports no size or is too small for a GPT. entry_blocks and last_usable
no longer panic on any geometry; for one that holds a GPT they are unchanged.

The picker reads no GPT on such a disk, draws it without segments, and
refuses it first: "Reports no size" for a block size of 0 or no blocks, "Too
small for a partition table" for fewer blocks than both GPT copies take
(chosen_disk::size_refusal). A firmware's last_block of u64::MAX counts as no
blocks instead of overflowing, and bytes() and mib_blocks() are checked.
Valid disks are listed, read and refused exactly as before.
2026-11-24 18:59:41 +00:00
Garvit Surana ed327327a8 merge release/0.6.1 into release/0.6.1-gpu-experimental 2026-11-24 16:19:08 +00:00
Garvit Surana 91f17ce6d3 merge fork/061-nvidia-render into release/0.6.1 2026-11-24 16:19:07 +00:00
Garvit Surana f3229446a9 fix(gpu): a command buffer marks each IOSurface it names in use until it completes, as Apple's GPU driver does, where a video decoder's pool reused a frame whose sampling command buffer the service had yet to run and the lock screen's aerial wallpaper showed green, stair-stepped blocks of rows not yet decoded
With no hardware video decoder, VideoToolbox decodes on the CPU into a
CVPixelBufferPool, which reuses only a surface that is not in use
(IOSurfaceIsInUse). The guest driver never marked a surface in use, so
the pool handed a frame back to the decoder as soon as WindowServer
committed the command buffer that sampled it; the service then copied the
4K 10-bit frame into device memory while the decoder rewrote it: zero
luma and chroma below the decoder's wavefront, green in YCbCr, for a frame
(rnz, RTX 5070 Laptop; reproducible on the ASUS TUF A16).

The commit now increments the use count of every IOSurface the command
buffer names, once a surface, and its completion or refusal decrements
them before anyone learns it completed.

Each distinct two-plane IOSurface texture is named once in the log
(GPU TWO-PLANE TEXTURE): format, size, usage, the surface's pixel format,
each plane's offset, row, extent and format, and whether the GPU samples a
device copy or the rows in place. Tests cover the note and the device copy
of a 3840x2160 10-bit 4:2:0 frame's two planes.
2026-11-24 16:17:54 +00:00
Garvit Surana 53c5ab12ac merge fork/061-navi3x into release/0.6.1-gpu-experimental 2026-11-24 14:58:32 +00:00
Garvit Surana 21ec0f8b73 feat(amdgpu): log the link masks the SMU's PCIe override is made from, what they give it, and each forced level's table values, argument and answer on SMU 13.0.0 and 13.0.7, where a refused override left no line saying whether it was asked for lane 0
New Linux patch 0235, under CONFIG_STELA, in smu_smc_hw_setup and in
smu_v13_0_0/smu_v13_0_7_update_pcie_parameters' force-all-levels loop.
2026-11-24 14:57:31 +00:00
Garvit Surana 5f9ff439bb merge origin/fork/061-intel-igpu into release/0.6.1-gpu-experimental 2026-11-24 14:34:39 +00:00
Garvit Surana 2a5402d8bf merge release/0.6.1 into release/0.6.1-gpu-experimental 2026-11-24 14:34:39 +00:00
Garvit Surana 12264e7dd4 fix(gpu): give amdgpu a discrete AMD GPU's slot link on Linux's command line on an Intel host, as amdgpu.pcie_gen_cap and amdgpu.pcie_lane_cap masks of the trained link between its card's switch and the root port from the port snapshots the claim holds, else its own link, never a width of 0, where an RX 7900 XTX's SMU refused OverridePcieParameters (0xFF, -EIO) and its probe failed at "Attempt to override pcie params failed!"
amdgpu_device_get_pcie_info takes both module parameters before it reads
any link, for every generation, so the SMU's forced link levels come from
Stambha's own read of the link amdgpu would read on Linux
(amdgpu::link::slot: its link_dev past the card's 1478/1479 switch and
its link_partner). gen 4 x16 gives 0xf000f and 0x3f003f, and the SMU
argument 0x0306 native Linux sends. Nothing is given for an integrated
GPU, another vendor's, one whose link does not read, or on an AMD host,
whose PCIe DPM keeps the SMU's own levels. Two AMD GPUs' masks keep the
bits both set (command_line::add). One line names the link and masks.
2026-11-24 14:31:06 +00:00
Garvit Surana 34f983aed8 merge fork/061-r8169 into release/0.6.1 2026-11-24 13:57:26 +00:00
Garvit Surana a5235bfb9a merge fork/061-r8169 into release/0.6.1 2026-11-24 13:57:26 +00:00
Garvit Surana b5ab1c9a33 merge fork/061-fixes (Wi-Fi page) into release/0.6.1 2026-11-24 12:57:25 +00:00
Garvit Surana 735ba9579f merge fork/061-fixes (Wi-Fi page) into release/0.6.1 2026-11-24 12:57:25 +00:00
Garvit Surana fb31457e3e feat(boot): open the Wi-Fi page by itself before the menu when a supported chip has no network, or on the network the earlier boot could not join with its password ready, and never on a boot nobody may be at
The guest network records each join's outcome and a wired link coming up
as "WIFI RECORD" lines that name a network only as configured (--wifi) or
saved-N, its place in wifi.saved. Before the menu, the next boot reads the
earlier boot from the bytes log_file already reads back for the
device-start record, and wifi_prompt::decide opens the page:
- with no network set up: "Connect to Wi-Fi so macOS has internet. Esc:
  start without Wi-Fi.";
- after a failed join: that network selected, its dialog on the password,
  and "Couldn't join <name>: the password may be wrong..." or "<name> isn't
  in range..."; the name is shown, never logged.
Esc skips Wi-Fi for this boot; a network saved there starts the boot.

It stays closed, and the boot goes on as before, after a restart macOS
asked for (the installer's and an update's restarts, any boot an install
chains into), after a stop or a boot that never ended, after a boot whose
wired network was up or that joined Wi-Fi, on a menu that holds for setup
or opens no menu, when the log could not be read, and on a PC whose chip
the driver does not start. A console with no input leaves it at once. A
join, or a network saved or forgotten at the menu, clears the failure.

With no --wifi, the boot now joins the saved networks, the newest first,
and the loader reads wifi.saved without --wifi, so a network saved on the
page is joined; choosing one moves it last in the file. The --wifi
network's password typed again goes to its key file. No option, the
options revision (13), the bundle revision (39) or the translator id
changes.
2026-11-24 12:56:53 +00:00
Garvit Surana f2c5c76cf9 feat(wifi): give what a Wi-Fi join came to through Link::take_join, once per change: joined, the password may be wrong, or not in range
The keeper notes a join as Joined when its port opens (an open network's
association or the 4-way handshake), WrongPassword when the handshake fails
or times out (wpa_supplicant's WRONG_KEY), and NotInRange when a scan finds
neither the preferred network nor any saved one. Each change is given once;
the network's name stays in memory for the boot to place, never in a log
line. The probe's adapters forward it for the Intel, MediaTek, Realtek and
rtw89 stations; a wired link gives none.
2026-11-24 12:56:53 +00:00
Garvit Surana 28b5c41055 fix(net): a Realtek receive ring follows a chip that passed the driver's slot, and an unanswered guest DHCP window logs the host adapter's state, where an RTL8168H (XID 541) that skipped one slot held every frame a full ring of 256 and the guest got no DHCP or ARP answer
The tester's 0.6.0 boot (Ryzen 7800X3D, B650, 10ec:8168 rev 15) got
its frames in runs of exactly 256 (to_guest 172, 428, 684, ... 2476),
where a working adapter's count grows unevenly. The driver waited on a
slot the chip had skipped while the chip wrote the other 255, so each
frame was released a full ring late, past macOS's DHCP and ARP timeouts.

Ring::follow_the_chip moves the driver's slot to the chip's first
completed slot past it at the second empty look that sees the same
pair; the skipped slots stay offered. Linux's layout, RxMaxSize 16384
and RX_MULTI_EN from 0.6.0 are kept. The diagnostic line gains
resyncs= and skipped=.
2026-11-24 12:56:26 +00:00
Garvit Surana 510daf2edc fix(linux): pass over a device whose link status names no lanes or no known speed in pcie_bandwidth_available, where a root port snapshot that read 0 won Linux's comparison as the last link and amdgpu took the slot as x0 at an unknown speed, which an RX 7900 XTX's SMU refuses as lane 0
test_upstream gains a Navi card whose root port reads 0, which now gives
the card's upstream port's gen 3 x8, and a GPU whose every link reads 0,
which gives no bandwidth with speed and width unknown rather than x0.
2026-11-24 12:40:43 +00:00
Garvit Surana a0afe2aebd merge fork/061-fixes into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana 2388d70afd merge fork/061-fixes into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana 758aac5c88 merge fork/061-cursor into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana 3e16314649 merge fork/061-cursor into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana fe950b2eab merge fork/061-sleep-amd into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana 6b59da131c merge fork/061-sleep-amd into release/0.6.1 2026-11-24 12:34:58 +00:00
Garvit Surana 6ed8ad8747 feat(boot): let W open a page saying the PC's Wi-Fi chip isn't supported yet, or that it has none, with "Wi-Fi: this chip isn't supported yet (press W)" on the menu, and let W open the Wi-Fi page on a USB with no network yet
On a PC whose census finds a Wi-Fi chip no driver here starts, the menu
showed no Wi-Fi line and W did nothing. Its bottom line now says
"Wi-Fi: this chip isn't supported yet (press W)", and W opens a page naming
the chip by vendor and PCI ID, saying to use Ethernet, a USB tether or a
supported card, and to post the log in hardware-reports to ask for it. With
no Wi-Fi chip at all, W opens a page saying so and the bottom line stays
clear. Every line of the page is at most 40 characters, inside the column.

W also opened the Wi-Fi page only with a --wifi entry or a wifi.saved file,
so on a USB with neither, the "press W to choose a network" line of
a95ddeb98 pointed at a key that did nothing. W now opens it whenever the
page is offered; a network saved there joins as before.
2026-11-24 12:29:12 +00:00
Garvit Surana 43b32e1a94 fix(gpu): read an AMD GPU's IP discovery table by its BAR's address when the firmware describes the BAR without a memory range, and count an AMD GPU whose table still is not read as discrete when it sits below its card's own PCIe switch (1002:1479 below 1002:1478), where an RX 7900 XTX whose board firmware answered GetBarAttributes(5) with no memory descriptor was taken as integrated and given a 5104M share of the host's RAM
amd_graphics_version returned at once when the description held no
memory range, so the by-address read added for firmware that does not
describe the BAR never ran. The decision is now
amd_discovery::described_registers, whose error falls through to that
read. Where the read still fails, gpu_kind looks at the bridges the
firmware lists: an APU sits straight below a host bridge or root port,
never below Navi's own switch.
2026-11-24 12:23:29 +00:00
Garvit Surana efc082e0d1 fix(gpu): a request on an IRQ line its previous driver freed is refused as unexposed, before any route, event or source, so xe's probe after a failed i915 probe on the same MSI line fails cleanly with -EOPNOTSUPP, where the refusal was classed as retained and stopped the boot with "IRQ enable uncertain; published request retained"
The retired line's owners stay with it and nothing of the new request is
published, as for the other refusals before a route in irq_enable. The
software IRQ peer of the workqueue fixture now keeps a freed line retired
on request, and the fixture checks that the next driver's request_irq on
it returns -EOPNOTSUPP with nothing enabled. MSI still has no fresh line
past a retired one, as MSI-X has, so xe cannot yet take over the interrupt
after i915 fails; that is left for later.
2026-11-24 12:22:41 +00:00
Garvit Surana e40d1d26b9 fix(linux): a kmem_cache request carrying __GFP_RETRY_MAYFAIL is served, its growth one fallible attempt as kmalloc's and the page allocator's policies already allow, where the cache refused it as an unsupported policy, so shmem's xarray node for i915's blocking retry of a shmem object's pages failed and Raptor Lake P's GuC log buffer ended i915's probe with -ENOMEM
shmem_folio forwards RETRY_MAYFAIL to the radix node it grows (file.c),
and i915's shmem_sg_alloc_table retries with it once its non-blocking
first attempt finds the node cache full. The cache test now grows a slab
with the flag (one page attempt, refused or not, and no refusal counted)
instead of listing it as unsupported, and the trees test stores past the
root with every free node held: -ENOMEM where pages are refused, a grown
node where they are not.
2026-11-24 12:22:40 +00:00
Garvit Surana fa401608bb release: Stambha 0.6.1
The workspace and stela-boot versions go from 0.6.0 to 0.6.1, with the same
workspace members in both Cargo.lock files as the 0.6.0 bump. The boot
bundle revision (39), the options revision (13) and the translator id stay
as they are.
2026-11-24 12:16:21 +00:00
Garvit Surana 058410bf2e fix(installer): call the dry run "Install check (dry run)" and end it with "Nothing was installed: this was only a check. Choose Install macOS to install", where a tester read "Check only" and its PASS screen as an install
The confirm page's Left button and key hint said "Check only", and the
PASS screen began "nothing was written. Turn the PC off". The button and
hint are now "Install check (dry run)" with "A dry run, changes nothing: it
reads the disk and installs nothing" under them, and both PASS and FAIL
screens and statuses say nothing was installed because this was only a
check; FAIL also says where the log is.
2026-11-24 12:16:21 +00:00
Garvit Surana 499ad908ee fix(boot,cli): say where the boot log is on the stop and restart screens and in stambha's help: stambha log on any computer, or the file \EFI\stela\boot.log on the stick
The stop screens and the restart screen named only `stambha log`, and the
help gave no place at all. Each now also names the file on the stick, whose
path stays \EFI\stela\boot.log.
2026-11-24 12:16:21 +00:00
Garvit Surana a71850aa20 fix(app): show "Stambha <version>" in Stela.app's About This PC, its summary and its Updates list, where they said "Stela 0.6.0"
The version macOS users saw as "Stela 0.6.0" is the app's About This PC
caption, "Stela \(stelaVersion)", over the StelaVersion key stela.efi
publishes. The caption, the copied summary line, the Updates row and the
no-description card now say Stambha; the bundle identifier, the StelaHost
keys and the on-disk paths are unchanged. The app is prebuilt on a Mac
(guest/stela-app/build.sh), so this reaches users with its next build.
2026-11-24 12:16:21 +00:00
Garvit Surana a95ddeb980 feat(boot): say "Wi-Fi: press W to choose a network" on the boot menu and in the log when a Wi-Fi chip Stambha starts has no network, where the menu showed no Wi-Fi line at all and testers missed the key
With a Wi-Fi chip the driver starts and no --wifi or saved network, the
startup menu's bottom line was empty, so nothing said that Wi-Fi needs a
network chosen with W. wifi_page::status_line now always gives the line
(CHOOSE for that case), and the menu logs hint_line's "CHOICE Wi-Fi: no
network is set up; press W in this menu to choose one, or Wi-Fi stays off".
The HOST and GUEST NETWORK lines for an adapter left off say the same in
place of "no --wifi network".
2026-11-24 12:16:21 +00:00
Garvit Surana 824961a982 fix(gpu): an Intel integrated GPU is claimed without a reset, left in D0 as the firmware left it for i915 or xe to take over at its probe, as Linux binds it, with one line saying so and naming the reset it offered, where the claim's Function Level Reset left a Raptor Lake P GPU (8086:a7a0) whose registers all read 0xFFFFFFFF, so i915 found it non-operational, xe took it for a VF and its display stayed dark
The claim's reset choice is now a plan of who takes the GPU from the
firmware (cold::Takeover), by stack and device: the claim (nouveau, and
Intel's discrete GPUs), the driver where the function has no
function-local reset (amdgpu, as before), or the driver alone (an
integrated GPU in i915's or xe's table). i915 resets its engines at probe
(sanitize_gpu) before pci_set_master; xe resets its GuC and GT. NVIDIA and
AMD plans are unchanged. Host tests cover the plan of each takeover, a
function that offers FLR under a driver takeover (no FLR, no bus reset,
bus mastering off), and 8086:a7a0 at 00:02.0 under i915 and xe.
2026-11-24 12:05:02 +00:00
Garvit Surana 837dc2d0ec fix(drivers): bring an HD Audio controller to D0 and turn its memory decode on before the cold preflight, as Linux pci_enable_device does, leaving Bus Master as it was, where an AMD laptop's 1022:15e3 the firmware left powered down or not decoding failed with PowerNotReady 2026-11-24 11:43:27 +00:00
Garvit Surana fb6224af36 fix(drivers): bring an HD Audio controller to D0 and turn its memory decode on before the cold preflight, as Linux pci_enable_device does, leaving Bus Master as it was, where an AMD laptop's 1022:15e3 the firmware left powered down or not decoding failed with PowerNotReady 2026-11-24 11:43:27 +00:00
Garvit Surana 9a252b3337 fix(loader): tell macOS this Mac cannot sleep with /defaults sleep-disabled, set in each boot's own tree with a SLEEP line, and pin macOS's SEP sleep and wake sequence in a host test, where the Apple menu's Sleep panicked with "SEP failed to power-gate after 5s"
macOS's sleep path quiesces the SEP and waits up to 5 s on iop-sep-nub's
function-wait_for_power_gate (PMGR Wait on device 0xa0, SEP), then stops the
processors and enters deep sleep, resuming through the reset vector. None of
that is modeled, so the wait timed out and macOS panicked. XNU reads
/defaults sleep-disabled into gSleepDisabledFlag once booted, and
checkSystemSleepAllowed then refuses every system sleep with
kPMConfigPreventSystemSleep: the Apple menu's, idle, a sleep key's and a
lid's (--lid-sleep). macOS stays up and only its display sleeps.
2026-11-24 11:43:27 +00:00
Garvit Surana 94e9d63c19 fix(loader): tell macOS this Mac cannot sleep with /defaults sleep-disabled, set in each boot's own tree with a SLEEP line, and pin macOS's SEP sleep and wake sequence in a host test, where the Apple menu's Sleep panicked with "SEP failed to power-gate after 5s"
macOS's sleep path quiesces the SEP and waits up to 5 s on iop-sep-nub's
function-wait_for_power_gate (PMGR Wait on device 0xa0, SEP), then stops the
processors and enters deep sleep, resuming through the reset vector. None of
that is modeled, so the wait timed out and macOS panicked. XNU reads
/defaults sleep-disabled into gSleepDisabledFlag once booted, and
checkSystemSleepAllowed then refuses every system sleep with
kPMConfigPreventSystemSleep: the Apple menu's, idle, a sleep key's and a
lid's (--lid-sleep). macOS stays up and only its display sleeps.
2026-11-24 11:43:27 +00:00
Garvit Surana afa70f9809 fix(drivers): say Stambha, not Stela, when a PCI BAR the firmware left unassigned keeps a device off, and name the windows as the firmware's root bridges report them
Asimose's touchpad (I2C0 at 0000:00:15.0, 8086:51e8) stays off because
its LPSS controller's BAR0 is 0 and nothing assigns it. The message said
"Stela assigns none yet", and the native MMIO line called the windows
"its ACPI host bridges declare", though they come from
EFI_PCI_ROOT_BRIDGE_IO.Configuration(), the space the firmware allocated.
The probe test now checks the whole message.

Assigning the BAR is left for a later change: it needs the host bridge's
ACPI _CRS window and PNP0C02 ranges, which nothing reads yet, and a new
NativeServices path past claim_bar's firmware-window check.
2026-11-24 11:42:28 +00:00
Garvit Surana 4d21b8e509 fix(e1000e): let a PCH I219 PHY that ignores the forced ULP exit be reached through forced SMBus and a PHY reset, and name the exit's cause, where the adapter stopped at "an earlier PHY failure left it unusable"
Asimose's I219 (8086:0dc6, Raptor Lake PCH) failed on three boots of four
with only that message. The unmanaged ULP exit ran inside a PHY
transaction, so an MDIO timeout there poisoned the session and the
LANPHYPC recovery that Linux relies on never ran, and the cause went with
the controller.

As e1000_disable_ulp_lpt_lp does:
- the CV_SMB_CTRL page select is part of the read
  (__e1000_read_phy_reg_hv), so its failure takes the forced-SMBus retry
  too: with the PHY in SMBus mode and the MAC in PCIe mode it is the first
  cycle to fail;
- a PHY that does not answer fails the exit at release:, with the
  semaphore released and the session kept; only a transport fault (a
  refused or all-ones access, the semaphore, the delay clock) ends it;
- after a failed forced exit the PHY is reset (unless the ME blocks it)
  and given 50 ms before the access checks.

A start that still fails after a failed exit now reports both:
"..., after the PHY did not leave its ultra-low-power state (lanphypc: ...)".
New model knobs keep a PHY asleep through the first toggle or reachable
only through forced SMBus; each fix's tests fail without it.
2026-11-24 11:38:03 +00:00
Garvit Surana 7f429a62f1 fix(engine): compile a stored block's fault rows from its guest bytes when the record a retired pack gives lacks its entry, where an ordinary page fault became STOP NATIVE_FAILURE (StoredRecord) and code=0x13
Asimose's 0.6.0 stopped 495 s into macOS, 2 s after "TRANSLATIONS retired":
a user-space block installed from the pack took its first host page fault
(trap 14, error 0, at a guest address: the usual shadow fill), and its
recovery rows, which a stored block only fills at that fault, could not be
qualified.

Once the store is retired, Store::stored skips a record's pieces still in
the file and returns the ones in memory, where it returned none before. The
fault path read the entry's guest bytes only when no record came back, so a
partial record without the entry left CodeRecovery::qualify with neither
and it returned StoredRecord. CodeRecovery::stored_in now says whether the
record holds the entry, and the bytes are read whenever it does not.

The translator id is unchanged: no translation input moved, and the new
tests live outside the fingerprinted files.
2026-11-24 11:24:54 +00:00
Garvit Surana dbdf868d4b fix(wifi): let the Intel boot reach the MSI-X registers in BAR0's upper 8 KiB, where an AX200 with an MSI-X vector stopped at Boot(Access(Bounds))
NativeBootIo maps the function's whole 16 KiB BAR0 but refused every access
past 8 KiB. iwl_pcie_conf_msix_hw's IVARs (0x2880, 0x2890..) and the MSI-X
cause and mask registers (0x2800..0x2810) sit at CSR_MSIX_BASE 0x2000, so
route_interrupts failed on the first write8 and the boot never reached
ALIVE: the first Intel Wi-Fi test on real hardware (AX200, 8086:2723).

One WINDOW bound and reach() check now serve read32, write32 and write8,
and the boot fixtures' model keeps the same bound, so a fixture can no
longer reach a register the real window refuses. With the old bound, four
tests fail. The pinned cc-a0-77 and ty-a0-gf-a0-89 images still parse,
plan their paging and run the image-driven boot fixtures through ALIVE.
2026-11-24 11:14:06 +00:00
Garvit Surana 160638d844 fix(display): show a pointer move at the next vblank ahead of a desktop frame still waiting for its GPU fence, and time the trackpad's pointer reports, where the cursor's swaps queued behind that frame up to 1.7 s and CURSOR counted no touch frame
macOS moves the pointer by swapping DCP layer 1 alone. The model latched
swaps strictly in order, so each move waited behind WindowServer's
fenced desktop frame (paulstelian97's 860M: deepest=33, latch max
1742 ms; boot 31: 74 ms). A ready swap whose slots no waiting swap in
front of it set is now composed over the frame on screen at the next
vblank; completions stay in submission order. DCP PACING reports these
presents as overtaking=N.

With --trackpad the touchpad gives touch frames, which the CURSOR line
never counted (samples=0 in every log): a frame whose one finger moved
now counts as a pointer report.
2026-11-24 11:11:01 +00:00
Garvit Surana 7b6bb562d5 merge fork/build1-polish @d398c1df1 (Stambha 0.6.0) into the experimental GPU branch
mount_interface keeps build1-polish's wording of what laptop auto turns on, with --acpi-hardware for the battery, lid and brightness keys, beside the GPU branch's --hybrid-scanout note.
2026-11-23 19:14:42 +00:00
Garvit Surana d398c1df1e release: Stambha 0.6.0, so a stick made with Stela 0.5.0 sees this build as an update
The workspace and stela-boot versions go from 0.5.0 to 0.6.0, with their workspace members in both Cargo.lock files. The boot bundle revision (39) and the options revision (13) are constants of their own and stay as they are.
2026-11-23 19:12:34 +00:00
Garvit Surana 4d50d41d42 fix(boot): say plainly that macOS crashed or the graphics card stopped working before the technical detail, point the Wi-Fi page at stambha settings instead of --wifi and stela.cfg, and call the stick's EFI partition Stambha's, where the first words were raw panic, GPU and option text 2026-11-23 19:09:36 +00:00
Garvit Surana 18ed6a738a fix(laptop): take the battery, lid and brightness keys unasked only with --acpi-hardware, keeping the touchpad, where a laptop without hardware mode got a battery frozen at its first reading and a lid and keys that did nothing 2026-11-23 19:09:36 +00:00
Garvit Surana e8dd6d38ec merge fork/build1c @0b154df79 into the experimental GPU branch: the background pack preload off by default 2026-11-23 18:32:11 +00:00
Garvit Surana 724e0f7037 test(boot-core): build1c's PE-count sizing test gives sizes the GpuMemory::Own the GPU branch's signature takes, where the merge left it the old three arguments 2026-11-23 18:31:47 +00:00
Garvit Surana 0b154df794 perf(boot-core): leave the translation pack's background preload off unless --pack-preload on, where its memory shrank the code window from 1280 to 1200 MiB and raised re-installs from 7-32% to 43-49% on a 16 GB laptop while compile was 1-4% of PE time 2026-11-23 18:30:10 +00:00
Garvit Surana 5318af1912 merge fork/build1c @b3a83b2c6 (tester build 1) into the experimental GPU branch, with fork/hybrid-scanout's --hybrid-scanout
Both sides kept where both added: --hybrid-scanout beside --asus-mode,
--gpu-aspm, --tlbi-keep, --host-core, --tier2 and --pack-preload in the
options, their errors, parsing, tests and mount_interface's notes;
amd_discovery beside acpi_hardware; the stop's firmware picture beside
tier 2's line; set_hybrid_scanout beside gpu::link::choose; the
integrated GPU's memory plan beside the pack preload's bounds.

The translation store passes the GPU plan to pack_budget and the
background preload to translations::read. The firmware counts keep the
GPU branch's per-port sums, its base now 93 files, 188,594,997 bytes,
with build1c's rtw88 RTL8821C firmware (BUILT_BUNDLE 469/442/120/93).
build1c's preload tests give pack_budget and sizes_with_room the
GpuMemory::Own the GPU branch's signatures take.
2026-11-23 17:24:19 +00:00
Garvit Surana b3a83b2c6f merge: fork/tlbi-keep2 into fork/build1c 2026-11-23 16:13:59 +00:00
Garvit Surana b9dec93dfb perf(engine): verify kept TLBI contexts in place and drop an entry by its own slot, where each record was taken out of a BTreeMap and put back and each drop searched every set its granule listed across all contexts
Boot 27 spent 5.3 ms per whole TLBI verifying about 6250 entries, 18% of
them dropped. In a host benchmark shaped like it
(tests/tlbi_keep_cost.rs: 1297 contexts, about 5400 entries verified per
TLBI), the time went to moving 170-byte walk records out of and back into
the BTreeMap, and at boot 27's drop rate to forget_range_where, about
1.9 us per drop.

Records now stay in a store indexed by (context, page), so a kept entry
moves nothing. A dropped entry clears its own slot through
LookupTable::set, with the same drop epoch bump. Variant numbers are
cached per verification.

Verification per TLBI on the host: 885 -> 234 us at a 2% drop rate,
1994 -> 306 us at 17%. The forget path refills in about 705 us. The
acceptance, adversarial and randomized tests pass, and every mutation is
caught. --tlbi-keep stays off by default until a hardware boot confirms.
2026-11-23 16:13:22 +00:00
Garvit Surana 90a69fdc77 merge: fork/launch-fast into fork/build1c 2026-11-23 16:06:13 +00:00
Garvit Surana 7dfa02cb40 feat(translations): read a pack read on demand into memory in the background once the guest runs, in 2 MiB sequential reads that never queue ahead of a lookup's own read, and decode a lookup's record from that memory, behind --pack-preload on|off (on unless given), where a record only on the USB stick reached memory after its block had compiled (4 thousand of 2.7 million awaited lookups served)
What "awaited" was. A lookup never waits for the stick: a page whose key
the in-memory index holds but whose record lies only in the file is
answered Awaited, its block compiles, and the reader reads the record for a
later fetch. awaited_lookups counts those later fetches' lookups of the
same pages, not misses: a key no index holds is absent at once and never
read (113 177 distinct absent keys on 2026-11-23, none read). The records
came 60-570 ms after they were asked for, queued on a stick that runs one
command at a time behind up to 16 record reads, the writer's merge reads
and its 512 KiB writes (HOST DISK IO ..6573: 108-124 ms a command, deepest
40), 25 KB a read, and 171 919 asks were dropped as too late.

- stela-runtime translation_bulk: the preload's plan (each segment from its
  first record not read ahead, the merged one first, its records in the
  order a boot first used them), the memory it fills (Bulk: single writer,
  lock-free readers below a Release count), its reader (BulkReader: one
  read in flight, started after the record reads a lookup asked for, so a
  record's read waits behind one chunk at most), and the lookup shape the
  boot follows. FileRead moves here from the boot unchanged.
- The loader sets the memory aside within the room the pack's budget
  leaves (host_memory::bulk_bound: all the records in the file within the
  room, at most 1 GiB), so the room the window and the guest share shrinks
  by it; the descriptor follows the blobs in the handoff region.
- The engine decodes a record the preload holds in Shared::lookup and in
  the reader, waits for the preload for a record in its next two chunks,
  reads at most two records beside it, stops its own read-ahead while it
  runs, serves the writer's merge reads from it, and stops it when a merge
  retires the segments. The host core steps it with --host-core on;
  otherwise PE 0 steps it between slices at EL0.
- Logs: TRANSLATIONS background preload planned=..., installed, read=N MiB
  in M s held=... stopped=..., and at the end lookups in memory, from the
  preload and from the stick, before and after it stopped.

Records are still checked by their own trailers as they decode; the
translator id, the pack format, options revision 13 and bundle revision
39 are unchanged.

Tests: absent keys never read the stick; after a whole preload no lookup
does; a bound smaller than the pack holds its first records and reads the
rest on demand; a record damaged on the stick is refused alone; a lookup's
read runs before every later bulk read. A launch model over a fake stick
(30 MB/s, 5-50 ms a command, 16 KiB records), a first lookup every 2 ms:
on demand 0% of records in memory within 50 ms, wait p50 41 s; preloaded
in 2 MiB reads 99%, p99 23 ms. Every 0.25 ms: on demand 0%, p50 44 s;
preloaded p50 0.8 s, p99 1.7 s.
2026-11-23 16:04:42 +00:00
Garvit Surana e1a89364bc merge: fork/tier2 into fork/build1, never promoting or replacing an HLE composite and ending a superblock before any HLE function entry, where tier 2 promoted every hot block and a superblock could run on through a branch into a function's original words past its composite
Keep both sides of the hand-written options (--host-core, --keep-running-on-panic, --tlbi-keep, --tlbi-verify-check, --core-trial, --gpu-aspm, --hle with --tier2 and --tier2-check), the boot's settings for every PE, the Block fields (hle and tier2), the PE counts (tlbi_keep and tier2) and their sums. Options revision 13 and bundle revision 39 stand.

Tier 2 now skips a composite block's heat, refuses to promote one, and a tier-2 install loses to a composite held in the index. A superblock's window ends at the first word where an enabled signature's function starts (Machine::hle_entry_after). Tests: tier2_hle (a composite is never promoted, and a superblock ends before an HLE entry; each one fails when its guard is removed) and tier2_interactions (a superblock reaches no store offer, and with --tlbi-keep on a kept context reaches a superblock only through its verified walk, the drop epochs growing at the TLBI). fork_lines covers --tier2 and --tier2-check.
2026-11-23 14:09:41 +00:00
Garvit Surana 502399e17b feat(engine): a second compilation tier behind --tier2 on|off (off by default) and --tier2-check, where every block ran as tier 1 compiled it however hot it was
Tier 2 compiles a hot block again with NativeSystem::traces: its region runs on past every branch it would end at, loop or none, so it becomes a superblock whose branches into itself jump there, whose others leave by side exits, whose NZCV is captured only where a path reads it (the region's liveness along every path), and whose run of locals stays in host registers across it. It takes a superblock only where one of its branches lands ahead inside it and none leaves backward, a loop edge that is mostly taken and would leave out of line. A superblock is a block in every contract (one entry PC, a contiguous source in one page, one source-map row per word, recovery rows the compiler marks), so faults, exits, interrupts, IC IVAU and ring retirement treat it as tier 1's blocks, and native_failure's checks are unchanged for both tiers. Tier-1 compilations are byte for byte those of 72a0c83c0: the golden set of 8000 still matches.

The engine counts heat (a run's entry 1, a budget-spent run's last block 8), promotes at 64 after the run's exit completes, compiles with a traced preparation, keeps tier 1's code where tier 2's is the same, and installs the tier-2 block in the tier-1 block's index place, detaching it. Tier-2 code is never offered to the store, the pack or the rebase keep, so packs stay tier 1's; compile_window asserts it.

--tier2-check runs one tier-2 entry in 64 whose block only reads memory alone, then the same instructions again from the same start as single-instruction blocks with no interrupt between, and compares registers, NZCV, vectors, FPSR, PC, retired and BTYPE; on a mismatch tier 1's end stands and the block's page is invalidated, the block promoted no more. Both options are hand-written, so options revision 13 stays. The boot logs TIER2 on/off at start and PES TIER2 promoted= installed= unchanged= refused= exits= exits_side= deopts= checks= check_mismatches= check_skipped= mismatch_pc= each beat.

Tests: 500 random programs x 2 starts, tier 2, checked tier 2 and tier 1 against linked single blocks (integer, flags and every flag reader, forward branches and counted loops, aliasing loads and stores, pairs, LSE, exclusives, acquire/release, PAC hints, MSR NZCV, DC ZVA, SVC; faults astride a page boundary at 32 positions; code astride a page end): 0 mismatches, 283 checks agree. Breaking flag liveness gives 26 tier-2 mismatches, breaking a side exit's settling 17 (tier 1: 0); the check catches 12 and 10 of those entries. A rewritten superblock runs its new body in every tier. Benchmarks (ticks per guest instruction, tier 2 / tier 1): branchy leaf in a loop 0.64-0.68, memcpy, string and arithmetic loops unchanged (tier 1 already forms their regions).
2026-11-23 13:03:15 +00:00
Garvit Surana 641a34b7f8 test(options): put each of the fork's hand-written options in every place of the stick's startup lines and setup's own, twice and with bad values, and check --laptop off beside --acpi-hardware and --profile beside --host-core and --tlbi-keep 2026-11-23 12:13:12 +00:00
Garvit Surana dc865a6f66 fix(translations): warn when a translator has no pack and no spare.bin to take, naming the pack and stambha repair, where the boot kept its translations in memory and the log said only allocated=false 2026-11-23 12:01:00 +00:00
Garvit Surana 5eae1273f9 fix(wifi): name an open network's association as connected among the keeper's timed steps, where fork/wifi-more's State::Open left advance_step's match non-exhaustive on fork/build1 2026-11-23 12:01:00 +00:00
Garvit Surana fef7f64c96 style: format stela-boot and take Vec::contains in a ranges test, where cargo fmt and clippy's manual_contains failed on fork/build1 2026-11-23 12:01:00 +00:00
Garvit Surana 9f25dd0c40 merge: fork/hle-2 into fork/build1
# Conflicts:
#	crates/stela-boot-core/src/options/tests.rs
#	crates/stela-boot/src/engine.rs
#	crates/stela-boot/src/engine/parallel.rs
#	crates/stela-boot/src/engine/start.rs
#	crates/stela-loader/src/mount_interface.rs
2026-11-23 11:56:58 +00:00
Garvit Surana 18cd60b48e merge: fork/wifi-more into fork/build1
# Conflicts:
#	crates/stela-driver-net/src/lib.rs
#	crates/stela-driver-net/src/wifi/connection/keeper.rs
#	crates/stela-drivers/src/probe/native.rs
2026-11-23 11:55:43 +00:00
Garvit Surana 3fca31b14c merge: fork/more-cores into fork/build1
# Conflicts:
#	crates/stela-boot-core/src/options.rs
#	crates/stela-boot-core/src/options/parse.rs
#	crates/stela-loader/src/mount_interface.rs
2026-11-23 11:54:57 +00:00
Garvit Surana 00aae1e5ef merge: fork/hybrid-gpu into fork/build1
# Conflicts:
#	crates/stela-boot-core/src/options.rs
#	crates/stela-boot-core/src/options/error.rs
#	crates/stela-boot-core/src/options/tests.rs
#	crates/stela-loader/src/mount_interface.rs
2026-11-23 11:54:32 +00:00
Garvit Surana aed721729c test(hle): name the real-bytes oracle's and timing's prerequisite, STELA_HLE_FUNCTIONS, in their ignore reasons, as the oracle manifest requires, where both said manual: opt-in 2026-11-23 11:50:06 +00:00
Garvit Surana c716c7c32d merge future/wifi-rtl8821ce: Tyler Smith's RTL8821CE station on rtw88's rtw_chip_info table and his RTL8822CE robustness fixes (chip-reset recovery, ASPM and deep power save quirks, stepped calibration, receive and mailbox fixes), with the pinned rtw8821c_fw.bin
Tyler's 52 commits (tylertms/Stela future/wifi-rtl8821ce, 1f077f635),
merged unchanged. 23 of them are the same patches future/wifi-mt7921
brought in (keeper notices, recovery, stepped SAE, the MT7925 fixes);
conflicts and how they were resolved:

- keeper.rs, keeper/tests.rs, lib.rs and the 10 conflicted MediaTek
  files: fork/wifi-more's side, which already holds those patches and
  the connac2 work built on them. Git's auto-merge also re-added this
  branch's copies of the stepped-work imports to 13 MediaTek files;
  those files are kept as fork/wifi-more has them.
- wifi/stepped.rs: this branch's earlier copy of the stepped work is
  dropped; the RTL8822C and RTL8821C code uses stela_driver_base's,
  which future/wifi-mt7921 moved it to (same API).
- realtek/identity.rs and chip.rs: Tyler's rtw_chip_info SPECS, with the
  fork's RTL8852C as a fourth spec (rtw89, staged only) and its firmware
  parsed with Ce::Never, the RTL8852B's with Ce::Prefer, as before.
  source_mac.rs refuses the RTL8852C profile as it refuses the RTL8852B.
- probe.rs: take_diagnostic came in twice, the same commit on both
  sides; one is kept.
- smbios.rs and the e1000e test: the fork's board name and chassis type
  with Tyler's product SKU.
- pci/tests.rs: both sides' tests.
- recipes.rs: rtw88/rtw8821c_fw.bin (linux-firmware 59f9fc2, rtlwifi
  licence) after the fork's RTL8852C image, its binding beside the
  RTL8852C's; wireless_resource_tests checks REALTEK_WIFI[4] too.
- The firmware bundle grows by that one file: 93 files, 179.9 MiB
  (126 files, 187.8 MiB with the AMD port); setup's and the loader's
  bundle tests say so.

In the same commit, so that no tree between starts the RTL8821CE under the
RTL8822CE's claim name or hides it on the menu:
- wifi_claim: an Rtl8821c claim, named RTL8821CE in the boot log; it gets
  the FLR it advertises (Linux's quirk_no_flr does not name it), else the
  Secondary Bus Reset, else stays sealed.
- realtek_wifi's admit names the RTL8821CE by its IDs (10ec:b821, c821).
- wifi_starts and the startup menu's census count both IDs.
- unsupported.rs no longer says the RTL8821CE has no driver; RTL8822BE
  stands in as the rtw88 chip that has none.
- NOTICE: the rtw88 RTL8821C, rtw_chip_info and RTL8822C robustness
  sources Tyler's port follows.

The RTL8852CE's 855 driver tests and 19 probe tests pass with the same
names and results as fork/perf-1.
2026-11-23 11:49:00 +00:00
Garvit Surana a15851c1bf test(hle): opt-in oracle of the real macOS platform functions against their natives, and their per-call timing by size, from the private extract STELA_HLE_FUNCTIONS names, where no test ran a native against Apple's own function 2026-11-23 11:38:32 +00:00
Garvit Surana fee7ea1d59 feat(hle): generate function signatures from a dyld shared cache with cargo xtask hle-signatures, its report naming each candidate symbol's verdict, where signatures could only be written by hand
The phase-0 reader gains the bytes of the functions a cache's images
name, to the next function start; the generator trims padding, takes the
first ret as the exit and runs the engine's own Signature::of. --out
writes a table of hashes only; --extract writes the functions' bytes for
the real-bytes oracle and refuses a directory inside the repository.
2026-11-23 11:38:32 +00:00
Garvit Surana f1a7ea57b4 feat(hle): pass --hle to every PE, name what it turned on at boot, and report each PE's HLE counts once a beat under --profile, where the option reached no machine
A boot with --hle prints `HLE on signatures=K ids=... off=... max=...`
(and that nothing is replaced while no routine has a signature); under
--profile each PE prints `PES HLE pe=N matched=K/T installed= bypassed=
refused=...` once a beat. Without --hle nothing is printed and nothing
changes.
2026-11-23 11:38:32 +00:00
Garvit Surana bf1c2a0083 test(hle): calls through bl in a hot loop, a tail branch and a fall-through into the entry, a function the guest rewrites and invalidates with IC IVAU, and a copy between a load-exclusive and its store-exclusive, each against the original, where no test reached a native as a guest program does
A fall-through into a function's first word runs the original, as the
block the word before starts runs on into it and no compile starts at
the entry; a call or a tail branch, as macOS reaches these functions,
runs the native.
2026-11-23 11:38:32 +00:00
Garvit Surana 5111493ad8 feat(hle): native memmove and memcpy, bzero, memset, memcmp and strlen, on SSE2, AVX2 or AVX-512F as the host has them, each checked against its original and the C model over every size, alignment, overlap and page-crossing fault position, where every production routine's composite was refused for want of a fast path
memmove copies up to 256 bytes in size classes whose head and tail
halves are all loaded before any store, so either overlap copies exactly,
and past 256 reads every source page and probes every destination page
before its first store, then loops over destination-aligned vectors
backward when the destination starts inside the source and forward
otherwise. bzero and memset store the same classes; memcmp compares
GPR head and tail words or 16/32-byte vectors and gives the first
differing byte's u32 difference; strlen scans aligned vectors from the
string's start, masking the bytes before it, and bails without a NUL
within max_bytes. Every pointer a fast path dereferences is the range
check's clamped one, every loop is bounded by max_bytes, and a probe of a
destination is a value-preserving lock or, so a fault leaves memory as
the call found it for the original to take.

The composite's request carries the PE's compile target: the fast path
uses VEX/EVEX forms throughout where AVX2 or AVX-512F is there, and ends
each way out after a vector instruction with vzeroupper, and SSE2
otherwise.

The differential harness runs each case's original once and the native on
a machine per vector set the host has, reused across cases, with the
stand-ins, cases and model of phase 1's Task 3.
2026-11-23 11:38:32 +00:00
Garvit Surana 912d54aef5 build(fingerprint): leave a module declared after a "not a translation input" comment out of a fingerprint that skips test modules, with its declaration, and so mark the compiler's HLE module, where the HLE emitters, whose composites are never stored, changed the translator id and refilled every boot's translation pack
The compiler's fingerprint now matches fork/perf-1's byte for byte
(2aae71a8...) with HLE in the tree, and so does the engine's: stored
translations stay valid. A file with no marker hashes as before.
2026-11-23 11:38:31 +00:00
Garvit Surana 5f4eba3e79 test(memory): pin what 12, 16 and 24 PEs cost the guest (a 16 GiB PC keeps macOS 9538 MiB on 8 PEs and 9522 MiB on 16, an 8 GiB PC 3824 MiB on 24) and that a 6 GiB host is refused at every PE count, where nothing measured the budget past 8 PEs 2026-11-23 11:30:47 +00:00
Garvit Surana 494d9d16eb feat(gpu): with --hybrid-scanout on, the GPU that draws composes a hybrid laptop's panel into the integrated GPU's scanout buffers, made in system memory on amdgpu, and the integrated GPU flips them on its vblank, where the CPU copied every frame's rows into them
On a laptop without a display mux the panel hangs off the integrated GPU,
which runs no Metal service, so composition.rs share() refused ("no
Metal service runs on the display's GPU") and the CPU copied each
frame. --hybrid-scanout on|off, default off, hand-written, so the
options revision stays 13, lends the display the service of the first
other GPU that serves Metal (gate::drawing_service): that service
imports the display's three dma-buf scanout buffers, composes each
frame's damaged rows into the hidden one, and the display's own driver
flips it on its vblank once the composition completed, as for a GPU
that composes its own display.

amdgpu makes an APU's dumb buffers in its VRAM carve-out and pins them
there for scanout, where a GPU that is not its peer can import only a
buffer it may pin in GTT. With the option on, an amdgpu display's
buffers are made with AMDGPU_GEM_CREATE in GTT with CPU_ACCESS_REQUIRED
and CPU_GTT_USWC, the flag amdgpu_display_supported_domains needs to
scan GTT out on an APU, at amdgpu_mode_dumb_create's pitch, and mapped
and freed as dumb buffers. i915's dumb buffers are shmem already and
stay as they are. Untested on hardware: whether DCN 2.1 scans these out
and nouveau imports them is for the first boot to show, in the line
"GPU <igpu>: GPU <dgpu> composes the display's frames ...".
2026-11-23 11:29:18 +00:00
Garvit Surana eacfabab50 merge: fork/pe0-free into fork/build1
# Conflicts:
#	crates/stela-boot-core/src/options/error.rs
2026-11-23 11:20:05 +00:00
Garvit Surana f2f464ed49 feat(boot): run the host's service turns and the GPUs' pump on one extra host core under --host-core on, default off, reserved past the guest's PEs, set aside before the topology, pinged before the guest starts and given up for the PE-0 path whenever a step cannot be checked, where PE 0 served the host and pumped the GPUs between its own slices
--host-core on|off is hand-written (stela_boot_core::options::HOST_CORE), so
the options revision stays 13; setup never writes it.

- stela_boot_core::host_core: plan (a processor left beyond the PEs, a
  parallel run), confirm (every reserved processor started, the host core
  last), the Channel (one poster, one taker: ping, stop, state, beat), the
  self-check, covers (PE 0 leaves the pump only to a serving host core with a
  fresh beat), Shares (each taker's time served). Host tests for each,
  including a two-thread handoff and every fallback.
- system.rs: the plan reserves PEs + 1 processors; a refused plan or a
  reservation that kept fewer boots exactly as without the option, with a
  HOST CORE off: line. Resources::host_core marks the last slot.
- native_smp: --native-cores counts PEs (Resources::pe_cores); the last
  started processor is set aside (Executors::set_aside_host_core) only when
  every reserved one started, so the guest's PE count and topology are as
  without the option.
- engine/host_core: the host core's loop (shootdowns, a service turn every
  500 us as a waiting PE serves, gpu::pump_host_core every pass), the ping
  it must answer within 50 ms before the guest starts, else HOST CORE
  fallback and PE 0 keeps everything, and its stop before the service is
  taken back at the run's end.
- gpu::pump_due: PE 0 defers ready work to a serving host core unless it
  waited DEFER_LONGEST_NS or the host core's beat is older than 2 ms.
- The services beat line gains served_us waiting/boot/host_core and
  pe0_share=N%, and with a host core its state, turns and pumps.

Lines: HOST CORE plan / off / set aside / cpu=... serving=service-turns,
gpu-pump ping_us= / fallback / stop.
2026-11-23 11:19:13 +00:00
Garvit Surana 71ff51765d feat(gpu): log the GPU's temperature every beat as GPU THERMAL, from the sensor nouveau now reads each second beside GSP-RM's P-state (patch 0223), where nothing read the GPU's temperature and a GPU that dropped off the bus under load could not show whether it ran hot
Each perf round reads NV_THERM_I2CS_SENSOR_00 as gp100_temp_get() does;
nvkm_perf gains the register as last read, the temperature and the
beat's highest. "GPU THERMAL temp=52C max=55C power=unread" follows the
GPU PERF line every beat with a reading; a sensor that gives none (a
GSP-RM priv error or all ones) is said once with its register. Whether
GSP-RM leaves the sensor readable to the CPU is untested. Power is not
read: GSP-RM 570.144's headers hold no power monitor control.
2026-11-23 11:04:09 +00:00
Garvit Surana dfda54be15 fix(nouveau): a GPU that stopped answering for good is no longer read or written, and every timer wait ends at once on it or on a timer that reads all ones (patch 0222), where a teardown of a GPU off the bus spun 30 s through VMM flush waits until the step watchdog stopped the boot
On the tester's boot 3 the GPU was gone at 531.7 s; from 609.8 s, after
NVK's device loss, a job ran tu102_vmm_flush() over and over, each a
stalled PTIMER, a "timeout" and a WARN at vmmtu102.c:51, until the step
watchdog stopped it at 640.6 s. Its rip, image+0x1f2653e, sits on an
lfence before a return (code 0faee85dc3), as after an MMIO read; the
0.5.0 image's symbols are not at hand to name the function. Patch 0222 makes the
nvkm_rd*()/nvkm_wr*() accessors give all ones and drop writes once
nvkm_device_gone() holds, ends nvkm_nsec() waits with -ENODEV before
their condition runs, ends a wait whose PTIMER reads all ones at once
(feeding nvkm_device_gone()), and warns for neither, so the boot
reaches the GPU-lost stop.
2026-11-23 11:04:09 +00:00
Garvit Surana 50fac65aba feat(gpu): read the port above a GPU through the fabric's owner of its page, with its DPC state, and turn the link's ASPM and L1 PM Substates off at both ends at the claim with --gpu-aspm off, where every GPU's port was refused with ResourceConflict and a link the firmware left in L1 stayed so
A port that forwards to its GPU keeps its configuration page with the
containment fabric's owner of it (forward_cold_bridge), beside which no
other mapping may open, so port_above's read-only mapping was refused
with ResourceConflict on every GPU (native_mmio/shared.rs:738). The port
is now read through that owner (read_forwarding_bridge), and the old
mapping is kept only for a port that does not forward. The link lines at
the claim and the port's line at a loss or return now carry the port's
link, slot, AER and, new in the link report, its Downstream Port
Containment control, status and error source. As the port now reads,
the L1 PM Substates are set as Linux leaves them where they were skipped.

--gpu-aspm off|firmware, default firmware, is hand-written, so the options
revision stays 13. With off, each GPU's claim turns every L1 PM Substate
off at both ends, the GPU's first, then ASPM L0s and L1 at the GPU and
then at its port, as Linux's pcie_aspm.policy=performance does, through
the fabric that owns the port, read back, before the claim's reset; one
line says what each end had. Without a port, only the GPU's end, which
still keeps the link out of L1. The register work is
disable_link_power, beside disable_aspm_link, which now shares its
link-control and L1SS helpers. For a Yoga Slim 7 16ACH6 whose RTX 3050
drops off the bus after minutes with the firmware's ASPM L1 on
(stambha issue #1).
2026-11-23 11:04:08 +00:00
Garvit Surana 2dfefa7318 merge: fork/pe0-free into fork/build1 2026-11-23 11:02:52 +00:00
Garvit Surana cfec986c86 merge: fork/tlbi-keep into fork/build1
# Conflicts:
#	crates/stela-boot-core/src/options.rs
#	crates/stela-boot-core/src/options/parse.rs
#	crates/stela-loader/src/mount_interface.rs
2026-11-23 11:02:52 +00:00
Garvit Surana c5822abb0e feat(drivers): start MT7921 and MT7922 Wi-Fi through the same reset claim as MT7925, offer them on the startup menu and name their Linux sources in NOTICE, where the probe still refused every MediaTek chip but the MT7925
- wifi_claim: Mt7921 and Mt7922 claims; every MT7922 and MT7925 ID is
  denied its Function Level Reset (Linux quirk_no_flr names 14c3:0616 and
  14c3:7925) and gets the Secondary Bus Reset or stays sealed.
- claim_quiesced: the admit check names the chip it claims for, so the
  MediaTek admit reads the function's IDs once and refuses an MT7920 or
  any other unknown MediaTek ID before its reset.
- wifi_starts: MT7921 (14c3:7961, 0608), MT7922 (14c3:7922, 0616 and
  ITTIM's 0b48:7922) and MT7925 (7925, 0717), so the startup menu's Wi-Fi
  line shows on their PCs.
- Located forwards take_diagnostic, so the MediaTek and Intel keepers'
  notices reach the adapter.
- The MediaTek attach errors and the adapter's driver name no longer say
  MT7925 alone.
- NOTICE: the mt7921 and connac2 mt76 sources Tyler's port follows.
2026-11-23 11:02:19 +00:00
Garvit Surana 91b9dead3c merge: fork/warm-cache into fork/build1 2026-11-23 11:01:09 +00:00
Garvit Surana e96b553c29 merge: fork/log-panic into fork/build1
# Conflicts:
#	crates/stela-loader/src/mount_interface.rs
2026-11-23 11:01:09 +00:00
Garvit Surana 9c45dd3bad perf(engine): keep the ITLB's lookup contexts across a TLBI of everything behind --tlbi-keep on (default off) and verify every entry against the tables at the context's next fetch, with --tlbi-verify-check walking each kept entry in full too, where every TLBI of everything forgot every context and walked up to 2048 pages a context again, ~100 a second on each busy PE
Each ITLB fill records its walk: every descriptor address and value read over
both stages, in order, the TTBR0 it started from and what it gave. A TLBI of
everything marks the contexts kept; Contexts::find gives no kept context, and
every number native code holds comes from find (the fetch's contexts, the
TTBR0 switch table through switch_contexts, the transition records through
live_contexts). The chain runs in contexts::VOID, both ITLB drop epochs grow
(no stamp or jump cache entry survives, since a stamp may name a page an
eviction took), the switch table and transition records are forgotten by the
generation as before, and the TLBI-by-VA filters are cleared and refilled by
verification.

Verification keeps an entry only while every recorded descriptor holds its
value, a lower-half page's TTBR0 is the recorded one (the upper context holds
the lower half's global pages and has no TTBR0 in its key), the host still
permits the fetch, and the entry is what a fill would make now (page_variant,
block_key). Anything else drops it and walks it again; a context with an entry
no record covers is forgotten. The upper half is kept only while its keys
leave out the ASID.

PES TLBI KEEP gives tlbis, contexts, verified, forgotten, kept, dropped,
checked, mismatches(check), verify_ns_per_tlbi and each PE's kept/dropped;
PES TLBI KEEP MISMATCH samples what the check found.

Tests: the five-scenario acceptance set runs on configured machines and passes
with the keep on, with and without the check, and fails in all five under the
mutation that keeps without verifying (a permanent test). New cases: a
descriptor changed and back (ABA), a table page freed and reused, a block split
into a table, a stage-2 change, permission-only changes (UXN, AP, PXN), a page
the host refuses, a frame whose variant changed, an ASID reused with the same
layout (private and global), the native paths' void state, and a randomized
differential of keeping against forgetting over 10,000 steps of table rewrites,
TLBIs and switches. Seven mutations of the checks (TTBR0, descriptors, host
permission, entry key, drop epochs, void context, refilter) each fail a test.

Options revision 13 kept: both options are hand-written. No translation input
changed, so the translator id is unchanged.
2026-11-23 10:59:20 +00:00
Garvit Surana f07a9f11a2 feat(options): add --core-trial, a hand-written read-only boot of a USB bundle on RAM-backed disks and an explicit --native-cores count that refuses --storage, --nor, --preboot, --install, --restore-study, --external-disks, --usb-storage and --wifi, applies no pending disk plan and opens no translation or pipeline store, so options revision 13 holds, and pin that a Mac mini disk boot takes --native-cores 4, 6 and 8 and stops at 9, where a many-core Mac could only be tried by installing it 2026-11-23 10:55:44 +00:00
Garvit Surana 30c9ca966f feat(board): admit the M2 Pro, Max and Ultra boards' first external display pipe (dispext0,t602x) and their memory cache (mcc,t6020), told apart from the M1 Pro's DCPEXT0 graph by the pipe, with oracle tests that the 26B123 J474s, J475c, J475d and J180d trees keep both and parse with 12 or 24 CPUs and that the Mac mini M2's admission is byte for byte unchanged, where every T602x board lost its display graph and MCC to the hidden list and its MCC owner was unreachable 2026-11-23 10:55:44 +00:00
Garvit Surana 3af4cac8f4 merge future/wifi-mt7921: Tyler Smith's MT7921/MT7922 (connac2) station, open networks, the SAE PMKSA cache, stepped SAE and radio recovery, keeping the RTL8852CE keeper on the contract its hardware proved
Tyler's 47 commits (tylertms/Stela future/wifi-mt7921, 6ecaf7e49), merged
unchanged. Conflicts and how they were resolved:

- wifi/connection/keeper.rs: choose() keeps the fork's saved alternates
  (candidate index, outranks, refusals per candidate) and takes Tyler's
  open networks and PMKSA resumption; each candidate's own secret decides
  open, passphrase or PSK. The Link impl's carrier wait is the radio's own
  where it names one (the RTL8852CE's 30 s WIFI_CARRIER_WAIT_US), else
  Tyler's 45 s CARRIER_WAIT_US instead of a wired PHY's 10 s.
- Two Radio constants keep the RTL8852CE keeper as it ran on hardware:
  RESUMES_PMKSA (false: every join runs the whole SAE exchange) and
  FAILS_THROUGH_RECEIVE (true: its failures still reach the boot as
  receive errors, the latest once, instead of take_diagnostic notices).
  Both default to Tyler's behaviour for every other radio.
- keeper/tests.rs, kept_connected.rs and lib.rs: both sides kept; Tyler's
  Network literals gain the fork's alternates; the wired-wait test now
  expects CARRIER_WAIT_US for a radio that names no wait.
- network.rs: the fork's Alternate and prefer with Tyler's Secret::Open.
- unsupported.rs: MT7921, MT7922, MT7925, RTL8822CE and RTL8852CE run a
  station here; the "only MT7925's" line is gone.

The RTL8852CE's 855 driver tests and 19 probe tests pass with the same
names and results as fork/perf-1.
2026-11-23 10:48:34 +00:00
Garvit Surana d5dc6fff42 fix(wifi): wait out the RTL8852C association's beacon interval across service turns, cap the network part's frame loops at 2 ms a turn, and name the slow piece and keeper step in HOST SERVICE SLOW, where boot 23 held PE 0 busy for 101 ms in rtw89_mac_port_cfg_func_sw's msleep(beacon_int + 1) inside the guest network's carrier poll
The 101 ms `HOST SERVICE SLOW part=network` lines of boot 23 (43.674 s and
1017.086 s, each ~260 ms before the host adapter's "link up") are the INFRA
port update of the association: ax/vif.rs cfg_func_sw delayed
(beacon_int + 1) * 1000 us once vif init had turned the port function on,
called from assoc::associate under Live::associate, under the station's
configure, under the keeper's poll, under GuestNetwork::carrier/receive in
the network part of PE 0's service step. Linux sleeps there; here it was a
busy wait on a guest PE.

- vif: port_function_on, quiet_us and port_update_after split the update
  around its wait; port_update keeps the blocking order for vif init.
- assoc: associate_begin and associate_end; associate is begin, wait, end.
- Live: begin_association and finish_association hold the begun
  association with its deadline; Chip::associate now returns Ok(false)
  until it has passed. A begun association leaves as a made one; set_bssid
  and a second association are refused meanwhile; power-off forgets it.
- ax station: configure keeps the admission and is Pending while the chip
  waits; the keeper retries a deferred configure while the radio is still
  Admitted (other radios unchanged).
- Flush without drop polls DLE_TXQ every 100 us instead of 10 ms.
- Link::slowest_step: the keeper times its steps (radio service, eapol and
  keys, port, scan, scan end and join, associate, configure, ...).
- service: the network part's transmit and receive loops stop starting
  frames after 2 ms (service_watch::Budget), the next turn starting at the
  network; HOST SERVICE SLOW part=network carries carrier/queued/transmit/
  receive/deliver us, sent, read, cut and keeper=step:us;
  HOST SERVICE KEEPER names a keeper step of 2 ms or more; the host
  adapter's link up/down line carries keeper_longest=.
2026-11-23 10:39:22 +00:00
Garvit Surana f6e2ecfadd test(engine): pin tier 1's output with a golden set of 8000 compilations from 72a0c83c0's compiler: a deterministic corpus of 2000 blocks over the integer, memory, exclusive, atomic, branch, FP, SIMD and system families, at EL1 and EL0, with and without regions and self-loops, for a fixed Zen 4 target, each digest of code, source map, relocations, exits, recovery rows and shape compared, before any tier-2 change to the compiler 2026-11-23 10:21:52 +00:00
Garvit Surana 2217199307 perf(ahead): keep 16384 jobs of a block's page and 4096 of other pages ahead of use, and let the previous translator's refill run beside the ahead queue rather than only once it empties, where a desktop boot dropped 24.0 M of 37.3 M jobs and the refill of blocks a boot ran waited behind guesses of which 14 % ran 2026-11-23 10:15:58 +00:00
Garvit Surana cb0c21ce7d feat(translations): read the first records of a pack read on demand into memory before the guest starts, within a fourth of the room its indexes leave (at most 256 MiB) and two seconds, split the segment in the store into those records and an index of the rest read on demand, check each record as before, and log TRANSLATIONS preload, where every record of the 498 MB pack waited for a USB read on an idle PE while busy PEs compiled it 2026-11-23 10:15:58 +00:00
Garvit Surana 5a388aef5d merge fork/hle into fork/perf-1 for HLE phase 1's natives
Tasks 1-7 of HLE phase 1 (signatures and matcher, --hle and --hle-off,
the differential harness, the compile hook, composite blocks, install and
the fault bypass) onto perf-1. The options conflicts with fork/amx are
both sides kept; --hle and --hle-off are hand-written opt-ins setup never
writes, so the options revision stays 13, as the revision's comment now
says.
2026-11-23 09:59:04 +00:00
Garvit Surana 0e188ceaa0 fix(boot): give every boot's XNU lock timeouts at least twice their default, 250 ms for a ticket spinlock, where a host as fast as the modeled chip kept 125 ms and warm boots have stalled every PE for 104-162 ms
A separate, conservative default: LOCK_SCALE_FLOOR is 2, a slower host
keeps its own larger scale, and --profile multiplies the result by 4 as
before. A real deadlock still panics within a second.
2026-11-23 09:45:17 +00:00
Garvit Surana 8c34c1b9c2 fix(boot): stop the run 30 s after a guest kernel panic that never resets the Mac, as "macOS panicked: <message>", store the USB log within a second of the panic, and name a guest console quiet for 120 s before macOS's first frame as BOOT STALLED?, where a boot whose macOS panicked at 42.7 s and then spun at one PC ran on for twenty minutes until the PC was turned off
stela-boot-core's guest_watch takes the lines the home PE writes: XNU's
"panic(cpu N ...)" header counts only at a line's start, so lines that
merely mention a panic, or a header inside a long line's continuation, do
not. The first header is logged (GUEST PANIC seen) and shown as the
running step's detail; with no reset PANIC_HOLD_MILLIS later the run ends
through finish() as a halt, logged as STELA FATAL macOS panicked, with the
stop's usual reports, translation write, log store and screen. A panic
that a reset follows keeps today's path. --keep-running-on-panic, a
hand-written opt-in like --acpi-hardware, keeps the options revision at 13.
2026-11-23 09:43:13 +00:00
Garvit Surana 0b326db4f5 fix(boot): multiply XNU's lock timeouts by 4 under --profile, where a profiled cold boot on a 5.04 GHz host kept lock_scale=1, stalled PEs 1-3 for 193 ms past ticket-lock's 125 ms and macOS panicked "Ticket spinlock ... timeout"
The scale stays the host's own without --profile; a profiled boot gets it
times PROFILE_LOCK_FACTOR, at most MAX_PROFILED_LOCK_SCALE (2 s for a
ticket spinlock). GUEST TIMEOUTS now also names host_scale and profile.
2026-11-23 09:37:03 +00:00
Garvit Surana 72a0c83c07 feat(log): count each PE's own TLBIs of everything by whether TTBR0_EL1 changed since its previous one, and under --profile sample one in 4096 with its PC, X16, X30 and both TTBR0 values, with the acceptance tests any whole-TLBI keep must pass, where nothing said what made SPTM flush everything at context-switch rate
PES WHOLE TLBI TRIGGER same_ttbr0/new_ttbr0 gives each PE's split, read at
the TLBI from the register, so native TTBR0 switches count too; mail's
TLBIs of everything are another PE's and count in neither. Under step
timing, PES WHOLE TLBI SAMPLE lines name the caller: if nearly every one
follows an address-space switch, the trigger is the shared-region rule in
pmap_switch, which only keeping translations across the flush answers; if
not, the CPU model makes SPTM flush. Reads registers only.

after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives runs five
scenarios on machines of their own: a page remapped, unmapped, made PXN, a
TTBR0 and ASID reused by a new process, one VA in two address spaces with
one changed. All pass, and all five fail when the TLBI of everything keeps
the contexts without checking them (a mutation of tlb_maintained), the
bar a "verify instead of forget" must clear. That change itself is not made
here. Engine translation inputs untouched: the translator id is unchanged.
2026-11-23 08:23:30 +00:00
Garvit Surana de600d5d1e perf(engine): walk the post-TLBI refill's pages from the leaf table the walk before read, with the controls and requester read once a batch, where refill_pages walked each of up to 2048 pages a context from the table base, its controls and requester rebuilt per page, about 0.9 ms of engine time each whole TLBI
mmu::WalkMemo keeps the last table a batch's walk read (translate_noting)
and starts the next walk there while it holds that walk's address
(translate_from), as a walk cache does; refill_pages makes one per batch
and drops it with the batch, which runs no guest code, changes no control,
makes no descriptor update and ends at the first walk that forgets
contexts. The refill's list is sorted, so its pages run through shared leaf
tables: one descriptor read a page past the first instead of three or four.

Tests: a randomized differential test (300 random regimes, granules,
stage 2 and tables) has every walk of a sorted batch equal the full walk,
also after the tables change between batches, path and hierarchical bits
included, and catches a memo kept across that change giving stale
translations; an engine test refills 48 pages after a TLBI ALL with a page
unmapped, one moved and one made PXN in between, takes exactly what full
walks give, and reads under two descriptors a page where the old walk read
three (144 in all; a
mutation to the old walk fails its bound). The engine's translation inputs
are untouched: the translator id is unchanged.
2026-11-23 08:10:24 +00:00
Garvit Surana 1832a6e6cc perf(boot): write every shadow page-table leaf with Accessed set, and Dirty on a writable one, so the processor makes no locked update of a fresh entry at its first access and first write, where a demand fill, prefill and restore wrote PRESENT | NX | WRITABLE | USER alone and each of the tens of millions of entries a minute the whole-TLB flushes cost took one or two
Nothing reads the host's A or D bits: the shadow keeps no dirty or access
tracking (the guest's own state is in its descriptors, which the walker
never updates, no FEAT_HAFDBS), and the fills test PRESENT alone. The
rights move to stela_boot_core::shadow_leaf, tested there, with a
compile-time check that its bits are the page tables' own. Engine and
compiler untouched: the translator id is unchanged.
2026-11-23 08:00:36 +00:00
Garvit Surana 3a1a91bfc5 feat(boot): set an ASUS laptop's firmware thermal policy to performance before macOS starts, as Linux's asus-wmi sets throttle_thermal_policy, with --asus-mode performance|turbo|silent|off, where macOS ran in whatever mode Windows last chose
The policy device (0x00120075, else the Vivobook's 0x00110019 with silent
and overboost swapped) is found by its DSTS presence bit on the ATK WMI
device that has the notebook events, and set with DEVS, which must answer
1, in a bounded firmware call after the ACPI activation, with or without
--acpi-hardware. The FA608PP's DSTS of the policy answers a constant
0x00010003, so the mode in effect is read from the EC RAM field its DEVS
writes (EC0.FTBL) before and after. One line:
"ASUS thermal policy: was X, set Y (...), the firmware reads Z", or why it
was skipped; nothing on a PC without the ASUS notebook device. A failure is
logged and the boot goes on. The asus-wmi power limits the device names
(PPT_* and NV_DYN_BOOST) are read with DSTS, read only, on a
"HOST POWER LIMITS asus-wmi" line.

--asus-mode is hand-written, as --laptop and --acpi-hardware are: no line
setup writes holds it, so the options revision stays 13.
2026-11-23 07:57:47 +00:00
Garvit Surana 45094bb513 merge: fork/acpi-hw into fork/next 2026-11-23 07:26:34 +00:00
Garvit Surana 2c73994467 merge: fork/touchpad-reset into fork/next 2026-11-23 07:26:34 +00:00
Garvit Surana 9f472e8f24 feat(boot): run the host's ACPI in hardware mode with --acpi-hardware, with _INI before the census as without it, the activation bounded on the firmware timeout, the SCI's storm guard and the EC's query budget and failure breaker, where hardware mode was off on every PC
With the option the provider attests FULL_CAPABILITIES, which only
Session::enable_hardware reads, so the namespace loads as without it.
Without it, or without a captured SCI route, nothing of hardware mode
runs and one line says why.

- _INI runs before the PCI census either way, so pci_power and the census
  see what they see now; hardware activation then runs no _INI again and
  the EC's _REG follows it, as under Linux without an ECDT.
- The activation runs inside the 10 s AML bound on the firmware calls'
  11 s deadline. Its 5 s deadline was shorter than ACPICA's own 3 s wait
  for SCI_EN plus _REG, and a continuation past its deadline closes the
  work owner's entry for every later firmware call.
- The SCI's dispatch follows the storm guard: masked and polled while it
  storms, its PM1/GPE registers logged once, run and rearmed on the retry.
- The EC's queries follow its budget and breaker; each query number gets
  one line, so a test boot shows which events arrive.
2026-11-23 07:24:16 +00:00
Garvit Surana 915cb88ef6 feat(boot-core): add --acpi-hardware, a hand-written opt-in that keeps options revision 13, and the lines, FADT ACPI-mode registers, SCI storm guard and EC query budget and failure breaker ACPI hardware mode runs with
--acpi-hardware is a flag setup never writes, so no line setup writes
changes meaning and the revision stays 13, as the fork's --trackpad and
--laptop did; mount_interface's revision notes name it. --laptop auto does
not take it until a laptop has proven it.

stela_boot_core::acpi_hardware holds what a host test can check:
- the off, refused and starting lines, the last naming SCI_INT, the SCI's
  route and whether entering ACPI mode takes SMI_CMD <- ACPI_ENABLE (read
  from the FADT: SCI_INT 46, SMI_CMD 48, ACPI_ENABLE 52, PM1a_CNT 64);
- SciGovernor: past 100 SCIs a second for 3 seconds the SCI stays masked
  and ACPICA's handler runs every 100 ms, interrupts are tried again once
  after 30 s, and a second storm keeps the polling for good;
- EcGovernor: 64 queries a second at most, events stopped after 3 failed
  transactions in a row, and each query number named once.
2026-11-23 07:24:16 +00:00
Garvit Surana 2809f1451b fix(acpi): disable, clear and flag a FADT GPE in the EC's raw handler with no GPE device, as Linux's EC handler does, where it passed on ACPICA's \_GPE node, which acpi_disable_gpe and acpi_clear_gpe refuse with AE_BAD_PARAMETER, so in hardware mode the EC's GPE was never flagged and its status kept the SCI asserted
ACPICA dispatches a raw GPE handler with gpe_block->node, which for the
FADT's blocks is acpi_gbl_fadt_gpe_device. acpi_ev_get_gpe_event_info finds
a GPE through a non-null device only when a GPE block device's object is
attached, which the \_GPE node never has, so both calls failed and the
handler returned NOT_HANDLED. Session::flag_gpe installs only on the FADT's
blocks, so the handler now names them with a null device
(drivers/acpi/ec.c: acpi_disable_gpe(NULL, ec->gpe)).

A new host test runs the --acpi-hardware path on the real ACPICA with a
fake chipset (PM1, PM1_CNT, GPE0 at 0x1010, SMI_CMD 0xb2 that sets SCI_EN
on ACPI_ENABLE 0xa0) and the fake EC: _INI once before activation, the
EC's _REG(3,1), ACPI_ENABLE written once, the SCI installed on IRQ 9, no
_INI replay, the EC's GPE taken from the SCI handler, QR_EC 0x2f, _Q2F's
Notify(LID0, 0x80) delivered as deferred work, and the GPE resumed. It
failed on the handler above before this fix.
2026-11-23 07:24:16 +00:00
Garvit Surana 8ddadfe4e8 fix(input): take an I2C-HID reset response no command waits for as Linux i2c_hid_get_input does, watch a precision touchpad's mode switch for the reset it causes, start a pad that reset out of touchpad mode again and switch it back, and read it as a mouse when the mode will not hold, where one zero-length input stopped and removed the touchpad for the whole session
On the ASUS TUF A16 FA608PP the ELAN touchpad at \_SB_.I2CA.TPD2 was
switched to touchpad mode at probe, then its first poll read a zero-length
input on the asserted pin. Device::poll returned UnexpectedReset for it,
fail() masked the interrupt route (the "recovery IrqMasked" in the log),
the device was left faulted and the boot's input loop removed it.

Linux takes a zero-length input as a host or device initiated reset
completing: it wakes a waiter when I2C_HID_RESET_PENDING is set and drops
it otherwise. Now:

- Device::poll returns InputReport::Reset and the device stays ready.
- Device::reinitialize starts a started device again from ready or failed
  (never after a timing failure or an unreturned callback): power on, RESET
  and its awaited response, both descriptors read again and unchanged.
- Device::settle watches the pin after a command that can reset the device.
- HidInput::new sets touchpad mode and watches 100 ms for a reset. A pad
  that reset and no longer reads back touchpad mode (GET_REPORT of its Input
  Mode feature) is started again and switched once more. A switch that
  fails, or a second reset out of the mode, starts the pad again in its
  firmware's mouse mode and reads it as a mouse.
- At run time a reset with the mode held is dropped and said once; a pad
  that lost the mode is started again and switched back, three times in
  10 s, then read as a mouse. Other devices stay in their power-on state,
  as Linux leaves them.
- Each of these is logged as "INPUT <name>: <notice>".
2026-11-23 07:15:26 +00:00
Garvit Surana 5529658db0 fix(boot): install the host lid's notify handler in a bounded firmware call on the work owner's continuation, where retain_power named the lid and installed its handler on the dispatcher's stack once the devices' start returned, so on a PC with a PNP0C0D lid ACPICA's namespace guard asked thread_id outside its continuation and the boot stopped with code 0x11 right after the LAPTOP line, --laptop off and explicit options alike
The FA608PP tester build stopped at step f with "ACPICA called outside its
owned native continuation". The laptop decision itself reads only the FADT
and what the probe already read; the call that reached ACPICA was
HostAcpi::retain_power's lid.path() and notify(), which take the namespace
guard (stela_acpi_guard_enter -> services.thread_id). The batteries and AC
adapter it publishes are the probe's cached readings and stay where they
were. A laptop test now follows take_laptop_features, retain_power and
attach_brightness_keys and fails on any ACPICA call outside a firmware call.
2026-11-23 06:01:54 +00:00
Garvit Surana 15e62270ae merge fork/next @21e10c4a1 (tester build 1) into the experimental GPU branch: the Stambha brand, X1's NVK-only fault dump, Bluetooth, the Wi-Fi menu, gate and claim, the hardware guards and Install caution, laptop-auto and the review fixes, beside amdgpu, xe and i915
Eight files conflicted; every resolution keeps both sides.

- gpu_status.rs (9 hunks), host_memory.rs, engine/gpu/before.rs,
  stela-driver-gpu lib.rs: gpu/intel's GPU-generic screen text (the GPU by
  its name, the drivers this build has, shown_by_copy(gpu)) in the fork's
  brand: Stambha and `stambha repair` where gpu/intel's words said Stela.
- storage.rs: gpu/intel's memory-plan census (plan_gpu_memory, gpu_census,
  gpu_plan) and the fork's census_pci, drawn_by_other and Install caution.
  drawn_by_other goes through H1's GpuStack::drawing (select, then draws),
  built on gpu/intel's admits, and answers the adapter with its revision
  too, for the HOST GPU line's market name.
- xe.rs: gpu/intel's admission (a GuC image and ANV opening the device);
  host_firmware.rs: gpu/intel's MAX_IMAGES 512 beside the 1 MiB manifest
  both sides have; bundle/tests.rs: gpu/intel's amdgpu, xe and i915
  selection tests (the fork's Raphael-only family test is for recipes this
  branch replaced).

Merged clean, fixed after the build: the fork's lost-device dump
(059d63ddf) read a render pipeline's bicubic variants as 3-tuples;
gpu/intel's f8b623bd7 gave them a topology class, so they are 4-tuples.
gpu/intel's other screen lines that said Stela (amd_metal's refusals,
selection's backend line) and gpu_step's and host_memory's expected text
now say Stambha.

The memory plan is as before (only its refusal's name changed). Interface
unchanged: bundle schema 4, OPTIONS_REVISION 13. Mesa patch 0043 (each
shader's program header and code) comes with fork/next.
2026-11-23 01:50:48 +00:00
Garvit Surana 21e10c4a10 fix(boot): keep the startup menu's Wi-Fi offered when a PCI port shows nothing below it, where a Wi-Fi card the firmware left powered off answers only after the engine powers the port on, as the NVIDIA notice's NotYet does, where a complete census without the chip hid the Wi-Fi line and W (review G1) 2026-11-23 00:35:52 +00:00
Garvit Surana b4c058ac4a fix(soc): give the Bluetooth bridge its controller's credit back when the guest resets or configures the function again, as Linux's hci_dev_do_reset sets cmd_cnt to one, where a command in flight then lost the only credit and the next HCI Reset waited for it until the lend fell back (review T1) 2026-11-23 00:35:52 +00:00
Garvit Surana ecbf17a9c0 fix(boot-core): write a saved network's leading # as %23, so a name such as #Home is a network line and not a comment that no boot joins, the page never lists and Forget cannot remove (review W2) 2026-11-23 00:35:52 +00:00
Garvit Surana 20a5f5c45f fix(boot): name in the menu's Wi-Fi line only a saved network a boot can join first, checked again when the page closes, and refuse Enter on a network whose saved key is unusable, where a network just forgotten or with a bad key stayed named and went to the boot as --wifi-prefer (review W3) 2026-11-23 00:35:52 +00:00
Garvit Surana bb196909a4 fix(boot): keep the saved Wi-Fi networks when the menu's Save or Forget cannot read or write them: an unreadable wifi.saved is refused, not taken for an empty one, and a change goes to wifi.saved.new and is read back before the file is rewritten, that copy standing for a file a stopped rewrite left absent, where uefi's write deletes the file first and a failed read or write erased every network (review W1) 2026-11-23 00:35:52 +00:00
Garvit Surana b3b7b1a788 fix(boot): count another vendor's display controller as one the image drives only when its kernel driver takes it (GpuStack::drawing, through amdgpu's or xe's admits), so the Install caution and the GPU notice are not skipped for a Radeon left to radeon or an Intel GPU outside xe's table (review H1) 2026-11-23 00:35:52 +00:00
Garvit Surana a54f384404 docs: run stambha, not stela, in the README's install, update, log and build steps, as the archives now hold stambha and stambha.exe (review B3) 2026-11-23 00:35:52 +00:00
Garvit Surana 0f79e73b34 fix(gpu): give the first fault's dump 6 KiB of shader code in hex, about 19 KB of GPU FAULT text, so the boot log's 64 KiB burst for those lines still holds all three dumped faults, where 32 KiB of hex, about 94 KB, hid the second and third (review X2) 2026-11-23 00:35:52 +00:00
Garvit Surana 8686ef4bcb fix(gpu): ask only NVK for a pipeline's internal representations in a lost device's fault dump, as Stela's pipelines are made without the capture flag, where RADV answered the query with strlen(NULL) and stopped the PC on an AMD device loss (review X1) 2026-11-23 00:35:52 +00:00
Garvit Surana 75549a26ff style(cli): rustfmt the old-stick wording test, which the shorter Stela 0.3 or older line fits on one line 2026-11-23 00:35:52 +00:00
Garvit Surana 5cefe081a1 fix(boot): say Stambha in the install warning's two NVIDIA notices hw-guards added, where they still said Stela after the brand merge; log lines keep their words 2026-11-23 00:35:52 +00:00
Garvit Surana e086fabb08 fix(cli): call a stick whose record names no release Stela 0.3 or older, in the home screen and in status, as Stela made those sticks, where the rename said Stambha 0.3 or older 2026-11-23 00:35:52 +00:00
Garvit Surana 43af99c1e4 merge fork/brand: Stambha's pillar logo and name on the boot screens and the setup tool named stambha; wifi-menu's header painter test follows the new logo_pixel(x, y, side) and the Stambha name, and the GPU notices stay where hw-guards moved them 2026-11-23 00:35:52 +00:00
Garvit Surana 0decabb78a merge fork/laptop-auto: a laptop found at boot (FADT mobile profile, or an ACPI battery and lid) takes --battery, --lid method, --brightness-keys and, with --input and a precision touchpad, --trackpad mt2 unasked; --laptop off keeps them opt-in; options revision 13 2026-11-23 00:35:52 +00:00
Garvit Surana 3b792a32d2 merge fork/manifest-cap: an NVIDIA image reads a host firmware manifest of up to 1 MiB and 1024 files, as upstream does, and an update shortens a boot log too long for the next update's loader copy 2026-11-23 00:35:52 +00:00
Garvit Surana 71c86e7a9b merge fork/hw-guards: a warning page before Install macOS on a PC with no graphics card the image drives (Back by default), a vendor-neutral log line for a display device no recipe covers, and setup notes on Wi-Fi (RTL8852CE only) and Secure Boot / BitLocker 2026-11-23 00:35:52 +00:00
Garvit Surana 541ec8cc3a fix(drivers): allow claim_unmastered to go unused where native-acpi is off, as wifi-claim moved the Wi-Fi claims to their quiesced claim and its other callers, the SMBus and I2C hosts, are native-acpi's, where cargo clippy -p stela-drivers failed on dead code 2026-11-23 00:35:34 +00:00
Garvit Surana 93ad9d63cd merge fork/wifi-claim: Intel AX2xx/BE200, MT7925 and RTL8822CE Wi-Fi claimed through cold preparation and reset to their power-on state (FLR, or a Secondary Bus Reset on an exclusive bus; never FLR for MT7925) before Bus Master, experimental; the RTL8852CE claim path unchanged 2026-11-23 00:35:34 +00:00
Garvit Surana 8d4b603135 fix(drivers): claim Intel, MT7925 and RTL8822CE Wi-Fi through cold preparation, reset each to its power-on state (FLR, or a Secondary Bus Reset of its own bus; never the FLR Linux's quirk_no_flr refuses an MT7925) before its quiescence is acknowledged and its own domain bound, keep it sealed and say why when no reset reaches it, clear Bus Master again after a failed attach, and offer Wi-Fi at the startup menu for these chips (experimental), where every claim kept the seal for good and no driver but rtw89's could set Bus Master 2026-11-23 00:24:38 +00:00
Garvit Surana 7795f5f809 feat(boot): detect a laptop at boot and take its laptop features unasked, --laptop off to keep them opt-in
A laptop is a FADT Preferred_PM_Profile of Mobile, Tablet or Appliance PC,
or an ACPI battery (PNP0C0A, present by _STA) and lid (PNP0C0D) the power
probe attached. On one, where the line does not say otherwise, the boot
behaves as if --battery, --lid method and --brightness-keys were given, and
--trackpad mt2 where --input is in effect, a precision touchpad is among
the host inputs and the guest's hub has a port left beside its disks.
--lid-sleep stays opt-in. Explicit options win (--test-battery, --lid
ignore, --trackpad builtin), and the new hand-written --laptop auto|off
takes none of them. The battery is still withheld from an install,
restore, staged update, recoveryOS and the plugin repair, and still waits
out a reading at 0%.

The decision runs once the probe has found the batteries, lid and inputs
and before the lid's handler, the input and the trackpad's cabling read
the options; brightness keys taken then are attached in their own bounded
firmware call, as hardware mode attaches them with the option. One line
says what was found and taken, with each skipped feature's reason:
"LAPTOP detected (FADT mobile, battery, lid): battery on, lid method,
brightness keys, trackpad mt2" or "DESKTOP (...): no laptop features".

Setup writes nothing new and the options revision stays 13 (schema 4):
--laptop is a hand-written option setup never writes, as --trackpad is.
2026-11-23 00:20:50 +00:00
Garvit Surana 80fb9a5544 merge fork/wifi-gate: the startup menu offers Wi-Fi only on a PC with a Wi-Fi chip the driver starts (RTL8852CE), from one ID list in the Realtek identity 2026-11-22 23:09:55 +00:00
Garvit Surana d7493d66af feat(setup): say that Wi-Fi works only with an RTL8852CE so far and that other PCs need Ethernet or an Offline installer, wherever a network is set, and that Secure Boot must be off first with the BitLocker recovery key at hand, in the last word of a create, where neither was said 2026-11-22 23:08:22 +00:00
Garvit Surana e54403085b fix(loader): name a display device no recipe covers by its PCI vendor alone, where the boot log called an AMD one the NVIDIA display device (#214, #208) 2026-11-22 23:08:22 +00:00
Garvit Surana d50dde6bfb feat(boot): ask before Install macOS on a PC with no graphics card Stela drives, Back focused and Install anyway one move away, from a PCI census taken at the choice, where the install ran an hour or more and the installed macOS then stopped with 0x11 at its first start (#24, #175, #214, #233) 2026-11-22 23:08:22 +00:00
Garvit Surana 46a0a3bfd9 fix(firmware): an NVIDIA image reads a host firmware bundle manifest of up to 1 MiB and 1024 files, as upstream's gpu/intel does, where a stick an image with the AMD and Intel ports set up lists 468 files in 194 KiB and the NVIDIA image refused it whole, its GSP-RM firmware with it
The minimal part of Tyler Smith's 149725231 (upstream gpu/amd, in
gpu/intel) an image without the ports needs: MAX_MANIFEST_BYTES 128 KiB to
1 MiB, which bounds the bundle manifest, the firmware manifest and the
requirement inventory, and the bundle's MAX_OBJECTS 256 to 1024, with the
three refusals' words. The amdgpu recipes, MAX_IMAGES (the files a boot
reads, which sizes the handoff) and everything else of that commit stay
out.

The experimental build's stela writes a bundle.json of 198,909 bytes and
468 files; this build parses it and finds all 26 GSP-RM images and all 92
of its own files by their digests in it. A test builds a manifest of that
many files beside this build's own and checks the same.
2026-11-22 23:02:57 +00:00
Garvit Surana d705b3c14c feat(boot): offer Wi-Fi at the startup menu only on a PC with a Wi-Fi chip the driver starts, from the firmware's PCI census before ExitBootServices, hiding the Wi-Fi line and W where none is and keeping both when the census is unavailable or incomplete, where the menu offered Wi-Fi from the configuration alone on PCs with no chip or an Intel or MediaTek card the driver cannot start 2026-11-22 23:00:24 +00:00
Garvit Surana 00a787f467 fix(cli): an update makes a boot log too long for the next update's copy of the loader shorter, 32 MiB to the longest of 16, 8 and 4 MiB that leaves it room, with its newest lines and its newest boots' records, where a stick an NVIDIA loader left a 32 MiB log could take an 87.7 MB loader once and never update it again
The EFI partition is 200 MiB and an update writes the new loader beside the
old one before the old one goes. A 32 MiB log only ever grew, so a stick
made with the 54 MB NVIDIA loader kept it after updating to an 87.7 MB
loader with the AMD and Intel ports: 199 MiB less that loader and the log
leaves 83.3 MiB, under the 83.65 MiB the next update's copy needs, and that
update would fail at its loader (the old one kept).

boot_log_bytes now also answers a log that as it is would leave the next
update no room for a copy of the loader and LOADER_MARGIN: the longest of
16 MiB, 8 MiB and 4 MiB shorter than it that does, or nothing where none
does. keep_boot_log writes it with boot_log::relayout, as it makes a log
longer: the stream's newest bytes at their positions, the boot count, and
the records of the newest boots the shorter layout has room for, cut at a
line's end. It still goes through write_atomic before the loader, so a
stick that refuses the shorter file keeps the long one as it was and the
update goes on; the loader's own swap is unchanged. A log that leaves
room, and every NVIDIA-loader stick, keeps its log as before.

Tests: the rule's sizes (an NVIDIA stick's 32 MiB log updated to the 87.7
MB loader becomes 8 MiB; the next update keeps it and has room); an update
over a 32 MiB log of twenty boots in a folder standing in for the EFI
partition, which keeps the newest 7 MiB of its lines and the records of its
eight newest boots, then takes the loader; and a refused shorter file,
which leaves the long log byte for byte. A 4 MiB-boot-log stick, the
options revision and the image's interface are unchanged.
2026-11-22 22:55:11 +00:00
Garvit Surana d82149244e fix(cli): an update makes a boot log too long for the next update's copy of the loader shorter, 32 MiB to the longest of 16, 8 and 4 MiB that leaves it room, with its newest lines and its newest boots' records, where a stick an NVIDIA loader left a 32 MiB log could take an 87.7 MB loader once and never update it again
The EFI partition is 200 MiB and an update writes the new loader beside the
old one before the old one goes. A 32 MiB log only ever grew, so a stick
made with the 54 MB NVIDIA loader kept it after updating to an 87.7 MB
loader with the AMD and Intel ports: 199 MiB less that loader and the log
leaves 83.3 MiB, under the 83.65 MiB the next update's copy needs, and that
update would fail at its loader (the old one kept).

boot_log_bytes now also answers a log that as it is would leave the next
update no room for a copy of the loader and LOADER_MARGIN: the longest of
16 MiB, 8 MiB and 4 MiB shorter than it that does, or nothing where none
does. keep_boot_log writes it with boot_log::relayout, as it makes a log
longer: the stream's newest bytes at their positions, the boot count, and
the records of the newest boots the shorter layout has room for, cut at a
line's end. It still goes through write_atomic before the loader, so a
stick that refuses the shorter file keeps the long one as it was and the
update goes on; the loader's own swap is unchanged. A log that leaves
room, and every NVIDIA-loader stick, keeps its log as before.

Tests: the rule's sizes (an NVIDIA stick's 32 MiB log updated to the 87.7
MB loader becomes 8 MiB; the next update keeps it and has room); an update
over a 32 MiB log of twenty boots in a folder standing in for the EFI
partition, which keeps the newest 7 MiB of its lines and the records of its
eight newest boots, then takes the loader; and a refused shorter file,
which leaves the long log byte for byte. A 4 MiB-boot-log stick, the
options revision and the image's interface are unchanged.

(cherry picked from commit 00a787f467)
2026-11-22 22:55:11 +00:00
Garvit Surana 1a3b81d24e fix(gpu): allow Kept::drain to go unused where only stela-driver-gpu's metal feature is on, as its callers are metal-vulkan's, where cargo clippy --features metal failed on dead code 2026-11-22 22:34:42 +00:00
Garvit Surana dd6e8052f0 merge fork/xid-diagnostics: a lost GPU device logs GPU FAULT lines naming the pipelines its unfinished command buffers bound, each stage's shader program header, code size and SHA-256, through Mesa patch 0043 (NVK reports each shader's program header and code) 2026-11-22 22:34:42 +00:00
Garvit Surana e7b14d5887 feat(cli): name the setup tool stambha, with Stambha in its help, --version, examples, prompts, progress and errors, where every one said stela or Stela
The [[bin]] is stambha, xtask dist prints target/release/stambha, and the
release workflow packages, version-checks and names stambha-v* archives;
its INSTALL notes say ./stambha. --version prints "Stambha 0.5.0" through
clap's display_name. A binary renamed back to stela still runs: clap reads
nothing from argv[0].

On-stick names stay as they were: the STELA volume label, \EFI\stela\,
stela.efi, stela.cfg, the per-user stela cache and Stela temp folder, the
archive comments, the boot log's "Stela boot log: N boots" header and the
mount interface's own message.
2026-11-22 22:26:46 +00:00
Garvit Surana 925e7514c4 feat(boot): say Stambha in what the boot screen shows, where its status lines, notices, stop screens and refusals named Stela and told people to run stela
The renamed text is what a person reads on the screen: status lines, GPU
and memory notices, stop reasons, the installer's disk refusals and the
commands they suggest (stambha repair, stambha log).

Boot log lines stay as they are, tags and text, since tools and people
grep them, and so do names written to disks or shown to macOS: the
"Stela macOS" GPT name, partition names, USB strings and Metal names.
2026-11-22 22:26:46 +00:00
Garvit Surana 3d4377dcd4 feat(boot): draw Stambha's pillar in the boot screen header and name it Stambha, where the menu, disk picker and console showed Stela's blue and orange S
screen::logo_pixel now draws identity/icon/stambha-icon.svg in integers: the
indigo tile with its 0.2 corner radius, the gold-to-saffron dome, abacus,
bell and shaft, two base steps and the pale highlight, each shape exact in
tenths of the icon's 1024 units. It takes a sample of a side-by-side grid
instead of f32 coordinates; ui::Canvas::logo keeps its 4x4 supersampling.

Tests check the transparent corners, the tile's gradient, the dome's top,
the gap under the abacus, the shaft's gold, the highlight and the steps.
A host test renders the logo and the header as the boot screen draws them,
and with STELA_BRAND_SHOTS=DIR saves them as brand-*.png.
2026-11-22 22:26:46 +00:00
Garvit Surana 0d54647214 feat(cli): name a build after its version in stela --version from STELA_BUILD, as 0.5.0 (NAME), so a tester build tells itself apart from a release, the version sticks record staying the package's, where every build printed only the package version 2026-11-22 22:11:44 +00:00
Garvit Surana 5ff29f53ff style(boot): rustfmt engine.rs, engine/host/sampling.rs and engine/run.rs, where the merges of the profiler, AMX and battery branches left them unformatted and the per-crate fmt check failed 2026-11-22 22:08:15 +00:00
Garvit Surana d55887078b merge fork/wifi-menu: the startup menu's Wi-Fi page redesigned as a panel in the menu's look (lock, default and this-boot markers), and each startup-page character drawn as one glyph from the console font's Unicode table 2026-11-22 22:07:34 +00:00
Garvit Surana d026fd36fd merge fork/next @e6e0836e0 into the experimental GPU branch: the nine upstream PRs (#222 #223 #226 #244 #245 #246 #247 #248 #249) beside amdgpu, xe and i915
fork/next moved past fd7b002b6 by its merge of fork/upstream-prs: DesignWare
I2C early STOP, PS/2 ACK before CTR, the fixed-MTRR VGA hole, Raptor Lake
HDA, the TLB mailbox and ITLB fixes, a 1024-entry jump cache and faster
block translation. No file it touches is one gpu/intel changes; the merge
is clean. Interface unchanged (schema 4, OPTIONS_REVISION 13).
2026-11-22 22:07:30 +00:00
Garvit Surana 059d63ddf2 feat(gpu): a lost device dumps the pipelines its unfinished command buffers bound, each stage's shader program header, code size and SHA-256, and the first fault's code in hex, followed by the kernel's first Xid, rc and disabled-channel lines, where an Xid 13 named no shader
nouveau's "Xid:13 Graphics Exception: Shader Program Header N Error"
(upstream #262, an RTX 4060 Laptop on Meteor Lake MS-Hybrid) names the
exception and its ESR words but not the shader, and the loss's refusal
named only the entry points in flight.

The service's description of a loss now ends with a fault dump, logged as
GPU FAULT lines apart from the refusals logged once per text:

- an opening line: the command buffers the GPU was given and had not
  finished, and the pipelines they bound, render pipelines first;
- a line for each stage of each pipeline (at most 8 pipelines, 4 Vulkan
  variants each): its functions, the code's size and SHA-256, NVK's
  instruction, GPR and SLM counts, the header's GPU address, whether the
  upload queue or a CPU mapping wrote the shader, and the 32 SPH words;
- for the boot's first fault only, each stage's code in hex, 64 bytes a
  line, within 32 KiB;
- after the opening, the kernel's first 12 Xid, rc and disabled-channel
  lines of the boot (ESR, chid, exception type) and a count of all of them.

It is always on and bounded, as the loss's other reports are: nothing asks
the driver until the device is lost, and only the boot's first 3 losses
are dumped. NVK reports the header and code through
VK_KHR_pipeline_executable_properties with Mesa patch 0043, which also
changes the pipeline store's compiler key, so the first boot recompiles.
2026-11-22 22:04:02 +00:00
Garvit Surana 7f7259fb45 feat(gpu): NVK reports each shader's program header and machine code as pipeline executable representations, with the header's GPU address and whether the upload queue wrote it, where a release build had no way to show the SPH a GPU rejected
Mesa patch 0043: each executable lists "NAK program header" (the 128-byte
SPH from Turing on; none for compute), "NAK geometry program header" for a
mesh shader that has one, and "NAK binary", whether or not the pipeline
asked to capture its representations. Its statistics add "Program header
address" and "Uploaded by queue" (1 when the shader heap has no CPU
mapping, as on a laptop without Resizable BAR).

It changes libstela-nvk.a and so the pipeline store's compiler key: the
first boot of a build with it compiles its pipelines again.
2026-11-22 22:04:02 +00:00
Garvit Surana 8f2ff76db8 merge fork/bt-bridge: opt-in --bluetooth-lend lends the host's Bluetooth controller to macOS behind the Apple module's model (default-deny opcodes, fallback to the model), --bluetooth-trace logs it masked, and redacted failure lines across vendors 2026-11-22 22:01:24 +00:00
Garvit Surana 679b1a0a1a feat(boot): make the startup menu's Wi-Fi page a panel in the menu's look, with a lock and a default or this-boot marker on each network, a Join other network dialog with a masked password Tab shows, Forget asking first, and a Wi-Fi line on the menu naming the network this boot joins, its model, keys and drawing in stela-boot-core's wifi_page where the host tests check them
The menu's bottom line reads "Wi-Fi: <network> · press W to change": the
network the page chose, else --wifi's, or "not set up" when the USB holds
wifi.saved but no entry sets --wifi, where W now opens the page to save or
forget a network (Enter cannot choose one: --wifi-prefer needs --wifi, so
with_prefer is unchanged). Delete or Backspace asks "Forget <name>? Enter to
confirm, Esc to cancel". The dialog keeps a refused name or password for
editing with the reason in red, where it closed and lost both; a saved line
whose key a boot cannot use is marked "key unusable". The password buffer
is never reallocated, and the drawn text is wiped once painted.
2026-11-22 21:44:01 +00:00
Garvit Surana 27ff6326ba fix(boot): draw each character of the startup pages as one glyph from the console font's Unicode table, parsed in stela-boot-core's psf where the host tests reach it, where Canvas drew each UTF-8 byte past ASCII as its own ?, so the Wi-Fi page's password dots showed as ??? and a network named Café as Caf?? 2026-11-22 21:44:01 +00:00
Garvit Surana 32b361e88a fix(drivers): print a Bluetooth controller's bytes in no failure line, Display or Debug: a Qualcomm controller dump's packet, a Broadcom PCIe frame, event and return, an Intel PCIe frame, a Realtek response and a MediaTek dump show their lengths, an Intel identity's or boot parameters' address its vendor half and last byte and its TLVs their lengths, and every initializer's failure and the lent controller's transport errors print any other byte list as its length, where BLUETOOTH FAILED lines printed controller RAM, which can hold link keys, raw frames that can name neighbours, and the controller's full address through Debug 2026-11-22 21:17:44 +00:00
Garvit Surana 4594332f15 fix(boot): say why --bluetooth-lend lends nothing when the boot has no --input or no host Bluetooth controller started, as it already said for --idle-skip, where the flag was dropped without a word 2026-11-22 21:16:21 +00:00
Garvit Surana cabf150f37 fix(bluetooth): hide every captured byte past the length a packet's header declares, the extended inquiry or advertising data from a structure that runs past the data's end, and all but the count of an event with several inquiry results or advertising reports, where the capture's rules showed trailing bytes to the frame's end, read a bad length's following bytes out of step as plain structures, and assumed the reports' arrays came device by device, which would show another device's address bytes if they came parameter by parameter 2026-11-22 21:15:09 +00:00
Garvit Surana ac6a2a87f1 fix(bluetooth): refill the --bluetooth-trace capture's budget of 1024 packets at most for the boot's first 4 configurations, and say once when the boot's capture is over, where every new configuration refilled it, so a guest that configured the function again and again filled the boot log without end 2026-11-22 21:14:32 +00:00
Garvit Surana 98cabd3f1b fix(bluetooth): fall back to the model when the lent controller reports a Hardware Error, which the guest never sees, send the controller a listed command only with its specification's parameter length, drop the controller's ACL data, as milestone 1 lends no connection, and say the deadline and the restarts in the log from the constants the bridge uses, where a Hardware Error passed to bluetoothd while the bridge kept forwarding, a listed command of any length reached the controller, its ACL data could reach the guest under a handle the shadow owns, and the log said 1 s and twice whatever DEADLINE and RESTARTS were 2026-11-22 21:13:39 +00:00
Garvit Surana fca12c8b79 fix(bluetooth): print the always-on GUEST BLUETOOTH command trace's first parameter bytes as the capture masks the whole command, a hidden one as xx, so Write Local Name, the module's Write BD_ADDR, Remote Name Request and LE Encrypt show no name, address middle or key, where every boot's log carried the first four raw parameter bytes of the guest's first 48 commands of each configuration 2026-11-22 21:12:49 +00:00
Garvit Surana 5175697fd6 merge upstream/gpu/intel (with gpu/amd) into the experimental GPU branch: amdgpu+RADV and xe/i915+ANV beside NVK, the memory plan holding main's code budget, the pack's room and --code-window together with the integrated-GPU share, the display reserve and the fallback room
upstream/gpu/intel @164d332ee holds all of gpu/amd @eca683096: 181 commits
by Tyler Smith past main. Eleven files conflicted; five are upstream's own
(main against gpu/intel), six are the fork's.

Memory plan (upstream):
- host_memory.rs: sizes() takes gpu/intel's GpuPlan and plans through
  plan(); main's code budget is applied to every estimate inside plan
  (budgeted()), so the GPU's share, the apertures' tables and the fallback's
  room are planned against the heap the boot runs with. Applying it after
  plan() would shrink the heap under a fallback reserve sized for the
  larger one. sizes_with_room() takes the GpuPlan; pack_budget()'s fallback
  lack reads the budgeted heap too. The fork's with_window() is unchanged.
  With GpuMemory::Own and no fallback the plan is main's exactly.
- host_memory/tests.rs (33 hunks): the base suite keeps main's pre-budget
  staged() split over GpuMemory::Own; main's code-budget, small-host,
  --code-window and pack-room tests and all of gpu/intel's GPU-plan tests
  are kept. Five gpu/intel tables were measured before the budget and are
  recomputed: heap and code move by the same bytes, the pool, guest and
  GPU share do not; the fallback room grows on small hosts and every host
  keeps its 768M bound; NVIDIA's 16 GiB numbers are main's own
  (small_hosts_move_their_kept_code_into_the_window).
- system/memory.rs: one HOST MEMORY line with both sides' fields (window,
  kept, gpu, aperture, pages, fallback); the page bound is taken after
  --code-window; EngineMemory keeps kept_code and the GPU fields.
- system.rs: both destructured field sets and the handoff's union.
- engine/gpu/gate.rs: main's unmapping of a failed service's stack with
  gpu/intel's Result and its refusal of a stack that did not run; the
  services' GPU names (main) follow the spliced served list, so a
  fallback's services keep their names.

- xtask/src/gpu/radv/metal.rs (merged clean, built broken): gpu/intel's
  RADV host harness builds the Metal compiler Service without main's
  compose_kernel (0ae834ade); it now resolves stela_metal_compose_kernel
  from the hosted library as the linked path does.

The fork's (union, nothing dropped):
- handoff.rs: low_dma and wifi_saved beside gpu_share, gpu_pages,
  gpu_pages_held and gpu_census.
- stela-cli/Cargo.toml: intel-port beside the trackpad's workspace-check.
- bundle.rs: gpu/intel's cfg-gated slice with the fork's Realtek
  Bluetooth family.
- bundle/tests.rs, setup/firmware.rs, setup/tests.rs: BASE is the fork's
  92 files and 188,455,525 bytes (upstream's 88 and the Realtek files), so
  BUILT_BUNDLE is (468, 245.8) with both ports, (441, 240.3) AMD only,
  (119, 185.2) Intel only and (92, 179.7) without.

Interface unchanged: bundle schema 4, OPTIONS_REVISION 13, NOR 0x800000,
SEP 0x10000, boot bundle REVISION 39 on both sides.
2026-11-22 21:01:46 +00:00
Garvit Surana e6e0836e03 merge fork/upstream-prs: nine upstream PRs (#222 #223 #226 #244 #245 #246 #247 #248 #249): DesignWare I2C early STOP, PS/2 ACK before CTR, fixed-MTRR VGA hole, Raptor Lake HDA, TLB mailbox and ITLB fixes, a 1024-entry jump cache, faster block translation 2026-11-22 20:36:32 +00:00
Garvit Surana fd7b002b6d test(xtask): bind the AMX cost table's opt-in test to the oracle manifest where it now lives, costs in crates/stela-compiler/tests/amx_native/costs.rs, with the canonical manual: opt-in reason, where the manifest still named native_and_model_costs in src/amx/native.rs, which fork/amx removed, and manifest_covers_every_ignored_test_in_tracked_sources failed 2026-11-22 19:53:38 +00:00
Garvit Surana 8cd2398dbe merge fork/amx: AMX native kernels for most register-op forms (vecfp, matfp, mac16, fma16/32/64 modes), --amx-native on|off|off:OPS to leave all or named ops to the reference model, per-form counts under --profile 2026-11-22 19:53:27 +00:00
Garvit Surana c4d75aea67 style: rustfmt the PS/2 controller's read past an ACK (upstream PR #226) and the mailbox bridge test, where cargo fmt --all --check failed on both 2026-11-22 19:52:42 +00:00
Garvit Surana 0e458bf4e7 test(compiler): opt-in checks of every 32-bit word at five PCs that the direct integer path goes past no decoder of the lift or of the block parse that would take the word, where upstream PR #247's own tests sample a million words and its full check was never committed
every_direct_word_skips_every_decoder_before_the_integer_one and
every_direct_word_skips_the_block_decoders run on all host threads in
release, at PCs 0, 0x1000, a user and a kernel address and the highest
word, where branch and literal targets overflow. They are the proof to
rerun when a decoder is added before the integer one or to the parse.
2026-11-22 19:52:01 +00:00
justpainful 84a3106593 perf(compiler): translate blocks 32% faster with byte-identical code
Profiled on 8 MiB of the macOS 26B123 kernel's __TEXT_EXEC (269,195
blocks): decoding took 23% (the common integer, load/store and branch
classes reached their decoder after ~25 refusals), allocation 18% (the
block buffer and parse list grew from empty; link-slot checks allocated),
and the vector cache rebuilt its occupied mask on every `Code::asm`.
- `skips_decoders` routes the common classes straight to their decoder
  in `lift` and the block parse (STGP excluded: the parse takes it as a
  tag access); the parse reserves 24 instructions;
- the block buffer starts at 1 KiB (`Code::new`), fault sites and
  relocations at 8;
- the vector cache keeps `held` current, so `occupied` does not scan;
- `jump`/empty-link checks no longer allocate.
compile-throughput: 4368 -> 2972 ns/block; native_bytes unchanged
(87196315); the --emit dump of every block is SHA-256-identical, and the
new `lift` matches the old for all 2^32 words at 5 PCs. Linux: compiler
1568 passed, engine 1921 passed, 0 failed.

Rebased by Garvit Surana onto Stambha's base (upstream main of 11-20):
kept the direct integer path (skips_decoders, lift_direct, lift_integer)
in Decoder::lift and in the parse's Words::decode, the parse's room for
24 instructions, the 1 KiB buffer and room for 8 sites and relocations,
and the next instruction's vector use kept for its turn. Dropped as
upstream already covers them: the link slot, patch jump and empty-link
helpers (329b54fc3 writes them on the stack), the vector cache's held
mask (96fb55ad3 asks it only where needed, and occupied() returns early
when nothing is held), and the block buffer from Code::new (Code::asm
reserves room at a buffer's first instruction). Dropped as they no longer
fit: the padding byte filters of exit_word_of and is_direct_exit, whose
byte offsets upstream's exit layout (290ba1138) moved.

(upstream PR #247 by justpainful)
2026-11-22 19:38:26 +00:00
Garvit Surana 5a81c900fd test(xtask): the oracle manifest names stela-engine's run_loop_costs, upstream PR #246's opt-in run loop timing, where manifest_covers_every_ignored_test_in_tracked_sources failed on its unbound #[ignore] 2026-11-22 19:03:22 +00:00
Garvit Surana d1cb43c865 test(engine): the run loop's timing reads the fake host's real_counter, the TSC upstream's fixture already gives host timing benches, where upstream PR #246 added a second stamped counter beside it
lock_path_costs times eight PEs on real_counter; run_loop_costs set its
own stamped flag to read the same TSC shifted seven bits. One switch is
enough, and the bench was rerun on it: every timing makes its two million
runs, one block a run.
2026-11-22 19:02:55 +00:00
justpainful 5e23b4a28f perf(engine): borrow the parallel hub around a step instead of cloning it
`step` cloned the hub's Arc around `act_on` on every run: a locked
increment and decrement of one reference count every PE wrote at each
of its runs, a cache line the PEs then passed between them. perf put a
quarter of a run's cycles there with two PEs or more. The hub is now
borrowed before the act and again for `leave_active`; a machine's hub is
set once (`enter_parallel`/`start_parallel` refuse one that has it) and
nothing the act does takes it. No memory ordering changed.
New ignored `run_loop_costs` benchmark, ns per run (mean of 3):
br 2 PEs 234 -> 192, 4 PEs 274 -> 196; mrs+br 2 PEs 277 -> 210,
4 PEs 302 -> 230. Linux: engine 1921 passed; parallel x20 clean.

Rebased by Garvit Surana: the fake host's counter keeps upstream's
real_counter ahead of the stamped one this adds.

(upstream PR #246 by justpainful)
2026-11-22 18:58:47 +00:00
justpainful ca4eb6326f perf(engine): a full ITLB set puts out a dead context's page first
`LookupTable::insert_over` treats an entry whose context no lookup
reaches any more as a free place: the resident moves over a dead
neighbour, and a dead resident is the one out, before a live entry is
put out at random. A busy desktop's ITLB evicted live pages while dead
contexts' entries sat in their sets (16% of its misses). The eviction
counter no longer counts a live entry as lost when the dead resident
leaves. stela-engine on Linux: 1921 passed, 0 failed.

Rebased by Garvit Surana: insert_over keeps upstream's removal of the entry's
older self beside it (6a1fe6e33) ahead of the dead-context rule, so
keep_resident is beside empty, older self or dead, then dead resident out.

(upstream PR #248 by justpainful)
2026-11-22 18:57:04 +00:00
justpainful 817e589e29 perf(compiler): a 1024-entry jump cache per PE
A lookup site over many targets (returns and indirect calls into shared
libraries) missed the 256-entry jump cache for most transfers and went
through the table probe: `transfer_path_costs` over 1024 targets ran
14.4 ns a transfer with 0.75 table probes; with 1024 entries 8.8 ns and
none (4096 gains nothing more). 64 KiB a PE; `forget_all_jumps`, the one
whole-cache walk, runs only on a table clear. Linux: engine 1921,
compiler 1568 passed, 0 failed.

(upstream PR #249 by justpainful)
2026-11-22 18:55:38 +00:00
Garvit Surana 1b36715e99 fix(engine): a full mailbox's merge is a bridge across a PE's global pages by the granule of the smallest global leaf it took, where a fixed 16 KiB granule hid a 4 KiB global page between the TLBIs of the pages on its two sides and the merge dropped it
A TLBI by VA removes the whole leaf at its address. Of 4 KiB leaves, the
TLBIs of the pages at 0x1000 and 0x3000 leave the global page at 0x2000,
but their merged range takes it in, and bridges() rounded both spans to
16 KiB and saw nothing between them. That is the finding an automated
review left on upstream PR #245, which the PR never answered. A fixed
4 KiB granule would instead count neighbouring 16 KiB pages, as macOS
maps them, as a bridge where the merge adds no entry. GlobalSpan now also
keeps the smallest leaf widen() took in, and bridges() rounds to it: a
global leaf the merged range reaches and neither TLBI does is at least
that size and aligned to it, so it lies between the granules the two
spans touch. Perf only: every kept scope still covers the TLBIs it
stands for, whatever the granule.
2026-11-22 18:55:26 +00:00
justpainful ff9a535a71 perf(engine): a full TLB mailbox merges no scope across the PE's global pages
Once a PE's mailbox held 256 scopes, a new TLBI merged with the narrowest
of the last 16 at any distance, so an ASID-tagged scope below the shared
region and one above it became one range over it; global entries match
any ASID, and the mail read dropped every global ITLB entry the PE held
(about 874k drops per 10 s per PE on an i7-12700KF desktop, mostly on
idle PEs). Merges now prefer one that leaves the PE's lower-half global
span alone, falling back to the old choice; every kept scope still
covers the TLBIs it stands for. Two-PE benchmark: drop_global and
refills 1280 -> 0. stela-engine on Linux: 1921 passed, 0 failed.

(upstream PR #245 by justpainful)
2026-11-22 18:51:38 +00:00
Garvit Surana 1641ec31df perf(compiler): trim AMX native dispatch: lane masks and Y-row sets with every lane on (most operands) without a loop, copies and constants stored as whole rows then, rows of lane values built a word at a time, and plain vecfp/matfp operands staged with no shuffle or index calls, where every operation built its masks lane by lane and splat built rows byte by byte
Plan task 20 (no new coverage; the harness guards every path). Release
timings on the 8940HX (ns per Native::execute, FMA3/AVX-512F, before ->
after): fma32 vector 48/48 -> 18/18, fma32 matrix f16-Y 68/64 -> 29/35,
fma64 matrix 43/39 -> 22/21, matfp f32 81/77 -> 29/27, vecfp f32 48/47 ->
25/25, fma16 widened clear (mode 7) 200/198 -> 58/59, fma32 constant
(mode 7) 170/175 -> 107/108.

Translator id: changes (stela-compiler source).
2026-11-22 18:44:33 +00:00
Garvit Surana d78c4bf2f5 perf(compiler): run the AMX vecfp multi-row form (bit 31, M2-M4) natively row by row as the model loops, every 32nd or 16th Z row, each broadcast of bits 34:32 (zeros, one X or Y row, zero X or Y, X lane 0, Y lane 0), indexed steps and the M4's aligned offsets from the model's own aligned_multiple_offset, with the whole operation's coverage decided before its first row, proven bit for bit over random operands in M2-M4, where multi-row vecfp went to the model
Plan task 17. The routine's block test now takes matfp, not vecfp, as the
operation the model tier leaves to the model (vecfp's bit selections run
on every tier).

Translator id: changes (stela-compiler source).
2026-11-22 18:33:41 +00:00
justpainful f21c28f754 fix(audio): keep refusing a GTS unit with a nonzero descriptor count
The walk measures GTS as its fixed 0x40 bytes. A nonzero descriptor
count makes the unit longer, so a later capability inside that tail
would pass the overlap check, and if it decoded as ML its LCTL could be
written there. Until the descriptor geometry is known, such a layout is
refused again; the version-0 headers and the skipped alternate links
stay accepted.

(upstream PR #244 by justpainful)
2026-11-22 18:29:51 +00:00
justpainful dbb879a83e fix(audio): a Raptor Lake HDA's version-0 capability headers start it
8086:7a50 reports its multi-link capability header as version 0, which
the preflight refused, so no HD Audio controller started ("HOST DEVICE
FAILED ... UnsupportedExtendedCapability { id: 2, version: 0 }"). Linux
never checks the version. GTS geometry is never touched, and only the
first link is clocked, so later alternate links are left alone.

(upstream PR #244 by justpainful)
2026-11-22 18:29:51 +00:00
BluePhi09 95e216ad43 fix(boot): the BSP's fixed MTRRs are admitted when firmware leaves the legacy VGA hole write-back with MMIO routing, as Linux runs with them, where Stela stopped with 'unsupported BSP memory-type register fields' on a Lenovo IdeaPad Pro 5 16AKP10 (Ryzen AI 7 350)
(upstream PR #222 by BluePhi09)
2026-11-22 18:29:51 +00:00
BluePhi09 6c841def87 fix(ps2): a controller config write the embedded controller acknowledges with an ACK ahead of the CTR is read past that ACK, where the PS/2 keyboard of a Lenovo IdeaPad Pro 5 16AKP10 was left out with ControllerReply { command: 96, received: 250 }
(upstream PR #226 by BluePhi09)
2026-11-22 18:29:51 +00:00
BluePhi09 f1fb28a30c fix(i2c): a STOP the DesignWare controller reports before any command of the transaction is queued is cleared and ignored, where an AMD I2C HID touchpad (Lenovo IdeaPad Pro 5 16AKP10) failed with UnexpectedStop right after enable and was left out
(upstream PR #223 by BluePhi09)
2026-11-22 18:29:51 +00:00
Garvit Surana 7c14354a59 perf(compiler): run AMX vecfp and matfp natively with shuffled operands and indexed loads, X and Y staged by the model's own shuffle and load_indexed (the ALU mode 0 that an indexed load forces included), then the native arithmetic, proven bit for bit over random operands in M1-M4 with floors for shuffled, indexed-X and indexed-Y forms, where both were left to the model
Plan task 16.

Translator id: changes (stela-compiler source).
2026-11-22 18:24:18 +00:00
Garvit Surana fa838295db refactor(compiler): expose the AMX model's operand staging helpers (shuffle, load_indexed, aligned_multiple_offset) to the crate, with no change to what they do, so that native paths stage X and Y with the model's own byte movement
Translator id: changes (stela-compiler source).
2026-11-22 18:16:29 +00:00
Garvit Surana 42210bff27 perf(compiler): run AMX vecfp natively on every IEEE type in one Z row, modes 0/1 and from the M2 10-12 (x*y, z + x, z + y) through the f16 rows with F16C, the FMA row kernels for f32/f64 and a widened vector row for f16-into-f32, and modes 4, 5 and 7 (select, FMIN, FMAX with the default NaN and -0 below +0) as integer bit selections on every tier, with broadcast Y lanes and the zero and zero-operand lane values, proven bit for bit over random operands in M1-M4 and rotated special values, where only f16 modes 0/1 ran natively
Plan tasks 14-15. Refused, before any write: bits 56:54, indexed loads,
shuffles, the M2's multiple rows, the model's no-op modes (10-12 on M1),
bf16, and arithmetic a tier cannot do exactly. Release timings on the
8940HX (ns, model vs FMA3 vs AVX-512F): f32 627/48/47, f64 multiply
290/33/33, f16 multiply 1108/29/26, f16 min 710/175/178; matfp's
selections now use fixed-size lane copies too (f32 select 4380/159/160).

Translator id: changes (stela-compiler source).
2026-11-22 18:14:52 +00:00
Garvit Surana 99cf7b77a2 merge fork/battery: opt-in --battery gives the guest's SMC the host's ACPI battery and AC adapter, --test-battery PERCENT,STATE a synthetic one, never for installs, restores, updates or recoveryOS 2026-11-22 18:03:32 +00:00
Garvit Surana 1d2e039323 perf(compiler): run AMX matfp natively on IEEE types on the FMA3 and AVX-512F tiers, f32 and f64 through the FMA kernels, f16 and f16-into-f32 (type 3) through the f16 and widened rows with F16C, modes 0/1, with mode 4 (x <= 0 ? 0 : y by IEEE order on the bits) and the zero-writing lane value as bit selections and the zero-operand values fed as zero rows, proven bit for bit over random operands in M1-M4 and rotated special values, where matfp always ran on the model
Plan tasks 11-13. Refused, before any write: bits 56:54, indexed loads,
shuffles, modes other than 0/1/4 (the model's no-ops), bf16 and the
model tier. Release timings on the 8940HX (ns, model vs FMA3 vs
AVX-512F): f32 12329/81/77, f64 3020/50/47, f32 select 5187/292/292,
f16 46982/812/697, f16-f32 114634/376/377. The engine's profiling test
now takes vecint as its model-only operation.

Translator id: changes (stela-compiler source).
2026-11-22 18:02:10 +00:00
Garvit Surana f7db19a5d9 feat(hle): a guest access's fault inside a composite's fast path puts the call back at the function's entry as the fast path found it and runs the original's first instruction alone, so the original takes the fault, where such a fault stopped the PE as a native failure with no recovery row
native_fault first asks hle_fault: for a block with an HLE mark, a fault
at an offset before the mark's prefix end, from an x86 exception that is
a guest access's as native_fault judges one (a #PF with a plain
read/write error code, or a #GP/#SS of a non-canonical address), settles
the run as native_fault does at the block's first instruction with none
of it retired: pinned::settle over a copy of the state, the chain's
retired instructions added, the PC at the entry, a link's BTYPE applied.
The fast path writes no guest register or frame field before its commit
point, so that is the state the call entered with. It then sets the
bypass and counts it. The scheduler's step takes the bypass beside PACM
(always evaluated, so a stale one is cleared) and fetches the entry as a
single-instruction block: the original runs from its first word and
takes the fault itself, with ESR, FAR, ELR and state as without HLE. A
fault in the bail's code keeps its moved recovery row; any other trap in
a fast path still stops the PE.

The plan bypassed #PF only; accepting the non-canonical #GP/#SS too keeps
a fast path exact where the placement's limit lies past the host's
canonical range (the test host's five-level limit on a four-level host),
the faults native_fault already accepts at a guest access.

Tests: Touch with X0 unreadable equals the original in full and bypasses
once; three such calls on one machine bypass three times and stay exact;
every readable/unreadable/read-only combination of X0 and X1 agrees;
4000 random Touch cases bypass exactly when X0's page is unreadable;
pointers at or past the limit, tagged or in the upper half bail without
a fault, an unmapped one in range bypasses; software step never matches;
a reused session runs as a fresh machine with Touch on as well, and no
call with every page mapped bypasses. Mutations caught: no hook, no
prefix bound, no bypass taken.

Translator id unchanged: engine glue and tests only.
2026-11-22 17:57:06 +00:00
Garvit Surana 176fcf2923 merge fork/wifi-saved: the hardware-proven Wi-Fi install fixes (32-bit DMA below 4 GiB, low DMA pool, longer range retries), macOS gets the Wi-Fi adapter, saved networks (wifi.saved) and the startup menu's Wi-Fi page (--wifi-prefer) 2026-11-22 17:53:03 +00:00
Garvit Surana 06aa8c1ea4 merge fork/trackpad: an opt-in emulated Magic Trackpad 2 fed whole precision-touchpad frames (--trackpad mt2|builtin with --input), options revision kept at 13 2026-11-22 17:52:57 +00:00
Garvit Surana 472f8baf5a perf(compiler): run AMX mac16 natively on the AVX-512F tier in vector, matrix and bit-62 widened shape, every operand (int8 X/Y, each selection of bits 29:28, the shift of bits 59:55, with or without Z, every lane-enable mode), with AVX-512F alone: lanes in i32 with Z's wrap, the selection as a product with 1 or 0, opmask lane enables, proven bit for bit over random operands in M1-M4 and every pair of i16 and int8 edge values in every field, where mac16 always ran on the model
Plan tasks 8-10. Release timings on the 8940HX (ns, model vs native):
vector 56 vs 17, matrix 796 vs 397, widened matrix 786 vs 321. The FMA3
tier still leaves mac16 to the model.

Translator id: changes (stela-compiler source).
2026-11-22 17:47:36 +00:00
Garvit Surana 3626235b46 merge fork/bt-rtl8852c: RTL8852CE USB Bluetooth bring-up (identity, EPATCH v2/v1, pinned rtl_bt firmware, 0xfc66 drop) and the --host-check --bluetooth-check / --keep-lines check 2026-11-22 17:45:10 +00:00
Garvit Surana 976aa6450b feat(hle): install a composite block at a matched function's entry, its first word compiled alone as the bail behind the routine's fast path, with a mark of where the fast path ends, where a match was only counted and the function translated
hle_compile now installs what it accepts (install_hle, after
install_device_stub): a copy of the entry's first word is admitted and
prepared alone in the compile's variant; anything but one instruction's
block counts the bail refusal, a refused layout the compose refusal, and
either is translated as before. The composite's emission holds that word
as its input and installs through Machine::install as a block of one
instruction at the entry's PC and frame, so the board indexes it, links
into and out of it and retires it as any block (an IC IVAU of any word of
the function retires its page's blocks), and nothing stores, offers or
rebases it. Its Block holds hle::Mark, one byte with a niche (the fast
path's length in 64-byte units), set from State::installing as a device
stub's flag is; Block stays within its 72-byte bound. The mark is read by
the fault bypass that follows (expect(dead_code) until then). The plan's
mark held the routine too; nothing reads it, so it is left out.

Tests: a Bail composite at every stand-in, entered directly and through
blr x16 on a guarded page, ends every call exactly as the original
(4000 cases each, a sixteenth through blr), installs and never bypasses;
a composite is installed once and reused; Touch with X1 unreadable takes
the original's fault through the bail's moved recovery row. A match
whose routine has no fast path yet (memmove) is refused as compose and
translated with the same blocks as off.

Translator id unchanged: engine glue and tests only.
2026-11-22 17:43:29 +00:00
Garvit Surana 32fcffb633 perf(compiler): AMX f16 rows (vecfp f16, fma16/fms16 vector and f16 matrix) in EVEX.512 on the AVX-512F tier, sixteen lanes per step with opmask lane enables that merge old Z as dwords and narrow back to halves, the same TwoSum round-to-odd algorithm proven bit for bit against the model and byte for byte against the VEX kernel at ties, and each operation's lane masks built once and its broadcast Y rows by the word, where every row ran four lanes per step with byte blends and rebuilt its masks
Release timings on the 8940HX (ns per Native::execute, VEX vs EVEX in one
run): fma16 matrix 634 vs 609, vecfp f16 broadcast 29 vs 27, fma16 vector
27 vs 24 (fma16 matrix was 679/684 before). The f16 row is bound by the
TwoSum chain's latency, not its width, so the gain is small.

Translator id: changes (stela-compiler source).
2026-11-22 17:38:33 +00:00
Garvit Surana f6042f296e feat(hle): composite blocks of a native fast path and the function's first instruction compiled alone, with the Bail and Touch test routines, a range check that subtracts and clamps past each branch, and a direct success exit to the original's ret, where no block could run a native routine in a function's place
stela_compiler::x86_64::hle::compose lays out a Request (routine, entry
PC, exit ret, max_bytes) in front of the bail, the entry's first word
compiled alone as the engine compiles a block: bytes [0, prefix_end) are
the fast path, built pinned with the block's link slots and padded with
INT3 to a multiple of 64; each bail is a jmp rel32 to prefix_end; from
prefix_end the bail's code follows unchanged, its direct exits, fault
recovery rows and cold code moved by prefix_end, which keeps their patch
points' residues mod 8, and align_exits runs over the whole. The
composite is one instruction: source_bytes 4, relocations None, no
self-loop or region.

emit.rs: Bails, checked() (xor edx; rax = lower_limit - base, bail on
BE; cmp rax, n, bail on B; after each branch a CMOV of the same flags
makes the dereferenced register and n 0, no LFENCE) and success() (a
Direct exit with its forward link slot). Bail's fast path is one jump to
the bail; Touch's checks X0 for one byte, loads it into EAX and bails,
followed by a success exit no path takes, for its layout's tests. The
production routines are refused (NoNative) until their fast paths land.

Two deviations from the plan, both forced by the engine: the source map
is [(pc, 0)] alone, since place() requires one entry per source word and
a second (pc, prefix_end) entry would make the one word two instructions;
and of the three const assertions only the pinned map (X0 in R15, X1 in
RBP) and the frame's X array at offset 0 are const, as link_slot and
offset are not const fns (chain.rs and x86_64.rs stay untouched): tests
pin the forward link slot and X2 at frame byte 16. compose also refuses
a fast path past 255 * 64 bytes (PrefixTooLong), the most the engine's
one-byte mark names.

Translator id CHANGES (crates/stela-compiler/src): together with the
previous commit's move, one refill of the translation store.
2026-11-22 17:36:40 +00:00
Garvit Surana b3cd128715 refactor(hle): move the routine ids into the compiler, beside the composite blocks it will lay out for them, where compose() in stela-compiler could not name an engine type
stela_compiler::x86_64::hle::Routine is the enum that was
stela_engine::hle's routine module, unchanged: the five production
routines and, under test or test-support, Bail and Touch. The engine
re-exports it as hle::Id, and its test-support feature now enables the
compiler's so the test routines exist wherever the engine's do. The
names test moves with it.

Translator id CHANGES: crates/stela-compiler/src is fingerprinted
(STELA_COMPILER_SOURCE_SHA256), so a pack made before this commit is
stale. The composite's emitters land in this same compiler module next,
so an image built from the finished branch refills the translation store
once, as the plan's section C expects.
2026-11-22 17:31:40 +00:00
Garvit Surana ad20c92307 perf(compiler): run AMX fma16/fms16 product-only, z ± x and z ± y (bits 29:27 of 1, 2 and 4) natively with F16C in vector, f16 matrix and bit-62 widened matrix shape, the product added to -0 and the adds multiplying by 1.0 so each still rounds once, proven bit for bit over random operands in M1-M4 and every pair of special halves, where only mode 0 and the copies ran on the host
Translator id: changes (stela-compiler source).
2026-11-22 17:28:36 +00:00
Garvit Surana cea2a5f852 feat(hle): match signed functions at compile time behind a default-off configuration, once per compile, and count the matches and the refusals of a function that crosses its fetch page, starts at a device site, holds a host breakpoint or trace point or holds a word the chip runs as another, where no compile looked for a signed function
Machine::set_hle takes a Config and hle_statistics reports what it did
(hle::Statistics: matched, the signatures that matched, installed,
bypassed and refusals by reason). compile_window calls hle_compile after
it reads the source and before it looks for a stored, shared or rebased
block. With no routine enabled it returns at once, so a boot without
--hle compiles exactly the blocks it did before (pinned by
hle_off_compiles_the_same_blocks_as_without_it, also for --hle with the
empty generated table). Only an EL0 compile of an ordinary variant
looks: not single-step, translated, DIT-timed or streaming, with FP on and
no alignment checks. A candidate's prefix hash is checked at its own
length, then its digest over the bytes of the window or, for a function
longer than it, of RAM. Only the first window of a compile looks, so the
whole-window compile that may follow does not count the same match twice.
Nothing is installed yet: a match is translated as before.

Beyond the plan's five refusals there is a sixth, admitted: a function
holding a word the chip lacks (Chip::admit makes it UDF or a NOP) is
refused, as the original would not run the bytes its signature was made
from.

The harness's Session::new and run take an Option<Config>, run returns
the run's Statistics, and a reused session runs as a fresh machine with
HLE on (Bail for every stand-in, Touch for touch's) as well as off.

Translator id unchanged: src/hle and the engine glue are not translation
inputs.
2026-11-22 17:27:14 +00:00
Garvit Surana cbc682f328 perf(compiler): run AMX fma32/fms32/fma64/fms64 z ± x and z ± y (bits 29:27 of 2 and 4) natively on the FMA3 and AVX-512F tiers, as a multiply-add by 1.0, whose exact product makes the sum round once to the model's add or subtract, signed zeros and default NaNs included, proven bit for bit over random operands in M1-M4 and every pair of special f32 and f64 values, where both modes went to the model
The native module's doc now lists the copies and constants every tier
completes, and Native::MODEL's says it still completes them (it said no
host path at all). Its inline unit tests, which the differential
harness re-expressed with the same seeds and floors, are removed; the
one without a counterpart moves to tests/amx_native/refusals.rs.

Translator id: changes (stela-compiler source).
2026-11-22 17:22:48 +00:00
Garvit Surana bcbccd4c21 feat(boot): --amx-native off:OPS leaves only the AMX register operations it names (corsix mnemonics, comma separated, such as off:fma16,vecfp) to the reference model, in blocks and in the service on every PE, with an AMX NATIVE line naming them, so that a guest misbehaving under host kernels can be narrowed to one operation, where the switch was all or nothing
Translator id: unchanged (no compiler source or engine translation input
changed).
2026-11-22 17:17:09 +00:00
Garvit Surana 1ba4a1ea2f test(hle): compare PSTATE and an abort's SPSR, enter the stand-ins through a blr x16 on a guarded page, check X0 against the reference model and start each call of a session with BTYPE 0 and clear syndrome registers, where the harness compared neither BTYPE nor SPSR, entered every call by setting the PC and checked only memory against the model
An Outcome now holds PSTATE, and an abort ESR, FAR, ELR and SPSR_EL1.
StandIn::through_blr appends a `blr x16` after the function and guards
the code mapping (store_host's NativeHost::guard sets GP, bit 50, in its
stage-1 descriptors): memset's `bti c` admits the call's BTYPE 0b10 and
runs as the model says, every other stand-in takes a Branch Target
exception at its entry with BTYPE in ESR and SPSR. A session's call clears
BTYPE, which the abort's ERET brought back from SPSR, and ESR, FAR, ELR
and SPSR, which a Branch Target exception leaves partly as they were, so
a reused session still runs as a fresh machine, now also through blr.
agree() requires PSTATE equal and X0 as the model gives it.

Translator id unchanged: tests only.
2026-11-22 17:14:05 +00:00
Garvit Surana 4dc2b4240f fix(hle): tell an outside branch from a branch to itself, refuse a function that can run past its last word, and refuse reserved words and ordered or tag accesses, where an outside b masked to the word of b . in the digest, a function ending in a NOP or B.cond was eligible and LDAPUR, STLUR, UDF and AMX words were too
The digest now follows each masked word with a byte that says whether
it has a masked field, so a candidate whose word is a branch out of the
function no longer matches a signed function holding `b .` there; the
prefix hash stays a filter. Eligibility refuses a last word other than
`ret` or an inside `b` (FallsThrough), every word with bits 31:25 clear
(Reserved: UDF, AMX's 0x00201000 | op << 5 | Rt, GXF and the SPTM's
maintenance words), and as Exclusive the RCpc forms with an offset or
writeback (LDAPUR, STLUR, their SIMD&FP forms, RCpc3), LSE128 and the MTE
tag accesses of that class. The stand-ins pad with NOPs before their last
`ret` instead of after it.

Translator id unchanged: only crates/stela-engine/src/hle (not a
translation input) and tests change.
2026-11-22 17:10:39 +00:00
Garvit Surana 75104de5a6 fix(engine): --amx-native off leaves every AMX register operation to the reference model, copies and constants included, in blocks through an engine routine that runs the model alone (counted by form under --profile) and in the service, which skips the host paths, where the model tier's paths still completed fma32/fma64/fma16 modes 3, 5, 6 and 7 on the host and the AMX NATIVE off line was false
The service now also counts the register operations its host paths
complete, which it left out of amx_operations, and every PE fills its
published AMX form counts only under step timing, which alone counts
them, instead of copying 3 KiB twice at each run slice. The ties test
asserts that an F16C path ran, and the AMX native tests' module and the
check gate say to set STELA_AMX_OPTIONAL=avx512f on a host without
AVX-512.

Translator id: unchanged (no compiler source and no engine translation
input changed; the code blocks hold is the same whichever routine the
cell names).
2026-11-22 17:09:17 +00:00
Garvit Surana 1f1088eae7 merge fork/laptop: the ASUS laptop host fixes (HDA parking, ALC256 init, power button, ASUS WMI keyboard backlight) and opt-in --lid method, --lid-sleep and --brightness-keys 2026-11-22 17:05:28 +00:00
Garvit Surana 2e89a8c783 merge fork/perf-quickwins: --code-window, --no-ibpb and --timer-delay-us measurement options, with the FP conversion/compare fast paths and in-block TPIDR reads on by default (new translator id) 2026-11-22 17:01:29 +00:00
Garvit Surana d6407f4f10 merge fork/profiler: --profile names the guest block each cycles sample lands in (PES PC lines) and cargo xtask symbolize ranks them by function and image 2026-11-22 16:58:40 +00:00
Garvit Surana d8fdb0eb0f test(compiler): time every AMX form the plan targets, through the model and through each native path with F16C, per Native::execute and per call of the routine blocks use, in an opt-in release test, where only the forms native code already covered had a timing 2026-11-22 16:54:19 +00:00
Garvit Surana e3dd1fc986 fix(battery): keep each reading to the host battery the SMC attached, giving no battery while that one has no reading and carrying only the AC adapter in a reading of another pack published before the pin, where a failed _BST on a machine with two batteries switched the SMC's one pack to the other's charge 2026-11-22 16:47:00 +00:00
Garvit Surana c604738c60 fix(boot): give no battery to a staged update, a recoveryOS or the Metal plugin repair, as to an install or restore, whatever --battery or --test-battery asks, with a POWER line that names the boot, where --upgrade, --paired-recovery, --system-recovery and --bundle-repair boots still got the battery 2026-11-22 16:43:28 +00:00
Garvit Surana 721da78597 fix(battery): give the SMC no battery from a reading at 0, a percentage or remaining charge of 0, and once it has one hold back a fall to 0 without the firmware's _BST critical bit until the next reading confirms it, with a POWER line that says so, and refuse --test-battery 0,charging, where a fixed _BST package before the EC answers, or a battery pulled with no notification, passed every check and showed macOS an empty battery, which it shuts down at 2026-11-22 16:41:55 +00:00
Garvit Surana bc21bd51a4 feat(boot): a Wi-Fi page at the startup menu (W): join a saved network first this boot (--wifi-prefer), save one by name and password typed there, or forget one, without logging a name or password 2026-11-22 16:12:15 +00:00
Garvit Surana 30e755e0c8 feat(wifi): join a saved network (EFI/stela/wifi.saved) when the preferred --wifi network is not in range, the strongest one a scan finds, without naming it in any failure 2026-11-22 15:57:28 +00:00
Garvit Surana d1c46c8998 fix(net): give macOS the configured Wi-Fi adapter when no adapter has carrier yet, where a laptop's empty Ethernet port, probed first, left macOS without a network although --wifi named one 2026-11-22 15:34:50 +00:00
Garvit Surana d7cbc1f514 fix(bluetooth): send the lent controller nothing once the bridge fell back, dropping a command the guest's function still had queued for it, and leave the controller alone from then on, where a command queued before the fallback could still reach it 2026-11-22 06:03:42 +00:00
Garvit Surana 4cf65a67c6 fix(boot): attach the brightness keys' outputs and the ASUS WMI device after the ACPI activation has installed the notify handlers and updated the GPEs, each in its own bounded firmware call, so a slow _BCL, _BCM, INIT or keyboard backlight method costs only what it attaches, where they ran inside the activation's 5 s call before notify_all and update_all_gpes, and one that outlasted it left every device's ACPI events off 2026-11-22 05:56:09 +00:00
Garvit Surana 10a28c389c fix(boot): take an ASUS WMI device only where its _WDG has the notebook events, call INIT only once their notify handler is in, and at each poll a notification reached read _WED until the firmware's queue answers empty, past a read that fails, as asus-nb-wmi binds and flushes, where INIT ran without the event block or with a refused handler, so every hotkey filled a queue nothing read, and a poll read one event per counted notification, at most 16, and gave up at the first bad read 2026-11-22 05:54:27 +00:00
Garvit Surana 578d044111 fix(boot): keep the host check's lines in the firmware with --keep-lines when --deadline stops it, once, as the summary does, and check the deadline and beats in the drivers' own waits through the Bluetooth bring-up and scan, where the deadline stop wrote no record and a bring-up hung in its driver for up to two minutes an attempt passed the deadline unseen 2026-11-22 05:50:58 +00:00
Garvit Surana b103cbf354 fix(boot): point the Bluetooth host check's no-PCI-access refusal at the CHECK storage FAIL no PCI access line, which says why, where it sent the reader to the cpu lines, which do not 2026-11-22 05:48:40 +00:00
Garvit Surana 71919cb165 fix(boot): size no NVMe host memory buffer under --host-check --bluetooth-check, so the firmware's NVMe pass-through is sent no Identify Controller and no NVMe command of Stela's reaches the Windows disk, where the storage discovery asked each NVMe for its HMPRE for a pool no NVMe driver of this mode uses 2026-11-22 05:47:10 +00:00
Garvit Surana 5f34b586ed fix(boot): follow the brightness keys only with --brightness-keys, and then only on a display output with _ADR that its video bus's _DOD lists, as Linux's ACPI video driver registers a backlight, with its level set at registration and a press without _BQC starting from the level last set, else the middle of _BCL, where every output with _BCL and _BCM was stepped on every PC, outputs absent in _DOD included, and the FA608PP's LCD, which has no _BQC, started from the highest, so its first press down could brighten the screen 2026-11-22 05:43:50 +00:00
Garvit Surana 8408ea05e3 fix(boot-core,boot): give up the Bluetooth host check's xHCI when its start fails, Bus Master, MSI and MSI-X off, and say its later steps were never reached rather than that nothing was started, where a start failing after enable_polled left the controller able to write memory and the lines denied it had been reset 2026-11-22 05:43:38 +00:00
Garvit Surana 3bcc1cbea1 fix(drivers): wait each command of the RTL8852C scan HCI_CMD_TIMEOUT, 2 s, as hci_sync's scan commands and btrtl's shutdown Reset do, and keep btrtl's 10 s HCI_INIT_TIMEOUT for its initialization alone, where the scan's commands waited the initialization's 10 s 2026-11-22 05:38:56 +00:00
Garvit Surana 61c0156950 fix(boot-core): refuse the Bluetooth host check when the firmware's USB stack lists more than one Realtek Bluetooth controller, naming each by its IDs, xHCI and path, and count a controller's interfaces as one, where the first one listed was started and any other went unmentioned 2026-11-22 05:36:48 +00:00
Garvit Surana e371558471 fix(boot): keep a hub port for the trackpad only when this boot cables one, through one guest_trackpad() the disk-port count and the cabling both read, --trackpad with host input, where the count read --trackpad alone and the cabling needed the host input too 2026-11-22 05:36:07 +00:00
Garvit Surana f8d5c6cd9e fix(boot): with --lid-sleep, ask macOS nothing when the lid darkens the panel while an external monitor shows it, as a Mac closed on an external display keeps running, and say so, where a laptop closed on a dock's monitor put macOS to sleep 2026-11-22 05:35:23 +00:00
Garvit Surana 0db2389292 fix(boot-core,boot): name in the Bluetooth host check's refusal what of the firmware's USB inventory could not be read, the step and the UsbIo handle, or the path of the disk Stela started from, where every failure became one "could not all be read" and an unreadable boot path counted the stick as another USB disk 2026-11-22 05:34:23 +00:00
Garvit Surana f083b1d012 fix(usb): trace the trackpad's mode only when the guest changes it, where Linux's resend after each reset-resume logged the same mode line again 2026-11-22 05:32:12 +00:00
Garvit Surana ce501e07ae fix(drivers,boot): start the Bluetooth host check's xHCI without mass storage, so the boot stick's disk is reported unused with no configuration, Bulk-Only or UAS command and no settle wait, where a stick bound to UAS got INQUIRY, TEST UNIT READY, READ CAPACITY and MODE SENSE at bind, which the firmware's descriptors could not foresee 2026-11-22 05:30:58 +00:00
Garvit Surana 388225a70c merge fork/install-speed: install medium read-ahead (--medium-read-ahead), a rewritten install-line scanner, faster USB log readback 2026-11-22 00:33:15 +00:00
Garvit Surana 90dd7f0b50 fix(bluetooth): hold a forwarded command until the lent controller has a command credit, as its last Command Complete or Command Status, stale answers and credits alone among them, said, where the bridge sent the next command whatever credits the controller had left 2026-11-22 00:33:09 +00:00
Garvit Surana 456a8f0734 merge wifi/rtw8852c-pr-prep: the RTL8852C Wi-Fi PR cleanup (docs, private items, PCI deinit and scan offload fixes, station tests, licensing) 2026-11-22 00:33:06 +00:00
Garvit Surana 665d7ca8e4 fix(boot): give a precision touchpad that arrives after the cabling frames mode and, when the guest trackpad was cabled at the MT2's own size, its surface at the next delivery, and say at the cabling that the trackpad spans the MT2's size until a touchpad arrives, where a late touchpad's frames were mapped over 160 x 114.9 mm and the log said the trackpad gets no frames 2026-11-22 00:32:21 +00:00
Garvit Surana bb1ac4e431 feat(boot): --amx-native off leaves every AMX register operation to the reference model, in blocks through the paths the engine gives each PE's cell and in the service, on every PE, with an AMX NATIVE off line at start, so that a boot can be set against one with host kernels on the same translations, where nothing could turn the host kernels off 2026-11-22 00:31:41 +00:00
Garvit Surana f041380018 fix(soc): cable the trackpad on the native hub's last port, after the Ethernet adapter, Bluetooth controller and disks, so they keep the ports they have without it, where taking the second port moved them all and gave macOS a new network interface 2026-11-22 00:27:40 +00:00
Garvit Surana cdbc91c617 fix(boot): light a display the lid darkened when an external monitor connects to its GPU, which KMS now tells while the outputs are off, so a laptop closed on a dock shows macOS on the dock's monitor, where the dark display's looks joined no new screen and the monitor stayed black 2026-11-22 00:25:51 +00:00
Garvit Surana 874e605aed fix(bluetooth): fall back to the model at bluetoothd's second HCI Reset after the start-up's first answered one, which the model answers, log each restart and the cause, and count them, where bluetoothd rejecting a well-formed merged answer restarted it with reason 108 forever while Setup's Language Chooser waited on it 2026-11-22 00:23:55 +00:00
Garvit Surana dda6326a1f fix(usb): coalesce a trackpad frame into the newest queued one of the same contacts and buttons once two are queued, counted apart and logged as coalesced in the TRACKPAD frames line, so a guest reading slower than the pad lags two frames at most, where the queue coalesced only when full and a guest a little slower than ~130 Hz kept about 31 frames, a quarter to half a second, of standing lag with no count 2026-11-22 00:23:03 +00:00
Garvit Surana 54e5ee56c2 fix(boot): do nothing with the lid unless --lid method asks, and with it count the reading a boot starts with for nothing, darken a display on built-in panels alone only after a lid notification whose _LID reads closed, and light it again at the next lid notification, whatever _LID reads, or at any input of the built-in keyboard or touchpad, with --lid-sleep needing --lid method, as Linux's kernel only reports the lid and keeps quirks for machines whose _LID reads closed when it is not, where a wrong reading at boot turned the screen off at its first frame with no way back 2026-11-22 00:17:01 +00:00
Garvit Surana ab924b656c fix(usb): send VoodooInput's 0xD9 range bytes verbatim after the pad's own width and height, the extremes Intel macOS is known to take, with the range the reports carry one constant away, where the first boot's 0xD9 stated a range no macOS had been seen to accept 2026-11-22 00:16:02 +00:00
Garvit Surana 21c103cd3b fix(boot): give no battery to an install or restore, whose SMC answers as the Mac mini's whatever --battery or --test-battery asks, and say so, where the installer's restore ramdisk got the battery too 2026-11-22 00:14:20 +00:00
Garvit Surana b5b1630505 fix(bluetooth): end at the fallback each inquiry and remote name request the guest saw the lent controller start and not end, with Inquiry Complete and Page Timeout, and stop the shadow's own, where the shadow's end, discarded while the bridge forwarded, could pass first and a fallback then dropped the controller's late one, so bluetoothd never got Inquiry Complete 2026-11-22 00:14:12 +00:00
Garvit Surana ad85ef61b4 feat(engine): count AMX register operations by form and path under --profile, in blocks through a counting routine the engine gives them in place of the compiler's, so the code they hold and the translator id stay the same, and in the service, with the 64th calls of each form timed, and log every PE's as PES AMX each beat and PES AMX TOTAL every 16 beats, where the per-operation counts never reached the log and named no form 2026-11-22 00:12:10 +00:00
Garvit Surana 8c1d11c0b6 fix(loader): keep the options revision at 13 and pin it with a test, since --trackpad is a hand-written opt-in setup never writes and no line setup writes changes meaning, where revision 14 made the revision-13 setup and this stela.efi refuse each other 2026-11-22 00:10:30 +00:00
Garvit Surana eb98d77595 fix(boot): say in the line that attaches the battery that it is one pack for the whole boot, which keeps its last reading if the battery is removed, and whether later readings follow it or ACPI hardware mode is off so none will, and in a later line with no battery that the SMC keeps its last reading, where the attach line said nothing of either and reported success when no reading could follow 2026-11-22 00:10:08 +00:00
Garvit Surana ac0a776845 fix(soc): build the emulated Magic Trackpad 2's device, descriptors and report encoder, which follow GPL-2.0-only VoodooInput material, only with stela-soc's new trackpad feature, which stela.efi alone enables, keep its identity, cabling, serial, trace and counters always built under GPL-2.0-or-later, refuse a trackpad's cabling without the feature and fail the CLI's build if its stela-soc carries one, and mark ptp_frames GPL-2.0-or-later as hid-multitouch is, where the GPL-3.0-or-later stela CLI linked the GPL-2.0-only model through its machine mount 2026-11-22 00:07:00 +00:00
Garvit Surana 92d199ee4c test(hle): differential harness and stand-in originals checked against a reference model: byte-loop leaves for memmove, bzero, memset, memcmp, strlen and a test-only touch, random and edge cases with overlaps, page-end NULs and unreadable or read-only pages, the C semantics of each, a comparison of two calls by what the ABI keeps, and sessions that run a suite's cases on one machine, returning from each abort, where a debug build took 0.1 s to make a machine per call and a machine's own test kernel address made two aborted calls differ 2026-11-22 00:06:48 +00:00
Garvit Surana ed5fd69916 fix(boot-core): refuse --test-battery discharging below 5%, where the synthetic battery is at or near its 3% low capacity and so critical as it attaches, which macOS shuts down at, where any percentage was accepted 2026-11-22 00:05:19 +00:00
Garvit Surana 38da8c90b1 perf(engine): MRS of TPIDRRO_EL0 and TPIDR_EL0, the user thread pointers, completes inside its block from stored cells every board numbers first, loading the register's storage the cell names, where each user thread-local access ended its block at the MRS and went through a thunk and a link 2026-11-22 00:05:13 +00:00
Garvit Surana 3871b06504 fix(bluetooth): give the guest the model, and say why, when --bluetooth-lend meets --idle-skip, where the guest's clock leaped over the bridge's 1 s wait for the controller and every forwarded command fell back at once 2026-11-22 00:03:27 +00:00
Garvit Surana 4b06697109 feat(boot): log each distinct SMC key macOS reads or asks about that a battery SMC does not have, and each distinct write, by key, size and result, once each and at most 256 in all, taken from the SMC every 2 s without waiting for a PE that holds the devices, so the first --battery boot says what macOS wants of the battery, where only the SMC's raw write log showed any of it 2026-11-22 00:01:20 +00:00
Garvit Surana 7d819f23ff fix(boot): take a control-method power button's notifications as one press after a second of quiet from every notification and fixed press, count none toward the double press that stands for a hold, drop those within five seconds of the service's first look, and name each look's count and what it was, where a held button's repeated _QE7 notifications or a pending EC query at start could stand for a hold and cut the guest off 2026-11-21 23:59:59 +00:00
Garvit Surana d6880d418b fix(bluetooth): mask every packet --bluetooth-trace captures before the function holds it, keeping headers, statuses and plain parameters, the vendor half and last byte of each address, and hiding names, opaque payloads, vendor parameters and returns, ACL past its HCI and L2CAP headers, keys and secrets and anything no rule names, printed xx and read back as 0, and say once in the log that the trace stays private until checked, where it logged the controller's and the platform's addresses, the Mac's name, every neighbour's address, name and manufacturer data and the guest's vendor parameters raw 2026-11-21 23:59:00 +00:00
Garvit Surana 9dc35d8b9f fix(boot): make the battery's timed reading only _BST and _PSR, on a flag of its own, as Linux polls them, leaving _BIX, _STA and _LID to their notifications, and double its period after a reading that fails or runs 100 ms or more of AML, up to 5 minutes, saying the first failure, the first slow reading and a recovery once each, where every 30 s the boot processor reran the whole notification refresh between PE0's slices, so a method at the 10 s AML bound stalled the guest's first CPU every 30 s, a failing battery printed every 30 s forever and a Notify from inside those methods refreshed again at every poll 2026-11-21 23:54:36 +00:00
Garvit Surana 6e5d820953 test(compiler): AMX native paths run against the model through one differential harness under a hostile caller MXCSR they must leave as they found it, with every refusal checked against the reasons its test admits, floors per form in each M1-M4 generation, and a host that lacks a covered tier failing unless STELA_AMX_OPTIONAL names it, where the unit tests skipped a missing tier with a note and never checked MXCSR 2026-11-21 23:51:25 +00:00
Garvit Surana f170e7d976 fix(drivers): retry an HD Audio controller's codec discovery only while it reports a codec that answers its vendor ID, as Linux's azx_probe_continue retries azx_codec_configure only while bus->codec_mask names one, where an AMD controller with no analog codec spent 59 one-second retries of each boot on nothing 2026-11-21 23:49:24 +00:00
Garvit Surana bdd8370c6a fix(soc): put the AC adapter's new state, 1 online, in pow.ExternalPowerChange's last byte as it goes out, the 0x710101xx form real SMC firmware was seen to send, where that byte was always 0 2026-11-21 23:49:05 +00:00
Garvit Surana 3bb52fe046 fix(soc): send pow.BatteryStateChange only when the battery turns critical, the one occasion real SMC firmware was seen to send it, and leave status and percentage changes to the battery driver's own poll, where it went out on every percent step and status change with no known reader, which Linux's macsmc-power takes as a critical battery and shuts down at 2026-11-21 23:47:23 +00:00
Garvit Surana 8f6b74e84c fix(boot): give the SMC the host's battery only with a reading that has a percentage, a remaining and a full capacity, the full one falling back to the design capacity as the percentage does, and refuse it once macOS has read the SMC's key table, keeping the Mac mini's keys with a POWER line that says what the reading lacked and trying each new reading, read every second, for up to a minute, where an unknown first reading, a battery with no full or design capacity or an mWh firmware with no voltage attached as 0, an empty battery to macOS, which shuts down, and its lpem then powered the laptop off 2026-11-21 23:45:03 +00:00
Garvit Surana 0fa8bfa87c feat(hle): --hle and --hle-off boot options and the HLE configuration, off by default: a signature table, the routines of it that are on and a bound of 256 bytes to 1 MiB on one call's work, with --hle-off naming distinct routines and an empty generated table, where no option or configuration could turn native routines on or off 2026-11-21 23:42:13 +00:00
Garvit Surana 947da83e38 fix(boot): enumerate the Bluetooth host check's one xHCI with its Bulk-Only disks left settling, so the boot stick it holds gets no SCSI command, where the controller's start went on to discover the stick's disk 2026-11-21 23:39:29 +00:00
Garvit Surana 4439bcd09f refactor(boot): keep --bluetooth-check's option, its tests and its host-check line apart from where the Wi-Fi host check adds --wifi-check, so a merge of the two meets only the --keep-lines port's own hunks, where each Bluetooth addition sat beside a Wi-Fi one and conflicted with it 2026-11-21 23:36:52 +00:00
Garvit Surana 57e84830a4 refactor(drivers): move the battery readings' handoff between processors and the service's timing into a tested relay in stela-driver-base, which the boot's battery now only calls, where the hand-rolled flag, the refresh period, the notification due time and the log's summary lived in the UEFI engine with no test 2026-11-21 23:35:22 +00:00
Garvit Surana 3a33ecc3aa fix(boot): start under --host-check --bluetooth-check only the xHCI the firmware's USB stack found the Realtek Bluetooth controller on, in place of the probe, with the TSC's minimum delays, and skip the storage, GPT and log checks, so no other PCI function gets a driver, BAR access or Bus Master and nothing writes to the stick, where the check ran the probe without native services, which starts no USB controller, so it could never reach the controller 2026-11-21 23:32:54 +00:00
Garvit Surana 823dc843aa feat(hle): masked function signatures and phase-1 eligibility, in the engine, which the translator id does not hash: routine ids, a function's SHA-256 with its outside branches, ADR, ADRP and literal loads masked, a prefix hash that depends on its length, and the self-contained leaves a native routine may replace, where nothing identified a guest function by its bytes 2026-11-21 23:32:53 +00:00
Garvit Surana b32fc611dd feat: cable an opt-in Magic Trackpad 2 for host precision touchpads (--trackpad mt2|builtin with --input, options revision 14): the touchpads give whole frames, the trackpad takes the hub's second port at full speed with the first pad's surface and the board's own serial, touch frames route to it, and what macOS asks of it and the pad's frame rate are logged as TRACKPAD lines, where a laptop's touchpad reached macOS only as a generic mouse; without the option every port, guest byte and log line is as it was 2026-11-21 23:31:48 +00:00
Garvit Surana ddae57347b fix(drivers): count the firmware's Design Capacity of Low toward a critical battery only when it is above zero and below a tenth of the full capacity, leaving the _BST critical bit alone otherwise, and say the warning and low capacities, and an ignored low, in the line that attaches the battery, where any Low counted, so a firmware's Low of 10-20% or of the whole battery made it critical, and macOS shut down, as soon as it discharged 2026-11-21 23:31:08 +00:00
Garvit Surana e61b02ec6d fix(boot): name the install medium's read-ahead --medium-read-ahead N and read install mode's options as exactly --install-mode and --install-build wherever they stand, in stela-boot-core, so no option of the mount's is read as one, name the option in a bad value's refusal and log it ignored on a network install, where --install-read-ahead, --install-source or any flag before them could land at a word the pairwise scan read as a name and refuse the boot as an unknown install option 2026-11-21 23:30:15 +00:00
Garvit Surana cc85d46f2c feat(boot-core): choose the one xHCI a Bluetooth host check may start, the one the firmware's USB stack found a Realtek controller on, admit no other PCI function, and refuse with a line when that xHCI also holds a USB disk other than the boot stick or the firmware's USB devices could not all be read, where the check could only run the probe, which without native services starts no controller 2026-11-21 23:29:02 +00:00
Garvit Surana a63d3e2592 fix(drivers): hold each byte of a battery's model and serial that is not printable ASCII as '?', where the firmware's raw bytes went on into the SMC's BMDN and BMSN strings 2026-11-21 23:26:11 +00:00
Garvit Surana 77d24deb7d fix(boot-core): print a refused Bluetooth identification's ROM version and key id whenever its attempt read them, where its line gave only the version readings and registers though the key id decides whether the patch can run at all 2026-11-21 23:25:20 +00:00
Garvit Surana 5970fb0c63 fix(soc): answer the battery's B0RM little-endian, as every other battery key, where it was big-endian, which Linux's macsmc-power expects only from firmware older than macOS 27's, the firmware the 1-byte BCF0 declares, so 3650 mAh read back as 16910 2026-11-21 23:24:34 +00:00
Garvit Surana b7faa3029f test(bluetooth): replay bluetoothd 26B123's start-up and System Settings' discovery through the bridged function, the owner's link and a scripted RTL8852C with devices in range, and check that the start-up completes as Apple's module with every vendor and unlisted command answered here, inquiry results of each mode, Inquiry Complete and remote names reach macOS in order, a burst beyond the guest's room is held with none lost, a bus reset keeps an old inquiry out, and a stall, refusal or transport failure at any of the 18 forwarded start-up steps falls back with the start-up still answered as by the model 2026-11-21 23:24:03 +00:00
Garvit Surana 2df60ddcdb fix(bluetooth): wait 10 s for each command of a Realtek controller's bring-up, btrtl's HCI_INIT_TIMEOUT, where it gave up after 5 s, half what Linux waits after 0xfc66 or a download fragment 2026-11-21 23:22:57 +00:00
Garvit Surana c45fff023d fix(bluetooth): keep a Realtek controller's first readings as a dropped patch only once 0xfc66 went out, where a 0xfc66 the bus refused was reported as a drop that never happened 2026-11-21 23:18:15 +00:00
Garvit Surana a259d5e9fe perf(compiler): scalar FCVT D to S converts in the entry MXCSR where FPCR is at its defaults and FPSR.IXC is set, FCMP and FCMPE of S and D registers give an unordered pair 0011 and its IOC inline, and FCVTZS saturates a NaN, an infinity or a value past the integer's range inline, where each conversion saved and loaded MXCSR four times and the others exited to software, about 1 us each 2026-11-21 23:14:38 +00:00
Garvit Surana 086c5d20e6 feat(bluetooth): lend the host's Bluetooth controller to macOS behind the modeled Apple module with --bluetooth-lend, off by default, so the guest keeps the module's identity and vendor answers while the bridge sends the controller milestone 1's standard commands, and log the lent controller, a fallback to the model with its command and cause, a BD_ADDR the guest wrote that the controller does not have, and the bridge's counters, where every boot gave macOS the model and dropped the host's controller 2026-11-21 23:11:19 +00:00
Garvit Surana f5dab8128c docs: name the Linux sources of the power button, ASUS WMI and ACPI video brightness ports in NOTICE, and the revision the ALC256 bind's parser and init were read at, where they were unlisted 2026-11-21 23:10:34 +00:00
Garvit Surana c0a1bac816 feat(boot): drive an ASUS laptop's WMI device as Linux's asus-wmi does, its notify handler first, then INIT, so the firmware reports its Fn hotkeys, then the keyboard backlight read with DSTS and set with DEVS to 0x80 | level, one event read through _WED at each notification so the firmware's queue drains, Fn+F2/F3 (0xc5/0xc4, toggle 0xc7) stepping the backlight over 0-3, and a line for the device, each step and each other code, where nothing called INIT, so those keys reached nothing 2026-11-21 23:10:08 +00:00
Garvit Surana a19c6d37e1 feat(usb): add an emulated Magic Trackpad 2 function, 05AC:0265 or VoodooInput's 05AC:0281 at full speed with its multitouch interface 1 on endpoint 0x83, VoodooInput's report descriptors and answers to Apple's multitouch feature requests, the 0x02 mode switch logged and never waited for, every other request refused and reported once, and host frames queued to 32 and encoded at the guest's IN, where macOS had no multitouch device to drive 2026-11-21 23:08:36 +00:00
Garvit Surana e577b8ba0f feat(usb): encode Magic Trackpad 2 multitouch reports from host touch frames, at the MT2's own resolution with the pad centred, each contact a rotating identifier from Start to one Stop, palms typed as palms, the lowest finger the thumb while clicking, pressure 120 with the button down and the header alone after the last lift, as Linux hid-magicmouse reads them back byte for byte, where the guest had no report to carry a touchpad's fingers in 2026-11-21 23:04:22 +00:00
Garvit Surana ae2efdfcd9 feat(bluetooth): carry a lent controller's packets through the bridge in the guest's Bluetooth function, which drops the controller's vendor events, credits alone and stale answers, keeps it out after a guest bus reset or new configuration until the guest's next HCI Reset is answered, never USB-resets it, gives the guest's ACL data to the shadow that owns every connection in milestone 1, and ends in the shadow each procedure the controller ended or refused; the engine reaches the controller through a HostController trait and a link that hands the guest at most its room left and tells the function when the controller fails, where one poll could overrun the guest's queues and a failed controller left its commands unanswered 2026-11-21 23:02:44 +00:00
Garvit Surana d72922e10a feat(boot): step each display output with _BCL and _BCM to its next level through _BCM at its brightness notifications (0x85-0x89), from the level _BQC reads where it is listed else the level last set, as Linux's acpi_video_switch_brightness and acpi_video_get_next_level do, naming at activation each output followed or that none was found and each step, where the Fn brightness keys' notifications only made the host re-read its batteries and lid 2026-11-21 22:59:36 +00:00
Garvit Surana 017b9a94ff feat(boot): give the guest's SMC the host's battery before macOS starts under --battery, or the synthetic one under --test-battery, from the reading the AML host publishes as its batteries and AC adapter attach and after each refresh, which it now also makes every 30 s, passing each newer reading to the SMC at a service turn with the notifications it holds once due, and log a POWER battery line at boot and at each change macOS acts on, where the host's battery readings reached no guest device and the log never showed them 2026-11-21 22:58:27 +00:00
Garvit Surana ce2ee05393 perf(boot): take the install medium's read-ahead from --install-read-ahead N, four 1 MiB chunks unless it says otherwise and 0 reading the medium only when asked, through the bound alone, 1 MiB a service and 2 MiB of the image kept ahead as before the read-ahead, log the depth at boot and count the time the translation store's reads waited, so one image can measure what the read-ahead costs lookups queued behind it on a one-command USB stick, where the depth was fixed and the store reader logged only its last reads' latency 2026-11-21 22:57:59 +00:00
Garvit Surana 39c937b8b5 feat(input): emit whole precision-touchpad frames on request, every contact in micrometres of the pad's exact surface with palms kept and each frame timed by the pad's scan clock, unwrapped and resynchronized after a second's gap as hid-multitouch does, where a precision touchpad reached the guest only as one finger's motion or two fingers' wheel, dropping palms and three or more fingers 2026-11-21 22:55:00 +00:00
Garvit Surana bf84b012b5 feat(boot-core): add --battery, which gives the guest's SMC the host's ACPI battery and AC adapter, and --test-battery PERCENT,STATE, a synthetic one at 0 to 100 percent charging, discharging or full for a machine with none, written back to the option line and refused when given twice or malformed, where a boot had no way to ask for a battery and no option-off boot changes 2026-11-21 22:53:37 +00:00
Garvit Surana 659d7cebde feat(soc): give the SMC the host's battery on request, with the keys the 26B123 battery driver reads at the types real Apple-silicon laptops declare (BPCC one pack and no charger, B0AV B0AC B0IV B0UC B0CM B0TE B0TF B0CT BMDN BMSN CHSC CHCE CHCC BSFC BCF0 AC-N AC-W, BUIC B0RM B0FC B0DC for the registry, and the charge-limit latches at their confirmed sizes), MSLD held open, values from the host's latest reading with each lost value kept, pow.ExternalPowerChange and pow.BatteryStateChange on an AC, status, percentage or critical change at most once a second and once every five seconds and only once notifications are on and the SoC is awake, and lpem as a power-off, where AppleSmartBatteryManager, which binds AppleSMC on every Mac, found no BPCC and so no battery on any board, and an SMC with no battery still answers as the Mac mini's 2026-11-21 22:50:54 +00:00
Garvit Surana 1432bfb22a feat(boot): with --lid-sleep, ask macOS to sleep when the host's lid closes, with a System Sleep press and release on a Generic Desktop System Control interface the guest keyboard then has as its fourth, and wake a sleeping guest with its power button when the lid opens, one line for each, where nothing told the guest of the lid; without the option the guest's keyboard and pointers are as they were 2026-11-21 22:49:10 +00:00
Garvit Surana 14cba4a9c3 feat(bluetooth): give the guest a lent controller's capabilities only merged with the model's, its supported commands and features less what the controller lacks of the forwarded ones, extended feature pages past 1 and LE features empty as the module's, and its ACL buffers with no synchronous ones, and check bluetoothd 26B123's whole start-up through the bridge and a scripted Realtek controller against the model step by step, where the controller's own Core 5.3 bitmap and features would have taken bluetoothd off the path it was traced on 2026-11-21 22:45:17 +00:00
Garvit Surana 19a8a15ed4 test(log): read the USB's log back across the end of a ring its stream has wrapped round, asked only as markers come and after every chunk alike, at nine chunk sizes, one cutting a marker line among them, and with every marked boot written over, where only a ring that never wrapped was read back 2026-11-21 22:44:09 +00:00
Garvit Surana 63da2d761c test(restore): hold the ASR sender reading in store-sized reads to sending its Initiate reply and then the image exactly, each byte once, where the test asked only that the output end with the image, which a part sent twice would pass 2026-11-21 22:44:08 +00:00
Garvit Surana ba730d9550 feat(input): add multi-contact touch frames to Input, a precision touchpad's contacts in micrometres with its buttons and scan time, released as a lifted frame when their device stops and refused by the native mouse, where an input change carried one pointer's motion at most 2026-11-21 22:39:34 +00:00
Garvit Surana bb913e1cde feat(drivers): read the host's first battery and its AC adapter as one power snapshot in mAh, mV and signed mA, converting an mWh firmware's capacities and rate through its design voltage, with Linux's status, rounded percentage and full test, critical also at the Design Capacity of Low on battery, the times its rate gives, a summary of what macOS acts on, a synthetic test battery and a POWER log line, where the ACPI battery's readings stayed in its firmware's units, which no guest SMC key takes 2026-11-21 22:35:54 +00:00
Garvit Surana 5bc37ce517 docs(profile): say that a PES PC block's cycles hold its tails and the helper, PAC service and shadow fills it called but not the engine's time between runs, and that gone also counts samples in context-ABI blocks and the boot's diagnostic native runs, which the host enters without a chain control, where the docs named neither 2026-11-21 22:34:33 +00:00
Garvit Surana 8acff80a87 docs(bluetooth): name the RTL8852CU identity, its v2 then v1 image, the 0xfc66 drop and the passive LE scan in the USB Bluetooth and Realtek module docs and their Linux sources in NOTICE, and say an RTL8852CU's wideband voice waits for its ALT 6 continuous output, where the docs named only the RTL8761BU, RTL8822B and EPATCH v1 2026-11-21 22:33:31 +00:00
Garvit Surana 45c2920c44 feat(bluetooth): add the core of a bridge to a lent host Bluetooth controller behind Apple's module, which answers every vendor command and every standard one off milestone 1's list from a shadow of the controller model, sends only listed standard commands to the host's controller, one in flight with one credit for the guest, and falls back to the model for good when the controller gives no answer in 1 s, fails, or answers with an error or a length the model would not give, where lending handed the host's controller every command of the guest 2026-11-21 22:32:56 +00:00
Garvit Surana 064f47f179 test(profile): cover naming a sampled block retired but still in its slot, a kernel or guarded block's vector base at EL1, EL2 and EL0 under VHE, a page that is not RAM naming no key and a page the board knows taking its known key, where no test reached those paths of naming a sample 2026-11-21 22:32:55 +00:00
Garvit Surana ac41b1703e test(drivers): read ahead a read half in memory and half in flight, a reader that seeks back while the chunks it left are in flight, and the short last chunk at the device's end, where none of them was tried 2026-11-21 22:32:17 +00:00
Garvit Surana 61baa6b5ca feat(boot): turn a guest display shown on built-in panels alone off while the host's lid is closed and give the guest's display sleep its say back when it opens, as Linux reports the lid switch at each change and the state it starts in, through the display sleep's own power path, and name each lid change and what the display did, where the host re-read _LID at every notification and nothing followed it, so a closed laptop kept its panel lit 2026-11-21 22:30:37 +00:00
Garvit Surana dabeba309d feat(boot): bring the first Realtek USB Bluetooth controller up under --host-check --bluetooth-check with the USB stick's verified firmware for USB Bluetooth requests alone, scan through it for 8 s, reset it and close its transport, and record one CHECK line per step and a summary, keeping them in the firmware with --keep-lines, where the host check never brought a Bluetooth controller up and nothing could prove its radio 2026-11-21 22:29:21 +00:00
Garvit Surana 13691d06db fix(xtask): refuse code that runs past the address space with an error, leave out a section that does, skip a cache missing a subcache or a file that cannot be read with a warning, warn of a dyld cache file with a dot and no main file beside it and read one named itself as a main file, where the symbolizer's sums could panic, one missing subcache or broken file aborted the run and a renamed main cache was skipped silently 2026-11-21 22:29:18 +00:00
Garvit Surana c3092d7014 fix(drivers): drop the chunks a missed read does not overlap only once its direct read is done, keeping the one it was served from in part, where the cleanup before that read dropped a chunk starting at the read's first block and a direct read past its bound read it again with the rest 2026-11-21 22:28:04 +00:00
Garvit Surana 1384ccf3ad feat(engine): --timer-delay-us sets the latest a busy PE's timer interrupt comes after its last, the engine's 10 ms otherwise, and a CLOCK TIMERS line counts each beat's timer interrupts, those the gate held past their deadline and how long, where the bound was fixed and nothing showed how late a busy PE's timers came 2026-11-21 22:27:27 +00:00
Garvit Surana 890b41c6ec feat(bluetooth): log every packet of the guest's Bluetooth controller with --bluetooth-trace, 1024 a configuration in both directions, whole up to 300 bytes, in a line format that reads back, where the boot log named only the first 48 commands with four parameter bytes each 2026-11-21 22:24:28 +00:00
Garvit Surana 2aff32e397 fix(drivers): take a chunk in flight that a read caught up with only if it has arrived, and else read directly, while no bound is set, where the read waited for it without any limit 2026-11-21 22:22:54 +00:00
Garvit Surana af2f5b5ed7 feat(boot-core): write a Bluetooth host check's lines, one CHECK line per step of a Realtek USB controller's bring-up as the probe kept it and of its LE scan, then a summary, in btrtl's reading names, with its address only masked and no driver error's bytes, and give its probe the stick's firmware for USB Bluetooth requests alone, where no line could say how far a controller came 2026-11-21 22:22:42 +00:00
Garvit Surana f1899c639a test(xtask): read a synthetic dyld cache of the shipping split layout, its main file naming a .01 that holds the image's __LINKEDIT and a .symbols by UUID, and have the real-cache oracle check an address inside each function, function starts for nearly every image and each start inside its image's code, where only the old one-file layout ever ran and the oracle named exact symbol addresses alone 2026-11-21 22:22:40 +00:00
Garvit Surana 3fcfd11de3 fix(xtask): name code outside an image's __text by its section, so stubs read as __auth_stubs or __objc_stubs, where the symbolizer gave them the name of the last __text function before them 2026-11-21 22:18:15 +00:00
Garvit Surana 25ef5d237c feat(bluetooth): scan passively for LE advertisers through a Realtek controller its initialization brought up, as Linux's core starts a passive scan, counting reports, distinct advertisers and the best RSSI without keeping an address, then reset the controller as btrtl_shutdown_realtek does and close the transport, where nothing could show an initialized controller's radio hearing anything 2026-11-21 22:16:06 +00:00
Garvit Surana 130d07f998 feat(firmware): pin an RTL8852CU's rtl8852cu_fw_v2.bin, rtl8852cu_fw.bin and the 8761BU config WHENCE links its rtl8852cu_config.bin to at linux-firmware 59f9fc2, bind them to the Realtek Bluetooth driver's requests by their stock-ROM label and read them in every boot as the other USB Bluetooth files, where the bundle held no rtl_bt file and an RTL8852CE's Bluetooth found none 2026-11-21 22:16:06 +00:00
Garvit Surana 47729020bd feat(bluetooth): drop a running patch once with 0xfc66 when a Realtek controller's readings match no USB entry of btrtl's IC table, sent outside the command flow, then wait 200 ms and identify it again, keeping both readings and what came meanwhile, and refuse readings still unknown, as btrtl_initialize's check_version does, where a controller a warm reboot left patched failed as a profile mismatch 2026-11-21 22:16:06 +00:00
Garvit Surana 3806c2f79d feat(bluetooth): ask an RTL8852CU for rtl8852cu_fw.bin under the EPATCH v1 target only when rtl8852cu_fw_v2.bin is missing, keep that absence in its report, and ask its config under the target of the image taken, as btrtl_initialize falls back, where only a profile's one image was ever asked 2026-11-21 22:16:06 +00:00
Garvit Surana b86fd8f0c5 fix(xtask): keep the file each page key was found in and name its function only from that file's innermost image range, reading a file once and no dSYM, where the symbolizer searched one list of every file's ranges by address and named another kernel's, kext's or cache's symbol, or no image where ranges nested 2026-11-21 22:15:21 +00:00
Garvit Surana 0475ae8c54 feat(boot): --no-ibpb issues no IBPB or return stack refill at guest context switches and discloses no FEAT_CSV2, giving up Spectre-v2 isolation between the guest's address spaces, and a PES PREDICTION line counts each beat's switches, the engine's and native code's, and the barriers issued for them, where a boot could not measure what the barrier costs 2026-11-21 22:15:11 +00:00
Garvit Surana 2cc1905f49 feat(boot): press the guest's power button for a control-method power button's notification, as Linux's acpi_button takes a PNP0C0C device, and name each such button found, with an AML encoder for ACPI fixtures and a fixture for the DSDT STELA_TEST_DSDT names whose regions answer as firmware's do, where a firmware with PWR_BUTTON set in its FADT, as the FA608PP's EC query _QE7 notifying \_SB.PWRB, pressed nothing 2026-11-21 22:13:11 +00:00
Garvit Surana 9d98f9c94b fix(profile): trim the PES PC total at each beat to the blocks with the most cycles, folding the rest into other, and have symbolize warn when other holds a tenth of the cycles, where the total kept the first 65536 blocks it saw forever and a later workload's code landed only in the other that symbolize's default reads 2026-11-21 22:11:13 +00:00
Garvit Surana c5e1de40bc feat(boot-core): --code-window MIB sets the board's code window in place of the one sized from the host's RAM, its bytes and their block records taken from the guest down to its floor, and a HOST CODE WINDOW line says what was asked, sized and chosen, where a boot could not measure another window against the sized one 2026-11-21 22:07:49 +00:00
Garvit Surana 0f8cbe8975 fix(xtask): skip a PES PC level line without its group's header, or a broken line, with a warning that names it, and apply a level line only whole, where one such line in a wrapped, dropped or cut log aborted the whole symbolize run 2026-11-21 22:06:46 +00:00
Garvit Surana ac070b749d fix(profile): print PES PC cycles whole and show them in the symbolizer's table as millions with a decimal, where each block's cycles were cut to whole millions, a one-sample block read 16M for 16.78M and --beats summed every cut 2026-11-21 22:04:11 +00:00
Garvit Surana 06b40196cf perf(profile): take a full block ring's overflow with a locked swap only when it holds cycles, where every native run's take swapped it even at zero 2026-11-21 21:59:19 +00:00
Garvit Surana cd9a1264f6 feat(bluetooth): parse an RTL8852CU's EPATCH v2 and v1 containers, each refusing only a file whose terminal project instruction names another chip, as btrtl's rtlbt_parse_firmware does, where the v2 parser took the RTL8852BU alone and the v1 parser refused it 2026-11-21 21:55:13 +00:00
Garvit Surana 6405ffe2af feat(bluetooth): identify an RTL8852CE's USB Bluetooth by btusb's 8852CE IDs and btrtl's 8852C stock profile as project 25, naming its v2 image, then its v1 image, and an optional config, where 13d3:3612 and the rest of its group were no vendor setup's and stayed off 2026-11-21 21:55:01 +00:00
Garvit Surana e5ff72e9f3 feat(drivers): run Linux's ALC256 init as the codec binds, alc_fill_eapd_coef, alc256_init on the headphone pin the pin defaults name as Linux's parser assigns it (else 0x21) and alc_auto_init_amp's EAPD on the listed pins, with one copy of alc256_init for the bind and the headphone route, and name the headphone, its jack, the speaker and the EAPD pins in the codec's line, where an ALC256 bound as standard widgets with none of Linux's init 2026-11-21 21:53:45 +00:00
Garvit Surana d55e89a72b docs(wifi): say what three RTL8852CE station tests pin and which part of each is a known gap, and state the PCI deinit's assumption that a failed index clear never reached the device, where one comment misread mac80211's beacon handling, one named a private ruling and the deinit left its assumption unstated 2026-11-21 21:52:46 +00:00
Garvit Surana 4b7a58bee0 perf(log): read the USB's log back to its newest boot with a device-start marker in time and copies linear in the bytes read, asking whether it settled only once another boot's marker line has come, where each 64 KiB read back copied every byte before it and parsed them all again, 21 MB parsed for a 1.6 MB boot and the whole ring once a chunk for a boot that wrote over its own marker 2026-11-21 21:42:16 +00:00
Garvit Surana 0306ca5447 fix(drivers): park as a GPU's HDMI audio only an ATI, AMD or NVIDIA HD Audio function 1 beside its display function 0, as Linux's quirk_gpu_hda links it and get_bound_vga pairs it, in the probe and the audio check alike, where any HD Audio function beside a GPU was parked, so an AMD APU's analog controller (1022:15e3 at 05:00.6 beside its iGPU) never started 2026-11-21 21:42:05 +00:00
Garvit Surana a74195ddce feat(boot): keep the host check's lines in the firmware's variables with --keep-lines so they can be read back without the screen, where the host check's results lived only on the screen 2026-11-21 21:37:40 +00:00
Garvit Surana cfb4063082 perf(boot): read 2 MiB of the system image ahead a service, in two reads the size of the store's largest, and keep 4 MiB of it read ahead, so a service that finds the install medium read ahead moves on twice what it did, where one read took 1 MiB a service and a single 2 MiB read would be refused as a payload random read past the store's 1 MiB 2026-11-21 21:36:56 +00:00
Garvit Surana 912aa6aed6 feat(xtask): add cargo xtask symbolize, which hashes the guest's dyld shared cache or Mach-O pages as the engine keys them and ranks a log's PES PC blocks by function and image, with an opt-in oracle test on a real cache, where no tool in the tree named a sampled guest PC 2026-11-21 21:33:19 +00:00
Garvit Surana f969b72398 feat(profile): name the guest block each --profile cycles sample finds running in native code, with its 4 KiB page's SHA-256 key and offset, and log them as PES PC lines each beat and PES PC TOTAL every 16 beats, where PES HOT weighed blocks by transfer, undercounted self-loops and named no page an offline tool could map 2026-11-21 21:33:19 +00:00
Garvit Surana 66cbf9d828 perf(boot): read the install medium's pieces ahead, as the study's raw source is, so the USB moves the next 4 MiB between the service's turns, with a read that catches up waiting for its chunk in flight, a read asked again after its bound finding the last one's chunks in memory and a reader that jumps read ahead only once it streams again, where the stick read only within each turn's 20 ms bound and the read-ahead read a caught-up chunk twice and dropped the one a timed-out read waited for 2026-11-21 21:26:26 +00:00
Garvit Surana 9bdbe8af49 docs(wifi): license the RTL8852CE station and association modules (GPL-2.0 OR BSD-3-Clause) AND GPL-2.0-only for the mac80211 code they port line by line, ieee80211_rx_h_check_dup and ieee80211_set_wmm_default's defaults with _ieee80211_sta_wmm_params' checks, as mediatek/station.rs is licensed, where their headers gave the driver's license alone 2026-11-21 21:26:17 +00:00
Garvit Surana 03b214ec09 test(wifi): cover an RTL8852CE's short slot granted by the association response alone, a PMF deauthentication with no PTK left to seal it, the keeper's group key handshake, the scan's early-frame and BSSID bounds and an RF 0x18 read failure, where the reviews found those paths untested 2026-11-21 21:26:17 +00:00
Garvit Surana 719e3cc390 refactor(wifi): make the RTL8852C TX power limit reads private to set_txpwr, drop TxPowerTables' Clone, rename H2c::addr_cam to addr_cam_unassociated, keep a departing ticket until its removal completes as rtw88 does, and release the test model before h2c_bytes panics, where a caller could read a limit under a regd that skipped the UK-to-ETSI mapping, a clone copied 40 KB on the stack and a missing H2C poisoned the model's mutex 2026-11-21 21:26:17 +00:00
Garvit Surana 2083b8387e fix(wifi): keep an RTL8852C's RX host indices when its PCI deinit cannot clear the ring indices and refuse an empty scan offload channel list, where a failed TX index clear restarted the RXQ and RPQ host indices over hardware ones it left as they were and an empty list went out as an ADD_SCANOFLD_CH of no channel 2026-11-21 21:26:17 +00:00
Garvit Surana f3831f9f02 docs(wifi): quote the RTL8852C module's register bit ranges and unlink its private items so its documentation builds without a warning, name the donor's rtw89_scanofld_notify_reason, point pn_valid at the drains that run it and say what a management frame the chip refuses holds up, where rustdoc took 112 bit ranges for links, 27 public docs linked private items, ppdu.rs and native.rs linked ambiguous names and scan.rs a moved counter 2026-11-21 21:26:17 +00:00
Tyler Smith 164d332ee1 feat(output): a stop inside a GPU driver's probe names the GPU, its driver, the probes' turn and another GPU of the PC that could have drawn in its place, where the stop named only Linux's own reason 2026-11-18 21:04:16 -05:00
Tyler Smith aba0fc5d7d fix(gpu): a stop during the fallback after a Metal device did not open, or during an unused GPU's unload, stores the USB's log as one in the GPUs' start does, where the log of that boot was lost 2026-11-18 21:03:40 -05:00
Tyler Smith 2d8678fe2d fix(gpu): a GPU whose Metal device did not open while another GPU's output shows the display has its driver unloaded within 10 s, its interrupts and bus mastering off, where it stayed bound holding Linux's pages, and one that shows the display stays 2026-11-18 21:03:20 -05:00
Tyler Smith 11ff6e5892 fix(gpu): the boot's stop shuts down the driver of every bound GPU, those a fallback started after the start among them, where it shut down only the start's 2026-11-18 21:02:58 -05:00
Tyler Smith 00e711c6c3 feat(gpu): the boot screen's line for a GPU another draws in place of names why it could not, its probe's or Metal device's first error cut to one line, where it said only that the boot log says why 2026-11-18 21:02:38 -05:00
Tyler Smith 1db07bac1b feat(memory): an image whose integrated GPU may draw in place of the discrete GPU the plan serves keeps room for 768M of Linux's pages as far as the guest's floor allows, and a fallback to it holds Linux's pages to the plan's bound before its probe or refuses it under 256M, where Linux's pages stayed unbounded and took the heap's own 2026-11-18 21:02:04 -05:00
Tyler Smith b2343d38a1 fix(gpu): only the UEFI image names the linked Vulkan drivers' symbols, so host test binaries built with every workspace feature link, and the AMD-only name test import is AMD-only 2026-11-18 19:48:54 -05:00
Tyler Smith acefc48ad7 feat(boot): a GPU chosen to draw that fails at its probe or its Metal device gives way to the next GPU, claimed and started after Linux 2026-11-18 17:41:56 -05:00
Tyler Smith 376dfdeec1 feat(boot-core): the GPU step names each stage a GPU chosen to draw failed at and the GPU that draws in its place 2026-11-18 17:40:36 -05:00
Tyler Smith d37d7b52c6 feat(gpu): the selection chooses again without the GPUs that failed after their claim, so the next GPU draws in their place 2026-11-18 17:35:19 -05:00
Tyler Smith cdf4ffed5c fix(linux): a GPU driver's failed probe leaves no interrupt request, message interrupt or bus mastering behind for the next driver 2026-11-18 17:24:31 -05:00
Tyler Smith fd926f1e9f fix(boot): the GPU step's screen lines and the log's GPU SELECT lines come from stela-boot-core's gpu_step, tested whole for desktops, laptops with and without a mux, servers and failed starts in a release and a full build: a GPU that only shows the picture is named only where a screen hangs on it, a PC without a usable GPU is told so without adapter addresses or port names, and a release never mentions the AMD and Intel ports 2026-11-18 16:51:54 -05:00
Tyler Smith 0fc68f2357 refactor(boot): a finished step's screen and log text is made by stela-boot-core's finished_step, so tests read the boot screen's step lines as the boot draws them 2026-11-18 16:51:54 -05:00
Tyler Smith 8c04d9d416 fix(gpu): a GPU no source names is called by its maker alone, as "NVIDIA GPU", where the boot screen showed its PCI IDs; the log's GPU SELECT line keeps them 2026-11-18 16:51:48 -05:00
Tyler Smith 9fe873d590 fix(gpu): every GPU the NVIDIA, AMD and Intel stacks admit has its market name, checked by a test that walks each driver's table: AMD's processor GPUs and devices named only by revision get AMD's names, laptop GeForce RTX 30 and later are Laptop GPUs, and engineering samples, reserved IDs and chip codes no longer pass for names 2026-11-18 16:51:39 -05:00
Tyler Smith b1703186a3 fix(boot): the census line of the GPU the image drives names it by its market name and PCI address, where it gave the vendor's enum name, as in "a Intel display controller" 2026-11-18 12:41:22 -05:00
Tyler Smith f9f545e637 test(gpu): the memory plan and the engine's census tell an Intel iGPU integrated and an Arc card discrete by their driver's table, and a laptop whose panel is on the Intel iGPU beside an NVIDIA, AMD or Arc card draws on the card with the iGPU showing its frames 2026-11-18 12:41:22 -05:00
Tyler Smith b279eb4381 fix(gpu): i915's parameters and its build of the display parameters register at ordinals 34 and 35, with i915's symbol renaming, so Linux's command line keeps i915.vbt_firmware, i915.huc_firmware_path and i915.gsc_firmware_path, where only xe's units registered parameters and the boot left every i915 word off the command line 2026-11-18 12:41:22 -05:00
Tyler Smith 412841cca1 fix(gpu): Meteor Lake, Arrow Lake and Lunar Lake keep their GSC firmware, which their media GT needs to enter C6, with one line saying so and the proxy's missing MEI component said at info level by i915 too (Linux patch 0234), where the boot turned the GSC off on every platform and those laptops' media GT never idled 2026-11-18 12:41:22 -05:00
Tyler Smith 1b9aa68efc fix(gpu): a laptop panel's PWM backlight that reads 0 when i915's or xe's display code starts, as the claim's reset can leave it, is lit at its highest level rather than the minimum, with one line per panel naming the level read, its maximum and minimum (Linux patch 0233), where the panel could come up lit but dim with nothing in the log 2026-11-18 12:41:22 -05:00
Tyler Smith c836208f92 fix(gpu): xe and i915 each describe the bound GPU for the boot log's summary, xe with its device, revision, each GT's IP version and the GuC submission interface it runs, i915 with its device, revision, execution units and the GuC submission interface where it submits through the GuC, both with the memory they manage, where neither driver's chip or firmware facts reached the log in one place 2026-11-18 12:41:22 -05:00
Tyler Smith ec6869f613 fix(gpu): the Video BIOS Table's panel line tells the display code's fallback entry 0 from a panel the EDID picks, gives the backlight PWM's polarity, says a panel without a PWM backlight entry or block gets no backlight from the display code, and says the eDP delays without the table's block are the registers' or the specification's, where it called a missing or invalid entry the EDID's choice and sent a non-PWM backlight to the eDP AUX channel 2026-11-18 12:41:22 -05:00
Tyler Smith c8a0e77de5 fix(gpu): i915's -ENODEV to ANV's GETPARAM probes of PXP_STATUS and of parameter 1, which Mesa's i915 device info asks by a getparam nested in a getparam's argument on every start, are ordinary answers and not refusals, where each would have printed a refused I915_GETPARAM line on every Intel GPU i915 drives 2026-11-18 12:41:22 -05:00
Tyler Smith 6db8a19fff test(linux): dma-buf's sync file ioctls run as ANV asks them on i915 before it makes a device, through the descriptor table and ioctl entry Stela's clients use: an idle buffer exports a signaled file, a file imports, a pending write fence holds a read export until it signals, bad flags and descriptors are refused, and the last close releases the buffer 2026-11-18 12:41:22 -05:00
Tyler Smith b6bda68862 fix(gpu): an Intel GPU's Video BIOS Table gets one boot-log line with what the display code takes for a built-in panel, its panel entry, backlight control and eDP power delays, where a dark or dim laptop panel's log said only the table's size 2026-11-18 12:41:22 -05:00
Tyler Smith a08f60ba02 fix(gpu): an Intel GPU is offered to i915 first where upstream Linux binds it to i915 and to xe when i915's probe fails, with ANV on either and the log naming the driver that bound it, and both drivers start with HuC and GSC left out, where xe alone was offered every Gen12 device and the boot pinned and loaded media and security firmware Stela never runs 2026-11-18 12:41:22 -05:00
Tyler Smith 150b28d2a1 fix(gpu): a GPU client's sysconf(_SC_PHYS_PAGES) and MemTotal are the RAM Linux sees, as on Linux, where they were the engine heap's capacity and ANV cut its system heap by a ratio no Linux system has 2026-11-18 12:26:51 -05:00
Tyler Smith 2189b73f88 fix(linux): an attached PCI function names the driver that bound it, and a driver whose probe fails leaves the function to the next registered driver with its devres released, where nothing said which driver held a function a second driver could take 2026-11-18 12:26:51 -05:00
Tyler Smith c4b0cd35df fix(gpu): an Intel GPU without a Video BIOS Table in the OpRegion is said to have its display code look in the GPU's own flash and option ROM, where the line said panels would be found by probing only, which is wrong for a discrete GPU 2026-11-18 12:26:51 -05:00
Tyler Smith ee9b575a05 fix(gpu): a function given fewer MSI-X vectors than it asks for says how many it asked, how many interrupt lines were left and how many it got, where xe, which needs all of its table's vectors, failed only with its own -ENOSPC line 2026-11-18 12:26:51 -05:00
Tyler Smith 41a198efc9 fix(gpu): a refused DRM call is named by the driver of its file, asked by DRM_IOCTL_VERSION, and xe's ordinary answers to ANV's protected-content and VM-fault probes are not refusals, where an image with several drivers named every driver command by amdgpu's table and every graphics 12 start logged a refused query 2026-11-18 12:26:51 -05:00
Tyler Smith c019473bd2 fix(ttm): a kernel built for Stela writes back the cache lines of pages a driver asks to have write-combined or uncached, as x86's change of their memory type does (patch 0232), where it changed nothing and a line dirtied when the page was cleared could later be written over what the GPU or the display put there 2026-11-18 12:26:51 -05:00
Tyler Smith 8af2e0ef5a fix(drm): a kernel built for Stela writes back cache lines as x86's does when a driver flushes them, with x86's clflush and clflushopt (patch 0231), where drm_clflush_pages, drm_clflush_sg and drm_clflush_virt_range warned once and flushed nothing, though i915 flushes with them every object the GPU or the display reads past the processor's caches 2026-11-18 12:26:51 -05:00
Tyler Smith 316ffcc057 fix(loader): the AMD and Intel GPU recipe tables are built only with their ports, as are the boot's amdgpu part and ATRM reader, so a release image and stick hold none of their file names, hashes or notices, where a release image carried every amdgpu, xe and i915 recipe as data 2026-11-18 12:26:51 -05:00
Tyler Smith 38b81a8458 fix(gpu): ANV's device serves only once an empty first submission signals within 2 s, at the open and after a loss, as RADV's does, while ANV's lost devices are still released, where a GPU xe or i915 left with engines that do not run, or that hung again after their recovery, took every client's work until their job timeout 2026-11-18 12:26:51 -05:00
Tyler Smith 354eb021ba fix(gpu): xe gets the stolen memory of a Tiger Lake to Raptor Lake integrated GPU, which the boot reads by the early-quirk method Linux names for it and says in one line, with xe taking the resource as x86's early quirks fill it (patch 0230), where xe ran those GPUs without stolen memory and said so only at debug level 2026-11-18 12:26:51 -05:00
Tyler Smith edff63e620 test(gpu): anv-test runs ANV on exactly the devices xe and i915 are handed, by the Mesa table reader their admission uses, checks ANV gives no Vulkan device for each device of Mesa's table left out, and checks the Metal device's own requirement list, where it named Gen5 to Gen8 display-only by rule and also required unrestricted primitive topology, which the Metal device does not 2026-11-18 12:26:51 -05:00
Tyler Smith fd6438840e feat(boot): the image's Intel port holds i915 beside xe, and the boot hands i915 its GPUs with their display program, Video BIOS Table, chipset bridges, host bridge configuration and stolen memory, with stela writing i915's firmware too (471 files, 247.6 MiB) 2026-11-18 12:26:51 -05:00
Tyler Smith 0307ddefad feat(gpu): Intel's stack gives ANV as its Vulkan driver in an image that holds it, so the GPU xe binds serves the Metal device when the Metal device rule chooses it 2026-11-18 12:26:51 -05:00
Tyler Smith 8e2f09b21e feat(boot): xtask boot build's image holds xe beside NVK and amdgpu outside a release, its log names xe's force probe, and stela writes xe's firmware by default (466 files, 247.6 MiB), where every Intel GPU was left with the firmware 2026-11-18 12:26:51 -05:00
Tyler Smith 6586edf9ed fix(i915): a GTT mmap fills its object's pages with the page tables any kernel with an MMU has (patch 0229), where it was built only under Linux's x86 arch and elsewhere warned and mapped nothing 2026-11-18 12:26:51 -05:00
Tyler Smith 3564cbde98 feat(gpu): ANV draws on the GPUs i915 is handed, Skylake to Ice Lake, over i915's uAPI in an image that holds it, and the Metal device admits them by i915's table, where i915's stack drove displays only 2026-11-18 12:26:51 -05:00
Tyler Smith 8d17abf121 test(gpu): anv-test also runs ANV over Mesa's own i915 no-op shim on every Gen9 to Gen11 device i915 binds and xe's table does not hold, with the Metal device's requirement check, every ioctl ANV makes one Stela's i915 serves on a render node, and i915's earlier devices named as display-only by rule 2026-11-18 12:26:51 -05:00
Tyler Smith 0991253bb9 refactor(gpu): i915's table readers stand in their own build module, so a host test reads i915's devices as its build does 2026-11-18 12:26:51 -05:00
Tyler Smith 473d8ac980 feat(linux): a client mapping's fault fills its own page table entries, vmap maps write-combining and vmap_pfn maps contiguous frames as device memory, with the firmware's graphics stolen memory among the ranges the owner maps, so i915's object faults and stolen-memory mappings no longer trap 2026-11-18 12:26:51 -05:00
Tyler Smith 0d9fd0252f refactor(boot): the claim finds a kernel driver's part by the driver's name and shows Linux the chipset functions the scan read, a host bridge function with its configuration, and the graphics stolen memory a part reports, where it found the part by vendor and showed PCI-to-ISA bridges only 2026-11-18 12:26:51 -05:00
Tyler Smith e0b23a4238 feat(gpu): an Intel GPU goes to the first registered driver handed it, xe and then i915, each handed only the GPUs of its table that ANV opens by Mesa's own device table and version checks, i915's being Skylake to Ice Lake with their two stolen memory methods, and any other Intel GPU is left unclaimed and reported as every GPU without a driver is, with i915's stack driving displays only 2026-11-18 12:26:51 -05:00
Tyler Smith 01c0a1e519 feat(loader): pin i915's display microcontroller programs for Skylake to Ice Lake, optional as intel_dmc.c treats them, and select each for the Intel GPUs of its platform that i915 drives, in a build with the loader's i915-port 2026-11-18 12:26:51 -05:00
Tyler Smith 85d88a84c5 feat(gpu): i915-port builds every unit of i915's Makefile into the registration image at ordinal 36, its copy of the display code renamed apart from xe's, with i915's PCI ID table and the stolen memory methods of early-quirks.c 2026-11-18 12:26:51 -05:00
Tyler Smith 2a7f57a366 feat(linux): a function published for searches may carry the configuration its owner read, and the boot may set the graphics stolen memory as x86's early quirks would, with devm regions recorded for their device 2026-11-18 12:26:51 -05:00
Tyler Smith 1dcd4c4873 feat(linux): shmem files keep zero-filled pages in their page cache until a truncation or their inode's last reference, with writes through write_iter and kernel_write and writeback as Linux without swap does it, where every shmem page was refused 2026-11-18 12:26:51 -05:00
Tyler Smith 385d3956b7 feat(linux): the kernel services i915 calls, with out-of-memory and vmap purge notifiers run where Linux runs them, and bus window placement, task address space mappings and userptr pins refused once 2026-11-18 12:26:51 -05:00
Tyler Smith e961543585 feat(linux): x86 CPU feature words, the TSC rate, PAT and cache writeback for the drivers that ask, wbinvd_on_all_cpus writing back this processor's caches and saying once that the others' are not 2026-11-18 12:26:51 -05:00
Tyler Smith fbb35fa42d feat(gpu): the Kbuild reader takes -D flags, variables a recursive reference reads before they are complete and dashed definitions, as i915's Makefile writes them 2026-11-18 12:26:51 -05:00
Tyler Smith 7c9e7abcab feat(linux): a function's MSI-X vectors reach Linux through its owner, which maps the table from the capability's BIR and offset, gives each vector its own line and masked entry on the interrupt controller MSI uses and writes the table back after a reset, so pci_alloc_irq_vectors with PCI_IRQ_MSIX gives as many vectors as the table holds and the owner has lines for, where every driver got one MSI vector 2026-11-18 12:26:51 -05:00
Tyler Smith 2bbad20291 fix(i915): a kernel without the PMC mux driver says once that a Type-C port shows a display only where firmware set its mux, where such a port stayed dark without a word (patch 0220) 2026-11-18 12:26:51 -05:00
Tyler Smith ce32d5148e test(gpu): gpu compilers --metal-corpus sweeps AIR modules through the Metal compiler with NAK's options and with ANV's for each Intel compiler generation from Gen9, compiles each kernel through NAK or BRW as the drivers would, each BRW compile in a child so an assertion is a finding, and counts the outcomes into the receipt 2026-11-18 12:26:51 -05:00
Tyler Smith a56b787572 test(gpu): anv-test runs ANV on every device xe's tables admit and Mesa's Intel table lists, and names each admitted device Mesa leaves out as one that shows displays only, where it ran one device of six platforms 2026-11-18 12:26:51 -05:00
Tyler Smith 946e6c063a feat(xe): xe's build reads its firmware table and its display code's firmware names, a test fails when either names a file of a GPU xe drives without a pinned recipe, a platform the table gives no GuC image is refused before the claim as Linux's probe stops there, and recipes cover ADL-P's fallback display program and the Flex GPUs without a display engine 2026-11-18 12:26:51 -05:00
Tyler Smith 0f7d76240d feat(firmware): the bundle holds the Intel GPU port's files, xe's, only in a build with the loader's xe-port, as it holds amdgpu's, so a stick for an image without xe carries none of them, where no bundle held the pinned xe files 2026-11-18 12:24:00 -05:00
Tyler Smith eca6830961 fix(gpu): the Metal open test's drawing xe stack sets the kernel fields xe's stack sets, its version, ROM, boot-CPU unload and page bound, where the GPU crate's tests with the Metal backend did not compile 2026-11-18 12:22:10 -05:00
Tyler Smith e36d33a0d7 fix(gpu): the engine's census takes each GPU's kind from the memory plan through one rule for both, so they select the same GPUs, and a GPU the plan did not see, below a port powered on after the firmware's exit, is named with what the plan kept for this boot, where an AMD iGPU told by IP discovery was left by the plan with no display reserve and claimed by the engine 2026-11-18 12:22:10 -05:00
Tyler Smith c8b736a155 fix(memory): Linux's pages are held to what the heap holds past its own need only where every GPU that starts has a driver that need was measured beside, amdgpu, and the first allocation the bound refuses is said once with its numbers, where an NVIDIA PC's pages were capped at 392 MiB on a floor heap, under a third of TTM's 1408 MiB on main, by a figure measured beside RADV 2026-11-18 12:22:10 -05:00
Tyler Smith 717fe703a7 fix(gpu): a fatal stop on the boot CPU unloads the GPUs there only where every bound GPU's driver is one shown to unload from such a stop, amdgpu, and otherwise leaves the firmware running with a line naming the driver, where it ran nouveau's GSP unload beside the stopped work's own state, which no boot had done 2026-11-18 12:22:10 -05:00
Tyler Smith 3d5e6c05d6 fix(gpu): only a driver that reads its video BIOS from the platform ROM and the ROM BAR has its claim size and place the expansion ROM BAR and hand over the firmware's option ROM and ATRM's image, where every claim, nouveau's too, did that new config-space work nouveau never needs 2026-11-18 12:22:10 -05:00
Tyler Smith 993004fc16 fix(gpu): the summary names a kernel driver's DRM version as the build read it from the driver's source, and the memory query and amdgpu's description share one render file, where every bound GPU had a DRM file opened and closed once more for the version 2026-11-18 12:22:10 -05:00
Tyler Smith 058c121191 fix(gpu): a claim's step waits 50 ms at most for the record of the firmware's picture, and one that gives up takes the picture as ended for the rest of the boot and says so once, where the wait had no deadline 2026-11-18 12:22:10 -05:00
Tyler Smith f534d0bab8 fix(gpu): a Linux WARN is counted by a hash of its site in a table of fixed size, allocating nothing, and one raised while a count is made is written as it is, where the count formatted its key and grew a map, so a WARN during heap exhaustion failed again, and a re-entered one panicked on the count's borrow 2026-11-18 12:22:10 -05:00
Tyler Smith 9e9b3e0047 fix(patches): linux 0202, 0216, 0217 and mesa 0036, 0038 keep the headers main holds byte for byte, where an export before the export's fix gave them UTC dates, long blob names, a new diffstat and no signature 2026-11-18 12:22:10 -05:00
Tyler Smith 7210aaf25e fix(boot): the GPU claim imports no gpu_status module it no longer uses, where stela-boot's strict Clippy failed on the unused import 2026-11-18 12:22:10 -05:00
Tyler Smith f6416ab355 style(boot): format the GPU claim, census and selection code as rustfmt does, where the check of stela-boot's formatting failed 2026-11-18 12:22:10 -05:00
Tyler Smith dc3882784f fix(gpu): the count of a repeated Linux line names it as the line Linux last wrote, where it said the line before, which is the boot's own line when one came between 2026-11-18 12:22:10 -05:00
Tyler Smith 9f14091d2a fix(gpu): a function-local or bus reset at the claim ends the firmware's picture for a driver that resets the GPU itself too, where an amdgpu GPU the claim reset was said to keep its picture and the console was given back to it after a failed probe 2026-11-18 12:22:10 -05:00
Tyler Smith d8e17740cb fix(gpu): a discrete GPU's bound on Linux's pages is named as that bound in the GPU summary and a heap stop, where every NVIDIA boot logged that an integrated GPU drew without a share and a heap stop called the bound the GPU's share of RAM 2026-11-18 12:22:10 -05:00
Tyler Smith 9d130c42c1 fix(gpu): the boot screen has no line for a display adapter left unstarted beside the GPU that draws, and an adapter of a maker without a driver stack is named without its PCI IDs, which the log's GPU SELECT line keeps 2026-11-18 12:22:10 -05:00
Tyler Smith ddb68da08e fix(memory): a discrete GPU's pages are held to what the heap holds past its own needs by the page catalog's limit and TTM's, and the heap grows by the page tables of a device-memory aperture its driver maps whole, both on the plan's line, where a discrete GPU's GTT and VRAM evictions could exhaust the heap and a Resizable BAR card's aperture tables were not counted 2026-11-18 12:22:10 -05:00
Tyler Smith a2e66a30a7 fix(gpu): a GPU whose driver fails before it resets the GPU or starts its display gives the firmware's picture back to the boot, and a driver step that ended it is named in the log and on the screen, where every AMD claim gave that screen up for good and the log blamed a claim reset that never happened 2026-11-18 12:22:10 -05:00
Tyler Smith 406629792d fix(linux): Linux task stacks are 32 KiB, where amdgpu's display core took about 14 KiB of the 16 KiB in a DCN 3.x commit, its DML frames grown by the UEFI calling convention's saved XMM registers 2026-11-18 12:22:10 -05:00
Tyler Smith aa4a1d3cd2 fix(gpu): a Metal device outside Metal3 or Apple7 gets one boot-log line with its name, its highest Apple family and what each missing family needs, as on GFX9 and GFX10.1 AMD GPUs without mesh shaders or barycentrics, where nothing said why macOS ran its pre-Apple7 paths 2026-11-18 12:22:10 -05:00
Tyler Smith 20bfdb1f22 fix(gpu): a GFX8 AMD GPU (Tonga, Fiji, Polaris, VegaM, Carrizo, Stoney, Topaz) is refused before anything of it changes with one line naming its missing Apple GPU family, and its firmware is no longer pinned, where it was claimed and its Metal device reached Mac2 alone 2026-11-18 12:22:10 -05:00
Tyler Smith 9218d68100 fix(gpu): amdgpu decides PCIe speed switching by the host's processor as on Linux, read by CPUID, where Stela's build without CONFIG_X86 kept the switching on Intel hosts and Pinnacle Ridge that Linux turns off 2026-11-18 12:22:10 -05:00
Tyler Smith 802d952a09 fix(gpu): amdgpu reads the PCIe link of the port above the GPU, past an AMD card's own switch, as on Linux, where Stela's Linux had no bridge above any function and amdgpu capped every discrete GPU's PCIe power levels at 5 GT/s 2026-11-18 12:22:10 -05:00
Tyler Smith 1474528c39 fix(pci): a function's MSI capability is saved with its state and written back after the header when the state is restored, as Linux's pci_restore_state does, where amdgpu's own mode 1 reset left the message cleared and the GPU fell back to its fence timer 2026-11-18 12:22:10 -05:00
Tyler Smith b506d0b7cf fix(gpu): a heap exhaustion stop says what Linux holds of an integrated GPU's share of RAM, its GTT's pages among them, where it gave the heap's figures alone 2026-11-18 12:22:10 -05:00
Tyler Smith bdbaa5b269 fix(gpu): an interrupt action Linux keeps names the retirement step that failed, the error in words and its vector, where it gave the error's name alone 2026-11-18 12:22:10 -05:00
Tyler Smith 64d98b09b0 fix(gpu): a fatal stop that leaves the GPU firmware running names which of the three conditions put it inside Linux, where it said only that the stop was inside Linux 2026-11-18 12:22:10 -05:00
Tyler Smith 70098fbaef fix(gpu): the count line of a GPU's many firmware files lists each file's name, where a selection that left a file out showed only in a later failed request 2026-11-18 12:22:10 -05:00
Tyler Smith 3f8ea344b4 fix(gpu): an AMD GPU's claim reads its security processor's state where its IP discovery table lists MP0, and an integrated one's names its share of RAM, the GTT and TTM limits that follow, its VRAM carve-out and the most Metal tells the guest, one line each, where a ring a previous driver left and the memory plan showed only in later failures 2026-11-18 12:22:10 -05:00
Tyler Smith 25db2f2b91 fix(gpu): an AMD graphics core whose memory hub places VRAM past the GPU's address space, as one a previous owner left powered down reads all ones, fails amdgpu's probe with one line saying it does not answer and the boot goes on without that GPU, where its page tables hit a BUG in gmc_v10_0_get_vm_pde that ended the boot 2026-11-18 12:22:10 -05:00
Tyler Smith 66c3920bbc fix(gpu): an AMD GPU's IP discovery refusal names the word read and the signature it should be, with its size and offset, and says what NoAnswer, NotReady and InSystemMemory mean, in the claim's read and in amdgpu's, where the claim gave the first bytes alone and amdgpu named neither 2026-11-18 12:22:10 -05:00
Tyler Smith 87323ced49 fix(gpu): the GPU SUMMARY line names the GPU's market name and, for an integrated GPU, its share of RAM and what Linux holds of it, where it gave only PCI IDs and said an integrated GPU's memory came from Stela's heap 2026-11-18 12:22:10 -05:00
Tyler Smith 58ed4a9d12 fix(gpu): an integrated GPU's memory notes read SHARED MEMORY (the GPU's share of RAM), and from Stela's heap only for a GPU with no share, where every integrated GPU's notes said its memory came from Stela's heap 2026-11-18 12:22:10 -05:00
Tyler Smith 6cfe7c755c fix(gpu): libdrm_amdgpu's lines are named in the boot log and its missing amdgpu.ids and /proc/cpuinfo make one line per boot, where each AMD device it opened printed the table's path and a bare No such file or directory 2026-11-18 12:22:10 -05:00
Tyler Smith dca464f7d0 test(gpu): the image test runs ANV on i915's no-op shim as well as xe's, and an AMD and an Intel GPU in one program, each GPU's ioctls under its own kernel driver's shim, where ANV ran only on xe and every run had one kernel driver 2026-11-18 12:22:10 -05:00
Tyler Smith e4d1e382ce fix(gpu): a binary archive file names a UUID made of the driver's pipeline cache UUID and the hash of the image's driver archives, and the driver reads its own UUID back, where the file named the driver's UUID, which is the same in every Stela build, so a guest's archive kept across a Stela update gave a newer driver another build's pipelines 2026-11-18 12:22:10 -05:00
Tyler Smith 8b2681500b test(gpu): cargo xtask gpu image-test runs the image's own RADV and ANV objects, C library and defines on the build host through devices, mapped memory and one submission on each GPU, where only hosted builds with the host's C library and probe results were tested and a define the image drops, such as HAVE_DLADDR, showed only on hardware 2026-11-18 12:22:10 -05:00
Tyler Smith dc73166032 fix(gpu): libdrm's stand-in names each render node's primary node, /dev/dri/card<minor>, where it named none and libdrm_amdgpu, which takes two descriptors without a name for one device, gave a second AMD GPU the first one's device while that was open, so RADV's device on the second GPU drove the first 2026-11-18 12:22:10 -05:00
Tyler Smith 5ce84b581c fix(gpu): the C library answers stat of a render node from the host's list of GPUs, as Linux's stat opens nothing, where it opened the node and closed it again, which on amdgpu built and tore down a GPU address space each time RADV or ANV made a physical device 2026-11-18 12:22:09 -05:00
Tyler Smith cc0bacf2dc fix(gpu): a client's unmap of part of a DRM mapping releases those pages and the mapping goes once all are released, as Linux's munmap does, where any unmap took the whole mapping and ANV, which maps a slab entry with the pages before it and unmaps those, lost the entry's mapping 2026-11-18 12:22:09 -05:00
Tyler Smith 0615f91a31 fix(boot): a build with no GPU driver compiles the GPU step's text without unused items, where the selection fields and the status import were unused and the strict lint refused them 2026-11-18 12:22:09 -05:00
Tyler Smith aa3311ee2e fix(boot): the loader reads an AMD GPU's IP discovery table at the register BAR's configured address through its root bridge when the firmware does not describe the BAR, with each bridge above it checked and its decoding turned on for the read, where the GPU's kind was then only taken as integrated 2026-11-18 12:22:09 -05:00
Tyler Smith 99069bb7f3 fix(memory): an integrated GPU that draws because the discrete GPU did not start is budgeted to what the heap holds past its own needs, said once, where it allocated from the heap with no budget until the heap ran out 2026-11-18 12:22:09 -05:00
Tyler Smith 1795679bdc fix(memory): the memory plan follows the GPU selection, so an integrated GPU that only shows the display beside a drawing discrete GPU grows the heap by 256M and bounds no Linux pages, and the plan's line states its rule, where such a laptop got no reserve for the integrated GPU's pages 2026-11-18 12:22:09 -05:00
Tyler Smith 607108fc6b fix(gpu): only a device whose GPU shares the processor's memory is budgeted by the share and told its working set, where a discrete GPU beside an integrated one was held to the integrated GPU's share 2026-11-18 12:22:09 -05:00
Tyler Smith db72bd3813 fix(gpu): a Vulkan instance or device the driver does not create is logged with its result, and the driver's messages while it creates the instance reach the log, where Metal's refusal gave only a mapped error and Mesa's instance-time messages were lost 2026-11-18 12:22:09 -05:00
Tyler Smith 7b884f0ded fix(gpu): a lost device's report names the connection that committed each command buffer in flight, or the device's own work, where it named only the command buffers 2026-11-18 12:22:09 -05:00
Tyler Smith b996b6689d fix(gpu): an integrated GPU's memory notes read SHARED MEMORY, system memory from Stela's heap, and every GPU note gives the heap's size beside its use, where an integrated GPU's notes read VRAM and a heap exhaustion log did not show that the GPU's memory was the heap's 2026-11-18 12:22:09 -05:00
Tyler Smith bbb1738cf4 fix(gpu): each GPU's Metal open, or failed open, prints one GPU SUMMARY line with its PCI IDs and revision, its driver and version, what the driver reports of the chip (for amdgpu its family, graphics version, the version of each firmware it runs, VRAM, visible VRAM and GTT), whether it shares system memory and Stela's heap size, Metal's working set and the Vulkan heaps, where those facts were spread over many lines or not in the log 2026-11-18 12:22:09 -05:00
Tyler Smith c2dfb62f0e fix(pci): a function refused because a stopped capability control read back otherwise names that register, and an ATS Control whose Enable bit stays set is said to be held on outside Stela, as by a hypervisor that drops the write, where the refusal named only an offset such as register 0x2b6 2026-11-18 12:22:09 -05:00
Tyler Smith 44146d3c7f fix(gpu): a Linux WARN site that fires again is printed at its first and each power-of-two firing with its count, where every firing printed a line, seventeen identical amdgpu_irq.c:670 lines after one failed amdgpu probe 2026-11-18 12:22:09 -05:00
Tyler Smith 8fc7c3bebd fix(linux): each firmware file a GPU driver asks for is named in the boot log with its bytes, or with why it was not given (not on the USB, not among the files Stela chose for the device, damaged), up to 64 requests a boot, where a delivered file left no line and a refusal said only its error number or nothing for an optional file 2026-11-18 12:22:09 -05:00
Tyler Smith 39e91c2b56 fix(memory): the Metal device on an integrated GPU refuses an allocation the GPU's share of RAM would not hold, from Linux's pages of it and the driver's measured 1.25 bytes per guest byte, tells the guest what the share backs, and the share's floor is 2.5 GiB, where RADV's advisory budget let the driver pass its GTT until every submission failed 2026-11-18 12:22:09 -05:00
Tyler Smith d2e1a9ff05 fix(gpu): identical lines in a row from the GPUs' Linux are written once, with a count at each power of two of their repeats and the total before the next line, where amdgpu's refused submission, retried every millisecond, wrote the same line 4266 times 2026-11-18 12:22:08 -05:00
Tyler Smith d867d8c6e1 fix(gpu): a fault in a client's GPU mapping holds that mapping instead of a borrow of the mapping table while Linux serves it, and a mapping unmapped meanwhile is released by its last fault, where a fault that slept in TTM under memory pressure let a new mapping's insert panic on the table's borrow 2026-11-18 12:22:08 -05:00
Tyler Smith 0b5022ec5c fix(boot): the loader's read of an AMD GPU's IP discovery table turns the GPU's memory decoding on when the firmware left it off, puts it back after, and names why a table was not read (the BAR, a refused read and its status, or all ones with decoding on), where a GPU no firmware driver started answered all ones and the log said only NoAnswer 2026-11-18 12:22:08 -05:00
Tyler Smith 5591b580fe fix(gpu): TTM's and xe's display parameters are registered under their modules, the engine's command line holds only words a built driver declares, leaving others out by name, and a refused start names the word, where Linux refused ttm.pages_limit as unknown and no GPU started 2026-11-18 12:22:08 -05:00
Tyler Smith ae308ddccb fix(gpu): an AMD GPU whose IP discovery table names a graphics or DMA block with no pinned amdgpu firmware is refused before its reset with one line naming the block, where it was claimed and amdgpu's probe failed after the reset (GC 11.5.4 and 11.5.6, SDMA 6.4.0 and 7.1.0, or a block newer than the pinned driver) 2026-11-18 12:22:08 -05:00
Tyler Smith 63088d37a1 fix(linux): pci_save_state keeps a function's PCI Express controls and pci_restore_state writes them back and sets each resizable BAR to its resource's size, as Linux does, where a driver's whole-chip reset (amdgpu's mode 1) got back only the header and a resizable BAR fell to its default size under the driver's full-size mapping 2026-11-18 12:22:08 -05:00
Tyler Smith 2fdb0486b7 fix(boot): the memory plan's look at the GPUs builds its adapter with the revision field the market names added 2026-11-18 12:22:08 -05:00
Tyler Smith b28a6bf5df feat(gpu): the boot log names every display controller with its market name, kind and why it was or was not started, and the GPU step names the GPU that draws, the one it draws in place of, and why each other one does not, where it said only started and named NVIDIA chips by code name 2026-11-18 12:22:08 -05:00
Tyler Smith c7085f5d3f feat(gpu): which display controllers start, in which order and why the others stay with the firmware is one rule over the census, tested for desktops, hybrid and mux laptops, two cards, unsupported adapters and refused claims 2026-11-18 12:22:08 -05:00
Tyler Smith c7c2d2c33b feat(gpu): a display controller has its market name by PCI ID and revision, generated by cargo xtask gpu names from the pinned pci.ids, libdrm amdgpu.ids and Mesa Intel tables, else its maker and IDs 2026-11-18 12:22:08 -05:00
Tyler Smith 3576e96b82 fix(amdgpu): the media engines (UVD, VCE, VCN, JPEG, VPE and the media scheduler) are left out at early init and their 52 firmware files are no longer pinned, where they took firmware and start time the Metal device never uses and a video decoder a previous owner left running failed the whole start 2026-11-18 12:22:08 -05:00
Tyler Smith 6ee6ef6065 fix(gpu): an AMD GPU's IP discovery table is matched against IPDS, the signature amdgpu checks, and a table not taken names the VRAM offset read and the first bytes of the binary and of its table, where the signature's bytes were reversed and every card's table was refused with TableSignature 2026-11-18 12:22:08 -05:00
Tyler Smith 1c13032c6c fix(gpu): a GPU driver's free_irq completes once its programmed MSI is turned off and read back, the vector drained and Linux's work joined, keeping the retired owners with the line, so a failed probe ends with the GPU unbound, where the close was refused as unsupported and the boot stopped with IRQ action retirement unavailable 2026-11-18 12:22:08 -05:00
Tyler Smith 23b35169ce fix(gpu): a fatal stop on the boot CPU outside Linux unloads the GPUs' drivers there, waiting for the host drivers' lock within the unload's deadline and reporting a refusal as one line, where every stop on the boot CPU left the firmware running and an AMD card's next start failed at its PSP ring 2026-11-18 12:22:08 -05:00
Tyler Smith 05e37c7f8b fix(memory): an integrated GPU that serves the Metal device gets a sixth of the free RAM, at least 2 GiB where the guest's floor allows and never under 256 MiB, beside the heap, with Linux's pages held to it and TTM's limit and amdgpu's GTT set to it, where its pages came from a heap sized without them, its GTT was half the heap and the heap ran out a minute into the desktop 2026-11-18 12:22:08 -05:00
Tyler Smith 8ad39d3e95 fix(gpu): the boot can tell before any probe whether the GPU that serves the Metal device shares the host's RAM, by amdgpu's table for a device it names and by amdgpu's own APU list of graphics versions for one it identifies by IP discovery, where only the driver's probe said so 2026-11-18 12:22:08 -05:00
Tyler Smith 23692ad023 fix(linux): the page catalog initializes a 2 MiB section of descriptors when the provider first hands out a page in it and leaves its per-page arrays unzeroed, where registration wrote every descriptor, state and record of the whole heap and the GPU start's Linux time grew from 26 to 628 ms with a 6.5 GB heap 2026-11-18 12:22:08 -05:00
Tyler Smith dc103d0e7f fix(linux): the page catalog can hold Linux to fewer pages than its inventory, refusing a request past the limit as an exhausted inventory after one shrink pass and reporting the limit as Linux's RAM, where Linux could take every page of the heap and TTM sized itself from all of it 2026-11-18 12:22:08 -05:00
Tyler Smith e54f54524d fix(gpu): amdgpu's EINVAL answer to RADV's count of a hardware engine type the GPU lacks is not logged as a refused DRM call, where every AMD start logged four refusals for UVD, VCE, UVD_ENC and VPE 2026-11-18 12:22:08 -05:00
Tyler Smith a248a38662 fix(linux): an attached PCI function has the DMA parameters Linux's PCI core gives it, a 64 KiB largest segment and a 4 GiB segment boundary that its driver may change, where it had none and amdgpu's memory setup warned at dma_set_max_seg_size 2026-11-18 12:22:08 -05:00
Tyler Smith 12f2345801 fix(gpu): an AMD GPU's IP discovery table is read through the one read-write mapping of its register BAR's first page that the claim makes for amdgpu, where the read mapped that page a second time beside the claim's read-only mapping, was refused with ResourceConflict and every IP-versioned firmware file was handed over 2026-11-18 12:22:08 -05:00
Tyler Smith b7b19c4d64 fix(output): the boot's first stop does its work on a 1 MiB stack the GPU start maps before Linux runs, where a stop raised on a Linux task's 16 KiB stack, as by amdgpu's failed probe, ran off it in the USB log store and faulted 2026-11-18 12:22:08 -05:00
Tyler Smith 90611a5574 fix(gpu): a driver stop after a failed GPU start names the maker of the GPU whose address the first error carries, else the one maker of every claimed GPU, where it always said the NVIDIA GPU did not start, also for an AMD GPU 2026-11-18 12:22:08 -05:00
Tyler Smith 68242eeaa4 fix(gpu): RADV is built with a named build ID, the note the image gives NVK and ANV, since its cache UUID comes from the shared object's own ID through dladdr, which the image lacks, where no AMD card could make a Vulkan device (cannot generate UUID) and Metal did not open 2026-11-18 12:22:08 -05:00
Tyler Smith 9af96a0172 fix(xtask): the VFIO helper reports each lent function's ATS, PRI and PASID controls and says when the host keeps ATS enabled, which a guest cannot switch off and for which Stela refuses the function, where the run only failed at the GPU's start 2026-11-18 12:22:08 -05:00
Tyler Smith d391727b34 fix(gpu): a device RADV reopens after a loss serves only once an empty submission on it signals within the first open's 2 s, looked at without waiting in a call, and one that does not or is refused fails the reopen, where the reopened device served with no check and a GPU that hung again took every client's work 2026-11-18 12:22:08 -05:00
Tyler Smith d5eb74baaa fix(gpu): a GPU found by IP discovery whose graphics block makes no graphics queue, a compute accelerator, is refused at its claim before the reset with the port's left-out line, where it was reset and started under amdgpu and RADV then opened no Vulkan device on it 2026-11-18 12:22:08 -05:00
Tyler Smith b11bd4fc59 fix(gpu): a Metal device on RADV or ANV, whose memory heaps do not overlap, counts every device-local heap in its working set, and an integrated GPU every heap of the memory it shares, with amdgpu's memory its VRAM or, integrated, its carve-out and GTT, where each counted only its largest device-local heap as NVK's nested ones need and an AMD APU's memory added GTT to a discrete GPU's VRAM 2026-11-18 12:22:08 -05:00
Tyler Smith 01b96164e1 fix(build): the GPU driver crate's build script runs again when one of its modules under build/ changes, where only an edit of build.rs itself did and a changed port table kept the old generated one 2026-11-18 12:22:08 -05:00
Tyler Smith 773e321f97 fix(gpu): the failed reopens of a lost device that first waited for its driver's reset span from that wait, so the session no GPU serves ends 30 s after the loss as before, where the 30 s wait came on top of the 30 s of failed reopens 2026-11-18 12:22:08 -05:00
Tyler Smith a02be5c304 fix(linux): a kmalloc that may not fail is served where a blocking one is and stops the boot if the heap cannot meet it, as Linux never returns NULL for one, where drm_modeset_lock_all's GFP_KERNEL | __GFP_NOFAIL context was refused on each amdgpu display hot-plug, so the connector state was restored without its locks 2026-11-18 12:22:08 -05:00
Tyler Smith e69cb22832 fix(linux): a kmalloc that may block is served inside a kernel FPU section holding only preemption off, as Linux's slab serves it there without sleeping, where every GFP_KERNEL request amdgpu's display core makes in DC_FP_START was refused and dcn30_resource_construct failed, so Navi 21 and Navi 22 never finished their probe 2026-11-18 12:22:08 -05:00
Tyler Smith 1495f38869 fix(gpu): a lost device's reopen waits while its kernel driver resets the GPU, at most 30 s, without counting as a failed reopen, and is refused only once the reset ran longer, where each connection during an amdgpu reset counted a failed reopen and a reset that never ended was waited on by no bound 2026-11-18 12:22:08 -05:00
Tyler Smith b94be1c3b5 refactor(gpu): amdgpu's table drops each device's register BAR and probe answer, which only the Southern and Sea Islands families the port leaves out differed in, and the build fails unless the profile holds amdgpu's support for exactly the families that serve and each has its registers in BAR 5 2026-11-18 12:22:08 -05:00
Tyler Smith 0e916e7408 docs(xtask): RADV's build notes say a release holds no amdgpu to ask for it and that the port drives AMD GPUs from GFX8, where they said AMD's stack gives no Vulkan driver yet 2026-11-18 12:22:08 -05:00
Tyler Smith 1e7a049bfe refactor(linux): drop pcie_get_readrq and pcie_set_readrq, which only amdgpu's Southern Islands unit called and the image no longer builds 2026-11-18 12:22:08 -05:00
Tyler Smith 06d089de93 fix(boot): the census skips the NVIDIA-only notice for a display controller only when its vendor's stack takes that device and draws, where any AMD display controller, also one amdgpu leaves to radeon or the port leaves out, counted as driven 2026-11-18 12:22:08 -05:00
Tyler Smith c6072ba5fa feat(xtask): gpu radv-test fails when the requirements RADV lacks on a chip differ from those the port's rule leaves its generation out for, or when amdgpu names a family RADV runs no device for that the rule does not, where it reported such a chip as showing displays only 2026-11-18 12:22:08 -05:00
Tyler Smith 414e7f1380 feat(firmware): the files only AMD families the port leaves out load are neither pinned nor bundled, and such a GPU is given none, so the AMD port's bundle is 567 files (254.1 MiB), where it pinned 114 files (8.0 MiB) of Southern and Sea Islands, Arcturus and Aldebaran 2026-11-18 12:22:08 -05:00
Tyler Smith c8087c5e6e feat(gpu): amdgpu's port leaves out a GPU whose RADV device cannot serve the Metal device, by a rule of the requirements RADV meets only from a graphics generation on and the generation amdgpu's own block lists give each family: Southern and Sea Islands (GFX6, GFX7, no shaderFloat16) and the Arcturus and Aldebaran accelerators are not claimed and reported once as any GPU without a driver, and the image builds no Southern or Sea Islands support, where every GPU of amdgpu's table was claimed and those showed displays only 2026-11-18 12:22:08 -05:00
Tyler Smith 2fcf53045e fix(gpu): a lost device reopens only once its kernel driver's reset of the GPU ended, asked of the reset watch, and the connection that asked says the reset still runs, where the reopen opened a new RADV device whose first work waits on an amdgpu reset without bound in the turn every client waits on 2026-11-18 12:22:08 -05:00
Tyler Smith 75186093cb fix(gpu): ATRM is read and ATPX powers a discrete GPU on only in an image that holds amdgpu, where an image without it evaluated both for a GPU it does not drive 2026-11-18 12:22:08 -05:00
Tyler Smith 12eab541f4 fix(gpu): AMD's graphics ACPI methods are looked for on the ACPI companion of a display function, the one the census finds once for each GPU and GSP-RM's data is read from, and ATPX of a GPU off the bus below its empty port's companion, where ATPX and the methods named were the first anywhere in the namespace, as of a node for a GPU the PC lacks, and each display function's companion was found twice 2026-11-18 12:22:08 -05:00
Tyler Smith 7c3394b024 fix(gpu): the Linux and Mesa series are as gpu export writes them, with full blob names, UTC dates, current hunk positions and no signature, where eight patches merged from pull requests differed and every export left a diff 2026-11-18 12:22:08 -05:00
Tyler Smith 36eb3da3c9 fix(boot): the hardware steps store the log before each part only while a bound GPU's driver watches for its own resets, where every image with amdgpu waited for eleven extra USB stores on each boot 2026-11-18 12:22:08 -05:00
Tyler Smith 674de4c0c1 feat(cli): stela writes the AMD port's firmware by default, as the image it carries holds amdgpu outside a release, and the release builds it without, where a development stick lacked the files its image's amdgpu asks for 2026-11-18 12:22:08 -05:00
Tyler Smith c5dcdc28ff feat(boot): xtask boot build makes one image with amdgpu beside NVK outside a release, and AMD's stack draws on RADV wherever the image's Mesa build holds it, where --amdgpu and --radv chose among three images 2026-11-18 12:22:08 -05:00
Tyler Smith 96ecd080ac fix(linux): the driver core's device searches walk the devices added, by parent, bus or class, with references taken under a lock and callbacks run outside it, so an Intel laptop's eDP backlight registers where class_find_device trapped 2026-11-18 12:22:08 -05:00
Tyler Smith bd69ea299b fix(gpu): RADV lowers a fragment stage's primitive ID given as NIR to the input ACO takes, as for a SPIR-V stage, where a Metal fragment function reading its primitive ID reached ACO as a system value 2026-11-18 12:22:08 -05:00
Tyler Smith 77a0e50336 feat(xtask): gpu radv-test runs RADV on every chip Mesa and amdgpu name, from GFX6 to GFX12, opens the Metal device on each as the boot does and reports its families or the requirement that leaves it display-only, and with --corpus compiles every function of the given Metal libraries through ACO and from the pipeline cache on one device of each generation, where it ran 9 fixed devices and no Metal shader 2026-11-18 12:22:08 -05:00
Tyler Smith abda79f2c5 fix(gpu): ACO's optimizer releases the operands of each instruction that dies with a vector when it turns a split of the vector into a copy, so Metal functions build on GFX8 and GFX9, where the dead instructions' operands kept their uses and ACO aborted on its validation 2026-11-18 12:22:08 -05:00
Tyler Smith e12ad36197 docs(metal): the native backend's notes on memory types, the pipeline store's cache keys and zero fills name what every Mesa driver does, where they described NVK's behaviour as the rule 2026-11-18 12:22:08 -05:00
Tyler Smith f8b623bd74 fix(metal): on a device that fixes each pipeline's topology class, as RADV, points and lines drawn with a render pipeline that names no input primitive topology bind a variant built for their class, and GPU-resident draws of it are reported once and draw triangles, where the Metal device required dynamicPrimitiveTopologyUnrestricted and refused every such device 2026-11-18 12:22:08 -05:00
Tyler Smith 97f3f4e2e1 fix(metal): the queue's timeline is exported for the guest's completion waits only when the driver reports timeline semaphores exportable as file descriptors, and completions are polled otherwise, where every driver with VK_KHR_external_semaphore_fd was assumed to export them as NVK does 2026-11-18 12:22:08 -05:00
Tyler Smith 35b565fc35 fix(gpu): RADV exposes shaderFloat16 on GFX8 by default, which runs it at single rate, so Polaris, Fiji, Tonga and Carrizo GPUs serve the Metal device, where they had float16 only by a driconf option and showed displays only 2026-11-18 12:22:08 -05:00
Tyler Smith 40e3b3533e fix(metal): a fragment function reads its position and pixel in the fragment coordinate form the driver's compiler takes, x and y, z and w apart on RADV, where it always read the whole coordinate, which RADV asserts it never gets 2026-11-18 12:22:08 -05:00
Tyler Smith d7b7fd6347 fix(metal): a vertex function's base_vertex reads Vulkan's first vertex, the vertex offset of an indexed draw, where it read OpenGL's base vertex, which ACO does not implement and aborts on 2026-11-18 12:22:08 -05:00
Tyler Smith 3c0dd58acb fix(metal): a threadgroup's memory limit is all the shared memory the Vulkan device reports, 64 KiB on RADV, where every device was capped at NAK's 16-bit 65535 bytes and a 64 KiB Metal threadgroup was refused 2026-11-18 12:22:08 -05:00
Tyler Smith 494dede4c0 fix(metal): a float atomic add on device or threadgroup memory compiles as a compare-and-swap loop on a device whose Vulkan driver lacks that add, as ANV lacks shared adds everywhere and buffer adds before LSC, where BRW was handed adds it cannot encode 2026-11-18 12:22:08 -05:00
Tyler Smith 9259961279 feat(pci): a hybrid laptop's discrete GPU that is off with no power resources of its own is powered on through ATPX before the PCI census, as amdgpu powers it, where ATPX controls its power 2026-11-18 12:22:08 -05:00
Tyler Smith 660de07a89 feat(gpu): a discrete GPU that is not the firmware's finds its video BIOS as amdgpu looks for it, through ATRM, the option ROM the firmware read, or its expansion ROM BAR, which the claim places in its bridge's window where firmware left it unassigned 2026-11-18 12:22:08 -05:00
Tyler Smith 56d6e3400a feat(gpu): an AMD GPU amdgpu identifies by IP discovery has its discovery table read at the claim, before its reset, and is given only the firmware of the IP versions it lists 2026-11-18 12:22:08 -05:00
Tyler Smith 47c59c67ec feat(gpu): where an AMD GPU is claimed, each of AMD's graphics ACPI methods the namespace holds is named once with what amdgpu does without it 2026-11-18 12:22:08 -05:00
Tyler Smith 152633295e feat(gpu): a GPU without a function reset whose driver resets it at its probe, as amdgpu does, is handed over with bus mastering off before any secondary bus reset, as Linux binds it 2026-11-18 12:22:08 -05:00
Tyler Smith 278e1fd831 feat(gpu): amdgpu claims every GPU its ID table binds, Southern and Sea Islands included as Linux builds them by default, with each family's register BAR and APU flag from the table 2026-11-18 12:22:08 -05:00
Tyler Smith 1497252317 feat(firmware): pin every firmware file amdgpu's built units name, selected per GPU by its family or, for a GPU amdgpu identifies by IP discovery, as every IP-versioned file 2026-11-18 12:22:08 -05:00
Tyler Smith da33fa2c23 feat(linux): pcie_get_readrq and pcie_set_readrq read and set a function's maximum read request size, as Southern Islands' PCIe setup in amdgpu asks 2026-11-18 12:22:07 -05:00
Tyler Smith ce43048447 feat(xtask): boot run --vfio-gpu gives the run's firmware the host's ACPI VFCT table when it holds a lent function's video BIOS, from the copy vfio-gpu.sh makes of the root-only table, so an integrated AMD GPU finds its video BIOS as on the host, where the run had no VFCT and the GPU no ROM 2026-11-18 12:22:07 -05:00
Tyler Smith 7c76660274 fix(xtask): boot run --vfio-gpu and vfio-gpu.sh lend an integrated GPU's display and HD audio functions and leave the rest of its slot to the host, a discrete card's slot still going whole, and vfio-gpu.sh opens each lent function's IOMMU group and leaves functions vfio-pci held before a run with it, where both lent every function of the slot, the host's USB controllers and security processor included 2026-11-18 12:22:07 -05:00
Tyler Smith 6ecaf7e49a feat(mediatek): program MT7921 and MT7922 SIFS and slot time in the MAC timing registers at association and on slot changes, as mt792x_mac_set_timeing does 2026-11-14 01:54:28 -05:00
Tyler Smith f4049ebd35 fix(mediatek): add only the peer's STATE_NONE record before an MT7921 or MT7922 authentication, as mt7921_mac_sta_add does 2026-11-14 01:54:28 -05:00
Tyler Smith e94ecb2c7f fix(mediatek): carry each band's probe elements and then the common elements once in a connac2 scan, as ieee80211_build_preq_ies builds its buffer 2026-11-14 01:54:28 -05:00
Tyler Smith 98f2d00ea0 feat(drivers): probe MT7921 and MT7922 Wi-Fi with the MediaTek station driver instead of reporting them unsupported 2026-11-14 01:54:28 -05:00
Tyler Smith 596949be51 feat(mediatek): take ITTIM's 0b48:7922 as an MT7922 with MediaTek's MT7922 images, as mt7921_pci_device_table lists it 2026-11-14 01:54:28 -05:00
Tyler Smith e1cfaf2404 test(mediatek): model connac2 join responses and run the PSK, SAE, PMF, DHCP, lost-link, recovery, PMKSA and open-network journeys on MT7921 and MT7922 2026-11-14 01:54:28 -05:00
Tyler Smith 58c4bb182f feat(mediatek): send MT7921 and MT7922 action frames, an ADDBA request with MT_TXD5_ADD_BA on its TID, as mt76_connac2_mac_write_txwi_80211 does 2026-11-14 01:54:28 -05:00
Tyler Smith 53c76f0a23 fix(mediatek): give MT7921 and MT7922 fixed-rate frames the lowest basic rate's connac2 rate word, as mt76_connac2_mac_tx_rate_val does 2026-11-14 01:54:28 -05:00
Tyler Smith b105de7ddb feat(mediatek): attach MT7921 and MT7922 and scan with mac80211's probe elements in every active connac2 scan 2026-11-14 01:54:28 -05:00
Tyler Smith 0333b937a2 feat(mediatek): send MT7921 and MT7922's CLC the platform's MTFG flags and each country's MTCL configuration as __mt7921_mcu_set_clc does 2026-11-14 01:54:28 -05:00
Tyler Smith 0abe4c6e84 feat(mediatek): advertise MT7921 and MT7922 station capabilities, probe elements and 6 GHz SAE records in their connac2 forms over the programmed domain 2026-11-14 01:54:28 -05:00
Tyler Smith 2ee41ceba8 feat(mediatek): plan MT7921 and MT7922 channel domain and rate power after their CLC as __mt7921_mcu_regd_update does 2026-11-14 01:54:28 -05:00
Tyler Smith 9130578f49 feat(mediatek): take MT7921 and MT7922 TXD, RXD and TXS in their connac2 layouts, with the TX-done and RSSI-notify events, instead of the MT7925's 2026-11-14 01:54:28 -05:00
Tyler Smith 4e9c84b73e feat(mediatek): send MT7921 and MT7922 ROC, EDCA, beacon filter, RX filter, BSS abort, RSSI monitor and channel RLM in their connac2 forms through the station codec 2026-11-14 01:54:28 -05:00
Tyler Smith 25379e5ba3 feat(mediatek): install MT7921 and MT7922 IGTKs as the second STA_REC_KEY_V2 key beside the cached CCMP GTK, as mt76_connac_mcu_sta_key_tlv does 2026-11-14 01:54:28 -05:00
Tyler Smith 6ff064c6b3 feat(mediatek): build MT7921 and MT7922 BSS, peer, broadcast and block-ack records in connac2 layout, with embedded WTBL TLVs, behind one per-chip station codec 2026-11-14 01:54:28 -05:00
Tyler Smith 4200d50099 feat(mediatek): scan on MT7921 and MT7922 by connac2's CE hardware scan request, cancel and scan-done events, and take their CE beacon-loss event, as mt76_connac_mcu_hw_scan and mt7921_mcu_rx_unsolicited_event do 2026-11-14 01:54:28 -05:00
Tyler Smith 021da52ce9 test(mediatek): bound every bring-up step of the MT7921 and MT7922 models through interface registration as the MT7925's 2026-11-14 01:54:28 -05:00
Tyler Smith d63dd85611 fix(mediatek): keep each scan's BSS observation until it expires, as cfg80211's BSS table does, so a PMF join takes an AP from the scan cache when the latest scan missed its beacon 2026-11-14 01:54:28 -05:00
Tyler Smith fb6669ed9b fix(wifi): let a PMF join under SAE resume a cached PMKSA by open-system authentication when its RSN element names the PMKID, and test the MT7925 rejoin and the status 53 fallback to full SAE 2026-11-14 01:54:28 -05:00
Tyler Smith e7da6a5c8c fix(mediatek): start each association's IGTK history afresh so an AP's unchanged IGTK installs again with its handshake IPN, as mac80211 installs it on every association 2026-11-14 01:54:28 -05:00
Tyler Smith dccc2612aa refactor(wifi): run the MediaTek bring-up and recovery on the driver base's stepped work and drop the Wi-Fi copy 2026-11-14 01:54:28 -05:00
Tyler Smith 19cbe7ee55 feat(wifi): join an open network's unprotected AP with no RSN element and an open port, as wpa_supplicant's key_mgmt=NONE does, refusing a protected BSS of its name 2026-11-14 01:54:28 -05:00
Tyler Smith 7b0e8d2a48 feat(wifi): cache an SAE exchange's PMKSA per AP for 12 hours and resume it by open-system authentication and its PMKID, dropping it when the resumption fails, as wpa_supplicant does 2026-11-14 01:54:28 -05:00
Tyler Smith 3f656763ab feat(mediatek): recover a lost MT7925 by a WLAN subsystem reset and the stepped bring-up, a bounded step per keeper poll, as mt7925_mac_reset_work does, and rejoin 2026-11-14 01:54:28 -05:00
Tyler Smith 956b992303 refactor(mediatek): run the bring-up as stepped async work, one register read or command a step, which the attach drives to completion 2026-11-14 01:54:28 -05:00
Tyler Smith 3efce77ad3 feat(wifi): add stepped work, async driver work polled with a no-op waker a bounded step at a time or run to completion, for radio bring-up and recovery 2026-11-14 01:54:28 -05:00
Tyler Smith 2b6939dd7e fix(wifi): derive the SAE password element four hunting-and-pecking rounds per keeper poll, committing on the poll that finds it, so no poll runs the whole derivation 2026-11-14 01:54:28 -05:00
Tyler Smith 90f437c41f feat(wifi): let a lost radio recover through Radio::recover in bounded steps the keeper polls, retrying a failed attempt after 1 s and losing the radio for good after ten in a row 2026-11-14 01:54:28 -05:00
Tyler Smith e872fdc2b9 fix(mediatek): end a firmware command that the station's poll waits on after 50 ms, the keeper's shared runtime bound, so that a hung firmware loses the radio instead of the machine 2026-11-14 01:54:28 -05:00
Tyler Smith f8062a8ad5 fix(mediatek): retry the bring-up up to ten times after a WLAN subsystem reset, as mt7925_init_hardware does, releasing each failed attempt's rings once the next reset stops them 2026-11-14 01:54:28 -05:00
Tyler Smith 8dee454a4b feat(net): let a link hand out its one-time runtime diagnostics through Link::take_diagnostic, which the Wi-Fi keeper and the probe's adapters forward 2026-11-14 01:54:28 -05:00
Tyler Smith 1fafc32e28 fix(wifi): give a station 45 s to carrier, a whole scan, join and handshake, instead of a wired PHY's 10 s 2026-11-14 01:54:28 -05:00
Tyler Smith 38a116d448 test(mediatek): carry DHCP under the handshake keys from the booted model through the keeper's link 2026-11-14 01:54:28 -05:00
Tyler Smith 3244b1af32 fix(wifi): log keeper notices once instead of returning them from receive, and stop retrying once the radio is lost for good 2026-11-14 01:54:28 -05:00
Tyler Smith 1d0e849b2b fix(mediatek): drop and count a refused receive frame as mac80211 does, keeping the frames before it, instead of failing the link's packet I/O 2026-11-14 01:54:28 -05:00
Tyler Smith 0b721ec494 feat(mediatek): enable firmware thermal protection after MAC init, as mt7925_init_work does 2026-11-14 01:54:28 -05:00
Tyler Smith 47f5909b87 fix(wifi): answer a repeated message 3 or group message without reinstalling keys, as wpa_supplicant does 2026-11-14 01:54:28 -05:00
Tyler Smith 23c3f83a6a fix(mediatek): join an AP MLD as a single-link station so the firmware keeps a non-MLD BSS and a single-link STA_REC 2026-11-14 01:54:28 -05:00
Tyler Smith ea7abcfcf1 fix(mediatek): skip unknown or repeated TX-free tokens as mt7925_mac_tx_free does instead of poisoning the data ring 2026-11-14 01:54:28 -05:00
Tyler Smith 8b415df6c6 fix(mediatek): drop a malformed or hardware-dropped receive frame, an over-long chain and surplus events and go on, as mt76's receive path does, instead of quarantining the adapter 2026-11-14 01:54:28 -05:00
Tyler Smith d8d2fe7738 fix(mediatek): set MT_HW_EMI_CTL sleep protection before the WLAN subsystem reset, as mt7925_pci_probe does 2026-11-14 01:54:28 -05:00
Tyler Smith ee6247063e fix(mediatek): download firmware after the MCU's power-on report times out, as mt792x_load_firmware warns and goes on, instead of failing the boot 2026-11-14 01:54:28 -05:00
Tyler Smith a4c5a68117 fix(mediatek): empty WFDMA rings outside MT7925's layout that another owner left counted while the engine is stopped, instead of refusing the adapter, as Linux never reads them 2026-11-14 01:54:28 -05:00
Tyler Smith 1a7d276b49 fix(mediatek): let the station transmit on indoor-only channels its AP serves, as cfg80211 never applies INDOOR_ONLY to a managed station, so US 6 GHz and EU channels 36-48 join 2026-11-14 01:54:27 -05:00
Tyler Smith 4bf1d79429 fix(mediatek): take a random locally administered station address when the firmware reports none valid, as mt76_eeprom_override does, instead of failing the attach 2026-11-14 01:54:27 -05:00
Tyler Smith 6eaeaf8f7a fix(wifi): take 32-bit DMA pages from below 4 GiB on a passthrough domain, as the DMA API bounces for a 32-bit mask, so Wi-Fi rings map without an IOMMU 2026-11-14 01:54:27 -05:00
Tyler Smith 1f077f6353 fix(wifi): tell the RTL8821C's Bluetooth to recover straight after the firmware download, as rtw88 does 2026-11-12 11:00:18 -05:00
Tyler Smith dbac98ccf2 feat(loader): pin rtw88/rtw8821c_fw.bin from the oracle and bundle it with the other Realtek Wi-Fi firmware 2026-11-12 10:55:24 -05:00
Tyler Smith 8c0f480d1f feat(drivers): match the RTL8821CE's PCI IDs 10ec:b821 and 10ec:c821 as Realtek Wi-Fi 2026-11-12 10:46:13 -05:00
Tyler Smith 0792ce4700 test(wifi): run the station journeys on an RTL8821C model through its registers and rings, crash and chip reset included, each step bounded 2026-11-12 10:43:37 -05:00
Tyler Smith a3e2af2c08 feat(wifi): RTL8821CE PCIe setup as rtw88 does it: completion timeouts off in device control 2, Bluetooth recovery once firmware runs 2026-11-12 10:35:29 -05:00
Tyler Smith 2e24f9932d feat(wifi): run the RTL8821C station runtime through its own chip operations: tune, TX power, firmware IQK, false alarms, DIG, CCK detection and power tracking 2026-11-12 10:26:58 -05:00
Tyler Smith 19ebc61483 feat(loader): rtw88/rtw8821c_fw.bin recipe and RTL8821C selection, pins pending the oracle 2026-11-12 08:54:26 -05:00
Tyler Smith 0ca707a3de feat(wifi): boot an RTL8821C through its own PHY, PCIe parameters and one-path layout, modeled end to end 2026-11-12 08:50:56 -05:00
Tyler Smith 0c5b015891 feat(wifi): RTL8821C PHY status, CCK power from its LNA tables and path A alone 2026-11-12 08:33:27 -05:00
Tyler Smith 1825f73d5b feat(wifi): RTL8821C coexistence tables, chip facts and antenna switch from rtw8821c.c 2026-11-12 08:29:18 -05:00
Tyler Smith 404621ce35 feat(wifi): RTL8821C IQK through its firmware command, polled a look per step 2026-11-12 08:17:03 -05:00
Tyler Smith 3226ee579c feat(wifi): RTL8821C TX power from its BCD by-rate and limit tables, written as absolute indices per rate 2026-11-12 08:08:09 -05:00
Tyler Smith a4c4e9d0a0 feat(wifi): RTL8821C PHY tables, rtw8821c_phy_set_param and channel switching, with SIPI RF writes 2026-11-12 08:00:07 -05:00
Tyler Smith 0b5fe9be0d feat(wifi): read the RTL8821C efuse map as rtw8821c_read_efuse does 2026-11-12 07:45:20 -05:00
Tyler Smith a630235497 feat(wifi): RTL8821C identity, power sequences, FIFO page table and MAC init from rtw8821c.c 2026-11-12 07:42:04 -05:00
Tyler Smith d19075182a refactor(wifi): read Realtek chip facts from one rtw_chip_info table instead of naming the RTL8822C in each layer 2026-11-12 07:33:14 -05:00
Tyler Smith dcf39fba3a feat(wifi): recover a lost RTL8822C by a chip reset that runs the async bring-up a bounded step per keeper poll, the same bring-up attach runs to completion 2026-11-12 07:17:58 -05:00
Tyler Smith ce362a9eb1 test(wifi): let a test attach a modeled chip at an RTL8822C BAR address, which the native register interface and ring blocks then reach in place of memory 2026-11-12 07:13:45 -05:00
Tyler Smith 3d17bab463 fix(wifi): run the RTL8822C join calibration and the leisure power save exit a step per poll, holding frames and authentication until they end 2026-11-12 06:55:37 -05:00
Tyler Smith 40fe48ec6b fix(wifi): bound the RTL8822C arbiter's calibration wait and synthesizer lock per call once the radio runs, telling each cut-short wait once 2026-11-12 06:55:37 -05:00
Tyler Smith f1fb2f8f04 fix(wifi): report a quarantined RTL8822C as a lost radio so the keeper says why once and stops servicing it 2026-11-12 06:55:37 -05:00
Tyler Smith 9d57f3c240 fix(wifi): turn off RTL8822C PCIe ASPM and deep power save on the systems rtw88's quirk list names 2026-11-12 06:55:37 -05:00
Tyler Smith 1ae9cc17dd feat(smbios): read the product SKU and first baseboard name as Linux saves DMI_PRODUCT_SKU and DMI_BOARD_NAME 2026-11-12 06:55:37 -05:00
Tyler Smith 04f4ffce6b test(wifi): point the RTL8822C PHY table generator at the tables in stela-driver-net 2026-11-12 06:55:37 -05:00
Tyler Smith a0f66c6751 fix(wifi): drop and count an RTL8822C frame or report the station refuses and handle the rest of the receive pass, instead of failing the link 2026-11-12 06:55:37 -05:00
Tyler Smith 075be22051 fix(wifi): wait up to 20 ms for the RTL8822C hardware feature report, which rtw88 reads only after the efuse dump 2026-11-12 06:55:37 -05:00
Tyler Smith b6eb301ade fix(wifi): drop an RTL8822C firmware command its busy mailbox refuses, as rtw88 does, instead of quarantining the device 2026-11-12 06:55:37 -05:00
Tyler Smith 5ec3525ffd fix(wifi): let an RTL8822C IQK that finds a done status or outlasts 300 ms go on as rtw88 does instead of quarantining the device 2026-11-12 06:55:37 -05:00
Tyler Smith c43d8af32f fix(wifi): drop RTL8822C receive descriptors rtw88 drops and take frames past an out-of-step DMA tag instead of quarantining the receive ring 2026-11-12 06:55:37 -05:00
Tyler Smith 401fea6841 feat(mediatek): recover a lost MT7925 by a WLAN subsystem reset and the stepped bring-up, a bounded step per keeper poll, as mt7925_mac_reset_work does, and rejoin 2026-11-12 06:51:42 -05:00
Tyler Smith b72e6d54e0 refactor(mediatek): run the bring-up as stepped async work, one register read or command a step, which the attach drives to completion 2026-11-12 06:51:42 -05:00
Tyler Smith 1c4e78fea8 feat(wifi): add stepped work, async driver work polled with a no-op waker a bounded step at a time or run to completion, for radio bring-up and recovery 2026-11-12 06:51:42 -05:00
Tyler Smith 448ea444fd fix(wifi): derive the SAE password element four hunting-and-pecking rounds per keeper poll, committing on the poll that finds it, so no poll runs the whole derivation 2026-11-12 06:51:42 -05:00
Tyler Smith 05fc7dc1ed feat(wifi): let a lost radio recover through Radio::recover in bounded steps the keeper polls, retrying a failed attempt after 1 s and losing the radio for good after ten in a row 2026-11-12 06:51:42 -05:00
Tyler Smith 072df32dc8 fix(mediatek): end a firmware command that the station's poll waits on after 50 ms, the keeper's shared runtime bound, so that a hung firmware loses the radio instead of the machine 2026-11-12 06:51:42 -05:00
Tyler Smith ff838bc097 fix(mediatek): retry the bring-up up to ten times after a WLAN subsystem reset, as mt7925_init_hardware does, releasing each failed attempt's rings once the next reset stops them 2026-11-12 06:51:42 -05:00
Tyler Smith 4b069a0bda feat(net): let a link hand out its one-time runtime diagnostics through Link::take_diagnostic, which the Wi-Fi keeper and the probe's adapters forward 2026-11-12 06:51:42 -05:00
Tyler Smith 858cd6a10f fix(wifi): give a station 45 s to carrier, a whole scan, join and handshake, instead of a wired PHY's 10 s 2026-11-12 06:51:42 -05:00
Tyler Smith eb9615419a test(mediatek): carry DHCP under the handshake keys from the booted model through the keeper's link 2026-11-12 06:51:42 -05:00
Tyler Smith 48facc7528 fix(wifi): log keeper notices once instead of returning them from receive, and stop retrying once the radio is lost for good 2026-11-12 06:51:42 -05:00
Tyler Smith 9483423db9 fix(mediatek): drop and count a refused receive frame as mac80211 does, keeping the frames before it, instead of failing the link's packet I/O 2026-11-12 06:51:42 -05:00
Tyler Smith ac71c74d01 feat(mediatek): enable firmware thermal protection after MAC init, as mt7925_init_work does 2026-11-12 06:51:42 -05:00
Tyler Smith bf2e46370e fix(wifi): answer a repeated message 3 or group message without reinstalling keys, as wpa_supplicant does 2026-11-12 06:51:42 -05:00
Tyler Smith 31450392e3 fix(mediatek): join an AP MLD as a single-link station so the firmware keeps a non-MLD BSS and a single-link STA_REC 2026-11-12 06:51:42 -05:00
Tyler Smith 8ace7bf53f fix(mediatek): skip unknown or repeated TX-free tokens as mt7925_mac_tx_free does instead of poisoning the data ring 2026-11-12 06:51:42 -05:00
Tyler Smith d8222a4f78 fix(mediatek): drop a malformed or hardware-dropped receive frame, an over-long chain and surplus events and go on, as mt76's receive path does, instead of quarantining the adapter 2026-11-12 06:51:42 -05:00
Tyler Smith 6831692adf fix(mediatek): set MT_HW_EMI_CTL sleep protection before the WLAN subsystem reset, as mt7925_pci_probe does 2026-11-12 06:51:42 -05:00
Tyler Smith 1a24dfe56b fix(mediatek): download firmware after the MCU's power-on report times out, as mt792x_load_firmware warns and goes on, instead of failing the boot 2026-11-12 06:51:42 -05:00
Tyler Smith d1bd35111e fix(mediatek): empty WFDMA rings outside MT7925's layout that another owner left counted while the engine is stopped, instead of refusing the adapter, as Linux never reads them 2026-11-12 06:51:42 -05:00
Tyler Smith 3a7be26799 fix(mediatek): let the station transmit on indoor-only channels its AP serves, as cfg80211 never applies INDOOR_ONLY to a managed station, so US 6 GHz and EU channels 36-48 join 2026-11-12 06:51:42 -05:00
Tyler Smith 65b03bd389 fix(mediatek): take a random locally administered station address when the firmware reports none valid, as mt76_eeprom_override does, instead of failing the attach 2026-11-12 06:51:42 -05:00
Tyler Smith 589f3a8a9b fix(wifi): take 32-bit DMA pages from below 4 GiB on a passthrough domain, as the DMA API bounces for a 32-bit mask, so Wi-Fi rings map without an IOMMU 2026-11-12 06:51:42 -05:00
1041 changed files with 168112 additions and 11912 deletions

No files matched your search

+8 -8
View File
@@ -5,21 +5,21 @@ Download the archive for your system, unpack it and plug in the USB stick. Then
Make a new stick (this erases it):
```
sudo ./stela
sudo ./stambha
```
Update an existing Stela stick to v@VERSION@:
Update an existing Stambha stick to v@VERSION@:
```
sudo ./stela update
sudo ./stambha update
```
On Windows, open Terminal with Run as administrator and write `.\stela.exe` in place of `sudo ./stela`.
On Windows, open Terminal with Run as administrator and write `.\stambha.exe` in place of `sudo ./stambha`.
On macOS, stela is not notarized. If macOS says it cannot be opened, run this once in the unpacked folder:
On macOS, stambha is not notarized. If macOS says it cannot be opened, run this once in the unpacked folder:
```
xattr -d com.apple.quarantine stela
xattr -d com.apple.quarantine stambha
```
Then boot the PC from the stick.
@@ -28,8 +28,8 @@ Then boot the PC from the stick.
## Boot log
If Stela does not work, save the boot log and include `log.txt` in your report:
If Stambha does not work, save the boot log and include `log.txt` in your report:
```
sudo ./stela log --output log.txt
sudo ./stambha log --output log.txt
```
+18 -16
View File
@@ -1,6 +1,6 @@
# One self-contained `stela` per platform. `stela` embeds stela.efi, which
# One self-contained `stambha` per platform. `stambha` embeds stela.efi, which
# carries the StelaGPU kext; the kext carries the Metal bundle and Stela.app.
# So the chain runs: Stela.app (macOS) -> stela.efi (Linux) -> stela for
# So the chain runs: Stela.app (macOS) -> stela.efi (Linux) -> stambha for
# Linux, Windows and macOS -> release.
#
# Runs only for a pushed `v*` tag, and publishes that tag's release.
@@ -87,7 +87,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 330
env:
SOURCE: stela-v${{ needs.version.outputs.version }}-source
SOURCE: stambha-v${{ needs.version.outputs.version }}-source
steps:
- uses: actions/checkout@v5
@@ -255,7 +255,7 @@ jobs:
runs-on: ${{ matrix.os }}
timeout-minutes: 90
env:
ARCHIVE: stela-v${{ needs.version.outputs.version }}-${{ matrix.platform }}
ARCHIVE: stambha-v${{ needs.version.outputs.version }}-${{ matrix.platform }}
steps:
- uses: actions/checkout@v5
@@ -304,28 +304,30 @@ jobs:
name: stela-efi
path: efi
- name: Build stela
- name: Build stambha
run: |
export STELA_EFI="$PWD/efi/stela.efi"
# As the release image, without the AMD port: no AMD firmware on
# the sticks it makes.
for target in ${{ matrix.targets }}; do
cargo build --release --locked -p stela-cli --target "$target"
cargo build --release --locked -p stela-cli --no-default-features --target "$target"
done
mkdir -p "$ARCHIVE"
case "$RUNNER_OS" in
Windows) cp target/x86_64-pc-windows-msvc/release/stela.exe "$ARCHIVE/" ;;
Windows) cp target/x86_64-pc-windows-msvc/release/stambha.exe "$ARCHIVE/" ;;
macOS)
lipo -create -output "$ARCHIVE/stela" \
target/aarch64-apple-darwin/release/stela target/x86_64-apple-darwin/release/stela
codesign --force --sign - "$ARCHIVE/stela"
lipo -info "$ARCHIVE/stela"
lipo -create -output "$ARCHIVE/stambha" \
target/aarch64-apple-darwin/release/stambha target/x86_64-apple-darwin/release/stambha
codesign --force --sign - "$ARCHIVE/stambha"
lipo -info "$ARCHIVE/stambha"
;;
*) cp target/x86_64-unknown-linux-gnu/release/stela "$ARCHIVE/" ;;
*) cp target/x86_64-unknown-linux-gnu/release/stambha "$ARCHIVE/" ;;
esac
- name: Check stela
- name: Check stambha
run: |
binary="$(ls "$ARCHIVE"/stela*)"
expected="stela ${{ needs.version.outputs.version }}"
binary="$(ls "$ARCHIVE"/stambha*)"
expected="Stambha ${{ needs.version.outputs.version }}"
actual="$("$binary" --version)"
[[ "$actual" == "$expected" ]] || { echo "::error::$binary --version printed '$actual', not '$expected'"; exit 1; }
python=python3
@@ -366,7 +368,7 @@ jobs:
- uses: actions/download-artifact@v4
with:
pattern: stela-v*
pattern: stambha-v*
path: dist
merge-multiple: true
Generated
+29 -40
View File
@@ -2103,22 +2103,9 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stambha-engine"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"serde",
"serde_json",
"stela-compiler",
"stela-engine",
"tempfile",
]
[[package]]
name = "stela-boot-core"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"serde_json",
"sha2",
@@ -2126,6 +2113,7 @@ dependencies = [
"stela-contracts",
"stela-crypto",
"stela-driver-base",
"stela-driver-core",
"stela-drivers",
"stela-engine",
"stela-formats",
@@ -2138,7 +2126,7 @@ dependencies = [
[[package]]
name = "stela-c-build"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"cc",
"libc",
@@ -2149,7 +2137,7 @@ dependencies = [
[[package]]
name = "stela-cli"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"aes 0.8.4",
"anyhow",
@@ -2193,7 +2181,7 @@ dependencies = [
[[package]]
name = "stela-compiler"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"rustc_apfloat",
"serde",
@@ -2202,14 +2190,14 @@ dependencies = [
[[package]]
name = "stela-contracts"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"serde",
]
[[package]]
name = "stela-crypto"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"aes 0.8.4",
"chacha20 0.10.2",
@@ -2223,7 +2211,7 @@ dependencies = [
[[package]]
name = "stela-dev"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"clap",
@@ -2242,7 +2230,7 @@ dependencies = [
[[package]]
name = "stela-driver-audio"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"sha2",
"stela-driver-base",
@@ -2251,7 +2239,7 @@ dependencies = [
[[package]]
name = "stela-driver-base"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"cc",
"sha2",
@@ -2263,7 +2251,7 @@ dependencies = [
[[package]]
name = "stela-driver-core"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"sha2",
"stela-contracts",
@@ -2272,7 +2260,7 @@ dependencies = [
[[package]]
name = "stela-driver-gpu"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"ash",
"cc",
@@ -2284,12 +2272,13 @@ dependencies = [
"stela-driver-base",
"stela-driver-core",
"stela-linux",
"stela-loader",
"triomphe",
]
[[package]]
name = "stela-driver-net"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"aes 0.8.4",
"hmac",
@@ -2305,7 +2294,7 @@ dependencies = [
[[package]]
name = "stela-driver-storage"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"stela-driver-base",
"stela-driver-core",
@@ -2313,7 +2302,7 @@ dependencies = [
[[package]]
name = "stela-drivers"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"sha2",
"stela-contracts",
@@ -2328,7 +2317,7 @@ dependencies = [
[[package]]
name = "stela-engine"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"hex",
@@ -2342,19 +2331,18 @@ dependencies = [
"stela-fingerprint",
"stela-formats",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "stela-fingerprint"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"sha2",
]
[[package]]
name = "stela-formats"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"crypto-bigint",
"hex",
@@ -2372,7 +2360,7 @@ dependencies = [
[[package]]
name = "stela-gpu-maintenance"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"clap",
@@ -2389,7 +2377,7 @@ dependencies = [
[[package]]
name = "stela-linux"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"cc",
"libc",
@@ -2403,7 +2391,7 @@ dependencies = [
[[package]]
name = "stela-loader"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"hex",
@@ -2426,7 +2414,7 @@ dependencies = [
[[package]]
name = "stela-metal-input"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"stela-contracts",
"stela-crypto",
@@ -2434,7 +2422,7 @@ dependencies = [
[[package]]
name = "stela-runtime"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"getrandom 0.2.17",
@@ -2460,7 +2448,7 @@ dependencies = [
[[package]]
name = "stela-soc"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"aes 0.8.4",
"hex",
@@ -2480,7 +2468,7 @@ dependencies = [
[[package]]
name = "stela-soc-data"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"hex",
"sha2",
@@ -2491,7 +2479,7 @@ dependencies = [
[[package]]
name = "stela-tls"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"aes 0.9.3",
"aes-gcm 0.11.1",
@@ -3082,7 +3070,7 @@ dependencies = [
[[package]]
name = "xtask"
version = "0.5.0"
version = "0.6.2"
dependencies = [
"anyhow",
"clap",
@@ -3099,6 +3087,7 @@ dependencies = [
"stela-cli",
"stela-compiler",
"stela-contracts",
"stela-driver-core",
"stela-drivers",
"stela-engine",
"stela-formats",
+1 -2
View File
@@ -1,6 +1,5 @@
[workspace]
members = [
"crates/stambha-engine",
"crates/stela-boot-core",
"crates/stela-crypto",
"crates/stela-cli",
@@ -61,7 +60,7 @@ exclude = ["crates/stela-boot", "crates/stela-mesa", "third_party/smoltcp"]
resolver = "2"
[workspace.package]
version = "0.5.0"
version = "0.6.2"
edition = "2024"
license = "GPL-2.0-or-later"
repository = "https://github.com/tylertms/Stela"
+75 -2
View File
@@ -16,7 +16,6 @@ without it that links Apache-2.0 code is distributed under GPL-3.0-or-later
stela.efi GPL-2.0-only (contains Linux code)
stela (CLI) GPL-3.0-or-later (links Apache-2.0 crates and no
GPL-2.0-only code)
stambha-engine GPL-3.0-or-later (hosted engine process)
stela-gpu-maintenance GPL-2.0-or-later
Stela.app GPL-2.0-or-later
StelaGPU.kext GPL-2.0-or-later
@@ -39,11 +38,15 @@ Component License Where
Linux kernel v7.2.12 (source in GPL-2.0-only, GPL-2.0-or-later, stela.efi
third_party/linux, Rust ports in MIT, GPL-2.0 OR BSD-3-Clause and
crates/stela-driver*/, other per-file terms
stela-linux, stela-boot-core)
stela-linux, stela-boot-core,
stela-soc)
FreeBSD e1000 driver BSD-3-Clause stela.efi
MediaTek mt76 Wi-Fi, btmtk and BSD-3-Clause-Clear, ISC stela.efi
wireless regulatory ports
Asahi Linux hci_bcm4377 GPL-2.0-only OR MIT (MIT used) stela.efi
VoodooInput (acidanthera), the GPL-2.0-only stela.efi
emulated Magic Trackpad 2's
reports and descriptors
Intel drm_eld.h definitions MIT stela.efi
Mesa 26.2.5 (NVK, NIR, NAK, MIT; c11 threads BSL-1.0 stela.efi
Vulkan runtime)
@@ -65,6 +68,12 @@ contributors)
Spleen 2.1.0 font (Frederic BSD-2-Clause stela.efi
Cambus)
Arm AARCHMRS data (Arm Limited) BSD-3-Clause stela.efi, stela
GPU market names: PCI ID GPL-2.0-or-later OR BSD-3-Clause stela.efi
database pci.ids 2026.02.12 (used under GPL-2.0-or-later);
(Martin Mares, Albert Pool), MIT (amdgpu.ids, Mesa)
libdrm data/amdgpu.ids, Mesa
include/pci_ids (generated into
crates/stela-driver-gpu/src/names)
corsix/amx (Peter Cawley) MIT stela.efi, stela
Rust standard library and MIT OR Apache-2.0 (MIT used) stela.efi, stela
RustCrypto portions in
@@ -373,6 +382,15 @@ crates/stela-driver-base/src/platform/: Smart Battery System native SMBus
transport
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-or-later
drivers/acpi/sbs.c
crates/stela-driver-base/src/platform/: ACPI control-method power button
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later
drivers/acpi/button.c
crates/stela-driver-base/src/platform/: ASUS WMI hotkey events and keyboard
backlight
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0 ; GPL-2.0-or-later
drivers/platform/wmi/core.c, drivers/platform/x86/asus-nb-wmi.c,
drivers/platform/x86/asus-wmi.c,
include/linux/platform_data/x86/asus-wmi.h
crates/stela-driver-gpu/src/: GPU sources and patch series
Linux a804c5742bff224d4cb4d25dd383554d598be32b; Apache-2.0 ; Apache-2.0
WITH LLVM-exception ; BSD-3-Clause OR GPL-2.0 ; GPL-2.0-only ;
@@ -664,6 +682,22 @@ crates/stela-driver-net/src/wifi/mediatek/: MT7925 station MLD links
Linux a804c5742bff224d4cb4d25dd383554d598be32b; see source headers
drivers/net/wireless/mediatek/mt76/mt7925/mcu.c, net/mac80211/mlme.c,
net/mac80211/rx.c
crates/stela-driver-net/src/wifi/mediatek/: MediaTek MT7921 and MT7922
(mt7921e, connac2) station: TXD, RXD and TXS, MCU station, BSS, WTBL and
key records, hardware scan, CLC, regulatory and MAC timing
Linux a804c5742bff224d4cb4d25dd383554d598be32b; BSD-3-Clause-Clear
drivers/net/wireless/mediatek/mt76/mt76_connac2_mac.h,
drivers/net/wireless/mediatek/mt76/mt76_connac_mac.c,
drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.c,
drivers/net/wireless/mediatek/mt76/mt76_connac_mcu.h,
drivers/net/wireless/mediatek/mt76/mt7921/init.c,
drivers/net/wireless/mediatek/mt76/mt7921/mac.c,
drivers/net/wireless/mediatek/mt76/mt7921/main.c,
drivers/net/wireless/mediatek/mt76/mt7921/mcu.c,
drivers/net/wireless/mediatek/mt76/mt7921/pci.c,
drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c,
drivers/net/wireless/mediatek/mt76/mt792x_core.c,
drivers/net/wireless/mediatek/mt76/mt792x_mac.c
crates/stela-driver-net/src/wifi/realtek/: Realtek PCIe Wi-Fi firmware and
identity primitives
Linux a804c5742bff224d4cb4d25dd383554d598be32b,
@@ -702,6 +736,23 @@ crates/stela-driver-net/src/wifi/realtek/: Realtek RTL8822C native firmware
crates/stela-driver-net/src/wifi/realtek/: Realtek RTL8822C station
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only
net/mac80211/scan.c, net/mac80211/wpa.c, net/wireless/reg.c
crates/stela-driver-net/src/wifi/realtek/: Realtek RTL8821C (rtw88)
station and the shared rtw_chip_info table, with the RTL8822C's chip-reset
recovery, PCIe ASPM quirks and stepped calibration
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0 OR BSD-3-Clause
drivers/net/wireless/realtek/rtw88/coex.c,
drivers/net/wireless/realtek/rtw88/fw.c,
drivers/net/wireless/realtek/rtw88/main.c,
drivers/net/wireless/realtek/rtw88/main.h,
drivers/net/wireless/realtek/rtw88/pci.c,
drivers/net/wireless/realtek/rtw88/phy.c,
drivers/net/wireless/realtek/rtw88/reg.h,
drivers/net/wireless/realtek/rtw88/rtw8821c.c,
drivers/net/wireless/realtek/rtw88/rtw8821c.h,
drivers/net/wireless/realtek/rtw88/rtw8821c_table.c,
drivers/net/wireless/realtek/rtw88/rtw8821c_table.h,
drivers/net/wireless/realtek/rtw88/rtw8821ce.c,
drivers/net/wireless/realtek/rtw88/rtw8822c.c
crates/stela-driver-net/src/wifi/realtek/ax/: Realtek RTL8852C (rtw89) native
PCIe power, efuse, DMA, firmware download, MAC init, H2C/C2H command channel,
BB/RF table, RF register page, coex Wi-Fi grant, calibration, channel, TX
@@ -844,6 +895,10 @@ crates/stela-drivers/src/input/: Native input timer admission
crates/stela-drivers/src/input/: Standard HID-over-I2C
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only
drivers/hid/hid-ids.h, drivers/hid/i2c-hid/i2c-hid-core.c
crates/stela-drivers/src/input/: Precision touchpad whole frames, their palms
and scan-time clock
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later
drivers/hid/hid-multitouch.c
crates/stela-drivers/src/input/: RMI4 transport and F01 control substrate
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only
drivers/input/rmi4/rmi_bus.h, drivers/input/rmi4/rmi_driver.c,
@@ -888,6 +943,9 @@ crates/stela-drivers/src/input/: AMD SFH v2
crates/stela-drivers/src/input/ish/: Intel ISH resident-firmware transport
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only
drivers/hid/intel-ish-hid/, include/linux/intel-ish-client-if.h
crates/stela-drivers/src/probe/: ACPI video brightness switching
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later
drivers/acpi/acpi_video.c
crates/stela-drivers/src/usb/: USB SuperSpeed endpoint contexts
Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0 ; GPL-2.0-only
drivers/usb/host/xhci-mem.c, include/uapi/linux/usb/ch9.h
@@ -1037,6 +1095,12 @@ crates/stela-drivers/src/usb/bluetooth/: Intel USB Bluetooth legacy RSA
crates/stela-drivers/src/usb/bluetooth/: Realtek Bluetooth EPATCH v1 staging
Linux 59f9fc2ef8d1e312d2a613d4e1ffad2ff31a0a01; GPL-2.0-or-later
drivers/bluetooth/btrtl.c
crates/stela-drivers/src/usb/bluetooth/: Realtek RTL8852CU identity, its v2
then v1 image, the 0xfc66 drop of a running patch and a passive LE scan
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later
drivers/bluetooth/btrtl.c, drivers/bluetooth/btusb.c,
net/bluetooth/hci_core.c, net/bluetooth/hci_event.c,
net/bluetooth/hci_sync.c
crates/stela-drivers/src/usb/bluetooth/: MediaTek MT79xx Bluetooth firmware
staging
Linux 59f9fc2ef8d1e312d2a613d4e1ffad2ff31a0a01,
@@ -1167,3 +1231,12 @@ crates/stela-linux/src/compat/kernel/: Linux kernel services for the unchanged
lib/list_sort.c, lib/seq_buf.c, lib/sort.c, lib/usercopy.c,
lib/vsprintf.c, mm/interval_tree.c, mm/memory.c, mm/mmap.c, mm/slab.h,
mm/slub.c, mm/util.c, mm/vmalloc.c
crates/stela-soc/src/usb/: Emulated Magic Trackpad 2: its USB function,
descriptors, multitouch feature answers and reports
Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later
drivers/hid/hid-ids.h, drivers/hid/hid-magicmouse.c
VoodooInput d897813718c2ef9ad143b6a86240fe52dcb1693e; GPL-2.0-only
VoodooInput/VoodooInputIDs.hpp,
VoodooInput/VoodooInputSimulator/VoodooInputActuatorDevice.cpp,
VoodooInput/VoodooInputSimulator/VoodooInputSimulatorDevice.cpp,
VoodooInput/VoodooInputSimulator/VoodooInputSimulatorDevice.hpp
+12 -40
View File
@@ -1,5 +1,5 @@
<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/canvas-night.svg"><img src="assets/readme/canvas-dawn.svg" width="100%" alt="Stambha: Apple-silicon macOS, on the PC you already have. It runs the real, unmodified Apple-silicon macOS on an ordinary Intel or AMD PC, translating it as it runs. Status: NVIDIA works; AMD experimental; Intel in testing; Wi-Fi works on RTL8852CE; laptops partly; sound and Bluetooth coming. Speed: Stambha 0.6.1 is about 1.5x Stela 0.5.0; more speed is in progress."></picture></p>
<p align="center"><a href="https://github.com/garvitsurana271/stambha/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-download-night.svg"><img src="assets/readme/btn-download-dawn.svg" width="32%" alt="Download Stambha 0.6.1"></picture></a>&nbsp;<a href="https://discord.gg/M66z9fPJy5"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-discord-night.svg"><img src="assets/readme/btn-discord-dawn.svg" width="32%" alt="Join the Discord"></picture></a>&nbsp;<a href="https://garvitsurana271.github.io/stambha/"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-website-night.svg"><img src="assets/readme/btn-website-dawn.svg" width="32%" alt="Website"></picture></a></p>
<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/canvas-night.svg"><img src="assets/readme/canvas-dawn.svg" width="100%" alt="Stambha: Apple-silicon macOS, on the PC you already have. It runs the real, unmodified Apple-silicon macOS on an ordinary Intel or AMD PC, translating it as it runs. Status: NVIDIA works; AMD and Intel experimental; Wi-Fi works on RTL8852CE; laptops partly; sound and Bluetooth coming. Speed: Stambha 0.6.1 is about 1.5x Stela 0.5.0; more speed is in progress."></picture></p>
<p align="center"><a href="https://github.com/garvitsurana271/stambha/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-download-night.svg"><img src="assets/readme/btn-download-dawn.svg" width="32%" alt="Download Stambha 0.6.2"></picture></a>&nbsp;<a href="https://discord.gg/M66z9fPJy5"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-discord-night.svg"><img src="assets/readme/btn-discord-dawn.svg" width="32%" alt="Join the Discord"></picture></a>&nbsp;<a href="https://garvitsurana271.github.io/stambha/"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-website-night.svg"><img src="assets/readme/btn-website-dawn.svg" width="32%" alt="Website"></picture></a></p>
<p align="center"><sub>Stambha runs the real, unmodified Apple-silicon macOS on ordinary Intel and AMD PCs, desktops and laptops, from a USB stick. Free and open source.</sub></p>
<!-- SCREENSHOTS: add community showcase shots here once their owners say yes, each with "by @name" under it -->
@@ -11,8 +11,8 @@
| 🖥️ **macOS on your PC** | Apple-silicon macOS boots, with NVIDIA GPU acceleration (GTX 16, RTX 20/30/40/50) |
| ⚡ **About 1.5x faster than Stela 0.5.0** | Hundreds of translator and engine improvements, and Apple's matrix engine (AMX) running natively on your CPU |
| 🛡️ **Steady** | No Wi-Fi freezes, laptop touchpads stay working, and a macOS crash stops cleanly with the log saved |
| 📶 **Wi-Fi** | Install over Wi-Fi and network inside macOS with a Realtek RTL8852CE; more chips experimental |
| 🎮 **AMD & Intel graphics** | Experimental: Radeon RX 6000 and RX 7000 cards boot macOS, and Intel built-in graphics now reach the macOS desktop in test builds (RX 9000 in testing; early builds on Discord) |
| 📶 **Wi-Fi** | Install over Wi-Fi and network inside macOS with a Realtek RTL8852CE; Intel AX211 (8086:51f1) and MediaTek MT7925 experimental |
| 🎮 **AMD & Intel graphics** | Experimental, in the same download: Radeon RX 6000 and RX 7000 cards boot macOS, and Intel Iris Xe and UHD built-in graphics reach the macOS desktop (RX 9000 in testing; early builds on Discord) |
## Safe for the system you already have
@@ -28,9 +28,8 @@ Installing macOS next to Windows or Linux should never risk them. Stambha's inst
## Get started
1. **[Download Stambha](https://github.com/garvitsurana271/stambha/releases/latest)** for Windows or Linux. AMD or Intel
graphics? Grab the [experimental build](https://github.com/garvitsurana271/stambha/releases/tag/v0.6.1-gpu-experimental),
or the latest test build on Discord.
1. **[Download Stambha](https://github.com/garvitsurana271/stambha/releases/latest)** for Windows or Linux. One download
covers NVIDIA, AMD and Intel graphics; test builds are on Discord.
2. **Make the USB stick:** run `stambha create` and pick your stick. Already on Stela? `stambha update` keeps your macOS.
3. **Boot from the stick** and choose **Install macOS**. It installs into empty space next to your other systems.
@@ -47,7 +46,7 @@ Stuck? **[Join the Discord](https://discord.gg/M66z9fPJy5)**: help, hardware rep
| Firmware | 64-bit UEFI with Secure Boot off |
| GPU | NVIDIA GeForce GTX 16 or RTX 20/30/40/50 series. Laptops with a MUX switch: use dGPU-only mode. AMD and Intel: experimental |
| Disk | NVMe, or SATA in AHCI mode, with **60 GB or more of unallocated space** (shrink a partition, leave the space empty) |
| Network | Ethernet (Intel, Realtek, Broadcom, Aquantia, Qualcomm Atheros, common USB adapters) or Realtek RTL8852CE Wi-Fi |
| Network | Ethernet (Intel, Realtek, Broadcom, Aquantia, Qualcomm Atheros, common USB adapters) or Realtek RTL8852CE Wi-Fi. Intel AX211 and MediaTek Wi-Fi: experimental |
| USB stick | 8 GB or more |
</details>
@@ -67,41 +66,14 @@ build fetches and compiles Linux, Mesa and LLVM sources and takes a long time. I
command keeps its original name until the rename to `stambha` lands.
</details>
### Hosted engine for VM managers
Build the standalone Windows x86-64 process with `cargo build --locked --release -p stambha-engine`.
```powershell
.\target\release\stambha-engine.exe info
.\target\release\stambha-engine.exe self-test
```
Each command writes one JSON object to standard output and exits with a nonzero code on error.
`info` reports the runtime kind `stambha-hosted`, the protocol version and the available capabilities.
`self-test` translates and executes two blocks from a built-in ARM64 program and reports the register
result. The check uses no installation media or guest disk.
`boot-plan` prepares a per-VM EDK2 variable store and returns `exe_path`, `args`, `work_dir` and
`serial_log`. Reims-Go can pass the command fields to its L3 Guest Driver's `host/vm.spawn` API
and track the QEMU PID directly.
```powershell
.\target\release\stambha-engine.exe boot-plan --qemu $qemuExe --firmware-code $uefiCode `
--firmware-vars $uefiTemplate --vm-dir $vmDir --boot-volume $bootVolume
```
Use `--usb-image` for a raw Stambha USB image. It uses a temporary overlay by default.
An explicitly supplied raw NVMe disk via `--disk` keeps guest writes.
The QEMU path runs the existing Stambha EFI engine inside a virtual PC. The native Windows
self-test exercises the optional direct translation path. Full macOS boot has yet to be
validated on the hosted runtime, so `info` reports `macos_boot: false`.
## What's next
- **0.6.2:** Intel graphics, safer installs over flaky networks, many fixes from your logs
- **0.6.2 (out now):** AMD and Intel graphics in the main download (experimental), Intel AX211 Wi-Fi and Bluetooth,
MediaTek Wi-Fi fixes, faster USB start, many fixes from your logs
- **In testing:** laptop battery, lid and brightness keys (`--acpi-hardware`), speed fixes measured on real hardware
- **0.6.5:** sound and Bluetooth
- **The next big release:** big speed work, real Wi-Fi inside macOS, AMD and Intel graphics in the main build, laptop battery, brightness and sleep, and an installer app with a hardware check
- **The next big release:** big speed work, macOS's own Wi-Fi menu, laptop battery, brightness and real sleep, and an
installer app with a hardware check
## Contributing
+1 -1
View File
@@ -1,2 +1,2 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 427 112" width="427" height="112"><defs><linearGradient id="b" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#FFD27A"/><stop offset="1" stop-color="#F07A28"/></linearGradient></defs>
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M120.04999999999998 65.1V61.525H123.62499999999999Q124.975 61.525 126.04999999999998 61.1125Q127.12499999999999 60.7 127.875 59.95Q128.625 59.2 129.02499999999998 58.150000000000006Q129.42499999999998 57.1 129.42499999999998 55.825Q129.42499999999998 54.5 129.02499999999998 53.4625Q128.625 52.425 127.875 51.6875Q127.12499999999999 50.95 126.04999999999998 50.5625Q124.975 50.175 123.62499999999999 50.175H120.04999999999998V46.625H123.42499999999998Q125.89999999999999 46.625 127.73749999999998 47.35Q129.575 48.075 130.8125 49.325Q132.04999999999998 50.575 132.67499999999998 52.1875Q133.29999999999998 53.8 133.29999999999998 55.55V56.1Q133.29999999999998 57.75 132.67499999999998 59.3625Q132.04999999999998 60.975 130.8125 62.2625Q129.575 63.55 127.73749999999998 64.32499999999999Q125.89999999999999 65.1 123.42499999999998 65.1ZM116.725 65.1V46.625H120.54999999999998V65.1Z M142.64999999999998 65.475Q140.84999999999997 65.475 139.46249999999998 64.9125Q138.075 64.35 137.11249999999998 63.3625Q136.14999999999998 62.375 135.66249999999997 61.125Q135.17499999999998 59.875 135.17499999999998 58.475V57.95Q135.17499999999998 56.525 135.6875 55.25Q136.2 53.975 137.17499999999998 53.0Q138.14999999999998 52.025 139.53749999999997 51.45Q140.92499999999998 50.875 142.64999999999998 50.875Q144.39999999999998 50.875 145.77499999999998 51.45Q147.14999999999998 52.025 148.12499999999997 53.0Q149.09999999999997 53.975 149.61249999999995 55.25Q150.12499999999997 56.525 150.12499999999997 57.95V58.475Q150.12499999999997 59.875 149.6375 61.125Q149.14999999999998 62.375 148.18749999999997 63.3625Q147.22499999999997 64.35 145.83749999999998 64.9125Q144.45 65.475 142.64999999999998 65.475ZM142.64999999999998 62.3Q143.87499999999997 62.3 144.7 61.775Q145.52499999999998 61.25 145.95 60.3125Q146.37499999999997 59.375 146.37499999999997 58.225Q146.37499999999997 57.0 145.93749999999997 56.075Q145.49999999999997 55.15 144.66249999999997 54.6125Q143.825 54.075 142.64999999999998 54.075Q141.47499999999997 54.075 140.6375 54.6125Q139.79999999999998 55.15 139.36249999999998 56.075Q138.92499999999998 57.0 138.92499999999998 58.225Q138.92499999999998 59.375 139.34999999999997 60.3125Q139.77499999999998 61.25 140.61249999999998 61.775Q141.45 62.3 142.64999999999998 62.3Z M157.575 65.0 160.125 51.825H164.325L167.25 65.0H164.325L161.325 51.9H162.95L160.25 65.0ZM156.6 65.0 156.575 61.9H159.325L159.35 65.0ZM155.0 65.0 151.325 51.375H154.95L158.42499999999998 65.0ZM165.275 65.0 165.29999999999998 61.9H168.04999999999998L168.025 65.0ZM166.375 65.0 169.475 51.375H172.875L169.6 65.0Z M175.475 65.0V51.375H178.42499999999998V57.225H178.2Q178.2 55.125 178.73749999999998 53.7375Q179.27499999999998 52.35 180.375 51.6375Q181.475 50.925 183.075 50.925H183.225Q185.64999999999998 50.925 186.91249999999997 52.5Q188.17499999999998 54.075 188.17499999999998 57.2V65.0H184.42499999999998V56.925Q184.42499999999998 55.75 183.73749999999998 55.025Q183.04999999999998 54.3 181.875 54.3Q180.67499999999998 54.3 179.95 55.05Q179.225 55.8 179.225 57.025V65.0Z M191.89999999999998 65.0V46.75H195.64999999999998V65.0ZM190.25 49.525V46.75H195.64999999999998V49.525Z M206.075 65.475Q204.27499999999998 65.475 202.8875 64.9125Q201.5 64.35 200.5375 63.3625Q199.575 62.375 199.08749999999998 61.125Q198.6 59.875 198.6 58.475V57.95Q198.6 56.525 199.1125 55.25Q199.625 53.975 200.6 53.0Q201.575 52.025 202.96249999999998 51.45Q204.35 50.875 206.075 50.875Q207.825 50.875 209.2 51.45Q210.575 52.025 211.54999999999998 53.0Q212.52499999999998 53.975 213.03749999999997 55.25Q213.54999999999998 56.525 213.54999999999998 57.95V58.475Q213.54999999999998 59.875 213.0625 61.125Q212.575 62.375 211.61249999999998 63.3625Q210.64999999999998 64.35 209.2625 64.9125Q207.875 65.475 206.075 65.475ZM206.075 62.3Q207.29999999999998 62.3 208.125 61.775Q208.95 61.25 209.375 60.3125Q209.79999999999998 59.375 209.79999999999998 58.225Q209.79999999999998 57.0 209.36249999999998 56.075Q208.92499999999998 55.15 208.08749999999998 54.6125Q207.25 54.075 206.075 54.075Q204.89999999999998 54.075 204.0625 54.6125Q203.225 55.15 202.7875 56.075Q202.35 57.0 202.35 58.225Q202.35 59.375 202.77499999999998 60.3125Q203.2 61.25 204.0375 61.775Q204.875 62.3 206.075 62.3Z M224.725 65.0V60.975H224.1V56.525Q224.1 55.425 223.5625 54.875Q223.02499999999998 54.325 221.875 54.325Q221.29999999999998 54.325 220.41249999999997 54.35Q219.52499999999998 54.375 218.59999999999997 54.4125Q217.67499999999998 54.45 216.92499999999998 54.5V51.325Q217.52499999999998 51.275 218.2625 51.2375Q219.0 51.2 219.8 51.175Q220.6 51.15 221.29999999999998 51.15Q223.39999999999998 51.15 224.8125 51.724999999999994Q226.225 52.3 226.95 53.5Q227.67499999999998 54.7 227.67499999999998 56.6V65.0ZM220.35 65.35Q218.875 65.35 217.7625 64.82499999999999Q216.64999999999998 64.3 216.03749999999997 63.325Q215.42499999999998 62.35 215.42499999999998 60.975Q215.42499999999998 59.475 216.17499999999998Line truncated
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M117.51249999999999 65.1V61.525H121.08749999999999Q122.4375 61.525 123.51249999999999 61.1125Q124.58749999999999 60.7 125.33749999999999 59.95Q126.08749999999999 59.2 126.48749999999998 58.150000000000006Q126.88749999999999 57.1 126.88749999999999 55.825Q126.88749999999999 54.5 126.48749999999998 53.4625Q126.08749999999999 52.425 125.33749999999999 51.6875Q124.58749999999999 50.95 123.51249999999999 50.5625Q122.4375 50.175 121.08749999999999 50.175H117.51249999999999V46.625H120.88749999999999Q123.3625 46.625 125.19999999999999 47.35Q127.0375 48.075 128.27499999999998 49.325Q129.5125 50.575 130.1375 52.1875Q130.7625 53.8 130.7625 55.55V56.1Q130.7625 57.75 130.1375 59.3625Q129.5125 60.975 128.27499999999998 62.2625Q127.0375 63.55 125.19999999999999 64.32499999999999Q123.3625 65.1 120.88749999999999 65.1ZM114.1875 65.1V46.625H118.01249999999999V65.1Z M140.1125 65.475Q138.3125 65.475 136.925 64.9125Q135.53750000000002 64.35 134.57500000000002 63.3625Q133.6125 62.375 133.125 61.125Q132.63750000000002 59.875 132.63750000000002 58.475V57.95Q132.63750000000002 56.525 133.15000000000003 55.25Q133.66250000000002 53.975 134.63750000000002 53.0Q135.6125 52.025 137.0 51.45Q138.38750000000002 50.875 140.1125 50.875Q141.8625 50.875 143.2375 51.45Q144.6125 52.025 145.5875 53.0Q146.5625 53.975 147.075 55.25Q147.5875 56.525 147.5875 57.95V58.475Q147.5875 59.875 147.10000000000002 61.125Q146.6125 62.375 145.65 63.3625Q144.6875 64.35 143.3 64.9125Q141.91250000000002 65.475 140.1125 65.475ZM140.1125 62.3Q141.3375 62.3 142.16250000000002 61.775Q142.9875 61.25 143.41250000000002 60.3125Q143.8375 59.375 143.8375 58.225Q143.8375 57.0 143.4 56.075Q142.9625 55.15 142.125 54.6125Q141.28750000000002 54.075 140.1125 54.075Q138.9375 54.075 138.10000000000002 54.6125Q137.26250000000002 55.15 136.82500000000002 56.075Q136.38750000000002 57.0 136.38750000000002 58.225Q136.38750000000002 59.375 136.8125 60.3125Q137.2375 61.25 138.07500000000002 61.775Q138.91250000000002 62.3 140.1125 62.3Z M155.0375 65.0 157.5875 51.825H161.7875L164.7125 65.0H161.7875L158.7875 51.9H160.4125L157.7125 65.0ZM154.0625 65.0 154.0375 61.9H156.7875L156.8125 65.0ZM152.4625 65.0 148.7875 51.375H152.4125L155.8875 65.0ZM162.7375 65.0 162.7625 61.9H165.5125L165.4875 65.0ZM163.8375 65.0 166.9375 51.375H170.3375L167.0625 65.0Z M172.9375 65.0V51.375H175.8875V57.225H175.6625Q175.6625 55.125 176.2 53.7375Q176.73749999999998 52.35 177.83749999999998 51.6375Q178.9375 50.925 180.5375 50.925H180.6875Q183.11249999999998 50.925 184.375 52.5Q185.6375 54.075 185.6375 57.2V65.0H181.8875V56.925Q181.8875 55.75 181.2 55.025Q180.5125 54.3 179.3375 54.3Q178.1375 54.3 177.4125 55.05Q176.6875 55.8 176.6875 57.025V65.0Z M189.36249999999998 65.0V46.75H193.11249999999998V65.0ZM187.7125 49.525V46.75H193.11249999999998V49.525Z M203.5375 65.475Q201.73749999999998 65.475 200.35 64.9125Q198.9625 64.35 198.0 63.3625Q197.0375 62.375 196.55 61.125Q196.0625 59.875 196.0625 58.475V57.95Q196.0625 56.525 196.575 55.25Q197.0875 53.975 198.0625 53.0Q199.0375 52.025 200.425 51.45Q201.8125 50.875 203.5375 50.875Q205.2875 50.875 206.6625 51.45Q208.0375 52.025 209.0125 53.0Q209.98749999999998 53.975 210.5 55.25Q211.0125 56.525 211.0125 57.95V58.475Q211.0125 59.875 210.52499999999998 61.125Q210.0375 62.375 209.075 63.3625Q208.11249999999998 64.35 206.725 64.9125Q205.3375 65.475 203.5375 65.475ZM203.5375 62.3Q204.7625 62.3 205.58749999999998 61.775Q206.4125 61.25 206.83749999999998 60.3125Q207.2625 59.375 207.2625 58.225Q207.2625 57.0 206.825 56.075Q206.3875 55.15 205.55 54.6125Q204.7125 54.075 203.5375 54.075Q202.36249999999998 54.075 201.52499999999998 54.6125Q200.6875 55.15 200.25 56.075Q199.8125 57.0 199.8125 58.225Q199.8125 59.375 200.2375 60.3125Q200.6625 61.25 201.5 61.775Q202.3375 62.3 203.5375 62.3Z M222.1875 65.0V60.975H221.5625V56.525Q221.5625 55.425 221.02499999999998 54.875Q220.48749999999998 54.325 219.3375 54.325Q218.7625 54.325 217.875 54.35Q216.98749999999998 54.375 216.0625 54.4125Q215.1375 54.45 214.3875 54.5V51.325Q214.98749999999998 51.275 215.725 51.2375Q216.4625 51.2 217.2625 51.175Q218.0625 51.15 218.7625 51.15Q220.86249999999998 51.15 222.27499999999998 51.724999999999994Q223.6875 52.3 224.4125 53.5Q225.1375 54.7 225.1375 56.6V65.0ZM217.8125 65.35Q216.3375 65.35 215.225 64.82499999999999Q214.11249999999998 64.3 213.5 63.325Q212.8875 62.35 212.8875 60.975Q212.8875 59.475 213.6375 58.5125Q214.3875 57.55 215.75 57.0875Q217.11249999999998 56.625 218.9375 56.625H221.9625V58.775H218.8875Q217.7875 58.775 217.175 59.325Q216.5625 59.875 216.5625 60.775Q216.5625 61.65 217.175 62.1875Q217.7875 62.725 218.8875 62.725Q219.5875 62.725 220.175 62.475Q220.7625 62.225 221.1375 61.625Q221.5125 61.025 221.5625 59.95L222.4625 60.925Q222.3375 62.35 221.775 63.337500000000006Q221.2125 64.325 220.225 64.8375Q219.23749999999998 65.35 217.8125 65.35Z M234.3375 65.45Q232.9125 65.45 231.71249999999998 64.92500000000001Q230.5125 64.4 229.6Line truncated

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 9.3 KiB

+1 -1
View File
@@ -1,2 +1,2 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 427 112" width="427" height="112"><defs><linearGradient id="b" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#FFD27A"/><stop offset="1" stop-color="#F07A28"/></linearGradient></defs>
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M120.04999999999998 65.1V61.525H123.62499999999999Q124.975 61.525 126.04999999999998 61.1125Q127.12499999999999 60.7 127.875 59.95Q128.625 59.2 129.02499999999998 58.150000000000006Q129.42499999999998 57.1 129.42499999999998 55.825Q129.42499999999998 54.5 129.02499999999998 53.4625Q128.625 52.425 127.875 51.6875Q127.12499999999999 50.95 126.04999999999998 50.5625Q124.975 50.175 123.62499999999999 50.175H120.04999999999998V46.625H123.42499999999998Q125.89999999999999 46.625 127.73749999999998 47.35Q129.575 48.075 130.8125 49.325Q132.04999999999998 50.575 132.67499999999998 52.1875Q133.29999999999998 53.8 133.29999999999998 55.55V56.1Q133.29999999999998 57.75 132.67499999999998 59.3625Q132.04999999999998 60.975 130.8125 62.2625Q129.575 63.55 127.73749999999998 64.32499999999999Q125.89999999999999 65.1 123.42499999999998 65.1ZM116.725 65.1V46.625H120.54999999999998V65.1Z M142.64999999999998 65.475Q140.84999999999997 65.475 139.46249999999998 64.9125Q138.075 64.35 137.11249999999998 63.3625Q136.14999999999998 62.375 135.66249999999997 61.125Q135.17499999999998 59.875 135.17499999999998 58.475V57.95Q135.17499999999998 56.525 135.6875 55.25Q136.2 53.975 137.17499999999998 53.0Q138.14999999999998 52.025 139.53749999999997 51.45Q140.92499999999998 50.875 142.64999999999998 50.875Q144.39999999999998 50.875 145.77499999999998 51.45Q147.14999999999998 52.025 148.12499999999997 53.0Q149.09999999999997 53.975 149.61249999999995 55.25Q150.12499999999997 56.525 150.12499999999997 57.95V58.475Q150.12499999999997 59.875 149.6375 61.125Q149.14999999999998 62.375 148.18749999999997 63.3625Q147.22499999999997 64.35 145.83749999999998 64.9125Q144.45 65.475 142.64999999999998 65.475ZM142.64999999999998 62.3Q143.87499999999997 62.3 144.7 61.775Q145.52499999999998 61.25 145.95 60.3125Q146.37499999999997 59.375 146.37499999999997 58.225Q146.37499999999997 57.0 145.93749999999997 56.075Q145.49999999999997 55.15 144.66249999999997 54.6125Q143.825 54.075 142.64999999999998 54.075Q141.47499999999997 54.075 140.6375 54.6125Q139.79999999999998 55.15 139.36249999999998 56.075Q138.92499999999998 57.0 138.92499999999998 58.225Q138.92499999999998 59.375 139.34999999999997 60.3125Q139.77499999999998 61.25 140.61249999999998 61.775Q141.45 62.3 142.64999999999998 62.3Z M157.575 65.0 160.125 51.825H164.325L167.25 65.0H164.325L161.325 51.9H162.95L160.25 65.0ZM156.6 65.0 156.575 61.9H159.325L159.35 65.0ZM155.0 65.0 151.325 51.375H154.95L158.42499999999998 65.0ZM165.275 65.0 165.29999999999998 61.9H168.04999999999998L168.025 65.0ZM166.375 65.0 169.475 51.375H172.875L169.6 65.0Z M175.475 65.0V51.375H178.42499999999998V57.225H178.2Q178.2 55.125 178.73749999999998 53.7375Q179.27499999999998 52.35 180.375 51.6375Q181.475 50.925 183.075 50.925H183.225Q185.64999999999998 50.925 186.91249999999997 52.5Q188.17499999999998 54.075 188.17499999999998 57.2V65.0H184.42499999999998V56.925Q184.42499999999998 55.75 183.73749999999998 55.025Q183.04999999999998 54.3 181.875 54.3Q180.67499999999998 54.3 179.95 55.05Q179.225 55.8 179.225 57.025V65.0Z M191.89999999999998 65.0V46.75H195.64999999999998V65.0ZM190.25 49.525V46.75H195.64999999999998V49.525Z M206.075 65.475Q204.27499999999998 65.475 202.8875 64.9125Q201.5 64.35 200.5375 63.3625Q199.575 62.375 199.08749999999998 61.125Q198.6 59.875 198.6 58.475V57.95Q198.6 56.525 199.1125 55.25Q199.625 53.975 200.6 53.0Q201.575 52.025 202.96249999999998 51.45Q204.35 50.875 206.075 50.875Q207.825 50.875 209.2 51.45Q210.575 52.025 211.54999999999998 53.0Q212.52499999999998 53.975 213.03749999999997 55.25Q213.54999999999998 56.525 213.54999999999998 57.95V58.475Q213.54999999999998 59.875 213.0625 61.125Q212.575 62.375 211.61249999999998 63.3625Q210.64999999999998 64.35 209.2625 64.9125Q207.875 65.475 206.075 65.475ZM206.075 62.3Q207.29999999999998 62.3 208.125 61.775Q208.95 61.25 209.375 60.3125Q209.79999999999998 59.375 209.79999999999998 58.225Q209.79999999999998 57.0 209.36249999999998 56.075Q208.92499999999998 55.15 208.08749999999998 54.6125Q207.25 54.075 206.075 54.075Q204.89999999999998 54.075 204.0625 54.6125Q203.225 55.15 202.7875 56.075Q202.35 57.0 202.35 58.225Q202.35 59.375 202.77499999999998 60.3125Q203.2 61.25 204.0375 61.775Q204.875 62.3 206.075 62.3Z M224.725 65.0V60.975H224.1V56.525Q224.1 55.425 223.5625 54.875Q223.02499999999998 54.325 221.875 54.325Q221.29999999999998 54.325 220.41249999999997 54.35Q219.52499999999998 54.375 218.59999999999997 54.4125Q217.67499999999998 54.45 216.92499999999998 54.5V51.325Q217.52499999999998 51.275 218.2625 51.2375Q219.0 51.2 219.8 51.175Q220.6 51.15 221.29999999999998 51.15Q223.39999999999998 51.15 224.8125 51.724999999999994Q226.225 52.3 226.95 53.5Q227.67499999999998 54.7 227.67499999999998 56.6V65.0ZM220.35 65.35Q218.875 65.35 217.7625 64.82499999999999Q216.64999999999998 64.3 216.03749999999997 63.325Q215.42499999999998 62.35 215.42499999999998 60.975Q215.42499999999998 59.475 216.17499999999998Line truncated
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M117.51249999999999 65.1V61.525H121.08749999999999Q122.4375 61.525 123.51249999999999 61.1125Q124.58749999999999 60.7 125.33749999999999 59.95Q126.08749999999999 59.2 126.48749999999998 58.150000000000006Q126.88749999999999 57.1 126.88749999999999 55.825Q126.88749999999999 54.5 126.48749999999998 53.4625Q126.08749999999999 52.425 125.33749999999999 51.6875Q124.58749999999999 50.95 123.51249999999999 50.5625Q122.4375 50.175 121.08749999999999 50.175H117.51249999999999V46.625H120.88749999999999Q123.3625 46.625 125.19999999999999 47.35Q127.0375 48.075 128.27499999999998 49.325Q129.5125 50.575 130.1375 52.1875Q130.7625 53.8 130.7625 55.55V56.1Q130.7625 57.75 130.1375 59.3625Q129.5125 60.975 128.27499999999998 62.2625Q127.0375 63.55 125.19999999999999 64.32499999999999Q123.3625 65.1 120.88749999999999 65.1ZM114.1875 65.1V46.625H118.01249999999999V65.1Z M140.1125 65.475Q138.3125 65.475 136.925 64.9125Q135.53750000000002 64.35 134.57500000000002 63.3625Q133.6125 62.375 133.125 61.125Q132.63750000000002 59.875 132.63750000000002 58.475V57.95Q132.63750000000002 56.525 133.15000000000003 55.25Q133.66250000000002 53.975 134.63750000000002 53.0Q135.6125 52.025 137.0 51.45Q138.38750000000002 50.875 140.1125 50.875Q141.8625 50.875 143.2375 51.45Q144.6125 52.025 145.5875 53.0Q146.5625 53.975 147.075 55.25Q147.5875 56.525 147.5875 57.95V58.475Q147.5875 59.875 147.10000000000002 61.125Q146.6125 62.375 145.65 63.3625Q144.6875 64.35 143.3 64.9125Q141.91250000000002 65.475 140.1125 65.475ZM140.1125 62.3Q141.3375 62.3 142.16250000000002 61.775Q142.9875 61.25 143.41250000000002 60.3125Q143.8375 59.375 143.8375 58.225Q143.8375 57.0 143.4 56.075Q142.9625 55.15 142.125 54.6125Q141.28750000000002 54.075 140.1125 54.075Q138.9375 54.075 138.10000000000002 54.6125Q137.26250000000002 55.15 136.82500000000002 56.075Q136.38750000000002 57.0 136.38750000000002 58.225Q136.38750000000002 59.375 136.8125 60.3125Q137.2375 61.25 138.07500000000002 61.775Q138.91250000000002 62.3 140.1125 62.3Z M155.0375 65.0 157.5875 51.825H161.7875L164.7125 65.0H161.7875L158.7875 51.9H160.4125L157.7125 65.0ZM154.0625 65.0 154.0375 61.9H156.7875L156.8125 65.0ZM152.4625 65.0 148.7875 51.375H152.4125L155.8875 65.0ZM162.7375 65.0 162.7625 61.9H165.5125L165.4875 65.0ZM163.8375 65.0 166.9375 51.375H170.3375L167.0625 65.0Z M172.9375 65.0V51.375H175.8875V57.225H175.6625Q175.6625 55.125 176.2 53.7375Q176.73749999999998 52.35 177.83749999999998 51.6375Q178.9375 50.925 180.5375 50.925H180.6875Q183.11249999999998 50.925 184.375 52.5Q185.6375 54.075 185.6375 57.2V65.0H181.8875V56.925Q181.8875 55.75 181.2 55.025Q180.5125 54.3 179.3375 54.3Q178.1375 54.3 177.4125 55.05Q176.6875 55.8 176.6875 57.025V65.0Z M189.36249999999998 65.0V46.75H193.11249999999998V65.0ZM187.7125 49.525V46.75H193.11249999999998V49.525Z M203.5375 65.475Q201.73749999999998 65.475 200.35 64.9125Q198.9625 64.35 198.0 63.3625Q197.0375 62.375 196.55 61.125Q196.0625 59.875 196.0625 58.475V57.95Q196.0625 56.525 196.575 55.25Q197.0875 53.975 198.0625 53.0Q199.0375 52.025 200.425 51.45Q201.8125 50.875 203.5375 50.875Q205.2875 50.875 206.6625 51.45Q208.0375 52.025 209.0125 53.0Q209.98749999999998 53.975 210.5 55.25Q211.0125 56.525 211.0125 57.95V58.475Q211.0125 59.875 210.52499999999998 61.125Q210.0375 62.375 209.075 63.3625Q208.11249999999998 64.35 206.725 64.9125Q205.3375 65.475 203.5375 65.475ZM203.5375 62.3Q204.7625 62.3 205.58749999999998 61.775Q206.4125 61.25 206.83749999999998 60.3125Q207.2625 59.375 207.2625 58.225Q207.2625 57.0 206.825 56.075Q206.3875 55.15 205.55 54.6125Q204.7125 54.075 203.5375 54.075Q202.36249999999998 54.075 201.52499999999998 54.6125Q200.6875 55.15 200.25 56.075Q199.8125 57.0 199.8125 58.225Q199.8125 59.375 200.2375 60.3125Q200.6625 61.25 201.5 61.775Q202.3375 62.3 203.5375 62.3Z M222.1875 65.0V60.975H221.5625V56.525Q221.5625 55.425 221.02499999999998 54.875Q220.48749999999998 54.325 219.3375 54.325Q218.7625 54.325 217.875 54.35Q216.98749999999998 54.375 216.0625 54.4125Q215.1375 54.45 214.3875 54.5V51.325Q214.98749999999998 51.275 215.725 51.2375Q216.4625 51.2 217.2625 51.175Q218.0625 51.15 218.7625 51.15Q220.86249999999998 51.15 222.27499999999998 51.724999999999994Q223.6875 52.3 224.4125 53.5Q225.1375 54.7 225.1375 56.6V65.0ZM217.8125 65.35Q216.3375 65.35 215.225 64.82499999999999Q214.11249999999998 64.3 213.5 63.325Q212.8875 62.35 212.8875 60.975Q212.8875 59.475 213.6375 58.5125Q214.3875 57.55 215.75 57.0875Q217.11249999999998 56.625 218.9375 56.625H221.9625V58.775H218.8875Q217.7875 58.775 217.175 59.325Q216.5625 59.875 216.5625 60.775Q216.5625 61.65 217.175 62.1875Q217.7875 62.725 218.8875 62.725Q219.5875 62.725 220.175 62.475Q220.7625 62.225 221.1375 61.625Q221.5125 61.025 221.5625 59.95L222.4625 60.925Q222.3375 62.35 221.775 63.337500000000006Q221.2125 64.325 220.225 64.8375Q219.23749999999998 65.35 217.8125 65.35Z M234.3375 65.45Q232.9125 65.45 231.71249999999998 64.92500000000001Q230.5125 64.4 229.6Line truncated

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 9.3 KiB

Executable → Regular
+1 -1
View File
@@ -24,4 +24,4 @@
</g></g></g></g>
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1s" dur=".8s" fill="freeze"/>
<animateTransform attributeName="transform" type="translate" values="0 26;0 0" keyTimes="0;1" calcMode="spline" keySplines="0.16 1 0.3 1" dur=".9s" begin="1s" fill="freeze"/><path d="M380.56 482.368H398.96Q399.42 485.496 401.72 487.75Q404.02 490.004 407.92999999999995 491.246Q411.84 492.488 416.99199999999996 492.488Q424.352 492.488 428.58399999999995 490.51Q432.816 488.532 432.816 484.76Q432.816 482.0 430.424 480.39Q428.032 478.78 421.224 478.136L408.068 476.756Q394.084 475.468 387.78200000000004 470.36199999999997Q381.48 465.256 381.48 456.516Q381.48 449.432 385.574 444.51Q389.668 439.588 397.166 437.058Q404.664 434.528 414.692 434.528Q424.536 434.528 432.172 437.334Q439.808 440.14 444.316 445.246Q448.82399999999996 450.352 449.284 457.16H430.884Q430.51599999999996 454.492 428.49199999999996 452.606Q426.46799999999996 450.72 422.88 449.616Q419.292 448.512 414.324 448.512Q407.608 448.512 403.652 450.398Q399.69599999999997 452.284 399.69599999999997 455.78Q399.69599999999997 458.356 402.042 459.91999999999996Q404.388 461.484 410.552 462.128L424.44399999999996 463.6Q434.19599999999997 464.52 440.038 466.82Q445.88 469.12 448.456 472.98400000000004Q451.032 476.848 451.032 482.736Q451.032 489.912 446.754 495.248Q442.476 500.584 434.748 503.528Q427.02 506.472 416.716 506.472Q406.13599999999997 506.472 398.086 503.48199999999997Q390.036 500.492 385.43600000000004 495.01800000000003Q380.836 489.544 380.56 482.368Z M452.228 465.716V457.896L462.9 453.848L470.628 438.484H480.748V452.468H503.104V465.716H480.748V482.276Q480.748 488.072 483.094 490.418Q485.44 492.764 491.604 492.764Q495.46799999999996 492.764 498.45799999999997 492.074Q501.448 491.384 504.024 490.188V503.62Q501.264 504.724 496.802 505.59799999999996Q492.34 506.472 487.556 506.472Q479.0 506.472 473.572 503.804Q468.144 501.136 465.522 496.214Q462.9 491.292 462.9 484.76V465.716Z M556.28 505.0 553.888 486.048 556.464 478.78 553.888 471.604 556.28 452.468H574.6800000000001L571.46 478.688L574.6800000000001 505.0ZM560.5120000000001 478.78Q559.224 487.06 555.36 493.31600000000003Q551.496 499.572 545.608 503.022Q539.72 506.472 532.36 506.472Q524.6320000000001 506.472 518.79 503.022Q512.948 499.572 509.63599999999997 493.27Q506.324 486.968 506.324 478.78Q506.324 470.408 509.63599999999997 464.198Q512.948 457.988 518.79 454.49199999999996Q524.6320000000001 450.996 532.36 450.996Q539.72 450.996 545.608 454.446Q551.496 457.896 555.406 464.106Q559.316 470.31600000000003 560.5120000000001 478.78ZM524.356 478.78Q524.356 482.92 526.012 486.048Q527.668 489.176 530.704 491.01599999999996Q533.74 492.856 537.604 492.856Q541.5600000000001 492.856 545.1020000000001 491.01599999999996Q548.644 489.176 551.358 486.048Q554.072 482.92 555.452 478.78Q554.072 474.64 551.358 471.466Q548.644 468.29200000000003 545.1020000000001 466.49800000000005Q541.5600000000001 464.704 537.604 464.704Q533.74 464.704 530.704 466.49800000000005Q527.668 468.29200000000003 526.012 471.466Q524.356 474.64 524.356 478.78Z M579.7399999999999 452.468H597.588L600.992 473.168V505.0H583.1439999999999V470.5ZM619.208 450.996Q626.3839999999999 450.996 631.444 454.032Q636.5039999999999 457.068 639.1719999999999 462.58799999999997Q641.8399999999999 468.108 641.8399999999999 475.652V505.0H623.992V478.32Q623.992 472.064 621.232 468.798Q618.4719999999999 465.532 613.136 465.532Q609.3639999999999 465.532 606.6039999999999 467.28Q603.8439999999999 469.028 602.4179999999999 472.202Q600.992 475.376 600.992 479.7L595.3799999999999 476.756Q596.3919999999999 468.384 599.75 462.68Q603.108 456.976 608.1679999999999 453.986Q613.228 450.996 619.208 450.996ZM659.9639999999999 450.996Q667.1399999999999 450.996 672.2459999999999 454.032Q677.3519999999999 457.068 680.0199999999999 462.58799999999997Q682.6879999999999 468.108 682.6879999999999 475.652V505.0H664.8399999999999V478.32Q664.8399999999999 472.064 662.0799999999999 468.798Q659.3199999999999 465.532 653.9839999999999 465.532Q650.2119999999999 465.532 647.4519999999999 467.28Q644.6919999999999 469.028 643.2659999999998 472.202Q641.8399999999999 475.376 641.8399999999999 479.7L636.228 476.756Q637.2399999999999 468.384 640.598 462.68Q643.9559999999999 456.976 648.9699999999999 453.986Q653.9839999999999 450.996 659.9639999999999 450.996Z M690.784 434.15999999999997H708.632V468.2L706.24 472.8V485.496L708.632 490.004V505.0H690.784ZM702.744 478.78Q704.0319999999999 470.31600000000003 707.896 464.106Q711.76 457.896 717.6479999999999 454.446Q723.536 450.996 730.896 450.996Q738.624 450.996 744.466 454.49199999999996Q750.308 457.988 753.62 464.198Q756.932 470.408 756.932 478.78Q756.932 486.968 753.62 493.27Q750.308 499.572 744.466 503.022Q738.624 506.472 730.896 506.472Q723.536 506.472 717.6479999999999 503.022Q711.76 499.572 707.942 493.31600000000003Q704.124 487.06 702.744 478.78ZM738.9 478.78Q738.9 474.64 737.2439999999999 471.466Q735.588 468.29200000000003 732.5519999999999 466.49800000000005Q729.516 464.704 725.6519999999999 464.704Q721.696 464.704 718.154 466.49800000000005Q714Line truncated
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated

Before

Width:  |  Height:  |  Size: 625 KiB

After

Width:  |  Height:  |  Size: 627 KiB

Executable → Regular
+1 -1
View File
@@ -24,4 +24,4 @@
</g></g></g></g>
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1s" dur=".8s" fill="freeze"/>
<animateTransform attributeName="transform" type="translate" values="0 26;0 0" keyTimes="0;1" calcMode="spline" keySplines="0.16 1 0.3 1" dur=".9s" begin="1s" fill="freeze"/><path d="M380.56 482.368H398.96Q399.42 485.496 401.72 487.75Q404.02 490.004 407.92999999999995 491.246Q411.84 492.488 416.99199999999996 492.488Q424.352 492.488 428.58399999999995 490.51Q432.816 488.532 432.816 484.76Q432.816 482.0 430.424 480.39Q428.032 478.78 421.224 478.136L408.068 476.756Q394.084 475.468 387.78200000000004 470.36199999999997Q381.48 465.256 381.48 456.516Q381.48 449.432 385.574 444.51Q389.668 439.588 397.166 437.058Q404.664 434.528 414.692 434.528Q424.536 434.528 432.172 437.334Q439.808 440.14 444.316 445.246Q448.82399999999996 450.352 449.284 457.16H430.884Q430.51599999999996 454.492 428.49199999999996 452.606Q426.46799999999996 450.72 422.88 449.616Q419.292 448.512 414.324 448.512Q407.608 448.512 403.652 450.398Q399.69599999999997 452.284 399.69599999999997 455.78Q399.69599999999997 458.356 402.042 459.91999999999996Q404.388 461.484 410.552 462.128L424.44399999999996 463.6Q434.19599999999997 464.52 440.038 466.82Q445.88 469.12 448.456 472.98400000000004Q451.032 476.848 451.032 482.736Q451.032 489.912 446.754 495.248Q442.476 500.584 434.748 503.528Q427.02 506.472 416.716 506.472Q406.13599999999997 506.472 398.086 503.48199999999997Q390.036 500.492 385.43600000000004 495.01800000000003Q380.836 489.544 380.56 482.368Z M452.228 465.716V457.896L462.9 453.848L470.628 438.484H480.748V452.468H503.104V465.716H480.748V482.276Q480.748 488.072 483.094 490.418Q485.44 492.764 491.604 492.764Q495.46799999999996 492.764 498.45799999999997 492.074Q501.448 491.384 504.024 490.188V503.62Q501.264 504.724 496.802 505.59799999999996Q492.34 506.472 487.556 506.472Q479.0 506.472 473.572 503.804Q468.144 501.136 465.522 496.214Q462.9 491.292 462.9 484.76V465.716Z M556.28 505.0 553.888 486.048 556.464 478.78 553.888 471.604 556.28 452.468H574.6800000000001L571.46 478.688L574.6800000000001 505.0ZM560.5120000000001 478.78Q559.224 487.06 555.36 493.31600000000003Q551.496 499.572 545.608 503.022Q539.72 506.472 532.36 506.472Q524.6320000000001 506.472 518.79 503.022Q512.948 499.572 509.63599999999997 493.27Q506.324 486.968 506.324 478.78Q506.324 470.408 509.63599999999997 464.198Q512.948 457.988 518.79 454.49199999999996Q524.6320000000001 450.996 532.36 450.996Q539.72 450.996 545.608 454.446Q551.496 457.896 555.406 464.106Q559.316 470.31600000000003 560.5120000000001 478.78ZM524.356 478.78Q524.356 482.92 526.012 486.048Q527.668 489.176 530.704 491.01599999999996Q533.74 492.856 537.604 492.856Q541.5600000000001 492.856 545.1020000000001 491.01599999999996Q548.644 489.176 551.358 486.048Q554.072 482.92 555.452 478.78Q554.072 474.64 551.358 471.466Q548.644 468.29200000000003 545.1020000000001 466.49800000000005Q541.5600000000001 464.704 537.604 464.704Q533.74 464.704 530.704 466.49800000000005Q527.668 468.29200000000003 526.012 471.466Q524.356 474.64 524.356 478.78Z M579.7399999999999 452.468H597.588L600.992 473.168V505.0H583.1439999999999V470.5ZM619.208 450.996Q626.3839999999999 450.996 631.444 454.032Q636.5039999999999 457.068 639.1719999999999 462.58799999999997Q641.8399999999999 468.108 641.8399999999999 475.652V505.0H623.992V478.32Q623.992 472.064 621.232 468.798Q618.4719999999999 465.532 613.136 465.532Q609.3639999999999 465.532 606.6039999999999 467.28Q603.8439999999999 469.028 602.4179999999999 472.202Q600.992 475.376 600.992 479.7L595.3799999999999 476.756Q596.3919999999999 468.384 599.75 462.68Q603.108 456.976 608.1679999999999 453.986Q613.228 450.996 619.208 450.996ZM659.9639999999999 450.996Q667.1399999999999 450.996 672.2459999999999 454.032Q677.3519999999999 457.068 680.0199999999999 462.58799999999997Q682.6879999999999 468.108 682.6879999999999 475.652V505.0H664.8399999999999V478.32Q664.8399999999999 472.064 662.0799999999999 468.798Q659.3199999999999 465.532 653.9839999999999 465.532Q650.2119999999999 465.532 647.4519999999999 467.28Q644.6919999999999 469.028 643.2659999999998 472.202Q641.8399999999999 475.376 641.8399999999999 479.7L636.228 476.756Q637.2399999999999 468.384 640.598 462.68Q643.9559999999999 456.976 648.9699999999999 453.986Q653.9839999999999 450.996 659.9639999999999 450.996Z M690.784 434.15999999999997H708.632V468.2L706.24 472.8V485.496L708.632 490.004V505.0H690.784ZM702.744 478.78Q704.0319999999999 470.31600000000003 707.896 464.106Q711.76 457.896 717.6479999999999 454.446Q723.536 450.996 730.896 450.996Q738.624 450.996 744.466 454.49199999999996Q750.308 457.988 753.62 464.198Q756.932 470.408 756.932 478.78Q756.932 486.968 753.62 493.27Q750.308 499.572 744.466 503.022Q738.624 506.472 730.896 506.472Q723.536 506.472 717.6479999999999 503.022Q711.76 499.572 707.942 493.31600000000003Q704.124 487.06 702.744 478.78ZM738.9 478.78Q738.9 474.64 737.2439999999999 471.466Q735.588 468.29200000000003 732.5519999999999 466.49800000000005Q729.516 464.704 725.6519999999999 464.704Q721.696 464.704 718.154 466.49800000000005Q714Line truncated
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated

Before

Width:  |  Height:  |  Size: 625 KiB

After

Width:  |  Height:  |  Size: 627 KiB

-20
View File
@@ -1,20 +0,0 @@
[package]
name = "stambha-engine"
version = "0.1.0"
edition.workspace = true
license = "GPL-3.0-or-later"
description = "Hosted Stambha engine for VM launchers"
rust-version.workspace = true
publish = false
[dependencies]
anyhow.workspace = true
clap.workspace = true
serde = { workspace = true, features = ["std"] }
serde_json.workspace = true
stela-compiler.workspace = true
stela-engine.workspace = true
tempfile.workspace = true
[lints]
workspace = true
-131
View File
@@ -1,131 +0,0 @@
use anyhow::{Context, Result, ensure};
use clap::{Parser, Subcommand};
use serde::Serialize;
use std::io::{self, Write};
use stela_compiler::{GuestAddress, GuestState, TargetCpu, block::BlockProfile};
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
mod qemu;
const RUNTIME_KIND: &str = "stambha-hosted";
const RUNTIME_API: &str = "0.1.0";
#[derive(Parser)]
#[command(version, about)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Report the runtime protocol and available capabilities as JSON.
Info,
/// Translate and execute the built-in ARM64 program.
SelfTest,
/// Prepare a launch command for the Stambha UEFI engine under QEMU.
BootPlan(Box<qemu::BootOptions>),
}
#[derive(Serialize)]
struct RuntimeInfo {
runtime_kind: &'static str,
runtime_api: &'static str,
engine_version: &'static str,
host_os: &'static str,
host_arch: &'static str,
capabilities: Capabilities,
}
#[derive(Serialize)]
struct Capabilities {
native_arm64_self_test: bool,
qemu_uefi_boot_plan: bool,
macos_boot: bool,
}
#[derive(Serialize)]
struct SelfTestReport {
runtime_api: &'static str,
guest_arch: &'static str,
blocks_executed: usize,
blocks_compiled: usize,
result: u64,
}
fn main() -> Result<()> {
match Cli::parse().command {
Command::Info => write_json(&RuntimeInfo {
runtime_kind: RUNTIME_KIND,
runtime_api: RUNTIME_API,
engine_version: env!("CARGO_PKG_VERSION"),
host_os: std::env::consts::OS,
host_arch: std::env::consts::ARCH,
capabilities: Capabilities {
native_arm64_self_test: stela_engine::execution::platform::ensure_supported()
.is_ok(),
qemu_uefi_boot_plan: true,
macos_boot: false,
},
}),
Command::SelfTest => write_json(&self_test()?),
Command::BootPlan(options) => write_json(&options.prepare()?),
}
}
fn write_json(value: &impl Serialize) -> Result<()> {
let mut stdout = io::stdout().lock();
serde_json::to_writer(&mut stdout, value)?;
writeln!(stdout)?;
Ok(())
}
fn self_test() -> Result<SelfTestReport> {
stela_engine::execution::platform::ensure_supported()?;
const ENTRY: GuestAddress = GuestAddress(0x1000);
const RETURN: GuestAddress = GuestAddress(0x2000);
const PROGRAM: [u32; 5] = [
0xd2800500, // MOV X0, #40
0x14000002, // B past the next instruction
0xd2800c60, // MOV X0, #99 (skipped)
0x91000800, // ADD X0, X0, #2
0xd65f03c0, // RET
];
let cache = tempfile::tempdir().context("create temporary self-test cache")?;
let mut engine = BlockRuntime::new_for_target(
1,
cache.path().to_path_buf(),
BlockProfile::ORDINARY,
TargetCpu::Baseline,
);
engine.register_code(
ENTRY,
PROGRAM.into_iter().flat_map(u32::to_le_bytes).collect(),
)?;
let mut thread = ThreadState {
pc: ENTRY,
registers: GuestState::default(),
};
thread.registers.x[30] = RETURN.0;
// SAFETY: the built-in instructions have no memory accesses and the only
// dynamic branch goes to the explicit stop address.
let outcome = unsafe { engine.run(&mut thread, Some(RETURN), 8)? };
ensure!(
outcome.reason == StopReason::StopAddress && thread.pc == RETURN,
"ARM64 self-test stopped at {:#x} with {:?}",
thread.pc.0,
outcome.reason
);
ensure!(
thread.registers.x[0] == 42 && outcome.blocks_executed == 2 && outcome.compiled_blocks == 2,
"unexpected ARM64 translation result or block counts"
);
Ok(SelfTestReport {
runtime_api: RUNTIME_API,
guest_arch: "arm64",
blocks_executed: outcome.blocks_executed,
blocks_compiled: outcome.compiled_blocks,
result: thread.registers.x[0],
})
}
-267
View File
@@ -1,267 +0,0 @@
use anyhow::{Context, Result, ensure};
use clap::Args;
use serde::Serialize;
use std::{
fs::{self, File},
io,
path::{Path, PathBuf},
};
use crate::RUNTIME_API;
#[derive(Args)]
pub(crate) struct BootOptions {
/// QEMU x86-64 executable.
#[arg(long)]
qemu: PathBuf,
/// Read-only EDK2 code image.
#[arg(long)]
firmware_code: PathBuf,
/// EDK2 variables template, copied on first launch.
#[arg(long)]
firmware_vars: PathBuf,
/// Directory that holds persistent firmware variables and the serial log.
#[arg(long)]
vm_dir: PathBuf,
/// Directory containing EFI/BOOT/BOOTX64.EFI and EFI/stela/stela.cfg.
#[arg(
long,
conflicts_with = "usb_image",
required_unless_present = "usb_image"
)]
boot_volume: Option<PathBuf>,
/// Raw Stambha USB disk image. Writes go to a temporary overlay by default.
#[arg(long)]
usb_image: Option<PathBuf>,
/// USB serial used by the boot medium's Stambha configuration.
#[arg(long, default_value = "STELAUSBIMAGE", value_parser = usb_serial)]
usb_serial: String,
/// Persist changes to the USB image.
#[arg(long, requires = "usb_image")]
write_usb: bool,
/// Optional writable raw file attached as an NVMe disk with serial STELAANS.
#[arg(long)]
disk: Option<PathBuf>,
#[arg(long, default_value_t = 8192, value_parser = clap::value_parser!(u32).range(1024..))]
memory_mib: u32,
#[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=64))]
cpus: u8,
/// Open an SDL display with a virtual keyboard and tablet.
#[arg(long)]
display: bool,
}
#[derive(Serialize)]
pub(crate) struct BootPlan {
runtime_api: &'static str,
exe_path: PathBuf,
args: Vec<String>,
work_dir: PathBuf,
serial_log: PathBuf,
}
impl BootOptions {
pub(crate) fn prepare(self) -> Result<BootPlan> {
let qemu = file(&self.qemu)?;
let firmware_code = file(&self.firmware_code)?;
let firmware_vars = file(&self.firmware_vars)?;
let vm_dir = absolute(&self.vm_dir)?;
let serial_log = vm_dir.join("serial.log");
let vars = vm_dir.join("uefi-vars.fd");
let mut args: Vec<String> = [
"-accel",
"tcg,thread=multi",
"-cpu",
"max,vendor=GenuineIntel",
"-nodefaults",
"-no-reboot",
"-monitor",
"none",
"-nic",
"none",
"-device",
"isa-debug-exit,iobase=0xf4,iosize=4",
"-serial",
"chardev:uart",
]
.into_iter()
.map(String::from)
.collect();
let i8042 = if self.usb_image.is_some() {
"on"
} else {
"off"
};
option(
&mut args,
"-machine",
format!("q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042={i8042},vmport=off",),
);
option(&mut args, "-m", format!("{}M", self.memory_mib));
option(
&mut args,
"-smp",
format!("cpus={},sockets=1,cores={},threads=1", self.cpus, self.cpus),
);
option(
&mut args,
"-display",
if self.display { "sdl" } else { "none" },
);
if self.display {
for device in ["VGA", "virtio-keyboard-pci", "virtio-tablet-pci"] {
option(&mut args, "-device", device);
}
}
option(
&mut args,
"-chardev",
format!("file,id=uart,path={},append=on", qemu_path(&serial_log)?),
);
option(
&mut args,
"-drive",
format!(
"if=pflash,format=raw,readonly=on,file={}",
qemu_path(&firmware_code)?
),
);
option(
&mut args,
"-drive",
format!("if=pflash,format=raw,file={}", qemu_path(&vars)?),
);
match (self.boot_volume, self.usb_image) {
(Some(volume), None) => {
let volume = absolute(&volume)?;
file(&volume.join("EFI/BOOT/BOOTX64.EFI"))?;
file(&volume.join("EFI/stela/stela.cfg"))?;
option(
&mut args,
"-drive",
format!(
"if=none,id=volume,format=raw,readonly=on,file=fat:{}",
qemu_path(&volume)?
),
);
option(&mut args, "-device", "virtio-blk-pci,drive=volume");
}
(None, Some(image)) => {
let image = file(&image)?;
let snapshot = if self.write_usb { "off" } else { "on" };
option(
&mut args,
"-drive",
format!(
"if=none,id=volume,format=raw,snapshot={snapshot},file={}",
qemu_path(&image)?
),
);
option(&mut args, "-device", "qemu-xhci,id=host-usb,p2=8,p3=0");
option(
&mut args,
"-device",
format!(
"usb-storage,drive=volume,serial={},bus=host-usb.0,bootindex=0",
self.usb_serial
),
);
}
_ => anyhow::bail!("provide exactly one boot medium"),
}
if let Some(disk) = self.disk {
option(
&mut args,
"-drive",
format!(
"if=none,id=guest,format=raw,file={}",
qemu_path(&file(&disk)?)?
),
);
option(&mut args, "-device", "nvme,drive=guest,serial=STELAANS");
}
fs::create_dir_all(&vm_dir).with_context(|| format!("create {}", vm_dir.display()))?;
prepare_vars(&firmware_vars, &vars)?;
Ok(BootPlan {
runtime_api: RUNTIME_API,
exe_path: qemu,
args,
work_dir: vm_dir,
serial_log,
})
}
}
fn option(args: &mut Vec<String>, flag: &str, value: impl Into<String>) {
args.extend([flag.to_owned(), value.into()]);
}
fn usb_serial(value: &str) -> Result<String, &'static str> {
if !value.is_empty()
&& value.len() <= 32
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
{
Ok(value.to_owned())
} else {
Err("use 1 to 32 letters, digits, dashes or underscores for the USB serial")
}
}
fn absolute(path: &Path) -> Result<PathBuf> {
let path = std::path::absolute(path)?;
#[cfg(windows)]
{
use std::path::{Component, Prefix};
ensure!(
matches!(path.components().next(), Some(Component::Prefix(prefix))
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::UNC(_, _))),
"expected a filesystem path: {}",
path.display()
);
}
Ok(path)
}
fn file(path: &Path) -> Result<PathBuf> {
let path = absolute(path)?;
let metadata = fs::metadata(&path).with_context(|| format!("open {}", path.display()))?;
ensure!(
metadata.is_file() && metadata.len() != 0,
"expected a nonempty file: {}",
path.display()
);
Ok(path)
}
fn qemu_path(path: &Path) -> Result<String> {
Ok(path
.to_str()
.context("QEMU paths must be valid Unicode")?
.replace(',', ",,"))
}
fn prepare_vars(template: &Path, destination: &Path) -> Result<()> {
if !destination.try_exists()? {
let parent = destination.parent().context("missing NVRAM directory")?;
let mut staging = tempfile::NamedTempFile::new_in(parent)?;
io::copy(&mut File::open(template)?, &mut staging)?;
staging.as_file().sync_all()?;
match staging.persist_noclobber(destination) {
Ok(_) => {}
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error.error.into()),
}
}
let actual = fs::symlink_metadata(destination)?;
ensure!(
actual.is_file() && actual.len() == fs::metadata(template)?.len(),
"UEFI variable store differs in size from its template: {}",
destination.display()
);
Ok(())
}
-87
View File
@@ -1,87 +0,0 @@
use std::{ffi::OsStr, fs, process::Command};
fn json_output(argument: &str) -> serde_json::Value {
run_json([OsStr::new(argument)])
}
fn run_json(arguments: impl IntoIterator<Item = impl AsRef<OsStr>>) -> serde_json::Value {
let output = Command::new(env!("CARGO_BIN_EXE_stambha-engine"))
.args(arguments)
.output()
.expect("start hosted engine");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("one JSON reply")
}
#[test]
fn reports_host_capabilities() {
let info = json_output("info");
assert_eq!(info["runtime_kind"], "stambha-hosted");
assert_eq!(info["runtime_api"], "0.1.0");
assert_eq!(info["host_os"], std::env::consts::OS);
assert_eq!(info["host_arch"], std::env::consts::ARCH);
assert_eq!(info["capabilities"]["macos_boot"], false);
}
#[cfg(all(
target_arch = "x86_64",
any(windows, target_os = "linux", target_os = "macos")
))]
#[test]
fn executes_two_translated_arm64_blocks() {
assert_eq!(
json_output("info")["capabilities"]["native_arm64_self_test"],
true
);
let report = json_output("self-test");
assert_eq!(report["runtime_api"], "0.1.0");
assert_eq!(report["guest_arch"], "arm64");
assert_eq!(report["blocks_compiled"], 2);
assert_eq!(report["blocks_executed"], 2);
assert_eq!(report["result"], 42);
}
#[test]
fn boot_plan_uses_file_media_and_keeps_existing_firmware_variables() {
let temp = tempfile::tempdir().unwrap();
let qemu = temp.path().join("qemu");
let code = temp.path().join("code.fd");
let template = temp.path().join("vars.fd");
let image = temp.path().join("test, disk.img");
let vm = temp.path().join("test vm");
for path in [&qemu, &code, &template, &image] {
fs::write(path, b"template").unwrap();
}
let plan = || {
run_json([
OsStr::new("boot-plan"),
OsStr::new("--qemu"),
qemu.as_os_str(),
OsStr::new("--firmware-code"),
code.as_os_str(),
OsStr::new("--firmware-vars"),
template.as_os_str(),
OsStr::new("--vm-dir"),
vm.as_os_str(),
OsStr::new("--usb-image"),
image.as_os_str(),
])
};
let reply = plan();
let args = reply["args"].as_array().unwrap();
assert!(args.iter().any(|argument| {
argument.as_str().is_some_and(|argument| {
argument.contains("format=raw,snapshot=on,file=")
&& argument.ends_with("test,, disk.img")
})
}));
let variables = vm.join("uefi-vars.fd");
assert_eq!(fs::read(&variables).unwrap(), b"template");
fs::write(&variables, b"memorize").unwrap();
plan();
assert_eq!(fs::read(&variables).unwrap(), b"memorize");
}
+2
View File
@@ -43,6 +43,8 @@ stela-soc-data = { path = "../stela-soc-data" }
[dev-dependencies]
stela-driver-base = { path = "../stela-driver-base", features = ["test-support"] }
# The AMD port's refusal of a generation, for the GPU step's tests.
stela-driver-core = { path = "../stela-driver-core" }
serde_json.workspace = true
# An independent SHA-256 the tests check digests against.
sha2 = { version = "0.10", default-features = false }
+385
View File
@@ -0,0 +1,385 @@
//! ACPI hardware mode (`--acpi-hardware`): what a boot says about it, and
//! the two guards that keep a misbehaving firmware from costing the guest
//! its time once it runs.
//!
//! Hardware mode is ACPICA with its events on: the firmware switched into
//! ACPI mode (`SMI_CMD` ← `ACPI_ENABLE`, unless `SCI_EN` is already set),
//! the SCI routed to the boot processor, the fixed events and GPEs
//! dispatched, the embedded controller's `_REG` run and its queries
//! (`_Qxx`) taken, and the notifications those send delivered as deferred
//! work. The engine runs all of it on the work owner's continuation
//! (`stela-boot`'s `engine::aml`); this module holds only what a host test
//! can check: the lines, the FADT's ACPI-mode registers, the SCI's storm
//! guard ([`SciGovernor`]) and the EC's query budget and failure breaker
//! ([`EcGovernor`]).
//!
//! It is off by default until a laptop has proven it: the option is a
//! hand-written opt-in setup never writes, so it keeps the options
//! revision (`stela_loader::mount_interface::OPTIONS_REVISION`), and a
//! laptop's boot does not take it unasked ([`crate::laptop`]).
use alloc::{format, string::String};
/// What stays off while hardware mode does: the list the off lines name.
pub const WITHOUT: &str = "the embedded controller and what firmware reads through it (battery, \
AC adapter, lid), ACPI device notifications and USB-C port reports (UCSI)";
/// The line of a boot that leaves hardware mode off because the option is
/// not given.
pub fn off_line() -> String {
format!(
"UNSUPPORTED ACPI hardware mode: off unless --acpi-hardware is given, until it is proven \
on hardware (no ACPI interrupt, ACPI events or deferred firmware work); off because of \
it: {WITHOUT}\n"
)
}
/// The line of a boot whose `--acpi-hardware` cannot start, for `reason`.
pub fn refused_line(reason: &str) -> String {
format!(
"UNSUPPORTED ACPI hardware mode: --acpi-hardware is given, but {reason}, so it stays off; \
off because of it: {WITHOUT}\n"
)
}
/// The FADT's legacy fixed-hardware registers ACPI mode involves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Registers {
/// `SCI_INT` (offset 46): the SCI's legacy interrupt number.
pub sci_interrupt: u16,
/// `SMI_CMD` (offset 48), 0 where the platform has none.
pub smi_command: u32,
/// `ACPI_ENABLE` (offset 52): written to `SMI_CMD` to enter ACPI mode.
pub acpi_enable: u8,
/// `PM1a_CNT_BLK` (offset 64), whose bit 0 is `SCI_EN`.
pub pm1a_control: u32,
/// HW_REDUCED_ACPI (flags bit 20): no SCI and no legacy fixed hardware.
pub reduced: bool,
}
/// `SCI_EN`, bit 0 of PM1_CNT: the platform is in ACPI mode, and its
/// events raise the SCI rather than an SMI.
pub const SCI_EN: u16 = 1;
impl Registers {
/// The registers of a FADT, `None` when it is shorter than its flags.
pub fn read(fadt: &[u8]) -> Option<Self> {
let word = |at: usize| Some(u16::from_le_bytes(fadt.get(at..at + 2)?.try_into().ok()?));
let dword = |at: usize| Some(u32::from_le_bytes(fadt.get(at..at + 4)?.try_into().ok()?));
Some(Self {
sci_interrupt: word(46)?,
smi_command: dword(48)?,
acpi_enable: *fadt.get(52)?,
pm1a_control: dword(64)?,
reduced: dword(112)? & (1 << 20) != 0,
})
}
/// The PM1a control port, where the platform has one in I/O space.
pub fn control_port(&self) -> Option<u16> {
u16::try_from(self.pm1a_control)
.ok()
.filter(|&port| port != 0)
}
/// What entering ACPI mode takes, with PM1a_CNT reading `control`
/// (`None` where it was not read): none when `SCI_EN` is set, as
/// ACPICA's `acpi_enable` skips the write then.
pub fn entry(&self, control: Option<u16>) -> String {
match control {
Some(value) if value & SCI_EN != 0 => {
String::from("the firmware left SCI_EN set, so no SMI_CMD write enters ACPI mode")
}
_ if self.smi_command == 0 || self.acpi_enable == 0 => {
String::from("SCI_EN is clear and the FADT has no SMI_CMD or ACPI_ENABLE")
}
Some(_) => format!(
"SCI_EN is clear, so ACPI mode is entered with SMI_CMD {:#x} <- {:#x}",
self.smi_command, self.acpi_enable
),
None => format!(
"PM1a_CNT unread; ACPI mode is entered with SMI_CMD {:#x} <- {:#x} if SCI_EN is \
clear",
self.smi_command, self.acpi_enable
),
}
}
}
/// The line of a boot that starts hardware mode: its SCI's route and what
/// entering ACPI mode takes.
pub fn starting_line(registers: &Registers, route: &str, control: Option<u16>) -> String {
format!(
"ACPI hardware mode starting (--acpi-hardware): SCI_INT {} on {route}; {}\n",
registers.sci_interrupt,
registers.entry(control)
)
}
/// A window of the SCI's storm guard, in milliseconds.
pub const WINDOW_MS: u64 = 1_000;
/// SCIs in one window that count toward a storm. The SCI is taken at most
/// once per host service turn (about 250 a second), and a laptop's events
/// (battery, lid, hotkeys) come a few a second at most, so a level held
/// asserted shows as nearly every turn's.
pub const STORM_PER_WINDOW: u32 = 100;
/// Windows in a row past [`STORM_PER_WINDOW`] that make a storm.
pub const STORM_WINDOWS: u32 = 3;
/// How often ACPICA's SCI handler runs while the SCI stays masked.
pub const POLL_MS: u64 = 100;
/// How long the first storm keeps the SCI masked before it is tried again;
/// a second storm keeps it masked for the rest of the boot.
pub const RETRY_MS: u64 = 30_000;
/// What the SCI's owner does this turn ([`SciGovernor::turn`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Turn {
/// Run ACPICA's SCI handler.
pub dispatch: bool,
/// Unmask the SCI's line again once the handler ran.
pub rearm: bool,
/// A change to report, once.
pub change: Option<Change>,
}
/// A change of the SCI's mode, for its line ([`Change::line`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
/// The SCI came `per_window` times in the last window, and as often in
/// the windows before it: it stays masked and is polled, for
/// [`RETRY_MS`] or, `lasting`, for good.
Storm { per_window: u32, lasting: bool },
/// The masked SCI is tried again after [`RETRY_MS`].
Retry,
}
impl Change {
pub fn line(&self) -> String {
match *self {
Self::Storm {
per_window,
lasting,
} => format!(
"HOST ACPI SCI storm: {per_window} interrupts in the last second, past \
{STORM_PER_WINDOW} for {STORM_WINDOWS} s; the SCI stays masked and ACPICA's \
handler runs every {POLL_MS} ms {}\n",
if lasting {
String::from("for the rest of the boot (the second storm)")
} else {
format!("for {} s, then interrupts are tried again", RETRY_MS / 1000)
}
),
Self::Retry => format!(
"HOST ACPI SCI interrupts tried again after {} s polled\n",
RETRY_MS / 1000
),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Interrupts,
Polled { since: u64, lasting: bool },
}
/// The SCI's storm guard. A level SCI that no handler clears (a GPE
/// without one that ACPICA cannot disable, a chipset's stuck status) would
/// otherwise run ACPICA's handler every turn for the rest of the boot.
/// Past [`STORM_PER_WINDOW`] for [`STORM_WINDOWS`] windows in a row the SCI
/// stays masked and the handler runs every [`POLL_MS`] instead, which still
/// takes every event, late; interrupts are tried again once after
/// [`RETRY_MS`], and a second storm keeps the polling for good.
#[derive(Clone, Copy, Debug)]
pub struct SciGovernor {
mode: Mode,
window_start: u64,
in_window: u32,
stormy: u32,
last_poll: u64,
storms: u32,
}
impl SciGovernor {
pub fn new(now: u64) -> Self {
Self {
mode: Mode::Interrupts,
window_start: now,
in_window: 0,
stormy: 0,
last_poll: now,
storms: 0,
}
}
/// Whether the SCI is masked and polled.
pub fn polled(&self) -> bool {
matches!(self.mode, Mode::Polled { .. })
}
/// The storms so far.
pub fn storms(&self) -> u32 {
self.storms
}
/// One turn at `now` (milliseconds), `interrupted` when the SCI's
/// interrupt arrived since the last turn.
pub fn turn(&mut self, now: u64, interrupted: bool) -> Turn {
match self.mode {
Mode::Interrupts => {
self.in_window += u32::from(interrupted);
let mut change = None;
if now.saturating_sub(self.window_start) >= WINDOW_MS {
if self.in_window >= STORM_PER_WINDOW {
self.stormy += 1;
} else {
self.stormy = 0;
}
let per_window = self.in_window;
self.window_start = now;
self.in_window = 0;
if self.stormy >= STORM_WINDOWS {
self.storms += 1;
let lasting = self.storms > 1;
self.mode = Mode::Polled {
since: now,
lasting,
};
self.stormy = 0;
self.last_poll = now;
change = Some(Change::Storm {
per_window,
lasting,
});
}
}
Turn {
dispatch: interrupted,
rearm: interrupted && !self.polled(),
change,
}
}
Mode::Polled { since, lasting } => {
if !lasting && now.saturating_sub(since) >= RETRY_MS {
self.mode = Mode::Interrupts;
self.window_start = now;
self.in_window = 0;
return Turn {
dispatch: true,
rearm: true,
change: Some(Change::Retry),
};
}
let due = now.saturating_sub(self.last_poll) >= POLL_MS;
if due {
self.last_poll = now;
}
Turn {
dispatch: due || interrupted,
rearm: false,
change: None,
}
}
}
}
}
/// EC queries one window takes at most; the rest wait for the next. An EC
/// that keeps `SCI_EVT` set and answers each `QR_EC` with an event would
/// otherwise run its `_Qxx` methods every turn.
pub const QUERIES_PER_WINDOW: u32 = 64;
/// Failed EC transactions in a row that stop the EC's events. Each one has
/// waited out the EC's timeout (500 ms), so a dead EC would otherwise cost
/// the guest that each turn.
pub const EC_FAILURES: u32 = 3;
/// Whether one more EC query is taken now ([`EcGovernor::admit`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Admit {
Take,
/// The window's budget is spent; `first` for the window's first refusal,
/// which the boot reports once.
Wait {
first: bool,
},
/// The EC's events are stopped.
Stopped,
}
/// The EC's query budget and failure breaker, and which query numbers the
/// boot has named, each once.
#[derive(Clone, Debug)]
pub struct EcGovernor {
window_start: u64,
in_window: u32,
refused: bool,
failures: u32,
stopped: bool,
named: [u64; 4],
}
impl EcGovernor {
pub fn new(now: u64) -> Self {
Self {
window_start: now,
in_window: 0,
refused: false,
failures: 0,
stopped: false,
named: [0; 4],
}
}
pub fn stopped(&self) -> bool {
self.stopped
}
/// One more query at `now` (milliseconds).
pub fn admit(&mut self, now: u64) -> Admit {
if self.stopped {
return Admit::Stopped;
}
if now.saturating_sub(self.window_start) >= WINDOW_MS {
self.window_start = now;
self.in_window = 0;
self.refused = false;
}
if self.in_window >= QUERIES_PER_WINDOW {
let first = !self.refused;
self.refused = true;
return Admit::Wait { first };
}
self.in_window += 1;
Admit::Take
}
/// A transaction that completed.
pub fn succeeded(&mut self) {
self.failures = 0;
}
/// A transaction that failed: true when this one stops the EC's events.
pub fn failed(&mut self) -> bool {
if self.stopped {
return false;
}
self.failures += 1;
if self.failures >= EC_FAILURES {
self.stopped = true;
return true;
}
false
}
/// Whether query `number` is named for the first time, so its line is
/// written: a laptop's few events each get one, and an event that
/// repeats does not fill the log.
pub fn first(&mut self, number: u8) -> bool {
let (word, bit) = (usize::from(number / 64), 1u64 << (number % 64));
let first = self.named[word] & bit == 0;
self.named[word] |= bit;
first
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,239 @@
use super::*;
/// Garvit's ASUS TUF A16 (FA608PP) FADT as dumped (2026-11-18), with only
/// the fields this module reads: SCI_INT 9, SMI_CMD 0xb2, ACPI_ENABLE 0xa0,
/// PM1a_CNT 0x804 and flags 0x23c5b5 (no HW_REDUCED_ACPI).
fn tuf_a16() -> alloc::vec::Vec<u8> {
let mut fadt = alloc::vec![0; 276];
fadt[..4].copy_from_slice(b"FACP");
fadt[46..48].copy_from_slice(&9u16.to_le_bytes());
fadt[48..52].copy_from_slice(&0xb2u32.to_le_bytes());
fadt[52] = 0xa0;
fadt[53] = 0xa1;
fadt[64..68].copy_from_slice(&0x804u32.to_le_bytes());
fadt[112..116].copy_from_slice(&0x23c5b5u32.to_le_bytes());
fadt
}
#[test]
fn reads_the_tuf_a16_acpi_mode_registers() {
let registers = Registers::read(&tuf_a16()).unwrap();
assert_eq!(
registers,
Registers {
sci_interrupt: 9,
smi_command: 0xb2,
acpi_enable: 0xa0,
pm1a_control: 0x804,
reduced: false,
}
);
assert_eq!(registers.control_port(), Some(0x804));
assert!(Registers::read(&tuf_a16()[..100]).is_none());
let mut reduced = tuf_a16();
reduced[112..116].copy_from_slice(&(1u32 << 20).to_le_bytes());
assert!(Registers::read(&reduced).unwrap().reduced);
}
#[test]
fn names_what_entering_acpi_mode_takes() {
let registers = Registers::read(&tuf_a16()).unwrap();
assert_eq!(
registers.entry(Some(1)),
"the firmware left SCI_EN set, so no SMI_CMD write enters ACPI mode"
);
assert_eq!(
registers.entry(Some(0)),
"SCI_EN is clear, so ACPI mode is entered with SMI_CMD 0xb2 <- 0xa0"
);
assert!(registers.entry(None).starts_with("PM1a_CNT unread"));
let none = Registers {
smi_command: 0,
..registers
};
assert_eq!(
none.entry(Some(0)),
"SCI_EN is clear and the FADT has no SMI_CMD or ACPI_ENABLE"
);
let line = starting_line(&registers, "GSI 9 low level", Some(1));
assert_eq!(
line,
"ACPI hardware mode starting (--acpi-hardware): SCI_INT 9 on GSI 9 low level; the \
firmware left SCI_EN set, so no SMI_CMD write enters ACPI mode\n"
);
}
#[test]
fn the_off_lines_name_the_option_and_what_stays_off() {
let off = off_line();
assert!(off.starts_with("UNSUPPORTED ACPI hardware mode: off unless --acpi-hardware"));
assert!(off.contains(WITHOUT) && off.ends_with('\n'));
let refused = refused_line("the SCI's route was not captured");
assert!(refused.contains("--acpi-hardware is given, but the SCI's route was not captured"));
assert!(refused.contains(WITHOUT));
}
/// A turn every 4 ms (250 a second) for `ms`, each interrupted when
/// `interrupted` says so; the turns that dispatched and rearmed, and the
/// changes.
fn run(
governor: &mut SciGovernor,
from: u64,
ms: u64,
interrupted: impl Fn(u64) -> bool,
) -> (u32, u32, alloc::vec::Vec<(u64, Change)>) {
let (mut dispatched, mut rearmed, mut changes) = (0, 0, alloc::vec::Vec::new());
let mut now = from;
while now < from + ms {
let turn = governor.turn(now, interrupted(now));
dispatched += u32::from(turn.dispatch);
rearmed += u32::from(turn.rearm);
if let Some(change) = turn.change {
changes.push((now, change));
}
now += 4;
}
(dispatched, rearmed, changes)
}
#[test]
fn a_laptops_few_events_stay_interrupts() {
let mut governor = SciGovernor::new(0);
// Ten events a second for a minute: a held brightness key is fewer.
let (dispatched, rearmed, changes) = run(&mut governor, 0, 60_000, |now| now % 100 == 0);
assert_eq!(dispatched, 600);
assert_eq!(rearmed, 600);
assert!(changes.is_empty());
assert!(!governor.polled());
// No interrupt, no handler and no rearm.
let turn = governor.turn(60_004, false);
assert!(!turn.dispatch && !turn.rearm && turn.change.is_none());
}
#[test]
fn a_burst_shorter_than_the_storm_windows_stays_interrupts() {
let mut governor = SciGovernor::new(0);
// Every turn for two seconds, then quiet: two windows, not three.
let (_, _, changes) = run(&mut governor, 0, 2_000, |_| true);
assert!(changes.is_empty());
let (_, _, changes) = run(&mut governor, 2_000, 10_000, |_| false);
assert!(changes.is_empty());
assert!(!governor.polled());
}
#[test]
fn a_held_sci_is_masked_polled_retried_and_then_polled_for_good() {
let mut governor = SciGovernor::new(0);
let (_, _, changes) = run(&mut governor, 0, 3_004, |_| true);
assert_eq!(
changes,
[(
3_000,
Change::Storm {
per_window: 250,
lasting: false
}
)]
);
assert!(governor.polled());
assert!(
changes[0]
.1
.line()
.contains("then interrupts are tried again")
);
// Masked: the handler runs every POLL_MS and the line is never rearmed,
// even if an interrupt arrived before the mask.
let (dispatched, rearmed, changes) = run(&mut governor, 3_004, 10_000, |_| false);
assert_eq!(rearmed, 0);
assert!(changes.is_empty());
assert!((99..=101).contains(&dispatched), "{dispatched}");
let (_, rearmed, _) = run(&mut governor, 13_004, 4, |_| true);
assert_eq!(rearmed, 0);
// After RETRY_MS, interrupts again, rearmed at once.
let (_, _, changes) = run(&mut governor, 13_008, 20_000, |_| false);
assert_eq!(changes, [(33_000, Change::Retry)]);
assert!(!governor.polled());
// A second storm keeps the polling for the rest of the boot.
let (_, _, changes) = run(&mut governor, 33_008, 3_100, |_| true);
assert_eq!(changes.len(), 1);
assert_eq!(
changes[0].1,
Change::Storm {
per_window: 250,
lasting: true
}
);
assert!(changes[0].1.line().contains("for the rest of the boot"));
let (dispatched, rearmed, changes) = run(&mut governor, 36_108, 600_000, |_| false);
assert!(changes.is_empty());
assert_eq!(rearmed, 0);
assert!(dispatched >= 5_990);
assert!(governor.polled());
assert_eq!(governor.storms(), 2);
}
#[test]
fn the_retry_turn_runs_the_handler_and_rearms_with_no_interrupt_pending() {
let mut governor = SciGovernor::new(0);
run(&mut governor, 0, 3_004, |_| true);
assert!(governor.polled());
// The line was masked, so no interrupt arrives; the turn that tries
// interrupts again must still dispatch and rearm, or it stays masked.
let turn = governor.turn(3_000 + RETRY_MS, false);
assert_eq!(
turn,
Turn {
dispatch: true,
rearm: true,
change: Some(Change::Retry)
}
);
assert!(!governor.polled());
}
#[test]
fn a_clock_that_goes_backwards_starts_no_storm() {
let mut governor = SciGovernor::new(5_000);
for now in (0..5_000).rev().step_by(4) {
assert!(governor.turn(now, true).change.is_none());
}
assert!(!governor.polled());
}
#[test]
fn the_ec_takes_a_windows_budget_of_queries_and_reports_its_first_refusal() {
let mut ec = EcGovernor::new(0);
for _ in 0..QUERIES_PER_WINDOW {
assert_eq!(ec.admit(10), Admit::Take);
}
assert_eq!(ec.admit(10), Admit::Wait { first: true });
assert_eq!(ec.admit(500), Admit::Wait { first: false });
// The next window starts the budget again.
assert_eq!(ec.admit(1_000), Admit::Take);
}
#[test]
fn failed_transactions_in_a_row_stop_the_ecs_events_once() {
let mut ec = EcGovernor::new(0);
assert!(!ec.failed());
assert!(!ec.failed());
ec.succeeded();
assert!(!ec.failed());
assert!(!ec.failed());
assert!(ec.failed());
assert!(ec.stopped());
assert!(!ec.failed(), "the stop is reported once");
assert_eq!(ec.admit(5_000), Admit::Stopped);
}
#[test]
fn each_query_number_is_named_once() {
let mut ec = EcGovernor::new(0);
assert!(ec.first(0x2f));
assert!(!ec.first(0x2f));
assert!(ec.first(0x17));
assert!(ec.first(0xff));
assert!(ec.first(0));
assert!(!ec.first(0xff));
}
+521
View File
@@ -0,0 +1,521 @@
//! An AMD GPU's IP discovery table, which names the version of each of its
//! IP blocks, as amdgpu reads it at its probe (`amdgpu_discovery.c`). The
//! boot reads it before the GPU's reset so the firmware it gives amdgpu is
//! the files of those versions only.
//!
//! The table lies in the GPU's memory, 64 KiB below the top of its VRAM as
//! `RCC_CONFIG_MEMSIZE` gives it, or where the GPU's security processor
//! says in the driver scratch registers (`amdgpu_discovery_get_tmr_info`).
//! amdgpu reads it through the `MM_INDEX`/`MM_DATA` window, which needs no
//! mapping of the GPU's memory (`amdgpu_device_mm_access`). The checks here
//! are `amdgpu_discovery_init`'s; the walk is
//! `amdgpu_discovery_reg_base_init`'s.
use alloc::vec::Vec;
/// Registers, as byte offsets in the register BAR (`amdgpu_discovery.c`:
/// "consistent across all the SOCs").
pub const MM_INDEX: usize = 0;
pub const MM_DATA: usize = 4;
pub const MM_INDEX_HI: usize = 0x6 * 4;
pub const DRIVER_SCRATCH_0: usize = 0x94 * 4;
pub const DRIVER_SCRATCH_1: usize = 0x95 * 4;
pub const DRIVER_SCRATCH_2: usize = 0x96 * 4;
pub const RCC_CONFIG_MEMSIZE: usize = 0xde3 * 4;
pub const MP0_SMN_C2PMSG_33: usize = 0x16061 * 4;
/// The security processor's ring command and response register, and its
/// secure OS's sign of life (`psp_v11_0.c`, `psp_v13_0.c`), at the place
/// amdgpu's discovery reads `C2PMSG_33` on every SOC.
pub const MP0_SMN_C2PMSG_64: usize = 0x16080 * 4;
pub const MP0_SMN_C2PMSG_81: usize = 0x16091 * 4;
/// The register window the read needs.
pub const REGISTER_BYTES: usize = MP0_SMN_C2PMSG_33 + 4;
/// The register window the security processor's state needs.
pub const SECURITY_PROCESSOR_BYTES: usize = MP0_SMN_C2PMSG_81 + 4;
/// `C2PMSG_33` bit 31: the GPU's firmware finished its start and placed the
/// table.
pub const FIRMWARE_READY: u32 = 1 << 31;
/// `DISCOVERY_TMR_SIZE` and `DISCOVERY_TMR_OFFSET`.
pub const TABLE_BYTES: usize = 10 << 10;
pub const BELOW_TOP: u64 = 64 << 10;
/// The most a scratch-register size may ask to read.
const MOST_BYTES: usize = 64 << 10;
/// `BINARY_SIGNATURE` and `DISCOVERY_TABLE_SIGNATURE` of
/// `include/discovery.h`, as little-endian dwords: the latter is "IPDS".
pub const BINARY_SIGNATURE: u32 = 0x2821_1407;
const DISCOVERY_TABLE_SIGNATURE: u32 = 0x5344_5049;
/// The hardware IDs of the blocks whose firmware amdgpu names after their
/// versions (`soc15_hw_ip.h`).
pub const MP1: u16 = 1;
pub const GC: u16 = 11;
pub const VCN: u16 = 12;
pub const VPE: u16 = 21;
pub const SDMA0: u16 = 42;
pub const DMU: u16 = 271;
pub const MP0: u16 = 255;
/// `HW_ID_MAX` and `HWIP_MAX_INSTANCE`: entries past these are skipped.
const HW_ID_MAX: u16 = 300;
const MAX_INSTANCE: u8 = 44;
/// One IP block as the table lists it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Ip {
pub hw_id: u16,
pub instance: u8,
pub major: u8,
pub minor: u8,
pub revision: u8,
}
/// Why the table was not read or not taken.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
/// `RCC_CONFIG_MEMSIZE` reads all ones: the GPU does not answer.
NoAnswer,
/// The GPU's firmware has not placed the table yet (`C2PMSG_33`).
NotReady,
/// The table is in system memory (no VRAM size and no scratch place),
/// where amdgpu finds it through ACPI.
InSystemMemory,
Signature,
Checksum,
Version(u16),
TableSignature,
TableChecksum,
Truncated,
DieId,
/// No memory for the table's bytes.
Memory,
}
/// Where to read the table: the VRAM offset and length.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Place {
pub offset: u64,
pub bytes: usize,
}
/// Where the table lies, as `amdgpu_discovery_get_tmr_info` finds it on a
/// GPU that is no virtual function: `read` reads a register of the
/// register BAR, `signature_at` the dword at a VRAM offset.
pub fn place(
mut read: impl FnMut(usize) -> u32,
mut signature_at: impl FnMut(u64) -> u32,
) -> Result<Place, Error> {
if read(MP0_SMN_C2PMSG_33) & FIRMWARE_READY == 0 {
return Err(Error::NotReady);
}
let vram_mib = read(RCC_CONFIG_MEMSIZE);
if vram_mib == u32::MAX {
return Err(Error::NoAnswer);
}
if vram_mib != 0 {
let offset = (u64::from(vram_mib) << 20).saturating_sub(BELOW_TOP);
if signature_at(offset) == BINARY_SIGNATURE {
return Ok(Place {
offset,
bytes: TABLE_BYTES,
});
}
}
let size = read(DRIVER_SCRATCH_2);
if size != 0 {
return Ok(Place {
offset: u64::from(read(DRIVER_SCRATCH_1)) << 32 | u64::from(read(DRIVER_SCRATCH_0)),
bytes: (size as usize).min(MOST_BYTES),
});
}
if vram_mib == 0 {
return Err(Error::InSystemMemory);
}
Ok(Place {
offset: (u64::from(vram_mib) << 20).saturating_sub(BELOW_TOP),
bytes: TABLE_BYTES,
})
}
/// The security processor's state as a function's previous owner left it,
/// from `C2PMSG_33` (its boot loader), `C2PMSG_64` (its ring's command and
/// answer) and `C2PMSG_81` (its secure OS), in words: what amdgpu's own
/// start then meets, such as a ring a previous driver made.
pub fn security_processor(c2pmsg_33: u32, c2pmsg_64: u32, c2pmsg_81: u32) -> alloc::string::String {
use alloc::format;
let read = format!(
"C2PMSG_33={c2pmsg_33:#010x} C2PMSG_64={c2pmsg_64:#010x} C2PMSG_81={c2pmsg_81:#010x}"
);
if [c2pmsg_33, c2pmsg_64, c2pmsg_81] == [u32::MAX; 3] {
return format!("{read}: it does not answer");
}
let loader = if c2pmsg_33 & FIRMWARE_READY != 0 {
"its boot loader is ready"
} else {
"its boot loader is not ready"
};
let os = if c2pmsg_81 != 0 {
"its secure OS runs, as the firmware or a previous driver left it"
} else {
"no secure OS runs"
};
let ring = match c2pmsg_64 {
0 => alloc::string::String::from("no ring command waits"),
answer if answer & (1 << 31) != 0 => format!(
"its last ring command was answered with status {:#06x}",
answer & 0xffff
),
command => format!("ring command {command:#x} waits for its answer"),
};
format!("{read}: {loader}; {os}; {ring}")
}
/// The register BAR's first page: the index registers and the driver
/// scratch registers lie in it.
pub const INDEX_PAGE_BYTES: usize = 4096;
/// The register BAR as the read before the reset reaches it. The read
/// writes the index registers, so the page that holds them is the one
/// mapping of it the read uses: a second mapping of a page already mapped
/// is refused.
pub trait Registers {
/// A dword of the register BAR; all ones when it does not answer.
fn read(&self, offset: usize) -> u32;
/// Writes a dword of the first page ([`INDEX_PAGE_BYTES`]); false when
/// the write was refused.
fn write(&self, offset: usize, value: u32) -> bool;
}
/// The IP blocks the table lists, read from VRAM through the `MM_INDEX`,
/// `MM_INDEX_HI` and `MM_DATA` window one dword at a time, as
/// `amdgpu_device_mm_access` reads it; the index registers hold their
/// earlier values again after.
pub fn read(registers: &impl Registers) -> Result<Vec<Ip>, Failure> {
let index = (registers.read(MM_INDEX), registers.read(MM_INDEX_HI));
let vram = |position: u64| -> u32 {
let selected = registers.write(MM_INDEX, position as u32 | 0x8000_0000)
&& registers.write(MM_INDEX_HI, (position >> 31) as u32);
if selected {
registers.read(MM_DATA)
} else {
u32::MAX
}
};
let result = place(|offset| registers.read(offset), vram)
.map_err(Failure::from)
.and_then(|place| {
let mut binary = Vec::new();
binary
.try_reserve_exact(place.bytes)
.map_err(|_| Failure::from(Error::Memory))?;
for at in (0..place.bytes as u64).step_by(4) {
binary.extend_from_slice(&vram(place.offset + at).to_le_bytes());
}
parse(&binary).map_err(|error| Failure::found(error, place, &binary))
});
registers.write(MM_INDEX, index.0);
registers.write(MM_INDEX_HI, index.1);
result
}
/// Why [`read`] took no table, with what it found where it read one: the
/// VRAM offset, the binary's first bytes and, past a good binary header,
/// where its IP discovery table was and that table's first bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Failure {
pub error: Error,
pub read: Option<(Place, [u8; 4])>,
pub table: Option<(u16, [u8; 4])>,
}
impl From<Error> for Failure {
fn from(error: Error) -> Self {
Self {
error,
read: None,
table: None,
}
}
}
impl Failure {
fn found(error: Error, place: Place, binary: &[u8]) -> Self {
let first = |at: usize| -> Option<[u8; 4]> { binary.get(at..at + 4)?.try_into().ok() };
// Past a binary that is none, no table is placed.
let entry = match u16_at(binary, 4) {
_ if error == Error::Signature => None,
Ok(0 | 1) => Some(12),
Ok(2) => Some(16),
_ => None,
};
let table = entry
.and_then(|entry| u16_at(binary, entry).ok())
.and_then(|offset| Some((offset, first(usize::from(offset))?)));
Self {
error,
read: first(0).map(|bytes| (place, bytes)),
table,
}
}
}
impl Error {
/// What the error means of the GPU, where its name does not say it.
fn meaning(self) -> Option<&'static str> {
Some(match self {
Self::NoAnswer => "RCC_CONFIG_MEMSIZE reads all ones: the GPU does not answer",
Self::NotReady => {
"MP0 C2PMSG_33 bit 31 is clear: the GPU's firmware has not placed the table"
}
Self::InSystemMemory => {
"RCC_CONFIG_MEMSIZE reads 0 and the scratch registers name no place: the table \
is in system memory, where amdgpu finds it through ACPI"
}
Self::Memory => "no memory for the table's bytes",
_ => return None,
})
}
}
impl core::fmt::Display for Failure {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", self.error)?;
if let Some(meaning) = self.error.meaning() {
write!(f, " ({meaning})")?;
}
if let Some((place, bytes)) = self.read {
write!(
f,
"; read {:#x} bytes at VRAM offset {:#x}, whose first word is {:#010x}",
place.bytes,
place.offset,
u32::from_le_bytes(bytes)
)?;
if self.error == Error::Signature {
write!(f, " where a table binary's is {BINARY_SIGNATURE:#010x}")?;
}
}
if let Some((offset, bytes)) = self.table {
write!(
f,
"; its table at {offset:#x} starts {:#010x}",
u32::from_le_bytes(bytes)
)?;
if self.error == Error::TableSignature {
write!(
f,
" where an IP discovery table's is {DISCOVERY_TABLE_SIGNATURE:#010x} (IPDS)"
)?;
}
}
Ok(())
}
}
fn u16_at(bytes: &[u8], at: usize) -> Result<u16, Error> {
bytes
.get(at..at + 2)
.map(|word| u16::from_le_bytes([word[0], word[1]]))
.ok_or(Error::Truncated)
}
fn u32_at(bytes: &[u8], at: usize) -> Result<u32, Error> {
bytes
.get(at..at + 4)
.map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]]))
.ok_or(Error::Truncated)
}
fn sum(bytes: &[u8]) -> u16 {
bytes
.iter()
.fold(0u16, |sum, &byte| sum.wrapping_add(u16::from(byte)))
}
/// The IP blocks the table `binary` lists, with its binary and data table
/// checked as amdgpu checks them. VCN's revision loses its two capability
/// bits, as amdgpu masks them.
pub fn parse(binary: &[u8]) -> Result<Vec<Ip>, Error> {
if u32_at(binary, 0)? != BINARY_SIGNATURE {
return Err(Error::Signature);
}
// The byte sum of the binary after its checksum field, to its size.
let checksum = u16_at(binary, 8)?;
let size = usize::from(u16_at(binary, 10)?);
let body = binary.get(10..size.max(10)).ok_or(Error::Truncated)?;
if sum(body) != checksum {
return Err(Error::Checksum);
}
// The IP discovery table's entry: version 0 and 1 list tables from 12,
// version 2 after a count and padding.
let entry = match u16_at(binary, 4)? {
0 | 1 => 12,
2 => 16,
version => return Err(Error::Version(version)),
};
let offset = usize::from(u16_at(binary, entry)?);
let table_checksum = u16_at(binary, entry + 2)?;
if u32_at(binary, offset)? != DISCOVERY_TABLE_SIGNATURE {
return Err(Error::TableSignature);
}
let table_bytes = usize::from(u16_at(binary, offset + 6)?);
let table = binary
.get(offset..offset + table_bytes)
.ok_or(Error::Truncated)?;
if sum(table) != table_checksum {
return Err(Error::TableChecksum);
}
let version = u16_at(binary, offset + 4)?;
let dies = usize::from(u16_at(binary, offset + 12)?).min(16);
// After the 16 die entries, version 4's flag byte: 64-bit base
// addresses.
let wide = version == 4 && binary.get(offset + 14 + 16 * 4).ok_or(Error::Truncated)? & 1 != 0;
let mut ips = Vec::new();
for die in 0..dies {
let die_offset = usize::from(u16_at(binary, offset + 14 + die * 4 + 2)?);
if usize::from(u16_at(binary, die_offset)?) != die {
return Err(Error::DieId);
}
let count = u16_at(binary, die_offset + 2)?;
let mut at = die_offset + 4;
for _ in 0..count {
let entry = binary.get(at..at + 8).ok_or(Error::Truncated)?;
let hw_id = u16::from_le_bytes([entry[0], entry[1]]);
let instance = entry[2];
let bases = usize::from(entry[3]);
let mut revision = entry[6];
if hw_id == VCN {
revision &= !0xc0;
}
if hw_id < HW_ID_MAX && instance < MAX_INSTANCE {
ips.push(Ip {
hw_id,
instance,
major: entry[4],
minor: entry[5],
revision,
});
}
at += 8 + bases * if wide { 8 } else { 4 };
}
}
Ok(ips)
}
/// The version of the first instance of `hw_id`, if the table lists it.
pub fn version(ips: &[Ip], hw_id: u16) -> Option<(u8, u8, u8)> {
ips.iter()
.filter(|ip| ip.hw_id == hw_id)
.min_by_key(|ip| ip.instance)
.map(|ip| (ip.major, ip.minor, ip.revision))
}
/// Where the register BAR `bar` starts, by the firmware's description of
/// it (`regions`, its GetBarAttributes answer): the start of its memory
/// range, which must hold the registers the table's read needs. A
/// description without a memory range, or with one too short, is an error
/// that says so, as a BAR the firmware does not describe at all is: the
/// caller then reads the BAR by its address instead.
pub fn described_registers(
bar: u8,
regions: &[crate::firmware_pci::BarRegion],
) -> Result<u64, alloc::string::String> {
let Some(window) = regions
.iter()
.find(|region| region.resource_type == 0)
.map(|region| &region.host)
else {
return Err(alloc::format!("its BAR {bar} holds no memory range"));
};
let length = window.end.saturating_sub(window.start);
if length < REGISTER_BYTES as u64 {
return Err(alloc::format!(
"its BAR {bar} at {:#x} holds {length:#x} bytes, under the {REGISTER_BYTES:#x} the \
table's registers need",
window.start
));
}
Ok(window.start)
}
/// AMD's PCI vendor ID, which its GPUs and the bridges on its cards carry
/// (Linux's `PCI_VENDOR_ID_ATI`).
pub const ATI_VENDOR: u16 = 0x1002;
/// The upstream port of the PCIe switch on AMD's discrete cards from Navi
/// on, whose ports amdgpu skips to find the slot's link
/// (`amdgpu_device_init_pcie_links`).
pub const SWITCH_UPSTREAM: u16 = 0x1478;
/// That switch's downstream port, right above the GPU.
pub const SWITCH_DOWNSTREAM: u16 = 0x1479;
/// A PCI-to-PCI bridge, as its configuration header gives it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Bridge {
pub segment: u16,
/// The bus the bridge itself is on.
pub bus: u8,
pub vendor: u16,
pub device: u16,
/// The bus right below it.
pub secondary: u8,
}
impl Bridge {
/// The bridge on `segment` and `bus` whose configuration header's first
/// 64 bytes are `header`, or `None` for a header of another type.
pub fn of(segment: u16, bus: u8, header: &[u8; 64]) -> Option<Self> {
const HEADER_TYPE: usize = 0x0e;
const SECONDARY_BUS: usize = 0x19;
(header[HEADER_TYPE] & 0x7f == 1).then(|| Self {
segment,
bus,
vendor: u16::from_le_bytes([header[0], header[1]]),
device: u16::from_le_bytes([header[2], header[3]]),
secondary: header[SECONDARY_BUS],
})
}
/// The bridge among `bridges` whose secondary bus is `bus` on `segment`;
/// a bridge whose bus numbers were never set is above nothing.
fn above(segment: u16, bus: u8, bridges: &[Self]) -> Option<&Self> {
bridges.iter().find(|bridge| {
bridge.segment == segment && bridge.secondary == bus && bridge.secondary > bridge.bus
})
}
}
/// Whether the function on `bus` of `segment` sits right below an AMD
/// card's own PCIe switch, among `bridges`: its downstream port (1002:1479)
/// above it, and that port below the switch's upstream port (1002:1478). An
/// APU sits straight below a host bridge or root port, so such a GPU is
/// discrete.
pub fn behind_own_switch(segment: u16, bus: u8, bridges: &[Bridge]) -> bool {
let is = |bridge: &Bridge, device: u16| bridge.vendor == ATI_VENDOR && bridge.device == device;
Bridge::above(segment, bus, bridges)
.filter(|downstream| is(downstream, SWITCH_DOWNSTREAM))
.and_then(|downstream| Bridge::above(segment, downstream.bus, bridges))
.is_some_and(|upstream| is(upstream, SWITCH_UPSTREAM))
}
/// The kind of an AMD GPU whose IP discovery table was not read (`why`):
/// discrete where it sits below its card's own PCIe switch
/// ([`behind_own_switch`]), else integrated, as a GPU whose kind is not
/// known counts. Whether it is integrated, and how that was told.
pub fn unread_kind(behind_switch: bool, why: &str) -> (bool, alloc::string::String) {
match behind_switch {
true => (
false,
alloc::format!(
"its IP discovery table was not read ({why}); discrete: behind its own PCIe switch"
),
),
false => (
true,
alloc::format!(
"not known: its IP discovery table was not read ({why}); taken as integrated"
),
),
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,369 @@
use super::*;
use alloc::{vec, vec::Vec};
use core::cell::RefCell;
/// A version 1 binary whose one die lists `ips` (hw_id, major, minor,
/// revision), each with one base address, in an IP discovery table of
/// version `table_version`.
pub(crate) fn binary(ips: &[(u16, u8, u8, u8)], table_version: u16) -> Vec<u8> {
const TABLE: usize = 64;
const DIE: usize = TABLE + 80;
let mut bytes = vec![0u8; DIE + 4 + ips.len() * 12];
let put16 = |bytes: &mut Vec<u8>, at: usize, value: u16| {
bytes[at..at + 2].copy_from_slice(&value.to_le_bytes())
};
let put32 = |bytes: &mut Vec<u8>, at: usize, value: u32| {
bytes[at..at + 4].copy_from_slice(&value.to_le_bytes())
};
// The signatures as the GPU's firmware lays them out.
bytes[0..4].copy_from_slice(&[0x07, 0x14, 0x21, 0x28]);
put16(&mut bytes, 4, 1);
let total = bytes.len();
put16(&mut bytes, 10, total as u16);
put16(&mut bytes, 12, TABLE as u16);
bytes[TABLE..TABLE + 4].copy_from_slice(b"IPDS");
put16(&mut bytes, TABLE + 4, table_version);
put16(&mut bytes, TABLE + 6, (total - TABLE) as u16);
put16(&mut bytes, TABLE + 12, 1);
put16(&mut bytes, TABLE + 16, DIE as u16);
put16(&mut bytes, DIE + 2, ips.len() as u16);
for (index, &(hw_id, major, minor, revision)) in ips.iter().enumerate() {
let at = DIE + 4 + index * 12;
put16(&mut bytes, at, hw_id);
bytes[at + 3] = 1;
bytes[at + 4] = major;
bytes[at + 5] = minor;
bytes[at + 6] = revision;
put32(&mut bytes, at + 8, 0x1234);
}
let table = sum(&bytes[TABLE..]);
put16(&mut bytes, 14, table);
let binary = sum(&bytes[10..]);
put16(&mut bytes, 8, binary);
bytes
}
/// Raphael's blocks: Ryzen 7000's graphics.
pub(crate) const RAPHAEL: &[(u16, u8, u8, u8)] = &[
(GC, 10, 3, 6),
(MP0, 13, 0, 5),
(MP1, 13, 0, 5),
(SDMA0, 5, 2, 6),
(VCN, 3, 1, 2),
(DMU, 3, 1, 5),
];
#[test]
fn the_table_lists_each_block_with_its_version() {
let ips = parse(&binary(RAPHAEL, 3)).unwrap();
assert_eq!(ips.len(), RAPHAEL.len());
assert_eq!(version(&ips, GC), Some((10, 3, 6)));
assert_eq!(version(&ips, DMU), Some((3, 1, 5)));
assert_eq!(version(&ips, VPE), None);
// VCN's capability bits are not its revision.
let ips = parse(&binary(&[(VCN, 4, 0, 0x85)], 3)).unwrap();
assert_eq!(version(&ips, VCN), Some((4, 0, 5)));
}
#[test]
fn a_damaged_table_is_refused() {
let good = binary(RAPHAEL, 3);
let mut bad = good.clone();
bad[0] ^= 1;
assert_eq!(parse(&bad), Err(Error::Signature));
let mut bad = good.clone();
let last = bad.len() - 1;
bad[last] ^= 1;
assert_eq!(parse(&bad), Err(Error::Checksum));
assert_eq!(parse(&good[..40]), Err(Error::Truncated));
}
#[test]
fn the_table_is_found_where_amdgpu_looks() {
let registers = |memsize: u32, scratch: [u32; 3], ready: bool| {
move |offset: usize| match offset {
MP0_SMN_C2PMSG_33 => {
if ready {
FIRMWARE_READY
} else {
0
}
}
RCC_CONFIG_MEMSIZE => memsize,
DRIVER_SCRATCH_0 => scratch[0],
DRIVER_SCRATCH_1 => scratch[1],
DRIVER_SCRATCH_2 => scratch[2],
_ => 0,
}
};
// 8 GiB of VRAM with the table at its usual place.
let top = (8192u64 << 20) - BELOW_TOP;
assert_eq!(
place(registers(8192, [0; 3], true), |at| if at == top {
BINARY_SIGNATURE
} else {
0
}),
Ok(Place {
offset: top,
bytes: TABLE_BYTES
})
);
// Elsewhere, where the scratch registers say.
assert_eq!(
place(registers(8192, [0x1000, 1, 0x3000], true), |_| 0),
Ok(Place {
offset: 0x1_0000_1000,
bytes: 0x3000
})
);
assert_eq!(
place(registers(8192, [0; 3], false), |_| 0),
Err(Error::NotReady)
);
assert_eq!(
place(registers(0, [0; 3], true), |_| 0),
Err(Error::InSystemMemory)
);
assert_eq!(
place(registers(u32::MAX, [0; 3], true), |_| 0),
Err(Error::NoAnswer)
);
}
/// A GPU's register BAR as the read reaches it: its first page, the
/// registers past it, and its VRAM behind the index window.
struct Gpu {
page: RefCell<[u32; INDEX_PAGE_BYTES / 4]>,
far: [(usize, u32); 2],
vram: Vec<u8>,
vram_base: u64,
}
impl Registers for Gpu {
fn read(&self, offset: usize) -> u32 {
if offset < INDEX_PAGE_BYTES {
if offset == MM_DATA {
let page = self.page.borrow();
let position = u64::from(page[MM_INDEX_HI / 4]) << 31
| u64::from(page[MM_INDEX / 4] & 0x7fff_ffff);
let at = position.wrapping_sub(self.vram_base) as usize;
return self.vram.get(at..at + 4).map_or(0, |word| {
u32::from_le_bytes([word[0], word[1], word[2], word[3]])
});
}
return self.page.borrow()[offset / 4];
}
self.far
.iter()
.find(|(at, _)| *at == offset)
.map_or(0, |&(_, value)| value)
}
fn write(&self, offset: usize, value: u32) -> bool {
assert!(offset < INDEX_PAGE_BYTES, "a write past the index page");
self.page.borrow_mut()[offset / 4] = value;
true
}
}
#[test]
fn the_table_is_read_through_the_index_page_and_the_index_is_put_back() {
// Raphael (Ryzen 7000's graphics) with 512 MiB of VRAM and the table
// not at its usual place but where the scratch registers in the first
// page place it.
let table = binary(RAPHAEL, 3);
let mut page = [0u32; INDEX_PAGE_BYTES / 4];
page[MM_INDEX / 4] = 0x1234;
page[MM_INDEX_HI / 4] = 0x5;
page[DRIVER_SCRATCH_0 / 4] = 0x1000_0000;
page[DRIVER_SCRATCH_2 / 4] = table.len() as u32;
let gpu = Gpu {
page: RefCell::new(page),
far: [
(MP0_SMN_C2PMSG_33, FIRMWARE_READY),
(RCC_CONFIG_MEMSIZE, 512),
],
vram: table.clone(),
vram_base: 0x1000_0000,
};
let ips = read(&gpu).unwrap();
assert_eq!(ips, parse(&table).unwrap());
assert_eq!(version(&ips, GC), Some((10, 3, 6)));
let page = gpu.page.borrow();
assert_eq!((page[MM_INDEX / 4], page[MM_INDEX_HI / 4]), (0x1234, 0x5));
}
#[test]
fn a_refused_index_write_reads_no_table_and_says_why() {
struct Refusing;
impl Registers for Refusing {
fn read(&self, offset: usize) -> u32 {
match offset {
MP0_SMN_C2PMSG_33 => FIRMWARE_READY,
RCC_CONFIG_MEMSIZE => 512,
DRIVER_SCRATCH_2 => 0x100,
_ => 0,
}
}
fn write(&self, _: usize, _: u32) -> bool {
false
}
}
// Every dword reads all ones: no signature.
assert_eq!(
read(&Refusing).map_err(|failure| failure.error),
Err(Error::Signature)
);
}
#[test]
fn a_table_not_taken_says_where_it_was_read_and_what_it_held() {
// A good binary whose table does not start "IPDS".
let mut table = binary(RAPHAEL, 3);
table[64] = b'X';
let place = Place {
offset: 0x1fff_0000,
bytes: TABLE_BYTES,
};
let failure = Failure::found(Error::TableSignature, place, &table);
assert_eq!(
alloc::format!("{failure}"),
"TableSignature; read 0x2800 bytes at VRAM offset 0x1fff0000, whose first word is \
0x28211407; its table at 0x40 starts 0x53445058 where an IP discovery table's is \
0x53445049 (IPDS)"
);
// A binary whose signature is wrong names what was read and what was
// looked for.
let mut table = binary(RAPHAEL, 3);
table[0..4].copy_from_slice(&[0xff; 4]);
let failure = Failure::found(Error::Signature, place, &table);
assert_eq!(
alloc::format!("{failure}"),
"Signature; read 0x2800 bytes at VRAM offset 0x1fff0000, whose first word is \
0xffffffff where a table binary's is 0x28211407"
);
assert_eq!(
alloc::format!("{}", Failure::from(Error::NotReady)),
"NotReady (MP0 C2PMSG_33 bit 31 is clear: the GPU's firmware has not placed the table)"
);
}
fn memory(start: u64, bytes: u64) -> crate::firmware_pci::BarRegion {
crate::firmware_pci::BarRegion {
resource_type: 0,
general_flags: 0,
specific_flags: 0,
granularity: 32,
observed_maximum: 0,
host: start..start + bytes,
translation: 0,
pci: start..start + bytes,
}
}
/// A firmware that describes the register BAR without a memory range, as
/// an RX 7900 XTX's board firmware answered, or with one too short, gives an
/// error, so the caller reads the BAR by its address; a whole range gives
/// its start.
#[test]
fn a_described_bar_without_a_whole_memory_range_is_read_by_its_address() {
assert_eq!(
described_registers(5, &[]),
Err(alloc::string::String::from(
"its BAR 5 holds no memory range"
))
);
let mut io = memory(0x2000, 0x100);
io.resource_type = 1;
assert!(described_registers(5, &[io]).is_err());
assert_eq!(
described_registers(5, &[memory(0x9540_0000, 0x100)]),
Err(alloc::string::String::from(
"its BAR 5 at 0x95400000 holds 0x100 bytes, under the 0x58188 the table's registers \
need"
))
);
assert_eq!(
described_registers(5, &[memory(0x9540_0000, 1 << 20)]),
Ok(0x9540_0000)
);
}
fn bridge(bus: u8, vendor: u16, device: u16, secondary: u8) -> Bridge {
let mut header = [0u8; 64];
header[0..2].copy_from_slice(&vendor.to_le_bytes());
header[2..4].copy_from_slice(&device.to_le_bytes());
header[0x0e] = 0x01;
header[0x18] = bus;
header[0x19] = secondary;
header[0x1a] = secondary;
Bridge::of(0, bus, &header).unwrap()
}
/// An RX 7900 XTX at 03:00.0 below its card's switch (02:00.0 1002:1479
/// below 01:00.0 1002:1478) below a Raptor Lake root port is discrete; an
/// APU below a host bridge or root port alone, a GPU below only one of the
/// switch's ports, or below another maker's switch, is not told so.
#[test]
fn a_gpu_below_its_own_switch_is_discrete() {
let root = bridge(0, 0x8086, 0xa70d, 1);
let upstream = bridge(1, ATI_VENDOR, SWITCH_UPSTREAM, 2);
let downstream = bridge(2, ATI_VENDOR, SWITCH_DOWNSTREAM, 3);
assert!(behind_own_switch(0, 3, &[root, upstream, downstream]));
assert!(!behind_own_switch(1, 3, &[root, upstream, downstream]));
assert!(!behind_own_switch(0, 3, &[root, downstream]));
assert!(!behind_own_switch(0, 2, &[root, upstream, downstream]));
// Raphael's GPU at 0e:00.0 below its internal bridge 00:08.1.
assert!(!behind_own_switch(
0,
0x0e,
&[bridge(0, 0x1022, 0x14ef, 0x0e)]
));
// Another maker's switch with the same device IDs.
let foreign = bridge(2, 0x10b5, SWITCH_DOWNSTREAM, 3);
assert!(!behind_own_switch(0, 3, &[root, upstream, foreign]));
// A bridge whose buses were never numbered is above nothing.
let unset = bridge(0, ATI_VENDOR, SWITCH_DOWNSTREAM, 0);
assert!(!behind_own_switch(0, 0, &[unset]));
// An endpoint header is no bridge.
assert_eq!(Bridge::of(0, 0, &[0u8; 64]), None);
}
/// A GPU whose table was not read is discrete below its own switch, and
/// integrated otherwise, as before.
#[test]
fn an_unread_gpu_below_its_own_switch_is_discrete() {
assert_eq!(
unread_kind(true, "its BAR 5 holds no memory range"),
(
false,
alloc::string::String::from(
"its IP discovery table was not read (its BAR 5 holds no memory range); discrete: \
behind its own PCIe switch"
)
)
);
let (integrated, how) = unread_kind(false, "x");
assert!(integrated);
assert!(how.ends_with("taken as integrated"));
}
#[test]
fn the_security_processor_state_is_read_in_words() {
assert_eq!(
security_processor(0x8000_0000, 0x8000_0000, 0x0021_0000),
"C2PMSG_33=0x80000000 C2PMSG_64=0x80000000 C2PMSG_81=0x00210000: its boot loader is \
ready; its secure OS runs, as the firmware or a previous driver left it; its last \
ring command was answered with status 0x0000"
);
assert_eq!(
security_processor(0, 0x0002_0000, 0),
"C2PMSG_33=0x00000000 C2PMSG_64=0x00020000 C2PMSG_81=0x00000000: its boot loader is \
not ready; no secure OS runs; ring command 0x20000 waits for its answer"
);
assert_eq!(
security_processor(u32::MAX, u32::MAX, u32::MAX),
"C2PMSG_33=0xffffffff C2PMSG_64=0xffffffff C2PMSG_81=0xffffffff: it does not answer"
);
}
+135
View File
@@ -830,10 +830,145 @@ pub fn bar_physical(
.and_then(|window| address.checked_add(window.translation))
}
/// Why a function's configuration space gives a memory BAR no address.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BarError {
/// The index names no BAR of a Type 0 header.
Index,
/// The BAR decodes I/O space.
Io,
/// Its type field holds the reserved value 01b.
ReservedType,
/// A 64-bit BAR in the last slot, with no upper half.
NoUpperHalf,
/// It holds address zero: no address was assigned.
Unassigned,
}
impl core::fmt::Display for BarError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(match self {
Self::Index => "names no BAR",
Self::Io => "decodes I/O space",
Self::ReservedType => "holds the reserved type 01b",
Self::NoUpperHalf => "is 64-bit in the last slot, with no upper half",
Self::Unassigned => "holds no address",
})
}
}
/// The bus address of memory BAR `index` in a Type 0 configuration
/// `header`, and whether it is prefetchable, as Linux's `__pci_read_base`
/// decodes it (PCI Local Bus 3.0, 6.2.5.1). Reads only; the BAR's size is
/// not sized here.
pub fn memory_bar(header: &[u8; 64], index: u8) -> Result<(u64, bool), BarError> {
let dword = |at: usize| {
u32::from_le_bytes([header[at], header[at + 1], header[at + 2], header[at + 3]])
};
if index >= 6 {
return Err(BarError::Index);
}
let at = 0x10 + usize::from(index) * 4;
let low = dword(at);
if low & 1 != 0 {
return Err(BarError::Io);
}
let address = match low >> 1 & 3 {
0 => u64::from(low & !0xf),
2 if index == 5 => return Err(BarError::NoUpperHalf),
2 => u64::from(low & !0xf) | u64::from(dword(at + 4)) << 32,
_ => return Err(BarError::ReservedType),
};
if address == 0 {
return Err(BarError::Unassigned);
}
Ok((address, low & 1 << 3 != 0))
}
/// The Resizable BAR extended capability's ID (PCIe Base 7.8.6).
const RESIZABLE_BAR: u32 = 0x15;
/// The size BAR `bar` decodes now, by its function's Resizable BAR
/// capability, read without a write: `read` gives the configuration dword
/// at an offset in extended space. `None` where the function has no such
/// capability or it does not list `bar`.
pub fn resizable_bar_bytes(mut read: impl FnMut(u16) -> u32, bar: u8) -> Option<u64> {
let mut offset: u16 = 0x100;
// Each capability is at least a dword; a loop in the list ends here.
for _ in 0..(4096 - 0x100) / 4 {
let header = read(offset);
if header == 0 || header == u32::MAX {
return None;
}
if header & 0xffff == RESIZABLE_BAR {
// Bits 7:5 of the first control register: how many BARs it lists.
let count = (read(offset + 8) >> 5 & 7).max(1) as u16;
return (0..count).find_map(|index| {
let control = read(offset + 8 + index * 8);
(control & 7 == u32::from(bar)).then(|| 1u64 << (20 + (control >> 8 & 0x3f)))
});
}
offset = (header >> 20) as u16 & !3;
if offset < 0x100 {
return None;
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_resizable_bars_size_is_read_from_its_control() {
// AER at 0x100, then Resizable BAR at 0x200 listing BAR 0 at 16 GiB
// (encoding 14) and BAR 2 at 256 MiB (encoding 8).
let space = |offset: u16| match offset {
0x100 => 0x2000_0001,
0x200 => 0x0001_0015,
0x208 => 0x0000_0e40,
0x210 => 0x0000_0802,
_ => 0,
};
assert_eq!(resizable_bar_bytes(space, 0), Some(16 << 30));
assert_eq!(resizable_bar_bytes(space, 2), Some(256 << 20));
assert_eq!(resizable_bar_bytes(space, 5), None);
// No extended capabilities, or a list that loops on itself.
assert_eq!(resizable_bar_bytes(|_| 0, 0), None);
assert_eq!(resizable_bar_bytes(|_| 0x1000_0001, 0), None);
}
#[test]
fn a_memory_bar_is_read_from_the_header_as_linux_decodes_it() {
let mut header = [0u8; 64];
let mut put =
|at: usize, value: u32| header[at..at + 4].copy_from_slice(&value.to_le_bytes());
// BAR 0: 64-bit prefetchable at 0x60_0000_0000; BAR 2: 64-bit at
// 0x80_0000_0000 + 0xc; BAR 4: I/O; BAR 5: 32-bit at 0xfcb0_0000.
put(0x10, 0x0000_000c);
put(0x14, 0x60);
put(0x18, 0x1000_000c);
put(0x1c, 0x80);
put(0x20, 0xe001);
put(0x24, 0xfcb0_0000);
assert_eq!(memory_bar(&header, 0), Ok((0x60_0000_0000, true)));
assert_eq!(memory_bar(&header, 2), Ok((0x80_1000_0000, true)));
assert_eq!(memory_bar(&header, 4), Err(BarError::Io));
assert_eq!(memory_bar(&header, 5), Ok((0xfcb0_0000, false)));
assert_eq!(memory_bar(&header, 6), Err(BarError::Index));
let mut header = [0u8; 64];
header[0x24..0x28].copy_from_slice(&4u32.to_le_bytes());
assert_eq!(memory_bar(&header, 5), Err(BarError::NoUpperHalf));
header[0x24..0x28].copy_from_slice(&2u32.to_le_bytes());
assert_eq!(memory_bar(&header, 5), Err(BarError::ReservedType));
assert_eq!(memory_bar(&header, 1), Err(BarError::Unassigned));
assert_eq!(
alloc::format!("{}", BarError::Unassigned),
"holds no address"
);
}
const PAT_DEFAULT: u64 = 0x0007_0406_0007_0406;
fn controls() -> Controls {
+162
View File
@@ -0,0 +1,162 @@
//! The block samples `--profile`'s NMI takes in native code (`PES PC`):
//! each the word `ChainControl::block` held, which names the block running,
//! and the cycles the sample stands for. The NMI keeps them in its
//! processor's ring ([`BlockRing::push`]) and the engine on that processor
//! takes them after each native run (`Host::profile_blocks`), while the
//! blocks they name are still in their slots.
//!
//! One producer, the NMI, and one consumer, the code it interrupts: the NMI
//! writes only the slot past `head` and then moves `head`, and the consumer
//! reads the slots below `head` and then moves `tail`, so neither waits and
//! neither allocates, as the NMI gate requires. A sample that finds the
//! ring full keeps its cycles in `overflow`, which the next take gives as
//! one sample of [`NO_BLOCK`].
use core::sync::atomic::{AtomicU64, Ordering};
use stela_engine::machine::engine::step_timing::{BlockSample, NO_BLOCK};
/// Samples a ring holds: native runs last tens of microseconds and each
/// is drained at its end, while an NMI comes every few milliseconds.
pub const BLOCK_RING: usize = 64;
pub struct BlockRing {
blocks: [AtomicU64; BLOCK_RING],
cycles: [AtomicU64; BLOCK_RING],
/// Samples pushed and taken so far.
head: AtomicU64,
tail: AtomicU64,
/// The cycles of samples that found the ring full, not yet taken.
overflow: AtomicU64,
}
impl Default for BlockRing {
fn default() -> Self {
Self::new()
}
}
impl BlockRing {
pub const fn new() -> Self {
Self {
blocks: [const { AtomicU64::new(0) }; BLOCK_RING],
cycles: [const { AtomicU64::new(0) }; BLOCK_RING],
head: AtomicU64::new(0),
tail: AtomicU64::new(0),
overflow: AtomicU64::new(0),
}
}
/// The producer's: keep a sample of `block` standing for `cycles`.
pub fn push(&self, block: u64, cycles: u64) {
let head = self.head.load(Ordering::Relaxed);
let tail = self.tail.load(Ordering::Acquire);
if head.wrapping_sub(tail) >= BLOCK_RING as u64 {
self.overflow.fetch_add(cycles, Ordering::Relaxed);
return;
}
let slot = head as usize % BLOCK_RING;
self.blocks[slot].store(block, Ordering::Relaxed);
self.cycles[slot].store(cycles, Ordering::Relaxed);
self.head.store(head.wrapping_add(1), Ordering::Release);
}
/// The consumer's: move the oldest samples into `into`, as many as fit,
/// the overflow's cycles last as one sample of [`NO_BLOCK`]; how many.
pub fn take(&self, into: &mut [BlockSample]) -> usize {
let head = self.head.load(Ordering::Acquire);
let tail = self.tail.load(Ordering::Relaxed);
let count = (head.wrapping_sub(tail) as usize).min(into.len());
for (index, sample) in into[..count].iter_mut().enumerate() {
let slot = tail.wrapping_add(index as u64) as usize % BLOCK_RING;
*sample = BlockSample {
block: self.blocks[slot].load(Ordering::Relaxed),
cycles: self.cycles[slot].load(Ordering::Relaxed),
};
}
self.tail
.store(tail.wrapping_add(count as u64), Ordering::Release);
// A locked swap only when there is an overflow to take: the engine
// takes after every native run.
if count < into.len() && self.overflow.load(Ordering::Relaxed) != 0 {
let cycles = self.overflow.swap(0, Ordering::Relaxed);
if cycles != 0 {
into[count] = BlockSample {
block: NO_BLOCK,
cycles,
};
return count + 1;
}
}
count
}
}
#[cfg(test)]
mod tests {
use super::*;
fn taken(ring: &BlockRing, room: usize) -> Vec<(u64, u64)> {
let mut into = vec![BlockSample::default(); room];
let count = ring.take(&mut into);
into[..count]
.iter()
.map(|sample| (sample.block, sample.cycles))
.collect()
}
#[test]
fn samples_come_out_in_order_and_once() {
let ring = BlockRing::new();
assert!(taken(&ring, 4).is_empty());
ring.push(3, 100);
ring.push(1 << 40 | 7, 200);
assert_eq!(taken(&ring, 4), [(3, 100), (1 << 40 | 7, 200)]);
assert!(taken(&ring, 4).is_empty());
// A take with less room leaves the rest for the next.
for index in 0..5 {
ring.push(index, 1);
}
assert_eq!(taken(&ring, 2), [(0, 1), (1, 1)]);
assert_eq!(taken(&ring, 8), [(2, 1), (3, 1), (4, 1)]);
}
#[test]
fn a_full_ring_keeps_the_cycles_as_no_block() {
let ring = BlockRing::new();
for index in 0..BLOCK_RING as u64 + 3 {
ring.push(index, 10);
}
let all = taken(&ring, 2 * BLOCK_RING);
assert_eq!(all.len(), BLOCK_RING + 1);
assert_eq!(all[0], (0, 10));
assert_eq!(all[BLOCK_RING - 1], (BLOCK_RING as u64 - 1, 10));
assert_eq!(all[BLOCK_RING], (NO_BLOCK, 30), "three samples overflowed");
assert!(taken(&ring, 4).is_empty());
// The overflow waits for room in a take.
for index in 0..BLOCK_RING as u64 + 1 {
ring.push(index, 1);
}
assert_eq!(taken(&ring, BLOCK_RING).len(), BLOCK_RING);
assert_eq!(taken(&ring, 4), [(NO_BLOCK, 1)]);
// The ring wraps.
for round in 0..3 * BLOCK_RING as u64 {
ring.push(round, round);
assert_eq!(taken(&ring, 1), [(round, round)]);
}
}
/// A push between a take's reads and its move of `tail`, as an NMI's
/// would be, neither overwrites what the take read nor is lost.
#[test]
fn a_push_during_a_take_is_kept() {
let ring = BlockRing::new();
for index in 0..BLOCK_RING as u64 - 1 {
ring.push(index, 1);
}
// One slot is free: the interrupting push takes it.
let head = ring.head.load(Ordering::Acquire);
ring.push(99, 5);
// The take saw `head` before the push: it moves `tail` to it.
ring.tail.store(head, Ordering::Release);
assert_eq!(taken(&ring, 4), [(99, 5)]);
}
}
@@ -0,0 +1,622 @@
//! `--host-check --bluetooth-check`'s lines: one `CHECK` line for each step
//! of a Realtek USB Bluetooth controller's bring-up as the host check's
//! probe ran it (`stela_drivers::usb::bluetooth::realtek`), one for the
//! passive LE scan after it, and a summary. The readings are named as
//! btrtl's kernel log names them (`examining hci_ver=… hci_rev=… lmp_ver=…
//! lmp_subver=…`, `rom_version`, `key id`, `fw version 0x…`).
//!
//! No address is printed whole: the controller's as [`masked::Mac`], its
//! vendor half and last byte, and a driver error without the bytes it
//! carries, which can hold one. Every line also passes
//! [`masked::mask_line`]. Nothing here touches hardware.
//!
//! [`BluetoothOnly`] is the firmware such a probe gives its drivers.
use alloc::{
format,
string::{String, ToString},
vec::Vec,
};
use core::fmt;
use stela_contracts::masked;
use stela_drivers::{
firmware::{self, Image, Provider, Requirement},
usb::bluetooth::{
InitializationError, InitializationReport, Setup,
realtek::{
self, Attempt, ConfigurationEvidence, ContainerVersion, FirmwareDrop, Identity,
LocalVersion, OwnedReport, Project, ScanReport,
},
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
Pass,
Fail,
Skip,
}
/// One `CHECK name verdict detail` line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Line {
pub name: &'static str,
pub verdict: Verdict,
pub detail: String,
}
/// A USB Bluetooth controller as the probe kept it.
pub struct Controller<'a> {
pub location: &'a str,
pub vendor: u16,
pub product: u16,
pub revision: u16,
pub initialization: Option<Result<&'a InitializationReport, &'a InitializationError>>,
}
/// The step names, in order; the summary is `bluetooth`.
pub const STEPS: [&str; 6] = [
"bluetooth-found",
"bluetooth-rom",
"bluetooth-firmware",
"bluetooth-download",
"bluetooth-version",
"bluetooth-scan",
];
/// The controller the check takes among `controllers`: the first whose
/// IDs a Realtek setup takes.
pub fn chosen(controllers: &[Controller<'_>]) -> Option<usize> {
controllers.iter().position(|controller| {
Setup::of(controller.vendor, controller.product, false) == Some(Setup::Realtek)
})
}
/// Whether the chosen controller came up, so the scan may run on it.
pub fn scannable(controller: &Controller<'_>) -> bool {
matches!(
controller.initialization,
Some(Ok(InitializationReport::Realtek(_)))
)
}
/// The check's lines for the controllers the probe kept, with the chosen
/// one's scan, `None` where none ran.
pub fn lines(
controllers: &[Controller<'_>],
scan: Option<&realtek::Result<ScanReport>>,
) -> Vec<Line> {
let mut lines = Vec::with_capacity(STEPS.len() + 1);
let mut add = |name, verdict, detail: String| {
lines.push(Line {
name,
verdict,
detail: masked::mask_line(&detail).into_owned(),
})
};
let Some(index) = chosen(controllers) else {
let found: Vec<String> = controllers
.iter()
.map(|c| format!("{:04x}:{:04x} at {}", c.vendor, c.product, c.location))
.collect();
add(
STEPS[0],
Verdict::Fail,
format!(
"no USB Bluetooth controller a Realtek setup takes; found {}",
if found.is_empty() {
String::from("none")
} else {
found.join(", ")
}
),
);
for name in &STEPS[1..] {
add(name, Verdict::Skip, String::from("no Realtek controller"));
}
add(
"bluetooth",
Verdict::Fail,
String::from("failed at bluetooth-found"),
);
return lines;
};
let controller = &controllers[index];
add(
STEPS[0],
Verdict::Pass,
format!(
"{:04x}:{:04x} revision {:04x} at {}: Realtek setup",
controller.vendor, controller.product, controller.revision, controller.location
),
);
let steps = match controller.initialization {
None => failed_before(String::from("the probe ran no initialization on it")),
Some(Ok(InitializationReport::Realtek(report))) => booted(report),
Some(Ok(_)) => failed_before(String::from("another vendor's setup took it")),
Some(Err(InitializationError::Realtek(error))) => attempted(error),
Some(Err(error)) => failed_before(transport_or_other(error)),
};
for (name, (verdict, detail)) in STEPS[1..5].iter().zip(steps) {
add(name, verdict, detail);
}
let scan = match scan {
None => (
Verdict::Skip,
String::from("the controller did not come up, so it was not scanned"),
),
Some(Ok(report)) => scanned(report),
Some(Err(error)) => (Verdict::Fail, format!("the scan failed: {}", cause(error))),
};
add(STEPS[5], scan.0, scan.1);
let failed = lines
.iter()
.find(|line| line.verdict != Verdict::Pass)
.map(|line| line.name);
let summary = match failed {
None => (
Verdict::Pass,
format!(
"{:04x}:{:04x} runs its patch and its radio hears advertisers",
controller.vendor, controller.product
),
),
Some(name) => (Verdict::Fail, format!("failed at {name}")),
};
lines.push(Line {
name: "bluetooth",
verdict: summary.0,
detail: summary.1,
});
lines
}
/// The check's lines when nothing was started at all
/// (`bluetooth_target::choose` refused), for `why`.
pub fn refused(why: &str) -> Vec<Line> {
found_failed(why, "nothing was started")
}
/// The check's lines when the chosen xHCI's start failed, for `why`: it
/// may have been reset by then, so the later steps are skipped as never
/// reached, not as never started.
pub fn not_started(why: &str) -> Vec<Line> {
found_failed(
why,
"its xHCI did not start, so no Bluetooth controller was reached",
)
}
/// `bluetooth-found` failed for `why`, every later step skipped for
/// `skipped`.
fn found_failed(why: &str, skipped: &str) -> Vec<Line> {
let mut lines = Vec::with_capacity(STEPS.len() + 1);
lines.push(Line {
name: STEPS[0],
verdict: Verdict::Fail,
detail: masked::mask_line(why).into_owned(),
});
for name in &STEPS[1..] {
lines.push(Line {
name,
verdict: Verdict::Skip,
detail: String::from(skipped),
});
}
lines.push(Line {
name: "bluetooth",
verdict: Verdict::Fail,
detail: String::from("failed at bluetooth-found"),
});
lines
}
type Step = (Verdict, String);
/// The four bring-up steps of a controller whose initialization never
/// began Realtek's: the first fails for `why`, the rest are skipped.
fn failed_before(why: String) -> [Step; 4] {
[
(Verdict::Fail, why),
(
Verdict::Skip,
String::from("the controller was not identified"),
),
(Verdict::Skip, String::from("no image was staged")),
(Verdict::Skip, String::from("no image was downloaded")),
]
}
fn booted(report: &OwnedReport) -> [Step; 4] {
[
(
Verdict::Pass,
identity(&report.before, report.dropped.as_deref()),
),
(
Verdict::Pass,
image(
&report.firmware,
report.fallback.as_deref(),
Some(&report.container_version),
&match &report.configuration {
ConfigurationEvidence::Supplied(config) => receipt(config),
ConfigurationEvidence::OptionalMissing(_) => {
String::from("no config (optional, missing)")
}
},
),
),
(Verdict::Pass, download(&report.download)),
(
Verdict::Pass,
format!(
"{}; address {}",
after(&report.after),
masked::Mac(&display_order(&report.address))
),
),
]
}
fn attempted(error: &realtek::Error) -> [Step; 4] {
let why = cause(error);
let Some(attempt) = observation(error) else {
return failed_before(why);
};
let identified = match (&attempt.identity, &attempt.version) {
(Some(identity), _) => (
Verdict::Pass,
self::identity(identity, attempt.dropped.as_ref()),
),
(None, Some(version)) => (
Verdict::Fail,
format!("{}: {why}", readings(attempt, version)),
),
(None, None) => (Verdict::Fail, why.clone()),
};
if attempt.identity.is_none() {
let mut steps = failed_before(String::new());
steps[0] = identified;
return steps;
}
let config = match &attempt.configuration {
Some(Ok(config)) => receipt(config),
Some(Err(error)) => format!("config {}", resource(error)),
None => String::from("no config asked"),
};
let staged = attempt.container_version.is_some();
let firmware = match (&attempt.firmware, staged) {
(Some(firmware), true) => (
Verdict::Pass,
image(
firmware,
attempt.fallback.as_ref(),
attempt.container_version.as_ref(),
&config,
),
),
(Some(firmware), false) => (
Verdict::Fail,
format!(
"{}: {why}",
image(firmware, attempt.fallback.as_ref(), None, &config)
),
),
(None, _) => (
Verdict::Fail,
match &attempt.fallback {
Some(first) => format!("{why} ({} first); {config}", resource(first)),
None => format!("{why}; {config}"),
},
),
};
let downloaded = attempt.after.is_some();
let download_step = match (staged, downloaded) {
(false, _) => (Verdict::Skip, String::from("no image was staged")),
(true, true) => (Verdict::Pass, self::download(&attempt.download)),
(true, false) => (
Verdict::Fail,
format!("{}: {why}", self::download(&attempt.download)),
),
};
let version = match &attempt.after {
Some(version) => (Verdict::Fail, format!("{}: {why}", after(version))),
None => (Verdict::Skip, String::from("no image was downloaded")),
};
[identified, firmware, download_step, version]
}
/// The partial observations a failed initialization kept.
fn observation(error: &realtek::Error) -> Option<&Attempt> {
match error {
realtek::Error::Attempt { observation, .. } => Some(observation),
realtek::Error::Cleanup { cause, .. } => observation(cause),
_ => None,
}
}
fn project(project: Project) -> &'static str {
match project {
Project::Rtl8761Bu => "RTL8761BU",
Project::Rtl8822B => "RTL8822B",
Project::Rtl8852Bu => "RTL8852BU",
Project::Rtl8852Cu => "RTL8852CU",
}
}
/// btrtl's `examining` line's readings.
fn examining(version: &LocalVersion) -> String {
format!(
"hci_ver={:02x} hci_rev={:04x} lmp_ver={:02x} lmp_subver={:04x} manufacturer={:04x}",
version.hci_version(),
version.hci_revision(),
version.lmp_version(),
version.lmp_subversion(),
version.manufacturer()
)
}
fn register(subversion: u16, revision: Option<u16>) -> String {
match revision {
Some(revision) => format!("register={subversion:04x}/{revision:04x}"),
None => format!("register={subversion:04x}"),
}
}
fn dropped(drop: &FirmwareDrop) -> String {
format!(
"; a running patch was dropped first with 0xfc66 (it read {}, {}; {} events in the \
200 ms after)",
examining(&drop.version),
register(drop.register_subversion, drop.register_revision),
drop.event_count
)
}
fn identity(identity: &Identity, drop: Option<&FirmwareDrop>) -> String {
format!(
"{} stock ROM: {} {} rom_version={:x} key_id={} (security {:02x}-{:02x}){}",
project(identity.project),
examining(&identity.version),
register(identity.register_subversion, identity.register_revision),
identity.rom_version,
identity.security[0],
identity.security[0],
identity.security[1],
drop.map(dropped).unwrap_or_default()
)
}
/// The readings of a controller that was not identified, with its ROM
/// version and key id when it was read so far.
fn readings(attempt: &Attempt, version: &LocalVersion) -> String {
let mut text = examining(version);
if let Some(subversion) = attempt.register_subversion {
text.push(' ');
text.push_str(&register(subversion, attempt.register_revision));
}
if let Some(rom) = attempt.rom_version {
text.push_str(&format!(" rom_version={rom:x}"));
}
if let Some([key, second]) = attempt.security {
text.push_str(&format!(" key_id={key} (security {key:02x}-{second:02x})"));
}
if let Some(drop) = &attempt.dropped {
text.push_str(&dropped(drop));
}
text
}
fn short(sha256: &[u8; 32]) -> String {
sha256[..8]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn receipt(receipt: &stela_drivers::usb::bluetooth::FirmwareReceipt) -> String {
let member = if receipt.member == receipt.name {
String::new()
} else {
format!(" ({})", receipt.member)
};
format!("config {} {} bytes{member}", receipt.name, receipt.length)
}
fn image(
firmware: &stela_drivers::usb::bluetooth::FirmwareReceipt,
fallback: Option<&firmware::Error>,
container: Option<&ContainerVersion>,
config: &str,
) -> String {
let container = match container {
Some(ContainerVersion::V2(version)) => format!(
" EPATCH v2 {}",
version
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>()
),
Some(ContainerVersion::V1(version)) => format!(" EPATCH v1 {version:#010x}"),
None => String::new(),
};
let fallback = fallback
.map(|first| format!(" (after {})", resource(first)))
.unwrap_or_default();
format!(
"{} {} bytes sha256 {}…{container}{fallback}; {config}",
firmware.name,
firmware.length,
short(&firmware.sha256)
)
}
fn download(download: &[realtek::DownloadResponse]) -> String {
match download.last() {
Some(last) => format!(
"{} fragments acknowledged, the last sent as index {:#04x}",
download.len(),
last.sent_index
),
None => String::from("no fragment acknowledged"),
}
}
/// The post-patch Read Local Version, with btrtl's `fw version` line.
fn after(version: &LocalVersion) -> String {
format!(
"fw version 0x{:04x}{:04x}: {}",
version.hci_revision(),
version.lmp_subversion(),
examining(version)
)
}
/// Read BD_ADDR's bytes, least significant first, in the order an address
/// is written.
fn display_order(address: &[u8; 6]) -> [u8; 6] {
let mut shown = *address;
shown.reverse();
shown
}
fn scanned(report: &ScanReport) -> Step {
let seconds = report.window_us / 1_000_000;
let mut extra = String::new();
if report.saturated {
extra.push_str(&format!(
", more than {} advertisers",
realtek::MAX_ADVERTISERS
));
}
if report.malformed > 0 {
extra.push_str(&format!(
", {} reports dropped as Linux drops them",
report.malformed
));
}
if report.other_events > 0 {
extra.push_str(&format!(", {} other events", report.other_events));
}
match (report.devices, report.best_rssi) {
(0, _) => (
Verdict::Fail,
format!(
"passive LE scan for {seconds} s heard no advertiser ({} reports{extra}): \
nothing advertised nearby, or the radio hears nothing (Wi-Fi may hold the \
shared antenna)",
report.reports
),
),
(devices, rssi) => (
Verdict::Pass,
format!(
"passive LE scan for {seconds} s: {devices} advertisers in {} reports, best \
RSSI {}{extra}",
report.reports,
rssi.map_or_else(
|| String::from("not reported"),
|rssi| format!("{rssi} dBm")
)
),
),
}
}
/// A driver error in words, without the bytes it carries: a response's
/// can be the controller's address.
fn cause(error: &realtek::Error) -> String {
use realtek::Error;
match error {
Error::Attempt { cause: inner, .. } => cause(inner),
Error::Cleanup {
cause: inner,
cleanup,
} => format!(
"{}; closing the transport failed too: {}",
cause(inner),
transport(cleanup)
),
Error::Unsupported(why) => why.to_string(),
Error::Protocol {
requirement,
observed,
} => format!("{requirement} ({} bytes)", observed.len()),
Error::Format(format) => format!("firmware format {format:?}"),
Error::Resource(error) => resource(error),
Error::Controller { opcode, status, .. } => {
format!("command {opcode:#06x} answered status {status:#04x}")
}
Error::Timeout(what) => format!("timed out waiting for {what}"),
Error::Transport(error) => transport(error),
}
}
/// A firmware request's failure: its name, unquoted, and why.
fn resource(error: &firmware::Error) -> String {
format!(
"{} {}",
error.name.as_str().unwrap_or("(unnamed)"),
error.kind
)
}
fn transport(error: &stela_drivers::usb::bluetooth::Error) -> String {
use stela_drivers::usb::bluetooth::ErrorKind;
let kind = match &error.kind {
ErrorKind::Usb(error) => format!("USB {error}"),
ErrorKind::InvalidPacket(why) => format!("invalid packet: {why}"),
ErrorKind::TooLarge { maximum, actual } => {
format!("packet of {actual} bytes, past {maximum}")
}
ErrorKind::PartialTimeout(pipe) => format!("partial {pipe:?} frame timed out"),
ErrorKind::ControllerDump { driver, .. } => format!("controller dump ({driver})"),
ErrorKind::Closed => String::from("transport closed"),
ErrorKind::Failed => String::from("transport failed"),
};
match &error.cleanup {
Some(cleanup) => format!("{kind}; cancellation failed: {cleanup}"),
None => kind,
}
}
fn transport_or_other(error: &InitializationError) -> String {
match error {
InitializationError::Transport(error) => transport(error),
InitializationError::UnsupportedDevice { .. } => error.to_string(),
_ => String::from("another vendor's setup failed on it"),
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Pass => "PASS",
Self::Fail => "FAIL",
Self::Skip => "SKIP",
})
}
}
/// The firmware a `--bluetooth-check` probe gives its drivers: a USB
/// Bluetooth initializer's request (its target's driver names
/// `-bluetooth-usb-`) goes to `bluetooth`, the stick's verified bundle, any
/// other to `rest`, so every other device starts as a plain host check
/// starts it.
pub struct BluetoothOnly<'a> {
pub bluetooth: &'a dyn Provider,
pub rest: &'a dyn Provider,
}
impl Provider for BluetoothOnly<'_> {
fn load(&self, requirement: Requirement<'_>) -> Result<Image<'_>, firmware::Error> {
if requirement.target.driver.contains("-bluetooth-usb-") {
self.bluetooth.load(requirement)
} else {
self.rest.load(requirement)
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,575 @@
use super::*;
use alloc::{boxed::Box, string::ToString, vec, vec::Vec};
use stela_crypto::{Sha256, digest::Digest};
use stela_drivers::{
firmware::{Catalog, ErrorKind, Provenance, Resource, Target},
usb::bluetooth::{
FirmwareReceipt,
realtek::{DownloadResponse, Error, UsbIdentity},
},
};
/// The controller's BD_ADDR as Read BD_ADDR returns it, least significant
/// byte first: f6:e5:d4:c3:b2:a1 as written.
const ADDRESS: [u8; 6] = [0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6];
const AT: &str = "xhci 0000:05:00.4 port 2.3";
fn stock() -> LocalVersion {
LocalVersion {
raw: [0, 0x0c, 0x0c, 0, 0x0c, 0x5d, 0, 0x52, 0x88],
}
}
/// The readings of a running patch: lmp_subver 0x0d7b.
fn patched() -> LocalVersion {
LocalVersion {
raw: [0, 0x0c, 0x0c, 0, 0x0c, 0x5d, 0, 0x7b, 0x0d],
}
}
fn identity() -> Identity {
Identity {
usb: UsbIdentity {
vendor: 0x13d3,
product: 0x3612,
revision: 0,
},
version: stock(),
register_subversion: 0x8852,
register_revision: None,
rom_version: 0,
security: [0, 0],
project: Project::Rtl8852Cu,
}
}
fn receipt(name: &str, length: usize, member: &str) -> FirmwareReceipt {
FirmwareReceipt {
name: name.into(),
length,
sha256: [0x11; 32],
source: "https://gitlab.com/kernel-firmware/linux-firmware".into(),
revision: "59f9fc2ef8d1e312d2a613d4e1ffad2ff31a0a01".into(),
member: member.into(),
license: "LICENSES/LICENCE.rtlwifi_firmware.txt".into(),
target_driver: "realtek-bluetooth-usb-epatch-v2".into(),
target_hardware: "usb:13d3:3612:0000".into(),
target_revision: identity().revision_label(),
target_board: None,
}
}
fn config() -> FirmwareReceipt {
receipt(
"rtl_bt/rtl8852cu_config.bin",
6,
"rtl_bt/rtl8761bu_config.bin",
)
}
fn missing(name: &str) -> firmware::Error {
firmware::Error {
name: name.into(),
kind: ErrorKind::Missing,
}
}
fn download() -> Vec<DownloadResponse> {
[0, 1, 0x82]
.into_iter()
.map(|sent_index| DownloadResponse {
sent_index,
returned_index: sent_index,
})
.collect()
}
fn report() -> OwnedReport {
OwnedReport {
dropped: None,
before: identity(),
after: patched(),
address: ADDRESS,
fallback: None,
firmware: Box::new(receipt(
"rtl_bt/rtl8852cu_fw_v2.bin",
112953,
"rtl_bt/rtl8852cu_fw_v2.bin",
)),
configuration: ConfigurationEvidence::Supplied(config()),
container_version: ContainerVersion::V2([0x6e, 0xb1, 0x34, 1, 0x49, 0x8c, 1, 0]),
v2: None,
download: download(),
credits: 1,
}
}
fn heard(devices: usize) -> ScanReport {
ScanReport {
reports: 340,
devices,
saturated: false,
best_rssi: Some(-48),
malformed: 0,
other_events: 0,
window_us: 8_000_000,
}
}
fn controller<'a>(
initialization: Option<Result<&'a InitializationReport, &'a InitializationError>>,
) -> Controller<'a> {
Controller {
location: AT,
vendor: 0x13d3,
product: 0x3612,
revision: 0,
initialization,
}
}
fn text(lines: &[Line]) -> Vec<(&'static str, Verdict, &str)> {
lines
.iter()
.map(|line| (line.name, line.verdict, line.detail.as_str()))
.collect()
}
#[test]
fn a_booted_rtl8852cu_that_hears_advertisers_passes_every_step() {
let booted = InitializationReport::Realtek(report());
let got = lines(&[controller(Some(Ok(&booted)))], Some(&Ok(heard(12))));
assert_eq!(
text(&got),
[
(
"bluetooth-found",
Verdict::Pass,
"13d3:3612 revision 0000 at xhci 0000:05:00.4 port 2.3: Realtek setup"
),
(
"bluetooth-rom",
Verdict::Pass,
"RTL8852CU stock ROM: hci_ver=0c hci_rev=000c lmp_ver=0c lmp_subver=8852 \
manufacturer=005d register=8852 rom_version=0 key_id=0 (security 00-00)"
),
(
"bluetooth-firmware",
Verdict::Pass,
"rtl_bt/rtl8852cu_fw_v2.bin 112953 bytes sha256 1111111111111111… EPATCH v2 \
6eb13401498c0100; config rtl_bt/rtl8852cu_config.bin 6 bytes \
(rtl_bt/rtl8761bu_config.bin)"
),
(
"bluetooth-download",
Verdict::Pass,
"3 fragments acknowledged, the last sent as index 0x82"
),
(
"bluetooth-version",
Verdict::Pass,
"fw version 0x000c0d7b: hci_ver=0c hci_rev=000c lmp_ver=0c lmp_subver=0d7b \
manufacturer=005d; address f6:e5:d4:..:..:a1"
),
(
"bluetooth-scan",
Verdict::Pass,
"passive LE scan for 8 s: 12 advertisers in 340 reports, best RSSI -48 dBm"
),
(
"bluetooth",
Verdict::Pass,
"13d3:3612 runs its patch and its radio hears advertisers"
),
]
);
assert_eq!(
got.iter().map(|line| line.name).collect::<Vec<_>>()[..6],
STEPS
);
}
#[test]
fn a_dropped_patch_and_a_v1_fallback_are_named_where_they_happened() {
let mut booted = report();
booted.dropped = Some(Box::new(FirmwareDrop {
register_subversion: 0x8852,
register_revision: None,
version: patched(),
events: vec![vec![0x0e, 4, 0, 0x66, 0xfc, 0]],
event_count: 1,
}));
booted.fallback = Some(Box::new(missing("rtl_bt/rtl8852cu_fw_v2.bin")));
booted.firmware = Box::new(receipt(
"rtl_bt/rtl8852cu_fw.bin",
113336,
"rtl_bt/rtl8852cu_fw.bin",
));
booted.container_version = ContainerVersion::V1(0xd7b8_fabf);
let booted = InitializationReport::Realtek(booted);
let got = lines(&[controller(Some(Ok(&booted)))], Some(&Ok(heard(3))));
assert!(got[1].detail.ends_with(
"; a running patch was dropped first with 0xfc66 (it read hci_ver=0c hci_rev=000c \
lmp_ver=0c lmp_subver=0d7b manufacturer=005d, register=8852; 1 events in the 200 ms \
after)"
));
assert!(
got[2]
.detail
.starts_with("rtl_bt/rtl8852cu_fw.bin 113336 bytes sha256 1111111111111111… EPATCH v1 0xd7b8fabf (after rtl_bt/rtl8852cu_fw_v2.bin not supplied);"),
"{}",
got[2].detail
);
assert!(got.iter().all(|line| line.verdict == Verdict::Pass));
}
#[test]
fn a_failed_attempt_passes_what_it_reached_and_fails_where_it_stopped() {
// Both images missing: identified, no image staged.
let attempt = Attempt {
version: Some(stock()),
register_subversion: Some(0x8852),
rom_version: Some(0),
security: Some([0, 0]),
identity: Some(identity()),
fallback: Some(missing("rtl_bt/rtl8852cu_fw_v2.bin")),
configuration: Some(Ok(config())),
..Attempt::default()
};
let failed = InitializationError::Realtek(Error::Attempt {
cause: Box::new(Error::Resource(missing("rtl_bt/rtl8852cu_fw.bin"))),
observation: Box::new(attempt),
});
let got = lines(&[controller(Some(Err(&failed)))], None);
assert_eq!(
text(&got)[1..],
[
(
"bluetooth-rom",
Verdict::Pass,
"RTL8852CU stock ROM: hci_ver=0c hci_rev=000c lmp_ver=0c lmp_subver=8852 \
manufacturer=005d register=8852 rom_version=0 key_id=0 (security 00-00)"
),
(
"bluetooth-firmware",
Verdict::Fail,
"rtl_bt/rtl8852cu_fw.bin not supplied (rtl_bt/rtl8852cu_fw_v2.bin not \
supplied first); config rtl_bt/rtl8852cu_config.bin 6 bytes \
(rtl_bt/rtl8761bu_config.bin)"
),
("bluetooth-download", Verdict::Skip, "no image was staged"),
(
"bluetooth-version",
Verdict::Skip,
"no image was downloaded"
),
(
"bluetooth-scan",
Verdict::Skip,
"the controller did not come up, so it was not scanned"
),
("bluetooth", Verdict::Fail, "failed at bluetooth-firmware"),
]
);
// Readings no btrtl IC matches, even after the drop: the ROM step
// fails with both readings, and nothing after it runs.
let unknown = Attempt {
dropped: Some(FirmwareDrop {
register_subversion: 0x8852,
register_revision: None,
version: patched(),
events: Vec::new(),
event_count: 0,
}),
version: Some(patched()),
register_subversion: Some(0x8852),
..Attempt::default()
};
let failed = InitializationError::Realtek(Error::Attempt {
cause: Box::new(Error::Unsupported(
"readings match no btrtl IC, also after its running patch was dropped",
)),
observation: Box::new(unknown),
});
let got = lines(&[controller(Some(Err(&failed)))], None);
assert_eq!(got[1].verdict, Verdict::Fail);
assert!(got[1].detail.starts_with(
"hci_ver=0c hci_rev=000c lmp_ver=0c lmp_subver=0d7b manufacturer=005d register=8852; a \
running patch was dropped first"
));
assert!(
got[1]
.detail
.ends_with(": readings match no btrtl IC, also after its running patch was dropped")
);
assert!(got[2..6].iter().all(|line| line.verdict == Verdict::Skip));
}
#[test]
fn no_address_is_printed_whole_in_any_line() {
let booted = InitializationReport::Realtek(report());
let mut all = lines(&[controller(Some(Ok(&booted)))], Some(&Ok(heard(1))));
// A refused address after the upload: its response holds the address.
let attempt = Attempt {
version: Some(stock()),
register_subversion: Some(0x8852),
rom_version: Some(0),
security: Some([0, 0]),
identity: Some(identity()),
firmware: Some(receipt(
"rtl_bt/rtl8852cu_fw_v2.bin",
112953,
"rtl_bt/rtl8852cu_fw_v2.bin",
)),
configuration: Some(Ok(config())),
container_version: Some(ContainerVersion::V2([0; 8])),
download: download(),
after: Some(patched()),
..Attempt::default()
};
let mut observed = vec![0];
observed.extend_from_slice(&ADDRESS);
let refused = InitializationError::Realtek(Error::Attempt {
cause: Box::new(Error::Protocol {
requirement: "invalid controller address",
observed,
}),
observation: Box::new(attempt),
});
let failed = lines(&[controller(Some(Err(&refused)))], None);
assert_eq!(failed[4].verdict, Verdict::Fail);
assert!(
failed[4]
.detail
.ends_with(": invalid controller address (7 bytes)"),
"{}",
failed[4].detail
);
all.extend(failed);
let text: String = all
.iter()
.map(|line| line.detail.to_ascii_lowercase())
.collect::<Vec<_>>()
.join("\n");
assert!(text.contains("address f6:e5:d4:..:..:a1"));
// The hidden middle bytes, c3 and b2, in no rendering.
for shown in [
"c3:b2", "b2:c3", "c3b2", "b2c3", "c3-b2", "b2-c3", "0xc3", "0xb2", "195, 178", "178, 195",
"d4:c3", "b2:a1",
] {
assert!(!text.contains(shown), "{shown} in {text}");
}
}
#[test]
fn no_realtek_controller_fails_the_check_naming_what_was_found() {
let lines_of = |controllers: &[Controller<'_>]| lines(controllers, None);
let none = lines_of(&[]);
assert_eq!(
text(&none)[0],
(
"bluetooth-found",
Verdict::Fail,
"no USB Bluetooth controller a Realtek setup takes; found none"
)
);
let mediatek = Controller {
location: "xhci 0000:00:14.0 port 10",
vendor: 0x0e8d,
product: 0x7922,
revision: 0x100,
initialization: None,
};
let other = lines_of(&[mediatek]);
assert_eq!(
other[0].detail,
"no USB Bluetooth controller a Realtek setup takes; found 0e8d:7922 at xhci \
0000:00:14.0 port 10"
);
for got in [none, other] {
assert!(got[1..6].iter().all(|line| line.verdict == Verdict::Skip));
assert_eq!(
text(&got)[6],
("bluetooth", Verdict::Fail, "failed at bluetooth-found")
);
}
}
#[test]
fn a_scan_that_hears_nothing_fails_the_check() {
let booted = InitializationReport::Realtek(report());
let got = lines(&[controller(Some(Ok(&booted)))], Some(&Ok(heard(0))));
assert_eq!(got[5].verdict, Verdict::Fail);
assert!(got[5].detail.starts_with(
"passive LE scan for 8 s heard no advertiser (340 reports): nothing advertised nearby"
));
assert_eq!(got[6].detail, "failed at bluetooth-scan");
let refused = Error::Controller {
opcode: 0x200b,
status: 0x0c,
parameters: vec![0x0c],
};
let got = lines(&[controller(Some(Ok(&booted)))], Some(&Err(refused)));
assert_eq!(
text(&got)[5],
(
"bluetooth-scan",
Verdict::Fail,
"the scan failed: command 0x200b answered status 0x0c"
)
);
}
#[test]
fn the_check_takes_the_first_realtek_controller_and_scans_only_a_booted_one() {
let booted = InitializationReport::Realtek(report());
let failed = InitializationError::Realtek(Error::Unsupported("USB identity"));
let mediatek = Controller {
location: "xhci 0000:00:14.0 port 10",
vendor: 0x0e8d,
product: 0x7922,
revision: 0x100,
initialization: None,
};
let controllers = [mediatek, controller(Some(Ok(&booted)))];
assert_eq!(chosen(&controllers), Some(1));
assert!(scannable(&controllers[1]));
assert!(!scannable(&controller(Some(Err(&failed)))));
assert!(!scannable(&controller(None)));
assert_eq!(Verdict::Skip.to_string(), "SKIP");
}
fn catalog(name: &'static str, driver: &'static str, bytes: &[u8]) -> Catalog {
Catalog::from_handoff(vec![Resource {
name,
target: Target {
driver,
hardware: "usb:13d3:3612:0000",
revision: "r",
board: None,
},
provenance: Provenance {
source: "synthetic",
revision: "v1",
member: name,
license: "MIT",
},
expected_length: bytes.len(),
expected_sha256: Sha256::digest(bytes).into(),
bytes: bytes.to_vec(),
}])
.unwrap()
}
#[test]
fn only_usb_bluetooth_requests_reach_the_bundle() {
let bundle = catalog("bt.bin", "realtek-bluetooth-usb-epatch-v2", b"bt");
let rest = catalog("nic.bin", "realtek", b"nic");
let provider = BluetoothOnly {
bluetooth: &bundle,
rest: &rest,
};
let request = |name, driver| Requirement {
name,
target: Target {
driver,
hardware: "usb:13d3:3612:0000",
revision: "r",
board: None,
},
minimum_bytes: 1,
};
assert_eq!(
provider
.load(request("bt.bin", "realtek-bluetooth-usb-epatch-v2"))
.unwrap()
.bytes(),
b"bt"
);
assert_eq!(
provider
.load(request("nic.bin", "realtek"))
.unwrap()
.bytes(),
b"nic"
);
// Neither is asked for the other's files.
assert_eq!(
provider
.load(request("nic.bin", "realtek-bluetooth-usb-epatch-v2"))
.unwrap_err()
.kind,
ErrorKind::Missing
);
assert_eq!(
provider
.load(request("bt.bin", "realtek"))
.unwrap_err()
.kind,
ErrorKind::Missing
);
}
#[test]
fn a_refused_identification_keeps_the_rom_version_and_key_id_it_read() {
// An 8852B's stock readings under an 8852CE ID: ROM and security were
// read before the profile refused them.
let refused = Attempt {
version: Some(LocalVersion {
raw: [0, 0x0b, 0x0b, 0, 0x0b, 0x5d, 0, 0x52, 0x88],
}),
register_subversion: Some(0x8852),
rom_version: Some(1),
security: Some([0, 0x5a]),
..Attempt::default()
};
let failed = InitializationError::Realtek(Error::Attempt {
cause: Box::new(Error::Unsupported(
"USB and observed stock ROM/HCI profile mismatch",
)),
observation: Box::new(refused),
});
let got = lines(&[controller(Some(Err(&failed)))], None);
assert_eq!(
text(&got)[1],
(
"bluetooth-rom",
Verdict::Fail,
"hci_ver=0b hci_rev=000b lmp_ver=0b lmp_subver=8852 manufacturer=005d register=8852 \
rom_version=1 key_id=0 (security 00-5a): USB and observed stock ROM/HCI profile \
mismatch"
)
);
}
#[test]
fn a_refused_target_fails_found_with_its_reason_and_starts_nothing_else() {
let got = refused("the firmware's USB devices could not all be read; nothing is started");
assert_eq!(
text(&got),
[
(
"bluetooth-found",
Verdict::Fail,
"the firmware's USB devices could not all be read; nothing is started"
),
("bluetooth-rom", Verdict::Skip, "nothing was started"),
("bluetooth-firmware", Verdict::Skip, "nothing was started"),
("bluetooth-download", Verdict::Skip, "nothing was started"),
("bluetooth-version", Verdict::Skip, "nothing was started"),
("bluetooth-scan", Verdict::Skip, "nothing was started"),
("bluetooth", Verdict::Fail, "failed at bluetooth-found"),
]
);
}
#[test]
fn a_failed_xhci_start_says_no_controller_was_reached_not_that_nothing_was_started() {
let why = "pci=0000:05:00.4 did not start: its xHCI driver failed: timeout; its Bus Master is \
off again";
let got = not_started(why);
assert_eq!(
text(&got),
[
("bluetooth-found", Verdict::Fail, why),
("bluetooth-rom", Verdict::Skip, NOT_REACHED),
("bluetooth-firmware", Verdict::Skip, NOT_REACHED),
("bluetooth-download", Verdict::Skip, NOT_REACHED),
("bluetooth-version", Verdict::Skip, NOT_REACHED),
("bluetooth-scan", Verdict::Skip, NOT_REACHED),
("bluetooth", Verdict::Fail, "failed at bluetooth-found"),
]
);
}
const NOT_REACHED: &str = "its xHCI did not start, so no Bluetooth controller was reached";
@@ -0,0 +1,214 @@
//! Which one PCI function `--host-check --bluetooth-check` may start: the
//! xHCI the firmware's own USB stack found a Realtek USB Bluetooth controller
//! on, read before ExitBootServices, and only when nothing on that xHCI but
//! the disk Stela started from could be a disk.
//!
//! The check runs none of the probe's drivers. It is handed one [`Target`],
//! whose [`Target::admits`] takes its controller alone: every other function
//! (the PC's NVMe and SATA disks, network and Wi-Fi cards, GPUs, USB4 hosts,
//! the other xHCIs and the bridges) gets no driver, no BAR access and no Bus
//! Master. A controller that also holds another USB disk, which its start
//! would reset, a firmware USB inventory that could not all be read, so
//! that the check cannot tell, or a second Realtek Bluetooth controller, so
//! that it cannot tell which one to start, starts nothing.
//!
//! On this PC the Bluetooth controller's xHCI (0000:05:00.4) also holds the
//! boot stick. Its start resets the controller, so the stick is enumerated
//! again; nothing writes to it, as the check's lines go to the screen and,
//! with `--keep-lines`, the firmware's variables.
use alloc::{format, string::String, vec::Vec};
use stela_drivers::{
bus::pci::Address,
usb::{bluetooth::Setup, xhci},
};
/// USB Bluetooth's interface class, subclass and protocol.
const BLUETOOTH: [u8; 3] = [0xe0, 0x01, 0x01];
/// The mass storage interface class, every disk's, UAS's too.
const MASS_STORAGE: u8 = 0x08;
/// A PCI function of the firmware's census.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PciFunction {
pub address: Address,
pub vendor: u16,
pub device: u16,
/// Base class, subclass and programming interface.
pub class: [u8; 3],
}
/// A USB interface the firmware's USB stack enumerated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UsbInterface {
/// The PCI function its device path leaves the PCI tree at.
pub controller: Address,
/// Its device path below that controller, as text.
pub path: String,
pub vendor: u16,
pub product: u16,
/// Interface class, subclass and protocol.
pub class: [u8; 3],
/// Its path leads to the disk Stela started from.
pub boot: bool,
}
/// The one function the check may start.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Target {
pub controller: Address,
/// Its PCI IDs, checked again before it is started.
pub vendor: u16,
pub device: u16,
/// The Bluetooth interface found on it.
pub bluetooth: UsbInterface,
/// The boot stick's path, when it is on this controller too.
pub stick: Option<String>,
/// The USB interfaces on it the firmware found.
pub interfaces: usize,
}
impl Target {
/// Whether the check may touch the PCI function at `address`: only its
/// one controller.
pub fn admits(&self, address: Address) -> bool {
address == self.controller
}
/// The line said before the firmware exits.
pub fn line(&self) -> String {
let stick = match &self.stick {
Some(path) => format!(
", and the boot stick at {path}, which its start resets and enumerates again"
),
None => String::from("; the boot stick is on another controller"),
};
format!(
"BLUETOOTH CHECK starts pci={} ({:04x}:{:04x}, xHCI) alone: it holds {:04x}:{:04x} at {} \
among {} USB interfaces{stick}; no other PCI function is touched, and nothing writes \
to the stick",
self.controller,
self.vendor,
self.device,
self.bluetooth.vendor,
self.bluetooth.product,
self.bluetooth.path,
self.interfaces
)
}
}
/// The function to start among `functions`, the firmware's PCI census, from
/// `usb`, the firmware's USB interfaces, or what of them could not be read;
/// or why nothing is started.
pub fn choose(
functions: &[PciFunction],
usb: Result<&[UsbInterface], &str>,
) -> Result<Target, String> {
let refuse = |why: String| Err(format!("{why}; nothing is started"));
let usb = match usb {
Ok(usb) => usb,
Err(unread) => {
return refuse(format!(
"the firmware's USB devices could not all be read ({unread}), so the check cannot \
tell what else the Bluetooth controller's xHCI holds"
));
}
};
// One entry per controller: its first Bluetooth interface, as a
// controller has two or more (btusb.c takes interface 0, and 1 for SCO).
let mut controllers: Vec<&UsbInterface> = Vec::new();
for interface in usb.iter().filter(|interface| {
interface.class == BLUETOOTH
&& Setup::of(interface.vendor, interface.product, false) == Some(Setup::Realtek)
}) {
if !controllers.iter().any(|seen| same_device(seen, interface)) {
controllers.push(interface);
}
}
let bluetooth = match controllers.as_slice() {
[] => {
return refuse(format!(
"the firmware's USB stack lists no Bluetooth controller a Realtek setup takes, \
among {} USB interfaces",
usb.len()
));
}
[one] => *one,
several => {
let mut named: Vec<String> = several
.iter()
.map(|interface| {
format!(
"{:04x}:{:04x} at pci={} {}",
interface.vendor, interface.product, interface.controller, interface.path
)
})
.collect();
let last = named.pop().unwrap_or_default();
return refuse(format!(
"the firmware's USB stack lists {} Bluetooth controllers a Realtek setup takes, \
{} and {last}, so the check cannot tell which to start",
several.len(),
named.join(", ")
));
}
};
let controller = bluetooth.controller;
let Some(function) = functions
.iter()
.find(|function| function.address == controller)
else {
return refuse(format!(
"the Bluetooth controller's controller pci={controller} is not in the firmware's PCI \
census"
));
};
if function.class != xhci::CLASS {
let [base, sub, interface] = function.class;
return refuse(format!(
"the Bluetooth controller's controller pci={controller} is of class \
{base:02x}{sub:02x}{interface:02x}, not an xHCI"
));
}
let on = || {
usb.iter()
.filter(move |interface| interface.controller == controller)
};
if let Some(disk) = on().find(|interface| interface.class[0] == MASS_STORAGE && !interface.boot)
{
return refuse(format!(
"the Bluetooth controller's xHCI pci={controller} also holds the USB disk \
{:04x}:{:04x} at {}, which its start would reset",
disk.vendor, disk.product, disk.path
));
}
Ok(Target {
controller,
vendor: function.vendor,
device: function.device,
bluetooth: bluetooth.clone(),
stick: on()
.find(|interface| interface.class[0] == MASS_STORAGE && interface.boot)
.map(|stick| stick.path.clone()),
interfaces: on().count(),
})
}
/// Whether two interfaces are of one device: on one controller, at one
/// path but for the last USB node's interface number (`USB(port,interface)`).
/// A path that does not end in a USB node is its own device's alone.
fn same_device(a: &UsbInterface, b: &UsbInterface) -> bool {
a.controller == b.controller && device_path(&a.path) == device_path(&b.path)
}
/// `path` without its last USB node's interface number.
fn device_path(path: &str) -> &str {
let last = path.rsplit('/').next().unwrap_or(path);
match path.rsplit_once(',') {
Some((device, _)) if last.starts_with("USB(") && last.ends_with(')') => device,
_ => path,
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,262 @@
use super::*;
use alloc::{string::ToString, vec, vec::Vec};
fn at(text: &str) -> Address {
Address::parse(text).unwrap()
}
fn pci(address: &str, vendor: u16, device: u16, class: [u8; 3]) -> PciFunction {
PciFunction {
address: at(address),
vendor,
device,
class,
}
}
fn usb(controller: &str, path: &str, ids: (u16, u16), class: [u8; 3], boot: bool) -> UsbInterface {
UsbInterface {
controller: at(controller),
path: path.to_string(),
vendor: ids.0,
product: ids.1,
class,
boot,
}
}
const XHCI: [u8; 3] = [0x0c, 0x03, 0x30];
const BLUETOOTH: [u8; 3] = [0xe0, 0x01, 0x01];
const DISK: [u8; 3] = [0x08, 0x06, 0x50];
const STICK: (u16, u16) = (0x0781, 0x5581);
/// This laptop's PCI functions, as its firmware's census lists them, with
/// one of each kind the check must never start.
fn census() -> Vec<PciFunction> {
vec![
pci("0000:00:00.0", 0x1022, 0x14e8, [0x06, 0x00, 0x00]),
pci("0000:00:08.1", 0x1022, 0x14eb, [0x06, 0x04, 0x00]),
pci("0000:01:00.0", 0x10ec, 0xc852, [0x02, 0x80, 0x00]),
// The Windows disk.
pci("0000:02:00.0", 0x144d, 0xa80c, [0x01, 0x08, 0x02]),
pci("0000:03:00.0", 0x1022, 0x7901, [0x01, 0x06, 0x01]),
pci("0000:04:00.0", 0x10ec, 0x8168, [0x02, 0x00, 0x00]),
pci("0000:05:00.0", 0x10de, 0x28a0, [0x03, 0x00, 0x00]),
pci("0000:05:00.3", 0x1022, 0x15b6, XHCI),
pci("0000:05:00.4", 0x1022, 0x15b7, XHCI),
pci("0000:06:00.0", 0x1022, 0x1668, [0x0c, 0x03, 0x40]),
pci("0000:07:00.0", 0x1022, 0x15c0, XHCI),
]
}
/// The firmware's USB interfaces: the stick and, behind a hub, the
/// RTL8852CE's Bluetooth (two interfaces) on 05:00.4; a keyboard and another
/// disk on 05:00.3.
fn interfaces() -> Vec<UsbInterface> {
vec![
usb("0000:05:00.4", "USB(0x0,0x0)", STICK, DISK, true),
usb(
"0000:05:00.4",
"USB(0x1,0x0)",
(0x05e3, 0x0610),
[0x09, 0, 0],
false,
),
usb(
"0000:05:00.4",
"USB(0x1,0x0)/USB(0x2,0x0)",
(0x13d3, 0x3612),
BLUETOOTH,
false,
),
usb(
"0000:05:00.4",
"USB(0x1,0x0)/USB(0x2,0x1)",
(0x13d3, 0x3612),
BLUETOOTH,
false,
),
usb(
"0000:05:00.3",
"USB(0x2,0x0)",
(0x046d, 0xc31c),
[0x03, 1, 1],
false,
),
usb(
"0000:05:00.3",
"USB(0x3,0x0)",
(0x0bc2, 0x2322),
DISK,
false,
),
]
}
#[test]
fn only_the_bluetooth_controllers_xhci_is_admitted_among_every_other_function() {
let functions = census();
let usb = interfaces();
let target = choose(&functions, Ok(&usb)).unwrap();
assert_eq!(target.controller, at("0000:05:00.4"));
assert_eq!((target.vendor, target.device), (0x1022, 0x15b7));
assert_eq!(
(target.bluetooth.vendor, target.bluetooth.product),
(0x13d3, 0x3612)
);
assert_eq!(target.bluetooth.path, "USB(0x1,0x0)/USB(0x2,0x0)");
assert_eq!(target.stick.as_deref(), Some("USB(0x0,0x0)"));
assert_eq!(target.interfaces, 4);
// Default deny: of every function the census lists, the NVMe, AHCI,
// network, Wi-Fi, GPU, USB4, bridges and the other xHCIs among them,
// the target alone is admitted.
let admitted: Vec<Address> = functions
.iter()
.map(|function| function.address)
.filter(|&address| target.admits(address))
.collect();
assert_eq!(admitted, [at("0000:05:00.4")]);
assert!(!target.admits(at("0000:02:00.0")));
assert!(!target.admits(at("0000:05:00.3")));
assert_eq!(
target.line(),
"BLUETOOTH CHECK starts pci=0000:05:00.4 (1022:15b7, xHCI) alone: it holds 13d3:3612 at \
USB(0x1,0x0)/USB(0x2,0x0) among 4 USB interfaces, and the boot stick at USB(0x0,0x0), \
which its start resets and enumerates again; no other PCI function is touched, and \
nothing writes to the stick"
);
}
#[test]
fn a_controller_with_another_disk_or_an_unreadable_census_is_never_started() {
let functions = census();
// What could not be read is named.
let unread = "UsbIo handle 3 of 7 at 0000:05:00.4 USB(0x1,0x0): its interface descriptor \
(DEVICE_ERROR)";
assert_eq!(
choose(&functions, Err(unread)).unwrap_err(),
"the firmware's USB devices could not all be read (UsbIo handle 3 of 7 at 0000:05:00.4 \
USB(0x1,0x0): its interface descriptor (DEVICE_ERROR)), so the check cannot tell what \
else the Bluetooth controller's xHCI holds; nothing is started"
);
// A USB disk beside the stick on the same controller.
let mut usb = interfaces();
usb.push(usb_disk_on_target());
let other = choose(&functions, Ok(&usb)).unwrap_err();
assert_eq!(
other,
"the Bluetooth controller's xHCI pci=0000:05:00.4 also holds the USB disk 152d:0583 at \
USB(0x1,0x0)/USB(0x3,0x0), which its start would reset; nothing is started"
);
// The stick alone is no other disk, wherever it is; a disk on another
// controller is not reset.
assert!(choose(&functions, Ok(&interfaces())).is_ok());
}
fn usb_disk_on_target() -> UsbInterface {
usb(
"0000:05:00.4",
"USB(0x1,0x0)/USB(0x3,0x0)",
(0x152d, 0x0583),
[0x08, 0x06, 0x62],
false,
)
}
#[test]
fn no_realtek_bluetooth_or_a_controller_that_is_no_listed_xhci_starts_nothing() {
let functions = census();
// A MediaTek controller is not this check's.
let mediatek = vec![usb(
"0000:05:00.4",
"USB(0x2,0x0)",
(0x0e8d, 0x7922),
BLUETOOTH,
false,
)];
let none = choose(&functions, Ok(&mediatek)).unwrap_err();
assert_eq!(
none,
"the firmware's USB stack lists no Bluetooth controller a Realtek setup takes, among 1 \
USB interfaces; nothing is started"
);
// A Realtek ID on an interface of another class is no Bluetooth one.
let wrong = vec![usb(
"0000:05:00.4",
"USB(0x2,0x0)",
(0x13d3, 0x3612),
[0xff, 0, 0],
false,
)];
assert!(choose(&functions, Ok(&wrong)).is_err());
// Its controller absent from the census, or no xHCI.
let usb = interfaces();
let missing: Vec<PciFunction> = functions
.iter()
.copied()
.filter(|function| function.address != at("0000:05:00.4"))
.collect();
assert_eq!(
choose(&missing, Ok(&usb)).unwrap_err(),
"the Bluetooth controller's controller pci=0000:05:00.4 is not in the firmware's PCI \
census; nothing is started"
);
let mut ehci = functions.clone();
for function in &mut ehci {
if function.address == at("0000:05:00.4") {
function.class = [0x0c, 0x03, 0x20];
}
}
assert_eq!(
choose(&ehci, Ok(&usb)).unwrap_err(),
"the Bluetooth controller's controller pci=0000:05:00.4 is of class 0c0320, not an \
xHCI; nothing is started"
);
}
#[test]
fn the_stick_on_another_controller_is_not_said_to_be_reset() {
let functions = census();
let mut usb = interfaces();
usb[0].controller = at("0000:05:00.3");
let target = choose(&functions, Ok(&usb)).unwrap();
assert_eq!(target.stick, None);
assert_eq!(target.interfaces, 3);
assert!(
target
.line()
.contains("the boot stick is on another controller")
);
}
#[test]
fn two_realtek_bluetooth_controllers_start_nothing_and_both_are_named() {
let functions = census();
// A Realtek dongle on the other xHCI too, its two interfaces.
let mut listed = interfaces();
for interface in ["USB(0x4,0x0)", "USB(0x4,0x1)"] {
listed.push(usb(
"0000:05:00.3",
interface,
(0x0bda, 0x8771),
BLUETOOTH,
false,
));
}
assert_eq!(
choose(&functions, Ok(&listed)).unwrap_err(),
"the firmware's USB stack lists 2 Bluetooth controllers a Realtek setup takes, 13d3:3612 \
at pci=0000:05:00.4 USB(0x1,0x0)/USB(0x2,0x0) and 0bda:8771 at pci=0000:05:00.3 \
USB(0x4,0x0), so the check cannot tell which to start; nothing is started"
);
// A second one on the same xHCI is refused alike.
let mut listed = interfaces();
listed.push(usb(
"0000:05:00.4",
"USB(0x1,0x0)/USB(0x4,0x0)",
(0x0bda, 0x8771),
BLUETOOTH,
false,
));
let both = choose(&functions, Ok(&listed)).unwrap_err();
assert!(both.contains("lists 2 Bluetooth controllers"), "{both}");
// The RTL8852CE's two interfaces are one controller's.
assert!(choose(&functions, Ok(&interfaces())).is_ok());
}
+8 -8
View File
@@ -287,8 +287,8 @@ pub fn take(variables: &mut Variables) -> Result<bool, String> {
pub fn untaken_reason(record: Record, why: &str) -> String {
format!(
"the Metal plugin repair's request ({}) could not be marked as taken in the machine \
state on the PC's disk: {why}. A repair boot now would repeat at every start, so Stela \
stopped before it; stela log saves the boot logs for a report",
state on the PC's disk: {why}. A repair boot now would repeat at every start, so Stambha \
stopped before it; stambha log saves the boot logs for a report",
record.name()
)
}
@@ -300,8 +300,8 @@ pub fn untaken_reason(record: Record, why: &str) -> String {
pub fn unstored_reason(what: &str, why: &str) -> String {
format!(
"the Metal plugin repair's record ({what}) could not be stored in the machine state on \
the PC's disk: {why}. A restart would not know it and could repeat this boot, so Stela \
stopped instead of restarting; stela log saves the boot logs for a report"
the PC's disk: {why}. A restart would not know it and could repeat this boot, so Stambha \
stopped instead of restarting; stambha log saves the boot logs for a report"
)
}
@@ -349,8 +349,8 @@ pub fn decide(report: Report, boot: Boot, record: Record, persistent: bool) -> D
/// this release: the record lives on the PC's own disk, which only a
/// system started on that PC reaches.
const AGAIN: &str = "start another system on this PC (Linux, Windows or a live USB), plug in \
the stick and run stela repair, which lets the repair run again at the next \
start; stela log saves the boot logs for a report";
the stick and run stambha repair, which lets the repair run again at the next \
start; stambha log saves the boot logs for a report";
/// The stop's reason for a normal boot that finds the plugin missing
/// ([`Decision::StopMissing`]): what the last repair boot reported
@@ -379,13 +379,13 @@ pub fn stop_reason(
if !persistent {
return format!(
"{MISSING}, and the machine state's NVRAM was not read at this start, so no \
automatic repair can be recorded (its NVRAM lines in the log say why); stela log \
automatic repair can be recorded (its NVRAM lines in the log say why); stambha log \
saves the boot logs for a report"
);
}
format!(
"{MISSING}, and NVRAM holds a repair record ({}) this start did not take, as when NVRAM \
is not read before the boot (its NVRAM lines in the log say why); stela log saves the \
is not read before the boot (its NVRAM lines in the log say why); stambha log saves the \
boot logs for a report",
record.name()
)
@@ -857,8 +857,8 @@ fn the_stop_names_the_repairs_result_and_advice_the_cli_can_follow() {
reason.contains(&format!("its boot reported: {reported}")),
"{reason}"
);
assert!(reason.contains("run stela repair"), "{reason}");
assert!(reason.contains("stela log"), "{reason}");
assert!(reason.contains("run stambha repair"), "{reason}");
assert!(reason.contains("stambha log"), "{reason}");
// No console takes the manual remedy on a PC without COM1, and no
// command asks for that boot.
assert!(!reason.contains("--single-user"), "{reason}");
@@ -867,7 +867,7 @@ fn the_stop_names_the_repairs_result_and_advice_the_cli_can_follow() {
assert!(silent.contains("left no result"), "{silent}");
let unread = stop_reason(false, Record::None, false, None);
assert!(unread.contains("NVRAM was not read"), "{unread}");
assert!(!unread.contains("stela repair"), "{unread}");
assert!(!unread.contains("stambha repair"), "{unread}");
let untaken = stop_reason(false, Record::Pending, true, None);
assert!(untaken.contains("(pending)"), "{untaken}");
for reason in [silent, unread, untaken] {
+122 -4
View File
@@ -8,6 +8,8 @@
//! confirmed. Only a store that cannot be read on a partition that is
//! otherwise the chosen one, with a Mac system on it, still stops the boot.
use stela_formats::payload::gpt;
/// What a search for the chosen partition found: every whole disk
/// reporting the serial, then its GPT partitions with the GUID.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -145,10 +147,32 @@ pub struct Candidate<'a> {
/// again once the firmware has exited.
pub serial: Option<&'a str>,
pub bytes: u64,
/// Why its geometry holds no partition table ([`size_refusal`]).
pub size: Option<&'static str>,
/// Why Stela's own drivers cannot reach its controller.
pub controller: Option<&'static str>,
}
/// The picker's refusal of a disk that reports a block size of 0 or no
/// blocks, as a UFS logical unit without media does.
pub const NO_SIZE: &str = "Reports no size";
/// The picker's refusal of a disk with fewer blocks than both copies of a
/// GPT take.
pub const NO_ROOM_FOR_TABLE: &str = "Too small for a partition table";
/// Why a disk of `geometry`, as its firmware reports it, cannot hold a GPT;
/// `None` when it can. The picker shows such a disk refused, and nothing
/// reads or lays out a GPT on it.
pub fn size_refusal(geometry: gpt::Disk) -> Option<&'static str> {
if !geometry.reports_size() {
Some(NO_SIZE)
} else if geometry.usable().is_none() {
Some(NO_ROOM_FOR_TABLE)
} else {
None
}
}
/// The picker's refusal of a disk whose serial another listed disk also
/// reports: after the firmware exits, Stela finds the chosen disk by its
/// serial alone, and two disks with one serial name neither
@@ -156,14 +180,19 @@ pub struct Candidate<'a> {
pub const SAME_SERIAL: &str = "Same serial as another disk";
/// Why the picker refuses disk `index` of `disks`, which it shows by the
/// disk; `None` when it can be chosen. A disk Stela's drivers cannot reach
/// or cannot find again by its serial is refused before its size is.
/// disk; `None` when it can be chosen. A disk that reports no size, or too
/// small a one for a GPT, is refused first, as nothing else about it can be
/// used; then one Stela's drivers cannot reach or cannot find again by its
/// serial, before its size is.
pub fn picker_refusal(
disks: &[Candidate<'_>],
index: usize,
min_bytes: u64,
) -> Option<&'static str> {
let disk = disks.get(index)?;
if disk.size.is_some() {
return disk.size;
}
if disk.controller.is_some() {
return disk.controller;
}
@@ -205,7 +234,7 @@ pub fn unreadable_store(blank: Option<bool>) -> Unreadable {
/// Why the boot stops on [`Unreadable::Fatal`], and what to do.
pub const UNREADABLE_STORE: &str = "NVRAM on the disk chosen for macOS cannot be read: choose \
Install macOS again, or on another computer plug in this USB and run `stela repair`";
Install macOS again, or on another computer plug in this USB and run `stambha repair`";
#[cfg(test)]
mod tests {
@@ -233,6 +262,7 @@ mod tests {
let disks = [Candidate {
serial: Some("WD-1"),
bytes: 1_000_000_000_000,
size: None,
controller: None,
}];
assert_eq!(picker_refusal(&disks, 0, 60_000_000_000), None);
@@ -294,6 +324,7 @@ mod tests {
let disk = |serial: Option<&'static str>, bytes: u64| Candidate {
serial,
bytes,
size: None,
controller: None,
};
// Two disks behind one USB-SATA bridge, or a cloned NVMe disk,
@@ -337,12 +368,99 @@ mod tests {
assert_eq!(picker_refusal(&unknown, 0, MIN), Some("No serial number"));
}
#[test]
fn a_disk_without_a_size_or_room_for_a_gpt_is_refused_by_its_size() {
let geometry = |block_bytes, blocks| gpt::Disk {
block_bytes,
blocks,
};
for none in [geometry(0, 0), geometry(0, 1 << 20), geometry(512, 0)] {
assert_eq!(size_refusal(none), Some(NO_SIZE), "{none:?}");
}
for tiny in [geometry(512, 1), geometry(512, 68), geometry(4096, 12)] {
assert_eq!(size_refusal(tiny), Some(NO_ROOM_FOR_TABLE), "{tiny:?}");
}
for fits in [
geometry(512, 69),
geometry(4096, 13),
geometry(512, 1_953_458_176),
geometry(4096, 31_246_336),
] {
assert_eq!(size_refusal(fits), None, "{fits:?}");
}
}
#[test]
fn the_picker_refuses_a_disk_that_reports_no_size_by_that() {
const MIN: u64 = 60_000_000_000;
// The two UFS logical units a Lenovo 500w Gen 5 listed: 128 GB
// with a GPT, and one of 0 bytes. Both sit behind a controller
// Stela has no driver for and report no serial; the empty one is
// refused for having no size, so nothing lays out a GPT on it.
let ufs = |bytes, geometry| Candidate {
serial: None,
bytes,
size: size_refusal(geometry),
controller: Some("Stambha has no driver for its controller"),
};
let disks = [
ufs(
127_984_992_256,
gpt::Disk {
block_bytes: 4096,
blocks: 127_984_992_256 / 4096,
},
),
ufs(
0,
gpt::Disk {
block_bytes: 0,
blocks: 0,
},
),
];
let refusals: Vec<_> = (0..disks.len())
.map(|index| picker_refusal(&disks, index, MIN))
.collect();
assert_eq!(
refusals,
[
Some("Stambha has no driver for its controller"),
Some(NO_SIZE)
]
);
// Its size is refused before anything else it lacks.
let alone = [Candidate {
serial: Some("S1"),
bytes: 0,
size: Some(NO_SIZE),
controller: None,
}];
assert_eq!(picker_refusal(&alone, 0, MIN), Some(NO_SIZE));
let tiny = [Candidate {
size: size_refusal(gpt::Disk {
block_bytes: 512,
blocks: 8,
}),
bytes: 4096,
..alone[0]
}];
assert_eq!(picker_refusal(&tiny, 0, MIN), Some(NO_ROOM_FOR_TABLE));
// A disk that holds a GPT is judged as before.
let sized = [Candidate {
size: None,
bytes: 500_000_000_000,
..alone[0]
}];
assert_eq!(picker_refusal(&sized, 0, MIN), None);
}
#[test]
fn an_unreadable_store_without_a_system_is_an_unfinished_install() {
assert_eq!(unreadable_store(Some(true)), Unreadable::Unprepared);
assert_eq!(unreadable_store(Some(false)), Unreadable::Fatal);
assert_eq!(unreadable_store(None), Unreadable::Fatal);
assert!(UNREADABLE_STORE.contains("Install macOS"));
assert!(UNREADABLE_STORE.contains("`stela repair`"));
assert!(UNREADABLE_STORE.contains("`stambha repair`"));
}
}
+330
View File
@@ -6,6 +6,8 @@
//! a client's mapping is Linux's to refault, as Linux's fault handler serves
//! only an address inside a VMA. Any other page is no client's: an access
//! there is the host code's own error, which no refault can answer.
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::fmt;
const PAGE: u64 = 4096;
@@ -31,6 +33,9 @@ impl Span {
pub enum Place {
/// In a client's mapping, at byte `at` of it: Linux's to refault.
Inside { span: Span, at: u64 },
/// In a page of a client's mapping that the client already unmapped,
/// at byte `at` of the mapping: as Linux's split mapping, no longer it.
Released { span: Span, at: u64 },
/// In no client's mapping, between the nearest ones.
Outside {
below: Option<Span>,
@@ -71,6 +76,16 @@ impl fmt::Display for Unserved {
span.offset,
span.start,
),
Place::Released { span, at } => write!(
f,
"FAULT IN UNMAPPED CLIENT PAGES a {access} at {:#x} is byte {at:#x} of fd {}'s \
mapping of {} KiB at {:#x}, in pages the client unmapped, so it is no longer \
the client's",
self.address,
span.fd,
(span.pages * PAGE) >> 10,
span.start,
),
Place::Outside { below, above } => {
write!(
f,
@@ -103,6 +118,188 @@ impl fmt::Display for Unserved {
}
}
/// The clients' mappings, by start, each with the faults running in it.
///
/// Linux serves a fault while its mapping is held (`mmap_lock`), and a fault
/// may sleep there: TTM waits for a buffer's move or eviction when memory is
/// short. Other calls run meanwhile, a new mapping or an unmapping among
/// them, so no borrow of the table lasts across the fault. A mapping a client
/// unmaps while faults run in it leaves the table's lookups at once and is
/// released by the last of them ([`Self::end_fault`]), so Linux never frees
/// a mapping a fault still uses, and its addresses are not given out again
/// before then.
///
/// As Linux's `munmap`, a client may unmap any page-aligned run of a mapping:
/// ANV maps a buffer from the kernel's start of it and unmaps the pages
/// before its slab entry. Those pages are no longer the mapping's, and the
/// mapping ends when every page of it is.
#[derive(Debug)]
pub struct Mappings<M> {
entries: BTreeMap<u64, Entry<M>>,
}
#[derive(Debug)]
struct Entry<M> {
map: M,
span: Span,
faults: u32,
unmapped: bool,
/// The page runs the client unmapped, sorted and merged.
released: Vec<(u64, u64)>,
}
impl<M> Entry<M> {
fn released(&self, page: u64) -> bool {
self.released
.iter()
.any(|&(first, end)| page >= first && page < end)
}
/// Releases the pages of `address..address + bytes` in the mapping:
/// whether every page of it now is.
fn release(&mut self, address: u64, bytes: u64) -> bool {
let first = (address - self.span.start) / PAGE;
let end = first
.saturating_add(bytes.div_ceil(PAGE))
.min(self.span.pages);
self.released.push((first, end));
self.released.sort_unstable();
let mut merged: Vec<(u64, u64)> = Vec::with_capacity(self.released.len());
for &(first, end) in &self.released {
match merged.last_mut() {
Some(previous) if first <= previous.1 => previous.1 = previous.1.max(end),
_ => merged.push((first, end)),
}
}
self.released = merged;
self.released == [(0, self.span.pages)]
}
}
/// A fault's lookup: where it lies, and the mapping Linux refaults it in,
/// which the fault holds until [`Mappings::end_fault`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Lookup<M> {
pub place: Place,
pub held: Option<M>,
}
/// An unmapping refused, as Linux's `munmap` refuses it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Refused {
/// No mapping holds the address.
NotMapped,
/// No bytes, or an address not on a page.
Invalid,
}
impl<M> Default for Mappings<M> {
fn default() -> Self {
Self {
entries: BTreeMap::new(),
}
}
}
impl<M: Copy> Mappings<M> {
/// A new mapping, `map`, at `span`.
pub fn insert(&mut self, span: Span, map: M) {
self.entries.insert(
span.start,
Entry {
map,
span,
faults: 0,
unmapped: false,
released: Vec::new(),
},
);
}
/// Where a fault at `address` lies among the mappings a client still
/// holds. Inside one, it is held for the fault until
/// [`Self::end_fault`] with the place's span start.
pub fn begin_fault(&mut self, address: u64) -> Lookup<M> {
let live = |entry: &&Entry<M>| !entry.unmapped;
let below = self
.entries
.range(..=address)
.map(|(_, e)| e)
.rev()
.find(live);
let above = self
.entries
.range(address.saturating_add(1)..)
.map(|(_, e)| e)
.find(live);
let place = match place(below.map(|e| e.span), above.map(|e| e.span), address) {
Place::Inside { span, at } if below.is_some_and(|e| e.released(at / PAGE)) => {
Place::Released { span, at }
}
place => place,
};
let held = match place {
Place::Inside { span, .. } => self.entries.get_mut(&span.start).map(|entry| {
entry.faults += 1;
entry.map
}),
Place::Released { .. } | Place::Outside { .. } => None,
};
Lookup { place, held }
}
/// Ends a fault held in the mapping at `start`: the mapping and its span
/// when it was unmapped while the fault ran and this was its last, for
/// the caller to release now.
pub fn end_fault(&mut self, start: u64) -> Option<(M, Span)> {
let entry = self.entries.get_mut(&start)?;
entry.faults = entry.faults.saturating_sub(1);
if entry.unmapped && entry.faults == 0 {
return self
.entries
.remove(&start)
.map(|entry| (entry.map, entry.span));
}
None
}
/// Unmaps the `bytes` at `address` of the mapping that holds it: the
/// mapping and its span to release now when that was its last page, or
/// none when pages of it remain or faults still run in it, the last of
/// which releases it.
pub fn unmap(&mut self, address: u64, bytes: u64) -> Result<Option<(M, Span)>, Refused> {
if bytes == 0 || !address.is_multiple_of(PAGE) {
return Err(Refused::Invalid);
}
let (&start, entry) = self
.entries
.range_mut(..=address)
.next_back()
.filter(|(_, entry)| !entry.unmapped && address < entry.span.end())
.ok_or(Refused::NotMapped)?;
if !entry.release(address, bytes) {
return Ok(None);
}
if entry.faults != 0 {
entry.unmapped = true;
return Ok(None);
}
Ok(self
.entries
.remove(&start)
.map(|entry| (entry.map, entry.span)))
}
/// The mappings not yet released, unmapped ones whose faults run among them.
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -197,4 +394,137 @@ mod tests {
it fd 9's mapping 0xffff80100e000000..0xffff80100e001000"
);
}
#[test]
fn a_mapping_unmapped_during_its_fault_is_released_by_the_fault() {
let mut maps = Mappings::default();
maps.insert(BELOW, 1u32);
maps.insert(ABOVE, 2u32);
let address = BELOW.start + PAGE;
let lookup = maps.begin_fault(address);
assert_eq!(lookup.held, Some(1));
// The fault sleeps; another call maps and the client unmaps.
let other = Span {
start: ABOVE.end() + PAGE,
..ABOVE
};
maps.insert(other, 3);
assert_eq!(maps.unmap(BELOW.start, BELOW.pages * PAGE), Ok(None));
assert_eq!(
maps.unmap(BELOW.start, BELOW.pages * PAGE),
Err(Refused::NotMapped)
);
// Its addresses stay taken, but no new fault finds it.
assert_eq!(maps.len(), 3);
let late = maps.begin_fault(address);
assert_eq!(late.held, None);
assert!(matches!(late.place, Place::Outside { below: None, .. }));
assert_eq!(maps.end_fault(BELOW.start), Some((1, BELOW)));
assert_eq!(maps.len(), 2);
assert_eq!(maps.end_fault(BELOW.start), None);
}
#[test]
fn faults_in_a_mapping_end_before_its_release() {
let mut maps = Mappings::default();
maps.insert(BELOW, 1u32);
assert_eq!(maps.begin_fault(BELOW.start).held, Some(1));
assert_eq!(maps.begin_fault(BELOW.start + 2 * PAGE).held, Some(1));
assert_eq!(maps.unmap(BELOW.start, u64::MAX), Ok(None));
assert_eq!(maps.end_fault(BELOW.start), None);
assert_eq!(maps.end_fault(BELOW.start), Some((1, BELOW)));
assert!(maps.is_empty());
// Without a fault running, an unmapping releases at once.
maps.insert(ABOVE, 2);
assert_eq!(maps.begin_fault(ABOVE.start).held, Some(2));
assert_eq!(maps.end_fault(ABOVE.start), None);
assert_eq!(maps.unmap(ABOVE.start, PAGE), Ok(Some((2, ABOVE))));
assert_eq!(maps.begin_fault(ABOVE.start).held, None);
}
#[test]
fn a_mapping_goes_once_every_page_of_it_is_released() {
// ANV's slab entry: the kernel maps a buffer from its start, so the
// entry at 12 KiB of a 16-page slab is mapped with the three pages
// before it, which are unmapped at once; the rest goes later.
let mut maps = Mappings::default();
maps.insert(BELOW, 1u32);
assert_eq!(maps.unmap(BELOW.start, 3 * PAGE), Ok(None));
assert_eq!(maps.begin_fault(BELOW.start + 3 * PAGE).held, Some(1));
assert_eq!(maps.end_fault(BELOW.start), None);
// A run inside, then the rest in two parts, out of order.
assert_eq!(maps.unmap(BELOW.start + 8 * PAGE, 2 * PAGE), Ok(None));
assert_eq!(maps.unmap(BELOW.start + 10 * PAGE, 100 * PAGE), Ok(None));
// A page released twice counts once.
assert_eq!(maps.unmap(BELOW.start + 9 * PAGE, PAGE), Ok(None));
assert_eq!(
maps.unmap(BELOW.start + 3 * PAGE, 5 * PAGE),
Ok(Some((1, BELOW)))
);
assert!(maps.is_empty());
}
#[test]
fn an_empty_unaligned_or_unmapped_unmap_is_refused_and_releases_nothing() {
let mut maps = Mappings::default();
maps.insert(BELOW, 1u32);
assert_eq!(maps.unmap(BELOW.start, 0), Err(Refused::Invalid));
assert_eq!(maps.unmap(BELOW.start + 1, PAGE), Err(Refused::Invalid));
assert_eq!(maps.unmap(BELOW.end(), PAGE), Err(Refused::NotMapped));
assert_eq!(
maps.unmap(BELOW.start - PAGE, PAGE),
Err(Refused::NotMapped)
);
assert_eq!(
maps.unmap(BELOW.start, BELOW.pages * PAGE),
Ok(Some((1, BELOW)))
);
}
#[test]
fn a_page_unmapped_during_a_fault_leaves_the_mapping_held_by_it() {
let mut maps = Mappings::default();
maps.insert(BELOW, 1u32);
let lookup = maps.begin_fault(BELOW.start + 5 * PAGE);
assert_eq!(lookup.held, Some(1));
// While the fault sleeps the client unmaps the first pages, then all
// but the faulting one's: the fault's page stays the mapping's.
assert_eq!(maps.unmap(BELOW.start, 5 * PAGE), Ok(None));
assert_eq!(maps.unmap(BELOW.start + 6 * PAGE, 10 * PAGE), Ok(None));
// A fault in a released page is not the mapping's.
let late = maps.begin_fault(BELOW.start + PAGE);
assert_eq!(late.held, None);
assert_eq!(
late.place,
Place::Released {
span: BELOW,
at: PAGE
}
);
// The last page goes while the fault runs: the fault releases it.
assert_eq!(maps.unmap(BELOW.start + 5 * PAGE, PAGE), Ok(None));
assert_eq!(maps.len(), 1);
assert_eq!(maps.begin_fault(BELOW.start + 5 * PAGE).held, None);
assert_eq!(maps.end_fault(BELOW.start), Some((1, BELOW)));
assert!(maps.is_empty());
}
#[test]
fn a_fault_in_an_unmapped_page_is_named_so() {
let line = Unserved {
address: BELOW.start + PAGE,
write: false,
place: Place::Released {
span: BELOW,
at: PAGE,
},
}
.to_string();
assert_eq!(
line,
"FAULT IN UNMAPPED CLIENT PAGES a read at 0xffff80100c001000 is byte 0x1000 of fd \
7's mapping of 64 KiB at 0xffff80100c000000, in pages the client unmapped, so it \
is no longer the client's"
);
}
}
+361
View File
@@ -0,0 +1,361 @@
//! A DRM driver's own ioctls by name, and which of its error answers are
//! its ordinary reply to a Vulkan driver's probe of what the GPU or the
//! kernel has. Both depend on the driver the file belongs to: every driver
//! numbers its commands from the same base, so one image that holds several
//! drivers must ask the file which one it is.
/// The first number of a driver's own commands (`DRM_COMMAND_BASE`).
pub const COMMAND_BASE: u32 = 0x40;
/// DRM's ioctl type, `'d'`.
const DRM: u32 = b'd' as u32;
/// `DRM_IOCTL_VERSION`: `DRM_IOWR(0x00, struct drm_version)`, 64 bytes on
/// x86-64. Its answer names the driver.
pub const VERSION: u32 = 0xc040_6400;
const ENOENT: i64 = -2;
const ENODEV: i64 = -19;
const EINVAL: i64 = -22;
/// The name of `driver`'s command `command`, its ioctl number less
/// [`COMMAND_BASE`], from the driver's own uAPI header.
pub fn driver_call(driver: &str, command: u32) -> Option<&'static str> {
let table: &[&'static str] = match driver {
"amdgpu" => &AMDGPU,
"xe" => &XE,
"i915" => &I915,
"nouveau" => return nouveau(command),
_ => return None,
};
table
.get(command as usize)
.copied()
.filter(|name| !name.is_empty())
}
/// `amdgpu_drm.h`, from `DRM_AMDGPU_GEM_CREATE` (0x00).
const AMDGPU: [&str; 0x16] = [
"AMDGPU_GEM_CREATE",
"AMDGPU_GEM_MMAP",
"AMDGPU_CTX",
"AMDGPU_BO_LIST",
"AMDGPU_CS",
"AMDGPU_INFO",
"AMDGPU_GEM_METADATA",
"AMDGPU_GEM_WAIT_IDLE",
"AMDGPU_GEM_VA",
"AMDGPU_WAIT_CS",
"",
"",
"",
"",
"",
"",
"AMDGPU_GEM_OP",
"AMDGPU_GEM_USERPTR",
"AMDGPU_WAIT_FENCES",
"AMDGPU_VM",
"AMDGPU_FENCE_TO_HANDLE",
"AMDGPU_SCHED",
];
/// `xe_drm.h`, from `DRM_XE_DEVICE_QUERY` (0x00).
const XE: [&str; 0x10] = [
"XE_DEVICE_QUERY",
"XE_GEM_CREATE",
"XE_GEM_MMAP_OFFSET",
"XE_VM_CREATE",
"XE_VM_DESTROY",
"XE_VM_BIND",
"XE_EXEC_QUEUE_CREATE",
"XE_EXEC_QUEUE_DESTROY",
"XE_EXEC_QUEUE_GET_PROPERTY",
"XE_EXEC",
"XE_WAIT_USER_FENCE",
"XE_OBSERVATION",
"XE_MADVISE",
"XE_VM_QUERY_MEM_RANGE_ATTRS",
"XE_EXEC_QUEUE_SET_PROPERTY",
"XE_VM_GET_PROPERTY",
];
/// `i915_drm.h`, from `DRM_I915_INIT` (0x00); a number two ioctls share
/// (by their argument's size) carries both names.
const I915: [&str; 0x3d] = [
"I915_INIT",
"I915_FLUSH",
"I915_FLIP",
"I915_BATCHBUFFER",
"I915_IRQ_EMIT",
"I915_IRQ_WAIT",
"I915_GETPARAM",
"I915_SETPARAM",
"I915_ALLOC",
"I915_FREE",
"I915_INIT_HEAP",
"I915_CMDBUFFER",
"I915_DESTROY_HEAP",
"I915_SET_VBLANK_PIPE",
"I915_GET_VBLANK_PIPE",
"I915_VBLANK_SWAP",
"",
"I915_HWS_ADDR",
"",
"I915_GEM_INIT",
"I915_GEM_EXECBUFFER",
"I915_GEM_PIN",
"I915_GEM_UNPIN",
"I915_GEM_BUSY",
"I915_GEM_THROTTLE",
"I915_GEM_ENTERVT",
"I915_GEM_LEAVEVT",
"I915_GEM_CREATE",
"I915_GEM_PREAD",
"I915_GEM_PWRITE",
"I915_GEM_MMAP",
"I915_GEM_SET_DOMAIN",
"I915_GEM_SW_FINISH",
"I915_GEM_SET_TILING",
"I915_GEM_GET_TILING",
"I915_GEM_GET_APERTURE",
"I915_GEM_MMAP_GTT/OFFSET",
"I915_GET_PIPE_FROM_CRTC_ID",
"I915_GEM_MADVISE",
"I915_OVERLAY_PUT_IMAGE",
"I915_OVERLAY_ATTRS",
"I915_GEM_EXECBUFFER2",
"I915_GET_SPRITE_COLORKEY",
"I915_SET_SPRITE_COLORKEY",
"I915_GEM_WAIT",
"I915_GEM_CONTEXT_CREATE(_EXT)",
"I915_GEM_CONTEXT_DESTROY",
"I915_GEM_SET_CACHING",
"I915_GEM_GET_CACHING",
"I915_REG_READ",
"I915_GET_RESET_STATS",
"I915_GEM_USERPTR",
"I915_GEM_CONTEXT_GETPARAM",
"I915_GEM_CONTEXT_SETPARAM",
"I915_PERF_OPEN",
"I915_PERF_ADD_CONFIG",
"I915_PERF_REMOVE_CONFIG",
"I915_QUERY",
"I915_GEM_VM_CREATE",
"I915_GEM_VM_DESTROY",
"I915_GEM_CREATE_EXT",
];
/// `nouveau_drm.h`, whose numbers have gaps.
fn nouveau(command: u32) -> Option<&'static str> {
Some(match command {
0x00 => "NOUVEAU_GETPARAM",
0x01 => "NOUVEAU_SETPARAM",
0x02 => "NOUVEAU_CHANNEL_ALLOC",
0x03 => "NOUVEAU_CHANNEL_FREE",
0x04 => "NOUVEAU_GROBJ_ALLOC",
0x05 => "NOUVEAU_NOTIFIEROBJ_ALLOC",
0x06 => "NOUVEAU_GPUOBJ_FREE",
0x07 => "NOUVEAU_NVIF",
0x08 => "NOUVEAU_SVM_INIT",
0x09 => "NOUVEAU_SVM_BIND",
0x10 => "NOUVEAU_VM_INIT",
0x11 => "NOUVEAU_VM_BIND",
0x12 => "NOUVEAU_EXEC",
0x13 => "NOUVEAU_GET_ZCULL_INFO",
0x40 => "NOUVEAU_GEM_NEW",
0x41 => "NOUVEAU_GEM_PUSHBUF",
0x42 => "NOUVEAU_GEM_CPU_PREP",
0x43 => "NOUVEAU_GEM_CPU_FINI",
0x44 => "NOUVEAU_GEM_INFO",
_ => return None,
})
}
/// `DRM_IOCTL_XE_DEVICE_QUERY`: `DRM_IOWR(0x40, struct drm_xe_device_query)`,
/// 40 bytes, its query kind at byte 8.
const XE_DEVICE_QUERY: u32 = 0xc028_6440;
/// `DRM_XE_DEVICE_QUERY_PXP_STATUS`.
const XE_QUERY_PXP_STATUS: u32 = 9;
/// `DRM_IOCTL_XE_VM_GET_PROPERTY`: `DRM_IOWR(0x4f, struct
/// drm_xe_vm_get_property)`, 56 bytes, its VM at byte 8.
const XE_VM_GET_PROPERTY: u32 = 0xc038_644f;
/// `DRM_IOCTL_I915_GETPARAM`: `DRM_IOWR(0x46, drm_i915_getparam_t)`, 16
/// bytes, its parameter at byte 0.
const I915_GETPARAM: u32 = 0xc010_6446;
/// `I915_PARAM_IRQ_ACTIVE`, a parameter i915 answers `-ENODEV` for.
const I915_PARAM_IRQ_ACTIVE: u32 = 1;
/// `I915_PARAM_PXP_STATUS`.
const I915_PARAM_PXP_STATUS: u32 = 58;
/// `DRM_IOCTL_I915_GEM_USERPTR`: `DRM_IOWR(0x73, struct
/// drm_i915_gem_userptr)`, 24 bytes, its size at byte 8.
const I915_GEM_USERPTR: u32 = 0xc018_6473;
/// Whether `driver`'s answer `result` to ioctl `request`, whose argument
/// began with `input` as the caller passed it, is the driver's ordinary
/// reply to a probe a Vulkan driver makes on every device and handles:
/// not a refusal worth a line.
///
/// - xe, `DEVICE_QUERY` of `PXP_STATUS`, `-ENODEV`: ANV asks on every
/// graphics 12 and later GPU whether protected content can run
/// (`xe_gem_supports_protected_exec_queue`). xe has none without the MEI
/// GSC proxy driver, which Stela's Linux does not build, and says so with
/// `-ENODEV` (`xe_pxp_get_readiness_status`).
/// - xe, `VM_GET_PROPERTY` of VM `u32::MAX`, `-ENOENT`: on Xe2 and later
/// ANV detects VM fault reporting by asking for a VM no file has
/// (`xe_gem_supports_get_vm_faults`); `-ENOENT` is the answer it wants.
/// - i915, `GETPARAM` of `PXP_STATUS`, `-ENODEV`: ANV asks on every GPU
/// whether protected content can run (`i915_gem_supports_protected_context`)
/// and takes `-ENODEV` as no; i915 has no PXP without
/// `CONFIG_DRM_I915_PXP` and the MEI drivers (`intel_pxp_get_readiness_status`).
/// - i915, `GETPARAM` of `IRQ_ACTIVE`, `-ENODEV`: Mesa's i915 device info
/// asks for the parameter numbered by the boolean answer to
/// `HAS_CONTEXT_ISOLATION` (`intel/dev/i915/intel_device_info.c`, a getparam
/// inside a getparam's argument), which is 1 on every GPU i915 is handed; i915
/// retired that parameter and answers `-ENODEV`, which Mesa ignores.
/// - i915, `GEM_USERPTR` of 0 bytes, `-EINVAL`: Mesa's i915 device info
/// asks whether the userptr interface exists with an empty object
/// (`has_userptr_uapi`, `intel/dev/i915/intel_device_info.c`), and
/// `-EINVAL` for its size is the yes (`i915_gem_userptr_ioctl`).
pub fn probe_answer(driver: &str, request: u32, input: &[u8], result: i64) -> bool {
let word = |at: usize| {
input
.get(at..at + 4)
.map(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
match (driver, request, result) {
("xe", XE_DEVICE_QUERY, ENODEV) => word(8) == Some(XE_QUERY_PXP_STATUS),
("xe", XE_VM_GET_PROPERTY, ENOENT) => word(8) == Some(u32::MAX),
("i915", I915_GETPARAM, ENODEV) => {
matches!(word(0), Some(I915_PARAM_PXP_STATUS | I915_PARAM_IRQ_ACTIVE))
}
("i915", I915_GEM_USERPTR, EINVAL) => input.get(8..16) == Some(&[0; 8]),
_ => false,
}
}
/// The driver command `request` is, if it is DRM's ioctl type and past
/// DRM's own commands.
pub fn driver_command(request: u32) -> Option<u32> {
let number = request & 0xff;
((request >> 8) & 0xff == DRM)
.then(|| number.checked_sub(COMMAND_BASE))
.flatten()
.filter(|command| *command < 0x60)
}
#[cfg(test)]
mod tests {
use super::*;
/// `_IOC(read | write, 'd', number, size)`, as Linux's `DRM_IOWR`.
fn iowr(number: u32, size: u32) -> u32 {
3 << 30 | size << 16 | DRM << 8 | number
}
#[test]
fn a_driver_command_is_named_by_the_driver_of_its_file() {
// The same number is a different call for each driver: the
// development image holds all four.
let request = iowr(COMMAND_BASE, 40);
let command = driver_command(request).unwrap();
assert_eq!(command, 0);
assert_eq!(driver_call("xe", command), Some("XE_DEVICE_QUERY"));
assert_eq!(driver_call("amdgpu", command), Some("AMDGPU_GEM_CREATE"));
assert_eq!(driver_call("i915", command), Some("I915_INIT"));
assert_eq!(driver_call("nouveau", command), Some("NOUVEAU_GETPARAM"));
assert_eq!(driver_call("vgem", command), None);
// The last of each table, and the gaps.
assert_eq!(driver_call("xe", 0x0f), Some("XE_VM_GET_PROPERTY"));
assert_eq!(driver_call("xe", 0x10), None);
assert_eq!(driver_call("i915", 0x29), Some("I915_GEM_EXECBUFFER2"));
assert_eq!(driver_call("i915", 0x3c), Some("I915_GEM_CREATE_EXT"));
assert_eq!(driver_call("i915", 0x10), None);
assert_eq!(driver_call("amdgpu", 0x0a), None);
assert_eq!(driver_call("amdgpu", 0x15), Some("AMDGPU_SCHED"));
assert_eq!(driver_call("nouveau", 0x44), Some("NOUVEAU_GEM_INFO"));
// DRM's own commands and other ioctl types are no driver's.
assert_eq!(driver_command(VERSION), None);
assert_eq!(driver_command(0xc008_6200 | 0x02), None);
}
#[test]
fn the_request_codes_are_the_uapi_headers() {
assert_eq!(VERSION, iowr(0x00, 64));
assert_eq!(XE_DEVICE_QUERY, iowr(COMMAND_BASE, 40));
assert_eq!(XE_VM_GET_PROPERTY, iowr(COMMAND_BASE + 0x0f, 56));
assert_eq!(I915_GETPARAM, iowr(COMMAND_BASE + 0x06, 16));
assert_eq!(I915_GEM_USERPTR, iowr(COMMAND_BASE + 0x33, 24));
}
#[test]
fn i915s_answer_to_mesas_userptr_probe_is_not_a_refusal() {
// Issue 8's T480s logged `I915_GEM_USERPTR ... refused: EINVAL`
// once a boot: Mesa's empty object, which only asks the interface.
let userptr = |size: u64| {
let mut argument = [0u8; 24];
argument[0..8].copy_from_slice(&0x1000u64.to_le_bytes());
argument[8..16].copy_from_slice(&size.to_le_bytes());
argument
};
assert!(probe_answer("i915", I915_GEM_USERPTR, &userptr(0), EINVAL));
// A real object's EINVAL, another errno or driver, or no kept
// input is a refusal.
assert!(!probe_answer(
"i915",
I915_GEM_USERPTR,
&userptr(4096),
EINVAL
));
assert!(!probe_answer("i915", I915_GEM_USERPTR, &userptr(0), -14));
assert!(!probe_answer("xe", I915_GEM_USERPTR, &userptr(0), EINVAL));
assert!(!probe_answer("i915", I915_GEM_USERPTR, &[], EINVAL));
}
#[test]
fn i915s_answers_to_anvs_parameter_probes_are_not_refusals() {
let param = |number: u32| {
let mut argument = [0u8; 16];
argument[..4].copy_from_slice(&number.to_le_bytes());
argument
};
for number in [I915_PARAM_PXP_STATUS, I915_PARAM_IRQ_ACTIVE] {
assert!(probe_answer("i915", I915_GETPARAM, &param(number), ENODEV));
// Another errno or another driver is a refusal.
assert!(!probe_answer("i915", I915_GETPARAM, &param(number), -22));
assert!(!probe_answer("xe", I915_GETPARAM, &param(number), ENODEV));
}
// Any other parameter's -ENODEV is (the chipset ID, slice mask).
for number in [4, 46] {
assert!(!probe_answer("i915", I915_GETPARAM, &param(number), ENODEV));
}
assert!(!probe_answer("i915", I915_GETPARAM, &[], ENODEV));
}
#[test]
fn xes_answers_to_anvs_feature_probes_are_not_refusals() {
let mut query = [0u8; 40];
query[8..12].copy_from_slice(&XE_QUERY_PXP_STATUS.to_le_bytes());
assert!(probe_answer("xe", XE_DEVICE_QUERY, &query, ENODEV));
// Another query, another errno or another driver is a refusal.
assert!(!probe_answer("xe", XE_DEVICE_QUERY, &query, -22));
assert!(!probe_answer("amdgpu", XE_DEVICE_QUERY, &query, ENODEV));
let mut config = [0u8; 40];
config[8..12].copy_from_slice(&2u32.to_le_bytes());
assert!(!probe_answer("xe", XE_DEVICE_QUERY, &config, ENODEV));
let mut faults = [0u8; 56];
faults[8..12].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(probe_answer("xe", XE_VM_GET_PROPERTY, &faults, ENOENT));
let mut real = [0u8; 56];
real[8..12].copy_from_slice(&1u32.to_le_bytes());
assert!(!probe_answer("xe", XE_VM_GET_PROPERTY, &real, ENOENT));
assert!(!probe_answer(
"xe",
XE_VM_GET_PROPERTY,
&faults[..8],
ENOENT
));
}
}
@@ -248,6 +248,11 @@ impl LeftOut {
Ok(())
}
/// Whether the census left nothing out.
pub fn is_empty(&self) -> bool {
self.functions.is_empty() && self.buses.is_empty()
}
/// Whether the census left out the function at `address`, alone or
/// with its bus.
pub fn holds(&self, address: Address) -> bool {
+2 -2
View File
@@ -129,7 +129,7 @@ impl core::fmt::Display for SealError {
Self::Capacity { entries, capacity } => write!(
f,
"the firmware's final memory map has {entries} entries, more than the \
{capacity} Stela keeps"
{capacity} Stambha keeps"
),
Self::Unaligned { index, start } => write!(
f,
@@ -276,7 +276,7 @@ mod tests {
);
assert_eq!(
alloc::format!("{error}"),
"the firmware's final memory map has 700 entries, more than the 512 Stela keeps"
"the firmware's final memory map has 700 entries, more than the 512 Stambha keeps"
);
}
@@ -0,0 +1,225 @@
//! The firmware's picture while GPU claims hold it.
//!
//! A claim of a GPU that may show the firmware's screen stops the boot's
//! writes to that framebuffer before it changes the GPU (its BAR sizing turns
//! memory decoding off for a moment). The picture itself lasts until a step
//! ends it: a reset of the GPU, by its claim or by its driver, or the start
//! of the driver's display engine, which blanks what the firmware lit. A
//! driver bound to the GPU drives that screen from then on. A claim that
//! lets go with none of those, as a driver whose probe failed before them,
//! leaves the picture as it was, and the boot draws on it again: its text,
//! a stop's reason, or macOS's frames copied from another GPU.
use crate::screen::Exclusive;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, Ordering};
/// [`Held`] as the processors that claim GPUs share it: each step takes it
/// for a few instructions, and a wait for it has a deadline. A wait that
/// gives up may miss a claim's hold or end, so from then on the record is
/// not known to be whole and the picture is taken as ended: the boot never
/// draws on it again ([`Self::lost`]).
pub struct Record {
held: Exclusive<Held>,
lost: AtomicBool,
}
/// How a wait for the [`Record`] ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Waited<R> {
Done(R),
/// The deadline passed with the record still taken; `first` for the
/// first such wait of the boot, which its caller says in a line.
GaveUp {
first: bool,
},
}
impl Default for Record {
fn default() -> Self {
Self::new()
}
}
impl Record {
pub const fn new() -> Self {
Self {
held: Exclusive::new(Held::new()),
lost: AtomicBool::new(false),
}
}
/// Run `f` on the record once it is free, waiting at most `limit`
/// ticks of `now`, which may wrap.
pub fn with_within<R>(
&self,
mut now: impl FnMut() -> u64,
limit: u64,
f: impl FnOnce(&mut Held) -> R,
) -> Waited<R> {
let started = now();
match self
.held
.with_until(|| now().wrapping_sub(started) >= limit, f)
{
Some(result) => Waited::Done(result),
None => Waited::GaveUp {
first: !self.lost.swap(true, Ordering::Relaxed),
},
}
}
/// Run `f` on the record unless it is taken now, as a stop must.
pub fn try_with<R>(&self, f: impl FnOnce(&mut Held) -> R) -> Option<R> {
self.held.try_with(f)
}
/// A wait for the record gave up, so the picture is taken as ended.
pub fn lost(&self) -> bool {
self.lost.load(Ordering::Relaxed)
}
}
/// The claims holding the firmware's picture, by PCI bus and devfn, and
/// whether a step ended it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Held {
holders: Vec<(u8, u8)>,
ended: bool,
}
impl Held {
pub const fn new() -> Self {
Self {
holders: Vec::new(),
ended: false,
}
}
/// The claim of the GPU at `bus` and `devfn` stopped the boot's writes
/// to the picture.
pub fn hold(&mut self, bus: u8, devfn: u8) {
if !self.holders.contains(&(bus, devfn)) {
self.holders.push((bus, devfn));
}
}
/// The GPU at `bus` and `devfn` ended the picture: it was reset, its
/// driver started its display engine, or its driver bound it.
pub fn end(&mut self, bus: u8, devfn: u8) {
self.holders.retain(|&holder| holder != (bus, devfn));
self.ended = true;
}
/// The claim of the GPU at `bus` and `devfn` let go without ending the
/// picture. Whether the boot may draw on it again now: no claim holds
/// it any more, and none ended it.
pub fn release(&mut self, bus: u8, devfn: u8) -> bool {
self.holders.retain(|&holder| holder != (bus, devfn));
self.holders.is_empty() && !self.ended
}
/// At a stop: whether the picture still shows, so the stop's reason may
/// be drawn on it. No step ended it, and `ended_in_probe` says for each
/// claim still holding it whether its driver ended it in a probe that
/// never returned, the probe the stop may come from.
pub fn shows_at_stop(&self, ended_in_probe: impl Fn(u8, u8) -> bool) -> bool {
!self.ended
&& !self
.holders
.iter()
.any(|&(bus, devfn)| ended_in_probe(bus, devfn))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A wait for the record has a deadline: one that passes while another
/// step holds it gives up, says so once, and leaves the picture taken
/// as ended, so no later claim gives it back to the boot.
#[test]
fn a_wait_for_a_taken_record_ends_at_its_deadline() {
let record = Record::new();
assert_eq!(
record.with_within(|| 0, 10, |held| held.hold(IGPU.0, IGPU.1)),
Waited::Done(())
);
let clock = core::cell::Cell::new(u64::MAX - 3);
let tick = || {
clock.set(clock.get().wrapping_add(1));
clock.get()
};
let inner = record.try_with(|_| {
let first = record.with_within(tick, 10, |_| ());
let second = record.with_within(tick, 10, |_| ());
(first, second)
});
assert_eq!(
inner,
Some((
Waited::GaveUp { first: true },
Waited::GaveUp { first: false }
))
);
assert!(clock.get() >= 20 - 4);
assert!(record.lost());
// The record itself still says the picture may come back; the loss
// is what keeps it from the boot.
assert_eq!(
record.with_within(|| 0, 10, |held| held.release(IGPU.0, IGPU.1)),
Waited::Done(true)
);
}
const IGPU: (u8, u8) = (1, 0);
const CARD: (u8, u8) = (3, 0);
#[test]
fn a_driver_that_fails_before_any_step_leaves_the_picture() {
let mut held = Held::new();
held.hold(IGPU.0, IGPU.1);
// During the probe, a stop may draw on it.
assert!(held.shows_at_stop(|_, _| false));
assert!(held.release(IGPU.0, IGPU.1));
assert!(held.shows_at_stop(|_, _| false));
}
#[test]
fn a_reset_or_a_bound_driver_ends_the_picture_for_good() {
let mut held = Held::new();
held.hold(IGPU.0, IGPU.1);
held.end(IGPU.0, IGPU.1);
assert!(!held.shows_at_stop(|_, _| false));
// A later claim that lets go does not bring it back.
held.hold(CARD.0, CARD.1);
assert!(!held.release(CARD.0, CARD.1));
}
#[test]
fn a_driver_ending_the_picture_in_a_probe_that_stopped_is_seen_at_the_stop() {
let mut held = Held::new();
held.hold(IGPU.0, IGPU.1);
assert!(!held.shows_at_stop(|bus, devfn| (bus, devfn) == IGPU));
assert!(held.shows_at_stop(|bus, devfn| (bus, devfn) == CARD));
}
#[test]
fn the_picture_comes_back_only_after_the_last_claim_lets_go() {
// Where the screen's function is unknown, every GPU that may show
// it holds it.
let mut held = Held::new();
held.hold(IGPU.0, IGPU.1);
held.hold(CARD.0, CARD.1);
held.hold(CARD.0, CARD.1);
assert!(!held.release(IGPU.0, IGPU.1));
assert!(held.release(CARD.0, CARD.1));
// One that ends it after another let go keeps it ended.
let mut held = Held::new();
held.hold(IGPU.0, IGPU.1);
held.hold(CARD.0, CARD.1);
assert!(!held.release(IGPU.0, IGPU.1));
held.end(CARD.0, CARD.1);
assert!(!held.shows_at_stop(|_, _| false));
}
}
@@ -88,6 +88,33 @@ impl BridgeWindows {
self.buses.clone()
}
/// Whether the bridge forwards every byte of `span` (one window holds
/// it all, or the bridge decodes subtractively).
pub fn forwards_all(&self, span: &Range<u64>) -> bool {
let holds = |window: &Range<u64>| window.start <= span.start && span.end <= window.end;
self.subtractive
|| self.memory.as_ref().is_some_and(holds)
|| self.prefetchable.as_ref().is_some_and(holds)
}
/// Its windows in words, for a log line.
pub fn describe(&self) -> alloc::string::String {
let window = |range: &Option<Range<u64>>| match range {
Some(range) => alloc::format!("{:#x}..{:#x}", range.start, range.end),
None => alloc::string::String::from("closed"),
};
alloc::format!(
"memory {}, prefetchable {}{}",
window(&self.memory),
window(&self.prefetchable),
if self.subtractive {
", subtractive"
} else {
""
}
)
}
/// Whether the bridge forwards any byte of `span`.
pub fn forwards(&self, span: &Range<u64>) -> bool {
let overlaps = |window: &Range<u64>| window.start < span.end && span.start < window.end;
@@ -210,6 +237,24 @@ mod tests {
assert!(!bridge.forwards(&(0xa10 * MIB..0xa20 * MIB)));
}
#[test]
fn a_span_is_forwarded_whole_only_inside_one_window() {
let bridge =
BridgeWindows::from_words(port(1, 3, Some((0xa00, 0xa0f)), Some((0x6_0000, 0x6_0fff))))
.unwrap();
assert!(bridge.forwards_all(&(0xa08 * MIB..0xa10 * MIB)));
assert!(!bridge.forwards_all(&(0xa08 * MIB..0xa10 * MIB + 1)));
assert!(bridge.forwards_all(&(0x6_0000 * MIB..0x6_0001 * MIB)));
assert!(!bridge.forwards_all(&(0x9ff * MIB..0xa01 * MIB)));
assert_eq!(
bridge.describe(),
"memory 0xa0000000..0xa1000000, prefetchable 0x6000000000..0x6100000000"
);
let closed = BridgeWindows::from_words(port(2, 2, None, None)).unwrap();
assert!(!closed.forwards_all(&(0..1)));
assert_eq!(closed.describe(), "memory closed, prefetchable closed");
}
#[test]
fn closed_windows_unassigned_buses_vga_and_subtractive_decode() {
let closed = BridgeWindows::from_words(port(2, 2, None, None)).unwrap();
+200
View File
@@ -0,0 +1,200 @@
//! The kernel's lines of a GPU fault, for the Metal device's fault dump
//! (`stela_driver_gpu::metal::fault_dump`) to follow with: nouveau's
//! `Xid` lines (GSP-RM's error log, whose Xid 13 text names the exception
//! and the ESR words, such as `Graphics Exception: ESR 0x405840=...`), its
//! `rc` line (the channel GSP-RM reset, by chid and exception type) and the
//! channel it disabled. A WindowServer that faults at each start prints
//! hundreds, so the first of the boot are kept, with a count of all.
use alloc::{format, string::String, vec::Vec};
use core::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
/// What a kernel line of a GPU fault contains.
const MARKERS: [&str; 3] = ["Xid:", " rc engn:", "errored - disabling channel"];
/// Whether `line` is a kernel line of a GPU fault.
pub fn is_fault_line(line: &str) -> bool {
MARKERS.iter().any(|marker| line.contains(marker))
}
/// The first `SLOTS` kernel lines of GPU faults of the boot, each cut to
/// `BYTES`, and how many there were. Each slot is written once; read
/// without a lock.
pub struct FaultLines<const SLOTS: usize, const BYTES: usize> {
lines: [Line<BYTES>; SLOTS],
claimed: AtomicUsize,
seen: AtomicU64,
}
struct Line<const BYTES: usize> {
ready: AtomicBool,
length: AtomicUsize,
bytes: [AtomicU8; BYTES],
}
impl<const SLOTS: usize, const BYTES: usize> Default for FaultLines<SLOTS, BYTES> {
fn default() -> Self {
Self::new()
}
}
impl<const SLOTS: usize, const BYTES: usize> FaultLines<SLOTS, BYTES> {
pub const fn new() -> Self {
Self {
lines: [const {
Line {
ready: AtomicBool::new(false),
length: AtomicUsize::new(0),
bytes: [const { AtomicU8::new(0) }; BYTES],
}
}; SLOTS],
claimed: AtomicUsize::new(0),
seen: AtomicU64::new(0),
}
}
/// Counts `line` if it is a GPU fault's and keeps it while a slot is
/// free, cut to the slot's size at a character boundary; whether it is
/// one.
pub fn observe(&self, line: &str) -> bool {
if !is_fault_line(line) {
return false;
}
self.seen.fetch_add(1, Ordering::Relaxed);
let Ok(slot) = self
.claimed
.try_update(Ordering::Relaxed, Ordering::Relaxed, |claimed| {
(claimed < SLOTS).then_some(claimed + 1)
})
else {
return true;
};
let mut end = line.len().min(BYTES);
while !line.is_char_boundary(end) {
end -= 1;
}
let slot = &self.lines[slot];
for (byte, value) in slot.bytes.iter().zip(line[..end].bytes()) {
byte.store(value, Ordering::Relaxed);
}
slot.length.store(end, Ordering::Relaxed);
slot.ready.store(true, Ordering::Release);
true
}
/// The kept lines, in the order they were printed.
pub fn kept(&self) -> Vec<String> {
self.lines
.iter()
.take_while(|slot| slot.ready.load(Ordering::Acquire))
.filter_map(|slot| {
let length = slot.length.load(Ordering::Relaxed);
let bytes = slot.bytes[..length]
.iter()
.map(|byte| byte.load(Ordering::Relaxed))
.collect();
String::from_utf8(bytes).ok()
})
.collect()
}
/// The GPU fault lines the kernel printed this boot.
pub fn seen(&self) -> u64 {
self.seen.load(Ordering::Relaxed)
}
}
/// The lines that follow fault `fault`'s opening in the log, each after
/// the log's `GPU FAULT `: the first fault gives the kept lines, and every
/// fault the count so far, which says whether each start faults alike.
pub fn kernel_lines(fault: u32, kept: &[String], seen: u64) -> Vec<String> {
let mut lines = Vec::new();
if fault == 1 {
lines.extend(kept.iter().map(|line| format!("{fault} kernel: {line}")));
}
let shown = match (fault, kept.len()) {
(_, 0) => String::new(),
(1, count) => format!(", the first {count} above"),
(_, count) => format!(", the first {count} after fault 1"),
};
lines.push(format!(
"{fault} kernel: {seen} Xid, rc and disabled-channel lines so far this boot{shown}"
));
lines
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
const XID: &str = "nouveau 0000:01:00.0: gsp: Xid:13 Graphics Exception: Shader Program \
Header 11 Error";
const ESR: &str = "nouveau 0000:01:00.0: gsp: Xid:13 Graphics Exception: ESR \
0x405840=0xa2040800 0x405844=0x0 0x405848=0x0 0x40584c=0x0";
const RC: &str = "nouveau 0000:01:00.0: gsp: rc engn:00000001 chid:22 gfid:0 level:2 \
type:13 scope:1 part:233 fault_addr:0000000000000000 fault_type:ffffffff";
const DISABLED: &str = "nouveau 0000:01:00.0: fifo:000000:0016:[stela-managed[22]] errored \
- disabling channel";
#[test]
fn the_fault_lines_are_nouveaus_xid_rc_and_disabled_channel() {
for line in [XID, ESR, RC, DISABLED] {
assert!(is_fault_line(line), "{line}");
}
for line in [
"nouveau 0000:01:00.0: gsp: mmu fault queued",
"nouveau 0000:01:00.0: stopped answering: BOOT_0 read ffffffff for 1004 ms",
"GPU REFUSED DeviceLost in operation 12",
] {
assert!(!is_fault_line(line), "{line}");
}
}
/// The first lines of the boot are kept in order, each cut at a
/// character boundary, and every one is counted.
#[test]
fn the_first_lines_are_kept_and_every_one_counted() {
let lines: FaultLines<2, 64> = FaultLines::new();
assert!(!lines.observe("nouveau 0000:01:00.0: gsp: mmu fault queued"));
assert_eq!(lines.seen(), 0);
for line in [XID, ESR, RC, DISABLED] {
assert!(lines.observe(line));
}
assert_eq!(lines.seen(), 4);
assert_eq!(lines.kept(), [&XID[..64], &ESR[..64]]);
let narrow: FaultLines<1, 5> = FaultLines::new();
narrow.observe("Xid:é13");
assert_eq!(
narrow.kept(),
["Xid:"],
"cut before a character the slot splits"
);
}
#[test]
fn the_first_fault_gives_the_kept_lines_and_each_fault_the_count() {
let kept = vec![String::from(XID), String::from(ESR)];
assert_eq!(
kernel_lines(1, &kept, 2),
[
format!("1 kernel: {XID}"),
format!("1 kernel: {ESR}"),
String::from(
"1 kernel: 2 Xid, rc and disabled-channel lines so far this boot, the first \
2 above"
),
]
);
assert_eq!(
kernel_lines(3, &kept, 240),
[
"3 kernel: 240 Xid, rc and disabled-channel lines so far this boot, the first 2 \
after fault 1"
]
);
assert_eq!(
kernel_lines(1, &[], 0),
["1 kernel: 0 Xid, rc and disabled-channel lines so far this boot"]
);
}
}
+47 -23
View File
@@ -3,7 +3,10 @@
//! goes on. When it does not and no other GPU serves Metal, every new
//! WindowServer is refused and dies, and the screen stays frozen: Stela then
//! stops as a boot without a GPU does, with which GPU was lost and what its
//! kernel driver said of it.
//! kernel driver said of it. A lost GPU whose driver said it stopped
//! answering is lost for good at once: no reopen can work on it, and one is
//! tried only once no client holds an object of the lost device, which a
//! client may never let go of.
use alloc::{format, string::String, vec::Vec};
use core::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
@@ -49,7 +52,7 @@ pub fn link_event(line: &str) -> Option<&'static str> {
/// Which recovery the port above a GPU that stopped answering still
/// allows, for one boot-log line. Stela tries none of them: the session
/// ends at the GPU's first failed reopen.
/// ends once the GPU is lost.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Recovery {
/// The port could not be read.
@@ -113,20 +116,23 @@ pub struct Gpu<'a> {
}
impl Gpu<'_> {
/// Whether the GPU is lost and will not reopen: a reopen failed and its
/// driver said it stopped answering (it then fails every later one), or
/// [`REOPEN_ATTEMPTS`] failed in a row over at least [`REOPEN_SPAN_MS`].
/// A lost GPU no reopen was tried on yet, or tried only within that
/// time, may still come back.
/// Whether the GPU is lost and will not reopen: its driver said it
/// stopped answering, after which every reopen fails, whether or not
/// one was tried yet; or [`REOPEN_ATTEMPTS`] failed in a row over at
/// least [`REOPEN_SPAN_MS`]. A lost GPU its driver said nothing of, with
/// no reopen tried yet or tried only within that time, may still come
/// back.
fn gone(&self) -> bool {
self.lost
&& match self.silent {
Some(_) => self.failed_reopens >= 1,
None => self.failed_reopens >= REOPEN_ATTEMPTS && self.failing_ms >= REOPEN_SPAN_MS,
}
&& (self.silent.is_some()
|| (self.failed_reopens >= REOPEN_ATTEMPTS && self.failing_ms >= REOPEN_SPAN_MS))
}
}
/// The plain start of [`verdict`]'s reason, before the details.
pub const LOST: &str = "The graphics card stopped working, and macOS cannot run without it. \
Details for a report: ";
/// Why the boot stops, once no GPU of `gpus` (those that serve Metal) can
/// serve macOS again; `None` while any of them works or may still reopen,
/// and for a boot that has none.
@@ -137,15 +143,22 @@ pub fn verdict(gpus: &[Gpu<'_>]) -> Option<String> {
let each: Vec<String> = gpus
.iter()
.map(|gpu| {
let tries = match gpu.failed_reopens {
1 => String::from("1 try"),
tries => format!("{tries} tries over {} s", gpu.failing_ms / 1000),
};
let error = gpu.error.unwrap_or("no error named");
let said = match gpu.silent {
Some(line) => format!("Its driver said: {line}"),
None => String::from("Its driver did not say that it left the bus"),
};
let tries = match gpu.failed_reopens {
0 => {
return format!(
"the GPU {} was lost while macOS ran and left the bus, so no reopen was \
tried. {said}",
gpu.name
);
}
1 => String::from("1 try"),
tries => format!("{tries} tries over {} s", gpu.failing_ms / 1000),
};
let error = gpu.error.unwrap_or("no error named");
format!(
"the GPU {} was lost while macOS ran and did not reopen ({tries}, last: \
{error}). {said}",
@@ -153,10 +166,7 @@ pub fn verdict(gpus: &[Gpu<'_>]) -> Option<String> {
)
})
.collect();
Some(format!(
"macOS cannot run without a GPU: {}",
each.join("; ")
))
Some(format!("{LOST}{}", each.join("; ")))
}
/// The kernel drivers' lines that a GPU stopped answering, the first of each
@@ -287,7 +297,6 @@ mod tests {
assert_eq!(verdict(&[gpu(false, 0, None)]), None);
// Lost, its connections still open: no reopen was tried.
assert_eq!(verdict(&[gpu(true, 0, None)]), None);
assert_eq!(verdict(&[gpu(true, 0, Some(GONE))]), None);
// One failed reopen with no word from the driver may be a passing
// refusal: the next client tries again.
assert_eq!(verdict(&[gpu(true, 1, None)]), None);
@@ -302,11 +311,26 @@ mod tests {
assert_eq!(verdict(&[gpu(false, 0, Some(GONE))]), None);
}
/// A client that keeps objects of the lost device keeps every reopen
/// from being tried: a GPU its driver said left the bus ends the session
/// all the same, where WindowServer was refused for 10 minutes until
/// macOS's watchdog panicked.
#[test]
fn a_gpu_off_the_bus_ends_the_session_once_lost_with_no_reopen_tried() {
let reason = verdict(&[gpu(true, 0, Some(GONE))]).expect("stops");
assert!(reason.starts_with(LOST));
assert!(reason[LOST.len()..].starts_with(
"the GPU 0000:02:00.0 was lost while macOS ran and left the bus, so no reopen was \
tried. Its driver said: nouveau 0000:02:00.0: stopped answering: BOOT_0 read"
));
}
#[test]
fn a_gpu_off_the_bus_ends_the_session_at_its_first_failed_reopen() {
let reason = verdict(&[gpu(true, 1, Some(GONE))]).expect("stops");
assert!(reason.starts_with(
"macOS cannot run without a GPU: the GPU 0000:02:00.0 was lost while macOS ran and \
assert!(reason.starts_with(LOST));
assert!(reason[LOST.len()..].starts_with(
"the GPU 0000:02:00.0 was lost while macOS ran and \
did not reopen (1 try, last: DeviceLost). Its driver said: nouveau 0000:02:00.0: \
stopped answering: BOOT_0 read ffffffff for 1004 ms; config vendor ffff"
));
+51 -2
View File
@@ -20,10 +20,12 @@ pub enum HostCall {
Export = 10,
Shutdown = 11,
Seek = 12,
BacklightInfo = 13,
BacklightSet = 14,
}
impl HostCall {
const ALL: [Self; 12] = [
const ALL: [Self; 14] = [
Self::Open,
Self::Close,
Self::Duplicate,
@@ -36,6 +38,8 @@ impl HostCall {
Self::Export,
Self::Shutdown,
Self::Seek,
Self::BacklightInfo,
Self::BacklightSet,
];
pub const fn code(self) -> u32 {
@@ -56,6 +60,8 @@ impl HostCall {
Self::Export => "export",
Self::Shutdown => "shutdown",
Self::Seek => "seek",
Self::BacklightInfo => "backlight-info",
Self::BacklightSet => "backlight-set",
}
}
}
@@ -74,11 +80,54 @@ impl core::fmt::Display for Request {
}
}
/// `DRM_IOCTL_AMDGPU_INFO`: `DRM_IOW(DRM_COMMAND_BASE + 0x05, struct
/// drm_amdgpu_info)`, 32 bytes, whose code no other driver's ioctl has.
pub const AMDGPU_INFO: u32 = 0x4020_6445;
/// `AMDGPU_INFO_HW_IP_COUNT`: how many engines of a hardware type the GPU
/// has.
pub const AMDGPU_INFO_HW_IP_COUNT: u32 = 0x03;
const EINVAL: i64 = -22;
/// Whether a DRM call's error `result` is its driver's answer to a probe,
/// which is no refusal: amdgpu answers `AMDGPU_INFO_HW_IP_COUNT` for a
/// hardware engine type the GPU lacks with EINVAL (`amdgpu_info_ioctl`),
/// and RADV asks about every type on every GPU. `query` is an
/// `AMDGPU_INFO` call's query, where it was kept.
pub fn probe_answer(request: u32, query: Option<u32>, result: i64) -> bool {
request == AMDGPU_INFO && query == Some(AMDGPU_INFO_HW_IP_COUNT) && result == EINVAL
}
#[cfg(test)]
mod tests {
use super::{HostCall, Request};
use super::{AMDGPU_INFO, AMDGPU_INFO_HW_IP_COUNT, HostCall, Request, probe_answer};
use alloc::format;
#[test]
fn an_engine_count_for_an_engine_the_gpu_lacks_is_an_answer() {
// igpu2's four lines: RADV's counts of UVD, VCE, UVD_ENC and VPE
// engines, which a Raphael iGPU has none of.
assert!(probe_answer(
AMDGPU_INFO,
Some(AMDGPU_INFO_HW_IP_COUNT),
-22
));
// Any other query, error or call stays a refusal, as does one whose
// query was not kept.
assert!(!probe_answer(
AMDGPU_INFO,
Some(AMDGPU_INFO_HW_IP_COUNT),
-14
));
assert!(!probe_answer(AMDGPU_INFO, Some(0x02), -22));
assert!(!probe_answer(AMDGPU_INFO, None, -22));
// DRM_IOCTL_NOUVEAU_GEM_NEW.
assert!(!probe_answer(
0xc030_6480,
Some(AMDGPU_INFO_HW_IP_COUNT),
-22
));
}
#[test]
fn host_calls_print_by_name_and_ioctls_in_hex() {
assert_eq!(format!("{}", Request(HostCall::Map.code())), "map");
File diff suppressed because it is too large. Load diff
+366
View File
@@ -0,0 +1,366 @@
//! The boot screen's GPU step and the log's `GPU SELECT` and `GPU FALLBACK`
//! lines, from what the selection chose ([`stela_drivers::gpu::selection`]),
//! which claims were refused, which GPUs their drivers bound and which
//! opened no Metal device. The engine prints what these answer; they read
//! nothing of the machine, so a test gives every kind of PC its whole text
//! (`gpu_step/tests.rs`), each stage a GPU chosen to draw may fail at too.
//!
//! A GPU chosen to draw that fails at its claim, its driver's probe or its
//! Metal device gives way to the next GPU the selection starts without it
//! ([`stela_drivers::gpu::selection::fall_back`]): one `GPU FALLBACK` line
//! names the GPU, the stage, its error and what draws in its place.
//!
//! The screen names the GPU that draws macOS by its market name, says which
//! other GPU shows the picture where one does, and says why a GPU that would
//! have drawn did not. A display adapter that needs nothing of the user, as
//! one left with the firmware beside the GPU that draws, is named in the log
//! alone.
use crate::gpu_status::{self, Reason};
use alloc::{format, string::String, vec::Vec};
use stela_drivers::gpu::{
Adapter, Vendor,
selection::{Choice, Found, Selection},
stack::{Candidate, metal_devices},
};
/// The step's title.
pub const TITLE: &str = "Starting the GPU";
/// How a line of the step shows on the screen.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mark {
/// The step ended well.
Ok,
/// The step ended without a GPU, or a line of its own warns.
Warn,
/// A line of its own that tells.
Info,
}
/// A display controller with a GPU stack whose claim was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Refused {
pub vendor: Vendor,
/// Its market name, or its maker alone.
pub name: String,
/// Its stack draws, so it would have drawn macOS.
pub draws: bool,
pub address: String,
pub device: u16,
pub reason: Reason,
/// The refusal's own words, for the screen as for the log.
pub why: String,
}
impl Refused {
/// `adapter`, whose stack draws or not, refused for `reason` in the
/// refusal's words `why`.
pub fn new(adapter: &Adapter, draws: bool, reason: Reason, why: &str) -> Self {
Self {
vendor: adapter.vendor,
name: adapter.name(),
draws,
address: format!("{}", adapter.address),
device: adapter.device,
reason,
why: String::from(why),
}
}
/// Its screen line ([`gpu_status::refused`]).
pub fn line(&self) -> String {
gpu_status::refused(
self.vendor,
&self.name,
&self.address,
self.device,
self.reason,
&self.why,
)
}
}
/// The step's lines when no GPU was claimed: the first ends the step. A
/// refused GPU says why, the first as the step's end; without one, the step
/// names the GPUs this PC has and what Stela needs ([`gpu_status::none`]),
/// `ports` being the makers whose GPUs this build drives. The display
/// adapters no stack drives are not named again: the log's `GPU SELECT`
/// lines say why each was not used.
pub fn not_started(
found: &[Adapter],
refused: &[Refused],
ports: &[Vendor],
) -> Vec<(Mark, String)> {
let Some((first, rest)) = refused.split_first() else {
return alloc::vec![(Mark::Warn, gpu_status::none(found, ports))];
};
let mut lines = alloc::vec![(Mark::Warn, first.line())];
lines.extend(rest.iter().map(|gpu| (Mark::Info, gpu.line())));
lines
}
/// A GPU its driver bound, as the step's end sees it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Bound<'a> {
/// Its market name, or its maker alone.
pub market: &'a str,
/// Its stack draws: the image holds its Vulkan driver.
pub draws: bool,
/// Its driver says it is built into the processor.
pub integrated: bool,
/// The firmware's picture may be on it: a screen hangs on its outputs.
pub shows_screen: bool,
}
/// The step's lines once GPUs bound, `bound` in the claims' order: the
/// first ends the step with the name of the GPU that is to draw macOS, as
/// [`metal_devices`] chooses it before any display is taken, and the
/// drawing GPUs that did not start in whose place it draws (`refused`, and
/// `unbound`, the names of drawing GPUs no driver bound). A refused GPU then
/// says why. A GPU that only shows the picture says so where a screen may
/// hang on it; elsewhere it needs nothing of the user, and the log has it.
/// `dark` names a GPU no driver bound whose screen, the one the PC started
/// on, went dark: where no bound GPU has a screen, the step says where
/// macOS shows instead ([`gpu_status::no_screen`]).
pub fn started(
bound: &[Bound],
unbound: &[&str],
refused: &[Refused],
dark: Option<&str>,
) -> Vec<(Mark, String)> {
let candidates: Vec<Candidate> = bound
.iter()
.map(|gpu| Candidate {
draws: gpu.draws,
integrated: gpu.integrated,
drives_display: false,
})
.collect();
let chosen = metal_devices(&candidates);
let drawer = chosen.serve.first().map(|&index| bound[index].market);
let failed: Vec<String> = refused
.iter()
.filter(|gpu| gpu.draws)
.map(|gpu| gpu.name.clone())
.chain(unbound.iter().map(|&name| String::from(name)))
.collect();
let mut lines = alloc::vec![(
Mark::Ok,
gpu_status::started(drawer, &failed, bound.first().map(|gpu| gpu.market)),
)];
lines.extend(refused.iter().map(|gpu| (Mark::Warn, gpu.line())));
// Without a GPU that draws, the first one is the step's own.
lines.extend(
bound
.iter()
.enumerate()
.filter(|&(index, gpu)| {
!chosen.serve.contains(&index)
&& gpu.shows_screen
&& (drawer.is_some() || index != 0)
})
.map(|(_, gpu)| (Mark::Info, gpu_status::shows_only(gpu.market, drawer))),
);
if let (Some(drawer), Some(dark)) = (drawer, dark)
&& !bound.iter().any(|gpu| gpu.shows_screen)
{
lines.push((Mark::Warn, gpu_status::no_screen(dark, drawer)));
}
lines
}
/// The stage at which a GPU started to draw macOS failed, which the log's
/// `GPU FALLBACK` line names with its error.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stage {
/// Its claim was refused, in the refusal's words.
Claim(String),
/// No kernel driver bound it: `what` says so as the start does ("nouveau
/// did not bind it", "nouveau's probe did not finish in 60 s"), and
/// `error` is the first error Linux reported in its probe.
Probe { what: String, error: Option<String> },
/// Its kernel driver `driver` bound it, and its Metal device did not
/// open, for `error`.
Metal { driver: String, error: String },
}
impl Stage {
/// The stage and its error, in words.
pub fn describe(&self) -> String {
match self {
Self::Claim(why) => format!("its claim was refused: {why}"),
Self::Probe {
what,
error: Some(error),
} => format!("its driver's probe failed: {what}; Linux's first error: {error}"),
Self::Probe { what, error: None } => {
format!("its driver's probe failed: {what}; Linux reported no error")
}
Self::Metal { driver, error } => format!(
"{driver} bound it, and its Metal device did not open: {error}; it still shows \
the screens wired to it"
),
}
}
}
/// What takes a failed GPU's place, by census index.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Next {
/// GPUs that were left with the firmware, claimed and started now.
Claimed(Vec<usize>),
/// A GPU that started beside it and draws in its place.
Drawing(usize),
/// None: no other GPU of the PC can draw.
Nothing,
}
impl Next {
/// What follows once GPUs could not draw, from the selection `before`
/// and the one made again without them, `after`
/// ([`stela_drivers::gpu::selection::fall_back`]): the GPUs it claims
/// newly, else `drawing`, a started GPU that draws now.
pub fn of(before: &Selection, after: &Selection, drawing: Option<usize>) -> Self {
let claimed = stela_drivers::gpu::selection::newly_claimed(before, after);
match (claimed.is_empty(), drawing) {
(false, _) => Self::Claimed(claimed),
(true, Some(drawing)) => Self::Drawing(drawing),
(true, None) => Self::Nothing,
}
}
/// In words; `name` names a GPU of the census.
pub fn describe(&self, name: &dyn Fn(usize) -> String) -> String {
match self {
Self::Claimed(claimed) => {
let names: Vec<String> = claimed.iter().map(|&index| name(index)).collect();
format!(
"the {} {} claimed and started in its place",
names.join(" and the "),
if names.len() == 1 { "is" } else { "are" }
)
}
Self::Drawing(index) => {
format!(
"the {}, started beside it, draws in its place",
name(*index)
)
}
Self::Nothing => String::from("no other GPU of this PC can draw in its place"),
}
}
}
/// The log's `GPU FALLBACK` line, without its prefix, for the GPU `failed`
/// of `adapters`, by census index, that failed at `stage`, and what took its
/// place: one line for each stage a GPU chosen to draw failed at.
pub fn fallback_line(adapters: &[Adapter], failed: usize, stage: &Stage, next: &Next) -> String {
let named = |index: usize| {
let adapter = &adapters[index];
format!("{} at {}", adapter.name(), adapter.address)
};
let adapter = &adapters[failed];
format!(
"{} {}: {}; {}",
adapter.address,
adapter.name(),
stage.describe(),
next.describe(&named)
)
}
/// The `GPU FALLBACK` lines of the claims, without their prefix: one for
/// each GPU whose claim was refused (`refused` gives its words) and that
/// would have started to draw had every claim succeeded, with what the
/// selection `chosen` started in its place.
pub fn refusal_lines(
adapters: &[Adapter],
found: &[Found],
chosen: &Selection,
refused: &[Refused],
) -> Vec<String> {
let ideal = stela_drivers::gpu::selection::select(found, |_| true);
let draws = |index: usize| found[index].stack.is_ok_and(|driven| driven.draws);
let drawing = chosen
.claimed
.iter()
.copied()
.find(|&index| chosen.choices[index] == Choice::First && draws(index));
let next = Next::of(&ideal, chosen, drawing);
(0..adapters.len())
.filter(|&index| {
chosen.choices[index] == Choice::Refused
&& ideal.choices[index] == Choice::First
&& draws(index)
})
.map(|index| {
let address = format!("{}", adapters[index].address);
let why = refused
.iter()
.find(|gpu| gpu.address == address)
.map_or_else(String::new, |gpu| gpu.why.clone());
fallback_line(adapters, index, &Stage::Claim(why), &next)
})
.collect()
}
/// The log's `GPU SELECT` lines, without their prefix: one for each display
/// controller of `adapters` with its address, IDs, name, kind and what was
/// chosen for it and why, `refused` saying why a claim was refused; then
/// the order the started ones were claimed in, which the display and the
/// Metal device follow, or that none started.
pub fn selection_lines(
adapters: &[Adapter],
found: &[Found],
chosen: &Selection,
refused: &[Refused],
) -> Vec<String> {
let named = |index: usize| {
let adapter = &adapters[index];
format!("{} at {}", adapter.name(), adapter.address)
};
let mut lines: Vec<String> = adapters
.iter()
.zip(found)
.enumerate()
.map(|(index, (adapter, found))| {
let kind = match found.stack {
Ok(driven) => format!("{}; ", driven.describe()),
Err(_) => String::new(),
};
let address = format!("{}", adapter.address);
let choice = match (
chosen.choices[index],
refused.iter().find(|gpu| gpu.address == address),
) {
(Choice::Refused, Some(gpu)) if !gpu.why.is_empty() => {
format!("not started: its claim was refused: {}", gpu.why)
}
(choice, _) => choice.describe(&named),
};
format!(
"{address} {:04x}:{:04x} rev {:02x} {}: {kind}{choice}",
adapter.vendor.pci_id(),
adapter.device,
adapter.revision,
adapter.name(),
)
})
.collect();
lines.push(match chosen.claimed.is_empty() {
true => String::from("started none"),
false => {
let order: Vec<String> = chosen.claimed.iter().map(|&index| named(index)).collect();
format!(
"started in this order: {}. A discrete GPU that draws gives the Metal device \
before an integrated one, and the next one does where it fails; the display is \
the first of them with a connected display, else the firmware's screen",
order.join(", ")
)
}
});
lines
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
+363
View File
@@ -0,0 +1,363 @@
//! Lines a GPU's boot log carries for whoever reads it after a failure on a
//! PC nobody here can test: a one-time summary of what the GPU and its
//! driver are, and a bound on lines that repeat.
use core::fmt;
/// Counts a keyed line's repeats and says which to print: the first, then
/// each power of two, so a line that repeats every frame costs a log a few
/// lines that still show how often it came. Keys are kept as hashes of
/// their text in a table of fixed size, so a count allocates nothing: a
/// `WARN` may come while the heap is exhausted.
pub struct Repeats {
/// Each tracked key's hash and count, the first `tracked` of them used.
counts: [(u64, u64); KEYS],
tracked: usize,
/// The count of every key past the table.
untracked: u64,
}
/// Keys a [`Repeats`] tracks; a key past them is printed at the powers of
/// two of the untracked count.
const KEYS: usize = 256;
/// How a counted line is printed: the suffix after its text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Seen {
/// Its first time: no suffix.
First,
/// A power of two of its count.
Times(u64),
/// A power of two of the count of the keys past the table.
PastTable(u64),
}
impl fmt::Display for Seen {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::First => Ok(()),
Self::Times(count) => write!(f, " (seen {count} times)"),
Self::PastTable(count) => write!(f, " ({count} past the log's table)"),
}
}
}
impl Default for Repeats {
fn default() -> Self {
Self::new()
}
}
impl Repeats {
pub const fn new() -> Self {
Self {
counts: [(0, 0); KEYS],
tracked: 0,
untracked: 0,
}
}
/// Count one more `key`: how to print it, `None` when it is not
/// printed.
pub fn count(&mut self, key: fmt::Arguments<'_>) -> Option<Seen> {
let hash = crate::repeated_lines::hash(key);
let slot = match self.counts[..self.tracked]
.iter()
.position(|&(known, _)| known == hash)
{
Some(slot) => Some(slot),
None if self.tracked < KEYS => {
self.counts[self.tracked] = (hash, 0);
self.tracked += 1;
Some(self.tracked - 1)
}
None => None,
};
let count = match slot {
Some(slot) => &mut self.counts[slot].1,
None => &mut self.untracked,
};
*count += 1;
let count = *count;
match (count.is_power_of_two(), slot.is_some()) {
(false, _) => None,
(true, true) if count == 1 => Some(Seen::First),
(true, true) => Some(Seen::Times(count)),
(true, false) => Some(Seen::PastTable(count)),
}
}
}
/// What a triager needs first of a GPU that opened, or failed to open, the
/// Metal service: printed once per GPU as `GPU SUMMARY …`.
pub struct Summary<'a> {
/// The GPU's PCI address.
pub address: &'a str,
pub vendor: u16,
pub device: u16,
pub revision: u8,
/// Its market name, or its maker alone.
pub market: &'a str,
/// The kernel driver's name.
pub driver: &'a str,
/// What the kernel driver says of itself and the chip: its version, the
/// chip's family, the firmware versions and the memory it reports.
pub facts: &'a str,
/// Whether the GPU is built into the processor, sharing system memory.
pub integrated: bool,
/// The memory Metal tells the guest it works in.
pub working_set: Option<u64>,
/// The Vulkan driver's heaps, `size/kind` each.
pub heaps: &'a str,
/// An integrated GPU's share of RAM: the bytes Linux holds of it and
/// its size. None where the memory plan gave it none.
pub share: Option<(u64, u64)>,
/// A discrete GPU's bound on Linux's pages, which its system-memory
/// buffers and its evictions from VRAM take: the bytes Linux holds and
/// the most it may hold. None where the plan set no bound.
pub pages: Option<(u64, u64)>,
/// Stela's heap: bytes in use and its size, which an integrated GPU
/// with no share takes its pages from.
pub heap_live: usize,
pub heap_total: usize,
}
impl core::fmt::Display for Summary<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mib = |bytes: u64| bytes >> 20;
write!(
f,
"GPU SUMMARY {} {:04x}:{:04x} rev {:#04x} {}: driver {}",
self.address, self.vendor, self.device, self.revision, self.market, self.driver
)?;
if !self.facts.is_empty() {
write!(f, " {}", self.facts)?;
}
match (self.integrated, self.share) {
(true, Some((held, limit))) => write!(
f,
"; integrated: its memory is the GPU's share of RAM, of which Linux holds {}M \
of {}M",
mib(held),
mib(limit)
)?,
(true, None) => write!(
f,
"; integrated with no share of RAM: its memory is system memory from Stela's \
heap of {}M ({}M in use)",
mib(self.heap_total as u64),
mib(self.heap_live as u64)
)?,
(false, _) => {
f.write_str("; discrete")?;
if let Some((held, limit)) = self.pages {
write!(
f,
", its system-memory buffers among Linux's pages, of which Linux holds \
{}M of the {}M it may hold",
mib(held),
mib(limit)
)?;
}
}
}
match self.working_set {
Some(bytes) => write!(f, "; Metal works in {}M", mib(bytes))?,
None => f.write_str("; the driver gave no memory size")?,
}
if self.heaps.is_empty() {
f.write_str("; no Vulkan device")
} else {
write!(f, "; Vulkan heaps{}", self.heaps)
}
}
}
/// What Linux held of its pages at a heap exhaustion stop, after the heap's
/// own figures: an integrated GPU's share (`share`), whose pages its GTT
/// takes, or the bound the plan set on Linux's pages beside a discrete GPU.
/// Written without allocating, as the heap is exhausted.
pub struct PagesAtStop {
pub held: u64,
pub limit: u64,
pub share: bool,
}
impl core::fmt::Display for PagesAtStop {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let (held, limit) = (self.held >> 20, self.limit >> 20);
match self.share {
true => write!(
f,
"; the GPU's share of RAM: Linux holds {held}M of {limit}M, its GTT's pages \
among them"
),
false => write!(
f,
"; Linux's pages, apart from the heap's own needs: it holds {held}M of the \
{limit}M it may hold"
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::{format, string::String, vec::Vec};
#[test]
fn a_repeated_line_prints_at_its_first_and_each_power_of_two() {
let mut repeats = Repeats::new();
let printed: Vec<(u64, String)> = (1..=17)
.filter_map(|n| {
repeats
.count(format_args!("{}:{}", "amdgpu_irq.c", 670))
.map(|seen| (n, format!("{seen}")))
})
.collect();
assert_eq!(
printed,
[
(1, String::new()),
(2, String::from(" (seen 2 times)")),
(4, String::from(" (seen 4 times)")),
(8, String::from(" (seen 8 times)")),
(16, String::from(" (seen 16 times)")),
]
);
// Another line is counted apart.
assert_eq!(
repeats.count(format_args!("dma-mapping.h:668")),
Some(Seen::First)
);
}
#[test]
fn keys_past_the_table_share_one_count() {
let mut repeats = Repeats::new();
for key in 0..KEYS {
assert_eq!(repeats.count(format_args!("{key}")), Some(Seen::First));
}
assert_eq!(repeats.count(format_args!("new")), Some(Seen::PastTable(1)));
assert_eq!(
format!("{}", Seen::PastTable(2)),
" (2 past the log's table)"
);
assert_eq!(
repeats.count(format_args!("other")),
Some(Seen::PastTable(2))
);
assert_eq!(repeats.count(format_args!("third")), None);
// A tracked key still counts on its own.
assert_eq!(repeats.count(format_args!("0")), Some(Seen::Times(2)));
}
/// A `WARN` may come while the heap is exhausted: the count takes no
/// memory beyond the table it was made with, and its suffix is written
/// from the count alone.
#[test]
fn a_count_allocates_nothing() {
use crate::native_memory::tests::allocation_failure;
let mut repeats = Repeats::new();
allocation_failure::arm(usize::MAX);
let seen = [(); 4].map(|()| repeats.count(format_args!("{}:{}", "nouveau_bo.c", 42)));
let observation = allocation_failure::disarm();
assert_eq!(observation.attempts, 0);
assert_eq!(
seen,
[
Some(Seen::First),
Some(Seen::Times(2)),
None,
Some(Seen::Times(4))
]
);
}
/// A heap stop names an integrated GPU's share as such, and the bound
/// beside a discrete GPU as Linux's pages, which are no share of RAM.
#[test]
fn a_heap_stop_names_linuxs_pages_as_the_plan_held_them() {
let pages = |share| {
format!(
"{}",
PagesAtStop {
held: 300 << 20,
limit: 392 << 20,
share,
}
)
};
assert_eq!(
pages(true),
"; the GPU's share of RAM: Linux holds 300M of 392M, its GTT's pages among them"
);
assert_eq!(
pages(false),
"; Linux's pages, apart from the heap's own needs: it holds 300M of the 392M it may \
hold"
);
}
#[test]
fn the_summary_names_the_gpu_and_where_its_memory_comes_from() {
let summary = Summary {
address: "0000:01:00.0",
vendor: 0x1002,
device: 0x13c0,
revision: 0xcb,
market: "AMD Radeon Graphics",
driver: "amdgpu",
facts: "3.64.0 family GC_10_3_6",
integrated: true,
working_set: Some(1512 << 20),
heaps: " 938M/host 1877M/local",
share: Some((480 << 20, 2560 << 20)),
pages: None,
heap_live: 512 << 20,
heap_total: 2816 << 20,
};
assert_eq!(
format!("{summary}"),
"GPU SUMMARY 0000:01:00.0 1002:13c0 rev 0xcb AMD Radeon Graphics: driver amdgpu \
3.64.0 family GC_10_3_6; integrated: its memory is the GPU's share of RAM, of \
which Linux holds 480M of 2560M; Metal works in 1512M; Vulkan heaps 938M/host \
1877M/local"
);
let summary = Summary {
share: None,
..summary
};
assert_eq!(
format!("{summary}"),
"GPU SUMMARY 0000:01:00.0 1002:13c0 rev 0xcb AMD Radeon Graphics: driver amdgpu \
3.64.0 family GC_10_3_6; integrated with no share of RAM: its memory is system \
memory from Stela's heap of 2816M (512M in use); Metal works in 1512M; Vulkan \
heaps 938M/host 1877M/local"
);
let summary = Summary {
integrated: false,
working_set: None,
heaps: "",
facts: "",
..summary
};
assert_eq!(
format!("{summary}"),
"GPU SUMMARY 0000:01:00.0 1002:13c0 rev 0xcb AMD Radeon Graphics: driver amdgpu; \
discrete; the driver gave no memory size; no Vulkan device"
);
// A discrete GPU's pages are held to the plan's bound, which is no
// share of RAM of its own.
let summary = Summary {
pages: Some((212 << 20, 876 << 20)),
..summary
};
assert_eq!(
format!("{summary}"),
"GPU SUMMARY 0000:01:00.0 1002:13c0 rev 0xcb AMD Radeon Graphics: driver amdgpu; \
discrete, its system-memory buffers among Linux's pages, of which Linux holds 212M \
of the 876M it may hold; the driver gave no memory size; no Vulkan device"
);
}
}
+108 -1
View File
@@ -8,7 +8,54 @@
//! The model has no radio. It is powered, has a stable locally administered
//! address, accepts scans and connection attempts and finds nothing, and has
//! no paired devices. That is a degraded answer, not Bluetooth, and the line
//! says so once. A host controller is not lent to the guest.
//! says so once. A host controller is not lent to the guest unless the boot
//! asks for it (`--bluetooth-lend`): it then sits behind the same module,
//! which falls back to the model when the controller fails or stalls, and
//! [`lend_line`] names it instead.
use alloc::{format, string::String};
/// The line for a boot that logs the guest's Bluetooth packets
/// (`--bluetooth-trace`): what is hidden of them, and what is not.
pub const TRACE_LINE: &str = "BLUETOOTH TRACE the guest's Bluetooth packets are logged masked: \
addresses keep their vendor half and last byte, and names, payloads and keys are hidden; \
the log still names nearby devices' classes and signal strengths, so keep it private \
until it has been checked\n";
/// Why a boot that asks to lend the host's controller (`--bluetooth-lend`)
/// does not, as its log line; `None` when nothing stops it, so the flag is
/// never ignored without a word. A boot without `--input` gives the guest
/// no Bluetooth controller at all; a host with no controller that started
/// has none to lend; and under `--idle-skip` the guest's clock leaps over
/// waits to the next deadline, and the bridge's wait for the controller's
/// answer is one in guest time, so every forwarded command would fall back
/// at once.
pub fn lend_refusal(input: bool, host_controller: bool, idle_skip: bool) -> Option<&'static str> {
if !input {
return Some(
"BLUETOOTH LEND not lent: the boot has no --input, so the guest has no Bluetooth \
controller\n",
);
}
if !host_controller {
return Some(
"BLUETOOTH LEND not lent: no host Bluetooth controller started, so the model \
answers alone\n",
);
}
idle_skip.then_some(
"BLUETOOTH LEND not lent: --idle-skip leaps the guest's clock over the bridge's wait \
for the controller's answers, so the model answers alone\n",
)
}
/// The line for a boot that lends the host's controller at `location` to
/// the guest behind Apple's module.
pub fn lend_line(location: &str) -> String {
format!(
"BLUETOOTH LEND the guest's controller is {location} behind Apple's module; \
it falls back to the model on failure\n"
)
}
/// The line for a boot that gives macOS host input, by whether the host
/// has a Bluetooth controller; `None` for a boot without host input.
@@ -40,6 +87,66 @@ mod tests {
}
}
/// Under `--idle-skip` the guest's clock leaps to the next deadline, the
/// bridge's wait for the controller among them, so a lent controller
/// would fall back at once: it is not lent, and the log says why.
#[test]
fn idle_skip_keeps_the_controller_from_being_lent_and_says_why() {
assert_eq!(lend_refusal(true, true, false), None);
let line = lend_refusal(true, true, true).expect("refused");
assert!(line.starts_with("BLUETOOTH LEND not lent: --idle-skip "));
assert!(line.contains("model"));
assert!(line.ends_with('\n') && line.matches('\n').count() == 1);
}
/// `--bluetooth-lend` is never dropped without a word: a boot without
/// host input, or a host with no controller that started, says why
/// nothing is lent, before `--idle-skip` is weighed.
#[test]
fn a_lend_with_no_input_or_no_controller_says_why_it_is_not_lent() {
for idle_skip in [false, true] {
let line = lend_refusal(false, true, idle_skip).expect("refused");
assert!(line.starts_with("BLUETOOTH LEND not lent: the boot has no --input"));
assert_eq!(lend_refusal(false, false, idle_skip), Some(line));
let line = lend_refusal(true, false, idle_skip).expect("refused");
assert!(line.starts_with("BLUETOOTH LEND not lent: no host Bluetooth controller"));
assert!(line.contains("model"));
}
for input in [false, true] {
for host_controller in [false, true] {
for idle_skip in [false, true] {
let line = lend_refusal(input, host_controller, idle_skip);
assert_eq!(line.is_none(), input && host_controller && !idle_skip);
assert!(line.is_none_or(|l| l.ends_with('\n') && l.matches('\n').count() == 1));
}
}
}
}
/// `--bluetooth-trace` says once what its lines hide and that the log
/// still needs checking before it is posted.
#[test]
fn the_capture_says_what_it_hides_and_that_the_log_stays_private() {
assert!(TRACE_LINE.starts_with("BLUETOOTH TRACE "));
for said in ["masked", "names", "keys", "hidden", "private"] {
assert!(TRACE_LINE.contains(said), "{said}");
}
assert!(TRACE_LINE.ends_with('\n') && TRACE_LINE.matches('\n').count() == 1);
}
/// `--bluetooth-lend`: the line names the controller lent, the module it
/// sits behind, and the fallback.
#[test]
fn a_lent_controller_is_named_with_its_fallback() {
let line = lend_line("xhci 0000:05:00.4 port 2.3");
assert_eq!(
line,
"BLUETOOTH LEND the guest's controller is xhci 0000:05:00.4 port 2.3 behind \
Apple's module; it falls back to the model on failure\n"
);
assert_eq!(line.matches('\n').count(), 1);
}
#[test]
fn a_host_controller_is_named_as_not_lent_and_a_boot_without_input_says_nothing() {
let line = model_line(true, true).expect("reported");
@@ -69,6 +69,37 @@ pub fn lock_scale(core_hz: u64) -> u64 {
.clamp(1, MAX_LOCK_SCALE)
}
/// What `--profile` multiplies the lock timeouts by: step timing makes
/// every fetch and exit slower, so a translated holder's critical section
/// and a stalled PE's hold both grow. A profiled cold boot on a 5.04 GHz
/// host (scale 1) stalled PEs for 193 ms, past `ticket-lock`'s 125 ms,
/// and the guest panicked "Ticket spinlock ... timeout"; four times gives
/// 500 ms.
pub const PROFILE_LOCK_FACTOR: u64 = 4;
/// The largest scale a profiled boot gets: 2 s for a ticket spinlock.
pub const MAX_PROFILED_LOCK_SCALE: u64 = MAX_LOCK_SCALE * 2;
/// The least scale any boot's lock timeouts get: a host as fast as the
/// modeled chip still stalls a PE for host work, a cold block's compile or
/// a translation read, and a warm boot stalled every PE for 104-162 ms,
/// past `ticket-lock`'s 125 ms. Twice gives 250 ms; a real deadlock still
/// panics within a second (`lock-panic`'s 0.5 s becomes 1 s).
pub const LOCK_SCALE_FLOOR: u64 = 2;
/// The scale this boot's lock timeouts get: the host's ([`lock_scale`]),
/// at least [`LOCK_SCALE_FLOOR`], times [`PROFILE_LOCK_FACTOR`] under
/// `--profile`.
pub fn boot_lock_scale(core_hz: u64, profile: bool) -> u64 {
let scale = lock_scale(core_hz).max(LOCK_SCALE_FLOOR);
match profile {
true => scale
.saturating_mul(PROFILE_LOCK_FACTOR)
.min(MAX_PROFILED_LOCK_SCALE),
false => scale,
}
}
/// The additions one timed run of the reference loop makes, each waiting
/// for the one before: 2,000,000 core cycles, 0.5 ms at 4 GHz.
pub const REFERENCE_ADDS: u64 = 2_000_000;
@@ -188,6 +219,32 @@ mod tests {
);
}
#[test]
fn profiling_widens_the_lock_timeouts() {
// The profiled boot that panicked on a ticket spinlock: 5.04 GHz.
assert_eq!(lock_scale(5_040_280_837), 1);
assert!(boot_lock_scale(5_040_280_837, true) >= 4);
// A slower host's own scale is multiplied too, up to the bound.
assert_eq!(boot_lock_scale(3_000_000_000, true), 8);
assert_eq!(boot_lock_scale(100_000_000, true), MAX_PROFILED_LOCK_SCALE);
assert!(boot_lock_scale(0, true) >= PROFILE_LOCK_FACTOR);
}
#[test]
fn every_boot_gets_at_least_the_floor_and_a_slower_host_its_own_scale() {
// 125 ms for a ticket spinlock left no margin for the 104-162 ms
// stalls of a warm boot: 250 ms.
assert_eq!(boot_lock_scale(5_040_280_837, false), LOCK_SCALE_FLOOR);
assert_eq!(boot_lock_scale(0, false), LOCK_SCALE_FLOOR);
assert_eq!(boot_lock_scale(1_100_000_000, false), 4);
assert_eq!(boot_lock_scale(100_000_000, false), MAX_LOCK_SCALE);
assert_eq!(
lock_scale_arguments(boot_lock_scale(5_040_280_837, false)),
" ml-timeout-ticket-lock-scale=2 ml-timeout-lock-scale=2 \
ml-timeout-lock-panic-scale=2"
);
}
#[test]
fn dependent_additions_show_the_core_clock() {
// 2,000,000 additions in 1,000,000 ticks of a 2 GHz TSC: 4 GHz.
+178
View File
@@ -0,0 +1,178 @@
//! What the home PE watches for in the guest's console while macOS runs:
//! a kernel panic that never resets the machine, and a console that has
//! gone quiet before macOS showed anything.
//!
//! XNU prints `panic(cpu N caller 0x...): message` at the start of a line
//! and then the panic log: the backtrace, `Panicked task`, the kernel
//! extensions in it, often a nested panic. On a Mac its watchdog or the PMU
//! resets the machine after that, which ends the run (`Stop::Reset`). A
//! panic whose handler hangs, as one with its other CPUs unanswered and no
//! watchdog armed yet, spins for good: a 2026-11-23 boot printed its panic
//! at 42.7 s and ran on for twenty minutes at one PC. [`Watch`] ends such a
//! run [`PANIC_HOLD_MILLIS`] after the panic's first line, time enough for
//! the rest of the panic log and for a reset that does come, unless the
//! boot asked to keep running (`--keep-running-on-panic`).
//!
//! A console with no line for [`STALL_MILLIS`] before the guest's first
//! frame reached the screen is only named, once a quiet stretch, as
//! `BOOT STALLED?`: macOS may still be working.
use alloc::string::String;
/// How long a panic is left to finish printing, or to reset the machine,
/// before the run stops: XNU writes its panic log within about a second,
/// and its watchdog mechanism resets within 10 s of arming
/// (`guest_timeouts::WATCHDOG_MECHANISM_SECONDS`).
pub const PANIC_HOLD_MILLIS: u64 = 30_000;
/// The lines after a panic's first that [`Watch`] counts as its log; more
/// are counted as this many.
pub const PANIC_LINES: u32 = 4096;
/// How long the console may stay quiet before the guest showed a frame
/// before the log names it.
pub const STALL_MILLIS: u64 = 120_000;
/// The most of a line [`Watch`] keeps to name it.
const KEPT_BYTES: usize = 240;
/// Whether `line`, from a line's start, begins XNU's panic header
/// `panic(cpu N caller ...)`. Only a line's start counts: a driver that
/// prints the word, or a header inside another line, is no panic.
pub fn begins_panic(line: &str) -> bool {
line.strip_prefix("panic(cpu ")
.is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
}
/// The first panic header seen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Panic {
/// When its line was written, in milliseconds.
pub at: u64,
/// Its line, at most [`KEPT_BYTES`] of it.
pub line: String,
/// The lines after it so far, at most [`PANIC_LINES`].
pub lines: u32,
}
/// What [`Watch::poll`] found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// A panic's first line arrived: the run stops after the hold, or with
/// `keep_running` goes on.
Panicked { line: String, keep_running: bool },
/// The hold after the panic ended with no reset: stop the run.
Stop(Panic),
/// The console has been quiet this many seconds before the guest's
/// first frame, since `last` (none: no line yet).
Stalled { seconds: u64, last: Option<String> },
}
#[derive(Debug, Default)]
pub struct Watch {
keep_running: bool,
/// When watching began, for a console that never printed.
began: Option<u64>,
panic: Option<Panic>,
/// [`Event::Panicked`] was given.
said: bool,
/// [`Event::Stop`] was given.
stopped: bool,
/// The last line with text, and when it came.
last: Option<(u64, String)>,
/// This quiet stretch was named.
warned: bool,
}
impl Watch {
pub const fn new() -> Self {
Self {
keep_running: false,
began: None,
panic: None,
said: false,
stopped: false,
last: None,
warned: false,
}
}
/// Go on after a panic instead of stopping (`--keep-running-on-panic`).
pub fn keep_running(&mut self, keep: bool) {
self.keep_running = keep;
}
/// The first panic, once one was seen.
pub fn panic(&self) -> Option<&Panic> {
self.panic.as_ref()
}
/// A console line or fragment written at `now` milliseconds; `beginning`
/// when it starts a line rather than continuing a long one.
pub fn line(&mut self, now: u64, text: &str, beginning: bool) {
if text.trim().is_empty() {
return;
}
self.last = Some((now, kept(text)));
self.warned = false;
match &mut self.panic {
Some(panic) => panic.lines = panic.lines.saturating_add(1).min(PANIC_LINES),
None if beginning && begins_panic(text) => {
self.panic = Some(Panic {
at: now,
line: kept(text),
lines: 0,
})
}
None => {}
}
}
/// What is due at `now` milliseconds; `shown` once the guest's first
/// frame reached the screen. Each event is given once (a stall once a
/// quiet stretch); a stop before a stall.
pub fn poll(&mut self, now: u64, shown: bool) -> Option<Event> {
let began = *self.began.get_or_insert(now);
if let Some(panic) = &self.panic {
if !self.said {
self.said = true;
return Some(Event::Panicked {
line: panic.line.clone(),
keep_running: self.keep_running,
});
}
if !self.keep_running
&& !self.stopped
&& now.saturating_sub(panic.at) >= PANIC_HOLD_MILLIS
{
self.stopped = true;
return Some(Event::Stop(panic.clone()));
}
}
let since = self.last.as_ref().map_or(began, |(at, _)| *at);
let quiet = now.saturating_sub(since);
if !shown && !self.warned && quiet >= STALL_MILLIS {
self.warned = true;
return Some(Event::Stalled {
seconds: quiet / 1000,
last: self.last.as_ref().map(|(_, line)| line.clone()),
});
}
None
}
}
/// At most [`KEPT_BYTES`] of `text`, cut at a character's boundary.
fn kept(text: &str) -> String {
let mut end = text.len().min(KEPT_BYTES);
while !text.is_char_boundary(end) {
end -= 1;
}
let mut line = String::from(text[..end].trim_end());
if end < text.len() {
line.push_str(" ...");
}
line
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,194 @@
use super::*;
use crate::console_lines::Lines;
use alloc::{string::String, vec::Vec};
/// The console of the 2026-11-23 boot that panicked at 42.7 s and then spun
/// at one PC for twenty minutes, around its panic, as XNU printed it: a
/// line that only mentions panics first, the nested panic's log, then the
/// original header and its log.
const PANICKED: &str = "AppleInterruptControllerV2::start: Num Shared Timestamps == 16\n\
Reconfig Watchdog: ICC = 360000000\n\
panic flow Config Engine Trigger NOT found\n\
IOReturn AppleSEPManager::_setPowerState(unsigned long *): power state 0 -> 2\n\
Nested panic detected - entry count: 2 panic_caller: 0xfffffe003acdbef4\n\
Kernel text exec slide: 0x0000000033340000\n\
Panicked thread: 0xfffffe2be43b0900, backtrace: 0xfffffe83e7f66b80, tid: 497\n\
\t\t lr: 0xfffffe003a397f3c fp: 0xfffffe83e7f66c00\n\
\t pc: 0xfffffe0039e19768 cpsr: 0x604013c8 esr: 0x0000000096000005 far: 0x0000000000000124\r\n\
Nested panic string:\n\
\n\
<end nested panic string>\n\
panic(cpu 0 caller 0xfffffe003acd0158): Ticket spinlock[0xfffffe003b18d000] timeout after 4243396 ticks; cticket: 0x9, nticket: 0xa, waiting for 0x9, current owner: 0 (on CPU -1), start time: 313898759, now: 318142155, timeout: 3000000 @lock_ticket.c:399\n\
Debugger message: panic\n\
Memory ID: 0x0\n\
Kernel version: Darwin Kernel Version 27.2.0: Wed Oct 14 23:48:16 PDT 2026; root:xnu-13432.41.4~25/RELEASE_ARM64_T8112\n\
Paniclog version: 16\n\
CORE 0 is the one that panicked. Check the full backtrace for details.\n\
CORE 1: PC=0x0000000000000000, LR=0x0000000000000000, FP=0x0000000000000000\n\
Panicked task 0xfffffe2be4034d80: 0 pages, 163 threads: pid 0: kernel_task\n\
Panicked thread: 0xfffffe2be43b0900, backtrace: 0xfffffe83e7f666c0, tid: 497\n\
\t\t lr: 0xfffffe003a3984e0 fp: 0xfffffe83e7f66760\n";
/// The 42.7 s boot's header, as the watch keeps it.
const HEADER: &str = "panic(cpu 0 caller 0xfffffe003acd0158): Ticket spinlock[0xfffffe003b18d000] \
timeout after 4243396 ticks; cticket: 0x9, nticket: 0xa, waiting for 0x9, current owner: 0 \
(on CPU -1), start time: 313898759, now: 318142155, timeout: 3000000 @lock_ticket.c:399";
/// Feed `console` to `watch` through the UART's line assembly in chunks of
/// `chunk` bytes, one millisecond a chunk from `start`, as the home PE
/// writes the lines the UART ended; the time after the last chunk.
fn feed(watch: &mut Watch, console: &[u8], chunk: usize, start: u64) -> u64 {
let mut lines = Lines::default();
let mut now = start;
for piece in console.chunks(chunk) {
for &byte in piece {
if let Some(line) = lines.push(byte) {
watch.line(now, &line.text, line.beginning);
}
}
now += 1;
}
now
}
#[test]
fn a_panic_header_split_across_console_chunks_is_seen_once_whole() {
for chunk in [1, 3, 7, 64, 4096] {
let mut watch = Watch::new();
let end = feed(&mut watch, PANICKED.as_bytes(), chunk, 42_000);
let panic = watch.panic().expect("the header");
assert!(
panic
.line
.starts_with("panic(cpu 0 caller 0xfffffe003acd0158): Ticket spinlock")
);
assert!(panic.line.len() <= KEPT_BYTES + 4, "{}", panic.line);
assert!(HEADER.starts_with(panic.line.trim_end_matches(" ...")));
// Its log after it: every line with text, not the header itself.
assert_eq!(panic.lines, 9, "chunk {chunk}");
assert!(panic.at >= 42_000 && panic.at < end);
}
}
#[test]
fn the_run_stops_after_the_hold_when_no_reset_came() {
let mut watch = Watch::new();
assert_eq!(watch.poll(39_553, false), None);
feed(&mut watch, PANICKED.as_bytes(), 61, 42_700);
let at = watch.panic().unwrap().at;
match watch.poll(at + 1, false) {
Some(Event::Panicked { line, keep_running }) => {
assert!(line.starts_with("panic(cpu 0 "));
assert!(!keep_running);
}
other => panic!("{other:?}"),
}
// The panic's log and a reset that may still come get the hold.
assert_eq!(watch.poll(at + PANIC_HOLD_MILLIS - 1, false), None);
match watch.poll(at + PANIC_HOLD_MILLIS, false) {
Some(Event::Stop(panic)) => {
assert_eq!(panic.at, at);
assert_eq!(panic.lines, 9);
}
other => panic!("{other:?}"),
}
// Once.
assert_eq!(watch.poll(at + PANIC_HOLD_MILLIS + 1, true), None);
}
#[test]
fn keep_running_names_the_panic_and_never_stops() {
let mut watch = Watch::new();
watch.keep_running(true);
feed(&mut watch, PANICKED.as_bytes(), 4096, 42_700);
assert!(matches!(
watch.poll(42_701, false),
Some(Event::Panicked {
keep_running: true,
..
})
));
assert_eq!(watch.poll(42_700 + 20 * PANIC_HOLD_MILLIS, true), None);
}
#[test]
fn lines_that_only_mention_a_panic_are_no_panic() {
let mut watch = Watch::new();
let console = "kernel panic medic: nothing to report\n\
panic flow Config Engine Trigger NOT found\n\
AppleImage4: panic-on-failure policy=0 image4_panic(cpu 0) not taken\n\
Nested panic detected - entry count: 2\n\
driver: panic(cpu 1 caller 0x1000): ordinary data\n\
panic(cpu x caller 0x1000): not XNU's header\n\
Panicked task 0xfffffe2be4034d80: 0 pages\n\
PANIC(cpu 0 caller 0x1): another case\n";
feed(&mut watch, console.as_bytes(), 5, 1_000);
assert_eq!(watch.panic(), None);
assert_eq!(watch.poll(1_000 + 10 * PANIC_HOLD_MILLIS, true), None);
for line in console.lines() {
assert!(!begins_panic(line.trim_start()), "{line}");
}
}
#[test]
fn a_header_inside_a_long_line_s_continuation_is_no_panic() {
let mut watch = Watch::new();
let mut console: Vec<u8> = core::iter::repeat_n(b'x', 1024).collect();
console.extend_from_slice(b"panic(cpu 0 caller 0x1000): inside another line\n");
feed(&mut watch, &console, 100, 0);
assert_eq!(watch.panic(), None);
}
#[test]
fn a_quiet_console_before_the_first_frame_is_named_once_a_stretch() {
let mut watch = Watch::new();
assert_eq!(watch.poll(40_000, false), None);
watch.line(41_000, "AppleSEPManager::_setPowerState 0 -> 2", true);
assert_eq!(watch.poll(41_000 + STALL_MILLIS - 1, false), None);
assert_eq!(
watch.poll(41_000 + STALL_MILLIS, false),
Some(Event::Stalled {
seconds: STALL_MILLIS / 1000,
last: Some(String::from("AppleSEPManager::_setPowerState 0 -> 2")),
})
);
// Not again in the same stretch.
assert_eq!(watch.poll(41_000 + 5 * STALL_MILLIS, false), None);
// A new line starts a new stretch; blank lines do not.
watch.line(800_000, "IOConsoleUsers: gIOScreenLockState 3", true);
watch.line(900_000, " ", true);
assert_eq!(watch.poll(800_000 + STALL_MILLIS - 1, false), None);
assert!(matches!(
watch.poll(800_000 + STALL_MILLIS, false),
Some(Event::Stalled { seconds: 120, .. })
));
}
#[test]
fn a_console_that_never_printed_is_named_from_when_watching_began() {
let mut watch = Watch::new();
assert_eq!(watch.poll(10_000, false), None);
assert_eq!(
watch.poll(10_000 + STALL_MILLIS, false),
Some(Event::Stalled {
seconds: STALL_MILLIS / 1000,
last: None
})
);
}
#[test]
fn a_quiet_console_after_the_guest_s_first_frame_is_not_named() {
let mut watch = Watch::new();
watch.line(0, "loginwindow: started", true);
assert_eq!(watch.poll(10 * STALL_MILLIS, true), None);
}
#[test]
fn a_kept_line_is_cut_at_a_character_boundary() {
let long = "é".repeat(KEPT_BYTES);
let line = kept(&long);
assert!(line.ends_with(" ..."));
assert!(line.len() <= KEPT_BYTES + 4);
assert_eq!(kept("short "), "short");
}
+59
View File
@@ -1002,6 +1002,65 @@ impl Heap {
block
}
/// Allocate zeroed storage for a Linux nonblocking (`GFP_ATOMIC`) caller.
///
/// Unlike [`Self::try_allocate_zeroed`], which returns `NULL` on a single
/// contended lock attempt, this serves small objects from this core's
/// local cache when cores are tagged and otherwise spins with local
/// interrupts masked until another processor releases the heap lock. That
/// matches Linux's `kmalloc(GFP_ATOMIC)` (`mm/slub.c`), which never sleeps
/// or reclaims but still waits on its spinlock. Without this, concurrent
/// allocation on other cores causes `amdgpu_dm_crtc_set_vblank`
/// (`amdgpu_dm_crtc.c:370`) to fail spuriously with `-ENOMEM`, triggering
/// `CRTC_GET_SEQUENCE` `-ENOMEM` and `drm_vblank_put` underflow warnings
/// (`drm_vblank.c:1271`) because `dm_arm_vblank_event_pre_programming`
/// (`amdgpu_dm.c:10491`) ignores `drm_crtc_vblank_get`'s return value.
///
/// # Safety
/// Same ownership, exact-layout `GlobalAlloc::dealloc`, and non-reentrancy
/// contract as [`Self::try_allocate`]: NMI, fault handlers, and callers
/// already holding this heap's lock on the current processor must not call
/// this function.
#[cfg_attr(
not(test),
allow(
dead_code,
reason = "nonblocking GFP_ATOMIC entry for the retained Linux GPU heap registration"
)
)]
pub unsafe fn allocate_atomic_zeroed(&self, layout: Layout) -> *mut u8 {
if layout.size() == 0 || self.stopping() {
return ptr::null_mut();
}
let class = class(layout);
let cpu = self.cpu();
let block = if let (Some(class), Some(cpu)) = (class, cpu) {
let flags = interrupts_off();
// SAFETY: on this core, with interrupts disabled.
let block = unsafe { self.take_cached(cpu, class) };
restore_interrupts(flags);
block
} else {
let guard = self.lock();
// SAFETY: this guard exclusively protects the heap state. The
// shared body checks initialization before accessing backing storage.
let block = unsafe { allocate_locked(&mut *self.state.get(), layout, class) };
drop(guard);
block
};
if !block.is_null() {
if class.is_none() {
tracked(block, layout.size(), true);
}
if let Some(cpu) = cpu {
self.count_own(cpu, layout, class, true);
}
// SAFETY: successful allocation gives this full payload exclusively.
unsafe { block.write_bytes(0, layout.size()) };
}
block
}
/// Select whole, zeroed pages inside a CPU interval from this same heap.
/// No reservation or CPU-to-physical relationship is inferred here.
/// Invalid geometry and exhaustion change no free-list bytes/accounting.
+53
View File
@@ -310,6 +310,59 @@ fn attempted_zeroed_reuse_keeps_other_live_payloads_and_global_free_rules() {
assert!(heap.usage().carved > 0);
}
#[test]
fn atomic_zeroed_allocation_waits_for_a_contended_lock_and_zeroes_reused_bytes() {
use core::sync::atomic::AtomicBool;
let heap = Heap::new();
let mut ram = backing();
let layout = Layout::from_size_align(64, 16).unwrap();
// SAFETY: uninitialized heap and zero-sized layout return NULL without
// touching backing storage.
unsafe {
assert!(heap.allocate_atomic_zeroed(layout).is_null());
heap.initialize(ram.0.as_mut_ptr(), ram.0.len());
assert!(
heap.allocate_atomic_zeroed(Layout::from_size_align(0, 16).unwrap())
.is_null()
);
let dirty = heap.alloc(layout);
assert!(!dirty.is_null());
dirty.write_bytes(0xa5, layout.size());
heap.dealloc(dirty, layout);
}
let entered = AtomicBool::new(false);
let guard = heap.lock();
let address = std::thread::scope(|scope| {
let handle = scope.spawn(|| {
entered.store(true, Ordering::Release);
// SAFETY: initialized backing stays live across the scope; the
// main thread releases its lock below so this spins and succeeds.
let block = unsafe { heap.allocate_atomic_zeroed(layout) };
block as usize
});
while !entered.load(Ordering::Acquire) {
std::thread::yield_now();
}
// Let the worker enter the spin path before dropping the lock.
std::thread::sleep(std::time::Duration::from_millis(5));
drop(guard);
handle.join().unwrap()
});
let block = address as *mut u8;
assert!(!block.is_null());
// SAFETY: exclusive freshly allocated block of `layout`.
unsafe {
assert!(
core::slice::from_raw_parts(block, layout.size())
.iter()
.all(|byte| *byte == 0)
);
heap.dealloc(block, layout);
}
assert_eq!(heap.usage().live, 0);
}
#[test]
fn attempted_general_alignment_zeroing_and_ordinary_free_coalesce() {
let heap = Heap::new();
+350
View File
@@ -0,0 +1,350 @@
//! `--host-core on` (`options::HOST_CORE`): one host processor beyond the
//! guest's PEs that runs the host's own work, the service turns and the
//! GPUs' pump, so that PE 0's core runs guest code where it served before.
//!
//! The core is started like a PE's (its record, descriptors, shootdown slot
//! and counter agreement), then given no PE: macOS sees exactly the PEs it
//! sees without the option. Every step that cannot be checked leaves the
//! boot as it is without it, with a line saying why:
//!
//! - [`plan`]: before anything is reserved, whether a processor is left
//! beyond the PEs, and the run is parallel.
//! - [`confirm`]: once the processors started, whether the last one, the
//! host core's, did, and the reservation kept the count it was planned
//! with.
//! - [`Channel::self_check`]: before the guest starts, the host core must
//! answer a ping through the [`Channel`] within its limit, or it never
//! serves and PE 0 keeps everything ([`State::Fallback`]).
//! - [`Channel::covers`]: PE 0 leaves the GPUs' pump to the host core only
//! while the host core serves and its beat is fresh; a stalled host core
//! gives the work back to PE 0 at once.
//!
//! The [`Channel`] has one poster (the boot processor) and one taker (the
//! host core): a request word with a sequence number, an answer word, the
//! state and the beat.
use core::sync::atomic::{AtomicU8, AtomicU64, Ordering};
/// What [`plan`] makes of the option.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Plan {
/// Not asked for: the boot reserves its PEs alone.
Off,
/// Asked for but not possible: the boot reserves its PEs alone and
/// says why.
Refused(&'static str),
/// Reserve `executors` processors: the PEs and the host core, last.
Reserve { executors: usize },
}
impl Plan {
/// The processors to reserve for `pes` PEs under this plan.
pub const fn executors(self, pes: usize) -> usize {
match self {
Self::Reserve { executors } => executors,
Self::Off | Self::Refused(_) => pes,
}
}
}
/// Whether a host core is reserved beside `pes` PEs: `wanted` is the
/// option, `parallel` whether every PE runs on a core of its own, and
/// `assignable` how many processors the capture can start (the boot
/// processor among them).
pub fn plan(wanted: bool, parallel: bool, pes: usize, assignable: usize) -> Plan {
if !wanted {
return Plan::Off;
}
if !parallel || pes < 1 {
return Plan::Refused("the PEs run serialized on one processor");
}
match pes.checked_add(1) {
Some(executors) if executors <= assignable => Plan::Reserve { executors },
_ => Plan::Refused("no processor is left beyond the guest's PEs"),
}
}
/// Whether the host core exists once the processors started: the plan
/// reserved `planned` (PEs and the host core), the reservation kept
/// `reserved` (fewer without a startup page), and `started` started, the
/// boot processor among them. The host core is the last slot, so a host
/// core that did not start loses only itself.
pub fn confirm(planned: usize, reserved: usize, started: usize) -> Result<(), &'static str> {
if reserved != planned {
return Err("the reservation kept fewer processors than planned");
}
if started == planned {
return Ok(());
}
if started + 1 == planned {
Err("the host core's processor did not start")
} else {
Err("a PE's processor did not start, and the ones after it with it")
}
}
/// Where the host core stands ([`Channel::state`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
/// No host core: PE 0 serves as without the option.
Off,
/// The self-check's ping is out.
Checking,
/// It answered: it serves and pumps.
Serving,
/// It did not answer in time, or was stopped: it serves nothing and PE
/// 0 keeps everything. A late answer does not change this.
Fallback,
/// The run ended and it acknowledged its stop.
Stopped,
}
impl State {
const ALL: [Self; 5] = [
Self::Off,
Self::Checking,
Self::Serving,
Self::Fallback,
Self::Stopped,
];
pub const fn name(self) -> &'static str {
match self {
Self::Off => "off",
Self::Checking => "checking",
Self::Serving => "serving",
Self::Fallback => "fallback",
Self::Stopped => "stopped",
}
}
}
/// A request to the host core.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Request {
/// Answer, and nothing else: the self-check.
Ping,
/// Answer, then serve nothing more.
Stop,
}
const PING: u64 = 1;
const STOP: u64 = 2;
const KIND_BITS: u32 = 2;
/// What the host core does in one pass of its loop ([`Channel::turn`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Turn {
/// Serve the host's work and pump.
Serve,
/// Nothing to do: wait a little.
Idle,
/// Leave the loop: the run ends.
Leave,
}
/// The boot processor's line to the host core.
pub struct Channel {
/// The last request: its sequence number above [`KIND_BITS`], then its
/// kind. Zero before the first.
request: AtomicU64,
/// The sequence number of the last request answered.
answer: AtomicU64,
state: AtomicU8,
/// The counter value at the host core's last pass while serving.
beat: AtomicU64,
}
impl Channel {
pub const fn new() -> Self {
Self {
request: AtomicU64::new(0),
answer: AtomicU64::new(0),
state: AtomicU8::new(0),
beat: AtomicU64::new(0),
}
}
pub fn state(&self) -> State {
State::ALL[usize::from(self.state.load(Ordering::Acquire)).min(State::ALL.len() - 1)]
}
fn set(&self, state: State) {
self.state.store(state as u8, Ordering::Release);
}
/// Post `request`, the boot processor's side: its sequence number. One
/// poster only.
pub fn post(&self, request: Request) -> u64 {
let seq = (self.request.load(Ordering::Relaxed) >> KIND_BITS) + 1;
let kind = match request {
Request::Ping => PING,
Request::Stop => STOP,
};
self.request
.store(seq << KIND_BITS | kind, Ordering::Release);
seq
}
/// Whether the request of `seq` was answered.
pub fn answered(&self, seq: u64) -> bool {
self.answer.load(Ordering::Acquire) >= seq
}
/// The host core's side: the request not answered yet, if any.
pub fn take(&self) -> Option<(u64, Request)> {
let word = self.request.load(Ordering::Acquire);
let seq = word >> KIND_BITS;
if seq == 0 || self.answered(seq) {
return None;
}
let request = match word & ((1 << KIND_BITS) - 1) {
STOP => Request::Stop,
_ => Request::Ping,
};
Some((seq, request))
}
fn answer(&self, seq: u64) {
self.answer.fetch_max(seq, Ordering::Release);
}
/// One pass of the host core's loop at counter value `now`: it answers
/// the request waiting, and serves only while [`State::Serving`],
/// beating as it does.
pub fn turn(&self, now: u64) -> Turn {
if let Some((seq, request)) = self.take() {
self.answer(seq);
if request == Request::Stop {
return Turn::Leave;
}
}
match self.state() {
State::Serving => {
self.beat.store(now, Ordering::Release);
Turn::Serve
}
State::Stopped => Turn::Leave,
State::Off | State::Checking | State::Fallback => Turn::Idle,
}
}
/// The boot processor's self-check before the guest starts: a ping,
/// then up to `limit` ticks of `now` for its answer, `wait` between
/// looks. Serving with the ticks it took, or [`State::Fallback`] with
/// why.
pub fn self_check(
&self,
mut now: impl FnMut() -> u64,
limit: u64,
mut wait: impl FnMut(),
) -> Result<u64, &'static str> {
self.set(State::Checking);
let seq = self.post(Request::Ping);
let start = now();
loop {
let at = now();
if self.answered(seq) {
self.beat.store(at, Ordering::Release);
self.set(State::Serving);
return Ok(at.wrapping_sub(start));
}
if at.wrapping_sub(start) >= limit {
self.set(State::Fallback);
return Err("the host core did not answer its ping in time");
}
wait();
}
}
/// Whether the host core takes the work PE 0 would leave it at counter
/// value `now`: serving, and its last pass less than `stale` ago.
pub fn covers(&self, now: u64, stale: u64) -> bool {
if self.state() != State::Serving {
return false;
}
let since = now.wrapping_sub(self.beat.load(Ordering::Acquire)) as i64;
(0..stale as i64).contains(&since) || since < 0 && since > -(stale as i64)
}
/// The run's end, on the boot processor: a host core that may serve is
/// told to stop and given up to `limit` ticks to acknowledge, after
/// which nothing has it serve. Whether it acknowledged (true when there
/// was nothing to stop).
pub fn stop(&self, mut now: impl FnMut() -> u64, limit: u64, mut wait: impl FnMut()) -> bool {
let state = self.state();
if matches!(state, State::Off | State::Stopped) {
return true;
}
// Nothing serves from here on, whether or not it answers.
self.set(State::Fallback);
let seq = self.post(Request::Stop);
let start = now();
let acknowledged = loop {
if self.answered(seq) {
break true;
}
if now().wrapping_sub(start) >= limit {
break false;
}
wait();
};
self.set(State::Stopped);
acknowledged
}
}
impl Default for Channel {
fn default() -> Self {
Self::new()
}
}
/// Who ran a service turn, for each one's share of the host's work.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Taker {
/// A PE that waits for an interrupt.
Waiting = 0,
/// The boot PE, PE 0.
Boot = 1,
/// The host core.
HostCore = 2,
}
/// The ticks each [`Taker`] served since the last [`Shares::take`].
pub struct Shares([AtomicU64; 3]);
impl Shares {
pub const fn new() -> Self {
Self([const { AtomicU64::new(0) }; 3])
}
pub fn add(&self, taker: Taker, ticks: u64) {
self.0[taker as usize].fetch_add(ticks, Ordering::Relaxed);
}
/// Each taker's ticks, in [`Taker`] order, and their sum, cleared.
pub fn take(&self) -> ([u64; 3], u64) {
let ticks = self.0.each_ref().map(|t| t.swap(0, Ordering::Relaxed));
(
ticks,
ticks.iter().fold(0u64, |sum, t| sum.saturating_add(*t)),
)
}
}
impl Default for Shares {
fn default() -> Self {
Self::new()
}
}
/// `part` of `total` in whole percent, 0 of nothing.
pub fn percent(part: u64, total: u64) -> u64 {
if total == 0 {
return 0;
}
(u128::from(part) * 100 / u128::from(total)) as u64
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,229 @@
extern crate std;
use super::*;
use core::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
#[test]
fn the_plan_reserves_one_more_only_when_asked_parallel_and_room_is_left() {
assert_eq!(plan(false, true, 8, 16), Plan::Off);
assert_eq!(plan(true, true, 8, 16), Plan::Reserve { executors: 9 });
// The FA608PP: 8 PEs of 16 threads leaves seven spare.
assert_eq!(Plan::Reserve { executors: 9 }.executors(8), 9);
// Exactly one spare is enough; none is not.
assert_eq!(plan(true, true, 15, 16), Plan::Reserve { executors: 16 });
assert!(matches!(plan(true, true, 16, 16), Plan::Refused(_)));
assert!(matches!(plan(true, true, 64, 64), Plan::Refused(_)));
assert!(matches!(
plan(true, true, usize::MAX, usize::MAX),
Plan::Refused(_)
));
// Serialized: one processor runs every PE, so there is nothing to add.
assert!(matches!(plan(true, false, 1, 16), Plan::Refused(_)));
assert!(matches!(plan(true, true, 0, 16), Plan::Refused(_)));
// Off or refused, the boot reserves its PEs alone: fail closed.
for plan in [Plan::Off, plan(true, true, 16, 16), plan(true, false, 1, 4)] {
assert_eq!(plan.executors(16), 16);
}
}
#[test]
fn the_host_core_exists_only_when_every_planned_processor_started() {
assert_eq!(confirm(9, 9, 9), Ok(()));
// The host core's own slot, the last, failed: the PEs are whole.
assert!(confirm(9, 9, 8).is_err());
// An earlier slot failed and took the rest with it.
assert!(confirm(9, 9, 5).is_err());
// No startup page: the reservation fell back to one processor.
assert!(confirm(9, 1, 1).is_err());
assert!(confirm(9, 8, 8).is_err());
}
/// A counter that moves one tick a look, for the boot processor's waits.
fn ticking() -> impl FnMut() -> u64 {
let now = Cell::new(0u64);
move || {
now.set(now.get() + 1);
now.get()
}
}
#[test]
fn a_ping_answered_in_time_has_the_host_core_serve() {
let channel = Channel::new();
assert_eq!(channel.state(), State::Off);
// Nothing waits and nothing is served before the check.
assert_eq!(channel.take(), None);
assert_eq!(channel.turn(0), Turn::Idle);
// The host core answers on the boot processor's third look.
let mut looks = 0;
let took = channel.self_check(ticking(), 100, || {
looks += 1;
if looks == 3 {
assert_eq!(channel.state(), State::Checking);
assert_eq!(channel.turn(5), Turn::Idle);
}
});
assert!(took.is_ok(), "{took:?}");
assert_eq!(channel.state(), State::Serving);
// Answered once: the next pass finds nothing to answer, and serves.
assert_eq!(channel.take(), None);
assert_eq!(channel.turn(10), Turn::Serve);
}
#[test]
fn an_unanswered_ping_falls_back_and_a_late_answer_changes_nothing() {
let channel = Channel::new();
let took = channel.self_check(ticking(), 50, || {});
assert!(took.is_err());
assert_eq!(channel.state(), State::Fallback);
// The host core wakes late: it answers, but never serves.
assert_eq!(channel.turn(1_000), Turn::Idle);
assert_eq!(channel.state(), State::Fallback);
assert!(!channel.covers(1_000, 100));
assert_eq!(channel.turn(2_000), Turn::Idle);
}
#[test]
fn pe0_leaves_the_pump_only_to_a_serving_host_core_with_a_fresh_beat() {
let channel = Channel::new();
assert!(!channel.covers(0, 100));
channel
.self_check(ticking(), 100, || {
channel.turn(0);
})
.unwrap();
assert_eq!(channel.turn(1_000), Turn::Serve);
assert!(channel.covers(1_050, 100));
// Another core's counter a little behind the beat is still fresh.
assert!(channel.covers(990, 100));
// A host core that stopped beating gives the work back at once.
assert!(!channel.covers(1_100, 100));
assert!(!channel.covers(50_000, 100));
assert_eq!(channel.turn(50_000), Turn::Serve);
assert!(channel.covers(50_001, 100));
}
#[test]
fn the_stop_is_acknowledged_and_nothing_serves_after_it() {
let channel = Channel::new();
// No host core: nothing to stop.
assert!(channel.stop(ticking(), 10, || {}));
assert_eq!(channel.state(), State::Off);
channel
.self_check(ticking(), 100, || {
channel.turn(0);
})
.unwrap();
let mut left = false;
let acknowledged = channel.stop(ticking(), 100, || {
// From the stop's first word nothing serves, even before the
// host core reads it.
assert!(!channel.covers(0, u64::MAX >> 2));
if !left {
left = channel.turn(0) == Turn::Leave;
}
});
assert!(acknowledged);
assert!(left);
assert_eq!(channel.state(), State::Stopped);
assert_eq!(channel.turn(0), Turn::Leave);
}
#[test]
fn a_host_core_that_never_answers_its_stop_is_given_up_after_the_limit() {
let channel = Channel::new();
channel
.self_check(ticking(), 100, || {
channel.turn(0);
})
.unwrap();
assert!(!channel.stop(ticking(), 20, || {}));
// Given up: it serves nothing from then on, and leaves when it looks.
assert_eq!(channel.state(), State::Stopped);
assert_eq!(channel.turn(0), Turn::Leave);
assert!(!channel.covers(0, 100));
}
#[test]
fn requests_are_answered_in_order_and_once() {
let channel = Channel::new();
let first = channel.post(Request::Ping);
assert_eq!(channel.take(), Some((first, Request::Ping)));
assert!(!channel.answered(first));
channel.turn(0);
assert!(channel.answered(first));
let second = channel.post(Request::Ping);
assert!(second > first);
assert!(!channel.answered(second));
assert_eq!(channel.take(), Some((second, Request::Ping)));
channel.turn(0);
assert!(channel.answered(second));
let stop = channel.post(Request::Stop);
assert_eq!(channel.take(), Some((stop, Request::Stop)));
assert_eq!(channel.turn(0), Turn::Leave);
assert!(channel.answered(stop));
}
/// The handoff across two threads, as across the boot processor and the
/// host core: the check passes, the host core beats while serving, and the
/// stop ends its loop.
#[test]
fn the_handoff_between_two_processors_checks_serves_and_stops() {
let channel = Arc::new(Channel::new());
let served = Arc::new(AtomicU64::new(0));
let running = Arc::new(AtomicBool::new(true));
let host = {
let (channel, served, running) = (channel.clone(), served.clone(), running.clone());
std::thread::spawn(move || {
let mut now = 0u64;
loop {
now += 1;
match channel.turn(now) {
Turn::Serve => {
served.fetch_add(1, Ordering::Relaxed);
}
Turn::Idle => std::thread::yield_now(),
Turn::Leave => break,
}
}
running.store(false, Ordering::Release);
})
};
let clock = std::time::Instant::now();
let micros = || clock.elapsed().as_micros() as u64;
// Two seconds is far past any answer; the loop answers in microseconds.
let took = channel.self_check(micros, 2_000_000, std::thread::yield_now);
assert!(took.is_ok(), "{took:?}");
while served.load(Ordering::Relaxed) < 100 {
std::thread::yield_now();
}
assert!(channel.stop(micros, 2_000_000, std::thread::yield_now));
host.join().unwrap();
assert!(!running.load(Ordering::Acquire));
let after = served.load(Ordering::Relaxed);
assert_eq!(channel.turn(0), Turn::Leave);
assert_eq!(served.load(Ordering::Relaxed), after);
}
#[test]
fn shares_split_the_ticks_and_clear() {
let shares = Shares::new();
shares.add(Taker::Boot, 25);
shares.add(Taker::HostCore, 70);
shares.add(Taker::Waiting, 5);
let (ticks, total) = shares.take();
assert_eq!(ticks, [5, 25, 70]);
assert_eq!(total, 100);
assert_eq!(percent(ticks[Taker::Boot as usize], total), 25);
assert_eq!(shares.take(), ([0; 3], 0));
assert_eq!(percent(1, 0), 0);
assert_eq!(percent(u64::MAX, u64::MAX), 100);
}
#[test]
fn every_state_has_a_name() {
for state in State::ALL {
assert!(!state.name().is_empty());
}
}
+733 -20
View File
@@ -3,8 +3,8 @@
//! left for the guest, and what is left of it for the translation pack.
use crate::Result;
use crate::native_resources::{
CODE_ALIGNMENT, CodeReservation, MAX_WINDOW, SMALL_WINDOW_PER_RUNNER, WINDOW_PER_RUNNER,
code_reservation_within, parked_reserve, window_share,
CODE_ALIGNMENT, CodeReservation, MAX_WINDOW, MIN_WINDOW, SMALL_WINDOW_PER_RUNNER,
WINDOW_PER_RUNNER, code_reservation_within, parked_reserve, window_share,
};
use stela_contracts::refuse;
@@ -117,6 +117,514 @@ pub const PACK_FLOOR: u64 = 64 * MIB;
/// reserving the parts, beyond the pack itself: the pack's placement page,
/// the storage drivers' rings and the firmware ranges' rounding to 2 MiB.
const PACK_MARGIN: u64 = 16 * MIB;
/// Free host RAM bytes per byte of the share an integrated GPU, which has
/// no memory of its own past its carve-out, takes for its pages. Linux and
/// Windows let such a GPU map up to half of RAM, and macOS on Apple silicon
/// about two thirds, but those are limits on memory the system takes back
/// under pressure; here the share is held from the guest for the boot, so
/// it is a quarter: 3.6 to 3.9 GiB on a 16 GB PC, 7.3 to 7.8 GiB on a 32 GB
/// PC, and the floor's 2.5 GiB below 10 GiB free.
///
/// A sixth left a 16 GB PC with a 512 MiB carve-out (14 842 MiB free) on
/// the floor, and its Metal device told the guest 1534 MiB: Setup's Liquid
/// Glass UI, blurring full-screen RGBA16F targets, ran it out of that at
/// 1527 MiB held, and WindowServer died with the refused commit. A 32 GB PC
/// got through Setup and the desktop at a 2.9 GiB peak. A quarter tells the
/// 16 GB PC 2.4 GiB and a 16 GiB one 2.6 GiB; what it takes comes from the
/// heap's growth past its floor while the guest keeps [`GUEST_ROOM`] (3.4
/// GiB of heap where the heap's own peak beside the share was 2.0 to 2.4
/// GiB, [`HEAP_OWN`]), so a 16 GB PC's guest keeps 6 GiB, and a 12 GB PC's
/// share grows by 150 to 400 MiB.
const GPU_SHARE: u64 = 4;
/// The share a macOS desktop needs. A 16 GiB VM's AMD integrated GPU (512
/// MiB carve-out, 3272 MiB of GTT) held 2058 MiB of RADV's heaps after a
/// sign-in and seven app launches, the guest holding 1326 MiB (`driver
/// heaps use/budget/size: 277/1176/1176M/host 1781/2352/2352M/local`). A 12
/// GiB VM's heaps held 489 MiB at the Metal device's first allocation and
/// grew 1.22 bytes for each byte the guest held, to 1763 MiB for 1045 MiB,
/// where its GTT, half of a 2 GiB share, ran out. The device budgets each
/// allocation at 1.25 bytes of the share and keeps a sixteenth free
/// (`metal::device::share` in the GPU crate), and Linux's own pages and the
/// driver's first buffers take about 480 MiB of it, so the guest is told
/// about (share - 480 MiB - share/16) * 0.8: 1.2 GiB of a 2 GiB share, short
/// of the session above, and 1.5 GiB of 2.5 GiB, which holds it. A host
/// that leaves the guest its floor only with less gets less, down to
/// [`GPU_LEAST`], and says so.
pub const GPU_FLOOR: u64 = 2560 * MIB;
/// The most an integrated GPU's share grows to. A GPU whose firmware gives
/// it a large carve-out (up to many GiB on recent processors) works in that
/// beside the share; the guest keeps the rest of a large host.
const GPU_CEILING: u64 = 8 * GIB;
/// The least share Stela boots an integrated GPU's Metal device with:
/// twice the 129 MiB of RADV's host heap the desktop above held, for its
/// command buffers, uploads and mapped buffers. A host that cannot give it
/// with the guest's floor is refused, as one short of the guest's floor is.
const GPU_LEAST: u64 = 256 * MIB;
/// What an integrated GPU that only shows the display (beside a discrete
/// GPU that draws) takes of the heap beside its own needs: its driver's
/// pages that its carve-out does not hold, and a few scanout and cursor
/// buffers, 32 MiB each at 3840x2160. Linux's pages are not bounded then:
/// the discrete GPU's system-memory buffers (TTM's system pages, a GTT,
/// page tables) come from the heap as its floor was measured with.
pub const DISPLAY_SHARE: u64 = 256 * MIB;
/// What the heap's own allocations held at most beside an integrated GPU's
/// pages: a 16 GiB VM's heap peaked at 4482 MiB with 2058 MiB of the driver's
/// heaps in it, beside amdgpu and RADV. Where no share is planned and every
/// GPU that starts has a driver this was measured beside
/// ([`GpuPlan::bounded`]), Linux's pages (a discrete GPU's system-memory
/// buffers, its evictions from VRAM, an integrated GPU that draws because
/// the discrete one did not start) are held to what the heap holds past
/// this ([`page_bound`]).
pub const HEAP_OWN: u64 = 2424 * MIB;
/// The least of the heap Linux's pages may hold where no share is planned,
/// for heaps whose spare past [`HEAP_OWN`] is less (a floor heap at a small
/// code window).
pub const PAGES_LEAST: u64 = 384 * MIB;
/// What an integrated GPU's Linux driver and RADV held of Linux's pages at
/// its Metal device's first allocation (AMD, with a 2 to 2.5 GiB share).
pub const FALLBACK_OPEN: u64 = 480 * MIB;
/// Linux's pages an integrated GPU needs to draw a desktop in place of a
/// discrete GPU that did not start: [`FALLBACK_OPEN`], and the least share
/// Stela boots an integrated GPU's Metal device with ([`GPU_LEAST`]), in
/// whole 256 MiB. Where such a GPU may draw
/// instead ([`GpuPlan::fallback`]), the plan makes the heap region hold this
/// past [`HEAP_OWN`] ([`Sizes::fallback`]), as far as the guest's floor
/// allows.
pub const FALLBACK_LEAST: u64 = 768 * MIB;
/// The least of Linux's pages an integrated GPU needs free under their bound
/// for its driver to bind it at all: what one that only shows the display
/// takes ([`DISPLAY_SHARE`]). With less, a fallback to it is refused
/// ([`fallback_pages`]).
pub const FALLBACK_START: u64 = DISPLAY_SHARE;
/// The page tables a driver's mapping of a whole device-memory aperture of
/// `bytes` takes from the heap: Stela's page window maps device memory in
/// 4 KiB pages, an 8-byte entry each (`bytes / 512`, 32 MiB for 16 GiB),
/// and a directory entry for each table, in whole alignments.
pub fn aperture_tables(bytes: u64) -> u64 {
let leaves = bytes.div_ceil(4096) * 8;
let directories = leaves.div_ceil(4096) * 8;
(leaves + directories).next_multiple_of(ALIGNMENT)
}
/// What the memory plan knows of the GPUs before the parts are sized: how
/// they use the host's RAM, the page tables of the device-memory apertures
/// their drivers map whole ([`aperture_tables`]), which the heap grows by,
/// and whether Linux's pages are held to [`page_bound`] where no share is
/// planned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GpuPlan {
pub memory: GpuMemory,
pub aperture: u64,
/// Every GPU that starts has a driver whose heap need beside it was
/// measured ([`HEAP_OWN`]), so Linux's pages are held to [`page_bound`]
/// where no share is planned ([`held_bound`]). Otherwise, as beside
/// nouveau and NVK, Linux takes the whole heap as its RAM and TTM keeps
/// its own limit, half of that, as every boot gave them before the
/// bound: a bound measured beside another driver could fail a session
/// that ran.
pub bounded: bool,
/// An integrated GPU this image draws with stands beside the discrete
/// GPU the plan gives the Metal device, and draws in its place should it
/// not start (`selection::integrated_may_draw_instead`): where no share
/// is planned, the heap region is made to hold [`FALLBACK_LEAST`] of
/// Linux's pages past [`HEAP_OWN`] ([`Sizes::fallback`]), and the engine
/// holds Linux's pages to [`page_bound`] once it draws
/// ([`fallback_pages`]). False in an image without such a GPU's driver,
/// which plans as before.
pub fallback: bool,
}
impl From<GpuMemory> for GpuPlan {
fn from(memory: GpuMemory) -> Self {
Self {
memory,
aperture: 0,
bounded: false,
fallback: false,
}
}
}
/// The most bytes of pages Linux may hold at once under `sizes`, planned
/// for `memory`: an integrated GPU's share where it draws
/// ([`GpuMemory::Shared`]); otherwise what the heap region (its display
/// reserve with it) holds past [`HEAP_OWN`], at least [`PAGES_LEAST`], so
/// that a discrete GPU's system-memory pages fail their allocation before
/// the heap runs out. Where [`held_bound`] holds Linux to it, the page
/// catalog refuses more and TTM's limit is the same; an integrated GPU that
/// draws without a share budgets its Metal device by it either way.
pub fn page_bound(sizes: &Sizes, memory: GpuMemory) -> u64 {
match memory {
GpuMemory::Shared => sizes.gpu,
GpuMemory::Own | GpuMemory::Display => {
let region = sizes.heap + sizes.gpu + sizes.fallback;
region.saturating_sub(HEAP_OWN).max(PAGES_LEAST).min(region) / ALIGNMENT * ALIGNMENT
}
}
}
/// What the engine does with Linux's pages once an integrated GPU is to
/// draw in place of a GPU that could not ([`fallback_pages`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FallbackPages {
/// Linux's pages are held to `limit` bytes already (an integrated GPU's
/// share, or a plan that holds them), with `room` of it free.
Held { limit: u64, room: u64 },
/// The plan held Linux's pages to no bound: they are held to `limit`
/// bytes from now on, before the integrated GPU's driver sizes its
/// memory from the RAM Linux reports, with `room` of it free.
Hold { limit: u64, room: u64 },
/// Linux holds `held` bytes of the `bound` already, which leaves less
/// than [`FALLBACK_START`] for the integrated GPU's driver: the fallback
/// to it is refused, as its start could only fail.
Short { held: u64, bound: u64 },
/// An integrated GPU started already draws, and Linux holds `held`
/// bytes, past the `bound`: its pages stay unbounded, and the GPU's
/// Metal device alone budgets its allocations to the bound
/// ([`drawing_pages`]).
Over { held: u64, bound: u64 },
}
impl FallbackPages {
/// The bytes Linux's pages are held to from now on, where the fallback
/// goes on.
pub fn limit(self) -> Option<u64> {
match self {
Self::Held { limit, .. } | Self::Hold { limit, .. } => Some(limit),
Self::Short { .. } | Self::Over { .. } => None,
}
}
/// The bytes of the limit free for the integrated GPU, where the
/// fallback goes on.
pub fn room(self) -> Option<u64> {
match self {
Self::Held { room, .. } | Self::Hold { room, .. } => Some(room),
Self::Short { .. } | Self::Over { .. } => None,
}
}
/// Whether the integrated GPU's Metal device, once its driver holds
/// [`FALLBACK_OPEN`] more, tells the guest a working set under half of
/// [`GPU_LEAST`] (`share::working_set`): it draws, and some windows may
/// not.
pub fn starved(self) -> bool {
use stela_drivers::gpu::share::{ShareState, working_set};
match self {
Self::Held { limit, room } | Self::Hold { limit, room } => {
let held = limit - room + FALLBACK_OPEN;
working_set(ShareState { held, limit }) < GPU_LEAST / 2
}
Self::Short { .. } | Self::Over { .. } => false,
}
}
/// The `GPU MEMORY` line's words, after the GPU's address.
pub fn describe(self) -> alloc::string::String {
let mib = |bytes: u64| bytes >> 20;
let desktop = match self.starved() {
true => alloc::format!(
", little past the {}M its driver holds as its Metal device opens, so some \
windows may not draw",
mib(FALLBACK_OPEN)
),
false => alloc::string::String::new(),
};
match self {
Self::Held { limit, room } => alloc::format!(
"draws in place of a GPU that could not, in Linux's pages, held to {}M as \
planned: {}M of them free{desktop}",
mib(limit),
mib(room)
),
Self::Hold { limit, room } => alloc::format!(
"draws in place of a GPU that could not: Linux's pages, which the plan left \
unbounded for the discrete GPU, are held from now on to {}M, what the heap \
holds past its own {}M, so the integrated GPU cannot take the heap's own: {}M \
of them free{desktop}",
mib(limit),
mib(HEAP_OWN),
mib(room)
),
Self::Short { held, bound } => alloc::format!(
"not started in place of a GPU that could not draw: Linux holds {}M of the {}M \
of pages the heap holds past its own {}M, which leaves under the {}M its \
driver needs to start",
mib(held),
mib(bound),
mib(HEAP_OWN),
mib(FALLBACK_START)
),
Self::Over { held, bound } => alloc::format!(
"draws in place of a GPU that could not, while Linux holds {}M of pages, past \
the {}M the heap holds past its own {}M: they stay unbounded, and its Metal \
device alone budgets its allocations to them",
mib(held),
mib(bound),
mib(HEAP_OWN)
),
}
}
}
/// Linux's pages once an integrated GPU is to draw in place of a GPU that
/// could not, with `bound` the plan's [`page_bound`] (or the share), `held`
/// the bytes Linux holds now and `limit` the bytes it is held to now, zero
/// for none: a plan that held Linux to no bound (beside nouveau, whose
/// heap need was not measured) holds it to `bound` from now on, so that the
/// integrated GPU's pages, which its driver sizes from the RAM Linux
/// reports, never take the heap's own and the worst is its Metal device's
/// out-of-memory answer; where too little is left for its driver to start,
/// the fallback is refused ([`FallbackPages::Short`]).
pub fn fallback_pages(bound: u64, held: u64, limit: u64) -> FallbackPages {
let limit_now = match limit {
0 => bound,
limit => limit,
};
let room = limit_now.saturating_sub(held);
if room < FALLBACK_START {
return FallbackPages::Short {
held,
bound: limit_now,
};
}
match limit {
0 => FallbackPages::Hold { limit: bound, room },
limit => FallbackPages::Held { limit, room },
}
}
/// [`fallback_pages`] for an integrated GPU started already, which draws
/// now in place of a GPU that could not: its driver bound it, so nothing is
/// refused; a plan that held Linux to no bound holds it to `bound` from now
/// on wherever Linux holds no more than that ([`FallbackPages::Over`]
/// otherwise).
pub fn drawing_pages(bound: u64, held: u64, limit: u64) -> FallbackPages {
match limit {
0 if held > bound => FallbackPages::Over { held, bound },
0 => FallbackPages::Hold {
limit: bound,
room: bound - held,
},
limit => FallbackPages::Held {
limit,
room: limit.saturating_sub(held),
},
}
}
/// The bound the page catalog and TTM hold Linux's pages to under `sizes`
/// for `plan`: the share where an integrated GPU draws, [`page_bound`] where
/// no share is planned and the plan is [`GpuPlan::bounded`], else none.
pub fn held_bound(sizes: &Sizes, plan: GpuPlan) -> Option<u64> {
match plan.memory {
GpuMemory::Shared => Some(sizes.gpu),
GpuMemory::Own | GpuMemory::Display => plan.bounded.then(|| page_bound(sizes, plan.memory)),
}
}
/// How the GPUs that start use the host's RAM, as the PCI census and the
/// GPU stacks know it before the parts are sized (the selection's rule,
/// `stela_driver_gpu::selection::memory`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GpuMemory {
/// No integrated GPU starts: a discrete GPU's system-memory pages come
/// from the heap, bounded by [`page_bound`] where the plan is
/// [`GpuPlan::bounded`].
Own,
/// An integrated GPU draws, sharing the host's RAM: the plan gives it a
/// share of its own beside the heap ([`Sizes::gpu`]), which bounds all
/// of Linux's pages.
Shared,
/// An integrated GPU only shows the display beside a discrete GPU that
/// draws: the heap grows by [`DISPLAY_SHARE`] ([`Sizes::gpu`]), and
/// Linux's pages are bounded by [`page_bound`] where the plan is
/// [`GpuPlan::bounded`], never by that reserve.
Display,
}
impl GpuMemory {
/// Whether [`Sizes::gpu`] is a share that alone bounds Linux's pages,
/// told to TTM at twice its size ([`page_bound`] for the others).
pub fn limits_pages(self) -> bool {
self == Self::Shared
}
}
/// The PCI device IDs of NVIDIA's Turing GPUs begin here (TU102's block),
/// and every NVIDIA GPU since has an ID past it. Every NVIDIA GPU before it
/// (Maxwell, Pascal and Volta, as the GeForce MX330, `10de:1d16`) has a
/// chipset nouveau runs without GSP-RM: Stela's claim refuses it ("the GPU's
/// PMC chipset is unsupported") and no recipe of the firmware catalog pins
/// its files.
pub const NVIDIA_TURING_FIRST: u16 = 0x1e00;
/// Why the display controller `vendor:device`, which a stack of this image
/// drives, cannot start, where that is known before the memory plan, from
/// its PCI IDs and whether the firmware catalog names its chip
/// (`catalog_chip`, the bundle's NO RECIPE line where it does not); `None`
/// where only its claim can tell. The plan leaves such a GPU out
/// (`selection::memory`), so an integrated GPU beside it, which draws in its
/// place, is planned as the GPU that draws, with its full share of RAM
/// ([`GpuMemory::Shared`]), where it was budgeted to what the heap holds
/// past its own needs as the discrete GPU's fallback ([`page_bound`]): on an
/// i5-1035G1 laptop with a GeForce MX330, 2248M, of which Metal had 1605M,
/// too little to draw 1080p, and WindowServer died.
///
/// A newer NVIDIA GPU whose device ID the catalog does not name still
/// counts: the claim reads its chip from the GPU itself, and its files are
/// read with every NVIDIA chip's.
pub fn cannot_start(vendor: u16, device: u16, catalog_chip: bool) -> Option<&'static str> {
const NVIDIA: u16 = 0x10de;
(vendor == NVIDIA && !catalog_chip && device < NVIDIA_TURING_FIRST).then_some(
"an NVIDIA GPU older than Turing, whose firmware no recipe pins and whose chipset the \
claim refuses",
)
}
impl GpuPlan {
/// The rule for the plan's line, for `sizes`.
pub fn describe(&self, sizes: &Sizes) -> alloc::string::String {
let mib = |bytes: u64| bytes >> 20;
let bound = page_bound(sizes, self.memory);
let past = alloc::format!(
"what the {}M heap holds past its own {}M (at least {}M)",
mib(sizes.heap + sizes.gpu),
mib(HEAP_OWN),
mib(PAGES_LEAST)
);
const UNBOUNDED: &str = "Linux takes the heap as its RAM and TTM its own limit, half of \
it, as the heap's own need was not measured beside every driver that starts";
let rule = match (self.memory, self.bounded) {
(GpuMemory::Own, true) => alloc::format!(
"no integrated GPU starts: Linux's pages, a discrete GPU's system-memory \
buffers and its evictions from VRAM among them, come from the heap, at most \
{}M of them, {past}; TTM's limit is the same, and an allocation past it fails \
as the GPU's memory being full",
mib(bound),
),
(GpuMemory::Own, false) => alloc::format!(
"no integrated GPU starts: Linux's pages, a discrete GPU's system-memory \
buffers and its evictions from VRAM among them, come from the heap with no \
bound of their own: {UNBOUNDED}"
),
(GpuMemory::Shared, _) => alloc::format!(
"the integrated GPU draws: its share of {}M bounds all of Linux's pages, and \
TTM's limit is twice it, so amdgpu's or xe's GTT is the share",
mib(sizes.gpu)
),
(GpuMemory::Display, true) => alloc::format!(
"a discrete GPU draws and the integrated GPU shows the display: the heap takes \
{}M more for the integrated GPU's driver and scanout; Linux's pages, the \
discrete GPU's system-memory buffers among them, are at most {}M, {past}, \
TTM's limit the same; should the discrete GPU not start and the integrated \
one draw, its Metal device works in those {}M",
mib(sizes.gpu),
mib(bound),
mib(bound)
),
(GpuMemory::Display, false) => alloc::format!(
"a discrete GPU draws and the integrated GPU shows the display: the heap takes \
{}M more for the integrated GPU's driver and scanout; Linux's pages, the \
discrete GPU's system-memory buffers among them, have no bound of their own: \
{UNBOUNDED}; should the discrete GPU not start and the integrated one draw, \
its Metal device budgets its allocations to {}M, {past}",
mib(sizes.gpu),
mib(bound)
),
};
let rule = match (self.fallback, self.memory) {
(false, _) | (true, GpuMemory::Shared) => rule,
(true, _) => alloc::format!(
"{rule}; an integrated GPU this image draws with may draw in the discrete GPU's \
place, Linux's pages then held to {}M{}",
mib(bound),
match (sizes.fallback, bound >= FALLBACK_LEAST) {
(0, true) => alloc::string::String::new(),
(more, true) => alloc::format!(
", for which the heap takes {}M more, to hold the {}M it needs",
mib(more),
mib(FALLBACK_LEAST)
),
(more, false) => alloc::format!(
", under the {}M it needs, as the heap takes only {}M more and the guest \
keeps its floor",
mib(FALLBACK_LEAST),
mib(more)
),
}
),
};
if sizes.aperture == 0 {
return rule;
}
alloc::format!(
"{rule}; the heap takes {}M more for the page tables of the device-memory \
apertures drivers map whole",
mib(sizes.aperture)
)
}
}
/// The share (a fraction's denominator) of the room a pack read on demand
/// leaves of its budget ([`sizes_with_room`]) that the loader fills with
/// the pack's first records before the guest starts, at most
/// [`PRELOAD_MOST`] and for at most [`PRELOAD_MILLIS`]: the rest of the
/// room still grows the code window and the guest. A merge lays a pack's
/// records out in the order a boot first used them, so its first bytes are
/// what the next boot needs first, while every PE is busy and none reads
/// the stick for it; the reader goes on in that order on PEs whose guest
/// waits.
pub const PRELOAD_SHARE: u64 = 4;
pub const PRELOAD_MOST: u64 = 256 * MIB;
/// The longest the loader reads ahead. Reading a whole 498 MB pack would
/// hold the boot 14 s on a USB 2 stick (35 MB/s) and 5 s on a USB 3 one
/// (100 MB/s); two seconds reads its first 70 or 200 MB, the boot's start.
pub const PRELOAD_MILLIS: u64 = 2000;
/// Below this bound the loader reads nothing ahead.
pub const PRELOAD_FLOOR: u64 = 4 * MIB;
/// The bytes of a pack read on demand the loader may read ahead into
/// memory when its indexes leave `room` of its budget: a
/// 1/[`PRELOAD_SHARE`] of it, at most [`PRELOAD_MOST`], in whole
/// [`ALIGNMENT`]s; none below [`PRELOAD_FLOOR`].
pub fn preload_bound(room: u64) -> u64 {
let bound = (room / PRELOAD_SHARE).min(PRELOAD_MOST) / ALIGNMENT * ALIGNMENT;
if bound < PRELOAD_FLOOR { 0 } else { bound }
}
/// The most of a pack read on demand its background preload holds
/// (`stela_runtime::translation_bulk`), whatever the room.
pub const BULK_MOST: u64 = GIB;
/// The memory the background preload of a pack read on demand sets aside,
/// when the pack's indexes and what the loader read ahead leave `room` of
/// its budget ([`pack_budget`]) and `left` bytes of its segments lie only in
/// the file: all of them, as a pack read whole holds its bytes, within the
/// room and [`BULK_MOST`]; none below [`PRELOAD_FLOOR`]. A room larger than
/// the pack still grows the code window and the guest by what is left
/// ([`sizes_with_room`]); a smaller one holds the records its boot used
/// first, and the others are read on demand.
pub fn bulk_bound(room: u64, left: u64) -> u64 {
let bound = left.min(room).min(BULK_MOST);
if bound < PRELOAD_FLOOR { 0 } else { bound }
}
/// What a preload within `bound` reads from a medium that reads
/// `bytes_per_second`, and the milliseconds it holds the boot: the model of
/// the stick [`PRELOAD_MILLIS`] was chosen with.
pub fn preload_reads(bound: u64, bytes_per_second: u64) -> (u64, u64) {
let in_time = bytes_per_second.saturating_mul(PRELOAD_MILLIS) / 1000;
let bytes = bound.min(in_time);
(bytes, bytes.saturating_mul(1000) / bytes_per_second.max(1))
}
/// The engine heap's share (a fraction's denominator) that held compiled
/// code beside the window before one budget held both: the blocks PEs
@@ -152,9 +660,26 @@ pub struct Sizes {
/// ([`code_budget`]).
pub kept: u64,
pub pool: u64,
/// Free RAM after the three parts; Stela's stacks, tables and image
/// take a few more MiB of it.
/// Free RAM after the three parts and the GPU's share; Stela's stacks,
/// tables and image take a few more MiB of it.
pub guest: u64,
/// The share of an integrated GPU ([`GpuMemory::Shared`]): the most
/// system memory Linux's pages hold at once, reserved beside the heap
/// and taken from the same region, on top of what the heap itself
/// needs. For one that only shows ([`GpuMemory::Display`]) its pages'
/// part of the heap; zero with no integrated GPU.
pub gpu: u64,
/// The page tables of the device-memory apertures drivers map whole
/// ([`GpuPlan::aperture`]), reserved beside the heap and taken from the
/// same region.
pub aperture: u64,
/// What the heap region takes beyond the heap and `gpu` so that it
/// holds [`FALLBACK_LEAST`] of Linux's pages past [`HEAP_OWN`], for an
/// integrated GPU that may draw in a discrete GPU's place
/// ([`GpuPlan::fallback`]), as much as the guest's floor allows; part of
/// the heap's region, which the heap uses while no such GPU draws. Zero
/// without such a GPU, and where the heap holds it already.
pub fallback: u64,
}
/// The DRAM the guest Mac reports and the host RAM it does not see.
@@ -186,11 +711,13 @@ pub fn guest_dram(installed: u64, backed: u64) -> GuestDram {
}
}
/// Too little RAM for the guest's floor: `free` bytes, of `needed`.
/// Too little RAM for the guest's floor (and an integrated GPU's least
/// share): `free` bytes, of `needed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Shortfall {
pub free: u64,
pub needed: u64,
pub gpu: GpuMemory,
}
impl Shortfall {
@@ -200,16 +727,27 @@ impl Shortfall {
let needed = self.needed.div_ceil(GIB);
let free = alloc::format!("{}.{}", self.free / GIB, self.free % GIB * 10 / GIB);
let floor = GUEST_FLOOR / GIB;
let rest = match self.gpu {
GpuMemory::Own | GpuMemory::Display => "its own memory",
GpuMemory::Shared => "its own memory and the graphics built into the processor",
};
refuse!(
"this PC has {free} GB of RAM free; Stela needs at least {needed} GB free: \
{floor} GB for macOS and the rest for its own memory",
"this PC has {free} GB of RAM free; Stambha needs at least {needed} GB free: \
{floor} GB for macOS and the rest for {rest}",
free = %free,
needed = %needed,
floor = %floor
floor = %floor,
rest = %rest
)
}
}
/// The share an integrated GPU would take of `free` bytes with the guest's
/// floor left aside: a [`GPU_SHARE`]th, within [`GPU_FLOOR`]..=[`GPU_CEILING`].
fn gpu_target(free: u64) -> u64 {
(free / GPU_SHARE / ALIGNMENT * ALIGNMENT).clamp(GPU_FLOOR, GPU_CEILING)
}
/// The sizes for `free` host bytes and `runners` of the `cores` executors
/// running PEs; the others add only their parked reserves.
///
@@ -233,17 +771,131 @@ impl Shortfall {
/// Then the window takes what the code kept beside it in the heap held
/// ([`code_budget`]): the guest and the pool stay as decided.
///
/// A GPU that shares the host's RAM ([`GpuMemory::Shared`]) first takes its
/// share ([`gpu_target`]), and the parts are sized as on a host with that
/// much less: the GPU's memory is no more Stela's to translate in than the
/// guest's. Where that leaves the guest under its floor, the share is the
/// most that does not, down to [`GPU_LEAST`]. The GPU's share, its
/// apertures' tables and the fallback's room are planned against the heap
/// the code budget leaves ([`budgeted`]).
///
/// A guest share under [`GUEST_FLOOR`] is a [`Shortfall`].
pub fn sizes(free: u64, cores: usize, runners: usize) -> Result<Sizes> {
let estimate = estimate(free, cores, runners)?;
if estimate.guest >= GUEST_FLOOR {
return Ok(code_budget(estimate));
pub fn sizes(free: u64, cores: usize, runners: usize, gpu: impl Into<GpuPlan>) -> Result<Sizes> {
let gpu = gpu.into();
if let Some(sizes) = plan(free, cores, runners, gpu)? {
return Ok(sizes);
}
let mut needed = free.next_multiple_of(NEEDED_STEP);
while estimate_guest(needed, cores, runners)? < GUEST_FLOOR {
while plan(needed, cores, runners, gpu)?.is_none() {
needed += NEEDED_STEP;
}
Err(Shortfall { free, needed }.refusal())
Err(Shortfall {
free,
needed,
gpu: gpu.memory,
}
.refusal())
}
/// [`sizes`], or `None` where the guest's floor (and the GPU's least
/// share) does not fit.
fn plan(free: u64, cores: usize, runners: usize, gpu: GpuPlan) -> Result<Option<Sizes>> {
let with_room = |share: u64, fallback: u64| -> Result<Option<Sizes>> {
let sizes = budgeted(
free.saturating_sub(share)
.saturating_sub(gpu.aperture)
.saturating_sub(fallback),
cores,
runners,
)?;
Ok((sizes.guest >= GUEST_FLOOR).then_some(Sizes {
gpu: share,
aperture: gpu.aperture,
fallback,
..sizes
}))
};
let with_share = |share: u64| -> Result<Option<Sizes>> {
match gpu.fallback {
false => with_room(share, 0),
true => with_fallback(share, &with_room),
}
};
let target = match gpu.memory {
GpuMemory::Own => return with_share(0),
GpuMemory::Shared => gpu_target(free.saturating_sub(gpu.aperture)),
// The display's pages where the guest keeps its floor beside them;
// a host too small for both gives them none, and they come from
// the heap.
GpuMemory::Display => {
return Ok(with_share(DISPLAY_SHARE)?.or(with_share(0)?));
}
};
let with_share = |share: u64| with_room(share, 0);
// The most share up to the target that leaves the guest its floor, in
// whole alignments; the guest grows with the RAM the parts are sized
// for, so the first found from the top is the most.
let mut share = target;
while share >= GPU_LEAST {
if let Some(sizes) = with_share(share)? {
return Ok(Some(sizes));
}
share -= ALIGNMENT;
}
Ok(None)
}
/// [`estimate`] with the code budget's window ([`code_budget`]): the heap
/// the GPU plan measures its share and the fallback's room against is the
/// one the boot runs with. The budget moves heap bytes into the window and
/// leaves the guest as estimated, so the guest's floor reads the same.
fn budgeted(free: u64, cores: usize, runners: usize) -> Result<Sizes> {
estimate(free, cores, runners).map(code_budget)
}
/// What the heap region lacks of [`HEAP_OWN`] and [`FALLBACK_LEAST`] beside
/// `share` for sizes `sizes`, in whole alignments.
fn fallback_lack(sizes: &Sizes, share: u64) -> u64 {
(HEAP_OWN + FALLBACK_LEAST)
.saturating_sub(sizes.heap + share)
.next_multiple_of(ALIGNMENT)
}
/// The plan with `share` beside the heap and room in the heap's region for
/// an integrated GPU that may draw in a discrete GPU's place: what the heap
/// and the share lack of [`HEAP_OWN`] and [`FALLBACK_LEAST`], found as the
/// heap shrinks with the RAM the reserve takes, or the most of it that
/// leaves the guest its floor; `with_room` plans a share and a reserve.
fn with_fallback(
share: u64,
with_room: &dyn Fn(u64, u64) -> Result<Option<Sizes>>,
) -> Result<Option<Sizes>> {
let Some(mut sizes) = with_room(share, 0)? else {
return Ok(None);
};
// The heap shrinks, or stays, as the reserve grows, so the lack grows
// to a fixed point from below, at most the whole of it.
let mut reserve = 0;
for _ in 0..=(HEAP_OWN + FALLBACK_LEAST) / ALIGNMENT {
let lack = fallback_lack(&sizes, share);
if lack <= reserve {
return Ok(Some(sizes));
}
reserve = lack;
match with_room(share, reserve)? {
Some(next) => sizes = next,
None => break,
}
}
// The whole reserve leaves the guest under its floor: the most that
// does not.
while reserve > ALIGNMENT {
reserve -= ALIGNMENT;
if let Some(sizes) = with_room(share, reserve)? {
return Ok(Some(sizes));
}
}
with_room(share, 0)
}
/// The code window per runner past which a larger one cuts reinstalls
@@ -260,11 +912,20 @@ pub const SHARED_PER_RUNNER: u64 = 202 * MIB;
/// its index and the records lookups ask for, not every record. The other
/// parts are what they were while the pack held its budget, and the room
/// goes to the code window (with its block records, [`HEAP_PER_WINDOW`] a
/// window byte) and the guest ([`give_room`]).
pub fn sizes_with_room(free: u64, cores: usize, runners: usize, room: u64) -> Result<Sizes> {
match sizes(free.saturating_sub(room), cores, runners) {
/// window byte) and the guest ([`give_room`]); the GPU's share, apertures
/// and fallback room are planned on the host without the room, as the
/// pack's budget left them.
pub fn sizes_with_room(
free: u64,
cores: usize,
runners: usize,
room: u64,
gpu: impl Into<GpuPlan>,
) -> Result<Sizes> {
let gpu = gpu.into();
match sizes(free.saturating_sub(room), cores, runners, gpu) {
Ok(sizes) => Ok(give_room(sizes, room, runners)),
Err(_) => sizes(free, cores, runners),
Err(_) => sizes(free, cores, runners, gpu),
}
}
@@ -296,6 +957,38 @@ fn give_room(sizes: Sizes, room: u64, runners: usize) -> Sizes {
}
}
/// `sizes` with the board's code window `window` bytes in place of the one
/// they chose (`--code-window`), for a boot that measures another window
/// against the sized one. The window and its block records
/// ([`HEAP_PER_WINDOW`] heap bytes a window byte, which moves the heap's
/// floor alike) come from the guest, or go back to it, so each byte past
/// the sized window costs the guest two: on a 16 GiB host with 8 PEs the
/// sized 1200 MiB window and 9538 MiB guest become 2048 MiB and 7842 MiB.
/// A window the guest's floor ([`GUEST_FLOOR`]) leaves too little room for
/// is the largest whole [`CODE_ALIGNMENT`]s that keep the floor; the pool
/// and the code kept beside the window stay as sized.
pub fn with_window(sizes: Sizes, window: u64) -> Sizes {
let per_byte = 1 + HEAP_PER_WINDOW;
let sized = sizes.code.window;
let window = window.clamp(MIN_WINDOW, MAX_WINDOW) / CODE_ALIGNMENT * CODE_ALIGNMENT;
let window = if window > sized {
let room = sizes.guest.saturating_sub(GUEST_FLOOR) / per_byte;
sized + (window - sized).min(room / CODE_ALIGNMENT * CODE_ALIGNMENT)
} else {
window
};
Sizes {
heap: sizes.heap + HEAP_PER_WINDOW * window - HEAP_PER_WINDOW * sized,
code: CodeReservation {
bytes: sizes.code.bytes + window - sized,
window,
..sizes.code
},
guest: sizes.guest + per_byte * sized - per_byte * window,
..sizes
}
}
/// One budget for compiled code, the window's first: the window, its
/// block records ([`HEAP_PER_WINDOW`]) and the code kept beside it in the
/// heap (a [`CODE_SHARE`]th of the heap for blocks and stored forms, a
@@ -341,10 +1034,27 @@ fn code_budget(sizes: Sizes) -> Sizes {
/// the guest's floor, after the pack and a margin for the loader's other
/// allocations. Zero, below [`PACK_FLOOR`]: the parts and the guest come
/// first, and the pack never makes a boot fail.
pub fn pack_budget(free: u64, cores: usize, runners: usize) -> u64 {
///
/// An integrated GPU's whole share ([`gpu_target`] of what the pack leaves)
/// comes before the pack: the pack never makes the GPU's share smaller.
pub fn pack_budget(free: u64, cores: usize, runners: usize, gpu: impl Into<GpuPlan>) -> u64 {
let gpu = gpu.into();
let mut budget = free / PACK_SHARE / ALIGNMENT * ALIGNMENT;
while budget >= PACK_FLOOR {
let left = free.saturating_sub(budget + PACK_MARGIN);
let mut left = free.saturating_sub(budget + PACK_MARGIN + gpu.aperture);
let share = match gpu.memory {
GpuMemory::Shared => gpu_target(left),
GpuMemory::Display => DISPLAY_SHARE,
GpuMemory::Own => 0,
};
left = left.saturating_sub(share);
// The room for an integrated GPU that may draw in a discrete one's
// place comes before the pack too.
if gpu.fallback && gpu.memory != GpuMemory::Shared {
let lack =
budgeted(left, cores, runners).map_or(0, |sizes| fallback_lack(&sizes, share));
left = left.saturating_sub(lack);
}
if estimate_guest(left, cores, runners).is_ok_and(|guest| guest >= GUEST_FLOOR) {
return budget;
}
@@ -466,6 +1176,9 @@ fn split(free: u64, heap: u64, code: CodeReservation, cores: usize, runners: usi
kept: kept_share(heap),
pool,
guest: rest.saturating_sub(pool),
gpu: 0,
aperture: 0,
fallback: 0,
}
}
File diff suppressed because it is too large. Load diff
+98 -8
View File
@@ -75,7 +75,7 @@
use crate::msr::{AMD_VENDOR, Bit, Gate, Msr, Register};
use alloc::{format, string::String};
use core::arch::x86_64::{__cpuid, __cpuid_count};
use core::sync::atomic::{AtomicU32, Ordering};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
const EIST_BIT: Bit = Bit::new(1, Register::Ecx, 7);
const CLOCK_MODULATION_BIT: Bit = Bit::new(1, Register::Edx, 22);
@@ -295,21 +295,53 @@ pub struct Bounds {
pub maximum: u8,
}
/// Whether Intel HWP asks for a shared power budget instead of full speed:
/// minimum 7:0 the lowest level, maximum 15:8 the highest, energy
/// preference 31:24 = 0x80 (balanced, intel_pstate's `balance_performance`
/// default is 0x80 too). On a laptop whose package sits at its PL1 limit
/// (for example 15 W on a U-series part) the full-speed request lets the
/// cores take the whole budget and the integrated GPU drops to its lowest
/// clock (MGKFN's i5-1235U log: `package(hot/power/prochot)%=0/100/0
/// package_w=15.0` with `rcs0 clock: gpu 100 MHz (asked 300, 100-1200);
/// perf limit reasons ...: pl1`). Off by default, so nothing changes until
/// a startup switch sets it before the processors make their request.
pub static INTEL_BALANCED: AtomicBool = AtomicBool::new(false);
/// IA32_HWP_REQUEST's energy preference under [`INTEL_BALANCED`].
pub const BALANCED_EPP: u64 = 0x80;
/// The IA32_HWP_REQUEST value for `capabilities`, or none to keep the
/// firmware's request: minimum 7:0 and maximum 15:8 both the highest level
/// (intel_pstate `intel_pstate_hwp_set`: `min = max` under the performance
/// policy), desired 23:16 = 0, with `epp` the energy preference 31:24 = 0,
/// and package control (bit 42) clear, so these fields govern this
/// processor. Bits 63:43 and 41:32 stay.
pub fn intel_request(capabilities: u64, current: u64, epp: bool) -> Option<(u64, Bounds)> {
/// processor. Bits 63:43 and 41:32 stay. With `balanced`, the minimum is
/// the lowest level and, with `epp`, the preference is [`BALANCED_EPP`].
pub fn intel_request(
capabilities: u64,
current: u64,
epp: bool,
balanced: bool,
) -> Option<(u64, Bounds)> {
let levels = Levels::intel(capabilities).ordered()?;
let kept = if epp { !0xffff_ffff } else { !0x00ff_ffff };
let highest = u64::from(levels.highest);
let value = (current & kept & !HWP_PACKAGE_CONTROL) | highest | highest << 8;
let minimum = if balanced {
levels.lowest
} else {
levels.highest
};
let preference = if epp && balanced {
BALANCED_EPP << 24
} else {
0
};
let value =
(current & kept & !HWP_PACKAGE_CONTROL) | u64::from(minimum) | highest << 8 | preference;
Some((
value,
Bounds {
minimum: levels.highest,
minimum,
maximum: levels.highest,
},
))
@@ -590,8 +622,12 @@ unsafe fn request_level(features: Features, registers: &mut impl Registers) -> O
}
let capabilities = registers.read(HWP_CAPABILITIES);
let current = registers.read(HWP_REQUEST);
let Some((value, bounds)) = intel_request(capabilities, current, features.hwp_epp)
else {
let Some((value, bounds)) = intel_request(
capabilities,
current,
features.hwp_epp,
INTEL_BALANCED.load(Ordering::Relaxed),
) else {
return Outcome::Unpublished;
};
registers.write(HWP_REQUEST, value);
@@ -664,6 +700,20 @@ unsafe fn request_level(features: Features, registers: &mut impl Registers) -> O
Outcome::Legacy
}
/// Ask again on a processor that already asked, once [`INTEL_BALANCED`]
/// changed, without counting it twice in the summary: its new minimum
/// replaces the one it reported first ([`Tally::replace_minimum`]).
///
/// # Safety
///
/// As [`request_full_performance`].
pub unsafe fn request_again(registers: &mut impl Registers) -> Report {
// SAFETY: the caller's contract; `Features::read` describes this CPU.
let report = unsafe { request_with(Features::read(), registers) };
TALLY.replace_minimum(report);
report
}
/// Ask this processor for full performance through `registers` and count
/// what it did.
///
@@ -685,6 +735,11 @@ impl Range {
Self([AtomicU32::new(u32::MAX), AtomicU32::new(0)])
}
fn clear(&self) {
self.0[0].store(u32::MAX, Ordering::Relaxed);
self.0[1].store(0, Ordering::Relaxed);
}
fn add(&self, value: u8) {
self.0[0].fetch_min(value.into(), Ordering::Relaxed);
self.0[1].fetch_max(value.into(), Ordering::Relaxed);
@@ -839,6 +894,40 @@ impl Tally {
class.maximum.add(bounds.maximum);
}
/// Take `report`'s requested minimum in place of the one its processor
/// recorded first, when it asked again ([`request_again`]). Processor,
/// outcome and level counts stay as recorded. Only while that processor
/// is the one recorded (the boot processor, before the others start)
/// is its first minimum known to be its alone and cleared; past that
/// the new minimum joins the range.
pub fn replace_minimum(&self, report: Report) {
let bounds = match report.outcome {
Outcome::Hwp { bounds, .. } | Outcome::Cppc { bounds, .. } => bounds,
_ => return,
};
let recorded: u32 = self
.classes
.iter()
.map(|class| class.processors.load(Ordering::Relaxed))
.sum();
let minimum = &self.classes[report.class.index()].minimum;
if recorded <= 1 {
minimum.clear();
}
minimum.add(bounds.minimum);
}
/// The energy preference the Intel requests took: `balanced` under
/// [`INTEL_BALANCED`] where a processor took an HWP request, otherwise
/// `performance`.
fn preference(&self) -> &'static str {
if INTEL_BALANCED.load(Ordering::Relaxed) && self.count(0) > 0 {
"balanced"
} else {
"performance"
}
}
fn count(&self, index: usize) -> u32 {
self.classes
.iter()
@@ -874,7 +963,7 @@ impl Tally {
let mut line = format!(
"HOST PERFORMANCE hwp={} cppc={} hwp_without_epp={} unpublished={} legacy={} \
package_controlled={package} highest={} requested_minimum={} perf_ctl={} pstate={} \
preference=performance\n",
preference={}\n",
self.count(0),
self.count(1),
self.count(4),
@@ -884,6 +973,7 @@ impl Tally {
self.merged(|class| &class.minimum),
self.count(2),
self.count(3),
self.preference(),
);
for class in Class::ALL {
if let Some(text) = self.classes[class.index()].line(class) {
@@ -187,7 +187,7 @@ fn unpublished_levels_keep_the_firmware_request() {
);
assert!(registers.writes().is_empty());
// Lowest above highest.
assert_eq!(intel_request(0x4000_0020, 0, true), None);
assert_eq!(intel_request(0x4000_0020, 0, true, false), None);
let mut registers = Logged::with(&[(AMD_CPPC_ENABLE, 1), (AMD_CPPC_REQ, 0x8000_ff01)]);
assert_eq!(request(amd(true), &mut registers), Outcome::Unpublished);
assert!(registers.writes().is_empty());
@@ -553,3 +553,67 @@ fn core_classes_follow_cpuid() {
assert_eq!(Class::amd(1 << 30, 0), Class::Performance);
assert_eq!(Class::amd(0, 1 << 28), Class::Uniform, "not heterogeneous");
}
#[test]
fn balanced_intel_request_lets_the_cores_slow_down() {
// Capabilities: lowest 0x01, most efficient 0x08, guaranteed 0x11,
// highest 0x38 (an i5-1235U performance core).
let capabilities = 0x0108_1138;
// Firmware: package control (bit 42), EPP 0x80, minimum and maximum
// 0x11, and bits above that stay.
let current = 0xdead_0400_8000_1111;
let (value, bounds) = intel_request(capabilities, current, true, true).unwrap();
assert_eq!(value, 0xdead_0000_8000_3801, "{value:#x}");
assert_eq!(
bounds,
Bounds {
minimum: 0x01,
maximum: 0x38
}
);
// Without EPP the preference field (here the firmware's 0x80) is left
// as found.
let (value, _) = intel_request(capabilities, current, false, true).unwrap();
assert_eq!(value, 0xdead_0000_8000_3801, "{value:#x}");
// The default stays full speed.
let (value, bounds) = intel_request(capabilities, current, true, false).unwrap();
assert_eq!(value, 0xdead_0000_0000_3838, "{value:#x}");
assert_eq!(
bounds,
Bounds {
minimum: 0x38,
maximum: 0x38
}
);
}
#[test]
fn asking_again_replaces_the_boot_processors_minimum_without_counting_it_twice() {
let tally = Tally::new();
let hwp = |minimum| {
plain(Outcome::Hwp {
levels: Levels {
highest: 0x30,
sustained: 0x24,
lowest: 0x08,
},
bounds: Bounds {
minimum,
maximum: 0x30,
},
epp: true,
package: false,
})
};
tally.record(hwp(0x30));
tally.replace_minimum(hwp(0x08));
let line = tally.summary();
assert!(line.starts_with("HOST PERFORMANCE hwp=1 "), "{line}");
assert!(line.contains(" requested_minimum=8 "), "{line}");
assert!(line.contains(" processors=1 "), "{line}");
// Once other processors have recorded, the first minimum may be shared,
// so the new one joins the range.
tally.record(hwp(0x08));
tally.replace_minimum(hwp(0x30));
assert!(tally.summary().contains(" requested_minimum=8-48 "));
}
+238
View File
@@ -0,0 +1,238 @@
//! When `stela-boot`'s input service polls each host keyboard and pointer
//! (`engine::input`), how a due poll meets the host drivers' lock another
//! processor holds, and the spread of the polls' lateness and of the gaps
//! between the inputs they deliver.
//!
//! Every poll runs under the host drivers' lock, which the GPUs' pump holds
//! while Linux runs, a step at a time, and lets go after its step once a
//! core spins for it. A device is due once its interval has passed since
//! its last poll. A due poll that finds the lock taken tries again at the
//! next service turn; once it is [`LATE_WAIT_MICROS`] late it spins for
//! the lock instead, as a waiter the pump lets in after its step, for the
//! turn's [`wait_micros`] at most, once a turn. A wait the holder outlasted
//! (one Linux step can take tens of milliseconds) is not tried again for
//! [`WAIT_BACKOFF_MICROS`], so a poll never spins through a long step.
//!
//! A device's interval is its looks' cost: a poll that delivered nothing
//! costs the boot PE what it took, and polls are spaced [`COST_SHARE`] times
//! that recent cost apart, between [`IDLE_MILLIS`] and [`SLOW_MILLIS`] when
//! idle and at most [`ACTIVE_MILLIS`] for [`ACTIVE_SECONDS`] after its last
//! input. A poll that delivered input is not counted: its time is the
//! input's own transfer, which an I2C touchpad behind an interrupt pin pays
//! only when its pin says a report is ready (about 0.75 ms for a report at
//! 400 kHz), so counting it held a moving finger to one read every 32 ms.
/// A device that gave no input for [`ACTIVE_SECONDS`] is polled this often
/// at most. A poll can be a port or register access a hypervisor takes to
/// its device model; USB low-speed keyboards and mice are polled as rarely.
pub const IDLE_MILLIS: u64 = 8;
/// How long a device is polled at every service turn after it last gave
/// input, so a pointer's motion keeps its full rate.
pub const ACTIVE_SECONDS: u64 = 5;
/// A device's looks may take at most one part in this of the boot PE: a
/// look costing more is spaced this many times its cost apart. A port read
/// that costs a microsecond on hardware can wait milliseconds for a
/// hypervisor's device-model lock; the boot PE's time is the guest's.
pub const COST_SHARE: u64 = 32;
/// The longest an idle device waits for its next poll however costly its
/// looks are, which its first input can wait.
pub const SLOW_MILLIS: u64 = 250;
/// The longest an active device waits for its next poll.
pub const ACTIVE_MILLIS: u64 = 32;
/// How late a due poll may run before it waits for a taken lock.
pub const LATE_WAIT_MICROS: u64 = 2000;
/// How long no poll waits for the lock after a wait the holder outlasted.
pub const WAIT_BACKOFF_MICROS: u64 = 8000;
/// The longest wait of a turn on a PE whose guest code waits for it (the
/// boot PE's step, which holds every PE's time), and of any other turn: a
/// waiting PE's or the host core's, whose guest is idle. The GPUs' pump's
/// Linux steps take about 0.2 ms on average.
pub const STEP_WAIT_MICROS: u64 = 250;
pub const WAIT_MICROS: u64 = 1000;
/// Gaps between a device's deliveries longer than this are pauses between
/// motions, not the rate of one, and are left out of its gap spread.
pub const GAP_MILLIS: u64 = 250;
/// The longest wait for the lock in a turn ([`STEP_WAIT_MICROS`]).
pub const fn wait_micros(step: bool) -> u64 {
if step { STEP_WAIT_MICROS } else { WAIT_MICROS }
}
/// One device's pace, in counter ticks of `per_micro` a microsecond.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Device {
/// The counter at its last poll.
looked: u64,
/// The counter at its last poll that delivered input.
active: u64,
/// Its looks' recent cost: an eighth of each poll that delivered
/// nothing joins seven eighths of the last.
cost: u64,
/// The counter at its last delivery, for the gap spread.
delivered: Option<u64>,
}
/// What a turn does with a device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Plan {
/// Not due yet.
Later,
/// Due, `late` ticks past its interval: take the lock if it is free,
/// else spin for it for `wait_micros` at most (none when zero).
Poll { late: u64, wait_micros: u64 },
}
/// One turn's waits: at most one, of at most `wait_micros`.
#[derive(Clone, Copy, Debug)]
pub struct Turn {
wait_micros: u64,
waited: bool,
}
impl Turn {
pub const fn new(wait_micros: u64) -> Self {
Self {
wait_micros,
waited: false,
}
}
}
/// The waits across turns: after one the holder outlasted, none until the
/// counter passes `quiet_until`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Waits {
quiet_until: Option<u64>,
}
impl Waits {
fn allowed(&self, now: u64) -> bool {
// The counter may wrap: the quiet time is over once `now` is no
// more than half the counter's range past it.
self.quiet_until
.is_none_or(|until| now.wrapping_sub(until) < u64::MAX / 2)
}
/// A wait that began at `now` found the lock still held at its end.
pub fn outlasted(&mut self, now: u64, per_micro: u64) {
self.quiet_until = Some(now.wrapping_add(per_micro * WAIT_BACKOFF_MICROS));
}
}
impl Device {
/// Whether it delivered input within [`ACTIVE_SECONDS`] of `now`.
pub fn active(&self, now: u64, per_micro: u64) -> bool {
now.wrapping_sub(self.active) < per_micro * 1_000_000 * ACTIVE_SECONDS
}
/// The ticks between its polls at `now`.
pub fn interval(&self, now: u64, per_micro: u64) -> u64 {
let millis = per_micro * 1000;
let spaced = self.cost.saturating_mul(COST_SHARE);
if self.active(now, per_micro) {
spaced.min(millis * ACTIVE_MILLIS)
} else {
spaced.clamp(millis * IDLE_MILLIS, millis * SLOW_MILLIS)
}
}
/// What `turn` does with this device at `now`.
pub fn plan(&self, now: u64, per_micro: u64, turn: &mut Turn, waits: &Waits) -> Plan {
let since = now.wrapping_sub(self.looked);
let interval = self.interval(now, per_micro);
if since < interval {
return Plan::Later;
}
let late = since - interval;
let wait = late >= per_micro * LATE_WAIT_MICROS
&& !turn.waited
&& turn.wait_micros != 0
&& waits.allowed(now);
if wait {
turn.waited = true;
}
Plan::Poll {
late,
wait_micros: if wait { turn.wait_micros } else { 0 },
}
}
/// A poll at `now` took `took` ticks inside the lock and `delivered`
/// input or not: the gap since its last delivery, when it delivered
/// within [`GAP_MILLIS`] of it.
pub fn polled(&mut self, now: u64, took: u64, delivered: bool, per_micro: u64) -> Option<u64> {
self.looked = now;
if !delivered {
self.cost = self.cost - self.cost / 8 + took / 8;
return None;
}
self.active = now;
let gap = self
.delivered
.map(|at| now.wrapping_sub(at))
.filter(|gap| *gap < per_micro * 1000 * GAP_MILLIS);
self.delivered = Some(now);
gap
}
}
/// The upper bounds of [`Spread`]'s buckets, in microseconds; the last
/// bucket is open.
const BOUNDS_US: [u64; 11] = [
125, 250, 500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000,
];
/// How a set of times spread, kept as counts in doubling buckets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Spread {
counts: [u32; BOUNDS_US.len() + 1],
max_us: u64,
}
impl Spread {
pub fn add(&mut self, us: u64) {
let bucket = BOUNDS_US
.iter()
.position(|bound| us <= *bound)
.unwrap_or(BOUNDS_US.len());
self.counts[bucket] = self.counts[bucket].saturating_add(1);
self.max_us = self.max_us.max(us);
}
pub fn count(&self) -> u64 {
self.counts.iter().map(|count| u64::from(*count)).sum()
}
/// The time at or below which `percent` of the times lie: the upper
/// bound of the bucket that holds that rank, or the largest time when
/// that is smaller or the bucket is the open one. `None` when empty.
pub fn percentile(&self, percent: u64) -> Option<u64> {
let count = self.count();
if count == 0 {
return None;
}
let rank = (count * percent.min(100)).div_ceil(100).max(1);
let mut seen = 0;
for (bucket, n) in self.counts.iter().enumerate() {
seen += u64::from(*n);
if seen >= rank {
let bound = BOUNDS_US.get(bucket).copied().unwrap_or(u64::MAX);
return Some(bound.min(self.max_us));
}
}
Some(self.max_us)
}
}
/// `p50+p95+max` in microseconds, `-` when empty.
impl core::fmt::Display for Spread {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match (self.percentile(50), self.percentile(95)) {
(Some(median), Some(high)) => write!(f, "{median}+{high}+{}", self.max_us),
_ => f.write_str("-"),
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,372 @@
extern crate std;
use super::*;
use std::string::ToString;
/// A 24 MHz counter, as `stela-boot`'s corrected count.
const PER_MICRO: u64 = 24;
const fn us(micros: u64) -> u64 {
micros * PER_MICRO
}
const fn ms(millis: u64) -> u64 {
us(millis * 1000)
}
/// A device last polled at `looked` that last delivered at `active`, with
/// looks costing `cost` ticks.
fn device(looked: u64, active: u64, cost: u64) -> Device {
Device {
looked,
active,
cost,
delivered: None,
}
}
/// A time long after any delivery: the device is idle there.
const IDLE: u64 = ms(60_000);
#[test]
fn an_idle_device_is_polled_at_most_every_idle_millis() {
let idle = device(IDLE, 0, us(2));
assert_eq!(idle.interval(IDLE, PER_MICRO), ms(IDLE_MILLIS));
let mut turn = Turn::new(WAIT_MICROS);
let waits = Waits::default();
assert_eq!(
idle.plan(IDLE + ms(IDLE_MILLIS) - 1, PER_MICRO, &mut turn, &waits),
Plan::Later
);
assert_eq!(
idle.plan(IDLE + ms(IDLE_MILLIS), PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: 0,
wait_micros: 0
}
);
}
#[test]
fn costly_looks_space_polls_within_their_bounds() {
// An empty look that costs a millisecond (a hypervisor's port read).
let costly = device(IDLE, 0, ms(1));
assert_eq!(costly.interval(IDLE, PER_MICRO), ms(COST_SHARE));
let ruinous = device(IDLE, 0, ms(100));
assert_eq!(ruinous.interval(IDLE, PER_MICRO), ms(SLOW_MILLIS));
// Active, the same looks are spaced no more than ACTIVE_MILLIS apart,
// and cheap ones not at all.
let active = device(IDLE, IDLE, ms(100));
assert_eq!(active.interval(IDLE, PER_MICRO), ms(ACTIVE_MILLIS));
let cheap = device(IDLE, IDLE, us(2));
assert_eq!(cheap.interval(IDLE, PER_MICRO), us(64));
}
#[test]
fn the_reads_that_delivered_input_do_not_slow_the_device() {
// A touchpad behind an interrupt pin: a pin read costs 2 us, a report's
// read 750 us. Counting the reports held it to one read every 24 ms.
let mut pad = Device::default();
let mut now = IDLE;
for _ in 0..16 {
pad.polled(now, us(2), false, PER_MICRO);
now += ms(1);
}
for _ in 0..64 {
pad.polled(now, us(750), true, PER_MICRO);
now += ms(8);
}
assert!(pad.active(now, PER_MICRO));
assert!(
pad.interval(now, PER_MICRO) <= us(64),
"{}",
pad.interval(now, PER_MICRO)
);
// Empty looks that cost as much do slow it, as before.
for _ in 0..64 {
pad.polled(now, us(750), false, PER_MICRO);
now += ms(1);
}
assert!(pad.interval(now, PER_MICRO) >= ms(20));
}
#[test]
fn a_due_poll_waits_only_once_late_and_once_a_turn() {
let waits = Waits::default();
let looked = ms(1000);
let pad = device(looked, looked, 0);
let other = device(looked, looked, 0);
// Due but not yet late enough: only a try.
let mut turn = Turn::new(WAIT_MICROS);
let early = looked + us(LATE_WAIT_MICROS) - 1;
assert_eq!(
pad.plan(early, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: early - looked,
wait_micros: 0
}
);
// Late: the first device of the turn waits, the next only tries.
let late = looked + us(LATE_WAIT_MICROS);
let mut turn = Turn::new(WAIT_MICROS);
assert_eq!(
pad.plan(late, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: WAIT_MICROS
}
);
assert_eq!(
other.plan(late, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: 0
}
);
// A step's turn waits less.
let mut step = Turn::new(wait_micros(true));
assert_eq!(
pad.plan(late, PER_MICRO, &mut step, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: STEP_WAIT_MICROS
}
);
}
#[test]
fn a_wait_the_holder_outlasted_is_not_tried_again_for_the_backoff() {
let looked = ms(1000);
let pad = device(looked, looked, 0);
let mut waits = Waits::default();
let late = looked + ms(3);
waits.outlasted(late, PER_MICRO);
let mut turn = Turn::new(WAIT_MICROS);
let within = late + us(WAIT_BACKOFF_MICROS) - 1;
assert!(matches!(
pad.plan(within, PER_MICRO, &mut turn, &waits),
Plan::Poll { wait_micros: 0, .. }
));
let after = late + us(WAIT_BACKOFF_MICROS);
assert!(matches!(
pad.plan(after, PER_MICRO, &mut turn, &waits),
Plan::Poll {
wait_micros: WAIT_MICROS,
..
}
));
}
#[test]
fn the_backoff_holds_across_the_counters_wrap() {
let mut waits = Waits::default();
let at = u64::MAX - us(100);
waits.outlasted(at, PER_MICRO);
assert!(!waits.allowed(at.wrapping_add(us(WAIT_BACKOFF_MICROS) - 1)));
assert!(waits.allowed(at.wrapping_add(us(WAIT_BACKOFF_MICROS))));
}
#[test]
fn gaps_count_only_within_a_motion() {
let mut pad = Device::default();
let start = ms(10_000);
assert_eq!(pad.polled(start, 0, true, PER_MICRO), None);
assert_eq!(pad.polled(start + ms(8), 0, true, PER_MICRO), Some(ms(8)));
// An empty poll between keeps the gap from the last delivery.
assert_eq!(pad.polled(start + ms(12), 0, false, PER_MICRO), None);
assert_eq!(pad.polled(start + ms(16), 0, true, PER_MICRO), Some(ms(8)));
// A pause between two motions is no gap.
assert_eq!(
pad.polled(start + ms(16 + GAP_MILLIS), 0, true, PER_MICRO),
None
);
}
#[test]
fn a_spread_reports_bucket_bounds_and_its_largest_time() {
let mut spread = Spread::default();
assert_eq!(spread.percentile(50), None);
assert_eq!(spread.to_string(), "-");
for _ in 0..90 {
spread.add(700);
}
for _ in 0..9 {
spread.add(3000);
}
spread.add(31_000);
assert_eq!(spread.count(), 100);
assert_eq!(spread.percentile(50), Some(1000));
assert_eq!(spread.percentile(95), Some(4000));
assert_eq!(spread.percentile(100), Some(31_000));
assert_eq!(spread.to_string(), "1000+4000+31000");
// A bound above every time is the largest time; the open bucket too.
let mut one = Spread::default();
one.add(9);
assert_eq!(one.to_string(), "9+9+9");
let mut huge = Spread::default();
huge.add(500_000);
assert_eq!(huge.percentile(50), Some(500_000));
}
/// A fake host-drivers lock: the GPUs' pump runs Linux in steps of
/// `step_us`, `steps` of them every `period_us`, and one step of `long_us`
/// at the start of every second. A waiter spinning for the lock is let in
/// at the end of the step in progress. `None` while free, else the end of
/// the step that holds it.
#[derive(Clone, Copy)]
struct Pump {
period_us: u64,
steps: u64,
step_us: u64,
long_us: u64,
}
impl Pump {
fn holds(&self, now: u64) -> Option<u64> {
let second = now - now % ms(1000);
if now - second < us(self.long_us) {
return Some(second + us(self.long_us));
}
let start = now - now % us(self.period_us);
let into = now - start;
(into < us(self.steps * self.step_us))
.then(|| start + (into / us(self.step_us) + 1) * us(self.step_us))
}
}
/// What a touchpad behind an interrupt pin gave the guest over a run.
struct Outcome {
reports: u64,
read: u64,
/// From a report's readiness to its read.
latency: Spread,
gaps: Spread,
spun_us: u64,
}
/// Run service turns every `turn_us` for `seconds` against `pump`, with a
/// touchpad that has a report ready every `report_us`: its pin read costs
/// 2 us and a report's read 750 us.
fn run(pump: Pump, turn_us: u64, report_us: u64, seconds: u64) -> Outcome {
let mut pad = Device::default();
let mut waits = Waits::default();
let mut outcome = Outcome {
reports: 0,
read: 0,
latency: Spread::default(),
gaps: Spread::default(),
spun_us: 0,
};
// The next report not yet read.
let mut next_report = us(report_us);
let end = ms(seconds * 1000);
let mut now = us(turn_us);
while now < end {
let mut turn = Turn::new(WAIT_MICROS);
if let Plan::Poll { wait_micros, .. } = pad.plan(now, PER_MICRO, &mut turn, &waits) {
let entered = match pump.holds(now) {
None => Some(now),
Some(step_end) if wait_micros != 0 => {
if step_end - now <= us(wait_micros) {
outcome.spun_us += (step_end - now) / PER_MICRO;
Some(step_end)
} else {
outcome.spun_us += wait_micros;
waits.outlasted(now, PER_MICRO);
None
}
}
Some(_) => None,
};
if let Some(at) = entered {
let mut delivered = false;
while next_report <= at {
outcome.latency.add((at - next_report) / PER_MICRO);
outcome.read += 1;
next_report += us(report_us);
delivered = true;
}
let took = if delivered { us(750) } else { us(2) };
if let Some(gap) = pad.polled(now, took, delivered, PER_MICRO) {
outcome.gaps.add(gap / PER_MICRO);
}
}
}
now += us(turn_us);
}
outcome.reports = end / us(report_us);
outcome
}
const FREE: Pump = Pump {
period_us: 1000,
steps: 0,
step_us: 1,
long_us: 0,
};
#[test]
fn a_free_lock_reads_every_report_within_a_turn() {
let outcome = run(FREE, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(95).unwrap() <= 500);
assert_eq!(outcome.gaps.percentile(50), Some(8000));
assert_eq!(outcome.spun_us, 0);
}
#[test]
fn a_busy_pump_in_short_steps_leaves_reads_at_the_reports_rate() {
// Half the time held, in Linux steps of 250 us, the pump's own mean.
let pump = Pump {
period_us: 2000,
steps: 4,
step_us: 250,
long_us: 0,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(95).unwrap() <= 2000);
assert!(outcome.gaps.percentile(95).unwrap() <= 16000);
// Rate: at least 120 reads a second over the run.
assert!(outcome.read >= 1200, "{}", outcome.read);
}
#[test]
fn a_long_linux_step_is_waited_for_a_few_times_not_spun_through() {
// The pump held three fifths of the time in 250 us steps, as in the
// busiest tenth of the logs' windows, and one 25 ms Linux step a second,
// which nothing can shorten.
let pump = Pump {
period_us: 2500,
steps: 6,
step_us: 250,
long_us: 25_000,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(50).unwrap() <= 1000);
assert!(outcome.latency.percentile(95).unwrap() <= 2000);
let short = run(Pump { long_us: 0, ..pump }, 500, 8000, 10);
// The short steps cost the turns' waits little, and each long step
// at most four outlasted waits of WAIT_MICROS, one per backoff.
assert!(short.spun_us <= 10 * 20_000, "{}", short.spun_us);
let long = outcome.spun_us - short.spun_us;
assert!(long <= 10 * 4 * WAIT_MICROS, "{long}");
}
#[test]
fn a_lock_held_nine_tenths_still_gives_every_report_at_a_bounded_spin() {
// 900 us steps with 100 us free between: tries mostly fail, and a late
// poll waits out about half a step. Every report is still read within
// a few milliseconds, at about a quarter of an idle PE's time.
let pump = Pump {
period_us: 1000,
steps: 1,
step_us: 900,
long_us: 0,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(50).unwrap() <= 2000);
assert!(outcome.latency.percentile(95).unwrap() <= 4000);
assert!(outcome.spun_us <= 10 * 300_000, "{}", outcome.spun_us);
}
@@ -0,0 +1,229 @@
//! The page Install macOS opens before its disk picker on a PC whose
//! firmware shows, before Stela starts, no graphics card Stela can start
//! macOS with (`stela-boot`'s `choice::menu`). The install draws through no
//! GPU and would finish, an hour or more later, and the installed macOS then
//! stops at its first start: four reporters met exactly that. The page says
//! why and asks; it refuses nothing, since a card the firmware keeps powered
//! off answers only after Stela has started (`NvidiaNotice::NotYet`).
//!
//! Focus starts on Back, so Enter pressed out of habit goes back to the
//! menu; Right or Tab reaches Install anyway, as the disk picker's
//! confirmation does. What the page holds and how keys change it are here,
//! where the host tests reach them; `stela-boot` paints it.
use alloc::vec::Vec;
use stela_loader::host_firmware::bundle::NvidiaNotice;
/// Said on a PC with no NVIDIA graphics card: the install itself draws
/// through no GPU and would finish, and the installed macOS then could not
/// start.
pub const NO_NVIDIA_GPU: &str = "No NVIDIA graphics card found: macOS can be installed, but it \
starts only with a GeForce GTX 16 or RTX 20, 30, 40 or 50 series card.";
/// Said on a PC whose NVIDIA cards are all of chips Stela has no driver
/// for, older or newer than the series it names.
pub const NO_DRIVEN_NVIDIA_GPU: &str = "The NVIDIA graphics card here is not one Stambha drives: \
macOS can be installed, but it starts only with a GeForce GTX 16 or RTX 20, 30, 40 or 50 \
series card.";
/// Said when no NVIDIA card Stela drives answers yet but a PCI port shows
/// nothing below it: a card the firmware left powered off there, as on some
/// laptops, answers only after Stela powers the port on.
pub const NO_NVIDIA_GPU_YET: &str = "No NVIDIA graphics card Stambha drives found yet: a card the \
PC keeps powered off, as some laptops do, is found only after Stambha has started. macOS can \
be installed, but it starts only with a GeForce GTX 16 or RTX 20, 30, 40 or 50 series card.";
/// The page's title.
pub const TITLE: &str = "Install macOS on this PC?";
/// The page's question, under the reason.
pub const ASK: &str = "Installing takes an hour or more. Choose Install anyway only if you \
know this PC has one of those cards.";
/// The words for the firmware census's `notice`; none when a card Stela
/// drives answers.
pub fn gpu_words(notice: NvidiaNotice) -> Option<&'static str> {
match notice {
NvidiaNotice::Driven => None,
NvidiaNotice::Absent => Some(NO_NVIDIA_GPU),
NvidiaNotice::NotDriven => Some(NO_DRIVEN_NVIDIA_GPU),
NvidiaNotice::NotYet => Some(NO_NVIDIA_GPU_YET),
}
}
/// A key as the page reads it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Key {
Left,
Right,
Tab,
Enter,
Escape,
Other,
}
/// The page's buttons, left to right.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Focus {
Back,
Install,
}
/// What a key press leads to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
Stay,
/// Back to the startup menu, nothing started.
Back,
/// On to the disk picker.
Install,
}
/// The page: its reason and the button with the focus.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Caution {
pub reason: &'static str,
focus: Focus,
}
impl Caution {
/// The page for the census's `notice`; `None` when a card Stela drives
/// answers, or when another vendor's card this image drives does
/// (`other_drawn`), and Install macOS goes on to the picker unasked.
pub fn new(notice: NvidiaNotice, other_drawn: bool) -> Option<Self> {
if other_drawn {
return None;
}
Some(Self {
reason: gpu_words(notice)?,
focus: Focus::Back,
})
}
pub fn focus(&self) -> Focus {
self.focus
}
pub fn press(&mut self, key: Key) -> Step {
match key {
Key::Escape => Step::Back,
Key::Left => {
self.focus = Focus::Back;
Step::Stay
}
Key::Right => {
self.focus = Focus::Install;
Step::Stay
}
Key::Tab => {
self.focus = match self.focus {
Focus::Back => Focus::Install,
Focus::Install => Focus::Back,
};
Step::Stay
}
Key::Enter => match self.focus {
Focus::Back => Step::Back,
Focus::Install => Step::Install,
},
Key::Other => Step::Stay,
}
}
}
/// `text` in lines of at most `columns` characters, broken between words;
/// a word longer than a line has a line of its own.
pub fn wrap(text: &str, columns: usize) -> Vec<&str> {
let columns = columns.max(1);
let mut lines = Vec::new();
let mut start: Option<usize> = None;
let mut end = 0;
for (at, word) in text
.split_ascii_whitespace()
.map(|word| (word.as_ptr() as usize - text.as_ptr() as usize, word))
{
let word_end = at + word.len();
match start {
Some(first) if word_end - first <= columns => end = word_end,
Some(first) => {
lines.push(&text[first..end]);
(start, end) = (Some(at), word_end);
}
None => (start, end) = (Some(at), word_end),
}
}
if let Some(first) = start {
lines.push(&text[first..end]);
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_pc_without_a_card_stela_drives_is_asked() {
assert_eq!(Caution::new(NvidiaNotice::Driven, false), None);
for notice in [
NvidiaNotice::Absent,
NvidiaNotice::NotDriven,
NvidiaNotice::NotYet,
] {
let caution = Caution::new(notice, false).expect("asked");
assert_eq!(Some(caution.reason), gpu_words(notice));
assert_eq!(caution.focus(), Focus::Back);
// Another vendor's card this image draws with is macOS's GPU.
assert_eq!(Caution::new(notice, true), None);
}
assert_eq!(gpu_words(NvidiaNotice::Absent), Some(NO_NVIDIA_GPU));
assert_eq!(
gpu_words(NvidiaNotice::NotDriven),
Some(NO_DRIVEN_NVIDIA_GPU)
);
assert_eq!(gpu_words(NvidiaNotice::NotYet), Some(NO_NVIDIA_GPU_YET));
}
#[test]
fn enter_out_of_habit_goes_back() {
let mut caution = Caution::new(NvidiaNotice::Absent, false).unwrap();
assert_eq!(caution.press(Key::Enter), Step::Back);
assert_eq!(caution.press(Key::Other), Step::Stay);
assert_eq!(caution.press(Key::Escape), Step::Back);
}
#[test]
fn install_anyway_takes_a_move_then_enter() {
let mut caution = Caution::new(NvidiaNotice::NotYet, false).unwrap();
assert_eq!(caution.press(Key::Right), Step::Stay);
assert_eq!(caution.focus(), Focus::Install);
assert_eq!(caution.press(Key::Enter), Step::Install);
let mut caution = Caution::new(NvidiaNotice::NotYet, false).unwrap();
assert_eq!(caution.press(Key::Tab), Step::Stay);
assert_eq!(caution.focus(), Focus::Install);
assert_eq!(caution.press(Key::Tab), Step::Stay);
assert_eq!(caution.focus(), Focus::Back);
caution.press(Key::Right);
caution.press(Key::Left);
assert_eq!(caution.press(Key::Enter), Step::Back);
// Escape leaves even with Install focused.
caution.press(Key::Right);
assert_eq!(caution.press(Key::Escape), Step::Back);
}
#[test]
fn wrap_breaks_between_words_within_the_width() {
assert_eq!(wrap("", 10), Vec::<&str>::new());
assert_eq!(wrap("one two three", 7), ["one two", "three"]);
assert_eq!(wrap(" one two ", 20), ["one two"]);
assert_eq!(wrap("a verylongword b", 4), ["a", "verylongword", "b"]);
for line in wrap(NO_NVIDIA_GPU_YET, 50) {
assert!(line.len() <= 50, "{line:?}");
}
let joined: Vec<&str> = wrap(ASK, 30)
.into_iter()
.flat_map(str::split_ascii_whitespace)
.collect();
assert_eq!(joined, ASK.split_ascii_whitespace().collect::<Vec<_>>());
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Install mode's options in a boot's chosen option line: `--install-mode
//! verify` and `--install-build BUILD`, which `stela.efi` reads before
//! any other parsing (`payload::run`) to find and verify a restore payload
//! and stop. Every other word goes on to the mount's own parser.
use crate::Result;
use alloc::string::String;
use stela_contracts::refuse;
/// Install mode's option that turns it on.
pub const MODE: &str = "--install-mode";
/// The build of the payload install mode verifies.
pub const BUILD: &str = "--install-build";
/// The install-mode options a line holds.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct InstallMode {
pub verify: bool,
pub build: Option<String>,
}
/// Read the install options in `options`: each of [`MODE`] and [`BUILD`],
/// spelled exactly, wherever it stands, takes the word after it. Every
/// other word is the mount's, which its own parser reads and refuses when
/// it does not know it, so no option of the mount's, whatever its name or
/// place in the line (a flag without a value before it among them), is
/// read as one of install mode's.
pub fn parse(options: &str) -> Result<InstallMode> {
let mut install = InstallMode::default();
let mut words = options.split_ascii_whitespace();
while let Some(name) = words.next() {
if name != MODE && name != BUILD {
continue;
}
let value = words
.next()
.ok_or(refuse!("install option without a value"))?;
match name {
MODE if value == "verify" => install.verify = true,
MODE => return Err(refuse!("--install-mode must be verify")),
_ => install.build = Some(value.into()),
}
}
if !install.verify && install.build.is_some() {
return Err(refuse!("install options need --install-mode"));
}
Ok(install)
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::{string::ToString, vec::Vec};
/// The Install macOS line setup writes (`stela-cli`'s setup tests).
const INSTALL_LINE: &str = "--system --storage 74EXN0LI:11111111-2222-3333-4444-555555555555 \
--nor 74EXN0LI:22222222-3333-4444-5555-666666666666 --bundle \\stela\\boot\\22A\\r \
--ecid 0x0000000000000001 --install \\stela\\install\\22A\\payload.json \
--install-source 33333333-4444-5555-6666-777777777777 --development-restore";
/// `options` with `inserted` among its words before word `at`.
fn with(options: &str, inserted: &str, at: usize) -> String {
let mut words: Vec<&str> = options.split_ascii_whitespace().collect();
let mut tail = words.split_off(at);
words.extend(inserted.split_ascii_whitespace());
words.append(&mut tail);
words.join(" ")
}
#[test]
fn install_mode_reads_its_mode_and_build_and_refuses_bad_ones() {
let verify = parse("--install-mode verify --install-build 22A").unwrap();
assert_eq!(
verify,
InstallMode {
verify: true,
build: Some("22A".to_string())
}
);
assert_eq!(
parse("--system --storage x").unwrap(),
InstallMode::default()
);
for line in [
"--install-mode other",
"--install-mode",
"--install-build 22A",
"--install-mode verify --install-build",
] {
assert!(parse(line).is_err(), "{line}");
}
}
/// No option of the mount's, whatever its name and wherever it stands
/// in setup's Install line, is read as an install-mode option: the
/// line goes on to the mount whole.
#[test]
fn no_mount_option_anywhere_in_the_install_line_is_read_as_install_mode() {
let options = [
"--medium-read-ahead 0",
"--install-source 33333333-4444-5555-6666-777777777777",
"--install \\stela\\install\\22A\\payload.json",
"--install-future 3",
"--verify-on-read",
"--update-restore",
"--external-disks",
"--usb-storage A",
];
let words = INSTALL_LINE.split_ascii_whitespace().count();
assert_eq!(words, 14);
let read = |line: &str| parse(line).unwrap_or_else(|error| panic!("{line}: {error:?}"));
for option in options {
for at in 1..=words {
let line = with(INSTALL_LINE, option, at);
assert_eq!(read(&line), InstallMode::default(), "{line}");
}
}
// Install mode's own options are read wherever they stand.
for at in 1..=words {
let line = with(
INSTALL_LINE,
"--install-mode verify --install-build 22A",
at,
);
assert!(read(&line).verify, "{line}");
}
}
}
+284
View File
@@ -0,0 +1,284 @@
//! Whether i915 starts an Intel GPU with its GuC (the microcontroller that
//! submits its work), and the record a boot leaves for the next one to
//! decide it by.
//!
//! On the platforms whose i915 default is GuC submission (Alder Lake P,
//! Raptor Lake P and U, Alder Lake N, Raptor Lake S, DG1) a failed GuC
//! wedges the GT or loses the Metal device, and i915 cannot be unbound and
//! probed again in the same boot: its unload is never run here, and a
//! failed probe's interrupt line is retired for good. So the boot that sees
//! the GuC fail writes a [`RECORD`] line in its log, and the next boot,
//! reading it back as the Wi-Fi page's record is read
//! (`stela-boot`'s `log_file`, handed to the engine with the rest of the
//! loader's reading: the engine runs a copy of the image taken before any
//! static was set), starts i915 with `i915.enable_guc=0`: its
//! execlists submission, which every Gen12 part has, with i915's own
//! frequency and RC6 control in place of the GuC's SLPC. A boot without the
//! GuC writes the record again, so the boots after it stay without it.
//!
//! A record names the device and this build ([`BUILD`]); one of another
//! device (the stick moved to another PC) or another build (a newer fix to
//! try) is passed over and the GuC is tried again. `--i915-guc off` turns
//! the GuC off by hand and `--i915-guc on` asks for it, the record still
//! followed; `--i915-guc auto`, the default, follows the record: test 4
//! starts Alder Lake P and Raptor Lake P or U with the GuC again
//! ([`off_by_default`]).
use alloc::{format, string::String};
/// What each record line starts with, after the log's time stamp.
pub const RECORD: &str = "INTEL GUC RECORD ";
/// The build whose records this one follows.
pub const BUILD: &str = "test4";
/// The marker line each boot's log starts with.
const BOOT: &str = "=== STELA BOOT ";
/// The hand-written `--i915-guc` setting.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Setting {
/// The platform's default ([`off_by_default`]); elsewhere the GuC,
/// unless the earlier boot recorded it failing.
#[default]
Auto,
/// No GuC: execlists submission.
Off,
/// The GuC, unless the earlier boot recorded it failing, also where
/// this build starts without it by default.
On,
}
impl Setting {
const NAMES: [(&'static str, Self); 3] =
[("auto", Self::Auto), ("off", Self::Off), ("on", Self::On)];
pub fn parse(word: &str) -> Option<Self> {
Self::NAMES
.iter()
.find(|(name, _)| *name == word)
.map(|(_, setting)| *setting)
}
pub fn name(self) -> &'static str {
Self::NAMES
.iter()
.find(|(_, setting)| *setting == self)
.map(|(name, _)| *name)
.unwrap_or_default()
}
}
/// Whether i915's GuC submission is its default on the platform i915's
/// table names (`uc_expand_default_options`), and execlists still drive it
/// with `enable_guc=0`. Tiger and Rocket Lake and Alder Lake S load no GuC
/// for submission by default; DG2 and Meteor Lake are left as they are.
pub fn falls_back(platform: &str) -> bool {
matches!(platform, "ALDERLAKE_P" | "ALDERLAKE_S" | "DG1")
}
/// Whether this test build starts the platform without its GuC unless
/// `--i915-guc on` asks for it: none in test 4. dev64-2 and test 3 started
/// Alder Lake P (Raptor Lake P and U, Alder Lake N) without it, as each of
/// Mesa's submissions had failed with -ENOMEM under the GuC in dev64-1, a
/// failure Linux patch 0237 removed in the same build. Under execlists
/// both Alder Lake P testers' boots (dev64's a7a0, MGKFN's 46a8) then lost
/// the GPU to an engine reset after minutes of the desktop, so test 4 tries
/// the GuC, whose SLPC sets the GPU's frequency, again; a GuC failure still
/// makes the next start go without it.
pub fn off_by_default(_platform: &str) -> bool {
false
}
/// How a boot's GuC failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cause {
/// i915's GuC start failed with this Linux error (`__uc_init_hw`'s
/// "GuC initialization failed").
Init(i32),
/// The GT was declared wedged at its start.
Wedged,
/// An error of the GuC's command transport (`GUC: CT:`).
Transport,
/// Another error i915 printed of its GuC.
Error,
/// The GPU's Metal device did not open while the GuC ran.
Metal,
}
impl Cause {
fn word(self) -> String {
match self {
Self::Init(error) => format!("init{error}"),
Self::Wedged => String::from("wedged"),
Self::Transport => String::from("transport"),
Self::Error => String::from("error"),
Self::Metal => String::from("metal"),
}
}
fn parse(word: &str) -> Option<Self> {
match word {
"wedged" => Some(Self::Wedged),
"transport" => Some(Self::Transport),
"error" => Some(Self::Error),
"metal" => Some(Self::Metal),
_ => word.strip_prefix("init")?.parse().ok().map(Self::Init),
}
}
/// The cause in the words of the boot's mode line.
pub fn told(self) -> String {
match self {
Self::Init(error) => format!("its start failed ({error})"),
Self::Wedged => String::from("the GT was declared wedged"),
Self::Transport => String::from("its command transport failed"),
Self::Error => String::from("i915 reported a GuC error"),
Self::Metal => String::from("the Metal device did not open"),
}
}
/// The cause a line i915 printed at error level or above tells of its
/// GuC, if any.
pub fn of_line(line: &str) -> Option<Self> {
if let Some((_, rest)) = line.split_once("GuC initialization failed ") {
let error = rest.split_ascii_whitespace().next()?;
return Some(Self::Init(error.parse().unwrap_or(0)));
}
if line.contains("Failed to initialize GPU, declaring it wedged") {
return Some(Self::Wedged);
}
if line.contains("GUC: CT:") {
return Some(Self::Transport);
}
(line.contains("GuC") || line.contains("GUC:")).then_some(Self::Error)
}
}
/// One record line: the GuC of `device` failed this boot (`kept` false),
/// or this boot ran without it after a failure and keeps it off (`kept`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Record {
pub device: u16,
pub cause: Cause,
pub kept: bool,
}
impl Record {
/// The log line, without the time stamp the log adds.
pub fn line(self) -> String {
format!(
"{RECORD}{} device={:04x} cause={} build={BUILD}\n",
if self.kept { "kept-off" } else { "failed" },
self.device,
self.cause.word()
)
}
/// The record of one log line of this build. Only a line that is the
/// record itself counts, not one that quotes it (a `PREVIOUS BOOT`
/// line repeats an earlier boot's).
fn parse(line: &str) -> Option<Self> {
let line = line.trim_start();
let line = match line.strip_prefix('[') {
Some(stamped) => stamped.split_once("] ")?.1,
None => line,
};
let mut words = line.strip_prefix(RECORD)?.split_ascii_whitespace();
let kept = match words.next()? {
"failed" => false,
"kept-off" => true,
_ => return None,
};
let device = u16::from_str_radix(words.next()?.strip_prefix("device=")?, 16).ok()?;
let cause = Cause::parse(words.next()?.strip_prefix("cause=")?)?;
(words.next()?.strip_prefix("build=")? == BUILD).then_some(Self {
device,
cause,
kept,
})
}
}
/// The newest record of the earlier boot in `stream`, the log's newest
/// bytes, read before this boot's marker line joins them.
pub fn earlier(stream: &[u8]) -> Option<Record> {
let text = String::from_utf8_lossy(stream);
let boot = text.rfind(BOOT).map_or(&text[..], |at| &text[at..]);
boot.lines().rev().find_map(Record::parse)
}
/// Whether this boot starts i915's GuC, and why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// GuC submission: i915's default, or `--i915-guc on`.
Guc,
/// No GuC: `--i915-guc off`.
OffByHand,
/// No GuC: this build's default on the platform ([`off_by_default`]).
OffByDefault,
/// No GuC: the earlier boot's record of this device.
Fallback(Cause),
}
impl Mode {
/// The mode for `device`, of i915's `platform`, under `setting` and the
/// earlier boot's `record`.
pub fn decide(setting: Setting, record: Option<Record>, device: u16, platform: &str) -> Self {
match (setting, record) {
(Setting::Off, _) => Self::OffByHand,
(Setting::Auto, _) if off_by_default(platform) => Self::OffByDefault,
(Setting::Auto | Setting::On, Some(record)) if record.device == device => {
Self::Fallback(record.cause)
}
(Setting::Auto | Setting::On, _) => Self::Guc,
}
}
pub fn guc(self) -> bool {
self == Self::Guc
}
/// The boot's one line saying which mode ran and why.
pub fn line(self, device: u16, record: Option<Record>) -> String {
match self {
Self::Guc => {
let passed = match record {
Some(record) if record.device != device => format!(
"; the record of device {:04x} is another PC's",
record.device
),
_ => String::new(),
};
format!(
"INTEL GUC on ({BUILD}): i915 starts {device:04x} with GuC submission and \
its guc_id taken before the lock{passed}; a GuC failure makes the next \
start go without it\n"
)
}
Self::OffByHand => format!(
"INTEL GUC off ({BUILD}): --i915-guc off, starting i915 on {device:04x} without \
GuC (execlists)\n"
),
Self::OffByDefault => format!(
"INTEL GUC off ({BUILD}): this test build's default on Alder Lake P and Raptor \
Lake P or U, starting i915 on {device:04x} without GuC (execlists); \
--i915-guc on starts it with GuC submission\n"
),
Self::Fallback(cause) => format!(
"INTEL GUC fallback ({BUILD}): GuC failed last boot ({}), starting i915 on \
{device:04x} without GuC (execlists)\n",
cause.told()
),
}
}
}
/// The stop a boot whose GuC failed and that has no Metal device gives.
pub fn second_start(cause: Cause) -> String {
format!(
"Intel graphics needs a second start; restart the PC. The GuC failed ({}), and the \
next start runs i915 without it",
cause.told()
)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,19 @@
[ 11.426] HOST FIRMWARE phase=before-ebs images=400 bytes=229486025 read_ms=0 catalog_ms=116
[ 11.427] STEP o Reading Stambha's settings (4 s) ms=4322
[ 11.458] STEP Checking the internal SSD and NVRAM t=11.458
[ 11.515] STEP o Checking the internal SSD and NVRAM ms=56
=== STELA BOOT 22 === version=0.6.1 firmware_clock=2026-11-24T19:52:37
[ 25.997] INTEL GUC on (dev64-1): i915 starts a7a0 with GuC submission and its guc_id taken before the lock; a GuC failure makes the next start go without it
[ 44.535] GPU DRIVER Vulkan device not created for the GPU at PciBusInfo { domain: 0, bus: 0, device: 2, function: 0 }: ERROR_DEVICE_LOST
[ 44.536] GPU 0000:00:02.0: Metal could not open: Device(DeviceLost)
[ 44.536] GPU SUMMARY 0000:00:02.0 8086:a7a0 rev 0x04 Intel Iris Xe Graphics: driver i915 1.6.0 device=0xa7a0 rev=0x4 eus=96; guc=none; memory=5072M; integrated: its memory is the GPU's share of RAM, of which Linux holds 66M of 5072M; the driver gave no memory size; no Vulkan device
[ 44.536] GPU FALLBACK 0000:00:02.0 Intel Iris Xe Graphics: i915 bound it, and its Metal device did not open: Metal could not open: Device(DeviceLost); it still shows the screens wired to it; no other GPU of this PC can draw in its place
[ 44.536] GPU USE draws macOS: none; shows the display: the Intel Iris Xe Graphics at 0000:00:02.0
[ 45.404] BOOT LOG boot=8 offset=0x810000 bytes=0x400000 head=0x43462f
[ 45.406] RTC ANCHOR ticks=0x2d8c429 unix=1795515029
[ 45.409] BUNDLE REPAIR NVRAM result of the last repair: every required step passed and the directories were created
[ 45.409] INTEL GUC RECORD failed device=a7a0 cause=metal build=dev64-1
[ 45.409]
[ 45.409] STELA FATAL Intel graphics needs a second start; restart the PC. The GuC failed (the Metal device did not open), and the next start runs i915 without it. macOS cannot run without a GPU: no Metal device opened on the GPUs that started; the lines above say why
[ 45.409] GPU firmware left running: the stop is on the CPU that unloads it, and i915's unload is not run from a stop there
[ 45.412] STELA STOPPED code=0x11; power off to continue
+275
View File
@@ -0,0 +1,275 @@
use super::*;
use alloc::string::ToString;
fn failed(device: u16, cause: Cause) -> Record {
Record {
device,
cause,
kept: false,
}
}
#[test]
fn a_setting_is_auto_off_or_on() {
assert_eq!(Setting::parse("auto"), Some(Setting::Auto));
assert_eq!(Setting::parse("off"), Some(Setting::Off));
assert_eq!(Setting::parse("on"), Some(Setting::On));
for word in ["AUTO", "Off", "ON", "1", "0", ""] {
assert_eq!(Setting::parse(word), None, "{word}");
}
assert_eq!(Setting::default(), Setting::Auto);
assert_eq!(Setting::Off.name(), "off");
assert_eq!(Setting::Auto.name(), "auto");
assert_eq!(Setting::On.name(), "on");
}
#[test]
fn a_record_round_trips_through_its_line() {
for cause in [
Cause::Init(-11),
Cause::Init(-110),
Cause::Wedged,
Cause::Transport,
Cause::Error,
Cause::Metal,
] {
for kept in [false, true] {
let record = Record {
device: 0xa7a0,
cause,
kept,
};
let line = record.line();
assert!(line.ends_with('\n'));
assert_eq!(Record::parse(line.trim_end()), Some(record), "{line}");
let stamped = alloc::format!("[ 142.235] {}", line.trim_end());
assert_eq!(Record::parse(&stamped), Some(record));
}
}
assert_eq!(
failed(0xa7a0, Cause::Init(-11)).line(),
"INTEL GUC RECORD failed device=a7a0 cause=init-11 build=test4\n"
);
}
#[test]
fn a_quoted_or_foreign_record_is_passed_over() {
let line = failed(0xa7ab, Cause::Transport).line();
let line = line.trim_end();
// An earlier boot's line repeated in this one.
assert_eq!(
Record::parse(&alloc::format!(
"[ 8.686] PREVIOUS BOOT [ 29.099] {line}"
)),
None
);
// Another build's record.
assert_eq!(Record::parse(&line.replace(BUILD, "dev64-1")), None);
for broken in [
"INTEL GUC RECORD failed device=a7a0 cause=init-11",
"INTEL GUC RECORD failed device=zzzz cause=wedged build=dev64-1",
"INTEL GUC RECORD failed device=a7a0 cause=sleepy build=dev64-1",
"INTEL GUC RECORD maybe device=a7a0 cause=wedged build=dev64-1",
"INTEL GUC RECORD",
] {
assert_eq!(Record::parse(broken), None, "{broken}");
}
}
#[test]
fn the_earlier_boot_is_the_part_after_its_marker() {
let older = failed(0x46a6, Cause::Wedged).line();
let newer = failed(0xa7a0, Cause::Init(-11)).line();
let kept = Record {
device: 0xa7a0,
cause: Cause::Init(-11),
kept: true,
};
let log = alloc::format!(
"=== STELA BOOT 16 === version=0.6.1\n[ 1.0] {older}=== STELA BOOT 17 === \
version=0.6.1\n[ 2.0] GPU x\n[ 142.235] {newer}[ 143.0] {}[ 144.0] STELA STOPPED code=0x11\n",
kept.line()
);
assert_eq!(earlier(log.as_bytes()), Some(kept));
// A boot with no record: the one before it does not count.
let log = alloc::format!("=== STELA BOOT 16 ===\n{older}=== STELA BOOT 17 ===\nnothing\n");
assert_eq!(earlier(log.as_bytes()), None);
// No marker: the bytes are the end of a boot whose marker was written over.
assert_eq!(
earlier(newer.as_bytes()),
Some(failed(0xa7a0, Cause::Init(-11)))
);
assert_eq!(earlier(b""), None);
}
#[test]
fn the_mode_follows_the_setting_then_the_record_of_this_device() {
// Raptor Lake S, whose default stays the GuC in this build.
let s = "ALDERLAKE_S";
let record = Some(failed(0xa780, Cause::Init(-11)));
assert_eq!(Mode::decide(Setting::Auto, None, 0xa780, s), Mode::Guc);
assert_eq!(
Mode::decide(Setting::Auto, record, 0xa780, s),
Mode::Fallback(Cause::Init(-11))
);
// The stick moved to another PC: the GuC is tried there.
assert_eq!(Mode::decide(Setting::Auto, record, 0xa788, s), Mode::Guc);
assert_eq!(Mode::decide(Setting::Off, None, 0xa780, s), Mode::OffByHand);
assert_eq!(
Mode::decide(Setting::Off, record, 0xa780, s),
Mode::OffByHand
);
assert_eq!(Mode::decide(Setting::On, None, 0xa780, s), Mode::Guc);
assert!(
Mode::Guc.guc()
&& !Mode::OffByHand.guc()
&& !Mode::OffByDefault.guc()
&& !Mode::Fallback(Cause::Metal).guc()
);
}
#[test]
fn alder_and_raptor_lake_p_start_with_the_guc_in_test_4_and_fall_back_after_a_failure() {
let p = "ALDERLAKE_P";
assert!(!off_by_default(p) && falls_back(p));
for platform in ["ALDERLAKE_S", "DG1", "TIGERLAKE", "DG2", "METEORLAKE"] {
assert!(!off_by_default(platform), "{platform}");
}
let record = Some(failed(0xa7a0, Cause::Metal));
for device in [0xa7a0, 0xa7ab, 0x46a8] {
assert_eq!(Mode::decide(Setting::Auto, None, device, p), Mode::Guc);
assert_eq!(Mode::decide(Setting::Off, None, device, p), Mode::OffByHand);
assert_eq!(Mode::decide(Setting::On, None, device, p), Mode::Guc);
}
// The boot after this device's GuC failed goes without it, asked or not.
for setting in [Setting::Auto, Setting::On] {
assert_eq!(
Mode::decide(setting, record, 0xa7a0, p),
Mode::Fallback(Cause::Metal)
);
assert_eq!(Mode::decide(setting, record, 0xa7ab, p), Mode::Guc);
}
assert_eq!(
Mode::decide(Setting::Off, record, 0xa7a0, p),
Mode::OffByHand
);
let line = Mode::OffByDefault.line(0xa7a0, None);
assert!(
line.starts_with("INTEL GUC off (test4): ") && line.contains("--i915-guc on"),
"{line}"
);
assert_eq!(line.matches('\n').count(), 1);
}
/// The bytes before boot 23's marker in dev64's log, cut to these lines:
/// boot 22 started the GuC, lost its Metal device and wrote its record at
/// the stop. The reader finds the record in them, as it did in dev64-1;
/// the engine, which runs a copy of the image taken before any static was
/// set, never saw what the loader read, and now takes it from the handoff.
/// This build passes a dev64-1 record over and follows one of its own.
#[test]
fn the_record_dev64s_boot_22_wrote_is_read_from_its_bytes() {
let real = include_bytes!("dev64-boot22-tail.log");
let text = core::str::from_utf8(real).unwrap();
assert!(text.contains("=== STELA BOOT 22 ===") && text.ends_with("power off to continue\n"));
assert!(
text.contains(
"[ 45.409] INTEL GUC RECORD failed device=a7a0 cause=metal build=dev64-1\n"
)
);
// Another build's record: passed over.
assert_eq!(earlier(real), None);
let ours = text.replace("build=dev64-1", &alloc::format!("build={BUILD}"));
let record = earlier(ours.as_bytes());
assert_eq!(record, Some(failed(0xa7a0, Cause::Metal)));
assert_eq!(
Mode::decide(Setting::On, record, 0xa7a0, "ALDERLAKE_P"),
Mode::Fallback(Cause::Metal)
);
// Its mode line is no record.
assert!(
ours.lines()
.filter(|line| line.contains("INTEL GUC on"))
.all(|line| Record::parse(line).is_none())
);
// Once boot 23's marker joins them, boot 22's record is not boot 23's.
let next = alloc::format!("{ours}=== STELA BOOT 23 === version=0.6.1\n");
assert_eq!(earlier(next.as_bytes()), None);
}
#[test]
fn each_mode_says_itself_in_one_line() {
let fallback = Mode::Fallback(Cause::Init(-11)).line(0xa7a0, None);
assert!(
fallback.starts_with(
"INTEL GUC fallback (test4): GuC failed last boot (its start failed (-11)), \
starting i915 on a7a0 without GuC"
),
"{fallback}"
);
assert!(
Mode::OffByHand
.line(0xa7a0, None)
.contains("--i915-guc off")
);
let on = Mode::Guc.line(0xa7ab, Some(failed(0xa7a0, Cause::Wedged)));
assert!(on.starts_with("INTEL GUC on (test4)") && on.contains("another PC's"));
for line in [fallback, on] {
assert_eq!(line.matches('\n').count(), 1);
}
}
#[test]
fn the_failures_dev64_and_a_second_raptor_lake_printed_are_told_apart() {
let lines = [
(
"i915 0000:00:02.0: [drm] *ERROR* GT0: GuC initialization failed -11",
Some(Cause::Init(-11)),
),
(
"i915 0000:00:02.0: [drm] *ERROR* GT0: Failed to initialize GPU, declaring it wedged!",
Some(Cause::Wedged),
),
(
"i915 0000:00:02.0: [drm] *ERROR* GT0: GUC: CT: Unsolicited response message: len 1, \
data 0xe0000101 (fence 105, last 107)",
Some(Cause::Transport),
),
(
"i915 0000:00:02.0: [drm] *ERROR* GT0: GUC: Failed to allocate or map log buffer -12",
Some(Cause::Error),
),
(
"i915 0000:00:02.0: [drm] *ERROR* GT0: Enabling uc failed (-5)",
None,
),
(
"i915 0000:00:02.0: [drm] *ERROR* Device initialization failed (-12)",
None,
),
];
for (line, cause) in lines {
assert_eq!(Cause::of_line(line), cause, "{line}");
}
}
#[test]
fn only_the_platforms_whose_default_is_guc_submission_fall_back() {
for platform in ["ALDERLAKE_P", "ALDERLAKE_S", "DG1"] {
assert!(falls_back(platform), "{platform}");
}
for platform in ["TIGERLAKE", "ROCKETLAKE", "DG2", "METEORLAKE", "SKYLAKE"] {
assert!(!falls_back(platform), "{platform}");
}
}
#[test]
fn the_second_start_names_the_cause() {
let stop = second_start(Cause::Transport);
assert!(stop.starts_with("Intel graphics needs a second start; restart the PC."));
assert!(stop.contains("command transport") && !stop.contains('\n'));
assert_eq!(
Cause::Metal.told().to_string(),
"the Metal device did not open"
);
}
+12 -6
View File
@@ -208,14 +208,16 @@ impl<R: Registers, P: Platform> FirmwareRoutes<R, P> {
// SAFETY: the unit lock held above serializes the withheld table.
unsafe { (*unit.withheld.get())[usize::from(pin)] = withheld };
}
self.check_masked()?;
self.check_masked(false)?;
self.phase.set(FirmwarePhase::Contained);
Ok(())
}
/// Check that every contained pin still reads as the cleared masked
/// entry, every withheld pin stays masked and every SMI pin keeps the
/// firmware's entry.
/// Check that every unclaimed contained pin still reads as the cleared
/// masked entry, every withheld pin stays masked and every SMI pin keeps
/// the firmware's entry. Pins claimed by this controller (such as an
/// active ACPI SCI line under `--acpi-hardware`) are already owned by
/// [`Unit`].
pub fn verify_contained(&self) -> Result<(), IrqError> {
if self.phase.get() != FirmwarePhase::Contained {
return Err(IrqError::Unavailable);
@@ -225,7 +227,7 @@ impl<R: Registers, P: Platform> FirmwareRoutes<R, P> {
unit.domain.check().map_err(IrqError::Delivery)?;
let _guard = unit.lock();
self.phase.set(FirmwarePhase::Uncertain);
self.check_masked()?;
self.check_masked(true)?;
self.phase.set(FirmwarePhase::Contained);
Ok(())
}
@@ -264,9 +266,13 @@ impl<R: Registers, P: Platform> FirmwareRoutes<R, P> {
})
}
fn check_masked(&self) -> Result<(), IrqError> {
fn check_masked(&self, allow_claimed: bool) -> Result<(), IrqError> {
let unit = &self.unit;
for (pin, &(low, _)) in (0..unit.pins as u8).zip(&self.entries) {
// SAFETY: the caller holds the selector and claims lock.
if allow_claimed && unsafe { (*unit.claims.get())[usize::from(pin)] } {
continue;
}
let (now, high) = unit.firmware_entry(pin)?;
let kept = match unit.withheld(pin) {
Some(_) if low & DELIVERY_MODE == SMI => now & CONFIG == low & CONFIG,
@@ -1326,3 +1326,41 @@ fn firmware_containment_leaves_smi_pins_alone_and_clears_every_other_mode() {
assert_eq!(plan.verify_contained(), Err(IrqError::Route));
}
}
/// Claiming a pin through `Unit` (such as ACPI SCI on GSI 9 under
/// `--acpi-hardware`) must not cause `verify_contained` to fail or poison
/// subsequent PCI containment checks, while unclaimed pins remain verified.
#[test]
fn verify_contained_allows_claimed_lines_and_catches_unclaimed_changes() {
let (board, unit, registry, line) = fixture();
// SAFETY: sole controller, CPU and original firmware route model.
let plan = unsafe { unit.firmware_routes() }.unwrap();
// SAFETY: the fixture retains the exact original controller.
unsafe { plan.contain() }.unwrap();
plan.verify_contained().unwrap();
// Claim and arm GSI 9 just as ACPI SCI does before PCI device bring-up.
// SAFETY: the fixture owns GSI 9 and its sole contributor.
let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap();
let registration = registry
.request(stela_drivers::bus::irq::Request {
source: Box::new(pin),
handler: Arc::new(Member(board.clone(), 1, true)),
routing: stela_drivers::bus::irq::RouteRequest::Line(line),
})
.unwrap();
// Claimed pin is owned by Unit; every other pin is still masked.
plan.verify_contained().unwrap();
// A second claim on GSI 9 must still be refused.
assert_eq!(plan.verify_line(line.gsi), Err(IrqError::Route));
// Unclaimed pins still verify cleanly.
plan.verify_line(1).unwrap();
// Tampering with an unclaimed pin must still be caught.
board.hw.lock().unwrap().regs[0x10 + 3 * 2] = 0x35;
assert_eq!(plan.verify_contained(), Err(IrqError::Route));
// Once containment fails, subsequent checks stay Unavailable.
assert_eq!(plan.verify_contained(), Err(IrqError::Unavailable));
drop(registration);
}
+296
View File
@@ -0,0 +1,296 @@
//! Whether the PC is a laptop, and the laptop features a boot then takes
//! without being asked (`--laptop auto`, the default).
//!
//! Setup writes none of the laptop options and the startup menu offers
//! none, so each was a line to find and hand-write. The boot reads facts it
//! reads anyway instead: the FADT's Preferred_PM_Profile, the ACPI batteries
//! (PNP0C0A, present by `_STA`) and the lid (PNP0C0D) the power probe
//! attached, and the precision touchpads among the host's inputs. A laptop
//! is a mobile-class profile ([`mobile_class`]), or a battery and a lid
//! together, which a laptop whose firmware leaves the profile unspecified
//! or says desktop still has. On a laptop the boot behaves as if
//! `--trackpad mt2` were given where a precision touchpad and `--input` are
//! there, and, only with `--acpi-hardware`, `--battery`, `--lid method` and
//! `--brightness-keys` too ([`plan`]): without hardware mode the battery
//! would freeze at its first reading and the lid and keys would do nothing.
//!
//! What the line gives wins: a `--test-battery`, `--lid ignore`,
//! `--trackpad builtin`. `--laptop off` takes nothing, so each feature stays
//! the opt-in it was ([`crate::options::Laptop`]). `--lid-sleep` is never
//! taken: it puts macOS to sleep each time the lid darkens the panel, which
//! is the user's to ask for. Nor is `--acpi-hardware`
//! ([`crate::acpi_hardware`]) until a laptop has proven it; it starts before
//! the power probe this decision reads, so a laptop could take it only from
//! the FADT's profile. The guards of each option hold as they did: the battery is not
//! taken for a boot that withholds it ([`System::battery_withheld`]), and
//! the battery's own refusal of an empty reading is the engine's, after
//! this. None of this is in the option line, whose meaning setup and
//! `stela.efi` share (`stela_loader::mount_interface::OPTIONS_REVISION`): a
//! line means what it meant, and only a boot's reading of its PC adds to it.
use crate::options::{Battery, GuestTrackpad, Laptop, Lid, System};
use alloc::{format, string::String, vec::Vec};
/// Byte offset of the FADT's Preferred_PM_Profile (ACPI 6.5, 5.2.9).
pub const FADT_PM_PROFILE: usize = 45;
/// The FADT's Preferred_PM_Profile; `None` without one, or before revision
/// 2, where ACPI 1.0 kept that byte reserved.
pub fn pm_profile(fadt: &[u8]) -> Option<u8> {
match fadt.get(8) {
Some(&revision) if revision >= 2 => fadt.get(FADT_PM_PROFILE).copied(),
_ => None,
}
}
/// A Preferred_PM_Profile's name (ACPI 6.5, table 5.9).
pub fn profile_name(profile: u8) -> &'static str {
match profile {
0 => "unspecified",
1 => "desktop",
2 => "mobile",
3 => "workstation",
4 => "enterprise server",
5 => "SOHO server",
6 => "appliance PC",
7 => "performance server",
8 => "tablet",
_ => "reserved",
}
}
/// Whether a profile names a laptop-class machine: Mobile, Tablet or
/// Appliance PC. Each laptop feature also needs its own device, so a
/// machine that only claims the class gains nothing it lacks.
pub fn mobile_class(profile: u8) -> bool {
matches!(profile, 2 | 6 | 8)
}
/// What the boot read of the PC.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Facts {
/// The FADT's Preferred_PM_Profile ([`pm_profile`]).
pub pm_profile: Option<u8>,
/// An ACPI battery (PNP0C0A) present by `_STA` attached.
pub battery: bool,
/// An ACPI lid (PNP0C0D) attached.
pub lid: bool,
/// A host input is a precision touchpad.
pub precision_touchpad: bool,
/// The guest's USB hub keeps a port for a trackpad beside the disks
/// it took.
pub trackpad_port: bool,
}
impl Facts {
/// A mobile-class profile, or a battery and a lid.
pub fn laptop(&self) -> bool {
self.pm_profile.is_some_and(mobile_class) || (self.battery && self.lid)
}
/// `FADT mobile, battery, lid`: what the decision read.
fn describe(&self) -> String {
let profile = match self.pm_profile {
Some(profile) => format!("FADT {}", profile_name(profile)),
None => String::from("no FADT profile"),
};
let have = |present: bool, name: &str| match present {
true => String::from(name),
false => format!("no {name}"),
};
format!(
"{profile}, {}, {}",
have(self.battery, "battery"),
have(self.lid, "lid")
)
}
}
/// What a boot does with one laptop feature.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Choice {
/// Taken as if its option were given.
Taken,
/// Its option, as the line gives it, stands.
Given(&'static str),
/// Not taken, for this reason.
Skipped(&'static str),
/// Not taken: the boot this names withholds it.
Withheld(&'static str),
}
/// The laptop features one boot takes ([`plan`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Plan {
pub facts: Facts,
/// `--laptop`'s value.
pub mode: Laptop,
pub battery: Choice,
pub lid: Choice,
pub brightness_keys: Choice,
pub trackpad: Choice,
}
/// Why a laptop's battery, lid and brightness keys are skipped on a boot
/// without `--acpi-hardware`.
pub const NEEDS_HARDWARE: &str = "needs --acpi-hardware";
/// The laptop features `options` and `facts` give this boot. Off a laptop,
/// or with `--laptop off`, each is what the line gives or skipped.
pub fn plan(options: &System, facts: Facts) -> Plan {
let auto = facts.laptop() && options.laptop() == Laptop::Auto;
let not_laptop = match options.laptop() {
Laptop::Off => "--laptop off",
Laptop::Auto => "not a laptop",
};
let choose = |given: Option<&'static str>, skip: Option<Choice>| match given {
Some(spelling) => Choice::Given(spelling),
None if !auto => Choice::Skipped(not_laptop),
None => skip.unwrap_or(Choice::Taken),
};
// The battery, the lid and the brightness keys follow the host only
// through ACPI hardware mode's events and polls: without it the battery
// would show its first reading for the whole boot, and the lid and the
// keys would do nothing. So a boot without `--acpi-hardware` takes none
// of them unasked; the options given still stand.
let without_hardware = (!options.acpi_hardware).then_some(Choice::Skipped(NEEDS_HARDWARE));
let battery = choose(
options.battery.map(|battery| match battery {
Battery::Host => "--battery",
Battery::Test { .. } => "--test-battery",
}),
// A boot that withholds the battery says so first: an install's.
match options.battery_withheld(false) {
Some(boot) => Some(Choice::Withheld(boot)),
None => (!facts.battery)
.then_some(Choice::Skipped("no ACPI battery"))
.or(without_hardware),
},
);
let lid = choose(
options.lid.map(|lid| match lid {
Lid::Ignore => "--lid ignore",
Lid::Method => "--lid method",
}),
(!facts.lid)
.then_some(Choice::Skipped("no ACPI lid"))
.or(without_hardware),
);
let brightness_keys = choose(
options.brightness_keys.then_some("--brightness-keys"),
without_hardware,
);
let trackpad = choose(
options.trackpad.map(|kind| match kind {
GuestTrackpad::Mt2 => "--trackpad mt2",
GuestTrackpad::Builtin => "--trackpad builtin",
}),
if !options.input {
Some(Choice::Skipped("no --input"))
} else if !facts.precision_touchpad {
Some(Choice::Skipped("no precision touchpad"))
} else if !facts.trackpad_port {
Some(Choice::Skipped("no free port on the guest's USB hub"))
} else {
None
},
);
Plan {
facts,
mode: options.laptop(),
battery,
lid,
brightness_keys,
trackpad,
}
}
impl Plan {
/// Whether the boot takes `--brightness-keys` itself, after the ACPI
/// hardware mode that attaches them with the option has started.
pub fn takes_brightness_keys(&self) -> bool {
self.brightness_keys == Choice::Taken
}
/// Set the features taken in `options`, as their options would.
pub fn apply(&self, options: &mut System) {
if self.battery == Choice::Taken {
options.battery = Some(Battery::Host);
}
if self.lid == Choice::Taken {
options.lid = Some(Lid::Method);
}
if self.brightness_keys == Choice::Taken {
options.brightness_keys = true;
}
if self.trackpad == Choice::Taken {
options.trackpad = Some(GuestTrackpad::Mt2);
}
}
/// The boot's one line: `LAPTOP detected (FADT mobile, battery, lid):
/// battery on, lid method, brightness keys, trackpad mt2`, each skipped
/// feature after with its reason, or `DESKTOP (...): no laptop
/// features`. Off a laptop a feature the line gives is still named.
pub fn line(&self) -> String {
let facts = self.facts.describe();
let features = [
("battery", "battery on", self.battery),
("lid", "lid method", self.lid),
("brightness keys", "brightness keys", self.brightness_keys),
("trackpad", "trackpad mt2", self.trackpad),
];
let given: Vec<String> = features
.iter()
.filter_map(|&(_, _, choice)| match choice {
Choice::Given(spelling) => Some(format!("{spelling} as given")),
_ => None,
})
.collect();
if !self.facts.laptop() {
return match given.is_empty() {
true => format!("DESKTOP ({facts}): no laptop features\n"),
false => format!(
"DESKTOP ({facts}): no laptop features but those given: {}\n",
given.join(", ")
),
};
}
if self.mode == Laptop::Off {
return match given.is_empty() {
true => format!("LAPTOP detected ({facts}), --laptop off: no laptop features\n"),
false => format!(
"LAPTOP detected ({facts}), --laptop off: only those given: {}\n",
given.join(", ")
),
};
}
let mut on = Vec::new();
let mut skipped = Vec::new();
for (name, taken, choice) in features {
match choice {
Choice::Taken => on.push(String::from(taken)),
Choice::Given(spelling) => on.push(format!("{spelling} as given")),
Choice::Skipped(reason) => skipped.push(format!("{name} ({reason})")),
Choice::Withheld(boot) => skipped.push(format!("{name} (not given to {boot})")),
}
}
let mut line = format!("LAPTOP detected ({facts}): ");
line.push_str(&match on.is_empty() {
true => String::from("no laptop features"),
false => on.join(", "),
});
if !skipped.is_empty() {
line.push_str("; skipped: ");
line.push_str(&skipped.join(", "));
}
line.push('\n');
line
}
}
/// The line of a boot that opens no host devices, and so reads no battery,
/// lid or touchpad.
pub const UNREAD: &str = "LAPTOP detection skipped: this boot opens no host devices; only the laptop options given apply\n";
#[cfg(test)]
mod tests;
+473
View File
@@ -0,0 +1,473 @@
use super::*;
use alloc::string::ToString;
/// A FADT of `revision` whose Preferred_PM_Profile is `profile`.
fn fadt(revision: u8, profile: u8) -> Vec<u8> {
let mut table = alloc::vec![0; 276];
table[..4].copy_from_slice(b"FACP");
table[8] = revision;
table[FADT_PM_PROFILE] = profile;
table
}
/// Garvit's ASUS TUF A16 (FA608PP): its FADT's first 48 bytes as dumped,
/// revision 6 and profile 2 at byte 45, and a battery, a lid and an ELAN
/// precision touchpad.
const TUF_A16_FADT: [u8; 48] = [
0x46, 0x41, 0x43, 0x50, 0x14, 0x01, 0x00, 0x00, 0x06, 0x5d, 0x5f, 0x41, 0x53, 0x55, 0x53, 0x5f,
0x4e, 0x6f, 0x74, 0x65, 0x62, 0x6f, 0x6f, 0x6b, 0x09, 0x20, 0x07, 0x01, 0x41, 0x4d, 0x49, 0x20,
0x13, 0x00, 0x01, 0x00, 0x00, 0x40, 0xb2, 0xb6, 0x00, 0x00, 0xb2, 0xb4, 0x00, 0x02, 0x09, 0x00,
];
fn laptop() -> Facts {
Facts {
pm_profile: Some(2),
battery: true,
lid: true,
precision_touchpad: true,
trackpad_port: true,
}
}
fn desktop() -> Facts {
Facts {
pm_profile: Some(1),
..Facts::default()
}
}
/// The installed macOS's line, as setup writes it: with `--input`.
fn installed(extra: &str) -> System {
System::parse(&alloc::format!("--system --input{extra}")).unwrap()
}
#[test]
fn the_profile_is_read_from_revision_2_on() {
assert_eq!(pm_profile(&fadt(6, 2)), Some(2));
assert_eq!(pm_profile(&fadt(2, 8)), Some(8));
// ACPI 1.0's byte 45 is reserved.
assert_eq!(pm_profile(&fadt(1, 2)), None);
assert_eq!(pm_profile(&fadt(6, 2)[..45]), None);
assert_eq!(pm_profile(&[]), None);
assert_eq!(pm_profile(&TUF_A16_FADT), Some(2));
}
#[test]
fn a_laptop_is_a_mobile_class_profile_or_a_battery_and_a_lid() {
for profile in [2, 6, 8] {
let facts = Facts {
pm_profile: Some(profile),
..Facts::default()
};
assert!(facts.laptop(), "{}", profile_name(profile));
}
for profile in [0, 1, 3, 4, 5, 7, 9, 0xff] {
let facts = Facts {
pm_profile: Some(profile),
..Facts::default()
};
assert!(!facts.laptop(), "{}", profile_name(profile));
// A battery and a lid make one whatever the profile says.
assert!(
Facts {
battery: true,
lid: true,
..facts
}
.laptop()
);
// One of them alone does not: a UPS battery, a desktop's lid switch.
assert!(
!Facts {
battery: true,
..facts
}
.laptop()
);
assert!(!Facts { lid: true, ..facts }.laptop());
}
assert!(!Facts::default().laptop());
assert!(
Facts {
battery: true,
lid: true,
..Facts::default()
}
.laptop()
);
// A touchpad alone is no laptop: USB touchpads plug into desktops.
assert!(
!Facts {
precision_touchpad: true,
trackpad_port: true,
..desktop()
}
.laptop()
);
}
#[test]
fn a_laptop_takes_every_feature_but_lid_sleep() {
let mut options = installed(" --acpi-hardware");
let plan = plan(&options, laptop());
assert_eq!(
[plan.battery, plan.lid, plan.brightness_keys, plan.trackpad],
[Choice::Taken; 4]
);
assert!(plan.takes_brightness_keys());
plan.apply(&mut options);
assert_eq!(options.battery, Some(Battery::Host));
assert_eq!(options.lid(), Lid::Method);
assert!(options.brightness_keys);
assert_eq!(options.guest_trackpad(), Some(GuestTrackpad::Mt2));
assert!(!options.lid_sleep);
// The record stays one the parser accepts.
assert_eq!(options.check(), Ok(()));
assert_eq!(
plan.line(),
"LAPTOP detected (FADT mobile, battery, lid): battery on, lid method, brightness keys, \
trackpad mt2\n"
);
}
#[test]
fn without_acpi_hardware_a_laptop_takes_only_the_trackpad() {
// The battery would freeze at its first reading, and the lid and the
// brightness keys would do nothing, without hardware mode's events.
let mut options = installed("");
let plan = plan(&options, laptop());
assert_eq!(
[plan.battery, plan.lid, plan.brightness_keys],
[Choice::Skipped(NEEDS_HARDWARE); 3]
);
assert_eq!(plan.trackpad, Choice::Taken);
assert!(!plan.takes_brightness_keys());
plan.apply(&mut options);
assert_eq!(options.battery, None);
assert_eq!(options.lid, None);
assert!(!options.brightness_keys);
assert_eq!(options.guest_trackpad(), Some(GuestTrackpad::Mt2));
assert!(
!options.acpi_hardware,
"ACPI hardware mode stays the line's to ask for"
);
assert_eq!(options.check(), Ok(()));
assert_eq!(plan.line(), TESTER_LINE);
// The options given still stand.
let given = installed(" --battery --lid method --brightness-keys");
let plan = super::plan(&given, laptop());
assert_eq!(plan.battery, Choice::Given("--battery"));
assert_eq!(plan.lid, Choice::Given("--lid method"));
assert_eq!(plan.brightness_keys, Choice::Given("--brightness-keys"));
}
/// A laptop's line without `--acpi-hardware`: the touchpad alone.
const TESTER_LINE: &str = "LAPTOP detected (FADT mobile, battery, lid): trackpad mt2; skipped: \
battery (needs --acpi-hardware), lid (needs --acpi-hardware), brightness keys (needs \
--acpi-hardware)\n";
#[test]
fn a_desktop_takes_nothing_and_keeps_what_is_given() {
let mut options = installed("");
let before = options.clone();
let plan = plan(&options, desktop());
plan.apply(&mut options);
assert_eq!(options, before);
assert!(!plan.takes_brightness_keys());
assert_eq!(
plan.line(),
"DESKTOP (FADT desktop, no battery, no lid): no laptop features\n"
);
let given = installed(" --battery --brightness-keys");
assert_eq!(
super::plan(&given, desktop()).line(),
"DESKTOP (FADT desktop, no battery, no lid): no laptop features but those given: \
--battery as given, --brightness-keys as given\n"
);
let unread = Facts::default();
assert_eq!(
super::plan(&installed(""), unread).line(),
"DESKTOP (no FADT profile, no battery, no lid): no laptop features\n"
);
}
#[test]
fn laptop_off_takes_nothing_but_the_options_given() {
let mut options = installed(" --laptop off");
let before = options.clone();
let plan = plan(&options, laptop());
plan.apply(&mut options);
assert_eq!(options, before);
assert_eq!(plan.battery, Choice::Skipped("--laptop off"));
assert_eq!(
plan.line(),
"LAPTOP detected (FADT mobile, battery, lid), --laptop off: no laptop features\n"
);
let given = installed(" --laptop off --lid method");
let plan = super::plan(&given, laptop());
assert_eq!(plan.lid, Choice::Given("--lid method"));
assert_eq!(
plan.line(),
"LAPTOP detected (FADT mobile, battery, lid), --laptop off: only those given: \
--lid method as given\n"
);
}
#[test]
fn explicit_options_win() {
// `--lid ignore` keeps the lid ignored, a test battery and the
// built-in trackpad ID stand, and `--lid-sleep` with its method too.
for (extra, check) in [
(
" --lid ignore",
(|options: &System| options.lid() == Lid::Ignore) as fn(&System) -> bool,
),
(" --test-battery 50,charging", |options| {
options.battery
== Some(Battery::Test {
percent: 50,
state: crate::options::TestState::Charging,
})
}),
(" --trackpad builtin", |options| {
options.trackpad == Some(GuestTrackpad::Builtin)
}),
(" --lid method --lid-sleep", |options| {
options.lid() == Lid::Method && options.lid_sleep
}),
] {
let mut options = installed(extra);
let plan = plan(&options, laptop());
plan.apply(&mut options);
assert!(check(&options), "{extra}");
assert_eq!(options.check(), Ok(()), "{extra}");
}
let options =
installed(" --acpi-hardware --lid ignore --test-battery 50,charging --trackpad builtin");
assert_eq!(
plan(&options, laptop()).line(),
"LAPTOP detected (FADT mobile, battery, lid): --test-battery as given, --lid ignore as \
given, brightness keys, --trackpad builtin as given\n"
);
}
#[test]
fn each_feature_without_its_device_is_skipped_with_its_reason() {
// A mobile profile alone, with no battery, lid or touchpad.
let bare = Facts {
pm_profile: Some(2),
..Facts::default()
};
let mut options = installed(" --acpi-hardware");
let plan = plan(&options, bare);
assert_eq!(plan.battery, Choice::Skipped("no ACPI battery"));
assert_eq!(plan.lid, Choice::Skipped("no ACPI lid"));
assert_eq!(plan.brightness_keys, Choice::Taken);
assert_eq!(plan.trackpad, Choice::Skipped("no precision touchpad"));
plan.apply(&mut options);
assert_eq!(options.battery, None);
assert_eq!(options.lid, None);
assert_eq!(options.trackpad, None);
assert_eq!(
plan.line(),
"LAPTOP detected (FADT mobile, no battery, no lid): brightness keys; skipped: battery \
(no ACPI battery), lid (no ACPI lid), trackpad (no precision touchpad)\n"
);
// The trackpad needs host input, then a free hub port.
let no_input = System::parse("--system").unwrap();
assert_eq!(
super::plan(&no_input, laptop()).trackpad,
Choice::Skipped("no --input")
);
let full_hub = Facts {
trackpad_port: false,
..laptop()
};
let plan = super::plan(&installed(""), full_hub);
assert_eq!(
plan.trackpad,
Choice::Skipped("no free port on the guest's USB hub")
);
let mut options = installed("");
plan.apply(&mut options);
assert_eq!(options.trackpad, None);
}
#[test]
fn a_boot_that_withholds_the_battery_does_not_take_it() {
const DISK: &str = "74EXN0LI:11111111-2222-3333-4444-555555555555";
for (line, boot) in [
(
alloc::format!(
"--system --input --acpi-hardware --storage {DISK} --nor {DISK} --bundle b \
--install p.json"
),
"the macOS installer",
),
(
alloc::format!("--system --input --acpi-hardware --preboot {DISK} --upgrade"),
"a staged macOS update",
),
(
alloc::format!("--system --input --acpi-hardware --preboot {DISK} --paired-recovery"),
"recoveryOS",
),
(
alloc::format!("--system --input --acpi-hardware --preboot {DISK} --bundle-repair"),
"the Metal plugin repair",
),
] {
let mut options = System::parse(&line).unwrap();
let plan = plan(&options, laptop());
assert_eq!(plan.battery, Choice::Withheld(boot), "{line}");
plan.apply(&mut options);
assert_eq!(options.battery, None, "{line}");
assert!(
plan.line()
.contains(&alloc::format!("skipped: battery (not given to {boot})")),
"{}",
plan.line()
);
// The other features stay.
assert_eq!(options.lid(), Lid::Method, "{line}");
}
// The installed macOS takes it, in single-user and safe mode too.
for flag in ["", " --single-user", " --safe-boot"] {
let options = System::parse(&alloc::format!(
"--system --input --acpi-hardware --preboot {DISK}{flag}"
))
.unwrap();
assert_eq!(plan(&options, laptop()).battery, Choice::Taken, "{flag}");
}
}
#[test]
fn the_tuf_a16_is_a_laptop_with_every_feature() {
let facts = Facts {
pm_profile: pm_profile(&TUF_A16_FADT),
..laptop()
};
assert_eq!(
plan(&installed(" --acpi-hardware"), facts)
.line()
.to_string(),
"LAPTOP detected (FADT mobile, battery, lid): battery on, lid method, brightness keys, \
trackpad mt2\n"
);
// A tester's boot, without hardware mode: the touchpad alone.
assert_eq!(plan(&installed(""), facts).line(), TESTER_LINE);
}
/// The engine's AML host and boot, whose laptop path these tests follow
/// into the firmware calls.
static AML: &str = include_str!("../../../stela-boot/src/engine/aml.rs");
static START: &str = include_str!("../../../stela-boot/src/engine/start.rs");
/// The body of `fn name` in `source`, braces included.
fn body<'a>(source: &'a str, name: &str) -> &'a str {
let at = source
.find(&alloc::format!("fn {name}("))
.unwrap_or_else(|| panic!("no fn {name}"));
let open = at + source[at..].find('{').unwrap();
let mut depth = 0;
for (offset, character) in source[open..].char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return &source[open..=open + offset];
}
}
_ => {}
}
}
panic!("fn {name} does not end")
}
/// `code` without its `firmware(...)` calls, which run their closure in
/// the work owner's continuation (`HostAcpi::firmware`).
fn outside_firmware(code: &str) -> alloc::string::String {
let mut kept = alloc::string::String::new();
let mut rest = code;
while let Some(at) = rest.find(".firmware(") {
kept.push_str(&rest[..at]);
let mut depth = 0;
let mut end = rest.len();
for (offset, character) in rest[at..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = at + offset + 1;
break;
}
}
_ => {}
}
}
rest = &rest[end..];
}
kept.push_str(rest);
kept
}
/// What reaches ACPICA, whose namespace guard and mutexes take the
/// continuation's identity and stop the boot outside it.
const ACPICA: [&str; 9] = [
".path(",
".notify(",
".notify_all(",
".evaluate(",
".refresh(",
".devices(",
".child(",
"session.",
".initialize_all(",
];
fn assert_no_acpica(what: &str, code: &str) {
let outside = outside_firmware(code);
for call in ACPICA {
assert!(
!outside.contains(call),
"{what} calls ACPICA ({call}) outside its owned native continuation:\n{outside}"
);
}
}
/// The FA608PP stopped with "ACPICA called outside its owned native
/// continuation" right after the laptop line, `--laptop off` too: the
/// devices' start returns to the dispatcher's stack, where the lid's path
/// and notify handler were installed directly. Everything the boot does
/// with the laptop's ACPI devices once that start has returned (the
/// decision, the brightness keys it takes and the batteries and lid it
/// keeps) reads the probe's readings or runs in a firmware call.
#[test]
fn the_laptop_path_calls_acpica_only_in_its_continuation() {
let decision = body(START, "take_laptop_features");
assert_no_acpica("take_laptop_features", decision);
// The decision's ACPI reaches the engine only through these.
for call in decision
.match_indices("acpi.")
.map(|(at, _)| &decision[at..])
{
assert!(
call.starts_with("acpi.attach_brightness_keys()"),
"take_laptop_features reaches the AML host unchecked: {}",
&call[..call.find('\n').unwrap_or(call.len())]
);
}
// What start_devices calls on the AML host after the devices' owned start.
let devices = body(START, "start_devices");
let after = &devices[devices.find(".call_owned(DEVICES_START_US").unwrap()..];
assert!(after.contains("acpi.retain_power(power)"));
for method in ["retain_power", "attach_brightness_keys"] {
assert_no_acpica(method, body(AML, method));
}
// The lid's handler is installed in the firmware call retain_power makes.
let kept = body(AML, "retain_power");
assert!(kept.contains(".firmware(") && kept.contains("self.follow_lid(lid)"));
assert!(body(AML, "follow_lid").contains(".notify("));
}
+29
View File
@@ -10,13 +10,18 @@ pub use stela_contracts::Refusal;
/// A refused request names the values that decided it.
pub type Result<T, E = Refusal> = core::result::Result<T, E>;
pub mod acpi_hardware;
pub mod amd_discovery;
pub mod aperture;
#[cfg(target_arch = "x86_64")]
pub mod apic;
pub mod assigned_topology;
pub mod audio_check_samples;
pub mod beat_pace;
pub mod block_samples;
pub mod bluetooth_check;
pub mod bluetooth_dsbr;
pub mod bluetooth_target;
pub mod boot_exit;
pub mod boot_ident;
pub mod boot_progress;
@@ -33,6 +38,7 @@ pub mod disk_speed;
pub mod dmar;
pub mod doorbell;
pub mod drivers_turn;
pub mod drm_calls;
pub mod early_fault;
pub mod entropy;
pub mod exit_port;
@@ -42,23 +48,29 @@ pub mod fiber;
pub mod file_kind;
pub mod firmware_connect;
pub mod firmware_pages;
pub mod firmware_picture;
pub mod firmware_runtime;
pub mod firmware_screen;
pub mod firmware_state;
pub mod firmware_time;
pub mod first_stop;
pub mod gpu_fault;
pub mod gpu_loss;
pub mod gpu_requests;
pub mod gpu_status;
pub mod gpu_step;
pub mod gpu_triage;
pub mod guarded_stacks;
pub mod guest_bluetooth;
pub mod guest_screen;
pub mod guest_session;
pub mod guest_timeouts;
pub mod guest_watch;
pub mod handoff_records;
pub mod heap;
#[cfg(target_arch = "x86_64")]
pub mod host_clock;
pub mod host_core;
pub mod host_identity;
pub mod host_memory;
#[cfg(target_arch = "x86_64")]
@@ -68,10 +80,16 @@ pub mod host_resources;
pub mod host_samples;
pub mod host_speed;
pub mod hpet;
pub mod input_pace;
pub mod install_caution;
pub mod install_mode;
pub mod install_progress;
pub mod intel_guc;
pub mod interrupt_image;
pub mod ioapic;
pub mod irq_context;
pub mod laptop;
pub mod lid_panel;
pub mod linux_pump;
pub mod load_lines;
pub mod loader_lines;
@@ -93,19 +111,24 @@ pub mod opregion;
pub mod options;
pub mod page_window;
pub mod paging_controls;
pub mod panel_backlight;
pub mod panic_region;
pub mod parking;
pub mod passthrough;
pub mod pci_map;
pub mod pe;
pub mod pm_timer;
pub mod poll_timer;
pub mod posted_call;
pub mod power_button;
pub mod prediction_lines;
pub mod process_fault;
pub mod psf;
pub mod ram;
pub mod random;
pub mod record;
pub mod remapping;
pub mod repeated_lines;
#[cfg(target_arch = "x86_64")]
pub mod requester;
pub mod reset_reason;
@@ -115,6 +138,7 @@ pub mod running_record;
pub mod screen;
pub mod service_watch;
pub mod shadow_fills;
pub mod shadow_leaf;
pub mod shutdown;
pub mod smi;
pub mod source_health;
@@ -133,8 +157,13 @@ pub mod tsc;
pub mod uart;
pub mod usb_legacy;
pub mod vfct;
pub mod video_bios;
#[cfg(target_arch = "x86_64")]
pub mod vtd;
pub mod wifi_hardware;
pub mod wifi_page;
pub mod wifi_prompt;
pub mod wifi_saved;
pub mod work_status;
pub mod worker_bindings;
pub mod writeback_placement;
+255
View File
@@ -0,0 +1,255 @@
//! A laptop's lid and its built-in panel, with `--lid method`.
//!
//! Linux's ACPI button driver only reports the lid; what follows is its
//! userspace's (logind waits after a boot and ignores a closed lid while
//! an external display is connected), and a wrong `_LID` is common enough
//! that Linux keeps DMI quirks for it (`button.c`'s lid quirks: machines
//! that read closed at boot, or always). So the reading a boot starts with
//! counts for nothing here ([`LidRequest`]): only a lid notification after
//! which `_LID` reads closed darkens the panel, and the next lid
//! notification, whatever `_LID` then reads, or any input of the built-in
//! keyboard or touchpad lights it again, so a wrong reading never leaves
//! the screen dark. A display that an external monitor shows as well stays
//! lit ([`PanelPower`]): its outputs go dark together.
/// The lid's request of a built-in panel: dark or not.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LidRequest {
dark: bool,
}
impl LidRequest {
/// The request `dark` already is.
pub const fn with(dark: bool) -> Self {
Self { dark }
}
pub fn dark(self) -> bool {
self.dark
}
/// A lid notification, after which `_LID` read `open`: the request it
/// changed to, where it changed. A dark panel lights at any.
pub fn notified(&mut self, open: bool) -> Option<bool> {
let dark = !self.dark && !open;
self.change(dark)
}
/// Input of the built-in keyboard or touchpad: a dark panel lights.
pub fn input(&mut self) -> Option<bool> {
self.change(false)
}
fn change(&mut self, dark: bool) -> Option<bool> {
(dark != self.dark).then(|| {
self.dark = dark;
dark
})
}
}
/// What a move of the lid's request asks of the guest (`--lid-sleep`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GuestRequest {
/// A HID System Sleep.
Sleep,
/// The power button's wake, where the guest sleeps.
Wake,
}
/// What the lid's request moving to `dark` asks of the guest, an external
/// monitor showing its display where `external`: to sleep when the panel
/// goes dark, unless an external monitor shows the guest, as a Mac closed
/// on an external display keeps running (clamshell mode); to wake when the
/// panel lights again.
pub fn guest_request(dark: bool, external: bool) -> Option<GuestRequest> {
match (dark, external) {
(true, true) => None,
(true, false) => Some(GuestRequest::Sleep),
(false, _) => Some(GuestRequest::Wake),
}
}
/// What a lid request does to the guest's display.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LidPower {
/// Its outputs go dark.
Off,
/// Its outputs light again.
On,
/// The lid no longer asks it dark, but the guest's display sleeps.
StaysOff,
/// An external monitor shows it too: it stays as the guest has it.
KeptLit,
}
/// A guest display's power as its display sleep and the lid ask.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PanelPower {
/// The guest's display is on.
guest_on: bool,
/// The lid's request last followed.
request: bool,
/// The display is dark for the lid.
lid_dark: bool,
}
impl Default for PanelPower {
fn default() -> Self {
Self::new()
}
}
impl PanelPower {
pub const fn new() -> Self {
Self {
guest_on: true,
request: false,
lid_dark: false,
}
}
/// The lid's request last followed.
pub fn request(&self) -> bool {
self.request
}
/// Whether the outputs are lit.
pub fn lit(&self) -> bool {
self.guest_on && !self.lid_dark
}
/// Whether the display is dark for the lid alone, where a monitor
/// connected now would not be shown ([`Self::external`]).
pub fn lid_dark(&self) -> bool {
self.lid_dark
}
/// An external monitor connected while the display is dark for the
/// lid, as a laptop closed on a dock's: the lid no longer keeps the
/// display dark, so it lights to show there (or at the guest's wake),
/// as macOS shows a closed laptop's picture on an external display.
/// `None` where the lid keeps nothing dark.
pub fn external(&mut self) -> Option<LidPower> {
if !self.lid_dark {
return None;
}
self.lid_dark = false;
Some(if self.guest_on {
LidPower::On
} else {
LidPower::StaysOff
})
}
/// The guest's display power `on`: whether the outputs are lit now.
pub fn guest(&mut self, on: bool) -> bool {
self.guest_on = on;
self.lit()
}
/// The lid's request `dark` ([`LidRequest`]), for a display shown on
/// built-in panels alone where `panels_only`: what it does, `None` for
/// a request already followed, or one to light a display the lid never
/// darkened.
pub fn lid(&mut self, dark: bool, panels_only: bool) -> Option<LidPower> {
if dark == self.request {
return None;
}
self.request = dark;
if dark {
if !panels_only {
return Some(LidPower::KeptLit);
}
self.lid_dark = true;
return Some(LidPower::Off);
}
if !self.lid_dark {
return None;
}
self.lid_dark = false;
Some(if self.guest_on {
LidPower::On
} else {
LidPower::StaysOff
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_notified_close_darkens_and_any_notification_or_input_lights() {
let mut request = LidRequest::default();
// An open reading asks nothing; a closed one after a notification
// darkens.
assert_eq!(request.notified(true), None);
assert_eq!(request.notified(false), Some(true));
// The next notification lights, whatever _LID reads: a lid that
// reads closed for good does not keep the screen dark.
assert_eq!(request.notified(false), Some(false));
assert_eq!(request.notified(false), Some(true));
assert_eq!(request.notified(true), Some(false));
// Built-in input lights a dark panel, and leaves a lit one.
assert_eq!(request.input(), None);
assert_eq!(request.notified(false), Some(true));
assert_eq!(request.input(), Some(false));
assert!(!request.dark());
assert!(LidRequest::with(true).dark());
}
#[test]
fn a_closed_lid_darkens_only_a_display_on_built_in_panels_alone() {
let mut panel = PanelPower::new();
assert!(panel.lit());
assert_eq!(panel.lid(true, true), Some(LidPower::Off));
assert!(!panel.lit());
// A wake of the guest's display stays dark under the lid.
assert!(!panel.guest(true));
assert_eq!(panel.lid(true, true), None);
assert_eq!(panel.lid(false, true), Some(LidPower::On));
assert!(panel.lit());
// Lit again while the guest's display sleeps: it stays off.
assert_eq!(panel.lid(true, true), Some(LidPower::Off));
assert!(!panel.guest(false));
assert_eq!(panel.lid(false, true), Some(LidPower::StaysOff));
assert!(panel.guest(true));
// An external monitor showing it too keeps it as the guest has it.
assert_eq!(panel.lid(true, false), Some(LidPower::KeptLit));
assert!(panel.lit());
assert_eq!(panel.lid(false, false), None);
assert!(panel.lit());
}
#[test]
fn a_dark_panel_asks_the_guest_to_sleep_unless_an_external_monitor_shows_it() {
assert_eq!(guest_request(true, false), Some(GuestRequest::Sleep));
// Clamshell: a Mac closed on an external display keeps running.
assert_eq!(guest_request(true, true), None);
for external in [false, true] {
assert_eq!(guest_request(false, external), Some(GuestRequest::Wake));
}
}
#[test]
fn an_external_monitor_connected_under_a_closed_lid_lights_the_display() {
let mut panel = PanelPower::new();
// Lit, or not dark for the lid: nothing to do.
assert_eq!(panel.external(), None);
assert_eq!(panel.lid(true, true), Some(LidPower::Off));
assert!(panel.lid_dark());
// A dock's monitor: the display lights, so it can show there.
assert_eq!(panel.external(), Some(LidPower::On));
assert!(panel.lit() && !panel.lid_dark());
// The lid's request is unchanged: its end changes nothing more.
assert_eq!(panel.lid(true, true), None);
assert_eq!(panel.lid(false, true), None);
// While the guest's display sleeps, it lights at the guest's wake.
assert_eq!(panel.lid(true, true), Some(LidPower::Off));
assert!(!panel.guest(false));
assert_eq!(panel.external(), Some(LidPower::StaysOff));
assert!(panel.guest(true));
}
}
+2 -2
View File
@@ -22,7 +22,7 @@ impl fmt::Display for InsufficientMemory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"this PC has {} MB of RAM free in firmware; Stela needs at least {} MB to start",
"this PC has {} MB of RAM free in firmware; Stambha needs at least {} MB to start",
self.free / 1_000_000,
MINIMUM_FREE.div_ceil(1_000_000)
)
@@ -53,7 +53,7 @@ mod tests {
);
assert_eq!(
InsufficientMemory { free: 200 * MIB }.to_string(),
"this PC has 209 MB of RAM free in firmware; Stela needs at least 269 MB to start"
"this PC has 209 MB of RAM free in firmware; Stambha needs at least 269 MB to start"
);
assert_eq!(bootstrap_heap(256 * MIB), Ok(16 * MIB));
assert_eq!(bootstrap_heap(1024 * MIB), Ok(64 * MIB));
@@ -122,7 +122,12 @@ impl Image {
Some(state)
if state.syscfg & amd::FIXED_DRAM != 0 && default & (1 << 10) != 0 =>
{
// The legacy hole is never RAM; firmware may leave it WB routed to MMIO
// (Lenovo IdeaPad Pro 5 16AKP10: MTRR 0x259 = 0x06), as Linux tolerates.
amd::fixed_type(kind, cap)
|| (amd::legacy_hole(index)
&& kind & !0x1f == 0
&& memory_type(kind & 7, cap))
}
Some(_) => kind & !0x1f == 0 && memory_type(kind & 7, cap),
None => memory_type(kind, cap),
@@ -334,6 +339,17 @@ mod tests {
.unwrap();
low.value ^= 0x08;
assert!(image.compatible(&changed).is_err());
// VGA memory left WB with MMIO routing (Lenovo IdeaPad Pro 5 16AKP10, 0x259 = 0x06 a
// byte) is admitted; conventional memory with that routing is not.
for (index, admitted) in [(0x259, true), (0x258, false)] {
let mut changed = snapshot;
let msr = changed.msrs[..changed.msr_count as usize]
.iter_mut()
.find(|msr| msr.index == index)
.unwrap();
msr.value = 0x0606_0606_0606_0606;
assert_eq!(Image::from_snapshot(&changed).is_ok(), admitted);
}
}
#[test]
@@ -61,12 +61,12 @@ pub const VENDOR: [u32; 3] = [
pub fn encryption_refusal(syscfg: u64) -> Option<&'static str> {
if syscfg & SECURE_NESTED_PAGING != 0 {
Some(
"SEV-SNP is on in the firmware setup, and Stela does not own its reverse map table: \
"SEV-SNP is on in the firmware setup, and Stambha does not own its reverse map table: \
turn off SEV-SNP (sometimes called SNP Memory Coverage) in the firmware setup",
)
} else if syscfg & HOST_MULTI_KEY != 0 {
Some(
"AMD host multi-key memory encryption is on in the firmware setup, which Stela does \
"AMD host multi-key memory encryption is on in the firmware setup, which Stambha does \
not support: turn it off in the firmware setup",
)
} else {
+214 -1
View File
@@ -19,6 +19,8 @@ const PAGE_SHIFT: u8 = 12;
pub const PAGE: usize = 1 << PAGE_SHIFT;
pub mod cache;
#[path = "native_memory/runs.rs"]
pub mod runs;
/// Checks that `bytes` at CPU address `cpu` map physical `physical` with an
/// effective write-back type, reading page tables at `table_offset` past
@@ -35,6 +37,16 @@ pub struct NativeMemory {
table_offset: AtomicU64,
generation: AtomicU64,
catalogs: AtomicUsize,
runs: runs::Arenas,
}
/// The Linux page arenas' state, for the heap report.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RunUsage {
pub arenas: usize,
pub arena_bytes: usize,
pub used: usize,
pub fallbacks: usize,
}
/// The registered heap extent, as `initialize` recorded it.
@@ -59,6 +71,7 @@ impl NativeMemory {
table_offset: AtomicU64::new(0),
generation: AtomicU64::new(0),
catalogs: AtomicUsize::new(0),
runs: runs::Arenas::new(),
}
}
@@ -214,6 +227,163 @@ impl PageSource for NativeMemory {
}
impl NativeMemory {
/// The Linux page arenas' state.
pub fn run_usage(&self) -> RunUsage {
let arenas = self.runs.count.load(Ordering::Relaxed);
RunUsage {
arenas,
arena_bytes: arenas * runs::ARENA_PAGES * PAGE,
used: self.runs.used.load(Ordering::Relaxed),
fallbacks: self.runs.fallbacks.load(Ordering::Relaxed),
}
}
/// A zeroed write-back run of `1 << order` pages aligned to its size, as
/// Linux's page allocator gives one: from an arena ([`runs`]), or from
/// the heap itself when no arena can be had.
pub fn allocate_run(&'static self, order: u32) -> Result<PinnedPages, MemoryError> {
if order > runs::MAX_RUN_ORDER {
return Err(MemoryError::InvalidSize);
}
let bytes = PAGE << order;
match self.arena_run(order) {
Ok(Some(pages)) => Ok(pages),
Ok(None) => {
self.runs.fallbacks.fetch_add(1, Ordering::Relaxed);
self.allocate(bytes, bytes, CacheAttribute::WriteBack)
}
Err(error) => Err(error),
}
}
/// A run from an arena, a new one when none has room; `None` when the
/// registration's CPU and physical bases differ in their arena residue
/// or the heap has no arena to give.
fn arena_run(&'static self, order: u32) -> Result<Option<PinnedPages>, MemoryError> {
let capacity = self.bytes.load(Ordering::Acquire);
if capacity == 0 {
return Err(MemoryError::Unavailable);
}
let cpu = self.cpu.load(Ordering::Relaxed);
let physical_base = self.physical.load(Ordering::Relaxed);
let arena_align = PAGE << runs::MAX_RUN_ORDER;
if ((cpu as u64) ^ physical_base) & (arena_align as u64 - 1) != 0 {
return Ok(None);
}
let arena_bytes = runs::ARENA_PAGES * PAGE;
let bytes = PAGE << order;
// Nothing is allocated under the arenas' spin lock: an allocation may
// end a GPU job's slice there (the heap's allocation hook), and every
// other processor asking Linux for a page would spin on the lock until
// the job ran again.
let found = {
let mut locked = self.runs.lock();
locked
.arenas()
.iter_mut()
.find_map(|arena| Some((arena.base, arena.buddy.allocate(order)?)))
};
let (base, page) = match found {
Some(found) => found,
None => {
let Some(mut buddy) = runs::Buddy::new() else {
return Ok(None);
};
let layout = Layout::from_size_align(arena_bytes, arena_align)
.map_err(|_| MemoryError::InvalidAlignment)?;
// SAFETY: a valid nonzero layout; the arena owns the block
// until it is wholly free and given back with it.
let Some(base) = NonNull::new(unsafe { self.heap.alloc(layout) }) else {
return Ok(None);
};
let in_heap = (base.as_ptr() as usize)
.checked_sub(cpu)
.is_some_and(|offset| offset + arena_bytes <= capacity);
let page = buddy.allocate(order);
let (true, Some(page)) = (in_heap, page) else {
// SAFETY: the block just allocated with this layout.
unsafe { self.heap.dealloc(base.as_ptr(), layout) };
return if in_heap {
Err(MemoryError::OutOfMemory)
} else {
Err(MemoryError::OutsideReservation)
};
};
if !self.runs.push(runs::Arena { base, buddy }) {
// SAFETY: as above; no run of it was handed out.
unsafe { self.heap.dealloc(base.as_ptr(), layout) };
return Ok(None);
}
self.runs.count.fetch_add(1, Ordering::Relaxed);
(base, page)
}
};
let mut run = RunAllocation {
source: self,
arena: base,
page,
order,
pages: Vec::new(),
};
self.runs.used.fetch_add(bytes, Ordering::Relaxed);
let start = run.cpu_base().as_ptr() as usize;
let physical = physical_base + (start - cpu) as u64;
(self.cache)(
start as u64,
physical,
bytes,
self.table_offset.load(Ordering::Relaxed),
)?;
run.pages
.try_reserve_exact(bytes / PAGE)
.map_err(|_| MemoryError::OutOfMemory)?;
run.pages
.extend((0..bytes / PAGE).map(|index| physical + (index * PAGE) as u64));
// SAFETY: the run's pages, exclusively owned until it drops.
unsafe { core::ptr::write_bytes(start as *mut u8, 0, bytes) };
// SAFETY: a valid nonzero layout for the run's owner.
let storage = NonNull::new(unsafe { alloc::alloc::alloc(Layout::new::<RunAllocation>()) })
.ok_or(MemoryError::OutOfMemory)?
.cast::<RunAllocation>();
// SAFETY: fresh aligned storage, initialized once; the Box owns it.
let run = unsafe {
storage.as_ptr().write(run);
Box::from_raw(storage.as_ptr())
};
PinnedPages::new(run, bytes, bytes).map(Some)
}
/// Give a run back to its arena, and the arena to the heap when it is
/// wholly free and another wholly free arena is kept.
fn free_run(&self, arena: NonNull<u8>, page: usize, order: u32) {
self.runs.used.fetch_sub(PAGE << order, Ordering::Relaxed);
let released = {
let mut locked = self.runs.lock();
let arenas = locked.arenas();
let Some(index) = arenas.iter().position(|candidate| candidate.base == arena) else {
panic!("a Linux page run outside every arena");
};
arenas[index].buddy.free(page, order);
let spare = arenas
.iter()
.enumerate()
.any(|(other, candidate)| other != index && candidate.buddy.empty());
if arenas[index].buddy.empty() && spare {
self.runs.count.fetch_sub(1, Ordering::Relaxed);
Some(arenas.swap_remove(index))
} else {
None
}
};
if let Some(arena) = released {
let layout =
Layout::from_size_align(runs::ARENA_PAGES * PAGE, PAGE << runs::MAX_RUN_ORDER)
.expect("the arena layout");
// SAFETY: the arena's own block and layout, with no run left.
unsafe { self.heap.dealloc(arena.base.as_ptr(), layout) };
}
}
fn allocate_native(
&self,
bytes: usize,
@@ -362,6 +532,49 @@ unsafe impl PageBacking for HeapAllocation {
}
}
/// A run of Linux pages in an arena ([`NativeMemory::allocate_run`]).
struct RunAllocation {
source: &'static NativeMemory,
arena: NonNull<u8>,
page: usize,
order: u32,
pages: Vec<u64>,
}
// SAFETY: as HeapAllocation's: an owned, immovable run; the arenas' lock
// orders its release.
unsafe impl Send for RunAllocation {}
// SAFETY: shared access exposes immutable metadata and raw pointers only.
unsafe impl Sync for RunAllocation {}
// SAFETY: the arena lies in the registered heap, whose PA relation
// initialize proved; the run is aligned to its size, zeroed, and every page
// recorded. Drop returns it only after the last lease.
unsafe impl PageBacking for RunAllocation {
fn cpu_base(&self) -> NonNull<u8> {
// SAFETY: the run lies inside its arena's block.
unsafe { self.arena.add(self.page * PAGE) }
}
fn physical_pages(&self) -> &[u64] {
&self.pages
}
fn page_shift(&self) -> u8 {
PAGE_SHIFT
}
fn cache_attribute(&self) -> CacheAttribute {
CacheAttribute::WriteBack
}
}
impl Drop for RunAllocation {
fn drop(&mut self) {
self.source.free_run(self.arena, self.page, self.order);
}
}
impl Drop for HeapAllocation {
fn drop(&mut self) {
// SAFETY: this owner is released only after every pin/mapping ends,
@@ -371,4 +584,4 @@ impl Drop for HeapAllocation {
}
#[cfg(test)]
mod tests;
pub(crate) mod tests;
@@ -0,0 +1,349 @@
//! Linux page runs from arenas: blocks of [`ARENA_BYTES`] the heap gives
//! whole, split by a buddy allocator into runs of up to [`MAX_RUN_ORDER`],
//! each aligned to its size, with no header between them.
//!
//! Linux's page allocator returns `1 << order` pages aligned to their size,
//! and its catalogue checks that. From the heap itself every such run is a
//! block whose boundary tag sits just before the aligned payload, so two runs
//! of one size can never lie side by side: each strands almost its own size
//! before the next. An integrated GPU's TTM fills its buffers with 4 MiB runs
//! first, and on a ThinkPad T14 Gen 2 (Cezanne) 339 of them (1356 MiB) left
//! a 6400 MiB heap with 1.7 GiB free in no extent larger than 6 MiB, 270 s
//! into macOS's setup, when a 4 MiB allocation of the Metal device failed.
//! In an arena the runs tile, and a freed run joins its buddy again.
//!
//! An arena the heap cannot give falls back to the heap's own block, as
//! before; an arena whose runs are all free goes back to the heap, but for
//! one kept for the next.
use alloc::vec::Vec;
use core::{
cell::UnsafeCell,
ptr::NonNull,
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
/// Pages in an arena: 32 MiB of 4 KiB pages.
pub const ARENA_ORDER: u32 = 13;
pub const ARENA_PAGES: usize = 1 << ARENA_ORDER;
/// Linux's `MAX_PAGE_ORDER`: runs of up to 4 MiB, and the arenas' alignment.
pub const MAX_RUN_ORDER: u32 = 10;
const LEVELS: usize = ARENA_ORDER as usize + 1;
/// The free runs of one arena, by order: a bit per run of each order, set
/// when that run is free and its buddy is not (they would have joined).
pub(crate) struct Buddy {
bits: Vec<u64>,
/// Each order's first word in `bits`.
offsets: [usize; LEVELS],
/// Each order's free runs.
free: [usize; LEVELS],
}
impl Buddy {
/// A wholly free arena, or `None` when its bitmaps cannot be allocated.
pub(crate) fn new() -> Option<Self> {
let mut offsets = [0; LEVELS];
let mut words = 0;
for (order, offset) in offsets.iter_mut().enumerate() {
*offset = words;
words += (ARENA_PAGES >> order).div_ceil(64);
}
let mut bits = Vec::new();
bits.try_reserve_exact(words).ok()?;
bits.resize(words, 0);
let mut buddy = Self {
bits,
offsets,
free: [0; LEVELS],
};
buddy.set(ARENA_ORDER as usize, 0, true);
Some(buddy)
}
fn get(&self, order: usize, index: usize) -> bool {
self.bits[self.offsets[order] + index / 64] & (1 << (index % 64)) != 0
}
fn set(&mut self, order: usize, index: usize, free: bool) {
let word = &mut self.bits[self.offsets[order] + index / 64];
let bit = 1 << (index % 64);
if free {
debug_assert!(*word & bit == 0);
*word |= bit;
self.free[order] += 1;
} else {
debug_assert!(*word & bit != 0);
*word &= !bit;
self.free[order] -= 1;
}
}
fn first(&self, order: usize) -> Option<usize> {
let words = (ARENA_PAGES >> order).div_ceil(64);
let start = self.offsets[order];
self.bits[start..start + words]
.iter()
.position(|word| *word != 0)
.map(|word| word * 64 + self.bits[start + word].trailing_zeros() as usize)
}
/// Take a free run of `order`, splitting the smallest larger one when
/// none is free: its first page.
pub(crate) fn allocate(&mut self, order: u32) -> Option<usize> {
let order = order as usize;
let from = (order..LEVELS).find(|level| self.free[*level] != 0)?;
let mut index = self.first(from)?;
self.set(from, index, false);
for level in (order..from).rev() {
index *= 2;
self.set(level, index + 1, true);
}
Some(index << order)
}
/// Free the run of `order` at `page`, joining it with its free buddies.
pub(crate) fn free(&mut self, page: usize, order: u32) {
let mut order = order as usize;
let mut index = page >> order;
debug_assert_eq!(index << order, page);
while order < ARENA_ORDER as usize && self.get(order, index ^ 1) {
self.set(order, index ^ 1, false);
index /= 2;
order += 1;
}
self.set(order, index, true);
}
/// Whether every page is free.
pub(crate) fn empty(&self) -> bool {
self.free[ARENA_ORDER as usize] == 1
}
/// Free pages.
#[cfg(test)]
pub(crate) fn free_pages(&self) -> usize {
self.free
.iter()
.enumerate()
.map(|(order, count)| count << order)
.sum()
}
}
pub(crate) struct Arena {
pub(crate) base: NonNull<u8>,
pub(crate) buddy: Buddy,
}
/// The arenas, behind a spin lock: Linux page requests come in process or
/// deferred context only (atomic ones are refused), and none nests.
pub(crate) struct Arenas {
held: AtomicBool,
arenas: UnsafeCell<Vec<Arena>>,
/// Arenas, and the bytes in runs, for the heap report.
pub(crate) count: AtomicUsize,
pub(crate) used: AtomicUsize,
/// Runs the arenas could not serve, which came from the heap.
pub(crate) fallbacks: AtomicUsize,
}
// SAFETY: `arenas` is touched only under `held`.
unsafe impl Sync for Arenas {}
pub(crate) struct Locked<'a> {
owner: &'a Arenas,
}
impl Drop for Locked<'_> {
fn drop(&mut self) {
self.owner.held.store(false, Ordering::Release);
}
}
impl Locked<'_> {
pub(crate) fn arenas(&mut self) -> &mut Vec<Arena> {
// SAFETY: this guard holds the lock.
unsafe { &mut *self.owner.arenas.get() }
}
}
impl Arenas {
pub(crate) const fn new() -> Self {
Self {
held: AtomicBool::new(false),
arenas: UnsafeCell::new(Vec::new()),
count: AtomicUsize::new(0),
used: AtomicUsize::new(0),
fallbacks: AtomicUsize::new(0),
}
}
pub(crate) fn lock(&self) -> Locked<'_> {
while self
.held
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
core::hint::spin_loop();
}
Locked { owner: self }
}
/// Adds `arena`, growing the list outside the lock: false when no room
/// for it could be allocated.
pub(crate) fn push(&self, arena: Arena) -> bool {
loop {
let wanted = {
let mut locked = self.lock();
let arenas = locked.arenas();
if arenas.len() < arenas.capacity() {
arenas.push(arena);
return true;
}
arenas.capacity() * 2 + 4
};
let mut bigger = Vec::new();
if bigger.try_reserve_exact(wanted).is_err() {
return false;
}
let old = {
let mut locked = self.lock();
let arenas = locked.arenas();
if arenas.capacity() >= bigger.capacity() {
// Another request grew it meanwhile.
None
} else {
bigger.append(arenas);
Some(core::mem::replace(arenas, bigger))
}
};
// The smaller list (or the unused one) is freed outside the lock.
drop(old);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runs_of_one_order_tile_an_arena_and_join_again_when_freed() {
let mut buddy = Buddy::new().unwrap();
let order = MAX_RUN_ORDER;
let runs: Vec<usize> = (0..ARENA_PAGES >> order)
.map(|_| buddy.allocate(order).unwrap())
.collect();
// Every run aligned to its size, side by side.
for (index, page) in runs.iter().enumerate() {
assert_eq!(*page, index << order);
}
assert_eq!(buddy.allocate(0), None);
assert_eq!(buddy.free_pages(), 0);
for page in runs.iter().rev() {
buddy.free(*page, order);
}
assert!(buddy.empty());
assert_eq!(buddy.free_pages(), ARENA_PAGES);
}
#[test]
fn four_mib_runs_tile_their_arenas_and_the_arenas_go_back_to_the_heap() {
use crate::{
heap::Heap,
native_memory::{NativeMemory, PAGE},
};
use core::alloc::Layout;
static HEAP: Heap = Heap::new();
static SOURCE: NativeMemory = NativeMemory::new(&HEAP, |_, _, _, _| Ok(()));
let arena = ARENA_PAGES * PAGE;
let bytes = 3 * arena + (16 << 20);
let layout = Layout::from_size_align(bytes, 4 << 20).unwrap();
// SAFETY: test RAM kept for the whole test; its PA relation is a model.
let ram = unsafe { std::alloc::alloc_zeroed(layout) };
assert!(!ram.is_null());
// SAFETY: one dedicated extent, no users before initialization.
unsafe {
HEAP.initialize(ram, bytes);
SOURCE.initialize(ram as usize, 0x1_0000_0000, bytes, 0);
}
let runs_per_arena = ARENA_PAGES >> MAX_RUN_ORDER;
let mut runs = Vec::new();
for _ in 0..3 * runs_per_arena {
runs.push(SOURCE.allocate_run(MAX_RUN_ORDER).unwrap());
}
let usage = SOURCE.run_usage();
assert_eq!((usage.arenas, usage.fallbacks), (3, 0));
assert_eq!(usage.used, 3 * arena);
// The heap holds the three arenas and their bitmaps, no gap per run.
assert!(
HEAP.usage().live < 3 * arena + (64 << 10),
"{}",
HEAP.usage().live
);
let mut bases: Vec<usize> = runs
.iter()
.map(|run| {
let mapping = run
.cpu_mapping(stela_drivers::bus::dma::memory::CacheAttribute::WriteBack)
.unwrap();
mapping.address(0, 1).unwrap().as_ptr() as usize
})
.collect();
bases.sort();
for base in &bases {
assert_eq!(base % (PAGE << MAX_RUN_ORDER), 0);
let offset = (base - ram as usize) as u64;
assert_eq!((0x1_0000_0000 + offset) % (PAGE << MAX_RUN_ORDER) as u64, 0);
}
bases.dedup();
assert_eq!(bases.len(), runs.len());
// The heap has no room for a fourth arena: a run comes from the heap.
let fallback = SOURCE.allocate_run(0).unwrap();
assert_eq!(SOURCE.run_usage().fallbacks, 1);
drop(fallback);
runs.clear();
// One wholly free arena is kept, the rest go back.
let usage = SOURCE.run_usage();
assert_eq!((usage.arenas, usage.used), (1, 0));
let small = SOURCE.allocate_run(0).unwrap();
assert_eq!(SOURCE.run_usage().arenas, 1);
drop(small);
}
#[test]
fn mixed_orders_split_the_smallest_run_and_rejoin_in_any_order() {
let mut buddy = Buddy::new().unwrap();
let mut live = Vec::new();
let mut seed = 0x2545_f491_u64;
let mut taken = 0;
for _ in 0..4000 {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
if live.is_empty() || !seed.is_multiple_of(3) {
let order = (seed >> 8) as u32 % (MAX_RUN_ORDER + 1);
if let Some(page) = buddy.allocate(order) {
assert_eq!(page % (1 << order), 0);
// No overlap with a live run.
for (other, other_order) in &live {
let (a, b) = (page, page + (1 << order));
let (c, d) = (*other, *other + (1usize << *other_order));
assert!(b <= c || d <= a);
}
taken += 1 << order;
live.push((page, order));
}
} else {
let (page, order) = live.swap_remove((seed >> 20) as usize % live.len());
taken -= 1 << order;
buddy.free(page, order);
}
assert_eq!(buddy.free_pages(), ARENA_PAGES - taken);
}
for (page, order) in live.drain(..) {
buddy.free(page, order);
}
assert!(buddy.empty());
}
}
@@ -4,7 +4,7 @@ use core::alloc::Layout;
// Only the hosted test executable uses this allocator. Each armed window
// is thread-local and contains no harness/assertion work. The production
// provider has no fault hook or alternate allocation path.
pub(super) mod allocation_failure {
pub(crate) mod allocation_failure {
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
+10 -6
View File
@@ -83,6 +83,9 @@ pub const ORDINARY_GENERAL_TASKS: usize = 4;
/// ones. Each Linux kthread, ioctl worker and driver thread holds one.
pub const KERNEL_GENERAL_TASKS: usize =
TASK_STACKS - stela_driver_base::platform::work::ROLE_STACKS - ORDINARY_GENERAL_TASKS;
/// A Linux task's stack: Linux's `THREAD_SIZE` as Stela's Linux build sets
/// it, which also aligns it (`stela_linux::task::stack_requirement`).
pub const LINUX_TASK_STACK_BYTES: u64 = 32 * 1024;
/// An ordinary task's Rust stack. Native driver probes run on one, through
/// controller attach paths whose frames alone pass 128 KiB.
pub const ORDINARY_TASK_STACK_BYTES: u64 = 1024 * 1024;
@@ -95,7 +98,7 @@ pub fn task_stacks(
base: u64,
) -> Result<crate::guarded_stacks::MixedLayout, crate::guarded_stacks::Error> {
use crate::guarded_stacks::{Error, Geometry, MixedLayout};
let kernel = Geometry::new(16 * 1024, 16 * 1024)?;
let kernel = Geometry::new(LINUX_TASK_STACK_BYTES, LINUX_TASK_STACK_BYTES)?;
let ordinary = Geometry::new(ORDINARY_TASK_STACK_BYTES, PAGE)?;
let geometries = core::array::from_fn::<_, TASK_STACKS, _>(|index| {
let roles = stela_driver_base::platform::work::ROLE_STACKS;
@@ -167,7 +170,7 @@ pub const WINDOW_PER_RUNNER: u64 = 96 * MIB;
/// The window per runner when [`WINDOW_PER_RUNNER`] would leave the guest
/// under its floor ([`crate::host_memory::sizes`] falls back to it).
pub const SMALL_WINDOW_PER_RUNNER: u64 = 64 * MIB;
const MIN_WINDOW: u64 = 64 * MIB;
pub const MIN_WINDOW: u64 = 64 * MIB;
pub const MAX_WINDOW: u64 = 2048 * MIB;
pub const CODE_ALIGNMENT: u64 = 16 * MIB;
pub const MAX_CODE_PARTS: u32 = 32;
@@ -440,19 +443,20 @@ mod tests {
assert_eq!(layout.count(), TASK_STACKS);
assert_eq!(
layout.physical_bytes(),
kernel as u64 * 16 * 1024 + ordinary as u64 * ORDINARY_TASK_STACK_BYTES
kernel as u64 * LINUX_TASK_STACK_BYTES + ordinary as u64 * ORDINARY_TASK_STACK_BYTES
);
assert_eq!(
layout.raw_allocation_bytes(),
layout.physical_bytes() + 12_288
// The first Linux stack's alignment, less the page UEFI gives.
layout.physical_bytes() + LINUX_TASK_STACK_BYTES - 4096
);
let mut counts = (0, 0);
for index in 0..TASK_STACKS {
let slot = layout.slot(index).unwrap();
let bytes = slot.usable.end - slot.usable.start;
if bytes == 16 * 1024 {
if bytes == LINUX_TASK_STACK_BYTES {
counts.0 += 1;
assert_eq!(slot.usable.start % (16 * 1024), 0);
assert_eq!(slot.usable.start % LINUX_TASK_STACK_BYTES, 0);
} else {
assert_eq!(bytes, ORDINARY_TASK_STACK_BYTES);
counts.1 += 1;
+137
View File
@@ -24,6 +24,97 @@ use stela_runtime::net::{NetError, stack::DHCP_WAIT_US};
/// What a hidden network name reads as.
const HIDDEN: &str = "<ssid>";
/// Which of the host's adapters macOS's network takes, given each one's
/// `carriers` now and whether it is `wireless`, in probe order: the first
/// with carrier; else, when a Wi-Fi network is configured (`--wifi`), the
/// first Wi-Fi adapter, whose keeper joins that network once the guest
/// owns it; else the first. A Wi-Fi adapter has no carrier before its
/// keeper runs, so on a laptop whose Ethernet port precedes its Wi-Fi and
/// has no cable, the first adapter was always the empty port and macOS
/// had no network although Wi-Fi was configured.
pub fn guest_adapter(carriers: &[bool], wireless: &[bool], wifi_configured: bool) -> usize {
carriers
.iter()
.position(|&carrier| carrier)
.or_else(|| {
wifi_configured
.then(|| wireless.iter().position(|&wireless| wireless))
.flatten()
})
.unwrap_or(0)
}
/// How long macOS's host adapter has had no carrier before another started
/// adapter with one takes its place ([`guest_switch`]): a cable moved from
/// one port to another, or a USB adapter whose PHY was still negotiating
/// when the guest network chose, is followed within seconds, where 0.6.0
/// kept the adapter it chose at the start for the whole boot.
pub const SWITCH_AFTER_MS: u64 = 2_000;
/// How long a spare adapter's carrier has held before it takes macOS's
/// network ([`guest_switch`]): a port that blinks up for a moment does not.
/// A 0.6.0 log of an IdeaPad with a broken RTL8168G port has that port up
/// for 410 ms and later 5.6 s, and an AX88179A up for 107 ms.
pub const SPARE_STEADY_MS: u64 = 1_000;
/// How long a wired adapter's carrier has held before the boot records a
/// wired network as up for the next boot's menu
/// (`wifi_prompt::Record::Wired`), which then leaves its Wi-Fi page closed:
/// that log's broken port and AX88179A each had a link for a moment, which
/// 0.6.1 would record as a wired network, closing the page on a machine
/// whose only working network may be its Wi-Fi.
pub const WIRED_STEADY_MS: u64 = 10_000;
/// Whether a carrier up since `since_ms` (none while down) has held for
/// `hold_ms` at `now_ms`.
pub fn steady(since_ms: Option<u64>, now_ms: u64, hold_ms: u64) -> bool {
since_ms.is_some_and(|since| now_ms.saturating_sub(since) >= hold_ms)
}
/// Which spare adapter takes macOS's network at `now_ms`, all times in one
/// clock's milliseconds: none while its host adapter has carrier
/// (`down_since_ms` none) or has had none for less than
/// [`SWITCH_AFTER_MS`]; else the first spare, in order, whose carrier has
/// been up (`spares_up_since_ms`) for [`SPARE_STEADY_MS`].
pub fn guest_switch(
now_ms: u64,
down_since_ms: Option<u64>,
spares_up_since_ms: &[Option<u64>],
) -> Option<usize> {
if !steady(down_since_ms, now_ms, SWITCH_AFTER_MS) {
return None;
}
spares_up_since_ms
.iter()
.position(|&since| steady(since, now_ms, SPARE_STEADY_MS))
}
/// [`guest_adapter`] among the adapters whose station address is `usable`,
/// in the same order; none when no adapter has one. The guest's USB
/// Ethernet adapter takes its host adapter's address, so an Intel Wi-Fi
/// chip whose firmware had not read its address yet gave macOS all zeros
/// and 0.6.1 stopped the boot ("the USB Ethernet address must be a unicast
/// address") on a laptop with no cable and a Wi-Fi network configured.
pub fn usable_guest_adapter(
carriers: &[bool],
wireless: &[bool],
usable: &[bool],
wifi_configured: bool,
) -> Option<usize> {
let kept: alloc::vec::Vec<usize> = (0..carriers.len())
.filter(|&index| usable.get(index).copied().unwrap_or(false))
.collect();
if kept.is_empty() {
return None;
}
let pick = |of: &[bool]| -> alloc::vec::Vec<bool> {
kept.iter()
.map(|&index| of.get(index).copied().unwrap_or(false))
.collect()
};
Some(kept[guest_adapter(&pick(carriers), &pick(wireless), wifi_configured)])
}
/// `text` with the network's name `ssid` written `<ssid>` wherever it
/// occurs, byte for byte, as `String::from_utf8_lossy` writes it (the
/// connection keeper's failures name the network so): occurrences that
@@ -226,5 +317,51 @@ pub fn address<T>(
(result, retried)
}
/// What became of the host adapter's receive signal once the guest's link
/// came up ([`receive_signal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReceiveSignal {
/// The adapter raises no receive signal: its driver polls, and its
/// frames are read at each host service turn, wherever that runs.
Polled,
/// The signal now goes to the processor asked for.
Moved,
/// The adapter signals, but its driver could not move the signal.
Kept,
}
/// Where the receive signal of an adapter that `signals` goes: moved by
/// `retarget` (`Link::retarget`), which is asked only of an adapter that
/// signals. Every adapter but a virtio one polled or kept its signal and
/// logged "stays: no MSI-X entry for processor apic=…" on 0.6.1, which read
/// as a missing entry for that processor when the processor was one of the
/// boot's own and the adapter (an I219, an RTL8168, an RTL8156) had no
/// signal to move.
pub fn receive_signal(signals: bool, retarget: impl FnOnce() -> bool) -> ReceiveSignal {
match (signals, signals && retarget()) {
(false, _) => ReceiveSignal::Polled,
(true, true) => ReceiveSignal::Moved,
(true, false) => ReceiveSignal::Kept,
}
}
/// The log line for `signal`, of the adapter at `location`, asked to
/// signal processor `apic` on `vector`.
pub fn receive_signal_line(signal: ReceiveSignal, location: &str, apic: u64, vector: u8) -> String {
match signal {
ReceiveSignal::Polled => alloc::format!(
"GUEST NETWORK receive polled: host adapter {location} raises no receive signal, \
its frames are read at each host service turn\n"
),
ReceiveSignal::Moved => alloc::format!(
"GUEST NETWORK receive signal moved to processor apic={apic:#x} vector={vector:#x}\n"
),
ReceiveSignal::Kept => alloc::format!(
"GUEST NETWORK receive signal stays where host adapter {location}'s driver set it: \
the driver cannot move it to processor apic={apic:#x} vector={vector:#x}\n"
),
}
}
#[cfg(test)]
mod tests;
@@ -235,3 +235,167 @@ fn a_keeper_failure_reaches_the_boot_with_the_name_hidden() {
);
assert!(!error.to_string().contains("test"));
}
/// macOS's network takes an adapter with carrier first; with none, the
/// configured Wi-Fi adapter, not an empty Ethernet port probed before it;
/// without a configured network, the first adapter as before.
#[test]
fn the_guest_takes_the_configured_wifi_over_an_empty_ethernet_port() {
// Ethernet (no cable) then Wi-Fi, a network configured: Wi-Fi.
assert_eq!(guest_adapter(&[false, false], &[false, true], true), 1);
// No network configured: the first adapter, as before.
assert_eq!(guest_adapter(&[false, false], &[false, true], false), 0);
// A cable in the Ethernet port: carrier wins over Wi-Fi.
assert_eq!(guest_adapter(&[true, false], &[false, true], true), 0);
// Carrier on a later adapter wins over the configured Wi-Fi.
assert_eq!(
guest_adapter(&[false, false, true], &[false, true, false], true),
2
);
// No Wi-Fi adapter at all: the first adapter.
assert_eq!(guest_adapter(&[false, false], &[false, false], true), 0);
// Wi-Fi alone: itself.
assert_eq!(guest_adapter(&[false], &[true], true), 0);
}
/// macOS's network leaves a host adapter without carrier for a spare that
/// has one, once the first has been down for a while and the spare's link
/// has held: a cable in a USB adapter whose PHY was still negotiating when
/// the guest chose the empty built-in port is followed.
#[test]
fn the_guest_moves_to_a_spare_whose_link_held_once_its_own_is_gone() {
// Its own link up: no move, whatever the spares say.
assert_eq!(guest_switch(10_000, None, &[Some(0)]), None);
// Down for less than the wait: no move yet.
assert_eq!(
guest_switch(10_000, Some(10_000 - SWITCH_AFTER_MS + 1), &[Some(0)]),
None
);
// Down for the wait, the spare up long enough: the spare.
assert_eq!(
guest_switch(10_000, Some(10_000 - SWITCH_AFTER_MS), &[Some(0)]),
Some(0)
);
// A spare that only just came up (a blinking port) is passed over for a
// later one whose link held.
assert_eq!(
guest_switch(10_000, Some(0), &[Some(9_900), None, Some(8_000)]),
Some(2)
);
// No spare with a held link: none.
assert_eq!(guest_switch(10_000, Some(0), &[None, Some(9_999)]), None);
assert_eq!(guest_switch(10_000, Some(0), &[]), None);
}
/// A wired link is recorded for the next boot's menu only once it held: the
/// 107 ms and 410 ms links of a 0.6.0 IdeaPad log are not a wired network.
#[test]
fn a_wired_link_counts_once_it_held() {
assert!(!steady(None, 50_000, WIRED_STEADY_MS));
assert!(!steady(Some(1_000), 1_107, WIRED_STEADY_MS));
assert!(!steady(Some(1_000), 1_410, WIRED_STEADY_MS));
assert!(steady(
Some(1_000),
1_000 + WIRED_STEADY_MS,
WIRED_STEADY_MS
));
// A clock read before the start counts as no time held.
assert!(!steady(Some(5_000), 1_000, 1));
}
/// An adapter without a usable station address is passed over, keeping the
/// order the guest's choice follows; none at all when no adapter has one.
#[test]
fn the_guest_adapter_is_one_with_a_usable_station_address() {
// A laptop's I219 with no cable and an AX200 whose firmware has not
// named its address: the I219, where 0.6.1 took the AX200 and stopped.
let (carriers, wireless) = ([false, false], [false, true]);
assert_eq!(guest_adapter(&carriers, &wireless, true), 1);
assert_eq!(
usable_guest_adapter(&carriers, &wireless, &[true, false], true),
Some(0)
);
// With its address the Wi-Fi chip is taken, as before.
assert_eq!(
usable_guest_adapter(&carriers, &wireless, &[true, true], true),
Some(1)
);
assert_eq!(
usable_guest_adapter(&carriers, &wireless, &[true, true], false),
Some(0)
);
// A carrier still comes first among the usable, and the indices are
// the adapters' own.
assert_eq!(
usable_guest_adapter(
&[true, false, true],
&[false; 3],
&[false, true, true],
false
),
Some(2)
);
assert_eq!(
usable_guest_adapter(
&[false, false, false],
&[false, true, true],
&[true, false, true],
true
),
Some(2)
);
assert_eq!(
usable_guest_adapter(&carriers, &wireless, &[false, false], true),
None
);
assert_eq!(usable_guest_adapter(&[], &[], &[], true), None);
}
/// An adapter that raises no receive signal (the I219 of a 0.6.1 log whose
/// line read "stays: no MSI-X entry for processor apic=0xe" while 0xe ran
/// one of the boot's PEs) is polled: its driver is never asked to move a
/// signal, and the line says it polls rather than naming a missing entry.
#[test]
fn an_adapter_without_a_receive_signal_is_polled_and_never_retargeted() {
let asked = Cell::new(false);
let signal = receive_signal(false, || {
asked.set(true);
true
});
assert_eq!(signal, ReceiveSignal::Polled);
assert!(!asked.get());
let line = receive_signal_line(signal, "0000:00:1f.6 Intel I219", 0xe, 0x63);
assert_eq!(
line,
"GUEST NETWORK receive polled: host adapter 0000:00:1f.6 Intel I219 raises no receive \
signal, its frames are read at each host service turn\n"
);
assert!(!line.contains("MSI-X"));
assert!(!line.contains("apic"));
}
/// An adapter that signals is asked to move its signal once: moved, the
/// line keeps 0.6.1's wording; refused, it names the driver, not an entry.
#[test]
fn a_signalling_adapter_is_moved_or_kept_as_its_driver_answers() {
let asked = Cell::new(0);
let moved = receive_signal(true, || {
asked.set(asked.get() + 1);
true
});
assert_eq!((moved, asked.get()), (ReceiveSignal::Moved, 1));
assert_eq!(
receive_signal_line(moved, "0000:00:03.0", 0x2, 0x63),
"GUEST NETWORK receive signal moved to processor apic=0x2 vector=0x63\n"
);
let kept = receive_signal(true, || {
asked.set(asked.get() + 1);
false
});
assert_eq!((kept, asked.get()), (ReceiveSignal::Kept, 2));
assert_eq!(
receive_signal_line(kept, "0000:02:00.0 RTL8168H/RTL8111H XID 541", 0xc, 0x63),
"GUEST NETWORK receive signal stays where host adapter 0000:02:00.0 RTL8168H/RTL8111H \
XID 541's driver set it: the driver cannot move it to processor apic=0xc vector=0x63\n"
);
}
+352
View File
@@ -213,6 +213,208 @@ pub fn read<E>(
.ok_or(unread.map_or(Absent::NoTable, Absent::Read))
}
/// What the display code reads from a Video BIOS Table for the built-in
/// panel (`intel_bios.c`): which panel entry is its, how its backlight is
/// driven, and the eDP power sequence delays it waits through.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Panel {
/// The table's BDB version.
pub version: u16,
/// The panel's entry, or `None` when the table leaves it to the panel's
/// EDID (255), which the display code matches against the table's
/// panel IDs (entry 0 when none matches). A table without the LFP
/// options block, or with an entry past 15, gives entry 0, the display
/// code's fallback (`get_panel_type`), with [`Self::fallback`] set.
pub panel_type: Option<u8>,
/// Whether [`Self::panel_type`] is the display code's fallback, not the
/// table's choice.
pub fallback: bool,
/// The panel entry's backlight, when the table has the block.
pub backlight: Option<Backlight>,
/// The panel entry's eDP power sequence, in 100 µs units: T1+T3, T8,
/// T9, T10, T11+T12 (`struct edp_power_seq`), when the table has the
/// eDP block.
pub power_sequence: Option<[u16; 5]>,
}
/// A panel entry's backlight in the table (`bdb_lfp_backlight`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Backlight {
/// A PWM signal, of `hertz`, from `method` (`lfp_backlight_control_method`
/// from BDB 191 on: 0 PMIC, 1 LPSS, 2 the display's own PWM, 3 DSI DCS,
/// 4 the panel driver, 5 the eDP AUX interface; before 191 the
/// display's own PWM) and its controller, `active_low` where its duty
/// is inverted.
Pwm {
method: u8,
controller: u8,
hertz: u16,
active_low: bool,
},
/// No PWM backlight (another entry type): the display code registers no
/// backlight for the panel (`intel_backlight_setup`), so it sets no
/// level.
NoPwm(u8),
}
/// BDB block IDs (`enum bdb_block_id`).
const BDB_EDP: u8 = 27;
const BDB_LFP_OPTIONS: u8 = 40;
const BDB_LFP_BACKLIGHT: u8 = 43;
const BDB_MIPI_SEQUENCE: u8 = 53;
/// The data of the BDB block `id` of `bdb`, as `find_raw_section` walks the
/// blocks: an ID, a 16-bit size (32-bit for a MIPI sequence block of
/// version 3 and later), then the data.
fn block(bdb: &[u8], id: u8) -> Option<&[u8]> {
let header = usize::from(u16::from_le_bytes([*bdb.get(18)?, *bdb.get(19)?]));
let total = usize::from(u16::from_le_bytes([*bdb.get(20)?, *bdb.get(21)?])).min(bdb.len());
let mut index = header;
while index + 3 < total {
let current = bdb[index];
let size = if current == BDB_MIPI_SEQUENCE && *bdb.get(index + 3)? >= 3 {
u32::from_le_bytes(bdb.get(index + 4..index + 8)?.try_into().ok()?) as usize
} else {
usize::from(u16::from_le_bytes([bdb[index + 1], bdb[index + 2]]))
};
index += 3;
let end = index.checked_add(size)?;
if end > total {
return None;
}
if current == id {
return Some(&bdb[index..end]);
}
index = end;
}
None
}
/// What the display code reads for the built-in panel from the Video BIOS
/// Table `vbt` (as [`table`] cut it), or `None` when its data block cannot
/// be found. Every field is read only where the block holds it.
pub fn panel(vbt: &[u8]) -> Option<Panel> {
/// `struct vbt_header`'s `bdb_offset`.
const BDB_OFFSET: usize = 0x1c;
let offset = u32::from_le_bytes(vbt.get(BDB_OFFSET..BDB_OFFSET + 4)?.try_into().ok()?);
let bdb = vbt.get(offset as usize..)?;
if bdb.get(..16)? != b"BIOS_DATA_BLOCK " {
return None;
}
let version = u16::from_le_bytes([*bdb.get(16)?, *bdb.get(17)?]);
// The OpRegion's panel type, which the display code asks first, comes
// through ACPI, which Stela's Linux does not build.
let (panel_type, fallback) =
match block(bdb, BDB_LFP_OPTIONS).and_then(|options| options.first().copied()) {
Some(panel @ 0..16) => (Some(panel), false),
Some(255) => (None, false),
_ => (Some(0), true),
};
let backlight = panel_type.and_then(|panel| {
let panel = usize::from(panel);
let data = block(bdb, BDB_LFP_BACKLIGHT)?;
// `entry_size`, then 16 entries of `lfp_backlight_data_entry`.
const ENTRY: usize = 6;
if usize::from(*data.first()?) != ENTRY {
return None;
}
let entry = data.get(1 + panel * ENTRY..1 + (panel + 1) * ENTRY)?;
let kind = entry[0] & 3;
if kind != 2 {
return Some(Backlight::NoPwm(kind));
}
let hertz = u16::from_le_bytes([entry[1], entry[2]]);
// `level[16]`, then `backlight_control[16]` from 191 on.
let (method, controller) = match data.get(1 + 16 * ENTRY + 16 + panel) {
Some(&control) if version >= 191 => (control & 0xf, control >> 4),
_ => (2, 0),
};
Some(Backlight::Pwm {
method,
controller,
hertz,
active_low: entry[0] & 4 != 0,
})
});
let power_sequence = panel_type.and_then(|panel| {
let data = block(bdb, BDB_EDP)?;
let entry = data.get(usize::from(panel) * 10..usize::from(panel) * 10 + 10)?;
let mut delays = [0; 5];
for (delay, bytes) in delays.iter_mut().zip(entry.as_chunks::<2>().0) {
*delay = u16::from_le_bytes(*bytes);
}
Some(delays)
});
Some(Panel {
version,
panel_type,
fallback,
backlight,
power_sequence,
})
}
impl core::fmt::Display for Panel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "BDB {}: ", self.version)?;
match self.panel_type {
Some(panel) if self.fallback => write!(
f,
"panel entry {panel}, the display code's fallback, as the table names no valid one"
)?,
Some(panel) => write!(f, "panel entry {panel}")?,
None => f.write_str("panel entry chosen by the panel's EDID (0 where none matches)")?,
}
match self.backlight {
Some(Backlight::Pwm {
method,
controller,
hertz,
active_low,
}) => {
let by = match method {
0 => "the PMIC",
1 => "the LPSS PWM",
2 => "the display's own PWM",
3 => "DSI DCS commands",
4 => "the panel driver",
5 => "the eDP AUX channel",
_ => "an unknown method",
};
write!(
f,
"; backlight by {by} (method {method}, controller {controller}) at {hertz} Hz{}",
if active_low { ", active low" } else { "" }
)?;
}
Some(Backlight::NoPwm(kind)) => write!(
f,
"; no PWM backlight (type {kind}): the display code registers no backlight and \
sets no level"
)?,
None if self.panel_type.is_some() => f.write_str(
"; no backlight block: the display code registers no backlight and sets no level",
)?,
None => {}
}
match self.power_sequence {
Some([t1_t3, t8, t9, t10, t11_t12]) => write!(
f,
"; eDP power delays T1+T3 {}, T8 {}, T9 {}, T10 {}, T11+T12 {} ms",
t1_t3 / 10,
t8 / 10,
t9 / 10,
t10 / 10,
t11_t12 / 10
),
None if self.panel_type.is_some() => {
f.write_str("; no eDP block: the registers' delays, or the eDP specification's where they read 0")
}
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -379,4 +581,154 @@ mod tests {
assert_eq!(table(&bytes), None);
assert_eq!(table(&bytes[..40]), None);
}
/// A table of BDB `version` with `blocks`, each an ID and its data.
fn with_blocks(version: u16, blocks: &[(u8, Vec<u8>)]) -> Vec<u8> {
let mut bdb = b"BIOS_DATA_BLOCK ".to_vec();
bdb.extend(version.to_le_bytes());
bdb.extend(22u16.to_le_bytes());
bdb.extend(0u16.to_le_bytes());
for (id, data) in blocks {
bdb.push(*id);
bdb.extend((data.len() as u16).to_le_bytes());
bdb.extend(data);
}
let size = bdb.len() as u16;
bdb[20..22].copy_from_slice(&size.to_le_bytes());
let mut table = vec![0; 48];
table[..4].copy_from_slice(b"$VBT");
table[0x1c..0x20].copy_from_slice(&48u32.to_le_bytes());
table.extend(bdb);
let total = table.len() as u16;
table[0x18..0x1a].copy_from_slice(&total.to_le_bytes());
table
}
#[test]
fn the_panels_backlight_and_power_delays_are_its_entrys() {
let mut backlight = vec![6];
for panel in 0..16u8 {
// Panel 3: a PWM of 200 Hz, active low; the others none.
let kind = if panel == 3 { 2 | 4 } else { 0 };
backlight.extend([kind, 200, 0, 0, 0, 0]);
}
backlight.extend([0; 16]);
let mut methods = [0u8; 16];
methods[3] = 5 | 1 << 4;
backlight.extend(methods);
let mut edp = vec![0; 160];
edp[30..40].copy_from_slice(&[0xd2, 0, 0x64, 0, 0xc8, 0, 0xf4, 1, 0x88, 0x13]);
// A MIPI block of version 3 comes first, its size in 32 bits after
// its version (the 16-bit size is not read).
let mut mipi = vec![3];
mipi.extend(6u32.to_le_bytes());
mipi.push(0);
let vbt = with_blocks(
236,
&[
(BDB_MIPI_SEQUENCE, mipi),
(BDB_LFP_OPTIONS, vec![3, 0, 0, 0]),
(BDB_LFP_BACKLIGHT, backlight),
(BDB_EDP, edp),
],
);
let panel = panel(table(&vbt).unwrap()).unwrap();
assert_eq!(
panel,
Panel {
version: 236,
panel_type: Some(3),
fallback: false,
backlight: Some(Backlight::Pwm {
method: 5,
controller: 1,
hertz: 200,
active_low: true,
}),
power_sequence: Some([210, 100, 200, 500, 5000]),
}
);
assert_eq!(
alloc::format!("{panel}"),
"BDB 236: panel entry 3; backlight by the eDP AUX channel (method 5, controller 1) \
at 200 Hz, active low; eDP power delays T1+T3 21, T8 10, T9 20, T10 50, T11+T12 \
500 ms"
);
// Before 191 the PWM is the display's own; a panel the EDID picks
// has no entry; no data block, no answer.
let old = with_blocks(
190,
&[
(BDB_LFP_OPTIONS, vec![3]),
(BDB_LFP_BACKLIGHT, {
let mut data = vec![6];
data.extend([2, 0x10, 0x27, 0, 0, 0].repeat(16));
data
}),
],
);
let panel = super::panel(&old).unwrap();
assert_eq!(
panel.backlight,
Some(Backlight::Pwm {
method: 2,
controller: 0,
hertz: 10000,
active_low: false,
})
);
assert_eq!(panel.power_sequence, None);
assert_eq!(
alloc::format!("{panel}"),
"BDB 190: panel entry 3; backlight by the display's own PWM (method 2, controller \
0) at 10000 Hz; no eDP block: the registers' delays, or the eDP specification's \
where they read 0"
);
// An entry type other than PWM: no backlight at all.
let unlit = with_blocks(
240,
&[
(BDB_LFP_OPTIONS, vec![0]),
(BDB_LFP_BACKLIGHT, {
let mut data = vec![6];
data.extend([1, 0, 0, 0, 0, 0].repeat(16));
data
}),
],
);
let panel = super::panel(&unlit).unwrap();
assert_eq!(panel.backlight, Some(Backlight::NoPwm(1)));
assert!(
alloc::format!("{panel}")
.contains("no PWM backlight (type 1): the display code registers no backlight")
);
let by_edid = with_blocks(240, &[(BDB_LFP_OPTIONS, vec![255])]);
let panel = super::panel(&by_edid).unwrap();
assert_eq!((panel.panel_type, panel.backlight), (None, None));
assert_eq!(
alloc::format!("{panel}"),
"BDB 240: panel entry chosen by the panel's EDID (0 where none matches)"
);
// An entry past 15, or no options block, is the fallback's entry 0.
for vbt in [
with_blocks(240, &[(BDB_LFP_OPTIONS, vec![16])]),
with_blocks(240, &[]),
] {
let panel = super::panel(&vbt).unwrap();
assert_eq!((panel.panel_type, panel.fallback), (Some(0), true));
assert!(alloc::format!("{panel}").starts_with(
"BDB 240: panel entry 0, the display code's fallback, as the table names no \
valid one; no backlight block"
));
}
let mut broken = by_edid.clone();
broken[48] = b'X';
assert_eq!(super::panel(&broken), None);
// A block that claims more than the table holds ends the walk.
let mut short = with_blocks(240, &[(BDB_LFP_OPTIONS, vec![1])]);
let last = short.len() - 2;
short[last] = 0xff;
let panel = super::panel(&short).unwrap();
assert_eq!((panel.panel_type, panel.fallback), (Some(0), true));
}
}
File diff suppressed because it is too large. Load diff
+111 -1
View File
@@ -36,6 +36,10 @@ pub enum Error {
NativeCoreCapacity,
DuplicateGuestPes,
GuestPeCount,
CodeWindow,
DuplicateCodeWindow,
TimerDelay,
DuplicateTimerDelay,
DisplaySize,
MissingRestoreSource,
DuplicateRestoreSource,
@@ -45,6 +49,8 @@ pub enum Error {
DuplicateInstallMedium,
MissingInstallSource,
DuplicateInstallSource,
MediumReadAhead,
DuplicateMediumReadAhead,
MissingRestoreIdentity,
RestoreIdentityCapacity,
DuplicateRestoreIdentity,
@@ -55,8 +61,14 @@ pub enum Error {
DuplicateWifi,
MissingWifiKey,
DuplicateWifiKey,
MissingWifiPrefer,
DuplicateWifiPrefer,
WifiCountry,
DuplicateWifiCountry,
Trackpad,
DuplicateTrackpad,
DuplicateBattery,
TestBattery,
Usb4Approve,
DuplicateUsb4Approve,
Ipv4,
@@ -66,6 +78,32 @@ pub enum Error {
Dns,
DuplicateDns,
DuplicateAudioCheck,
Lid,
DuplicateLid,
Laptop,
DuplicateLaptop,
HybridScanout,
DuplicateHybridScanout,
AsusMode,
DuplicateAsusMode,
TlbiKeep,
DuplicateTlbiKeep,
ShareAliases,
DuplicateShareAliases,
DuplicateTlbiVerifyCheck,
HostCore,
DuplicateHostCore,
GpuAspm,
DuplicateGpuAspm,
Tier2,
DuplicateTier2,
Tier2CheckOff,
PackPreload,
DuplicatePackPreload,
HostCursor,
DuplicateHostCursor,
I915Guc,
DuplicateI915Guc,
DuplicateAudioHpet,
DuplicateNativePciIoapic,
MissingAudioMode,
@@ -99,6 +137,10 @@ pub enum Error {
WifiNetwork,
DuplicateNativeShared,
DuplicateNativeBootstrap,
AmxNative,
DuplicateAmxNative,
DuplicateHle,
HleId,
Constraint(Constraint),
Target {
argument: TargetArgument,
@@ -123,6 +165,7 @@ pub enum Constraint {
WifiDependency,
Ipv4Gateway,
InstallSourceDependency,
MediumReadAheadDependency,
InstallConfiguration,
UpdateDependency,
DevelopmentRestore,
@@ -134,6 +177,9 @@ pub enum Constraint {
DramAlignment,
AudioHpetDependency,
NativePciIoapicExclusive,
LidSleepDependency,
TrackpadDependency,
CoreTrial,
}
impl Error {
/// The established stela.cfg diagnostic at presentation-only callers.
@@ -156,6 +202,12 @@ impl Error {
}
Self::DuplicateGuestPes => "--guest-pes must occur once",
Self::GuestPeCount => "--guest-pes needs a processor count",
Self::CodeWindow => {
"--code-window needs MiB in steps of 16, from 64 to 2048, such as 1536"
}
Self::DuplicateCodeWindow => "--code-window must occur once",
Self::TimerDelay => "--timer-delay-us needs microseconds from 100 to 100000",
Self::DuplicateTimerDelay => "--timer-delay-us must occur once",
Self::DisplaySize => "--display-size needs WIDTHxHEIGHT, such as 1920x1080",
Self::MissingRestoreSource => "missing restore source partition",
Self::DuplicateRestoreSource => "duplicate restore source",
@@ -165,6 +217,10 @@ impl Error {
Self::DuplicateInstallMedium => "duplicate install medium",
Self::MissingInstallSource => "missing install medium partition",
Self::DuplicateInstallSource => "duplicate install medium partition",
Self::MediumReadAhead => {
"--medium-read-ahead needs a count of 1 MiB chunks from 0 to 16"
}
Self::DuplicateMediumReadAhead => "--medium-read-ahead must occur once",
Self::MissingRestoreIdentity => "missing restore identity index",
Self::RestoreIdentityCapacity => "restore identity too large",
Self::DuplicateRestoreIdentity => "duplicate restore identity",
@@ -175,8 +231,16 @@ impl Error {
Self::DuplicateWifi => "duplicate --wifi",
Self::MissingWifiKey => "--wifi-key needs an ESP path",
Self::DuplicateWifiKey => "duplicate --wifi-key",
Self::MissingWifiPrefer => "--wifi-prefer needs a network name",
Self::DuplicateWifiPrefer => "duplicate --wifi-prefer",
Self::WifiCountry => "--wifi-country needs a two-letter country",
Self::DuplicateWifiCountry => "duplicate --wifi-country",
Self::Trackpad => "--trackpad takes mt2 or builtin",
Self::DuplicateTrackpad => "duplicate --trackpad",
Self::DuplicateBattery => "duplicate --battery or --test-battery",
Self::TestBattery => {
"--test-battery needs PERCENT,STATE: 1 to 100, then charging, discharging (at 5 or more) or full (at 100 only)"
}
Self::Usb4Approve => "--usb4-approve needs a device UUID",
Self::DuplicateUsb4Approve => "duplicate --usb4-approve",
Self::Ipv4 => "--ipv4 needs a host ADDRESS/PREFIX, such as 192.168.1.20/24",
@@ -186,6 +250,32 @@ impl Error {
Self::Dns => "--dns needs 1 to 3 distinct server addresses separated by commas",
Self::DuplicateDns => "duplicate --dns",
Self::DuplicateAudioCheck => "duplicate audio check",
Self::Lid => "--lid takes ignore or method",
Self::DuplicateLid => "duplicate --lid",
Self::Laptop => "--laptop takes auto or off",
Self::DuplicateLaptop => "duplicate --laptop",
Self::HybridScanout => "--hybrid-scanout takes on or off",
Self::DuplicateHybridScanout => "duplicate --hybrid-scanout",
Self::AsusMode => "--asus-mode takes performance, turbo, silent or off",
Self::DuplicateAsusMode => "duplicate --asus-mode",
Self::TlbiKeep => "--tlbi-keep takes on or off",
Self::DuplicateTlbiKeep => "duplicate --tlbi-keep",
Self::ShareAliases => "--share-aliases takes on or off",
Self::DuplicateShareAliases => "duplicate --share-aliases",
Self::DuplicateTlbiVerifyCheck => "duplicate --tlbi-verify-check",
Self::HostCore => "--host-core takes on or off",
Self::DuplicateHostCore => "duplicate --host-core",
Self::GpuAspm => "--gpu-aspm takes off or firmware",
Self::DuplicateGpuAspm => "duplicate --gpu-aspm",
Self::Tier2 => "--tier2 takes on or off",
Self::DuplicateTier2 => "duplicate --tier2",
Self::Tier2CheckOff => "--tier2-check runs tier 2, which --tier2 off turns off",
Self::PackPreload => "--pack-preload takes on or off",
Self::DuplicatePackPreload => "duplicate --pack-preload",
Self::HostCursor => "--host-cursor takes on or off",
Self::DuplicateHostCursor => "duplicate --host-cursor",
Self::I915Guc => "--i915-guc takes auto, off or on",
Self::DuplicateI915Guc => "duplicate --i915-guc",
Self::DuplicateAudioHpet => "duplicate audio HPET handoff",
Self::DuplicateNativePciIoapic => "duplicate native PCI IOAPIC handoff",
Self::MissingAudioMode => "missing audio check mode",
@@ -221,6 +311,14 @@ impl Error {
Self::WifiNetwork => "--wifi needs a 1 to 32 byte network name, with %XX escapes",
Self::DuplicateNativeShared => "duplicate native shared check",
Self::DuplicateNativeBootstrap => "duplicate native bootstrap check",
Self::AmxNative => {
"--amx-native takes on, off, or off: and AMX register operations such as fma32,vecfp"
}
Self::DuplicateAmxNative => "duplicate --amx-native",
Self::DuplicateHle => "--hle and --hle-off each occur once",
Self::HleId => {
"--hle-off needs distinct routines separated by commas: memmove, bzero, memset, memcmp or strlen"
}
Self::Constraint(rule) => rule.message(),
Self::Target { source, .. } | Self::Guid { source, .. } => source,
Self::BootCommandOrigin { source, .. } => source,
@@ -235,11 +333,14 @@ impl Constraint {
"--restore-study requires --bundle, --storage, --restore-source, --restore-manifest and --restore-identity; refuses --preboot/--survey"
}
Self::UnexpectedRestoreInputs => "restore inputs require explicit --restore-study",
Self::WifiDependency => "--wifi-key and --wifi-country configure a --wifi network",
Self::WifiDependency => {
"--wifi-key, --wifi-country and --wifi-prefer configure a --wifi network"
}
Self::Ipv4Gateway => "--ipv4-gateway needs --ipv4 and another address of its subnet",
Self::InstallSourceDependency => {
"--install-source names the partition of an --install medium"
}
Self::MediumReadAheadDependency => "--medium-read-ahead applies to --install",
Self::InstallConfiguration => {
"--install requires --bundle, --storage and --nor; refuses --restore-study, --preboot and --survey"
}
@@ -262,6 +363,15 @@ impl Constraint {
Self::NativePciIoapicExclusive => {
"--native-pci-own-ioapic requires the normal system platform path"
}
Self::LidSleepDependency => "--lid-sleep requires --lid method",
Self::TrackpadDependency => {
"--trackpad needs --input: the trackpad sits on the native keyboard and pointer's hub"
}
Self::CoreTrial => {
"--core-trial writes nothing: it needs --bundle, --storage-ram and --native-cores, and \
refuses --storage, --nor, --preboot, --install, --restore-study, --external-disks, \
--usb-storage and --wifi, each of which can write a disk"
}
}
}
}
+197
View File
@@ -36,9 +36,139 @@ impl ParseState<'_> {
"--parallel" => options.parallel = true,
"--serialized" => options.parallel = false,
"--profile" => options.profile = true,
"--lid-sleep" => options.lid_sleep = true,
"--brightness-keys" => options.brightness_keys = true,
ACPI_HARDWARE => options.acpi_hardware = true,
HOST_CORE => {
let on = match value() {
Some("on") => true,
Some("off") => false,
_ => return Err(Error::HostCore),
};
if options.host_core.replace(on).is_some() {
return Err(Error::DuplicateHostCore);
}
}
KEEP_RUNNING_ON_PANIC => options.keep_running_on_panic = true,
TLBI_KEEP => {
let keep = match value() {
Some("on") => true,
Some("off") => false,
_ => return Err(Error::TlbiKeep),
};
if options.tlbi_keep.replace(keep).is_some() {
return Err(Error::DuplicateTlbiKeep);
}
}
SHARE_ALIASES => {
let on = match value() {
Some("on") => true,
Some("off") => false,
_ => return Err(Error::ShareAliases),
};
if options.share_aliases.replace(on).is_some() {
return Err(Error::DuplicateShareAliases);
}
}
I915_GUC => {
let setting = value()
.and_then(crate::intel_guc::Setting::parse)
.ok_or(Error::I915Guc)?;
if options.i915_guc.replace(setting).is_some() {
return Err(Error::DuplicateI915Guc);
}
}
TLBI_VERIFY_CHECK => flag(
&mut options.tlbi_verify_check,
Error::DuplicateTlbiVerifyCheck,
)?,
CORE_TRIAL => options.core_trial = true,
TIER2 => {
let on = match value().ok_or(Error::Tier2)? {
"on" => true,
"off" => false,
_ => return Err(Error::Tier2),
};
if options.tier2.replace(on).is_some() {
return Err(Error::DuplicateTier2);
}
}
TIER2_CHECK => options.tier2_check = true,
PACK_PRELOAD => {
let on = match value().ok_or(Error::PackPreload)? {
"on" => true,
"off" => false,
_ => return Err(Error::PackPreload),
};
if options.pack_preload.replace(on).is_some() {
return Err(Error::DuplicatePackPreload);
}
}
HOST_CURSOR => {
let on = match value().ok_or(Error::HostCursor)? {
"on" => true,
"off" => false,
_ => return Err(Error::HostCursor),
};
if options.host_cursor.replace(on).is_some() {
return Err(Error::DuplicateHostCursor);
}
}
"--lid" => {
if options.lid.is_some() {
return Err(Error::DuplicateLid);
}
options.lid = Some(Lid::parse(value().ok_or(Error::Lid)?)?);
}
LAPTOP => {
let laptop = Laptop::parse(value().ok_or(Error::Laptop)?)?;
if options.laptop.replace(laptop).is_some() {
return Err(Error::DuplicateLaptop);
}
}
HYBRID_SCANOUT => {
let on = match value().ok_or(Error::HybridScanout)? {
"on" => true,
"off" => false,
_ => return Err(Error::HybridScanout),
};
if options.hybrid_scanout.replace(on).is_some() {
return Err(Error::DuplicateHybridScanout);
}
}
ASUS_MODE => {
let mode = AsusMode::parse(value().ok_or(Error::AsusMode)?)?;
if options.asus_mode.replace(mode).is_some() {
return Err(Error::DuplicateAsusMode);
}
}
GPU_ASPM => {
let aspm = GpuAspm::parse(value().ok_or(Error::GpuAspm)?)?;
if options.gpu_aspm.replace(aspm).is_some() {
return Err(Error::DuplicateGpuAspm);
}
}
AMX_NATIVE => {
let model = value().and_then(AmxModel::parse).ok_or(Error::AmxNative)?;
if options.amx_native.replace(model).is_some() {
return Err(Error::DuplicateAmxNative);
}
}
"--hle" => flag(&mut options.hle, Error::DuplicateHle)?,
"--hle-off" => {
// A list is never empty, so an empty one is none yet.
if !options.hle_off.is_empty() {
return Err(Error::DuplicateHle);
}
options.hle_off = hle_routines(value().ok_or(Error::HleId)?)?;
}
"--cpu-balanced" => options.cpu_balanced = true,
"--panel-backlight" => options.panel_backlight = true,
MAINTENANCE_WRITE => options.maintenance_write = true,
SINGLE_USER => options.single_user = true,
SCANOUT_MIRROR => options.scanout_mirror = true,
GPU_STRICT_FAMILIES => options.gpu_strict_families = true,
INTEL_CCS => options.intel_ccs = true,
"--monitor-trace" => options.monitor_trace = true,
"--display-trace" => options.display_trace = true,
"--native-shared-check" => flag(
@@ -75,6 +205,22 @@ impl ParseState<'_> {
}
options.guest_pes = Some(count);
}
CODE_WINDOW => {
use crate::native_resources::{CODE_ALIGNMENT, MAX_WINDOW, MIN_WINDOW};
if options.code_window.is_some() {
return Err(Error::DuplicateCodeWindow);
}
let mib = value()
.and_then(|word| word.parse::<u64>().ok())
.ok_or(Error::CodeWindow)?;
let bytes = mib.saturating_mul(1 << 20);
if !(MIN_WINDOW..=MAX_WINDOW).contains(&bytes)
|| !bytes.is_multiple_of(CODE_ALIGNMENT)
{
return Err(Error::CodeWindow);
}
options.code_window = Some(mib);
}
DISPLAY_SIZE => {
let size = value().ok_or(Error::DisplaySize)?;
let (width, height) = size.split_once('x').ok_or(Error::DisplaySize)?;
@@ -124,6 +270,16 @@ impl ParseState<'_> {
return Err(Error::DuplicateInstallSource);
}
}
MEDIUM_READ_AHEAD => {
let chunks = value()
.and_then(|value| number(value).ok())
.and_then(|chunks| usize::try_from(chunks).ok())
.filter(|&chunks| chunks <= MAX_MEDIUM_READ_AHEAD)
.ok_or(Error::MediumReadAhead)?;
if options.medium_read_ahead.replace(chunks).is_some() {
return Err(Error::DuplicateMediumReadAhead);
}
}
"--restore-identity" => {
let index = number(value().ok_or(Error::MissingRestoreIdentity)?)?;
let index = usize::try_from(index).map_err(|_| Error::RestoreIdentityCapacity)?;
@@ -141,7 +297,26 @@ impl ParseState<'_> {
UPDATE_RESTORE => options.update_restore = true,
"--development-restore" => options.development_restore = true,
"--idle-skip" => options.idle_skip = true,
NO_IBPB => options.no_ibpb = true,
TIMER_DELAY => {
if options.timer_delay.is_some() {
return Err(Error::DuplicateTimerDelay);
}
let micros = value()
.and_then(|word| word.parse::<u64>().ok())
.filter(|micros| TIMER_DELAY_MICROS.contains(micros))
.ok_or(Error::TimerDelay)?;
options.timer_delay = Some(micros);
}
"--input" => options.input = true,
TRACKPAD => {
let kind = GuestTrackpad::parse(value().ok_or(Error::Trackpad)?)?;
if options.trackpad.replace(kind).is_some() {
return Err(Error::DuplicateTrackpad);
}
}
BLUETOOTH_TRACE => options.bluetooth_trace = true,
BLUETOOTH_LEND => options.bluetooth_lend = true,
"--usb-storage" => {
let serial = value().ok_or(Error::MissingUsbStorage)?;
if options.usb_storage.iter().any(|other| other == serial) {
@@ -150,12 +325,31 @@ impl ParseState<'_> {
options.usb_storage.push(String::from(serial));
}
"--guest-network" => options.guest_network = true,
BATTERY => {
if options.battery.replace(Battery::Host).is_some() {
return Err(Error::DuplicateBattery);
}
}
TEST_BATTERY => {
let battery = value()
.and_then(Battery::parse_test)
.ok_or(Error::TestBattery)?;
if options.battery.replace(battery).is_some() {
return Err(Error::DuplicateBattery);
}
}
WIFI => {
let ssid = ssid(value().ok_or(Error::MissingWifiNetwork)?)?;
if options.ssid.replace(ssid).is_some() {
return Err(Error::DuplicateWifi);
}
}
WIFI_PREFER => {
let ssid = ssid(value().ok_or(Error::MissingWifiPrefer)?)?;
if options.wifi_prefer.replace(ssid).is_some() {
return Err(Error::DuplicateWifiPrefer);
}
}
WIFI_KEY => {
let path = value().ok_or(Error::MissingWifiKey)?;
if options.wifi_key.replace(String::from(path)).is_some() {
@@ -324,6 +518,9 @@ impl ParseState<'_> {
if options.native_rounds || options.native_shared_check || options.native_bootstrap_check {
options.parallel = false;
}
if options.tier2_check && options.tier2 == Some(false) {
return Err(Error::Tier2CheckOff);
}
if options.ssid.is_some() && options.wifi_key.is_none() {
options.wifi_key = Some(String::from(DEFAULT_WIFI_KEY));
}
+867 -1
View File
@@ -1,5 +1,259 @@
use super::*;
#[test]
fn the_lid_is_ignored_unless_asked_and_its_sleep_needs_the_method() {
// The default does nothing with the lid, and writes nothing.
let plain = System::parse("--system").unwrap();
assert_eq!(plain.lid(), Lid::Ignore);
assert_eq!(plain.to_string(), "--system");
for (text, lid) in [
("--system --lid ignore", Lid::Ignore),
("--system --lid method", Lid::Method),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.lid(), lid);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --lid", Error::Lid),
("--system --lid close", Error::Lid),
("--system --lid method --lid ignore", Error::DuplicateLid),
(
"--system --lid-sleep",
Error::Constraint(Constraint::LidSleepDependency),
),
(
"--system --lid ignore --lid-sleep",
Error::Constraint(Constraint::LidSleepDependency),
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
assert!(System::parse("--system --lid method --lid-sleep").is_ok());
}
#[test]
fn a_laptop_takes_its_features_unless_laptop_off_and_the_option_round_trips() {
// The default is auto, and writes nothing.
let plain = System::parse("--system").unwrap();
assert_eq!(plain.laptop(), Laptop::Auto);
assert_eq!(plain.laptop, None);
for (text, laptop) in [
("--system --laptop auto", Laptop::Auto),
("--system --laptop off", Laptop::Off),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.laptop(), laptop);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --laptop", Error::Laptop),
("--system --laptop on", Error::Laptop),
(
"--system --laptop off --laptop auto",
Error::DuplicateLaptop,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
// `--host-core`: off unless given, each value kept as written.
assert!(!plain.host_core());
assert_eq!(plain.host_core, None);
for (text, on) in [
("--system --host-core on", true),
("--system --host-core off", false),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.host_core(), on);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --host-core", Error::HostCore),
("--system --host-core yes", Error::HostCore),
(
"--system --host-core on --host-core off",
Error::DuplicateHostCore,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
// `off` beside the opt-ins it leaves: each still parses as before.
let given =
System::parse("--system --laptop off --battery --lid method --brightness-keys").unwrap();
assert_eq!(given.battery, Some(Battery::Host));
assert_eq!(given.lid(), Lid::Method);
assert!(given.brightness_keys);
}
#[test]
fn i915_guc_takes_auto_off_or_on_and_the_option_round_trips() {
use crate::intel_guc::Setting;
let plain = System::parse("--system").unwrap();
assert_eq!(plain.i915_guc, None);
assert_eq!(plain.i915_guc(), Setting::Auto);
assert_eq!(plain.to_string(), "--system");
for (text, setting) in [
("--system --i915-guc auto", Setting::Auto),
("--system --i915-guc off", Setting::Off),
("--system --i915-guc on", Setting::On),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.i915_guc(), setting);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --i915-guc", Error::I915Guc),
("--system --i915-guc ON", Error::I915Guc),
(
"--system --i915-guc auto --i915-guc off",
Error::DuplicateI915Guc,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn a_hybrid_laptops_panel_is_copied_by_the_cpu_unless_hybrid_scanout_is_on() {
let plain = System::parse("--system").unwrap();
assert!(!plain.hybrid_scanout());
assert_eq!(plain.hybrid_scanout, None);
assert_eq!(plain.to_string(), "--system");
for (text, on) in [
("--system --hybrid-scanout on", true),
("--system --hybrid-scanout off", false),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.hybrid_scanout(), on);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --hybrid-scanout", Error::HybridScanout),
("--system --hybrid-scanout yes", Error::HybridScanout),
(
"--system --hybrid-scanout on --hybrid-scanout off",
Error::DuplicateHybridScanout,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn an_asus_laptop_runs_in_performance_unless_asus_mode_says_otherwise() {
// The default is performance, and writes nothing.
let plain = System::parse("--system").unwrap();
assert_eq!(plain.asus_mode(), AsusMode::Performance);
assert_eq!(plain.asus_mode, None);
assert_eq!(plain.to_string(), "--system");
for (text, mode) in [
("--system --asus-mode performance", AsusMode::Performance),
("--system --asus-mode turbo", AsusMode::Turbo),
("--system --asus-mode silent", AsusMode::Silent),
("--system --asus-mode off", AsusMode::Off),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.asus_mode(), mode);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --asus-mode", Error::AsusMode),
("--system --asus-mode balanced", Error::AsusMode),
(
"--system --asus-mode off --asus-mode turbo",
Error::DuplicateAsusMode,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn sharing_aliases_is_off_unless_asked_for() {
let plain = System::parse("--system").unwrap();
assert!(!plain.share_aliases());
for (text, on) in [
("--system --share-aliases on", true),
("--system --share-aliases off", false),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.share_aliases(), on, "{text}");
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --share-aliases", Error::ShareAliases),
("--system --share-aliases yes", Error::ShareAliases),
(
"--system --share-aliases on --share-aliases off",
Error::DuplicateShareAliases,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn the_tlbi_keep_is_off_unless_asked_for_and_its_check_needs_it() {
let plain = System::parse("--system").unwrap();
assert_eq!(plain.tlbi_keep(), (false, false));
assert_eq!(plain.to_string(), "--system");
for (text, keep) in [
("--system --tlbi-keep on", (true, false)),
("--system --tlbi-keep off", (false, false)),
("--system --tlbi-keep on --tlbi-verify-check", (true, true)),
(
"--system --tlbi-keep off --tlbi-verify-check",
(false, false),
),
("--system --tlbi-verify-check", (false, false)),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.tlbi_keep(), keep, "{text}");
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --tlbi-keep", Error::TlbiKeep),
("--system --tlbi-keep yes", Error::TlbiKeep),
(
"--system --tlbi-keep on --tlbi-keep off",
Error::DuplicateTlbiKeep,
),
(
"--system --tlbi-verify-check --tlbi-verify-check",
Error::DuplicateTlbiVerifyCheck,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn a_gpu_link_keeps_the_firmwares_aspm_unless_gpu_aspm_turns_it_off() {
let plain = System::parse("--system").unwrap();
assert_eq!(plain.gpu_aspm(), GpuAspm::Firmware);
assert_eq!(plain.gpu_aspm, None);
assert_eq!(plain.to_string(), "--system");
for (text, aspm) in [
("--system --gpu-aspm off", GpuAspm::Off),
("--system --gpu-aspm firmware", GpuAspm::Firmware),
("--system --acpi-hardware --gpu-aspm off", GpuAspm::Off),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.gpu_aspm(), aspm);
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --gpu-aspm", Error::GpuAspm),
("--system --gpu-aspm on", Error::GpuAspm),
(
"--system --gpu-aspm off --gpu-aspm off",
Error::DuplicateGpuAspm,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn audio_hpet_handoff_requires_an_audio_diagnostic() {
assert_eq!(
@@ -25,6 +279,60 @@ fn native_pci_ioapic_handoff_round_trips_and_refuses_diagnostic_paths() {
use alloc::{format, string::ToString, vec};
#[test]
fn the_trackpad_is_cabled_only_beside_host_input() {
// The disk-port count and the cabling both read this: no port is kept
// for a trackpad there is no host input to cable.
let cabled = System {
input: true,
trackpad: Some(GuestTrackpad::Mt2),
..System::default()
};
assert_eq!(cabled.guest_trackpad(), Some(GuestTrackpad::Mt2));
let no_input = System {
input: false,
..cabled.clone()
};
assert_eq!(no_input.guest_trackpad(), None);
let no_flag = System {
trackpad: None,
..cabled
};
assert_eq!(no_flag.guest_trackpad(), None);
}
#[test]
fn options_round_trip_trackpad() {
for (word, kind) in [
("mt2", GuestTrackpad::Mt2),
("builtin", GuestTrackpad::Builtin),
] {
let text = format!("--system --input --trackpad {word}");
let options = System::parse(&text).unwrap();
assert_eq!(options.trackpad, Some(kind));
assert_eq!(options.to_string(), text);
assert_eq!(System::parse(&options.to_string()), Ok(options));
}
// Without the flag: no trackpad, and the line has no word for it.
let plain = System::parse("--system --input").unwrap();
assert_eq!(plain.trackpad, None);
assert_eq!(plain.to_string(), "--system --input");
for (text, error) in [
("--system --input --trackpad nope", Error::Trackpad),
("--system --input --trackpad", Error::Trackpad),
(
"--system --input --trackpad mt2 --trackpad builtin",
Error::DuplicateTrackpad,
),
(
"--system --trackpad mt2",
Error::Constraint(Constraint::TrackpadDependency),
),
] {
assert_eq!(System::parse(text).unwrap_err(), error, "{text}");
}
}
#[test]
fn diagnostic_options_are_typed() {
for text in ["--system", "--system --wifi --audio-own-hpet"] {
@@ -55,15 +363,44 @@ fn host_check_lines_round_trip_and_refuse_bad_values() {
assert_eq!(HostCheck::parse("--host-check"), Ok(HostCheck::default()));
for text in [
"--system",
"--host-check --bluetooth-check=1",
"--host-check --bluetooth-check on",
"--host-check --native-dma-check",
"--host-check --deadline 0",
"--host-check --nor-file x",
"--host-check --unknown",
"--host-check --keep-lines=1",
"--host-check --keep-lines 1",
] {
assert!(HostCheck::parse(text).is_err(), "{text}");
}
}
#[test]
fn host_check_keep_lines_is_off_unless_named_and_round_trips() {
assert!(!HostCheck::parse("--host-check").unwrap().keep_lines);
assert!(
!HostCheck::parse("--host-check --deadline 30")
.unwrap()
.keep_lines
);
let options = HostCheck::parse("--host-check --keep-lines --deadline 600").unwrap();
assert!(options.keep_lines);
assert_eq!(options.deadline, Some(600));
assert_eq!(
options.to_string(),
"--host-check --deadline 600 --keep-lines"
);
assert_eq!(HostCheck::parse(&options.to_string()), Ok(options));
assert_eq!(
HostCheck::parse("--host-check --keep-lines --keep-lines").unwrap(),
HostCheck {
keep_lines: true,
..HostCheck::default()
}
);
}
const DISK: &str = "74EXN0LI:11111111-2222-3333-4444-555555555555";
fn round_trip(text: &str) -> System {
@@ -131,12 +468,77 @@ fn no_boot_that_starts_metal_clients_sees_the_agx_model_and_restore_ramdisks_kee
}
}
#[test]
fn an_install_a_restore_a_staged_update_a_recovery_os_and_a_repair_get_no_battery() {
use stela_loader::boot_selection::{
BUNDLE_REPAIR_OPTION, PAIRED_RECOVERY_OPTION, SAFE_BOOT_OPTION, SYSTEM_RECOVERY_OPTION,
UPGRADE_OPTION,
};
let withheld = |line: &str| round_trip(line).battery_withheld(false);
// The installed macOS takes the battery, in single-user and safe mode
// too.
for flag in ["", SINGLE_USER, SAFE_BOOT_OPTION] {
let line = format!("--system --battery --preboot {DISK} {flag}");
assert_eq!(withheld(&line), None, "{line}");
}
// A staged update runs the restore ramdisk; a recoveryOS and the repair
// mend the installed system.
for (flag, boot) in [
(UPGRADE_OPTION, "a staged macOS update"),
(PAIRED_RECOVERY_OPTION, "recoveryOS"),
(SYSTEM_RECOVERY_OPTION, "recoveryOS"),
(BUNDLE_REPAIR_OPTION, "the Metal plugin repair"),
] {
let line = format!("--system --battery --preboot {DISK} {flag}");
assert_eq!(withheld(&line), Some(boot), "{line}");
}
// An install and a restore study, by their options or by the restore the
// engine runs.
let install = format!(
"--system --test-battery 80,charging --storage {DISK} --nor {DISK} --bundle b \
--install p.json"
);
let study = format!(
"--system --battery --bundle b --storage {DISK} --restore-study --restore-source {DISK} \
--restore-manifest m.plist --restore-identity 2"
);
for line in [install, study] {
assert_eq!(withheld(&line), Some("the macOS installer"), "{line}");
}
let plain = round_trip("--system --battery");
assert_eq!(plain.battery_withheld(false), None);
assert_eq!(plain.battery_withheld(true), Some("the macOS installer"));
}
#[test]
fn scanout_mirror_round_trips() {
assert!(!round_trip("--system").scanout_mirror);
assert!(round_trip(&format!("--system {SCANOUT_MIRROR}")).scanout_mirror);
}
#[test]
fn strict_gpu_families_round_trip_and_are_off_unless_written() {
let plain = round_trip("--system");
assert!(!plain.gpu_strict_families);
assert!(!plain.to_string().contains(GPU_STRICT_FAMILIES));
let strict = round_trip(&format!("--system {GPU_STRICT_FAMILIES}"));
assert!(strict.gpu_strict_families);
assert!(strict.to_string().contains(GPU_STRICT_FAMILIES));
}
#[test]
fn intel_ccs_round_trips_and_is_off_unless_written() {
let plain = round_trip("--system");
assert!(!plain.intel_ccs);
assert!(!plain.to_string().contains(INTEL_CCS));
let kept = round_trip(&format!("--system {INTEL_CCS}"));
assert!(kept.intel_ccs);
assert!(kept.to_string().contains(INTEL_CCS));
assert!(intel_ccs_line(false).contains("INTEL_DEBUG=noccs"));
assert!(intel_ccs_line(false).contains(INTEL_CCS));
assert!(intel_ccs_line(true).contains(INTEL_CCS));
}
#[test]
fn maintenance_writes_require_an_explicit_preboot_selection() {
let ordinary = round_trip(&format!("--system --preboot {DISK}"));
@@ -175,13 +577,57 @@ fn chosen_disk_round_trips_and_the_mount_refuses_it_unreplaced() {
assert!(System::parse_resolved(&resolved).is_ok());
}
/// `--medium-read-ahead` takes the install medium's read-ahead in 1 MiB
/// chunks, 0 (read only when asked) to [`MAX_MEDIUM_READ_AHEAD`], once, for
/// an `--install`; without it the engine takes its own default.
#[test]
fn the_medium_read_ahead_is_a_chunk_count_for_an_install() {
let install = format!("--system --storage {DISK} --nor {DISK} --bundle b --install p.json");
assert_eq!(System::parse(&install).unwrap().medium_read_ahead, None);
for chunks in [0, 4, MAX_MEDIUM_READ_AHEAD] {
let options = round_trip(&format!("{install} {MEDIUM_READ_AHEAD} {chunks}"));
assert_eq!(options.medium_read_ahead, Some(chunks));
}
let past = MAX_MEDIUM_READ_AHEAD + 1;
for (text, error) in [
(
format!("{install} {MEDIUM_READ_AHEAD} {past}"),
Error::MediumReadAhead,
),
(
format!("{install} {MEDIUM_READ_AHEAD}"),
Error::MediumReadAhead,
),
(
format!("{install} {MEDIUM_READ_AHEAD} -1"),
Error::MediumReadAhead,
),
(
format!("{install} {MEDIUM_READ_AHEAD} abc"),
Error::MediumReadAhead,
),
(
format!("{install} {MEDIUM_READ_AHEAD} 1 {MEDIUM_READ_AHEAD} 2"),
Error::DuplicateMediumReadAhead,
),
(
format!("--system {MEDIUM_READ_AHEAD} 2"),
Error::Constraint(Constraint::MediumReadAheadDependency),
),
] {
assert_eq!(System::parse(&text).unwrap_err(), error, "{text}");
}
}
#[test]
fn every_option_survives_a_round_trip() {
let options = round_trip(&format!(
"--system --storage {DISK} --nor {DISK} --bundle b --install p.json \
--install-source 11111111-2222-3333-4444-555555555555 --verify-on-read \
--usb-storage A --usb-storage B --input --idle-skip --sep-observe --native-cores 3 \
--native-artifacts --serialized --profile --monitor-trace --display-trace \
--native-artifacts --serialized --profile --lid method --lid-sleep --brightness-keys \
--acpi-hardware --keep-running-on-panic --tier2 on --tier2-check --amx-native off \n --hle --hle-off bzero \n --monitor-trace \
--display-trace \
--network-check http://h/p --audio-check transport-duplex --audio-own-hpet --dram-base 0x10000000000 \
--load 0x10000004000 --entry 0x10000008000 --x0 7 --budget 99 --break 0x10 \
--trace 0x20 --watch 0x30,0x40 --dump x21-0x8,0x10 --dump 0x50,0x60"
@@ -191,7 +637,21 @@ fn every_option_survives_a_round_trip() {
assert!(options.audio_own_hpet);
assert!(options.display_trace);
assert!(!System::default().display_trace);
assert!(options.lid_sleep);
assert!(!System::default().lid_sleep);
assert_eq!(options.lid(), Lid::Method);
assert!(options.brightness_keys);
assert!(!System::default().brightness_keys);
assert!(options.acpi_hardware);
assert!(!System::default().acpi_hardware);
assert!(options.keep_running_on_panic);
assert!(!System::default().keep_running_on_panic);
assert_eq!(options.tier2, Some(true));
assert!(options.tier2_check && options.tier2_runs());
assert_eq!(options.amx_model(), AmxModel::ALL);
assert!(!options.parallel);
assert!(options.hle);
assert_eq!(options.hle_off, [stela_engine::hle::Id::Bzero]);
assert_eq!(options.dumps[0], (Base::Register(21, -8), 0x10));
let restore = round_trip(&format!(
"--system --bundle b --storage {DISK} --restore-study --restore-source {DISK} \
@@ -200,6 +660,65 @@ fn every_option_survives_a_round_trip() {
assert_eq!(restore.restore_manifest_path.as_deref(), Some("m.plist"));
}
/// The guest Bluetooth capture is off unless asked for, and survives the
/// line a setup writes.
#[test]
fn the_bluetooth_capture_round_trips_and_is_off_by_default() {
assert!(!System::default().bluetooth_trace);
assert!(!round_trip("--system --input").bluetooth_trace);
let line = format!("--system --storage {DISK} --input {BLUETOOTH_TRACE}");
let options = round_trip(&line);
assert!(options.input && options.bluetooth_trace);
assert_eq!(options.to_string(), line);
assert!(!System::default().to_string().contains("bluetooth"));
}
/// Lending the host's controller is off unless asked for: a line without
/// the flag gives every boot the model, as before.
#[test]
fn the_bluetooth_lend_round_trips_and_is_off_by_default() {
assert!(!System::default().bluetooth_lend);
assert!(!round_trip("--system --input --bluetooth-trace").bluetooth_lend);
let line = format!("--system --storage {DISK} --input {BLUETOOTH_LEND} {BLUETOOTH_TRACE}");
let options = round_trip(&line);
assert!(options.bluetooth_lend && options.bluetooth_trace);
assert_eq!(options.to_string(), line);
}
#[test]
fn hle_flags_round_trip_and_refuse_unknown_ids() {
use stela_engine::hle::Id;
let off = round_trip("--system");
assert!(!off.hle);
assert!(off.hle_off.is_empty());
assert!(round_trip("--system --hle").hle);
let some = round_trip("--system --hle --hle-off memmove,strlen");
assert!(some.hle);
assert_eq!(some.hle_off, [Id::Memmove, Id::Strlen]);
assert_eq!(some.to_string(), "--system --hle --hle-off memmove,strlen");
// Without --hle the list is kept, and turns nothing off.
let alone = round_trip("--system --hle-off bzero,memset,memcmp");
assert!(!alone.hle);
assert_eq!(alone.hle_off, [Id::Bzero, Id::Memset, Id::Memcmp]);
for text in [
"--system --hle-off nosuch",
"--system --hle-off",
"--system --hle-off memmove,",
"--system --hle-off ,memmove",
"--system --hle-off memmove,memmove",
"--system --hle-off bail",
"--system --hle-off Memmove",
] {
assert_eq!(System::parse(text), Err(Error::HleId), "{text}");
}
for text in [
"--system --hle --hle",
"--system --hle-off memmove --hle-off strlen",
] {
assert_eq!(System::parse(text), Err(Error::DuplicateHle), "{text}");
}
}
#[test]
fn usb4_approvals_repeat_and_keep_their_canonical_spelling() {
let first = "446ab8f0-5aff-47c9-8962-5870641e4d61";
@@ -319,6 +838,74 @@ fn native_core_counts_refuse_duplicates_zero_and_over_capacity() {
);
}
/// `--timer-delay-us` bounds how late a busy PE's timer interrupt comes,
/// from 100 us to 100 ms; without it the engine's 10 ms holds.
#[test]
fn a_timer_delay_takes_microseconds_within_its_bounds() {
assert_eq!(System::default().timer_delay, None);
let options = round_trip("--system --timer-delay-us 2000");
assert_eq!(options.timer_delay, Some(2000));
assert_eq!(options.to_string(), "--system --timer-delay-us 2000");
for micros in [100, 10_000, 100_000] {
let line = format!("--system --timer-delay-us {micros}");
assert_eq!(round_trip(&line).timer_delay, Some(micros), "{line}");
}
for (text, error) in [
("--system --timer-delay-us", Error::TimerDelay),
("--system --timer-delay-us x", Error::TimerDelay),
("--system --timer-delay-us 0", Error::TimerDelay),
("--system --timer-delay-us 99", Error::TimerDelay),
("--system --timer-delay-us 100001", Error::TimerDelay),
(
"--system --timer-delay-us 1000 --timer-delay-us 1000",
Error::DuplicateTimerDelay,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
/// `--no-ibpb` drops the prediction barrier at guest context switches; a
/// boot without it isolates as before.
#[test]
fn prediction_isolation_stays_on_unless_no_ibpb_is_given() {
assert!(!System::default().no_ibpb);
assert!(!System::parse("--system").unwrap().no_ibpb);
let options = round_trip("--system --no-ibpb");
assert!(options.no_ibpb);
assert_eq!(options.to_string(), "--system --no-ibpb");
}
/// `--code-window` names the board's code window in MiB: whole 16 MiB
/// steps from 64 MiB to 2 GiB, the window's own bounds, once.
#[test]
fn a_code_window_takes_whole_steps_within_the_windows_bounds() {
let options = round_trip("--system --code-window 1536");
assert_eq!(options.code_window, Some(1536));
assert_eq!(options.to_string(), "--system --code-window 1536");
assert_eq!(System::default().code_window, None);
assert!(!System::default().to_string().contains("--code-window"));
for mib in [64, 784, 2048] {
let line = format!("--system --code-window {mib}");
assert_eq!(round_trip(&line).code_window, Some(mib), "{line}");
}
for (text, error) in [
("--system --code-window", Error::CodeWindow),
("--system --code-window x", Error::CodeWindow),
("--system --code-window 0", Error::CodeWindow),
("--system --code-window 48", Error::CodeWindow),
("--system --code-window 1000", Error::CodeWindow),
("--system --code-window 2064", Error::CodeWindow),
("--system --code-window 0x600", Error::CodeWindow),
(
"--system --code-window 1024 --code-window 1024",
Error::DuplicateCodeWindow,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn guest_pes_bound_the_executors_that_run_them() {
for text in [
@@ -400,6 +987,69 @@ fn invalid_lines_refuse() {
}
}
#[test]
fn the_battery_options_round_trip_and_refuse_a_second_or_a_malformed_one() {
assert_eq!(System::default().battery, None);
assert!(!System::default().to_string().contains("battery"));
assert_eq!(
round_trip("--system --battery").battery,
Some(Battery::Host)
);
assert_eq!(
System::parse("--system --battery").unwrap().to_string(),
"--system --battery"
);
for (text, percent, state) in [
("80,charging", 80, TestState::Charging),
("1,charging", 1, TestState::Charging),
("5,discharging", 5, TestState::Discharging),
("100,full", 100, TestState::Full),
] {
let line = format!("--system {TEST_BATTERY} {text}");
assert_eq!(
round_trip(&line).battery,
Some(Battery::Test { percent, state })
);
assert_eq!(System::parse(&line).unwrap().to_string(), line);
}
for text in [
"--system --battery --battery",
"--system --battery --test-battery 1,charging",
"--system --test-battery 1,charging --battery",
"--system --test-battery 1,charging --test-battery 2,charging",
] {
assert_eq!(
System::parse(text).unwrap_err(),
Error::DuplicateBattery,
"{text}"
);
}
for value in [
"",
"80",
"101,charging",
"-1,charging",
"80,full",
"80,idle",
"80,charging,more",
"80,Charging",
",charging",
// Discharging below 5% the test battery is at or near its 3% low
// capacity: critical at boot, and macOS shuts down.
"4,discharging",
"0,discharging",
// At 0 the SMC takes no battery: macOS shuts down on an empty one.
"0,charging",
] {
let text = format!("--system --test-battery {value}");
assert_eq!(
System::parse(&text).unwrap_err(),
Error::TestBattery,
"{text}"
);
}
}
#[test]
fn numbers_take_decimal_and_separated_hex() {
assert_eq!(number("0x1_0000"), Ok(0x10000));
@@ -411,5 +1061,221 @@ fn numbers_take_decimal_and_separated_hex() {
);
}
#[test]
fn amx_native_is_on_unless_turned_off() {
let default = round_trip("--system");
assert_eq!(default.amx_model(), AmxModel::NONE);
assert!(!default.to_string().contains(AMX_NATIVE));
let off = round_trip(&format!("--system {AMX_NATIVE} off"));
assert_eq!(off.amx_model(), AmxModel::ALL);
assert!(off.to_string().contains("--amx-native off"));
assert_eq!(
round_trip(&format!("--system {AMX_NATIVE} on")).amx_model(),
AmxModel::NONE
);
// Named operations, by number, printed in number order.
let some = round_trip(&format!(
"--system {AMX_NATIVE} off:vecfp,fma16,fms16,fma16"
));
assert_eq!(some.amx_model(), AmxModel(1 << 19 | 1 << 16 | 1 << 15));
assert!(
some.to_string()
.contains("--amx-native off:fma16,fms16,vecfp")
);
for text in [
"--system --amx-native",
"--system --amx-native no",
"--system --amx-native off:",
"--system --amx-native off:fma32,",
"--system --amx-native off:ldx",
"--system --amx-native off:set",
"--system --amx-native off:FMA32",
"--system --amx-native on:fma32",
] {
assert_eq!(System::parse(text), Err(Error::AmxNative), "{text}");
}
assert_eq!(
System::parse("--system --amx-native off --amx-native on"),
Err(Error::DuplicateAmxNative)
);
}
#[test]
fn cpu_balanced_is_a_flag() {
assert!(!System::default().cpu_balanced);
let options = System::parse("--system --cpu-balanced").unwrap();
assert!(options.cpu_balanced);
}
#[test]
fn panel_backlight_is_a_flag() {
assert!(!System::default().panel_backlight);
let options = System::parse("--system --panel-backlight").unwrap();
assert!(options.panel_backlight);
assert!(options.to_string().contains("--panel-backlight"));
}
mod constraints;
mod fork_lines;
mod grammar;
#[test]
fn host_check_bluetooth_check_is_off_unless_named_and_round_trips() {
assert!(!HostCheck::parse("--host-check").unwrap().bluetooth_check);
assert!(
!HostCheck::parse("--host-check --keep-lines")
.unwrap()
.bluetooth_check
);
let options =
HostCheck::parse("--host-check --keep-lines --bluetooth-check --deadline 600").unwrap();
assert!(options.bluetooth_check && options.keep_lines);
assert_eq!(
options.to_string(),
"--host-check --bluetooth-check --deadline 600 --keep-lines"
);
assert_eq!(HostCheck::parse(&options.to_string()), Ok(options));
assert_eq!(
HostCheck::parse("--host-check --bluetooth-check --bluetooth-check").unwrap(),
HostCheck {
bluetooth_check: true,
..HostCheck::default()
}
);
// Without it, the line prints as before.
assert_eq!(
HostCheck::parse("--host-check --key-seconds 5")
.unwrap()
.to_string(),
"--host-check --key-seconds 5"
);
}
#[test]
fn a_core_trial_reaches_no_disk() {
const TRIAL: &str =
"--system --bundle m2u --storage-ram 0x200000000 --native-cores 16 --core-trial";
let options = round_trip(TRIAL);
assert!(options.core_trial);
assert!(!System::default().core_trial);
assert_eq!(options.native_cores, Some(16));
assert!(options.storage.is_none() && options.nor.is_none() && options.preboot.is_none());
// Its order in the canonical line does not matter to the grammar.
assert_eq!(
System::parse(
"--system --core-trial --native-cores 16 --storage-ram 0x200000000 --bundle m2u"
),
Ok(options.clone())
);
// Without the flag nothing changes, and the line has no word for it.
let plain = System::parse("--system --bundle m2u --storage-ram 0x200000000").unwrap();
assert!(!plain.core_trial);
assert!(!plain.to_string().contains(CORE_TRIAL));
let refused = Error::Constraint(Constraint::CoreTrial);
// What it needs: a bundle, RAM-backed disks and an explicit PE count.
for missing in [
"--system --storage-ram 0x200000000 --native-cores 16 --core-trial",
"--system --bundle m2u --native-cores 16 --core-trial",
"--system --bundle m2u --storage-ram 0x200000000 --core-trial",
] {
assert_eq!(System::parse(missing).err(), Some(refused), "{missing}");
}
// Every option that can reach a disk is refused beside it.
for added in [
format!("--nor {DISK}"),
format!("--preboot {DISK}"),
"--external-disks".to_string(),
"--usb-storage A".to_string(),
"--wifi home".to_string(),
] {
let text = format!("{TRIAL} {added}");
assert_eq!(System::parse(&text).err(), Some(refused), "{text}");
}
// `--storage` cannot stand beside `--storage-ram` at all; on its own
// it is refused as the trial's.
let storage = format!("--system --bundle m2u --storage {DISK} --native-cores 16 --core-trial");
assert_eq!(System::parse(&storage).err(), Some(refused), "{storage}");
// An install or a restore study needs `--storage`, so either refusal
// stops it before anything opens.
for text in [
format!(
"--system --bundle m2u --storage {DISK} --nor {DISK} --install p.json \
--native-cores 16 --core-trial"
),
format!(
"--system --bundle m2u --storage {DISK} --restore-study --restore-source {DISK} \
--restore-manifest m.plist --restore-identity 2 --native-cores 16 --core-trial"
),
] {
assert_eq!(System::parse(&text).err(), Some(refused), "{text}");
}
assert!(refused.message().contains("--core-trial writes nothing"));
}
/// The scaling test's boots: a Mac mini M2 disk boot (setup's line, with
/// `--guest-pes 8`) on a 16-core, 32-thread PC, given `--native-cores` 4, 6
/// and 8. Each reserves that many host cores before the Preboot is read,
/// passes the live check against the disk's 8 CPUs, and skips the CPU-count
/// check the count stands in for. Past the board's 8 the boot stops at that
/// check, before any AP starts.
#[test]
fn a_disk_boot_runs_on_four_six_or_eight_native_cores() {
const LAPTOP_THREADS: usize = 32;
const MAC_MINI_CPUS: usize = 8;
let line = format!("--system --storage {DISK} --nor {DISK} --preboot {DISK} --guest-pes 8");
let plain = System::parse(&line).unwrap();
assert_eq!(plain.assigned_native_cores(LAPTOP_THREADS, None), Ok(8));
for count in [4, 6, 8] {
let options = round_trip(&format!("{line} --native-cores {count}"));
assert_eq!(options.guest_pes, Some(8));
assert_eq!(
options.assigned_native_cores(LAPTOP_THREADS, None),
Ok(count),
"{count}"
);
assert_eq!(
options.validate_native_cores(LAPTOP_THREADS, count, MAC_MINI_CPUS),
Ok(()),
"{count}"
);
}
let over = System::parse(&format!("{line} --native-cores 9")).unwrap();
assert_eq!(over.assigned_native_cores(LAPTOP_THREADS, None), Ok(9));
assert!(
over.validate_native_cores(LAPTOP_THREADS, 9, MAC_MINI_CPUS)
.is_err()
);
}
/// Tier 2 is off unless `--tier2 on` or `--tier2-check` asks for it, and
/// both are hand-written: a line without them parses as it did.
#[test]
fn tier2_runs_only_when_asked() {
let plain = System::parse("--system").unwrap();
assert_eq!(
(plain.tier2, plain.tier2_check, plain.tier2_runs()),
(None, false, false)
);
for (line, tier2, check, runs) in [
("--system --tier2 on", Some(true), false, true),
("--system --tier2 off", Some(false), false, false),
("--system --tier2-check", None, true, true),
("--system --tier2 on --tier2-check", Some(true), true, true),
] {
let options = System::parse(line).unwrap();
assert_eq!(
(options.tier2, options.tier2_check, options.tier2_runs()),
(tier2, check, runs),
"{line}"
);
assert_eq!(round_trip(line).tier2, tier2, "{line}");
}
for (line, error) in [
("--system --tier2", Error::Tier2),
("--system --tier2 yes", Error::Tier2),
("--system --tier2 on --tier2 off", Error::DuplicateTier2),
("--system --tier2 off --tier2-check", Error::Tier2CheckOff),
] {
assert_eq!(System::parse(line).err(), Some(error), "{line}");
}
}
@@ -0,0 +1,424 @@
//! The fork's hand-written options against the startup lines a stick
//! holds: each in every place on each line, twice, and with bad values, so
//! no option of the fork's changes what a line setup wrote means.
use super::*;
use crate::laptop::{self, Choice, Facts};
use alloc::{format, string::String, vec, vec::Vec};
/// The plain `macOS` startup choice of a tester's stick, as setup wrote it
/// (its ECID and network made up), one option and its value a group.
const MACOS: [&str; 9] = [
"--storage @disk",
"--nor @disk",
"--preboot @disk",
"--ecid 0x0000000000001234",
"--guest-network",
"--wifi HomeNet",
"--wifi-country IN",
"--input",
"--guest-pes 8",
];
/// The stick's startup choices: `macOS`, then the ones hand-written from it.
fn stick_lines() -> Vec<Vec<String>> {
let base: Vec<String> = MACOS.iter().map(|group| String::from(*group)).collect();
let with = |extra: &[&str]| {
let mut line = base.clone();
line.extend(extra.iter().map(|group| String::from(*group)));
line
};
vec![
base.clone(),
with(&["--laptop off"]),
with(&["--profile", "--laptop off"]),
with(&["--bluetooth-lend", "--laptop off"]),
with(&["--acpi-hardware"]),
]
}
/// The lines setup itself writes (its Preboot, bundle and Install lines),
/// which must parse and serialize exactly as they are.
fn setup_lines() -> Vec<Vec<String>> {
let groups = |groups: &[&str]| groups.iter().map(|g| String::from(*g)).collect::<Vec<_>>();
let storage = format!("--storage {DISK}");
let nor = format!("--nor {DISK}");
let preboot = format!("--preboot {DISK}");
vec![
groups(&[
&storage,
&nor,
&preboot,
"--ecid 0x0000000000001234",
"--external-disks",
"--guest-network",
]),
groups(&[&storage, &nor, "--bundle \\EFI\\stela\\r"]),
groups(&[
&storage,
&nor,
"--bundle \\stela\\boot\\22A\\r",
"--ecid 0x0000000000000001",
"--install \\stela\\install\\22A\\payload.json",
"--install-source 33333333-4444-5555-6666-777777777777",
"--development-restore",
]),
]
}
/// `--system` and `groups`, with `inserted` before group `at`.
fn line(groups: &[String], inserted: &[(&str, usize)]) -> String {
let mut text = String::from("--system");
for at in 0..=groups.len() {
for (option, _) in inserted.iter().filter(|(_, place)| *place == at) {
text.push(' ');
text.push_str(option);
}
if let Some(group) = groups.get(at) {
text.push(' ');
text.push_str(group);
}
}
text
}
/// One of the fork's hand-written options: its spellings, what each sets,
/// and the errors a bad value and a second copy give.
struct Fork {
valid: &'static [&'static str],
set: fn(&mut System, &str),
bad: &'static [(&'static str, Error)],
/// `None` for a flag a second copy of which is accepted, as `--profile`.
duplicate: Option<Error>,
}
fn value(option: &str) -> &str {
option.split_once(' ').map_or("", |(_, value)| value)
}
fn on(option: &str) -> bool {
value(option) == "on"
}
fn forks() -> [Fork; 17] {
[
Fork {
valid: &["--acpi-hardware"],
set: |o, _| o.acpi_hardware = true,
bad: &[],
duplicate: None,
},
Fork {
valid: &[
"--asus-mode performance",
"--asus-mode turbo",
"--asus-mode silent",
"--asus-mode off",
],
set: |o, t| o.asus_mode = Some(AsusMode::parse(value(t)).unwrap()),
bad: &[
("--asus-mode", Error::AsusMode),
("--asus-mode balanced", Error::AsusMode),
("--asus-mode Performance", Error::AsusMode),
],
duplicate: Some(Error::DuplicateAsusMode),
},
Fork {
valid: &["--keep-running-on-panic"],
set: |o, _| o.keep_running_on_panic = true,
bad: &[],
duplicate: None,
},
Fork {
valid: &["--cpu-balanced"],
set: |o, _| o.cpu_balanced = true,
bad: &[],
duplicate: None,
},
Fork {
valid: &["--panel-backlight"],
set: |o, _| o.panel_backlight = true,
bad: &[],
duplicate: None,
},
Fork {
valid: &["--tlbi-keep on", "--tlbi-keep off"],
set: |o, t| o.tlbi_keep = Some(on(t)),
bad: &[
("--tlbi-keep", Error::TlbiKeep),
("--tlbi-keep yes", Error::TlbiKeep),
("--tlbi-keep ON", Error::TlbiKeep),
("--tlbi-keep 1", Error::TlbiKeep),
],
duplicate: Some(Error::DuplicateTlbiKeep),
},
Fork {
valid: &["--share-aliases on", "--share-aliases off"],
set: |o, t| o.share_aliases = Some(on(t)),
bad: &[
("--share-aliases", Error::ShareAliases),
("--share-aliases yes", Error::ShareAliases),
("--share-aliases ON", Error::ShareAliases),
("--share-aliases 1", Error::ShareAliases),
],
duplicate: Some(Error::DuplicateShareAliases),
},
Fork {
valid: &["--tlbi-verify-check"],
set: |o, _| o.tlbi_verify_check = true,
bad: &[],
duplicate: Some(Error::DuplicateTlbiVerifyCheck),
},
Fork {
valid: &["--host-core on", "--host-core off"],
set: |o, t| o.host_core = Some(on(t)),
bad: &[
("--host-core", Error::HostCore),
("--host-core true", Error::HostCore),
("--host-core 1", Error::HostCore),
],
duplicate: Some(Error::DuplicateHostCore),
},
Fork {
valid: &["--gpu-aspm off", "--gpu-aspm firmware"],
set: |o, t| o.gpu_aspm = Some(GpuAspm::parse(value(t)).unwrap()),
bad: &[
("--gpu-aspm", Error::GpuAspm),
("--gpu-aspm on", Error::GpuAspm),
("--gpu-aspm performance", Error::GpuAspm),
],
duplicate: Some(Error::DuplicateGpuAspm),
},
Fork {
valid: &["--hle"],
set: |o, _| o.hle = true,
bad: &[],
duplicate: Some(Error::DuplicateHle),
},
Fork {
valid: &["--hle-off bzero", "--hle-off memmove,strlen"],
set: |o, t| {
o.hle_off = match value(t) {
"bzero" => vec![stela_engine::hle::Id::Bzero],
_ => vec![
stela_engine::hle::Id::Memmove,
stela_engine::hle::Id::Strlen,
],
}
},
bad: &[
("--hle-off", Error::HleId),
("--hle-off nosuch", Error::HleId),
("--hle-off memmove,", Error::HleId),
],
duplicate: Some(Error::DuplicateHle),
},
Fork {
valid: &["--tier2 on", "--tier2 off"],
set: |o, t| o.tier2 = Some(on(t)),
bad: &[
("--tier2", Error::Tier2),
("--tier2 yes", Error::Tier2),
("--tier2 ON", Error::Tier2),
],
duplicate: Some(Error::DuplicateTier2),
},
Fork {
valid: &["--tier2-check"],
set: |o, _| o.tier2_check = true,
bad: &[],
duplicate: None,
},
Fork {
valid: &["--pack-preload on", "--pack-preload off"],
set: |o, t| o.pack_preload = Some(on(t)),
bad: &[
("--pack-preload", Error::PackPreload),
("--pack-preload yes", Error::PackPreload),
("--pack-preload OFF", Error::PackPreload),
],
duplicate: Some(Error::DuplicatePackPreload),
},
Fork {
valid: &["--host-cursor on", "--host-cursor off"],
set: |o, t| o.host_cursor = Some(on(t)),
bad: &[
("--host-cursor", Error::HostCursor),
("--host-cursor yes", Error::HostCursor),
("--host-cursor ON", Error::HostCursor),
],
duplicate: Some(Error::DuplicateHostCursor),
},
Fork {
valid: &["--i915-guc auto", "--i915-guc off", "--i915-guc on"],
set: |o, t| o.i915_guc = crate::intel_guc::Setting::parse(&t["--i915-guc ".len()..]),
bad: &[
("--i915-guc", Error::I915Guc),
("--i915-guc OFF", Error::I915Guc),
("--i915-guc 0", Error::I915Guc),
],
duplicate: Some(Error::DuplicateI915Guc),
},
]
}
/// `--core-trial` is a read-only boot of its own: on any line that names
/// a disk or a network it is refused, wherever it stands, so a stray copy
/// never boots a stick's macOS without its disks.
#[test]
fn core_trial_anywhere_on_a_stick_or_setup_line_is_refused() {
for groups in all_lines() {
for at in 0..=groups.len() {
let text = line(&groups, &[("--core-trial", at)]);
assert_eq!(
System::parse(&text),
Err(Error::Constraint(Constraint::CoreTrial)),
"{text}"
);
}
}
let trial = "--system --bundle \\stela\\boot\\m2u\\r --storage-ram 0x200000000 --native-cores 16 --core-trial";
assert!(round_trip(trial).core_trial);
}
fn all_lines() -> Vec<Vec<String>> {
let mut lines = stick_lines();
lines.extend(setup_lines());
lines
}
#[test]
fn setup_lines_and_the_stick_s_choices_mean_what_they_meant() {
for groups in setup_lines() {
let text = line(&groups, &[]);
assert_eq!(round_trip(&text).to_string(), text);
}
for groups in stick_lines() {
let options = round_trip(&line(&groups, &[]));
// None of the fork's options is set by a line that does not hold it.
let held = |option: &str| groups.iter().any(|g| g.starts_with(option));
assert_eq!(options.acpi_hardware, held("--acpi-hardware"));
assert_eq!(options.asus_mode, None);
assert!(!options.keep_running_on_panic);
assert_eq!(options.tlbi_keep(), (false, false));
assert!(!options.host_core());
assert_eq!(options.gpu_aspm, None);
assert!(!options.hle && options.hle_off.is_empty());
assert!(!options.core_trial);
assert!(options.tier2.is_none() && !options.tier2_check && !options.tier2_runs());
assert!(options.pack_preload.is_none() && !options.pack_preload());
assert!(options.host_cursor.is_none() && !options.host_cursor());
assert_eq!(options.i915_guc, None);
assert_eq!(options.i915_guc(), crate::intel_guc::Setting::Auto);
}
}
#[test]
fn each_fork_option_means_the_same_in_every_place_of_every_line() {
let mut checked = 0;
for groups in all_lines() {
let plain = System::parse(&line(&groups, &[])).unwrap();
for fork in forks() {
for option in fork.valid {
let mut expected = plain.clone();
(fork.set)(&mut expected, option);
for at in 0..=groups.len() {
let text = line(&groups, &[(option, at)]);
assert_eq!(round_trip(&text), expected, "{text}");
checked += 1;
}
}
}
}
// 8 lines of 3 to 11 groups, 19 spellings.
assert!(checked > 1000, "{checked}");
}
#[test]
fn a_second_copy_anywhere_is_refused_or_changes_nothing() {
for groups in all_lines() {
let plain = System::parse(&line(&groups, &[])).unwrap();
for fork in forks() {
let first = fork.valid[0];
let second = fork.valid[fork.valid.len() - 1];
for i in 0..=groups.len() {
for j in i..=groups.len() {
let text = line(&groups, &[(first, i), (second, j)]);
match &fork.duplicate {
Some(error) => {
assert_eq!(System::parse(&text), Err(*error), "{text}")
}
None => {
let mut expected = plain.clone();
(fork.set)(&mut expected, first);
assert_eq!(System::parse(&text), Ok(expected), "{text}");
}
}
}
}
}
}
}
#[test]
fn a_bad_value_anywhere_is_its_option_s_own_error() {
for groups in all_lines() {
for fork in forks() {
for (bad, error) in fork.bad {
for at in 0..=groups.len() {
let text = line(&groups, &[(bad, at)]);
assert_eq!(System::parse(&text), Err(*error), "{text}");
}
}
}
}
}
/// A laptop's facts as the FA608 reads them.
const LAPTOP: Facts = Facts {
pm_profile: Some(2),
battery: true,
lid: true,
precision_touchpad: true,
trackpad_port: true,
};
#[test]
fn laptop_off_takes_nothing_and_leaves_acpi_hardware_on() {
let base = line(&stick_lines()[0], &[]);
let mut off = System::parse(&format!("{base} --laptop off --acpi-hardware")).unwrap();
let plan = laptop::plan(&off, LAPTOP);
for choice in [plan.battery, plan.lid, plan.brightness_keys, plan.trackpad] {
assert_eq!(choice, Choice::Skipped("--laptop off"));
}
plan.apply(&mut off);
assert!(off.acpi_hardware);
assert_eq!((off.battery, off.lid, off.trackpad), (None, None, None));
assert!(!off.brightness_keys);
// The battery + lid choice: auto, so the laptop takes its features too.
let mut auto = System::parse(&format!("{base} --acpi-hardware")).unwrap();
let plan = laptop::plan(&auto, LAPTOP);
plan.apply(&mut auto);
assert!(auto.acpi_hardware && auto.brightness_keys);
assert_eq!(auto.battery, Some(Battery::Host));
assert_eq!(auto.lid, Some(Lid::Method));
assert_eq!(auto.trackpad, Some(GuestTrackpad::Mt2));
assert!(plan.takes_brightness_keys());
}
#[test]
fn profile_takes_the_host_core_and_the_tlbi_keep_beside_it() {
let base = line(&stick_lines()[0], &[]);
let speed = "--profile --tlbi-keep on --tlbi-verify-check --host-core on";
let options = round_trip(&format!("{base} {speed}"));
assert!(options.profile && options.parallel && options.host_core());
assert_eq!(options.tlbi_keep(), (true, true));
// Eight PEs and a host core on a 16-thread laptop.
assert_eq!(
crate::host_core::plan(options.host_core(), options.parallel, 8, 16),
crate::host_core::Plan::Reserve { executors: 9 }
);
// The profile entry as the stick has it (`--laptop off`) with them.
let profiled = round_trip(&format!("{base} --profile --laptop off {speed}"));
assert_eq!(profiled.laptop(), Laptop::Off);
assert_eq!(profiled.tlbi_keep(), (true, true));
}
+41 -1
View File
@@ -11,6 +11,9 @@ pub(super) fn system(options: &System) -> Result<(), Error> {
if options.audio_own_hpet && options.audio_check.is_none() {
return Err(Error::Constraint(Constraint::AudioHpetDependency));
}
if options.lid_sleep && options.lid() != Lid::Method {
return Err(Error::Constraint(Constraint::LidSleepDependency));
}
if options.native_pci_own_ioapic
&& (options.audio_check.is_some()
|| options.native_bootstrap_check
@@ -18,6 +21,36 @@ pub(super) fn system(options: &System) -> Result<(), Error> {
{
return Err(Error::Constraint(Constraint::NativePciIoapicExclusive));
}
if options.trackpad.is_some() && !options.input {
return Err(Error::Constraint(Constraint::TrackpadDependency));
}
core_trial(options)
}
/// A `--core-trial` boot reaches no disk: its guest disks are engine memory
/// and no option that opens a host disk, the NOR store, an install or
/// restore source, or a lent USB disk, or that writes the USB's saved
/// Wi-Fi networks, is admitted beside it. `--preboot` is refused, and with
/// it every option that chooses a Preboot boot (`boot_selection`).
fn core_trial(options: &System) -> Result<(), Error> {
if options.core_trial
&& (!options.bundle
|| options.storage_ram.is_none()
|| options.native_cores.is_none()
|| options.storage.is_some()
|| options.nor.is_some()
|| options.preboot.is_some()
|| options.install.is_some()
|| options.install_source.is_some()
|| options.update_restore
|| options.restore
|| options.restore_source.is_some()
|| options.external_disks
|| !options.usb_storage.is_empty()
|| options.ssid.is_some())
{
return Err(Error::Constraint(Constraint::CoreTrial));
}
Ok(())
}
@@ -43,7 +76,11 @@ fn restore(options: &System) -> Result<(), Error> {
}
fn wifi(options: &System) -> Result<(), Error> {
if options.ssid.is_none() && (options.wifi_key.is_some() || options.wifi_country.is_some()) {
if options.ssid.is_none()
&& (options.wifi_key.is_some()
|| options.wifi_country.is_some()
|| options.wifi_prefer.is_some())
{
return Err(Error::Constraint(Constraint::WifiDependency));
}
Ok(())
@@ -62,6 +99,9 @@ fn install(options: &System) -> Result<(), Error> {
if options.install_source.is_some() && options.install.is_none() {
return Err(Error::Constraint(Constraint::InstallSourceDependency));
}
if options.medium_read_ahead.is_some() && options.install.is_none() {
return Err(Error::Constraint(Constraint::MediumReadAheadDependency));
}
if options.install.is_some()
&& (!options.bundle
|| options.preboot.is_some()
@@ -0,0 +1,99 @@
//! Perceptual 16-stop stepping for native Linux DRM panel backlights
//! (`BACKLIGHT_RAW`, such as `amdgpu_bl0` on eDP OLED panels or
//! `intel_backlight`), driven by ACPI brightness key notifications.
use core::sync::atomic::AtomicBool;
/// Whether the brightness keys drive the GPU's own Linux backlight
/// (`--panel-backlight`). Off unless given: a panel then keeps ACPI's
/// `_BCM` as before, and no GPU's Linux backlight (nouveau's among them) is
/// read, raised or stepped.
pub static NATIVE: AtomicBool = AtomicBool::new(false);
/// `ACPI_VIDEO_NOTIFY_*` codes (matching `stela_drivers::probe::backlight`).
pub const NOTIFY_CYCLE: u32 = 0x85;
pub const NOTIFY_INC: u32 = 0x86;
pub const NOTIFY_DEC: u32 = 0x87;
pub const NOTIFY_ZERO: u32 = 0x88;
pub const NOTIFY_OFF: u32 = 0x89;
/// 16 perceptual stops in per-mille of `max_brightness` (1.5% ..= 100%).
/// Fine steps at the bottom keep OLED panels controllable indoors without
/// blanking the panel on `NOTIFY_DEC`, while still reaching 100% in 15 taps.
const STOPS_PER_MILLE: [u32; 16] = [
15, 30, 50, 80, 120, 170, 230, 300, 380, 470, 560, 660, 760, 860, 930, 1000,
];
fn stop_level(max: u32, per_mille: u32) -> u32 {
if max == 0 {
return 0;
}
let scaled = ((u64::from(max) * u64::from(per_mille) + 500) / 1000) as u32;
scaled.clamp(1, max)
}
/// The next raw backlight level for `event` given `current` and `max`.
pub fn step(current: u32, max: u32, event: u32) -> u32 {
if max == 0 {
return 0;
}
let current = current.min(max);
let levels = STOPS_PER_MILLE.map(|pm| stop_level(max, pm));
let min = levels[0];
let above = || levels.iter().copied().find(|&lvl| lvl > current);
let below = || levels.iter().copied().rev().find(|&lvl| lvl < current);
match event {
NOTIFY_INC => above().unwrap_or(max),
NOTIFY_DEC => below().unwrap_or(min),
NOTIFY_CYCLE => above().unwrap_or(min),
NOTIFY_ZERO | NOTIFY_OFF => 0,
_ => current,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn oled_496k_steps_monotonically_down_and_up() {
let max = 496_000;
let mut cur = max;
let mut down = alloc::vec![cur];
for _ in 0..20 {
let next = step(cur, max, NOTIFY_DEC);
if next == cur {
break;
}
assert!(next < cur);
cur = next;
down.push(cur);
}
assert_eq!(down.len(), 16);
assert_eq!(*down.last().unwrap(), 7_440);
// Further DEC stays at the non-zero floor.
assert_eq!(step(cur, max, NOTIFY_DEC), 7_440);
let mut up = alloc::vec![cur];
for _ in 0..20 {
let next = step(cur, max, NOTIFY_INC);
if next == cur {
break;
}
assert!(next > cur);
cur = next;
up.push(cur);
}
assert_eq!(up.len(), 16);
assert_eq!(*up.last().unwrap(), max);
}
#[test]
fn pwm_255_and_cycle_and_off_work() {
assert_eq!(step(255, 255, NOTIFY_CYCLE), 4);
assert_eq!(step(100, 255, NOTIFY_ZERO), 0);
assert_eq!(step(100, 255, NOTIFY_OFF), 0);
assert_eq!(step(0, 255, NOTIFY_INC), 4);
assert_eq!(step(0, 0, NOTIFY_INC), 0);
}
}
+144
View File
@@ -0,0 +1,144 @@
//! What the firmware's PCI bus driver knew of each function before it
//! exited, as Linux's EFI stub hands some of it over: the memory each BAR
//! decodes, each bridge's buses and non-prefetchable window, and a copy of
//! a display function's option ROM, which the firmware read from the ROM
//! BAR and keeps (`EFI_PCI_IO_PROTOCOL.RomImage`; Linux's stub copies it
//! into `setup_data` as `SETUP_PCI`, and `pci_dev::rom` holds it).
//!
//! The boot reads it once before the firmware's exit and the engine places
//! an expansion ROM BAR the firmware left unassigned with it
//! ([`rom_room`]): the firmware sized every BAR, which the engine cannot
//! do again on functions other drivers own.
use crate::video_bios::{bridge_window, place};
use alloc::vec::Vec;
use core::ops::Range;
/// One function as the firmware left it.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Function {
pub segment: u16,
pub bus: u8,
pub device: u8,
pub function: u8,
/// A bridge's secondary and subordinate buses and register 0x20.
pub bridge: Option<(u8, u8, u32)>,
/// The memory each BAR decodes.
pub spans: Vec<Range<u64>>,
/// Where the copy of its option ROM lies in memory the boot keeps.
pub rom: Option<Range<u64>>,
}
/// The most functions the map holds.
pub const MOST_FUNCTIONS: usize = 1024;
const MOST_SPANS: usize = 16;
fn put(out: &mut Vec<u8>, bytes: &[u8]) {
out.extend_from_slice(bytes);
}
/// The map as bytes, which [`decode`] reads back.
pub fn encode(functions: &[Function]) -> Vec<u8> {
let mut out = Vec::new();
put(
&mut out,
&(functions.len().min(MOST_FUNCTIONS) as u32).to_le_bytes(),
);
for function in functions.iter().take(MOST_FUNCTIONS) {
put(&mut out, &function.segment.to_le_bytes());
put(
&mut out,
&[function.bus, function.device, function.function],
);
let (secondary, subordinate, window) = function.bridge.unwrap_or_default();
put(
&mut out,
&[u8::from(function.bridge.is_some()), secondary, subordinate],
);
put(&mut out, &window.to_le_bytes());
let spans = function.spans.len().min(MOST_SPANS);
put(&mut out, &[spans as u8]);
for span in function.spans.iter().take(spans) {
put(&mut out, &span.start.to_le_bytes());
put(&mut out, &span.end.to_le_bytes());
}
let rom = function.rom.clone().unwrap_or_default();
put(&mut out, &rom.start.to_le_bytes());
put(&mut out, &rom.end.to_le_bytes());
}
out
}
/// The map [`encode`] wrote, or `None` for bytes it did not write.
pub fn decode(bytes: &[u8]) -> Option<Vec<Function>> {
let mut at = 0usize;
let mut take = |count: usize| -> Option<&[u8]> {
let taken = bytes.get(at..at.checked_add(count)?)?;
at += count;
Some(taken)
};
let u64_of = |bytes: &[u8]| u64::from_le_bytes(bytes.try_into().unwrap_or([0; 8]));
let count = u32::from_le_bytes(take(4)?.try_into().ok()?) as usize;
if count > MOST_FUNCTIONS {
return None;
}
let mut functions = Vec::new();
for _ in 0..count {
let segment = u16::from_le_bytes(take(2)?.try_into().ok()?);
let place = take(3)?;
let (bus, device, function) = (place[0], place[1], place[2]);
let bridge = take(3)?;
let (is_bridge, secondary, subordinate) = (bridge[0] != 0, bridge[1], bridge[2]);
let window = u32::from_le_bytes(take(4)?.try_into().ok()?);
let spans_count = usize::from(take(1)?[0]);
if spans_count > MOST_SPANS {
return None;
}
let mut spans = Vec::new();
for _ in 0..spans_count {
let start = u64_of(take(8)?);
let end = u64_of(take(8)?);
spans.push(start..end);
}
let start = u64_of(take(8)?);
let end = u64_of(take(8)?);
functions.push(Function {
segment,
bus,
device,
function,
bridge: is_bridge.then_some((secondary, subordinate, window)),
spans,
rom: (end > start).then_some(start..end),
});
}
Some(functions)
}
/// Where to place an expansion ROM BAR of `bytes` for the function at
/// `segment`/`bus`/`device`/`function`: the lowest place aligned to its
/// size in the non-prefetchable window of the bridge whose secondary bus is
/// the function's, clear of every BAR of every function below that bridge
/// and of every window of the bridges below it. `None` where no bridge is
/// above the function, its window is closed or holds no room.
pub fn rom_room(map: &[Function], segment: u16, bus: u8, bytes: u64) -> Option<u64> {
let (secondary, subordinate, window) = map.iter().find_map(|function| {
function
.bridge
.filter(|&(secondary, _, _)| function.segment == segment && secondary == bus)
})?;
let window = bridge_window(window)?;
let below = |function: &&Function| {
function.segment == segment && (secondary..=subordinate).contains(&function.bus)
};
let mut used: Vec<Range<u64>> = Vec::new();
for function in map.iter().filter(below) {
used.extend(function.spans.iter().cloned());
if let Some(window) = function.bridge.and_then(|(_, _, word)| bridge_window(word)) {
used.push(window);
}
}
place(&window, &used, bytes)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,49 @@
use super::*;
use alloc::vec;
/// A root port at 00:01.1 forwarding bus 3 and the window 0xfc00_0000 to
/// 0xfcff_ffff; a GPU at 03:00.0 with its registers at the window's
/// bottom and its option ROM copied at 0x1000_0000; its audio function.
fn map() -> Vec<Function> {
vec![
Function {
device: 1,
function: 1,
bridge: Some((3, 3, 0xfcf0_fc00)),
..Function::default()
},
Function {
bus: 3,
spans: vec![0xe000_0000..0xf000_0000, 0xfc00_0000..0xfc04_0000],
rom: Some(0x1000_0000..0x1001_0000),
..Function::default()
},
Function {
bus: 3,
function: 1,
spans: core::iter::once(0xfc06_0000..0xfc06_4000).collect(),
..Function::default()
},
]
}
#[test]
fn the_map_reads_back_as_written() {
let map = map();
assert_eq!(decode(&encode(&map)).as_ref(), Some(&map));
assert_eq!(decode(&encode(&map)[..10]), None);
assert_eq!(decode(&[]), None);
}
#[test]
fn an_unassigned_rom_bar_goes_in_its_bridges_window_clear_of_every_bar() {
let map = map();
// Between the registers and the audio function, else above both.
assert_eq!(rom_room(&map, 0, 3, 0x2_0000), Some(0xfc04_0000));
assert_eq!(rom_room(&map, 0, 3, 0x4_0000), Some(0xfc08_0000));
// No bridge above bus 0, and none on another segment.
assert_eq!(rom_room(&map, 0, 0, 0x2_0000), None);
assert_eq!(rom_room(&map, 1, 3, 0x2_0000), None);
// A window too small.
assert_eq!(rom_room(&map, 0, 3, 0x200_0000), None);
}
+30 -4
View File
@@ -11,10 +11,28 @@
//! a processor spinning forever ([`crate::bounded_spin`]).
use core::sync::atomic::{AtomicU32, Ordering};
/// How long a posted call may wait for a task to take it.
pub const WITHDRAW_MS: u64 = 300;
/// How long a posted call a task performs may run before the boot stops.
pub const STOP_MS: u64 = 10_000;
/// How long a posted call may wait for a task to take it: 400 ms, still
/// under XNU's half second. At 300 ms, the boot processor's GPU pump held
/// for 350 to 364 ms on a UHD 630 and an Iris Xe withdrew a GPU call that
/// was about to be taken, and WindowServer crashed (stambha issue #52).
pub const WITHDRAW_MS: u64 = 400;
/// How long a posted call a task performs may run before the boot stops:
/// past the slowest reset a kernel driver gives a hung GPU, so that the
/// driver's reset ends the call, which fails, the device is lost and
/// WindowServer restarts on a reopened one. i915 with GuC submission on a
/// Gen12 render engine takes up to [`I915_GUC_RESET_MS`]: its heartbeat
/// raises a stuck engine's priority a beat after it found it stuck, and
/// GuC then waits the render engine's 7.5 s preemption timeout before it
/// resets the context. dev64's Iris Xe recovered from a hung execbuffer
/// 5.6 s after it was first reported in test 4, and test 5's 10 s stop
/// came first in both of its boots, before i915 reset anything.
pub const STOP_MS: u64 = 30_000;
/// The longest i915 with GuC submission takes to reset a hung Gen12 render
/// context: two of its heartbeats (`DRM_I915_HEARTBEAT_INTERVAL`, 2.5 s),
/// one that finds the engine stuck and one that raises its priority, then
/// the render engine's preemption timeout
/// (`DRM_I915_PREEMPT_TIMEOUT_COMPUTE`, 7.5 s on Gen12).
pub const I915_GUC_RESET_MS: u64 = 2 * 2_500 + 7_500;
/// The longest a posted DRM fence wait may wait in a deferred job's slice,
/// which gives its processor back while it waits: the bound of the GPU
/// backend's own idle waits. A wait asking for longer, as Mesa's
@@ -150,6 +168,14 @@ mod tests {
const _: () = assert!(WITHDRAW_MS < 500 && STOP_MS > 500);
}
#[test]
fn a_hung_gpu_is_reset_by_its_driver_before_the_stop() {
// i915's slowest GuC reset of a Gen12 render context, with room for
// the reset itself and the call's failing after it.
const _: () = assert!(I915_GUC_RESET_MS == 12_500);
const _: () = assert!(STOP_MS >= 2 * I915_GUC_RESET_MS);
}
#[test]
fn a_fence_wait_ends_before_the_stop_and_a_held_one_within_xnus_bound() {
const _: () = assert!(WITHDRAW_MS + WAIT_MS < STOP_MS);
+118
View File
@@ -57,6 +57,81 @@ impl Presses {
}
}
/// How long after the service's first look a control-method power
/// button's notification stands for one its firmware raised before (an EC
/// query pending at start), not a press.
pub const NOTIFY_SETTLE_MILLIS: u64 = 5000;
/// How long a power button's notifications must stop before the next is a
/// new press: firmware may notify again and again while the button is
/// held (the FA608PP's EC query `_QE7` notifies, sleeps 500 ms and is
/// queried again), or with the fixed event of the same press.
pub const NOTIFY_DEBOUNCE_MILLIS: u64 = 1000;
/// What a control-method power button's notification is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Notified {
/// A press: a press and a release for the guest. A notification never
/// stands for a hold, as a repeat of one press may follow it.
Press,
/// The press a notification or a fixed event just before stood for.
Repeat,
/// Within the settling after the first look.
Settling,
}
/// A control-method power button's notifications, taken as presses.
#[derive(Clone, Copy, Debug, Default)]
pub struct Notifications {
/// The service's first look, the settling's start.
start: Option<u64>,
/// The last notification and the last fixed-event press.
notified: Option<u64>,
fixed: Option<u64>,
}
impl Notifications {
pub const fn new() -> Self {
Self {
start: None,
notified: None,
fixed: None,
}
}
/// The service looked at `now`: the first look starts the settling.
pub fn look(&mut self, now: u64) {
self.start.get_or_insert(now);
}
/// One or more notifications seen at `now`, with `settle` and
/// `debounce` ticks long: a press after `debounce` of quiet from every
/// notification and fixed press, else a repeat of the last.
pub fn notified(&mut self, now: u64, settle: u64, debounce: u64) -> Notified {
let start = *self.start.get_or_insert(now);
let recent = |at: Option<u64>| at.is_some_and(|at| now.wrapping_sub(at) < debounce);
let notified = if now.wrapping_sub(start) < settle {
Notified::Settling
} else if recent(self.notified) || recent(self.fixed) {
Notified::Repeat
} else {
Notified::Press
};
self.notified = Some(now);
notified
}
/// A fixed-event press at `now`: whether it is one of its own, not the
/// press a notification within `debounce` before already stood for.
/// Fixed presses keep their own pairing ([`Presses`]).
pub fn fixed(&mut self, now: u64, debounce: u64) -> bool {
let own = !self
.notified
.is_some_and(|at| now.wrapping_sub(at) < debounce);
self.fixed = Some(now);
own
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -97,6 +172,49 @@ mod tests {
assert_eq!(presses.press(2600, WINDOW, 2, false), Press::ForceOff);
}
const SETTLE: u64 = 5000;
const DEBOUNCE: u64 = 1000;
#[test]
fn notifications_settle_after_the_first_look() {
let mut notes = Notifications::new();
notes.look(10_000);
// Queued before the boot looked, or pending EC queries at start.
assert_eq!(notes.notified(10_000, SETTLE, DEBOUNCE), Notified::Settling);
assert_eq!(notes.notified(14_800, SETTLE, DEBOUNCE), Notified::Settling);
// A burst that ran past the settling stays one.
assert_eq!(notes.notified(15_500, SETTLE, DEBOUNCE), Notified::Repeat);
assert_eq!(notes.notified(17_000, SETTLE, DEBOUNCE), Notified::Press);
}
#[test]
fn a_held_buttons_repeated_notifications_are_one_press() {
let mut notes = Notifications::new();
notes.look(0);
// The FA608PP's _QE7 notifies, sleeps 500 ms and runs again while
// the button is held: 0, 0.5, 1.0 and 1.5 s are one press.
assert_eq!(notes.notified(10_000, SETTLE, DEBOUNCE), Notified::Press);
for at in [10_500, 11_000, 11_500] {
assert_eq!(notes.notified(at, SETTLE, DEBOUNCE), Notified::Repeat);
}
// A second of quiet ends it.
assert_eq!(notes.notified(12_500, SETTLE, DEBOUNCE), Notified::Press);
}
#[test]
fn a_fixed_event_and_a_notification_of_one_press_are_one_press() {
let mut notes = Notifications::new();
notes.look(0);
assert_eq!(notes.notified(10_000, SETTLE, DEBOUNCE), Notified::Press);
assert!(!notes.fixed(10_400, DEBOUNCE));
assert!(notes.fixed(20_000, DEBOUNCE));
assert_eq!(notes.notified(20_300, SETTLE, DEBOUNCE), Notified::Repeat);
// Fixed presses alone keep their own pairing, however close.
let mut fixed = Notifications::new();
assert!(fixed.fixed(1000, DEBOUNCE));
assert!(fixed.fixed(1200, DEBOUNCE));
}
#[test]
fn a_counter_that_wraps_keeps_the_window() {
let mut presses = Presses::new();
@@ -0,0 +1,75 @@
//! `PES PREDICTION`: the guest context switches since the last beat and the
//! prediction barriers the host issued for them, so that a boot with
//! `--no-ibpb` and one without show what the barrier costs. Every count is
//! one the engine keeps anyway, but for the engine path's barriers, which
//! the host counts as it issues them.
use alloc::{format, string::String};
/// One beat's counts, every PE's together.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Contexts {
/// Whether the host isolates predictions between guest contexts: IBPB
/// and a return stack refill at each switch (`speculation::isolates`).
pub isolating: bool,
/// The engine's `Statistics::prediction_isolations`: every guest context
/// change the engine made and, where the host isolates, every native
/// TTBR0 switch too.
pub isolations: u64,
/// The TTBR0 switches native code made (`Statistics::native_table_switches`).
pub native: u64,
/// The barriers the engine's path issued (`speculation::isolate`).
pub engine_barriers: u64,
}
impl Contexts {
/// `PES PREDICTION isolating=1 switches=E/N ibpb=B`: the guest context
/// switches the engine made (E) and native code made (N), and the IBPBs
/// the host issued for them, each with its return stack refill: the
/// engine path's, and where the host isolates one per native switch,
/// which the switch thunk issues itself.
pub fn line(&self) -> String {
let native_barriers = if self.isolating { self.native } else { 0 };
let engine = self.isolations.saturating_sub(native_barriers);
format!(
"PES PREDICTION isolating={} switches={engine}/{} ibpb={}\n",
u8::from(self.isolating),
self.native,
self.engine_barriers + native_barriers,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The same workload counts the same switches in both boots of an A/B;
/// only the isolating one issues barriers, one per switch.
#[test]
fn both_boots_count_the_switches_and_only_an_isolating_one_barriers() {
let isolating = Contexts {
isolating: true,
isolations: 150,
native: 50,
engine_barriers: 100,
};
assert_eq!(
isolating.line(),
"PES PREDICTION isolating=1 switches=100/50 ibpb=150\n"
);
let shared = Contexts {
isolating: false,
isolations: 100,
native: 50,
engine_barriers: 0,
};
assert_eq!(
shared.line(),
"PES PREDICTION isolating=0 switches=100/50 ibpb=0\n"
);
assert_eq!(
Contexts::default().line(),
"PES PREDICTION isolating=0 switches=0/0 ibpb=0\n"
);
}
}
+207
View File
@@ -0,0 +1,207 @@
//! A bitmap font in the Linux console's PSF1 or PSF2 format, as the boot
//! console and the startup pages draw it (`stela-boot`'s `console::font`).
//! Each glyph is `height` rows of `width` bits, MSB first, each row padded
//! to whole bytes. The first 128 glyphs are ASCII in code point order; any
//! other character is found in the font's Unicode table ([`Font::index`]).
/// One font, parsed from its PSF file.
pub struct Font {
pub width: usize,
pub height: usize,
row_bytes: usize,
glyph_bytes: usize,
count: usize,
glyphs: &'static [u8],
/// The Unicode table after the glyphs, when the file has one.
table: Option<Table>,
}
#[derive(Clone, Copy)]
enum Table {
/// PSF1: UCS-2 little-endian values, each glyph's ended by `0xFFFF`,
/// with `0xFFFE` starting the sequences that follow its characters.
Psf1(&'static [u8]),
/// PSF2: UTF-8, each glyph's ended by `0xFF`, with `0xFE` starting its
/// sequences.
Psf2(&'static [u8]),
}
const PSF1_MAGIC: [u8; 2] = [0x36, 0x04];
const PSF1_512: u8 = 1;
const PSF1_TABLE: u8 = 2;
const PSF2_MAGIC: [u8; 4] = [0x72, 0xb5, 0x4a, 0x86];
const PSF2_TABLE: usize = 1;
/// The glyphs a font must have: printable ASCII and below.
const GLYPHS: usize = 0x80;
fn word(file: &[u8], offset: usize) -> Option<usize> {
let bytes = file.get(offset..offset + 4)?;
Some(u32::from_le_bytes(bytes.try_into().ok()?) as usize)
}
impl Font {
pub fn parse(file: &'static [u8]) -> Option<Self> {
let (width, height, header, count, glyph_bytes, table) = if file.starts_with(&PSF1_MAGIC) {
let mode = *file.get(2)?;
let height = usize::from(*file.get(3)?);
let count = if mode & PSF1_512 != 0 { 512 } else { 256 };
(8, height, 4, count, height, mode & PSF1_TABLE != 0)
} else if file.starts_with(&PSF2_MAGIC) {
(
word(file, 28)?,
word(file, 24)?,
word(file, 8)?,
word(file, 16)?,
word(file, 20)?,
word(file, 12)? & PSF2_TABLE != 0,
)
} else {
return None;
};
let row_bytes = width.div_ceil(8);
if width == 0 || height == 0 || glyph_bytes != row_bytes * height || count < GLYPHS {
return None;
}
let end = header.checked_add(count.checked_mul(glyph_bytes)?)?;
let glyphs = file.get(header..end)?;
let table = match (table, file.get(end..)) {
(true, Some(rest)) if file.starts_with(&PSF1_MAGIC) => Some(Table::Psf1(rest)),
(true, Some(rest)) => Some(Table::Psf2(rest)),
_ => None,
};
Some(Self {
width,
height,
row_bytes,
glyph_bytes,
count,
glyphs,
table,
})
}
/// Whether pixel (`x`, `y`) of `character`'s glyph is set; anything
/// outside ASCII draws as `?`.
pub fn pixel(&self, character: u8, x: usize, y: usize) -> bool {
let index = if usize::from(character) < GLYPHS {
character
} else {
b'?'
};
self.set(usize::from(index), x, y)
}
/// The glyph that draws `character`: ASCII by its code point, anything
/// else by the font's Unicode table, and `?` when the font has none.
pub fn index(&self, character: char) -> usize {
let code = u32::from(character);
if code < GLYPHS as u32 {
return code as usize;
}
self.table
.and_then(|table| table.find(character))
.filter(|&index| index < self.count)
.unwrap_or(usize::from(b'?'))
}
/// Whether pixel (`x`, `y`) of glyph `index` ([`Self::index`]) is set.
pub fn set(&self, index: usize, x: usize, y: usize) -> bool {
let row = index * self.glyph_bytes + y * self.row_bytes;
self.glyphs[row + x / 8] & (0x80 >> (x % 8)) != 0
}
}
impl Table {
/// The first glyph whose own characters, not its sequences, include
/// `character`.
fn find(self, character: char) -> Option<usize> {
match self {
Self::Psf1(table) => {
let wanted = u16::try_from(u32::from(character)).ok()?;
let mut glyph = 0;
let mut sequences = false;
for pair in table.as_chunks::<2>().0 {
match u16::from_le_bytes(*pair) {
0xffff => {
glyph += 1;
sequences = false;
}
0xfffe => sequences = true,
value if !sequences && value == wanted => return Some(glyph),
_ => {}
}
}
None
}
Self::Psf2(table) => table.split(|&byte| byte == 0xff).position(|entry| {
let own = entry.split(|&byte| byte == 0xfe).next().unwrap_or(&[]);
core::str::from_utf8(own).is_ok_and(|own| own.contains(character))
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The boot console's font.
static SPLEEN: &[u8] = include_bytes!("../../stela-boot/src/console/spleen-8x16.psfu");
fn font() -> Font {
Font::parse(SPLEEN).expect("Spleen parses")
}
fn ink(font: &Font, index: usize) -> usize {
(0..font.height)
.flat_map(|y| (0..font.width).map(move |x| (x, y)))
.filter(|&(x, y)| font.set(index, x, y))
.count()
}
#[test]
fn ascii_draws_by_its_code_point() {
let font = font();
assert_eq!((font.width, font.height), (8, 16));
assert_eq!(font.index('A'), usize::from(b'A'));
for y in 0..16 {
for x in 0..8 {
assert_eq!(font.pixel(b'A', x, y), font.set(usize::from(b'A'), x, y));
}
}
}
#[test]
fn other_characters_draw_by_the_unicode_table() {
let font = font();
// The middle dot: a few pixels in the middle rows.
let dot = font.index('\u{b7}');
assert_ne!(dot, usize::from(b'?'));
assert!((1..=9).contains(&ink(&font, dot)));
assert!(
(0..16)
.filter(|y| !(5..11).contains(y))
.all(|y| (0..8).all(|x| !font.set(dot, x, y)))
);
// An accented letter has a glyph of its own, unlike its bare letter.
let e = font.index('\u{e9}');
assert_ne!(e, usize::from(b'?'));
assert_ne!(e, usize::from(b'e'));
}
#[test]
fn a_character_the_font_lacks_draws_as_a_question_mark() {
assert_eq!(font().index('\u{1f600}'), usize::from(b'?'));
// Bytes past ASCII still draw as `?` for the console.
let font = font();
for y in 0..16 {
assert_eq!(font.pixel(0xe9, 3, y), font.pixel(b'?', 3, y));
}
}
#[test]
fn a_file_that_is_not_a_font_is_refused() {
assert!(Font::parse(b"not a font").is_none());
assert!(Font::parse(&SPLEEN[..100]).is_none());
}
}
@@ -0,0 +1,168 @@
//! Thinning of a log's identical lines in a row: the first is written, each
//! power of two of its repeats leaves one count line, and the next different
//! line is preceded by the total, so a line Linux prints once per retry (an
//! amdgpu submission refused for memory, which RADV retries every
//! millisecond for a second) costs a few lines, not thousands, and the count
//! is in the log even if the boot stops while it repeats.
//!
//! Lines are compared by a hash of their text, which needs no buffer: the
//! sink may run where nothing can be allocated.
use core::fmt;
/// What to write for a line.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Verdict {
/// Write it, after a line saying the one before came `repeated` more
/// times than the count already written, if any.
Write { repeated: Option<u64> },
/// The same as the one before: write nothing, or a line saying it has
/// come `count` more times so far.
Repeat { count: Option<u64> },
}
/// The last line's hash and its repeats.
#[derive(Debug, Default)]
pub struct Repeats {
last: Option<u64>,
count: u64,
written: u64,
}
impl Repeats {
/// What to write for the line `text`.
pub fn line(&mut self, text: fmt::Arguments<'_>) -> Verdict {
self.hashed(hash(text))
}
fn hashed(&mut self, hash: u64) -> Verdict {
if self.last == Some(hash) {
self.count += 1;
if self.count.is_power_of_two() {
self.written = self.count;
return Verdict::Repeat {
count: Some(self.count),
};
}
return Verdict::Repeat { count: None };
}
let repeated = (self.count > self.written).then_some(self.count);
*self = Self {
last: Some(hash),
count: 0,
written: 0,
};
Verdict::Write { repeated }
}
}
/// The line that counts repeats of the line Linux last wrote: `count` more
/// so far, or in all once a different line follows (`ended`). It names that
/// line as Linux's, as the boot's own lines may come between them.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Counted {
pub count: u64,
pub ended: bool,
}
impl fmt::Display for Counted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let when = if self.ended { "in all" } else { "so far" };
write!(
f,
"the line Linux last wrote came {} more times {when}",
self.count
)
}
}
/// FNV-1a over the formatted text.
pub(crate) fn hash(text: fmt::Arguments<'_>) -> u64 {
struct Fnv(u64);
impl fmt::Write for Fnv {
fn write_str(&mut self, s: &str) -> fmt::Result {
for byte in s.bytes() {
self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
}
Ok(())
}
}
let mut fnv = Fnv(0xcbf2_9ce4_8422_2325);
let _ = fmt::write(&mut fnv, text);
fnv.0
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
#[test]
fn identical_lines_are_counted_at_powers_of_two_and_totalled() {
let mut repeats = Repeats::default();
let refused = format_args!("<3> amdgpu: Not enough memory for command submission!");
assert_eq!(repeats.line(refused), Verdict::Write { repeated: None });
let counts: Vec<_> = (0..4265)
.filter_map(|_| match repeats.line(refused) {
Verdict::Repeat { count } => count,
Verdict::Write { .. } => panic!("a repeat written"),
})
.collect();
assert_eq!(
counts,
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
);
assert_eq!(
repeats.line(format_args!("<6> other")),
Verdict::Write {
repeated: Some(4265)
}
);
assert_eq!(
repeats.line(format_args!("<6> {}", "other")),
Verdict::Repeat { count: Some(1) }
);
// A total already written is not written again.
assert_eq!(
repeats.line(format_args!("<6> third")),
Verdict::Write { repeated: None }
);
}
/// A count names the line it counts as Linux's last, not the line above
/// it in the log, which may be the boot's own.
#[test]
fn a_count_names_the_line_linux_last_wrote() {
use alloc::format;
assert_eq!(
format!(
"{}",
Counted {
count: 4,
ended: false
}
),
"the line Linux last wrote came 4 more times so far"
);
assert_eq!(
format!(
"{}",
Counted {
count: 4265,
ended: true
}
),
"the line Linux last wrote came 4265 more times in all"
);
}
#[test]
fn different_lines_are_all_written() {
let mut repeats = Repeats::default();
for line in ["a", "b", "a", "b"] {
assert_eq!(
repeats.line(format_args!("{line}")),
Verdict::Write { repeated: None }
);
}
}
}
+5 -5
View File
@@ -438,9 +438,9 @@ impl Unfinished {
(false, true) => format!(" during \"{}\" or soon after", self.stage),
};
format!(
"The last start of Stela on this PC did not end by itself: the PC was switched off \
or reset{stage}. If Stela had stopped working, its log is on this USB: on any \
computer with stela, plug in this USB and run `stela log`, which saves it to \
"The last start of Stambha on this PC did not end by itself: the PC was switched off \
or reset{stage}. If Stambha had stopped working, its log is on this USB: on any \
computer with stambha, plug in this USB and run `stambha log`, which saves it to \
log.txt; include that file in a report."
)
}
@@ -646,8 +646,8 @@ mod tests {
"switched off or reset during \"Taking control of the other processors\" or soon \
after"
));
assert!(notice.contains("on any computer with stela"), "{notice}");
assert!(notice.contains("`stela log`"), "{notice}");
assert!(notice.contains("on any computer with stambha"), "{notice}");
assert!(notice.contains("`stambha log`"), "{notice}");
}
#[test]
+351 -38
View File
@@ -138,6 +138,25 @@ pub fn window(selected: usize, count: usize, fits: usize) -> usize {
.min(count.saturating_sub(fits))
}
/// A finished step's text, as the screen and the log's `STEP` line give it:
/// its title, where a failed step was (`at`, as the PCI function a probe
/// stopped in), then its result, which may be empty, and its whole seconds
/// when there are any: "Starting the GPU (NVIDIA GeForce RTX 5080, 9 s)".
pub fn finished_step(title: &str, at: Option<&str>, result: &str, seconds: u64) -> String {
let mut text = String::from(title);
if let Some(at) = at.filter(|at| !at.is_empty()) {
text.push_str(" at ");
text.push_str(at);
}
match (result.is_empty(), seconds) {
(true, 0) => {}
(true, seconds) => text.push_str(&format!(" ({seconds} s)")),
(false, 0) => text.push_str(&format!(" ({result})")),
(false, seconds) => text.push_str(&format!(" ({result}, {seconds} s)")),
}
text
}
/// `completed` of `total` as a percentage rounded down, so 100 needs
/// completion; `None` for an unknown or inconsistent total. Wide
/// intermediates keep full-width byte counts exact.
@@ -193,46 +212,129 @@ pub fn present_changed<C: Copy + PartialEq>(
true
}
/// The logo at (`u`, `v`) of its unit square: a rounded square split by an
/// S curve into a blue half and an orange half, each lighter at the top.
/// `None` outside it and in the gap between the halves.
pub fn logo_pixel(u: f32, v: f32) -> Option<u32> {
const RADIUS: f32 = 0.2;
// Outside a rounded corner.
let cx = u.clamp(RADIUS, 1.0 - RADIUS);
let cy = v.clamp(RADIUS, 1.0 - RADIUS);
let (dx, dy) = (u - cx, v - cy);
if !(0.0..1.0).contains(&u) || !(0.0..1.0).contains(&v) || dx * dx + dy * dy > RADIUS * RADIUS {
/// The logo's sample (`x`, `y`) of a `side` by `side` grid, taken at the
/// sample's centre: Stambha's pillar on a rounded indigo tile, the shapes
/// and colours of `identity/icon/stambha-icon.svg` in integers. `None`
/// outside the tile's rounded corners.
pub fn logo_pixel(x: u32, y: u32, side: u32) -> Option<u32> {
// The icon's 1024-unit square in tenths of a unit, as its shapes are
// written: the sample's centre, rounded down.
let at = |i: u32| (2 * i64::from(i) + 1) * i64::from(SQUARE / 2) / i64::from(side.max(1));
let (x, y) = (at(x), at(y));
let square = i64::from(SQUARE);
if !(0..square).contains(&x) || !(0..square).contains(&y) {
return None;
}
// One period of a sine, from two parabolas.
let t = 2.0 * v;
let wave = if t < 1.0 {
4.0 * t * (1.0 - t)
} else {
-4.0 * (t - 1.0) * (2.0 - t)
};
let side = u - (0.5 - 0.12 * wave);
if side.abs() < 0.022 {
// Outside a rounded corner: radius 0.2 of the square.
let radius = square / 5;
let (dx, dy) = (
x - x.clamp(radius, square - radius),
y - y.clamp(radius, square - radius),
);
if dx * dx + dy * dy > radius * radius {
return None;
}
let (top, bottom) = if side < 0.0 {
(0x5fe3c8, 0x2f6fe0)
let colour = if pillar(x, y) {
// Gold to saffron, over the pillar's height.
mix(0xffd27a, 0xf07a28, y - 1178, 8704 - 1178)
} else {
(0xffc46b, 0xe2522a)
mix(0x2b3a8c, 0x141a3d, y, square)
};
Some(mix(top, bottom, v))
Some(match polygon(&SHINE, x, y) {
// The highlight, #FFF1C9 at 45% over what is under it.
true => mix(colour, 0xfff1c9, 45, 100),
false => colour,
})
}
/// `from` blended toward `to` by `amount`, channel by channel.
fn mix(from: u32, to: u32, amount: f32) -> u32 {
/// The icon's square in tenths of its 1024 units.
const SQUARE: u32 = 10240;
/// Whether (`x`, `y`), in tenths of the icon's units, is on the pillar: its
/// dome, abacus, bell and shaft, and two base steps.
fn pillar(x: i64, y: i64) -> bool {
let rect = |left: i64, top: i64, right: i64, bottom: i64| {
(left..right).contains(&x) && (top..bottom).contains(&y)
};
// The dome: the top half of an ellipse 87 by 56.3 units about (512, 169).
let (rx, ry) = (870, 563);
let (dx, dy) = (x - 5120, y - 1690);
let dome = dy <= 0 && (dx * ry) * (dx * ry) + (dy * rx) * (dy * rx) <= (rx * ry) * (rx * ry);
dome || rect(2918, 1690, 7321, 2509)
|| polygon(&BODY, x, y)
|| rect(3430, 7762, 6809, 8192)
|| rect(2816, 8192, 7424, 8704)
}
/// Whether (`x`, `y`) is inside `points`, by the even-odd rule, in exact
/// integer arithmetic.
fn polygon(points: &[(i16, i16)], x: i64, y: i64) -> bool {
let mut inside = false;
let mut previous = points[points.len() - 1];
for &point in points {
let (xi, yi) = (i64::from(point.0), i64::from(point.1));
let (xj, yj) = (i64::from(previous.0), i64::from(previous.1));
if (yi > y) != (yj > y) {
// Left of the edge's crossing at row `y`, with both sides
// multiplied by the edge's height to stay in integers.
let (left, crossing) = ((x - xi) * (yj - yi), (y - yi) * (xj - xi));
if (yj > yi && left < crossing) || (yj < yi && left > crossing) {
inside = !inside;
}
}
previous = point;
}
inside
}
/// The bell and shaft, one outline: the bell's two curves to the abacus
/// above it, the shaft's tapered sides down to the base.
#[rustfmt::skip]
const BODY: [(i16, i16); 64] = [
(6810, 2642), (6715, 2686), (6656, 2731), (6606, 2776), (6561, 2820), (6519, 2865),
(6479, 2909), (6441, 2954), (6405, 2998), (6370, 3043), (6337, 3087), (6304, 3132),
(6272, 3176), (6242, 3221), (6211, 3266), (6182, 3310), (6153, 3355), (6124, 3399),
(6096, 3444), (6069, 3488), (6042, 3533), (5960, 3533), (5978, 3942), (5997, 4352),
(6015, 4762), (6033, 5171), (6052, 5581), (6070, 5990), (6089, 6400), (6107, 6810),
(6126, 7219), (6144, 7629), (4096, 7629), (4114, 7219), (4133, 6810), (4151, 6400),
(4170, 5990), (4188, 5581), (4207, 5171), (4225, 4762), (4243, 4352), (4262, 3942),
(4280, 3533), (4198, 3533), (4171, 3488), (4144, 3444), (4116, 3399), (4087, 3355),
(4058, 3310), (4029, 3266), (3998, 3221), (3968, 3176), (3936, 3132), (3903, 3087),
(3870, 3043), (3835, 2998), (3799, 2954), (3761, 2909), (3721, 2865), (3679, 2820),
(3634, 2776), (3584, 2731), (3525, 2686), (3430, 2642),
];
/// The pale stripe down the left of the bell and shaft.
#[rustfmt::skip]
const SHINE: [(i16, i16); 82] = [
(3684, 2642), (3849, 2767), (3952, 2891), (4039, 3016), (4119, 3141), (4192, 3265),
(4261, 3390), (4327, 3515), (4402, 3639), (4397, 3764), (4393, 3889), (4388, 4013),
(4383, 4138), (4378, 4263), (4374, 4387), (4369, 4512), (4364, 4637), (4359, 4761),
(4355, 4886), (4350, 5011), (4345, 5135), (4340, 5260), (4335, 5385), (4331, 5509),
(4326, 5634), (4321, 5759), (4316, 5883), (4312, 6008), (4307, 6133), (4302, 6257),
(4297, 6382), (4293, 6507), (4288, 6631), (4283, 6756), (4278, 6881), (4273, 7005),
(4269, 7130), (4264, 7255), (4259, 7379), (4254, 7504), (4250, 7629), (4659, 7629),
(4662, 7504), (4664, 7379), (4667, 7255), (4669, 7130), (4672, 7005), (4674, 6881),
(4677, 6756), (4679, 6631), (4682, 6507), (4684, 6382), (4687, 6257), (4689, 6133),
(4692, 6008), (4695, 5883), (4697, 5759), (4700, 5634), (4702, 5509), (4705, 5385),
(4707, 5260), (4710, 5135), (4712, 5011), (4715, 4886), (4717, 4761), (4720, 4637),
(4722, 4512), (4725, 4387), (4727, 4263), (4730, 4138), (4732, 4013), (4735, 3889),
(4737, 3764), (4740, 3639), (4700, 3515), (4665, 3390), (4629, 3265), (4590, 3141),
(4548, 3016), (4501, 2891), (4447, 2767), (4360, 2642),
];
/// `from` blended toward `to` by `part` of `whole`, clamped to the two, with
/// each channel rounded to nearest.
fn mix(from: u32, to: u32, part: i64, whole: i64) -> u32 {
let whole = whole.max(1);
let part = part.clamp(0, whole);
(0..3).fold(0, |pixel, channel| {
let shift = 16 - 8 * channel;
let (a, b) = (
((from >> shift) & 0xff) as f32,
((to >> shift) & 0xff) as f32,
i64::from((from >> shift) & 0xff),
i64::from((to >> shift) & 0xff),
);
(pixel << 8) | (a + (b - a) * amount + 0.5) as u32
(pixel << 8) | ((a * (whole - part) + b * part + whole / 2) / whole) as u32
})
}
@@ -396,6 +498,30 @@ mod tests {
assert_eq!(window(1, 2, 4), 0);
}
#[test]
fn a_finished_step_carries_its_result_and_seconds() {
assert_eq!(
finished_step("Starting the GPU", None, "", 0),
"Starting the GPU"
);
assert_eq!(
finished_step("Starting the GPU", None, "", 9),
"Starting the GPU (9 s)"
);
assert_eq!(
finished_step("Starting the GPU", None, "NVIDIA GeForce RTX 5080", 0),
"Starting the GPU (NVIDIA GeForce RTX 5080)"
);
assert_eq!(
finished_step("Starting the GPU", Some(""), "NVIDIA GeForce RTX 5080", 9),
"Starting the GPU (NVIDIA GeForce RTX 5080, 9 s)"
);
assert_eq!(
finished_step("Probing PCI", Some("0000:03:00.0"), "stopped", 2),
"Probing PCI at 0000:03:00.0 (stopped, 2 s)"
);
}
#[test]
fn percentages_need_a_consistent_total_and_complete_only_at_the_end() {
assert_eq!(percentage(0, 0), None);
@@ -422,16 +548,203 @@ mod tests {
assert_eq!(disk_size(260 * 1_000_000), "260 MB");
}
/// Whether each channel of `pixel` is within 2 of `expected`'s.
fn near(pixel: u32, expected: u32) -> bool {
(0..3).all(|channel| {
let value = |colour: u32| i32::from((colour >> (8 * channel)) as u8);
(value(pixel) - value(expected)).abs() <= 2
})
}
/// Indigo: more blue than red.
fn tile(pixel: u32) -> bool {
pixel & 0xff > pixel >> 16
}
#[test]
fn the_logo_is_blue_left_orange_right_split_by_a_gap() {
assert_eq!(logo_pixel(0.0, 0.0), None);
assert_eq!(logo_pixel(0.5, 0.0), None);
let blue = logo_pixel(0.15, 0.5).unwrap();
let orange = logo_pixel(0.85, 0.5).unwrap();
assert!(blue & 0xff > blue >> 16);
assert!(orange >> 16 > orange & 0xff);
// The curve bulges left in the upper half and right in the lower.
assert!(logo_pixel(0.45, 0.25).unwrap() >> 16 > 0xc0);
assert!(logo_pixel(0.55, 0.75).unwrap() >> 16 < 0x80);
fn the_logo_is_a_gold_pillar_on_an_indigo_tile() {
// The tile's rounded corners are transparent at any size.
for side in [32, 128, 1024] {
let last = side - 1;
for (x, y) in [(0, 0), (last, 0), (0, last), (last, last)] {
assert_eq!(logo_pixel(x, y, side), None, "{side}: ({x}, {y})");
}
}
// One sample per unit of the icon's 1024.
let at = |x, y| logo_pixel(x, y, 1024).unwrap();
// The tile: indigo at the top to deep navy at the bottom.
assert!(near(at(512, 5), 0x2b3a8c), "{:06x}", at(512, 5));
assert!(near(at(512, 1018), 0x141a3d), "{:06x}", at(512, 1018));
// The dome's top, at 112.7: the tile just above, gold just below.
assert!(tile(at(512, 111)), "{:06x}", at(512, 111));
assert_eq!(at(512, 114), 0xffd27a);
// The abacus, and the tile in the gap between it and the bell.
assert!(near(at(300, 200), 0xfdc871), "{:06x}", at(300, 200));
assert!(tile(at(512, 257)), "{:06x}", at(512, 257));
// The shaft, gold toward saffron, and its pale stripe lighter.
assert!(near(at(512, 563), 0xf69e49), "{:06x}", at(512, 563));
assert!(at(450, 500) & 0xff > (at(540, 500) & 0xff) + 40);
// The base step is wider than the step above it.
assert!(!tile(at(290, 845)));
assert!(tile(at(300, 800)));
assert!(!tile(at(350, 800)));
}
/// The logo `side` pixels square, as `stela-boot`'s `ui::Canvas` draws
/// it: four by four samples a pixel, `ui::BACKGROUND` outside the tile.
fn drawn(side: usize) -> Vec<u32> {
const SAMPLES: usize = 4;
let mut pixels = Vec::new();
for py in 0..side {
for px in 0..side {
let mut sum = [0u32; 3];
for sy in 0..SAMPLES {
for sx in 0..SAMPLES {
let colour = logo_pixel(
(px * SAMPLES + sx) as u32,
(py * SAMPLES + sy) as u32,
(side * SAMPLES) as u32,
)
.unwrap_or(BACKGROUND);
for (channel, total) in sum.iter_mut().enumerate() {
*total += (colour >> (16 - 8 * channel)) & 0xff;
}
}
}
let n = (SAMPLES * SAMPLES) as u32;
pixels.push(
sum.iter()
.fold(0, |pixel, total| (pixel << 8) | ((total + n / 2) / n)),
);
}
}
pixels
}
/// `ui::BACKGROUND` and `ui::TEXT`.
const BACKGROUND: u32 = 0x18191c;
const TEXT: u32 = 0xe6e7ea;
/// The console font (`stela-boot`'s `console::font`): PSF1, 8 by 16.
static SPLEEN: &[u8] = include_bytes!("../../stela-boot/src/console/spleen-8x16.psfu");
fn glyph(character: u8, x: usize, y: usize) -> bool {
assert_eq!(SPLEEN[..2], [0x36, 0x04]);
SPLEEN[4 + usize::from(character) * 16 + y] & (0x80 >> x) != 0
}
/// The page header `ui::Canvas::header` draws, `width` units wide at
/// `scale`: the logo and the name, together centred.
fn header(width: usize, scale: usize, name: &str) -> (usize, Vec<u32>) {
const LOGO: usize = 32;
const HEADER: usize = 88;
let (columns, rows) = (width * scale, HEADER * scale);
let mut pixels = vec![BACKGROUND; columns * rows];
let name_width = name.len() * 8 * 2;
let gap = 12;
let left = (width - (LOGO + gap + name_width)) / 2;
let top = 28;
let logo = drawn(LOGO * scale);
for (index, &colour) in logo.iter().enumerate() {
let (x, y) = (index % (LOGO * scale), index / (LOGO * scale));
pixels[(top * scale + y) * columns + left * scale + x] = colour;
}
let set = |y| name.bytes().any(|c| (0..8).any(|x| glyph(c, x, y)));
let first = (0..16).find(|&y| set(y)).unwrap();
let last = (0..16).rev().find(|&y| set(y)).unwrap();
let text_top = (top + LOGO / 2) - (first + last + 1);
let s = 2 * scale;
for (index, character) in name.bytes().enumerate() {
let x0 = (left + LOGO + gap + index * 16) * scale;
for gy in 0..16 {
for gx in (0..8).filter(|&gx| glyph(character, gx, gy)) {
for dy in 0..s {
let row = text_top * scale + gy * s + dy;
let start = row * columns + x0 + gx * s;
pixels[start..start + s].fill(TEXT);
}
}
}
}
(columns, pixels)
}
/// A PNG of `pixels`, rows of `width`, stored without compression.
fn png(width: usize, pixels: &[u32]) -> Vec<u8> {
fn crc(bytes: &[u8]) -> u32 {
let mut crc = !0u32;
for &byte in bytes {
crc ^= u32::from(byte);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
}
}
!crc
}
let mut raw = Vec::new();
for row in pixels.chunks(width) {
raw.push(0);
for &pixel in row {
raw.extend_from_slice(&[(pixel >> 16) as u8, (pixel >> 8) as u8, pixel as u8]);
}
}
let mut zlib = vec![0x78, 0x01];
let blocks = raw.chunks(0xffff).count();
for (index, block) in raw.chunks(0xffff).enumerate() {
zlib.push(u8::from(index + 1 == blocks));
let length = block.len() as u16;
zlib.extend_from_slice(&length.to_le_bytes());
zlib.extend_from_slice(&(!length).to_le_bytes());
zlib.extend_from_slice(block);
}
let (mut a, mut b) = (1u32, 0u32);
for &byte in &raw {
a = (a + u32::from(byte)) % 65521;
b = (b + a) % 65521;
}
zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
let mut header = Vec::new();
header.extend_from_slice(&(width as u32).to_be_bytes());
header.extend_from_slice(&((pixels.len() / width) as u32).to_be_bytes());
header.extend_from_slice(&[8, 2, 0, 0, 0]);
let mut file = b"\x89PNG\r\n\x1a\n".to_vec();
for (kind, data) in [(b"IHDR", &header[..]), (b"IDAT", &zlib), (b"IEND", &[])] {
file.extend_from_slice(&(data.len() as u32).to_be_bytes());
let start = file.len();
file.extend_from_slice(kind);
file.extend_from_slice(data);
let sum = crc(&file[start..]);
file.extend_from_slice(&sum.to_be_bytes());
}
file
}
/// The logo and the header render; with `STELA_BRAND_SHOTS=DIR` they
/// are also written to `DIR` as `brand-*.png`, to look at.
#[test]
fn the_logo_and_header_render_as_the_boot_screen_draws_them() {
let mut shots = Vec::new();
let large = (0..1024 * 1024)
.map(|index| logo_pixel(index % 1024, index / 1024, 1024).unwrap_or(BACKGROUND))
.collect::<Vec<_>>();
shots.push((String::from("brand-logo-1024"), 1024, large));
for side in [32, 64, 96] {
shots.push((format!("brand-logo-{side}"), side, drawn(side)));
}
for scale in [1, 2] {
let (width, pixels) = header(480, scale, "Stambha");
// The name's text is drawn right of the logo.
assert!(pixels.contains(&TEXT));
shots.push((format!("brand-header-{scale}x"), width, pixels));
}
let directory = std::env::var_os("STELA_BRAND_SHOTS");
for (name, width, pixels) in &shots {
let file = png(*width, pixels);
assert!(file.starts_with(b"\x89PNG"));
if let Some(directory) = &directory {
let path = std::path::Path::new(directory).join(format!("{name}.png"));
std::fs::write(&path, file).expect("the screenshot is written");
}
}
}
}
+104
View File
@@ -259,6 +259,59 @@ impl Turn {
}
}
/// A part's own time inside one turn, for a part made of pieces it can stop
/// between (one frame, one packet) and leave the rest of to a later turn:
/// a piece starts only while the part has run less than its limit, and the
/// first always does, so a part always gets on. A piece that started runs
/// to its end, so a single piece's time is not bounded here; a part whose
/// one piece is long must be split by its own code.
#[derive(Clone, Copy, Debug)]
pub struct Budget {
started: u64,
limit: u64,
pieces: u32,
cut: bool,
}
impl Budget {
/// A part started at counter value `started` that may start pieces for
/// `limit` ticks.
pub const fn new(started: u64, limit: u64) -> Self {
Self {
started,
limit,
pieces: 0,
cut: false,
}
}
/// Whether the next piece starts, asked at counter value `now`: the
/// first always; a later one while less than the limit has passed
/// since the part started. Once it refuses, it refuses for the rest of
/// the turn.
pub fn allows(&mut self, now: u64) -> bool {
if self.cut {
return false;
}
if self.pieces > 0 && now.wrapping_sub(self.started) >= self.limit {
self.cut = true;
return false;
}
self.pieces = self.pieces.saturating_add(1);
true
}
/// Whether a piece was refused: the part left work for a later turn.
pub const fn cut(&self) -> bool {
self.cut
}
/// The pieces that started.
pub const fn pieces(&self) -> u32 {
self.pieces
}
}
/// What kept guest work for the serving PE waiting past the floor, as one
/// part ends ([`blame`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -541,4 +594,55 @@ mod tests {
assert_eq!(split.line(2, 1_000_000), " piece=5 rest=0");
assert_eq!(split.line(10, 0), " piece=5000000 rest=5000000");
}
/// A part of 1 ms pieces with a 2 ms budget: what runs, and that the
/// rest is left to a later turn.
#[test]
fn a_budget_starts_pieces_until_its_limit_then_cuts_for_the_turn() {
let mut budget = Budget::new(10_000, 2_000);
let mut now = 10_000;
let mut ran = 0;
while budget.allows(now) {
ran += 1;
now += 1_000;
assert!(ran < 100, "the budget never cut");
}
// Pieces starting at 0 and 1 ms ran; the one at 2 ms did not.
assert_eq!(ran, 2);
assert_eq!(budget.pieces(), 2);
assert!(budget.cut());
// Cut stays cut, even asked as if time went back.
assert!(!budget.allows(10_000));
}
/// A part always gets on: its first piece starts however late the
/// turn came to it, and an unused budget leaves nothing behind.
#[test]
fn a_budget_always_starts_the_first_piece() {
let mut late = Budget::new(0, 2_000);
assert!(late.allows(1_000_000));
assert!(!late.allows(1_000_001));
assert!(late.cut());
let mut quick = Budget::new(0, 2_000);
for now in [0, 10, 20] {
assert!(quick.allows(now));
}
assert!(!quick.cut());
assert_eq!(quick.pieces(), 3);
}
/// The boot 23 case: one 101 ms piece cannot be cut, but nothing more
/// starts after it in the same turn.
#[test]
fn a_budget_starts_nothing_after_a_long_piece_and_survives_a_wrap() {
let mut budget = Budget::new(u64::MAX - 500, 2_000);
assert!(budget.allows(u64::MAX - 500));
// The piece took 101 ms on a 1 MHz counter, past the wrap.
assert!(!budget.allows(101_000));
assert!(budget.cut());
let mut within = Budget::new(u64::MAX - 500, 2_000);
assert!(within.allows(u64::MAX - 500));
assert!(within.allows(1_000));
assert!(!within.cut());
}
}
+60
View File
@@ -0,0 +1,60 @@
//! The bits of a shadow page-table leaf (`stela-boot`'s `engine::host`
//! faults): the x86 entry a demand fill, a prefill and fault-around write
//! for a guest page the walk translated.
//!
//! Every leaf is written with Accessed set, and a writable one with Dirty
//! set too. Nothing reads them back: the host keeps no dirty or access
//! tracking in its shadow tables (guest dirty and access state is the
//! guest's own descriptors', which the engine's walker never updates, no
//! FEAT_HAFDBS). Left clear, the processor sets each with a locked update
//! of the entry at the first access, and Dirty at the first write, which
//! costs every freshly written entry (tens of millions a minute after the
//! whole-TLB flushes a guest issues) one or two atomic page-table writes,
//! and may keep a core from merging the four 4 KiB entries of one 16 KiB
//! guest page into one TLB entry.
/// x86 page-table entry bits (Intel SDM Vol. 3A, 4.5, table 4-20).
pub const PRESENT: u64 = 1;
pub const WRITABLE: u64 = 1 << 1;
pub const USER: u64 = 1 << 2;
pub const ACCESSED: u64 = 1 << 5;
pub const DIRTY: u64 = 1 << 6;
pub const NX: u64 = 1 << 63;
/// The rights of a shadow leaf: present, never executable (translated code
/// runs from the code window, not guest pages), writable as the guest's
/// translation is, a user page where SMAP must guard it (`guarded`), and
/// Accessed, with Dirty on a writable leaf.
pub const fn rights(writable: bool, guarded: bool) -> u64 {
PRESENT
| NX
| ACCESSED
| if writable { WRITABLE | DIRTY } else { 0 }
| if guarded { USER } else { 0 }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_leaf_is_accessed_and_a_writable_one_dirty() {
for writable in [false, true] {
for guarded in [false, true] {
let leaf = rights(writable, guarded);
assert_eq!(leaf & (PRESENT | NX | ACCESSED), PRESENT | NX | ACCESSED);
assert_eq!(leaf & WRITABLE != 0, writable);
// Dirty only where a write may set it: a read-only leaf
// stays clean, as the processor would leave it.
assert_eq!(leaf & DIRTY != 0, writable);
assert_eq!(leaf & USER != 0, guarded);
// No other bit: no address, caching or global bits.
let known = PRESENT | WRITABLE | USER | ACCESSED | DIRTY | NX;
assert_eq!(leaf & !known, 0);
}
}
assert_eq!(rights(false, false), 0x8000_0000_0000_0021);
assert_eq!(rights(true, false), 0x8000_0000_0000_0063);
assert_eq!(rights(true, true), 0x8000_0000_0000_0067);
}
}
@@ -89,6 +89,66 @@ impl<const N: usize> StackGuards<N> {
}
}
/// The stack the boot's first stop does its work on: storing the logs runs
/// the USB's drivers, whose frames pass a Linux task's 16 KiB stack, and a
/// stop is often raised on one (a Linux driver's failed probe). Kept once,
/// for the boot.
pub struct StopStack {
start: AtomicU64,
end: AtomicU64,
}
impl Default for StopStack {
fn default() -> Self {
Self::new()
}
}
impl StopStack {
pub const fn new() -> Self {
Self {
start: AtomicU64::new(0),
end: AtomicU64::new(0),
}
}
/// Keeps the stack whose usable bytes are `usable`. False for an empty
/// range or when one is kept already.
pub fn keep(&self, usable: Range<u64>) -> bool {
if usable.start == 0 || usable.is_empty() {
return false;
}
if self
.start
.compare_exchange(0, usable.start, Ordering::AcqRel, Ordering::Relaxed)
.is_err()
{
return false;
}
self.end.store(usable.end, Ordering::Release);
true
}
/// Whether a stack is kept.
pub fn kept(&self) -> bool {
self.start.load(Ordering::Acquire) != 0
}
/// The top a stop running at stack pointer `pointer` moves to: none
/// while no stack is kept, or when `pointer` lies on it already, as a
/// stop within the stop does, whose caller's frames are below it.
pub fn top_for(&self, pointer: u64) -> Option<u64> {
let end = self.end.load(Ordering::Acquire);
let start = self.start.load(Ordering::Acquire);
if start == 0 || end <= start {
return None;
}
// At the top itself nothing is pushed yet: a pointer there is on
// the stack too.
(!(start..=end).contains(&pointer)).then_some(end)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -140,6 +200,37 @@ mod tests {
);
}
#[test]
fn a_stop_on_a_linux_task_stack_moves_to_the_stop_stack() {
// igpu3: amdgpu's failed probe stopped the boot on its 16 KiB task
// stack at 0xffff_8008_0075_8000, and the log's store through the
// USB's drivers ran off its bottom.
let task = 0xffff_8008_0075_8000..0xffff_8008_0075_c000_u64;
let stop = StopStack::new();
assert!(!stop.kept());
assert_eq!(stop.top_for(task.end - 0x200), None, "none kept yet");
const STOP_BYTES: u64 = 1 << 20;
assert!(stop.keep(TOP - STOP_BYTES..TOP));
assert!(stop.kept());
assert!(!stop.keep(0x1000..0x2000), "kept once");
assert_eq!(stop.top_for(task.start + 0x100), Some(TOP));
// A stop within the stop, already on it, stays where it is.
assert_eq!(stop.top_for(TOP - 0x800), None);
assert_eq!(stop.top_for(TOP), None);
assert_eq!(stop.top_for(TOP - STOP_BYTES), None);
// Just past either end is another stack.
assert_eq!(stop.top_for(TOP + 8), Some(TOP));
assert_eq!(stop.top_for(TOP - STOP_BYTES - 8), Some(TOP));
}
#[test]
fn an_empty_stop_stack_is_not_kept() {
let stop = StopStack::new();
assert!(!stop.keep(0x1000..0x1000));
assert!(!stop.keep(0..0x1000));
assert_eq!(stop.top_for(0x800), None);
}
#[test]
fn an_empty_range_is_not_recorded() {
let guards = StackGuards::<1>::new();
+133 -17
View File
@@ -10,9 +10,14 @@
//! [`message`]) with the interrupted instruction pointer.
//!
//! The counter counts unhalted core cycles, whose rate follows the core's
//! clock: [`start_value`] counts [`CLOCK_FACTOR`] times the time-stamp
//! counter's rate, so the NMI never comes before the limit, and comes at
//! most `CLOCK_FACTOR` times later on a core that runs at its base clock.
//! clock, so it does not time the limit itself: it overflows after
//! [`CHECK_SECONDS`] of cycles at the time-stamp counter's rate
//! ([`start_value`]), and an overflow that comes before the limit by the
//! time-stamp counter puts it back for what is left of the limit, its NMI
//! returning ([`check_in`]). The stop then comes within [`CHECK_FLOOR_MS`]
//! of the limit on a core at or above its nominal clock, and within one
//! check of it below, where 0.6.1 counted three times the limit's cycles at
//! once and stopped after 45 to 90 s while saying 30 s (65 s on an i5-10500).
//!
//! Once the other processors run, the counter is off (`--profile` may use
//! it) and they watch instead: each of them, between two slices of its
@@ -36,20 +41,31 @@ pub const LIMIT_SECONDS: u64 = 30;
/// How often at most a returned step puts the counter back.
pub const REARM_SECONDS: u64 = 1;
/// The core clock's bound as a multiple of the time-stamp counter's rate:
/// a turbo clock stays below three times the nominal one.
pub const CLOCK_FACTOR: u64 = 3;
/// How many seconds of cycles at the time-stamp counter's rate the counter
/// counts before its NMI looks at the time ([`check_in`]): a core at a
/// turbo clock overflows sooner and one below its nominal clock later, so
/// the look, not the count, decides when the limit has passed.
pub const CHECK_SECONDS: u64 = 5;
/// The value a `width`-bit up-counter starts from to overflow after the
/// limit's cycles at [`CLOCK_FACTOR`] times `tsc_hz`; `None` when the
/// count does not fit or the rate is unknown.
/// The fewest cycles a check puts the counter back for, in milliseconds at
/// the time-stamp counter's rate: a core above its nominal clock overflows
/// before each rest of the limit runs out, and this bounds how many such
/// checks it takes and how late past the limit the last one comes.
pub const CHECK_FLOOR_MS: u64 = 500;
/// The value a `width`-bit up-counter starts from to overflow after
/// [`CHECK_SECONDS`] of cycles at `tsc_hz`; `None` when the count does not
/// fit or the rate is unknown.
pub fn start_value(tsc_hz: u64, width: u32) -> Option<u64> {
if tsc_hz == 0 || !(32..=64).contains(&width) {
counter_start(tsc_hz.checked_mul(CHECK_SECONDS)?, width)
}
/// The value a `width`-bit up-counter starts from to overflow after
/// `cycles`; `None` when they do not fit.
pub fn counter_start(cycles: u64, width: u32) -> Option<u64> {
if !(32..=64).contains(&width) {
return None;
}
let cycles = tsc_hz
.checked_mul(LIMIT_SECONDS)?
.checked_mul(CLOCK_FACTOR)?;
let mask = u64::MAX >> (64 - width);
if cycles == 0 || cycles > mask {
return None;
@@ -57,6 +73,24 @@ pub fn start_value(tsc_hz: u64, width: u32) -> Option<u64> {
Some((mask - cycles).wrapping_add(1) & mask)
}
/// What the counter's overflow NMI at `now` does, the counter last put back
/// by a returned step at `armed_at`, all by the time-stamp counter at
/// `tsc_hz`: before the limit, the cycles to count again (what is left of
/// the limit, at most [`CHECK_SECONDS`] and at least [`CHECK_FLOOR_MS`]),
/// the NMI then returning; `None` once nothing returned for the whole
/// limit, and the NMI is the watchdog's stop ([`attribute`]). A put-back
/// time after `now` counts as none passed.
pub fn check_in(armed_at: u64, now: u64, tsc_hz: u64) -> Option<u64> {
let limit = tsc_hz.checked_mul(LIMIT_SECONDS)?;
let quiet = now.saturating_sub(armed_at);
if tsc_hz == 0 || quiet >= limit {
return None;
}
let check = tsc_hz.saturating_mul(CHECK_SECONDS);
let floor = tsc_hz.saturating_mul(CHECK_FLOOR_MS) / 1000;
Some((limit - quiet).min(check).max(floor.max(1)))
}
/// When a step returning at `now` next puts the counter back.
pub fn next_rearm(now: u64, tsc_hz: u64) -> u64 {
now.saturating_add(tsc_hz.saturating_mul(REARM_SECONDS).max(1))
@@ -472,18 +506,100 @@ mod tests {
const HZ: u64 = 2_400_000_000;
#[test]
fn the_counter_overflows_after_the_limit_at_the_bounded_clock() {
fn the_counter_overflows_after_one_check_at_the_nominal_clock() {
let start = start_value(HZ, 48).unwrap();
assert_eq!((1u64 << 48) - start, HZ * LIMIT_SECONDS * CLOCK_FACTOR);
assert_eq!((1u64 << 48) - start, HZ * CHECK_SECONDS);
let start = start_value(HZ, 64).unwrap();
assert_eq!(start.wrapping_neg(), HZ * LIMIT_SECONDS * CLOCK_FACTOR);
// A 32-bit counter cannot hold 216 G cycles; no rate, no counter.
assert_eq!(start.wrapping_neg(), HZ * CHECK_SECONDS);
assert_eq!(counter_start(1000, 48), Some((1 << 48) - 1000));
assert_eq!(counter_start(0, 48), None);
// A 32-bit counter cannot hold 12 G cycles; no rate, no counter.
assert_eq!(start_value(HZ, 32), None);
assert_eq!(start_value(0, 48), None);
assert_eq!(start_value(HZ, 16), None);
assert_eq!(start_value(u64::MAX / 2, 64), None);
}
/// When the watchdog stops a step that never returns on a core whose
/// clock is `ratio` (in hundredths) of the time-stamp counter's rate,
/// in milliseconds by the time-stamp counter: each overflow comes
/// after its cycles at that clock, and [`check_in`] decides.
fn stopped_after_ms(ratio: u64) -> u64 {
let armed_at = 1 << 40;
let mut now = armed_at;
let mut cycles = HZ * CHECK_SECONDS;
let mut checks = 0;
loop {
now += cycles * 100 / ratio;
match check_in(armed_at, now, HZ) {
Some(next) => cycles = next,
None => {
let observation = Observation {
armed: true,
armed_at,
step_began: armed_at,
task: 1,
sequence: 1,
now,
tsc_hz: HZ,
};
// The stop's NMI is the watchdog's, past the limit.
assert!(attribute(&observation).is_some());
return (now - armed_at) * 1000 / HZ;
}
}
checks += 1;
assert!(checks < 100, "the checks never end at {ratio}%");
}
}
#[test]
fn a_step_that_never_returns_stops_near_the_limit_at_any_clock() {
let limit = LIMIT_SECONDS * 1000;
// At or above the nominal clock (an i5-10500 turbos at 1.45 times
// it, where 0.6.1's count of three limits stopped after 65 s):
// within the floor of the limit.
for ratio in [100, 145, 200, 300, 450] {
let stopped = stopped_after_ms(ratio);
assert!(
(limit..limit + CHECK_FLOOR_MS).contains(&stopped),
"{ratio}%: {stopped} ms"
);
}
// Below it, within the slower clock's one check.
for ratio in [50, 80] {
let stopped = stopped_after_ms(ratio);
let late = CHECK_SECONDS * 1000 * (100 - ratio) / ratio;
assert!(
(limit..=limit + late).contains(&stopped),
"{ratio}%: {stopped} ms"
);
}
}
#[test]
fn a_check_counts_what_is_left_of_the_limit() {
let armed_at = 1 << 40;
// Early on, one whole check; near the end, what is left; past the
// limit, the stop.
assert_eq!(
check_in(armed_at, armed_at + HZ, HZ),
Some(HZ * CHECK_SECONDS)
);
assert_eq!(check_in(armed_at, armed_at + 28 * HZ, HZ), Some(2 * HZ));
assert_eq!(
check_in(armed_at, armed_at + LIMIT_SECONDS * HZ - 1, HZ),
Some(HZ * CHECK_FLOOR_MS / 1000)
);
assert_eq!(check_in(armed_at, armed_at + LIMIT_SECONDS * HZ, HZ), None);
// A put-back time after the NMI's reading: none passed.
assert_eq!(
check_in(armed_at, armed_at - HZ, HZ),
Some(HZ * CHECK_SECONDS)
);
assert_eq!(check_in(armed_at, armed_at, 0), None);
}
#[test]
fn a_returned_step_puts_the_counter_back_once_a_second_at_most() {
assert_eq!(next_rearm(10, HZ), 10 + HZ);
+9 -9
View File
@@ -326,7 +326,7 @@ pub fn stop_reason(text: &str) -> Option<&str> {
/// log took them. A stop that left no screen, as one after the GPU's
/// reset, is then told at the next start.
pub fn carried_notice(reason: Option<&str>, in_log: bool) -> String {
let mut notice = String::from("The last start of Stela on this PC stopped");
let mut notice = String::from("The last start of Stambha on this PC stopped");
if let Some(reason) = reason {
notice.push_str(": ");
match reason.char_indices().nth(REASON_CHARACTERS) {
@@ -338,8 +338,8 @@ pub fn carried_notice(reason: Option<&str>, in_log: bool) -> String {
}
}
notice.push_str(if in_log {
". This PC kept its last lines, now in the log on this USB: on any computer with stela, \
plug in this USB and run `stela log`, which saves it to log.txt; include that file in a \
". This PC kept its last lines, now in the log on this USB: on any computer with stambha, \
plug in this USB and run `stambha log`, which saves it to log.txt; include that file in a \
report."
} else {
". This PC keeps its last lines, but the log on this USB did not take them; they stay \
@@ -386,15 +386,15 @@ impl FirmwareCall {
Self::Record => (
"to keep this stop's last lines",
"this PC keeps no record of the stop; the failure before this line is why \
Stela stopped",
Stambha stopped",
),
Self::BootNext => (
"to start Stela again after the restart macOS asked for",
"to start Stambha again after the restart macOS asked for",
"the PC does not restart by itself",
),
};
Some(alloc::format!(
"{FAULT_WORDS}, which Stela called {purpose} ({exception}): {outcome}"
"{FAULT_WORDS}, which Stambha called {purpose} ({exception}): {outcome}"
))
}
}
@@ -449,11 +449,11 @@ mod tests {
fn the_carried_notice_says_why_and_where_the_lines_are() {
let logged = carried_notice(Some("GPU startup exceeded its deadline"), true);
assert!(logged.starts_with(
"The last start of Stela on this PC stopped: GPU startup exceeded its deadline. "
"The last start of Stambha on this PC stopped: GPU startup exceeded its deadline. "
));
assert!(logged.contains("`stela log`"));
assert!(logged.contains("`stambha log`"));
let kept = carried_notice(None, false);
assert!(kept.starts_with("The last start of Stela on this PC stopped. "));
assert!(kept.starts_with("The last start of Stambha on this PC stopped. "));
assert!(kept.contains("did not take them"));
// A long reason is cut on a character, not a byte.
let long = "é".repeat(REASON_CHARACTERS + 5);
+1 -1
View File
@@ -683,7 +683,7 @@ impl Missing {
lacks.push_str(name);
}
refuse!(
"this PC's CPU lacks {lacks}; Stela needs an x86-64-v2 CPU (Intel Nehalem, AMD \
"this PC's CPU lacks {lacks}; Stambha needs an x86-64-v2 CPU (Intel Nehalem, AMD \
Bulldozer or newer)",
lacks = %lacks
)
+2 -2
View File
@@ -1339,7 +1339,7 @@ fn a_missing_floor_names_each_feature() {
assert_eq!(missing.names().collect::<Vec<_>>(), ["SSE4.2", "POPCNT"]);
assert_eq!(
missing.refusal().to_string(),
"this PC's CPU lacks SSE4.2 and POPCNT; Stela needs an x86-64-v2 CPU (Intel Nehalem, \
"this PC's CPU lacks SSE4.2 and POPCNT; Stambha needs an x86-64-v2 CPU (Intel Nehalem, \
AMD Bulldozer or newer)"
);
for (field, bit, name) in [(0, 0, "SSE3"), (0, 9, "SSSE3"), (0, 13, "CX16")] {
@@ -1352,7 +1352,7 @@ fn a_missing_floor_names_each_feature() {
changed.records[0].edx &= !(1 << 25);
assert_eq!(
refusal(changed).refusal().to_string(),
"this PC's CPU lacks SSE and a valid PAT setting; Stela needs an x86-64-v2 CPU (Intel Nehalem, AMD \
"this PC's CPU lacks SSE and a valid PAT setting; Stambha needs an x86-64-v2 CPU (Intel Nehalem, AMD \
Bulldozer or newer)"
);
}
+87
View File
@@ -0,0 +1,87 @@
//! What the boot checks of a video BIOS image it gives a GPU's driver as
//! the function's platform ROM, and where it places an expansion ROM BAR
//! firmware left unassigned.
//!
//! amdgpu takes an image only when it is an ATOM BIOS (`check_atom_bios`);
//! a PCI expansion ROM names the device it is for in its PCI data
//! structure (PCI Firmware 3.0, 5.1.2). The ROM BAR is placed as Linux's
//! PCI core places an unassigned resource: aligned to its size, in the
//! upstream bridge's non-prefetchable window, clear of every BAR and window
//! decoded below that bridge (`pci_assign_resource`, `pbus_size_mem`).
use core::ops::Range;
/// Whether `image` is an ATOM BIOS as `check_atom_bios` judges one of
/// `image.len()` bytes: the ROM signature, a header pointer at 0x48 and
/// "ATOM" (or "MOTA") four bytes after it.
pub fn atom(image: &[u8]) -> bool {
if image.len() < 0x49 || image[0] != 0x55 || image[1] != 0xaa {
return false;
}
let header = usize::from(u16::from_le_bytes([image[0x48], image[0x49]]));
if header == 0 {
return false;
}
let at = header + 4;
image
.get(at..at + 4)
.is_some_and(|word| word == b"ATOM" || word == b"MOTA")
}
/// The vendor and device IDs the first image of expansion ROM `image`
/// names in its PCI data structure, if it has one.
pub fn names(image: &[u8]) -> Option<(u16, u16)> {
if image.get(..2)? != [0x55, 0xaa] {
return None;
}
let at = usize::from(u16::from_le_bytes([*image.get(0x18)?, *image.get(0x19)?]));
let data = image.get(at..at + 8)?;
if &data[..4] != b"PCIR" {
return None;
}
Some((
u16::from_le_bytes([data[4], data[5]]),
u16::from_le_bytes([data[6], data[7]]),
))
}
/// The bytes an expansion ROM BAR decodes, from what it reads back after
/// all ones were written to its address bits (`pci_size`): `None` for a
/// function without one.
pub fn rom_size(read_back: u32) -> Option<u32> {
let mask = read_back & 0xffff_f800;
(mask != 0).then(|| (!mask).wrapping_add(1))
}
/// A bridge's non-prefetchable memory window, from its register 0x20
/// (memory base and limit); `None` where it forwards none.
pub fn bridge_window(word: u32) -> Option<Range<u64>> {
let base = u64::from(word & 0xfff0) << 16;
let limit = (u64::from(word >> 16 & 0xfff0) << 16) | 0xf_ffff;
(base <= limit).then(|| base..limit + 1)
}
/// The lowest place for `bytes` (a power of two) aligned to its size in
/// `window` that overlaps none of `used`, as Linux places a resource it
/// assigns in its bridge's window.
pub fn place(window: &Range<u64>, used: &[Range<u64>], bytes: u64) -> Option<u64> {
if bytes == 0 || !bytes.is_power_of_two() {
return None;
}
let mut start = window.start.next_multiple_of(bytes);
while start.checked_add(bytes)? <= window.end {
let end = start + bytes;
match used
.iter()
.filter(|range| range.start < end && start < range.end)
.map(|range| range.end)
.max()
{
None => return Some(start),
Some(past) => start = past.next_multiple_of(bytes),
}
}
None
}
#[cfg(test)]
mod tests;
Loaded 100 of 1041 files, more files were not shown because too many files have changed in this diff. Show more