Merge current runtime master into capture shortcut validation
This commit is contained in:
commit
76791eb6b6
10 files changed
+128
-1136
No files matched your search
@@ -25,7 +25,7 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TARGET_BRANCH: codex/intel-vm-suspend
|
||||
TARGET_BRANCH: intel-vm-suspend
|
||||
UPSTREAM_REPO: steelbrain/reims-vgpu
|
||||
UPSTREAM_BRANCH: master
|
||||
GIT_AUTHOR_NAME: YXC0915
|
||||
|
||||
@@ -31,7 +31,7 @@ permissions:
|
||||
|
||||
env:
|
||||
UPSTREAM_URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
UPSTREAM_BRANCH: codex/intel-vm-suspend
|
||||
UPSTREAM_BRANCH: intel-vm-suspend
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
@@ -128,31 +128,22 @@ jobs:
|
||||
git -C $work submodule update --init --depth 1 vendor/qemu
|
||||
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
|
||||
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
|
||||
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
|
||||
$utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs')
|
||||
if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' }
|
||||
$utilRev = $Matches[1]
|
||||
git init -q $utilRepo
|
||||
if ($LASTEXITCODE) { throw 'reims-util init failed' }
|
||||
git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev
|
||||
if ($LASTEXITCODE) { throw 'reims-util fetch failed' }
|
||||
git -C $utilRepo checkout -q --detach FETCH_HEAD
|
||||
if ($LASTEXITCODE) { throw 'reims-util checkout failed' }
|
||||
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
|
||||
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml')
|
||||
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
|
||||
$m2vRev = $Matches[1]
|
||||
} else {
|
||||
$lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock')
|
||||
if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
|
||||
$m2vRev = $Matches[1]
|
||||
$pins = & ./packaging/windows-runtime/scripts/read-runtime-dependencies.ps1 -RuntimeRepo $work
|
||||
function Get-DependencyCheckout($pin, [string]$path) {
|
||||
git init -q $path
|
||||
if ($LASTEXITCODE) { throw "Could not initialize $path" }
|
||||
git -C $path remote add origin $pin.Url
|
||||
if ($LASTEXITCODE) { throw "Could not add origin for $path" }
|
||||
git -C $path fetch -q --depth 1 origin $pin.Rev
|
||||
if ($LASTEXITCODE) { throw "Could not fetch $($pin.Url)@$($pin.Rev)" }
|
||||
git -C $path checkout -q --detach $pin.Rev
|
||||
if ($LASTEXITCODE) { throw "Could not check out $($pin.Url)@$($pin.Rev)" }
|
||||
Write-Host "Using $($pin.Url)@$($pin.Rev)"
|
||||
}
|
||||
git init -q $m2vRepo
|
||||
if ($LASTEXITCODE) { throw 'metal2vulkan init failed' }
|
||||
git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev
|
||||
if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' }
|
||||
git -C $m2vRepo checkout -q --detach FETCH_HEAD
|
||||
if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' }
|
||||
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
|
||||
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
|
||||
Get-DependencyCheckout $pins.Util $utilRepo
|
||||
Get-DependencyCheckout $pins.Metal $m2vRepo
|
||||
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
|
||||
|
||||
# Applies what applies, skips what upstream already has, stops on a
|
||||
@@ -170,13 +161,17 @@ jobs:
|
||||
}
|
||||
if (-not $ok) { throw 'patch queue does not apply' }
|
||||
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
|
||||
$m2vFwd = $m2vRepo.Replace('\', '/')
|
||||
$cargoCfg = @"
|
||||
[patch."https://github.com/steelbrain/metal2vulkan"]
|
||||
$m2vChanges = git -C $m2vRepo status --porcelain
|
||||
if ($LASTEXITCODE) { throw 'Could not read metal2vulkan checkout status' }
|
||||
if ($m2vChanges) {
|
||||
$m2vFwd = $m2vRepo.Replace('\', '/')
|
||||
$cargoCfg = @"
|
||||
[patch."$($pins.Metal.Url)"]
|
||||
metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" }
|
||||
metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" }
|
||||
"@ -replace '(?m)^ ', ''
|
||||
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
|
||||
"@
|
||||
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
"REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV
|
||||
"METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV
|
||||
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
|
||||
@@ -259,8 +254,13 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:CURRENT_ONLY -eq 'true') {
|
||||
$remote = git ls-remote $env:UPSTREAM_URL "refs/heads/$env:UPSTREAM_BRANCH"
|
||||
if ($LASTEXITCODE -or !$remote) { throw 'Could not resolve the runtime maintenance tip' }
|
||||
$ref = "refs/heads/$env:UPSTREAM_BRANCH"
|
||||
$remote = git ls-remote $env:UPSTREAM_URL $ref
|
||||
if ($LASTEXITCODE -ne 0) { throw "Could not query the runtime maintenance ref $ref" }
|
||||
if (!$remote) {
|
||||
Write-Warning "Skipping Alpha publication because $ref no longer exists. The verified archives are available in the workflow artifact."
|
||||
return
|
||||
}
|
||||
if (($remote -split '\s+')[0] -ne '${{ needs.resolve.outputs.commit }}') {
|
||||
Write-Host 'Skipping Alpha publication for a superseded runtime commit.'
|
||||
return
|
||||
|
||||
@@ -4,23 +4,18 @@
|
||||
|
||||
| 组件 | 源码 | 维护范围 |
|
||||
| :--- | :--- | :--- |
|
||||
| Reims vGPU | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu/tree/codex/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 |
|
||||
| QEMU | [`yxc0915/qemu-reims-vgpu`](https://github.com/yxc0915/qemu-reims-vgpu/tree/codex/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 |
|
||||
| Reims vGPU | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu/tree/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 |
|
||||
| QEMU | [`reims-go/qemu-reims-vgpu`](https://github.com/reims-go/qemu-reims-vgpu/tree/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 |
|
||||
| metal2vulkan | [`reims-go/metal2vulkan`](https://github.com/reims-go/metal2vulkan/tree/development) | Vulkan 渲染、附件反馈和 GPU 地址重放 |
|
||||
| reims-util | [`reims-go/reims-util`](https://github.com/reims-go/reims-util/tree/development) | OpenCore 和 macOS 安装介质,包括并发离线下载 |
|
||||
|
||||
Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runtime.json` 声明运行时能力。更新 QEMU 时先把新提交推到 QEMU fork,再更新 Reims vGPU 的子模块指针。Reims-Go 构建据此记录两个源码仓库及提交号。
|
||||
Reims vGPU 用 `vendor/qemu` 固定 QEMU 提交,用 `Cargo.toml` 和 `Cargo.lock` 固定 metal2vulkan,用 `crates/reims-ctl/src/reims_util.rs` 固定 reims-util。CI 根据这些固定值检出依赖,在运行时清单和对应源码包中记录四个组件的仓库及实际提交。
|
||||
|
||||
Alpha 编号与挂起兼容判定见 [Alpha 运行时编号与挂起兼容性规范](../versioning.md)。
|
||||
|
||||
## 构建时应用的依赖补丁
|
||||
|
||||
[`series.txt`](series.txt) 是可执行清单。依赖检出版本由 Reims vGPU 源码固定。补丁冲突会停止构建。
|
||||
|
||||
| 补丁 | 依赖 | 作用 |
|
||||
| :--- | :--- | :--- |
|
||||
| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `steelbrain/reims-util` | 有 Apple 分块校验数据时并发下载离线安装包,按顺序验证并写入镜像。 |
|
||||
| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `steelbrain/metal2vulkan` | 读取和恢复缓冲、纹理及事件状态,为 GPU 挂起重放提供依赖。 |
|
||||
|
||||
构建通过 Cargo 的本地源码覆盖使用已打补丁的 `metal2vulkan`。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
|
||||
[`series.txt`](series.txt) 目前为空。临时补丁按清单顺序应用,冲突会停止构建。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -45,5 +40,5 @@ Alpha 编号与挂起兼容判定见 [Alpha 运行时编号与挂起兼容性规
|
||||
每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。
|
||||
|
||||
1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。
|
||||
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml)。
|
||||
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/reims-go/reims-vgpu/actions/workflows/runtime-preview.yml)。
|
||||
3. 在真实宿主运行 [`smoke-runtime.ps1`](../scripts/smoke-runtime.ps1) 完成冒烟并人工确认后,将对应 Release 升级为 `stable`。
|
||||
@@ -1,525 +0,0 @@
|
||||
diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs
|
||||
index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/block.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/block.rs
|
||||
@@ -54,6 +54,12 @@ impl Block {
|
||||
Block { claim }
|
||||
}
|
||||
|
||||
+ /// Returns capture/replay address metadata for this block (if supported).
|
||||
+ pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
|
||||
+ let (core, block) = self.held().ok()?;
|
||||
+ core.pool.capture_info(&block.memory)
|
||||
+ }
|
||||
+
|
||||
/// Whether the block is of `core`'s device.
|
||||
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
|
||||
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
|
||||
diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs
|
||||
index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/device.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/device.rs
|
||||
@@ -273,6 +273,7 @@ pub(crate) struct Core {
|
||||
/// every render pipeline takes its colour flag, and a draw reads an attachment of its pass
|
||||
/// with the image in the feedback layout.
|
||||
pub(crate) feedback_loop: bool,
|
||||
+ pub(crate) capture_replay: bool,
|
||||
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
|
||||
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
|
||||
pub(crate) fault: Option<ash::ext::device_fault::Device>,
|
||||
@@ -860,6 +861,7 @@ impl Device {
|
||||
ticks,
|
||||
calibrated,
|
||||
feedback_loop: capabilities.feedback_loop,
|
||||
+ capture_replay: capabilities.buffer_device_address_capture_replay,
|
||||
fault,
|
||||
indirect,
|
||||
attachment_reads: capabilities.attachment_reads,
|
||||
@@ -1140,6 +1142,41 @@ impl Device {
|
||||
/// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped)
|
||||
/// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the
|
||||
/// device is out of memory or lost; [`Error::Quiesced`].
|
||||
+ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
|
||||
+ pub fn buffer_device_address_capture_replay(&self) -> bool {
|
||||
+ self.shared.core.capture_replay
|
||||
+ }
|
||||
+
|
||||
+ /// Waits non-destructively until all in-flight GPU work has completed and retired.
|
||||
+ pub fn wait_idle(&self) -> Result<(), Error> {
|
||||
+ let core = &self.shared.core;
|
||||
+ if core.closed() {
|
||||
+ return Err(Error::Quiesced);
|
||||
+ }
|
||||
+ // Wait for submitted command buffers to retire on the completion thread.
|
||||
+ let deadline = Instant::now() + Duration::from_secs(10);
|
||||
+ while core.pool.in_flight() > 0 && Instant::now() < deadline {
|
||||
+ std::thread::sleep(Duration::from_millis(1));
|
||||
+ }
|
||||
+ // SAFETY: `device` is live and wait_idle synchronizes all host queues.
|
||||
+ let _q = lock(&core.queues.runtime);
|
||||
+ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
|
||||
+ Ok(())
|
||||
+ }
|
||||
+
|
||||
+ /// Replays a previously captured block at its exact Vulkan device address.
|
||||
+ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
|
||||
+ let core = &self.shared.core;
|
||||
+ if core.closed() {
|
||||
+ return Err(Error::Quiesced);
|
||||
+ }
|
||||
+ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
|
||||
+ let info = memory.info();
|
||||
+ let block = memory::Block::new(memory, Arc::clone(core));
|
||||
+ Ok(Block::claim(core, info, block))
|
||||
+ }
|
||||
+
|
||||
+ /// Allocates a new GPU memory block of `class` and `len` bytes.
|
||||
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error> {
|
||||
let core = &self.shared.core;
|
||||
if core.closed() {
|
||||
diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs
|
||||
index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/event.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/event.rs
|
||||
@@ -140,6 +140,35 @@ impl Event {
|
||||
}
|
||||
}
|
||||
|
||||
+impl Event {
|
||||
+ /// Reads the current signaled value of this timeline event (for checkpointing).
|
||||
+ pub fn signaled_value(&self) -> u64 {
|
||||
+ let inner = &self.inner;
|
||||
+ let state = lock(&inner.state);
|
||||
+ let floor = state.observed.max(state.floor);
|
||||
+ inner.reached(None).map_or(floor, |reached| reached.max(floor))
|
||||
+ }
|
||||
+
|
||||
+ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event.
|
||||
+ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
|
||||
+ if value == 0 {
|
||||
+ return Ok(());
|
||||
+ }
|
||||
+ let inner = &self.inner;
|
||||
+ let info = vk::SemaphoreSignalInfo::default()
|
||||
+ .semaphore(inner.semaphore)
|
||||
+ .value(value);
|
||||
+ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`.
|
||||
+ unsafe { inner.core.device.signal_semaphore(&info) }
|
||||
+ .map_err(Error::vulkan("vkSignalSemaphore"))?;
|
||||
+ let mut state = lock(&inner.state);
|
||||
+ state.floor = state.floor.max(value);
|
||||
+ state.observed = state.observed.max(value);
|
||||
+ inner.changed.notify_all();
|
||||
+ Ok(())
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
impl SharedEvent {
|
||||
/// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's
|
||||
/// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout
|
||||
diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs
|
||||
index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/floor.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/floor.rs
|
||||
@@ -1079,6 +1079,8 @@ pub struct Capabilities {
|
||||
/// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback
|
||||
/// loop, the feedback layout its image moves to and the flag every render pipeline takes.
|
||||
pub feedback_loop: bool,
|
||||
+ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
|
||||
+ pub buffer_device_address_capture_replay: bool,
|
||||
/// The features device creation enables: every one the floor requires, each of the optional,
|
||||
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
|
||||
/// and fault-report ones the device reports, the attachment-read ones where
|
||||
@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
|
||||
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
|
||||
return Err(BelowFloor { missing });
|
||||
};
|
||||
+ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
|
||||
+ if capture_replay {
|
||||
+ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
|
||||
+ }
|
||||
for feature in (OPTIONAL.iter().chain(STEP_RATES))
|
||||
.chain(MIN_LOD_CLAMPS)
|
||||
.chain(FILL_MODES)
|
||||
@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
|
||||
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
|
||||
attachment_reads,
|
||||
feedback_loop,
|
||||
+ buffer_device_address_capture_replay: capture_replay,
|
||||
features,
|
||||
extensions: DEVICE_EXTENSIONS
|
||||
.iter()
|
||||
diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
|
||||
index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/lib.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/lib.rs
|
||||
@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes;
|
||||
pub use import::ImportHandle;
|
||||
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
|
||||
pub use instance::{Instance, PhysicalDevice};
|
||||
-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
|
||||
+pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
|
||||
/// `MTLLibrary`: the translator's, read from AIR or a metallib.
|
||||
/// `MTLSamplerDescriptor`: the translator's.
|
||||
pub use metal2vulkan::bind::SamplerDescriptor;
|
||||
diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs
|
||||
index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/memory.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/memory.rs
|
||||
@@ -235,8 +235,28 @@ impl AllocationId {
|
||||
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
|
||||
/// usage and a device address, spans it; an imported or exported block is the whole of an
|
||||
/// allocation of its own. Only an exported block is exportable.
|
||||
+/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
|
||||
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
+pub struct BlockCaptureInfo {
|
||||
+ /// Storage mode (`Shared` or `Private`).
|
||||
+ pub class: MemoryClass,
|
||||
+ /// Full parent Vulkan allocation length in bytes.
|
||||
+ pub alloc_len: u64,
|
||||
+ /// Offset of this block inside its parent allocation.
|
||||
+ pub offset: u64,
|
||||
+ /// Block length in bytes.
|
||||
+ pub len: u64,
|
||||
+ /// Guest-visible `VkDeviceAddress` of this block's first byte.
|
||||
+ pub gpu_address: u64,
|
||||
+ /// Opaque capture address of the parent `VkBuffer`.
|
||||
+ pub opaque_buffer_address: u64,
|
||||
+ /// Opaque capture address of the parent `VkDeviceMemory`.
|
||||
+ pub opaque_memory_address: u64,
|
||||
+}
|
||||
+
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
+/// Metadata describing an allocated GPU memory block.
|
||||
pub struct BlockInfo {
|
||||
/// The block's number.
|
||||
pub id: BlockId,
|
||||
@@ -611,6 +631,10 @@ struct Allocation {
|
||||
buffer: vk::Buffer,
|
||||
/// The device address of its first byte.
|
||||
address: u64,
|
||||
+ /// Opaque capture address of `buffer` (0 if capture-replay unsupported).
|
||||
+ opaque_buffer_address: u64,
|
||||
+ /// Opaque capture address of `memory` (0 if capture-replay unsupported).
|
||||
+ opaque_memory_address: u64,
|
||||
len: u64,
|
||||
mapping: Option<Mapping>,
|
||||
device_local: bool,
|
||||
@@ -823,6 +847,8 @@ struct State {
|
||||
/// The internal the block-maker thread took up and is making ([`run`]).
|
||||
making: Option<Internal>,
|
||||
stop: bool,
|
||||
+ replaying: bool,
|
||||
+ making_ahead: bool,
|
||||
next_id: u32,
|
||||
next_allocation: u32,
|
||||
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
|
||||
@@ -952,6 +978,8 @@ impl Pool {
|
||||
asked: [true; INTERNALS],
|
||||
making: None,
|
||||
stop: false,
|
||||
+ replaying: false,
|
||||
+ making_ahead: false,
|
||||
next_id: 1,
|
||||
next_allocation: 1,
|
||||
mapped: HashSet::new(),
|
||||
@@ -1368,6 +1396,158 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
+ /// Returns capture/replay info for a pool block, if capture-replay is enabled.
|
||||
+ pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
|
||||
+ if memory.own.is_some() {
|
||||
+ return None;
|
||||
+ }
|
||||
+ let state = self.lock();
|
||||
+ let alloc = state.allocations[memory.class.index()]
|
||||
+ .iter()
|
||||
+ .find(|a| a.memory == memory.memory)?;
|
||||
+
|
||||
+ Some(BlockCaptureInfo {
|
||||
+ class: memory.class,
|
||||
+ alloc_len: alloc.len,
|
||||
+ offset: memory.base,
|
||||
+ len: memory.len,
|
||||
+ gpu_address: memory.address,
|
||||
+ opaque_buffer_address: alloc.opaque_buffer_address,
|
||||
+ opaque_memory_address: alloc.opaque_memory_address,
|
||||
+ })
|
||||
+ }
|
||||
+
|
||||
+ /// Replays a previously captured pool block at its exact Vulkan device address.
|
||||
+ pub(crate) fn take_replayed(
|
||||
+ &self,
|
||||
+ core: &Core,
|
||||
+ cap: BlockCaptureInfo,
|
||||
+ site: Site,
|
||||
+ ) -> Result<Memory, Error> {
|
||||
+ let index = cap.class.index();
|
||||
+ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
|
||||
+ // or a pre-stocked idle reserve landed at the exact same address!).
|
||||
+ {
|
||||
+ let mut state = self.lock();
|
||||
+ if state.stop {
|
||||
+ return Err(Error::Quiesced);
|
||||
+ }
|
||||
+ let id = number(&mut state)?;
|
||||
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
|
||||
+ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
|
||||
+ a.address == want_base
|
||||
+ && a.opaque_buffer_address == cap.opaque_buffer_address
|
||||
+ && a.opaque_memory_address == cap.opaque_memory_address
|
||||
+ && a.len == cap.alloc_len
|
||||
+ }) {
|
||||
+ if alloc.free.take_at(cap.offset, cap.len) {
|
||||
+ let carve = alloc.carve(cap.offset);
|
||||
+ alloc.live += 1;
|
||||
+ alloc.placed += cap.len;
|
||||
+ alloc.ahead = false;
|
||||
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
|
||||
+ self.settle(&mut state, cap.class);
|
||||
+ self.changed.notify_all();
|
||||
+ return Ok(carve.block(id, cap.class, cap.len));
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
|
||||
+ // and purge idle reserve slabs so none collide with the target opaque VA!
|
||||
+ let idle_allocs: Vec<Allocation> = {
|
||||
+ let mut state = self.lock();
|
||||
+ state.replaying = true;
|
||||
+ while state.making_ahead {
|
||||
+ state = self.wait(state);
|
||||
+ }
|
||||
+ // Re-check if an ahead allocation that just finished landed at the exact target VA!
|
||||
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
|
||||
+ let hit = state.allocations[index].iter_mut().find_map(|a| {
|
||||
+ if a.address == want_base
|
||||
+ && a.opaque_buffer_address == cap.opaque_buffer_address
|
||||
+ && a.opaque_memory_address == cap.opaque_memory_address
|
||||
+ && a.len == cap.alloc_len
|
||||
+ && a.free.take_at(cap.offset, cap.len)
|
||||
+ {
|
||||
+ let carve = a.carve(cap.offset);
|
||||
+ a.live += 1;
|
||||
+ a.placed += cap.len;
|
||||
+ a.ahead = false;
|
||||
+ Some(carve)
|
||||
+ } else {
|
||||
+ None
|
||||
+ }
|
||||
+ });
|
||||
+ if let Some(carve) = hit {
|
||||
+ let id = number(&mut state)?;
|
||||
+ state.replaying = false;
|
||||
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
|
||||
+ self.settle(&mut state, cap.class);
|
||||
+ self.changed.notify_all();
|
||||
+ return Ok(carve.block(id, cap.class, cap.len));
|
||||
+ }
|
||||
+ let mut drained = Vec::new();
|
||||
+ for c in MemoryClass::ALL {
|
||||
+ let ci = c.index();
|
||||
+ let mut kept = Vec::new();
|
||||
+ for a in state.allocations[ci].drain(..) {
|
||||
+ if a.live == 0 {
|
||||
+ drained.push(a);
|
||||
+ } else {
|
||||
+ kept.push(a);
|
||||
+ }
|
||||
+ }
|
||||
+ state.allocations[ci] = kept;
|
||||
+ self.settle(&mut state, c);
|
||||
+ }
|
||||
+ drained
|
||||
+ };
|
||||
+ for a in idle_allocs {
|
||||
+ free_idle(core, a);
|
||||
+ }
|
||||
+ // 3. Allocate at the exact captured opaque buffer + memory addresses.
|
||||
+ let alloc_res = make_allocation_ex(
|
||||
+ core,
|
||||
+ cap.class,
|
||||
+ cap.alloc_len,
|
||||
+ Some(site),
|
||||
+ Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
|
||||
+ );
|
||||
+ let mut allocation = match alloc_res {
|
||||
+ Ok(a) => a,
|
||||
+ Err(e) => {
|
||||
+ let mut state = self.lock();
|
||||
+ state.replaying = false;
|
||||
+ self.changed.notify_all();
|
||||
+ return Err(e);
|
||||
+ }
|
||||
+ };
|
||||
+ let mapped = self.map(&allocation, cap.class, true);
|
||||
+ if !mapped {
|
||||
+ free_allocation(core, allocation);
|
||||
+ let mut state = self.lock();
|
||||
+ state.replaying = false;
|
||||
+ self.changed.notify_all();
|
||||
+ return Err(Error::Limit(Limit::AllocationNotMapped {
|
||||
+ class: cap.class,
|
||||
+ len: cap.alloc_len,
|
||||
+ }));
|
||||
+ }
|
||||
+ let ok = allocation.free.take_at(cap.offset, cap.len);
|
||||
+ debug_assert!(ok, "fresh allocation must contain captured block range");
|
||||
+ let mut state = self.lock();
|
||||
+ let id = number(&mut state)?;
|
||||
+ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
|
||||
+ allocation.live = 1;
|
||||
+ allocation.placed = cap.len;
|
||||
+ state.allocations[index].push(allocation);
|
||||
+ state.replaying = false;
|
||||
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
|
||||
+ self.settle(&mut state, cap.class);
|
||||
+ self.changed.notify_all();
|
||||
+ Ok(memory)
|
||||
+ }
|
||||
+
|
||||
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
|
||||
/// allocation at once.
|
||||
pub(crate) fn give_back(&self, memory: Memory) {
|
||||
@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
state = pool.lock();
|
||||
continue;
|
||||
}
|
||||
- let wanted = (MemoryClass::ALL.into_iter())
|
||||
- .find(|&class| !state.failed[class.index()] && !state.whole(class));
|
||||
+ let wanted = (!state.replaying).then(|| {
|
||||
+ (MemoryClass::ALL.into_iter())
|
||||
+ .find(|&class| !state.failed[class.index()] && !state.whole(class))
|
||||
+ }).flatten();
|
||||
if let Some(class) = wanted {
|
||||
+ state.making_ahead = true;
|
||||
drop(state);
|
||||
let made = ahead(&core, class);
|
||||
state = pool.lock();
|
||||
+ state.making_ahead = false;
|
||||
match made {
|
||||
// Idle from now: the reserve, which the idle rule does not weigh.
|
||||
Some(mut allocation) => {
|
||||
@@ -2022,6 +2206,16 @@ fn make_allocation(
|
||||
class: MemoryClass,
|
||||
len: u64,
|
||||
site: Option<Site>,
|
||||
+) -> Result<Allocation, Error> {
|
||||
+ make_allocation_ex(core, class, len, site, None)
|
||||
+}
|
||||
+
|
||||
+fn make_allocation_ex(
|
||||
+ core: &Core,
|
||||
+ class: MemoryClass,
|
||||
+ len: u64,
|
||||
+ site: Option<Site>,
|
||||
+ replay: Option<(u64, u64)>,
|
||||
) -> Result<Allocation, Error> {
|
||||
let device = &core.device;
|
||||
let (id, freed_at) = {
|
||||
@@ -2031,22 +2225,38 @@ fn make_allocation(
|
||||
state.freed_at[class.index()],
|
||||
)
|
||||
};
|
||||
- let info = vk::BufferCreateInfo::default()
|
||||
+ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
|
||||
+ .opaque_capture_address(replay.map_or(0, |(b, _)| b));
|
||||
+ let mut info = vk::BufferCreateInfo::default()
|
||||
.size(len)
|
||||
.usage(floor::BUFFER_USAGE)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE);
|
||||
+ if core.capture_replay {
|
||||
+ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
|
||||
+ if replay.is_some_and(|(b, _)| b != 0) {
|
||||
+ info = info.push_next(&mut buf_opaque);
|
||||
+ }
|
||||
+ }
|
||||
// SAFETY: the device is live, and the create info valid: `len` is at most its
|
||||
// `maxBufferSize`.
|
||||
let buffer =
|
||||
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
|
||||
// SAFETY: the buffer is the device's.
|
||||
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
|
||||
- let mut flags =
|
||||
- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
|
||||
- let allocate_info = vk::MemoryAllocateInfo::default()
|
||||
+ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
|
||||
+ if core.capture_replay {
|
||||
+ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
|
||||
+ }
|
||||
+ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
|
||||
+ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
|
||||
+ .opaque_capture_address(replay.map_or(0, |(_, m)| m));
|
||||
+ let mut allocate_info = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(requirements.size.max(len))
|
||||
.memory_type_index(core.memory_type(class))
|
||||
.push_next(&mut flags);
|
||||
+ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) {
|
||||
+ allocate_info = allocate_info.push_next(&mut mem_opaque);
|
||||
+ }
|
||||
let bits = requirements.memory_type_bits;
|
||||
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and
|
||||
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
|
||||
@@ -2065,6 +2275,8 @@ fn make_allocation(
|
||||
memory,
|
||||
buffer,
|
||||
address: 0,
|
||||
+ opaque_buffer_address: 0,
|
||||
+ opaque_memory_address: 0,
|
||||
len,
|
||||
mapping: None,
|
||||
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
|
||||
@@ -2101,6 +2313,13 @@ fn make_allocation(
|
||||
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
|
||||
// SAFETY: the buffer has device-address usage and is bound.
|
||||
allocation.address = unsafe { device.get_buffer_device_address(&of) };
|
||||
+ if core.capture_replay {
|
||||
+ allocation.opaque_buffer_address =
|
||||
+ unsafe { device.get_buffer_opaque_capture_address(&of) };
|
||||
+ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
|
||||
+ allocation.opaque_memory_address =
|
||||
+ unsafe { device.get_device_memory_opaque_capture_address(&mof) };
|
||||
+ }
|
||||
(core.spans).made(
|
||||
buffer,
|
||||
allocation.address,
|
||||
diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs
|
||||
index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644
|
||||
--- a/crates/metal2vulkan-runtime/src/places.rs
|
||||
+++ b/crates/metal2vulkan-runtime/src/places.rs
|
||||
@@ -248,6 +248,33 @@ impl Ranges {
|
||||
Some(at)
|
||||
}
|
||||
|
||||
+ /// Takes the exact range `at..at + len` if it is completely free.
|
||||
+ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
|
||||
+ let Some(stop) = at.checked_add(len) else {
|
||||
+ return false;
|
||||
+ };
|
||||
+ let Some(index) = self
|
||||
+ .free
|
||||
+ .iter()
|
||||
+ .position(|&(start, end)| start <= at && stop <= end)
|
||||
+ else {
|
||||
+ return false;
|
||||
+ };
|
||||
+ let (start, end) = self.free[index];
|
||||
+ match (start < at, stop < end) {
|
||||
+ (false, false) => {
|
||||
+ self.free.remove(index);
|
||||
+ }
|
||||
+ (true, false) => self.free[index] = (start, at),
|
||||
+ (false, true) => self.free[index] = (stop, end),
|
||||
+ (true, true) => {
|
||||
+ self.free[index] = (start, at);
|
||||
+ self.free.insert(index + 1, (stop, end));
|
||||
+ }
|
||||
+ }
|
||||
+ true
|
||||
+ }
|
||||
+
|
||||
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
|
||||
pub(crate) fn give(&mut self, offset: u64, len: u64) {
|
||||
let end = offset + len;
|
||||
@@ -1,524 +0,0 @@
|
||||
diff --git a/src/http.rs b/src/http.rs
|
||||
index 69aeb817b8dc1ff2cebb91bbcad5d4ad749b1540..777a7d8adf65faaff0f08e228a4165ed48984e42 100644
|
||||
--- a/src/http.rs
|
||||
+++ b/src/http.rs
|
||||
@@ -13,13 +13,15 @@
|
||||
use crate::progress::{self, Reporter};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::fs::{File, OpenOptions};
|
||||
-use std::io::{Read, Seek, SeekFrom, Write};
|
||||
+use std::io::{Cursor, Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
+use std::thread;
|
||||
use std::time::Duration;
|
||||
use ureq::Agent;
|
||||
|
||||
/// The most each request asks for.
|
||||
pub const SEGMENT: u64 = 64 << 20;
|
||||
+const PARALLEL_REQUESTS: usize = 4;
|
||||
/// How long a request may take to send its range: a stall is noticed within this. (On a
|
||||
/// connection too slow to send a whole range in it, each request sends what it can.)
|
||||
pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180);
|
||||
@@ -124,6 +126,8 @@ pub struct Download<'a> {
|
||||
/// For requests the server refuses (401, 403): new headers, such as a fresh asset token.
|
||||
pub refresh: Option<&'a mut dyn FnMut() -> Result<Headers>>,
|
||||
pub user_agent: Option<&'static str>,
|
||||
+ /// Fetch the public installer package in parallel within each checked segment.
|
||||
+ pub parallel: bool,
|
||||
/// Failed requests in a row, with no byte received between them, before it gives up:
|
||||
/// [`MAX_FAILURES`], or fewer when there is another place to download the file from.
|
||||
pub tries: u32,
|
||||
@@ -138,6 +142,7 @@ impl Download<'_> {
|
||||
size: None,
|
||||
refresh: None,
|
||||
user_agent: None,
|
||||
+ parallel: false,
|
||||
tries: MAX_FAILURES,
|
||||
}
|
||||
}
|
||||
@@ -229,6 +234,8 @@ pub fn download(
|
||||
let mut failures = 0u32;
|
||||
let mut bad_chunks = 0u32;
|
||||
let mut buf = vec![0u8; 1 << 18];
|
||||
+ let mut parallel =
|
||||
+ d.parallel && check.verifies() && d.headers.is_empty() && d.user_agent.is_none();
|
||||
r.progress(have, total);
|
||||
|
||||
'requests: loop {
|
||||
@@ -240,94 +247,116 @@ pub fn download(
|
||||
Some(t) => (have + SEGMENT).min(t) - 1,
|
||||
None => have + SEGMENT - 1,
|
||||
};
|
||||
- let mut req = agent
|
||||
- .get(&d.url)
|
||||
- .header("Range", format!("bytes={have}-{end}"));
|
||||
- for (k, v) in &d.headers {
|
||||
- req = req.header(k, v);
|
||||
- }
|
||||
- let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
|
||||
- if let Some(ua) = d.user_agent {
|
||||
- cfg = cfg.user_agent(ua);
|
||||
- }
|
||||
- let resp = match cfg.build().call() {
|
||||
- Ok(resp) => resp,
|
||||
- Err(e) => {
|
||||
- failures += 1;
|
||||
- retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
|
||||
- continue;
|
||||
+ // Keep one segment in memory and commit it through the same ordered
|
||||
+ // writer and chunk checker used by serial downloads.
|
||||
+ let batch = if parallel
|
||||
+ && let Some(size) = total
|
||||
+ && end - have >= (PARALLEL_REQUESTS - 1) as u64
|
||||
+ {
|
||||
+ match read_parallel_segment(agent, &d.url, have, end, size, r) {
|
||||
+ Ok(bytes) => Some(bytes),
|
||||
+ Err(_) => {
|
||||
+ progress::check(r)?;
|
||||
+ parallel = false;
|
||||
+ r.note("Parallel ranges could not be read. Continuing with one connection.");
|
||||
+ None
|
||||
+ }
|
||||
}
|
||||
+ } else {
|
||||
+ None
|
||||
};
|
||||
- let status = resp.status().as_u16();
|
||||
- match status {
|
||||
- 206 => {
|
||||
- let range = resp
|
||||
- .headers()
|
||||
- .get("content-range")
|
||||
- .and_then(|v| v.to_str().ok())
|
||||
- .and_then(content_range)
|
||||
- .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
|
||||
- if range.0 != have {
|
||||
- bail!(
|
||||
- "{} sent bytes from {} when asked for {have}",
|
||||
- d.url,
|
||||
- range.0
|
||||
- );
|
||||
+ let mut body: Box<dyn Read> = if let Some(bytes) = batch {
|
||||
+ Box::new(Cursor::new(bytes))
|
||||
+ } else {
|
||||
+ let mut req = agent
|
||||
+ .get(&d.url)
|
||||
+ .header("Range", format!("bytes={have}-{end}"));
|
||||
+ for (k, v) in &d.headers {
|
||||
+ req = req.header(k, v);
|
||||
+ }
|
||||
+ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
|
||||
+ if let Some(ua) = d.user_agent {
|
||||
+ cfg = cfg.user_agent(ua);
|
||||
+ }
|
||||
+ let resp = match cfg.build().call() {
|
||||
+ Ok(resp) => resp,
|
||||
+ Err(e) => {
|
||||
+ failures += 1;
|
||||
+ retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
|
||||
+ continue;
|
||||
+ }
|
||||
+ };
|
||||
+ let status = resp.status().as_u16();
|
||||
+ match status {
|
||||
+ 206 => {
|
||||
+ let range = resp
|
||||
+ .headers()
|
||||
+ .get("content-range")
|
||||
+ .and_then(|v| v.to_str().ok())
|
||||
+ .and_then(content_range)
|
||||
+ .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
|
||||
+ if range.0 != have {
|
||||
+ bail!(
|
||||
+ "{} sent bytes from {} when asked for {have}",
|
||||
+ d.url,
|
||||
+ range.0
|
||||
+ );
|
||||
+ }
|
||||
+ match (total, range.1) {
|
||||
+ (Some(t), Some(rt)) if t != rt => bail!(
|
||||
+ "{} is {} long, not the expected {}: it changed on the server",
|
||||
+ d.url,
|
||||
+ rt,
|
||||
+ t
|
||||
+ ),
|
||||
+ (None, Some(rt)) => {
|
||||
+ total = Some(rt);
|
||||
+ r.progress(have, total);
|
||||
+ }
|
||||
+ _ => {}
|
||||
+ }
|
||||
}
|
||||
- match (total, range.1) {
|
||||
- (Some(t), Some(rt)) if t != rt => bail!(
|
||||
- "{} is {} long, not the expected {}: it changed on the server",
|
||||
- d.url,
|
||||
- rt,
|
||||
- t
|
||||
- ),
|
||||
- (None, Some(rt)) => {
|
||||
- total = Some(rt);
|
||||
- r.progress(have, total);
|
||||
+ 200 => {
|
||||
+ // The whole file: the server ignored the range.
|
||||
+ if have > 0 {
|
||||
+ cut(file, 0)?;
|
||||
+ have = 0;
|
||||
+ check.restart_at(0);
|
||||
+ }
|
||||
+ if total.is_none() {
|
||||
+ total = resp.body().content_length();
|
||||
}
|
||||
- _ => {}
|
||||
}
|
||||
- }
|
||||
- 200 => {
|
||||
- // The whole file: the server ignored the range.
|
||||
- if have > 0 {
|
||||
+ 416 if total.is_some_and(|t| have >= t) => break,
|
||||
+ 416 => {
|
||||
+ // Past the end: the file on the server is shorter than what we have.
|
||||
+ if have == 0 {
|
||||
+ bail!("{} refused every range", d.url);
|
||||
+ }
|
||||
+ r.note("The file changed on the server: starting over");
|
||||
cut(file, 0)?;
|
||||
have = 0;
|
||||
check.restart_at(0);
|
||||
+ continue;
|
||||
}
|
||||
- if total.is_none() {
|
||||
- total = resp.body().content_length();
|
||||
- }
|
||||
- }
|
||||
- 416 if total.is_some_and(|t| have >= t) => break,
|
||||
- 416 => {
|
||||
- // Past the end: the file on the server is shorter than what we have.
|
||||
- if have == 0 {
|
||||
- bail!("{} refused every range", d.url);
|
||||
+ 401 | 403 if d.refresh.is_some() && failures < 3 => {
|
||||
+ failures += 1;
|
||||
+ if let Some(f) = d.refresh.as_mut() {
|
||||
+ d.headers = f()?;
|
||||
+ }
|
||||
+ continue;
|
||||
}
|
||||
- r.note("The file changed on the server: starting over");
|
||||
- cut(file, 0)?;
|
||||
- have = 0;
|
||||
- check.restart_at(0);
|
||||
- continue;
|
||||
- }
|
||||
- 401 | 403 if d.refresh.is_some() && failures < 3 => {
|
||||
- failures += 1;
|
||||
- if let Some(f) = d.refresh.as_mut() {
|
||||
- d.headers = f()?;
|
||||
+ 408 | 429 | 500..=599 => {
|
||||
+ failures += 1;
|
||||
+ retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
|
||||
+ continue;
|
||||
}
|
||||
- continue;
|
||||
- }
|
||||
- 408 | 429 | 500..=599 => {
|
||||
- failures += 1;
|
||||
- retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
|
||||
- continue;
|
||||
+ _ => bail!("{} answered HTTP {status}", d.url),
|
||||
}
|
||||
- _ => bail!("{} answered HTTP {status}", d.url),
|
||||
- }
|
||||
+ Box::new(resp.into_body().into_reader())
|
||||
+ };
|
||||
|
||||
file.seek(SeekFrom::Start(base + have))?;
|
||||
- let mut body = resp.into_body().into_reader();
|
||||
let start = have;
|
||||
loop {
|
||||
if r.cancelled() {
|
||||
@@ -389,6 +418,79 @@ pub fn download(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+fn read_parallel_segment(
|
||||
+ agent: &Agent,
|
||||
+ url: &str,
|
||||
+ start: u64,
|
||||
+ end: u64,
|
||||
+ total: u64,
|
||||
+ r: &dyn Reporter,
|
||||
+) -> Result<Vec<u8>> {
|
||||
+ let mut segment = vec![0; (end - start + 1) as usize];
|
||||
+ let request_size = segment.len().div_ceil(PARALLEL_REQUESTS);
|
||||
+ thread::scope(|scope| -> Result<()> {
|
||||
+ let mut requests = Vec::with_capacity(PARALLEL_REQUESTS);
|
||||
+ for (index, chunk) in segment.chunks_mut(request_size).enumerate() {
|
||||
+ let first = start + (index * request_size) as u64;
|
||||
+ let request = thread::Builder::new().spawn_scoped(scope, move || {
|
||||
+ read_exact_range(agent, url, first, total, chunk, r)
|
||||
+ })?;
|
||||
+ requests.push(request);
|
||||
+ }
|
||||
+ for request in requests {
|
||||
+ request
|
||||
+ .join()
|
||||
+ .map_err(|_| anyhow::anyhow!("range worker failed"))??;
|
||||
+ }
|
||||
+ Ok(())
|
||||
+ })?;
|
||||
+ Ok(segment)
|
||||
+}
|
||||
+
|
||||
+fn read_exact_range(
|
||||
+ agent: &Agent,
|
||||
+ url: &str,
|
||||
+ start: u64,
|
||||
+ total: u64,
|
||||
+ mut remaining: &mut [u8],
|
||||
+ r: &dyn Reporter,
|
||||
+) -> Result<()> {
|
||||
+ let end = start + remaining.len() as u64 - 1;
|
||||
+ progress::check(r)?;
|
||||
+ let response = agent
|
||||
+ .get(url)
|
||||
+ .header("Range", format!("bytes={start}-{end}"))
|
||||
+ .header("Accept-Encoding", "identity")
|
||||
+ .config()
|
||||
+ .timeout_recv_body(Some(SEGMENT_BUDGET))
|
||||
+ .build()
|
||||
+ .call()?;
|
||||
+ let expected = format!("bytes {start}-{end}/{total}");
|
||||
+ if response.status().as_u16() != 206
|
||||
+ || response
|
||||
+ .headers()
|
||||
+ .get("Content-Range")
|
||||
+ .and_then(|value| value.to_str().ok())
|
||||
+ != Some(expected.as_str())
|
||||
+ {
|
||||
+ bail!("server did not return the requested byte range");
|
||||
+ }
|
||||
+ let mut body = response.into_body().into_reader();
|
||||
+ while !remaining.is_empty() {
|
||||
+ progress::check(r)?;
|
||||
+ let n = body.read(remaining)?;
|
||||
+ if n == 0 {
|
||||
+ bail!("range body ended before its declared length");
|
||||
+ }
|
||||
+ remaining = &mut remaining[n..];
|
||||
+ }
|
||||
+ progress::check(r)?;
|
||||
+ if body.read(&mut [0u8; 1])? != 0 {
|
||||
+ bail!("range body exceeded its declared length");
|
||||
+ }
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
fn retry_or_fail(
|
||||
failures: &mut u32,
|
||||
tries: u32,
|
||||
@@ -455,6 +557,173 @@ pub fn hex(b: &[u8]) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
+ use std::io::{BufRead, BufReader};
|
||||
+ use std::net::{TcpListener, TcpStream};
|
||||
+
|
||||
+ struct Silent;
|
||||
+
|
||||
+ impl Reporter for Silent {
|
||||
+ fn event(&self, _: progress::Event) {}
|
||||
+ }
|
||||
+
|
||||
+ fn read_request(stream: &TcpStream) -> Result<String> {
|
||||
+ stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
+ let mut reader = BufReader::new(stream);
|
||||
+ let mut range = String::new();
|
||||
+ loop {
|
||||
+ let mut line = String::new();
|
||||
+ if reader.read_line(&mut line)? == 0 || line == "\r\n" {
|
||||
+ break;
|
||||
+ }
|
||||
+ if let Some((name, value)) = line.split_once(':')
|
||||
+ && name.eq_ignore_ascii_case("range")
|
||||
+ {
|
||||
+ range = value.trim().to_string();
|
||||
+ }
|
||||
+ }
|
||||
+ Ok(range)
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn sends_four_ranges_before_waiting_for_their_bodies() -> Result<()> {
|
||||
+ let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
+ listener.set_nonblocking(true)?;
|
||||
+ let url = format!("http://{}", listener.local_addr()?);
|
||||
+ let server = thread::spawn(move || -> Result<()> {
|
||||
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
+ let mut requests = std::collections::BTreeMap::new();
|
||||
+ while requests.len() < 4 {
|
||||
+ match listener.accept() {
|
||||
+ Ok((stream, _)) => {
|
||||
+ let range = read_request(&stream)?;
|
||||
+ requests.insert(range, stream);
|
||||
+ }
|
||||
+ Err(e)
|
||||
+ if e.kind() == std::io::ErrorKind::WouldBlock
|
||||
+ && std::time::Instant::now() < deadline =>
|
||||
+ {
|
||||
+ thread::sleep(Duration::from_millis(5));
|
||||
+ }
|
||||
+ Err(e) => {
|
||||
+ return Err(e).context("waiting for four simultaneous range requests");
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ // No worker gets a response until all four requests have arrived.
|
||||
+ let data = b"abcdefghijklmnop";
|
||||
+ for offset in (0..data.len()).step_by(4).rev() {
|
||||
+ let mut stream = requests
|
||||
+ .remove(&format!("bytes={offset}-{}", offset + 3))
|
||||
+ .context("missing requested range")?;
|
||||
+ write!(
|
||||
+ stream,
|
||||
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes {offset}-{}/16\r\nConnection: close\r\n\r\n",
|
||||
+ offset + 3
|
||||
+ )?;
|
||||
+ stream.write_all(&data[offset..offset + 4])?;
|
||||
+ }
|
||||
+ Ok(())
|
||||
+ });
|
||||
+ let data = read_parallel_segment(&test_agent(), &url, 0, 15, 16, &Silent);
|
||||
+ server
|
||||
+ .join()
|
||||
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
|
||||
+ assert_eq!(data?, b"abcdefghijklmnop");
|
||||
+ Ok(())
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn rejects_ignored_misaligned_and_truncated_ranges() -> Result<()> {
|
||||
+ let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
+ let url = format!("http://{}", listener.local_addr()?);
|
||||
+ let server = thread::spawn(move || -> Result<()> {
|
||||
+ for reply in [
|
||||
+ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nabcd",
|
||||
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes 5-8/16\r\nConnection: close\r\n\r\nabcd",
|
||||
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 4-7/16\r\nConnection: close\r\n\r\nabc",
|
||||
+ ] {
|
||||
+ let (mut stream, _) = listener.accept()?;
|
||||
+ read_request(&stream)?;
|
||||
+ stream.write_all(reply.as_bytes())?;
|
||||
+ }
|
||||
+ Ok(())
|
||||
+ });
|
||||
+ let agent = test_agent();
|
||||
+ for _ in 0..3 {
|
||||
+ assert!(read_exact_range(&agent, &url, 4, 16, &mut [0; 4], &Silent).is_err());
|
||||
+ }
|
||||
+ server
|
||||
+ .join()
|
||||
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
|
||||
+ Ok(())
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn falls_back_to_a_single_request_from_the_verified_prefix() -> Result<()> {
|
||||
+ use crate::chunklist::{ChunkCheck, Chunklist, Signature};
|
||||
+ use sha2::{Digest, Sha256};
|
||||
+
|
||||
+ let data = b"abcdefghijklmnop";
|
||||
+ let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
+ let url = format!("http://{}", listener.local_addr()?);
|
||||
+ let server = thread::spawn(move || -> Result<()> {
|
||||
+ for _ in 0..PARALLEL_REQUESTS {
|
||||
+ let (mut stream, _) = listener.accept()?;
|
||||
+ read_request(&stream)?;
|
||||
+ stream.write_all(
|
||||
+ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
+ )?;
|
||||
+ }
|
||||
+ let (mut stream, _) = listener.accept()?;
|
||||
+ assert_eq!(read_request(&stream)?, "bytes=4-15");
|
||||
+ stream.write_all(
|
||||
+ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 12\r\nContent-Range: bytes 4-15/16\r\nConnection: close\r\n\r\n",
|
||||
+ )?;
|
||||
+ stream.write_all(&data[4..])?;
|
||||
+ Ok(())
|
||||
+ });
|
||||
+ let dir = std::env::temp_dir().join(format!("reims-util-fallback-{}", std::process::id()));
|
||||
+ std::fs::create_dir_all(&dir)?;
|
||||
+ let path = dir.join("download");
|
||||
+ std::fs::write(part_path(&path), &data[..4])?;
|
||||
+ let chunks = data
|
||||
+ .chunks_exact(4)
|
||||
+ .map(|chunk| (4, Sha256::digest(chunk).into()))
|
||||
+ .collect();
|
||||
+ let mut check = ChunkCheck::new(Chunklist {
|
||||
+ chunks,
|
||||
+ signature: Signature::Digest,
|
||||
+ });
|
||||
+ let mut request = Download::new(&url, "Test download".into());
|
||||
+ request.size = Some(data.len() as u64);
|
||||
+ request.parallel = true;
|
||||
+ let result = download(
|
||||
+ &test_agent(),
|
||||
+ request,
|
||||
+ Dest::File(&path),
|
||||
+ &mut check,
|
||||
+ &Silent,
|
||||
+ );
|
||||
+ let actual = std::fs::read(&path);
|
||||
+ let _ = std::fs::remove_file(&path);
|
||||
+ let _ = std::fs::remove_file(part_path(&path));
|
||||
+ let _ = std::fs::remove_dir(&dir);
|
||||
+ result?;
|
||||
+ server
|
||||
+ .join()
|
||||
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
|
||||
+ assert_eq!(actual?, data);
|
||||
+ Ok(())
|
||||
+ }
|
||||
+
|
||||
+ fn test_agent() -> Agent {
|
||||
+ Agent::config_builder()
|
||||
+ .proxy(None)
|
||||
+ .http_status_as_error(false)
|
||||
+ .timeout_global(Some(Duration::from_secs(5)))
|
||||
+ .build()
|
||||
+ .into()
|
||||
+ }
|
||||
|
||||
#[test]
|
||||
fn parses_content_range() {
|
||||
diff --git a/src/installer.rs b/src/installer.rs
|
||||
index 7c17423300c153fd24fe9e031de3a835dcda57e1..265031a5d2ff54e0b8c9b752bad579c5927c5ef1 100644
|
||||
--- a/src/installer.rs
|
||||
+++ b/src/installer.rs
|
||||
@@ -475,6 +475,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu
|
||||
progress::check(r)?;
|
||||
let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label()));
|
||||
d.size = Some(inst.size);
|
||||
+ d.parallel = true;
|
||||
let pkg = Dest::Region {
|
||||
file: &mut f,
|
||||
offset: pkg_at,
|
||||
@@ -746,6 +747,7 @@ mod tests {
|
||||
/// macOS 12's and 26's do, through `<target>Applications`), and where it fails after placing
|
||||
/// the app (as Big Sur's does, needing zsh), the app gets the package as SharedSupport.dmg
|
||||
/// and the script starts its startosinstall on the volume.
|
||||
+ #[cfg(unix)]
|
||||
#[test]
|
||||
fn install_script_runs_without_dirname_or_zsh() {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
diff --git a/src/recovery.rs b/src/recovery.rs
|
||||
index fe4eadc745ac4867802254a53197821acac3d411..11406e790884549b7e4e6b297f29c3a0285c606f 100644
|
||||
--- a/src/recovery.rs
|
||||
+++ b/src/recovery.rs
|
||||
@@ -311,6 +311,7 @@ impl Image {
|
||||
size: Some(self.size()),
|
||||
refresh: Some(&mut refresh),
|
||||
user_agent: Some(USER_AGENT),
|
||||
+ parallel: false,
|
||||
tries: http::MAX_FAILURES,
|
||||
};
|
||||
http::download(&self.agent, d, dest, check, r)
|
||||
@@ -1,8 +1,6 @@
|
||||
# Patch queue, in the order the patches are applied (see patches/README.md).
|
||||
# One patch per line: <target> <file>.
|
||||
# The runtime forks contain the Reims vGPU and QEMU changes.
|
||||
# This queue applies additional patches to their pinned dependencies.
|
||||
# Runtime components are built from the pinned Reims-Go organization forks.
|
||||
# The queue is reserved for temporary patches to those pinned checkouts.
|
||||
# CI (runtime-preview.yml via scripts/apply-patch-series.ps1) and
|
||||
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
|
||||
reims-util reims-util-parallel-offline-download.patch
|
||||
metal2vulkan metal2vulkan-snapshot-replay.patch
|
||||
@@ -33,9 +33,10 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
|
||||
$localDb = Join-Path $Msys2 'var\lib\pacman\local'
|
||||
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
|
||||
$zstd = Join-Path $Msys2 'usr\bin\zstd.exe'
|
||||
$zstd = Resolve-Zstd -Msys2 $Msys2
|
||||
|
||||
function Write-Utf8([string]$path, [string]$text) {
|
||||
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
|
||||
|
||||
@@ -59,6 +59,7 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$patchesDir = Join-Path $repoRoot 'patches'
|
||||
$CargoBin = Join-Path $CargoHome 'bin'
|
||||
@@ -97,17 +98,7 @@ function Write-Utf8([string]$path, [string]$text) {
|
||||
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
|
||||
function Resolve-Zstd {
|
||||
@(
|
||||
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
|
||||
(Join-Path $Msys2 'usr\bin\zstd.exe'),
|
||||
(Join-Path $Msys2 'clang64\bin\zstd.exe')
|
||||
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
|
||||
}
|
||||
|
||||
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
|
||||
$zstd = Resolve-Zstd
|
||||
if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' }
|
||||
$tar = Join-Path $TempRoot "$name.tar"
|
||||
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
|
||||
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
|
||||
@@ -147,10 +138,9 @@ if (Test-Path -LiteralPath $runtimeFeatures) {
|
||||
$capabilities = @((Get-Content -Raw -LiteralPath $runtimeFeatures | ConvertFrom-Json).capabilities)
|
||||
}
|
||||
|
||||
# reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV).
|
||||
$utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs')
|
||||
if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' }
|
||||
$utilCommit = $Matches[1]
|
||||
$pins = & (Join-Path $PSScriptRoot 'read-runtime-dependencies.ps1') -RuntimeRepo $ReimsRepo
|
||||
$utilCommit = $pins.Util.Rev
|
||||
$m2vCommit = $pins.Metal.Rev
|
||||
$checkouts = Join-Path $CargoHome 'git\checkouts'
|
||||
$utilTree = if ($UtilRepo) {
|
||||
(Resolve-Path -LiteralPath $UtilRepo).Path
|
||||
@@ -163,15 +153,6 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" }
|
||||
$actualUtil = git -C $utilTree rev-parse HEAD
|
||||
if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" }
|
||||
|
||||
# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock).
|
||||
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml')
|
||||
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
|
||||
$m2vCommit = $Matches[1]
|
||||
} else {
|
||||
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
|
||||
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
|
||||
$m2vCommit = $Matches[1]
|
||||
}
|
||||
$m2vTree = if ($Metal2VulkanRepo) {
|
||||
(Resolve-Path -LiteralPath $Metal2VulkanRepo).Path
|
||||
} else {
|
||||
@@ -462,7 +443,9 @@ foreach ($extra in @(
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
|
||||
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
|
||||
foreach ($ps in $patchSpecs) {
|
||||
Copy-Item -LiteralPath (Join-Path "$bundleDir\patches" $ps.Name) -Destination "$srcDir\patches\"
|
||||
}
|
||||
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
|
||||
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
|
||||
$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) {
|
||||
@@ -475,7 +458,7 @@ and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``:
|
||||
|
||||
$m2vApply
|
||||
cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" <<EOF
|
||||
[patch."https://github.com/steelbrain/metal2vulkan"]
|
||||
[patch."$($pins.Metal.Url)"]
|
||||
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
|
||||
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
|
||||
EOF
|
||||
@@ -498,6 +481,14 @@ $utilApply
|
||||
|
||||
"@
|
||||
}
|
||||
$applyRuntimePatches = @(
|
||||
foreach ($ps in $patchSpecs) {
|
||||
switch ($ps.Target) {
|
||||
'reims-vgpu' { " git -C reims-vgpu-$commit apply ../patches/$($ps.Name)" }
|
||||
'vendor/qemu' { " git -C reims-vgpu-$commit/vendor/qemu apply ../../../patches/$($ps.Name)" }
|
||||
}
|
||||
}
|
||||
)
|
||||
Write-Utf8 "$srcDir\README.md" @"
|
||||
# Source for $bundleName
|
||||
|
||||
@@ -507,21 +498,18 @@ Corresponding source for the binaries in ``$bundleName.tar.zst``.
|
||||
| :-- | :-- | :-- |
|
||||
| ``reims-vgpu-$commit/`` | $reimsSource | ``$fullCommit`` |
|
||||
| ``reims-vgpu-$commit/vendor/qemu/`` | $qemuSource | ``$qemuCommit`` |
|
||||
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` |
|
||||
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` |
|
||||
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | $($pins.Util.Url) | ``$utilCommit`` |
|
||||
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | $($pins.Metal.Url) | ``$m2vCommit`` |
|
||||
|
||||
The archive exports the commits above. Apply the patches in ``patches/``
|
||||
before compiling:
|
||||
$(
|
||||
if ($applyRuntimePatches) {
|
||||
"Apply the runtime patches from the archive root.`n`n" + ($applyRuntimePatches -join "`n")
|
||||
}
|
||||
)
|
||||
|
||||
cd reims-vgpu-$commit
|
||||
$((($patchSpecs | Where-Object { $_.Target -eq 'reims-vgpu' } | ForEach-Object { " git apply ../patches/$($_.Name)" }) -join "`n"))
|
||||
cd vendor/qemu
|
||||
$((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object { " git apply ../../../patches/$($_.Name)" }) -join "`n"))
|
||||
|
||||
(``patch -p1`` works too.)
|
||||
$m2vBuildSteps
|
||||
Then build as upstream documents (``scripts/install-ctl.sh``
|
||||
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
|
||||
From ``reims-vgpu-$commit/``, run ``scripts/install-ctl.sh``
|
||||
in an MSYS2 CLANG64 shell. The DLLs in ``qemu/bin`` come from the MSYS2
|
||||
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
|
||||
$utilBuildSteps
|
||||
"@
|
||||
@@ -541,7 +529,9 @@ $manifest = [ordered]@{
|
||||
full_commit = $fullCommit
|
||||
vendor_qemu_repo = $qemuSource
|
||||
vendor_qemu_commit = $qemuCommit
|
||||
util_repo = $pins.Util.Url
|
||||
util_commit = $utilCommit
|
||||
metal2vulkan_repo = $pins.Metal.Url
|
||||
metal2vulkan_commit = $m2vCommit
|
||||
patches = $patchEntries
|
||||
capabilities = $capabilities
|
||||
@@ -563,6 +553,7 @@ $manifest.raw_bytes += (Get-Item -LiteralPath "$bundleDir\manifest.json").Length
|
||||
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
|
||||
|
||||
# ── 6. Archives and sums ─────────────────────────────────────
|
||||
$zstd = Resolve-Zstd -Msys2 $Msys2
|
||||
Write-Host '==> Compressing runtime'
|
||||
$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst"
|
||||
New-TarZst $stageRoot $bundleName $runtimeArchive
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
param([Parameter(Mandatory)][string]$RuntimeRepo)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$githubUrl = 'https://github\.com/[\w.-]+/[\w.-]+'
|
||||
$util = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'crates/reims-ctl/src/reims_util.rs')
|
||||
$utilUrl = [regex]::Match($util, "pub const REPO: &str = ""($githubUrl)"";").Groups[1].Value
|
||||
$utilRev = [regex]::Match($util, 'pub const REV: &str = "([0-9a-f]{40})";').Groups[1].Value
|
||||
if (-not $utilUrl -or -not $utilRev) { throw 'reims-util REPO or REV is missing from reims_util.rs' }
|
||||
|
||||
$cargo = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.toml')
|
||||
$metal = foreach ($name in 'metal2vulkan', 'metal2vulkan-runtime') {
|
||||
$entry = [regex]::Match($cargo, "(?m)^$name\s*=\s*\{([^}]+)\}").Groups[1].Value
|
||||
$url = [regex]::Match($entry, "git\s*=\s*""($githubUrl)""").Groups[1].Value
|
||||
if (-not $url) { throw "$name git URL is missing from Cargo.toml" }
|
||||
$rev = [regex]::Match($entry, 'rev\s*=\s*"([0-9a-f]{40})"').Groups[1].Value
|
||||
if (-not $rev) {
|
||||
$lock = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.lock')
|
||||
$pin = '(?m)^source = "git\+' + [regex]::Escape($url) + '\?rev=([0-9a-f]{40})#[0-9a-f]{40}"'
|
||||
$rev = [regex]::Match($lock, $pin).Groups[1].Value
|
||||
}
|
||||
if (-not $rev) { throw "$name revision is missing from Cargo.toml and Cargo.lock" }
|
||||
[pscustomobject]@{ Url = $url; Rev = $rev }
|
||||
}
|
||||
if ($metal[0].Url -cne $metal[1].Url -or $metal[0].Rev -cne $metal[1].Rev) {
|
||||
throw 'metal2vulkan and metal2vulkan-runtime must use the same repository and commit'
|
||||
}
|
||||
|
||||
[pscustomobject]@{
|
||||
Util = [pscustomobject]@{ Url = $utilUrl; Rev = $utilRev }
|
||||
Metal = $metal[0]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
function Resolve-Zstd([string]$Msys2) {
|
||||
$candidates = @(
|
||||
Get-Command zstd.exe -CommandType Application -All -ErrorAction SilentlyContinue |
|
||||
Select-Object -ExpandProperty Source
|
||||
Join-Path $Msys2 'usr\bin\zstd.exe'
|
||||
Join-Path $Msys2 'clang64\bin\zstd.exe'
|
||||
)
|
||||
$failures = @()
|
||||
|
||||
foreach ($candidate in ($candidates | Select-Object -Unique)) {
|
||||
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { continue }
|
||||
|
||||
# A binary can exist but fail to load its DLLs outside the MSYS2 shell.
|
||||
try {
|
||||
& $candidate --version *> $null
|
||||
if ($LASTEXITCODE -eq 0) { return $candidate }
|
||||
$failures += "$candidate (exit $LASTEXITCODE)"
|
||||
} catch {
|
||||
$failures += "$candidate ($($_.Exception.Message))"
|
||||
}
|
||||
}
|
||||
|
||||
if ($failures.Count) { throw "Could not run zstd.exe: $($failures -join '; ')" }
|
||||
throw "zstd.exe not found on PATH or in MSYS2 at $Msys2"
|
||||
}
|
||||
Reference in new issue
Block a user