Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44c162cd5f | ||
|
|
082e26a54b | ||
|
|
db47becab8 | ||
|
|
853dd544f3 | ||
|
|
fab2832b73 | ||
|
|
038cc17f20 | ||
|
|
ebe7fd89d5 | ||
|
|
8ea0ef4e15 | ||
|
|
252ab84f1a | ||
|
|
485509a41e | ||
|
|
80bf54e220 |
No files matched your search
@@ -0,0 +1,93 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
foreach ($name in @('REIMS_STELA_INPUT_ROOT', 'REIMS_STELA_TOOLCHAIN', 'REIMS_STELA_KEXT')) {
|
||||
$value = [Environment]::GetEnvironmentVariable($name)
|
||||
if (!$value -or !(Test-Path -LiteralPath $value -PathType Container)) {
|
||||
throw "Runner input directory missing: $name"
|
||||
}
|
||||
}
|
||||
|
||||
$workspace = (Get-Location).ProviderPath
|
||||
$inputRoot = $env:REIMS_STELA_INPUT_ROOT
|
||||
$toolchain = $env:REIMS_STELA_TOOLCHAIN
|
||||
$output = Join-Path $workspace 'artifacts/hosted-efi'
|
||||
$guest = Join-Path $workspace 'target/guest'
|
||||
New-Item -Path $output, $guest -ItemType Directory -Force | Out-Null
|
||||
|
||||
# Work on copies of the lab's prepared source trees so the build cannot alter them.
|
||||
foreach ($name in @('linux', 'xnu')) {
|
||||
$source = Join-Path $inputRoot "third_party/$name"
|
||||
$destination = Join-Path $workspace "third_party/$name"
|
||||
if (!(Test-Path -LiteralPath $source -PathType Container)) {
|
||||
throw "Source tree missing: $source"
|
||||
}
|
||||
& robocopy $source $destination /E /XD .git /R:2 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Host
|
||||
if ($LASTEXITCODE -ge 8) {
|
||||
throw "Copying $name failed with robocopy exit $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
# The generated include references only the Reims kext objects provisioned on this runner.
|
||||
$include = Join-Path $inputRoot 'target/guest/ReimsGraphics.kext.rs'
|
||||
Copy-Item -LiteralPath $include -Destination $guest
|
||||
$kext = (Resolve-Path -LiteralPath $env:REIMS_STELA_KEXT).Path.Replace('\', '/')
|
||||
$entries = Select-String -LiteralPath $include -Pattern 'include_bytes!\("(.+)"\)' -AllMatches
|
||||
if (!$entries) { throw 'The generated Reims kext include is empty' }
|
||||
$kextHashes = foreach ($entry in $entries) {
|
||||
foreach ($match in $entry.Matches) {
|
||||
$path = $match.Groups[1].Value.Replace('\\', '/')
|
||||
if (!$path.StartsWith("$kext/", [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Kext input outside the configured bundle: $path"
|
||||
}
|
||||
$hash = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
"$hash $($path.Substring($kext.Length + 1))"
|
||||
}
|
||||
}
|
||||
$kextHashes | Set-Content -LiteralPath (Join-Path $output 'ReimsGraphics.SHA256SUMS.txt') -Encoding ascii
|
||||
|
||||
$rust = Join-Path $toolchain 'rustup/toolchains/1.99.1-x86_64-pc-windows-gnullvm/bin'
|
||||
$clang = Join-Path $toolchain 'portable/msys64/clang64/bin'
|
||||
$msys = Join-Path $toolchain 'portable/msys64/usr/bin'
|
||||
$env:PATH = "$rust;$clang;$msys;$env:PATH"
|
||||
$env:CARGO_HOME = Join-Path $toolchain 'cargo'
|
||||
$env:RUSTUP_HOME = Join-Path $toolchain 'rustup'
|
||||
$env:CARGO_TARGET_DIR = Join-Path $workspace 'target/hosted-efi-ci'
|
||||
$env:CARGO_BUILD_JOBS = '4'
|
||||
$env:CC = 'clang'
|
||||
$env:CXX = 'clang++'
|
||||
$env:AR = 'llvm-ar'
|
||||
$env:CC_x86_64_pc_windows_gnullvm = 'clang'
|
||||
$env:CXX_x86_64_pc_windows_gnullvm = 'clang++'
|
||||
$env:AR_x86_64_pc_windows_gnullvm = 'llvm-ar'
|
||||
$env:CC_x86_64_unknown_uefi = 'clang'
|
||||
$env:AR_x86_64_unknown_uefi = 'llvm-ar'
|
||||
|
||||
& cargo.exe build --locked --release --manifest-path crates/stela-boot/Cargo.toml --target x86_64-unknown-uefi --features hosted-reims-graphics
|
||||
if ($LASTEXITCODE -ne 0) { throw "Cargo exited with $LASTEXITCODE" }
|
||||
|
||||
$raw = Join-Path $env:CARGO_TARGET_DIR 'x86_64-unknown-uefi/release/stela.efi'
|
||||
$efi = Join-Path $output 'stambha.efi'
|
||||
& llvm-objcopy.exe --strip-debug $raw $efi
|
||||
if ($LASTEXITCODE -ne 0) { throw "llvm-objcopy exited with $LASTEXITCODE" }
|
||||
|
||||
$headers = & llvm-readobj.exe --file-headers $efi
|
||||
if ($LASTEXITCODE -ne 0 -or ($headers -join [Environment]::NewLine) -notmatch 'IMAGE_FILE_MACHINE_AMD64' -or ($headers -join [Environment]::NewLine) -notmatch 'IMAGE_SUBSYSTEM_EFI_APPLICATION') {
|
||||
throw 'Output is not an x86-64 EFI application'
|
||||
}
|
||||
$headers | Out-Host
|
||||
$sha256 = (Get-FileHash -LiteralPath $efi -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
"$sha256 stambha.efi" | Set-Content -LiteralPath (Join-Path $output 'SHA256SUMS.txt') -Encoding ascii
|
||||
Copy-Item -LiteralPath LICENSE, NOTICE, LICENSES -Destination $output -Recurse
|
||||
|
||||
[ordered]@{
|
||||
source = (& git.exe rev-parse HEAD)
|
||||
target = 'x86_64-unknown-uefi'
|
||||
features = @('hosted-reims-graphics')
|
||||
rustc = (& rustc.exe --version)
|
||||
clang = (& clang.exe --version | Select-Object -First 1)
|
||||
linux_base = (& git.exe -C (Join-Path $inputRoot 'third_party/linux') rev-parse HEAD)
|
||||
xnu_base = (& git.exe -C (Join-Path $inputRoot 'third_party/xnu') rev-parse HEAD)
|
||||
kext_include_sha256 = (Get-FileHash -LiteralPath $include -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
efi_sha256 = $sha256
|
||||
} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $output 'build.json') -Encoding ascii
|
||||
Write-Output "stambha.efi SHA-256: $sha256"
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Build Reims hosted EFI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [codex/reims-hosted-efi]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: [self-hosted, Windows, X64, reims-stela-efi]
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Build the hosted UEFI kernel
|
||||
shell: powershell
|
||||
run: .github/scripts/build-hosted-efi.ps1
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: stambha-hosted-efi
|
||||
path: artifacts/hosted-efi/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -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]]
|
||||
@@ -2103,6 +2103,19 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "stambha-engine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"stela-compiler",
|
||||
"stela-engine",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stela-boot-core"
|
||||
version = "0.6.2"
|
||||
@@ -2331,6 +2344,7 @@ dependencies = [
|
||||
"stela-fingerprint",
|
||||
"stela-formats",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2525,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",
|
||||
@@ -2551,7 +2565,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2595,7 +2609,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2880,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",
|
||||
@@ -2893,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",
|
||||
@@ -2904,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",
|
||||
@@ -2914,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",
|
||||
@@ -3116,7 +3129,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -3137,7 +3150,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -3193,7 +3206,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/stambha-engine",
|
||||
"crates/stela-boot-core",
|
||||
"crates/stela-crypto",
|
||||
"crates/stela-cli",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/canvas-night.svg"><img src="assets/readme/canvas-dawn.svg" width="100%" alt="Stambha: Apple-silicon macOS, on the PC you already have. It runs the real, unmodified Apple-silicon macOS on an ordinary Intel or AMD PC, translating it as it runs. Status: NVIDIA works; AMD and Intel experimental; Wi-Fi works on RTL8852CE; laptops partly; sound and Bluetooth coming. Speed: Stambha 0.6.1 is about 1.5x Stela 0.5.0; more speed is in progress."></picture></p>
|
||||
<p align="center"><a href="https://github.com/garvitsurana271/stambha/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-download-night.svg"><img src="assets/readme/btn-download-dawn.svg" width="32%" alt="Download Stambha 0.6.2"></picture></a> <a href="https://discord.gg/M66z9fPJy5"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-discord-night.svg"><img src="assets/readme/btn-discord-dawn.svg" width="32%" alt="Join the Discord"></picture></a> <a href="https://garvitsurana271.github.io/stambha/"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-website-night.svg"><img src="assets/readme/btn-website-dawn.svg" width="32%" alt="Website"></picture></a></p>
|
||||
<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/canvas-night.svg"><img src="assets/readme/canvas-dawn.svg" width="100%" alt="Stambha: Apple-silicon macOS, on the PC you already have. It runs the real, unmodified Apple-silicon macOS on an ordinary Intel or AMD PC, translating it as it runs. Status: NVIDIA works; AMD experimental; Intel in testing; Wi-Fi works on RTL8852CE; laptops partly; sound and Bluetooth coming. Speed: Stambha 0.6.1 is about 1.5x Stela 0.5.0; more speed is in progress."></picture></p>
|
||||
<p align="center"><a href="https://github.com/garvitsurana271/stambha/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-download-night.svg"><img src="assets/readme/btn-download-dawn.svg" width="32%" alt="Download Stambha 0.6.1"></picture></a> <a href="https://discord.gg/M66z9fPJy5"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-discord-night.svg"><img src="assets/readme/btn-discord-dawn.svg" width="32%" alt="Join the Discord"></picture></a> <a href="https://garvitsurana271.github.io/stambha/"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/readme/btn-website-night.svg"><img src="assets/readme/btn-website-dawn.svg" width="32%" alt="Website"></picture></a></p>
|
||||
<p align="center"><sub>Stambha runs the real, unmodified Apple-silicon macOS on ordinary Intel and AMD PCs, desktops and laptops, from a USB stick. Free and open source.</sub></p>
|
||||
|
||||
<!-- SCREENSHOTS: add community showcase shots here once their owners say yes, each with "by @name" under it -->
|
||||
@@ -11,8 +11,8 @@
|
||||
| 🖥️ **macOS on your PC** | Apple-silicon macOS boots, with NVIDIA GPU acceleration (GTX 16, RTX 20/30/40/50) |
|
||||
| ⚡ **About 1.5x faster than Stela 0.5.0** | Hundreds of translator and engine improvements, and Apple's matrix engine (AMX) running natively on your CPU |
|
||||
| 🛡️ **Steady** | No Wi-Fi freezes, laptop touchpads stay working, and a macOS crash stops cleanly with the log saved |
|
||||
| 📶 **Wi-Fi** | Install over Wi-Fi and network inside macOS with a Realtek RTL8852CE; Intel AX211 (8086:51f1) and MediaTek MT7925 experimental |
|
||||
| 🎮 **AMD & Intel graphics** | Experimental, in the same download: Radeon RX 6000 and RX 7000 cards boot macOS, and Intel Iris Xe and UHD built-in graphics reach the macOS desktop (RX 9000 in testing; early builds on Discord) |
|
||||
| 📶 **Wi-Fi** | Install over Wi-Fi and network inside macOS with a Realtek RTL8852CE; more chips experimental |
|
||||
| 🎮 **AMD & Intel graphics** | Experimental: Radeon RX 6000 and RX 7000 cards boot macOS, and Intel built-in graphics now reach the macOS desktop in test builds (RX 9000 in testing; early builds on Discord) |
|
||||
|
||||
## Safe for the system you already have
|
||||
|
||||
@@ -28,8 +28,9 @@ Installing macOS next to Windows or Linux should never risk them. Stambha's inst
|
||||
|
||||
## Get started
|
||||
|
||||
1. **[Download Stambha](https://github.com/garvitsurana271/stambha/releases/latest)** for Windows or Linux. One download
|
||||
covers NVIDIA, AMD and Intel graphics; test builds are on Discord.
|
||||
1. **[Download Stambha](https://github.com/garvitsurana271/stambha/releases/latest)** for Windows or Linux. AMD or Intel
|
||||
graphics? Grab the [experimental build](https://github.com/garvitsurana271/stambha/releases/tag/v0.6.1-gpu-experimental),
|
||||
or the latest test build on Discord.
|
||||
2. **Make the USB stick:** run `stambha create` and pick your stick. Already on Stela? `stambha update` keeps your macOS.
|
||||
3. **Boot from the stick** and choose **Install macOS**. It installs into empty space next to your other systems.
|
||||
|
||||
@@ -46,7 +47,7 @@ Stuck? **[Join the Discord](https://discord.gg/M66z9fPJy5)**: help, hardware rep
|
||||
| Firmware | 64-bit UEFI with Secure Boot off |
|
||||
| GPU | NVIDIA GeForce GTX 16 or RTX 20/30/40/50 series. Laptops with a MUX switch: use dGPU-only mode. AMD and Intel: experimental |
|
||||
| Disk | NVMe, or SATA in AHCI mode, with **60 GB or more of unallocated space** (shrink a partition, leave the space empty) |
|
||||
| Network | Ethernet (Intel, Realtek, Broadcom, Aquantia, Qualcomm Atheros, common USB adapters) or Realtek RTL8852CE Wi-Fi. Intel AX211 and MediaTek Wi-Fi: experimental |
|
||||
| Network | Ethernet (Intel, Realtek, Broadcom, Aquantia, Qualcomm Atheros, common USB adapters) or Realtek RTL8852CE Wi-Fi |
|
||||
| USB stick | 8 GB or more |
|
||||
|
||||
</details>
|
||||
@@ -68,12 +69,9 @@ command keeps its original name until the rename to `stambha` lands.
|
||||
|
||||
## What's next
|
||||
|
||||
- **0.6.2 (out now):** AMD and Intel graphics in the main download (experimental), Intel AX211 Wi-Fi and Bluetooth,
|
||||
MediaTek Wi-Fi fixes, faster USB start, many fixes from your logs
|
||||
- **In testing:** laptop battery, lid and brightness keys (`--acpi-hardware`), speed fixes measured on real hardware
|
||||
- **0.6.2:** Intel graphics, safer installs over flaky networks, many fixes from your logs
|
||||
- **0.6.5:** sound and Bluetooth
|
||||
- **The next big release:** big speed work, macOS's own Wi-Fi menu, laptop battery, brightness and real sleep, and an
|
||||
installer app with a hardware check
|
||||
- **The next big release:** big speed work, real Wi-Fi inside macOS, AMD and Intel graphics in the main build, laptop battery, brightness and sleep, and an installer app with a hardware check
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
|
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 |
@@ -1,2 +1,2 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 427 112" width="427" height="112"><defs><linearGradient id="b" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#FFD27A"/><stop offset="1" stop-color="#F07A28"/></linearGradient></defs>
|
||||
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M117.51249999999999 65.1V61.525H121.08749999999999Q122.4375 61.525 123.51249999999999 61.1125Q124.58749999999999 60.7 125.33749999999999 59.95Q126.08749999999999 59.2 126.48749999999998 58.150000000000006Q126.88749999999999 57.1 126.88749999999999 55.825Q126.88749999999999 54.5 126.48749999999998 53.4625Q126.08749999999999 52.425 125.33749999999999 51.6875Q124.58749999999999 50.95 123.51249999999999 50.5625Q122.4375 50.175 121.08749999999999 50.175H117.51249999999999V46.625H120.88749999999999Q123.3625 46.625 125.19999999999999 47.35Q127.0375 48.075 128.27499999999998 49.325Q129.5125 50.575 130.1375 52.1875Q130.7625 53.8 130.7625 55.55V56.1Q130.7625 57.75 130.1375 59.3625Q129.5125 60.975 128.27499999999998 62.2625Q127.0375 63.55 125.19999999999999 64.32499999999999Q123.3625 65.1 120.88749999999999 65.1ZM114.1875 65.1V46.625H118.01249999999999V65.1Z M140.1125 65.475Q138.3125 65.475 136.925 64.9125Q135.53750000000002 64.35 134.57500000000002 63.3625Q133.6125 62.375 133.125 61.125Q132.63750000000002 59.875 132.63750000000002 58.475V57.95Q132.63750000000002 56.525 133.15000000000003 55.25Q133.66250000000002 53.975 134.63750000000002 53.0Q135.6125 52.025 137.0 51.45Q138.38750000000002 50.875 140.1125 50.875Q141.8625 50.875 143.2375 51.45Q144.6125 52.025 145.5875 53.0Q146.5625 53.975 147.075 55.25Q147.5875 56.525 147.5875 57.95V58.475Q147.5875 59.875 147.10000000000002 61.125Q146.6125 62.375 145.65 63.3625Q144.6875 64.35 143.3 64.9125Q141.91250000000002 65.475 140.1125 65.475ZM140.1125 62.3Q141.3375 62.3 142.16250000000002 61.775Q142.9875 61.25 143.41250000000002 60.3125Q143.8375 59.375 143.8375 58.225Q143.8375 57.0 143.4 56.075Q142.9625 55.15 142.125 54.6125Q141.28750000000002 54.075 140.1125 54.075Q138.9375 54.075 138.10000000000002 54.6125Q137.26250000000002 55.15 136.82500000000002 56.075Q136.38750000000002 57.0 136.38750000000002 58.225Q136.38750000000002 59.375 136.8125 60.3125Q137.2375 61.25 138.07500000000002 61.775Q138.91250000000002 62.3 140.1125 62.3Z M155.0375 65.0 157.5875 51.825H161.7875L164.7125 65.0H161.7875L158.7875 51.9H160.4125L157.7125 65.0ZM154.0625 65.0 154.0375 61.9H156.7875L156.8125 65.0ZM152.4625 65.0 148.7875 51.375H152.4125L155.8875 65.0ZM162.7375 65.0 162.7625 61.9H165.5125L165.4875 65.0ZM163.8375 65.0 166.9375 51.375H170.3375L167.0625 65.0Z M172.9375 65.0V51.375H175.8875V57.225H175.6625Q175.6625 55.125 176.2 53.7375Q176.73749999999998 52.35 177.83749999999998 51.6375Q178.9375 50.925 180.5375 50.925H180.6875Q183.11249999999998 50.925 184.375 52.5Q185.6375 54.075 185.6375 57.2V65.0H181.8875V56.925Q181.8875 55.75 181.2 55.025Q180.5125 54.3 179.3375 54.3Q178.1375 54.3 177.4125 55.05Q176.6875 55.8 176.6875 57.025V65.0Z M189.36249999999998 65.0V46.75H193.11249999999998V65.0ZM187.7125 49.525V46.75H193.11249999999998V49.525Z M203.5375 65.475Q201.73749999999998 65.475 200.35 64.9125Q198.9625 64.35 198.0 63.3625Q197.0375 62.375 196.55 61.125Q196.0625 59.875 196.0625 58.475V57.95Q196.0625 56.525 196.575 55.25Q197.0875 53.975 198.0625 53.0Q199.0375 52.025 200.425 51.45Q201.8125 50.875 203.5375 50.875Q205.2875 50.875 206.6625 51.45Q208.0375 52.025 209.0125 53.0Q209.98749999999998 53.975 210.5 55.25Q211.0125 56.525 211.0125 57.95V58.475Q211.0125 59.875 210.52499999999998 61.125Q210.0375 62.375 209.075 63.3625Q208.11249999999998 64.35 206.725 64.9125Q205.3375 65.475 203.5375 65.475ZM203.5375 62.3Q204.7625 62.3 205.58749999999998 61.775Q206.4125 61.25 206.83749999999998 60.3125Q207.2625 59.375 207.2625 58.225Q207.2625 57.0 206.825 56.075Q206.3875 55.15 205.55 54.6125Q204.7125 54.075 203.5375 54.075Q202.36249999999998 54.075 201.52499999999998 54.6125Q200.6875 55.15 200.25 56.075Q199.8125 57.0 199.8125 58.225Q199.8125 59.375 200.2375 60.3125Q200.6625 61.25 201.5 61.775Q202.3375 62.3 203.5375 62.3Z M222.1875 65.0V60.975H221.5625V56.525Q221.5625 55.425 221.02499999999998 54.875Q220.48749999999998 54.325 219.3375 54.325Q218.7625 54.325 217.875 54.35Q216.98749999999998 54.375 216.0625 54.4125Q215.1375 54.45 214.3875 54.5V51.325Q214.98749999999998 51.275 215.725 51.2375Q216.4625 51.2 217.2625 51.175Q218.0625 51.15 218.7625 51.15Q220.86249999999998 51.15 222.27499999999998 51.724999999999994Q223.6875 52.3 224.4125 53.5Q225.1375 54.7 225.1375 56.6V65.0ZM217.8125 65.35Q216.3375 65.35 215.225 64.82499999999999Q214.11249999999998 64.3 213.5 63.325Q212.8875 62.35 212.8875 60.975Q212.8875 59.475 213.6375 58.5125Q214.3875 57.55 215.75 57.0875Q217.11249999999998 56.625 218.9375 56.625H221.9625V58.775H218.8875Q217.7875 58.775 217.175 59.325Q216.5625 59.875 216.5625 60.775Q216.5625 61.65 217.175 62.1875Q217.7875 62.725 218.8875 62.725Q219.5875 62.725 220.175 62.475Q220.7625 62.225 221.1375 61.625Q221.5125 61.025 221.5625 59.95L222.4625 60.925Q222.3375 62.35 221.775 63.337500000000006Q221.2125 64.325 220.225 64.8375Q219.23749999999998 65.35 217.8125 65.35Z M234.3375 65.45Q232.9125 65.45 231.71249999999998 64.92500000000001Q230.5125 64.4 229.6Line truncated
|
||||
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M120.04999999999998 65.1V61.525H123.62499999999999Q124.975 61.525 126.04999999999998 61.1125Q127.12499999999999 60.7 127.875 59.95Q128.625 59.2 129.02499999999998 58.150000000000006Q129.42499999999998 57.1 129.42499999999998 55.825Q129.42499999999998 54.5 129.02499999999998 53.4625Q128.625 52.425 127.875 51.6875Q127.12499999999999 50.95 126.04999999999998 50.5625Q124.975 50.175 123.62499999999999 50.175H120.04999999999998V46.625H123.42499999999998Q125.89999999999999 46.625 127.73749999999998 47.35Q129.575 48.075 130.8125 49.325Q132.04999999999998 50.575 132.67499999999998 52.1875Q133.29999999999998 53.8 133.29999999999998 55.55V56.1Q133.29999999999998 57.75 132.67499999999998 59.3625Q132.04999999999998 60.975 130.8125 62.2625Q129.575 63.55 127.73749999999998 64.32499999999999Q125.89999999999999 65.1 123.42499999999998 65.1ZM116.725 65.1V46.625H120.54999999999998V65.1Z M142.64999999999998 65.475Q140.84999999999997 65.475 139.46249999999998 64.9125Q138.075 64.35 137.11249999999998 63.3625Q136.14999999999998 62.375 135.66249999999997 61.125Q135.17499999999998 59.875 135.17499999999998 58.475V57.95Q135.17499999999998 56.525 135.6875 55.25Q136.2 53.975 137.17499999999998 53.0Q138.14999999999998 52.025 139.53749999999997 51.45Q140.92499999999998 50.875 142.64999999999998 50.875Q144.39999999999998 50.875 145.77499999999998 51.45Q147.14999999999998 52.025 148.12499999999997 53.0Q149.09999999999997 53.975 149.61249999999995 55.25Q150.12499999999997 56.525 150.12499999999997 57.95V58.475Q150.12499999999997 59.875 149.6375 61.125Q149.14999999999998 62.375 148.18749999999997 63.3625Q147.22499999999997 64.35 145.83749999999998 64.9125Q144.45 65.475 142.64999999999998 65.475ZM142.64999999999998 62.3Q143.87499999999997 62.3 144.7 61.775Q145.52499999999998 61.25 145.95 60.3125Q146.37499999999997 59.375 146.37499999999997 58.225Q146.37499999999997 57.0 145.93749999999997 56.075Q145.49999999999997 55.15 144.66249999999997 54.6125Q143.825 54.075 142.64999999999998 54.075Q141.47499999999997 54.075 140.6375 54.6125Q139.79999999999998 55.15 139.36249999999998 56.075Q138.92499999999998 57.0 138.92499999999998 58.225Q138.92499999999998 59.375 139.34999999999997 60.3125Q139.77499999999998 61.25 140.61249999999998 61.775Q141.45 62.3 142.64999999999998 62.3Z M157.575 65.0 160.125 51.825H164.325L167.25 65.0H164.325L161.325 51.9H162.95L160.25 65.0ZM156.6 65.0 156.575 61.9H159.325L159.35 65.0ZM155.0 65.0 151.325 51.375H154.95L158.42499999999998 65.0ZM165.275 65.0 165.29999999999998 61.9H168.04999999999998L168.025 65.0ZM166.375 65.0 169.475 51.375H172.875L169.6 65.0Z M175.475 65.0V51.375H178.42499999999998V57.225H178.2Q178.2 55.125 178.73749999999998 53.7375Q179.27499999999998 52.35 180.375 51.6375Q181.475 50.925 183.075 50.925H183.225Q185.64999999999998 50.925 186.91249999999997 52.5Q188.17499999999998 54.075 188.17499999999998 57.2V65.0H184.42499999999998V56.925Q184.42499999999998 55.75 183.73749999999998 55.025Q183.04999999999998 54.3 181.875 54.3Q180.67499999999998 54.3 179.95 55.05Q179.225 55.8 179.225 57.025V65.0Z M191.89999999999998 65.0V46.75H195.64999999999998V65.0ZM190.25 49.525V46.75H195.64999999999998V49.525Z M206.075 65.475Q204.27499999999998 65.475 202.8875 64.9125Q201.5 64.35 200.5375 63.3625Q199.575 62.375 199.08749999999998 61.125Q198.6 59.875 198.6 58.475V57.95Q198.6 56.525 199.1125 55.25Q199.625 53.975 200.6 53.0Q201.575 52.025 202.96249999999998 51.45Q204.35 50.875 206.075 50.875Q207.825 50.875 209.2 51.45Q210.575 52.025 211.54999999999998 53.0Q212.52499999999998 53.975 213.03749999999997 55.25Q213.54999999999998 56.525 213.54999999999998 57.95V58.475Q213.54999999999998 59.875 213.0625 61.125Q212.575 62.375 211.61249999999998 63.3625Q210.64999999999998 64.35 209.2625 64.9125Q207.875 65.475 206.075 65.475ZM206.075 62.3Q207.29999999999998 62.3 208.125 61.775Q208.95 61.25 209.375 60.3125Q209.79999999999998 59.375 209.79999999999998 58.225Q209.79999999999998 57.0 209.36249999999998 56.075Q208.92499999999998 55.15 208.08749999999998 54.6125Q207.25 54.075 206.075 54.075Q204.89999999999998 54.075 204.0625 54.6125Q203.225 55.15 202.7875 56.075Q202.35 57.0 202.35 58.225Q202.35 59.375 202.77499999999998 60.3125Q203.2 61.25 204.0375 61.775Q204.875 62.3 206.075 62.3Z M224.725 65.0V60.975H224.1V56.525Q224.1 55.425 223.5625 54.875Q223.02499999999998 54.325 221.875 54.325Q221.29999999999998 54.325 220.41249999999997 54.35Q219.52499999999998 54.375 218.59999999999997 54.4125Q217.67499999999998 54.45 216.92499999999998 54.5V51.325Q217.52499999999998 51.275 218.2625 51.2375Q219.0 51.2 219.8 51.175Q220.6 51.15 221.29999999999998 51.15Q223.39999999999998 51.15 224.8125 51.724999999999994Q226.225 52.3 226.95 53.5Q227.67499999999998 54.7 227.67499999999998 56.6V65.0ZM220.35 65.35Q218.875 65.35 217.7625 64.82499999999999Q216.64999999999998 64.3 216.03749999999997 63.325Q215.42499999999998 62.35 215.42499999999998 60.975Q215.42499999999998 59.475 216.17499999999998Line truncated
|
||||
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 8.8 KiB |
@@ -1,2 +1,2 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 427 112" width="427" height="112"><defs><linearGradient id="b" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#FFD27A"/><stop offset="1" stop-color="#F07A28"/></linearGradient></defs>
|
||||
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M117.51249999999999 65.1V61.525H121.08749999999999Q122.4375 61.525 123.51249999999999 61.1125Q124.58749999999999 60.7 125.33749999999999 59.95Q126.08749999999999 59.2 126.48749999999998 58.150000000000006Q126.88749999999999 57.1 126.88749999999999 55.825Q126.88749999999999 54.5 126.48749999999998 53.4625Q126.08749999999999 52.425 125.33749999999999 51.6875Q124.58749999999999 50.95 123.51249999999999 50.5625Q122.4375 50.175 121.08749999999999 50.175H117.51249999999999V46.625H120.88749999999999Q123.3625 46.625 125.19999999999999 47.35Q127.0375 48.075 128.27499999999998 49.325Q129.5125 50.575 130.1375 52.1875Q130.7625 53.8 130.7625 55.55V56.1Q130.7625 57.75 130.1375 59.3625Q129.5125 60.975 128.27499999999998 62.2625Q127.0375 63.55 125.19999999999999 64.32499999999999Q123.3625 65.1 120.88749999999999 65.1ZM114.1875 65.1V46.625H118.01249999999999V65.1Z M140.1125 65.475Q138.3125 65.475 136.925 64.9125Q135.53750000000002 64.35 134.57500000000002 63.3625Q133.6125 62.375 133.125 61.125Q132.63750000000002 59.875 132.63750000000002 58.475V57.95Q132.63750000000002 56.525 133.15000000000003 55.25Q133.66250000000002 53.975 134.63750000000002 53.0Q135.6125 52.025 137.0 51.45Q138.38750000000002 50.875 140.1125 50.875Q141.8625 50.875 143.2375 51.45Q144.6125 52.025 145.5875 53.0Q146.5625 53.975 147.075 55.25Q147.5875 56.525 147.5875 57.95V58.475Q147.5875 59.875 147.10000000000002 61.125Q146.6125 62.375 145.65 63.3625Q144.6875 64.35 143.3 64.9125Q141.91250000000002 65.475 140.1125 65.475ZM140.1125 62.3Q141.3375 62.3 142.16250000000002 61.775Q142.9875 61.25 143.41250000000002 60.3125Q143.8375 59.375 143.8375 58.225Q143.8375 57.0 143.4 56.075Q142.9625 55.15 142.125 54.6125Q141.28750000000002 54.075 140.1125 54.075Q138.9375 54.075 138.10000000000002 54.6125Q137.26250000000002 55.15 136.82500000000002 56.075Q136.38750000000002 57.0 136.38750000000002 58.225Q136.38750000000002 59.375 136.8125 60.3125Q137.2375 61.25 138.07500000000002 61.775Q138.91250000000002 62.3 140.1125 62.3Z M155.0375 65.0 157.5875 51.825H161.7875L164.7125 65.0H161.7875L158.7875 51.9H160.4125L157.7125 65.0ZM154.0625 65.0 154.0375 61.9H156.7875L156.8125 65.0ZM152.4625 65.0 148.7875 51.375H152.4125L155.8875 65.0ZM162.7375 65.0 162.7625 61.9H165.5125L165.4875 65.0ZM163.8375 65.0 166.9375 51.375H170.3375L167.0625 65.0Z M172.9375 65.0V51.375H175.8875V57.225H175.6625Q175.6625 55.125 176.2 53.7375Q176.73749999999998 52.35 177.83749999999998 51.6375Q178.9375 50.925 180.5375 50.925H180.6875Q183.11249999999998 50.925 184.375 52.5Q185.6375 54.075 185.6375 57.2V65.0H181.8875V56.925Q181.8875 55.75 181.2 55.025Q180.5125 54.3 179.3375 54.3Q178.1375 54.3 177.4125 55.05Q176.6875 55.8 176.6875 57.025V65.0Z M189.36249999999998 65.0V46.75H193.11249999999998V65.0ZM187.7125 49.525V46.75H193.11249999999998V49.525Z M203.5375 65.475Q201.73749999999998 65.475 200.35 64.9125Q198.9625 64.35 198.0 63.3625Q197.0375 62.375 196.55 61.125Q196.0625 59.875 196.0625 58.475V57.95Q196.0625 56.525 196.575 55.25Q197.0875 53.975 198.0625 53.0Q199.0375 52.025 200.425 51.45Q201.8125 50.875 203.5375 50.875Q205.2875 50.875 206.6625 51.45Q208.0375 52.025 209.0125 53.0Q209.98749999999998 53.975 210.5 55.25Q211.0125 56.525 211.0125 57.95V58.475Q211.0125 59.875 210.52499999999998 61.125Q210.0375 62.375 209.075 63.3625Q208.11249999999998 64.35 206.725 64.9125Q205.3375 65.475 203.5375 65.475ZM203.5375 62.3Q204.7625 62.3 205.58749999999998 61.775Q206.4125 61.25 206.83749999999998 60.3125Q207.2625 59.375 207.2625 58.225Q207.2625 57.0 206.825 56.075Q206.3875 55.15 205.55 54.6125Q204.7125 54.075 203.5375 54.075Q202.36249999999998 54.075 201.52499999999998 54.6125Q200.6875 55.15 200.25 56.075Q199.8125 57.0 199.8125 58.225Q199.8125 59.375 200.2375 60.3125Q200.6625 61.25 201.5 61.775Q202.3375 62.3 203.5375 62.3Z M222.1875 65.0V60.975H221.5625V56.525Q221.5625 55.425 221.02499999999998 54.875Q220.48749999999998 54.325 219.3375 54.325Q218.7625 54.325 217.875 54.35Q216.98749999999998 54.375 216.0625 54.4125Q215.1375 54.45 214.3875 54.5V51.325Q214.98749999999998 51.275 215.725 51.2375Q216.4625 51.2 217.2625 51.175Q218.0625 51.15 218.7625 51.15Q220.86249999999998 51.15 222.27499999999998 51.724999999999994Q223.6875 52.3 224.4125 53.5Q225.1375 54.7 225.1375 56.6V65.0ZM217.8125 65.35Q216.3375 65.35 215.225 64.82499999999999Q214.11249999999998 64.3 213.5 63.325Q212.8875 62.35 212.8875 60.975Q212.8875 59.475 213.6375 58.5125Q214.3875 57.55 215.75 57.0875Q217.11249999999998 56.625 218.9375 56.625H221.9625V58.775H218.8875Q217.7875 58.775 217.175 59.325Q216.5625 59.875 216.5625 60.775Q216.5625 61.65 217.175 62.1875Q217.7875 62.725 218.8875 62.725Q219.5875 62.725 220.175 62.475Q220.7625 62.225 221.1375 61.625Q221.5125 61.025 221.5625 59.95L222.4625 60.925Q222.3375 62.35 221.775 63.337500000000006Q221.2125 64.325 220.225 64.8375Q219.23749999999998 65.35 217.8125 65.35Z M234.3375 65.45Q232.9125 65.45 231.71249999999998 64.92500000000001Q230.5125 64.4 229.6Line truncated
|
||||
<rect x="26" y="24" width="375" height="64" rx="32" fill="url(#b)"/><path d="M120.04999999999998 65.1V61.525H123.62499999999999Q124.975 61.525 126.04999999999998 61.1125Q127.12499999999999 60.7 127.875 59.95Q128.625 59.2 129.02499999999998 58.150000000000006Q129.42499999999998 57.1 129.42499999999998 55.825Q129.42499999999998 54.5 129.02499999999998 53.4625Q128.625 52.425 127.875 51.6875Q127.12499999999999 50.95 126.04999999999998 50.5625Q124.975 50.175 123.62499999999999 50.175H120.04999999999998V46.625H123.42499999999998Q125.89999999999999 46.625 127.73749999999998 47.35Q129.575 48.075 130.8125 49.325Q132.04999999999998 50.575 132.67499999999998 52.1875Q133.29999999999998 53.8 133.29999999999998 55.55V56.1Q133.29999999999998 57.75 132.67499999999998 59.3625Q132.04999999999998 60.975 130.8125 62.2625Q129.575 63.55 127.73749999999998 64.32499999999999Q125.89999999999999 65.1 123.42499999999998 65.1ZM116.725 65.1V46.625H120.54999999999998V65.1Z M142.64999999999998 65.475Q140.84999999999997 65.475 139.46249999999998 64.9125Q138.075 64.35 137.11249999999998 63.3625Q136.14999999999998 62.375 135.66249999999997 61.125Q135.17499999999998 59.875 135.17499999999998 58.475V57.95Q135.17499999999998 56.525 135.6875 55.25Q136.2 53.975 137.17499999999998 53.0Q138.14999999999998 52.025 139.53749999999997 51.45Q140.92499999999998 50.875 142.64999999999998 50.875Q144.39999999999998 50.875 145.77499999999998 51.45Q147.14999999999998 52.025 148.12499999999997 53.0Q149.09999999999997 53.975 149.61249999999995 55.25Q150.12499999999997 56.525 150.12499999999997 57.95V58.475Q150.12499999999997 59.875 149.6375 61.125Q149.14999999999998 62.375 148.18749999999997 63.3625Q147.22499999999997 64.35 145.83749999999998 64.9125Q144.45 65.475 142.64999999999998 65.475ZM142.64999999999998 62.3Q143.87499999999997 62.3 144.7 61.775Q145.52499999999998 61.25 145.95 60.3125Q146.37499999999997 59.375 146.37499999999997 58.225Q146.37499999999997 57.0 145.93749999999997 56.075Q145.49999999999997 55.15 144.66249999999997 54.6125Q143.825 54.075 142.64999999999998 54.075Q141.47499999999997 54.075 140.6375 54.6125Q139.79999999999998 55.15 139.36249999999998 56.075Q138.92499999999998 57.0 138.92499999999998 58.225Q138.92499999999998 59.375 139.34999999999997 60.3125Q139.77499999999998 61.25 140.61249999999998 61.775Q141.45 62.3 142.64999999999998 62.3Z M157.575 65.0 160.125 51.825H164.325L167.25 65.0H164.325L161.325 51.9H162.95L160.25 65.0ZM156.6 65.0 156.575 61.9H159.325L159.35 65.0ZM155.0 65.0 151.325 51.375H154.95L158.42499999999998 65.0ZM165.275 65.0 165.29999999999998 61.9H168.04999999999998L168.025 65.0ZM166.375 65.0 169.475 51.375H172.875L169.6 65.0Z M175.475 65.0V51.375H178.42499999999998V57.225H178.2Q178.2 55.125 178.73749999999998 53.7375Q179.27499999999998 52.35 180.375 51.6375Q181.475 50.925 183.075 50.925H183.225Q185.64999999999998 50.925 186.91249999999997 52.5Q188.17499999999998 54.075 188.17499999999998 57.2V65.0H184.42499999999998V56.925Q184.42499999999998 55.75 183.73749999999998 55.025Q183.04999999999998 54.3 181.875 54.3Q180.67499999999998 54.3 179.95 55.05Q179.225 55.8 179.225 57.025V65.0Z M191.89999999999998 65.0V46.75H195.64999999999998V65.0ZM190.25 49.525V46.75H195.64999999999998V49.525Z M206.075 65.475Q204.27499999999998 65.475 202.8875 64.9125Q201.5 64.35 200.5375 63.3625Q199.575 62.375 199.08749999999998 61.125Q198.6 59.875 198.6 58.475V57.95Q198.6 56.525 199.1125 55.25Q199.625 53.975 200.6 53.0Q201.575 52.025 202.96249999999998 51.45Q204.35 50.875 206.075 50.875Q207.825 50.875 209.2 51.45Q210.575 52.025 211.54999999999998 53.0Q212.52499999999998 53.975 213.03749999999997 55.25Q213.54999999999998 56.525 213.54999999999998 57.95V58.475Q213.54999999999998 59.875 213.0625 61.125Q212.575 62.375 211.61249999999998 63.3625Q210.64999999999998 64.35 209.2625 64.9125Q207.875 65.475 206.075 65.475ZM206.075 62.3Q207.29999999999998 62.3 208.125 61.775Q208.95 61.25 209.375 60.3125Q209.79999999999998 59.375 209.79999999999998 58.225Q209.79999999999998 57.0 209.36249999999998 56.075Q208.92499999999998 55.15 208.08749999999998 54.6125Q207.25 54.075 206.075 54.075Q204.89999999999998 54.075 204.0625 54.6125Q203.225 55.15 202.7875 56.075Q202.35 57.0 202.35 58.225Q202.35 59.375 202.77499999999998 60.3125Q203.2 61.25 204.0375 61.775Q204.875 62.3 206.075 62.3Z M224.725 65.0V60.975H224.1V56.525Q224.1 55.425 223.5625 54.875Q223.02499999999998 54.325 221.875 54.325Q221.29999999999998 54.325 220.41249999999997 54.35Q219.52499999999998 54.375 218.59999999999997 54.4125Q217.67499999999998 54.45 216.92499999999998 54.5V51.325Q217.52499999999998 51.275 218.2625 51.2375Q219.0 51.2 219.8 51.175Q220.6 51.15 221.29999999999998 51.15Q223.39999999999998 51.15 224.8125 51.724999999999994Q226.225 52.3 226.95 53.5Q227.67499999999998 54.7 227.67499999999998 56.6V65.0ZM220.35 65.35Q218.875 65.35 217.7625 64.82499999999999Q216.64999999999998 64.3 216.03749999999997 63.325Q215.42499999999998 62.35 215.42499999999998 60.975Q215.42499999999998 59.475 216.17499999999998Line truncated
|
||||
|
Before Width: | Height: | Size: 9.3 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 |
@@ -24,4 +24,4 @@
|
||||
</g></g></g></g>
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1s" dur=".8s" fill="freeze"/>
|
||||
<animateTransform attributeName="transform" type="translate" values="0 26;0 0" keyTimes="0;1" calcMode="spline" keySplines="0.16 1 0.3 1" dur=".9s" begin="1s" fill="freeze"/><path d="M380.56 482.368H398.96Q399.42 485.496 401.72 487.75Q404.02 490.004 407.92999999999995 491.246Q411.84 492.488 416.99199999999996 492.488Q424.352 492.488 428.58399999999995 490.51Q432.816 488.532 432.816 484.76Q432.816 482.0 430.424 480.39Q428.032 478.78 421.224 478.136L408.068 476.756Q394.084 475.468 387.78200000000004 470.36199999999997Q381.48 465.256 381.48 456.516Q381.48 449.432 385.574 444.51Q389.668 439.588 397.166 437.058Q404.664 434.528 414.692 434.528Q424.536 434.528 432.172 437.334Q439.808 440.14 444.316 445.246Q448.82399999999996 450.352 449.284 457.16H430.884Q430.51599999999996 454.492 428.49199999999996 452.606Q426.46799999999996 450.72 422.88 449.616Q419.292 448.512 414.324 448.512Q407.608 448.512 403.652 450.398Q399.69599999999997 452.284 399.69599999999997 455.78Q399.69599999999997 458.356 402.042 459.91999999999996Q404.388 461.484 410.552 462.128L424.44399999999996 463.6Q434.19599999999997 464.52 440.038 466.82Q445.88 469.12 448.456 472.98400000000004Q451.032 476.848 451.032 482.736Q451.032 489.912 446.754 495.248Q442.476 500.584 434.748 503.528Q427.02 506.472 416.716 506.472Q406.13599999999997 506.472 398.086 503.48199999999997Q390.036 500.492 385.43600000000004 495.01800000000003Q380.836 489.544 380.56 482.368Z M452.228 465.716V457.896L462.9 453.848L470.628 438.484H480.748V452.468H503.104V465.716H480.748V482.276Q480.748 488.072 483.094 490.418Q485.44 492.764 491.604 492.764Q495.46799999999996 492.764 498.45799999999997 492.074Q501.448 491.384 504.024 490.188V503.62Q501.264 504.724 496.802 505.59799999999996Q492.34 506.472 487.556 506.472Q479.0 506.472 473.572 503.804Q468.144 501.136 465.522 496.214Q462.9 491.292 462.9 484.76V465.716Z M556.28 505.0 553.888 486.048 556.464 478.78 553.888 471.604 556.28 452.468H574.6800000000001L571.46 478.688L574.6800000000001 505.0ZM560.5120000000001 478.78Q559.224 487.06 555.36 493.31600000000003Q551.496 499.572 545.608 503.022Q539.72 506.472 532.36 506.472Q524.6320000000001 506.472 518.79 503.022Q512.948 499.572 509.63599999999997 493.27Q506.324 486.968 506.324 478.78Q506.324 470.408 509.63599999999997 464.198Q512.948 457.988 518.79 454.49199999999996Q524.6320000000001 450.996 532.36 450.996Q539.72 450.996 545.608 454.446Q551.496 457.896 555.406 464.106Q559.316 470.31600000000003 560.5120000000001 478.78ZM524.356 478.78Q524.356 482.92 526.012 486.048Q527.668 489.176 530.704 491.01599999999996Q533.74 492.856 537.604 492.856Q541.5600000000001 492.856 545.1020000000001 491.01599999999996Q548.644 489.176 551.358 486.048Q554.072 482.92 555.452 478.78Q554.072 474.64 551.358 471.466Q548.644 468.29200000000003 545.1020000000001 466.49800000000005Q541.5600000000001 464.704 537.604 464.704Q533.74 464.704 530.704 466.49800000000005Q527.668 468.29200000000003 526.012 471.466Q524.356 474.64 524.356 478.78Z M579.7399999999999 452.468H597.588L600.992 473.168V505.0H583.1439999999999V470.5ZM619.208 450.996Q626.3839999999999 450.996 631.444 454.032Q636.5039999999999 457.068 639.1719999999999 462.58799999999997Q641.8399999999999 468.108 641.8399999999999 475.652V505.0H623.992V478.32Q623.992 472.064 621.232 468.798Q618.4719999999999 465.532 613.136 465.532Q609.3639999999999 465.532 606.6039999999999 467.28Q603.8439999999999 469.028 602.4179999999999 472.202Q600.992 475.376 600.992 479.7L595.3799999999999 476.756Q596.3919999999999 468.384 599.75 462.68Q603.108 456.976 608.1679999999999 453.986Q613.228 450.996 619.208 450.996ZM659.9639999999999 450.996Q667.1399999999999 450.996 672.2459999999999 454.032Q677.3519999999999 457.068 680.0199999999999 462.58799999999997Q682.6879999999999 468.108 682.6879999999999 475.652V505.0H664.8399999999999V478.32Q664.8399999999999 472.064 662.0799999999999 468.798Q659.3199999999999 465.532 653.9839999999999 465.532Q650.2119999999999 465.532 647.4519999999999 467.28Q644.6919999999999 469.028 643.2659999999998 472.202Q641.8399999999999 475.376 641.8399999999999 479.7L636.228 476.756Q637.2399999999999 468.384 640.598 462.68Q643.9559999999999 456.976 648.9699999999999 453.986Q653.9839999999999 450.996 659.9639999999999 450.996Z M690.784 434.15999999999997H708.632V468.2L706.24 472.8V485.496L708.632 490.004V505.0H690.784ZM702.744 478.78Q704.0319999999999 470.31600000000003 707.896 464.106Q711.76 457.896 717.6479999999999 454.446Q723.536 450.996 730.896 450.996Q738.624 450.996 744.466 454.49199999999996Q750.308 457.988 753.62 464.198Q756.932 470.408 756.932 478.78Q756.932 486.968 753.62 493.27Q750.308 499.572 744.466 503.022Q738.624 506.472 730.896 506.472Q723.536 506.472 717.6479999999999 503.022Q711.76 499.572 707.942 493.31600000000003Q704.124 487.06 702.744 478.78ZM738.9 478.78Q738.9 474.64 737.2439999999999 471.466Q735.588 468.29200000000003 732.5519999999999 466.49800000000005Q729.516 464.704 725.6519999999999 464.704Q721.696 464.704 718.154 466.49800000000005Q714Line truncated
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
|
||||
|
Before Width: | Height: | Size: 627 KiB After Width: | Height: | Size: 625 KiB |
@@ -24,4 +24,4 @@
|
||||
</g></g></g></g>
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1s" dur=".8s" fill="freeze"/>
|
||||
<animateTransform attributeName="transform" type="translate" values="0 26;0 0" keyTimes="0;1" calcMode="spline" keySplines="0.16 1 0.3 1" dur=".9s" begin="1s" fill="freeze"/><path d="M380.56 482.368H398.96Q399.42 485.496 401.72 487.75Q404.02 490.004 407.92999999999995 491.246Q411.84 492.488 416.99199999999996 492.488Q424.352 492.488 428.58399999999995 490.51Q432.816 488.532 432.816 484.76Q432.816 482.0 430.424 480.39Q428.032 478.78 421.224 478.136L408.068 476.756Q394.084 475.468 387.78200000000004 470.36199999999997Q381.48 465.256 381.48 456.516Q381.48 449.432 385.574 444.51Q389.668 439.588 397.166 437.058Q404.664 434.528 414.692 434.528Q424.536 434.528 432.172 437.334Q439.808 440.14 444.316 445.246Q448.82399999999996 450.352 449.284 457.16H430.884Q430.51599999999996 454.492 428.49199999999996 452.606Q426.46799999999996 450.72 422.88 449.616Q419.292 448.512 414.324 448.512Q407.608 448.512 403.652 450.398Q399.69599999999997 452.284 399.69599999999997 455.78Q399.69599999999997 458.356 402.042 459.91999999999996Q404.388 461.484 410.552 462.128L424.44399999999996 463.6Q434.19599999999997 464.52 440.038 466.82Q445.88 469.12 448.456 472.98400000000004Q451.032 476.848 451.032 482.736Q451.032 489.912 446.754 495.248Q442.476 500.584 434.748 503.528Q427.02 506.472 416.716 506.472Q406.13599999999997 506.472 398.086 503.48199999999997Q390.036 500.492 385.43600000000004 495.01800000000003Q380.836 489.544 380.56 482.368Z M452.228 465.716V457.896L462.9 453.848L470.628 438.484H480.748V452.468H503.104V465.716H480.748V482.276Q480.748 488.072 483.094 490.418Q485.44 492.764 491.604 492.764Q495.46799999999996 492.764 498.45799999999997 492.074Q501.448 491.384 504.024 490.188V503.62Q501.264 504.724 496.802 505.59799999999996Q492.34 506.472 487.556 506.472Q479.0 506.472 473.572 503.804Q468.144 501.136 465.522 496.214Q462.9 491.292 462.9 484.76V465.716Z M556.28 505.0 553.888 486.048 556.464 478.78 553.888 471.604 556.28 452.468H574.6800000000001L571.46 478.688L574.6800000000001 505.0ZM560.5120000000001 478.78Q559.224 487.06 555.36 493.31600000000003Q551.496 499.572 545.608 503.022Q539.72 506.472 532.36 506.472Q524.6320000000001 506.472 518.79 503.022Q512.948 499.572 509.63599999999997 493.27Q506.324 486.968 506.324 478.78Q506.324 470.408 509.63599999999997 464.198Q512.948 457.988 518.79 454.49199999999996Q524.6320000000001 450.996 532.36 450.996Q539.72 450.996 545.608 454.446Q551.496 457.896 555.406 464.106Q559.316 470.31600000000003 560.5120000000001 478.78ZM524.356 478.78Q524.356 482.92 526.012 486.048Q527.668 489.176 530.704 491.01599999999996Q533.74 492.856 537.604 492.856Q541.5600000000001 492.856 545.1020000000001 491.01599999999996Q548.644 489.176 551.358 486.048Q554.072 482.92 555.452 478.78Q554.072 474.64 551.358 471.466Q548.644 468.29200000000003 545.1020000000001 466.49800000000005Q541.5600000000001 464.704 537.604 464.704Q533.74 464.704 530.704 466.49800000000005Q527.668 468.29200000000003 526.012 471.466Q524.356 474.64 524.356 478.78Z M579.7399999999999 452.468H597.588L600.992 473.168V505.0H583.1439999999999V470.5ZM619.208 450.996Q626.3839999999999 450.996 631.444 454.032Q636.5039999999999 457.068 639.1719999999999 462.58799999999997Q641.8399999999999 468.108 641.8399999999999 475.652V505.0H623.992V478.32Q623.992 472.064 621.232 468.798Q618.4719999999999 465.532 613.136 465.532Q609.3639999999999 465.532 606.6039999999999 467.28Q603.8439999999999 469.028 602.4179999999999 472.202Q600.992 475.376 600.992 479.7L595.3799999999999 476.756Q596.3919999999999 468.384 599.75 462.68Q603.108 456.976 608.1679999999999 453.986Q613.228 450.996 619.208 450.996ZM659.9639999999999 450.996Q667.1399999999999 450.996 672.2459999999999 454.032Q677.3519999999999 457.068 680.0199999999999 462.58799999999997Q682.6879999999999 468.108 682.6879999999999 475.652V505.0H664.8399999999999V478.32Q664.8399999999999 472.064 662.0799999999999 468.798Q659.3199999999999 465.532 653.9839999999999 465.532Q650.2119999999999 465.532 647.4519999999999 467.28Q644.6919999999999 469.028 643.2659999999998 472.202Q641.8399999999999 475.376 641.8399999999999 479.7L636.228 476.756Q637.2399999999999 468.384 640.598 462.68Q643.9559999999999 456.976 648.9699999999999 453.986Q653.9839999999999 450.996 659.9639999999999 450.996Z M690.784 434.15999999999997H708.632V468.2L706.24 472.8V485.496L708.632 490.004V505.0H690.784ZM702.744 478.78Q704.0319999999999 470.31600000000003 707.896 464.106Q711.76 457.896 717.6479999999999 454.446Q723.536 450.996 730.896 450.996Q738.624 450.996 744.466 454.49199999999996Q750.308 457.988 753.62 464.198Q756.932 470.408 756.932 478.78Q756.932 486.968 753.62 493.27Q750.308 499.572 744.466 503.022Q738.624 506.472 730.896 506.472Q723.536 506.472 717.6479999999999 503.022Q711.76 499.572 707.942 493.31600000000003Q704.124 487.06 702.744 478.78ZM738.9 478.78Q738.9 474.64 737.2439999999999 471.466Q735.588 468.29200000000003 732.5519999999999 466.49800000000005Q729.516 464.704 725.6519999999999 464.704Q721.696 464.704 718.154 466.49800000000005Q714Line truncated
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
|
||||
<g opacity="0"><animate attributeName="opacity" from="0" to="1" begin="1.4s" dur=".8s" fill="freeze"/><path d="M303.418 556.0 310.546 536.29H314.866L322.23699999999997 556.0H319.618L312.92199999999997 537.937L314.191 538.558H311.086L312.409 537.937L305.956 556.0ZM307.57599999999996 550.033 308.44 547.765H317.08L317.917 550.033Z M325.531 561.4V541.609H327.502V547.819L327.01599999999996 547.792Q327.15099999999995 545.497 327.98799999999994 544.0255Q328.825 542.554 330.2155 541.8385000000001Q331.606 541.123 333.253 541.123Q334.81899999999996 541.123 336.1015 541.7170000000001Q337.38399999999996 542.311 338.30199999999996 543.337Q339.21999999999997 544.363 339.6925 545.713Q340.16499999999996 547.063 340.16499999999996 548.575V549.034Q340.16499999999996 550.546 339.66549999999995 551.8825Q339.166 553.219 338.2345 554.2585Q337.303 555.298 336.02049999999997 555.892Q334.738 556.486 333.19899999999996 556.486Q331.633 556.486 330.2155 555.784Q328.798 555.082 327.8935 553.5699999999999Q326.989 552.058 326.854 549.655L328.015 551.788V561.4ZM332.82099999999997 554.299Q334.306 554.299 335.3995 553.597Q336.493 552.895 337.1005 551.653Q337.70799999999997 550.411 337.70799999999997 548.791Q337.70799999999997 547.171 337.1005 545.9425000000001Q336.493 544.714 335.3995 543.9985Q334.306 543.283 332.82099999999997 543.283Q331.498 543.283 330.364 543.877Q329.22999999999996 544.471 328.5685 545.5915Q327.907 546.712 327.907 548.251V549.52Q327.907 551.005 328.582 552.0715Q329.257 553.138 330.3775 553.7185Q331.498 554.299 332.82099999999997 554.299Z M344.107 561.4V541.609H346.07800000000003V547.819L345.592 547.792Q345.727 545.497 346.56399999999996 544.0255Q347.401 542.554 348.79150000000004 541.8385000000001Q350.182 541.123 351.829 541.123Q353.395 541.123 354.6775 541.7170000000001Q355.96 542.311 356.878 543.337Q357.796 544.363 358.2685 545.713Q358.741 547.063 358.741 548.575V549.034Q358.741 550.546 358.2415 551.8825Q357.742 553.219 356.81050000000005 554.2585Q355.879 555.298 354.5965 555.892Q353.314 556.486 351.775 556.486Q350.209 556.486 348.79150000000004 555.784Q347.374 555.082 346.46950000000004 553.5699999999999Q345.565 552.058 345.43 549.655L346.591 551.788V561.4ZM351.397 554.299Q352.882 554.299 353.9755 553.597Q355.069 552.895 355.67650000000003 551.653Q356.284 550.411 356.284 548.791Q356.284 547.171 355.67650000000003 545.9425000000001Q355.069 544.714 353.9755 543.9985Q352.882 543.283 351.397 543.283Q350.074 543.283 348.94 543.877Q347.806 544.471 347.1445 545.5915Q346.483 546.712 346.483 548.251V549.52Q346.483 551.005 347.158 552.0715Q347.833 553.138 348.9535 553.7185Q350.074 554.299 351.397 554.299Z M362.84499999999997 556.0V536.29H365.32899999999995V556.0ZM360.82 538.261V536.29H365.32899999999995V538.261Z M376.453 556.486Q374.563 556.486 373.19949999999994 555.838Q371.83599999999996 555.19 370.972 554.1235Q370.10799999999995 553.057 369.68949999999995 551.7339999999999Q369.27099999999996 550.411 369.27099999999996 549.034V548.575Q369.27099999999996 547.171 369.68949999999995 545.848Q370.10799999999995 544.525 370.972 543.4585Q371.83599999999996 542.392 373.159 541.7575Q374.48199999999997 541.123 376.291 541.123Q378.613 541.123 380.1385 542.1355000000001Q381.664 543.148 382.4065 544.7275Q383.149 546.307 383.149 548.116V549.25H370.351V547.387H381.34L380.77299999999997 548.386Q380.77299999999997 546.847 380.2735 545.6995Q379.774 544.552 378.7885 543.9175Q377.803 543.283 376.291 543.283Q374.72499999999997 543.283 373.68549999999993 544.012Q372.64599999999996 544.741 372.14649999999995 545.9694999999999Q371.647 547.198 371.647 548.791Q371.647 550.357 372.14649999999995 551.5989999999999Q372.64599999999996 552.841 373.726 553.5699999999999Q374.806 554.299 376.453 554.299Q378.181 554.299 379.26099999999997 553.5295Q380.34099999999995 552.76 380.58399999999995 551.734H382.90599999999995Q382.609 553.192 381.71799999999996 554.2719999999999Q380.827 555.352 379.4905 555.919Q378.154 556.486 376.453 556.486Z M386.173 549.547V547.441H396.109V549.547Z M405.1 556.432Q402.29200000000003 556.432 400.75300000000004 555.217Q399.214 554.002 399.16 551.923H401.482Q401.536 552.787 402.346 553.543Q403.156 554.299 405.1 554.299Q406.882 554.299 407.8 553.597Q408.718 552.895 408.718 551.869Q408.718 550.951 408.0295 550.4245000000001Q407.341 549.898 405.829 549.736L404.236 549.574Q402.211 549.358 400.9285 548.3589999999999Q399.646 547.36 399.646 545.551Q399.646 544.174 400.348 543.202Q401.05 542.23 402.2785 541.7035000000001Q403.507 541.177 405.1 541.177Q407.503 541.177 409.00149999999996 542.2570000000001Q410.5 543.337 410.55400000000003 545.443H408.232Q408.205 544.552 407.422 543.9175Q406.639 543.283 405.1 543.283Q403.561 543.283 402.778 543.931Q401.995 544.579 401.995 545.551Q401.995 546.361 402.562 546.874Q403.129 547.387 404.398 547.522L405.964 547.684Q408.259 547.927 409.663 548.953Q411.067 549.979 411.067 551.869Q411.067 553.192 410.2975 554.2315Q409.528 555.271 408.1915 555.8515Q406.855 556.432 405.1 556.432Z M415.576 556.0V541.609H418.06Line truncated
|
||||
|
Before Width: | Height: | Size: 627 KiB After Width: | Height: | Size: 625 KiB |
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "stambha-engine"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Hosted Stambha engine for VM launchers"
|
||||
rust-version.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
serde = { workspace = true, features = ["std"] }
|
||||
serde_json.workspace = true
|
||||
stela-compiler.workspace = true
|
||||
stela-engine.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,131 @@
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::Serialize;
|
||||
use std::io::{self, Write};
|
||||
use stela_compiler::{GuestAddress, GuestState, TargetCpu, block::BlockProfile};
|
||||
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
|
||||
|
||||
mod qemu;
|
||||
|
||||
const RUNTIME_KIND: &str = "stambha-hosted";
|
||||
const RUNTIME_API: &str = "0.1.0";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Report the runtime protocol and available capabilities as JSON.
|
||||
Info,
|
||||
/// Translate and execute the built-in ARM64 program.
|
||||
SelfTest,
|
||||
/// Prepare a launch command for the Stambha UEFI engine under QEMU.
|
||||
BootPlan(Box<qemu::BootOptions>),
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct RuntimeInfo {
|
||||
runtime_kind: &'static str,
|
||||
runtime_api: &'static str,
|
||||
engine_version: &'static str,
|
||||
host_os: &'static str,
|
||||
host_arch: &'static str,
|
||||
capabilities: Capabilities,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Capabilities {
|
||||
native_arm64_self_test: bool,
|
||||
qemu_uefi_boot_plan: bool,
|
||||
macos_boot: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SelfTestReport {
|
||||
runtime_api: &'static str,
|
||||
guest_arch: &'static str,
|
||||
blocks_executed: usize,
|
||||
blocks_compiled: usize,
|
||||
result: u64,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
match Cli::parse().command {
|
||||
Command::Info => write_json(&RuntimeInfo {
|
||||
runtime_kind: RUNTIME_KIND,
|
||||
runtime_api: RUNTIME_API,
|
||||
engine_version: env!("CARGO_PKG_VERSION"),
|
||||
host_os: std::env::consts::OS,
|
||||
host_arch: std::env::consts::ARCH,
|
||||
capabilities: Capabilities {
|
||||
native_arm64_self_test: stela_engine::execution::platform::ensure_supported()
|
||||
.is_ok(),
|
||||
qemu_uefi_boot_plan: true,
|
||||
macos_boot: false,
|
||||
},
|
||||
}),
|
||||
Command::SelfTest => write_json(&self_test()?),
|
||||
Command::BootPlan(options) => write_json(&options.prepare()?),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_json(value: &impl Serialize) -> Result<()> {
|
||||
let mut stdout = io::stdout().lock();
|
||||
serde_json::to_writer(&mut stdout, value)?;
|
||||
writeln!(stdout)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn self_test() -> Result<SelfTestReport> {
|
||||
stela_engine::execution::platform::ensure_supported()?;
|
||||
const ENTRY: GuestAddress = GuestAddress(0x1000);
|
||||
const RETURN: GuestAddress = GuestAddress(0x2000);
|
||||
const PROGRAM: [u32; 5] = [
|
||||
0xd2800500, // MOV X0, #40
|
||||
0x14000002, // B past the next instruction
|
||||
0xd2800c60, // MOV X0, #99 (skipped)
|
||||
0x91000800, // ADD X0, X0, #2
|
||||
0xd65f03c0, // RET
|
||||
];
|
||||
let cache = tempfile::tempdir().context("create temporary self-test cache")?;
|
||||
let mut engine = BlockRuntime::new_for_target(
|
||||
1,
|
||||
cache.path().to_path_buf(),
|
||||
BlockProfile::ORDINARY,
|
||||
TargetCpu::Baseline,
|
||||
);
|
||||
engine.register_code(
|
||||
ENTRY,
|
||||
PROGRAM.into_iter().flat_map(u32::to_le_bytes).collect(),
|
||||
)?;
|
||||
let mut thread = ThreadState {
|
||||
pc: ENTRY,
|
||||
registers: GuestState::default(),
|
||||
};
|
||||
thread.registers.x[30] = RETURN.0;
|
||||
|
||||
// SAFETY: the built-in instructions have no memory accesses and the only
|
||||
// dynamic branch goes to the explicit stop address.
|
||||
let outcome = unsafe { engine.run(&mut thread, Some(RETURN), 8)? };
|
||||
ensure!(
|
||||
outcome.reason == StopReason::StopAddress && thread.pc == RETURN,
|
||||
"ARM64 self-test stopped at {:#x} with {:?}",
|
||||
thread.pc.0,
|
||||
outcome.reason
|
||||
);
|
||||
ensure!(
|
||||
thread.registers.x[0] == 42 && outcome.blocks_executed == 2 && outcome.compiled_blocks == 2,
|
||||
"unexpected ARM64 translation result or block counts"
|
||||
);
|
||||
Ok(SelfTestReport {
|
||||
runtime_api: RUNTIME_API,
|
||||
guest_arch: "arm64",
|
||||
blocks_executed: outcome.blocks_executed,
|
||||
blocks_compiled: outcome.compiled_blocks,
|
||||
result: thread.registers.x[0],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use clap::Args;
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::RUNTIME_API;
|
||||
|
||||
#[derive(Args)]
|
||||
pub(crate) struct BootOptions {
|
||||
/// QEMU x86-64 executable.
|
||||
#[arg(long)]
|
||||
qemu: PathBuf,
|
||||
/// Read-only EDK2 code image.
|
||||
#[arg(long)]
|
||||
firmware_code: PathBuf,
|
||||
/// EDK2 variables template, copied on first launch.
|
||||
#[arg(long)]
|
||||
firmware_vars: PathBuf,
|
||||
/// Directory that holds persistent firmware variables and the serial log.
|
||||
#[arg(long)]
|
||||
vm_dir: PathBuf,
|
||||
/// Directory containing EFI/BOOT/BOOTX64.EFI and EFI/stela/stela.cfg.
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with = "usb_image",
|
||||
required_unless_present = "usb_image"
|
||||
)]
|
||||
boot_volume: Option<PathBuf>,
|
||||
/// Raw Stambha USB disk image. Writes go to a temporary overlay by default.
|
||||
#[arg(long)]
|
||||
usb_image: Option<PathBuf>,
|
||||
/// USB serial used by the boot medium's Stambha configuration.
|
||||
#[arg(long, default_value = "STELAUSBIMAGE", value_parser = usb_serial)]
|
||||
usb_serial: String,
|
||||
/// Persist changes to the USB image.
|
||||
#[arg(long, requires = "usb_image")]
|
||||
write_usb: bool,
|
||||
/// Optional writable raw file attached as an NVMe disk with serial STELAANS.
|
||||
#[arg(long)]
|
||||
disk: Option<PathBuf>,
|
||||
#[arg(long, default_value_t = 8192, value_parser = clap::value_parser!(u32).range(1024..))]
|
||||
memory_mib: u32,
|
||||
#[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=64))]
|
||||
cpus: u8,
|
||||
/// Open an SDL display with a virtual keyboard and tablet.
|
||||
#[arg(long)]
|
||||
display: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct BootPlan {
|
||||
runtime_api: &'static str,
|
||||
exe_path: PathBuf,
|
||||
args: Vec<String>,
|
||||
work_dir: PathBuf,
|
||||
serial_log: PathBuf,
|
||||
}
|
||||
|
||||
impl BootOptions {
|
||||
pub(crate) fn prepare(self) -> Result<BootPlan> {
|
||||
let qemu = file(&self.qemu)?;
|
||||
let firmware_code = file(&self.firmware_code)?;
|
||||
let firmware_vars = file(&self.firmware_vars)?;
|
||||
let vm_dir = absolute(&self.vm_dir)?;
|
||||
let serial_log = vm_dir.join("serial.log");
|
||||
let vars = vm_dir.join("uefi-vars.fd");
|
||||
|
||||
let mut args: Vec<String> = [
|
||||
"-accel",
|
||||
"tcg,thread=multi",
|
||||
"-cpu",
|
||||
"max,vendor=GenuineIntel",
|
||||
"-nodefaults",
|
||||
"-no-reboot",
|
||||
"-monitor",
|
||||
"none",
|
||||
"-nic",
|
||||
"none",
|
||||
"-device",
|
||||
"isa-debug-exit,iobase=0xf4,iosize=4",
|
||||
"-serial",
|
||||
"chardev:uart",
|
||||
]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let i8042 = if self.usb_image.is_some() {
|
||||
"on"
|
||||
} else {
|
||||
"off"
|
||||
};
|
||||
option(
|
||||
&mut args,
|
||||
"-machine",
|
||||
format!("q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042={i8042},vmport=off",),
|
||||
);
|
||||
option(&mut args, "-m", format!("{}M", self.memory_mib));
|
||||
option(
|
||||
&mut args,
|
||||
"-smp",
|
||||
format!("cpus={},sockets=1,cores={},threads=1", self.cpus, self.cpus),
|
||||
);
|
||||
option(
|
||||
&mut args,
|
||||
"-display",
|
||||
if self.display { "sdl" } else { "none" },
|
||||
);
|
||||
if self.display {
|
||||
for device in ["VGA", "virtio-keyboard-pci", "virtio-tablet-pci"] {
|
||||
option(&mut args, "-device", device);
|
||||
}
|
||||
}
|
||||
option(
|
||||
&mut args,
|
||||
"-chardev",
|
||||
format!("file,id=uart,path={},append=on", qemu_path(&serial_log)?),
|
||||
);
|
||||
option(
|
||||
&mut args,
|
||||
"-drive",
|
||||
format!(
|
||||
"if=pflash,format=raw,readonly=on,file={}",
|
||||
qemu_path(&firmware_code)?
|
||||
),
|
||||
);
|
||||
option(
|
||||
&mut args,
|
||||
"-drive",
|
||||
format!("if=pflash,format=raw,file={}", qemu_path(&vars)?),
|
||||
);
|
||||
|
||||
match (self.boot_volume, self.usb_image) {
|
||||
(Some(volume), None) => {
|
||||
let volume = absolute(&volume)?;
|
||||
file(&volume.join("EFI/BOOT/BOOTX64.EFI"))?;
|
||||
file(&volume.join("EFI/stela/stela.cfg"))?;
|
||||
option(
|
||||
&mut args,
|
||||
"-drive",
|
||||
format!(
|
||||
"if=none,id=volume,format=raw,readonly=on,file=fat:{}",
|
||||
qemu_path(&volume)?
|
||||
),
|
||||
);
|
||||
option(&mut args, "-device", "virtio-blk-pci,drive=volume");
|
||||
}
|
||||
(None, Some(image)) => {
|
||||
let image = file(&image)?;
|
||||
let snapshot = if self.write_usb { "off" } else { "on" };
|
||||
option(
|
||||
&mut args,
|
||||
"-drive",
|
||||
format!(
|
||||
"if=none,id=volume,format=raw,snapshot={snapshot},file={}",
|
||||
qemu_path(&image)?
|
||||
),
|
||||
);
|
||||
option(&mut args, "-device", "qemu-xhci,id=host-usb,p2=8,p3=0");
|
||||
option(
|
||||
&mut args,
|
||||
"-device",
|
||||
format!(
|
||||
"usb-storage,drive=volume,serial={},bus=host-usb.0,bootindex=0",
|
||||
self.usb_serial
|
||||
),
|
||||
);
|
||||
}
|
||||
_ => anyhow::bail!("provide exactly one boot medium"),
|
||||
}
|
||||
if let Some(disk) = self.disk {
|
||||
option(
|
||||
&mut args,
|
||||
"-drive",
|
||||
format!(
|
||||
"if=none,id=guest,format=raw,file={}",
|
||||
qemu_path(&file(&disk)?)?
|
||||
),
|
||||
);
|
||||
option(&mut args, "-device", "nvme,drive=guest,serial=STELAANS");
|
||||
}
|
||||
|
||||
fs::create_dir_all(&vm_dir).with_context(|| format!("create {}", vm_dir.display()))?;
|
||||
prepare_vars(&firmware_vars, &vars)?;
|
||||
Ok(BootPlan {
|
||||
runtime_api: RUNTIME_API,
|
||||
exe_path: qemu,
|
||||
args,
|
||||
work_dir: vm_dir,
|
||||
serial_log,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn option(args: &mut Vec<String>, flag: &str, value: impl Into<String>) {
|
||||
args.extend([flag.to_owned(), value.into()]);
|
||||
}
|
||||
|
||||
fn usb_serial(value: &str) -> Result<String, &'static str> {
|
||||
if !value.is_empty()
|
||||
&& value.len() <= 32
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
|
||||
{
|
||||
Ok(value.to_owned())
|
||||
} else {
|
||||
Err("use 1 to 32 letters, digits, dashes or underscores for the USB serial")
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: &Path) -> Result<PathBuf> {
|
||||
let path = std::path::absolute(path)?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::path::{Component, Prefix};
|
||||
ensure!(
|
||||
matches!(path.components().next(), Some(Component::Prefix(prefix))
|
||||
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::UNC(_, _))),
|
||||
"expected a filesystem path: {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn file(path: &Path) -> Result<PathBuf> {
|
||||
let path = absolute(path)?;
|
||||
let metadata = fs::metadata(&path).with_context(|| format!("open {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_file() && metadata.len() != 0,
|
||||
"expected a nonempty file: {}",
|
||||
path.display()
|
||||
);
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn qemu_path(path: &Path) -> Result<String> {
|
||||
Ok(path
|
||||
.to_str()
|
||||
.context("QEMU paths must be valid Unicode")?
|
||||
.replace(',', ",,"))
|
||||
}
|
||||
|
||||
fn prepare_vars(template: &Path, destination: &Path) -> Result<()> {
|
||||
if !destination.try_exists()? {
|
||||
let parent = destination.parent().context("missing NVRAM directory")?;
|
||||
let mut staging = tempfile::NamedTempFile::new_in(parent)?;
|
||||
io::copy(&mut File::open(template)?, &mut staging)?;
|
||||
staging.as_file().sync_all()?;
|
||||
match staging.persist_noclobber(destination) {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error.error.into()),
|
||||
}
|
||||
}
|
||||
let actual = fs::symlink_metadata(destination)?;
|
||||
ensure!(
|
||||
actual.is_file() && actual.len() == fs::metadata(template)?.len(),
|
||||
"UEFI variable store differs in size from its template: {}",
|
||||
destination.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use std::{ffi::OsStr, fs, process::Command};
|
||||
|
||||
fn json_output(argument: &str) -> serde_json::Value {
|
||||
run_json([OsStr::new(argument)])
|
||||
}
|
||||
|
||||
fn run_json(arguments: impl IntoIterator<Item = impl AsRef<OsStr>>) -> serde_json::Value {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_stambha-engine"))
|
||||
.args(arguments)
|
||||
.output()
|
||||
.expect("start hosted engine");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
serde_json::from_slice(&output.stdout).expect("one JSON reply")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_host_capabilities() {
|
||||
let info = json_output("info");
|
||||
assert_eq!(info["runtime_kind"], "stambha-hosted");
|
||||
assert_eq!(info["runtime_api"], "0.1.0");
|
||||
assert_eq!(info["host_os"], std::env::consts::OS);
|
||||
assert_eq!(info["host_arch"], std::env::consts::ARCH);
|
||||
assert_eq!(info["capabilities"]["macos_boot"], false);
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(windows, target_os = "linux", target_os = "macos")
|
||||
))]
|
||||
#[test]
|
||||
fn executes_two_translated_arm64_blocks() {
|
||||
assert_eq!(
|
||||
json_output("info")["capabilities"]["native_arm64_self_test"],
|
||||
true
|
||||
);
|
||||
let report = json_output("self-test");
|
||||
assert_eq!(report["runtime_api"], "0.1.0");
|
||||
assert_eq!(report["guest_arch"], "arm64");
|
||||
assert_eq!(report["blocks_compiled"], 2);
|
||||
assert_eq!(report["blocks_executed"], 2);
|
||||
assert_eq!(report["result"], 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_plan_uses_file_media_and_keeps_existing_firmware_variables() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let qemu = temp.path().join("qemu");
|
||||
let code = temp.path().join("code.fd");
|
||||
let template = temp.path().join("vars.fd");
|
||||
let image = temp.path().join("test, disk.img");
|
||||
let vm = temp.path().join("test vm");
|
||||
for path in [&qemu, &code, &template, &image] {
|
||||
fs::write(path, b"template").unwrap();
|
||||
}
|
||||
let plan = || {
|
||||
run_json([
|
||||
OsStr::new("boot-plan"),
|
||||
OsStr::new("--qemu"),
|
||||
qemu.as_os_str(),
|
||||
OsStr::new("--firmware-code"),
|
||||
code.as_os_str(),
|
||||
OsStr::new("--firmware-vars"),
|
||||
template.as_os_str(),
|
||||
OsStr::new("--vm-dir"),
|
||||
vm.as_os_str(),
|
||||
OsStr::new("--usb-image"),
|
||||
image.as_os_str(),
|
||||
])
|
||||
};
|
||||
let reply = plan();
|
||||
let args = reply["args"].as_array().unwrap();
|
||||
assert!(args.iter().any(|argument| {
|
||||
argument.as_str().is_some_and(|argument| {
|
||||
argument.contains("format=raw,snapshot=on,file=")
|
||||
&& argument.ends_with("test,, disk.img")
|
||||
})
|
||||
}));
|
||||
let variables = vm.join("uefi-vars.fd");
|
||||
assert_eq!(fs::read(&variables).unwrap(), b"template");
|
||||
fs::write(&variables, b"memorize").unwrap();
|
||||
plan();
|
||||
assert_eq!(fs::read(&variables).unwrap(), b"memorize");
|
||||
}
|
||||
@@ -126,6 +126,61 @@ impl fmt::Display for AmxModel {
|
||||
pub const SINGLE_USER: &str = "--single-user";
|
||||
/// Keeps the newest presented frame at one logged address.
|
||||
pub const SCANOUT_MIRROR: &str = "--scanout-mirror";
|
||||
/// Verify the hosted Reims device through Stela's owned host PCI mappings.
|
||||
pub const PROBE_HOSTED_REIMS: &str = "--probe-hosted-reims";
|
||||
/// Place the hosted Reims apertures at the supplied ARM physical base.
|
||||
pub const HOSTED_REIMS_BASE: &str = "--hosted-reims-base";
|
||||
/// Wire hosted Reims completions to an ARM AIC vector.
|
||||
pub const HOSTED_REIMS_IRQ: &str = "--hosted-reims-irq";
|
||||
pub const HOSTED_REIMS_IRQ_MODE: &str = "--hosted-reims-irq-mode";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HostedReimsIrq {
|
||||
Auto,
|
||||
Vector(u32),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum HostedReimsIrqMode {
|
||||
#[default]
|
||||
Poll,
|
||||
Event,
|
||||
}
|
||||
|
||||
impl HostedReimsIrqMode {
|
||||
const NAMES: [(&'static str, Self); 2] = [("poll", Self::Poll), ("event", Self::Event)];
|
||||
|
||||
pub fn parse(value: &str) -> Result<Self, Error> {
|
||||
Self::NAMES
|
||||
.iter()
|
||||
.find(|(name, _)| *name == value)
|
||||
.map(|(_, mode)| *mode)
|
||||
.ok_or(Error::HostedReimsIrqMode)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
Self::NAMES
|
||||
.iter()
|
||||
.find(|(_, mode)| *mode == self)
|
||||
.map(|(name, _)| *name)
|
||||
.unwrap_or("poll")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for HostedReimsIrqMode {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for HostedReimsIrq {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Auto => formatter.write_str("auto"),
|
||||
Self::Vector(vector) => write!(formatter, "{vector}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub const WIFI: &str = "--wifi";
|
||||
pub const WIFI_KEY: &str = "--wifi-key";
|
||||
pub const WIFI_COUNTRY: &str = "--wifi-country";
|
||||
@@ -696,6 +751,10 @@ pub struct System {
|
||||
pub gpu_strict_families: bool,
|
||||
/// Keep Intel's CCS compression on ([`INTEL_CCS`]).
|
||||
pub intel_ccs: bool,
|
||||
pub probe_hosted_reims: bool,
|
||||
pub hosted_reims_base: Option<u64>,
|
||||
pub hosted_reims_irq: Option<HostedReimsIrq>,
|
||||
pub hosted_reims_irq_mode: Option<HostedReimsIrqMode>,
|
||||
/// The NVRAM boot volume the loader chose (`--boot-volume`), naming the
|
||||
/// Preboot disk's container and volume group.
|
||||
pub boot_volume: Option<BootVolume>,
|
||||
@@ -976,6 +1035,10 @@ impl Default for System {
|
||||
scanout_mirror: false,
|
||||
gpu_strict_families: false,
|
||||
intel_ccs: false,
|
||||
probe_hosted_reims: false,
|
||||
hosted_reims_base: None,
|
||||
hosted_reims_irq: None,
|
||||
hosted_reims_irq_mode: None,
|
||||
boot_command: None,
|
||||
upgrade: false,
|
||||
recovery: None,
|
||||
@@ -1586,6 +1649,10 @@ impl fmt::Display for System {
|
||||
line.flag(SCANOUT_MIRROR, self.scanout_mirror)?;
|
||||
line.flag(GPU_STRICT_FAMILIES, self.gpu_strict_families)?;
|
||||
line.flag(INTEL_CCS, self.intel_ccs)?;
|
||||
line.flag(PROBE_HOSTED_REIMS, self.probe_hosted_reims)?;
|
||||
line.value(HOSTED_REIMS_BASE, self.hosted_reims_base.map(Hex))?;
|
||||
line.value(HOSTED_REIMS_IRQ, self.hosted_reims_irq)?;
|
||||
line.value(HOSTED_REIMS_IRQ_MODE, self.hosted_reims_irq_mode)?;
|
||||
line.flag(boot_selection::UPGRADE_OPTION, self.upgrade)?;
|
||||
line.flag(
|
||||
boot_selection::PAIRED_RECOVERY_OPTION,
|
||||
|
||||
@@ -26,6 +26,9 @@ pub enum Error {
|
||||
AudioMode,
|
||||
DumpRegister,
|
||||
Number,
|
||||
HostedReimsBase,
|
||||
HostedReimsIrq,
|
||||
HostedReimsIrqMode,
|
||||
UrlScheme,
|
||||
UrlPath,
|
||||
UrlHost,
|
||||
@@ -190,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",
|
||||
|
||||
@@ -169,6 +169,33 @@ impl ParseState<'_> {
|
||||
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(
|
||||
|
||||
@@ -539,6 +539,62 @@ fn intel_ccs_round_trips_and_is_off_unless_written() {
|
||||
assert!(intel_ccs_line(true).contains(INTEL_CCS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_probe_round_trips() {
|
||||
assert!(!round_trip("--system").probe_hosted_reims);
|
||||
assert!(round_trip(&format!("--system {PROBE_HOSTED_REIMS}")).probe_hosted_reims);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_guest_base_must_be_aligned_and_excludes_probe() {
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x200000000").hosted_reims_base,
|
||||
Some(0x200000000)
|
||||
);
|
||||
for invalid in [
|
||||
"--system --hosted-reims-base 0",
|
||||
"--system --hosted-reims-base 0x200004000",
|
||||
"--system --hosted-reims-base 0x200000000 --probe-hosted-reims",
|
||||
] {
|
||||
assert_eq!(System::parse(invalid).unwrap_err(), Error::HostedReimsBase);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_reims_irq_requires_a_guest_aperture() {
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq 740")
|
||||
.hosted_reims_irq,
|
||||
Some(HostedReimsIrq::Vector(740))
|
||||
);
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto")
|
||||
.hosted_reims_irq,
|
||||
Some(HostedReimsIrq::Auto)
|
||||
);
|
||||
assert_eq!(
|
||||
System::parse("--system --hosted-reims-irq 740").unwrap_err(),
|
||||
Error::HostedReimsIrq
|
||||
);
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode poll")
|
||||
.hosted_reims_irq_mode,
|
||||
Some(HostedReimsIrqMode::Poll)
|
||||
);
|
||||
assert_eq!(
|
||||
round_trip("--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode event")
|
||||
.hosted_reims_irq_mode,
|
||||
Some(HostedReimsIrqMode::Event)
|
||||
);
|
||||
for invalid in [
|
||||
"--system --hosted-reims-base 0x300000000 --hosted-reims-irq-mode event",
|
||||
"--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode bogus",
|
||||
"--system --hosted-reims-base 0x300000000 --hosted-reims-irq auto --hosted-reims-irq-mode poll --hosted-reims-irq-mode event",
|
||||
] {
|
||||
assert_eq!(System::parse(invalid).unwrap_err(), Error::HostedReimsIrqMode);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maintenance_writes_require_an_explicit_preboot_selection() {
|
||||
let ordinary = round_trip(&format!("--system --preboot {DISK}"));
|
||||
|
||||
@@ -8,6 +8,17 @@ 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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -15,7 +15,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]]
|
||||
@@ -119,9 +119,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[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",
|
||||
@@ -177,7 +177,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.5",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -258,9 +258,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",
|
||||
]
|
||||
@@ -284,7 +284,7 @@ dependencies = [
|
||||
"defmt-parser",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -308,9 +308,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 = "digest"
|
||||
@@ -357,9 +357,9 @@ dependencies = [
|
||||
|
||||
[[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"
|
||||
@@ -389,9 +389,9 @@ dependencies = [
|
||||
|
||||
[[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 = "generic-array"
|
||||
@@ -529,9 +529,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",
|
||||
]
|
||||
@@ -547,15 +547,15 @@ dependencies = [
|
||||
|
||||
[[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 = "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"
|
||||
@@ -565,9 +565,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[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 = "managed"
|
||||
@@ -643,9 +643,9 @@ checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[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",
|
||||
"indexmap",
|
||||
@@ -718,7 +718,7 @@ checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -799,9 +799,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",
|
||||
@@ -825,9 +825,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 = [
|
||||
"zeroize",
|
||||
]
|
||||
@@ -883,7 +883,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1135,6 +1135,7 @@ dependencies = [
|
||||
"stela-fingerprint",
|
||||
"stela-formats",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1402,9 +1403,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",
|
||||
@@ -1441,7 +1442,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1519,7 +1520,7 @@ checksum = "643efa8b64be89780bc498b290fab04337c7c4d171cc82cce2e133a74616dcc4"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.8",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -30,6 +30,10 @@ test = false
|
||||
[features]
|
||||
default = []
|
||||
diagnostics = ["stela-drivers/irq-diagnostics"]
|
||||
# Include the arm64e device driver built by cargo xtask guest.
|
||||
hosted-reims-kext = []
|
||||
# Include a prepared ReimsGraphics KEXT instead of the diagnostic driver.
|
||||
hosted-reims-graphics = []
|
||||
native-profile = ["stela-soc/native-profile", "stela-engine/native-profile"]
|
||||
# NVK, NIR and NAK in the image, from `cargo xtask gpu nvk`.
|
||||
nvk = ["dep:stela-mesa", "stela-drivers/metal-linked"]
|
||||
|
||||
@@ -347,6 +347,7 @@ fn take_screen() -> bool {
|
||||
return false;
|
||||
}
|
||||
DCP_PRESENTED.store(true, Ordering::Relaxed);
|
||||
output::arguments(format_args!("DISPLAY first frame\n"));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -35,6 +35,20 @@ mod kext {
|
||||
"/../../target/guest/StelaGPU.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(all(feature = "hosted-reims-kext", not(feature = "hosted-reims-graphics")))]
|
||||
mod hosted_reims_kext {
|
||||
include!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../target/guest/ReimsHostedDevice.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
mod hosted_reims_graphics {
|
||||
include!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../target/guest/ReimsGraphics.kext.rs"
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "nvk")]
|
||||
mod refused;
|
||||
#[cfg(feature = "nvk")]
|
||||
@@ -3615,17 +3629,36 @@ pub(super) fn no_metal_device() -> Option<&'static str> {
|
||||
Some("this stela.efi was built without GPU drivers (the `nvk` feature)")
|
||||
}
|
||||
|
||||
/// The kexts a boot that gives the GPUs to nouveau links into its system.
|
||||
pub(super) fn kexts() -> Vec<stela_loader::aux_kc::Kext<'static>> {
|
||||
/// The GPU kexts this boot links into its system.
|
||||
pub(super) fn kexts(_hosted_reims: bool) -> Vec<stela_loader::aux_kc::Kext<'static>> {
|
||||
#[allow(unused_mut)]
|
||||
let mut bundles = Vec::new();
|
||||
#[cfg(feature = "nvk")]
|
||||
return alloc::vec![stela_loader::aux_kc::Kext {
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
info: kext::INFO,
|
||||
objects: kext::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/StelaGPU.kext".into(),
|
||||
trusted_code: kext::TRUSTED_CODE.to_vec(),
|
||||
}];
|
||||
#[cfg(not(feature = "nvk"))]
|
||||
Vec::new()
|
||||
});
|
||||
#[cfg(all(feature = "hosted-reims-kext", not(feature = "hosted-reims-graphics")))]
|
||||
if _hosted_reims {
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
info: hosted_reims_kext::INFO,
|
||||
objects: hosted_reims_kext::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/ReimsHostedDevice.kext".into(),
|
||||
trusted_code: hosted_reims_kext::TRUSTED_CODE.to_vec(),
|
||||
});
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
if _hosted_reims {
|
||||
bundles.push(stela_loader::aux_kc::Kext {
|
||||
info: hosted_reims_graphics::INFO,
|
||||
objects: hosted_reims_graphics::OBJECTS.to_vec(),
|
||||
bundle_path: "/Library/Extensions/ReimsGraphics.kext".into(),
|
||||
trusted_code: hosted_reims_graphics::TRUSTED_CODE.to_vec(),
|
||||
});
|
||||
}
|
||||
bundles
|
||||
}
|
||||
|
||||
/// Takes the display for the GPUs [`open`] bound, in the monitor's own mode
|
||||
|
||||
@@ -71,9 +71,10 @@ use faults::*;
|
||||
pub(crate) use faults::{gate_fill, native_exception, page_fault};
|
||||
pub(crate) use signals::{
|
||||
clear_interrupted, completion_signal, device_signals, doorbell_counter, doorbells,
|
||||
end_stale_in_service, in_interrupt, interrupted, join_shootdown, network_interrupt,
|
||||
network_signal, nmi, ring, root_irq_active, shootdown, shootdown_interrupt, signal_interrupt,
|
||||
sleep_for, stale_in_service_report, take_network_signal, undelivered_doorbells, wake_interrupt,
|
||||
end_stale_in_service, gpu_interrupt, gpu_signal, gpu_signalled, gpu_signals, in_interrupt,
|
||||
interrupted, join_shootdown, network_interrupt, network_signal, nmi, ring, root_irq_active,
|
||||
shootdown, shootdown_interrupt, signal_interrupt, sleep_for, stale_in_service_report,
|
||||
take_gpu_signal, take_network_signal, undelivered_doorbells, wake_interrupt,
|
||||
};
|
||||
pub use signals::{spurious_interrupt, stray_interrupt, timer_interrupt};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
|
||||
@@ -875,7 +875,7 @@ impl Host for BareHost<'_> {
|
||||
// service moves them now rather than at its next tick, about 4 ms
|
||||
// on. Taken either way, as a disk's due service moves them too.
|
||||
let frames = super::take_network_signal();
|
||||
super::super::storage::signalled() || frames
|
||||
super::super::storage::signalled() || frames || super::gpu_signalled()
|
||||
}
|
||||
|
||||
fn report(&mut self, event: &stela_engine::machine::Event) {
|
||||
|
||||
@@ -120,7 +120,14 @@ impl Owner {
|
||||
/// backing, before a guest regime, frame or registered RAM exists: the
|
||||
/// host drivers that read a bundle's DRAM base run after `install`.
|
||||
/// Root contexts and MMIO views see only the host spans, which stay.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn place_ram(&mut self, base: u64) -> Result<()> {
|
||||
self.place_ram_except_host(base, None)
|
||||
}
|
||||
|
||||
/// [`Self::place_ram`], keeping any range backed by `fixed_host` at its
|
||||
/// fixed guest physical address and maintaining guest-address order.
|
||||
pub(crate) fn place_ram_except_host(&mut self, base: u64, fixed_host: Option<u64>) -> Result<()> {
|
||||
if current() != self.local.as_ptr() {
|
||||
return Err(refuse!("native Host owner migrated"));
|
||||
}
|
||||
@@ -130,7 +137,7 @@ impl Owner {
|
||||
"guest RAM is placed before the guest's memory is registered"
|
||||
));
|
||||
}
|
||||
super::ram::place(&mut state.ram, base);
|
||||
super::ram::place_except_host(&mut state.ram, base, fixed_host);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -221,6 +221,36 @@ pub(crate) fn take_network_signal() -> bool {
|
||||
&& NETWORK_SIGNALLED.swap(false, core::sync::atomic::Ordering::AcqRel)
|
||||
}
|
||||
|
||||
/// Hosted Reims MSI-X wakes sent to the BSP on `GPU_VECTOR`.
|
||||
static GPU_SIGNALS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
|
||||
static GPU_SIGNALLED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub(crate) fn gpu_signal(id: u64) -> Option<stela_drivers::bus::irq::MsiMessage> {
|
||||
(id < 255).then(|| stela_drivers::bus::irq::MsiMessage {
|
||||
address: 0xfee0_0000 | id << 12,
|
||||
data: u32::from(super::super::interrupts::GPU_VECTOR),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn gpu_interrupt() {
|
||||
GPU_SIGNALS.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||
GPU_SIGNALLED.store(true, core::sync::atomic::Ordering::Release);
|
||||
wake_interrupt();
|
||||
}
|
||||
|
||||
pub(crate) fn gpu_signals() -> u64 {
|
||||
GPU_SIGNALS.load(core::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn gpu_signalled() -> bool {
|
||||
GPU_SIGNALLED.load(core::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub(crate) fn take_gpu_signal() -> bool {
|
||||
GPU_SIGNALLED.load(core::sync::atomic::Ordering::Relaxed)
|
||||
&& GPU_SIGNALLED.swap(false, core::sync::atomic::Ordering::AcqRel)
|
||||
}
|
||||
|
||||
/// Doorbells a local APIC did not deliver since the last report: each may
|
||||
/// leave its processor asleep until its next wake.
|
||||
pub(super) static UNDELIVERED: core::sync::atomic::AtomicU64 =
|
||||
|
||||
@@ -33,6 +33,8 @@ pub(crate) const SIGNAL_VECTOR: u8 = 0x62;
|
||||
/// Apart from [`SIGNAL_VECTOR`], so a disk does not look for completions
|
||||
/// each time a frame comes.
|
||||
pub(crate) const NETWORK_VECTOR: u8 = 0x63;
|
||||
/// Hosted Reims GPU MSI-X wake vector (`host::gpu_signal`).
|
||||
pub(crate) const GPU_VECTOR: u8 = 0x64;
|
||||
pub const SPURIOUS_VECTOR: u8 = 0xff;
|
||||
const CODE_SELECTOR: u16 = 0x08;
|
||||
const DATA_SELECTOR: u16 = 0x10;
|
||||
@@ -489,7 +491,7 @@ vectors!(
|
||||
64 none,
|
||||
80 none, 81 none, 82 none, 83 none, 84 none, 85 none, 86 none, 87 none,
|
||||
88 none, 89 none, 90 none, 91 none, 92 none, 93 none, 94 none, 95 none,
|
||||
96 none, 97 none, 98 none, 99 none, 236 none, 251 none, 253 none, 255 none,
|
||||
96 none, 97 none, 98 none, 99 none, 100 none, 236 none, 251 none, 253 none, 255 none,
|
||||
);
|
||||
|
||||
/// Whether the table gives `vector` a stub, and so a gate: an interrupt on
|
||||
@@ -510,6 +512,7 @@ const _: () = assert!(
|
||||
&& has_stub(SHOOTDOWN_VECTOR)
|
||||
&& has_stub(SIGNAL_VECTOR)
|
||||
&& has_stub(NETWORK_VECTOR)
|
||||
&& has_stub(GPU_VECTOR)
|
||||
&& has_stub(SPURIOUS_VECTOR)
|
||||
);
|
||||
// The timer's class is above every device and completion vector's, so none
|
||||
@@ -520,6 +523,7 @@ const _: () = assert!(
|
||||
TIMER_VECTOR >> 4 > 0x5f >> 4
|
||||
&& TIMER_VECTOR >> 4 > SIGNAL_VECTOR >> 4
|
||||
&& TIMER_VECTOR >> 4 > NETWORK_VECTOR >> 4
|
||||
&& TIMER_VECTOR >> 4 > GPU_VECTOR >> 4
|
||||
&& NATIVE_WAKE_VECTOR >> 4 > TIMER_VECTOR >> 4
|
||||
&& SHOOTDOWN_VECTOR >> 4 > TIMER_VECTOR >> 4
|
||||
&& TIMER_VECTOR < SPURIOUS_VECTOR
|
||||
@@ -540,6 +544,7 @@ pub(crate) const ORDINARY_ENTRIES: () = {
|
||||
interrupt_image::ist(TIMER_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
&& interrupt_image::ist(SIGNAL_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
&& interrupt_image::ist(NETWORK_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
&& interrupt_image::ist(GPU_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
&& interrupt_image::ist(SHOOTDOWN_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
&& interrupt_image::ist(NATIVE_WAKE_VECTOR) == interrupt_image::ORDINARY_IST
|
||||
);
|
||||
@@ -790,6 +795,7 @@ pub(crate) extern "sysv64" fn interrupt(frame: &mut Frame, saved: &SavedState<'_
|
||||
SIGNAL_VECTOR => host::signal_interrupt(),
|
||||
SHOOTDOWN_VECTOR => host::shootdown_interrupt(),
|
||||
NETWORK_VECTOR => host::network_interrupt(),
|
||||
GPU_VECTOR => host::gpu_interrupt(),
|
||||
SPURIOUS_VECTOR => host::spurious_interrupt(),
|
||||
vector @ 32.. => host::stray_interrupt(vector),
|
||||
_ => fatal(frame),
|
||||
|
||||
@@ -941,6 +941,41 @@ fn write_times_report<H: Host>(machine: &Machine<H, parallel::Board>, tsc_hz: u6
|
||||
/// the event reads that claimed an IRQ or found none
|
||||
/// (`stela_soc::aic::AicCounts`): pins per rise is the fan-out, and the
|
||||
/// empty reads mostly the CPUs that lost the claim.
|
||||
fn reims_irq_report<H: Host>(machine: &Machine<H, parallel::Board>) {
|
||||
let Some(stats) = machine
|
||||
.devices
|
||||
.with(|devices| devices.hosted_reims_irq_stats())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let hz = u128::from(stela_soc::counter::FREQUENCY_HZ);
|
||||
let ticks_to_us = |ticks: u64| u128::from(ticks) * 1_000_000 / hz;
|
||||
let ticks_to_ms = |ticks: u64| u128::from(ticks) * 1000 / hz;
|
||||
let mode = if stats.event_driven { "event" } else { "poll" };
|
||||
let ack_us_avg = if stats.ack_lat_samples == 0 {
|
||||
0
|
||||
} else {
|
||||
ticks_to_us(stats.ack_lat_sum_ticks) / u128::from(stats.ack_lat_samples)
|
||||
};
|
||||
output::arguments(format_args!(
|
||||
"REIMS IRQ mode={mode} seen={} polls={} msi={} fallback={} injects={} coalesced={} reads={} acks={} stale={} ack_us_avg={ack_us_avg} ack_us_max={} first_inj_ms={} first_ack_ms={} host_msi={}
|
||||
",
|
||||
stats.seen,
|
||||
stats.polls,
|
||||
stats.msi_wakes,
|
||||
stats.fallback_polls,
|
||||
stats.injects,
|
||||
stats.coalesced,
|
||||
stats.token_reads,
|
||||
stats.acks,
|
||||
stats.stale_acks,
|
||||
ticks_to_us(stats.ack_lat_max_ticks),
|
||||
ticks_to_ms(stats.first_inject_ticks),
|
||||
ticks_to_ms(stats.first_ack_ticks),
|
||||
host::gpu_signals(),
|
||||
));
|
||||
}
|
||||
|
||||
fn aic_counts_report<H: Host>(machine: &Machine<H, parallel::Board>) {
|
||||
let Some(counts) = machine.devices.with(|devices| devices.take_aic_counts()) else {
|
||||
return;
|
||||
@@ -1089,6 +1124,9 @@ pub(super) fn run<H: Host>(
|
||||
// The GPUs' work waits for a boot PE that holds no lock, as the
|
||||
// service does, for a bounded time (`gpu::pump_due`).
|
||||
super::gpu::interrupt_window();
|
||||
if host::take_gpu_signal() {
|
||||
machine.poll_hosted_devices();
|
||||
}
|
||||
let pump = super::gpu::pump_due(calm(machine, quiet));
|
||||
// The frames the DCP model presented reach the screen outside the
|
||||
// devices' lock its presents hold, from the other PEs while they
|
||||
@@ -1171,6 +1209,7 @@ pub(super) fn run<H: Host>(
|
||||
millis(hub.clock_lag().0),
|
||||
));
|
||||
}
|
||||
reims_irq_report(machine);
|
||||
output::report_log_stores();
|
||||
return panicked.unwrap_or(stop);
|
||||
}
|
||||
@@ -1896,6 +1935,7 @@ impl Heartbeat {
|
||||
for state in machine.devices.with(|devices| devices.usb_diagnostics()) {
|
||||
output::arguments(format_args!("USB {state}\n"));
|
||||
}
|
||||
reims_irq_report(machine);
|
||||
// The SPI NOR's work on every PE since the last beat: an
|
||||
// NVRAM sync runs through it inside XNU's halt/restart timer.
|
||||
if let Some(nor) = machine
|
||||
@@ -2243,6 +2283,7 @@ impl Heartbeat {
|
||||
// GEXIT's, SVC's and ERET's.
|
||||
let mut transitions =
|
||||
String::from("PES TRANSITIONS genter/engine/gexit/engine/svc/engine/eret/engine");
|
||||
let mut native_ttbr0 = String::from("PES NATIVE_TTBR0 hit/miss");
|
||||
// All PEs: why SVC, ERET, GENTER and GEXIT took the engine path.
|
||||
let mut transition_misses = [0u64; 36];
|
||||
// All PEs: why TTBR0 changes took the engine path.
|
||||
@@ -2472,6 +2513,13 @@ impl Heartbeat {
|
||||
&before.itlb_sources,
|
||||
);
|
||||
deltas(&mut transitions, pe, &now.transitions, &before.transitions);
|
||||
let ttbr0_hits = now.contexts[1].saturating_sub(before.contexts[1]);
|
||||
let ttbr0_misses = now
|
||||
.switch_misses
|
||||
.iter()
|
||||
.sum::<u64>()
|
||||
.saturating_sub(before.switch_misses.iter().sum::<u64>());
|
||||
native_ttbr0.push_str(&format!(" {pe}:{ttbr0_hits}/{ttbr0_misses}"));
|
||||
for (total, (now, before)) in transition_misses.iter_mut().zip(
|
||||
now.transition_misses
|
||||
.as_flattened()
|
||||
@@ -2907,6 +2955,7 @@ impl Heartbeat {
|
||||
engine_barriers: super::speculation::take_issued(),
|
||||
};
|
||||
output::arguments(format_args!("{}", prediction.line()));
|
||||
output::arguments(format_args!("{native_ttbr0}\n"));
|
||||
let [fallthrough, direct, indirect, call, ret] = [0, 1, 2, 3, 4].map(|kind| {
|
||||
branch_misses[kind * 8..kind * 8 + 8]
|
||||
.iter()
|
||||
|
||||
@@ -113,7 +113,7 @@ fn from_disk(
|
||||
} else if let Some(kind) = options.recovery {
|
||||
bundle::recovery_from_disk(partition, kind, options.boot_volume, &defaults)
|
||||
} else {
|
||||
let kexts = gpu::kexts();
|
||||
let kexts = gpu::kexts(options.hosted_reims_irq.is_some());
|
||||
let request = installed::Request {
|
||||
volume: options.boot_volume,
|
||||
kexts: &kexts,
|
||||
@@ -161,6 +161,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
|
||||
if options.boots_macos()
|
||||
&& !options.single_user
|
||||
&& !options.bundle_repair
|
||||
&& host.devices.hosted_reims.is_none()
|
||||
&& let Some(reason) = gpu::no_metal_device()
|
||||
{
|
||||
// An Intel GPU whose GuC failed starts without it next time.
|
||||
@@ -429,6 +430,37 @@ fn open_host(
|
||||
// read from its disk by the host drivers, which run after the host is
|
||||
// installed; the placements then move there (`HostOwner::place_ram`).
|
||||
let mut ram = guest_ram(handoff, options).unwrap_or_else(|error| output::fatal(error));
|
||||
let fixed_reims_host = if let Some(base) = options.hosted_reims_base
|
||||
&& handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES
|
||||
{
|
||||
let apertures = stela_contracts::reims_hosted::Apertures::at(base)
|
||||
.unwrap_or_else(|| output::fatal("invalid hosted Reims guest address"));
|
||||
if ram.iter().any(|range| apertures.overlaps(range.guest, range.bytes)) {
|
||||
output::fatal("hosted Reims apertures overlap guest RAM");
|
||||
}
|
||||
// SAFETY: BSP at CPL0 with IF=0 and APs parked, before root_identity
|
||||
// capture and AP startup so every core adopts the WB MTRR.
|
||||
unsafe {
|
||||
crate::native_memory::ensure_writeback_mtrr(
|
||||
handoff.hosted_reims_region.physical,
|
||||
handoff.hosted_reims_region.bytes,
|
||||
)
|
||||
}
|
||||
.unwrap_or_else(|error| {
|
||||
output::fatal(format_args!(
|
||||
"hosted Reims BAR2 write-back MTRR refused: {error:?}"
|
||||
))
|
||||
});
|
||||
ram.push(RamRange {
|
||||
guest: apertures.region,
|
||||
host: handoff.hosted_reims_region.physical,
|
||||
bytes: handoff.hosted_reims_region.bytes,
|
||||
});
|
||||
ram.sort_by_key(|range| range.guest);
|
||||
Some(handoff.hosted_reims_region.physical)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The translation store the loader read, and its partition when the
|
||||
// pack can be rewritten.
|
||||
let translation_store = handoff.files[..handoff.file_count]
|
||||
@@ -608,15 +640,22 @@ fn open_host(
|
||||
options.dram_base = base;
|
||||
}
|
||||
}
|
||||
ram::place(&mut ram, options.dram_base);
|
||||
ram::place_except_host(&mut ram, options.dram_base, fixed_reims_host);
|
||||
host_owner
|
||||
.place_ram(options.dram_base)
|
||||
.place_ram_except_host(options.dram_base, fixed_reims_host)
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
for range in &ram {
|
||||
output::arguments(format_args!(
|
||||
"GUEST DRAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
if Some(range.host) == fixed_reims_host {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims RAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
} else {
|
||||
output::arguments(format_args!(
|
||||
"GUEST DRAM pa={:#x} bytes={:#x} host={:#x}\n",
|
||||
range.guest, range.bytes, range.host
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(url) = &options.network_check {
|
||||
@@ -1066,6 +1105,7 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
guest_network,
|
||||
host_disks,
|
||||
fdr: mut fdr_device,
|
||||
hosted_reims,
|
||||
..
|
||||
},
|
||||
ram: worker_ram,
|
||||
@@ -1092,9 +1132,9 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
.map(|assigned| gpu::gate::place(&mut assigned.tree))
|
||||
.unwrap_or_default();
|
||||
#[cfg(feature = "nvk")]
|
||||
let metal_device = !gpu_gates.is_empty();
|
||||
let metal_device = !gpu_gates.is_empty() || hosted_reims.is_some();
|
||||
#[cfg(not(feature = "nvk"))]
|
||||
let metal_device = false;
|
||||
let metal_device = hosted_reims.is_some();
|
||||
if let Some(assigned) = &mut assigned
|
||||
&& options.hides_agx(metal_device)
|
||||
{
|
||||
@@ -1125,6 +1165,19 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
))
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "hosted-reims-graphics")]
|
||||
if let Some(assigned) = &mut assigned
|
||||
&& hosted_reims.is_some()
|
||||
{
|
||||
let retired = stela_loader::devices::hide_external_outputs(&mut assigned.tree);
|
||||
if !retired.is_empty() {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims hides DCP external outputs ({} nodes) so ReimsGraphics is the sole display\n",
|
||||
retired.len()
|
||||
));
|
||||
hidden_devices.extend(retired);
|
||||
}
|
||||
}
|
||||
hardware_step("canonical-ram");
|
||||
// SAFETY: all raw guest input copies have ended, AP executors are waiting
|
||||
// for their guest contexts, and no guest/device DMA producer has entered.
|
||||
@@ -1155,6 +1208,35 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
boot_processor,
|
||||
));
|
||||
}
|
||||
let direct_reims_region =
|
||||
handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES;
|
||||
let reims = hosted_reims.as_ref().map(|_| {
|
||||
let (apertures, vector) = hosted_reims_placement(
|
||||
options,
|
||||
&worker_ram,
|
||||
direct_reims_region.then_some(handoff.hosted_reims_region.physical),
|
||||
board.as_ref(),
|
||||
assigned.as_ref().map(|assigned| &assigned.tree),
|
||||
);
|
||||
if let (Some(assigned), Some(vector)) = (&mut assigned, vector) {
|
||||
stela_loader::stela_gpu::place_hosted_reims(&mut assigned.tree, apertures, vector)
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims DeviceTree /arm-io/reims-graphics irq={vector}\n"
|
||||
));
|
||||
}
|
||||
(apertures, vector)
|
||||
});
|
||||
let projected_bytes = assigned.as_ref().map(|assigned| assigned.tree.serialize());
|
||||
if reims.is_some_and(|(_, vector)| vector.is_some())
|
||||
&& let (Some(previous), Some(bytes)) = (&board, &projected_bytes)
|
||||
{
|
||||
let described = board::board(bytes).unwrap_or_else(|error| output::fatal(error));
|
||||
if described.aic != previous.aic {
|
||||
output::fatal("Reims DeviceTree changed the board's AIC capacity");
|
||||
}
|
||||
board = Some(described);
|
||||
}
|
||||
// The verified image is placed and its provenance is owned. The
|
||||
// remaining device and flash consumers read board firmware by name.
|
||||
if let Some(files) = &mut built {
|
||||
@@ -1164,7 +1246,6 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
.unwrap_or_default();
|
||||
files.retain(|(name, _)| firmware.contains(name));
|
||||
}
|
||||
let projected_bytes = assigned.as_ref().map(|assigned| assigned.tree.serialize());
|
||||
let tree = projected_bytes
|
||||
.as_deref()
|
||||
.or_else(|| loaded_tree.as_ref().map(|tree| tree.bytes()));
|
||||
@@ -1227,6 +1308,51 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! {
|
||||
loaded_source.as_ref(),
|
||||
tree,
|
||||
);
|
||||
if let Some((mut transport, (apertures, vector))) = hosted_reims.zip(reims) {
|
||||
let fixed_reims_host = direct_reims_region.then_some(handoff.hosted_reims_region.physical);
|
||||
let dram_ranges: alloc::vec::Vec<(u64, u64, u64)> = worker_ram
|
||||
.iter()
|
||||
.filter(|range| Some(range.host) != fixed_reims_host)
|
||||
.map(|range| (range.guest, range.host, range.bytes))
|
||||
.collect();
|
||||
match transport.publish_guest_ram(&dram_ranges) {
|
||||
Ok(Some(committed)) => output::arguments(format_args!(
|
||||
"GUEST Reims zero-copy RAM map ranges={committed} (staged={})\n",
|
||||
dram_ranges.len()
|
||||
)),
|
||||
Ok(None) => output::arguments(format_args!(
|
||||
"GUEST Reims zero-copy RAM map unsupported by host QEMU (copy-only mode)\n"
|
||||
)),
|
||||
Err(error) => output::arguments(format_args!(
|
||||
"GUEST Reims zero-copy RAM map warning: {error}\n"
|
||||
)),
|
||||
}
|
||||
let installed = match (direct_reims_region, vector) {
|
||||
(true, Some(vector)) => {
|
||||
devices.add_hosted_reims_direct_region_with_interrupt(apertures, transport, vector)
|
||||
}
|
||||
(true, None) => devices.add_hosted_reims_direct_region(apertures, transport),
|
||||
(false, Some(vector)) => {
|
||||
devices.add_hosted_reims_with_interrupt(apertures, transport, vector)
|
||||
}
|
||||
(false, None) => devices.add_hosted_reims(apertures, transport),
|
||||
};
|
||||
installed
|
||||
.unwrap_or_else(|error| output::fatal(format_args!("hosted Reims guest bus: {error:?}")));
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims MMIO registers={:#x} region={:#x} doorbells={:#x}\n",
|
||||
apertures.registers, apertures.region, apertures.doorbells
|
||||
));
|
||||
if direct_reims_region {
|
||||
output::arguments(format_args!(
|
||||
"GUEST Reims region direct-mapped RAM pa={:#x} host={:#x}\n",
|
||||
apertures.region, handoff.hosted_reims_region.physical
|
||||
));
|
||||
}
|
||||
if let Some(vector) = vector {
|
||||
output::arguments(format_args!("GUEST Reims AIC vector={vector}\n"));
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "nvk")]
|
||||
hardware_step("add-gpu-gates");
|
||||
#[cfg(feature = "nvk")]
|
||||
@@ -3406,6 +3532,7 @@ struct HostDevices {
|
||||
guest_network: Option<network::GuestNetwork>,
|
||||
host_disks: storage::HostDisks,
|
||||
fdr: Option<alloc::boxed::Box<dyn stela_drivers::block::BlockDevice>>,
|
||||
hosted_reims: Option<stela_drivers::probe::reims_hosted::PciTransport>,
|
||||
}
|
||||
|
||||
/// Probe the host's devices once, with the native services when the
|
||||
@@ -3474,6 +3601,7 @@ fn start_devices(
|
||||
} = wanted;
|
||||
let mut fdr_device = None;
|
||||
let mut host_usb = None;
|
||||
let mut hosted_reims = None;
|
||||
let mut host_bluetooth: Option<bluetooth::HostBluetooth> = None;
|
||||
let (services, medium, preboot, host_input, host_network, usb_disks, guest_network, host_disks) =
|
||||
if targets.is_empty()
|
||||
@@ -3484,6 +3612,8 @@ fn start_devices(
|
||||
&& options.usb_storage.is_empty()
|
||||
&& !options.external_disks
|
||||
&& !options.guest_network
|
||||
&& !options.probe_hosted_reims
|
||||
&& options.hosted_reims_base.is_none()
|
||||
&& translation_store.is_none()
|
||||
&& fdr_partition.is_none()
|
||||
{
|
||||
@@ -3708,6 +3838,19 @@ fn start_devices(
|
||||
stela_boot_core::options::intel_ccs_line(options.intel_ccs)
|
||||
));
|
||||
}
|
||||
if options.probe_hosted_reims || options.hosted_reims_base.is_some() {
|
||||
let work = work.unwrap_or_else(|error| output::fatal(error));
|
||||
hosted_reims = prepare_hosted_reims(
|
||||
handoff,
|
||||
options,
|
||||
&gpus,
|
||||
work,
|
||||
mmio,
|
||||
remappers,
|
||||
host_acpi,
|
||||
bsp_apic,
|
||||
);
|
||||
}
|
||||
if options.boots_macos()
|
||||
&& let Ok(work) = work
|
||||
&& let Some(mut fallback) = open_gpus(
|
||||
@@ -3875,5 +4018,127 @@ fn start_devices(
|
||||
guest_network,
|
||||
host_disks,
|
||||
fdr: fdr_device,
|
||||
hosted_reims,
|
||||
}
|
||||
}
|
||||
|
||||
fn hosted_reims_placement(
|
||||
options: &Options,
|
||||
ram: &[RamRange],
|
||||
fixed_reims_host: Option<u64>,
|
||||
board: Option<&board::Board>,
|
||||
tree: Option<&DeviceTree>,
|
||||
) -> (stela_contracts::reims_hosted::Apertures, Option<u32>) {
|
||||
use stela_boot_core::options::HostedReimsIrq;
|
||||
use stela_contracts::reims_hosted::Apertures;
|
||||
let apertures = options
|
||||
.hosted_reims_base
|
||||
.and_then(Apertures::at)
|
||||
.unwrap_or_else(|| output::fatal("invalid hosted Reims guest address"));
|
||||
if ram
|
||||
.iter()
|
||||
.filter(|ram| Some(ram.host) != fixed_reims_host)
|
||||
.any(|ram| apertures.overlaps(ram.guest, ram.bytes))
|
||||
{
|
||||
output::fatal("hosted Reims apertures overlap guest RAM");
|
||||
}
|
||||
let vector = options.hosted_reims_irq.map(|requested| {
|
||||
let (layout, inputs) = board.map_or_else(
|
||||
|| (AicLayout::aic2(J473_AIC_EVENT, J473_AIC_TIMESTAMPS), J473_AIC.1),
|
||||
|board| (board.aic.layout, board.aic.inputs),
|
||||
);
|
||||
let occupied = tree.map_or_else(
|
||||
|| alloc::vec![J473_UART.2, J473_WDT.2],
|
||||
|tree| stela_loader::stela_gpu::aic_vectors_in_use(tree)
|
||||
.unwrap_or_else(|error| output::fatal(error)),
|
||||
);
|
||||
let vector = match requested {
|
||||
HostedReimsIrq::Auto => layout
|
||||
.free_vector(inputs, &occupied)
|
||||
.unwrap_or_else(|| output::fatal("hosted Reims has no free AIC vector")),
|
||||
HostedReimsIrq::Vector(vector) => vector,
|
||||
};
|
||||
if occupied.contains(&vector) {
|
||||
output::fatal("hosted Reims AIC vector is already assigned");
|
||||
}
|
||||
vector
|
||||
});
|
||||
(apertures, vector)
|
||||
}
|
||||
|
||||
fn prepare_hosted_reims(
|
||||
handoff: &Handoff,
|
||||
options: &Options,
|
||||
gpus: &[stela_drivers::gpu::Adapter],
|
||||
work: &kernel_work::KernelWork,
|
||||
mmio: Option<&'static crate::native_mmio::Source>,
|
||||
remappers: &'static remapping::Remappers,
|
||||
acpi: Option<&'static aml::HostAcpi>,
|
||||
bsp_apic: u64,
|
||||
) -> Option<stela_drivers::probe::reims_hosted::PciTransport> {
|
||||
use stela_drivers::{gpu::Vendor, probe::reims_hosted};
|
||||
let mut matches = gpus.iter().filter(|adapter| {
|
||||
adapter.vendor == Vendor::Other(reims_hosted::VENDOR)
|
||||
&& adapter.device == reims_hosted::DEVICE
|
||||
});
|
||||
let Some(adapter) = matches.next().filter(|_| matches.next().is_none()) else {
|
||||
output::fatal("expected one hosted Reims PCI device");
|
||||
};
|
||||
let mmio = mmio.unwrap_or_else(|| output::fatal("hosted Reims needs native MMIO"));
|
||||
let address = adapter.address;
|
||||
let heap = handoff.heap.physical..handoff.heap.physical + handoff.heap.bytes;
|
||||
let clock = handoff.tsc_hz;
|
||||
let usb4_approved = options.usb4_approved.clone();
|
||||
let retain = options.hosted_reims_base.is_some();
|
||||
let direct_region = (retain
|
||||
&& handoff.hosted_reims_region.bytes == stela_contracts::reims_hosted::REGION_BYTES)
|
||||
.then_some(handoff.hosted_reims_region.physical);
|
||||
let event_signal = (retain
|
||||
&& options.hosted_reims_irq.is_some()
|
||||
&& options.hosted_reims_irq_mode
|
||||
== Some(stela_boot_core::options::HostedReimsIrqMode::Event))
|
||||
.then(|| {
|
||||
let message = host::gpu_signal(bsp_apic)
|
||||
.unwrap_or_else(|| output::fatal("hosted Reims MSI-X: BSP APIC ID unsupported"));
|
||||
reims_hosted::GpuSignal {
|
||||
message,
|
||||
counter: host::gpu_signals,
|
||||
}
|
||||
});
|
||||
let (transport, [registers, region, doorbells]) = work
|
||||
.call_owned(DEVICES_START_US, move || {
|
||||
let native = services::Services::new(mmio, remappers, acpi, heap, clock, usb4_approved);
|
||||
if let Some(expected_region) = direct_region {
|
||||
let transport = reims_hosted::PciTransport::open_direct_region_with_signal(
|
||||
&native,
|
||||
address,
|
||||
expected_region,
|
||||
event_signal,
|
||||
)?;
|
||||
let bases = transport.bases()?;
|
||||
Ok((Some(transport), bases))
|
||||
} else if retain {
|
||||
let transport =
|
||||
reims_hosted::PciTransport::open_with_signal(&native, address, event_signal)?;
|
||||
let bases = transport.bases()?;
|
||||
Ok((Some(transport), bases))
|
||||
} else {
|
||||
reims_hosted::PciTransport::probe(&native, address).map(|bases| (None, bases))
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|error| output::fatal(format_args!("hosted Reims probe work: {error}")))
|
||||
.unwrap_or_else(|error| output::fatal(error));
|
||||
if let Some(signal) = event_signal {
|
||||
output::arguments(format_args!(
|
||||
"HOST Reims MSI-X enabled vector={:#x} apic={bsp_apic} addr={:#x} data={:#x}
|
||||
",
|
||||
interrupts::GPU_VECTOR,
|
||||
signal.message.address,
|
||||
signal.message.data,
|
||||
));
|
||||
}
|
||||
output::arguments(format_args!(
|
||||
"HOST Reims PCI {address}: wire v2 via BAR0={registers:#x} BAR2={region:#x} BAR4={doorbells:#x}\n"
|
||||
));
|
||||
transport
|
||||
}
|
||||
@@ -2706,7 +2706,10 @@ impl WriterReads {
|
||||
}
|
||||
let depth = device.depth().clamp(1, MAX_FLIGHTS);
|
||||
let mut started = false;
|
||||
while self.flights.len() < depth && device.room() {
|
||||
// Serialize multi-chunk (> 64 KiB) merge reads so one 512 KiB piece
|
||||
// (8 x 64 KiB = 128 bounce pages) never exhausts NVMe's 256-page bounce pool.
|
||||
let max_inflight = depth.min(2);
|
||||
while self.flights.len() < max_inflight && device.room() {
|
||||
let Some((id, offset, bytes)) = reads.take_asked() else {
|
||||
break;
|
||||
};
|
||||
|
||||
@@ -1,203 +1,206 @@
|
||||
//! Plain data the loader phase passes to the engine phase. Addresses are host
|
||||
//! physical; the engine reaches them through its physmap.
|
||||
use crate::console::Framebuffer;
|
||||
use stela_engine::machine::mmu::placement::Placement;
|
||||
use stela_runtime::pc;
|
||||
|
||||
pub const MAGIC: u64 = 0x5354_454c_4153_5953; // "SYSALETS"
|
||||
pub const MAX_GUEST_RANGES: usize = 128;
|
||||
/// A restore bundle's files (13 for a MacBookPro18,3 with its USB-C port
|
||||
/// controllers' firmware) and the install inventory's four, with room.
|
||||
pub const MAX_FILES: usize = 32;
|
||||
pub use stela_boot_core::handoff_records::{File, MAX_NAME, Region, Storage};
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Handoff {
|
||||
pub magic: u64,
|
||||
/// `stela.cfg`.
|
||||
pub options: Region,
|
||||
/// The disk work decided before the firmware exited (`pc::disk_writes`,
|
||||
/// encoded), which the engine's drivers do once: the change Install
|
||||
/// macOS's disk picker planned for the `--storage` partition's disk,
|
||||
/// before that partition is looked up, and then the updates of the
|
||||
/// boot's partitions, before anything reads them. Empty when nothing
|
||||
/// is pending. It lives only in this memory.
|
||||
pub disk_writes: Region,
|
||||
/// Exclusive 256-bit pre-EBS seed, erased by the engine on consumption.
|
||||
/// An empty region means no checked entropy source was available.
|
||||
pub random_seed: Region,
|
||||
/// `source.bin`: the guest image, when no boot bundle is configured.
|
||||
pub source: Region,
|
||||
/// The boot bundle's `bundle.json` and every file it lists.
|
||||
pub files: [File; MAX_FILES],
|
||||
pub file_count: usize,
|
||||
pub heap: Region,
|
||||
/// The heap bytes for compiled code beside the code window: blocks the
|
||||
/// PEs share as they compile and stored forms of blocks the window let
|
||||
/// go (`host_memory::Sizes::kept`).
|
||||
pub kept_code: u64,
|
||||
pub stack: Region,
|
||||
pub code: Region,
|
||||
/// Page-table frames: engine roots and shadow tables.
|
||||
pub pool: Region,
|
||||
/// Where the guest's address space lies beside the window.
|
||||
pub placement: Placement,
|
||||
/// The loader's root, whose window entries every engine root shares.
|
||||
pub root: u64,
|
||||
/// The physical addresses of the bounce slot's two leaf entries.
|
||||
pub bounce: [u64; 2],
|
||||
pub screen: Option<Framebuffer>,
|
||||
/// The loader's finished status lines, which the engine's screen starts
|
||||
/// with (`status::replay`).
|
||||
pub history: [u8; crate::status::HISTORY_BYTES],
|
||||
pub history_bytes: usize,
|
||||
/// The loader's lines that no log stored, after the firmware's log
|
||||
/// closed (`output::unkept_lines`), in the handoff allocation's tail,
|
||||
/// which the engine's record starts with (`output::carry_loader_lines`).
|
||||
pub loader_lines: Region,
|
||||
/// The loader's facts about the PC, as a host record, which the engine
|
||||
/// takes up (`host_inventory::restore`).
|
||||
pub host: [u8; crate::host_inventory::HANDOFF_BYTES],
|
||||
pub host_bytes: usize,
|
||||
/// The partition holding the USB's boot log the loader keeps
|
||||
/// (`log_file`), which the engine writes on to.
|
||||
pub log_partition: Option<[u8; 16]>,
|
||||
/// Where the firmware found the disk Stela started from
|
||||
/// (`pci_io::disk_location`), as text, for the account a failed disk
|
||||
/// search gives.
|
||||
pub boot_disk: [u8; BOOT_DISK_BYTES],
|
||||
pub boot_disk_bytes: usize,
|
||||
/// TSC ticks per second (`firmware::tsc_hz`).
|
||||
pub tsc_hz: u64,
|
||||
/// How `tsc_hz` was found.
|
||||
pub tsc_source: crate::firmware::TscSource,
|
||||
/// The most `tsc_hz` may be off by, in parts per million.
|
||||
pub tsc_tolerance_ppm: u32,
|
||||
/// IA32_APIC_BASE as the firmware left it.
|
||||
pub apic_base: u64,
|
||||
/// Immutable copied UEFI processor identities and per-physical-core raw
|
||||
/// CPUID/control observations; absent unless native cores were requested.
|
||||
pub native_processors: Region,
|
||||
pub native_resources: crate::native_smp::resources::Resources,
|
||||
/// Sealed owned UEFI/ACPI resource inventory and empty MMIO aperture.
|
||||
/// Zero when capture is unavailable; this alone grants no device owner.
|
||||
pub native_mmio: Region,
|
||||
/// The firmware's real-time clock at boot; `None` when the firmware has
|
||||
/// no valid time.
|
||||
pub wall: Option<RtcReading>,
|
||||
/// Free host RAM after boot services, in 2 MiB-aligned ranges.
|
||||
pub guest: [Region; MAX_GUEST_RANGES],
|
||||
pub guest_count: usize,
|
||||
/// The host's RAM in the firmware's memory map, every RAM type
|
||||
/// included: the DRAM the guest Mac reports.
|
||||
pub installed: u64,
|
||||
/// The host storage drivers' ranges, for a bundle built from a disk.
|
||||
pub storage: Storage,
|
||||
/// Host-device firmware, separate from guest boot-bundle files.
|
||||
pub host_firmware: crate::host_firmware::Resources,
|
||||
/// The host's ACPI power hardware, when its FADT is usable.
|
||||
pub power: Option<pc::power::HostPower>,
|
||||
/// The firmware's `ResetSystem` runtime service, whose regions the
|
||||
/// loader keeps mapped by identity; zero without one.
|
||||
pub efi_reset: u64,
|
||||
/// The firmware's ACPI RSDP; zero without one.
|
||||
pub rsdp: u64,
|
||||
/// The firmware's PCI map, with copies of the display functions' option
|
||||
/// ROMs (`pci_io::firmware_map`); empty without one.
|
||||
pub pci_map: Region,
|
||||
/// The `--wifi-key` file's bytes, read from the ESP; empty when
|
||||
/// `--wifi` names no network or the file could not be read. The engine
|
||||
/// parses and wipes them.
|
||||
pub wifi_key: Region,
|
||||
/// Firmware-created task allocation owners; the preceding wire fields keep
|
||||
/// their offsets. The engine can claim each owner once, after mapping checks.
|
||||
pub(crate) native_task_allocations: crate::native_smp::resources::TaskAllocations,
|
||||
/// Original loader table allocations; root is only their copied descriptor.
|
||||
pub(crate) native_loader_tables: crate::paging::loader::LoaderTables,
|
||||
/// Moved original allocation of the relocated static Rust/C engine image.
|
||||
/// Observed PE/header ranges cannot recreate this non-Clone owner.
|
||||
pub(crate) native_image: crate::native_image::ResidentImage,
|
||||
/// Original aperture capture sealed with this boot's successful exit.
|
||||
pub(crate) native_mmio_capture: crate::native_mmio::CaptureHandoff,
|
||||
/// Original remapping inventory qualified at firmware exit.
|
||||
pub(crate) inactive_firmware_units: crate::native_dma::InactiveFirmwareUnits,
|
||||
/// Exclusive firmware RAM below 4 GiB for AMD-Vi device tables.
|
||||
pub(crate) amd_tables: Region,
|
||||
/// Exclusive firmware RAM below 4 GiB for 32-bit device DMA on a
|
||||
/// passthrough domain (`native_memory::reserve_low_dma`).
|
||||
pub(crate) low_dma: Region,
|
||||
/// The saved networks file's bytes (`options::WIFI_SAVED`), read from the
|
||||
/// ESP beside the key; empty without `--wifi` or the file. The engine
|
||||
/// parses and wipes them, as it does the key's.
|
||||
pub(crate) wifi_saved: Region,
|
||||
/// The bytes at `heap`'s end kept for an integrated GPU's pages
|
||||
/// (`host_memory::Sizes::gpu`), zero for a GPU with memory of its own:
|
||||
/// Linux holds at most this many bytes of pages at once.
|
||||
pub(crate) gpu_share: u64,
|
||||
/// The most bytes of pages Linux may hold at once
|
||||
/// (`host_memory::page_bound`): `gpu_share` where it is set, else what
|
||||
/// the heap holds past its own needs. The page catalog's limit, and
|
||||
/// TTM's where no share is set, when `gpu_pages_held`; an integrated GPU
|
||||
/// that draws without a share budgets its Metal device by it either way.
|
||||
pub(crate) gpu_pages: u64,
|
||||
/// The plan holds Linux to `gpu_pages` (`host_memory::held_bound`).
|
||||
pub(crate) gpu_pages_held: bool,
|
||||
/// The display controllers the memory plan saw and the kinds it took
|
||||
/// for them, which the engine's census takes so that both select the
|
||||
/// same GPUs; `None` where no census ran.
|
||||
pub(crate) gpu_census: Option<stela_drivers::gpu::selection::Planned>,
|
||||
/// The PCI functions an earlier boot did not finish starting, or
|
||||
/// skipped since, as the USB's log gives them (`log_file::device_skips`).
|
||||
pub(crate) device_skips: pc::device_starts::Skips,
|
||||
/// The controllers of the disks this boot cannot continue without,
|
||||
/// which it never skips (`selection::disk_controllers`).
|
||||
pub(crate) device_needs: pc::device_starts::Needed,
|
||||
/// The firmware's variable services, whose regions the loader keeps
|
||||
/// mapped by identity as it does `efi_reset`'s, and this boot's number
|
||||
/// in the USB's log: what a stop the log cannot keep leaves its record
|
||||
/// with (`stop_record`).
|
||||
pub(crate) stop_record: crate::stop_record::Services,
|
||||
/// The firmware's runtime regions and how the loader's root reaches
|
||||
/// each, for the line of a fault inside a firmware call.
|
||||
pub(crate) runtime_regions: stela_boot_core::firmware_runtime::Regions,
|
||||
/// Whether the loader found a UART at COM1 (`serial::present`). The
|
||||
/// engine runs a copy of this image taken before any Rust state
|
||||
/// existed, so it learns the result here, not from its own statics.
|
||||
pub(crate) serial_present: bool,
|
||||
/// The earlier boot's Intel GuC record, as the loader read it from the
|
||||
/// USB's log (`log_file::earlier_guc`), for the same reason: dev64-1's
|
||||
/// engine read its own copy of that static, never set, and started the
|
||||
/// GuC again after a boot whose GuC failed.
|
||||
pub(crate) intel_guc_earlier: Option<stela_boot_core::intel_guc::Record>,
|
||||
}
|
||||
|
||||
/// A read of the firmware's real-time clock: its time as UTC and its
|
||||
/// resolution in counts per second, read between TSC values `tsc_before`
|
||||
/// and `tsc_after`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RtcReading {
|
||||
pub utc: stela_boot_core::firmware_time::Timestamp,
|
||||
pub resolution: u32,
|
||||
pub tsc_before: u64,
|
||||
pub tsc_after: u64,
|
||||
}
|
||||
|
||||
impl RtcReading {
|
||||
/// The Unix seconds at TSC `tsc`, carried forward at `tsc_hz`.
|
||||
pub fn unix_seconds_at(&self, tsc: u64, tsc_hz: u64) -> u64 {
|
||||
self.utc.seconds + tsc.saturating_sub(self.tsc_after) / tsc_hz
|
||||
}
|
||||
}
|
||||
|
||||
/// The most [`Handoff::boot_disk`] holds.
|
||||
pub const BOOT_DISK_BYTES: usize = 128;
|
||||
|
||||
impl Handoff {
|
||||
/// [`Self::boot_disk`] as text, when the loader found it.
|
||||
pub fn boot_disk(&self) -> Option<&str> {
|
||||
let bytes = self.boot_disk.get(..self.boot_disk_bytes)?;
|
||||
core::str::from_utf8(bytes)
|
||||
.ok()
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
}
|
||||
//! Plain data the loader phase passes to the engine phase. Addresses are host
|
||||
//! physical; the engine reaches them through its physmap.
|
||||
use crate::console::Framebuffer;
|
||||
use stela_engine::machine::mmu::placement::Placement;
|
||||
use stela_runtime::pc;
|
||||
|
||||
pub const MAGIC: u64 = 0x5354_454c_4153_5953; // "SYSALETS"
|
||||
pub const MAX_GUEST_RANGES: usize = 128;
|
||||
/// A restore bundle's files (13 for a MacBookPro18,3 with its USB-C port
|
||||
/// controllers' firmware) and the install inventory's four, with room.
|
||||
pub const MAX_FILES: usize = 32;
|
||||
pub use stela_boot_core::handoff_records::{File, MAX_NAME, Region, Storage};
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Handoff {
|
||||
pub magic: u64,
|
||||
/// `stela.cfg`.
|
||||
pub options: Region,
|
||||
/// The disk work decided before the firmware exited (`pc::disk_writes`,
|
||||
/// encoded), which the engine's drivers do once: the change Install
|
||||
/// macOS's disk picker planned for the `--storage` partition's disk,
|
||||
/// before that partition is looked up, and then the updates of the
|
||||
/// boot's partitions, before anything reads them. Empty when nothing
|
||||
/// is pending. It lives only in this memory.
|
||||
pub disk_writes: Region,
|
||||
/// Exclusive 256-bit pre-EBS seed, erased by the engine on consumption.
|
||||
/// An empty region means no checked entropy source was available.
|
||||
pub random_seed: Region,
|
||||
/// `source.bin`: the guest image, when no boot bundle is configured.
|
||||
pub source: Region,
|
||||
/// The boot bundle's `bundle.json` and every file it lists.
|
||||
pub files: [File; MAX_FILES],
|
||||
pub file_count: usize,
|
||||
pub heap: Region,
|
||||
/// The heap bytes for compiled code beside the code window: blocks the
|
||||
/// PEs share as they compile and stored forms of blocks the window let
|
||||
/// go (`host_memory::Sizes::kept`).
|
||||
pub kept_code: u64,
|
||||
pub stack: Region,
|
||||
pub code: Region,
|
||||
/// Page-table frames: engine roots and shadow tables.
|
||||
pub pool: Region,
|
||||
/// Where the guest's address space lies beside the window.
|
||||
pub placement: Placement,
|
||||
/// The loader's root, whose window entries every engine root shares.
|
||||
pub root: u64,
|
||||
/// The physical addresses of the bounce slot's two leaf entries.
|
||||
pub bounce: [u64; 2],
|
||||
pub screen: Option<Framebuffer>,
|
||||
/// The loader's finished status lines, which the engine's screen starts
|
||||
/// with (`status::replay`).
|
||||
pub history: [u8; crate::status::HISTORY_BYTES],
|
||||
pub history_bytes: usize,
|
||||
/// The loader's lines that no log stored, after the firmware's log
|
||||
/// closed (`output::unkept_lines`), in the handoff allocation's tail,
|
||||
/// which the engine's record starts with (`output::carry_loader_lines`).
|
||||
pub loader_lines: Region,
|
||||
/// The loader's facts about the PC, as a host record, which the engine
|
||||
/// takes up (`host_inventory::restore`).
|
||||
pub host: [u8; crate::host_inventory::HANDOFF_BYTES],
|
||||
pub host_bytes: usize,
|
||||
/// The partition holding the USB's boot log the loader keeps
|
||||
/// (`log_file`), which the engine writes on to.
|
||||
pub log_partition: Option<[u8; 16]>,
|
||||
/// Where the firmware found the disk Stela started from
|
||||
/// (`pci_io::disk_location`), as text, for the account a failed disk
|
||||
/// search gives.
|
||||
pub boot_disk: [u8; BOOT_DISK_BYTES],
|
||||
pub boot_disk_bytes: usize,
|
||||
/// TSC ticks per second (`firmware::tsc_hz`).
|
||||
pub tsc_hz: u64,
|
||||
/// How `tsc_hz` was found.
|
||||
pub tsc_source: crate::firmware::TscSource,
|
||||
/// The most `tsc_hz` may be off by, in parts per million.
|
||||
pub tsc_tolerance_ppm: u32,
|
||||
/// IA32_APIC_BASE as the firmware left it.
|
||||
pub apic_base: u64,
|
||||
/// Immutable copied UEFI processor identities and per-physical-core raw
|
||||
/// CPUID/control observations; absent unless native cores were requested.
|
||||
pub native_processors: Region,
|
||||
pub native_resources: crate::native_smp::resources::Resources,
|
||||
/// Sealed owned UEFI/ACPI resource inventory and empty MMIO aperture.
|
||||
/// Zero when capture is unavailable; this alone grants no device owner.
|
||||
pub native_mmio: Region,
|
||||
/// The firmware's real-time clock at boot; `None` when the firmware has
|
||||
/// no valid time.
|
||||
pub wall: Option<RtcReading>,
|
||||
/// Free host RAM after boot services, in 2 MiB-aligned ranges.
|
||||
pub guest: [Region; MAX_GUEST_RANGES],
|
||||
pub guest_count: usize,
|
||||
/// The host's RAM in the firmware's memory map, every RAM type
|
||||
/// included: the DRAM the guest Mac reports.
|
||||
pub installed: u64,
|
||||
/// The host storage drivers' ranges, for a bundle built from a disk.
|
||||
pub storage: Storage,
|
||||
/// Host-device firmware, separate from guest boot-bundle files.
|
||||
pub host_firmware: crate::host_firmware::Resources,
|
||||
/// The host's ACPI power hardware, when its FADT is usable.
|
||||
pub power: Option<pc::power::HostPower>,
|
||||
/// The firmware's `ResetSystem` runtime service, whose regions the
|
||||
/// loader keeps mapped by identity; zero without one.
|
||||
pub efi_reset: u64,
|
||||
/// The firmware's ACPI RSDP; zero without one.
|
||||
pub rsdp: u64,
|
||||
/// The firmware's PCI map, with copies of the display functions' option
|
||||
/// ROMs (`pci_io::firmware_map`); empty without one.
|
||||
pub pci_map: Region,
|
||||
/// The `--wifi-key` file's bytes, read from the ESP; empty when
|
||||
/// `--wifi` names no network or the file could not be read. The engine
|
||||
/// parses and wipes them.
|
||||
pub wifi_key: Region,
|
||||
/// Firmware-created task allocation owners; the preceding wire fields keep
|
||||
/// their offsets. The engine can claim each owner once, after mapping checks.
|
||||
pub(crate) native_task_allocations: crate::native_smp::resources::TaskAllocations,
|
||||
/// Original loader table allocations; root is only their copied descriptor.
|
||||
pub(crate) native_loader_tables: crate::paging::loader::LoaderTables,
|
||||
/// Moved original allocation of the relocated static Rust/C engine image.
|
||||
/// Observed PE/header ranges cannot recreate this non-Clone owner.
|
||||
pub(crate) native_image: crate::native_image::ResidentImage,
|
||||
/// Original aperture capture sealed with this boot's successful exit.
|
||||
pub(crate) native_mmio_capture: crate::native_mmio::CaptureHandoff,
|
||||
/// Original remapping inventory qualified at firmware exit.
|
||||
pub(crate) inactive_firmware_units: crate::native_dma::InactiveFirmwareUnits,
|
||||
/// Exclusive firmware RAM below 4 GiB for AMD-Vi device tables.
|
||||
pub(crate) amd_tables: Region,
|
||||
/// Exclusive firmware RAM below 4 GiB for 32-bit device DMA on a
|
||||
/// passthrough domain (`native_memory::reserve_low_dma`).
|
||||
pub(crate) low_dma: Region,
|
||||
/// The saved networks file's bytes (`options::WIFI_SAVED`), read from the
|
||||
/// ESP beside the key; empty without `--wifi` or the file. The engine
|
||||
/// parses and wipes them, as it does the key's.
|
||||
pub(crate) wifi_saved: Region,
|
||||
/// The bytes at `heap`'s end kept for an integrated GPU's pages
|
||||
/// (`host_memory::Sizes::gpu`), zero for a GPU with memory of its own:
|
||||
/// Linux holds at most this many bytes of pages at once.
|
||||
pub(crate) gpu_share: u64,
|
||||
/// The most bytes of pages Linux may hold at once
|
||||
/// (`host_memory::page_bound`): `gpu_share` where it is set, else what
|
||||
/// the heap holds past its own needs. The page catalog's limit, and
|
||||
/// TTM's where no share is set, when `gpu_pages_held`; an integrated GPU
|
||||
/// that draws without a share budgets its Metal device by it either way.
|
||||
pub(crate) gpu_pages: u64,
|
||||
/// The plan holds Linux to `gpu_pages` (`host_memory::held_bound`).
|
||||
pub(crate) gpu_pages_held: bool,
|
||||
/// The display controllers the memory plan saw and the kinds it took
|
||||
/// for them, which the engine's census takes so that both select the
|
||||
/// same GPUs; `None` where no census ran.
|
||||
pub(crate) gpu_census: Option<stela_drivers::gpu::selection::Planned>,
|
||||
/// The PCI functions an earlier boot did not finish starting, or
|
||||
/// skipped since, as the USB's log gives them (`log_file::device_skips`).
|
||||
pub(crate) device_skips: pc::device_starts::Skips,
|
||||
/// The controllers of the disks this boot cannot continue without,
|
||||
/// which it never skips (`selection::disk_controllers`).
|
||||
pub(crate) device_needs: pc::device_starts::Needed,
|
||||
/// The firmware's variable services, whose regions the loader keeps
|
||||
/// mapped by identity as it does `efi_reset`'s, and this boot's number
|
||||
/// in the USB's log: what a stop the log cannot keep leaves its record
|
||||
/// with (`stop_record`).
|
||||
pub(crate) stop_record: crate::stop_record::Services,
|
||||
/// The firmware's runtime regions and how the loader's root reaches
|
||||
/// each, for the line of a fault inside a firmware call.
|
||||
pub(crate) runtime_regions: stela_boot_core::firmware_runtime::Regions,
|
||||
/// Whether the loader found a UART at COM1 (`serial::present`). The
|
||||
/// engine runs a copy of this image taken before any Rust state
|
||||
/// existed, so it learns the result here, not from its own statics.
|
||||
pub(crate) serial_present: bool,
|
||||
/// The earlier boot's Intel GuC record, as the loader read it from the
|
||||
/// USB's log (`log_file::earlier_guc`), for the same reason: dev64-1's
|
||||
/// engine read its own copy of that static, never set, and started the
|
||||
/// GuC again after a boot whose GuC failed.
|
||||
pub(crate) intel_guc_earlier: Option<stela_boot_core::intel_guc::Record>,
|
||||
/// Direct-mapped BAR2 (command and allocation region) of the hosted Reims
|
||||
/// PCI device when `--hosted-reims-base` is configured. Empty when absent.
|
||||
pub(crate) hosted_reims_region: Region,
|
||||
}
|
||||
|
||||
/// A read of the firmware's real-time clock: its time as UTC and its
|
||||
/// resolution in counts per second, read between TSC values `tsc_before`
|
||||
/// and `tsc_after`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RtcReading {
|
||||
pub utc: stela_boot_core::firmware_time::Timestamp,
|
||||
pub resolution: u32,
|
||||
pub tsc_before: u64,
|
||||
pub tsc_after: u64,
|
||||
}
|
||||
|
||||
impl RtcReading {
|
||||
/// The Unix seconds at TSC `tsc`, carried forward at `tsc_hz`.
|
||||
pub fn unix_seconds_at(&self, tsc: u64, tsc_hz: u64) -> u64 {
|
||||
self.utc.seconds + tsc.saturating_sub(self.tsc_after) / tsc_hz
|
||||
}
|
||||
}
|
||||
|
||||
/// The most [`Handoff::boot_disk`] holds.
|
||||
pub const BOOT_DISK_BYTES: usize = 128;
|
||||
|
||||
impl Handoff {
|
||||
/// [`Self::boot_disk`] as text, when the loader found it.
|
||||
pub fn boot_disk(&self) -> Option<&str> {
|
||||
let bytes = self.boot_disk.get(..self.boot_disk_bytes)?;
|
||||
core::str::from_utf8(bytes)
|
||||
.ok()
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
}
|
||||
@@ -406,6 +406,15 @@ pub(crate) unsafe fn qualify_reserved_writeback(
|
||||
cache::verify_writeback(cpu, physical, bytes, SOURCE.table_offset())
|
||||
}
|
||||
|
||||
/// Ensure a naturally aligned host range (such as hosted Reims BAR2) has a
|
||||
/// Write-Back variable MTRR on the BSP before platform/AP capture.
|
||||
///
|
||||
/// # Safety
|
||||
/// CPL0 on BSP with interrupts disabled and all APs parked.
|
||||
pub(crate) unsafe fn ensure_writeback_mtrr(physical: u64, bytes: u64) -> Result<(), MemoryError> {
|
||||
unsafe { cache::ensure_writeback_mtrr(physical, bytes) }
|
||||
}
|
||||
|
||||
/// Exercise the registered mapping and allocator through the Linux page
|
||||
/// catalog and the page source. Called by the mount's host check.
|
||||
pub fn verify() -> Result<(), MemoryError> {
|
||||
|
||||
@@ -70,7 +70,13 @@ pub(crate) fn verify_writeback(
|
||||
// table pages; every index is within its 4 KiB page.
|
||||
Some(unsafe { (address as *const u64).read_volatile() })
|
||||
},
|
||||
)?;
|
||||
)
|
||||
.map_err(|err| {
|
||||
crate::output::arguments(format_args!(
|
||||
"NATIVE RAM verify_mappings failed cpu={cpu:#x} pa={start:#x} bytes={bytes:#x} err={err:?}\n"
|
||||
));
|
||||
err
|
||||
})?;
|
||||
let count = msr(MTRR_CAP) as u8;
|
||||
let variables = (0..count).filter_map(|index| {
|
||||
let base = msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
@@ -96,6 +102,175 @@ pub(crate) fn verify_writeback(
|
||||
physical_bits,
|
||||
}
|
||||
.writeback(start, bytes, variables)
|
||||
.map_err(|err| {
|
||||
crate::output::arguments(format_args!(
|
||||
"NATIVE RAM MTRR writeback failed pa={start:#x} bytes={bytes:#x} default={default:#x} count={count} err={err:?}\n"
|
||||
));
|
||||
err
|
||||
})
|
||||
}
|
||||
|
||||
/// Ensure a naturally aligned power-of-two range (such as a host RAM-backed
|
||||
/// PCI BAR2 region) is covered as Write-Back in the BSP's variable MTRRs.
|
||||
///
|
||||
/// # Safety
|
||||
/// Must be called on the BSP at CPL0 with interrupts disabled and all APs
|
||||
/// parked, before `root_identity` capture and AP startup so that `executor::start`
|
||||
/// replicates the updated MTRR image to every AP.
|
||||
pub(crate) unsafe fn ensure_writeback_mtrr(start: u64, bytes: u64) -> Result<(), MemoryError> {
|
||||
use crate::cpu::msr::{MTRR_CAP, MTRR_DEFAULT, MTRR_PHYS_BASE, Msr};
|
||||
use core::arch::{asm, x86_64::__cpuid};
|
||||
const VALID: u64 = 1 << 11;
|
||||
const MTRR_ENABLE: u64 = 1 << 11;
|
||||
const WRITE_BACK: u64 = 6;
|
||||
if bytes == 0 || !bytes.is_power_of_two() || !start.is_multiple_of(bytes) || start < (1 << 20) {
|
||||
return Err(MemoryError::InvalidSize);
|
||||
}
|
||||
let vendor = __cpuid(0);
|
||||
if [vendor.ebx, vendor.edx, vendor.ecx] != [0x756e_6547, 0x4965_6e69, 0x6c65_746e] {
|
||||
return Ok(());
|
||||
}
|
||||
let features = __cpuid(1).edx;
|
||||
if features & (1 << 12) == 0 {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let maximum = __cpuid(0x8000_0000).eax;
|
||||
let physical_bits = if maximum >= 0x8000_0008 {
|
||||
__cpuid(0x8000_0008).eax as u8
|
||||
} else {
|
||||
36
|
||||
};
|
||||
if !(32..=52).contains(&physical_bits) {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let end = start.checked_add(bytes).ok_or(MemoryError::InvalidSize)?;
|
||||
if end > 1u64 << physical_bits {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let address_mask = ((1u64 << physical_bits) - 1) & !4095;
|
||||
let read_msr = |register: Msr| unsafe { register.read() };
|
||||
let default = read_msr(MTRR_DEFAULT);
|
||||
let count = read_msr(MTRR_CAP) as u8;
|
||||
let cr0: u64;
|
||||
unsafe { asm!("mov {}, cr0", out(reg) cr0, options(nomem, nostack, preserves_flags)) };
|
||||
let variables = (0..count).filter_map(|index| {
|
||||
let base = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
let mask = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index) + 1));
|
||||
if mask & VALID == 0 {
|
||||
return None;
|
||||
}
|
||||
let size = ((!mask) & address_mask) + 4096;
|
||||
let base_addr = base & address_mask;
|
||||
Some(if size.is_power_of_two() && base_addr.is_multiple_of(size) {
|
||||
Ok(Variable {
|
||||
range: base_addr..base_addr + size,
|
||||
kind: base as u8,
|
||||
})
|
||||
} else {
|
||||
Err(MemoryError::CacheAttributeUnavailable)
|
||||
})
|
||||
});
|
||||
let policy = Policy {
|
||||
enabled: default & MTRR_ENABLE != 0,
|
||||
caches_enabled: cr0 & (1 << 30 | 1 << 29) == 0,
|
||||
default_kind: default as u8,
|
||||
physical_bits,
|
||||
};
|
||||
if let Ok(len) = usize::try_from(bytes)
|
||||
&& policy.writeback(start, len, variables.clone()).is_ok()
|
||||
{
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR already WB pa={start:#x} bytes={bytes:#x} default={default:#x}\n"
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
if default & MTRR_ENABLE == 0 {
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
let mut free_slots = alloc::vec::Vec::new();
|
||||
let mut conflict = None;
|
||||
for index in 0..count {
|
||||
let base = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index)));
|
||||
let mask = read_msr(MTRR_PHYS_BASE.at(2 * u32::from(index) + 1));
|
||||
if mask & VALID == 0 {
|
||||
free_slots.push(index);
|
||||
continue;
|
||||
}
|
||||
let size = ((!mask) & address_mask) + 4096;
|
||||
let base_addr = base & address_mask;
|
||||
let kind = base as u8;
|
||||
if size.is_power_of_two() && base_addr.is_multiple_of(size) {
|
||||
let v_end = base_addr.saturating_add(size);
|
||||
if base_addr < end && start < v_end && kind != WRITE_BACK as u8 {
|
||||
if conflict.is_some() || kind != 0 || base_addr > start || v_end < end {
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR uncarvable conflict slot={index} range={base_addr:#x}..{v_end:#x} kind={kind}\n"
|
||||
));
|
||||
return Err(MemoryError::CacheAttributeUnavailable);
|
||||
}
|
||||
conflict = Some((index, base_addr, v_end, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut updates: alloc::vec::Vec<(u8, u64, u64)> = alloc::vec::Vec::new();
|
||||
if let Some((slot, v_start, v_end, kind)) = conflict {
|
||||
// Split [v_start, start) and [end, v_end) into aligned power-of-two UC MTRRs
|
||||
// so [start, end) is carved cleanly out of the 64-bit PCI UC aperture.
|
||||
let mut pieces: alloc::vec::Vec<(u64, u64)> = alloc::vec::Vec::new();
|
||||
for (mut cur, limit) in [(v_start, start), (end, v_end)] {
|
||||
while cur < limit {
|
||||
let remaining = limit - cur;
|
||||
let align_size = 1u64 << cur.trailing_zeros().min(62);
|
||||
let max_pow2 = 1u64 << (63 - remaining.leading_zeros());
|
||||
let chunk = align_size.min(max_pow2);
|
||||
pieces.push((cur, chunk));
|
||||
cur += chunk;
|
||||
}
|
||||
}
|
||||
let mut avail = alloc::vec::Vec::with_capacity(1 + free_slots.len());
|
||||
avail.push(slot);
|
||||
avail.extend_from_slice(&free_slots);
|
||||
if pieces.len() <= avail.len() {
|
||||
for (s, (p_start, p_len)) in avail.iter().copied().zip(pieces.iter().copied()) {
|
||||
let b = (p_start & address_mask) | u64::from(kind);
|
||||
let m = ((!(p_len - 1)) & address_mask) | VALID;
|
||||
updates.push((s, b, m));
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
updates.push((slot, 0, 0));
|
||||
}
|
||||
free_slots = avail[pieces.len().max(1)..].to_vec();
|
||||
} else {
|
||||
// Fewer free variable MTRRs than carved chunks; clear the broad 64-bit UC window
|
||||
// (all native MMIO mappings explicitly enforce UC via PAT).
|
||||
updates.push((slot, 0, 0));
|
||||
}
|
||||
}
|
||||
if (default as u8) != WRITE_BACK as u8 {
|
||||
let slot = free_slots
|
||||
.first()
|
||||
.copied()
|
||||
.ok_or(MemoryError::CacheAttributeUnavailable)?;
|
||||
let base_val = (start & address_mask) | WRITE_BACK;
|
||||
let mask_val = ((!(bytes - 1)) & address_mask) | VALID;
|
||||
updates.push((slot, base_val, mask_val));
|
||||
}
|
||||
// SAFETY: Intel SDM Vol. 3A 11.11.8 MTRR update on BSP with IF=0 and APs parked.
|
||||
unsafe {
|
||||
MTRR_DEFAULT.write(default & !MTRR_ENABLE);
|
||||
asm!("wbinvd", options(nostack, preserves_flags));
|
||||
for &(slot, base_val, mask_val) in &updates {
|
||||
MTRR_PHYS_BASE.at(2 * u32::from(slot)).write(base_val);
|
||||
MTRR_PHYS_BASE.at(2 * u32::from(slot) + 1).write(mask_val);
|
||||
}
|
||||
asm!("wbinvd", options(nostack, preserves_flags));
|
||||
MTRR_DEFAULT.write(default);
|
||||
}
|
||||
crate::output::arguments(format_args!(
|
||||
"HOST Reims MTRR carved WB pa={start:#x} bytes={bytes:#x} default={default:#x} updates={}\n",
|
||||
updates.len()
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// AMD's effective DRAM routing is additional to the common PAT/MTRR fields.
|
||||
|
||||
@@ -26,6 +26,7 @@ const HUGE: u64 = 1 << 7;
|
||||
const NX: u64 = 1 << 63;
|
||||
const APERTURE_OFFSET: u64 = 0x5_0000_0000;
|
||||
const ENTRIES: usize = 512;
|
||||
const DIRECTORY_BYTES: u64 = PAGE << 18;
|
||||
|
||||
fn failed<T>(_: T) -> Error {
|
||||
Error::Unavailable
|
||||
|
||||
@@ -23,6 +23,8 @@ const MAX_MEMORY: usize = firmware_map::INVENTORY_ENTRIES;
|
||||
const TABLE_BYTES: usize = 65536;
|
||||
/// Leaf tables in the aperture: 4 KiB mappings for 32 MiB.
|
||||
pub(super) const LEAVES: usize = 16;
|
||||
/// Two directories let a full 1 GiB BAR coexist with the 4 KiB window.
|
||||
pub(super) const DIRECTORIES: usize = 2;
|
||||
|
||||
pub(super) type Memory = firmware_map::Entry;
|
||||
/// All fields are initialized by the loader. Kept in reserved
|
||||
@@ -33,9 +35,9 @@ pub(crate) struct Wire {
|
||||
pub(super) root: u64,
|
||||
/// The aperture's first leaf table, which the scoped diagnostics use.
|
||||
pub(super) leaf: u64,
|
||||
/// The aperture's page directory: its first `LEAVES` entries hold the
|
||||
/// leaf tables, the rest map 2 MiB pages.
|
||||
pub(super) directory: u64,
|
||||
/// The aperture's consecutive page directories. The first LEAVES entries
|
||||
/// hold the leaf tables. The other entries map 2 MiB pages.
|
||||
pub(super) directories: [u64; DIRECTORIES],
|
||||
pub(super) leaves: [u64; LEAVES],
|
||||
pub(super) virtual_base: u64,
|
||||
pub(super) cores: u32,
|
||||
@@ -361,19 +363,26 @@ impl Prepared {
|
||||
}
|
||||
*slot = leaf as u64;
|
||||
}
|
||||
let first = crate::tables::entry(frames, root, base, 1, false)?
|
||||
.ok_or(refuse!("MMIO aperture directory missing"))?;
|
||||
let directory = first as u64 & ADDRESS;
|
||||
if first as u64 != directory {
|
||||
return Err(refuse!("MMIO aperture is not directory aligned"));
|
||||
for (index, slot) in wire.directories.iter_mut().enumerate() {
|
||||
let address = base + index as u64 * DIRECTORY_BYTES;
|
||||
let first = crate::tables::entry(frames, root, address, 1, true)?
|
||||
.ok_or(refuse!("MMIO aperture directory missing"))?;
|
||||
let directory = first as u64 & ADDRESS;
|
||||
if first as u64 != directory {
|
||||
return Err(refuse!("MMIO aperture is not directory aligned"));
|
||||
}
|
||||
let used = if index == 0 { LEAVES } else { 0 };
|
||||
// SAFETY: this directory belongs to the loader's page-table builder.
|
||||
if (used..ENTRIES).any(|i| unsafe { first.add(i).read_volatile() } != 0) {
|
||||
return Err(refuse!("MMIO aperture overlaps an existing mapping"));
|
||||
}
|
||||
*slot = directory;
|
||||
}
|
||||
// SAFETY: the directory the builder walked for `base`.
|
||||
if (LEAVES..ENTRIES).any(|i| unsafe { first.add(i).read_volatile() } != 0) {
|
||||
return Err(refuse!("MMIO aperture overlaps an existing mapping"));
|
||||
if wire.directories[0] == wire.directories[1] {
|
||||
return Err(refuse!("MMIO aperture directories alias each other"));
|
||||
}
|
||||
wire.root = root;
|
||||
wire.leaf = wire.leaves[0];
|
||||
wire.directory = directory;
|
||||
wire.virtual_base = base;
|
||||
wire.cores = u32::try_from(cores).map_err(|_| refuse!("MMIO core count overflow"))?;
|
||||
wire.levels = crate::layout::top_level() + 1;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
use super::*;
|
||||
use super::{
|
||||
aliases::{aliases, owned_table},
|
||||
capture::LEAVES,
|
||||
capture::{DIRECTORIES, LEAVES},
|
||||
};
|
||||
use crate::{
|
||||
engine::host::{HostOwner, MmioRoots, RootIdentity},
|
||||
@@ -158,7 +158,7 @@ impl Size {
|
||||
fn slots(self) -> core::ops::Range<usize> {
|
||||
match self {
|
||||
Size::Page => 0..LEAVES * ENTRIES,
|
||||
Size::Large => LEAVES..ENTRIES,
|
||||
Size::Large => LEAVES..DIRECTORIES * ENTRIES,
|
||||
}
|
||||
}
|
||||
/// The size a request maps with: 2 MiB pages when it is 2 MiB aligned at
|
||||
@@ -229,7 +229,9 @@ impl Platform {
|
||||
Size::Page => {
|
||||
owned_table(wire, wire.leaves[index / ENTRIES])?.wrapping_add(index % ENTRIES)
|
||||
}
|
||||
Size::Large => owned_table(wire, wire.directory)?.wrapping_add(index),
|
||||
Size::Large => {
|
||||
owned_table(wire, wire.directories[index / ENTRIES])?.wrapping_add(index % ENTRIES)
|
||||
}
|
||||
})
|
||||
}
|
||||
fn address(&self, size: Size, index: usize) -> u64 {
|
||||
@@ -564,10 +566,10 @@ impl Source {
|
||||
});
|
||||
let mut written = Vec::new();
|
||||
written
|
||||
.try_reserve_exact(LEAVES + 1)
|
||||
.try_reserve_exact(LEAVES + DIRECTORIES)
|
||||
.map_err(refused("MMIO aperture: room for the aperture's table list"))?;
|
||||
written.extend_from_slice(&wire.leaves);
|
||||
written.push(wire.directory);
|
||||
written.extend_from_slice(&wire.directories);
|
||||
for &table in &written {
|
||||
crate::native_memory::cache::verify_writeback(
|
||||
crate::layout::physical(table),
|
||||
@@ -587,32 +589,34 @@ impl Source {
|
||||
platform.check_context(space).map_err(named(
|
||||
"the boot processor's root does not share the aperture",
|
||||
))?;
|
||||
for root in catalog.roots() {
|
||||
let mut table = *root;
|
||||
for level in (2..wire.levels).rev() {
|
||||
let slot = ((wire.virtual_base >> (12 + 9 * level)) & 511) as usize;
|
||||
// SAFETY: an owned table page.
|
||||
let entry = unsafe {
|
||||
owned_table(wire, table)
|
||||
.map_err(named("a root's aperture path leaves the capture's tables"))?
|
||||
.add(slot)
|
||||
.read_volatile()
|
||||
};
|
||||
if entry & (PRESENT | HUGE) != PRESENT {
|
||||
for (index, &directory) in wire.directories.iter().enumerate() {
|
||||
let base = wire.virtual_base + index as u64 * DIRECTORY_BYTES;
|
||||
for root in catalog.roots() {
|
||||
let mut table = *root;
|
||||
for level in (2..wire.levels).rev() {
|
||||
let slot = ((base >> (12 + 9 * level)) & 511) as usize;
|
||||
// SAFETY: an owned table page.
|
||||
let entry = unsafe {
|
||||
owned_table(wire, table)
|
||||
.map_err(named("a root's aperture path leaves the capture's tables"))?
|
||||
.add(slot)
|
||||
.read_volatile()
|
||||
};
|
||||
if entry & (PRESENT | HUGE) != PRESENT {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} has entry {entry:#x} at level {level} of the aperture's path"
|
||||
)));
|
||||
}
|
||||
table = entry & ADDRESS;
|
||||
}
|
||||
if table != directory {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} has entry {entry:#x} at level {level} of the aperture's path"
|
||||
"root {root:#x} reaches {table:#x}, not the aperture's directory {directory:#x}"
|
||||
)));
|
||||
}
|
||||
table = entry & ADDRESS;
|
||||
}
|
||||
if table != wire.directory {
|
||||
return Err(refuse(&alloc::format!(
|
||||
"root {root:#x} reaches {table:#x}, not the aperture's directory {:#x}",
|
||||
wire.directory
|
||||
)));
|
||||
}
|
||||
}
|
||||
let directory = owned_table(wire, wire.directory).map_err(named(
|
||||
let directory = owned_table(wire, wire.directories[0]).map_err(named(
|
||||
"the aperture's directory is not a table page the capture owns",
|
||||
))?;
|
||||
for (index, &leaf) in wire.leaves.iter().enumerate() {
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
//! [`Processors::plan`]: stela_boot_core::aperture::Processors::plan
|
||||
use super::PROCESSORS;
|
||||
use crate::engine::interrupts::{
|
||||
NATIVE_WAKE_VECTOR, NETWORK_VECTOR, SHOOTDOWN_VECTOR, SIGNAL_VECTOR, TIMER_VECTOR,
|
||||
GPU_VECTOR, NATIVE_WAKE_VECTOR, NETWORK_VECTOR, SHOOTDOWN_VECTOR, SIGNAL_VECTOR, TIMER_VECTOR,
|
||||
};
|
||||
use core::{
|
||||
arch::{asm, x86_64::__cpuid_count},
|
||||
@@ -71,6 +71,7 @@ const _: () = assert!(
|
||||
(TIMER_VECTOR >> 4) as u64 <= JOB_PRIORITY
|
||||
&& (SIGNAL_VECTOR >> 4) as u64 <= JOB_PRIORITY
|
||||
&& (NETWORK_VECTOR >> 4) as u64 <= JOB_PRIORITY
|
||||
&& (GPU_VECTOR >> 4) as u64 <= JOB_PRIORITY
|
||||
&& 0x5f >> 4 <= JOB_PRIORITY
|
||||
);
|
||||
|
||||
|
||||
@@ -142,17 +142,19 @@ unsafe fn reserve_with_limit(
|
||||
.host
|
||||
.checked_add(range.bytes)
|
||||
.ok_or(refuse!("canonical guest RAM extent wraps"))?;
|
||||
if range.bytes == 0
|
||||
|| !handoff.guest[..handoff.guest_count]
|
||||
.iter()
|
||||
.any(|reservation| {
|
||||
reservation.physical <= range.host
|
||||
&& reservation
|
||||
.physical
|
||||
.checked_add(reservation.bytes)
|
||||
.is_some_and(|top| end <= top)
|
||||
})
|
||||
{
|
||||
let in_guest = handoff.guest[..handoff.guest_count]
|
||||
.iter()
|
||||
.any(|reservation| {
|
||||
reservation.physical <= range.host
|
||||
&& reservation
|
||||
.physical
|
||||
.checked_add(reservation.bytes)
|
||||
.is_some_and(|top| end <= top)
|
||||
});
|
||||
let is_reims_region = handoff.hosted_reims_region.bytes != 0
|
||||
&& range.host == handoff.hosted_reims_region.physical
|
||||
&& range.bytes == handoff.hosted_reims_region.bytes;
|
||||
if range.bytes == 0 || !(in_guest || is_reims_region) {
|
||||
return Err(refuse!(
|
||||
"canonical guest RAM is outside actual loader ownership"
|
||||
));
|
||||
|
||||
@@ -21,6 +21,7 @@ pub(super) struct EngineImage {
|
||||
pub ram: Vec<(usize, usize)>,
|
||||
pub screen: Option<Framebuffer>,
|
||||
pub apic: u64,
|
||||
pub hosted_reims_region: Region,
|
||||
pub placement: Placement,
|
||||
}
|
||||
|
||||
@@ -58,7 +59,10 @@ pub(super) struct EngineMemory {
|
||||
}
|
||||
|
||||
/// Copy and relocate the pristine image into the selected host window.
|
||||
pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
pub(super) fn prepare_image(
|
||||
snapshot: &Snapshot,
|
||||
hosted_reims_region: Region,
|
||||
) -> Result<EngineImage> {
|
||||
let image = firmware::Image::loaded()?;
|
||||
if image.start != snapshot.start || image.end - image.start != snapshot.bytes {
|
||||
return Err(refuse!("image layout changed after the snapshot"));
|
||||
@@ -66,7 +70,26 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
let ram = firmware::ram()?;
|
||||
let screen = Framebuffer::for_engine()?;
|
||||
let apic_base = crate::apic::base_msr();
|
||||
// The physmap reaches RAM, the framebuffer and the local APIC.
|
||||
let hosted_reims_end = if hosted_reims_region.bytes != 0 {
|
||||
let end = hosted_reims_region
|
||||
.physical
|
||||
.checked_add(hosted_reims_region.bytes)
|
||||
.ok_or(refuse!("hosted Reims BAR2 extent overflows"))?;
|
||||
if hosted_reims_region.physical == 0
|
||||
|| !hosted_reims_region.physical.is_multiple_of(tables::LARGE)
|
||||
|| !hosted_reims_region.bytes.is_multiple_of(tables::LARGE)
|
||||
|| ram
|
||||
.iter()
|
||||
.any(|&(start, end_ram)| (start as u64) < end && hosted_reims_region.physical < end_ram as u64)
|
||||
{
|
||||
return Err(refuse!("hosted Reims BAR2 overlaps RAM or is unaligned"));
|
||||
}
|
||||
Some(end)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The physmap reaches RAM, the framebuffer, the local APIC, and any
|
||||
// direct-mapped hosted Reims BAR2 region.
|
||||
let apic = apic_base & crate::apic::BASE_ADDRESS;
|
||||
let top = ram
|
||||
.iter()
|
||||
@@ -78,6 +101,7 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
.filter_map(|s| s.flip)
|
||||
.map(|r| r as u64 + PAGE),
|
||||
)
|
||||
.chain(hosted_reims_end)
|
||||
.chain(core::iter::once(apic + PAGE))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
@@ -114,6 +138,7 @@ pub(super) fn prepare_image(snapshot: &Snapshot) -> Result<EngineImage> {
|
||||
ram,
|
||||
screen,
|
||||
apic,
|
||||
hosted_reims_region,
|
||||
placement,
|
||||
})
|
||||
}
|
||||
@@ -352,6 +377,7 @@ pub(super) fn map(
|
||||
ram,
|
||||
screen,
|
||||
apic,
|
||||
hosted_reims_region,
|
||||
..
|
||||
} = image;
|
||||
let EngineMemory {
|
||||
@@ -507,7 +533,7 @@ pub(super) fn map(
|
||||
code.bytes,
|
||||
PRESENT | tables::GLOBAL,
|
||||
)?;
|
||||
// The physmap: all RAM, the framebuffer and the local APIC.
|
||||
// The physmap: all RAM, any direct-mapped hosted Reims BAR2, the framebuffer and the local APIC.
|
||||
for &(start, end) in ram {
|
||||
let (start, end) = (start as u64, end as u64);
|
||||
tables::map_range(
|
||||
@@ -519,6 +545,16 @@ pub(super) fn map(
|
||||
data | tables::GLOBAL,
|
||||
)?;
|
||||
}
|
||||
if hosted_reims_region.bytes != 0 {
|
||||
tables::map_range(
|
||||
frames,
|
||||
root,
|
||||
layout::physical(hosted_reims_region.physical),
|
||||
hosted_reims_region.physical,
|
||||
hosted_reims_region.bytes,
|
||||
data | tables::GLOBAL,
|
||||
)?;
|
||||
}
|
||||
if let Some(screen) = screen {
|
||||
let start = screen.base as u64 & !(PAGE - 1);
|
||||
let end = ((screen.base + screen.bytes) as u64).next_multiple_of(PAGE);
|
||||
|
||||
@@ -311,6 +311,24 @@ fn group_symbol(module: &str) -> String {
|
||||
format!("stela_linux_group__{DOMAIN}__{}", token(module))
|
||||
}
|
||||
|
||||
fn compiler_source(path: &Path) -> &Path {
|
||||
// Windows Clang opens a verbatim DOS source path but cannot find its
|
||||
// sibling quoted includes. Keep the canonical path for the input owner
|
||||
// and use the equivalent short DOS path for Clang.
|
||||
#[cfg(windows)]
|
||||
if let Some(dos) = path
|
||||
.to_str()
|
||||
.and_then(|path| path.strip_prefix(r"\\?\"))
|
||||
.filter(|path| {
|
||||
path.as_bytes().get(1..3) == Some(b":\\") && path.encode_utf16().count() < 260
|
||||
})
|
||||
&& fs::canonicalize(dos).is_ok_and(|normalized| normalized == path)
|
||||
{
|
||||
return Path::new(dos);
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// The compiler on `PATH`, as the registry records what built each object.
|
||||
fn resolved(program: &Path) -> PathBuf {
|
||||
let found = env::var_os("PATH")
|
||||
@@ -430,13 +448,14 @@ pub fn compile(
|
||||
.collect();
|
||||
// System-header diagnostics are normally suppressed. Keep the original
|
||||
// function prototypes checked before producing an object for any class.
|
||||
crate::linux_build::check_declarations(&build, std::slice::from_ref(&placement.source));
|
||||
let compiler_source = compiler_source(&placement.source).to_path_buf();
|
||||
crate::linux_build::check_declarations(&build, std::slice::from_ref(&compiler_source));
|
||||
let object = placement.output.join(format!("captured-{token}.o"));
|
||||
let depfile = object.with_extension("d");
|
||||
run(compiler
|
||||
.to_command()
|
||||
.arg("-c")
|
||||
.arg(&placement.source)
|
||||
.arg(&compiler_source)
|
||||
.arg("-o")
|
||||
.arg(&object)
|
||||
.arg("-MD")
|
||||
|
||||
@@ -678,6 +678,7 @@ impl CompilationPlan {
|
||||
options.memory_checks(),
|
||||
options.native_system(),
|
||||
parsed.region,
|
||||
options.position_independent(),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
@@ -714,6 +715,7 @@ impl CompilationPlan {
|
||||
parsed.next_pc,
|
||||
linked,
|
||||
home,
|
||||
options.position_independent(),
|
||||
),
|
||||
};
|
||||
// Code moved after its exits were emitted: each patch point
|
||||
|
||||
@@ -88,6 +88,7 @@ pub(crate) fn emit(
|
||||
flags_live: false,
|
||||
target,
|
||||
zero_branch: None,
|
||||
sharing: false,
|
||||
},
|
||||
);
|
||||
if let Some(profile) = profile
|
||||
|
||||
@@ -730,3 +730,78 @@ fn self_loops_keep_flags_across_joins_and_back_edges() {
|
||||
}
|
||||
assert!(checked >= 20, "{checked}");
|
||||
}
|
||||
|
||||
/// A self-loop's compare whose B.cond joins a load that faults, in the
|
||||
/// first iteration or a later one: the word at the fault is the compare's
|
||||
/// NZCV, whether the branch was taken (its join stores the word) or fell
|
||||
/// through (the instruction it skips is not a reader).
|
||||
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
|
||||
#[test]
|
||||
fn a_fault_where_a_self_loop_join_lands_finds_the_compare_nzcv() {
|
||||
use super::vector_cache_tests::faulting;
|
||||
use crate::{Anchor, x86_64::chain::ChainControl};
|
||||
const LDR_X8: u32 = 0xf840_8408;
|
||||
const CMP_X8_X9: u32 = 0xeb09_011f;
|
||||
const ADD_X10_1: u32 = 0x9100_054a;
|
||||
/// LDR X11, [X12, X8].
|
||||
const LDR_X11_X12_X8: u32 = 0xf868_698b;
|
||||
const SUBS_X2_1: u32 = 0xf100_0442;
|
||||
let guard = faulting::guard_page();
|
||||
let buffer = vec![0_u64; 512];
|
||||
let mut faults = 0;
|
||||
for target in targets() {
|
||||
for condition in [0, 1, 2, 3, 4, 8, 9, 10, 11, 12] {
|
||||
let words = [
|
||||
LDR_X8,
|
||||
CMP_X8_X9,
|
||||
b_cond(condition, 8),
|
||||
ADD_X10_1,
|
||||
LDR_X11_X12_X8,
|
||||
SUBS_X2_1,
|
||||
b_cond(1, -24),
|
||||
];
|
||||
let source: Vec<u8> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
let options = super::host_cost::options(target).with_native_system(NativeSystem {
|
||||
exclusive: true,
|
||||
self_loops: true,
|
||||
..NativeSystem::NONE
|
||||
});
|
||||
let compiled =
|
||||
crate::block::CompilationPlan::new(&source, GuestAddress(0x1000), &options)
|
||||
.and_then(|plan| plan.compile())
|
||||
.unwrap();
|
||||
assert!(compiled.self_loop);
|
||||
let code = pinned::entered(&compiled.native.x86_64_code);
|
||||
for faulting_iteration in [0, 1, 4, 20] {
|
||||
for x9 in [0, 0x7f8, 0x1000, 0x8000_0000_0000_0000, u64::MAX] {
|
||||
// Offsets into the buffer, then the one onto the guard.
|
||||
let mut elements: Vec<u64> = (0..faulting_iteration)
|
||||
.map(|at| (at as u64 * 0x2a8) % 0x1000)
|
||||
.collect();
|
||||
elements.push(guard.wrapping_sub(buffer.as_ptr() as u64));
|
||||
let mut control = ChainControl::default();
|
||||
let mut state = GuestState {
|
||||
nzcv: 0x5000_0000,
|
||||
lower_limit: Limit(u64::MAX),
|
||||
..GuestState::default()
|
||||
};
|
||||
state.anchors[Anchor::Control] = (&raw mut control) as u64;
|
||||
state.x[0] = elements.as_ptr() as u64;
|
||||
state.x[2] = 1000;
|
||||
state.x[9] = x9;
|
||||
state.x[12] = buffer.as_ptr() as u64;
|
||||
let label =
|
||||
alloc::format!("{condition} {faulting_iteration} {x9:#x} {target:?}");
|
||||
assert!(faulting::run(&code, &mut state).is_err(), "{label}");
|
||||
assert_eq!(
|
||||
flag_word::arm(state.nzcv),
|
||||
nzcv_of_subtract(*elements.last().unwrap(), x9),
|
||||
"{label}"
|
||||
);
|
||||
faults += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(faults >= 200, "{faults}");
|
||||
}
|
||||
@@ -426,12 +426,19 @@ pub struct ChainControl {
|
||||
pub reserved: u32,
|
||||
/// The host address of the board's retire epoch, which every step that
|
||||
/// retires blocks advances, or 0 with `frame_room` 0. A frame holds
|
||||
/// the epoch of its push; a return takes it only while the epoch is
|
||||
/// unchanged, as its continuation may lie in a block retired since.
|
||||
/// the epoch of its push plus `moves`; a return takes it only while
|
||||
/// that sum is unchanged, as its continuation may lie in a block
|
||||
/// retired since or in other contexts.
|
||||
pub retire_epoch: u64,
|
||||
/// What paired frames did ([`PairCount`]): native code's counts, which
|
||||
/// only grow.
|
||||
pub pairs: [u64; PAIR_COUNTS],
|
||||
/// Advanced by every native write of `contexts` (a transition's
|
||||
/// commit or a native table switch), and never lowered: as the retire
|
||||
/// epoch only grows too, their sum, which a paired frame holds, is
|
||||
/// unchanged only while both are. The engine's own writes of `contexts`
|
||||
/// come between native runs, which keep no frames.
|
||||
pub moves: u64,
|
||||
}
|
||||
|
||||
/// The counts of [`ChainControl::pairs`].
|
||||
@@ -462,7 +469,7 @@ pub const DEFAULT_FRAME_BOUND: u32 = 64;
|
||||
/// block's word, the retire epoch and the lower and upper half's contexts
|
||||
/// ([`FrameWord`]). A multiple of 16, so code between blocks keeps its
|
||||
/// stack alignment.
|
||||
pub const FRAME_BYTES: usize = 48;
|
||||
pub const FRAME_BYTES: usize = 32;
|
||||
|
||||
/// The words of a paired frame above its host return address, by their
|
||||
/// offset from RSP while the return address is on top.
|
||||
@@ -470,17 +477,15 @@ pub const FRAME_BYTES: usize = 48;
|
||||
enum FrameWord {
|
||||
Address = 8,
|
||||
Block = 16,
|
||||
Epoch = 24,
|
||||
LowerContext = 32,
|
||||
UpperContext = 40,
|
||||
Key = 24,
|
||||
}
|
||||
const _: () = assert!(FrameWord::UpperContext as usize + 8 == FRAME_BYTES);
|
||||
const _: () = assert!(FrameWord::Key as usize + 8 == FRAME_BYTES);
|
||||
|
||||
// Epoch and observed state are naturally aligned atomic-width words. Capture
|
||||
// and storage owners keep the mapped control alive for every embedded address.
|
||||
const _: () = assert!(core::mem::offset_of!(ChainControl, interrupt_epoch) == 64);
|
||||
const _: () = assert!(core::mem::offset_of!(ChainControl, observed_interrupt_epoch) == 72);
|
||||
const _: () = assert!(core::mem::size_of::<ChainControl>() == 184);
|
||||
const _: () = assert!(core::mem::size_of::<ChainControl>() == 192);
|
||||
// The gates read the quiet word with no displacement, on `block`'s line.
|
||||
const _: () = assert!(core::mem::offset_of!(ChainControl, quiet) == 0);
|
||||
|
||||
@@ -2618,6 +2623,15 @@ const OBSERVED_INTERRUPT_EPOCH: i32 =
|
||||
const FRAME_ROOM: i32 = core::mem::offset_of!(ChainControl, frame_room) as i32;
|
||||
const RETIRE_EPOCH: i32 = core::mem::offset_of!(ChainControl, retire_epoch) as i32;
|
||||
const PAIRS: i32 = core::mem::offset_of!(ChainControl, pairs) as i32;
|
||||
const MOVES: i32 = core::mem::offset_of!(ChainControl, moves) as i32;
|
||||
|
||||
/// R8 = a paired frame's key now: the board's retire epoch plus the context
|
||||
/// moves ([`ChainControl::moves`]), RCX at the control.
|
||||
fn frame_key(asm: &mut crate::x86_64::asm::Asm) {
|
||||
asm.mov_load(Qword, R8, Mem::base(Rcx, RETIRE_EPOCH));
|
||||
asm.mov_load(Qword, R8, Mem::base(R8, 0));
|
||||
asm.alu_load(Alu::Add, Qword, R8, Mem::base(Rcx, MOVES));
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Interruption {
|
||||
@@ -3399,10 +3413,8 @@ pub(crate) fn paired_call(
|
||||
asm.alu(Alu::Sub, Qword, R8, Gpr::Rsp);
|
||||
asm.alu_load(Alu::Cmp, Dword, R8, Mem::base(Rcx, FRAME_ROOM));
|
||||
let refused = asm.jcc(Cond::Ae);
|
||||
asm.push_rm(Mem::base(Rcx, CONTEXTS + 8));
|
||||
asm.push_rm(Mem::base(Rcx, CONTEXTS));
|
||||
asm.mov_load(Qword, R8, Mem::base(Rcx, RETIRE_EPOCH));
|
||||
asm.push_rm(Mem::base(R8, 0));
|
||||
frame_key(asm);
|
||||
asm.push(R8);
|
||||
asm.push_rm(Mem::base(Rcx, BLOCK));
|
||||
asm.guest_imm64(R8, return_address);
|
||||
asm.push(R8);
|
||||
@@ -3463,15 +3475,9 @@ fn paired_return_for(asm: &mut crate::x86_64::asm::Asm, ran: u32, sharing: bool)
|
||||
let mut misses = Vec::new();
|
||||
asm.alu_load(Alu::Cmp, Qword, Rax, frame(FrameWord::Address));
|
||||
misses.push(asm.jcc8(Cond::Ne));
|
||||
asm.mov_load(Qword, R8, Mem::base(Rcx, RETIRE_EPOCH));
|
||||
asm.mov_load(Qword, R8, Mem::base(R8, 0));
|
||||
asm.alu_load(Alu::Cmp, Qword, R8, frame(FrameWord::Epoch));
|
||||
frame_key(asm);
|
||||
asm.alu_load(Alu::Cmp, Qword, R8, frame(FrameWord::Key));
|
||||
misses.push(asm.jcc8(Cond::Ne));
|
||||
for (half, word) in [(0, FrameWord::LowerContext), (1, FrameWord::UpperContext)] {
|
||||
asm.mov_load(Qword, R8, Mem::base(Rcx, CONTEXTS + 8 * half));
|
||||
asm.alu_load(Alu::Cmp, Qword, R8, frame(word));
|
||||
misses.push(asm.jcc8(Cond::Ne));
|
||||
}
|
||||
// A transfer left and no interruption pending. A return spends none,
|
||||
// and counts the block's instructions.
|
||||
misses.push(stop_check(asm, Interruption::Quiet, false));
|
||||
|
||||
@@ -92,17 +92,20 @@ enum Callee {
|
||||
/// A native SVC or exception entry: the lower half's context changes
|
||||
/// (another EL's), and the upper half's.
|
||||
Entered,
|
||||
/// That entry, then the ERET back: the contexts are the call's again.
|
||||
/// That entry, then the ERET back: the contexts are the call's again,
|
||||
/// but they moved.
|
||||
EnteredAndReturned,
|
||||
/// A native ERET to another process: the lower half's context alone
|
||||
/// changes.
|
||||
Switched,
|
||||
}
|
||||
|
||||
/// Change the context of `half` by `by`.
|
||||
/// Change the context of `half` by `by`, a move, as a transition's commit
|
||||
/// does.
|
||||
fn move_context(asm: &mut Asm, half: i32, by: i8) {
|
||||
asm.place(Rcx, CONTROL);
|
||||
asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, CONTEXTS_AT + 8 * half), by);
|
||||
asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, MOVES), 1);
|
||||
}
|
||||
const CONTEXTS_AT: i32 = core::mem::offset_of!(ChainControl, contexts) as i32;
|
||||
|
||||
@@ -257,7 +260,7 @@ fn what_runs_between_call_and_return_decides_the_frame() {
|
||||
(Callee::Interrupted, false),
|
||||
(Callee::Entered, false),
|
||||
(Callee::Switched, false),
|
||||
(Callee::EnteredAndReturned, true),
|
||||
(Callee::EnteredAndReturned, false),
|
||||
] {
|
||||
let code = pages(&call_and_return(callee));
|
||||
let mut run = Run::new(DEFAULT_FRAME_BOUND);
|
||||
|
||||
@@ -91,9 +91,10 @@ pub(super) fn memcmp(code: &mut Code, request: Request, bails: &mut Bails) -> Ve
|
||||
let mut asm = code.asm();
|
||||
asm.movzx(Size::Dword, Gpr::Rax, Size::Byte, at(a, Some(Gpr::Rdx), 0));
|
||||
asm.movzx(Size::Dword, Gpr::R10, Size::Byte, at(b, Some(Gpr::Rdx), 0));
|
||||
asm.alu(Alu::Sub, Size::Dword, Gpr::Rax, Gpr::R10);
|
||||
// The commit: X0, zero-extended from its low word.
|
||||
asm.mov(Size::Dword, Gpr::R15, Gpr::Rax);
|
||||
asm.alu(Alu::Sub, Size::Qword, Gpr::Rax, Gpr::R10);
|
||||
// The commit: X0, 64-bit signed difference `i64(a[i]) - i64(b[i])`
|
||||
// matching Apple's `__platform_memcmp` (`sub x0, ...`).
|
||||
asm.mov(Size::Qword, Gpr::R15, Gpr::Rax);
|
||||
}
|
||||
let mut done = Label::default();
|
||||
done.jump(code);
|
||||
|
||||
@@ -867,6 +867,16 @@ pub(super) fn pair(
|
||||
// Block code (no recipe) moves an aligned quadword pair straight
|
||||
// between XMM0 and where its registers live.
|
||||
let direct_pair = recipe.is_none() && alignment == PairAlignment::Aligned;
|
||||
// And, in pinned code, a tested one where its address tests aligned:
|
||||
// the element accesses stage and commit on their own path. Frame code
|
||||
// keeps the form the regions' tests know byte for byte.
|
||||
let direct_tested = recipe.is_none()
|
||||
&& code.is_pinned()
|
||||
&& tested
|
||||
&& match transfer {
|
||||
MemoryTransfer::Store => data.iter().all(|®ister| register != Register::Zero),
|
||||
MemoryTransfer::Load { .. } => !loads_base,
|
||||
};
|
||||
match transfer {
|
||||
MemoryTransfer::Store
|
||||
if direct_pair
|
||||
@@ -876,6 +886,15 @@ pub(super) fn pair(
|
||||
quadword_pair_load_direct(code, Mem::base(at, displacement), data);
|
||||
}
|
||||
MemoryTransfer::Store => {
|
||||
let mut done = None;
|
||||
if direct_tested {
|
||||
code.asm().test_imm(Size::Byte, at, 15);
|
||||
let split = code.asm().jcc8(Cond::Ne);
|
||||
quadword_pair_store_direct(code, Mem::base(at, displacement), data)
|
||||
.expect("neither is XZR");
|
||||
done = Some(code.asm().jmp8());
|
||||
code.asm().bind(split);
|
||||
}
|
||||
let first = match code.host(data[0]) {
|
||||
Some(host) => memory_store::Source::Host(host),
|
||||
None => {
|
||||
@@ -927,8 +946,7 @@ pub(super) fn pair(
|
||||
quadword_pair_store(code, Mem::base(at, displacement), sources);
|
||||
mark(&mut recipe, code, start, Kind::Store, 0);
|
||||
} else {
|
||||
let mut done = None;
|
||||
if tested {
|
||||
if tested && !direct_tested {
|
||||
code.asm().test_imm(Size::Byte, at, 15);
|
||||
let split = code.asm().jcc8(Cond::Ne);
|
||||
quadword_pair_store(code, Mem::base(at, displacement), sources);
|
||||
@@ -975,8 +993,12 @@ pub(super) fn pair(
|
||||
if tested {
|
||||
code.asm().test_imm(Size::Byte, at, 15);
|
||||
let split = code.asm().jcc8(Cond::Ne);
|
||||
quadword_pair_load(code, Mem::base(at, displacement), hosts[0]);
|
||||
quadword_pair_second(code, hosts[1]);
|
||||
if direct_tested {
|
||||
quadword_pair_load_direct(code, Mem::base(at, displacement), data);
|
||||
} else {
|
||||
quadword_pair_load(code, Mem::base(at, displacement), hosts[0]);
|
||||
quadword_pair_second(code, hosts[1]);
|
||||
}
|
||||
done = Some(code.asm().jmp8());
|
||||
code.asm().bind(split);
|
||||
}
|
||||
@@ -1006,7 +1028,8 @@ pub(super) fn pair(
|
||||
});
|
||||
}
|
||||
if element == 1
|
||||
&& let Some(done) = done
|
||||
&& !direct_tested
|
||||
&& let Some(done) = done.take()
|
||||
{
|
||||
code.asm().bind(done);
|
||||
}
|
||||
@@ -1033,6 +1056,10 @@ pub(super) fn pair(
|
||||
mark(&mut recipe, code, start, Kind::Commit, 0);
|
||||
}
|
||||
}
|
||||
// The 16-byte access has left both elements where they live.
|
||||
if let Some(done) = done {
|
||||
code.asm().bind(done);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Commit writeback only after all faultable element accesses succeed.
|
||||
|
||||
@@ -1,218 +1,246 @@
|
||||
//! PAC instructions computed in native code, without the memo.
|
||||
//!
|
||||
//! Where the host has AES-NI, the engine's PAC cipher is the whitening key
|
||||
//! and six full AES rounds of the pointer and modifier under the key
|
||||
//! (`pauth::keyed`, the PAC algorithm Apple silicon leaves IMPLEMENTATION
|
||||
//! DEFINED), whose state's low half is the PAC. Native code runs those
|
||||
//! rounds in fewer instructions than a memo miss spends reaching the
|
||||
//! service, and a memo hit is a load from a table far larger than the
|
||||
//! caches. So a block or thunk given a [`Cipher`] computes every signing,
|
||||
//! successful authentication and PACGA itself, from what the engine keeps
|
||||
//! there for the current keys, PAC version and TCR: each key's schedule
|
||||
//! (the whitening key and six round keys) and, for each domain, the PAC
|
||||
//! field of each range ([`Range`]).
|
||||
//!
|
||||
//! Native code completes canonical pointers only, whose extension bits all
|
||||
//! equal bit 55. For them Arm `AddPAC` and `Auth` take one layout, the one
|
||||
//! bit 55 selects (a signing that selects by bit 63 sees the same bit
|
||||
//! there), so the range table is indexed by bit 55 alone. With `E` that
|
||||
//! range's extension mask, `M` it without bit 55 and `pac` the cipher of
|
||||
//! the input:
|
||||
//! - a signing of a canonical pointer (`p & E` is the range's canonical
|
||||
//! extension) has the pointer as its input and gives
|
||||
//! `p ^ (pac & M) ^ signed`, where `signed` turns the classic insertion,
|
||||
//! which replaces an upper pointer's all-ones field, into that XOR;
|
||||
//! - an authentication's input is `p` stripped, `(p & !E) | canonical`; it
|
||||
//! succeeds exactly when `(p ^ pac) & M` is the range's `authenticated`
|
||||
//! (the input's field under FEAT_PAuth2's XOR, zero under the classic
|
||||
//! comparison), and then gives its input;
|
||||
//! - PACGA gives the cipher's upper half.
|
||||
//!
|
||||
//! A key whose tag word is [`super::DISABLED`] (its SCTLR enable clear)
|
||||
//! gives the pointer unchanged, as Arm does, from the tag word alone: native
|
||||
//! transitions switch the tag words between two exception levels of one
|
||||
//! memo generation (`transition::check_pointer`), whose enables differ while
|
||||
//! their keys, version and layouts do not, so nothing else in the cipher
|
||||
//! may depend on an enable. One compare tells an open key from a closed or
|
||||
//! disabled one; the out-of-line path then tells those two apart
|
||||
//! (`Lookup::unopened`). Everything else, a closed key (tag word
|
||||
//! zero), a signing of a non-canonical pointer and a failed authentication,
|
||||
//! goes to the service as a memo miss does, which computes it the engine's
|
||||
//! way. The computation clobbers RAX, R8 to R11, XMM0, XMM1 and flags.
|
||||
use super::{GENERIC_KEY, Lookup, TAG_WORDS, operands};
|
||||
use crate::Place;
|
||||
use crate::x86_64::asm::{Alu, Asm, BitTest, Cond, Gpr, Mem, Rm, ShiftOp, Size};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// The words of a key's schedule: the whitening key and six round keys,
|
||||
/// each low quadword first.
|
||||
pub const SCHEDULE: usize = 7;
|
||||
|
||||
/// The bit that selects a canonical pointer's range: Arm keeps it in a
|
||||
/// signed pointer.
|
||||
const RANGE_BIT: u8 = 55;
|
||||
|
||||
/// Where one range of one domain puts its PAC field, as native code applies
|
||||
/// it to canonical pointers ([`Range::new`]).
|
||||
#[repr(C, align(64))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Range {
|
||||
/// `E`: the extension bits, from bit 64 - TnSZ to the top PAC bit.
|
||||
pub extension: u64,
|
||||
/// `!E`: the bits a stripped pointer keeps.
|
||||
pub kept: u64,
|
||||
/// A canonical pointer's extension in this range: zero in the lower
|
||||
/// range, `E` in the upper one.
|
||||
pub canonical: u64,
|
||||
/// `M`: `E` without bit 55, the PAC field.
|
||||
pub field: u64,
|
||||
/// What a signing XORs into the field besides the PAC: `M` in the upper
|
||||
/// range under the classic insertion, which replaces the field (all
|
||||
/// ones there), else zero.
|
||||
pub signed: u64,
|
||||
/// What `(p ^ pac) & M` is for an authentic `p`: `M` in the upper range
|
||||
/// under FEAT_PAuth2, which XORs the PAC into the field (all ones in
|
||||
/// the input), else zero.
|
||||
pub authenticated: u64,
|
||||
}
|
||||
|
||||
impl Range {
|
||||
/// The range whose extension mask is `extension` (it holds bit 55), the
|
||||
/// upper one if `upper`, under the classic insertion if `classic`.
|
||||
pub const fn new(extension: u64, upper: bool, classic: bool) -> Self {
|
||||
let field = extension & !(1 << RANGE_BIT);
|
||||
Self {
|
||||
extension,
|
||||
kept: !extension,
|
||||
canonical: if upper { extension } else { 0 },
|
||||
field,
|
||||
signed: if upper && classic { field } else { 0 },
|
||||
authenticated: if upper && !classic { field } else { 0 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What native code computes PAC results from, at a fixed host address.
|
||||
#[repr(C, align(64))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Cipher {
|
||||
/// Each tag word's key schedule ([`SCHEDULE`]).
|
||||
pub schedules: [[[u64; 2]; SCHEDULE]; TAG_WORDS],
|
||||
/// The instruction keys' ranges, then the data keys', each by bit 55.
|
||||
pub ranges: [[Range; 2]; 2],
|
||||
}
|
||||
|
||||
const SCHEDULES: usize = core::mem::offset_of!(Cipher, schedules);
|
||||
const RANGES: usize = core::mem::offset_of!(Cipher, ranges);
|
||||
/// Bytes of a [`Range`], which bit 55 indexes.
|
||||
const RANGE_BYTES: i32 = core::mem::size_of::<Range>() as i32;
|
||||
const _: () = assert!(RANGE_BYTES == 64 && SCHEDULES.is_multiple_of(16));
|
||||
const EXTENSION: usize = core::mem::offset_of!(Range, extension);
|
||||
const KEPT: usize = core::mem::offset_of!(Range, kept);
|
||||
const CANONICAL: usize = core::mem::offset_of!(Range, canonical);
|
||||
const FIELD: usize = core::mem::offset_of!(Range, field);
|
||||
const SIGNED: usize = core::mem::offset_of!(Range, signed);
|
||||
const AUTHENTICATED: usize = core::mem::offset_of!(Range, authenticated);
|
||||
|
||||
/// `operation` on XMM0 with ModRM.rm `rm`, a legacy SSE form.
|
||||
fn sse(asm: &mut Asm, opcode: &[u8], rm: impl Into<Rm>) {
|
||||
asm.sse(Some(0x66), opcode, 0, rm);
|
||||
}
|
||||
|
||||
/// The cipher of `data` and `modifier` under the schedule at R8 +
|
||||
/// `schedule` into XMM0, whose low half is the PAC: the whitening key and
|
||||
/// the six AES rounds of `pauth::keyed`. Clobbers XMM1.
|
||||
fn rounds(asm: &mut Asm, data: Gpr, modifier: Gpr, schedule: i32) {
|
||||
const PXOR: [u8; 2] = [0x0f, 0xef];
|
||||
const AESENC: [u8; 3] = [0x0f, 0x38, 0xdc];
|
||||
asm.movq_to_xmm(0, data);
|
||||
asm.movq_to_xmm(1, modifier);
|
||||
asm.punpcklqdq(0, Rm::Xmm(1));
|
||||
let word = |index: i32| Mem::base(Gpr::R8, schedule + 16 * index);
|
||||
sse(asm, &PXOR, word(0));
|
||||
for round in 1..SCHEDULE as i32 {
|
||||
sse(asm, &AESENC, word(round));
|
||||
}
|
||||
}
|
||||
|
||||
/// R11 the byte offset of the range bit 55 of RAX selects: 0 or
|
||||
/// [`RANGE_BYTES`].
|
||||
fn range_index(asm: &mut Asm) {
|
||||
use Gpr::{R11, Rax};
|
||||
asm.bit_imm(BitTest::Bt, Size::Qword, Rax, RANGE_BIT);
|
||||
asm.alu(Alu::Sbb, Size::Qword, R11, R11);
|
||||
asm.alu_imm8(Alu::And, Size::Dword, R11, RANGE_BYTES as i8);
|
||||
}
|
||||
|
||||
/// The result of `form` on its operands, computed from the [`Cipher`] at
|
||||
/// `cipher` under the tag words at `tags` (one anchor): RAX the result, the
|
||||
/// misses' jumps with RAX the pointer and the modifier in its register, as
|
||||
/// [`super::lookup`] leaves them, and the jump taken while the key is not
|
||||
/// open.
|
||||
pub(super) fn compute(asm: &mut Asm, form: super::Form, tags: Place, cipher: Place) -> Lookup {
|
||||
use Gpr::{R8, R9, R10, R11, Rax};
|
||||
use Size::Qword;
|
||||
assert_eq!(
|
||||
tags.anchor, cipher.anchor,
|
||||
"the tag words and cipher share an anchor"
|
||||
);
|
||||
let modifier = operands(asm, form);
|
||||
debug_assert!(!matches!(modifier, R9 | R10 | R11));
|
||||
asm.place(R8, Place::new(tags.anchor, 0));
|
||||
let at = |offset: usize| i32::try_from(cipher.offset + offset).expect("a cipher field offset");
|
||||
// Every open key's tag word is above the disabled one's, and a closed
|
||||
// key's is below it.
|
||||
let word = i32::try_from(tags.offset + usize::from(form.key) * 8).expect("a tag word offset");
|
||||
asm.alu_imm32(Alu::Cmp, Qword, Mem::base(R8, word), super::DISABLED as i32);
|
||||
let unopened = asm.jcc(Cond::Be);
|
||||
let schedule = at(SCHEDULES + usize::from(form.key) * SCHEDULE * 16);
|
||||
if form.key == GENERIC_KEY {
|
||||
// The generic key is never disabled: a closed one misses.
|
||||
rounds(asm, Rax, modifier, schedule);
|
||||
asm.movq_from_xmm(Rax, 0);
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, Rax, 32);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 32);
|
||||
return Lookup {
|
||||
misses: alloc::vec![unopened],
|
||||
modifier,
|
||||
unopened: None,
|
||||
};
|
||||
}
|
||||
let data = form.key >= super::key_index(crate::block::PointerAuthenticationKey::Da);
|
||||
let domain = RANGES + usize::from(data) * 2 * RANGE_BYTES as usize;
|
||||
let range = |field: usize| Mem::indexed(R8, R11, 1, at(domain + field));
|
||||
let mut misses = Vec::new();
|
||||
if form.kind != super::AUTHENTICATED {
|
||||
// The cipher of the pointer itself, a canonical one's input.
|
||||
rounds(asm, Rax, modifier, schedule);
|
||||
range_index(asm);
|
||||
asm.mov(Qword, R10, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R10, range(EXTENSION));
|
||||
asm.alu_load(Alu::Cmp, Qword, R10, range(CANONICAL));
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
// p ^ (pac & M) ^ signed.
|
||||
asm.movq_from_xmm(R9, 0);
|
||||
asm.alu_load(Alu::And, Qword, R9, range(FIELD));
|
||||
asm.alu_load(Alu::Xor, Qword, R9, range(SIGNED));
|
||||
asm.alu(Alu::Xor, Qword, Rax, R9);
|
||||
} else {
|
||||
// R9 = the input: (p & !E) | canonical.
|
||||
range_index(asm);
|
||||
asm.mov(Qword, R9, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R9, range(KEPT));
|
||||
asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL));
|
||||
rounds(asm, R9, modifier, schedule);
|
||||
// Authentic when (p ^ pac) & M is the range's `authenticated`.
|
||||
asm.movq_from_xmm(R10, 0);
|
||||
asm.alu(Alu::Xor, Qword, R10, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R10, range(FIELD));
|
||||
asm.alu_load(Alu::Cmp, Qword, R10, range(AUTHENTICATED));
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.mov(Qword, Rax, R9);
|
||||
}
|
||||
Lookup {
|
||||
misses,
|
||||
modifier,
|
||||
unopened: Some(unopened),
|
||||
}
|
||||
}
|
||||
//! PAC instructions computed in native code, without the memo.
|
||||
//!
|
||||
//! Where the host has AES-NI, the engine's PAC cipher is the whitening key
|
||||
//! and six full AES rounds of the pointer and modifier under the key
|
||||
//! (`pauth::keyed`, the PAC algorithm Apple silicon leaves IMPLEMENTATION
|
||||
//! DEFINED), whose state's low half is the PAC. Native code runs those
|
||||
//! rounds in fewer instructions than a memo miss spends reaching the
|
||||
//! service, and a memo hit is a load from a table far larger than the
|
||||
//! caches. So a block or thunk given a [`Cipher`] computes every signing,
|
||||
//! successful authentication and PACGA itself, from what the engine keeps
|
||||
//! there for the current keys, PAC version and TCR: each key's schedule
|
||||
//! (the whitening key and six round keys) and, for each domain, the PAC
|
||||
//! field of each range ([`Range`]).
|
||||
//!
|
||||
//! Native code completes canonical pointers only, whose extension bits all
|
||||
//! equal bit 55. For them Arm `AddPAC` and `Auth` take one layout, the one
|
||||
//! bit 55 selects (a signing that selects by bit 63 sees the same bit
|
||||
//! there), so the range table is indexed by bit 55 alone. With `E` that
|
||||
//! range's extension mask, `M` it without bit 55 and `pac` the cipher of
|
||||
//! the input:
|
||||
//! - a signing of a canonical pointer (`p & E` is the range's canonical
|
||||
//! extension) has the pointer as its input and gives
|
||||
//! `p ^ (pac & M) ^ signed`, where `signed` turns the classic insertion,
|
||||
//! which replaces an upper pointer's all-ones field, into that XOR;
|
||||
//! - an authentication's input is `p` stripped, `(p & !E) | canonical`; it
|
||||
//! succeeds exactly when `(p ^ pac) & M` is the range's `authenticated`
|
||||
//! (the input's field under FEAT_PAuth2's XOR, zero under the classic
|
||||
//! comparison), and then gives its input;
|
||||
//! - PACGA gives the cipher's upper half.
|
||||
//!
|
||||
//! A key whose tag word is [`super::DISABLED`] (its SCTLR enable clear)
|
||||
//! gives the pointer unchanged, as Arm does, from the tag word alone: native
|
||||
//! transitions switch the tag words between two exception levels of one
|
||||
//! memo generation (`transition::check_pointer`), whose enables differ while
|
||||
//! their keys, version and layouts do not, so nothing else in the cipher
|
||||
//! may depend on an enable. One compare tells an open key from a closed or
|
||||
//! disabled one; the out-of-line path then tells those two apart
|
||||
//! (`Lookup::unopened`). Everything else, a closed key (tag word
|
||||
//! zero), a signing of a non-canonical pointer and a failed authentication,
|
||||
//! goes to the service as a memo miss does, which computes it the engine's
|
||||
//! way. The computation clobbers RAX, R8 to R11, XMM0, XMM1 and flags.
|
||||
use super::{GENERIC_KEY, Lookup, TAG_WORDS, operands};
|
||||
use crate::Place;
|
||||
use crate::x86_64::asm::{Alu, Asm, BitTest, Cond, Gpr, Mem, Rm, ShiftOp, Size};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// The words of a key's schedule: the whitening key and six round keys,
|
||||
/// each low quadword first.
|
||||
pub const SCHEDULE: usize = 7;
|
||||
|
||||
/// The bit that selects a canonical pointer's range: Arm keeps it in a
|
||||
/// signed pointer.
|
||||
const RANGE_BIT: u8 = 55;
|
||||
|
||||
/// Where one range of one domain puts its PAC field, as native code applies
|
||||
/// it to canonical pointers ([`Range::new`]).
|
||||
#[repr(C, align(64))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Range {
|
||||
/// `E`: the extension bits, from bit 64 - TnSZ to the top PAC bit.
|
||||
pub extension: u64,
|
||||
/// `!E`: the bits a stripped pointer keeps.
|
||||
pub kept: u64,
|
||||
/// A canonical pointer's extension in this range: zero in the lower
|
||||
/// range, `E` in the upper one.
|
||||
pub canonical: u64,
|
||||
/// `M`: `E` without bit 55, the PAC field.
|
||||
pub field: u64,
|
||||
/// What a signing XORs into the field besides the PAC: `M` in the upper
|
||||
/// range under the classic insertion, which replaces the field (all
|
||||
/// ones there), else zero.
|
||||
pub signed: u64,
|
||||
/// What `(p ^ pac) & M` is for an authentic `p`: `M` in the upper range
|
||||
/// under FEAT_PAuth2, which XORs the PAC into the field (all ones in
|
||||
/// the input), else zero.
|
||||
pub authenticated: u64,
|
||||
/// Nonzero under FEAT_PAuth2 (`!classic`), enabling native signing of
|
||||
/// non-canonical pointers.
|
||||
pub enhanced: u64,
|
||||
/// Nonzero when signing selects TnSZ by bit 63 rather than bit 55
|
||||
/// (neither range ignores the top byte).
|
||||
pub select_bit63: u64,
|
||||
}
|
||||
|
||||
impl Range {
|
||||
/// The range whose extension mask is `extension` (it holds bit 55), the
|
||||
/// upper one if `upper`, under the classic insertion if `classic`, and
|
||||
/// selecting TnSZ by bit 63 when signing if `select_bit63`.
|
||||
pub const fn new(extension: u64, upper: bool, classic: bool, select_bit63: bool) -> Self {
|
||||
let field = extension & !(1 << RANGE_BIT);
|
||||
Self {
|
||||
extension,
|
||||
kept: !extension,
|
||||
canonical: if upper { extension } else { 0 },
|
||||
field,
|
||||
signed: if upper && classic { field } else { 0 },
|
||||
authenticated: if upper && !classic { field } else { 0 },
|
||||
enhanced: if !classic { 1 } else { 0 },
|
||||
select_bit63: if select_bit63 { 1 } else { 0 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What native code computes PAC results from, at a fixed host address.
|
||||
#[repr(C, align(64))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Cipher {
|
||||
/// Each tag word's key schedule ([`SCHEDULE`]).
|
||||
pub schedules: [[[u64; 2]; SCHEDULE]; TAG_WORDS],
|
||||
/// The instruction keys' ranges, then the data keys', each by bit 55.
|
||||
pub ranges: [[Range; 2]; 2],
|
||||
}
|
||||
|
||||
const SCHEDULES: usize = core::mem::offset_of!(Cipher, schedules);
|
||||
const RANGES: usize = core::mem::offset_of!(Cipher, ranges);
|
||||
/// Bytes of a [`Range`], which bit 55 indexes.
|
||||
const RANGE_BYTES: i32 = core::mem::size_of::<Range>() as i32;
|
||||
const _: () = assert!(RANGE_BYTES == 64 && SCHEDULES.is_multiple_of(16));
|
||||
const EXTENSION: usize = core::mem::offset_of!(Range, extension);
|
||||
const KEPT: usize = core::mem::offset_of!(Range, kept);
|
||||
const CANONICAL: usize = core::mem::offset_of!(Range, canonical);
|
||||
const FIELD: usize = core::mem::offset_of!(Range, field);
|
||||
const SIGNED: usize = core::mem::offset_of!(Range, signed);
|
||||
const AUTHENTICATED: usize = core::mem::offset_of!(Range, authenticated);
|
||||
const ENHANCED: usize = core::mem::offset_of!(Range, enhanced);
|
||||
const SELECT_BIT63: usize = core::mem::offset_of!(Range, select_bit63);
|
||||
|
||||
/// `operation` on XMM0 with ModRM.rm `rm`, a legacy SSE form.
|
||||
fn sse(asm: &mut Asm, opcode: &[u8], rm: impl Into<Rm>) {
|
||||
asm.sse(Some(0x66), opcode, 0, rm);
|
||||
}
|
||||
|
||||
/// The cipher of `data` and `modifier` under the schedule at R8 +
|
||||
/// `schedule` into XMM0, whose low half is the PAC: the whitening key and
|
||||
/// the six AES rounds of `pauth::keyed`. Clobbers XMM1.
|
||||
fn rounds(asm: &mut Asm, data: Gpr, modifier: Gpr, schedule: i32) {
|
||||
const PXOR: [u8; 2] = [0x0f, 0xef];
|
||||
const AESENC: [u8; 3] = [0x0f, 0x38, 0xdc];
|
||||
asm.movq_to_xmm(0, data);
|
||||
asm.movq_to_xmm(1, modifier);
|
||||
asm.punpcklqdq(0, Rm::Xmm(1));
|
||||
let word = |index: i32| Mem::base(Gpr::R8, schedule + 16 * index);
|
||||
sse(asm, &PXOR, word(0));
|
||||
for round in 1..SCHEDULE as i32 {
|
||||
sse(asm, &AESENC, word(round));
|
||||
}
|
||||
}
|
||||
|
||||
/// R11 the byte offset of the range bit 55 of RAX selects: 0 or
|
||||
/// [`RANGE_BYTES`].
|
||||
fn range_index(asm: &mut Asm) {
|
||||
use Gpr::{R11, Rax};
|
||||
asm.bit_imm(BitTest::Bt, Size::Qword, Rax, RANGE_BIT);
|
||||
asm.alu(Alu::Sbb, Size::Qword, R11, R11);
|
||||
asm.alu_imm8(Alu::And, Size::Dword, R11, RANGE_BYTES as i8);
|
||||
}
|
||||
|
||||
/// The result of `form` on its operands, computed from the [`Cipher`] at
|
||||
/// `cipher` under the tag words at `tags` (one anchor): RAX the result, the
|
||||
/// misses' jumps with RAX the pointer and the modifier in its register, as
|
||||
/// [`super::lookup`] leaves them, and the jump taken while the key is not
|
||||
/// open.
|
||||
pub(super) fn compute(asm: &mut Asm, form: super::Form, tags: Place, cipher: Place) -> Lookup {
|
||||
use Gpr::{R8, R9, R10, R11, Rax};
|
||||
use Size::Qword;
|
||||
assert_eq!(
|
||||
tags.anchor, cipher.anchor,
|
||||
"the tag words and cipher share an anchor"
|
||||
);
|
||||
let modifier = operands(asm, form);
|
||||
debug_assert!(!matches!(modifier, R9 | R10 | R11));
|
||||
asm.place(R8, Place::new(tags.anchor, 0));
|
||||
let at = |offset: usize| i32::try_from(cipher.offset + offset).expect("a cipher field offset");
|
||||
// Every open key's tag word is above the disabled one's, and a closed
|
||||
// key's is below it.
|
||||
let word = i32::try_from(tags.offset + usize::from(form.key) * 8).expect("a tag word offset");
|
||||
asm.alu_imm32(Alu::Cmp, Qword, Mem::base(R8, word), super::DISABLED as i32);
|
||||
let unopened = asm.jcc(Cond::Be);
|
||||
let schedule = at(SCHEDULES + usize::from(form.key) * SCHEDULE * 16);
|
||||
if form.key == GENERIC_KEY {
|
||||
// The generic key is never disabled: a closed one misses.
|
||||
rounds(asm, Rax, modifier, schedule);
|
||||
asm.movq_from_xmm(Rax, 0);
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, Rax, 32);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 32);
|
||||
return Lookup {
|
||||
misses: alloc::vec![unopened],
|
||||
modifier,
|
||||
unopened: None,
|
||||
};
|
||||
}
|
||||
let data = form.key >= super::key_index(crate::block::PointerAuthenticationKey::Da);
|
||||
let domain = RANGES + usize::from(data) * 2 * RANGE_BYTES as usize;
|
||||
let range = |field: usize| Mem::indexed(R8, R11, 1, at(domain + field));
|
||||
let mut misses = Vec::new();
|
||||
if form.kind != super::AUTHENTICATED {
|
||||
range_index(asm);
|
||||
asm.mov(Qword, R10, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R10, range(EXTENSION));
|
||||
asm.alu_load(Alu::Cmp, Qword, R10, range(CANONICAL));
|
||||
let canonical = asm.jcc(Cond::E);
|
||||
// Non-canonical signing: FEAT_PAuth2 (`enhanced != 0`) completes
|
||||
// natively when TnSZ selects by bit 55 or when bit 63 matches bit 55.
|
||||
asm.alu_imm8(Alu::Cmp, Qword, range(ENHANCED), 0);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.alu_imm8(Alu::Cmp, Qword, range(SELECT_BIT63), 0);
|
||||
let select_55 = asm.jcc(Cond::E);
|
||||
asm.mov(Qword, R10, Rax);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, R10, 8);
|
||||
asm.alu(Alu::Xor, Qword, R10, Rax);
|
||||
misses.push(asm.jcc(Cond::S));
|
||||
asm.bind(select_55);
|
||||
asm.mov(Qword, R9, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R9, range(KEPT));
|
||||
asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL));
|
||||
let noncanonical_ready = asm.jmp8();
|
||||
asm.bind(canonical);
|
||||
asm.mov(Qword, R9, Rax);
|
||||
asm.bind(noncanonical_ready);
|
||||
rounds(asm, R9, modifier, schedule);
|
||||
// p ^ (pac & M) ^ signed.
|
||||
asm.movq_from_xmm(R9, 0);
|
||||
asm.alu_load(Alu::And, Qword, R9, range(FIELD));
|
||||
asm.alu_load(Alu::Xor, Qword, R9, range(SIGNED));
|
||||
asm.alu(Alu::Xor, Qword, Rax, R9);
|
||||
} else {
|
||||
// R9 = the input: (p & !E) | canonical.
|
||||
range_index(asm);
|
||||
asm.mov(Qword, R9, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R9, range(KEPT));
|
||||
asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL));
|
||||
rounds(asm, R9, modifier, schedule);
|
||||
// Authentic when (p ^ pac) & M is the range's `authenticated`.
|
||||
asm.movq_from_xmm(R10, 0);
|
||||
asm.alu(Alu::Xor, Qword, R10, Rax);
|
||||
asm.alu_load(Alu::And, Qword, R10, range(FIELD));
|
||||
asm.alu_load(Alu::Cmp, Qword, R10, range(AUTHENTICATED));
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.mov(Qword, Rax, R9);
|
||||
}
|
||||
Lookup {
|
||||
misses,
|
||||
modifier,
|
||||
unopened: Some(unopened),
|
||||
}
|
||||
}
|
||||
@@ -1,462 +1,467 @@
|
||||
//! Native completion of a TTBR0 write that switches the PE to another
|
||||
//! address space the engine and the host both keep.
|
||||
//!
|
||||
//! An MSR TTBR0 ends its block with a System exit. The thunk the engine
|
||||
//! installs over it completes a write of the value the register holds as
|
||||
//! [`super::register_read::unchanged_write_thunk`] does, and a write of
|
||||
//! another value when the PE's [`Table`] holds an [`Entry`] for that value,
|
||||
//! of the table's generation, made in the state the PE is in (its upper
|
||||
//! half's lookup context is the entry's `upper`). Where the host keeps root
|
||||
//! sets ([`Sets`]), the entry's set must also be open, of the generation
|
||||
//! the entry names and of the class of the set the current CR3 belongs to:
|
||||
//! the same rights and lower TCR fields, so the set differs from the
|
||||
//! current one in TTBR0 alone.
|
||||
//!
|
||||
//! On a hit the thunk publishes the entry's translating word where the PE
|
||||
//! publishes one (the regime and ASID other PEs' TLBIs test, as
|
||||
//! `Machine::publish_translating` does), and if that changed it and mail is
|
||||
//! then pending, takes the original exit: the engine reads the mail before
|
||||
//! the new context is used. Otherwise it writes the register, the lower
|
||||
//! half's ITLB context and salt, closes the cells a translation change
|
||||
//! closes (`closes`), moves the transition records' contexts generation
|
||||
//! (records continue only once the engine gave them contexts again), counts
|
||||
//! the switch for the engine, which settles the rest at its next exit, and
|
||||
//! loads CR3 with the target set's root of the view the current CR3 is of:
|
||||
//! in that view's PCID, without the no-flush bit while the view's stale
|
||||
//! byte is set, which it clears and counts. Where the host isolates predictions
|
||||
//! between contexts it issues IBPB and refills the return stack, as the
|
||||
//! engine's exit would. It clobbers RAX, RCX, RDX, R8, R9 and flags, which
|
||||
//! no exit keeps live.
|
||||
use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, ShiftOp, Size};
|
||||
use super::pointer::Thunk;
|
||||
use super::register_read::Written;
|
||||
use crate::{GuestAddress, Place, block::ExitKind};
|
||||
use alloc::vec::Vec;
|
||||
use core::mem::offset_of;
|
||||
|
||||
/// The views a set has a root for: four permission views, unchecked and
|
||||
/// tag-checked.
|
||||
pub const SET_ROOTS: usize = 8;
|
||||
/// The root sets a host keeps.
|
||||
pub const SETS: usize = 40;
|
||||
/// The PCID of set `s`'s view `v` is `FIRST_CONTEXT + s * SET_ROOTS + v`.
|
||||
pub const FIRST_CONTEXT: u64 = 2;
|
||||
/// CR3's no-flush bit.
|
||||
pub const KEEP_ENTRIES: u64 = 1 << 63;
|
||||
/// CR3's root address bits.
|
||||
pub const ROOT_ADDRESS: u64 = 0x000f_ffff_ffff_f000;
|
||||
|
||||
/// A host's root sets as native code reads them: set `s`'s view `v` root
|
||||
/// lies at `base + (s * SET_ROOTS + v) * 4096`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Sets {
|
||||
/// Nonzero while a native switch may move to another set.
|
||||
pub open: u64,
|
||||
pub base: u64,
|
||||
/// Nonzero while roots load in their PCIDs.
|
||||
pub tagged: u64,
|
||||
/// One more than the set a native switch moved to since the host last
|
||||
/// followed, 0 for none.
|
||||
pub switched: u64,
|
||||
/// The current set's first root, which transition records check.
|
||||
pub current: u64,
|
||||
/// CR3 loads that flushed a stale view's PCID, the host's and native
|
||||
/// code's.
|
||||
pub flushes: u64,
|
||||
/// Each set's generation, which moves whenever it is given to another
|
||||
/// context, and class: sets of one class differ in TTBR0 alone.
|
||||
pub generations: [u64; SETS],
|
||||
pub classes: [u64; SETS],
|
||||
/// Each set's views whose PCID may hold what was removed since.
|
||||
pub stale: [u8; SETS * SET_ROOTS],
|
||||
}
|
||||
|
||||
impl Default for Sets {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
open: 0,
|
||||
base: 0,
|
||||
tagged: 0,
|
||||
switched: 0,
|
||||
current: 0,
|
||||
flushes: 0,
|
||||
generations: [0; SETS],
|
||||
classes: [0; SETS],
|
||||
stale: [1; SETS * SET_ROOTS],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries a [`Table`] holds.
|
||||
pub const ENTRIES: usize = 8;
|
||||
|
||||
/// One TTBR0 value a native switch may write.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Entry {
|
||||
/// The table's generation it holds in; 0 never does.
|
||||
pub generation: u64,
|
||||
/// TTBR0 as the register takes it.
|
||||
pub value: u64,
|
||||
/// The upper half's lookup context (`ChainControl::contexts[1]`) it
|
||||
/// holds under, which a TTBR0 write leaves.
|
||||
pub upper: u64,
|
||||
/// The lower half's lookup context and its salt after the write.
|
||||
pub lower: u64,
|
||||
pub salt: u64,
|
||||
/// The translating word to publish.
|
||||
pub translating: u64,
|
||||
/// The host's set of the context and its generation.
|
||||
pub set: u64,
|
||||
pub set_generation: u64,
|
||||
}
|
||||
|
||||
/// A PE's switch entries. Tables are equal where they hold the same
|
||||
/// entries and words, whatever generation they count.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Table {
|
||||
/// Starts at 1.
|
||||
pub generation: u64,
|
||||
/// Native switches since the engine last took them.
|
||||
pub switches: u64,
|
||||
/// The host's [`Sets`], 0 where it keeps none.
|
||||
pub sets: u64,
|
||||
/// The PE's published translating word (32 bits) and its pending-mail
|
||||
/// byte, both 0 where it publishes none.
|
||||
pub translating: u64,
|
||||
pub pending: u64,
|
||||
/// The entry the next one replaces (the engine's alone).
|
||||
pub next: u64,
|
||||
pub entries: [Entry; ENTRIES],
|
||||
}
|
||||
|
||||
impl Default for Table {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
generation: 1,
|
||||
switches: 0,
|
||||
sets: 0,
|
||||
translating: 0,
|
||||
pending: 0,
|
||||
next: 0,
|
||||
entries: [Entry::default(); ENTRIES],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Table {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.switches, self.sets, self.translating, self.pending)
|
||||
== (other.switches, other.sets, other.translating, other.pending)
|
||||
&& self.held().eq(other.held())
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Table {}
|
||||
|
||||
impl Table {
|
||||
/// Each entry slot's entry if it holds, without its generation.
|
||||
fn held(&self) -> impl Iterator<Item = Option<Entry>> + '_ {
|
||||
self.entries.iter().map(|entry| {
|
||||
(entry.generation == self.generation).then_some(Entry {
|
||||
generation: 0,
|
||||
..*entry
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// No entry holds any more.
|
||||
pub fn forget(&mut self) {
|
||||
self.generation += 1;
|
||||
}
|
||||
|
||||
/// Hold `entry` from now on, in place of one for the same value or the
|
||||
/// next in turn.
|
||||
pub fn keep(&mut self, mut entry: Entry) {
|
||||
entry.generation = self.generation;
|
||||
let index = self
|
||||
.entries
|
||||
.iter()
|
||||
.position(|held| held.value == entry.value && held.generation == self.generation)
|
||||
.unwrap_or_else(|| {
|
||||
let index = self.next as usize % ENTRIES;
|
||||
self.next = self.next.wrapping_add(1);
|
||||
index
|
||||
});
|
||||
self.entries[index] = entry;
|
||||
}
|
||||
|
||||
/// The native switches since the last call, which it clears.
|
||||
pub fn take_switches(&mut self) -> u64 {
|
||||
core::mem::take(&mut self.switches)
|
||||
}
|
||||
}
|
||||
|
||||
/// How the thunk reads and loads CR3: the register, or for tests the word
|
||||
/// at an address that stands for it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Cr3 {
|
||||
Register,
|
||||
Word(u64),
|
||||
}
|
||||
|
||||
/// Where a switch thunk finds what it reads and writes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Places {
|
||||
/// The PE's [`Table`].
|
||||
pub table: Place,
|
||||
/// `ChainControl::contexts` and `salts`.
|
||||
pub contexts: Place,
|
||||
pub salts: Place,
|
||||
/// The transition table's contexts generation.
|
||||
pub contexts_generation: Place,
|
||||
/// The `readable` words of cells the switch closes.
|
||||
pub closes: Vec<Place>,
|
||||
/// Whether the table's sets are loaded through CR3; without, the thunk
|
||||
/// switches only where the table names no sets.
|
||||
pub cr3: Option<Cr3>,
|
||||
/// Issue IBPB and refill the return stack.
|
||||
pub isolate: bool,
|
||||
}
|
||||
|
||||
/// IA32_PRED_CMD.
|
||||
const PRED_CMD: i32 = 0x49;
|
||||
/// The return stack entries a refill writes, as the host's isolation does.
|
||||
const RETURN_STACK_ENTRIES: usize = 32;
|
||||
const XCHG_RCX_EAX: [u8; 2] = [0x87, 0x01];
|
||||
const MOV_R9_CR3: [u8; 4] = [0x41, 0x0f, 0x20, 0xd9];
|
||||
const MOV_CR3_RAX: [u8; 3] = [0x0f, 0x22, 0xd8];
|
||||
const WRMSR: [u8; 2] = [0x0f, 0x30];
|
||||
const LFENCE: [u8; 3] = [0x0f, 0xae, 0xe8];
|
||||
/// CALL to the next instruction but one, over an INT3.
|
||||
const REFILL_CALL: [u8; 6] = [0xe8, 0x01, 0x00, 0x00, 0x00, 0xcc];
|
||||
|
||||
/// The thunk completing `MSR TTBR0, Xt` at `pc`, whose register storage the
|
||||
/// `value` of the cell at `cell` points at, taking `written` of Xt.
|
||||
pub fn switch_thunk(
|
||||
pc: GuestAddress,
|
||||
rt: u8,
|
||||
cell: Place,
|
||||
written: Written,
|
||||
places: &Places,
|
||||
) -> Thunk {
|
||||
use Gpr::{R8, R9, Rax, Rcx, Rdx};
|
||||
use Size::{Byte, Dword, Qword};
|
||||
let mut code = Vec::with_capacity(768);
|
||||
let mut asm = Asm::new(&mut code);
|
||||
let mut misses: Vec<Patch> = Vec::new();
|
||||
let entry = |field: usize| Mem::base(R8, field as i32);
|
||||
let table = |field: usize| Mem::base(Rdx, field as i32);
|
||||
// The cell, and a write of the value the register holds.
|
||||
asm.place(Rax, cell);
|
||||
asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, 8));
|
||||
written.apply(&mut asm, rt);
|
||||
asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0));
|
||||
let unchanged = asm.jcc(Cond::E);
|
||||
// The entry for the value, of the table's generation.
|
||||
asm.place(Rdx, places.table);
|
||||
asm.mov_load(Qword, R9, table(offset_of!(Table, generation)));
|
||||
let mut hits = Vec::new();
|
||||
for index in 0..ENTRIES {
|
||||
let at = offset_of!(Table, entries) + index * size_of::<Entry>();
|
||||
asm.alu_load(Alu::Cmp, Qword, Rax, table(at + offset_of!(Entry, value)));
|
||||
let other = asm.jcc8(Cond::Ne);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
R9,
|
||||
table(at + offset_of!(Entry, generation)),
|
||||
);
|
||||
let old = asm.jcc8(Cond::Ne);
|
||||
asm.lea(Qword, R8, table(at));
|
||||
hits.push(asm.jmp());
|
||||
asm.bind(other);
|
||||
asm.bind(old);
|
||||
}
|
||||
misses.push(asm.jmp());
|
||||
for hit in hits {
|
||||
asm.bind(hit);
|
||||
}
|
||||
// Made in this state: the upper half's context is the entry's.
|
||||
asm.place(Rcx, places.contexts);
|
||||
asm.mov_load(Qword, Rcx, Mem::base(Rcx, 8));
|
||||
asm.alu_load(Alu::Cmp, Qword, Rcx, entry(offset_of!(Entry, upper)));
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
// The host's sets: open, the entry's set of its generation and of the
|
||||
// current set's class. R9 keeps the current root's index.
|
||||
let sets = |field: usize| Mem::base(Rdx, field as i32);
|
||||
if let Some(cr3) = places.cr3 {
|
||||
asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets)));
|
||||
asm.test(Qword, Rdx, Rdx);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, open)), 0);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set)));
|
||||
asm.alu_imm32(Alu::Cmp, Qword, Rcx, SETS as i32);
|
||||
misses.push(asm.jcc(Cond::Ae));
|
||||
asm.mov_load(
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, generations) as i32),
|
||||
);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
Rax,
|
||||
entry(offset_of!(Entry, set_generation)),
|
||||
);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
read_cr3(&mut asm, cr3);
|
||||
asm.mov_imm64(Rax, ROOT_ADDRESS);
|
||||
asm.alu(Alu::And, Qword, R9, Rax);
|
||||
asm.alu_load(Alu::Sub, Qword, R9, sets(offset_of!(Sets, base)));
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, R9, 12);
|
||||
asm.alu_imm32(Alu::Cmp, Qword, R9, (SETS * SET_ROOTS) as i32);
|
||||
misses.push(asm.jcc(Cond::Ae));
|
||||
asm.mov(Qword, Rax, R9);
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, Rax, SET_ROOTS.trailing_zeros() as u8);
|
||||
asm.mov_load(
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rax, 8, offset_of!(Sets, classes) as i32),
|
||||
);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, classes) as i32),
|
||||
);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.place(Rdx, places.table);
|
||||
} else {
|
||||
asm.alu_imm8(Alu::Cmp, Qword, table(offset_of!(Table, sets)), 0);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
}
|
||||
// Publish the translating word; mail pending after a change goes to
|
||||
// the engine first.
|
||||
asm.mov_load(Qword, Rcx, table(offset_of!(Table, translating)));
|
||||
asm.test(Qword, Rcx, Rcx);
|
||||
let unpublished = asm.jcc(Cond::E);
|
||||
asm.mov_load(Dword, Rax, entry(offset_of!(Entry, translating)));
|
||||
asm.alu_load(Alu::Cmp, Dword, Rax, Mem::base(Rcx, 0));
|
||||
let published = asm.jcc(Cond::E);
|
||||
asm.fixed(&XCHG_RCX_EAX);
|
||||
asm.mov_load(Qword, Rcx, table(offset_of!(Table, pending)));
|
||||
asm.movzx(Dword, Rax, Byte, Mem::base(Rcx, 0));
|
||||
asm.test(Dword, Rax, Rax);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.bind(unpublished);
|
||||
asm.bind(published);
|
||||
// The register, the lower half's context and salt.
|
||||
asm.place(Rcx, cell);
|
||||
asm.mov_load(Qword, Rcx, Mem::base_disp8(Rcx, 8));
|
||||
asm.mov_load(Qword, Rax, entry(offset_of!(Entry, value)));
|
||||
asm.mov_store(Qword, Mem::base(Rcx, 0), Rax);
|
||||
asm.place(Rcx, places.contexts);
|
||||
asm.mov_load(Qword, Rax, entry(offset_of!(Entry, lower)));
|
||||
asm.mov_store(Qword, Mem::base(Rcx, 0), Rax);
|
||||
asm.place(Rcx, places.salts);
|
||||
asm.mov_load(Dword, Rax, entry(offset_of!(Entry, salt)));
|
||||
asm.mov_store(Dword, Mem::base(Rcx, 0), Rax);
|
||||
for &close in &places.closes {
|
||||
asm.place(Rcx, close);
|
||||
asm.mov_rm_imm32(Qword, Mem::base(Rcx, 0), 0);
|
||||
}
|
||||
asm.place(Rcx, places.contexts_generation);
|
||||
asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1);
|
||||
asm.alu_imm8(Alu::Add, Qword, table(offset_of!(Table, switches)), 1);
|
||||
if let Some(cr3) = places.cr3 {
|
||||
// The target root's index: the entry's set, the current view.
|
||||
asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets)));
|
||||
asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set)));
|
||||
asm.lea(Qword, Rax, Mem::base(Rcx, 1));
|
||||
asm.mov_store(Qword, sets(offset_of!(Sets, switched)), Rax);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rcx, SET_ROOTS.trailing_zeros() as u8);
|
||||
asm.alu_imm8(Alu::And, Qword, R9, (SET_ROOTS - 1) as i8);
|
||||
asm.alu(Alu::Or, Qword, Rcx, R9);
|
||||
// The set's first root, then the view's.
|
||||
asm.mov(Qword, Rax, Rcx);
|
||||
asm.alu_imm8(Alu::And, Qword, Rax, !((SET_ROOTS - 1) as i8));
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12);
|
||||
asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base)));
|
||||
asm.mov_store(Qword, sets(offset_of!(Sets, current)), Rax);
|
||||
asm.mov(Qword, Rax, Rcx);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12);
|
||||
asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base)));
|
||||
asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, tagged)), 0);
|
||||
let untagged = asm.jcc(Cond::E);
|
||||
asm.lea(Qword, R9, Mem::base(Rcx, FIRST_CONTEXT as i32));
|
||||
asm.alu(Alu::Or, Qword, Rax, R9);
|
||||
let stale = Mem::indexed(Rdx, Rcx, 1, offset_of!(Sets, stale) as i32);
|
||||
asm.movzx(Dword, R9, Byte, stale);
|
||||
asm.test(Dword, R9, R9);
|
||||
let flush = asm.jcc8(Cond::Ne);
|
||||
asm.mov_imm64(R9, KEEP_ENTRIES);
|
||||
asm.alu(Alu::Or, Qword, Rax, R9);
|
||||
let kept = asm.jmp8();
|
||||
asm.bind(flush);
|
||||
asm.alu_imm8(Alu::Add, Qword, sets(offset_of!(Sets, flushes)), 1);
|
||||
asm.alu(Alu::Xor, Dword, R9, R9);
|
||||
asm.mov_store(Byte, stale, R9);
|
||||
asm.bind(kept);
|
||||
asm.bind(untagged);
|
||||
load_cr3(&mut asm, cr3);
|
||||
}
|
||||
if places.isolate {
|
||||
asm.mov_rm_imm32(Dword, Rcx, PRED_CMD);
|
||||
asm.mov_rm_imm32(Dword, Rax, 1);
|
||||
asm.alu(Alu::Xor, Dword, Rdx, Rdx);
|
||||
asm.fixed(&WRMSR);
|
||||
for _ in 0..RETURN_STACK_ENTRIES {
|
||||
asm.fixed(&REFILL_CALL);
|
||||
}
|
||||
asm.alu_imm32(Alu::Add, Qword, Gpr::Rsp, (RETURN_STACK_ENTRIES * 8) as i32);
|
||||
asm.fixed(&LFENCE);
|
||||
}
|
||||
asm.bind(unchanged);
|
||||
let next = code.len();
|
||||
let mut asm = Asm::new(&mut code);
|
||||
super::block::direct_exit_with(
|
||||
&mut asm,
|
||||
GuestAddress(pc.0.wrapping_add(4)),
|
||||
ExitKind::Fallthrough,
|
||||
);
|
||||
for miss in misses {
|
||||
asm.bind(miss);
|
||||
}
|
||||
super::block::direct_exit_with(&mut asm, pc, ExitKind::System);
|
||||
Thunk::new(code, Some(next), None)
|
||||
}
|
||||
|
||||
/// R9 = CR3.
|
||||
fn read_cr3(asm: &mut Asm<'_>, cr3: Cr3) {
|
||||
match cr3 {
|
||||
Cr3::Register => asm.fixed(&MOV_R9_CR3),
|
||||
Cr3::Word(address) => {
|
||||
asm.mov_imm64(Gpr::R9, address);
|
||||
asm.mov_load(Size::Qword, Gpr::R9, Mem::base(Gpr::R9, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CR3 = RAX. Clobbers RCX for a word.
|
||||
fn load_cr3(asm: &mut Asm<'_>, cr3: Cr3) {
|
||||
match cr3 {
|
||||
Cr3::Register => asm.fixed(&MOV_CR3_RAX),
|
||||
Cr3::Word(address) => {
|
||||
asm.mov_imm64(Gpr::Rcx, address);
|
||||
asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
test,
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "macos", target_os = "linux")
|
||||
))]
|
||||
mod tests;
|
||||
//! Native completion of a TTBR0 write that switches the PE to another
|
||||
//! address space the engine and the host both keep.
|
||||
//!
|
||||
//! An MSR TTBR0 ends its block with a System exit. The thunk the engine
|
||||
//! installs over it completes a write of the value the register holds as
|
||||
//! [`super::register_read::unchanged_write_thunk`] does, and a write of
|
||||
//! another value when the PE's [`Table`] holds an [`Entry`] for that value,
|
||||
//! of the table's generation, made in the state the PE is in (its upper
|
||||
//! half's lookup context is the entry's `upper`). Where the host keeps root
|
||||
//! sets ([`Sets`]), the entry's set must also be open, of the generation
|
||||
//! the entry names and of the class of the set the current CR3 belongs to:
|
||||
//! the same rights and lower TCR fields, so the set differs from the
|
||||
//! current one in TTBR0 alone.
|
||||
//!
|
||||
//! On a hit the thunk publishes the entry's translating word where the PE
|
||||
//! publishes one (the regime and ASID other PEs' TLBIs test, as
|
||||
//! `Machine::publish_translating` does), and if that changed it and mail is
|
||||
//! then pending, takes the original exit: the engine reads the mail before
|
||||
//! the new context is used. Otherwise it writes the register, the lower
|
||||
//! half's ITLB context and salt, closes the cells a translation change
|
||||
//! closes (`closes`), moves the transition records' contexts generation
|
||||
//! (records continue only once the engine gave them contexts again), counts
|
||||
//! the switch for the engine, which settles the rest at its next exit, and
|
||||
//! loads CR3 with the target set's root of the view the current CR3 is of:
|
||||
//! in that view's PCID, without the no-flush bit while the view's stale
|
||||
//! byte is set, which it clears and counts. Where the host isolates predictions
|
||||
//! between contexts it issues IBPB and refills the return stack, as the
|
||||
//! engine's exit would. It clobbers RAX, RCX, RDX, R8, R9 and flags, which
|
||||
//! no exit keeps live.
|
||||
use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, ShiftOp, Size};
|
||||
use super::pointer::Thunk;
|
||||
use super::register_read::Written;
|
||||
use crate::{GuestAddress, Place, block::ExitKind};
|
||||
use alloc::vec::Vec;
|
||||
use core::mem::offset_of;
|
||||
|
||||
/// The views a set has a root for: four permission views, unchecked and
|
||||
/// tag-checked.
|
||||
pub const SET_ROOTS: usize = 8;
|
||||
/// The root sets a host keeps.
|
||||
pub const SETS: usize = 40;
|
||||
/// The PCID of set `s`'s view `v` is `FIRST_CONTEXT + s * SET_ROOTS + v`.
|
||||
pub const FIRST_CONTEXT: u64 = 2;
|
||||
/// CR3's no-flush bit.
|
||||
pub const KEEP_ENTRIES: u64 = 1 << 63;
|
||||
/// CR3's root address bits.
|
||||
pub const ROOT_ADDRESS: u64 = 0x000f_ffff_ffff_f000;
|
||||
|
||||
/// A host's root sets as native code reads them: set `s`'s view `v` root
|
||||
/// lies at `base + (s * SET_ROOTS + v) * 4096`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Sets {
|
||||
/// Nonzero while a native switch may move to another set.
|
||||
pub open: u64,
|
||||
pub base: u64,
|
||||
/// Nonzero while roots load in their PCIDs.
|
||||
pub tagged: u64,
|
||||
/// One more than the set a native switch moved to since the host last
|
||||
/// followed, 0 for none.
|
||||
pub switched: u64,
|
||||
/// The current set's first root, which transition records check.
|
||||
pub current: u64,
|
||||
/// CR3 loads that flushed a stale view's PCID, the host's and native
|
||||
/// code's.
|
||||
pub flushes: u64,
|
||||
/// Each set's generation, which moves whenever it is given to another
|
||||
/// context, and class: sets of one class differ in TTBR0 alone.
|
||||
pub generations: [u64; SETS],
|
||||
pub classes: [u64; SETS],
|
||||
/// Each set's views whose PCID may hold what was removed since.
|
||||
pub stale: [u8; SETS * SET_ROOTS],
|
||||
}
|
||||
|
||||
impl Default for Sets {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
open: 0,
|
||||
base: 0,
|
||||
tagged: 0,
|
||||
switched: 0,
|
||||
current: 0,
|
||||
flushes: 0,
|
||||
generations: [0; SETS],
|
||||
classes: [0; SETS],
|
||||
stale: [1; SETS * SET_ROOTS],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries a [`Table`] holds.
|
||||
pub const ENTRIES: usize = 32;
|
||||
|
||||
/// One TTBR0 value a native switch may write.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Entry {
|
||||
/// The table's generation it holds in; 0 never does.
|
||||
pub generation: u64,
|
||||
/// TTBR0 as the register takes it.
|
||||
pub value: u64,
|
||||
/// The upper half's lookup context (`ChainControl::contexts[1]`) it
|
||||
/// holds under, which a TTBR0 write leaves.
|
||||
pub upper: u64,
|
||||
/// The lower half's lookup context and its salt after the write.
|
||||
pub lower: u64,
|
||||
pub salt: u64,
|
||||
/// The translating word to publish.
|
||||
pub translating: u64,
|
||||
/// The host's set of the context and its generation.
|
||||
pub set: u64,
|
||||
pub set_generation: u64,
|
||||
}
|
||||
|
||||
/// A PE's switch entries. Tables are equal where they hold the same
|
||||
/// entries and words, whatever generation they count.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Table {
|
||||
/// Starts at 1.
|
||||
pub generation: u64,
|
||||
/// Native switches since the engine last took them.
|
||||
pub switches: u64,
|
||||
/// The host's [`Sets`], 0 where it keeps none.
|
||||
pub sets: u64,
|
||||
/// The PE's published translating word (32 bits) and its pending-mail
|
||||
/// byte, both 0 where it publishes none.
|
||||
pub translating: u64,
|
||||
pub pending: u64,
|
||||
/// The entry the next one replaces (the engine's alone).
|
||||
pub next: u64,
|
||||
pub entries: [Entry; ENTRIES],
|
||||
}
|
||||
|
||||
impl Default for Table {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
generation: 1,
|
||||
switches: 0,
|
||||
sets: 0,
|
||||
translating: 0,
|
||||
pending: 0,
|
||||
next: 0,
|
||||
entries: [Entry::default(); ENTRIES],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Table {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.switches, self.sets, self.translating, self.pending)
|
||||
== (other.switches, other.sets, other.translating, other.pending)
|
||||
&& self.held().eq(other.held())
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Table {}
|
||||
|
||||
impl Table {
|
||||
/// Each entry slot's entry if it holds, without its generation.
|
||||
fn held(&self) -> impl Iterator<Item = Option<Entry>> + '_ {
|
||||
self.entries.iter().map(|entry| {
|
||||
(entry.generation == self.generation).then_some(Entry {
|
||||
generation: 0,
|
||||
..*entry
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// No entry holds any more.
|
||||
pub fn forget(&mut self) {
|
||||
self.generation += 1;
|
||||
}
|
||||
|
||||
/// Hold `entry` from now on, in place of one for the same value or the
|
||||
/// next in turn.
|
||||
pub fn keep(&mut self, mut entry: Entry) {
|
||||
entry.generation = self.generation;
|
||||
let index = self
|
||||
.entries
|
||||
.iter()
|
||||
.position(|held| held.value == entry.value && held.generation == self.generation)
|
||||
.unwrap_or_else(|| {
|
||||
let index = self.next as usize % ENTRIES;
|
||||
self.next = self.next.wrapping_add(1);
|
||||
index
|
||||
});
|
||||
self.entries[index] = entry;
|
||||
}
|
||||
|
||||
/// The native switches since the last call, which it clears.
|
||||
pub fn take_switches(&mut self) -> u64 {
|
||||
core::mem::take(&mut self.switches)
|
||||
}
|
||||
}
|
||||
|
||||
/// How the thunk reads and loads CR3: the register, or for tests the word
|
||||
/// at an address that stands for it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Cr3 {
|
||||
Register,
|
||||
Word(u64),
|
||||
}
|
||||
|
||||
/// Where a switch thunk finds what it reads and writes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Places {
|
||||
/// The PE's [`Table`].
|
||||
pub table: Place,
|
||||
/// `ChainControl::contexts`, `moves` and `salts`.
|
||||
pub contexts: Place,
|
||||
pub moves: Place,
|
||||
pub salts: Place,
|
||||
/// The transition table's contexts generation.
|
||||
pub contexts_generation: Place,
|
||||
/// The `readable` words of cells the switch closes.
|
||||
pub closes: Vec<Place>,
|
||||
/// Whether the table's sets are loaded through CR3; without, the thunk
|
||||
/// switches only where the table names no sets.
|
||||
pub cr3: Option<Cr3>,
|
||||
/// Issue IBPB and refill the return stack.
|
||||
pub isolate: bool,
|
||||
}
|
||||
|
||||
/// IA32_PRED_CMD.
|
||||
const PRED_CMD: i32 = 0x49;
|
||||
/// The return stack entries a refill writes, as the host's isolation does.
|
||||
const RETURN_STACK_ENTRIES: usize = 32;
|
||||
const XCHG_RCX_EAX: [u8; 2] = [0x87, 0x01];
|
||||
const MOV_R9_CR3: [u8; 4] = [0x41, 0x0f, 0x20, 0xd9];
|
||||
const MOV_CR3_RAX: [u8; 3] = [0x0f, 0x22, 0xd8];
|
||||
const WRMSR: [u8; 2] = [0x0f, 0x30];
|
||||
const LFENCE: [u8; 3] = [0x0f, 0xae, 0xe8];
|
||||
/// CALL to the next instruction but one, over an INT3.
|
||||
const REFILL_CALL: [u8; 6] = [0xe8, 0x01, 0x00, 0x00, 0x00, 0xcc];
|
||||
|
||||
/// The thunk completing `MSR TTBR0, Xt` at `pc`, whose register storage the
|
||||
/// `value` of the cell at `cell` points at, taking `written` of Xt.
|
||||
pub fn switch_thunk(
|
||||
pc: GuestAddress,
|
||||
rt: u8,
|
||||
cell: Place,
|
||||
written: Written,
|
||||
places: &Places,
|
||||
) -> Thunk {
|
||||
use Gpr::{R8, R9, Rax, Rcx, Rdx};
|
||||
use Size::{Byte, Dword, Qword};
|
||||
let mut code = Vec::with_capacity(768);
|
||||
let mut asm = Asm::new(&mut code);
|
||||
let mut misses: Vec<Patch> = Vec::new();
|
||||
let entry = |field: usize| Mem::base(R8, field as i32);
|
||||
let table = |field: usize| Mem::base(Rdx, field as i32);
|
||||
// The cell, and a write of the value the register holds.
|
||||
asm.place(Rax, cell);
|
||||
asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, 8));
|
||||
written.apply(&mut asm, rt);
|
||||
asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0));
|
||||
let unchanged = asm.jcc(Cond::E);
|
||||
// The entry for the value, of the table's generation.
|
||||
asm.place(Rdx, places.table);
|
||||
asm.mov_load(Qword, R9, table(offset_of!(Table, generation)));
|
||||
asm.lea(Qword, R8, table(offset_of!(Table, entries)));
|
||||
asm.lea(
|
||||
Qword,
|
||||
Rcx,
|
||||
table(offset_of!(Table, entries) + ENTRIES * size_of::<Entry>()),
|
||||
);
|
||||
let search = asm.len();
|
||||
asm.alu_load(Alu::Cmp, Qword, Rax, entry(offset_of!(Entry, value)));
|
||||
let other = asm.jcc8(Cond::Ne);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
R9,
|
||||
entry(offset_of!(Entry, generation)),
|
||||
);
|
||||
let hit = asm.jcc8(Cond::E);
|
||||
asm.bind(other);
|
||||
asm.alu_imm8(Alu::Add, Qword, R8, size_of::<Entry>() as i8);
|
||||
asm.alu(Alu::Cmp, Qword, R8, Rcx);
|
||||
let next_entry = asm.jcc8(Cond::B);
|
||||
asm.bind_back(next_entry, search);
|
||||
misses.push(asm.jmp());
|
||||
asm.bind(hit);
|
||||
// Made in this state: the upper half's context is the entry's.
|
||||
asm.place(Rcx, places.contexts);
|
||||
asm.mov_load(Qword, Rcx, Mem::base(Rcx, 8));
|
||||
asm.alu_load(Alu::Cmp, Qword, Rcx, entry(offset_of!(Entry, upper)));
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
// The host's sets: open, the entry's set of its generation and of the
|
||||
// current set's class. R9 keeps the current root's index.
|
||||
let sets = |field: usize| Mem::base(Rdx, field as i32);
|
||||
if let Some(cr3) = places.cr3 {
|
||||
asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets)));
|
||||
asm.test(Qword, Rdx, Rdx);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, open)), 0);
|
||||
misses.push(asm.jcc(Cond::E));
|
||||
asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set)));
|
||||
asm.alu_imm32(Alu::Cmp, Qword, Rcx, SETS as i32);
|
||||
misses.push(asm.jcc(Cond::Ae));
|
||||
asm.mov_load(
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, generations) as i32),
|
||||
);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
Rax,
|
||||
entry(offset_of!(Entry, set_generation)),
|
||||
);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
read_cr3(&mut asm, cr3);
|
||||
asm.mov_imm64(Rax, ROOT_ADDRESS);
|
||||
asm.alu(Alu::And, Qword, R9, Rax);
|
||||
asm.alu_load(Alu::Sub, Qword, R9, sets(offset_of!(Sets, base)));
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, R9, 12);
|
||||
asm.alu_imm32(Alu::Cmp, Qword, R9, (SETS * SET_ROOTS) as i32);
|
||||
misses.push(asm.jcc(Cond::Ae));
|
||||
asm.mov(Qword, Rax, R9);
|
||||
asm.shift_imm(ShiftOp::Shr, Qword, Rax, SET_ROOTS.trailing_zeros() as u8);
|
||||
asm.mov_load(
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rax, 8, offset_of!(Sets, classes) as i32),
|
||||
);
|
||||
asm.alu_load(
|
||||
Alu::Cmp,
|
||||
Qword,
|
||||
Rax,
|
||||
Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, classes) as i32),
|
||||
);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.place(Rdx, places.table);
|
||||
} else {
|
||||
asm.alu_imm8(Alu::Cmp, Qword, table(offset_of!(Table, sets)), 0);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
}
|
||||
// Publish the translating word; mail pending after a change goes to
|
||||
// the engine first.
|
||||
asm.mov_load(Qword, Rcx, table(offset_of!(Table, translating)));
|
||||
asm.test(Qword, Rcx, Rcx);
|
||||
let unpublished = asm.jcc(Cond::E);
|
||||
asm.mov_load(Dword, Rax, entry(offset_of!(Entry, translating)));
|
||||
asm.alu_load(Alu::Cmp, Dword, Rax, Mem::base(Rcx, 0));
|
||||
let published = asm.jcc(Cond::E);
|
||||
asm.fixed(&XCHG_RCX_EAX);
|
||||
asm.mov_load(Qword, Rcx, table(offset_of!(Table, pending)));
|
||||
asm.movzx(Dword, Rax, Byte, Mem::base(Rcx, 0));
|
||||
asm.test(Dword, Rax, Rax);
|
||||
misses.push(asm.jcc(Cond::Ne));
|
||||
asm.bind(unpublished);
|
||||
asm.bind(published);
|
||||
// The register, the lower half's context and salt.
|
||||
asm.place(Rcx, cell);
|
||||
asm.mov_load(Qword, Rcx, Mem::base_disp8(Rcx, 8));
|
||||
asm.mov_load(Qword, Rax, entry(offset_of!(Entry, value)));
|
||||
asm.mov_store(Qword, Mem::base(Rcx, 0), Rax);
|
||||
asm.place(Rcx, places.contexts);
|
||||
asm.mov_load(Qword, Rax, entry(offset_of!(Entry, lower)));
|
||||
asm.mov_store(Qword, Mem::base(Rcx, 0), Rax);
|
||||
asm.place(Rcx, places.moves);
|
||||
asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1);
|
||||
asm.place(Rcx, places.salts);
|
||||
asm.mov_load(Dword, Rax, entry(offset_of!(Entry, salt)));
|
||||
asm.mov_store(Dword, Mem::base(Rcx, 0), Rax);
|
||||
for &close in &places.closes {
|
||||
asm.place(Rcx, close);
|
||||
asm.mov_rm_imm32(Qword, Mem::base(Rcx, 0), 0);
|
||||
}
|
||||
asm.place(Rcx, places.contexts_generation);
|
||||
asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1);
|
||||
asm.alu_imm8(Alu::Add, Qword, table(offset_of!(Table, switches)), 1);
|
||||
if let Some(cr3) = places.cr3 {
|
||||
// The target root's index: the entry's set, the current view.
|
||||
asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets)));
|
||||
asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set)));
|
||||
asm.lea(Qword, Rax, Mem::base(Rcx, 1));
|
||||
asm.mov_store(Qword, sets(offset_of!(Sets, switched)), Rax);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rcx, SET_ROOTS.trailing_zeros() as u8);
|
||||
asm.alu_imm8(Alu::And, Qword, R9, (SET_ROOTS - 1) as i8);
|
||||
asm.alu(Alu::Or, Qword, Rcx, R9);
|
||||
// The set's first root, then the view's.
|
||||
asm.mov(Qword, Rax, Rcx);
|
||||
asm.alu_imm8(Alu::And, Qword, Rax, !((SET_ROOTS - 1) as i8));
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12);
|
||||
asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base)));
|
||||
asm.mov_store(Qword, sets(offset_of!(Sets, current)), Rax);
|
||||
asm.mov(Qword, Rax, Rcx);
|
||||
asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12);
|
||||
asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base)));
|
||||
asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, tagged)), 0);
|
||||
let untagged = asm.jcc(Cond::E);
|
||||
asm.lea(Qword, R9, Mem::base(Rcx, FIRST_CONTEXT as i32));
|
||||
asm.alu(Alu::Or, Qword, Rax, R9);
|
||||
let stale = Mem::indexed(Rdx, Rcx, 1, offset_of!(Sets, stale) as i32);
|
||||
asm.movzx(Dword, R9, Byte, stale);
|
||||
asm.test(Dword, R9, R9);
|
||||
let flush = asm.jcc8(Cond::Ne);
|
||||
asm.mov_imm64(R9, KEEP_ENTRIES);
|
||||
asm.alu(Alu::Or, Qword, Rax, R9);
|
||||
let kept = asm.jmp8();
|
||||
asm.bind(flush);
|
||||
asm.alu_imm8(Alu::Add, Qword, sets(offset_of!(Sets, flushes)), 1);
|
||||
asm.alu(Alu::Xor, Dword, R9, R9);
|
||||
asm.mov_store(Byte, stale, R9);
|
||||
asm.bind(kept);
|
||||
asm.bind(untagged);
|
||||
load_cr3(&mut asm, cr3);
|
||||
}
|
||||
if places.isolate {
|
||||
asm.mov_rm_imm32(Dword, Rcx, PRED_CMD);
|
||||
asm.mov_rm_imm32(Dword, Rax, 1);
|
||||
asm.alu(Alu::Xor, Dword, Rdx, Rdx);
|
||||
asm.fixed(&WRMSR);
|
||||
for _ in 0..RETURN_STACK_ENTRIES {
|
||||
asm.fixed(&REFILL_CALL);
|
||||
}
|
||||
asm.alu_imm32(Alu::Add, Qword, Gpr::Rsp, (RETURN_STACK_ENTRIES * 8) as i32);
|
||||
asm.fixed(&LFENCE);
|
||||
}
|
||||
asm.bind(unchanged);
|
||||
let next = code.len();
|
||||
let mut asm = Asm::new(&mut code);
|
||||
super::block::direct_exit_with(
|
||||
&mut asm,
|
||||
GuestAddress(pc.0.wrapping_add(4)),
|
||||
ExitKind::Fallthrough,
|
||||
);
|
||||
for miss in misses {
|
||||
asm.bind(miss);
|
||||
}
|
||||
super::block::direct_exit_with(&mut asm, pc, ExitKind::System);
|
||||
Thunk::new(code, Some(next), None)
|
||||
}
|
||||
|
||||
/// R9 = CR3.
|
||||
fn read_cr3(asm: &mut Asm<'_>, cr3: Cr3) {
|
||||
match cr3 {
|
||||
Cr3::Register => asm.fixed(&MOV_R9_CR3),
|
||||
Cr3::Word(address) => {
|
||||
asm.mov_imm64(Gpr::R9, address);
|
||||
asm.mov_load(Size::Qword, Gpr::R9, Mem::base(Gpr::R9, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CR3 = RAX. Clobbers RCX for a word.
|
||||
fn load_cr3(asm: &mut Asm<'_>, cr3: Cr3) {
|
||||
match cr3 {
|
||||
Cr3::Register => asm.fixed(&MOV_CR3_RAX),
|
||||
Cr3::Word(address) => {
|
||||
asm.mov_imm64(Gpr::Rcx, address);
|
||||
asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
test,
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "macos", target_os = "linux")
|
||||
))]
|
||||
mod tests;
|
||||
@@ -1,336 +1,354 @@
|
||||
use super::*;
|
||||
use crate::{Anchor, GuestState, x86_64::register_read::Cell};
|
||||
|
||||
const PC: GuestAddress = GuestAddress(0x4000);
|
||||
const RT: u8 = 3;
|
||||
const OLD: u64 = 1 << 48 | 0x8000;
|
||||
const NEW: u64 = 2 << 48 | 0xc000;
|
||||
const UPPER: u64 = 0x77;
|
||||
const BASE: u64 = 0x10_0000;
|
||||
|
||||
/// Everything a switch thunk reads and writes, at the Mirrors anchor.
|
||||
#[repr(C)]
|
||||
struct World {
|
||||
cell: Cell,
|
||||
register: u64,
|
||||
table: Table,
|
||||
contexts: [u64; 2],
|
||||
salts: [u32; 2],
|
||||
contexts_generation: u64,
|
||||
closes: [u64; 2],
|
||||
cr3: u64,
|
||||
translating: u32,
|
||||
pending: u8,
|
||||
sets: Sets,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
struct Exit {
|
||||
pc: u64,
|
||||
kind: u64,
|
||||
}
|
||||
|
||||
const NEXT: Exit = Exit {
|
||||
pc: PC.0 + 4,
|
||||
kind: ExitKind::Fallthrough as u64,
|
||||
};
|
||||
const MISS: Exit = Exit {
|
||||
pc: PC.0,
|
||||
kind: ExitKind::System as u64,
|
||||
};
|
||||
|
||||
fn at(field: usize) -> Place {
|
||||
Place::new(Anchor::Mirrors, field)
|
||||
}
|
||||
|
||||
fn places(sets: bool, world: &World) -> Places {
|
||||
Places {
|
||||
table: at(offset_of!(World, table)),
|
||||
contexts: at(offset_of!(World, contexts)),
|
||||
salts: at(offset_of!(World, salts)),
|
||||
contexts_generation: at(offset_of!(World, contexts_generation)),
|
||||
closes: alloc::vec![
|
||||
at(offset_of!(World, closes)),
|
||||
at(offset_of!(World, closes) + 8)
|
||||
],
|
||||
cr3: sets.then_some(Cr3::Word(&world.cr3 as *const u64 as u64)),
|
||||
isolate: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn root(set: u64, view: u64) -> u64 {
|
||||
BASE + (set * SET_ROOTS as u64 + view) * 4096
|
||||
}
|
||||
|
||||
/// A world whose register holds OLD, with an entry for NEW to set 5 and
|
||||
/// the current CR3 set 2's view 3.
|
||||
fn world(sets: bool) -> alloc::boxed::Box<World> {
|
||||
let mut world = alloc::boxed::Box::new(World {
|
||||
cell: Cell::default(),
|
||||
register: OLD,
|
||||
table: Table::default(),
|
||||
contexts: [0x11, UPPER],
|
||||
salts: [0x21, 0x22],
|
||||
contexts_generation: 9,
|
||||
closes: [1, 1],
|
||||
cr3: root(2, 3) | (FIRST_CONTEXT + 2 * 8 + 3),
|
||||
translating: 0x100,
|
||||
pending: 0,
|
||||
sets: Sets::default(),
|
||||
});
|
||||
world.cell = Cell {
|
||||
readable: 1,
|
||||
value: &world.register as *const u64 as u64,
|
||||
};
|
||||
world.table.translating = &world.translating as *const u32 as u64;
|
||||
world.table.pending = &world.pending as *const u8 as u64;
|
||||
if sets {
|
||||
world.table.sets = &world.sets as *const Sets as u64;
|
||||
world.sets.open = 1;
|
||||
world.sets.base = BASE;
|
||||
world.sets.tagged = 1;
|
||||
world.sets.classes[2] = 7;
|
||||
world.sets.classes[5] = 7;
|
||||
world.sets.generations[5] = 4;
|
||||
world.sets.stale[5 * 8 + 3] = 0;
|
||||
}
|
||||
world.table.keep(Entry {
|
||||
generation: 0,
|
||||
value: NEW,
|
||||
upper: UPPER,
|
||||
lower: 0x55,
|
||||
salt: 0x66,
|
||||
translating: 0x200,
|
||||
set: 5,
|
||||
set_generation: 4,
|
||||
});
|
||||
world
|
||||
}
|
||||
|
||||
fn run(thunk: &Thunk, world: &mut World, x: u64) -> Exit {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "C" {
|
||||
fn mmap(a: *mut c_void, b: usize, p: i32, f: i32, fd: i32, o: i64) -> *mut c_void;
|
||||
fn mprotect(a: *mut c_void, b: usize, p: i32) -> i32;
|
||||
fn munmap(a: *mut c_void, b: usize) -> i32;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAP_ANONYMOUS: i32 = 0x1000;
|
||||
#[cfg(target_os = "linux")]
|
||||
const MAP_ANONYMOUS: i32 = 0x20;
|
||||
const BYTES: usize = 8192;
|
||||
let mut state = GuestState::default();
|
||||
state.x[RT as usize] = x;
|
||||
state.anchors[Anchor::Mirrors] = world as *mut World as u64;
|
||||
let code = crate::x86_64::pinned::entered(&thunk.code);
|
||||
assert!(code.len() <= BYTES);
|
||||
// SAFETY: private anonymous memory, RX after the copy, unmapped after
|
||||
// the call; the thunk touches only `state` and `world`.
|
||||
unsafe {
|
||||
let page = mmap(core::ptr::null_mut(), BYTES, 3, 2 | MAP_ANONYMOUS, -1, 0);
|
||||
assert_ne!(page as usize, usize::MAX);
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
assert_eq!(mprotect(page, BYTES, 5), 0);
|
||||
let exit = crate::x86_64::native::call::<Exit>(page as *const u8, &mut state, 0, 0);
|
||||
assert_eq!(munmap(page, BYTES), 0);
|
||||
exit
|
||||
}
|
||||
}
|
||||
|
||||
fn thunk(sets: bool, world: &World) -> Thunk {
|
||||
let all = Written {
|
||||
keep: u64::MAX,
|
||||
set: 0,
|
||||
};
|
||||
switch_thunk(
|
||||
PC,
|
||||
RT,
|
||||
at(offset_of!(World, cell)),
|
||||
all,
|
||||
&places(sets, world),
|
||||
)
|
||||
}
|
||||
|
||||
/// What a switch leaves: the register, contexts, salts, contexts
|
||||
/// generation, closed cells, translating word, switches and CR3.
|
||||
type Seen = (u64, [u64; 2], [u32; 2], u64, [u64; 2], u32, u64, u64);
|
||||
|
||||
/// What a switch leaves, as a tuple to compare.
|
||||
fn seen(world: &World) -> Seen {
|
||||
(
|
||||
world.register,
|
||||
world.contexts,
|
||||
world.salts,
|
||||
world.contexts_generation,
|
||||
world.closes,
|
||||
world.translating,
|
||||
world.table.switches,
|
||||
world.cr3,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_value_completes_and_changes_nothing() {
|
||||
for sets in [false, true] {
|
||||
let mut world = world(sets);
|
||||
let before = seen(&world);
|
||||
assert_eq!(run(&thunk(sets, &world), &mut world, OLD), NEXT);
|
||||
assert_eq!(seen(&world), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_without_an_entry_exits_and_changes_nothing() {
|
||||
for sets in [false, true] {
|
||||
let mut world = world(sets);
|
||||
let before = seen(&world);
|
||||
assert_eq!(run(&thunk(sets, &world), &mut world, 3 << 48), MISS);
|
||||
assert_eq!(seen(&world), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_switches_the_register_contexts_cells_and_publication() {
|
||||
let mut world = world(false);
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, NEW), NEXT);
|
||||
assert_eq!(
|
||||
seen(&world),
|
||||
(
|
||||
NEW,
|
||||
[0x55, UPPER],
|
||||
[0x66, 0x22],
|
||||
10,
|
||||
[0, 0],
|
||||
0x200,
|
||||
1,
|
||||
world.cr3
|
||||
)
|
||||
);
|
||||
// And back is a miss until the engine keeps an entry for OLD.
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, OLD), MISS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_entries_and_other_states_exit() {
|
||||
// An entry of an older generation.
|
||||
let mut old = world(false);
|
||||
old.table.forget();
|
||||
let before = seen(&old);
|
||||
assert_eq!(run(&thunk(false, &old), &mut old, NEW), MISS);
|
||||
assert_eq!(seen(&old), before);
|
||||
// Another state's upper context.
|
||||
let mut other = world(false);
|
||||
other.contexts[1] = UPPER + 1;
|
||||
let before = seen(&other);
|
||||
assert_eq!(run(&thunk(false, &other), &mut other, NEW), MISS);
|
||||
assert_eq!(seen(&other), before);
|
||||
// A closed cell.
|
||||
let mut closed = world(false);
|
||||
closed.cell.readable = 0;
|
||||
let before = seen(&closed);
|
||||
assert_eq!(run(&thunk(false, &closed), &mut closed, NEW), MISS);
|
||||
assert_eq!(seen(&closed), before);
|
||||
// A table naming sets where the thunk was made without CR3.
|
||||
let mut sets = world(true);
|
||||
let before = seen(&sets);
|
||||
assert_eq!(run(&thunk(false, &sets), &mut sets, NEW), MISS);
|
||||
assert_eq!(seen(&sets), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_mail_after_a_publication_exits_before_the_switch() {
|
||||
let mut world = world(false);
|
||||
world.pending = 1;
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, NEW), MISS);
|
||||
// Published, but nothing else moved: the engine reads the mail and
|
||||
// completes the write.
|
||||
assert_eq!(world.translating, 0x200);
|
||||
assert_eq!(
|
||||
(world.register, world.contexts[0], world.table.switches),
|
||||
(OLD, 0x11, 0)
|
||||
);
|
||||
// An unchanged publication does not look at the mail.
|
||||
let mut same = self::world(false);
|
||||
same.pending = 1;
|
||||
same.translating = 0x200;
|
||||
assert_eq!(run(&thunk(false, &same), &mut same, NEW), NEXT);
|
||||
assert_eq!(same.register, NEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_loads_the_same_view_of_its_root_in_its_context() {
|
||||
let mut world = world(true);
|
||||
assert_eq!(run(&thunk(true, &world), &mut world, NEW), NEXT);
|
||||
let index = 5 * 8 + 3;
|
||||
assert_eq!(
|
||||
world.cr3,
|
||||
root(5, 3) | (FIRST_CONTEXT + index) | KEEP_ENTRIES
|
||||
);
|
||||
assert_eq!((world.sets.switched, world.sets.current), (6, root(5, 0)));
|
||||
assert_eq!(world.register, NEW);
|
||||
assert_eq!(world.sets.flushes, 0);
|
||||
// A stale view flushes as it loads, counted, and is fresh after.
|
||||
let mut stale = self::world(true);
|
||||
stale.sets.stale[index as usize] = 1;
|
||||
assert_eq!(run(&thunk(true, &stale), &mut stale, NEW), NEXT);
|
||||
assert_eq!(stale.cr3, root(5, 3) | (FIRST_CONTEXT + index));
|
||||
assert_eq!(stale.sets.stale[index as usize], 0);
|
||||
assert_eq!(stale.sets.flushes, 1);
|
||||
// Untagged roots load bare.
|
||||
let mut untagged = self::world(true);
|
||||
untagged.sets.tagged = 0;
|
||||
untagged.cr3 = root(2, 3);
|
||||
assert_eq!(run(&thunk(true, &untagged), &mut untagged, NEW), NEXT);
|
||||
assert_eq!(untagged.cr3, root(5, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_of_another_class_generation_or_closed_exit() {
|
||||
let cases: [fn(&mut World); 5] = [
|
||||
|world| world.sets.classes[5] = 8,
|
||||
|world| world.sets.generations[5] = 5,
|
||||
|world| world.sets.open = 0,
|
||||
// CR3 outside the sets: the host's own root.
|
||||
|world| world.cr3 = BASE - 4096,
|
||||
|world| world.table.entries[0].set = SETS as u64,
|
||||
];
|
||||
for (case, change) in cases.into_iter().enumerate() {
|
||||
let mut world = world(true);
|
||||
change(&mut world);
|
||||
let before = seen(&world);
|
||||
assert_eq!(
|
||||
run(&thunk(true, &world), &mut world, NEW),
|
||||
MISS,
|
||||
"case {case}"
|
||||
);
|
||||
assert_eq!(seen(&world), before, "case {case}");
|
||||
assert_eq!(world.sets.switched, 0, "case {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_entry_slot_is_found() {
|
||||
for index in 0..ENTRIES as u64 {
|
||||
let mut world = world(false);
|
||||
for other in 0..index {
|
||||
world.table.keep(Entry {
|
||||
value: 0x9000 + other,
|
||||
upper: UPPER,
|
||||
..Entry::default()
|
||||
});
|
||||
}
|
||||
world.table.keep(Entry {
|
||||
value: 0xa000,
|
||||
upper: UPPER,
|
||||
lower: 0x99,
|
||||
..Entry::default()
|
||||
});
|
||||
assert_eq!(
|
||||
run(&thunk(false, &world), &mut world, 0xa000),
|
||||
NEXT,
|
||||
"slot {index}"
|
||||
);
|
||||
assert_eq!(world.contexts[0], 0x99);
|
||||
}
|
||||
}
|
||||
use super::*;
|
||||
use crate::{Anchor, GuestState, x86_64::register_read::Cell};
|
||||
|
||||
const PC: GuestAddress = GuestAddress(0x4000);
|
||||
const RT: u8 = 3;
|
||||
const OLD: u64 = 1 << 48 | 0x8000;
|
||||
const NEW: u64 = 2 << 48 | 0xc000;
|
||||
const UPPER: u64 = 0x77;
|
||||
const BASE: u64 = 0x10_0000;
|
||||
|
||||
/// Everything a switch thunk reads and writes, at the Mirrors anchor.
|
||||
#[repr(C)]
|
||||
struct World {
|
||||
cell: Cell,
|
||||
register: u64,
|
||||
table: Table,
|
||||
contexts: [u64; 2],
|
||||
moves: u64,
|
||||
salts: [u32; 2],
|
||||
contexts_generation: u64,
|
||||
closes: [u64; 2],
|
||||
cr3: u64,
|
||||
translating: u32,
|
||||
pending: u8,
|
||||
sets: Sets,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
struct Exit {
|
||||
pc: u64,
|
||||
kind: u64,
|
||||
}
|
||||
|
||||
const NEXT: Exit = Exit {
|
||||
pc: PC.0 + 4,
|
||||
kind: ExitKind::Fallthrough as u64,
|
||||
};
|
||||
const MISS: Exit = Exit {
|
||||
pc: PC.0,
|
||||
kind: ExitKind::System as u64,
|
||||
};
|
||||
|
||||
fn at(field: usize) -> Place {
|
||||
Place::new(Anchor::Mirrors, field)
|
||||
}
|
||||
|
||||
fn places(sets: bool, world: &World) -> Places {
|
||||
Places {
|
||||
table: at(offset_of!(World, table)),
|
||||
contexts: at(offset_of!(World, contexts)),
|
||||
moves: at(offset_of!(World, moves)),
|
||||
salts: at(offset_of!(World, salts)),
|
||||
contexts_generation: at(offset_of!(World, contexts_generation)),
|
||||
closes: alloc::vec![
|
||||
at(offset_of!(World, closes)),
|
||||
at(offset_of!(World, closes) + 8)
|
||||
],
|
||||
cr3: sets.then_some(Cr3::Word(&world.cr3 as *const u64 as u64)),
|
||||
isolate: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn root(set: u64, view: u64) -> u64 {
|
||||
BASE + (set * SET_ROOTS as u64 + view) * 4096
|
||||
}
|
||||
|
||||
/// A world whose register holds OLD, with an entry for NEW to set 5 and
|
||||
/// the current CR3 set 2's view 3.
|
||||
fn world(sets: bool) -> alloc::boxed::Box<World> {
|
||||
let mut world = alloc::boxed::Box::new(World {
|
||||
cell: Cell::default(),
|
||||
register: OLD,
|
||||
table: Table::default(),
|
||||
contexts: [0x11, UPPER],
|
||||
moves: 0,
|
||||
salts: [0x21, 0x22],
|
||||
contexts_generation: 9,
|
||||
closes: [1, 1],
|
||||
cr3: root(2, 3) | (FIRST_CONTEXT + 2 * 8 + 3),
|
||||
translating: 0x100,
|
||||
pending: 0,
|
||||
sets: Sets::default(),
|
||||
});
|
||||
world.cell = Cell {
|
||||
readable: 1,
|
||||
value: &world.register as *const u64 as u64,
|
||||
};
|
||||
world.table.translating = &world.translating as *const u32 as u64;
|
||||
world.table.pending = &world.pending as *const u8 as u64;
|
||||
if sets {
|
||||
world.table.sets = &world.sets as *const Sets as u64;
|
||||
world.sets.open = 1;
|
||||
world.sets.base = BASE;
|
||||
world.sets.tagged = 1;
|
||||
world.sets.classes[2] = 7;
|
||||
world.sets.classes[5] = 7;
|
||||
world.sets.generations[5] = 4;
|
||||
world.sets.stale[5 * 8 + 3] = 0;
|
||||
}
|
||||
world.table.keep(Entry {
|
||||
generation: 0,
|
||||
value: NEW,
|
||||
upper: UPPER,
|
||||
lower: 0x55,
|
||||
salt: 0x66,
|
||||
translating: 0x200,
|
||||
set: 5,
|
||||
set_generation: 4,
|
||||
});
|
||||
world
|
||||
}
|
||||
|
||||
fn run(thunk: &Thunk, world: &mut World, x: u64) -> Exit {
|
||||
use core::ffi::c_void;
|
||||
const BYTES: usize = 8192;
|
||||
let mut state = GuestState::default();
|
||||
state.x[RT as usize] = x;
|
||||
state.anchors[Anchor::Mirrors] = world as *mut World as u64;
|
||||
let code = crate::x86_64::pinned::entered(&thunk.code);
|
||||
assert!(code.len() <= BYTES);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
unsafe {
|
||||
unsafe extern "C" {
|
||||
fn mmap(a: *mut c_void, b: usize, p: i32, f: i32, fd: i32, o: i64) -> *mut c_void;
|
||||
fn mprotect(a: *mut c_void, b: usize, p: i32) -> i32;
|
||||
fn munmap(a: *mut c_void, b: usize) -> i32;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAP_ANONYMOUS: i32 = 0x1000;
|
||||
#[cfg(target_os = "linux")]
|
||||
const MAP_ANONYMOUS: i32 = 0x20;
|
||||
let page = mmap(core::ptr::null_mut(), BYTES, 3, 2 | MAP_ANONYMOUS, -1, 0);
|
||||
assert_ne!(page as usize, usize::MAX);
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
assert_eq!(mprotect(page, BYTES, 5), 0);
|
||||
let exit = crate::x86_64::native::call::<Exit>(page as *const u8, &mut state, 0, 0);
|
||||
assert_eq!(munmap(page, BYTES), 0);
|
||||
exit
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
unsafe {
|
||||
unsafe extern "system" {
|
||||
fn VirtualAlloc(a: *const c_void, b: usize, t: u32, p: u32) -> *mut c_void;
|
||||
fn VirtualProtect(a: *const c_void, b: usize, p: u32, o: *mut u32) -> i32;
|
||||
fn VirtualFree(a: *mut c_void, b: usize, t: u32) -> i32;
|
||||
}
|
||||
let page = VirtualAlloc(core::ptr::null(), BYTES, 0x1000 | 0x2000, 0x04);
|
||||
assert!(!page.is_null());
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
let mut old = 0u32;
|
||||
assert_ne!(VirtualProtect(page, BYTES, 0x20, &mut old), 0);
|
||||
let exit = crate::x86_64::native::call::<Exit>(page as *const u8, &mut state, 0, 0);
|
||||
assert_ne!(VirtualFree(page, 0, 0x8000), 0);
|
||||
exit
|
||||
}
|
||||
}
|
||||
|
||||
fn thunk(sets: bool, world: &World) -> Thunk {
|
||||
let all = Written {
|
||||
keep: u64::MAX,
|
||||
set: 0,
|
||||
};
|
||||
switch_thunk(
|
||||
PC,
|
||||
RT,
|
||||
at(offset_of!(World, cell)),
|
||||
all,
|
||||
&places(sets, world),
|
||||
)
|
||||
}
|
||||
|
||||
/// What a switch leaves: the register, contexts, salts, contexts
|
||||
/// generation, closed cells, translating word, switches and CR3.
|
||||
type Seen = (u64, [u64; 2], [u32; 2], u64, [u64; 2], u32, u64, u64);
|
||||
|
||||
/// What a switch leaves, as a tuple to compare.
|
||||
fn seen(world: &World) -> Seen {
|
||||
(
|
||||
world.register,
|
||||
world.contexts,
|
||||
world.salts,
|
||||
world.contexts_generation,
|
||||
world.closes,
|
||||
world.translating,
|
||||
world.table.switches,
|
||||
world.cr3,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_value_completes_and_changes_nothing() {
|
||||
for sets in [false, true] {
|
||||
let mut world = world(sets);
|
||||
let before = seen(&world);
|
||||
assert_eq!(run(&thunk(sets, &world), &mut world, OLD), NEXT);
|
||||
assert_eq!(seen(&world), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_without_an_entry_exits_and_changes_nothing() {
|
||||
for sets in [false, true] {
|
||||
let mut world = world(sets);
|
||||
let before = seen(&world);
|
||||
assert_eq!(run(&thunk(sets, &world), &mut world, 3 << 48), MISS);
|
||||
assert_eq!(seen(&world), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_switches_the_register_contexts_cells_and_publication() {
|
||||
let mut world = world(false);
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, NEW), NEXT);
|
||||
assert_eq!(
|
||||
seen(&world),
|
||||
(
|
||||
NEW,
|
||||
[0x55, UPPER],
|
||||
[0x66, 0x22],
|
||||
10,
|
||||
[0, 0],
|
||||
0x200,
|
||||
1,
|
||||
world.cr3
|
||||
)
|
||||
);
|
||||
// And back is a miss until the engine keeps an entry for OLD.
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, OLD), MISS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_entries_and_other_states_exit() {
|
||||
// An entry of an older generation.
|
||||
let mut old = world(false);
|
||||
old.table.forget();
|
||||
let before = seen(&old);
|
||||
assert_eq!(run(&thunk(false, &old), &mut old, NEW), MISS);
|
||||
assert_eq!(seen(&old), before);
|
||||
// Another state's upper context.
|
||||
let mut other = world(false);
|
||||
other.contexts[1] = UPPER + 1;
|
||||
let before = seen(&other);
|
||||
assert_eq!(run(&thunk(false, &other), &mut other, NEW), MISS);
|
||||
assert_eq!(seen(&other), before);
|
||||
// A closed cell.
|
||||
let mut closed = world(false);
|
||||
closed.cell.readable = 0;
|
||||
let before = seen(&closed);
|
||||
assert_eq!(run(&thunk(false, &closed), &mut closed, NEW), MISS);
|
||||
assert_eq!(seen(&closed), before);
|
||||
// A table naming sets where the thunk was made without CR3.
|
||||
let mut sets = world(true);
|
||||
let before = seen(&sets);
|
||||
assert_eq!(run(&thunk(false, &sets), &mut sets, NEW), MISS);
|
||||
assert_eq!(seen(&sets), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_mail_after_a_publication_exits_before_the_switch() {
|
||||
let mut world = world(false);
|
||||
world.pending = 1;
|
||||
assert_eq!(run(&thunk(false, &world), &mut world, NEW), MISS);
|
||||
// Published, but nothing else moved: the engine reads the mail and
|
||||
// completes the write.
|
||||
assert_eq!(world.translating, 0x200);
|
||||
assert_eq!(
|
||||
(world.register, world.contexts[0], world.table.switches),
|
||||
(OLD, 0x11, 0)
|
||||
);
|
||||
// An unchanged publication does not look at the mail.
|
||||
let mut same = self::world(false);
|
||||
same.pending = 1;
|
||||
same.translating = 0x200;
|
||||
assert_eq!(run(&thunk(false, &same), &mut same, NEW), NEXT);
|
||||
assert_eq!(same.register, NEW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_loads_the_same_view_of_its_root_in_its_context() {
|
||||
let mut world = world(true);
|
||||
assert_eq!(run(&thunk(true, &world), &mut world, NEW), NEXT);
|
||||
let index = 5 * 8 + 3;
|
||||
assert_eq!(
|
||||
world.cr3,
|
||||
root(5, 3) | (FIRST_CONTEXT + index) | KEEP_ENTRIES
|
||||
);
|
||||
assert_eq!((world.sets.switched, world.sets.current), (6, root(5, 0)));
|
||||
assert_eq!(world.register, NEW);
|
||||
assert_eq!(world.sets.flushes, 0);
|
||||
// A stale view flushes as it loads, counted, and is fresh after.
|
||||
let mut stale = self::world(true);
|
||||
stale.sets.stale[index as usize] = 1;
|
||||
assert_eq!(run(&thunk(true, &stale), &mut stale, NEW), NEXT);
|
||||
assert_eq!(stale.cr3, root(5, 3) | (FIRST_CONTEXT + index));
|
||||
assert_eq!(stale.sets.stale[index as usize], 0);
|
||||
assert_eq!(stale.sets.flushes, 1);
|
||||
// Untagged roots load bare.
|
||||
let mut untagged = self::world(true);
|
||||
untagged.sets.tagged = 0;
|
||||
untagged.cr3 = root(2, 3);
|
||||
assert_eq!(run(&thunk(true, &untagged), &mut untagged, NEW), NEXT);
|
||||
assert_eq!(untagged.cr3, root(5, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_of_another_class_generation_or_closed_exit() {
|
||||
let cases: [fn(&mut World); 5] = [
|
||||
|world| world.sets.classes[5] = 8,
|
||||
|world| world.sets.generations[5] = 5,
|
||||
|world| world.sets.open = 0,
|
||||
// CR3 outside the sets: the host's own root.
|
||||
|world| world.cr3 = BASE - 4096,
|
||||
|world| world.table.entries[0].set = SETS as u64,
|
||||
];
|
||||
for (case, change) in cases.into_iter().enumerate() {
|
||||
let mut world = world(true);
|
||||
change(&mut world);
|
||||
let before = seen(&world);
|
||||
assert_eq!(
|
||||
run(&thunk(true, &world), &mut world, NEW),
|
||||
MISS,
|
||||
"case {case}"
|
||||
);
|
||||
assert_eq!(seen(&world), before, "case {case}");
|
||||
assert_eq!(world.sets.switched, 0, "case {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_entry_slot_is_found() {
|
||||
for index in 0..ENTRIES as u64 {
|
||||
let mut world = world(false);
|
||||
for other in 0..index {
|
||||
world.table.keep(Entry {
|
||||
value: 0x9000 + other,
|
||||
upper: UPPER,
|
||||
..Entry::default()
|
||||
});
|
||||
}
|
||||
world.table.keep(Entry {
|
||||
value: 0xa000,
|
||||
upper: UPPER,
|
||||
lower: 0x99,
|
||||
..Entry::default()
|
||||
});
|
||||
assert_eq!(
|
||||
run(&thunk(false, &world), &mut world, 0xa000),
|
||||
NEXT,
|
||||
"slot {index}"
|
||||
);
|
||||
assert_eq!(world.contexts[0], 0x99);
|
||||
}
|
||||
}
|
||||
@@ -626,6 +626,14 @@ fn commit(
|
||||
asm.mov_load(Qword, Rax, to(offset_of!(Record, contexts) + half * 8));
|
||||
asm.mov_store(Qword, Mem::base(Rcx, (half * 8) as i32), Rax);
|
||||
}
|
||||
// Every paired frame of before fails from here on.
|
||||
let moves = offset_of!(super::chain::ChainControl, moves);
|
||||
asm.alu_imm8(
|
||||
Alu::Add,
|
||||
Qword,
|
||||
Mem::base(Rcx, (moves - contexts) as i32),
|
||||
1,
|
||||
);
|
||||
let salts = offset_of!(super::chain::ChainControl, salts);
|
||||
asm.place(Rcx, Place::new(Anchor::Control, salts));
|
||||
asm.mov_load(Qword, Rax, to(offset_of!(Record, salts)));
|
||||
@@ -1307,6 +1315,8 @@ mod tests {
|
||||
assert_eq!(self.words.status, 0);
|
||||
assert_eq!(self.state.anchors[Anchor::Cells], 0x1234_5000);
|
||||
assert_eq!(self.control.contexts, [11, 12]);
|
||||
// Its paired frames fail from here on.
|
||||
assert_eq!(self.control.moves, 1);
|
||||
assert_eq!(self.control.salts, [5, 7]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod masked;
|
||||
pub mod pauth;
|
||||
pub mod processor;
|
||||
pub mod refusal;
|
||||
pub mod reims_hosted;
|
||||
pub mod tag_storage;
|
||||
pub mod uuid;
|
||||
|
||||
|
||||
@@ -0,0 +1,814 @@
|
||||
//! Guest-physical apertures for a copy-only hosted Reims device.
|
||||
//!
|
||||
//! The host transport owns the outer PCI resources. The inner guest sees the
|
||||
//! graphics registers below MSI-X, the command region and the doorbell pages.
|
||||
//! MSI-X and the guest's own RAM have separate ownership and are not forwarded.
|
||||
use alloc::{boxed::Box, sync::Arc};
|
||||
use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
|
||||
use crate::{
|
||||
Refusal,
|
||||
bus::{self, Access, AdvancePolicy, Bus, DeviceId, Direction, MapError, MmioDevice, MmioError, Width},
|
||||
interrupt::{AicInput, Wire},
|
||||
};
|
||||
|
||||
/// Values from Reims graphics wire version 2 and its C transport header.
|
||||
const MAGIC: u64 = 1481000786;
|
||||
const VERSION: u64 = 2;
|
||||
const SURFACE_PAGES: u64 = 1;
|
||||
const POOL_FEATURES_HI: u64 = (1 << 25) | (1 << 27);
|
||||
const DOORBELL_PAGES_HI: u64 = 1 << (46 - 32);
|
||||
pub const REGISTER_BYTES: u64 = 2048;
|
||||
pub const REGION_BYTES: u64 = 1 << 30;
|
||||
pub const DOORBELL_BYTES: u64 = 4 << 20;
|
||||
/// Outer QEMU's hosted-only interrupt and RAM-map control registers in BAR4.
|
||||
pub const HOST_RAM_GUEST_PA_LO_OFFSET: u64 = DOORBELL_BYTES - 0x2c;
|
||||
pub const HOST_RAM_GUEST_PA_HI_OFFSET: u64 = DOORBELL_BYTES - 0x28;
|
||||
pub const HOST_RAM_HOST_GPA_LO_OFFSET: u64 = DOORBELL_BYTES - 0x24;
|
||||
pub const HOST_RAM_HOST_GPA_HI_OFFSET: u64 = DOORBELL_BYTES - 0x20;
|
||||
pub const HOST_RAM_BYTES_LO_OFFSET: u64 = DOORBELL_BYTES - 0x1c;
|
||||
pub const HOST_RAM_BYTES_HI_OFFSET: u64 = DOORBELL_BYTES - 0x18;
|
||||
pub const HOST_RAM_CMD_OFFSET: u64 = DOORBELL_BYTES - 0x14;
|
||||
pub const HOST_RAM_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 0x10;
|
||||
pub const HOST_RAM_SIGNATURE: u32 = 0x524d_4150;
|
||||
pub const HOST_RAM_CMD_CLEAR: u32 = 1;
|
||||
pub const HOST_RAM_CMD_ADD: u32 = 2;
|
||||
pub const HOST_RAM_CMD_COMMIT: u32 = 3;
|
||||
pub const HOST_CONTROL_MIN_OFFSET: u64 = HOST_RAM_GUEST_PA_LO_OFFSET;
|
||||
pub const HOST_IRQ_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 8;
|
||||
pub const HOST_IRQ_GENERATION_OFFSET: u64 = DOORBELL_BYTES - 4;
|
||||
pub const HOST_IRQ_SIGNATURE: u32 = 0x5249_5251;
|
||||
/// Guest read returns the observed generation. A matching write acknowledges it.
|
||||
pub const GUEST_IRQ_TOKEN: u64 = REGISTER_BYTES - 4;
|
||||
const ARM_PAGE: u64 = 16 << 10;
|
||||
// Adaptive host IRQ polling intervals in the guest system counter's 24 MHz ticks:
|
||||
// 1.0 ms active cadence for 50 ms after activity or IRQ, decaying to 5.0 ms idle.
|
||||
const ACTIVE_POLL_TICKS: u64 = 24_000;
|
||||
const IDLE_POLL_TICKS: u64 = 120_000;
|
||||
const ACTIVE_WINDOW_TICKS: u64 = 1_200_000;
|
||||
const EVENT_SAFETY_POLL_TICKS: u64 = 2_400_000;
|
||||
|
||||
// Separate device offsets distinguish the three guest-physical mappings.
|
||||
const REGION_OFFSET: u64 = 1 << 32;
|
||||
const DOORBELL_OFFSET: u64 = 2 << 32;
|
||||
const NAME: &str = "Reims hosted graphics";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Bar {
|
||||
Registers,
|
||||
Region,
|
||||
Doorbells,
|
||||
}
|
||||
|
||||
/// The service that owns the outer device's three BARs. Values occupy the low
|
||||
/// bytes in little-endian order. Implementations must preserve the order in
|
||||
/// which the bus calls them and use the publication semantics of the wire.
|
||||
pub trait Transport {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal>;
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal>;
|
||||
|
||||
/// A wrapping counter published by the host after it writes completion
|
||||
/// data. None means the transport has no notification channel.
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// True once the hosted translator has published its inner ARM64 DRAM map
|
||||
/// to outer QEMU via the RMAP mailbox, allowing zero-copy SURFACE_PAGES.
|
||||
fn guest_ram_mapped(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// True when host completion wakes arrive via an event interrupt rather
|
||||
/// than adaptive 1 ms / 5 ms polling.
|
||||
fn event_driven(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Monotonic host interrupt signal count observed for this transport.
|
||||
fn signal_count(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot of hosted Reims interrupt delivery across all four stages:
|
||||
/// host signal wake -> host token poll -> AIC assertion -> guest token ACK.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct IrqStats {
|
||||
pub event_driven: bool,
|
||||
pub seen: u32,
|
||||
pub polls: u64,
|
||||
pub msi_wakes: u64,
|
||||
pub fallback_polls: u64,
|
||||
pub injects: u64,
|
||||
pub coalesced: u64,
|
||||
pub token_reads: u64,
|
||||
pub acks: u64,
|
||||
pub stale_acks: u64,
|
||||
pub ack_lat_sum_ticks: u64,
|
||||
pub ack_lat_max_ticks: u64,
|
||||
pub ack_lat_samples: u64,
|
||||
pub first_inject_ticks: u64,
|
||||
pub first_ack_ticks: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct IrqMetrics {
|
||||
event_driven: AtomicBool,
|
||||
seen: AtomicU32,
|
||||
polls: AtomicU64,
|
||||
msi_wakes: AtomicU64,
|
||||
fallback_polls: AtomicU64,
|
||||
injects: AtomicU64,
|
||||
coalesced: AtomicU64,
|
||||
token_reads: AtomicU64,
|
||||
acks: AtomicU64,
|
||||
stale_acks: AtomicU64,
|
||||
ack_lat_sum_ticks: AtomicU64,
|
||||
ack_lat_max_ticks: AtomicU64,
|
||||
ack_lat_samples: AtomicU64,
|
||||
first_inject_ticks: AtomicU64,
|
||||
first_ack_ticks: AtomicU64,
|
||||
}
|
||||
|
||||
impl IrqMetrics {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> IrqStats {
|
||||
IrqStats {
|
||||
event_driven: self.event_driven.load(Ordering::Relaxed),
|
||||
seen: self.seen.load(Ordering::Relaxed),
|
||||
polls: self.polls.load(Ordering::Relaxed),
|
||||
msi_wakes: self.msi_wakes.load(Ordering::Relaxed),
|
||||
fallback_polls: self.fallback_polls.load(Ordering::Relaxed),
|
||||
injects: self.injects.load(Ordering::Relaxed),
|
||||
coalesced: self.coalesced.load(Ordering::Relaxed),
|
||||
token_reads: self.token_reads.load(Ordering::Relaxed),
|
||||
acks: self.acks.load(Ordering::Relaxed),
|
||||
stale_acks: self.stale_acks.load(Ordering::Relaxed),
|
||||
ack_lat_sum_ticks: self.ack_lat_sum_ticks.load(Ordering::Relaxed),
|
||||
ack_lat_max_ticks: self.ack_lat_max_ticks.load(Ordering::Relaxed),
|
||||
ack_lat_samples: self.ack_lat_samples.load(Ordering::Relaxed),
|
||||
first_inject_ticks: self.first_inject_ticks.load(Ordering::Relaxed),
|
||||
first_ack_ticks: self.first_ack_ticks.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ARM guest's physical bases, aligned to its 16 KiB page.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Apertures {
|
||||
pub registers: u64,
|
||||
pub region: u64,
|
||||
pub doorbells: u64,
|
||||
}
|
||||
|
||||
impl Apertures {
|
||||
/// Place the 1 GiB region first, followed by the registers and doorbells.
|
||||
pub fn at(base: u64) -> Option<Self> {
|
||||
if base == 0 || !base.is_multiple_of(REGION_BYTES) {
|
||||
return None;
|
||||
}
|
||||
let registers = base.checked_add(REGION_BYTES)?;
|
||||
let doorbells = registers.checked_add(DOORBELL_BYTES)?;
|
||||
doorbells.checked_add(DOORBELL_BYTES)?;
|
||||
Some(Self { registers, region: base, doorbells })
|
||||
}
|
||||
|
||||
/// Whether any of the device's three mappings intersects a RAM range.
|
||||
pub fn overlaps(self, start: u64, bytes: u64) -> bool {
|
||||
bytes != 0
|
||||
&& [
|
||||
(self.registers, REGISTER_BYTES),
|
||||
(self.region, REGION_BYTES),
|
||||
(self.doorbells, DOORBELL_BYTES),
|
||||
]
|
||||
.into_iter()
|
||||
.any(|(base, size)| {
|
||||
base < start.saturating_add(bytes) && start < base.saturating_add(size)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum InstallError {
|
||||
Alignment,
|
||||
WireVersion,
|
||||
GuestRamFeatures,
|
||||
ControlGeometry,
|
||||
InterruptUnavailable,
|
||||
InterruptInput,
|
||||
Transport(Refusal),
|
||||
Mapping(MapError),
|
||||
}
|
||||
|
||||
/// Check the outer device's protocol before exposing it to the ARM guest.
|
||||
pub fn validate_wire(transport: &mut impl Transport) -> Result<(), InstallError> {
|
||||
let guest_ram_mapped = transport.guest_ram_mapped();
|
||||
let mut register =
|
||||
|offset| transport.read(Bar::Registers, offset, Width::Word).map_err(InstallError::Transport);
|
||||
if register(0)? != MAGIC || register(4)? != VERSION {
|
||||
return Err(InstallError::WireVersion);
|
||||
}
|
||||
let lo = register(8)?;
|
||||
let hi = register(12)?;
|
||||
if (!guest_ram_mapped && lo & SURFACE_PAGES != 0) || hi & POOL_FEATURES_HI != 0 {
|
||||
return Err(InstallError::GuestRamFeatures);
|
||||
}
|
||||
if hi & DOORBELL_PAGES_HI == 0 || register(20)? != REGION_BYTES || register(24)? != 0 {
|
||||
return Err(InstallError::ControlGeometry);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Install the three ranges as one bus owner. The outer device must advertise
|
||||
/// the command region and doorbells without importing the inner guest's RAM.
|
||||
pub fn install(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, None, false, None)
|
||||
}
|
||||
|
||||
/// Install the device with a level AIC input serviced through GUEST_IRQ_TOKEN.
|
||||
pub fn install_with_interrupt(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), false, None)
|
||||
}
|
||||
|
||||
/// [`install_with_interrupt`] exporting live interrupt metrics.
|
||||
pub fn install_with_interrupt_metrics(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
metrics: Arc<IrqMetrics>,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), false, Some(metrics))
|
||||
}
|
||||
|
||||
/// Install only registers and doorbells on the MMIO bus when BAR2 (the command
|
||||
/// and allocation region) is mapped directly in guest physical RAM.
|
||||
pub fn install_direct_region(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, None, true, None)
|
||||
}
|
||||
|
||||
/// [`install_direct_region`] with a level AIC input serviced through GUEST_IRQ_TOKEN.
|
||||
pub fn install_direct_region_with_interrupt(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), true, None)
|
||||
}
|
||||
|
||||
/// [`install_direct_region_with_interrupt`] exporting live interrupt metrics.
|
||||
pub fn install_direct_region_with_interrupt_metrics(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
transport: impl Transport + 'static,
|
||||
input: AicInput,
|
||||
metrics: Arc<IrqMetrics>,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
install_inner(bus, addresses, transport, Some(input), true, Some(metrics))
|
||||
}
|
||||
|
||||
fn install_inner(
|
||||
bus: &mut Bus,
|
||||
addresses: Apertures,
|
||||
mut transport: impl Transport + 'static,
|
||||
input: Option<AicInput>,
|
||||
direct_region: bool,
|
||||
metrics: Option<Arc<IrqMetrics>>,
|
||||
) -> Result<DeviceId, InstallError> {
|
||||
if [addresses.registers, addresses.region, addresses.doorbells]
|
||||
.into_iter()
|
||||
.any(|address| !address.is_multiple_of(ARM_PAGE))
|
||||
{
|
||||
return Err(InstallError::Alignment);
|
||||
}
|
||||
validate_wire(&mut transport)?;
|
||||
let irq = if let Some(input) = input {
|
||||
let seen = transport
|
||||
.interrupt_generation()
|
||||
.map_err(InstallError::Transport)?
|
||||
.ok_or(InstallError::InterruptUnavailable)?;
|
||||
let metrics = metrics.unwrap_or_else(|| Arc::new(IrqMetrics::new()));
|
||||
metrics
|
||||
.event_driven
|
||||
.store(transport.event_driven(), Ordering::Relaxed);
|
||||
metrics.seen.store(seen, Ordering::Relaxed);
|
||||
Some(Interrupt {
|
||||
input,
|
||||
seen,
|
||||
next_poll: 0,
|
||||
active_until: 0,
|
||||
last_signal: transport.signal_count(),
|
||||
pending: false,
|
||||
pending_since: 0,
|
||||
metrics,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let device = Box::new(Device { transport, irq });
|
||||
if direct_region {
|
||||
bus.install(
|
||||
device,
|
||||
&[
|
||||
(addresses.registers, REGISTER_BYTES, 0),
|
||||
(addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET),
|
||||
],
|
||||
)
|
||||
.map_err(InstallError::Mapping)
|
||||
} else {
|
||||
bus.install(
|
||||
device,
|
||||
&[
|
||||
(addresses.registers, REGISTER_BYTES, 0),
|
||||
(addresses.region, REGION_BYTES, REGION_OFFSET),
|
||||
(addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET),
|
||||
],
|
||||
)
|
||||
.map_err(InstallError::Mapping)
|
||||
}
|
||||
}
|
||||
|
||||
struct Device<T> {
|
||||
transport: T,
|
||||
irq: Option<Interrupt>,
|
||||
}
|
||||
|
||||
struct Interrupt {
|
||||
input: AicInput,
|
||||
seen: u32,
|
||||
next_poll: u64,
|
||||
active_until: u64,
|
||||
last_signal: u64,
|
||||
pending: bool,
|
||||
pending_since: u64,
|
||||
metrics: Arc<IrqMetrics>,
|
||||
}
|
||||
|
||||
fn register(offset: u64, width: Width, direction: Direction) -> Result<(Bar, u64), MmioError> {
|
||||
if (REGION_OFFSET..REGION_OFFSET + REGION_BYTES).contains(&offset) {
|
||||
return Ok((Bar::Region, offset - REGION_OFFSET));
|
||||
}
|
||||
if width == Width::Word {
|
||||
if offset < REGISTER_BYTES {
|
||||
return Ok((Bar::Registers, offset));
|
||||
}
|
||||
if (DOORBELL_OFFSET..DOORBELL_OFFSET + DOORBELL_BYTES).contains(&offset) {
|
||||
return Ok((Bar::Doorbells, offset - DOORBELL_OFFSET));
|
||||
}
|
||||
}
|
||||
Err(bus::refuse(
|
||||
NAME,
|
||||
offset,
|
||||
width,
|
||||
direction,
|
||||
"graphics registers and doorbells take 32-bit accesses",
|
||||
))
|
||||
}
|
||||
|
||||
impl<T: Transport + 'static> MmioDevice for Device<T> {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn advance_policy(&self) -> AdvancePolicy {
|
||||
if self.irq.is_some() {
|
||||
AdvancePolicy::Always
|
||||
} else {
|
||||
AdvancePolicy::Passive
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&mut self, access: &mut Access<'_>) -> Result<Option<u64>, MmioError> {
|
||||
let Some(irq) = &mut self.irq else {
|
||||
return Ok(None);
|
||||
};
|
||||
let event_driven = self.transport.event_driven();
|
||||
irq.metrics
|
||||
.event_driven
|
||||
.store(event_driven, Ordering::Relaxed);
|
||||
let signals = self.transport.signal_count();
|
||||
let signal_bumped = event_driven && signals != irq.last_signal;
|
||||
let timer_due = access.now >= irq.next_poll;
|
||||
let should_poll = if event_driven {
|
||||
signal_bumped || timer_due
|
||||
} else {
|
||||
timer_due
|
||||
};
|
||||
if should_poll {
|
||||
irq.metrics.polls.fetch_add(1, Ordering::Relaxed);
|
||||
if event_driven {
|
||||
if signal_bumped {
|
||||
irq.metrics.msi_wakes.fetch_add(1, Ordering::Relaxed);
|
||||
irq.last_signal = signals;
|
||||
} else {
|
||||
irq.metrics.fallback_polls.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let generation = self.transport.interrupt_generation().map_err(|error| {
|
||||
bus::refuse(NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, error)
|
||||
})?;
|
||||
let Some(generation) = generation else {
|
||||
return Err(bus::refuse(
|
||||
NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read,
|
||||
"the host notification channel disappeared",
|
||||
));
|
||||
};
|
||||
if generation != irq.seen {
|
||||
let delta = u64::from(generation.wrapping_sub(irq.seen));
|
||||
if irq.pending {
|
||||
irq.metrics.coalesced.fetch_add(delta, Ordering::Relaxed);
|
||||
} else {
|
||||
irq.metrics.injects.fetch_add(1, Ordering::Relaxed);
|
||||
if delta > 1 {
|
||||
irq.metrics.coalesced.fetch_add(delta - 1, Ordering::Relaxed);
|
||||
}
|
||||
irq.pending = true;
|
||||
irq.pending_since = access.now;
|
||||
let _ = irq.metrics.first_inject_ticks.compare_exchange(
|
||||
0,
|
||||
access.now.max(1),
|
||||
Ordering::Relaxed,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
}
|
||||
irq.seen = generation;
|
||||
irq.metrics.seen.store(generation, Ordering::Relaxed);
|
||||
access.interrupts.set_level(Wire::Aic(irq.input), true);
|
||||
if !event_driven {
|
||||
irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS);
|
||||
}
|
||||
}
|
||||
if event_driven {
|
||||
irq.next_poll = access.now.saturating_add(EVENT_SAFETY_POLL_TICKS);
|
||||
} else {
|
||||
let interval = if access.now < irq.active_until {
|
||||
ACTIVE_POLL_TICKS
|
||||
} else {
|
||||
IDLE_POLL_TICKS
|
||||
};
|
||||
irq.next_poll = access.now.saturating_add(interval);
|
||||
}
|
||||
}
|
||||
Ok(Some(irq.next_poll))
|
||||
}
|
||||
|
||||
fn read(&mut self, offset: u64, width: Width, _: &mut Access<'_>) -> Result<u64, MmioError> {
|
||||
let (bar, at) = register(offset, width, Direction::Read)?;
|
||||
if let Some(irq) = &self.irq
|
||||
&& bar == Bar::Registers
|
||||
&& at == GUEST_IRQ_TOKEN
|
||||
{
|
||||
irq.metrics.token_reads.fetch_add(1, Ordering::Relaxed);
|
||||
return Ok(u64::from(irq.seen));
|
||||
}
|
||||
self.transport
|
||||
.read(bar, at, width)
|
||||
.map_err(|error| bus::refuse(NAME, offset, width, Direction::Read, error))
|
||||
}
|
||||
|
||||
fn write(
|
||||
&mut self,
|
||||
offset: u64,
|
||||
width: Width,
|
||||
value: u64,
|
||||
access: &mut Access<'_>,
|
||||
) -> Result<(), MmioError> {
|
||||
let (bar, at) = register(offset, width, Direction::Write)?;
|
||||
if let Some(irq) = &mut self.irq
|
||||
&& bar == Bar::Registers
|
||||
&& at == GUEST_IRQ_TOKEN
|
||||
{
|
||||
if value as u32 == irq.seen {
|
||||
access.interrupts.set_level(Wire::Aic(irq.input), false);
|
||||
irq.metrics.acks.fetch_add(1, Ordering::Relaxed);
|
||||
let _ = irq.metrics.first_ack_ticks.compare_exchange(
|
||||
0,
|
||||
access.now.max(1),
|
||||
Ordering::Relaxed,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
if irq.pending {
|
||||
let lat = access.now.saturating_sub(irq.pending_since);
|
||||
irq.metrics.ack_lat_sum_ticks.fetch_add(lat, Ordering::Relaxed);
|
||||
irq.metrics.ack_lat_max_ticks.fetch_max(lat, Ordering::Relaxed);
|
||||
irq.metrics.ack_lat_samples.fetch_add(1, Ordering::Relaxed);
|
||||
irq.pending = false;
|
||||
}
|
||||
if !self.transport.event_driven() {
|
||||
irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS);
|
||||
}
|
||||
} else {
|
||||
irq.metrics.stale_acks.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let event_driven = self.transport.event_driven();
|
||||
self.transport
|
||||
.write(bar, at, width, value)
|
||||
.map_err(|error| bus::refuse(NAME, offset, width, Direction::Write, error))?;
|
||||
if matches!(bar, Bar::Doorbells | Bar::Registers)
|
||||
&& !event_driven
|
||||
&& let Some(irq) = &mut self.irq
|
||||
{
|
||||
irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS);
|
||||
irq.next_poll = irq.next_poll.min(access.now.saturating_add(ACTIVE_POLL_TICKS));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::interrupt::InterruptLatch;
|
||||
use alloc::{rc::Rc, vec::Vec};
|
||||
use core::cell::{Cell, RefCell};
|
||||
|
||||
const ADDRESSES: Apertures = Apertures {
|
||||
registers: 0x2000_0000,
|
||||
region: 0x4000_0000,
|
||||
doorbells: 0x8040_0000,
|
||||
};
|
||||
|
||||
type Writes = Rc<RefCell<Vec<(Bar, u64, Width, u64)>>>;
|
||||
|
||||
struct FakeHost {
|
||||
surface_pages: bool,
|
||||
writes: Writes,
|
||||
generation: Option<Rc<Cell<u32>>>,
|
||||
}
|
||||
|
||||
impl Transport for FakeHost {
|
||||
fn read(&mut self, bar: Bar, offset: u64, _: Width) -> Result<u64, Refusal> {
|
||||
Ok(match (bar, offset) {
|
||||
(Bar::Registers, 0) => MAGIC,
|
||||
(Bar::Registers, 4) => VERSION,
|
||||
(Bar::Registers, 8) => u64::from(self.surface_pages),
|
||||
(Bar::Registers, 12) => DOORBELL_PAGES_HI,
|
||||
(Bar::Registers, 20) => REGION_BYTES,
|
||||
(Bar::Region, 256) => 0x4433_2211,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
self.writes.borrow_mut().push((bar, offset, width, value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
Ok(self.generation.as_deref().map(Cell::get))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwards_the_three_graphics_apertures_excluding_outer_msix() {
|
||||
let writes = Writes::default();
|
||||
let mut bus = Bus::new();
|
||||
let host = FakeHost {
|
||||
surface_pages: false,
|
||||
writes: Rc::clone(&writes),
|
||||
generation: None,
|
||||
};
|
||||
install(&mut bus, ADDRESSES, host).unwrap();
|
||||
let mut interrupts = InterruptLatch::new();
|
||||
let mut access = Access::new(0, 0, &mut interrupts);
|
||||
assert_eq!(bus.read(ADDRESSES.registers, Width::Word, &mut access), Ok(MAGIC));
|
||||
assert_eq!(bus.read(ADDRESSES.region + 256, Width::Word, &mut access), Ok(0x4433_2211));
|
||||
assert!(bus.write(ADDRESSES.registers + 32, Width::Word, 0, &mut access).is_ok());
|
||||
assert!(bus.write(ADDRESSES.region + 8, Width::Double, 16, &mut access).is_ok());
|
||||
assert!(bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 5, &mut access).is_ok());
|
||||
assert!(matches!(
|
||||
bus.write(ADDRESSES.registers + REGISTER_BYTES, Width::Word, 0, &mut access),
|
||||
Err(MmioError::Unmapped { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
bus.write(ADDRESSES.doorbells, Width::Byte, 1, &mut access),
|
||||
Err(MmioError::Unsupported { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
&*writes.borrow(),
|
||||
&[
|
||||
(Bar::Registers, 32, Width::Word, 0),
|
||||
(Bar::Region, 8, Width::Double, 16),
|
||||
(Bar::Doorbells, ARM_PAGE, Width::Word, 5),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_outer_ram_features_and_conflicts_before_mapping_any_aperture() {
|
||||
let mut bus = Bus::new();
|
||||
let host = |surface_pages| FakeHost {
|
||||
surface_pages,
|
||||
writes: Writes::default(),
|
||||
generation: None,
|
||||
};
|
||||
assert_eq!(install(&mut bus, ADDRESSES, host(true)), Err(InstallError::GuestRamFeatures));
|
||||
assert_eq!(bus.name_at(ADDRESSES.registers), None);
|
||||
let conflict = Apertures { doorbells: ADDRESSES.region, ..ADDRESSES };
|
||||
assert_eq!(
|
||||
install(&mut bus, conflict, host(false)),
|
||||
Err(InstallError::Mapping(MapError::ProposedOverlap))
|
||||
);
|
||||
assert_eq!(bus.name_at(ADDRESSES.registers), None);
|
||||
assert_eq!(bus.name_at(ADDRESSES.region), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_irq_ack_keeps_an_observed_completion_pending() {
|
||||
let generation = Rc::new(Cell::new(u32::MAX));
|
||||
let mut bus = Bus::new();
|
||||
let input = AicInput::new(0, 740);
|
||||
let host = FakeHost {
|
||||
surface_pages: false,
|
||||
writes: Writes::default(),
|
||||
generation: Some(Rc::clone(&generation)),
|
||||
};
|
||||
install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap();
|
||||
let mut latch = InterruptLatch::new();
|
||||
let token = ADDRESSES.registers + GUEST_IRQ_TOKEN;
|
||||
let mut access = Access::new(0, 0, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(IDLE_POLL_TICKS)));
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
|
||||
generation.set(0);
|
||||
let first_irq = IDLE_POLL_TICKS;
|
||||
let mut access = Access::new(0, first_irq, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(first_irq + ACTIVE_POLL_TICKS)));
|
||||
assert_eq!(bus.read(token, Width::Word, &mut access), Ok(0));
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]);
|
||||
|
||||
generation.set(1);
|
||||
let second_irq = first_irq + ACTIVE_POLL_TICKS;
|
||||
let mut access = Access::new(0, second_irq, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(second_irq + ACTIVE_POLL_TICKS)));
|
||||
bus.write(token, Width::Word, 0, &mut access).unwrap();
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
|
||||
let mut access = Access::new(0, second_irq, &mut latch);
|
||||
bus.write(token, Width::Word, 1, &mut access).unwrap();
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_irq_polling_runs_1ms_active_and_decays_to_5ms_idle() {
|
||||
let generation = Rc::new(Cell::new(0));
|
||||
let mut bus = Bus::new();
|
||||
let input = AicInput::new(0, 740);
|
||||
let host = FakeHost {
|
||||
surface_pages: false,
|
||||
writes: Writes::default(),
|
||||
generation: Some(Rc::clone(&generation)),
|
||||
};
|
||||
install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap();
|
||||
let mut latch = InterruptLatch::new();
|
||||
|
||||
// Initially idle: 5 ms cadence.
|
||||
let mut access = Access::new(0, 0, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(IDLE_POLL_TICKS)));
|
||||
|
||||
// A doorbell write pulls next_poll in to 1 ms and opens the 50 ms active window.
|
||||
let doorbell_at = 10_000;
|
||||
let mut access = Access::new(0, doorbell_at, &mut latch);
|
||||
bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 1, &mut access).unwrap();
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(doorbell_at + ACTIVE_POLL_TICKS)));
|
||||
|
||||
// Stays at 1 ms cadence throughout the active window.
|
||||
let mut t = doorbell_at + ACTIVE_POLL_TICKS;
|
||||
while t < doorbell_at + ACTIVE_WINDOW_TICKS {
|
||||
let mut access = Access::new(0, t, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(t + ACTIVE_POLL_TICKS)));
|
||||
t += ACTIVE_POLL_TICKS;
|
||||
}
|
||||
|
||||
// At active_until (50 ms elapsed), cadence decays back to 5 ms idle.
|
||||
let mut access = Access::new(0, doorbell_at + ACTIVE_WINDOW_TICKS, &mut latch);
|
||||
assert_eq!(
|
||||
bus.advance(&mut access),
|
||||
Ok(Some(doorbell_at + ACTIVE_WINDOW_TICKS + IDLE_POLL_TICKS))
|
||||
);
|
||||
|
||||
// An observed IRQ generation change also switches back to 1 ms cadence.
|
||||
let irq_at = doorbell_at + ACTIVE_WINDOW_TICKS + IDLE_POLL_TICKS;
|
||||
generation.set(1);
|
||||
let mut access = Access::new(0, irq_at, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(irq_at + ACTIVE_POLL_TICKS)));
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_driven_waits_for_signal_or_safety_timer_and_tracks_metrics() {
|
||||
struct EventHost {
|
||||
generation: Rc<Cell<u32>>,
|
||||
signals: Rc<Cell<u64>>,
|
||||
polls: Rc<Cell<u64>>,
|
||||
}
|
||||
impl Transport for EventHost {
|
||||
fn read(&mut self, bar: Bar, offset: u64, _: Width) -> Result<u64, Refusal> {
|
||||
match (bar, offset) {
|
||||
(Bar::Registers, 0) => Ok(MAGIC),
|
||||
(Bar::Registers, 4) => Ok(VERSION),
|
||||
(Bar::Registers, 8) => Ok(0),
|
||||
(Bar::Registers, 12) => Ok(DOORBELL_PAGES_HI),
|
||||
(Bar::Registers, 20) => Ok(REGION_BYTES),
|
||||
(Bar::Registers, 24) => Ok(0),
|
||||
_ => Ok(0),
|
||||
}
|
||||
}
|
||||
fn write(&mut self, _: Bar, _: u64, _: Width, _: u64) -> Result<(), Refusal> {
|
||||
Ok(())
|
||||
}
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
self.polls.set(self.polls.get() + 1);
|
||||
Ok(Some(self.generation.get()))
|
||||
}
|
||||
fn event_driven(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn signal_count(&self) -> u64 {
|
||||
self.signals.get()
|
||||
}
|
||||
}
|
||||
|
||||
let mut bus = Bus::new();
|
||||
let input = AicInput::new(0, 45);
|
||||
let generation = Rc::new(Cell::new(0));
|
||||
let signals = Rc::new(Cell::new(0));
|
||||
let polls = Rc::new(Cell::new(0));
|
||||
let metrics = Arc::new(IrqMetrics::new());
|
||||
let host = EventHost {
|
||||
generation: generation.clone(),
|
||||
signals: signals.clone(),
|
||||
polls: polls.clone(),
|
||||
};
|
||||
install_with_interrupt_metrics(&mut bus, ADDRESSES, host, input, metrics.clone()).unwrap();
|
||||
let mut latch = InterruptLatch::new();
|
||||
|
||||
// Install read generation once; at t=0 timer_due fires initial safety poll -> next_poll = 100 ms.
|
||||
assert_eq!(polls.get(), 1);
|
||||
let mut access = Access::new(0, 0, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(EVENT_SAFETY_POLL_TICKS)));
|
||||
assert_eq!(polls.get(), 2);
|
||||
|
||||
// Doorbell write in event-driven mode does not shrink next_poll to 1 ms.
|
||||
let mut access = Access::new(0, 10_000, &mut latch);
|
||||
bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 1, &mut access).unwrap();
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(EVENT_SAFETY_POLL_TICKS)));
|
||||
assert_eq!(polls.get(), 2);
|
||||
|
||||
// Signal bump triggers immediate poll even far before EVENT_SAFETY_POLL_TICKS.
|
||||
generation.set(2);
|
||||
signals.set(1);
|
||||
let irq_at = 25_000;
|
||||
let mut access = Access::new(0, irq_at, &mut latch);
|
||||
assert_eq!(bus.advance(&mut access), Ok(Some(irq_at + EVENT_SAFETY_POLL_TICKS)));
|
||||
assert_eq!(polls.get(), 3);
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]);
|
||||
|
||||
// Guest reads token, writes stale ack, then writes matching ack.
|
||||
let ack_at = 27_400;
|
||||
let mut access = Access::new(0, ack_at, &mut latch);
|
||||
assert_eq!(bus.read(ADDRESSES.registers + GUEST_IRQ_TOKEN, Width::Word, &mut access), Ok(2));
|
||||
bus.write(ADDRESSES.registers + GUEST_IRQ_TOKEN, Width::Word, 1, &mut access).unwrap();
|
||||
assert!(latch.take_aic_inputs().is_empty());
|
||||
let mut access = Access::new(0, ack_at, &mut latch);
|
||||
bus.write(ADDRESSES.registers + GUEST_IRQ_TOKEN, Width::Word, 2, &mut access).unwrap();
|
||||
assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, false)]);
|
||||
|
||||
let stats = metrics.snapshot();
|
||||
assert!(stats.event_driven);
|
||||
assert_eq!(stats.seen, 2);
|
||||
assert_eq!(stats.polls, 2);
|
||||
assert_eq!(stats.msi_wakes, 1);
|
||||
assert_eq!(stats.fallback_polls, 1);
|
||||
assert_eq!(stats.injects, 1);
|
||||
assert_eq!(stats.coalesced, 1);
|
||||
assert_eq!(stats.token_reads, 1);
|
||||
assert_eq!(stats.acks, 1);
|
||||
assert_eq!(stats.stale_acks, 1);
|
||||
assert_eq!(stats.ack_lat_samples, 1);
|
||||
assert_eq!(stats.ack_lat_sum_ticks, 2_400);
|
||||
assert_eq!(stats.ack_lat_max_ticks, 2_400);
|
||||
assert_eq!(stats.first_inject_ticks, irq_at);
|
||||
assert_eq!(stats.first_ack_ticks, ack_at);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! A manual integration fixture for a realized, paused x86 QEMU Reims device.
|
||||
#![cfg(feature = "std")]
|
||||
|
||||
use std::{
|
||||
env,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{SocketAddr, TcpStream},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use stela_contracts::{
|
||||
Refusal,
|
||||
bus::{Access, Bus, Width},
|
||||
interrupt::InterruptLatch,
|
||||
reims_hosted::{self, Apertures, Bar, Transport},
|
||||
};
|
||||
|
||||
struct Qtest {
|
||||
stream: BufReader<TcpStream>,
|
||||
bases: [u64; 3],
|
||||
}
|
||||
|
||||
impl Qtest {
|
||||
fn address(&self, bar: Bar, offset: u64) -> Result<u64, Refusal> {
|
||||
let index = match bar {
|
||||
Bar::Registers => 0,
|
||||
Bar::Region => 1,
|
||||
Bar::Doorbells => 2,
|
||||
};
|
||||
self.bases[index]
|
||||
.checked_add(offset)
|
||||
.ok_or_else(|| Refusal::new("QTest address overflow"))
|
||||
}
|
||||
|
||||
fn request(&mut self, command: &str) -> Result<Option<u64>, Refusal> {
|
||||
writeln!(self.stream.get_mut(), "{command}")
|
||||
.map_err(|_| Refusal::new("could not write QTest command"))?;
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
if self.stream.read_line(&mut line).map_err(|_| Refusal::new("QTest response failed"))? == 0
|
||||
{
|
||||
return Err(Refusal::new("QTest connection closed"));
|
||||
}
|
||||
let mut words = line.split_whitespace();
|
||||
match words.next() {
|
||||
Some("IRQ") => continue,
|
||||
Some("OK") => {
|
||||
return words
|
||||
.next()
|
||||
.map(|word| {
|
||||
u64::from_str_radix(word.trim_start_matches("0x"), 16)
|
||||
.map_err(|_| Refusal::new("invalid QTest value"))
|
||||
})
|
||||
.transpose();
|
||||
}
|
||||
_ => return Err(stela_contracts::refuse!("QTest rejected the request", command, line)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn suffix(width: Width) -> &'static str {
|
||||
match width {
|
||||
Width::Byte => "b",
|
||||
Width::Half => "w",
|
||||
Width::Word => "l",
|
||||
Width::Double => "q",
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Qtest {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal> {
|
||||
let addr = self.address(bar, offset)?;
|
||||
self.request(&format!("read{} {addr:#x}", suffix(width)))?
|
||||
.ok_or_else(|| Refusal::new("QTest read returned no value"))
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
let addr = self.address(bar, offset)?;
|
||||
self.request(&format!("write{} {addr:#x} {value:#x}", suffix(width))).map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_env(name: &str) -> u64 {
|
||||
u64::from_str_radix(env::var(name).unwrap().trim_start_matches("0x"), 16).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a paused hosted Reims QEMU fixture"]
|
||||
fn arm_guest_apertures_carry_a_display_query_to_reims() {
|
||||
let addr: SocketAddr = env::var("STELA_REIMS_QTEST").unwrap().parse().unwrap();
|
||||
assert!(addr.ip().is_loopback());
|
||||
let stream = TcpStream::connect_timeout(&addr, Duration::from_secs(3)).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut host = Qtest {
|
||||
stream: BufReader::new(stream),
|
||||
bases: [
|
||||
hex_env("STELA_REIMS_PCI_BAR0"),
|
||||
hex_env("STELA_REIMS_PCI_BAR2"),
|
||||
hex_env("STELA_REIMS_PCI_BAR4"),
|
||||
],
|
||||
};
|
||||
let pci_config = 0x8000_2000u32;
|
||||
host.request(&format!("outl 0xcf8 {pci_config:#x}")).unwrap();
|
||||
assert_eq!(host.request("inl 0xcfc").unwrap(), Some(0x5247_1234));
|
||||
let [bar0, bar2, bar4] = host.bases;
|
||||
for (offset, value) in [(0x10, bar0), (0x18, bar2 & 0xffff_ffff), (0x1c, bar2 >> 32), (0x20, bar4)] {
|
||||
host.request(&format!("outl 0xcf8 {:#x}", pci_config + offset)).unwrap();
|
||||
host.request(&format!("outl 0xcfc {value:#x}")).unwrap();
|
||||
}
|
||||
host.request(&format!("outl 0xcf8 {:#x}", pci_config + 4)).unwrap();
|
||||
host.request("outw 0xcfc 0x2").unwrap();
|
||||
// These ARM physical addresses are intentionally different from the host's BARs.
|
||||
let arm = Apertures {
|
||||
registers: 0x2000_0000,
|
||||
region: 0x4000_0000,
|
||||
doorbells: 0x8040_0000,
|
||||
};
|
||||
let mut bus = Bus::new();
|
||||
reims_hosted::install(&mut bus, arm, host).unwrap();
|
||||
let mut interrupts = InterruptLatch::new();
|
||||
let mut access = Access::new(0, 0, &mut interrupts);
|
||||
assert_eq!(bus.read(arm.registers, Width::Word, &mut access).unwrap(), 1481000786);
|
||||
assert!(bus.read(arm.registers + 2048, Width::Word, &mut access).is_err());
|
||||
assert_eq!(bus.read(arm.doorbells, Width::Word, &mut access).unwrap(), 0);
|
||||
|
||||
// Wire v2: a 16-byte GET_DISPLAYS header, then publish its ring producer.
|
||||
let submit = arm.region + 256;
|
||||
let complete = arm.region + 65536;
|
||||
assert_eq!(bus.read(complete, Width::Double, &mut access).unwrap(), 0);
|
||||
bus.write(arm.registers + 16, Width::Word, 1, &mut access).unwrap();
|
||||
bus.write(submit, Width::Word, 1, &mut access).unwrap();
|
||||
bus.write(submit + 4, Width::Word, 16, &mut access).unwrap();
|
||||
bus.write(submit + 8, Width::Double, 1, &mut access).unwrap();
|
||||
bus.write(arm.region, Width::Double, 16, &mut access).unwrap();
|
||||
bus.write(arm.registers + 32, Width::Word, 0, &mut access).unwrap();
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while bus.read(complete, Width::Double, &mut access).unwrap() == 0 {
|
||||
assert!(Instant::now() < until, "Reims did not reply to GET_DISPLAYS");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(bus.read(complete + 256, Width::Word, &mut access).unwrap(), 257);
|
||||
assert_eq!(bus.read(complete + 264, Width::Double, &mut access).unwrap(), 1);
|
||||
assert_eq!(bus.read(complete + 272, Width::Word, &mut access).unwrap(), 1);
|
||||
println!("ARM guest addresses carried GET_DISPLAYS to the hosted device and received one display");
|
||||
}
|
||||
@@ -354,12 +354,13 @@ impl Linux {
|
||||
common_environment.profile(&mut common_build, None, &[], None);
|
||||
let mut common_build = upstream_build(&common_build, Path::new("src/compat"));
|
||||
upstream_warnings(&mut common_build);
|
||||
let registration = Path::new("src/compat").join("stela/registration.h");
|
||||
let common_profiles = COMMON
|
||||
.iter()
|
||||
.map(|spec| {
|
||||
linux_capture::profile(
|
||||
&common_build,
|
||||
Path::new("src/compat/stela/registration.h"),
|
||||
®istration,
|
||||
*spec,
|
||||
Path::new("../stela-linux"),
|
||||
)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
../../../../third_party/mesa
|
||||
@@ -42,6 +42,7 @@ mod power;
|
||||
#[cfg(feature = "native-acpi")]
|
||||
pub use power::{EmbeddedControllerInstallation, Power, install_embedded_controller};
|
||||
pub mod native;
|
||||
pub mod reims_hosted;
|
||||
#[cfg(any(test, feature = "native-acpi"))]
|
||||
mod platform;
|
||||
pub mod services;
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Host PCI access for the copy-only Reims ARM64 transport.
|
||||
use super::{NativeServices, services::claim_unmastered};
|
||||
use crate::bus::{
|
||||
irq::MsiMessage,
|
||||
mmio::owned::Mapping,
|
||||
pci::{self, Address, Function, owned::OwnedConfig, requester::preparation::Attachment},
|
||||
};
|
||||
use core::ptr::NonNull;
|
||||
use stela_contracts::{
|
||||
Refusal,
|
||||
bus::Width,
|
||||
refuse,
|
||||
reims_hosted::{
|
||||
self, Bar, DOORBELL_BYTES, HOST_CONTROL_MIN_OFFSET, HOST_IRQ_GENERATION_OFFSET,
|
||||
HOST_IRQ_SIGNATURE, HOST_IRQ_SIGNATURE_OFFSET, HOST_RAM_BYTES_HI_OFFSET,
|
||||
HOST_RAM_BYTES_LO_OFFSET, HOST_RAM_CMD_ADD, HOST_RAM_CMD_CLEAR, HOST_RAM_CMD_COMMIT,
|
||||
HOST_RAM_CMD_OFFSET, HOST_RAM_GUEST_PA_HI_OFFSET, HOST_RAM_GUEST_PA_LO_OFFSET,
|
||||
HOST_RAM_HOST_GPA_HI_OFFSET, HOST_RAM_HOST_GPA_LO_OFFSET, HOST_RAM_SIGNATURE,
|
||||
HOST_RAM_SIGNATURE_OFFSET, REGION_BYTES, REGISTER_BYTES, Transport,
|
||||
},
|
||||
};
|
||||
|
||||
pub const VENDOR: u16 = 0x1234;
|
||||
pub const DEVICE: u16 = 0x5247;
|
||||
// The physical BAR includes MSI-X data above the wire's register window.
|
||||
const REGISTER_BAR_BYTES: u64 = 4096;
|
||||
|
||||
/// The host function and its uncached BAR mappings. The original PCI owner
|
||||
/// keeps bus mastering sealed off. MSI-X is not part of this transport.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct GpuSignal {
|
||||
pub message: MsiMessage,
|
||||
pub counter: fn() -> u64,
|
||||
}
|
||||
|
||||
pub struct PciTransport {
|
||||
registers: Mapping,
|
||||
region: Option<Mapping>,
|
||||
region_base: u64,
|
||||
doorbells: Mapping,
|
||||
hosted_irq: bool,
|
||||
guest_ram_mapped: bool,
|
||||
event_signal: Option<fn() -> u64>,
|
||||
_attachment: Option<Attachment>,
|
||||
_function: Function<OwnedConfig>,
|
||||
}
|
||||
|
||||
impl PciTransport {
|
||||
pub fn open(services: &dyn NativeServices, address: Address) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, None, None)
|
||||
}
|
||||
|
||||
pub fn open_with_signal(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
signal: Option<GpuSignal>,
|
||||
) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, None, signal)
|
||||
}
|
||||
|
||||
/// Open the host PCI function while leaving BAR2 unmapped in the uncached
|
||||
/// MMIO aperture because the loader already mapped BAR2 write-back into
|
||||
/// guest physical RAM at `expected_region`.
|
||||
pub fn open_direct_region(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
expected_region: u64,
|
||||
) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, Some(expected_region), None)
|
||||
}
|
||||
|
||||
pub fn open_direct_region_with_signal(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
expected_region: u64,
|
||||
signal: Option<GpuSignal>,
|
||||
) -> Result<Self, Refusal> {
|
||||
Self::open_inner(services, address, Some(expected_region), signal)
|
||||
}
|
||||
|
||||
fn open_inner(
|
||||
services: &dyn NativeServices,
|
||||
address: Address,
|
||||
direct_region: Option<u64>,
|
||||
signal: Option<GpuSignal>,
|
||||
) -> Result<Self, Refusal> {
|
||||
let (attachment, mut function) = if signal.is_some() {
|
||||
let preparing = services
|
||||
.prepare_requester(address)
|
||||
.map_err(|error| refuse!("Reims PCI preparation: {error}", %error))?;
|
||||
// SAFETY: Bus Master, MSI, MSI-X, and INTx are disabled while
|
||||
// parked; hosted Reims performs no DMA or MSI-X before guest
|
||||
// doorbells are written after device attachment.
|
||||
let bound = unsafe { preparing.acknowledge_quiescence() }
|
||||
.finalize()
|
||||
.map_err(|failure| {
|
||||
let error = failure.error;
|
||||
core::mem::forget(failure);
|
||||
refuse!("Reims PCI requester bind: {error}", %error)
|
||||
})?;
|
||||
(Some(bound.attachment), bound.requester.into_function())
|
||||
} else {
|
||||
let requester = claim_unmastered(services, address)
|
||||
.map_err(|error| refuse!("Reims PCI ownership: {error}", %error))?;
|
||||
(None, requester.into_function())
|
||||
};
|
||||
if function.vendor != VENDOR || function.device != DEVICE {
|
||||
return Err(refuse!("Reims PCI identity changed after enumeration"));
|
||||
}
|
||||
let bars = function.bars().map_err(|error| refuse!("Reims PCI BARs: {error}", %error))?;
|
||||
let memory = |index: usize, bytes: u64| {
|
||||
let Some(bar @ pci::Bar::Memory { .. }) = bars[index] else {
|
||||
return Err(refuse!("Reims PCI BAR {index} is not memory", index));
|
||||
};
|
||||
let span = bar
|
||||
.memory()
|
||||
.ok_or_else(|| refuse!("Reims PCI BAR {index} is unassigned", index))?;
|
||||
if span.start == 0 || span.end - span.start != bytes {
|
||||
return Err(refuse!("Reims PCI BAR {index} has unexpected geometry", index));
|
||||
}
|
||||
Ok((bar, span.start))
|
||||
};
|
||||
let (registers, _) = memory(0, REGISTER_BAR_BYTES)?;
|
||||
let (region_bar, region_base) = memory(2, REGION_BYTES)?;
|
||||
let (doorbells, _) = memory(4, DOORBELL_BYTES)?;
|
||||
let map = |index, bar| {
|
||||
services
|
||||
.map_bar(address, bar)
|
||||
.map_err(|error| refuse!("Reims PCI BAR {index}: {error}", index, %error))
|
||||
};
|
||||
let registers = map(0, registers)?;
|
||||
let region = match direct_region {
|
||||
Some(expected) => {
|
||||
if region_base != expected {
|
||||
return Err(refuse!(
|
||||
"Reims PCI BAR 2 moved after firmware capture ({region_base:#x} != {expected:#x})",
|
||||
region_base,
|
||||
expected
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
None => Some(map(2, region_bar)?),
|
||||
};
|
||||
let doorbells = map(4, doorbells)?;
|
||||
function
|
||||
.enable_polled_decode()
|
||||
.map_err(|error| refuse!("Reims PCI memory decoding: {error}", ?error))?;
|
||||
let hosted_irq = doorbells
|
||||
.read32(HOST_IRQ_SIGNATURE_OFFSET as usize)
|
||||
.map_err(|error| refuse!("Reims host IRQ signature: {error}", ?error))?
|
||||
== HOST_IRQ_SIGNATURE;
|
||||
let event_signal = if let Some(GpuSignal { message, counter }) = signal {
|
||||
if !hosted_irq {
|
||||
return Err(refuse!("Reims host IRQ signature absent for MSI-X event mode"));
|
||||
}
|
||||
let interrupts = function
|
||||
.interrupts()
|
||||
.map_err(|error| refuse!("Reims PCI interrupts: {error}", ?error))?;
|
||||
let msix = interrupts
|
||||
.msix
|
||||
.ok_or_else(|| refuse!("Reims PCI device lacks MSI-X capability"))?;
|
||||
if msix.table_bar != 0
|
||||
|| msix.vectors < 1
|
||||
|| u64::from(msix.table_offset) < REGISTER_BYTES
|
||||
|| u64::from(msix.table_offset).saturating_add(16) > REGISTER_BAR_BYTES
|
||||
{
|
||||
return Err(refuse!("Reims PCI MSI-X table geometry unsupported"));
|
||||
}
|
||||
let table_offset = msix.table_offset as usize;
|
||||
function
|
||||
.enable_bus_master()
|
||||
.map_err(|error| refuse!("Reims PCI bus master: {error}", ?error))?;
|
||||
function
|
||||
.enable_msix(msix, || {
|
||||
let map_err = |_| crate::block::BlockError::Protocol("Reims MSI-X table write");
|
||||
registers.write32(table_offset, message.address as u32).map_err(map_err)?;
|
||||
registers
|
||||
.write32(table_offset + 4, (message.address >> 32) as u32)
|
||||
.map_err(map_err)?;
|
||||
registers.write32(table_offset + 8, message.data).map_err(map_err)?;
|
||||
registers.write32(table_offset + 12, 0).map_err(map_err)?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|error| refuse!("Reims PCI MSI-X enable: {error}", ?error))?;
|
||||
Some(counter)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut transport = Self {
|
||||
registers,
|
||||
region,
|
||||
region_base,
|
||||
doorbells,
|
||||
hosted_irq,
|
||||
guest_ram_mapped: false,
|
||||
event_signal,
|
||||
_attachment: attachment,
|
||||
_function: function,
|
||||
};
|
||||
reims_hosted::validate_wire(&mut transport)
|
||||
.map_err(|error| refuse!("Reims graphics wire: {error}", ?error))?;
|
||||
Ok(transport)
|
||||
}
|
||||
|
||||
/// Verify the mapped wire and report its host apertures in a diagnostic boot.
|
||||
pub fn probe(services: &dyn NativeServices, address: Address) -> Result<[u64; 3], Refusal> {
|
||||
let mut transport = Self::open(services, address)?;
|
||||
let bases = transport.bases();
|
||||
if let Some(region) = &mut transport.region {
|
||||
// SAFETY: this transport has only read its wire registers; no
|
||||
// driver, callback or raw pointer can still access the mapping.
|
||||
unsafe { region.retire() }
|
||||
.map_err(|error| refuse!("retire Reims PCI BAR: {error}", ?error))?;
|
||||
}
|
||||
for mapping in [&mut transport.doorbells, &mut transport.registers] {
|
||||
// SAFETY: this transport has only read its wire registers; no
|
||||
// driver, callback or raw pointer can still access the mapping.
|
||||
unsafe { mapping.retire() }
|
||||
.map_err(|error| refuse!("retire Reims PCI BAR: {error}", ?error))?;
|
||||
}
|
||||
bases
|
||||
}
|
||||
|
||||
pub fn bases(&self) -> Result<[u64; 3], Refusal> {
|
||||
let base = |mapping: &Mapping| {
|
||||
mapping
|
||||
.physical_span()
|
||||
.map(|span| span.start())
|
||||
.map_err(|error| refuse!("Reims PCI BAR mapping: {error}", ?error))
|
||||
};
|
||||
let region = match &self.region {
|
||||
Some(mapping) => base(mapping)?,
|
||||
None => self.region_base,
|
||||
};
|
||||
Ok([base(&self.registers)?, region, base(&self.doorbells)?])
|
||||
}
|
||||
|
||||
/// Publish the inner ARM64 guest DRAM `(guest_pa, host_gpa, bytes)` ranges to
|
||||
/// outer QEMU's `reims-graphics-pci` BAR4 RMAP mailbox to enable zero-copy
|
||||
/// `RGFX_FEATURE_SURFACE_PAGES`. Returns `Ok(None)` on older QEMU without RMAP.
|
||||
pub fn publish_guest_ram(&mut self, ranges: &[(u64, u64, u64)]) -> Result<Option<u32>, Refusal> {
|
||||
let sig = self
|
||||
.doorbells
|
||||
.read32(HOST_RAM_SIGNATURE_OFFSET as usize)
|
||||
.map_err(|error| refuse!("Reims RMAP signature: {error}", ?error))?;
|
||||
if sig != HOST_RAM_SIGNATURE {
|
||||
return Ok(None);
|
||||
}
|
||||
let write32 = |off: u64, val: u32| -> Result<(), Refusal> {
|
||||
self.doorbells
|
||||
.write32(off as usize, val)
|
||||
.map_err(|error| refuse!("Reims RMAP write: {error}", ?error))
|
||||
};
|
||||
write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_CLEAR)?;
|
||||
for &(guest_pa, host_gpa, bytes) in ranges {
|
||||
if bytes == 0 {
|
||||
continue;
|
||||
}
|
||||
write32(HOST_RAM_GUEST_PA_LO_OFFSET, guest_pa as u32)?;
|
||||
write32(HOST_RAM_GUEST_PA_HI_OFFSET, (guest_pa >> 32) as u32)?;
|
||||
write32(HOST_RAM_HOST_GPA_LO_OFFSET, host_gpa as u32)?;
|
||||
write32(HOST_RAM_HOST_GPA_HI_OFFSET, (host_gpa >> 32) as u32)?;
|
||||
write32(HOST_RAM_BYTES_LO_OFFSET, bytes as u32)?;
|
||||
write32(HOST_RAM_BYTES_HI_OFFSET, (bytes >> 32) as u32)?;
|
||||
write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_ADD)?;
|
||||
}
|
||||
write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_COMMIT)?;
|
||||
let committed = self
|
||||
.doorbells
|
||||
.read32(HOST_RAM_CMD_OFFSET as usize)
|
||||
.map_err(|error| refuse!("Reims RMAP status: {error}", ?error))?;
|
||||
self.guest_ram_mapped = committed > 0;
|
||||
Ok(Some(committed))
|
||||
}
|
||||
|
||||
fn address(&self, bar: Bar, offset: u64, width: Width) -> Result<NonNull<u8>, Refusal> {
|
||||
let (mapping, limit) = match bar {
|
||||
Bar::Registers => (&self.registers, REGISTER_BYTES),
|
||||
Bar::Region => (
|
||||
self.region
|
||||
.as_ref()
|
||||
.ok_or_else(|| refuse!("Reims PCI BAR 2 is direct-mapped RAM"))?,
|
||||
REGION_BYTES,
|
||||
),
|
||||
Bar::Doorbells => (&self.doorbells, DOORBELL_BYTES),
|
||||
};
|
||||
let bytes = width.bytes();
|
||||
if !offset.is_multiple_of(bytes)
|
||||
|| offset.checked_add(bytes).is_none_or(|end| end > limit)
|
||||
|| (bar != Bar::Region && width != Width::Word)
|
||||
{
|
||||
return Err(refuse!("Reims PCI access outside its aligned aperture"));
|
||||
}
|
||||
mapping
|
||||
.address(offset as usize, bytes as usize)
|
||||
.map_err(|error| refuse!("Reims PCI BAR access: {error}", ?error))
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for PciTransport {
|
||||
fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result<u64, Refusal> {
|
||||
let address = self.address(bar, offset, width)?;
|
||||
if bar == Bar::Doorbells && offset >= HOST_CONTROL_MIN_OFFSET {
|
||||
return Ok(0);
|
||||
}
|
||||
// SAFETY: the live uncached mapping covers this naturally aligned
|
||||
// access. The transport has the only owner that can access the BAR.
|
||||
Ok(unsafe {
|
||||
match width {
|
||||
Width::Byte => u64::from(address.read_volatile()),
|
||||
Width::Half => u64::from(u16::from_le(address.cast::<u16>().read_volatile())),
|
||||
Width::Word => u64::from(u32::from_le(address.cast::<u32>().read_volatile())),
|
||||
Width::Double => u64::from_le(address.cast::<u64>().read_volatile()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> {
|
||||
if bar == Bar::Doorbells && offset >= HOST_CONTROL_MIN_OFFSET {
|
||||
return Ok(());
|
||||
}
|
||||
let address = self.address(bar, offset, width)?;
|
||||
// SAFETY: as for read; the uncached x86 mapping orders the accesses
|
||||
// to the ring before a subsequent MMIO doorbell.
|
||||
unsafe {
|
||||
match width {
|
||||
Width::Byte => address.write_volatile(value as u8),
|
||||
Width::Half => address.cast::<u16>().write_volatile((value as u16).to_le()),
|
||||
Width::Word => address.cast::<u32>().write_volatile((value as u32).to_le()),
|
||||
Width::Double => address.cast::<u64>().write_volatile(value.to_le()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn interrupt_generation(&mut self) -> Result<Option<u32>, Refusal> {
|
||||
if !self.hosted_irq {
|
||||
return Ok(None);
|
||||
}
|
||||
self.doorbells
|
||||
.read32(HOST_IRQ_GENERATION_OFFSET as usize)
|
||||
.map(Some)
|
||||
.map_err(|error| refuse!("Reims host IRQ generation: {error}", ?error))
|
||||
}
|
||||
|
||||
fn guest_ram_mapped(&self) -> bool {
|
||||
self.guest_ram_mapped
|
||||
}
|
||||
|
||||
fn event_driven(&self) -> bool {
|
||||
self.event_signal.is_some()
|
||||
}
|
||||
|
||||
fn signal_count(&self) -> u64 {
|
||||
self.event_signal.map_or(0, |counter| counter())
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ workspace = true
|
||||
default = ["std"]
|
||||
test-support = ["stela-compiler/test-support"]
|
||||
native-profile = ["stela-contracts/native-profile"]
|
||||
std = ["serde/std", "serde_json/std", "stela-compiler/std", "stela-contracts/std", "stela-formats/std", "dep:tempfile", "dep:libc"]
|
||||
std = ["serde/std", "serde_json/std", "stela-compiler/std", "stela-contracts/std", "stela-formats/std", "dep:tempfile", "dep:libc", "dep:windows-sys"]
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
@@ -32,6 +32,13 @@ stela-formats = { path = "../stela-formats", default-features = false }
|
||||
[build-dependencies]
|
||||
stela-fingerprint = { path = "../stela-fingerprint" }
|
||||
|
||||
[target.'cfg(all(windows, target_arch = "x86_64"))'.dependencies]
|
||||
windows-sys = { version = "0.61", optional = true, features = [
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow.workspace = true
|
||||
stela-compiler = { path = "../stela-compiler", features = ["test-support"] }
|
||||
|
||||
@@ -7,9 +7,15 @@ pub mod checked_memory;
|
||||
pub(crate) mod context;
|
||||
#[cfg(feature = "std")]
|
||||
pub(crate) mod floating_environment;
|
||||
#[cfg(all(host_memory, target_arch = "x86_64"))]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(host_memory, all(windows, feature = "std"))
|
||||
))]
|
||||
mod native_image;
|
||||
#[cfg(all(host_memory, target_arch = "x86_64"))]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(host_memory, all(windows, feature = "std"))
|
||||
))]
|
||||
pub(crate) use native_image::ReachedCall as ObservedNativeCall;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
@@ -2,20 +2,36 @@
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", target_os = "uefi", not(feature = "std")))]
|
||||
mod freestanding;
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
mod posix;
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
feature = "std",
|
||||
any(windows, target_os = "macos", target_os = "linux")
|
||||
))]
|
||||
mod hosted;
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")),
|
||||
all(
|
||||
target_arch = "x86_64",
|
||||
feature = "std",
|
||||
any(windows, target_os = "macos", target_os = "linux")
|
||||
),
|
||||
all(target_arch = "x86_64", target_os = "uefi", not(feature = "std"))
|
||||
)))]
|
||||
mod unsupported;
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", target_os = "uefi", not(feature = "std")))]
|
||||
pub use freestanding::*;
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
|
||||
pub use posix::*;
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
feature = "std",
|
||||
any(windows, target_os = "macos", target_os = "linux")
|
||||
))]
|
||||
pub use hosted::*;
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")),
|
||||
all(
|
||||
target_arch = "x86_64",
|
||||
feature = "std",
|
||||
any(windows, target_os = "macos", target_os = "linux")
|
||||
),
|
||||
all(target_arch = "x86_64", target_os = "uefi", not(feature = "std"))
|
||||
)))]
|
||||
pub use unsupported::*;
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Native code mappings in x86-64 host processes.
|
||||
#[cfg_attr(windows, path = "hosted/windows.rs")]
|
||||
#[cfg_attr(not(windows), path = "hosted/posix.rs")]
|
||||
mod memory;
|
||||
|
||||
use crate::Result;
|
||||
use crate::execution::native_image::{ExecutableStorage, NativeImage};
|
||||
use core::{convert::Infallible, ptr::NonNull};
|
||||
use stela_compiler::GuestState;
|
||||
use stela_contracts::require;
|
||||
|
||||
pub fn ensure_supported() -> Result<()> {
|
||||
// Every x86-64 CPU implements Stela's integer and SSE2 baseline.
|
||||
// Native calls explicitly use the compiler's System V ABI on every host.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Mapping {
|
||||
pointer: NonNull<u8>,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn new(bytes: &[u8]) -> Result<Self> {
|
||||
require!(!bytes.is_empty(), "cannot map empty native code");
|
||||
let mapping = Self {
|
||||
pointer: memory::allocate(bytes.len())?,
|
||||
length: bytes.len(),
|
||||
};
|
||||
// SAFETY: allocate returned at least length fresh RW bytes, disjoint from
|
||||
// the input Vec, and this mapping has not escaped.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(bytes.as_ptr(), mapping.pointer.as_ptr(), bytes.len());
|
||||
}
|
||||
// SAFETY: this is the full, initialized allocation, still uniquely
|
||||
// owned by mapping. Drop releases it if publication fails.
|
||||
unsafe { memory::protect_executable(mapping.pointer, mapping.length)? };
|
||||
Ok(mapping)
|
||||
}
|
||||
|
||||
/// Address of the owned RX mapping. It remains valid only while this
|
||||
/// mapping is held; using it requires the caller's native ABI and
|
||||
/// source/target/memory/fault contracts.
|
||||
pub fn entry(&self) -> usize {
|
||||
self.pointer.as_ptr() as usize
|
||||
}
|
||||
|
||||
/// Invoke this owned mapping with the compiler's leaf ABI.
|
||||
///
|
||||
/// # Safety
|
||||
/// The bytes must implement the leaf ABI for the admitted host
|
||||
/// target. The caller keeps exclusive guest state and every accessed
|
||||
/// memory/service owner through return and any fault settlement.
|
||||
pub unsafe fn call(&self, state: &mut GuestState) -> Result<()> {
|
||||
// SAFETY: the mapping is still owned and the caller upholds the
|
||||
// leaf ABI.
|
||||
let reached = match unsafe { NativeImage::borrow(self).call(state) } {
|
||||
Ok(reached) => reached,
|
||||
Err(never) => match never {},
|
||||
};
|
||||
reached.into_infallible();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Invoke this owned mapping with the compiler's context-block ABI.
|
||||
///
|
||||
/// # Safety
|
||||
/// The code, target, source map and context requirements must describe the
|
||||
/// same checked compilation. The caller keeps exclusive state, the live
|
||||
/// context and all reachable memory/service owners through return, context
|
||||
/// finalization and recovered source-PC settlement; entry cannot reenter.
|
||||
pub unsafe fn call_context_block(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
context: &mut stela_compiler::context::ExecutionContext,
|
||||
) -> Result<stela_compiler::block::BlockExit> {
|
||||
// SAFETY: the mapping and the block's context stay borrowed for
|
||||
// this synchronous call.
|
||||
let reached = match unsafe { self.call_context_block_observed(state, context) } {
|
||||
Ok(reached) => reached,
|
||||
Err(never) => match never {},
|
||||
};
|
||||
Ok(reached.into_infallible())
|
||||
}
|
||||
|
||||
/// Call the two-argument context-leaf ABI. Architectural failures are
|
||||
/// recorded in the memory view, never inferred from RAX.
|
||||
/// # Safety
|
||||
/// The bytes must implement the two-argument context-leaf ABI for the
|
||||
/// admitted target. The caller keeps exclusive state and a valid
|
||||
/// context with all borrowed memory/service owners until call completion
|
||||
/// and architectural failure finalization. No callback may reenter them.
|
||||
pub unsafe fn call_context(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
context: &mut stela_compiler::context::ExecutionContext,
|
||||
) -> Result<()> {
|
||||
// SAFETY: The context entry owns the checked source/profile and
|
||||
// validates its live borrowed views before this synchronous call.
|
||||
let function: unsafe extern "sysv64" fn(
|
||||
*mut GuestState,
|
||||
*mut stela_compiler::context::ExecutionContext,
|
||||
) = unsafe { core::mem::transmute(self.pointer.as_ptr()) };
|
||||
// SAFETY: the caller upholds `call_context`'s contract above.
|
||||
unsafe { function(state, context) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keep the native result alongside the storage check. Err is a refusal
|
||||
/// before the call; the borrowed RX allocation stays live across it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The source, native code, ABI, map, requirements and context must be
|
||||
/// bound. A PE may call only from its session, which holds the thread,
|
||||
/// system state, backend, source and domain through this call, the
|
||||
/// context finalization and PC settlement.
|
||||
pub(crate) unsafe fn call_context_block_observed(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
context: &mut stela_compiler::context::ExecutionContext,
|
||||
) -> core::result::Result<
|
||||
crate::execution::ObservedNativeCall<stela_compiler::block::BlockExit, Infallible>,
|
||||
Infallible,
|
||||
> {
|
||||
// SAFETY: the mapping stays borrowed, and the caller upholds the
|
||||
// execution contract.
|
||||
unsafe { NativeImage::borrow(self).call_context_block(state, context) }
|
||||
}
|
||||
|
||||
/// Call the resident-budget block ABI. The budget bounds execution.
|
||||
///
|
||||
/// # Safety
|
||||
/// The caller binds the source, ABI, target and register bank. Resident
|
||||
/// loops are non-faulting integer code; a fallback has the ordinary
|
||||
/// call's memory, fault and target requirements. Not for asynchronous
|
||||
/// producer domains or checked, system or threaded entry.
|
||||
pub unsafe fn call_budgeted_block(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
budget: &mut stela_compiler::block::loop_budget::LoopBudget,
|
||||
) -> Result<stela_compiler::block::BlockExit> {
|
||||
// SAFETY: the mapping, register bank and budget stay borrowed
|
||||
// through the call.
|
||||
let reached = match unsafe { NativeImage::borrow(self).call_budgeted_block(state, budget) }
|
||||
{
|
||||
Ok(reached) => reached,
|
||||
Err(never) => match never {},
|
||||
};
|
||||
Ok(reached.into_infallible())
|
||||
}
|
||||
|
||||
/// The native result and storage check for the one-pointer block ABI.
|
||||
/// The PE's session must hold its state, source and domain through
|
||||
/// settlement.
|
||||
pub(crate) unsafe fn call_block_observed(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
) -> core::result::Result<
|
||||
crate::execution::ObservedNativeCall<stela_compiler::block::BlockExit, Infallible>,
|
||||
Infallible,
|
||||
> {
|
||||
// SAFETY: the caller upholds the source, profile, ABI and map, and
|
||||
// the session contract.
|
||||
unsafe { NativeImage::borrow(self).call_block(state) }
|
||||
}
|
||||
|
||||
/// Invoke this owned mapping with the compiler's ordinary block ABI.
|
||||
///
|
||||
/// # Safety
|
||||
/// The bytes must implement the struct-return block ABI for the
|
||||
/// admitted target. Every directly addressed guest range must remain
|
||||
/// mapped with the compiled rights, and the caller keeps exclusive
|
||||
/// state, memory/fault owners and source identity through full settlement.
|
||||
pub unsafe fn call_block(
|
||||
&self,
|
||||
state: &mut GuestState,
|
||||
) -> Result<stela_compiler::block::BlockExit> {
|
||||
// SAFETY: the caller upholds the struct-return ABI and the
|
||||
// direct-RAM contract.
|
||||
let reached = match unsafe { self.call_block_observed(state) } {
|
||||
Ok(reached) => reached,
|
||||
Err(never) => match never {},
|
||||
};
|
||||
Ok(reached.into_infallible())
|
||||
}
|
||||
|
||||
/// Call the AMX kernel at `offset` in this library image.
|
||||
///
|
||||
/// # Safety
|
||||
/// As for `NativeImage::call_amx_kernel`.
|
||||
pub(crate) unsafe fn call_amx_kernel(
|
||||
&self,
|
||||
offset: usize,
|
||||
z: *mut u8,
|
||||
x: *const u8,
|
||||
y: *const u8,
|
||||
row: u64,
|
||||
) -> Result<()> {
|
||||
require!(
|
||||
offset < self.length,
|
||||
"AMX kernel offset outside its library"
|
||||
);
|
||||
// SAFETY: the mapping stays borrowed and the caller upholds the
|
||||
// kernel ABI.
|
||||
let reached =
|
||||
match unsafe { NativeImage::borrow(self).call_amx_kernel(offset, z, x, y, row) } {
|
||||
Ok(reached) => reached,
|
||||
Err(never) => match never {},
|
||||
};
|
||||
reached.into_infallible();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
pub fn address(&self) -> usize {
|
||||
self.pointer.as_ptr() as usize
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: Mapping::new exclusively owns fresh, initialized OS pages
|
||||
// transitioned to RX. Calls borrow self, keeping those pages live and
|
||||
// immutable until return. Raw entry users must uphold the same ownership.
|
||||
unsafe impl ExecutableStorage for Mapping {
|
||||
type Error = Infallible;
|
||||
fn entry(&self) -> NonNull<u8> {
|
||||
self.pointer
|
||||
}
|
||||
fn revalidate(&self) -> core::result::Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Mapping {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: this mapping uniquely owns the original allocation.
|
||||
unsafe { memory::release(self.pointer, self.length) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::{Result, error::Io};
|
||||
use core::ptr::NonNull;
|
||||
use stela_contracts::refuse;
|
||||
|
||||
pub(super) fn allocate(length: usize) -> Result<NonNull<u8>> {
|
||||
// SAFETY: request a new private mapping, checking the result before use.
|
||||
let pointer = unsafe {
|
||||
libc::mmap(
|
||||
core::ptr::null_mut(),
|
||||
length,
|
||||
libc::PROT_READ | libc::PROT_WRITE,
|
||||
libc::MAP_PRIVATE | libc::MAP_ANON,
|
||||
-1,
|
||||
0,
|
||||
)
|
||||
};
|
||||
if pointer == libc::MAP_FAILED {
|
||||
return Err(std::io::Error::last_os_error()).io("allocate RW native code");
|
||||
}
|
||||
let Some(mapping) = NonNull::new(pointer.cast()) else {
|
||||
// SAFETY: address zero was returned by a successful mmap above.
|
||||
unsafe { libc::munmap(pointer, length) };
|
||||
return Err(refuse!("OS returned an unusable null native mapping").into());
|
||||
};
|
||||
Ok(mapping)
|
||||
}
|
||||
|
||||
pub(super) unsafe fn protect_executable(pointer: NonNull<u8>, length: usize) -> Result<()> {
|
||||
// SAFETY: the caller uniquely owns this initialized allocation. On x86-64
|
||||
// instruction and data caches are coherent for the published mapping.
|
||||
let result = unsafe {
|
||||
libc::mprotect(
|
||||
pointer.as_ptr().cast(),
|
||||
length,
|
||||
libc::PROT_READ | libc::PROT_EXEC,
|
||||
)
|
||||
};
|
||||
if result != 0 {
|
||||
return Err(std::io::Error::last_os_error()).io("protect native code RX");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) unsafe fn release(pointer: NonNull<u8>, length: usize) {
|
||||
// SAFETY: the caller exclusively owns the original allocation.
|
||||
unsafe { libc::munmap(pointer.as_ptr().cast(), length) };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::{Result, error::Io};
|
||||
use core::ptr::NonNull;
|
||||
use windows_sys::Win32::System::{
|
||||
Diagnostics::Debug::FlushInstructionCache,
|
||||
Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc,
|
||||
VirtualFree, VirtualProtect,
|
||||
},
|
||||
Threading::GetCurrentProcess,
|
||||
};
|
||||
|
||||
pub(super) fn allocate(length: usize) -> Result<NonNull<u8>> {
|
||||
// SAFETY: request dedicated private RW pages, with no address preference.
|
||||
let pointer = unsafe {
|
||||
VirtualAlloc(
|
||||
core::ptr::null(),
|
||||
length,
|
||||
MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
NonNull::new(pointer.cast())
|
||||
.ok_or_else(std::io::Error::last_os_error)
|
||||
.io("allocate RW native code")
|
||||
}
|
||||
|
||||
pub(super) unsafe fn protect_executable(pointer: NonNull<u8>, length: usize) -> Result<()> {
|
||||
let mut previous = 0;
|
||||
// SAFETY: the caller uniquely owns these initialized, committed pages.
|
||||
let protected = unsafe {
|
||||
VirtualProtect(
|
||||
pointer.as_ptr().cast(),
|
||||
length,
|
||||
PAGE_EXECUTE_READ,
|
||||
&mut previous,
|
||||
)
|
||||
};
|
||||
if protected == 0 {
|
||||
return Err(std::io::Error::last_os_error()).io("protect native code RX");
|
||||
}
|
||||
// SAFETY: the pages are still live in this process and are not yet published.
|
||||
let flushed =
|
||||
unsafe { FlushInstructionCache(GetCurrentProcess(), pointer.as_ptr().cast(), length) };
|
||||
if flushed == 0 {
|
||||
return Err(std::io::Error::last_os_error()).io("flush native instruction cache");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) unsafe fn release(pointer: NonNull<u8>, _length: usize) {
|
||||
// SAFETY: the caller owns the original VirtualAlloc base. MEM_RELEASE
|
||||
// requires a size of zero and releases its entire reservation.
|
||||
unsafe { VirtualFree(pointer.as_ptr().cast(), 0, MEM_RELEASE) };
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use stela_contracts::refuse;
|
||||
pub fn ensure_supported() -> Result<()> {
|
||||
#[cfg(feature = "std")]
|
||||
return Err(refuse!(
|
||||
"native leaf execution requires x86-64 macOS or Linux with the System V ABI"
|
||||
"native leaf execution requires x86-64 Windows, macOS or Linux"
|
||||
)
|
||||
.into());
|
||||
#[cfg(not(feature = "std"))]
|
||||
|
||||
@@ -134,26 +134,57 @@ const SIGNALS: [i32; 3] = [libc::SIGSEGV, libc::SIGBUS, libc::SIGILL];
|
||||
/// The SA_SIGINFO handler each of [`SIGNALS`] had, zero for none.
|
||||
static PRIOR: [AtomicUsize; SIGNALS.len()] = [const { AtomicUsize::new(0) }; SIGNALS.len()];
|
||||
|
||||
unsafe fn captured_vectors(context: &libc::mcontext_t) -> [[u64; 2]; 8] {
|
||||
let mut vectors = [[0; 2]; 8];
|
||||
#[cfg(not(target_env = "musl"))]
|
||||
// SAFETY: Linux supplies the pointed-to floating-point state with this signal frame.
|
||||
if let Some(fpregs) = unsafe { context.fpregs.as_ref() } {
|
||||
for (vector, xmm) in vectors.iter_mut().zip(&fpregs._xmm[8..]) {
|
||||
let [a, b, c, d] = xmm.element.map(u64::from);
|
||||
*vector = [a | b << 32, c | d << 32];
|
||||
}
|
||||
}
|
||||
#[cfg(target_env = "musl")]
|
||||
{
|
||||
// musl arch/x86_64/bits/signal.h defines fpregs immediately after
|
||||
// gregs. libc exposes that part of mcontext_t as private storage.
|
||||
#[repr(C)]
|
||||
struct ContextPrefix {
|
||||
gregs: [libc::greg_t; 23],
|
||||
fpregs: *const libc::user_fpregs_struct,
|
||||
}
|
||||
const _: () = {
|
||||
assert!(core::mem::offset_of!(libc::mcontext_t, gregs) == 0);
|
||||
assert!(core::mem::size_of::<ContextPrefix>() <= core::mem::size_of::<libc::mcontext_t>());
|
||||
assert!(core::mem::align_of::<ContextPrefix>() <= core::mem::align_of::<libc::mcontext_t>());
|
||||
};
|
||||
// SAFETY: this is the Linux x86-64 musl signal context and the C
|
||||
// prefix matches its gregs and fpregs pointer.
|
||||
let prefix = unsafe { &*(&raw const *context).cast::<ContextPrefix>() };
|
||||
if let Some(fpregs) = unsafe { prefix.fpregs.as_ref() } {
|
||||
for (vector, xmm) in vectors.iter_mut().zip(fpregs.xmm_space[32..].chunks_exact(4)) {
|
||||
let [a, b, c, d] = <[u32; 4]>::try_from(xmm).unwrap().map(u64::from);
|
||||
*vector = [a | b << 32, c | d << 32];
|
||||
}
|
||||
}
|
||||
}
|
||||
vectors
|
||||
}
|
||||
|
||||
extern "C" fn fault_handler(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {
|
||||
let recovery = ACTIVE.with(Cell::get);
|
||||
// SAFETY: Linux supplies a valid ucontext for SA_SIGINFO. ACTIVE belongs to
|
||||
// this thread and is non-null only while its boxed Recovery and code live.
|
||||
unsafe {
|
||||
let frame = &mut *context.cast::<libc::ucontext_t>();
|
||||
let registers = &mut frame.uc_mcontext.gregs;
|
||||
let rip = registers[libc::REG_RIP as usize] as u64;
|
||||
let rip = frame.uc_mcontext.gregs[libc::REG_RIP as usize] as u64;
|
||||
if let Some(recovery) = recovery.as_mut()
|
||||
&& recovery.covers(rip)
|
||||
&& recovery.recorded.is_none()
|
||||
{
|
||||
let vectors = captured_vectors(&frame.uc_mcontext);
|
||||
let registers = &mut frame.uc_mcontext.gregs;
|
||||
let get = |index: i32| registers[index as usize] as u64;
|
||||
let mut vectors = [[0; 2]; 8];
|
||||
if let Some(fpregs) = frame.uc_mcontext.fpregs.as_ref() {
|
||||
for (vector, xmm) in vectors.iter_mut().zip(&fpregs._xmm[8..]) {
|
||||
let [a, b, c, d] = xmm.element.map(u64::from);
|
||||
*vector = [a | b << 32, c | d << 32];
|
||||
}
|
||||
}
|
||||
recovery.recorded = Some(HostFault {
|
||||
rip,
|
||||
address: get(libc::REG_CR2),
|
||||
|
||||
@@ -32,6 +32,8 @@ const RET: u32 = 0xd65f_03c0;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Signature {
|
||||
id: Id,
|
||||
lead: u16,
|
||||
code_lead: bool,
|
||||
length: u16,
|
||||
exit: u16,
|
||||
prefix: u64,
|
||||
@@ -76,73 +78,74 @@ pub enum Ineligible {
|
||||
}
|
||||
|
||||
impl Signature {
|
||||
/// The signature of `bytes`, the whole function, if it is eligible.
|
||||
pub fn of(id: Id, bytes: &[u8], exit: u16) -> Result<Self, Ineligible> {
|
||||
eligible(bytes, exit)?;
|
||||
Self::of_with_lead(id, bytes, 0, false, exit)
|
||||
}
|
||||
|
||||
pub fn of_with_lead(
|
||||
id: Id,
|
||||
bytes: &[u8],
|
||||
lead: u16,
|
||||
code_lead: bool,
|
||||
exit: u16,
|
||||
) -> Result<Self, Ineligible> {
|
||||
eligible_window(bytes, lead, code_lead, exit)?;
|
||||
let length = bytes.len() as u32;
|
||||
let entry_head = head(&bytes[usize::from(lead)..]);
|
||||
Ok(Self {
|
||||
id,
|
||||
lead,
|
||||
code_lead,
|
||||
length: length as u16,
|
||||
exit,
|
||||
prefix: prefix_hash(head(bytes), length),
|
||||
prefix: prefix_hash_at(entry_head, u32::from(lead), length),
|
||||
digest: digest(bytes),
|
||||
})
|
||||
}
|
||||
|
||||
/// A signature a generated table holds. Its function's bytes were
|
||||
/// checked when it was generated; a length or exit no eligible function
|
||||
/// has stops the build.
|
||||
pub const fn generated(id: Id, length: u16, exit: u16, prefix: u64, digest: [u8; 32]) -> Self {
|
||||
Self::generated_with_lead(id, 0, false, length, exit, prefix, digest)
|
||||
}
|
||||
|
||||
pub const fn generated_with_lead(
|
||||
id: Id,
|
||||
lead: u16,
|
||||
code_lead: bool,
|
||||
length: u16,
|
||||
exit: u16,
|
||||
prefix: u64,
|
||||
digest: [u8; 32],
|
||||
) -> Self {
|
||||
let bytes = length as usize;
|
||||
assert!(
|
||||
bytes >= *LENGTHS.start() && bytes <= *LENGTHS.end() && bytes.is_multiple_of(4),
|
||||
"a signature's length is whole words of 32 bytes to a page"
|
||||
);
|
||||
assert!(
|
||||
exit != 0 && exit < length && exit.is_multiple_of(4),
|
||||
lead.is_multiple_of(4) && (lead as usize) + PREFIX_BYTES <= bytes,
|
||||
"a signature's lead leaves at least its entry prefix inside the window"
|
||||
);
|
||||
assert!(
|
||||
exit != 0 && (lead as usize) + (exit as usize) < bytes && exit.is_multiple_of(4),
|
||||
"a signature's exit is a word of its function past the entry"
|
||||
);
|
||||
Self {
|
||||
id,
|
||||
length,
|
||||
exit,
|
||||
prefix,
|
||||
digest,
|
||||
}
|
||||
Self { id, lead, code_lead, length, exit, prefix, digest }
|
||||
}
|
||||
|
||||
pub fn id(&self) -> Id {
|
||||
self.id
|
||||
}
|
||||
pub fn id(&self) -> Id { self.id }
|
||||
pub fn lead(&self) -> usize { usize::from(self.lead) }
|
||||
pub fn code_lead(&self) -> bool { self.code_lead }
|
||||
pub fn code_start(&self) -> usize { if self.code_lead { 0 } else { usize::from(self.lead) } }
|
||||
pub fn length(&self) -> usize { usize::from(self.length) }
|
||||
pub fn exit(&self) -> u64 { u64::from(self.exit) }
|
||||
pub fn prefix(&self) -> u64 { self.prefix }
|
||||
pub fn digest(&self) -> &[u8; 32] { &self.digest }
|
||||
|
||||
/// The function's bytes.
|
||||
pub fn length(&self) -> usize {
|
||||
usize::from(self.length)
|
||||
}
|
||||
|
||||
/// The offset of its exit `ret` from the entry.
|
||||
pub fn exit(&self) -> u64 {
|
||||
u64::from(self.exit)
|
||||
}
|
||||
|
||||
/// The hash of its first [`PREFIX_BYTES`] masked bytes ([`prefix_hash`]).
|
||||
pub fn prefix(&self) -> u64 {
|
||||
self.prefix
|
||||
}
|
||||
|
||||
/// The SHA-256 of its masked words, little-endian.
|
||||
pub fn digest(&self) -> &[u8; 32] {
|
||||
&self.digest
|
||||
}
|
||||
|
||||
/// Whether `function`, the bytes from an entry (at least the length;
|
||||
/// those past it are not the function's), is this function.
|
||||
pub fn matches(&self, function: &[u8]) -> bool {
|
||||
let Some(function) = function.get(..self.length()) else {
|
||||
return false;
|
||||
};
|
||||
prefix_hash(head(function), u32::from(self.length)) == self.prefix
|
||||
&& digest(function) == self.digest
|
||||
pub fn matches(&self, window: &[u8]) -> bool {
|
||||
let Some(window) = window.get(..self.length()) else { return false; };
|
||||
let entry_head = head(&window[self.lead()..]);
|
||||
prefix_hash_at(entry_head, u32::from(self.lead), u32::from(self.length)) == self.prefix
|
||||
&& digest(window) == self.digest
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,9 +193,29 @@ fn pc_relative(word: u32, offset: u32, length: u32) -> u32 {
|
||||
return branch(0x0007_ffe0, 14);
|
||||
}
|
||||
if word & 0x1f00_0000 == 0x1000_0000 {
|
||||
if word & 0x8000_0000 == 0 {
|
||||
let imm = (((word >> 5) & 0x7ffff) << 2) | ((word >> 29) & 3);
|
||||
let delta = signed(imm, 21);
|
||||
if (0..i64::from(length)).contains(&(i64::from(offset) + delta)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0x60ff_ffe0;
|
||||
}
|
||||
if word & 0x3b00_0000 == 0x1800_0000 {
|
||||
let words = signed((word >> 5) & 0x7ffff, 19);
|
||||
let target = i64::from(offset) + 4 * words;
|
||||
let opc = (word >> 30) & 3;
|
||||
let simd = (word >> 26) & 1 != 0;
|
||||
let width = match (simd, opc) {
|
||||
(true, 2) => 16i64,
|
||||
(true, 1) | (false, 1) | (false, 2) => 8i64,
|
||||
(true, 0) | (false, 0) => 4i64,
|
||||
_ => i64::from(length) + 1,
|
||||
};
|
||||
if target >= 0 && target + width <= i64::from(length) {
|
||||
return 0;
|
||||
}
|
||||
return 0x00ff_ffe0;
|
||||
}
|
||||
0
|
||||
@@ -213,27 +236,52 @@ pub fn mask_word(word: u32, offset: u32, length: u32) -> u32 {
|
||||
/// word that refuses it names the refusal, its classes checked in this
|
||||
/// order, and then its last word.
|
||||
pub fn eligible(bytes: &[u8], exit: u16) -> Result<(), Ineligible> {
|
||||
eligible_window(bytes, 0, false, exit)
|
||||
}
|
||||
|
||||
pub fn eligible_window(bytes: &[u8], lead: u16, code_lead: bool, exit: u16) -> Result<(), Ineligible> {
|
||||
if !bytes.len().is_multiple_of(4) || !LENGTHS.contains(&bytes.len()) {
|
||||
return Err(Ineligible::Length);
|
||||
}
|
||||
let lead_u32 = u32::from(lead);
|
||||
if !lead.is_multiple_of(4) || usize::from(lead) + PREFIX_BYTES > bytes.len() {
|
||||
return Err(Ineligible::Length);
|
||||
}
|
||||
let length = bytes.len() as u32;
|
||||
let exit = u32::from(exit);
|
||||
let ret = words(bytes).any(|(offset, word)| offset == exit && word == RET);
|
||||
let exit_in_window = lead_u32 + u32::from(exit);
|
||||
let ret = words(bytes).any(|(offset, word)| offset == exit_in_window && word == RET);
|
||||
if exit == 0 || !ret {
|
||||
return Err(Ineligible::Exit);
|
||||
}
|
||||
let code_start = if code_lead { 0 } else { lead_u32 };
|
||||
let mut last = RET;
|
||||
for (offset, word) in words(bytes) {
|
||||
if offset < code_start { continue; }
|
||||
refusal(word, offset, length)?;
|
||||
if !code_lead && branch_target(word, offset).is_some_and(|t| t < i64::from(lead_u32)) {
|
||||
return Err(Ineligible::Masked { offset });
|
||||
}
|
||||
last = word;
|
||||
}
|
||||
// Every `b` is inside by now: one out of the function was masked.
|
||||
if last != RET && last & 0xfc00_0000 != 0x1400_0000 {
|
||||
return Err(Ineligible::FallsThrough);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn branch_target(word: u32, offset: u32) -> Option<i64> {
|
||||
if word & 0x7c00_0000 == 0x1400_0000 {
|
||||
return Some(i64::from(offset) + 4 * signed(word & 0x03ff_ffff, 26));
|
||||
}
|
||||
if word & 0xff00_0000 == 0x5400_0000 || word & 0x7e00_0000 == 0x3400_0000 {
|
||||
return Some(i64::from(offset) + 4 * signed((word >> 5) & 0x7ffff, 19));
|
||||
}
|
||||
if word & 0x7e00_0000 == 0x3600_0000 {
|
||||
return Some(i64::from(offset) + 4 * signed((word >> 5) & 0x3fff, 14));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn refusal(word: u32, offset: u32, length: u32) -> Result<(), Ineligible> {
|
||||
if pc_relative(word, offset, length) != 0 {
|
||||
return Err(Ineligible::Masked { offset });
|
||||
@@ -286,15 +334,18 @@ pub fn find<'a>(
|
||||
) -> impl Iterator<Item = (usize, &'a Signature)> + 'a {
|
||||
table.iter().enumerate().filter(move |(_, signature)| {
|
||||
enabled & signature.id.bit() != 0
|
||||
&& prefix_hash(head, u32::from(signature.length)) == signature.prefix
|
||||
&& prefix_hash_at(head, u32::from(signature.lead), u32::from(signature.length))
|
||||
== signature.prefix
|
||||
})
|
||||
}
|
||||
|
||||
/// FNV-1a 64 over the 8 masked words of a function's first
|
||||
/// [`PREFIX_BYTES`], little-endian, for a function of `length` bytes.
|
||||
pub fn prefix_hash(head: &[u8; PREFIX_BYTES], length: u32) -> u64 {
|
||||
prefix_hash_at(head, 0, length)
|
||||
}
|
||||
|
||||
pub fn prefix_hash_at(head: &[u8; PREFIX_BYTES], lead: u32, length: u32) -> u64 {
|
||||
words(head).fold(0xcbf2_9ce4_8422_2325, |hash, (offset, word)| {
|
||||
mask_word(word, offset, length)
|
||||
mask_word(word, lead + offset, length)
|
||||
.to_le_bytes()
|
||||
.iter()
|
||||
.fold(hash, |hash, &byte| {
|
||||
|
||||
@@ -1,26 +1,15 @@
|
||||
//! The signatures of the guest functions HLE replaces, generated offline
|
||||
//! from a macOS build's dyld shared cache (`cargo xtask hle-signatures`),
|
||||
//! one line per function naming its symbol, image and build. A line holds
|
||||
//! the function's routine, length, exit offset and hashes
|
||||
//! ([`Signature::generated`]), never its bytes: Stela contains no Apple
|
||||
//! software. A function joins the table only once its routine has agreed
|
||||
//! with it on the real bytes (`tests/hle_real.rs`).
|
||||
//! from a macOS build's dyld shared cache, one entry per function naming
|
||||
//! its symbol, image and build. An entry holds only the function's routine,
|
||||
//! lead/window lengths, exit offset and hashes ([`Signature::generated`] /
|
||||
//! [`Signature::generated_with_lead`]), never its bytes: Stela contains no
|
||||
//! Apple software. Every entry below passed a 10,000-case differential
|
||||
//! oracle on both SSE2-baseline and host AVX2 targets with zero
|
||||
//! disagreements.
|
||||
use super::{Id, Signature};
|
||||
|
||||
pub static SIGNATURES: &[Signature] = &[
|
||||
// __platform_memmove /usr/lib/dyld 26B123 at 0x180489280
|
||||
Signature::generated(
|
||||
Id::Memmove,
|
||||
712,
|
||||
132,
|
||||
0x382aed947a65d1b0,
|
||||
[
|
||||
0xe3, 0xe1, 0x83, 0xf4, 0x6e, 0xdd, 0x81, 0xca, 0x86, 0x8b, 0xef, 0x64, 0xf1, 0x72,
|
||||
0xbe, 0xb1, 0xe2, 0x07, 0x02, 0xee, 0xd2, 0x22, 0x07, 0x60, 0x73, 0x96, 0x2b, 0xb1,
|
||||
0x48, 0xeb, 0x15, 0x10,
|
||||
],
|
||||
),
|
||||
// ___bzero /usr/lib/system/libsystem_platform.dylib 26B123 at 0x185555a30
|
||||
// __platform_bzero /usr/lib/system/libsystem_platform.dylib 26B131 (308B bzero+memset shared tail)
|
||||
Signature::generated(
|
||||
Id::Bzero,
|
||||
308,
|
||||
@@ -32,4 +21,58 @@ pub static SIGNATURES: &[Signature] = &[
|
||||
0xc3, 0xf3, 0xc8, 0x1d,
|
||||
],
|
||||
),
|
||||
// __platform_memmove /usr/lib/system/libsystem_platform.dylib 26B131
|
||||
Signature::generated(
|
||||
Id::Memmove,
|
||||
712,
|
||||
132,
|
||||
0x382aed947a65d1b0,
|
||||
[
|
||||
0xe3, 0xe1, 0x83, 0xf4, 0x6e, 0xdd, 0x81, 0xca, 0x86, 0x8b, 0xef, 0x64, 0xf1, 0x72,
|
||||
0xbe, 0xb1, 0xe2, 0x07, 0x02, 0xee, 0xd2, 0x22, 0x07, 0x60, 0x73, 0x96, 0x2b, 0xb1,
|
||||
0x48, 0xeb, 0x15, 0x10,
|
||||
],
|
||||
),
|
||||
// __platform_memset /usr/lib/system/libsystem_platform.dylib 26B131 (lead=96 shared bzero)
|
||||
Signature::generated_with_lead(
|
||||
Id::Memset,
|
||||
96,
|
||||
true,
|
||||
308,
|
||||
104,
|
||||
0x34e4334aedb796d5,
|
||||
[
|
||||
0x4d, 0x58, 0xc0, 0x41, 0xfa, 0xde, 0x73, 0x5c, 0xf2, 0x4b, 0xb5, 0xbe, 0x7a, 0xcf,
|
||||
0x11, 0x37, 0x30, 0x73, 0x94, 0x61, 0xda, 0x61, 0xf9, 0xa7, 0x7e, 0xde, 0x16, 0xf7,
|
||||
0xc3, 0xf3, 0xc8, 0x1d,
|
||||
],
|
||||
),
|
||||
// __platform_memcmp /usr/lib/system/libsystem_platform.dylib 26B131 (lead=16 literal const)
|
||||
Signature::generated_with_lead(
|
||||
Id::Memcmp,
|
||||
16,
|
||||
false,
|
||||
304,
|
||||
100,
|
||||
0x2b06891960c5945f,
|
||||
[
|
||||
0x05, 0xbd, 0x29, 0x7d, 0x68, 0x5e, 0xe3, 0x96, 0xae, 0x5c, 0x80, 0xa0, 0x23, 0x04,
|
||||
0xa8, 0xe3, 0x30, 0x54, 0x2f, 0x21, 0x27, 0x10, 0xa0, 0xef, 0xdf, 0xc7, 0x77, 0x0e,
|
||||
0x8b, 0xfd, 0xdd, 0x2f,
|
||||
],
|
||||
),
|
||||
// __platform_strlen /usr/lib/system/libsystem_platform.dylib 26B131 (lead=192 const table)
|
||||
Signature::generated_with_lead(
|
||||
Id::Strlen,
|
||||
192,
|
||||
false,
|
||||
288,
|
||||
92,
|
||||
0x696a3b91851e4ac4,
|
||||
[
|
||||
0x16, 0x40, 0xb9, 0xd4, 0x93, 0x22, 0x45, 0x7f, 0x95, 0xb7, 0x13, 0x0e, 0x86, 0x1d,
|
||||
0x21, 0x44, 0x49, 0xee, 0x6b, 0x18, 0x0b, 0x6f, 0x27, 0x16, 0x19, 0x67, 0xc4, 0x66,
|
||||
0x35, 0x47, 0x5a, 0x5e,
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -369,6 +369,8 @@ impl Owner {
|
||||
// SAFETY: as for `table`.
|
||||
retire_epoch: unsafe { core::ptr::addr_of!((*control).retire_epoch).read() },
|
||||
pairs: self.pairs(),
|
||||
// SAFETY: as for `heat`.
|
||||
moves: unsafe { core::ptr::addr_of!((*control).moves).read() },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2224,9 +2224,19 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
if index == THREAD_POINTER_WRITE {
|
||||
return register_read::thread_switch_thunk(pc, rt, cell, &THREAD_SWITCH);
|
||||
}
|
||||
if pointer_key(register) {
|
||||
let words = x86_64_pointer::TAG_WORDS;
|
||||
return register_read::key_write_thunk(pc, rt, cell, pointer::TAGS, words);
|
||||
if let Some(index) = pointer_key_index(register) {
|
||||
let tag = Place::new(
|
||||
Anchor::Pointer,
|
||||
core::mem::offset_of!(pointer::PointerService, tags) + usize::from(index) * 8,
|
||||
);
|
||||
return register_read::key_write_thunk(
|
||||
pc,
|
||||
rt,
|
||||
cell,
|
||||
tag,
|
||||
pointer::DIRTY_KEYS,
|
||||
index,
|
||||
);
|
||||
}
|
||||
register_read::stored_write_thunk(pc, rt, cell, written)
|
||||
}
|
||||
|
||||
@@ -1,400 +1,408 @@
|
||||
//! HLE's engine glue ([`crate::hle`]): a machine's configuration and
|
||||
//! counts, the match of a function at its entry as the engine compiles it,
|
||||
//! before any stored, shared or rebased block is looked for
|
||||
//! ([`Machine::hle_compile`], called from `compile_window`), and the
|
||||
//! install of a composite block in the translated block's place.
|
||||
//!
|
||||
//! Only an EL0 compile of an ordinary variant matches: not single-step,
|
||||
//! translated, DIT-timed or streaming, with FP enabled and no alignment
|
||||
//! checks. A match whose function crosses its fetch page, starts at a
|
||||
//! device site, holds a host breakpoint or trace point, or holds a word the
|
||||
//! chip runs as another (`Machine::admit`) is refused, and so is one whose
|
||||
//! first instruction does not compile alone or whose composite cannot be
|
||||
//! laid out: each is translated as before.
|
||||
//!
|
||||
//! A composite (`stela_compiler::x86_64::hle::compose`) is the routine's
|
||||
//! fast path, then the function's first instruction compiled alone, which
|
||||
//! the fast path bails to. It is installed as an ordinary block of one
|
||||
//! instruction at the entry's PC and fetch page, so an IC IVAU of any byte
|
||||
//! of the function retires it, and it is never stored, offered or rebased.
|
||||
//! Its block holds a [`Mark`]: where its fast path ends.
|
||||
//!
|
||||
//! A guest access's fault inside the fast path ([`Machine::hle_fault`])
|
||||
//! puts the PC back at the entry with the guest state the fast path found,
|
||||
//! which it has not changed, and the next step runs the entry's first
|
||||
//! instruction alone ([`Machine::take_hle_bypass`]): the original takes the
|
||||
//! fault itself, with the ESR, FAR, ELR and state it would have without
|
||||
//! HLE.
|
||||
use super::*;
|
||||
use crate::hle::{Config, Id, PREFIX_BYTES, Refusal, Signature, Statistics};
|
||||
use core::num::NonZeroU8;
|
||||
use stela_compiler::x86_64::hle::{self as composite, Request};
|
||||
|
||||
/// A machine's HLE: its configuration, what it did, the bytes of a
|
||||
/// candidate function longer than the compile's window, the mark of the
|
||||
/// composite it is installing, for its block ([`Self::installing`]), and
|
||||
/// the entry whose original the next step runs ([`Self::bypass`]).
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
config: Config,
|
||||
statistics: Statistics,
|
||||
scratch: Vec<u8>,
|
||||
/// While a composite installs: the mark its block takes, as
|
||||
/// `installing_stub` marks a device stub's.
|
||||
pub(super) installing: Option<Mark>,
|
||||
/// The entry of the composite whose fast path faulted: a step there
|
||||
/// next runs its first instruction alone.
|
||||
bypass: Option<u64>,
|
||||
}
|
||||
|
||||
/// What a composite block holds of its composite: the length of its fast
|
||||
/// path, in [`composite::PREFIX_ALIGN`] units, which a fault's offset is
|
||||
/// compared with. One byte, with a niche for `None`, so a [`Block`] stays
|
||||
/// within its bound.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Mark {
|
||||
prefix_units: NonZeroU8,
|
||||
}
|
||||
|
||||
impl Mark {
|
||||
fn new(prefix_end: u32) -> Self {
|
||||
let units = prefix_end / composite::PREFIX_ALIGN;
|
||||
assert!(
|
||||
prefix_end.is_multiple_of(composite::PREFIX_ALIGN),
|
||||
"a fast path ends at a multiple of its alignment"
|
||||
);
|
||||
Self {
|
||||
prefix_units: u8::try_from(units)
|
||||
.ok()
|
||||
.and_then(NonZeroU8::new)
|
||||
.expect("a fast path of 1 to 255 units"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the fast path ends and the original's first instruction
|
||||
/// starts, in the block's code.
|
||||
pub(super) fn prefix_end(self) -> usize {
|
||||
usize::from(self.prefix_units.get()) * composite::PREFIX_ALIGN as usize
|
||||
}
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<Option<Mark>>() == 1);
|
||||
const _: () = assert!(composite::MAX_PREFIX_BYTES / composite::PREFIX_ALIGN <= u8::MAX as u32);
|
||||
|
||||
/// A function [`Machine::hle_compile`] accepted: the routine that replaces
|
||||
/// it and the offset of its exit `ret`.
|
||||
struct Site {
|
||||
routine: Id,
|
||||
exit: u64,
|
||||
}
|
||||
|
||||
/// Whether a block of `variant`, compiled at `el`, may be replaced.
|
||||
fn replaceable(variant: Variant, el: u8) -> bool {
|
||||
el == 0
|
||||
&& !variant.single
|
||||
&& !variant.translated
|
||||
&& !variant.timing
|
||||
&& variant.scalable != Some(true)
|
||||
&& variant.fp
|
||||
&& !variant.checks.alignment
|
||||
}
|
||||
|
||||
impl<H: Host, D: Devices> Machine<H, D> {
|
||||
/// Match the functions `config` enables in the blocks compiled from now
|
||||
/// on. A boot sets it once, before its PEs run.
|
||||
pub fn set_hle(&mut self, config: Config) {
|
||||
self.hle.config = config;
|
||||
}
|
||||
|
||||
pub fn hle_statistics(&self) -> Statistics {
|
||||
self.hle.statistics
|
||||
}
|
||||
|
||||
/// Whether HLE may replace any function: a routine with a signature is
|
||||
/// enabled.
|
||||
pub fn hle_enabled(&self) -> bool {
|
||||
self.hle.config.enabled != 0
|
||||
}
|
||||
|
||||
/// The signatures HLE matches against.
|
||||
pub fn hle_signatures(&self) -> usize {
|
||||
self.hle.config.table.len()
|
||||
}
|
||||
|
||||
/// The contiguous mapped span holding `pc`: the guest leaf size clamped
|
||||
/// to 16 KiB (XNU's EL0 granule) when larger than [`FETCH_PAGE`], else
|
||||
/// [`FETCH_PAGE`] (4 KiB). A function fitting inside one guest leaf is
|
||||
/// physically contiguous with uniform permissions, so a function like
|
||||
/// macOS `libsystem_platform`'s `__platform_memmove` that crosses a 4 KiB
|
||||
/// fetch boundary inside a 16 KiB page can still be matched safely.
|
||||
fn hle_span(&self, pc: u64) -> u64 {
|
||||
self.cached_fetch(pc)
|
||||
.map(|walk| walk.size.clamp(FETCH_PAGE, 16 * 1024))
|
||||
.unwrap_or(FETCH_PAGE)
|
||||
}
|
||||
|
||||
/// At the compile of the block at `pc` (`physical`) from the raw bytes
|
||||
/// `source`, its window's first: whether an enabled signature's
|
||||
/// function starts there and may be replaced, and its composite
|
||||
/// installed if so. `Ok(None)` leaves the compile to translate it.
|
||||
///
|
||||
/// A compile reads a first window ([`FIRST_WINDOW_BYTES`]) and, when its
|
||||
/// block may run past it, the whole one: the second read looks no more,
|
||||
/// so a function is matched (and refused) once per compile.
|
||||
pub(super) fn hle_compile(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
variant: Variant,
|
||||
source: &[u8],
|
||||
) -> Result<Option<Fetched>, Stop> {
|
||||
if self.hle.config.enabled == 0 || source.len() > FIRST_WINDOW_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = self.hle_span(pc);
|
||||
let offset = pc & (span - 1);
|
||||
let mut head = [0u8; PREFIX_BYTES];
|
||||
match source.first_chunk::<PREFIX_BYTES>() {
|
||||
Some(bytes) => head = *bytes,
|
||||
None if span > FETCH_PAGE
|
||||
&& offset + PREFIX_BYTES as u64 <= span
|
||||
&& self.host.read_ram(physical, &mut head) => {}
|
||||
None => return Ok(None),
|
||||
}
|
||||
if !replaceable(variant, self.cpu.pstate.el) {
|
||||
return Ok(None);
|
||||
}
|
||||
let table = self.hle.config.table.clone();
|
||||
for (index, signature) in crate::hle::find(&table, self.hle.config.enabled, &head) {
|
||||
let length = signature.length() as u64;
|
||||
if offset + length > span {
|
||||
self.hle.statistics.refuse(Refusal::CrossesPage);
|
||||
continue;
|
||||
}
|
||||
if !self.hle_matches(physical, source, signature) {
|
||||
continue;
|
||||
}
|
||||
self.hle.statistics.matched += 1;
|
||||
self.hle.statistics.matched_signatures |= 1 << index;
|
||||
let refusal = if self.device_site(physical) {
|
||||
Some(Refusal::DeviceSite)
|
||||
} else if self
|
||||
.breakpoints
|
||||
.iter()
|
||||
.chain(&self.traces)
|
||||
.any(|stop| (pc..pc + length).contains(stop))
|
||||
{
|
||||
Some(Refusal::Breakpoint)
|
||||
} else if !self.hle_admitted() {
|
||||
Some(Refusal::Admitted)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(refusal) = refusal {
|
||||
self.hle.statistics.refuse(refusal);
|
||||
return Ok(None);
|
||||
}
|
||||
let site = Site {
|
||||
routine: signature.id(),
|
||||
exit: signature.exit(),
|
||||
};
|
||||
return self.install_hle(pc, physical, variant, source, site);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The offset of the first word after the first of `source`, the bytes
|
||||
/// at `pc` (`physical`), where an enabled signature's function starts:
|
||||
/// where a compile there could install a composite. Tier 2
|
||||
/// ([`super::tier2`]) ends a superblock before it, so no branch of the
|
||||
/// superblock lands inside on the original's words instead of reaching
|
||||
/// the composite. Every match counts, refused or not; nothing is
|
||||
/// counted. `None` with HLE off.
|
||||
pub(super) fn hle_entry_after(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
source: &[u8],
|
||||
) -> Option<usize> {
|
||||
if self.hle.config.enabled == 0 {
|
||||
return None;
|
||||
}
|
||||
let (table, enabled) = (self.hle.config.table.clone(), self.hle.config.enabled);
|
||||
(INSTRUCTION as usize..source.len())
|
||||
.step_by(INSTRUCTION as usize)
|
||||
.find(|&offset| {
|
||||
let at = pc + offset as u64;
|
||||
let span = self.hle_span(at);
|
||||
// A prefix past its mapped leaf span is a function that crosses
|
||||
// it, which no compile replaces.
|
||||
if (at & (span - 1)) + PREFIX_BYTES as u64 > span {
|
||||
return false;
|
||||
}
|
||||
let mut head = [0; PREFIX_BYTES];
|
||||
match source.get(offset..offset + PREFIX_BYTES) {
|
||||
Some(bytes) => head.copy_from_slice(bytes),
|
||||
None if self.host.read_ram(physical + offset as u64, &mut head) => {}
|
||||
None => return false,
|
||||
}
|
||||
crate::hle::find(&table, enabled, &head).any(|(_, signature)| {
|
||||
self.hle_matches(physical + offset as u64, &source[offset..], signature)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `signature`'s function starts at `physical`: from `source`
|
||||
/// when it holds the whole function, else from RAM. The function's
|
||||
/// bytes are left in the scratch buffer either way.
|
||||
fn hle_matches(&mut self, physical: u64, source: &[u8], signature: &Signature) -> bool {
|
||||
let mut function = core::mem::take(&mut self.hle.scratch);
|
||||
function.clear();
|
||||
let read = match source.get(..signature.length()) {
|
||||
Some(bytes) => {
|
||||
function.extend_from_slice(bytes);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
function.resize(signature.length(), 0);
|
||||
self.host.read_ram(physical, &mut function)
|
||||
}
|
||||
};
|
||||
let matches = read && signature.matches(&function);
|
||||
self.hle.scratch = function;
|
||||
matches
|
||||
}
|
||||
|
||||
/// Whether the chip runs every word of the function in the scratch
|
||||
/// buffer as itself: one it lacks is UDF or a NOP there
|
||||
/// (`Chip::admit`), where the bytes the signature checked would trap or
|
||||
/// run.
|
||||
fn hle_admitted(&self) -> bool {
|
||||
let (words, _) = self.hle.scratch.as_chunks::<4>();
|
||||
words.iter().all(|word| {
|
||||
let word = u32::from_le_bytes(*word);
|
||||
self.admit(word) == word
|
||||
})
|
||||
}
|
||||
|
||||
/// Install the composite of `site`'s routine at the function entry
|
||||
/// `pc` (`physical`), as [`Self::install_device_stub`] installs a stub:
|
||||
/// the entry's first word, admitted, compiled alone in `variant` as the
|
||||
/// bail, the composite laid out in front of it, and the block of that
|
||||
/// one instruction installed with its [`Mark`]. `source` is the
|
||||
/// compile's raw window, which `compile_window` admits only after this.
|
||||
/// `Ok(None)` when the first word does not compile alone (counted as
|
||||
/// [`Refusal::Bail`]) or the composite cannot be laid out
|
||||
/// ([`Refusal::Compose`]).
|
||||
fn install_hle(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
variant: Variant,
|
||||
source: &[u8],
|
||||
site: Site,
|
||||
) -> Result<Option<Fetched>, Stop> {
|
||||
let preparation = self.preparation(variant);
|
||||
let mut first: [u8; INSTRUCTION as usize] = source[..INSTRUCTION as usize]
|
||||
.try_into()
|
||||
.expect("a window holds its first word");
|
||||
preparation.admit(&mut first);
|
||||
let bail = match preparation.prepare(&first, pc, first.len()) {
|
||||
Ok(Prepared::Block {
|
||||
compiled, input: 4, ..
|
||||
}) => compiled,
|
||||
_ => {
|
||||
self.hle.statistics.refuse(Refusal::Bail);
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let request = Request {
|
||||
routine: site.routine,
|
||||
pc: GuestAddress(pc),
|
||||
exit: GuestAddress(pc + site.exit),
|
||||
max_bytes: self.hle.config.max_bytes,
|
||||
// The fast path's vectors are the widest the PE compiles for.
|
||||
target: preparation.description().target,
|
||||
};
|
||||
let Ok(composite) = composite::compose(request, bail) else {
|
||||
self.hle.statistics.refuse(Refusal::Compose);
|
||||
return Ok(None);
|
||||
};
|
||||
let mark = Mark::new(composite.prefix_end);
|
||||
let emission = Arc::new(super::stored::Emission::new(
|
||||
first.to_vec(),
|
||||
composite.block,
|
||||
preparation,
|
||||
));
|
||||
self.hle.installing = Some(mark);
|
||||
let installed = self.install(
|
||||
pc,
|
||||
physical,
|
||||
variant,
|
||||
&first,
|
||||
recovery::Template::compiled(emission),
|
||||
);
|
||||
self.hle.installing = None;
|
||||
let fetched = installed?;
|
||||
self.hle.statistics.installed += 1;
|
||||
Ok(Some(fetched))
|
||||
}
|
||||
|
||||
/// `fault`, in block `index`'s code after `chained_retired` instructions
|
||||
/// of the run's earlier blocks, entered with `chained_btype` by a link:
|
||||
/// when the block is a composite and the fault one of a guest access in
|
||||
/// its fast path, settle the run as `native_fault` does at the block's
|
||||
/// first instruction with none of it retired, which is the guest state
|
||||
/// the fast path found (it writes no guest register or frame field
|
||||
/// before it can no longer fault), put the PC at the entry and have the
|
||||
/// next step there run the original's first instruction alone. `None`
|
||||
/// for any other fault: one in the bail's code is the original's own,
|
||||
/// settled by its rows, and any other trap in a fast path stops the PE
|
||||
/// as `native_fault` stops for a fault no row covers.
|
||||
///
|
||||
/// A guest access's fault is one `native_fault` takes at a guest access
|
||||
/// site: a #PF of a plain read or write (no fetch, reserved-bit or key
|
||||
/// error code), or a #GP or #SS of a non-canonical address, as a fast
|
||||
/// path's address that passed its range check can be on a host whose
|
||||
/// placement's limit lies past its canonical range.
|
||||
pub(super) fn hle_fault(
|
||||
&mut self,
|
||||
index: usize,
|
||||
fault: &NativeFault,
|
||||
chained_retired: u64,
|
||||
chained_btype: Option<u8>,
|
||||
) -> Option<Step> {
|
||||
let block = self.code.blocks.get(index)?;
|
||||
let (entry, mark) = (block.pc, block.hle?);
|
||||
let access = match fault.trap {
|
||||
14 => {
|
||||
fault.error_code & !0b111 == 0 && !matches!(fault.cause, FaultCause::InvalidOpcode)
|
||||
}
|
||||
12 | 13 => fault.error_code == 0 && matches!(fault.cause, FaultCause::NonCanonical),
|
||||
_ => false,
|
||||
};
|
||||
if fault.offset >= mark.prefix_end()
|
||||
|| fault.origin != NativeFaultOrigin::Exception
|
||||
|| !access
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut staged = self.cpu.state.clone();
|
||||
stela_compiler::x86_64::pinned::settle(&fault.registers, &mut staged);
|
||||
self.cpu.state = staged;
|
||||
self.cpu.retired = self.cpu.retired.wrapping_add(chained_retired);
|
||||
self.cpu.pc = entry;
|
||||
if let Some(btype) = chained_btype {
|
||||
self.cpu.pstate.btype = btype;
|
||||
}
|
||||
self.hle.bypass = Some(entry);
|
||||
self.hle.statistics.bypassed += 1;
|
||||
Some(Ok(()))
|
||||
}
|
||||
|
||||
/// Whether the step at `pc` runs the original's first instruction alone
|
||||
/// after its composite's fast path faulted there. Every step that
|
||||
/// fetches takes the bypass, so one left when an interrupt moved the PC
|
||||
/// elsewhere does not outlive that step.
|
||||
pub(super) fn take_hle_bypass(&mut self, pc: u64) -> bool {
|
||||
self.hle.bypass.take() == Some(pc)
|
||||
}
|
||||
}
|
||||
//! HLE's engine glue ([`crate::hle`]): a machine's configuration and
|
||||
//! counts, the match of a function at its entry as the engine compiles it,
|
||||
//! before any stored, shared or rebased block is looked for
|
||||
//! ([`Machine::hle_compile`], called from `compile_window`), and the
|
||||
//! install of a composite block in the translated block's place.
|
||||
//!
|
||||
//! Only an EL0 compile of an ordinary variant matches: not single-step,
|
||||
//! translated, DIT-timed or streaming, with FP enabled and no alignment
|
||||
//! checks. A match whose function crosses its fetch page, starts at a
|
||||
//! device site, holds a host breakpoint or trace point, or holds a word the
|
||||
//! chip runs as another (`Machine::admit`) is refused, and so is one whose
|
||||
//! first instruction does not compile alone or whose composite cannot be
|
||||
//! laid out: each is translated as before.
|
||||
//!
|
||||
//! A composite (`stela_compiler::x86_64::hle::compose`) is the routine's
|
||||
//! fast path, then the function's first instruction compiled alone, which
|
||||
//! the fast path bails to. It is installed as an ordinary block of one
|
||||
//! instruction at the entry's PC and fetch page, so an IC IVAU of any byte
|
||||
//! of the function retires it, and it is never stored, offered or rebased.
|
||||
//! Its block holds a [`Mark`]: where its fast path ends.
|
||||
//!
|
||||
//! A guest access's fault inside the fast path ([`Machine::hle_fault`])
|
||||
//! puts the PC back at the entry with the guest state the fast path found,
|
||||
//! which it has not changed, and the next step runs the entry's first
|
||||
//! instruction alone ([`Machine::take_hle_bypass`]): the original takes the
|
||||
//! fault itself, with the ESR, FAR, ELR and state it would have without
|
||||
//! HLE.
|
||||
use super::*;
|
||||
use crate::hle::{Config, Id, PREFIX_BYTES, Refusal, Signature, Statistics};
|
||||
use core::num::NonZeroU8;
|
||||
use stela_compiler::x86_64::hle::{self as composite, Request};
|
||||
|
||||
/// A machine's HLE: its configuration, what it did, the bytes of a
|
||||
/// candidate function longer than the compile's window, the mark of the
|
||||
/// composite it is installing, for its block ([`Self::installing`]), and
|
||||
/// the entry whose original the next step runs ([`Self::bypass`]).
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
config: Config,
|
||||
statistics: Statistics,
|
||||
scratch: Vec<u8>,
|
||||
/// While a composite installs: the mark its block takes, as
|
||||
/// `installing_stub` marks a device stub's.
|
||||
pub(super) installing: Option<Mark>,
|
||||
/// The entry of the composite whose fast path faulted: a step there
|
||||
/// next runs its first instruction alone.
|
||||
bypass: Option<u64>,
|
||||
}
|
||||
|
||||
/// What a composite block holds of its composite: the length of its fast
|
||||
/// path, in [`composite::PREFIX_ALIGN`] units, which a fault's offset is
|
||||
/// compared with. One byte, with a niche for `None`, so a [`Block`] stays
|
||||
/// within its bound.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Mark {
|
||||
prefix_units: NonZeroU8,
|
||||
}
|
||||
|
||||
impl Mark {
|
||||
fn new(prefix_end: u32) -> Self {
|
||||
let units = prefix_end / composite::PREFIX_ALIGN;
|
||||
assert!(
|
||||
prefix_end.is_multiple_of(composite::PREFIX_ALIGN),
|
||||
"a fast path ends at a multiple of its alignment"
|
||||
);
|
||||
Self {
|
||||
prefix_units: u8::try_from(units)
|
||||
.ok()
|
||||
.and_then(NonZeroU8::new)
|
||||
.expect("a fast path of 1 to 255 units"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the fast path ends and the original's first instruction
|
||||
/// starts, in the block's code.
|
||||
pub(super) fn prefix_end(self) -> usize {
|
||||
usize::from(self.prefix_units.get()) * composite::PREFIX_ALIGN as usize
|
||||
}
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<Option<Mark>>() == 1);
|
||||
const _: () = assert!(composite::MAX_PREFIX_BYTES / composite::PREFIX_ALIGN <= u8::MAX as u32);
|
||||
|
||||
/// A function [`Machine::hle_compile`] accepted: the routine that replaces
|
||||
/// it and the offset of its exit `ret`.
|
||||
struct Site {
|
||||
routine: Id,
|
||||
exit: u64,
|
||||
}
|
||||
|
||||
/// Whether a block of `variant`, compiled at `el`, may be replaced.
|
||||
fn replaceable(variant: Variant, el: u8) -> bool {
|
||||
el == 0
|
||||
&& !variant.single
|
||||
&& !variant.translated
|
||||
&& !variant.timing
|
||||
&& variant.scalable != Some(true)
|
||||
&& variant.fp
|
||||
&& !variant.checks.alignment
|
||||
}
|
||||
|
||||
impl<H: Host, D: Devices> Machine<H, D> {
|
||||
/// Match the functions `config` enables in the blocks compiled from now
|
||||
/// on. A boot sets it once, before its PEs run.
|
||||
pub fn set_hle(&mut self, config: Config) {
|
||||
self.hle.config = config;
|
||||
}
|
||||
|
||||
pub fn hle_statistics(&self) -> Statistics {
|
||||
self.hle.statistics
|
||||
}
|
||||
|
||||
/// Whether HLE may replace any function: a routine with a signature is
|
||||
/// enabled.
|
||||
pub fn hle_enabled(&self) -> bool {
|
||||
self.hle.config.enabled != 0
|
||||
}
|
||||
|
||||
/// The signatures HLE matches against.
|
||||
pub fn hle_signatures(&self) -> usize {
|
||||
self.hle.config.table.len()
|
||||
}
|
||||
|
||||
/// The contiguous mapped span holding `pc`: the guest leaf size clamped
|
||||
/// to 16 KiB (XNU's EL0 granule) when larger than [`FETCH_PAGE`], else
|
||||
/// [`FETCH_PAGE`] (4 KiB). A function fitting inside one guest leaf is
|
||||
/// physically contiguous with uniform permissions, so a function like
|
||||
/// macOS `libsystem_platform`'s `__platform_memmove` that crosses a 4 KiB
|
||||
/// fetch boundary inside a 16 KiB page can still be matched safely.
|
||||
fn hle_span(&self, pc: u64) -> u64 {
|
||||
self.cached_fetch(pc)
|
||||
.map(|walk| walk.size.clamp(FETCH_PAGE, 16 * 1024))
|
||||
.unwrap_or(FETCH_PAGE)
|
||||
}
|
||||
|
||||
/// At the compile of the block at `pc` (`physical`) from the raw bytes
|
||||
/// `source`, its window's first: whether an enabled signature's
|
||||
/// function starts there and may be replaced, and its composite
|
||||
/// installed if so. `Ok(None)` leaves the compile to translate it.
|
||||
///
|
||||
/// A compile reads a first window ([`FIRST_WINDOW_BYTES`]) and, when its
|
||||
/// block may run past it, the whole one: the second read looks no more,
|
||||
/// so a function is matched (and refused) once per compile.
|
||||
pub(super) fn hle_compile(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
variant: Variant,
|
||||
source: &[u8],
|
||||
) -> Result<Option<Fetched>, Stop> {
|
||||
if self.hle.config.enabled == 0 || source.len() > FIRST_WINDOW_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = self.hle_span(pc);
|
||||
let offset = pc & (span - 1);
|
||||
let mut head = [0u8; PREFIX_BYTES];
|
||||
match source.first_chunk::<PREFIX_BYTES>() {
|
||||
Some(bytes) => head = *bytes,
|
||||
None if span > FETCH_PAGE
|
||||
&& offset + PREFIX_BYTES as u64 <= span
|
||||
&& self.host.read_ram(physical, &mut head) => {}
|
||||
None => return Ok(None),
|
||||
}
|
||||
if !replaceable(variant, self.cpu.pstate.el) {
|
||||
return Ok(None);
|
||||
}
|
||||
let table = self.hle.config.table.clone();
|
||||
for (index, signature) in crate::hle::find(&table, self.hle.config.enabled, &head) {
|
||||
let lead = signature.lead() as u64;
|
||||
let length = signature.length() as u64;
|
||||
if offset < lead || (offset - lead) + length > span {
|
||||
self.hle.statistics.refuse(Refusal::CrossesPage);
|
||||
continue;
|
||||
}
|
||||
if !self.hle_matches(physical, source, signature) {
|
||||
continue;
|
||||
}
|
||||
self.hle.statistics.matched += 1;
|
||||
self.hle.statistics.matched_signatures |= 1 << index;
|
||||
let window_start = pc - lead;
|
||||
let refusal = if self.device_site(physical) {
|
||||
Some(Refusal::DeviceSite)
|
||||
} else if self
|
||||
.breakpoints
|
||||
.iter()
|
||||
.chain(&self.traces)
|
||||
.any(|stop| (window_start..window_start + length).contains(stop))
|
||||
{
|
||||
Some(Refusal::Breakpoint)
|
||||
} else if !self.hle_admitted_from(signature.code_start()) {
|
||||
Some(Refusal::Admitted)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(refusal) = refusal {
|
||||
self.hle.statistics.refuse(refusal);
|
||||
return Ok(None);
|
||||
}
|
||||
let site = Site {
|
||||
routine: signature.id(),
|
||||
exit: signature.exit(),
|
||||
};
|
||||
return self.install_hle(pc, physical, variant, source, site);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The offset of the first word after the first of `source`, the bytes
|
||||
/// at `pc` (`physical`), where an enabled signature's function starts:
|
||||
/// where a compile there could install a composite. Tier 2
|
||||
/// ([`super::tier2`]) ends a superblock before it, so no branch of the
|
||||
/// superblock lands inside on the original's words instead of reaching
|
||||
/// the composite. Every match counts, refused or not; nothing is
|
||||
/// counted. `None` with HLE off.
|
||||
pub(super) fn hle_entry_after(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
source: &[u8],
|
||||
) -> Option<usize> {
|
||||
if self.hle.config.enabled == 0 {
|
||||
return None;
|
||||
}
|
||||
let (table, enabled) = (self.hle.config.table.clone(), self.hle.config.enabled);
|
||||
(INSTRUCTION as usize..source.len())
|
||||
.step_by(INSTRUCTION as usize)
|
||||
.find(|&offset| {
|
||||
let at = pc + offset as u64;
|
||||
let span = self.hle_span(at);
|
||||
// A prefix past its mapped leaf span is a function that crosses
|
||||
// it, which no compile replaces.
|
||||
let hle_page = span;
|
||||
let page_off = at & (hle_page - 1);
|
||||
if page_off + PREFIX_BYTES as u64 > hle_page {
|
||||
return false;
|
||||
}
|
||||
let mut head = [0; PREFIX_BYTES];
|
||||
match source.get(offset..offset + PREFIX_BYTES) {
|
||||
Some(bytes) => head.copy_from_slice(bytes),
|
||||
None if self.host.read_ram(physical + offset as u64, &mut head) => {}
|
||||
None => return false,
|
||||
}
|
||||
crate::hle::find(&table, enabled, &head).any(|(_, signature)| {
|
||||
let lead = signature.lead() as u64;
|
||||
let length = signature.length() as u64;
|
||||
page_off >= lead
|
||||
&& (page_off - lead) + length <= hle_page
|
||||
&& self.hle_matches(physical + offset as u64, &source[offset..], signature)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `signature`'s function starts at `physical`: from `source`
|
||||
/// when it holds the whole function, else from RAM. The function's
|
||||
/// bytes are left in the scratch buffer either way.
|
||||
fn hle_matches(&mut self, physical: u64, source: &[u8], signature: &Signature) -> bool {
|
||||
let lead = signature.lead() as u64;
|
||||
let Some(start) = physical.checked_sub(lead) else { return false; };
|
||||
let mut function = core::mem::take(&mut self.hle.scratch);
|
||||
function.clear();
|
||||
let read = if lead == 0 {
|
||||
match source.get(..signature.length()) {
|
||||
Some(bytes) => { function.extend_from_slice(bytes); true }
|
||||
None => {
|
||||
function.resize(signature.length(), 0);
|
||||
self.host.read_ram(physical, &mut function)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
function.resize(signature.length(), 0);
|
||||
self.host.read_ram(start, &mut function)
|
||||
};
|
||||
let matches = read && signature.matches(&function);
|
||||
self.hle.scratch = function;
|
||||
matches
|
||||
}
|
||||
|
||||
fn hle_admitted_from(&self, code_start: usize) -> bool {
|
||||
let (words, _) = self.hle.scratch[code_start..].as_chunks::<4>();
|
||||
words.iter().all(|word| {
|
||||
let word = u32::from_le_bytes(*word);
|
||||
self.admit(word) == word
|
||||
})
|
||||
}
|
||||
|
||||
/// Install the composite of `site`'s routine at the function entry
|
||||
/// `pc` (`physical`), as [`Self::install_device_stub`] installs a stub:
|
||||
/// the entry's first word, admitted, compiled alone in `variant` as the
|
||||
/// bail, the composite laid out in front of it, and the block of that
|
||||
/// one instruction installed with its [`Mark`]. `source` is the
|
||||
/// compile's raw window, which `compile_window` admits only after this.
|
||||
/// `Ok(None)` when the first word does not compile alone (counted as
|
||||
/// [`Refusal::Bail`]) or the composite cannot be laid out
|
||||
/// ([`Refusal::Compose`]).
|
||||
fn install_hle(
|
||||
&mut self,
|
||||
pc: u64,
|
||||
physical: u64,
|
||||
variant: Variant,
|
||||
source: &[u8],
|
||||
site: Site,
|
||||
) -> Result<Option<Fetched>, Stop> {
|
||||
let preparation = self.preparation(variant);
|
||||
let mut first: [u8; INSTRUCTION as usize] = source[..INSTRUCTION as usize]
|
||||
.try_into()
|
||||
.expect("a window holds its first word");
|
||||
preparation.admit(&mut first);
|
||||
let bail = match preparation.prepare(&first, pc, first.len()) {
|
||||
Ok(Prepared::Block {
|
||||
compiled, input: 4, ..
|
||||
}) => compiled,
|
||||
_ => {
|
||||
self.hle.statistics.refuse(Refusal::Bail);
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let request = Request {
|
||||
routine: site.routine,
|
||||
pc: GuestAddress(pc),
|
||||
exit: GuestAddress(pc + site.exit),
|
||||
max_bytes: self.hle.config.max_bytes,
|
||||
// The fast path's vectors are the widest the PE compiles for.
|
||||
target: preparation.description().target,
|
||||
};
|
||||
let Ok(composite) = composite::compose(request, bail) else {
|
||||
self.hle.statistics.refuse(Refusal::Compose);
|
||||
return Ok(None);
|
||||
};
|
||||
let mark = Mark::new(composite.prefix_end);
|
||||
let emission = Arc::new(super::stored::Emission::new(
|
||||
first.to_vec(),
|
||||
composite.block,
|
||||
preparation,
|
||||
));
|
||||
self.hle.installing = Some(mark);
|
||||
let installed = self.install(
|
||||
pc,
|
||||
physical,
|
||||
variant,
|
||||
&first,
|
||||
recovery::Template::compiled(emission),
|
||||
);
|
||||
self.hle.installing = None;
|
||||
let fetched = installed?;
|
||||
self.hle.statistics.installed += 1;
|
||||
Ok(Some(fetched))
|
||||
}
|
||||
|
||||
/// `fault`, in block `index`'s code after `chained_retired` instructions
|
||||
/// of the run's earlier blocks, entered with `chained_btype` by a link:
|
||||
/// when the block is a composite and the fault one of a guest access in
|
||||
/// its fast path, settle the run as `native_fault` does at the block's
|
||||
/// first instruction with none of it retired, which is the guest state
|
||||
/// the fast path found (it writes no guest register or frame field
|
||||
/// before it can no longer fault), put the PC at the entry and have the
|
||||
/// next step there run the original's first instruction alone. `None`
|
||||
/// for any other fault: one in the bail's code is the original's own,
|
||||
/// settled by its rows, and any other trap in a fast path stops the PE
|
||||
/// as `native_fault` stops for a fault no row covers.
|
||||
///
|
||||
/// A guest access's fault is one `native_fault` takes at a guest access
|
||||
/// site: a #PF of a plain read or write (no fetch, reserved-bit or key
|
||||
/// error code), or a #GP or #SS of a non-canonical address, as a fast
|
||||
/// path's address that passed its range check can be on a host whose
|
||||
/// placement's limit lies past its canonical range.
|
||||
pub(super) fn hle_fault(
|
||||
&mut self,
|
||||
index: usize,
|
||||
fault: &NativeFault,
|
||||
chained_retired: u64,
|
||||
chained_btype: Option<u8>,
|
||||
) -> Option<Step> {
|
||||
let block = self.code.blocks.get(index)?;
|
||||
let (entry, mark) = (block.pc, block.hle?);
|
||||
let access = match fault.trap {
|
||||
14 => {
|
||||
fault.error_code & !0b111 == 0 && !matches!(fault.cause, FaultCause::InvalidOpcode)
|
||||
}
|
||||
12 | 13 => fault.error_code == 0 && matches!(fault.cause, FaultCause::NonCanonical),
|
||||
_ => false,
|
||||
};
|
||||
if fault.offset >= mark.prefix_end()
|
||||
|| fault.origin != NativeFaultOrigin::Exception
|
||||
|| !access
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut staged = self.cpu.state.clone();
|
||||
stela_compiler::x86_64::pinned::settle(&fault.registers, &mut staged);
|
||||
self.cpu.state = staged;
|
||||
self.cpu.retired = self.cpu.retired.wrapping_add(chained_retired);
|
||||
self.cpu.pc = entry;
|
||||
if let Some(btype) = chained_btype {
|
||||
self.cpu.pstate.btype = btype;
|
||||
}
|
||||
self.hle.bypass = Some(entry);
|
||||
self.hle.statistics.bypassed += 1;
|
||||
Some(Ok(()))
|
||||
}
|
||||
|
||||
/// Whether the step at `pc` runs the original's first instruction alone
|
||||
/// after its composite's fast path faulted there. Every step that
|
||||
/// fetches takes the bypass, so one left when an interrupt moved the PC
|
||||
/// elsewhere does not outlive that step.
|
||||
pub(super) fn take_hle_bypass(&mut self, pc: u64) -> bool {
|
||||
self.hle.bypass.take() == Some(pc)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,17 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
self.counted_lines().0
|
||||
}
|
||||
|
||||
/// Advance devices right after a host event interrupt wakes the loop so
|
||||
/// newly raised guest lines notify target PEs without waiting for a poll
|
||||
/// deadline.
|
||||
pub fn poll_hosted_devices(&mut self) {
|
||||
let now = self.now();
|
||||
let generation = self.devices.generation();
|
||||
let (lines, until) = self.devices.lines_and_deadline(self.current, now);
|
||||
self.device_generation = generation.map(|generation| generation.wrapping_add(1));
|
||||
self.device_lines = Some((lines, until.unwrap_or(u64::MAX), self.current));
|
||||
}
|
||||
|
||||
/// [`Self::lines`] and the count they were read at, 0 where no answer
|
||||
/// could change with the count.
|
||||
fn counted_lines(&mut self) -> (Lines, u64) {
|
||||
|
||||
@@ -174,6 +174,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
version,
|
||||
tcr: self.cpu.regime_tcr(),
|
||||
};
|
||||
self.pointer.set_key_storage(self.pointer_key_storage());
|
||||
let stripping = self.pointer.revalidate(inputs);
|
||||
let trapped = self.pointer_authentication_trapped();
|
||||
let enables = self.pointer_key_enables();
|
||||
|
||||
@@ -714,6 +714,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
};
|
||||
// A block the run made hot, once its exit completed and linked.
|
||||
self.tier2_after_run();
|
||||
self.release_ephemeral_alias();
|
||||
step
|
||||
}
|
||||
|
||||
@@ -965,12 +966,24 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
self.direct_exit = Some((index, record.incarnation(), next_pc, word));
|
||||
return false;
|
||||
};
|
||||
// Shared code runs at every alias's page: it enters only code that
|
||||
// does too.
|
||||
let exit = block.successors[position];
|
||||
// Shared code runs at every alias's page: it cannot chain directly
|
||||
// into non-shared code (such as a region, PAC, system, or HLE block),
|
||||
// so settle the exit through a relative lookup tail that resolves
|
||||
// `page_base + offset` to each alias's own target block.
|
||||
if block.marks.independent() && !code.blocks[target].marks.shared() {
|
||||
let point = match exit.slot {
|
||||
0 => chain::direct_patch(exit.site),
|
||||
slot => chain::slot_patch(exit.site - u64::from(slot)),
|
||||
};
|
||||
let offset = (next_pc & (FETCH_PAGE - 1)) as i32;
|
||||
let mut table = code.cache_at(board::LockSite::Link);
|
||||
if self.link_relative(&mut table, point, offset, retired, word) {
|
||||
record.settle(position);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
let exit = block.successors[position];
|
||||
let site = exit.site;
|
||||
let entry = code.blocks[target].code.0 as u64;
|
||||
// A slot's body runs in the block's own code, once: its patch
|
||||
|
||||
@@ -78,14 +78,57 @@ impl Marks {
|
||||
/// at, owners among them; read and written under its own lock, inside a
|
||||
/// shard's when both are held. An entry may outlive its slot: each is
|
||||
/// checked against the slot's block before it is used.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Table {
|
||||
slots: BTreeMap<(usize, u64), u32>,
|
||||
owners: BTreeMap<usize, u32>,
|
||||
/// Number of `slots` entries at which dead entries are next swept,
|
||||
/// growing geometrically with live size so a large live working set
|
||||
/// never triggers an O(N) sweep on every alias insert.
|
||||
next_prune: usize,
|
||||
}
|
||||
|
||||
/// Entries past which [`Table`] drops those whose slots went.
|
||||
const TABLE_BOUND: usize = 1 << 16;
|
||||
impl Default for Table {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
slots: BTreeMap::new(),
|
||||
owners: BTreeMap::new(),
|
||||
next_prune: TABLE_BOUND,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// Drop entries whose slots are no longer installed once `slots` reaches
|
||||
/// `next_prune`, then advance `next_prune` geometrically above the
|
||||
/// surviving live count. Returns whether a sweep ran.
|
||||
pub(super) fn prune_if_needed(&mut self, blocks: &board::Blocks) -> bool {
|
||||
if self.slots.len() < self.next_prune {
|
||||
return false;
|
||||
}
|
||||
self.slots
|
||||
.retain(|_, slot| blocks.installed(*slot as usize).is_some());
|
||||
self.owners
|
||||
.retain(|_, slot| blocks.installed(*slot as usize).is_some());
|
||||
self.next_prune = self.slots.len().saturating_mul(2).max(TABLE_BOUND);
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn test_seed(&mut self, count: usize, slot: u32) {
|
||||
for i in 0..count {
|
||||
self.slots.insert((i, 0), slot);
|
||||
self.owners.insert(i, slot);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn test_state(&self) -> (usize, usize, usize) {
|
||||
(self.slots.len(), self.owners.len(), self.next_prune)
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimum `slots` entries before [`Table`] sweeps dead slots.
|
||||
pub(super) const TABLE_BOUND: usize = 1 << 16;
|
||||
|
||||
/// What sharing did, for the beat's log (`PES SHARE ALIASES`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
@@ -148,6 +191,9 @@ pub(super) struct Share {
|
||||
pub(super) on: bool,
|
||||
/// The aliases runs' ends named last.
|
||||
found: Box<[Found]>,
|
||||
/// Unindexed alias slot synthesized for a concurrently retired owner so
|
||||
/// the current native run's exit or fault can finish before release.
|
||||
ephemeral: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for Share {
|
||||
@@ -155,6 +201,7 @@ impl Default for Share {
|
||||
Self {
|
||||
on: false,
|
||||
found: vec![(u32::MAX, 0, 0, 0, 0); FOUND].into_boxed_slice(),
|
||||
ephemeral: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,27 +260,32 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
return Ok(alias as usize);
|
||||
}
|
||||
let (code, pc) = (block.code, page | (block.pc & PAGE));
|
||||
let alias = match self.slot_of(code, page) {
|
||||
Some(alias) => alias,
|
||||
let (alias, cacheable) = match self.slot_of(code, page) {
|
||||
Some(alias) => (alias, true),
|
||||
None => match self.make_alias(index, pc, false)? {
|
||||
Some(alias) => alias,
|
||||
None => {
|
||||
self.statistics.share_aliases.failed += 1;
|
||||
return Err(self.unsupported(RequirementKind::Native(
|
||||
"shared code ran at a page whose alias could not be made",
|
||||
)));
|
||||
}
|
||||
Some(alias) => (alias, true),
|
||||
None => match self.make_retired_alias(index, pc) {
|
||||
Some(alias) => (alias, false),
|
||||
None => {
|
||||
self.statistics.share_aliases.failed += 1;
|
||||
return Err(self.unsupported(RequirementKind::Native(
|
||||
"shared code ran at a page whose alias could not be made",
|
||||
)));
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
self.statistics.share_aliases.mapped += 1;
|
||||
let alias_incarnation = self.code.blocks.record(alias).incarnation();
|
||||
self.share.found[at] = (
|
||||
index as u32,
|
||||
incarnation,
|
||||
page,
|
||||
alias as u32,
|
||||
alias_incarnation,
|
||||
);
|
||||
if cacheable {
|
||||
let alias_incarnation = self.code.blocks.record(alias).incarnation();
|
||||
self.share.found[at] = (
|
||||
index as u32,
|
||||
incarnation,
|
||||
page,
|
||||
alias as u32,
|
||||
alias_incarnation,
|
||||
);
|
||||
}
|
||||
Ok(alias)
|
||||
}
|
||||
|
||||
@@ -442,14 +494,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
.aliases
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
if table.slots.len() > TABLE_BOUND {
|
||||
table
|
||||
.slots
|
||||
.retain(|_, slot| shared.blocks.installed(*slot as usize).is_some());
|
||||
table
|
||||
.owners
|
||||
.retain(|_, slot| shared.blocks.installed(*slot as usize).is_some());
|
||||
}
|
||||
table.prune_if_needed(&shared.blocks);
|
||||
table.slots.insert((code.0, pc & !PAGE), slot as u32);
|
||||
}
|
||||
drop(cache);
|
||||
@@ -457,6 +502,62 @@ impl<H: Host, D: Devices> Machine<H, D> {
|
||||
Ok(Some(slot))
|
||||
}
|
||||
|
||||
/// Synthesize an unpublished alias slot at `pc` for a shared `source` block
|
||||
/// whose arena part was concurrently retired while this PE was executing
|
||||
/// it. Stambha's grace period keeps `source` and its recovery rows intact
|
||||
/// until this PE completes the run; the returned slot is held only for the
|
||||
/// remainder of `execute()` and reclaimed via [`Self::release_ephemeral_alias`].
|
||||
fn make_retired_alias(&mut self, source: usize, pc: u64) -> Option<usize> {
|
||||
self.release_ephemeral_alias();
|
||||
let shared = Arc::clone(&self.code);
|
||||
let block = shared.blocks.get(source)?;
|
||||
let delta = (pc & !PAGE).wrapping_sub(block.pc & !PAGE);
|
||||
let rows = shared
|
||||
.blocks
|
||||
.recovery()
|
||||
.get(&source)
|
||||
.and_then(|owner| owner.rebased(delta));
|
||||
let slot = self.take_slot().or_else(|| self.retire_for_slot())?;
|
||||
let Some(block) = shared.blocks.get(source) else {
|
||||
self.release_alias(slot);
|
||||
return None;
|
||||
};
|
||||
let alias = Block {
|
||||
pc,
|
||||
physical: block.physical,
|
||||
code: block.code,
|
||||
instructions: block.instructions,
|
||||
variant: block.variant,
|
||||
successors: Box::default(),
|
||||
dynamic_site: block.dynamic_site,
|
||||
landing: block.landing,
|
||||
terminal: block.terminal,
|
||||
source_hash: block.source_hash,
|
||||
installer: self.current as u8,
|
||||
part: block.part,
|
||||
marks: Marks::ALIASED,
|
||||
hle: None,
|
||||
tier2: false,
|
||||
};
|
||||
if let Some(old) = shared.blocks.vacate(slot) {
|
||||
self.keep_successor_box(old.successors);
|
||||
}
|
||||
shared.blocks.fill(slot, alias);
|
||||
if let Some(rows) = rows {
|
||||
shared.blocks.recovery().insert(slot, rows);
|
||||
}
|
||||
self.share.ephemeral = Some(slot);
|
||||
Some(slot)
|
||||
}
|
||||
|
||||
/// Release any unpublished alias slot created by [`Self::make_retired_alias`]
|
||||
/// once the native run's exit or fault handling has completed.
|
||||
pub(super) fn release_ephemeral_alias(&mut self) {
|
||||
if let Some(slot) = self.share.ephemeral.take() {
|
||||
self.release_alias(slot);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give back `slot`, filled for an alias that was never published.
|
||||
fn release_alias(&mut self, slot: usize) {
|
||||
let shared = Arc::clone(&self.code);
|
||||
|
||||
@@ -229,3 +229,94 @@ fn a_fault_in_an_alias_recovers_at_the_aliass_pc() {
|
||||
assert_eq!(machine.cpu.read(SystemRegister::ELR_EL1), MOVED);
|
||||
assert_eq!(machine.statistics.share_aliases.shared_fetches, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_table_prune_threshold_grows_geometrically_and_shrinks_after_eviction() {
|
||||
let mut machine = two_mappings(true);
|
||||
let owners = fetch_all(&mut machine, BASE);
|
||||
let live_slot = owners[0] as u32;
|
||||
let dead_slot = u32::MAX - 1;
|
||||
let bound = super::super::share_aliases::TABLE_BOUND;
|
||||
|
||||
let mut table = machine.code.aliases.lock().unwrap();
|
||||
// Seed a live table past TABLE_BOUND: one sweep runs and raises next_prune to 2 * live.
|
||||
table.test_seed(bound + 100, live_slot);
|
||||
assert!(table.prune_if_needed(&machine.code.blocks));
|
||||
let (slots, owners_len, next_prune) = table.test_state();
|
||||
assert!(slots >= bound + 100);
|
||||
assert!(owners_len >= bound + 100);
|
||||
assert_eq!(next_prune, slots * 2);
|
||||
// Subsequent inserts below the doubled threshold do not trigger O(N) sweeps.
|
||||
assert!(!table.prune_if_needed(&machine.code.blocks));
|
||||
|
||||
// When entries become dead and the threshold is reached again, dead slots
|
||||
// are dropped and next_prune returns to TABLE_BOUND.
|
||||
table.test_seed(next_prune, dead_slot);
|
||||
assert!(table.prune_if_needed(&machine.code.blocks));
|
||||
let (after_slots, _, after_next) = table.test_state();
|
||||
assert!(after_slots < bound);
|
||||
assert_eq!(after_next, bound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_block_same_page_exit_to_unshared_target_settles_through_relative_tail() {
|
||||
// B +0x10 at offset 0 (position independent) -> MRS X0, SCTLR_EL1 at offset 0x10 (not shared).
|
||||
const B_PLUS_16: u32 = 0x1400_0004;
|
||||
const MRS_X0_SCTLR_EL1: u32 = 0xd538_1000;
|
||||
let mut machine = two_mappings(true);
|
||||
machine.host.ram[..4].copy_from_slice(&B_PLUS_16.to_le_bytes());
|
||||
machine.host.ram[0x10..0x14].copy_from_slice(&MRS_X0_SCTLR_EL1.to_le_bytes());
|
||||
|
||||
let Ok(Fetched::Block(owner)) = machine.fetch_block(BASE, false) else {
|
||||
panic!("shared source block");
|
||||
};
|
||||
let Ok(Fetched::Block(target)) = machine.fetch_block(BASE + 0x10, false) else {
|
||||
panic!("unshared target block");
|
||||
};
|
||||
assert!(machine.code.blocks[owner].marks.independent());
|
||||
assert!(!machine.code.blocks[target].marks.shared());
|
||||
|
||||
// First link settles the exit through a relative lookup tail instead of
|
||||
// leaving it unlinked forever.
|
||||
assert!(machine.link(owner, BASE + 0x10, ExitKind::Direct));
|
||||
let record = machine.code.blocks.record(owner);
|
||||
assert!(record.linked(0));
|
||||
assert!(!record.chained(0));
|
||||
|
||||
// Subsequent calls (from owner or an alias) see the exit already settled.
|
||||
assert!(!machine.link(owner, BASE + 0x10, ExitKind::Direct));
|
||||
let Ok(Fetched::Block(alias)) = machine.fetch_block(MOVED, false) else {
|
||||
panic!("alias block");
|
||||
};
|
||||
assert!(machine.code.blocks[alias].marks.alias());
|
||||
assert!(!machine.link(alias, MOVED + 0x10, ExitKind::Direct));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_block_handles_concurrently_retired_owner_via_ephemeral_alias() {
|
||||
let mut machine = two_mappings(true);
|
||||
let owners = fetch_all(&mut machine, BASE);
|
||||
let owner = owners[0];
|
||||
let expected_rows: Vec<u64> = row_pcs(&machine, owner)
|
||||
.iter()
|
||||
.map(|pc| pc + (MOVED - BASE))
|
||||
.collect();
|
||||
|
||||
// Simulate another PE retiring the owner's arena part while this PE is
|
||||
// still inside native execution: installed() is None, while get() and
|
||||
// recovery() stay readable until this PE crosses its grace boundary.
|
||||
machine.code.blocks.retire(owner);
|
||||
assert!(machine.code.blocks.installed(owner).is_none());
|
||||
assert!(machine.code.blocks.get(owner).is_some());
|
||||
|
||||
let alias = machine
|
||||
.shared_block(owner, MOVED)
|
||||
.expect("concurrently retired owner must not fatally stop the PE");
|
||||
assert_ne!(alias, owner);
|
||||
assert_eq!(machine.code.blocks[alias].pc, MOVED);
|
||||
assert_eq!(row_pcs(&machine, alias), expected_rows);
|
||||
assert_eq!(machine.statistics.share_aliases.failed, 0);
|
||||
|
||||
machine.release_ephemeral_alias();
|
||||
assert!(!machine.code.blocks.record(alias).live());
|
||||
}
|
||||