Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8cb516b00 | ||
|
|
d6d1ad81cf | ||
|
|
db47becab8 | ||
|
|
853dd544f3 | ||
|
|
fab2832b73 | ||
|
|
038cc17f20 | ||
|
|
ebe7fd89d5 | ||
|
|
8ea0ef4e15 | ||
|
|
252ab84f1a | ||
|
|
485509a41e | ||
|
|
80bf54e220 |
No files matched your search
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.5",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -232,9 +232,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.8.0"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
|
||||
checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
@@ -321,7 +321,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.5",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -355,7 +355,7 @@ dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -450,9 +450,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
version = "1.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
|
||||
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
@@ -509,9 +509,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.7"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
@@ -561,7 +561,7 @@ dependencies = [
|
||||
"defmt-parser",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -586,9 +586,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
@@ -598,7 +598,7 @@ checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -621,7 +621,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -667,9 +667,9 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
@@ -705,15 +705,15 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
version = "1.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
||||
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
@@ -1244,9 +1244,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.5"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
|
||||
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
@@ -1274,15 +1274,15 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
|
||||
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
@@ -1291,9 +1291,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.190"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
@@ -1309,9 +1309,9 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
@@ -1412,9 +1412,9 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.81"
|
||||
version = "0.10.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
|
||||
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
@@ -1443,9 +1443,9 @@ checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.117"
|
||||
version = "0.9.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
||||
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -1516,9 +1516,9 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plist"
|
||||
version = "1.10.1"
|
||||
version = "1.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"
|
||||
checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"indexmap",
|
||||
@@ -1829,9 +1829,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.5"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"errno",
|
||||
@@ -1856,9 +1856,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
@@ -1975,7 +1975,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2118,7 +2118,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-boot-core"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -2126,6 +2126,7 @@ dependencies = [
|
||||
"stela-contracts",
|
||||
"stela-crypto",
|
||||
"stela-driver-base",
|
||||
"stela-driver-core",
|
||||
"stela-drivers",
|
||||
"stela-engine",
|
||||
"stela-formats",
|
||||
@@ -2138,7 +2139,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-c-build"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -2149,7 +2150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-cli"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"anyhow",
|
||||
@@ -2193,7 +2194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-compiler"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"rustc_apfloat",
|
||||
"serde",
|
||||
@@ -2202,14 +2203,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 +2224,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-dev"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2242,7 +2243,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-driver-audio"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
"stela-driver-base",
|
||||
@@ -2251,7 +2252,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-driver-base"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"sha2",
|
||||
@@ -2263,7 +2264,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-driver-core"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
"stela-contracts",
|
||||
@@ -2272,7 +2273,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-driver-gpu"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"cc",
|
||||
@@ -2284,12 +2285,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 +2307,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-driver-storage"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"stela-driver-base",
|
||||
"stela-driver-core",
|
||||
@@ -2313,7 +2315,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-drivers"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
"stela-contracts",
|
||||
@@ -2328,7 +2330,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-engine"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hex",
|
||||
@@ -2347,14 +2349,14 @@ dependencies = [
|
||||
|
||||
[[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 +2374,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-gpu-maintenance"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -2389,7 +2391,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-linux"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -2403,7 +2405,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-loader"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"hex",
|
||||
@@ -2426,7 +2428,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-metal-input"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"stela-contracts",
|
||||
"stela-crypto",
|
||||
@@ -2434,7 +2436,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-runtime"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"getrandom 0.2.17",
|
||||
@@ -2460,7 +2462,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-soc"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"hex",
|
||||
@@ -2480,7 +2482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-soc-data"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"sha2",
|
||||
@@ -2491,7 +2493,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stela-tls"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"aes 0.9.3",
|
||||
"aes-gcm 0.11.1",
|
||||
@@ -2537,9 +2539,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.8"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -2563,7 +2565,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2607,7 +2609,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2892,12 +2894,11 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
|
||||
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
@@ -2905,9 +2906,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-futures"
|
||||
version = "0.4.79"
|
||||
version = "0.4.80"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
|
||||
checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"tokio",
|
||||
@@ -2916,9 +2917,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.129"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
|
||||
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
@@ -2926,31 +2927,31 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.129"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
|
||||
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.129"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
|
||||
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.106"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
|
||||
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
@@ -3082,7 +3083,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.5.0"
|
||||
version = "0.6.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -3099,6 +3100,7 @@ dependencies = [
|
||||
"stela-cli",
|
||||
"stela-compiler",
|
||||
"stela-contracts",
|
||||
"stela-driver-core",
|
||||
"stela-drivers",
|
||||
"stela-engine",
|
||||
"stela-formats",
|
||||
@@ -3127,7 +3129,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -3148,7 +3150,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -3204,7 +3206,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -61,7 +61,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"
|
||||
|
||||
@@ -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
|
||||
@@ -67,36 +67,6 @@ 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
|
||||
|
||||
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 9.9 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.8 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.8 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 625 KiB After Width: | Height: | Size: 625 KiB |
|
Before Width: | Height: | Size: 625 KiB After Width: | Height: | Size: 625 KiB |
@@ -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 }
|
||||
|
||||
@@ -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(®isters, "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));
|
||||
}
|
||||
@@ -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| ®ion.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"
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(®ister(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());
|
||||
}
|
||||
@@ -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] {
|
||||
|
||||
@@ -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`"));
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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, ¶m(number), ENODEV));
|
||||
// Another errno or another driver is a refusal.
|
||||
assert!(!probe_answer("i915", I915_GETPARAM, ¶m(number), -22));
|
||||
assert!(!probe_answer("xe", I915_GETPARAM, ¶m(number), ENODEV));
|
||||
}
|
||||
// Any other parameter's -ENODEV is (the chipset ID, slice mask).
|
||||
for number in [4, 46] {
|
||||
assert!(!probe_answer("i915", I915_GETPARAM, ¶m(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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
));
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 "));
|
||||
}
|
||||
@@ -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<_>>());
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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("));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@ pub enum Error {
|
||||
AudioMode,
|
||||
DumpRegister,
|
||||
Number,
|
||||
HostedReimsBase,
|
||||
HostedReimsIrq,
|
||||
HostedReimsIrqMode,
|
||||
UrlScheme,
|
||||
UrlPath,
|
||||
UrlHost,
|
||||
@@ -36,6 +39,10 @@ pub enum Error {
|
||||
NativeCoreCapacity,
|
||||
DuplicateGuestPes,
|
||||
GuestPeCount,
|
||||
CodeWindow,
|
||||
DuplicateCodeWindow,
|
||||
TimerDelay,
|
||||
DuplicateTimerDelay,
|
||||
DisplaySize,
|
||||
MissingRestoreSource,
|
||||
DuplicateRestoreSource,
|
||||
@@ -45,6 +52,8 @@ pub enum Error {
|
||||
DuplicateInstallMedium,
|
||||
MissingInstallSource,
|
||||
DuplicateInstallSource,
|
||||
MediumReadAhead,
|
||||
DuplicateMediumReadAhead,
|
||||
MissingRestoreIdentity,
|
||||
RestoreIdentityCapacity,
|
||||
DuplicateRestoreIdentity,
|
||||
@@ -55,8 +64,14 @@ pub enum Error {
|
||||
DuplicateWifi,
|
||||
MissingWifiKey,
|
||||
DuplicateWifiKey,
|
||||
MissingWifiPrefer,
|
||||
DuplicateWifiPrefer,
|
||||
WifiCountry,
|
||||
DuplicateWifiCountry,
|
||||
Trackpad,
|
||||
DuplicateTrackpad,
|
||||
DuplicateBattery,
|
||||
TestBattery,
|
||||
Usb4Approve,
|
||||
DuplicateUsb4Approve,
|
||||
Ipv4,
|
||||
@@ -66,6 +81,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 +140,10 @@ pub enum Error {
|
||||
WifiNetwork,
|
||||
DuplicateNativeShared,
|
||||
DuplicateNativeBootstrap,
|
||||
AmxNative,
|
||||
DuplicateAmxNative,
|
||||
DuplicateHle,
|
||||
HleId,
|
||||
Constraint(Constraint),
|
||||
Target {
|
||||
argument: TargetArgument,
|
||||
@@ -123,6 +168,7 @@ pub enum Constraint {
|
||||
WifiDependency,
|
||||
Ipv4Gateway,
|
||||
InstallSourceDependency,
|
||||
MediumReadAheadDependency,
|
||||
InstallConfiguration,
|
||||
UpdateDependency,
|
||||
DevelopmentRestore,
|
||||
@@ -134,6 +180,9 @@ pub enum Constraint {
|
||||
DramAlignment,
|
||||
AudioHpetDependency,
|
||||
NativePciIoapicExclusive,
|
||||
LidSleepDependency,
|
||||
TrackpadDependency,
|
||||
CoreTrial,
|
||||
}
|
||||
impl Error {
|
||||
/// The established stela.cfg diagnostic at presentation-only callers.
|
||||
@@ -144,6 +193,15 @@ impl Error {
|
||||
}
|
||||
Self::DumpRegister => "a dump register is x0 to x30",
|
||||
Self::Number => "invalid number in system options",
|
||||
Self::HostedReimsBase => {
|
||||
"--hosted-reims-base needs one nonzero 1 GiB aligned base and excludes --probe-hosted-reims"
|
||||
}
|
||||
Self::HostedReimsIrq => {
|
||||
"--hosted-reims-irq needs auto or one AIC vector, with --hosted-reims-base"
|
||||
}
|
||||
Self::HostedReimsIrqMode => {
|
||||
"--hosted-reims-irq-mode must be poll or event, with --hosted-reims-irq"
|
||||
}
|
||||
Self::UrlScheme => "URL scheme must be http or https",
|
||||
Self::UrlPath => "URL without a path",
|
||||
Self::UrlHost => "URL without a host",
|
||||
@@ -156,6 +214,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 +229,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 +243,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 +262,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 +323,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 +345,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 +375,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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,9 +36,166 @@ 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,
|
||||
PROBE_HOSTED_REIMS => options.probe_hosted_reims = true,
|
||||
HOSTED_REIMS_BASE => {
|
||||
let base = number(value().ok_or(Error::MissingNumericValue)?)?;
|
||||
if options.hosted_reims_base.replace(base).is_some() {
|
||||
return Err(Error::HostedReimsBase);
|
||||
}
|
||||
}
|
||||
HOSTED_REIMS_IRQ => {
|
||||
let requested = value().ok_or(Error::HostedReimsIrq)?;
|
||||
let irq = if requested == "auto" {
|
||||
HostedReimsIrq::Auto
|
||||
} else {
|
||||
let vector = u32::try_from(number(requested)?)
|
||||
.map_err(|_| Error::HostedReimsIrq)?;
|
||||
HostedReimsIrq::Vector(vector)
|
||||
};
|
||||
if options.hosted_reims_irq.replace(irq).is_some() {
|
||||
return Err(Error::HostedReimsIrq);
|
||||
}
|
||||
}
|
||||
HOSTED_REIMS_IRQ_MODE => {
|
||||
let requested = value().ok_or(Error::HostedReimsIrqMode)?;
|
||||
let mode = HostedReimsIrqMode::parse(requested)?;
|
||||
if options.hosted_reims_irq_mode.replace(mode).is_some() {
|
||||
return Err(Error::HostedReimsIrqMode);
|
||||
}
|
||||
}
|
||||
"--monitor-trace" => options.monitor_trace = true,
|
||||
"--display-trace" => options.display_trace = true,
|
||||
"--native-shared-check" => flag(
|
||||
@@ -75,6 +232,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 +297,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 +324,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 +352,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 +545,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));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -8,9 +8,23 @@ pub(super) fn system(options: &System) -> Result<(), Error> {
|
||||
install(options)?;
|
||||
boot_selection(options)?;
|
||||
dram(options)?;
|
||||
if options.hosted_reims_base.is_some_and(|base| {
|
||||
options.probe_hosted_reims || stela_contracts::reims_hosted::Apertures::at(base).is_none()
|
||||
}) {
|
||||
return Err(Error::HostedReimsBase);
|
||||
}
|
||||
if options.hosted_reims_irq.is_some() && options.hosted_reims_base.is_none() {
|
||||
return Err(Error::HostedReimsIrq);
|
||||
}
|
||||
if options.hosted_reims_irq_mode.is_some() && options.hosted_reims_irq.is_none() {
|
||||
return Err(Error::HostedReimsIrqMode);
|
||||
}
|
||||
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 +32,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 +87,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 +110,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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,21 @@ pub fn place(ram: &mut [RamRange], base: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay the DRAM ranges of `ram` out end to end from `base`, keeping any range
|
||||
/// whose host physical address equals `fixed_host` at its fixed guest address
|
||||
/// and keeping `ram` sorted by guest physical address.
|
||||
pub fn place_except_host(ram: &mut [RamRange], base: u64, fixed_host: Option<u64>) {
|
||||
let mut guest = base;
|
||||
for range in ram.iter_mut() {
|
||||
if Some(range.host) == fixed_host {
|
||||
continue;
|
||||
}
|
||||
range.guest = guest;
|
||||
guest += range.bytes;
|
||||
}
|
||||
ram.sort_by_key(|range| range.guest);
|
||||
}
|
||||
|
||||
/// The longest RAM run starting at `guest`, as (host physical, bytes).
|
||||
pub fn run(ram: &[RamRange], guest: u64) -> Option<(u64, u64)> {
|
||||
let index = ram.partition_point(|range| range.guest <= guest);
|
||||
|
||||
@@ -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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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)"
|
||||
);
|
||||
}
|
||||
|
||||