diff --git a/.config/nextest.toml b/.config/nextest.toml index 0f706905b..068d7e684 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -13,62 +13,6 @@ slow-timeout = { period = "60s", terminate-after = 20 } filter = 'test(/::soak_/)' slow-timeout = { period = "300s", terminate-after = 24 } -# The runtime's isolation tests of command queues sharing `VkQueue`s run alone. Each holds a -# compositor's 99th percentile of commit-to-completion latency under 5 ms, and its stalls over -# 10 ms to at most one, beside an application's 30 ms command buffers (and beside a queue waiting -# on the GPU for them): a bound of the GPU's time, which other test processes' work on the same GPU -# spends too. So does the held-head test, whose hold needs the long command buffer (about 30 ms of -# GPU time as it measures it first) to have more than the hold's budget left when the next commits -# come: other processes' work changes that time between its measure and its run. On the RTX 2080 -# the gpu-wait and held-head tests failed only beside the parallel suite, and pass alone. So does -# the turns test, which holds each of a burst's command buffers to a submission at most 20 ms after -# the GPU end of the one before it: on lavapipe (Mesa 26.2.4) on msi-laptop, beside two other build -# and test jobs, the burst's eighth missed it (m3-max-51548), and the same tests on an idle node -# passed 3 runs of 3 (m3-max-51697). -[[profile.default.overrides]] -filter = 'package(metal2vulkan-runtime) & test(/^tests::queue_share_device::(a_compositor_beside_a_long_queue_keeps_its_latency_once_that_queue_went_long|an_unshared_compositor_beside_a_long_queue_never_stalls|a_compositor_beside_a_queue_waiting_on_the_gpu_for_long_work_keeps_its_latency|an_unshared_head_behind_an_earlier_commit_of_the_held_queue_holds_nothing|a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst)$/)' -threads-required = 'num-test-threads' - -# The runtime's GPU-start test of a command buffer's own long work runs alone. It holds the time -# from the command buffer's kernel end to its GPU start under half its life, a bound the GPU's -# queue sets: other test processes' work on the same GPU runs first. In an RTX 5080 Laptop GPU's -# whole runtime suite the start came 14.5 ms after the kernel end, of a 25.8 ms life, where the -# 64 dispatches' GPU span of 11.2 ms still held the work. -[[profile.default.overrides]] -filter = 'package(metal2vulkan-runtime) & test(/^tests::start_stamp::a_command_buffer_s_gpu_start_comes_before_its_own_long_work$/)' -threads-required = 'num-test-threads' - -# The runtime's teardown test of the queue-switch check runs alone. It holds the teardown's wait -# for the check (its stop at the next step, its release of its Vulkan objects and of its shares) -# under the 16 ms the owner allows a wait. On an RTX 5080 Laptop GPU (NVIDIA 615.71.09) that wait -# took 1.12 to 1.23 ms in 3 runs with the GPU to itself (the objects' release 0.79 to 0.93 ms, the -# shares' 2 us), and 26.5 and 42.4 ms in runs where other test processes used the GPU. -[[profile.default.overrides]] -filter = 'package(metal2vulkan-runtime) & test(/^tests::teardown_threads::a_running_queue_switch_check_leaves_the_device_to_the_program_s_thread$/)' -threads-required = 'num-test-threads' - -# The runtime's test of command buffers made `Scheduled` behind a waiting host step runs alone. It -# holds the long command buffer's commit call under the 16 ms the owner allows a wait in one of its -# runs at least, by the call's own clock. That call is recording on the program's thread alone (no -# pipeline wait, no wait for the scheduler's lock, no submission): on a Radeon 780M (RADV PHOENIX, -# Ryzen 7 7840HS) its later calls took 1.1 to 1.2 ms in the unoptimized test build with the GPU to -# itself, 0.10 to 0.26 ms in a release build. Beside the device suite's other processes (load -# average 14 on 16 threads) the same work took many times the CPU time and waited for a CPU too: -# 10.7 and 16.3 ms in the test build (8.2 and 10.4 ms of them on a CPU), and up to 38 ms in the -# rounds' runs; 5.8 and 7.0 ms in a release build (4.7 and 7.3 ms on a CPU). -[[profile.default.overrides]] -filter = 'package(metal2vulkan-runtime) & test(/^tests::held_step_order::command_buffers_behind_a_waiting_step_read_scheduled$/)' -threads-required = 'num-test-threads' - -# The runtime's video interop tests run alone on Linux. Each makes a device with extra compute and -# video decode queues; on an RTX 3090 (NVIDIA 620.70.06) several such devices made at once by -# processes of these tests now and then met an error the kernel logged (Xid 69, 32 or 13), -# their devices lost, and another process's submission never completed (HOWTO.md, section 8). -[[profile.default.overrides]] -platform = 'cfg(target_os = "linux")' -filter = 'package(metal2vulkan-runtime) & test(/^tests::video_interop::/)' -threads-required = 'num-test-threads' - # The new runtime's device test of accesses up to 2 GiB runs alone. Its buffer is one Shared block # of `MAX_BUFFER_LENGTH` (2 GiB), host memory where the Shared memory type is the host's (an RTX # 2080, NVIDIA 620.70.06). Beside the runtime's compute encoder tests and three other translate diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97c836019..a64554094 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,9 +87,7 @@ jobs: # may build it. `--all-features` compiles every gated item, but an import or item that only # another feature (or only a test) uses is unused, or missing, without it; `--workspace` # cannot check that either, since the validation member enables most features for every - # build. Feature gates combine with platform cfgs, so both hosts run it. The runtime crate - # (`metal2vulkan-runtime`) has no feature and reaches the translator only - # through its public API: it is checked the same way. + # build. Feature gates combine with platform cfgs, so both hosts run it. - name: Clippy under each feature alone (warnings denied) run: | set -euo pipefail @@ -98,9 +96,6 @@ jobs: cargo clippy -p metal2vulkan --all-targets --no-default-features --features "$features" -- -D warnings echo "::endgroup::" done - echo "::group::metal2vulkan-runtime" - cargo clippy -p metal2vulkan-runtime --all-targets -- -D warnings - echo "::endgroup::" # The AIR front end's crate as a consumer of `metal2vulkan-air` builds it # alone, with no feature and with `serde`, so nothing the translator or # validation enables in a workspace build hides an unused import or a missing item. @@ -131,7 +126,7 @@ jobs: rustup target add x86_64-pc-windows-gnullvm x86_64-pc-windows-msvc for target in x86_64-pc-windows-gnullvm x86_64-pc-windows-msvc; do echo "::group::$target" - cargo clippy --target "$target" -p metal2vulkan-air -p metal2vulkan -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-conformance --all-targets --all-features -- -D warnings + cargo clippy --target "$target" -p metal2vulkan-air -p metal2vulkan -p metal2vulkan-rt -p metal2vulkan-devtools -p metal2vulkan-conformance --all-targets --all-features -- -D warnings echo "::endgroup::" done @@ -180,7 +175,6 @@ jobs: metal2vulkan=0 \ metal2vulkan-air=0 \ metal2vulkan-rt=0 \ - metal2vulkan-runtime=0 \ metal2vulkan-validation=0 \ metal2vulkan-conformance=0 \ metal2vulkan-devtools=0 \ @@ -216,7 +210,7 @@ jobs: # With the AIR front end's crate's own tests, and the dev-tools crate's: # its tool runner and L3 checks. - name: Test metal2vulkan - run: cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features + run: cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-rt -p metal2vulkan-devtools -p metal2vulkan-harness --all-features # GPU-free on every host: tests that open a device compile only under `--cfg m2v_gpu` or # `--cfg m2v_cpu_icd`, and no device-opening code runs without one of them. diff --git a/Cargo.toml b/Cargo.toml index de73002a0..dfdcdb2a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ members = [ "crates/metal2vulkan-devtools", "crates/metal2vulkan-harness", "crates/metal2vulkan-rt", - "crates/metal2vulkan-runtime", "crates/metal2vulkan-validation", ] # A bare `cargo build`, `cargo test` or `cargo run` at the root acts on the translator alone, as it diff --git a/crates/metal2vulkan-devtools/src/tests.rs b/crates/metal2vulkan-devtools/src/tests.rs index eb015a4a6..03a53fa76 100644 --- a/crates/metal2vulkan-devtools/src/tests.rs +++ b/crates/metal2vulkan-devtools/src/tests.rs @@ -4,13 +4,11 @@ use std::path::{Path, PathBuf}; /// The trees, relative to the workspace, whose tests run from nextest archives carried to other /// machines (`cargo nextest run --archive-file ... --workspace-remap `): all of the -/// validation crate (its lib test binary holds the runtime lanes and the library code they call, -/// its integration tests and binaries ride a full archive), and the runtime's lib tests -/// (`src/tests/` and the test modules beside its sources). -const CARRIED: [&str; 3] = [ +/// validation crate (its lib test binary and the library code it calls; its integration tests and +/// binaries ride a full archive). +const CARRIED: [&str; 2] = [ "crates/metal2vulkan-validation/src", "crates/metal2vulkan-validation/tests", - "crates/metal2vulkan-runtime/src", ]; /// The `.rs` files at or below `path`. diff --git a/crates/metal2vulkan-runtime/Cargo.toml b/crates/metal2vulkan-runtime/Cargo.toml deleted file mode 100644 index 890a22ec6..000000000 --- a/crates/metal2vulkan-runtime/Cargo.toml +++ /dev/null @@ -1,201 +0,0 @@ -[package] -name = "metal2vulkan-runtime" -version = "0.2.0" -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -description = "The Metal API on Vulkan: Metal's objects and calls run on a Vulkan device through ash" -readme = "README.md" -repository.workspace = true -documentation = "https://docs.rs/metal2vulkan-runtime" -keywords = ["metal", "vulkan", "gpu", "graphics"] -categories = ["graphics", "api-bindings"] -# No crate root can appear unannounced, so validation's product fingerprint follows exactly the -# runtime's module tree (build_support.rs). Each example is listed below. -autobins = false -autoexamples = false -# The runtime's tests read the repository's profiles, fixtures and guide beside this directory. -exclude = ["/target/", "**/*.air", "**/*.metallib", "**/*.spv"] - -[lib] -name = "metal2vulkan_runtime" -path = "src/lib.rs" - -# Runnable examples for consumers (README.md, "Examples"): each runs the owned fixture -# validation/fixtures/public/examples/runtime_examples.metal on the system default device, from the -# workspace checkout (its committed LLVM text, assembled by `llvm-as`), or a metallib passed as the -# first argument. -[[example]] -name = "compute_dispatch" -path = "examples/compute_dispatch.rs" - -[[example]] -name = "render_to_texture" -path = "examples/render_to_texture.rs" - -[[example]] -name = "indirect_command_buffer" -path = "examples/indirect_command_buffer.rs" - -[[example]] -name = "heap_placement" -path = "examples/heap_placement.rs" - -[[example]] -name = "adopted_buffer" -path = "examples/adopted_buffer.rs" - -# Not a consumer's example: the host A/B benchmark, the same Metal workloads natively on Metal -# and through the runtime, with a table of the two (examples/host_ab/main.rs). -[[example]] -name = "host_ab" -path = "examples/host_ab/main.rs" - -# Not a consumer's example: a command buffer's fixed cost on the submit and completion path, from -# commit to its handler, and the CPU of the runtime's threads per command buffer -# (examples/submit_path.rs). -[[example]] -name = "submit_path" -path = "examples/submit_path.rs" - -# Not a consumer's example: a kernel submission's cost beside no-copy buffers over dma-bufs, each -# a dma-buf of its own against pieces of shared files (Linux, udmabuf). -[[example]] -name = "shared_files" -path = "examples/shared_files.rs" - -# Not a consumer's example: the CPU cost of an indirect command buffer's command setters, a -# render and a compute command encoded field by field (examples/icb_setters.rs). -[[example]] -name = "icb_setters" -path = "examples/icb_setters.rs" - -# Not a consumer's example: command queues sharing `VkQueue`s, each workload under the policy its -# arguments name (examples/queue_share.rs). -[[example]] -name = "queue_share" -path = "examples/queue_share.rs" - -# Not a consumer's example: what a draw costs the thread that encodes it, in three shapes of a -# guest's render work: a compositor's binds, many short command buffers, and long ones -# (examples/draw_costs.rs). -[[example]] -name = "draw_costs" -path = "examples/draw_costs.rs" - -# Not a consumer's example: the GPU's bandwidth through 256 MiB buffers of each storage mode, over -# the caller's pages and the runtime's own (examples/managed_bandwidth.rs). -[[example]] -name = "managed_bandwidth" -path = "examples/managed_bandwidth.rs" - -# Not a consumer's example: what `synchronize_resource` of `Managed` buffers over the caller's -# pages costs a command buffer, by how many of them the GPU wrote (examples/managed_sync_out.rs). -[[example]] -name = "managed_sync_out" -path = "examples/managed_sync_out.rs" - -# Not a consumer's example: which command buffer copies `Managed` buffers' CPU writes in when the -# first one to bind them only dispatches an empty kernel, and what the next one that reads them -# costs (examples/inert_uploads.rs). -[[example]] -name = "inert_uploads" -path = "examples/inert_uploads.rs" - -# Not a consumer's example: the GPU's bandwidth through 256 MiB buffers of the runtime's own memory, -# made after other buffers went (examples/private_bandwidth.rs). -[[example]] -name = "private_bandwidth" -path = "examples/private_bandwidth.rs" - -# Not a consumer's example: what copies between host and device memory cost on the graphics -# queue and on a copy engine, alone and beside a compute load, on a Vulkan device of its own -# (examples/copy_engine.rs). -[[example]] -name = "copy_engine" -path = "examples/copy_engine.rs" - -# Not a consumer's example: what a device's `VkQueue`s cost the driver to make, drop and hold, by -# how many it takes (examples/queue_plan_cost.rs). -[[example]] -name = "queue_plan_cost" -path = "examples/queue_plan_cost.rs" - -# Not a consumer's example: what a render pass instance costs the driver's CPU, by how it is -# recorded: a primary per pass or per submission, a framebuffer made per pass or kept, or dynamic -# rendering, on a Vulkan device of its own (examples/pass_costs.rs). -[[example]] -name = "pass_costs" -path = "examples/pass_costs.rs" - -# Not a consumer's example: what a chain of dependent compute dispatches costs the GPU, by how a -# command buffer holds them (an encoder each, one serial or concurrent encoder), beside the same -# chain recorded straight through Vulkan (examples/dispatch_chain.rs). -[[example]] -name = "dispatch_chain" -path = "examples/dispatch_chain.rs" - -# Not a consumer's example: what a frame of indexed draws costs the GPU where a compute dispatch -# before each draw writes the draw's indices, as a layer that fixes up each draw's index buffer -# does, beside the same frame with its indices written once (examples/fixed_index_draws.rs). -[[example]] -name = "fixed_index_draws" -path = "examples/fixed_index_draws.rs" - -# Not a consumer's example: what the GPU pays a draw for reading the draw's own data in the -# command buffer's upload arena, by what its fragment function reads (examples/draw_reads.rs). -[[example]] -name = "draw_reads" -path = "examples/draw_reads.rs" - -# Not a consumer's example: what an indirect command buffer's records cost the GPU and the host, -# written by a kernel or the CPU and executed by a render pass (examples/icb_reads.rs). -[[example]] -name = "icb_reads" -path = "examples/icb_reads.rs" - -[dependencies] -# The translator, through its public API only: the compiler checks that the runtime -# reaches nothing else. `ash` gives `ash_interop`'s conversions and `DeviceDescription::query`; -# `serde` the FALLBACK repro bundles' writer and their `device.json` (`repro.rs`). -metal2vulkan = { version = "0.2.0", path = "../metal2vulkan", features = ["ash", "serde"] } -# `ash/loaded` opens the Vulkan loader with `dlopen` when a device is created; nothing is linked at -# build time. -ash = { workspace = true, features = ["std", "loaded"] } -# The shader cache's entry names and the binary archive's keys. -sha2.workspace = true - -# The host's pages, clocks, threads and exit handlers on unix. -[target.'cfg(unix)'.dependencies] -libc.workspace = true - -# The same on Windows: pages (`VirtualQuery`, `VirtualAlloc`), the performance counter, thread -# times and the current process's memory reads. -[target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = [ - "Win32_Foundation", - "Win32_Security", - "Win32_System_Diagnostics_Debug", - "Win32_System_Memory", - "Win32_System_Performance", - "Win32_System_SystemInformation", - "Win32_System_Threading", -] } - -[dev-dependencies] -serde_json.workspace = true -# `llvm-as` for the device tests' owned fixture (`tests/pipeline_wait_order.rs`). -metal2vulkan-devtools = { path = "../metal2vulkan-devtools" } - -# The host A/B benchmark's native side (examples/host_ab): Metal itself, on macOS. -[target.'cfg(target_os = "macos")'.dev-dependencies] -block2 = "0.6" -objc2 = "0.6" -objc2-foundation = "0.3" -objc2-metal = "0.3" - -# The device tests compile only under the validation crate's GPU safety cfgs (`tests/mod.rs`). -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ["cfg(m2v_gpu)", "cfg(m2v_cpu_icd)", "cfg(m2v_gpu_hazards)", "cfg(m2v_no_recycle)"] } - diff --git a/crates/metal2vulkan-runtime/LICENSE b/crates/metal2vulkan-runtime/LICENSE deleted file mode 100644 index 901f4f84b..000000000 --- a/crates/metal2vulkan-runtime/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -metal2vulkan is dual-licensed. You can redistribute it and/or modify it -under the terms of either of these two licenses, at your choice: - - * the GNU General Public License as published by the Free Software - Foundation, either version 2 of the License, or (at your option) any - later version; or - - * the GNU Lesser General Public License as published by the Free - Software Foundation, either version 3 of the License, or (at your - option) any later version. - -The license texts are in these files: - - LICENSE-GPL-2.0 the GNU General Public License, version 2 - LICENSE-LGPL-3.0 the GNU Lesser General Public License, version 3 - LICENSE-GPL-3.0 the GNU General Public License, version 3, whose - terms the GNU Lesser General Public License, - version 3 incorporates - -metal2vulkan is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -or FITNESS FOR A PARTICULAR PURPOSE. See the license you choose for more -details. - -SPDX-License-Identifier: GPL-2.0-or-later OR LGPL-3.0-or-later diff --git a/crates/metal2vulkan-runtime/LICENSE-GPL-2.0 b/crates/metal2vulkan-runtime/LICENSE-GPL-2.0 deleted file mode 100644 index 9efa6fbc9..000000000 --- a/crates/metal2vulkan-runtime/LICENSE-GPL-2.0 +++ /dev/null @@ -1,338 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Moe Ghoul, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/crates/metal2vulkan-runtime/LICENSE-GPL-3.0 b/crates/metal2vulkan-runtime/LICENSE-GPL-3.0 deleted file mode 100644 index f288702d2..000000000 --- a/crates/metal2vulkan-runtime/LICENSE-GPL-3.0 +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/crates/metal2vulkan-runtime/LICENSE-LGPL-3.0 b/crates/metal2vulkan-runtime/LICENSE-LGPL-3.0 deleted file mode 100644 index 0a041280b..000000000 --- a/crates/metal2vulkan-runtime/LICENSE-LGPL-3.0 +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md deleted file mode 100644 index ae5863a8f..000000000 --- a/crates/metal2vulkan-runtime/README.md +++ /dev/null @@ -1,1406 +0,0 @@ -# metal2vulkan-runtime - -The Metal API on Vulkan. A program calls it the way it calls Apple's Metal (a device, command -queues, command buffers, the encoders, buffers, textures, heaps, pipeline states, events), and the -runtime runs the work on a Vulkan device through [`ash`](https://crates.io/crates/ash). It -translates each shader from Metal AIR to SPIR-V, owns the command buffers, submission and -barriers, and tracks hazards as Metal does. - -> **Unstable.** Names and shapes may change before the runtime's API is frozen. Where the runtime -> cannot give Metal's answer exactly it refuses with a typed error, or announces a recorded -> near-equivalent; it never silently runs something else. - -- Objects keep Metal's names without the `MTL` prefix (`Device`, `CommandQueue`, `Buffer`, ...). - Methods are Metal's selectors in snake case: `newBufferWithLength:options:` is - `Device::new_buffer`. Each item's rustdoc names its Metal counterpart and what differs or is - refused. -- Rust ownership stands for retain and release. Handles are cheap to clone, `Send + Sync`, and - equal when they are the same object; encoders are owned values that `end_encoding` consumes. -- Where Metal raises, ends the process, answers nil or fills an `NSError`, a call returns a typed - `Error` ([Errors](#errors)). - -## The crates - -| Crate | Directory | What it is | -|---|---|---| -| `metal2vulkan-runtime` | `crates/metal2vulkan-runtime` (this crate) | The Metal API on Vulkan, built only on the translator's public API | -| `metal2vulkan` | [`crates/metal2vulkan`](../metal2vulkan) | The translator: AIR to SPIR-V for a described Vulkan device, and its compile-and-plan API ([docs/API.md](../../docs/API.md)) | -| `metal2vulkan-air` | [`crates/metal2vulkan-air`](../metal2vulkan-air) | The AIR front end | - -The three are released together at one version. A program using the runtime depends on the -runtime and on `metal2vulkan`: the runtime's calls take the translator's descriptors and Metal's -value types, which it does not re-export (`metal2vulkan::pipeline::RenderPipelineDescriptor`, -`metal2vulkan::metal::PixelFormat`, ...). - -## Depending on it - -Not on crates.io yet. Depend on both crates from the same git revision (or checkout): - -```toml -[dependencies] -metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "" } -metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "" } -# Only for the Vulkan interop calls (raw handles, adopting a VkBuffer or VkImage): -ash = { version = "0.38", default-features = false, features = ["std"] } -``` - -- Rust 1.98 or newer. -- Nothing links against Vulkan at build time. The runtime opens the Vulkan loader when it makes a - device, or takes the consumer's `vkGetInstanceProcAddr` when it adopts one. A device needs - Vulkan 1.2 and `timelineSemaphore`. -- A program that makes a `VkInstance` of its own beside a runtime device calls - `program_instance_made()` right after it. A layer registers an exit handler as an instance is - made (the validation layer's forgets every device it knows), and exit handlers run in the reverse - order of their registration: unreported, that handler runs before the runtime's at exit, and a - call the runtime's threads still make into the layer ends the process. The instance of a device - the runtime adopts (`Device::from_raw`) needs no call. -- Shaders come in as a metallib (`Device::new_library_with_data`); there is no MSL compiler. Like - Metal, `new_library_with_data` refuses bare AIR bitcode. For AIR bitcode, parse it with - `metal2vulkan::library::Library::from_air` and pass the result to - `Device::new_library_with_compile_library`. A Core Image kernel library (`metallib -cikernel`) - loads as Metal loads it: an executable library whose kernels are extern functions - (`Library::extern_function_names`), which Core Image links into an ordinary kernel library of - its own through Metal; that library's kernel is what a pipeline state compiles. -- Every shader the runtime translates is kept on disk, by default in the platform's per-user cache - directory, and in memory ([HOWTO](../../docs/HOWTO.md#the-runtimes-shader-cache)). - `ShaderCacheOptions` names another directory; give each test its own. - -## Windows - -The three crates build for Windows: `x86_64-pc-windows-gnullvm` first, and -`x86_64-pc-windows-msvc`. CI runs clippy for both targets from Linux; the suites run on Linux and -macOS only. The runtime opens `vulkan-1.dll`. Where it asks the system something on Linux or -macOS, it asks Win32 on Windows: - -- Host pages a no-copy object names: `VirtualQuery` answers whether they are committed and - writable, and `GetSystemInfo` gives the page size. Pages the process cannot write are a copy - whose GPU writes are dropped (`copied-host-pages`), as on Linux. A view of a section - (`CreateFileMapping`, as a VMM's guest RAM is made) is imported by its pointer through - `VK_EXT_external_memory_host` where the driver takes it: `Device::imports_shared_host_pointers` - asks the driver with a section of the runtime's own. Where the driver refuses it, a no-copy - buffer or heap over such memory is a copy of the pages (`copied-host-pages`), a rebind to it is - refused (`Unsupported`, `HostMemory`), and a `HostRam` of it imports no chunk - ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)), as on Linux for shared memory with no - dma-buf source. -- The host clock is the performance counter (`QueryPerformanceCounter`); calibrated timestamps use - `VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR`. -- Thread CPU times come from `GetThreadTimes`, and the runtime's exit handler is registered with - the C runtime's `atexit`. -- The default shader cache directory is `%LOCALAPPDATA%\metal2vulkan`; where `LOCALAPPDATA` is - unset or not absolute, a device keeps its shader cache in memory alone and says so - ([HOWTO](../../docs/HOWTO.md#the-runtimes-shader-cache)). Its directories and files take the - access control list they inherit; the runtime sets no permissions of its own there. - -The items that take or hand out file descriptors do not exist on Windows (they are absent at -compile time), and nothing stands in for them with Win32 handles: - -- dma-buf sources: `HostMemory::with_dma_buf`, `HostRam::with_dma_buf`, - `HostRam::with_largest_dma_buf`, `HostRam::with_dma_buf_of_runs`, `DmaBufSource`, - `DmaBufRunsSource`, `DmaBufRequest`, `DmaBufChunk` and `DmaBufStandingRefusal`, and - `Device::import_shared_dma_buf` and `SharedDmaBufImport`; -- exported memory: `Device::new_exportable_buffer`, `Buffer::export_memory_fd`, - `Buffer::export_memory_dma_buf`, `Buffer::external_write_done` and `ExportedMemory`; -- exported semaphores and sync files: `Device::new_exportable_shared_event`, - `SharedEvent::export_semaphore_fd`, `CommandBuffer::add_completion_sync_file` and - `CommandBuffer::export_completion_sync_file`. - -## A first dispatch - -From [`examples/compute_dispatch.rs`](examples/compute_dispatch.rs): - -```rust,ignore -let device = Device::system_default()?; -let library = device.new_library_with_data(&metallib_bytes)?; -let function = library.new_function_with_name("scale_and_offset")?; -let state = - device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - -let input = device.new_buffer_with_bytes(&input_bytes, ResourceOptions::shared())?; -let output = device.new_buffer((COUNT * 4) as u64, ResourceOptions::shared())?; - -let queue = device.new_command_queue()?; -let command_buffer = queue.command_buffer()?; -let mut encoder = command_buffer.compute_command_encoder()?; -encoder.set_compute_pipeline_state(&state)?; -encoder.set_buffer(Some(&input), 0, 0)?; -encoder.set_buffer(Some(&output), 0, 1)?; -encoder.dispatch_threads(Size::new(COUNT as u64, 1, 1), Size::new(64, 1, 1))?; -encoder.end_encoding()?; -command_buffer.commit()?; -command_buffer.wait_until_completed()?; -// `output.contents()` now holds the kernel's results. -``` - -Creating a pipeline state translates its functions, each under the 20-second translation budget. -A function the device cannot run exactly is refused there, typed, naming what is missing. A stage -function made by `Library::new_function_with_name` whose function declares function constants is -refused before anything is translated (`Invalid`, `Problem::UnspecializedFunction`), as Metal ends -its process for it; make it with `new_function_with_name_constant_values` (no values are needed) -or `new_function_with_descriptor`, and a constant without a value is undefined (read as -[docs/API.md](../../docs/API.md)'s accepted differences, "Function constants", say). - -A `[[visible]]` function a stage calls but does not define comes from the functions it links: -`Function::linked_function` of each, in the stage's `LinkedFunctions` -(`function.function_descriptor().with_linked(linked)`, `MTLLinkedFunctions`). A call resolves to -the linked function of its name, `Function::name`: the specialized name -`Library::new_function_with_descriptor` made it with (`FunctionDescriptor::specialized_name`, -Metal's `specializedName`), else its own, whatever the definition's type: the arguments pass by -position ([docs/API.md](../../docs/API.md) section 3, "Linked functions: types"). A linked -function computes with the constant values it was made with, and a constant it was given no value -for reads as undefined, as Metal's does; one -made by `new_function_with_name` that reaches a constant of its module refuses the pipeline state -(`Compile`, `LinkProblem::UnresolvedConstant`), as Metal fails its creation. A function in the -stage's `binary_functions` is one a visible-function table calls: no call by name resolves to it -(`Compile`, `NeedsInput(LinkedFunction)`, as Metal's creation fails), and beside a function of its -name in `functions` the call calls that one while a table holds both, each with its handle. A -function there that was not made with `FunctionOptions::COMPILE_TO_BINARY` fails the creation as -plain Metal's does (`MetalError`, code 2), and one added to a made state -(`*_with_additional_binary_functions`) fails that call (`MetalError`, code 1). A function Metal's -stitcher made links the same way, privately or not, from the stitched library's bytes -(`Device::new_library_with_data`); the runtime makes no stitched library itself -(`newLibraryWithStitchedDescriptor:` is not built). - -Creating a render pipeline state also makes the `VkPipeline` its first draw is predicted to take, -before it returns, where Metal compiles. The prediction comes from the descriptor and the device -alone: the pass of its attachments, its input primitive class, each vertex-descriptor layout's -buffer bound at an aligned offset (a layout of `MTLBufferLayoutStrideDynamic` at the stride that -packs its attributes), Metal's default sampler at each runtime sampler slot, no texture, and -Metal's default encoder state. A pipeline's key holds no pass's resolves, which render pass -compatibility ignores, so a draw in a pass that resolves takes the predicted one. A point-class -state's prediction takes the variant its draws of points take under Metal's guard band, and a -multisampled state that blends into or reads an extended-range color (`BGRA10_XR` and its kin) the -variant that holds the color's `half` shadow, as its draws in a pass that clears the color do. A -draw whose key differs makes its own `VkPipeline` at that draw. Tessellated and mesh states, -separate depth and stencil formats and fragment functions that write depth make nothing at -creation. - -Where the device links its render pipelines from graphics pipeline libraries -(`VK_EXT_graphics_pipeline_library` with fast linking; MoltenVK makes them whole), -a linked `VkPipeline` is the device's, found by exactly what its linking takes: its four -libraries and its pipeline layout. Render states whose whole key is equal share it even where -each is a compiled pipeline of its own, whose stages come out as the same words (descriptors that -differ only in the call stack depth of a function that recurses through no visible function, for -one): the first links it, and each later one takes it with no driver call -(`WorkCounts::linked_pipelines_shared`). - -## Examples - -Each example runs on the system default device and uses only public API. Without an argument it -runs the repository's own fixture -[`runtime_examples.metal`](../metal2vulkan-validation/fixtures/public/examples/runtime_examples.metal), -assembled from its committed LLVM text by `llvm-as` (LLVM 21 or newer) on `PATH`. With an argument -it runs that metallib instead, for example one built with -`xcrun -sdk macosx metal -o runtime_examples.metallib runtime_examples.metal`. - -| Example | What it shows | -|---|---| -| [`compute_dispatch`](examples/compute_dispatch.rs) | A library from bytes, a compute pipeline state, buffers, one dispatch, the result read on the CPU | -| [`render_to_texture`](examples/render_to_texture.rs) | A render pipeline state, a render pass that clears and draws into a `Private` texture, and a blit that reads it back | -| [`indirect_command_buffer`](examples/indirect_command_buffer.rs) | Compute commands encoded on the CPU, read back as typed records, and executed after `use_resource` | -| [`heap_placement`](examples/heap_placement.rs) | A placement heap, textures at offsets `heap_texture_size_and_align` answers, and fences between the encoders that use them | -| [`adopted_buffer`](examples/adopted_buffer.rs) | A `Shared` buffer over a `VkBuffer` and `VkDeviceMemory` the caller made, the shape of a dma-buf import | - -```sh -cargo run -p metal2vulkan-runtime --example compute_dispatch -cargo run -p metal2vulkan-runtime --example render_to_texture -- runtime_examples.metallib -``` - -## Opening a device - -**Made by the runtime.** `Device::system_default()` is `MTLCreateSystemDefaultDevice()`: the first -physical device the runtime can open, in the order discrete, integrated, virtual, CPU. -`Device::all()` is `MTLCopyAllDevices()`. Their `_with` forms take `DeviceOptions`, the -Vulkan-side choices Metal has no counterpart for: - -| `DeviceOptions` field | What it chooses | -|---|---| -| `policy` | The translator's `DevicePolicy` ([docs/API.md](../../docs/API.md#the-policy)): containment, and the fast or exact form of each accuracy choice ([FAST-PATHS](../../docs/FAST-PATHS.md)). | -| `kinds` | Which `DeviceKind`s qualify; empty admits every kind. | -| `loader` | A Vulkan loader library to open instead of the default ones (the platform's loader by name, then on macOS `$VULKAN_SDK/lib`, `/opt/homebrew/lib` and `/usr/local/lib`). If none opens, `Error::LoaderNotFound` lists each path tried. | -| `layers`, `layer_settings` | Instance layers, in order, and their settings. | -| `instance_extensions`, `device_extensions` | Extensions beyond those the runtime enables (a swapchain, for example). | -| `optional_device_extensions` | Device extensions each device enables only where it can (it lists one, the instance has what it requires, and the device has its features), never refused for one; `Device::enables_extension` says which. A listed extension's feature structure is enabled with it where the runtime knows one (`VK_KHR_video_maintenance1` and `2`'s, `VK_KHR_unified_image_layouts`' with `unifiedImageLayoutsVideo` where the device has it), here and for `device_extensions`. | -| `extra_queues` | Queues each device makes for the consumer beside its own, one per `VkQueueFlags` entry (a video decode queue, for example), of the first family whose flags contain the entry's; `DeviceHandles::extra_queues` returns them. A device with no queue for an entry is made all the same, says so (`metal2vulkan-extra-queues-absent`), and leaves it out. The runtime never submits to them. Empty by default. | -| `reserved_queues` | How many queues of its own queue families each device reserves for the consumer out of the round robin its command queues share, which shrinks by each (on an RTX 5080, 13 `VkQueue`s rather than 14); `DeviceHandles::reserved_queues` returns them. The round robin keeps its first four and presenting its two, so a device with none to spare past those (MoltenVK's four families of one queue, lavapipe's one queue) reserves fewer, is made all the same, and says so (`metal2vulkan-reserved-queues-absent`). No command queue, presenting or not, and no internal copy ever submits to them. 0 by default. | -| `queue_limits` | Fewer `VkQueue`s for each device than its queue plan takes (`QueueLimits`: the most for the round robin its command queues share, at least one, and for presenting queues), so making and dropping a device costs less: on an RTX 5080, whose plan takes 18 queues, a device of 17 took 445 ms to make and 110 ms to drop, and one of 2 (one round-robin queue and the staging queue) 145 ms and 44 ms. Past the limits command queues share `VkQueue`s (one waits behind another's whole command buffer), and presenting and unshared ones may share. Where the limits change a placement from what the plan gives, the device says so in an informational message (`metal2vulkan-queue-limits-reached`), at the first such change alone, and counts each later one (`WorkCounts::queue_limits_reached_withheld`). A device with no queue to spare (RADV's, lavapipe's one graphics queue) takes its plan. `None` (the default) is the plan. For tests and tools that make many devices. | -| `instance_api_version` | The instance's `apiVersion` (1.2 when unset); a version outside 1.2 to the loader's is refused, never clamped. | -| `withheld_features`, `withheld_extensions`, `withhold_generated_commands`, `withhold_view_reinterpretation` | Parts of the recommended enables to leave off; the device then compiles for what is enabled. | -| `messages` | A `MessageSink` for the validation layer's messages and the runtime's notices; without one, notices go to stderr. `MessageSink::with_least_severity` skips messages below a severity (never a degrade notice), and the runtime then formats none of its own lines it would skip. | -| `shader_cache` | Where translated shaders are kept, and how much. | -| `gpu_times_from_host` | Answer command buffers' GPU times from the host clock, sparing two timestamps per command buffer. | -| `announce_each` | Degradation kinds to announce at every occurrence instead of once. | -| `lowering_refuses` | Degradation kinds that refuse a render encoder's call when its lowering after the call meets them (`RenderLoweringPolicy::Worker`), failing its command buffer, instead of being announced. Empty by default. | -| `record_executions` | Keep, per command buffer, which pipeline each dispatch and draw ran (`CommandBuffer::executions`). Off by default. | -| `load_no_dynamic_library_file` | Open no dynamic library's file, for libraries that come from a party that must not read the host's files (a guest's). Pipeline creations link only the libraries their function descriptors give (`libraries.preloaded`, and `libraries.loaded` by install name); an install name `loaded` lacks loads nothing, so a creation whose import survives specialization fails (`Compile(NeedsInput(DynamicLibrary))`), and `Device::new_dynamic_library_with_url` is refused (`DynamicLibraryError::NoFileLoading`). Off by default: as Metal does, a creation reads the file each install name names, a regular file alone (a FIFO, a device or a directory loads nothing). Also on `RawDevice`. | - -**A driver short of resources.** Where the driver refuses a device with its queue plan's `VkQueue`s -for want of its resources (`vkCreateDevice` answering `VK_ERROR_TOO_MANY_OBJECTS`, -`VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`: -on NVIDIA's driver, other devices of the GPU, in this process or others, holding what it needs, -such as its channels), the runtime asks once more with its least plan's: a round robin of one -`VkQueue` and none reserved for presenting, the extra, staging and fill queues kept, and as many -reserved queues as the plan reserves, no more (`queue_limits` of one and none, without that -option's messages). A device made so announces `metal2vulkan-degrade-least-queue-plan` once, as -it is made: its command queues share that one `VkQueue`. A device the driver refuses again, or -whose least plan takes no fewer queues, is refused, `Error::DeviceRefused`. On an RTX 2080 with a 256 MiB BAR (NVIDIA -620.70.06), sixteen processes started 3 s apart, each making one device: seven devices were made -with 17 `VkQueue`s and two more with 2 (one round-robin queue and the staging queue). The driver -refused the other seven with both plans, and the kernel logged that it could not allocate a -channel's instance block. In one process, the driver refused the eighth device with either plan, on -that RTX 2080 and on an RTX 3090. - -While a handle lives, equal options give the same device for a physical device, as Metal has one -`MTLDevice` per GPU. Nothing is read from the environment but the platform's default cache -directory. `Device::registry_ids_with` lists each qualifying physical device's `registryID`, -preferred first, without making any device, and `Device::with_registry_id` makes only the device -of one ID (runtime extensions). `Device::identities_with` reads the identity of each of those -physical devices, in the same order, with no device made, and `Device::system_default_identity_with` -the first of them, the one `Device::system_default_with` makes its device of: its name, kind, IDs, -`deviceUUID`, `registryID`, Vulkan version, the size of its largest `DEVICE_LOCAL` memory heap -(`recommended_max_working_set_size`, named after Metal's nearest property, whose estimate it is -not), and its PCI bus address and DRM render node where the physical device lists -`VK_EXT_pci_bus_info` and `VK_EXT_physical_device_drm`, which a consumer addresses the same GPU -through another API by. The same two are -`DeviceProperties::pci_bus` and `DeviceProperties::drm_render` on a device that exists; both are -`None` on macOS, where MoltenVK lists neither extension. - -**Adopted from the consumer.** `unsafe Device::from_raw(RawDevice, DevicePolicy)` works on an -instance and device the consumer made and keeps. `RawDevice` takes the `vkGetInstanceProcAddr`, -the instance and its version, the physical device, the device, the queue family and index, and -exactly what the device enabled (an `EnableSet`), plus what the runtime may use outside that -vocabulary (calibrated timestamps, sparse features, view format reinterpretation, host image copy) -and the same per-device choices as `DeviceOptions`. Dropping the runtime device destroys only what -the runtime made. The program's last drop of the device and its objects, on a thread of the -program's, returns once that is done: it stops the runtime's own background work on the device (its -check of textures over host pages, its warm pass) and waits for it, at most a round of the check or -the record the pass is making, and for the release a handler thread makes of a no-copy buffer's -pages that a keep-alive alone waits for (their free, then the keep-alive's drop), so a keep-alive's -drop must not wait for the thread that drops the device. - -**At the process's exit.** On NVIDIA's proprietary driver, drop the runtime's devices before the -process exits. A device kept to the exit can end it with `SIGSEGV` inside the driver's own exit -handler, which tears the driver's SPIR-V compiler down while a worker thread of the driver's still -runs in it, where the device's check of textures over host pages ended a few seconds or less before -the exit: on an RTX 3090 (620.70.06), 6 of 80 exits right after the check, 0 of 80 three seconds -after it, and 0 of 80 with the device dropped first -([HOWTO](../../docs/HOWTO.md#8-check-the-integration)). - -**The Vulkan objects underneath** (no Metal counterpart; each call is `unsafe`): - -- `Device::raw()` gives the entry, instance, physical device, `ash::Device`, queue families, and - the extra queues the options asked for (`ExtraQueue`: flags, family, `VkQueue`), which the - consumer alone submits to. The runtime's own buffers and images are shared among its own queue - families only, so work on an extra queue of another family uses the consumer's own objects. - The reserved queues (`ReservedQueue`: family, `VkQueue`) are of the runtime's own families, so - the consumer's work there uses the runtime's buffers and images with no ownership transfer - (while they live, ordered against the runtime's work through semaphores, a runtime image left - in `GENERAL`), and waits behind no command queue's command buffers. - `CommandQueue::with_vk_queue` lends a queue's `VkQueue`, with the `VkDevice` it belongs to and - its family, under the runtime's lock: the consumer's submissions there sit in that command - queue's order, and in that of any other command queue sharing the `VkQueue`. From its first call the command queue keeps that `VkQueue` for its life. -- `Texture::vk_image`, `Buffer::vk_buffer`, `Event::vk_semaphore` and `SharedEvent::vk_semaphore` - give an object's handle. Handing out a texture's image, or a buffer's `VkBuffer` whose zeros or - bytes still wait for the device's next submission (a new `Private` buffer's), first makes that - work, the handle's own alone, by a submission it waits for, so the consumer's own work on the - handle comes after it: a buffer's on the device's staging queue where it reserved one (a copy - engine; or, on a device where no memory the host caches holds a texture's image, such as an - RX 7900 XTX under RADV, a queue of compute work beside its own), behind no other work of the - program's, else on the device's first `VkQueue`, behind what was submitted there before. - A texture over a buffer's bytes that aliases them gives a linear image (the same one for textures - of one image over the same bytes of one import of host pages, which share it), which over a - no-copy buffer's or dma-buf host pages may be of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` - (`DRM_FORMAT_MOD_LINEAR`, its one memory plane at the texture's `bytes_per_row`): ask its layout - of memory plane 0. An `A8Unorm` texture over a buffer that only reads (no render, shader write or - atomic usage; one level and one sample), on a device whose `A8_UNORM` image lacks a feature its - optimal one has in linear tiling or in `DRM_FORMAT_MOD_LINEAR` (the RTX 3090 lists that - modifier for no `A8_UNORM` image) and whose `R8_UNORM` image lacks none in either, has the image - an `R8Unorm` texture over the same bytes has, of `R8_UNORM`, which its bindings read through - `(0, 0, 0, R)` (`WorkCounts::alpha_textures_held_in_red`). -- `CommandBuffer::encode_wait_for_vk_semaphore` and `encode_signal_vk_semaphore` order a command - buffer against the consumer's own work. -- An event's timeline semaphore, plain or shared, orders the consumer's submissions against - command buffers' `encodeWaitForEvent:` and `encodeSignalEvent:` of the event. Its counter is a - signal index, not the event's value: `vk_wait(value)` answers the counter a submission waits for - (or that the value is reached, or not yet signalled), and `unsafe reserve_vk_signal(value)` - reserves the counter one submission signals, after the counter it names, or answers that Metal - drops the signal (`Event` and `SharedEvent` have both). A command buffer's wait for a plain - event's reserved signal goes to its `VkQueue` with a Vulkan wait for the counter, maybe before - the consumer's submission is made, so the consumer signals from a queue no such command buffer - is ahead of (an extra or reserved queue). A shared event's value may be set from the host - (`setSignaledValue:`), which no Vulkan wait can answer, so a command buffer's wait for its - reserved signal is held until the device's watcher saw the signal land: an event the host never - sets avoids that hold as a plain one. The device watches for the consumer's signals landing and - keeps the event's value in step. -- `Device::new_texture_with_vk_image` makes a `Private` texture over the consumer's `VkImage` (a - swapchain image, for presenting). Placed `IdPlacement::Outside`, it takes no resource ID, so the - program's textures are numbered as with no window. -- `Device::new_buffer_with_vk_buffer` makes a buffer over the consumer's `VkBuffer` and memory, - such as an imported dma-buf, made with `Device::vk_buffer_usage()`. The runtime never frees it. -- `Device::new_texture_with_vk_image_plane` makes a `Private` texture over one plane of the - consumer's multi-planar `VkImage` (`R8`/`RG8` of NV12, `R16`/`RG16` of P010), as - `newTextureWithDescriptor:iosurface:plane:` does of an IOSurface plane: the consumer's image is - `CONCURRENT` across the runtime's queue families and its own, `MUTABLE_FORMAT` and - `EXTENDED_USAGE`, rests in `GENERAL`, and outlives the texture; the runtime views the plane in - place and never moves its layout, takes ownership or frees it. A copy, fill, mipmap generation - or render pass of the plane is refused (`RuntimeGap::VkImagePlaneCopy`). -- `Buffer::vk_host_memory` answers where a no-copy buffer's bytes lie in the device's import of - the consumer's pages (memory, offset, size, type, `HOST_ALLOCATION` handle type), where they are - imported by their pointer in one allocation, so the consumer binds a buffer of its own usage - (a video decode's bitstream source) to the same bytes; `None` for copied, dma-buf, read-only or - detached pages. -- `Device::new_exportable_buffer` makes a buffer whose memory another API imports (CUDA's - `cuImportExternalMemory`, another `VkDevice`), in memory allocated exportable as an opaque file - descriptor: its own dedicated allocation where the device needs one (it exports such memory - only so, or requires one; a driver's preference alone does not make one), else a block - that exportable buffers share; every other buffer stays in the device's other pooled blocks. - `Buffer::export_memory_fd` answers a new descriptor each call, the consumer's to close, with the - allocation's size, the buffer's offset and length in it, whether it is a dedicated allocation - and its memory type. An import of a shared block reaches the whole block, of which the buffer - is its offset and length. The buffer must outlive every access through an import; an import - may outlive it unused, since each descriptor holds a reference to the allocation's payload. On - a device loss the memory's contents are lost for the imports too, and a device made again exports new allocations. A - device without `VK_KHR_external_memory_fd`, or that exports no buffer's memory so, refuses it - (`RuntimeGap::ExportableMemory`). -- A buffer descriptor's `exported_as` (`MemoryExport::OpaqueFd` or `MemoryExport::DmaBuf`) makes - such a buffer of either handle type with the descriptor's other fields: `aligned_byte` lays that - byte on a multiple of 256 bytes of the exported memory, and `padding_unobserved` lets textures - over it alias it with rows apart. A texture over such a buffer is a linear image made for the - memory's handle type, as Vulkan requires of an image bound in exported memory; such an image - starts `UNDEFINED`, so it takes the memory in place where the device's in-place check of that - exported memory passed, and a texture made before the check answered is a shadow that moves in - place at a later commit (docs/HOWTO.md, section 7, says where each plane must lie). Over a - dma-buf export where no image binds in the memory itself (RADV's 780M), the texture's image is a - `DRM_FORMAT_MOD_LINEAR` one bound to a dedicated import of that memory's own dma-buf, in place - as well (`WorkCounts::exported_dma_buf_images`). An opaque file descriptor's memory the driver - exports only as the buffer's dedicated allocation takes no image: its textures are shadows, - announced. Dma-buf-exportable buffers share blocks of their own kind, or - take a dedicated allocation where the device needs one. `Buffer::export_memory_dma_buf` - answers a new dma-buf each call, with what `export_memory_fd` answers; its `offset` is the - buffer's first byte, so a VA-API `DRM_PRIME_2` surface's plane lies at `offset` plus the plane's - offset in the buffer. A device without `VK_KHR_external_memory_fd`, - `VK_EXT_external_memory_dma_buf` and `VK_EXT_queue_family_foreign`, which the runtime enables - wherever listed, or that exports no buffer's memory as a dma-buf, refuses it - (`RuntimeGap::DmaBufExport`). `NoCopy` contents with `exported_as` are refused - (`Problem::ExportedNoCopy`). -- `Buffer::external_write_done` says the other API's writes to an exported buffer completed (the - consumer waited for them: `vaSyncSurface`, a CUDA stream's synchronize). Vulkan needs an acquire - from the queue family reserved for that API before the device reads them - (`VK_QUEUE_FAMILY_FOREIGN_EXT` for a dma-buf, `VK_QUEUE_FAMILY_EXTERNAL` for an opaque - descriptor): the device's next submission records it, of the whole `VkBuffer`, before any of its - commands, so the call waits for no GPU work; a host-visible buffer's acquire is made at once and - waited for alone. A texture over the buffer that reads it through a shadow (rows no image of the - memory holds, such as a decoder's pitch) copies the bytes in again at its next use in a command - buffer committed after the call; without the call, it may keep reading what it copied in before. - Call it once after each external write, while none of the runtime's commands that use the buffer - is in flight. Metal has no counterpart. -- `Device::new_exportable_shared_event` makes a shared event whose timeline semaphore another API - imports (CUDA's external semaphores, another `VkDevice`), made exportable as an opaque file - descriptor; `SharedEvent::export_semaphore_fd` answers a new descriptor each call. Its counter - is the signal index the event's interop hooks name: the importer waits for the counter - `vk_wait` answers and signals only one `reserve_vk_signal` reserved. The event outlives every - import and every signal and wait an importer submitted; on a device loss its state is lost for - the imports too. A device without `VK_KHR_external_semaphore_fd`, or that exports no timeline - semaphore so, refuses it (`RuntimeGap::ExportableSemaphore`). -- `CommandBuffer::add_completion_sync_file`, before the commit, has the command buffer's last - batch also signal a binary semaphore made exportable as a sync file, after every command it - holds and every earlier submission of its `VkQueue`; `export_completion_sync_file`, after the - commit, hands it out as a new descriptor (`VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT`), - which a `VkDevice` of any driver imports (temporarily) and waits for on its own GPU: another - vendor's GPU that reads what the command buffer wrote waits for no host thread. The export - blocks only until that batch was submitted, never for the GPU (at once after - `commit_and_submit`), and answers `None`, a sync file already signaled (import -1), where the - command buffer finished first. One export per command buffer (`SyncFileProblem::Exported`). - A command buffer that needs no GPU work still takes a submission for the signal, and its last - batch joins no grouped submission. Where the command buffer's completion writes the caller's - pages on the host after its GPU work (a copied host buffer's merge back, a two-copy buffer's - copy out into pages no import maps), the export waits for the completion and answers `None`, - announced (`sync-file-after-host-copies`; counted: `WorkCounts::sync_files_exported`, - `sync_files_after_host_copies`). A device without `VK_KHR_external_semaphore_fd`, or that exports - no binary semaphore as a sync file (MoltenVK among them), refuses it - (`RuntimeGap::SyncFileExport`). - -## The memory model - -- **Storage modes** keep Metal's meaning. `DeviceProperties::has_unified_memory` answers from the - device type: yes for an integrated GPU or a CPU implementation, no for a discrete GPU. Without - unified memory a `Managed` buffer has two copies, as on a Mac with a discrete GPU - (`did_modify_range` and a blit's `synchronize_resource` move the bytes), a `Managed` no-copy - buffer's included (its CPU copy the caller's pages; **Host memory without a copy**, below), and - a `Shared` resource lies in host-cached system memory (announced once, - `shared-in-system-memory`). On a device whose family of transfers alone has a second queue - (NVIDIA's copy engine), the copies in after `did_modify_range`, and new buffers' zeros and - staged bytes, run on that queue before the command buffer that takes them, rather than on the - queue its kernels run on, where they come to 1 MiB or more - (`WorkCounts::fill_queue_submissions`). There a command buffer takes and waits for only the - fills of memory its commands may reach (`WorkCounts::fill_queue_waits_unused` counts those - that waited for fills they reach none of). -- **Past device-local memory.** Where no device-local memory type a `Private` buffer or heap, a - texture's image or (without unified memory) a `Managed` buffer's own bytes takes has room, it - lies in system memory, as Metal makes such resources past a discrete GPU's memory rather than refusing - them (announced once, `device-memory-overflow`; counted in - `WorkCounts::device_memory_overflows`); a `Managed` no-copy buffer then lies in the caller's - pages, as a `Shared` one does (`WorkCounts::managed_device_copies_in_place`). Where the device lists - `VK_EXT_pageable_device_local_memory`, the runtime enables it and the driver may page memory out - to make room instead. A resource Metal itself refuses (longer than `max_buffer_length`, past a - texture's limits) is refused as before. -- **New resources** read what plain Metal's measured answer is: a new buffer reads zero. A - host-visible buffer longer than 32 MiB lies, where the device imports host pointers, in fresh - anonymous pages imported by their pointer, zero as mapped, so that nothing writes its zeros; a - recycled one is set to zero on the host. A new `Shared` or `Managed` texture reads zero: where - it copies on the host, its image is zeroed on the host as it is made, or, where the device has - `VK_EXT_zero_initialize_device_memory` and the image lies in memory no resource used, starts in - the driver's zeros. A new - `Private` texture answers as the Mac the device presents (`MacClass`, which - `DeviceOptions::mac_class` declares, by default the class of the device's GPU: an Apple silicon - Mac on an Apple GPU, a Mac with an Intel or AMD GPU on every other; - `DeviceProperties::lossless_compression` states it): an Apple silicon Mac's reads zero or that - Mac's fixed pattern of a compressed texture; a Mac with an Intel or AMD GPU's reads zero, - filled at its first use (`WorkCounts::private_textures_zero_filled`) unless that use writes - every texel first (`WorkCounts::private_textures_overwritten_unfilled`), never what its memory - held, which may be another process's texels where a consumer's processes share the device - (docs/API.md, accepted differences). A new - resource's first GPU work (its image's first layout, its zeros) runs at the start of the next - command buffer committed on any queue, or on the fill queue (above); a command buffer on - another queue waits for it only where its commands, or its own first work, may reach the new - resource's memory (`WorkCounts::first_work_waits_unused` counts those that waited for first - work they reach none of). -- **The Metal address space.** Every buffer and heap has a `gpu_address`, and textures, samplers, - pipeline states and indirect command buffers a `gpu_resource_id`. Translated shaders read both - from argument buffers, as on Metal 3. A consumer may pin either (`AddressPlacement`, - `IdPlacement`, `Device::reserve_resource_ids`); a pin the space cannot honour is - `Error::PlacementConflict`. The runtime's own buffers (its in-place check's among them), and - the storage of objects Metal shows no address of (a texture buffer the device makes, a visible - function table), lie outside the space, so no pin meets them and no buffer's address depends - on them. -- **Host memory without a copy.** `unsafe Device::new_buffer_with_bytes_no_copy` imports host - memory, given as a `HostMemory`, through `VK_EXT_external_memory_host`; memory the device cannot - import exactly is refused, but where the driver refuses the pointer itself (below). - `unsafe Device::new_heap_with_bytes_no_copy` is its heap twin. - `Buffer::rebind_bytes_no_copy` and `Heap::rebind_bytes_no_copy` move either to another range, - keeping the objects, addresses and IDs. A rebind is refused (`RebindProblem::EncodedUses`) while - a command buffer not yet committed, or an open encoder, used the bytes, or while one committed - that used them, with commands the runtime records once earlier work completed (an indirect - command buffer's executions the GPU writes, a dispatch left to its host step, a predicated - loop's run again of such work or of work on the GPU alone), has not completed; a render - encoder whose attachment lies in them uses them from its open. So is one while a command buffer - committed and not yet submitted used them in an encoder the runtime cannot encode again (a - compute encoder its unit of command predication reaches past, among others), until its last - submission (`WorkCounts::rebinds_refused_unsubmitted`). Other threads may encode and - commit command buffers that use the bytes during a rebind: a blit encoder, or a render encoder - that keeps a log, whose call raced it is encoded again over the new pages before its first - submission (`WorkCounts::encoders_raced_rebind` counts the encoders that raced). The calls of the - encoders the runtime may not be able to encode again (every compute encoder's, and a render - encoder's that keeps no log) never race it: the rebind waits up to 2 ms for such a call under way - and is refused past it (`EncodedUses`, counted by `WorkCounts::rebinds_refused_calls_in_flight`; - try again), and such a call that begins during the rebind waits for it; another rebind or a detach of the same buffer or heap, a texture made - over its bytes and a resource placed in the heap during the call are the caller's to exclude. - Where a driver refuses the pointer (RADV refuses shared mappings, a `memfd`'s among them), memory made - with `HostMemory::with_dma_buf` is imported from dma-bufs of its pages instead - ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)), and a no-copy buffer or heap - over memory made without a source is a copy of its pages, as below. A device that enables no - `VK_EXT_external_memory_host` but imports dma-bufs imports only those: memory made with a - source is imported from its dma-bufs, and a no-copy buffer or heap over memory made without - one is a copy of its pages, as where a driver refuses the pointer (a rebind to such memory is - refused, `Unsupported`, naming the extension); on NVIDIA's driver the runtime - never hands the driver pages the kernel cannot pin (a dma-buf's mapping): they take the source, - and else, or where its import fails, a copy, as below. A no-copy buffer's import of such - dma-bufs that only blits have read may be released while idle and imported again at its next - blit, which then costs time: RADV lists every import in every submission. Nothing of Metal's - observes it. A no-copy buffer, heap, or buffer's or heap's rebind whose import the caller's gate - refuses (`HostMemory::with_import_gate`), or whose admitted import fails, and a no-copy buffer - or heap whose pointer the device refuses, or on a device that imports no pointer, with no - dma-buf of its pages serving it (no source given, or one that failed or whose dma-bufs the - device refused), is made over a copy of - its bytes in memory of the device's own, announced (`copied-host-pages`, - [HOWTO](../../docs/HOWTO.md#copied-host-buffers)), wherever the process maps the pages - readable (a dma-buf's mapping among them); over pages not mapped readable it is refused. A - rebind's textures follow it onto the copy. A buffer over exactly the bytes a live copy covers - lies in that copy, as one over a live import's bytes lies in that import. - Without unified memory a `Managed` no-copy buffer is two copies instead - (`HostBacking::DeviceCopy`): the GPU's in device-local memory of the runtime's own, which every - command reads and writes, and the caller's pages, which `contents` answers. The pages are - copied in as the buffer is made and by a rebind (whole), before any command of a command - buffer committed after the call, and a `did_modify_range`'s range at the next commit of a - command buffer that uses the buffer, copied in on that command buffer's queue after the command - buffers before it there, so a later range never lands under an earlier command buffer still to - read the buffer. By default the GPU copies it from the pages' import as that submission runs, - so a CPU write after the commit, before the GPU runs the command buffer, may be read; - `ManagedCopyInPolicy::AtCommit` (which `DevicePolicy::exact_answers()` selects) copies it on - the CPU at the commit into staging buffers of host-cached memory instead, as the pages hold it - then (docs/FAST-PATHS.md). A CPU write no - `did_modify_range` names is not seen by the GPU, as on a Mac with a discrete GPU. A blit's - `synchronize_resource` copies the GPU's copy out to the pages in its command buffer's order: - the bytes the GPU wrote since the buffer's last copy out (every other byte of the pages already - holds what the GPU's copy holds), the whole buffer where those writes are not known (an - untracked buffer, one whose `VkBuffer` was handed out, its first synchronize, - `WorkCounts::managed_synchronizes_whole`). A byte the CPU wrote that the GPU did not keeps the - CPU's value. - The copies run from an import of the pages where the device makes one, else (the gate refused - it, the device refused the pointer) through staging buffers held until their work completed, - at most 256 MiB staged ahead (`WorkCounts::managed_staging_bytes`): never through a copy of the - pages as well. Over pages the process maps read-only the GPU's writes are dropped: nothing is - copied out, and the pages are copied in again at the completion of each command buffer that - used the buffer (`managed_writes_undone`). A detach keeps the GPU's copy, which commands go on - reading and writing; `contents` answers the detached pages' pointer, as every detached no-copy - buffer's does (`Buffer::detach_backing`). The device-local memory it holds is counted in - `managed_device_copy_bytes`. - `CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a - program knows when it may take memory away. The pages under a no-copy object are unmapped only - after the object goes and its keep-alive is dropped (or, given none, its deallocator ran), never - before: Vulkan requires imported pages to stay mapped while their import lives, and the - runtime's threads free imports and submit work over them at any moment - ([HOWTO](../../docs/HOWTO.md#unmapping-host-memory)). A no-copy buffer made over part of a live - one's bytes, or over the same bytes as memory of another class, is bound inside the live one's - import (one live import of a page: Vulkan leaves the same pages imported twice undefined) and - holds it, so the live one's keep-alive is dropped, or, given none, its deallocator runs, only - once both are gone; with a keep-alive its deallocator still runs at its release, as Metal's - (`WorkCounts::host_releases_held_inside`). -- **Constants over imported memory.** On ANV on the Iris Xe RPL-P a uniform buffer read of memory - the device marks external (a no-copy buffer's host pages, a dma-buf) misses a cache: a kernel - whose invocations read one word of a 1 KiB window took 2.0 to 2.5 times as long there as over - device memory, and 5.2 to 5.5 times where each read its own. Where the device's view check - finds that (`ExternalUniformReadsSkipACache`), a `constant` slot with an indexed read whose - window the translation bounds to at most 4 KiB reads through a uniform texel buffer instead, - measured at 0.98 to 1.04 times the time over device memory: the runtime makes a view of the - bound range for each bind, counted in `WorkCounts::uniform_texels_bound`. A longer window keeps its uniform buffer and - stays slower over imported memory (`uniform_buffers_bound_to_16k`, - `uniform_buffers_bound_past_16k`; docs/FAST-PATHS.md, known gaps). -- **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so - encoders that share them order themselves with fences. Commands that reach a resource through an - address or ID in memory need it resident (`use_resource`, `use_heap`), as on Metal. The runtime - orders a tracked buffer by the bytes a command reaches: those its translation proves a shader - reads or writes, else from the bound offset to the buffer's end. Vulkan's synchronization - validation takes a shader's buffer as accessed over its whole descriptor, which spans those - bytes widened to 16-byte granules from the device's offset alignment, so it reports hazards - between commands whose bytes are apart, as it does between untracked uses Metal leaves to the - program; no order of either changes a result. -- **Textures over buffers** share the buffer's bytes. Over a no-copy buffer's host pages or such - a long buffer's fresh pages, an image bound to them would start `UNDEFINED`, and Vulkan lets its - first move, and a render pass's load and store, rewrite any byte bound to it: by default - (`HostPageTexturePolicy::InPlace`) a texture there that samples, reads, renders into it or is - written through a shader (of texels of 1, 2, 4, 8 or 16 bytes, the narrow ones checked apart) - is an image in place wherever the - device makes it and its own check showed those operations keeping every byte for that kind of - pages (but the rows' padding of a texture over a buffer a kernel writes, which an x86 Mac's GPU - may change too: docs/API.md, section 10), on a discrete GPU as on any other (run once per driver and release on a thread of its - own, kept in the shader cache). The runtime keeps a copy and announces it (`shadowed-texture`, - naming why) for every other texture there (under `HostPageTexturePolicy::Shadow`, one a shader - writes of texels of a width the check stores none of, one made before the check answered or - whose check did not - pass), where the device's linear images cannot hold Metal's layout, and where the rows lie with - bytes between them (but over a buffer whose maker declared them unobserved, - `BufferDescriptor::padding_unobserved`, below). A texture over a two-copy `Managed` no-copy - buffer's bytes is over the GPU's copy, as over a `Managed` buffer of the runtime's own. On a - discrete GPU, a `Managed` texture over the bytes of a no-copy buffer that lies in its pages - (not an IOSurface plane's) that only samples or reads, whose - policy takes the image in place, over memory that carries a log of its writes - (`HostMemory::with_dirty_pages`), tracked and laid out as one copy, is instead such a copy in - the device's memory, announced nowhere, whatever the check answered: the GPU's copy of the two - a `Managed` resource is on a Mac with a discrete GPU, its copies in only the rows the log - reports changed (`WorkCounts::device_copy_textures`). A `Shared` texture and an IOSurface's - stay in place there, read across the bus as a discrete Mac's GPU reads them. Exact either way; - integrated GPUs, CPU devices and memory without a log keep the image in place. -- **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin over a surface's planes) hold an - image of the texels Metal reads, converted from the planes before a command buffer's first use - where they changed. Where `has_unified_memory`, a function that only samples or gathers a - `YCBCR8_420_2P` or `YCBCR10_420_2P` texture reads the planes' codes in place instead and converts them in the - shader, exactly as the image holds them (`WorkCounts::ycbcr_textures_in_place`, - `ycbcr_planes_bound`; a texture that keeps the image counts why, `ycbcr_images_kept_*`). - -## Runtime extensions - -Calls Metal does not have, for a consumer that emulates a Metal device: - -- `Device::new_command_queue_unshared(count)` makes a command queue that shares its `VkQueue` with - no other where the device has `VkQueue`s to share, for one whose command buffers must never wait - behind another queue's (a compositor's); a device with one graphics queue (RADV, ANV, lavapipe) - has none to spare, so there the other queues' batches are held back from that `VkQueue` while 2 - ms or more of their expected GPU work is in flight on it (`UnsharedIsolationPolicy::Bounded`, the - default), and its command buffers wait behind about one batch of theirs, the whole of a long - one (docs/FAST-PATHS.md, known gaps; counted: - `WorkCounts::unshared_command_buffers_behind_other_queues`, and its wait's tallies). The plain - queues there take turns (`QueueTurnPolicy::Fair`, the default): each keeps about 2 ms of its - own expected GPU work in flight while another submits there, so none waits behind another's - whole burst of command buffers (`WorkCounts::heads_held_for_queue_turns`). Under `QueueSharingPolicy::Adaptive` (the default), where the device's own check - finds its GPU idle between consecutive work of two `VkQueue`s (NVIDIA's driver), the other - command queues move among the `VkQueue`s of their family at their idle points and share them - ([docs/API.md](../../docs/API.md#the-policy)); this one keeps the `VkQueue` it takes for its - life, no queue moves onto it, and a queue already there leaves at its next idle point. A - shared queue waits behind another's long command buffer once per queue that goes long: the - first long command buffer of a queue it shares a `VkQueue` with holds its command buffers for - that command buffer's whole length (beside 30 ms command buffers on an RTX 5080, a compositor's - 64 completions over 10 ms and one of 30 ms). Make a queue that must never wait so (a - compositor's) with this call: on that GPU, none of its completions took over 10 ms in any run. - Under every policy it takes a `VkQueue` no other command queue holds where one is free, and no - command queue made later takes that `VkQueue` while another is free of unshared queues (every - command queue takes, as it is made, the `VkQueue` the fewest live queues hold); where none is - free it shares the one the fewest hold, counted - (`WorkCounts::unshared_queues_sharing_a_vk_queue`). A count of 0 and a lost device are refused - as `new_command_queue_with_max_command_buffer_count` refuses them. - -- `Device::new_command_queue_for_copies()` makes a command queue whose command buffers run on the - device's copy engine (a queue family of transfers alone), beside the graphics family's work - rather than behind it: on an RTX 3090 a readback through another graphics-family queue waited - 1.88 s for a 2 s kernel, where the copy engine's took 7.8 to 13.5 ms. Metal has no such queue. - It answers `None` where the device has no copy engine to give (MoltenVK, lavapipe, RADV unless - `RADV_PERFTEST=transfer_queue`, a copy engine of one queue, a device made with - `Device::from_raw`); keep a plain queue's path there. Every copy queue of a device submits to - one `VkQueue`: the copy engine's third queue, or, on NVIDIA's copy engine of two, the queue the - device's own fills from host memory take (`device/staging.rs`). Its command buffers take blit - encoders alone, and of those `copy_from_buffer_to_buffer`, `fill_buffer` and fence updates and - waits; anything else, and a buffer of the consumer's (`new_buffer_with_vk_buffer`) not - concurrent with the copy engine's family, is refused (`Invalid`, `Problem::CopyQueue`). Every - buffer the runtime makes, a no-copy buffer over host pages among them, is shared with that - family (`VK_SHARING_MODE_CONCURRENT`), so no buffer changes owner; hazards are tracked across - queues as for any queue, and its command buffers keep commit order: a copy that reads what - another queue's command buffer committed before it wrote (or writes what that one uses) waits - for it on the GPU, and where the runtime holds that command buffer back (for a pipeline still - being made, a host step, its submission checks), waits behind it in the scheduler with no host - wait; one held for an event the program has not signalled holds back no copy. On a device that - answers `None`, a plain queue used instead does not keep that order behind a command buffer held - for its pipelines' making (the pipeline waits, below): order such a copy after it with an event. - The completion sync file - (`CommandBuffer::export_completion_sync_file`) is signalled on the copy engine. Its batches are - counted (`WorkCounts::copy_queue_batches`). - -- A blit encoder's consecutive `copy_from_buffer_to_buffer` calls between the same two buffers - that need no barrier between them (none reads or writes what an earlier one of the run wrote, - nor writes what it read) are one `vkCmdCopyBuffer` of many regions, on every queue - (`WorkCounts::buffer_copies_merged`). The encoder's hazard order keeps eight ranges of a buffer - and then one span over them all, so a copy into that span takes a barrier and starts a new run: - sort row copies by destination offset (rows in order, tile beside tile) to merge them all. - -- `CommandBuffer::commit_failed(CommitFailure)` commits a command buffer as failed, running the - encoders Metal would still run and keeping its signals, as a consumer measured on an M3 Max. -- `CommandBuffer::set_submission_check` runs a check as the command buffer is submitted, and fails - it as Metal fails a submission. It runs on the thread that submits it: the scheduler's, one in - `commit_and_submit`, or the one that makes the pass of a `commit_and_submit` left for a render - encoder's end, so it must take no lock that thread holds and wait for no GPU work. It - runs once the command buffer's event waits are met as Metal submits it: an `Event` wait for a - signal already submitted is met at once and waits on the `VkQueue`; a `SharedEvent` wait that - only a GPU signal still running reaches is held until the signal lands (measured on an M3 Max, - the conformance case `event-wait-behind-a-running-signal`). -- `CommandBuffer::add_submission_handler` is called when the runtime takes the command buffer's - last batch for its queue (submits it, or holds it for one kernel submission with later ones; - what another queue's command buffers had held then goes to the driver before it runs, and the - completion of one that needs no GPU work, taken with no submission behind no work in flight, - never waits for it), or sooner, as the command buffer becomes `Scheduled`, where its remaining - batches wait only for a host step of its queue's behind work already submitted (Metal schedules - it then, its dependencies resolved). Which thread runs it: where the command buffer's own - `commit_and_submit` call took the last batch, that call's thread, inside the call; otherwise - one of the device's handler threads, those that run its scheduled and completed handlers, to - which the scheduler thread, or another `commit_and_submit` call's pass, hands it right after - taking the batch, going on with its submissions meanwhile. Two exceptions - run it on the scheduler thread or the hang's thread: a pass that settled a switch of a fetched - target's storage form before taking the batch (once the switch ended), and a command buffer - behind a GPU hang. Every command buffer's handlers run in submission order. The command buffer - becomes `Scheduled` (its scheduled handlers on) only after them; the completion of its queue's - earlier command buffer never waits for them, and its own completion, where its work ended - first, waits for them in its place without holding a thread; - `add_executed_commands_handler` each time an execution's indirect records are read. -- `CommandBuffer::add_completion_seen_handler` is called once the command buffer completed, its - status, error and GPU times final, on the runtime's thread that saw it complete (its queue's - waiter) where its transition to `Completed` runs there, before its completed handlers and - before `wait_until_completed` returns: one with no completed handler then finishes with no - handler thread woken. One with completed handlers too has its status made final and these run - there, and the rest of its transition (its completed handlers on) goes to its queue's handler - thread, where its queue's later transitions follow it; unless another queue's command buffer - may complete after it (it signals an event at its end). It runs on the queue's handler thread - where the transition does (an earlier transition of the queue still there, a command buffer that - signals an event at its end with completed handlers, or the transition of another queue's - command buffer whose GPU signal it waited for not yet at that one's handlers: it completes after - that one, as Metal's completion follows the GPU's). It must be short and never - block; a wait in it for what has not happened is refused - (`DeadlockCause::CompletionSeenHandler`). -- `CommandBuffer::set_completion_joins_next` marks a command buffer, before its commit, as one - whose completion may be seen with the next one's: under `CompletionPolicy::Exact`, on a device - whose submissions merge (`Device::submissions_merge`) and whose queues' failures are not relayed, - its batches may wait in the scheduler's group as every batch does under - `CompletionPolicy::Grouped`, so up to four batches of one `VkQueue` found ready together in one - pass go in one kernel submission, the first command buffer behind them that is not marked going - last in it and seen complete at its own end. The marked one is seen complete, and its event - signals reached, once the last of that submission completed (late by the GPU time of at most - three batches after it); the submission checks of the batches right behind it run with its own; - no group is kept past its pass under `Exact`, and an unmarked command buffer is never held back - for one. Announced `grouped-completion` once. A no-op elsewhere: under `Grouped`, on a device - whose check did not find the merge, and for a batch that never groups. No Metal counterpart. -- `CommandBuffer::commit_and_submit` commits as `commit` does, then submits on the calling thread - where no other submission pass is under way: the ready command buffers in commit order, this - one among them, each needing no host step and no switch of a storage form, up to the pass's - bound, but for those of a `VkQueue` whose batches' submissions are slow (its last 15 that - submitted command buffers 100 us or more at their median, as timed from each one's start to its - `vkQueueSubmit`'s return: a driver that lists every host import in each kernel submission, - RADV's and ANV's over a guest's memory on a host of unified memory), - which the - scheduler's thread submits while the calling thread goes on - (`WorkCounts::scheduler_at_commit_left_slow_calls`; under `CompletionPolicy::Grouped`, on a driver whose batches may wait in a group, one - goes alone where its `VkQueue` runs at most one earlier submission not seen complete, and is - left to the scheduler's thread to group where two or more run; one held back, another queue's waiting for its check or an event, holds back only the - later commits that wait behind it, as on the scheduler's thread), their submission checks run - inside the call just before each submission (unless one waits for a shared event's GPU signal - to land, which the scheduler's thread waits for; a plain event's wait goes to the `VkQueue`, as - Metal submits an `MTLEvent` wait at once), and its own submission handlers after it, in - submission order with every other command buffer's (those of the other command buffers its pass - submits go to the device's handler threads as it goes on; where it has submission handlers, its - pass ends right after its own last batch, so they wait for no later batch's submission, and it - wakes the scheduler's thread for the rest before it runs them, which submits it meanwhile). - What it leaves goes to the scheduler's thread, which it wakes, as it does after a batch it submitted alone where the batch - may wait in a group. No wake and no thread hop lies on its way to the `VkQueue`, where `commit`'s submission is the - scheduler thread's, as Metal's is its own thread's - (`WorkCounts::scheduler_passes_at_commit`, `batches_submitted_at_commit`, - `batches_checked_at_commit`; why it made no pass, or made one that left its command buffer to - that thread, by reason: the `scheduler_at_commit_left_*` counts). Under - `RenderLoweringPolicy::Worker`, one whose last render encoder's end the lowering thread has not - lowered returns as `commit` does, and the thread that runs its commit once the end is lowered - (the lowering thread, or one waiting for the command buffer) makes that pass, its checks and - handlers with it. How long the program's `commit`, - `commit_and_submit` and `commit_failed` calls held its thread, and how much of it each phase - took (lowering, recording the work left to the commit, its pipeline waits, the scheduler lock's - wait, the pass, the submissions with their checks and handlers), each apart from the others: - `WorkCounts::commit_calls`, `commit_nanos` and the `commit_*_nanos` beside it. -- `RenderCommandEncoder::set_color_resolve_target`, `set_depth_resolve_target` and - `set_stencil_resolve_target` change where a pass resolves until it ends (the last target set - wins), as Metal's private calls do. -- The four draw calls, and an indirect render command's two, take a `DrawPrimitiveType`, which - every `PrimitiveType` converts into, and - whose `LineLoop`, `TriangleFan`, `Quads` and `QuadStrip` are the values 5 to 8 Metal's draws take - besides its header's (`DrawPrimitiveType::from_raw`): each draws as the list plain Metal draws, - in Metal's vertex order, direct, indexed and indirect, and quads and a quad strip count one - `[[primitive_id]]` a quad, as Metal does, where the list draws two triangles. Its `Nine`, value - 9, draws nothing and fails the command buffer as Metal's GPU does: a hang - (`CommandBufferError::GpuHang`), a page fault or a victim of the GPU's recovery - (`GpuRecoveryVictim`), by the draw's form, running nothing from its encoder on (docs/API.md, - "Accepted differences", for the timing and the race over the encoders after a fault); one that - fails at more than one encoder fails with the first one's error, in the time Metal's GPU takes - to reach and recover from each; - a queue's second hang or page fault revokes it, as Metal's does: its later command buffers fail - at their commit (`AccessRevoked`). A kernel's draw of a value past the header's draws points, - as Metal's does. -- `TextureDescriptor::address_mode_map` presents a texture as sampling by other address modes than - its sampler's. -- Resource ID reservations, placements and counts (`Device::reserve_resource_ids`, - `IdPlacement`, `Device::sampler_ids_live`), and the private getters of indirect commands. -- `execute_commands_in_buffer_checked` and `execute_commands_in_buffer_indirect_checked` (render and - compute encoders) take an `IndirectCommandCheck` and what it looks for - (`IndirectCommandCheckNeeds`). Wherever the runtime reads an execution's records, at `commit` for - the CPU's or in the host step for records the GPU may have written, it calls the check with each - command it will record, before it records any; an execution whose records cannot hold what the - check looks for never calls it, and runs on the GPU alone where it can. -- `IndirectCommandBuffer::gpu_written` says whether a route that may write a buffer's records met - it: its command buffer made it resident for writing (`ResourceUsage::WRITE`) and set, in any - encoder, before or after, a pipeline state whose functions may call an indirect-command operation - (`indirect_command_writes`, read from their AIR), or executed commands whose records may name - one; or a blit copied or reset commands into it. Only then does an execution of it wait for the - work before it and read its records on the host. A buffer made resident for writing beside - functions that call no such operation runs its executions from the CPU's records, as one made - resident for reading does (`WorkCounts::indirect_write_residencies_unmarked`). What its records - may hold (`command_writes`), which decides whether an execution runs on the GPU alone, takes what - every such state of the command buffer may write, whichever encoder set it. -- `HostMemory::with_dma_buf` and its `DmaBufSource`: dma-bufs of a no-copy object's pages, for a - device that refuses their pointer, each chunk a dma-buf of its own or a piece of a file the - source shares among several objects (`DmaBufChunk`), which the device imports once. A - source's error holding a `DmaBufStandingRefusal` stands for every range that holds the one it - refused while the texture that asked is made: the making asks the source for none of those - again, where any other error refuses only the request it answers. -- `Device::import_shared_dma_buf` and its `SharedDmaBufImport`: such a shared file imported ahead - and kept while the handle lives, so buffers over it that come and go join one import. -- `HostMemory::with_dirty_pages` and its `DirtyPages` (with `DirtyStamp`): the consumer's log of - the writes to a no-copy object's pages, by which every copy of them into memory of the device's - own (a shadow of a texture over them, a copied buffer or heap over them) copies in only the - pages changed since its last copy, on every device. The runtime's own writes into the pages are - reported back: a copy's (a shadow's copy back, a copied buffer's merge back) naming the copy as - their writer (`DirtyPages::wrote_runs_as`), and the GPU's writes into pages imported in place - and the runtime's CPU writes into them as the consumer's (`DirtyPages::wrote_runs`). Each write - is one call to each log, carrying every run of it there (an object over a guest RAM's scattered - pages is many runs of the RAM's log); by default those call `wrote_as` or `wrote` once a run. - A command that replaces every texel of such a shadow is merged back, as one that leaves some is: - copied in (the changed pages), kept, and only the words it changed written into the pages. -- `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's - gate over a no-copy buffer's, heap's or rebind's import of its pages; a refusal makes a copy of - them. -- `HostMemory::with_zero_from`: the consumer's promise that a no-copy buffer's bytes from an - offset to its length read zero at its making. A `Managed` one's GPU copy on a device without - unified memory then takes those bytes as zeros the device writes in its own memory, none copied - across the bus (`WorkCounts::managed_device_copies_zeroed`, `managed_bytes_zeroed`); nothing - else changes ([HOWTO](../../docs/HOWTO.md#copied-host-buffers)). -- `Buffer::host_backing` (with `HostBacking`): what the GPU uses for a no-copy buffer's bytes now, - or a no-copy heap's buffer's: the caller's pages, imported by their pointer, as dma-bufs or in a - guest RAM's chunk, a copy of them (`copied-host-pages`), which Metal never makes, or, for a - `Managed` one without unified memory, a copy in device-local memory (`DeviceCopy`); a rebind - may change it ([HOWTO](../../docs/HOWTO.md#copied-host-buffers)). -- `BufferDescriptor::padding_unobserved` (`with_padding_unobserved`): the maker of a buffer of - the runtime's own memory declares that nothing reads the bytes between a texture's rows over it - (each row's after its texels to its pitch, the last row's included) or between its slices, so - such a texture is a linear image aliasing the buffer where the device lays one out at its - pitches, or else a `DRM_FORMAT_MOD_LINEAR` image at them where the device's in-place check - passed for its pooled memory (`WorkCounts::pooled_pitched_images`), not a shadow, and those - bytes may change whenever it is made or used; no other byte does - (`WorkCounts::unobserved_padding_aliases`). On a unified-memory device whose other buffers lie - in blocks allocated exportable (docs/FAST-PATHS.md, the `Private` row) such a buffer lies in - blocks of its own, allocated exportable as an opaque file descriptor and a dma-buf where the - device's buffer query takes both, in which no image is bound: a texture over it takes a - `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import of its block's dma-buf - (`WorkCounts::exported_dma_buf_images`), each import held costing each submission as a block - held does. As the texture goes its image parks under the buffer, and the next texture over the - same buffer of the same plan at the same texels and pitches takes it, exporting and importing - nothing (`WorkCounts::exported_dma_buf_images_taken`; untaken, it is released at the residency - thread's next pass where held imports cost each submission, and as the buffer goes); elsewhere - in a plain block of the runtime's memory, whose making holds the process's - submissions on RADV (`WorkCounts::plain_buffer_blocks_made`). Its placement starts on the - device's linear images' memory alignment and takes whole units of it (4096 bytes on Intel's - driver for the UHD 630 on Windows, which rounds a small linear image's size up to it; every - placement meets the 256 or less of the other devices measured), so an image whose rows fill the - buffer lies in bytes the buffer owns, for at most that alignment less one byte more memory. No - Metal counterpart; refused (`PaddingUnobservedNoCopy`) with `NoCopy` contents. -- `BufferDescriptor::aligned_byte` (`with_aligned_byte`): a buffer of the runtime's own memory - laying one of its bytes on a multiple of 256 bytes of its memory, so a texture whose texels start - there (a decoded frame's plane 32 bytes into its surface, say) is a linear image aliasing the - buffer where the device lays one out, not a shadow, on a device whose linear images start on a - multiple of more than the texture's offset (RADV's 256). Its contents start that byte's remainder - short of a multiple of 256, not on a page as Metal's do; its length and `gpuAddress` are Metal's. - No Metal counterpart; refused (`AlignedByteNoCopy`) with `NoCopy` contents. -- `Buffer::texture_placement` and `texture_placement_with_iosurface_plane` (with - `TexturePlacement` and `TextureShadowReason`): where a texture `new_texture` or - `new_texture_with_iosurface_plane` makes of the same arguments lies if made now: in place over - host pages, a shadow pending the device's in-place check, a shadow and why, no host pages, or - another shape. The making's own route answers it, after every check the making runs before it - makes anything, so the same arguments are refused with the same errors. An answer in place asks - the device's format, feature and limit queries first, which make no image; where they refuse - every plan the making would try, that refusal is the answer. Otherwise the query runs the image's - making up to its bind (one or two unbound `VkImage`s, released), so a pitch or an image the device - refuses answers the shadow the texture then is. - `Device::settle_in_place_checks` starts the check and says when its verdicts are known (a zero - timeout waits for nothing). `Buffer::tiled_texture_placement` answers it for - `new_tiled_texture`'s arguments. -- `Device::settle_view_check`, `Device::view_costs` (with `ViewCosts` and `ViewVerdict`) and - `Device::view_check_report`: the device's view check, which decides the two view cost facts - translation takes (`DeviceDescription::measured`) from the device's own timings, never from its - driver or GPU identity. It starts as the device is made, on a thread of its own, and no call - waits for it but `settle_view_check`. The device's work never waits on it: before each kernel's - making it stands by until no command buffer committed waits for its submission, none is in - flight and no `VkQueue` has been used for 20 ms since its start, and before each timed dispatch - for 1 ms; each timed dispatch is submitted only where no command buffer is in flight as it - goes, so it never runs behind the program's work, and stands by again where one is. It - carries none of the program's work: the first work of new resources and the copies queued for - the staging queue wait for the program's own next submission. Its - stand-bys take 10 s in all at most: a device whose work never pauses long enough within them - ends the check `Unchecked`, with no further attempt (`WorkCounts::device_checks`, - `view_check_stand_bys`); it stands by for no one while `settle_view_check` waits. Eight kernels of 256 workgroups of 64 invocations each read - a 1 KiB and a 4 KiB window 256 times through a uniform buffer, a storage buffer and a uniform - texel buffer, every invocation the same vector at each step, each its own, or two fixed ones; - the window lies in the device's memory, and the uniform and per-lane reads through the uniform - and texel buffers run again over host pages the device imported by their pointer. Seven rounds - after a warm-up, the arms interleaved, medians of timestamps. `UniformBufferPerLaneReadsSerialize` - where the storage buffer's per-lane reads took less than 0.3 of the uniform buffer's at both - windows (NVIDIA's measured 0.011 to 0.107, RADV's 0.96 to 1.00). `ExternalUniformReadsSkipACache` - is judged on the reads it moves, over the imported pages: the uniform reads, and the per-lane - reads where the per-lane fact does not hold. It holds where, at both windows, the texel buffer - took less than the uniform buffer's time in every one of them and less than 0.7 of it in at - least one (ANV on the Iris Xe of RPL-P, from its records over host memory: 0.026 to 0.86 of - it, the least for each invocation walking a 1 KiB window, the most for each workgroup walking - 4 KiB; RADV on the Radeon 780M 0.93 and 0.97 for the uniform reads). Both may hold: a slot - with a per-lane read then keeps its storage view, one with indexed reads all uniform takes the - texel view, and one read at constant offsets alone keeps its uniform buffer. `Unchecked`, never - fatal, with no fact, where the device writes no timestamps the host reads or refuses any part of - it. A recovery ends a check under way on the lost `VkDevice`, which it lets go of, and the new - `VkDevice` runs a check of its own. Measured on six devices (jobs m3-max-38378, 38379, 38380, 38382, 38389 and 38359): the - RTX 3090 and the RTX 2080 take `UniformBufferPerLaneReadsSerialize` alone (per-lane 0.073 and - 0.102; the texel buffer 2.20 to 2.26 and 2.26 to 2.72 times the uniform buffer over imported - pages); the Iris Xe of RPL-P takes `ExternalUniformReadsSkipACache` alone (per-lane 4.84; the - texel buffer 0.22 to 0.76); the Radeon 780M, the RX 7900 XTX and lavapipe take neither (the - texel buffer 0.93 to 1.00, 0.99 to 1.41 and 0.86 to 1.84). It holds 4 KiB and 64 KiB of the - device's memory and 64 KiB of host pages while it runs. A cold run took 28 ms (RX 7900 XTX), - 75 ms (Radeon 780M), 101 ms (RTX 3090), 134 ms (Iris Xe) and 136 ms (RTX 2080) from its - thread's start to its answer, 268 ms on lavapipe, of which its 24 arms' medians times its eight - rounds are 7.9, 17.0, 8.9, 43.2 and 12.5 ms of GPU time; a warm one reads its record and runs no - check. Until it answers, pipelines compile with the profile of the - device's identity alone (a uniform view stays a uniform buffer); once it answers with a fact, - every compile from then on takes the profile with those facts measured - (`Device::compile_device`), whose fingerprint, and so every shader cache key, differs; a - pipeline made before keeps its form. Its medians are kept in the shader cache's directory for the - driver, its release and the runtime's, so a later device of the same reads them as it is made - and compiles with its facts from its first pipeline. -- `Device::settle_tiling_cost_check`, `Device::tiling_cost` (with `TilingCost` and - `TilingVerdict`) and `Device::tiling_cost_check_report`: whether the device's GPU pays more for - a texture in place over host pages (a linear image) than for a `Private` one (optimal), measured - on the device, for a consumer that keeps a GPU copy of host pages where it does, as an x86 Mac's - GPU keeps one of each IOSurface. The check runs once the first `settle_tiling_cost_check` - asks, on a thread of its own: over 2048x1536 `BGRA8Unorm` images, a frame of a render pass - that loads and stores the whole target, each fragment fetching a source's texel, and a pass - that writes zero, into each arm's target from its source, and the copies between the optimal - image and the host pages both ways (a download at a CPU lock, an upload after a CPU write), - eight rounds after a warm-up, medians of timestamps. `LinearCostly` where the linear frame - passes the optimal one by more than 500 us and twice, else `LinearCheap` (measured: the Iris - Xe of RPL-P under ANV 2.1 to 4.7 ms against 0.40 to 0.89 ms, about 5.25 times, costly; lavapipe - 3.2 against 2.9 ms, cheap; the check took 78 to 99 ms there); `Unchecked`, - never fatal, where the device writes no timestamps the host reads, imports no host pointer, or - makes or records any part of it otherwise. It holds 24 MiB of host pages and 24 MiB of the - device's memory while it runs, and keeps its medians in the shader cache's directory for the - driver, its release and the runtime's, so a later device of the same reads them at once. The - runtime makes no choice from it. No Metal counterpart. -- `Device::host_pages_texture_placement`: the same answer for a texture - `new_texture_with_iosurface_plane` would make over a no-copy buffer of host pages (`start`, - `length`) imported by pointer or as dma-bufs (`HostBacking::ImportedByPointer`, - `ImportedAsDmaBuf`), asked before the buffer exists. It makes no buffer, import or image. Where - the steps before an import or an image decide the answer (the texture's shape and refusals, the - policy, the texel width, the check's verdicts for texels laid out from `start`, texels past - `length`, rows that share bytes, and the refusals of the device's format, feature and limit - queries), it answers what `texture_placement_with_iosurface_plane` answers once the buffer is - made. Where only an image or the import decides (the driver's linear image's layout, a - `DRM_FORMAT_MOD_LINEAR` plane, their requirements against the import, the dma-buf's source and - import), it answers `InPlace`. No Metal counterpart. -- `Texture::view_placement` (with `ViewPlacement` and `ViewShadowReason`): what a view of the - whole texture in a pixel format (`new_texture_view`) would be if made now: a Vulkan view of the - texture's image, whose copies, bindings and attachments are the image's and whose uses are - ordered with every other view's of it (the tracker keys a view's uses on its image); the image - through a swizzle (a view in other channels of the image's bits, which a render pass renders - into through a view shadow); a view shadow, an image of its own the encoders copy the texels - into and back out of (`shadowed-texture-view`), and why: the device's views reinterpret no - components, the formats' compatibility classes differ, or the image lists no such format (a - texture made without `PixelFormatView` usage takes views of its own format, its sRGB twin and, - where it renders, its channel-order sibling and that sibling's twin); or storage of its own over - the bytes the texture is over. The view's making takes the same decision, so the query refuses - what `new_texture_view` refuses, with the same error, but for storage over the bytes, refused - only as it is made. It makes nothing. No Metal counterpart: Metal makes the view of the - texture's own memory. -- `HostRam`, `Device::use_host_ram` (with `HostRamUse`) and `HostMemory::with_runs` (with - `RunResolver`): a guest's RAM imported whole, in 64 MiB chunks, for a device that refuses views - of guest pages made through dma-bufs; a no-copy object whose pages the consumer resolves to one - run inside one chunk is bound in the chunk, with no import of its own - ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). `HostRam::with_dma_buf` gives the RAM a - source of dma-bufs of its pages: a device whose own check finds held pointer imports taxing - every submission (RADV), or that refuses the RAM's pointer, imports each chunk as one dma-buf. - `HostRam::with_dma_buf_of_runs` gives it a source of one dma-buf of a list of runs (udmabuf's - `UDMABUF_CREATE_LIST`): there a copy by runs over a chunk not imported imports lists of its own - pages in place of the chunk, which pins every page of it, each list kept past its command buffer - for the copies of the same pages after it (at most 64 MiB and 16 lists, each released once no - copy took it for 2 s). -- `BlitCommandEncoder::copy_from_host_ram` and `copy_to_host_ram`: runs of a used guest RAM - (host addresses from a 4-byte word to any byte) gathered into consecutive bytes of a buffer, - or scattered back, from the device's chunk imports: runs that start and end on a word (whole - pages, or rows of 4-byte texels) by one compute dispatch for up to 30 of the chunks the runs - touch (the device's `PagesCopyModule::imports`: one where it indexes no array of storage - buffers), other runs by - a copy region per run in a chunk; over a chunk not imported yet, where the device's thread - imports ahead, through memory of the command buffer's own that the CPU copies from or into - the pages; neither touches another byte of their pages; with no view - of the pages and no import of their own; ordered and seen as a copy between the buffer and a - no-copy buffer over the pages - ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). `copy_runs_from_host_ram` and - `copy_runs_to_host_ram` take each run at a byte of the buffer of its own, so a buffer that - keeps a surface's layout (rows at a pitch, the padding between them untouched) is one call for - every row. -- `BlitCommandEncoder::copy_texture_from_host_ram` and `copy_texture_to_host_ram`: one 2D region - of a texture's slice and level filled from, or copied out into, a surface laid out in a used - guest RAM: the surface's bytes in order as host runs (as `copy_from_host_ram` takes them), the - region's rows from a byte of them at a pitch (Metal's buffer layout for - `copy_from_buffer_to_texture`). The rows whose host bytes lie the pitch apart in one chunk - (pages in a row) are one region of a `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` - straight on the chunk's import (`bufferRowLength` the pitch), a row across a chunk's end or a - break in the host bytes a region for each piece, with no staging copy (first touch through the - CPU as the buffer forms); only the texels' bytes are - read or written; ordered and seen as the buffer forms are, the texture as a blit uses it - ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). For a single-sample texture of - uncompressed colour texels with an image of its own. -- `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory), - which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through - the pointer, where the slice forms would need the caller's own copy first. -- `DeviceOptions::pipeline_records` (and `RawDevice::pipeline_records`) is called once per - pipeline state creation (compute, render, mesh and tile, and each - `*_with_additional_binary_functions`) with a `PipelineRecord`: the creation's descriptor, every - field, its libraries named by content hash and kept once in the shader cache directory. A - compute state's direct dispatch of a new shape whose `VkPipeline`s it made (its threadgroup, - its grid's ragged edge and its threadgroup memory lengths) hands it one more record, the - creation's descriptor with that dispatch, at most 16 per state. - `PipelineRecord::to_bytes` and `from_bytes` carry it to a later process; `from_bytes` answers - `None` for a record of another format, so a consumer keeps records across updates and drops - those. Equal creations make equal records. -- `Device::warm(records, byte_budget)` stands in for Metal's own pipeline caches across - processes. It returns at once and, on one background thread of the device's (the utility class - on macOS, its pipeline makings ranked after every other making of the process), makes what each - record's creation makes, in order: its translations into the shader cache and its predicted - `VkPipeline`s' data into the driver's records, so the program's later creation of the same - descriptor finds them, and for a dispatch's record that dispatch's `VkPipeline`s, planned with - nothing bound, so the program's later dispatch of that shape finds their data. It stops once the driver's pipeline cache data its makings added reaches - `byte_budget` bytes; data a making finds in the directory already adds nothing, so over the - directory whose creations made the records the budget binds only where a making writes new - data. It takes no identifier, resource ID or sampler number, makes no neutral, - announces no degradation and keeps nothing for the program's kept variants, and it reads no - translation of another translator and no creation record of another `RUNTIME_VERSION` (a record - holds a descriptor, never a translation), so no answer the program gets changes. Nothing fails: - a record it cannot read (another format, damaged, or a library the directory no longer holds) - is counted and dropped, the device's first announced as the warning - `metal2vulkan-warm-record-unread`, and a failed creation is counted and dropped, the device's - first of each kind announced as the warning `metal2vulkan-warm-record-failed`, which names the - kind (the runtime's error and, for a translator refusal, the refused feature and what it needs) - and nothing of the record's shaders. A creation refused for good on the device (a typed - refusal, such as a kernel past what its driver compiles intact or past the private memory a - thread holds) is kept in the shader cache directory, keyed by the record, the driver's identity - and version, the profile, the runtime's version and the translator's build, and a later pass - over the directory answers that record as failed at once, not translating it again; a transient - failure is never kept. A mesh render - pipeline's record is not made (its creation keeps nothing past the state), and a layout that - bakes an immutable sampler is translated only. `Device::warm_statistics` counts the records - made, each record's outcome (`records_failed_before`: the failures answered from a kept - refusal), the dispatches' `VkPipeline`s made and the driver bytes added. - -[docs/API.md section 10](../../docs/API.md#10-accepted-differences) lists where the runtime -answers otherwise than Metal on purpose. - -## Errors - -Every failure is a value of `metal2vulkan_runtime::Error`. Match its variants; never read the -message text. The ones a consumer meets most: - -| Variant | Means | -|---|---| -| `Invalid(Invalid)` | Misuse plain Metal itself refuses, ending its process or failing the call: `call` names the method, `problem` the typed `Problem`. A program that runs on Metal never makes it. | -| `Nil(Nil)` | What plain Metal answers nil for, the process going on. | -| `MetalError(MetalError)` | What plain Metal answers nil for with an `NSError`: Metal's `domain`, `code` and description as measured, for a consumer to pass on. | -| `Unproven(Unproven)` | What the runtime cannot prove plain Metal's answer for. A consumer that answers as Metal stops its guest, naming the problem. | -| `Unsupported(Unsupported)` | The device lacks what an exact answer needs: `feature` names the Metal feature, `needs` what would change the answer. | -| `NotImplemented(RuntimeGap)` | Plain Metal the runtime does not build yet. Metal takes the input, so a later build may too. | -| `AppleOnly(AppleOnly)` | An Apple-private call off Metal's default with no Vulkan form, or whose meaning on Apple's GPU is unmeasured. Calls that state Metal's default are accepted. | -| `Compile(...)` | A library or pipeline the translator refused, over budget or cancelled ([docs/API.md section 8](../../docs/API.md#8-refusals-requested-inputs-and-precision)). | -| `OutOfMemory`, `DeviceLost`, `Vulkan`, `NoDevice` | The device's own failures. `NoDevice`: the loader opened but found no usable device. A device holding `maxMemoryAllocationCount` allocations live has the next refused (`Vulkan`, `VK_ERROR_TOO_MANY_OBJECTS`) without a call of the driver, counted in `WorkCounts::memory_allocations_refused_at_limit`, once the frees its releases posted to its free thread (which count until they run) completed. | -| `LoaderNotFound(LoaderNotFound)` | The Vulkan loader did not open; `tried` lists each path. | -| `DriverSetting(DriverSetting)` | A driver setting the runtime cannot run under, such as MoltenVK with `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` off. | -| `DeviceRefused(DeviceRefused)` | The driver refused to make the device for want of its resources (`VK_ERROR_TOO_MANY_OBJECTS`, `VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`), with its queue plan's `VkQueue`s and then with its least plan's; `attempts` names each. Other devices of the GPU, in any process, hold what it lacks; once fewer are live it may be made. | -| `WaitWouldDeadlock(DeadlockCause)` | A command buffer wait that would deadlock, refused at once instead of hanging. | -| `ShaderCache(...)` | The shader cache directory `ShaderCacheOptions::directory` names cannot be made or written. | - -```rust,ignore -match device.new_render_pipeline_state(&descriptor, &PipelineOptions::default()) { - Ok(state) => use_it(state), - Err(Error::Unsupported(gap)) => report_device_gap(gap.feature, gap.needs), - Err(Error::NotImplemented(gap)) => report_runtime_gap(gap), - Err(Error::AppleOnly(call)) => report_apple_only(call), - Err(other) => return Err(other.into()), -} -``` - -A library or pipeline creation the runtime refuses can leave what replays it with the -translator's command line, a FALLBACK repro bundle, where `METAL2VULKAN_REPRO_DIR` names a -directory (unset, the runtime writes none): the library's bytes, `device.json` (the device's -description and policy, which the command line's `--device` reads), the request as the command -line's options and descriptor files, `repro.sh`, and `failure.txt` (the call, the refusal, and what -of the request the command does not replay). One is written for each distinct refusal of -`new_library_with_data`, a function's lookup, and a compute, tile or render pipeline state's -creation (not a mesh state's, nor a later variant's of a dispatch or draw), in a directory named by -its content, at most 32 bundles and 256 MiB per process; each is named in one line through the -device's message sink (id name `metal2vulkan-repro`) or on stderr. The refusal returned is the -same, with or without the variable. - -A refused call records nothing. A command buffer that fails while it runs ends with status -`Error` and an `error()`; `metal_code()` gives Metal's code, and `origin()` whether Metal or the -runtime failed it. What a translated shader reports (a resident-set miss, for one) is a fact of -the run, not an error: `CommandBuffer::execution_report` reads it once the command buffer -completed. - -A draw whose pipeline the driver did not make after the draw returned (the runtime makes a draw's -pipeline while the draw goes on) runs nothing, and its command buffer runs on without error: -`CommandBuffer::dropped_draw` names the first, counted: `WorkCounts::draws_dropped_unmade`. A -dispatch's such failure fails its command buffer (`CommandBufferError::PipelineCreation`, -`CommandBuffer::failed_pipeline`). - -A draw or dispatch whose pipeline the driver is still making as its command buffer is committed -is waited for until it is made (`PipelineWaitPolicy::Bounded`, the default; a render or compute -state's creation waits `DevicePolicy::pipeline_creation_wait`, 4.5 s by default, at most for the -pipeline it hands to the runtime's pool): the command buffer completes later, as on a slower GPU, -and renders and writes what Metal's does. `commit` and every other call return as before; only -calls that wait for the GPU (its completion or scheduling, an event it signals, a new command -buffer of a queue whose most are all uncompleted) wait for it. No draw or dispatch is dropped for -its making's time. While it waits, another queue's command buffer committed after it goes first, even over a tracked -resource the two share, and the waiting one runs after it, as an x86 Mac's GPU may take a later -commit of another queue first; a fence the two share keeps commit order, and so does a command -buffer of a queue made for copies (`Device::new_command_queue_for_copies`), which waits behind it -where the two conflict. One -call so waits for the driver's makings at most: a state's creation, its creation wait; a `commit`, -until its commit plus its commit wait (`DevicePolicy::pipeline_commit_wait`, 4.5 s by default), -for a pass that executes render commands the CPU writes, its pipelines and those its executions' -replay begins itself, which it leaves to its host step past that (the commit records there only -what it can; the step records the pass once they are made, and waits on its own thread for a -making it begins itself); neither -waits on the other's bound, so a host step that creates a state and commits waits 9 s at most by -default. Made until made under either value, in the call that makes them: a -draw that records nothing, a draw in a pass of custom sample positions or recorded again into -another instance of its pass (in the draw's call or an execution's replay), a device replay's draws -(in its `commit`), and a making that failed, made again by its command's recording. -`PipelineWaitPolicy::Exact` waits until the pipeline is made, the creation too. - -## A lost device - -A device the runtime made survives the loss of its `VkDevice` (`VK_ERROR_DEVICE_LOST`), as Metal's -device survives a GPU recovery. The first call that needs the device after the loss makes a new -`VkDevice` of the same physical device, options, queue families and extensions; the calls made -meanwhile wait for it. - -- The command buffers in flight fail: the oldest incomplete one with `GpuHang`, the rest with - `GpuRecoveryVictim`. Until the recovery, a command buffer committed on the hang's queue runs - nothing and completes with no error, as on Metal's hang's queue. One made before the recovery - and committed after fails with `GpuRecoveryVictim`. A queue's second hang revokes it, as - Metal's does: a command buffer committed on it from then on, before the recovery too, fails - with `AccessRevoked`. The recovery's notice (`DeviceRecovered`) names the hang's command buffer - by its label (`CommandBuffer::set_label`) and its queue's, with its ended encoders' kinds and - labels (each encoder's `set_label`, which `CommandBuffer::ended_encoders` reports too). -- The `Device` and its `CommandQueue`s go on: what they make from then on is made on the new - `VkDevice`. A `Device` call that the loss meets while it runs is not refused for it: it runs - again on the new `VkDevice`. One that takes host memory, a deallocator or a range token, which a - second run could not have, runs on the new `VkDevice` where the loss came before it took them, - and completes on the lost one where the loss came after, its object then one made before the - recovery. -- The recovery carries the events, the fences, the depth/stencil states, the libraries and their - functions, the dynamic libraries, the binary archives, the address pools (`AddressPool`, whose slots take buffers after it as before), the - rasterization rate maps, the argument encoders, the - uses of guest RAM (`HostRamUse`), the no-copy buffers, the `Private` buffers (exportable ones - among them), the buffers in the runtime's own pages, the `Private` heaps and the heaps over the - caller's memory with the buffers and textures placed in them, the textures of - `new_texture`, the textures over the buffers it carried and the views of either, the compute, - tile, drawing and mesh pipeline states, the sampler states, the indirect command buffers and the - visible function tables to the new `VkDevice`: the same - objects, at the same addresses and resource IDs. A pipeline state's base variant is made again there from what its creation - compiled, with no translation, and the `VkPipeline` its creation predicted is queued with no - wait; a bind of one whose making there failed is refused - (`RuntimeGap::RemadeAfterRecoveryFailed`). Its objects on the lost `VkDevice` go once none of - that device's command buffers may record. A sampler state is placed there as at its making, so an argument - buffer naming its resource ID reads it, and an equal request gets it; its `VkSampler`s are made - there as its binds need them. An indirect command buffer keeps its records where they lie in the - runtime's own pages; elsewhere they are lost and every command reads as reset (the notice counts - these); the programs of the states its commands name are made there, a released state's too. A - visible function table keeps its entries. - An event keeps the value the host saw and its listeners' notifications. A buffer in the - runtime's own pages keeps its bytes and its `contents` pointer: a long host-visible buffer's - fresh pages, and, on a device whose checks found that a held import of host pages costs its - submissions nothing and that textures over such pages take in place what they take over the - device's own memory, the blocks of pages the `Shared` and `Managed` (unified memory) buffers lie - in, imported again on the new `VkDevice`. A no-copy buffer is - made again over the same pages, so it keeps its bytes and its pointer (a two-copy `Managed` one - makes its GPU copy again and copies the pages in: what the GPU wrote and no synchronize copied - out is lost, as a `Private` buffer's contents are); its import gate, run - resolver and dma-buf source are asked again, on the thread that recovers, and must not call - into the device. Its deallocator runs at its release once no `VkDevice` imports its pages. A - `Private` buffer's contents are lost: it reads zero, but for an exportable one, made again over - its own memory's payload imported on the new `VkDevice`, at its offset there: the other API's - imports reach it still, it keeps whatever that memory holds, and its exports after answer the - same memory, with the same allocation size, offset and memory type. So are a `Private` heap's, whose buffers - and textures placed before go on with it and in which buffers and textures are made again. A - heap over the caller's memory (`new_heap_with_bytes_no_copy`) is made again over the same pages, - as a no-copy buffer is, with the buffers and textures placed in it, which read what the pages - hold, and places more there. A texture of `new_texture`, and one placed in a `Private` heap, is - made again in new memory, so its contents are lost whatever its storage mode, `Shared` included, - as its image was their only copy (it reads as a new texture of its descriptor: refill one filled - once and kept); the notice counts these by storage mode. A texture buffer of `new_texture` is made again over its texels' - buffer where the recovery carried that, and one over a carried buffer over the buffer's bytes: - each reads what the buffer holds. A view views its parent there. Their images on the lost - `VkDevice` go once none of that device's command buffers may record, but one whose `VkImage` - was handed out (`Texture::vk_image`), which stays, and keeps that device alive, until its - texture goes. -- Any other object made before the recovery is refused where it meets the new `VkDevice` (an - encoder's bind, a pipeline made from its functions) and in its own calls that need its lost one: - `Error::NotImplemented(RuntimeGap::MadeBeforeRecovery)`. That covers pooled `Shared` and - `Managed` buffers in memory the device allocated, whose `contents` pointer is the lost memory's - mapping (on a device that imports no host pointer, or whose checks found that a held import - costs its submissions or that textures over such pages take less, or had not answered; and a - `Managed` buffer without unified memory), detached no-copy buffers, `Shared`, sparse and - detached no-copy heaps with the buffers and textures placed in them, textures over the caller's - `VkImage`, sparse and shareable textures, textures over buffers left and their views, buffers - over the caller's `VkBuffer`, `Shared` and `Managed` buffers in exportable memory, buffers in an - opaque descriptor's dedicated allocation (Vulkan defines no buffer of another device identical to - its own), exportable events and the visible function tables of pipeline states left. Make it - again. - Metal's objects go on. The recovery's notice counts the buffers, heaps, textures and events it - carried and left, by kind, and the indirect command buffers and visible function tables. -- The lost `VkDevice` is destroyed once the objects left on it went and, where `Device::raw` - answered its handles, a later `raw` call answered the new one's: `WorkCounts::vk_devices_live` - reads 2 until then. A carried object but a texture holds nothing of it once none of its - command buffers records; a carried texture holds it until the texture goes. `vk_devices_made` - and `device_recoveries` count the rest. -- An object's `device` is a generation handle: of the `VkDevice` it was made on, else of the one - a recovery carried it to last. A handle taken of it before the recovery keeps meaning the lost - `VkDevice`: its `raw` answers that one's handles, kept alive while the consumer holds the - handle, so the consumer destroys what it made with them through it. -- Each recovery is announced (`device-recovered`), naming the hang's command buffer. -- A `VkDevice` whose work stopped while the driver answers no loss is recovered from as a lost - one: where no work of it advanced for 10 seconds with some pending and a probe on another - engine (the staging queue) did not complete in 2 seconds, its command buffers in flight fail as - above and the device recovers. Metal's own watchdog is kept too, at 20.2 seconds, the largest - of its measured bounds: a queue's front batch that goes that long without its queue's work - advancing, whatever the probe answers, fails as Metal's timed-out command buffer (`GpuHang`), - the rest in flight as victims, and the device recovers the same way. The stopped `VkDevice` is - parked: never destroyed, none of its objects released, its queues never waited for, and the - notice says it stopped and why. `Device::is_parked` answers whether a `VkDevice` whose handles - `Device::raw` answered is parked: a consumer leaves what it made with those handles (a - swapchain among them) and waits for none of its queues. Counted: `stall_probes_sent`, - `wedges_declared`, `watchdog_timeouts`, `longest_stall_nanos`. -- A command buffer whose queue's timeline passed it while its own timestamps read unavailable - completes, its GPU times 0: a signal with its timestamps unavailable is no loss of the GPU (an - Intel UHD Graphics 630 on Windows read one so, its device going on). So work the driver dropped - while its `VkDevice` goes on completes with no error (docs/FAST-PATHS.md, known gaps): Linux's - amdgpu ends a job past its timeout (2 s by default), and on a Radeon 780M (RADV) the command - buffer queued behind such a job on the same queue never ran either, with no error the device - reported. Counted: `unrun_command_buffers`. -- `Device::raw` answers the new `VkDevice`'s handles once a later call asks; the handles it - answered before stay valid until then, and the lost `VkDevice` stays alive until then, so the - consumer destroys what it made with those handles (a swapchain, an import) first. -- `CommandQueue::with_vk_queue` gives its closure the `VkDevice` the lent `VkQueue` belongs to, - read under the same lock: from the recovery on, the new one, whatever `Device::raw` answered - before. A consumer whose command pool, fence or semaphore was made on another `VkDevice` makes - it again on that one before it submits there. -- A device the consumer made (`Device::from_raw`) is not made again: it answers `DeviceLost` from - the loss on. - -`Device::recover_for_test` runs the same recovery with no GPU fault, for tests of what survives -one. - -## Degrade notices - -Where the runtime gives Metal's answer only at a cost Metal does not pay (a copy, a scratch -resource, an extra pass), or gives a recorded near-equivalent, the device announces it once per -kind: through `DeviceOptions::messages` as a `DebugMessage` whose `degradation` holds a -`DegradeNotice`, else on stderr. A notice is never fatal. `Degradation::code()` is a stable -`metal2vulkan-degrade-` string and `category()` says whether it costs time and memory or -exactness; decode a notice by its `Degradation`, never its text. -[docs/API.md section 9](../../docs/API.md#9-degrade-notices) lists every kind. - -```rust,ignore -let mut options = DeviceOptions::default(); -options.messages = Some(MessageSink::new(|message: &DebugMessage| { - if let Some(notice) = &message.degradation { - log_degradation(notice.degradation, ¬ice.object, ¬ice.reason); - } -})); -let device = Device::system_default_with(&options)?; -``` - -## Line widths - -Apple's private `setLineWidth:` (`RenderCommandEncoder::set_line_width`) takes every width. As -measured on an Apple M3 Max (macOS 27.0.1), Metal draws `w' = floor(16 w) / 16` clamped to -`[0, 16]` (NaN and negative widths as 0), the encoder's from 1 at its start: at `w' = 1` its -ordinary lines, at every other `w'` the parallelogram Vulkan's non-strict wide lines may be (its -minor-axis edges `w'` long through the endpoints, the ends not extended), at 0 as at 1/16. A strip -or loop draws one parallelogram per segment; triangles in fill mode `Lines` draw each edge so, -facing as the triangle does and culled by it, their flat inputs the provoking vertex's. -The runtime draws each draw at `w' != 1` that draws a primitive by one of three routes, counted -(`WorkCounts::device_wide_line_draws`, `line_band_draws`, `nearest_width_line_draws`); a direct -draw whose vertices or indices complete no primitive of its type draws nothing, as Metal's: - -| Device | Route | -|---|---| -| `wideLines`, `w'` in `lineWidthRange` and above 0 | Its own lines, announced `device-wide-lines` (`WideLinePolicy::Device`, the default): no device's are taken as Metal's, a driver's parallelograms included, whose ends the driver places; under `WideLinePolicy::Exact` (`DevicePolicy::exact_answers()`) the band | -| No `wideLines` (MoltenVK), `w'` outside `lineWidthRange`, or `w' = 0` | The band | -| What neither draws | Its own lines at the width nearest Metal's they draw (clamped into `lineWidthRange` and put on the nearer step of `lineWidthGranularity`'s grid from its bottom, never 0; 1 without `wideLines`), announced `lines-at-nearest-width` | - -The band is the pipeline's band variant, through a tessellation control and evaluation stage the -translator adds (docs/API.md section 4): two triangles over each line's parallelogram, and for a -triangle in fill mode `Lines` its three edges' parallelograms, which face as the triangle does under -the draw's cull mode, front face and depth bias. A strip, loop or fan is drawn as the list of its -primitives. The band's depth bias is the device's, of each band triangle's own slope and depths, -where Metal biases the edges by the triangle's: announced `wide-edge-depth-bias` under a slope -factor, or a constant factor over a float depth. Neither route draws, so the nearest width takes: a -mesh draw's lines and edges and a tessellated patch draw's edges the device's lines do not draw (1 -pixel wide on MoltenVK), lines and edges on a device without `tessellationShader` whose lines do not -draw them or of a pipeline state whose band variant the translator refuses (a vertex function that -selects a slice or viewport, barycentric weights, synthesized geometry, multiview; the state's first -band asks), a draw whose own band variant the translator refuses where the state's first band -compiled (a varying or push data the draw's variant adds past the evaluation stage's outputs or -`maxPushConstantsSize`; the state's later draws of the primitive take the nearest width too), an -amplified band, and every wide line in an execution or a rasterization-rate-mapped pass, whose width -Metal's answer is not measured for. Refused `NotImplemented(RuntimeGap::WideLines)`: a strip's band -whose list of primitives the runtime cannot draw. -docs/FAST-PATHS.md records the choice and the known gaps. - -## GPU families - -`DeviceProperties` answers Metal's device queries from the Vulkan device. -`Device::supports_family` answers yes for a GPU family only where every row of Apple's feature set -tables for it (features, limits and pixel-format capabilities) is exact on the device; -`Device::family_blockers` names each blocking row and why: not built yet (`RowState::Gap`), not -possible on this device (a refusal), or Metal's own answer is no. Run it on the device for its -list. - -`Device::supports_32bit_msaa` (`supports32BitMSAA`) answers yes where the device makes a -multisample texture of each 32-bit integer and float color format at every sample count its -textures take, 4 among them, and resolves the float ones, each planned as `Device::new_texture` -plans it within the device's own limits for the format. Vulkan guarantees an integer format only -`framebufferIntegerColorSampleCounts`, one sample on some drivers, but a driver may take more for -one format (RADV does), so the answer follows the device's per-format limits. A float resolve is -the device's own average, announced as `device-rounded-resolve` where it is not Metal's. - -`DeviceProperties::supports_pull_model_interpolation` (`supportsPullModelInterpolation`) answers -yes where the device has `sampleRateShading` (and, on MoltenVK, the portability subset's -`shaderSampleRateInterpolationFunctions`): an `interpolant` input is then read at its centroid, a -sample and an offset through Vulkan's interpolation functions; without them only -`interpolate_at_center` compiles. An offset is read within the device's range and on its grid -(`device-interpolation-offset`); on RADV a perspective interpolant read at a sample or an offset -is the driver's extrapolation from the pixel center, off by the value's curvature across the -distance (`extrapolated-interpolation`); and a draw at custom sample positions through a -function that reads at a sample is refused (`RuntimeGap::InterpolateAtSampleWithPositions`). - -`Device::minimum_linear_texture_alignment_for_pixel_format` -(`minimumLinearTextureAlignmentForPixelFormat:`) answers, per pixel format, the alignment of a -texture's offset and `bytesPerRow` in a buffer at which the device's images hold the texture in -place over host pages, read, rendered and written by a shader, at least the 16 bytes Metal -answers on an Apple GPU and at least the device's `nonCoherentAtomSize`, the line of memory its -check of images in place measures. The runtime asks the driver for every format at the first -query of any by making those images (none is bound), keeps those answers for the device's life, -and writes them as one record per driver in the shader cache's content directory. ANV on an -Iris Xe and lavapipe answer 64, and RADV on a Radeon RX 550 256 (512 and 1024 for the formats of -8- and 16-byte texels), for each format whose texture over a buffer they can hold in place, and -16 for the rest (the two-plane YCbCr, packed and extended-range formats among them). A texture at a smaller multiple -of 16 is still made, as a shadow where the device's images do not take its layout -(`shadowed-texture`). The answer does not put every texture in place: one whose rows' bytes are -no multiple of the device's line keeps its padding in its rows' last line at any alignment, and -on a device whose stores write back such a line whole (ANV's Iris Xe) its renders and writes go -through a shadow. The private `deviceLinearTextureAlignmentBytes` and -`linearTextureAlignmentBytes` answer the largest of the formats' answers. -`Device::linear_texture_bytes_per_row` (a runtime extension, no Metal counterpart) answers, for a -2D texture's descriptor, the row pitch the driver lays its own linear image's rows at, which a -texture over a buffer of the runtime's own memory must meet exactly to be that image, with no -check of the device's: a pitch rounded up to the alignment above can miss it, as that alignment -is where images over host pages lie. - -Where Metal's answers differ by macOS release (which pixel formats it describes, how a heap -texture's blocks lie, its private device properties), -every device answers as one release, `MACOS_RELEASE` (macOS 27.0.1, measured on an Apple M3 Max), -on every host, whatever release the host runs. What a device can do, its GPU family, features and -limits, follows its GPU. - -## Out of scope - -What an ordinary Metal program on Linux needs belongs here; what exists only because the work comes -from a paravirtualized guest belongs to that consumer. So the runtime has none of these, and a -consumer builds them on public calls: - -- IOSurface and Mach VM: use host memory without a copy, textures over buffers, and adopted - `VkBuffer`s and `VkImage`s. Importing a file descriptor or dma-buf is plain Vulkan on the - runtime's device. -- Scattered backing (`replaceBackingWithRanges:`, `detachBacking`): remap memory to be contiguous. -- Apple's serialized pipeline descriptors and guest-visible identifiers (`resourceIndex`, - `uniqueIdentifier`, private device answers): keep them beside the runtime's objects. -- Presentation (`CAMetalLayer`): render into a texture over a swapchain image and present with - plain Vulkan. -- Threads, clocks, preferences and other OS services. - -Plain Metal the runtime does not build yet is refused typed where a program reaches it -(`RuntimeGap` lists every gap; [docs/METAL-COVERAGE.md](../../docs/METAL-COVERAGE.md) maps the -whole Metal API). - -## Further reading - -- [docs/RUNTIME-PORTING.md](../../docs/RUNTIME-PORTING.md): Metal's calls, as Objective-C or - metal-rs makes them, mapped to the runtime's. -- [docs/API.md](../../docs/API.md): the translator's API, the degrade notices, and the accepted - differences. -- [docs/HOWTO.md](../../docs/HOWTO.md): integration, the shader cache, failures. -- [docs/REFUSALS.md](../../docs/REFUSALS.md): every refusal of something Metal accepts. -- The rustdoc (`cargo doc -p metal2vulkan-runtime --open`): every item with its Metal counterpart. - -## License - -Dual-licensed, as the rest of the repository: the GNU General Public License, version 2 or (at -your option) any later version, or the GNU Lesser General Public License, version 3 or (at your -option) any later version, at your choice (`GPL-2.0-or-later OR LGPL-3.0-or-later`). -[LICENSE](LICENSE) is the notice; [LICENSE-GPL-2.0](LICENSE-GPL-2.0), -[LICENSE-LGPL-3.0](LICENSE-LGPL-3.0) and [LICENSE-GPL-3.0](LICENSE-GPL-3.0) (which the LGPL v3 -incorporates) are the texts. diff --git a/crates/metal2vulkan-runtime/examples/adopted_buffer.rs b/crates/metal2vulkan-runtime/examples/adopted_buffer.rs deleted file mode 100644 index 0f14d8005..000000000 --- a/crates/metal2vulkan-runtime/examples/adopted_buffer.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! A Metal buffer over a `VkBuffer` the caller made: the shape of a consumer that imports memory -//! with plain Vulkan (another process's pages, as a dma-buf) and hands it to the runtime. -//! -//! ```sh -//! cargo run -p metal2vulkan-runtime --example adopted_buffer [-- path/to/library.metallib] -//! ``` -//! -//! The example makes the `VkBuffer` and its `VkDeviceMemory` itself, through the runtime device's -//! raw handles, in host-visible coherent memory it maps. A consumer importing a dma-buf does the -//! same, but chains `VkImportMemoryFdInfoKHR` (handle type `DMA_BUF_BIT_EXT`, with -//! `VK_EXT_external_memory_dma_buf` enabled on the device) to the allocation, and passes its own -//! mapping of the same pages as the contents: the runtime never sees the file descriptor. Then -//! `new_buffer_with_vk_buffer` makes a `Shared` Metal buffer over it, which the kernel -//! `scale_and_offset` (of the repository's owned fixture, or of the metallib the argument names) -//! reads and writes, and the caller reads the result through its own mapping. - -mod common; - -use ash::vk; -use metal2vulkan_runtime::{Device, PipelineOptions, ResourceOptions, Size, VkBufferMemory}; -use std::ptr::NonNull; - -/// The floats the kernel scales: the input in the buffer's first half, the output in its second. -const COUNT: u64 = 64; - -/// The caller's buffer: COUNT input floats, then COUNT output floats. -const SIZE: u64 = 2 * COUNT * 4; - -fn main() -> common::Result<()> { - let device = Device::system_default()?; - println!("device: {}", device.name()); - let library = common::library(&device)?; - let function = library.new_function_with_name("scale_and_offset")?; - let state = - device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - - // SAFETY: the handles are used only while the device lives, and none of them is destroyed. - let raw = unsafe { device.raw() }; - // The buffer must be one the runtime could have made: every usage its own buffers have. - let usage = vk::BufferUsageFlags::from(device.vk_buffer_usage()); - let info = vk::BufferCreateInfo::default() - .size(SIZE) - .usage(usage) - .sharing_mode(vk::SharingMode::EXCLUSIVE); - // SAFETY: a live device and a valid creation. - let buffer = unsafe { raw.device.create_buffer(&info, None) }?; - // SAFETY: a live buffer of the device, and the instance's physical device. - let (requirements, properties) = unsafe { - ( - raw.device.get_buffer_memory_requirements(buffer), - raw.instance - .get_physical_device_memory_properties(raw.physical_device), - ) - }; - let host = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; - let type_index = (0..properties.memory_type_count) - .find(|&index| { - requirements.memory_type_bits & (1 << index) != 0 - && properties.memory_types[index as usize] - .property_flags - .contains(host) - }) - .ok_or("no host-visible coherent memory type for the buffer")?; - // Where the device enables `bufferDeviceAddress`, the usage names device addresses and the - // memory must be allocated for them. - let mut address = - vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let mut allocate = vk::MemoryAllocateInfo::default() - .allocation_size(requirements.size) - .memory_type_index(type_index); - if usage.contains(vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS) { - allocate = allocate.push_next(&mut address); - } - // A dma-buf import chains its `VkImportMemoryFdInfoKHR` here. - // SAFETY: `allocate` and its chain live for the call. - let memory = unsafe { raw.device.allocate_memory(&allocate, None) }?; - // SAFETY: unbound memory meeting the buffer's requirements from offset 0. - unsafe { raw.device.bind_buffer_memory(buffer, memory, 0) }?; - // SAFETY: host-visible memory, mapped once, whole. - let mapped = unsafe { - raw.device - .map_memory(memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) - }?; - let mapped = NonNull::new(mapped.cast::()).ok_or("a null mapping")?; - - // The caller writes the input through its own mapping. - let input: Vec = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect(); - // SAFETY: SIZE mapped bytes, which nothing else uses yet. - unsafe { std::ptr::copy_nonoverlapping(input.as_ptr(), mapped.as_ptr(), input.len()) }; - - // `Shared` storage: `contents` is the caller's mapping. - // SAFETY: the buffer was made with exactly `info` and bound whole at 0 to `memory` of - // `type_index` (allocated for device addresses where the usage names them); `mapped` maps its - // bytes, coherent, for as long as the Metal buffer lives; both outlive the Metal buffer and the - // command buffer, and the caller touches the bytes only once that has completed. - let metal = unsafe { - device.new_buffer_with_vk_buffer( - buffer, - &info, - VkBufferMemory::new(memory, 0, type_index, Some(mapped)), - SIZE, - ResourceOptions::shared(), - ) - }?; - println!( - "adopted: {} bytes at Metal address {:#x}, contents at the caller's mapping: {}", - metal.length(), - metal.gpu_address().0, - metal.contents() == Some(mapped) - ); - - let scale = device.new_buffer_with_bytes(&2.0f32.to_le_bytes(), ResourceOptions::shared())?; - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(&state)?; - encoder.set_buffer(Some(&metal), 0, 0)?; - encoder.set_buffer(Some(&metal), COUNT * 4, 1)?; - encoder.set_buffer(Some(&scale), 0, 2)?; - encoder.dispatch_threads(Size::new(COUNT, 1, 1), Size::new(32, 1, 1))?; - encoder.end_encoding()?; - common::run(&command_buffer)?; - - // The caller reads the output through its own mapping: output[i] = i * 2 + i = 3i. - // SAFETY: SIZE mapped bytes; the command buffer that wrote them completed. - let bytes = unsafe { std::slice::from_raw_parts(mapped.as_ptr(), SIZE as usize) }; - // The Metal buffer's `contents` are the same bytes. - if common::bytes(&metal)? != bytes { - return Err("the Metal buffer's contents differ from the caller's mapping".into()); - } - let output: Vec = bytes[(COUNT * 4) as usize..] - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect(); - for (i, &value) in output.iter().enumerate() { - if value != 3.0 * i as f32 { - return Err(format!("output[{i}] is {value}, not {}", 3 * i).into()); - } - } - println!( - "output[0..4] = {:?}: as expected, in the caller's memory", - &output[..4] - ); - - // The Metal buffer goes first, then the caller's objects: the runtime never destroys them. - drop((metal, command_buffer)); - // SAFETY: no Metal buffer or command buffer uses them any more. - unsafe { - raw.device.unmap_memory(memory); - raw.device.destroy_buffer(buffer, None); - raw.device.free_memory(memory, None); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/common/mod.rs b/crates/metal2vulkan-runtime/examples/common/mod.rs deleted file mode 100644 index 90476f586..000000000 --- a/crates/metal2vulkan-runtime/examples/common/mod.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! What every example shares: the library it runs, running a command buffer to completion, and -//! reading a buffer's bytes. - -use metal2vulkan_runtime::{Buffer, CommandBuffer, CommandBufferStatus, Device, Library}; -use std::path::PathBuf; -use std::process::Command; -use std::time::Duration; - -/// An example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -pub type Result = std::result::Result>; - -/// The longest an example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// The library the example runs: the metallib file the first argument names -/// (`newLibraryWithData:`, which takes a metallib alone, as Metal's does), or else the -/// repository's owned fixture `validation/fixtures/public/examples/runtime_examples.ll`, -/// assembled to AIR bitcode by `llvm-as` from `PATH` and parsed by the translator -/// (`metal2vulkan::library::Library::from_air`), whose library the device takes -/// (`new_library_with_compile_library`). A metallib built from `runtime_examples.metal` with -/// Apple's tools runs the same: -/// -/// ```sh -/// xcrun -sdk macosx metal -o runtime_examples.metallib \ -/// validation/fixtures/public/examples/runtime_examples.metal -/// cargo run -p metal2vulkan-runtime --example compute_dispatch -- runtime_examples.metallib -/// ``` -pub fn library(device: &Device) -> Result { - match std::env::args_os().nth(1) { - Some(path) => { - let bytes = std::fs::read(&path) - .map_err(|error| format!("read {}: {error}", PathBuf::from(&path).display()))?; - Ok(device.new_library_with_data(&bytes)?) - } - None => { - let library = metal2vulkan::library::Library::from_air(&fixture_bitcode()?)?; - Ok(device.new_library_with_compile_library(library)) - } - } -} - -/// The owned fixture's LLVM text, assembled to AIR bitcode by `llvm-as` (LLVM 21 or newer). -fn fixture_bitcode() -> Result> { - let ll = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); - let output = Command::new("llvm-as") - .arg("-o") - .arg("-") - .arg(&ll) - .output() - .map_err(|error| { - format!("cannot run llvm-as (put LLVM's bin directory on PATH, or pass a metallib): {error}") - })?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - return Err(format!("llvm-as {}: {stderr}", ll.display()).into()); - } - Ok(output.stdout) -} - -/// Commit `command_buffer` and wait for it, as `commit` then `waitUntilCompleted`: an error when -/// it did not complete, with the command buffer's `error`. -pub fn run(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("the command buffer did not complete within {WAIT:?}"))?; - match command_buffer.status() { - CommandBufferStatus::Completed => Ok(()), - status => Err(format!( - "the command buffer ended {status:?}: {:?}", - command_buffer.error() - ) - .into()), - } -} - -/// A copy of the bytes of `buffer`, whose storage the host reaches (`contents`), once no command -/// buffer writes it. -pub fn bytes(buffer: &Buffer) -> Result> { - let contents = buffer.contents().ok_or("the buffer has no contents")?; - // SAFETY: `contents` holds the buffer's `length` bytes, and no command buffer writes them - // now (the caller's contract). - let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }; - Ok(bytes.to_vec()) -} diff --git a/crates/metal2vulkan-runtime/examples/compute_dispatch.rs b/crates/metal2vulkan-runtime/examples/compute_dispatch.rs deleted file mode 100644 index 333af5833..000000000 --- a/crates/metal2vulkan-runtime/examples/compute_dispatch.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! A compute dispatch from a metallib, as a Metal program makes one: the system default device, a -//! library from bytes, a compute pipeline state of one of its functions, three buffers, one -//! command buffer, and the result read back on the CPU. -//! -//! ```sh -//! cargo run -p metal2vulkan-runtime --example compute_dispatch [-- path/to/library.metallib] -//! ``` -//! -//! Without an argument it runs `scale_and_offset` of the repository's owned fixture -//! (`validation/fixtures/public/examples/runtime_examples.metal`), assembled from its committed -//! LLVM text with `llvm-as` from `PATH` and parsed by the translator; with one, the metallib it -//! names, which must define the same kernel. `new_library_with_data` takes a metallib alone, as -//! Metal does: AIR bitcode goes through the translator (`common::library`). - -mod common; - -use metal2vulkan_runtime::{Device, PipelineOptions, ResourceOptions, Size}; - -/// How many floats the kernel scales. -const COUNT: usize = 1000; - -fn main() -> common::Result<()> { - // `MTLCreateSystemDefaultDevice()`: the preferred Vulkan physical device (discrete, then - // integrated, virtual, CPU) that the runtime can open, with the default options. - let device = Device::system_default()?; - println!("device: {}", device.name()); - - // `newLibraryWithData:error:`, `newFunctionWithName:`, and - // `newComputePipelineStateWithFunction:error:`. The translation to SPIR-V happens here, under - // the 20-second budget; a refusal is a typed error naming what the device lacks. - let library = common::library(&device)?; - let function = library.new_function_with_name("scale_and_offset")?; - let state = - device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - println!( - "pipeline: {} threads per threadgroup at most, SIMD width {}", - state.max_total_threads_per_threadgroup(), - state.thread_execution_width() - ); - - // `newBufferWithBytes:length:options:` and `newBufferWithLength:options:`, in `Shared` - // storage, which the CPU reads and writes through `contents`. - let input: Vec = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect(); - let input = device.new_buffer_with_bytes(&input, ResourceOptions::shared())?; - let output = device.new_buffer((COUNT * 4) as u64, ResourceOptions::shared())?; - let scale = device.new_buffer_with_bytes(&2.0f32.to_le_bytes(), ResourceOptions::shared())?; - - // One command buffer with one compute encoder. Hazards between commands are tracked as Metal - // tracks them: no barrier is written by hand. - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(&state)?; - encoder.set_buffer(Some(&input), 0, 0)?; - encoder.set_buffer(Some(&output), 0, 1)?; - encoder.set_buffer(Some(&scale), 0, 2)?; - // `dispatchThreads:threadsPerThreadgroup:`: a grid of COUNT threads, the last threadgroup - // partial, as Metal runs it. - encoder.dispatch_threads(Size::new(COUNT as u64, 1, 1), Size::new(64, 1, 1))?; - encoder.end_encoding()?; - common::run(&command_buffer)?; - - // output[i] = input[i] * 2 + i = 3i. - let output: Vec = common::bytes(&output)? - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect(); - for (i, &value) in output.iter().enumerate() { - if value != 3.0 * i as f32 { - return Err(format!("output[{i}] is {value}, not {}", 3 * i).into()); - } - } - println!( - "output[0..4] = {:?}, ..., output[{}] = {}: as expected", - &output[..4], - COUNT - 1, - output[COUNT - 1] - ); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/copy_engine.rs b/crates/metal2vulkan-runtime/examples/copy_engine.rs deleted file mode 100644 index 622b068c6..000000000 --- a/crates/metal2vulkan-runtime/examples/copy_engine.rs +++ /dev/null @@ -1,1378 +0,0 @@ -//! Not a consumer's example: what a copy between host memory and device memory costs on a queue -//! of the device's graphics family, where the runtime records its shadows' copies and its first -//! work, and on a queue of a family of transfers alone (a copy engine, the family the runtime's -//! staging queue takes: `src/device/staging.rs`), alone and beside a compute load on another -//! queue of the graphics family. It uses no runtime: a Vulkan device of its own, made through the -//! loader, on the first discrete GPU (else integrated, virtual or CPU device) the loader lists. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example copy_engine -//! ``` -//! -//! The device takes the graphics family's first two queues (copies on the first, the load on the -//! second) and the first queue of the first family of transfers alone whose copies take any texel -//! (`copy`), else of the first other family of compute work (`compute`), as the runtime's staging -//! queue takes them. It prints `COPY-ENGINE` lines: -//! -//! - **Copies**: host-visible memory the device does not hold (the host's pages, a shadow's or a -//! `Managed` buffer's host side) to and from device-local memory: into and out of an optimal -//! `R8G8B8A8_UNORM` image [`WIDTH`] texels wide (`image`), and a buffer (`buffer`); each one -//! submission waited for. GPU time from its timestamps, wall time from `vkQueueSubmit` to the -//! wait's return, and the bytes a second of GPU time. First, 4 MiB round trip through the -//! image on each queue and are checked. -//! - **Load**: a kernel of [`LOAD_WORDS`] invocations of integer arithmetic, sized to about -//! [`LOAD_MS`] a dispatch, two in flight on the graphics family's second queue; each phase -//! beside it prints the dispatches completed a second, against the load alone before it. -//! - **Handoff**: a copy into the device buffer and then a dispatch that reads it, on the graphics -//! queue in one submission (`graphics`), or the copy on the other queue and the dispatch on the -//! graphics queue waiting for its timeline semaphore (`copy`, `compute`): wall time from the -//! first `vkQueueSubmit` to the dispatch's completion, what moving a copy the next commands wait -//! for costs them. -//! -//! Each phase prints its span on the host's clock (`from`, `to`, Unix milliseconds), so a -//! sampler's lines (`nvidia-smi dmon`) can be placed in it. - -use ash::vk; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -/// The texels of a row of the image, and so a row's bytes. -const WIDTH: u32 = 8192; -const ROW: u64 = WIDTH as u64 * 4; -/// The most bytes a copy moves: the host buffer's, the device buffer's and the image's size. -const MOST: u64 = 256 << 20; -/// The copies timed beside the load and alone, a phase each, and how long a phase runs. -const LARGE: [u64; 2] = [64 << 20, 256 << 20]; -const LARGE_SPAN: Duration = Duration::from_secs(4); -/// The copies timed alone, and how long a phase runs. -const SMALL: [u64; 4] = [64 << 10, 1 << 20, 4 << 20, 16 << 20]; -const SMALL_SPAN: Duration = Duration::from_millis(1500); -/// The handoffs' copies, and how long a phase runs. -const HANDOFF: [u64; 5] = [4 << 10, 64 << 10, 1 << 20, 16 << 20, 64 << 20]; -/// The fewest copies a phase times. -const LEAST: usize = 5; -/// The load's invocations, one word of its buffer each (32768 workgroups of 64: within the -/// 65535 every device dispatches along x), and the GPU time a dispatch aims at. -const LOAD_WORDS: u64 = 32768 * 64; -const LOAD_MS: f64 = 4.0; -/// How long one wait lasts before the test fails. -const TIMEOUT: u64 = 20_000_000_000; - -/// The load kernel: each invocation of 64 a workgroup reads its word, runs `rounds` steps of a -/// linear congruential generator on it and stores it. Compiled from this GLSL with glslang -/// (`--target-env vulkan1.0`, debug names stripped): -/// -/// ```glsl -/// #version 450 -/// layout(local_size_x = 64) in; -/// layout(std430, set = 0, binding = 0) buffer Words { uint words[]; }; -/// layout(push_constant) uniform Push { uint rounds; }; -/// void main() { -/// uint i = gl_GlobalInvocationID.x; -/// uint v = words[i]; -/// for (uint k = 0u; k < rounds; k++) { -/// v = v * 1664525u + 1013904223u; -/// } -/// words[i] = v; -/// } -/// ``` -#[rustfmt::skip] -const LOAD_SPIRV: [u32; 309] = [ - 0x07230203, 0x00010000, 0x0008000b, 0x00000038, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, - 0x00000011, 0x00000040, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001c, - 0x00040047, 0x00000011, 0x00000006, 0x00000004, 0x00030047, 0x00000012, 0x00000003, 0x00050048, - 0x00000012, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000014, 0x00000021, 0x00000000, - 0x00040047, 0x00000014, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, 0x00050048, - 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000037, 0x0000000b, 0x00000019, - 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, - 0x00000000, 0x00040020, 0x00000007, 0x00000007, 0x00000006, 0x00040017, 0x00000009, 0x00000006, - 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, - 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, 0x0000000d, 0x00000001, - 0x00000006, 0x0003001d, 0x00000011, 0x00000006, 0x0003001e, 0x00000012, 0x00000011, 0x00040020, - 0x00000013, 0x00000002, 0x00000012, 0x0004003b, 0x00000013, 0x00000014, 0x00000002, 0x00040015, - 0x00000015, 0x00000020, 0x00000001, 0x0004002b, 0x00000015, 0x00000016, 0x00000000, 0x00040020, - 0x00000018, 0x00000002, 0x00000006, 0x0003001e, 0x00000022, 0x00000006, 0x00040020, 0x00000023, - 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, 0x00040020, 0x00000025, - 0x00000009, 0x00000006, 0x00020014, 0x00000028, 0x0004002b, 0x00000006, 0x0000002b, 0x0019660d, - 0x0004002b, 0x00000006, 0x0000002d, 0x3c6ef35f, 0x0004002b, 0x00000015, 0x00000030, 0x00000001, - 0x0004002b, 0x00000006, 0x00000035, 0x00000040, 0x0004002b, 0x00000006, 0x00000036, 0x00000001, - 0x0006002c, 0x00000009, 0x00000037, 0x00000035, 0x00000036, 0x00000036, 0x00050036, 0x00000002, - 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003b, 0x00000007, 0x00000008, - 0x00000007, 0x0004003b, 0x00000007, 0x00000010, 0x00000007, 0x0004003b, 0x00000007, 0x0000001b, - 0x00000007, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, - 0x0000000f, 0x0000000e, 0x0003003e, 0x00000008, 0x0000000f, 0x0004003d, 0x00000006, 0x00000017, - 0x00000008, 0x00060041, 0x00000018, 0x00000019, 0x00000014, 0x00000016, 0x00000017, 0x0004003d, - 0x00000006, 0x0000001a, 0x00000019, 0x0003003e, 0x00000010, 0x0000001a, 0x0003003e, 0x0000001b, - 0x0000000c, 0x000200f9, 0x0000001c, 0x000200f8, 0x0000001c, 0x000400f6, 0x0000001e, 0x0000001f, - 0x00000000, 0x000200f9, 0x00000020, 0x000200f8, 0x00000020, 0x0004003d, 0x00000006, 0x00000021, - 0x0000001b, 0x00050041, 0x00000025, 0x00000026, 0x00000024, 0x00000016, 0x0004003d, 0x00000006, - 0x00000027, 0x00000026, 0x000500b0, 0x00000028, 0x00000029, 0x00000021, 0x00000027, 0x000400fa, - 0x00000029, 0x0000001d, 0x0000001e, 0x000200f8, 0x0000001d, 0x0004003d, 0x00000006, 0x0000002a, - 0x00000010, 0x00050084, 0x00000006, 0x0000002c, 0x0000002a, 0x0000002b, 0x00050080, 0x00000006, - 0x0000002e, 0x0000002c, 0x0000002d, 0x0003003e, 0x00000010, 0x0000002e, 0x000200f9, 0x0000001f, - 0x000200f8, 0x0000001f, 0x0004003d, 0x00000006, 0x0000002f, 0x0000001b, 0x00050080, 0x00000006, - 0x00000031, 0x0000002f, 0x00000030, 0x0003003e, 0x0000001b, 0x00000031, 0x000200f9, 0x0000001c, - 0x000200f8, 0x0000001e, 0x0004003d, 0x00000006, 0x00000032, 0x00000008, 0x0004003d, 0x00000006, - 0x00000033, 0x00000010, 0x00060041, 0x00000018, 0x00000034, 0x00000014, 0x00000016, 0x00000032, - 0x0003003e, 0x00000034, 0x00000033, 0x000100fd, 0x00010038, -]; - -/// Where a copy runs. -#[derive(Clone, Copy, PartialEq)] -enum On { - /// The graphics family's first queue. - Graphics, - /// The other family's queue: transfers alone, or compute work. - Other, -} - -/// What a copy moves between. -#[derive(Clone, Copy)] -enum Kind { - Image, - Buffer, -} - -/// Which way a copy goes. -#[derive(Clone, Copy)] -enum Way { - /// Host memory into device memory. - Up, - /// Device memory into host memory. - Down, -} - -/// A queue and the command pool of its family, for the main thread. -struct Lane { - family: u32, - queue: vk::Queue, - pool: vk::CommandPool, - /// The family writes timestamps. - timed: bool, - label: &'static str, -} - -/// The test's own device and its objects. -struct Bench { - _entry: ash::Entry, - instance: ash::Instance, - device: ash::Device, - graphics: Lane, - other: Option, - /// The graphics family's second queue, where the load runs. - load_queue: Option, - /// Nanoseconds a timestamp tick. - period: f64, - host: (vk::Buffer, vk::DeviceMemory), - device_buffer: (vk::Buffer, vk::DeviceMemory), - image: (vk::Image, vk::DeviceMemory), - load_buffer: (vk::Buffer, vk::DeviceMemory), - descriptors: vk::DescriptorPool, - set_layout: vk::DescriptorSetLayout, - /// The load buffer's set, and the device buffer's (the handoffs' dispatch). - load_set: vk::DescriptorSet, - device_set: vk::DescriptorSet, - layout: vk::PipelineLayout, - pipeline: vk::Pipeline, - queries: vk::QueryPool, - timeline: vk::Semaphore, - /// The timeline's last value signaled. - value: u64, -} - -/// Unix milliseconds now, on the host's clock. -fn unix_ms() -> u128 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |since| since.as_millis()) -} - -/// The 50th and 90th percentiles of `values`, nearest rank. -fn percentiles(mut values: Vec) -> [f64; 2] { - if values.is_empty() { - return [f64::NAN; 2]; - } - values.sort_by(f64::total_cmp); - let at = |p: usize| values[((values.len() * p).div_ceil(100)).clamp(1, values.len()) - 1]; - [at(50), at(90)] -} - -/// The first memory type of `types` that `bits` admits, holds `wanted` and none of `unwanted`, -/// preferring one that also holds `preferred`. -fn memory_type( - types: &[vk::MemoryType], - bits: u32, - wanted: vk::MemoryPropertyFlags, - unwanted: vk::MemoryPropertyFlags, - preferred: vk::MemoryPropertyFlags, -) -> Option { - let fits = |index: usize| { - bits & (1 << index) != 0 - && types[index].property_flags.contains(wanted) - && !types[index].property_flags.intersects(unwanted) - }; - let all = 0..types.len(); - (all.clone()) - .find(|&index| fits(index) && types[index].property_flags.contains(preferred)) - .or_else(|| all.clone().find(|&index| fits(index))) - .map(|index| index as u32) -} - -impl Bench { - fn new() -> Bench { - // SAFETY: loading the Vulkan loader runs its initialization; nothing else is assumed. - let entry = unsafe { ash::Entry::load() }.expect("the Vulkan loader"); - // SAFETY: a global command of a loaded entry. - let listed = unsafe { entry.enumerate_instance_extension_properties(None) }.unwrap(); - let portability = listed.iter().any(|extension| { - extension.extension_name_as_c_str() == Ok(ash::khr::portability_enumeration::NAME) - }); - let extensions: Vec<*const std::ffi::c_char> = match portability { - true => vec![ash::khr::portability_enumeration::NAME.as_ptr()], - false => Vec::new(), - }; - let application = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_2); - let info = vk::InstanceCreateInfo::default() - .application_info(&application) - .enabled_extension_names(&extensions) - .flags(match portability { - true => vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR, - false => vk::InstanceCreateFlags::empty(), - }); - // SAFETY: `info` and what it points at live for the call. - let instance = unsafe { entry.create_instance(&info, None) }.unwrap(); - // SAFETY: the instance is live. - let physicals = unsafe { instance.enumerate_physical_devices() }.unwrap(); - let types = [ - vk::PhysicalDeviceType::DISCRETE_GPU, - vk::PhysicalDeviceType::INTEGRATED_GPU, - vk::PhysicalDeviceType::VIRTUAL_GPU, - vk::PhysicalDeviceType::CPU, - ]; - // SAFETY: each is the instance's. - let kind = |physical: vk::PhysicalDevice| unsafe { - instance - .get_physical_device_properties(physical) - .device_type - }; - let physical = (types.iter()) - .find_map(|&wanted| physicals.iter().copied().find(|&p| kind(p) == wanted)) - .expect("a device"); - let mut driver = vk::PhysicalDeviceDriverProperties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut driver); - // SAFETY: the instance's; Vulkan 1.1's command. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - let properties = properties.properties; - let name = (properties.device_name_as_c_str()) - .map_or("?".to_owned(), |name| name.to_string_lossy().into_owned()); - let driver_info = (driver.driver_info_as_c_str()) - .map_or("?".to_owned(), |info| info.to_string_lossy().into_owned()); - // SAFETY: the instance's. - let families = unsafe { instance.get_physical_device_queue_family_properties(physical) }; - let wanted = vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE; - let graphics = (families.iter()) - .position(|family| family.queue_flags.contains(wanted) && family.queue_count > 0) - .expect("a family of graphics and compute work") as u32; - let unit = vk::Extent3D { - width: 1, - height: 1, - depth: 1, - }; - let besides = - vk::QueueFlags::TRANSFER | vk::QueueFlags::SPARSE_BINDING | vk::QueueFlags::PROTECTED; - let other_of = |test: &dyn Fn(vk::QueueFlags) -> bool| { - (families.iter().enumerate()).position(|(index, family)| { - index as u32 != graphics - && family.queue_count > 0 - && family.min_image_transfer_granularity == unit - && test(family.queue_flags) - }) - }; - let copy = other_of(&|flags| { - flags.contains(vk::QueueFlags::TRANSFER) && (flags & !besides).is_empty() - }); - let compute = other_of(&|flags| flags.contains(vk::QueueFlags::COMPUTE)); - let other = (copy.map(|family| (family as u32, "copy"))) - .or(compute.map(|family| (family as u32, "compute"))); - for (index, family) in families.iter().enumerate() { - println!( - "COPY-ENGINE family {index} flags {:#x} queues {} timestamp bits {} granularity {}x{}x{}", - family.queue_flags.as_raw(), - family.queue_count, - family.timestamp_valid_bits, - family.min_image_transfer_granularity.width, - family.min_image_transfer_granularity.height, - family.min_image_transfer_granularity.depth, - ); - } - let graphics_queues = families[graphics as usize].queue_count.min(2); - let priorities = [1.0, 1.0]; - let mut queue_infos = vec![vk::DeviceQueueCreateInfo::default() - .queue_family_index(graphics) - .queue_priorities(&priorities[..graphics_queues as usize])]; - if let Some((family, _)) = other { - queue_infos.push( - vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities[..1]), - ); - } - let mut features = vk::PhysicalDeviceVulkan12Features::default() - .timeline_semaphore(true) - .host_query_reset(true); - let info = vk::DeviceCreateInfo::default() - .queue_create_infos(&queue_infos) - .push_next(&mut features); - // SAFETY: `info` and what it points at live for the call. - let device = unsafe { instance.create_device(physical, &info, None) }.unwrap(); - let lane = |family: u32, index: u32, label: &'static str| { - // SAFETY: the family and index were created; `info` is valid. - let (queue, pool) = unsafe { - ( - device.get_device_queue(family, index), - device - .create_command_pool( - &vk::CommandPoolCreateInfo::default() - .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER) - .queue_family_index(family), - None, - ) - .unwrap(), - ) - }; - Lane { - family, - queue, - pool, - timed: families[family as usize].timestamp_valid_bits > 0, - label, - } - }; - let graphics_lane = lane(graphics, 0, "graphics"); - let other_lane = other.map(|(family, label)| lane(family, 0, label)); - let load_queue = (graphics_queues > 1).then(|| { - // SAFETY: the family's second queue was created. - unsafe { device.get_device_queue(graphics, 1) } - }); - // SAFETY: the instance's. - let memory = unsafe { instance.get_physical_device_memory_properties(physical) }; - let memory_types = &memory.memory_types[..memory.memory_type_count as usize]; - let shared: Vec = std::iter::once(graphics) - .chain(other.map(|(family, _)| family)) - .collect(); - let usage = vk::BufferUsageFlags::TRANSFER_SRC - | vk::BufferUsageFlags::TRANSFER_DST - | vk::BufferUsageFlags::STORAGE_BUFFER; - let host_flags = - vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; - let buffer = |size: u64, host: bool| { - let info = vk::BufferCreateInfo::default().size(size).usage(usage); - let info = match shared.len() > 1 { - true => info - .sharing_mode(vk::SharingMode::CONCURRENT) - .queue_family_indices(&shared), - false => info.sharing_mode(vk::SharingMode::EXCLUSIVE), - }; - // SAFETY: the device is live and `info` valid. - let buffer = unsafe { device.create_buffer(&info, None) }.unwrap(); - // SAFETY: the buffer is the device's. - let needs = unsafe { device.get_buffer_memory_requirements(buffer) }; - let index = match host { - // The host's own memory, which the device reaches across the bus where it has its - // own. - true => memory_type( - memory_types, - needs.memory_type_bits, - host_flags, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - vk::MemoryPropertyFlags::HOST_CACHED, - ) - .or_else(|| { - memory_type( - memory_types, - needs.memory_type_bits, - host_flags, - vk::MemoryPropertyFlags::empty(), - vk::MemoryPropertyFlags::HOST_CACHED, - ) - }), - false => memory_type( - memory_types, - needs.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - vk::MemoryPropertyFlags::HOST_VISIBLE, - vk::MemoryPropertyFlags::empty(), - ) - .or_else(|| { - memory_type( - memory_types, - needs.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - vk::MemoryPropertyFlags::empty(), - vk::MemoryPropertyFlags::empty(), - ) - }), - } - .expect("a memory type for the buffer"); - println!( - "COPY-ENGINE {} buffer memory type {index} flags {:#x} heap {}", - if host { "host" } else { "device" }, - memory_types[index as usize].property_flags.as_raw(), - memory_types[index as usize].heap_index, - ); - let allocate = vk::MemoryAllocateInfo::default() - .allocation_size(needs.size) - .memory_type_index(index); - // SAFETY: as above; the memory is bound once, at offset 0. - unsafe { - let memory = device.allocate_memory(&allocate, None).unwrap(); - device.bind_buffer_memory(buffer, memory, 0).unwrap(); - (buffer, memory) - } - }; - let host = buffer(MOST, true); - let device_buffer = buffer(MOST, false); - let load_buffer = buffer(LOAD_WORDS * 4, false); - let image_info = vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(vk::Format::R8G8B8A8_UNORM) - .extent(vk::Extent3D { - width: WIDTH, - height: (MOST / ROW) as u32, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::OPTIMAL) - .usage( - vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST - | vk::ImageUsageFlags::SAMPLED, - ) - .initial_layout(vk::ImageLayout::UNDEFINED); - let image_info = match shared.len() > 1 { - true => image_info - .sharing_mode(vk::SharingMode::CONCURRENT) - .queue_family_indices(&shared), - false => image_info.sharing_mode(vk::SharingMode::EXCLUSIVE), - }; - // SAFETY: the device is live and every info valid. - let image = unsafe { - let image = device.create_image(&image_info, None).unwrap(); - let needs = device.get_image_memory_requirements(image); - let index = memory_type( - memory_types, - needs.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - vk::MemoryPropertyFlags::empty(), - vk::MemoryPropertyFlags::empty(), - ) - .expect("a device-local type for the image"); - let memory = device - .allocate_memory( - &vk::MemoryAllocateInfo::default() - .allocation_size(needs.size) - .memory_type_index(index), - None, - ) - .unwrap(); - device.bind_image_memory(image, memory, 0).unwrap(); - (image, memory) - }; - let bindings = [vk::DescriptorSetLayoutBinding::default() - .binding(0) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .descriptor_count(1) - .stage_flags(vk::ShaderStageFlags::COMPUTE)]; - let push = [vk::PushConstantRange::default() - .stage_flags(vk::ShaderStageFlags::COMPUTE) - .offset(0) - .size(4)]; - let sizes = [vk::DescriptorPoolSize::default() - .ty(vk::DescriptorType::STORAGE_BUFFER) - .descriptor_count(2)]; - // SAFETY: the device is live and every info valid. - let (set_layout, layout, pipeline, descriptors, load_set, device_set) = unsafe { - let set_layout = device - .create_descriptor_set_layout( - &vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings), - None, - ) - .unwrap(); - let layouts = [set_layout]; - let layout = device - .create_pipeline_layout( - &vk::PipelineLayoutCreateInfo::default() - .set_layouts(&layouts) - .push_constant_ranges(&push), - None, - ) - .unwrap(); - let module = device - .create_shader_module( - &vk::ShaderModuleCreateInfo::default().code(&LOAD_SPIRV), - None, - ) - .unwrap(); - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(module) - .name(c"main"); - let pipeline = device - .create_compute_pipelines( - vk::PipelineCache::null(), - &[vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(layout)], - None, - ) - .map_err(|(_, error)| error) - .unwrap()[0]; - device.destroy_shader_module(module, None); - let descriptors = device - .create_descriptor_pool( - &vk::DescriptorPoolCreateInfo::default() - .max_sets(2) - .pool_sizes(&sizes), - None, - ) - .unwrap(); - let both = [set_layout, set_layout]; - let sets = device - .allocate_descriptor_sets( - &vk::DescriptorSetAllocateInfo::default() - .descriptor_pool(descriptors) - .set_layouts(&both), - ) - .unwrap(); - for (set, buffer) in [(sets[0], load_buffer.0), (sets[1], device_buffer.0)] { - let infos = [vk::DescriptorBufferInfo::default() - .buffer(buffer) - .offset(0) - .range(vk::WHOLE_SIZE)]; - let write = vk::WriteDescriptorSet::default() - .dst_set(set) - .dst_binding(0) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .buffer_info(&infos); - device.update_descriptor_sets(&[write], &[]); - } - (set_layout, layout, pipeline, descriptors, sets[0], sets[1]) - }; - let mut kind = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - // SAFETY: the device is live and every info valid. - let (queries, timeline) = unsafe { - ( - device - .create_query_pool( - &vk::QueryPoolCreateInfo::default() - .query_type(vk::QueryType::TIMESTAMP) - .query_count(2), - None, - ) - .unwrap(), - device - .create_semaphore( - &vk::SemaphoreCreateInfo::default().push_next(&mut kind), - None, - ) - .unwrap(), - ) - }; - println!( - "COPY-ENGINE device {name} driver {} {driver_info} graphics family {graphics} ({} queues) other {}", - driver.driver_id.as_raw(), - graphics_queues, - match other { - Some((family, label)) => format!("{label} family {family}"), - None => "none".to_owned(), - }, - ); - let mut bench = Bench { - _entry: entry, - instance, - device, - graphics: graphics_lane, - other: other_lane, - load_queue, - period: f64::from(properties.limits.timestamp_period), - host, - device_buffer, - image, - load_buffer, - descriptors, - set_layout, - load_set, - device_set, - layout, - pipeline, - queries, - timeline, - value: 0, - }; - // The image rests in GENERAL, as the runtime's do. - bench.run(On::Graphics, |device, command| { - let barrier = vk::ImageMemoryBarrier::default() - .src_access_mask(vk::AccessFlags::empty()) - .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE) - .old_layout(vk::ImageLayout::UNDEFINED) - .new_layout(vk::ImageLayout::GENERAL) - .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .image(image.0) - .subresource_range(color_range()); - // SAFETY: recording. - unsafe { - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::TOP_OF_PIPE, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::DependencyFlags::empty(), - &[], - &[], - &[barrier], - ) - }; - }); - bench - } - - fn lane(&self, on: On) -> &Lane { - match on { - On::Graphics => &self.graphics, - On::Other => self.other.as_ref().expect("another family's queue"), - } - } - - /// A new primary command buffer of `on`'s pool. - fn command(&self, on: On) -> vk::CommandBuffer { - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(self.lane(on).pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - // SAFETY: the pool is the device's, used by this thread alone. - unsafe { self.device.allocate_command_buffers(&allocate) }.unwrap()[0] - } - - /// Record `record` into a new command buffer of `on`, submit it and wait for it. - fn run(&mut self, on: On, record: impl FnOnce(&ash::Device, vk::CommandBuffer)) { - let command = self.command(on); - // SAFETY: a new command buffer, recorded here alone. - unsafe { - self.device - .begin_command_buffer(command, &vk::CommandBufferBeginInfo::default()) - .unwrap(); - record(&self.device, command); - self.device.end_command_buffer(command).unwrap(); - } - self.submit(on, command, None); - self.wait(); - // SAFETY: the command buffer completed. - unsafe { - (self.device).free_command_buffers(self.lane(on).pool, &[command]); - } - } - - /// Submit `command` on `on`'s queue, waiting first for the timeline's `wait` (at every stage) - /// where given; it signals the timeline's next value. - fn submit(&mut self, on: On, command: vk::CommandBuffer, wait: Option) { - self.value += 1; - let waits: Vec = wait.into_iter().collect(); - let wait_semaphores = vec![self.timeline; waits.len()]; - let stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; waits.len()]; - let signals = [self.value]; - let mut values = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&waits) - .signal_semaphore_values(&signals); - let commands = [command]; - let semaphores = [self.timeline]; - let submit = vk::SubmitInfo::default() - .wait_semaphores(&wait_semaphores) - .wait_dst_stage_mask(&stages) - .command_buffers(&commands) - .signal_semaphores(&semaphores) - .push_next(&mut values); - // SAFETY: the queue is used by this thread alone; the command buffer is executable and - // not pending; the signal is above the timeline's value. - unsafe { - (self.device) - .queue_submit(self.lane(on).queue, &[submit], vk::Fence::null()) - .unwrap() - }; - } - - /// Wait on the host for the timeline's last value signaled. - fn wait(&self) { - let semaphores = [self.timeline]; - let values = [self.value]; - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&semaphores) - .values(&values); - // SAFETY: the semaphore is the device's. - unsafe { self.device.wait_semaphores(&info, TIMEOUT) }.unwrap(); - } - - /// A command buffer of `on` that moves `bytes` `way` between host memory and the image or - /// device buffer (`kind`), timed by the query pool's two timestamps where the family writes - /// them. - fn copy_command(&self, on: On, kind: Kind, way: Way, bytes: u64) -> vk::CommandBuffer { - let command = self.command(on); - let timed = self.lane(on).timed; - let device = &self.device; - let all = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::MEMORY_WRITE) - .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE); - let to_host = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::MEMORY_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ); - let region = vk::BufferImageCopy::default() - .image_subresource( - vk::ImageSubresourceLayers::default() - .aspect_mask(vk::ImageAspectFlags::COLOR) - .layer_count(1), - ) - .image_extent(vk::Extent3D { - width: WIDTH, - height: (bytes / ROW) as u32, - depth: 1, - }); - let range = vk::BufferCopy::default().size(bytes); - // SAFETY: a new command buffer, recorded here alone; every object is the device's. - unsafe { - device - .begin_command_buffer(command, &vk::CommandBufferBeginInfo::default()) - .unwrap(); - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::DependencyFlags::empty(), - &[all], - &[], - &[], - ); - if timed { - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::TOP_OF_PIPE, - self.queries, - 0, - ); - } - match (kind, way) { - (Kind::Image, Way::Up) => device.cmd_copy_buffer_to_image( - command, - self.host.0, - self.image.0, - vk::ImageLayout::GENERAL, - &[region], - ), - (Kind::Image, Way::Down) => device.cmd_copy_image_to_buffer( - command, - self.image.0, - vk::ImageLayout::GENERAL, - self.host.0, - &[region], - ), - (Kind::Buffer, Way::Up) => { - device.cmd_copy_buffer(command, self.host.0, self.device_buffer.0, &[range]) - } - (Kind::Buffer, Way::Down) => { - device.cmd_copy_buffer(command, self.device_buffer.0, self.host.0, &[range]) - } - } - if timed { - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - self.queries, - 1, - ); - } - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::PipelineStageFlags::HOST, - vk::DependencyFlags::empty(), - &[to_host], - &[], - &[], - ); - device.end_command_buffer(command).unwrap(); - } - command - } - - /// The query pool's two timestamps apart, in milliseconds. - fn gpu_ms(&self) -> f64 { - let mut ticks = [0u64; 2]; - // SAFETY: both queries were written by a submission the host saw complete. - unsafe { - self.device.get_query_pool_results( - self.queries, - 0, - &mut ticks, - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, - ) - } - .unwrap(); - ticks[1].wrapping_sub(ticks[0]) as f64 * self.period / 1e6 - } - - /// Copies of `bytes` `way` on `on`, one submission waited for at a time, for `span` and at - /// least [`LEAST`] of them: their GPU and wall times in milliseconds. - fn copies(&mut self, on: On, kind: Kind, way: Way, bytes: u64, span: Duration) -> Phase { - let command = self.copy_command(on, kind, way, bytes); - let timed = self.lane(on).timed; - let from = unix_ms(); - let began = Instant::now(); - let (mut gpu, mut wall) = (Vec::new(), Vec::new()); - while began.elapsed() < span || wall.len() < LEAST { - // SAFETY: the queries are not in use: the last submission completed. - unsafe { self.device.reset_query_pool(self.queries, 0, 2) }; - let start = Instant::now(); - self.submit(on, command, None); - self.wait(); - wall.push(start.elapsed().as_secs_f64() * 1e3); - if timed { - gpu.push(self.gpu_ms()); - } - } - let to = unix_ms(); - // SAFETY: the command buffer completed. - unsafe { (self.device).free_command_buffers(self.lane(on).pool, &[command]) }; - Phase { - from, - to, - gpu, - wall, - } - } - - /// A command buffer of the graphics queue that dispatches the load kernel once over the - /// device buffer's first workgroup (`rounds` 0), after a copy into it where `copy` (bytes) - /// is given, with a barrier between. - fn dispatch_command(&self, copy: Option) -> vk::CommandBuffer { - let command = self.command(On::Graphics); - let device = &self.device; - // SAFETY: a new command buffer, recorded here alone; every object is the device's. - unsafe { - device - .begin_command_buffer(command, &vk::CommandBufferBeginInfo::default()) - .unwrap(); - if let Some(bytes) = copy { - let range = vk::BufferCopy::default().size(bytes); - device.cmd_copy_buffer(command, self.host.0, self.device_buffer.0, &[range]); - let after = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE); - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::TRANSFER, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::DependencyFlags::empty(), - &[after], - &[], - &[], - ); - } - device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, self.pipeline); - device.cmd_bind_descriptor_sets( - command, - vk::PipelineBindPoint::COMPUTE, - self.layout, - 0, - &[self.device_set], - &[], - ); - device.cmd_push_constants( - command, - self.layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &0u32.to_ne_bytes(), - ); - device.cmd_dispatch(command, 1, 1, 1); - device.end_command_buffer(command).unwrap(); - } - command - } - - /// Handoffs of `bytes` (the module docs), for [`SMALL_SPAN`] and at least [`LEAST`]: on the - /// graphics queue alone, or the copy on the other queue: their wall times in milliseconds. - fn handoffs(&mut self, on: On, bytes: u64) -> Phase { - let (first, then) = match on { - On::Graphics => (self.dispatch_command(Some(bytes)), None), - On::Other => { - let copy = self.command(On::Other); - let range = vk::BufferCopy::default().size(bytes); - // SAFETY: a new command buffer, recorded here alone. - unsafe { - (self.device) - .begin_command_buffer(copy, &vk::CommandBufferBeginInfo::default()) - .unwrap(); - (self.device).cmd_copy_buffer( - copy, - self.host.0, - self.device_buffer.0, - &[range], - ); - self.device.end_command_buffer(copy).unwrap(); - } - (copy, Some(self.dispatch_command(None))) - } - }; - let from = unix_ms(); - let began = Instant::now(); - let mut wall = Vec::new(); - while began.elapsed() < SMALL_SPAN || wall.len() < LEAST { - let start = Instant::now(); - self.submit(on, first, None); - if let Some(dispatch) = then { - // The semaphore's signal and wait order the copy's writes before the dispatch: - // the buffer is concurrent between the two families, so no ownership moves. - let copied = self.value; - self.submit(On::Graphics, dispatch, Some(copied)); - } - self.wait(); - wall.push(start.elapsed().as_secs_f64() * 1e3); - } - let to = unix_ms(); - // SAFETY: every submission completed. - unsafe { - (self.device).free_command_buffers(self.lane(on).pool, &[first]); - if let Some(dispatch) = then { - (self.device).free_command_buffers(self.graphics.pool, &[dispatch]); - } - } - Phase { - from, - to, - gpu: Vec::new(), - wall, - } - } - - /// The load's rounds for a dispatch of about [`LOAD_MS`], and the dispatch's GPU time then, - /// measured on the graphics queue alone. - fn calibrate(&mut self) -> (u32, f64) { - let groups = (LOAD_WORDS / 64) as u32; - let time = |bench: &mut Bench, rounds: u32| { - let (queries, layout, pipeline, set) = - (bench.queries, bench.layout, bench.pipeline, bench.load_set); - // SAFETY: the queries are not in use. - unsafe { bench.device.reset_query_pool(queries, 0, 2) }; - bench.run(On::Graphics, |device, command| { - // SAFETY: recording. - unsafe { - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::TOP_OF_PIPE, - queries, - 0, - ); - record_load(device, command, (pipeline, layout, set), groups, rounds); - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - queries, - 1, - ); - } - }); - bench.gpu_ms() - }; - let probe = 256; - let ms = time(self, probe).max(0.01); - let rounds = ((f64::from(probe) * LOAD_MS / ms) as u32).clamp(1, 1 << 22); - let ms = time(self, rounds); - (rounds, ms) - } -} - -/// The color aspect's one level and layer. -fn color_range() -> vk::ImageSubresourceRange { - vk::ImageSubresourceRange::default() - .aspect_mask(vk::ImageAspectFlags::COLOR) - .level_count(1) - .layer_count(1) -} - -/// Record one dispatch of the load kernel of `groups` workgroups and `rounds` rounds over `set`. -/// -/// # Safety -/// -/// `command` is recording, of a family of compute work; the objects are its device's. -unsafe fn record_load( - device: &ash::Device, - command: vk::CommandBuffer, - (pipeline, layout, set): (vk::Pipeline, vk::PipelineLayout, vk::DescriptorSet), - groups: u32, - rounds: u32, -) { - // SAFETY: the caller's contract. - unsafe { - device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, pipeline); - device.cmd_bind_descriptor_sets( - command, - vk::PipelineBindPoint::COMPUTE, - layout, - 0, - &[set], - &[], - ); - device.cmd_push_constants( - command, - layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &rounds.to_ne_bytes(), - ); - device.cmd_dispatch(command, groups, 1, 1); - } -} - -/// A phase's span and times. -struct Phase { - from: u128, - to: u128, - gpu: Vec, - wall: Vec, -} - -impl Phase { - fn line(&self, bytes: u64) -> String { - let [gpu50, gpu90] = percentiles(self.gpu.clone()); - let [wall50, wall90] = percentiles(self.wall.clone()); - let rate = bytes as f64 / (gpu50 * 1e6); - format!( - "n {} gpu_ms p50 {gpu50:.3} p90 {gpu90:.3} wall_ms p50 {wall50:.3} p90 {wall90:.3} \ - gpu_GB/s {rate:.2} from {} to {}", - self.wall.len(), - self.from, - self.to, - ) - } -} - -/// The load running on the graphics family's second queue, two dispatches in flight, until it is -/// stopped: the dispatches it completed, and their GPU time in nanoseconds. -struct Load { - stop: Arc, - done: Arc, - busy: Arc, - thread: Option>, -} - -impl Load { - fn start(bench: &Bench, queue: vk::Queue, rounds: u32) -> Load { - let stop = Arc::new(AtomicBool::new(false)); - let done = Arc::new(AtomicU64::new(0)); - let busy = Arc::new(AtomicU64::new(0)); - let device = bench.device.clone(); - let family = bench.graphics.family; - let objects = (bench.pipeline, bench.layout, bench.load_set); - let period = bench.period; - let (thread_stop, thread_done, thread_busy) = (stop.clone(), done.clone(), busy.clone()); - let thread = std::thread::spawn(move || { - let groups = (LOAD_WORDS / 64) as u32; - let mut kind = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - // SAFETY: the device is live; every object here is this thread's alone, and the - // queue is used by it alone. - unsafe { - let pool = device - .create_command_pool( - &vk::CommandPoolCreateInfo::default().queue_family_index(family), - None, - ) - .unwrap(); - let commands = device - .allocate_command_buffers( - &vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(2), - ) - .unwrap(); - let queries = device - .create_query_pool( - &vk::QueryPoolCreateInfo::default() - .query_type(vk::QueryType::TIMESTAMP) - .query_count(4), - None, - ) - .unwrap(); - let timeline = device - .create_semaphore( - &vk::SemaphoreCreateInfo::default().push_next(&mut kind), - None, - ) - .unwrap(); - for (slot, &command) in commands.iter().enumerate() { - let first = 2 * slot as u32; - device - .begin_command_buffer(command, &vk::CommandBufferBeginInfo::default()) - .unwrap(); - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::TOP_OF_PIPE, - queries, - first, - ); - record_load(&device, command, objects, groups, rounds); - device.cmd_write_timestamp( - command, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - queries, - first + 1, - ); - device.end_command_buffer(command).unwrap(); - } - let mut submitted = [0u64; 2]; - let mut value = 0u64; - let mut slot = 0; - while !thread_stop.load(Ordering::Relaxed) { - let first = 2 * slot as u32; - if submitted[slot] > 0 { - let semaphores = [timeline]; - let values = [submitted[slot]]; - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&semaphores) - .values(&values); - device.wait_semaphores(&info, TIMEOUT).unwrap(); - let mut ticks = [0u64; 2]; - device - .get_query_pool_results( - queries, - first, - &mut ticks, - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, - ) - .unwrap(); - let ns = ticks[1].wrapping_sub(ticks[0]) as f64 * period; - thread_busy.fetch_add(ns as u64, Ordering::Relaxed); - thread_done.fetch_add(1, Ordering::Relaxed); - } - device.reset_query_pool(queries, first, 2); - value += 1; - let signals = [value]; - let mut values = vk::TimelineSemaphoreSubmitInfo::default() - .signal_semaphore_values(&signals); - let buffers = [commands[slot]]; - let semaphores = [timeline]; - let submit = vk::SubmitInfo::default() - .command_buffers(&buffers) - .signal_semaphores(&semaphores) - .push_next(&mut values); - device - .queue_submit(queue, &[submit], vk::Fence::null()) - .unwrap(); - submitted[slot] = value; - slot = 1 - slot; - } - let semaphores = [timeline]; - let values = [value]; - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&semaphores) - .values(&values); - device.wait_semaphores(&info, TIMEOUT).unwrap(); - device.destroy_semaphore(timeline, None); - device.destroy_query_pool(queries, None); - device.destroy_command_pool(pool, None); - } - }); - Load { - stop, - done, - busy, - thread: Some(thread), - } - } - - /// The dispatches completed so far and their GPU time in nanoseconds. - fn read(&self) -> (u64, u64) { - ( - self.done.load(Ordering::Relaxed), - self.busy.load(Ordering::Relaxed), - ) - } -} - -impl Drop for Load { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - thread.join().unwrap(); - } - } -} - -/// The load's rate over a span: dispatches a second, and the GPU time a dispatch in -/// milliseconds. -fn load_rate(before: (u64, u64), after: (u64, u64), seconds: f64) -> (f64, f64) { - let count = after.0 - before.0; - let busy = (after.1 - before.1) as f64 / 1e6; - (count as f64 / seconds, busy / count.max(1) as f64) -} - -impl Drop for Bench { - fn drop(&mut self) { - // SAFETY: nothing is pending (every submission was waited for, the load thread joined); - // each object is destroyed once. - unsafe { - let device = &self.device; - device.device_wait_idle().unwrap(); - device.destroy_semaphore(self.timeline, None); - device.destroy_query_pool(self.queries, None); - device.destroy_pipeline(self.pipeline, None); - device.destroy_pipeline_layout(self.layout, None); - device.destroy_descriptor_pool(self.descriptors, None); - device.destroy_descriptor_set_layout(self.set_layout, None); - device.destroy_image(self.image.0, None); - device.free_memory(self.image.1, None); - for (buffer, memory) in [self.host, self.device_buffer, self.load_buffer] { - device.destroy_buffer(buffer, None); - device.free_memory(memory, None); - } - device.destroy_command_pool(self.graphics.pool, None); - if let Some(other) = &self.other { - device.destroy_command_pool(other.pool, None); - } - device.destroy_device(None); - self.instance.destroy_instance(None); - } - } -} - -fn name(kind: Kind, way: Way) -> &'static str { - match (kind, way) { - (Kind::Image, Way::Up) => "image up", - (Kind::Image, Way::Down) => "image down", - (Kind::Buffer, Way::Up) => "buffer up", - (Kind::Buffer, Way::Down) => "buffer down", - } -} - -fn main() { - let mut bench = Bench::new(); - // The bytes round trip exactly through the image on each queue: a pattern up, zeros over it - // on the host, and back down. - let check = 4 << 20; - let ons: Vec = std::iter::once(On::Graphics) - .chain(bench.other.as_ref().map(|_| On::Other)) - .collect(); - for &on in &ons { - // SAFETY: the host memory is host-visible and coherent, of `MOST` bytes, and no - // submission is pending. - unsafe { - let mapped = (bench.device) - .map_memory(bench.host.1, 0, check, vk::MemoryMapFlags::empty()) - .unwrap() as *mut u32; - let words = std::slice::from_raw_parts_mut(mapped, (check / 4) as usize); - for (i, word) in words.iter_mut().enumerate() { - *word = (i as u32).wrapping_mul(2654435761) ^ (on == On::Other) as u32; - } - bench.copies(on, Kind::Image, Way::Up, check, Duration::ZERO); - words.fill(0); - bench.copies(on, Kind::Image, Way::Down, check, Duration::ZERO); - let wrong = (words.iter().enumerate()) - .filter(|&(i, &word)| { - word != (i as u32).wrapping_mul(2654435761) ^ (on == On::Other) as u32 - }) - .count(); - (bench.device).unmap_memory(bench.host.1); - assert_eq!( - wrong, - 0, - "{} queue: words that did not round trip", - bench.lane(on).label - ); - } - } - for &bytes in &SMALL { - for kind in [Kind::Image, Kind::Buffer] { - for way in [Way::Up, Way::Down] { - for &on in &ons { - let phase = bench.copies(on, kind, way, bytes, SMALL_SPAN); - println!( - "COPY-ENGINE copy {} {} {bytes} load off {}", - bench.lane(on).label, - name(kind, way), - phase.line(bytes), - ); - } - } - } - } - for &bytes in &HANDOFF { - for &on in &ons { - let phase = bench.handoffs(on, bytes); - println!( - "COPY-ENGINE handoff {} {bytes} {}", - bench.lane(on).label, - phase.line(bytes), - ); - } - } - let (rounds, ms) = bench.calibrate(); - println!("COPY-ENGINE load rounds {rounds} dispatch_ms {ms:.2}"); - for &bytes in &LARGE { - for kind in [Kind::Image, Kind::Buffer] { - for way in [Way::Up, Way::Down] { - for &on in &ons { - let phase = bench.copies(on, kind, way, bytes, LARGE_SPAN); - println!( - "COPY-ENGINE copy {} {} {bytes} load off {}", - bench.lane(on).label, - name(kind, way), - phase.line(bytes), - ); - } - } - } - } - let Some(queue) = bench.load_queue else { - println!("COPY-ENGINE load none: the graphics family has one queue"); - return; - }; - let load = Load::start(&bench, queue, rounds); - let alone = |load: &Load, label: &str| { - let (from, before, began) = (unix_ms(), load.read(), Instant::now()); - std::thread::sleep(LARGE_SPAN); - let (rate, ms) = load_rate(before, load.read(), began.elapsed().as_secs_f64()); - println!( - "COPY-ENGINE load alone {label} rate {rate:.1}/s dispatch_ms {ms:.2} from {from} to {}", - unix_ms() - ); - rate - }; - let first = alone(&load, "first"); - for &bytes in &LARGE { - for kind in [Kind::Image, Kind::Buffer] { - for way in [Way::Up, Way::Down] { - for &on in &ons { - let (before, began) = (load.read(), Instant::now()); - let phase = bench.copies(on, kind, way, bytes, LARGE_SPAN); - let (rate, ms) = load_rate(before, load.read(), began.elapsed().as_secs_f64()); - println!( - "COPY-ENGINE copy {} {} {bytes} load on {} load_rate {rate:.1}/s \ - ({:.0}% of alone) load_dispatch_ms {ms:.2}", - bench.lane(on).label, - name(kind, way), - phase.line(bytes), - 100.0 * rate / first, - ); - } - } - } - } - alone(&load, "last"); -} diff --git a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs deleted file mode 100644 index 6d5fe340f..000000000 --- a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs +++ /dev/null @@ -1,2620 +0,0 @@ -//! Not a consumer's example: what a chain of dependent compute dispatches costs the GPU, by how a -//! command buffer holds them, beside the same chain recorded straight through Vulkan on a -//! `VkDevice` of the example's own, made on the runtime device's physical device. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example dispatch_chain -- \ -//! [--dispatches N] [--groups G] [--threads T] [--runs R] [--only SHAPE,...] \ -//! [--binds 1|4|tex|tex-moved|ptr|params|params-off] [--host C] [--pages] [--heap] [--heap-churn K] \ -//! [--heap-kept H] [--live L] [--idle MS] [--vary] [--ragged] [--samplers K] [--classes K] \ -//! [--zero-classes Z] [--stay Q] [--states K] [--back-to-back] [--encoding-threads E] \ -//! [--queue-each] [--spawned] [--settle MS] -//! ``` -//! -//! Each run is one command buffer of `N` dispatches (200 by default) of `G` threadgroups of `T` -//! threads (4096 of 32 by default) over one `Private` buffer of `G * T` words, each thread adding -//! 1 to its own word: every dispatch reads what the one before wrote. The shapes: -//! -//! - **`encoders`**: `N` compute encoders of one dispatch each, as a program that opens an encoder -//! for each dispatch records them; -//! - **`blits`**: `encoders` with a blit encoder after each compute encoder, which copies the -//! words into a `Private` buffer of their length, as an image workload copies between its -//! dispatches: `2N` encoders, each copy reading what the dispatch before it wrote and each -//! dispatch writing what the copy before it read. The copy's buffer is checked as the words are; -//! - **`copies`**: `N` blit encoders of that copy alone, no dispatch: what a program of blit -//! encoders alone costs (each line's "dispatch" is a copy). The copies' buffer must hold the -//! words' zeros; -//! - **`renders`**: `blits` with a render encoder between each compute encoder and its blit -//! encoder, which draws two triangles over the whole of a `Private` `RGBA8Unorm` target of -//! `TARGET_SIDE` texels a side, loaded and stored (a pass whose first instance records inline, -//! `render/inline_first.rs`), with `colored_vertex` and `colored_fragment` of the repository's -//! owned fixture (`validation/fixtures/public/examples/runtime_examples.ll`): `3N` encoders, as -//! an image workload that also draws between its dispatches and copies. Every texel of the -//! target must hold the triangles' color; -//! - **`renders-apart`**: `renders` with the target not loaded (`DontCare`), a pass recorded in a -//! secondary command buffer that the encoder's end executes; -//! - **`passes`**: `N` render encoders of that loaded pass alone, no dispatch and no copy: what a -//! program of render encoders alone costs (each line's "dispatch" is a pass). The words must -//! hold their zeros; -//! - **`serial`**: one serial compute encoder of the `N` dispatches; -//! - **`concurrent`**: one concurrent encoder of them, with no memory barrier: nothing orders the -//! dispatches, so this is the kernels' own time with no barrier between them (their words race, -//! which is not checked); -//! - **`barriers`**: one concurrent encoder of them with `memoryBarrierWithScope:` of buffers -//! between every two, as a program that orders a concurrent encoder's dispatches itself does; -//! - **`raw-barrier`**: one `VkCommandBuffer` of the `N` dispatches of the same work (a SPIR-V -//! kernel written here, assembled by `spirv-as`), each after one `VkMemoryBarrier` from -//! `COMPUTE_SHADER`'s `SHADER_WRITE` to `COMPUTE_SHADER`'s `SHADER_READ | SHADER_WRITE`, the -//! least barrier Vulkan states for a read after a write between dispatches; -//! - **`raw-wide`**: the same, with the runtime's barrier between dispatches of an encoder -//! (`Barrier::between_dispatches`: also `DRAW_INDIRECT` and its `INDIRECT_COMMAND_READ`, and -//! `UNIFORM_READ`); -//! - **`raw-uniform`**: `raw-barrier` with `UNIFORM_READ` also in the destination; -//! - **`raw-indirect`**: `raw-barrier` with `DRAW_INDIRECT` and its `INDIRECT_COMMAND_READ` also -//! in the destination; -//! - **`raw-split`**: `raw-barrier` with each dispatch in a `VkCommandBuffer` of its own, after -//! a `VkCommandBuffer` holding its barrier alone: `2N` command buffers in one `vkQueueSubmit`; -//! - **`raw-none`**: one `VkCommandBuffer` of the dispatches with no barrier. -//! -//! `--idle MS` leaves the GPU idle for `MS` milliseconds before each command buffer of every shape -//! goes to the queue, as long as a program's encoding of a large command buffer can: a GPU that -//! lowers its clocks while idle runs the next one slower. -//! -//! The runtime's shapes take the GPU's time from the command buffer's `gpu_start_time` to its -//! `gpu_end_time`, the raw ones from a timestamp before the first dispatch to one after the last; -//! the runtime's shapes also take the time from the commit to the command buffer's completion on -//! the host (which also holds the GPU work the runtime records before the command buffer's own, -//! such as host calls' staged copies, `command_buffer/submit.rs`). Each line is the median over `R` runs (9 by default) after one -//! not counted, per dispatch, with the runtime's counts per command buffer that moved -//! (`WorkCounts`, by name from their `Debug` form), and those of the run not counted, the shape's first command buffer, apart: its first -//! recording of the kernel's dispatches, as a program's first command buffer of a kind is. The -//! words are read back after each chained shape: each must hold the dispatches run on it. -//! -//! ```text -//! CHAIN dispatches groups threads gpu_us_per_dispatch least -//! [wall_us_per_dispatch ] -//! CHAIN-COUNTS = ... -//! CHAIN-FIRST = ... -//! ``` -//! -//! With `--binds 4` the runtime's shapes run `bump_wide`, which also reads two `Private` buffers of -//! zeros at indices 1 and 2 and a word of 1 set as bytes at index 3 (`a[gid] += b[gid] + c[gid] + -//! k`), each dispatch binding its two zero buffers the other way round from the dispatch before it. -//! With `--binds moved` they run `bump_wide` bound as a guest's serial encoder of small fix-up -//! dispatches binds it: each binding a list of one (`setBuffers:offsets:withRange:`), the words at -//! offset 0, the two zero buffers at an offset that moves [`MOVE_STRIDE`] bytes a dispatch over -//! [`MOVES`] places, and the word of 1 as a buffer of 1s at an offset that moves the same way, as a -//! guest's `setBytes:` arrives as a buffer of its bytes. `--binds fixed` binds the same way at -//! offset 0 for every dispatch, so only the offsets differ from `moved`. -//! -//! `--vary` gives dispatch `n` of an encoder `1 + n % G` threadgroups (so `N` must be a multiple -//! of `G`), as a guest's small dispatches take a group count each; each word must then hold the -//! dispatches whose grid covered it. -//! -//! `--ragged` instead dispatches threads (`dispatchThreads:`): dispatch `n` of a command buffer, -//! with `k = n % 50`, takes `1 + 5 * k` threads in threadgroups of `T`, a grid of 1 to 241 threads -//! that is never a whole number of threadgroups, but where `k % 5 == 4`, which takes -//! `T * (1 + k / 5 % 3)` threads, a whole number of threadgroups (so `G * T` must cover both, `N` -//! be a multiple of 50), as a guest's fix-up dispatch takes a thread for each element it fixes. -//! `--samplers K` makes `K` distinct sampler states first, alive through the runs, as a guest's -//! device holds its programs' samplers. `--classes K` binds `--binds moved`'s and `fixed`'s 1s at -//! index 3 from `K` buffers (1 to 12, of 16 KiB up to 32 MiB) of `K` length classes in turn -//! (`BindState::shape`'s `length_class`), so the dispatches' bind state takes `K` shapes, as a -//! guest's buffers of many sizes do. `--zero-classes Z` binds the zeros at indices 1 and 2 from `Z` -//! pairs of buffers (1 to 8, each class twice the length of the one before), dispatch `n` the pair -//! of class `n / K % Z`, so the bind state takes `K * Z` shapes. `--stay Q` binds dispatch `n`'s -//! classes as dispatch `n - 1` bound them at a chance of `Q` percent, and else a pair of the -//! `K * Z` drawn evenly, from a generator of a fixed seed (every command buffer binds the same -//! sequence): as a guest's fix-up dispatches take the buffers of the draws they fix, some in a row -//! of one buffer, the rest scattered over many. -//! `--states K` (with `--host`) makes `K` compute pipeline states of the kernel, one creation each -//! from the same function, and dispatch `n` of a command buffer sets state `n % K`, as a program -//! whose dispatches each run a kernel of their own sets another state for each. -//! With `--binds tex` they run `bump_tex`, which samples two 16 by 16 `RGBA8Unorm` textures at -//! indices 0 and 1 through a sampler at 0, and reads a word of 1 set as bytes at buffer index 1 -//! (`a[gid] += k`, plus 1000 where a texel's red is below -1e30, which none is): each dispatch -//! binds the pipeline state, the two textures (the other way round from the dispatch before it), -//! the sampler, the words and the bytes, the shape of a guest's compute encoders. -//! `--binds tex-moved` binds the same, but the words and the 1 each as a list of one -//! (`setBuffers:offsets:withRange:`), the 1 from a buffer of 1s at an offset that moves -//! [`MOVE_STRIDE`] bytes a dispatch over [`MOVES`] places (with `--pages`, a no-copy buffer over host -//! pages), as a guest's `setBytes:` arrives as its upload chunk at the chunk's next offset. -//! With `--binds params` they run `bump_params`, which reads a `constant` block of two `uint4` -//! set as bytes at index 1: its second `uint4`'s first word bounds a loop of [`PARAMS_STEPS`] -//! steps, and each step reads the first `uint4` again four times, between two reads of a -//! `Private` buffer of zeros at index 2 at indices the block's words steer, as a convolution -//! kernel's tap loop reads its sizes again around each sample (Metal's compiler leaves such -//! repeated `constant` loads for its own backend to fold): `a[gid] += 1` once the loop ends. -//! `--binds params-off` binds the block as a buffer at offset [`PARAMS_OFFSET`], which no view -//! base alignment of 32 or more divides, so where a kernel's uniform view would read the block at -//! its bind offset alone it reads it at its residual. -//! With `--binds ptr` they run `bump_ptr`, `bump_wide` with its first zero buffer read through an -//! address the dispatch sets as bytes at index 1 (a `Holder` of one pointer, as an argument buffer -//! holds it): a command that loads a pointer, which the device's resident set of its live buffers -//! resolves (`live_buffers.rs`). -//! With `--pages` the words and the zero buffers are `Shared` no-copy buffers over host pages -//! (`new_buffer_with_bytes_no_copy`), as a guest's buffers over its own RAM are on a device with -//! unified memory, which makes the device log the encoders' calls and hold the buffers its commands -//! name (`replay.rs`, `rebind.rs`). With `--heap` they are instead placed, 64 KiB apart, in one -//! `Placement` heap over host pages (`new_heap_with_bytes_no_copy`, then `new_buffer_at_offset`), -//! beside a no-copy buffer over those pages and 64 KiB more before them, as the consumer places a -//! guest's buffers in a heap over the guest's RAM, whose own buffer stands for the RAM: each use of -//! the heap's bytes takes a use of the RAM's key too (`host_aliases.rs`'s placements). The heap is -//! `Tracked`: a heap's default is untracked, which Metal leaves unordered between encoders, so -//! the shapes of several encoders over its words would race without the fences a program puts -//! there; tracked, its buffers are ordered as the plain shapes' tracked words are. -//! -//! **The host's time** (`--host C`): the runtime's shapes alone, each run `C` command buffers of the -//! `N` dispatches, every dispatch setting its pipeline state and buffers again as a program that -//! encodes a dispatch's whole state does, each command buffer committed with `commit_and_submit` -//! (as a consumer that submits on its own thread commits) and waited for before the next is made, -//! outside the times. Each call is timed on the calling thread; per dispatch, the means over the -//! `R` runs after one not counted: -//! -//! ```text -//! HOST dispatches command_buffers binds states ns_per_dispatch make -//! open pipeline bind dispatch end encode commit -//! thread_cpu least_encode_commit -//! HOST-COMMIT lowering recording pipeline_wait lock_wait pass -//! submit -//! HOST-THREADS = ... -//! HOST-BUSY ms = ... -//! HOST-LATENCY samples commit_to_submit_us p50 p99 -//! commit_to_gpu_start_us p50 p99 -//! HOST-IDLE ms = ... -//! ``` -//! -//! `make` is `command_buffer`, `open` the encoders' opening, `pipeline` and `bind` the state's -//! calls, `end` `end_encoding` (with `blits`, a dispatch's blit encoder's opening, copy and end -//! count in its `open`, `dispatch` and `end`; with `copies`, each blit encoder's alone; with -//! `renders` and `renders-apart`, a dispatch's render encoder's opening, pipeline state, vertex -//! buffers, draw and end count in its `open`, `pipeline`, `bind`, `dispatch` and `end` too; with -//! `passes`, each render encoder's alone); `encode` is their sum and `commit` the -//! `commit_and_submit` call; -//! `thread_cpu` the calling thread's CPU time over both (`CLOCK_THREAD_CPUTIME_ID`), and -//! `least_encode_commit` the least run's. `--back-to-back` commits a run's `C` command buffers one -//! after another and then waits for them all, as a guest's command buffers of a frame go. -//! `--encoding-threads E` runs `E` threads at once, started together each run, each making its own -//! `C` command buffers on the one queue, as a guest's queue is walked on threads of its own: a -//! `HOST /thread-` line for each thread, its calls per its own dispatch, and the lines -//! after it over every thread's dispatches. `--queue-each` gives each encoding thread a queue of -//! its own, as a program whose threads each encode on their own queue does. `--spawned` runs one -//! encoding thread as the several run, a thread of its own started each run, rather than on the -//! calling thread. `HOST-COMMIT` splits the commit call by the device's -//! commit phases (`WorkCounts::commit_lowering_nanos` and kin). `HOST-THREADS` is each group of the -//! process's threads' CPU time per dispatch over the counted runs, waits included, by the thread's -//! name (Linux only, from `/proc/self/task/*/schedstat`): `committer` is the calling thread (the -//! process's first) and the encoding threads, the driver's threads (a CPU device's execution among them) are `driver`. -//! `HOST-BUSY` is the same CPU time per second of the counted runs' wall time. `HOST-LATENCY` is -//! each counted command buffer's time from just before its `commit_and_submit` call to its -//! `kernel_start_time` (the scheduler's first submission of its work) and to its -//! `gpu_start_time`, the percentiles over every thread's. With `--idle MS`, each command buffer -//! of the host's time (each run's first, with `--back-to-back`) waits `MS` first, outside the -//! times. `--settle MS` sleeps `MS` after the runs and prints each group's CPU time per second of -//! that sleep (`HOST-IDLE`): what the runtime's threads spend with nothing to do. -//! -//! **Buffers in a heap a command buffer** (`--heap-churn K`, with `--host` and `--binds 4` or -//! `ptr`): each command buffer first makes `K` buffers of the words' length in an automatic -//! `Private` heap of the example's own, made once with room for them and zeroed, as a program that -//! takes a command buffer's scratch from a heap does; its dispatches take them as the two read-only -//! buffers in turn, and they are let go once it completed. `--heap-kept H` places `H` more buffers -//! of 256 bytes in that heap and `--live L` makes `L` more of the device's own, all living through -//! the runs, as a program's other buffers do. Per command buffer, the means over the counted runs: -//! -//! ```text -//! HOST-CB churn kept live ns_per_command_buffer make place -//! encode commit free = ... -//! ``` -//! -//! `make` is `command_buffer`, `place` the `K` buffers' making, `encode` the encoders' calls, -//! `commit` the `commit_and_submit` call and `free` the `K` buffers' release after completion, -//! each on the calling thread; then each group of threads' CPU time (as `HOST-THREADS`), the -//! scheduler's among them. -//! -//! The kernels are text here: LLVM IR assembled by `llvm-as`, SPIR-V by `spirv-as`, both from -//! `PATH`; the render shapes' functions are the owned fixture's LLVM IR, assembled by `llvm-as`. - -use ash::vk; -use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::metal::{BarrierScope, DispatchType, PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - BlitOption, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, - ComputePipelineState, CpuCacheMode, Device, DeviceOptions, HazardTrackingMode, Heap, - HeapDescriptor, HeapType, HostMemory, LoadAction, Origin, PipelineOptions, - RenderPassDescriptor, RenderPipelineState, ResourceOptions, SamplerState, Size, StorageMode, - StoreAction, Texture, TextureDescriptor, WorkCounts, -}; -use std::collections::BTreeMap; -use std::io::Write; -use std::process::{Command, Stdio}; -use std::ptr::NonNull; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// `bump`: `a[gid] += 1`, `a` a buffer of words at index 0. -const KERNEL: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define void @bump(ptr addrspace(1) noundef %a, i32 noundef %gid) {\n\ -entry:\n\ - %gw = zext i32 %gid to i64\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %x = load i32, ptr addrspace(1) %p, align 4\n\ - %v = add i32 %x, 1\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!5, !7}\n\ -!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!7 = !{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @bump, !3, !4}\n"; - -/// `bump_wide`: `a[gid] += b[gid] + c[gid] + *k`, `a` a buffer of words at index 0, `b` and `c` -/// read-only ones at 1 and 2, `k` a `constant` word at 3. -const KERNEL_WIDE: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define void @bump_wide(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef readonly %b, ptr addrspace(1) noundef readonly %c, ptr addrspace(2) noundef %k, i32 noundef %gid) {\n\ -entry:\n\ - %gw = zext i32 %gid to i64\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %pb = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\ - %pc = getelementptr inbounds i32, ptr addrspace(1) %c, i64 %gw\n\ - %x = load i32, ptr addrspace(1) %p, align 4\n\ - %y = load i32, ptr addrspace(1) %pb, align 4\n\ - %z = load i32, ptr addrspace(1) %pc, align 4\n\ - %w = load i32, ptr addrspace(2) %k, align 4\n\ - %s1 = add i32 %x, %y\n\ - %s2 = add i32 %s1, %z\n\ - %v = add i32 %s2, %w\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!5, !10, !11, !12, !7}\n\ -!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!10 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"b\"}\n\ -!11 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"c\"}\n\ -!12 = !{i32 3, !\"air.buffer\", !\"air.buffer_size\", i32 4, !\"air.location_index\", i32 3, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"k\"}\n\ -!7 = !{i32 4, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @bump_wide, !3, !4}\n"; - -/// The steps of `bump_params`'s loop, its block's word 4. -const PARAMS_STEPS: u32 = 16; - -/// `bump_params`'s block: its first `uint4` (the words the loop's steps read, which leave each -/// word as it was), then the loop's steps and the 1 the kernel adds once it ends. -const PARAMS: [u32; 8] = [0, 1, 0, 0, PARAMS_STEPS, 1, 0, 0]; - -/// The offset `--binds params-off` binds `bump_params`'s block at. -const PARAMS_OFFSET: u64 = 16; - -/// `bump_params`: `a[gid] += 1` after [`PARAMS_STEPS`] steps (`p`'s word 4) that each read `p`'s -/// first `uint4` four times, between reads of `s`; `a` a buffer of words at index 0, `p` a -/// `constant` block of two `uint4` ([`PARAMS`]) at 1, `s` a read-only buffer of zeros at 2. -const KERNEL_PARAMS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define void @bump_params(ptr addrspace(1) noundef %a, ptr addrspace(2) noundef %p, ptr addrspace(1) noundef readonly %s, i32 noundef %gid) {\n\ -entry:\n\ - %gw = zext i32 %gid to i64\n\ - %pa = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %x0 = load i32, ptr addrspace(1) %pa, align 4\n\ - %pq = getelementptr inbounds <4 x i32>, ptr addrspace(2) %p, i64 1\n\ - %q = load <4 x i32>, ptr addrspace(2) %pq, align 16\n\ - %n = extractelement <4 x i32> %q, i64 0\n\ - %one = extractelement <4 x i32> %q, i64 1\n\ - br label %loop\n\n\ -loop:\n\ - %i = phi i32 [ 0, %entry ], [ %i1, %loop ]\n\ - %x = phi i32 [ %x0, %entry ], [ %x4, %loop ]\n\ - %v0 = load <4 x i32>, ptr addrspace(2) %p, align 16\n\ - %e0 = extractelement <4 x i32> %v0, i64 0\n\ - %j0 = and i32 %i, %e0\n\ - %k0 = xor i32 %gid, %j0\n\ - %kw0 = zext i32 %k0 to i64\n\ - %ps0 = getelementptr inbounds i32, ptr addrspace(1) %s, i64 %kw0\n\ - %y0 = load i32, ptr addrspace(1) %ps0, align 4\n\ - %x1 = add i32 %x, %y0\n\ - %v1 = load <4 x i32>, ptr addrspace(2) %p, align 16\n\ - %e1 = extractelement <4 x i32> %v1, i64 1\n\ - %x2 = mul i32 %x1, %e1\n\ - %v2 = load <4 x i32>, ptr addrspace(2) %p, align 16\n\ - %e2 = extractelement <4 x i32> %v2, i64 2\n\ - %j2 = and i32 %i, %e2\n\ - %k2 = xor i32 %gid, %j2\n\ - %kw2 = zext i32 %k2 to i64\n\ - %ps2 = getelementptr inbounds i32, ptr addrspace(1) %s, i64 %kw2\n\ - %y2 = load i32, ptr addrspace(1) %ps2, align 4\n\ - %x3 = add i32 %x2, %y2\n\ - %v3 = load <4 x i32>, ptr addrspace(2) %p, align 16\n\ - %e3 = extractelement <4 x i32> %v3, i64 3\n\ - %x4 = xor i32 %x3, %e3\n\ - %i1 = add i32 %i, 1\n\ - %c = icmp ult i32 %i1, %n\n\ - br i1 %c, label %loop, label %exit\n\n\ -exit:\n\ - %v = add i32 %x4, %one\n\ - store i32 %v, ptr addrspace(1) %pa, align 4\n\ - ret void\n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!5, !10, !11, !7}\n\ -!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!10 = !{i32 1, !\"air.buffer\", !\"air.buffer_size\", i32 32, !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"uint4\", !\"air.arg_name\", !\"p\"}\n\ -!11 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"s\"}\n\ -!7 = !{i32 3, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @bump_params, !3, !4}\n"; - -/// `bump_ptr`: `bump_wide` with `b` read through the pointer `h` holds, `h` a `Holder` of one -/// pointer at index 1. -const KERNEL_PTR: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -%struct.Holder = type { ptr addrspace(1) }\n\n\ -define void @bump_ptr(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef readonly %h, ptr addrspace(1) noundef readonly %c, ptr addrspace(2) noundef %k, i32 noundef %gid) {\n\ -entry:\n\ - %gw = zext i32 %gid to i64\n\ - %hp = getelementptr inbounds %struct.Holder, ptr addrspace(1) %h, i64 0, i32 0\n\ - %b = load ptr addrspace(1), ptr addrspace(1) %hp, align 8\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %pb = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\ - %pc = getelementptr inbounds i32, ptr addrspace(1) %c, i64 %gw\n\ - %x = load i32, ptr addrspace(1) %p, align 4\n\ - %y = load i32, ptr addrspace(1) %pb, align 4\n\ - %z = load i32, ptr addrspace(1) %pc, align 4\n\ - %w = load i32, ptr addrspace(2) %k, align 4\n\ - %s1 = add i32 %x, %y\n\ - %s2 = add i32 %s1, %z\n\ - %v = add i32 %s2, %w\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!5, !10, !11, !12, !7}\n\ -!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!10 = !{i32 1, !\"air.indirect_buffer\", !\"air.buffer_size\", i32 8, !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.struct_type_info\", !13, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"Holder\", !\"air.arg_name\", !\"h\"}\n\ -!13 = !{i32 0, i32 8, i32 0, !\"uint\", !\"p\", !\"air.indirect_argument\", !14}\n\ -!14 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"p\"}\n\ -!11 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"c\"}\n\ -!12 = !{i32 3, !\"air.buffer\", !\"air.buffer_size\", i32 4, !\"air.location_index\", i32 3, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"k\"}\n\ -!7 = !{i32 4, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @bump_ptr, !3, !4}\n"; - -/// `bump_tex`: `a[gid] += k`, plus 1000 where a texel `t0` or `t1` samples through `s` at the -/// middle has its red below -1e30; `t0`, `t1` textures at 0 and 1, `s` a sampler at 0, `a` a -/// buffer of words at index 0, `k` a `constant` word at 1. -const KERNEL_TEX: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define void @bump_tex(ptr addrspace(1) %t0, ptr addrspace(1) %t1, ptr addrspace(2) %s, ptr addrspace(1) noundef %a, ptr addrspace(2) noundef %k, i32 noundef %gid) {\n\ -entry:\n\ - %r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t0, ptr addrspace(2) %s, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)\n\ - %r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t1, ptr addrspace(2) %s, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)\n\ - %v0 = extractvalue { <4 x float>, i8 } %r0, 0\n\ - %v1 = extractvalue { <4 x float>, i8 } %r1, 0\n\ - %x0 = extractelement <4 x float> %v0, i64 0\n\ - %x1 = extractelement <4 x float> %v1, i64 0\n\ - %x = fadd float %x0, %x1\n\ - %low = fcmp olt float %x, -1.0e30\n\ - %e = select i1 %low, i32 1000, i32 0\n\ - %gw = zext i32 %gid to i64\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %w = load i32, ptr addrspace(1) %p, align 4\n\ - %kv = load i32, ptr addrspace(2) %k, align 4\n\ - %s1 = add i32 %w, %kv\n\ - %v = add i32 %s1, %e\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}\n\n\ -declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!10, !11, !12, !5, !13, !7}\n\ -!10 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"t0\"}\n\ -!11 = !{i32 1, !\"air.texture\", !\"air.location_index\", i32 1, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"t1\"}\n\ -!12 = !{i32 2, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}\n\ -!5 = !{i32 3, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!13 = !{i32 4, !\"air.buffer\", !\"air.buffer_size\", i32 4, !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"k\"}\n\ -!7 = !{i32 5, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @bump_tex, !3, !4}\n"; - -/// The same work in SPIR-V, its threadgroup `{T}` threads wide: `words[gid.x] += 1` over a -/// storage buffer at set 0, binding 0. -const SPIRV: &str = "OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main \"main\" %gid %buf -OpExecutionMode %main LocalSize {T} 1 1 -OpDecorate %gid BuiltIn GlobalInvocationId -OpDecorate %words ArrayStride 4 -OpMemberDecorate %block 0 Offset 0 -OpDecorate %block Block -OpDecorate %buf DescriptorSet 0 -OpDecorate %buf Binding 0 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v3uint = OpTypeVector %uint 3 -%in_v3 = OpTypePointer Input %v3uint -%gid = OpVariable %in_v3 Input -%words = OpTypeRuntimeArray %uint -%block = OpTypeStruct %words -%sb_block = OpTypePointer StorageBuffer %block -%buf = OpVariable %sb_block StorageBuffer -%sb_uint = OpTypePointer StorageBuffer %uint -%zero = OpConstant %uint 0 -%one = OpConstant %uint 1 -%main = OpFunction %void None %fn -%entry = OpLabel -%g = OpLoad %v3uint %gid -%x = OpCompositeExtract %uint %g 0 -%p = OpAccessChain %sb_uint %buf %zero %x -%v = OpLoad %uint %p -%w = OpIAdd %uint %v %one -OpStore %p %w -OpReturn -OpFunctionEnd -"; - -/// What a dispatch binds (`--binds`), and so its kernel. -#[derive(Clone, Copy, PartialEq)] -enum Binds { - /// `bump`'s words alone. - One, - /// `bump_wide`'s words, two buffers of zeros and bytes. - Wide, - /// `bump_tex`'s two textures, sampler, words and bytes. - Textures, - /// [`Binds::Textures`]'s, the words and the 1 each bound as a list of one, the 1 at a moving - /// offset of a buffer of 1s. - TexMoved, - /// `bump_ptr`'s words, the address of a buffer of zeros, another buffer of zeros and bytes. - Pointer, - /// `bump_wide`'s, each bound as a list of one, the zeros and the 1s at moving offsets. - Moved, - /// [`Binds::Moved`]'s, every offset 0. - Fixed, - /// `bump_params`'s words, block set as bytes and zeros. - Params, - /// [`Binds::Params`]'s, the block bound as a buffer at [`PARAMS_OFFSET`]. - ParamsOff, -} - -/// The places a moved binding's offset takes in turn (`--binds moved`), and the bytes between -/// them. -const MOVES: u64 = 64; -const MOVE_STRIDE: u64 = 256; - -impl Binds { - fn name(self) -> &'static str { - match self { - Binds::One => "1", - Binds::Wide => "4", - Binds::Textures => "tex", - Binds::TexMoved => "tex-moved", - Binds::Pointer => "ptr", - Binds::Moved => "moved", - Binds::Fixed => "fixed", - Binds::Params => "params", - Binds::ParamsOff => "params-off", - } - } -} - -/// The run's shape: dispatches a command buffer, threadgroups a dispatch, threads a threadgroup, -/// timed runs, and the shapes to run. -struct Shape { - dispatches: u32, - groups: u32, - threads: u32, - runs: usize, - only: Option>, - /// What a dispatch binds. - binds: Binds, - /// Command buffers a run of the host's time (`--host`), `None` for the GPU's. - host: Option, - /// Whether the words and zeros lie in no-copy buffers over host pages (`--pages`). - pages: bool, - /// Whether the words and zeros are placed in a heap over host pages beside a buffer over them - /// (`--heap`). - heap: bool, - /// Buffers made in a heap of their own for each command buffer of the host's time - /// (`--heap-churn`). - churn: Option, - /// Buffers of 256 bytes in that heap that live through the runs (`--heap-kept`). - kept: u32, - /// Buffers of 256 bytes of the device's own that live through the runs (`--live`). - live: u32, - /// How long the GPU is left idle before each command buffer goes to the queue (`--idle`). - idle: Duration, - /// How long to sleep after the host's runs, its threads' CPU time read over it (`--settle`). - settle: Duration, - /// Whether dispatch `n` takes `1 + n % groups` threadgroups (`--vary`). - vary: bool, - /// Whether dispatch `n` takes [`ragged_threads`] threads (`--ragged`). - ragged: bool, - /// Sampler states alive through the runs (`--samplers`). - samplers: u32, - /// The length classes of the buffers of 1s (`--classes`). - classes: u32, - /// The length classes of the pairs of buffers of zeros (`--zero-classes`). - zero_classes: u32, - /// The percent chance that a dispatch binds the classes the one before it bound, each other - /// dispatch any pair of classes in turn from a fixed sequence (`--stay`). - stay: Option, - /// The compute pipeline states the dispatches of a command buffer set in turn (`--states`). - states: u32, - /// Whether a run of the host's time commits its command buffers back to back and then waits - /// for them all (`--back-to-back`), rather than each before the next is made. - back_to_back: bool, - /// The threads that each encode a run's command buffers on the one queue at once - /// (`--encoding-threads`). - encoding_threads: u32, - /// Whether each encoding thread encodes on a queue of its own (`--queue-each`). - queue_each: bool, - /// Whether one encoding thread is started each run, as several are, rather than the calling - /// thread encoding (`--spawned`). - spawned: bool, -} - -/// The dispatches of `--ragged`'s cycle of thread counts. -const RAGGED: u32 = 50; - -/// The threads of `--ragged`'s dispatch `n` of a command buffer, in threadgroups of `t`. -fn ragged_threads(n: u32, t: u32) -> u32 { - let k = n % RAGGED; - match k % 5 { - 4 => t * (1 + k / 5 % 3), - _ => 1 + 5 * k, - } -} - -impl Shape { - fn from_args() -> Result { - let mut shape = Shape { - dispatches: 200, - groups: 4096, - threads: 32, - runs: 9, - only: None, - binds: Binds::One, - host: None, - pages: false, - heap: false, - churn: None, - kept: 0, - live: 0, - idle: Duration::ZERO, - settle: Duration::ZERO, - vary: false, - ragged: false, - samplers: 0, - classes: 1, - zero_classes: 1, - stay: None, - states: 1, - back_to_back: false, - encoding_threads: 1, - queue_each: false, - spawned: false, - }; - let mut args = std::env::args().skip(1); - while let Some(flag) = args.next() { - let flags = [ - "--pages", - "--heap", - "--vary", - "--ragged", - "--back-to-back", - "--queue-each", - "--spawned", - ]; - if flags.contains(&flag.as_str()) { - shape.pages |= flag == "--pages"; - shape.heap |= flag == "--heap"; - shape.vary |= flag == "--vary"; - shape.ragged |= flag == "--ragged"; - shape.back_to_back |= flag == "--back-to-back"; - shape.queue_each |= flag == "--queue-each"; - shape.spawned |= flag == "--spawned"; - continue; - } - let value = args.next().ok_or(format!("{flag} takes a value"))?; - match flag.as_str() { - "--dispatches" => shape.dispatches = value.parse()?, - "--groups" => shape.groups = value.parse()?, - "--threads" => shape.threads = value.parse()?, - "--runs" => shape.runs = value.parse()?, - "--only" => shape.only = Some(value.split(',').map(str::to_owned).collect()), - "--binds" => { - shape.binds = - match value.as_str() { - "1" => Binds::One, - "4" => Binds::Wide, - "tex" => Binds::Textures, - "tex-moved" => Binds::TexMoved, - "ptr" => Binds::Pointer, - "moved" => Binds::Moved, - "fixed" => Binds::Fixed, - "params" => Binds::Params, - "params-off" => Binds::ParamsOff, - _ => return Err( - "--binds takes 1, 4, tex, tex-moved, ptr, moved, fixed, params or \ - params-off" - .into(), - ), - } - } - "--host" => shape.host = Some(value.parse()?), - "--heap-churn" => shape.churn = Some(value.parse()?), - "--heap-kept" => shape.kept = value.parse()?, - "--live" => shape.live = value.parse()?, - "--idle" => shape.idle = Duration::from_millis(value.parse()?), - "--settle" => shape.settle = Duration::from_millis(value.parse()?), - "--samplers" => shape.samplers = value.parse()?, - "--classes" => shape.classes = value.parse()?, - "--zero-classes" => shape.zero_classes = value.parse()?, - "--stay" => shape.stay = Some(value.parse()?), - "--states" => shape.states = value.parse()?, - "--encoding-threads" => shape.encoding_threads = value.parse()?, - _ => return Err(format!("unknown flag {flag}").into()), - } - } - if shape.vary && !shape.dispatches.is_multiple_of(shape.groups) { - return Err("--vary takes a dispatch count that is a multiple of --groups".into()); - } - let most = (0..RAGGED).map(|n| ragged_threads(n, shape.threads)).max(); - if shape.ragged - && (!shape.dispatches.is_multiple_of(RAGGED) - || most.is_none_or(|most| shape.words() < u64::from(most))) - { - return Err( - "--ragged takes a multiple of 50 dispatches over every grid's words".into(), - ); - } - if !(1..=12).contains(&shape.classes) { - return Err("--classes takes 1 to 12".into()); - } - if !(1..=8).contains(&shape.zero_classes) { - return Err("--zero-classes takes 1 to 8".into()); - } - if shape.stay.is_some_and(|stay| stay > 100) { - return Err("--stay takes a percent, 0 to 100".into()); - } - let moved = matches!(shape.binds, Binds::Moved | Binds::Fixed); - if (shape.zero_classes > 1 || shape.stay.is_some()) && !moved { - return Err("--zero-classes and --stay take --binds moved or fixed".into()); - } - if shape.states == 0 || (shape.states > 1 && shape.host.is_none()) { - return Err("--states takes 1 or more, and more than 1 takes --host".into()); - } - if shape.encoding_threads == 0 || (shape.encoding_threads > 1 && shape.host.is_none()) { - return Err("--encoding-threads takes 1 or more, and more than 1 takes --host".into()); - } - if shape.queue_each && shape.encoding_threads < 2 { - return Err("--queue-each takes --encoding-threads 2 or more".into()); - } - if shape.spawned && shape.host.is_none() { - return Err("--spawned takes --host".into()); - } - if shape.back_to_back && (shape.host.is_none() || shape.churn.is_some()) { - return Err("--back-to-back takes --host and no --heap-churn".into()); - } - let zeros_read = matches!(shape.binds, Binds::Wide | Binds::Pointer); - if shape.churn.is_some() && (shape.host.is_none() || !zeros_read) { - return Err("--heap-churn takes --host and --binds 4 or ptr".into()); - } - Ok(shape) - } - - fn runs(&self, name: &str) -> bool { - self.only - .as_ref() - .is_none_or(|only| only.iter().any(|shape| shape == name)) - } - - fn words(&self) -> u64 { - u64::from(self.groups) * u64::from(self.threads) - } - - /// The length classes each dispatch of a command buffer binds, of its buffer of 1s - /// (`--classes`) and of its pair of zeros (`--zero-classes`): dispatch `n`'s are `n % K` and - /// `n / K % Z`, but under `--stay Q`, where dispatch `n` binds those of dispatch `n - 1` at a - /// chance of `Q` percent, and else a pair drawn evenly from all `K * Z`, from a generator of a - /// fixed seed, so every command buffer binds the same sequence. - fn picks(&self) -> Vec<(usize, usize)> { - let (ones, zeros) = (self.classes as usize, self.zero_classes as usize); - let Some(stay) = self.stay else { - return (0..self.dispatches as usize) - .map(|n| (n % ones, n / ones % zeros)) - .collect(); - }; - // A 64-bit linear congruential generator (Knuth's MMIX constants), its high bits drawn. - let mut state = 0x5eed_u64; - let mut draw = |below: u64| { - state = (state.wrapping_mul(6_364_136_223_846_793_005)) - .wrapping_add(1_442_695_040_888_963_407); - (state >> 33) % below - }; - let mut picks: Vec<(usize, usize)> = Vec::with_capacity(self.dispatches as usize); - for _ in 0..self.dispatches { - let kept = picks - .last() - .copied() - .filter(|_| draw(100) < u64::from(stay)); - let pick = kept.unwrap_or_else(|| { - let pair = draw((ones * zeros) as u64) as usize; - (pair % ones, pair / ones) - }); - picks.push(pick); - } - picks - } - - /// The threadgroups of an encoder's dispatch `n`: all of them, or `1 + n % groups` with - /// `--vary`. - fn grid(&self, n: u32) -> Size { - let groups = match self.vary { - true => 1 + n % self.groups, - false => self.groups, - }; - Size::new(u64::from(groups), 1, 1) - } - - /// What word `at` holds after `want` dispatches over every word: under `--vary`, those whose - /// grid covered it, `groups - at / threads` of each `groups` dispatches; under `--ragged`, - /// those of each cycle of [`RAGGED`] whose threads covered it. - fn want_at(&self, want: u32, at: usize) -> u32 { - if self.ragged { - let covered = (0..RAGGED) - .filter(|&n| ragged_threads(n, self.threads) as usize > at) - .count(); - return want / RAGGED * covered as u32; - } - match self.vary { - false => want, - true => { - let covered = self.groups - (at as u32 / self.threads).min(self.groups); - want / self.groups * covered - } - } - } - - /// Dispatch an encoder's dispatch `n` of the command buffer: its threadgroups (`grid`), or - /// under `--ragged` its threads. - fn dispatch(&self, encoder: &mut ComputeCommandEncoder, n: u32) -> Result<()> { - let threads = Size::new(u64::from(self.threads), 1, 1); - match self.ragged { - true => { - let grid = Size::new(u64::from(ragged_threads(n, self.threads)), 1, 1); - encoder.dispatch_threads(grid, threads)? - } - false => encoder.dispatch_threadgroups(self.grid(n), threads)?, - } - Ok(()) - } -} - -/// Run `tool` from `PATH` over `input` on its standard input: its standard output. -fn tool(tool: &str, args: &[&str], input: &str) -> Result> { - let mut child = Command::new(tool) - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; - child - .stdin - .take() - .ok_or("no stdin")? - .write_all(input.as_bytes())?; - let output = child.wait_with_output()?; - if !output.status.success() { - return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); - } - Ok(output.stdout) -} - -/// `count` states of the kernel `binds` binds for, one creation each from the same function. -fn states(device: &Device, binds: Binds, count: u32) -> Result> { - let (text, name) = match binds { - Binds::One => (KERNEL, "bump"), - Binds::Wide | Binds::Moved | Binds::Fixed => (KERNEL_WIDE, "bump_wide"), - Binds::Textures | Binds::TexMoved => (KERNEL_TEX, "bump_tex"), - Binds::Pointer => (KERNEL_PTR, "bump_ptr"), - Binds::Params | Binds::ParamsOff => (KERNEL_PARAMS, "bump_params"), - }; - let bitcode = tool("llvm-as", &["-o", "-", "-"], text)?; - let library = metal2vulkan::library::Library::from_air(&bitcode)?; - let function = device - .new_library_with_compile_library(library) - .new_function_with_name(name)?; - let options = PipelineOptions::default(); - let states: std::result::Result, _> = (0..count) - .map(|_| device.new_compute_pipeline_state_with_function(&function, &options)) - .collect(); - Ok(states?) -} - -/// The render shapes' target's side, in texels. -const TARGET_SIDE: u64 = 64; - -/// The color the render shapes' triangles draw, and the bytes an `RGBA8Unorm` texel stores of it. -const DRAWN: [f32; 4] = [1.0, 0.2, 0.0, 1.0]; -const DRAWN_TEXEL: [u8; 4] = [255, 51, 0, 255]; - -/// The render shapes' names, each with whether its passes load the target (`renders`, `passes`), -/// whose first instance records inline, or not (`renders-apart`), recorded in a secondary. -const RENDER_SHAPES: [(&str, bool); 3] = [ - ("renders", true), - ("renders-apart", false), - ("passes", true), -]; - -/// Whether the shape `name` loads its passes' target, where it is a render shape. -fn loads(name: &str) -> Option { - (RENDER_SHAPES.iter()) - .find(|(shape, _)| *shape == name) - .map(|(_, loads)| *loads) -} - -/// The render shapes' pipeline state, target, vertices and passes. -struct Render { - state: RenderPipelineState, - target: Texture, - positions: Buffer, - colors: Buffer, - /// The target loaded and stored. - loaded: RenderPassDescriptor, - /// The target not loaded (`DontCare`), and stored. - apart: RenderPassDescriptor, - /// What the target's texels are copied into to be checked. - readback: Buffer, -} - -impl Render { - /// The owned fixture's `colored_vertex` and `colored_fragment`, assembled by `llvm-as`, over - /// a `Private` target, and two triangles over the whole of it. - fn new(device: &Device) -> Result { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll" - ); - let text = - std::fs::read_to_string(path).map_err(|error| format!("read {path}: {error}"))?; - let bitcode = tool("llvm-as", &["-o", "-", "-"], &text)?; - let library = device - .new_library_with_compile_library(metal2vulkan::library::Library::from_air(&bitcode)?); - let vertex = library.new_function_with_name("colored_vertex")?; - let fragment = library.new_function_with_name("colored_fragment")?; - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let state = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?; - let mut texture = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, TARGET_SIDE, TARGET_SIDE, false); - texture.usage = TextureUsage::RENDER_TARGET; - texture.resource_options = ResourceOptions::private(); - let target = device.new_texture(&texture)?; - let corners: [[f32; 2]; 6] = [ - [-1.0, 1.0], - [1.0, 1.0], - [-1.0, -1.0], - [1.0, 1.0], - [1.0, -1.0], - [-1.0, -1.0], - ]; - let positions: Vec = (corners.iter().flatten()) - .flat_map(|value| value.to_le_bytes()) - .collect(); - let colors: Vec = (0..corners.len()) - .flat_map(|_| DRAWN) - .flat_map(|value| value.to_le_bytes()) - .collect(); - let pass = |load_action: LoadAction| { - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = load_action; - color.store_action = StoreAction::Store; - pass - }; - Ok(Render { - state, - positions: device.new_buffer_with_bytes(&positions, ResourceOptions::shared())?, - colors: device.new_buffer_with_bytes(&colors, ResourceOptions::shared())?, - loaded: pass(LoadAction::Load), - apart: pass(LoadAction::DontCare), - readback: device - .new_buffer(TARGET_SIDE * TARGET_SIDE * 4, ResourceOptions::shared())?, - target, - }) - } -} - -/// The counts of `counts` by name, read from their `Debug` form. -fn counts(counts: &WorkCounts) -> BTreeMap { - let text = format!("{counts:?}"); - text.split([',', '{']) - .filter_map(|part| { - let (name, value) = part.split_once(':')?; - Some((name.trim().to_owned(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// The samples of one shape: GPU microseconds per dispatch, microseconds from the commit to the -/// completion per dispatch (the runtime's shapes), the counts' sums over the runs counted, and the -/// counts of the run not counted, its first. -#[derive(Default)] -struct Samples { - per_dispatch: Vec, - walls: Vec, - counts: BTreeMap, - first: BTreeMap, -} - -/// What moved from `before` to `after`, added to `into`. -fn add_moved(into: &mut BTreeMap, before: &WorkCounts, after: &WorkCounts) { - let before = counts(before); - for (name, value) in counts(after) { - let moved = value.saturating_sub(before.get(&name).copied().unwrap_or(0)); - if moved > 0 { - *into.entry(name).or_default() += moved; - } - } -} - -impl Samples { - fn add_counts(&mut self, before: &WorkCounts, after: &WorkCounts) { - add_moved(&mut self.counts, before, after); - } - - fn print(mut self, name: &str, shape: &Shape, device: &str) { - self.per_dispatch.sort_by(f64::total_cmp); - self.walls.sort_by(f64::total_cmp); - let wall = match self.walls.get(self.walls.len() / 2) { - Some(wall) => format!(" wall_us_per_dispatch {wall:.2}"), - None => String::new(), - }; - println!( - "CHAIN {name} dispatches {} groups {} threads {} gpu_us_per_dispatch {:.2} least {:.2}\ - {wall} {device}", - shape.dispatches, - shape.groups, - shape.threads, - self.per_dispatch[self.per_dispatch.len() / 2], - self.per_dispatch[0], - ); - if !self.counts.is_empty() { - let runs = self.per_dispatch.len() as f64; - let line: Vec = (self.counts.iter()) - .map(|(name, sum)| format!("{name}={:.2}", *sum as f64 / runs)) - .collect(); - println!("CHAIN-COUNTS {name} {}", line.join(" ")); - } - if !self.first.is_empty() { - let line: Vec = (self.first.iter()) - .map(|(name, value)| format!("{name}={value}")) - .collect(); - println!("CHAIN-FIRST {name} {}", line.join(" ")); - } - } -} - -/// A call of the host's time, in [`Lap`]'s order. -#[derive(Clone, Copy)] -enum Call { - Make, - Open, - Pipeline, - Bind, - Dispatch, - End, - Commit, - Place, - Free, -} - -/// The calls' names, in [`Call`]'s order: the `HOST` line's, then the churned heap's -/// (`--heap-churn`). -const CALLS: [&str; 9] = [ - "make", "open", "pipeline", "bind", "dispatch", "end", "commit", "place", "free", -]; - -/// Nanoseconds of the calling thread's time by [`Call`], over a run. -#[derive(Default, Clone, Copy)] -struct Lap([u64; 9]); - -impl Lap { - /// Count the time since `at` to `call`, and start the next call's there. - fn lap(&mut self, at: &mut Instant, call: Call) { - let now = Instant::now(); - self.0[call as usize] += (now - *at).as_nanos() as u64; - *at = now; - } -} - -/// The host's time of the counted runs: each call's sum, the calling thread's CPU over them, and -/// each run's encoding and commit. -#[derive(Default)] -struct HostSample { - calls: [u64; 9], - thread_cpu: u64, - per_run: Vec, - /// Each command buffer's microseconds from before its commit to its kernel start and to its - /// GPU start. - latency: Vec<(f64, f64)>, -} - -impl HostSample { - fn add(&mut self, lap: Lap) { - for (sum, nanos) in self.calls.iter_mut().zip(lap.0) { - *sum += nanos; - } - self.per_run.push(lap.0[..7].iter().sum()); - } - - fn print(&self, name: &str, shape: &Shape, command_buffers: u32, dispatches: f64) { - let per = |nanos: u64| nanos as f64 / dispatches; - let mut line = format!( - "HOST {name} dispatches {} command_buffers {command_buffers} binds {} states {} \ - ns_per_dispatch", - shape.dispatches, - shape.binds.name(), - shape.states, - ); - for (call, nanos) in CALLS.iter().zip(self.calls).take(7) { - if *call == "commit" { - let encode: u64 = self.calls[..6].iter().sum(); - line.push_str(&format!(" encode {:.0}", per(encode))); - } - line.push_str(&format!(" {call} {:.0}", per(nanos))); - } - let least = self.per_run.iter().min().copied().unwrap_or(0); - let runs = self.per_run.len().max(1) as f64; - line.push_str(&format!( - " thread_cpu {:.0} least_encode_commit {:.0}", - per(self.thread_cpu), - least as f64 * runs / dispatches - )); - println!("{line}"); - } - - /// The `HOST-CB` line of `--heap-churn`, `threads` each group's CPU time over the counted runs. - fn print_per_command_buffer( - &self, - name: &str, - shape: &Shape, - command_buffers: u32, - threads: &[(String, u64)], - ) { - let Some(churn) = shape.churn else { - return; - }; - let per = - |nanos: u64| nanos as f64 / (command_buffers as usize * self.per_run.len()) as f64; - let encode: u64 = self.calls[1..6].iter().sum(); - let mut line = format!( - "HOST-CB {name} churn {churn} kept {} live {} ns_per_command_buffer make {:.0} place {:.0} \ - encode {:.0} commit {:.0} free {:.0}", - shape.kept, - shape.live, - per(self.calls[Call::Make as usize]), - per(self.calls[Call::Place as usize]), - per(encode), - per(self.calls[Call::Commit as usize]), - per(self.calls[Call::Free as usize]), - ); - for (group, nanos) in threads { - line.push_str(&format!(" {group}={:.0}", per(*nanos))); - } - println!("{line}"); - } -} - -/// The bytes a placed buffer takes in [`Placed`]'s heap, and the RAM's before the heap's. -const CHUNK: u64 = 0x1_0000; - -/// The words and the zeros' heap (`--heap`): a tracked `Placement` heap over host pages, beside a -/// no-copy buffer over its pages and [`CHUNK`] more before them, which stands for a guest's RAM. -/// Both are kept for the process's life, so no import outlives its pages. -struct Placed { - heap: Heap, - _ram: Buffer, - /// Each buffer's offset in the heap and length, in the order they are placed. - places: Vec<(u64, u64)>, -} - -impl Placed { - /// Room for buffers of `lengths` bytes, each in chunks of its own. - fn new(device: &Device, lengths: &[u64]) -> Result { - let mut places = Vec::with_capacity(lengths.len()); - let mut room = 0; - for &bytes in lengths { - places.push((room, bytes)); - room += bytes.div_ceil(CHUNK) * CHUNK; - } - let length = CHUNK + room; - let pages = host_pages(length as usize)?; - // SAFETY: page-aligned read-write memory of `length` bytes, never unmapped, which outlives - // the buffer. - let ram = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(pages), - length, - ResourceOptions::shared(), - None, - ) - }?; - // SAFETY: inside the mapping, past its first chunk. - let at = NonNull::new(unsafe { pages.as_ptr().add(CHUNK as usize) }).ok_or("null")?; - // Tracked: the encoders of a command buffer are ordered over its buffers as over the plain - // shapes' words, with no fence (a heap's default is untracked). - let options = ResourceOptions::new( - StorageMode::Shared, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Tracked, - ); - let descriptor = HeapDescriptor::new(HeapType::Placement, room, options); - // SAFETY: the mapping past its first chunk, which outlives the heap. - let heap = unsafe { - device.new_heap_with_bytes_no_copy(HostMemory::new(at), &descriptor, None, None) - }?; - Ok(Placed { - heap, - _ram: ram, - places, - }) - } - - /// The `n`th buffer placed in the heap, of the `n`th length it has room for. - fn buffer(&self, n: usize) -> Result { - let (offset, bytes) = *self.places.get(n).ok_or("no room in the placed heap")?; - Ok(self - .heap - .new_buffer_at_offset(bytes, ResourceOptions::shared(), offset)?) - } -} - -/// `bump_params`'s block ([`PARAMS`]) as bytes. -fn params_bytes() -> Vec { - PARAMS.iter().flat_map(|word| word.to_le_bytes()).collect() -} - -/// A `Shared` buffer of 256 bytes holding `bump_params`'s block at [`PARAMS_OFFSET`]. -fn params_buffer(device: &Device) -> Result { - let bytes = params_bytes(); - let buffer = device.new_buffer(256, ResourceOptions::shared())?; - let contents = buffer.contents().ok_or("no contents")?; - for (at, byte) in bytes.iter().enumerate() { - // SAFETY: inside the buffer's mapped bytes, which no GPU work uses yet. - unsafe { contents.add(PARAMS_OFFSET as usize + at).write(*byte) }; - } - Ok(buffer) -} - -/// A `Shared` buffer of words of 1 over [`MOVES`] places of [`MOVE_STRIDE`] bytes, of the length -/// class `class` past the least such buffer's: a no-copy buffer over host pages where `pages`. -fn ones(device: &Device, class: u32, pages: bool) -> Result { - let bytes = (MOVE_STRIDE * MOVES) << class; - let ones = match pages { - // SAFETY: page-aligned read-write memory of `bytes` bytes, never unmapped, which outlives - // the buffer. - true => unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(host_pages(bytes as usize)?), - bytes, - ResourceOptions::shared(), - None, - ) - }?, - false => device.new_buffer(bytes, ResourceOptions::shared())?, - }; - let contents = ones.contents().ok_or("no contents")?; - for at in 0..(bytes / 4) as usize { - // SAFETY: inside the buffer's mapped bytes, which no GPU work uses yet. - unsafe { contents.cast::().add(at).write(1) }; - } - Ok(ones) -} - -/// `bytes` bytes of fresh host pages, read-write, never unmapped: private, as RADV refuses to -/// import shared anonymous memory (`host_memory.rs`'s `import_refused`). -fn host_pages(bytes: usize) -> Result> { - #[cfg(unix)] - // SAFETY: a fresh anonymous mapping, read-write, never unmapped. - let pages = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pages = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - bytes, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pages == libc::MAP_FAILED { - return Err(format!("mmap: {}", std::io::Error::last_os_error()).into()); - } - Ok(NonNull::new(pages.cast::()).ok_or("a null mapping")?) -} - -/// This thread's CPU time so far, in nanoseconds. -#[cfg(unix)] -fn thread_cpu_nanos() -> u64 { - // SAFETY: a plain call with an out-parameter of the right type. - let spec = unsafe { - let mut spec: libc::timespec = std::mem::zeroed(); - libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut spec); - spec - }; - spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64 -} - -/// This thread's CPU time so far, in nanoseconds: its kernel and user times (`GetThreadTimes`), -/// in 100 ns units. -#[cfg(windows)] -fn thread_cpu_nanos() -> u64 { - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetThreadTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 -} - -/// The group a thread named `comm` is counted in, the process's first thread (`main`) the -/// committer. -fn group_of(comm: &str, main: bool) -> &'static str { - match comm { - _ if main => "committer", - c if c.starts_with("encoding-") => "committer", - c if c.starts_with("metal2vulkan-sc") => "scheduler", - c if c.starts_with("metal2vulkan-qu") => "queue-waiters", - c if c.starts_with("metal2vulkan") || c.starts_with("m2v-") => "other-m2v", - _ => "driver", - } -} - -/// Nanoseconds of CPU by thread group, each of the process's threads by its name: Linux only, -/// none elsewhere. -fn cpu_by_group() -> Vec<(String, u64)> { - let mut groups: Vec<(String, u64)> = Vec::new(); - let Ok(tasks) = std::fs::read_dir("/proc/self/task") else { - return groups; - }; - for task in tasks.flatten() { - let path = task.path(); - let comm = std::fs::read_to_string(path.join("comm")).unwrap_or_default(); - let stat = std::fs::read_to_string(path.join("schedstat")).unwrap_or_default(); - let nanos: u64 = (stat.split_whitespace().next()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - let main = task.file_name().to_str() == Some(&std::process::id().to_string()); - let group = group_of(comm.trim(), main); - match groups.iter_mut().find(|(n, _)| *n == group) { - Some((_, total)) => *total += nanos, - None => groups.push((group.to_owned(), nanos)), - } - } - groups -} - -/// The microseconds from `committed` (a [`host_time`](metal2vulkan_runtime::host_time)) to the -/// completed `command_buffer`'s kernel start and to its GPU start. -fn started(command_buffer: &CommandBuffer, committed: f64) -> Result<(f64, f64)> { - let kernel = command_buffer.kernel_start_time() - committed; - let gpu = command_buffer.gpu_start_time()? - committed; - Ok((kernel * 1e6, gpu * 1e6)) -} - -/// The `p`th percentile of `sorted`, 0 where it is empty. -fn percentile(sorted: &[f64], p: usize) -> f64 { - match sorted.len() { - 0 => 0.0, - n => sorted[((n * p).div_ceil(100)).clamp(1, n) - 1], - } -} - -/// Each group's CPU time from `earlier` to `later` ([`cpu_by_group`]). -fn moved_by_group(earlier: &[(String, u64)], later: &[(String, u64)]) -> Vec<(String, u64)> { - (later.iter()) - .map(|(group, nanos)| { - let before = (earlier.iter()) - .find(|(g, _)| g == group) - .map_or(0, |(_, n)| *n); - (group.clone(), nanos.saturating_sub(before)) - }) - .collect() -} - -/// Print `label`'s line: each group's CPU time `threads` per second of `wall`, in milliseconds. -fn print_per_second(label: &str, name: &str, wall: Duration, threads: &[(String, u64)]) { - let seconds = wall.as_secs_f64().max(1e-9); - let line: Vec = (threads.iter()) - .map(|(group, nanos)| format!("{group}={:.1}", *nanos as f64 / 1e6 / seconds)) - .collect(); - println!( - "{label} {name} ms {:.1} {}", - wall.as_secs_f64() * 1e3, - line.join(" ") - ); -} - -/// Wait for `command_buffer` to complete, as it must. -fn completed(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - if command_buffer.status() != CommandBufferStatus::Completed { - return Err(format!("a command buffer ended {:?}", command_buffer.error()).into()); - } - Ok(()) -} - -/// The runtime's shapes over one buffer, with two of zeros for `bump_wide`, two textures and a -/// sampler for `bump_tex`, and a block for `bump_params`. -struct Ours<'a> { - device: &'a Device, - /// The kernel's states, dispatch `n` of a command buffer of the host's time setting state - /// `n % K` (`--states`); one for every other shape. - states: Vec, - words: Buffer, - /// Pairs of buffers of zeros, of one length class each (`--zero-classes`), the least first. - zeros: Vec<[Buffer; 2]>, - /// Words of 1, [`MOVES`] places of [`MOVE_STRIDE`] bytes, for `--binds moved` and `fixed`, of - /// one length class each (`--classes`). - ones: Vec, - /// The classes of 1s and of zeros each dispatch of a command buffer binds ([`Shape::picks`]). - picks: Vec<(usize, usize)>, - textures: [Texture; 2], - sampler: SamplerState, - /// `bump_params`'s block at [`PARAMS_OFFSET`], for `--binds params-off`. - params: Buffer, - readback: Buffer, - /// What the `blits` shape's copies write. - copies: Buffer, - /// The render shapes' pipeline state, target and passes, where one runs. - render: Option, - /// The heap each command buffer of the host's time makes its buffers in (`--heap-churn`). - churn: Option, -} - -impl Ours<'_> { - /// One command buffer of `shape`'s dispatches as `name` holds them, committed and waited for: - /// its GPU time and its time from the commit to its completion per dispatch, in microseconds. - fn run(&self, name: &str, shape: &Shape) -> Result<(f64, f64)> { - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let encoders = match name { - "encoders" | "blits" | "copies" => shape.dispatches, - _ if loads(name).is_some() => shape.dispatches, - _ => 1, - }; - // The command buffer's dispatches so far, for `--vary`'s group counts. - let mut dispatched = 0; - for _ in 0..encoders { - if name == "copies" { - self.copy(&command_buffer)?; - continue; - } - if name == "passes" { - self.draw(&command_buffer, true, None)?; - continue; - } - let mut encoder = match name { - "concurrent" | "barriers" => command_buffer - .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent)?, - _ => command_buffer.compute_command_encoder()?, - }; - encoder.set_compute_pipeline_state(&self.states[0])?; - for n in 0..shape.dispatches / encoders { - if n > 0 && name == "barriers" { - encoder.memory_barrier_with_scope(BarrierScope::BUFFERS); - } - self.bind(&mut encoder, shape.binds, dispatched as usize, &[])?; - shape.dispatch(&mut encoder, dispatched)?; - dispatched += 1; - } - encoder.end_encoding()?; - if let Some(loaded) = loads(name) { - self.draw(&command_buffer, loaded, None)?; - } - if name == "blits" || loads(name).is_some() { - self.copy(&command_buffer)?; - } - } - std::thread::sleep(shape.idle); - let committed = Instant::now(); - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - let wall = committed.elapsed().as_secs_f64(); - if command_buffer.status() != CommandBufferStatus::Completed { - return Err(format!("a command buffer ended {:?}", command_buffer.error()).into()); - } - let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; - let dispatches = f64::from(shape.dispatches); - Ok((gpu * 1e6 / dispatches, wall * 1e6 / dispatches)) - } - - /// Bind what dispatch `n` of a command buffer binds, whatever encoder holds it: the words, and - /// `bump_wide`'s read-only buffers (the next two of `churned`, the command buffer's buffers in - /// its heap, where it has any) or `bump_tex`'s textures the other way round from dispatch - /// `n - 1`, with their word of 1, at the offsets `n` moves to: so the `encoders` shape's - /// dispatches, one an encoder, bind as the `serial` shape's do. - fn bind( - &self, - encoder: &mut ComputeCommandEncoder, - binds: Binds, - n: usize, - churned: &[Buffer], - ) -> Result<()> { - let one = 1u32.to_le_bytes(); - match binds { - Binds::One => encoder.set_buffer(Some(&self.words), 0, 0)?, - Binds::Wide | Binds::Pointer => { - let (b, c) = match churned.len() { - 0 => (&self.zeros[0][n % 2], &self.zeros[0][1 - n % 2]), - k => (&churned[(2 * n) % k], &churned[(2 * n + 1) % k]), - }; - encoder.set_buffer(Some(&self.words), 0, 0)?; - match binds { - Binds::Pointer => encoder.set_bytes(&b.gpu_address().0.to_le_bytes(), 1)?, - _ => encoder.set_buffer(Some(b), 0, 1)?, - } - encoder.set_buffer(Some(c), 0, 2)?; - encoder.set_bytes(&one, 3)?; - } - Binds::Moved | Binds::Fixed => { - let at = match binds { - Binds::Moved => MOVE_STRIDE * (n as u64 % MOVES), - _ => 0, - }; - let (one, zero) = self.picks[n % self.picks.len()]; - let zeros = &self.zeros[zero]; - let (b, c) = (&zeros[n % 2], &zeros[1 - n % 2]); - encoder.set_buffers(&[Some(&self.words)], &[0], 0)?; - encoder.set_buffers(&[Some(b)], &[at], 1)?; - encoder.set_buffers(&[Some(c)], &[at], 2)?; - encoder.set_buffers(&[Some(&self.ones[one])], &[at], 3)?; - } - Binds::Params | Binds::ParamsOff => { - encoder.set_buffer(Some(&self.words), 0, 0)?; - match binds { - Binds::Params => encoder.set_bytes(¶ms_bytes(), 1)?, - _ => encoder.set_buffer(Some(&self.params), PARAMS_OFFSET, 1)?, - } - encoder.set_buffer(Some(&self.zeros[0][n % 2]), 0, 2)?; - } - Binds::Textures => { - encoder.set_texture(Some(&self.textures[n % 2]), 0)?; - encoder.set_texture(Some(&self.textures[1 - n % 2]), 1)?; - encoder.set_sampler_state(Some(&self.sampler), 0)?; - encoder.set_buffer(Some(&self.words), 0, 0)?; - encoder.set_bytes(&one, 1)?; - } - Binds::TexMoved => { - let at = MOVE_STRIDE * (n as u64 % MOVES); - encoder.set_texture(Some(&self.textures[n % 2]), 0)?; - encoder.set_texture(Some(&self.textures[1 - n % 2]), 1)?; - encoder.set_sampler_state(Some(&self.sampler), 0)?; - encoder.set_buffers(&[Some(&self.words)], &[0], 0)?; - encoder.set_buffers(&[Some(&self.ones[0])], &[at], 1)?; - } - } - Ok(()) - } - - /// One run of the host's time: `command_buffers` command buffers of `shape`'s dispatches as - /// `name` holds them on `queue`, each committed with `commit_and_submit` and waited for (all of - /// them once the last is committed, with `--back-to-back`). - fn run_host( - &self, - queue: &CommandQueue, - name: &str, - shape: &Shape, - command_buffers: u32, - host: &mut HostSample, - ) -> Result<()> { - let encoders = match name { - "encoders" | "blits" | "copies" => shape.dispatches, - _ if loads(name).is_some() => shape.dispatches, - _ => 1, - }; - let mut lap = Lap::default(); - let mut in_flight = Vec::new(); - for at_buffer in 0..command_buffers { - if !shape.back_to_back || at_buffer == 0 { - std::thread::sleep(shape.idle); - } - // The command buffer's dispatches so far, for `--vary`'s group counts. - let mut dispatched = 0; - let cpu = thread_cpu_nanos(); - let mut at = Instant::now(); - let command_buffer = queue.command_buffer()?; - lap.lap(&mut at, Call::Make); - let churned = self.churned(shape)?; - lap.lap(&mut at, Call::Place); - for _ in 0..encoders { - if name == "copies" { - self.copy_lapped(&command_buffer, &mut lap, &mut at)?; - continue; - } - if name == "passes" { - self.draw(&command_buffer, true, Some((&mut lap, &mut at)))?; - continue; - } - let mut encoder = match name { - "concurrent" | "barriers" => command_buffer - .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent)?, - _ => command_buffer.compute_command_encoder()?, - }; - lap.lap(&mut at, Call::Open); - for n in 0..shape.dispatches / encoders { - if n > 0 && name == "barriers" { - encoder.memory_barrier_with_scope(BarrierScope::BUFFERS); - } - let state = &self.states[dispatched as usize % self.states.len()]; - encoder.set_compute_pipeline_state(state)?; - lap.lap(&mut at, Call::Pipeline); - self.bind(&mut encoder, shape.binds, dispatched as usize, &churned)?; - lap.lap(&mut at, Call::Bind); - shape.dispatch(&mut encoder, dispatched)?; - dispatched += 1; - lap.lap(&mut at, Call::Dispatch); - } - encoder.end_encoding()?; - lap.lap(&mut at, Call::End); - if let Some(loaded) = loads(name) { - self.draw(&command_buffer, loaded, Some((&mut lap, &mut at)))?; - } - if name == "blits" || loads(name).is_some() { - self.copy_lapped(&command_buffer, &mut lap, &mut at)?; - } - } - let committed = metal2vulkan_runtime::host_time(); - command_buffer.commit_and_submit()?; - lap.lap(&mut at, Call::Commit); - host.thread_cpu += thread_cpu_nanos() - cpu; - if shape.back_to_back { - in_flight.push((command_buffer, committed)); - continue; - } - completed(&command_buffer)?; - host.latency.push(started(&command_buffer, committed)?); - let mut at = Instant::now(); - drop(churned); - lap.lap(&mut at, Call::Free); - } - for (command_buffer, committed) in &in_flight { - completed(command_buffer)?; - host.latency.push(started(command_buffer, *committed)?); - } - host.add(lap); - Ok(()) - } - - /// [`run_host`](Self::run_host) on each of `hosts.len()` threads at once, thread `t` on - /// `queues[t % queues.len()]`, each counted in its own sample: on the calling thread where - /// there is one. - fn run_host_threads( - &self, - queues: &[CommandQueue], - name: &str, - shape: &Shape, - command_buffers: u32, - hosts: &mut [HostSample], - ) -> Result<()> { - if let ([host], false) = (&mut *hosts, shape.spawned) { - return self.run_host(&queues[0], name, shape, command_buffers, host); - } - let start = std::sync::Barrier::new(hosts.len()); - let ran: Vec> = std::thread::scope(|scope| { - let running: std::io::Result> = (hosts.iter_mut().enumerate()) - .map(|(thread, host)| { - let start = &start; - let queue = &queues[thread % queues.len()]; - std::thread::Builder::new() - .name(format!("encoding-{thread}")) - .spawn_scoped(scope, move || { - start.wait(); - // Each thread's refusal as its text, which crosses threads. - (self.run_host(queue, name, shape, command_buffers, host)) - .map_err(|error| error.to_string()) - }) - }) - .collect(); - match running { - Ok(running) => (running.into_iter()) - .map(|thread| thread.join().unwrap_or(Err("a thread panicked".into()))) - .collect(), - Err(error) => vec![Err(error.to_string())], - } - }); - for answer in ran { - answer?; - } - Ok(()) - } - - /// The buffers a command buffer of the host's time makes in its heap (`--heap-churn`): none - /// without one. - fn churned(&self, shape: &Shape) -> Result> { - let (Some(heap), Some(count)) = (&self.churn, shape.churn) else { - return Ok(Vec::new()); - }; - let bytes = shape.words() * 4; - let placed: std::result::Result, _> = (0..count) - .map(|_| heap.new_buffer(bytes, ResourceOptions::private())) - .collect(); - Ok(placed?) - } - - /// Clear the words, run the host's time of `shape` as `name` holds it, and check the words. - fn host_shape(&self, name: &str, shape: &Shape, command_buffers: u32) -> Result<()> { - self.fill(0)?; - let encoding = shape.encoding_threads as usize; - let made = (0..if shape.queue_each { encoding } else { 1 }) - .map(|_| self.device.new_command_queue()) - .collect::, _>>(); - let queues = made?; - let mut first: Vec = (0..encoding).map(|_| HostSample::default()).collect(); - self.run_host_threads(&queues, name, shape, command_buffers, &mut first)?; - let mut hosts: Vec = (0..encoding).map(|_| HostSample::default()).collect(); - let (before, threads) = (self.device.work_counts(), cpu_by_group()); - let began = Instant::now(); - for _ in 0..shape.runs { - self.run_host_threads(&queues, name, shape, command_buffers, &mut hosts)?; - } - let wall = began.elapsed(); - let (after, threads_after) = (self.device.work_counts(), cpu_by_group()); - // Each thread's own dispatches, then every thread's. - let own = (shape.dispatches * command_buffers) as f64 * shape.runs as f64; - let dispatches = own * encoding as f64; - for (thread, host) in hosts.iter().enumerate() { - match encoding { - 1 => host.print(name, shape, command_buffers, own), - _ => host.print( - &format!("{name}/thread-{thread}"), - shape, - command_buffers, - own, - ), - } - } - let host = &hosts[0]; - let phases = [ - ( - "lowering", - after.commit_lowering_nanos - before.commit_lowering_nanos, - ), - ( - "recording", - after.commit_recording_nanos - before.commit_recording_nanos, - ), - ( - "pipeline_wait", - after.commit_pipeline_wait_nanos - before.commit_pipeline_wait_nanos, - ), - ( - "lock_wait", - after.commit_lock_wait_nanos - before.commit_lock_wait_nanos, - ), - ("pass", after.commit_pass_nanos - before.commit_pass_nanos), - ( - "submit", - after.commit_submit_nanos - before.commit_submit_nanos, - ), - ]; - let line: Vec = (phases.iter()) - .map(|(phase, nanos)| format!("{phase} {:.0}", *nanos as f64 / dispatches)) - .collect(); - println!("HOST-COMMIT {name} {}", line.join(" ")); - let threads = moved_by_group(&threads, &threads_after); - let line: Vec = (threads.iter()) - .map(|(group, nanos)| format!("{group}={:.0}", *nanos as f64 / dispatches)) - .collect(); - if !line.is_empty() { - println!("HOST-THREADS {name} {}", line.join(" ")); - print_per_second("HOST-BUSY", name, wall, &threads); - } - let (mut to_submit, mut to_gpu): (Vec, Vec) = hosts - .iter() - .flat_map(|host| host.latency.iter().copied()) - .unzip(); - to_submit.sort_by(f64::total_cmp); - to_gpu.sort_by(f64::total_cmp); - println!( - "HOST-LATENCY {name} samples {} commit_to_submit_us p50 {:.1} p99 {:.1} \ - commit_to_gpu_start_us p50 {:.1} p99 {:.1}", - to_submit.len(), - percentile(&to_submit, 50), - percentile(&to_submit, 99), - percentile(&to_gpu, 50), - percentile(&to_gpu, 99), - ); - if !shape.settle.is_zero() { - let earlier = cpu_by_group(); - let began = Instant::now(); - std::thread::sleep(shape.settle); - let slept = began.elapsed(); - let idle = moved_by_group(&earlier, &cpu_by_group()); - print_per_second("HOST-IDLE", name, slept, &idle); - } - host.print_per_command_buffer(name, shape, command_buffers, &threads); - let mut moved = BTreeMap::new(); - add_moved(&mut moved, &before, &after); - let line: Vec = (moved.iter()) - .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / dispatches)) - .collect(); - println!("HOST-COUNTS {name} {}", line.join(" ")); - // Checked after the lines, so a check that fails still shows what the runs counted. - if name != "concurrent" { - let runs = shape.runs as u32 + 1; - let want = shape.dispatches * command_buffers * runs * shape.encoding_threads; - self.check(want, name, shape)?; - } - Ok(()) - } - - /// Clear the words, run `shape` as `name` holds it, and check what the chained shapes left. - fn shape(&self, name: &str, shape: &Shape, device: &str) -> Result<()> { - self.fill(0)?; - let mut samples = Samples::default(); - for run in 0..=shape.runs { - let before = self.device.work_counts(); - let (per, wall) = self.run(name, shape)?; - match run { - 0 => add_moved(&mut samples.first, &before, &self.device.work_counts()), - _ => { - samples.per_dispatch.push(per); - samples.walls.push(wall); - samples.add_counts(&before, &self.device.work_counts()); - } - } - } - samples.print(name, shape, device); - // Checked after the lines, so a check that fails still shows what the runs counted. - if name != "concurrent" { - self.check(shape.dispatches * (shape.runs as u32 + 1), name, shape)?; - } - Ok(()) - } - - /// A blit encoder of `command_buffer` that copies the words into `copies`, ended (`blits`). - fn copy(&self, command_buffer: &CommandBuffer) -> Result<()> { - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(&self.words, 0, &self.copies, 0, self.words.length())?; - blit.end_encoding()?; - Ok(()) - } - - /// [`copy`](Self::copy), its opening, copy and end timed as an encoder's opening, dispatch - /// and end. - fn copy_lapped( - &self, - command_buffer: &CommandBuffer, - lap: &mut Lap, - at: &mut Instant, - ) -> Result<()> { - let mut blit = command_buffer.blit_command_encoder()?; - lap.lap(at, Call::Open); - blit.copy_from_buffer_to_buffer(&self.words, 0, &self.copies, 0, self.words.length())?; - lap.lap(at, Call::Dispatch); - blit.end_encoding()?; - lap.lap(at, Call::End); - Ok(()) - } - - /// A render encoder of `command_buffer` that draws the triangles over the render shapes' - /// target, loaded or not, ended; with `laps`, its opening, pipeline state, vertex buffers, - /// draw and end timed as an encoder's opening, pipeline, bind, dispatch and end. - fn draw( - &self, - command_buffer: &CommandBuffer, - loaded: bool, - mut laps: Option<(&mut Lap, &mut Instant)>, - ) -> Result<()> { - let render = self.render.as_ref().ok_or("no render state")?; - let mut lap = |call: Call| { - if let Some((sum, at)) = laps.as_mut() { - sum.lap(at, call); - } - }; - let pass = match loaded { - true => &render.loaded, - false => &render.apart, - }; - let mut encoder = command_buffer.render_command_encoder(pass)?; - lap(Call::Open); - encoder.set_render_pipeline_state(&render.state)?; - lap(Call::Pipeline); - encoder.set_vertex_buffer(Some(&render.positions), 0, 0)?; - encoder.set_vertex_buffer(Some(&render.colors), 0, 1)?; - lap(Call::Bind); - encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)?; - lap(Call::Dispatch); - encoder.end_encoding()?; - lap(Call::End); - Ok(()) - } - - /// Copy the render shapes' target back and check each texel holds the triangles' color. - fn check_target(&self, name: &str) -> Result<()> { - let render = self.render.as_ref().ok_or("no render state")?; - let row = TARGET_SIDE * 4; - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_texture_to_buffer( - &render.target, - 0, - 0, - Origin::new(0, 0, 0), - Size::new(TARGET_SIDE, TARGET_SIDE, 1), - &render.readback, - 0, - row, - row * TARGET_SIDE, - BlitOption::None, - )?; - blit.end_encoding()?; - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| "the target's read back did not complete")?; - let contents = render.readback.contents().ok_or("no contents")?; - for at in 0..(TARGET_SIDE * TARGET_SIDE) as usize { - // SAFETY: the target's `readback` is `Shared`, as long as its texels, and no command - // buffer writes it while the CPU reads it. - let texel = unsafe { contents.as_ptr().cast::<[u8; 4]>().add(at).read_volatile() }; - if texel != DRAWN_TEXEL { - return Err(format!("{name}: texel {at} is {texel:?}, not {DRAWN_TEXEL:?}").into()); - } - } - Ok(()) - } - - fn fill(&self, value: u8) -> Result<()> { - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.fill_buffer(&self.words, 0..self.words.length(), value)?; - for zeros in self.zeros.iter().flatten() { - blit.fill_buffer(zeros, 0..zeros.length(), 0)?; - } - blit.end_encoding()?; - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| "the fill did not complete")?; - Ok(()) - } - - /// Copy the words back and check each is `want`; with `blits`, the last copy's too; with - /// `copies`, which dispatches nothing, the copies' alone, the words' zeros; with `renders` and - /// `renders-apart`, the last copy's and the target's too; with `passes`, which dispatches - /// nothing, the words' zeros and the target. - fn check(&self, want: u32, name: &str, shape: &Shape) -> Result<()> { - match name { - "copies" => self.check_words(&self.copies, 0, name, shape), - "blits" => { - self.check_words(&self.words, want, name, shape)?; - self.check_words(&self.copies, want, "blits' copies", shape) - } - "passes" => { - self.check_words(&self.words, 0, name, shape)?; - self.check_target(name) - } - "renders" | "renders-apart" => { - self.check_words(&self.words, want, name, shape)?; - self.check_words(&self.copies, want, "renders' copies", shape)?; - self.check_target(name) - } - _ => self.check_words(&self.words, want, name, shape), - } - } - - /// Copy `words` back and check each holds `want` dispatches' increments (those that covered - /// it, `Shape::want_at`). - fn check_words(&self, words: &Buffer, want: u32, name: &str, shape: &Shape) -> Result<()> { - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(words, 0, &self.readback, 0, words.length())?; - blit.end_encoding()?; - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| "the read back did not complete")?; - let contents = self.readback.contents().ok_or("no contents")?; - for at in 0..(self.words.length() / 4) as usize { - // SAFETY: `readback` is `Shared`, as long as `words`, and no command buffer writes it - // while the CPU reads it. - let word = unsafe { contents.as_ptr().cast::().add(at).read_volatile() }; - let want = shape.want_at(want, at); - if word != want { - return Err(format!("{name}: word {at} is {word}, not {want}").into()); - } - } - Ok(()) - } -} - -/// The raw shapes' Vulkan objects, on a `VkDevice` of their own over the runtime device's -/// physical device, whose instance they borrow. -struct Raw<'a> { - _runtime: &'a Device, - vk: ash::Device, - queue: vk::Queue, - pool: vk::CommandPool, - commands: Vec, - layout: vk::PipelineLayout, - set_layout: vk::DescriptorSetLayout, - descriptors: vk::DescriptorPool, - set: vk::DescriptorSet, - module: vk::ShaderModule, - pipeline: vk::Pipeline, - buffers: [(vk::Buffer, vk::DeviceMemory); 2], - bytes: u64, - mapped: *const u32, - queries: vk::QueryPool, - fence: vk::Fence, - period: f64, -} - -/// The least barrier between dispatches, a read after a write. -fn least() -> vk::MemoryBarrier<'static> { - vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE) -} - -impl<'a> Raw<'a> { - /// The objects, on a `VkDevice` made with one queue of the runtime device's primary family. - fn new(device: &'a Device, shape: &Shape) -> Result> { - // SAFETY: the handles are used while the runtime device lives (the result borrows it), - // and none of the runtime's objects is destroyed. - let handles = unsafe { device.raw() }; - let family = handles.queue_family; - let priorities = [1.0f32]; - let queues = [vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities)]; - // SAFETY: the instance's own physical device and a valid creation; the device is - // destroyed in `drop`, before the instance (which the runtime device holds) goes. - let vk = unsafe { - handles.instance.create_device( - handles.physical_device, - &vk::DeviceCreateInfo::default().queue_create_infos(&queues), - None, - ) - }?; - // SAFETY: the family and index were created. - let queue = unsafe { vk.get_device_queue(family, 0) }; - let text = SPIRV.replace("{T}", &shape.threads.to_string()); - let bytes = tool( - "spirv-as", - &["--target-env", "vulkan1.2", "-o", "-", "-"], - &text, - )?; - let code: Vec = (bytes.as_chunks::<4>().0.iter()) - .map(|word| u32::from_le_bytes(*word)) - .collect(); - let properties = - // SAFETY: the instance's own physical device. - unsafe { handles.instance.get_physical_device_properties(handles.physical_device) }; - let memory = - // SAFETY: as above. - unsafe { handles.instance.get_physical_device_memory_properties(handles.physical_device) }; - // SAFETY: every info below is valid and lives for its call; every object is of `vk`. - // Objects made before a failure here are not destroyed: the example ends on it. - unsafe { - let make_buffer = - |bytes: u64, usage, flags| -> Result<(vk::Buffer, vk::DeviceMemory)> { - let buffer = vk.create_buffer( - &vk::BufferCreateInfo::default().size(bytes).usage(usage), - None, - )?; - let requirements = vk.get_buffer_memory_requirements(buffer); - let index = (0..memory.memory_type_count) - .find(|&index| { - requirements.memory_type_bits & (1 << index) != 0 - && memory.memory_types[index as usize] - .property_flags - .contains(flags) - }) - .ok_or("no memory type for the buffer")?; - let allocation = vk.allocate_memory( - &vk::MemoryAllocateInfo::default() - .allocation_size(requirements.size) - .memory_type_index(index), - None, - )?; - vk.bind_buffer_memory(buffer, allocation, 0)?; - Ok((buffer, allocation)) - }; - let bytes = shape.words() * 4; - let words = make_buffer( - bytes, - vk::BufferUsageFlags::STORAGE_BUFFER - | vk::BufferUsageFlags::TRANSFER_SRC - | vk::BufferUsageFlags::TRANSFER_DST, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - )?; - let readback = make_buffer( - bytes, - vk::BufferUsageFlags::TRANSFER_DST, - vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, - )?; - let mapped = vk - .map_memory(readback.1, 0, bytes, vk::MemoryMapFlags::empty())? - .cast::(); - let binding = [vk::DescriptorSetLayoutBinding::default() - .binding(0) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .descriptor_count(1) - .stage_flags(vk::ShaderStageFlags::COMPUTE)]; - let set_layout = vk.create_descriptor_set_layout( - &vk::DescriptorSetLayoutCreateInfo::default().bindings(&binding), - None, - )?; - let layout = vk.create_pipeline_layout( - &vk::PipelineLayoutCreateInfo::default().set_layouts(&[set_layout]), - None, - )?; - let module = - vk.create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&code), None)?; - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(module) - .name(c"main"); - let pipeline = vk - .create_compute_pipelines( - vk::PipelineCache::null(), - &[vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(layout)], - None, - ) - .map_err(|(_, error)| error)?[0]; - let sizes = [vk::DescriptorPoolSize::default() - .ty(vk::DescriptorType::STORAGE_BUFFER) - .descriptor_count(1)]; - let descriptors = vk.create_descriptor_pool( - &vk::DescriptorPoolCreateInfo::default() - .max_sets(1) - .pool_sizes(&sizes), - None, - )?; - let set = vk.allocate_descriptor_sets( - &vk::DescriptorSetAllocateInfo::default() - .descriptor_pool(descriptors) - .set_layouts(&[set_layout]), - )?[0]; - let info = [vk::DescriptorBufferInfo::default() - .buffer(words.0) - .range(vk::WHOLE_SIZE)]; - vk.update_descriptor_sets( - &[vk::WriteDescriptorSet::default() - .dst_set(set) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .buffer_info(&info)], - &[], - ); - let pool = vk.create_command_pool( - &vk::CommandPoolCreateInfo::default().queue_family_index(family), - None, - )?; - let commands = vk.allocate_command_buffers( - &vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(2 * shape.dispatches + 2), - )?; - let queries = vk.create_query_pool( - &vk::QueryPoolCreateInfo::default() - .query_type(vk::QueryType::TIMESTAMP) - .query_count(2), - None, - )?; - let fence = vk.create_fence(&vk::FenceCreateInfo::default(), None)?; - Ok(Raw { - _runtime: device, - vk, - queue, - pool, - commands, - layout, - set_layout, - descriptors, - set, - module, - pipeline, - buffers: [words, readback], - bytes, - mapped, - queries, - fence, - period: f64::from(properties.limits.timestamp_period), - }) - } - } - - /// Submit `commands` and wait for them. - /// - /// # Safety - /// - /// Each is recorded and executable, and none is pending. - unsafe fn submit(&self, commands: &[vk::CommandBuffer]) -> Result<()> { - // SAFETY: the caller's contract; the queue is the caller's alone. - unsafe { - self.vk.queue_submit( - self.queue, - &[vk::SubmitInfo::default().command_buffers(commands)], - self.fence, - )?; - self.vk - .wait_for_fences(&[self.fence], true, WAIT.as_nanos() as u64)?; - self.vk.reset_fences(&[self.fence])?; - } - Ok(()) - } - - /// Begin `command` for one submission. - /// - /// # Safety - /// - /// `command` is of the pool, not pending. - unsafe fn begin(&self, command: vk::CommandBuffer) -> Result<()> { - let info = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the caller's contract. - unsafe { self.vk.begin_command_buffer(command, &info) }?; - Ok(()) - } - - /// Record a dispatch of the kernel into `command`. - /// - /// # Safety - /// - /// `command` is recording. - unsafe fn dispatch(&self, command: vk::CommandBuffer, shape: &Shape) { - // SAFETY: the caller's contract; the objects are live. - unsafe { - self.vk - .cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, self.pipeline); - self.vk.cmd_bind_descriptor_sets( - command, - vk::PipelineBindPoint::COMPUTE, - self.layout, - 0, - &[self.set], - &[], - ); - self.vk.cmd_dispatch(command, shape.groups, 1, 1); - } - } - - /// Record `barrier` from `src` stages to `dst` stages into `command`. - /// - /// # Safety - /// - /// `command` is recording. - unsafe fn barrier( - &self, - command: vk::CommandBuffer, - (src, dst, barrier): ( - vk::PipelineStageFlags, - vk::PipelineStageFlags, - vk::MemoryBarrier, - ), - ) { - // SAFETY: the caller's contract. - unsafe { - self.vk.cmd_pipeline_barrier( - command, - src, - dst, - vk::DependencyFlags::empty(), - &[barrier], - &[], - &[], - ); - } - } - - /// One run of `name`: its GPU time per dispatch in microseconds. - fn run(&self, name: &str, shape: &Shape) -> Result { - let compute = vk::PipelineStageFlags::COMPUTE_SHADER; - let barrier = match name { - "raw-wide" => Some(( - compute, - compute | vk::PipelineStageFlags::DRAW_INDIRECT, - vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask( - vk::AccessFlags::SHADER_READ - | vk::AccessFlags::SHADER_WRITE - | vk::AccessFlags::UNIFORM_READ - | vk::AccessFlags::INDIRECT_COMMAND_READ, - ), - )), - "raw-uniform" => Some(( - compute, - compute, - least().dst_access_mask( - vk::AccessFlags::SHADER_READ - | vk::AccessFlags::SHADER_WRITE - | vk::AccessFlags::UNIFORM_READ, - ), - )), - "raw-indirect" => Some(( - compute, - compute | vk::PipelineStageFlags::DRAW_INDIRECT, - least().dst_access_mask( - vk::AccessFlags::SHADER_READ - | vk::AccessFlags::SHADER_WRITE - | vk::AccessFlags::INDIRECT_COMMAND_READ, - ), - )), - "raw-none" => None, - _ => Some((compute, compute, least())), - }; - let split = name == "raw-split"; - // SAFETY: every command buffer is of the pool, none pending (each run waits for its - // submission), and the pool is reset before they are recorded again. - unsafe { - self.vk - .reset_command_pool(self.pool, vk::CommandPoolResetFlags::empty())?; - let first = self.commands[0]; - self.begin(first)?; - self.vk.cmd_reset_query_pool(first, self.queries, 0, 2); - self.vk.cmd_write_timestamp( - first, - vk::PipelineStageFlags::TOP_OF_PIPE, - self.queries, - 0, - ); - let mut used = vec![first]; - let mut current = first; - for n in 0..shape.dispatches as usize { - if split { - self.vk.end_command_buffer(current)?; - current = self.commands[1 + 2 * n]; - self.begin(current)?; - used.push(current); - } - if let (Some(barrier), true) = (barrier, n > 0) { - self.barrier(current, barrier); - } - if split { - self.vk.end_command_buffer(current)?; - current = self.commands[2 + 2 * n]; - self.begin(current)?; - used.push(current); - } - self.dispatch(current, shape); - } - self.vk.cmd_write_timestamp( - current, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - self.queries, - 1, - ); - self.vk.end_command_buffer(current)?; - std::thread::sleep(shape.idle); - self.submit(&used)?; - let mut stamps = [0u64; 2]; - self.vk.get_query_pool_results( - self.queries, - 0, - &mut stamps, - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, - )?; - let nanos = stamps[1].wrapping_sub(stamps[0]) as f64 * self.period; - Ok(nanos / 1e3 / f64::from(shape.dispatches)) - } - } - - /// Fill the words with `value`, or copy them back. - fn transfer(&self, fill: Option) -> Result<()> { - let command = self.commands[0]; - // SAFETY: as `run`. - unsafe { - self.vk - .reset_command_pool(self.pool, vk::CommandPoolResetFlags::empty())?; - self.begin(command)?; - match fill { - Some(value) => { - self.vk - .cmd_fill_buffer(command, self.buffers[0].0, 0, vk::WHOLE_SIZE, value) - } - None => { - let to_copy = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask(vk::AccessFlags::TRANSFER_READ); - self.barrier( - command, - ( - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::PipelineStageFlags::TRANSFER, - to_copy, - ), - ); - let region = vk::BufferCopy::default().size(self.bytes); - self.vk.cmd_copy_buffer( - command, - self.buffers[0].0, - self.buffers[1].0, - &[region], - ); - let to_host = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ); - self.barrier( - command, - ( - vk::PipelineStageFlags::TRANSFER, - vk::PipelineStageFlags::HOST, - to_host, - ), - ); - } - } - if fill.is_some() { - let to_compute = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE); - self.barrier( - command, - ( - vk::PipelineStageFlags::TRANSFER, - vk::PipelineStageFlags::COMPUTE_SHADER, - to_compute, - ), - ); - } - self.vk.end_command_buffer(command)?; - self.submit(&[command])?; - } - Ok(()) - } -} - -impl Drop for Raw<'_> { - fn drop(&mut self) { - // SAFETY: nothing is pending (each submission was waited for), and every object is this - // example's own. - unsafe { - self.vk.destroy_fence(self.fence, None); - self.vk.destroy_query_pool(self.queries, None); - self.vk.destroy_command_pool(self.pool, None); - self.vk.destroy_descriptor_pool(self.descriptors, None); - self.vk.destroy_pipeline(self.pipeline, None); - self.vk.destroy_shader_module(self.module, None); - self.vk.destroy_pipeline_layout(self.layout, None); - self.vk.destroy_descriptor_set_layout(self.set_layout, None); - for (buffer, memory) in self.buffers { - self.vk.destroy_buffer(buffer, None); - self.vk.free_memory(memory, None); - } - self.vk.destroy_device(None); - } - } -} - -/// An automatic `Private` heap with room for `count` buffers of `bytes` and `kept` of 256, its -/// bytes zeroed by a buffer over all of them that a blit fills and that goes after. -fn zeroed_heap(device: &Device, bytes: u64, count: u32, kept: u32) -> Result { - let need = device.heap_buffer_size_and_align(bytes, ResourceOptions::private()); - let small = device.heap_buffer_size_and_align(256, ResourceOptions::private()); - let size = need.size.next_multiple_of(need.align) * u64::from(count) - + small.size.next_multiple_of(small.align) * u64::from(kept); - let descriptor = HeapDescriptor::new(HeapType::Automatic, size, ResourceOptions::private()); - let heap = device.new_heap(&descriptor)?; - let whole = heap.new_buffer(heap.size(), ResourceOptions::private())?; - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.fill_buffer(&whole, 0..whole.length(), 0)?; - blit.end_encoding()?; - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| "the heap's fill did not complete")?; - Ok(heap) -} - -fn main() -> Result<()> { - let shape = Shape::from_args()?; - let device = Device::system_default_with(&DeviceOptions::default())?; - let name = device.name().to_string(); - println!("device: {name}"); - let bytes = shape.words() * 4; - // A moved binding reads the zeros past its offset. - let zeros = match shape.binds { - Binds::Moved | Binds::Fixed => bytes + MOVE_STRIDE * MOVES, - _ => bytes, - }; - // Each pair of zeros of class `z` is `2^z` times the least pair's length. - let lengths: Vec = std::iter::once(bytes) - .chain((0..shape.zero_classes).flat_map(|z| [zeros << z; 2])) - .collect(); - let placed = match shape.heap { - true => Some(Placed::new(&device, &lengths)?), - false => None, - }; - let mut place = 0; - let mut buffer = |bytes: u64| -> Result { - if let Some(placed) = &placed { - place += 1; - return placed.buffer(place - 1); - } - if !shape.pages { - return Ok(device.new_buffer(bytes, ResourceOptions::private())?); - } - // SAFETY: page-aligned read-write memory of `bytes` bytes, never unmapped, which outlives - // the buffer. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(host_pages(bytes as usize)?), - bytes, - ResourceOptions::shared(), - None, - ) - }?; - Ok(buffer) - }; - let texture = || -> Result { - let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false); - descriptor.usage = TextureUsage::SHADER_READ; - descriptor.resource_options = ResourceOptions::private(); - Ok(device.new_texture(&descriptor)?) - }; - let churn = match shape.churn { - None => None, - Some(count) => Some(zeroed_heap(&device, bytes, count, shape.kept)?), - }; - // The heap's other buffers, listed among the device's live ones through the runs. - let kept: std::result::Result, _> = (churn.iter()) - .flat_map(|heap| (0..shape.kept).map(|_| heap.new_buffer(256, ResourceOptions::private()))) - .collect(); - let _kept = kept?; - // The program's other buffers, listed among the device's live ones through the runs. - let live: std::result::Result, _> = (0..shape.live) - .map(|_| device.new_buffer(256, ResourceOptions::private())) - .collect(); - let _live = live?; - // The program's other sampler states, distinct, alive through the runs. - let samplers: std::result::Result, _> = (0..shape.samplers) - .map(|n| { - let mut descriptor = SamplerDescriptor::new(); - descriptor.lod_max_clamp = 1.0 + n as f32; - device.new_sampler_state(&descriptor) - }) - .collect(); - let _samplers = samplers?; - let ours = Ours { - device: &device, - states: states(&device, shape.binds, shape.states)?, - words: buffer(lengths[0])?, - zeros: (lengths[1..].chunks(2)) - .map(|pair| Ok([buffer(pair[0])?, buffer(pair[1])?])) - .collect::>()?, - ones: (0..shape.classes) - .map(|class| { - ones( - &device, - class, - shape.pages && matches!(shape.binds, Binds::TexMoved), - ) - }) - .collect::>()?, - picks: shape.picks(), - textures: [texture()?, texture()?], - sampler: device.new_sampler_state(&SamplerDescriptor::new())?, - params: params_buffer(&device)?, - readback: device.new_buffer(bytes, ResourceOptions::shared())?, - copies: device.new_buffer(bytes, ResourceOptions::private())?, - churn, - render: match RENDER_SHAPES.iter().any(|(name, _)| shape.runs(name)) { - true => Some(Render::new(&device)?), - false => None, - }, - }; - for shape_name in [ - "encoders", - "blits", - "copies", - "renders", - "renders-apart", - "passes", - "serial", - "concurrent", - "barriers", - ] { - match (shape.runs(shape_name), shape.host) { - (false, _) => {} - (true, Some(command_buffers)) => { - ours.host_shape(shape_name, &shape, command_buffers)? - } - (true, None) => ours.shape(shape_name, &shape, &name)?, - } - } - if shape.host.is_some() { - return Ok(()); - } - let raw = Raw::new(&device, &shape)?; - for shape_name in [ - "raw-barrier", - "raw-uniform", - "raw-indirect", - "raw-wide", - "raw-split", - "raw-none", - ] { - if !shape.runs(shape_name) { - continue; - } - raw.transfer(Some(0))?; - let mut samples = Samples::default(); - for run in 0..=shape.runs { - let per = raw.run(shape_name, &shape)?; - if run > 0 { - samples.per_dispatch.push(per); - } - } - if shape_name != "raw-none" { - raw.transfer(None)?; - let want = shape.dispatches * (shape.runs as u32 + 1); - for at in 0..shape.words() as usize { - // SAFETY: the mapped read-back, as long as the words, written by the copy the - // transfer waited for. - let word = unsafe { raw.mapped.add(at).read_volatile() }; - if word != want { - return Err(format!("{shape_name}: word {at} is {word}, not {want}").into()); - } - } - } - samples.print(shape_name, &shape, &name); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/draw_costs.metal b/crates/metal2vulkan-runtime/examples/draw_costs.metal deleted file mode 100644 index 02916a02f..000000000 --- a/crates/metal2vulkan-runtime/examples/draw_costs.metal +++ /dev/null @@ -1,140 +0,0 @@ -// The draw_costs example's functions (examples/draw_costs.rs), shaped as a guest's draws: a -// vertex function whose positions come from vertex buffer 0 by vertex and whose colour comes from -// buffer 1; a fragment function that returns fragment buffer 0's first value, and one that samples -// texture 0 with sampler 0. -#include -using namespace metal; - -struct DrawCostsOut { - float4 position [[position]]; - float4 colour; -}; - -vertex DrawCostsOut draw_costs_vertex(uint vid [[vertex_id]], - const device float4 *positions [[buffer(0)]], - const device float4 *colours [[buffer(1)]]) { - DrawCostsOut out; - out.position = positions[vid]; - out.colour = colours[0]; - return out; -} - -fragment float4 draw_costs_buffer(DrawCostsOut in [[stage_in]], - const device float4 *colour [[buffer(0)]]) { - return colour[0] * in.colour; -} - -fragment float4 draw_costs_texture(DrawCostsOut in [[stage_in]], - texture2d source [[texture(0)]], - sampler linear [[sampler(0)]]) { - return source.sample(linear, in.position.xy / 64.0) * in.colour; -} - -// The compositor shape's functions: a quad's corner (a position in [0, 1] and its texture -// coordinate) from vertex buffer 0 by vertex, placed by buffer 1's scale and offset; fragments -// that sample texture 0 tinted by fragment buffer 0, masked by texture 1's alpha, or blended over -// texture 1 read at the fragment's own pixel (the pass's own color attachment, a backdrop). -struct DrawCostsCorner { - float2 position; - float2 uv; -}; - -struct DrawCostsPlace { - float2 scale; - float2 offset; -}; - -struct DrawCostsQuad { - float4 position [[position]]; - float2 uv; -}; - -vertex DrawCostsQuad draw_costs_quad_vertex(uint vid [[vertex_id]], - const device DrawCostsCorner *corners [[buffer(0)]], - constant DrawCostsPlace &place [[buffer(1)]]) { - DrawCostsCorner corner = corners[vid]; - DrawCostsQuad out; - out.position = float4(corner.position * place.scale + place.offset, 0.0, 1.0); - out.uv = corner.uv; - return out; -} - -fragment float4 draw_costs_quad(DrawCostsQuad in [[stage_in]], - texture2d source [[texture(0)]], - sampler linear [[sampler(0)]], - constant float4 &tint [[buffer(0)]]) { - return source.sample(linear, in.uv) * tint; -} - -fragment float4 draw_costs_quad_masked(DrawCostsQuad in [[stage_in]], - texture2d source [[texture(0)]], - texture2d mask [[texture(1)]], - sampler linear [[sampler(0)]], - constant float4 &tint [[buffer(0)]]) { - return source.sample(linear, in.uv) * tint * mask.sample(linear, in.uv).a; -} - -fragment float4 draw_costs_quad_backdrop(DrawCostsQuad in [[stage_in]], - texture2d source [[texture(0)]], - texture2d backdrop [[texture(1)]], - sampler linear [[sampler(0)]], - constant float4 &tint [[buffer(0)]]) { - float4 colour = source.sample(linear, in.uv) * tint; - float4 under = backdrop.read(uint2(in.position.xy)); - return float4(mix(under.rgb, colour.rgb, colour.a), 1.0); -} - -// The scene shape's functions, a 3D engine's draws into four colors: a vertex (a position and a -// texture coordinate, from vertex buffer 0 through the pipeline's vertex descriptor) placed by -// buffer 1's transform; fragments that sample eight textures, each with a sampler of its own, -// scaled by fragment buffer 0's material. -struct DrawCostsSceneVertex { - float3 position [[attribute(0)]]; - float2 uv [[attribute(1)]]; -}; - -struct DrawCostsSceneOut { - float4 position [[position]]; - float2 uv; -}; - -vertex DrawCostsSceneOut draw_costs_scene_vertex(DrawCostsSceneVertex in [[stage_in]], - constant float4x4 &transform [[buffer(1)]]) { - DrawCostsSceneOut out; - out.position = transform * float4(in.position, 1.0); - out.uv = in.uv; - return out; -} - -struct DrawCostsSceneColors { - float4 albedo [[color(0)]]; - float4 normal [[color(1)]]; - float4 material [[color(2)]]; - float4 lit [[color(3)]]; -}; - -fragment DrawCostsSceneColors draw_costs_scene(DrawCostsSceneOut in [[stage_in]], - constant float4 &scale [[buffer(0)]], - texture2d t0 [[texture(0)]], - texture2d t1 [[texture(1)]], - texture2d t2 [[texture(2)]], - texture2d t3 [[texture(3)]], - texture2d t4 [[texture(4)]], - texture2d t5 [[texture(5)]], - texture2d t6 [[texture(6)]], - texture2d t7 [[texture(7)]], - sampler s0 [[sampler(0)]], - sampler s1 [[sampler(1)]], - sampler s2 [[sampler(2)]], - sampler s3 [[sampler(3)]], - sampler s4 [[sampler(4)]], - sampler s5 [[sampler(5)]], - sampler s6 [[sampler(6)]], - sampler s7 [[sampler(7)]]) { - DrawCostsSceneColors out; - out.albedo = t0.sample(s0, in.uv) * t1.sample(s1, in.uv) * scale; - out.normal = t2.sample(s2, in.uv) + t3.sample(s3, in.uv); - out.material = t4.sample(s4, in.uv) * t5.sample(s5, in.uv); - out.lit = t6.sample(s6, in.uv) + t7.sample(s7, in.uv) * scale.w; - return out; -} diff --git a/crates/metal2vulkan-runtime/examples/draw_costs.rs b/crates/metal2vulkan-runtime/examples/draw_costs.rs deleted file mode 100644 index 3b5a599d0..000000000 --- a/crates/metal2vulkan-runtime/examples/draw_costs.rs +++ /dev/null @@ -1,2311 +0,0 @@ -//! Not a consumer's example: what a draw costs the thread that encodes it, in four shapes of a -//! consumer's render work (a guest's command buffers as its host replays them on the runtime), -//! through the runtime's public calls alone, on one thread. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example draw_costs [-- [ws|many|10k|clips|damage|compositor|backdrops|pass1|pass17|scene|rebinds|restated|moved|guest|splits]... [--runs N] [--calls] [--counts] [--heap] [--shadowed] [--pages] [--states N] [--worker] [--threads N] [--metallib PATH]] -//! ``` -//! -//! Each shape is command buffers committed back to back, each of one render pass over a 512x512 -//! `BGRA8Unorm` target, cleared and stored. A command buffer's pass sets the first pipeline state -//! and a constants buffer at vertex index 1 and fragment index 0, then draws: -//! -//! - **ws**, a compositor's frames: 8 command buffers of 500 draws. Each draw is a 4-vertex -//! triangle strip after `set_fragment_texture` (one of 16 64x64 textures), `set_fragment_buffer` -//! and `set_vertex_buffer`, each buffer at a 256-byte slot of its own; every 4 draws, -//! `set_render_pipeline_state` (the next of 4) and `set_fragment_sampler_states` again. -//! - **many**, a guest's frame in short command buffers: 64 command buffers of 16 draws, each a -//! `set_vertex_buffer` at the next slot and a 3-vertex triangle list. -//! - **10k**: 3 command buffers of 10,000 such draws. -//! - **clips**, a compositor's frames under clips: 8 command buffers of 500 draws, each a 4-vertex -//! triangle strip after `set_vertex_buffer` at the next slot; before every second one, -//! `set_scissor_rect` (the top half of the target, then the bottom, in turn); every 4 draws -//! instead `set_render_pipeline_state` (the next of 4), `set_fragment_sampler_states` and -//! `set_fragment_texture` (the next of 16). -//! - **damage**, a compositor's frames of damaged rectangles: as **clips**, but each draw after a -//! `set_scissor_rect` of its own, the next cell of a grid of 25 by 20 cells of 20x25 pixels, so -//! a pass's 500 draws are bounded by 500 rectangles. -//! - **compositor**, a window compositor's frame as the consumer's per-draw table measures it: -//! 8 command buffers of 6 passes and 35 draws. Five passes each load a layer's surface -//! (1600x1000, 1280x800, 1024x768, 800x600, 512x512) and draw 4 quads into it, then one clears -//! a 3840x2400 framebuffer surface and draws 15. Every surface is `BGRA8Unorm`, a texture over -//! its own buffer's one IOSurface plane at packed rows (`new_texture_with_iosurface_plane`): -//! a `Private` buffer, as a host keeps a surface's device copy, or with `--pages` a no-copy -//! buffer over host pages of its own. Each pass begins with `set_viewport`; each draw sets the -//! pipeline state where its kind differs from the last draw's (plain, masked or backdrop, each -//! blended), vertex buffers 0 (corners) and 1 (placement) and fragment buffer 0 (a tint) at -//! slots of one no-copy buffer over host pages that move every draw, fragment texture 0 (one -//! of 12 sampled surfaces: a 3840x2400 desktop picture, then windows of 1920x1200, 1024x768, -//! 512x512 and 256x256), a masked draw's texture 1 (another of them) or a backdrop draw's -//! (its own pass's color attachment, read at the fragment's pixel), a sampler and a scissor -//! rectangle, then draws 6 vertices, three draws of five indexed (`UInt16`). One draw in each -//! pass is a backdrop. -//! - **backdrops**: as **compositor**, but every draw a backdrop, each under its own scissor -//! rectangle: a draw reads its pass's color through its copy at its fragments' own pixels -//! (`texture/attached_reads.rs`), bounded to the texels around its scissor, other bounds than -//! the draw's before it. -//! - **pass1** and **pass17**, a window server's frame of many small passes as it composites a -//! view of icons: 8 command buffers of 16 passes of 1 draw, and of 4 passes of 17 draws. Each -//! pass loads and stores one of 8 surfaces of 256x256 over buffers of their own as the -//! compositor's are (`--pages` too), sets its viewport and draws the compositor's plain quads, -//! each after the pipeline state (once a pass: the next of 20 plain ones of their own blend -//! factors, so the state a pass draws through is none of the sixteen the last passes drew -//! through, and its first draw takes every step, no kept draw of its state carried in; with -//! `--states N`, the first N of them), its -//! vertex buffers 0 and 1 and fragment buffer 0, fragment texture 0 (the next of its sampled -//! surfaces), its sampler and a scissor rectangle. A pass's cost is the first's figure a draw -//! less the draw's, which the second's gives: (17 draws and a pass) less (1 draw and a pass), -//! over 16. -//! - **scene**, a 3D engine's frame as a layer over another graphics API issues it: 8 command -//! buffers of 10 passes and 24 draws each, every pass over the same four 512x512 color -//! targets (`BGRA8Unorm`, `RGBA8Unorm` and two `RGBA16Float`), the first cleared, the rest -//! loaded, all stored. Each pass binds vertex buffer 0 (a mesh's vertices, read through the -//! pipeline's vertex descriptor), vertex buffer 1 (transforms) and fragment buffer 0 (material -//! scales), all in one no-copy buffer over host pages. Every 4 draws a material of 6 takes -//! its turn: the pipeline state (one of 2), `set_fragment_textures` (its 8 of 48 textures, -//! 64x64, 32x32 or 16x16 by material, each with its whole mipmap chain) and -//! `set_fragment_sampler_states` (8 samplers of their own filters and address modes). Each draw moves buffer 1's and fragment buffer 0's offsets to its own slots -//! (`set_vertex_buffer_offset`, `set_fragment_buffer_offset`), then draws one of 64 pieces of -//! the mesh by 6 indices (`UInt16`) at the piece's offset. -//! - **rebinds**: as **scene**, but each draw first binds its material's 8 textures and 8 -//! samplers again, the same objects within a material's run. -//! - **restated**: as **scene**, but each draw first sets a scissor rectangle of its own, the -//! next cell of **damage**'s grid, so nearly every draw is its pipeline state's kept draw -//! rebound with its scissor restated, its offsets moved and its own indices. -//! - **moved**: as **restated**, but each pass sets one material's pipeline state, textures and -//! samplers once, before its first draw, so every later draw of the pass changes only its -//! scissor rectangle, its offsets and its indices. -//! - **guest**, a guest's command buffers of a few render encoders: 16 command buffers of 4 -//! passes over the target (the first cleared, the rest loaded) of 8 draws each. Each draw is a -//! 4-vertex triangle strip after `set_fragment_texture` (the next of 16), `set_vertex_buffer` at -//! its slot, then 16 bytes of `set_vertex_bytes` at index 1 and of `set_fragment_bytes` at -//! index 0, each its own; every second draw first `set_render_pipeline_state` (the next of 4) -//! and `set_fragment_sampler_states`. -//! - **splits**, a guest's render encoders that split their pass: 8 command buffers of 8 passes -//! over the target (the first cleared, the rest loaded) of 4 draws each, every pass after the -//! constants buffer and the sampler. Its first draw is through the first pipeline state; then -//! `memory_barrier_with_scope` over the render targets, fragment to fragment, and a draw of the -//! fourth state sampling the target itself, which splits the pass; then a draw of the second -//! state and one of the third, each after `set_fragment_texture` (the next of 16). Each -//! draw is a 4-vertex triangle strip after `set_vertex_buffer` at its slot. Every pass after a -//! command buffer's first opens from the kept draws the pass before it carried, the second and -//! third states' undrawn before its split. -//! -//! The slots lie in 64 KiB no-copy buffers over host pages (`new_buffer_with_bytes_no_copy`), as -//! a guest's upload chunks do, each command buffer's in chunks of its own. With `--heap`, the -//! chunks are instead buffers placed at their offsets in one `Placement` heap over the pages -//! (`new_heap_with_bytes_no_copy`, then `new_buffer_at_offset`), as the consumer places a guest's -//! upload chunks in a heap over the guest's own RAM, beside a no-copy buffer over pages that hold -//! the heap's and one chunk more, which stands for the guest RAM's own key over them: the -//! heap's bytes meet it, so each use of them takes a use of it too (`host_aliases.rs`'s -//! placements), as the guest RAM's do. A command buffer ends -//! with `end_encoding`, `add_completed_handler` and `commit`. The four pipeline states pair one -//! vertex function (positions from vertex buffer 0, a colour from buffer 1) with a fragment -//! function that returns fragment buffer 0's first value or samples texture 0 with sampler 0, -//! each opaque and blended over (`draw_costs.metal`). The device is opened with GPU times from -//! the host's clock and a message sink, the rest at its defaults. -//! -//! With `METAL2VULKAN_LOG_SHADOWS=1` (`metal2vulkan::env_vars`), each shadow the device makes is -//! printed on stderr with why, and so is each degrade notice's text. -//! -//! With `--worker`, the device lowers render encoders' calls on its lowering thread -//! (`RenderLoweringPolicy::Worker`), after each call returned. -//! -//! With `--shadowed`, the target is a texture over a no-copy buffer of host pages, as a guest's -//! window surface is, each pass loading it rather than clearing it, and the device is opened with -//! `HostPageTexturePolicy::Shadow`, so the target is a shadow on every device: each pass's end -//! plans its copy back, and counts its tiles against its draws' scissor rectangles -//! (`WorkCounts::shadow_attachment_tiles_covered`). -//! -//! A run is 2 untimed repetitions then 6 counted ones. Each repetition counts the calling -//! thread's CPU time and its instructions and cycles from the first command buffer's creation -//! through the last commit, then waits for every command buffer's handler outside the count, and -//! the process's page faults and voluntary context switches meanwhile (`getrusage`). On Linux, -//! the process's threads' CPU time over the counted repetitions, their waits included, is also -//! printed per draw by thread name (`DRAW-THREAD` lines, from each thread's `schedstat`, the -//! kernel's time on its behalf included; a thread that ended meanwhile is not counted; unnamed -//! threads under the program's name): the encoding thread's (`encoding`) against the runtime's own -//! threads' (its scheduler's submissions, its handler threads') and the driver's. On macOS the instructions and cycles are libSystem's -//! `thread_selfcounts` (readable unprivileged), which hold the kernel's where it ran on the -//! thread; on Linux they are the thread's own user-space counts -//! (`perf_event_open`, where `kernel.perf_event_paranoid` is at most 2; on a hybrid Intel CPU its -//! performance cores' counters alone, so pin the run there with `taskset`), with its L1 data -//! cache's read misses and its cache misses (`PERF_COUNT_HW_CACHE_MISSES`: the L2 on AMD's Zen, -//! the last-level cache on Intel's), what its memory touches cost it. Printed per shape and -//! figure: the figure a draw, the median over the runs with the lowest and the highest -//! (`DRAW-COST` lines). Instructions are the figure to compare between builds: a busy host moves -//! them little where it moves time. The thread asks for the performance cores -//! (`QOS_CLASS_USER_INTERACTIVE`). -//! -//! With `--threads N`, N threads encode at once on the one device and queue, each its own command -//! buffers of the shape over chunks of its own (in the one heap, with `--heap`), every repetition -//! started together, as the consumer walks a queue's command buffers on threads of their own: -//! each figure is then the threads' together a draw, so a cost that grows with the threads is -//! work they contend on (a lock, a counter every thread writes). -//! -//! With `--calls`, a run also counts each call's instructions apart, reading the counters around -//! each call (the read's own cost, measured as the run starts, taken off): printed per call -//! (`DRAW-CALL` lines), its calls a draw, its instructions a call and its share of a draw, the -//! median over the runs, with the lowest and highest a call, and its median cycles and cache -//! misses a call (no misses where the system counts none). The reads cost the totals their own -//! instructions, so a run's totals are read without `--calls`. -//! -//! With `--counts`, each shape's runs are bracketed by the device's work counts -//! (`Device::work_counts`), printed whole before and after (`WORK-COUNTS` lines) with the draws -//! between, warm repetitions included. -//! -//! The library is the metallib `--metallib` names, or else `draw_costs.metal` compiled by -//! `xcrun metal` in a scratch directory, removed once read. - -use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::device::{HostPageTexturePolicy, RenderLoweringPolicy}; -use metal2vulkan::metal::{ - BarrierScope, BlendFactor, IndexType, PixelFormat, PrimitiveType, RenderStages, - SamplerAddressMode, SamplerMinMagFilter, TextureUsage, VertexFormat, -}; -use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource, VertexAttributeDescriptor, - VertexBufferLayoutDescriptor, VertexDescriptor, -}; -use metal2vulkan_runtime::{ - Buffer, ClearColor, CommandBuffer, CommandBufferStatus, CommandQueue, Device, DeviceOptions, - Heap, HeapDescriptor, HeapType, HostMemory, IoSurfacePlane, Library, LoadAction, MessageSink, - PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, SamplerState, - ScissorRect, StoreAction, Texture, TextureDescriptor, Viewport, -}; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{mpsc, Barrier}; -use std::time::Duration; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// A run's untimed repetitions, then its counted ones; the runs by default. -const WARM: usize = 2; -const COUNTED: usize = 6; -const RUNS: usize = 9; - -/// An upload chunk's bytes, and each draw's slot in it. -const CHUNK: u64 = 0x1_0000; -const SLOT: u64 = 256; - -/// A compositor's pipeline states and textures, and the draws a pipeline state runs for. -const PIPELINES: usize = 4; -const TEXTURES: usize = 16; -const RUN: usize = 4; - -/// The target's side, and a texture's. -const SIDE: u64 = 512; -const TEXTURE_SIDE: u64 = 64; - -/// The longest a repetition waits for a command buffer's handler. -const WAIT: Duration = Duration::from_secs(30); - -/// The notices the device's sink heard. -static NOTICES: AtomicU64 = AtomicU64::new(0); - -/// What a shape's draws set. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Stream { - /// Each draw a vertex buffer at its slot, one pipeline state. - Bytes, - /// A compositor's: each draw a texture and its fragment and vertex slots, the pipeline state - /// and the sampler again every [`RUN`] draws. - Layers, - /// A compositor's under clips: each draw its vertex slot, every second one a scissor - /// rectangle of [`CLIPS`] before it, and every [`RUN`] draws instead the pipeline state, the - /// sampler and a texture again. - Clipped, - /// A compositor's under damaged rectangles: as [`Stream::Clipped`], each draw after a - /// scissor rectangle of its own ([`damaged`]). - Damaged, - /// A window compositor's frame of passes over surfaces ([`Compositor`]), each draw a backdrop - /// where `backdrops`. - Composited { backdrops: bool }, - /// A window server's frame of small passes of this many draws each, over the compositor's - /// objects ([`Compositor::small_passes`]). - Passes(usize), - /// A 3D engine's frame of passes over four color targets ([`Scene`]), each draw binding its - /// material's textures and samplers again where `rebinds`, and setting a scissor rectangle - /// of its own ([`damaged`]) where `scissors`; a material runs for `run` draws. - Scene { - rebinds: bool, - scissors: bool, - run: usize, - }, - /// A guest's: [`GUEST_PASSES`] passes of [`GUEST_PASS_DRAWS`] draws, each draw a texture, its - /// vertex slot and its vertex and fragment bytes, every second one the pipeline state and the - /// sampler again ([`Bench::guest_steps`]). - Guest, - /// Passes of [`SPLIT_PASS_DRAWS`] draws that split after their first ([`Bench::split_steps`]). - Splits, -} - -/// A splits shape's draws a pass. -const SPLIT_PASS_DRAWS: usize = 4; - -/// A guest shape's passes a command buffer, and a pass's draws. -const GUEST_PASSES: usize = 4; -const GUEST_PASS_DRAWS: usize = 8; - -/// The columns of the grid of damaged rectangles a [`Stream::Damaged`] pass's draws take in turn, -/// and a cell's side in pixels. -const DAMAGE_COLUMNS: u64 = 25; -const DAMAGE_CELL: [u64; 2] = [20, 25]; - -/// Draw `draw`'s scissor rectangle in a [`Stream::Damaged`] pass: the next cell of the grid. -fn damaged(draw: usize) -> ScissorRect { - let (column, row) = (draw as u64 % DAMAGE_COLUMNS, draw as u64 / DAMAGE_COLUMNS); - ScissorRect { - x: column * DAMAGE_CELL[0], - y: row * DAMAGE_CELL[1] % SIDE, - width: DAMAGE_CELL[0], - height: DAMAGE_CELL[1], - } -} - -/// The scissor rectangles a clipped stream's draws take in turn: the target's top half, then its -/// bottom half. -const CLIPS: [ScissorRect; 2] = [ - ScissorRect { - x: 0, - y: 0, - width: SIDE, - height: SIDE / 2, - }, - ScissorRect { - x: 0, - y: SIDE / 2, - width: SIDE, - height: SIDE / 2, - }, -]; - -/// Command buffers of `draws` draws of `stream`'s each. -#[derive(Clone, Copy)] -struct Shape { - name: &'static str, - buffers: usize, - draws: usize, - stream: Stream, -} - -/// The shapes, in the order they run. -const SHAPES: [Shape; 15] = [ - Shape { - name: "ws", - buffers: 8, - draws: 500, - stream: Stream::Layers, - }, - Shape { - name: "many", - buffers: 64, - draws: 16, - stream: Stream::Bytes, - }, - Shape { - name: "10k", - buffers: 3, - draws: 10_000, - stream: Stream::Bytes, - }, - Shape { - name: "clips", - buffers: 8, - draws: 500, - stream: Stream::Clipped, - }, - Shape { - name: "damage", - buffers: 8, - draws: 500, - stream: Stream::Damaged, - }, - Shape { - name: "compositor", - buffers: 8, - draws: COMPOSITOR_DRAWS, - stream: Stream::Composited { backdrops: false }, - }, - Shape { - name: "backdrops", - buffers: 8, - draws: COMPOSITOR_DRAWS, - stream: Stream::Composited { backdrops: true }, - }, - Shape { - name: "pass1", - buffers: 8, - draws: 16, - stream: Stream::Passes(1), - }, - Shape { - name: "pass17", - buffers: 8, - draws: 4 * 17, - stream: Stream::Passes(17), - }, - Shape { - name: "scene", - buffers: 8, - draws: SCENE_DRAWS, - stream: Stream::Scene { - rebinds: false, - scissors: false, - run: SCENE_RUN, - }, - }, - Shape { - name: "rebinds", - buffers: 8, - draws: SCENE_DRAWS, - stream: Stream::Scene { - rebinds: true, - scissors: false, - run: SCENE_RUN, - }, - }, - Shape { - name: "restated", - buffers: 8, - draws: SCENE_DRAWS, - stream: Stream::Scene { - rebinds: false, - scissors: true, - run: SCENE_RUN, - }, - }, - Shape { - name: "moved", - buffers: 8, - draws: SCENE_DRAWS, - stream: Stream::Scene { - rebinds: false, - scissors: true, - run: SCENE_PASS_DRAWS, - }, - }, - Shape { - name: "guest", - buffers: 16, - draws: GUEST_PASSES * GUEST_PASS_DRAWS, - stream: Stream::Guest, - }, - Shape { - name: "splits", - buffers: 8, - draws: 8 * SPLIT_PASS_DRAWS, - stream: Stream::Splits, - }, -]; - -impl Shape { - /// The slots a draw takes: its vertex bytes, and its fragment bytes in a compositor's stream. - fn slots(self) -> u64 { - match self.stream { - Stream::Bytes | Stream::Clipped | Stream::Damaged | Stream::Guest | Stream::Splits => 1, - Stream::Layers => 2, - // Its slots lie in the compositor's or the scene's own buffer. - Stream::Composited { .. } | Stream::Passes(_) | Stream::Scene { .. } => 0, - } - } - - /// The chunks a command buffer's draws take. - fn chunks_a_buffer(self) -> u64 { - (self.draws as u64 * self.slots() * SLOT).div_ceil(CHUNK) - } - - /// The chunk and the offset of slot `slot` of command buffer `buffer`. - fn slot(self, buffer: usize, slot: u64) -> (usize, u64) { - let at = slot * SLOT; - let chunk = buffer as u64 * self.chunks_a_buffer() + at / CHUNK; - (chunk as usize, at % CHUNK) - } -} - -/// The calls `--calls` counts apart, by their index in a [`Tally`]. -const CALLS: [&str; 20] = [ - "command_buffer", - "render_command_encoder", - "set_render_pipeline_state", - "set_vertex_buffer", - "set_fragment_buffer", - "set_fragment_texture", - "set_fragment_sampler_states", - "draw_primitives", - "end_encoding", - "add_completed_handler", - "commit", - "set_scissor_rect", - "set_viewport", - "draw_indexed_primitives", - "set_vertex_buffer_offset", - "set_fragment_buffer_offset", - "set_fragment_textures", - "set_vertex_bytes", - "set_fragment_bytes", - "memory_barrier_with_scope", -]; - -/// Each call's count, and its instructions, cycles and cache misses ([`call_counts`]), over a -/// run's counted repetitions. -type Tally = [(u64, [u64; 3]); CALLS.len()]; - -/// The calling thread's instructions, cycles and cache misses so far, the misses 0 where the -/// system counts none ([`data_misses`]). -fn call_counts() -> Option<[u64; 3]> { - let [instructions, cycles] = instructions_and_cycles()?; - let misses = data_misses().map_or(0, |[_, cache]| cache); - Some([instructions, cycles, misses]) -} - -/// Run `body` as call `kind`, counting its instructions, cycles and cache misses into `tally` -/// where there is one. -fn call(tally: &mut Option<&mut Tally>, kind: usize, body: impl FnOnce() -> T) -> T { - let Some(tally) = tally else { - return body(); - }; - let before = call_counts(); - let answer = body(); - if let Some((after, before)) = call_counts().zip(before) { - tally[kind].0 += 1; - for (sum, (after, before)) in tally[kind].1.iter_mut().zip(after.into_iter().zip(before)) { - *sum += after - before; - } - } - answer -} - -/// The instructions, cycles and cache misses a read of the counters costs between them, the -/// median of many each. -fn read_cost() -> [f64; 3] { - let pairs = (0..10_000) - .filter_map(|_| { - let before = call_counts()?; - let after = call_counts()?; - Some([0, 1, 2].map(|at| (after[at] - before[at]) as f64)) - }) - .collect::>(); - match pairs.is_empty() { - true => [0.0; 3], - false => [0, 1, 2].map(|at| spread(pairs.iter().map(|pair| pair[at]).collect()).0), - } -} - -/// One call of a command buffer's pass, its objects looked up before a count starts. -#[derive(Clone, Copy)] -enum Step<'a> { - /// End the open encoder, if any, and open the compositor's pass of this index, its viewport - /// set; a command buffer whose steps start otherwise opens the bench's one pass first. - Pass(usize), - /// End the open encoder, if any, and open a pass of this descriptor. - Begin(&'a RenderPassDescriptor), - VertexOffset(u64, u32), - FragmentOffset(u64, u32), - /// Fragment textures from index 0, at most [`SCENE_UNITS`]. - FragmentTextures(&'a [Texture]), - /// Fragment sampler states from index 0, at most [`SCENE_UNITS`]. - FragmentSamplers(&'a [SamplerState]), - Pipeline(&'a RenderPipelineState), - VertexBuffer(&'a Buffer, u64, u32), - FragmentBuffer(&'a Buffer, u64, u32), - FragmentTexture(&'a Texture, u32), - FragmentSampler(&'a SamplerState), - Scissor(ScissorRect), - Draw(PrimitiveType, u32), - /// Six `UInt16` indices of a triangle list at this offset of the buffer. - DrawIndexed(&'a Buffer, u64), - /// 16 bytes, each this value, at this vertex or fragment index. - VertexBytes(u8, u32), - FragmentBytes(u8, u32), - /// `memory_barrier_with_scope` over the render targets, from the fragment stage to the - /// fragment stage. - Barrier, -} - -/// The objects every shape draws with. -struct Bench { - device: Device, - queue: CommandQueue, - pass: RenderPassDescriptor, - /// The pass, loading the target rather than clearing it. - loaded: RenderPassDescriptor, - pipelines: Vec, - textures: Vec, - sampler: SamplerState, - constants: Buffer, - /// With `--shadowed`, the no-copy buffer the target is a texture over. - _target_pages: Option, - /// The compositor shape's objects, where it runs. - compositor: Option, - /// The scene shapes' objects, where one runs. - scene: Option, -} - -/// A shape's chunks, and with `--heap` the heap they are placed in and the buffer over the guest -/// RAM's pages that stands beside it ([`Bench::chunks`]). -struct Chunks { - buffers: Vec, - _heap: Option, - _ram: Option, -} - -impl Bench { - fn new( - device: Device, - library: &Library, - shadowed: bool, - (compositor, scene): (Option<(bool, usize)>, bool), - ) -> Result { - let function = |name: &str| -> Result { - let function = library.new_function_with_name(name)?; - Ok(StageSource::Function(function.function_descriptor())) - }; - let (buffer, texture) = ( - function("draw_costs_buffer")?, - function("draw_costs_texture")?, - ); - let pipelines = (0..PIPELINES) - .map(|n| { - let mut descriptor = RenderPipelineDescriptor::new(function("draw_costs_vertex")?); - descriptor.fragment = Some(match n % 2 { - 0 => buffer.clone(), - _ => texture.clone(), - }); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm); - if n >= 2 { - color.blending_enabled = true; - color.source_rgb_blend_factor = BlendFactor::One; - color.source_alpha_blend_factor = BlendFactor::One; - color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - } - descriptor.color_attachments[0] = Some(color); - Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) - }) - .collect::>>()?; - let mut sampled = TextureDescriptor::texture_2d( - PixelFormat::BGRA8Unorm, - TEXTURE_SIDE, - TEXTURE_SIDE, - false, - ); - sampled.usage = TextureUsage::SHADER_READ; - let textures = (0..TEXTURES) - .map(|_| device.new_texture(&sampled)) - .collect::, _>>()?; - let mut target = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, SIDE, SIDE, false); - target.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - // With `--shadowed`, a texture over host pages at its packed rows, loaded. - let (texture, target_pages, load) = match shadowed { - false => (device.new_texture(&target)?, None, LoadAction::Clear), - true => { - let bytes = SIDE * SIDE * 4; - // SAFETY: page-aligned read-write memory of `bytes` bytes, never unmapped, which - // outlives the buffer. - let pages = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(host_pages(bytes as usize)?), - bytes, - ResourceOptions::shared(), - None, - ) - }?; - target.resource_options = ResourceOptions::shared(); - let texture = pages.new_texture(&target, 0, SIDE * 4)?; - (texture, Some(pages), LoadAction::Load) - } - }; - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(texture); - color.load_action = load; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0); - let mut loaded = pass.clone(); - loaded.color_attachments[0].load_action = LoadAction::Load; - let compositor = match compositor { - Some(made) => Some(Compositor::new(&device, library, made)?), - None => None, - }; - let scene = match scene { - true => Some(Scene::new(&device, library)?), - false => None, - }; - Ok(Bench { - queue: device.new_command_queue()?, - sampler: device.new_sampler_state(&SamplerDescriptor::new())?, - constants: device.new_buffer(4096, ResourceOptions::shared())?, - device, - pass, - loaded, - pipelines, - textures, - _target_pages: target_pages, - compositor, - scene, - }) - } - - /// `shape`'s chunks, `threads` times over: no-copy buffers over fresh host pages, or with - /// `heap` buffers placed in one heap over them beside a buffer over them and one chunk more - /// (the module docs), kept mapped for the process's life, so no import outlives its pages. - fn chunks(&self, shape: Shape, threads: usize, heap: bool) -> Result { - let count = shape.chunks_a_buffer() * (shape.buffers * threads) as u64; - if count == 0 { - return Ok(Chunks { - buffers: Vec::new(), - _heap: None, - _ram: None, - }); - } - // With `heap`, one chunk before the heap's pages that only the guest RAM's buffer covers. - let ahead = u64::from(heap) * CHUNK; - let bytes = (ahead + count * CHUNK) as usize; - let pages = host_pages(bytes)?; - let at = |offset: u64| { - // SAFETY: inside the mapping, which stays mapped and writable for the process's - // life; CHUNK is a multiple of the host's page. - NonNull::new(unsafe { pages.as_ptr().add(offset as usize) }).ok_or("a null mapping") - }; - if !heap { - let buffers = (0..count) - .map(|n| { - // SAFETY: page-aligned read-write memory that outlives the buffer. - let buffer = unsafe { - self.device.new_buffer_with_bytes_no_copy( - HostMemory::new(at(n * CHUNK)?), - CHUNK, - ResourceOptions::shared(), - None, - ) - }?; - Ok(buffer) - }) - .collect::>>()?; - return Ok(Chunks { - buffers, - _heap: None, - _ram: None, - }); - } - // SAFETY: as above, the whole mapping. - let ram = unsafe { - self.device.new_buffer_with_bytes_no_copy( - HostMemory::new(at(0)?), - bytes as u64, - ResourceOptions::shared(), - None, - ) - }?; - let descriptor = HeapDescriptor::new( - HeapType::Placement, - count * CHUNK, - ResourceOptions::shared(), - ); - // SAFETY: as above, the mapping past its first chunk. - let placed = unsafe { - self.device.new_heap_with_bytes_no_copy( - HostMemory::new(at(ahead)?), - &descriptor, - None, - None, - ) - }?; - let buffers = (0..count) - .map(|n| { - Ok(placed.new_buffer_at_offset(CHUNK, ResourceOptions::shared(), n * CHUNK)?) - }) - .collect::>>()?; - Ok(Chunks { - buffers, - _heap: Some(placed), - _ram: Some(ram), - }) - } - - /// Command buffer `buffer`'s calls of a repetition of `shape`, over `chunks`. - fn steps<'a>(&'a self, chunks: &'a [Buffer], shape: Shape, buffer: usize) -> Vec> { - if let (Stream::Composited { backdrops }, Some(compositor)) = - (shape.stream, &self.compositor) - { - return compositor.steps(buffer, backdrops); - } - if let (Stream::Passes(each), Some(compositor)) = (shape.stream, &self.compositor) { - return compositor.small_passes(buffer, shape.draws / each, each); - } - if let ( - Stream::Scene { - rebinds, - scissors, - run, - }, - Some(scene), - ) = (shape.stream, &self.scene) - { - return scene.steps(buffer, (rebinds, scissors), run); - } - if shape.stream == Stream::Guest { - return self.guest_steps(chunks, shape, buffer); - } - if shape.stream == Stream::Splits { - return self.split_steps(chunks, shape, buffer); - } - let mut steps = vec![ - Step::Pipeline(&self.pipelines[0]), - Step::VertexBuffer(&self.constants, 0, 1), - Step::FragmentBuffer(&self.constants, 0, 0), - ]; - for draw in 0..shape.draws { - let slot = draw as u64 * shape.slots(); - match shape.stream { - Stream::Bytes => { - let (chunk, offset) = shape.slot(buffer, slot); - steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0)); - steps.push(Step::Draw(PrimitiveType::Triangle, 3)); - } - Stream::Layers => { - if draw % RUN == 0 { - steps.push(Step::Pipeline(&self.pipelines[draw / RUN % PIPELINES])); - steps.push(Step::FragmentSampler(&self.sampler)); - } - steps.push(Step::FragmentTexture(&self.textures[draw % TEXTURES], 0)); - let (chunk, offset) = shape.slot(buffer, slot + 1); - steps.push(Step::FragmentBuffer(&chunks[chunk], offset, 0)); - let (chunk, offset) = shape.slot(buffer, slot); - steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0)); - steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4)); - } - Stream::Composited { .. } - | Stream::Passes(_) - | Stream::Scene { .. } - | Stream::Guest - | Stream::Splits => {} - Stream::Clipped | Stream::Damaged => { - if draw % RUN == 0 { - steps.push(Step::Pipeline(&self.pipelines[draw / RUN % PIPELINES])); - steps.push(Step::FragmentSampler(&self.sampler)); - steps.push(Step::FragmentTexture( - &self.textures[draw / RUN % TEXTURES], - 0, - )); - } else if draw % 2 == 1 && shape.stream == Stream::Clipped { - steps.push(Step::Scissor(CLIPS[draw / 2 % CLIPS.len()])); - } - if shape.stream == Stream::Damaged { - steps.push(Step::Scissor(damaged(draw))); - } - let (chunk, offset) = shape.slot(buffer, slot); - steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0)); - steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4)); - } - } - } - steps - } - - /// Command buffer `buffer`'s calls of a guest shape ([`Stream::Guest`]), over `chunks`. - fn guest_steps<'a>( - &'a self, - chunks: &'a [Buffer], - shape: Shape, - buffer: usize, - ) -> Vec> { - let mut steps = Vec::new(); - for draw in 0..shape.draws { - if draw % GUEST_PASS_DRAWS == 0 { - steps.push(Step::Begin(match draw { - 0 => &self.pass, - _ => &self.loaded, - })); - } - if draw % 2 == 0 { - steps.push(Step::Pipeline(&self.pipelines[draw / 2 % PIPELINES])); - steps.push(Step::FragmentSampler(&self.sampler)); - } - steps.push(Step::FragmentTexture(&self.textures[draw % TEXTURES], 0)); - let (chunk, offset) = shape.slot(buffer, draw as u64); - steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0)); - steps.push(Step::VertexBytes(draw as u8, 1)); - steps.push(Step::FragmentBytes(draw as u8, 0)); - steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4)); - } - steps - } - - /// Command buffer `buffer`'s calls of a splits shape ([`Stream::Splits`]), over `chunks`: each - /// pass's draw through the first pipeline state, the barrier, the draw of the fourth sampling - /// the target, which splits the pass, then the draws of the second and the third. - fn split_steps<'a>( - &'a self, - chunks: &'a [Buffer], - shape: Shape, - buffer: usize, - ) -> Vec> { - let target = self.pass.color_attachments[0].texture.as_ref(); - let mut steps = Vec::new(); - for draw in 0..shape.draws { - let at = draw % SPLIT_PASS_DRAWS; - if at == 0 { - steps.push(Step::Begin(match draw { - 0 => &self.pass, - _ => &self.loaded, - })); - steps.push(Step::VertexBuffer(&self.constants, 0, 1)); - steps.push(Step::FragmentBuffer(&self.constants, 0, 0)); - steps.push(Step::FragmentSampler(&self.sampler)); - } - let (state, texture) = match (at, target) { - (1, Some(target)) => { - steps.push(Step::Barrier); - (3, target) - } - _ => (at.saturating_sub(1), &self.textures[draw % TEXTURES]), - }; - steps.push(Step::Pipeline(&self.pipelines[state])); - steps.push(Step::FragmentTexture(texture, 0)); - let (chunk, offset) = shape.slot(buffer, draw as u64); - steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0)); - steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4)); - } - steps - } - - /// One repetition: every command buffer's calls, counted from the first one's creation - /// through the last commit, then each handler waited for; each call counted apart into - /// `tally` where there is one. - fn repetition( - &self, - buffers: &[Vec>], - mut tally: Option<&mut Tally>, - ) -> Result { - let (sender, completions) = mpsc::channel(); - let start = Counts::now(); - for steps in buffers { - let command_buffer = call(&mut tally, 0, || self.queue.command_buffer())?; - let mut open = match steps.first() { - Some(Step::Pass(_) | Step::Begin(_)) => None, - _ => Some(call(&mut tally, 1, || { - command_buffer.render_command_encoder(&self.pass) - })?), - }; - for &step in steps { - if let Step::Begin(descriptor) = step { - if let Some(encoder) = open.take() { - call(&mut tally, 8, || encoder.end_encoding())?; - } - open = Some(call(&mut tally, 1, || { - command_buffer.render_command_encoder(descriptor) - })?); - continue; - } - if let Step::Pass(at) = step { - if let Some(encoder) = open.take() { - call(&mut tally, 8, || encoder.end_encoding())?; - } - let compositor = self - .compositor - .as_ref() - .ok_or("a pass with no compositor")?; - let (descriptor, viewport) = &compositor.passes[at]; - let mut encoder = call(&mut tally, 1, || { - command_buffer.render_command_encoder(descriptor) - })?; - call(&mut tally, 12, || encoder.set_viewport(*viewport))?; - open = Some(encoder); - continue; - } - let encoder = open.as_mut().ok_or("a step before its pass")?; - match step { - Step::Pass(_) | Step::Begin(_) => Ok(()), - Step::VertexOffset(offset, index) => call(&mut tally, 14, || { - encoder.set_vertex_buffer_offset(offset, index) - }), - Step::FragmentOffset(offset, index) => call(&mut tally, 15, || { - encoder.set_fragment_buffer_offset(offset, index) - }), - Step::FragmentTextures(textures) => call(&mut tally, 16, || { - let units: [Option<&Texture>; SCENE_UNITS] = - std::array::from_fn(|at| textures.get(at)); - encoder.set_fragment_textures(&units[..textures.len()], 0) - }), - Step::FragmentSamplers(samplers) => call(&mut tally, 6, || { - let units: [Option<&SamplerState>; SCENE_UNITS] = - std::array::from_fn(|at| samplers.get(at)); - encoder.set_fragment_sampler_states(&units[..samplers.len()], None, 0) - }), - Step::Pipeline(state) => { - call(&mut tally, 2, || encoder.set_render_pipeline_state(state)) - } - Step::VertexBuffer(buffer, offset, index) => call(&mut tally, 3, || { - encoder.set_vertex_buffer(Some(buffer), offset, index) - }), - Step::FragmentBuffer(buffer, offset, index) => call(&mut tally, 4, || { - encoder.set_fragment_buffer(Some(buffer), offset, index) - }), - Step::FragmentTexture(texture, index) => call(&mut tally, 5, || { - encoder.set_fragment_texture(Some(texture), index) - }), - Step::FragmentSampler(sampler) => call(&mut tally, 6, || { - encoder.set_fragment_sampler_states(&[Some(sampler)], None, 0) - }), - Step::Scissor(rect) => call(&mut tally, 11, || encoder.set_scissor_rect(rect)), - Step::Draw(primitive, count) => call(&mut tally, 7, || { - encoder.draw_primitives(primitive, 0, count, 1, 0) - }), - Step::VertexBytes(value, index) => call(&mut tally, 17, || { - encoder.set_vertex_bytes(&[value; 16], index) - }), - Step::FragmentBytes(value, index) => call(&mut tally, 18, || { - encoder.set_fragment_bytes(&[value; 16], index) - }), - Step::Barrier => call(&mut tally, 19, || { - let fragment = RenderStages::FRAGMENT; - encoder.memory_barrier_with_scope( - BarrierScope::RENDER_TARGETS, - fragment, - fragment, - ); - Ok(()) - }), - Step::DrawIndexed(buffer, offset) => call(&mut tally, 13, || { - encoder.draw_indexed_primitives( - PrimitiveType::Triangle, - 6, - IndexType::UInt16, - buffer, - offset, - 1, - 0, - 0, - ) - }), - }?; - } - if let Some(encoder) = open { - call(&mut tally, 8, || encoder.end_encoding())?; - } - let sender = sender.clone(); - call(&mut tally, 9, || { - command_buffer.add_completed_handler(Box::new(move |done: &CommandBuffer| { - let _ = sender.send(done.status()); - })) - })?; - call(&mut tally, 10, || command_buffer.commit())?; - } - let spent = Counts::now().since(start); - for _ in buffers { - match completions.recv_timeout(WAIT) { - Ok(CommandBufferStatus::Completed) => {} - Ok(status) => return Err(format!("a command buffer ended {status:?}").into()), - Err(_) => { - return Err(format!("a command buffer did not complete in {WAIT:?}").into()) - } - } - } - Ok(spent) - } -} - -/// The compositor shape's framebuffer surface, its five layer surfaces, and the draws of a layer's -/// pass and of the framebuffer's. -const FRAMEBUFFER: (u64, u64) = (3840, 2400); -const LAYERS: [(u64, u64); 5] = [ - (1600, 1000), - (1280, 800), - (1024, 768), - (800, 600), - (512, 512), -]; -const LAYER_DRAWS: usize = 4; - -/// The small passes' surfaces ([`Compositor::small_passes`]), and their side. -const SMALL_TARGETS: usize = 8; -const SMALL_SIDE: u64 = 256; -const FRAMEBUFFER_DRAWS: usize = 15; -const COMPOSITOR_DRAWS: usize = LAYERS.len() * LAYER_DRAWS + FRAMEBUFFER_DRAWS; - -/// The sampled surfaces: the first a desktop picture of the framebuffer's size, the rest windows -/// of these sizes in turn. -const SOURCES: usize = 12; -const SOURCE_SIZES: [(u64, u64); 4] = [(1920, 1200), (1024, 768), (512, 512), (256, 256)]; - -/// The compositor's per-draw data in its buffer over host pages: `COMPOSITOR_SLOTS` slots of each -/// kind, a draw taking the next: 4 corners (64 bytes a slot), 6 corners (128), 6 `UInt16` -/// indices (64), a placement (256) and a tint (256). -const COMPOSITOR_SLOTS: u64 = 256; -const CORNERS4: u64 = 0; -const CORNERS6: u64 = 64 << 10; -const INDICES: u64 = 128 << 10; -const PLACEMENT: u64 = 256 << 10; -const TINT: u64 = 512 << 10; -const COMPOSITOR_BYTES: u64 = 16 << 20; - -/// A compositor draw's fragment function: its pipeline state's index. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Quad { - Plain, - Masked, - Backdrop, -} - -/// One draw of a compositor frame: its pass, its kind, whether it is indexed, its scissor -/// rectangle and its pass's size. -#[derive(Clone, Copy)] -struct FrameDraw { - pass: usize, - quad: Quad, - indexed: bool, - scissor: ScissorRect, - size: (u64, u64), -} - -/// The plain pipeline states of the small passes ([`Stream::Passes`]), by their color's source -/// and destination blend factors: more than the eight a render encoder carries kept draws of (its -/// last state's and the seven its bind state sets aside). -const SMALL_BLENDS: [(BlendFactor, BlendFactor); 20] = [ - (BlendFactor::One, BlendFactor::OneMinusSourceAlpha), - (BlendFactor::SourceAlpha, BlendFactor::OneMinusSourceAlpha), - (BlendFactor::One, BlendFactor::Zero), - (BlendFactor::One, BlendFactor::One), - (BlendFactor::DestinationColor, BlendFactor::Zero), - (BlendFactor::OneMinusDestinationColor, BlendFactor::One), - (BlendFactor::SourceColor, BlendFactor::Zero), - (BlendFactor::Zero, BlendFactor::SourceColor), - (BlendFactor::OneMinusSourceAlpha, BlendFactor::SourceAlpha), - (BlendFactor::DestinationAlpha, BlendFactor::One), - (BlendFactor::OneMinusDestinationAlpha, BlendFactor::One), - (BlendFactor::SourceAlphaSaturated, BlendFactor::One), - (BlendFactor::SourceAlpha, BlendFactor::One), - (BlendFactor::One, BlendFactor::SourceAlpha), - (BlendFactor::Zero, BlendFactor::One), - (BlendFactor::Zero, BlendFactor::OneMinusSourceAlpha), - (BlendFactor::OneMinusSourceColor, BlendFactor::One), - (BlendFactor::DestinationColor, BlendFactor::One), - (BlendFactor::SourceAlpha, BlendFactor::Zero), - (BlendFactor::One, BlendFactor::SourceColor), -]; - -/// The compositor shape's objects (the module docs): its passes with their viewports, their -/// targets, the sampled surfaces, its three pipeline states and the small passes' plain ones, its -/// sampler and the buffer of its per-draw data, and the buffers its surfaces lie in. -struct Compositor { - passes: Vec<(RenderPassDescriptor, Viewport)>, - targets: Vec, - sources: Vec, - pipelines: Vec, - plain: Vec, - sampler: SamplerState, - data: Buffer, - _surfaces: Vec, -} - -impl Compositor { - fn new( - device: &Device, - library: &Library, - (pages, states): (bool, usize), - ) -> Result { - let function = |name: &str| -> Result { - let function = library.new_function_with_name(name)?; - Ok(StageSource::Function(function.function_descriptor())) - }; - let pipeline = |fragment: &str, (source, destination)| -> Result { - let mut descriptor = RenderPipelineDescriptor::new(function("draw_costs_quad_vertex")?); - descriptor.fragment = Some(function(fragment)?); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm); - color.blending_enabled = true; - color.source_rgb_blend_factor = source; - color.source_alpha_blend_factor = source; - color.destination_rgb_blend_factor = destination; - color.destination_alpha_blend_factor = destination; - descriptor.color_attachments[0] = Some(color); - Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) - }; - let pipelines = [ - "draw_costs_quad", - "draw_costs_quad_masked", - "draw_costs_quad_backdrop", - ] - .iter() - .map(|fragment| pipeline(fragment, SMALL_BLENDS[0])) - .collect::>>()?; - let plain = (SMALL_BLENDS.iter().take(states)) - .map(|&blend| pipeline("draw_costs_quad", blend)) - .collect::>>()?; - let mut sampler = SamplerDescriptor::new(); - sampler.min_filter = SamplerMinMagFilter::Linear; - sampler.mag_filter = SamplerMinMagFilter::Linear; - let sampler = device.new_sampler_state(&sampler)?; - let mut surfaces = Vec::new(); - let mut surface = |(width, height): (u64, u64), target: bool| -> Result { - let (row, mut descriptor) = ( - width * 4, - TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, width, height, false), - ); - descriptor.usage = match target { - true => TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, - false => TextureUsage::SHADER_READ, - }; - let buffer = match pages { - // SAFETY: page-aligned read-write memory of the surface's bytes, never unmapped, - // which outlives the buffer. - true => unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(host_pages((row * height) as usize)?), - row * height, - ResourceOptions::shared(), - None, - )? - }, - false => { - descriptor.resource_options = ResourceOptions::private(); - device.new_buffer(row * height, ResourceOptions::private())? - } - }; - let plane = IoSurfacePlane::new(0, row, false); - let texture = buffer.new_texture_with_iosurface_plane(&descriptor, plane)?; - surfaces.push(buffer); - Ok(texture) - }; - let small = [(SMALL_SIDE, SMALL_SIDE); SMALL_TARGETS]; - let targets = (LAYERS.iter().copied().chain([FRAMEBUFFER]).chain(small)) - .map(|size| surface(size, true)) - .collect::>>()?; - let sources = (0..SOURCES) - .map(|at| match at { - 0 => surface(FRAMEBUFFER, false), - at => surface(SOURCE_SIZES[(at - 1) % SOURCE_SIZES.len()], false), - }) - .collect::>>()?; - let sizes = LAYERS.iter().chain([&FRAMEBUFFER]).chain(&small); - let passes = (targets.iter().zip(sizes)) - .enumerate() - .map(|(at, (target, &(width, height)))| { - let mut descriptor = RenderPassDescriptor::new(); - let color = &mut descriptor.color_attachments[0]; - color.texture = Some(target.clone()); - color.store_action = StoreAction::Store; - match at == LAYERS.len() { - false => color.load_action = LoadAction::Load, - true => { - color.load_action = LoadAction::Clear; - color.clear_color = ClearColor::new(0.1, 0.1, 0.1, 1.0); - } - } - let viewport = Viewport { - origin_x: 0.0, - origin_y: 0.0, - width: width as f64, - height: height as f64, - znear: 0.0, - zfar: 1.0, - }; - (descriptor, viewport) - }) - .collect(); - let memory = host_pages(COMPOSITOR_BYTES as usize)?; - // SAFETY: page-aligned read-write memory of its length, never unmapped, which outlives - // the buffer. - let data = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(memory), - COMPOSITOR_BYTES, - ResourceOptions::shared(), - None, - )? - }; - let write = |at: u64, values: &[f32]| { - let bytes: Vec = values - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect(); - // SAFETY: inside the mapping, which nothing reads yet. - unsafe { - std::ptr::copy_nonoverlapping( - bytes.as_ptr(), - memory.as_ptr().add(at as usize), - bytes.len(), - ) - } - }; - // A corner is a position in [0, 1] and its texture coordinate, y down for both. - let [tl, tr, bl, br] = - [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0f32]].map(|[x, y]| [x, y, x, y]); - let plan = Compositor::plan(false); - for slot in 0..COMPOSITOR_SLOTS { - write(CORNERS4 + slot * 64, &[tl, tr, bl, br].concat()); - write(CORNERS6 + slot * 128, &[tl, tr, bl, bl, tr, br].concat()); - write(TINT + slot * 256, &[1.0, 1.0, 1.0, 0.9]); - let FrameDraw { scissor, size, .. } = plan[slot as usize % plan.len()]; - let (w, h) = (size.0 as f32, size.1 as f32); - let placement = [ - 2.0 * scissor.width as f32 / w, - -2.0 * scissor.height as f32 / h, - 2.0 * scissor.x as f32 / w - 1.0, - 1.0 - 2.0 * scissor.y as f32 / h, - ]; - write(PLACEMENT + slot * 256, &placement); - let indices: Vec = [0u16, 1, 2, 2, 1, 3] - .iter() - .flat_map(|index| index.to_le_bytes()) - .collect(); - // SAFETY: as above. - unsafe { - std::ptr::copy_nonoverlapping( - indices.as_ptr(), - memory.as_ptr().add((INDICES + slot * 64) as usize), - indices.len(), - ) - } - } - // A guest's first session makes its surfaces before the device's in-place check answered - // (a shader cache that holds no record of it): shadows, which move in place at a quiet - // commit once it answers. The shape's draws are measured after it answered. - if !device.settle_in_place_checks(Duration::from_secs(60)) { - eprintln!("the device's in-place check did not answer in 60 s"); - } - Ok(Compositor { - passes, - targets, - sources, - pipelines, - plain, - sampler, - data, - _surfaces: surfaces, - }) - } - - /// A frame's draws in order, each a backdrop where `backdrops`. - fn plan(backdrops: bool) -> Vec { - let mut draws = Vec::with_capacity(COMPOSITOR_DRAWS); - let passes = (LAYERS.iter().map(|&size| (LAYER_DRAWS, size))) - .chain([(FRAMEBUFFER_DRAWS, FRAMEBUFFER)]); - for (pass, (count, (width, height))) in passes.enumerate() { - for k in 0..count { - let d = draws.len(); - let backdrop = backdrops - || (pass < LAYERS.len() && k == 1) - || (pass == LAYERS.len() && k == 7); - let kind = match () { - _ if backdrop => Quad::Backdrop, - _ if d % 3 == 2 => Quad::Masked, - _ => Quad::Plain, - }; - let scissor = ScissorRect { - x: (d * 97 % 8) as u64 * width / 16, - y: (d * 53 % 8) as u64 * height / 16, - width: width / 2, - height: height / 2, - }; - draws.push(FrameDraw { - pass, - quad: kind, - indexed: matches!(d % 5, 0 | 2 | 3), - scissor, - size: (width, height), - }); - } - } - draws - } - - /// Command buffer `buffer`'s steps: its six passes and their draws, each draw's slots the - /// next of the buffer's, each draw a backdrop where `backdrops`. - fn steps(&self, buffer: usize, backdrops: bool) -> Vec> { - let (mut steps, mut kind, mut open) = (Vec::new(), None, None); - for (d, draw) in Compositor::plan(backdrops).into_iter().enumerate() { - let FrameDraw { - pass, - quad, - indexed, - scissor, - .. - } = draw; - if open != Some(pass) { - steps.push(Step::Pass(pass)); - (open, kind) = (Some(pass), None); - } - let slot = (buffer * COMPOSITOR_DRAWS + d) as u64 % COMPOSITOR_SLOTS; - if kind != Some(quad) { - steps.push(Step::Pipeline(&self.pipelines[quad as usize])); - kind = Some(quad); - } - let corners = match indexed { - true => CORNERS4 + slot * 64, - false => CORNERS6 + slot * 128, - }; - steps.push(Step::VertexBuffer(&self.data, corners, 0)); - steps.push(Step::VertexBuffer(&self.data, PLACEMENT + slot * 256, 1)); - steps.push(Step::FragmentBuffer(&self.data, TINT + slot * 256, 0)); - steps.push(Step::FragmentTexture( - &self.sources[(d * 5 + buffer) % SOURCES], - 0, - )); - match quad { - Quad::Plain => {} - Quad::Masked => { - let mask = &self.sources[(d * 7 + 3 + buffer) % SOURCES]; - steps.push(Step::FragmentTexture(mask, 1)); - } - Quad::Backdrop => steps.push(Step::FragmentTexture(&self.targets[pass], 1)), - } - steps.push(Step::FragmentSampler(&self.sampler)); - steps.push(Step::Scissor(scissor)); - steps.push(match indexed { - true => Step::DrawIndexed(&self.data, INDICES + slot * 64), - false => Step::Draw(PrimitiveType::Triangle, 6), - }); - } - steps - } -} - -impl Compositor { - /// Command buffer `buffer`'s steps of a window server's frame ([`Stream::Passes`]): `passes` - /// passes of `each` plain quads, each pass over the next of the small surfaces through the - /// next of the plain pipeline states, each draw's slots the next of the buffer's. - fn small_passes(&self, buffer: usize, passes: usize, each: usize) -> Vec> { - let first = LAYERS.len() + 1; - let mut steps = Vec::new(); - for pass in 0..passes { - let at = buffer * passes + pass; - steps.push(Step::Pass(first + at % SMALL_TARGETS)); - steps.push(Step::Pipeline(&self.plain[at % self.plain.len()])); - for k in 0..each { - let d = pass * each + k; - let slot = (buffer * passes * each + d) as u64 % COMPOSITOR_SLOTS; - steps.push(Step::VertexBuffer(&self.data, CORNERS6 + slot * 128, 0)); - steps.push(Step::VertexBuffer(&self.data, PLACEMENT + slot * 256, 1)); - steps.push(Step::FragmentBuffer(&self.data, TINT + slot * 256, 0)); - let source = &self.sources[(d * 5 + buffer) % SOURCES]; - steps.push(Step::FragmentTexture(source, 0)); - steps.push(Step::FragmentSampler(&self.sampler)); - steps.push(Step::Scissor(ScissorRect { - x: (d * 97 % 8) as u64 * SMALL_SIDE / 16, - y: (d * 53 % 8) as u64 * SMALL_SIDE / 16, - width: SMALL_SIDE / 2, - height: SMALL_SIDE / 2, - })); - steps.push(Step::Draw(PrimitiveType::Triangle, 6)); - } - } - steps - } -} - -/// The scene shapes' passes of a command buffer, a pass's draws, and theirs together. -const SCENE_PASSES: usize = 10; -const SCENE_PASS_DRAWS: usize = 24; -const SCENE_DRAWS: usize = SCENE_PASSES * SCENE_PASS_DRAWS; - -/// The scene's materials, the textures and samplers a material binds, the draws a material runs -/// for (a pass's draws are a multiple of them), and its pipeline states. -const SCENE_MATERIALS: usize = 6; -const SCENE_UNITS: usize = 8; -const SCENE_RUN: usize = 4; -const SCENE_PIPELINES: usize = 2; - -/// The scene's color targets' formats. -const SCENE_COLORS: [PixelFormat; 4] = [ - PixelFormat::BGRA8Unorm, - PixelFormat::RGBA8Unorm, - PixelFormat::RGBA16Float, - PixelFormat::RGBA16Float, -]; - -/// The scene's data in its buffer over host pages: its mesh's `SCENE_PIECES` pieces, a quad each -/// (4 vertices of a position and a texture coordinate, `SCENE_VERTEX` bytes each; 6 `UInt16` -/// indices, 16 bytes a piece), then `SCENE_SLOTS` slots of 256 bytes of transforms (a -/// `float4x4`) and of material scales (a `float4`), a draw taking the next. -const SCENE_PIECES: u64 = 64; -const SCENE_SLOTS: u64 = 1024; -const SCENE_VERTEX: u64 = 20; -const SCENE_VERTICES: u64 = 0; -const SCENE_INDICES: u64 = 64 << 10; -const SCENE_TRANSFORMS: u64 = 128 << 10; -const SCENE_SCALES: u64 = 512 << 10; -const SCENE_BYTES: u64 = 1 << 20; - -/// The scene shapes' objects (the module docs): a command buffer's first pass and its later -/// ones, over the same targets, its pipeline states, each material's textures, the samplers, and -/// the buffer of its data. -struct Scene { - passes: [RenderPassDescriptor; 2], - pipelines: Vec, - materials: Vec>, - samplers: Vec, - data: Buffer, -} - -impl Scene { - fn new(device: &Device, library: &Library) -> Result { - let function = |name: &str| -> Result { - let function = library.new_function_with_name(name)?; - Ok(StageSource::Function(function.function_descriptor())) - }; - let mut vertices = VertexDescriptor::new(); - let attributes = [(VertexFormat::Float3, 0), (VertexFormat::Float2, 12)]; - for (at, (format, offset)) in (0..).zip(attributes) { - let attribute = VertexAttributeDescriptor::new(format, offset, 0); - vertices.attributes.insert(at, attribute); - } - let layout = VertexBufferLayoutDescriptor::new(Some(SCENE_VERTEX as u32)); - vertices.layouts.insert(0, layout); - let pipelines = (0..SCENE_PIPELINES) - .map(|n| { - let vertex = function("draw_costs_scene_vertex")?; - let mut descriptor = RenderPipelineDescriptor::new(vertex); - descriptor.fragment = Some(function("draw_costs_scene")?); - descriptor.vertex_descriptor = Some(vertices.clone()); - for (at, format) in SCENE_COLORS.into_iter().enumerate() { - let mut color = ColorAttachmentDescriptor::new(format); - // The second state blends its first color over what is there. - if n == 1 && at == 0 { - color.blending_enabled = true; - color.source_rgb_blend_factor = BlendFactor::One; - color.source_alpha_blend_factor = BlendFactor::One; - color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - } - descriptor.color_attachments[at] = Some(color); - } - Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) - }) - .collect::>>()?; - // Material `m`'s textures: of side 64, 32 or 16 as `m` goes, each with its levels. - let materials = (0..SCENE_MATERIALS) - .map(|material| { - let side = TEXTURE_SIDE >> (material % 3); - let mut sampled = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, side, side, true); - sampled.usage = TextureUsage::SHADER_READ; - (0..SCENE_UNITS) - .map(|_| Ok(device.new_texture(&sampled)?)) - .collect::>>() - }) - .collect::>>()?; - let addresses = [ - SamplerAddressMode::Repeat, - SamplerAddressMode::ClampToEdge, - SamplerAddressMode::MirrorRepeat, - SamplerAddressMode::ClampToEdge, - ]; - let samplers = (0..SCENE_UNITS) - .map(|unit| { - let mut sampler = SamplerDescriptor::new(); - let filter = match unit % 2 { - 0 => SamplerMinMagFilter::Linear, - _ => SamplerMinMagFilter::Nearest, - }; - (sampler.min_filter, sampler.mag_filter) = (filter, filter); - let address = addresses[unit / 2 % addresses.len()]; - (sampler.s_address_mode, sampler.t_address_mode) = (address, address); - Ok(device.new_sampler_state(&sampler)?) - }) - .collect::>>()?; - let mut target = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, SIDE, SIDE, false); - target.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let targets = (SCENE_COLORS.iter()) - .map(|&format| { - target.pixel_format = format; - Ok(device.new_texture(&target)?) - }) - .collect::>>()?; - let passes = [LoadAction::Clear, LoadAction::Load].map(|load| { - let mut descriptor = RenderPassDescriptor::new(); - for (color, target) in descriptor.color_attachments.iter_mut().zip(&targets) { - color.texture = Some(target.clone()); - color.load_action = load; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0); - } - descriptor - }); - let memory = host_pages(SCENE_BYTES as usize)?; - // SAFETY: page-aligned read-write memory of its length, never unmapped, which outlives - // the buffer. - let data = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(memory), - SCENE_BYTES, - ResourceOptions::shared(), - None, - )? - }; - let write = |at: u64, bytes: &[u8]| { - // SAFETY: inside the mapping, which nothing reads yet. - unsafe { - std::ptr::copy_nonoverlapping( - bytes.as_ptr(), - memory.as_ptr().add(at as usize), - bytes.len(), - ) - } - }; - let floats = |values: &[f32]| -> Vec { - values - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect() - }; - // Piece `p` is the quad of cell `p` of an 8 by 8 grid over the target. - for piece in 0..SCENE_PIECES { - let (x, y) = ( - (piece % 8) as f32 / 4.0 - 1.0, - (piece / 8) as f32 / 4.0 - 1.0, - ); - for (corner, [u, v]) in [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0f32]] - .into_iter() - .enumerate() - { - let vertex = floats(&[x + u / 4.0, y + v / 4.0, 0.5, u, v]); - write( - SCENE_VERTICES + (piece * 4 + corner as u64) * SCENE_VERTEX, - &vertex, - ); - } - let first = (piece * 4) as u16; - let indices: Vec = [0u16, 1, 2, 2, 1, 3] - .iter() - .flat_map(|index| (first + index).to_le_bytes()) - .collect(); - write(SCENE_INDICES + piece * 16, &indices); - } - let identity = floats(&[ - 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, - ]); - for slot in 0..SCENE_SLOTS { - write(SCENE_TRANSFORMS + slot * 256, &identity); - write(SCENE_SCALES + slot * 256, &floats(&[1.0, 1.0, 1.0, 0.5])); - } - Ok(Scene { - passes, - pipelines, - materials, - samplers, - data, - }) - } - - /// Command buffer `buffer`'s steps: its passes and their draws, each draw's slots the next - /// of the buffer's; each draw binding its material's textures and samplers again where - /// `rebinds`, and setting a scissor rectangle of its own where `scissors`; a material runs - /// for `run` draws, a divisor of a pass's. - fn steps(&self, buffer: usize, (rebinds, scissors): (bool, bool), run: usize) -> Vec> { - let mut steps = Vec::new(); - for d in 0..SCENE_DRAWS { - if d % SCENE_PASS_DRAWS == 0 { - steps.push(Step::Begin(&self.passes[usize::from(d > 0)])); - steps.push(Step::VertexBuffer(&self.data, SCENE_VERTICES, 0)); - steps.push(Step::VertexBuffer(&self.data, SCENE_TRANSFORMS, 1)); - steps.push(Step::FragmentBuffer(&self.data, SCENE_SCALES, 0)); - } - let material = (buffer * SCENE_DRAWS + d) / run % SCENE_MATERIALS; - if d % run == 0 { - steps.push(Step::Pipeline(&self.pipelines[material % SCENE_PIPELINES])); - } - if rebinds || d % run == 0 { - steps.push(Step::FragmentTextures(&self.materials[material])); - steps.push(Step::FragmentSamplers(&self.samplers)); - } - if scissors { - steps.push(Step::Scissor(damaged(d))); - } - let slot = (buffer * SCENE_DRAWS + d) as u64 % SCENE_SLOTS; - steps.push(Step::VertexOffset(SCENE_TRANSFORMS + slot * 256, 1)); - steps.push(Step::FragmentOffset(SCENE_SCALES + slot * 256, 0)); - let piece = (d as u64 * 7 + buffer as u64) % SCENE_PIECES; - steps.push(Step::DrawIndexed(&self.data, SCENE_INDICES + piece * 16)); - } - steps - } -} - -/// The calling thread's CPU time, and its instructions and cycles where the system counts them; -/// the process's page faults that needed no I/O and its voluntary context switches, every -/// thread's (`getrusage`): what the kernel did, which the thread's counts hold where it ran on it. -#[derive(Clone, Copy, Default)] -struct Counts { - nanos: u64, - instructions: Option<[u64; 2]>, - /// Its L1 data cache's read misses and its cache misses where the system counts them - /// ([`data_misses`]). - misses: Option<[u64; 2]>, - /// The process's minor faults and voluntary context switches where the system counts them - /// (`getrusage`; none on Windows). - process: Option<[u64; 2]>, -} - -impl Counts { - #[cfg(unix)] - fn now() -> Counts { - let mut at = libc::timespec { - tv_sec: 0, - tv_nsec: 0, - }; - // SAFETY: `at` is a timespec, which the call writes. - let answer = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut at) }; - assert_eq!(answer, 0, "clock_gettime"); - // SAFETY: a `rusage` is plain integers, all zero valid, which the call writes. - let mut usage: libc::rusage = unsafe { std::mem::zeroed() }; - // SAFETY: `usage` is a `rusage`, which the call writes. - let answer = unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut usage) }; - assert_eq!(answer, 0, "getrusage"); - Counts { - nanos: at.tv_sec as u64 * 1_000_000_000 + at.tv_nsec as u64, - instructions: instructions_and_cycles(), - misses: data_misses(), - process: Some([usage.ru_minflt as u64, usage.ru_nvcsw as u64]), - } - } - - /// The counts now on Windows: the thread's kernel and user times (`GetThreadTimes`, in 100 ns - /// units), and no process counts, which Windows does not keep per process. - #[cfg(windows)] - fn now() -> Counts { - let nanos = { - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetThreadTimes"); - let ticks = - |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 - }; - Counts { - nanos, - instructions: instructions_and_cycles(), - misses: data_misses(), - process: None, - } - } - - /// What the thread spent from `start` until `self`. - fn since(self, start: Counts) -> Counts { - Counts { - nanos: self.nanos - start.nanos, - instructions: self - .instructions - .zip(start.instructions) - .map(|(now, then)| [now[0] - then[0], now[1] - then[1]]), - misses: self - .misses - .zip(start.misses) - .map(|(now, then)| [now[0] - then[0], now[1] - then[1]]), - process: self - .process - .zip(start.process) - .map(|(now, then)| [now[0] - then[0], now[1] - then[1]]), - } - } - - fn plus(self, more: Counts) -> Counts { - Counts { - nanos: self.nanos + more.nanos, - instructions: self - .instructions - .zip(more.instructions) - .map(|(a, b)| [a[0] + b[0], a[1] + b[1]]), - misses: self - .misses - .zip(more.misses) - .map(|(a, b)| [a[0] + b[0], a[1] + b[1]]), - process: self - .process - .zip(more.process) - .map(|(a, b)| [a[0] + b[0], a[1] + b[1]]), - } - } -} - -/// The calling thread's instructions and cycles so far: libSystem's `thread_selfcounts`, whose -/// `THSC_CPI` (1) answers the two as `u64`s. -#[cfg(target_os = "macos")] -fn instructions_and_cycles() -> Option<[u64; 2]> { - unsafe extern "C" { - fn thread_selfcounts(kind: i32, buffer: *mut u64, bytes: usize) -> i32; - } - let mut words = [0u64; 2]; - // SAFETY: the buffer holds the two words `THSC_CPI` writes. - let answer = unsafe { thread_selfcounts(1, words.as_mut_ptr(), size_of_val(&words)) }; - (answer == 0).then_some(words) -} - -/// On Linux, the calling thread's user-space instructions and cycles since its counters opened -/// at its first call ([`thread_counters`]). -#[cfg(target_os = "linux")] -fn instructions_and_cycles() -> Option<[u64; 2]> { - let [instructions, cycles, _, _] = thread_counters()?; - Some([instructions, cycles]) -} - -/// The calling thread's user-space read misses of its L1 data cache and its cache misses (the -/// last level a core's `PERF_COUNT_HW_CACHE_MISSES` names: its L2 on AMD's Zen, its last-level -/// cache on Intel's) since its counters opened at its first call ([`thread_counters`]): what a -/// draw's memory touches cost it, which its instructions do not show. -#[cfg(target_os = "linux")] -fn data_misses() -> Option<[u64; 2]> { - let [_, _, l1d, cache] = thread_counters()?; - Some([l1d, cache]) -} - -/// Elsewhere no misses are counted. -#[cfg(not(target_os = "linux"))] -fn data_misses() -> Option<[u64; 2]> { - None -} - -/// On Linux, the calling thread's user-space instructions, cycles, L1 data read misses and cache -/// misses since its counters opened at its first call (`perf_event_open`, where -/// `kernel.perf_event_paranoid` is at most 2): on a hybrid Intel CPU its performance cores' -/// counters (`cpu_core`), which count only there. -#[cfg(target_os = "linux")] -fn thread_counters() -> Option<[u64; 4]> { - use std::cell::Cell; - - /// `struct perf_event_attr` as its first published size (`PERF_ATTR_SIZE_VER0`). - #[repr(C)] - struct Attr { - kind: u32, - size: u32, - config: u64, - sample_period: u64, - sample_type: u64, - read_format: u64, - flags: u64, - wakeup_events: u32, - bp_type: u32, - config1: u64, - } - - /// `PERF_TYPE_HARDWARE`; `PERF_COUNT_HW_CPU_CYCLES`, `PERF_COUNT_HW_INSTRUCTIONS` and - /// `PERF_COUNT_HW_CACHE_MISSES`; `PERF_TYPE_HW_CACHE` with `PERF_COUNT_HW_CACHE_L1D`, - /// `PERF_COUNT_HW_CACHE_OP_READ` and `PERF_COUNT_HW_CACHE_RESULT_MISS`; the `exclude_kernel` - /// and `exclude_hv` flags. - const HARDWARE: u32 = 0; - const HW_CACHE: u32 = 3; - const CYCLES: u64 = 0; - const INSTRUCTIONS: u64 = 1; - const CACHE_MISSES: u64 = 3; - const L1D_READ_MISS: u64 = 1 << 16; - const EXCLUDE_KERNEL_HV: u64 = (1 << 5) | (1 << 6); - - thread_local! { - /// The thread's four counters' descriptors, opened at its first read; -1 where one is - /// not. - static COUNTERS: Cell> = const { Cell::new(None) }; - } - - fn open((kind, event): (u32, u64)) -> i32 { - // A hybrid CPU's performance cores' PMU, in the config's upper half; none elsewhere. - let pmu = std::fs::read_to_string("/sys/bus/event_source/devices/cpu_core/type") - .ok() - .and_then(|text| text.trim().parse::().ok()) - .unwrap_or(0); - let attr = Attr { - kind, - size: size_of::() as u32, - config: event | (pmu << 32), - sample_period: 0, - sample_type: 0, - read_format: 0, - flags: EXCLUDE_KERNEL_HV, - wakeup_events: 0, - bp_type: 0, - config1: 0, - }; - // SAFETY: `attr` is a valid `perf_event_attr` of its stated size, live for the call; the - // calling thread (0), any CPU (-1), no group (-1), no flags. - let fd = unsafe { - libc::syscall( - libc::SYS_perf_event_open, - &attr as *const Attr, - 0, - -1, - -1, - 0, - ) - }; - i32::try_from(fd).unwrap_or(-1) - } - - fn read(fd: i32) -> Option { - let mut count = 0u64; - // SAFETY: `count` is 8 writable bytes, the size of the counter's value. - let read = unsafe { libc::read(fd, (&mut count as *mut u64).cast(), 8) }; - (read == 8).then_some(count) - } - - let fds = COUNTERS.with(|cell| match cell.get() { - Some(fds) => fds, - None => { - let events = [ - (HARDWARE, INSTRUCTIONS), - (HARDWARE, CYCLES), - (HW_CACHE, L1D_READ_MISS), - (HARDWARE, CACHE_MISSES), - ]; - let fds = events.map(open); - cell.set(Some(fds)); - fds - } - }); - let [a, b, c, d] = fds.map(read); - Some([a?, b?, c?, d?]) -} - -/// Elsewhere the CPU time alone. -#[cfg(not(any(target_os = "macos", target_os = "linux")))] -fn instructions_and_cycles() -> Option<[u64; 2]> { - None -} - -/// The median, the lowest and the highest of `values`. -fn spread(mut values: Vec) -> (f64, f64, f64) { - values.sort_by(f64::total_cmp); - let n = values.len(); - let median = match n % 2 { - 1 => values[n / 2], - _ => (values[n / 2 - 1] + values[n / 2]) / 2.0, - }; - (median, values[0], values[n - 1]) -} - -/// How a run is made beside its shape: `--calls`, `--counts`, `--heap` and `--threads`. -#[derive(Clone, Copy)] -struct Options { - calls: bool, - counts: bool, - heap: bool, - threads: usize, -} - -/// What one thread's run answers ([`thread_run`]): its counts, its calls' tally, and each named -/// thread's CPU time. -type ThreadRun = (Counts, Tally, Vec<(String, u64)>); - -/// One thread's run of its command buffers' `buffers`: its counted repetitions' counts together, -/// its calls' tally where `calls`, and where `whole` the process's threads' CPU time over them -/// ([`thread_times`]), each repetition started with the other threads' at `start`. -fn thread_run( - bench: &Bench, - buffers: &[Vec>], - (calls, whole): (bool, bool), - start: &Barrier, -) -> Result { - // On a Mac, the performance cores, as the main thread asks for them. - #[cfg(target_os = "macos")] - // SAFETY: sets the calling thread's own class; it takes no pointer. - unsafe { - libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0); - } - let mut total: Option = None; - let mut tally: Tally = [(0, [0; 3]); CALLS.len()]; - let mut threads = Vec::new(); - for repetition in 0..WARM + COUNTED { - let counted = repetition >= WARM; - start.wait(); - if whole && repetition == WARM { - threads = thread_times(); - } - let spent = bench.repetition(buffers, (calls && counted).then_some(&mut tally))?; - if counted { - total = Some(total.map_or(spent, |total| total.plus(spent))); - } - } - if whole { - let before = threads; - threads = thread_times(); - for (name, spent) in &mut threads { - let then = before.iter().find(|(named, _)| named == name); - *spent = spent.saturating_sub(then.map_or(0, |(_, then)| *then)); - } - } - Ok((total.unwrap_or_default(), tally, threads)) -} - -/// On Linux, the CPU time of each of the process's threads so far, summed by thread name -/// (`/proc/self/task/*/comm`), the calling thread's as `encoding` (an unnamed thread takes the -/// program's name): the first field of its `schedstat`, its nanoseconds on a CPU, the kernel's on -/// its behalf included. A thread that ended is no longer counted. -#[cfg(target_os = "linux")] -fn thread_times() -> Vec<(String, u64)> { - let mut times: Vec<(String, u64)> = Vec::new(); - let Ok(tasks) = std::fs::read_dir("/proc/self/task") else { - return times; - }; - // SAFETY: takes no argument and answers the calling thread's id. - let caller = unsafe { libc::gettid() }.to_string(); - for task in tasks.flatten() { - let path = task.path(); - let (Ok(name), Ok(stat)) = ( - std::fs::read_to_string(path.join("comm")), - std::fs::read_to_string(path.join("schedstat")), - ) else { - continue; - }; - let Some(nanos) = (stat.split_whitespace().next()).and_then(|ns| ns.parse::().ok()) - else { - continue; - }; - let name = match task.file_name().to_str() == Some(caller.as_str()) { - true => "encoding", - false => name.trim(), - }; - match times.iter_mut().find(|(named, _)| named == name) { - Some((_, total)) => *total += nanos, - None => times.push((name.to_owned(), nanos)), - } - } - times -} - -/// Elsewhere, none: the threads' times are read on Linux alone. -#[cfg(not(target_os = "linux"))] -fn thread_times() -> Vec<(String, u64)> { - Vec::new() -} - -/// Run `shape` `runs` times and print its figures a draw, and with `--calls` each call's. -fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result<()> { - let Options { - calls, - counts, - heap, - threads, - } = options; - let chunks = bench.chunks(shape, threads, heap)?; - let before = counts.then(|| bench.device.work_counts()); - // Each thread's command buffers, the chunks of thread `t`'s from its `t * shape.buffers`th. - let buffers: Vec>>> = (0..threads) - .map(|thread| { - let first = thread * shape.buffers; - (first..first + shape.buffers) - .map(|buffer| bench.steps(&chunks.buffers, shape, buffer)) - .collect() - }) - .collect(); - let draws = (COUNTED * threads * shape.buffers * shape.draws) as f64; - let mut seen = Vec::with_capacity(runs); - let mut tallies = Vec::with_capacity(runs); - let mut threads_seen: Vec> = Vec::with_capacity(runs); - for _ in 0..runs { - let start = Barrier::new(threads); - let ran: Vec> = match threads { - 1 => vec![thread_run(bench, &buffers[0], (calls, true), &start)], - _ => std::thread::scope(|scope| { - // Each thread's refusal as its text, which crosses threads; the first reads the - // process's threads' times. - let running: Vec<_> = (buffers.iter().enumerate()) - .map(|(at, own)| { - let start = &start; - scope.spawn(move || { - thread_run(bench, own, (calls, at == 0), start) - .map_err(|error| error.to_string()) - }) - }) - .collect(); - (running.into_iter()) - .map(|thread| match thread.join() { - Ok(ran) => ran.map_err(Into::into), - Err(_) => Err("a thread panicked".into()), - }) - .collect() - }), - }; - let mut total: Option = None; - let mut tally: Tally = [(0, [0; 3]); CALLS.len()]; - for answer in ran { - let (spent, own, times) = answer?; - if !times.is_empty() { - threads_seen.push(times); - } - total = Some(total.map_or(spent, |total| total.plus(spent))); - for (all, one) in tally.iter_mut().zip(own) { - all.0 += one.0; - for (sum, more) in all.1.iter_mut().zip(one.1) { - *sum += more; - } - } - } - // The process's counts each thread took over the same span: theirs once. - let mut total = total.unwrap_or_default(); - total.process = (total.process).map(|counts| counts.map(|count| count / threads as u64)); - seen.push(total); - tallies.push(tally); - } - if let Some(before) = before { - let drawn = (WARM + COUNTED) * runs * threads * shape.buffers * shape.draws; - println!("WORK-COUNTS {} draws {drawn}", shape.name); - println!("WORK-COUNTS {} before {before:?}", shape.name); - println!( - "WORK-COUNTS {} after {:?}", - shape.name, - bench.device.work_counts() - ); - } - println!( - "{}: {} command buffers of {} draws on {threads} thread(s), chunks in {}, {runs} runs of \ - {COUNTED} counted repetitions; a draw:", - shape.name, - shape.buffers, - shape.draws, - match heap { - true => "a heap", - false => "buffers", - } - ); - let mut figures: Vec<(&str, Vec)> = vec![( - "cpu_ns", - seen.iter().map(|c| c.nanos as f64 / draws).collect(), - )]; - if seen.iter().all(|c| c.process.is_some()) { - for (figure, index) in [("process_faults", 0), ("process_switches", 1)] { - let values = seen - .iter() - .filter_map(|c| c.process.map(|p| p[index] as f64 / draws)) - .collect(); - figures.push((figure, values)); - } - } - if seen.iter().all(|c| c.instructions.is_some()) { - for (figure, index) in [("instructions", 0), ("cycles", 1)] { - let values = seen - .iter() - .filter_map(|c| c.instructions.map(|i| i[index] as f64 / draws)) - .collect(); - figures.push((figure, values)); - } - } - if seen.iter().all(|c| c.misses.is_some()) { - for (figure, index) in [("l1d_read_misses", 0), ("cache_misses", 1)] { - let values = seen - .iter() - .filter_map(|c| c.misses.map(|m| m[index] as f64 / draws)) - .collect(); - figures.push((figure, values)); - } - } - for (figure, values) in figures { - let (median, low, high) = spread(values); - println!( - "DRAW-COST {} {figure} {median:.3} [{low:.3}, {high:.3}]", - shape.name - ); - } - // Each thread name's CPU time a draw, by the most first, and the threads' together. - let mut names: Vec<&str> = Vec::new(); - for (name, _) in threads_seen.iter().flatten() { - if !names.contains(&name.as_str()) { - names.push(name); - } - } - let a_draw = |run: &Vec<(String, u64)>, name: Option<&str>| { - let spent = run - .iter() - .filter(|(named, _)| name.is_none_or(|name| named == name)); - spent.map(|(_, nanos)| *nanos).sum::() as f64 / draws - }; - let mut thread_figures: Vec<(&str, (f64, f64, f64))> = (names.iter()) - .map(|&name| { - let values = threads_seen.iter().map(|run| a_draw(run, Some(name))); - (name, spread(values.collect())) - }) - .collect(); - thread_figures.sort_by(|(_, a), (_, b)| b.0.total_cmp(&a.0)); - if !threads_seen.is_empty() { - let values = threads_seen.iter().map(|run| a_draw(run, None)); - thread_figures.push(("all", spread(values.collect()))); - } - for (name, (median, low, high)) in thread_figures { - println!( - "DRAW-THREAD {} {name} ns {median:.1} [{low:.1}, {high:.1}]", - shape.name - ); - } - if calls && seen.iter().all(|c| c.instructions.is_some()) { - let read = read_cost(); - println!( - "{}: a counter read's own instructions, cycles and cache misses: {:.1}, {:.1}, {:.1}", - shape.name, read[0], read[1], read[2] - ); - for (kind, name) in CALLS.iter().enumerate() { - let made = tallies[0][kind].0; - if made == 0 { - continue; - } - let a_call = |at: usize| { - let each = (tallies.iter()) - .map(|tally| tally[kind].1[at] as f64 / tally[kind].0 as f64 - read[at]); - spread(each.collect()) - }; - let (median, low, high) = a_call(0); - let (cycles, misses) = (a_call(1).0, a_call(2).0); - let a_draw = made as f64 / draws; - println!( - "DRAW-CALL {} {name} calls_a_draw {a_draw:.3} a_call {median:.1} [{low:.1}, \ - {high:.1}] a_draw {:.1} cycles_a_call {cycles:.0} misses_a_call {misses:.1}", - shape.name, - median * a_draw - ); - } - } - Ok(()) -} - -/// `bytes` bytes of fresh host pages, read-write, never unmapped: private, as RADV refuses to -/// import shared anonymous memory (`host_memory.rs`'s `import_refused`). -fn host_pages(bytes: usize) -> Result> { - #[cfg(unix)] - // SAFETY: a fresh anonymous mapping, read-write, never unmapped. - let pages = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pages = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - bytes, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pages == libc::MAP_FAILED { - return Err(format!("mmap: {}", std::io::Error::last_os_error()).into()); - } - Ok(NonNull::new(pages.cast::()).ok_or("a null mapping")?) -} - -/// The library: the metallib at `metallib`, or `draw_costs.metal` compiled by `xcrun metal`. -fn library(device: &Device, metallib: Option<&Path>) -> Result { - if let Some(path) = metallib { - return Ok(device.new_library_with_data(&std::fs::read(path)?)?); - } - let scratch = std::env::temp_dir().join(format!("draw-costs-{}", std::process::id())); - std::fs::create_dir_all(&scratch)?; - let compiled = compile(&scratch).and_then(|metallib| Ok(std::fs::read(metallib)?)); - std::fs::remove_dir_all(&scratch)?; - Ok(device.new_library_with_data(&compiled?)?) -} - -/// `draw_costs.metal`, written into `scratch` and compiled there. -fn compile(scratch: &Path) -> Result { - let source = scratch.join("draw_costs.metal"); - std::fs::write(&source, include_str!("draw_costs.metal"))?; - let out = scratch.join("draw_costs.metallib"); - let status = Command::new("xcrun") - .args(["-sdk", "macosx", "metal", "-o"]) - .arg(&out) - .arg(&source) - .status() - .map_err(|error| format!("cannot run xcrun metal (or pass --metallib): {error}"))?; - match status.success() { - true => Ok(out), - false => Err(format!("xcrun metal: {status}").into()), - } -} - -fn main() -> Result<()> { - let mut shapes = Vec::new(); - let (mut runs, mut metallib, mut shadowed, mut pages) = (RUNS, None, false, false); - let (mut states, mut worker) = (SMALL_BLENDS.len(), false); - let mut options = Options { - calls: false, - counts: false, - heap: false, - threads: 1, - }; - let mut args = std::env::args().skip(1); - while let Some(arg) = args.next() { - match arg.as_str() { - "--runs" => runs = args.next().ok_or("--runs N")?.parse()?, - "--calls" => options.calls = true, - "--counts" => options.counts = true, - "--heap" => options.heap = true, - "--shadowed" => shadowed = true, - "--pages" => pages = true, - "--worker" => worker = true, - "--states" => { - states = args.next().ok_or("--states N")?.parse()?; - if !(1..=SMALL_BLENDS.len()).contains(&states) { - return Err(format!("--states N: 1 to {}", SMALL_BLENDS.len()).into()); - } - } - "--threads" => { - options.threads = args.next().ok_or("--threads N")?.parse()?; - if options.threads == 0 { - return Err("--threads N: at least 1".into()); - } - } - "--metallib" => metallib = Some(PathBuf::from(args.next().ok_or("--metallib PATH")?)), - name => shapes.push(*SHAPES.iter().find(|shape| shape.name == name).ok_or_else( - || { - format!( - "no shape {name}: ws, many, 10k, clips, damage, compositor, backdrops, \ - pass1, pass17, scene, rebinds, restated, moved, guest or splits" - ) - }, - )?), - } - } - if shapes.is_empty() { - shapes = SHAPES.to_vec(); - } - // On a Mac, the performance cores, which an efficiency core's slower draws would otherwise mix - // into the figures. - #[cfg(target_os = "macos")] - // SAFETY: sets the calling thread's own class; it takes no pointer. - unsafe { - libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0); - } - let mut device_options = DeviceOptions::default(); - device_options.gpu_times_from_host = true; - if shadowed { - device_options.policy.host_page_textures = HostPageTexturePolicy::Shadow; - } - if worker { - device_options.policy.render_lowering = RenderLoweringPolicy::Worker; - } - // With the shadow log on, its lines and each notice's text on stderr. - let log = metal2vulkan::env_vars::log_shadows(); - device_options.messages = Some(MessageSink::new(move |message| { - if message.degradation.is_some() { - NOTICES.fetch_add(1, Ordering::Relaxed); - } - if log && (message.degradation.is_some() || message.id_name == "metal2vulkan-shadows") { - eprintln!("{}: {}", message.id_name, message.text); - } - })); - let device = Device::system_default_with(&device_options)?; - println!("device: {}", device.name()); - let library = library(&device, metallib.as_deref())?; - let compositor = (shapes.iter()) - .any(|shape| matches!(shape.stream, Stream::Composited { .. } | Stream::Passes(_))) - .then_some((pages, states)); - let scene = (shapes.iter()).any(|shape| matches!(shape.stream, Stream::Scene { .. })); - let bench = Bench::new(device, &library, shadowed, (compositor, scene))?; - for shape in shapes { - measure(&bench, shape, runs, options)?; - } - println!("notices heard: {}", NOTICES.load(Ordering::Relaxed)); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/draw_reads.rs b/crates/metal2vulkan-runtime/examples/draw_reads.rs deleted file mode 100644 index e3ccdd10f..000000000 --- a/crates/metal2vulkan-runtime/examples/draw_reads.rs +++ /dev/null @@ -1,451 +0,0 @@ -//! Not a consumer's example: what the GPU pays a draw for reading the draw's own data, the tables -//! and bytes the runtime writes into the command buffer's upload arena (`upload.rs`), by what the -//! draw's fragment function reads. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example draw_reads -- \ -//! [--draws N] [--tile T] [--side S] [--runs R] [--only READS,...] [--idle MS] -//! ``` -//! -//! Each run is one command buffer of one render pass over an `S` by `S` `RGBA8Unorm` target -//! (1024 by default), cleared and stored, of `N` draws (2048 by default), each a 4-vertex -//! triangle strip over the next `T` by `T` tile of the target (64 by default), in rows. Each draw -//! sets its tile's corner and side as vertex bytes at index 0, which `tile_vertex` reads, then -//! what its fragment function reads at fragment index 0, by `READS`: -//! -//! - **`bytes`**: its color, as fragment bytes (`direct_fragment`, a `constant float4`); -//! - **`direct`**: the color, at the next of 256 slots of a `Private` buffer -//! (`set_fragment_buffer`, `direct_fragment`); -//! - **`ptr`**: the address of that color, at the next of 256 slots of another `Private` buffer -//! (`holder_fragment`: a `Holder` of one pointer, as an argument buffer holds a material's -//! parameters): every fragment loads the pointer and reads the color through it, which the -//! resident set resolves (`metal2vulkan::bind::ResidentSet`). -//! -//! Every color is opaque magenta, and once a kind's runs ended its target is read back: every -//! texel must hold it. `--idle MS` leaves the device idle for `MS` milliseconds before each run's -//! encoding, as long as a GPU that powers down when idle needs to (an RTX 5080 laptop GPU in -//! NVIDIA's runtime D3 after about 20 s): a run's encoding that waits for the GPU to wake shows in -//! its encoding time. -//! -//! Each line is the median over `R` runs (9 by default) after one not counted, of the command -//! buffer's GPU time (`gpu_start_time` to `gpu_end_time`) a draw, and of its time from the commit -//! to its completion on the host a draw (which also holds the GPU work the runtime records before -//! the command buffer's own, such as host calls' staged copies, `command_buffer/submit.rs`), with -//! the runtime's counts a command buffer that moved over the counted runs (`WorkCounts`, by name -//! from their `Debug` form): -//! -//! ```text -//! DRAW-READS draws tile side gpu_us_per_draw least wall_us_per_draw encode_ms most -//! DRAW-READS-COUNTS = ... -//! ``` -//! -//! The functions are LLVM text here, assembled by `llvm-as` from `PATH`. - -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, Device, LoadAction, Origin, - PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, - Texture, TextureDescriptor, WorkCounts, -}; -use std::collections::BTreeMap; -use std::io::Write; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// The slots of the colors' buffer and of the holders' buffer. -const SLOTS: u64 = 256; - -/// Every draw's color: opaque magenta, exact in `RGBA8Unorm`. -const COLOR: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; -const TEXEL: [u8; 4] = [255, 0, 255, 255]; - -/// `tile_vertex`: vertex `id`'s corner of the tile `rect` (x, y, width, height in normalized -/// device coordinates) sets at index 0; `direct_fragment`: the `float4` at fragment index 0; -/// `holder_fragment`: the `float4` the pointer of the `Holder` at fragment index 0 points at. -const FUNCTIONS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -%struct.Holder = type { ptr addrspace(1) }\n\n\ -define <4 x float> @tile_vertex(ptr addrspace(2) noundef %rect, i32 noundef %id) {\n\ -entry:\n\ - %r = load <4 x float>, ptr addrspace(2) %rect, align 16\n\ - %bx = and i32 %id, 1\n\ - %by = lshr i32 %id, 1\n\ - %fx = call float @air.convert.f.f32.u.i32(i32 %bx)\n\ - %fy = call float @air.convert.f.f32.u.i32(i32 %by)\n\ - %x0 = extractelement <4 x float> %r, i64 0\n\ - %y0 = extractelement <4 x float> %r, i64 1\n\ - %w = extractelement <4 x float> %r, i64 2\n\ - %h = extractelement <4 x float> %r, i64 3\n\ - %dx = fmul float %fx, %w\n\ - %dy = fmul float %fy, %h\n\ - %x = fadd float %x0, %dx\n\ - %y = fadd float %y0, %dy\n\ - %p0 = insertelement <4 x float> , float %x, i64 0\n\ - %p = insertelement <4 x float> %p0, float %y, i64 1\n\ - ret <4 x float> %p\n\ -}\n\n\ -define <4 x float> @direct_fragment(ptr addrspace(2) noundef %c) {\n\ -entry:\n\ - %v = load <4 x float>, ptr addrspace(2) %c, align 16\n\ - ret <4 x float> %v\n\ -}\n\n\ -define <4 x float> @holder_fragment(ptr addrspace(1) noundef readonly %h) {\n\ -entry:\n\ - %hp = getelementptr inbounds %struct.Holder, ptr addrspace(1) %h, i64 0, i32 0\n\ - %b = load ptr addrspace(1), ptr addrspace(1) %hp, align 8\n\ - %v = load <4 x float>, ptr addrspace(1) %b, align 16\n\ - ret <4 x float> %v\n\ -}\n\n\ -declare float @air.convert.f.f32.u.i32(i32)\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.vertex = !{!20}\n!air.fragment = !{!30, !40}\n\ -!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_constant_buffers\", i32 31}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @tile_vertex, !21, !23}\n\ -!21 = !{!22}\n\ -!22 = !{!\"air.position\", !\"air.arg_type_name\", !\"float4\"}\n\ -!23 = !{!24, !25}\n\ -!24 = !{i32 0, !\"air.buffer\", !\"air.buffer_size\", i32 16, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"rect\"}\n\ -!25 = !{i32 1, !\"air.vertex_id\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"id\"}\n\ -!26 = !{!27}\n\ -!27 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}\n\ -!30 = !{ptr @direct_fragment, !26, !31}\n\ -!31 = !{!32}\n\ -!32 = !{i32 0, !\"air.buffer\", !\"air.buffer_size\", i32 16, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"c\"}\n\ -!40 = !{ptr @holder_fragment, !26, !41}\n\ -!41 = !{!42}\n\ -!42 = !{i32 0, !\"air.indirect_buffer\", !\"air.buffer_size\", i32 8, !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.struct_type_info\", !43, !\"air.arg_type_size\", i32 8, !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"Holder\", !\"air.arg_name\", !\"h\"}\n\ -!43 = !{i32 0, i32 8, i32 0, !\"float4\", !\"p\", !\"air.indirect_argument\", !44}\n\ -!44 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"p\"}\n"; - -/// What a draw's fragment function reads. -#[derive(Clone, Copy, PartialEq)] -enum Reads { - Bytes, - Direct, - Pointer, -} - -impl Reads { - const ALL: [Reads; 3] = [Reads::Bytes, Reads::Direct, Reads::Pointer]; - - fn name(self) -> &'static str { - match self { - Reads::Bytes => "bytes", - Reads::Direct => "direct", - Reads::Pointer => "ptr", - } - } -} - -/// The run's shape: draws a command buffer, a tile's and the target's side in texels, timed runs, -/// and the kinds to run. -struct Shape { - draws: u32, - tile: u64, - side: u64, - runs: usize, - only: Vec, - /// How long the device is left idle before each run's encoding (`--idle`). - idle: Duration, -} - -impl Shape { - fn from_args() -> Result { - let mut shape = Shape { - draws: 2048, - tile: 64, - side: 1024, - runs: 9, - only: Vec::new(), - idle: Duration::ZERO, - }; - let mut args = std::env::args().skip(1); - while let Some(arg) = args.next() { - let mut value = || args.next().ok_or_else(|| format!("{arg} takes a value")); - match arg.as_str() { - "--draws" => shape.draws = value()?.parse()?, - "--tile" => shape.tile = value()?.parse()?, - "--side" => shape.side = value()?.parse()?, - "--runs" => shape.runs = value()?.parse()?, - "--only" => shape.only = value()?.split(',').map(str::to_owned).collect(), - "--idle" => shape.idle = Duration::from_millis(value()?.parse()?), - other => return Err(format!("unknown argument {other}").into()), - } - } - if shape.tile == 0 || !shape.side.is_multiple_of(shape.tile) || shape.runs == 0 { - return Err("the side must be a multiple of the tile, and runs at least 1".into()); - } - Ok(shape) - } - - fn runs(&self, reads: Reads) -> bool { - self.only.is_empty() || self.only.iter().any(|name| name == reads.name()) - } - - /// Draw `n`'s tile as vertex bytes: its corner and side in normalized device coordinates. - fn rect(&self, n: u32) -> Vec { - let across = self.side / self.tile; - let tile = u64::from(n) % (across * across); - let step = 2.0 * self.tile as f32 / self.side as f32; - let x = -1.0 + step * (tile % across) as f32; - let y = -1.0 + step * (tile / across) as f32; - [x, y, step, step] - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect() - } -} - -/// Run `tool` from `PATH` over `input`: its output. -fn tool(tool: &str, args: &[&str], input: &str) -> Result> { - let mut child = Command::new(tool) - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; - child - .stdin - .take() - .ok_or("no stdin")? - .write_all(input.as_bytes())?; - let output = child.wait_with_output()?; - if !output.status.success() { - return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); - } - Ok(output.stdout) -} - -/// The counts of `counts` by name, read from their `Debug` form. -fn counts(counts: &WorkCounts) -> BTreeMap { - let text = format!("{counts:?}"); - text.split([',', '{']) - .filter_map(|part| { - let (name, value) = part.split_once(':')?; - Some((name.trim().to_owned(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// Commit `command_buffer` and wait for it: an error where it did not complete. -fn run(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - match command_buffer.status() { - CommandBufferStatus::Completed => Ok(()), - status => Err(format!( - "a command buffer ended {status:?}: {:?}", - command_buffer.error() - ) - .into()), - } -} - -/// What every run draws with. -struct Ours<'a> { - device: &'a Device, - direct: RenderPipelineState, - holder: RenderPipelineState, - target: Texture, - /// [`SLOTS`] colors of 16 bytes. - colors: Buffer, - /// [`SLOTS`] addresses of 8 bytes, each of its color. - holders: Buffer, -} - -impl Ours<'_> { - /// One command buffer of `shape`'s draws reading as `reads` says, committed and waited for: - /// its GPU time a draw and its time from the commit to its completion a draw, in - /// microseconds, and its encoding time in milliseconds. - fn run(&self, reads: Reads, shape: &Shape) -> Result<(f64, f64, f64)> { - std::thread::sleep(shape.idle); - let begun = Instant::now(); - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(self.target.clone()); - color.load_action = LoadAction::Clear; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); - let mut encoder = command_buffer.render_command_encoder(&pass)?; - encoder.set_render_pipeline_state(match reads { - Reads::Pointer => &self.holder, - _ => &self.direct, - })?; - let bytes: Vec = COLOR.iter().flat_map(|value| value.to_le_bytes()).collect(); - for n in 0..shape.draws { - encoder.set_vertex_bytes(&shape.rect(n), 0)?; - let slot = u64::from(n) % SLOTS; - match reads { - Reads::Bytes => encoder.set_fragment_bytes(&bytes, 0)?, - Reads::Direct => encoder.set_fragment_buffer(Some(&self.colors), 16 * slot, 0)?, - Reads::Pointer => encoder.set_fragment_buffer(Some(&self.holders), 8 * slot, 0)?, - } - encoder.draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0)?; - } - encoder.end_encoding()?; - let encode = begun.elapsed().as_secs_f64() * 1e3; - let committed = Instant::now(); - run(&command_buffer)?; - let wall = committed.elapsed().as_secs_f64(); - let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; - let draws = f64::from(shape.draws); - Ok((gpu * 1e6 / draws, wall * 1e6 / draws, encode)) - } - - /// Every texel of the target, read back, is [`TEXEL`]. - fn check(&self, reads: Reads, shape: &Shape) -> Result<()> { - let row = shape.side * 4; - let readback = self - .device - .new_buffer(row * shape.side, ResourceOptions::shared())?; - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_texture_to_buffer( - &self.target, - 0, - 0, - Origin::new(0, 0, 0), - Size::new(shape.side, shape.side, 1), - &readback, - 0, - row, - row * shape.side, - BlitOption::None, - )?; - blit.end_encoding()?; - run(&command_buffer)?; - let contents = readback.contents().ok_or("the read-back has no contents")?; - // SAFETY: `contents` holds the buffer's bytes, which no command buffer writes now. - let texels = - unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; - match texels - .as_chunks::<4>() - .0 - .iter() - .position(|texel| *texel != TEXEL) - { - None => Ok(()), - Some(at) => Err(format!( - "{}: texel {at} is {:?}, not {TEXEL:?}", - reads.name(), - &texels[4 * at..4 * at + 4] - ) - .into()), - } - } -} - -/// A `Private` buffer holding `bytes`, copied in from a `Shared` one. -fn private_with(device: &Device, bytes: &[u8]) -> Result { - let staging = device.new_buffer_with_bytes(bytes, ResourceOptions::shared())?; - let buffer = device.new_buffer(bytes.len() as u64, ResourceOptions::private())?; - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, bytes.len() as u64)?; - blit.end_encoding()?; - run(&command_buffer)?; - Ok(buffer) -} - -fn main() -> Result<()> { - let shape = Shape::from_args()?; - let device = Device::system_default()?; - let name = device.name().to_string(); - println!("device: {name}"); - let bitcode = tool("llvm-as", &["-o", "-", "-"], FUNCTIONS)?; - let library = device - .new_library_with_compile_library(metal2vulkan::library::Library::from_air(&bitcode)?); - let vertex = library.new_function_with_name("tile_vertex")?; - let state = |fragment: &str| -> Result { - let fragment = library.new_function_with_name(fragment)?; - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) - }; - let mut target = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, shape.side, shape.side, false); - target.usage = TextureUsage::RENDER_TARGET; - target.resource_options = ResourceOptions::private(); - let colors: Vec = (0..SLOTS) - .flat_map(|_| COLOR) - .flat_map(|value| value.to_le_bytes()) - .collect(); - let colors = private_with(&device, &colors)?; - let holders: Vec = (0..SLOTS) - .flat_map(|slot| (colors.gpu_address().0 + 16 * slot).to_le_bytes()) - .collect(); - let ours = Ours { - device: &device, - direct: state("direct_fragment")?, - holder: state("holder_fragment")?, - target: device.new_texture(&target)?, - holders: private_with(&device, &holders)?, - colors, - }; - for reads in Reads::ALL { - if !shape.runs(reads) { - continue; - } - let mut per_draw = Vec::new(); - let mut walls = Vec::new(); - let mut encodes = Vec::new(); - let mut moved: BTreeMap = BTreeMap::new(); - for run in 0..=shape.runs { - let before = counts(&device.work_counts()); - let (per, wall, encode) = ours.run(reads, &shape)?; - if run == 0 { - continue; - } - per_draw.push(per); - walls.push(wall); - encodes.push(encode); - for (count, value) in counts(&device.work_counts()) { - let delta = value.saturating_sub(before.get(&count).copied().unwrap_or(0)); - if delta > 0 { - *moved.entry(count).or_default() += delta; - } - } - } - ours.check(reads, &shape)?; - per_draw.sort_by(f64::total_cmp); - walls.sort_by(f64::total_cmp); - encodes.sort_by(f64::total_cmp); - println!( - "DRAW-READS {} draws {} tile {} side {} gpu_us_per_draw {:.3} least {:.3} \ - wall_us_per_draw {:.3} encode_ms {:.3} most {:.3} {name}", - reads.name(), - shape.draws, - shape.tile, - shape.side, - per_draw[per_draw.len() / 2], - per_draw[0], - walls[walls.len() / 2], - encodes[encodes.len() / 2], - encodes[encodes.len() - 1], - ); - let line: Vec = (moved.iter()) - .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / shape.runs as f64)) - .collect(); - println!("DRAW-READS-COUNTS {} {}", reads.name(), line.join(" ")); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/fixed_index_draws.rs b/crates/metal2vulkan-runtime/examples/fixed_index_draws.rs deleted file mode 100644 index 20c955f41..000000000 --- a/crates/metal2vulkan-runtime/examples/fixed_index_draws.rs +++ /dev/null @@ -1,507 +0,0 @@ -//! Not a consumer's example: what a frame of indexed draws costs the GPU where a compute dispatch -//! before each draw writes that draw's indices into a buffer of its own, as a layer over another -//! graphics API that fixes up each draw's index buffer does, beside the same frame with its indices -//! written once before. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example fixed_index_draws -- \ -//! [--frames F] [--draws N] [--group G] [--pass-draws R] [--cb-passes Q] [--indices I] \ -//! [--side S] [--apart] [--only SHAPE,...] -//! ``` -//! -//! A frame is `N` draws (1,280 by default) of `I` indices each (1,536: 512 triangles), split into -//! groups of `G` draws (256). A group's first command buffer opens with a serial compute encoder of -//! `G` dispatches of the owned fixture's `fix_indices` -//! (`validation/fixtures/public/examples/fixed_indices.metal`), one per draw: each binds the -//! frame's one `Private` source of 16-bit indices at the draw's place, the draw's own `Private` -//! buffer of `I` 32-bit indices, and the draw's place and count as bytes, and writes the widened -//! indices into the draw's buffer, one thread an index in threadgroups of 64. Then the group's -//! draws, `R` (26) to a render encoder, `Q` (4) render encoders to a command buffer: each pass loads -//! and stores one `Private` `RGBA8Unorm` target of `S` (1024) texels a side (`--apart`: not loaded, -//! so its draws record in a secondary command buffer the pass executes at its end), and each draw -//! draws its triangles from its buffer through `placed_vertex` and `flat_fragment`, every triangle -//! a few texels wide. The defaults are the shape a GL benchmark's frames took through Apple's -//! GL-on-Metal layer on the runtime (each second: about 470 compute encoders of about 256 -//! dispatches, 4,650 render passes of about 26 indexed draws, 1,270 command buffers). -//! -//! Two frames are in flight, each with its own draws' buffers, on one queue. The shapes: -//! -//! - **`fixed`**: the frame as above; -//! - **`prefixed`**: the same command buffers and passes without the compute encoders: each draw -//! reads the indices one `fixed` frame wrote before the timed ones; -//! - **`dispatches`**: the compute encoders alone, each in a command buffer of its own. -//! -//! Each frame's GPU time is the union of its command buffers' spans from `gpu_start_time` to -//! `gpu_end_time` (`busy`), and its span from its first command buffer's start to its last's end; -//! each line is the median over `F` frames (60) after 10 not counted, with the runtime's counts per -//! frame that moved (`WorkCounts`, by name from their `Debug` form). Then each draw's indices of -//! the last frame are read back and checked against the source's. -//! -//! ```text -//! FIXED draws group pass_draws cb_passes indices gpu_ms -//! least span_ms us_per_draw -//! FIXED-COUNTS = ... -//! ``` -//! -//! Measured on an RTX 5080 Laptop GPU (release, the defaults, 60 frames): `fixed` 0.526 ms of GPU -//! busy a frame, `prefixed` 0.404 ms, `dispatches` 0.116 ms (0.09 us a dispatch); with `--apart` -//! 0.555, 0.455 and 0.116 ms. So the compute encoders cost their dispatches' own time and the -//! frame's 5 compute-to-render transitions next to nothing: no barrier records between the -//! dispatches (each writes a buffer of its own), and 15 `vkCmdPipelineBarrier` a frame. - -use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputePipelineState, Device, - DeviceOptions, LoadAction, PipelineOptions, RenderPassDescriptor, RenderPipelineState, - ResourceOptions, Size, StoreAction, TextureDescriptor, WorkCounts, -}; -use std::collections::{BTreeMap, VecDeque}; -use std::process::Command; -use std::time::Duration; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// The threads of a `fix_indices` threadgroup. -const THREADS: u64 = 64; - -/// Frames run before the timed ones. -const WARM: usize = 10; - -/// Frames in flight. -const IN_FLIGHT: usize = 2; - -/// The vertices the source's indices name: triangles of three in a row, each a few texels wide. -const VERTICES: u32 = 3 * 4096; - -/// The shapes, in the order they run. -const SHAPES: [&str; 3] = ["fixed", "prefixed", "dispatches"]; - -/// The run's shape (the module docs). -struct Shape { - frames: usize, - draws: u32, - group: u32, - pass_draws: u32, - cb_passes: u32, - indices: u32, - side: u64, - apart: bool, - only: Option>, -} - -impl Shape { - fn from_args() -> Result { - let mut shape = Shape { - frames: 60, - draws: 1280, - group: 256, - pass_draws: 26, - cb_passes: 4, - indices: 1536, - side: 1024, - apart: false, - only: None, - }; - let mut args = std::env::args().skip(1); - while let Some(flag) = args.next() { - if flag == "--apart" { - shape.apart = true; - continue; - } - let value = args.next().ok_or(format!("{flag} takes a value"))?; - match flag.as_str() { - "--frames" => shape.frames = value.parse()?, - "--draws" => shape.draws = value.parse()?, - "--group" => shape.group = value.parse()?, - "--pass-draws" => shape.pass_draws = value.parse()?, - "--cb-passes" => shape.cb_passes = value.parse()?, - "--indices" => shape.indices = value.parse()?, - "--side" => shape.side = value.parse()?, - "--only" => shape.only = Some(value.split(',').map(str::to_owned).collect()), - _ => return Err(format!("unknown flag {flag}").into()), - } - } - if shape.frames == 0 || shape.draws == 0 || shape.group == 0 || shape.pass_draws == 0 { - return Err("--frames, --draws, --group and --pass-draws take 1 or more".into()); - } - if shape.cb_passes == 0 || shape.indices % 3 != 0 || shape.indices == 0 { - return Err("--cb-passes takes 1 or more, --indices a multiple of 3".into()); - } - if shape.indices > VERTICES { - return Err(format!("--indices takes at most {VERTICES}").into()); - } - Ok(shape) - } - - fn runs(&self, name: &str) -> bool { - self.only - .as_ref() - .is_none_or(|only| only.iter().any(|shape| shape == name)) - } -} - -/// The owned fixture's functions, assembled by `llvm-as` from `PATH`. -struct Functions { - fix: ComputePipelineState, - draw: RenderPipelineState, -} - -impl Functions { - fn new(device: &Device) -> Result { - let path = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../metal2vulkan-validation/fixtures/public/examples/fixed_indices.ll" - ); - let output = Command::new("llvm-as") - .args(["-o", "-", path]) - .output() - .map_err(|error| format!("cannot run llvm-as (put it on PATH): {error}"))?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - return Err(format!("llvm-as {path}: {stderr}").into()); - } - let library = device.new_library_with_compile_library( - metal2vulkan::library::Library::from_air(&output.stdout)?, - ); - let options = PipelineOptions::default(); - let kernel = library.new_function_with_name("fix_indices")?; - let fix = device.new_compute_pipeline_state_with_function(&kernel, &options)?; - let vertex = library.new_function_with_name("placed_vertex")?; - let fragment = library.new_function_with_name("flat_fragment")?; - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let draw = device.new_render_pipeline_state(&descriptor, &options)?; - Ok(Functions { fix, draw }) - } -} - -/// A `Private` buffer holding `bytes`, copied in from a `Shared` one by a blit. -fn private_with(device: &Device, queue: &CommandQueue, bytes: &[u8]) -> Result { - let staging = device.new_buffer_with_bytes(bytes, ResourceOptions::shared())?; - let buffer = device.new_buffer(bytes.len() as u64, ResourceOptions::private())?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, bytes.len() as u64)?; - blit.end_encoding()?; - finish(&command_buffer)?; - Ok(buffer) -} - -/// Commit `command_buffer` and wait for it. -fn finish(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer.commit()?; - completed(command_buffer) -} - -/// Wait for a committed `command_buffer`: an error where it did not complete. -fn completed(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - match command_buffer.status() { - CommandBufferStatus::Completed => Ok(()), - status => Err(format!( - "a command buffer ended {status:?}: {:?}", - command_buffer.error() - ) - .into()), - } -} - -/// What every frame draws from: the source's indices, the vertices' positions, the target's -/// pass, and each in-flight frame's draws' buffers. -struct Scene { - source: Buffer, - /// The source's indices, as the check reads them. - indices: Vec, - positions: Buffer, - pass: RenderPassDescriptor, - /// Per frame in flight, one buffer per draw. - fixed: Vec>, -} - -impl Scene { - fn new(device: &Device, queue: &CommandQueue, shape: &Shape) -> Result { - let count = shape.draws as usize * shape.indices as usize; - // Each draw's indices start at a triangle of their own, the source's indices name the - // vertices in a row, wrapping at `VERTICES`. - let indices: Vec = (0..count).map(|at| (at as u32 % VERTICES) as u16).collect(); - let index_bytes: Vec = indices - .iter() - .flat_map(|index| index.to_le_bytes()) - .collect(); - let source = private_with(device, queue, &index_bytes)?; - // Triangle `t`'s three corners lie a texel or two apart at a cell of a 64 by 64 grid. - let texel = 2.0 / shape.side as f32; - let positions: Vec = (0..VERTICES) - .flat_map(|vertex| { - let cell = (vertex / 3) % 4096; - let x = -1.0 + (cell % 64) as f32 * 2.0 / 64.0 + texel; - let y = -1.0 + (cell / 64) as f32 * 2.0 / 64.0 + texel; - let (dx, dy) = match vertex % 3 { - 0 => (0.0, 0.0), - 1 => (2.0 * texel, 0.0), - _ => (0.0, 2.0 * texel), - }; - [x + dx, y + dy] - }) - .flat_map(|value| value.to_le_bytes()) - .collect(); - let positions = private_with(device, queue, &positions)?; - let mut texture = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, shape.side, shape.side, false); - texture.usage = TextureUsage::RENDER_TARGET; - texture.resource_options = ResourceOptions::private(); - let target = device.new_texture(&texture)?; - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target); - color.load_action = match shape.apart { - true => LoadAction::DontCare, - false => LoadAction::Load, - }; - color.store_action = StoreAction::Store; - let bytes = u64::from(shape.indices) * 4; - let fixed = (0..IN_FLIGHT) - .map(|_| { - (0..shape.draws) - .map(|_| Ok(device.new_buffer(bytes, ResourceOptions::private())?)) - .collect::>>() - }) - .collect::>>()?; - Ok(Scene { - source, - indices, - positions, - pass, - fixed, - }) - } -} - -/// One frame of `name`'s command buffers, committed, for the frame in flight `slot`. -fn frame( - queue: &CommandQueue, - functions: &Functions, - scene: &Scene, - shape: &Shape, - (name, slot): (&str, usize), -) -> Result> { - let fixed = &scene.fixed[slot]; - let mut committed = Vec::new(); - let threadgroups = u64::from(shape.indices).div_ceil(THREADS); - for first in (0..shape.draws).step_by(shape.group as usize) { - let draws = first..(first + shape.group).min(shape.draws); - let mut command_buffer = queue.command_buffer()?; - if name != "prefixed" { - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(&functions.fix)?; - for draw in draws.clone() { - let place = draw * shape.indices; - let arguments: Vec = [place, shape.indices, 0] - .iter() - .flat_map(|word| word.to_le_bytes()) - .collect(); - encoder.set_buffer(Some(&scene.source), 0, 0)?; - encoder.set_buffer(Some(&fixed[draw as usize]), 0, 1)?; - encoder.set_bytes(&arguments, 2)?; - encoder.dispatch_threadgroups( - Size::new(threadgroups, 1, 1), - Size::new(THREADS, 1, 1), - )?; - } - encoder.end_encoding()?; - } - if name == "dispatches" { - command_buffer.commit()?; - committed.push(command_buffer); - continue; - } - let passes: Vec = draws.clone().step_by(shape.pass_draws as usize).collect(); - for (at, pass_first) in passes.iter().enumerate() { - if at > 0 && at % shape.cb_passes as usize == 0 { - command_buffer.commit()?; - committed.push(command_buffer); - command_buffer = queue.command_buffer()?; - } - let mut encoder = command_buffer.render_command_encoder(&scene.pass)?; - encoder.set_render_pipeline_state(&functions.draw)?; - encoder.set_vertex_buffer(Some(&scene.positions), 0, 0)?; - for draw in *pass_first..(pass_first + shape.pass_draws).min(draws.end) { - encoder.draw_indexed_primitives( - PrimitiveType::Triangle, - shape.indices, - IndexType::UInt32, - &fixed[draw as usize], - 0, - 1, - 0, - 0, - )?; - } - encoder.end_encoding()?; - } - command_buffer.commit()?; - committed.push(command_buffer); - } - Ok(committed) -} - -/// A completed frame's GPU times in seconds: the union of its command buffers' spans, and its span. -fn times(frame: &[CommandBuffer]) -> Result<(f64, f64)> { - let mut spans = Vec::with_capacity(frame.len()); - for command_buffer in frame { - completed(command_buffer)?; - spans.push(( - command_buffer.gpu_start_time()?, - command_buffer.gpu_end_time()?, - )); - } - spans.sort_by(|a, b| a.0.total_cmp(&b.0)); - let (mut busy, mut reached) = (0.0, f64::MIN); - for &(start, end) in &spans { - let start = start.max(reached); - if end > start { - busy += end - start; - } - reached = reached.max(end); - } - let first = spans.first().map_or(0.0, |span| span.0); - Ok((busy, reached.max(first) - first)) -} - -/// The counts of `counts` by name, read from their `Debug` form. -fn counts(counts: &WorkCounts) -> BTreeMap { - let text = format!("{counts:?}"); - text.split([',', '{']) - .filter_map(|part| { - let (name, value) = part.split_once(':')?; - Some((name.trim().to_owned(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// Run `name`'s frames: the `FIXED` and `FIXED-COUNTS` lines. -fn run( - device: &Device, - queue: &CommandQueue, - (functions, scene): (&Functions, &Scene), - shape: &Shape, - name: &str, -) -> Result<()> { - // The frames in flight, each with whether it is timed. - let mut flight: VecDeque<(bool, Vec)> = VecDeque::new(); - let mut samples = Vec::with_capacity(shape.frames); - let mut before = None; - for at in 0..WARM + shape.frames { - if at == WARM { - // Every warm frame completed: the counts from here are the timed frames' alone. - while let Some((_, earlier)) = flight.pop_front() { - times(&earlier)?; - } - before = Some(counts(&device.work_counts())); - } - if flight.len() == IN_FLIGHT { - if let Some((timed, earlier)) = flight.pop_front() { - let measured = times(&earlier)?; - if timed { - samples.push(measured); - } - } - } - let committed = frame(queue, functions, scene, shape, (name, at % IN_FLIGHT))?; - flight.push_back((at >= WARM, committed)); - } - while let Some((_, earlier)) = flight.pop_front() { - samples.push(times(&earlier)?); - } - let after = counts(&device.work_counts()); - let before = before.ok_or("no timed frame")?; - let mut busy: Vec = samples.iter().map(|sample| sample.0).collect(); - let mut span: Vec = samples.iter().map(|sample| sample.1).collect(); - busy.sort_by(f64::total_cmp); - span.sort_by(f64::total_cmp); - let median = busy[busy.len() / 2]; - println!( - "FIXED {name} draws {} group {} pass_draws {} cb_passes {} indices {} gpu_ms {:.3} least \ - {:.3} span_ms {:.3} us_per_draw {:.3} {}", - shape.draws, - shape.group, - shape.pass_draws, - shape.cb_passes, - shape.indices, - median * 1e3, - busy[0] * 1e3, - span[span.len() / 2] * 1e3, - median * 1e6 / f64::from(shape.draws), - device.name(), - ); - let frames = shape.frames as f64; - let moved: Vec = (after.iter()) - .filter_map(|(name, value)| { - let moved = value.saturating_sub(before.get(name).copied().unwrap_or(0)); - (moved > 0).then(|| format!("{name}={:.1}", moved as f64 / frames)) - }) - .collect(); - println!("FIXED-COUNTS {name} {}", moved.join(" ")); - Ok(()) -} - -/// Each draw's indices in the frame in flight `slot`, read back: the source's, widened. -fn check( - device: &Device, - queue: &CommandQueue, - scene: &Scene, - shape: &Shape, - slot: usize, -) -> Result<()> { - let bytes = u64::from(shape.indices) * 4; - let readback = device.new_buffer(bytes * u64::from(shape.draws), ResourceOptions::shared())?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - for (draw, fixed) in scene.fixed[slot].iter().enumerate() { - blit.copy_from_buffer_to_buffer(fixed, 0, &readback, draw as u64 * bytes, bytes)?; - } - blit.end_encoding()?; - finish(&command_buffer)?; - let contents = readback.contents().ok_or("the readback has no contents")?; - // SAFETY: `contents` holds the buffer's `length` bytes, and no command buffer writes them now. - let read = unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; - for (at, word) in read.as_chunks::<4>().0.iter().enumerate() { - let got = u32::from_le_bytes(*word); - let want = u32::from(scene.indices[at]); - if got != want { - return Err(format!("index {at} of the fixed draws is {got}, not {want}").into()); - } - } - Ok(()) -} - -fn main() -> Result<()> { - let shape = Shape::from_args()?; - let device = Device::system_default_with(&DeviceOptions::default())?; - println!("device: {}", device.name()); - let queue = device.new_command_queue()?; - let functions = Functions::new(&device)?; - let scene = Scene::new(&device, &queue, &shape)?; - // Both frames in flight's draws' buffers written once, for `prefixed`. - for slot in 0..IN_FLIGHT { - for command_buffer in frame(&queue, &functions, &scene, &shape, ("fixed", slot))? { - completed(&command_buffer)?; - } - check(&device, &queue, &scene, &shape, slot)?; - } - for name in SHAPES.into_iter().filter(|name| shape.runs(name)) { - run(&device, &queue, (&functions, &scene), &shape, name)?; - check(&device, &queue, &scene, &shape, 0)?; - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/heap_placement.rs b/crates/metal2vulkan-runtime/examples/heap_placement.rs deleted file mode 100644 index 8632d2af8..000000000 --- a/crates/metal2vulkan-runtime/examples/heap_placement.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! A placement heap with textures at offsets the program chooses: the device's size and alignment -//! for the texture, a `Private` heap of two, a texture at each offset, and fences that order the -//! encoders that use them (a heap's resources are untracked by default, as on Metal). -//! -//! ```sh -//! cargo run -p metal2vulkan-runtime --example heap_placement [-- path/to/library.metallib] -//! ``` -//! -//! A blit uploads texels into the first texture, the kernel `invert_texels` of the repository's -//! owned fixture (`validation/fixtures/public/examples/runtime_examples.metal`, or of the metallib -//! the argument names) writes their inverse into the second, and a blit reads it back. - -mod common; - -use metal2vulkan::metal::{PixelFormat, TextureUsage}; -use metal2vulkan_runtime::{ - BlitOption, Device, HeapDescriptor, HeapType, Origin, PipelineOptions, ResourceOptions, Size, - TextureDescriptor, -}; - -/// The textures' side, in texels. -const SIDE: u64 = 16; - -fn main() -> common::Result<()> { - let device = Device::system_default()?; - println!("device: {}", device.name()); - let library = common::library(&device)?; - let function = library.new_function_with_name("invert_texels")?; - let state = - device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - - // A texture's storage and CPU cache modes are its heap's. - let mut texture = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); - texture.usage = TextureUsage::SHADER_READ.union(TextureUsage::SHADER_WRITE); - texture.resource_options = ResourceOptions::private(); - - // `heapTextureSizeAndAlignWithDescriptor:`: this device's own requirement for the texture, - // which is not an Apple GPU's. A program places by the answer, never by a constant. - let need = device.heap_texture_size_and_align(&texture)?; - let stride = need.size.next_multiple_of(need.align); - println!( - "a {SIDE}x{SIDE} RGBA8Unorm texture takes {} bytes at a multiple of {}", - need.size, need.align - ); - - // `MTLHeapTypePlacement`: the program places each resource at an offset. - let heap = device.new_heap(&HeapDescriptor::new( - HeapType::Placement, - 2 * stride, - ResourceOptions::private(), - ))?; - // `newTextureWithDescriptor:offset:`. - let source = heap.new_texture_at_offset(&texture, 0)?; - let destination = heap.new_texture_at_offset(&texture, stride)?; - println!( - "heap of {} bytes, hazard tracking {:?}; textures at 0 and {stride}", - heap.size(), - heap.hazard_tracking_mode() - ); - - let row = SIDE * 4; - let texels: Vec = (0..SIDE * SIDE) - .flat_map(|i| [i as u8, (i * 3) as u8, 255 - i as u8, 200]) - .collect(); - let upload = device.new_buffer_with_bytes(&texels, ResourceOptions::shared())?; - let download = device.new_buffer(row * SIDE, ResourceOptions::shared())?; - - // The heap's resources are untracked: the encoders order themselves with fences - // (`updateFence:` after the writes, `waitForFence:` before the reads), as on Metal. - let uploaded = device.new_fence(); - let inverted = device.new_fence(); - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_texture( - &upload, - 0, - row, - row * SIDE, - Size::new(SIDE, SIDE, 1), - &source, - 0, - 0, - Origin::new(0, 0, 0), - BlitOption::None, - )?; - blit.update_fence(&uploaded)?; - blit.end_encoding()?; - - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.wait_for_fence(&uploaded)?; - encoder.set_compute_pipeline_state(&state)?; - encoder.set_texture(Some(&source), 0)?; - encoder.set_texture(Some(&destination), 1)?; - encoder.dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(8, 8, 1))?; - encoder.update_fence(&inverted)?; - encoder.end_encoding()?; - - let mut blit = command_buffer.blit_command_encoder()?; - blit.wait_for_fence(&inverted)?; - blit.copy_from_texture_to_buffer( - &destination, - 0, - 0, - Origin::new(0, 0, 0), - Size::new(SIDE, SIDE, 1), - &download, - 0, - row, - row * SIDE, - BlitOption::None, - )?; - blit.end_encoding()?; - common::run(&command_buffer)?; - - // Each color channel inverted, alpha kept. - let read = common::bytes(&download)?; - for (at, (texel, original)) in read - .as_chunks::<4>() - .0 - .iter() - .zip(texels.as_chunks::<4>().0.iter()) - .enumerate() - { - let expected = [ - 255 - original[0], - 255 - original[1], - 255 - original[2], - original[3], - ]; - if *texel != expected { - return Err(format!("texel {at} is {texel:?}, not {expected:?}").into()); - } - } - println!( - "texel 1 was {:?} and is {:?}: every texel as expected", - &texels[4..8], - &read[4..8] - ); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/allocs.rs b/crates/metal2vulkan-runtime/examples/host_ab/allocs.rs deleted file mode 100644 index 087dc92d3..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/allocs.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! The process's allocator, counting each thread's allocations while [`counting`] runs: the -//! calls workload's `*_allocs` metrics. Outside it each allocation pays one relaxed load more -//! than the system allocator's own work. - -use std::alloc::{GlobalAlloc, Layout, System}; -use std::cell::Cell; -use std::sync::atomic::{AtomicBool, Ordering}; - -/// Allocations are counted. -static ON: AtomicBool = AtomicBool::new(false); - -struct Counting; - -#[global_allocator] -static ALLOCATOR: Counting = Counting; - -thread_local! { - /// Allocations (and reallocations) this thread made. - static MADE: Cell = const { Cell::new(0) }; -} - -fn note() { - if ON.load(Ordering::Relaxed) { - // A thread being torn down no longer counts. - let _ = MADE.try_with(|made| made.set(made.get() + 1)); - } -} - -/// Run `f` with allocations counted. -pub fn counting(f: impl FnOnce() -> T) -> T { - ON.store(true, Ordering::Relaxed); - let out = f(); - ON.store(false, Ordering::Relaxed); - out -} - -/// The allocations this thread made so far. -pub fn this_thread() -> u64 { - MADE.try_with(Cell::get).unwrap_or(0) -} - -// SAFETY: every call goes to the system allocator as it came. -unsafe impl GlobalAlloc for Counting { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - note(); - // SAFETY: the caller's contract, passed on. - unsafe { System.alloc(layout) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - note(); - // SAFETY: as `alloc`. - unsafe { System.alloc_zeroed(layout) } - } - - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - // SAFETY: as `alloc`. - unsafe { System.dealloc(ptr, layout) } - } - - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - note(); - // SAFETY: as `alloc`. - unsafe { System.realloc(ptr, layout, new_size) } - } -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/gpu.rs b/crates/metal2vulkan-runtime/examples/host_ab/gpu.rs deleted file mode 100644 index db32c3254..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/gpu.rs +++ /dev/null @@ -1,552 +0,0 @@ -//! The Metal calls a workload makes, as one trait both sides implement: native Metal -//! (`native.rs`) and the runtime (`runtime.rs`). Each method is one Metal call, or the few calls a -//! descriptor takes, so a workload written once against it makes the same calls on either side. - -use std::path::Path; - -/// The pixel formats the workloads use. -#[derive(Clone, Copy, Debug)] -pub enum Format { - Bgra8, - Rgba8, - Rgba16Float, - /// A depth attachment's (`texture` with `target`). - Depth32Float, -} - -/// One side of the A/B: a device, its queue, and Metal's calls on them. Its device, libraries and -/// render pipeline states are shared by threads that each draw through a queue of their own -/// (`threads`). -pub trait Gpu: Sync { - type Library: Sync; - type RenderPipeline: Sync; - type ComputePipeline; - type Buffer; - type Texture; - type Sampler; - type CommandBuffer; - type RenderEncoder; - type ComputeEncoder; - type Heap; - type DepthStencil; - type IndirectCommands; - type SharedEvent; - type Listener; - type Pass; - type BlitEncoder; - type Fence; - - /// The side and the device's name. - fn label(&self) -> String; - - /// Another handle on the same device, with a command queue of its own: a thread's own - /// (`threads`). - fn with_own_queue(&self) -> Self - where - Self: Sized; - - /// `newLibraryWithURL:` (native) or `newLibraryWithData:` of the file's bytes (the runtime). - fn library(&self, metallib: &Path) -> Self::Library; - /// `newRenderPipelineStateWithDescriptor:error:` of two functions and one color attachment. - fn render_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - format: Format, - blend: bool, - ) -> Self::RenderPipeline; - /// As `render_pipeline` into `BGRA8Unorm`, with a `Depth32Float` depth attachment, blending - /// source over destination by the source's alpha where `blend`. - fn depth_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - blend: bool, - ) -> Self::RenderPipeline; - /// `newDepthStencilStateWithDescriptor:`: a depth compare of `Less` with writes, or of - /// `LessEqual` without. - fn depth_stencil(&self, writes: bool) -> Self::DepthStencil; - /// `newComputePipelineStateWithFunction:error:`. - fn compute_pipeline(&self, library: &Self::Library, kernel: &str) -> Self::ComputePipeline; - /// `newComputePipelineStateWithDescriptor:options:reflection:error:` of `kernel`, with - /// `supportIndirectCommandBuffers`. - fn indirect_compute_pipeline( - &self, - library: &Self::Library, - kernel: &str, - ) -> Self::ComputePipeline; - /// As `render_pipeline` of `vertex` and `fragment` into `BGRA8Unorm`, without blending, with - /// `supportIndirectCommandBuffers`. - fn indirect_render_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - ) -> Self::RenderPipeline; - /// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` of `count` draws of - /// `Shared` storage whose commands inherit the pipeline state, not the buffers, and bind - /// `vertex_buffers` vertex buffers and no fragment buffer. - fn indirect_draws(&self, count: usize, vertex_buffers: usize) -> Self::IndirectCommands; - /// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` of `count` concurrent - /// dispatches, each binding one kernel buffer and inheriting nothing, of `Private` storage. - fn indirect_commands(&self, count: usize) -> Self::IndirectCommands; - /// The `gpuResourceID` of `commands`, as a kernel reads it from an argument buffer. - fn commands_id(&self, commands: &Self::IndirectCommands) -> u64; - /// The `gpuResourceID` of `state`, made with `supportIndirectCommandBuffers`. - fn pipeline_id(&self, state: &Self::ComputePipeline) -> u64; - /// The `gpuResourceID` of `texture`, as a kernel reads it from an argument buffer. - fn texture_id(&self, texture: &Self::Texture) -> u64; - /// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` of `count` concurrent - /// dispatches of `Shared` storage that inherit nothing and bind one kernel buffer, for the - /// CPU to encode. - fn cpu_indirect_commands(&self, count: usize) -> Self::IndirectCommands; - /// As `cpu_indirect_commands`, of draws of primitives binding one vertex and one fragment - /// buffer. - fn cpu_indirect_draws(&self, count: usize) -> Self::IndirectCommands; - /// `indirectComputeCommandAtIndex:`, then the command's `setComputePipelineState:`. - fn command_pipeline( - &self, - commands: &Self::IndirectCommands, - index: usize, - state: &Self::ComputePipeline, - ); - /// `indirectComputeCommandAtIndex:`, then `setKernelBuffer:offset:atIndex:` at index 0. - fn command_kernel_buffer( - &self, - commands: &Self::IndirectCommands, - index: usize, - buffer: &Self::Buffer, - offset: usize, - ); - /// `indirectComputeCommandAtIndex:`, then - /// `concurrentDispatchThreadgroups:threadsPerThreadgroup:` of `groups` of 64 threads. - fn command_dispatch(&self, commands: &Self::IndirectCommands, index: usize, groups: usize); - /// `indirectComputeCommandAtIndex:`, then `setBarrier`. - fn command_barrier(&self, commands: &Self::IndirectCommands, index: usize); - /// `indirectComputeCommandAtIndex:`, then Apple's private `getKernelBufferAddressAtIndex:` of - /// index 0 (the runtime's read-back of it). - fn command_kernel_buffer_address(&self, commands: &Self::IndirectCommands, index: usize) - -> u64; - /// `indirectComputeCommandAtIndex:`, then Apple's private `hasBarrier`. - fn command_has_barrier(&self, commands: &Self::IndirectCommands, index: usize) -> bool; - /// `indirectRenderCommandAtIndex:`, then `setRenderPipelineState:`. - fn draw_command_pipeline( - &self, - commands: &Self::IndirectCommands, - index: usize, - state: &Self::RenderPipeline, - ); - /// `indirectRenderCommandAtIndex:`, then `setVertexBuffer:offset:atIndex:` at index 0. - fn draw_command_vertex_buffer( - &self, - commands: &Self::IndirectCommands, - index: usize, - buffer: &Self::Buffer, - offset: usize, - ); - /// `indirectRenderCommandAtIndex:`, then - /// `drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:` of a triangle strip of - /// four vertices, one instance. - fn draw_command_draw(&self, commands: &Self::IndirectCommands, index: usize); - /// `indirectRenderCommandAtIndex:`, then Apple's private `getVertexBufferAddressAtIndex:` of - /// index 0 (the runtime's read-back of it). - fn draw_command_vertex_buffer_address( - &self, - commands: &Self::IndirectCommands, - index: usize, - ) -> u64; - - /// `newBufferWithLength:options:` of `Shared` storage. - fn buffer(&self, length: usize) -> Self::Buffer; - /// `newBufferWithBytes:length:options:` of `Shared` storage. - fn buffer_with(&self, bytes: &[u8]) -> Self::Buffer; - /// `newBufferWithBytesNoCopy:length:options:deallocator:` of `Shared` storage, no - /// deallocator. - /// - /// # Safety - /// - /// `pointer` is page-aligned, `length` (a multiple of the page size) bytes of read-write - /// memory that outlive the buffer. - unsafe fn buffer_no_copy(&self, pointer: *mut u8, length: usize) -> Self::Buffer; - /// `newHeapWithDescriptor:` of a `Placement` heap of `Shared` storage, `size` bytes. - fn heap(&self, size: usize) -> Self::Heap; - /// The runtime's heap of the same over `size` bytes of host pages at `pointer` - /// (`new_heap_with_bytes_no_copy`); none natively. - /// - /// # Safety - /// - /// `pointer` is page-aligned, `size` (a multiple of the page size) bytes of read-write memory - /// that outlive the heap and every texture placed in it. - unsafe fn heap_no_copy(&self, pointer: *mut u8, size: usize) -> Option; - /// `newTextureWithDescriptor:offset:` of `heap`: a 2D `BGRA8Unorm` texture of one level that - /// passes render to and the shaders read, at `offset`, whose contents Metal does not optimize - /// for the GPU (`allowGPUOptimizedContents` off), so its bytes in the heap are its texels. - fn heap_texture( - &self, - heap: &Self::Heap, - width: usize, - height: usize, - offset: usize, - ) -> Self::Texture; - /// `newTextureWithDescriptor:offset:bytesPerRow:` of `buffer`: a 2D `BGRA8Unorm` texture of - /// one level that passes render to and the shaders read, its rows `bytes_per_row` apart from - /// `offset`, as a window surface's texture over its memory. - fn buffer_texture( - &self, - buffer: &Self::Buffer, - size: (usize, usize), - offset: usize, - bytes_per_row: usize, - ) -> Self::Texture; - /// A 2D texture of one level: a render target of `Private` storage, or a `Shared` one the - /// shaders read. - fn texture(&self, format: Format, width: usize, height: usize, target: bool) -> Self::Texture; - /// `newHeapWithDescriptor:` of a `Placement` heap of `size` bytes of `Shared` storage, - /// its resources' hazards tracked. - fn tracked_heap(&self, size: usize) -> Self::Heap; - /// `newTextureWithDescriptor:offset:` of a `side` x `side` 2D texture of one level at - /// `offset` of `heap`, which draws render into and shaders read, its contents Metal's to - /// optimize. - fn heap_render_texture( - &self, - heap: &Self::Heap, - format: Format, - side: usize, - offset: usize, - ) -> Self::Texture; - /// `replaceRegion:mipmapLevel:withBytes:bytesPerRow:` over the whole level 0. - fn replace_region( - &self, - texture: &Self::Texture, - size: (usize, usize), - bytes: &[u8], - row: usize, - ); - /// `getBytes:bytesPerRow:fromRegion:mipmapLevel:` of the whole level 0. - fn get_bytes( - &self, - texture: &Self::Texture, - size: (usize, usize), - bytes: &mut [u8], - row: usize, - ); - /// The first `bytes.len()` bytes of a `Shared` buffer's `contents`, no GPU work writing them. - fn read_buffer(&self, buffer: &Self::Buffer, bytes: &mut [u8]); - /// Set every byte of a `Shared` buffer's `contents` to `value`, no GPU work using them. - fn write_buffer(&self, buffer: &Self::Buffer, value: u8); - /// `newSamplerStateWithDescriptor:`, nearest or linear. - fn sampler(&self, linear: bool) -> Self::Sampler; - - /// `commandBuffer`. - fn command_buffer(&self) -> Self::CommandBuffer; - /// `renderCommandEncoderWithDescriptor:` of one color attachment, cleared or loaded, stored. - fn render_encoder( - &self, - command_buffer: &Self::CommandBuffer, - target: &Self::Texture, - clear: bool, - ) -> Self::RenderEncoder; - /// `renderCommandEncoderWithDescriptor:` of one color attachment and a depth attachment, - /// both cleared, the color stored and the depth not. - fn depth_render_encoder( - &self, - command_buffer: &Self::CommandBuffer, - target: &Self::Texture, - depth: &Self::Texture, - ) -> Self::RenderEncoder; - /// A `MTLRenderPassDescriptor` of one color attachment, cleared and stored, made once for - /// many encoders ([`Gpu::pass_encoder`]). - fn pass(&self, target: &Self::Texture) -> Self::Pass; - /// `renderCommandEncoderWithDescriptor:` of `pass`. - fn pass_encoder( - &self, - command_buffer: &Self::CommandBuffer, - pass: &Self::Pass, - ) -> Self::RenderEncoder; - fn set_render_pipeline(&self, encoder: &mut Self::RenderEncoder, state: &Self::RenderPipeline); - fn set_depth_stencil(&self, encoder: &mut Self::RenderEncoder, state: &Self::DepthStencil); - /// `setCullMode:` of `Back`, or of `None`. - fn set_cull_back(&self, encoder: &mut Self::RenderEncoder, back: bool); - /// `setFrontFacingWinding:` of `CounterClockwise`. - fn set_counter_clockwise(&self, encoder: &mut Self::RenderEncoder); - /// `setVertexBytes:length:atIndex:`. - fn set_vertex_bytes(&self, encoder: &mut Self::RenderEncoder, bytes: &[u8], index: usize); - fn set_vertex_buffer( - &self, - encoder: &mut Self::RenderEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ); - /// `setVertexBufferOffset:atIndex:`. - fn set_vertex_buffer_offset( - &self, - encoder: &mut Self::RenderEncoder, - offset: usize, - index: usize, - ); - /// `setVertexBuffers:offsets:withRange:` of `buffers` from index `first`. - fn set_vertex_buffers( - &self, - encoder: &mut Self::RenderEncoder, - buffers: &[&Self::Buffer], - offsets: &[usize], - first: usize, - ); - fn set_fragment_buffer( - &self, - encoder: &mut Self::RenderEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ); - fn set_fragment_texture( - &self, - encoder: &mut Self::RenderEncoder, - texture: &Self::Texture, - index: usize, - ); - fn set_fragment_sampler( - &self, - encoder: &mut Self::RenderEncoder, - sampler: &Self::Sampler, - index: usize, - ); - /// `drawPrimitives:vertexStart:vertexCount:` of a triangle strip. - fn draw_strip(&self, encoder: &mut Self::RenderEncoder, vertices: usize); - /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:` of triangles - /// and 16-bit indices from the buffer's start. - fn draw_indexed(&self, encoder: &mut Self::RenderEncoder, count: usize, indices: &Self::Buffer); - /// `drawPrimitives:vertexStart:vertexCount:` of triangles. - fn draw_triangles(&self, encoder: &mut Self::RenderEncoder, start: usize, count: usize); - /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:` of triangles - /// and 16-bit indices from `offset`. - fn draw_indexed_at( - &self, - encoder: &mut Self::RenderEncoder, - count: usize, - indices: &Self::Buffer, - offset: usize, - ); - /// `drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:` of a triangle - /// strip and 16-bit indices from `offset`. - fn draw_indexed_strip_at( - &self, - encoder: &mut Self::RenderEncoder, - count: usize, - indices: &Self::Buffer, - offset: usize, - ); - /// `drawPrimitives:indirectBuffer:indirectBufferOffset:` of triangles. - fn draw_triangles_indirect( - &self, - encoder: &mut Self::RenderEncoder, - arguments: &Self::Buffer, - offset: usize, - ); - /// `drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer: - /// indirectBufferOffset:` of triangles and 16-bit indices from the buffer's start. - fn draw_indexed_indirect( - &self, - encoder: &mut Self::RenderEncoder, - indices: &Self::Buffer, - arguments: &Self::Buffer, - offset: usize, - ); - /// `setProvokingVertexMode:` (Apple's SPI). - fn set_provoking_vertex_mode(&self, encoder: &mut Self::RenderEncoder, mode: u64); - /// `useResource:usage:stages:` of `buffer`, read by the vertex stage. - fn use_in_vertex(&self, encoder: &mut Self::RenderEncoder, buffer: &Self::Buffer); - /// `executeCommandsInBuffer:withRange:` of draws `0..count`. - fn execute_draws( - &self, - encoder: &mut Self::RenderEncoder, - commands: &Self::IndirectCommands, - count: usize, - ); - fn end_render(&self, encoder: Self::RenderEncoder); - - /// `computeCommandEncoder`. - fn compute_encoder(&self, command_buffer: &Self::CommandBuffer) -> Self::ComputeEncoder; - /// `computeCommandEncoderWithDispatchType:` of `MTLDispatchTypeConcurrent`. - fn concurrent_compute_encoder( - &self, - command_buffer: &Self::CommandBuffer, - ) -> Self::ComputeEncoder; - fn set_compute_pipeline( - &self, - encoder: &mut Self::ComputeEncoder, - state: &Self::ComputePipeline, - ); - fn set_buffer( - &self, - encoder: &mut Self::ComputeEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ); - fn set_texture( - &self, - encoder: &mut Self::ComputeEncoder, - texture: &Self::Texture, - index: usize, - ); - /// `dispatchThreadgroups:threadsPerThreadgroup:` of a 1D grid. - fn dispatch(&self, encoder: &mut Self::ComputeEncoder, groups: usize, threads: usize); - /// `useResource:usage:` of `commands`, `MTLResourceUsageWrite`: the encoder's kernels write - /// them. - fn use_commands(&self, encoder: &mut Self::ComputeEncoder, commands: &Self::IndirectCommands); - /// `useResources:count:usage:` of `buffers`, `MTLResourceUsageRead`. - fn use_buffers_read(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]); - /// `useResources:count:usage:stages:` of `buffers`, `MTLResourceUsageRead`, in the vertex and - /// fragment stages. - fn use_buffers_drawn(&self, encoder: &mut Self::RenderEncoder, buffers: &[&Self::Buffer]); - /// `useResource:usage:` of `buffer`, read and write: the executed commands bind it. - fn use_buffer(&self, encoder: &mut Self::ComputeEncoder, buffer: &Self::Buffer); - /// `useHeap:` of `heap`, whose textures the encoder's kernels read. - fn use_heap(&self, encoder: &mut Self::ComputeEncoder, heap: &Self::Heap); - /// `updateFence:` of a compute encoder. - fn update_fence(&self, encoder: &mut Self::ComputeEncoder, fence: &Self::Fence); - /// `waitForFence:` of a compute encoder. - fn wait_for_fence(&self, encoder: &mut Self::ComputeEncoder, fence: &Self::Fence); - /// `useResources:count:usage:` of `buffers`, `MTLResourceUsageRead`. - fn use_buffers(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]); - /// `useResources:count:usage:` of `textures`, `MTLResourceUsageRead`. - fn use_textures(&self, encoder: &mut Self::ComputeEncoder, textures: &[&Self::Texture]); - /// `executeCommandsInBuffer:withRange:` of commands `0..count`. - fn execute_commands( - &self, - encoder: &mut Self::ComputeEncoder, - commands: &Self::IndirectCommands, - count: usize, - ); - fn end_compute(&self, encoder: Self::ComputeEncoder); - - /// A blit encoder of one `resetCommandsInBuffer:withRange:` of commands `0..count`. - fn reset_commands( - &self, - command_buffer: &Self::CommandBuffer, - commands: &Self::IndirectCommands, - count: usize, - ); - /// `blitCommandEncoder`. - fn blit_encoder(&self, command_buffer: &Self::CommandBuffer) -> Self::BlitEncoder; - /// `copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:`. - fn copy_buffer( - &self, - encoder: &mut Self::BlitEncoder, - from: (&Self::Buffer, usize), - to: (&Self::Buffer, usize), - size: usize, - ); - /// `fillBuffer:range:value:` of `length` bytes from `offset` inside `encoder`. - fn fill_buffer_in( - &self, - encoder: &mut Self::BlitEncoder, - buffer: &Self::Buffer, - offset: usize, - length: usize, - ); - /// `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture: - /// destinationSlice:destinationLevel:destinationOrigin:` of a `size` region from the start of - /// `source`, its rows `bytes_per_row` apart, inside `encoder`. - fn copy_to_texture( - &self, - encoder: &mut Self::BlitEncoder, - source: &Self::Buffer, - texture: &Self::Texture, - size: (usize, usize), - bytes_per_row: usize, - ); - fn end_blit(&self, encoder: Self::BlitEncoder); - /// A blit encoder of one `fillBuffer:range:value:` over the buffer's first `length` bytes. - fn fill(&self, command_buffer: &Self::CommandBuffer, buffer: &Self::Buffer, length: usize); - /// A blit encoder of `copyFromBuffer:...toTexture:...` into each of `textures`, a - /// `width` x `height` region from the start of `source`, its rows `bytes_per_row` apart, as a - /// compositor uploads its windows' contents. - fn upload( - &self, - command_buffer: &Self::CommandBuffer, - source: &Self::Buffer, - textures: &[&Self::Texture], - size: (usize, usize), - bytes_per_row: usize, - ); - - fn commit(&self, command_buffer: &Self::CommandBuffer); - /// `waitUntilCompleted`, then a check that it completed without error. - fn wait(&self, command_buffer: &Self::CommandBuffer); - /// `waitUntilCompleted` alone, no status read after it. - fn wait_only(&self, command_buffer: &Self::CommandBuffer); - /// `status`, as `MTLCommandBufferStatus` numbers it: 0 not enqueued, 1 enqueued, 2 committed, - /// 3 scheduled, 4 completed, 5 in error. - fn status(&self, command_buffer: &Self::CommandBuffer) -> u64; - /// `newFence`. - fn fence(&self) -> Self::Fence; - /// `addCompletedHandler:`. - fn on_completed(&self, command_buffer: &Self::CommandBuffer, handler: Box); - /// `newSharedEvent`. - fn shared_event(&self) -> Self::SharedEvent; - /// `signaledValue`. - fn event_value(&self, event: &Self::SharedEvent) -> u64; - /// `setSignaledValue:`. - fn set_event_value(&self, event: &Self::SharedEvent, value: u64); - /// `addScheduledHandler:` of a handler that sets `event`'s value to `value`: how a program - /// without `encodeSignalEventScheduled:value:` signals as the command buffer is scheduled. - fn set_when_scheduled( - &self, - command_buffer: &Self::CommandBuffer, - event: &Self::SharedEvent, - value: u64, - ); - /// `encodeSignalEventScheduled:value:` (Apple's private call; the runtime's - /// `encode_signal_event_scheduled`). - fn signal_when_scheduled( - &self, - command_buffer: &Self::CommandBuffer, - event: &Self::SharedEvent, - value: u64, - ); - /// `[[MTLSharedEventListener alloc] init]`. - fn listener(&self) -> Self::Listener; - /// `notifyListener:atValue:block:` of `event`, calling `block` on the listener's thread. - fn notify( - &self, - event: &Self::SharedEvent, - listener: &Self::Listener, - value: u64, - block: Box, - ); - /// A submission check that answers none (the runtime's `set_submission_check`, which Metal - /// has not): whether the side has it. - fn check_submissions(&self, _command_buffer: &Self::CommandBuffer) -> bool { - false - } - /// `GPUEndTime - GPUStartTime`, in seconds, where the side measures it on the GPU. - fn gpu_seconds(&self, command_buffer: &Self::CommandBuffer) -> Option; - /// `kernelStartTime`, `kernelEndTime`, `GPUStartTime` and `GPUEndTime`, in seconds of the - /// host clock [`crate::host_seconds`] reads. - fn times(&self, command_buffer: &Self::CommandBuffer) -> [f64; 4]; - - /// Run `f` inside an autorelease pool (native), as a Metal program's frame runs. - fn pool(&self, f: impl FnOnce() -> R) -> R; - - /// Time the driver's own calls under the side's, `windows` windows each, over `pages` of - /// host memory: the runtime's side alone (`vkfloor.rs`), which measures them on the Vulkan - /// device it holds. Metal has no such call, so the native side measures nothing. - /// - /// # Safety - /// - /// `pages` is read-write host memory of this process, at least eight megabytes, that - /// outlives the call. - unsafe fn driver_floor(&self, _windows: usize, _pages: *mut u8) {} - - /// The side's own counts of the work its calls made, by name, as they stand: every scalar - /// count of the runtime's `WorkCounts`, which the compositing and burst workloads report a - /// few of and the per-call table reports every one a call moved; none natively. - fn work_counts(&self) -> Vec<(&'static str, f64)> { - Vec::new() - } -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/host_ab.metal b/crates/metal2vulkan-runtime/examples/host_ab/host_ab.metal deleted file mode 100644 index cf16afdcd..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/host_ab.metal +++ /dev/null @@ -1,489 +0,0 @@ -// The host A/B benchmark's shaders (examples/host_ab): one source, compiled once into a metallib -// that both sides load, natively and through the runtime's translation. -// -// xcrun -sdk macosx metal -DNONCE= -o host_ab.metallib host_ab.metal -// -// NONCE (below 2^24, so each value is its own float) only changes a constant in each function, -// so each value gives functions of the same shape whose bytes differ: a cold pipeline creation -// finds them in no cache, Metal's or the runtime's. - -#include -using namespace metal; - -#ifndef NONCE -#define NONCE 0 -#endif - -struct QuadOut { - float4 position [[position]]; - float2 uv; -}; - -// A rectangle (x0, y0, x1, y1 in normalized device coordinates) as a strip of four vertices. -vertex QuadOut quad_vertex(uint vid [[vertex_id]], constant float4 &rect [[buffer(0)]]) { - float2 corner = float2(float(vid & 1u), float(vid >> 1)); - QuadOut out; - out.position = float4(mix(rect.xy, rect.zw, corner), float(NONCE) * 1.0e-12, 1.0); - out.uv = float2(corner.x, 1.0 - corner.y); - return out; -} - -// An OpenGL guest's flat-shaded triangles (the provoking workload): each vertex at its position in -// buffer 0, with a colour of its own that the fragment reads flat, from the primitive's provoking -// vertex. -struct FlatOut { - float4 position [[position]]; - uint colour [[flat]]; -}; - -vertex FlatOut flat_vertex(uint vid [[vertex_id]], const device float4 *positions [[buffer(0)]]) { - FlatOut out; - out.position = positions[vid] + float4(0.0, 0.0, float(NONCE) * 1.0e-12, 0.0); - out.colour = vid * 2654435761u; - return out; -} - -fragment float4 flat_fragment(FlatOut in [[stage_in]]) { - return unpack_unorm4x8_to_float(in.colour) + float4(float(NONCE) * 1.0e-12); -} - -// The small draws' fragment: one sample. -fragment float4 textured_fragment(QuadOut in [[stage_in]], - texture2d tex [[texture(0)]], - sampler smp [[sampler(0)]]) { - return tex.sample(smp, in.uv) + float4(float(NONCE) * 1.0e-12); -} - -// The heavy work's parameters, read from a constant buffer. -struct HeavyParams { - float4 coeffs[64]; - uint iterations; - float scale; -}; - -// The heavy fragment: float ALU, half math, texture sampling and constant-buffer reads in a loop. -fragment half4 heavy_fragment(QuadOut in [[stage_in]], - constant HeavyParams &p [[buffer(0)]], - texture2d tex [[texture(0)]], - sampler smp [[sampler(0)]]) { - float2 uv = in.uv; - float acc = float(NONCE) * 1.0e-12; - half4 hacc = half4(0.0h); - for (uint i = 0; i < p.iterations; i++) { - float4 c = p.coeffs[i & 63u]; - acc = fma(acc, c.x, sin(uv.x * c.y + acc) * c.z); - half4 t = tex.sample(smp, uv + float2(c.w, acc) * 0.01); - hacc = fma(hacc, half4(half(c.x)), t * 0.5h); - uv = fract(uv * 1.37 + c.zw); - } - return hacc + half4(half(acc * p.scale)); -} - -// The heavy kernel: float ALU, half math, texture reads, constant-buffer reads and threadgroup -// memory with barriers, in a loop. Threadgroups of 256 threads. -kernel void heavy_kernel(device float4 *out [[buffer(0)]], - constant HeavyParams &p [[buffer(1)]], - texture2d tex [[texture(0)]], - uint tid [[thread_position_in_grid]], - uint lid [[thread_index_in_threadgroup]]) { - threadgroup float shared_f[256]; - threadgroup half shared_h[256]; - float acc = float(tid) * 1.0e-6 + float(NONCE) * 1.0e-12; - half hacc = 0.0h; - for (uint i = 0; i < p.iterations; i++) { - float4 c = p.coeffs[(i + lid) & 63u]; - acc = fma(acc, c.x, sin(acc * c.y) * c.z + c.w); - half4 t = tex.read(uint2((tid + i * 7u) & 255u, ((tid >> 8) + i) & 255u)); - hacc = fma(hacc, half(c.x), dot(t, half4(0.25h))); - shared_f[lid] = acc; - shared_h[lid] = hacc; - threadgroup_barrier(mem_flags::mem_threadgroup); - acc += shared_f[(lid + 1u) & 255u] * 0.5; - hacc += shared_h[(lid + 7u) & 255u] * 0.5h; - threadgroup_barrier(mem_flags::mem_threadgroup); - } - out[tid] = float4(acc * p.scale, float(hacc), 0.0, 1.0); -} - -// The feature kernels: each one Metal feature of the heavy kernel in the same loop, so their -// ratios say which feature its cost comes from. Each takes the heavy kernel's bindings -// (`out`, `p`, `tex`) and `src`, a device buffer as large as `out`. -kernel void k_fma(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - float a = float(tid) * 1.0e-6 + float(NONCE) * 1.0e-12; - float b = 1.0; - for (uint i = 0; i < p.iterations; i++) { - a = fma(a, 0.999, b); - b = fma(b, 1.0001, -a * 0.5); - } - out[tid] = float4(a, b, 0.0, 1.0); -} - -kernel void k_sin(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - float a = float(tid) * 1.0e-6 + float(NONCE) * 1.0e-12; - for (uint i = 0; i < p.iterations; i++) { - a = sin(a * 1.3 + 0.7); - } - out[tid] = float4(a, 0.0, 0.0, 1.0); -} - -kernel void k_half(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - half a = half(tid & 255u) * 0.01h + half(float(NONCE) * 1.0e-12); - half b = 0.5h; - for (uint i = 0; i < p.iterations; i++) { - a = fma(a, 0.999h, b); - b = b * 0.75h + a * 0.125h; - } - out[tid] = float4(float(a), float(b), 0.0, 1.0); -} - -kernel void k_constant(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - float4 acc = float4(float(NONCE) * 1.0e-12); - for (uint i = 0; i < p.iterations; i++) { - acc = fma(acc, float4(0.5), p.coeffs[(i + tid) & 63u]); - } - out[tid] = acc; -} - -kernel void k_device(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - device const float4 *src [[buffer(2)]], - uint tid [[thread_position_in_grid]]) { - float4 acc = float4(float(NONCE) * 1.0e-12); - for (uint i = 0; i < p.iterations; i++) { - acc = fma(acc, float4(0.5), src[(tid + i * 4099u) & 1048575u]); - } - out[tid] = acc; -} - -kernel void k_texture(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - texture2d tex [[texture(0)]], - uint tid [[thread_position_in_grid]]) { - half4 acc = half4(half(float(NONCE) * 1.0e-12)); - for (uint i = 0; i < p.iterations; i++) { - acc = fma(acc, half4(0.5h), tex.read(uint2((tid + i * 7u) & 255u, ((tid >> 8) + i) & 255u))); - } - out[tid] = float4(acc); -} - -kernel void k_texture_float(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - texture2d tex [[texture(0)]], - uint tid [[thread_position_in_grid]]) { - float4 acc = float4(float(NONCE) * 1.0e-12); - for (uint i = 0; i < p.iterations; i++) { - acc = fma(acc, float4(0.5), tex.read(uint2((tid + i * 7u) & 255u, ((tid >> 8) + i) & 255u))); - } - out[tid] = acc; -} - -kernel void k_threadgroup_float(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]], - uint lid [[thread_index_in_threadgroup]]) { - threadgroup float shared_f[256]; - float acc = float(tid) * 1.0e-6 + float(NONCE) * 1.0e-12; - for (uint i = 0; i < p.iterations; i++) { - shared_f[lid] = acc; - threadgroup_barrier(mem_flags::mem_threadgroup); - acc = fma(shared_f[(lid + 1u) & 255u], 0.5, acc); - threadgroup_barrier(mem_flags::mem_threadgroup); - } - out[tid] = float4(acc, 0.0, 0.0, 1.0); -} - -kernel void k_threadgroup_half(device float4 *out [[buffer(0)]], constant HeavyParams &p [[buffer(1)]], - uint tid [[thread_position_in_grid]], - uint lid [[thread_index_in_threadgroup]]) { - threadgroup half shared_h[256]; - half acc = half(tid & 255u) * 0.01h + half(float(NONCE) * 1.0e-12); - for (uint i = 0; i < p.iterations; i++) { - shared_h[lid] = acc; - threadgroup_barrier(mem_flags::mem_threadgroup); - acc = fma(shared_h[(lid + 7u) & 255u], 0.5h, acc); - threadgroup_barrier(mem_flags::mem_threadgroup); - } - out[tid] = float4(float(acc), 0.0, 0.0, 1.0); -} - -// The small dispatches' kernels: two, so a dispatch can change the pipeline state. -kernel void tiny_kernel(device uint *out [[buffer(0)]], - constant uint &value [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = value + tid + uint(NONCE); -} - -kernel void tiny_kernel_b(device uint *out [[buffer(0)]], - constant uint &value [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = value * 3u + tid + uint(NONCE); -} - -// The handle dispatches' kernel: it reads its texture through a handle in an argument buffer, so -// each of its dispatches binds the device's texture table (`dispatch_handles`). -struct TinyHandles { - texture2d texture; -}; - -kernel void tiny_handle_kernel(device uint *out [[buffer(0)]], - constant TinyHandles &handles [[buffer(1)]], - uint tid [[thread_position_in_grid]]) { - out[tid] = uint(handles.texture.read(uint2(0, 0)).x * 255.0) + tid + uint(NONCE); -} - -// The many-draws workload's functions: a small rectangle per draw, of its own uniforms, and four -// fragment functions over two textures and one sampler. -struct DrawUniforms { - float4 rect; // x, y, width, height in NDC - float4 color; - float4 misc; // x: depth, y: phase -}; - -struct DrawOut { - float4 position [[position]]; - float2 uv; - float4 color; -}; - -vertex DrawOut draws_vertex(uint vid [[vertex_id]], - const device float2 *quad [[buffer(0)]], - constant DrawUniforms &u [[buffer(1)]], - constant float4 &jitter [[buffer(2)]]) { - float2 p = quad[vid]; - DrawOut out; - out.position = float4(u.rect.xy + p * u.rect.zw + jitter.xy, u.misc.x, 1.0); - out.uv = p; - out.color = u.color + float4(float(NONCE) * 1.0e-12); - return out; -} - -fragment float4 draws_fragment0(DrawOut in [[stage_in]], - texture2d t0 [[texture(0)]], - texture2d t1 [[texture(1)]], - sampler s [[sampler(0)]], - constant DrawUniforms &u [[buffer(0)]]) { - return t0.sample(s, in.uv) * in.color; -} - -fragment float4 draws_fragment1(DrawOut in [[stage_in]], - texture2d t0 [[texture(0)]], - texture2d t1 [[texture(1)]], - sampler s [[sampler(0)]], - constant DrawUniforms &u [[buffer(0)]]) { - return mix(t0.sample(s, in.uv), t1.sample(s, in.uv * 2.0), 0.5) * in.color; -} - -fragment float4 draws_fragment2(DrawOut in [[stage_in]], - texture2d t0 [[texture(0)]], - texture2d t1 [[texture(1)]], - sampler s [[sampler(0)]], - constant DrawUniforms &u [[buffer(0)]]) { - float r = length(in.uv - 0.5); - return float4(in.color.rgb * (1.0 - r), 0.8) * t1.sample(s, in.uv); -} - -fragment float4 draws_fragment3(DrawOut in [[stage_in]], - texture2d t0 [[texture(0)]], - texture2d t1 [[texture(1)]], - sampler s [[sampler(0)]], - constant DrawUniforms &u [[buffer(0)]]) { - return float4(in.uv, fract(u.misc.y), 1.0) * t0.sample(s, in.uv.yx); -} - -// The icb workload's functions (workloads::icb): a kernel that encodes one compute command a -// thread into an indirect command buffer, and the four states the commands run, each on its own -// 64-word window of `data`. Command `tid` runs state `tid % states` over one threadgroup of 64 -// threads, with no barrier, as a culling kernel encodes the work it keeps. The states add by -// relaxed atomics: a kernel that reads and then writes a word by its grid position alone leaves -// the order of a simdgroup's accesses to Apple's lockstep, which the runtime makes explicit with a -// barrier that observes the threadgroup partition, so its commands could not run on the GPU -// alone. -struct IcbEncoder { - command_buffer commands; - compute_pipeline_state step0; - compute_pipeline_state step1; - compute_pipeline_state step2; - compute_pipeline_state step3; -}; - -kernel void icb_encode(device const IcbEncoder &encoder [[buffer(0)]], - device uint *data [[buffer(1)]], - constant uint &states [[buffer(2)]], - uint tid [[thread_position_in_grid]]) { - compute_command command(encoder.commands, tid); - switch (tid % states) { - case 0: command.set_compute_pipeline_state(encoder.step0); break; - case 1: command.set_compute_pipeline_state(encoder.step1); break; - case 2: command.set_compute_pipeline_state(encoder.step2); break; - default: command.set_compute_pipeline_state(encoder.step3); break; - } - command.set_kernel_buffer(data + tid * 64, 0); - command.concurrent_dispatch_threadgroups(uint3(1, 1, 1), uint3(64, 1, 1)); -} - -kernel void icb_step0(device atomic_uint *data [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - atomic_fetch_add_explicit(&data[tid], 1u + uint(NONCE), memory_order_relaxed); -} - -kernel void icb_step1(device atomic_uint *data [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - atomic_fetch_add_explicit(&data[tid], 2u + uint(NONCE), memory_order_relaxed); -} - -kernel void icb_step2(device atomic_uint *data [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - atomic_fetch_add_explicit(&data[tid], 3u + uint(NONCE), memory_order_relaxed); -} - -kernel void icb_step3(device atomic_uint *data [[buffer(0)]], - uint tid [[thread_position_in_grid]]) { - atomic_fetch_add_explicit(&data[tid], 4u + uint(NONCE), memory_order_relaxed); -} - -// The icb_draws workload's frame state and objects, as Apple's "Encoding Indirect Command Buffers -// on the GPU" lays them out: a translation and scale shared by every object, and each object's -// position, bounding radius and mesh vertex count. -struct IcbDrawFrame { - float2 translation; - float2 scale; -}; - -struct IcbDrawObject { - float2 position; - float radius; - uint vertices; -}; - -// The argument buffer that holds the indirect command buffer. -struct IcbDrawContainer { - command_buffer commands; -}; - -// Culls `object` against the view and, where it is visible, encodes its command: the frame state, -// the objects and the mesh as vertex buffers, and a draw of `type` of its mesh's vertices whose -// base instance is the object's index. An object out of view keeps the command the frame's reset -// left: nothing. -static void icb_draw_encode_object(uint object, constant IcbDrawFrame *frame, - device const IcbDrawObject *objects, device const float2 *mesh, - device const IcbDrawContainer *container, primitive_type type) { - float2 center = frame->scale * (frame->translation + objects[object].position); - float2 radius = frame->scale * objects[object].radius; - bool visible = all(center + radius >= float2(-1.0)) && all(center - radius <= float2(1.0)); - render_command command(container->commands, object); - if (visible) { - command.set_vertex_buffer(frame, 0); - command.set_vertex_buffer(objects, 1); - command.set_vertex_buffer(mesh, 2); - command.draw_primitives(type, 0, objects[object].vertices, 1, object); - } -} - -// Each thread encodes one object's command, a draw of triangles. -kernel void icb_draw_encode(uint object [[thread_position_in_grid]], - constant IcbDrawFrame *frame [[buffer(0)]], - device const IcbDrawObject *objects [[buffer(1)]], - device const float2 *mesh [[buffer(2)]], - device const IcbDrawContainer *container [[buffer(3)]]) { - icb_draw_encode_object(object, frame, objects, mesh, container, primitive_type::triangle); -} - -// icb_draw_encode, the draws' primitive type read from `type` (the CPU writes triangles), so the -// kernel's code does not tell which type its draws are of. -kernel void icb_draw_encode_any_type(uint object [[thread_position_in_grid]], - constant IcbDrawFrame *frame [[buffer(0)]], - device const IcbDrawObject *objects [[buffer(1)]], - device const float2 *mesh [[buffer(2)]], - device const IcbDrawContainer *container [[buffer(3)]], - constant uint &type [[buffer(4)]]) { - icb_draw_encode_object(object, frame, objects, mesh, container, primitive_type(type)); -} - -// An object's mesh vertex, moved to the object (its instance is the object's index). -vertex QuadOut icb_draw_vertex(uint vid [[vertex_id]], uint object [[instance_id]], - constant IcbDrawFrame *frame [[buffer(0)]], - device const IcbDrawObject *objects [[buffer(1)]], - device const float2 *mesh [[buffer(2)]]) { - QuadOut out; - float2 at = frame->scale * (frame->translation + objects[object].position + mesh[vid]); - out.position = float4(at, float(NONCE) * 1.0e-12, 1.0); - out.uv = mesh[vid] * 0.5 + 0.5; - return out; -} - -// The object's color from its mesh coordinates. -fragment float4 icb_draw_fragment(QuadOut in [[stage_in]]) { - return float4(in.uv, float(NONCE) * 1.0e-12, 1.0); -} - -// The layers workload's (m2vbench's composite mode): a layer's rectangle in pixels (x, y, w, h) -// and the viewport's size, its opacity and its corner radius. -struct LayerUniforms { - float4 rect; - float4 v; -}; - -struct LayerOut { - float4 position [[position]]; - float2 uv; - float4 shape; -}; - -// A layer's rectangle as a strip of four vertices. -vertex LayerOut layer_vertex(uint vid [[vertex_id]], constant LayerUniforms &u [[buffer(0)]]) { - float2 p = float2(float(vid & 1u), float(vid >> 1)); - float2 ndc = (u.rect.xy + p * u.rect.zw) / u.v.xy * 2.0 - 1.0; - LayerOut out; - out.position = float4(ndc.x, -ndc.y, float(NONCE) * 1.0e-12, 1.0); - out.uv = p; - out.shape = float4(u.rect.zw, u.v.z, u.v.w); - return out; -} - -static float rounded_rect(float2 uv, float2 size, float r) { - float2 q = abs(uv - 0.5) * size - (size * 0.5 - r); - return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; -} - -// A layer's texels inside its rounded corners, premultiplied by its opacity. -fragment float4 layer_fragment(LayerOut in [[stage_in]], - texture2d t [[texture(0)]], - sampler s [[sampler(0)]]) { - float a = saturate(0.5 - rounded_rect(in.uv, in.shape.xy, in.shape.w)); - return t.sample(s, in.uv) * (a * in.shape.z) + float4(float(NONCE) * 1.0e-12); -} - -// A soft shadow under a layer grown by 32 pixels on each side. -fragment float4 shadow_fragment(LayerOut in [[stage_in]]) { - float d = rounded_rect(in.uv, in.shape.xy, in.shape.w + 32.0) + 32.0; - float a = 1.0 - smoothstep(-24.0, 24.0, d); - return float4(0.0, 0.0, 0.0, 0.35 * a * in.shape.z + float(NONCE) * 1.0e-12); -} - -// The calls workload's functions (workloads::calls), shaped as a guest's draws: positions from -// vertex buffer 0 by vertex, a colour from buffer 1 at an offset that moves; a fragment that -// samples texture 0 with sampler 0, or one that returns fragment buffer 0's first float4. -struct CallsOut { - float4 position [[position]]; - float4 color; -}; - -vertex CallsOut calls_vertex(uint vid [[vertex_id]], - const device float4 *positions [[buffer(0)]], - const device float4 *colours [[buffer(1)]]) { - CallsOut out; - out.position = positions[vid] + float4(0.0, 0.0, float(NONCE) * 1.0e-12, 0.0); - out.color = colours[0]; - return out; -} - -fragment float4 calls_texture_fragment(CallsOut in [[stage_in]], - texture2d t [[texture(0)]], - sampler s [[sampler(0)]]) { - return t.sample(s, in.position.xy / 512.0) * in.color; -} - -fragment float4 calls_buffer_fragment(CallsOut in [[stage_in]], - const device float4 *c [[buffer(0)]]) { - return c[0] * in.color; -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/main.rs b/crates/metal2vulkan-runtime/examples/host_ab/main.rs deleted file mode 100644 index 3e0e2913f..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/main.rs +++ /dev/null @@ -1,916 +0,0 @@ -//! The host A/B benchmark: the same Metal workloads run two ways on one machine, natively on -//! Metal (macOS only, through objc2-metal) and through this runtime on the Vulkan device its -//! loader finds (on a Mac, MoltenVK), from one metallib that `xcrun metal` compiles from -//! `host_ab.metal`. The runtime takes it through `new_library_with_data`, so its functions run as -//! the translator's SPIR-V. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example host_ab -- [options] -//! ``` -//! -//! Without `--side`, each round runs one process per side, native first, then prints a table of -//! each metric: the median of the rounds' medians per side, the ratio runtime / native, and the -//! spread of the rounds. `--side native|runtime` runs one side in this process and prints its -//! result lines (for a profiler). -//! -//! Workloads (`--only a,b,...`; all by default): -//! -//! - `encode`: CPU cost of encoding. A render pass of `--draws` small textured draws into a -//! 512x512 `BGRA8Unorm` target, `static` (nothing set between draws), `offset` (each draw the -//! vertex buffer's offset alone, `setVertexBufferOffset:atIndex:`), `bind` (each draw another -//! vertex buffer and offset, and another fragment texture), `pipeline` (as `bind`, and the -//! pipeline state switched between two), `passes` (as `pipeline`, in render passes of three -//! draws, as a window server draws) and `compositor` (as `bind`, in render passes of 300 draws, -//! each run of 10 draws by the next of three pipeline states, as a window server's frame -//! draws) and `host` (each draw the vertex buffer bound at the next 256 bytes of no-copy -//! buffers of 64 KiB over host pages, as a guest's `setVertexBytes:` reaches its upload -//! chunks), and a compute encoder of as many single-threadgroup -//! dispatches, `static`, `offsets` (both buffers' offsets each dispatch) and `churn` (the -//! pipeline state and both buffers' offsets each dispatch). Per draw and dispatch: the encoding thread's wall time from the command buffer's -//! creation through `endEncoding`, and the whole process's CPU time until the wait returned. -//! Then `dispatch_resident_*`: as many dispatches of the tiny kernel after one -//! `useResources:count:usage:` of 0, 1, 256 or 4096 buffers, or of one buffer 4096 times -//! (`same_4096`); per variant the `useResources` call and the `endEncoding` call, and per -//! dispatch the encoding thread's wall time between them and the process's CPU time; -//! `dispatch_resident_moving_0`, `_16`, `_256` and `_4096`: as many after none, 16, 256 or 4096 -//! buffers made resident, the output buffer's offset moved before each dispatch; -//! `dispatch_resident_textures_256` and `_4096`: as many after 256 or 4096 textures made -//! resident; `dispatch_handles`: as many of a kernel reading a -//! resident texture through a handle in an argument buffer. -//! - `fixed`: a command buffer's creation, an encoder of one command each (render, compute, -//! blit), and the commit call of a command buffer of 30 such encoders. -//! - `calls`: the frames of a guest as reims-vgpu's `frame_cost` measures them, call by call: one -//! command buffer of long encoders (`wide`: a render pass of 512 draws, two compute encoders of -//! 64 dispatches, a blit encoder of 32 copies) and 64 command buffers of short ones (`many`: -//! 16 draws, one dispatch each, one copy), each with a completed handler and committed, then -//! each handler awaited and the command buffer waited for. Each draw sets two vertex buffers, -//! the second's offset moving, then a fragment texture and sampler or a fragment buffer at a -//! moving offset, by the pipeline state, which changes every eighth draw; the second compute -//! encoder makes 16 buffers resident first. Per step (`command_buffer`, `render_encoder`, -//! `set_state`, ..., `draw`, `end_render`, ..., `handler_commit`): the mean a call of each of -//! `--timed` frames, in ns, after 5 frames not timed; `*_frame_calls`, the frame's timed calls -//! summed; and `*_allocs`, the heap allocations a call of the step made on the encoding thread -//! over one more frame (`allocs`); `*_frame_wall`, the frame from its first call until its last -//! wait returned. `--variants wide` or `many` runs one shape alone. Only where named, -//! `resident_0`, `_1`, `_256` and `_4096`: a render encoder's 512 draws, nothing changed between -//! them, after one `useResources:count:usage:stages:` of 0, 1, 256 or 4096 buffers; the call, -//! each draw after it, and the command buffer to its wait's return. -//! - `latency`: commit to `waitUntilCompleted`'s return, and commit to the completed handler, of -//! a command buffer that is empty, one blit fill, one dispatch, or one draw; one in flight. -//! - `gpu`: a full-screen heavy fragment (`heavy_fragment`, 2048x2048 `RGBA16Float`) and a heavy -//! kernel (`heavy_kernel`, 4096 threadgroups of 256), one command buffer in flight: commit to -//! the wait's return, and native's `GPUEndTime - GPUStartTime`. `--heavy-iterations` sets -//! the fragment's loop, and 16 times it the kernel's. Then each feature kernel (`k_*`, one -//! feature of the heavy kernel each: fma, sin, half, constant buffer, device buffer, texture -//! read as `half` and as `float`, threadgroup float, threadgroup half) on the kernel's grid -//! and loop. With both sides, each round also compares every kernel's output buffer after its -//! last run between the sides, and the last table counts the 32-bit words that differ. -//! - `signals`: a command buffer of one tiny fill with a completed handler, committed alone and -//! waited for, as the consumer's isolated execution is: `plain`; `scheduled_handler`, with a -//! scheduled handler that sets a shared event's value (how a program without -//! `encodeSignalEventScheduled:value:` signals as it is scheduled); `scheduled_signal`, with that -//! private call (the runtime's `encode_signal_event_scheduled`); and the runtime's alone, -//! `checked`, with a submission check that answers none (`set_submission_check`). Per command -//! buffer: commit to the completed handler, commit to the wait's return, the process's CPU time, -//! and on the runtime's side its work counts (`rt_*`: handler-thread and scheduler wakes, and -//! the command buffers scheduled where their last batch was submitted, the scheduler's passes). -//! Then bursts of 64 such command buffers committed back to back, `plain` and `checked`, to -//! the last one's completion, per command buffer. Then a shared event listener made and dropped -//! unused, one made, and its first notification, asked for a value already reached, from the -//! ask to the block's start. -//! - `latency_split` (with `latency`): the same command buffers' host-clock timeline, commit to -//! `kernelStartTime` to `kernelEndTime` to `GPUStartTime` to `GPUEndTime` to the wait's return. -//! The runtime's GPU times on MoltenVK are the host's (its docs): its GPU start is its kernel -//! end and its GPU end the moment it saw the command buffer complete. -//! - `pipeline`: the library, then each of four states' creation and first use, then each made -//! again in the process. Each round runs it in two processes per side over a metallib of a -//! fresh `NONCE` (`host_ab.metal`): `cold_*` (no cache holds its functions) and `warm_*` (a -//! second process over the same runtime shader cache directory, after Metal's own caches took -//! the first). -//! - `frame`: a window server's frame of heap textures: eight `BGRA8Unorm` textures of 256x256 -//! (`allowGPUOptimizedContents` off) made at their offsets of a `Placement` heap of `Shared` -//! storage, each rendered by a pass of -//! three textured draws, then each sampled into the target by one draw of a last pass, the -//! command buffer committed and waited for, and the textures dropped. Per frame: the encoding -//! thread's wall time from the first texture's creation through the commit, the textures' -//! creation alone, their drop, and the process's CPU time until the drop returned. The -//! runtime's alone (`frame_no_copy_*`): the same over a heap of host pages -//! (`new_heap_with_bytes_no_copy`), as a guest's heap is. -//! - `many_draws`: a frame of `--many-draws` small draws, shaped as m2vbench's draws mode: one -//! render pass into a 1920x1080 `BGRA8Unorm` target with a cleared `Depth32Float` attachment, -//! each draw a textured rectangle of its own uniforms (a vertex and a fragment buffer at the -//! draw's offset of one of four buffers), two fragment textures of sixteen, 16 bytes of -//! `setVertexBytes`, alternately indexed and not; the pipeline state (four) every 8 draws, the -//! depth-stencil state (two) every 16, the fragment sampler (two) every 32 and the cull mode -//! every 64. Per frame: the encoding thread's wall time from the command buffer's creation -//! through `endEncoding`, the commit call's, from its return to the wait's, the whole frame's, -//! the process's CPU time, the encoding thread's CPU time through the commit's return, and -//! native's GPU time. Where the side makes a heap over host pages (the runtime's), the frames -//! again with the four uniform buffers no-copy buffers over host pages that such a heap lies -//! over too, as a guest's buffers lie in its memory beside its heaps (the `pages_` rows). -//! - `layers`: a frame shaped as m2vbench's composite mode (CoreAnimation-like layers): one render -//! pass into a 1920x1080 `BGRA8Unorm` target, a wallpaper, then 800 textured rounded-corner -//! layers back to front, each one draw of a strip whose uniforms are its `setVertexBytes` and -//! whose texture (of 48) is bound before it, with a soft shadow's draw under every eighth (its -//! own pipeline state, set before it and back after): 901 draws. Per frame as `many_draws`. -//! - `drag`: a frame shaped as the guest's window drag (a macOS guest's WindowServer, measured in -//! a VM's work counts): 40 command buffers, each committed, of which the first 31 hold a render -//! pass of three textured draws into one of eight 256x256 `BGRA8Unorm` window surfaces in a -//! `Placement` heap, and the first 22 a dispatch of the tiny kernel; the last waited for. Per -//! frame: the encoding thread's wall time through the last commit, the whole frame's, the -//! encoding thread's CPU time and the process's. The runtime's alone (`drag_no_copy_*`): the -//! same over a heap of host pages, as a guest's heap is, and (`drag_heap_surfaces_*`) again -//! with textures Metal may optimize, each pass's draws sampling three other surfaces, as a -//! compositor's do, the frame's first command buffer uploading a window's contents into every -//! other surface in one blit encoder first. Then (`drag_surfaces_*`) the surfaces as textures -//! over host pages, a no-copy buffer each, their rows padded, as a guest's window surfaces -//! are, composited and uploaded into alike. -//! - `memory`: `newBufferWithLength:` and `newBufferWithBytes:` of 4 KiB, 1 MiB and 64 MiB, -//! `newBufferWithBytesNoCopy:` of 1 MiB and 64 MiB, each released before the next is made; -//! `newBufferWithLength:` of 1 MiB and 64 MiB held (`held`: 48 and 6 of them, none made in -//! memory an earlier one used), and the first touch of all of each one's bytes: a CPU write -//! (`first_write_held`), or, of a second set, a blit fill from commit to the wait's return -//! (`first_fill_held`) and that fill again (`second_fill_held`); and a 1024x1024 `RGBA8Unorm` -//! `Shared` texture's `replaceRegion` and `getBytes`. -//! - `churn`: each frame makes eight 1280x800 `Private` render targets, clears and releases them, -//! the same size each frame (`same`) or one of 64 widths in turn (`varied`); and sixteen 64-KiB -//! buffers, filled and released (`buffers`) (`workloads::churn`). -//! - `compositing`: frames of the consumer's compositing shape, paced at 60 Hz: 20 command -//! buffers a frame, and 10 new textures made in a `Placement` heap of tracked `Shared` storage -//! (as the guest makes heap textures each frame): 10 command buffers each clear one new -//! texture, made just before it, and draw 2 quads into it, 8 each draw 8 blended quads into one -//! of two 1024x1024 layers from 4 new textures and the other layer (each depending on the -//! command buffers before it), one dispatches 15 small kernels and fills a buffer, and the last -//! draws both layers and 4 new textures onto a screen texture. Per frame: the wall time from the -//! first command buffer's creation to the last one's completion (its median, its 99th -//! percentile and the frames over 16.7 ms), the encoding thread's time to encode and commit, -//! the process's CPU time, and on the runtime's side its work counts per frame (`rt_*`: -//! `vkQueueSubmit` calls, the `VkSubmitInfo`s they held, each a Metal command buffer under -//! MoltenVK, and the rest). -//! - `burst`: a window server's frames paced at 60 Hz, each period of 3 s ending in a burst of -//! 1 s, shaped as a guest's bursts in a VM's work counts (`workloads::burst`). Calm, a frame -//! makes 15 `Private` render targets of the same sizes each frame and 10 heap textures, clears -//! and draws into each over 20 command buffers, draws the heap textures onto a screen texture, -//! and waits for its command buffers. In a burst it also makes 45 render targets of widths made -//! once, its heap textures take 128 sides in turn, it spreads the work over 60 command buffers, -//! and it leaves them in flight until the next frame starts. Calm and burst frames apart: the -//! interval from a frame's start to the next one's (its median, its 99th percentile, and those -//! over 16.7 and 25 ms), the encoding thread's time to encode and commit, the process's CPU -//! time, and on the runtime's side its work counts per frame (`rt_*`). -//! - `icb`: indirect command buffers a kernel writes. Per frame, a kernel encodes 16, 64, 256 or -//! 4096 compute commands into an indirect command buffer (one a thread: one of 1 to 21 live -//! states made with `supportIndirectCommandBuffers`, of which the commands name four at most, -//! its own 64-word window of a buffer, one threadgroup of 64 threads, no barrier), and a -//! second compute encoder, serial or concurrent, executes them -//! (`executeCommandsInBuffer:withRange:`), as a GPU culling pass hands its kept work on. Per -//! frame: the wall time from the command buffer's creation to the wait's return, the encoding -//! thread's through the commit, the process's CPU time, and on the runtime's side its queue -//! submissions, barriers, dispatches and indirect dispatches (`rt_*`). The first frame's output -//! is checked (`workloads::icb`). -//! - `icb_draws`: a frame of Apple's "Encoding Indirect Command Buffers on the GPU": a blit -//! resets an indirect command buffer of 65,536 draws whose commands inherit the pipeline state, -//! a kernel culls 65,536 objects on a grid a little wider than the view and encodes a command for -//! each visible one (three vertex buffers and a draw of its mesh's 18 vertices whose base -//! instance is its index), and a render pass into a 1920x1080 `BGRA8Unorm` target executes them -//! all. Per frame, as `many_draws`; `icb_draws_any_type_*`: the same, the kernel reading the -//! draws' primitive type (triangles) from a buffer, where the runtime cannot tell the type from -//! the kernel's code and so reads the records on the host. On the runtime's side, the commands -//! drawn on the GPU alone, the records read on the host, and the draws and pipeline barriers -//! recorded per frame (`rt_*`). -//! - `percall`: the device API's CPU cost per call, Metal against the runtime: one group a call, -//! each timed alone, warm, with no making inside a timed window, and attributed three ways (the -//! calling thread, our own other threads, and what the caller blocks for). It prints its own -//! table after the metric table (`percall.rs`). -//! - `icb_cpu`: the CPU's encoding of indirect commands, each call's time: of 4096 commands of a -//! buffer of dispatches and one of draws, each setter (pipeline state, buffer, dispatch or draw, -//! barrier) on every command in turn, then Apple's private getters of a buffer's address and of -//! the barrier (the runtime's read-back of them), each call taking its command first -//! (`workloads::icb_cpu`). -//! -//! - `provoking`: an OpenGL guest's flat-shaded draws, which Apple's GL draws at -//! `setProvokingVertexMode:` 1 (the last vertex): one render pass into a 512x512 `BGRA8Unorm` -//! target of `--draws` draws of two small triangles each, six vertices of their own, under a -//! pipeline whose fragment function reads a flat input; direct, indexed (16-bit, each draw its -//! own six indices of one buffer), indexed strips (each draw a strip of four of its six -//! vertices, its own four indices of another buffer), indirect and indexed indirect, each at -//! mode 0 and at mode 1. -//! Per draw: the encoding thread's wall time through `endEncoding`, the process's CPU time, and -//! the frame from the command buffer's creation to the wait's return; and the commit to the -//! wait's return. On the runtime's side, its draws through last-vertex pipelines, its listed -//! draws, dispatches and pipeline barriers per frame (`rt_*`). -//! - **threads**: the encode workload's `static` and `offset` draws on 1, 2, 4 and 8 threads at -//! once, each with its own command queue and target, through one shared pipeline state -//! (`shared`) and through one of each thread's own (`each`); each thread encodes `--timed / 4` -//! (at least 8) command buffers of `--draws` draws, one in flight before the next commits. Per -//! case, over 3 runs: the draws a second of all threads together (from their common start to -//! the last one's last commit), each thread's CPU time per draw, and the process's. -//! -//! Options: `--rounds N` (3), `--draws N` (2000), `--timed N` (30), `--latency N` (200), -//! `--heavy-iterations N` (64), `--heavy-runs N` (15), `--many-draws N` (6000), `--frames N` -//! (120, the compositing workload's timed frames), `--scratch DIR` (metallibs and the runtime's -//! shader caches; a directory under the OS's temporary directory by default, removed at the end), -//! `--metallib PATH` (skip the compile; not with `pipeline`), `--cache DIR` (the runtime's shader -//! cache, with `--side`), `--variants a,b,...` (the encode workload's variants alone: -//! `draw_static`, `draw_offset`, `draw_bind`, `draw_pipeline`, `draw_passes`, `draw_compositor`, -//! `draw_host`, -//! `dispatch_static`, `dispatch_offsets`, `dispatch_churn`, `dispatch_resident_0`, `_1`, `_256`, -//! `_4096`, `_same_4096`, `dispatch_resident_moving_0`, `_16`, `_256`, `_4096`, -//! `dispatch_resident_textures_256`, `_4096`, `dispatch_handles`; for a profile of one; and the -//! memory workload's parts alone: `create`, `no_copy`, `held_1m`, `held_64m`, `texture`), -//! `--announce-each a,b,...` (the runtime's device -//! announces these degradation kinds, by code with or without its `metal2vulkan-degrade-` prefix, -//! or `all` of them, at every occurrence, `DeviceOptions::announce_each`, as a consumer that hears -//! some kinds at each call opens it), `--sink-least verbose|info|warning|error` (the runtime's -//! sink hears no other message below it, `MessageSink::with_least_severity`; `verbose` by -//! default). -//! -//! On a Mac, the runtime's device opens the Vulkan loader (`/opt/homebrew/lib` among the places -//! it looks) and MoltenVK's `MVK_CONFIG_*` variables apply. Run timings on an otherwise idle GPU. - -mod allocs; -mod gpu; -#[cfg(target_os = "macos")] -mod native; -mod percall; -mod runtime; -mod vkfloor; -mod workloads; - -use gpu::Gpu; -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; -use workloads::Sizes; - -const WORKLOADS: [&str; 21] = [ - "encode", - "fixed", - "calls", - "latency", - "gpu", - "pipeline", - "memory", - "frame", - "many_draws", - "layers", - "churn", - "compositing", - "drag", - "burst", - "icb", - "icb_draws", - "signals", - "provoking", - "icb_cpu", - "percall", - "threads", -]; - -struct Options { - side: Option, - only: Vec, - rounds: usize, - sizes: Sizes, - scratch: Option, - metallib: Option, - cache: Option, - /// Where a side writes the gpu workload's kernel outputs (`--outputs`). - outputs: Option, - /// The encode and memory workloads' variants to run (`--variants`); all when empty. - variants: Vec, - /// The kinds the runtime's device announces at every occurrence (`--announce-each`). - announce_each: Vec, - /// The least severity of the messages the runtime's sink hears (`--sink-least`). - sink_least: metal2vulkan_runtime::MessageSeverity, - /// Arguments passed on to each child. - passed: Vec, -} - -fn options() -> Options { - let mut options = Options { - side: None, - only: WORKLOADS.iter().map(|w| w.to_string()).collect(), - rounds: 3, - sizes: Sizes { - draws: 2000, - timed: 30, - latency: 200, - heavy_iterations: 64, - heavy_runs: 15, - many_draws: 6000, - frames: 120, - }, - scratch: None, - metallib: None, - cache: None, - outputs: None, - variants: vec![], - announce_each: vec![], - sink_least: metal2vulkan_runtime::MessageSeverity::Verbose, - passed: vec![], - }; - let mut args = std::env::args().skip(1); - while let Some(flag) = args.next() { - let mut value = || { - args.next() - .unwrap_or_else(|| panic!("{flag} takes a value")) - }; - let mut number = |passed: &mut Vec| { - let v = value(); - passed.extend([flag.clone(), v.clone()]); - v.parse::() - .unwrap_or_else(|_| panic!("{flag}: a number")) - }; - match flag.as_str() { - "--side" => options.side = Some(value()), - "--only" => options.only = value().split(',').map(str::to_owned).collect(), - "--rounds" => options.rounds = value().parse().expect("--rounds: a number"), - "--draws" => options.sizes.draws = number(&mut options.passed), - "--timed" => options.sizes.timed = number(&mut options.passed), - "--latency" => options.sizes.latency = number(&mut options.passed), - "--heavy-iterations" => { - options.sizes.heavy_iterations = number(&mut options.passed) as u32 - } - "--heavy-runs" => options.sizes.heavy_runs = number(&mut options.passed), - "--many-draws" => options.sizes.many_draws = number(&mut options.passed), - "--frames" => options.sizes.frames = number(&mut options.passed), - "--scratch" => options.scratch = Some(PathBuf::from(value())), - "--metallib" => options.metallib = Some(PathBuf::from(value())), - "--cache" => options.cache = Some(PathBuf::from(value())), - "--outputs" => options.outputs = Some(PathBuf::from(value())), - "--variants" => { - let v = value(); - options.variants = v.split(',').map(str::to_owned).collect(); - options.passed.extend(["--variants".to_owned(), v]); - } - "--announce-each" => { - let v = value(); - options.announce_each = match v.as_str() { - "all" => metal2vulkan_runtime::Degradation::ALL.to_vec(), - _ => v.split(',').map(degradation).collect(), - }; - options.passed.extend(["--announce-each".to_owned(), v]); - } - "--sink-least" => { - let v = value(); - use metal2vulkan_runtime::MessageSeverity as S; - options.sink_least = match v.as_str() { - "verbose" => S::Verbose, - "info" => S::Info, - "warning" => S::Warning, - "error" => S::Error, - other => panic!("--sink-least: verbose, info, warning or error, not {other}"), - }; - options.passed.extend(["--sink-least".to_owned(), v]); - } - "--help" | "-h" => { - eprintln!("see the module docs of examples/host_ab/main.rs"); - std::process::exit(0); - } - other => panic!("unknown option {other}"), - } - } - for workload in &options.only { - assert!( - WORKLOADS.contains(&workload.as_str()), - "unknown workload {workload}" - ); - } - options -} - -/// The degradation kind of `code`, with or without its `metal2vulkan-degrade-` prefix. -fn degradation(code: &str) -> metal2vulkan_runtime::Degradation { - let prefixed = match code.starts_with("metal2vulkan-degrade-") { - true => code.to_owned(), - false => format!("metal2vulkan-degrade-{code}"), - }; - metal2vulkan_runtime::Degradation::from_code(&prefixed) - .unwrap_or_else(|| panic!("--announce-each: no degradation kind {code}")) -} - -fn main() { - let options = options(); - match options.side.as_deref() { - None => parent(&options), - Some(side) => child(side, &options), - } -} - -/// One side in this process: open its device, run the selected workloads, print result lines. -fn child(side: &str, options: &Options) { - let metallib = options.metallib.as_deref().expect("--metallib with --side"); - let t = Instant::now(); - match side { - #[cfg(target_os = "macos")] - "native" => { - let native = native::Native::open(); - run(&native, t.elapsed(), metallib, options); - } - "runtime" => { - let cache = options - .cache - .clone() - .unwrap_or_else(|| scratch_default().join("cache")); - let runtime = - runtime::Runtime::open(&cache, &options.announce_each, options.sink_least); - let opened = t.elapsed(); - runtime.settle_checks(); - run(&runtime, opened, metallib, options); - let c = runtime.device().work_counts(); - eprintln!( - "runtime work counts: queue_submissions {} command_buffers_submitted {} \ - pipeline_barriers {} draws {} dispatches {} variant_pipelines_made {} \ - device_memory_allocated {} host_pointer_imports_made {} \ - fresh_page_buffers_made {} fresh_page_bytes {} new_buffer_bytes_cleared {} \ - requirement_images_made {} arena_pools_made {} owned_descriptor_pools {} \ - draws_settled {} stage_tables_read {} graphics_pipelines_looked_up {} \ - draws_pushing_set_zero {} set_zero_writes_pushed {} set_zero_sets_reused {} \ - set_zero_sets_found {} draw_shapes_reused {} \ - completed_waits {} bare_starts {} submit_infos {} finales_folded {} \ - finales_apart {} pending_none {} pending_one {} pending_two_three {} \ - pending_four_more {}", - c.queue_submissions, - c.command_buffers_submitted, - c.commands_recorded.cmd_pipeline_barrier, - c.commands_recorded.cmd_draw, - c.commands_recorded.cmd_dispatch, - c.variant_pipelines_made, - c.device_memory_allocated, - c.host_pointer_imports_made, - c.fresh_page_buffers_made, - c.fresh_page_bytes, - c.new_buffer_bytes_cleared, - c.requirement_images_made, - c.arena_pools_made, - c.owned_descriptor_pools, - c.draws_settled, - c.stage_tables_read, - c.graphics_pipelines_looked_up, - c.draws_pushing_set_zero, - c.set_zero_writes_pushed, - c.set_zero_sets_reused, - c.set_zero_sets_found, - c.draw_shapes_reused, - c.completed_waits, - c.bare_starts, - c.submit_infos, - c.finales_folded, - c.finales_apart, - c.batches_with_none_pending, - c.batches_with_one_pending, - c.batches_with_two_or_three_pending, - c.batches_with_four_or_more_pending, - ); - eprintln!( - "runtime scheduler: scheduler_sleeps {} scheduler_wakes_commit {}", - c.scheduler_sleeps, c.scheduler_wakes_commit, - ); - eprintln!( - "runtime submit stalls: idle_submits {} submit_stalls_idle {} \ - submit_stalls_on_work {} submits_behind_idle_stalls {} \ - wait_behind_idle_stall_longest_nanos {}", - c.idle_submits, - c.submit_stalls_idle, - c.submit_stalls_on_work, - c.submits_behind_idle_stalls, - c.wait_behind_idle_stall_longest_nanos, - ); - eprintln!("runtime commands recorded: {:?}", c.commands_recorded); - eprintln!( - "runtime notices: {} (bound notices made {}), other messages heard {}", - runtime::NOTICES.load(std::sync::atomic::Ordering::Relaxed), - c.bound_notices_made, - runtime::MESSAGES.load(std::sync::atomic::Ordering::Relaxed) - ); - } - other => panic!("--side native|runtime, not {other}"), - } -} - -/// Run the selected workloads on `g`, whose device took `opened` to open. -fn run(g: &G, opened: Duration, metallib: &Path, options: &Options) { - workloads::emit( - "meta", - "device_open", - "ms", - &mut [opened.as_secs_f64() * 1e3], - ); - eprintln!("{}", g.label()); - let sizes = &options.sizes; - if options.only.iter().any(|w| w == "pipeline") { - workloads::pipeline(g, metallib, sizes); - } - let rest: Vec<&str> = options - .only - .iter() - .map(String::as_str) - .filter(|w| *w != "pipeline") - .collect(); - if rest.is_empty() { - return; - } - let t = Instant::now(); - let library = g.library(metallib); - let scene = workloads::Scene::new(g, &library, sizes); - workloads::emit( - "meta", - "scene_setup", - "ms", - &mut [t.elapsed().as_secs_f64() * 1e3], - ); - for workload in rest { - match workload { - "encode" => workloads::encode(g, &scene, &library, sizes, &options.variants), - "fixed" => workloads::fixed(g, &scene, sizes), - "calls" => workloads::calls(g, &scene, &library, sizes, &options.variants), - "latency" => workloads::latency(g, &scene, sizes), - "gpu" => workloads::gpu(g, &scene, sizes, options.outputs.as_deref()), - "memory" => workloads::memory(g, sizes, &options.variants), - "frame" => workloads::frame(g, &scene, sizes), - "many_draws" => workloads::many_draws(g, &library, sizes), - "layers" => workloads::layers(g, &library, sizes), - "churn" => workloads::churn(g, sizes), - "compositing" => workloads::compositing(g, &scene, sizes), - "drag" => workloads::drag(g, &scene, sizes), - "burst" => workloads::burst(g, &scene), - "icb" => workloads::icb(g, &library, sizes), - "icb_draws" => workloads::icb_draws(g, &library, sizes), - "signals" => workloads::signals(g, &scene, sizes), - "provoking" => workloads::provoking(g, &library, sizes), - "icb_cpu" => workloads::icb_cpu(g, &library, sizes), - "percall" => percall::percall(g, &scene, &library, sizes), - "threads" => workloads::threads(g, &library, &scene.textured[0], sizes), - _ => unreachable!(), - } - } -} - -/// The host clock Metal's and the runtime's command buffer times count: `CLOCK_UPTIME_RAW` -/// (`mach_absolute_time`) on macOS. -pub fn host_seconds() -> f64 { - metal2vulkan_runtime::host_time() -} - -fn scratch_default() -> PathBuf { - std::env::temp_dir().join(format!("host-ab-{}", std::process::id())) -} - -/// The shaders' source, beside this file. -fn source() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/host_ab/host_ab.metal") -} - -/// Compile the source with `NONCE` into `scratch`. -fn compile(scratch: &Path, nonce: u64) -> PathBuf { - let out = scratch.join(format!("host_ab-{nonce}.metallib")); - let status = Command::new("xcrun") - .args(["-sdk", "macosx", "metal", &format!("-DNONCE={nonce}"), "-o"]) - .arg(&out) - .arg(source()) - .status() - .expect("run xcrun metal"); - assert!(status.success(), "xcrun metal failed"); - out -} - -/// One side's results: (workload, metric) to (unit, median). -type Results = BTreeMap<(String, String), (String, f64)>; - -/// Run this binary as one side and collect its result lines; with `outputs`, the side writes its -/// kernel outputs there. -fn spawn( - side: &str, - metallib: &Path, - (cache, outputs): (&Path, Option<&Path>), - only: &[&str], - options: &Options, -) -> Results { - let mut command = Command::new(std::env::current_exe().expect("this executable")); - command - .args(["--side", side, "--only", &only.join(",")]) - .arg("--metallib") - .arg(metallib) - .arg("--cache") - .arg(cache); - if let Some(outputs) = outputs { - command.arg("--outputs").arg(outputs); - } - let output = command - .args(&options.passed) - .stderr(Stdio::inherit()) - .output() - .expect("run a side"); - assert!( - output.status.success(), - "the {side} side failed: {}", - output.status - ); - let mut results = Results::new(); - for line in String::from_utf8_lossy(&output.stdout).lines() { - let fields: Vec<&str> = line.split('\t').collect(); - if fields.first() == Some(&"R") && fields.len() >= 5 { - let median = fields[4].parse().expect("a median"); - results.insert( - (fields[1].to_owned(), fields[2].to_owned()), - (fields[3].to_owned(), median), - ); - } - } - results -} - -/// Every round's results per side: (workload, metric) to (unit, [native medians], [runtime -/// medians]). -type Table = BTreeMap<(String, String), (String, Vec, Vec)>; - -/// Each kernel output's 32-bit words, and per round how many differ between the sides. -type Compared = BTreeMap)>; - -/// Compare the outputs both sides wrote (`.bin` in each directory), then remove them. -fn compare(dirs: &[PathBuf], compared: &mut Compared) { - let mut names: Vec<_> = std::fs::read_dir(&dirs[0]) - .expect("read the outputs") - .map(|entry| entry.expect("an output").file_name()) - .collect(); - names.sort(); - for name in names { - let [a, b] = [0, 1].map(|s| std::fs::read(dirs[s].join(&name)).expect("read an output")); - assert_eq!(a.len(), b.len(), "{name:?}: the sides' lengths"); - let differ = a.chunks(4).zip(b.chunks(4)).filter(|(x, y)| x != y).count(); - let key = name.to_string_lossy().trim_end_matches(".bin").to_owned(); - let entry = compared.entry(key).or_insert((a.len() / 4, vec![])); - entry.1.push(differ); - } - for dir in dirs { - let _ = std::fs::remove_dir_all(dir); - } -} - -fn add(table: &mut Table, side: usize, results: Results, prefix: &str) { - for ((workload, metric), (unit, median)) in results { - let key = (workload, format!("{prefix}{metric}")); - let entry = table.entry(key).or_insert_with(|| (unit, vec![], vec![])); - [&mut entry.1, &mut entry.2][side].push(median); - } -} - -fn parent(options: &Options) { - let scratch = options.scratch.clone().unwrap_or_else(scratch_default); - let removes = options.scratch.is_none(); - std::fs::create_dir_all(&scratch).expect("make the scratch directory"); - let sides: &[&str] = if cfg!(target_os = "macos") { - &["native", "runtime"] - } else { - &["runtime"] - }; - let rest: Vec<&str> = options - .only - .iter() - .map(String::as_str) - .filter(|w| *w != "pipeline") - .collect(); - let mut table = Table::new(); - let mut compared = Compared::new(); - // Both sides' kernel outputs, compared each round. - let outputs: Vec = if sides.len() == 2 && rest.contains(&"gpu") { - sides - .iter() - .map(|side| scratch.join(format!("outputs-{side}"))) - .collect() - } else { - vec![] - }; - let metallib = match &options.metallib { - Some(path) => path.clone(), - None => compile(&scratch, 0), - }; - // Below 2^24 (host_ab.metal), and new each second. - let nonce_base = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("a clock after 1970") - .as_secs() - % 100_000; - for round in 0..options.rounds { - eprintln!("round {} of {}", round + 1, options.rounds); - if !rest.is_empty() { - for (s, side) in sides.iter().enumerate() { - let out = outputs.get(s).map(PathBuf::as_path); - if let Some(dir) = out { - std::fs::create_dir_all(dir).expect("make an outputs directory"); - } - let cache = scratch.join("cache-main"); - let results = spawn(side, &metallib, (&cache, out), &rest, options); - add(&mut table, s, results, ""); - } - if !outputs.is_empty() { - compare(&outputs, &mut compared); - } - } - if options.only.iter().any(|w| w == "pipeline") { - for (s, side) in sides.iter().enumerate() { - let nonce = nonce_base * 100 + (round * 2 + s) as u64 + 1; - let fresh = compile(&scratch, nonce); - let cache = scratch.join(format!("cache-{nonce}")); - let cold = spawn(side, &fresh, (&cache, None), &["pipeline"], options); - add(&mut table, s, cold, "cold_"); - let warm = spawn(side, &fresh, (&cache, None), &["pipeline"], options); - add(&mut table, s, warm, "warm_"); - let _ = std::fs::remove_dir_all(&cache); - let _ = std::fs::remove_file(&fresh); - } - } - } - print_table(&table, options.rounds); - print_percall(&table, options.rounds); - print_compared(&compared); - if removes { - let _ = std::fs::remove_dir_all(&scratch); - } -} - -fn median(values: &[f64]) -> Option { - let mut sorted = values.to_vec(); - sorted.sort_by(f64::total_cmp); - sorted.get(sorted.len() / 2).copied() -} - -fn print_table(table: &Table, rounds: usize) { - println!( - "| workload | metric | unit | native | runtime | runtime/native | native rounds | runtime rounds |" - ); - println!("|---|---|---|---:|---:|---:|---|---|"); - let spread = |values: &[f64]| match ( - values.iter().copied().reduce(f64::min), - values.iter().copied().reduce(f64::max), - ) { - (Some(low), Some(high)) => format!("{low:.3}..{high:.3} ({})", values.len()), - _ => "-".to_owned(), - }; - for ((workload, metric), (unit, native, runtime)) in table { - let (n, r) = (median(native), median(runtime)); - let show = |v: Option| v.map_or("-".to_owned(), |v| format!("{v:.3}")); - let ratio = match (n, r) { - (Some(n), Some(r)) if n > 0.0 => format!("{:.2}x", r / n), - _ => "-".to_owned(), - }; - println!( - "| {workload} | {metric} | {unit} | {} | {} | {ratio} | {} | {} |", - show(n), - show(r), - spread(native), - spread(runtime) - ); - } - println!("\n{rounds} rounds; each cell is the median of the rounds' medians."); -} - -/// The per-call table of the percall workload: each call's cost on each side, their ratio, where -/// we are worst, the three attributions, and the runtime's own counts of what each call made -/// (`percall.rs`). Nothing is printed where the workload did not run. -fn print_percall(table: &Table, rounds: usize) { - let of = |call: &str, what: &str| -> (Option, Option) { - match table.get(&("percall".to_owned(), format!("{call}_{what}"))) { - Some((_, native, runtime)) => (median(native), median(runtime)), - None => (None, None), - } - }; - let calls: Vec<&str> = table - .keys() - .filter(|(workload, _)| workload == "percall") - .filter_map(|(_, metric)| metric.strip_suffix("_self")) - .collect(); - if calls.is_empty() { - return; - } - let show = |v: Option| v.map_or("-".to_owned(), |v| format!("{v:.1}")); - let ratio = |(n, r): (Option, Option)| match (n, r) { - (Some(n), Some(r)) if n > 0.0 => Some(r / n), - _ => None, - }; - println!("\n### The per-call cost of the device API, Metal against the runtime\n"); - println!("Each call timed alone, warm, {rounds} rounds; ns a call.\n"); - println!("| call | Metal | runtime | runtime/Metal | runtime - Metal |"); - println!("|---|---:|---:|---:|---:|"); - // A call of the driver's own, which the runtime's side alone times, has no Metal counterpart - // and goes in its own table below (`vkfloor.rs`). - let (floor, metal): (Vec<&&str>, Vec<&&str>) = - calls.iter().partition(|call| call.starts_with("vk_")); - for call in &metal { - let (n, r) = of(call, "self"); - let added = match (n, r) { - (Some(n), Some(r)) => format!("{:+.1}", r - n), - _ => "-".to_owned(), - }; - println!( - "| {call} | {} | {} | {} | {added} |", - show(n), - show(r), - ratio((n, r)).map_or("-".to_owned(), |v| format!("{v:.2}x")) - ); - } - if !floor.is_empty() { - println!( - "\nThe driver's own calls under them, on the Vulkan device the runtime holds \ - (MoltenVK here), which Metal has no counterpart for: what a gap above costs \ - outside our code.\n" - ); - println!("| driver call | cost |"); - println!("|---|---:|"); - for call in &floor { - println!("| {call} | {} |", show(of(call, "self").1)); - } - } - let mut worst: Vec<(&str, f64, f64, f64)> = calls - .iter() - .filter_map(|call| { - let (n, r) = of(call, "self"); - Some((*call, ratio((n, r))?, r? - n?, n?)) - }) - .collect(); - let top = |rows: &[(&str, f64, f64, f64)], what: &str| { - println!("\n{what}\n"); - println!("| call | Metal ns | runtime ns | runtime/Metal | runtime - Metal |"); - println!("|---|---:|---:|---:|---:|"); - for (call, ratio, added, native) in rows.iter().take(12) { - println!( - "| {call} | {native:.1} | {:.1} | {ratio:.2}x | {added:+.1} |", - native + added - ); - } - }; - worst.sort_by(|a, b| b.1.total_cmp(&a.1)); - top(&worst, "Worst by ratio:"); - worst.sort_by(|a, b| b.2.total_cmp(&a.2)); - top(&worst, "Worst by the nanoseconds a call adds:"); - println!("\n### Where each call's cost falls\n"); - println!( - "`self` is the calling thread's wall time a call, `blocked` how much of it the thread \ - was off a CPU, `others` our own other threads' CPU time while the calls ran, `drain` \ - the calling thread's wall time after them (the commit and wait of the command buffer \ - the calls filled, where the group has one), `drain blocked` how much of that drain the \ - thread was off a CPU, and `drain others` our other threads' CPU time in it. ns a call, \ - and allocations a call on the calling thread.\n" - ); - println!( - "| call | Metal self | Metal others | Metal blocked | Metal drain | Metal drain \ - blocked | Metal drain others | Metal allocs | runtime self | runtime others | runtime \ - blocked | runtime drain | runtime drain blocked | runtime drain others | runtime \ - allocs |" - ); - println!("|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|"); - for call in &calls { - let parts = [ - "self", - "others", - "blocked", - "drain", - "drain_blocked", - "drain_others", - "allocs", - ]; - let cells: Vec = [0, 1] - .into_iter() - .flat_map(|side| { - parts.map(|what| { - let both = of(call, what); - show([both.0, both.1][side]) - }) - }) - .collect(); - println!("| {call} | {} |", cells.join(" | ")); - } - let counts: Vec<(&String, &str, Option)> = table - .iter() - .filter(|((workload, _), _)| workload == "percall") - .filter_map(|((_, metric), (_, _, runtime))| { - let (call, counted) = metric.split_once("_rt_")?; - let _ = call; - Some((metric, counted, median(runtime))) - }) - .collect(); - if counts.is_empty() { - return; - } - println!("\n### What the runtime's calls made it do, per call\n"); - println!("Counts, which are the same under any load; none natively.\n"); - println!("| call and count | per call |"); - println!("|---|---:|"); - for (metric, counted, value) in counts { - let call = metric.split_once("_rt_").map_or("", |(call, _)| call); - println!("| {call} / {counted} | {} |", show(value)); - } -} - -fn print_compared(compared: &Compared) { - if compared.is_empty() { - return; - } - println!("\n| kernel output | 32-bit words | words differing (native vs runtime), per round |"); - println!("|---|---:|---|"); - for (name, (words, differ)) in compared { - let rounds: Vec = differ.iter().map(usize::to_string).collect(); - println!("| {name} | {words} | {} |", rounds.join(", ")); - } -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/native.rs b/crates/metal2vulkan-runtime/examples/host_ab/native.rs deleted file mode 100644 index c705e945a..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/native.rs +++ /dev/null @@ -1,1354 +0,0 @@ -//! The native side: Metal's calls on Metal itself (objc2-metal), on the system default device. - -use crate::gpu::{Format, Gpu}; -use block2::RcBlock; -use objc2::msg_send; -use objc2::rc::{autoreleasepool, Retained}; -use objc2::runtime::ProtocolObject; -use objc2_foundation::{NSString, NSURL}; -use objc2_metal::{ - MTLBlendFactor, MTLBlitCommandEncoder, MTLBuffer, MTLClearColor, MTLCommandBuffer, - MTLCommandBufferStatus, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, - MTLComputeCommandEncoder, MTLComputePipelineDescriptor, MTLComputePipelineState, - MTLCreateSystemDefaultDevice, MTLCullMode, MTLDepthStencilDescriptor, MTLDepthStencilState, - MTLDevice, MTLDispatchType, MTLHazardTrackingMode, MTLHeap, MTLHeapDescriptor, MTLHeapType, - MTLIndexType, MTLIndirectCommandBuffer, MTLIndirectCommandBufferDescriptor, - MTLIndirectCommandType, MTLIndirectComputeCommand, MTLIndirectRenderCommand, MTLLibrary, - MTLLoadAction, MTLOrigin, MTLPipelineOption, MTLPixelFormat, MTLPrimitiveType, MTLRegion, - MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, - MTLRenderPipelineState, MTLRenderStages, MTLResource, MTLResourceOptions, MTLResourceUsage, - MTLSamplerDescriptor, MTLSamplerMinMagFilter, MTLSamplerState, MTLSharedEvent, - MTLSharedEventListener, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, - MTLTextureDescriptor, MTLTextureUsage, MTLWinding, -}; -use std::ffi::c_void; -use std::path::Path; -use std::ptr::NonNull; -use std::sync::Mutex; - -type Object = Retained>; - -pub struct Native { - device: Object, - queue: Object, -} - -impl Native { - pub fn open() -> Native { - let device = MTLCreateSystemDefaultDevice().expect("MTLCreateSystemDefaultDevice"); - let queue = device.newCommandQueue().expect("newCommandQueue"); - Native { device, queue } - } -} - -fn pixel_format(format: Format) -> MTLPixelFormat { - match format { - Format::Bgra8 => MTLPixelFormat::BGRA8Unorm, - Format::Rgba8 => MTLPixelFormat::RGBA8Unorm, - Format::Rgba16Float => MTLPixelFormat::RGBA16Float, - Format::Depth32Float => MTLPixelFormat::Depth32Float, - } -} - -fn region(size: (usize, usize)) -> MTLRegion { - MTLRegion { - origin: MTLOrigin { x: 0, y: 0, z: 0 }, - size: MTLSize { - width: size.0, - height: size.1, - depth: 1, - }, - } -} - -fn function( - library: &ProtocolObject, - name: &str, -) -> Object { - library - .newFunctionWithName(&NSString::from_str(name)) - .unwrap_or_else(|| panic!("newFunctionWithName {name}")) -} - -impl Gpu for Native { - type Library = Object; - type RenderPipeline = Object; - type ComputePipeline = Object; - type Buffer = Object; - type Texture = Object; - type Sampler = Object; - type CommandBuffer = Object; - type RenderEncoder = Object; - type ComputeEncoder = Object; - type Heap = Object; - type DepthStencil = Object; - type IndirectCommands = Object; - type SharedEvent = Object; - type Listener = Retained; - type Pass = Retained; - type BlitEncoder = Object; - type Fence = Object; - - fn label(&self) -> String { - format!("native Metal on {}", self.device.name()) - } - - fn with_own_queue(&self) -> Native { - let queue = self.device.newCommandQueue().expect("newCommandQueue"); - Native { - device: self.device.clone(), - queue, - } - } - - fn library(&self, metallib: &Path) -> Self::Library { - let path = NSString::from_str(metallib.to_str().expect("a UTF-8 path")); - self.device - .newLibraryWithURL_error(&NSURL::fileURLWithPath(&path)) - .expect("newLibraryWithURL") - } - - fn render_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - format: Format, - blend: bool, - ) -> Self::RenderPipeline { - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setVertexFunction(Some(&function(library, vertex))); - descriptor.setFragmentFunction(Some(&function(library, fragment))); - // SAFETY: attachment 0 exists. - let color = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color.setPixelFormat(pixel_format(format)); - color.setBlendingEnabled(blend); - self.device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .expect("newRenderPipelineStateWithDescriptor") - } - - fn depth_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - blend: bool, - ) -> Self::RenderPipeline { - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setVertexFunction(Some(&function(library, vertex))); - descriptor.setFragmentFunction(Some(&function(library, fragment))); - // SAFETY: attachment 0 exists. - let color = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color.setPixelFormat(MTLPixelFormat::BGRA8Unorm); - if blend { - color.setBlendingEnabled(true); - color.setSourceRGBBlendFactor(MTLBlendFactor::SourceAlpha); - color.setSourceAlphaBlendFactor(MTLBlendFactor::One); - color.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - color.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - } - descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); - self.device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .expect("newRenderPipelineStateWithDescriptor") - } - - fn depth_stencil(&self, writes: bool) -> Self::DepthStencil { - let descriptor = MTLDepthStencilDescriptor::new(); - descriptor.setDepthCompareFunction(if writes { - MTLCompareFunction::Less - } else { - MTLCompareFunction::LessEqual - }); - descriptor.setDepthWriteEnabled(writes); - self.device - .newDepthStencilStateWithDescriptor(&descriptor) - .expect("newDepthStencilStateWithDescriptor") - } - - fn compute_pipeline(&self, library: &Self::Library, kernel: &str) -> Self::ComputePipeline { - self.device - .newComputePipelineStateWithFunction_error(&function(library, kernel)) - .expect("newComputePipelineStateWithFunction") - } - - fn indirect_compute_pipeline( - &self, - library: &Self::Library, - kernel: &str, - ) -> Self::ComputePipeline { - let descriptor = MTLComputePipelineDescriptor::new(); - descriptor.setComputeFunction(Some(&function(library, kernel))); - descriptor.setSupportIndirectCommandBuffers(true); - self.device - .newComputePipelineStateWithDescriptor_options_reflection_error( - &descriptor, - MTLPipelineOption::None, - None, - ) - .expect("newComputePipelineStateWithDescriptor") - } - - fn indirect_commands(&self, count: usize) -> Self::IndirectCommands { - let descriptor = MTLIndirectCommandBufferDescriptor::new(); - descriptor.setCommandTypes(MTLIndirectCommandType::ConcurrentDispatch); - descriptor.setInheritPipelineState(false); - descriptor.setInheritBuffers(false); - descriptor.setMaxKernelBufferBindCount(1); - // SAFETY: `count` is within Metal's most commands (16,384), which the workload keeps. - unsafe { - self.device - .newIndirectCommandBufferWithDescriptor_maxCommandCount_options( - &descriptor, - count, - MTLResourceOptions::StorageModePrivate, - ) - } - .expect("newIndirectCommandBufferWithDescriptor") - } - - fn indirect_render_pipeline( - &self, - library: &Self::Library, - vertex: &str, - fragment: &str, - ) -> Self::RenderPipeline { - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setVertexFunction(Some(&function(library, vertex))); - descriptor.setFragmentFunction(Some(&function(library, fragment))); - // SAFETY: attachment 0 exists. - let color = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color.setPixelFormat(MTLPixelFormat::BGRA8Unorm); - descriptor.setSupportIndirectCommandBuffers(true); - self.device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .expect("newRenderPipelineStateWithDescriptor") - } - - fn indirect_draws(&self, count: usize, vertex_buffers: usize) -> Self::IndirectCommands { - let descriptor = MTLIndirectCommandBufferDescriptor::new(); - descriptor.setCommandTypes(MTLIndirectCommandType::Draw); - descriptor.setInheritPipelineState(true); - descriptor.setInheritBuffers(false); - descriptor.setMaxVertexBufferBindCount(vertex_buffers); - descriptor.setMaxFragmentBufferBindCount(0); - // SAFETY: the descriptor is a draw buffer's, of a count above zero. - unsafe { - self.device - .newIndirectCommandBufferWithDescriptor_maxCommandCount_options( - &descriptor, - count, - MTLResourceOptions::StorageModeShared, - ) - } - .expect("newIndirectCommandBufferWithDescriptor") - } - - fn commands_id(&self, commands: &Self::IndirectCommands) -> u64 { - commands.gpuResourceID().to_raw() - } - - fn pipeline_id(&self, state: &Self::ComputePipeline) -> u64 { - state.gpuResourceID().to_raw() - } - - fn texture_id(&self, texture: &Self::Texture) -> u64 { - texture.gpuResourceID().to_raw() - } - - fn cpu_indirect_commands(&self, count: usize) -> Self::IndirectCommands { - let descriptor = MTLIndirectCommandBufferDescriptor::new(); - descriptor.setCommandTypes(MTLIndirectCommandType::ConcurrentDispatch); - descriptor.setInheritPipelineState(false); - descriptor.setInheritBuffers(false); - descriptor.setMaxKernelBufferBindCount(1); - // SAFETY: `count` is within Metal's most commands (16,384), which the workload keeps. - unsafe { - self.device - .newIndirectCommandBufferWithDescriptor_maxCommandCount_options( - &descriptor, - count, - MTLResourceOptions::StorageModeShared, - ) - } - .expect("newIndirectCommandBufferWithDescriptor") - } - - fn cpu_indirect_draws(&self, count: usize) -> Self::IndirectCommands { - let descriptor = MTLIndirectCommandBufferDescriptor::new(); - descriptor.setCommandTypes(MTLIndirectCommandType::Draw); - descriptor.setInheritPipelineState(false); - descriptor.setInheritBuffers(false); - descriptor.setMaxVertexBufferBindCount(1); - descriptor.setMaxFragmentBufferBindCount(1); - // SAFETY: the descriptor is a draw buffer's, of a count within Metal's most. - unsafe { - self.device - .newIndirectCommandBufferWithDescriptor_maxCommandCount_options( - &descriptor, - count, - MTLResourceOptions::StorageModeShared, - ) - } - .expect("newIndirectCommandBufferWithDescriptor") - } - - fn command_pipeline( - &self, - commands: &Self::IndirectCommands, - index: usize, - state: &Self::ComputePipeline, - ) { - // SAFETY: `index` is below the buffer's count (the workload's). - let command = unsafe { commands.indirectComputeCommandAtIndex(index) }; - command.setComputePipelineState(state); - } - - fn command_kernel_buffer( - &self, - commands: &Self::IndirectCommands, - index: usize, - buffer: &Self::Buffer, - offset: usize, - ) { - // SAFETY: `index` is below the buffer's count, the buffer binds index 0, and `offset` - // lies inside `buffer` (the workload's). - unsafe { - let command = commands.indirectComputeCommandAtIndex(index); - command.setKernelBuffer_offset_atIndex(buffer, offset, 0); - } - } - - fn command_dispatch(&self, commands: &Self::IndirectCommands, index: usize, groups: usize) { - let size = |width| MTLSize { - width, - height: 1, - depth: 1, - }; - // SAFETY: `index` is below the buffer's count (the workload's). - let command = unsafe { commands.indirectComputeCommandAtIndex(index) }; - command.concurrentDispatchThreadgroups_threadsPerThreadgroup(size(groups), size(64)); - } - - fn command_barrier(&self, commands: &Self::IndirectCommands, index: usize) { - // SAFETY: `index` is below the buffer's count (the workload's). - let command = unsafe { commands.indirectComputeCommandAtIndex(index) }; - command.setBarrier(); - } - - fn command_kernel_buffer_address( - &self, - commands: &Self::IndirectCommands, - index: usize, - ) -> u64 { - // SAFETY: `index` is below the buffer's count; Apple's private getter takes an index the - // descriptor binds and answers a `uint64_t` (measured by the consumer on an M3 Max). - unsafe { - let command = commands.indirectComputeCommandAtIndex(index); - msg_send![&*command, getKernelBufferAddressAtIndex: 0usize] - } - } - - fn command_has_barrier(&self, commands: &Self::IndirectCommands, index: usize) -> bool { - // SAFETY: `index` is below the buffer's count; Apple's private getter answers a `BOOL`. - unsafe { - let command = commands.indirectComputeCommandAtIndex(index); - msg_send![&*command, hasBarrier] - } - } - - fn draw_command_pipeline( - &self, - commands: &Self::IndirectCommands, - index: usize, - state: &Self::RenderPipeline, - ) { - // SAFETY: `index` is below the buffer's count (the workload's). - let command = unsafe { commands.indirectRenderCommandAtIndex(index) }; - command.setRenderPipelineState(state); - } - - fn draw_command_vertex_buffer( - &self, - commands: &Self::IndirectCommands, - index: usize, - buffer: &Self::Buffer, - offset: usize, - ) { - // SAFETY: `index` is below the buffer's count, the buffer binds vertex index 0, and - // `offset` lies inside `buffer` (the workload's). - unsafe { - let command = commands.indirectRenderCommandAtIndex(index); - command.setVertexBuffer_offset_atIndex(buffer, offset, 0); - } - } - - fn draw_command_draw(&self, commands: &Self::IndirectCommands, index: usize) { - // SAFETY: `index` is below the buffer's count; a strip of four vertices, one instance. - unsafe { - let command = commands.indirectRenderCommandAtIndex(index); - command.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::TriangleStrip, - 0, - 4, - 1, - 0, - ); - } - } - - fn draw_command_vertex_buffer_address( - &self, - commands: &Self::IndirectCommands, - index: usize, - ) -> u64 { - // SAFETY: as `command_kernel_buffer_address`'s, of Apple's private vertex getter. - unsafe { - let command = commands.indirectRenderCommandAtIndex(index); - msg_send![&*command, getVertexBufferAddressAtIndex: 0usize] - } - } - - fn buffer(&self, length: usize) -> Self::Buffer { - self.device - .newBufferWithLength_options(length, MTLResourceOptions::StorageModeShared) - .expect("newBufferWithLength") - } - - fn buffer_with(&self, bytes: &[u8]) -> Self::Buffer { - let pointer = NonNull::new(bytes.as_ptr() as *mut c_void).expect("bytes"); - // SAFETY: `bytes` holds `bytes.len()` bytes, which Metal copies. - unsafe { - self.device.newBufferWithBytes_length_options( - pointer, - bytes.len(), - MTLResourceOptions::StorageModeShared, - ) - } - .expect("newBufferWithBytes") - } - - unsafe fn buffer_no_copy(&self, pointer: *mut u8, length: usize) -> Self::Buffer { - let pointer = NonNull::new(pointer as *mut c_void).expect("a pointer"); - // SAFETY: the caller's contract. - unsafe { - self.device - .newBufferWithBytesNoCopy_length_options_deallocator( - pointer, - length, - MTLResourceOptions::StorageModeShared, - None, - ) - } - .expect("newBufferWithBytesNoCopy") - } - - fn heap(&self, size: usize) -> Self::Heap { - let descriptor = MTLHeapDescriptor::new(); - descriptor.setType(MTLHeapType::Placement); - descriptor.setStorageMode(MTLStorageMode::Shared); - descriptor.setSize(size); - self.device - .newHeapWithDescriptor(&descriptor) - .expect("newHeapWithDescriptor") - } - - unsafe fn heap_no_copy(&self, _pointer: *mut u8, _size: usize) -> Option { - None - } - - fn heap_texture( - &self, - heap: &Self::Heap, - width: usize, - height: usize, - offset: usize, - ) -> Self::Texture { - // SAFETY: plain sizes. - let descriptor = unsafe { - MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( - MTLPixelFormat::BGRA8Unorm, - width, - height, - false, - ) - }; - descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); - descriptor.setStorageMode(MTLStorageMode::Shared); - descriptor.setAllowGPUOptimizedContents(false); - // SAFETY: the offset lies inside the heap, aligned for the texture (the workload's). - unsafe { heap.newTextureWithDescriptor_offset(&descriptor, offset) } - .expect("newTextureWithDescriptor:offset:") - } - - fn buffer_texture( - &self, - buffer: &Self::Buffer, - (width, height): (usize, usize), - offset: usize, - bytes_per_row: usize, - ) -> Self::Texture { - // SAFETY: plain sizes. - let descriptor = unsafe { - MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( - MTLPixelFormat::BGRA8Unorm, - width, - height, - false, - ) - }; - descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); - descriptor.setStorageMode(MTLStorageMode::Shared); - buffer - .newTextureWithDescriptor_offset_bytesPerRow(&descriptor, offset, bytes_per_row) - .expect("newTextureWithDescriptor:offset:bytesPerRow:") - } - - fn texture(&self, format: Format, width: usize, height: usize, target: bool) -> Self::Texture { - // SAFETY: plain sizes. - let descriptor = unsafe { - MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( - pixel_format(format), - width, - height, - false, - ) - }; - if target { - descriptor.setUsage(MTLTextureUsage::RenderTarget); - descriptor.setStorageMode(MTLStorageMode::Private); - } else { - descriptor.setUsage(MTLTextureUsage::ShaderRead); - descriptor.setStorageMode(MTLStorageMode::Shared); - } - self.device - .newTextureWithDescriptor(&descriptor) - .expect("newTextureWithDescriptor") - } - - fn tracked_heap(&self, size: usize) -> Self::Heap { - let descriptor = MTLHeapDescriptor::new(); - descriptor.setType(MTLHeapType::Placement); - descriptor.setStorageMode(MTLStorageMode::Shared); - descriptor.setHazardTrackingMode(MTLHazardTrackingMode::Tracked); - descriptor.setSize(size); - self.device - .newHeapWithDescriptor(&descriptor) - .expect("newHeapWithDescriptor") - } - - fn heap_render_texture( - &self, - heap: &Self::Heap, - format: Format, - side: usize, - offset: usize, - ) -> Self::Texture { - // SAFETY: plain sizes. - let descriptor = unsafe { - MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( - pixel_format(format), - side, - side, - false, - ) - }; - descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); - descriptor.setStorageMode(MTLStorageMode::Shared); - // SAFETY: the workload places each texture within the heap at its alignment. - unsafe { heap.newTextureWithDescriptor_offset(&descriptor, offset) } - .expect("newTextureWithDescriptor:offset:") - } - - fn replace_region( - &self, - texture: &Self::Texture, - size: (usize, usize), - bytes: &[u8], - row: usize, - ) { - let pointer = NonNull::new(bytes.as_ptr() as *mut c_void).expect("bytes"); - // SAFETY: `bytes` holds the region's rows at `row` bytes each. - unsafe { - texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(region(size), 0, pointer, row) - }; - } - - fn get_bytes( - &self, - texture: &Self::Texture, - size: (usize, usize), - bytes: &mut [u8], - row: usize, - ) { - let pointer = NonNull::new(bytes.as_mut_ptr() as *mut c_void).expect("bytes"); - // SAFETY: `bytes` has room for the region's rows at `row` bytes each. - unsafe { - texture.getBytes_bytesPerRow_fromRegion_mipmapLevel(pointer, row, region(size), 0) - }; - } - - fn read_buffer(&self, buffer: &Self::Buffer, bytes: &mut [u8]) { - assert!(bytes.len() <= buffer.length(), "a read within the buffer"); - // SAFETY: a `Shared` buffer's `contents` holds its `length` bytes, which no GPU work - // writes now (the caller's contract), and `bytes` is as long as the copy. - unsafe { - std::ptr::copy_nonoverlapping( - buffer.contents().as_ptr() as *const u8, - bytes.as_mut_ptr(), - bytes.len(), - ) - }; - } - - fn write_buffer(&self, buffer: &Self::Buffer, value: u8) { - // SAFETY: a `Shared` buffer's `contents` holds its `length` bytes, which no GPU work - // uses now (the caller's contract). - unsafe { - std::ptr::write_bytes( - buffer.contents().as_ptr() as *mut u8, - value, - buffer.length(), - ) - }; - } - - fn sampler(&self, linear: bool) -> Self::Sampler { - let descriptor = MTLSamplerDescriptor::new(); - if linear { - descriptor.setMinFilter(MTLSamplerMinMagFilter::Linear); - descriptor.setMagFilter(MTLSamplerMinMagFilter::Linear); - } - self.device - .newSamplerStateWithDescriptor(&descriptor) - .expect("newSamplerStateWithDescriptor") - } - - fn command_buffer(&self) -> Self::CommandBuffer { - self.queue.commandBuffer().expect("commandBuffer") - } - - fn render_encoder( - &self, - command_buffer: &Self::CommandBuffer, - target: &Self::Texture, - clear: bool, - ) -> Self::RenderEncoder { - let pass = MTLRenderPassDescriptor::renderPassDescriptor(); - // SAFETY: attachment 0 exists. - let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) }; - color.setTexture(Some(target)); - color.setLoadAction(if clear { - MTLLoadAction::Clear - } else { - MTLLoadAction::Load - }); - color.setStoreAction(MTLStoreAction::Store); - color.setClearColor(MTLClearColor { - red: 0.0, - green: 0.0, - blue: 0.0, - alpha: 1.0, - }); - command_buffer - .renderCommandEncoderWithDescriptor(&pass) - .expect("renderCommandEncoderWithDescriptor") - } - - fn pass(&self, target: &Self::Texture) -> Self::Pass { - let pass = MTLRenderPassDescriptor::renderPassDescriptor(); - // SAFETY: attachment 0 exists. - let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) }; - color.setTexture(Some(target)); - color.setLoadAction(MTLLoadAction::Clear); - color.setStoreAction(MTLStoreAction::Store); - color.setClearColor(MTLClearColor { - red: 0.0, - green: 0.0, - blue: 0.0, - alpha: 1.0, - }); - pass - } - - fn pass_encoder( - &self, - command_buffer: &Self::CommandBuffer, - pass: &Self::Pass, - ) -> Self::RenderEncoder { - command_buffer - .renderCommandEncoderWithDescriptor(pass) - .expect("renderCommandEncoderWithDescriptor") - } - - fn depth_render_encoder( - &self, - command_buffer: &Self::CommandBuffer, - target: &Self::Texture, - depth: &Self::Texture, - ) -> Self::RenderEncoder { - let pass = MTLRenderPassDescriptor::renderPassDescriptor(); - // SAFETY: attachment 0 exists. - let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) }; - color.setTexture(Some(target)); - color.setLoadAction(MTLLoadAction::Clear); - color.setStoreAction(MTLStoreAction::Store); - color.setClearColor(MTLClearColor { - red: 0.1, - green: 0.1, - blue: 0.12, - alpha: 1.0, - }); - let attachment = pass.depthAttachment(); - attachment.setTexture(Some(depth)); - attachment.setLoadAction(MTLLoadAction::Clear); - attachment.setStoreAction(MTLStoreAction::DontCare); - attachment.setClearDepth(1.0); - command_buffer - .renderCommandEncoderWithDescriptor(&pass) - .expect("renderCommandEncoderWithDescriptor") - } - - fn set_render_pipeline(&self, encoder: &mut Self::RenderEncoder, state: &Self::RenderPipeline) { - encoder.setRenderPipelineState(state); - } - - fn set_depth_stencil(&self, encoder: &mut Self::RenderEncoder, state: &Self::DepthStencil) { - encoder.setDepthStencilState(Some(state)); - } - - fn set_cull_back(&self, encoder: &mut Self::RenderEncoder, back: bool) { - encoder.setCullMode(if back { - MTLCullMode::Back - } else { - MTLCullMode::None - }); - } - - fn set_counter_clockwise(&self, encoder: &mut Self::RenderEncoder) { - encoder.setFrontFacingWinding(MTLWinding::CounterClockwise); - } - - fn set_vertex_bytes(&self, encoder: &mut Self::RenderEncoder, bytes: &[u8], index: usize) { - let pointer = NonNull::new(bytes.as_ptr() as *mut c_void).expect("bytes"); - // SAFETY: `bytes` holds `bytes.len()` bytes, which Metal copies; the index is in Metal's - // range. - unsafe { encoder.setVertexBytes_length_atIndex(pointer, bytes.len(), index) }; - } - - fn set_vertex_buffer( - &self, - encoder: &mut Self::RenderEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ) { - // SAFETY: the offset lies in the buffer and the index is in Metal's range. - unsafe { encoder.setVertexBuffer_offset_atIndex(Some(buffer), offset, index) }; - } - - fn set_vertex_buffer_offset( - &self, - encoder: &mut Self::RenderEncoder, - offset: usize, - index: usize, - ) { - // SAFETY: the offset lies in the buffer bound at the index, which is in Metal's range. - unsafe { encoder.setVertexBufferOffset_atIndex(offset, index) }; - } - - fn set_vertex_buffers( - &self, - encoder: &mut Self::RenderEncoder, - buffers: &[&Self::Buffer], - offsets: &[usize], - first: usize, - ) { - let pointers: Vec<*const ProtocolObject> = - buffers.iter().map(|b| &***b as *const _).collect(); - let range = objc2_foundation::NSRange { - location: first, - length: buffers.len(), - }; - // SAFETY: as many buffers as offsets, each offset inside its buffer, the indices in - // Metal's range. - unsafe { - encoder.setVertexBuffers_offsets_withRange( - NonNull::new(pointers.as_ptr() as *mut _).expect("buffers"), - NonNull::new(offsets.as_ptr() as *mut usize).expect("offsets"), - range, - ) - }; - } - - fn set_fragment_buffer( - &self, - encoder: &mut Self::RenderEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ) { - // SAFETY: as `set_vertex_buffer`. - unsafe { encoder.setFragmentBuffer_offset_atIndex(Some(buffer), offset, index) }; - } - - fn set_fragment_texture( - &self, - encoder: &mut Self::RenderEncoder, - texture: &Self::Texture, - index: usize, - ) { - // SAFETY: the index is in Metal's range. - unsafe { encoder.setFragmentTexture_atIndex(Some(texture), index) }; - } - - fn set_fragment_sampler( - &self, - encoder: &mut Self::RenderEncoder, - sampler: &Self::Sampler, - index: usize, - ) { - // SAFETY: the index is in Metal's range. - unsafe { encoder.setFragmentSamplerState_atIndex(Some(sampler), index) }; - } - - fn draw_strip(&self, encoder: &mut Self::RenderEncoder, vertices: usize) { - // SAFETY: the bound state reads only its bound buffers. - unsafe { - encoder.drawPrimitives_vertexStart_vertexCount( - MTLPrimitiveType::TriangleStrip, - 0, - vertices, - ) - }; - } - - fn draw_indexed( - &self, - encoder: &mut Self::RenderEncoder, - count: usize, - indices: &Self::Buffer, - ) { - // SAFETY: the indices lie in the buffer, and the bound state reads only its bound buffers. - unsafe { - encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset( - MTLPrimitiveType::Triangle, - count, - MTLIndexType::UInt16, - indices, - 0, - ) - }; - } - - fn use_in_vertex(&self, encoder: &mut Self::RenderEncoder, buffer: &Self::Buffer) { - encoder.useResource_usage_stages( - ProtocolObject::from_ref(&**buffer), - MTLResourceUsage::Read, - MTLRenderStages::Vertex, - ); - } - - fn draw_triangles(&self, encoder: &mut Self::RenderEncoder, start: usize, count: usize) { - // SAFETY: the bound state reads only its bound buffers. - unsafe { - encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, start, count) - }; - } - - fn draw_indexed_at( - &self, - encoder: &mut Self::RenderEncoder, - count: usize, - indices: &Self::Buffer, - offset: usize, - ) { - // SAFETY: the indices lie in the buffer, and the bound state reads only its bound buffers. - unsafe { - encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset( - MTLPrimitiveType::Triangle, - count, - MTLIndexType::UInt16, - indices, - offset, - ) - }; - } - - fn draw_indexed_strip_at( - &self, - encoder: &mut Self::RenderEncoder, - count: usize, - indices: &Self::Buffer, - offset: usize, - ) { - // SAFETY: the indices lie in the buffer, and the bound state reads only its bound buffers. - unsafe { - encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset( - MTLPrimitiveType::TriangleStrip, - count, - MTLIndexType::UInt16, - indices, - offset, - ) - }; - } - - fn draw_triangles_indirect( - &self, - encoder: &mut Self::RenderEncoder, - arguments: &Self::Buffer, - offset: usize, - ) { - // SAFETY: the arguments lie in the buffer and name vertices the bound buffers hold. - unsafe { - encoder.drawPrimitives_indirectBuffer_indirectBufferOffset( - MTLPrimitiveType::Triangle, - arguments, - offset, - ) - }; - } - - fn draw_indexed_indirect( - &self, - encoder: &mut Self::RenderEncoder, - indices: &Self::Buffer, - arguments: &Self::Buffer, - offset: usize, - ) { - // SAFETY: the arguments lie in the buffer and name indices it holds. - unsafe { - encoder.drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset( - MTLPrimitiveType::Triangle, - MTLIndexType::UInt16, - indices, - 0, - arguments, - offset, - ) - }; - } - - fn set_provoking_vertex_mode(&self, encoder: &mut Self::RenderEncoder, mode: u64) { - // SAFETY: Apple's render encoders answer `setProvokingVertexMode:` (an NSUInteger). - unsafe { - let _: () = objc2::msg_send![&**encoder, setProvokingVertexMode: mode as usize]; - } - } - - fn execute_draws( - &self, - encoder: &mut Self::RenderEncoder, - commands: &Self::IndirectCommands, - count: usize, - ) { - let range = objc2_foundation::NSRange { - location: 0, - length: count, - }; - // SAFETY: the encoder's command buffer holds `commands` until it completes, the range - // lies within its commands, and they inherit the encoder's pipeline state. - unsafe { encoder.executeCommandsInBuffer_withRange(commands, range) }; - } - - fn end_render(&self, encoder: Self::RenderEncoder) { - encoder.endEncoding(); - } - - fn compute_encoder(&self, command_buffer: &Self::CommandBuffer) -> Self::ComputeEncoder { - command_buffer - .computeCommandEncoder() - .expect("computeCommandEncoder") - } - - fn concurrent_compute_encoder( - &self, - command_buffer: &Self::CommandBuffer, - ) -> Self::ComputeEncoder { - command_buffer - .computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent) - .expect("computeCommandEncoderWithDispatchType") - } - - fn set_compute_pipeline( - &self, - encoder: &mut Self::ComputeEncoder, - state: &Self::ComputePipeline, - ) { - encoder.setComputePipelineState(state); - } - - fn set_buffer( - &self, - encoder: &mut Self::ComputeEncoder, - buffer: &Self::Buffer, - offset: usize, - index: usize, - ) { - // SAFETY: as `set_vertex_buffer`. - unsafe { encoder.setBuffer_offset_atIndex(Some(buffer), offset, index) }; - } - - fn set_texture( - &self, - encoder: &mut Self::ComputeEncoder, - texture: &Self::Texture, - index: usize, - ) { - // SAFETY: the index is in Metal's range. - unsafe { encoder.setTexture_atIndex(Some(texture), index) }; - } - - fn dispatch(&self, encoder: &mut Self::ComputeEncoder, groups: usize, threads: usize) { - let size = |width| MTLSize { - width, - height: 1, - depth: 1, - }; - encoder.dispatchThreadgroups_threadsPerThreadgroup(size(groups), size(threads)); - } - - fn use_commands(&self, encoder: &mut Self::ComputeEncoder, commands: &Self::IndirectCommands) { - encoder.useResource_usage( - ProtocolObject::from_ref(&**commands), - MTLResourceUsage::Write, - ); - } - - fn use_buffers_read(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]) { - let resources: Vec>> = buffers - .iter() - .map(|b| NonNull::from(ProtocolObject::::from_ref(&***b))) - .collect(); - if let Some(first) = NonNull::new(resources.as_ptr() as *mut _) { - // SAFETY: `resources.len()` resources of this device. - unsafe { - encoder.useResources_count_usage(first, resources.len(), MTLResourceUsage::Read) - }; - } - } - - fn use_buffers_drawn(&self, encoder: &mut Self::RenderEncoder, buffers: &[&Self::Buffer]) { - let resources: Vec>> = buffers - .iter() - .map(|b| NonNull::from(ProtocolObject::::from_ref(&***b))) - .collect(); - if let Some(first) = NonNull::new(resources.as_ptr() as *mut _) { - // SAFETY: `resources.len()` resources of this device. - unsafe { - encoder.useResources_count_usage_stages( - first, - resources.len(), - MTLResourceUsage::Read, - MTLRenderStages::Vertex | MTLRenderStages::Fragment, - ) - }; - } - } - - fn use_buffer(&self, encoder: &mut Self::ComputeEncoder, buffer: &Self::Buffer) { - encoder.useResource_usage( - ProtocolObject::from_ref(&**buffer), - MTLResourceUsage::Read | MTLResourceUsage::Write, - ); - } - - fn use_heap(&self, encoder: &mut Self::ComputeEncoder, heap: &Self::Heap) { - encoder.useHeap(heap); - } - - fn update_fence(&self, encoder: &mut Self::ComputeEncoder, fence: &Self::Fence) { - encoder.updateFence(fence); - } - - fn wait_for_fence(&self, encoder: &mut Self::ComputeEncoder, fence: &Self::Fence) { - encoder.waitForFence(fence); - } - - fn use_buffers(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]) { - let resources: Vec>> = buffers - .iter() - .map(|buffer| NonNull::from(ProtocolObject::from_ref(&***buffer))) - .collect(); - let Some(first) = NonNull::new(resources.as_ptr().cast_mut()) else { - return; - }; - // SAFETY: `first` points at `resources.len()` live resources, held by `buffers`. - unsafe { encoder.useResources_count_usage(first, resources.len(), MTLResourceUsage::Read) }; - } - - fn use_textures(&self, encoder: &mut Self::ComputeEncoder, textures: &[&Self::Texture]) { - let resources: Vec>> = textures - .iter() - .map(|texture| NonNull::from(ProtocolObject::from_ref(&***texture))) - .collect(); - let Some(first) = NonNull::new(resources.as_ptr().cast_mut()) else { - return; - }; - // SAFETY: `first` points at `resources.len()` live resources, held by `textures`. - unsafe { encoder.useResources_count_usage(first, resources.len(), MTLResourceUsage::Read) }; - } - - fn execute_commands( - &self, - encoder: &mut Self::ComputeEncoder, - commands: &Self::IndirectCommands, - count: usize, - ) { - let range = objc2_foundation::NSRange { - location: 0, - length: count, - }; - // SAFETY: the encoder's command buffer holds `commands` until it completes, and the range - // lies within its commands. - unsafe { encoder.executeCommandsInBuffer_withRange(commands, range) }; - } - - fn end_compute(&self, encoder: Self::ComputeEncoder) { - encoder.endEncoding(); - } - - fn reset_commands( - &self, - command_buffer: &Self::CommandBuffer, - commands: &Self::IndirectCommands, - count: usize, - ) { - let blit = command_buffer - .blitCommandEncoder() - .expect("blitCommandEncoder"); - let range = objc2_foundation::NSRange { - location: 0, - length: count, - }; - // SAFETY: the range lies within the buffer's commands. - unsafe { blit.resetCommandsInBuffer_withRange(commands, range) }; - blit.endEncoding(); - } - - fn blit_encoder(&self, command_buffer: &Self::CommandBuffer) -> Self::BlitEncoder { - command_buffer - .blitCommandEncoder() - .expect("blitCommandEncoder") - } - - fn copy_buffer( - &self, - encoder: &mut Self::BlitEncoder, - (from, from_offset): (&Self::Buffer, usize), - (to, to_offset): (&Self::Buffer, usize), - size: usize, - ) { - // SAFETY: both ranges lie in their buffers. - unsafe { - encoder.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size( - from, - from_offset, - to, - to_offset, - size, - ) - }; - } - - fn fill_buffer_in( - &self, - encoder: &mut Self::BlitEncoder, - buffer: &Self::Buffer, - offset: usize, - length: usize, - ) { - encoder.fillBuffer_range_value( - buffer, - objc2_foundation::NSRange { - location: offset, - length, - }, - 0x5a, - ); - } - - fn copy_to_texture( - &self, - encoder: &mut Self::BlitEncoder, - source: &Self::Buffer, - texture: &Self::Texture, - (width, height): (usize, usize), - bytes_per_row: usize, - ) { - // SAFETY: the region lies in the buffer and in the texture (the workload's). - unsafe { - encoder.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin( - source, - 0, - bytes_per_row, - bytes_per_row * height, - MTLSize { width, height, depth: 1 }, - texture, - 0, - 0, - MTLOrigin { x: 0, y: 0, z: 0 }, - ) - }; - } - - fn end_blit(&self, encoder: Self::BlitEncoder) { - encoder.endEncoding(); - } - - fn fill(&self, command_buffer: &Self::CommandBuffer, buffer: &Self::Buffer, length: usize) { - let blit = command_buffer - .blitCommandEncoder() - .expect("blitCommandEncoder"); - blit.fillBuffer_range_value( - buffer, - objc2_foundation::NSRange { - location: 0, - length, - }, - 0x5a, - ); - blit.endEncoding(); - } - - fn upload( - &self, - command_buffer: &Self::CommandBuffer, - source: &Self::Buffer, - textures: &[&Self::Texture], - (width, height): (usize, usize), - bytes_per_row: usize, - ) { - let mut blit = command_buffer - .blitCommandEncoder() - .expect("blitCommandEncoder"); - for texture in textures { - self.copy_to_texture(&mut blit, source, texture, (width, height), bytes_per_row); - } - blit.endEncoding(); - } - - fn commit(&self, command_buffer: &Self::CommandBuffer) { - command_buffer.commit(); - } - - fn wait(&self, command_buffer: &Self::CommandBuffer) { - command_buffer.waitUntilCompleted(); - let status = command_buffer.status(); - assert!( - status == MTLCommandBufferStatus::Completed, - "the command buffer ended {status:?}: {:?}", - command_buffer.error() - ); - } - - fn wait_only(&self, command_buffer: &Self::CommandBuffer) { - command_buffer.waitUntilCompleted(); - } - - fn status(&self, command_buffer: &Self::CommandBuffer) -> u64 { - command_buffer.status().0 as u64 - } - - fn fence(&self) -> Self::Fence { - self.device.newFence().expect("newFence") - } - - fn shared_event(&self) -> Self::SharedEvent { - self.device.newSharedEvent().expect("newSharedEvent") - } - - fn event_value(&self, event: &Self::SharedEvent) -> u64 { - event.signaledValue() - } - - fn set_event_value(&self, event: &Self::SharedEvent, value: u64) { - event.setSignaledValue(value); - } - - fn set_when_scheduled( - &self, - command_buffer: &Self::CommandBuffer, - event: &Self::SharedEvent, - value: u64, - ) { - let event = event.clone(); - let block = RcBlock::new(move |_: NonNull>| { - event.setSignaledValue(value); - }); - // SAFETY: the block is a valid scheduled handler, which Metal copies. - unsafe { command_buffer.addScheduledHandler(RcBlock::as_ptr(&block)) }; - } - - fn listener(&self) -> Self::Listener { - MTLSharedEventListener::new() - } - - fn notify( - &self, - event: &Self::SharedEvent, - listener: &Self::Listener, - value: u64, - block: Box, - ) { - let block = Mutex::new(Some(block)); - let block = RcBlock::new( - move |_: NonNull>, _: u64| { - if let Some(block) = block.lock().unwrap().take() { - block(); - } - }, - ); - // SAFETY: the block is a valid notification block, which Metal copies. - unsafe { event.notifyListener_atValue_block(listener, value, RcBlock::as_ptr(&block)) }; - } - - fn signal_when_scheduled( - &self, - command_buffer: &Self::CommandBuffer, - event: &Self::SharedEvent, - value: u64, - ) { - let event: &ProtocolObject = event; - // SAFETY: `encodeSignalEventScheduled:value:` takes a shared event and a 64-bit value - // (`v@:@Q`) and returns nothing. - let _: () = unsafe { - objc2::msg_send![&**command_buffer, encodeSignalEventScheduled: event, value: value] - }; - } - - fn on_completed( - &self, - command_buffer: &Self::CommandBuffer, - handler: Box, - ) { - let handler = Mutex::new(Some(handler)); - let block = RcBlock::new(move |_: NonNull>| { - if let Some(handler) = handler.lock().unwrap().take() { - handler(); - } - }); - // SAFETY: the block is valid for the call, and Metal copies it before returning; it is - // added before the commit. - unsafe { command_buffer.addCompletedHandler(RcBlock::as_ptr(&block)) }; - } - - fn gpu_seconds(&self, command_buffer: &Self::CommandBuffer) -> Option { - Some(command_buffer.GPUEndTime() - command_buffer.GPUStartTime()) - } - - fn times(&self, command_buffer: &Self::CommandBuffer) -> [f64; 4] { - [ - command_buffer.kernelStartTime(), - command_buffer.kernelEndTime(), - command_buffer.GPUStartTime(), - command_buffer.GPUEndTime(), - ] - } - - fn pool(&self, f: impl FnOnce() -> R) -> R { - autoreleasepool(|_| f()) - } -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/percall.rs b/crates/metal2vulkan-runtime/examples/host_ab/percall.rs deleted file mode 100644 index a5a4c7fa7..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/percall.rs +++ /dev/null @@ -1,1458 +0,0 @@ -//! The per-call cost table (`--only percall`): one group a call, each call timed alone on both -//! sides, with Metal's cost as the budget. -//! -//! A group's window prepares the state its call needs, untimed; makes that one call `inner` -//! times; then drains the state, committing and waiting where the calls encoded work. Three -//! warm windows run first, and every pipeline state, library and texture the groups bind is made -//! before any of them, so no making falls inside a timed window (the `variant_pipelines_made` -//! count a group reports is the proof); and the runtime's device's own checks answered before -//! any workload (`runtime.rs`'s `Runtime::settle_checks`), so none of their work, which the -//! device counts as its own, falls inside one either. -//! -//! Per call a group reports -//! -//! - `_self`: the calling thread's wall time, the cost the caller pays inline; -//! - `_blocked`: how much of that the calling thread was off a CPU, so it waited; -//! - `_others`: our own other threads' CPU time while the calls ran; -//! - `_drain`: the calling thread's wall time in the drain after the calls, where the -//! group has one (its command buffer's commit and wait): what the caller pays later; -//! - `_drain_blocked`: how much of that drain the calling thread was off a CPU, so a -//! drain that costs CPU instead was spent spinning; -//! - `_drain_others`: our other threads' CPU time in that drain; -//! - `_allocs`: the heap allocations a call made on the calling thread; -//! - `_rt_`: the runtime's own counts of what the calls made, where they moved -//! ([`counted`]); none natively, so these rows have no ratio. Every count the runtime keeps is -//! reported where a call moved it, and `_at_call` and `_at_commit` say whether the call paid -//! for it or left it for the commit — including the driver's own makings, which the runtime -//! counts where it calls them (`churn_counts.rs`), so a creation call's driver share is a count -//! and not an inference from the driver floor below the table. -//! -//! The wall times are a median over the windows, and the rest the group's totals over its -//! calls, because the thread and process CPU clocks answer in microseconds. -//! -//! The counts are also the table's **gate**: [`HELD`] holds named calls to what they were -//! measured making ([`HELD_ON_PATH`] a call on a path of its own that inherently makes more), and -//! the run fails where one makes more: after its last group, naming every -//! call that did, so a call over its bound leaves none of the groups after it unmeasured. A count -//! is deterministic, so it holds in CI under any load, where none of the times above can. - -use crate::gpu::{Format, Gpu}; -use crate::workloads::{emit, host_pages, process_cpu, thread_cpu, Scene, Sizes, TARGET_SIDE}; -use std::sync::{Mutex, PoisonError}; -use std::time::{Duration, Instant}; - -/// The windows a group runs before the measured ones. -const WARM: usize = 3; - -/// Whether a count of the side's own ([`Gpu::work_counts`]) belongs in the table: every count -/// of work does, and the accumulators of nanoseconds do not, since a time is not a fact a gate -/// can hold. Every other count the side keeps is reported where a group's calls moved it, so no -/// family of work is left out of a call's row by an allowlist nobody revisits. -fn counted(name: &str) -> bool { - !name.ends_with("_nanos") -} - -/// What each group's call is on the runtime's public API, one entry a group: the group's name, -/// then the methods it calls, `Type::method`. [`group`] fails for a group that is not named here -/// (a driver call of `vkfloor.rs`, whose name starts with `vk_`, is no Metal call and is -/// exempt), and `scripts/api-cost-coverage` reads it to say how much of the public surface the -/// table times and how much is still untimed. -pub const TIMED: [(&str, &str); 61] = [ - ("command_buffer", "CommandQueue::command_buffer"), - ("commit_empty", "CommandBuffer::commit"), - ("commit_one_dispatch", "CommandBuffer::commit"), - ("commit_no_copy_dispatch", "CommandBuffer::commit"), - ("on_completed", "CommandBuffer::add_completed_handler"), - ("status_completed", "CommandBuffer::status"), - ( - "times_completed", - "CommandBuffer::kernel_start_time, CommandBuffer::kernel_end_time, \ - CommandBuffer::gpu_start_time, CommandBuffer::gpu_end_time", - ), - ("wait_completed", "CommandBuffer::wait_until_completed"), - ( - "render_encoder_pass", - "CommandBuffer::render_command_encoder", - ), - ( - "render_encoder_clear", - "CommandBuffer::render_command_encoder", - ), - ( - "render_encoder_load", - "CommandBuffer::render_command_encoder", - ), - ("end_render", "RenderCommandEncoder::end_encoding"), - ("compute_encoder", "CommandBuffer::compute_command_encoder"), - ("end_compute", "ComputeCommandEncoder::end_encoding"), - ("blit_encoder", "CommandBuffer::blit_command_encoder"), - ("end_blit", "BlitCommandEncoder::end_encoding"), - ( - "set_render_pipeline", - "RenderCommandEncoder::set_render_pipeline_state", - ), - ( - "set_vertex_buffer", - "RenderCommandEncoder::set_vertex_buffer", - ), - ( - "set_vertex_buffers_two", - "RenderCommandEncoder::set_vertex_buffers", - ), - ( - "set_vertex_bytes_16", - "RenderCommandEncoder::set_vertex_bytes", - ), - ( - "set_fragment_buffer", - "RenderCommandEncoder::set_fragment_buffer", - ), - ( - "set_fragment_texture", - "RenderCommandEncoder::set_fragment_texture", - ), - ( - "set_fragment_sampler", - "RenderCommandEncoder::set_fragment_sampler_state", - ), - ("set_cull_mode", "RenderCommandEncoder::set_cull_mode"), - ( - "set_depth_stencil", - "RenderCommandEncoder::set_depth_stencil_state", - ), - ("draw_strip", "RenderCommandEncoder::draw_primitives"), - ("draw_strip_in_64", "RenderCommandEncoder::draw_primitives"), - ("draw_triangles", "RenderCommandEncoder::draw_primitives"), - ( - "draw_indexed", - "RenderCommandEncoder::draw_indexed_primitives", - ), - ( - "use_resources_read_1_drawn", - "RenderCommandEncoder::use_resources", - ), - ( - "use_resources_read_256_drawn", - "RenderCommandEncoder::use_resources", - ), - ( - "set_compute_pipeline", - "ComputeCommandEncoder::set_compute_pipeline_state", - ), - ("set_buffer", "ComputeCommandEncoder::set_buffer"), - ("set_texture", "ComputeCommandEncoder::set_texture"), - ("dispatch", "ComputeCommandEncoder::dispatch_threadgroups"), - ( - "use_resources_read_1", - "ComputeCommandEncoder::use_resources", - ), - ( - "use_resources_read_256", - "ComputeCommandEncoder::use_resources", - ), - ( - "use_resource_read_write", - "ComputeCommandEncoder::use_resource", - ), - ("use_heap", "ComputeCommandEncoder::use_heap"), - ("update_fence", "ComputeCommandEncoder::update_fence"), - ("wait_for_fence", "ComputeCommandEncoder::wait_for_fence"), - ( - "copy_buffer_1k", - "BlitCommandEncoder::copy_from_buffer_to_buffer", - ), - ("fill_buffer_256", "BlitCommandEncoder::fill_buffer"), - ( - "copy_buffer_to_texture", - "BlitCommandEncoder::copy_from_buffer_to_texture", - ), - ( - "fill_in_own_encoder", - "CommandBuffer::blit_command_encoder, BlitCommandEncoder::fill_buffer, \ - BlitCommandEncoder::end_encoding", - ), - ("buffer_4k", "Device::new_buffer"), - ("buffer_1m", "Device::new_buffer"), - ("buffer_with_bytes_4k", "Device::new_buffer_with_bytes"), - ("buffer_no_copy_1m", "Device::new_buffer_with_bytes_no_copy"), - ("texture_256_shared", "Device::new_texture"), - ("texture_1024_target", "Device::new_texture"), - ("heap_texture_256", "Heap::new_texture_at_offset"), - ("buffer_texture_256", "Buffer::new_texture"), - ("sampler", "Device::new_sampler_state"), - ("shared_event", "Device::new_shared_event"), - ("fence", "Device::new_fence"), - ("event_value", "SharedEvent::signaled_value"), - ("set_event_value", "SharedEvent::set_signaled_value"), - ("read_buffer_contents_256", "Buffer::contents"), - ("get_bytes_256", "Texture::get_bytes"), - ("replace_region_256", "Texture::replace_region"), -]; - -/// The counts [`counted`] keeps that moved between two readings of the side's own counts, and by -/// how much: none at all on a side that keeps none. -fn moved(from: &[(&'static str, f64)], to: &[(&'static str, f64)]) -> Vec<(&'static str, f64)> { - from.iter() - .filter(|(name, _)| counted(name)) - .filter_map(|(counted, before)| { - let now = to - .iter() - .find(|(name, _)| name == counted) - .map_or(0.0, |(_, count)| *count); - (now > *before).then_some((*counted, now - before)) - }) - .collect() -} - -/// What one window measured: the calls' wall time on the calling thread, that thread's CPU time -/// and the whole process's while they ran, then the same three of the drain after them. -#[derive(Clone, Copy, Default)] -struct Sample { - wall: Duration, - cpu: Duration, - process: Duration, - drain_wall: Duration, - drain_cpu: Duration, - drain_process: Duration, -} - -/// A group's windows, summed. -#[derive(Default)] -struct Totals { - /// Each window's wall time a call, in ns: the call's own cost. - own: Vec, - /// Each window's drain, in ns a call. - drain: Vec, - sums: Sample, -} - -impl Totals { - fn add(&mut self, inner: usize, s: Sample) { - let each = |d: Duration| d.as_nanos() as f64 / inner as f64; - self.own.push(each(s.wall)); - self.drain.push(each(s.drain_wall)); - let sums = &mut self.sums; - sums.wall += s.wall; - sums.cpu += s.cpu; - sums.process += s.process; - sums.drain_wall += s.drain_wall; - sums.drain_cpu += s.drain_cpu; - sums.drain_process += s.drain_process; - } -} - -/// Time one call group: `windows` measured windows, each preparing the call's state, making the -/// call `inner` times, then draining it. Every window runs inside an autorelease pool, as a -/// Metal program's frame does, so nothing of one window is released inside another's timing. -pub fn group( - g: &G, - name: &str, - (inner, windows): (usize, usize), - mut prepare: impl FnMut() -> S, - mut call: impl FnMut(&mut S, usize), - mut drain: impl FnMut(S), -) { - assert!(inner > 0 && windows > 0, "{name}: no calls"); - assert!( - name.starts_with("vk_") || TIMED.iter().any(|(group, _)| *group == name), - "{name}: no entry in TIMED, so the timing census would not count its calls" - ); - let mut totals = Totals::default(); - let mut before = vec![]; - for window in 0..WARM + windows { - if window == WARM { - before = g.work_counts(); - } - let sample = g.pool(|| { - let mut state = prepare(); - let (cpu0, process0) = (thread_cpu(), process_cpu()); - let start = Instant::now(); - for i in 0..inner { - call(&mut state, i); - } - let called = Instant::now(); - let (cpu1, process1) = (thread_cpu(), process_cpu()); - let drained_from = Instant::now(); - drain(state); - let drained = Instant::now(); - let (cpu2, process2) = (thread_cpu(), process_cpu()); - Sample { - wall: called - start, - cpu: cpu1 - cpu0, - process: process1 - process0, - drain_wall: drained - drained_from, - drain_cpu: cpu2 - cpu1, - drain_process: process2 - process1, - } - }); - if window >= WARM { - totals.add(inner, sample); - } - } - let after = g.work_counts(); - let calls = (inner * windows) as f64; - let each = |d: Duration| d.as_nanos() as f64 / calls; - let sums = &totals.sums; - let metric = |what: &str| format!("{name}_{what}"); - emit("percall", &metric("self"), "ns/call", &mut totals.own); - emit( - "percall", - &metric("blocked"), - "ns/call", - &mut [(each(sums.wall) - each(sums.cpu)).max(0.0)], - ); - emit( - "percall", - &metric("others"), - "ns/call", - &mut [(each(sums.process) - each(sums.cpu)).max(0.0)], - ); - emit("percall", &metric("drain"), "ns/call", &mut totals.drain); - emit( - "percall", - &metric("drain_blocked"), - "ns/call", - &mut [(each(sums.drain_wall) - each(sums.drain_cpu)).max(0.0)], - ); - emit( - "percall", - &metric("drain_others"), - "ns/call", - &mut [(each(sums.drain_process) - each(sums.drain_cpu)).max(0.0)], - ); - // One window more, this thread's allocations counted, and the runtime's counts read between - // the calls and the drain as well: what a call made the runtime do at the call, and what it - // left for the commit. - let (made, at_call, at_drain) = g.pool(|| { - let mut state = prepare(); - let opened = g.work_counts(); - let made = crate::allocs::counting(|| { - let before = crate::allocs::this_thread(); - for i in 0..inner { - call(&mut state, i); - } - crate::allocs::this_thread() - before - }); - let called = g.work_counts(); - drain(state); - let drained = g.work_counts(); - (made, moved(&opened, &called), moved(&called, &drained)) - }); - // The counts this group measured, under the names the table prints, so [`HELD`]'s rows for it - // are checked against the same numbers the report shows. - let mut measured: Vec<(String, f64)> = vec![]; - let mut keep = |what: String, value: f64| { - emit( - "percall", - &metric(&what), - if what == "allocs" { - "allocs/call" - } else { - "count/call" - }, - &mut [value], - ); - measured.push((what, value)); - }; - keep("allocs".to_owned(), made as f64 / inner as f64); - for (counted, count) in at_call { - keep(format!("rt_{counted}_at_call"), count / inner as f64); - } - for (counted, count) in at_drain { - keep(format!("rt_{counted}_at_commit"), count / inner as f64); - } - // What the measured windows' calls made the runtime do, per call. - for (which, from) in &before { - if !counted(which) { - continue; - } - let now = after - .iter() - .find(|(counted, _)| counted == which) - .map_or(0.0, |(_, count)| *count); - assert!( - *which != "variant_pipelines_made" || now <= *from, - "{name}: {} pipeline states were made inside its timed windows", - now - from - ); - if now > *from { - keep(format!("rt_{which}"), (now - from) / calls); - } - } - // The side that keeps no counts of its own is Metal's, which has no counterpart for any of - // these, so only ours is held to them. - if !before.is_empty() { - hold(name, &measured); - } -} - -/// What a call may make, per call: the group, the count under the name the table prints -/// (`allocs`, or `rt__at_call`, `rt__at_commit` and `rt_` for the runtime's -/// own counts), and the most a call of it may make. A count a group never moved is not printed, -/// and reads as zero here, so a row of `0.0` holds a call to making none of that work at all. -/// -/// These are the gate on the cost half. A count is the same under any load and on any host, so a -/// regression reads "this call now makes two allocations where it made none" and fails the run, -/// where a 12% change in a time would not. Each row is a fact measured on this M3 Max that the -/// runtime should not quietly lose: an upper bound, so a call that does *less* work passes and the -/// row is then tightened. The bound holds on every device: where a call takes another path there, -/// the row holds that path's count too, and a count the path does not move reads zero. A `Shared` -/// texture's image, for one, is made at the call where the device copies its texels on the host -/// (`texture/host_copy.rs`: the M3 Max), and taken from the parked images the textures of an -/// earlier window left where it copies them on the staging queue (`texture/staging_copy.rs`: -/// NVIDIA's copy engine), which makes no image, binds none and starts none on the host. A call's -/// allocations are the runtime's own on the calling thread, a few more or fewer where its path -/// differs: a heap texture made 12.25 a call under lavapipe, and as many on an RTX 5080, where -/// its image is linear because the device's optimal image takes none of the heap's memory types; -/// on macOS the first lock of each of its mutexes allocates too (std's). A path that inherently -/// makes more of a count is held to its own measure there ([`HELD_ON_PATH`]). -/// -/// A driver making (`rt_vk__this_thread`) is held as the calling thread's: what the call -/// made, and a block of the runtime's memory pool it waited for, which the pool's thread made -/// (`ObjectChurn`'s `_this_thread` counts). A block that thread makes ahead while no call waits -/// for it is no call's making: it waits for a pause in the device's queue uses, at most 50 ms -/// (`memory/ready.rs`), and lands in whichever group's window runs then, where the process's -/// count (`rt_vk_`) shows it. -const HELD: [(&str, &str, f64); 47] = [ - // A draw records exactly one draw command, at the call, and makes no driver object: the cost - // it pays there is planning and recording, which is settled work and nothing a driver - // charges for. - ("draw_strip", "rt_draws_at_call", 1.0), - ("draw_strip", "rt_vk_images_made_this_thread_at_call", 0.0), - ("draw_strip", "rt_vk_buffers_made_this_thread_at_call", 0.0), - ( - "draw_strip", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - ("draw_triangles", "rt_draws_at_call", 1.0), - ("draw_indexed", "rt_recorded_cmd_draw_indexed_at_call", 1.0), - // And it allocates about once in twenty draws (0.049 measured), nothing a draw of its own. - ("draw_strip", "allocs", 0.2), - ("draw_triangles", "allocs", 0.2), - ("draw_indexed", "allocs", 0.2), - // The draw's settling is three lookups that each find what an earlier draw made: a draw that - // starts recording shapes or sets again would show here before it showed in a time. - ("draw_strip", "rt_draw_shapes_made_at_call", 0.0), - ("draw_strip", "rt_sampler_sets_made_at_call", 0.0), - ("draw_strip", "rt_live_tables_uploaded_at_call", 0.0), - // Ending the encoding begins its render pass once, at the call, and makes no driver object. - // Its 24 allocations are the largest counted quantity on the path. - ("end_render", "rt_render_passes_begun_at_call", 1.0), - ("end_render", "rt_vk_images_made_this_thread_at_call", 0.0), - ("end_render", "allocs", 24.0), - ("end_compute", "allocs", 7.0), - ("end_blit", "allocs", 7.0), - // A dispatch records one dispatch command, at the call (6.13 allocations measured): its uses - // over the last dispatch's storage, and no group counts outside a predication unit. - ("dispatch", "rt_dispatches_at_call", 1.0), - ("dispatch", "allocs", 6.2), - // A heap texture's image takes its storage from the heap: one image and one binding, and no - // allocation of memory of its own. - ( - "heap_texture_256", - "rt_vk_images_made_this_thread_at_call", - 1.0, - ), - ( - "heap_texture_256", - "rt_vk_image_bindings_this_thread_at_call", - 1.0, - ), - ( - "heap_texture_256", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - ("heap_texture_256", "allocs", 17.25), - // A Shared texture likewise, and it starts its image on the host once; or it takes one parked - // image, made and bound before, where the device stages its copies. - ( - "texture_256_shared", - "rt_vk_images_made_this_thread_at_call", - 1.0, - ), - ("texture_256_shared", "rt_images_recycled_at_call", 1.0), - ( - "texture_256_shared", - "rt_vk_image_bindings_this_thread_at_call", - 1.0, - ), - ( - "texture_256_shared", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - ( - "texture_256_shared", - "rt_images_started_on_the_host_at_call", - 1.0, - ), - ("texture_256_shared", "allocs", 32.0), - // A render target of a shape the runtime has seen takes a parked image: it makes no image at - // all, which is why it costs what Metal's does. Losing the recycler here would cost 20 us a - // call and this row is what would say so. - ( - "texture_1024_target", - "rt_vk_images_made_this_thread_at_call", - 0.0, - ), - ( - "texture_1024_target", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - // A texture over a buffer's bytes makes its image at the call, bound in the buffer's memory: - // one image and one binding, no memory of its own, and no view at the call. - ( - "buffer_texture_256", - "rt_vk_images_made_this_thread_at_call", - 1.0, - ), - ( - "buffer_texture_256", - "rt_vk_image_bindings_this_thread_at_call", - 1.0, - ), - ( - "buffer_texture_256", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - ( - "buffer_texture_256", - "rt_vk_image_views_made_this_thread_at_call", - 0.0, - ), - // A buffer comes out of the runtime's memory pool: no `vkCreateBuffer`, no `vkAllocateMemory`. - ("buffer_4k", "rt_vk_buffers_made_this_thread_at_call", 0.0), - ( - "buffer_4k", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - ("buffer_1m", "rt_vk_buffers_made_this_thread_at_call", 0.0), - ( - "buffer_1m", - "rt_vk_memory_allocations_this_thread_at_call", - 0.0, - ), - // A no-copy buffer imports its pages once: one buffer, one import, one binding. A walk of the - // memory types that tried several would read as more than one allocation here. - ( - "buffer_no_copy_1m", - "rt_vk_buffers_made_this_thread_at_call", - 1.0, - ), - ( - "buffer_no_copy_1m", - "rt_vk_memory_allocations_this_thread_at_call", - 1.0, - ), - ( - "buffer_no_copy_1m", - "rt_vk_buffer_bindings_this_thread_at_call", - 1.0, - ), - // Residency is our own bookkeeping: no driver call, and no allocation a resource (16 for 256 - // of them). - ( - "use_resources_read_256", - "rt_vk_buffers_made_this_thread_at_call", - 0.0, - ), - ("use_resources_read_256", "allocs", 16.0), - // One Metal command buffer carrying one dispatch is submitted as two of Vulkan's. - ( - "commit_one_dispatch", - "rt_vk_command_buffers_submitted", - 2.0, - ), - // Its commit makes four allocations, and five more where its buffers lie over host pages; - // counting the host imports they lie in makes none (`Buffer::distinct_host_imports`). - ("commit_one_dispatch", "allocs", 4.0), - ("commit_no_copy_dispatch", "allocs", 9.0), -]; - -/// What a call may make on a path of its own that inherently makes more of a count than -/// [`HELD`]'s row of it holds on every other path, per call: the group, the count whose moving -/// marks the path (as [`HELD`] names its counts), the count held, and the most a call of that path -/// may make. Where the call moved its mark, the row holds the count in place of [`HELD`]'s row of -/// it; where it did not, [`HELD`]'s row holds it. -const HELD_ON_PATH: [(&str, &str, &str, f64); 1] = [ - // A heap texture the device holds as a shadow of Metal's tiles (`texture/heap_tiled.rs`, - // counted as `heap_textures_tiled`): where its image does not fit Metal's answer, which the - // program places it by, Metal's bytes stay in the heap and the image lies in memory of its - // own. On the Radeon 780M (RADV PHOENIX) the group's optimal 256x256 BGRA8 image takes 262144 - // bytes at an alignment of 65536, where Metal answers 262144 at 128. There it makes 28.25 - // allocations a call: 11.25 for its plan and its texture object, and 17 for the route: its - // moves' planes and levels (2), the image (1), one staging buffer for the texture's bytes, - // the image's elements and the kernel's shapes (3) and its copies back (1), the kernel's two - // descriptor sets from a pool of their own (5), its copies into the image (1), and the - // shadow's state (4). - ( - "heap_texture_256", - "rt_heap_textures_tiled_at_call", - "allocs", - 28.25, - ), -]; - -/// The calls the groups run so far made more work than [`HELD`] or [`HELD_ON_PATH`] allows them, -/// as [`hold`] words each; [`percall`] fails on them all after its last group. -static BREACHED: Mutex> = Mutex::new(Vec::new()); - -/// Note, for [`percall`] to fail on, where a group's call made more work than [`HELD`] allows it, -/// or [`HELD_ON_PATH`] on a path whose mark it moved, naming the call, the count, what it made and -/// what it is held to. A count the group never moved reads zero: the call made none of it on this -/// device, where it may take another path than on the M3 Max ([`HELD`]). -fn hold(name: &str, measured: &[(String, f64)]) { - let made = |what: &str| { - let made = measured.iter().find(|(counted, _)| counted == what); - made.map_or(0.0, |(_, value)| *value) - }; - // The rows of the paths this group's call took. - let taken = (HELD_ON_PATH.iter()) - .filter(|&&(group, mark, ..)| group == name && made(mark) > 0.0) - .map(|&(_, mark, what, most)| (mark, what, most)); - let mut breached = vec![]; - for (group, what, most) in HELD { - let on_path = taken.clone().any(|(_, counted, _)| counted == what); - if group == name && !on_path && made(what) > most { - breached.push(format!( - "{name}: {what} is {} a call, where it is held to at most {most}", - made(what) - )); - } - } - for (mark, what, most) in taken { - if made(what) > most { - breached.push(format!( - "{name}: {what} is {} a call on the path {mark} marks, where it is held to at \ - most {most}", - made(what) - )); - } - } - let mut noted = BREACHED.lock().unwrap_or_else(PoisonError::into_inner); - noted.extend(breached); -} - -/// Fail where a row of [`HELD`] or [`HELD_ON_PATH`] could hold nothing on any device: its group -/// has no entry in [`TIMED`], or a count it names is none the table prints, `allocs` or one of the -/// side's own counts `kept` ([`Gpu::work_counts`], every one whatever its value) under `rt_`, with -/// `_at_call` or `_at_commit` after it or nothing. A count that moved nowhere is not printed and -/// reads zero ([`hold`]), so a misspelled one would pass whatever the call made, and a misspelled -/// mark would hold no call to its path: checked by name, before any group runs, on every device, -/// whichever path its calls take. -fn check_held(kept: &[(&'static str, f64)]) { - let keeps = |count: &str| counted(count) && kept.iter().any(|(name, _)| *name == count); - let printed = |what: &str| { - what == "allocs" - || what.strip_prefix("rt_").is_some_and(|rest| { - keeps(rest) - || [ - rest.strip_suffix("_at_call"), - rest.strip_suffix("_at_commit"), - ] - .into_iter() - .flatten() - .any(keeps) - }) - }; - let check = |group: &str, what: &str| { - assert!( - TIMED.iter().any(|(timed, _)| *timed == group), - "HELD holds {group}, a group TIMED does not name" - ); - assert!( - printed(what), - "{group}: HELD names {what}, which names no count the side keeps, so the row holds \ - nothing" - ); - }; - for (group, what, _) in HELD { - check(group, what); - } - for (group, mark, what, _) in HELD_ON_PATH { - check(group, mark); - check(group, what); - } -} - -/// How many bytes of host pages the no-copy buffers of one window lie over, and how many such -/// buffers a window makes: one megabyte each, the same pages every window, as a guest's buffers -/// lie in its memory. -const NO_COPY_EACH: usize = 1 << 20; -const NO_COPY_BUFFERS: usize = 8; - -/// The buffers a residency group makes resident, 256 bytes each. -const RESIDENT: usize = 256; - -/// The side of the textures the creation and upload groups make. -const SMALL_SIDE: usize = 256; - -/// The bytes a small texture's level holds, as `BGRA8Unorm` of unpadded rows. -const SMALL_BYTES: usize = SMALL_SIDE * SMALL_SIDE * 4; - -/// The textures a placement heap holds in the heap-texture and `useHeap` groups. -const HEAP_TEXTURES: usize = 16; - -/// What the groups bind, draw and copy: made once, before any window. -struct Objects { - /// A render pass of the scene's target, cleared and stored, made once for many encoders. - pass: G::Pass, - /// `calls_vertex` with the texture-reading and the buffer-reading fragment function. - textured: G::RenderPipeline, - buffered: G::RenderPipeline, - /// `quad_vertex` + `textured_fragment` into the depth pass's attachments. - depth_state: G::RenderPipeline, - depth: G::Texture, - /// A depth compare with writes, and one without. - depth_stencils: [G::DepthStencil; 2], - /// The vertex buffers `calls_vertex` reads, and the fragment buffer `calls_buffer_fragment` - /// does. - positions: G::Buffer, - colours: G::Buffer, - uniforms: G::Buffer, - /// Sixteen 16-bit indices of a triangle. - indices: G::Buffer, - /// A compute encoder's bound buffers, and a blit's source and destination. - input: G::Buffer, - output: G::Buffer, - from: G::Buffer, - to: G::Buffer, - /// A small texture's bytes, for the upload and `replaceRegion` groups, and a texture of that - /// size to upload into and read back. - texels: Vec, - small: G::Buffer, - small_texture: G::Texture, - /// The buffers the residency groups make resident. - resident: Vec, - /// A placement heap of `Shared` storage, whose hazards nothing tracks: what `useHeap` is - /// for, and where the heap-texture group places its textures. - heap: G::Heap, - /// A shared event, a fence, and the pages the no-copy buffers lie over. - event: G::SharedEvent, - fence: G::Fence, - pages: *mut u8, - /// A command buffer of one fill, committed and completed, whose status, times and wait the - /// read groups take. - done: G::CommandBuffer, -} - -impl Objects { - fn new(g: &G, s: &Scene, library: &G::Library) -> Objects { - let state = - |fragment| g.render_pipeline(library, "calls_vertex", fragment, Format::Bgra8, false); - let floats = - |values: &[f32]| -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() }; - // A strip of four corners of a small square, then nothing, as the calls workload's. - let positions: Vec = (0..256) - .flat_map(|v| match v { - 0..4 => [ - -0.1 + 0.2 * (v & 1) as f32, - -0.1 + 0.2 * (v >> 1) as f32, - 0.0, - 1.0, - ], - _ => [0.0; 4], - }) - .collect(); - let texels: Vec = (0..SMALL_BYTES).map(|i| (i % 251) as u8).collect(); - let done = g.command_buffer(); - g.fill(&done, &s.fill, 256); - g.commit(&done); - g.wait(&done); - Objects { - pass: g.pass(&s.target), - textured: state("calls_texture_fragment"), - buffered: state("calls_buffer_fragment"), - depth_state: g.depth_pipeline(library, "quad_vertex", "textured_fragment", false), - depth: g.texture(Format::Depth32Float, TARGET_SIDE, TARGET_SIDE, true), - depth_stencils: [g.depth_stencil(true), g.depth_stencil(false)], - positions: g.buffer_with(&floats(&positions)), - colours: g.buffer_with(&floats(&[0.5f32, 0.25, 0.75, 1.0].repeat(256))), - uniforms: g.buffer_with(&floats(&[0.25f32, 0.5, 0.75, 1.0].repeat(4096))), - indices: g.buffer_with(&(0..16u16).flat_map(u16::to_le_bytes).collect::>()), - input: g.buffer_with(&vec![1u8; 1 << 16]), - output: g.buffer(1 << 16), - from: g.buffer_with(&vec![0x3cu8; 1 << 18]), - to: g.buffer(1 << 18), - small: g.buffer_with(&texels), - small_texture: g.texture(Format::Bgra8, SMALL_SIDE, SMALL_SIDE, false), - texels, - resident: (0..RESIDENT).map(|_| g.buffer(256)).collect(), - heap: g.heap(HEAP_TEXTURES * SMALL_BYTES * 2), - event: g.shared_event(), - fence: g.fence(), - // SAFETY: the pages outlive every buffer made over them; nothing unmaps them. - pages: unsafe { host_pages(NO_COPY_BUFFERS * NO_COPY_EACH) }, - done, - } - } -} - -/// The per-call table: every group, in the order a frame makes its calls. -pub fn percall(g: &G, s: &Scene, library: &G::Library, sizes: &Sizes) { - let o = Objects::new(g, s, library); - let w = sizes.timed; - // A group whose window makes one call, because a second call of it would not pay what the - // first did, runs more windows: its samples are its windows, and the host clock this Mac - // counts steps in 41.67 ns, so a call of a few tens of nanoseconds needs many of them. - let lone = w * 6; - let made_before = g.work_counts(); - // The side that keeps no counts of its own is Metal's, which [`HELD`] does not hold. - if !made_before.is_empty() { - check_held(&made_before); - } - - // The command buffer: made, committed empty, committed with one encoder's work, and the - // status, times and completed wait a frame's end reads. - group( - g, - "command_buffer", - (32, w), - || Vec::with_capacity(32), - |held: &mut Vec, _| held.push(g.command_buffer()), - drop, - ); - group( - g, - "commit_empty", - (16, w), - || (0..16).map(|_| g.command_buffer()).collect::>(), - |held: &mut Vec, i| g.commit(&held[i]), - |held| held.iter().for_each(|cb| g.wait(cb)), - ); - group( - g, - "commit_one_dispatch", - (16, w), - || { - (0..16) - .map(|_| { - let cb = g.command_buffer(); - let mut e = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - g.set_buffer(&mut e, &o.output, 0, 0); - g.set_buffer(&mut e, &o.input, 0, 1); - g.dispatch(&mut e, 1, 64); - g.end_compute(e); - cb - }) - .collect::>() - }, - |held: &mut Vec, i| g.commit(&held[i]), - |held| held.iter().for_each(|cb| g.wait(cb)), - ); - // And one whose dispatch binds two no-copy buffers, whose host imports the commit counts - // (`WorkCounts::host_imports_used`): made in its window over the no-copy pages and gone with - // it, so no other group's calls meet live buffers over host pages. - group( - g, - "commit_no_copy_dispatch", - (16, w), - || { - // SAFETY: the pages are page-aligned read-write memory of this many bytes, and they - // outlive every buffer made over them (`Objects::pages`). - let buffers: Vec = (0..2) - .map(|i| unsafe { g.buffer_no_copy(o.pages.add(i * NO_COPY_EACH), NO_COPY_EACH) }) - .collect(); - let held = (0..16) - .map(|_| { - let cb = g.command_buffer(); - let mut e = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - g.set_buffer(&mut e, &buffers[0], 0, 0); - g.set_buffer(&mut e, &buffers[1], 0, 1); - g.dispatch(&mut e, 1, 64); - g.end_compute(e); - cb - }) - .collect::>(); - (buffers, held) - }, - |(_, held): &mut (Vec, Vec), i| g.commit(&held[i]), - |(buffers, held)| { - held.iter().for_each(|cb| g.wait(cb)); - drop((held, buffers)); - }, - ); - group( - g, - "on_completed", - (16, w), - || (0..16).map(|_| g.command_buffer()).collect::>(), - |held: &mut Vec, i| g.on_completed(&held[i], Box::new(|| {})), - |held| { - held.iter().for_each(|cb| g.commit(cb)); - held.iter().for_each(|cb| g.wait(cb)); - }, - ); - assert_eq!(g.status(&o.done), 4, "the read groups' command buffer"); - group( - g, - "status_completed", - (256, w), - || (), - |_, _| assert_eq!(std::hint::black_box(g.status(&o.done)), 4), - drop, - ); - group( - g, - "times_completed", - (256, w), - || (), - |_, _| { - std::hint::black_box(g.times(&o.done)); - }, - drop, - ); - group( - g, - "wait_completed", - (256, w), - || (), - |_, _| g.wait_only(&o.done), - drop, - ); - - // The encoders: opened and ended. A window opens or ends one encoder, so neither call pays - // for the other, and the command buffer the window built is committed and waited in its - // drain, so the work our threads do for it lands in the drain's columns. - group( - g, - "render_encoder_pass", - (1, lone), - || g.command_buffer(), - |cb: &mut G::CommandBuffer, _| { - let e = g.pass_encoder(cb, &o.pass); - g.end_render(e); - }, - |cb| { - g.commit(&cb); - g.wait(&cb); - }, - ); - for (name, clear) in [ - ("render_encoder_clear", true), - ("render_encoder_load", false), - ] { - group( - g, - name, - (1, lone), - || g.command_buffer(), - |cb: &mut G::CommandBuffer, _| { - let e = g.render_encoder(cb, &s.target, clear); - g.end_render(e); - }, - |cb| { - g.commit(&cb); - g.wait(&cb); - }, - ); - } - group( - g, - "end_render", - (1, lone), - || { - let cb = g.command_buffer(); - let e = g.pass_encoder(&cb, &o.pass); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), _| { - g.end_render(state.1.take().expect("the window's encoder")) - }, - |(cb, _)| { - g.commit(&cb); - g.wait(&cb); - }, - ); - group( - g, - "compute_encoder", - (1, lone), - || g.command_buffer(), - |cb: &mut G::CommandBuffer, _| { - let e = g.compute_encoder(cb); - g.end_compute(e); - }, - |cb| { - g.commit(&cb); - g.wait(&cb); - }, - ); - group( - g, - "end_compute", - (1, lone), - || { - let cb = g.command_buffer(); - let mut e = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - g.set_buffer(&mut e, &o.output, 0, 0); - g.set_buffer(&mut e, &o.input, 0, 1); - g.dispatch(&mut e, 1, 64); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), _| { - g.end_compute(state.1.take().expect("the window's encoder")) - }, - |(cb, _)| { - g.commit(&cb); - g.wait(&cb); - }, - ); - group( - g, - "blit_encoder", - (1, lone), - || g.command_buffer(), - |cb: &mut G::CommandBuffer, _| { - let e = g.blit_encoder(cb); - g.end_blit(e); - }, - |cb| { - g.commit(&cb); - g.wait(&cb); - }, - ); - group( - g, - "end_blit", - (1, lone), - || { - let cb = g.command_buffer(); - let mut e = g.blit_encoder(&cb); - g.copy_buffer(&mut e, (&o.from, 0), (&o.to, 0), 1024); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), _| { - g.end_blit(state.1.take().expect("the window's encoder")) - }, - |(cb, _)| { - g.commit(&cb); - g.wait(&cb); - }, - ); - - // The state a draw binds. Each window's encoder is committed and waited, so the binds' later - // cost shows in the drain. - let render = |name: &str, binds: usize, bind: &dyn Fn(&mut G::RenderEncoder, usize)| { - group( - g, - name, - (binds, w), - || { - let cb = g.command_buffer(); - let mut e = g.pass_encoder(&cb, &o.pass); - g.set_render_pipeline(&mut e, &o.textured); - g.set_vertex_buffers(&mut e, &[&o.positions, &o.colours], &[0, 0], 0); - g.set_fragment_texture(&mut e, &s.textures[0], 0); - g.set_fragment_sampler(&mut e, &s.sampler, 0); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), i| { - bind(state.1.as_mut().expect("the window's encoder"), i) - }, - |(cb, e)| { - g.end_render(e.expect("the window's encoder")); - g.commit(&cb); - g.wait(&cb); - }, - ); - }; - render("set_render_pipeline", 256, &|e, i| { - g.set_render_pipeline(e, [&o.textured, &o.buffered][i % 2]) - }); - render("set_vertex_buffer", 256, &|e, i| { - g.set_vertex_buffer(e, &o.positions, (i % 64) * 16, 0) - }); - render("set_vertex_buffers_two", 256, &|e, i| { - g.set_vertex_buffers(e, &[&o.positions, &o.colours], &[0, (i % 64) * 16], 0) - }); - const SIXTEEN: [u8; 16] = [0x3c; 16]; - render("set_vertex_bytes_16", 256, &|e, _| { - g.set_vertex_bytes(e, &SIXTEEN, 2) - }); - render("set_fragment_buffer", 256, &|e, i| { - g.set_fragment_buffer(e, &o.uniforms, (i % 256) * 256, 0) - }); - render("set_fragment_texture", 256, &|e, i| { - g.set_fragment_texture(e, &s.textures[i % s.textures.len()], 0) - }); - render("set_fragment_sampler", 256, &|e, _| { - g.set_fragment_sampler(e, &s.sampler, 0) - }); - render("set_cull_mode", 256, &|e, i| g.set_cull_back(e, i % 2 == 0)); - let resident: Vec<&G::Buffer> = o.resident.iter().collect(); - render("use_resources_read_256_drawn", 1, &|e, _| { - g.use_buffers_drawn(e, &resident) - }); - render("use_resources_read_1_drawn", 1, &|e, _| { - g.use_buffers_drawn(e, &[&o.resident[0]]) - }); - - // The draws, each of a strip of four vertices, and the state they draw under set once. The - // short encoder's draws cost what the long one's do, or the cost is not a call's but grows - // with the encoder's length. - render("draw_strip", 512, &|e, _| g.draw_strip(e, 4)); - render("draw_strip_in_64", 64, &|e, _| g.draw_strip(e, 4)); - render("draw_triangles", 512, &|e, _| g.draw_triangles(e, 0, 3)); - render("draw_indexed", 512, &|e, _| { - g.draw_indexed(e, 3, &o.indices) - }); - - // A depth pass: the depth-stencil state, which no other group binds. - group( - g, - "set_depth_stencil", - (256, w), - || { - let cb = g.command_buffer(); - let mut e = g.depth_render_encoder(&cb, &s.target, &o.depth); - g.set_render_pipeline(&mut e, &o.depth_state); - g.set_vertex_buffer(&mut e, &s.rects[0], 0, 0); - g.set_fragment_texture(&mut e, &s.textures[0], 0); - g.set_fragment_sampler(&mut e, &s.sampler, 0); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), i| { - g.set_depth_stencil( - state.1.as_mut().expect("the window's encoder"), - &o.depth_stencils[i % 2], - ) - }, - |(cb, e)| { - g.end_render(e.expect("the window's encoder")); - g.commit(&cb); - g.wait(&cb); - }, - ); - - // The compute encoder's calls. - let compute = |name: &str, calls: usize, call: &dyn Fn(&mut G::ComputeEncoder, usize)| { - group( - g, - name, - (calls, w), - || { - let cb = g.command_buffer(); - let mut e = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - g.set_buffer(&mut e, &o.output, 0, 0); - g.set_buffer(&mut e, &o.input, 0, 1); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), i| { - call(state.1.as_mut().expect("the window's encoder"), i) - }, - |(cb, e)| { - g.end_compute(e.expect("the window's encoder")); - g.commit(&cb); - g.wait(&cb); - }, - ); - }; - compute("set_compute_pipeline", 256, &|e, i| { - g.set_compute_pipeline(e, &s.tiny[i % 2]) - }); - compute("set_buffer", 256, &|e, i| { - g.set_buffer(e, &o.output, (i % 64) * 256, 0) - }); - compute("set_texture", 256, &|e, i| { - g.set_texture(e, &s.textures[i % s.textures.len()], 0) - }); - compute("dispatch", 256, &|e, _| g.dispatch(e, 1, 64)); - compute("use_resources_read_256", 1, &|e, _| { - g.use_buffers_read(e, &resident) - }); - compute("use_resources_read_1", 1, &|e, _| { - g.use_buffers_read(e, &[&o.resident[0]]) - }); - compute("use_resource_read_write", 1, &|e, _| { - g.use_buffer(e, &o.resident[0]) - }); - compute("use_heap", 1, &|e, _| g.use_heap(e, &o.heap)); - compute("update_fence", 1, &|e, _| g.update_fence(e, &o.fence)); - // The fence this encoder waits for was updated by the encoder before it in the same command - // buffer, as Metal's fences are used, so nothing waits for an update that never comes. - group( - g, - "wait_for_fence", - (1, lone), - || { - let cb = g.command_buffer(); - let mut first = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut first, &s.tiny[0]); - g.set_buffer(&mut first, &o.output, 0, 0); - g.set_buffer(&mut first, &o.input, 0, 1); - g.dispatch(&mut first, 1, 64); - g.update_fence(&mut first, &o.fence); - g.end_compute(first); - let mut e = g.compute_encoder(&cb); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - g.set_buffer(&mut e, &o.output, 0, 0); - g.set_buffer(&mut e, &o.input, 0, 1); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), _| { - g.wait_for_fence(state.1.as_mut().expect("the window's encoder"), &o.fence) - }, - |(cb, e)| { - let mut e = e.expect("the window's encoder"); - g.dispatch(&mut e, 1, 64); - g.end_compute(e); - g.commit(&cb); - g.wait(&cb); - }, - ); - - // The blit encoder's calls, and the whole blit encoder one fill takes. - let blit = |name: &str, calls: usize, call: &dyn Fn(&mut G::BlitEncoder, usize)| { - group( - g, - name, - (calls, w), - || { - let cb = g.command_buffer(); - let e = g.blit_encoder(&cb); - (cb, Some(e)) - }, - |state: &mut (G::CommandBuffer, Option), i| { - call(state.1.as_mut().expect("the window's encoder"), i) - }, - |(cb, e)| { - g.end_blit(e.expect("the window's encoder")); - g.commit(&cb); - g.wait(&cb); - }, - ); - }; - blit("copy_buffer_1k", 256, &|e, i| { - let at = (i % 256) * 1024; - g.copy_buffer(e, (&o.from, at), (&o.to, at), 1024) - }); - blit("fill_buffer_256", 256, &|e, i| { - g.fill_buffer_in(e, &o.to, (i % 256) * 1024, 256) - }); - blit("copy_buffer_to_texture", 16, &|e, _| { - g.copy_to_texture( - e, - &o.small, - &o.small_texture, - (SMALL_SIDE, SMALL_SIDE), - SMALL_SIDE * 4, - ) - }); - group( - g, - "fill_in_own_encoder", - (16, w), - || g.command_buffer(), - |cb: &mut G::CommandBuffer, _| g.fill(cb, &o.to, 256), - |cb| { - g.commit(&cb); - g.wait(&cb); - }, - ); - - // The objects a frame makes and drops: each window's are released before the next window's, - // so no group runs in memory the one before it filled. - group( - g, - "buffer_4k", - (64, w), - || Vec::with_capacity(64), - |held: &mut Vec, _| held.push(g.buffer(4096)), - drop, - ); - group( - g, - "buffer_1m", - (16, w), - || Vec::with_capacity(16), - |held: &mut Vec, _| held.push(g.buffer(1 << 20)), - drop, - ); - group( - g, - "buffer_with_bytes_4k", - (64, w), - || Vec::with_capacity(64), - |held: &mut Vec, _| held.push(g.buffer_with(&o.texels[..4096])), - drop, - ); - group( - g, - "buffer_no_copy_1m", - (NO_COPY_BUFFERS, w), - || Vec::with_capacity(NO_COPY_BUFFERS), - |held: &mut Vec, i| { - // SAFETY: the pages are page-aligned read-write memory of this many bytes, and they - // outlive every buffer made over them (`Objects::pages`). - held.push(unsafe { g.buffer_no_copy(o.pages.add(i * NO_COPY_EACH), NO_COPY_EACH) }) - }, - drop, - ); - group( - g, - "texture_256_shared", - (32, w), - || Vec::with_capacity(32), - |held: &mut Vec, _| { - held.push(g.texture(Format::Bgra8, SMALL_SIDE, SMALL_SIDE, false)) - }, - drop, - ); - group( - g, - "texture_1024_target", - (8, w), - || Vec::with_capacity(8), - |held: &mut Vec, _| held.push(g.texture(Format::Bgra8, 1024, 1024, true)), - drop, - ); - group( - g, - "heap_texture_256", - (HEAP_TEXTURES, w), - || Vec::with_capacity(HEAP_TEXTURES), - |held: &mut Vec, i| { - held.push(g.heap_texture(&o.heap, SMALL_SIDE, SMALL_SIDE, i * SMALL_BYTES)) - }, - drop, - ); - group( - g, - "buffer_texture_256", - (16, w), - || Vec::with_capacity(16), - |held: &mut Vec, _| { - held.push(g.buffer_texture(&o.small, (SMALL_SIDE, SMALL_SIDE), 0, SMALL_SIDE * 4)) - }, - drop, - ); - group( - g, - "sampler", - (32, w), - || Vec::with_capacity(32), - |held: &mut Vec, i| held.push(g.sampler(i % 2 == 0)), - drop, - ); - group( - g, - "shared_event", - (16, w), - || Vec::with_capacity(16), - |held: &mut Vec, _| held.push(g.shared_event()), - drop, - ); - group( - g, - "fence", - (16, w), - || Vec::with_capacity(16), - |held: &mut Vec, _| held.push(g.fence()), - drop, - ); - group( - g, - "event_value", - (256, w), - || (), - |_, _| { - std::hint::black_box(g.event_value(&o.event)); - }, - drop, - ); - let next_value = std::cell::Cell::new(1u64); - group( - g, - "set_event_value", - (256, w), - || (), - |_, _| { - let value = next_value.get(); - next_value.set(value + 1); - g.set_event_value(&o.event, value) - }, - drop, - ); - - // The bytes a frame reads back and writes in, with no GPU work writing them: Metal's - // `getBytes` and `contents` wait for nothing, and nor may ours. - group( - g, - "read_buffer_contents_256", - (256, w), - || vec![0u8; 256], - |bytes: &mut Vec, _| g.read_buffer(&o.input, bytes), - drop, - ); - group( - g, - "get_bytes_256", - (4, w), - || vec![0u8; SMALL_BYTES], - |bytes: &mut Vec, _| { - g.get_bytes( - &o.small_texture, - (SMALL_SIDE, SMALL_SIDE), - bytes, - SMALL_SIDE * 4, - ) - }, - drop, - ); - group( - g, - "replace_region_256", - (4, w), - || (), - |_, _| { - g.replace_region( - &o.small_texture, - (SMALL_SIDE, SMALL_SIDE), - &o.texels, - SMALL_SIDE * 4, - ) - }, - drop, - ); - - // The driver's own cost under the calls above, where the side has one (`vkfloor.rs`). - // SAFETY: the pages are this process's, eight megabytes of them, and they outlive the call. - unsafe { g.driver_floor(w, o.pages) }; - - // Nothing above may have made a pipeline: the groups bind states made before them, and a - // making is pipeline-creation time, which has its own ceiling and no place in a call's cost. - let made_after = g.work_counts(); - for (counted, before) in &made_before { - if *counted != "variant_pipelines_made" { - continue; - } - let now = made_after - .iter() - .find(|(name, _)| name == counted) - .map_or(0.0, |(_, count)| *count); - emit( - "percall", - "meta_pipelines_made", - "count", - &mut [now - before], - ); - } - // Every group ran, measured whatever an earlier one made: the gate's verdict on them all. - let breached = BREACHED.lock().unwrap_or_else(PoisonError::into_inner); - assert!( - breached.is_empty(), - "{} of the gate's checks failed:\n{}", - breached.len(), - breached.join("\n") - ); -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs deleted file mode 100644 index cd82288ec..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ /dev/null @@ -1,2292 +0,0 @@ -//! The runtime's side: Metal's calls on `metal2vulkan_runtime`, on the Vulkan device its loader -//! finds (MoltenVK on a Mac). The device is opened as the consumer opens it (reims-vgpu's -//! `device_options`): GPU times from the host's clock, the exact completion and uncompressed heap -//! textures, the rest of the policy at its defaults, the shader cache in a directory of the -//! bench's own. It is then held until the device's own checks answered -//! ([`Runtime::settle_checks`]), as a consumer's device that reads their verdicts from its cache's -//! records knows them as it is made. - -use crate::gpu::{Format, Gpu}; -use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::device::{CompletionPolicy, HeapCompressionPolicy}; -use metal2vulkan::metal::state::DepthStencilDescriptor; -use metal2vulkan::metal::{ - BlendFactor, CompareFunction, CullMode, DispatchType, IndexType, IndirectCommandType, - PixelFormat, PrimitiveType, ResourceUsage, SamplerMinMagFilter, TextureUsage, Winding, -}; -use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, -}; -use metal2vulkan_runtime as rt; -use std::path::Path; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::{Duration, Instant}; - -/// The degradation notices the runtime's device announced. -pub static NOTICES: AtomicU64 = AtomicU64::new(0); - -/// The other messages the runtime's device's sink heard. -pub static MESSAGES: AtomicU64 = AtomicU64::new(0); - -/// How long [`Runtime::settle_checks`] waits for each of the device's checks to answer. -const SETTLE: Duration = Duration::from_secs(30); - -pub struct Runtime { - device: rt::Device, - queue: rt::CommandQueue, -} - -impl Runtime { - /// Open the device with its shader cache in `cache`, announcing the kinds of `announce_each` - /// at every occurrence, its notices counted ([`NOTICES`]) as a consumer's sink hears them, - /// and its other messages ([`MESSAGES`]), the sink hearing those of `least` severity and above. - pub fn open( - cache: &Path, - announce_each: &[rt::Degradation], - least: rt::MessageSeverity, - ) -> Runtime { - let mut options = rt::DeviceOptions::default(); - options.announce_each = announce_each.iter().copied().collect(); - let sink = rt::MessageSink::new(|message| { - let count = match message.degradation { - Some(_) => &NOTICES, - None => &MESSAGES, - }; - count.fetch_add(1, Ordering::Relaxed); - }); - options.messages = Some(sink.with_least_severity(least)); - options.gpu_times_from_host = true; - options.policy.completion = CompletionPolicy::Exact; - options.policy.heap_compression = HeapCompressionPolicy::Uncompressed; - options.shader_cache = rt::ShaderCacheOptions::in_directory(cache); - let device = rt::Device::system_default_with(&options).expect("open the runtime's device"); - let queue = device.new_command_queue().expect("new_command_queue"); - Runtime { device, queue } - } - - /// Wait until the device's own checks answered: of textures over host pages in place, of its - /// submissions and of its queue switch. Each runs once per driver on a thread of its own, its - /// verdicts kept in the shader cache's records, and the bench's cache is a new directory of - /// each run's unless `--cache` names one, so each would else run beside the workloads: its - /// work, which the device counts as its own, in whichever call's window it fell (the in-place - /// check, which the first texture over a buffer in exported memory starts, makes and binds - /// its images on its thread for as long as it runs), and the calls before its verdicts taking - /// another path than those after. A consumer's device that read the verdicts from its cache's - /// records runs none of them, and so is the device every workload is measured on. How long - /// they took is reported apart from the device's opening (`meta device_checks`, ms); a check - /// that did not answer within [`SETTLE`] is named on stderr, and the run goes on. - pub fn settle_checks(&self) { - let started = Instant::now(); - let settled = [ - ("in-place", self.device.settle_in_place_checks(SETTLE)), - ("submission", self.device.settle_submit_checks(SETTLE)), - ( - "queue switch", - self.device.settle_queue_switch_check(SETTLE), - ), - ]; - crate::workloads::emit( - "meta", - "device_checks", - "ms", - &mut [started.elapsed().as_secs_f64() * 1e3], - ); - for (check, answered) in settled { - if !answered { - eprintln!("runtime: the device's {check} check did not answer within {SETTLE:?}"); - } - } - } - - pub fn device(&self) -> &rt::Device { - &self.device - } -} - -/// Command `index` of `commands`' setters (`indirectComputeCommandAtIndex:`). -fn compute_command( - commands: &rt::IndirectCommandBuffer, - index: usize, -) -> rt::IndirectComputeCommand { - commands - .indirect_compute_command_at(index as u64) - .expect("indirect_compute_command_at") -} - -/// Command `index` of `commands`' setters (`indirectRenderCommandAtIndex:`). -fn render_command(commands: &rt::IndirectCommandBuffer, index: usize) -> rt::IndirectRenderCommand { - commands - .indirect_render_command_at(index as u64) - .expect("indirect_render_command_at") -} - -fn pixel_format(format: Format) -> PixelFormat { - match format { - Format::Bgra8 => PixelFormat::BGRA8Unorm, - Format::Rgba8 => PixelFormat::RGBA8Unorm, - Format::Rgba16Float => PixelFormat::RGBA16Float, - Format::Depth32Float => PixelFormat::Depth32Float, - } -} - -impl Gpu for Runtime { - type Library = rt::Library; - type RenderPipeline = rt::RenderPipelineState; - type ComputePipeline = rt::ComputePipelineState; - type Buffer = rt::Buffer; - type Texture = rt::Texture; - type Sampler = rt::SamplerState; - type CommandBuffer = rt::CommandBuffer; - type RenderEncoder = rt::RenderCommandEncoder; - type ComputeEncoder = rt::ComputeCommandEncoder; - type Heap = rt::Heap; - type DepthStencil = rt::DepthStencilState; - type IndirectCommands = rt::IndirectCommandBuffer; - type SharedEvent = rt::SharedEvent; - type Listener = rt::SharedEventListener; - type Pass = rt::RenderPassDescriptor; - type BlitEncoder = rt::BlitCommandEncoder; - type Fence = rt::Fence; - - fn label(&self) -> String { - format!("runtime on {}", self.device.name()) - } - - fn with_own_queue(&self) -> Runtime { - let queue = self.device.new_command_queue().expect("new_command_queue"); - Runtime { - device: self.device.clone(), - queue, - } - } - - fn library(&self, metallib: &Path) -> rt::Library { - let bytes = std::fs::read(metallib).expect("read the metallib"); - self.device - .new_library_with_data(&bytes) - .expect("new_library_with_data") - } - - fn render_pipeline( - &self, - library: &rt::Library, - vertex: &str, - fragment: &str, - format: Format, - blend: bool, - ) -> rt::RenderPipelineState { - let function = |name: &str| { - let function = library - .new_function_with_name(name) - .expect("new_function_with_name"); - StageSource::Function(function.function_descriptor()) - }; - let mut descriptor = RenderPipelineDescriptor::new(function(vertex)); - descriptor.fragment = Some(function(fragment)); - let mut color = ColorAttachmentDescriptor::new(pixel_format(format)); - color.blending_enabled = blend; - descriptor.color_attachments[0] = Some(color); - self.device - .new_render_pipeline_state(&descriptor, &rt::PipelineOptions::default()) - .expect("new_render_pipeline_state") - } - - fn depth_pipeline( - &self, - library: &rt::Library, - vertex: &str, - fragment: &str, - blend: bool, - ) -> rt::RenderPipelineState { - let function = |name: &str| { - let function = library - .new_function_with_name(name) - .expect("new_function_with_name"); - StageSource::Function(function.function_descriptor()) - }; - let mut descriptor = RenderPipelineDescriptor::new(function(vertex)); - descriptor.fragment = Some(function(fragment)); - let mut color = ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm); - if blend { - color.blending_enabled = true; - color.source_rgb_blend_factor = BlendFactor::SourceAlpha; - color.source_alpha_blend_factor = BlendFactor::One; - color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; - color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; - } - descriptor.color_attachments[0] = Some(color); - descriptor.depth_format = Some(PixelFormat::Depth32Float); - self.device - .new_render_pipeline_state(&descriptor, &rt::PipelineOptions::default()) - .expect("new_render_pipeline_state") - } - - fn depth_stencil(&self, writes: bool) -> rt::DepthStencilState { - let mut descriptor = DepthStencilDescriptor::default(); - descriptor.depth_compare_function = if writes { - CompareFunction::Less - } else { - CompareFunction::LessEqual - }; - descriptor.depth_write_enabled = writes; - self.device - .new_depth_stencil_state(&descriptor) - .expect("new_depth_stencil_state") - } - - fn compute_pipeline(&self, library: &rt::Library, kernel: &str) -> rt::ComputePipelineState { - let function = library - .new_function_with_name(kernel) - .expect("new_function_with_name"); - self.device - .new_compute_pipeline_state_with_function(&function, &rt::PipelineOptions::default()) - .expect("new_compute_pipeline_state_with_function") - } - - fn indirect_compute_pipeline( - &self, - library: &rt::Library, - kernel: &str, - ) -> rt::ComputePipelineState { - let function = library - .new_function_with_name(kernel) - .expect("new_function_with_name"); - let mut descriptor = - ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); - descriptor.support_indirect_command_buffers = true; - self.device - .new_compute_pipeline_state(&descriptor, &rt::PipelineOptions::default()) - .expect("new_compute_pipeline_state") - } - - fn indirect_render_pipeline( - &self, - library: &rt::Library, - vertex: &str, - fragment: &str, - ) -> rt::RenderPipelineState { - let function = |name: &str| { - let function = library - .new_function_with_name(name) - .expect("new_function_with_name"); - StageSource::Function(function.function_descriptor()) - }; - let mut descriptor = RenderPipelineDescriptor::new(function(vertex)); - descriptor.fragment = Some(function(fragment)); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm)); - descriptor.support_indirect_command_buffers = true; - self.device - .new_render_pipeline_state(&descriptor, &rt::PipelineOptions::default()) - .expect("new_render_pipeline_state") - } - - fn indirect_draws(&self, count: usize, vertex_buffers: usize) -> rt::IndirectCommandBuffer { - let mut descriptor = rt::IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::DRAW; - descriptor.inherit_pipeline_state = true; - descriptor.inherit_buffers = false; - descriptor.max_vertex_buffer_bind_count = vertex_buffers as u32; - descriptor.max_fragment_buffer_bind_count = 0; - self.device - .new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::shared()) - .expect("new_indirect_command_buffer") - } - - fn indirect_commands(&self, count: usize) -> rt::IndirectCommandBuffer { - let mut descriptor = rt::IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; - descriptor.inherit_pipeline_state = false; - descriptor.inherit_buffers = false; - descriptor.max_kernel_buffer_bind_count = 1; - self.device - .new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::private()) - .expect("new_indirect_command_buffer") - } - - fn commands_id(&self, commands: &rt::IndirectCommandBuffer) -> u64 { - commands.gpu_resource_id().0 - } - - fn pipeline_id(&self, state: &rt::ComputePipelineState) -> u64 { - state.gpu_resource_id().0 - } - - fn texture_id(&self, texture: &rt::Texture) -> u64 { - texture.gpu_resource_id().0 - } - - fn cpu_indirect_commands(&self, count: usize) -> rt::IndirectCommandBuffer { - let mut descriptor = rt::IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; - descriptor.inherit_pipeline_state = false; - descriptor.inherit_buffers = false; - descriptor.max_kernel_buffer_bind_count = 1; - self.device - .new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::shared()) - .expect("new_indirect_command_buffer") - } - - fn cpu_indirect_draws(&self, count: usize) -> rt::IndirectCommandBuffer { - let mut descriptor = rt::IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::DRAW; - descriptor.inherit_pipeline_state = false; - descriptor.inherit_buffers = false; - descriptor.max_vertex_buffer_bind_count = 1; - descriptor.max_fragment_buffer_bind_count = 1; - self.device - .new_indirect_command_buffer(&descriptor, count as u64, rt::ResourceOptions::shared()) - .expect("new_indirect_command_buffer") - } - - fn command_pipeline( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - state: &rt::ComputePipelineState, - ) { - compute_command(commands, index) - .set_compute_pipeline_state(state) - .expect("set_compute_pipeline_state"); - } - - fn command_kernel_buffer( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - buffer: &rt::Buffer, - offset: usize, - ) { - compute_command(commands, index) - .set_kernel_buffer(Some(buffer), offset as u64, 0) - .expect("set_kernel_buffer"); - } - - fn command_dispatch(&self, commands: &rt::IndirectCommandBuffer, index: usize, groups: usize) { - compute_command(commands, index) - .concurrent_dispatch_threadgroups( - rt::Size::new(groups as u64, 1, 1), - rt::Size::new(64, 1, 1), - ) - .expect("concurrent_dispatch_threadgroups"); - } - - fn command_barrier(&self, commands: &rt::IndirectCommandBuffer, index: usize) { - compute_command(commands, index) - .set_barrier() - .expect("set_barrier"); - } - - fn command_kernel_buffer_address( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - ) -> u64 { - compute_command(commands, index) - .kernel_buffer(0) - .expect("kernel_buffer") - .expect("a kernel buffer") - .address - .0 - } - - fn command_has_barrier(&self, commands: &rt::IndirectCommandBuffer, index: usize) -> bool { - compute_command(commands, index) - .has_barrier() - .expect("has_barrier") - } - - fn draw_command_pipeline( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - state: &rt::RenderPipelineState, - ) { - render_command(commands, index) - .set_render_pipeline_state(state) - .expect("set_render_pipeline_state"); - } - - fn draw_command_vertex_buffer( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - buffer: &rt::Buffer, - offset: usize, - ) { - render_command(commands, index) - .set_vertex_buffer(Some(buffer), offset as u64, 0) - .expect("set_vertex_buffer"); - } - - fn draw_command_draw(&self, commands: &rt::IndirectCommandBuffer, index: usize) { - render_command(commands, index) - .draw_primitives(PrimitiveType::TriangleStrip, 0, 4, 1, 0) - .expect("draw_primitives"); - } - - fn draw_command_vertex_buffer_address( - &self, - commands: &rt::IndirectCommandBuffer, - index: usize, - ) -> u64 { - render_command(commands, index) - .vertex_buffer(0) - .expect("vertex_buffer") - .expect("a vertex buffer") - .address - .0 - } - - fn buffer(&self, length: usize) -> rt::Buffer { - self.device - .new_buffer(length as u64, rt::ResourceOptions::shared()) - .expect("new_buffer") - } - - fn buffer_with(&self, bytes: &[u8]) -> rt::Buffer { - self.device - .new_buffer_with_bytes(bytes, rt::ResourceOptions::shared()) - .expect("new_buffer_with_bytes") - } - - unsafe fn buffer_no_copy(&self, pointer: *mut u8, length: usize) -> rt::Buffer { - let pointer = NonNull::new(pointer).expect("a pointer"); - // SAFETY: the caller's contract: page-aligned read-write memory that outlives the buffer. - unsafe { - self.device.new_buffer_with_bytes_no_copy( - rt::HostMemory::new(pointer), - length as u64, - rt::ResourceOptions::shared(), - None, - ) - } - .expect("new_buffer_with_bytes_no_copy") - } - - fn heap(&self, size: usize) -> rt::Heap { - let descriptor = rt::HeapDescriptor::new( - rt::HeapType::Placement, - size as u64, - rt::ResourceOptions::shared(), - ); - self.device.new_heap(&descriptor).expect("new_heap") - } - - unsafe fn heap_no_copy(&self, pointer: *mut u8, size: usize) -> Option { - let pointer = NonNull::new(pointer).expect("a pointer"); - let descriptor = rt::HeapDescriptor::new( - rt::HeapType::Placement, - size as u64, - rt::ResourceOptions::shared(), - ); - // SAFETY: the caller's contract: page-aligned read-write memory that outlives the heap. - let heap = unsafe { - self.device.new_heap_with_bytes_no_copy( - rt::HostMemory::new(pointer), - &descriptor, - None, - None, - ) - }; - Some(heap.expect("new_heap_with_bytes_no_copy")) - } - - fn heap_texture( - &self, - heap: &rt::Heap, - width: usize, - height: usize, - offset: usize, - ) -> rt::Texture { - let mut descriptor = rt::TextureDescriptor::texture_2d( - PixelFormat::BGRA8Unorm, - width as u64, - height as u64, - false, - ); - descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - descriptor.resource_options = rt::ResourceOptions::shared(); - descriptor.allow_gpu_optimized_contents = false; - heap.new_texture_at_offset(&descriptor, offset as u64) - .expect("new_texture_at_offset") - } - - fn buffer_texture( - &self, - buffer: &rt::Buffer, - (width, height): (usize, usize), - offset: usize, - bytes_per_row: usize, - ) -> rt::Texture { - let mut descriptor = rt::TextureDescriptor::texture_2d( - PixelFormat::BGRA8Unorm, - width as u64, - height as u64, - false, - ); - descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - descriptor.resource_options = rt::ResourceOptions::shared(); - buffer - .new_texture(&descriptor, offset as u64, bytes_per_row as u64) - .expect("new_texture over a buffer") - } - - fn texture(&self, format: Format, width: usize, height: usize, target: bool) -> rt::Texture { - let mut descriptor = rt::TextureDescriptor::texture_2d( - pixel_format(format), - width as u64, - height as u64, - false, - ); - if target { - descriptor.usage = TextureUsage::RENDER_TARGET; - descriptor.resource_options = rt::ResourceOptions::private(); - } else { - descriptor.usage = TextureUsage::SHADER_READ; - descriptor.resource_options = rt::ResourceOptions::shared(); - } - self.device.new_texture(&descriptor).expect("new_texture") - } - - fn tracked_heap(&self, size: usize) -> rt::Heap { - let options = rt::ResourceOptions::new( - rt::StorageMode::Shared, - rt::CpuCacheMode::DefaultCache, - rt::HazardTrackingMode::Tracked, - ); - let descriptor = rt::HeapDescriptor::new(rt::HeapType::Placement, size as u64, options); - self.device.new_heap(&descriptor).expect("new_heap") - } - - fn heap_render_texture( - &self, - heap: &rt::Heap, - format: Format, - side: usize, - offset: usize, - ) -> rt::Texture { - let mut descriptor = rt::TextureDescriptor::texture_2d( - pixel_format(format), - side as u64, - side as u64, - false, - ); - descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - descriptor.resource_options = rt::ResourceOptions::shared(); - heap.new_texture_at_offset(&descriptor, offset as u64) - .expect("new_texture_at_offset") - } - - fn replace_region( - &self, - texture: &rt::Texture, - size: (usize, usize), - bytes: &[u8], - row: usize, - ) { - let region = rt::Region::new_2d(0, 0, size.0 as u64, size.1 as u64); - texture - .replace_region(region, 0, 0, bytes, row as u64, 0) - .expect("replace_region"); - } - - fn get_bytes(&self, texture: &rt::Texture, size: (usize, usize), bytes: &mut [u8], row: usize) { - let region = rt::Region::new_2d(0, 0, size.0 as u64, size.1 as u64); - texture - .get_bytes(bytes, row as u64, 0, region, 0, 0) - .expect("get_bytes"); - } - - fn read_buffer(&self, buffer: &rt::Buffer, bytes: &mut [u8]) { - assert!( - bytes.len() as u64 <= buffer.length(), - "a read within the buffer" - ); - let contents = buffer.contents().expect("a Shared buffer's contents"); - // SAFETY: `contents` holds the buffer's `length` bytes, which no GPU work writes now (the - // caller's contract), and `bytes` is as long as the copy. - unsafe { - std::ptr::copy_nonoverlapping(contents.as_ptr(), bytes.as_mut_ptr(), bytes.len()) - }; - } - - fn write_buffer(&self, buffer: &rt::Buffer, value: u8) { - let contents = buffer.contents().expect("a Shared buffer's contents"); - // SAFETY: `contents` holds the buffer's `length` bytes, which no GPU work uses now (the - // caller's contract). - unsafe { std::ptr::write_bytes(contents.as_ptr(), value, buffer.length() as usize) }; - } - - fn sampler(&self, linear: bool) -> rt::SamplerState { - let mut descriptor = SamplerDescriptor::new(); - if linear { - descriptor.min_filter = SamplerMinMagFilter::Linear; - descriptor.mag_filter = SamplerMinMagFilter::Linear; - } - self.device - .new_sampler_state(&descriptor) - .expect("new_sampler_state") - } - - fn command_buffer(&self) -> rt::CommandBuffer { - self.queue.command_buffer().expect("command_buffer") - } - - fn render_encoder( - &self, - command_buffer: &rt::CommandBuffer, - target: &rt::Texture, - clear: bool, - ) -> rt::RenderCommandEncoder { - let mut pass = rt::RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = if clear { - rt::LoadAction::Clear - } else { - rt::LoadAction::Load - }; - color.store_action = rt::StoreAction::Store; - command_buffer - .render_command_encoder(&pass) - .expect("render_command_encoder") - } - - fn pass(&self, target: &rt::Texture) -> rt::RenderPassDescriptor { - let mut pass = rt::RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = rt::LoadAction::Clear; - color.store_action = rt::StoreAction::Store; - pass - } - - fn pass_encoder( - &self, - command_buffer: &rt::CommandBuffer, - pass: &rt::RenderPassDescriptor, - ) -> rt::RenderCommandEncoder { - command_buffer - .render_command_encoder(pass) - .expect("render_command_encoder") - } - - fn depth_render_encoder( - &self, - command_buffer: &rt::CommandBuffer, - target: &rt::Texture, - depth: &rt::Texture, - ) -> rt::RenderCommandEncoder { - let mut pass = rt::RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = rt::LoadAction::Clear; - color.store_action = rt::StoreAction::Store; - color.clear_color = rt::ClearColor { - red: 0.1, - green: 0.1, - blue: 0.12, - alpha: 1.0, - }; - let attachment = &mut pass.depth_attachment; - attachment.texture = Some(depth.clone()); - attachment.load_action = rt::LoadAction::Clear; - attachment.store_action = rt::StoreAction::DontCare; - attachment.clear_depth = 1.0; - command_buffer - .render_command_encoder(&pass) - .expect("render_command_encoder") - } - - fn set_render_pipeline( - &self, - encoder: &mut rt::RenderCommandEncoder, - state: &rt::RenderPipelineState, - ) { - encoder - .set_render_pipeline_state(state) - .expect("set_render_pipeline_state"); - } - - fn set_depth_stencil( - &self, - encoder: &mut rt::RenderCommandEncoder, - state: &rt::DepthStencilState, - ) { - encoder - .set_depth_stencil_state(state) - .expect("set_depth_stencil_state"); - } - - fn set_cull_back(&self, encoder: &mut rt::RenderCommandEncoder, back: bool) { - encoder.set_cull_mode(if back { CullMode::Back } else { CullMode::None }); - } - - fn set_counter_clockwise(&self, encoder: &mut rt::RenderCommandEncoder) { - encoder.set_front_facing_winding(Winding::CounterClockwise); - } - - fn set_vertex_bytes(&self, encoder: &mut rt::RenderCommandEncoder, bytes: &[u8], index: usize) { - encoder - .set_vertex_bytes(bytes, index as u32) - .expect("set_vertex_bytes"); - } - - fn set_vertex_buffer( - &self, - encoder: &mut rt::RenderCommandEncoder, - buffer: &rt::Buffer, - offset: usize, - index: usize, - ) { - encoder - .set_vertex_buffer(Some(buffer), offset as u64, index as u32) - .expect("set_vertex_buffer"); - } - - fn set_vertex_buffer_offset( - &self, - encoder: &mut rt::RenderCommandEncoder, - offset: usize, - index: usize, - ) { - encoder - .set_vertex_buffer_offset(offset as u64, index as u32) - .expect("set_vertex_buffer_offset"); - } - - fn set_vertex_buffers( - &self, - encoder: &mut rt::RenderCommandEncoder, - buffers: &[&rt::Buffer], - offsets: &[usize], - first: usize, - ) { - let buffers: [Option<&rt::Buffer>; 2] = [Some(buffers[0]), Some(buffers[1])]; - let offsets = [offsets[0] as u64, offsets[1] as u64]; - encoder - .set_vertex_buffers(&buffers, &offsets, first as u32) - .expect("set_vertex_buffers"); - } - - fn set_fragment_buffer( - &self, - encoder: &mut rt::RenderCommandEncoder, - buffer: &rt::Buffer, - offset: usize, - index: usize, - ) { - encoder - .set_fragment_buffer(Some(buffer), offset as u64, index as u32) - .expect("set_fragment_buffer"); - } - - fn set_fragment_texture( - &self, - encoder: &mut rt::RenderCommandEncoder, - texture: &rt::Texture, - index: usize, - ) { - encoder - .set_fragment_texture(Some(texture), index as u32) - .expect("set_fragment_texture"); - } - - fn set_fragment_sampler( - &self, - encoder: &mut rt::RenderCommandEncoder, - sampler: &rt::SamplerState, - index: usize, - ) { - encoder - .set_fragment_sampler_state(Some(sampler), index as u32) - .expect("set_fragment_sampler_state"); - } - - fn draw_strip(&self, encoder: &mut rt::RenderCommandEncoder, vertices: usize) { - encoder - .draw_primitives(PrimitiveType::TriangleStrip, 0, vertices as u32, 1, 0) - .expect("draw_primitives"); - } - - fn draw_indexed( - &self, - encoder: &mut rt::RenderCommandEncoder, - count: usize, - indices: &rt::Buffer, - ) { - encoder - .draw_indexed_primitives( - PrimitiveType::Triangle, - count as u32, - IndexType::UInt16, - indices, - 0, - 1, - 0, - 0, - ) - .expect("draw_indexed_primitives"); - } - - fn draw_triangles(&self, encoder: &mut rt::RenderCommandEncoder, start: usize, count: usize) { - encoder - .draw_primitives(PrimitiveType::Triangle, start as u32, count as u32, 1, 0) - .expect("draw_primitives"); - } - - fn draw_indexed_at( - &self, - encoder: &mut rt::RenderCommandEncoder, - count: usize, - indices: &rt::Buffer, - offset: usize, - ) { - encoder - .draw_indexed_primitives( - PrimitiveType::Triangle, - count as u32, - IndexType::UInt16, - indices, - offset as u64, - 1, - 0, - 0, - ) - .expect("draw_indexed_primitives"); - } - - fn draw_indexed_strip_at( - &self, - encoder: &mut rt::RenderCommandEncoder, - count: usize, - indices: &rt::Buffer, - offset: usize, - ) { - encoder - .draw_indexed_primitives( - PrimitiveType::TriangleStrip, - count as u32, - IndexType::UInt16, - indices, - offset as u64, - 1, - 0, - 0, - ) - .expect("draw_indexed_primitives"); - } - - fn draw_triangles_indirect( - &self, - encoder: &mut rt::RenderCommandEncoder, - arguments: &rt::Buffer, - offset: usize, - ) { - encoder - .draw_primitives_indirect(PrimitiveType::Triangle, arguments, offset as u64) - .expect("draw_primitives_indirect"); - } - - fn draw_indexed_indirect( - &self, - encoder: &mut rt::RenderCommandEncoder, - indices: &rt::Buffer, - arguments: &rt::Buffer, - offset: usize, - ) { - encoder - .draw_indexed_primitives_indirect( - PrimitiveType::Triangle, - IndexType::UInt16, - indices, - 0, - arguments, - offset as u64, - ) - .expect("draw_indexed_primitives_indirect"); - } - - fn set_provoking_vertex_mode(&self, encoder: &mut rt::RenderCommandEncoder, mode: u64) { - encoder - .set_provoking_vertex_mode(mode) - .expect("set_provoking_vertex_mode"); - } - - fn use_in_vertex(&self, encoder: &mut rt::RenderCommandEncoder, buffer: &rt::Buffer) { - encoder - .use_resource( - buffer.as_resource(), - ResourceUsage::READ, - metal2vulkan::metal::RenderStages::VERTEX, - ) - .expect("use_resource"); - } - - fn execute_draws( - &self, - encoder: &mut rt::RenderCommandEncoder, - commands: &rt::IndirectCommandBuffer, - count: usize, - ) { - encoder - .execute_commands_in_buffer(commands, 0..count as u64) - .expect("execute_commands_in_buffer"); - } - - fn end_render(&self, encoder: rt::RenderCommandEncoder) { - encoder.end_encoding().expect("end_encoding"); - } - - fn compute_encoder(&self, command_buffer: &rt::CommandBuffer) -> rt::ComputeCommandEncoder { - command_buffer - .compute_command_encoder() - .expect("compute_command_encoder") - } - - fn concurrent_compute_encoder( - &self, - command_buffer: &rt::CommandBuffer, - ) -> rt::ComputeCommandEncoder { - command_buffer - .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent) - .expect("compute_command_encoder_with_dispatch_type") - } - - fn set_compute_pipeline( - &self, - encoder: &mut rt::ComputeCommandEncoder, - state: &rt::ComputePipelineState, - ) { - encoder - .set_compute_pipeline_state(state) - .expect("set_compute_pipeline_state"); - } - - fn set_buffer( - &self, - encoder: &mut rt::ComputeCommandEncoder, - buffer: &rt::Buffer, - offset: usize, - index: usize, - ) { - encoder - .set_buffer(Some(buffer), offset as u64, index as u32) - .expect("set_buffer"); - } - - fn set_texture( - &self, - encoder: &mut rt::ComputeCommandEncoder, - texture: &rt::Texture, - index: usize, - ) { - encoder - .set_texture(Some(texture), index as u32) - .expect("set_texture"); - } - - fn dispatch(&self, encoder: &mut rt::ComputeCommandEncoder, groups: usize, threads: usize) { - encoder - .dispatch_threadgroups( - rt::Size::new(groups as u64, 1, 1), - rt::Size::new(threads as u64, 1, 1), - ) - .expect("dispatch_threadgroups"); - } - - fn use_commands( - &self, - encoder: &mut rt::ComputeCommandEncoder, - commands: &rt::IndirectCommandBuffer, - ) { - encoder - .use_resource(commands.as_resource(), ResourceUsage::WRITE) - .expect("use_resource"); - } - - fn use_heap(&self, encoder: &mut rt::ComputeCommandEncoder, heap: &rt::Heap) { - encoder.use_heap(heap).expect("use_heap"); - } - - fn update_fence(&self, encoder: &mut rt::ComputeCommandEncoder, fence: &rt::Fence) { - encoder.update_fence(fence).expect("update_fence"); - } - - fn wait_for_fence(&self, encoder: &mut rt::ComputeCommandEncoder, fence: &rt::Fence) { - encoder.wait_for_fence(fence).expect("wait_for_fence"); - } - - fn use_buffers_read(&self, encoder: &mut rt::ComputeCommandEncoder, buffers: &[&rt::Buffer]) { - let resources: Vec = buffers.iter().map(|b| b.as_resource()).collect(); - encoder - .use_resources(&resources, ResourceUsage::READ) - .expect("use_resources"); - } - - fn use_buffers_drawn(&self, encoder: &mut rt::RenderCommandEncoder, buffers: &[&rt::Buffer]) { - let resources: Vec = buffers.iter().map(|b| b.as_resource()).collect(); - let stages = - metal2vulkan::metal::RenderStages::VERTEX | metal2vulkan::metal::RenderStages::FRAGMENT; - encoder - .use_resources(&resources, ResourceUsage::READ, stages) - .expect("use_resources"); - } - - fn use_buffer(&self, encoder: &mut rt::ComputeCommandEncoder, buffer: &rt::Buffer) { - encoder - .use_resource( - buffer.as_resource(), - ResourceUsage::READ.union(ResourceUsage::WRITE), - ) - .expect("use_resource"); - } - - fn use_buffers(&self, encoder: &mut rt::ComputeCommandEncoder, buffers: &[&rt::Buffer]) { - let resources: Vec<_> = buffers.iter().map(|buffer| buffer.as_resource()).collect(); - encoder - .use_resources(&resources, ResourceUsage::READ) - .expect("use_resources"); - } - - fn use_textures(&self, encoder: &mut rt::ComputeCommandEncoder, textures: &[&rt::Texture]) { - let resources: Vec<_> = textures - .iter() - .map(|texture| texture.as_resource()) - .collect(); - encoder - .use_resources(&resources, ResourceUsage::READ) - .expect("use_resources"); - } - - fn execute_commands( - &self, - encoder: &mut rt::ComputeCommandEncoder, - commands: &rt::IndirectCommandBuffer, - count: usize, - ) { - encoder - .execute_commands_in_buffer(commands, 0..count as u64) - .expect("execute_commands_in_buffer"); - } - - fn end_compute(&self, encoder: rt::ComputeCommandEncoder) { - encoder.end_encoding().expect("end_encoding"); - } - - fn reset_commands( - &self, - command_buffer: &rt::CommandBuffer, - commands: &rt::IndirectCommandBuffer, - count: usize, - ) { - let mut blit = command_buffer - .blit_command_encoder() - .expect("blit_command_encoder"); - blit.reset_commands_in_buffer(commands, 0..count as u64) - .expect("reset_commands_in_buffer"); - blit.end_encoding().expect("end_encoding"); - } - - fn blit_encoder(&self, command_buffer: &rt::CommandBuffer) -> rt::BlitCommandEncoder { - command_buffer - .blit_command_encoder() - .expect("blit_command_encoder") - } - - fn copy_buffer( - &self, - encoder: &mut rt::BlitCommandEncoder, - (from, from_offset): (&rt::Buffer, usize), - (to, to_offset): (&rt::Buffer, usize), - size: usize, - ) { - encoder - .copy_from_buffer_to_buffer(from, from_offset as u64, to, to_offset as u64, size as u64) - .expect("copy_from_buffer_to_buffer"); - } - - fn fill_buffer_in( - &self, - encoder: &mut rt::BlitCommandEncoder, - buffer: &rt::Buffer, - offset: usize, - length: usize, - ) { - encoder - .fill_buffer(buffer, offset as u64..(offset + length) as u64, 0x5a) - .expect("fill_buffer"); - } - - fn copy_to_texture( - &self, - encoder: &mut rt::BlitCommandEncoder, - source: &rt::Buffer, - texture: &rt::Texture, - (width, height): (usize, usize), - bytes_per_row: usize, - ) { - encoder - .copy_from_buffer_to_texture( - source, - 0, - bytes_per_row as u64, - (bytes_per_row * height) as u64, - rt::Size::new(width as u64, height as u64, 1), - texture, - 0, - 0, - rt::Origin::new(0, 0, 0), - rt::BlitOption::None, - ) - .expect("copy_from_buffer_to_texture"); - } - - fn end_blit(&self, encoder: rt::BlitCommandEncoder) { - encoder.end_encoding().expect("end_encoding"); - } - - fn fill(&self, command_buffer: &rt::CommandBuffer, buffer: &rt::Buffer, length: usize) { - let mut blit = command_buffer - .blit_command_encoder() - .expect("blit_command_encoder"); - blit.fill_buffer(buffer, 0..length as u64, 0x5a) - .expect("fill_buffer"); - blit.end_encoding().expect("end_encoding"); - } - - fn upload( - &self, - command_buffer: &rt::CommandBuffer, - source: &rt::Buffer, - textures: &[&rt::Texture], - (width, height): (usize, usize), - bytes_per_row: usize, - ) { - let mut blit = command_buffer - .blit_command_encoder() - .expect("blit_command_encoder"); - for texture in textures { - self.copy_to_texture(&mut blit, source, texture, (width, height), bytes_per_row); - } - blit.end_encoding().expect("end_encoding"); - } - - fn commit(&self, command_buffer: &rt::CommandBuffer) { - command_buffer.commit().expect("commit"); - } - - fn wait(&self, command_buffer: &rt::CommandBuffer) { - command_buffer - .wait_until_completed() - .expect("wait_until_completed"); - let status = command_buffer.status(); - assert_eq!( - status, - rt::CommandBufferStatus::Completed, - "the command buffer ended {status:?}: {:?}", - command_buffer.error() - ); - } - - fn wait_only(&self, command_buffer: &rt::CommandBuffer) { - command_buffer - .wait_until_completed() - .expect("wait_until_completed"); - } - - fn status(&self, command_buffer: &rt::CommandBuffer) -> u64 { - command_buffer.status().raw() - } - - fn fence(&self) -> rt::Fence { - self.device.new_fence() - } - - fn shared_event(&self) -> rt::SharedEvent { - self.device.new_shared_event().expect("new_shared_event") - } - - fn event_value(&self, event: &rt::SharedEvent) -> u64 { - event.signaled_value() - } - - fn set_event_value(&self, event: &rt::SharedEvent, value: u64) { - event.set_signaled_value(value); - } - - fn set_when_scheduled( - &self, - command_buffer: &rt::CommandBuffer, - event: &rt::SharedEvent, - value: u64, - ) { - let event = event.clone(); - command_buffer - .add_scheduled_handler(Box::new(move |_| event.set_signaled_value(value))) - .expect("add_scheduled_handler"); - } - - fn signal_when_scheduled( - &self, - command_buffer: &rt::CommandBuffer, - event: &rt::SharedEvent, - value: u64, - ) { - command_buffer - .encode_signal_event_scheduled(event, value) - .expect("encode_signal_event_scheduled"); - } - - fn listener(&self) -> rt::SharedEventListener { - rt::SharedEventListener::new() - } - - fn notify( - &self, - event: &rt::SharedEvent, - listener: &rt::SharedEventListener, - value: u64, - block: Box, - ) { - event.notify_listener(listener, value, Box::new(move |_, _| block())); - } - - fn check_submissions(&self, command_buffer: &rt::CommandBuffer) -> bool { - command_buffer - .set_submission_check(std::sync::Arc::new(|_: &rt::Submission<'_>| None)) - .expect("set_submission_check"); - true - } - - fn on_completed(&self, command_buffer: &rt::CommandBuffer, handler: Box) { - command_buffer - .add_completed_handler(Box::new(move |_| handler())) - .expect("add_completed_handler"); - } - - fn gpu_seconds(&self, _command_buffer: &rt::CommandBuffer) -> Option { - // On MoltenVK the runtime answers GPU times from the host's clock (their docs), which - // is no measure of the GPU. - None - } - - fn times(&self, command_buffer: &rt::CommandBuffer) -> [f64; 4] { - [ - command_buffer.kernel_start_time(), - command_buffer.kernel_end_time(), - command_buffer.gpu_start_time().unwrap_or(0.0), - command_buffer.gpu_end_time().unwrap_or(0.0), - ] - } - - fn pool(&self, f: impl FnOnce() -> R) -> R { - f() - } - - unsafe fn driver_floor(&self, windows: usize, pages: *mut u8) { - // SAFETY: the caller's contract, passed on. - unsafe { crate::vkfloor::measure(self, &self.device, windows, pages) }; - } - - fn work_counts(&self) -> Vec<(&'static str, f64)> { - let c = self.device.work_counts(); - let recorded = &c.commands_recorded; - [ - ("queue_submissions", c.queue_submissions), - ("submit_infos", c.submit_infos), - ("vk_command_buffers_submitted", c.command_buffers_submitted), - ("first_work_buffers", c.command_buffers_begun_batch_work), - ("barrier_buffers", c.command_buffers_begun_batch_barriers), - ("finales_apart", c.finales_apart), - ("render_passes_begun", recorded.cmd_begin_render_pass), - ("render_encoders_ended", c.render_encoders_ended), - ("passes_begun_instances", c.render_passes_begun_instances), - ("passes_begun_inline", c.render_passes_begun_inline), - ( - "passes_begun_inline_splits", - c.render_passes_begun_inline_splits, - ), - ("passes_begun_resolves", c.render_passes_begun_resolves), - ("passes_continued", c.render_passes_continued), - ("splits_barrier", c.instance_splits_barrier), - ("splits_tile_dispatch", c.instance_splits_tile_dispatch), - ("splits_tile_memory", c.instance_splits_tile_memory), - ( - "splits_interlocked_writes", - c.instance_splits_interlocked_writes, - ), - ("splits_attached_read", c.instance_splits_attached_read), - ("splits_feedback", c.instance_splits_feedback), - ( - "splits_memoryless_write", - c.instance_splits_memoryless_write, - ), - ( - "splits_pending_pipeline", - c.instance_splits_pending_pipeline, - ), - ("splits_execution", c.instance_splits_execution), - ("splits_visibility", c.instance_splits_visibility), - ("splits_shape", c.instance_splits_shape), - ("pipeline_barriers", recorded.cmd_pipeline_barrier), - ("vk_images_destroyed", c.object_churn.vk_images_destroyed), - ("images_own_memory", c.object_churn.images_own_memory), - ("images_parked", c.object_churn.images_parked), - ("images_recycled", c.object_churn.images_recycled), - ("images_evicted", c.object_churn.images_evicted), - ("requirement_images_made", c.requirement_images_made), - ("arena_pools_made", c.arena_pools_made), - ("command_pools_made", c.command_pools_made), - ("command_buffers_made", c.command_buffers_made), - ("dispatches", recorded.cmd_dispatch), - ("draws", recorded.cmd_draw), - ("gpu_form_commands", c.gpu_form_commands), - ("merged_draw_commands", c.merged_draw_commands), - ("indirect_records_read", c.indirect_records_read), - ("dispatches_indirect", recorded.cmd_dispatch_indirect), - ("wakes_handler_threads", c.wakes_handler_threads), - ("scheduled_where_submitted", c.scheduled_where_submitted), - ("scheduler_passes", c.scheduler_passes), - ("scheduler_sleeps", c.scheduler_sleeps), - ("scheduler_wakes_commit", c.scheduler_wakes_commit), - ("scheduler_wakes_host", c.scheduler_wakes_host), - ( - "dispatches_settled_as_before", - c.dispatches_settled_as_before, - ), - ("dispatches_instantiated", c.dispatches_instantiated), - ( - "dispatches_instantiated_as_before", - c.dispatches_instantiated_as_before, - ), - ( - "dispatches_planned_as_before", - c.dispatches_planned_as_before, - ), - ( - "provoking_last_pipeline_draws", - c.provoking_last_pipeline_draws, - ), - ("provoking_listed_draws", c.provoking_listed_draws), - ("gathered_draws", c.gathered_draws), - ("bounded_run_draws", c.bounded_run_draws), - ("variant_pipelines_made", c.variant_pipelines_made), - ("host_pointer_imports_made", c.host_pointer_imports_made), - ("completed_waits", c.completed_waits), - ("device_memory_bytes", c.device_memory_allocated), - ("cleared_bytes", c.new_buffer_bytes_cleared), - ("new_buffer_zero_fills", c.new_buffer_zero_fills), - ( - "recorded_begin_command_buffer", - recorded.begin_command_buffer, - ), - ("recorded_end_command_buffer", recorded.end_command_buffer), - ("recorded_cmd_bind_pipeline", recorded.cmd_bind_pipeline), - ("recorded_cmd_set_viewport", recorded.cmd_set_viewport), - ("recorded_cmd_set_scissor", recorded.cmd_set_scissor), - ("recorded_cmd_set_depth_bias", recorded.cmd_set_depth_bias), - ( - "recorded_cmd_set_blend_constants", - recorded.cmd_set_blend_constants, - ), - ( - "recorded_cmd_set_stencil_compare_mask", - recorded.cmd_set_stencil_compare_mask, - ), - ( - "recorded_cmd_set_stencil_write_mask", - recorded.cmd_set_stencil_write_mask, - ), - ( - "recorded_cmd_set_stencil_reference", - recorded.cmd_set_stencil_reference, - ), - ( - "recorded_cmd_bind_descriptor_sets", - recorded.cmd_bind_descriptor_sets, - ), - ( - "recorded_cmd_bind_index_buffer", - recorded.cmd_bind_index_buffer, - ), - ( - "recorded_cmd_bind_vertex_buffers", - recorded.cmd_bind_vertex_buffers, - ), - ("recorded_cmd_draw_indexed", recorded.cmd_draw_indexed), - ("recorded_cmd_draw_indirect", recorded.cmd_draw_indirect), - ( - "recorded_cmd_draw_indexed_indirect", - recorded.cmd_draw_indexed_indirect, - ), - ("recorded_cmd_copy_buffer", recorded.cmd_copy_buffer), - ("recorded_cmd_copy_image", recorded.cmd_copy_image), - ("recorded_cmd_blit_image", recorded.cmd_blit_image), - ( - "recorded_cmd_copy_buffer_to_image", - recorded.cmd_copy_buffer_to_image, - ), - ( - "recorded_cmd_copy_image_to_buffer", - recorded.cmd_copy_image_to_buffer, - ), - ("recorded_cmd_update_buffer", recorded.cmd_update_buffer), - ("recorded_cmd_fill_buffer", recorded.cmd_fill_buffer), - ( - "recorded_cmd_clear_color_image", - recorded.cmd_clear_color_image, - ), - ( - "recorded_cmd_clear_depth_stencil_image", - recorded.cmd_clear_depth_stencil_image, - ), - ( - "recorded_cmd_clear_attachments", - recorded.cmd_clear_attachments, - ), - ("recorded_cmd_begin_query", recorded.cmd_begin_query), - ("recorded_cmd_end_query", recorded.cmd_end_query), - ( - "recorded_cmd_reset_query_pool", - recorded.cmd_reset_query_pool, - ), - ("recorded_cmd_write_timestamp", recorded.cmd_write_timestamp), - ( - "recorded_cmd_copy_query_pool_results", - recorded.cmd_copy_query_pool_results, - ), - ("recorded_cmd_push_constants", recorded.cmd_push_constants), - ("recorded_cmd_end_render_pass", recorded.cmd_end_render_pass), - ( - "recorded_cmd_execute_commands", - recorded.cmd_execute_commands, - ), - ("recorded_cmd_set_cull_mode", recorded.cmd_set_cull_mode), - ("recorded_cmd_set_front_face", recorded.cmd_set_front_face), - ( - "recorded_cmd_set_primitive_topology", - recorded.cmd_set_primitive_topology, - ), - ( - "recorded_cmd_bind_vertex_buffers2", - recorded.cmd_bind_vertex_buffers2, - ), - ( - "recorded_cmd_set_depth_test_enable", - recorded.cmd_set_depth_test_enable, - ), - ( - "recorded_cmd_set_depth_write_enable", - recorded.cmd_set_depth_write_enable, - ), - ( - "recorded_cmd_set_depth_compare_op", - recorded.cmd_set_depth_compare_op, - ), - ( - "recorded_cmd_set_stencil_test_enable", - recorded.cmd_set_stencil_test_enable, - ), - ("recorded_cmd_set_stencil_op", recorded.cmd_set_stencil_op), - ( - "recorded_cmd_push_descriptor_set", - recorded.cmd_push_descriptor_set, - ), - ( - "recorded_cmd_set_color_write_mask", - recorded.cmd_set_color_write_mask, - ), - ( - "recorded_cmd_bind_index_buffer2", - recorded.cmd_bind_index_buffer2, - ), - ("recorded_cmd_draw_mesh_tasks", recorded.cmd_draw_mesh_tasks), - ( - "recorded_cmd_draw_mesh_tasks_indirect", - recorded.cmd_draw_mesh_tasks_indirect, - ), - ("copy_regions_split", c.copy_regions_split), - ("spare_command_pools_taken", c.spare_command_pools_taken), - ("spare_command_pools_reset", c.spare_command_pools_reset), - ("live_tables_uploaded", c.live_tables_uploaded), - ("timeline_waits", c.timeline_waits), - ("missed_completion_wakes", c.missed_completion_wakes), - ("completed_where_seen", c.completed_where_seen), - ("timestamp_slots_taken", c.timestamp_slots_taken), - ( - "timestamp_slots_reset_on_host", - c.timestamp_slots_reset_on_host, - ), - ("calibrations", c.calibrations), - ("calibration_readings", c.calibration_readings), - ("calibration_deviation_most", c.calibration_deviation_most), - ("calibration_disagreements", c.calibration_disagreements), - ( - "loosely_calibrated_gpu_times", - c.loosely_calibrated_gpu_times, - ), - ("storage_forms_taken", c.storage_forms_taken), - ("addressable_buffers_made", c.addressable_buffers_made), - ("mipmaps_filtered", c.mipmaps_filtered), - ("mipmap_first_levels_fetched", c.mipmap_first_levels_fetched), - ("pipelines_pooled", c.pipelines_pooled), - ("residual_form_draws", c.residual_form_draws), - ("residual_form_makings", c.residual_form_makings), - ("pipeline_pool_busy", c.pipeline_pool_busy), - ("shader_modules_made", c.shader_modules_made), - ("shader_modules_shared", c.shader_modules_shared), - ("pipeline_layouts_made", c.pipeline_layouts_made), - ("pipeline_layouts_shared", c.pipeline_layouts_shared), - ("flights_followed", c.flights_followed), - ( - "makings_held_for_compile_memory", - c.makings_held_for_compile_memory, - ), - ("compile_memory_held_nanos", c.compile_memory_held_nanos), - ("predicated_loop_runs_again", c.predicated_loop_runs_again), - ("variants_taken_back", c.variants_taken_back), - ( - "unlisted_argument_sampler_buffers", - c.unlisted_argument_sampler_buffers, - ), - ("host_step_sampler_sets_made", c.host_step_sampler_sets_made), - ("creation_pipelines_made", c.creation_pipelines_made), - ("creation_pipelines_drawn", c.creation_pipelines_drawn), - ("sampler_sets_made", c.sampler_sets_made), - ("sampler_sets_shared", c.sampler_sets_shared), - ("sampler_sets_destroyed", c.sampler_sets_destroyed), - ("ahead_render_passes_made", c.ahead_render_passes_made), - ("render_passes_made", c.render_passes_made), - ("ahead_framebuffers_made", c.ahead_framebuffers_made), - ("kept_backings_made", c.kept_backings_made), - ("pooled_backings_made", c.pooled_backings_made), - ("storage_placeholders_made", c.storage_placeholders_made), - ( - "storage_placeholder_attachments", - c.storage_placeholder_attachments, - ), - ("color_resolve_passes_made", c.color_resolve_passes_made), - ("color_resolve_passes_kept", c.color_resolve_passes_kept), - ("ahead_nanos", c.ahead_nanos), - ("driver_diagnostics_withheld", c.driver_diagnostics_withheld), - ("memory_blocks_live", c.memory_blocks_live), - ("empty_memory_blocks_live", c.empty_memory_blocks_live), - ("pooled_memory_blocks_made", c.pooled_memory_blocks_made), - ("pooled_memory_blocks_freed", c.pooled_memory_blocks_freed), - ( - "dedicated_memory_blocks_live", - c.dedicated_memory_blocks_live, - ), - ("host_imports_live", c.host_imports_live), - ("freed_memory_parked", c.freed_memory_parked), - ("freed_memory_waiting", c.freed_memory_waiting), - ("stand_ins_made", c.stand_ins_made), - ("stand_in_bytes", c.stand_in_bytes), - ("stale_detached_reaches", c.stale_detached_reaches), - ("detached_storage_reaches", c.detached_storage_reaches), - ("heap_slots_rewritten", c.heap_slots_rewritten), - ("heap_slot_writes_deferred", c.heap_slot_writes_deferred), - ("host_range_lookups", c.host_range_lookups), - ("heap_textures_tiled", c.heap_textures_tiled), - ( - "heap_sample_move_images_made", - c.heap_sample_move_images_made, - ), - ( - "heap_sample_move_images_lent", - c.heap_sample_move_images_lent, - ), - ("requirement_limits_asked", c.requirement_limits_asked), - ( - "heap_texture_lossless_layouts", - c.heap_texture_lossless_layouts, - ), - ( - "heap_texture_block_compressed_layouts", - c.heap_texture_block_compressed_layouts, - ), - ( - "heap_texture_untiled_layouts", - c.heap_texture_untiled_layouts, - ), - ("fills_recorded", c.fills_recorded), - ("ycbcr_refreshes", c.ycbcr_refreshes), - ("ycbcr_whole_conversions", c.ycbcr_whole_conversions), - ("attachment_clears_recorded", c.attachment_clears_recorded), - ("image_blits_recorded", c.image_blits_recorded), - ( - "query_result_copies_recorded", - c.query_result_copies_recorded, - ), - ("visibility_queries_begun", c.visibility_queries_begun), - ("indirect_draws_recorded", c.indirect_draws_recorded), - ("gpu_pool_blocks_made", c.gpu_pool_blocks_made), - ("gpu_pool_blocks_released", c.gpu_pool_blocks_released), - ("gpu_pool_leases_peak", c.gpu_pool_leases_peak), - ("internal_submissions", c.internal_submissions), - ("batch_submit_nanos", c.batch_submit_nanos), - ("command_buffers_begun", c.command_buffers_begun), - ( - "encoder_command_buffers_begun", - c.encoder_command_buffers_begun, - ), - ( - "command_buffers_begun_encoders", - c.command_buffers_begun_encoders, - ), - ( - "command_buffers_begun_segments", - c.command_buffers_begun_segments, - ), - ( - "command_buffers_begun_continuations", - c.command_buffers_begun_continuations, - ), - ( - "command_buffers_begun_secondaries", - c.command_buffers_begun_secondaries, - ), - ( - "command_buffers_begun_kept_barriers", - c.command_buffers_begun_kept_barriers, - ), - ( - "command_buffers_begun_internal", - c.command_buffers_begun_internal, - ), - ( - "encoder_primaries_begun_ahead", - c.encoder_primaries_begun_ahead, - ), - ( - "encoder_primaries_begun_ahead_missed", - c.encoder_primaries_begun_ahead_missed, - ), - ("primaries_begun_ahead", c.primaries_begun_ahead), - ("barrier_buffers_kept", c.barrier_buffers_kept), - ("stamped_buffers_kept", c.stamped_buffers_kept), - ("stamped_buffers_reused", c.stamped_buffers_reused), - ("finales_folded", c.finales_folded), - ("grouped_submissions", c.grouped_submissions), - ("batches_grouped", c.batches_grouped), - ("group_ends_full", c.group_ends_full), - ("group_ends_wait", c.group_ends_wait), - ("group_ends_apart", c.group_ends_apart), - ("group_ends_first_work", c.group_ends_first_work), - ("group_ends_long", c.group_ends_long), - ("group_ends_drained", c.group_ends_drained), - ("group_ends_checks", c.group_ends_checks), - ("group_ends_held", c.group_ends_held), - ("group_ends_closed", c.group_ends_closed), - ("batches_with_none_pending", c.batches_with_none_pending), - ("batches_with_one_pending", c.batches_with_one_pending), - ( - "batches_with_two_or_three_pending", - c.batches_with_two_or_three_pending, - ), - ( - "batches_with_four_or_more_pending", - c.batches_with_four_or_more_pending, - ), - ("groups_kept_pending", c.groups_kept_pending), - ("groups_sent_for_waits", c.groups_sent_for_waits), - ("registrations_waited", c.registrations_waited), - ("scheduler_wakes_completion", c.scheduler_wakes_completion), - ("scheduler_sleep_slices", c.scheduler_sleep_slices), - ("scheduler_slice_rescues", c.scheduler_slice_rescues), - ("scheduler_gpu_waits", c.scheduler_gpu_waits), - ("wakes_completion_waiters", c.wakes_completion_waiters), - ( - "wakes_command_buffer_waiters", - c.wakes_command_buffer_waiters, - ), - ("wakes_event_waiters", c.wakes_event_waiters), - ("wakes_spared", c.wakes_spared), - ("slot_returns", c.slot_returns), - ("slot_return_nanos", c.slot_return_nanos), - ("slot_waits", c.slot_waits), - ("slot_wait_nanos", c.slot_wait_nanos), - ("event_waits_met", c.event_waits_met), - ("shared_event_waits_held", c.shared_event_waits_held), - ("event_signals_behind_merge", c.event_signals_behind_merge), - ("bare_starts", c.bare_starts), - ("prefixed_starts", c.prefixed_starts), - ("command_barriers", c.command_barriers), - ("commands_ordered_inside", c.commands_ordered_inside), - ("unrun_instances_ended", c.unrun_instances_ended), - ("untouched_passes_skipped", c.untouched_passes_skipped), - ("inline_passes", c.inline_passes), - ("inline_passes_split", c.inline_passes_split), - ("inline_split_instances", c.inline_split_instances), - ( - "inline_memoryless_write_splits", - c.inline_memoryless_write_splits, - ), - ( - "render_log_batches_by_thread", - c.render_log_batches_by_thread, - ), - ( - "render_log_batches_by_program", - c.render_log_batches_by_program, - ), - ("render_log_waits", c.render_log_waits), - ("render_log_ends_by_thread", c.render_log_ends_by_thread), - ("render_log_ends_by_program", c.render_log_ends_by_program), - ( - "render_log_commits_by_thread", - c.render_log_commits_by_thread, - ), - ( - "render_log_commits_by_program", - c.render_log_commits_by_program, - ), - ("passes_not_inline_encoders", c.passes_not_inline_encoders), - ("passes_not_inline_layouts", c.passes_not_inline_layouts), - ( - "passes_not_inline_memoryless", - c.passes_not_inline_memoryless, - ), - ("passes_not_inline_actions", c.passes_not_inline_actions), - ( - "passes_not_inline_actions_dont_care_load", - c.passes_not_inline_actions_dont_care_load, - ), - ( - "passes_not_inline_actions_unequal_reach", - c.passes_not_inline_actions_unequal_reach, - ), - ( - "passes_not_inline_actions_resolve", - c.passes_not_inline_actions_resolve, - ), - ( - "passes_not_inline_actions_store", - c.passes_not_inline_actions_store, - ), - ( - "passes_not_inline_buffer_textures", - c.passes_not_inline_buffer_textures, - ), - ( - "passes_not_inline_attachments", - c.passes_not_inline_attachments, - ), - ("passes_not_inline_storage", c.passes_not_inline_storage), - ("passes_not_inline_stand_ins", c.passes_not_inline_stand_ins), - ( - "passes_not_inline_memoryless_writes", - c.passes_not_inline_memoryless_writes, - ), - ("passes_not_inline_draws", c.passes_not_inline_draws), - ("commits_handed_off", c.commits_handed_off), - ("images_started_on_the_host", c.images_started_on_the_host), - ("host_texel_copies", c.host_texel_copies), - ("staging_submissions", c.staging_submissions), - ("staging_copies_queued", c.staging_copies_queued), - ("staging_moves_queued", c.staging_moves_queued), - ("staging_flushes", c.staging_flushes), - ("staging_gpu_waits", c.staging_gpu_waits), - ("fill_queue_submissions", c.fill_queue_submissions), - ("fill_queue_waits", c.fill_queue_waits), - ("fill_queue_waits_unused", c.fill_queue_waits_unused), - ("first_work_waits", c.first_work_waits), - ("first_work_waits_unused", c.first_work_waits_unused), - ("uncached_host_images", c.uncached_host_images), - ("cpu_block_decodes", c.cpu_block_decodes), - ("block_decode_passes", c.block_decode_passes), - ("second_twins", c.second_twins), - ("second_twin_checks", c.second_twin_checks), - ("second_twin_decodes", c.second_twin_decodes), - ("queue_drains", c.queue_drains), - ("stand_in_copies_made", c.stand_in_copies_made), - ( - "stand_in_copies_made_at_draws", - c.stand_in_copies_made_at_draws, - ), - ("draw_shapes_made", c.draw_shapes_made), - ("draw_shapes_found", c.draw_shapes_found), - ("dispatch_shapes_made", c.dispatch_shapes_made), - ("dispatch_shapes_found", c.dispatch_shapes_found), - ( - "dispatch_used_resources_listed", - c.dispatch_used_resources_listed, - ), - ("resident_textures_looked_at", c.resident_textures_looked_at), - ("resident_resources_joined", c.resident_resources_joined), - ("heap_tables_worked_out", c.heap_tables_worked_out), - ("argument_samplers_taken", c.argument_samplers_taken), - ("bind_views_worked_out", c.bind_views_worked_out), - ("bind_samplers_worked_out", c.bind_samplers_worked_out), - ("bind_spaces_read", c.bind_spaces_read), - ("stage_tables_read", c.stage_tables_read), - ("stage_tables_read_in_part", c.stage_tables_read_in_part), - ("no_copy_lies_read", c.no_copy_lies_read), - ("commands_noted_as_before", c.commands_noted_as_before), - ("draws_settled", c.draws_settled), - ("two_plane_draws", c.two_plane_draws), - ("bound_notices_made", c.bound_notices_made), - ("argument_tables_retained", c.argument_tables_retained), - ("argument_objects_retained", c.argument_objects_retained), - ( - "graphics_pipelines_looked_up", - c.graphics_pipelines_looked_up, - ), - ("linear_passes_in_place", c.linear_passes_in_place), - ( - "linear_passes_through_copies", - c.linear_passes_through_copies, - ), - ("kept_bytes_passes", c.kept_bytes_passes), - ("kept_texels_passes", c.kept_texels_passes), - ("color_group_passes", c.color_group_passes), - ("color_group_twins", c.color_group_twins), - ("color_group_draws_skipped", c.color_group_draws_skipped), - ("draw_states_recorded", c.draw_states_recorded), - ("draws_pushing_set_zero", c.draws_pushing_set_zero), - ("set_zero_writes_pushed", c.set_zero_writes_pushed), - ( - "set_zero_equal_shape_switches", - c.set_zero_equal_shape_switches, - ), - ( - "set_zero_writes_on_equal_shape_switches", - c.set_zero_writes_on_equal_shape_switches, - ), - ( - "set_zero_writes_if_shapes_shared", - c.set_zero_writes_if_shapes_shared, - ), - ("dispatches_pushing_set_zero", c.dispatches_pushing_set_zero), - ( - "dispatch_set_zero_writes_pushed", - c.dispatch_set_zero_writes_pushed, - ), - ("dispatches_tracked", c.dispatches_tracked), - ("dispatch_uses_tracked", c.dispatch_uses_tracked), - ("set_zero_sets_reused", c.set_zero_sets_reused), - ("set_zero_sets_found", c.set_zero_sets_found), - ("draw_shapes_reused", c.draw_shapes_reused), - ( - "baked_sampler_dispatches_apart", - c.baked_sampler_dispatches_apart, - ), - ("host_deallocators_delayed", c.host_deallocators_delayed), - ("host_import_releases_posted", c.host_import_releases_posted), - ( - "host_import_releases_pending", - c.host_import_releases_pending, - ), - ("host_keep_alives_kept", c.host_keep_alives_kept), - ("host_keep_alives_covered", c.host_keep_alives_covered), - ("host_releases_held_inside", c.host_releases_held_inside), - ("host_mappings_queried", c.host_mappings_queried), - ("dma_buf_imports", c.dma_buf_imports), - ("dma_buf_memories_live", c.dma_buf_memories_live), - ("dma_buf_image_memories_live", c.dma_buf_image_memories_live), - ("host_imports_released", c.host_imports_released), - ("host_imports_reimported", c.host_imports_reimported), - ( - "host_imports_joined_releasable", - c.host_imports_joined_releasable, - ), - ("host_imports_resident", c.host_imports_resident), - ("host_imports_held_for_good", c.host_imports_held_for_good), - ("host_imports_lost", c.host_imports_lost), - ("host_import_fds_kept", c.host_import_fds_kept), - ("host_imports_kept_for_fds", c.host_imports_kept_for_fds), - ("host_imports_used", c.host_imports_used), - ("host_imports_read_apart", c.host_imports_read_apart), - ( - "host_imports_read_apart_address", - c.host_imports_read_apart_address, - ), - ( - "host_imports_read_apart_vk_buffer", - c.host_imports_read_apart_vk_buffer, - ), - ( - "host_imports_read_apart_binding", - c.host_imports_read_apart_binding, - ), - ( - "host_imports_read_apart_texture", - c.host_imports_read_apart_texture, - ), - ( - "host_imports_read_apart_inside", - c.host_imports_read_apart_inside, - ), - ( - "host_imports_read_apart_shared_range", - c.host_imports_read_apart_shared_range, - ), - ( - "host_imports_read_apart_heap", - c.host_imports_read_apart_heap, - ), - ( - "host_imports_read_apart_rebound", - c.host_imports_read_apart_rebound, - ), - ( - "host_imports_read_apart_unreleased", - c.host_imports_read_apart_unreleased, - ), - ("host_remaps_reported", c.host_remaps_reported), - ("host_remaps_over_imports", c.host_remaps_over_imports), - ("host_imports_remapped", c.host_imports_remapped), - ( - "host_pointer_import_bytes_made", - c.host_pointer_import_bytes_made, - ), - ("host_imports_kept_of_heap", c.host_imports_kept_of_heap), - ("host_imports_kept_rebound", c.host_imports_kept_rebound), - ( - "host_imports_rebound_unlisted", - c.host_imports_rebound_unlisted, - ), - ("host_rebind_imports_made", c.host_rebind_imports_made), - ("host_rebind_imports_covered", c.host_rebind_imports_covered), - ("host_imports_kept_pointer", c.host_imports_kept_pointer), - ( - "host_imports_kept_no_stand_in", - c.host_imports_kept_no_stand_in, - ), - ("dma_buf_sparse_buffers", c.dma_buf_sparse_buffers), - ("dma_buf_sparse_binds", c.dma_buf_sparse_binds), - ("dma_buf_images", c.dma_buf_images), - ("dma_buf_image_fallbacks", c.dma_buf_image_fallbacks), - ("modifier_feature_queries", c.modifier_feature_queries), - ("shadowed_textures", c.shadowed_textures), - ("shadows_zeroed", c.shadows_zeroed), - ("shadows_over_fresh_pages", c.shadows_over_fresh_pages), - ("fresh_page_buffers_made", c.fresh_page_buffers_made), - ("fresh_page_bytes", c.fresh_page_bytes), - ("shadow_copies", c.shadow_copies), - ("shadow_texels_copied_in", c.shadow_texels_copied_in), - ( - "shadow_texels_copied_in_images", - c.shadow_texels_copied_in_images, - ), - ( - "shadow_texels_first_copied_in", - c.shadow_texels_first_copied_in, - ), - ( - "shadow_texels_first_copied_in_images", - c.shadow_texels_first_copied_in_images, - ), - ( - "shadow_texels_first_copied_in_private_buffers", - c.shadow_texels_first_copied_in_private_buffers, - ), - ( - "shadow_texels_first_copied_in_mapped_buffers", - c.shadow_texels_first_copied_in_mapped_buffers, - ), - ( - "shadow_texels_first_copied_in_host_pages", - c.shadow_texels_first_copied_in_host_pages, - ), - ( - "shadow_texels_first_copied_in_aliased_host_pages", - c.shadow_texels_first_copied_in_aliased_host_pages, - ), - ( - "shadow_texels_first_copied_in_surfaces", - c.shadow_texels_first_copied_in_surfaces, - ), - ( - "shadow_texels_first_copied_in_large_surfaces", - c.shadow_texels_first_copied_in_large_surfaces, - ), - ( - "shadow_texels_first_copied_in_again", - c.shadow_texels_first_copied_in_again, - ), - ( - "shadow_texels_recopied_beyond_held", - c.shadow_texels_recopied_beyond_held, - ), - ( - "shadow_texels_recopied_after_changes", - c.shadow_texels_recopied_after_changes, - ), - ( - "shadow_texels_recopied_after_other_shadows", - c.shadow_texels_recopied_after_other_shadows, - ), - ( - "shadow_texels_recopied_after_two_ways_merges", - c.shadow_texels_recopied_after_two_ways_merges, - ), - ( - "shadow_texels_recopied_after_writes", - c.shadow_texels_recopied_after_writes, - ), - ( - "shadow_texels_recopied_after_writes_within", - c.shadow_texels_recopied_after_writes_within, - ), - ( - "shadow_texels_recopied_after_dropped_writes", - c.shadow_texels_recopied_after_dropped_writes, - ), - ( - "shadow_texels_bounded_copied_in", - c.shadow_texels_bounded_copied_in, - ), - ( - "shadow_texels_recopied_in_images", - c.shadow_texels_recopied_in_images, - ), - ( - "shadow_texels_recopied_in_private_buffers", - c.shadow_texels_recopied_in_private_buffers, - ), - ( - "shadow_texels_recopied_in_mapped_buffers", - c.shadow_texels_recopied_in_mapped_buffers, - ), - ( - "shadow_texels_recopied_in_host_pages", - c.shadow_texels_recopied_in_host_pages, - ), - ( - "shadow_texels_recopied_in_aliased_host_pages", - c.shadow_texels_recopied_in_aliased_host_pages, - ), - ( - "shadow_texels_recopied_in_surfaces", - c.shadow_texels_recopied_in_surfaces, - ), - ( - "shadow_texels_recopied_in_large_surfaces", - c.shadow_texels_recopied_in_large_surfaces, - ), - ("shadow_texels_copied_back", c.shadow_texels_copied_back), - ( - "shadow_copies_back_dispatched", - c.shadow_copies_back_dispatched, - ), - ("shadow_copies_in_dispatched", c.shadow_copies_in_dispatched), - ("shadow_keeps_from_staging", c.shadow_keeps_from_staging), - ( - "shadow_merge_copies_dispatched", - c.shadow_merge_copies_dispatched, - ), - ( - "shadow_merge_scratches_reused", - c.shadow_merge_scratches_reused, - ), - ( - "shadow_merge_scratches_zeroed", - c.shadow_merge_scratches_zeroed, - ), - ("row_copies", c.row_copies), - ("row_copy_regions", c.row_copy_regions), - ("row_copy_regions_most", c.row_copy_regions_most), - ("row_copies_dispatched", c.row_copies_dispatched), - ("shadow_merges_fetched", c.shadow_merges_fetched), - ( - "shadow_merges_kept_in_images", - c.shadow_merges_kept_in_images, - ), - ( - "shadow_merge_kept_images_made", - c.shadow_merge_kept_images_made, - ), - ( - "shadow_merge_kept_images_followed", - c.shadow_merge_kept_images_followed, - ), - ( - "shadow_merge_kept_images_live", - c.shadow_merge_kept_images_live, - ), - ("shadow_attachment_passes", c.shadow_attachment_passes), - ("shadow_attachment_textures", c.shadow_attachment_textures), - ( - "shadow_attachment_loads_within", - c.shadow_attachment_loads_within, - ), - ( - "shadow_attachment_loads_whole", - c.shadow_attachment_loads_whole, - ), - ("shadow_attachment_clears", c.shadow_attachment_clears), - ( - "shadow_attachment_clears_in_part", - c.shadow_attachment_clears_in_part, - ), - ( - "shadow_attachment_loads_untouched", - c.shadow_attachment_loads_untouched, - ), - ( - "shadow_attachment_tiles_covered", - c.shadow_attachment_tiles_covered, - ), - ( - "shadow_attachment_tiles_bounded", - c.shadow_attachment_tiles_bounded, - ), - ("shadows_sharing_truth", c.shadows_sharing_truth), - ("owned_descriptor_pools", c.owned_descriptor_pools), - ("shadow_texels_kept", c.shadow_texels_kept), - ("bounded_shadow_copies", c.bounded_shadow_copies), - ("views_through_swizzle", c.views_through_swizzle), - ("alpha_textures_held_in_red", c.alpha_textures_held_in_red), - ("view_shadows", c.view_shadows), - ( - "attachment_reads_through_copies", - c.attachment_reads_through_copies, - ), - ("attachment_read_splits", c.attachment_read_splits), - ("attachment_read_clears", c.attachment_read_clears), - ("fetch_draw_barriers", c.fetch_draw_barriers), - ("reading_draws_snapshotted", c.reading_draws_snapshotted), - ( - "reading_draws_snapshotted_leading", - c.reading_draws_snapshotted_leading, - ), - ("snapshot_inline_splits", c.snapshot_inline_splits), - ("reading_draws_by_coverage", c.reading_draws_by_coverage), - ( - "reading_draws_leading_covered_within", - c.reading_draws_leading_covered_within, - ), - ( - "reading_draws_leading_covered_to_half", - c.reading_draws_leading_covered_to_half, - ), - ( - "reading_draws_leading_covered_over_half", - c.reading_draws_leading_covered_over_half, - ), - ("coverage_queries", c.coverage_queries), - ("coverage_pools_made", c.coverage_pools_made), - ("reading_draws_pinned", c.reading_draws_pinned), - ("stand_ins_after_pins", c.stand_ins_after_pins), - ("feedback_loop_alias_images", c.feedback_loop_alias_images), - ("feedback_loop_shadow_images", c.feedback_loop_shadow_images), - ("depth_attachments_moved", c.depth_attachments_moved), - ("depth_instances_held", c.depth_instances_held), - ("held_depths_released", c.held_depths_released), - ("own_pixel_reads", c.own_pixel_reads), - ("replay_logs_kept", c.replay_logs_kept), - ("replay_log_bytes", c.replay_log_bytes), - ("encoders_reencoded", c.encoders_reencoded), - ("segments_recorded_again", c.segments_recorded_again), - ("replay_tables_pointed", c.replay_tables_pointed), - ("reencodes_refused", c.reencodes_refused), - ("fences_made", c.fences_made), - ("pipeline_libraries_made", c.pipeline_libraries_made), - ( - "fragment_shader_libraries_made", - c.fragment_shader_libraries_made, - ), - ("pipelines_linked", c.pipelines_linked), - ("dispatch_pipelines_pooled", c.dispatch_pipelines_pooled), - ("tile_pipelines_pooled", c.tile_pipelines_pooled), - ( - "upload_chunks_in_device_memory", - c.upload_chunks_in_device_memory, - ), - ("tile_dispatches_recorded", c.tile_dispatches_recorded), - ( - "churn_vk_buffers_destroyed", - c.object_churn.vk_buffers_destroyed, - ), - ( - "churn_vk_buffer_views_destroyed", - c.object_churn.vk_buffer_views_destroyed, - ), - ("churn_vk_memory_freed", c.object_churn.vk_memory_freed), - ("vk_images_made", c.object_churn.vk_images_made), - ("vk_buffers_made", c.object_churn.vk_buffers_made), - ("vk_image_views_made", c.object_churn.vk_image_views_made), - ( - "vk_memory_allocations", - c.object_churn.vk_memory_allocations, - ), - ("vk_image_bindings", c.object_churn.vk_image_bindings), - ("vk_buffer_bindings", c.object_churn.vk_buffer_bindings), - ( - "vk_images_made_this_thread", - c.object_churn.vk_images_made_this_thread, - ), - ( - "vk_buffers_made_this_thread", - c.object_churn.vk_buffers_made_this_thread, - ), - ( - "vk_image_views_made_this_thread", - c.object_churn.vk_image_views_made_this_thread, - ), - ( - "vk_memory_allocations_this_thread", - c.object_churn.vk_memory_allocations_this_thread, - ), - ( - "vk_image_bindings_this_thread", - c.object_churn.vk_image_bindings_this_thread, - ), - ( - "vk_buffer_bindings_this_thread", - c.object_churn.vk_buffer_bindings_this_thread, - ), - ("churn_images_in_buffers", c.object_churn.images_in_buffers), - ("churn_images_in_heaps", c.object_churn.images_in_heaps), - ("churn_images_other", c.object_churn.images_other), - ("churn_textures_image", c.object_churn.textures_image), - ("churn_textures_in_heaps", c.object_churn.textures_in_heaps), - ("churn_textures_shadow", c.object_churn.textures_shadow), - ("churn_textures_alias", c.object_churn.textures_alias), - ("churn_textures_texels", c.object_churn.textures_texels), - ("churn_buffers_recycled", c.object_churn.buffers_recycled), - ("churn_buffers_parked", c.object_churn.buffers_parked), - ("churn_buffers_evicted", c.object_churn.buffers_evicted), - ( - "churn_imports_inside_live", - c.object_churn.imports_inside_live, - ), - ( - "churn_buffers_bound_in_import", - c.object_churn.buffers_bound_in_import, - ), - ( - "churn_imports_over_ram_chunk_pages", - c.object_churn.imports_over_ram_chunk_pages, - ), - ("keeps_render_cut", c.shadow_keeps.render_cut), - ("keeps_render_cut_texels", c.shadow_keeps.render_cut_texels), - ("keeps_render_whole", c.shadow_keeps.render_whole), - ( - "keeps_render_whole_texels", - c.shadow_keeps.render_whole_texels, - ), - ("keeps_compute_cut", c.shadow_keeps.compute_cut), - ( - "keeps_compute_cut_texels", - c.shadow_keeps.compute_cut_texels, - ), - ("keeps_compute_whole", c.shadow_keeps.compute_whole), - ( - "keeps_compute_whole_texels", - c.shadow_keeps.compute_whole_texels, - ), - ("keeps_blit_cut", c.shadow_keeps.blit_cut), - ("keeps_blit_cut_texels", c.shadow_keeps.blit_cut_texels), - ("keeps_blit_whole", c.shadow_keeps.blit_whole), - ("keeps_blit_whole_texels", c.shadow_keeps.blit_whole_texels), - ] - .into_iter() - .map(|(name, count)| (name, count as f64)) - .collect() - } -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/vkfloor.rs b/crates/metal2vulkan-runtime/examples/host_ab/vkfloor.rs deleted file mode 100644 index c55c29f05..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/vkfloor.rs +++ /dev/null @@ -1,356 +0,0 @@ -//! The driver's own cost under our calls: the Vulkan calls the runtime's creation, submission and -//! event paths make, timed on the same device the runtime's side of the A/B holds -//! (`Device::raw`), which on this Mac is MoltenVK. Metal has no equivalent call, so these rows -//! are the runtime's alone; what they measure is the share of a per-call gap that belongs to the -//! driver, which we never patch, and the rest is ours. -//! -//! Each row is a `percall` group, so it is timed, attributed and counted exactly as a Metal call -//! is, and it appears in the same table with no Metal column. A row times the Vulkan calls alone: -//! no planning, no bookkeeping and no state of ours. - -use crate::gpu::Gpu; -use crate::percall::group; -use ash::vk; -use metal2vulkan_runtime as rt; -use std::ffi::c_void; - -/// The buffers and images one window makes, and a buffer's and an image's size. -const BUFFERS: usize = 16; -const IMAGES: usize = 16; -const BUFFER_BYTES: u64 = 1 << 20; -const IMAGE_SIDE: u32 = 256; - -/// The memory type of `bits` whose properties hold all of `wanted`, the first of them. -fn memory_type( - properties: &vk::PhysicalDeviceMemoryProperties, - bits: u32, - wanted: vk::MemoryPropertyFlags, -) -> Option { - (0..properties.memory_type_count).find(|index| { - bits & (1 << index) != 0 - && properties.memory_types[*index as usize] - .property_flags - .contains(wanted) - }) -} - -/// A buffer of [`BUFFER_BYTES`] as the runtime makes one for a `Shared` Metal buffer. -fn buffer_info() -> vk::BufferCreateInfo<'static> { - vk::BufferCreateInfo::default() - .size(BUFFER_BYTES) - .usage( - vk::BufferUsageFlags::STORAGE_BUFFER - | vk::BufferUsageFlags::TRANSFER_SRC - | vk::BufferUsageFlags::TRANSFER_DST, - ) - .sharing_mode(vk::SharingMode::EXCLUSIVE) -} - -/// An image as the runtime makes one for a 2D `BGRA8Unorm` texture of one level that draws render -/// into and shaders read. -fn image_info() -> vk::ImageCreateInfo<'static> { - vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(vk::Format::B8G8R8A8_UNORM) - .extent(vk::Extent3D { - width: IMAGE_SIDE, - height: IMAGE_SIDE, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::OPTIMAL) - .usage( - vk::ImageUsageFlags::SAMPLED - | vk::ImageUsageFlags::COLOR_ATTACHMENT - | vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST, - ) - .sharing_mode(vk::SharingMode::EXCLUSIVE) - .initial_layout(vk::ImageLayout::UNDEFINED) -} - -/// Time the driver's calls under the runtime's, `windows` windows each, on `device`'s own Vulkan -/// device. Nothing here submits anything or touches an object of the runtime's: the device's -/// queues are the runtime's to submit to (`CommandQueue::with_vk_queue`), so the submission path -/// has no floor row. -/// -/// # Safety -/// -/// `pages` is the host memory the no-copy group of [`crate::percall`] made its buffers over: -/// read-write pages of this process, at least eight megabytes, that outlive this call. -pub unsafe fn measure(g: &G, device: &rt::Device, windows: usize, pages: *mut u8) { - // SAFETY: the handles are used only while the device lives, and only from this thread. - let raw = unsafe { device.raw() }; - let vk = raw.device; - // SAFETY: the physical device is the device's. - let properties = unsafe { - raw.instance - .get_physical_device_memory_properties(raw.physical_device) - }; - let host = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; - - // What the rows bind into and submit with, made once. - let probe = unsafe { vk.create_buffer(&buffer_info(), None) }.expect("vkCreateBuffer"); - // SAFETY: the buffer is this device's. - let buffer_needs = unsafe { vk.get_buffer_memory_requirements(probe) }; - let buffer_type = memory_type(&properties, buffer_needs.memory_type_bits, host) - .expect("a host-visible memory type for a buffer"); - let image = unsafe { vk.create_image(&image_info(), None) }.expect("vkCreateImage"); - // SAFETY: the image is this device's. - let image_needs = unsafe { vk.get_image_memory_requirements(image) }; - let image_type = memory_type( - &properties, - image_needs.memory_type_bits, - vk::MemoryPropertyFlags::DEVICE_LOCAL, - ) - .or_else(|| { - memory_type( - &properties, - image_needs.memory_type_bits, - vk::MemoryPropertyFlags::empty(), - ) - }) - .expect("a memory type for an image"); - let stride = image_needs - .size - .next_multiple_of(image_needs.alignment.max(1)); - let block = |size: u64, index: u32| { - let info = vk::MemoryAllocateInfo::default() - .allocation_size(size) - .memory_type_index(index); - unsafe { vk.allocate_memory(&info, None) }.expect("vkAllocateMemory") - }; - let buffer_block = block(BUFFER_BYTES * BUFFERS as u64, buffer_type); - let image_block = block(stride * IMAGES as u64, image_type); - let signalled = { - let info = vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED); - unsafe { vk.create_fence(&info, None) }.expect("vkCreateFence") - }; - - // The memory a buffer and an image take. - group( - g, - "vk_create_buffer_1m", - (BUFFERS, windows), - || Vec::with_capacity(BUFFERS), - |held: &mut Vec, _| { - let buffer = unsafe { vk.create_buffer(&buffer_info(), None) }.expect("vkCreateBuffer"); - let _ = unsafe { vk.get_buffer_memory_requirements(buffer) }; - held.push(buffer); - }, - |held| { - for buffer in held { - unsafe { vk.destroy_buffer(buffer, None) }; - } - }, - ); - group( - g, - "vk_allocate_memory_1m", - (BUFFERS, windows), - || Vec::with_capacity(BUFFERS), - |held: &mut Vec, _| held.push(block(BUFFER_BYTES, buffer_type)), - |held| { - for memory in held { - unsafe { vk.free_memory(memory, None) }; - } - }, - ); - group( - g, - "vk_bind_buffer_memory", - (BUFFERS, windows), - || { - (0..BUFFERS) - .map(|_| unsafe { vk.create_buffer(&buffer_info(), None) }.expect("vkCreateBuffer")) - .collect::>() - }, - |held: &mut Vec, i| { - unsafe { vk.bind_buffer_memory(held[i], buffer_block, i as u64 * BUFFER_BYTES) } - .expect("vkBindBufferMemory") - }, - |held| { - for buffer in held { - unsafe { vk.destroy_buffer(buffer, None) }; - } - }, - ); - group( - g, - "vk_create_image_256", - (IMAGES, windows), - || Vec::with_capacity(IMAGES), - |held: &mut Vec, _| { - let image = unsafe { vk.create_image(&image_info(), None) }.expect("vkCreateImage"); - let _ = unsafe { vk.get_image_memory_requirements(image) }; - held.push(image); - }, - |held| { - for image in held { - unsafe { vk.destroy_image(image, None) }; - } - }, - ); - group( - g, - "vk_bind_image_memory_256", - (IMAGES, windows), - || { - (0..IMAGES) - .map(|_| unsafe { vk.create_image(&image_info(), None) }.expect("vkCreateImage")) - .collect::>() - }, - |held: &mut Vec, i| { - unsafe { vk.bind_image_memory(held[i], image_block, i as u64 * stride) } - .expect("vkBindImageMemory") - }, - |held| { - for image in held { - unsafe { vk.destroy_image(image, None) }; - } - }, - ); - let view_info = |image| { - vk::ImageViewCreateInfo::default() - .image(image) - .view_type(vk::ImageViewType::TYPE_2D) - .format(vk::Format::B8G8R8A8_UNORM) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }) - }; - { - let bound = unsafe { vk.create_image(&image_info(), None) }.expect("vkCreateImage"); - unsafe { vk.bind_image_memory(bound, image_block, 0) }.expect("vkBindImageMemory"); - group( - g, - "vk_create_image_view_256", - (IMAGES, windows), - || Vec::with_capacity(IMAGES), - |held: &mut Vec, _| { - held.push( - unsafe { vk.create_image_view(&view_info(bound), None) } - .expect("vkCreateImageView"), - ) - }, - |held| { - for view in held { - unsafe { vk.destroy_image_view(view, None) }; - } - }, - ); - unsafe { vk.destroy_image(bound, None) }; - } - - // The host pages a no-copy buffer lies over, imported as the runtime imports them. - let import = device.device_proc_addr(c"vkGetMemoryHostPointerPropertiesEXT"); - if let Some(import) = import { - let import: vk::PFN_vkGetMemoryHostPointerPropertiesEXT = - // SAFETY: the loader answered for exactly this entry point's name. - unsafe { std::mem::transmute(import) }; - let types = { - let mut found = vk::MemoryHostPointerPropertiesEXT::default(); - // SAFETY: the pages are host memory of this process, page-aligned. - let result = unsafe { - import( - vk.handle(), - vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT, - pages.cast::(), - &mut found, - ) - }; - assert_eq!(result, vk::Result::SUCCESS, "host pointer properties"); - found.memory_type_bits - }; - let index = memory_type(&properties, types, host).expect("a memory type for host pages"); - group( - g, - "vk_import_host_pointer_1m", - (BUFFERS.min(8), windows), - || Vec::with_capacity(8), - |held: &mut Vec, i| { - let mut info = vk::ImportMemoryHostPointerInfoEXT::default() - .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) - // SAFETY: the window's buffers lie in the pages the caller gave, one - // megabyte each ([`crate::percall`]'s no-copy group). - .host_pointer(unsafe { pages.add(i * BUFFER_BYTES as usize) }.cast()); - let allocate = vk::MemoryAllocateInfo::default() - .allocation_size(BUFFER_BYTES) - .memory_type_index(index) - .push_next(&mut info); - held.push( - unsafe { vk.allocate_memory(&allocate, None) }.expect("an imported pointer"), - ); - }, - |held| { - for memory in held { - unsafe { vk.free_memory(memory, None) }; - } - }, - ); - } - - group( - g, - "vk_wait_for_fences_signalled", - (256, windows), - || (), - |_, _| { - unsafe { vk.wait_for_fences(&[signalled], true, u64::MAX) }.expect("vkWaitForFences") - }, - drop, - ); - - // A timeline semaphore made, and its value read: what a shared event is. - group( - g, - "vk_create_semaphore_timeline", - (16, windows), - || Vec::with_capacity(16), - |held: &mut Vec, _| { - let mut timeline = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - let info = vk::SemaphoreCreateInfo::default().push_next(&mut timeline); - held.push(unsafe { vk.create_semaphore(&info, None) }.expect("vkCreateSemaphore")); - }, - |held| { - for semaphore in held { - unsafe { vk.destroy_semaphore(semaphore, None) }; - } - }, - ); - { - let mut timeline = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - let info = vk::SemaphoreCreateInfo::default().push_next(&mut timeline); - let semaphore = unsafe { vk.create_semaphore(&info, None) }.expect("vkCreateSemaphore"); - group( - g, - "vk_get_semaphore_counter_value", - (256, windows), - || (), - |_, _| { - std::hint::black_box( - unsafe { vk.get_semaphore_counter_value(semaphore) } - .expect("vkGetSemaphoreCounterValue"), - ); - }, - drop, - ); - unsafe { vk.destroy_semaphore(semaphore, None) }; - } - - unsafe { vk.destroy_fence(signalled, None) }; - unsafe { vk.destroy_buffer(probe, None) }; - unsafe { vk.destroy_image(image, None) }; - unsafe { vk.free_memory(buffer_block, None) }; - unsafe { vk.free_memory(image_block, None) }; -} diff --git a/crates/metal2vulkan-runtime/examples/host_ab/workloads.rs b/crates/metal2vulkan-runtime/examples/host_ab/workloads.rs deleted file mode 100644 index c0f2002bd..000000000 --- a/crates/metal2vulkan-runtime/examples/host_ab/workloads.rs +++ /dev/null @@ -1,3594 +0,0 @@ -//! The workloads, written once against [`Gpu`]. Each prints its measurements as result lines -//! ([`emit`]): `R`, the workload, the metric, the unit, the median, the 10th and 90th percentiles -//! and the sample count, tab-separated. - -use crate::gpu::{Format, Gpu}; -use std::path::Path; -use std::sync::mpsc; -use std::time::{Duration, Instant}; - -/// How hard the workloads run. -#[derive(Clone, Copy, Debug)] -pub struct Sizes { - /// Draws in a render pass, and dispatches in a compute encoder, of the encode workload. - pub draws: usize, - /// Timed command buffers of the encode workload, and of each phase of `fixed`. - pub timed: usize, - /// Command buffers of each latency phase. - pub latency: usize, - /// Loop iterations of the heavy shaders. - pub heavy_iterations: u32, - /// Timed command buffers of each heavy shader. - pub heavy_runs: usize, - /// Draws in the many-draws workload's frame. - pub many_draws: usize, - /// Timed frames of the compositing workload. - pub frames: usize, -} - -/// One result line (module docs) of `values`, which it sorts. -pub fn emit(workload: &str, metric: &str, unit: &str, values: &mut [f64]) { - assert!(!values.is_empty(), "{workload} {metric}: no samples"); - values.sort_by(f64::total_cmp); - let at = |p: f64| values[((values.len() - 1) as f64 * p).round() as usize]; - println!( - "R\t{workload}\t{metric}\t{unit}\t{:.3}\t{:.3}\t{:.3}\t{}", - at(0.5), - at(0.1), - at(0.9), - values.len() - ); -} - -fn us(d: Duration) -> f64 { - d.as_secs_f64() * 1e6 -} - -fn ms(d: Duration) -> f64 { - d.as_secs_f64() * 1e3 -} - -/// The process's CPU time so far (user and system, every thread). -#[cfg(unix)] -pub fn process_cpu() -> Duration { - // SAFETY: `getrusage` writes the struct it is given. - let usage = unsafe { - let mut usage = std::mem::zeroed::(); - assert_eq!(libc::getrusage(libc::RUSAGE_SELF, &mut usage), 0); - usage - }; - let tv = |t: libc::timeval| Duration::new(t.tv_sec as u64, t.tv_usec as u32 * 1000); - tv(usage.ru_utime) + tv(usage.ru_stime) -} - -/// The process's CPU time so far (user and system, every thread): its kernel and user times -/// (`GetProcessTimes`), in 100 ns units. -#[cfg(windows)] -pub fn process_cpu() -> Duration { - Duration::from_nanos({ - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: this process's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetProcessTimes(GetCurrentProcess(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetProcessTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 - }) -} - -/// The calling thread's CPU time so far. -#[cfg(unix)] -pub fn thread_cpu() -> Duration { - // SAFETY: `clock_gettime` writes the struct it is given. - let spec = unsafe { - let mut spec = std::mem::zeroed::(); - assert_eq!( - libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut spec), - 0 - ); - spec - }; - Duration::new(spec.tv_sec as u64, spec.tv_nsec as u32) -} - -/// The calling thread's CPU time so far: its kernel and user times (`GetThreadTimes`), in 100 ns -/// units. -#[cfg(windows)] -pub fn thread_cpu() -> Duration { - Duration::from_nanos({ - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetThreadTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 - }) -} - -/// The rectangles' buffers: [`RECTS`] rectangles each, one every [`RECT_STRIDE`] bytes. -const RECT_BUFFERS: usize = 4; -const RECTS: usize = 1024; -const RECT_STRIDE: usize = 256; -/// The small textures the draws take in turn, and their side. -const TEXTURES: usize = 16; -const TEXTURE_SIDE: usize = 64; -/// The small draws' target's side. -pub const TARGET_SIDE: usize = 512; -/// The heavy fragment's target's side, its texture's side, and the heavy kernel's texture's. -const HEAVY_TARGET_SIDE: usize = 2048; -const HEAVY_TEXTURE_SIDE: usize = 1024; -const KERNEL_TEXTURE_SIDE: usize = 256; -/// The heavy kernel's grid: threadgroups of 256 threads. -const HEAVY_GROUPS: usize = 4096; -/// The feature kernels (`host_ab.metal`). -const FEATURES: [&str; 9] = [ - "k_fma", - "k_sin", - "k_half", - "k_constant", - "k_device", - "k_texture", - "k_texture_float", - "k_threadgroup_float", - "k_threadgroup_half", -]; -const HEAVY_THREADS: usize = 256; -/// The heavy and feature kernels' output: one `float4` per thread. -const HEAVY_OUT_BYTES: usize = HEAVY_GROUPS * HEAVY_THREADS * 16; - -/// What the workloads draw and dispatch with, made once per process. -pub struct Scene { - /// `quad_vertex` + `textured_fragment` into `BGRA8Unorm`, without and with blending. - pub textured: [G::RenderPipeline; 2], - /// `quad_vertex` + `icb_draw_fragment` (a fill of its own color, no texture) into - /// `BGRA8Unorm`, blending. - pub solid: G::RenderPipeline, - /// `quad_vertex` + `heavy_fragment` into `RGBA16Float`. - pub heavy_fragment: G::RenderPipeline, - pub heavy_kernel: G::ComputePipeline, - /// The feature kernels (`host_ab.metal`), by name. - pub features: Vec<(&'static str, G::ComputePipeline)>, - /// `tiny_kernel` and `tiny_kernel_b`. - pub tiny: [G::ComputePipeline; 2], - pub textures: Vec, - pub heavy_texture: G::Texture, - pub kernel_texture: G::Texture, - pub sampler: G::Sampler, - pub target: G::Texture, - pub heavy_target: G::Texture, - pub rects: Vec, - /// One rectangle over the whole target. - pub full: G::Buffer, - /// The heavy fragment's parameters, and the heavy kernel's (16 times the iterations). - pub params: G::Buffer, - pub kernel_params: G::Buffer, - pub tiny_out: G::Buffer, - pub tiny_values: G::Buffer, - pub heavy_out: G::Buffer, - /// The feature kernels' `src`. - pub heavy_in: G::Buffer, - pub fill: G::Buffer, -} - -/// A 32 by 32 grid of small rectangles over the target, each at its own 256-byte offset (a -/// constant buffer's offset alignment), in the order of rectangle buffer `b`. -fn rect_bytes(b: usize) -> Vec { - let mut bytes = vec![0u8; RECTS * RECT_STRIDE]; - for r in 0..RECTS { - let cell = (r + b * 7) % RECTS; - let (x, y) = ((cell % 32) as f32, (cell / 32) as f32); - let at = |v: f32| v / 16.0 - 1.0; - let rect = floats(&[at(x), at(y), at(x + 0.5), at(y + 0.5)]); - bytes[r * RECT_STRIDE..r * RECT_STRIDE + 16].copy_from_slice(&rect); - } - bytes -} - -fn texels(side: usize, seed: u8) -> Vec { - (0..side * side) - .flat_map(|i| { - let (x, y) = ((i % side) as u8, (i / side) as u8); - [x.wrapping_mul(3) ^ seed, y.wrapping_mul(5), x ^ y, 255] - }) - .collect() -} - -fn floats(values: &[f32]) -> Vec { - values.iter().flat_map(|v| v.to_le_bytes()).collect() -} - -/// The heavy shaders' `HeavyParams`: 64 `float4`, the iterations and a scale. -pub fn params_bytes(iterations: u32) -> Vec { - let mut bytes = Vec::with_capacity(1040); - for i in 0..64 { - let f = i as f32; - bytes.extend(floats(&[ - 0.97 - f * 0.001, - 1.3 + f * 0.01, - 0.25 + f * 0.002, - 0.003 * f, - ])); - } - bytes.extend(iterations.to_le_bytes()); - bytes.extend(0.5f32.to_le_bytes()); - bytes.resize(1040, 0); - bytes -} - -impl Scene { - pub fn new(g: &G, library: &G::Library, sizes: &Sizes) -> Scene { - let textured = [ - g.render_pipeline( - library, - "quad_vertex", - "textured_fragment", - Format::Bgra8, - false, - ), - g.render_pipeline( - library, - "quad_vertex", - "textured_fragment", - Format::Bgra8, - true, - ), - ]; - let solid = g.render_pipeline( - library, - "quad_vertex", - "icb_draw_fragment", - Format::Bgra8, - true, - ); - let heavy_fragment = g.render_pipeline( - library, - "quad_vertex", - "heavy_fragment", - Format::Rgba16Float, - false, - ); - let heavy_kernel = g.compute_pipeline(library, "heavy_kernel"); - let features = FEATURES - .iter() - .map(|&name| (name, g.compute_pipeline(library, name))) - .collect(); - let tiny = [ - g.compute_pipeline(library, "tiny_kernel"), - g.compute_pipeline(library, "tiny_kernel_b"), - ]; - let shader_texture = |side: usize, seed: u8| { - let texture = g.texture(Format::Rgba8, side, side, false); - g.replace_region(&texture, (side, side), &texels(side, seed), side * 4); - texture - }; - let textures = (0..TEXTURES) - .map(|n| shader_texture(TEXTURE_SIDE, n as u8 * 16)) - .collect(); - let rects = (0..RECT_BUFFERS) - .map(|b| g.buffer_with(&rect_bytes(b))) - .collect(); - Scene { - textured, - solid, - heavy_fragment, - heavy_kernel, - features, - tiny, - textures, - heavy_texture: shader_texture(HEAVY_TEXTURE_SIDE, 7), - kernel_texture: shader_texture(KERNEL_TEXTURE_SIDE, 9), - sampler: g.sampler(true), - target: g.texture(Format::Bgra8, TARGET_SIDE, TARGET_SIDE, true), - heavy_target: g.texture( - Format::Rgba16Float, - HEAVY_TARGET_SIDE, - HEAVY_TARGET_SIDE, - true, - ), - rects, - full: g.buffer_with(&floats(&[-1.0, -1.0, 1.0, 1.0])), - params: g.buffer_with(¶ms_bytes(sizes.heavy_iterations)), - kernel_params: g.buffer_with(¶ms_bytes(sizes.heavy_iterations * 16)), - tiny_out: g.buffer(RECTS * RECT_STRIDE), - tiny_values: g.buffer_with(&vec![1u8; RECTS * RECT_STRIDE]), - heavy_out: g.buffer(HEAVY_OUT_BYTES), - heavy_in: g.buffer_with(&vec![0x3c; HEAVY_OUT_BYTES]), - fill: g.buffer(4096), - } - } -} - -/// What the encode workload changes between draws (and dispatches). -#[derive(Clone, Copy)] -enum Churn { - /// Nothing: every draw the same. - Static, - /// The vertex buffer's offset alone (`setVertexBufferOffset:atIndex:`). - Offset, - /// The vertex buffer (another buffer and offset) and the fragment texture. - Bind, - /// As `Bind`, and the pipeline state switched between two. - Pipeline, - /// As `Pipeline`, in render passes of [`PASS_DRAWS`] draws each (the pass loads the target, - /// the first clears it): a window server's few draws a pass, each binding its own. - Passes, - /// As `Bind`, in render passes of [`COMPOSITOR_DRAWS`] draws each, every [`COMPOSITOR_RUN`] - /// draws drawn by the next of three pipeline states (the two textured states and the solid - /// one): a window server's frame of a few hundred draws a pass, each binding its own buffer - /// and texture, its few pipeline states the same every frame. - Compositor, - /// Each draw's own rectangle, at the next [`RECT_STRIDE`] bytes of no-copy buffers over host - /// pages of [`HOST_CHUNK`] bytes each (`setVertexBuffer:offset:atIndex:` of the chunk at the - /// offset): a guest's `setVertexBytes:` as its upload chunks hand it on. - Host, -} - -/// The bytes of each no-copy buffer [`Churn::Host`] draws from, a guest's upload chunk: 256 -/// draws' rectangles. -const HOST_CHUNK: usize = 64 * 1024; - -/// The draws of each pass of [`Churn::Passes`]. -const PASS_DRAWS: usize = 3; - -/// The draws of each pass of [`Churn::Compositor`], and of each run of one pipeline state there. -const COMPOSITOR_DRAWS: usize = 300; -const COMPOSITOR_RUN: usize = 10; - -impl Churn { - fn name(self) -> &'static str { - match self { - Churn::Static => "static", - Churn::Offset => "offset", - Churn::Bind => "bind", - Churn::Pipeline => "pipeline", - Churn::Passes => "passes", - Churn::Compositor => "compositor", - Churn::Host => "host", - } - } - - /// The draws of each of its render passes, where it draws in several. - fn pass_draws(self) -> Option { - match self { - Churn::Passes => Some(PASS_DRAWS), - Churn::Compositor => Some(COMPOSITOR_DRAWS), - _ => None, - } - } -} - -/// Encode one render pass of `draws` small draws with `churn` (module docs of `main.rs`), the -/// host churn's from `chunks` ([`host_chunks`]). -fn encode_draws( - g: &G, - s: &Scene, - command_buffer: &G::CommandBuffer, - (draws, churn): (usize, Churn), - chunks: &[G::Buffer], -) { - let mut encoder = g.render_encoder(command_buffer, &s.target, true); - g.set_render_pipeline(&mut encoder, &s.textured[0]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - g.set_vertex_buffer(&mut encoder, &s.rects[0], 0, 0); - g.set_fragment_texture(&mut encoder, &s.textures[0], 0); - for draw in 0..draws { - let new_pass = churn - .pass_draws() - .is_some_and(|per| draw > 0 && draw % per == 0); - if new_pass { - g.end_render(encoder); - encoder = g.render_encoder(command_buffer, &s.target, false); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - } - if matches!(churn, Churn::Compositor) && (new_pass || draw % COMPOSITOR_RUN == 0) { - let states = [&s.textured[0], &s.textured[1], &s.solid]; - g.set_render_pipeline(&mut encoder, states[(draw / COMPOSITOR_RUN) % states.len()]); - } - if matches!(churn, Churn::Offset) { - g.set_vertex_buffer_offset(&mut encoder, (draw % RECTS) * RECT_STRIDE, 0); - } - if matches!(churn, Churn::Host) { - let at = draw * RECT_STRIDE; - g.set_vertex_buffer(&mut encoder, &chunks[at / HOST_CHUNK], at % HOST_CHUNK, 0); - } - if matches!( - churn, - Churn::Bind | Churn::Pipeline | Churn::Passes | Churn::Compositor - ) { - let buffer = &s.rects[(draw / 7) % RECT_BUFFERS]; - g.set_vertex_buffer(&mut encoder, buffer, (draw % RECTS) * RECT_STRIDE, 0); - g.set_fragment_texture(&mut encoder, &s.textures[draw % TEXTURES], 0); - } - if matches!(churn, Churn::Pipeline | Churn::Passes) { - g.set_render_pipeline(&mut encoder, &s.textured[draw % 2]); - } - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); -} - -/// [`Churn::Host`]'s chunks for `draws` draws: no-copy buffers of [`HOST_CHUNK`] bytes each over -/// one mapping of host pages, draw `d`'s rectangle at `d * RECT_STRIDE` bytes of them end to end. -fn host_chunks(g: &G, draws: usize) -> Vec { - let chunks = (draws * RECT_STRIDE).div_ceil(HOST_CHUNK).max(1); - let rects = rect_bytes(0); - // SAFETY: kept for the process's life, past every buffer over it. - let pages = unsafe { host_pages(chunks * HOST_CHUNK) }; - // SAFETY: the mapping's bytes, read-write, which nothing else holds yet. - let bytes = unsafe { std::slice::from_raw_parts_mut(pages, chunks * HOST_CHUNK) }; - for (at, rect) in bytes - .as_chunks_mut::() - .0 - .iter_mut() - .enumerate() - { - let r = at % RECTS; - rect.copy_from_slice(&rects[r * RECT_STRIDE..][..RECT_STRIDE]); - } - (0..chunks) - .map(|chunk| { - // SAFETY: page-aligned read-write bytes of the mapping, which outlives the buffer. - unsafe { g.buffer_no_copy(pages.add(chunk * HOST_CHUNK), HOST_CHUNK) } - }) - .collect() -} - -/// Encode one compute encoder of `dispatches` small dispatches, changing the buffers' offsets and -/// the pipeline state at each where `churn`. -fn encode_dispatches( - g: &G, - s: &Scene, - command_buffer: &G::CommandBuffer, - dispatches: usize, - churn: DispatchChurn, -) { - let mut encoder = g.compute_encoder(command_buffer); - g.set_compute_pipeline(&mut encoder, &s.tiny[0]); - g.set_buffer(&mut encoder, &s.tiny_out, 0, 0); - g.set_buffer(&mut encoder, &s.tiny_values, 0, 1); - for dispatch in 0..dispatches { - if churn == DispatchChurn::Churn { - g.set_compute_pipeline(&mut encoder, &s.tiny[dispatch % 2]); - } - if churn != DispatchChurn::Static { - let offset = (dispatch % RECTS) * RECT_STRIDE; - g.set_buffer(&mut encoder, &s.tiny_out, offset, 0); - g.set_buffer(&mut encoder, &s.tiny_values, offset, 1); - } - g.dispatch(&mut encoder, 1, 64); - } - g.end_compute(encoder); -} - -/// What the encode workload's dispatches change between them. -#[derive(Clone, Copy, PartialEq, Eq)] -enum DispatchChurn { - /// Nothing. - Static, - /// Both buffers' offsets. - Offsets, - /// The pipeline state and both buffers' offsets. - Churn, -} - -impl DispatchChurn { - fn name(self) -> &'static str { - match self { - DispatchChurn::Static => "static", - DispatchChurn::Offsets => "offsets", - DispatchChurn::Churn => "churn", - } - } -} - -/// Encode the encode workload's draws with `churn` on `threads` threads at once, each through its -/// own queue (`Gpu::with_own_queue`) into its own target, of its own rectangles, texture and -/// sampler, through `shared` where given, else through a pipeline state of its own made like it, `rounds` command buffers of `draws` draws -/// each, one in flight while the next encodes: the draws a second of all of them together, from -/// their common start to the last one's last commit, the mean of each thread's CPU time per draw, -/// and the process's CPU time per draw (module docs of `main.rs`). -fn threaded_draws( - g: &G, - library: &G::Library, - (threads, shared): (usize, Option<&G::RenderPipeline>), - (rounds, draws, churn): (usize, usize, Churn), -) -> (f64, f64, f64) { - let start = std::sync::Barrier::new(threads + 1); - let (per_thread, wall, cpu) = std::thread::scope(|scope| { - let workers: Vec<_> = (0..threads) - .map(|_| { - let start = &start; - scope.spawn(move || { - let g = g.with_own_queue(); - let target = g.texture(Format::Bgra8, 256, 256, true); - let rects = g.buffer_with(&rect_bytes(0)); - let texture = g.texture(Format::Rgba8, TEXTURE_SIDE, TEXTURE_SIDE, false); - let side = (TEXTURE_SIDE, TEXTURE_SIDE); - g.replace_region(&texture, side, &texels(TEXTURE_SIDE, 0), TEXTURE_SIDE * 4); - let sampler = g.sampler(true); - let own = shared.is_none().then(|| { - let (vertex, fragment) = ("quad_vertex", "textured_fragment"); - g.render_pipeline(library, vertex, fragment, Format::Bgra8, false) - }); - let state = shared.or(own.as_ref()).expect("a pipeline state"); - let encode = |command_buffer: &G::CommandBuffer| { - let mut encoder = g.render_encoder(command_buffer, &target, true); - g.set_render_pipeline(&mut encoder, state); - g.set_fragment_sampler(&mut encoder, &sampler, 0); - g.set_vertex_buffer(&mut encoder, &rects, 0, 0); - g.set_fragment_texture(&mut encoder, &texture, 0); - for draw in 0..draws { - if matches!(churn, Churn::Offset) { - let offset = (draw % RECTS) * RECT_STRIDE; - g.set_vertex_buffer_offset(&mut encoder, offset, 0); - } - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - }; - // Warm: its pipeline made, its queue's first command buffers behind it. - for _ in 0..3 { - g.pool(|| { - let command_buffer = g.command_buffer(); - encode(&command_buffer); - g.commit(&command_buffer); - g.wait(&command_buffer); - }); - } - start.wait(); - let cpu0 = thread_cpu(); - let mut in_flight: Option = None; - for _ in 0..rounds { - g.pool(|| { - let command_buffer = g.command_buffer(); - encode(&command_buffer); - if let Some(last) = in_flight.take() { - g.wait(&last); - } - g.commit(&command_buffer); - in_flight = Some(command_buffer); - }); - } - let (done, cpu) = (Instant::now(), thread_cpu() - cpu0); - if let Some(last) = in_flight.take() { - g.wait(&last); - } - (done, cpu) - }) - }) - .collect(); - start.wait(); - let (t0, cpu0) = (Instant::now(), process_cpu()); - let ended: Vec<(Instant, Duration)> = workers - .into_iter() - .map(|worker| worker.join().expect("a drawing thread")) - .collect(); - let cpu = process_cpu() - cpu0; - let last = ended.iter().map(|(done, _)| *done).max().expect("a thread"); - let per_thread: Duration = ended.iter().map(|(_, cpu)| *cpu).sum(); - (per_thread / threads as u32, last - t0, cpu) - }); - let each = (rounds * draws) as f64; - let all = each * threads as f64; - ( - all / wall.as_secs_f64(), - us(per_thread) / each, - us(cpu) / all, - ) -} - -/// The thread-scaling workload, its shared pipeline state `shared` (module docs of `main.rs`). -pub fn threads(g: &G, library: &G::Library, shared: &G::RenderPipeline, sizes: &Sizes) { - let rounds = (sizes.timed / 4).max(8); - for churn in [Churn::Static, Churn::Offset] { - for (pso, shared) in [("shared", Some(shared)), ("each", None)] { - for threads in [1, 2, 4, 8] { - let (mut rate, mut thread, mut process) = (vec![], vec![], vec![]); - for _ in 0..3 { - let run = (rounds, sizes.draws, churn); - let (r, t, p) = threaded_draws(g, library, (threads, shared), run); - rate.push(r / 1e6); - thread.push(t); - process.push(p); - } - let name = format!("draw_{}_{pso}_{threads}t", churn.name()); - emit("threads", &format!("{name}_rate"), "Mdraws/s", &mut rate); - emit( - "threads", - &format!("{name}_thread_cpu"), - "us/draw", - &mut thread, - ); - emit( - "threads", - &format!("{name}_process_cpu"), - "us/draw", - &mut process, - ); - } - } - } -} - -/// The CPU cost of encoding: per draw and per dispatch, on the encoding thread (wall) and in the -/// whole process (CPU time of every thread, from the command buffer's creation until its wait -/// returned, which takes in work moved off the encoding thread to commit or to other threads). -pub fn encode( - g: &G, - s: &Scene, - library: &G::Library, - sizes: &Sizes, - variants: &[String], -) { - let n = sizes.draws; - let runs = |name: String| variants.is_empty() || variants.contains(&name); - for churn in [ - Churn::Static, - Churn::Offset, - Churn::Bind, - Churn::Pipeline, - Churn::Passes, - Churn::Compositor, - Churn::Host, - ] { - if !runs(format!("draw_{}", churn.name())) { - continue; - } - let chunks = match churn { - Churn::Host => host_chunks(g, n), - _ => vec![], - }; - let (mut wall, mut cpu, mut commit, mut total) = (vec![], vec![], vec![], vec![]); - for run in 0..sizes.timed + 3 { - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - encode_draws(g, s, &command_buffer, (n, churn), &chunks); - let t1 = Instant::now(); - g.commit(&command_buffer); - let t2 = Instant::now(); - g.wait(&command_buffer); - let t3 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 3 { - wall.push(us(t1 - t0) / n as f64); - cpu.push(us(cpu1 - cpu0) / n as f64); - commit.push(us(t2 - t1)); - total.push(ms(t3 - t0)); - } - }); - } - let name = churn.name(); - emit( - "encode", - &format!("draw_{name}_encode"), - "us/draw", - &mut wall, - ); - emit( - "encode", - &format!("draw_{name}_process_cpu"), - "us/draw", - &mut cpu, - ); - emit( - "encode", - &format!("draw_{name}_commit_call"), - "us", - &mut commit, - ); - emit("encode", &format!("draw_{name}_cb_total"), "ms", &mut total); - } - for churn in [ - DispatchChurn::Static, - DispatchChurn::Offsets, - DispatchChurn::Churn, - ] { - if !runs(format!("dispatch_{}", churn.name())) { - continue; - } - let (mut wall, mut cpu, mut total) = (vec![], vec![], vec![]); - let mut counts = None; - for run in 0..sizes.timed + 3 { - if run == 3 { - counts = Some(g.work_counts()); - } - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - encode_dispatches(g, s, &command_buffer, n, churn); - let t1 = Instant::now(); - g.commit(&command_buffer); - g.wait(&command_buffer); - let t3 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 3 { - wall.push(us(t1 - t0) / n as f64); - cpu.push(us(cpu1 - cpu0) / n as f64); - total.push(ms(t3 - t0)); - } - }); - } - let name = churn.name(); - emit( - "encode", - &format!("dispatch_{name}_encode"), - "us/dispatch", - &mut wall, - ); - emit( - "encode", - &format!("dispatch_{name}_process_cpu"), - "us/dispatch", - &mut cpu, - ); - emit( - "encode", - &format!("dispatch_{name}_cb_total"), - "ms", - &mut total, - ); - let dispatches = (sizes.timed * n) as f64; - emit_memo_shares(g, counts, dispatches, &format!("dispatch_{name}")); - } - encode_resident(g, s, sizes, &runs); - encode_handles(g, s, library, sizes, &runs); -} - -/// The encode workload's `dispatch_handles` variant: a compute encoder of `draws` -/// single-threadgroup dispatches of `tiny_handle_kernel`, which reads a texture made resident -/// through its handle in an argument buffer, so each dispatch binds the device's texture table. -/// Per dispatch: the encoding thread's wall time and the process's CPU time. -fn encode_handles( - g: &G, - s: &Scene, - library: &G::Library, - sizes: &Sizes, - runs: &dyn Fn(String) -> bool, -) { - if !runs("dispatch_handles".to_owned()) { - return; - } - let n = sizes.draws; - let pipeline = g.compute_pipeline(library, "tiny_handle_kernel"); - let texture = &s.textures[0]; - let handles = g.buffer_with(&g.texture_id(texture).to_le_bytes()); - let (mut wall, mut cpu) = (vec![], vec![]); - let mut counts = None; - for run in 0..sizes.timed + 3 { - if run == 3 { - counts = Some(g.work_counts()); - } - g.pool(|| { - let cpu0 = process_cpu(); - let command_buffer = g.command_buffer(); - let mut encoder = g.compute_encoder(&command_buffer); - g.set_compute_pipeline(&mut encoder, &pipeline); - g.set_buffer(&mut encoder, &s.tiny_out, 0, 0); - g.set_buffer(&mut encoder, &handles, 0, 1); - g.use_textures(&mut encoder, &[texture]); - let t0 = Instant::now(); - for _ in 0..n { - g.dispatch(&mut encoder, 1, 64); - } - let t1 = Instant::now(); - g.end_compute(encoder); - g.commit(&command_buffer); - g.wait(&command_buffer); - let cpu1 = process_cpu(); - if run >= 3 { - wall.push(us(t1 - t0) / n as f64); - cpu.push(us(cpu1 - cpu0) / n as f64); - } - }); - } - emit( - "encode", - "dispatch_handles_encode", - "us/dispatch", - &mut wall, - ); - emit( - "encode", - "dispatch_handles_process_cpu", - "us/dispatch", - &mut cpu, - ); - let dispatches = (sizes.timed * n) as f64; - emit_memo_shares(g, counts, dispatches, "dispatch_handles"); -} - -/// The resident buffers of the encode workload's `dispatch_resident` variants, of 256 bytes each. -const RESIDENT: usize = 4096; - -/// The encode workload's `dispatch_resident_*` variants: a compute encoder whose pipeline state -/// and buffers are set, one `useResources:count:usage:` (reading) of none, 1, 256 or 4096 -/// buffers, or of one buffer 4096 times (`same_4096`), then `draws` single-threadgroup dispatches -/// of the tiny kernel; `moving_0`, `_16`, `_256` and `_4096` as many after none, 16, 256 or 4096, -/// each dispatch after the output buffer's offset moved; `textures_256` and `_4096` as many after -/// 256 or 4096 4-by-4 textures made resident. Per variant: the `useResources` call, the encoding -/// thread's wall time per dispatch, the process's CPU time per dispatch, and the command buffer's -/// whole time. -fn encode_resident(g: &G, s: &Scene, sizes: &Sizes, runs: &dyn Fn(String) -> bool) { - // (name, resident buffers or textures, one buffer `count` times, the output's offset moving, - // textures). - let variants = [ - ("0", 0, false, false, false), - ("1", 1, false, false, false), - ("256", 256, false, false, false), - ("4096", 4096, false, false, false), - ("same_4096", 4096, true, false, false), - ("moving_0", 0, false, true, false), - ("moving_16", 16, false, true, false), - ("moving_256", 256, false, true, false), - ("moving_4096", 4096, false, true, false), - ("textures_256", 256, false, false, true), - ("textures_4096", 4096, false, false, true), - ]; - let wanted: Vec<_> = (variants.iter()) - .filter(|(name, ..)| runs(format!("dispatch_resident_{name}"))) - .collect(); - if wanted.is_empty() { - return; - } - let n = sizes.draws; - let resident: Vec = (0..RESIDENT).map(|_| g.buffer(256)).collect(); - let textures: Vec = match wanted.iter().any(|(.., textures)| *textures) { - true => (0..RESIDENT) - .map(|_| g.texture(Format::Rgba8, 4, 4, false)) - .collect(), - false => Vec::new(), - }; - for &&(name, count, same, moving, of_textures) in &wanted { - let list: Vec<&G::Buffer> = match (same, of_textures) { - (_, true) => Vec::new(), - (true, false) => vec![&resident[0]; count], - (false, false) => resident[..count].iter().collect(), - }; - let texture_list: Vec<&G::Texture> = match of_textures { - true => textures[..count].iter().collect(), - false => Vec::new(), - }; - let (mut using, mut wall, mut cpu, mut total) = (vec![], vec![], vec![], vec![]); - let mut ending = vec![]; - let mut counts = None; - for run in 0..sizes.timed + 3 { - if run == 3 { - counts = Some(g.work_counts()); - } - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - let mut encoder = g.compute_encoder(&command_buffer); - g.set_compute_pipeline(&mut encoder, &s.tiny[0]); - g.set_buffer(&mut encoder, &s.tiny_out, 0, 0); - g.set_buffer(&mut encoder, &s.tiny_values, 0, 1); - let t1 = Instant::now(); - match of_textures { - true => g.use_textures(&mut encoder, &texture_list), - false => g.use_buffers(&mut encoder, &list), - } - let t2 = Instant::now(); - for dispatch in 0..n { - if moving { - let offset = (dispatch % RECTS) * RECT_STRIDE; - g.set_buffer(&mut encoder, &s.tiny_out, offset, 0); - } - g.dispatch(&mut encoder, 1, 64); - } - let t3 = Instant::now(); - g.end_compute(encoder); - let ended = Instant::now(); - g.commit(&command_buffer); - g.wait(&command_buffer); - let t4 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 3 { - using.push(us(t2 - t1)); - ending.push(us(ended - t3)); - wall.push(us(t3 - t2) / n as f64); - cpu.push(us(cpu1 - cpu0) / n as f64); - total.push(ms(t4 - t0)); - } - }); - } - let metric = |what: &str| format!("dispatch_resident_{name}_{what}"); - emit("encode", &metric("use_call"), "us", &mut using); - emit("encode", &metric("end_call"), "us", &mut ending); - emit("encode", &metric("encode"), "us/dispatch", &mut wall); - emit("encode", &metric("process_cpu"), "us/dispatch", &mut cpu); - emit("encode", &metric("cb_total"), "ms", &mut total); - let dispatches = (sizes.timed * n) as f64; - emit_memo_shares(g, counts, dispatches, &format!("dispatch_resident_{name}")); - } -} - -/// The share of `dispatches` since `counts` the runtime took as settled before -/// (`dispatches_settled_as_before`) and as planned before (`dispatches_planned_as_before`), and -/// the reads of a layout for the device's tables per dispatch (`heap_tables_worked_out`), as the -/// encode workload's `_rt_*` lines. -fn emit_memo_shares( - g: &G, - counts: Option>, - dispatches: f64, - variant: &str, -) { - let after = g.work_counts(); - for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) { - let metric = match *counted { - "dispatches_settled_as_before" => "rt_settled_as_before", - "dispatches_planned_as_before" => "rt_planned_as_before", - "heap_tables_worked_out" => "rt_heap_tables_worked_out", - _ => continue, - }; - let share = (now - before) / dispatches; - emit( - "encode", - &format!("{variant}_{metric}"), - "share", - &mut [share], - ); - } -} - -/// The fixed costs: a command buffer's creation, an encoder of one command (opened, bound, one -/// command, ended), and the commit call. -pub fn fixed(g: &G, s: &Scene, sizes: &Sizes) { - const ENCODERS: usize = 10; - let (mut create, mut render, mut compute, mut blit, mut commit) = - (vec![], vec![], vec![], vec![], vec![]); - for run in 0..sizes.timed + 3 { - g.pool(|| { - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - let t1 = Instant::now(); - let mut times = [vec![], vec![], vec![]]; - for _ in 0..ENCODERS { - let a = Instant::now(); - let mut encoder = g.render_encoder(&command_buffer, &s.target, false); - g.set_render_pipeline(&mut encoder, &s.textured[0]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - g.set_vertex_buffer(&mut encoder, &s.rects[0], 0, 0); - g.set_fragment_texture(&mut encoder, &s.textures[0], 0); - g.draw_strip(&mut encoder, 4); - g.end_render(encoder); - let b = Instant::now(); - let mut encoder = g.compute_encoder(&command_buffer); - g.set_compute_pipeline(&mut encoder, &s.tiny[0]); - g.set_buffer(&mut encoder, &s.tiny_out, 0, 0); - g.set_buffer(&mut encoder, &s.tiny_values, 0, 1); - g.dispatch(&mut encoder, 1, 64); - g.end_compute(encoder); - let c = Instant::now(); - g.fill(&command_buffer, &s.fill, 256); - let d = Instant::now(); - times[0].push(us(b - a)); - times[1].push(us(c - b)); - times[2].push(us(d - c)); - } - let t2 = Instant::now(); - g.commit(&command_buffer); - let t3 = Instant::now(); - g.wait(&command_buffer); - let _ = t2; - if run >= 3 { - create.push(us(t1 - t0)); - render.extend(×[0]); - compute.extend(×[1]); - blit.extend(×[2]); - commit.push(us(t3 - t2)); - } - }); - } - emit("fixed", "command_buffer_create", "us", &mut create); - emit("fixed", "render_encoder_1draw", "us", &mut render); - emit("fixed", "compute_encoder_1dispatch", "us", &mut compute); - emit("fixed", "blit_encoder_1fill", "us", &mut blit); - emit("fixed", "commit_call_30_encoders", "us", &mut commit); -} - -/// What a latency command buffer holds. -#[derive(Clone, Copy)] -enum Tiny { - Empty, - Fill, - Dispatch, - Draw, -} - -fn encode_tiny(g: &G, s: &Scene, command_buffer: &G::CommandBuffer, tiny: Tiny) { - match tiny { - Tiny::Empty => {} - Tiny::Fill => g.fill(command_buffer, &s.fill, 256), - Tiny::Dispatch => encode_dispatches(g, s, command_buffer, 1, DispatchChurn::Static), - Tiny::Draw => encode_draws(g, s, command_buffer, (1, Churn::Static), &[]), - } -} - -/// Submit-to-completion latency of a tiny command buffer, one in flight: from the commit call -/// until `waitUntilCompleted` returns, and until a completed handler runs. -pub fn latency(g: &G, s: &Scene, sizes: &Sizes) { - for (name, tiny) in [ - ("empty", Tiny::Empty), - ("fill", Tiny::Fill), - ("dispatch", Tiny::Dispatch), - ("draw", Tiny::Draw), - ] { - let (mut wait, mut commit) = (vec![], vec![]); - // The host-clock timeline: commit to kernel start, kernel start to end, kernel end to - // GPU start, GPU start to end, GPU end to the wait's return. - let mut split: [Vec; 5] = Default::default(); - for run in 0..sizes.latency + 10 { - g.pool(|| { - let command_buffer = g.command_buffer(); - encode_tiny(g, s, &command_buffer, tiny); - let h0 = crate::host_seconds(); - let t0 = Instant::now(); - g.commit(&command_buffer); - let t1 = Instant::now(); - g.wait(&command_buffer); - let t2 = Instant::now(); - let h2 = crate::host_seconds(); - if run >= 10 { - commit.push(us(t1 - t0)); - wait.push(us(t2 - t0)); - let [ks, ke, gs, ge] = g.times(&command_buffer); - let points = [h0, ks, ke, gs, ge, h2]; - for (k, part) in split.iter_mut().enumerate() { - part.push((points[k + 1] - points[k]) * 1e6); - } - } - }); - } - for (part, values) in [ - "commit_to_kernel_start", - "kernel_start_to_end", - "kernel_end_to_gpu_start", - "gpu_start_to_end", - "gpu_end_to_wait_return", - ] - .iter() - .zip(&mut split) - { - emit("latency_split", &format!("{name}_{part}"), "us", values); - } - emit( - "latency", - &format!("{name}_commit_to_wait_return"), - "us", - &mut wait, - ); - emit("latency", &format!("{name}_commit_call"), "us", &mut commit); - let mut handler = vec![]; - for run in 0..sizes.latency + 10 { - g.pool(|| { - let command_buffer = g.command_buffer(); - encode_tiny(g, s, &command_buffer, tiny); - let (send, receive) = mpsc::channel(); - g.on_completed( - &command_buffer, - Box::new(move || { - let _ = send.send(Instant::now()); - }), - ); - let t0 = Instant::now(); - g.commit(&command_buffer); - let at = receive.recv().expect("the completed handler ran"); - if run >= 10 { - handler.push(us(at - t0)); - } - }); - } - emit( - "latency", - &format!("{name}_commit_to_handler"), - "us", - &mut handler, - ); - } -} - -/// The `signals` workload (module docs of `main.rs`): a command buffer of one tiny fill with a -/// completed handler, committed alone and waited for, as the consumer's isolated execution is, -/// `plain`, and with what each other variant adds. -pub fn signals(g: &G, s: &Scene, sizes: &Sizes) { - for name in ["plain", "scheduled_handler", "scheduled_signal", "checked"] { - let event = g.shared_event(); - let (mut handler, mut wait, mut cpu) = (vec![], vec![], vec![]); - let mut counts = None; - let mut has = true; - let runs = sizes.latency + 10; - for run in 0..runs { - if run == 10 { - counts = Some(g.work_counts()); - } - let value = run as u64 + 1; - g.pool(|| { - let command_buffer = g.command_buffer(); - encode_tiny(g, s, &command_buffer, Tiny::Fill); - match name { - "scheduled_handler" => g.set_when_scheduled(&command_buffer, &event, value), - "scheduled_signal" => g.signal_when_scheduled(&command_buffer, &event, value), - "checked" => has = g.check_submissions(&command_buffer), - _ => {} - } - let (send, receive) = mpsc::channel(); - g.on_completed( - &command_buffer, - Box::new(move || { - let _ = send.send(Instant::now()); - }), - ); - let cpu0 = process_cpu(); - let t0 = Instant::now(); - g.commit(&command_buffer); - let at = receive.recv().expect("the completed handler ran"); - g.wait(&command_buffer); - let t1 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 10 { - handler.push(us(at - t0)); - wait.push(us(t1 - t0)); - cpu.push(us(cpu1 - cpu0)); - } - }); - if !has { - break; - } - if name.starts_with("scheduled") { - assert_eq!(g.event_value(&event), value, "{name}: the value set"); - } - } - if !has { - continue; - } - emit( - "signals", - &format!("{name}_commit_to_handler"), - "us", - &mut handler, - ); - emit( - "signals", - &format!("{name}_commit_to_wait_return"), - "us", - &mut wait, - ); - emit("signals", &format!("{name}_process_cpu"), "us", &mut cpu); - let after = g.work_counts(); - for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) { - let per = (now - before) / sizes.latency as f64; - emit( - "signals", - &format!("rt_{name}_{counted}"), - "per cb", - &mut [per], - ); - } - } - // A burst of command buffers committed back to back, each checked or not, to the last one's - // completion: the scheduler's cost of a batch, per command buffer. - const BURST: usize = 64; - for name in ["plain", "checked"] { - let (mut wall, mut cpu) = (vec![], vec![]); - let mut counts = None; - let mut has = true; - for run in 0..sizes.latency + 3 { - if run == 3 { - counts = Some(g.work_counts()); - } - g.pool(|| { - let buffers: Vec<_> = (0..BURST) - .map(|_| { - let command_buffer = g.command_buffer(); - encode_tiny(g, s, &command_buffer, Tiny::Fill); - if name == "checked" { - has = g.check_submissions(&command_buffer); - } - command_buffer - }) - .collect(); - let cpu0 = process_cpu(); - let t0 = Instant::now(); - for command_buffer in &buffers { - g.commit(command_buffer); - } - g.wait(&buffers[BURST - 1]); - let t1 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 3 { - wall.push(us(t1 - t0) / BURST as f64); - cpu.push(us(cpu1 - cpu0) / BURST as f64); - } - }); - if !has { - break; - } - } - if !has { - continue; - } - emit("signals", &format!("burst_{name}_wall"), "us/cb", &mut wall); - emit( - "signals", - &format!("burst_{name}_process_cpu"), - "us/cb", - &mut cpu, - ); - let after = g.work_counts(); - for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) { - let per = (now - before) / (sizes.latency * BURST) as f64; - emit( - "signals", - &format!("rt_burst_{name}_{counted}"), - "per cb", - &mut [per], - ); - } - } - // A listener made and dropped unused, as the consumer makes one per task; then one made, and - // its first notification asked for a value already reached, to its block's start. - let (mut unused, mut made, mut first) = (vec![], vec![], vec![]); - let event = g.shared_event(); - for run in 0..sizes.latency + 10 { - let t0 = Instant::now(); - drop(g.listener()); - let t1 = Instant::now(); - let listener = g.listener(); - let t2 = Instant::now(); - let (send, receive) = mpsc::channel(); - g.notify( - &event, - &listener, - 0, - Box::new(move || { - let _ = send.send(Instant::now()); - }), - ); - let at = receive.recv().expect("the notification ran"); - drop(listener); - if run >= 10 { - unused.push(us(t1 - t0)); - made.push(us(t2 - t1)); - first.push(us(at - t2)); - } - } - emit( - "signals", - "listener_made_and_dropped_unused", - "us", - &mut unused, - ); - emit("signals", "listener_made", "us", &mut made); - emit("signals", "listener_first_notification", "us", &mut first); -} - -/// GPU time of the heavy shaders and the feature kernels, one command buffer in flight: from the -/// commit until the wait returned, and `GPUEndTime - GPUStartTime` where the side measures it on -/// the GPU. With `outputs`, each kernel's output after its last run goes to `/.bin`. -pub fn gpu(g: &G, s: &Scene, sizes: &Sizes, outputs: Option<&Path>) { - let run = |name: &str, encode: &dyn Fn(&G::CommandBuffer)| { - let (mut wall, mut times) = (vec![], vec![]); - for run in 0..sizes.heavy_runs + 3 { - g.pool(|| { - let command_buffer = g.command_buffer(); - encode(&command_buffer); - let t0 = Instant::now(); - g.commit(&command_buffer); - g.wait(&command_buffer); - let t1 = Instant::now(); - if run >= 3 { - wall.push(ms(t1 - t0)); - if let Some(seconds) = g.gpu_seconds(&command_buffer) { - times.push(seconds * 1e3); - } - } - }); - } - emit("gpu", &format!("{name}_commit_to_wait"), "ms", &mut wall); - if !times.is_empty() { - emit("gpu", &format!("{name}_gpu_time"), "ms", &mut times); - } - }; - let keep = |name: &str| { - if let Some(dir) = outputs { - let mut bytes = vec![0u8; HEAVY_OUT_BYTES]; - g.read_buffer(&s.heavy_out, &mut bytes); - std::fs::write(dir.join(format!("{name}.bin")), bytes).expect("write an output"); - } - }; - run("heavy_fragment", &|command_buffer| { - let mut encoder = g.render_encoder(command_buffer, &s.heavy_target, true); - g.set_render_pipeline(&mut encoder, &s.heavy_fragment); - g.set_vertex_buffer(&mut encoder, &s.full, 0, 0); - g.set_fragment_buffer(&mut encoder, &s.params, 0, 0); - g.set_fragment_texture(&mut encoder, &s.heavy_texture, 0); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - g.draw_strip(&mut encoder, 4); - g.end_render(encoder); - }); - run("heavy_kernel", &|command_buffer| { - let mut encoder = g.compute_encoder(command_buffer); - g.set_compute_pipeline(&mut encoder, &s.heavy_kernel); - g.set_buffer(&mut encoder, &s.heavy_out, 0, 0); - g.set_buffer(&mut encoder, &s.kernel_params, 0, 1); - g.set_texture(&mut encoder, &s.kernel_texture, 0); - g.dispatch(&mut encoder, HEAVY_GROUPS, HEAVY_THREADS); - g.end_compute(encoder); - }); - keep("heavy_kernel"); - for (name, state) in &s.features { - run(name, &|command_buffer| { - let mut encoder = g.compute_encoder(command_buffer); - g.set_compute_pipeline(&mut encoder, state); - g.set_buffer(&mut encoder, &s.heavy_out, 0, 0); - g.set_buffer(&mut encoder, &s.kernel_params, 0, 1); - g.set_buffer(&mut encoder, &s.heavy_in, 0, 2); - g.set_texture(&mut encoder, &s.kernel_texture, 0); - g.dispatch(&mut encoder, HEAVY_GROUPS, HEAVY_THREADS); - g.end_compute(encoder); - }); - keep(name); - } -} - -/// Pipeline creation, in a process whose caches are as the caller left them: the library, each -/// state's creation, its first use (a command buffer of one draw or dispatch, to completion), and -/// each state made again in the same process. Single samples. -pub fn pipeline(g: &G, metallib: &std::path::Path, sizes: &Sizes) { - let t = Instant::now(); - let library = g.library(metallib); - emit("pipeline", "library", "ms", &mut [ms(t.elapsed())]); - let target = g.texture(Format::Bgra8, TARGET_SIDE, TARGET_SIDE, true); - let heavy_target = g.texture(Format::Rgba16Float, 256, 256, true); - let side = KERNEL_TEXTURE_SIDE; - let texture = g.texture(Format::Rgba8, side, side, false); - g.replace_region(&texture, (side, side), &texels(side, 1), side * 4); - let sampler = g.sampler(true); - let rect = g.buffer_with(&floats(&[-1.0, -1.0, 1.0, 1.0])); - let params = g.buffer_with(¶ms_bytes(sizes.heavy_iterations.min(4))); - let out = g.buffer(HEAVY_THREADS * 16); - let values = g.buffer(HEAVY_THREADS * 4); - for pass in ["first", "again"] { - let timed = |name: &str, f: &mut dyn FnMut()| { - let t = Instant::now(); - f(); - emit( - "pipeline", - &format!("{name}_{pass}"), - "ms", - &mut [ms(t.elapsed())], - ); - }; - let draw = |state: &G::RenderPipeline, target: &G::Texture, uniforms: bool| { - g.pool(|| { - let command_buffer = g.command_buffer(); - let mut encoder = g.render_encoder(&command_buffer, target, true); - g.set_render_pipeline(&mut encoder, state); - g.set_vertex_buffer(&mut encoder, &rect, 0, 0); - if uniforms { - g.set_fragment_buffer(&mut encoder, ¶ms, 0, 0); - } - g.set_fragment_texture(&mut encoder, &texture, 0); - g.set_fragment_sampler(&mut encoder, &sampler, 0); - g.draw_strip(&mut encoder, 4); - g.end_render(encoder); - g.commit(&command_buffer); - g.wait(&command_buffer); - }) - }; - let dispatch = |state: &G::ComputePipeline, heavy: bool| { - g.pool(|| { - let command_buffer = g.command_buffer(); - let mut encoder = g.compute_encoder(&command_buffer); - g.set_compute_pipeline(&mut encoder, state); - g.set_buffer(&mut encoder, &out, 0, 0); - if heavy { - g.set_buffer(&mut encoder, ¶ms, 0, 1); - g.set_texture(&mut encoder, &texture, 0); - } else { - g.set_buffer(&mut encoder, &values, 0, 1); - } - g.dispatch(&mut encoder, 1, HEAVY_THREADS); - g.end_compute(encoder); - g.commit(&command_buffer); - g.wait(&command_buffer); - }) - }; - let mut state = None; - timed("textured_create", &mut || { - state = Some(g.render_pipeline( - &library, - "quad_vertex", - "textured_fragment", - Format::Bgra8, - false, - )) - }); - let textured = state.take().unwrap(); - timed("textured_first_draw", &mut || { - draw(&textured, &target, false) - }); - timed("heavy_fragment_create", &mut || { - state = Some(g.render_pipeline( - &library, - "quad_vertex", - "heavy_fragment", - Format::Rgba16Float, - false, - )) - }); - let heavy = state.take().unwrap(); - timed("heavy_fragment_first_draw", &mut || { - draw(&heavy, &heavy_target, true) - }); - let mut kernel = None; - timed("heavy_kernel_create", &mut || { - kernel = Some(g.compute_pipeline(&library, "heavy_kernel")) - }); - let heavy_kernel = kernel.take().unwrap(); - timed("heavy_kernel_first_dispatch", &mut || { - dispatch(&heavy_kernel, true) - }); - timed("tiny_kernel_create", &mut || { - kernel = Some(g.compute_pipeline(&library, "tiny_kernel")) - }); - let tiny = kernel.take().unwrap(); - timed("tiny_kernel_first_dispatch", &mut || dispatch(&tiny, false)); - } -} - -/// Memory: buffer creation (`Shared`, by length, by bytes, and over host memory without a copy) -/// and a `Shared` texture's `replaceRegion` and `getBytes`; only the parts `variants` names where -/// it names any (`create`, `no_copy`, `held_1m`, `held_64m`, `texture`). -pub fn memory(g: &G, sizes: &Sizes, variants: &[String]) { - const KIB: usize = 1024; - const MIB: usize = 1024 * 1024; - let runs = |name: &str| variants.is_empty() || variants.iter().any(|v| v == name); - let repeats = |length: usize| { - if length >= 16 * MIB { - 8 - } else { - sizes.timed.max(20) - } - }; - let created = [("4k", 4 * KIB), ("1m", MIB), ("64m", 64 * MIB)]; - for (name, length) in created.into_iter().filter(|_| runs("create")) { - let mut times = vec![]; - for _ in 0..repeats(length) { - let t = Instant::now(); - let buffer = g.buffer(length); - times.push(us(t.elapsed())); - drop(buffer); - } - emit("memory", &format!("new_buffer_{name}"), "us", &mut times); - let bytes = vec![0x33u8; length]; - let mut times = vec![]; - for _ in 0..repeats(length) { - let t = Instant::now(); - let buffer = g.buffer_with(&bytes); - times.push(us(t.elapsed())); - drop(buffer); - } - emit( - "memory", - &format!("new_buffer_with_bytes_{name}"), - "us", - &mut times, - ); - } - let no_copy = [("1m", MIB), ("64m", 64 * MIB)]; - for (name, length) in no_copy.into_iter().filter(|_| runs("no_copy")) { - let mut times = vec![]; - let mut maps = vec![]; - for _ in 0..repeats(length) { - #[cfg(unix)] - // SAFETY: an anonymous private mapping of `length` bytes, unmapped below once every - // buffer over it is gone. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - length, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - length, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - assert_ne!(pointer, libc::MAP_FAILED); - #[cfg(windows)] - assert!(!pointer.is_null()); - // SAFETY: the pages are mapped read-write; touch them as a program's own data is. - unsafe { std::ptr::write_bytes(pointer as *mut u8, 0x11, length) }; - let t = Instant::now(); - // SAFETY: page-aligned read-write memory that outlives the buffer (unmapped below). - let buffer = unsafe { g.buffer_no_copy(pointer as *mut u8, length) }; - times.push(us(t.elapsed())); - drop(buffer); - maps.push(pointer); - } - emit( - "memory", - &format!("new_buffer_no_copy_{name}"), - "us", - &mut times, - ); - // Let any release the side defers finish before the pages go. - let command_buffer = g.command_buffer(); - g.commit(&command_buffer); - g.wait(&command_buffer); - std::thread::sleep(Duration::from_millis(50)); - for pointer in maps { - // SAFETY: mapped above, no buffer over it remains. - #[cfg(unix)] - unsafe { - libc::munmap(pointer, length) - }; - #[cfg(windows)] - // SAFETY: as above; a release frees the allocation whole, from its base. - unsafe { - windows_sys::Win32::System::Memory::VirtualFree( - pointer, - 0, - windows_sys::Win32::System::Memory::MEM_RELEASE, - ) - }; - } - } - // Buffers held, as a program that grows its memory makes them: each takes memory no buffer - // of the run used before, so neither side hands back one it made earlier (the runtime's - // recycler lets go of what it parked above once a second passed). Each one's creation, then - // the first touch of all its bytes: a write from the CPU, or, of another set, a blit fill - // from the GPU (commit to the wait's return), and that fill again. - let held = [("1m", MIB, 48), ("64m", 64 * MIB, 6)]; - for (name, length, count) in held - .into_iter() - .filter(|(name, ..)| runs(&format!("held_{name}"))) - { - std::thread::sleep(Duration::from_millis(1100)); - let mut make = vec![]; - let mut held = || -> Vec { - (0..count) - .map(|_| { - let t = Instant::now(); - let buffer = g.buffer(length); - make.push(us(t.elapsed())); - buffer - }) - .collect() - }; - // Both sets held to the end, so that the second takes none of the first's memory. - let (written, filled) = (held(), held()); - let mut write = vec![]; - for buffer in &written { - let t = Instant::now(); - g.write_buffer(buffer, 0x5a); - write.push(us(t.elapsed())); - } - let (mut fill, mut again) = (vec![], vec![]); - for buffer in &filled { - for times in [&mut fill, &mut again] { - let t = Instant::now(); - let command_buffer = g.command_buffer(); - g.fill(&command_buffer, buffer, length); - g.commit(&command_buffer); - g.wait(&command_buffer); - times.push(us(t.elapsed())); - } - } - drop((written, filled)); - emit( - "memory", - &format!("new_buffer_held_{name}"), - "us", - &mut make, - ); - emit( - "memory", - &format!("first_write_held_{name}"), - "us", - &mut write, - ); - emit( - "memory", - &format!("first_fill_held_{name}"), - "us", - &mut fill, - ); - emit( - "memory", - &format!("second_fill_held_{name}"), - "us", - &mut again, - ); - } - if !runs("texture") { - return; - } - let side = HEAVY_TEXTURE_SIDE; - let texture = g.texture(Format::Rgba8, side, side, false); - let bytes = texels(side, 3); - let mut back = vec![0u8; bytes.len()]; - let (mut replace, mut get) = (vec![], vec![]); - for run in 0..sizes.timed.max(20) + 2 { - let t0 = Instant::now(); - g.replace_region(&texture, (side, side), &bytes, side * 4); - let t1 = Instant::now(); - g.get_bytes(&texture, (side, side), &mut back, side * 4); - let t2 = Instant::now(); - if run >= 2 { - replace.push(us(t1 - t0)); - get.push(us(t2 - t1)); - } - } - assert!(back == bytes, "getBytes read back what replaceRegion wrote"); - emit("memory", "texture_replace_region_4m", "us", &mut replace); - emit("memory", "texture_get_bytes_4m", "us", &mut get); -} - -/// The `frame` workload's textures, their side, and the bytes between their offsets. -const FRAME_TEXTURES: usize = 8; -const FRAME_SIDE: usize = 256; -const FRAME_STRIDE: usize = 1 << 20; - -/// One frame of the `frame` workload (module docs of `main.rs`) in `heap`: the textures made, -/// each rendered by a pass of three draws, each sampled into the target, committed, waited for -/// and dropped; the times of each step into `times` (`[encode, make, drop, process CPU]`, the CPU -/// per frame). -fn frame_once(g: &G, s: &Scene, heap: &G::Heap, times: &mut [Vec; 4]) { - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let textures: Vec = (0..FRAME_TEXTURES) - .map(|i| g.heap_texture(heap, FRAME_SIDE, FRAME_SIDE, i * FRAME_STRIDE)) - .collect(); - let t1 = Instant::now(); - let command_buffer = g.command_buffer(); - for (i, texture) in textures.iter().enumerate() { - let mut encoder = g.render_encoder(&command_buffer, texture, true); - g.set_render_pipeline(&mut encoder, &s.textured[0]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for draw in 0..PASS_DRAWS { - let rect = (i * PASS_DRAWS + draw) % RECTS; - g.set_vertex_buffer(&mut encoder, &s.rects[0], rect * RECT_STRIDE, 0); - g.set_fragment_texture(&mut encoder, &s.textures[(i + draw) % TEXTURES], 0); - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - } - let mut encoder = g.render_encoder(&command_buffer, &s.target, true); - g.set_render_pipeline(&mut encoder, &s.textured[1]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for (i, texture) in textures.iter().enumerate() { - g.set_vertex_buffer(&mut encoder, &s.rects[1], i * RECT_STRIDE, 0); - g.set_fragment_texture(&mut encoder, texture, 0); - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - g.commit(&command_buffer); - let t2 = Instant::now(); - g.wait(&command_buffer); - let t3 = Instant::now(); - drop(textures); - let t4 = Instant::now(); - let cpu1 = process_cpu(); - times[0].push(us(t2 - t0)); - times[1].push(us(t1 - t0)); - times[2].push(us(t4 - t3)); - times[3].push(us(cpu1 - cpu0)); - }); -} - -/// A window server's frame of heap textures (module docs of `main.rs`), in a heap of the device, -/// and the runtime's over host pages. -pub fn frame(g: &G, s: &Scene, sizes: &Sizes) { - let size = FRAME_TEXTURES * FRAME_STRIDE; - let run = |name: &str, heap: &G::Heap| { - let mut times: [Vec; 4] = Default::default(); - for run in 0..sizes.timed + 3 { - let mut taken: [Vec; 4] = Default::default(); - frame_once(g, s, heap, &mut taken); - if run >= 3 { - for (all, one) in times.iter_mut().zip(taken) { - all.extend(one); - } - } - } - let [encode, make, dropped, cpu] = &mut times; - emit("frame", &format!("{name}_encode"), "us", encode); - emit("frame", &format!("{name}_make_textures"), "us", make); - emit("frame", &format!("{name}_drop_textures"), "us", dropped); - emit("frame", &format!("{name}_process_cpu"), "us", cpu); - }; - run("frame", &g.heap(size)); - #[cfg(unix)] - // SAFETY: an anonymous private mapping of `size` bytes, never unmapped: the process's to its - // end, past the heap and every texture placed in it. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - size, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - assert_ne!(pointer, libc::MAP_FAILED); - #[cfg(windows)] - assert!(!pointer.is_null()); - // SAFETY: page-aligned read-write memory of `size` bytes that outlives the heap. - if let Some(heap) = unsafe { g.heap_no_copy(pointer as *mut u8, size) } { - run("frame_no_copy", &heap); - } -} - -/// The `drag` workload's frame (module docs of `main.rs`): its command buffers, its render passes -/// (over [`DRAG_SURFACES`] window surfaces), the draws of each pass, and its dispatches. -const DRAG_COMMAND_BUFFERS: usize = 40; -const DRAG_PASSES: usize = 31; -const DRAG_PASS_DRAWS: usize = 3; -const DRAG_DISPATCHES: usize = 22; -const DRAG_SURFACES: usize = 8; - -/// The bytes a window surface's rows lie apart in the `drag` workload's surfaces over host pages: -/// its packed row padded, as a surface's rows are. -const DRAG_SURFACE_ROW: usize = FRAME_SIDE * 4 + 256; - -/// One frame of the `drag` workload: [`DRAG_COMMAND_BUFFERS`] command buffers, pass `p` in -/// command buffer `p` and a dispatch in each of the first [`DRAG_DISPATCHES`], each committed; -/// the last waited for. A pass's draws sample the scene's textures, or, where the frame -/// composites (`uploads` holds the windows' contents), the other surfaces, as a compositor's do, -/// the first command buffer uploading `uploads` into half the surfaces in one blit encoder before -/// its pass. Its times into `times` (`[encode, frame, thread CPU, process CPU]`). -fn drag_once( - g: &G, - s: &Scene, - (surfaces, uploads): (&[G::Texture], Option<&G::Buffer>), - times: &mut [Vec; 4], -) { - g.pool(|| { - let cpu = process_cpu(); - let thread = thread_cpu(); - let start = Instant::now(); - let mut last = None; - for at in 0..DRAG_COMMAND_BUFFERS { - let command_buffer = g.command_buffer(); - if let Some(contents) = uploads.filter(|_| at == 0) { - let windows: Vec<&G::Texture> = surfaces.iter().step_by(2).collect(); - let side = (FRAME_SIDE, FRAME_SIDE); - g.upload(&command_buffer, contents, &windows, side, FRAME_SIDE * 4); - } - if at < DRAG_PASSES { - let target = &surfaces[at % DRAG_SURFACES]; - let mut encoder = g.render_encoder(&command_buffer, target, at % 4 != 0); - g.set_render_pipeline(&mut encoder, &s.textured[at % 2]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for draw in 0..DRAG_PASS_DRAWS { - let rect = (at * DRAG_PASS_DRAWS + draw) % RECTS; - g.set_vertex_buffer(&mut encoder, &s.rects[0], rect * RECT_STRIDE, 0); - let texture = match uploads { - Some(_) => &surfaces[(at + draw + 1) % DRAG_SURFACES], - None => &s.textures[(at + draw) % TEXTURES], - }; - g.set_fragment_texture(&mut encoder, texture, 0); - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - } - if at < DRAG_DISPATCHES { - encode_dispatches(g, s, &command_buffer, 1, DispatchChurn::Static); - } - g.commit(&command_buffer); - last = Some(command_buffer); - } - let encoded = Instant::now(); - let thread = thread_cpu() - thread; - if let Some(command_buffer) = &last { - g.wait(command_buffer); - } - let done = Instant::now(); - let cpu = process_cpu() - cpu; - times[0].push(ms(encoded - start)); - times[1].push(ms(done - start)); - times[2].push(ms(thread)); - times[3].push(ms(cpu)); - }); -} - -/// A frame shaped as the guest's window drag (module docs of `main.rs`), its window surfaces in -/// a heap of the device, and the runtime's in a heap over host pages too; then its surfaces as -/// textures over host pages, one buffer each, the draws sampling the other surfaces. -pub fn drag(g: &G, s: &Scene, sizes: &Sizes) { - let size = DRAG_SURFACES * FRAME_STRIDE; - let contents = g.buffer(FRAME_SIDE * FRAME_SIDE * 4); - let run = |name: &str, surfaces: &[G::Texture], composites: bool| { - let uploads = composites.then_some(&contents); - let mut times: [Vec; 4] = Default::default(); - for frame in 0..sizes.timed + 3 { - let mut taken: [Vec; 4] = Default::default(); - drag_once(g, s, (surfaces, uploads), &mut taken); - if frame >= 3 { - for (all, one) in times.iter_mut().zip(taken) { - all.extend(one); - } - } - } - let [encode, frame, thread, cpu] = &mut times; - emit("drag", &format!("{name}_encode"), "ms", encode); - emit("drag", &format!("{name}_frame"), "ms", frame); - emit("drag", &format!("{name}_thread_cpu"), "ms", thread); - emit("drag", &format!("{name}_process_cpu"), "ms", cpu); - }; - let in_heap = |heap: &G::Heap| -> Vec { - (0..DRAG_SURFACES) - .map(|i| g.heap_texture(heap, FRAME_SIDE, FRAME_SIDE, i * FRAME_STRIDE)) - .collect() - }; - run("drag", &in_heap(&g.heap(size)), false); - // SAFETY: an anonymous private mapping of `size` bytes, never unmapped: the process's to its - // end, past the heap and every texture placed in it. - let pointer = unsafe { host_pages(size) }; - // SAFETY: page-aligned read-write memory of `size` bytes that outlives the heap. - if let Some(heap) = unsafe { g.heap_no_copy(pointer, size) } { - run("drag_no_copy", &in_heap(&heap), false); - } - // SAFETY: as above, a mapping of its own. - let pointer = unsafe { host_pages(size) }; - // SAFETY: page-aligned read-write memory of `size` bytes that outlives the heap. - if let Some(heap) = unsafe { g.heap_no_copy(pointer, size) } { - let surfaces: Vec = (0..DRAG_SURFACES) - .map(|i| g.heap_render_texture(&heap, Format::Bgra8, FRAME_SIDE, i * FRAME_STRIDE)) - .collect(); - run("drag_heap_surfaces", &surfaces, true); - } - let surfaces: Vec = (0..DRAG_SURFACES) - .map(|_| { - // SAFETY: as above, a mapping of its own for each surface. - let buffer = unsafe { g.buffer_no_copy(host_pages(FRAME_STRIDE), FRAME_STRIDE) }; - let side = (FRAME_SIDE, FRAME_SIDE); - g.buffer_texture(&buffer, side, 0, DRAG_SURFACE_ROW) - }) - .collect(); - run("drag_surfaces", &surfaces, true); -} - -/// An anonymous private mapping of `size` bytes, read-write. -/// -/// # Safety -/// -/// Never unmapped: the caller keeps it for the process's life. -pub unsafe fn host_pages(size: usize) -> *mut u8 { - #[cfg(unix)] - // SAFETY: a new anonymous mapping, which nothing else holds. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - size, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - assert_ne!(pointer, libc::MAP_FAILED); - #[cfg(windows)] - assert!(!pointer.is_null()); - pointer as *mut u8 -} - -/// The many-draws workload's target (1080p `BGRA8Unorm`, with a `Depth32Float` attachment), its -/// textures (16 `RGBA8Unorm` of 128x128) and its uniforms' stride. -const MANY_TARGET: (usize, usize) = (1920, 1080); -const MANY_TEXTURES: usize = 16; -const MANY_TEXTURE_SIDE: usize = 128; -const MANY_STRIDE: usize = 256; - -/// What the many-draws workload draws with (module docs of `main.rs`). -struct ManyDraws { - /// `draws_vertex` with each of `draws_fragment0` to `3`, the third blending. - pipelines: [G::RenderPipeline; 4], - /// `Less` with depth writes, `LessEqual` without. - depth_states: [G::DepthStencil; 2], - /// Linear and nearest. - samplers: [G::Sampler; 2], - textures: Vec, - /// The rectangle's corners, and its two triangles' indices. - quad: G::Buffer, - indices: G::Buffer, - /// Four uniform buffers: draw `i` reads buffer `i % 4` at `(i / 4) * MANY_STRIDE`. - uniforms: [G::Buffer; 4], - /// Where the uniforms lie in host pages: the heap over those pages, which the buffers lie in - /// too, as a guest's buffers lie in its memory beside its heaps. - _pages: Option, - target: G::Texture, - depth: G::Texture, -} - -impl ManyDraws { - /// The scene of `count` draws, its uniforms in buffers of their own, or with `pages` in - /// no-copy buffers over host pages a no-copy heap lies over too: `None` where the side makes - /// no such heap. - fn new(g: &G, library: &G::Library, count: usize, pages: bool) -> Option> { - let pipeline = |i: usize| { - g.depth_pipeline( - library, - "draws_vertex", - &format!("draws_fragment{i}"), - i == 2, - ) - }; - let textures = (0..MANY_TEXTURES) - .map(|n| { - let side = MANY_TEXTURE_SIDE; - let texture = g.texture(Format::Rgba8, side, side, false); - g.replace_region( - &texture, - (side, side), - &texels(side, n as u8 * 13 + 1), - side * 4, - ); - texture - }) - .collect(); - // A grid of rectangles over the target, each half again a cell's side, as m2vbench lays - // them. - let grid = (count as f64).sqrt().ceil() as usize; - let cell = 2.0 / grid as f32; - let per = count.div_ceil(4) * MANY_STRIDE; - let mut bytes = [(); 4].map(|_| vec![0u8; per]); - for i in 0..count { - let (x, y) = ((i % grid) as f32, (i / grid) as f32); - let at = (i / 4) * MANY_STRIDE; - let uniforms = floats(&[ - -1.0 + x * cell, - -1.0 + y * cell, - cell * 1.5, - cell * 1.5, - 0.5 + 0.5 * (i as f32 * 0.1).sin(), - 0.5 + 0.5 * (i as f32 * 0.07).cos(), - (i % 7) as f32 / 7.0, - 1.0, - i as f32 / count as f32, - i as f32 * 0.001, - 0.0, - 0.0, - ]); - bytes[i % 4][at..at + uniforms.len()].copy_from_slice(&uniforms); - } - let indices: Vec = [0u16, 1, 2, 2, 1, 3] - .iter() - .flat_map(|i| i.to_le_bytes()) - .collect(); - let (uniforms, pages) = match pages { - false => (bytes.map(|bytes| g.buffer_with(&bytes)), None), - true => { - let page = 16 << 10; - let each = per.next_multiple_of(page); - // SAFETY: a new mapping of four buffers' pages, never unmapped: the process's to - // its end, past the heap and the buffers over it. - let pointer = unsafe { host_pages(4 * each) }; - for (at, bytes) in bytes.iter().enumerate() { - // SAFETY: `at * each + per` bytes lie in the mapping, which nothing uses yet. - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), pointer.add(at * each), per) - }; - } - // SAFETY: page-aligned read-write memory that outlives the heap. - let heap = unsafe { g.heap_no_copy(pointer, 4 * each) }?; - // SAFETY: as above, each buffer over its own pages of the mapping. - let buffer = |at: usize| unsafe { g.buffer_no_copy(pointer.add(at * each), each) }; - ([0, 1, 2, 3].map(buffer), Some(heap)) - } - }; - Some(ManyDraws { - pipelines: [pipeline(0), pipeline(1), pipeline(2), pipeline(3)], - depth_states: [g.depth_stencil(true), g.depth_stencil(false)], - samplers: [g.sampler(true), g.sampler(false)], - textures, - quad: g.buffer_with(&floats(&[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0])), - indices: g.buffer_with(&indices), - uniforms, - _pages: pages, - target: g.texture(Format::Bgra8, MANY_TARGET.0, MANY_TARGET.1, true), - depth: g.texture(Format::Depth32Float, MANY_TARGET.0, MANY_TARGET.1, true), - }) - } - - /// Encode one frame's render pass of `count` draws into `command_buffer`, as m2vbench's draws - /// mode does. - fn encode(&self, g: &G, command_buffer: &G::CommandBuffer, count: usize) { - let mut encoder = g.depth_render_encoder(command_buffer, &self.target, &self.depth); - g.set_vertex_buffer(&mut encoder, &self.quad, 0, 0); - g.set_counter_clockwise(&mut encoder); - for i in 0..count { - if i % 8 == 0 { - g.set_render_pipeline(&mut encoder, &self.pipelines[(i / 8) % 4]); - } - if i % 16 == 0 { - g.set_depth_stencil(&mut encoder, &self.depth_states[(i / 16) % 2]); - } - if i % 32 == 0 { - g.set_fragment_sampler(&mut encoder, &self.samplers[(i / 32) % 2], 0); - } - if i % 64 == 0 { - g.set_cull_back(&mut encoder, (i / 64) % 2 == 0); - } - let uniforms = &self.uniforms[i % 4]; - let at = (i / 4) * MANY_STRIDE; - g.set_vertex_buffer(&mut encoder, uniforms, at, 1); - g.set_fragment_buffer(&mut encoder, uniforms, at, 0); - g.set_fragment_texture(&mut encoder, &self.textures[i % MANY_TEXTURES], 0); - g.set_fragment_texture(&mut encoder, &self.textures[(i * 7 + 3) % MANY_TEXTURES], 1); - let mut jitter = [0u8; 16]; - jitter[..4].copy_from_slice(&(0.002 * (i % 3) as f32).to_le_bytes()); - g.set_vertex_bytes(&mut encoder, &jitter, 2); - if i % 2 == 1 { - g.draw_indexed(&mut encoder, 6, &self.indices); - } else { - g.draw_strip(&mut encoder, 4); - } - } - g.end_render(encoder); - } -} - -/// The many-draws workload (module docs of `main.rs`): per frame, the encoding thread's wall -/// time from the command buffer's creation through `endEncoding`, the commit call's, the commit's -/// return to the wait's, the whole frame's, the process's CPU time, the encoding thread's CPU -/// time through the commit's return, and the GPU time where the side measures it. -pub fn many_draws(g: &G, library: &G::Library, sizes: &Sizes) { - let count = sizes.many_draws; - for (name, pages) in [("", false), ("pages_", true)] { - let Some(scene) = ManyDraws::new(g, library, count, pages) else { - continue; - }; - many_draws_of(g, &scene, (name, count), sizes); - } -} - -/// The many-draws workload's frames of `scene`, `count` draws each, its rows' names prefixed with -/// `name`. -fn many_draws_of(g: &G, scene: &ManyDraws, (name, count): (&str, usize), sizes: &Sizes) { - let mut times: [Vec; 7] = Default::default(); - for frame in 0..sizes.timed + 3 { - g.pool(|| { - let cpu = process_cpu(); - let thread = thread_cpu(); - let start = Instant::now(); - let command_buffer = g.command_buffer(); - scene.encode(g, &command_buffer, count); - let encoded = Instant::now(); - g.commit(&command_buffer); - let committed = Instant::now(); - let thread = thread_cpu() - thread; - g.wait(&command_buffer); - let done = Instant::now(); - let cpu = process_cpu() - cpu; - if frame < 3 { - return; - } - times[6].push(ms(thread)); - times[0].push(ms(encoded - start)); - times[1].push(ms(committed - encoded)); - times[2].push(ms(done - committed)); - times[3].push(ms(done - start)); - times[4].push(ms(cpu)); - if let Some(gpu) = g.gpu_seconds(&command_buffer) { - times[5].push(gpu * 1e3); - } - }); - } - let [encode, commit, wait, frame, cpu, gpu, thread] = &mut times; - emit("many_draws", &format!("{name}encode"), "ms", encode); - emit("many_draws", &format!("{name}commit"), "ms", commit); - emit("many_draws", &format!("{name}commit_to_done"), "ms", wait); - emit("many_draws", &format!("{name}frame"), "ms", frame); - emit("many_draws", &format!("{name}cpu"), "ms", cpu); - emit("many_draws", &format!("{name}thread_cpu"), "ms", thread); - if !gpu.is_empty() { - emit("many_draws", &format!("{name}gpu"), "ms", gpu); - } -} - -/// The layers workload's layers, its textures, their sides, and the target's size (m2vbench's -/// composite mode at its default count). -const LAYERS: usize = 800; -const LAYER_TEXTURES: usize = 48; -const LAYER_SIDES: [usize; 5] = [64, 96, 128, 192, 256]; -const LAYERS_TARGET: (usize, usize) = (1920, 1080); - -/// What the layers workload draws with (module docs of `main.rs`). -struct Layers { - /// The layers' and the shadows' pipeline states; the wallpaper is drawn as a layer. - layer: G::RenderPipeline, - shadow: G::RenderPipeline, - sampler: G::Sampler, - wallpaper: G::Texture, - textures: Vec, - /// Each layer's rectangle at rest: x, y, w, h in pixels. - rests: Vec<[f32; 4]>, - target: G::Texture, -} - -impl Layers { - fn new(g: &G, library: &G::Library) -> Layers { - let (width, height) = LAYERS_TARGET; - let pipeline = - |fragment| g.render_pipeline(library, "layer_vertex", fragment, Format::Bgra8, true); - let texture = |w: usize, h: usize, seed: usize| { - let texture = g.texture(Format::Rgba8, w, h, false); - let texels: Vec = (0..w * h) - .flat_map(|i| { - let (x, y) = (i % w, i / w); - let v = ((x * 7 + y * 13) ^ seed.wrapping_mul(2_654_435_761)) as u8; - [ - v, - (x * 255 / w) as u8, - ((y * 255 / h + seed * 31) % 256) as u8, - 255, - ] - }) - .collect(); - g.replace_region(&texture, (w, h), &texels, w * 4); - texture - }; - let textures = (0..LAYER_TEXTURES) - .map(|i| texture(LAYER_SIDES[i % 5], LAYER_SIDES[(i / 5) % 5], i + 300)) - .collect(); - let mut seed = 42u32; - let mut next = || { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 8) as f32 / (1u32 << 24) as f32 - }; - let rests = (0..LAYERS) - .map(|_| { - let (w, h) = (120.0 + next() * 560.0, 90.0 + next() * 420.0); - let (x, y) = (next() * (width as f32 - w), next() * (height as f32 - h)); - [x, y, w, h] - }) - .collect(); - Layers { - layer: pipeline("layer_fragment"), - shadow: pipeline("shadow_fragment"), - sampler: g.sampler(true), - wallpaper: texture(256, 256, 999), - textures, - rests, - target: g.texture(Format::Bgra8, width, height, true), - } - } - - /// Encode one frame at time `t` into `command_buffer`, as m2vbench's composite mode does: the - /// wallpaper, then each layer back to front, a shadow under every eighth, one draw each, its - /// uniforms as vertex bytes and its texture bound before it. - fn encode(&self, g: &G, command_buffer: &G::CommandBuffer, t: f32) { - let (width, height) = (LAYERS_TARGET.0 as f32, LAYERS_TARGET.1 as f32); - let uniforms = |rect: [f32; 4], opacity: f32| { - floats(&[ - rect[0], rect[1], rect[2], rect[3], width, height, opacity, 12.0, - ]) - }; - let mut encoder = g.render_encoder(command_buffer, &self.target, true); - g.set_fragment_sampler(&mut encoder, &self.sampler, 0); - g.set_render_pipeline(&mut encoder, &self.layer); - g.set_vertex_bytes(&mut encoder, &uniforms([0.0, 0.0, width, height], 1.0), 0); - g.set_fragment_texture(&mut encoder, &self.wallpaper, 0); - g.draw_strip(&mut encoder, 4); - for (i, rest) in self.rests.iter().enumerate() { - let f = i as f32; - let rect = [ - rest[0] + 40.0 * (t * 0.7 + f).sin(), - rest[1] + 30.0 * (t * 0.5 + f * 0.3).cos(), - rest[2], - rest[3], - ]; - let opacity = 0.75 + 0.25 * (f * 1.7).sin(); - if i % 8 == 0 { - let grown = [ - rect[0] - 32.0, - rect[1] - 24.0, - rect[2] + 64.0, - rect[3] + 64.0, - ]; - g.set_render_pipeline(&mut encoder, &self.shadow); - g.set_vertex_bytes(&mut encoder, &uniforms(grown, opacity), 0); - g.draw_strip(&mut encoder, 4); - g.set_render_pipeline(&mut encoder, &self.layer); - } - g.set_vertex_bytes(&mut encoder, &uniforms(rect, opacity), 0); - g.set_fragment_texture(&mut encoder, &self.textures[i % LAYER_TEXTURES], 0); - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - } -} - -/// The layers workload (module docs of `main.rs`): per frame, the encoding thread's wall time -/// through `endEncoding`, the commit call's, the commit's return to the wait's, the whole frame's, -/// the process's CPU time, the encoding thread's CPU time through the commit's return, and the -/// GPU time where the side measures it. -pub fn layers(g: &G, library: &G::Library, sizes: &Sizes) { - let scene = Layers::new(g, library); - let mut times: [Vec; 7] = Default::default(); - for frame in 0..sizes.timed + 3 { - g.pool(|| { - let cpu = process_cpu(); - let thread = thread_cpu(); - let start = Instant::now(); - let command_buffer = g.command_buffer(); - scene.encode(g, &command_buffer, frame as f32 / 60.0); - let encoded = Instant::now(); - g.commit(&command_buffer); - let committed = Instant::now(); - let thread = thread_cpu() - thread; - g.wait(&command_buffer); - let done = Instant::now(); - let cpu = process_cpu() - cpu; - if frame < 3 { - return; - } - times[6].push(ms(thread)); - times[0].push(ms(encoded - start)); - times[1].push(ms(committed - encoded)); - times[2].push(ms(done - committed)); - times[3].push(ms(done - start)); - times[4].push(ms(cpu)); - if let Some(gpu) = g.gpu_seconds(&command_buffer) { - times[5].push(gpu * 1e3); - } - }); - } - let [encode, commit, wait, frame, cpu, gpu, thread] = &mut times; - emit("layers", "encode", "ms", encode); - emit("layers", "commit", "ms", commit); - emit("layers", "commit_to_done", "ms", wait); - emit("layers", "frame", "ms", frame); - emit("layers", "cpu", "ms", cpu); - emit("layers", "thread_cpu", "ms", thread); - if !gpu.is_empty() { - emit("layers", "gpu", "ms", gpu); - } -} - -/// The textures each frame of the `churn` workload makes. -const CHURNED: usize = 8; -/// The buffers each frame of the `churn` workload's `buffers` makes, and their length. -const CHURNED_BUFFERS: usize = 16; -const CHURNED_LENGTH: usize = 64 << 10; - -/// Churn: each frame makes eight 1280x800 `BGRA8Unorm` `Private` render targets, clears each in a -/// render pass of one command buffer, waits for it and releases them, as a window server's frame -/// makes and releases its textures. `same`: every frame's textures are of the same size; `varied`: -/// each frame's are a pixel wider than the frame before's, over 64 widths, so no texture's making -/// meets one of its shape released within the last 64 frames. `buffers`: each frame makes sixteen -/// 64-KiB buffers, fills each in a blit of one command buffer, waits for it and releases them, as -/// the staging and scratch buffers a frame's copies make. Per frame: the time from the first -/// making to the wait's return, and the process's CPU time. -pub fn churn(g: &G, sizes: &Sizes) { - let frames = sizes.timed.max(60); - for (name, varied) in [("same", false), ("varied", true)] { - let (mut frame, mut cpu) = (vec![], vec![]); - for i in 0..frames + 5 { - let width = 1280 + if varied { i % 64 } else { 0 }; - g.pool(|| { - let (t, c) = (Instant::now(), process_cpu()); - let textures: Vec = (0..CHURNED) - .map(|_| g.texture(Format::Bgra8, width, 800, true)) - .collect(); - let command_buffer = g.command_buffer(); - for texture in &textures { - let encoder = g.render_encoder(&command_buffer, texture, true); - g.end_render(encoder); - } - g.commit(&command_buffer); - g.wait(&command_buffer); - drop(command_buffer); - drop(textures); - if i >= 5 { - frame.push(ms(t.elapsed())); - cpu.push(ms(process_cpu() - c)); - } - }); - } - emit("churn", &format!("{name}_frame"), "ms", &mut frame); - emit("churn", &format!("{name}_cpu"), "ms", &mut cpu); - } - let (mut frame, mut cpu) = (vec![], vec![]); - for i in 0..frames + 5 { - g.pool(|| { - let (t, c) = (Instant::now(), process_cpu()); - let buffers: Vec = (0..CHURNED_BUFFERS) - .map(|_| g.buffer(CHURNED_LENGTH)) - .collect(); - let command_buffer = g.command_buffer(); - for buffer in &buffers { - g.fill(&command_buffer, buffer, CHURNED_LENGTH); - } - g.commit(&command_buffer); - g.wait(&command_buffer); - drop(command_buffer); - drop(buffers); - if i >= 5 { - frame.push(ms(t.elapsed())); - cpu.push(ms(process_cpu() - c)); - } - }); - } - emit("churn", "buffers_frame", "ms", &mut frame); - emit("churn", "buffers_cpu", "ms", &mut cpu); -} - -/// The compositing workload's command buffers a frame, and the new heap textures each frame -/// makes. -const COMPOSITING_BUFFERS: usize = 20; -const COMPOSITING_NEW: usize = 10; -/// A new texture's side, and the heap's bytes for each (past any texture's alignment). -const COMPOSITING_NEW_SIDE: usize = 256; -const COMPOSITING_SLOT: usize = 1 << 20; -/// The two layers' and the screen's side. -const COMPOSITING_SIDE: usize = 1024; -/// Frames run before the timed ones. -const COMPOSITING_WARM: usize = 20; - -/// Frames of the consumer's compositing shape (module docs of `main.rs`), paced at 60 Hz: per -/// frame, its wall time from the first command buffer's creation to the last one's completion, -/// the process's CPU time over it, the encoding thread's time to encode and commit all, the -/// frames over 16.7 ms and the 99th percentile, and the side's work counts per frame. -pub fn compositing(g: &G, s: &Scene, sizes: &Sizes) { - let heap = g.tracked_heap(COMPOSITING_NEW * COMPOSITING_SLOT); - let layers = [ - g.texture(Format::Bgra8, COMPOSITING_SIDE, COMPOSITING_SIDE, true), - g.texture(Format::Bgra8, COMPOSITING_SIDE, COMPOSITING_SIDE, true), - ]; - let screen = g.texture(Format::Bgra8, COMPOSITING_SIDE, COMPOSITING_SIDE, true); - let period = Duration::from_secs_f64(1.0 / 60.0); - let (mut wall, mut cpu, mut encode) = (vec![], vec![], vec![]); - let mut counts = Vec::new(); - let mut next = Instant::now(); - for frame in 0..COMPOSITING_WARM + sizes.frames { - if frame == COMPOSITING_WARM { - counts = g.work_counts(); - } - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - // Each new texture is made just before the command buffer that first draws into it. - let mut news = Vec::with_capacity(COMPOSITING_NEW); - let mut buffers = Vec::with_capacity(COMPOSITING_BUFFERS); - for c in 0..COMPOSITING_BUFFERS { - if c < COMPOSITING_NEW { - let at = c * COMPOSITING_SLOT; - news.push(g.heap_render_texture( - &heap, - Format::Bgra8, - COMPOSITING_NEW_SIDE, - at, - )); - } - let command_buffer = g.command_buffer(); - compositing_buffer(g, s, &command_buffer, (frame, c), &news, (&layers, &screen)); - g.commit(&command_buffer); - buffers.push(command_buffer); - } - let t1 = Instant::now(); - for command_buffer in &buffers { - g.wait(command_buffer); - } - let t2 = Instant::now(); - if frame >= COMPOSITING_WARM { - wall.push(ms(t2 - t0)); - encode.push(ms(t1 - t0)); - cpu.push(ms(process_cpu() - cpu0)); - } - }); - next += period; - match next.checked_duration_since(Instant::now()) { - Some(left) => std::thread::sleep(left), - None => next = Instant::now(), - } - } - let over = wall.iter().filter(|&&ms| ms > 1e3 / 60.0).count(); - emit("compositing", "over_16_7ms", "frames", &mut [over as f64]); - let mut sorted = wall.clone(); - sorted.sort_by(f64::total_cmp); - let p99 = sorted[((sorted.len() - 1) as f64 * 0.99).round() as usize]; - emit("compositing", "wall_p99", "ms", &mut [p99]); - emit("compositing", "wall", "ms", &mut wall); - emit("compositing", "encode_and_commit", "ms", &mut encode); - emit("compositing", "process_cpu", "ms", &mut cpu); - let after = g.work_counts(); - for ((name, before), (_, now)) in counts.iter().zip(&after) { - let per_frame = (now - before) / sizes.frames as f64; - emit( - "compositing", - &format!("rt_{name}"), - "per frame", - &mut [per_frame], - ); - } -} - -/// Command buffer `c` of frame `frame`: the first ten each clear one of the frame's new -/// textures (made just before it) and draw two textured quads into it; the next eight draw eight blended quads each -/// into one of the two layers, from four of the new textures and the other layer (which the -/// command buffer before drew into); one dispatches 15 small kernels and fills a buffer; the -/// last draws both layers and four new textures onto the screen. -fn compositing_buffer( - g: &G, - s: &Scene, - command_buffer: &G::CommandBuffer, - (frame, c): (usize, usize), - news: &[G::Texture], - (layers, screen): (&[G::Texture; 2], &G::Texture), -) { - let quad = |encoder: &mut G::RenderEncoder, n: usize| { - let rects = &s.rects[n % RECT_BUFFERS]; - g.set_vertex_buffer(encoder, rects, (n % RECTS) * RECT_STRIDE, 0); - g.draw_strip(encoder, 4); - }; - match c { - 0..COMPOSITING_NEW => { - let mut encoder = g.render_encoder(command_buffer, &news[c], true); - g.set_render_pipeline(&mut encoder, &s.textured[0]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - g.set_fragment_texture(&mut encoder, &s.textures[(frame + c) % TEXTURES], 0); - g.set_vertex_buffer(&mut encoder, &s.full, 0, 0); - g.draw_strip(&mut encoder, 4); - quad(&mut encoder, frame + c); - g.end_render(encoder); - } - 10..18 => { - let (layer, other) = (&layers[c % 2], &layers[(c + 1) % 2]); - let mut encoder = g.render_encoder(command_buffer, layer, c < 12); - g.set_render_pipeline(&mut encoder, &s.textured[1]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for d in 0..8 { - let texture = match d { - 0..4 => &news[(c + d) % COMPOSITING_NEW], - _ => other, - }; - g.set_fragment_texture(&mut encoder, texture, 0); - quad(&mut encoder, c * 8 + d); - } - g.end_render(encoder); - } - 18 => { - let mut encoder = g.compute_encoder(command_buffer); - g.set_compute_pipeline(&mut encoder, &s.tiny[0]); - g.set_buffer(&mut encoder, &s.tiny_values, 0, 1); - for d in 0..15 { - g.set_buffer(&mut encoder, &s.tiny_out, d * RECT_STRIDE, 0); - g.dispatch(&mut encoder, 1, 64); - } - g.end_compute(encoder); - g.fill(command_buffer, &s.fill, 4096); - } - _ => { - let mut encoder = g.render_encoder(command_buffer, screen, frame == 0); - g.set_render_pipeline(&mut encoder, &s.textured[1]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for layer in layers { - g.set_fragment_texture(&mut encoder, layer, 0); - g.set_vertex_buffer(&mut encoder, &s.full, 0, 0); - g.draw_strip(&mut encoder, 4); - } - for (n, texture) in news.iter().take(4).enumerate() { - g.set_fragment_texture(&mut encoder, texture, 0); - quad(&mut encoder, n * 3); - } - g.end_render(encoder); - } - } -} - -/// The burst workload's period and its burst, in frames at 60 Hz: each period's last -/// `BURST_FRAMES` frames are a burst. -const BURST_PERIOD: usize = 180; -const BURST_FRAMES: usize = 60; -/// Periods run before the timed ones, and the timed ones. -const BURST_WARM: usize = 1; -const BURST_TIMED: usize = 3; -/// Command buffers a frame, calm and in a burst. -const BURST_CALM_BUFFERS: usize = 20; -const BURST_BUFFERS: usize = 60; -/// The render targets every frame makes, of the same sizes each frame ([`burst_stable_side`]). -const BURST_STABLE: usize = 15; -/// The render targets a burst's frame makes besides, each of a width no other of the last -/// `BURST_ONE_OFF_WIDTHS` made had: makings seen once. -const BURST_ONE_OFF: usize = 45; -const BURST_ONE_OFF_WIDTHS: usize = 4096; -/// The heap textures each frame makes; a burst's take sides cycling through `BURST_HEAP_SIDES`. -const BURST_HEAP: usize = 10; -const BURST_HEAP_SIDES: usize = 128; - -/// Stable render target `i`'s width (each is 96 texels high). -fn burst_stable_side(i: usize) -> usize { - 96 + 32 * i -} - -/// What one frame of the burst workload measured: its start, its encoding and commits, and the -/// process's CPU time at its start. -struct BurstFrame { - start: Instant, - encoded: Duration, - cpu: Duration, -} - -/// Frames of a window server's shape paced at 60 Hz, each period of 3 s ending in a burst of -/// 1 s, as a guest's window server bursts (a VM's work counts: about three times the command -/// buffers, many new render targets of sizes made once, heap textures of more sizes, command -/// buffers left in flight). Calm, a frame makes the `BURST_STABLE` render targets and the -/// `BURST_HEAP` heap textures, clears each and draws into it, draws the heap textures onto a -/// screen texture in its last command buffer, and waits for its `BURST_CALM_BUFFERS` command -/// buffers. In a burst it also makes `BURST_ONE_OFF` render targets of one-off widths, its heap -/// textures take sides cycling through `BURST_HEAP_SIDES`, it spreads the work over -/// `BURST_BUFFERS` command buffers, and it waits at its start for the frame before's instead of -/// its own. Calm and burst frames apart: the interval from a frame's start to the next one's (its -/// median, its 99th percentile, and those over 16.7 and 25 ms), the encoding thread's time to -/// encode and commit, and, over the same interval (a burst's command buffers complete, and their -/// textures go, while the frame after waits for its start), the process's CPU time and the side's -/// work counts. -pub fn burst(g: &G, s: &Scene) { - // Two sets of heap slots: a burst's frame leaves the frame before's in flight. - let heap = g.tracked_heap(2 * BURST_HEAP * COMPOSITING_SLOT); - let screen = g.texture(Format::Bgra8, COMPOSITING_SIDE, COMPOSITING_SIDE, true); - let period = Duration::from_secs_f64(1.0 / 60.0); - let warm = BURST_WARM * BURST_PERIOD; - let mut frames: Vec<(bool, BurstFrame)> = Vec::new(); - // The work counts' changes over calm frames and over burst frames, each from a frame's start - // to the next one's, and the frames of each. - let mut counts: [(usize, Vec<(&'static str, f64)>); 2] = [(0, vec![]), (0, vec![])]; - let mut add = - |bursting: bool, before: &[(&'static str, f64)], after: &[(&'static str, f64)]| { - let (n, sum) = &mut counts[usize::from(bursting)]; - *n += 1; - if sum.is_empty() { - *sum = after.iter().map(|&(name, _)| (name, 0.0)).collect(); - } - for ((_, total), ((_, b), (_, a))) in sum.iter_mut().zip(before.iter().zip(after)) { - *total += a - b; - } - }; - let mut one_off = 0; - let mut in_flight: Vec = Vec::new(); - // The frame before's class and its start's counts, once timed. - let mut last: Option<(bool, Vec<(&'static str, f64)>)> = None; - let mut next = Instant::now(); - for frame in 0..warm + BURST_TIMED * BURST_PERIOD { - let bursting = frame % BURST_PERIOD >= BURST_PERIOD - BURST_FRAMES; - let before = g.work_counts(); - if let Some((was_bursting, then)) = last.take() { - add(was_bursting, &then, &before); - } - let measured = g.pool(|| { - let cpu = process_cpu(); - let start = Instant::now(); - for command_buffer in in_flight.drain(..) { - g.wait(&command_buffer); - } - let slots = (frame % 2) * BURST_HEAP; - let heaped: Vec = (0..BURST_HEAP) - .map(|i| { - let side = match bursting { - true => 128 + 2 * ((frame * BURST_HEAP + i) % BURST_HEAP_SIDES), - false => COMPOSITING_NEW_SIDE, - }; - let at = (slots + i) * COMPOSITING_SLOT; - g.heap_render_texture(&heap, Format::Bgra8, side, at) - }) - .collect(); - let mut targets: Vec = (0..BURST_STABLE) - .map(|i| g.texture(Format::Bgra8, burst_stable_side(i), 96, true)) - .collect(); - if bursting { - for _ in 0..BURST_ONE_OFF { - let width = 128 + one_off % BURST_ONE_OFF_WIDTHS; - one_off += 1; - targets.push(g.texture(Format::Bgra8, width, 64, true)); - } - } - let buffers = match bursting { - true => BURST_BUFFERS, - false => BURST_CALM_BUFFERS, - }; - // Each texture is cleared and drawn into by one of the command buffers before the - // last, in turn; the last draws the heap textures onto the screen. - let drawn: Vec<&G::Texture> = heaped.iter().chain(&targets).collect(); - let mut committed = Vec::with_capacity(buffers); - for c in 0..buffers { - let command_buffer = g.command_buffer(); - if c + 1 < buffers { - let mine = drawn - .iter() - .enumerate() - .filter(|(n, _)| n % (buffers - 1) == c); - for (n, target) in mine { - let mut encoder = g.render_encoder(&command_buffer, target, true); - g.set_render_pipeline(&mut encoder, &s.textured[0]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - g.set_fragment_texture(&mut encoder, &s.textures[n % TEXTURES], 0); - g.set_vertex_buffer(&mut encoder, &s.full, 0, 0); - g.draw_strip(&mut encoder, 4); - g.end_render(encoder); - } - } else { - let mut encoder = g.render_encoder(&command_buffer, &screen, false); - g.set_render_pipeline(&mut encoder, &s.textured[1]); - g.set_fragment_sampler(&mut encoder, &s.sampler, 0); - for (n, texture) in heaped.iter().enumerate() { - g.set_fragment_texture(&mut encoder, texture, 0); - let rects = &s.rects[n % RECT_BUFFERS]; - g.set_vertex_buffer(&mut encoder, rects, (n % RECTS) * RECT_STRIDE, 0); - g.draw_strip(&mut encoder, 4); - } - g.end_render(encoder); - } - g.commit(&command_buffer); - committed.push(command_buffer); - } - let encoded = start.elapsed(); - if bursting { - in_flight = committed; - } else { - for command_buffer in &committed { - g.wait(command_buffer); - } - } - BurstFrame { - start, - encoded, - cpu, - } - }); - if frame >= warm { - last = Some((bursting, before)); - frames.push((bursting, measured)); - } - next += period; - match next.checked_duration_since(Instant::now()) { - Some(left) => std::thread::sleep(left), - None => next = Instant::now(), - } - } - for command_buffer in in_flight.drain(..) { - g.wait(&command_buffer); - } - if let Some((was_bursting, then)) = last.take() { - add(was_bursting, &then, &g.work_counts()); - } - for (bursting, name) in [(false, "calm"), (true, "burst")] { - // A frame's interval: from its start to the next frame's (the run's last has none). - let pairs = || (frames.windows(2)).filter(|pair| pair[0].0 == bursting); - let mut intervals: Vec = pairs() - .map(|pair| ms(pair[1].1.start - pair[0].1.start)) - .collect(); - let over = |limit: f64| intervals.iter().filter(|&&ms| ms > limit).count() as f64; - let (over_16_7, over_25) = (over(1e3 / 60.0), over(25.0)); - emit( - "burst", - &format!("{name}_over_16_7ms"), - "frames", - &mut [over_16_7], - ); - emit( - "burst", - &format!("{name}_over_25ms"), - "frames", - &mut [over_25], - ); - let mut sorted = intervals.clone(); - sorted.sort_by(f64::total_cmp); - let p99 = sorted[((sorted.len() - 1) as f64 * 0.99).round() as usize]; - emit("burst", &format!("{name}_interval_p99"), "ms", &mut [p99]); - emit("burst", &format!("{name}_interval"), "ms", &mut intervals); - let class = || { - frames - .iter() - .filter(|(b, _)| *b == bursting) - .map(|(_, f)| f) - }; - let mut encoded: Vec = class().map(|f| ms(f.encoded)).collect(); - emit( - "burst", - &format!("{name}_encode_and_commit"), - "ms", - &mut encoded, - ); - let mut cpu: Vec = pairs() - .map(|pair| ms(pair[1].1.cpu - pair[0].1.cpu)) - .collect(); - emit("burst", &format!("{name}_process_cpu"), "ms", &mut cpu); - let (n, sum) = &counts[usize::from(bursting)]; - for (count, total) in sum { - let per_frame = total / *n as f64; - emit( - "burst", - &format!("{name}_rt_{count}"), - "per frame", - &mut [per_frame], - ); - } - } -} - -/// The icb workload's command counts per execution. -const ICB_COMMANDS: [usize; 4] = [16, 64, 256, 4096]; -/// The words of one command's window of the icb workload's data. -const ICB_WINDOW: usize = 64; -/// Untimed frames before the icb workload's timed ones. -const ICB_WARM: usize = 3; -/// The icb workload's live states made with `supportIndirectCommandBuffers`: the commands name -/// the first four at most, the rest stay alive unnamed, as an app's other such states do. Each -/// side of the runtime's bounds on the states an execution runs with on the GPU alone, at each -/// count of [`ICB_COMMANDS`] (a concurrent encoder's: 20, 8, 5 and 4; a serial encoder's: 44, 20, -/// 14 and 8). -const ICB_STATES: [usize; 10] = [1, 4, 5, 6, 8, 9, 14, 15, 20, 21]; -/// The most states the icb workload's commands name (`icb_step0` to `icb_step3`). -const ICB_NAMED: usize = 4; - -/// The icb workload (main.rs): per frame, one command buffer of a compute encoder whose kernel -/// (`icb_encode`) encodes `commands` compute commands into an indirect command buffer, one a -/// thread, and a second compute encoder that executes them, each command one threadgroup of 64 -/// threads of one of the first [`ICB_NAMED`] at most of `states` states made with -/// `supportIndirectCommandBuffers` (the only such states alive), in turn; committed and waited -/// for. For a serial and a concurrent executing encoder, each count of [`ICB_STATES`] and of -/// [`ICB_COMMANDS`]: the frame's wall time (the command buffer's creation to the wait's return), -/// the encoding thread's (through the commit's return) and the process's CPU time, and on the -/// runtime's side its work counts per frame (`rt_*`). The first frame's output is checked: each -/// command's window holds its state's step of zero. -pub fn icb(g: &G, library: &G::Library, sizes: &Sizes) { - let encode = g.compute_pipeline(library, "icb_encode"); - for states in ICB_STATES { - let named = states.min(ICB_NAMED); - let steps: Vec = (0..states) - .map(|k| g.indirect_compute_pipeline(library, &format!("icb_step{}", k % ICB_NAMED))) - .collect(); - for (concurrent, commands) in [false, true] - .into_iter() - .flat_map(|c| ICB_COMMANDS.map(|n| (c, n))) - { - let icb = g.indirect_commands(commands); - let mut arguments = g.commands_id(&icb).to_le_bytes().to_vec(); - for k in 0..ICB_NAMED { - arguments.extend(g.pipeline_id(&steps[k.min(named - 1)]).to_le_bytes()); - } - let arguments = g.buffer_with(&arguments); - let count = g.buffer_with(&(named as u32).to_le_bytes()); - let data = g.buffer_with(&vec![0u8; commands * ICB_WINDOW * 4]); - let threads = commands.min(64); - let (mut wall, mut encoding, mut cpu) = (vec![], vec![], vec![]); - let mut counts = Vec::new(); - for frame in 0..ICB_WARM + sizes.timed { - if frame == ICB_WARM { - counts = g.work_counts(); - } - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - let mut encoder = g.compute_encoder(&command_buffer); - g.set_compute_pipeline(&mut encoder, &encode); - g.set_buffer(&mut encoder, &arguments, 0, 0); - g.set_buffer(&mut encoder, &data, 0, 1); - g.set_buffer(&mut encoder, &count, 0, 2); - g.use_commands(&mut encoder, &icb); - g.dispatch(&mut encoder, commands / threads, threads); - g.end_compute(encoder); - let mut encoder = match concurrent { - true => g.concurrent_compute_encoder(&command_buffer), - false => g.compute_encoder(&command_buffer), - }; - g.use_buffer(&mut encoder, &data); - g.execute_commands(&mut encoder, &icb, commands); - g.end_compute(encoder); - g.commit(&command_buffer); - let t1 = Instant::now(); - g.wait(&command_buffer); - let t2 = Instant::now(); - if frame >= ICB_WARM { - wall.push(ms(t2 - t0)); - encoding.push(ms(t1 - t0)); - cpu.push(ms(process_cpu() - cpu0)); - } - }); - if frame == 0 { - let mut bytes = vec![0u8; commands * ICB_WINDOW * 4]; - g.read_buffer(&data, &mut bytes); - for (word, value) in bytes.as_chunks::<4>().0.iter().enumerate() { - let expected = (word / ICB_WINDOW % named) as u32 + 1; - assert_eq!( - u32::from_le_bytes(*value), - expected, - "icb: word {word} of {commands} commands of {states} states" - ); - } - } - } - let kind = if concurrent { "concurrent" } else { "serial" }; - let at = format!("{kind}_s{states}_c{commands}"); - emit("icb", &format!("frame_{at}"), "ms", &mut wall); - emit("icb", &format!("encode_{at}"), "ms", &mut encoding); - emit("icb", &format!("process_cpu_{at}"), "ms", &mut cpu); - let after = g.work_counts(); - for ((name, before), (_, now)) in counts.iter().zip(&after) { - if [ - "queue_submissions", - "pipeline_barriers", - "dispatches", - "dispatches_indirect", - ] - .contains(name) - { - let per_frame = (now - before) / sizes.timed as f64; - emit( - "icb", - &format!("rt_{name}_{at}"), - "per frame", - &mut [per_frame], - ); - } - } - } - } -} - -/// The commands of each of the icb_cpu workload's buffers. -const ICB_CPU_COMMANDS: usize = 4096; - -/// The icb_cpu workload (main.rs): the CPU's encoding of indirect commands and their read-back, -/// each call's time. Per pass, over [`ICB_CPU_COMMANDS`] commands of a buffer of dispatches and -/// one of draws (`Shared`, inheriting nothing), each setter on every command in turn, then each -/// getter; each call takes the command (`indirectComputeCommandAtIndex:` or -/// `indirectRenderCommandAtIndex:`) first, as a program that encodes once per command does. The -/// medians over the passes, in nanoseconds a call; [`ICB_WARM`] untimed passes first. -pub fn icb_cpu(g: &G, library: &G::Library, sizes: &Sizes) { - let state = g.indirect_compute_pipeline(library, "icb_step0"); - let draw = g.indirect_render_pipeline(library, "icb_draw_vertex", "icb_draw_fragment"); - let buffer = g.buffer(ICB_CPU_COMMANDS * 256); - let dispatches = g.cpu_indirect_commands(ICB_CPU_COMMANDS); - let draws = g.cpu_indirect_draws(ICB_CPU_COMMANDS); - let names = [ - "set_compute_pipeline", - "set_kernel_buffer", - "dispatch_threadgroups", - "set_barrier", - "kernel_buffer_address", - "has_barrier", - "set_render_pipeline", - "set_vertex_buffer", - "draw_primitives", - "vertex_buffer_address", - ]; - let mut times: Vec> = vec![Vec::new(); names.len()]; - let mut sink = 0u64; - for pass in 0..ICB_WARM + sizes.timed { - g.pool(|| { - let mut timed = |at: usize, call: &mut dyn FnMut(usize)| { - let t = Instant::now(); - for index in 0..ICB_CPU_COMMANDS { - call(index); - } - if pass >= ICB_WARM { - let each = t.elapsed().as_secs_f64() * 1e9 / ICB_CPU_COMMANDS as f64; - times[at].push(each); - } - }; - timed(0, &mut |i| g.command_pipeline(&dispatches, i, &state)); - timed(1, &mut |i| { - g.command_kernel_buffer(&dispatches, i, &buffer, i * 256) - }); - timed(2, &mut |i| g.command_dispatch(&dispatches, i, 1 + i % 4)); - timed(3, &mut |i| g.command_barrier(&dispatches, i)); - timed(4, &mut |i| { - sink = sink.wrapping_add(g.command_kernel_buffer_address(&dispatches, i)) - }); - timed(5, &mut |i| { - sink = sink.wrapping_add(u64::from(g.command_has_barrier(&dispatches, i))) - }); - timed(6, &mut |i| g.draw_command_pipeline(&draws, i, &draw)); - timed(7, &mut |i| { - g.draw_command_vertex_buffer(&draws, i, &buffer, i * 256) - }); - timed(8, &mut |i| g.draw_command_draw(&draws, i)); - timed(9, &mut |i| { - sink = sink.wrapping_add(g.draw_command_vertex_buffer_address(&draws, i)) - }); - }); - } - std::hint::black_box(sink); - for (name, times) in names.iter().zip(&mut times) { - emit("icb_cpu", name, "ns", times); - } -} - -/// The icb_draws workload's objects, as many as Apple's "Encoding Indirect Command Buffers on the GPU" -/// draws (`AAPLNumObjects`), on a grid of `ICB_DRAW_GRID` columns. -const ICB_DRAW_OBJECTS: usize = 65536; -const ICB_DRAW_GRID: usize = 256; -/// Each object's mesh: a hexagon's six triangles. -const ICB_DRAW_VERTICES: usize = 18; - -/// The icb_draws workload's objects and their indirect command buffer (`main.rs`'s module docs). -struct IcbDraws { - encode: G::ComputePipeline, - draw: G::RenderPipeline, - /// The frame state, the objects, the mesh, the argument buffer holding the buffer's ID and the - /// draws' primitive type (`icb_draw_encode_any_type`'s). - frame: G::Buffer, - objects: G::Buffer, - mesh: G::Buffer, - container: G::Buffer, - primitive: G::Buffer, - commands: G::IndirectCommands, - target: G::Texture, -} - -impl IcbDraws { - /// The objects, encoded by `kernel`. - fn new(g: &G, library: &G::Library, kernel: &str) -> IcbDraws { - // The grid spans a little more than the view, so its edge objects are culled. - let span = 2.2f32; - let cell = span / ICB_DRAW_GRID as f32; - let mut objects = Vec::with_capacity(ICB_DRAW_OBJECTS * 16); - for object in 0..ICB_DRAW_OBJECTS { - let (column, row) = (object % ICB_DRAW_GRID, object / ICB_DRAW_GRID); - let x = -span / 2.0 + (column as f32 + 0.5) * cell; - let y = -span / 2.0 + (row as f32 + 0.5) * cell; - for word in [x.to_bits(), y.to_bits(), (cell * 0.4).to_bits()] { - objects.extend_from_slice(&word.to_le_bytes()); - } - objects.extend_from_slice(&(ICB_DRAW_VERTICES as u32).to_le_bytes()); - } - let mut mesh = Vec::with_capacity(ICB_DRAW_VERTICES * 8); - let corner = |k: usize| { - let angle = k as f32 * std::f32::consts::TAU / 6.0; - [angle.cos() * cell * 0.4, angle.sin() * cell * 0.4] - }; - for k in 0..6 { - for [x, y] in [[0.0, 0.0], corner(k), corner(k + 1)] { - mesh.extend_from_slice(&f32::to_le_bytes(x)); - mesh.extend_from_slice(&f32::to_le_bytes(y)); - } - } - let frame: Vec = [0.0f32, 0.0, 1.0, 1.0] - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect(); - let commands = g.indirect_draws(ICB_DRAW_OBJECTS, 3); - IcbDraws { - encode: g.compute_pipeline(library, kernel), - draw: g.indirect_render_pipeline(library, "icb_draw_vertex", "icb_draw_fragment"), - frame: g.buffer_with(&frame), - objects: g.buffer_with(&objects), - mesh: g.buffer_with(&mesh), - container: g.buffer_with(&g.commands_id(&commands).to_le_bytes()), - // `MTLPrimitiveTypeTriangle`. - primitive: g.buffer_with(&3u32.to_le_bytes()), - commands, - target: g.texture(Format::Bgra8, 1920, 1080, true), - } - } - - /// One frame, as the sample's: a blit resets the commands, a kernel culls the objects and - /// encodes a command for each visible one, and a render pass executes them all. - fn encode(&self, g: &G, command_buffer: &G::CommandBuffer) { - g.reset_commands(command_buffer, &self.commands, ICB_DRAW_OBJECTS); - let mut encoder = g.compute_encoder(command_buffer); - g.set_compute_pipeline(&mut encoder, &self.encode); - g.set_buffer(&mut encoder, &self.frame, 0, 0); - g.set_buffer(&mut encoder, &self.objects, 0, 1); - g.set_buffer(&mut encoder, &self.mesh, 0, 2); - g.set_buffer(&mut encoder, &self.container, 0, 3); - g.set_buffer(&mut encoder, &self.primitive, 0, 4); - g.use_commands(&mut encoder, &self.commands); - g.dispatch(&mut encoder, ICB_DRAW_OBJECTS / 64, 64); - g.end_compute(encoder); - let mut encoder = g.render_encoder(command_buffer, &self.target, true); - g.set_render_pipeline(&mut encoder, &self.draw); - for buffer in [&self.frame, &self.objects, &self.mesh] { - g.use_in_vertex(&mut encoder, buffer); - } - g.execute_draws(&mut encoder, &self.commands, ICB_DRAW_OBJECTS); - g.end_render(encoder); - } -} - -/// The icb_draws workload (module docs of `main.rs`): per frame, the encoding thread's wall time -/// through `endEncoding`, the commit call's, the commit's return to the wait's, the whole frame's, -/// the process's CPU time, the encoding thread's CPU time through the commit's return, and the GPU -/// time where the side measures it; the same of commands whose primitive type the encoding kernel -/// reads from a buffer (`icb_draws_any_type`), and on the runtime's side its counts of commands -/// drawn on the GPU alone and records read on the host, per frame. -pub fn icb_draws(g: &G, library: &G::Library, sizes: &Sizes) { - for (name, kernel) in [ - ("icb_draws", "icb_draw_encode"), - ("icb_draws_any_type", "icb_draw_encode_any_type"), - ] { - let scene = IcbDraws::new(g, library, kernel); - let mut times: [Vec; 7] = Default::default(); - let mut counts = Vec::new(); - for frame in 0..sizes.timed + 3 { - if frame == 3 { - counts = g.work_counts(); - } - g.pool(|| { - let cpu = process_cpu(); - let thread = thread_cpu(); - let start = Instant::now(); - let command_buffer = g.command_buffer(); - scene.encode(g, &command_buffer); - let encoded = Instant::now(); - g.commit(&command_buffer); - let committed = Instant::now(); - let thread = thread_cpu() - thread; - g.wait(&command_buffer); - let done = Instant::now(); - let cpu = process_cpu() - cpu; - if frame < 3 { - return; - } - times[6].push(ms(thread)); - times[0].push(ms(encoded - start)); - times[1].push(ms(committed - encoded)); - times[2].push(ms(done - committed)); - times[3].push(ms(done - start)); - times[4].push(ms(cpu)); - if let Some(gpu) = g.gpu_seconds(&command_buffer) { - times[5].push(gpu * 1e3); - } - }); - } - let [encode, commit, wait, frame, cpu, gpu, thread] = &mut times; - emit(name, "encode", "ms", encode); - emit(name, "commit", "ms", commit); - emit(name, "commit_to_done", "ms", wait); - emit(name, "frame", "ms", frame); - emit(name, "cpu", "ms", cpu); - emit(name, "thread_cpu", "ms", thread); - if !gpu.is_empty() { - emit(name, "gpu", "ms", gpu); - } - let after = g.work_counts(); - for ((counted, before), (_, now)) in counts.iter().zip(&after) { - if matches!( - *counted, - "gpu_form_commands" - | "merged_draw_commands" - | "indirect_records_read" - | "draws" - | "pipeline_barriers" - ) { - let per_frame = (now - before) / sizes.timed as f64; - emit(name, &format!("rt_{counted}"), "count", &mut [per_frame]); - } - } - } -} - -/// A frame of the calls workload, as a guest cuts one (module docs of `main.rs`): command -/// buffers, each of a render pass of `draws` draws, two compute encoders of `dispatches` -/// dispatches and a blit encoder of `blits` copies. -#[derive(Clone, Copy)] -struct CallShape { - name: &'static str, - command_buffers: usize, - draws: usize, - dispatches: usize, - blits: usize, -} - -/// One command buffer of long encoders, and many of short ones. -const CALL_SHAPES: [CallShape; 2] = [ - CallShape { - name: "wide", - command_buffers: 1, - draws: 512, - dispatches: 64, - blits: 32, - }, - CallShape { - name: "many", - command_buffers: 64, - draws: 16, - dispatches: 1, - blits: 1, - }, -]; - -/// The calls a frame of the calls workload times, each a step. -const CALL_STEPS: [&str; 16] = [ - "command_buffer", - "render_encoder", - "set_state", - "set_vertex_buffers", - "set_fragment_texture", - "set_fragment_sampler", - "set_fragment_buffer", - "draw", - "end_render", - "compute_encoder", - "dispatch", - "dispatch_resident", - "end_compute", - "blit_copy", - "end_blit", - "handler_commit", -]; - -/// The buffers the second compute encoder of each command buffer makes resident. -const CALL_RESIDENT: usize = 16; - -/// Each step's total and count over a frame: nanoseconds, or with `allocs` the allocations -/// (`crate::allocs`) on the encoding thread. -#[derive(Clone, Copy, Default)] -struct StepTally([(u64, u64); CALL_STEPS.len()]); - -impl StepTally { - fn time(&mut self, step: usize, allocs: bool, call: impl FnOnce() -> T) -> T { - let (out, amount) = match allocs { - true => { - let before = crate::allocs::this_thread(); - let out = call(); - (out, crate::allocs::this_thread() - before) - } - false => { - let start = Instant::now(); - let out = call(); - (out, start.elapsed().as_nanos() as u64) - } - }; - let (total, count) = &mut self.0[step]; - *total += amount; - *count += 1; - out - } -} - -/// The calls workload's objects. -struct CallObjects { - pass: G::Pass, - positions: G::Buffer, - colours: G::Buffer, - uniforms: G::Buffer, - states: [G::RenderPipeline; 2], - input: G::Buffer, - output: G::Buffer, - resident: Vec, - from: G::Buffer, - to: G::Buffer, -} - -impl CallObjects { - /// One command buffer of `shape`, its calls timed (or their allocations counted) into `t`, - /// committed with a completed handler that sends on its channel. - fn command_buffer( - &self, - g: &G, - s: &Scene, - shape: CallShape, - (t, allocs): (&mut StepTally, bool), - ) -> (G::CommandBuffer, mpsc::Receiver<()>) { - let cb = t.time(0, allocs, || g.command_buffer()); - let mut e = t.time(1, allocs, || g.pass_encoder(&cb, &self.pass)); - let vertex = [&self.positions, &self.colours]; - for i in 0..shape.draws { - let textured = (i / 8) % 2 == 0; - if i % 8 == 0 { - let state = &self.states[usize::from(!textured)]; - t.time(2, allocs, || g.set_render_pipeline(&mut e, state)); - } - t.time(3, allocs, || { - g.set_vertex_buffers(&mut e, &vertex, &[0, (i % 64) * 16], 0) - }); - if textured { - t.time(4, allocs, || { - g.set_fragment_texture(&mut e, &s.textures[0], 0) - }); - t.time(5, allocs, || g.set_fragment_sampler(&mut e, &s.sampler, 0)); - } else { - t.time(6, allocs, || { - g.set_fragment_buffer(&mut e, &self.uniforms, (i % 256) * 256, 0) - }); - } - t.time(7, allocs, || g.draw_strip(&mut e, 4)); - } - t.time(8, allocs, || g.end_render(e)); - let resident: Vec<&G::Buffer> = self.resident.iter().collect(); - for (step, used) in [(10, &resident[..0]), (11, &resident[..])] { - let mut e = t.time(9, allocs, || g.compute_encoder(&cb)); - g.set_compute_pipeline(&mut e, &s.tiny[0]); - if !used.is_empty() { - g.use_buffers_read(&mut e, used); - } - for i in 0..shape.dispatches { - let at = i * 256; - t.time(step, allocs, || { - g.set_buffer(&mut e, &self.output, at, 0); - g.set_buffer(&mut e, &self.input, at, 1); - g.dispatch(&mut e, 1, 64); - }); - } - t.time(12, allocs, || g.end_compute(e)); - } - let mut blit = g.blit_encoder(&cb); - for i in 0..shape.blits { - let at = i * 1024; - t.time(13, allocs, || { - g.copy_buffer(&mut blit, (&self.from, at), (&self.to, at), 1024) - }); - } - t.time(14, allocs, || g.end_blit(blit)); - let (tx, rx) = mpsc::channel(); - t.time(15, allocs, || { - g.on_completed(&cb, Box::new(move || tx.send(()).unwrap())); - g.commit(&cb); - }); - (cb, rx) - } - - /// One frame of `shape`: its command buffers committed, then each one's handler and wait. - fn frame(&self, g: &G, s: &Scene, shape: CallShape, allocs: bool) -> StepTally { - g.pool(|| { - let mut t = StepTally::default(); - let committed: Vec<_> = (0..shape.command_buffers) - .map(|_| self.command_buffer(g, s, shape, (&mut t, allocs))) - .collect(); - for (cb, rx) in committed { - rx.recv().unwrap(); - g.wait(&cb); - } - t - }) - } -} - -/// The buffers the calls workload's `resident_*` variants make resident, of 256 bytes each. -const DRAWN_RESIDENT: usize = 4096; - -/// The draws of a `resident_*` variant's render encoder. -const RESIDENT_DRAWS: usize = 512; - -/// The calls workload's `resident_*` variants, each run only where named: a render encoder of the -/// buffer-fragment pipeline state, its vertex and fragment buffers set, one -/// `useResources:count:usage:stages:` (reading, vertex and fragment) of 0, 1, 256 or 4096 buffers, -/// then [`RESIDENT_DRAWS`] draws of a strip with nothing changed between them. Per variant: the -/// `useResources` call, the encoding thread's wall time per draw after it, and the command -/// buffer's whole time to its wait's return. -fn calls_resident(g: &G, objects: &CallObjects, sizes: &Sizes, variants: &[String]) { - let wanted: Vec<(&str, usize)> = [("0", 0), ("1", 1), ("256", 256), ("4096", 4096)] - .into_iter() - .filter(|(name, _)| variants.iter().any(|v| *v == format!("resident_{name}"))) - .collect(); - if wanted.is_empty() { - return; - } - let resident: Vec = (0..DRAWN_RESIDENT).map(|_| g.buffer(256)).collect(); - let vertex = [&objects.positions, &objects.colours]; - for (name, count) in wanted { - let list: Vec<&G::Buffer> = resident[..count].iter().collect(); - let (mut using, mut draws, mut total) = (vec![], vec![], vec![]); - for run in 0..sizes.timed + 3 { - g.pool(|| { - let t0 = Instant::now(); - let cb = g.command_buffer(); - let mut e = g.pass_encoder(&cb, &objects.pass); - g.set_render_pipeline(&mut e, &objects.states[1]); - g.set_vertex_buffers(&mut e, &vertex, &[0, 0], 0); - g.set_fragment_buffer(&mut e, &objects.uniforms, 0, 0); - let t1 = Instant::now(); - g.use_buffers_drawn(&mut e, &list); - let t2 = Instant::now(); - for _ in 0..RESIDENT_DRAWS { - g.draw_strip(&mut e, 4); - } - let t3 = Instant::now(); - g.end_render(e); - g.commit(&cb); - g.wait(&cb); - let t4 = Instant::now(); - if run >= 3 { - using.push((t2 - t1).as_secs_f64() * 1e6); - draws.push((t3 - t2).as_secs_f64() * 1e9 / RESIDENT_DRAWS as f64); - total.push((t4 - t0).as_secs_f64() * 1e3); - } - }); - } - let metric = |what: &str| format!("resident_{name}_{what}"); - emit("calls", &metric("use_call"), "us", &mut using); - emit("calls", &metric("draw"), "ns/call", &mut draws); - emit("calls", &metric("cb_total"), "ms", &mut total); - } -} - -/// The consumer's frames, call by call (module docs of `main.rs`): each step's mean a call over -/// each timed frame, then its allocations a call on the encoding thread over one more frame. -/// The `resident_*` variants run only where named ([`calls_resident`]). -pub fn calls( - g: &G, - s: &Scene, - library: &G::Library, - sizes: &Sizes, - variants: &[String], -) { - let floats_of = |n: usize, f: &dyn Fn(usize) -> [f32; 4]| { - let values: Vec = (0..n).flat_map(f).collect(); - g.buffer_with(&floats(&values)) - }; - let state = - |fragment| g.render_pipeline(library, "calls_vertex", fragment, Format::Bgra8, false); - let objects = CallObjects { - pass: g.pass(&s.target), - // A strip of four corners of a small square, then nothing. - positions: floats_of(256, &|v| match v { - 0..4 => [ - -0.1 + 0.2 * (v & 1) as f32, - -0.1 + 0.2 * (v >> 1) as f32, - 0.0, - 1.0, - ], - _ => [0.0; 4], - }), - colours: floats_of(256, &|v| [0.5, (v % 7) as f32 / 7.0, 0.25, 1.0]), - uniforms: floats_of(4096, &|v| [(v % 5) as f32 / 5.0, 0.5, 0.5, 1.0]), - states: [ - state("calls_texture_fragment"), - state("calls_buffer_fragment"), - ], - input: g.buffer_with(&vec![1u8; 65536]), - output: g.buffer(65536), - resident: (0..CALL_RESIDENT).map(|_| g.buffer(4096)).collect(), - from: g.buffer_with(&vec![0x3cu8; 65536]), - to: g.buffer(65536), - }; - const WARM: usize = 5; - let shapes = CALL_SHAPES - .into_iter() - .filter(|shape| variants.is_empty() || variants.iter().any(|v| v == shape.name)); - for shape in shapes { - let mut means: [Vec; CALL_STEPS.len()] = Default::default(); - let (mut frames, mut walls) = (vec![], vec![]); - for frame in 0..WARM + sizes.timed { - let start = Instant::now(); - let t = objects.frame(g, s, shape, false); - let wall = start.elapsed(); - if frame >= WARM { - walls.push(wall.as_secs_f64() * 1e6); - let mut sum = 0.0; - for (step, &(total, count)) in t.0.iter().enumerate() { - if count > 0 { - means[step].push(total as f64 / count as f64); - } - sum += total as f64; - } - frames.push(sum / 1e3); - } - } - let name = shape.name; - for (step, values) in CALL_STEPS.iter().zip(&mut means) { - if !values.is_empty() { - emit("calls", &format!("{name}_{step}"), "ns/call", values); - } - } - emit("calls", &format!("{name}_frame_calls"), "us", &mut frames); - // The frame from its first call until its last command buffer's handler ran and its wait - // returned: what the calls cost, and how soon their work went to the GPU and completed. - emit("calls", &format!("{name}_frame_wall"), "us", &mut walls); - let t = crate::allocs::counting(|| objects.frame(g, s, shape, true)); - for (step, &(total, count)) in CALL_STEPS.iter().zip(&t.0) { - if count > 0 { - emit( - "calls", - &format!("{name}_{step}_allocs"), - "allocs/call", - &mut [total as f64 / count as f64], - ); - } - } - } - calls_resident(g, &objects, sizes, variants); -} - -/// The provoking workload's draws in a frame: each two small triangles of six vertices of their own -/// in a 64 by 32 grid over the target (module docs of `main.rs`). -const FLAT_VERTICES: usize = 6; - -/// How the provoking workload draws. -#[derive(Clone, Copy)] -enum FlatForm { - Direct, - Indexed, - IndexedStrip, - Indirect, - IndexedIndirect, -} - -impl FlatForm { - fn name(self) -> &'static str { - match self { - FlatForm::Direct => "direct", - FlatForm::Indexed => "indexed", - FlatForm::IndexedStrip => "indexed_strip", - FlatForm::Indirect => "indirect", - FlatForm::IndexedIndirect => "indexed_indirect", - } - } -} - -/// An OpenGL guest's flat-shaded draws (module docs of `main.rs`): per draw, at -/// `setProvokingVertexMode:` 0 and at 1 (Apple's GL's last vertex), each form's encoding time, -/// the process's CPU time, and the frame from the command buffer's creation to the wait's return. -pub fn provoking(g: &G, library: &G::Library, sizes: &Sizes) { - let n = sizes.draws; - assert!( - n * FLAT_VERTICES <= 65536, - "--draws {n}: past 16-bit indices" - ); - let mut positions = Vec::with_capacity(n * FLAT_VERTICES * 16); - for draw in 0..n { - let cell = draw % 2048; - let (x, y) = ((cell % 64) as f32, (cell / 64) as f32); - let (x0, x1) = (x / 32.0 - 1.0, (x + 0.8) / 32.0 - 1.0); - let (y0, y1) = (y / 16.0 - 1.0, (y + 0.8) / 16.0 - 1.0); - for (px, py) in [(x0, y0), (x1, y0), (x0, y1), (x0, y1), (x1, y0), (x1, y1)] { - positions.extend(floats(&[px, py, 0.0, 1.0])); - } - } - let words = |w: &[u32]| -> Vec { w.iter().flat_map(|w| w.to_le_bytes()).collect() }; - let indices: Vec = (0..n * FLAT_VERTICES) - .flat_map(|i| (i as u16).to_le_bytes()) - .collect(); - // Each draw's two triangles as a strip of four of its six vertices: the list's second - // triangle is the strip's second, in its order. - let strip_indices: Vec = (0..n * FLAT_VERTICES) - .step_by(FLAT_VERTICES) - .flat_map(|at| [at, at + 1, at + 2, at + 5]) - .flat_map(|i| (i as u16).to_le_bytes()) - .collect(); - let arguments: Vec = (0..n) - .flat_map(|d| [FLAT_VERTICES as u32, 1, (d * FLAT_VERTICES) as u32, 0]) - .collect(); - let indexed_arguments: Vec = (0..n) - .flat_map(|d| [FLAT_VERTICES as u32, 1, (d * FLAT_VERTICES) as u32, 0, 0]) - .collect(); - let positions = g.buffer_with(&positions); - let indices = g.buffer_with(&indices); - let strip_indices = g.buffer_with(&strip_indices); - let arguments = g.buffer_with(&words(&arguments)); - let indexed_arguments = g.buffer_with(&words(&indexed_arguments)); - let pipeline = g.render_pipeline( - library, - "flat_vertex", - "flat_fragment", - Format::Bgra8, - false, - ); - let target = g.texture(Format::Bgra8, TARGET_SIDE, TARGET_SIDE, true); - let forms = [ - FlatForm::Direct, - FlatForm::Indexed, - FlatForm::IndexedStrip, - FlatForm::Indirect, - FlatForm::IndexedIndirect, - ]; - for form in forms { - for mode in [0u64, 1] { - let name = format!("{}_mode{mode}", form.name()); - let counts = g.work_counts(); - let mut times: [Vec; 4] = Default::default(); - for run in 0..sizes.timed + 3 { - g.pool(|| { - let cpu0 = process_cpu(); - let t0 = Instant::now(); - let command_buffer = g.command_buffer(); - let mut encoder = g.render_encoder(&command_buffer, &target, true); - g.set_render_pipeline(&mut encoder, &pipeline); - g.set_vertex_buffer(&mut encoder, &positions, 0, 0); - g.set_provoking_vertex_mode(&mut encoder, mode); - for draw in 0..n { - let at = draw * FLAT_VERTICES; - match form { - FlatForm::Direct => g.draw_triangles(&mut encoder, at, FLAT_VERTICES), - FlatForm::Indexed => { - g.draw_indexed_at(&mut encoder, FLAT_VERTICES, &indices, at * 2) - } - FlatForm::IndexedStrip => { - g.draw_indexed_strip_at(&mut encoder, 4, &strip_indices, draw * 8) - } - FlatForm::Indirect => { - g.draw_triangles_indirect(&mut encoder, &arguments, draw * 16) - } - FlatForm::IndexedIndirect => g.draw_indexed_indirect( - &mut encoder, - &indices, - &indexed_arguments, - draw * 20, - ), - } - } - g.end_render(encoder); - let t1 = Instant::now(); - g.commit(&command_buffer); - g.wait(&command_buffer); - let t2 = Instant::now(); - let cpu1 = process_cpu(); - if run >= 3 { - times[0].push(us(t1 - t0) / n as f64); - times[1].push(us(cpu1 - cpu0) / n as f64); - times[2].push(ms(t2 - t1)); - times[3].push(us(t2 - t0) / n as f64); - } - }); - } - let [encode, cpu, wait, frame] = &mut times; - emit("provoking", &format!("{name}_encode"), "us/draw", encode); - emit("provoking", &format!("{name}_process_cpu"), "us/draw", cpu); - emit("provoking", &format!("{name}_commit_to_done"), "ms", wait); - emit("provoking", &format!("{name}_frame"), "us/draw", frame); - let after = g.work_counts(); - for ((counted, before), (_, now)) in counts.iter().zip(&after) { - if matches!( - *counted, - "provoking_last_pipeline_draws" - | "provoking_listed_draws" - | "gathered_draws" - | "bounded_run_draws" - | "dispatches" - | "pipeline_barriers" - ) { - let per_frame = (now - before) / (sizes.timed + 3) as f64; - emit( - "provoking", - &format!("{name}_rt_{counted}"), - "count", - &mut [per_frame], - ); - } - } - } - } -} diff --git a/crates/metal2vulkan-runtime/examples/icb_reads.rs b/crates/metal2vulkan-runtime/examples/icb_reads.rs deleted file mode 100644 index 8a170716a..000000000 --- a/crates/metal2vulkan-runtime/examples/icb_reads.rs +++ /dev/null @@ -1,875 +0,0 @@ -//! Not a consumer's example: what an indirect command buffer's records cost the GPU and the host, -//! where a kernel or the CPU writes them and a render pass executes them. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example icb_reads -- \ -//! [--commands N] [--runs R] [--only SHAPE,...] [--idle S] [--heap-textures H] [--no-twin] \ -//! [--rate-map] [--wide-every W] -//! ``` -//! -//! Each shape's buffer holds `N` draw commands (8192 by default) that inherit the pipeline state, -//! each of one triangle of its own over a 1024 by 1024 `RGBA8Unorm` target (an 8 by 8 texel -//! cell's lower half, in rows), its vertices read by vertex ID from vertex buffer 0, which every -//! command binds, with fragment buffer 1 (`kernel_icb_encode_render_commands`' bindings); the -//! fragment function returns opaque magenta. The shapes: -//! -//! - **`gpu-shared`** and **`gpu-private`**: a buffer of `Shared`, or `Private`, storage whose -//! commands the owned kernel `kernel_icb_encode_render_commands` writes, one thread a command, -//! in one command buffer, and a render pass of another command buffer executes; -//! - **`gpu-reset`**: `gpu-shared` with each thread first resetting its command on the GPU -//! (`air.reset_render_command`), as a kernel that encodes commands anew each frame does; -//! - **`cpu-shared`**: a `Shared` buffer whose commands the CPU writes through each command's -//! setters (its two buffers and its draw), then a render pass executes; -//! - **`gpu-step`**: as `gpu-shared`, but each command's fragment buffer 1 is a material: an -//! argument buffer of [`TEXTURES`] textures, which its fragment function samples (Metal takes no -//! direct texture argument in a state that supports indirect command buffers), of the `H` (512 -//! by default) 64 by 64 textures of a heap the pass uses (`use_heap`), as a 3D renderer's -//! materials lie in one. The kernel is the owned one with its fragment buffer the material in -//! place of the vertices, and no output; the CPU set a barrier on the last command and cleared -//! it first, so the buffer may hold barriers and its execution takes the host step -//! (`render/executions.rs`), as a renderer's commands a culling kernel writes may. The fragment -//! function adds the samples, times zero, to magenta. Before the shapes run, the device makes a -//! no-copy buffer of host pages with the private option bit (`ResourceOptions::PRIVATE_BIT`), -//! which takes a read twin where the device imports its pages in place, as a guest's window -//! server's buffers do, so each command's slots are looked at for read twins -//! (`binding::TwinSlots`); `--no-twin` makes none. -//! -//! With `--rate-map`, every shape's pass is over a rasterization-rate map of a guest's rate-mapped -//! frame (`rate_mapped_pieces`' in the validation crate's runtime lane): one layer over a -//! [`MAP_SCREEN`] screen whose quality falls from 1 at the centre to 0.3 at the edges on both axes -//! ([`MAP_QUALITY`]), into a target of its physical size, so the `gpu-step` shape's host step fans -//! the commands' triangles out to the map's regions after a probe (`rate_mapped_pass.rs`, -//! **Fan-out**). With `--wide-every W` too, every `W`th command's triangle covers the screen, -//! which touches more regions than the fan-out's copies: the probe flags it, and its draw is drawn -//! in parts. The read-back check is left out over a map, whose regions move the texels. -//! -//! Each line is the median over `R` runs (9 by default) after one not counted, of each command -//! buffer's GPU time (`gpu_start_time` to `gpu_end_time`) a command, the writer's (`encode`, the -//! kernel's command buffer; none for the CPU's) and the pass's (`execute`), and the host's time a -//! command in the CPU's setters (`cpu_encode`), with the runtime's counts a run that moved over -//! the counted runs (`WorkCounts`, by name from their `Debug` form). Once a shape's runs ended its -//! target is read back: every texel a triangle covers must be magenta. -//! -//! ```text -//! ICB-READS commands gpu_us_per_command encode execute -//! cpu_encode_us_per_command host_step_ns_per_command -//! ICB-READS-COUNTS = ... -//! ``` -//! -//! `host_step_ns_per_command` is a run's `WorkCounts::host_step_nanos` over its commands: the time -//! the host step's thread spent recording the execution, 0 where none took the step. The read -//! twin's making prints `ICB-TWIN read_twins_made `. -//! -//! With `--idle S`, the CPU's shape first waits `S` seconds with no work on the device, then -//! writes one buffer's commands, commits its pass and waits for it, printing the longest single -//! setter call, the writes' and the commit's times and the commit to the completion: -//! -//! ```text -//! ICB-IDLE longest_setter_ms encode_ms commit_ms commit_to_completed_ms -//! ``` -//! -//! The render functions are LLVM text here and the kernel the owned fixture's (`metal2vulkan- -//! validation/fixtures/public/kernel_icb_encode_render_commands.ll`, built in), each assembled by -//! `llvm-as` from `PATH`. - -use metal2vulkan::bind::{RateMapDescriptor, RateMapLayerDescriptor}; -use metal2vulkan::metal::{ - IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureUsage, -}; -use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, -}; -use metal2vulkan_runtime::{ - BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, - Device, Heap, HeapDescriptor, HeapType, HostMemory, IndirectCommandBuffer, - IndirectCommandBufferDescriptor, Library, LoadAction, Origin, PipelineOptions, - RasterizationRateMap, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, Texture, TextureDescriptor, WorkCounts, -}; -use std::collections::BTreeMap; -use std::io::Write; -use std::process::{Command, Stdio}; -use std::ptr::NonNull; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// The target's side, and a cell's. -const SIDE: u64 = 1024; -const CELL: u64 = 8; - -/// The fragment function's color, exact in `RGBA8Unorm`. -const TEXEL: [u8; 4] = [255, 0, 255, 255]; - -/// The writer: the owned fixture's kernel. -const WRITER: &str = include_str!( - "../../metal2vulkan-validation/fixtures/public/kernel_icb_encode_render_commands.ll" -); - -/// `icb_vertex`: the `float4` at vertex `id` of vertex buffer 0; `icb_fragment`: opaque magenta. -const FUNCTIONS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define <4 x float> @icb_vertex(ptr addrspace(1) noundef readonly %v, i32 noundef %id) {\n\ -entry:\n\ - %i = zext i32 %id to i64\n\ - %p = getelementptr inbounds <4 x float>, ptr addrspace(1) %v, i64 %i\n\ - %x = load <4 x float>, ptr addrspace(1) %p, align 16\n\ - ret <4 x float> %x\n\ -}\n\n\ -define <4 x float> @icb_fragment() {\n\ -entry:\n\ - ret <4 x float> \n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.vertex = !{!20}\n!air.fragment = !{!30}\n\ -!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_constant_buffers\", i32 31}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @icb_vertex, !21, !23}\n\ -!21 = !{!22}\n\ -!22 = !{!\"air.position\", !\"air.arg_type_name\", !\"float4\"}\n\ -!23 = !{!24, !25}\n\ -!24 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"v\"}\n\ -!25 = !{i32 1, !\"air.vertex_id\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"id\"}\n\ -!26 = !{!27}\n\ -!27 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}\n\ -!28 = !{}\n\ -!30 = !{ptr @icb_fragment, !26, !28}\n"; - -/// The screen of `--rate-map`'s map, and its quality samples on both axes. -const MAP_SCREEN: [u32; 2] = [3648, 1734]; -const MAP_QUALITY: [f32; 5] = [0.3, 0.6, 1.0, 0.6, 0.3]; - -/// The textures of a `gpu-step` command's material, which its fragment function samples. -const TEXTURES: u32 = 8; - -/// The side of each texture of the `gpu-step` shape's heap. -const TEXTURE_SIDE: u64 = 64; - -/// `icb_vertex` (as [`FUNCTIONS`]'), and `icb_sampled`: opaque magenta plus zero times the sum -/// of the samples of the [`TEXTURES`] textures of the material at fragment buffer 1 (an argument -/// buffer of their resource IDs), at the fragment's position, each through one constexpr sampler. -fn sampled_functions() -> String { - let n = TEXTURES as usize; - let mut body = String::from( - " %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> \n \ - %uv = fmul <2 x float> %xy, \n", - ); - let mut sum = String::from("zeroinitializer"); - for t in 0..n { - body += &format!( - " %p{t} = getelementptr inbounds i8, ptr addrspace(2) %material, i64 {}\n \ - %t{t} = load ptr addrspace(1), ptr addrspace(2) %p{t}, align 8\n \ - %s{t} = call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) \ - %t{t}, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> \ - zeroinitializer, i1 false, float 0.0, float 0.0, i32 0)\n %v{t} = extractvalue \ - {{ <4 x float>, i8 }} %s{t}, 0\n %a{t} = fadd <4 x float> {sum}, %v{t}\n", - 8 * t - ); - sum = format!("%a{t}"); - } - body += &format!( - " %z = fmul <4 x float> {sum}, zeroinitializer\n %out = fadd <4 x float> , %z\n" - ); - let fields: Vec = (0..n) - .map(|t| { - format!( - "i32 {}, i32 8, i32 0, !\"texture2d\", !\"t{t}\", \ - !\"air.indirect_argument\", !{}", - 8 * t, - 60 + t - ) - }) - .collect(); - let textures: Vec = (0..n) - .map(|t| { - format!( - "!{} = !{{i32 {t}, !\"air.texture\", !\"air.location_index\", i32 {t}, i32 1, \ - !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", \ - !\"air.arg_name\", !\"t{t}\"}}\n", - 60 + t - ) - }) - .collect(); - let bytes = 8 * n; - let vertex_at = FUNCTIONS - .find("define <4 x float> @icb_vertex") - .expect("icb_vertex"); - let vertex_end = vertex_at + FUNCTIONS[vertex_at..].find("}\n").expect("its end") + 2; - format!( - "{head}@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 \ - 34901797601020489, i64 0], align 8\n\n{vertex}\n\ - define <4 x float> @icb_sampled(<4 x float> %pos, ptr addrspace(2) %material) \ - {{\nentry:\n{body} ret <4 x float> %out\n}}\n\n\ - declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr \ - addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)\n\n\ - !llvm.module.flags = !{{!0, !1}}\n!air.vertex = !{{!20}}\n!air.fragment = !{{!40}}\n\ - !air.sampler_states = !{{!45}}\n!air.version = !{{!8}}\n!air.language_version = !{{!9}}\n\ - !0 = !{{i32 7, !\"air.max_device_buffers\", i32 31}}\n\ - !1 = !{{i32 7, !\"air.max_constant_buffers\", i32 31}}\n\ - !8 = !{{i32 2, i32 8, i32 0}}\n!9 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n\ - {vertex_metadata}\ - !26 = !{{!27}}\n\ - !27 = !{{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}}\n\ - !40 = !{{ptr @icb_sampled, !26, !41}}\n!41 = !{{!49, !50}}\n\ - !45 = !{{!\"air.sampler_state\", ptr addrspace(2) @__air_sampler_state}}\n\ - !49 = !{{i32 0, !\"air.position\", !\"air.center\", !\"air.no_perspective\", \ - !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"position\"}}\n\ - !50 = !{{i32 1, !\"air.indirect_buffer\", !\"air.buffer_size\", i32 {bytes}, \ - !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 2, \ - !\"air.struct_type_info\", !51, !\"air.arg_type_size\", i32 {bytes}, \ - !\"air.arg_type_align_size\", i32 8, !\"air.arg_type_name\", !\"Material\", \ - !\"air.arg_name\", !\"material\"}}\n!51 = !{{{fields}}}\n{textures}", - head = &FUNCTIONS[..FUNCTIONS.find("define").expect("a definition")], - vertex = &FUNCTIONS[vertex_at..vertex_end], - vertex_metadata = (FUNCTIONS.lines()) - .filter(|line| ["!20 ", "!21 ", "!22 ", "!23 ", "!24 ", "!25 "] - .iter() - .any(|id| line.starts_with(id))) - .map(|line| format!("{line}\n")) - .collect::(), - fields = fields.join(", "), - textures = textures.concat(), - ) -} - -/// A shape: who writes the commands, and the buffer's storage. -#[derive(Clone, Copy, PartialEq)] -enum Shape { - GpuShared, - GpuReset, - GpuPrivate, - CpuShared, - GpuStep, -} - -impl Shape { - const ALL: [Shape; 5] = [ - Shape::GpuShared, - Shape::GpuReset, - Shape::GpuPrivate, - Shape::CpuShared, - Shape::GpuStep, - ]; - - fn name(self) -> &'static str { - match self { - Shape::GpuShared => "gpu-shared", - Shape::GpuReset => "gpu-reset", - Shape::GpuPrivate => "gpu-private", - Shape::CpuShared => "cpu-shared", - Shape::GpuStep => "gpu-step", - } - } - - fn options(self) -> ResourceOptions { - match self { - Shape::GpuPrivate => ResourceOptions::private(), - _ => ResourceOptions::shared(), - } - } -} - -/// The run's arguments. -struct Args { - commands: u64, - runs: usize, - only: Vec, - idle: Option, - heap_textures: u64, - twin: bool, - rate_map: bool, - wide_every: Option, -} - -impl Args { - fn parse() -> Result { - let mut parsed = Args { - commands: 8192, - runs: 9, - only: Vec::new(), - idle: None, - heap_textures: 512, - twin: true, - rate_map: false, - wide_every: None, - }; - let mut args = std::env::args().skip(1); - while let Some(arg) = args.next() { - let mut value = || args.next().ok_or_else(|| format!("{arg} takes a value")); - match arg.as_str() { - "--commands" => parsed.commands = value()?.parse()?, - "--runs" => parsed.runs = value()?.parse()?, - "--only" => parsed.only = value()?.split(',').map(str::to_owned).collect(), - "--idle" => parsed.idle = Some(value()?.parse()?), - "--heap-textures" => parsed.heap_textures = value()?.parse()?, - "--no-twin" => parsed.twin = false, - "--rate-map" => parsed.rate_map = true, - "--wide-every" => parsed.wide_every = Some(value()?.parse()?), - other => return Err(format!("unknown argument {other}").into()), - } - } - let cells = (SIDE / CELL) * (SIDE / CELL); - if parsed.commands == 0 || parsed.commands > cells || parsed.runs == 0 { - return Err(format!("commands must be 1 to {cells}, and runs at least 1").into()); - } - if parsed.heap_textures < u64::from(TEXTURES) { - return Err(format!("the heap holds at least {TEXTURES} textures").into()); - } - if parsed - .wide_every - .is_some_and(|every| every == 0 || !parsed.rate_map) - { - return Err("--wide-every takes a count of 1 or more, with --rate-map".into()); - } - Ok(parsed) - } - - fn runs(&self, shape: Shape) -> bool { - self.only.is_empty() || self.only.iter().any(|name| name == shape.name()) - } -} - -/// Run `tool` from `PATH` over `input`: its output. -fn tool(tool: &str, args: &[&str], input: &str) -> Result> { - let mut child = Command::new(tool) - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; - child - .stdin - .take() - .ok_or("no stdin")? - .write_all(input.as_bytes())?; - let output = child.wait_with_output()?; - if !output.status.success() { - return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); - } - Ok(output.stdout) -} - -/// The counts of `counts` by name, read from their `Debug` form. -fn counts(counts: &WorkCounts) -> BTreeMap { - let text = format!("{counts:?}"); - text.split([',', '{']) - .filter_map(|part| { - let (name, value) = part.split_once(':')?; - Some((name.trim().to_owned(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// Commit `command_buffer` and wait for it: an error where it did not complete. -fn run(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer.commit()?; - wait(command_buffer) -} - -/// Wait for `command_buffer`: an error where it did not complete. -fn wait(command_buffer: &CommandBuffer) -> Result<()> { - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - match command_buffer.status() { - CommandBufferStatus::Completed => Ok(()), - status => Err(format!( - "a command buffer ended {status:?}: {:?}", - command_buffer.error() - ) - .into()), - } -} - -/// `command_buffer`'s GPU time in microseconds. -fn gpu_us(command_buffer: &CommandBuffer) -> Result { - Ok((command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?) * 1e6) -} - -/// What every run uses. -struct Ours<'a> { - device: &'a Device, - writer: ComputePipelineState, - /// The writer with a GPU reset of each command before its writes ([`resetting`]). - resetter: ComputePipelineState, - /// The writer of commands whose fragment buffer is the material ([`materials`]). - material_writer: ComputePipelineState, - state: RenderPipelineState, - /// `icb_vertex` with `icb_sampled` ([`sampled_functions`]), the heap of textures, and the - /// material: the resource IDs of its first [`TEXTURES`] textures. - sampled: RenderPipelineState, - heap: Heap, - material: Buffer, - target: Texture, - /// The passes' rasterization-rate map, with `--rate-map`. - rate_map: Option, - /// Three vertices a command: the lower half of its cell. - vertices: Buffer, - /// The writer's third argument, a word a thread. - out: Buffer, - commands: u64, -} - -impl Ours<'_> { - /// A new buffer of the shape's storage for the commands. - fn icb(&self, shape: Shape) -> Result { - let mut descriptor = IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::DRAW; - descriptor.inherit_pipeline_state = true; - descriptor.max_vertex_buffer_bind_count = 2; - descriptor.max_fragment_buffer_bind_count = 2; - let icb = - self.device - .new_indirect_command_buffer(&descriptor, self.commands, shape.options())?; - // A barrier the CPU set and cleared: the buffer may hold barriers, which sends its - // execution to the host step. - if shape == Shape::GpuStep { - let last = icb.indirect_render_command_at(self.commands - 1)?; - last.set_barrier()?; - last.clear_barrier()?; - } - Ok(icb) - } - - /// `writer`'s writes of every command of `icb`, committed and waited for: its GPU time. Its - /// third buffer is `third`. - fn write_on_gpu( - &self, - icb: &IndirectCommandBuffer, - (writer, third): (&ComputePipelineState, &Buffer), - ) -> Result { - let arguments = self.device.new_buffer_with_bytes( - &icb.gpu_resource_id().0.to_le_bytes(), - ResourceOptions::shared(), - )?; - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(writer)?; - encoder.set_buffer(Some(&arguments), 0, 0)?; - encoder.set_buffer(Some(&self.vertices), 0, 1)?; - encoder.set_buffer(Some(third), 0, 2)?; - encoder.use_resource(icb.as_resource(), ResourceUsage::WRITE)?; - encoder.dispatch_threads(Size::new(self.commands, 1, 1), Size::new(64, 1, 1))?; - encoder.end_encoding()?; - run(&command_buffer)?; - gpu_us(&command_buffer) - } - - /// The CPU's writes of every command of `icb`: the longest single call and the whole. - fn write_on_cpu(&self, icb: &IndirectCommandBuffer) -> Result<(Duration, Duration)> { - let started = Instant::now(); - let mut longest = Duration::ZERO; - let mut timed = |call: &mut dyn FnMut() -> Result<()>| -> Result<()> { - let at = Instant::now(); - call()?; - longest = longest.max(at.elapsed()); - Ok(()) - }; - for index in 0..self.commands { - let command = icb.indirect_render_command_at(index)?; - timed(&mut || Ok(command.set_vertex_buffer(Some(&self.vertices), 0, 0)?))?; - timed(&mut || Ok(command.set_fragment_buffer(Some(&self.vertices), 0, 1)?))?; - let start = 3 * index; - timed(&mut || Ok(command.draw_primitives(PrimitiveType::Triangle, start, 3, 1, 0)?))?; - } - Ok((longest, started.elapsed())) - } - - /// A render pass that executes every command of `icb`, encoded, not committed. - fn execute(&self, icb: &IndirectCommandBuffer, shape: Shape) -> Result { - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(self.target.clone()); - color.load_action = LoadAction::Clear; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); - pass.rasterization_rate_map = self.rate_map.clone(); - let mut encoder = command_buffer.render_command_encoder(&pass)?; - match shape { - Shape::GpuStep => { - encoder.set_render_pipeline_state(&self.sampled)?; - encoder.use_heap(&self.heap, RenderStages::FRAGMENT)?; - let read = ResourceUsage::READ; - encoder.use_resource(self.material.as_resource(), read, RenderStages::FRAGMENT)?; - } - _ => encoder.set_render_pipeline_state(&self.state)?, - } - encoder.use_resource( - self.vertices.as_resource(), - ResourceUsage::READ, - RenderStages::VERTEX, - )?; - encoder.execute_commands_in_buffer(icb, 0..self.commands)?; - encoder.end_encoding()?; - Ok(command_buffer) - } - - /// Every texel a command's triangle covers fully is [`TEXEL`]. - fn check(&self, shape: Shape) -> Result<()> { - let row = SIDE * 4; - let readback = self - .device - .new_buffer(row * SIDE, ResourceOptions::shared())?; - let queue = self.device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_texture_to_buffer( - &self.target, - 0, - 0, - Origin::new(0, 0, 0), - Size::new(SIDE, SIDE, 1), - &readback, - 0, - row, - row * SIDE, - BlitOption::None, - )?; - blit.end_encoding()?; - run(&command_buffer)?; - let contents = readback.contents().ok_or("the read-back has no contents")?; - // SAFETY: `contents` holds the buffer's bytes, which no command buffer writes now. - let texels = - unsafe { std::slice::from_raw_parts(contents.as_ptr(), readback.length() as usize) }; - let across = SIDE / CELL; - for command in 0..self.commands { - // Texel (1, 6) of the cell, in Metal's rows from the top: inside the lower half's - // triangle (`vertices`) whatever the rasterizer's rules for its edges. - let (cx, cy) = (command % across, command / across); - let x = cx * CELL + 1; - let y = SIDE - 1 - (cy * CELL + 1); - let at = ((y * SIDE + x) * 4) as usize; - if texels[at..at + 4] != TEXEL { - return Err(format!( - "{}: command {command}'s texel ({x}, {y}) is {:?}, not {TEXEL:?}", - shape.name(), - &texels[at..at + 4] - ) - .into()); - } - } - Ok(()) - } -} - -/// The library of the LLVM text `text`, assembled by `llvm-as`. -/// The writer, each thread first resetting its command on the GPU (`air.reset_render_command`), -/// as a kernel that encodes commands anew each frame does. -fn resetting() -> String { - let load = " %7 = bitcast"; - let at = WRITER.find(load).expect("the fixture's buffer cast"); - let declare = at - + WRITER[at..] - .find("; Function Attrs") - .expect("the fixture's declarations"); - format!( - "{} tail call void @air.reset_render_command(ptr addrspace(1) captures(none) %6, i32 %3) \ - #2\n{}declare void @air.reset_render_command(ptr addrspace(1) captures(none), i32) \ - local_unnamed_addr #1\n\n{}", - &WRITER[..at], - &WRITER[at..declare], - &WRITER[declare..] - ) -} - -/// The writer of commands whose fragment buffer 1 is the kernel's third buffer (a material) in -/// place of its vertices, the owned kernel's output store left out. -fn materials() -> String { - let fragment = "@air.set_fragment_buffer_render_command.p1i8(ptr addrspace(1) captures(none) \ - %6, i32 %3, ptr addrspace(1) %7, i32 1)"; - assert!( - WRITER.contains(fragment), - "the fixture's fragment buffer setter" - ); - let own = fragment.replace("%7, i32 1)", "%2, i32 1)"); - (WRITER.lines()) - .filter(|line| !line.contains("store i32 %10")) - .map(|line| format!("{}\n", line.replace(fragment, &own))) - .collect() -} - -/// The writer of `text`'s kernel. -fn writer(device: &Device, text: &str) -> Result { - let writer = library(device, text)?; - let writer = ComputePipelineDescriptor::new(StageSource::Function( - writer - .new_function_with_name("kernel_icb_encode_render_commands")? - .function_descriptor(), - )); - Ok(device.new_compute_pipeline_state(&writer, &PipelineOptions::default())?) -} - -fn library(device: &Device, text: &str) -> Result { - let bitcode = tool("llvm-as", &["-o", "-", "-"], text)?; - let library = metal2vulkan::library::Library::from_air(&bitcode)?; - Ok(device.new_library_with_compile_library(library)) -} - -/// `bytes` in a new `Private` buffer, copied in from a `Shared` one. -fn private_with(device: &Device, bytes: &[u8]) -> Result { - let staging = device.new_buffer_with_bytes(bytes, ResourceOptions::shared())?; - let buffer = device.new_buffer(bytes.len() as u64, ResourceOptions::private())?; - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, bytes.len() as u64)?; - blit.end_encoding()?; - run(&command_buffer)?; - Ok(buffer) -} - -/// A no-copy buffer of `bytes` bytes of fresh host pages with the private option bit -/// (`ResourceOptions::PRIVATE_BIT`): a read twin where the device imports the pages in place. -fn twinned(device: &Device, bytes: usize) -> Result { - #[cfg(unix)] - // SAFETY: a fresh anonymous mapping, read-write, never unmapped. - let pages = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pages = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - bytes, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pages == libc::MAP_FAILED { - return Err(format!("mmap: {}", std::io::Error::last_os_error()).into()); - } - let pages = NonNull::new(pages.cast::()).ok_or("a null mapping")?; - let options = - ResourceOptions::from_raw(ResourceOptions::shared().raw() | ResourceOptions::PRIVATE_BIT)?; - // SAFETY: page-aligned read-write memory of `bytes` bytes, never unmapped, which outlives the - // buffer. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy(HostMemory::new(pages), bytes as u64, options, None) - }?; - Ok(buffer) -} - -/// Three vertices a command, in normalized device coordinates: its cell's lower half, the cells in -/// rows from the bottom left; with `wide_every`, every that many commands' a triangle over the -/// whole screen instead. -fn vertices(commands: u64, wide_every: Option) -> Vec { - let across = SIDE / CELL; - let step = 2.0 * CELL as f32 / SIDE as f32; - (0..commands) - .flat_map(|command| { - if wide_every.is_some_and(|every| command % every == every - 1) { - return [[-1.0, -1.0], [3.0, -1.0], [-1.0, 3.0]]; - } - let x = -1.0 + step * (command % across) as f32; - let y = -1.0 + step * (command / across) as f32; - [[x, y], [x + step, y], [x, y + step]] - }) - .flat_map(|[x, y]| [x, y, 0.0, 1.0]) - .flat_map(f32::to_le_bytes) - .collect() -} - -fn main() -> Result<()> { - let args = Args::parse()?; - let device = Device::system_default()?; - let name = device.name().to_string(); - println!("device: {name}"); - let functions = library(&device, FUNCTIONS)?; - let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function( - functions - .new_function_with_name("icb_vertex")? - .function_descriptor(), - )); - descriptor.fragment = Some(StageSource::Function( - functions - .new_function_with_name("icb_fragment")? - .function_descriptor(), - )); - descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - descriptor.support_indirect_command_buffers = true; - let state = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?; - let sampling = library(&device, &sampled_functions())?; - let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function( - sampling - .new_function_with_name("icb_vertex")? - .function_descriptor(), - )); - descriptor.fragment = Some(StageSource::Function( - sampling - .new_function_with_name("icb_sampled")? - .function_descriptor(), - )); - descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - descriptor.support_indirect_command_buffers = true; - let sampled = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?; - let mut sampled_texture = - TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, TEXTURE_SIDE, TEXTURE_SIDE, false); - sampled_texture.usage = TextureUsage::SHADER_READ; - sampled_texture.resource_options = ResourceOptions::private(); - let fit = device.heap_texture_size_and_align(&sampled_texture)?; - let room = args.heap_textures * fit.size.next_multiple_of(fit.align); - let heap = device.new_heap(&HeapDescriptor::new( - HeapType::Automatic, - room, - ResourceOptions::private(), - ))?; - let textures = (0..args.heap_textures) - .map(|_| Ok(heap.new_texture(&sampled_texture)?)) - .collect::>>()?; - let ids: Vec = (textures.iter().take(TEXTURES as usize)) - .flat_map(|texture| texture.gpu_resource_id().0.to_le_bytes()) - .collect(); - let material = device.new_buffer_with_bytes(&ids, ResourceOptions::shared())?; - // Held to the end: the device has a read twin while it lives. - let _twin = match args.twin { - true => { - let twin = twinned(&device, 1 << 16)?; - println!( - "ICB-TWIN read_twins_made {}", - device.work_counts().read_twins_made - ); - Some(twin) - } - false => None, - }; - let rate_map = match args.rate_map { - true => { - let mut map = RateMapDescriptor::new(MAP_SCREEN); - map.layers = vec![RateMapLayerDescriptor::new( - MAP_QUALITY.to_vec(), - MAP_QUALITY.to_vec(), - )]; - Some(device.new_rasterization_rate_map(&map)?) - } - false => None, - }; - let (width, height) = match &rate_map { - Some(map) => { - let size = map.physical_size_for_layer(0); - (size.width, size.height) - } - None => (SIDE, SIDE), - }; - let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, width, height, false); - target.usage = TextureUsage::RENDER_TARGET; - target.resource_options = ResourceOptions::private(); - let ours = Ours { - device: &device, - writer: writer(&device, WRITER)?, - resetter: writer(&device, &resetting())?, - material_writer: writer(&device, &materials())?, - state, - sampled, - heap, - material, - target: device.new_texture(&target)?, - rate_map, - vertices: private_with(&device, &vertices(args.commands, args.wide_every))?, - out: device.new_buffer(4 * args.commands, ResourceOptions::private())?, - commands: args.commands, - }; - if let Some(seconds) = args.idle { - let icb = ours.icb(Shape::CpuShared)?; - std::thread::sleep(Duration::from_secs(seconds)); - let (longest, encode) = ours.write_on_cpu(&icb)?; - let command_buffer = ours.execute(&icb, Shape::CpuShared)?; - let at = Instant::now(); - command_buffer.commit()?; - let commit = at.elapsed(); - wait(&command_buffer)?; - println!( - "ICB-IDLE {seconds} longest_setter_ms {:.3} encode_ms {:.3} commit_ms {:.3} \ - commit_to_completed_ms {:.3}", - longest.as_secs_f64() * 1e3, - encode.as_secs_f64() * 1e3, - commit.as_secs_f64() * 1e3, - at.elapsed().as_secs_f64() * 1e3, - ); - } - let per = |us: f64| us / args.commands as f64; - for shape in Shape::ALL { - if !args.runs(shape) { - continue; - } - let mut samples: [Vec; 4] = Default::default(); - let mut moved: BTreeMap = BTreeMap::new(); - for round in 0..=args.runs { - let before = counts(&device.work_counts()); - let icb = ours.icb(shape)?; - let (encode, cpu) = match shape { - Shape::CpuShared => (0.0, ours.write_on_cpu(&icb)?.1.as_secs_f64() * 1e6), - Shape::GpuReset => (ours.write_on_gpu(&icb, (&ours.resetter, &ours.out))?, 0.0), - Shape::GpuStep => { - let writing = (&ours.material_writer, &ours.material); - (ours.write_on_gpu(&icb, writing)?, 0.0) - } - _ => (ours.write_on_gpu(&icb, (&ours.writer, &ours.out))?, 0.0), - }; - let command_buffer = ours.execute(&icb, shape)?; - run(&command_buffer)?; - let execute = gpu_us(&command_buffer)?; - if round == 0 { - continue; - } - let after = counts(&device.work_counts()); - let moved_by = |name: &str| { - let at = |of: &BTreeMap| of.get(name).copied().unwrap_or(0); - at(&after).saturating_sub(at(&before)) - }; - // The step's nanoseconds, which `per` gives a command. - let step = moved_by("host_step_nanos") as f64; - for (sample, value) in samples.iter_mut().zip([encode, execute, cpu, step]) { - sample.push(per(value)); - } - for (count, value) in after { - let delta = value.saturating_sub(before.get(&count).copied().unwrap_or(0)); - if delta > 0 { - *moved.entry(count).or_default() += delta; - } - } - } - if ours.rate_map.is_none() { - ours.check(shape)?; - } - let median = |sample: &mut Vec| { - sample.sort_by(f64::total_cmp); - sample[sample.len() / 2] - }; - let [encode, execute, cpu, step] = &mut samples; - println!( - "ICB-READS {} commands {} gpu_us_per_command encode {:.4} execute {:.4} \ - cpu_encode_us_per_command {:.4} host_step_ns_per_command {:.1} {name}", - shape.name(), - args.commands, - median(encode), - median(execute), - median(cpu), - median(step), - ); - let line: Vec = (moved.iter()) - .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / args.runs as f64)) - .collect(); - println!("ICB-READS-COUNTS {} {}", shape.name(), line.join(" ")); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/icb_setters.rs b/crates/metal2vulkan-runtime/examples/icb_setters.rs deleted file mode 100644 index 318a223f1..000000000 --- a/crates/metal2vulkan-runtime/examples/icb_setters.rs +++ /dev/null @@ -1,500 +0,0 @@ -//! Not a consumer's example: the CPU cost of an indirect command buffer's command setters, the -//! shape of a consumer that encodes every field of each command on the CPU, one thread, nothing -//! executing. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example icb_setters [-- [render|compute|all] [--repetitions N] [--calls] [--kept]] -//! ``` -//! -//! - **render**: a buffer of [`COMMANDS`] commands of `DRAW` alone, 2 vertex buffers and 1 -//! fragment buffer, nothing inherited. Each command: `indirect_render_command_at`, -//! `set_render_pipeline_state`, `set_vertex_buffer` twice, `set_fragment_buffer` and -//! `draw_primitives`. -//! - **compute**: a buffer of [`COMMANDS`] commands of `CONCURRENT_DISPATCH`, 3 kernel buffers, -//! nothing inherited. Each command: `indirect_compute_command_at`, -//! `set_compute_pipeline_state`, `set_kernel_buffer` three times and -//! `concurrent_dispatch_threadgroups`. -//! -//! Each repetition encodes every command of the buffer once, over the commands the repetition -//! before encoded (as a consumer encodes a buffer again each frame), and is timed as a whole: the -//! wall time and, on macOS, the calling thread's own instructions and cycles -//! (`thread_selfcounts`, libSystem's, readable unprivileged; other systems print the wall time -//! alone). Printed: the median over the repetitions of each a command, with the lowest and the -//! highest. With `--calls`, each call kind is also timed alone, a pass of that one call over -//! every command of the encoded buffer, a setter's cost; and the record format's own writes of -//! the same fields (`CommandRecord::write_field` into one record's bytes, no lock and no check), -//! the floor a setter's write costs. -//! -//! With `--kept`, the compute row also runs its encoding after executions that kept the -//! buffer's chunks' recordings (`kept_commands.rs`), as a consumer's frame executes the buffer and -//! then encodes it again: before each repetition, untimed, a compute encoder executes every -//! command three times, each in a command buffer committed and waited for. The first records as -//! one that keeps nothing (a range's first execution since a write keeps nothing), the second -//! records every chunk to keep, and the third runs every chunk from those recordings (the printed -//! `indirect_chunks_kept` of each third one). That mode submits work to the GPU; the rest submits -//! nothing. -//! -//! The pipeline states are the owned fixture's (`runtime_examples.ll`'s `colored_vertex`, -//! `colored_fragment` and `scale_and_offset`), assembled by `llvm-as` from `PATH` or -//! `METAL2VULKAN_LLVM_AS`. - -use metal2vulkan::bind::indirect_commands::{ - Action, BufferBinding, BufferStage, CommandRecord, RecordField, COMMAND_BYTES, -}; -use metal2vulkan::metal::{IndirectCommandType, PixelFormat, PrimitiveType, ResourceUsage}; -use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, -}; -use metal2vulkan_runtime::{ - Buffer, CommandBufferStatus, CommandQueue, ComputePipelineState, Device, IndirectCommandBuffer, - IndirectCommandBufferDescriptor, Library, PipelineOptions, RenderPipelineState, - ResourceOptions, ResourceRef, Size, -}; -use std::hint::black_box; -use std::num::NonZeroU64; -use std::path::Path; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The commands of each buffer, and of each repetition. -const COMMANDS: u32 = 16384; - -/// The repetitions a row runs by default, after one untimed. -const REPETITIONS: usize = 30; - -/// The calling thread's own counts so far: instructions and cycles, where the system counts them. -#[derive(Clone, Copy, Default)] -struct Counts { - instructions: u64, - cycles: u64, -} - -#[cfg(target_os = "macos")] -fn counts() -> Option { - unsafe extern "C" { - /// libSystem's per-thread counters; `THSC_CPI` (1) answers the instructions and the - /// cycles, two `u64`s. - fn thread_selfcounts(kind: i32, buffer: *mut u64, bytes: usize) -> i32; - } - let mut words = [0u64; 2]; - // SAFETY: the buffer holds the two words `THSC_CPI` writes. - let answer = unsafe { thread_selfcounts(1, words.as_mut_ptr(), size_of_val(&words)) }; - (answer == 0).then_some(Counts { - instructions: words[0], - cycles: words[1], - }) -} - -#[cfg(not(target_os = "macos"))] -fn counts() -> Option { - None -} - -/// One repetition's measure: the wall time and the thread's counts, over `commands` commands. -#[derive(Clone, Copy)] -struct Sample { - nanos: f64, - counts: Option, -} - -/// Run `body` once untimed, then `repetitions` times, each measured. -fn measure(repetitions: usize, body: impl FnMut()) -> Vec { - measure_after(repetitions, || {}, body) -} - -/// [`measure`], with `prepare` run untimed before each run of `body`. -fn measure_after( - repetitions: usize, - mut prepare: impl FnMut(), - mut body: impl FnMut(), -) -> Vec { - prepare(); - body(); - (0..repetitions) - .map(|_| { - prepare(); - let (before, start) = (counts(), Instant::now()); - body(); - let nanos = start.elapsed().as_nanos() as f64; - let after = counts(); - let counts = before.zip(after).map(|(before, after)| Counts { - instructions: after.instructions - before.instructions, - cycles: after.cycles - before.cycles, - }); - Sample { nanos, counts } - }) - .collect() -} - -/// The median, the lowest and the highest of `values`. -fn spread(mut values: Vec) -> (f64, f64, f64) { - values.sort_by(f64::total_cmp); - let n = values.len(); - let median = match n % 2 { - 1 => values[n / 2], - _ => (values[n / 2 - 1] + values[n / 2]) / 2.0, - }; - (median, values[0], values[n - 1]) -} - -/// Print `row`'s samples, each of `per` units (commands, or calls). -fn report(row: &str, samples: &[Sample], per: f64) { - let (ns, low, high) = spread(samples.iter().map(|s| s.nanos / per).collect()); - let mut line = format!("{row:<34} {ns:>9.1} ns [{low:.1}, {high:.1}]"); - if samples.iter().all(|s| s.counts.is_some()) { - let of = |pick: fn(Counts) -> u64| { - spread( - samples - .iter() - .filter_map(|s| s.counts.map(|c| pick(c) as f64 / per)) - .collect(), - ) - .0 - }; - let (instructions, cycles) = (of(|c| c.instructions), of(|c| c.cycles)); - line += &format!(" {instructions:>9.1} instructions {cycles:>8.1} cycles"); - } - println!("{line}"); -} - -/// The owned fixture's library (the module docs). -fn library(device: &Device) -> Result { - let ll = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); - let bitcode = metal2vulkan_devtools::llvm_assemble(&ll) - .map_err(|error| format!("llvm-as {}: {error:?}", ll.display()))?; - let library = metal2vulkan::library::Library::from_air(&bitcode)?; - Ok(device.new_library_with_compile_library(library)) -} - -/// The render row's state: `colored_vertex` and `colored_fragment`, for indirect command buffers. -fn render_state(device: &Device) -> Result { - let library = library(device)?; - let vertex = library.new_function_with_name("colored_vertex")?; - let fragment = library.new_function_with_name("colored_fragment")?; - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - descriptor.support_indirect_command_buffers = true; - Ok(device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?) -} - -/// The compute row's state: `scale_and_offset`, for indirect command buffers. -fn compute_state(device: &Device) -> Result { - let function = library(device)?.new_function_with_name("scale_and_offset")?; - let mut descriptor = - ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); - descriptor.support_indirect_command_buffers = true; - Ok(device.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())?) -} - -/// The render row (the module docs). -fn render(device: &Device, repetitions: usize, calls: bool) -> Result<()> { - let state = render_state(device)?; - let mut descriptor = IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::DRAW; - descriptor.max_vertex_buffer_bind_count = 2; - descriptor.max_fragment_buffer_bind_count = 1; - let icb = device.new_indirect_command_buffer( - &descriptor, - u64::from(COMMANDS), - ResourceOptions::shared(), - )?; - let (a, b) = ( - device.new_buffer(4096, ResourceOptions::shared())?, - device.new_buffer(4096, ResourceOptions::shared())?, - ); - let encode = |icb: &IndirectCommandBuffer| { - for index in 0..COMMANDS { - let command = icb.indirect_render_command_at(u64::from(index)).unwrap(); - command.set_render_pipeline_state(&state).unwrap(); - command - .set_vertex_buffer(Some(&a), u64::from(index % 16) * 16, 0) - .unwrap(); - command.set_vertex_buffer(Some(&b), 0, 1).unwrap(); - command.set_fragment_buffer(Some(&a), 256, 0).unwrap(); - command - .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) - .unwrap(); - } - }; - let per = f64::from(COMMANDS); - report( - "render command", - &measure(repetitions, || encode(&icb)), - per, - ); - if !calls { - return Ok(()); - } - let commands: Vec<_> = (0..COMMANDS) - .map(|index| icb.indirect_render_command_at(u64::from(index)).unwrap()) - .collect(); - let each = |call: &dyn Fn(&metal2vulkan_runtime::IndirectRenderCommand)| { - measure(repetitions, || commands.iter().for_each(call)) - }; - let rows: [(&str, Vec); 5] = [ - ( - " indirect_render_command_at", - measure(repetitions, || { - for index in 0..COMMANDS { - black_box(icb.indirect_render_command_at(u64::from(index)).unwrap()); - } - }), - ), - ( - " set_render_pipeline_state", - each(&|command| command.set_render_pipeline_state(&state).unwrap()), - ), - ( - " set_vertex_buffer", - each(&|command| command.set_vertex_buffer(Some(&b), 0, 1).unwrap()), - ), - ( - " set_fragment_buffer", - each(&|command| command.set_fragment_buffer(Some(&a), 256, 0).unwrap()), - ), - ( - " draw_primitives", - each(&|command| { - command - .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) - .unwrap() - }), - ), - ]; - for (row, samples) in &rows { - report(row, samples, per); - } - let fields = [ - RecordField::Pipeline(NonZeroU64::new(state.gpu_resource_id().0).unwrap()), - buffer_field(BufferStage::Vertex, 0, &a, 16), - buffer_field(BufferStage::Vertex, 1, &b, 0), - buffer_field(BufferStage::Fragment, 0, &a, 256), - RecordField::Action(Action::DrawPrimitives { - primitive_type: 3, - vertex_start: 0, - vertex_count: 3, - instance_count: 1, - base_instance: 0, - }), - ]; - report( - " floor: the 5 fields' write_field", - &floor(repetitions, &fields), - per, - ); - Ok(()) -} - -/// The compute row (the module docs). -fn compute(device: &Device, repetitions: usize, (calls, kept): (bool, bool)) -> Result<()> { - let state = compute_state(device)?; - let mut descriptor = IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; - descriptor.max_kernel_buffer_bind_count = 3; - let icb = device.new_indirect_command_buffer( - &descriptor, - u64::from(COMMANDS), - ResourceOptions::shared(), - )?; - let buffers = [ - device.new_buffer(4096, ResourceOptions::shared())?, - device.new_buffer(4096, ResourceOptions::shared())?, - device.new_buffer(256, ResourceOptions::shared())?, - ]; - let (threadgroups, threads) = (Size::new(4, 1, 1), Size::new(64, 1, 1)); - let encode = |icb: &IndirectCommandBuffer| { - for index in 0..COMMANDS { - let command = icb.indirect_compute_command_at(u64::from(index)).unwrap(); - command.set_compute_pipeline_state(&state).unwrap(); - command - .set_kernel_buffer(Some(&buffers[0]), u64::from(index % 16) * 16, 0) - .unwrap(); - command.set_kernel_buffer(Some(&buffers[1]), 0, 1).unwrap(); - command.set_kernel_buffer(Some(&buffers[2]), 0, 2).unwrap(); - command - .concurrent_dispatch_threadgroups(threadgroups, threads) - .unwrap(); - } - }; - let per = f64::from(COMMANDS); - report( - "compute command", - &measure(repetitions, || encode(&icb)), - per, - ); - let commands: Vec<_> = (0..COMMANDS) - .map(|index| icb.indirect_compute_command_at(u64::from(index)).unwrap()) - .collect(); - if kept { - let queue = device.new_command_queue()?; - let chunks = std::cell::RefCell::new(Vec::new()); - // Three times: the first keeps nothing, the second records every chunk to keep, and the - // third runs every chunk from those recordings. - let prepare = || { - execute(&queue, &icb, &buffers); - execute(&queue, &icb, &buffers); - let before = device.work_counts().indirect_chunks_kept; - execute(&queue, &icb, &buffers); - let ran = device.work_counts().indirect_chunks_kept - before; - chunks.borrow_mut().push(ran); - }; - let rows = [ - ( - "compute command, chunks kept", - measure_after(repetitions, prepare, || encode(&icb)), - ), - ( - " set_kernel_buffer, chunks kept", - measure_after(repetitions, prepare, || { - for command in &commands { - command.set_kernel_buffer(Some(&buffers[1]), 0, 1).unwrap(); - } - }), - ), - ]; - for (row, samples) in &rows { - report(row, samples, per); - } - let mut chunks = chunks.into_inner(); - chunks.dedup(); - println!(" (chunks each third execution ran from kept recordings: {chunks:?})"); - } - if !calls { - return Ok(()); - } - let each = |call: &dyn Fn(&metal2vulkan_runtime::IndirectComputeCommand)| { - measure(repetitions, || commands.iter().for_each(call)) - }; - let rows: [(&str, Vec); 4] = [ - ( - " indirect_compute_command_at", - measure(repetitions, || { - for index in 0..COMMANDS { - black_box(icb.indirect_compute_command_at(u64::from(index)).unwrap()); - } - }), - ), - ( - " set_compute_pipeline_state", - each(&|command| command.set_compute_pipeline_state(&state).unwrap()), - ), - ( - " set_kernel_buffer", - each(&|command| command.set_kernel_buffer(Some(&buffers[1]), 0, 1).unwrap()), - ), - ( - " concurrent_dispatch_threadgroups", - each(&|command| { - command - .concurrent_dispatch_threadgroups(threadgroups, threads) - .unwrap() - }), - ), - ]; - for (row, samples) in &rows { - report(row, samples, per); - } - let fields = [ - RecordField::Pipeline(NonZeroU64::new(state.gpu_resource_id().0).unwrap()), - buffer_field(BufferStage::Kernel, 0, &buffers[0], 16), - buffer_field(BufferStage::Kernel, 1, &buffers[1], 0), - buffer_field(BufferStage::Kernel, 2, &buffers[2], 0), - RecordField::Action(Action::DispatchThreadgroups { - grid: [4, 1, 1], - local_size: [64, 1, 1], - }), - ]; - report( - " floor: the 5 fields' write_field", - &floor(repetitions, &fields), - per, - ); - Ok(()) -} - -/// Execute every command of `icb`, which dispatches over `buffers`, in a command buffer of -/// `queue`, committed and waited for. -fn execute(queue: &CommandQueue, icb: &IndirectCommandBuffer, buffers: &[Buffer]) { - let command_buffer = queue.command_buffer().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - for buffer in buffers { - let usage = ResourceUsage::READ | ResourceUsage::WRITE; - encoder - .use_resource(ResourceRef::Buffer(buffer), usage) - .unwrap(); - } - encoder - .execute_commands_in_buffer(icb, 0..u64::from(COMMANDS)) - .unwrap(); - encoder.end_encoding().unwrap(); - command_buffer.commit().unwrap(); - command_buffer - .wait_until_completed_for(Duration::from_secs(60)) - .unwrap(); - assert_eq!( - command_buffer.status(), - CommandBufferStatus::Completed, - "{:?}", - command_buffer.error() - ); -} - -/// The field a buffer setter writes: `buffer` at `offset`, at slot `slot` of `stage`. -fn buffer_field(stage: BufferStage, slot: usize, buffer: &Buffer, offset: u64) -> RecordField { - RecordField::Buffer { - stage, - slot, - binding: Some(BufferBinding { - address: buffer.gpu_address().0 + offset, - attribute_stride: None, - }), - } -} - -/// `fields` written into one record's bytes by the record format alone, [`COMMANDS`] times a -/// repetition: what the setters' writes cost without a lock, a check or the bookkeeping. -fn floor(repetitions: usize, fields: &[RecordField]) -> Vec { - let mut bytes = vec![0u8; COMMAND_BYTES]; - CommandRecord::default().encode_into(&mut bytes).unwrap(); - measure(repetitions, || { - for _ in 0..COMMANDS { - for &field in fields { - black_box(CommandRecord::write_field(black_box(&mut bytes), field).unwrap()); - } - } - }) -} - -fn main() -> Result<()> { - let arguments: Vec = std::env::args().skip(1).collect(); - let mode = arguments.first().map_or("all", String::as_str); - let repetitions = arguments - .iter() - .position(|argument| argument == "--repetitions") - .and_then(|at| arguments.get(at + 1)) - .map_or(Ok(REPETITIONS), |count| count.parse())?; - let calls = arguments.iter().any(|argument| argument == "--calls"); - let kept = arguments.iter().any(|argument| argument == "--kept"); - let device = Device::system_default()?; - println!( - "device: {}; {COMMANDS} commands a repetition, median of {repetitions}", - device.name() - ); - if counts().is_none() { - println!("(this system's thread counters are not read: wall time alone)"); - } - match mode { - "render" => render(&device, repetitions, calls), - "compute" => compute(&device, repetitions, (calls, kept)), - "all" => { - render(&device, repetitions, calls)?; - compute(&device, repetitions, (calls, kept)) - } - other => Err(format!("unknown mode {other}: render, compute or all").into()), - } -} diff --git a/crates/metal2vulkan-runtime/examples/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/examples/indirect_command_buffer.rs deleted file mode 100644 index f71b8bc0d..000000000 --- a/crates/metal2vulkan-runtime/examples/indirect_command_buffer.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! An indirect command buffer: two compute commands encoded on the CPU, each its own dispatch over -//! its own half of the arrays with its own scale, read back as typed records, and run by a compute -//! encoder's `executeCommandsInBuffer:withRange:`. -//! -//! ```sh -//! cargo run -p metal2vulkan-runtime --example indirect_command_buffer [-- path/to/library.metallib] -//! ``` -//! -//! The kernel is `scale_and_offset` of the repository's owned fixture -//! (`validation/fixtures/public/examples/runtime_examples.metal`), or of the metallib the argument -//! names. - -mod common; - -use metal2vulkan::metal::{IndirectCommandType, ResourceUsage}; -use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - Device, IndirectCommand, IndirectCommandBufferDescriptor, PipelineOptions, ResourceOptions, - ResourceRef, Size, -}; - -/// The floats each command scales. -const HALF: u64 = 256; - -/// Each command's scale. -const SCALES: [f32; 2] = [2.0, -1.0]; - -fn main() -> common::Result<()> { - let device = Device::system_default()?; - println!("device: {}", device.name()); - let library = common::library(&device)?; - let function = library.new_function_with_name("scale_and_offset")?; - - // A pipeline state an indirect command may name is made with - // `supportIndirectCommandBuffers`, as Metal requires. - let mut descriptor = - ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); - descriptor.support_indirect_command_buffers = true; - let state = device.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())?; - - let input: Vec = (0..2 * HALF) - .flat_map(|i| (i as f32).to_le_bytes()) - .collect(); - let input = device.new_buffer_with_bytes(&input, ResourceOptions::shared())?; - let output = device.new_buffer(2 * HALF * 4, ResourceOptions::shared())?; - let scales = [ - device.new_buffer_with_bytes(&SCALES[0].to_le_bytes(), ResourceOptions::shared())?, - device.new_buffer_with_bytes(&SCALES[1].to_le_bytes(), ResourceOptions::shared())?, - ]; - - // `MTLIndirectCommandBufferDescriptor` and - // `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:`: two commands of - // `dispatchThreads`, each with its own pipeline state and three kernel buffers. - let mut icb_descriptor = IndirectCommandBufferDescriptor::new(); - icb_descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH_THREADS; - icb_descriptor.max_kernel_buffer_bind_count = 3; - let icb = device.new_indirect_command_buffer(&icb_descriptor, 2, ResourceOptions::shared())?; - - // `indirectComputeCommandAtIndex:` and its setters: command h scales half h. - for (h, scale) in scales.iter().enumerate() { - let offset = h as u64 * HALF * 4; - let command = icb.indirect_compute_command_at(h as u64)?; - command.set_compute_pipeline_state(&state)?; - command.set_kernel_buffer(Some(&input), offset, 0)?; - command.set_kernel_buffer(Some(&output), offset, 1)?; - command.set_kernel_buffer(Some(scale), 0, 2)?; - command.concurrent_dispatch_threads(Size::new(HALF, 1, 1), Size::new(64, 1, 1))?; - } - - // The typed read-back of the records (a runtime extension standing for Metal's private - // getters): each command's dispatch, and each buffer as its Metal address plus its offset. - for (h, command) in icb.commands(0..2)?.iter().enumerate() { - if let IndirectCommand::Compute(command) = command { - println!( - "command {h}: {:?}, kernel buffers {:?}", - command.dispatch, command.kernel_buffers - ); - } - } - - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - // The commands reach their buffers through the addresses their records hold, so the encoder - // makes the buffers resident first, as Metal's `useResource:usage:` does; an address in no - // resident resource reads zero and drops its writes. - encoder.use_resource(ResourceRef::Buffer(&input), ResourceUsage::READ)?; - encoder.use_resource(ResourceRef::Buffer(&output), ResourceUsage::WRITE)?; - for scale in &scales { - encoder.use_resource(ResourceRef::Buffer(scale), ResourceUsage::READ)?; - } - encoder.execute_commands_in_buffer(&icb, 0..2)?; - encoder.end_encoding()?; - common::run(&command_buffer)?; - - // Half h: output[h * HALF + i] = input[h * HALF + i] * SCALES[h] + i, its thread position i. - let output: Vec = common::bytes(&output)? - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect(); - for (at, &value) in output.iter().enumerate() { - let (h, i) = (at / HALF as usize, at % HALF as usize); - let expected = at as f32 * SCALES[h] + i as f32; - if value != expected { - return Err(format!("output[{at}] is {value}, not {expected}").into()); - } - } - println!( - "output[0..3] = {:?}, output[{HALF}..{}] = {:?}: as expected", - &output[..3], - HALF + 3, - &output[HALF as usize..HALF as usize + 3] - ); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/inert_uploads.rs b/crates/metal2vulkan-runtime/examples/inert_uploads.rs deleted file mode 100644 index 75e1b7e0b..000000000 --- a/crates/metal2vulkan-runtime/examples/inert_uploads.rs +++ /dev/null @@ -1,467 +0,0 @@ -//! Not a consumer's example: which command buffer copies a `Managed` buffer's CPU writes in, on a -//! device without unified memory, when the first command buffer to bind the buffer only -//! dispatches a kernel that does nothing (an empty kernel with buffer arguments it never reads). -//! A program uses such a command buffer to upload ahead of timed work. The example also measures -//! what the next command buffer, the one that reads the buffer, costs. Three rows, each a shape -//! of a guest workload's: -//! -//! - **`batch`**: 40 `Managed` no-copy buffers of 8 MiB, which the CPU writes and names with -//! `did_modify_range`. Command buffer `A` dispatches the empty kernel once for each buffer, and -//! command buffer `B` dispatches a kernel that reads 4 KiB of each. -//! - **`frames`**: 33 such buffers of 614,400 bytes, written and named the same way. `A` binds -//! each, then 11 frames each read three of them, then fill 1 MiB of a `Private` buffer and -//! synchronize two 335,872-byte `Managed` buffers that nobody wrote. -//! - **`inert`**: command buffers of 42 dispatches of the empty kernel over `Private` buffers alone. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example inert_uploads -//! ``` -//! -//! The kernels are LLVM text written here, assembled by `llvm-as` from `PATH`. The CPU checks -//! every word `B` and the frames read. Each line is the median over the timed command buffers of -//! the row's kind (`A`, `B`, `frame`, `inert`), and each count is a mean per command buffer: -//! -//! ```text -//! ROW gpu_ms wall_ms encode_us copied_in_mb fillq fillq_waits vkcbs subs skipped -//! -//! ``` -//! -//! `skipped` reads `-` where the device's counts have no such field. - -use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputePipelineState, CpuCacheMode, - Device, HazardTrackingMode, HostMemory, PipelineOptions, ResourceOptions, ResourceRef, Size, - StorageMode, WorkCounts, -}; -use std::process::Command; -use std::ptr::NonNull; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// Two kernels of buffers `a` (index 0) and `b` (index 1) and the thread's grid position: -/// `empty` does nothing; `twice` stores `2 * a[gid]` at `b[gid]`. -const KERNELS: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ -target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ -define void @empty(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\ -entry:\n\ - ret void\n\ -}\n\n\ -define void @twice(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef %b, i32 noundef %gid) {\n\ -entry:\n\ - %gw = zext i32 %gid to i64\n\ - %q = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ - %x = load i32, ptr addrspace(1) %q, align 4\n\ - %v = shl i32 %x, 1\n\ - %p = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\ - store i32 %v, ptr addrspace(1) %p, align 4\n\ - ret void\n\ -}\n\n\ -!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20, !21}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ -!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ -!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ -!3 = !{}\n!4 = !{!5, !6, !7}\n\ -!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ -!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"b\"}\n\ -!7 = !{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ -!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ -!20 = !{ptr @empty, !3, !4}\n!21 = !{ptr @twice, !3, !4}\n"; - -/// The words `twice` reads of each buffer it reads: 4 KiB. -const WORDS: u64 = 1024; -/// The bytes of the small buffers the frames synchronize. -const SMALL: u64 = 82 * 4096; -/// The bytes of the frames' fill. -const FILL: u64 = 1 << 20; - -/// Anonymous private pages of the example's own, unmapped when dropped, after the buffer over them. -struct Pages(NonNull, u64); - -impl Pages { - fn new(bytes: u64) -> Result { - #[cfg(unix)] - // SAFETY: a new anonymous mapping, which nothing else uses. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - bytes as usize, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pointer == libc::MAP_FAILED { - return Err("mmap failed".into()); - } - let pointer = NonNull::new(pointer.cast::()).ok_or("mmap gave null")?; - Ok(Pages(pointer, bytes)) - } - - /// Write `value` over every byte, as the CPU. - fn write(&self, value: u8) { - // SAFETY: the mapping's bytes, which no command buffer uses while the CPU writes them. - unsafe { std::ptr::write_bytes(self.0.as_ptr(), value, self.1 as usize) }; - } -} - -impl Drop for Pages { - fn drop(&mut self) { - // SAFETY: the mapping `new` made; every buffer over it went before it. - #[cfg(unix)] - unsafe { - libc::munmap(self.0.as_ptr().cast(), self.1 as usize) - }; - #[cfg(windows)] - // SAFETY: as above; a release frees the allocation whole, from its base. - unsafe { - windows_sys::Win32::System::Memory::VirtualFree( - self.0.as_ptr().cast(), - 0, - windows_sys::Win32::System::Memory::MEM_RELEASE, - ) - }; - } -} - -/// `count` `Managed` no-copy buffers of `bytes` each, each over pages of its own. -struct Managed { - buffers: Vec, - // After the buffers: dropped once they went. - pages: Vec, -} - -impl Managed { - fn new(device: &Device, count: usize, bytes: u64) -> Result { - let options = ResourceOptions::new( - StorageMode::Managed, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Default, - ); - let mut buffers = Vec::with_capacity(count); - let mut pages = Vec::with_capacity(count); - for _ in 0..count { - let host = Pages::new(bytes)?; - // SAFETY: the pages outlive the buffer (dropped after it, `Managed`), and only its - // commands and this example's CPU accesses use them. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy(HostMemory::new(host.0), bytes, options, None) - }?; - buffers.push(buffer); - pages.push(host); - } - Ok(Managed { buffers, pages }) - } - - /// The CPU writes `value` over every buffer and names it whole with `did_modify_range`. - fn write(&self, value: u8) -> Result<()> { - for (buffer, pages) in self.buffers.iter().zip(&self.pages) { - pages.write(value); - buffer.did_modify_range(0..pages.1)?; - } - Ok(()) - } -} - -/// The state of kernel `name` of [`KERNELS`], assembled by `llvm-as`. -fn state(device: &Device, name: &str) -> Result { - let mut child = Command::new("llvm-as") - .args(["-o", "-", "-"]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn() - .map_err(|error| format!("cannot run llvm-as (put LLVM's bin on PATH): {error}"))?; - { - use std::io::Write; - let mut stdin = child.stdin.take().ok_or("llvm-as has no stdin")?; - stdin.write_all(KERNELS.as_bytes())?; - } - let output = child.wait_with_output()?; - if !output.status.success() { - return Err(format!("llvm-as: {}", String::from_utf8_lossy(&output.stderr)).into()); - } - let library = metal2vulkan::library::Library::from_air(&output.stdout)?; - let function = device - .new_library_with_compile_library(library) - .new_function_with_name(name)?; - Ok(device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?) -} - -/// Commit `command_buffer` and wait for it: its GPU time and its wall time from the commit to its -/// completion, in milliseconds. -fn run(command_buffer: &CommandBuffer) -> Result<(f64, f64)> { - let began = Instant::now(); - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - let wall = began.elapsed().as_secs_f64() * 1e3; - if command_buffer.status() != CommandBufferStatus::Completed { - let error = command_buffer.error(); - return Err(format!( - "a command buffer ended {:?}: {error:?}", - command_buffer.status() - ) - .into()); - } - let gpu = (command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?) * 1e3; - Ok((gpu, wall)) -} - -/// A field of `counts` by name, read from their `Debug` form: `None` where they have none. -fn field(counts: &WorkCounts, name: &str) -> Option { - let text = format!("{counts:?}"); - let at = text.find(&format!(" {name}: "))? + name.len() + 3; - let digits: String = text[at..] - .chars() - .take_while(char::is_ascii_digit) - .collect(); - digits.parse().ok() -} - -/// One kind of command buffer's samples and counts, over the command buffers it ran. -#[derive(Default)] -struct Kind { - gpu: Vec, - wall: Vec, - encode: Vec, - copied_in: u64, - fillq: u64, - fillq_waits: u64, - vkcbs: u64, - subs: u64, - skipped: Option, -} - -impl Kind { - /// Add one command buffer: its times, its encoding's time per dispatch in microseconds, and - /// the device's counts before its encoding and after its completion. - fn add( - &mut self, - (gpu, wall): (f64, f64), - encode: f64, - before: &WorkCounts, - after: &WorkCounts, - ) { - self.gpu.push(gpu); - self.wall.push(wall); - self.encode.push(encode); - self.copied_in += after.managed_bytes_copied_in - before.managed_bytes_copied_in; - self.fillq += after.fill_queue_submissions - before.fill_queue_submissions; - self.fillq_waits += after.fill_queue_waits - before.fill_queue_waits; - self.vkcbs += after.command_buffers_begun - before.command_buffers_begun; - self.subs += after.queue_submissions - before.queue_submissions; - let skipped = |counts| field(counts, "dispatches_skipped_inert"); - if let (Some(after), Some(before)) = (skipped(after), skipped(before)) { - *self.skipped.get_or_insert(0) += after - before; - } - } - - fn print(&mut self, row: &str, kind: &str, device: &str) { - let n = self.gpu.len() as f64; - let median = |values: &mut Vec| { - values.sort_by(f64::total_cmp); - values[values.len() / 2] - }; - let skipped = match self.skipped { - Some(skipped) => format!("{:.2}", skipped as f64 / n), - None => "-".to_string(), - }; - println!( - "ROW {row} {kind} gpu_ms {:.3} wall_ms {:.3} encode_us {:.2} copied_in_mb {:.2} \ - fillq {:.2} fillq_waits {:.2} vkcbs {:.2} subs {:.2} skipped {skipped} {device}", - median(&mut self.gpu), - median(&mut self.wall), - median(&mut self.encode), - self.copied_in as f64 / n / 1e6, - self.fillq as f64 / n, - self.fillq_waits as f64 / n, - self.vkcbs as f64 / n, - self.subs as f64 / n, - ); - } -} - -/// The kernels and the queue every row uses. -struct Rig { - device: Device, - queue: CommandQueue, - empty: ComputePipelineState, - twice: ComputePipelineState, -} - -impl Rig { - /// A command buffer that dispatches `empty` once for each of `buffers` (bound at index 0 and - /// 1), one thread each: its encoding's time per dispatch, in microseconds. - fn binds(&self, buffers: &[Buffer]) -> Result<(CommandBuffer, f64)> { - let command_buffer = self.queue.command_buffer()?; - let began = Instant::now(); - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(&self.empty)?; - for buffer in buffers { - encoder.set_buffer(Some(buffer), 0, 0)?; - encoder.set_buffer(Some(buffer), 0, 1)?; - encoder.dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1))?; - } - encoder.end_encoding()?; - let encode = began.elapsed().as_secs_f64() * 1e6 / buffers.len() as f64; - Ok((command_buffer, encode)) - } - - /// Encode, into `command_buffer`, `twice` over the first [`WORDS`] words of each of - /// `buffers`, into `out` at 4 KiB apart. - fn reads( - &self, - command_buffer: &CommandBuffer, - buffers: &[Buffer], - out: &Buffer, - ) -> Result<()> { - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(&self.twice)?; - for (n, buffer) in buffers.iter().enumerate() { - encoder.set_buffer(Some(buffer), 0, 0)?; - encoder.set_buffer(Some(out), n as u64 * WORDS * 4, 1)?; - encoder.dispatch_threads(Size::new(WORDS, 1, 1), Size::new(64, 1, 1))?; - } - encoder.end_encoding()?; - Ok(()) - } -} - -/// Check that `out`'s first `count` blocks of [`WORDS`] words hold twice the word of bytes -/// `value`. -fn check(out: &Buffer, count: usize, value: u8, what: &str) -> Result<()> { - let contents = out.contents().ok_or("the output has no contents")?; - let want = (u32::from_ne_bytes([value; 4])).wrapping_shl(1); - for at in 0..count * WORDS as usize { - // SAFETY: `out` is `Shared`, at least `count` blocks long, and no command buffer - // writes it while the CPU reads it. - let word = unsafe { contents.as_ptr().cast::().add(at).read_volatile() }; - if word != want { - return Err(format!("{what}: word {at} is {word:#x}, not {want:#x}").into()); - } - } - Ok(()) -} - -fn main() -> Result<()> { - let device = Device::system_default()?; - let unified = device.properties().has_unified_memory; - let name = device.name().to_string(); - println!("device: {name} (unified memory: {unified})"); - let rig = Rig { - queue: device.new_command_queue()?, - empty: state(&device, "empty")?, - twice: state(&device, "twice")?, - device, - }; - let device = &rig.device; - let private = ResourceOptions::new( - StorageMode::Private, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Default, - ); - let out = device.new_buffer(40 * WORDS * 4, ResourceOptions::shared())?; - let mut round = 0x20u8; - let mut next = || { - round = round.wrapping_add(1).max(0x21); - round - }; - - // `inert`: the empty kernel's own cost, over buffers with nothing to copy in. - let plain: Vec = (0..42) - .map(|_| device.new_buffer(64 * 1024, private)) - .collect::>()?; - let mut inert = Kind::default(); - for timed in [false; 3].into_iter().chain([true; 20]) { - let before = device.work_counts(); - let (command_buffer, encode) = rig.binds(&plain)?; - let times = run(&command_buffer)?; - if timed { - inert.add(times, encode, &before, &device.work_counts()); - } - } - inert.print("inert", "inert", &name); - - // `frames`: 33 buffers uploaded by `A`, read three a frame. - let uploads = Managed::new(device, 33, 150 * 4096)?; - let small = Managed::new(device, 2, SMALL)?; - let fill = device.new_buffer(FILL, private)?; - let (mut a, mut frame) = (Kind::default(), Kind::default()); - for timed in [false, true, true, true, true] { - let value = next(); - uploads.write(value)?; - let before = device.work_counts(); - let (command_buffer, encode) = rig.binds(&uploads.buffers)?; - let times = run(&command_buffer)?; - if timed { - a.add(times, encode, &before, &device.work_counts()); - } - for three in uploads.buffers.chunks(3) { - let before = device.work_counts(); - let command_buffer = rig.queue.command_buffer()?; - let began = Instant::now(); - rig.reads(&command_buffer, three, &out)?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.fill_buffer(&fill, 0..FILL, value)?; - for buffer in &small.buffers { - blit.synchronize_resource(ResourceRef::Buffer(buffer))?; - } - blit.end_encoding()?; - let encode = began.elapsed().as_secs_f64() * 1e6 / three.len() as f64; - let times = run(&command_buffer)?; - check(&out, three.len(), value, "a frame")?; - if timed { - frame.add(times, encode, &before, &device.work_counts()); - } - } - } - a.print("frames", "A", &name); - frame.print("frames", "frame", &name); - - // `batch`: 40 buffers of 8 MiB uploaded by `A`, read by `B`. - let uploads = Managed::new(device, 40, 8 << 20)?; - let (mut a, mut b) = (Kind::default(), Kind::default()); - for timed in [false, false, true, true, true, true, true, true] { - let value = next(); - uploads.write(value)?; - let before = device.work_counts(); - let (command_buffer, encode) = rig.binds(&uploads.buffers)?; - let times = run(&command_buffer)?; - if timed { - a.add(times, encode, &before, &device.work_counts()); - } - let before = device.work_counts(); - let command_buffer = rig.queue.command_buffer()?; - let began = Instant::now(); - rig.reads(&command_buffer, &uploads.buffers, &out)?; - let encode = began.elapsed().as_secs_f64() * 1e6 / uploads.buffers.len() as f64; - let times = run(&command_buffer)?; - check(&out, uploads.buffers.len(), value, "B")?; - if timed { - b.add(times, encode, &before, &device.work_counts()); - } - } - a.print("batch", "A", &name); - b.print("batch", "B", &name); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/managed_bandwidth.rs b/crates/metal2vulkan-runtime/examples/managed_bandwidth.rs deleted file mode 100644 index 2d3107b61..000000000 --- a/crates/metal2vulkan-runtime/examples/managed_bandwidth.rs +++ /dev/null @@ -1,300 +0,0 @@ -//! Not a consumer's example: the GPU's bandwidth through buffers of each storage mode and placement, -//! a kernel reading one 256 MiB buffer and writing another of the same kind, in GB/s read plus -//! written. A `Managed` buffer over the caller's pages (`new_buffer_with_bytes_no_copy`) is the -//! subject: on a device without unified memory Metal keeps it as two copies, the caller's pages and -//! the GPU's own, so the kernel runs at the device memory's speed; a `Shared` one over the caller's -//! pages is the control, read across the bus where the device has no unified memory, as on a Mac -//! with a discrete GPU. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example managed_bandwidth -//! ``` -//! -//! Each row checks the kernel's answer (`output[i] = input[i] + i` for `input[i] = i`), reading a -//! `Managed` output after a blit's `synchronize_resource`; the `Managed` no-copy rows also write the -//! input again on the CPU, tell the buffer (`did_modify_range`) and check the next command buffer -//! reads it. It prints one line a row: -//! -//! ```text -//! BANDWIDTH -//! ``` -//! -//! The kernel is `scale_and_offset` of the owned fixture (`common::library`), with a scale of 1: -//! 4 bytes read and 4 written a thread. - -mod common; - -use metal2vulkan_runtime::{ - Buffer, CommandQueue, ComputePipelineState, CpuCacheMode, Device, HazardTrackingMode, - HostMemory, PipelineOptions, ResourceOptions, ResourceRef, Size, StorageMode, -}; -use std::ptr::NonNull; - -/// The bytes of each buffer. -const BYTES: u64 = 256 << 20; -/// The floats each buffer holds. -const COUNT: u64 = BYTES / 4; -/// The command buffers run before the timed ones. -const WARM: usize = 2; -/// The command buffers timed. -const TIMED: usize = 10; - -/// How a row makes its two buffers. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Made { - /// `newBufferWithBytesNoCopy:` over pages of the example's own. - NoCopy(StorageMode), - /// `newBufferWithLength:`. - Own(StorageMode), -} - -impl Made { - fn name(self) -> String { - match self { - Made::NoCopy(storage) => format!("{storage:?}-no-copy"), - Made::Own(storage) => format!("{storage:?}"), - } - } - - fn storage(self) -> StorageMode { - match self { - Made::NoCopy(storage) | Made::Own(storage) => storage, - } - } -} - -/// Anonymous private pages of the example's own, unmapped when dropped, after the buffer over them. -struct Pages(NonNull); - -impl Pages { - fn new() -> common::Result { - #[cfg(unix)] - // SAFETY: a new anonymous mapping, which nothing else uses. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - BYTES as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - BYTES as usize, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pointer == libc::MAP_FAILED { - return Err("mmap failed".into()); - } - Ok(Pages(NonNull::new(pointer.cast()).ok_or("mmap gave null")?)) - } -} - -impl Drop for Pages { - fn drop(&mut self) { - // SAFETY: the mapping `new` made; every buffer over it went before it. - #[cfg(unix)] - unsafe { - libc::munmap(self.0.as_ptr().cast(), BYTES as usize) - }; - #[cfg(windows)] - // SAFETY: as above; a release frees the allocation whole, from its base. - unsafe { - windows_sys::Win32::System::Memory::VirtualFree( - self.0.as_ptr().cast(), - 0, - windows_sys::Win32::System::Memory::MEM_RELEASE, - ) - }; - } -} - -/// The floats at `pointer`, `COUNT` of them. -/// -/// # Safety -/// -/// `pointer` holds `BYTES` bytes that nothing else reads or writes meanwhile. -unsafe fn floats<'a>(pointer: NonNull) -> &'a mut [f32] { - // SAFETY: the caller's contract; mmap and Metal's buffers are page-aligned. - unsafe { std::slice::from_raw_parts_mut(pointer.as_ptr().cast(), COUNT as usize) } -} - -/// A row's two buffers, the pages under no-copy ones, and how they were made. -struct Row { - made: Made, - input: Buffer, - output: Buffer, - // After the buffers: dropped once they went. - _pages: Vec, -} - -impl Row { - fn new(device: &Device, made: Made) -> common::Result { - let options = ResourceOptions::new( - made.storage(), - CpuCacheMode::DefaultCache, - HazardTrackingMode::Default, - ); - let mut pages = Vec::new(); - let mut make = |first: bool| -> common::Result { - match made { - Made::NoCopy(_) => { - let host = Pages::new()?; - if first { - // The input's bytes, written before the buffer is made: its first GPU use - // reads them. - // SAFETY: the pages are new and the example's alone. - let values = unsafe { floats(host.0) }; - for (i, value) in values.iter_mut().enumerate() { - *value = i as f32; - } - } - // SAFETY: the pages outlive the buffer (dropped after it, `Row`), and only its - // commands and this example's CPU reads and writes use them. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(host.0), - BYTES, - options, - None, - ) - }?; - pages.push(host); - Ok(buffer) - } - Made::Own(storage) => { - let buffer = device.new_buffer(BYTES, options)?; - if first && storage != StorageMode::Private { - let contents = buffer.contents().ok_or("no contents")?; - // SAFETY: the buffer's bytes, which no command uses yet. - let values = unsafe { floats(contents) }; - for (i, value) in values.iter_mut().enumerate() { - *value = i as f32; - } - buffer.did_modify_range(0..BYTES)?; - } - Ok(buffer) - } - } - }; - let input = make(true)?; - let output = make(false)?; - Ok(Row { - made, - input, - output, - _pages: pages, - }) - } -} - -/// One command buffer of the kernel over `row`'s buffers, synchronizing a `Managed` output when -/// `synchronize`: its GPU time in seconds. -fn run( - queue: &CommandQueue, - state: &ComputePipelineState, - row: &Row, - synchronize: bool, -) -> common::Result { - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(state)?; - encoder.set_buffer(Some(&row.input), 0, 0)?; - encoder.set_buffer(Some(&row.output), 0, 1)?; - encoder.set_bytes(&1.0f32.to_le_bytes(), 2)?; - encoder.dispatch_threads(Size::new(COUNT, 1, 1), Size::new(256, 1, 1))?; - encoder.end_encoding()?; - if synchronize && row.made.storage() == StorageMode::Managed { - let mut blit = command_buffer.blit_command_encoder()?; - blit.synchronize_resource(ResourceRef::Buffer(&row.output))?; - blit.end_encoding()?; - } - common::run(&command_buffer)?; - Ok(command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?) -} - -/// Check `row`'s output holds `(i + shift) + i` at a sample of its floats, for an input of -/// `i + shift`; nothing for a `Private` output, which the CPU cannot read. -fn check(row: &Row, shift: f32) -> common::Result<()> { - if row.output.contents().is_none() { - return Ok(()); - } - let bytes = common::bytes(&row.output)?; - let values = bytes.as_chunks::<4>().0; - for i in (0..COUNT as usize) - .step_by(4099) - .chain([COUNT as usize - 1]) - { - // The input's float, then the kernel's sum (a product by 1 is exact, so a fused - // multiply-add rounds as the sum does). - let want = (i as f32 + shift) + i as f32; - let value = f32::from_le_bytes(values[i]); - if value != want { - return Err(format!("{}: output[{i}] is {value}, not {want}", row.made.name()).into()); - } - } - Ok(()) -} - -fn main() -> common::Result<()> { - let device = Device::system_default()?; - let unified = device.properties().has_unified_memory; - println!("device: {} (unified memory: {unified})", device.name()); - let library = common::library(&device)?; - let function = library.new_function_with_name("scale_and_offset")?; - let state = - device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - let queue = device.new_command_queue()?; - let rows = [ - Made::NoCopy(StorageMode::Shared), - Made::NoCopy(StorageMode::Managed), - Made::Own(StorageMode::Shared), - Made::Own(StorageMode::Managed), - Made::Own(StorageMode::Private), - ]; - for made in rows { - let row = Row::new(&device, made)?; - // The first command buffer reads the input's first contents. - run(&queue, &state, &row, true)?; - check(&row, 0.0)?; - if made == Made::NoCopy(StorageMode::Managed) { - // A CPU write the buffer is told of reaches the next command buffer. - let contents = row.input.contents().ok_or("no contents")?; - // SAFETY: the input's bytes, which no command buffer uses now. - let values = unsafe { floats(contents) }; - for value in values.iter_mut() { - *value += 1.0; - } - row.input.did_modify_range(0..BYTES)?; - run(&queue, &state, &row, true)?; - check(&row, 1.0)?; - } - for _ in 0..WARM { - run(&queue, &state, &row, false)?; - } - let mut rates = Vec::with_capacity(TIMED); - for _ in 0..TIMED { - let seconds = run(&queue, &state, &row, false)?; - rates.push(2.0 * BYTES as f64 / seconds / 1e9); - } - rates.sort_by(f64::total_cmp); - println!( - "BANDWIDTH {} {:.1} {:.1} {:.1} {}", - made.name(), - rates[TIMED / 2], - rates[0], - rates[TIMED - 1], - device.name() - ); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/managed_sync_out.rs b/crates/metal2vulkan-runtime/examples/managed_sync_out.rs deleted file mode 100644 index b763b078b..000000000 --- a/crates/metal2vulkan-runtime/examples/managed_sync_out.rs +++ /dev/null @@ -1,367 +0,0 @@ -//! Not a consumer's example: what `synchronize_resource` of `Managed` buffers over the caller's -//! pages costs a command buffer on a device without unified memory, where each such buffer is two -//! copies (the caller's pages and the GPU's own) and a synchronize copies the GPU's copy out to the -//! pages. Two shapes a guest workload showed: -//! -//! - **Synchronizes of 40 buffers a command buffer**, 4,399,104 bytes each (about 176 MB a command -//! buffer, 800 synchronizes over 20 command buffers), after a blit encoder that fills `written` -//! of them whole; the rest the CPU wrote and named with `did_modify_range` before the command -//! buffer (rows `all`, `mixed`), or nobody wrote (row `none`). -//! - **Synchronizes of two 335,872-byte buffers nobody wrote**, after a 1 MiB fill of a `Private` -//! buffer (row `small`), against the fill alone (row `fill`). -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example managed_sync_out -//! ``` -//! -//! After each command buffer the CPU checks a sample of every buffer's pages. It prints one line -//! a row, each value a command buffer's (medians of the times, means of the counts over the timed -//! ones): -//! -//! ```text -//! ROW gpu_ms wall_ms copied_mb -//! subs infos vkcbs -//! (encoders, continuations, batch work, batch barriers, internal) fillq commit_us topped_up -//! ``` -//! -//! `topped_up` reads `-` where the device's counts have no such field. - -use metal2vulkan_runtime::{ - Buffer, CommandBufferStatus, CommandQueue, CpuCacheMode, Device, HazardTrackingMode, - HostMemory, ResourceOptions, ResourceRef, StorageMode, WorkCounts, -}; -use std::ptr::NonNull; -use std::time::{Duration, Instant}; - -/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. -type Result = std::result::Result>; - -/// The longest the example waits for a command buffer. -const WAIT: Duration = Duration::from_secs(60); - -/// The bytes of each of the 40 buffers: whole pages of any host. -const LARGE: u64 = 1074 * 4096; -/// The bytes of each of the two small buffers. -const SMALL: u64 = 82 * 4096; -/// The bytes of the small rows' fill. -const FILL: u64 = 1 << 20; -/// The command buffers run before the timed ones. -const WARM: usize = 3; -/// The first bytes of every buffer's pages. -const FIRST: u8 = 0x11; - -/// Anonymous private pages of the example's own, unmapped when dropped, after the buffer over them. -struct Pages(NonNull, u64); - -impl Pages { - fn new(bytes: u64) -> Result { - #[cfg(unix)] - // SAFETY: a new anonymous mapping, which nothing else uses. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - bytes as usize, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pointer == libc::MAP_FAILED { - return Err("mmap failed".into()); - } - let pointer = NonNull::new(pointer.cast::()).ok_or("mmap gave null")?; - let pages = Pages(pointer, bytes); - pages.write(FIRST); - Ok(pages) - } - - /// Write `value` over every byte, as the CPU. - fn write(&self, value: u8) { - // SAFETY: the mapping's bytes, which no command buffer uses while the CPU writes them. - unsafe { std::ptr::write_bytes(self.0.as_ptr(), value, self.1 as usize) }; - } - - /// The byte at `at`, as the CPU reads it. - fn byte(&self, at: u64) -> u8 { - // SAFETY: inside the mapping, which no command buffer writes while the CPU reads it. - unsafe { self.0.as_ptr().add(at as usize).read_volatile() } - } - - /// Check a sample of its bytes hold `want`. - fn check(&self, want: u8, what: &str) -> Result<()> { - for at in (0..self.1).step_by(65_537).chain([self.1 - 1]) { - let byte = self.byte(at); - if byte != want { - return Err(format!("{what}: byte {at} is {byte:#x}, not {want:#x}").into()); - } - } - Ok(()) - } -} - -impl Drop for Pages { - fn drop(&mut self) { - // SAFETY: the mapping `new` made; every buffer over it went before it. - #[cfg(unix)] - unsafe { - libc::munmap(self.0.as_ptr().cast(), self.1 as usize) - }; - #[cfg(windows)] - // SAFETY: as above; a release frees the allocation whole, from its base. - unsafe { - windows_sys::Win32::System::Memory::VirtualFree( - self.0.as_ptr().cast(), - 0, - windows_sys::Win32::System::Memory::MEM_RELEASE, - ) - }; - } -} - -/// `count` buffers of `bytes` each, each over pages of its own. -struct Buffers { - buffers: Vec, - // After the buffers: dropped once they went. - pages: Vec, -} - -impl Buffers { - fn new(device: &Device, count: usize, bytes: u64) -> Result { - let options = ResourceOptions::new( - StorageMode::Managed, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Default, - ); - let mut buffers = Vec::with_capacity(count); - let mut pages = Vec::with_capacity(count); - for _ in 0..count { - let host = Pages::new(bytes)?; - // SAFETY: the pages outlive the buffer (dropped after it, `Buffers`), and only its - // commands and this example's CPU accesses use them. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy(HostMemory::new(host.0), bytes, options, None) - }?; - buffers.push(buffer); - pages.push(host); - } - Ok(Buffers { buffers, pages }) - } -} - -/// One row's command buffers: what each does. -#[derive(Clone, Copy)] -enum Shape { - /// 40 large buffers: the GPU fills `written` of them, the CPU writes the rest where - /// `modified`, and a blit synchronizes all 40. - Large { written: usize, modified: bool }, - /// The 1 MiB fill, then a blit synchronizing the two small buffers where `synchronized`. - Small { synchronized: bool }, -} - -/// One command buffer of `shape`, of round `round`: its GPU time and its wall time from the commit -/// to its completion, in seconds. -fn run( - queue: &CommandQueue, - shape: Shape, - buffers: &Buffers, - target: &Buffer, - round: u8, -) -> Result<(f64, f64)> { - let command_buffer = queue.command_buffer()?; - match shape { - Shape::Large { written, modified } => { - if modified { - for (buffer, pages) in buffers.buffers.iter().zip(&buffers.pages).skip(written) { - pages.write(round); - buffer.did_modify_range(0..LARGE)?; - } - } - if written > 0 { - let mut fill = command_buffer.blit_command_encoder()?; - for buffer in &buffers.buffers[..written] { - fill.fill_buffer(buffer, 0..LARGE, round)?; - } - fill.end_encoding()?; - } - let mut sync = command_buffer.blit_command_encoder()?; - for buffer in &buffers.buffers { - sync.synchronize_resource(ResourceRef::Buffer(buffer))?; - } - sync.end_encoding()?; - } - Shape::Small { synchronized } => { - let mut fill = command_buffer.blit_command_encoder()?; - fill.fill_buffer(target, 0..FILL, round)?; - fill.end_encoding()?; - if synchronized { - let mut sync = command_buffer.blit_command_encoder()?; - for buffer in &buffers.buffers { - sync.synchronize_resource(ResourceRef::Buffer(buffer))?; - } - sync.end_encoding()?; - } - } - } - let began = Instant::now(); - command_buffer.commit()?; - command_buffer - .wait_until_completed_for(WAIT) - .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; - let wall = began.elapsed().as_secs_f64(); - if command_buffer.status() != CommandBufferStatus::Completed { - let error = command_buffer.error(); - return Err(format!( - "a command buffer ended {:?}: {error:?}", - command_buffer.status() - ) - .into()); - } - let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; - match shape { - Shape::Large { written, modified } => { - for (index, pages) in buffers.pages.iter().enumerate() { - let want = match index < written || modified { - true => round, - false => FIRST, - }; - pages.check(want, &format!("round {round}, buffer {index}"))?; - } - } - Shape::Small { .. } => { - for (index, pages) in buffers.pages.iter().enumerate() { - pages.check(FIRST, &format!("round {round}, small buffer {index}"))?; - } - } - } - Ok((gpu, wall)) -} - -/// A field of `counts` by name, read from their `Debug` form: `None` where they have none. -fn field(counts: &WorkCounts, name: &str) -> Option { - let text = format!("{counts:?}"); - let at = text.find(&format!(" {name}: "))? + name.len() + 3; - let digits: String = text[at..] - .chars() - .take_while(char::is_ascii_digit) - .collect(); - digits.parse().ok() -} - -/// The median of `values`, sorted here. -fn median(values: &mut [f64]) -> f64 { - values.sort_by(f64::total_cmp); - values[values.len() / 2] -} - -fn main() -> Result<()> { - let device = Device::system_default()?; - let unified = device.properties().has_unified_memory; - println!("device: {} (unified memory: {unified})", device.name()); - let queue = device.new_command_queue()?; - let private = ResourceOptions::new( - StorageMode::Private, - CpuCacheMode::DefaultCache, - HazardTrackingMode::Default, - ); - let target = device.new_buffer(FILL, private)?; - let rows = [ - ( - "all", - Shape::Large { - written: 40, - modified: false, - }, - 20, - ), - ( - "mixed", - Shape::Large { - written: 30, - modified: true, - }, - 20, - ), - ( - "none", - Shape::Large { - written: 0, - modified: false, - }, - 20, - ), - ("small", Shape::Small { synchronized: true }, 200), - ( - "fill", - Shape::Small { - synchronized: false, - }, - 200, - ), - ]; - for (name, shape, timed) in rows { - let buffers = match shape { - Shape::Large { .. } => Buffers::new(&device, 40, LARGE)?, - Shape::Small { .. } => Buffers::new(&device, 2, SMALL)?, - }; - let mut round = 0u8; - let mut next = || { - round = round.wrapping_add(1).max(FIRST + 1); - round - }; - for _ in 0..WARM { - run(&queue, shape, &buffers, &target, next())?; - } - let before = device.work_counts(); - let mut gpu = Vec::with_capacity(timed); - let mut wall = Vec::with_capacity(timed); - for _ in 0..timed { - let (seconds, elapsed) = run(&queue, shape, &buffers, &target, next())?; - gpu.push(seconds * 1e3); - wall.push(elapsed * 1e3); - } - let after = device.work_counts(); - let each = - |pick: fn(&WorkCounts) -> u64| (pick(&after) - pick(&before)) as f64 / timed as f64; - let topped_up = match ( - field(&after, "managed_synchronizes_topped_up"), - field(&before, "managed_synchronizes_topped_up"), - ) { - (Some(after), Some(before)) => (after - before).to_string(), - _ => "-".to_string(), - }; - println!( - "ROW {name} gpu_ms {:.3} wall_ms {:.3} copied_mb {:.2} subs {:.2} infos {:.2} \ - vkcbs {:.2} ({:.2}, {:.2}, {:.2}, {:.2}, {:.2}) fillq {:.2} commit_us {:.1} \ - topped_up {topped_up} {}", - median(&mut gpu), - median(&mut wall), - each(|counts| counts.managed_bytes_copied_out) / 1e6, - each(|counts| counts.queue_submissions), - each(|counts| counts.submit_infos), - each(|counts| counts.command_buffers_begun), - each(|counts| counts.command_buffers_begun_encoders), - each(|counts| counts.command_buffers_begun_continuations), - each(|counts| counts.command_buffers_begun_batch_work), - each(|counts| counts.command_buffers_begun_batch_barriers), - each(|counts| counts.command_buffers_begun_internal), - each(|counts| counts.fill_queue_submissions), - each(|counts| counts.commit_nanos) / 1e3, - device.name() - ); - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/pass_costs.rs b/crates/metal2vulkan-runtime/examples/pass_costs.rs deleted file mode 100644 index b7abd0a62..000000000 --- a/crates/metal2vulkan-runtime/examples/pass_costs.rs +++ /dev/null @@ -1,1086 +0,0 @@ -//! Not a consumer's example: what a render pass instance costs the driver's CPU, by how it is -//! recorded. It uses no runtime: a Vulkan 1.3 device of its own, made through the loader, on the -//! first discrete GPU (else integrated, virtual or CPU device) the loader lists. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example pass_costs -- \ -//! [--frames F] [--repeats R] [--draws D] [--extent W,H] [--clear] [--begins] -//! ``` -//! -//! Each frame is [`PASSES`] render pass instances of `D` draws (1 by default), over one -//! `B8G8R8A8_UNORM` color attachment of `W` by `H` texels (1024 by 1024 by default) held in -//! `GENERAL`, loaded (cleared with `--clear`) and stored, submitted [`GROUP`] passes -//! to a `vkQueueSubmit`, two frames in flight; each draw binds the pipeline and draws a triangle. -//! The shapes: -//! -//! - **Command buffers**: a primary of its own for each pass (`per-pass`), as the runtime records -//! an encoder's pass, or one primary for each submission's passes (`per-group`). A new primary -//! starts with no dynamic state, so it sets the 17 dynamic states the runtime's draws record -//! (`render.rs`'s `RECORDED` and the color write mask); `per-group-restated` sets them at each -//! pass too. `per-pass-fresh` allocates each pass's primary and frees it once its frame -//! completed, the pool untrimmed (Mesa's common pool keeps a freed command buffer for its next -//! allocation); `per-pass-fresh-trimmed` trims the pool after the frees, so each allocation -//! makes a new command buffer, with no command stream memory of its own yet. -//! - **The instance**: a `VkRenderPass` instance (`vkCmdBeginRenderPass`) over a `VkFramebuffer` -//! made for the pass and destroyed once its frame completed (`made`), as the runtime makes one -//! for each instance (`render_target::framebuffer`), or over one framebuffer kept (`kept`); or a -//! dynamic rendering instance (`vkCmdBeginRendering`, `dynamic`), which takes no framebuffer. -//! -//! It prints a `PASS-COSTS` line for each shape: the calling thread's CPU time a pass (the -//! median of `R` runs of `F` frames, 5 of 200 by default, after a run of 20 not counted) to -//! record (its framebuffer's making included), to submit, and to reclaim (the framebuffers' -//! destruction and the command pool's reset once the frame completed), and their sum. Then the -//! differences between shapes that differ in one thing, a pass. With `--begins` it also times -//! each `vkBeginCommandBuffer` and each instance's begin (`vkCmdBeginRenderPass` or -//! `vkCmdBeginRendering`) alone, a pass, which adds the clock's reads to the record time. - -use std::cell::Cell; - -use ash::vk; - -/// Render pass instances a frame: the walk's frames of the window server averaged about 150. -const PASSES: usize = 150; - -/// Passes a `vkQueueSubmit`: the walk's submissions averaged about 6 primaries each. -const GROUP: usize = 6; - -/// Frames in flight. -const SLOTS: usize = 2; - -/// The color attachment's extent where the command line gives none. -const EXTENT: vk::Extent2D = vk::Extent2D { - width: 1024, - height: 1024, -}; - -/// The color attachment's format. -const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM; - -/// The attachment's clear value, where it is cleared (`--clear`). -const CLEAR: [vk::ClearValue; 1] = [vk::ClearValue { - color: vk::ClearColorValue { - float32: [0.0, 0.0, 0.0, 1.0], - }, -}]; - -/// The longest wait for a frame. -const TIMEOUT: u64 = 20_000_000_000; - -/// The vertex shader: a small triangle from the vertex index, no input. Compiled from this GLSL -/// with glslang (`--target-env vulkan1.0`, debug names stripped): -/// -/// ```glsl -/// #version 450 -/// void main() { -/// vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2)); -/// gl_Position = vec4(p * 0.25 - 0.5, 0.0, 1.0); -/// } -/// ``` -#[rustfmt::skip] -const VERTEX_SPIRV: [u32; 236] = [ - 0x07230203, 0x00010000, 0x0008000b, 0x0000002c, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0007000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000c, 0x0000001d, 0x00040047, - 0x0000000c, 0x0000000b, 0x0000002a, 0x00030047, 0x0000001b, 0x00000002, 0x00050048, 0x0000001b, - 0x00000000, 0x0000000b, 0x00000000, 0x00050048, 0x0000001b, 0x00000001, 0x0000000b, 0x00000001, - 0x00050048, 0x0000001b, 0x00000002, 0x0000000b, 0x00000003, 0x00050048, 0x0000001b, 0x00000003, - 0x0000000b, 0x00000004, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, - 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000002, 0x00040020, 0x00000008, - 0x00000007, 0x00000007, 0x00040015, 0x0000000a, 0x00000020, 0x00000001, 0x00040020, 0x0000000b, - 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000001, 0x0004002b, 0x0000000a, - 0x0000000e, 0x00000001, 0x0004002b, 0x0000000a, 0x00000010, 0x00000002, 0x00040017, 0x00000017, - 0x00000006, 0x00000004, 0x00040015, 0x00000018, 0x00000020, 0x00000000, 0x0004002b, 0x00000018, - 0x00000019, 0x00000001, 0x0004001c, 0x0000001a, 0x00000006, 0x00000019, 0x0006001e, 0x0000001b, - 0x00000017, 0x00000006, 0x0000001a, 0x0000001a, 0x00040020, 0x0000001c, 0x00000003, 0x0000001b, - 0x0004003b, 0x0000001c, 0x0000001d, 0x00000003, 0x0004002b, 0x0000000a, 0x0000001e, 0x00000000, - 0x0004002b, 0x00000006, 0x00000020, 0x3e800000, 0x0004002b, 0x00000006, 0x00000022, 0x3f000000, - 0x0004002b, 0x00000006, 0x00000025, 0x00000000, 0x0004002b, 0x00000006, 0x00000026, 0x3f800000, - 0x00040020, 0x0000002a, 0x00000003, 0x00000017, 0x00050036, 0x00000002, 0x00000004, 0x00000000, - 0x00000003, 0x000200f8, 0x00000005, 0x0004003b, 0x00000008, 0x00000009, 0x00000007, 0x0004003d, - 0x0000000a, 0x0000000d, 0x0000000c, 0x000500c4, 0x0000000a, 0x0000000f, 0x0000000d, 0x0000000e, - 0x000500c7, 0x0000000a, 0x00000011, 0x0000000f, 0x00000010, 0x0004006f, 0x00000006, 0x00000012, - 0x00000011, 0x0004003d, 0x0000000a, 0x00000013, 0x0000000c, 0x000500c7, 0x0000000a, 0x00000014, - 0x00000013, 0x00000010, 0x0004006f, 0x00000006, 0x00000015, 0x00000014, 0x00050050, 0x00000007, - 0x00000016, 0x00000012, 0x00000015, 0x0003003e, 0x00000009, 0x00000016, 0x0004003d, 0x00000007, - 0x0000001f, 0x00000009, 0x0005008e, 0x00000007, 0x00000021, 0x0000001f, 0x00000020, 0x00050050, - 0x00000007, 0x00000023, 0x00000022, 0x00000022, 0x00050083, 0x00000007, 0x00000024, 0x00000021, - 0x00000023, 0x00050051, 0x00000006, 0x00000027, 0x00000024, 0x00000000, 0x00050051, 0x00000006, - 0x00000028, 0x00000024, 0x00000001, 0x00070050, 0x00000017, 0x00000029, 0x00000027, 0x00000028, - 0x00000025, 0x00000026, 0x00050041, 0x0000002a, 0x0000002b, 0x0000001d, 0x0000001e, 0x0003003e, - 0x0000002b, 0x00000029, 0x000100fd, 0x00010038, -]; - -/// The fragment shader: one color. Compiled as [`VERTEX_SPIRV`] from: -/// -/// ```glsl -/// #version 450 -/// layout(location = 0) out vec4 color; -/// void main() { -/// color = vec4(0.25, 0.5, 0.75, 1.0); -/// } -/// ``` -#[rustfmt::skip] -const FRAGMENT_SPIRV: [u32; 84] = [ - 0x07230203, 0x00010000, 0x0008000b, 0x0000000f, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0006000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x00030010, 0x00000004, - 0x00000007, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, - 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, - 0x00000004, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000009, - 0x00000003, 0x0004002b, 0x00000006, 0x0000000a, 0x3e800000, 0x0004002b, 0x00000006, 0x0000000b, - 0x3f000000, 0x0004002b, 0x00000006, 0x0000000c, 0x3f400000, 0x0004002b, 0x00000006, 0x0000000d, - 0x3f800000, 0x0007002c, 0x00000007, 0x0000000e, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000d, - 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0003003e, - 0x00000009, 0x0000000e, 0x000100fd, 0x00010038, -]; - -/// How a frame's passes take primaries. -#[derive(Clone, Copy, PartialEq)] -enum Buffers { - /// A primary of its own for each pass, setting the dynamic states. - Pass, - /// One primary for each submission's passes, setting the dynamic states once. - Group, - /// One primary for each submission's passes, setting the dynamic states at each pass. - GroupRestated, - /// A primary allocated for each pass, freed once its frame completed. - Fresh, - /// A primary allocated for each pass, freed once its frame completed, the pool trimmed. - FreshTrimmed, -} - -/// How a pass begins its instance. -#[derive(Clone, Copy, PartialEq)] -enum Instance { - /// `vkCmdBeginRenderPass` over a framebuffer made for the pass. - Made, - /// `vkCmdBeginRenderPass` over one framebuffer kept. - Kept, - /// `vkCmdBeginRendering`. - Dynamic, -} - -/// A way to record a frame. -#[derive(Clone, Copy)] -struct Shape { - buffers: Buffers, - instance: Instance, -} - -impl Shape { - fn name(self) -> String { - let buffers = match self.buffers { - Buffers::Pass => "per-pass", - Buffers::Group => "per-group", - Buffers::GroupRestated => "per-group-restated", - Buffers::Fresh => "per-pass-fresh", - Buffers::FreshTrimmed => "per-pass-fresh-trimmed", - }; - let instance = match self.instance { - Instance::Made => "made", - Instance::Kept => "kept", - Instance::Dynamic => "dynamic", - }; - format!("{buffers}/{instance}") - } -} - -/// The shapes, in the order they run. -const SHAPES: [Shape; 9] = [ - Shape { - buffers: Buffers::Pass, - instance: Instance::Made, - }, - Shape { - buffers: Buffers::Pass, - instance: Instance::Kept, - }, - Shape { - buffers: Buffers::Pass, - instance: Instance::Dynamic, - }, - Shape { - buffers: Buffers::GroupRestated, - instance: Instance::Made, - }, - Shape { - buffers: Buffers::Group, - instance: Instance::Made, - }, - Shape { - buffers: Buffers::Group, - instance: Instance::Kept, - }, - Shape { - buffers: Buffers::Group, - instance: Instance::Dynamic, - }, - Shape { - buffers: Buffers::Fresh, - instance: Instance::Made, - }, - Shape { - buffers: Buffers::FreshTrimmed, - instance: Instance::Made, - }, -]; - -/// The pairs of shapes that differ in one thing, and what that is. -const DIFFERENCES: [(usize, usize, &str); 8] = [ - ( - 0, - 3, - "a primary per pass (begin, end, submission), states set in both", - ), - (3, 4, "the 17 dynamic states set again"), - (0, 1, "a framebuffer made and destroyed (primary per pass)"), - ( - 1, - 2, - "vkCmdBeginRenderPass against vkCmdBeginRendering (primary per pass)", - ), - ( - 0, - 2, - "a render pass instance with its framebuffer against dynamic rendering", - ), - ( - 0, - 6, - "today's shape against a primary per group and dynamic rendering", - ), - ( - 7, - 0, - "a primary allocated and freed for each pass against one kept", - ), - ( - 8, - 0, - "a new primary for each pass (pool trimmed) against one kept", - ), -]; - -/// A frame's slot: its command pool and primaries, the primaries its frame allocated and whether -/// their frees trim the pool, the framebuffers its passes made, and the fence its last submission -/// signals. -struct Slot { - pool: vk::CommandPool, - buffers: Vec, - fresh: Vec, - trim: bool, - framebuffers: Vec, - fence: vk::Fence, -} - -/// The calling thread's CPU time in nanoseconds. -#[cfg(unix)] -fn thread_ns() -> u64 { - let mut at = libc::timespec { - tv_sec: 0, - tv_nsec: 0, - }; - // SAFETY: `at` is a live `timespec` the call writes. - let answer = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut at) }; - assert_eq!(answer, 0, "{}", std::io::Error::last_os_error()); - at.tv_sec as u64 * 1_000_000_000 + at.tv_nsec as u64 -} - -/// The calling thread's CPU time in nanoseconds: its kernel and user times (`GetThreadTimes`), -/// in 100 ns units. -#[cfg(windows)] -fn thread_ns() -> u64 { - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetThreadTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 -} - -/// The CPU time of a run's phases, in nanoseconds a pass, and of the begins inside the record -/// (`--begins`; 0 where untimed). -#[derive(Clone, Copy, Default)] -struct Phases { - record: f64, - submit: f64, - reclaim: f64, - buffer_begins: f64, - instance_begins: f64, -} - -impl Phases { - fn total(self) -> f64 { - self.record + self.submit + self.reclaim - } -} - -/// The median of `values`. -fn median(mut values: Vec) -> f64 { - values.sort_by(f64::total_cmp); - values[values.len() / 2] -} - -/// The device, its attachment, render pass, pipelines and frame slots. -struct Bench { - _entry: ash::Entry, - instance: ash::Instance, - device: ash::Device, - color_mask: Option, - queue: vk::Queue, - image: vk::Image, - memory: vk::DeviceMemory, - view: vk::ImageView, - render_pass: vk::RenderPass, - kept: vk::Framebuffer, - layout: vk::PipelineLayout, - pass_pipeline: vk::Pipeline, - dynamic_pipeline: vk::Pipeline, - slots: Vec, - next: usize, - draws: u32, - extent: vk::Extent2D, - load: vk::AttachmentLoadOp, - /// Whether the begins are timed (`--begins`), and their thread time this run: the primaries' - /// and the instances'. - timed: bool, - begins: [Cell; 2], -} - -impl Bench { - fn new(draws: u32, extent: vk::Extent2D, load: vk::AttachmentLoadOp, timed: bool) -> Bench { - // SAFETY: loading the Vulkan loader runs its initialization; nothing else is assumed. - let entry = unsafe { ash::Entry::load() }.expect("the Vulkan loader"); - // SAFETY: a global command of a loaded entry. - let listed = unsafe { entry.enumerate_instance_extension_properties(None) }.unwrap(); - let portability = listed.iter().any(|extension| { - extension.extension_name_as_c_str() == Ok(ash::khr::portability_enumeration::NAME) - }); - let extensions: Vec<*const std::ffi::c_char> = match portability { - true => vec![ash::khr::portability_enumeration::NAME.as_ptr()], - false => Vec::new(), - }; - let application = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_3); - let info = vk::InstanceCreateInfo::default() - .application_info(&application) - .enabled_extension_names(&extensions) - .flags(match portability { - true => vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR, - false => vk::InstanceCreateFlags::empty(), - }); - // SAFETY: `info` and what it points at live for the call. - let instance = unsafe { entry.create_instance(&info, None) }.unwrap(); - // SAFETY: the instance is live. - let physicals = unsafe { instance.enumerate_physical_devices() }.unwrap(); - let types = [ - vk::PhysicalDeviceType::DISCRETE_GPU, - vk::PhysicalDeviceType::INTEGRATED_GPU, - vk::PhysicalDeviceType::VIRTUAL_GPU, - vk::PhysicalDeviceType::CPU, - ]; - // SAFETY: each is the instance's. - let properties = |physical: vk::PhysicalDevice| unsafe { - instance.get_physical_device_properties(physical) - }; - let physical = (types.iter()) - .find_map(|&wanted| { - (physicals.iter().copied()).find(|&p| properties(p).device_type == wanted) - }) - .expect("a device"); - let found = properties(physical); - assert!( - found.api_version >= vk::API_VERSION_1_3, - "a Vulkan 1.3 device" - ); - let mut driver = vk::PhysicalDeviceDriverProperties::default(); - let mut wanted = vk::PhysicalDeviceProperties2::default().push_next(&mut driver); - // SAFETY: the instance's; Vulkan 1.1's command. - unsafe { instance.get_physical_device_properties2(physical, &mut wanted) }; - let name = (found.device_name_as_c_str()) - .map_or("?".to_owned(), |name| name.to_string_lossy().into_owned()); - let driver_info = (driver.driver_info_as_c_str()) - .map_or("?".to_owned(), |info| info.to_string_lossy().into_owned()); - // SAFETY: the instance's. - let device_extensions = - unsafe { instance.enumerate_device_extension_properties(physical) }.unwrap(); - let has_state3 = device_extensions.iter().any(|extension| { - extension.extension_name_as_c_str() == Ok(ash::ext::extended_dynamic_state3::NAME) - }); - let mut state3 = vk::PhysicalDeviceExtendedDynamicState3FeaturesEXT::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut state3); - // SAFETY: the instance's; Vulkan 1.1's command. - unsafe { instance.get_physical_device_features2(physical, &mut features) }; - let color_mask = has_state3 && state3.extended_dynamic_state3_color_write_mask == vk::TRUE; - println!( - "PASS-COSTS device {name} driver {driver_info} color write mask {color_mask} \ - passes {PASSES} group {GROUP} draws {draws} extent {}x{} cleared {}", - extent.width, - extent.height, - load == vk::AttachmentLoadOp::CLEAR, - ); - // SAFETY: the instance's. - let families = unsafe { instance.get_physical_device_queue_family_properties(physical) }; - let family = (families.iter()) - .position(|family| family.queue_flags.contains(vk::QueueFlags::GRAPHICS)) - .expect("a family of graphics work") as u32; - let priorities = [1.0]; - let queue_infos = [vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities)]; - let mut v13 = vk::PhysicalDeviceVulkan13Features::default().dynamic_rendering(true); - let mut state3 = vk::PhysicalDeviceExtendedDynamicState3FeaturesEXT::default() - .extended_dynamic_state3_color_write_mask(true); - let names = [ash::ext::extended_dynamic_state3::NAME.as_ptr()]; - let mut info = vk::DeviceCreateInfo::default() - .queue_create_infos(&queue_infos) - .push_next(&mut v13); - if color_mask { - info = info.enabled_extension_names(&names).push_next(&mut state3); - } - // SAFETY: `info` and what it points at live for the call. - let device = unsafe { instance.create_device(physical, &info, None) }.unwrap(); - let color_mask = - color_mask.then(|| ash::ext::extended_dynamic_state3::Device::new(&instance, &device)); - // SAFETY: the family's first queue was created. - let queue = unsafe { device.get_device_queue(family, 0) }; - // SAFETY: the instance's. - let memory_types = unsafe { instance.get_physical_device_memory_properties(physical) }; - let image_info = vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(FORMAT) - .extent(extent.into()) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::OPTIMAL) - .usage( - vk::ImageUsageFlags::COLOR_ATTACHMENT - | vk::ImageUsageFlags::SAMPLED - | vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST, - ) - .initial_layout(vk::ImageLayout::UNDEFINED); - // SAFETY: `image_info` is valid for the device. - let image = unsafe { device.create_image(&image_info, None) }.unwrap(); - // SAFETY: the image is the device's. - let needs = unsafe { device.get_image_memory_requirements(image) }; - let types = &memory_types.memory_types[..memory_types.memory_type_count as usize]; - let local = vk::MemoryPropertyFlags::DEVICE_LOCAL; - let type_index = (0..types.len()) - .find(|&index| { - needs.memory_type_bits & (1 << index) != 0 - && types[index].property_flags.contains(local) - }) - .or_else(|| (0..types.len()).find(|&index| needs.memory_type_bits & (1 << index) != 0)) - .expect("a memory type for the image") as u32; - let allocate = vk::MemoryAllocateInfo::default() - .allocation_size(needs.size) - .memory_type_index(type_index); - // SAFETY: a valid allocation of the device; the image is bound to it once. - let memory = unsafe { device.allocate_memory(&allocate, None) }.unwrap(); - // SAFETY: as above. - unsafe { device.bind_image_memory(image, memory, 0) }.unwrap(); - let range = vk::ImageSubresourceRange::default() - .aspect_mask(vk::ImageAspectFlags::COLOR) - .level_count(1) - .layer_count(1); - let view_info = vk::ImageViewCreateInfo::default() - .image(image) - .view_type(vk::ImageViewType::TYPE_2D) - .format(FORMAT) - .subresource_range(range); - // SAFETY: the image is bound and live. - let view = unsafe { device.create_image_view(&view_info, None) }.unwrap(); - let attachment = [vk::AttachmentDescription::default() - .format(FORMAT) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(load) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(vk::ImageLayout::GENERAL) - .final_layout(vk::ImageLayout::GENERAL)]; - let reference = [vk::AttachmentReference::default() - .attachment(0) - .layout(vk::ImageLayout::GENERAL)]; - let subpass = [vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&reference)]; - let pass_info = vk::RenderPassCreateInfo::default() - .attachments(&attachment) - .subpasses(&subpass); - // SAFETY: `pass_info` and what it points at live for the call. - let render_pass = unsafe { device.create_render_pass(&pass_info, None) }.unwrap(); - let kept = framebuffer(&device, render_pass, view, extent); - // SAFETY: an empty layout. - let layout = unsafe { - device.create_pipeline_layout(&vk::PipelineLayoutCreateInfo::default(), None) - } - .unwrap(); - let (pass_pipeline, dynamic_pipeline) = - pipelines(&device, render_pass, layout, color_mask.is_some()); - let slots = (0..SLOTS) - .map(|_| { - let pool_info = vk::CommandPoolCreateInfo::default().queue_family_index(family); - // SAFETY: the family's. - let pool = unsafe { device.create_command_pool(&pool_info, None) }.unwrap(); - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(PASSES as u32); - // SAFETY: the pool is live. - let buffers = unsafe { device.allocate_command_buffers(&allocate) }.unwrap(); - let fence_info = - vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED); - // SAFETY: a valid fence of the device. - let fence = unsafe { device.create_fence(&fence_info, None) }.unwrap(); - Slot { - pool, - buffers, - fresh: Vec::with_capacity(PASSES), - trim: false, - framebuffers: Vec::with_capacity(PASSES), - fence, - } - }) - .collect(); - let bench = Bench { - _entry: entry, - instance, - device, - color_mask, - queue, - image, - memory, - view, - render_pass, - kept, - layout, - pass_pipeline, - dynamic_pipeline, - slots, - next: 0, - draws, - extent, - load, - timed, - begins: [Cell::new(0), Cell::new(0)], - }; - bench.to_general(range); - bench - } - - /// Move the attachment into `GENERAL`, once, and wait. - fn to_general(&self, range: vk::ImageSubresourceRange) { - let device = &self.device; - let slot = &self.slots[0]; - let command = slot.buffers[0]; - let barrier = [vk::ImageMemoryBarrier::default() - .src_access_mask(vk::AccessFlags::empty()) - .dst_access_mask( - vk::AccessFlags::COLOR_ATTACHMENT_READ | vk::AccessFlags::COLOR_ATTACHMENT_WRITE, - ) - .old_layout(vk::ImageLayout::UNDEFINED) - .new_layout(vk::ImageLayout::GENERAL) - .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .image(self.image) - .subresource_range(range)]; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - let commands = [command]; - let submit = [vk::SubmitInfo::default().command_buffers(&commands)]; - // SAFETY: the command buffer is idle; the barrier names the live image; the wait ends its - // use before the pool is reset. - unsafe { - device.begin_command_buffer(command, &begin).unwrap(); - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::TOP_OF_PIPE, - vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, - vk::DependencyFlags::empty(), - &[], - &[], - &barrier, - ); - device.end_command_buffer(command).unwrap(); - device - .queue_submit(self.queue, &submit, vk::Fence::null()) - .unwrap(); - device.queue_wait_idle(self.queue).unwrap(); - (device.reset_command_pool(slot.pool, vk::CommandPoolResetFlags::empty())).unwrap(); - } - } - - /// Run `call`, adding its thread time to begin `at`'s where the begins are timed. - fn begin(&self, at: usize, call: impl FnOnce()) { - match self.timed { - true => { - let start = thread_ns(); - call(); - (self.begins[at]).set(self.begins[at].get() + thread_ns() - start); - } - false => call(), - } - } - - /// A primary allocated from `pool`. - fn allocate(&self, pool: vk::CommandPool) -> vk::CommandBuffer { - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - // SAFETY: the pool is live and this thread's alone. - unsafe { self.device.allocate_command_buffers(&allocate) }.unwrap()[0] - } - - /// Set the 17 dynamic states on `command`, as a new primary needs. - fn set_states(&self, command: vk::CommandBuffer) { - let device = &self.device; - let viewport = [vk::Viewport { - x: 0.0, - y: 0.0, - width: self.extent.width as f32, - height: self.extent.height as f32, - min_depth: 0.0, - max_depth: 1.0, - }]; - let scissor = [vk::Rect2D { - offset: vk::Offset2D::default(), - extent: self.extent, - }]; - let both = vk::StencilFaceFlags::FRONT_AND_BACK; - // SAFETY: `command` is recording, of a device of Vulkan 1.3, whose pipelines take each - // state as dynamic. - unsafe { - device.cmd_set_viewport(command, 0, &viewport); - device.cmd_set_scissor(command, 0, &scissor); - device.cmd_set_depth_bias(command, 0.0, 0.0, 0.0); - device.cmd_set_blend_constants(command, &[0.0; 4]); - device.cmd_set_stencil_compare_mask(command, both, !0); - device.cmd_set_stencil_write_mask(command, both, !0); - device.cmd_set_stencil_reference(command, both, 0); - device.cmd_set_cull_mode(command, vk::CullModeFlags::NONE); - device.cmd_set_front_face(command, vk::FrontFace::COUNTER_CLOCKWISE); - device.cmd_set_primitive_topology(command, vk::PrimitiveTopology::TRIANGLE_LIST); - device.cmd_set_primitive_restart_enable(command, false); - device.cmd_set_depth_test_enable(command, false); - device.cmd_set_depth_write_enable(command, false); - device.cmd_set_depth_compare_op(command, vk::CompareOp::ALWAYS); - device.cmd_set_stencil_test_enable(command, false); - device.cmd_set_stencil_op( - command, - both, - vk::StencilOp::KEEP, - vk::StencilOp::KEEP, - vk::StencilOp::KEEP, - vk::CompareOp::ALWAYS, - ); - if let Some(color_mask) = &self.color_mask { - color_mask.cmd_set_color_write_mask(command, 0, &[vk::ColorComponentFlags::RGBA]); - } - } - } - - /// Record one pass into `command`: its instance, `draws` draws, its end; a framebuffer made - /// for it goes into `made`. - fn pass( - &self, - command: vk::CommandBuffer, - instance: Instance, - made: &mut Vec, - ) { - let device = &self.device; - let area = vk::Rect2D { - offset: vk::Offset2D::default(), - extent: self.extent, - }; - // SAFETY: `command` is recording, outside any instance; the framebuffer, view and - // pipelines are live until the frame completed. - unsafe { - let pipeline = match instance { - Instance::Made | Instance::Kept => { - let target = match instance { - Instance::Made => { - let target = - framebuffer(device, self.render_pass, self.view, self.extent); - made.push(target); - target - } - _ => self.kept, - }; - let begin = vk::RenderPassBeginInfo::default() - .render_pass(self.render_pass) - .framebuffer(target) - .render_area(area) - .clear_values(&CLEAR); - self.begin(1, || { - device.cmd_begin_render_pass(command, &begin, vk::SubpassContents::INLINE) - }); - self.pass_pipeline - } - Instance::Dynamic => { - let colors = [vk::RenderingAttachmentInfo::default() - .image_view(self.view) - .image_layout(vk::ImageLayout::GENERAL) - .load_op(self.load) - .store_op(vk::AttachmentStoreOp::STORE) - .clear_value(CLEAR[0])]; - let begin = vk::RenderingInfo::default() - .render_area(area) - .layer_count(1) - .color_attachments(&colors); - self.begin(1, || device.cmd_begin_rendering(command, &begin)); - self.dynamic_pipeline - } - }; - for _ in 0..self.draws { - device.cmd_bind_pipeline(command, vk::PipelineBindPoint::GRAPHICS, pipeline); - device.cmd_draw(command, 3, 1, 0, 0); - } - match instance { - Instance::Dynamic => device.cmd_end_rendering(command), - _ => device.cmd_end_render_pass(command), - } - } - } - - /// Run `frames` frames of `shape`: the CPU time of each phase, a pass. - fn run(&mut self, shape: Shape, frames: usize) -> Phases { - let mut spent = [0u64; 3]; - for begins in &self.begins { - begins.set(0); - } - for _ in 0..frames { - let at = self.next; - self.next = (self.next + 1) % SLOTS; - let fence = self.slots[at].fence; - // SAFETY: the slot's fence, signaled by its last frame's last submission. - unsafe { self.device.wait_for_fences(&[fence], true, TIMEOUT) }.unwrap(); - let start = thread_ns(); - for target in self.slots[at].framebuffers.drain(..) { - // SAFETY: the frame that used it completed. - unsafe { self.device.destroy_framebuffer(target, None) }; - } - // SAFETY: the slot's command buffers completed (the fence). - unsafe { - let slot = &mut self.slots[at]; - if !slot.fresh.is_empty() { - self.device.free_command_buffers(slot.pool, &slot.fresh); - slot.fresh.clear(); - if slot.trim { - (self.device) - .trim_command_pool(slot.pool, vk::CommandPoolTrimFlags::empty()); - } - } - let pool = self.slots[at].pool; - (self - .device - .reset_command_pool(pool, vk::CommandPoolResetFlags::empty())) - .unwrap(); - self.device.reset_fences(&[fence]).unwrap(); - } - let reclaimed = thread_ns(); - let (submissions, made) = self.record(at, shape); - let recorded = thread_ns(); - for (index, commands) in submissions.iter().enumerate() { - let submit = [vk::SubmitInfo::default().command_buffers(commands)]; - let signal = match index + 1 == submissions.len() { - true => fence, - false => vk::Fence::null(), - }; - // SAFETY: each command buffer is executable and submitted once. - unsafe { self.device.queue_submit(self.queue, &submit, signal) }.unwrap(); - } - let submitted = thread_ns(); - self.slots[at].framebuffers = made; - if matches!(shape.buffers, Buffers::Fresh | Buffers::FreshTrimmed) { - self.slots[at].fresh = submissions.concat(); - self.slots[at].trim = shape.buffers == Buffers::FreshTrimmed; - } - spent[0] += recorded - reclaimed; - spent[1] += submitted - recorded; - spent[2] += reclaimed - start; - } - let passes = (frames * PASSES) as f64; - Phases { - record: spent[0] as f64 / passes, - submit: spent[1] as f64 / passes, - reclaim: spent[2] as f64 / passes, - buffer_begins: self.begins[0].get() as f64 / passes, - instance_begins: self.begins[1].get() as f64 / passes, - } - } - - /// Record a frame of `shape` into slot `at`'s primaries: each submission's command buffers, - /// and the framebuffers its passes made. - fn record( - &self, - at: usize, - shape: Shape, - ) -> (Vec>, Vec) { - let mut made = Vec::with_capacity(PASSES); - let device = &self.device; - let (buffers, pool) = (&self.slots[at].buffers, self.slots[at].pool); - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - let mut submissions = Vec::with_capacity(PASSES / GROUP + 1); - for group in 0..PASSES.div_ceil(GROUP) { - let passes = group * GROUP..((group + 1) * GROUP).min(PASSES); - let mut commands = Vec::with_capacity(GROUP); - // SAFETY: each primary is reset (its pool) and begun once a frame. - unsafe { - match shape.buffers { - Buffers::Pass | Buffers::Fresh | Buffers::FreshTrimmed => { - for pass in passes { - let command = match shape.buffers { - Buffers::Pass => buffers[pass], - _ => self.allocate(pool), - }; - self.begin(0, || device.begin_command_buffer(command, &begin).unwrap()); - self.set_states(command); - self.pass(command, shape.instance, &mut made); - device.end_command_buffer(command).unwrap(); - commands.push(command); - } - } - Buffers::Group | Buffers::GroupRestated => { - let command = buffers[group]; - self.begin(0, || device.begin_command_buffer(command, &begin).unwrap()); - for pass in passes.clone() { - if pass == passes.start || shape.buffers == Buffers::GroupRestated { - self.set_states(command); - } - self.pass(command, shape.instance, &mut made); - } - device.end_command_buffer(command).unwrap(); - commands.push(command); - } - } - } - submissions.push(commands); - } - (submissions, made) - } -} - -impl Drop for Bench { - fn drop(&mut self) { - let device = &self.device; - // SAFETY: the queue goes idle first; then nothing uses any of these. - unsafe { - device.queue_wait_idle(self.queue).unwrap(); - for slot in &self.slots { - for &target in &slot.framebuffers { - device.destroy_framebuffer(target, None); - } - device.destroy_fence(slot.fence, None); - device.destroy_command_pool(slot.pool, None); - } - device.destroy_pipeline(self.pass_pipeline, None); - device.destroy_pipeline(self.dynamic_pipeline, None); - device.destroy_pipeline_layout(self.layout, None); - device.destroy_framebuffer(self.kept, None); - device.destroy_render_pass(self.render_pass, None); - device.destroy_image_view(self.view, None); - device.destroy_image(self.image, None); - device.free_memory(self.memory, None); - device.destroy_device(None); - self.instance.destroy_instance(None); - } - } -} - -/// A framebuffer of `render_pass` over `view`. -fn framebuffer( - device: &ash::Device, - render_pass: vk::RenderPass, - view: vk::ImageView, - extent: vk::Extent2D, -) -> vk::Framebuffer { - let views = [view]; - let info = vk::FramebufferCreateInfo::default() - .render_pass(render_pass) - .attachments(&views) - .width(extent.width) - .height(extent.height) - .layers(1); - // SAFETY: `info` and the view are live for the call; the view is of `extent`. - unsafe { device.create_framebuffer(&info, None) }.unwrap() -} - -/// The two pipelines: of `render_pass`'s subpass, and of dynamic rendering into [`FORMAT`]; every -/// state the runtime's draws record is dynamic in both (the color write mask where `color_mask`). -fn pipelines( - device: &ash::Device, - render_pass: vk::RenderPass, - layout: vk::PipelineLayout, - color_mask: bool, -) -> (vk::Pipeline, vk::Pipeline) { - let module = |code: &[u32]| { - let info = vk::ShaderModuleCreateInfo::default().code(code); - // SAFETY: valid SPIR-V of Vulkan 1.0. - unsafe { device.create_shader_module(&info, None) }.unwrap() - }; - let (vertex, fragment) = (module(&VERTEX_SPIRV), module(&FRAGMENT_SPIRV)); - let stages = [ - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(vertex) - .name(c"main"), - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::FRAGMENT) - .module(fragment) - .name(c"main"), - ]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - let assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); - let raster = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(vk::PolygonMode::FILL) - .line_width(1.0); - let multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::TYPE_1); - let depth = vk::PipelineDepthStencilStateCreateInfo::default(); - let blend = [vk::PipelineColorBlendAttachmentState::default() - .color_write_mask(vk::ColorComponentFlags::RGBA)]; - let blending = vk::PipelineColorBlendStateCreateInfo::default().attachments(&blend); - let mut states = vec![ - vk::DynamicState::VIEWPORT, - vk::DynamicState::SCISSOR, - vk::DynamicState::DEPTH_BIAS, - vk::DynamicState::BLEND_CONSTANTS, - vk::DynamicState::STENCIL_COMPARE_MASK, - vk::DynamicState::STENCIL_WRITE_MASK, - vk::DynamicState::STENCIL_REFERENCE, - vk::DynamicState::CULL_MODE, - vk::DynamicState::FRONT_FACE, - vk::DynamicState::PRIMITIVE_TOPOLOGY, - vk::DynamicState::PRIMITIVE_RESTART_ENABLE, - vk::DynamicState::DEPTH_TEST_ENABLE, - vk::DynamicState::DEPTH_WRITE_ENABLE, - vk::DynamicState::DEPTH_COMPARE_OP, - vk::DynamicState::STENCIL_TEST_ENABLE, - vk::DynamicState::STENCIL_OP, - ]; - if color_mask { - states.push(vk::DynamicState::COLOR_WRITE_MASK_EXT); - } - let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&states); - let base = || { - vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&assembly) - .viewport_state(&viewport) - .rasterization_state(&raster) - .multisample_state(&multisample) - .depth_stencil_state(&depth) - .color_blend_state(&blending) - .dynamic_state(&dynamic) - .layout(layout) - }; - let formats = [FORMAT]; - let mut rendering = - vk::PipelineRenderingCreateInfo::default().color_attachment_formats(&formats); - let infos = [ - base().render_pass(render_pass).subpass(0), - base().push_next(&mut rendering), - ]; - // SAFETY: `infos` and what they point at live for the call; the device has dynamic rendering - // on and, where `color_mask`, the color write mask's dynamic state. - let made = unsafe { device.create_graphics_pipelines(vk::PipelineCache::null(), &infos, None) } - .map_err(|(_, error)| error) - .unwrap(); - // SAFETY: the pipelines no longer need the modules. - unsafe { - device.destroy_shader_module(vertex, None); - device.destroy_shader_module(fragment, None); - } - (made[0], made[1]) -} - -/// The value after `flag` on the command line, parsed, else `default`. -fn option(arguments: &[String], flag: &str, default: usize) -> usize { - match arguments.iter().position(|argument| argument == flag) { - Some(at) => (arguments.get(at + 1)) - .and_then(|value| value.parse().ok()) - .unwrap_or_else(|| panic!("{flag} takes a count")), - None => default, - } -} - -fn main() { - let arguments: Vec = std::env::args().skip(1).collect(); - let frames = option(&arguments, "--frames", 200); - let repeats = option(&arguments, "--repeats", 5).max(1); - let draws = option(&arguments, "--draws", 1) as u32; - let extent = match arguments.iter().position(|argument| argument == "--extent") { - Some(at) => { - let given = arguments.get(at + 1).expect("--extent takes W,H"); - let (width, height) = given.split_once(',').expect("--extent takes W,H"); - vk::Extent2D { - width: width.parse().expect("--extent takes W,H"), - height: height.parse().expect("--extent takes W,H"), - } - } - None => EXTENT, - }; - let load = match arguments.iter().any(|argument| argument == "--clear") { - true => vk::AttachmentLoadOp::CLEAR, - false => vk::AttachmentLoadOp::LOAD, - }; - let timed = arguments.iter().any(|argument| argument == "--begins"); - let mut bench = Bench::new(draws, extent, load, timed); - for shape in SHAPES { - bench.run(shape, 20); - } - let mut runs: Vec> = vec![Vec::new(); SHAPES.len()]; - for _ in 0..repeats { - for (index, shape) in SHAPES.iter().enumerate() { - runs[index].push(bench.run(*shape, frames)); - } - } - let medians: Vec = (runs.iter()) - .map(|phases| Phases { - record: median(phases.iter().map(|p| p.record).collect()), - submit: median(phases.iter().map(|p| p.submit).collect()), - reclaim: median(phases.iter().map(|p| p.reclaim).collect()), - buffer_begins: median(phases.iter().map(|p| p.buffer_begins).collect()), - instance_begins: median(phases.iter().map(|p| p.instance_begins).collect()), - }) - .collect(); - for (shape, phases) in SHAPES.iter().zip(&medians) { - println!( - "PASS-COSTS {:<26} record_ns {:8.0} submit_ns {:7.0} reclaim_ns {:7.0} total_ns {:8.0}", - shape.name(), - phases.record, - phases.submit, - phases.reclaim, - phases.total(), - ); - if timed { - println!( - "PASS-COSTS {:<26} begin_command_buffer_ns {:7.0} begin_instance_ns {:7.0}", - shape.name(), - phases.buffer_begins, - phases.instance_begins, - ); - } - } - for (from, to, what) in DIFFERENCES { - let (a, b) = (medians[from], medians[to]); - println!( - "PASS-COSTS difference {} - {}: {:7.0} ns a pass ({what})", - SHAPES[from].name(), - SHAPES[to].name(), - a.total() - b.total(), - ); - } -} diff --git a/crates/metal2vulkan-runtime/examples/private_bandwidth.rs b/crates/metal2vulkan-runtime/examples/private_bandwidth.rs deleted file mode 100644 index ebacc9963..000000000 --- a/crates/metal2vulkan-runtime/examples/private_bandwidth.rs +++ /dev/null @@ -1,524 +0,0 @@ -//! Not a consumer's example: the GPU's bandwidth through two 256 MiB buffers, made as a program -//! makes them (`new_buffer`, `new_buffer_with_descriptor` at an address it picks or at a pinned -//! one, or `new_buffer_with_bytes_no_copy` over pages of the example's own, over the bytes of a -//! `Shared` no-copy buffer that is a copy of them, or over read-only ones), each pair after the -//! pairs before it in the same device went, so that a pair may take the memory an earlier one -//! left. A kernel reads one buffer and writes the other, one dispatch a command buffer, committed -//! and waited for, with no CPU access. -//! -//! ```sh -//! METAL2VULKAN_LOG_MEMORY=1 cargo run --release -p metal2vulkan-runtime --example private_bandwidth -//! ``` -//! -//! Each sequence runs on a device of its own (the last one's dropped first), each pair made after -//! the device idled for [`PAUSE`], filled once with zero by a blit, then run [`PASSES`] times in -//! each of [`ROUNDS`] rounds back to back; the last [`TIMED`] of a round are timed. It prints one -//! line a round: -//! -//! ```text -//! BANDWIDTH round wall gpu made: -//! ``` -//! -//! GB/s is read plus written over the median command buffer: `wall` from commit to its wait's end, -//! `gpu` from its GPU start and end times. A `PASSES` line after it gives each command buffer's -//! commit time since the Unix epoch and its two times, in milliseconds (`at:wall/gpu`), and -//! `COUNTS` lines every `WorkCounts` field the first timed pass and the last one moved. The memory -//! counts are those the two buffers' making moved: `vkAllocateMemory` and `vkBindBufferMemory` -//! calls, live dedicated blocks, live empty blocks, overflows into system memory; then the first -//! buffer's `host_backing`. With `METAL2VULKAN_LOG_MEMORY=1` the memory log names the block and -//! memory type each buffer took. -//! -//! The kernel is `scale_and_offset` of the owned fixture (`common::library`), with a scale of 1: -//! 4 bytes read and 4 written a thread. - -mod common; - -use metal2vulkan_runtime::{ - AddressPlacement, Buffer, BufferContents, BufferDescriptor, CommandQueue, ComputePipelineState, - Device, GpuAddress, HostMemory, PipelineOptions, ResourceOptions, Size, StorageMode, - WorkCounts, -}; -use std::ptr::NonNull; -use std::sync::Arc; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; - -/// The bytes of each buffer. -const BYTES: u64 = 256 << 20; -/// The floats each buffer holds. -const COUNT: u64 = BYTES / 4; -/// The command buffers a pair runs. -const PASSES: usize = 10; -/// The last of them timed. -const TIMED: usize = 8; -/// The rounds of [`PASSES`] a pair runs, back to back. -const ROUNDS: usize = 2; -/// The device's idle time before each pair is made: as long as a guest's stages wait. -const PAUSE: Duration = Duration::from_secs(3); -/// The first pinned address, and the distance between a pair's two pins: past every range the -/// runtime picks for two 256 MiB buffers at the space's start. -const PIN_BASE: u64 = 1 << 40; -const PIN_STEP: u64 = 1 << 30; - -/// How a pair's buffers are made. -#[derive(Clone, Copy, Debug)] -enum Made { - /// `newBufferWithLength:options:`. - New, - /// `newBufferWithDescriptor:` at an address the runtime picks. - Descriptor, - /// `newBufferWithDescriptor:` at a pinned address. - Pinned, - /// `newBufferWithBytesNoCopy:length:options:deallocator:` over pages of the example's own. - NoCopy, - /// `newBufferWithLength:options:`, with a `Shared` no-copy buffer over pages of the example's - /// own beside each, which the kernel never uses and which goes with it: as a guest's `Managed` - /// buffer is made with its CPU copy over the guest's pages. - Beside, - /// `newBufferWithBytesNoCopy:length:options:deallocator:` over exactly the bytes of a `Shared` - /// no-copy buffer beside it, which the kernel never uses, whose pages' import the caller's - /// gate refused, so that it is a copy of them (`HostMemory::with_import_gate`, which refuses - /// the pair's buffer's import too): as a host that refuses a second import of pages makes a - /// guest's buffers. - OverCopy, - /// `newBufferWithBytesNoCopy:length:options:deallocator:` over pages of the example's own that - /// it maps read-only, whose import a gate refuses: the GPU's writes are dropped, so the - /// kernel's output reads the pages' zeros. - ReadOnly, -} - -/// The storage mode's bits of a resource's options. -const STORAGE_MASK: u64 = 0xf0; - -/// The resource option bit no Metal header names that programs pass with their buffers' options -/// (`ResourceOptions::BIT_20`), as a guest's calls carry it. -const BIT_20: u64 = ResourceOptions::BIT_20; - -/// A pair: its buffers' storage mode, how they are made, and the option bits passed beside the -/// storage mode. -#[derive(Clone, Copy, Debug)] -struct Pair(StorageMode, Made, u64); - -impl Pair { - fn name(self) -> String { - format!("{:?}-{:?}-{:#x}", self.0, self.1, self.options().raw()) - } - - fn options(self) -> ResourceOptions { - let modes = ResourceOptions::new(self.0, Default::default(), Default::default()); - ResourceOptions::from_raw(modes.raw() | self.2).expect("options a buffer takes") - } -} - -/// Anonymous private pages of the example's own, unmapped when dropped, after the buffer over them. -struct Pages(NonNull); - -impl Pages { - fn new() -> common::Result { - #[cfg(unix)] - // SAFETY: a new anonymous mapping, which nothing else uses. - let pointer = unsafe { - libc::mmap( - std::ptr::null_mut(), - BYTES as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, - -1, - 0, - ) - }; - #[cfg(windows)] - // SAFETY: a new allocation of its own, at an address the system picks. - let pointer = unsafe { - windows_sys::Win32::System::Memory::VirtualAlloc( - std::ptr::null(), - BYTES as usize, - windows_sys::Win32::System::Memory::MEM_RESERVE - | windows_sys::Win32::System::Memory::MEM_COMMIT, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - ) - }; - #[cfg(unix)] - if pointer == libc::MAP_FAILED { - return Err("mmap failed".into()); - } - Ok(Pages(NonNull::new(pointer.cast()).ok_or("mmap gave null")?)) - } - - /// Let the process only read them from now on. - #[cfg(unix)] - fn read_only(&self) -> common::Result<()> { - // SAFETY: the mapping `new` made, whole. - let done = - unsafe { libc::mprotect(self.0.as_ptr().cast(), BYTES as usize, libc::PROT_READ) }; - match done { - 0 => Ok(()), - _ => Err("mprotect failed".into()), - } - } - - /// Let the process only read them from now on (`VirtualProtect`). - #[cfg(windows)] - fn read_only(&self) -> common::Result<()> { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_READONLY}; - let mut old = 0; - // SAFETY: the allocation `new` made, whole, and `old` for the call to fill. - let done = unsafe { - VirtualProtect( - self.0.as_ptr().cast(), - BYTES as usize, - PAGE_READONLY, - &mut old, - ) - }; - match done { - 0 => Err("VirtualProtect failed".into()), - _ => Ok(()), - } - } -} - -impl Drop for Pages { - fn drop(&mut self) { - // SAFETY: the mapping `new` made; every buffer over it went before it. - #[cfg(unix)] - unsafe { - libc::munmap(self.0.as_ptr().cast(), BYTES as usize) - }; - #[cfg(windows)] - // SAFETY: as above; a release frees the allocation whole, from its base. - unsafe { - windows_sys::Win32::System::Memory::VirtualFree( - self.0.as_ptr().cast(), - 0, - windows_sys::Win32::System::Memory::MEM_RELEASE, - ) - }; - } -} - -/// The sequences, each on a device of its own: a pair first in a device, and after pairs of each -/// storage mode went. -const SEQUENCES: [(&str, &[Pair]); 7] = [ - ( - "first", - &[ - Pair(StorageMode::Private, Made::New, 0), - Pair(StorageMode::Private, Made::Descriptor, 0), - Pair(StorageMode::Private, Made::Pinned, 0), - ], - ), - ( - "after-managed", - &[ - Pair(StorageMode::Managed, Made::New, 0), - Pair(StorageMode::Private, Made::New, 0), - Pair(StorageMode::Private, Made::Pinned, 0), - ], - ), - ( - "after-shared", - &[ - Pair(StorageMode::Shared, Made::New, 0), - Pair(StorageMode::Private, Made::New, 0), - Pair(StorageMode::Private, Made::Pinned, 0), - ], - ), - ( - "shared-managed-private", - &[ - Pair(StorageMode::Shared, Made::Pinned, 0), - Pair(StorageMode::Managed, Made::Pinned, 0), - Pair(StorageMode::Private, Made::Pinned, 0), - ], - ), - // As a guest's buffers come: `Shared` and `Managed` ones over its pages with bit 20, as its - // no-copy calls pass it, then `Private` ones at its addresses, of its plain options. - ( - "no-copy-then-private", - &[ - Pair(StorageMode::Shared, Made::NoCopy, BIT_20), - Pair(StorageMode::Managed, Made::NoCopy, BIT_20), - Pair(StorageMode::Private, Made::Pinned, 0), - Pair(StorageMode::Private, Made::Pinned, BIT_20), - ], - ), - // As a guest's Metal buffers come: `Shared` ones over its pages, `Managed` ones with their CPU - // copies over its pages beside them, then `Private` ones at its addresses. - ( - "guest-order", - &[ - Pair(StorageMode::Shared, Made::NoCopy, 0), - Pair(StorageMode::Managed, Made::Beside, 0), - Pair(StorageMode::Private, Made::Pinned, 0), - ], - ), - // No-copy buffers over the bytes of `Shared` ones that are copies of them, and over pages no - // other buffer is made over. - ( - "over-copy", - &[ - Pair(StorageMode::Managed, Made::OverCopy, 0), - Pair(StorageMode::Managed, Made::NoCopy, 0), - Pair(StorageMode::Shared, Made::OverCopy, 0), - Pair(StorageMode::Managed, Made::ReadOnly, 0), - ], - ), -]; - -/// A `Shared` no-copy buffer of `options`' other modes over new pages of the example's own, which -/// it pushes to `pages`. -fn no_copy( - device: &Device, - options: ResourceOptions, - pages: &mut Vec, -) -> common::Result { - let host = Pages::new()?; - // SAFETY: the pages outlive the buffer (`run_pair` drops them after it), and only its - // commands use them. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy(HostMemory::new(host.0), BYTES, options, None) - }?; - pages.push(host); - Ok(buffer) -} - -/// A no-copy buffer of `options` over the bytes of `host`, whose import a gate refuses. -/// -/// # Safety -/// -/// The pages outlive the buffer. -unsafe fn refused( - device: &Device, - options: ResourceOptions, - host: &Pages, -) -> common::Result { - // SAFETY: the caller's contract, and only the example's commands use the pages. - let memory = unsafe { HostMemory::new(host.0) }.with_import_gate(Arc::new(|_| false)); - // SAFETY: as above. - Ok(unsafe { device.new_buffer_with_bytes_no_copy(memory, BYTES, options, None) }?) -} - -/// One buffer of `pair`, the `index`th of its two, over pages it pushes to `pages` where it is a -/// no-copy one, and the buffers beside it pushed to `beside`. -fn make( - device: &Device, - pair: Pair, - index: u64, - (pages, beside): (&mut Vec, &mut Vec), -) -> common::Result { - let options = pair.options(); - let buffer = match pair.1 { - Made::NoCopy => no_copy(device, options, pages)?, - Made::New => device.new_buffer(BYTES, options)?, - Made::Beside => { - let buffer = device.new_buffer(BYTES, options)?; - let shared = ResourceOptions::from_raw( - (options.raw() & !STORAGE_MASK) | ResourceOptions::shared().raw(), - )?; - beside.push(no_copy(device, shared, pages)?); - buffer - } - Made::OverCopy => { - let host = Pages::new()?; - // SAFETY: the pages outlive both buffers (`run_pair` drops them after them). - let copy = unsafe { refused(device, ResourceOptions::shared(), &host) }?; - // SAFETY: as above. - let buffer = unsafe { refused(device, options, &host) }?; - beside.push(copy); - pages.push(host); - buffer - } - Made::ReadOnly => { - let host = Pages::new()?; - host.read_only()?; - // SAFETY: the pages outlive the buffer (`run_pair` drops them after it). - let buffer = unsafe { refused(device, options, &host) }?; - pages.push(host); - buffer - } - Made::Descriptor => device.new_buffer_with_descriptor(BufferDescriptor::new( - BYTES, - options, - BufferContents::Zero, - ))?, - Made::Pinned => { - let at = GpuAddress(PIN_BASE + index * PIN_STEP); - let descriptor = BufferDescriptor::new(BYTES, options, BufferContents::Zero) - .with_placement(AddressPlacement::At(at)); - device.new_buffer_with_descriptor(descriptor)? - } - }; - Ok(buffer) -} - -/// The memory counts the making moved, from `before` to `after` (the module docs). -fn moved(before: &WorkCounts, after: &WorkCounts) -> String { - let (b, a) = (&before.object_churn, &after.object_churn); - let delta = |after: u64, before: u64| after as i64 - before as i64; - format!( - "allocations {} bindings {} dedicated {:+} empty {:+} overflows {}", - delta(a.vk_memory_allocations, b.vk_memory_allocations), - delta(a.vk_buffer_bindings, b.vk_buffer_bindings), - delta( - after.dedicated_memory_blocks_live, - before.dedicated_memory_blocks_live - ), - delta( - after.empty_memory_blocks_live, - before.empty_memory_blocks_live - ), - delta( - after.device_memory_overflows, - before.device_memory_overflows - ), - ) -} - -/// Every `WorkCounts` field that moved from `before` to `after`, as `after` names it: the lines -/// of the two counts' debug forms that differ. -fn changed(before: &WorkCounts, after: &WorkCounts) -> String { - let (before, after) = (format!("{before:#?}"), format!("{after:#?}")); - let lines: Vec<&str> = (before.lines().zip(after.lines())) - .filter(|(was, now)| was != now) - .map(|(_, now)| now.trim().trim_end_matches(',')) - .collect(); - lines.join(" ") -} - -/// One command buffer of the kernel from `input` to `output`: its commit's time since the Unix -/// epoch, in milliseconds, and its wall time from commit to its wait's end and its GPU time, in -/// seconds. -fn pass( - queue: &CommandQueue, - state: &ComputePipelineState, - input: &Buffer, - output: &Buffer, -) -> common::Result<(u128, f64, f64)> { - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.compute_command_encoder()?; - encoder.set_compute_pipeline_state(state)?; - encoder.set_buffer(Some(input), 0, 0)?; - encoder.set_buffer(Some(output), 0, 1)?; - encoder.set_bytes(&1.0f32.to_le_bytes(), 2)?; - encoder.dispatch_threads(Size::new(COUNT, 1, 1), Size::new(256, 1, 1))?; - encoder.end_encoding()?; - let at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(); - let start = Instant::now(); - common::run(&command_buffer)?; - let wall = start.elapsed().as_secs_f64(); - let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; - Ok((at, wall, gpu)) -} - -/// The floats at the start of an output the check reads. -const CHECKED: u64 = 1024; - -/// Check that `output` holds the kernel's answer for an input of zeros, `output[i] = i`, in its -/// first [`CHECKED`] floats, copied by a blit into a `Shared` buffer the host reads; for a pair -/// over read-only pages, whose GPU writes are dropped, the pages' zeros. -fn check( - device: &Device, - queue: &CommandQueue, - output: &Buffer, - pair: &Pair, -) -> common::Result<()> { - let read = device.new_buffer(CHECKED * 4, ResourceOptions::shared())?; - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_buffer_to_buffer(output, 0, &read, 0, CHECKED * 4)?; - blit.end_encoding()?; - common::run(&command_buffer)?; - let bytes = common::bytes(&read)?; - let dropped = matches!(pair.1, Made::ReadOnly); - for (i, value) in bytes.as_chunks::<4>().0.iter().enumerate() { - let value = f32::from_le_bytes(*value); - let expected = if dropped { 0.0 } else { i as f32 }; - if value != expected { - let name = pair.name(); - return Err(format!("{name}: output[{i}] is {value}, not {expected}").into()); - } - } - Ok(()) -} - -/// The median of `seconds` as GB/s, read plus written. -fn rate(mut seconds: Vec) -> f64 { - seconds.sort_by(f64::total_cmp); - 2.0 * BYTES as f64 / seconds[seconds.len() / 2] / 1e9 -} - -/// Run `pair` on `device`: made, filled, then timed. -fn run_pair( - device: &Device, - (queue, state): (&CommandQueue, &ComputePipelineState), - sequence: &str, - pair: Pair, -) -> common::Result<()> { - // Before the buffers: dropped after them. - let (mut pages, mut beside) = (Vec::new(), Vec::new()); - let before = device.work_counts(); - let input = make(device, pair, 0, (&mut pages, &mut beside))?; - let output = make(device, pair, 1, (&mut pages, &mut beside))?; - let made = moved(&before, &device.work_counts()); - let made = format!("{made} backing {:?}", input.host_backing()); - let command_buffer = queue.command_buffer()?; - let mut blit = command_buffer.blit_command_encoder()?; - blit.fill_buffer(&input, 0..BYTES, 0)?; - blit.fill_buffer(&output, 0..BYTES, 0)?; - blit.end_encoding()?; - common::run(&command_buffer)?; - for round in 0..ROUNDS { - let (mut walls, mut gpus, mut passes) = (Vec::new(), Vec::new(), Vec::new()); - let mut counts = Vec::new(); - for index in 0..PASSES { - let before = device.work_counts(); - let (at, wall, gpu) = pass(queue, state, &input, &output)?; - passes.push(format!("{at}:{:.2}/{:.2}", wall * 1e3, gpu * 1e3)); - if index >= PASSES - TIMED { - walls.push(wall); - gpus.push(gpu); - } - if index == PASSES - TIMED || index == PASSES - 1 { - counts.push((index, changed(&before, &device.work_counts()))); - } - } - check(device, queue, &output, &pair)?; - let name = pair.name(); - for (index, moved) in counts { - println!("COUNTS {sequence} {name} round {round} pass {index}: {moved}"); - } - println!( - "BANDWIDTH {sequence} {name} round {round} wall {:.1} gpu {:.1} made: {made} {}", - rate(walls), - rate(gpus), - device.name() - ); - println!( - "PASSES {sequence} {name} round {round} at-ms:wall/gpu-ms: {}", - passes.join(" ") - ); - } - Ok(()) -} - -fn main() -> common::Result<()> { - for (sequence, pairs) in SEQUENCES { - // A device of its own: the last sequence's went with its last handle. - let device = Device::system_default()?; - let unified = device.properties().has_unified_memory; - println!( - "sequence {sequence}: {} (unified memory: {unified})", - device.name() - ); - let library = common::library(&device)?; - let function = library.new_function_with_name("scale_and_offset")?; - let state = device - .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?; - let queue = device.new_command_queue()?; - for &pair in pairs { - std::thread::sleep(PAUSE); - run_pair(&device, (&queue, &state), sequence, pair)?; - } - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/queue_plan_cost.rs b/crates/metal2vulkan-runtime/examples/queue_plan_cost.rs deleted file mode 100644 index 7ec128e9b..000000000 --- a/crates/metal2vulkan-runtime/examples/queue_plan_cost.rs +++ /dev/null @@ -1,938 +0,0 @@ -//! Not a consumer's example: what a device's `VkQueue`s cost the driver, by how many it takes, on -//! the first discrete GPU (else integrated, virtual or CPU device) the loader lists. The runtime's -//! queue plan (`src/device/create.rs`'s `queue_plan`) takes up to 16 queues of the graphics family -//! (its round robin and two for presenting) and two of a family of transfers alone (the staging -//! and fill queues), where the device has them; `DeviceOptions::queue_limits` takes fewer. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example queue_plan_cost -- \ -//! [--rounds R] [--hold H] [--runtime] [--exhaust PROCESSES] [--exhaust-only] \ -//! [--fills N,M,...] -//! ``` -//! -//! Each shape is a count of graphics-family queues and of copy-family queues (none where the -//! device has no family of transfers alone): 1 + 0, 1 + 2 (the least plan's), 2 + 2, 4 + 2, -//! 8 + 2 and the graphics family's count + 2 (the plan's, 16 + 2 on NVIDIA). It prints -//! `QUEUE-PLAN-COST` lines: -//! -//! - **make**: `R` rounds (5 by default), each making and destroying one device of each shape in -//! turn, through Vulkan alone (no extension, no feature): `vkCreateDevice` and -//! `vkDestroyDevice` wall times, median, least and most per shape, and the slope per queue. -//! - **hold**: `H` devices of each shape held at once (4 by default), with the GPU's memory in use -//! before and while they live, as `nvidia-smi` reports it where it runs (framebuffer and BAR1 -//! used, MiB), and that over `H` per device. -//! - **runtime** (`--runtime`): the runtime's own device of each queue limit (round robin 1, 2, 4, -//! 8 and the plan's, presenting 0 or 2), `Device::system_default_with` and its drop, after one -//! device of each not counted: what the queues add to a device the runtime makes. -//! - **exhaust** (`--exhaust P`, opt-in: it runs the GPU out of what its devices need, which the -//! driver logs, such as NVIDIA's `NV_ERR_NO_MEMORY` from `kchannelAllocMem`): for the plan's -//! shape and the least plan's, up to `P` processes, started one after another, each making -//! devices of the shape until the driver refuses one or it holds 6, all held until the last -//! process is done: how many devices, and so `VkQueue`s, the GPU held at once, and each -//! refusal's `VkResult`. While they are held, one more process makes the runtime's own device -//! (`Device::system_default_with`, the plan): whether it came up (on its least plan where the -//! driver refused the plan, which it announces) or what it answered. -//! `--exhaust-only` skips the make and hold phases. -//! - **fills** (`--fills N,M,...`): for each count, that many devices of the least plan's shape -//! held at once, then the runtime's device made beside them, as above: what the runtime's -//! device making answers where the plan's `vkCreateDevice` still fits but little more does. -//! - **rooms** (`--rooms SPEC,...`, opt-in as the exhaust phase is): for each `SPEC`, `K+N` (or -//! `N`, K of 0), K devices of the plan's shape and N of the least plan's held at once, then one -//! more process asks for a device of every graphics-family count from the plan's down to one -//! (the copy family's queues kept), each made and destroyed at once where the driver makes it: -//! which counts the driver accepts beside what is held, and how long each `vkCreateDevice` -//! took, refused or made. -//! - **overlap** (`--overlap K,...`): for the plan's shape, two between (round robins of 7 and 3 -//! with the two presenting) and the least plan's (16 + 2, 9 + 2, 5 + 2 and 1 + 2 on NVIDIA), K -//! processes each making one device at the same moment, `R` rounds (`--rounds`, 3 by default): -//! each `vkCreateDevice`'s time, median, least and most, and the time until all K were made, as -//! when every device of a GPU is made again at once (a device lost). -//! - **runtime rooms** (`--runtime-rooms N,...`, opt-in as the exhaust phase is): as the rooms -//! phase, beside N of the runtime's own devices (as the runtime fill phase makes them) instead -//! of bare ones: a runtime device holds more of what the driver gives than a bare device of its -//! queues. -//! - **runtime fill** (`--runtime-fill P`, opt-in as the exhaust phase is): up to `P` processes, -//! started one after another, each making the runtime's own devices (the plan, each of its own -//! options, so not one device returned again) until one is refused or it holds 6, all held -//! until the last is done: each device's make time and the `VkQueue`s it took (the plan's, or -//! what its `least-queue-plan` notice says), as the GPU fills. - -use ash::vk; -use std::io::{BufRead, BufReader, Read, Write}; -use std::process::{Child, Command, Stdio}; -use std::time::{Duration, Instant}; - -/// The most devices one process of the exhaust phase makes: NVIDIA's driver refused one -/// process's eighth device on an RTX 2080 and an RTX 3090 whatever its queues. -const PER_PROCESS: usize = 6; - -/// A shape: queues of the graphics family, and of the copy family. -type Shape = (u32, u32); - -struct Gpu { - _entry: ash::Entry, - instance: ash::Instance, - physical: vk::PhysicalDevice, - name: String, - driver: String, - graphics: u32, - graphics_count: u32, - copy: Option<(u32, u32)>, -} - -impl Gpu { - fn new() -> Gpu { - // SAFETY: loading the Vulkan loader runs its initialization; nothing else is assumed. - let entry = unsafe { ash::Entry::load() }.expect("the Vulkan loader"); - let application = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_2); - let info = vk::InstanceCreateInfo::default().application_info(&application); - // SAFETY: `info` and what it points at live for the call. - let instance = unsafe { entry.create_instance(&info, None) }.expect("an instance"); - // SAFETY: the instance is live. - let physicals = unsafe { instance.enumerate_physical_devices() }.expect("devices"); - let types = [ - vk::PhysicalDeviceType::DISCRETE_GPU, - vk::PhysicalDeviceType::INTEGRATED_GPU, - vk::PhysicalDeviceType::VIRTUAL_GPU, - vk::PhysicalDeviceType::CPU, - ]; - // SAFETY: each is the instance's. - let kind = |physical: vk::PhysicalDevice| unsafe { - instance - .get_physical_device_properties(physical) - .device_type - }; - let physical = (types.iter()) - .find_map(|&wanted| physicals.iter().copied().find(|&p| kind(p) == wanted)) - .expect("a device"); - let mut driver = vk::PhysicalDeviceDriverProperties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut driver); - // SAFETY: the instance's; Vulkan 1.1's command. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - let name = (properties.properties.device_name_as_c_str()) - .map_or("?".to_owned(), |name| name.to_string_lossy().into_owned()); - let driver = (driver.driver_info_as_c_str()) - .map_or("?".to_owned(), |info| info.to_string_lossy().into_owned()); - // SAFETY: the instance's. - let families = unsafe { instance.get_physical_device_queue_family_properties(physical) }; - let wanted = vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE; - let graphics = (families.iter()) - .position(|family| family.queue_flags.contains(wanted) && family.queue_count > 0) - .expect("a family of graphics and compute work"); - let besides = - vk::QueueFlags::TRANSFER | vk::QueueFlags::SPARSE_BINDING | vk::QueueFlags::PROTECTED; - let copy = (families.iter().enumerate()).find(|(index, family)| { - *index != graphics - && family.queue_count > 0 - && family.queue_flags.contains(vk::QueueFlags::TRANSFER) - && (family.queue_flags & !besides).is_empty() - }); - Gpu { - _entry: entry, - name, - driver, - graphics: graphics as u32, - graphics_count: families[graphics].queue_count, - copy: copy.map(|(index, family)| (index as u32, family.queue_count)), - instance, - physical, - } - } - - /// The shapes the phases take (the module docs), the plan's last. - fn shapes(&self) -> Vec { - let copies = self.copy.map_or(0, |(_, count)| count.min(2)); - let mut shapes = vec![(1, 0)]; - for graphics in [1, 2, 4, 8] { - if graphics <= self.graphics_count && !shapes.contains(&(graphics, copies)) { - shapes.push((graphics, copies)); - } - } - let plan = (self.graphics_count.min(16), copies); - if !shapes.contains(&plan) { - shapes.push(plan); - } - shapes - } - - /// The least plan's shape and the plan's (the module docs). - fn least_and_plan(&self) -> [Shape; 2] { - let copies = self.copy.map_or(0, |(_, count)| count.min(2)); - [(1, copies), (self.graphics_count.min(16), copies)] - } - - /// A device of `shape`, and how long `vkCreateDevice` took; the driver's answer where it - /// refused it. - fn make(&self, (graphics, copies): Shape) -> Result<(ash::Device, Duration), vk::Result> { - let priorities = vec![1.0f32; graphics.max(copies) as usize]; - let mut infos = vec![vk::DeviceQueueCreateInfo::default() - .queue_family_index(self.graphics) - .queue_priorities(&priorities[..graphics as usize])]; - if let (Some((family, _)), true) = (self.copy, copies > 0) { - infos.push( - vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities[..copies as usize]), - ); - } - let info = vk::DeviceCreateInfo::default().queue_create_infos(&infos); - let start = Instant::now(); - // SAFETY: `info` and what it points at live for the call; `physical` is the instance's. - let device = unsafe { self.instance.create_device(self.physical, &info, None) }?; - Ok((device, start.elapsed())) - } -} - -/// Destroy `device`, and how long it took. -fn destroy(device: ash::Device) -> Duration { - let start = Instant::now(); - // SAFETY: nothing of the device is in use: it made nothing. - unsafe { device.destroy_device(None) }; - start.elapsed() -} - -fn ms(duration: Duration) -> f64 { - duration.as_secs_f64() * 1e3 -} - -/// The median, least and most of `times`, in milliseconds. -fn spread(times: &mut [f64]) -> (f64, f64, f64) { - times.sort_by(f64::total_cmp); - (times[times.len() / 2], times[0], times[times.len() - 1]) -} - -/// The least-squares slope of `points` (x, y). -fn slope(points: &[(f64, f64)]) -> f64 { - let n = points.len() as f64; - let (sx, sy) = points - .iter() - .fold((0.0, 0.0), |(sx, sy), (x, y)| (sx + x, sy + y)); - let (mx, my) = (sx / n, sy / n); - let (num, den) = points.iter().fold((0.0, 0.0), |(num, den), (x, y)| { - (num + (x - mx) * (y - my), den + (x - mx) * (x - mx)) - }); - num / den -} - -/// The GPU's framebuffer and BAR1 memory in use, MiB, as `nvidia-smi` reports them for its first -/// GPU; `None` where it does not run. -fn smi_memory() -> Option<(u64, u64)> { - let output = Command::new("nvidia-smi") - .args(["-i", "0", "-q", "-d", "MEMORY"]) - .output() - .ok()?; - let text = String::from_utf8_lossy(&output.stdout); - let mut section = ""; - let (mut fb, mut bar1) = (None, None); - for line in text.lines() { - let trimmed = line.trim(); - if trimmed.ends_with("Memory Usage") { - section = trimmed; - } - if let Some(value) = trimmed.strip_prefix("Used") { - let mib = value - .trim_start_matches([' ', ':']) - .trim_end_matches(" MiB") - .parse::() - .ok(); - match section { - "FB Memory Usage" => fb = mib, - "BAR1 Memory Usage" => bar1 = mib, - _ => {} - } - } - } - Some((fb?, bar1?)) -} - -fn queues((graphics, copies): Shape) -> u32 { - graphics + copies -} - -fn make_phase(gpu: &Gpu, rounds: usize) { - let shapes = gpu.shapes(); - let mut made: Vec> = vec![Vec::new(); shapes.len()]; - let mut dropped: Vec> = vec![Vec::new(); shapes.len()]; - // One device of each first, not counted: the driver's first device loads what later ones - // share. - for &shape in &shapes { - if let Ok((device, _)) = gpu.make(shape) { - destroy(device); - } - } - for _ in 0..rounds { - for (at, &shape) in shapes.iter().enumerate() { - match gpu.make(shape) { - Ok((device, took)) => { - made[at].push(ms(took)); - dropped[at].push(ms(destroy(device))); - } - Err(result) => println!("QUEUE-PLAN-COST make {shape:?} refused: {result:?}"), - } - } - } - let mut made_points = Vec::new(); - let mut dropped_points = Vec::new(); - for (at, &shape) in shapes.iter().enumerate() { - if made[at].is_empty() { - continue; - } - let (m50, mlo, mhi) = spread(&mut made[at]); - let (d50, dlo, dhi) = spread(&mut dropped[at]); - let count = queues(shape); - made_points.push((count as f64, m50)); - dropped_points.push((count as f64, d50)); - println!( - "QUEUE-PLAN-COST make {}+{} = {count} queues: create median {m50:.1} ms ({mlo:.1} to \ - {mhi:.1}), destroy median {d50:.1} ms ({dlo:.1} to {dhi:.1}), {} rounds", - shape.0, - shape.1, - made[at].len() - ); - } - if made_points.len() > 1 { - println!( - "QUEUE-PLAN-COST make slope: create {:.2} ms a queue, destroy {:.2} ms a queue", - slope(&made_points), - slope(&dropped_points) - ); - } -} - -fn hold_phase(gpu: &Gpu, hold: usize) { - let settle = || std::thread::sleep(Duration::from_millis(500)); - settle(); - let Some(base) = smi_memory() else { - println!("QUEUE-PLAN-COST hold: no nvidia-smi, no memory read"); - return; - }; - println!( - "QUEUE-PLAN-COST hold base: fb {} MiB, bar1 {} MiB", - base.0, base.1 - ); - let mut points = Vec::new(); - for shape in gpu.shapes() { - let mut devices = Vec::new(); - for _ in 0..hold { - match gpu.make(shape) { - Ok((device, _)) => devices.push(device), - Err(result) => { - println!("QUEUE-PLAN-COST hold {shape:?} refused: {result:?}"); - break; - } - } - } - settle(); - let held = smi_memory().unwrap_or(base); - let count = devices.len(); - for device in devices { - destroy(device); - } - settle(); - let after = smi_memory().unwrap_or(base); - let per = |used: u64, base: u64| (used as f64 - base as f64) / count.max(1) as f64; - println!( - "QUEUE-PLAN-COST hold {}+{} = {} queues x {count} devices: fb {} MiB, bar1 {} MiB \ - (after: fb {}, bar1 {}): per device fb {:.1} MiB, bar1 {:.1} MiB", - shape.0, - shape.1, - queues(shape), - held.0, - held.1, - after.0, - after.1, - per(held.0, base.0), - per(held.1, base.1) - ); - points.push(( - queues(shape) as f64, - per(held.0, base.0), - per(held.1, base.1), - )); - } - if points.len() > 1 { - let fb: Vec<(f64, f64)> = points.iter().map(|&(q, fb, _)| (q, fb)).collect(); - let bar1: Vec<(f64, f64)> = points.iter().map(|&(q, _, bar1)| (q, bar1)).collect(); - println!( - "QUEUE-PLAN-COST hold slope: fb {:.3} MiB a queue, bar1 {:.3} MiB a queue", - slope(&fb), - slope(&bar1) - ); - } -} - -fn runtime_phase() { - use metal2vulkan_runtime::{Device, DeviceKind, DeviceOptions, QueueLimits}; - let cache = std::env::temp_dir().join(format!("queue-plan-cost-{}", std::process::id())); - let limits: Vec> = [1, 2, 4, 8] - .iter() - .flat_map(|&round_robin| { - [0, 2].map(|presenting| { - Some(QueueLimits { - round_robin, - presenting, - }) - }) - }) - .chain([None]) - .collect(); - let options = |queue_limits: Option| { - let mut options = DeviceOptions::default(); - options.kinds = vec![DeviceKind::Discrete, DeviceKind::Integrated]; - options.shader_cache = - metal2vulkan_runtime::ShaderCacheOptions::in_directory(cache.clone()); - options.queue_limits = queue_limits; - options - }; - let mut made: Vec> = vec![Vec::new(); limits.len()]; - let mut dropped: Vec> = vec![Vec::new(); limits.len()]; - for round in 0..4 { - for (at, &limit) in limits.iter().enumerate() { - let start = Instant::now(); - let device = Device::system_default_with(&options(limit)).expect("a device"); - let took = start.elapsed(); - let start = Instant::now(); - drop(device); - let gone = start.elapsed(); - if round > 0 { - made[at].push(ms(took)); - dropped[at].push(ms(gone)); - } - } - } - for (at, limit) in limits.iter().enumerate() { - let (m50, mlo, mhi) = spread(&mut made[at]); - let (d50, dlo, dhi) = spread(&mut dropped[at]); - let name = match limit { - Some(limit) => format!( - "round robin {} presenting {}", - limit.round_robin, limit.presenting - ), - None => "the plan".to_owned(), - }; - println!( - "QUEUE-PLAN-COST runtime {name}: make median {m50:.1} ms ({mlo:.1} to {mhi:.1}), \ - drop median {d50:.1} ms ({dlo:.1} to {dhi:.1}), {} rounds", - made[at].len() - ); - } - let _ = std::fs::remove_dir_all(&cache); -} - -/// A child of the exhaust phase: make devices of `shape` until refused or `most` (at most -/// [`PER_PROCESS`]), say how many (`HOLDING n`), hold them until stdin closes. -fn child(gpu: &Gpu, shape: Shape, most: usize) { - let mut devices = Vec::new(); - let mut refusal = None; - while devices.len() < most.min(PER_PROCESS) { - match gpu.make(shape) { - Ok((device, _)) => devices.push(device), - Err(result) => { - refusal = Some(result); - break; - } - } - } - println!("HOLDING {} {refusal:?}", devices.len()); - std::io::stdout().flush().ok(); - let mut rest = Vec::new(); - std::io::stdin().read_to_end(&mut rest).ok(); - for device in devices { - destroy(device); - } -} - -fn exhaust_phase(gpu: &Gpu, processes: usize) { - for shape in gpu.least_and_plan() { - held_beside_runtime(shape, processes, usize::MAX); - } -} - -/// The fill phase (`--fills N,M,...`): for each count, that many devices of the least plan's -/// shape held at once (or as many as the driver gives), then the runtime's own device made -/// beside them, as the exhaust phase makes it: where the plan's `vkCreateDevice` still fits but -/// little else does. -fn fill_phase(gpu: &Gpu, fills: &[usize]) { - for &fill in fills { - held_beside_runtime( - gpu.least_and_plan()[0], - fill.div_ceil(PER_PROCESS) + 1, - fill, - ); - } -} - -/// Devices held by child processes: the children, holding theirs until their stdin closes; how -/// many devices; each child's first line, and each child's count, `r(...)` naming a refusal. -struct Held { - children: Vec, - devices: usize, - lines: Vec, - counts: Vec, -} - -impl Held { - /// Up to `processes` processes, started one after another, each making devices of `shape` - /// until refused or 6, `most` in all. - fn of(shape: Shape, processes: usize, most: usize) -> Held { - let (graphics, copies) = (shape.0.to_string(), shape.1.to_string()); - Held::spawned(processes, most, |left| { - vec!["--child".into(), graphics.clone(), copies.clone(), left] - }) - } - - /// Up to `processes` processes, started one after another, each making the runtime's own - /// devices until one is refused or it holds 6, `most` in all (`--runtime-fill-child`). - fn runtime(processes: usize, most: usize) -> Held { - Held::spawned(processes, most, |left| { - vec!["--runtime-fill-child".into(), left] - }) - } - - /// Up to `processes` children run with `args` of the devices left to make, started one after - /// another until `most` are held or one makes none; each says how many it holds in its first - /// line's second word. - fn spawned(processes: usize, most: usize, args: impl Fn(String) -> Vec) -> Held { - let exe = std::env::current_exe().expect("this program"); - let mut held = Held { - children: Vec::new(), - devices: 0, - lines: Vec::new(), - counts: Vec::new(), - }; - for _ in 0..processes { - if held.devices >= most { - break; - } - let mut child = Command::new(&exe) - .args(args((most - held.devices).to_string())) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("a child"); - let stdout = child.stdout.take().expect("its stdout"); - let mut line = String::new(); - BufReader::new(stdout).read_line(&mut line).ok(); - let made: usize = (line.split_whitespace().nth(1)) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - // The refusal's `VkResult`, where the child's line names one (`Some(ERROR_...)`). - let refusal = (line.split_once("Some(")) - .and_then(|(_, rest)| rest.split_once(')')) - .map(|(code, _)| code.to_owned()); - held.counts.push(match refusal { - Some(code) => format!("{made}r({code})"), - None => made.to_string(), - }); - held.lines.push(line.trim().to_owned()); - held.devices += made; - held.children.push(child); - if made == 0 { - break; - } - } - held - } - - /// Close each child's stdin and wait for it: its devices destroyed. - fn release(self) { - for mut child in self.children { - drop(child.stdin.take()); - child.wait().ok(); - } - } -} - -/// The rooms phase (`--rooms SPEC,...`, the module docs). -fn rooms_phase(gpu: &Gpu, specs: &[(usize, usize)]) { - let [least, plan] = gpu.least_and_plan(); - let exe = std::env::current_exe().expect("this program"); - for &(plans, leasts) in specs { - let first = Held::of(plan, plans.div_ceil(PER_PROCESS) + 1, plans); - let second = Held::of(least, leasts.div_ceil(PER_PROCESS) + 1, leasts); - let vk_queues = - first.devices * queues(plan) as usize + second.devices * queues(least) as usize; - let probe = Command::new(&exe) - .arg("--probe-child") - .output() - .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned()) - .unwrap_or_else(|error| format!("not run: {error}")); - println!( - "QUEUE-PLAN-COST room beside {} of {}+{} [{}] and {} of {}+{} [{}] ({vk_queues} \ - VkQueues held): {probe}", - first.devices, - plan.0, - plan.1, - first.counts.join(" "), - second.devices, - least.0, - least.1, - second.counts.join(" ") - ); - second.release(); - first.release(); - std::thread::sleep(Duration::from_secs(2)); - } -} - -/// The rooms phase's probe: a device of each graphics-family count from the plan's down to one, -/// the copy family's queues kept, each destroyed at once where made; one line, the most queues -/// the driver made, each attempt (`g+c:ok|ERROR_...:ms`), and the made attempts' create time a -/// queue. -fn probe_child(gpu: &Gpu) { - let [(_, copies), (most, _)] = gpu.least_and_plan(); - let mut attempts = Vec::new(); - let mut made = Vec::new(); - let mut largest = None; - for graphics in (1..=most).rev() { - let shape = (graphics, copies); - let start = Instant::now(); - let answer = gpu.make(shape); - let took = ms(start.elapsed()); - let what = match answer { - Ok((device, _)) => { - destroy(device); - made.push((queues(shape) as f64, took)); - largest.get_or_insert(queues(shape)); - "ok".to_owned() - } - Err(result) => format!("{result:?}"), - }; - attempts.push(format!("{graphics}+{copies}:{what}:{took:.1}")); - } - let per = match made.len() > 1 { - true => format!("{:.2}", slope(&made)), - false => "-".to_owned(), - }; - println!( - "most made {largest:?} queues; attempts {}; made create {per} ms a queue", - attempts.join(" ") - ); -} - -/// The runtime fill phase (`--runtime-fill P`, the module docs). -fn runtime_fill_phase(processes: usize) { - let held = Held::runtime(processes, usize::MAX); - let mut devices = 0; - for (at, line) in held.lines.iter().enumerate() { - let made: usize = (line.split_whitespace().nth(1)) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - devices += made; - println!("QUEUE-PLAN-COST runtime fill process {at} ({devices} devices held): {line}"); - } - held.release(); -} - -/// The runtime rooms phase (`--runtime-rooms N,...`, the module docs). -fn runtime_rooms_phase(counts: &[usize]) { - let exe = std::env::current_exe().expect("this program"); - for &count in counts { - let held = Held::runtime(count.div_ceil(PER_PROCESS) + 1, count); - let probe = Command::new(&exe) - .arg("--probe-child") - .output() - .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned()) - .unwrap_or_else(|error| format!("not run: {error}")); - println!( - "QUEUE-PLAN-COST runtime room beside {} runtime devices [{}]: {probe}", - held.devices, - held.lines.join(" || ") - ); - held.release(); - std::thread::sleep(Duration::from_secs(2)); - } -} - -/// The runtime fill phase's child: the runtime's own devices (the plan), each of its own options -/// (a shader cache directory of its own, so not the device the last call made), until one is -/// refused or it holds `most` (at most [`PER_PROCESS`]), held until stdin closes; one line, -/// `RTFILL n`, then each device's make time and what it took (`plan`, or its `least-queue-plan` -/// notice's reason), and the refusal. -fn runtime_fill_child(most: usize) { - use metal2vulkan_runtime::{Degradation, Device, DeviceKind, DeviceOptions, MessageSink}; - use std::sync::{Arc, Mutex}; - let cache = std::env::temp_dir().join(format!("queue-plan-cost-{}", std::process::id())); - let heard: Arc>> = Arc::default(); - let mut options = DeviceOptions::default(); - options.kinds = vec![DeviceKind::Discrete, DeviceKind::Integrated]; - let sink = Arc::clone(&heard); - options.messages = Some(MessageSink::new(move |message| { - if let Some(notice) = &message.degradation { - if notice.degradation == Degradation::LeastQueuePlan { - *sink.lock().unwrap() = Some(notice.reason.clone()); - } - } - })); - let mut devices = Vec::new(); - let mut each = Vec::new(); - let mut refusal = None; - while devices.len() < most.min(PER_PROCESS) { - *heard.lock().unwrap() = None; - let directory = cache.join(devices.len().to_string()); - options.shader_cache = metal2vulkan_runtime::ShaderCacheOptions::in_directory(directory); - let start = Instant::now(); - let made = Device::system_default_with(&options); - let took = ms(start.elapsed()); - match made { - Ok(device) => { - let what = heard.lock().unwrap().take(); - each.push(format!("{took:.0}ms:{}", what.as_deref().unwrap_or("plan"))); - devices.push(device); - } - Err(error) => { - refusal = Some(format!("{took:.0}ms:{error}")); - break; - } - } - } - println!( - "RTFILL {} [{}] refused {refusal:?}", - devices.len(), - each.join(" | ") - ); - std::io::stdout().flush().ok(); - let mut rest = Vec::new(); - std::io::stdin().read_to_end(&mut rest).ok(); - drop(devices); - let _ = std::fs::remove_dir_all(&cache); -} - -/// Up to `processes` processes, started one after another, each making devices of `shape` until -/// refused or 6, `most` in all, held while one more makes the runtime's own device; printed. -fn held_beside_runtime(shape: Shape, processes: usize, most: usize) { - let exe = std::env::current_exe().expect("this program"); - let held = Held::of(shape, processes, most); - let memory = smi_memory(); - let runtime = Command::new(&exe) - .arg("--runtime-child") - // Its notices (the least plan's among them) go to this one's stderr. - .stderr(Stdio::inherit()) - .output() - .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned()) - .unwrap_or_else(|error| format!("not run: {error}")); - let (devices, counts) = (held.devices, held.counts.join(" ")); - let processes = held.children.len(); - held.release(); - println!( - "QUEUE-PLAN-COST exhaust {}+{} = {} queues: {devices} devices ({} VkQueues) held at \ - once by {processes} processes [{counts}] (r: refused), memory then {memory:?}; then \ - the runtime's device: {runtime}", - shape.0, - shape.1, - queues(shape), - devices * queues(shape) as usize, - ); - std::thread::sleep(Duration::from_secs(2)); -} - -/// A child of the exhaust phase made while the others hold their devices: the runtime's own device -/// of the plan, and what it answered (`RUNTIME made` or `RUNTIME refused: ...`). Where it took -/// its least plan it says so on stderr (`metal2vulkan-degrade-least-queue-plan`). -fn runtime_child() { - use metal2vulkan_runtime::{Device, DeviceKind, DeviceOptions}; - let cache = std::env::temp_dir().join(format!("queue-plan-cost-{}", std::process::id())); - let mut options = DeviceOptions::default(); - options.kinds = vec![DeviceKind::Discrete, DeviceKind::Integrated]; - options.shader_cache = metal2vulkan_runtime::ShaderCacheOptions::in_directory(cache.clone()); - match Device::system_default_with(&options) { - Ok(device) => { - println!("RUNTIME made"); - drop(device); - } - Err(error) => println!("RUNTIME refused: {error:?}"), - } - let _ = std::fs::remove_dir_all(&cache); -} - -/// The overlap phase (`--overlap K,...`, the module docs): for each of its shapes and each count, -/// `rounds` rounds of that many processes making one device each at once. -fn overlap_phase(gpu: &Gpu, counts: &[usize], rounds: usize) { - let exe = std::env::current_exe().expect("this program"); - let [(_, copies), (most, _)] = gpu.least_and_plan(); - // The plan's (16 graphics-family queues on NVIDIA: 14 round robin and 2 presenting), the - // round robins of 7 and 3 with presenting's two, and the least plan's one. - let mut shapes: Vec = vec![(most, copies)]; - for graphics in [9, 5, 1] { - if graphics < most { - shapes.push((graphics, copies)); - } - } - for shape in shapes { - for &count in counts { - let mut each = Vec::new(); - let mut walls = Vec::new(); - let mut refused = Vec::new(); - for _ in 0..rounds { - let mut children: Vec<(Child, BufReader)> = (0..count) - .map(|_| { - let mut child = Command::new(&exe) - .args([ - "--overlap-child", - &shape.0.to_string(), - &shape.1.to_string(), - ]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .expect("a child"); - let mut stdout = BufReader::new(child.stdout.take().expect("stdout")); - let mut ready = String::new(); - stdout.read_line(&mut ready).ok(); - (child, stdout) - }) - .collect(); - let start = Instant::now(); - for (child, _) in &mut children { - let stdin = child.stdin.as_mut().expect("stdin"); - stdin.write_all(b"go\n").ok(); - stdin.flush().ok(); - } - for (_, stdout) in &mut children { - let mut line = String::new(); - stdout.read_line(&mut line).ok(); - match line.split_whitespace().collect::>()[..] { - ["MADE", took] => each.push(took.parse::().unwrap_or(f64::NAN)), - _ => refused.push(line.trim().to_owned()), - } - } - walls.push(ms(start.elapsed())); - // Destroyed once all are made, so no destroy overlaps a making. - for (mut child, _) in children { - drop(child.stdin.take()); - child.wait().ok(); - } - } - if each.is_empty() { - println!( - "QUEUE-PLAN-COST overlap {}+{} x{count}: none made {refused:?}", - shape.0, shape.1 - ); - continue; - } - let (m50, mlo, mhi) = spread(&mut each); - let (w50, _, whi) = spread(&mut walls); - println!( - "QUEUE-PLAN-COST overlap {}+{} = {} queues x{count} at once: create median \ - {m50:.1} ms ({mlo:.1} to {mhi:.1}), all made median {w50:.1} ms (most {whi:.1}), \ - {rounds} rounds, refused {refused:?}", - shape.0, - shape.1, - queues(shape) - ); - } - } -} - -/// The overlap phase's child: says `READY` once its instance is made, makes a device of `shape` -/// when a line arrives on stdin, says `MADE ms` (or the refusal) and destroys it once stdin closes. -fn overlap_child(gpu: &Gpu, shape: Shape) { - println!("READY"); - std::io::stdout().flush().ok(); - let mut go = String::new(); - std::io::stdin().read_line(&mut go).ok(); - match gpu.make(shape) { - Ok((device, took)) => { - println!("MADE {:.1}", ms(took)); - std::io::stdout().flush().ok(); - let mut rest = Vec::new(); - std::io::stdin().read_to_end(&mut rest).ok(); - destroy(device); - } - Err(result) => println!("REFUSED {result:?}"), - } -} - -fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if args.first().map(String::as_str) == Some("--runtime-child") { - runtime_child(); - return; - } - if args.first().map(String::as_str) == Some("--runtime-fill-child") { - let most = (args.get(1)).map_or(PER_PROCESS, |most| most.parse().unwrap()); - runtime_fill_child(most); - return; - } - let gpu = Gpu::new(); - if args.first().map(String::as_str) == Some("--child") { - let shape = (args[1].parse().unwrap(), args[2].parse().unwrap()); - let most = (args.get(3)).map_or(PER_PROCESS, |most| most.parse().unwrap()); - child(&gpu, shape, most); - return; - } - if args.first().map(String::as_str) == Some("--probe-child") { - probe_child(&gpu); - return; - } - if args.first().map(String::as_str) == Some("--overlap-child") { - overlap_child(&gpu, (args[1].parse().unwrap(), args[2].parse().unwrap())); - return; - } - let value = |flag: &str| { - (args.iter().position(|arg| arg == flag)) - .and_then(|at| args.get(at + 1)) - .and_then(|value| value.parse::().ok()) - }; - println!( - "QUEUE-PLAN-COST device {} ({}), graphics family {} of {} queues, copy family {:?}", - gpu.name, gpu.driver, gpu.graphics, gpu.graphics_count, gpu.copy - ); - if !args.iter().any(|arg| arg == "--exhaust-only") { - make_phase(&gpu, value("--rounds").unwrap_or(5)); - hold_phase(&gpu, value("--hold").unwrap_or(4)); - } - if args.iter().any(|arg| arg == "--runtime") { - runtime_phase(); - } - if let Some(processes) = value("--exhaust") { - exhaust_phase(&gpu, processes); - } - let fills = (args.iter().position(|arg| arg == "--fills")) - .and_then(|at| args.get(at + 1)) - .map(|list| { - list.split(',') - .filter_map(|n| n.parse().ok()) - .collect::>() - }); - if let Some(fills) = fills { - fill_phase(&gpu, &fills); - } - // Each `K+N` or `N`: K devices of the plan's shape and N of the least plan's. - let rooms = (args.iter().position(|arg| arg == "--rooms")) - .and_then(|at| args.get(at + 1)) - .map(|list| { - (list.split(',')) - .filter_map(|spec| match spec.split_once('+') { - Some((plans, leasts)) => Some((plans.parse().ok()?, leasts.parse().ok()?)), - None => Some((0, spec.parse().ok()?)), - }) - .collect::>() - }); - if let Some(rooms) = rooms { - rooms_phase(&gpu, &rooms); - } - let overlap = (args.iter().position(|arg| arg == "--overlap")) - .and_then(|at| args.get(at + 1)) - .map(|list| { - (list.split(',')) - .filter_map(|n| n.parse().ok()) - .collect::>() - }); - if let Some(counts) = overlap { - overlap_phase(&gpu, &counts, value("--rounds").unwrap_or(3)); - } - let runtime_rooms = (args.iter().position(|arg| arg == "--runtime-rooms")) - .and_then(|at| args.get(at + 1)) - .map(|list| { - (list.split(',')) - .filter_map(|n| n.parse().ok()) - .collect::>() - }); - if let Some(counts) = runtime_rooms { - runtime_rooms_phase(&counts); - } - if let Some(processes) = value("--runtime-fill") { - runtime_fill_phase(processes); - } -} diff --git a/crates/metal2vulkan-runtime/examples/queue_share.rs b/crates/metal2vulkan-runtime/examples/queue_share.rs deleted file mode 100644 index 52310e296..000000000 --- a/crates/metal2vulkan-runtime/examples/queue_share.rs +++ /dev/null @@ -1,1335 +0,0 @@ -//! Not a consumer's example: command queues sharing `VkQueue`s (`QueueSharingPolicy`), each -//! workload run under the policy the arguments name, with the device's sharing counts after it. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example queue_share -- \ -//! [--policy adaptive|per-queue] [--seconds S] [--dispatches N] [--unshared] \ -//! [--threads T --in-flight F [--one-vk-queue]] [--long-ms L] [--period-ms P] \ -//! [--isolation bounded|off] [--turns fair|commit-order] [--fixture PATH] -//! ``` -//! -//! Every command buffer is one of two kinds. A *draw*: a render pass over a 512x512 `RGBA8Unorm` -//! texture, cleared and one triangle drawn (`colored_vertex` and `colored_fragment` of the -//! repository's owned fixture `runtime_examples.metal`, assembled by `llvm-as` on `PATH` from its -//! `.ll`, the repository's or `--fixture`'s, for a binary carried to another tree). A *long* -//! one: `--dispatches` dispatches of `scale_and_offset` over one buffer, sized as the run starts -//! so the command buffer's GPU time is `--long-ms` (30 ms by default). Latencies are a command -//! buffer's `commit` to the start of its completed handler, on the host's clock. -//! -//! - **check**: the device's check of its GPU's idling between `VkQueue`s: its verdict and -//! switch cost (run where no record of it is kept, read back where one is). -//! - **isolation**: a compositor thread commits draws at 4,800 a second and never waits; an -//! application thread commits long command buffers back to back, each waited for. The -//! compositor's latencies, and how many of them are stalls (over 10 ms). `--unshared` makes the -//! compositor's queue with `new_command_queue_unshared`. -//! - **pipelined**: as isolation, but the application keeps two long command buffers in flight, -//! so its queue holds no idle point. -//! - **frames**: a compositor thread commits one draw every `--period-ms` (16 ms by default) and -//! never waits, beside an application thread that keeps `--in-flight` long command buffers in -//! flight (3 by default). The compositor's latencies and how many ran over 16 ms, the -//! application's long command buffers a second, and the device's counts of command buffers that -//! waited behind another queue's batch (`WorkCounts::command_buffers_behind_other_queues` and -//! kin). `--unshared` makes the compositor's queue with `new_command_queue_unshared`; -//! `--isolation` sets `UnsharedIsolationPolicy` (`bounded`, the default, or `off`), and -//! `--turns` sets `QueueTurnPolicy` (`fair`, the default, or `commit-order`): without -//! `--unshared`, the compositor's plain queue and the application's take turns. The -//! application's GPU-busy share is its command buffers' GPU time over the span from its first -//! one's start to its last one's end; the GPU's idle share, that span less every command -//! buffer's GPU time, either queue's. -//! - **pairs**: a game's frames beside a compositor's queue: each frame a long command buffer and -//! then a draw, committed back to back on one queue, `--in-flight` frames in flight, a frame -//! starting once the draw of the frame that many before ran its completed handler; the compositor commits one draw every `--period-ms`, or none at all with -//! `--period-ms 0` (its queue still made first). `--unshared` and `--isolation` as for -//! **frames**. The application's frame period, its GPU time a frame (the long one's GPU start to -//! the draw's GPU end) and the GPU's idle share over its frames; each command buffer's commit to -//! its kernel start (the scheduler's hold), the GPU's gap before each long one, and the draw's GPU -//! end to its completed handler; the device's hold, submission and scheduler counts a frame -//! (`WorkCounts::batch_hold_nanos` and kin), and the first frames one by one. -//! - **trap**: as isolation, but the application alternates 500 ms of draws committed at 10,000 a -//! second with 10 long command buffers. -//! - **alternating**: as trap, with 2 ms of draws between each long command buffer; and -//! **slow-alternating**, 1,500 ms. -//! - **interleave**: two compositor threads, each its own queue, at 4,800 draws a second each; the -//! first's latencies, and the GPU's idle time between command buffers of different queues as a -//! share of the run (from their GPU start and end times, in commit order on the GPU). -//! - **rates**: 2 and 8 threads, each its own queue, committing draws as fast as they can with 3, -//! then 1, in flight a thread: command buffers a second, and the GPU's idle share at switches. -//! With `--threads` and `--in-flight`, that one shape, with each command buffer's GPU end and -//! commit to its completed handler, the device's submission, scheduler and wake counts per -//! command buffer, and the busiest threads' CPU (Linux); `--one-vk-queue` puts every thread's -//! queue on one `VkQueue`, each lent once (`with_vk_queue`) so it never moves. -//! - **idle-queues**: one thread committing draws in turn over 16, then 2,048 queues, 3 in flight: -//! command buffers a second, and the thread's time in `command_buffer` per command buffer. -//! - **churn**: command queues made and dropped as a guest's processes make them (about 350 in a -//! 250 s walk, here `--churn N` over `--seconds`): a compositor thread commits one draw every -//! `--period-ms` (16 ms) and never waits (`--unshared` makes its queue unshared), three kept -//! queues commit a draw every 8 ms each, and every `seconds / N` a new queue is made that commits -//! one long command buffer, then a draw at each later tick, and is dropped 1 to 8 ticks later -//! (a deterministic sequence). `--untimed` makes the device answer GPU times from the host, as a -//! consumer that does so does not share `VkQueue`s. The compositor's latencies, the most queues -//! live at once, and the device's counts of command buffers that waited behind another queue's. - -use metal2vulkan::device::{ - DevicePolicy, QueueSharingPolicy, QueueTurnPolicy, UnsharedIsolationPolicy, -}; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - Buffer, ClearColor, CommandBuffer, CommandQueue, ComputePipelineState, Device, DeviceOptions, - LoadAction, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, Texture, TextureDescriptor, -}; -use std::path::PathBuf; -use std::process::Command; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; - -/// A compositor's latency past which it counts as a stall. -const STALL_MS: f64 = 10.0; - -/// The draws a second of a compositor thread. -const COMPOSITOR_RATE: f64 = 4800.0; - -/// The render target's side, in texels. -const SIDE: u64 = 512; - -/// The floats the long command buffers' buffers hold at most. -const MOST_FLOATS: u64 = 96 << 20; - -struct Options { - mode: String, - policy: QueueSharingPolicy, - isolation: UnsharedIsolationPolicy, - turns: QueueTurnPolicy, - seconds: f64, - dispatches: u64, - unshared: bool, - /// `rates` of this many threads alone (0: the default set). - threads: usize, - in_flight: usize, - /// `rates` with every thread's queue on one `VkQueue`, each lent once so it never moves. - one_vk_queue: bool, - /// A long command buffer's GPU time. - long: Duration, - /// `frames`: the compositor's period between commits. - period: Duration, - /// `churn`: the queues made over the run. - churn: usize, - /// The device answers GPU times from the host (`DeviceOptions::gpu_times_from_host`). - untimed: bool, - /// The fixture's LLVM text: the repository's where `None`. - fixture: Option, -} - -fn options() -> Options { - let mut args = std::env::args().skip(1); - let mut options = Options { - mode: args.next().unwrap_or_else(|| "isolation".to_owned()), - policy: QueueSharingPolicy::Adaptive, - isolation: UnsharedIsolationPolicy::Bounded, - turns: QueueTurnPolicy::Fair, - seconds: 2.0, - dispatches: 300, - unshared: false, - threads: 0, - in_flight: 3, - one_vk_queue: false, - long: Duration::from_millis(30), - period: Duration::from_millis(16), - churn: 340, - untimed: false, - fixture: None, - }; - while let Some(arg) = args.next() { - let mut value = || args.next().unwrap_or_else(|| panic!("{arg} needs a value")); - match arg.as_str() { - "--policy" => { - options.policy = match value().as_str() { - "adaptive" => QueueSharingPolicy::Adaptive, - "per-queue" => QueueSharingPolicy::PerQueue, - other => panic!("no policy {other}"), - } - } - "--isolation" => { - options.isolation = match value().as_str() { - "bounded" => UnsharedIsolationPolicy::Bounded, - "off" => UnsharedIsolationPolicy::Off, - other => panic!("no isolation {other}"), - } - } - "--turns" => { - options.turns = match value().as_str() { - "fair" => QueueTurnPolicy::Fair, - "commit-order" => QueueTurnPolicy::CommitOrder, - other => panic!("no turns {other}"), - } - } - "--seconds" => options.seconds = value().parse().unwrap(), - "--dispatches" => options.dispatches = value().parse().unwrap(), - "--unshared" => options.unshared = true, - "--threads" => options.threads = value().parse().unwrap(), - "--in-flight" => options.in_flight = value().parse().unwrap(), - "--one-vk-queue" => options.one_vk_queue = true, - "--churn" => options.churn = value().parse().unwrap(), - "--untimed" => options.untimed = true, - "--fixture" => options.fixture = Some(PathBuf::from(value())), - "--long-ms" => { - options.long = Duration::from_secs_f64(value().parse::().unwrap() / 1e3) - } - "--period-ms" => { - options.period = Duration::from_secs_f64(value().parse::().unwrap() / 1e3) - } - other => panic!("unknown argument {other}"), - } - } - options -} - -/// What every workload draws and dispatches with. -struct Kit { - device: Device, - draw_state: RenderPipelineState, - positions: Buffer, - colors: Buffer, - compute: ComputePipelineState, - input: Buffer, - output: Buffer, - scale: Buffer, - /// The grid of one long command buffer's dispatches. - grid: u64, - dispatches: u64, - /// The GPU time a long command buffer is sized for. - long_time: Duration, -} - -impl Kit { - fn new(options: &Options) -> Kit { - let device = device(options); - let settled = device.settle_queue_switch_check(Duration::from_secs(10)); - println!( - "device: {}; policy {:?}, isolation {:?}; check settled {settled}: {}", - device.name(), - options.policy, - options.isolation, - device.queue_switch_check_report() - ); - let bitcode = fixture_bitcode(options.fixture.as_deref()); - let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); - let library = device.new_library_with_compile_library(library); - let vertex = library.new_function_with_name("colored_vertex").unwrap(); - let fragment = library.new_function_with_name("colored_fragment").unwrap(); - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let draw_state = device - .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) - .unwrap(); - let positions: Vec = [[-1.0f32, -1.0], [1.0, -1.0], [0.0, 1.0]] - .iter() - .flatten() - .flat_map(|v| v.to_le_bytes()) - .collect(); - let colors: Vec = (0..3) - .flat_map(|_| [1.0f32, 0.5, 0.0, 1.0]) - .flat_map(|v| v.to_le_bytes()) - .collect(); - let positions = device - .new_buffer_with_bytes(&positions, ResourceOptions::shared()) - .unwrap(); - let colors = device - .new_buffer_with_bytes(&colors, ResourceOptions::shared()) - .unwrap(); - let function = library.new_function_with_name("scale_and_offset").unwrap(); - let compute = device - .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) - .unwrap(); - let input = device - .new_buffer(MOST_FLOATS * 4, ResourceOptions::private()) - .unwrap(); - let output = device - .new_buffer(MOST_FLOATS * 4, ResourceOptions::private()) - .unwrap(); - let scale = device - .new_buffer_with_bytes(&1.0f32.to_le_bytes(), ResourceOptions::shared()) - .unwrap(); - let mut kit = Kit { - device, - draw_state, - positions, - colors, - compute, - input, - output, - scale, - grid: 1 << 20, - dispatches: options.dispatches, - long_time: options.long, - }; - kit.size_long(); - kit - } - - /// Size the long command buffers' grid so one's GPU time is `long_time`. - fn size_long(&mut self) { - let queue = self.device.new_command_queue().unwrap(); - for _ in 0..3 { - let command_buffer = self.long(&queue); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed().unwrap(); - let gpu = - command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); - let wanted = self.grid as f64 * self.long_time.as_secs_f64() / gpu.max(1e-6); - self.grid = (wanted as u64).clamp(1 << 16, MOST_FLOATS) & !63; - } - let command_buffer = self.long(&queue); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed().unwrap(); - let gpu = command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); - println!( - "long command buffer: {} dispatches of {} threads, {:.1} ms of GPU time", - self.dispatches, - self.grid, - gpu * 1e3 - ); - } - - /// A long command buffer of `queue`'s, not committed. - fn long(&self, queue: &CommandQueue) -> CommandBuffer { - let command_buffer = queue.command_buffer().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - encoder.set_compute_pipeline_state(&self.compute).unwrap(); - encoder.set_buffer(Some(&self.scale), 0, 2).unwrap(); - for dispatch in 0..self.dispatches { - let (from, to) = match dispatch % 2 { - 0 => (&self.input, &self.output), - _ => (&self.output, &self.input), - }; - encoder.set_buffer(Some(from), 0, 0).unwrap(); - encoder.set_buffer(Some(to), 0, 1).unwrap(); - encoder - .dispatch_threads(Size::new(self.grid, 1, 1), Size::new(64, 1, 1)) - .unwrap(); - } - encoder.end_encoding().unwrap(); - command_buffer - } - - /// A draw command buffer of `queue`'s into `target`, not committed. - fn draw(&self, queue: &CommandQueue, target: &Texture) -> CommandBuffer { - self.draw_into(queue.command_buffer().unwrap(), target) - } - - /// `command_buffer` with a draw into `target` encoded, not committed. - fn draw_into(&self, command_buffer: CommandBuffer, target: &Texture) -> CommandBuffer { - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = LoadAction::Clear; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0); - let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); - encoder.set_render_pipeline_state(&self.draw_state).unwrap(); - encoder - .set_vertex_buffer(Some(&self.positions), 0, 0) - .unwrap(); - encoder.set_vertex_buffer(Some(&self.colors), 0, 1).unwrap(); - encoder - .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) - .unwrap(); - encoder.end_encoding().unwrap(); - command_buffer - } - - fn target(&self) -> Texture { - let mut texture = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); - texture.usage = TextureUsage::RENDER_TARGET; - texture.resource_options = ResourceOptions::private(); - self.device.new_texture(&texture).unwrap() - } - - fn queue(&self, unshared: bool) -> CommandQueue { - match unshared { - true => self.device.new_command_queue_unshared(64).unwrap(), - false => self.device.new_command_queue().unwrap(), - } - } - - fn counts(&self) -> String { - let c = self.device.work_counts(); - format!( - "moves {} joins {} gone long {} settles {} off unshared {} withheld {}", - c.queue_moves, - c.queue_joins, - c.queues_gone_long, - c.long_queue_settles, - c.queue_moves_off_unshared, - c.joins_withheld_from_unshared - ) - } -} - -/// The system default device, of the default policy but for `queue_sharing`, -/// `unshared_isolation` and `queue_turns`, as `options` say. -fn device(options: &Options) -> Device { - let mut device = DeviceOptions::default(); - device.policy = DevicePolicy::UNTRUSTED; - device.policy.queue_sharing = options.policy; - device.policy.unshared_isolation = options.isolation; - device.policy.queue_turns = options.turns; - device.gpu_times_from_host = options.untimed; - Device::system_default_with(&device).unwrap() -} - -/// The owned fixture's LLVM text, at `fixture` where given, assembled to AIR bitcode by `llvm-as`. -fn fixture_bitcode(fixture: Option<&std::path::Path>) -> Vec { - let ll = fixture.map_or_else( - || { - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll") - }, - PathBuf::from, - ); - let output = Command::new("llvm-as") - .arg("-o") - .arg("-") - .arg(&ll) - .output() - .expect("llvm-as on PATH"); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - output.stdout -} - -/// Each draw's queue number and its GPU start and end there, in seconds. -type Times = Arc>>; - -/// A queue's changes of `VkQueue` or long mark: its command buffers made by then, the -/// microseconds into the run, and its `VkQueue` and mark. -type Seen = Vec<(u64, u128, (usize, bool))>; - -/// The p50, p99 and largest of `samples` (milliseconds), and how many are stalls. -fn summary(samples: &mut [f64]) -> String { - if samples.is_empty() { - return "no samples".to_owned(); - } - samples.sort_by(f64::total_cmp); - let at = |p: f64| samples[((samples.len() as f64 * p) as usize).min(samples.len() - 1)]; - let stalls = samples.iter().filter(|&&s| s > STALL_MS).count(); - format!( - "p50 {:.3} p90 {:.3} p99 {:.3} max {:.1} ms, {} stalls over {STALL_MS} ms, {} samples", - at(0.5), - at(0.9), - at(0.99), - samples[samples.len() - 1], - stalls, - samples.len() - ) -} - -/// A thread committing draws on `queue` at `rate` a second until `stop`, never waiting, each -/// draw's latency in `latencies` and, where `times` is given, its queue's number and its GPU start -/// and end there. -fn compositor( - kit: &Arc, - queue: CommandQueue, - rate: f64, - stop: &Arc, - latencies: &Arc>>, - times: Option<(usize, Times)>, -) -> std::thread::JoinHandle<()> { - let kit = Arc::clone(kit); - let stop = Arc::clone(stop); - let latencies = Arc::clone(latencies); - std::thread::spawn(move || { - let target = kit.target(); - let period = Duration::from_secs_f64(1.0 / rate); - let mut next = Instant::now(); - while !stop.load(Ordering::Relaxed) { - let command_buffer = kit.draw(&queue, &target); - let latencies = Arc::clone(&latencies); - let times = times.clone(); - let committed = Arc::new(Mutex::new(Instant::now())); - let at = Arc::clone(&committed); - command_buffer - .add_completed_handler(Box::new(move |done: &CommandBuffer| { - let latency = at.lock().unwrap().elapsed().as_secs_f64() * 1e3; - latencies.lock().unwrap().push(latency); - if let Some((queue, times)) = × { - if let (Ok(start), Ok(end)) = (done.gpu_start_time(), done.gpu_end_time()) { - times.lock().unwrap().push((*queue, start, end)); - } - } - })) - .unwrap(); - *committed.lock().unwrap() = Instant::now(); - command_buffer.commit().unwrap(); - drop(command_buffer); - next += period; - let now = Instant::now(); - match next > now { - true => std::thread::sleep(next - now), - false => next = now, - } - } - }) -} - -/// The application's loop until `stop`, on its own thread: `long_every` long command buffers after -/// each `short` of draws at 10,000 a second (none where `short` is zero), each long one waited for, -/// or with `in_flight` long ones in flight where above 1, each long one's GPU start and end in -/// `times` where given, as queue 0. Answers how many long ones completed. -fn application( - kit: &Arc, - (short, long_every, in_flight): (Duration, usize, usize), - stop: &Arc, - times: Option, -) -> std::thread::JoinHandle { - let kit = Arc::clone(kit); - let stop = Arc::clone(stop); - std::thread::spawn(move || { - let queue = kit.device.new_command_queue().unwrap(); - let target = kit.target(); - let mut flying: std::collections::VecDeque = Default::default(); - let mut longs = 0u64; - while !stop.load(Ordering::Relaxed) { - if !short.is_zero() { - let began = Instant::now(); - let period = Duration::from_secs_f64(1.0 / 10_000.0); - let mut next = began; - while began.elapsed() < short && !stop.load(Ordering::Relaxed) { - let command_buffer = kit.draw(&queue, &target); - command_buffer.commit().unwrap(); - next += period; - let now = Instant::now(); - if next > now { - std::thread::sleep(next - now); - } - } - } - for _ in 0..long_every { - if stop.load(Ordering::Relaxed) { - break; - } - let command_buffer = kit.long(&queue); - if let Some(times) = × { - let times = Arc::clone(times); - command_buffer - .add_completed_handler(Box::new(move |done: &CommandBuffer| { - if let (Ok(start), Ok(end)) = - (done.gpu_start_time(), done.gpu_end_time()) - { - times.lock().unwrap().push((0, start, end)); - } - })) - .unwrap(); - } - command_buffer.commit().unwrap(); - flying.push_back(command_buffer); - while flying.len() >= in_flight.max(1) { - flying.pop_front().unwrap().wait_until_completed().unwrap(); - longs += 1; - } - } - } - for command_buffer in flying { - command_buffer.wait_until_completed().unwrap(); - longs += 1; - } - longs - }) -} - -/// A compositor beside an application of `short` draws between `long_every` long command buffers, -/// `in_flight` of them in flight: the compositor's latencies. -fn beside(kit: &Arc, options: &Options, short: Duration, long_every: usize, in_flight: usize) { - let stop = Arc::new(AtomicBool::new(false)); - let latencies = Arc::new(Mutex::new(Vec::new())); - let app = application(kit, (short, long_every, in_flight), &stop, None); - std::thread::sleep(Duration::from_millis(50)); - let queue = kit.queue(options.unshared); - let comp = compositor(kit, queue, COMPOSITOR_RATE, &stop, &latencies, None); - std::thread::sleep(Duration::from_secs_f64(options.seconds)); - stop.store(true, Ordering::Relaxed); - comp.join().unwrap(); - app.join().unwrap(); - std::thread::sleep(Duration::from_millis(100)); - let mut samples = latencies.lock().unwrap().clone(); - println!( - "{} (policy {:?}, compositor {}, {} dispatches, short {:?} x{} in flight {}): compositor {}; {}", - options.mode, - options.policy, - if options.unshared { "unshared" } else { "shared" }, - kit.dispatches, - short, - long_every, - in_flight, - summary(&mut samples), - kit.counts() - ); -} - -/// A compositor committing one draw every `options.period` beside an application keeping -/// `options.in_flight` long command buffers in flight: the compositor's latencies, the -/// application's long command buffers a second, and the device's counts of waits behind other -/// queues' batches over the run. The compositor's queue is made before the application starts, as -/// a compositor's exists before the applications it shows: other queues' batches are held back -/// only while an unshared queue exists. -fn frames(kit: &Arc, options: &Options) { - let stop = Arc::new(AtomicBool::new(false)); - let latencies = Arc::new(Mutex::new(Vec::new())); - let times: Times = Arc::new(Mutex::new(Vec::new())); - let before = kit.device.work_counts(); - let began = Instant::now(); - let shape = (Duration::ZERO, 1, options.in_flight); - let queue = kit.queue(options.unshared); - let app = application(kit, shape, &stop, Some(Arc::clone(×))); - std::thread::sleep(Duration::from_millis(50)); - let rate = 1.0 / options.period.as_secs_f64(); - let comp = compositor( - kit, - queue, - rate, - &stop, - &latencies, - Some((1, Arc::clone(×))), - ); - std::thread::sleep(Duration::from_secs_f64(options.seconds)); - stop.store(true, Ordering::Relaxed); - comp.join().unwrap(); - let longs = app.join().unwrap(); - let elapsed = began.elapsed().as_secs_f64(); - std::thread::sleep(Duration::from_millis(100)); - let c = kit.device.work_counts(); - let mut samples = latencies.lock().unwrap().clone(); - let over_16 = samples.iter().filter(|&&ms| ms > 16.0).count(); - let unshared_16 = c.unshared_command_buffers_behind_other_queues_over_16ms - - before.unshared_command_buffers_behind_other_queues_over_16ms; - let per_16 = |sum: u64| sum as f64 / unshared_16.max(1) as f64; - let (app_busy, gpu_idle) = busy_shares(×.lock().unwrap()); - let app_spans: Vec = (times.lock().unwrap().iter()) - .filter(|(queue, _, _)| *queue == 0) - .map(|(_, start, end)| end - start) - .collect(); - let app_mean = app_spans.iter().sum::() / app_spans.len().max(1) as f64; - let submissions = c.queue_submissions - before.queue_submissions; - println!( - "frames (policy {:?}, isolation {:?}, turns {:?}, compositor {} every {:?}, application {} in flight of {:.1} ms): compositor {}, {over_16} over 16 ms; application {:.2} long command buffers/s ({:.2} ms of GPU time each), GPU-busy {:.1}%; GPU idle {:.2}%; {:.0} kernel submissions/s; {} looks held a head for isolation, {} for its turn, {} let go on an idle turn", - options.policy, - options.isolation, - options.turns, - if options.unshared { "unshared" } else { "shared" }, - options.period, - options.in_flight, - kit.long_time.as_secs_f64() * 1e3, - summary(&mut samples), - longs as f64 / elapsed, - app_mean * 1e3, - app_busy * 100.0, - gpu_idle * 100.0, - submissions as f64 / elapsed, - c.heads_held_for_unshared_isolation - before.heads_held_for_unshared_isolation, - c.heads_held_for_queue_turns - before.heads_held_for_queue_turns, - c.heads_let_go_turn_idle - before.heads_let_go_turn_idle, - ); - println!( - " behind other queues: {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared waits over 16 ms: {:.2} batches ahead on average, at most {}, longest run {:.1} ms on average, {} behind one run over 16 ms", - c.command_buffers_behind_other_queues - before.command_buffers_behind_other_queues, - c.command_buffers_behind_other_queues_over_16ms - - before.command_buffers_behind_other_queues_over_16ms, - c.command_buffers_behind_other_queues_over_33ms - - before.command_buffers_behind_other_queues_over_33ms, - c.wait_behind_other_queues_longest_nanos as f64 / 1e6, - c.unshared_command_buffers_behind_other_queues - - before.unshared_command_buffers_behind_other_queues, - unshared_16, - c.unshared_command_buffers_behind_other_queues_over_33ms - - before.unshared_command_buffers_behind_other_queues_over_33ms, - c.unshared_wait_behind_other_queues_longest_nanos as f64 / 1e6, - per_16(c.unshared_waits_over_16ms_batches_ahead - before.unshared_waits_over_16ms_batches_ahead), - c.unshared_waits_over_16ms_most_batches_ahead, - per_16( - c.unshared_waits_over_16ms_longest_runs_nanos - - before.unshared_waits_over_16ms_longest_runs_nanos - ) / 1e6, - c.unshared_waits_over_16ms_behind_one_long_run - - before.unshared_waits_over_16ms_behind_one_long_run, - ); -} - -/// One frame of `pairs`, in seconds of `host_time`'s clock: its start once its slot was free; the -/// long command buffer's commit, kernel start, GPU start and GPU end; and the draw's, then its -/// completed handler's start. -#[derive(Clone, Copy, Default)] -struct Pair { - start: f64, - long: [f64; 4], - draw: [f64; 5], -} - -/// The p50 and p90 of `samples` (seconds), in milliseconds. -fn p50_p90(mut samples: Vec) -> String { - if samples.is_empty() { - return "none".to_owned(); - } - samples.sort_by(f64::total_cmp); - let at = |p: f64| samples[((samples.len() as f64 * p) as usize).min(samples.len() - 1)] * 1e3; - format!("p50 {:.2} p90 {:.2}", at(0.5), at(0.9)) -} - -/// The `pairs` mode (the module docs). -fn pairs(kit: &Arc, options: &Options) { - /// The frames before the measured ones. - const WARM: usize = 10; - let stop = Arc::new(AtomicBool::new(false)); - let latencies = Arc::new(Mutex::new(Vec::new())); - let queue = kit.queue(options.unshared); - let comp = (!options.period.is_zero()).then(|| { - let rate = 1.0 / options.period.as_secs_f64(); - compositor(kit, queue.clone(), rate, &stop, &latencies, None) - }); - let app = kit.device.new_command_queue().unwrap(); - let target = kit.target(); - let in_flight = options.in_flight.max(1); - let slots = Arc::new((Mutex::new(in_flight), std::sync::Condvar::new())); - let frames: Arc>> = Arc::new(Mutex::new(Vec::new())); - let mut before = None; - let began = Instant::now(); - let mut count = 0; - while began.elapsed().as_secs_f64() < options.seconds || count <= WARM { - { - let (free, freed) = &*slots; - let mut free = free.lock().unwrap(); - while *free == 0 { - free = freed.wait(free).unwrap(); - } - *free -= 1; - } - if count == WARM { - before = Some((kit.device.work_counts(), Instant::now())); - } - let start = metal2vulkan_runtime::host_time(); - frames.lock().unwrap().push(Pair { - start, - ..Pair::default() - }); - let long = kit.long(&app); - let at = Arc::clone(&frames); - long.add_completed_handler(Box::new(move |done: &CommandBuffer| { - let pair = &mut at.lock().unwrap()[count]; - pair.long[1] = done.kernel_start_time(); - pair.long[2] = done.gpu_start_time().unwrap_or(0.0); - pair.long[3] = done.gpu_end_time().unwrap_or(0.0); - })) - .unwrap(); - frames.lock().unwrap()[count].long[0] = metal2vulkan_runtime::host_time(); - long.commit().unwrap(); - drop(long); - let draw = kit.draw(&app, &target); - let (at, slot) = (Arc::clone(&frames), Arc::clone(&slots)); - draw.add_completed_handler(Box::new(move |done: &CommandBuffer| { - let handled = metal2vulkan_runtime::host_time(); - { - let pair = &mut at.lock().unwrap()[count]; - pair.draw[1] = done.kernel_start_time(); - pair.draw[2] = done.gpu_start_time().unwrap_or(0.0); - pair.draw[3] = done.gpu_end_time().unwrap_or(0.0); - pair.draw[4] = handled; - } - let (free, freed) = &*slot; - *free.lock().unwrap() += 1; - freed.notify_one(); - })) - .unwrap(); - frames.lock().unwrap()[count].draw[0] = metal2vulkan_runtime::host_time(); - draw.commit().unwrap(); - drop(draw); - count += 1; - } - { - let (free, freed) = &*slots; - let mut free = free.lock().unwrap(); - while *free < in_flight { - free = freed.wait(free).unwrap(); - } - } - let after = kit.device.work_counts(); - let (before, from) = before.unwrap(); - let elapsed = from.elapsed().as_secs_f64(); - stop.store(true, Ordering::Relaxed); - if let Some(comp) = comp { - comp.join().unwrap(); - } - drop(queue); - let all = frames.lock().unwrap().clone(); - let measured = &all[WARM..]; - let n = measured.len() as f64; - let periods: Vec = (all[WARM - 1..].windows(2)) - .map(|w| w[1].start - w[0].start) - .collect(); - let gpu: Vec = measured.iter().map(|f| f.draw[3] - f.long[2]).collect(); - let busy: f64 = (measured.iter()) - .map(|f| (f.long[3] - f.long[2]) + (f.draw[3] - f.draw[2])) - .sum(); - let span = measured[measured.len() - 1].draw[3] - measured[0].long[2]; - let long_held: Vec = measured.iter().map(|f| f.long[1] - f.long[0]).collect(); - let draw_held: Vec = measured.iter().map(|f| f.draw[1] - f.draw[0]).collect(); - let gaps: Vec = (all[WARM - 1..].windows(2)) - .map(|w| w[1].long[2] - w[0].draw[3]) - .collect(); - let seen: Vec = measured.iter().map(|f| f.draw[4] - f.draw[3]).collect(); - let commit_to_seen: Vec = measured.iter().map(|f| f.draw[4] - f.long[0]).collect(); - let per = |a: u64, b: u64| (a - b) as f64 / n; - println!( - "pairs (isolation {:?}, compositor {} {}, {} frames in flight, a long command buffer of \ - {:.1} ms and a draw a frame): {:.1} frames/s; frame period {} ms (mean {:.2}); GPU a frame \ - {} ms; GPU idle {:.1}% of the frames' span", - options.isolation, - if options.unshared { "unshared" } else { "shared" }, - match options.period.is_zero() { - true => "committing nothing".to_owned(), - false => format!("every {:?}", options.period), - }, - in_flight, - kit.long_time.as_secs_f64() * 1e3, - n / elapsed, - p50_p90(periods.clone()), - periods.iter().sum::() / periods.len().max(1) as f64 * 1e3, - p50_p90(gpu), - (1.0 - busy / span.max(1e-9)) * 100.0, - ); - println!( - " commit to kernel start: long {} ms, draw {} ms; GPU gap before a long one {} ms; the \ - draw's GPU end to its completed handler {} ms; the long one's commit to the draw's \ - handler {} ms", - p50_p90(long_held), - p50_p90(draw_held), - p50_p90(gaps.clone()), - p50_p90(seen), - p50_p90(commit_to_seen), - ); - println!( - " a frame: batch_hold_nanos {:.2} ms, batches_held_past_a_look {:.2}, \ - heads_held_for_unshared_isolation {:.2}, scheduler_slice_rescues {:.2}, \ - scheduler_sleep_slices {:.2}, scheduler_wakes_completion {:.2}, scheduler_sleeps {:.2}, \ - queue_submissions {:.2}, command_buffers_behind_other_queues {:.2}; compositor {}", - per(after.batch_hold_nanos, before.batch_hold_nanos) / 1e6, - per( - after.batches_held_past_a_look, - before.batches_held_past_a_look - ), - per( - after.heads_held_for_unshared_isolation, - before.heads_held_for_unshared_isolation - ), - per( - after.scheduler_slice_rescues, - before.scheduler_slice_rescues - ), - per(after.scheduler_sleep_slices, before.scheduler_sleep_slices), - per( - after.scheduler_wakes_completion, - before.scheduler_wakes_completion - ), - per(after.scheduler_sleeps, before.scheduler_sleeps), - per(after.queue_submissions, before.queue_submissions), - per( - after.command_buffers_behind_other_queues, - before.command_buffers_behind_other_queues - ), - summary(&mut latencies.lock().unwrap().clone()), - ); - let first: Vec = (0..8.min(periods.len())) - .map(|i| { - let f = &measured[i]; - format!( - "{:.1}/{:.1}/{:.1}/{:.1}", - periods[i] * 1e3, - gaps[i] * 1e3, - (f.long[1] - f.long[0]) * 1e3, - (f.draw[1] - f.draw[0]) * 1e3 - ) - }) - .collect(); - println!( - " first frames (period/GPU gap before its long one/long held/draw held, ms): {}", - first.join(" ") - ); -} - -/// The `churn` mode (the module docs). -fn churn(kit: &Arc, options: &Options) { - let stop = Arc::new(AtomicBool::new(false)); - let latencies = Arc::new(Mutex::new(Vec::new())); - let before = kit.device.work_counts(); - let comp = compositor( - kit, - kit.queue(options.unshared), - 1.0 / options.period.as_secs_f64(), - &stop, - &latencies, - None, - ); - let kept: Vec> = (0..3) - .map(|_| { - let kit = Arc::clone(kit); - let stop = Arc::clone(&stop); - std::thread::spawn(move || { - let queue = kit.device.new_command_queue().unwrap(); - let target = kit.target(); - while !stop.load(Ordering::Relaxed) { - kit.draw(&queue, &target).commit().unwrap(); - std::thread::sleep(Duration::from_millis(8)); - } - }) - }) - .collect(); - let tick = Duration::from_secs_f64(options.seconds / options.churn.max(1) as f64); - let target = kit.target(); - let mut live: Vec<(CommandQueue, usize, CommandBuffer)> = Vec::new(); - let mut seed = 0x2545_f491_4f6c_dd1du64; - let mut most = 0; - let mut next = Instant::now(); - for made in 0..options.churn { - live.retain(|(_, until, last)| { - let keep = *until > made; - if !keep { - last.wait_until_completed().unwrap(); - } - keep - }); - for (queue, _, last) in &mut live { - let draw = kit.draw(queue, &target); - draw.commit().unwrap(); - *last = draw; - } - let queue = kit.device.new_command_queue().unwrap(); - let long = kit.long(&queue); - long.commit().unwrap(); - seed = - (seed.wrapping_mul(6_364_136_223_846_793_005)).wrapping_add(1_442_695_040_888_963_407); - live.push((queue, made + 1 + ((seed >> 33) % 8) as usize, long)); - // The compositor's, the kept ones and the churn's. - most = most.max(1 + 3 + live.len()); - next += tick; - let now = Instant::now(); - if next > now { - std::thread::sleep(next - now); - } - } - stop.store(true, Ordering::Relaxed); - comp.join().unwrap(); - for thread in kept { - thread.join().unwrap(); - } - for (_, _, last) in &live { - last.wait_until_completed().unwrap(); - } - std::thread::sleep(Duration::from_millis(100)); - let c = kit.device.work_counts(); - let mut samples = latencies.lock().unwrap().clone(); - let over_16 = samples.iter().filter(|&&ms| ms > 16.0).count(); - println!( - "churn (policy {:?}, untimed {}, compositor {} every {:?}, {} queues made, one every {:.0} ms, each with one long command buffer of {:.1} ms, at most {most} live): compositor {}, {over_16} over 16 ms; {} queues past the round robin", - options.policy, - options.untimed, - if options.unshared { "unshared" } else { "shared" }, - options.period, - options.churn, - tick.as_secs_f64() * 1e3, - kit.long_time.as_secs_f64() * 1e3, - summary(&mut samples), - c.queues_sharing_a_vk_queue - before.queues_sharing_a_vk_queue, - ); - println!( - " behind other queues: {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms)", - c.command_buffers_behind_other_queues - before.command_buffers_behind_other_queues, - c.command_buffers_behind_other_queues_over_16ms - - before.command_buffers_behind_other_queues_over_16ms, - c.command_buffers_behind_other_queues_over_33ms - - before.command_buffers_behind_other_queues_over_33ms, - c.wait_behind_other_queues_longest_nanos as f64 / 1e6, - c.unshared_command_buffers_behind_other_queues - - before.unshared_command_buffers_behind_other_queues, - c.unshared_command_buffers_behind_other_queues_over_16ms - - before.unshared_command_buffers_behind_other_queues_over_16ms, - c.unshared_command_buffers_behind_other_queues_over_33ms - - before.unshared_command_buffers_behind_other_queues_over_33ms, - c.unshared_wait_behind_other_queues_longest_nanos as f64 / 1e6, - ); -} - -/// Of `times` (queue, GPU start, GPU end), queue 0's GPU time over the span from its first start -/// to its last end, and the share of that span no command buffer of either queue ran in. -fn busy_shares(times: &[(usize, f64, f64)]) -> (f64, f64) { - let app: Vec<&(usize, f64, f64)> = times.iter().filter(|(queue, _, _)| *queue == 0).collect(); - let (Some(from), Some(to)) = ( - app.iter().map(|t| t.1).min_by(f64::total_cmp), - app.iter().map(|t| t.2).max_by(f64::total_cmp), - ) else { - return (0.0, 0.0); - }; - let span = (to - from).max(1e-9); - let busy: f64 = app.iter().map(|(_, start, end)| end - start).sum(); - let mut all: Vec<(f64, f64)> = (times.iter()) - .map(|&(_, start, end)| (start.max(from), end.min(to))) - .filter(|(start, end)| end > start) - .collect(); - all.sort_by(|a, b| a.0.total_cmp(&b.0)); - let (mut covered, mut reach) = (0.0, from); - for (start, end) in all { - if end > reach { - covered += end - start.max(reach); - reach = end; - } - } - (busy / span, 1.0 - covered / span) -} - -/// The GPU's idle time between command buffers of different queues, as a share of the span of -/// `times` (queue, GPU start, GPU end), in GPU start order; with the switches counted. -fn switch_idle(times: &mut [(usize, f64, f64)]) -> (f64, usize) { - if times.len() < 2 { - return (0.0, 0); - } - times.sort_by(|a, b| a.1.total_cmp(&b.1)); - let span = times[times.len() - 1].2 - times[0].1; - let mut idle = 0.0; - let mut switches = 0; - for pair in times.windows(2) { - if pair[0].0 != pair[1].0 { - switches += 1; - idle += (pair[1].1 - pair[0].2).max(0.0); - } - } - (idle / span.max(1e-9), switches) -} - -fn interleave(kit: &Arc, options: &Options) { - let stop = Arc::new(AtomicBool::new(false)); - let first = Arc::new(Mutex::new(Vec::new())); - let second = Arc::new(Mutex::new(Vec::new())); - let times = Arc::new(Mutex::new(Vec::new())); - let a = compositor( - kit, - kit.queue(false), - COMPOSITOR_RATE, - &stop, - &first, - Some((0, Arc::clone(×))), - ); - let b = compositor( - kit, - kit.queue(false), - COMPOSITOR_RATE, - &stop, - &second, - Some((1, Arc::clone(×))), - ); - std::thread::sleep(Duration::from_secs_f64(options.seconds)); - stop.store(true, Ordering::Relaxed); - a.join().unwrap(); - b.join().unwrap(); - std::thread::sleep(Duration::from_millis(100)); - let mut samples: Vec = first.lock().unwrap().iter().map(|ms| ms * 1e3).collect(); - samples.sort_by(f64::total_cmp); - let at = |p: f64| samples[((samples.len() as f64 * p) as usize).min(samples.len() - 1)]; - let (idle, switches) = switch_idle(&mut times.lock().unwrap()); - println!( - "interleave (policy {:?}): first stream p50 {:.1} p99 {:.1} us; GPU idle at {switches} switches {:.1}% of the span; {}", - options.policy, - at(0.5), - at(0.99), - idle * 100.0, - kit.counts() - ); -} - -/// `threads` threads, each its own queue, committing draws with `in_flight` in flight: command -/// buffers a second over the run, and the GPU's idle share at switches. -/// The queues of `threads` threads: each its own where `one` is false; else all on the first's -/// `VkQueue`, made until the round robin comes back to it, each lent once so it never moves. -fn rate_queues(kit: &Kit, threads: usize, one: bool) -> Vec { - if !one { - return (0..threads).map(|_| kit.queue(false)).collect(); - } - // SAFETY: the closures keep the handle only to compare it; nothing is submitted. - let raw = |queue: &CommandQueue| unsafe { queue.with_vk_queue(|_, raw, _| raw) }; - let first = kit.queue(false); - let home = raw(&first); - let mut queues = vec![first]; - let mut others = Vec::new(); - while queues.len() < threads { - let queue = kit.queue(false); - match raw(&queue) == home { - true => queues.push(queue), - false => others.push(queue), - } - } - queues -} - -/// Per-thread CPU time of this process by thread name, in clock ticks (Linux; empty elsewhere). -fn thread_ticks() -> Vec<(u64, String, u64)> { - let Ok(tasks) = std::fs::read_dir("/proc/self/task") else { - return Vec::new(); - }; - let mut ticks = Vec::new(); - for task in tasks.flatten() { - let Ok(stat) = std::fs::read_to_string(task.path().join("stat")) else { - continue; - }; - let (Some(open), Some(close)) = (stat.find('('), stat.rfind(')')) else { - continue; - }; - let name = stat[open + 1..close].to_owned(); - let fields: Vec<&str> = stat[close + 2..].split(' ').collect(); - let (Some(user), Some(system)) = (fields.get(11), fields.get(12)) else { - continue; - }; - let tid = task.file_name().to_string_lossy().parse().unwrap_or(0); - ticks.push(( - tid, - name, - user.parse::().unwrap_or(0) + system.parse::().unwrap_or(0), - )); - } - ticks -} - -/// The busiest threads between `before` and `after`, as a share of `seconds` each. -fn busiest(before: &[(u64, String, u64)], after: &[(u64, String, u64)], seconds: f64) -> String { - let mut used: Vec<(f64, String)> = after - .iter() - .map(|(tid, name, ticks)| { - let was = before - .iter() - .find(|(t, _, _)| t == tid) - .map_or(0, |(_, _, t)| *t); - ((ticks - was) as f64 / 100.0 / seconds, name.clone()) - }) - .filter(|(share, _)| *share > 0.02) - .collect(); - used.sort_by(|a, b| b.0.total_cmp(&a.0)); - used.iter() - .take(8) - .map(|(share, name)| format!("{name} {:.0}%", share * 100.0)) - .collect::>() - .join(", ") -} - -/// The p50 and p99 of `samples`, in microseconds. -fn quantiles(samples: &mut [f64]) -> String { - if samples.is_empty() { - return "none".to_owned(); - } - samples.sort_by(f64::total_cmp); - let at = |p: f64| samples[((samples.len() as f64 * p) as usize).min(samples.len() - 1)] * 1e6; - format!("p50 {:.1} p99 {:.1} us", at(0.5), at(0.99)) -} - -fn rate(kit: &Arc, options: &Options, threads: usize, in_flight: usize) { - let stop = Arc::new(AtomicBool::new(false)); - let times = Arc::new(Mutex::new(Vec::new())); - // Each command buffer's GPU end to its completed handler, and its commit to that handler. - let latencies = Arc::new(Mutex::new((Vec::new(), Vec::new()))); - let queues = rate_queues(kit, threads, options.one_vk_queue); - let counts = kit.device.work_counts(); - let cpu = thread_ticks(); - let began = Instant::now(); - let handles: Vec<_> = (queues.into_iter().enumerate()) - .map(|(thread, queue)| { - let kit = Arc::clone(kit); - let stop = Arc::clone(&stop); - let times = Arc::clone(×); - let latencies = Arc::clone(&latencies); - std::thread::spawn(move || { - let target = kit.target(); - let mut flying = std::collections::VecDeque::new(); - let mut made = 0u64; - // Each change of the queue's `VkQueue` or long mark: at which command buffer, - // how far into the run. - let mut seen = Vec::new(); - let started = Instant::now(); - while !stop.load(Ordering::Relaxed) { - let command_buffer = kit.draw(&queue, &target); - let now = queue.vk_queue_sharing(); - if seen.last().is_none_or(|&(_, _, last)| last != now) { - seen.push((made, started.elapsed().as_micros(), now)); - } - let times = Arc::clone(×); - let latencies = Arc::clone(&latencies); - let committed = Arc::new(Mutex::new(0.0)); - let at = Arc::clone(&committed); - command_buffer - .add_completed_handler(Box::new(move |done: &CommandBuffer| { - let now = metal2vulkan_runtime::host_time(); - if let (Ok(start), Ok(end)) = - (done.gpu_start_time(), done.gpu_end_time()) - { - times.lock().unwrap().push((thread, start, end)); - let mut latencies = latencies.lock().unwrap(); - latencies.0.push(now - end); - latencies.1.push(now - *at.lock().unwrap()); - } - })) - .unwrap(); - *committed.lock().unwrap() = metal2vulkan_runtime::host_time(); - command_buffer.commit().unwrap(); - flying.push_back(command_buffer); - made += 1; - while flying.len() >= in_flight { - let done: CommandBuffer = flying.pop_front().unwrap(); - done.wait_until_completed().unwrap(); - } - } - for done in flying { - done.wait_until_completed().unwrap(); - } - (made, seen) - }) - }) - .collect(); - std::thread::sleep(Duration::from_secs_f64(options.seconds)); - stop.store(true, Ordering::Relaxed); - let each: Vec<(u64, Seen)> = handles.into_iter().map(|h| h.join().unwrap()).collect(); - let made: u64 = each.iter().map(|(made, _)| made).sum(); - let elapsed = began.elapsed().as_secs_f64(); - let cpu_after = thread_ticks(); - std::thread::sleep(Duration::from_millis(100)); - let after = kit.device.work_counts(); - let (idle, switches) = switch_idle(&mut times.lock().unwrap()); - let mut latencies = latencies.lock().unwrap(); - let per = |a: u64, b: u64| (a - b) as f64 / made.max(1) as f64; - println!( - "rates (policy {:?}{}): {threads} threads, {in_flight} in flight: {:.1}k command buffers/s; GPU idle at {switches} switches {:.1}%; {}", - options.policy, - if options.one_vk_queue { ", one VkQueue" } else { "" }, - made as f64 / elapsed / 1e3, - idle * 100.0, - kit.counts() - ); - println!( - " GPU end to handler {}; commit to handler {}", - quantiles(&mut latencies.0), - quantiles(&mut latencies.1) - ); - println!( - " per command buffer: submissions {:.2}, submit infos {:.2}, VkCommandBuffers {:.2}, scheduler passes {:.2} (by waiters {:.2}, their batches {:.2}), scheduler sleeps {:.2} (woken by commits {:.2}, completions {:.2}), timeline waits {:.2}, fence waits {:.2}, waiter parks {:.2} (timed out {:.2}), waiter wakes {:.2}, handler-thread wakes {:.2}, command-buffer wakes {:.2}, completed where seen {:.2}, turns taken {:.2}, submit {:.1} us", - per(after.queue_submissions, counts.queue_submissions), - per(after.submit_infos, counts.submit_infos), - per(after.command_buffers_submitted, counts.command_buffers_submitted), - per(after.scheduler_passes, counts.scheduler_passes), - per(after.scheduler_passes_by_waiters, counts.scheduler_passes_by_waiters), - per(after.batches_submitted_by_waiters, counts.batches_submitted_by_waiters), - per(after.scheduler_sleeps, counts.scheduler_sleeps), - per(after.scheduler_wakes_commit, counts.scheduler_wakes_commit), - per(after.scheduler_wakes_completion, counts.scheduler_wakes_completion), - per(after.timeline_waits, counts.timeline_waits), - per(after.fence_waits, counts.fence_waits), - per(after.completion_waiter_parks, counts.completion_waiter_parks), - per(after.completion_waiter_parks_timed_out, counts.completion_waiter_parks_timed_out), - per(after.wakes_completion_waiters, counts.wakes_completion_waiters), - per(after.wakes_handler_threads, counts.wakes_handler_threads), - per(after.wakes_command_buffer_waiters, counts.wakes_command_buffer_waiters), - per(after.completed_where_seen, counts.completed_where_seen), - per(after.completion_turns_where_taken, counts.completion_turns_where_taken), - per(after.batch_submit_nanos, counts.batch_submit_nanos) / 1e3, - ); - println!(" threads' CPU: {}", busiest(&cpu, &cpu_after, elapsed)); - for (thread, (made, seen)) in each.iter().enumerate() { - let changes: Vec = seen - .iter() - .map(|(at, us, (vk_queue, long))| { - format!( - "#{at} {us}us VkQueue {vk_queue}{}", - if *long { " long" } else { "" } - ) - }) - .collect(); - println!( - " thread {thread}: {made} command buffers; {}", - changes.join(", ") - ); - } -} - -fn idle_queues(kit: &Arc, options: &Options, count: usize) { - let queues: Vec = (0..count).map(|_| kit.queue(false)).collect(); - let target = kit.target(); - let mut flying = std::collections::VecDeque::new(); - let mut made = 0u64; - let mut making = Duration::ZERO; - let began = Instant::now(); - while began.elapsed().as_secs_f64() < options.seconds { - let queue = &queues[made as usize % count]; - let start = Instant::now(); - let command_buffer = queue.command_buffer().unwrap(); - making += start.elapsed(); - let command_buffer = kit.draw_into(command_buffer, &target); - command_buffer.commit().unwrap(); - flying.push_back(command_buffer); - made += 1; - while flying.len() >= 3 { - let done: CommandBuffer = flying.pop_front().unwrap(); - done.wait_until_completed().unwrap(); - } - } - for done in flying { - done.wait_until_completed().unwrap(); - } - let elapsed = began.elapsed().as_secs_f64(); - println!( - "idle-queues (policy {:?}): {count} queues in turn: {:.1}k command buffers/s, command_buffer {:.0} ns each; {}", - options.policy, - made as f64 / elapsed / 1e3, - making.as_nanos() as f64 / made as f64, - kit.counts() - ); -} - -fn main() { - let options = options(); - if options.mode == "check" { - let device = device(&options); - let settled = device.settle_queue_switch_check(Duration::from_secs(10)); - println!( - "device: {}; settled {settled}: {}", - device.name(), - device.queue_switch_check_report() - ); - return; - } - let kit = Arc::new(Kit::new(&options)); - match options.mode.as_str() { - "isolation" => beside(&kit, &options, Duration::ZERO, 1, 1), - "pipelined" => beside(&kit, &options, Duration::ZERO, 1, 2), - "trap" => beside(&kit, &options, Duration::from_millis(500), 10, 1), - "alternating" => beside(&kit, &options, Duration::from_millis(2), 1, 1), - "slow-alternating" => beside(&kit, &options, Duration::from_millis(1500), 1, 1), - "frames" => frames(&kit, &options), - "pairs" => pairs(&kit, &options), - "interleave" => interleave(&kit, &options), - "rates" if options.threads > 0 => { - rate(&kit, &options, options.threads, options.in_flight); - } - "rates" => { - for in_flight in [3, 1] { - for threads in [2, 8] { - rate(&kit, &options, threads, in_flight); - } - } - } - "idle-queues" => { - idle_queues(&kit, &options, 16); - idle_queues(&kit, &options, 2048); - } - "churn" => churn(&kit, &options), - other => panic!("no mode {other}"), - } -} diff --git a/crates/metal2vulkan-runtime/examples/render_to_texture.rs b/crates/metal2vulkan-runtime/examples/render_to_texture.rs deleted file mode 100644 index 9f965949d..000000000 --- a/crates/metal2vulkan-runtime/examples/render_to_texture.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! A render pass to a texture, read back: a render pipeline state of a vertex and a fragment -//! function, a `Private` render target cleared to blue, two triangles over its top-left quarter, -//! and a blit of its texels into a `Shared` buffer the CPU reads. -//! -//! ```sh -//! cargo run -p metal2vulkan-runtime --example render_to_texture [-- path/to/library.metallib] -//! ``` -//! -//! The functions are `colored_vertex` and `colored_fragment` of the repository's owned fixture -//! (`validation/fixtures/public/examples/runtime_examples.metal`), or of the metallib the argument -//! names. Positions are Metal's normalized device coordinates (y up, the texture's row 0 at the -//! top), whatever Vulkan's are: the runtime keeps Metal's. - -mod common; - -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan_runtime::{ - BlitOption, ClearColor, Device, LoadAction, Origin, PipelineOptions, RenderPassDescriptor, - ResourceOptions, Size, StoreAction, TextureDescriptor, -}; - -/// The render target's side, in texels. -const SIDE: u64 = 8; - -/// The color the triangles draw, and the bytes an `RGBA8Unorm` texel stores of it. -const DRAWN: [f32; 4] = [1.0, 0.2, 0.0, 1.0]; -const DRAWN_TEXEL: [u8; 4] = [255, 51, 0, 255]; - -/// The clear color, and its texel. -const CLEARED_TEXEL: [u8; 4] = [0, 0, 255, 255]; - -fn main() -> common::Result<()> { - let device = Device::system_default()?; - println!("device: {}", device.name()); - let library = common::library(&device)?; - let vertex = library.new_function_with_name("colored_vertex")?; - let fragment = library.new_function_with_name("colored_fragment")?; - - // `MTLRenderPipelineDescriptor`: the compile layer's descriptor, its stages the functions' - // descriptors. `newRenderPipelineStateWithDescriptor:error:` compiles both stages. - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); - descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); - descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let state = device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())?; - - // `texture2DDescriptorWithPixelFormat:width:height:mipmapped:`, a render target the GPU alone - // reaches. - let mut texture = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); - texture.usage = TextureUsage::RENDER_TARGET; - texture.resource_options = ResourceOptions::private(); - let target = device.new_texture(&texture)?; - - // The top-left quarter as two triangles, each vertex's position and color by vertex ID. - let positions: [[f32; 2]; 6] = [ - [-1.0, 1.0], - [0.0, 1.0], - [-1.0, 0.0], - [0.0, 1.0], - [0.0, 0.0], - [-1.0, 0.0], - ]; - let positions: Vec = positions - .iter() - .flatten() - .flat_map(|value| value.to_le_bytes()) - .collect(); - let colors: Vec = (0..6) - .flat_map(|_| DRAWN) - .flat_map(|value| value.to_le_bytes()) - .collect(); - let positions = device.new_buffer_with_bytes(&positions, ResourceOptions::shared())?; - let colors = device.new_buffer_with_bytes(&colors, ResourceOptions::shared())?; - - // `MTLRenderPassDescriptor`: clear the target to blue, and store what the pass draws. - let mut pass = RenderPassDescriptor::new(); - let color = &mut pass.color_attachments[0]; - color.texture = Some(target.clone()); - color.load_action = LoadAction::Clear; - color.store_action = StoreAction::Store; - color.clear_color = ClearColor::new(0.0, 0.0, 1.0, 1.0); - - let row = SIDE * 4; - let readback = device.new_buffer(row * SIDE, ResourceOptions::shared())?; - let queue = device.new_command_queue()?; - let command_buffer = queue.command_buffer()?; - let mut encoder = command_buffer.render_command_encoder(&pass)?; - encoder.set_render_pipeline_state(&state)?; - encoder.set_vertex_buffer(Some(&positions), 0, 0)?; - encoder.set_vertex_buffer(Some(&colors), 0, 1)?; - encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)?; - encoder.end_encoding()?; - // `copyFromTexture:...toBuffer:...`: the blit runs after the pass, ordered by the runtime's - // hazard tracking. - let mut blit = command_buffer.blit_command_encoder()?; - blit.copy_from_texture_to_buffer( - &target, - 0, - 0, - Origin::new(0, 0, 0), - Size::new(SIDE, SIDE, 1), - &readback, - 0, - row, - row * SIDE, - BlitOption::None, - )?; - blit.end_encoding()?; - common::run(&command_buffer)?; - - let texels = common::bytes(&readback)?; - for y in 0..SIDE as usize { - let mut line = String::new(); - for x in 0..SIDE as usize { - let at = (y * SIDE as usize + x) * 4; - let texel = &texels[at..at + 4]; - let inside = x < SIDE as usize / 2 && y < SIDE as usize / 2; - let expected = if inside { DRAWN_TEXEL } else { CLEARED_TEXEL }; - if texel != expected { - return Err(format!("texel ({x}, {y}) is {texel:?}, not {expected:?}").into()); - } - line.push(if inside { '#' } else { '.' }); - } - println!("{line}"); - } - println!("every texel as expected: the top-left quarter drawn, the rest cleared"); - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/examples/shared_files.rs b/crates/metal2vulkan-runtime/examples/shared_files.rs deleted file mode 100644 index 81f121c28..000000000 --- a/crates/metal2vulkan-runtime/examples/shared_files.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Not a consumer's example: what one kernel submission costs beside no-copy buffers over -//! dma-bufs of their pages, each a dma-buf of its own against pieces of files shared among them -//! (`DmaBufChunk`, one import per file), on a device that refuses the pages' pointer: RADV refuses -//! the pointer of a `memfd`'s shared mapping, as of QEMU's guest RAM, and lists every import in -//! every kernel submission. Linux only, with access to `/dev/udmabuf`. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example shared_files [-- BUFFERS [PER_FILE ...]] -//! ``` -//! -//! For each count of buffers a file (by default 1, 8 and `BUFFERS`, which is 1000 by default): -//! `BUFFERS` no-copy buffers of 64 KiB over one sealed `memfd` mapped shared, each -//! answered by a source with a piece of the `udmabuf` of its file's run of the `memfd` (1: a -//! `udmabuf` of its own pages, a dma-buf of its own), each buffer's Metal address handed out (so -//! its import stays imported, as a guest's buffers' do); then 300 command buffers of one 4-KiB -//! fill, one at a time, each waited for, after 30 untimed. One `SHARED-FILES` line -//! each: the imports made, the pieces joined to a live import, the dma-buf memories and shared -//! imports live (`WorkCounts::dma_buf_imports`, `dma_buf_pieces_joined`, `dma_buf_memories_live`, -//! `dma_buf_shared_imports_live`), the imports released past the most the device keeps and those -//! imported again (`host_imports_released_over_most`, `host_imports_reimported`: a buffer released -//! while the others were made is imported again as its address is handed out, a shared file's -//! piece joining the file's live import again), a command buffer's time from its kernelStartTime -//! to its kernelEndTime (50th and 90th percentiles), and the mean time of a `vkQueueSubmit` call -//! in the driver (`WorkCounts::batch_submit_nanos` over `queue_submissions`). The device's -//! submission checks answer first, so that every phase runs under their verdicts and none beside -//! their work. A device that imports the pointer (NVIDIA, lavapipe) makes no dma-buf import, which -//! the line shows. - -#[cfg(target_os = "linux")] -mod linux { - use metal2vulkan_runtime::{ - Buffer, CommandBufferStatus, CommandQueue, Device, DmaBufChunk, DmaBufRequest, - DmaBufSource, HostMemory, ResourceOptions, - }; - use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; - use std::ptr::NonNull; - use std::sync::Arc; - use std::time::Duration; - - /// The bytes of each buffer: one 64-KiB chunk, RADV 26.2.4's sparse granule. - const BUFFER_BYTES: usize = 64 << 10; - /// Command buffers committed untimed first. - const WARM: usize = 30; - /// Command buffers timed. - const COMMITS: usize = 300; - /// The longest a command buffer may take, and the device's submission checks. - pub const WAIT: Duration = Duration::from_secs(60); - - /// `struct udmabuf_create` of Linux's `include/uapi/linux/udmabuf.h`. - #[repr(C)] - struct Create { - memfd: u32, - flags: u32, - offset: u64, - size: u64, - } - - /// `UDMABUF_FLAGS_CLOEXEC`. - const UDMABUF_FLAGS_CLOEXEC: u32 = 0x01; - - /// `UDMABUF_CREATE`, `_IOW('u', 0x42, struct udmabuf_create)` in the generic ioctl encoding. - const UDMABUF_CREATE: u64 = - (1 << 30) | ((size_of::() as u64) << 16) | ((b'u' as u64) << 8) | 0x42; - - /// A dma-buf of `memfd`'s `size` bytes from `offset`. - fn udmabuf(memfd: &OwnedFd, offset: u64, size: u64) -> std::io::Result { - let device = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open("/dev/udmabuf")?; - let create = Create { - memfd: memfd.as_raw_fd() as u32, - flags: UDMABUF_FLAGS_CLOEXEC, - offset, - size, - }; - // SAFETY: the ioctl reads `create`, a valid `udmabuf_create`. - let fd = unsafe { libc::ioctl(device.as_raw_fd(), UDMABUF_CREATE as _, &create) }; - if fd < 0 { - return Err(std::io::Error::last_os_error()); - } - // SAFETY: a new descriptor the ioctl returned, owned at once. - Ok(unsafe { OwnedFd::from_raw_fd(fd) }) - } - - /// Guest RAM: a `memfd` of `len` bytes sealed against growing and shrinking, mapped shared - /// whole; unmapped when dropped. - struct Ram { - fd: OwnedFd, - at: NonNull, - len: usize, - } - - impl Ram { - fn new(len: usize) -> Ram { - // SAFETY: a new anonymous file, owned at once, then sized and sealed. - let fd = unsafe { - let fd = libc::memfd_create( - c"m2v-shared-files".as_ptr(), - libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, - ); - assert!(fd >= 0, "memfd_create: {}", std::io::Error::last_os_error()); - OwnedFd::from_raw_fd(fd) - }; - // SAFETY: the descriptor is this object's. - unsafe { - assert_eq!(libc::ftruncate(fd.as_raw_fd(), len as libc::off_t), 0); - let seals = libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; - assert_eq!(libc::fcntl(fd.as_raw_fd(), libc::F_ADD_SEALS, seals), 0); - } - // SAFETY: a new shared mapping of the whole file. - let at = unsafe { - libc::mmap( - std::ptr::null_mut(), - len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_SHARED, - fd.as_raw_fd(), - 0, - ) - }; - assert_ne!(at, libc::MAP_FAILED, "mmap of the memfd"); - Ram { - fd, - at: NonNull::new(at.cast()).unwrap(), - len, - } - } - - /// The mapping's address `offset` bytes in. - fn pointer(&self, offset: usize) -> NonNull { - assert!(offset < self.len); - // SAFETY: inside the mapping. - unsafe { NonNull::new_unchecked(self.at.as_ptr().add(offset)) } - } - - /// A source answering each request with a piece of the file of `per_file` buffers' - /// pages its pages lie in (made now, held by the source), or, for 1, a `udmabuf` of its - /// own pages made as it is asked. - fn source(&self, per_file: usize) -> DmaBufSource { - let base = self.at.as_ptr() as u64; - let file_bytes = (per_file * BUFFER_BYTES) as u64; - let memfd = Arc::new(self.fd.try_clone().unwrap()); - let files: Vec> = match per_file { - 1 => Vec::new(), - _ => (0..(self.len as u64).div_ceil(file_bytes)) - .map(|index| { - let at = index * file_bytes; - let size = file_bytes.min(self.len as u64 - at); - Arc::new(udmabuf(&memfd, at, size).expect("a udmabuf of a file's run")) - }) - .collect(), - }; - Arc::new(move |request: DmaBufRequest| { - let at = (request.start.as_ptr() as u64) - .checked_sub(base) - .ok_or_else(|| std::io::Error::other("pages before the mapping"))?; - if files.is_empty() { - return Ok(vec![DmaBufChunk { - file: Arc::new(udmabuf(&memfd, at, request.length)?), - offset: 0, - length: request.length, - }]); - } - let (index, offset) = (at / file_bytes, at % file_bytes); - let file = (files.get(index as usize)) - .filter(|_| offset + request.length <= file_bytes) - .ok_or_else(|| std::io::Error::other("pages across two files"))?; - Ok(vec![DmaBufChunk { - file: Arc::clone(file), - offset, - length: request.length, - }]) - }) - } - } - - impl Drop for Ram { - fn drop(&mut self) { - // SAFETY: the mapping is this object's, and its buffers went first. - unsafe { libc::munmap(self.at.as_ptr().cast(), self.len) }; - } - } - - /// Commit a fill of `target`'s 4 KiB and wait for it: the microseconds from its - /// kernelStartTime to its kernelEndTime. - fn submitted(queue: &CommandQueue, target: &Buffer, value: u8) -> f64 { - let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(target, 0..4096, value).unwrap(); - blit.end_encoding().unwrap(); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); - (command_buffer.kernel_end_time() - command_buffer.kernel_start_time()) * 1e6 - } - - /// The phase of `buffers` buffers, `per_file` a file: held, measured and printed. - pub fn phase( - device: &Device, - queue: &CommandQueue, - target: &Buffer, - buffers: usize, - per_file: usize, - ) { - let ram = Ram::new(buffers * BUFFER_BYTES); - let source = ram.source(per_file); - let before = device.work_counts(); - let held: Vec = (0..buffers) - .map(|index| { - let at = ram.pointer(index * BUFFER_BYTES); - // SAFETY: the mapping outlives the buffers (dropped first), and the source makes - // dma-bufs of exactly the pages asked for. - unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::with_dma_buf(at, Arc::clone(&source)), - BUFFER_BYTES as u64, - ResourceOptions::shared(), - None, - ) - } - .unwrap() - }) - .collect(); - drop(source); - // Handed out, as a guest's buffers' addresses are: each import stays imported for good. - for buffer in &held { - buffer.gpu_address(); - } - for value in 0..WARM { - submitted(queue, target, value as u8); - } - let counts = device.work_counts(); - let mut times: Vec = (0..COMMITS) - .map(|value| submitted(queue, target, value as u8)) - .collect(); - let after = device.work_counts(); - times.sort_by(f64::total_cmp); - let at = |p: usize| times[(times.len() * p / 100).min(times.len() - 1)]; - let submits = after.queue_submissions - counts.queue_submissions; - let in_driver = (after.batch_submit_nanos - counts.batch_submit_nanos) as f64 - / submits.max(1) as f64 - / 1e3; - println!( - "SHARED-FILES {}: {buffers} buffers, {per_file} a file: {} imports made, {} pieces \ - joined, {} dma-buf memories live ({} shared imports), {} released past the most, {} \ - imported again; submit p50 {:.1} us (p90 {:.1}); vkQueueSubmit {in_driver:.1} us \ - each in the driver over {submits} calls", - device.name(), - counts.dma_buf_imports - before.dma_buf_imports, - counts.dma_buf_pieces_joined - before.dma_buf_pieces_joined, - counts.dma_buf_memories_live, - counts.dma_buf_shared_imports_live, - counts.host_imports_released_over_most - before.host_imports_released_over_most, - counts.host_imports_reimported - before.host_imports_reimported, - at(50), - at(90), - ); - drop(held); - } -} - -#[cfg(target_os = "linux")] -fn main() { - use metal2vulkan_runtime::{Device, ResourceOptions}; - let mut args = std::env::args() - .skip(1) - .map(|arg| arg.parse::().unwrap()); - let buffers = args.next().unwrap_or(1000); - let mut per_file: Vec = args.collect(); - if per_file.is_empty() { - per_file = vec![1, 8, buffers]; - } - let device = Device::system_default().unwrap(); - let answered = device.settle_submit_checks(linux::WAIT); - println!( - "device: {}; submission checks answered: {answered}; idle imports released: {}", - device.name(), - device.releases_idle_pointer_imports(), - ); - let queue = device.new_command_queue().unwrap(); - let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); - for each in per_file { - linux::phase(&device, &queue, &target, buffers, each); - } -} - -#[cfg(not(target_os = "linux"))] -fn main() { - println!("shared_files: Linux only (udmabuf)"); -} diff --git a/crates/metal2vulkan-runtime/examples/submit_path.rs b/crates/metal2vulkan-runtime/examples/submit_path.rs deleted file mode 100644 index 96c216942..000000000 --- a/crates/metal2vulkan-runtime/examples/submit_path.rs +++ /dev/null @@ -1,657 +0,0 @@ -//! Not a consumer's example: a command buffer's fixed cost on the submit and completion path, the -//! shape of a consumer that records a command buffer, adds handlers, commits and never waits. -//! -//! ```sh -//! cargo run --release -p metal2vulkan-runtime --example submit_path [-- latency|cross|cpu|threads|empty|idle|all [--seen] [--bare] [--at-commit] [--checked]] -//! ``` -//! -//! - **latency**: one thread commits a tiny blit command buffer (a fill of 16 bytes) with a -//! scheduled handler and a completed handler, or a completion-seen handler instead of the -//! completed one (`seen`), and does not wait for it: it blocks on a condition variable the -//! handler signals as it starts. Timed: `commit` to the handler's start, and the command -//! buffer's `GPUEndTime` to the handler's start (both on the runtime's host clock, -//! `host_time`), at idle gaps of 0, 100 us, 300 us and 2 ms between command buffers. With -//! `--bare`, also with no scheduled handler: a lone fill and its one callback. -//! - **cross**: the latency shape over two queues: command buffer A on the first signals an event -//! at its end, a shared one (whose wait the host holds until its value is reached) and a plain -//! one (whose wait goes to the GPU), and B on the second waits for it, each with a scheduled -//! handler and the handler `callback` names; A is committed, then B. Timed: A's commit to each -//! handler's start, at the same gaps; counted, the rounds where B's handler started before A's -//! or saw A's status short of `Completed` (Metal's completion follows the GPU's: none). -//! - **cpu**: the same command buffers committed as fast as the queue's slots allow, never waited -//! for: command buffers a second, and the CPU per command buffer of the runtime's threads (by -//! thread on Linux, from `/proc/self/task/*/schedstat`; elsewhere the process's CPU less the -//! committing thread's). -//! - **threads**: the cpu shape on 1 and on 8 threads at once, each with a queue of its own: -//! command buffers a second in all, and the CPU per command buffer. -//! - **empty**: a command buffer with nothing encoded, committed and waited for, back to back and -//! at a 300 us gap; and committed as fast as the slots allow, never waited for. -//! - **idle**: after one fill committed and waited for, wakes a second over [`IDLE_SECONDS`] with -//! nothing committed: on Linux the voluntary context switches by thread group, from -//! `/proc/self/task/*/status`; everywhere the scheduler's sleeps and the sleeps that ended at -//! its slice, from the device's work counts (macOS's per-process switch counts read back -//! inconsistently, so none is printed there). -//! -//! With `--at-commit`, latency, cpu and threads commit with `CommandBuffer::commit_and_submit` -//! (a runtime extension: the committing thread submits where no pass is under way) instead of -//! `commit`. With `--checked`, their fills carry a submission check that passes them -//! (`CommandBuffer::set_submission_check`, a runtime extension), as a consumer's detach check does. - -use metal2vulkan_runtime::{ - host_time, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, EventRef, - ResourceOptions, Submission, -}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; - -/// Whether command buffers are committed with `commit_and_submit` (`--at-commit`). -static AT_COMMIT: AtomicBool = AtomicBool::new(false); - -/// Whether the fills carry a submission check (`--checked`). -static CHECKED: AtomicBool = AtomicBool::new(false); - -/// Commit `command_buffer` as `--at-commit` says. -fn commit(command_buffer: &CommandBuffer) { - match AT_COMMIT.load(Ordering::Relaxed) { - true => command_buffer.commit_and_submit().unwrap(), - false => command_buffer.commit().unwrap(), - } -} - -/// Command buffers per measured row. -const ROUNDS: usize = 2000; - -/// How long a full-rate row runs. -const RATE_SECONDS: f64 = 3.0; - -/// How long the idle row watches the process. -const IDLE_SECONDS: f64 = 3.0; - -/// The idle gaps of the latency rows. -const GAPS_US: [u64; 4] = [0, 100, 300, 2000]; - -/// Which handler the latency and cpu rows signal from. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Callback { - /// A completed handler, with a scheduled handler before it. - Completed, - /// A completion-seen handler, with a scheduled handler before it. - Seen, -} - -impl Callback { - fn name(self) -> &'static str { - match self { - Callback::Completed => "completed", - Callback::Seen => "seen", - } - } -} - -/// A one-shot signal from a handler to the committing thread: the instant the handler started, -/// and the seconds from its command buffer's `GPUEndTime` to then on the host clock. -#[derive(Default)] -struct Signal { - at: Mutex>, - changed: Condvar, -} - -impl Signal { - fn set(&self, after_gpu_end: f64) { - let now = Instant::now(); - *self.at.lock().unwrap() = Some((now, after_gpu_end)); - self.changed.notify_one(); - } - - fn take(&self) -> (Instant, f64) { - let mut at = self.at.lock().unwrap(); - loop { - if let Some(at) = at.take() { - return at; - } - at = self.changed.wait(at).unwrap(); - } - } -} - -/// A tiny blit command buffer: a fill of 16 bytes of `target`, with a scheduled handler where -/// `scheduled`, and the handler `callback` names, which runs `then` with the seconds from the -/// command buffer's `GPUEndTime` to its start. -fn tiny( - queue: &CommandQueue, - target: &Buffer, - (callback, scheduled): (Callback, bool), - then: impl FnOnce(f64) + Send + 'static, -) -> CommandBuffer { - let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(target, 0..16, 0xa5).unwrap(); - blit.end_encoding().unwrap(); - if CHECKED.load(Ordering::Relaxed) { - command_buffer - .set_submission_check(Arc::new(|_: &Submission<'_>| None)) - .unwrap(); - } - if scheduled { - command_buffer - .add_scheduled_handler(Box::new(|_: &CommandBuffer| {})) - .unwrap(); - } - let handler = Box::new(move |buffer: &CommandBuffer| { - let now = host_time(); - then(now - buffer.gpu_end_time().unwrap_or(now)) - }); - match callback { - Callback::Completed => command_buffer.add_completed_handler(handler).unwrap(), - Callback::Seen => command_buffer.add_completion_seen_handler(handler).unwrap(), - } - command_buffer -} - -/// Sleep `gap` microseconds (none for 0). -fn idle(gap: u64) { - if gap > 0 { - std::thread::sleep(Duration::from_micros(gap)); - } -} - -/// The p50, p90 and p99 of `samples`, in microseconds. -fn percentiles(samples: &mut [f64]) -> (f64, f64, f64) { - samples.sort_by(f64::total_cmp); - let at = |p: f64| samples[((samples.len() as f64 * p) as usize).min(samples.len() - 1)]; - (at(0.5), at(0.9), at(0.99)) -} - -fn latency(device: &Device, callback: Callback, scheduled: bool) { - let queue = device.new_command_queue().unwrap(); - let target = device.new_buffer(16, ResourceOptions::shared()).unwrap(); - let name = match scheduled { - true => callback.name().to_owned(), - false => format!("{} bare", callback.name()), - }; - for gap in GAPS_US { - let signal = Arc::new(Signal::default()); - let (mut samples, mut after_end) = (Vec::with_capacity(ROUNDS), Vec::new()); - for round in 0..ROUNDS + 50 { - idle(gap); - let signalled = Arc::clone(&signal); - let command_buffer = tiny(&queue, &target, (callback, scheduled), move |after| { - signalled.set(after) - }); - let committed = Instant::now(); - commit(&command_buffer); - drop(command_buffer); - let (started, after) = signal.take(); - if round >= 50 { - samples.push(started.duration_since(committed).as_secs_f64() * 1e6); - after_end.push(after * 1e6); - } - } - let (p50, p90, p99) = percentiles(&mut samples); - let (e50, e90, e99) = percentiles(&mut after_end); - println!( - "latency {name:<14} gap {gap:>4} us: commit to handler p50 {p50:7.1} p90 {p90:7.1} \ - p99 {p99:7.1} us; GPU end to handler p50 {e50:7.1} p90 {e90:7.1} p99 {e99:7.1} us" - ); - } -} - -/// One round's handler starts of the cross row: A's, and B's with whether A's handler had started -/// and its status was `Completed` then. -type Starts = (Option, Option<(Instant, bool)>); - -/// The cross row's [`Starts`], and their signal to the committing thread. -#[derive(Default)] -struct Cross { - starts: Mutex, - changed: Condvar, -} - -impl Cross { - fn take(&self) -> (Instant, Instant, bool) { - let mut starts = self.starts.lock().unwrap(); - loop { - if let (Some(a), Some((b, completed))) = *starts { - *starts = (None, None); - return (a, b, completed); - } - starts = self.changed.wait(starts).unwrap(); - } - } -} - -fn cross(device: &Device, callback: Callback, shared: bool) { - let (first, second) = ( - device.new_command_queue().unwrap(), - device.new_command_queue().unwrap(), - ); - let (shared_event, plain_event) = ( - device.new_shared_event().unwrap(), - device.new_event().unwrap(), - ); - let event = || match shared { - true => EventRef::from(&shared_event), - false => EventRef::from(&plain_event), - }; - let target = device.new_buffer(32, ResourceOptions::shared()).unwrap(); - let mut value = 0; - for gap in GAPS_US { - let starts = Arc::new(Cross::default()); - let (mut to_a, mut to_b) = (Vec::with_capacity(ROUNDS), Vec::with_capacity(ROUNDS)); - let mut overtaken = 0; - for round in 0..ROUNDS + 50 { - idle(gap); - value += 1; - let at_a = Arc::clone(&starts); - let a = tiny(&first, &target, (callback, true), move |_| { - at_a.starts.lock().unwrap().0 = Some(Instant::now()); - at_a.changed.notify_one(); - }); - a.encode_signal_event(event(), value).unwrap(); - let b = second.command_buffer().unwrap(); - b.encode_wait_for_event(event(), value).unwrap(); - let mut blit = b.blit_command_encoder().unwrap(); - blit.fill_buffer(&target, 16..32, 0x5a).unwrap(); - blit.end_encoding().unwrap(); - b.add_scheduled_handler(Box::new(|_: &CommandBuffer| {})) - .unwrap(); - let (at_b, signaller) = (Arc::clone(&starts), a.clone()); - let handler = Box::new(move |_: &CommandBuffer| { - let completed = signaller.status() == CommandBufferStatus::Completed; - let mut starts = at_b.starts.lock().unwrap(); - let before_a = starts.0.is_none(); - starts.1 = Some((Instant::now(), completed && !before_a)); - at_b.changed.notify_one(); - }); - match callback { - Callback::Completed => b.add_completed_handler(handler).unwrap(), - Callback::Seen => b.add_completion_seen_handler(handler).unwrap(), - } - let committed = Instant::now(); - commit(&a); - commit(&b); - drop((a, b)); - let (a_started, b_started, in_order) = starts.take(); - if round >= 50 { - to_a.push(a_started.duration_since(committed).as_secs_f64() * 1e6); - to_b.push(b_started.duration_since(committed).as_secs_f64() * 1e6); - overtaken += usize::from(!in_order); - } - } - let (a50, a90, a99) = percentiles(&mut to_a); - let (b50, b90, b99) = percentiles(&mut to_b); - let kind = match shared { - true => "shared", - false => "plain", - }; - println!( - "cross {:<10} {kind:<6} gap {gap:>4} us: A's commit to A's handler p50 {a50:7.1} p90 \ - {a90:7.1} p99 {a99:7.1} us, to B's p50 {b50:7.1} p90 {b90:7.1} p99 {b99:7.1} us; B \ - before A {overtaken}/{ROUNDS}", - callback.name() - ); - } -} - -/// The group a thread named `comm` is counted in. -fn group_of(comm: &str) -> &'static str { - match comm { - c if c.starts_with("metal2vulkan-sc") => "scheduler", - c if c.starts_with("metal2vulkan-qu") => "queue-waiters", - c if c.starts_with("metal2vulkan-ha") => "handlers", - c if c.starts_with("metal2vulkan") => "other-m2v", - c if c.starts_with("submit_path") => "committer+main", - _ => "driver/other", - } -} - -/// Voluntary context switches by thread group, each of the process's threads by its name's -/// prefix: Linux only, none elsewhere. -fn switches_by_group() -> Vec<(String, u64)> { - let mut groups: Vec<(String, u64)> = Vec::new(); - if let Ok(tasks) = std::fs::read_dir("/proc/self/task") { - for task in tasks.flatten() { - let path = task.path(); - let comm = std::fs::read_to_string(path.join("comm")).unwrap_or_default(); - let status = std::fs::read_to_string(path.join("status")).unwrap_or_default(); - let switches: u64 = status - .lines() - .find_map(|line| line.strip_prefix("voluntary_ctxt_switches:")) - .and_then(|n| n.trim().parse().ok()) - .unwrap_or(0); - let group = group_of(comm.trim()).to_owned(); - match groups.iter_mut().find(|(n, _)| *n == group) { - Some((_, total)) => *total += switches, - None => groups.push((group, switches)), - } - } - } - groups -} - -fn idle_wakes(device: &Device) { - let queue = device.new_command_queue().unwrap(); - let target = device.new_buffer(16, ResourceOptions::shared()).unwrap(); - let signal = Arc::new(Signal::default()); - let signalled = Arc::clone(&signal); - let command_buffer = tiny(&queue, &target, (Callback::Completed, true), move |after| { - signalled.set(after) - }); - command_buffer.commit().unwrap(); - signal.take(); - command_buffer.wait_until_completed().unwrap(); - std::thread::sleep(Duration::from_millis(300)); - let (before, counts) = (switches_by_group(), device.work_counts()); - std::thread::sleep(Duration::from_secs_f64(IDLE_SECONDS)); - let (after, later) = (switches_by_group(), device.work_counts()); - if !after.is_empty() { - let mut line = "idle wakes a second:".to_owned(); - for (name, count) in &after { - let earlier = before - .iter() - .find(|(n, _)| n == name) - .map_or(0, |(_, n)| *n); - let per = count.saturating_sub(earlier) as f64 / IDLE_SECONDS; - line.push_str(&format!(" {name} {per:.1}")); - } - println!("{line} (voluntary context switches, the main thread's one sleep among them)"); - } - println!( - "idle scheduler a second: {:.1} sleeps, {:.1} ended at the slice", - (later.scheduler_sleeps - counts.scheduler_sleeps) as f64 / IDLE_SECONDS, - (later.scheduler_sleep_slices - counts.scheduler_sleep_slices) as f64 / IDLE_SECONDS, - ); -} - -/// Nanoseconds of CPU by thread group: on Linux each of the process's threads by its name's -/// prefix; elsewhere `other` alone (the process less the calling thread). -fn cpu_by_group() -> Vec<(String, u64)> { - let mut groups: Vec<(String, u64)> = Vec::new(); - let mut add = |name: String, nanos: u64| match groups.iter_mut().find(|(n, _)| *n == name) { - Some((_, total)) => *total += nanos, - None => groups.push((name, nanos)), - }; - if let Ok(tasks) = std::fs::read_dir("/proc/self/task") { - for task in tasks.flatten() { - let path = task.path(); - let comm = std::fs::read_to_string(path.join("comm")).unwrap_or_default(); - let stat = std::fs::read_to_string(path.join("schedstat")).unwrap_or_default(); - let nanos: u64 = stat - .split_whitespace() - .next() - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - add(group_of(comm.trim()).to_owned(), nanos); - } - return groups; - } - // The process's CPU less this thread's. - #[cfg(unix)] - // SAFETY: plain calls with out-parameters of the right types. - let (process, own) = unsafe { - let mut usage: libc::rusage = std::mem::zeroed(); - libc::getrusage(libc::RUSAGE_SELF, &mut usage); - let process = (usage.ru_utime.tv_sec as u64 * 1_000_000 - + usage.ru_utime.tv_usec as u64 - + usage.ru_stime.tv_sec as u64 * 1_000_000 - + usage.ru_stime.tv_usec as u64) - * 1000; - let mut spec: libc::timespec = std::mem::zeroed(); - libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut spec); - ( - process, - spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64, - ) - }; - #[cfg(windows)] - let (process, own) = (process_cpu_nanos(), thread_cpu_nanos()); - add("committer".to_owned(), own); - add("all-but-committer".to_owned(), process.saturating_sub(own)); - groups -} - -/// This thread's CPU so far, in nanoseconds. -#[cfg(unix)] -fn thread_cpu_nanos() -> u64 { - // SAFETY: a plain call with an out-parameter of the right type. - let spec = unsafe { - let mut spec: libc::timespec = std::mem::zeroed(); - libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut spec); - spec - }; - spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64 -} - -/// This thread's CPU so far, in nanoseconds: its kernel and user times (`GetThreadTimes`), in -/// 100 ns units. -#[cfg(windows)] -fn thread_cpu_nanos() -> u64 { - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetThreadTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 -} - -/// The process's CPU so far, every thread's, in nanoseconds: its kernel and user times -/// (`GetProcessTimes`), in 100 ns units. -#[cfg(windows)] -fn process_cpu_nanos() -> u64 { - use windows_sys::Win32::Foundation::FILETIME; - use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; - let mut times = [FILETIME::default(); 4]; - let [created, exited, kernel, user] = &mut times; - // SAFETY: this process's pseudo-handle, and four `FILETIME`s for the call to fill. - let read = unsafe { GetProcessTimes(GetCurrentProcess(), created, exited, kernel, user) }; - assert_ne!(read, 0, "GetProcessTimes"); - let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime); - (ticks(kernel) + ticks(user)) * 100 -} - -/// The CPU each group spent between `before` and `after`, per command buffer, in microseconds. -fn print_cpu(label: &str, before: &[(String, u64)], after: &[(String, u64)], count: usize) { - let mut line = format!("{label}:"); - for (name, nanos) in after { - let earlier = before - .iter() - .find(|(n, _)| n == name) - .map_or(0, |(_, n)| *n); - let per = (nanos.saturating_sub(earlier)) as f64 / 1e3 / count as f64; - line.push_str(&format!(" {name} {per:.2}")); - } - println!("{line} (us of CPU per command buffer)"); -} - -fn cpu(device: &Device, callback: Callback) { - let queue = device.new_command_queue().unwrap(); - let target = device.new_buffer(16, ResourceOptions::shared()).unwrap(); - // Warm. - for _ in 0..200 { - commit(&tiny(&queue, &target, (callback, true), |_| {})); - } - std::thread::sleep(Duration::from_millis(200)); - let before = cpu_by_group(); - let start = Instant::now(); - let mut count = 0; - while start.elapsed().as_secs_f64() < RATE_SECONDS { - commit(&tiny(&queue, &target, (callback, true), |_| {})); - count += 1; - } - let elapsed = start.elapsed().as_secs_f64(); - let after = cpu_by_group(); - println!( - "cpu {:<9} {:.0} command buffers a second ({count} in {elapsed:.2} s)", - callback.name(), - count as f64 / elapsed - ); - print_cpu( - &format!("cpu {:<9}", callback.name()), - &before, - &after, - count, - ); - let last = queue.command_buffer().unwrap(); - last.commit().unwrap(); - last.wait_until_completed().unwrap(); -} - -fn empty(device: &Device) { - let queue = device.new_command_queue().unwrap(); - for gap in [0, 300] { - let mut samples = Vec::with_capacity(ROUNDS); - for round in 0..ROUNDS + 50 { - idle(gap); - let command_buffer = queue.command_buffer().unwrap(); - let committed = Instant::now(); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed().unwrap(); - if round >= 50 { - samples.push(committed.elapsed().as_secs_f64() * 1e6); - } - } - let (p50, p90, p99) = percentiles(&mut samples); - println!( - "empty commit and wait, gap {gap:>4} us: p50 {p50:7.1} p90 {p90:7.1} p99 {p99:7.1} us" - ); - } - let before_counts = device.work_counts(); - let before = cpu_by_group(); - let start = Instant::now(); - let mut count = 0; - while start.elapsed().as_secs_f64() < RATE_SECONDS { - queue.command_buffer().unwrap().commit().unwrap(); - count += 1; - } - let elapsed = start.elapsed().as_secs_f64(); - let after = cpu_by_group(); - let last = queue.command_buffer().unwrap(); - last.commit().unwrap(); - last.wait_until_completed().unwrap(); - let after_counts = device.work_counts(); - println!( - "empty never waited: {:.0} command buffers a second ({count} in {elapsed:.2} s), {} queue submissions", - count as f64 / elapsed, - after_counts.queue_submissions - before_counts.queue_submissions - ); - print_cpu("empty never waited", &before, &after, count); -} - -/// The cpu shape on `threads` threads at once, each with a queue of its own. -fn threads(device: &Device, threads: usize) { - let queues: Vec<(CommandQueue, Buffer)> = (0..threads) - .map(|_| { - let queue = device.new_command_queue().unwrap(); - let target = device.new_buffer(16, ResourceOptions::shared()).unwrap(); - (queue, target) - }) - .collect(); - for (queue, target) in &queues { - for _ in 0..200 { - commit(&tiny(queue, target, (Callback::Completed, true), |_| {})); - } - } - std::thread::sleep(Duration::from_millis(200)); - let before = cpu_by_group(); - let start = Instant::now(); - // Each committing thread's own CPU, read before it ends (its schedstat goes with it). - let (count, committers): (usize, u64) = std::thread::scope(|scope| { - let running: Vec<_> = (queues.iter()) - .map(|(queue, target)| { - scope.spawn(move || { - let (mut count, began) = (0, thread_cpu_nanos()); - while start.elapsed().as_secs_f64() < RATE_SECONDS { - commit(&tiny(queue, target, (Callback::Completed, true), |_| {})); - count += 1; - } - (count, thread_cpu_nanos() - began) - }) - }) - .collect(); - (running.into_iter()) - .map(|thread| thread.join().unwrap()) - .fold((0, 0), |(count, nanos), (more, spent)| { - (count + more, nanos + spent) - }) - }); - let elapsed = start.elapsed().as_secs_f64(); - let after = cpu_by_group(); - println!( - "threads {threads}: {:.0} command buffers a second ({count} in {elapsed:.2} s), \ - committing threads {:.2} us of CPU per command buffer", - count as f64 / elapsed, - committers as f64 / 1e3 / count as f64 - ); - print_cpu(&format!("threads {threads}"), &before, &after, count); - for (queue, _) in &queues { - let last = queue.command_buffer().unwrap(); - last.commit().unwrap(); - last.wait_until_completed().unwrap(); - } -} - -fn main() { - let device = Device::system_default().unwrap(); - println!("device: {}", device.name()); - let what = std::env::args().nth(1).unwrap_or_else(|| "all".to_owned()); - let seen = std::env::args().any(|arg| arg == "--seen"); - let bare = std::env::args().any(|arg| arg == "--bare"); - let at_commit = std::env::args().any(|arg| arg == "--at-commit"); - AT_COMMIT.store(at_commit, Ordering::Relaxed); - let checked = std::env::args().any(|arg| arg == "--checked"); - CHECKED.store(checked, Ordering::Relaxed); - println!( - "committed with {}{}", - if at_commit { - "commit_and_submit" - } else { - "commit" - }, - if checked { - ", each with a submission check" - } else { - "" - } - ); - let callbacks: &[Callback] = match seen { - true => &[Callback::Completed, Callback::Seen], - false => &[Callback::Completed], - }; - if what == "latency" || what == "all" { - for &callback in callbacks { - latency(&device, callback, true); - } - if bare { - for &callback in callbacks { - latency(&device, callback, false); - } - } - } - if what == "cross" || what == "all" { - for &callback in callbacks { - for shared in [true, false] { - cross(&device, callback, shared); - } - } - } - if what == "cpu" || what == "all" { - for &callback in callbacks { - cpu(&device, callback); - } - } - if what == "threads" || what == "all" { - for count in [1, 8] { - threads(&device, count); - } - } - if what == "empty" || what == "all" { - empty(&device); - } - if what == "idle" || what == "all" { - idle_wakes(&device); - } -} diff --git a/crates/metal2vulkan-runtime/src/address.rs b/crates/metal2vulkan-runtime/src/address.rs deleted file mode 100644 index 46b388cd2..000000000 --- a/crates/metal2vulkan-runtime/src/address.rs +++ /dev/null @@ -1,795 +0,0 @@ -//! The device's Metal address space. -//! -//! Vulkan cannot place a buffer at an address the caller picks, and the translated shaders do -//! not need it to: a pointer value is the Metal address the binder was told (the resident table). -//! So each device hands every buffer a range of its own 64-bit Metal address space, and the program -//! sees those values everywhere: `gpu_address`, pointers a kernel derives, compares, stores, and -//! the CPU reads back. Vulkan device addresses are never shown. -//! -//! - **The space** is `[2^32, 2^47)`: never 0 (the null pointer), above every 32-bit value, and -//! past every address Metal pinned (on an M3 Max and an M4 every pin at 2^42 or above failed). -//! Ranges the runtime picks are aligned and sized to Metal's 16-KiB page, as Metal places -//! buffers on Apple silicon. -//! - **Pinned placement** (`setPinnedGPUAddress:`, a runtime extension; measured on an M3 Max and -//! an M4, and by the consumer's M3 Max probes): a buffer or heap made at a caller's address -//! has exactly that address, at any byte of a 32-KiB granule's first page, and holds Metal's span -//! of it: the pages its bytes touch and one guard page after them, rounded up to 32 KiB (2 pages -//! for 1, 4 for 2 or 3, 6 for 4 or 5, 66 for 64 or 65), so the page before a pinned range cannot -//! start another pin either. A pin whose first page is not a 32-KiB granule's (`OffGranule`), -//! whose span meets bytes another resource holds, or that leaves the space, is refused -//! ([`PlacementConflict`]); Metal answers nil for each and aliases nothing. A released pin frees -//! its whole span, as Metal's does, before a later making takes a range, whichever thread let -//! go of the pinned resource last: a making in the Metal space waits for the runtime's passing -//! holds of the program's textures, one of which may hold the last handle of a texture over the -//! resource (`Device::address_space_for`; `resource_ids.rs`, **Passing holds**). Metal's own process layout refused some ranges inside the -//! space (below 2^36, 2^39, just below 2^40, 2^42 and above); that is no contract, and the -//! runtime pins any free range of the space. -//! - **A shared range** (the consumer's ask C3): a no-copy buffer made over the same first byte of -//! host memory as a live no-copy buffer, no longer than it (`BufferDescriptor::range_of`), -//! answers that buffer's address and holds its range with it, as Metal answers one IOSurface's -//! address for every buffer over the surface (the consumer's probe on an M3 Max under macOS -//! 26.7). The range is free once every buffer holding it is gone; each one's range token drops -//! with it. -//! - **Pools and their slots** (the consumer's ask "sub-page placement", its `vaprobe smallpool` -//! and `texpool2` probes on an M3 Max under macOS 26.7). Metal makes each buffer of its own -//! memory shorter than a page in a pool of 0x20000 bytes, a plain range of the space, at a -//! 256-byte-aligned slot of `round_up(length, 256)` bytes, so buffers share pages. A caller that -//! models those pools reserves each one (`Device::reserve_address_pool`, a runtime extension): -//! the pool holds the span a pin of its length holds (its pages, one guard page, rounded up to 32 -//! KiB), so no other range, pin or pick lands in it while it lives. A buffer placed in a slot of -//! it (`BufferDescriptor::with_pool_slot`) has the pool's address plus the slot's offset, and -//! holds only `round_up(length, 256)` bytes of the pool, with no guard and no page rounding; a -//! slot whose offset is not a multiple of 256 bytes (`OffSlot`), that passes the pool's end -//! (`OutsidePool`), or that meets a live slot (`Held`), is refused. The slot is free once its -//! buffer is gone (its range token drops then). A dropped pool's span stays held until the last -//! buffer in its slots is gone. Which slot a buffer takes, and when a pool is needed or goes, is -//! the caller's to model, as are Metal's own allocations in its pools. -//! - **Outside the space**: the runtime's own buffers (the index buffers it generates, staging for -//! fills, uploads and copies, scratch, tile memory, shadows, and the buffers of the device's -//! in-place check, `in_place_check.rs`, which runs on a thread of its own while the program makes -//! its resources) take ranges of a second space above it, `[2^47, 2^48)`, so a program's buffer -//! addresses never depend on whether or when the runtime's own work runs or completes, as -//! Metal's own allocations never move a program's, and no pin of the program's meets them. So -//! does the storage of a program's object whose address Metal shows no program: a texture -//! buffer's texels the device makes (`newTextureWithDescriptor:`, -//! `newSharedTextureWithDescriptor:`) and a visible function table's words, each reached -//! through its binding or its `gpuResourceID`, never at an address of the space, as a texture -//! of its own memory takes none of it. The space holds only what Metal gives an address (a -//! buffer's `gpuAddress`; a heap's range, which its resources lie in) and the pools a caller -//! reserves. -//! [`AddressPlacement::Outside`], a runtime extension, puts a caller's helper buffer there too. A -//! pin never reaches it. -//! - **Indirect command buffers' records**: an indirect command buffer's ID is the one Metal's pool -//! of their own space hands out, from 1, as Metal's `gpuResourceID` is (an M3 Max and an M4; the -//! pool's rule, first 32 IDs, is `resource_ids.rs`'), or the one it is placed at, and its records -//! start at `records_address` of it, `2^63 + id * 2^31`, the address a translated kernel -//! encoding through the ID reaches: records of more than 2^31 bytes run past later IDs' starts, -//! which the kernel's search tells apart, as it finds records only at their start. So the -//! records take no Metal address, as Metal's indirect command buffers take none of its buffers' -//! (four of 1024 commands moved no buffer made after them). -//! - **Records IDs** (the M4 probe, plain Metal). The buffer holds its ID -//! ([`RecordsId`]), not its records' memory: the ID is free again once the buffer and every -//! command that holds it are gone, a compute or render execution and a `useResource` until their -//! command buffer completes or is dropped uncommitted, while a blit's copy, reset or optimize -//! holds only the records' memory (Metal handed a blit's buffer's ID out again while the blit -//! waited). A placed buffer's ID is not the pool's: plain allocation neither skips it nor gets it -//! back, but it counts as an allocation for a later reservation. Each ID has one slot, the buffer -//! last made with it, placed or plain, which a kernel encoding through the ID reaches; once that -//! buffer is gone the ID reaches none, even while an earlier buffer with it lives -//! ([`AddressSpace::holds_records_slot`]). - -use super::device::{lock, Device}; -use super::error::{internal, Error, MemoryKind}; -use super::exit_guard; -use super::program_objects::ProgramObject; -use super::range::RangeAllocator; -use super::resource_ids::Pool; -use metal2vulkan::bind::indirect_commands::{records_address, RECORDS_ID_LIMIT}; -use std::collections::BTreeMap; -use std::mem::ManuallyDrop; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard}; - -/// A Metal GPU address: what `gpuAddress` answers and what a kernel's pointers hold. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct GpuAddress(pub u64); - -/// The lowest address the space hands out. -pub(super) const SPACE_BASE: u64 = 1 << 32; -/// The end of the space. -pub(super) const SPACE_END: u64 = 1 << 47; -/// The end of the space outside the Metal one, `[SPACE_END, OUTSIDE_END)` (module docs). -pub(super) const OUTSIDE_END: u64 = 1 << 48; -/// The alignment and size granule of every range: Metal's page on Apple silicon. -pub(super) const PAGE: u64 = 16 << 10; -/// The granule of a pinned range: its first page starts one, and its span is a multiple of it. -pub(super) const GRANULE: u64 = 2 * PAGE; -/// The alignment and size granule of a pool's slot: Metal's for a buffer shorter than a page. -pub(super) const SLOT: u64 = 0x100; - -/// Where a buffer or heap goes in the Metal address space: where the runtime picks, or at the -/// caller's address (`setPinnedGPUAddress:`, a runtime extension), or outside the space (a -/// runtime extension, no Metal counterpart). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum AddressPlacement { - /// A range the runtime picks. - #[default] - Any, - /// At this address, which the resource's `gpu_address` then answers. - At(GpuAddress), - /// A range the runtime picks outside the Metal address space, `[2^47, 2^48)`, where the - /// runtime's own buffers lie: for a caller's helper buffer that must take no Metal address, - /// so no Metal buffer's address depends on it. Its `gpu_address` answers that range's - /// address, which no Metal resource shares and no pin reaches. A runtime extension: Metal has - /// no such placement. - Outside, -} - -/// Where the runtime places a buffer it makes: as a placement says, or as the records of the -/// indirect command buffer that holds records ID `id`, at `records_address` of it (module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Place { - At(AddressPlacement), - Records(u64), - /// At `address`, sharing `held`, a live buffer's range (module docs). - Shared { - address: GpuAddress, - held: Held, - }, - /// At `offset` in the pool reserved at `pool`, the descriptor's placement being `placement` - /// (module docs). - InPool { - pool: u64, - offset: u64, - placement: AddressPlacement, - }, -} - -impl From for Place { - fn from(placement: AddressPlacement) -> Place { - Place::At(placement) - } -} - -impl Place { - /// Whether a resource placed here takes bytes of the Metal space: a range the runtime picks - /// there, a pin, a pool's slot. A shared range is its live holder's, which the caller holds; - /// records and the space outside take none. - fn takes_metal_bytes(self) -> bool { - matches!( - self, - Place::At(AddressPlacement::Any | AddressPlacement::At(_)) | Place::InPool { .. } - ) - } -} - -impl Device { - /// The device's address space, locked, for a placement at `place` (a resource's range, or a - /// pool's span). Where it takes bytes of the Metal space, once every passing hold of the - /// device ended (`resource_ids.rs`, **Passing holds**): the bytes a resource the program - /// released held are free by then, whichever thread let go of it last, as Metal's release - /// freed them, so a pin or a pool's slot where they lay is made, and a range the runtime - /// picks does not depend on when the runtime's own work let go. A making waits holding none - /// of the runtime's locks, and on a thread inside a passing hold not at all. - pub(super) fn address_space_for( - &self, - place: impl Into, - ) -> MutexGuard<'_, AddressSpace> { - if place.into().takes_metal_bytes() { - self.shared().passing_holds.wait(); - } - lock(&self.shared().addresses) - } -} - -/// A caller's token for a resource's range of the Metal address space (a runtime extension, no -/// Metal counterpart): `BufferDescriptor::range_token`, `Device::new_heap_with_range_token`, -/// `Device::new_heap_with_bytes_no_copy_and_range_token`, and -/// `Device::new_texture_with_range_token` and `Device::new_shared_texture_with_range_token`. The -/// runtime drops it right after it frees the resource, at or before the point Metal frees a -/// released resource's range. Metal never frees that range inside a completed handler of the last -/// command buffer that held it, which is a guarantee: 4,800 of 4,800 ICBs and 4,800 of 4,800 -/// buffers held their ID and `gpuAddress` there (the consumer's probe on an Apple M3 Max, macOS -/// 27.0.1). After those handlers it USUALLY frees before that command buffer's waiters wake, but -/// that is its usual order and not a rule: 10 of 8,400 ICBs were still held under load, coming back -/// up to 884 us later, against 0 of 6,000 unloaded, and a dispatch-bound buffer's `gpuAddress` was -/// still held in 16 of 3,000 unloaded and 19 of 8,400 loaded runs, up to 3.9 ms after the wait. So -/// the runtime's own order -- status, the completed handlers, the releases, then the gate that -/// wakes the waiters (`CommandBufferShared::complete`) -- is the deterministic side of a race Metal -/// leaves open, and is within Metal's behaviour rather than a copy of a rule of Metal's. A caller -/// that must see the range free waits for the handlers, which is what Metal guarantees, and not for -/// a waiter to wake. It drops with no runtime lock held, so a -/// creation at the range from its drop on succeeds; on the thread that drops the resource's last -/// holder (the program's, or a runtime thread that runs a command buffer's completed handlers, as -/// the program's code there, a panic in it caught, as a no-copy buffer's deallocator), an -/// uncommitted command buffer's holds included; before a refused creation returns; and never where -/// the runtime leaves the resource to the process's exit (leaked with it). A heap's token goes with -/// the heap's own bytes, once the heap and every resource placed in it are gone; a sparse heap's -/// once the heap, its textures and the command buffers that hold them are gone. A texture's goes as -/// Metal frees the texture: once the texture, every view and texture opened from it, and the -/// command buffers that hold any of them are gone, whatever the runtime keeps of its image after -/// that (for a command buffer committed before it went that may reach it by its resource ID, or the -/// batch that took its first move), as Metal frees a released texture's range while a command -/// buffer that only names it in an argument buffer still runs (an Apple M4). -pub type RangeToken = Box; - -/// Where a resource keeps its caller's [`RangeToken`], held as the program's object -/// (`program_objects.rs`): set once as the resource is made ([`keep`](Self::keep)), and dropped by [`release`](Self::release), which the resource's -/// teardown calls once its range is free. Never dropped otherwise: a resource the runtime leaves -/// to the process's exit leaks its token with it (`ManuallyDrop`). -#[derive(Default)] -pub(super) struct KeptToken(ManuallyDrop>>>); - -impl KeptToken { - /// Keep `token`. Internal where one is kept already: no creator gives two. - pub(super) fn keep(&self, token: RangeToken) -> Result<(), Error> { - let mut kept = lock(&self.0); - if kept.is_some() { - return Err(internal("a resource's range token kept twice")); - } - *kept = Some(ProgramObject::new(token)); - Ok(()) - } - - /// Hand the token kept, if any, to `to`, which keeps none: a buffer carried to its device's - /// next generation (`device/carry.rs`), whose parts there hold the buffer's range last. - pub(super) fn hand_to(&self, to: &KeptToken) { - let token = lock(&self.0).take(); - if let Some(token) = token { - *lock(&to.0) = Some(token); - } - } - - /// Drop the token kept, if any: the resource's range is free, outside its teardown's exit - /// section and with no runtime lock held, so a creation at the range from its drop on - /// succeeds. Its drop is the program's code, which a runtime thread (a command buffer's - /// completion) runs as such, a panic in it caught, as a deallocator (`exit_guard::program`). - /// Left to the process's exit (leaked) once the process is exiting, as the resource is. - pub(super) fn release(&self) { - if exit_guard::closed() { - return; - } - let token = lock(&self.0).take(); - if let Some(token) = token { - exit_guard::program_release(move || drop(token)); - } - } -} - -/// A texture's [`RangeToken`], kept for the texture objects over its image or texels (the -/// texture, its views, the textures opened from its handles): dropped as the last of them goes, -/// as Metal frees the texture, whatever the runtime keeps of the image or texels after that (a -/// gone texture's image retired for the command buffers that may reach it by its resource ID, -/// the batch that took its first move). A command buffer holds the texture objects it uses, so -/// a texture it uses goes with it. -#[derive(Default)] -pub(super) struct ObjectsToken { - objects: AtomicUsize, - token: KeptToken, -} - -impl ObjectsToken { - /// A texture object over the image or texels was made. - pub(super) fn object_made(&self) { - self.objects.fetch_add(1, Ordering::Relaxed); - } - - /// How many texture objects are over the image or texels now. - pub(super) fn count(&self) -> usize { - self.objects.load(Ordering::Relaxed) - } - - /// Keep `token`, as [`KeptToken::keep`]. - pub(super) fn keep(&self, token: RangeToken) -> Result<(), Error> { - self.token.keep(token) - } - - /// Hand the token kept, if any, to `to`, as [`KeptToken::hand_to`]: a texture's parts on a lost - /// generation going at its rest, its parts on the next holding its range last - /// (`texture/carry.rs`). - pub(super) fn hand_token_to(&self, to: &ObjectsToken) { - self.token.hand_to(&to.token); - } - - /// A texture object over the image or texels went, its teardown done and no lock held: the - /// token drops with the last ([`KeptToken::release`]). Whether it was the last (a heap - /// texture's range then goes back to its heap). - pub(super) fn object_gone(&self) -> bool { - let last = self.objects.fetch_sub(1, Ordering::AcqRel) == 1; - if last { - self.token.release(); - } - last - } -} - -/// Bytes of the Metal address space. No Metal counterpart: a placement refusal's range. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct AddressRange { - /// The first byte. - pub start: GpuAddress, - /// The bytes. - pub length: u64, -} - -impl AddressRange { - pub(super) fn of(start: u64, length: u64) -> AddressRange { - AddressRange { - start: GpuAddress(start), - length, - } - } -} - -/// A pinned address the space cannot honour (`Error::PlacementConflict`). `requested` is the -/// range the pin needs: the pages its bytes touch and the guard page after them, rounded up to -/// 32 KiB (module docs); for a buffer in a pool's slot, the slot's bytes. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PlacementConflict { - /// The range meets bytes another resource holds; `held` is the first run of held bytes it - /// meets (of one resource or of several beside each other). - Held { - /// The range the pin needs. - requested: AddressRange, - /// The first run of held bytes it meets. - held: AddressRange, - }, - /// The range leaves the space, `[2^32, 2^47)`. - OutsideSpace { - /// The range the pin needs. - requested: AddressRange, - }, - /// The pin's first page is not the first of a 32-KiB granule: Metal pins none there (an - /// Apple M4 and an M3 Max answered nil for every such pin). - OffGranule { - /// The range the pin needs. - requested: AddressRange, - }, - /// A buffer made to share another's range (`BufferDescriptor::range_of`) that cannot share - /// it: it is not a no-copy buffer over the same first byte of host memory as the other, the - /// other is not a no-copy buffer of its own range, it is longer than the other, or its - /// placement names another address. A runtime extension: Metal has no such call. - Unshared { - /// The other buffer's bytes. - held: AddressRange, - }, - /// A buffer made in a pool's slot (`BufferDescriptor::with_pool_slot`) whose offset in the - /// pool is not a multiple of 256 bytes, where Metal places no buffer in its pools, or whose - /// descriptor's placement names another address. A runtime extension: Metal has no such call. - OffSlot { - /// The bytes the slot needs: from the pool's address plus the offset, the buffer's length - /// rounded up to 256 bytes. - requested: AddressRange, - /// The pool's bytes. - pool: AddressRange, - }, - /// A buffer made in a pool's slot whose bytes pass the pool's end. A runtime extension. - OutsidePool { - /// The bytes the slot needs. - requested: AddressRange, - /// The pool's bytes. - pool: AddressRange, - }, -} - -/// Bytes of the space a resource holds until it is gone ([`AddressSpace::free`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Held { - start: u64, - size: u64, - /// The address of the pool whose slot the bytes are; `None` for a range of the space. - pool: Option, -} - -impl Held { - /// A range of the space (or of the space outside it), no pool's slot. - fn range(start: u64, size: u64) -> Held { - Held { - start, - size, - pool: None, - } - } -} - -/// One device's Metal address space, the space outside it, and the indirect command buffers' -/// records IDs (module docs). -#[derive(Debug)] -pub(super) struct AddressSpace { - ranges: RangeAllocator, - outside: RangeAllocator, - records: RecordIds, - /// Each shared range's holders past its first, by its start: [`free`](Self::free) frees the - /// range only once none is left. - shares: BTreeMap, - /// Each reserved pool, by its address (module docs). - pools: BTreeMap, -} - -/// A reserved pool (module docs): the span it holds of the space, its length, its slots, and -/// whether its caller let it go, its span then free once no slot is held. -#[derive(Debug)] -struct SlotPool { - span: Held, - length: u64, - slots: RangeAllocator, - released: bool, -} - -/// The records IDs (module docs): Metal's pool of indirect command buffer IDs, its first 32 IDs -/// (`resource_ids.rs`), and each held ID's slot. -#[derive(Debug)] -struct RecordIds { - /// The plain IDs. - pool: Pool, - /// Each held ID's slot: the serial of the buffer last made with it. - slots: BTreeMap, - /// The serial of the buffer made last. - serial: u64, -} - -/// An indirect command buffer's hold on its records ID (module docs): the ID, the buffer's -/// serial, which orders the buffers made with one ID, and whether plain allocation handed it out. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct RecordsId { - /// The ID: what `gpuResourceID` answers. - pub(super) id: u64, - serial: u64, - plain: bool, -} - -impl RecordIds { - /// A new buffer's ID, now held and its slot's: `placed`, or the one Metal hands out next; - /// `None` when that is [`RECORDS_ID_LIMIT`] or more. - fn take(&mut self, placed: Option) -> Option { - let (id, plain) = match placed { - Some(id) => { - self.pool.start(); - (id, false) - } - None if self.pool.next() >= RECORDS_ID_LIMIT => return None, - None => (self.pool.take(), true), - }; - self.serial += 1; - self.slots.insert(id, self.serial); - Some(RecordsId { - id, - serial: self.serial, - plain, - }) - } - - /// `held` gone: its slot empty where it was the slot's, and a plain ID free again. - fn give(&mut self, held: RecordsId) { - if self.slots.get(&held.id) == Some(&held.serial) { - self.slots.remove(&held.id); - } - if held.plain { - self.pool.give(held.id); - } - } -} - -impl AddressSpace { - /// The whole space free, the space outside it, and every records ID. - pub(super) fn new() -> AddressSpace { - AddressSpace { - ranges: RangeAllocator::new(SPACE_BASE, SPACE_END), - outside: RangeAllocator::new(SPACE_END, OUTSIDE_END), - records: RecordIds { - pool: Pool::new(32), - slots: BTreeMap::new(), - serial: 0, - }, - shares: BTreeMap::new(), - pools: BTreeMap::new(), - } - } - - /// The bytes a resource of `length` bytes holds of the space: whole pages, at least one. - pub(super) fn span(length: u64) -> Option { - length.max(1).checked_next_multiple_of(PAGE) - } - - /// A free range of the runtime's choice for a resource of `length` bytes, now held: its - /// start, and what to free; `None` when the space is full. - pub(super) fn allocate(&mut self, length: u64) -> Option<(GpuAddress, Held)> { - let size = Self::span(length)?; - let start = self.ranges.allocate(size, PAGE)?; - Some((GpuAddress(start), Held::range(start, size))) - } - - /// [`AddressSpace::allocate`] outside the Metal space (module docs). - pub(super) fn allocate_outside(&mut self, length: u64) -> Option<(GpuAddress, Held)> { - let size = Self::span(length)?; - let start = self.outside.allocate(size, PAGE)?; - Some((GpuAddress(start), Held::range(start, size))) - } - - /// The range a resource of `length` bytes pinned at `address` needs, now held: the pages - /// its bytes touch and the guard page after them, rounded up to 32 KiB (module docs). - pub(super) fn pin( - &mut self, - address: GpuAddress, - length: u64, - ) -> Result { - let start = address.0 - address.0 % PAGE; - let requested = address - .0 - .checked_add(length.max(1)) - .and_then(|end| end.checked_next_multiple_of(PAGE)) - .and_then(|end| span_end(start, end)) - .map(|end| AddressRange::of(start, end - start)); - let Some(requested) = requested else { - return Err(PlacementConflict::OutsideSpace { - requested: AddressRange::of(start, u64::MAX - start), - }); - }; - if start < SPACE_BASE || requested.length > SPACE_END.saturating_sub(start) { - return Err(PlacementConflict::OutsideSpace { requested }); - } - if !start.is_multiple_of(GRANULE) { - return Err(PlacementConflict::OffGranule { requested }); - } - self.ranges - .allocate_at(start, requested.length) - .map_err(|(from, length)| PlacementConflict::Held { - requested, - held: AddressRange::of(from, length), - })?; - Ok(Held::range(start, requested.length)) - } - - /// Keep indirect command buffer IDs `ids` from the records' pool for good (`Pool::reserve`, - /// the IDs below [`RECORDS_ID_LIMIT`]): false, reserving nothing, once the pool handed out - /// an ID or took a reservation. - pub(super) fn reserve_records(&mut self, ids: &[u64]) -> bool { - self.records.pool.reserve(ids.iter().copied()) - } - - /// Whether the records' pool handed out an ID or took a reservation: a reservation is - /// ignored then (`Pool::started`). - pub(super) fn records_started(&self) -> bool { - self.records.pool.started() - } - - /// A new indirect command buffer's records ID, now held and its slot's (module docs): - /// `placed`, or the one Metal hands out next; `None` when that is [`RECORDS_ID_LIMIT`] or - /// more. The buffer gives it back with [`give_records_id`](Self::give_records_id). - pub(super) fn take_records_id(&mut self, placed: Option) -> Option { - self.records.take(placed) - } - - /// `held`'s buffer gone: its slot empty where it was the slot's, and a plain ID free again. - pub(super) fn give_records_id(&mut self, held: RecordsId) { - self.records.give(held) - } - - /// Whether `held`'s buffer holds its ID's slot: what a kernel encoding through the ID - /// reaches (module docs). - pub(super) fn holds_records_slot(&self, held: RecordsId) -> bool { - self.records.slots.get(&held.id) == Some(&held.serial) - } - - /// The records of an indirect command buffer of `length` bytes holding records ID `id`: from - /// `records_address` of it, of any length that ends below 2^64 (2^62 bytes past the last - /// ID's start). `None` for an ID of [`RECORDS_ID_LIMIT`] or more, or a longer length. - fn records(id: u64, length: u64) -> Option<(GpuAddress, Held)> { - let size = Self::span(length)?; - if id >= RECORDS_ID_LIMIT || records_address(id).checked_add(size).is_none() { - return None; - } - let start = records_address(id); - Some((GpuAddress(start), Held::range(start, size))) - } - - /// The address and held bytes of a resource of `length` bytes at `place`: refused when the - /// space is full (`OutOfMemory`) or the pin cannot be honoured (`PlacementConflict`). - pub(super) fn place( - &mut self, - place: impl Into, - length: u64, - ) -> Result<(GpuAddress, Held), Error> { - let placement = match place.into() { - Place::At(placement) => placement, - Place::Records(id) => { - return Self::records(id, length).ok_or(Error::OutOfMemory(MemoryKind::Device)) - } - // The range's holder lives (its caller holds it), so the range is held still. - Place::Shared { address, held } => { - *self.shares.entry(held.start).or_default() += 1; - return Ok((address, held)); - } - Place::InPool { - pool, - offset, - placement, - } => return self.slot(pool, offset, placement, length), - }; - match placement { - AddressPlacement::Any => self - .allocate(length) - .ok_or(Error::OutOfMemory(MemoryKind::Device)), - AddressPlacement::At(address) => self - .pin(address, length) - .map(|held| (address, held)) - .map_err(Error::PlacementConflict), - AddressPlacement::Outside => self - .allocate_outside(length) - .ok_or(Error::OutOfMemory(MemoryKind::Device)), - } - } - - /// Give back what [`AddressSpace::allocate`], [`AddressSpace::allocate_outside`] or - /// [`AddressSpace::pin`] held. Records hold nothing of the spaces: their buffer gives its - /// ID back ([`give_records_id`](Self::give_records_id)). - pub(super) fn free(&mut self, held: Held) { - // A shared range stays while another buffer holds it. - if let Some(others) = self.shares.get_mut(&held.start) { - *others -= 1; - if *others == 0 { - self.shares.remove(&held.start); - } - return; - } - // A slot goes back to its pool, and a released pool's span with its last slot. - if let Some(address) = held.pool { - if let Some(pool) = self.pools.get_mut(&address) { - pool.slots.free(held.start, held.size); - if pool.released && pool.slots.used() == 0 { - self.drop_pool(address); - } - } - return; - } - self.give_back_range(held); - } - - /// Give back a range of the space or of the space outside it. - fn give_back_range(&mut self, held: Held) { - if held.start < SPACE_END { - self.ranges.free(held.start, held.size); - } else if held.start < OUTSIDE_END { - self.outside.free(held.start, held.size); - } - } - - /// Reserve a pool of `length` bytes at `placement` (module docs): its address. It holds the - /// span a pin of `length` bytes holds, at the address asked (refused as [`pin`](Self::pin) - /// refuses it), or at a 32-KiB granule the runtime picks in the space or outside it - /// (`OutOfMemory` when none is free). Its caller lets it go with - /// [`release_pool`](Self::release_pool). - pub(super) fn reserve_pool( - &mut self, - placement: AddressPlacement, - length: u64, - ) -> Result { - let picked = |space: &mut RangeAllocator| { - let pages = length.max(1).checked_next_multiple_of(PAGE)?; - let size = span_end(0, pages)?; - space - .allocate(size, GRANULE) - .map(|start| (GpuAddress(start), Held::range(start, size))) - }; - let (address, span) = match placement { - AddressPlacement::Any => picked(&mut self.ranges), - AddressPlacement::Outside => picked(&mut self.outside), - AddressPlacement::At(address) => { - let span = self - .pin(address, length) - .map_err(Error::PlacementConflict)?; - Some((address, span)) - } - } - .ok_or(Error::OutOfMemory(MemoryKind::Device))?; - // The span holds the pool's bytes: `pin` and `picked` hold at least `length` bytes from - // the address. - let slots = RangeAllocator::new(address.0, address.0 + length); - let pool = SlotPool { - span, - length, - slots, - released: false, - }; - self.pools.insert(address.0, pool); - Ok(address) - } - - /// The caller let the pool reserved at `address` go: its span is free now where no slot of it - /// is held, else once the last is. - pub(super) fn release_pool(&mut self, address: GpuAddress) { - let Some(pool) = self.pools.get_mut(&address.0) else { - return; - }; - pool.released = true; - if pool.slots.used() == 0 { - self.drop_pool(address.0); - } - } - - /// The pool at `address` gone, its span free. - fn drop_pool(&mut self, address: u64) { - if let Some(pool) = self.pools.remove(&address) { - self.give_back_range(pool.span); - } - } - - /// The slot of a buffer of `length` bytes at `offset` in the pool reserved at `pool`, now - /// held, the descriptor's placement being `placement` (module docs): refused `OffSlot`, - /// `OutsidePool` or `Held` (the first run of held slot bytes it meets). - fn slot( - &mut self, - pool: u64, - offset: u64, - placement: AddressPlacement, - length: u64, - ) -> Result<(GpuAddress, Held), Error> { - let Some(slots) = self.pools.get_mut(&pool) else { - return Err(internal("a slot of a pool not reserved")); - }; - let pool_range = AddressRange::of(pool, slots.length); - let start = pool.saturating_add(offset); - let size = length.max(1).div_ceil(SLOT).saturating_mul(SLOT); - let requested = AddressRange::of(start, size); - let named = match placement { - AddressPlacement::Any => true, - AddressPlacement::At(address) => address.0 == start, - AddressPlacement::Outside => false, - }; - let conflict = if !offset.is_multiple_of(SLOT) || !named { - Some(PlacementConflict::OffSlot { - requested, - pool: pool_range, - }) - } else if offset - .checked_add(size) - .is_none_or(|end| end > pool_range.length) - { - Some(PlacementConflict::OutsidePool { - requested, - pool: pool_range, - }) - } else { - None - }; - if let Some(conflict) = conflict { - return Err(Error::PlacementConflict(conflict)); - } - slots - .slots - .allocate_at(start, size) - .map_err(|(from, length)| { - Error::PlacementConflict(PlacementConflict::Held { - requested, - held: AddressRange::of(from, length), - }) - })?; - let held = Held { - start, - size, - pool: Some(pool), - }; - Ok((GpuAddress(start), held)) - } - - /// Whether no range is held, in the space or outside it, and no records ID. - #[cfg(test)] - pub(super) fn is_empty(&self) -> bool { - self.ranges.is_empty() - && self.outside.is_empty() - && self.records.pool.is_empty() - && self.records.slots.is_empty() - && self.shares.is_empty() - && self.pools.is_empty() - } -} - -/// The end of the span a pinned range of the pages `[start, end)` holds, as Metal holds it: one -/// guard page after them, rounded up to 32 KiB from `start` (module docs); `None` past `u64`. -fn span_end(start: u64, end: u64) -> Option { - let pages = end.checked_add(PAGE)? - start; - start.checked_add(pages.checked_next_multiple_of(GRANULE)?) -} diff --git a/crates/metal2vulkan-runtime/src/address_map.rs b/crates/metal2vulkan-runtime/src/address_map.rs deleted file mode 100644 index 406d421d4..000000000 --- a/crates/metal2vulkan-runtime/src/address_map.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! A texture's address-mode map (a runtime extension): how a texture that presents another format's -//! sampling rules is sampled, and how a command's samplers take it. -//! -//! - **The map** ([`AddressModeMap`], `TextureDescriptor::address_mode_map`): for each -//! `MTLSamplerAddressMode` a sampler states, the mode the texture is sampled with. A texture and -//! its views carry it. The identity map, every texture's default, changes nothing: a command -//! whose stages bind no mapped texture computes nothing here and binds, plans and compiles as -//! it did before the map existed. -//! - **Applied at bind** ([`sampler_maps`]): a runtime sampler at a slot of a stage that samples -//! a mapped texture is bound as the sampler of its mapped modes, its `VkSampler` and the word -//! its slot's specialization reads (`SpecKey::SamplerState`) alike, so every emulation that reads -//! the mode (the linear and bicubic filters by fetches, the gather corners, the border texels) -//! follows with no code of its own. A mapped sampler is one more state of the slot, as binding -//! another sampler there is. -//! - **Constexpr samplers**: a constexpr sampler's state is the pipeline's (its immutable sampler, -//! and the modes its emulations read), so a slot a constexpr sampler samples takes a texture's -//! map through the pipeline variant of the slot (`VariantKey::address_maps`), whose compile maps -//! the sampler's modes; Metal samples a constexpr sampler as a runtime one of its modes. A -//! texture of the identity map keeps every key. -//! - **Refused, typed** (`RuntimeGap::MappedTextureSampling`, naming the map): what cannot follow -//! the map ([`MappedSampling`]): a constexpr sampler whose modes the map sends where a -//! constexpr sampler cannot address, or whose modes are not stated; one sampler slot sampling -//! textures whose maps give it different modes in one stage, whose one state cannot be both; -//! and a mapped texture a function that samples handles (an argument buffer's or a heap's) can -//! reach, whose sampler is read from memory. - -use super::argument_table::ArgumentTable; -use super::error::RuntimeGap; -use super::residency::Residency; -use super::texture::Texture; -use metal2vulkan::bind::{BindState, SamplerDescriptor}; -use metal2vulkan::metal::SamplerAddressMode; -use metal2vulkan::pipeline::{ - BindingSource, HandleClass, PipelineLayout, SamplerRef, SlotClass, SlotRef, Stage, -}; -use std::collections::BTreeMap; - -/// The modes a texture is sampled with, `metal2vulkan`'s (moved there, so a pipeline variant can -/// name it). -pub use metal2vulkan::metal::sampler::AddressModeMap; - -/// How a mapped texture would be sampled that the runtime cannot map at bind -/// (`RuntimeGap::MappedTextureSampling`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum MappedSampling { - /// Through a constexpr sampler whose modes the map sends where a constexpr sampler cannot - /// address (`AddressModeMap::constexpr_mode`: mirror-clamp-to-edge, or a clamp to zero or to - /// the border from another mode), or whose modes the layout does not state. Any other is - /// sampled through its slot's pipeline variant. - ConstexprSampler, - /// Through a runtime sampler slot that samples, in the same stage, a texture whose map gives - /// it other modes: the slot's one state cannot be both. - SharedSamplerSlot, - /// By a function that samples textures through handles (an argument buffer's or a heap's), - /// which can reach the texture, bound at a slot of the command or made resident for it: its - /// sampler is read from memory. - Handles, -} - -/// The address-mode map each runtime sampler slot of one command is bound with: those whose -/// mapped modes differ from the bound sampler's, by slot. Empty for a command that binds no -/// mapped texture. -#[derive(Clone, Debug, Default, PartialEq)] -pub(super) struct SamplerMaps { - maps: BTreeMap, -} - -impl SamplerMaps { - /// `desc`, the sampler bound at `slot`, as the command binds it: its modes mapped where the - /// slot samples a mapped texture. - pub(super) fn sampler(&self, slot: SlotRef, desc: SamplerDescriptor) -> SamplerDescriptor { - match self.maps.get(&slot) { - Some(map) => map.sampler(desc), - None => desc, - } - } - - /// The map the command binds the sampler at `slot` with, where the slot samples a mapped - /// texture. - pub(super) fn map(&self, slot: SlotRef) -> Option { - self.maps.get(&slot).copied() - } - - /// `state`'s samplers as the command binds them, so the plan's specialization reads the - /// mapped words. - pub(super) fn apply(&self, state: &mut BindState) { - for (slot, map) in &self.maps { - let bound = state - .stages - .get_mut(&slot.stage) - .and_then(|table| table.samplers.get_mut(&slot.index)); - if let Some(bound) = bound { - bound.desc = map.sampler(bound.desc); - } - } - } -} - -/// One texture slot of a layout with the sampler it is sampled through. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Pair { - /// A runtime sampler slot of the texture's stage. - Slot { texture: SlotRef, sampler: SlotRef }, - /// A constexpr sampler, with its modes on `s`, `t` and `r` (`None`: a sampler whose modes - /// the layout does not state). - Constexpr { - texture: SlotRef, - modes: Option<[SamplerAddressMode; 3]>, - }, -} - -/// The texture slots `layout` samples, each with its sampler, and whether a function of it -/// samples textures through handles. -pub(super) fn pairs(layout: &PipelineLayout) -> (Vec, bool) { - let mut pairs = Vec::new(); - let mut handles = false; - for binding in layout.sets.iter().flat_map(|set| &set.bindings) { - match binding.source { - BindingSource::CombinedTextureSampler { texture, sampler } - | BindingSource::SeparateTexture { texture, sampler } => { - let pair = match sampler.sampler { - SamplerRef::Slot(index) => Pair::Slot { - texture, - sampler: SlotRef { - stage: texture.stage, - class: SlotClass::Sampler, - index, - }, - }, - // A constexpr sampler, and any other the layout names in time: its state - // is no bound sampler's. - other => Pair::Constexpr { - texture, - modes: other.constexpr_address_modes(), - }, - }; - if !pairs.contains(&pair) { - pairs.push(pair); - } - } - BindingSource::HeapSampler { .. } - | BindingSource::Heap(HandleClass::Sampler { .. }) => { - handles = true; - } - _ => {} - } - } - (pairs, handles) -} - -/// The maps the runtime sampler slots of `pairs` take: each slot's sampler, `sampler_of`, mapped -/// by the map of every texture it samples, `map_of`. Refused where a constexpr sampler samples a -/// texture whose map changes one of its modes (or its modes are not stated), where one slot's -/// textures map it to different modes, and, where `handles`, where a texture of `reached` (those -/// a function sampling handles can reach) has a map. -pub(super) fn resolve( - pairs: &[Pair], - handles: bool, - map_of: impl Fn(SlotRef) -> AddressModeMap, - sampler_of: impl Fn(SlotRef) -> Option, - reached: impl IntoIterator, -) -> Result { - let refuse = |map, through| RuntimeGap::MappedTextureSampling { map, through }; - if handles { - if let Some(map) = reached.into_iter().find(|map| !map.is_identity()) { - return Err(refuse(map, MappedSampling::Handles)); - } - } - // Each runtime sampler slot's bound state, its modes as the first texture it samples maps - // them, and that texture's map. - let mut seen: BTreeMap = - BTreeMap::new(); - for pair in pairs { - match *pair { - Pair::Constexpr { texture, modes } => { - // A constexpr sampler samples a mapped texture through the pipeline variant of - // its slot (`VariantKey::address_maps`), whose state holds its modes mapped, as - // Metal samples it (a constexpr sampler samples as a runtime one - // of its modes): refused only where the map sends a mode where a constexpr - // sampler cannot address, or its modes are not stated. - let map = map_of(texture); - let stated = - modes.is_some_and(|m| m.iter().all(|&mode| map.constexpr_mode(mode).is_some())); - if !map.is_identity() && !stated { - return Err(refuse(map, MappedSampling::ConstexprSampler)); - } - } - Pair::Slot { texture, sampler } => { - // An unbound slot binds the device's neutral sampler, which no map changes. - let Some(desc) = sampler_of(sampler) else { - continue; - }; - let map = map_of(texture); - let mapped = map.sampler(desc); - let modes = [ - mapped.s_address_mode, - mapped.t_address_mode, - mapped.r_address_mode, - ]; - match seen.get(&sampler) { - Some(&(_, first, other)) if first != modes => { - let named = if map.is_identity() { other } else { map }; - return Err(refuse(named, MappedSampling::SharedSamplerSlot)); - } - Some(_) => {} - None => { - seen.insert(sampler, (desc, modes, map)); - } - } - } - } - } - Ok(SamplerMaps { - maps: seen - .into_iter() - .filter(|(_, (desc, modes, _))| { - *modes - != [ - desc.s_address_mode, - desc.t_address_mode, - desc.r_address_mode, - ] - }) - .map(|(slot, (_, _, map))| (slot, map)) - .collect(), - }) -} - -/// The maps one command of `layout` binds its runtime samplers with ([`resolve`]): `tables` -/// are its stages' argument tables, and `residency` what its encoder made resident. A command -/// whose tables bind no mapped texture, and whose encoder made none resident -/// (`Residency::maps_addresses`, kept as textures are made resident), takes none, and reads no -/// more of `layout` and no resident texture. -pub(super) fn sampler_maps( - layout: &PipelineLayout, - tables: &[(Stage, &ArgumentTable)], - residency: Option<&Residency>, -) -> Result { - let mapped = |texture: &Texture| !texture.address_mode_map().is_identity(); - let bound = tables.iter().flat_map(|(_, table)| table.textures.values()); - let resident = || residency.into_iter().flat_map(Residency::textures); - if !bound.clone().any(mapped) && !residency.is_some_and(Residency::maps_addresses) { - return Ok(SamplerMaps::default()); - } - let (pairs, handles) = pairs(layout); - let table = |stage: Stage| { - tables - .iter() - .find(|(of, _)| *of == stage) - .map(|&(_, table)| table) - }; - let texture_of = - |slot: SlotRef| table(slot.stage).and_then(|table| table.textures.get(&slot.index)); - let sampler_of = |slot: SlotRef| { - table(slot.stage) - .and_then(|table| table.samplers.get(&slot.index)) - .map(|(state, clamps)| super::binding::bound_sampler(state, *clamps)) - }; - resolve( - &pairs, - handles, - |slot| texture_of(slot).map_or(AddressModeMap::IDENTITY, Texture::address_mode_map), - sampler_of, - bound.chain(resident()).map(Texture::address_mode_map), - ) -} diff --git a/crates/metal2vulkan-runtime/src/address_pool.rs b/crates/metal2vulkan-runtime/src/address_pool.rs deleted file mode 100644 index c4bb2cd1d..000000000 --- a/crates/metal2vulkan-runtime/src/address_pool.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! A pool of the Metal address space whose slots buffers are placed in (the consumer's ask -//! "sub-page placement", `address.rs`' module docs). -//! -//! Metal makes each buffer of its own memory shorter than a page in a pool of its own, at a -//! 256-byte-aligned slot of `round_up(length, 256)` bytes, so several buffers share a 16-KiB page -//! (the consumer's `vaprobe smallpool` on an M3 Max under macOS 26.7). A caller that models those -//! pools reserves each ([`Device::reserve_address_pool`]) and places each small buffer at the slot -//! its model gives (`BufferDescriptor::with_pool_slot`): the buffer answers Metal's address. - -use super::address::{AddressPlacement, AddressSpace, GpuAddress}; -use super::device::carry::LineDevice; -use super::device::lock; -use super::error::Error; -use super::Device; -use std::sync::{Arc, Mutex}; - -/// A reserved range of the Metal address space whose slots buffers are placed in -/// (`BufferDescriptor::with_pool_slot`; a runtime extension, no Metal counterpart: Metal's own -/// buffer pools, which hold every buffer shorter than a page, are not objects of its API). While -/// it lives, no other buffer or heap, pinned or not, lands in its span. Dropping it lets the span -/// go, at once where no buffer lies in a slot of it, else once the last such buffer is gone. -/// -/// Where the device's recovery makes it a new `VkDevice` (`Degradation::DeviceRecovered`), the -/// pool goes on there: it is a span of the device's address space, which every `VkDevice` of the -/// device shares, and holds no Vulkan object, so buffers made after the recovery take its slots -/// as before. -pub struct AddressPool { - /// The device: its root handle, which a buffer's placement in a slot matches by its line, - /// and the generation handle `device` answers. - device: LineDevice, - /// The device's address space, which its span is of. - addresses: Arc>, - address: GpuAddress, - length: u64, -} - -impl AddressPool { - /// The pool's first byte: a slot's buffer at `offset` answers this plus `offset`. - pub fn gpu_address(&self) -> GpuAddress { - self.address - } - - /// The pool's bytes, which its slots lie in. - pub fn length(&self) -> u64 { - self.length - } - - /// The device whose address space the pool is of: a generation handle of the device: of the - /// generation the pool was made on, then of each one the device's recoveries carried the pool - /// to. The handle is the caller's: it keeps meaning that generation while held, past a recovery - /// that carries the pool on, its raw handles that generation's `VkDevice`'s, kept alive while - /// held. - pub fn device(&self) -> Device { - self.device.generation().clone() - } - - /// A root handle of the pool's device, which a buffer's placement in a slot matches by its - /// line. - pub(crate) fn root_device(&self) -> &Device { - self.device.root() - } -} - -impl std::fmt::Debug for AddressPool { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AddressPool") - .field("gpu_address", &self.address) - .field("length", &self.length) - .finish() - } -} - -impl Drop for AddressPool { - fn drop(&mut self) { - lock(&self.addresses).release_pool(self.address); - } -} - -impl Device { - /// Reserve a pool of `length` bytes of the Metal address space at `placement` (a runtime - /// extension, no Metal counterpart; `address.rs`' module docs): the pool holds the span a - /// buffer of `length` bytes pinned at its address holds (the pages its bytes touch and one - /// guard page, rounded up to 32 KiB), so no other placement, pin or range the runtime picks - /// lands in it while it lives. Buffers go in its slots (`BufferDescriptor::with_pool_slot`). - /// - /// At `AddressPlacement::At`, refused as a pin is (`PlacementConflict`: `Held`, - /// `OffGranule`, `OutsideSpace`); at `Any` or `Outside`, at a 32-KiB granule the runtime - /// picks in the space or outside it, refused `OutOfMemory` where no span is free. - pub fn reserve_address_pool( - &self, - placement: AddressPlacement, - length: u64, - ) -> Result { - self.at_serving(|device| device.reserve_address_pool_now(placement, length)) - } - - /// [`Device::reserve_address_pool`] on the generation that serves (`device/line.rs`). - pub(crate) fn reserve_address_pool_now( - &self, - placement: AddressPlacement, - length: u64, - ) -> Result { - let address = (self.address_space_for(placement)).reserve_pool(placement, length)?; - Ok(AddressPool { - device: LineDevice::new(self), - addresses: Arc::clone(&self.shared().addresses), - address, - length, - }) - } -} diff --git a/crates/metal2vulkan-runtime/src/alias_split.rs b/crates/metal2vulkan-runtime/src/alias_split.rs deleted file mode 100644 index c50241d74..000000000 --- a/crates/metal2vulkan-runtime/src/alias_split.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! A use of an image after a write through a buffer over its memory, in a new `VkCommandBuffer`, -//! on a driver whose image uses miss such writes inside one -//! (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`). -//! -//! Vulkan makes a write through a buffer visible to a later use of a linear image in `GENERAL` -//! over the same memory once a memory dependency orders the two: both are host-accessible -//! aliases. The tracker orders them so (`tracker.rs`): one key names a heap's bytes and the -//! images bound in them, a buffer's bytes and the images over them, and a write of a range of -//! them orders every later use that meets it, inside an encoder and between the encoders of a -//! group that share a `VkCommandBuffer` (`encoder_fold.rs`). On NVIDIA's 620.70.06 on the RTX -//! 3090 a copy out of such an image, behind that global memory barrier in the same -//! `VkCommandBuffer` as the buffer's write, read every texel as it was before the write, where -//! the same two commands in two `VkCommandBuffer`s of one submission, the barrier between them, -//! read the write (the fact's measurement, `driver_facts.rs`). -//! -//! - **The rule.** On such a device an encoder notes the bytes each of its commands writes into -//! the `VkCommandBuffer` it records into ([`AliasWrites`]); an encoder that joined a group of -//! encoders starts from what the group's earlier encoders wrote there, its order's writes of -//! bytes ([`FoldOrder::byte_writes`]). A command that uses an image of a key whose noted bytes -//! meet the image's place ([`UseRange::shares_memory`]) goes in a new `VkCommandBuffer`: the -//! encoder ends the one it records into and goes on in a new one, the command's barrier first -//! (`EncoderCore::split_at_aliases`), which notes none. An encoder that joined a group goes on -//! in a `VkCommandBuffer` of its own after the group's: its part's submission orders it after -//! the group's first part, the tracker's barrier between them in a command buffer of barriers, -//! the form measured to read the write. Counted: `WorkCounts::command_buffers_split_at_aliases`. -//! - **Render encoders.** A pass records no barrier, nor a new `VkCommandBuffer`, inside it, so -//! the split goes before it. One whose pass records at its end joins a group as any encoder -//! (`State::join_fold`). Its draws, recorded into its secondary, run after every command it -//! records into the `VkCommandBuffer` before the pass, whichever came first: each draw's image -//! uses are noted apart ([`AliasWrites::noted_apart`]), and where one meets a noted write, or a -//! write noted later meets one ([`AliasWrites::note`]), the encoder owes a split. The first -//! command it then records into the `VkCommandBuffer` (a shadow's copy before a later draw, or -//! at its end the steps before its pass and the pass, whose uses hold its attachments') goes in -//! a new one where it owes one, or where its own uses meet the writes: so every image the pass -//! uses is checked against every write before it before the pass records. The images noted -//! apart stay noted in the new one, whose later writes their draws still follow. One whose -//! first instance records inline joins no group (`encoder_fold.rs`): its draws record from its -//! first on, before its later calls are known. It may continue the render pass instance the -//! encoder before it left open in the group's tail (`encoder_fold.rs`'s **Continued passes**), -//! which records what its pass records after what the group's encoders wrote there: it does so -//! only where no memory its draws use (noted apart), nor its attachments', nor that of the -//! copies and steps before its later instances, meets the group's writes of bytes -//! ([`AliasWrites::continues`]), and then notes those writes as its own, as a joining encoder -//! does; else its pass begins its own instance in a `VkCommandBuffer` of its own, counted as -//! a split. Its uses of bytes count there with its images': a texture whose image aliases a -//! buffer's bytes names them as the buffer's (`Texture::image_use`), which no use tells from a -//! use through the buffer. -//! - **Scope.** The measured direction alone: a use through an image after a write through a -//! buffer. A use through a buffer after a write through an image is not measured and takes no -//! split. A render pass's draws record inside its pass, where no `VkCommandBuffer` ends; what -//! they write a later encoder's commands meet through the group's order, as any encoder's. -//! - **Elsewhere** nothing is noted and nothing splits: the device's encoders carry no -//! [`AliasWrites`]. - -use crate::encoder_fold::FoldOrder; -use crate::resource::ResourceKey; -use crate::tracker::{Use, UseRange}; -use metal2vulkan::device::DriverFact; -use std::collections::BTreeSet; -use std::ops::Range; - -/// Whether a device whose driver has `facts` records a use of an image after a write through a -/// buffer over its memory in a new `VkCommandBuffer` (the module docs). -pub(crate) fn splits_at_aliases(facts: &BTreeSet) -> bool { - facts.contains(&DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer) -} - -/// The most keys an [`AliasWrites`] notes the bytes of apart, in its writes and in its images -/// noted apart each: past them a new key makes every range meet, so the next image use, or the -/// next write, splits. -const KEPT: usize = 32; - -/// Ranges of bytes of keys' memory: at most [`KEPT`] keys', a key's ranges joined into the range -/// that holds them all, and past that every key's. -#[derive(Default)] -struct Noted { - ranges: Vec<(ResourceKey, Range)>, - /// A range of more keys than [`KEPT`] was noted: every range meets one. - every: bool, -} - -impl Noted { - /// Note `bytes` of `key`: joined into the key's noted range where it has one, else apart - /// while fewer than [`KEPT`] keys are. - fn add(&mut self, key: ResourceKey, bytes: Range) { - if self.every { - return; - } - if let Some((_, range)) = self.ranges.iter_mut().find(|(noted, _)| *noted == key) { - range.start = range.start.min(bytes.start); - range.end = range.end.max(bytes.end); - } else if self.ranges.len() < KEPT { - self.ranges.push((key, bytes)); - } else { - self.every = true; - } - } - - /// Whether `bytes` of `key` meet a noted range. - fn meets(&self, key: ResourceKey, bytes: &Range) -> bool { - self.every - || (self.ranges.iter()).any(|(noted, range)| { - *noted == key && range.start < bytes.end && bytes.start < range.end - }) - } - - /// Whether a range of `other` meets a noted range: none where either noted nothing. - fn meets_any(&self, other: &Noted) -> bool { - let empty = |noted: &Noted| !noted.every && noted.ranges.is_empty(); - if empty(self) || empty(other) { - return false; - } - self.every - || other.every - || (other.ranges.iter()).any(|(key, bytes)| self.meets(*key, bytes)) - } - - /// Note every range of `other`. - fn join(&mut self, other: Noted) { - if other.every { - self.every = true; - self.ranges.clear(); - return; - } - for (key, bytes) in other.ranges { - self.add(key, bytes); - } - } - - fn clear(&mut self) { - self.ranges.clear(); - self.every = false; - } -} - -/// What an encoder's commands on a device that splits at aliases noted (the module docs): the -/// bytes of each key the commands recorded into its current `VkCommandBuffer` wrote, and the -/// memory the images of its commands recorded apart use, which run after them (a pass's draws). -/// Each holds at most [`KEPT`] keys' ranges, and past that every key's. -#[derive(Default)] -pub(crate) struct AliasWrites { - writes: Noted, - /// The bytes the images of the commands recorded outside the `VkCommandBuffer`, which a - /// later command there executes, use ([`noted_apart`](Self::noted_apart)): kept from one - /// `VkCommandBuffer` to the next, as those commands run after what either records before them. - apart: Noted, - /// The bytes of the keys the commands noted apart use through their bytes - /// ([`noted_apart`](Self::noted_apart)): what a texture whose image aliases a buffer's bytes - /// names of them too (`Texture::image_use`), which [`continues`](Self::continues) checks. - bytes_apart: Noted, - /// A command noted apart uses an image whose memory meets a noted write, or a write noted - /// since meets an image one uses: the next command recorded into the `VkCommandBuffer` goes - /// in a new one. - owed: bool, -} - -impl AliasWrites { - /// What the earlier encoders of the group an encoder joined wrote into its `VkCommandBuffer`, - /// the group's tail: their order's writes of bytes; nothing where it joined none. - pub(crate) fn joining(order: Option<&FoldOrder>) -> AliasWrites { - let mut writes = AliasWrites::default(); - for (key, bytes) in order.into_iter().flat_map(FoldOrder::byte_writes) { - writes.writes.add(key, bytes); - } - writes - } - - /// Note a command recorded into the `VkCommandBuffer` with `uses`: the bytes it writes, and - /// whether one meets the memory of an image a command noted apart uses, which runs after it - /// ([`noted_apart`](Self::noted_apart)): the next command recorded there goes in a new one. - pub(crate) fn note(&mut self, uses: &[Use]) { - for used in uses.iter().filter(|used| !used.write.is_empty()) { - if let UseRange::Bytes(bytes) = &used.range { - self.owed |= self.apart.meets(used.key, bytes); - self.writes.add(used.key, bytes.clone()); - } - } - } - - /// Note a command recorded outside the `VkCommandBuffer` with `uses`, which a later command - /// there executes (a draw of a pass recorded at its end, into its secondary): the memory its - /// images use, and whether it meets a noted write. Where it does, now or once a later write - /// meets it ([`note`](Self::note)), the next command recorded there goes in a new one - /// ([`meets`](Self::meets)). - pub(crate) fn noted_apart(&mut self, uses: &[Use]) { - for used in uses { - match &used.range { - UseRange::Bytes(bytes) => self.bytes_apart.add(used.key, bytes.clone()), - range => { - if let Some(bytes) = range.image_bytes() { - self.owed |= self.writes.meets(used.key, &bytes); - self.apart.add(used.key, bytes); - } - } - } - } - } - - /// Whether a command with `uses` uses an image whose memory meets bytes a command before it - /// in the `VkCommandBuffer` wrote, or follows a command noted apart whose images do - /// ([`noted_apart`](Self::noted_apart)): it goes in a new one (the module docs). - pub(crate) fn meets(&self, uses: &[Use]) -> bool { - self.owed - || (uses.iter()).any(|used| { - (used.range.image_bytes()).is_some_and(|bytes| self.writes.meets(used.key, &bytes)) - }) - } - - /// Whether the encoder's pass may continue the render pass instance the tail of the group - /// `order` describes holds open (`encoder_fold.rs`'s **Continued passes**), which puts what - /// its pass records into that `VkCommandBuffer`, after what the group's encoders wrote there, - /// its order's writes of bytes: where no memory its commands noted apart use (its draws', - /// [`noted_apart`](Self::noted_apart)) nor that of one of `uses` (what else its pass records - /// there: its attachments, and the copies and steps before its later instances) meets them. - /// Their uses of bytes count with their images': a texture whose image aliases a buffer's - /// bytes names them as the buffer's (`Texture::image_use`), as a use through the buffer does, - /// so either may be an image's. Then those writes are noted as written into the - /// `VkCommandBuffer` the encoder records into, the tail, as for an encoder that joined the - /// group ([`joining`](Self::joining)), so a command it records there after its pass that uses - /// an image over them goes in a new one; else nothing changes, and its pass begins its own - /// instance in a `VkCommandBuffer` of its own. - pub(crate) fn continues( - &mut self, - order: &FoldOrder, - uses: &[Use], - ) -> bool { - let group = AliasWrites::joining(Some(order)).writes; - let meets = group.meets_any(&self.apart) - || group.meets_any(&self.bytes_apart) - || (uses.iter()).any(|used| { - let bytes = match &used.range { - UseRange::Bytes(bytes) => Some(bytes.clone()), - range => range.image_bytes(), - }; - bytes.is_some_and(|bytes| group.meets(used.key, &bytes)) - }); - if !meets { - self.writes.join(group); - } - !meets - } - - /// The encoder went on in a new `VkCommandBuffer`: no command wrote anything there yet, and - /// nothing is owed. The images noted apart stay: their commands run after what the new one - /// records before them. - pub(crate) fn begun(&mut self) { - self.writes.clear(); - self.owed = false; - } -} diff --git a/crates/metal2vulkan-runtime/src/allocations.rs b/crates/metal2vulkan-runtime/src/allocations.rs deleted file mode 100644 index a90066f37..000000000 --- a/crates/metal2vulkan-runtime/src/allocations.rs +++ /dev/null @@ -1,571 +0,0 @@ -//! The `VkDeviceMemory` allocations each device has live, held to its `maxMemoryAllocationCount` -//! (`VUID-vkAllocateMemory-maxMemoryAllocationCount-04101`: "There must be less than -//! `VkPhysicalDeviceLimits::maxMemoryAllocationCount` device memory allocations currently allocated -//! on the device"). -//! -//! - **Counted at the two doors.** Every allocation the runtime makes goes through -//! `creation::allocate_memory` and every free through `release::object`, a source test holding -//! both (`tests/exit_guard.rs`). So the count is kept there, by the device's handle, with no -//! caller passing it: the runtime's pooled blocks, its dedicated ones, every import of host -//! memory (no-copy objects' own, guest RAM chunks, fresh pages) and of dma-bufs. The device's -//! priming (`device/prime.rs`) frees all it allocates before the device is registered, so it is -//! not counted. What a consumer allocates itself on a device it hands the runtime -//! (`Device::adopt`) is not seen. -//! - **Refused at the limit.** An allocation the limit leaves no room for is refused -//! (`ERROR_TOO_MANY_OBJECTS`) without calling the driver, counted -//! (`WorkCounts::memory_allocations_refused_at_limit`). A caller then frees what it keeps and -//! tries again as after the driver's own refusal (`memory.rs`). -//! - **Posted frees count until they run.** A block whose free is posted to the device's free -//! thread (`free_thread.rs`) stays counted until its `vkFreeMemory`; an allocation that finds -//! the limit reached while frees are posted waits for them, then asks again, before it is -//! refused. -//! - **A margin the runtime's own work leaves.** [`Allocations::room_ahead`]: the allocations the -//! runtime makes ahead of any object (`host_ram.rs`'s ahead import, and the pooled blocks -//! `memory.rs`'s `keep_room` and `memory/ready.rs` make before anything is placed in them) stop -//! while fewer than a quarter of the limit are left, so the objects and their imports have -//! those. The pooled blocks are made under an [`Ahead`] mark: each is admitted only where one -//! more leaves that quarter, in one step with the count, so that no allocation counted -//! meanwhile takes the margin's share twice, and none waits at the limit. Once the device's -//! allocations reach that quarter, it gives back the chunks it imported ahead that no object -//! took and the blocks made ahead that are not yet in a pool and that no placement waits for -//! ([`Allocations::made`]), on a thread of the device's, so they are gone before they could -//! take the last. Objects that allocate faster than that thread runs (a loaded host -//! may leave it unscheduled) reach the limit first: an allocation that finds the limit reached -//! starts the give-back where one is due and waits for those under way -//! ([`GiveBack`]), then for the frees posted, then asks again, before it is refused. The -//! give-back's thread takes the RAMs' and their chunks' locks and the memory's lock, none of -//! which an allocation is made under (`memory.rs` makes its blocks and imports with its lock -//! released, `host_ram.rs` its chunks' with theirs), and allocates nothing, so the wait ends. - -use crate::free_thread::FreeThread; -use crate::step_aside::{Activity, OwnCall}; -use ash::vk; -use std::cell::Cell; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; - -/// The registered devices' counts, by handle: a few at most, so a list. -static DEVICES: Mutex)>> = Mutex::new(Vec::new()); - -thread_local! { - /// The allocations this thread makes now are the runtime's work ahead of any object - /// ([`Ahead`]). - static AHEAD: Cell = const { Cell::new(false) }; -} - -/// The allocations made on this thread while this lives are the runtime's work ahead of any -/// object (the module docs): each is counted only where one more leaves the margin of the limit -/// ([`Allocations::take_ahead`]), else refused at once, never waiting for a give-back or a free. -pub(crate) struct Ahead(bool); - -impl Ahead { - pub(crate) fn begin() -> Ahead { - Ahead(AHEAD.with(|ahead| ahead.replace(true))) - } -} - -impl Drop for Ahead { - fn drop(&mut self) { - AHEAD.with(|ahead| ahead.set(self.0)); - } -} - -/// One device's live allocations and its limit. -pub(crate) struct Allocations { - live: AtomicU32, - /// `maxMemoryAllocationCount`, which the tests may lower (`Allocations::limit_to`). - limit: AtomicU32, - /// Allocations refused at the limit. - refused: AtomicU32, - /// Something the runtime allocated ahead may be given back: set by each such allocation, - /// taken by the first allocation that leaves the device within the margin. - ahead: AtomicBool, - /// What gives the allocations made ahead back, set once the device is made: handed the - /// give-back's [`GiveBack`], which it drops once it gave back what it found. - give_back: OnceLock>, - /// The give-backs under way, which an allocation at the limit waits for. - giving_back: Arc, - /// The device's free thread, whose posted frees an allocation at the limit waits for, set - /// once the device is made. - frees: OnceLock>, - /// The allocations and frees in progress on threads not the device's checks', which those - /// step aside for (`step_aside.rs`). - activity: Activity, - /// How long each give-back's thread waits as it starts: the tests' stand-in for a loaded host - /// that leaves it unscheduled ([`Allocations::hold_give_backs`]). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - give_backs_held: Mutex, -} - -impl Allocations { - fn new(limit: u32) -> Allocations { - Allocations { - live: AtomicU32::new(0), - limit: AtomicU32::new(limit), - refused: AtomicU32::new(0), - ahead: AtomicBool::new(false), - give_back: OnceLock::new(), - giving_back: Arc::default(), - frees: OnceLock::new(), - activity: Activity::new(), - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - give_backs_held: Mutex::default(), - } - } - - /// The device's allocations and frees in progress on threads not its checks' - /// (`step_aside.rs`). - pub(crate) fn activity(&self) -> &Activity { - &self.activity - } - - /// The margin of the limit the runtime's work ahead leaves: a quarter (1024 of the 4096 the - /// spec requires at least), at least one. - fn margin(limit: u32) -> u32 { - (limit / 4).max(1) - } - - /// Count one more live allocation, or refuse it where the limit is reached, once what was - /// allocated ahead was given back and the frees posted to the device's free thread completed - /// (the module docs). - fn take(&self) -> bool { - let taken = self.try_take() || self.room_made() && self.try_take(); - if !taken { - self.refused.fetch_add(1, Ordering::Relaxed); - } - taken - } - - /// At the limit: what was allocated ahead given back (started where it is due, and every - /// give-back under way waited for), then the frees posted waited for. Whether either was - /// waited for, so the count may have room again. - fn room_made(&self) -> bool { - self.give_back_ahead(); - let given = self.giving_back.wait(); - let freed = self.frees.get().is_some_and(|frees| frees.wait()); - given || freed - } - - /// Count one more live allocation made ahead of any object where one more leaves the margin - /// ([`Allocations::room_ahead`]), in one step with the count: what was allocated ahead is - /// due to be given back from then on, its making still under way. Never refused as an - /// object's allocation is: no wait, nothing counted as refused. - fn take_ahead(&self) -> bool { - let limit = self.limit.load(Ordering::Relaxed); - let margin = Self::margin(limit); - let taken = self - .live - .try_update(Ordering::AcqRel, Ordering::Acquire, |live| { - (live.saturating_add(1).saturating_add(margin) <= limit).then_some(live + 1) - }) - .is_ok(); - if taken { - self.ahead.store(true, Ordering::Release); - } - taken - } - - /// Count one more live allocation where the limit leaves room for it. - fn try_take(&self) -> bool { - let limit = self.limit.load(Ordering::Relaxed); - self.live - .try_update(Ordering::AcqRel, Ordering::Acquire, |live| { - (live < limit).then_some(live + 1) - }) - .is_ok() - } - - /// Wait for the frees posted to `frees` before refusing an allocation at the limit, from now - /// on. - pub(crate) fn wait_for_frees_on(&self, frees: Arc) { - let _ = self.frees.set(frees); - } - - /// One counted allocation was freed, or its making failed. - fn give(&self) { - // Saturating: a free the count never saw (none is made today) leaves it at zero. - let _ = (self.live).try_update(Ordering::AcqRel, Ordering::Acquire, |live| { - live.checked_sub(1) - }); - } - - /// An allocation was made: where it leaves the device fewer than the margin, give back what - /// was allocated ahead since the last give-back ([`Allocations::give_back_ahead`]). - fn made(&self) { - let limit = self.limit.load(Ordering::Relaxed); - let live = self.live.load(Ordering::Acquire); - if live.saturating_add(Self::margin(limit)) <= limit { - return; - } - self.give_back_ahead(); - } - - /// Where something was allocated ahead since the last give-back, give that back: on a thread - /// of the device's, with no lock of the caller's held, counted under way until it ends. - fn give_back_ahead(&self) { - if !self.ahead.swap(false, Ordering::AcqRel) { - return; - } - if let Some(give_back) = self.give_back.get() { - give_back(self.giving_back.begin()); - } - } - - /// Whether the runtime may allocate one more ahead of any object: one more leaves at least - /// the margin of the limit. Counted as such ([`Allocations::made_ahead`]). - pub(crate) fn room_ahead(&self) -> bool { - let limit = self.limit.load(Ordering::Relaxed); - let live = self.live.load(Ordering::Acquire); - live.saturating_add(1).saturating_add(Self::margin(limit)) <= limit - } - - /// An allocation was made ahead of any object, which [`Allocations::made`] gives back once - /// the device's allocations come within the margin. - pub(crate) fn made_ahead(&self) { - self.ahead.store(true, Ordering::Release); - self.made(); - } - - /// Whether an allocation at the limit waits for a give-back under way now: its thread's - /// frees do not pace then (`host_ram.rs`). - pub(crate) fn give_back_awaited(&self) -> bool { - self.giving_back.waiting.load(Ordering::Acquire) > 0 - } - - /// Give back what was allocated ahead with `give_back` from now on. - pub(crate) fn give_back_with(&self, give_back: Box) { - let _ = self.give_back.set(give_back); - } - - /// The allocations refused at the limit so far. - pub(crate) fn refused(&self) -> u32 { - self.refused.load(Ordering::Relaxed) - } - - /// The device's live allocations. - #[cfg(test)] - pub(crate) fn live(&self) -> u32 { - self.live.load(Ordering::Acquire) - } - - /// The device's limit. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn limit(&self) -> u32 { - self.limit.load(Ordering::Relaxed) - } - - /// Hold the device to `limit` allocations from now on: the tests' small device. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn limit_to(&self, limit: u32) { - self.limit.store(limit, Ordering::Relaxed); - } - - /// Hold each give-back's thread `held` as it starts, from now on. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn hold_give_backs(&self, held: std::time::Duration) { - *self.give_backs_held.lock().unwrap() = held; - } - - /// How long each give-back's thread is held as it starts ([`Allocations::hold_give_backs`]). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn give_backs_held(&self) -> std::time::Duration { - *self.give_backs_held.lock().unwrap() - } - - /// The allocations at the limit that waited for a give-back under way so far. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn give_back_waits(&self) -> u64 { - self.giving_back.waits.load(Ordering::Relaxed) - } -} - -/// The give-backs of what the runtime allocated ahead under way ([`Allocations::give_back_ahead`]), -/// which an allocation at the limit waits for. -#[derive(Default)] -struct GivingBack { - /// How many are under way. - under_way: Mutex, - /// The last one under way ended. - ended: Condvar, - /// The allocations waiting for them now. - waiting: AtomicU32, - /// The waits for one. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - waits: std::sync::atomic::AtomicU64, -} - -impl GivingBack { - /// One more give-back under way, until its [`GiveBack`] drops. - fn begin(self: &Arc) -> GiveBack { - *lock_count(&self.under_way) += 1; - GiveBack(Arc::clone(self)) - } - - /// Wait until no give-back is under way: whether one was. - fn wait(&self) -> bool { - let mut under_way = lock_count(&self.under_way); - if *under_way == 0 { - return false; - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - self.waits.fetch_add(1, Ordering::Relaxed); - self.waiting.fetch_add(1, Ordering::AcqRel); - while *under_way > 0 { - under_way = (self.ended.wait(under_way)).unwrap_or_else(PoisonError::into_inner); - } - self.waiting.fetch_sub(1, Ordering::AcqRel); - true - } -} - -/// One give-back under way ([`GivingBack`]): it ends as this drops, on its thread once that gave -/// back what it found, or where its thread never started. -pub(crate) struct GiveBack(Arc); - -impl Drop for GiveBack { - fn drop(&mut self) { - let mut under_way = lock_count(&self.0.under_way); - *under_way -= 1; - if *under_way == 0 { - self.0.ended.notify_all(); - } - } -} - -fn lock_count(count: &Mutex) -> std::sync::MutexGuard<'_, u32> { - count.lock().unwrap_or_else(PoisonError::into_inner) -} - -/// A device's registration ([`register`]), let go of with the device. -pub(crate) struct Registered { - device: vk::Device, - pub(crate) allocations: Arc, -} - -impl Drop for Registered { - fn drop(&mut self) { - let mut devices = lock(); - devices.retain(|(device, allocations)| { - *device != self.device || !Arc::ptr_eq(allocations, &self.allocations) - }); - } -} - -/// Count `device`'s allocations from now on, against `limit` (its `maxMemoryAllocationCount`): -/// before its first allocation but its priming's. A handle a device let go of may come again: -/// the new device's count replaces the old. -pub(crate) fn register(device: vk::Device, limit: u32) -> Registered { - let allocations = Arc::new(Allocations::new(limit)); - let mut devices = lock(); - devices.retain(|(known, _)| *known != device); - devices.push((device, Arc::clone(&allocations))); - Registered { - device, - allocations, - } -} - -/// Whether `device` may allocate one more ahead of any object ([`Allocations::room_ahead`]): -/// always where it is not registered. -pub(crate) fn room_ahead(device: vk::Device) -> bool { - of(device).is_none_or(|allocations| allocations.room_ahead()) -} - -/// `device`'s count, where it is registered. -pub(crate) fn of(device: vk::Device) -> Option> { - let devices = lock(); - (devices.iter()) - .find(|(known, _)| *known == device) - .map(|(_, allocations)| Arc::clone(allocations)) -} - -fn lock() -> std::sync::MutexGuard<'static, Vec<(vk::Device, Arc)>> { - DEVICES - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) -} - -/// One allocation of `device` about to be made: `None` where the limit leaves it no room (or, -/// under an [`Ahead`] mark, where one more leaves less than the margin), so the caller refuses it -/// without calling the driver; else what the caller hands [`allocated`] with the driver's answer. -pub(crate) fn before_allocation(device: vk::Device) -> Option>> { - let Some(allocations) = of(device) else { - return Some(None); - }; - let taken = match AHEAD.with(Cell::get) { - true => allocations.take_ahead(), - false => allocations.take(), - }; - taken.then_some(Some(allocations)) -} - -/// The driver answered an allocation [`before_allocation`] admitted: `made` or not. -pub(crate) fn allocated(allocations: Option>, made: bool) { - let Some(allocations) = allocations else { - return; - }; - if made { - allocations.made(); - } else { - allocations.give(); - } -} - -/// One allocation of the device of `allocations` (its count, where it is registered: [`of`]) was -/// freed. -pub(crate) fn freed(allocations: Option<&Allocations>) { - if let Some(allocations) = allocations { - allocations.give(); - } -} - -/// An allocation or free of the device of `allocations` in progress on this thread, counted for -/// its checks to step aside for (`step_aside.rs`) until this goes: none where the device is not -/// registered or this is a check's thread, whose own call on a registered device is owed to its -/// next step instead ([`OwnCall`]), as a paced thread's is to its next pace. -pub(crate) struct Busy<'a>(Option<&'a Allocations>, Option); - -impl<'a> Busy<'a> { - pub(crate) fn of(allocations: Option<&'a Allocations>) -> Busy<'a> { - Busy( - allocations.filter(|allocations| allocations.activity.begin()), - allocations.and_then(|_| OwnCall::begin()), - ) - } -} - -impl Drop for Busy<'_> { - fn drop(&mut self) { - if let Some(allocations) = self.0 { - allocations.activity.end(); - } - // A check's or a paced thread's own call ends: its length is owed now. - drop(self.1.take()); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use ash::vk::Handle; - use std::sync::atomic::AtomicUsize; - - #[test] - fn an_allocation_past_the_limit_is_refused_and_a_free_makes_room() { - let count = Allocations::new(3); - assert!(count.take() && count.take() && count.take()); - assert!(!count.take(), "the limit reached"); - assert_eq!(count.refused(), 1); - count.give(); - assert!(count.take(), "a free made room"); - assert_eq!(count.live(), 3); - } - - #[test] - fn work_ahead_leaves_a_quarter_and_is_given_back_once_the_device_reaches_it() { - let count = Allocations::new(8); - let given = Arc::new(AtomicUsize::new(0)); - let seen = Arc::clone(&given); - count.give_back_with(Box::new(move |_| { - seen.fetch_add(1, Ordering::Relaxed); - })); - // A margin of 2 of 8: room ahead while one more leaves 2. - let mut ahead = 0; - while count.room_ahead() { - assert!(count.take()); - count.made_ahead(); - ahead += 1; - } - assert_eq!((ahead, count.live()), (6, 6)); - assert_eq!( - given.load(Ordering::Relaxed), - 0, - "not within the margin yet" - ); - // The objects' allocation inside the margin gives the work ahead back, once. - assert!(count.take()); - count.made(); - assert_eq!(given.load(Ordering::Relaxed), 1); - assert!(count.take()); - count.made(); - assert_eq!(given.load(Ordering::Relaxed), 1, "once per work ahead"); - } - - #[test] - fn an_allocation_at_the_limit_waits_for_the_give_back_under_way() { - let count = Arc::new(Allocations::new(8)); - let weak = Arc::downgrade(&count); - // A give-back slow to run, as on a loaded host: it frees the two allocated ahead. - count.give_back_with(Box::new(move |giving| { - let count = weak.upgrade().unwrap(); - crate::exit_guard::spawn(std::thread::Builder::new(), move || { - std::thread::sleep(std::time::Duration::from_millis(100)); - count.give(); - count.give(); - drop(giving); - }) - .unwrap(); - })); - for _ in 0..2 { - assert!(count.take()); - count.made_ahead(); - } - // The objects' allocations to the limit: the one that comes within the margin starts - // the give-back, and the one past the limit waits for it rather than being refused. - while count.live() < 8 { - assert!(count.take()); - count.made(); - } - assert!(count.take(), "refused while the give-back was under way"); - assert_eq!((count.live(), count.refused()), (7, 0)); - assert!(count.take() && !count.take(), "the limit holds after it"); - } - - #[test] - fn an_allocation_ahead_takes_the_room_past_the_margin_alone_and_is_given_back() { - let handle = vk::Device::from_raw(0xa4ead); - let registered = register(handle, 8); - let count = ®istered.allocations; - let given = Arc::new(AtomicUsize::new(0)); - let seen = Arc::clone(&given); - count.give_back_with(Box::new(move |_| { - seen.fetch_add(1, Ordering::Relaxed); - })); - // A margin of 2 of 8: allocations ahead are counted while one more leaves 2, then refused - // at once, as no object's is. - let ahead = super::Ahead::begin(); - let mut taken = 0; - while let Some(admitted) = before_allocation(handle) { - allocated(admitted, true); - taken += 1; - assert!(taken <= 8, "the margin holds"); - } - drop(ahead); - assert_eq!((taken, count.live(), count.refused()), (6, 6, 0)); - assert_eq!(given.load(Ordering::Relaxed), 0, "not within the margin"); - // The objects have the margin, and their first allocation inside it gives back what was - // allocated ahead. - allocated(before_allocation(handle).unwrap(), true); - assert_eq!(given.load(Ordering::Relaxed), 1); - allocated(before_allocation(handle).unwrap(), true); - assert!(before_allocation(handle).is_none(), "the limit holds"); - assert_eq!(count.refused(), 1); - } - - #[test] - fn a_registration_counts_its_device_until_it_goes() { - let handle = vk::Device::from_raw(0x5ee5); - let registered = register(handle, 2); - let admitted = before_allocation(handle).unwrap(); - allocated(admitted, true); - assert_eq!(registered.allocations.live(), 1); - freed(of(handle).as_deref()); - assert_eq!(registered.allocations.live(), 0); - drop(registered); - assert!(of(handle).is_none()); - assert!( - matches!(before_allocation(handle), Some(None)), - "not counted" - ); - } -} diff --git a/crates/metal2vulkan-runtime/src/amplification.rs b/crates/metal2vulkan-runtime/src/amplification.rs deleted file mode 100644 index dd0affca4..000000000 --- a/crates/metal2vulkan-runtime/src/amplification.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! A render encoder's vertex amplification (`setVertexAmplificationCount:viewMappings:`): the count -//! and the view mappings the draws after it take. -//! -//! The binder takes them as `BindState::vertex_amplification` and plans the draws' views -//! (`bind::ViewSetup`): Vulkan multiview over the pass's layers from the one the first mapping -//! names, or without multiview into that one layer, or, where multiview does not draw them as Metal -//! does, one draw per amplification (`render.rs`). Metal's validation stops a draw whose count is 0 -//! or above its pipeline's `maxVertexAmplificationCount`, not the setter (a Metal probe on an M4: -//! "Vertex Amplification Count (3) must be between (inclusive) 1 and the maximum vertex -//! amplification count specified in the pipeline state (2)"), so the encoder holds any count. A -//! draw of a count of 0 draws nothing, as plain Metal draws it (probe 13 `amp0`). One above a -//! pipeline's maximum of 2 or more, up to Metal's 8, draws that many amplifications, as plain Metal -//! draws them (probe 13 `amp3_pipeline2`, a probe `amp_*` on an M4: 3 and 4 on a maximum of 2, 4 on -//! 3, 8 on 2 and on 4 rendered every amplification through its mapping, and `nil` mappings each -//! into the first slice, the last one's texels kept). One above a maximum of 1 is refused: plain -//! Metal stored garbage (probe 13 `amp2_pipeline1`, probe 2 `amp_2_on_1`, `amp_3_on_1`). Metal -//! reads `count` mappings from its pointer; a slice of fewer is refused at the setter, and one of -//! more gives its first `count`. `setVertexAmplificationMode:value:` sets the count and keeps the -//! mappings ([`Amplification::with_count`], `apple_only.rs`). - -use super::capabilities::MAX_VERTEX_AMPLIFICATION; -use super::render::DrawProblem; -use metal2vulkan::bind::{VertexAmplification, ViewMapping}; - -/// `MTLVertexAmplificationViewMapping`: the offsets an amplification adds to the viewport and -/// render target array indices it renders through. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct VertexAmplificationViewMapping { - /// `viewportArrayIndexOffset`. - pub viewport_array_index_offset: u32, - /// `renderTargetArrayIndexOffset`. - pub render_target_array_index_offset: u32, -} - -impl VertexAmplificationViewMapping { - /// The mapping of these offsets. - pub fn new( - viewport_array_index_offset: u32, - render_target_array_index_offset: u32, - ) -> VertexAmplificationViewMapping { - VertexAmplificationViewMapping { - viewport_array_index_offset, - render_target_array_index_offset, - } - } -} - -/// The encoder's vertex amplification: Metal's default, a count of 1 without mappings, until -/// set. -#[derive(Clone, Debug, PartialEq)] -pub(super) struct Amplification { - count: u64, - /// The first `count` mappings; empty for `nil`. - mappings: Vec, -} - -impl Default for Amplification { - fn default() -> Amplification { - Amplification { - count: 1, - mappings: Vec::new(), - } - } -} - -impl Amplification { - /// The amplification of `count` with `mappings` (`None` for `nil`). Refused: fewer mappings - /// than the count. - pub(super) fn new( - count: u64, - mappings: Option<&[VertexAmplificationViewMapping]>, - ) -> Result { - let mappings = match mappings { - None => Vec::new(), - Some(given) => { - let taken = usize::try_from(count) - .ok() - .and_then(|count| given.get(..count)) - .ok_or(DrawProblem::ViewMappings { - count, - given: given.len() as u64, - })?; - taken.to_vec() - } - }; - Ok(Amplification { count, mappings }) - } - - /// The amplification of `count` with these view mappings kept - /// (`setVertexAmplificationMode:value:`, `apple_only.rs`): `None` where there are mappings - /// and the count passes them, which Metal's measurements do not reach. - pub(super) fn with_count(&self, count: u64) -> Option { - let mappings = match self.mappings.is_empty() { - true => Vec::new(), - false => self.mappings.get(..usize::try_from(count).ok()?)?.to_vec(), - }; - Some(Amplification { count, mappings }) - } - - /// Whether a draw draws nothing: a count of 0 (the module docs). - pub(super) fn draws_nothing(&self) -> bool { - self.count == 0 - } - - /// Whether a draw draws more than one amplification. - pub(super) fn amplifies(&self) -> bool { - self.count > 1 - } - - /// Whether a mapping moves an amplification to another viewport. - pub(super) fn offsets_viewports(&self) -> bool { - self.mappings - .iter() - .any(|m| m.viewport_array_index_offset != 0) - } - - /// The amplification as the binder takes it, for a draw of a pipeline whose - /// `maxVertexAmplificationCount` is `max`. Refused (the module docs): a count above 1 where - /// `max` is 1, and one above Metal's 8 (unmeasured); a count of 0 draws nothing before it is - /// asked for (`draws_nothing`). - pub(super) fn bind_state(&self, max: u32) -> Result { - let count = u32::try_from(self.count) - .ok() - .filter(|&count| { - (1..=max).contains(&count) - || (max > 1 && (1..=MAX_VERTEX_AMPLIFICATION).contains(&u64::from(count))) - }) - .ok_or(DrawProblem::AmplificationCount { - count: self.count, - max, - })?; - let mappings = self - .mappings - .iter() - .map(|m| { - ViewMapping::new( - m.viewport_array_index_offset, - m.render_target_array_index_offset, - ) - }) - .collect(); - Ok(VertexAmplification::new(count, mappings)) - } -} diff --git a/crates/metal2vulkan-runtime/src/apple_only.rs b/crates/metal2vulkan-runtime/src/apple_only.rs deleted file mode 100644 index 028436b90..000000000 --- a/crates/metal2vulkan-runtime/src/apple_only.rs +++ /dev/null @@ -1,451 +0,0 @@ -//! The Apple-only calls of the consumer's trait: each is accepted where it is exact on Vulkan, and -//! otherwise refused with [`AppleOnly`] naming the missing feature, and [`AppleOnly::gap`] saying -//! why: Metal's answer is not measured, or the runtime has not built it. None is a device's gap: -//! each is the runtime's own. -//! -//! Exact means one of: -//! - the call states Metal's default, which every runtime object already has: the viewport -//! transform on; -//! - the call sets encoder state the runtime draws as Metal does: a provoking vertex mode of 0 -//! or 1, `render/provoking.rs`; a line width, `render/line_width.rs` (the device's own lines -//! where they differ from Metal's are announced, `device-wide-lines`, and those at the nearest -//! width they draw where neither they nor the band draw Metal's, `lines-at-nearest-width`); -//! - the call acts on state no runtime object has: Vulkan shows no texture compression, so a -//! reinterpretation flush has nothing to flush, and after an invalidation Metal leaves the -//! contents undefined, so keeping them is one of the outcomes Metal allows; -//! - the call sets encoder state a runtime pipeline reads as Metal's does: the alpha test -//! reference, which a pipeline with the private alpha test compares against (`BindState`'s -//! `alpha_test_reference`). -//! -//! - `setPointSize:`, which Metal measured makes a no-op: the point is the vertex function's -//! `[[point_size]]`; and `setDepthCleared` and `setStencilCleared`, which change nothing Metal -//! draws (the consumer's suite case on the M3 Max, pixel for pixel). -//! - `setVertexAmplificationMode:value:`, which sets the amplification count -//! `setVertexAmplificationCount:viewMappings:` sets and keeps the view mappings that call set, -//! whichever of the two comes last deciding (the consumer's measurements on the M3 Max, modes 0 -//! to 8, 15, 16, 255 and the largest values): the count is the value's set bits in mode 1 and the -//! value in every other mode, exact from 1 to 8 (`amplification_mode_count`). -//! -//! A provoking vertex mode past 1, which Metal draws a third way, is accepted and drawn as mode 1 -//! (patches as mode 0), announced at each draw whose shape and pipeline state Metal draws -//! otherwise there (`provoking-vertex-unmatched`). -//! -//! Every other call is refused, and records nothing: -//! - a vertex amplification mode whose count is 0, which draws a number of copies that changes -//! from run to run on Metal, or above 8 (9 draws one copy and 16 and 32 eight, the rest -//! unmeasured), and one whose count passes the view mappings kept (unmeasured); -//! - turning the viewport transform off, which Vulkan has no switch for and whose meaning on -//! Metal is not measured; -//! - a texture over an IOSurface made with `kIOSurfaceClientDirection`, a key in no header of the -//! public macOS SDK, refused by the IOSurface plane's stand-in -//! (`Buffer::new_texture_with_iosurface_plane`), which is no call of the table. -//! -//! Texture fills (`blit_fill.rs`) refuse nothing here: a multisample texture's samples, a texture -//! buffer's bytes and a color packed in a format Metal packs no color in (the command buffer's -//! last packed texel, announced as `unpacked-fill-color`) are built. A multisample fill a device -//! cannot copy into the texture is refused there, `Unsupported`, as the device's gap. -//! -//! [`AppleOnlyCall`] is the table, and every call of it is here: the compute, render and blit -//! encoders', and the texture's protection options. The command buffer's protection options are -//! `command_buffer/protection.rs`'s, as Metal's GPU answers them, but the forms not measured -//! ([`AppleOnly::ProtectedContent`]). A texture's -//! rotation is the runtime's (`TextureDescriptor::rotation`), and command predication, loops -//! included, is `predication.rs`'s. - -use super::blit::BlitCommandEncoder; -use super::blit_texture::check_slice_level; -use super::capabilities::MAX_VERTEX_AMPLIFICATION; -use super::compute::ComputeCommandEncoder; -use super::error::Error; -use super::render::RenderCall; -use super::render::RenderCommandEncoder; -use super::render::RenderLowering; -use super::replay::BlitCall; -use super::texture::Texture; - -/// An Apple-only feature the runtime refuses, each for the reason [`AppleOnly::gap`] gives (No -/// device lacks any of them; each is a gap of the runtime's own). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum AppleOnly { - /// Protection options whose answer on Metal is not measured - /// (`command_buffer/protection.rs`): options changed once an encoder was made under some, or - /// after options from 0x10 up, and a resource state encoder made under 1, 3 or 7. - ProtectedContent, - /// The viewport transform turned off (`setViewportTransformEnabled:NO`). - ViewportTransformDisabled, - /// `setVertexAmplificationMode:value:` of a count (the value's set bits in mode 1, else the - /// value) of 0, whose copies change from run to run on Metal, or above 8, or above the view - /// mappings kept. - VertexAmplificationMode, - /// A texture over an IOSurface made with `kIOSurfaceClientDirection` - /// (`newTextureWithDescriptor:iosurface:plane:` of such a surface): IOSurface SPI, a key - /// IOSurface.framework exports and no header of the public macOS SDK declares, so the - /// surface is the consumer's to build. The consumer reports that Metal drops a GPU write into - /// a surface made with value 2 (read-only), without a fault; the runtime does not model the - /// key's values. - SurfaceClientDirection, -} - -/// Why the runtime refuses an [`AppleOnly`] feature. None is a device's gap: no measured Vulkan -/// device lacks what an exact form would need. Each is the runtime's own, and a measurement can -/// lift it. A color fill whose bytes Metal leaves undefined, once refused as having no one -/// answer, is built: the runtime gives one of Metal's answers. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum AppleOnlyGap { - /// What Metal does on Apple's GPU is not measured, so the runtime does not guess it: the - /// runtime's gap, which a measurement would let it build. - Unmeasured, -} - -impl AppleOnly { - /// Why the runtime refuses the feature ([`AppleOnlyGap`]). - pub const fn gap(self) -> AppleOnlyGap { - match self { - Self::ProtectedContent - | Self::ViewportTransformDisabled - | Self::VertexAmplificationMode - | Self::SurfaceClientDirection => AppleOnlyGap::Unmeasured, - } - } -} - -/// Metal's `protectionOptions` of a resource made without any, and of every runtime texture. -pub const DEFAULT_PROTECTION_OPTIONS: u64 = 0; - -/// One Apple-only call (class A) with the arguments its answer depends on: the table each -/// encoder's, descriptor's and command buffer's method of that call answers by. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum AppleOnlyCall { - /// `invalidateCompressedTexture:` (blit encoder). - InvalidateCompressedTexture, - /// `invalidateCompressedTexture:slice:level:` (blit encoder). - InvalidateCompressedTextureSlice, - /// `insertCompressedTextureReinterpretationFlush` (compute encoder). - CompressedTextureReinterpretationFlush, - /// `setAlphaTestReferenceValue:` (render encoder). - SetAlphaTestReferenceValue(f32), - /// `setLineWidth:` (render encoder). - SetLineWidth(f32), - /// `setPointSize:` (render encoder). - SetPointSize(f32), - /// `setProvokingVertexMode:` (render encoder). - SetProvokingVertexMode(u64), - /// `setViewportTransformEnabled:` (render encoder). - SetViewportTransformEnabled(bool), - /// `setVertexAmplificationMode:value:` (render encoder). - SetVertexAmplificationMode { - /// The mode given. - mode: u64, - /// The value given. - value: u64, - }, - /// `setDepthCleared` (render encoder). - SetDepthCleared, - /// `setStencilCleared` (render encoder). - SetStencilCleared, -} - -impl AppleOnlyCall { - /// Metal's selector. - pub fn selector(self) -> &'static str { - match self { - AppleOnlyCall::InvalidateCompressedTexture => "invalidateCompressedTexture:", - AppleOnlyCall::InvalidateCompressedTextureSlice => { - "invalidateCompressedTexture:slice:level:" - } - AppleOnlyCall::CompressedTextureReinterpretationFlush => { - "insertCompressedTextureReinterpretationFlush" - } - AppleOnlyCall::SetAlphaTestReferenceValue(_) => "setAlphaTestReferenceValue:", - AppleOnlyCall::SetLineWidth(_) => "setLineWidth:", - AppleOnlyCall::SetPointSize(_) => "setPointSize:", - AppleOnlyCall::SetProvokingVertexMode(_) => "setProvokingVertexMode:", - AppleOnlyCall::SetViewportTransformEnabled(_) => "setViewportTransformEnabled:", - AppleOnlyCall::SetVertexAmplificationMode { .. } => "setVertexAmplificationMode:value:", - AppleOnlyCall::SetDepthCleared => "setDepthCleared", - AppleOnlyCall::SetStencilCleared => "setStencilCleared", - } - } - - /// The runtime's answer: `Ok` where it takes the call (it states Metal's default, acts on - /// state no runtime object has, so it records nothing, or sets the encoder's provoking - /// vertex or line width, [`RenderCommandEncoder::set_provoking_vertex_mode`] and - /// [`RenderCommandEncoder::set_line_width`]), else the refusal naming the missing feature. - pub fn check(self) -> Result<(), AppleOnly> { - match self { - AppleOnlyCall::InvalidateCompressedTexture - | AppleOnlyCall::InvalidateCompressedTextureSlice - | AppleOnlyCall::CompressedTextureReinterpretationFlush - | AppleOnlyCall::SetAlphaTestReferenceValue(_) - | AppleOnlyCall::SetLineWidth(_) - | AppleOnlyCall::SetPointSize(_) - | AppleOnlyCall::SetProvokingVertexMode(_) - | AppleOnlyCall::SetDepthCleared - | AppleOnlyCall::SetStencilCleared => Ok(()), - AppleOnlyCall::SetViewportTransformEnabled(enabled) => { - default_or(enabled, AppleOnly::ViewportTransformDisabled) - } - AppleOnlyCall::SetVertexAmplificationMode { mode, value } => default_or( - (1..=MAX_VERTEX_AMPLIFICATION).contains(&lification_mode_count(mode, value)), - AppleOnly::VertexAmplificationMode, - ), - } - } -} - -/// The amplification count `setVertexAmplificationMode:value:` sets (the consumer's measurements -/// on the M3 Max): the number of `value`'s set bits in mode 1, and `value` in every other mode. -/// Metal draws that many copies, amplification IDs from 0 up, for a count from 1 to 8. -pub(crate) fn amplification_mode_count(mode: u64, value: u64) -> u64 { - match mode { - 1 => u64::from(value.count_ones()), - _ => value, - } -} - -/// `Ok` where the call states Metal's default, else the refusal of `feature`. -fn default_or(is_default: bool, feature: AppleOnly) -> Result<(), AppleOnly> { - if is_default { - Ok(()) - } else { - Err(feature) - } -} - -/// The runtime error of `call`'s answer. -fn answer(call: AppleOnlyCall) -> Result<(), Error> { - call.check().map_err(Error::AppleOnly) -} - -impl Texture { - /// `protectionOptions` (SPI): [`DEFAULT_PROTECTION_OPTIONS`], the only protection options a - /// runtime texture has. - pub fn protection_options(&self) -> u64 { - DEFAULT_PROTECTION_OPTIONS - } -} - -impl BlitCommandEncoder { - /// `invalidateCompressedTexture:` (SPI): a no-op. Vulkan shows no texture compression, and - /// after an invalidation Metal leaves the contents undefined, so keeping them is an outcome - /// Metal allows. Refused (`Invalid`, `ForeignObject`) for another device's texture, as every - /// blit is. - pub fn invalidate_compressed_texture(&mut self, texture: &Texture) -> Result<(), Error> { - self.logged( - |_| BlitCall::InvalidateCompressedTexture(texture.clone()), - |this| { - this.core() - .check_device("invalidate_compressed_texture", texture.generation())?; - answer(AppleOnlyCall::InvalidateCompressedTexture) - }, - ) - } - - /// `invalidateCompressedTexture:slice:level:` (SPI): a no-op, as - /// [`invalidate_compressed_texture`](Self::invalidate_compressed_texture) is, for one slice - /// and level. Refused (`Invalid`) also for a slice or level the texture does not have, as the - /// blit encoder's hints of a slice and level are. - pub fn invalidate_compressed_texture_slice( - &mut self, - texture: &Texture, - slice: u64, - level: u64, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::InvalidateCompressedTextureSlice(texture.clone(), slice, level), - |this| { - const CALL: &str = "invalidate_compressed_texture_slice"; - this.core().check_device(CALL, texture.generation())?; - check_slice_level(CALL, texture, slice, level)?; - answer(AppleOnlyCall::InvalidateCompressedTextureSlice) - }, - ) - } -} - -impl ComputeCommandEncoder { - /// `insertCompressedTextureReinterpretationFlush` (SPI): a no-op. Vulkan shows no texture - /// compression, so there is nothing to flush. - pub fn insert_compressed_texture_reinterpretation_flush(&mut self) {} -} - -impl RenderLowering { - /// The lowering of [`RenderCommandEncoder::set_alpha_test_reference_value`]. - pub(crate) fn set_alpha_test_reference_value(&mut self, value: f32) -> Result<(), Error> { - self.log(|_| RenderCall::AlphaTestReferenceValue(value)); - answer(AppleOnlyCall::SetAlphaTestReferenceValue(value))?; - self.set_alpha_test_reference(value); - Ok(()) - } - - /// The lowering of [`RenderCommandEncoder::set_line_width`]. - pub(crate) fn set_line_width(&mut self, width: f32) -> Result<(), Error> { - self.log(|_| RenderCall::LineWidth(width)); - answer(AppleOnlyCall::SetLineWidth(width))?; - self.set_encoder_line_width(width); - Ok(()) - } - - /// The lowering of [`RenderCommandEncoder::set_point_size`]. - pub(crate) fn set_point_size(&mut self, size: f32) -> Result<(), Error> { - self.log(|_| RenderCall::PointSize(size)); - answer(AppleOnlyCall::SetPointSize(size)) - } - - /// The lowering of [`RenderCommandEncoder::set_provoking_vertex_mode`]. - pub(crate) fn set_provoking_vertex_mode(&mut self, mode: u64) -> Result<(), Error> { - self.log(|_| RenderCall::ProvokingVertexMode(mode)); - self.set_provoking_vertex(mode); - Ok(()) - } - - /// The lowering of [`RenderCommandEncoder::set_viewport_transform_enabled`]. - pub(crate) fn set_viewport_transform_enabled(&mut self, enabled: bool) -> Result<(), Error> { - self.log(|_| RenderCall::ViewportTransformEnabled(enabled)); - answer(AppleOnlyCall::SetViewportTransformEnabled(enabled)) - } - - /// The lowering of [`RenderCommandEncoder::set_vertex_amplification_mode`]. - pub(crate) fn set_vertex_amplification_mode( - &mut self, - mode: u64, - value: u64, - ) -> Result<(), Error> { - self.log(|_| RenderCall::VertexAmplificationMode(mode, value)); - answer(AppleOnlyCall::SetVertexAmplificationMode { mode, value })?; - self.amplify_with_kept_mappings(amplification_mode_count(mode, value)) - .ok_or(Error::AppleOnly(AppleOnly::VertexAmplificationMode)) - } - - /// The lowering of [`RenderCommandEncoder::set_depth_cleared`]. - pub(crate) fn set_depth_cleared(&mut self) -> Result<(), Error> { - self.log(|_| RenderCall::DepthCleared); - answer(AppleOnlyCall::SetDepthCleared) - } - - /// The lowering of [`RenderCommandEncoder::set_stencil_cleared`]. - pub(crate) fn set_stencil_cleared(&mut self) -> Result<(), Error> { - self.log(|_| RenderCall::StencilCleared); - answer(AppleOnlyCall::SetStencilCleared) - } -} - -impl RenderCommandEncoder { - /// `setAlphaTestReferenceValue:` (SPI): the reference a pipeline with the private alpha test - /// (`PrivateRenderState::alpha_test_enabled`) compares its fragments' color 0 alpha against, - /// both as Metal's 8-bit unorm codes; each encoder starts at Metal's 1. Accepted for every - /// value, as on Metal. - pub fn set_alpha_test_reference_value(&mut self, value: f32) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_alpha_test_reference_value(value)), - false => self.defer(|_| RenderCall::AlphaTestReferenceValue(value)), - } - } - - /// `setLineWidth:` (SPI): the width the encoder's lines, and triangles' edges in fill mode - /// `Lines`, are drawn at after the call, until the next call or the encoder's end, each encoder - /// starting at 1, as Metal draws it (the M3 Max, macOS 27.0.1): `floor(16 width) / 16` clamped - /// to `[0, 16]`, NaN and every width not above 0 as 0. At 1 a line is Metal's ordinary one; at - /// any other width the parallelogram whose minor-axis edges pass through the endpoints, each - /// that width long, a strip's segments and a triangle's edges each their own; at 0 as at 1/16. - /// Points and filled triangles do not change. Every width is accepted. A draw at another width - /// than 1 runs the device's own lines where they draw it (announced `device-wide-lines` where - /// they differ from Metal's, or under `WideLinePolicy::Exact` the band below where they do), - /// else the pipeline's band variant, which needs `tessellationShader`: two triangles over each - /// line's parallelogram, and each triangle's three edges' parallelograms, which face as the - /// triangle does and are culled by the cull mode (announced `wide-edge-depth-bias` under a - /// depth bias the device can apply otherwise than Metal). What neither draws runs the device's - /// own lines at the width nearest Metal's they draw (1 without `wideLines`), announced - /// `lines-at-nearest-width`: a mesh draw and a tessellated patch draw where the device's lines - /// do not draw the width, lines and edges without `tessellationShader` or of a pipeline state - /// whose band the translator refuses, a line in a rasterization-rate-mapped pass or of an - /// execution's command, and a band under vertex amplification above 1. A draw of no complete - /// primitive draws nothing, as Metal's. Refused at the draw (`NotImplemented(WideLines)`): a - /// strip's band whose list of primitives the runtime cannot draw. The runtime's README states - /// the route each device takes. - pub fn set_line_width(&mut self, width: f32) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_line_width(width)), - false => self.defer(|_| RenderCall::LineWidth(width)), - } - } - - /// `setPointSize:` (SPI): a no-op. On an M4 it changes nothing Metal draws at any size (0, - /// 0.5, 1, 3, 5, 100, -2, NaN, infinity), whether the vertex function writes `[[point_size]]` - /// or not and whether the pipeline's private `pointSizeOutputVS` is set. - pub fn set_point_size(&mut self, size: f32) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_point_size(size)), - false => self.defer(|_| RenderCall::PointSize(size)), - } - } - - /// `setProvokingVertexMode:` (SPI): the vertex the encoder's draws after the call take each - /// primitive's flat inputs from, until the next call or the encoder's end, as Metal draws it - /// (the M3 Max, macOS 27.0.1): mode 0, Metal's default, the first vertex; mode 1 the last, a - /// triangle strip's odd triangle then in Vulkan's last-vertex order for its barycentric - /// weights too. An execution of indirect render commands takes the first vertex whatever the - /// mode, as on Metal. Mode 1 runs a pipeline of the last vertex where the device enables - /// `VK_EXT_provoking_vertex`'s `provokingVertexLast` with `provokingVertexModePerPipeline`, - /// and elsewhere draws each primitive whose vertex order a pipeline state reads from a list - /// led by its last vertex, which a GPU pass writes (the CPU for a direct draw without - /// indices); what that list draws otherwise than Metal is announced - /// (`provoking-vertex-lines`, `provoking-vertex-unmatched`). Metal draws every other mode, - /// its top bit set or not, as 2, a third way: a triangle list's, a fan's and the private - /// triangle types' primitives as mode 1 (but a triangle of a pipeline that selects its slice - /// or viewport from its middle vertex), a strip's odd triangle from its first vertex, every - /// line's flat inputs and `[[primitive_id]]` 0, and patches as mode 0. The runtime draws it as - /// mode 1, and patches as mode 0, announcing each draw whose pipeline state reads what Metal - /// draws otherwise there (`provoking-vertex-unmatched`). No mode is refused. - pub fn set_provoking_vertex_mode(&mut self, mode: u64) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_provoking_vertex_mode(mode)), - false => self.defer(|_| RenderCall::ProvokingVertexMode(mode)), - } - } - - /// `setViewportTransformEnabled:` (SPI): accepted on, Metal's default and every runtime - /// draw's; off is refused ([`AppleOnly::ViewportTransformDisabled`]): Vulkan has no form for - /// it. - pub fn set_viewport_transform_enabled(&mut self, enabled: bool) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_viewport_transform_enabled(enabled)), - false => self.defer(|_| RenderCall::ViewportTransformEnabled(enabled)), - } - } - - /// `setVertexAmplificationMode:value:` (SPI): sets the amplification count - /// [`set_vertex_amplification_count`](Self::set_vertex_amplification_count) sets, the number - /// of `value`'s set bits in mode 1 and `value` in every other mode, and keeps the view mappings - /// that call set (none at the encoder's start), as Metal does (the consumer's measurements on - /// the M3 Max). Refused - /// ([`AppleOnly::VertexAmplificationMode`]) for a count of 0, whose copies Metal draws change - /// from run to run, above 8 (unmeasured but for three values), or above the view mappings kept - /// (unmeasured); a refused call keeps the amplification set before. - pub fn set_vertex_amplification_mode(&mut self, mode: u64, value: u64) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_vertex_amplification_mode(mode, value)), - false => self.defer(|_| RenderCall::VertexAmplificationMode(mode, value)), - } - } - - /// `setDepthCleared` (SPI): a no-op. It changes nothing Metal draws (the consumer's suite case - /// on the M3 Max, pixel for pixel). - pub fn set_depth_cleared(&mut self) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_depth_cleared()), - false => self.defer(|_| RenderCall::DepthCleared), - } - } - - /// `setStencilCleared` (SPI): a no-op, as [`set_depth_cleared`](Self::set_depth_cleared) is. - pub fn set_stencil_cleared(&mut self) -> Result<(), Error> { - match self.lowers_at_call() { - true => self.at_call(|lowering| lowering.set_stencil_cleared()), - false => self.defer(|_| RenderCall::StencilCleared), - } - } -} diff --git a/crates/metal2vulkan-runtime/src/argument_encoder.rs b/crates/metal2vulkan-runtime/src/argument_encoder.rs deleted file mode 100644 index e7a033e12..000000000 --- a/crates/metal2vulkan-runtime/src/argument_encoder.rs +++ /dev/null @@ -1,860 +0,0 @@ -//! Argument encoders (`MTLArgumentEncoder`). -//! -//! An encoder writes the arguments of an argument buffer at the places a -//! [`bind::ArgumentBufferLayout`](metal2vulkan::bind::ArgumentBufferLayout) gives: the layout of the -//! argument buffer a function takes (`Function::new_argument_encoder_with_buffer_index`), the -//! layout of a pointer member's argument buffer (`new_argument_encoder_for_buffer_at_index`), the -//! layout of argument descriptors (`Device::new_argument_encoder_with_arguments`), or the layout a -//! reflected buffer binding states (`Device::new_argument_encoder_with_buffer_binding`). Each -//! argument is the 8 bytes, little endian, a program could write itself: a buffer's Metal -//! address plus the offset, and every other object's `gpu_resource_id`; `None` writes 0. So -//! encoded and hand-written argument buffers reach the translated functions alike, through the -//! resident and handle tables. An encoder makes nothing resident: as on Metal, the program calls -//! `use_resource(s)` or `use_heap(s)` for what the function reaches. -//! -//! The bytes are written at once, through the argument buffer's mapping: a `Shared` or `Managed` -//! buffer, as Metal's validation requires. Writing them while a command reads them races, as on -//! Metal. -//! -//! **What Metal's validation stops is refused** (`Invalid`, [`ArgumentEncoderProblem`]), and -//! nothing is written; measured on an M3 Max and an M4 with `MTL_DEBUG_LAYER=1` (probes), where -//! Metal without validation writes regardless, or crashes: -//! - a setter or `constant_data` before an argument buffer is set; -//! - an argument buffer of `Private` storage, or one whose `offset + encoded_length` passes its -//! length (`RangeOutOfBounds`); an unaligned offset is taken, as Metal takes it; -//! - a setter's index of an argument of another type ("Trying to set a Texture at index 0 but the -//! argument buffer has a Buffer at this index"), and one no argument has where the 8 bytes at -//! the arguments' offset would pass the argument buffer's end; a range form checks every index -//! before writing any. -//! -//! **Where plain Metal gives a deterministic, measured answer, the encoder gives it, even where -//! the debug layer asserts** (the orchestrator's parity rule): -//! - `constant_data` at an index no argument has answers the arguments' start (offset 0), and at -//! an argument of another type that argument's own offset, as plain Metal's -//! `constantDataAtIndex:` did on an M4; `MTL_DEBUG_LAYER=1` asserts at both -//! ("Index 2 does not correspond to any valid member of the argument buffer"); -//! - every setter writes its word at the arguments' offset 0 for an index no argument has, -//! whatever argument lies there, a range's words in turn, so the last stands, and in a layout -//! of fewer than 8 bytes past its encoded length (an M4); -//! - `set_buffer` with no buffer writes 0 whatever the offset ("offset(16) must be 0 when buffer -//! is nil"); -//! - a sampler state made without `support_argument_buffers` is written as any other, and a -//! kernel samples through it as its descriptor says ("Sampler state did not have -//! supportArgumentBuffers flag set on creation"; and the probe 7 for an ID -//! written by hand); -//! - a compute or render pipeline state made without `support_indirect_command_buffers`, a tile -//! pipeline's among them, is written as its resource ID, which is 0 ("Setting a pipeline that -//! does not have supportIndirectCommandBuffers = YES is invalid"). An indirect command a kernel -//! encodes with that word names no state, as one encoded from `None` does: Metal's GPU faulted -//! running one, and the runtime's execution runs nothing for it; -//! - an indirect command buffer of no command types is written as its resource ID, as a buffer of -//! command types is. Its command types decide nothing about the word: the ID is the buffer's -//! place among the device's indirect command buffers, so two buffers encoded in one process take -//! two IDs whatever their command types, and the first of them takes 1 whichever it is (an M3 -//! Max, macOS 27.0.1, build 26A434, the validation layer off, one shape per process, four -//! processes a shape, all four alike: a buffer of no command types and a `Draw` buffer encoded -//! side by side into one argument buffer took `0100000000000000` and `0200000000000000` in the -//! order they were made, either order, and so did two `Draw` buffers and two buffers of no -//! command types; `probes/icb_argument_encode_and_copy_destinations.m`). A kernel that reads -//! such a word reaches the buffer: `command_buffer::size()` answered 4 for a buffer of 4 -//! commands and no command types, and `render_command(cb, 0).reset()` ran with no fault and no -//! error, where the same reset on a `Draw` buffer removed the draw the CPU had set (the same -//! probe, four processes a shape). A render pass's execution of such a buffer paints nothing, -//! before the kernel and after it. -//! -//! Where plain Metal's result is undefined (memory-dependent, a crash, or unmeasured), the call is -//! refused, as validation refuses it: the list above; -//! - a buffer offset at or past the buffer's length (`OffsetOutOfRange`); -//! - an object of another device (`ForeignObject`). -//! -//! **What the runtime does not build has no setter**: the runtime has no intersection function -//! tables or acceleration structures (ray tracing is out of scope), and its depth-stencil states -//! have no resource ID, so their arguments keep the bytes the buffer holds. A render pipeline -//! state's resource ID is its ID among the states made with `supportIndirectCommandBuffers`, as a -//! compute state's is. - -use super::buffer::Buffer; -use super::device::carry::LineDevice; -use super::device::device_error; -use super::error::{internal, invalid, nil, Error, Problem}; -use super::function_table::VisibleFunctionTable; -use super::indirect_command_buffer::IndirectCommandBuffer; -use super::library::Function; -use super::pipeline::{ComputePipelineState, RenderPipelineState}; -use super::sampler::SamplerState; -use super::texture::Texture; -use super::{Device, StorageMode}; -use crate::derived::DerivedMap; -use metal2vulkan::bind::{ - ArgumentBufferLayout, ArgumentDescriptor, ArgumentLayoutError, ArgumentPlace, ArgumentType, - ARGUMENT_HANDLE_BYTES, -}; -use metal2vulkan::reflection::BufferBinding; -use metal2vulkan::Budget; -use std::ops::Range; -use std::ptr::NonNull; -use std::sync::Arc; - -/// What an argument encoder call did wrong (`Problem::ArgumentEncoder`). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum ArgumentEncoderProblem { - /// The layout cannot be made: no argument buffer at the function's buffer index, an array of - /// arrays, or descriptors Metal stops (`bind::ArgumentLayoutError`). Boxed, so a [`Problem`] - /// stays small: an [`Error`] holds one in each of two kinds. - /// - /// Basis: unknown (the layout's own refusals carry their reasons in - /// `bind::ArgumentLayoutError`, which this column does not read, so Metal's answer for each is - /// not settled here). - Layout(Box), - /// `new_argument_encoder_for_buffer_at_index`: the buffer at `index` points to no argument - /// buffer, for which Metal answers nil ("No argument buffer at that index"), an - /// [`Error::Nil`]. - /// - /// Basis: metal-documented (Metal's validation says "No argument buffer at that index", for - /// which it answers nil). - NoNestedArgumentBuffer { - /// The argument's index. - index: u32, - }, - /// A setter or `constant_data` with no argument buffer set ("No argument buffer is set"). - /// - /// Basis: metal-measured (an Apple M3 Max, macOS 27.0.1: plain Metal's process ends, SIGSEGV, - /// at a setter with no argument buffer set, where `constantDataAtIndex:` answers a null - /// pointer). - NoArgumentBuffer, - /// No argument of the layout has `index` ("Index 15 does not correspond to any valid member - /// of the argument buffer", "index (1000) is outside of the valid index range"), where the 8 - /// bytes at the arguments' offset would pass the argument buffer's end, and for a range whose - /// indices pass `u32::MAX` (`index` is then `u32::MAX`). Elsewhere every setter writes there, - /// as plain Metal does. - /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal takes - /// `setBuffer:offset:atIndex:15` on a layout holding index 0 alone, writes nothing and returns, - /// its validation alone saying "index (15) is outside of the valid index range `[0, 0]`"). - NoArgument { - /// The index given. - index: u32, - }, - /// The argument at `index` is of type `found`, the call writes `expected`. - /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal takes `setTexture:atIndex:0` - /// where the layout says a pointer, and returns). - ArgumentType { - /// The argument's index. - index: u32, - /// The type the call writes. - expected: ArgumentType, - /// The argument's type. - found: ArgumentType, - }, -} - -fn problem(call: &'static str, problem: ArgumentEncoderProblem) -> Error { - invalid(call, Problem::ArgumentEncoder(problem)) -} - -/// A layout refusal of `call`: the compile layer's own errors as the device's, the rest as what -/// Metal stops. -fn layout_error(call: &'static str, error: ArgumentLayoutError) -> Error { - match error { - ArgumentLayoutError::Compile(error) => device_error(error), - other => problem(call, ArgumentEncoderProblem::Layout(Box::new(other))), - } -} - -/// An argument encoder (`MTLArgumentEncoder`): a layout and the argument buffer it writes into. -/// Cheap to clone (the layout is shared); `Send + Sync`. -#[derive(Clone, Debug)] -pub struct ArgumentEncoder { - /// Its device: a handle a recovery carries (`device/carry.rs`), as the encoder holds no - /// Vulkan object, so an encoder made before a recovery writes the arguments of what is made - /// or carried after it. - device: LineDevice, - layout: Arc, - /// The argument buffer and the offset of the arguments in it. - target: Option<(Buffer, u64)>, - label: Option, -} - -impl Device { - /// `newArgumentEncoderWithArguments:`: an encoder of the layout `arguments` give - /// (`ArgumentBufferLayout::from_descriptors`). Refused (`Invalid`, - /// [`ArgumentEncoderProblem::Layout`]): no arguments, a data type no argument has, and a - /// constant block alignment on a constant that does not start its block, as Metal raises. - pub fn new_argument_encoder_with_arguments( - &self, - arguments: &[ArgumentDescriptor], - ) -> Result { - self.at_serving(|device| device.new_argument_encoder_with_arguments_now(arguments)) - } - - /// [`Device::new_argument_encoder_with_arguments`] on the generation that serves - /// (`device/line.rs`). - pub(crate) fn new_argument_encoder_with_arguments_now( - &self, - arguments: &[ArgumentDescriptor], - ) -> Result { - const CALL: &str = "new_argument_encoder_with_arguments"; - let layout = ArgumentBufferLayout::from_descriptors(arguments) - .map_err(|error| layout_error(CALL, error))?; - Ok(ArgumentEncoder::new(self, Arc::new(layout))) - } - - /// `newArgumentEncoderWithBufferBinding:`: an encoder of the argument buffer a reflected - /// buffer binding describes, a library's or a pipeline's, laid out from its struct type as - /// Metal lays it out (`ArgumentBufferLayout::from_buffer_binding`): a library's binding gives - /// the function's layout, and a pipeline's, whose arrays of textures, samplers and pointers, - /// and of structs of them only, reflect stride 0, an encoder that writes every element of such an array at element - /// 0's place. A plain buffer of a struct gives the encoder Metal makes of it, each constant - /// member 8 bytes aligned to 8 at its offset (an M3 Max's answer; an M4's is never longer or - /// more aligned), and a binding with no struct type (a plain buffer of a scalar, vector or - /// matrix) Metal's encoder of no bytes, alignment 1; Metal's API validation lets each through. - /// Refused: an array of arrays (`Invalid`, [`ArgumentEncoderProblem::Layout`]), as for - /// [`Function::new_argument_encoder_with_buffer_index`]; a member whose encoder Metal's was - /// not measured for (`Unsupported`), such as a plain buffer's pointer member. - pub fn new_argument_encoder_with_buffer_binding( - &self, - binding: &BufferBinding, - ) -> Result { - self.at_serving(|device| device.new_argument_encoder_with_buffer_binding_now(binding)) - } - - /// [`Device::new_argument_encoder_with_buffer_binding`] on the generation that serves - /// (`device/line.rs`). - pub(crate) fn new_argument_encoder_with_buffer_binding_now( - &self, - binding: &BufferBinding, - ) -> Result { - const CALL: &str = "new_argument_encoder_with_buffer_binding"; - let layout = ArgumentBufferLayout::from_buffer_binding(binding) - .map_err(|error| layout_error(CALL, error))?; - Ok(ArgumentEncoder::new(self, Arc::new(layout))) - } -} - -impl Function { - /// `newArgumentEncoderWithBufferIndex:`: an encoder of the argument buffer the function takes - /// at buffer index `index`, as its AIR lays it out - /// (`library::Function::argument_buffer_layout`, decoded once per function and index). - /// Refused: no argument buffer at the index, or an array of arrays (`Invalid`, - /// [`ArgumentEncoderProblem::Layout`]), as Metal stops or raises (a plain buffer at the index - /// fails Metal's API validation); the decode's errors as a pipeline - /// creation's (`Compile`, `Unsupported`). - pub fn new_argument_encoder_with_buffer_index( - &self, - index: u32, - ) -> Result { - const CALL: &str = "new_argument_encoder_with_buffer_index"; - let layout = DerivedMap::or_derive(self.argument_layouts(), index, || { - self.compile_function() - .argument_buffer_layout(index, self.constants(), &Budget::standard()) - .map(Arc::new) - .map_err(|error| layout_error(CALL, error)) - })?; - Ok(ArgumentEncoder::new(self.generation(), layout)) - } -} - -/// The offset of the arguments in an argument buffer of `length` bytes: -/// `start_offset + element · encoded_length`, refused where the arguments pass the buffer's end -/// (`RangeOutOfBounds`, as Metal's validation: "offset + encodedLength should be smaller or -/// equal to the buffer length"). -pub(super) fn target_offset( - layout: &ArgumentBufferLayout, - length: u64, - start_offset: u64, - element: u64, -) -> Result { - let size = layout.encoded_length; - let out_of_bounds = |offset| Problem::RangeOutOfBounds { - offset, - size, - length, - }; - let offset = element - .checked_mul(size) - .and_then(|bytes| bytes.checked_add(start_offset)) - .ok_or(out_of_bounds(u64::MAX))?; - match offset.checked_add(size) { - Some(end) if end <= length => Ok(offset), - _ => Err(out_of_bounds(offset)), - } -} - -/// The place of argument `index` of `layout` for a write of type `ty`, refused where the layout -/// has no such argument or one of another type. -pub(super) fn argument_place( - layout: &ArgumentBufferLayout, - index: u32, - ty: ArgumentType, -) -> Result { - let place = layout - .argument(index) - .ok_or(ArgumentEncoderProblem::NoArgument { index })?; - if place.ty != ty { - return Err(ArgumentEncoderProblem::ArgumentType { - index, - expected: ty, - found: place.ty, - }); - } - Ok(place) -} - -/// The offset in the arguments that `constantDataAtIndex:` answers for `index` of `layout`, as -/// plain Metal answers it (an M4): the offset of the argument at `index`, a -/// constant's or one of any other type, and 0 where no argument of the layout has `index`. The -/// debug layer asserts at the last two. -pub(super) fn constant_offset(layout: &ArgumentBufferLayout, index: u32) -> u64 { - layout.argument(index).map_or(0, |place| place.offset) -} - -/// The word `setBuffer:offset:atIndex:` writes for a buffer of Metal address `address` and -/// `length` bytes (or none) at `offset`: the address plus the offset, or 0 for none whatever the -/// offset, as plain Metal writes it (an M4; Metal's validation stops an -/// offset other than 0 there). Refused as Metal's validation refuses: an offset at or past the -/// length. -pub(super) fn buffer_word(buffer: Option<(u64, u64)>, offset: u64) -> Result { - match buffer { - None => Ok(0), - Some((_, length)) if offset >= length => Err(Problem::OffsetOutOfRange { offset, length }), - // An address is below 2^48 (`address.rs`) and the offset below the buffer's length. - Some((address, _)) => Ok(address.wrapping_add(offset)), - } -} - -impl ArgumentEncoder { - fn new(device: &Device, layout: Arc) -> ArgumentEncoder { - ArgumentEncoder { - device: LineDevice::new(device), - layout, - target: None, - label: None, - } - } - - /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained - /// device: of the generation the encoder was made on, then of each one the device's - /// recoveries carried it to. The handle is the caller's: it keeps meaning that generation - /// while held. - pub fn device(&self) -> Device { - self.device.generation().clone() - } - - /// `label`: `None` until one is set. - pub fn label(&self) -> Option<&str> { - self.label.as_deref() - } - - /// `setLabel:`. - pub fn set_label(&mut self, label: &str) { - self.label = Some(label.to_owned()); - } - - /// `encodedLength`: the bytes the encoder's arguments take in an argument buffer. - pub fn encoded_length(&self) -> u64 { - self.layout.encoded_length - } - - /// `alignment`. - pub fn alignment(&self) -> u64 { - self.layout.alignment - } - - /// The layout the encoder writes (a runtime extension): where each argument goes. - pub fn layout(&self) -> &ArgumentBufferLayout { - &self.layout - } - - /// `setArgumentBuffer:offset:`: write the arguments into `buffer` from `offset` on; `None` - /// sets no buffer, and a later write is refused until one is set. Refused (`Invalid`): a - /// buffer of another device, a `Private` one (`StorageMode`), and one whose `offset + - /// encoded_length` passes its length (`RangeOutOfBounds`), as Metal's validation stops them. - pub fn set_argument_buffer( - &mut self, - buffer: Option<&Buffer>, - offset: u64, - ) -> Result<(), Error> { - self.target("set_argument_buffer", buffer, offset, 0) - } - - /// `setArgumentBuffer:startOffset:arrayElement:`: the arguments of element `array_element` - /// of an array of argument buffers from `start_offset`, at `start_offset + array_element · - /// encoded_length`. Refused as [`set_argument_buffer`](Self::set_argument_buffer). - pub fn set_argument_buffer_start_offset_array_element( - &mut self, - buffer: Option<&Buffer>, - start_offset: u64, - array_element: u64, - ) -> Result<(), Error> { - self.target( - "set_argument_buffer_start_offset_array_element", - buffer, - start_offset, - array_element, - ) - } - - fn target( - &mut self, - call: &'static str, - buffer: Option<&Buffer>, - start_offset: u64, - element: u64, - ) -> Result<(), Error> { - let Some(buffer) = buffer else { - self.target = None; - return Ok(()); - }; - if !buffer.generation().same(self.device.generation()) { - return Err(buffer.generation().foreign(call, self.device.generation())); - } - if buffer.storage_mode() == StorageMode::Private || buffer.mapped_contents().is_none() { - return Err(invalid(call, Problem::StorageMode)); - } - let offset = target_offset(&self.layout, buffer.length(), start_offset, element) - .map_err(|problem| invalid(call, problem))?; - self.target = Some((buffer.clone(), offset)); - Ok(()) - } - - /// The argument buffer's mapping at the arguments' offset, refused when none is set. - fn mapped(&self, call: &'static str) -> Result, Error> { - let (buffer, offset) = self - .target - .as_ref() - .ok_or_else(|| problem(call, ArgumentEncoderProblem::NoArgumentBuffer))?; - let contents = buffer - .mapped_contents() - .ok_or_else(|| internal("an argument buffer lost its mapping"))?; - // `target` checked `offset + encoded_length` against the buffer's length. - NonNull::new(contents.as_ptr().wrapping_add(*offset as usize)) - .ok_or_else(|| internal("an argument buffer's mapping is null")) - } - - /// The place of argument `index` for a write of type `ty`, inside the encoded length. - fn place( - &self, - call: &'static str, - index: u32, - ty: ArgumentType, - ) -> Result { - let place = argument_place(&self.layout, index, ty).map_err(|p| problem(call, p))?; - match place.offset.checked_add(place.size) { - Some(end) if end <= self.layout.encoded_length => Ok(place), - _ => Err(internal("an argument past its layout's encoded length")), - } - } - - /// The offset of argument `index` for a write of type `ty`: the argument's, or, where no - /// argument of the layout has `index`, the arguments' offset 0, whatever argument lies there, - /// as plain Metal writes every setter's word, a range's each in turn (an M4; no other byte - /// changed; Metal's debug layer asserts). The 8 bytes pass the encoded length of a layout of - /// fewer, as Metal's did in a layout of 4; where they would pass the argument buffer's end, - /// which holds memory Metal's result depends on, the refusal stands (`NoArgument`). - fn offset(&self, call: &'static str, index: u32, ty: ArgumentType) -> Result { - let inside = |(buffer, at): &(Buffer, u64)| { - at.checked_add(ARGUMENT_HANDLE_BYTES) - .is_some_and(|end| end <= buffer.length()) - }; - if self.layout.argument(index).is_none() && self.target.as_ref().is_some_and(inside) { - return Ok(0); - } - Ok(self.place(call, index, ty)?.offset) - } - - /// Write `words[k]` at argument `first + k`, each of type `ty` (at its [`offset`](Self::offset)): - /// every index checked before any is written, and the words written in order, so the last of - /// those at one offset stands. - fn write( - &self, - call: &'static str, - ty: ArgumentType, - first: u32, - words: &[u64], - ) -> Result<(), Error> { - let at = self.mapped(call)?; - let mut offsets = Vec::with_capacity(words.len()); - for k in 0..words.len() { - let index = u32::try_from(k) - .ok() - .and_then(|k| first.checked_add(k)) - .ok_or_else(|| { - problem(call, ArgumentEncoderProblem::NoArgument { index: u32::MAX }) - })?; - offsets.push(self.offset(call, index, ty)?); - } - // The bytes written, from the mapping's first: reported once written. - let mut wrote: Option> = None; - for (offset, word) in offsets.into_iter().zip(words) { - let end = offset + ARGUMENT_HANDLE_BYTES; - wrote = Some(wrote.map_or(offset..end, |w| w.start.min(offset)..w.end.max(end))); - let bytes = word.to_le_bytes(); - debug_assert_eq!(bytes.len() as u64, ARGUMENT_HANDLE_BYTES); - // SAFETY: `mapped` is the argument buffer's mapping at the arguments' offset, whose - // `encoded_length` bytes lie inside the buffer (`target`), and `offset` keeps - // `offset + 8` inside the buffer: inside those bytes (`place`), or 0 where the - // arguments' offset plus 8 is at most the buffer's length. A command that reads or - // writes them meanwhile races, as on Metal. - unsafe { - std::ptr::copy_nonoverlapping( - bytes.as_ptr(), - at.as_ptr().add(offset as usize), - bytes.len(), - ) - }; - } - // A write of host pages a consumer logs is the runtime's own, which its log does not see: - // reported, so the copies of the pages take it (`dirty_pages.rs`). - if let (Some((buffer, _)), Some(wrote)) = (&self.target, wrote) { - let first = at.as_ptr() as u64; - buffer.wrote_host(first + wrote.start..first + wrote.end); - } - Ok(()) - } - - /// Refuse an object of another device. - fn check_device(&self, call: &'static str, device: &Device) -> Result<(), Error> { - if device.same(self.device.generation()) { - Ok(()) - } else { - Err(device.foreign(call, self.device.generation())) - } - } - - fn buffer_word( - &self, - call: &'static str, - buffer: Option<&Buffer>, - offset: u64, - ) -> Result { - if let Some(buffer) = buffer { - self.check_device(call, buffer.generation())?; - } - buffer_word(buffer.map(|b| (b.gpu_address().0, b.length())), offset) - .map_err(|p| invalid(call, p)) - } - - /// `setBuffer:offset:atIndex:`: the buffer's Metal address plus `offset`, or 0 for `None` - /// whatever the offset; at an index no argument has, at the arguments' offset 0, as plain - /// Metal writes both (the module docs). Refused (`Invalid`): as the module docs list, and an - /// offset at or past the buffer's length (`OffsetOutOfRange`). - pub fn set_buffer( - &self, - buffer: Option<&Buffer>, - offset: u64, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_buffer"; - let word = self.buffer_word(CALL, buffer, offset)?; - self.write(CALL, ArgumentType::Buffer, index, &[word]) - } - - /// `setBuffers:offsets:withRange:`: `buffers[k]` at `offsets[k]` at index `first + k`. - /// Refused as [`set_buffer`](Self::set_buffer) is for each, and when the slices' lengths - /// differ (`LengthMismatch`); nothing is written then. - pub fn set_buffers( - &self, - buffers: &[Option<&Buffer>], - offsets: &[u64], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_buffers"; - if buffers.len() != offsets.len() { - return Err(invalid(CALL, Problem::LengthMismatch)); - } - let words = buffers - .iter() - .zip(offsets) - .map(|(buffer, offset)| self.buffer_word(CALL, *buffer, *offset)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::Buffer, first, &words) - } - - fn texture_word(&self, call: &'static str, texture: Option<&Texture>) -> Result { - match texture { - None => Ok(0), - Some(texture) => { - self.check_device(call, texture.generation())?; - Ok(texture.gpu_resource_id().0) - } - } - } - - /// `setTexture:atIndex:`: the texture's resource ID, or 0 for `None`; at an index no argument - /// has, at the arguments' offset 0, as plain Metal writes it (the module docs). - pub fn set_texture(&self, texture: Option<&Texture>, index: u32) -> Result<(), Error> { - const CALL: &str = "set_texture"; - let word = self.texture_word(CALL, texture)?; - self.write(CALL, ArgumentType::Texture, index, &[word]) - } - - /// `setTextures:withRange:`: `textures[k]` at index `first + k`. - pub fn set_textures(&self, textures: &[Option<&Texture>], first: u32) -> Result<(), Error> { - const CALL: &str = "set_textures"; - let words = textures - .iter() - .map(|texture| self.texture_word(CALL, *texture)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::Texture, first, &words) - } - - fn sampler_word( - &self, - call: &'static str, - sampler: Option<&SamplerState>, - ) -> Result { - match sampler { - None => Ok(0), - Some(sampler) => { - self.check_device(call, sampler.generation())?; - Ok(sampler.gpu_resource_id().0) - } - } - } - - /// `setSamplerState:atIndex:`: the sampler state's resource ID, or 0 for `None`. A state made - /// without `support_argument_buffers` is written too, and a kernel samples through it, as - /// plain Metal does (Metal's API validation stops it). - pub fn set_sampler_state( - &self, - sampler: Option<&SamplerState>, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_sampler_state"; - let word = self.sampler_word(CALL, sampler)?; - self.write(CALL, ArgumentType::Sampler, index, &[word]) - } - - /// `setSamplerStates:withRange:`: `samplers[k]` at index `first + k`. - pub fn set_sampler_states( - &self, - samplers: &[Option<&SamplerState>], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_sampler_states"; - let words = samplers - .iter() - .map(|sampler| self.sampler_word(CALL, *sampler)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::Sampler, first, &words) - } - - fn compute_word( - &self, - call: &'static str, - state: Option<&ComputePipelineState>, - ) -> Result { - match state { - None => Ok(0), - Some(state) => { - // The state's program, held while its device is checked (`pipeline/carry.rs`). - let _held = state.hold(); - self.check_device(call, state.bound_device()?)?; - Ok(state.gpu_resource_id().0) - } - } - } - - /// `setComputePipelineState:atIndex:`: the state's resource ID, or 0 for `None`; a state made - /// without `support_indirect_command_buffers` writes its ID, 0, as plain Metal writes it (the - /// module docs). - pub fn set_compute_pipeline_state( - &self, - state: Option<&ComputePipelineState>, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_compute_pipeline_state"; - let word = self.compute_word(CALL, state)?; - self.write(CALL, ArgumentType::ComputePipelineState, index, &[word]) - } - - /// `setComputePipelineStates:withRange:`: `states[k]` at index `first + k`. - pub fn set_compute_pipeline_states( - &self, - states: &[Option<&ComputePipelineState>], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_compute_pipeline_states"; - let words = states - .iter() - .map(|state| self.compute_word(CALL, *state)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::ComputePipelineState, first, &words) - } - - fn render_word( - &self, - call: &'static str, - state: Option<&RenderPipelineState>, - ) -> Result { - match state { - None => Ok(0), - Some(state) => { - // The state's program, held while its device is checked (`pipeline/carry.rs`). - let _held = state.hold(); - self.check_device(call, state.bound_device()?)?; - Ok(state.gpu_resource_id().0) - } - } - } - - /// `setRenderPipelineState:atIndex:`: the state's resource ID, or 0 for `None`; a state made - /// without `support_indirect_command_buffers`, a tile pipeline's among them, writes its ID, - /// 0, as plain Metal writes it (the module docs). - pub fn set_render_pipeline_state( - &self, - state: Option<&RenderPipelineState>, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_render_pipeline_state"; - let word = self.render_word(CALL, state)?; - self.write(CALL, ArgumentType::RenderPipelineState, index, &[word]) - } - - /// `setRenderPipelineStates:withRange:`: `states[k]` at index `first + k`. - pub fn set_render_pipeline_states( - &self, - states: &[Option<&RenderPipelineState>], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_render_pipeline_states"; - let words = states - .iter() - .map(|state| self.render_word(CALL, *state)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::RenderPipelineState, first, &words) - } - - fn command_buffer_word( - &self, - call: &'static str, - buffer: Option<&IndirectCommandBuffer>, - ) -> Result { - match buffer { - None => Ok(0), - Some(buffer) => { - self.check_device(call, buffer.generation())?; - Ok(buffer.gpu_resource_id().0) - } - } - } - - /// `setIndirectCommandBuffer:atIndex:`: the buffer's resource ID (`gpu_resource_id`, a small - /// integer of the buffers' own space, as Metal writes it), or 0 for `None`. A buffer of no - /// command types encodes its own ID as any other buffer's, as plain Metal encodes it: its - /// command types decide nothing about the word (the module docs). - pub fn set_indirect_command_buffer( - &self, - buffer: Option<&IndirectCommandBuffer>, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_indirect_command_buffer"; - let word = self.command_buffer_word(CALL, buffer)?; - self.write(CALL, ArgumentType::IndirectCommandBuffer, index, &[word]) - } - - /// `setIndirectCommandBuffers:withRange:`: `buffers[k]` at index `first + k`. - pub fn set_indirect_command_buffers( - &self, - buffers: &[Option<&IndirectCommandBuffer>], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_indirect_command_buffers"; - let words = buffers - .iter() - .map(|buffer| self.command_buffer_word(CALL, *buffer)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::IndirectCommandBuffer, first, &words) - } - - fn table_word( - &self, - call: &'static str, - table: Option<&VisibleFunctionTable>, - ) -> Result { - match table { - None => Ok(0), - Some(table) => { - self.check_device(call, &table.device())?; - Ok(table.gpu_resource_id().0) - } - } - } - - /// `setVisibleFunctionTable:atIndex:`: the table's resource ID, or 0 for `None` (resolved for a - /// dispatch of the state that made the table). - pub fn set_visible_function_table( - &self, - table: Option<&VisibleFunctionTable>, - index: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_visible_function_table"; - let word = self.table_word(CALL, table)?; - self.write(CALL, ArgumentType::VisibleFunctionTable, index, &[word]) - } - - /// `setVisibleFunctionTables:withRange:`: `tables[k]` at index `first + k`. - pub fn set_visible_function_tables( - &self, - tables: &[Option<&VisibleFunctionTable>], - first: u32, - ) -> Result<(), Error> { - const CALL: &str = "set_visible_function_tables"; - let words = tables - .iter() - .map(|table| self.table_word(CALL, *table)) - .collect::, _>>()?; - self.write(CALL, ArgumentType::VisibleFunctionTable, first, &words) - } - - /// `constantDataAtIndex:`: the CPU address of the constant at `index` in the argument - /// buffer, for the program to write its bytes. As plain Metal answers (the module docs): at an - /// argument of another type, that argument's address, and at an index no argument has, the - /// arguments' start (offset 0); the debug layer asserts at both. Refused (`Invalid`): no - /// argument buffer set. - pub fn constant_data(&self, index: u32) -> Result, Error> { - const CALL: &str = "constant_data"; - let at = self.mapped(CALL)?; - let offset = constant_offset(&self.layout, index); - if offset > self.layout.encoded_length { - return Err(internal("a constant past its layout's encoded length")); - } - // The constant lies inside the encoded length (the layout's), inside the mapping - // (`target`); offset 0 is the arguments' start. - NonNull::new(at.as_ptr().wrapping_add(offset as usize)) - .ok_or_else(|| internal("an argument buffer's mapping is null")) - } - - /// `newArgumentEncoderForBufferAtIndex:`: an encoder of the argument buffer the buffer - /// argument at `index` points to, with no argument buffer set. - /// - /// Every index that names no nested argument buffer answers `Nil` - /// ([`NoNestedArgumentBuffer`](ArgumentEncoderProblem::NoNestedArgumentBuffer)), because plain - /// Metal answers **nil** for each of them rather than raising: measured on an Apple M3 Max - /// under macOS 27.0.1 over one layout's own indices — a plain `device float *`, a pointer to a - /// struct of constants, an inline struct of a texture and a sampler, a texture, a sampler, an - /// array of textures, an array of samplers, an array of structs, an indirect command buffer, a - /// compute pipeline state, and an index past the layout — and an encoder only for a pointer - /// whose pointee holds a resource (`metal2vulkan-conformance`'s - /// `probes/argument_descriptor_types.m`, held by its `argument-encoder-cross-nested` case). - /// So the index's **reason** for having no nested buffer changes nothing a program sees, and - /// an `Invalid` here would refuse what plain Metal answers. - pub fn new_argument_encoder_for_buffer_at_index( - &self, - index: u32, - ) -> Result { - const CALL: &str = "new_argument_encoder_for_buffer_at_index"; - let nested = self - .layout - .argument(index) - .filter(|place| place.ty == ArgumentType::Buffer) - .and_then(|place| place.nested) - .ok_or_else(|| { - let problem = ArgumentEncoderProblem::NoNestedArgumentBuffer { index }; - nil(CALL, Problem::ArgumentEncoder(problem)) - })?; - Ok(ArgumentEncoder::new(self.device.generation(), nested)) - } -} diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs deleted file mode 100644 index 590f5a131..000000000 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ /dev/null @@ -1,2281 +0,0 @@ -//! One stage's argument table: the buffers with their offsets, inline bytes, textures, and sampler -//! states with their LOD clamps an encoder binds by Metal index. A compute encoder has one, a -//! render encoder one per stage (vertex and fragment); every `set_*` call of either is one of these -//! methods, with the same refusals. -//! -//! Inline bytes (`setBytes:length:atIndex:` and its forms) are copied at the call into the command -//! buffer's upload arena (`upload.rs`), as Metal copies them, so the caller's memory may change at -//! once; the bind layer states them as `BoundBuffer::Bytes`, and the binder binds the copy where -//! the plan writes `WriteSource::InlineBytes` or a vertex buffer. -//! -//! What a bound texture's usage allows, and what a sampler's clamps sample, is checked at the -//! command that uses the slot, against the function's use of it; binding checks only the index -//! range, the object's device, a buffer offset against the buffer's length, and that a texture is -//! not memoryless (Metal's validation stops binding one; a Metal probe on an M4). -//! -//! Every object a table binds is held until its encoder's command buffer completes, as Metal (with -//! retained references) holds what an encoder was handed: a no-copy buffer bound, then released by -//! the program, ran its deallocator only after its command buffer completed, whether a command used -//! it, it was replaced before any did, or it was bound after the last (the M3 Max under macOS -//! 27.0.1, probes `dealloc-probe` and `dealloc-probe2`, compute and render encoders). A command -//! that uses the table retains what it binds (`ArgumentTable::retain`); an object replaced or -//! unbound that no such command retained, and one still bound as the encoder ends, is retained -//! then (`let_go`, `ArgumentTable::let_go_all`). Each object names the core that holds it from -//! such a retain (`retained::HeldBy`), so an object retained once is not retained again by that -//! core, whichever slot binds it: a bind before each draw, and a draw that binds objects an -//! earlier draw of the encoder bound, retain nothing of their own. -//! -//! A compute encoder's table differs in one answer, as plain Metal's compute encoder gave it on an -//! M4 where its API validation asserts: it holds a buffer bound past its length, which a dispatch -//! refuses only where the kernel reads the slot (a read there is past the buffer: memory decides -//! it). A render stage's table refuses that at the call, as Metal's validation does; plain Metal's -//! render form is not measured. Both tables' stride forms hold a stride as its low 32 bits, -//! `MTLAttributeStrideStatic`'s included ([`per_bind_stride`]). -//! -//! An offset set at an index with no buffer bound is no change in either, as plain Metal's render -//! and compute encoders both take it ([`ArgumentTable::take_buffer_offset`]). - -use super::address_map::SamplerMaps; -use super::binding::bound_sampler; -use super::buffer::{Buffer, ReadApart}; -use super::device::lock; -use super::device::Device; -use super::encoder::EncoderCore; -use super::error::{invalid, Error, Problem}; -use super::function_table::{FunctionTableProblem, VisibleFunctionTable}; -use super::live_bind::Reshape; -use super::residency::whole_use; -use super::resource::ResourceKey; -use super::retained::HeldBy; -use super::sampler::SamplerState; -use super::texture::Texture; -use super::tracker::{Access, Use}; -use super::upload::Upload; -use super::work_counts::{Counting, ReshapedBy}; -use ash::vk; -use metal2vulkan::bind::{ - BindState, BoundBuffer, BoundSampler, BoundTexture, BufferRanges, StageTable, -}; -use metal2vulkan::device::DriverWorkaround; -use metal2vulkan::pipeline::{ - BufferKind, PipelineInterface, RenderPipeline, SlotClass, SlotInterface, SlotRef, Stage, -}; -use std::any::Any; -use std::collections::btree_map::Entry; -use std::collections::{BTreeMap, BTreeSet}; -use std::ops::Range; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, PoisonError}; - -/// Entries of a buffer table (`setBuffer:offset:atIndex:` and its stage forms). -pub(super) const BUFFER_SLOTS: u32 = 31; -/// Entries of a texture table (`setTexture:atIndex:` and its stage forms). -pub(super) const TEXTURE_SLOTS: u32 = 128; -/// Entries of a sampler table (`setSamplerState:atIndex:` and its stage forms). -pub(super) const SAMPLER_SLOTS: u32 = 16; -/// The most bytes one `setBytes:length:atIndex:` (or a stage form) takes: Metal's documented -/// limit for inline bytes, 4 KiB. -pub(super) const INLINE_BYTES_LIMIT: u64 = 4096; - -/// The stages whose buffer slots [`AtBindViews`] keeps, in its order. -const VIEW_STAGES: [Stage; 5] = [ - Stage::Vertex, - Stage::Fragment, - Stage::Kernel, - Stage::Object, - Stage::Mesh, -]; - -/// A pipeline state's buffer slots, per stage, whose bind offset class tells the device's uniform -/// view base alignment apart (`StageTable::at_bind_views`): at first those its functions read -/// through a uniform view (`PipelineInterface::uniform_view_buffers`), which a command bound at a -/// multiple of the alignment reads at its bind offset alone (`SpecKey::RangeAtBindOffset`). A slot -/// a command binds at an offset the alignment does not divide is left out from then on: a slot -/// bound at offsets that move takes one shape and one pipeline, its view read at its residual -/// (exact at any offset), not a shape and a pipeline for each in turn, whose draws would each -/// settle and switch pipelines on the encoding thread. -/// -/// On a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` it keeps a second -/// set alike, the slots whose bind offset class tells offset 0 apart -/// (`StageTable::zero_offset_views`): at first those its functions read through a storage view -/// (`PipelineInterface::storage_view_buffers`), which a command bound at offset 0 reads at its bind -/// offset alone; a slot a command binds at another offset is left out from then on. Elsewhere that -/// set is empty, and every shape and plan is as without it. -pub(crate) struct AtBindViews { - /// Each stage's of [`VIEW_STAGES`], bit `i` for buffer index `i`. - slots: [AtomicU64; VIEW_STAGES.len()], - /// Each stage's of [`VIEW_STAGES`] that tell offset 0 apart, bit `i` for buffer index `i`. - zero_slots: [AtomicU64; VIEW_STAGES.len()], - /// The device's view base alignment (`BindState::view_base_alignment_of`). - alignment: u32, - /// The device's buffer range limits (`BufferRanges::of`), under which its states' tables - /// class their buffers' lengths (`StageTable::buffer_ranges`). - ranges: BufferRanges, - /// Whether the device reads every uniform view at its residual - /// (`pipeline::reads_views_at_bind`), which a bind state states - /// (`BindState::uniform_views_at_residual`). - at_residual: bool, - /// The slots of its tables the state's bind state holds ([`ReadSlots`]). - read: ReadSlots, -} - -impl AtBindViews { - /// The slots `interface`'s functions read through a uniform view, under the view base - /// alignment of `device`: on every device, so a command's shape and its plan are the ones the - /// translator makes of its binds there. On a device that reads every uniform view at its - /// residual (`pipeline::reads_views_at_bind`) only the key the plan gives takes its uniform - /// views' residual form (`RenderVariant::plan`, `Variant::keyed_regions`). The slots it reads - /// through a storage view tell offset 0 apart where the profile of `device` takes - /// `DriverWorkaround::PushReadsLengthenThreadPayload`, the one profile whose modules declare - /// their key (`lower::access`), which the plan keeps; none elsewhere. The state's bind state - /// holds the slots `read` holds. - pub(crate) fn new( - device: &Device, - interface: &PipelineInterface, - read: ReadSlots, - ) -> AtBindViews { - let profile = device.compile_device().profile(); - let limits = profile.limits(); - let storage_at_bind = - (profile.workarounds()).contains(&DriverWorkaround::PushReadsLengthenThreadPayload); - let storage = |stage| match storage_at_bind { - true => interface.storage_view_buffers(stage), - false => 0, - }; - AtBindViews { - slots: VIEW_STAGES.map(|stage| AtomicU64::new(interface.uniform_view_buffers(stage))), - zero_slots: VIEW_STAGES.map(|stage| AtomicU64::new(storage(stage))), - alignment: BindState::view_base_alignment_of(limits), - ranges: BufferRanges::of(limits), - at_residual: !crate::pipeline::reads_views_at_bind(device), - read, - } - } - - /// That `variant`, a pipeline a draw of the state settled, reads no slot the state's bind - /// state leaves out (`ReadSlots::check_variant`; builds with debug assertions). - #[cfg(debug_assertions)] - pub(crate) fn check_variant(&self, variant: &RenderPipeline) { - self.read.check_variant(variant); - } - - /// The device's view base alignment, which a bind state states - /// (`BindState::view_base_alignment`). - pub(crate) fn alignment(&self) -> u32 { - self.alignment - } - - /// Whether the device reads every uniform view at its residual, which a bind state states - /// (`BindState::uniform_views_at_residual`): every key its draws and dispatches take is then - /// its residual form (`RenderVariant::plan`, `Variant::keyed_regions`), so instantiation may - /// bind a uniform view over a range its bind offsets share. - pub(crate) fn at_residual(&self) -> bool { - self.at_residual - } - - /// Whether `stage`'s slots of both sets are those `table` holds (none for a stage it does not - /// keep), and its buffer range limits the device's: a table read under them that binds the - /// same offsets leaves the same out ([`ArgumentTable::at_bind_views`], - /// [`ArgumentTable::zero_offset_views`]), as it left out its own as it was read, and classes - /// its buffers' lengths alike. - pub(super) fn holds(&self, stage: Stage, table: &StageTable) -> bool { - let now = |slots: Option<&AtomicU64>| slots.map_or(0, |s| s.load(Ordering::Relaxed)); - now(self.of(stage)) == table.at_bind_views - && now(self.zero_of(stage)) == table.zero_offset_views - && table.buffer_ranges == self.ranges - } - - /// `stage`'s slots, none for a stage it does not keep. - fn of(&self, stage: Stage) -> Option<&AtomicU64> { - let at = VIEW_STAGES.iter().position(|s| *s == stage)?; - Some(&self.slots[at]) - } - - /// `stage`'s slots that tell offset 0 apart, none for a stage it does not keep. - fn zero_of(&self, stage: Stage) -> Option<&AtomicU64> { - let at = VIEW_STAGES.iter().position(|s| *s == stage)?; - Some(&self.zero_slots[at]) - } -} - -/// The render stages whose slots [`ReadSlots`] tells apart, in its order. -const READ_STAGES: [Stage; 4] = [Stage::Vertex, Stage::Fragment, Stage::Object, Stage::Mesh]; - -/// The texture and sampler slots of one stage's tables a bind state holds ([`ReadSlots`]), bit `i` -/// for index `i` of each table: as wide as Metal's tables ([`TEXTURE_SLOTS`], [`SAMPLER_SLOTS`]). -#[derive(Clone, Copy, Default, PartialEq, Eq)] -struct StageReads { - textures: u128, - samplers: u16, -} - -impl StageReads { - /// Hold `class`'s slot `index`: whether it lies inside the class's table. A buffer slot is - /// held whatever it reads ([`ReadSlots`]). - fn add(&mut self, class: SlotClass, index: u32) -> bool { - match class { - SlotClass::Buffer => return index < BUFFER_SLOTS, - SlotClass::Texture if index < TEXTURE_SLOTS => self.textures |= 1 << index, - SlotClass::Sampler if index < SAMPLER_SLOTS => self.samplers |= 1 << index, - _ => return false, - } - true - } - - /// Whether it holds `class`'s slot `index`: every buffer slot. - fn holds(&self, class: SlotClass, index: u32) -> bool { - match class { - SlotClass::Buffer => true, - SlotClass::Texture => index < TEXTURE_SLOTS && self.textures >> index & 1 != 0, - SlotClass::Sampler => index < SAMPLER_SLOTS && self.samplers >> index & 1 != 0, - } - } -} - -/// The slots of its tables a pipeline state's bind state holds (`ArgumentTable::refresh_reading`, -/// `refresh_changed`): of a render pipeline state that indirect command buffers may not hold, none -/// of whose functions resolves texture or sampler handles, translates pointers or reaches an -/// indirect command buffer (`PipelineInterface::needs_handle_translation`, -/// `needs_pointer_translation`, `reaches_command_buffers`), every buffer slot and the texture and -/// sampler slots its functions statically use (`PipelineInterface::slots`), the only texture and -/// sampler slots a plan of it reads (checked against each variant its draws settle in builds with -/// debug assertions: [`check_variant`](Self::check_variant)); of any other, every slot. A handle -/// table holds the textures bound at any slot, so a state whose functions read one holds them all; -/// so does a state indirect command buffers may hold, whose executions draw through variants of -/// their own (`LoweringInputs::replay_bindings`). Every buffer slot is held: a variant may read -/// its buffers through the root table, whose resident set is every bound buffer (`memory/roots.rs` -/// in the translator), whatever its base reads. -/// -/// A slot it leaves out is no part of the bind state: a bind there changes neither its shape nor -/// its plan, as it changes none of the state's commands. So draws of a state whose functions -/// sample one texture keep their shape and their kept draw (`render/draw_again.rs`) while draws -/// of another state between them bind other textures at a slot it leaves unread, and its kept -/// draw carried into the next encoder is not stale for such a slot left unbound there -/// (`render/carried.rs`). -pub(crate) struct ReadSlots(Option<[StageReads; READ_STAGES.len()]>); - -impl ReadSlots { - /// Every slot: a compute state's, whose bind state is read whole. - pub(crate) fn every() -> ReadSlots { - ReadSlots(None) - } - - /// The slots a render pipeline state of `pipeline`, its base, holds, one indirect command - /// buffers may hold where `executable` (the type's docs). - pub(crate) fn of(pipeline: &RenderPipeline, executable: bool) -> ReadSlots { - let interface = &pipeline.interface; - if executable - || interface.needs_handle_translation - || interface.needs_pointer_translation - || interface.reaches_command_buffers - { - return ReadSlots(None); - } - let mut stages = [StageReads::default(); READ_STAGES.len()]; - // A slot of another stage, or past its table, is held whole. - for slot in interface.slots.keys() { - let at = READ_STAGES.iter().position(|stage| *stage == slot.stage); - if !at.is_some_and(|at| stages[at].add(slot.class, slot.index)) { - return ReadSlots(None); - } - } - ReadSlots(Some(stages)) - } - - /// Whether the bind state holds `stage`'s slot of `class` at `index`: every slot of a stage - /// it does not tell apart. - fn reads(&self, stage: Stage, class: SlotClass, index: u32) -> bool { - let Some(stages) = &self.0 else { - return true; - }; - match READ_STAGES.iter().position(|of| *of == stage) { - Some(at) => stages[at].holds(class, index), - None => true, - } - } - - /// That `variant`, a pipeline a draw of the state settled (a variant of its base), reads no - /// slot it leaves out (builds with debug assertions): its functions resolve no handle, and - /// every texture and sampler slot its interface uses is held. - #[cfg(debug_assertions)] - fn check_variant(&self, variant: &RenderPipeline) { - if self.0.is_none() { - return; - } - let interface = &variant.interface; - assert!( - !interface.needs_handle_translation, - "a variant reads a handle table its base reads none of" - ); - for slot in interface.slots.keys() { - assert!( - self.reads(slot.stage, slot.class, slot.index), - "a variant uses {slot:?}, which its base's bind state leaves out" - ); - } - } -} - -/// One stage's bound objects, by Metal index. -#[derive(Default)] -pub(super) struct ArgumentTable { - /// A compute encoder's table ([`ArgumentTable::compute`]): it holds buffers bound past their - /// length (the module docs). - compute: bool, - /// Each buffer with its bind offset; a visible-function table's words at offset 0. - pub(super) buffers: BTreeMap, - /// The visible-function tables among `buffers`, by the index they share with buffers: a - /// later buffer at the index replaces the table, and a later table the buffer, as on Metal. - pub(super) function_tables: BTreeMap, - /// The indices where a visible-function table was bound and an offset then set - /// (`setBufferOffset:` and its forms): plain Metal reads the table there as the null table, - /// of size 0 and every entry null, until a table or a buffer is bound at the index again. - /// Neither `buffers` nor `function_tables` holds them. - pub(super) null_tables: BTreeSet, - /// The per-bind attribute strides of buffers in `buffers`, by index - /// (`setBuffer:offset:attributeStride:atIndex:` and its forms, [`per_bind_stride`]): a layout - /// of `MTLBufferLayoutStrideDynamic` reads its buffer at this stride. The plain setters set - /// none, which such a layout reads at stride 0. - pub(super) attribute_strides: BTreeMap, - pub(super) textures: BTreeMap, - /// The indices of `textures` that hold a memoryless texture, a texture buffer's too: none, - /// nearly always, so a command finds nothing to check ([`uses_memoryless`](Self::uses_memoryless)). - memoryless: BTreeSet, - /// Each sampler state with the LOD clamps its bind set - /// (`setSamplerState:lodMinClamp:lodMaxClamp:atIndex:`), which replace the state's. - pub(super) samplers: BTreeMap)>, - /// The bytes of `setBytes:length:atIndex:` and its forms, by index: copied at the call - /// ([`set_bytes`](Self::set_bytes)). Neither `buffers` nor `function_tables` holds the index. - pub(super) bytes: BTreeMap, - /// What the table bound as an encoder's core last retained it ([`retain`](Self::retain)). - retained: Retained, - /// Its contents' stamp, drawn afresh by every call that may change them. - stamp: Stamp, - /// The slots its last calls changed, by the stamps they took ([`Changes`]). - changes: Changes, -} - -/// A copy binds what the table binds, under a stamp of its own: a copy changed in place (a -/// pass's copies of bytes its fragment stages wrote: `render/pass_start_reads.rs`) binds others. -impl Clone for ArgumentTable { - fn clone(&self) -> ArgumentTable { - ArgumentTable { - compute: self.compute, - buffers: self.buffers.clone(), - function_tables: self.function_tables.clone(), - null_tables: self.null_tables.clone(), - attribute_strides: self.attribute_strides.clone(), - textures: self.textures.clone(), - memoryless: self.memoryless.clone(), - samplers: self.samplers.clone(), - bytes: self.bytes.clone(), - retained: self.retained.unheld(), - stamp: Stamp::fresh(), - changes: Changes::default(), - } - } -} - -/// What an argument table binds, named by a number drawn afresh for each new table (a copy -/// included) and at each call that may change what it binds, which no other table of the process -/// takes ([`ArgumentTable::stamp`]): while a table's stamp holds, it binds what it bound, by -/// identity. A call that binds each of its slots as it is bound already (the same object, offset, -/// per-bind stride and clamps) changes nothing and draws none. A table made for one command (an execution's own buffers) is filled in place before -/// any command reads it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Stamp(u64); - -/// The stamps a thread takes from the process's at once ([`Stamp::fresh`]). -const STAMP_BLOCK: u64 = 1 << 16; - -impl Stamp { - /// A stamp no table took before: the next of the calling thread's block, a range of the - /// process's stamps no other thread draws from, its next block taken once it is spent. So a - /// call that changes a table writes no memory another thread's calls write: a consumer encodes - /// a queue's command buffers on threads of their own, and where each call drew its stamp from - /// one counter of the process, each thread's calls waited for that counter's line to come - /// back from the others'. - pub(super) fn fresh() -> Stamp { - static NEXT: AtomicU64 = AtomicU64::new(0); - thread_local! { - /// The calling thread's next stamp and the end of its block. - static BLOCK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; - } - BLOCK.with(|block| { - let (mut next, mut end) = block.get(); - if next == end { - next = NEXT.fetch_add(STAMP_BLOCK, Ordering::Relaxed); - end = next + STAMP_BLOCK; - } - block.set((next + 1, end)); - Stamp(next) - }) - } - - /// Its number, which no other stamp has (read by `tests::argument_table`, a debug-build - /// test). - #[cfg(all(test, debug_assertions))] - pub(super) fn raw(self) -> u64 { - self.0 - } -} - -impl Default for Stamp { - fn default() -> Stamp { - Stamp::fresh() - } -} - -/// The slots of its last calls' changes a table keeps at least, once it noted as many, and the -/// most slots a call notes ([`Changes`]): it keeps at most twice as many, and a reader that read it -/// before those it keeps reads it whole. Enough for the binds between a pipeline state's draws -/// where draws of a few others come between, each binding a few slots: the state's bind state, -/// set aside meanwhile (`live_bind.rs`), and its kept draw, rebound (`render/draw_again.rs`), -/// bring in only what changed, found by a scan back from the newest change to their stamp. -const CHANGES_KEPT: usize = 64; - -/// The slots a table's last calls changed (or may have: a refused call's too), each with the -/// stamp the table took at that call, oldest first, and the stamp before the oldest: a reader that -/// read the table under one of those stamps brings in the slots changed since alone -/// ([`ArgumentTable::refresh_changed`]); a reader under any other stamp reads it whole. A copy of -/// a table keeps none (its stamp is its own). -#[derive(Default)] -struct Changes { - since: Option, - slots: Vec, -} - -/// A slot a call changed, with the stamp the table took at the call: of `class` at `index`, and -/// whether the call kept the buffer bound there, moving its offset or attribute stride alone -/// (`offset`). -#[derive(Clone, Copy)] -struct Changed { - stamp: Stamp, - class: SlotClass, - index: u32, - offset: bool, -} - -impl Changes { - /// Note a call that took the table from `before` to `after`, changing the slots of `class` - /// at `indices`, their offsets alone where `offset` ([`Changed`]): of more slots than are - /// kept, it leaves none to read from. - fn note( - &mut self, - (before, after): (Stamp, Stamp), - class: SlotClass, - indices: Range, - offset: bool, - ) { - if indices.len() > CHANGES_KEPT { - self.since = None; - self.slots.clear(); - return; - } - if self.slots.is_empty() { - self.since = Some(before); - } - self.slots.extend(indices.map(|index| Changed { - stamp: after, - class, - index, - offset, - })); - // Past twice the slots it keeps, the oldest calls go whole, at once, down to the newest - // calls of at most `CHANGES_KEPT` slots: a reader under the stamp one of them took saw its - // slots. At once, so a note moves the slots it keeps once in `CHANGES_KEPT` calls. - if self.slots.len() > 2 * CHANGES_KEPT { - let mut cut = self.slots.len() - CHANGES_KEPT; - while cut < self.slots.len() && self.slots[cut].stamp == self.slots[cut - 1].stamp { - cut += 1; - } - self.since = Some(self.slots[cut - 1].stamp); - self.slots.drain(..cut); - } - } - - /// The slots changed since the table's stamp was `read`, where it keeps them. - fn since(&self, read: Stamp) -> Option + Clone + '_> { - let from = match self.since == Some(read) { - true => 0, - false => (self.slots.iter()).rposition(|changed| changed.stamp == read)? + 1, - }; - Some(self.slots[from..].iter().copied()) - } -} - -/// The core an argument table was last retained into ([`EncoderCore::id`]) and the table's stamp -/// then ([`ArgumentTable::retain`]): while both hold, that core holds every object the table -/// binds. -#[derive(Default)] -struct Retained(Mutex); - -impl Retained { - /// A copy whose core is to look at every object at its next retain - /// ([`RetainedBy::unheld`]): a table's copy, which may be changed in place without its calls - /// (`render/pass_start_reads.rs`). - fn unheld(&self) -> Retained { - let mut copy = lock(&self.0).clone(); - copy.unheld = true; - Retained(Mutex::new(copy)) - } -} - -#[derive(Clone, Default)] -struct RetainedBy { - core: Option, - /// The table's stamp then: while it holds, the table binds those objects still. - stamp: Option, - /// Whether a call since bound an object that core did not hold then - /// ([`ArgumentTable::note_bound`]): until one does, the core holds every object the table - /// binds, so a retain looks at none ([`retain_into`]). - unheld: bool, - /// The objects the core holds of those the table bound since that retain, its own then - /// among them, each by the address of its [`HeldBy`] (builds with debug assertions: - /// [`check_held`](Self::check_held)). Its storage is kept from retain to retain, so a draw - /// allocates as many times with debug assertions as without. - #[cfg(debug_assertions)] - held: Vec, -} - -#[cfg(debug_assertions)] -impl RetainedBy { - /// Note the objects `objects` binds now, as the table was just retained: the core holds them - /// all. - fn note_retained(&mut self, objects: Objects<'_>) { - self.held.clear(); - let (buffers, textures, samplers) = objects; - let bound = bound_in(buffers, textures, samplers); - (self.held).extend(bound.map(|object| std::ptr::from_ref(object.held_by()).addr())); - } - - /// That every object `objects` binds is one the core holds ([`retain_into`]'s premise where - /// it looks at none): bound at its last retain, or bound since while the core held it. - fn check_held(&self, objects: Objects<'_>) { - let (buffers, textures, samplers) = objects; - for object in bound_in(buffers, textures, samplers) { - let address = std::ptr::from_ref(object.held_by()).addr(); - assert!( - self.held.contains(&address), - "an argument table binds an object its core neither retained at its last retain \ - nor held as a call bound it, and no call since noted it unheld" - ); - } - } -} - -/// What an argument table binds: its buffers, textures and sampler states, by index. -type Objects<'a> = ( - &'a BTreeMap, - &'a BTreeMap, - &'a BTreeMap)>, -); - -/// An object an argument table binds, which a command that uses the table holds. -#[derive(Clone, Copy)] -enum Bound<'a> { - Buffer(&'a Buffer), - Texture(&'a Texture), - Sampler(&'a SamplerState), -} - -impl<'a> Bound<'a> { - /// The core that holds it from a table's retain. - fn held_by(self) -> &'a HeldBy { - match self { - Bound::Buffer(buffer) => buffer.held_by(), - Bound::Texture(texture) => texture.held_by(), - Bound::Sampler(sampler) => sampler.held_by(), - } - } - - /// The key its uses name, which a core that retains it keeps: none for a sampler state. - fn key(self) -> Option { - match self { - Bound::Buffer(buffer) => Some(buffer.identity().key), - Bound::Texture(texture) => Some(texture.use_key()), - Bound::Sampler(_) => None, - } - } - - fn held(self) -> Arc { - match self { - Bound::Buffer(buffer) => buffer.held(), - Bound::Texture(texture) => texture.held(), - Bound::Sampler(sampler) => sampler.held(), - } - } - - /// The address of what [`held`](Self::held) refers to, which a core looks among those it - /// holds lately for (`retained.rs`). - fn address(self) -> usize { - match self { - Bound::Buffer(buffer) => buffer.address(), - Bound::Texture(texture) => texture.address(), - Bound::Sampler(sampler) => sampler.address(), - } - } -} - -/// One `set*Bytes` call's copy of its bytes: a region of the command buffer's upload arena -/// (`upload.rs`) written at the call, so a later write of the caller's memory reaches no -/// command, as Metal copies the bytes at the call. -#[derive(Clone)] -pub(super) struct InlineBytes { - /// The region: the bytes, then zeros to a multiple of 16 bytes, at least 16. - pub(super) region: Upload, - /// The call's length. - pub(super) len: u32, - /// The stride form's stride, its low 32 bits (`MTLAttributeStrideStatic` is `u32::MAX`); - /// `None` for the plain setters (`BoundBuffer::Bytes`). - pub(super) attribute_stride: Option, -} - -/// Refuse `index` past a table of `limit` entries. -pub(super) fn check_index(call: &'static str, index: u32, limit: u32) -> Result<(), Error> { - if index < limit { - Ok(()) - } else { - Err(invalid(call, Problem::IndexOutOfRange { index, limit })) - } -} - -/// Refuse `count` entries from `first` past a table of `limit` entries. -pub(super) fn check_range( - call: &'static str, - first: u32, - count: usize, - limit: u32, -) -> Result<(), Error> { - if count == 0 { - return Ok(()); - } - let count = u32::try_from(count).unwrap_or(u32::MAX); - check_index(call, first.saturating_add(count - 1), limit) -} - -/// Refuse `buffer` at `offset` in `call` of an encoder of `device`: a buffer of another device, -/// and, in a render stage's table (not `compute`), an offset past its length -/// ([`ArgumentTable::compute`] holds it). The table's check, and a render encoder's at the call -/// (`render/table_facts.rs`). -pub(super) fn check_bound_buffer( - device: &Device, - call: &'static str, - (buffer, offset): (&Buffer, u64), - compute: bool, -) -> Result<(), Error> { - super::encoder::check_device(device, call, buffer.generation())?; - let length = buffer.length(); - if offset > length && !compute { - return Err(invalid(call, Problem::OffsetOutOfRange { offset, length })); - } - Ok(()) -} - -/// The per-bind stride a stride form's `stride` names in a compute table or a render stage's: its -/// low 32 bits. Plain Metal reads a stride past 32 bits so, and its validation takes it (an M4 -/// under macOS 27.0.1 and an M3 Max under 26.7, compute stage-in and vertex fetch, both binding -/// forms: `2^32 + 8` and `2^63 + 8` read at 8, `2^33 + 4` at 4, `2^32` at 0). -/// -/// `MTLAttributeStrideStatic` (`u64::MAX`) is no exception: its low 32 bits, `2^32 - 1`, are the -/// stride a layout of `MTLBufferLayoutStrideDynamic` reads, a kernel's stage-in layout or a vertex -/// descriptor's. Plain Metal on an Apple M3 Max under macOS 27.0.1 answered each of the compute -/// encoder's four stride forms, and the render encoder's `setVertexBuffer:offset:attributeStride: -/// atIndex:`, bound so with the element at the bind offset for the first element and zero for -/// every element past it, the bind offset reaching the first (`metal2vulkan-conformance`'s -/// `attribute-stride-*` recordings, buffers of 512 and 64 bytes), which is a fetch at that stride: -/// element 1 lies `2^32 - 1` bytes on, past the buffer (an indirect command buffer's command read -/// the byte there in a buffer that holds it, `indirect_execute::unstrided_stride`). -/// Metal's API validation stops a draw bound so. -pub(super) fn per_bind_stride(stride: u64) -> u32 { - // Truncation is the measured answer. - stride as u32 -} - -/// Bind `value` at `index` of `table`, or unbind the index when `value` is `None`: what was -/// bound there before. -fn set_entry(table: &mut BTreeMap, index: u32, value: Option) -> Option { - match value { - Some(value) => table.insert(index, value), - None => table.remove(&index), - } -} - -/// Bind the handle `value` at `index` of `table` with `with` (its offset, its clamps), or unbind -/// the index when `value` is `None`: the handle it replaced or unbound, another object than -/// `value` ([`let_go`]). The handle already bound there (the same object) keeps -/// its hold and takes `with` alone: binding it again takes no new reference, whose count the -/// threads that release the encoder's holds share. -fn set_handle( - table: &mut BTreeMap, - index: u32, - value: Option<&T>, - with: W, -) -> Option { - match value { - Some(value) => match table.entry(index) { - Entry::Occupied(mut bound) if bound.get().0 == *value => { - bound.get_mut().1 = with; - None - } - Entry::Occupied(mut bound) => Some(bound.insert((value.clone(), with)).0), - Entry::Vacant(slot) => { - slot.insert((value.clone(), with)); - None - } - }, - None => table.remove(&index).map(|(handle, _)| handle), - } -} - -/// [`set_handle`] for a table of handles alone. -fn set_bare_handle( - table: &mut BTreeMap, - index: u32, - value: Option<&T>, -) -> Option { - match value { - Some(value) => match table.entry(index) { - Entry::Occupied(bound) if bound.get() == value => None, - Entry::Occupied(mut bound) => Some(bound.insert(value.clone())), - Entry::Vacant(slot) => { - slot.insert(value.clone()); - None - } - }, - None => table.remove(&index), - } -} - -/// Whether a setter of `values` from index `first` binds each index as it is bound already, as -/// `held(at, index, value)` tells of the value at place `at`: such a call changes nothing, and -/// the table keeps its stamp ([`ArgumentTable::changed`]). -fn binds_as(values: &[T], first: u32, held: impl Fn(usize, u32, &T) -> bool) -> bool { - (values.iter().enumerate()).all(|(at, value)| { - let index = u32::try_from(at).ok().and_then(|at| first.checked_add(at)); - index.is_some_and(|index| held(at, index, value)) - }) -} - -/// `buffer` bound at `offset`, read at `attribute_stride`, as the bind layer reads it -/// ([`ArgumentTable::stage_table`]), or `None` where it is bound past its length. -fn bound_buffer( - buffer: &Buffer, - offset: u64, - attribute_stride: Option, -) -> Option { - if offset > buffer.length() { - return None; - } - // The Metal address first, which keeps a no-copy buffer's import for good, then where the - // buffer lies, in one look. - let gpu_address = buffer.exposed_address(ReadApart::Binding).0; - let (base, device_address) = buffer.base_and_device_address(ReadApart::Binding); - Some(BoundBuffer::Buffer { - length: base + buffer.length(), - offset: base + offset, - gpu_address: gpu_address - base, - device_address: device_address.map(|address| address - base), - attribute_stride, - }) -} - -/// Inline bytes as the bind layer reads them. -fn bound_bytes(bytes: &InlineBytes) -> BoundBuffer { - BoundBuffer::Bytes { - len: bytes.len, - attribute_stride: bytes.attribute_stride, - } -} - -/// `texture` as the bind layer reads it. -fn bound_texture(texture: &Texture) -> BoundTexture { - match texture.texels() { - Some(texels) => texels.bound(texture.pixel_format(), texture.record().sampled_swizzle()), - // Its resource ID makes it a member of the handle tables that reach its slot: an argument - // buffer can name it too. - None => BoundTexture::Texture { - facts: texture.facts(), - resource_id: Some(texture.gpu_resource_id().0), - }, - } -} - -/// Whether `a` and `b` print alike (`{:?}`), told without printing them -/// ([`ArgumentTable::check_reading`]): every field as `==` compares it, but the descriptor's LOD -/// clamps and LOD bias, which print a float's sign (`0.0` and `-0.0` differ, where `==` takes -/// them for equal) and print every NaN alike (where `==` takes no NaN for equal). -/// `tests/argument_table.rs` fails when `BoundSampler` or `SamplerDescriptor` gains a field, so a -/// new one is compared here too. -#[cfg(debug_assertions)] -pub(super) fn same_as_printed(a: &BoundSampler, b: &BoundSampler) -> bool { - let alike = |x: f32, y: f32| x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan()); - let floats = |s: &BoundSampler| [s.desc.lod_min_clamp, s.desc.lod_max_clamp, s.desc.lod_bias]; - let floats_alike = (floats(a).into_iter()) - .zip(floats(b)) - .all(|(x, y)| alike(x, y)); - let [mut a, mut b] = [*a, *b]; - for desc in [&mut a.desc, &mut b.desc] { - [desc.lod_min_clamp, desc.lod_max_clamp, desc.lod_bias] = [0.0; 3]; - } - floats_alike && a == b -} - -impl ArgumentTable { - /// What commands that run with this table's bindings, as an indirect command buffer's - /// commands inherit the encoder's, may use of them, for the scheduler's order across queues - /// (`CommandBufferShared::footprint`): each buffer over all its bytes and each texture over its - /// whole image, read and written in every stage, as nothing bounds what their functions do - /// there. `None` where it binds a visible-function table, whose functions reach more. - pub(super) fn bound_uses(&self) -> Option>> { - if !self.function_tables.is_empty() { - return None; - } - let stages = vk::PipelineStageFlags2::ALL_COMMANDS; - let read = Access::new(stages, vk::AccessFlags2::MEMORY_READ); - let write = Access::new(stages, vk::AccessFlags2::MEMORY_WRITE); - let buffers = (self.buffers.values()).map(|(buffer, _)| whole_use(buffer, read, write)); - let textures = (self.textures.values()).map(|texture| texture.bound_use(read, write)); - Some(buffers.chain(textures).collect()) - } - - /// A compute encoder's table (the module docs). - pub(super) fn compute() -> ArgumentTable { - ArgumentTable { - compute: true, - ..ArgumentTable::default() - } - } - - /// The stamp of what the table binds now ([`Stamp`]). - pub(super) fn stamp(&self) -> Stamp { - self.stamp - } - - /// A call that may change the slots of `class` at `indices` (before its checks: a refused one - /// may have changed nothing, which a reader then reads again): a fresh stamp, and the slots - /// noted ([`Changes`]). A call that binds each slot as it is bound already ([`binds_as`]) - /// takes none. - fn changed(&mut self, class: SlotClass, indices: Range) { - self.changed_as(class, indices, false); - } - - /// [`changed`](Self::changed), the call's change of the buffer slots at `indices` their - /// offsets alone where `offset`: each binds the buffer it bound, and keeps binding it - /// whatever the call's checks answer ([`Changed`]). - fn changed_as(&mut self, class: SlotClass, indices: Range, offset: bool) { - let before = self.stamp; - self.stamp = Stamp::fresh(); - self.changes - .note((before, self.stamp), class, indices, offset); - } - - /// Whether buffer slot `index` binds `buffer` now: a buffer's offset moved there is the - /// change of an offset alone ([`changed_as`](Self::changed_as)). - fn binds_buffer(&self, index: u32, buffer: &Buffer) -> bool { - (self.buffers.get(&index)).is_some_and(|(bound, _)| bound == buffer) - && !self.function_tables.contains_key(&index) - } - - /// Whether buffer slot `index` holds what a buffer setter leaves there binding `buffer` at - /// `offset` with the per-bind stride `stride`: that buffer at that offset, or no buffer where - /// `buffer` is `None`, that stride, and no function table, null table or bytes. Such a call - /// changes nothing. - fn holds_buffer( - &self, - index: u32, - (buffer, offset): (Option<&Buffer>, u64), - stride: Option, - ) -> bool { - let bound = (self.buffers.get(&index)).map(|(bound, at)| (bound, *at)); - bound == buffer.map(|buffer| (buffer, offset)) - && self.attribute_strides.get(&index).copied() == stride - && !self.function_tables.contains_key(&index) - && !self.null_tables.contains(&index) - && !self.bytes.contains_key(&index) - } - - /// A call through `core` binds `object`: where `core` does not hold it (from a retain of its - /// own, `retained::HeldBy`), or is not the core the table was last retained into, the next - /// retain looks at every object ([`retain_into`]); else `core` holds it until its command - /// buffer completes, and keeps its key. - fn note_bound(&mut self, core: &EncoderCore, object: Bound<'_>) { - let id = core.id(); - let retained = self - .retained - .0 - .get_mut() - .unwrap_or_else(PoisonError::into_inner); - let held_here = retained.core == Some(id) && object.held_by().is(id); - if !held_here { - retained.unheld = true; - } - #[cfg(debug_assertions)] - if held_here { - let address = std::ptr::from_ref(object.held_by()).addr(); - if !retained.held.contains(&address) { - retained.held.push(address); - } - } - } - - /// Refuse `buffer` at `offset` in `call` of an encoder of `core`: a buffer of another device, - /// and, in a render stage's table, an offset past its length (a compute table holds it). - fn check_buffer( - &self, - core: &EncoderCore, - call: &'static str, - buffer: &Buffer, - offset: u64, - ) -> Result<(), Error> { - check_bound_buffer(core.device(), call, (buffer, offset), self.compute) - } - - /// `setBuffer:offset:atIndex:` (`None` unbinds the index) in an encoder of `core`, with no - /// per-bind stride. Refused: an index past the table, a buffer of another device, and in a - /// render stage's table an offset past the buffer's length. - pub(super) fn set_buffer( - &mut self, - core: &mut EncoderCore, - call: &'static str, - buffer: Option<&Buffer>, - offset: u64, - index: u32, - ) -> Result<(), Error> { - self.bind_buffer(core, call, buffer, offset, None, index) - } - - /// `setBuffer:offset:attributeStride:atIndex:` (`None` unbinds the index) in an encoder of - /// `core`, at the per-bind stride `stride` names ([`per_bind_stride`]). Refused as - /// [`set_buffer`](Self::set_buffer) is. - pub(super) fn set_buffer_with_stride( - &mut self, - core: &mut EncoderCore, - call: &'static str, - buffer: Option<&Buffer>, - offset: u64, - stride: u64, - index: u32, - ) -> Result<(), Error> { - let stride = per_bind_stride(stride); - self.bind_buffer(core, call, buffer, offset, Some(stride), index) - } - - /// [`set_buffer_with_stride`](Self::set_buffer_with_stride) at the per-bind stride `stride`, - /// none for the plain setter. - fn bind_buffer( - &mut self, - core: &mut EncoderCore, - call: &'static str, - buffer: Option<&Buffer>, - offset: u64, - stride: Option, - index: u32, - ) -> Result<(), Error> { - // A call that binds the slot as it is bound already changes nothing. - if !self.holds_buffer(index, (buffer, offset), stride) { - let same = buffer.is_some_and(|buffer| self.binds_buffer(index, buffer)); - self.changed_as(SlotClass::Buffer, index..index.saturating_add(1), same); - } - check_index(call, index, BUFFER_SLOTS)?; - if let Some(buffer) = buffer { - self.check_buffer(core, call, buffer, offset)?; - self.note_bound(core, Bound::Buffer(buffer)); - } - let replaced = set_handle(&mut self.buffers, index, buffer, offset); - set_entry(&mut self.attribute_strides, index, stride); - self.function_tables.remove(&index); - self.null_tables.remove(&index); - self.bytes.remove(&index); - if let Some(replaced) = replaced { - let_go(core, Bound::Buffer(&replaced)); - } - Ok(()) - } - - /// `setBuffers:offsets:withRange:`: `buffers[i]` at offset `offsets[i]` at index `first + i`, - /// with no per-bind stride. Refused as [`set_buffer`](Self::set_buffer) is, - /// and when the slices' lengths differ; a refusal binds none of them. - pub(super) fn set_buffers( - &mut self, - core: &mut EncoderCore, - call: &'static str, - buffers: &[Option<&Buffer>], - offsets: &[u64], - first: u32, - ) -> Result<(), Error> { - self.set_buffers_with_strides(core, call, buffers, offsets, None, first) - } - - /// `setBuffers:offsets:attributeStrides:withRange:`: as [`set_buffers`](Self::set_buffers), - /// each buffer at the per-bind stride `strides[i]` names ([`per_bind_stride`]) where `strides` - /// is given. Refused as `set_buffers` is. - pub(super) fn set_buffers_with_strides( - &mut self, - core: &mut EncoderCore, - call: &'static str, - buffers: &[Option<&Buffer>], - offsets: &[u64], - strides: Option<&[u64]>, - first: u32, - ) -> Result<(), Error> { - let held = binds_as(buffers, first, |at, index, buffer| { - let offset = offsets.get(at).copied(); - let stride = strides.map(|strides| strides.get(at).copied().map(per_bind_stride)); - match (offset, stride) { - (Some(offset), None) => self.holds_buffer(index, (*buffer, offset), None), - (Some(offset), Some(Some(stride))) => { - self.holds_buffer(index, (*buffer, offset), Some(stride)) - } - _ => false, - } - }); - if !held { - self.changed(SlotClass::Buffer, span(first, buffers.len())); - } - if buffers.len() != offsets.len() || strides.is_some_and(|s| s.len() != buffers.len()) { - return Err(invalid(call, Problem::LengthMismatch)); - } - check_range(call, first, buffers.len(), BUFFER_SLOTS)?; - for (buffer, &offset) in buffers.iter().zip(offsets) { - if let Some(buffer) = buffer { - self.check_buffer(core, call, buffer, offset)?; - } - } - let strides = (0..buffers.len()).map(|i| strides.map(|s| per_bind_stride(s[i]))); - for (((buffer, &offset), stride), index) in - buffers.iter().zip(offsets).zip(strides).zip(first..) - { - if let Some(buffer) = buffer { - self.note_bound(core, Bound::Buffer(buffer)); - } - let replaced = set_handle(&mut self.buffers, index, *buffer, offset); - set_entry(&mut self.attribute_strides, index, stride); - self.function_tables.remove(&index); - self.null_tables.remove(&index); - self.bytes.remove(&index); - if let Some(replaced) = replaced { - let_go(core, Bound::Buffer(&replaced)); - } - } - Ok(()) - } - - /// `setBufferOffset:atIndex:`: it clears the index's stride, as the plain buffer setters do, - /// and as the stride form with `MTLAttributeStrideStatic` does in a render stage's table. - /// Measured for the vertex form on an M4: - /// after a stride form, Metal's validation stops the draw for "providing - /// `MTLAttributeStrideStatic` to `attributeStride` when stride at buffer-layout index 0 is - /// dynamic", and Metal without it reads the buffer at stride 0. Every stage's form sets this - /// one table. At an index holding a visible-function table, plain Metal then reads the null - /// table there, of size 0 and every entry null, at any offset, 0 included, until a table or - /// buffer is bound again (an M4 under macOS 27.0.1: the compute form at offsets 0 to 4096, the - /// vertex form at 4 to 24; a second offset keeps it null; Metal's debug layer raises an - /// exception there), and so does the runtime. At an index holding inline bytes, they read as - /// zeros at any offset until the index is bound again, as plain Metal reads them (an M4). - /// At an index with no buffer bound it keeps no offset, in a render stage's table as in a - /// compute one ([`take_buffer_offset`](Self::take_buffer_offset)). Refused: an index past the - /// table, and in a render stage's table an offset past a bound buffer's length. - pub(super) fn set_buffer_offset( - &mut self, - core: &mut EncoderCore, - call: &'static str, - offset: u64, - index: u32, - ) -> Result<(), Error> { - self.move_buffer_offset(core, call, offset, None, index) - } - - /// `setBufferOffset:attributeStride:atIndex:` with the per-bind stride `stride` names - /// ([`per_bind_stride`]). Refused as [`set_buffer_offset`](Self::set_buffer_offset) is. - pub(super) fn set_buffer_offset_with_stride( - &mut self, - core: &mut EncoderCore, - call: &'static str, - offset: u64, - stride: u64, - index: u32, - ) -> Result<(), Error> { - let stride = per_bind_stride(stride); - self.move_buffer_offset(core, call, offset, Some(stride), index) - } - - /// [`set_buffer_offset_with_stride`](Self::set_buffer_offset_with_stride) at the per-bind - /// stride `stride`, none for the plain setter. - fn move_buffer_offset( - &mut self, - core: &mut EncoderCore, - call: &'static str, - offset: u64, - stride: Option, - index: u32, - ) -> Result<(), Error> { - // A buffer bound there keeps being bound, at another offset; inline bytes and a - // visible-function table are another change. - let same = !self.bytes.contains_key(&index) - && !self.function_tables.contains_key(&index) - && self.buffers.contains_key(&index); - self.changed_as(SlotClass::Buffer, index..index.saturating_add(1), same); - check_index(call, index, BUFFER_SLOTS)?; - if let Some(len) = self.bytes.get(&index).map(|bytes| bytes.len) { - // Inline bytes then read as zeros, at any offset, until the index is bound again: - // plain Metal on an M4 read 64 zero bytes after `setBytes` of 64 then an offset of - // 0, 16 or 128, in the compute, vertex and fragment forms (twice each; its debug layer - // asserts "index(0) must have an existing buffer"). - let zeros = [0u8; INLINE_BYTES_LIMIT as usize]; - let padded = u64::from(len).next_multiple_of(16).max(16); - let region = core.command_buffer().state().uploads.upload( - core.device(), - &zeros[..len as usize], - padded, - )?; - self.bytes.insert( - index, - InlineBytes { - region, - len, - attribute_stride: stride, - }, - ); - return Ok(()); - } - if self.function_tables.remove(&index).is_some() { - // The table reads as the null table until the index is bound again. - let words = self.buffers.remove(&index); - self.attribute_strides.remove(&index); - self.null_tables.insert(index); - if let Some((words, _)) = words { - let_go(core, Bound::Buffer(&words)); - } - return Ok(()); - } - self.take_buffer_offset(call, offset, stride, index) - } - - /// `setBufferOffset:attributeStride:atIndex:` at an index that binds a buffer, or binds - /// nothing at all, with `stride` - /// ([`set_buffer_offset_with_stride`](Self::set_buffer_offset_with_stride)'s inline bytes and - /// visible-function tables are its own). It needs no encoder, since nothing here is retained - /// or let go, so one test reads both tables' answer. - /// - /// Nothing bound keeps no offset, in a render stage's table as in a compute one: the index - /// stays unbound, a later `setBuffer:offset:atIndex:` states its own offset, and a draw or a - /// dispatch before that reads zeros, byte for byte as it reads an index never bound. - /// - /// An Apple M3 Max under macOS 27.0.1, three runs with Metal's API validation off in a fresh - /// process and one with it on: `setVertexBufferOffset:64 atIndex:0` with nothing bound at 0 - /// returned, the draw ran its 3 vertices and 4096 fragments, the command buffer completed with - /// no error, and the vertex function read `0x00000000` from `src[0]` — the same word a draw - /// with no setter at all read, where the setter over a bound buffer read that buffer's word at - /// 64, `0x22222222`. Metal's API validation alone objects, and - /// `MTL_DEBUG_LAYER_ERROR_MODE=assert` ends the program there: - /// `index(0) must have an existing buffer.` for the setter, then - /// `Vertex Function(vread): missing Buffer binding at index 0 for src[0].` for the draw, which - /// the never-bound run raises on its own. - /// - /// `metal2vulkan-conformance`'s `probes/buffer_offset_at_an_unbound_index.m` reads the same - /// answer for an offset of 0, at an index that never held a buffer, on the same device and - /// release: three runs a shape, one shape a process, API validation out of the environment. - /// `setVertexBufferOffset:0 atIndex:3` with nothing bound at 3 returned, `endEncoding` and - /// `commit` returned, the command buffer completed with no error, and the stages counted 3 - /// vertices and 256 fragments, having read `0x00000000` from `src[0]` -- the same word the - /// never-bound control read, where a buffer bound at 3 read `0x11111111` at offset 0 and - /// `0x22222222` after `setVertexBufferOffset:64`, so the setter demonstrably moves a bound - /// buffer's offset. Under `MTL_DEBUG_LAYER=1` the layer alone objects, the command buffer - /// still completing: `Set Vertex Buffer Offset Validation` / - /// `index(3) must have an existing buffer.`, then the draw message the never-bound control - /// raises on its own; `MTL_DEBUG_LAYER_ERROR_MODE=assert` ends the program there. - /// - /// Refused: an offset past a bound buffer's length in a render stage's table, which a compute - /// one holds (the module docs). - pub(super) fn take_buffer_offset( - &mut self, - call: &'static str, - offset: u64, - stride: Option, - index: u32, - ) -> Result<(), Error> { - let compute = self.compute; - let Some(bound) = self.buffers.get_mut(&index) else { - return Ok(()); - }; - let length = bound.0.length(); - if offset > length && !compute { - return Err(invalid(call, Problem::OffsetOutOfRange { offset, length })); - } - bound.1 = offset; - set_entry(&mut self.attribute_strides, index, stride); - Ok(()) - } - - /// `setBytes:length:atIndex:` (`stride` `None`) and `setBytes:length:attributeStride:atIndex:` - /// (and every stage's forms) in an encoder of `core`: `bytes` copied now into the command - /// buffer's upload arena, then zeros to a multiple of 16 bytes, in place of anything bound at - /// `index`. A layout of `MTLBufferLayoutStrideDynamic` reads them at the stride form's - /// stride, its low 32 bits, and at 0 after a plain setter (`BoundBuffer::Bytes`). Refused: an - /// index past the table, and more than [`INLINE_BYTES_LIMIT`] bytes. - pub(super) fn set_bytes( - &mut self, - core: &mut EncoderCore, - call: &'static str, - bytes: &[u8], - stride: Option, - index: u32, - ) -> Result<(), Error> { - self.changed(SlotClass::Buffer, index..index.saturating_add(1)); - check_index(call, index, BUFFER_SLOTS)?; - let length = bytes.len() as u64; - if length > INLINE_BYTES_LIMIT { - return Err(invalid( - call, - Problem::InlineBytesLength { - length, - limit: INLINE_BYTES_LIMIT, - }, - )); - } - // The bind layer binds at most the bytes padded to 16, at least 16. - let padded = length.next_multiple_of(16).max(16); - let region = core - .command_buffer() - .state() - .uploads - .upload(core.device(), bytes, padded)?; - let replaced = self.buffers.remove(&index); - self.attribute_strides.remove(&index); - self.function_tables.remove(&index); - self.null_tables.remove(&index); - if let Some((replaced, _)) = replaced { - let_go(core, Bound::Buffer(&replaced)); - } - self.bytes.insert( - index, - InlineBytes { - region, - // At most `INLINE_BYTES_LIMIT`. - len: length as u32, - // Truncation is the measured answer for a buffer's (`attribute_stride`). - attribute_stride: stride.map(|stride| stride as u32), - }, - ); - Ok(()) - } - - /// `setTextures:withRange:` (and `setTexture:atIndex:` as a range of one): `textures[i]` at - /// index `first + i`. A memoryless texture binds as plain Metal binds it (its API validation - /// stops the call: "texture is Memoryless, and cannot be assigned"): a command whose function - /// uses the slot fails its command buffer ([`uses_memoryless`](Self::uses_memoryless)). - /// Refused: an index past the table, a texture of another device; a refusal binds none of - /// them. - pub(super) fn set_textures( - &mut self, - core: &mut EncoderCore, - call: &'static str, - textures: &[Option<&Texture>], - first: u32, - ) -> Result<(), Error> { - // A call that binds each slot as it is bound already changes nothing. - let held = binds_as(textures, first, |_, index, texture| { - self.textures.get(&index) == *texture - }); - if !held { - self.changed(SlotClass::Texture, span(first, textures.len())); - } - check_range(call, first, textures.len(), TEXTURE_SLOTS)?; - for texture in textures.iter().flatten() { - core.check_device(call, texture.generation())?; - } - for (texture, index) in textures.iter().zip(first..) { - match texture { - Some(texture) if texture.is_memoryless() => self.memoryless.insert(index), - _ => self.memoryless.remove(&index), - }; - if let Some(texture) = texture { - self.note_bound(core, Bound::Texture(texture)); - } - if let Some(replaced) = set_bare_handle(&mut self.textures, index, *texture) { - let_go(core, Bound::Texture(&replaced)); - } - } - Ok(()) - } - - /// Whether it binds nothing: no buffer, function table, null table, texture, sampler or bytes. - pub(super) fn binds_nothing(&self) -> bool { - self.buffers.is_empty() - && self.function_tables.is_empty() - && self.null_tables.is_empty() - && self.textures.is_empty() - && self.samplers.is_empty() - && self.bytes.is_empty() - } - - /// Whether a texture slot of `stage` that `interface`'s function statically uses holds a - /// memoryless texture, a texture buffer's too. Plain Metal fails the command buffer of a - /// command that runs such a function (`CommandBufferError::InvalidResource`), whether or not - /// its run reads the slot, and of none whose function leaves the slot unused (an M3 Max under - /// macOS 27.0.1). - pub(super) fn uses_memoryless(&self, interface: &PipelineInterface, stage: Stage) -> bool { - self.memoryless.iter().any(|&index| { - let slot = SlotRef { - stage, - class: SlotClass::Texture, - index, - }; - interface.slots.contains_key(&slot) - }) - } - - /// Bind `samplers` from index `first`, with `clamps` (minimums and maximums) when given. - /// Refused: slices of different lengths, an index past the table, a state of another device; - /// a refusal binds none of them. Metal takes any clamps; a sampler whose clamps are NaN or - /// inverted is refused at the command that samples through it. - pub(super) fn set_samplers( - &mut self, - core: &mut EncoderCore, - call: &'static str, - samplers: &[Option<&SamplerState>], - clamps: Option<(&[f32], &[f32])>, - first: u32, - ) -> Result<(), Error> { - // A call that binds each slot as it is bound already, with the same clamps, changes - // nothing. - let held = binds_as(samplers, first, |at, index, sampler| { - let clamp = match clamps { - Some((min, max)) => match (min.get(at), max.get(at)) { - (Some(&min), Some(&max)) => Some([min, max]), - _ => return false, - }, - None => None, - }; - let bound = self.samplers.get(&index); - bound.map(|(state, held)| (state, *held)) == sampler.map(|state| (state, clamp)) - }); - if !held { - self.changed(SlotClass::Sampler, span(first, samplers.len())); - } - if let Some((min, max)) = clamps { - if min.len() != samplers.len() || max.len() != samplers.len() { - return Err(invalid(call, Problem::LengthMismatch)); - } - } - check_range(call, first, samplers.len(), SAMPLER_SLOTS)?; - for sampler in samplers.iter().flatten() { - core.check_device(call, sampler.generation())?; - } - for (i, (sampler, index)) in samplers.iter().zip(first..).enumerate() { - let clamp = clamps.map(|(min, max)| [min[i], max[i]]); - if let Some(sampler) = sampler { - self.note_bound(core, Bound::Sampler(sampler)); - } - if let Some(replaced) = set_handle(&mut self.samplers, index, *sampler, clamp) { - let_go(core, Bound::Sampler(&replaced)); - } - } - Ok(()) - } - - /// `setVisibleFunctionTables:withBufferRange:` (and `setVisibleFunctionTable:atBufferIndex:` - /// as a range of one): `tables[i]` at buffer index `first + i`, in place of any buffer there; - /// `None` unbinds the index. The table's words are the buffer the slot reads. Refused: an - /// index past the buffer table, a table of another device; a refusal binds none of them. - pub(super) fn set_function_tables( - &mut self, - core: &mut EncoderCore, - call: &'static str, - tables: &[Option<&VisibleFunctionTable>], - first: u32, - ) -> Result<(), Error> { - self.changed(SlotClass::Buffer, span(first, tables.len())); - check_range(call, first, tables.len(), BUFFER_SLOTS)?; - for table in tables.iter().flatten() { - core.check_device(call, table.generation())?; - } - for (table, index) in tables.iter().zip(first..) { - if let Some(table) = table { - self.note_bound(core, Bound::Buffer(table.words())); - } - let replaced = set_entry( - &mut self.buffers, - index, - table.map(|table| (table.words().clone(), 0)), - ); - set_entry(&mut self.function_tables, index, table.cloned()); - self.attribute_strides.remove(&index); - self.null_tables.remove(&index); - self.bytes.remove(&index); - // A table's words bound again at its index are the same object, held by the table. - if let Some((replaced, _)) = replaced.filter(|(replaced, _)| { - !self - .buffers - .get(&index) - .is_some_and(|(bound, _)| bound == replaced) - }) { - let_go(core, Bound::Buffer(&replaced)); - } - } - Ok(()) - } - - /// Refuse a command of `call` whose `stage` function writes a buffer, or reads an - /// intersection function table, where a visible-function table is bound, by `interface`'s - /// slots: plain Metal's answer was not measured (ray tracing's tables are out of scope). A - /// table bound where the function only reads a buffer reads as an unbound buffer, and a buffer - /// bound where it reads a visible-function table as a null table (`stage_table_reading`). A - /// table an offset made null (`null_tables`) where the function reads a buffer is refused too: - /// not measured. - pub(super) fn check_function_tables( - &self, - call: &'static str, - stage: Stage, - interface: &PipelineInterface, - ) -> Result<(), Error> { - // No slot is refused where the table binds no visible-function table and no offset made - // one null: the check below holds for each slot. - if self.function_tables.is_empty() && self.null_tables.is_empty() { - return Ok(()); - } - for (slot, slot_interface) in interface.slots.range(buffer_slots(stage)) { - let SlotInterface::Buffer(buffer) = slot_interface else { - continue; - }; - let index = slot.index; - let table = self.function_tables.contains_key(&index); - let unmeasured = match buffer.kind { - BufferKind::Buffer => buffer.access.write, - BufferKind::VisibleFunctionTable => false, - _ => true, - }; - let nulled = self.null_tables.contains(&index) - && !matches!(buffer.kind, BufferKind::VisibleFunctionTable); - if (unmeasured && table) || nulled { - return Err(invalid( - call, - Problem::FunctionTable(FunctionTableProblem::TableAtBufferIndex { index }), - )); - } - } - Ok(()) - } - - /// Refuse a command of `call` whose `stage` function reads a buffer slot bound past its - /// buffer's length (a compute table holds one, the module docs): Metal's read there is past - /// the buffer, which memory decides. A slot the function does not read runs as Metal's does. - pub(super) fn check_offsets( - &self, - call: &'static str, - stage: Stage, - interface: &PipelineInterface, - ) -> Result<(), Error> { - for slot in interface - .slots - .range(buffer_slots(stage)) - .map(|(slot, _)| slot) - { - if let Some((buffer, offset)) = self.buffers.get(&slot.index) { - let (offset, length) = (*offset, buffer.length()); - if offset > length { - return Err(invalid(call, Problem::OffsetOutOfRange { offset, length })); - } - } - } - Ok(()) - } - - /// The table as the bind layer reads it. A buffer is stated in its space (`Buffer::space`), - /// which the descriptor ranges, vertex buffer offsets and device addresses the bind layer - /// derives count from: a no-copy buffer's bytes may start past its space's start, where its - /// length and offset are as many bytes longer and its addresses as many lower, so every Metal - /// address the layer derives is the buffer's. A heap buffer's space starts at its own byte 0, - /// so the layer states its bytes alone. A buffer bound past its length is left out: a command - /// whose function reads its slot is refused ([`check_offsets`](Self::check_offsets)), and no - /// other reads it. - pub(super) fn stage_table(&self) -> StageTable { - let mut table = StageTable::default(); - for (&index, (buffer, offset)) in &self.buffers { - let stride = self.attribute_strides.get(&index).copied(); - if let Some(bound) = bound_buffer(buffer, *offset, stride) { - table.buffers.insert(index, bound); - } - } - for (&index, bytes) in &self.bytes { - table.buffers.insert(index, bound_bytes(bytes)); - } - for (&index, texture) in &self.textures { - table.textures.insert(index, bound_texture(texture)); - } - for (&index, (sampler, clamps)) in &self.samplers { - table - .samplers - .insert(index, BoundSampler::new(bound_sampler(sampler, *clamps))); - } - table - } - - /// The table as `stage`'s function of `interface` reads it: `stage_table`, but a buffer bound - /// where the function reads a visible-function table is left out, so the slot reads its - /// neutral, a null table of size 0, as plain Metal reads such a buffer where its validation - /// stops the command (an M3 Max and an M4), and so is a table bound where it reads a buffer, - /// whose slot then reads zeros, as plain Metal's read (an M4). Its slots that tell the device's - /// view base alignment apart are those of `views`, the state's, as - /// [`at_bind_views`](Self::at_bind_views) leaves them, its slots that tell offset 0 apart - /// as [`zero_offset_views`](Self::zero_offset_views) leaves them, and its buffers' lengths - /// classed under the device's buffer range limits, the state's `views` hold. - pub(super) fn stage_table_reading( - &self, - stage: Stage, - interface: &PipelineInterface, - views: &AtBindViews, - ) -> StageTable { - let mut table = self.stage_table(); - table.at_bind_views = self.at_bind_views(stage, views); - table.zero_offset_views = self.zero_offset_views(stage, views); - table.buffer_ranges = views.ranges; - let read = |class, index| views.read.reads(stage, class, index); - table - .buffers - .retain(|&index, _| !self.reads_unbound((stage, interface), index)); - table - .textures - .retain(|&index, _| read(SlotClass::Texture, index)); - table - .samplers - .retain(|&index, _| read(SlotClass::Sampler, index)); - table - } - - /// The slots of `stage` whose bind offset class tells the device's view base alignment apart - /// for a command binding this table (`StageTable::at_bind_views`): the state's `views` of it, - /// each that binds a buffer here at an offset the alignment does not divide left out, now and - /// from then on ([`AtBindViews`]). Inline bytes leave none out. - fn at_bind_views(&self, stage: Stage, views: &AtBindViews) -> u64 { - let alignment = u64::from(views.alignment); - self.views_left(views.of(stage), |offset| { - alignment != 0 && !offset.is_multiple_of(alignment) - }) - } - - /// The slots of `stage` whose bind offset class tells offset 0 apart for a command binding - /// this table (`StageTable::zero_offset_views`): the state's `views` of it, each that binds a - /// buffer here at an offset other than 0 left out, now and from then on ([`AtBindViews`]). - /// Inline bytes leave none out. - fn zero_offset_views(&self, stage: Stage, views: &AtBindViews) -> u64 { - self.views_left(views.zero_of(stage), |offset| offset != 0) - } - - /// The slots `kept` holds (none where it is `None`), each that binds a buffer here at an - /// offset `moved` holds of left out, in `kept` too. - fn views_left(&self, kept: Option<&AtomicU64>, moved: impl Fn(u64) -> bool) -> u64 { - let Some(kept) = kept else { - return 0; - }; - let viewed = kept.load(Ordering::Relaxed); - let mut slots = viewed; - let mut left = viewed; - while left != 0 { - let index = left.trailing_zeros(); - left &= left - 1; - let out = !self.bytes.contains_key(&index) - && (self.buffers.get(&index)).is_some_and(|(_, offset)| moved(*offset)); - if out { - slots &= !(1 << index); - } - } - if slots != viewed { - kept.fetch_and(slots, Ordering::Relaxed); - } - slots - } - - /// Whether `stage`'s function of `interface` reads buffer index `index` as unbound - /// ([`stage_table_reading`](Self::stage_table_reading)): a buffer is bound there and the - /// function reads a visible-function table, or a table is bound there and the function reads a - /// buffer it does not write, which plain Metal read as zeros, where its validation stops the - /// command. - fn reads_unbound(&self, (stage, interface): (Stage, &PipelineInterface), index: u32) -> bool { - let slot = SlotRef { - stage, - class: SlotClass::Buffer, - index, - }; - let Some(SlotInterface::Buffer(buffer)) = interface.slots.get(&slot) else { - return false; - }; - let table_bound = self.function_tables.contains_key(&index); - match buffer.kind { - BufferKind::VisibleFunctionTable => !table_bound, - BufferKind::Buffer => table_bound && !buffer.access.write, - _ => false, - } - } - - /// Bring `kept`, the table as a stage's function read it at an earlier draw, to the table as - /// `stage`'s function of `interface` reads it now - /// ([`stage_table_reading`](Self::stage_table_reading)), each sampler as `maps` binds it, in - /// place (`live_bind.rs`): every slot's binding is derived again and stored, so one whose - /// object changed since with no call (a buffer's pages rebound or detached) is read as it is - /// now, and `reshape` is told of each change that may change the shape. - pub(super) fn refresh_reading( - &self, - kept: &mut StageTable, - (stage, interface): (Stage, &PipelineInterface), - (maps, views): (&SamplerMaps, &AtBindViews), - reshape: &mut Reshape, - ) { - let read = (stage, interface); - // The slots that tell the view base alignment and offset 0 apart and the buffer range - // limits first, which the buffers' shapes read. - reshape.field(&mut kept.at_bind_views, self.at_bind_views(stage, views)); - reshape.field( - &mut kept.zero_offset_views, - self.zero_offset_views(stage, views), - ); - reshape.field(&mut kept.buffer_ranges, views.ranges); - let (alignment, ranges) = (views.alignment, views.ranges); - // The slots the state holds alone (`ReadSlots`). - let held = |class, index| views.read.reads(stage, class, index); - kept.buffers.retain(|&index, _| { - let bound = !self.reads_unbound(read, index) - && (self.bytes.contains_key(&index) - || self - .buffers - .get(&index) - .is_some_and(|(buffer, offset)| *offset <= buffer.length())); - if !bound { - reshape.unbound(SlotClass::Buffer); - } - bound - }); - for (&index, (buffer, offset)) in &self.buffers { - if self.bytes.contains_key(&index) || self.reads_unbound(read, index) { - continue; - } - let stride = self.attribute_strides.get(&index).copied(); - if let Some(bound) = bound_buffer(buffer, *offset, stride) { - let a = kept.class_alignment(index, alignment); - reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| { - b.shape(a, ranges) - }); - } - } - for (&index, bytes) in &self.bytes { - if !self.reads_unbound(read, index) { - let a = kept.class_alignment(index, alignment); - reshape.slot( - SlotClass::Buffer, - &mut kept.buffers, - index, - bound_bytes(bytes), - |b| b.shape(a, ranges), - ); - } - } - kept.textures.retain(|&index, _| { - let bound = held(SlotClass::Texture, index) && self.textures.contains_key(&index); - if !bound { - reshape.unbound(SlotClass::Texture); - } - bound - }); - for (&index, texture) in &self.textures { - if !held(SlotClass::Texture, index) { - continue; - } - reshape.slot( - SlotClass::Texture, - &mut kept.textures, - index, - bound_texture(texture), - BoundTexture::shape, - ); - } - kept.samplers.retain(|&index, _| { - let bound = held(SlotClass::Sampler, index) && self.samplers.contains_key(&index); - if !bound { - reshape.unbound(SlotClass::Sampler); - } - bound - }); - for (&index, (sampler, clamps)) in &self.samplers { - if !held(SlotClass::Sampler, index) { - continue; - } - let slot = SlotRef { - stage, - class: SlotClass::Sampler, - index, - }; - let desc = maps.sampler(slot, bound_sampler(sampler, *clamps)); - reshape.slot( - SlotClass::Sampler, - &mut kept.samplers, - index, - BoundSampler::new(desc), - BoundSampler::shape, - ); - } - #[cfg(debug_assertions)] - self.check_reading(kept, read, (maps, views)); - } - - /// The slots the table's calls changed since its stamp was `read`, where it keeps them - /// ([`Changes`]): those [`refresh_changed`](Self::refresh_changed) brings in, each with - /// whether the call changed a buffer slot's offset alone, binding the buffer it bound - /// ([`changed_as`](Self::changed_as)), once for each call. - pub(super) fn changed_since( - &self, - read: Stamp, - ) -> Option + Clone + '_> { - Some( - self.changes - .since(read)? - .map(|changed| (changed.class, changed.index, changed.offset)), - ) - } - - /// [`refresh_reading`](Self::refresh_reading) of `kept`, read last under the stamp `read` - /// through the same interface and maps: only the slots the table's calls changed since, where - /// it keeps them ([`Changes`]) and its slots that tell the view base alignment apart are as - /// `kept` holds them, so every other slot's binding and shape are as read then. Whether it - /// brought them in; else nothing is changed, and the table is to be read whole. What it - /// counts goes to `counts`, the caller's. - pub(super) fn refresh_changed( - &self, - (kept, read): (&mut StageTable, Stamp), - (stage, interface): (Stage, &PipelineInterface), - (maps, views): (&SamplerMaps, &AtBindViews), - reshape: &mut Reshape, - counts: Counting<'_>, - ) -> bool { - let Some(changed) = self.changes.since(read) else { - return false; - }; - // A buffer's shape reads these slots and the buffer range limits: where they changed, - // every buffer is read again. - if self.at_bind_views(stage, views) != kept.at_bind_views - || self.zero_offset_views(stage, views) != kept.zero_offset_views - || views.ranges != kept.buffer_ranges - { - return false; - } - let alignment = views.alignment; - // The buffer slots some call since changed otherwise than by its offset (indices below - // `BUFFER_SLOTS`): each is brought in whole. - let bit = |index: u32| 1u64.checked_shl(index).unwrap_or(0); - let whole = (changed.clone()) - .filter(|c| c.class == SlotClass::Buffer && !c.offset) - .fold(0u64, |whole, c| whole | bit(c.index)); - for Changed { - class, - index, - offset, - .. - } in changed - { - // A slot the state does not hold, which it never took in (`ReadSlots`). - if !views.read.reads(stage, class, index) { - continue; - } - match class { - SlotClass::Buffer if offset && bit(index) != 0 && whole & bit(index) == 0 => { - let read = (stage, interface); - self.refresh_offset((kept, index), read, (alignment, counts), reshape) - } - SlotClass::Buffer => { - self.refresh_buffer((kept, index), (stage, interface), alignment, reshape) - } - SlotClass::Texture => match self.textures.get(&index) { - Some(texture) => reshape.slot( - SlotClass::Texture, - &mut kept.textures, - index, - bound_texture(texture), - BoundTexture::shape, - ), - None => { - if kept.textures.remove(&index).is_some() { - reshape.unbound(SlotClass::Texture); - } - } - }, - SlotClass::Sampler => match self.samplers.get(&index) { - Some((sampler, clamps)) => { - let slot = SlotRef { - stage, - class: SlotClass::Sampler, - index, - }; - let desc = maps.sampler(slot, bound_sampler(sampler, *clamps)); - reshape.slot( - SlotClass::Sampler, - &mut kept.samplers, - index, - BoundSampler::new(desc), - BoundSampler::shape, - ); - } - None => { - if kept.samplers.remove(&index).is_some() { - reshape.unbound(SlotClass::Sampler); - } - } - }, - } - } - #[cfg(debug_assertions)] - self.check_reading(kept, (stage, interface), (maps, views)); - true - } - - /// Buffer slot `index` of `kept` brought in place where every call since `kept` was read moved - /// the offset (or attribute stride) of the buffer it bound alone ([`Changed`]): `kept`'s - /// binding of the same buffer, its offset and stride the table's now. The buffer's space and - /// addresses are as `kept` read them, as no no-copy buffer moved since (the callers' reads - /// stand only while none did: `live_bind::ReadFrom`), so the buffer is not looked at - /// (`WorkCounts::bound_offsets_moved`; checked against [`refresh_buffer`](Self::refresh_buffer)'s - /// binding in builds with debug assertions), and the length the two bindings share is not - /// classed to compare their shapes ([`BoundBuffer::same_shape`]). The function reads the slot - /// bound as `kept` was read: a buffer `kept` binds there was read bound, and no call since - /// bound a visible-function table there, which changes the slot otherwise than by its offset - /// ([`binds_buffer`](Self::binds_buffer)), through the same interface (checked in builds with - /// debug assertions). Else as `refresh_buffer`. - fn refresh_offset( - &self, - (kept, index): (&mut StageTable, u32), - read: (Stage, &PipelineInterface), - (alignment, counts): (u32, Counting<'_>), - reshape: &mut Reshape, - ) { - let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges); - let held = (self.buffers.get(&index)).filter(|(buffer, offset)| *offset <= buffer.length()); - let (Some((buffer, offset)), Some(slot)) = (held, kept.buffers.get_mut(&index)) else { - return self.refresh_buffer((kept, index), read, alignment, reshape); - }; - let BoundBuffer::Buffer { - length, - gpu_address, - device_address, - .. - } = *slot - else { - return self.refresh_buffer((kept, index), read, alignment, reshape); - }; - debug_assert!( - !self.reads_unbound(read, index), - "a buffer slot whose offset alone moved is read unbound" - ); - let stride = self.attribute_strides.get(&index).copied(); - // The space's start before the buffer's byte 0, as `bound_buffer` states it. - let base = length - buffer.length(); - let bound = BoundBuffer::Buffer { - length, - offset: base + offset, - gpu_address, - device_address, - attribute_stride: stride, - }; - #[cfg(debug_assertions)] - assert_eq!( - Some(bound), - bound_buffer(buffer, *offset, stride), - "a buffer slot whose offset alone moved brought in otherwise than read whole" - ); - counts.bound_offset_moved(); - reshape.replace_by(ReshapedBy::BufferOffset, slot, bound, |was, now| { - was.same_shape(now, a, ranges) - }); - } - - /// Buffer slot `index` of `kept` brought in place as [`refresh_reading`](Self::refresh_reading) - /// brings it: unbound where the function reads it unbound or nothing within its length is - /// bound there, else its inline bytes or buffer, its shape of the class `alignment` tells it. - fn refresh_buffer( - &self, - (kept, index): (&mut StageTable, u32), - read: (Stage, &PipelineInterface), - alignment: u32, - reshape: &mut Reshape, - ) { - let bound = !self.reads_unbound(read, index) - && (self.bytes.contains_key(&index) - || (self.buffers.get(&index)) - .is_some_and(|(buffer, offset)| *offset <= buffer.length())); - if !bound { - if kept.buffers.remove(&index).is_some() { - reshape.unbound(SlotClass::Buffer); - } - return; - } - let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges); - if let Some(bytes) = self.bytes.get(&index) { - reshape.slot( - SlotClass::Buffer, - &mut kept.buffers, - index, - bound_bytes(bytes), - |b| b.shape(a, ranges), - ); - } else if let Some((buffer, offset)) = self.buffers.get(&index) { - let stride = self.attribute_strides.get(&index).copied(); - if let Some(bound) = bound_buffer(buffer, *offset, stride) { - reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| { - b.shape(a, ranges) - }); - } - } - } - - /// That `kept`, brought in place by [`refresh_reading`](Self::refresh_reading) (or kept unread - /// while nothing it reads changed: `live_bind::ReadFrom`), is the table `stage`'s function of - /// `interface` reads whole ([`stage_table_reading`](Self::stage_table_reading)), each sampler - /// as `maps` binds it and its slots that tell the view base alignment apart as `views` leaves - /// them (debug builds): the same slots, each bound alike as its value prints (a float's sign - /// told apart, every NaN alike: [`same_as_printed`]), and nothing else in the table. Compared - /// slot by slot, with no table read whole made and nothing printed unless a slot differs, so a - /// draw allocates as many times with debug assertions as without (`runtime_lane::frame_costs` - /// holds its bound in every build). A slot that differs is named in the panic. - #[cfg(debug_assertions)] - pub(super) fn check_reading( - &self, - kept: &StageTable, - read: (Stage, &PipelineInterface), - (maps, views): (&SamplerMaps, &AtBindViews), - ) { - // A call that raced a rebind on another thread may have kept what a reading now no longer - // finds; its hold tells it apart, and its encoder runs only encoded again - // (`rebind::call_may_have_raced`). - if crate::rebind::call_may_have_raced() { - return; - } - let (stage, _) = read; - const DIFFERS: &str = "a stage table brought in place that is not the table read whole"; - // The slots that tell the view base alignment apart, and those that tell offset 0 apart, - // which the buffers' shapes read: each binds no buffer here at an offset the alignment - // does not divide, or other than 0, and they hold every slot the state's views hold now. A - // slot leaves those for good, and another encoder of the state may leave one out after - // this table read them, so `kept` may hold more than a table read whole now would, never - // fewer. - let alignment = u64::from(views.alignment); - let off_alignment = |offset: u64| alignment != 0 && !offset.is_multiple_of(alignment); - let off_zero = |offset: u64| offset != 0; - let sets: [(&str, u64, Option<&AtomicU64>, &dyn Fn(u64) -> bool); 2] = [ - ( - "the view base alignment", - kept.at_bind_views, - views.of(stage), - &off_alignment, - ), - ( - "offset 0", - kept.zero_offset_views, - views.zero_of(stage), - &off_zero, - ), - ]; - for (what, told, slots, moved) in sets { - let now = slots.map_or(0, |slots| slots.load(Ordering::Relaxed)); - assert!( - now & !told == 0, - "{DIFFERS}: {stage:?} tells {what} apart at {told:#x}, the state's views at \ - {now:#x}" - ); - let mut left = told; - while left != 0 { - let index = left.trailing_zeros(); - left &= left - 1; - let out = !self.bytes.contains_key(&index) - && (self.buffers.get(&index)).is_some_and(|(_, offset)| moved(*offset)); - assert!( - !out, - "{DIFFERS}: {stage:?} buffer {index} tells {what} apart at an offset that \ - leaves it out (view base alignment {alignment})" - ); - } - } - assert!( - kept.buffer_ranges == views.ranges, - "{DIFFERS}: {stage:?} classes its buffers' lengths under {:?}, the device's limits \ - are {:?}", - kept.buffer_ranges, - views.ranges - ); - // A buffer slot as `stage_table_reading` reads it: inline bytes where they are bound, - // else the buffer within its length, and nothing where the function reads it unbound. - let held = |class, index| views.read.reads(stage, class, index); - let buffer = |index: u32| { - if self.reads_unbound(read, index) { - return None; - } - match self.bytes.get(&index) { - Some(bytes) => Some(bound_bytes(bytes)), - None => self.buffers.get(&index).and_then(|(buffer, offset)| { - let stride = self.attribute_strides.get(&index).copied(); - bound_buffer(buffer, *offset, stride) - }), - } - }; - // Each slot read whole once: a kept slot against its value, then the slots not kept, - // each of which reads nothing. A read of a no-copy buffer is a look at where it lies - // (`WorkCounts::no_copy_lies_read`), one a slot here as in the refresh. - for (&index, bound) in &kept.buffers { - let whole = buffer(index); - assert!( - whole.as_ref() == Some(bound), - "{DIFFERS}: {stage:?} buffer {index} kept as {bound:?}, read whole as {whole:?}" - ); - } - let not_kept = (self.buffers.keys().chain(self.bytes.keys())) - .filter(|&&index| !kept.buffers.contains_key(&index)); - for &index in not_kept { - let whole = buffer(index); - assert!( - whole.is_none(), - "{DIFFERS}: {stage:?} buffer {index} not kept, read whole as {whole:?}" - ); - } - for (&index, bound) in &kept.textures { - let whole = (self.textures.get(&index)) - .filter(|_| held(SlotClass::Texture, index)) - .map(bound_texture); - assert!( - whole.as_ref() == Some(bound), - "{DIFFERS}: {stage:?} texture {index} kept as {bound:?}, read whole as {whole:?}" - ); - } - let held_textures = self.textures.iter(); - for (&index, texture) in held_textures.filter(|(&index, _)| held(SlotClass::Texture, index)) - { - assert!( - kept.textures.contains_key(&index), - "{DIFFERS}: {stage:?} texture {index} not kept, read whole as {:?}", - bound_texture(texture) - ); - } - let sampler = |index: u32| { - let bound = self - .samplers - .get(&index) - .filter(|_| held(SlotClass::Sampler, index)); - bound.map(|(sampler, clamps)| { - let slot = SlotRef { - stage, - class: SlotClass::Sampler, - index, - }; - let mut whole = BoundSampler::new(bound_sampler(sampler, *clamps)); - whole.desc = maps.sampler(slot, whole.desc); - whole - }) - }; - for (&index, bound) in &kept.samplers { - let whole = sampler(index); - assert!( - whole.is_some_and(|whole| same_as_printed(&whole, bound)), - "{DIFFERS}: {stage:?} sampler {index} kept as {bound:?}, read whole as {whole:?}" - ); - } - for &index in (self.samplers.keys()).filter(|&&index| held(SlotClass::Sampler, index)) { - assert!( - kept.samplers.contains_key(&index), - "{DIFFERS}: {stage:?} sampler {index} not kept, read whole as {:?}", - sampler(index) - ); - } - // A table read whole binds nothing else (`stage_table` starts from the empty table), but - // for the object stage's and the kernel's threadgroup lengths, the encoder's, which the - // draw or the dispatch writes into the kept table after the read - // (`RenderLowering::refresh_bind_state`, `LiveDispatch::refresh`). - let encoders = matches!(stage, Stage::Object | Stage::Kernel); - let lengths = !encoders && !kept.threadgroup_lengths.is_empty(); - assert!( - !lengths && kept.acceleration_structures.is_empty(), - "{DIFFERS}: {stage:?} keeps threadgroup lengths {:?} and acceleration structures {:?}, \ - where the table read whole has none", - kept.threadgroup_lengths, - kept.acceleration_structures - ); - } - - /// Hold everything bound until `core`'s command buffer completes: a command uses it, and - /// the command buffer lists it among its used resources (`used_resources.rs`). Once while it - /// binds the same objects: where `core` retained the table before under its stamp now, - /// nothing is retained again, nor where `core` retained it last and each object a call bound - /// since was one `core` held as it was bound. Else each object `core` holds from an earlier retain - /// (`retained::HeldBy`) is held and its key kept already, each a function of its object; - /// `core` keeps the others' keys and takes them, each by another reference to it - /// (`retained.rs`), but those it or its command buffer held lately, held already: its last - /// first, so they go in the table's order, as one hold of them all went. - pub(super) fn retain(&self, core: &mut EncoderCore) { - let mut retained = lock(&self.retained.0); - let objects = (&self.buffers, &self.textures, &self.samplers); - retain_into(objects, self.stamp, &mut retained, core); - } - - /// [`retain`](Self::retain) by its only holder: the borrow is exclusive, so no other thread - /// can reach the table's record of its last retain, which is read and written without taking - /// its lock (a render encoder's own tables, at each draw). - pub(super) fn retain_exclusive(&mut self, core: &mut EncoderCore) { - let ArgumentTable { - buffers, - textures, - samplers, - retained, - stamp, - .. - } = self; - let retained = retained.0.get_mut().unwrap_or_else(PoisonError::into_inner); - retain_into((buffers, textures, samplers), *stamp, retained, core); - } - - /// Let go of everything the table binds, as its encoder ends or its state is set back: - /// [`let_go`] of each object, the last first, so they go in the table's order. - /// Metal holds what an encoder was handed until its command buffer completes, a binding no - /// command used included (probe `dealloc-probe2`: a buffer or texture bound after the last - /// draw or dispatch). - pub(super) fn let_go_all(&mut self, core: &mut EncoderCore) { - let ArgumentTable { - buffers, - textures, - samplers, - .. - } = self; - // A stage the encoder bound nothing to (most often its object, mesh and tile stages'). - if buffers.is_empty() && textures.is_empty() && samplers.is_empty() { - return; - } - for object in bound_in(buffers, textures, samplers).rev() { - if !object.held_by().is(core.id()) { - core.retain_shared(object.held()); - } - } - } -} - -/// Let go of `object`, which a table bound until a call replaced or unbound it: `core` holds it -/// until its command buffer completes, as Metal holds every object an encoder was handed, a -/// binding replaced before any command used it included (the M3 Max under macOS 27.0.1, probes -/// `dealloc-probe` and `dealloc-probe2`: a no-copy buffer so bound, then released, ran its -/// deallocator only after the command buffer completed). Nothing is retained where `core` holds -/// it already, from a command that used a table that bound it ([`ArgumentTable::retain`]): a -/// bind before each draw retains nothing here. -fn let_go(core: &mut EncoderCore, object: Bound<'_>) { - if !object.held_by().is(core.id()) { - core.retain_shared(object.held()); - } -} - -/// [`ArgumentTable::retain`] of a table that binds `objects` (its buffers, textures and sampler -/// states) under `stamp`, whose record of its last retain is `retained`. Where `core` retained the -/// table last and no call since bound an object `core` did not hold as it bound it -/// (`RetainedBy::unheld`), `core` holds every object the table binds, and keeps its key: nothing -/// is looked at. Else every object bound is. -fn retain_into( - objects: Objects<'_>, - stamp: Stamp, - retained: &mut RetainedBy, - core: &mut EncoderCore, -) { - let (buffers, textures, samplers) = objects; - let id = core.id(); - if retained.core == Some(id) { - // No call changed what it binds since: the same objects, by the stamp. - if retained.stamp == Some(stamp) { - return; - } - // Calls changed it, binding only objects `core` held. - if !retained.unheld { - #[cfg(debug_assertions)] - retained.check_held(objects); - retained.stamp = Some(stamp); - core.counts().argument_table_held_at_bind(); - return; - } - } - let bound = || bound_in(buffers, textures, samplers); - let fresh = |object: &Bound<'_>| !object.held_by().is(id); - core.touch_keys(bound().filter(fresh).filter_map(Bound::key)); - let mut taken = 0; - for object in bound().rev().filter(fresh) { - // One its command buffer holds lately is held already: no other reference is taken. - if !core.holds_lately(object.address()) { - core.retain_shared(object.held()); - } - object.held_by().set(id); - taken += 1; - } - retained.core = Some(id); - retained.stamp = Some(stamp); - retained.unheld = false; - #[cfg(debug_assertions)] - retained.note_retained(objects); - if taken > 0 { - core.counts().argument_table_retained(taken); - } -} - -/// The buffer slots of `stage`, every index, as an interface's slots order them (by stage, class -/// and index). -fn buffer_slots(stage: Stage) -> std::ops::RangeInclusive { - let slot = |index| SlotRef { - stage, - class: SlotClass::Buffer, - index, - }; - slot(0)..=slot(u32::MAX) -} - -/// The `count` indices from `first`, as many as lie below `u32::MAX`. -fn span(first: u32, count: usize) -> Range { - first..first.saturating_add(u32::try_from(count).unwrap_or(u32::MAX)) -} - -/// The objects a table's `buffers`, `textures` and `samplers` bind, in the table's order: its -/// buffers, then its textures, then its sampler states, each by index. -fn bound_in<'a>( - buffers: &'a BTreeMap, - textures: &'a BTreeMap, - samplers: &'a BTreeMap)>, -) -> impl DoubleEndedIterator> { - let buffers = buffers.values().map(|(buffer, _)| Bound::Buffer(buffer)); - let textures = textures.values().map(Bound::Texture); - let samplers = samplers - .values() - .map(|(sampler, _)| Bound::Sampler(sampler)); - buffers.chain(textures).chain(samplers) -} - -#[cfg(test)] -mod tests { - use super::{Changes, SlotClass, Stamp, CHANGES_KEPT}; - - /// A reader under the stamp before any of the calls the log keeps reads the slots those calls - /// changed, in order, with their offset marks; it keeps every call after a stamp whose calls - /// since changed at most `CHANGES_KEPT` slots, and never more than twice as many slots. - #[test] - fn the_changes_log_keeps_the_newest_calls() { - let mut changes = Changes::default(); - // Each call: the stamp before it, and its slots with their offset marks. - let mut calls: Vec<(Stamp, Vec<(u32, bool)>)> = Vec::new(); - let mut stamp = Stamp::fresh(); - for call in 0..200u32 { - let first = call % 29; - let indices = first..first + 1 + call % 3; - let offset = call % 5 == 0; - let after = Stamp::fresh(); - changes.note((stamp, after), SlotClass::Buffer, indices.clone(), offset); - calls.push((stamp, indices.map(|index| (index, offset)).collect())); - stamp = after; - assert!(changes.slots.len() <= 2 * CHANGES_KEPT, "call {call}"); - for (at, (read, _)) in calls.iter().enumerate() { - let want: Vec<(u32, bool)> = calls[at..].iter().flat_map(|c| c.1.clone()).collect(); - match changes.since(*read) { - Some(got) => { - let got: Vec<(u32, bool)> = got.map(|c| (c.index, c.offset)).collect(); - assert_eq!(got, want, "call {call}, read before call {at}"); - } - None => assert!(want.len() > CHANGES_KEPT, "call {call}, read before {at}"), - } - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/astc.rs b/crates/metal2vulkan-runtime/src/astc.rs deleted file mode 100644 index 1ddcc1724..000000000 --- a/crates/metal2vulkan-runtime/src/astc.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! ASTC textures (LDR, sRGB and HDR) on a device without their ASTC block, and Apple's 4x2 and -//! 8x4 footprints (which no Vulkan format holds) on every device: their blocks held as raw bytes -//! in a carrier, which copies move, and their samples read a decoded twin. -//! -//! - **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probes: -//! `conformance/probes/astc_hdr_textures.m` and `astc_passes_writes_footprints.m`): every ASTC -//! format, LDR, sRGB and HDR, of every footprint, the 4x2 and 8x4 ones among them, makes a -//! texture, `Shared`, `Private` and memoryless, of every type but 1D and multisampled (which -//! end the process), of `ShaderWrite` and `RenderTarget` usage too, and views as its other -//! forms of the footprint (another footprint's view ends the process). `getBytes` and a blit out -//! of the texture hand back the blocks a write put there; a copy's region rounds out to whole -//! blocks, the 4x2 and 8x4 footprints' as the others', its last block ending at the level's -//! edge; a new texture's blocks are zeros, which read magenta (an error block; an HDR texture's -//! NaN). Its reads and samples are `bind::AstcDecode`'s. A render pipeline of any ASTC color -//! attachment ends the process. A pass with such a texture as a color attachment completes, -//! whatever its load and store actions, with a draw and without: the texture's blocks stay as -//! they were, and the pass's other attachments load, clear, draw and store as they would. A -//! kernel's `write` or `read_write` of one completes and stores bytes no format defines into its -//! blocks (the same for the same written value). -//! - **The store.** Vulkan copies a compressed image's blocks as bytes. Such a texture holds its -//! blocks in an image of a *carrier*: a compressed format whose blocks are also 16 bytes, over -//! 4 x 4 texels, the first of [`CARRIERS`] the device copies (every Vulkan device has BC or ETC2, -//! which hold one). Each of the texture's blocks, of whatever footprint, lies over 4 x 4 carrier -//! texels, so a region of the texture's blocks is a region of the carrier's ([`image_region`]). -//! A level of the carrier holds at least the blocks the texture's level holds -//! ([`carrier_side`]): the carrier's side is the least whose every level, halved as Vulkan -//! halves it, keeps them (at most about the texture's side in texels, 1 byte a texel), and a -//! copy addresses the first of them. -//! - **What it serves.** Copies between buffers and the texture and between textures (fills -//! included), and the CPU's copies, move its blocks through the carrier, so `getBytes` and a -//! blit out of it hand back the blocks written. Its sampled views present its decoded twin -//! (`texture/decoded_twin.rs`), Metal's decode of the blocks as 8-bit codes (an LDR form's the -//! code nearest Metal's 12-bit value, announced `decoded-texel-precision`; an sRGB form's its own -//! codes, which its slots read through the twin's `R8G8B8A8_SRGB` view, the device's decode, -//! announced `srgb-texel-decode`) or an HDR form's halves, Metal's exactly -//! (`R16G16B16A16_SFLOAT`), decoded after each write as a BC -//! texture's twin is: on the GPU (`bind::astc_decode_module`), or a host write's on the CPU. -//! A view in the texture's other colour space (its `_sRGB` or LDR form) presents a second twin -//! of that form's decode, made at the first such view. Refused: a heap's or a sparse heap's -//! texture (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (an LDR or sRGB -//! texture's HDR form, an HDR texture's LDR or sRGB form, or another footprint; -//! `Feature::TextureView`). -//! - **Passes and shader writes.** No Vulkan format of a block is an attachment's or a storage -//! image's, the device's own ASTC block's included. A pass drops an ASTC color attachment that -//! resolves nothing (`render_pass::layout`): it loads, clears and stores nothing into it, which -//! is Metal's answer, so nothing is announced; a resolve of one is not measured and keeps the -//! format's refusal. A draw or dispatch that binds such a texture at a storage slot binds the -//! slot's neutral instead (`bind::PlanDiagnostic::AstcStorageNeutral`): its writes leave the -//! blocks as they were and its reads answer zero, announced `astc-storage-neutral`, where Metal -//! stores undefined bytes and reads the blocks' decode. A render pipeline of an ASTC color -//! attachment is refused, where Metal ends the process. - -use super::copy_plan::ImageRegion; -use super::image_plan::{sample_count, ImageFacts, ImagePlan}; -use super::texture_descriptor::{effective_usage, TextureLayout}; -use metal2vulkan::bind::AstcDecode; -use metal2vulkan::device::FormatUsage; -use metal2vulkan::metal::format::{image_type, vk_format, FormatEmulation, FormatMapping}; -use metal2vulkan::metal::TextureUsage; -use metal2vulkan::vk::{ - Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, -}; - -/// The compressed formats whose blocks are 16 bytes over 4 x 4 texels, in the order an ASTC -/// texture's blocks take the first the device copies: BC7, BC3, BC2 and BC5 (desktop GPUs), then -/// ETC2's and EAC's (mobile GPUs). -pub(super) const CARRIERS: [Format; 6] = [ - Format::BC7_UNORM_BLOCK, - Format::BC3_UNORM_BLOCK, - Format::BC2_UNORM_BLOCK, - Format::BC5_UNORM_BLOCK, - Format::ETC2_R8G8B8A8_UNORM_BLOCK, - Format::EAC_R11G11_UNORM_BLOCK, -]; - -/// The decode of the ASTC texture whose blocks `plan` holds in a carrier; `None` for any other -/// image. -pub(super) fn decode_of(plan: &ImagePlan) -> Option { - AstcDecode::of(plan.pixel_format).filter(|_| CARRIERS.contains(&plan.format)) -} - -/// The least carrier side, in carrier texels, whose `levels` levels each hold the blocks of -/// `block` texels a side that a texture of `side` texels holds at that level: the carrier's level -/// `l`, `max(1, c >> l)` wide, holds `ceil(max(1, c >> l) / 4)` blocks, at least `n` where -/// `c >= (4 n - 3) << l`. The last level's term is at least `2^(levels - 1)`, so the carrier takes -/// every level. -pub(super) fn carrier_side(side: u32, block: u32, levels: u32) -> u32 { - (0..levels) - .map(|l| { - let blocks = (side >> l).max(1).div_ceil(block); - (4 * blocks - 3) << l - }) - .max() - .unwrap_or(1) -} - -/// The image of an ASTC texture of `layout` with Metal `usage` on a device with `facts` that -/// holds its blocks in a carrier (the module docs): `None` for a texture of another format, or of -/// an ASTC format the device holds (its block, or no decoded twin: its refusal stands), or where -/// no carrier is copied (the device's refusal of the format stands). -pub(super) fn plan_blocks( - layout: &TextureLayout, - usage: TextureUsage, - facts: &ImageFacts<'_>, -) -> Option { - let pf = layout.pixel_format; - let decode = AstcDecode::of(pf)?; - let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), facts.profile).ok()?; - if sampled.emulation != FormatEmulation::Decoded { - return None; - } - let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; - let carrier = CARRIERS - .into_iter() - .find(|&f| facts.optimal(f).contains(copies))?; - // No create flags, never cube compatible: copies alone reach the carrier and no view of it is - // made, so a cube texture's faces are its layers. - let (image_type, _) = image_type(layout.texture_type)?; - let [width, height, depth] = layout.extent; - let [bw, bh] = decode.block_extent(); - Some(ImagePlan { - pixel_format: pf, - flags: ImageCreateFlags::empty(), - image_type, - format: carrier, - extent: [ - carrier_side(width, bw, layout.levels), - carrier_side(height, bh, layout.levels), - depth, - ], - levels: layout.levels, - layers: layout.layers, - samples: sample_count(layout.samples)?, - usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping: FormatMapping::direct(carrier, ImageAspectFlags::COLOR), - // Its decoded twin serves its samples and reads. (`BlockWritesOnly` plans as - // `ShaderWrite` does, which Metal's functions never use on a compressed texture.) - unavailable: effective_usage(usage).intersection( - TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, - ), - }) -} - -/// `region`, in the texels of the ASTC texture whose carrier `plan` plans (a region of whole -/// blocks, or ending at the level's edge), in the carrier's texels: each block 4 x 4 of them, the -/// region's last block's ending at the carrier level's edge where that comes first. `None` for an -/// image of another kind. -pub(super) fn image_region(plan: &ImagePlan, region: ImageRegion) -> Option { - let decode = decode_of(plan)?; - let [bw, bh] = decode.block_extent(); - let [x, y, z] = region.origin; - let [width, height, depth] = region.size; - let level = |axis: usize| (plan.extent[axis] >> region.level.min(31)).max(1); - let span = |at: u32, size: u32, block: u32, axis: usize| { - let first = at / block; - let end = (at + size).div_ceil(block); - (4 * first, (4 * end).min(level(axis)) - 4 * first) - }; - let (x, width) = span(x, width, bw, 0); - let (y, height) = span(y, height, bh, 1); - Some(ImageRegion { - origin: [x, y, z], - size: [width, height, depth], - ..region - }) -} - -/// [`image_region`]'s inverse: `region` of the carrier `plan` plans, in the texture's texels, its -/// last block's ending at the texture level's edge (`extent`, the texture's level 0). `None` for -/// an image of another kind. -pub(super) fn texture_region( - plan: &ImagePlan, - extent: [u32; 3], - region: ImageRegion, -) -> Option { - let decode = decode_of(plan)?; - let [bw, bh] = decode.block_extent(); - let [x, y, z] = region.origin; - let [width, height, depth] = region.size; - let level = |axis: usize| (extent[axis] >> region.level.min(31)).max(1); - let span = |at: u32, size: u32, block: u32, axis: usize| { - let first = at / 4; - let end = (at + size).div_ceil(4); - ( - block * first, - (block * end).min(level(axis)) - block * first, - ) - }; - let (x, width) = span(x, width, bw, 0); - let (y, height) = span(y, height, bh, 1); - Some(ImageRegion { - origin: [x, y, z], - size: [width, height, depth], - ..region - }) -} - -/// A buffer row length or image height of `texels` texture texels in carrier texels: its blocks -/// of `block` texels, 4 carrier texels each (0, tightly packed, stays 0). -pub(super) fn carrier_texels(texels: u32, block: u32) -> u32 { - texels / block * 4 -} diff --git a/crates/metal2vulkan-runtime/src/attachment_stand_in.rs b/crates/metal2vulkan-runtime/src/attachment_stand_in.rs deleted file mode 100644 index ad2d2e5da..000000000 --- a/crates/metal2vulkan-runtime/src/attachment_stand_in.rs +++ /dev/null @@ -1,881 +0,0 @@ -//! Images that stand in for a pass's attachment for the whole pass (step 6's fourth part). -//! -//! - **A memoryless texture's backing.** A pass split into instances (`render.rs`) keeps its -//! attachments' contents in memory between them, and a draw that fetches an attachment in the -//! pixel interlock reads and writes it as a storage image (`framebuffer_fetch.rs`): neither is -//! open to a transient image, which may have no memory and has no `STORAGE` usage. Such a pass -//! renders the memoryless attachment into an image of its own. Nothing is copied: Metal neither -//! loads nor stores a memoryless texture, so its contents do not survive the pass either way. A -//! color's backing is one its queue keeps for its passes of the attachment's shape -//! ([`pooled_backing`]). -//! - **A fetched texture's scratch.** One rule for both forms of framebuffer fetch: a color -//! texture whose image lacks the usage its fetch form needs renders, in a pass that fetches -//! it, into a scratch image that has it, as its attachment in every instance too, but those -//! that render the texture itself before it arrives (recorded inline, or pinned by a draw that -//! reads it through a snapshot: `render/inline_first.rs`, `render/snapshot.rs`), after which it -//! is copied in. In the -//! pixel interlock that usage is `STORAGE`, which a texture the runtime makes holds only where -//! it costs the image nothing (`framebuffer_fetch::Answers`); through input attachments it is -//! input attachment usage, which every color render target the runtime makes holds and a -//! caller's image may not (`texture/wrapped.rs`). A caller's image without `STORAGE` takes the -//! scratch in the interlock too. Through sample planes (`sample_planes.rs`) the usage is the -//! planes' copies': sampled, with a view in the unsigned-integer format of its texel size, -//! which a multisampled color render target the runtime makes takes only where it costs the -//! image nothing, like `STORAGE`. The texture's level and layer are copied into the scratch -//! image before the pass where Metal loads it (`Load`; a `Clear` or `DontCare` load is the -//! scratch image's own first operation) and back after the pass where Metal stores its texels -//! (`Store`, `StoreAndMultisampleResolve`). A pass that stores `DontCare` copies nothing back: -//! the texture keeps its texels, as Apple's GPU keeps them. In the pixel interlock an 8-bit sRGB -//! texture renders, in a pass that fetches it, into a scratch made mutable to the -//! unsigned-integer view a fetching draw reads and writes it through -//! (`framebuffer_fetch::storage_view_format`), to which a texture's image is not made; so does -//! a BGRA-order texture viewed in its RGBA-order twin (ANV) whose image does not take that view. -//! -//! - **A depth/stencil texture not made for the pass's custom sample positions**. Vulkan rasterizes -//! a depth/stencil attachment at custom positions only where its image was made with -//! `VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT` (`sample_positions.rs`), which -//! every image the runtime makes for them has and a caller's image may lack. Such a pass renders -//! the texture's level and layer into a stand-in made with the flag: each aspect copied in before -//! the pass where Metal loads it (or keeps it, an aspect of the texture's format no attachment -//! names), and back after it where Metal stores or keeps it, over the reach of the pass's clear -//! past the render area where an aspect is cleared and stored (`clear_reach.rs`), the copy in -//! covering the same extent. The copies keep the format and the sample count, so they are plain -//! image copies of the aspects. A caller's image is wrapped without the flag -//! (`texture/wrapped.rs`). An image of a format the device does not copy both ways (no transfer -//! usage) stays refused (`NotImplemented(SamplePositionsAtBegin)`). -//! - **A depth/stencil texture without `RenderTarget` usage**, whose image lacks depth/stencil -//! attachment usage, which plain Metal renders as a render target: one -//! texture renders through a stand-in copied as the custom positions' one is, each aspect in -//! where Metal loads or keeps it and back where it stores or keeps it, so a `DontCare` store -//! leaves the texture as it was, as Metal leaves it. Separate depth and stencil textures render -//! through their combined scratch image (`depth_stencil_scratch.rs`), which copies them alike. A -//! texture whose format the device does not copy both ways, and a memoryless one, stay refused -//! (`NotImplemented(Render)`). -//! - **A texture over a buffer a pass does not store** (`DontCare`, or `MultisampleResolve`), whose -//! image is linear over the buffer's bytes: Metal leaves the buffer's bytes, so the pass renders -//! it through the image its texture keeps, copied into where the pass loads it (`Load`), and -//! never back (`kept_bytes.rs`). -//! - **A multisampled color attachment whose samples a resolve after the pass reads**, which the -//! pass stores nothing of (`MultisampleResolve`): Metal leaves the texture's samples as they -//! were, and the crate-owned resolve (`color_resolve.rs`) reads the samples the pass stores, so -//! the pass renders it through the image its texture keeps, copied into where the pass loads it -//! (`Load`), and never back (`resolve::keep_samples`). -//! - **A pass's hidden depth and stencil**. In a pass without a depth/stencil attachment, plain -//! Metal tests a draw whose state uses depth or the stencil against a hidden depth of `float`, -//! 1.0 at the pass's start, and a stencil of 0, kept per sample through the pass. Such a draw -//! gives the pass an image of its own for them (`hidden`): the depth/stencil attachment of the -//! draw's instance and every later one, cleared before the pass and never stored. -//! -//! A stand-in has the attachment's format, size and samples; its copies keep the sample count -//! both ways. A multisampled one (a memoryless attachment's backing, or a fetched texture's -//! scratch) takes the usage the device's fetch form needs of a multisampled attachment: through -//! the attachment's own multisampled storage image -//! (`framebuffer_fetch::through_multisampled_storage`), `STORAGE` where the device stores its -//! format at its sample count; through sample planes (`framebuffer_fetch::through_planes`), sampled -//! with the copies' view where the device has its formats, and no `STORAGE`, which such a device -//! has at one sample only; through input attachments, input attachment usage. A multisampled color -//! one takes input attachment usage too where the exact color resolve may read it -//! (`color_resolve.rs`). Only a pass of fetching draws needs a stand-in, and a pass of draws that -//! test the stencil in the shader (`shadow_stencil.rs`) one for its memoryless stencil. A -//! single-sampled one takes the usages either fetch form needs where the device has them. A color -//! one takes transfer writes (it may be cleared before the pass, `render.rs`), and a depth/stencil -//! one transfer reads and writes (the shadow's copies). A stand-in is the pass's own: made with the -//! draw that needs it and held by the command buffer until it completes, like the depth/stencil -//! scratch (`depth_stencil_scratch.rs`) and the resolve scratch (`resolve.rs`); but a memoryless -//! color's backing, which its queue keeps ([`pooled_backing`]). The copies cover -//! the render area and every layer of a layered pass, between barriers from everything before and -//! to everything after. - -use super::blit::TRANSFER; -use super::color_resolve; -use super::command_buffer::{CommandBuffer, Finished}; -use super::device::lock; -use super::encoder::EncoderCore; -use super::error::{internal, Error, RuntimeGap}; -use super::framebuffer_fetch; -use super::image_plan::{sample_count, ImagePlan}; -use super::nan_clear; -use super::render_pass::{PassLayout, Target}; -use super::resource::ResourceKey; -use super::sample_positions; -use super::texture::Texture; -use super::texture_descriptor::TextureDescriptor; -use super::tracker::{Access, Barrier, Use}; -use super::values::ResourceOptions; -use super::Device; -use crate::device::functions::Vk; -use ash::vk; -use metal2vulkan::device::FormatUsage; -use metal2vulkan::metal::format::{aspects, FormatMapping}; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; -use metal2vulkan::vk::{ - FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags, -}; - -/// What one attachment's stand-in stands in for: the attachment's own level and layer, which the -/// pass's target names no longer. -#[derive(Clone, Debug)] -pub(super) struct StandIn { - pub(super) own: Target, - /// Why the attachment renders through it, which names its notice - /// (`Device::degrade_instances`) and whether it is copied to and from the attachment. - pub(super) cause: Cause, - /// The box its copies cover, `[x0, y0, x1, y1]` (half-open) inside the render area, where a - /// pass loads the attachment and its draws write inside the box alone - /// (`linear_attachment::choose`): `None` copies over the render area (or the reach of the - /// pass's clear, `clear_reach.rs`). - pub(super) area: Option<[u32; 4]>, -} - -/// Why an attachment renders through a stand-in for the pass. Each cause names its own notice: -/// before, every stand-in copied to and from its attachment was announced as a fetched texture's -/// scratch (`fetch-through-scratch`), so a texture over a buffer that rendered through the image -/// its texture keeps was announced as read "through the pixel interlock" where no draw read it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) enum Cause { - /// A memoryless texture's backing, or the backing a texture keeps for a pass that clears it - /// and resolves it alone into another format: nothing is copied. - Backing, - /// A fetched texture's scratch, with the usage the fetch's form needs - /// (`fetch-through-scratch`): `by`, the draw that first fetched it in the pass, in words (its - /// fragment function, and the blend state of the attachment's color). - Fetch { by: String }, - /// A texture without render target usage (`undeclared-usage-shadow`). - Unattachable, - /// A depth/stencil texture's, made for the pass's custom sample positions - /// (`positions-through-scratch`). - Positions, - /// A bound linear attachment's image its texture keeps (`linear_attachment.rs`, which - /// announces it under its own kinds). - Linear, - /// The image a texture over a buffer keeps for a pass that does not store it, so that the - /// buffer keeps its bytes (`kept_bytes.rs`, which announces it, `dont-care-stand-in`): copied - /// into where the pass loads it, and never back. - KeptBytes, - /// A multisampled color attachment the pass stores nothing of (`MultisampleResolve`) whose - /// samples a resolve the runtime draws after the pass reads, which the pass must store for it - /// (`resolve::keep_samples`): it renders through the image its texture keeps for the queue, - /// copied into where the pass loads it and never back, so the texture keeps the samples it - /// held before the pass, as Metal's does. - KeptSamples, - /// The image a pass renders a texture's own image through where it stores it `DontCare` - /// under `DontCareColorPolicy::Kept` and the device's own `DONT_CARE` would not leave the - /// texture's earlier texels, which Metal leaves (`kept_bytes.rs`): one its queue keeps for its passes of the attachment's shape - /// ([`pooled_backing`]), copied into where the pass loads it and never back. No notice names - /// it: the texture keeps its texels, Metal's answer. - KeptTexels, -} - -impl StandIn { - /// Whether it is copied to and from its attachment: all but a backing. - pub(super) fn copies(&self) -> bool { - self.cause != Cause::Backing - } -} - -/// A memoryless attachment's backing that its texture keeps ([`kept_backing`]): for the passes -/// of one queue, of one subresource of the texture (its level, layers, format, samples and -/// extent as the pass's target names them). -pub(super) struct KeptBacking { - queue: u64, - /// It was made for copies to and from its attachment (`stand_in`'s `copies`). - copies: bool, - level: u32, - layer: u32, - layers: u32, - format: metal2vulkan::vk::Format, - samples: u32, - extent: [u32; 2], - backing: Target, -} - -impl KeptBacking { - /// Whether it backs `own` for the passes of `queue`, copied to and from it where `copies`. - fn backs(&self, own: &Target, queue: u64, copies: bool) -> bool { - self.queue == queue - && (self.copies || !copies) - && self.level == own.level - && self.layer == own.layer - && self.layers == own.layers - && self.format == own.format - && self.samples == own.samples - && self.extent == own.extent - } -} - -/// The backing of `own`, a memoryless attachment of a pass of `queue` whose image is lazily -/// allocated (`render/executions.rs`'s `Rendered::back_memoryless`), or an attachment a pass -/// without a draw call clears and resolves into another pixel format (`render.rs`), whose samples -/// Metal leaves as they were: the stand-in the attachment's texture keeps for that queue and -/// subresource, made now and kept where it keeps none. Metal neither loads nor stores a memoryless -/// texture, and the other kind of pass clears the backing first, so no pass reads what another left -/// in it, and the passes of one queue that back it are ordered by their uses of it, as by their -/// uses of the texture: one backing serves them all, and the memory a texture's backings take does -/// not grow with its passes. It goes with the texture (each command buffer that rendered it holds -/// it until it completes). Or, `copies`, a linear attachment a pass renders through a stand-in -/// (`linear_attachment.rs`), copied in where the pass loads it and back where it stores it, as a -/// texture without render target usage is: the copies, and the clears of the tiles a `DontCare` -/// load reaches (`clear_reach.rs`), give each pass all it reads of the backing first, so one serves -/// them too. So does a texture over a buffer that a pass does not store (`kept_bytes.rs`), copied -/// in where the pass loads it and never back: nothing reads what such a pass leaves there. -pub(super) fn kept_backing( - maker: &CommandBuffer, - own: &Target, - queue: u64, - copies: bool, -) -> Result { - let device = maker.device(); - let kept = own.texture.kept_backings(); - if let Some(found) = lock(kept).iter().find(|k| k.backs(own, queue, copies)) { - // Held as one `maker` made: its first batch moves it to `GENERAL` where the command - // buffer that made it has not yet submitted a batch. - maker.hold_own_texture(found.backing.texture.clone()); - return Ok(found.backing.clone()); - } - // Made with no lock held; one another thread kept meanwhile is taken, and this one dropped. - let made = stand_in(maker, own, copies)?; - let mut kept = lock(kept); - if let Some(found) = kept.iter().find(|k| k.backs(own, queue, copies)) { - maker.hold_own_texture(found.backing.texture.clone()); - return Ok(found.backing.clone()); - } - device.shared().counts.kept_backing_made(); - kept.push(KeptBacking { - queue, - copies, - level: own.level, - layer: own.layer, - layers: own.layers, - format: own.format, - samples: own.samples, - extent: own.extent, - backing: made.clone(), - }); - Ok(made) -} - -/// The most color backings a queue keeps ([`pooled_backing`]), and the most bytes of -/// device memory their images take together: past either, the backing passes took least recently -/// goes (but the one just made, which alone may take more). The count is above the shapes a -/// frame cycles through: a compositor's frames on the consumer's macOS guest render 11 to 14 -/// extents of one memoryless `RGBA16Float` attachment (1920x1080 down to 192x64), about 40 MB of -/// backings together, and a pool that keeps fewer than a frame takes, in the same order each -/// frame, finds none of them kept. -const MOST_POOLED_BACKINGS: usize = 32; -const MOST_POOLED_BYTES: u64 = 256 << 20; - -/// A color attachment's backing its queue keeps ([`pooled_backing`]): the shape it backs (the -/// attachment's pixel format, the format its pass renders it in, its samples, layers and extent), -/// whether it was made for copies from its attachment (`stand_in`'s `copies`), the bytes its image -/// takes, and the pool's count of takes at its last take. -struct PooledBacking { - pixel_format: PixelFormat, - format: metal2vulkan::vk::Format, - samples: u32, - layers: u32, - extent: [u32; 2], - copies: bool, - bytes: u64, - taken: u64, - /// Whether the command buffer that took it last completed. - taker: Finished, - backing: Target, -} - -impl PooledBacking { - /// Whether it backs an attachment of `own`'s shape, copied from it where `copies`. - fn backs(&self, own: &Target, copies: bool) -> bool { - (self.copies || !copies) - && self.pixel_format == own.texture.pixel_format() - && self.format == own.format - && self.samples == own.samples - && self.layers == own.layers - && self.extent == own.extent - } -} - -/// The color backings one command queue keeps for its passes ([`pooled_backing`]): at -/// most [`MOST_POOLED_BACKINGS`], over at most [`MOST_POOLED_BYTES`] but for the one just made. -/// They go with the queue; each command buffer that rendered into one holds it until it -/// completes. -#[derive(Default)] -pub(crate) struct BackingPool { - kept: Vec, - /// The takes so far, the clock each backing's `taken` reads. - takes: u64, -} - -impl BackingPool { - /// Drop the backings taken least recently while the pool keeps more than its bounds, but - /// the last one, just made. - fn bound(&mut self) { - loop { - let bytes: u64 = self.kept.iter().map(|k| k.bytes).sum(); - let over = self.kept.len() > MOST_POOLED_BACKINGS || bytes > MOST_POOLED_BYTES; - let last = self.kept.len().saturating_sub(1); - let oldest = self.kept[..last] - .iter() - .enumerate() - .min_by_key(|(_, k)| k.taken) - .map(|(at, _)| at); - match oldest { - Some(at) if over => drop(self.kept.remove(at)), - _ => return, - } - } - } -} - -/// The backing of `own`, a memoryless color attachment of a pass of `maker`'s queue that renders -/// into an image of its own (a framebuffer fetch through the pixel interlock reads it, or the pass -/// splits), or a color a pass stores `DontCare` that renders through one so that its texture -/// keeps its texels (`kept_bytes.rs`), made for the copy into it where `copies` (the pass loads -/// it): one the queue keeps of `own`'s pixel format, format, samples, layers and extent (made for -/// copies where `copies`) that is none of `taken` (the images the pass renders its other -/// attachments into), else one made now and kept ([`BackingPool`]). Metal neither loads nor stores -/// a memoryless texture (`render_pass::check_memoryless`), and a pass gives a memoryless color's -/// every texel a draw can read a value before its draws: its `Clear` load, or the zero its -/// `DontCare` load clears to in a pass that draws (`clear_reach::dont_care_loads`), before the pass -/// where the pass leaves it out of its subpass (`render.rs`); a `DontCare` store's backing is -/// given the same before its pass, or the texture's texels over the render area where the pass -/// loads it, and nothing reads what its pass leaves in it. A fresh image's texels were undefined -/// there as well. So no pass reads what another left in the backing, and the passes of one queue -/// that take it are ordered by their uses of it, as by any texture's: one image serves every pass -/// of the shape, across command buffers and frames (`WorkCounts::pooled_backings_made`, -/// `pooled_backings_taken`, `pooled_backings_taken_in_flight`). -pub(super) fn pooled_backing( - maker: &CommandBuffer, - own: &Target, - taken: &[Texture], - copies: bool, -) -> Result { - let queue = maker.queue_place(); - let free = |k: &PooledBacking| k.backs(own, copies) && !taken.contains(&k.backing.texture); - { - let mut pool = lock(queue.memoryless_backings()); - pool.takes += 1; - let takes = pool.takes; - if let Some(found) = pool.kept.iter_mut().find(|k| free(k)) { - found.taken = takes; - let backing = found.backing.clone(); - // Taken while another command buffer that took it has not completed: the hazard - // tracker orders their uses of it (counted). - let in_flight = !found.taker.of(maker) && !found.taker.completed(); - found.taker = maker.finished(); - drop(pool); - maker - .device() - .shared() - .counts - .pooled_backing_taken(in_flight); - // Held as one `maker` made: its first batch moves it to `GENERAL` where the command - // buffer that made it has not yet submitted a batch. - maker.hold_own_texture(backing.texture.clone()); - return Ok(backing); - } - } - // Made with no lock held; the pool may keep one another thread made meanwhile beside it. - let made = stand_in(maker, own, copies)?; - maker.device().shared().counts.pooled_backing_made(); - let mut pool = lock(queue.memoryless_backings()); - pool.takes += 1; - let takes = pool.takes; - pool.kept.push(PooledBacking { - pixel_format: own.texture.pixel_format(), - format: own.format, - samples: own.samples, - layers: own.layers, - extent: own.extent, - copies, - bytes: made.texture.placed_bytes().unwrap_or(0), - taken: takes, - taker: maker.finished(), - backing: made.clone(), - }); - pool.bound(); - Ok(made) -} - -/// The stand-in for `target`, an attachment the pass renders whole into an image of its own -/// (the module docs): `copies` where the pass copies between them (a fetched texture's scratch). -/// A single-sampled color stand-in takes `STORAGE` usage where the device stores the format of a -/// fetching draw's storage view of it (`framebuffer_fetch::storage_view_format`), which every -/// fetched format's has (the compile layer's interlock form needs it), and is made mutable to -/// that view where it is another format (an 8-bit sRGB format's, a BGRA-order one's RGBA-order -/// twin on ANV); a multisampled one where the -/// device's fetch reads the attachment's own multisampled image and stores that view at its -/// sample count. Either takes input attachment usage where the device's -/// framebuffer fetch reads input attachments, and a multisampled one the sample planes' copies' -/// usage where the fetch reads planes and the device has it. A sample count or usage the -/// device's image limits for the format lack is refused where the image is made (`Unsupported`, -/// `image_plan::check_image_limits`). A stand-in has the pass's layers (a layered pass's -/// attachment: added). -pub(super) fn stand_in( - maker: &CommandBuffer, - target: &Target, - copies: bool, -) -> Result { - stand_in_as(maker, target, copies, target.format) -} - -/// The stand-in for `target` in `format`, a format of the attachment's texel size: a color the -/// pass's draws render in another encoding where the attachment's image takes no view of it -/// (`render.rs`'s `Reformat`), copied between them, as [`stand_in`]'s scratch is otherwise. -/// Refused (`NotImplemented(Render)`) where the device copies no image of `format`. -pub(super) fn stand_in_as( - maker: &CommandBuffer, - target: &Target, - copies: bool, - format: metal2vulkan::vk::Format, -) -> Result { - let device = maker.device(); - // A 3D attachment's planes, and a 1D attachment, are not copied to or from a stand-in - // (`render_pass::not_2d`). - if super::render_pass::not_2d(target) { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - let profile = device.compile_device().profile(); - let layers = target.layers; - let multisampled = target.samples != 1; - let pixel_format = target.texture.pixel_format(); - let aspects = aspects(pixel_format).unwrap_or(ImageAspectFlags::COLOR); - let color = aspects == ImageAspectFlags::COLOR; - let mut usage = if color { - ImageUsageFlags::COLOR_ATTACHMENT - } else { - ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT - }; - let own_image = !multisampled - || (framebuffer_fetch::through_multisampled_storage(profile, target.samples) - && framebuffer_fetch::stores_samples(profile, target.samples)); - // A fetching draw's storage view is in `view`: an 8-bit sRGB format's, the unsigned-integer - // format of its texel size, a BGRA-order one's, its RGBA-order twin on a device that accesses - // its format without one in neither direction (`framebuffer_fetch::storage_view_format`). - let view = framebuffer_fetch::storage_view_format(profile, format); - let stored = color && own_image && profile.supports_format(view, FormatUsage::StorageImage); - if stored { - usage |= ImageUsageFlags::STORAGE; - } - // The crate-owned color resolve reads a multisampled extended-range color attachment as an - // input attachment (`color_resolve.rs`), as does the resolve into the attachment's format's - // sRGB twin, whose encoding no device's average writes (`color_resolve::twin_resolved`). - let resolved = multisampled - && (color_resolve::shader_rules(pixel_format, target.format, target.samples).is_some() - || color_resolve::twin_resolved(pixel_format, target.samples)); - if color && (framebuffer_fetch::through_inputs(profile) || resolved) { - usage |= ImageUsageFlags::INPUT_ATTACHMENT; - } - // A color stand-in may be cleared before the pass (`render.rs`), and a scratch is copied. A - // depth/stencil one may be copied to and from a shader-side stencil's shadow - // (`shadow_stencil.rs`), whichever draw first made the pass need the stand-in. - let transfer = device.shared().textures.facts(profile).optimal(format); - if color && transfer.contains(FormatFeatureFlags2::TRANSFER_DST) { - usage |= ImageUsageFlags::TRANSFER_DST; - } - let both = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; - if !color && transfer.contains(both) { - usage |= ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST; - } - // A multisampled depth/stencil stand-in (a memoryless attachment's backing) is read sampled - // where the device's depth/stencil-colour image copies cannot move its samples: a - // shader-side depth test's split fills the depth's stand-in from it, as the copies of a - // separate texture read one (`depth_stencil_scratch::sampled_candidate`). It is the - // runtime's own image, so no answer the caller sees moves. - let feature = metal2vulkan::error::Feature::FramebufferFetch; - if !color - && multisampled - && super::depth_stencil_scratch::colour_copies_refused(device, feature, aspects).is_some() - && profile.supports_format(format, FormatUsage::SampledImage) - { - usage |= ImageUsageFlags::SAMPLED; - } - if copies { - if !transfer.contains(both) { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - usage |= ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST; - } - let [width, height] = target.extent; - let descriptor = TextureDescriptor { - texture_type: match (multisampled, layers > 1) { - (false, false) => TextureType::Type2D, - (false, true) => TextureType::Type2DArray, - (true, false) => TextureType::Type2DMultisample, - (true, true) => TextureType::Type2DMultisampleArray, - }, - pixel_format, - width: width.into(), - height: height.into(), - array_length: layers.into(), - sample_count: target.samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - ..TextureDescriptor::default() - }; - let samples = sample_count(target.samples) - .ok_or_else(|| internal("an attachment of a sample count Vulkan lacks"))?; - let mut plan = ImagePlan { - pixel_format, - // A depth/stencil stand-in is the pass's attachment, made for its custom sample positions - // where the device takes them. - flags: sample_positions::compatible_depth(profile, format, samples), - image_type: ImageType::TYPE_2D, - format, - extent: [width, height, 1], - levels: 1, - layers, - samples, - usage, - view_formats: Vec::new(), - mapping: FormatMapping::direct(format, aspects), - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - // A stand-in a fetching draw views in another format than its own (an sRGB format's, an - // RGBA-order twin's) is mutable to that view, with extended usage: its `STORAGE` is the - // view's, which its own format need not have (a view in its own format serves the draws that - // do not fetch it, each view's usage restricted to what it serves, `binding_view.rs`). - if stored && view != format { - plan.flags |= ImageCreateFlags::MUTABLE_FORMAT | ImageCreateFlags::EXTENDED_USAGE; - plan.view_formats = vec![format, view]; - } - // A stand-in in another format than the attachment's, copied to or from it, is mutable to - // the attachment's format: a device that copies between formats through a view of one image - // in the other's format copies it so (MoltenVK, whose copy of a multisampled image between - // formats where neither takes such a view goes through a buffer, which holds no samples). - if copies && format != target.format { - plan.flags |= ImageCreateFlags::MUTABLE_FORMAT; - if plan.view_formats.is_empty() { - plan.view_formats.push(format); - } - plan.view_formats.push(target.format); - } - // A multisampled color stand-in is read and written by the sample planes' copies where the - // fetch reads planes and the device views it so (`sample_planes.rs` refuses the planes - // otherwise). - if color && framebuffer_fetch::through_planes(profile, target.samples) { - if let Some(planes) = framebuffer_fetch::with_planes_copies(&plan, profile) { - plan = planes; - } - } - // A multisampled 8-bit color stand-in that a resolve into its format's twin reads through - // the other member of the pair (`color_resolve::twin_read_view`: an sRGB one through the - // UNORM twin its rules are in, a UNORM one through the sRGB twin the device decodes) is - // mutable to that view. - let raw = color_resolve::twin_read_view(profile, pixel_format, plan.format, target.samples) - .filter(|_| resolved); - if let Some(raw) = raw { - plan.flags |= ImageCreateFlags::MUTABLE_FORMAT; - if plan.view_formats.is_empty() { - plan.view_formats.push(plan.format); - } - if !plan.view_formats.contains(&raw) { - plan.view_formats.push(raw); - } - } - let texture = Device::new_planned_texture(maker, &descriptor, plan)?; - Ok(Target { - texture, - level: 0, - layer: 0, - layers, - format, - samples: target.samples, - extent: target.extent, - }) -} - -/// The image of `layout`'s hidden depth and stencil (`render_pass::DepthStencilTarget::hidden`): -/// a private `Depth32Float_Stencil8` texture of the pass's samples and layers over its render -/// area, as a depth/stencil attachment and cleared before the pass by a transfer. Metal's hidden -/// depth is a `float` (a Metal probe: a write at 0.5 compared unequal to 0.5 plus 2^-24), and its -/// stencil 8 bits; the one image holds both, so a pass whose draws use the one and then the other -/// keeps one attachment. Refused `Unsupported` where the device lacks the format as a depth/stencil -/// attachment at the pass's samples, and `NotImplemented(HiddenDepthStencil)` where it does not -/// clear it by a transfer. -pub(super) fn hidden(maker: &CommandBuffer, layout: &PassLayout) -> Result { - let device = maker.device(); - let profile = device.compile_device().profile(); - let pixel_format = PixelFormat::Depth32FloatStencil8; - let usages = [FormatUsage::DepthStencilAttachment].into(); - let mapping = metal2vulkan::metal::format::vk_format(pixel_format, &usages, profile).map_err( - |error| match error { - metal2vulkan::error::Error::Unsupported(unsupported) => Error::Unsupported(unsupported), - other => Error::Compile(other), - }, - )?; - let format = mapping.format; - let transfer = device.shared().textures.facts(profile).optimal(format); - if !transfer.contains(FormatFeatureFlags2::TRANSFER_DST) { - return Err(Error::NotImplemented(RuntimeGap::HiddenDepthStencil)); - } - let samples = sample_count(layout.samples) - .ok_or_else(|| internal("a pass of a sample count Vulkan lacks"))?; - let (layers, multisampled) = (layout.layers, layout.samples != 1); - let [width, height] = layout.extent; - let descriptor = TextureDescriptor { - texture_type: match (multisampled, layers > 1) { - (false, false) => TextureType::Type2D, - (false, true) => TextureType::Type2DArray, - (true, false) => TextureType::Type2DMultisample, - (true, true) => TextureType::Type2DMultisampleArray, - }, - pixel_format, - width: width.into(), - height: height.into(), - array_length: layers.into(), - sample_count: layout.samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - ..TextureDescriptor::default() - }; - let plan = ImagePlan { - pixel_format, - // The pass's attachment, made for its custom sample positions where the device takes - // them, as a depth/stencil stand-in is. - flags: sample_positions::compatible_depth(profile, format, samples), - image_type: ImageType::TYPE_2D, - format, - extent: [width, height, 1], - levels: 1, - layers, - samples, - usage: ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping, - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - let texture = Device::new_planned_texture(maker, &descriptor, plan)?; - Ok(Target { - texture, - level: 0, - layer: 0, - layers, - format, - samples: layout.samples, - extent: layout.extent, - }) -} - -/// The clear of a pass's hidden depth and stencil (`hidden`) to Metal's 1.0 and 0, every layer of -/// its image, recorded before the pass: each of the pass's instances loads it. -pub(super) struct HiddenClear { - image: vk::Image, - layers: u32, - uses: [Use; 1], -} - -impl HiddenClear { - /// The clear of `target`, the hidden depth and stencil's image. - pub(super) fn plan(target: &Target) -> Result { - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - Ok(HiddenClear { - image: target.texture.raw_image()?, - layers: target.layers, - uses: [target - .texture - .image_use(0..1, 0..target.layers, write, true)?], - }) - } - - /// Record the clear in `core`'s command buffer, between barriers from everything before and - /// to everything after. - pub(super) fn record(self, core: &mut EncoderCore) { - let HiddenClear { - image, - layers, - uses, - } = self; - core.barrier(Barrier::everything()); - core.command(TRANSFER, &uses, |device, raw| { - let value = vk::ClearDepthStencilValue { - depth: 1.0, - stencil: 0, - }; - let range = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: layers, - }; - // SAFETY: the encoder's command buffer is recording outside a render pass; the image - // is live until it completes (the encoder retains the pass's targets), rests in - // `GENERAL`, takes transfer writes (`hidden`), and has one level and `layers` layers - // of both aspects. - unsafe { - device.cmd_clear_depth_stencil_image( - raw, - image, - vk::ImageLayout::GENERAL, - &value, - &[range], - ); - } - }); - core.barrier(Barrier::everything()); - } -} - -/// Refuse (`NotImplemented(Render)`) a fetched texture's scratch, or a stand-in for a texture -/// without render target usage, where `target`'s image does not copy both ways: its format has no -/// transfer usage on the device. -pub(super) fn check_copies(target: &Target) -> Result<(), Error> { - let both = ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST; - if target.texture.image_plan()?.usage.contains(both) { - Ok(()) - } else { - Err(Error::NotImplemented(RuntimeGap::Render)) - } -} - -/// One direction of a pass's copies between its attachments and their stand-ins, over the render -/// area: into the stand-ins before the pass, or back after it. -pub(super) struct StandInCopies { - /// `(from, to, region)` of each copy. - copies: Vec<(vk::Image, vk::Image, vk::ImageCopy)>, - uses: Vec>, -} - -impl StandInCopies { - /// The copies between `pairs` (each color attachment's stand-in, then its own target, then - /// the extent from the origin copied: the render area, or the reach of the pass's clear past - /// it, `clear_reach.rs`): into the stand-ins (`into_stand_in`) or back; `None` when there is - /// none. - pub(super) fn plan( - pairs: &[(&Target, &Target, [u32; 2])], - into_stand_in: bool, - ) -> Result, Error> { - let color: Vec<_> = pairs - .iter() - .map(|&(stand_in, own, [width, height])| { - let area = [0, 0, width, height]; - (stand_in, own, area, vk::ImageAspectFlags::COLOR) - }) - .collect(); - StandInCopies::plan_aspects(&color, into_stand_in) - } - - /// [`StandInCopies::plan`] of `pairs` that each name the aspects copied: a color attachment's - /// color, or a depth/stencil attachment's depth, stencil or both (one pair per stand-in and - /// direction, so each image has one use). Each pair names the box copied, `[x0, y0, x1, y1]` - /// (half-open): from the origin over the render area or a clear's reach, or a stand-in's - /// `area`. - pub(super) fn plan_aspects( - pairs: &[(&Target, &Target, [u32; 4], vk::ImageAspectFlags)], - into_stand_in: bool, - ) -> Result, Error> { - if pairs.is_empty() { - return Ok(None); - } - let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - let mut copies = Vec::with_capacity(pairs.len()); - let mut uses = Vec::with_capacity(2 * pairs.len()); - for &(stand_in, own, [x0, y0, x1, y1], aspect_mask) in pairs { - let (from, to) = if into_stand_in { - (own, stand_in) - } else { - (stand_in, own) - }; - // Every layer of the pass's, each image's from its first. - let count = stand_in.layers; - let layers = |target: &Target| vk::ImageSubresourceLayers { - aspect_mask, - mip_level: target.level, - base_array_layer: target.layer, - layer_count: count, - }; - // Inside the render area, whose extent fits an `i32`. - let offset = vk::Offset3D { - x: x0 as i32, - y: y0 as i32, - z: 0, - }; - let region = vk::ImageCopy { - src_subresource: layers(from), - src_offset: offset, - dst_subresource: layers(to), - dst_offset: offset, - extent: vk::Extent3D { - width: x1.saturating_sub(x0), - height: y1.saturating_sub(y0), - depth: 1, - }, - }; - if aspect_mask == vk::ImageAspectFlags::COLOR { - let direction = if into_stand_in { "into" } else { "back from" }; - nan_clear::degrade_converting_copy( - to.texture.generation(), - to.format, - to.samples, - || { - format!( - "the copy of a multisampled {:?} attachment {direction} the image it \ - renders through", - own.texture.pixel_format() - ) - }, - ); - } - let at = |target: &Target| target.level..target.level + 1; - let on = |target: &Target| target.layer..target.layer + count; - uses.push(from.texture.image_use(at(from), on(from), read, false)?); - uses.push(to.texture.image_use(at(to), on(to), write, true)?); - copies.push((from.texture.raw_image()?, to.texture.raw_image()?, region)); - } - Ok(Some(StandInCopies { copies, uses })) - } - - /// The copies' uses. - pub(super) fn uses(&self) -> &[Use] { - &self.uses - } - - /// Record the copies into `command_buffer`, between barriers from everything before and to - /// everything after, as [`StandInCopies::record`] records them in an encoder's command - /// buffer: a step of a pass recorded later (`render/executions.rs`), whose uses the pass - /// took. - /// - /// # Safety - /// - /// `command_buffer` is recording outside a render pass, and only the caller records it; the - /// images are live until it completes and rest in `GENERAL`. - pub(super) unsafe fn record_in(&self, raw: &Vk, command_buffer: vk::CommandBuffer) { - let general = vk::ImageLayout::GENERAL; - // SAFETY: the caller's contract; every image has the transfer usage its copy needs - // (checked when the stand-in was made), and each region lies in both images. - unsafe { - Barrier::everything().record(raw, command_buffer); - for (from, to, region) in &self.copies { - raw.cmd_copy_image(command_buffer, *from, general, *to, general, &[*region]); - } - Barrier::everything().record(raw, command_buffer); - } - } - - /// Record the copies in `core`'s command buffer, between barriers from everything before and - /// to everything after. - pub(super) fn record(self, core: &mut EncoderCore) { - let StandInCopies { copies, uses } = self; - core.barrier(Barrier::everything()); - core.command(TRANSFER, &uses, |device, raw| { - let general = vk::ImageLayout::GENERAL; - // SAFETY: the encoder's command buffer is recording outside a render pass; the images - // are live until it completes (the encoder retains the textures); every image rests in - // `GENERAL`, has the transfer usage its copy needs (checked when the stand-in was - // made), and each region lies in both images (the render area). - unsafe { - for (from, to, region) in &copies { - device.cmd_copy_image(raw, *from, general, *to, general, &[*region]); - } - } - }); - core.barrier(Barrier::everything()); - } -} diff --git a/crates/metal2vulkan-runtime/src/attachmentless.rs b/crates/metal2vulkan-runtime/src/attachmentless.rs deleted file mode 100644 index 29569ad8c..000000000 --- a/crates/metal2vulkan-runtime/src/attachmentless.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! The render passes a device keeps for its passes without attachments: one per sample count and -//! view mask (a multiview instance's), made when an encoder of such a pass first needs it and -//! destroyed with the device. Every encoder of a pass without attachments records its draws against -//! its sample count's kept pass, makes its pipelines against it, and begins it. -//! -//! Such a pass rasterizes at its `defaultRasterSampleCount` (a Metal probe on an M4), the sample -//! count the encoder checks each pipeline's `rasterSampleCount` against (`render.rs`). A Vulkan -//! subpass without attachments rasterizes at its pipelines' `rasterizationSamples`, but MoltenVK -//! takes the count from its subpass's default sample count, which only creating a pipeline against -//! that very `VkRenderPass` sets (`MVKGraphicsPipeline` in MoltenVK 1.4.1's `MVKPipeline.mm`; a -//! `MVKRenderSubpass` begins with 1). A pass made per encoder, after the pipelines it draws were -//! made against another, compatible one, rasterized one sample: at 2x each pixel held sample 0 -//! alone. The kept pass is the one its pipelines were made against, on every -//! device, so it is the one its subpass's default was set on; the others rasterize the pipelines' -//! count either way. A pass of no attachments has no load or store operation, so the one pass -//! serves both as the compatible pass and as the pass begun. -//! -//! A pass whose subpass leaves out attachments the pass still describes (the sample planes', with -//! their anchor, `render_target.rs`) is no pass without attachments here: only a shape with no -//! attachment at all is kept, so the kept passes number at most the sample counts times the -//! view masks drawn. - -use super::color_list::ColorList; -use super::device::lock; -use super::error::Error; -use super::render_target::{self, PassShape, RenderPassObject}; -use super::Device; -use crate::release; -use ash::vk; -use std::collections::BTreeMap; - -/// The device's kept passes, by sample count and view mask. -#[derive(Default)] -pub(super) struct KeptPasses { - passes: BTreeMap<(u32, u32), vk::RenderPass>, -} - -impl KeptPasses { - /// Destroy every kept pass; the device is idle, and is destroyed next. - pub(super) fn destroy(&self, raw: &ash::Device) { - for &pass in self.passes.values() { - // SAFETY: the device is idle, so no pending command uses the pass, and a pipeline - // made with it does not keep it. - unsafe { release::object(raw, pass) }; - } - } -} - -/// Whether a device keeps the pass of `shape`: a shape with no attachment at all. -pub(super) fn keeps(shape: &PassShape) -> bool { - *shape == self::shape(shape.samples, shape.view_mask) -} - -/// The shape of a pass without attachments of `samples` samples whose subpasses have -/// `view_mask`. -pub(super) fn shape(samples: u32, view_mask: u32) -> PassShape { - PassShape { - colors: ColorList::new(), - depth_stencil: None, - samples, - color_resolves: ColorList::new(), - depth_stencil_resolve: None, - fetch_inputs: false, - no_inputs: ColorList::new(), - storage: ColorList::new(), - view_mask, - locations: ColorList::new(), - } -} - -/// The pass `device` keeps for `shape` (made now if this is its first use), where `shape` has no -/// attachment at all; `None` for any other shape. -pub(super) fn kept(device: &Device, shape: &PassShape) -> Result, Error> { - if !keeps(shape) { - return Ok(None); - } - let mut kept = lock(&device.shared().attachmentless); - let key = (shape.samples, shape.view_mask); - let raw = match kept.passes.get(&key) { - Some(&raw) => raw, - None => { - let raw = render_target::made_compatible_pass(device, shape)?.into_kept(); - kept.passes.insert(key, raw); - raw - } - }; - Ok(Some(RenderPassObject::kept(device, raw))) -} diff --git a/crates/metal2vulkan-runtime/src/attributes.rs b/crates/metal2vulkan-runtime/src/attributes.rs deleted file mode 100644 index 177ff6917..000000000 --- a/crates/metal2vulkan-runtime/src/attributes.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! What a Metal resource carries beside its memory: its label and its purgeable state -//! (`MTLResource`'s `label` and `setPurgeableState:`). -//! -//! The purgeable state follows Metal's answers as measured (an Apple M3 Max and an M4): a query -//! answers the state, any other request answers the state before it and becomes the state. The -//! runtime never purges a volatile resource: Metal may discard its contents and need not, so this -//! is one of Metal's allowed behaviours, not a measured match. Metal keeps the state only of a -//! resource with an allocation of its own, one whose `allocatedSize` is at least -//! `PURGEABLE_ALLOCATION`: it answers `NonVolatile` to every request on a smaller one and keeps its -//! contents. Emptying a `Shared` or `Managed` buffer discards its bytes (they read zero after); a -//! `Private` buffer and every texture keep theirs, as Metal's did. Each buffer embeds one -//! [`ResourceAttributes`] and forwards its methods (`Buffer` here); a texture keeps its label and -//! state itself (`texture/attributes.rs`). - -use super::buffer::Buffer; -use super::device::lock; -use super::error::{invalid, Error, Problem}; -use super::values::StorageMode; -use std::sync::Mutex; - -/// The least `allocatedSize` of a Metal resource whose purgeable state Metal keeps. A smaller -/// one shares an allocation with others: Metal answers `NonVolatile` to every request on it and -/// keeps its contents (buffers of 1, 4, 8 KiB and 16383 bytes, and textures of up to 12672 bytes, -/// did so on an Apple M3 Max and an M4; buffers of 16384 bytes and more, and textures of 16384 -/// bytes and more, kept their state). -pub(super) const PURGEABLE_ALLOCATION: u64 = 16 * 1024; - -/// The bytes Metal allocates for a texture of this shape, as the runtime models Apple's layout: for -/// each level, its extent in blocks of `block_extent` texels, each axis rounded up to a power of -/// two (the depth only for a `volume`, a 3D texture), times `block_bytes`; summed over the -/// `levels`, times the `layers` (a cube's faces each) and the `samples`. Compared with -/// `PURGEABLE_ALLOCATION`, it answers as Metal did for each of the 45 texture shapes the probes -/// measured (sizes, formats, mipmaps, arrays, cubes, 3D, 1D, multisample, compressed); Apple's own -/// sizes (`allocatedSize`) differ from it, by compression metadata and alignment. -pub(super) fn texture_allocation( - block_extent: [u32; 2], - block_bytes: u64, - extent: [u32; 3], - volume: bool, - levels: u32, - layers: u32, - samples: u32, -) -> u64 { - let blocks = |texels: u32, block: u32| u64::from(texels.div_ceil(block.max(1)).max(1)); - let level_bytes: u64 = (0..levels.max(1)) - .map(|level| { - let [w, h, d] = extent.map(|axis| (axis >> level.min(31)).max(1)); - let depth = if volume { u64::from(d) } else { 1 }; - blocks(w, block_extent[0]).next_power_of_two() - * blocks(h, block_extent[1]).next_power_of_two() - * depth.next_power_of_two() - * block_bytes - }) - .sum(); - level_bytes * u64::from(layers.max(1)) * u64::from(samples.max(1)) -} - -/// `MTLPurgeableState`, with Metal's raw values. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum PurgeableState { - /// `MTLPurgeableStateKeepCurrent`: a query; the state does not change. - KeepCurrent, - /// `MTLPurgeableStateNonVolatile`: the contents may not be discarded. - NonVolatile, - /// `MTLPurgeableStateVolatile`: the contents may be discarded. - Volatile, - /// `MTLPurgeableStateEmpty`: the contents are discarded. - Empty, -} - -impl PurgeableState { - /// Metal's raw value. - pub fn raw(self) -> u64 { - match self { - PurgeableState::KeepCurrent => 1, - PurgeableState::NonVolatile => 2, - PurgeableState::Volatile => 3, - PurgeableState::Empty => 4, - } - } - - /// The state of Metal's raw value `raw`. - pub fn from_raw(raw: u64) -> Result { - Ok(match raw { - 1 => PurgeableState::KeepCurrent, - 2 => PurgeableState::NonVolatile, - 3 => PurgeableState::Volatile, - 4 => PurgeableState::Empty, - raw => { - return Err(invalid( - "from_raw", - Problem::UndefinedValue { - ty: "MTLPurgeableState", - raw, - }, - )) - } - }) - } -} - -/// The purgeable state of a resource that is never purged: `set` of `requested` while the state -/// is `current`, as `(the answer, the new state)`. A query answers the state and keeps it; any -/// other request answers the state before it and becomes the state. -/// -/// One request does not take: `Volatile` asked of an object that is already `Empty` leaves it -/// `Empty`. Metal's own rule, measured over every ordered pair of the three states on an -/// `MTLHeap` and on an `MTLTexture` on an Apple M3 Max under Metal 27.0.1 — `Empty` then -/// `Volatile` reads back `Empty`, where `Empty` then `NonVolatile` reads back `NonVolatile` and -/// `Volatile` then `Empty` reads back `Empty`. Contents that have been discarded cannot be made -/// discardable again; only `NonVolatile` brings the object back. The answer is still the state -/// before the call, so a caller sees the refusal in the read-back and not in the return. -pub(super) fn set_purgeable( - current: PurgeableState, - requested: PurgeableState, -) -> (PurgeableState, PurgeableState) { - match (current, requested) { - (current, PurgeableState::KeepCurrent) => (current, current), - (PurgeableState::Empty, PurgeableState::Volatile) => { - (PurgeableState::Empty, PurgeableState::Empty) - } - (current, requested) => (current, requested), - } -} - -/// A resource's label and purgeable state. A new resource has no label and is non-volatile. -#[derive(Debug)] -pub(super) struct ResourceAttributes { - label: Mutex>, - purgeable: Mutex, -} - -impl ResourceAttributes { - /// No label, non-volatile. - pub(super) fn new() -> ResourceAttributes { - ResourceAttributes { - label: Mutex::new(None), - purgeable: Mutex::new(PurgeableState::NonVolatile), - } - } - - /// The label and purgeable state now, for the resource carried to its device's next - /// generation (`device/carry.rs`). - pub(super) fn carried(&self) -> ResourceAttributes { - ResourceAttributes { - label: Mutex::new(lock(&self.label).clone()), - purgeable: Mutex::new(*lock(&self.purgeable)), - } - } - - /// `setLabel:`. - pub(super) fn set_label(&self, label: &str) { - *lock(&self.label) = Some(label.to_owned()); - } - - /// `label`. - pub(super) fn label(&self) -> Option { - lock(&self.label).clone() - } - - /// `setPurgeableState:`: the state before the call, or the state now for `KeepCurrent`. - pub(super) fn set_purgeable_state(&self, state: PurgeableState) -> PurgeableState { - let mut current = lock(&self.purgeable); - let (answer, next) = set_purgeable(*current, state); - *current = next; - answer - } -} - -impl Buffer { - /// `setLabel:`. - pub fn set_label(&self, label: &str) { - self.attributes().set_label(label); - } - - /// `label`: `None` until one is set. - pub fn label(&self) -> Option { - self.attributes().label() - } - - /// `setPurgeableState:`: the state before the call, or the state now for `KeepCurrent`, as - /// measured on Metal. The runtime never purges a volatile buffer (Metal may, and need not). - /// `Empty` discards a `Shared` or `Managed` buffer's bytes, which then read zero, and keeps a - /// `Private` buffer's, as Metal's did. - /// - /// A buffer shorter than `PURGEABLE_ALLOCATION` (16 KiB), whose `allocatedSize` is its - /// length, shares an allocation on Metal: it answers `NonVolatile` to every call and keeps its - /// bytes, as Metal's does. So does a no-copy buffer, as Metal's does, and a buffer over the - /// caller's `VkBuffer`, whose memory the runtime never empties. A texture over the buffer - /// changes none of its answers. Emptying a buffer the GPU is using leaves what either sees - /// undefined, as in Metal. - /// - /// A buffer placed in a heap, whose state is its heap's, answers `NonVolatile` to every call - /// and changes nothing: `Empty` keeps its bytes and its heap's state stays as it was, as plain - /// Metal answers where its validation stops every call there, a query included. Fails only when - /// zeroing a `Managed` buffer's bytes on a device without unified memory fails. - pub fn set_purgeable_state(&self, state: PurgeableState) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - if self.heap().is_some() { - return Ok(PurgeableState::NonVolatile); - } - // A two-copy buffer (`managed_copy.rs`) is a no-copy buffer: its device copy is the - // runtime's own memory, but its bytes are the caller's pages. - let no_copy = self.caller_memory().is_some() || self.caller_copy().is_some(); - if no_copy || self.length() < PURGEABLE_ALLOCATION { - return Ok(PurgeableState::NonVolatile); - } - let answer = self.attributes().set_purgeable_state(state); - if state == PurgeableState::Empty && self.storage_mode() != StorageMode::Private { - self.clear()?; - } - Ok(answer) - } -} diff --git a/crates/metal2vulkan-runtime/src/batch_order.rs b/crates/metal2vulkan-runtime/src/batch_order.rs deleted file mode 100644 index 0ffd75507..000000000 --- a/crates/metal2vulkan-runtime/src/batch_order.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! How a batch of command buffers on one `VkQueue` begins after the batches before it there -//! (`DevicePolicy::batch_order`). -//! -//! Metal orders a command buffer after the earlier ones of its queue only where its work depends -//! on theirs: an independent fill committed behind a running fill of other bytes started while -//! the first ran, on an M3 Max under macOS 27.0.1 (probe `gpustart`). The exact form copies that: -//! a batch begins with a barrier for each access that depends on an earlier batch's of its -//! `VkQueue` (`tracker.rs`), its first encoder's GPU start written at the top of the pipe, and -//! ends with [`Barrier::to_host`], which orders only the host's reads and writes after it. -//! -//! Some drivers run no two kernel submissions of one queue side by side anyway. Measured with a -//! probe outside the runtime: batches A and B, each a command buffer of a start timestamp, one of -//! work and one of an end barrier and an end timestamp, signalling the queue's timeline, B's work -//! independent of A's; work of one workgroup of 64 invocations running a dependent multiply-add -//! chain of about 3 to 10 ms (so two run side by side in about one's time), or fills of other -//! buffers; with no end barrier, `to_host`'s or [`Barrier::to_all`]'s; in two `vkQueueSubmit` -//! calls or one; with and without the timestamps, the queries reset on the host or the GPU, and -//! with only the last submission signalling. On each of these, every shape ran B after A, in -//! about the sum of their times (20.0 ms for two 10 ms batches on the RTX 5080 Laptop GPU, 18.5 -//! on the RX 7900 XTX, 20.0 on the UHD 770), where the same two dispatches recorded in one command -//! buffer ran side by side (10.0, 9.3 and 10.0 ms): -//! - ANV (Mesa 26.2.4) on the UHD 770 of RPL-S; -//! - RADV (Mesa 26.0.8) on the Radeon 780M and the RX 7900 XTX; -//! - NVIDIA's driver (615.71.09) on the RTX 5080 Laptop GPU. -//! -//! On those drivers ([`ends_order`]) the default form orders batches by their ends: every batch -//! ends with [`Barrier::to_all`], every write before every access of every later command of its -//! `VkQueue`, so the tracker plans no barrier after an access of an earlier batch there -//! ([`Tracker::by_ends`](crate::tracker::Tracker)). A batch's start timestamp, written at the top -//! of the pipe as on every driver (`gpu_time.rs`), is then written once everything before it in -//! submission order completed, which is when such a driver starts it: the earlier batch's -//! [`Barrier::to_all`] holds it, as "the second synchronization scope includes all commands that -//! occur later in submission order" (`vkCmdPipelineBarrier`), its destination stages all commands. -//! A start written at the bottom of the pipe there read late on RADV (Mesa 26.2.6) on an RX 7900 -//! XTX and a Radeon 780M: in a traced compute benchmark's pass, a population of command buffers -//! read their start in the last tenth of their own kernel job, spans of 1 us on jobs of 4.5 to -//! 36.5 ms. A batch no longer needs a command buffer of barriers -//! for a dependency on the batch before it (on the UHD 770, with the consumer's frames over 520 -//! host imports, 67.0 command buffers submitted a frame against 129.3 to 129.7), and runs as the -//! driver ran it before. Elsewhere, and under `BatchOrderPolicy::Exact`, the exact form. - -use crate::tracker::Barrier; -use metal2vulkan::device::{BatchOrderPolicy, DevicePolicy}; -use metal2vulkan::vk::DriverId; - -/// Whether a device of `policy` and `driver` orders its batches by their ends (the module docs): -/// its policy asks for it and its driver is measured to run no two kernel submissions of one -/// queue side by side. -pub(crate) fn by_ends(policy: &DevicePolicy, driver: Option) -> bool { - policy.batch_order == BatchOrderPolicy::Ends && ends_order(driver) -} - -/// Whether the driver is measured to run the kernel submissions of one queue one after another, -/// with or without a barrier between them (the module docs). -fn ends_order(driver: Option) -> bool { - matches!( - driver, - Some(DriverId::INTEL_OPEN_SOURCE_MESA | DriverId::MESA_RADV | DriverId::NVIDIA_PROPRIETARY) - ) -} - -/// The barrier that ends each batch of a device that orders its batches `by_ends` or not. -pub(crate) fn end(by_ends: bool) -> Barrier { - match by_ends { - true => Barrier::to_all(), - false => Barrier::to_host(), - } -} diff --git a/crates/metal2vulkan-runtime/src/begin_ahead.rs b/crates/metal2vulkan-runtime/src/begin_ahead.rs deleted file mode 100644 index b2ee8927f..000000000 --- a/crates/metal2vulkan-runtime/src/begin_ahead.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! The device's begin-ahead thread: a settled spare command pool's primaries are begun here, for -//! the encoders of the command buffer that takes the pool next (`spares.rs`), off the thread that -//! completed the command buffer that gave the pool back. -//! -//! - **What is posted.** The first command pool of a command buffer that completed and ended -//! every command buffer its pools handed out, once its completed handlers ran, before its gate -//! opens (`command_buffer/mod.rs`, `command_buffer/gate.rs`): the completing thread posts the -//! pool and goes on, so neither the command buffer's waiters nor its queue's next transitions -//! wait for a begin, and a waiter's return comes after the post. On ANV a begin was 8 to 20 us -//! (`spares.rs`), which the completing thread spent before, one a command buffer, while the -//! queue's context was held, and only where no thread waited for the command buffer. -//! - **What it begins.** As many of the pool's primaries as encoders of the command buffer that -//! gave it back opened their own in it, one at least and `spares::AHEAD` at most, one at a time, -//! the pool out of the spares only while it begins one (`spares.rs`'s -//! `BeginTargets::begin_ahead`). A command buffer that takes the pool before the thread came -//! to it, or between two begins, takes it as it is: its encoders past those begun begin their -//! own, counted (`WorkCounts::encoder_primaries_begun_ahead_missed`). -//! - **Bounded.** One thread a device, started by its first post. At most [`QUEUE`] pools wait; -//! a pool posted while it waits waits once, and one that finds the queue full, the device's -//! teardown begun, or no thread, is begun by none: its command buffer's encoders begin their -//! own. Stopped and joined by the device's teardown, before the spares are released -//! ([`BeginAhead::stop`]). -//! - **Holds nothing of the device**: the spares' command pools, the device's functions, its -//! loader word and its counts (`spares.rs`'s `BeginTargets`), as the free thread does -//! (`free_thread.rs`). No release of the device's runs on it. -//! - **A section of the exit guard** for each begin (`exit_guard.rs`); once the process exits, -//! nothing more is begun and the thread ends. -//! - **At the user-interactive class** ([`exit_guard::spawn_user_interactive`]), as the handler -//! threads that began the primaries before: its begins race the next command buffer's take. - -use crate::device::lock; -use crate::exit_guard; -use crate::spares::BeginTargets; -use ash::vk; -use std::collections::VecDeque; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; -use std::thread::JoinHandle; - -/// The most pools that wait for the thread (the module docs). -pub(crate) const QUEUE: usize = 64; - -/// A device's begin-ahead thread (the module docs). -#[derive(Default)] -pub(crate) struct BeginAhead { - shared: Arc, - thread: Mutex>>, -} - -/// What the thread and the posters share. -#[derive(Default)] -struct Shared { - state: Mutex, - /// A pool was posted, or the thread is asked to stop. - work: Condvar, - /// The crate's device tests' hold of each posted pool's begins as they start - /// (`tests/begin_ahead.rs`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - held: crate::freed_memory::held::Held, - /// A posted pool's begins ended, for the crate's device tests ([`BeginAhead::settle`]). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - idle: Condvar, -} - -#[derive(Default)] -struct State { - queue: VecDeque, - /// The thread was started, or a start failed. - started: bool, - stopping: bool, - /// The thread makes a posted pool's begins, for the crate's device tests. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - running: bool, -} - -impl BeginAhead { - /// Post the spare command pool `raw`, given back settled, for its primaries to be begun ahead - /// on the thread, started unless it runs, with what `targets` gives; nothing where the pool - /// waits already, the queue is full, the device's teardown began or the host starts no - /// thread (the module docs). - pub(crate) fn post(&self, raw: vk::CommandPool, targets: impl FnOnce() -> BeginTargets) { - let mut state = lock(&self.shared.state); - if state.stopping || state.queue.len() >= QUEUE || state.queue.contains(&raw) { - return; - } - if !state.started { - state.started = true; - let (shared, targets) = (Arc::clone(&self.shared), targets()); - let builder = std::thread::Builder::new().name("metal2vulkan-begin-ahead".into()); - match exit_guard::spawn_user_interactive(builder, move || run(&shared, &targets)) { - Ok(handle) => *lock(&self.thread) = Some(handle), - Err(_) => return, - } - } - if lock(&self.thread).is_none() { - return; - } - state.queue.push_back(raw); - drop(state); - self.shared.work.notify_one(); - } - - /// The device's teardown, before it releases the spares: no pool is posted from here on, the - /// thread ends once its begins in progress are done, joined; those still waiting are begun by - /// none. - pub(crate) fn stop(&self) { - lock(&self.shared.state).stopping = true; - self.shared.work.notify_all(); - let handle = lock(&self.thread).take(); - if let Some(handle) = handle { - let _ = handle.join(); - } - } - - /// The tests' hold of each posted pool's begins as they start. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn held(&self) -> &crate::freed_memory::held::Held { - &self.shared.held - } - - /// Wait until no posted pool waits and the thread makes no begins, for the crate's device - /// tests: what the spares hold, and the counts of the begins, are then final for the command - /// buffers whose waits returned, as a waiter's return comes after its command buffer's post. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn settle(&self) { - let mut state = lock(&self.shared.state); - while state.running || !state.queue.is_empty() && lock(&self.thread).is_some() { - state = (self.shared.idle.wait(state)).unwrap_or_else(PoisonError::into_inner); - } - } -} - -/// The thread's loop: each posted pool's begins in turn, until stopped or the process exits. -fn run(shared: &Shared, targets: &BeginTargets) { - loop { - let raw = { - let mut state = lock(&shared.state); - loop { - if state.stopping { - return; - } - if let Some(raw) = state.queue.pop_front() { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - state.running = true; - } - break raw; - } - state = (shared.work.wait(state)).unwrap_or_else(PoisonError::into_inner); - } - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - shared.held.pass(); - if exit_guard::closed() { - return; - } - targets.begin_ahead(raw); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - lock(&shared.state).running = false; - shared.idle.notify_all(); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/binary_archive/container.rs b/crates/metal2vulkan-runtime/src/binary_archive/container.rs deleted file mode 100644 index 364ccead2..000000000 --- a/crates/metal2vulkan-runtime/src/binary_archive/container.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! A binary archive's file: the compile layer's self-checking artifacts the creations added to it -//! used, each under its kind, key and profile, and the archive key (`metal_key`) of each descriptor -//! added. -//! -//! ```text -//! magic 8 bytes "M2VBARCH" -//! version u32 1 -//! keys u32 their count, then each key's 32 bytes, ascending -//! entries u32 their count, then each entry, ascending by (kind, key, profile): -//! kind u32 a translated function 1, a compute pipeline 2, a render -//! pipeline 4 (the shader cache's entry kinds) -//! key 32 bytes the function's or pipeline's key -//! profile 32 bytes the fingerprint of the profile it was compiled for -//! length u64 then that many bytes: the artifact's encoding -//! checksum 32 bytes SHA-256 of every byte before it -//! ``` -//! -//! Integers are little-endian. Bytes that are not exactly this (another magic or version, a kind -//! not listed, a count or length past the end, bytes after the checksum, a checksum that does -//! not hold, keys or entries out of order or repeated) are not an archive. Nothing is allocated -//! for a count before the bytes it counts are there. -//! -//! A file is read whole, and written through a temporary file beside it and a rename, so a -//! reader never sees part of one. The errors are Metal's (measured on an M3 Max and an M4): a -//! file that is missing or not an archive, or a missing directory to write into, is -//! `InvalidFile`; any other failure to write (a directory at the path, for one) is `Write`. - -use crate::error::{BinaryArchiveError, Error}; -use crate::shader_cache::EntryKind; -use metal2vulkan::cache::Hash256; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use std::io::Write as _; -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -const MAGIC: &[u8; 8] = b"M2VBARCH"; -const VERSION: u32 = 1; -const KINDS: [EntryKind; 3] = [ - EntryKind::Function, - EntryKind::ComputePipeline, - EntryKind::RenderPipeline, -]; - -/// An artifact's place in an archive. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub(crate) struct Place { - pub(crate) kind: u32, - pub(crate) key: Hash256, - pub(crate) profile: Hash256, -} - -impl Place { - /// The place of the artifact of `kind` under `key` for the profile of fingerprint - /// `profile`. - pub(crate) fn new(kind: EntryKind, key: Hash256, profile: Hash256) -> Place { - Place { - kind: kind as u32, - key, - profile, - } - } -} - -/// What an archive holds. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub(crate) struct Contents { - /// The archive keys of the descriptors added. - pub(crate) keys: BTreeSet, - /// The artifacts' encodings by place. - pub(crate) entries: BTreeMap>, -} - -impl Contents { - /// Whether nothing was added. - pub(crate) fn is_empty(&self) -> bool { - self.keys.is_empty() && self.entries.is_empty() - } -} - -/// The file of `contents`. -pub(crate) fn encode(contents: &Contents) -> Vec { - let bytes: usize = contents - .entries - .values() - .map(|entry| entry.len() + 76) - .sum(); - let mut out = Vec::with_capacity(52 + contents.keys.len() * 32 + bytes); - out.extend_from_slice(MAGIC); - out.extend_from_slice(&VERSION.to_le_bytes()); - out.extend_from_slice(&(contents.keys.len() as u32).to_le_bytes()); - for key in &contents.keys { - out.extend_from_slice(key); - } - out.extend_from_slice(&(contents.entries.len() as u32).to_le_bytes()); - for (place, entry) in &contents.entries { - out.extend_from_slice(&place.kind.to_le_bytes()); - out.extend_from_slice(&place.key); - out.extend_from_slice(&place.profile); - out.extend_from_slice(&(entry.len() as u64).to_le_bytes()); - out.extend_from_slice(entry); - } - let checksum: Hash256 = Sha256::digest(&out).into(); - out.extend_from_slice(&checksum); - out -} - -/// The contents of `bytes`, or `None` when they are not an archive. -pub(crate) fn decode(bytes: &[u8]) -> Option { - let end = bytes.len().checked_sub(32)?; - let checksum: Hash256 = Sha256::digest(&bytes[..end]).into(); - if bytes[end..] != checksum { - return None; - } - let mut reader = Reader(&bytes[..end]); - if reader.take(8)? != MAGIC || reader.u32()? != VERSION { - return None; - } - let mut contents = Contents::default(); - let keys = reader.u32()? as usize; - if keys.checked_mul(32)? > reader.0.len() { - return None; - } - for _ in 0..keys { - let key = reader.hash()?; - if contents.keys.last().is_some_and(|last| *last >= key) { - return None; - } - contents.keys.insert(key); - } - let entries = reader.u32()?; - for _ in 0..entries { - let kind = reader.u32()?; - if !KINDS.iter().any(|known| *known as u32 == kind) { - return None; - } - let place = Place { - kind, - key: reader.hash()?, - profile: reader.hash()?, - }; - let length = usize::try_from(reader.u64()?).ok()?; - let entry = reader.take(length)?; - if contents - .entries - .last_key_value() - .is_some_and(|(last, _)| *last >= place) - { - return None; - } - contents.entries.insert(place, Arc::from(entry)); - } - reader.0.is_empty().then_some(contents) -} - -/// The bytes not read yet. -struct Reader<'a>(&'a [u8]); - -impl<'a> Reader<'a> { - fn take(&mut self, count: usize) -> Option<&'a [u8]> { - if count > self.0.len() { - return None; - } - let (taken, rest) = self.0.split_at(count); - self.0 = rest; - Some(taken) - } - - fn u32(&mut self) -> Option { - Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) - } - - fn u64(&mut self) -> Option { - Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?)) - } - - fn hash(&mut self) -> Option { - self.take(32)?.try_into().ok() - } -} - -/// The archive in the file `path`: an archive of ours, or a metallib, which Metal takes as an -/// archive (`newBinaryArchiveWithDescriptor:error:` answers one, measured on an M3 Max under -/// macOS 27.0.1) and which holds nothing of ours, so it loads as an archive holding nothing, -/// whose lookups miss as Metal's archive of a metallib does (`binary-archive-sources`). A path -/// that names no regular file (a FIFO, a device or a directory) is no archive ([`read_file`]). -pub(crate) fn read(path: &Path) -> Result { - let bytes = read_file(path).map_err(|_| invalid_file(path))?; - if let Some(contents) = decode(&bytes) { - return Ok(contents); - } - match metal2vulkan::library::Library::from_metallib(&bytes) { - Ok(_) => Ok(Contents::default()), - Err(_) => Err(invalid_file(path)), - } -} - -/// Why [`read_file`] could not read a file. -pub(crate) enum ReadFailure { - /// The path names no regular file: a FIFO, a device, a socket or a directory. - NotRegular, - /// Reading failed (a missing file, for one). - Io(std::io::Error), -} - -/// The bytes of the regular file `path`, read once and no further than the length it has when -/// opened: a binary archive's file, and a dynamic library's (`dynamic_library.rs`). A path that -/// names anything else is [`ReadFailure::NotRegular`], and nothing that could wait for a writer or -/// act on a device is done to it: it is looked at before it is opened, opened without waiting -/// (`O_NONBLOCK`, which a regular file's reads ignore) and looked at again through the handle, in -/// case it changed between the two. A length the process cannot hold is refused (`OutOfMemory`) -/// rather than allocated. -pub(crate) fn read_file(path: &Path) -> Result, ReadFailure> { - use std::io::Read as _; - if !std::fs::metadata(path).map_err(ReadFailure::Io)?.is_file() { - return Err(ReadFailure::NotRegular); - } - let mut options = std::fs::OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt as _; - options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY); - } - let file = options.open(path).map_err(ReadFailure::Io)?; - let metadata = file.metadata().map_err(ReadFailure::Io)?; - if !metadata.is_file() { - return Err(ReadFailure::NotRegular); - } - let length = metadata.len(); - let mut bytes = Vec::new(); - usize::try_from(length) - .ok() - .and_then(|length| bytes.try_reserve_exact(length).ok()) - .ok_or_else(|| { - ReadFailure::Io(std::io::Error::new( - std::io::ErrorKind::OutOfMemory, - format!("{length} bytes cannot be held"), - )) - })?; - file.take(length) - .read_to_end(&mut bytes) - .map_err(ReadFailure::Io)?; - Ok(bytes) -} - -/// Write `bytes`, an archive's encoding, to the file `url`, replacing what is there. -pub(crate) fn write(bytes: &[u8], url: &Path) -> Result<(), Error> { - write_file(bytes, url).map_err(|failure| match failure { - WriteFailure::NoDirectory => invalid_file(url), - WriteFailure::Io(error) => Error::BinaryArchive(BinaryArchiveError::Write { - path: url.to_path_buf(), - kind: error.kind(), - message: error.to_string(), - }), - }) -} - -/// Why [`write_file`] could not write a file. -pub(crate) enum WriteFailure { - /// The directory to write into is missing. - NoDirectory, - /// Writing failed (a directory at the path, for one). - Io(std::io::Error), -} - -/// Write `bytes` to the file `url`, replacing what is there, through a temporary file beside it -/// and a rename, so a reader never sees part of it: a binary archive's file, and a dynamic -/// library's (`dynamic_library.rs`). -pub(crate) fn write_file(bytes: &[u8], url: &Path) -> Result<(), WriteFailure> { - let directory = match url.parent() { - Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(), - _ => PathBuf::from("."), - }; - if !directory.is_dir() { - return Err(WriteFailure::NoDirectory); - } - if url.is_dir() { - return Err(WriteFailure::Io(std::io::Error::new( - std::io::ErrorKind::IsADirectory, - "a directory is at the path", - ))); - } - let mut temporary = Temporary::beside(&directory, url).map_err(WriteFailure::Io)?; - temporary - .file - .write_all(bytes) - .and_then(|()| temporary.file.sync_all()) - .and_then(|()| std::fs::rename(&temporary.path, url)) - .map_err(WriteFailure::Io)?; - temporary.renamed = true; - Ok(()) -} - -/// `BinaryArchive(InvalidFile)` of `path`. -fn invalid_file(path: &Path) -> Error { - Error::BinaryArchive(BinaryArchiveError::InvalidFile { - path: path.to_path_buf(), - }) -} - -/// A temporary file beside the file it writes, removed when dropped unless renamed onto it. -struct Temporary { - path: PathBuf, - file: std::fs::File, - renamed: bool, -} - -impl Temporary { - /// A new temporary file in `directory` for writing `url`, named after it, the process and a - /// counter. - fn beside(directory: &Path, url: &Path) -> std::io::Result { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT: AtomicU64 = AtomicU64::new(0); - let name = url - .file_name() - .map_or_else(|| "archive".into(), |name| name.to_string_lossy()); - let path = directory.join(format!( - ".{name}.{}.{}.tmp", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - let file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path)?; - Ok(Temporary { - path, - file, - renamed: false, - }) - } -} - -impl Drop for Temporary { - fn drop(&mut self) { - if !self.renamed { - let _ = std::fs::remove_file(&self.path); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/binary_archive/metal_key.rs b/crates/metal2vulkan-runtime/src/binary_archive/metal_key.rs deleted file mode 100644 index 79b40cfed..000000000 --- a/crates/metal2vulkan-runtime/src/binary_archive/metal_key.rs +++ /dev/null @@ -1,517 +0,0 @@ -//! The key Metal's binary archives find a pipeline by, so that -//! `PipelineOption::FAIL_ON_BINARY_ARCHIVE_MISS` refuses exactly where Metal's does. -//! -//! Measured on an M3 Max (macOS 26.7) and an M4 (macOS 27.0.1), which agree on every field: a -//! creation hits an archive a descriptor was added to unless a keyed field differs. -//! -//! - **Functions.** A function is its name and its bitcode's content (a library made again from -//! the same bytes hits), and the value of each constant it declares, however supplied (by name -//! or by index alike; a value it does not declare changes nothing; a constant without a value -//! differs from one with). Its linked functions are keyed as sets (their order changes -//! nothing, an empty set is none), each list apart: `functions`, `private_functions`, -//! `binary_functions`, and each group by name. -//! - **Compute.** The kernel; the stage input descriptor in full (an empty one is none; every -//! attribute and layout, used or not, and the index buffer's index, but not the index type); -//! `max_total_threads_per_threadgroup`; `support_indirect_command_buffers`; -//! `support_adding_binary_functions`; `required_threads_per_threadgroup` (an all-zero size is -//! none); the buffers set `Mutable`. Not `threadgroup_size_is_multiple_of_execution_width`, nor -//! the label. -//! - **Tile.** The tile function, apart from a compute key of the same function; each color -//! attachment with a pixel format (its index and format); the raster sample count; -//! `threadgroup_size_matches_tile_size`; `max_total_threads_per_threadgroup`; -//! `support_adding_binary_functions`; `required_threads_per_threadgroup`; the buffers set -//! `Mutable`. Not the label. -//! - **Buffer mutability**. A stage's key holds the index of each buffer set `Mutable`, whether its -//! function writes, reads or does not use it, in compute, tile, vertex and fragment stages alike. -//! `Immutable` and the default change nothing. -//! - **Render: each stage apart.** A render creation looks up its fragment stage's key, then its -//! vertex stage's, each in every archive listed, and misses naming the first function not -//! found: so two adds' stages combine. The fragment key: the fragment function, the vertex -//! descriptor in full (an empty one is none), each color attachment with a pixel format (its -//! index, format and write mask, whether it blends, and its blend factors and operations only -//! when it blends), the raster sample count, alpha to coverage and to one, and -//! `support_indirect_command_buffers`, `support_adding_fragment_binary_functions` and the -//! fragment buffers set `Mutable`. The vertex key: the vertex function, the vertex -//! descriptor, the input primitive topology class (line and triangle alike), whether -//! rasterization is enabled, whether a fragment stage reads the vertex outputs, the vertex -//! amplification count, `support_indirect_command_buffers`, the tessellation partition mode -//! and factor step function, `support_adding_vertex_binary_functions` and the vertex buffers -//! set `Mutable`. The control point index type is in both keys, only for a -//! post-tessellation vertex function. Neither holds the depth and stencil formats, the maximum -//! tessellation factor, factor scale or winding order, nor the label; a creation without a -//! fragment function looks up no fragment key, so its color attachments change nothing. -//! - **Which vertex outputs the fragment stage reads.** Metal's vertex key holds the outputs its -//! compiler finds the fragment reading: none for a fragment that reads only its position or -//! nothing, or whose color the write mask or blend factors discard, the same set for two -//! fragments reading the same outputs. A lookup here does not decode, so the key holds whether -//! a fragment stage reads at all (a fragment function under enabled rasterization). That is -//! Metal's answer whenever both stages come from one add. An add also keeps its two stages' -//! pair key (`RenderKeys::pair`), so a lookup that finds both stages but no add's pair of them -//! combines two adds' stages; that creation announces `combined-archive-stages`, since Metal -//! misses it where the two fragments read different outputs. Where the key's answer makes the -//! runtime miss and Metal hit, the creation is refused. -//! - **Mesh** (not measured: no probe has asked which of a mesh descriptor's fields Metal keys). -//! One key of every field the descriptor holds: the object, mesh and fragment stages, each as a -//! stage (its function, constants and linked functions), each color attachment with a pixel -//! format as the render fragment key holds it, the depth and stencil formats, the raster -//! sample count, rasterization, alpha to coverage and to one, the texture write rounding mode, -//! `support_indirect_command_buffers`, both threadgroup maxima, the mesh-grid maximum, both -//! multiple-of-execution-width flags, the payload length, the vertex amplification count and -//! both required threadgroup sizes. So a creation hits only an add of an equal descriptor, -//! where Metal's hits too, and one that differs from every add in a field Metal does not key -//! misses here where Metal's may hit. -//! - **Dynamic libraries** (probes, an M3 Max and an M4). Neither a stage's preloaded libraries -//! (used or not, in any order, of any contents or install name) nor the contents of the libraries -//! its install names load are in its key: a dependency's file replaced hits, and the creation -//! links the new file's code. A function's bitcode names the install names it was linked against, -//! so they are in its content. -//! - **The rest.** Metal's descriptor fields the compile layer's descriptors do not have yet -//! (call stack depths, shader validation) never reach a key. -//! -//! Every key also holds the profile it is for and the artifact and semantics versions, as an -//! archive made on another device, or by a build whose translations differ, misses on Metal's -//! GPUs (an M4's archive missed on the M3). -//! -//! Whether a vertex function is a post-tessellation one shows only once it is decoded, and a -//! lookup must not decode. So each render stage has two keys, without and with the control point -//! index type, and an archive keeps the ones that fit its vertex function, which it learns from -//! the compile its add makes. The vertex key holds the function's identity, so the variant an -//! archive holds of it tells a lookup which of the fragment's keys to look for. - -use metal2vulkan::cache::{Hash256, ARTIFACT_FORMAT_VERSION, SEMANTICS_VERSION}; -use metal2vulkan::library::{Function, FunctionConstantValues}; -use metal2vulkan::metal::{ - AttributeFormat, Mutability, PixelFormat, PrimitiveTopologyClass, VertexFormat, -}; -use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, ComputePipelineDescriptor, LinkedFunction, LinkedFunctions, - MeshPipelineDescriptor, RenderPipelineDescriptor, StageInputAttributeDescriptor, - StageInputDescriptor, StageInputLayoutDescriptor, StageSource, TileRenderPipelineDescriptor, - VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, -}; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; - -/// Whether a vertex function is a post-tessellation one. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum VertexKind { - Plain, - Patch, -} - -/// A render stage's two keys, by the kind of the vertex function. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct StageKeys { - /// The key beside a vertex function that is not a post-tessellation one. - pub(crate) plain: Hash256, - /// The key beside a post-tessellation vertex function: `plain`'s fields and the control - /// point index type. - pub(crate) patch: Hash256, -} - -impl StageKeys { - /// The key beside a vertex function of `kind`. - pub(crate) fn of(&self, kind: VertexKind) -> Hash256 { - match kind { - VertexKind::Plain => self.plain, - VertexKind::Patch => self.patch, - } - } - - /// The kind whose key `held` holds, if either's. - pub(crate) fn held(&self, held: &dyn Fn(&Hash256) -> bool) -> Option { - [VertexKind::Plain, VertexKind::Patch] - .into_iter() - .find(|kind| held(&self.of(*kind))) - } -} - -/// A render descriptor's stage keys. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct RenderKeys { - /// The fragment stage's keys, when there is a fragment function. - pub(crate) fragment: Option, - /// The vertex stage's keys. - pub(crate) vertex: StageKeys, -} - -impl RenderKeys { - /// The key of both stages of one add beside a vertex function of `kind`, when there is a - /// fragment function: an add keeps it, so a lookup whose two stages were found tells one - /// add's stages from two adds' (which vertex outputs the fragment reads, the module docs). - pub(crate) fn pair(&self, kind: VertexKind) -> Option { - let fragment = self.fragment?; - let mut key = Key(Sha256::new()); - key.bytes(b"metal2vulkan binary archive render pair 1"); - key.0.update(self.vertex.of(kind)); - key.0.update(fragment.of(kind)); - Some(key.finish()) - } -} - -/// The archive key of `descriptor` on the device of profile `profile`. -pub(crate) fn compute(profile: &Hash256, descriptor: &ComputePipelineDescriptor) -> Hash256 { - let mut key = Key::new(b"compute", profile); - key.stage(&descriptor.kernel); - match &descriptor.stage_input { - Some(input) if *input != StageInputDescriptor::new() => { - key.flag(true); - stage_input(&mut key, input); - } - _ => key.flag(false), - } - key.u32(descriptor.max_total_threads_per_threadgroup.unwrap_or(0)); - key.flag(descriptor.support_indirect_command_buffers); - key.flag(descriptor.support_adding_binary_functions); - key.required(descriptor.required_threads_per_threadgroup); - key.mutable(&descriptor.buffers); - key.finish() -} - -/// The archive key of the tile pipeline `descriptor` on the device of profile `profile`. -pub(crate) fn tile(profile: &Hash256, descriptor: &TileRenderPipelineDescriptor) -> Hash256 { - let mut key = Key::new(b"tile", profile); - key.stage(&descriptor.tile); - for (index, format) in (0u32..).zip(&descriptor.color_attachment_formats) { - match format { - Some(format) if *format != PixelFormat::Invalid => { - key.u32(index); - key.u32(format.as_raw()); - } - _ => {} - } - } - key.u32(u32::MAX); - key.u32(descriptor.raster_sample_count); - key.flag(descriptor.threadgroup_size_matches_tile_size); - key.u32(descriptor.max_total_threads_per_threadgroup.unwrap_or(0)); - key.flag(descriptor.support_adding_binary_functions); - key.required(descriptor.required_threads_per_threadgroup); - key.mutable(&descriptor.buffers); - key.finish() -} - -/// The archive keys of `descriptor`'s stages on the device of profile `profile`. -pub(crate) fn render(profile: &Hash256, descriptor: &RenderPipelineDescriptor) -> RenderKeys { - let tessellation = descriptor.tessellation.unwrap_or_default(); - let control_points = tessellation.control_point_index_type.as_raw(); - let fragment = descriptor.fragment.as_ref().map(|fragment| { - let mut key = Key::new(b"render fragment", profile); - key.stage(fragment); - vertex_descriptor(&mut key, descriptor.vertex_descriptor.as_ref()); - color_attachments(&mut key, &descriptor.color_attachments); - key.u32(descriptor.raster_sample_count); - key.flag(descriptor.alpha_to_coverage); - key.flag(descriptor.alpha_to_one); - key.flag(descriptor.support_indirect_command_buffers); - key.flag(descriptor.support_adding_fragment_binary_functions); - key.mutable(&descriptor.fragment_buffers); - key.variants(control_points) - }); - let mut key = Key::new(b"render vertex", profile); - key.stage(&descriptor.vertex); - vertex_descriptor(&mut key, descriptor.vertex_descriptor.as_ref()); - // Measured: a line and a triangle class make one key; no class, points and the two differ. - let class = match descriptor.input_primitive_topology { - PrimitiveTopologyClass::Triangle => PrimitiveTopologyClass::Line, - class => class, - }; - key.u32(class.as_raw()); - key.flag(descriptor.rasterization_enabled); - key.flag(descriptor.fragment.is_some() && descriptor.rasterization_enabled); - key.u32(descriptor.max_vertex_amplification_count); - key.flag(descriptor.support_indirect_command_buffers); - key.u32(tessellation.partition_mode.as_raw()); - key.u32(tessellation.factor_step_function.as_raw()); - key.flag(descriptor.support_adding_vertex_binary_functions); - key.mutable(&descriptor.vertex_buffers); - RenderKeys { - fragment, - vertex: key.variants(control_points), - } -} - -/// The archive key of the mesh pipeline `descriptor` on the device of profile `profile`: every -/// field it holds (the module docs). -pub(crate) fn mesh(profile: &Hash256, descriptor: &MeshPipelineDescriptor) -> Hash256 { - let mut key = Key::new(b"mesh", profile); - let stages = [ - descriptor.object.as_ref(), - Some(&descriptor.mesh), - descriptor.fragment.as_ref(), - ]; - for stage in stages { - match stage { - Some(stage) => { - key.flag(true); - key.stage(stage); - } - None => key.flag(false), - } - } - color_attachments(&mut key, &descriptor.color_attachments); - for format in [descriptor.depth_format, descriptor.stencil_format] { - key.u32(format.map_or(u32::MAX, PixelFormat::as_raw)); - } - key.u32(descriptor.raster_sample_count); - key.flag(descriptor.rasterization_enabled); - key.flag(descriptor.alpha_to_coverage); - key.flag(descriptor.alpha_to_one); - // The mode by its name: the enum states no raw value of its own. - key.bytes(format!("{:?}", descriptor.texture_write_rounding_mode).as_bytes()); - key.flag(descriptor.support_indirect_command_buffers); - for limit in [ - descriptor.max_total_threads_per_object_threadgroup, - descriptor.max_total_threads_per_mesh_threadgroup, - descriptor.max_total_threadgroups_per_mesh_grid, - descriptor.payload_memory_length, - ] { - key.u32(limit.unwrap_or(0)); - } - key.flag(descriptor.object_threadgroup_size_is_multiple_of_thread_execution_width); - key.flag(descriptor.mesh_threadgroup_size_is_multiple_of_thread_execution_width); - key.u32(descriptor.max_vertex_amplification_count); - key.required(descriptor.required_threads_per_object_threadgroup); - key.required(descriptor.required_threads_per_mesh_threadgroup); - key.finish() -} - -/// Each color attachment of `attachments` with a pixel format: its index, format and write mask, -/// whether it blends, and its blend factors and operations only when it blends. -fn color_attachments(key: &mut Key, attachments: &[Option]) { - for (index, attachment) in (0u32..).zip(attachments) { - let Some(attachment) = attachment else { - continue; - }; - if attachment.pixel_format == PixelFormat::Invalid { - continue; - } - key.u32(index); - key.u32(attachment.pixel_format.as_raw()); - key.u32(attachment.write_mask.as_raw()); - key.flag(attachment.blending_enabled); - if attachment.blending_enabled { - for raw in [ - attachment.source_rgb_blend_factor.as_raw(), - attachment.destination_rgb_blend_factor.as_raw(), - attachment.rgb_blend_operation.as_raw(), - attachment.source_alpha_blend_factor.as_raw(), - attachment.destination_alpha_blend_factor.as_raw(), - attachment.alpha_blend_operation.as_raw(), - ] { - key.u32(raw); - } - } - } - key.u32(u32::MAX); -} - -/// The stage input descriptor `input`: each layout but Metal's unset one (stride 0, per vertex, -/// step rate 1, which Metal's serializer leaves out) and each set attribute, then the index -/// buffer's index. -fn stage_input(key: &mut Key, input: &StageInputDescriptor) { - let unset_layout = StageInputLayoutDescriptor::new(Some(0)); - let unset_attribute = StageInputAttributeDescriptor::new(AttributeFormat::Invalid, 0, 0); - for (index, layout) in &input.layouts { - if *layout != unset_layout { - key.u32(*index); - match layout.stride { - Some(stride) => { - key.flag(true); - key.u32(stride); - } - None => key.flag(false), - } - key.u32(layout.step_function.as_raw()); - key.u32(layout.step_rate); - } - } - key.u32(u32::MAX); - for (index, attribute) in &input.attributes { - if *attribute != unset_attribute { - key.u32(*index); - key.u32(attribute.format.as_raw()); - key.u32(attribute.offset); - key.u32(attribute.buffer_index); - } - } - key.u32(u32::MAX); - key.u32(input.index_buffer_index); -} - -/// The vertex descriptor `vertex`, an empty one as none. -fn vertex_descriptor(key: &mut Key, vertex: Option<&VertexDescriptor>) { - let Some(vertex) = vertex.filter(|vertex| **vertex != VertexDescriptor::new()) else { - key.flag(false); - return; - }; - key.flag(true); - let unset_layout = VertexBufferLayoutDescriptor::new(Some(0)); - let unset_attribute = VertexAttributeDescriptor::new(VertexFormat::Invalid, 0, 0); - for (index, layout) in &vertex.layouts { - if *layout != unset_layout { - key.u32(*index); - match layout.stride { - Some(stride) => { - key.flag(true); - key.u32(stride); - } - None => key.flag(false), - } - key.u32(layout.step_function.as_raw()); - key.u32(layout.step_rate); - } - } - key.u32(u32::MAX); - for (index, attribute) in &vertex.attributes { - if *attribute != unset_attribute { - key.u32(*index); - key.u32(attribute.format.as_raw()); - key.u32(attribute.offset); - key.u32(attribute.buffer_index); - } - } - key.u32(u32::MAX); -} - -/// A key being written: SHA-256 over a fixed-width, length-prefixed encoding. -#[derive(Clone)] -struct Key(Sha256); - -impl Key { - /// A key of pipeline `kind` for `profile`, under this build's artifact and semantics - /// versions. - fn new(kind: &[u8], profile: &Hash256) -> Key { - let mut key = Key(Sha256::new()); - key.bytes(b"metal2vulkan binary archive key 1"); - key.bytes(kind); - key.0.update(profile); - key.u32(ARTIFACT_FORMAT_VERSION); - key.u32(SEMANTICS_VERSION); - key - } - - fn finish(self) -> Hash256 { - self.0.finalize().into() - } - - /// The stage keys of what is written: as it is, and with the control point index type - /// `control_points` appended. - fn variants(self, control_points: u32) -> StageKeys { - let mut patch = self.clone(); - patch.u32(control_points); - StageKeys { - plain: self.finish(), - patch: patch.finish(), - } - } - - fn u32(&mut self, value: u32) { - self.0.update(value.to_le_bytes()); - } - - fn flag(&mut self, value: bool) { - self.0.update([u8::from(value)]); - } - - /// The indices of a stage's buffers set `Mutable`: Metal keys those alone, whether the function - /// writes, reads or does not use the buffer, and keys neither `Immutable` nor the default. - fn mutable(&mut self, buffers: &BTreeMap) { - for (index, mutability) in buffers { - if *mutability == Mutability::Mutable { - self.u32(*index); - } - } - self.u32(u32::MAX); - } - - /// A required threadgroup size (`requiredThreadsPerThreadgroup`), or none: Metal's all-zero - /// size is none. - fn required(&mut self, required: Option<[u32; 3]>) { - match required.filter(|axes| *axes != [0; 3]) { - Some(axes) => { - self.flag(true); - for axis in axes { - self.u32(axis); - } - } - None => self.flag(false), - } - } - - fn bytes(&mut self, bytes: &[u8]) { - self.0.update((bytes.len() as u64).to_le_bytes()); - self.0.update(bytes); - } - - /// A stage: its function, constant values and linked functions, or the compile key of a - /// function compiled already. - fn stage(&mut self, source: &StageSource) { - match source { - StageSource::Function(descriptor) => { - self.flag(true); - self.function(&descriptor.function, &descriptor.constants); - self.linked(&descriptor.linked); - } - StageSource::Compiled(compiled) => { - self.flag(false); - self.0.update(compiled.key().digest()); - } - } - } - - /// `function`'s name and content, and the value of each constant it declares. - fn function(&mut self, function: &Function, values: &FunctionConstantValues) { - let info = function.info(); - self.bytes(info.name.as_bytes()); - self.0.update(info.air_hash); - for constant in info.constants { - let value = constant - .index - .and_then(|index| values.by_index.get(&index)) - .or_else(|| values.by_name.get(&constant.name)); - match value { - Some(value) => { - self.flag(true); - self.u32(value.ty.as_raw()); - self.bytes(&value.bytes); - } - None => self.flag(false), - } - } - } - - /// Each list of `linked` as a set. - fn linked(&mut self, linked: &LinkedFunctions) { - if linked.is_empty() { - self.flag(false); - return; - } - self.flag(true); - self.set(&linked.functions); - self.set(&linked.private_functions); - self.set(&linked.binary_functions); - self.u32(linked.groups.len() as u32); - for (name, functions) in &linked.groups { - self.bytes(name.as_bytes()); - self.set(functions); - } - } - - /// `functions` in no order: each function's own key, sorted. - fn set(&mut self, functions: &[LinkedFunction]) { - let mut members: Vec = functions - .iter() - .map(|linked| { - let mut member = Key(Sha256::new()); - member.function(&linked.function, &linked.constants); - member.finish() - }) - .collect(); - members.sort_unstable(); - self.u32(members.len() as u32); - for member in members { - self.0.update(member); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/binary_archive/mod.rs b/crates/metal2vulkan-runtime/src/binary_archive/mod.rs deleted file mode 100644 index cc3d39256..000000000 --- a/crates/metal2vulkan-runtime/src/binary_archive/mod.rs +++ /dev/null @@ -1,502 +0,0 @@ -//! `BinaryArchive` (`MTLBinaryArchive`) and `Device::new_binary_archive`. -//! -//! - **What it holds.** The compile layer's self-checking artifacts, not driver binaries: each -//! translated function and linked pipeline a creation added to it used, under its kind, key and -//! profile; and the archive key (`metal_key`) of each descriptor added. The driver's pipeline -//! cache data stays in the device's shader cache. -//! - **Where creations look.** A creation that lists archives in its [`PipelineOptions`] looks -//! in the device's memo, then in its archives in order, then in the shader cache on disk, -//! before compiling (`pipeline/sources.rs`). What an archive gives skips the translation, as -//! Metal's archives skip the compile. A variant a dispatch or draw needs later is not looked -//! up in archives: no add compiled it. -//! - **Failing on a miss.** Under `PipelineOption::FAIL_ON_BINARY_ARCHIVE_MISS`, a creation -//! that lists at least one archive is refused ([`Error::BinaryArchiveMiss`]) unless the -//! archives hold the archive key of each of its stages (`metal_key`), as Metal's creation is, -//! naming the first stage's function they miss. Without archives, or without the option, -//! archives only make creation faster. -//! - **Adding.** `add_compute_pipeline_functions`, `add_render_pipeline_functions`, -//! `add_tile_render_pipeline_functions` and `add_mesh_render_pipeline_functions` make the state -//! their descriptor describes, as the creation would, and answer that creation's error; then -//! they keep what the creation used and the archive keys of its stages. Adding twice keeps one -//! copy. A mesh creation compiles its pipeline whole, looking in no archive, so a mesh add keeps -//! its key alone, which `FAIL_ON_BINARY_ARCHIVE_MISS` finds. -//! - **Files.** An archive is read whole from its descriptor's file (`container.rs`) and written -//! through a temporary file and a rename. A metallib, which Metal takes as an archive, loads as -//! an empty one, whose lookups miss as Metal's do. An archive of another profile or build -//! loads, and its entries miss, as Metal's archive of another device or OS does. Labels are not -//! written, as Metal's are not. -//! - **Across a recovery.** An archive holds no Vulkan object, so it goes on past its device's -//! recovery, as Metal's does, the recovery carrying its handle of the device alone -//! (`device/carry.rs`'s `LineDevice`): a creation of any generation lists it, and an add makes -//! its state on the generation that serves. -//! - **Differences from Metal**, accepted (docs/API.md §10): the file is read whole at load, so an -//! archive serializes after its file was deleted, where Metal's fails; and a file is a path, -//! so a URL that is not a file cannot be named, where Metal answers it as an invalid URL. - -pub(super) mod container; -pub(super) mod metal_key; - -use super::device::carry::LineDevice; -use super::device::lock; -use super::error::{ArchivedPipeline, BinaryArchiveError, BinaryArchiveMiss, Error}; -use super::pipeline::{ - ComputePipelineState, GraphicsState, PipelineOption, PipelineOptions, TileState, -}; -use super::shader_cache::EntryKind; -use super::Device; -use container::{Contents, Place}; -use metal2vulkan::cache::{Hash256, PipelineArtifact, PipelineKey}; -use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; -use metal2vulkan::pipeline::{ - ComputePipeline, ComputePipelineDescriptor, MeshPipelineDescriptor, RenderPipeline, - RenderPipelineDescriptor, StageSource, TileRenderPipelineDescriptor, -}; -use metal_key::VertexKind; -use std::cell::RefCell; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; - -/// `MTLBinaryArchiveDescriptor`. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct BinaryArchiveDescriptor { - /// `url`: the file to load the archive from; `None` makes an empty archive. - pub url: Option, -} - -impl BinaryArchiveDescriptor { - /// The descriptor of the archive in the file `url`. - pub fn new(url: Option) -> BinaryArchiveDescriptor { - BinaryArchiveDescriptor { url } - } -} - -/// A Metal binary archive (`MTLBinaryArchive`). Cheap to clone (a retain); `Send + Sync`. -#[derive(Clone)] -pub struct BinaryArchive(Arc); - -struct Shared { - /// The device: its root handle, which a creation's check matches by its line and an add's - /// creation goes through, and the generation handle `device` answers. - device: LineDevice, - label: Mutex>, - contents: Mutex, -} - -impl std::fmt::Debug for BinaryArchive { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let contents = lock(&self.0.contents); - f.debug_struct("BinaryArchive") - .field("keys", &contents.keys.len()) - .field("entries", &contents.entries.len()) - .finish() - } -} - -/// An artifact a creation used, which an add keeps. -pub(crate) enum Artifact { - Function(CompiledFunction), - Compute(Arc), - Render(Arc), -} - -/// The artifacts a creation for an add used, in order. -pub(crate) type Used = RefCell>; - -impl Device { - /// `newBinaryArchiveWithDescriptor:error:`: an empty archive, or the archive in the - /// descriptor's file. A file that is missing or neither an archive nor a metallib is - /// `BinaryArchive(InvalidFile)`, as Metal answers for a missing, empty, garbage or text file - /// and for a directory (measured on an M3 Max and an M4). A metallib, which Metal takes as an - /// archive (measured on an M3 Max), holds nothing of ours: it loads as an empty archive, - /// whose lookups miss and which serializes as one nothing was added to. Metal's archive of a - /// metallib misses too: a compute pipeline of a kernel the metallib holds, listing it with - /// `FAIL_ON_BINARY_ARCHIVE_MISS`, is refused, and without the bit it is created (measured on - /// an M3 Max under macOS 27.0.1, `binary-archive-sources`). - pub fn new_binary_archive( - &self, - descriptor: &BinaryArchiveDescriptor, - ) -> Result { - self.at_serving(|device| device.new_binary_archive_now(descriptor)) - } - - /// [`Device::new_binary_archive`] on the generation that serves (`device/line.rs`). - pub(crate) fn new_binary_archive_now( - &self, - descriptor: &BinaryArchiveDescriptor, - ) -> Result { - let contents = match &descriptor.url { - None => Contents::default(), - Some(path) => container::read(path)?, - }; - Ok(BinaryArchive(Arc::new(Shared { - device: LineDevice::new(self), - label: Mutex::new(None), - contents: Mutex::new(contents), - }))) - } -} - -impl BinaryArchive { - /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained - /// device: of the generation the archive was made on, then of each one the device's recoveries - /// carried the archive to. The handle is the caller's: it keeps meaning that generation while - /// held, past a recovery that carries the archive on, its raw handles that generation's - /// `VkDevice`'s, kept alive while held. - pub fn device(&self) -> Device { - self.generation().clone() - } - - /// The generation handle [`device`](Self::device) answers a clone of, borrowed for the - /// runtime's own reads: a caller's handle is `device`'s, as a recovery lets go of the - /// object's handle of a lost generation at that generation's rest (`device/carry.rs`). - pub(crate) fn generation(&self) -> &Device { - self.0.device.generation() - } - - /// A root handle of the archive's device, which a creation of any of its generations - /// matches. - fn root_device(&self) -> &Device { - self.0.device.root() - } - - /// `setLabel:`. - pub fn set_label(&self, label: &str) { - *lock(&self.0.label) = Some(label.to_owned()); - } - - /// `label`: `None` until one is set. - pub fn label(&self) -> Option { - lock(&self.0.label).clone() - } - - /// `addComputePipelineFunctionsWithDescriptor:error:`: make the state `descriptor` - /// describes, as `new_compute_pipeline_state` makes it with the default options, answering - /// its error; then keep what that creation used and the descriptor's archive key. - pub fn add_compute_pipeline_functions( - &self, - descriptor: &ComputePipelineDescriptor, - ) -> Result<(), Error> { - let used = self.root_device().at_serving(|device| { - let used = Used::default(); - let options = PipelineOptions::default(); - ComputePipelineState::create(device, descriptor, &options, Some(&used))?; - Ok(used) - })?; - let profile = self.profile(); - self.keep( - used.into_inner(), - &profile, - [metal_key::compute(&profile, descriptor)], - ); - Ok(()) - } - - /// `addRenderPipelineFunctionsWithDescriptor:error:`: make the state `descriptor` - /// describes, as `new_render_pipeline_state` makes it with the default options, answering - /// its error; then keep what that creation used and the archive keys of its stages. - pub fn add_render_pipeline_functions( - &self, - descriptor: &RenderPipelineDescriptor, - ) -> Result<(), Error> { - let (state, used) = self.root_device().at_serving(|device| { - let used = Used::default(); - let options = PipelineOptions::default(); - let state = GraphicsState::create(device, descriptor, &options, Some(&used))?; - Ok((state, used)) - })?; - let profile = self.profile(); - let keys = metal_key::render(&profile, descriptor); - let kind = if crate::tessellation::patches(&state.base().graphics).is_some() { - VertexKind::Patch - } else { - VertexKind::Plain - }; - let fragment = keys.fragment.map(|fragment| fragment.of(kind)); - self.keep( - used.into_inner(), - &profile, - fragment - .into_iter() - .chain([keys.vertex.of(kind)]) - .chain(keys.pair(kind)), - ); - Ok(()) - } - - /// `addTileRenderPipelineFunctionsWithDescriptor:error:`: make the state `descriptor` - /// describes, as `new_tile_render_pipeline_state` makes it with the default options, - /// answering its error; then keep what that creation used and the descriptor's archive key. - pub fn add_tile_render_pipeline_functions( - &self, - descriptor: &TileRenderPipelineDescriptor, - ) -> Result<(), Error> { - let used = self.root_device().at_serving(|device| { - let used = Used::default(); - let options = PipelineOptions::default(); - TileState::create(device, descriptor, &options, Some(&used))?; - Ok(used) - })?; - let profile = self.profile(); - self.keep( - used.into_inner(), - &profile, - [metal_key::tile(&profile, descriptor)], - ); - Ok(()) - } - - /// `addMeshRenderPipelineFunctionsWithDescriptor:error:`: make the state `descriptor` - /// describes, as `new_mesh_render_pipeline_state` makes it with the default options, - /// answering its error; then keep the descriptor's archive key. A mesh creation compiles its - /// pipeline whole and looks in no archive, so the add keeps no compiled artifact and makes no - /// later creation faster. Which of the descriptor's fields Metal keys a mesh pipeline by is - /// not measured: the key holds every field (`metal_key`), so under - /// `FAIL_ON_BINARY_ARCHIVE_MISS` a mesh creation hits only an add of an equal descriptor, and - /// one that differs from every add in a field Metal does not key is `BinaryArchiveMiss` where - /// Metal's creation may hit. - pub fn add_mesh_render_pipeline_functions( - &self, - descriptor: &MeshPipelineDescriptor, - ) -> Result<(), Error> { - self.root_device().at_serving(|device| { - GraphicsState::create_mesh(device, descriptor, &PipelineOptions::default()) - })?; - let profile = self.profile(); - self.keep( - Vec::new(), - &profile, - [metal_key::mesh(&profile, descriptor)], - ); - Ok(()) - } - - /// `serializeToURL:error:`: write the archive to the file `url`, replacing what is there, - /// through a temporary file beside it and a rename. An archive nothing was added to or - /// loaded into is `BinaryArchive(NothingToSerialize)`; a missing directory - /// `BinaryArchive(InvalidFile)`, and any other failure to write the file (a directory at - /// `url`, for one) `BinaryArchive(Write)`, as Metal answers each (measured on an M3 Max and - /// an M4). - pub fn serialize_to_url(&self, url: &Path) -> Result<(), Error> { - let bytes = { - let contents = lock(&self.0.contents); - if contents.is_empty() { - return Err(Error::BinaryArchive(BinaryArchiveError::NothingToSerialize)); - } - container::encode(&contents) - }; - container::write(&bytes, url) - } - - /// Whether the archive holds the archive key `key`. - pub(crate) fn holds(&self, key: &Hash256) -> bool { - lock(&self.0.contents).keys.contains(key) - } - - /// The function `compile` compiled under `key`, from the archive, and its encoded length. - pub(crate) fn function( - &self, - compile: &metal2vulkan::device::Device, - key: &FunctionCompileKey, - ) -> Option<(CompiledFunction, u64)> { - let bytes = self.entry(EntryKind::Function, key.digest(), compile)?; - let function = CompiledFunction::from_bytes_for_key(&bytes, key, compile).ok()?; - Some((function, bytes.len() as u64)) - } - - /// The compute pipeline `compile` compiled under `key`, from the archive, and its encoded - /// length. - pub(crate) fn compute_pipeline( - &self, - compile: &metal2vulkan::device::Device, - key: &PipelineKey, - ) -> Option<(ComputePipeline, u64)> { - let bytes = self.entry(EntryKind::ComputePipeline, key.digest(), compile)?; - let pipeline = ComputePipeline::from_bytes_for_key(&bytes, key, compile).ok()?; - Some((pipeline, bytes.len() as u64)) - } - - /// The render pipeline `compile` compiled under `key`, from the archive, and its encoded - /// length. - pub(crate) fn render_pipeline( - &self, - compile: &metal2vulkan::device::Device, - key: &PipelineKey, - ) -> Option<(RenderPipeline, u64)> { - let bytes = self.entry(EntryKind::RenderPipeline, key.digest(), compile)?; - let pipeline = RenderPipeline::from_bytes_for_key(&bytes, key, compile).ok()?; - Some((pipeline, bytes.len() as u64)) - } - - /// The encoding of the artifact of `kind` under `key` for `compile`'s profile. - fn entry( - &self, - kind: EntryKind, - key: &Hash256, - compile: &metal2vulkan::device::Device, - ) -> Option> { - let place = Place::new(kind, *key, compile.profile_fingerprint()); - lock(&self.0.contents).entries.get(&place).cloned() - } - - /// The fingerprint of the device's profile. - fn profile(&self) -> Hash256 { - self.generation().compile_device().profile_fingerprint() - } - - /// Keep `used`, compiled for the profile of fingerprint `profile`, and the archive keys - /// `keys`. An artifact already held is not encoded again. - fn keep( - &self, - used: Vec, - profile: &Hash256, - keys: impl IntoIterator, - ) { - let mut contents = lock(&self.0.contents); - for artifact in used { - let (kind, artifact_key) = match &artifact { - Artifact::Function(function) => (EntryKind::Function, *function.key().digest()), - Artifact::Compute(pipeline) => { - (EntryKind::ComputePipeline, *pipeline.key().digest()) - } - Artifact::Render(pipeline) => (EntryKind::RenderPipeline, *pipeline.key().digest()), - }; - let place = Place::new(kind, artifact_key, *profile); - contents.entries.entry(place).or_insert_with(|| { - Arc::from(match &artifact { - Artifact::Function(function) => function.to_bytes(), - Artifact::Compute(pipeline) => pipeline.to_bytes(), - Artifact::Render(pipeline) => pipeline.to_bytes(), - }) - }); - } - contents.keys.extend(keys); - } -} - -/// Refuse a creation under `options` that lists another device's archive -/// (`Invalid(ForeignObject)` in `call`), or that fails on an archive miss and has a stage whose -/// archive key no listed archive holds: `missing` answers, from the device's profile and whether -/// a listed archive holds a key, the function of the first such stage, which the miss names with -/// the kind of `pipeline`. -pub(crate) fn check<'a>( - device: &Device, - options: &PipelineOptions, - call: &'static str, - pipeline: ArchivedPipeline, - missing: impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> Option<&'a StageSource>, -) -> Result<(), Error> { - let archives = &options.binary_archives; - if let Some(archive) = archives - .iter() - .find(|archive| !archive.root_device().same(device)) - { - return Err(archive.root_device().foreign(call, device)); - } - if archives.is_empty() - || !options - .options - .contains(PipelineOption::FAIL_ON_BINARY_ARCHIVE_MISS) - { - return Ok(()); - } - let held = |key: &Hash256| archives.iter().any(|archive| archive.holds(key)); - let Some(function) = missing(&device.compile_device().profile_fingerprint(), &held) else { - return Ok(()); - }; - let name = match function { - StageSource::Function(descriptor) => descriptor.function.info().name.to_string(), - StageSource::Compiled(compiled) => format!("{:?}", compiled.key()), - }; - Err(Error::BinaryArchiveMiss(BinaryArchiveMiss::new( - &name, pipeline, - ))) -} - -/// The kernel of a compute creation of `descriptor`, when no listed archive holds its key. -pub(crate) fn compute_missing<'a>( - descriptor: &'a ComputePipelineDescriptor, -) -> impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> Option<&'a StageSource> + 'a { - move |profile, held| { - (!held(&metal_key::compute(profile, descriptor))).then_some(&descriptor.kernel) - } -} - -/// The mesh function of a mesh creation of `descriptor`, when no listed archive holds its key. -pub(crate) fn mesh_missing<'a>( - descriptor: &'a MeshPipelineDescriptor, -) -> impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> Option<&'a StageSource> + 'a { - move |profile, held| (!held(&metal_key::mesh(profile, descriptor))).then_some(&descriptor.mesh) -} - -/// The tile function of a tile creation of `descriptor`, when no listed archive holds its key. -pub(crate) fn tile_missing<'a>( - descriptor: &'a TileRenderPipelineDescriptor, -) -> impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> Option<&'a StageSource> + 'a { - move |profile, held| (!held(&metal_key::tile(profile, descriptor))).then_some(&descriptor.tile) -} - -/// Whether a render creation of `descriptor` under `options`, which fails on an archive miss, -/// found both its stages' keys but not the two from one add: one add's vertex stage with another -/// add's fragment stage, under enabled rasterization. Metal's vertex key holds the vertex outputs -/// its compiler finds the fragment reading, which this lookup does not decode, so Metal misses -/// such a creation where the two fragments read different outputs (`metal_key`'s module docs). -pub(crate) fn combines_stages( - device: &Device, - options: &PipelineOptions, - descriptor: &RenderPipelineDescriptor, -) -> bool { - let archives = &options.binary_archives; - if archives.is_empty() - || !options - .options - .contains(PipelineOption::FAIL_ON_BINARY_ARCHIVE_MISS) - { - return false; - } - let held = |key: &Hash256| archives.iter().any(|archive| archive.holds(key)); - render_combined(descriptor)(&device.compile_device().profile_fingerprint(), &held) -} - -/// Whether a render lookup of `descriptor` found both its stages but no add's pair of them -/// ([`combines_stages`]); never for a creation without a fragment stage that reads. -pub(crate) fn render_combined( - descriptor: &RenderPipelineDescriptor, -) -> impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> bool + '_ { - move |profile, held| { - if descriptor.fragment.is_none() || !descriptor.rasterization_enabled { - return false; - } - let keys = metal_key::render(profile, descriptor); - let Some(kind) = keys.vertex.held(held) else { - return false; - }; - let found = keys - .fragment - .is_some_and(|fragment| held(&fragment.of(kind))); - found && keys.pair(kind).is_some_and(|pair| !held(&pair)) - } -} - -/// The function of the first stage of a render creation of `descriptor`, fragment then vertex, -/// whose key no listed archive holds (`metal_key`). An archive holds only the vertex key that -/// fits its function, so the one held says which of the fragment's keys to look for; with -/// neither held, the vertex misses, after the fragment if neither of its keys is held. -pub(crate) fn render_missing<'a>( - descriptor: &'a RenderPipelineDescriptor, -) -> impl FnOnce(&Hash256, &dyn Fn(&Hash256) -> bool) -> Option<&'a StageSource> + 'a { - move |profile, held| { - let keys = metal_key::render(profile, descriptor); - let vertex = keys.vertex.held(held); - if let (Some(fragment), Some(keys)) = (&descriptor.fragment, keys.fragment) { - let found = match vertex { - Some(kind) => held(&keys.of(kind)), - None => keys.held(held).is_some(), - }; - if !found { - return Some(fragment); - } - } - vertex.is_none().then_some(&descriptor.vertex) - } -} diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs deleted file mode 100644 index 1269e9d22..000000000 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ /dev/null @@ -1,4126 +0,0 @@ -//! From a dispatch's or draw's plan and commands to what the encoder records: the buffer descriptor -//! of every plan write, the command's own data in the command buffer's upload arena, the push holes -//! filled, and the uses the tracker orders. A compute encoder binds one stage's [`ArgumentTable`], -//! a render encoder its vertex and fragment stages'. -//! -//! - **Buffers** a slot binds take exactly their `DescriptorRange`. -//! - **Tables and blobs** (an argument table, a handle table, the constant blob) are uploaded -//! per command, padded to 16 bytes; a handle table is bound over exactly its planned length -//! (the shader counts its entries from the range). -//! - **Neutral buffers** are zero regions of the arena, fresh for each command, so a contained -//! store into a stand-in reaches nothing another command reads. -//! - **Root tables**, one per stage that reads one, are uploaded with a fresh sink's device address -//! in the sink entry; a stage's push holes take its root table's address and that of the command -//! buffer's execution status words, each hole in the stage's own push write. A flat variant's -//! dispatch takes the device address of the region record its preprocess writes -//! (`Tables::region_record`) in its `ReplayRegionAddress` hole. -//! - **Textures** a slot binds take the `VkImageView` the plan's view asks for (the texture's, -//! made at its first bind, `binding_view.rs`), in the `GENERAL` layout every runtime image -//! rests in; a draw's sampled binding of a texture its render pass instance renders takes the -//! texture's copy (`texture/attached_reads.rs`). **Samplers** take the `VkSampler` of their -//! state for the write's use and the bind's LOD clamps (`bind::sampler_desc`, `sampler.rs`), its -//! address modes mapped where the slot samples a texture of an address-mode map -//! (`address_map.rs`); a combined write checks the view format's filtering against it. A slot -//! with nothing bound takes the device's neutral image or sampler (`neutral.rs`). -//! - **Texture buffers** a slot binds take a texel buffer view of their buffer's bytes in the -//! format the plan names, over the range it gives (`buffer_texture.rs`); an unbound slot takes -//! the device's neutral texel buffer. -//! - **Tessellation factors** (a patch draw's control stage, `tessellation.rs`) take the -//! encoder's factor buffer over the range the plan gives, as a slot's buffer does. -//! - **Input attachments** (a draw's framebuffer fetch, `framebuffer_fetch.rs`) take the view of -//! the pass's color attachment of their index, the framebuffer's. **Storage attachments** (its -//! fetch in the pixel interlock) take a storage view of the attachment's level and layer, or of -//! its stand-in's (`attachment_stand_in.rs`). -//! - **The heap** (set 1): the device's heap set of the command's layout, which holds every live -//! texture at its resource ID and each array's neutral at element 0 (`heap_sets.rs`), so a heap -//! entry writes nothing: the texture it names (made resident, or bound at a slot) is checked as a -//! slot's view is, and nor does any other image element (an array's neutral where a member's -//! texture does not fit its class). It holds every live sampler state at its element too, so an -//! argument sampler writes nothing either. A texture handle table is the device's texture table -//! (`heap_sets::texture_table`), and a sampler table the device's sampler table of the layout's -//! kind (`heap_sets::sampler_table`), so a handle reaches every live texture and sampler state -//! by its ID as the command runs, as Metal's does. A draw whose caller keeps its heap part -//! (`render/heap_part.rs`) writes, after one draw checked each entry, only the plan's writes -//! past the heap's entries that draw listed ([`PastHeap`]). -//! - **Function tables** an argument buffer names: a set-1 element takes a listed table's words -//! buffer whole. On a device without the function-table array's features the stage's snapshot -//! takes the listed tables' words copied into the arena (`function_table.rs`), which the command -//! buffer copies again as it commits. -//! - Every other write source names a later step's resource and is refused, typed, before -//! anything is recorded. - -use std::cell::Cell; -use std::mem::MaybeUninit; - -use super::address_map::SamplerMaps; -use super::argument_table::{ArgumentTable, InlineBytes}; -use super::buffer::{Buffer, KeptSpaces}; -use super::command_buffer::{CommandBuffer, NotedTable, State}; -use super::degradation::EachWatch; -use super::device::lock; -use super::error::{internal, Error, RuntimeGap}; -use super::function_table::{self, TableSnapshot, VisibleFunctionTable}; -use super::heap_sets::{self, Keeper, SamplerTable, TextureTable, HEAP_SET}; -#[cfg(debug_assertions)] -use super::kept_checks::KeptChecks; -use super::key_hash::KeyMap; -use super::render_pass::{PassLayout, Target}; -use super::render_target; -use super::residency::{Residency, Used}; -use super::resource::ResourceKey; -use super::sampler::{HashedDesc, OwnedSampler, SamplerShared, SamplerState}; -use super::texture::{Texture, TextureShared}; -use super::tracker::{Access, Use, UseRange}; -use super::uniform_texels::UniformTexels; -use super::upload::Upload; -use super::Device; -use ash::vk; -use metal2vulkan::bind::{ - AccessClass, BindingPlan, BufferExtent, BufferRange, DescriptorBytes, DescriptorRange, - DescriptorWrite, FunctionTableWords, HeapElements, HeapSource, ImageSource, ImageViewDesc, - IndexBufferRef, NeutralResource, PushConstantWrite, PushHole, ResourceUse, RootTable, - SamplerDescriptor, SamplerSource, UseTarget, ViewSetup, WriteSource, -}; -use metal2vulkan::metal::format::writes_dropped; -use metal2vulkan::metal::sampler::{AddressModeMap, OpaqueBlackBorder, SamplerUse}; -use metal2vulkan::pipeline::{ - HandleClass, ImageAccess, SlotClass, SlotRef, Stage, StorageAttachmentView, Window, -}; -use std::collections::BTreeSet; -use std::ops::{Deref, Range}; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex, OnceLock, Weak}; - -/// What an encoder binds: each stage's argument table. -pub(super) struct Tables<'a> { - stages: &'a [(Stage, &'a ArgumentTable)], - /// The resources the encoder made resident, which the bind state lists as used. - residency: Option<&'a Residency>, - /// A render encoder's pass, whose attachments a draw's input and storage attachments read, - /// and the draw's views of its layers (`render_target::viewed`). - pass: Option<(&'a PassLayout, ViewSetup)>, - /// A draw's render pass instance's attachments: a sampled slot binding of a texture that - /// presents one of its color attachments takes the texture's copy - /// (`texture/attached_reads.rs`). - attached: Option<&'a PassLayout>, - /// The sampler states the bind state lists as argument samplers, in its order. - argument_samplers: &'a [SamplerState], - /// Where the plan's heap writes go, when the command writes a heap. - heap: Option<&'a HeapElements>, - /// The device's texture table, which the layout's texture handle tables bind. - texture_table: Option<&'a TextureTable<'a>>, - /// The device's sampler table, which the layout's sampler tables bind. - sampler_table: Option<&'a SamplerTable<'a>>, - /// The tables the bind state lists as function tables, in its order. - function_tables: &'a [VisibleFunctionTable], - /// A tile dispatch's scratch images, by color index, which its storage attachments read and - /// write in place of the pass's attachments (`render/tile_dispatch.rs`). - tile_scratch: Option<&'a [(u32, Target)]>, - /// The storage view of a render encoder's shader-side stencil's shadow, when the draw tests - /// the stencil in the shader (`shadow_stencil.rs`): its returned `[[stencil]]`, or, as the - /// stencil's stand-in, the draw's stencil test. - shadow: Option, - /// The storage view of a render encoder's depth stand-in, when the draw tests the depth in - /// the shader (`depth_stand_in.rs`). - depth_stand_in: Option, - /// The storage views of the `half` shadows a render encoder's current instance holds of - /// its extended-range colors, by color index (`render/extended_shadow.rs`). - extended_shadows: Vec<(u32, vk::ImageView)>, - /// A render encoder's tessellation factor buffer and its offset, when it set one - /// (`tessellation.rs`). - factors: Option<(&'a Buffer, u64)>, - /// The storage view of a render encoder's fragment imageblock storage, when the draw's - /// fragment function declares an explicit imageblock (`fragment_imageblock.rs`). - imageblock: Option, - /// The device address of the 32-byte region record a flat variant's dispatch reads, when - /// the command is one (`BindingPlan::instantiate_dispatch` of a flat plan): a region of the - /// command buffer's upload arena (`upload.rs`), with the dispatch's - /// `VkDispatchIndirectCommand` beside it, which a single-dispatch preprocess writes on the - /// device before the dispatch. Its `PushHole::ReplayRegionAddress` takes it. - pub(super) region_record: Option, - /// A patch draw's patch index buffer and its offset, when the draw has one. - patch_indices: Option<(&'a Buffer, u64)>, - /// An indexed patch draw's control-point index buffer and its offset. - control_point_indices: Option<(&'a Buffer, u64)>, - /// A render pass's tile threadgroup memory, when a tile dispatch's function reads it - /// (`render/tile_memory.rs`). - tile_memory: Option<&'a Buffer>, - /// The address-mode maps the command's runtime samplers are bound with (`address_map.rs`). - sampler_maps: SamplerMaps, - /// A de-indexed draw's first index's address (`VariantKey::primitive_id_indices`): its - /// `PushHole::CaptureIndexAddress` takes it. - indices: Option, - /// A draw's slots read through snapshots (`render/snapshot.rs`): each binds its own texture, - /// not a copy, in the feedback loop layout, and its snapshot at `WriteSource::SnapshotTexels`. - snapshots: Option<&'a SnapshotViews>, - /// A merged draw replay's header's address (`render/executions/gpu.rs`): its vertex - /// function's `PushHole::MergedDrawAddress` takes it. - merged_header: Option, - /// A draw's sampled slots that read the levels of their texture's own image apart from the - /// attached ones, in place of its copy (`render/attached_levels.rs`). - narrowed: Option<&'a NarrowedSlots>, - /// The texture and buffer slots the command reads through read twins, in place of what they - /// bind (`read_twin.rs`, [`TwinSlots`]). - twins: Option<&'a TwinSlots>, -} - -/// The slots a command reads through read twins (`read_twin.rs`), each bound in place of what -/// the slot binds where the command only reads it: at a texture slot, the runtime's texture over a -/// no-copy buffer's pages in place, made for the program's texture over the buffer's copy; at a -/// buffer slot, the buffer's own read twin, at the slot's offset. -pub(super) struct TwinSlots { - textures: Vec<(SlotRef, Texture)>, - buffers: Vec<(SlotRef, (Buffer, u64))>, -} - -impl TwinProofs { - /// The slots of `tables` that the command of `plan`, whose proofs these keep, and its own - /// uses `command_uses`, which reaches memory through a root table where `roots`, reads - /// through read twins, in `command_buffer` (`None` where none is): - /// - /// - each texture slot whose every use only reads, as a sampled or storage image (proven - /// from lowering: an unknown access is a write), and whose every descriptor is that image, - /// with no element of the heap, texel buffer or plane of it; not read through a snapshot, - /// narrowed to levels, nor presenting an attachment of the draw's instance; whose texture - /// has a read twin that serves each such binding with no shadow of its usage, and whose - /// bytes no earlier command of the command buffer may have written (`Texture::read_twin`); - /// - each buffer slot of a command that reaches no memory through a root table (so no address - /// of the slot's buffer reaches its functions), whose every use only reads, as a storage or - /// uniform buffer (proven from lowering, writes through the slot's escaped address among - /// them), and whose every descriptor is that buffer's, none a vertex buffer of it; whose - /// buffer has a read twin at its own base, and whose copy no earlier command of the command - /// buffer may have written (`Buffer::slot_twin`). - /// - /// A command's own uses name no slot (its index buffer, indirect arguments and the like), so - /// the proofs are the plan's alone. - pub(super) fn slots( - &self, - command_buffer: &CommandBuffer, - (plan, command_uses, roots): (&BindingPlan, &[ResourceUse], bool), - tables: &Tables<'_>, - ) -> Option { - if !crate::read_twin::twinned(command_buffer) { - return None; - } - debug_assert!( - !command_uses.iter().any(names_slot), - "a command's own use of a slot, which its plan's twin proofs leave out" - ); - let unproven = crate::read_twin::binds_unproven(command_buffer.generation()); - // A test's device that binds twins at slots it may write: proven so at each command. - let fresh; - let proven = match unproven { - true => { - fresh = TwinProofs::proven(plan, true); - &fresh[..] - } - false => self.of(plan), - }; - let mut textures = Vec::new(); - let mut buffers = Vec::new(); - for &(slot, proof) in proven { - match proof { - Proven::Buffer => { - if roots { - continue; - } - let Some((buffer, offset)) = stage_buffer(tables.stages, slot) else { - continue; - }; - if let Some(twin) = buffer.slot_twin(command_buffer) { - buffers.push((slot, (twin, *offset))); - } - } - Proven::Texture(kinds) => { - let Some(texture) = tables - .of(slot.stage) - .and_then(|t| t.textures.get(&slot.index)) - else { - continue; - }; - let apart = tables.snapshot_slot(slot) - || (tables.narrowed).is_some_and(|n| n.levels(slot).is_some()) - || (tables.attached).is_some_and(|instance| texture.attached_in(instance)); - if apart { - continue; - } - if let Some(twin) = texture.read_twin(command_buffer, kinds) { - textures.push((slot, twin)); - } - } - } - } - let any = !textures.is_empty() || !buffers.is_empty(); - any.then_some(TwinSlots { textures, buffers }) - } -} - -impl TwinSlots { - /// The read twin bound at texture slot `slot`, where the command reads it so. - fn texture(&self, slot: SlotRef) -> Option<&Texture> { - let found = self.textures.iter().find(|(at, _)| *at == slot); - found.map(|(_, twin)| twin) - } - - /// The read twin bound at buffer slot `slot`, with the slot's offset, where the command - /// reads it so. - fn buffer(&self, slot: SlotRef) -> Option<&(Buffer, u64)> { - let found = self.buffers.iter().find(|(at, _)| *at == slot); - found.map(|(_, twin)| twin) - } -} - -/// Whether `used` names a slot: the resource bound there, or its tile map. -fn names_slot(used: &ResourceUse) -> bool { - matches!(used.resource, UseTarget::Slot(_) | UseTarget::TileMap(_)) -} - -/// The slots of a plan whose commands may read them through read twins, as -/// [`slots`](TwinProofs::slots) proves them, each with the kinds of its bindings where it is a -/// texture's: the plan's alone, as no command's own use names a slot. A plan's uses and -/// descriptor writes number one for each resource its heap reaches (every texture an encoder made -/// resident, in each heap array), and the proofs walk them for each slot, so they are worked out -/// once for the plan, the first time a command of it asks on a device with read twins, and kept -/// with its other facts: a draw's with its plan's (`render/plan_facts.rs`), a dispatch's with what -/// it planned (`pipeline::Planned`). -#[derive(Default)] -pub(super) struct TwinProofs(OnceLock>); - -/// A slot [`TwinProofs`] proved a command of its plan only reads. -#[derive(Clone, Copy)] -enum Proven { - /// A buffer slot, as a storage or uniform buffer. - Buffer, - /// A texture slot, as images of these kinds. - Texture(TwinKinds), -} - -impl TwinProofs { - /// The proofs of `plan`, the plan these were kept for: worked out the first time. - fn of(&self, plan: &BindingPlan) -> &[(SlotRef, Proven)] { - self.0.get_or_init(|| TwinProofs::proven(plan, false)) - } - - /// The slots of `plan` a command of it only reads, each once, in the order of its uses, as - /// [`read_only_buffer_slot`] and [`read_only_slot`] prove them under `unproven`. - fn proven(plan: &BindingPlan, unproven: bool) -> Vec<(SlotRef, Proven)> { - #[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] - PLAN_WALKS.with(|walks| walks.set(walks.get() + plan.uses.len() as u64)); - let mut seen: Vec = Vec::new(); - let mut proven = Vec::new(); - for used in &plan.uses { - let UseTarget::Slot(slot) = used.resource else { - continue; - }; - if seen.contains(&slot) { - continue; - } - seen.push(slot); - let proof = match slot.class { - SlotClass::Buffer => { - read_only_buffer_slot(slot, plan, unproven).then_some(Proven::Buffer) - } - SlotClass::Texture => read_only_slot(slot, plan, unproven).map(Proven::Texture), - _ => None, - }; - if let Some(proof) = proof { - proven.push((slot, proof)); - } - } - proven - } -} - -/// Whether every use of buffer slot `slot` by a command of `plan` only reads it, as a storage or -/// uniform buffer, and every descriptor of the plan that names the slot is its buffer's, none of -/// it a vertex buffer. -fn read_only_buffer_slot(slot: SlotRef, plan: &BindingPlan, unproven: bool) -> bool { - #[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] - PLAN_WALKS.with(|walks| { - let walked = plan.uses.len() + plan.descriptors.len(); - walks.set(walks.get() + walked as u64) - }); - let mut read = unproven; - for used in &plan.uses { - if used.resource != UseTarget::Slot(slot) { - continue; - } - let buffer = matches!(used.class, AccessClass::Storage | AccessClass::Uniform); - if (used.access.write && !unproven) || !buffer { - return false; - } - read |= used.access.read; - } - let vertex = (plan.vertex_buffers.iter()) - .any(|bind| slot.stage == Stage::Vertex && bind.buffer_index == slot.index); - let named = |write: &&DescriptorWrite| match &write.source { - WriteSource::Buffer { slot: at } | WriteSource::InlineBytes { slot: at } => *at == slot, - _ => false, - }; - let buffers = plan.descriptors.iter().filter(named).all(|write| { - let ty: vk::DescriptorType = write.ty.into(); - matches!(write.source, WriteSource::Buffer { .. }) - && matches!( - ty, - vk::DescriptorType::STORAGE_BUFFER - | vk::DescriptorType::STORAGE_BUFFER_DYNAMIC - | vk::DescriptorType::UNIFORM_BUFFER - | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC - ) - }); - read && !vertex && buffers -} - -/// Where every use of texture slot `slot` by a command of `plan` only reads it, as a sampled or -/// storage image, and every descriptor of the plan that names the slot is that image (a -/// texture's or a combined image sampler's): the kinds of its bindings, a storage image's and a -/// sampled one's ([`TwinKinds`]); else `None`. -fn read_only_slot(slot: SlotRef, plan: &BindingPlan, unproven: bool) -> Option { - #[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] - PLAN_WALKS.with(|walks| { - let walked = plan.uses.len() + plan.descriptors.len(); - walks.set(walks.get() + walked as u64) - }); - let mut read = unproven; - for used in &plan.uses { - let named = match used.resource { - UseTarget::Slot(at) | UseTarget::TileMap(at) => at == slot, - _ => false, - }; - if !named { - continue; - } - let image = matches!(used.class, AccessClass::Sampled | AccessClass::StorageImage); - let writes = used.access.write && !unproven; - if writes || !image || matches!(used.resource, UseTarget::TileMap(_)) { - return None; - } - read |= used.access.read; - } - let mut kinds = TwinKinds::default(); - for write in &plan.descriptors { - // The slot's own descriptors: `Some(true)` an image of it, `Some(false)` any other - // binding of it; another slot's, `None`. - let named = match &write.source { - WriteSource::Texture { slot: at, .. } => (*at == slot).then_some(true), - WriteSource::CombinedImageSampler { - image: ImageSource::Texture { slot: at, .. }, - .. - } => (*at == slot).then_some(true), - WriteSource::YCbCrInPlace { slot: at } - | WriteSource::YCbCrPlanesImage { slot: at } - | WriteSource::TexelRows { slot: at, .. } - | WriteSource::TexelBuffer { slot: at, .. } - | WriteSource::HeapEntry { - source: HeapSource::Bound(at), - .. - } => (*at == slot).then_some(false), - _ => None, - }; - let ty: vk::DescriptorType = write.ty.into(); - match named { - Some(true) if ty == vk::DescriptorType::STORAGE_IMAGE => kinds.storage = true, - Some(true) => kinds.sampled = true, - Some(false) => return None, - None => {} - } - } - (read && (kinds.storage || kinds.sampled)).then_some(kinds) -} - -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -thread_local! { - /// The uses and descriptor writes of plans this thread walked for facts of a plan alone - /// ([`binds_own_zeros`], [`TwinProofs`]), in the device tests that read it - /// (`tests::resident_uses`). - static PLAN_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// How many uses and descriptor writes of plans this thread walked so far for facts of a plan -/// alone ([`binds_own_zeros`], [`TwinProofs`]). -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn plan_walks() -> u64 { - PLAN_WALKS.with(std::cell::Cell::get) -} - -/// The kinds of a texture slot's bindings ([`read_only_slot`]): whether one is a storage image, -/// and whether one is sampled. -#[derive(Clone, Copy, Default)] -pub(super) struct TwinKinds { - pub(super) storage: bool, - pub(super) sampled: bool, -} - -/// The levels a narrowed slot reads of its texture's own image (`NarrowedSlots`), counted from -/// the texture's own first level: its view holds `0..view`, and its reads reach `first..view`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct NarrowedLevels { - pub(super) first: u32, - pub(super) view: u32, -} - -/// The sampled texture slots of a draw narrowed to the levels of their texture's own image apart -/// from those its render pass instance renders (`render/attached_levels.rs`): each binds the image -/// through a view of its levels `0..view`, counted from the texture's own first level, and names -/// the levels its reads reach in its uses, in place of the texture's copy -/// (`texture/attached_reads.rs`). Once withdrawn, every slot binds as it would without them: its -/// copy. -#[derive(Default)] -pub(super) struct NarrowedSlots { - /// Each slot, its levels, its use of them, and the colors of the instance that render levels - /// its view holds (bit `i` for color `i`). - slots: Vec<(SlotRef, NarrowedLevels, Use, u32)>, - withdrawn: Cell, -} - -impl NarrowedSlots { - /// Narrow `slot` to its texture's levels `levels`, whose use `used` names those its reads - /// reach, past the attached levels of the colors `spanned` where its view holds them. - pub(super) fn narrow( - &mut self, - slot: SlotRef, - levels: NarrowedLevels, - used: Use, - spanned: u32, - ) { - self.slots.push((slot, levels, used, spanned)); - } - - /// The levels `slot` is narrowed to, where it is and they are not withdrawn. - fn levels(&self, slot: SlotRef) -> Option { - if self.withdrawn.get() { - return None; - } - (self.slots.iter()) - .find(|(narrowed, ..)| *narrowed == slot) - .map(|&(_, levels, ..)| levels) - } - - /// The colors of the instance whose attached levels the slots' views hold, none once - /// withdrawn: the instance must hold them in `GENERAL`, the layout the views' descriptors name - /// (`render/attached_levels.rs`). - pub(super) fn spanned(&self) -> u32 { - match self.withdrawn.get() { - true => 0, - false => (self.slots.iter()).fold(0, |colors, &(.., spanned)| colors | spanned), - } - } - - /// How many slots are narrowed to levels before the attached ones, and how many to levels - /// past them, withdrawn or not. - pub(super) fn kinds(&self) -> (usize, usize) { - let past = (self.slots.iter()) - .filter(|(_, levels, ..)| levels.first > 0) - .count(); - (self.slots.len() - past, past) - } - - /// How many slots are narrowed, none once withdrawn. - pub(super) fn len(&self) -> usize { - match self.withdrawn.get() { - true => 0, - false => self.slots.len(), - } - } - - /// The narrowed slots and their levels, in the order they were narrowed; none once withdrawn. - pub(super) fn listed(&self) -> impl Iterator + '_ { - let withdrawn = self.withdrawn.get(); - (self.slots.iter()) - .filter(move |_| !withdrawn) - .map(|&(slot, levels, ..)| (slot, levels)) - } - - /// Whether a write among `uses` meets the levels a narrowed slot reads: their memory - /// (`UseRange::shares_memory`, so a write of another texture placed in the same heap apart - /// from them meets none). - pub(super) fn written_by(&self, uses: &[Use]) -> bool { - (self.slots.iter()).any(|(.., narrowed, _)| { - (uses.iter()).any(|used| { - !used.write.is_empty() - && used.key == narrowed.key - && used.range.shares_memory(&narrowed.range) - }) - }) - } - - /// Bind every slot as it would without these: through its copy. - pub(super) fn withdraw(&self) { - self.withdrawn.set(true); - } -} - -/// The fragment texture slots a draw reads through snapshots, and the storage view of each one's -/// snapshot (`render/snapshot.rs`, `Texture::snapshot_texels`). -pub(super) struct SnapshotViews { - pub(super) slots: BTreeSet, - pub(super) views: Vec<(u32, vk::ImageView)>, - /// The slots' textures are in the feedback loop layout where the draw reads them; else in - /// `GENERAL`, read by snapshots that lead the draw's instance (`render/snapshot.rs`, leading - /// snapshots). - pub(super) feedback: bool, -} - -impl<'a> Tables<'a> { - /// The tables of `stages`. - pub(super) fn new(stages: &'a [(Stage, &'a ArgumentTable)]) -> Tables<'a> { - Tables { - stages, - residency: None, - pass: None, - attached: None, - argument_samplers: &[], - heap: None, - texture_table: None, - sampler_table: None, - function_tables: &[], - tile_scratch: None, - shadow: None, - depth_stand_in: None, - extended_shadows: Vec::new(), - factors: None, - imageblock: None, - region_record: None, - patch_indices: None, - control_point_indices: None, - tile_memory: None, - sampler_maps: SamplerMaps::default(), - indices: None, - snapshots: None, - merged_header: None, - narrowed: None, - twins: None, - } - } - - /// The tables, with the texture slots the command reads through their textures' read twins - /// (`read_twin.rs`). - pub(super) fn with_twins(self, twins: &'a TwinSlots) -> Tables<'a> { - Tables { - twins: Some(twins), - ..self - } - } - - /// The tables, with a draw's slots read through snapshots and their snapshots' views - /// (`render/snapshot.rs`). - pub(super) fn with_snapshots(self, snapshots: &'a SnapshotViews) -> Tables<'a> { - Tables { - snapshots: Some(snapshots), - ..self - } - } - - /// The tables, with the draw's slots narrowed to the levels apart from the attached ones - /// (`Tables::narrowed`). - pub(super) fn with_narrowed(self, narrowed: &'a NarrowedSlots) -> Tables<'a> { - Tables { - narrowed: Some(narrowed), - ..self - } - } - - /// How a slot binding of `texture` at `slot`, of the kind `storage`, reads it: through a view - /// of its own image where the slot is narrowed to levels apart from the attached ones (a - /// sampled binding alone), else through its copy where it presents an attachment of the draw's - /// instance and the slot reads no snapshot, else its own image. - fn slot_read(&self, texture: &Texture, slot: SlotRef, storage: bool) -> SlotRead { - let narrowed = (self.narrowed.filter(|_| !storage)).and_then(|n| n.levels(slot)); - match narrowed { - Some(levels) => SlotRead::Levels(levels), - None if self.attached(texture, storage) && !self.snapshot_slot(slot) => SlotRead::Copy, - None => SlotRead::Own, - } - } - - /// Whether `slot` is one a draw reads through a snapshot: its binding takes the texture - /// itself, never its copy. - fn snapshot_slot(&self, slot: SlotRef) -> bool { - slot.stage == Stage::Fragment - && slot.class == SlotClass::Texture - && self - .snapshots - .is_some_and(|s| s.slots.contains(&slot.index)) - } - - /// Whether `slot` is one a draw reads through a snapshot whose texture is in the feedback - /// loop layout where the draw reads it ([`SnapshotViews::feedback`]). - fn feedback_slot(&self, slot: SlotRef) -> bool { - self.snapshot_slot(slot) && self.snapshots.is_some_and(|s| s.feedback) - } - - /// The tables, with a merged draw replay's header's address (`Tables::merged_header`). - pub(super) fn with_merged_header(self, address: u64) -> Tables<'a> { - Tables { - merged_header: Some(address), - ..self - } - } - - /// The tables, with a de-indexed draw's first index's address (`Tables::indices`). - pub(super) fn with_indices(self, address: u64) -> Tables<'a> { - Tables { - indices: Some(address), - ..self - } - } - - /// The tables, with the address-mode maps the command's runtime samplers are bound with, - /// the bind state's (`address_map::sampler_maps`). - pub(super) fn with_sampler_maps(self, maps: SamplerMaps) -> Tables<'a> { - Tables { - sampler_maps: maps, - ..self - } - } - - /// The tables, with a tile dispatch's `scratch` images by color index. - pub(super) fn with_tile_scratch(self, scratch: &'a [(u32, Target)]) -> Tables<'a> { - Tables { - tile_scratch: Some(scratch), - ..self - } - } - - /// The tables, with the render encoder's `pass` and the draw's `views` of its layers. - pub(super) fn with_pass(self, pass: &'a PassLayout, views: ViewSetup) -> Tables<'a> { - Tables { - pass: Some((pass, views)), - ..self - } - } - - /// The tables, with a draw's render pass instance of `instance`'s attachments: a sampled slot - /// binding of a texture that presents one of its color attachments takes the texture's copy - /// (`texture/attached_reads.rs`). - pub(super) fn with_attachments(self, instance: &'a PassLayout) -> Tables<'a> { - Tables { - attached: Some(instance), - ..self - } - } - - /// Whether a slot binding of `texture` of the kind `storage` reads it where the draw's - /// instance renders it: a sampled one of a texture that presents one of its color - /// attachments (`texture/attached_reads.rs`). - fn attached(&self, texture: &Texture, storage: bool) -> bool { - !storage - && self - .attached - .is_some_and(|instance| texture.attached_in(instance)) - } - - /// The tables, with the storage view of the shader-side stencil's `shadow`. - pub(super) fn with_shadow(self, shadow: vk::ImageView) -> Tables<'a> { - Tables { - shadow: Some(shadow), - ..self - } - } - - /// The tables, with the storage view of the depth stand-in `stand_in`. - pub(super) fn with_depth_stand_in(self, stand_in: vk::ImageView) -> Tables<'a> { - Tables { - depth_stand_in: Some(stand_in), - ..self - } - } - - /// The tables, with the storage views of the extended-range colors' `half` `shadows`, by - /// color index. - pub(super) fn with_extended_shadows(self, shadows: Vec<(u32, vk::ImageView)>) -> Tables<'a> { - Tables { - extended_shadows: shadows, - ..self - } - } - - /// The tables, with the render encoder's tessellation factor buffer and its offset. - pub(super) fn with_factors(self, buffer: &'a Buffer, offset: u64) -> Tables<'a> { - Tables { - factors: Some((buffer, offset)), - ..self - } - } - - /// The tables, with a patch draw's patch index buffer and its offset. - pub(super) fn with_patch_indices(self, buffer: &'a Buffer, offset: u64) -> Tables<'a> { - Tables { - patch_indices: Some((buffer, offset)), - ..self - } - } - - /// The tables, with an indexed patch draw's control-point index buffer and its offset. - pub(super) fn with_control_point_indices(self, buffer: &'a Buffer, offset: u64) -> Tables<'a> { - Tables { - control_point_indices: Some((buffer, offset)), - ..self - } - } - - /// The tables, with the render pass's tile threadgroup memory. - pub(super) fn with_tile_memory(self, buffer: &'a Buffer) -> Tables<'a> { - Tables { - tile_memory: Some(buffer), - ..self - } - } - - /// The tables, with the storage view of the fragment imageblock's storage. - pub(super) fn with_imageblock(self, imageblock: vk::ImageView) -> Tables<'a> { - Tables { - imageblock: Some(imageblock), - ..self - } - } - - /// The tables, with the sampler states the bind state lists as argument samplers and where - /// the plan's heap writes go. - pub(super) fn with_heap( - self, - samplers: &'a [SamplerState], - heap: &'a HeapElements, - ) -> Tables<'a> { - Tables { - argument_samplers: samplers, - heap: Some(heap), - ..self - } - } - - /// The tables, with the device's texture table at the layout's texture handle tables. - pub(super) fn with_texture_table(self, table: Option<&'a TextureTable<'a>>) -> Tables<'a> { - Tables { - texture_table: table, - ..self - } - } - - /// The tables, with the device's sampler table at the layout's sampler tables. - pub(super) fn with_sampler_table(self, table: Option<&'a SamplerTable<'a>>) -> Tables<'a> { - Tables { - sampler_table: table, - ..self - } - } - - /// The tables, with the visible-function tables the bind state lists as function tables. - pub(super) fn with_function_tables(self, tables: &'a [VisibleFunctionTable]) -> Tables<'a> { - Tables { - function_tables: tables, - ..self - } - } - - /// The tables, with the resources the encoder made resident (`use_resource(s)`). - pub(super) fn with_residency(self, residency: &'a Residency) -> Tables<'a> { - Tables { - residency: Some(residency), - ..self - } - } - - /// The resource the encoder made resident under `token`. - fn used(&self, token: u32) -> Option<&'a Used> { - self.residency?.get(token) - } - - /// The pixel format the texture bound at texture slot `slot` presents to the slot's binding, - /// if one is bound (`Texture::bound_pixel_format`): the format whose texels the slot reads, - /// which a specialized notice tests and names (`Device::degrade_specialized`). - pub(super) fn bound_format(&self, slot: SlotRef) -> Option { - slot_texture(self, slot).map(Texture::bound_pixel_format) - } - - /// The table of `stage`, if the encoder has one. - fn of(&self, stage: Stage) -> Option<&'a ArgumentTable> { - self.stages - .iter() - .find(|(of, _)| *of == stage) - .map(|&(_, table)| table) - } -} - -/// What one command's instantiation gives the binder, a dispatch's or a draw's alike. -pub(super) struct Command<'a> { - pub(super) descriptor_bytes: &'a [DescriptorBytes], - /// The plan's heap tables, where its caller keeps them apart from the command's other - /// descriptor bytes (`BindingPlan::heap_tables_into`, `render/heap_part.rs`): empty where - /// they are among those. - pub(super) heap_tables: &'a [DescriptorBytes], - pub(super) descriptor_ranges: &'a [DescriptorRange], - /// The windows of its bound buffers' slots (`metal2vulkan::bind::BufferExtent`), which the - /// counts of uniform views by window read (`WorkCounts::uniform_buffers_bound_to_16k`). - pub(super) extents: &'a [BufferExtent], - /// Each stage's root table, by the stages its push hole names. - pub(super) root_tables: Vec<(metal2vulkan::vk::ShaderStageFlags, &'a RootTable)>, - /// Whether a function that reads one of them may write memory (stores or atomic updates, - /// `StageInterface::writes_memory`): where none does, nothing writes memory through them - /// (`State::writes_unnamed`). - pub(super) root_writes: bool, - pub(super) push_holes: &'a [PushHole], - /// The command's own resources beyond the plan's uses (an index buffer, indirect arguments). - pub(super) uses: &'a [ResourceUse], - /// Each Metal stage's constant blob, for its `ConstantBlob` write. - pub(super) blobs: Vec<(Stage, &'a Arc<[u8]>)>, - /// An emulated mesh draw's work buffer and records, for its `MeshWork` and `MeshRecords` - /// writes. - pub(super) mesh: Option, - /// An emulated tessellation draw's work buffer and records, for its `TessellationWork` and - /// `TessellationRecords` writes. - pub(super) tessellation: Option, - /// A fan-out draw's region table and a probe's flags (`render/fan_out.rs`), for its - /// `RateMapRegions` and `RateMapFlags` writes. - pub(super) fan_out: Option, -} - -/// Where a fan-out draw's region table and a probe's flags lie (`render/fan_out.rs`), each bound -/// whole. -#[derive(Clone, Copy)] -pub(super) struct FanOutBuffers { - pub(super) regions: vk::DescriptorBufferInfo, - /// A probe's flags; `None` for a draw. - pub(super) flags: Option, -} - -/// Where an emulated mesh or tessellation draw's work buffer and records lie (`render/mesh.rs`, -/// `render/tessellation_scan.rs`), each bound whole. -#[derive(Clone, Copy)] -pub(super) struct MeshRegions { - pub(super) work: vk::DescriptorBufferInfo, - pub(super) records: vk::DescriptorBufferInfo, -} - -/// The descriptor of a sampler `state` bound with `clamps`: the state's, its LOD clamps replaced -/// by the bind's when it set them, as plain Metal samples with them -/// ([`metal_lod_clamps`](super::sampler::metal_lod_clamps): inverted ones read the upper clamp's -/// level). -pub(super) fn bound_sampler(state: &SamplerState, clamps: Option<[f32; 2]>) -> SamplerDescriptor { - let mut descriptor = *state.descriptor(); - if let Some(clamps) = clamps { - [descriptor.lod_min_clamp, descriptor.lod_max_clamp] = - super::sampler::metal_lod_clamps(clamps); - } - descriptor -} - -/// The type a set-0 binding of `ty` takes where its variant makes it dynamic -/// (`objects::dynamic_bindings`): a uniform or storage buffer's dynamic type. -pub(crate) fn dynamic_type(ty: vk::DescriptorType) -> vk::DescriptorType { - match ty { - vk::DescriptorType::UNIFORM_BUFFER => vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC, - vk::DescriptorType::STORAGE_BUFFER => vk::DescriptorType::STORAGE_BUFFER_DYNAMIC, - ty => ty, - } -} - -/// Make the descriptors `writes` holds for the set-0 bindings numbered in `dynamic` (a variant's, -/// ascending: `VariantObjects::dynamic_bindings`) dynamic, and their offsets `offsets`, one per -/// binding in that order, as `vkCmdBindDescriptorSets` takes them ("ordered by the binding -/// numbers in the descriptor set layouts"): each such write of its dynamic type at offset 0, its -/// offset the binding's dynamic offset. The effective offset is "the sum of the dynamic offset -/// and the offset" of the descriptor (`VkDescriptorBufferInfo`), its range unchanged: each -/// command reaches the bytes it reached through the static descriptor, and the set holds the same -/// descriptors whatever the offsets. Valid as the static one: a dynamic offset must be a multiple -/// of the binding's `min*BufferOffsetAlignment`, as a static descriptor's offset must, and offset -/// and range within the buffer likewise. An offset past 32 bits stays in its descriptor, its -/// dynamic offset 0; a binding no write names takes 0. -pub(super) fn dynamic_writes(writes: &mut [Write], dynamic: &[u32], offsets: &mut Vec) { - offsets.clear(); - offsets.resize(dynamic.len(), 0); - if dynamic.is_empty() { - return; - } - for write in writes.iter_mut() { - dynamic_write(write, dynamic, offsets); - } -} - -/// [`dynamic_writes`]' work on one write, where it is set 0's at a binding `dynamic` numbers: -/// made dynamic, its offset its binding's in `offsets`. -fn dynamic_write(write: &mut Write, dynamic: &[u32], offsets: &mut [u32]) { - if write.set != 0 { - return; - } - let (Ok(at), Info::Buffer(info)) = (dynamic.binary_search(&write.binding), &mut write.info) - else { - return; - }; - write.ty = dynamic_type(write.ty); - offsets[at] = 0; - if let Ok(offset) = u32::try_from(info.offset) { - offsets[at] = offset; - info.offset = 0; - } -} - -/// Write again, over `writes` and `offsets` (a command's set-0 writes and dynamic offsets as -/// [`bind_into`] and [`dynamic_writes`] made them, for a variant of the dynamic bindings -/// `dynamic`), the descriptors of the plan's writes from the buffer, texture and sampler slots -/// `slots`, which the command's tables now bind otherwise (another buffer, offset or bytes, another -/// texture or sampler state, the shape the same), with `command`'s ranges for the buffers: the -/// writes and offsets [`bind_into`] and [`dynamic_writes`] make for the tables now, each image -/// descriptor's sampler kept in `samplers` (emptied first) as [`bind_into`] keeps it, through -/// `memo` likewise. Its buffers' descriptors take nothing of the command buffer's state -/// ([`slot_descriptor`]), so it locks none. `Ok(false)` where a write of theirs is not at its -/// place among `writes` (a heap's, which skips writes), holds a keeper, reads a changed slot -/// otherwise (a texel buffer, a YCbCr texture's planes, an argument sampler), or is a uniform -/// view's texel form of a changed or unbound slot, whose view its command buffer made for it -/// ([`written`]): the caller binds whole. -pub(super) fn rebind_into( - call: &'static str, - device: &Device, - (plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>), - slots: &[SlotRef], - (writes, dynamic, offsets): (&mut [Write], &[u32], &mut [u32]), - (mut memo, samplers): (Option<&mut BindMemo>, &mut Vec>), -) -> Result { - samplers.clear(); - if tables.heap.is_some() || writes.len() != plan.descriptors.len() { - return Ok(false); - } - let changed = |slot: &SlotRef| slots.contains(slot); - for (write, planned) in writes.iter_mut().zip(&plan.descriptors) { - // Whether its descriptor is a buffer's or an image's of a changed slot. - let buffer = match &planned.source { - WriteSource::Buffer { slot } | WriteSource::InlineBytes { slot } => { - if !changed(slot) { - continue; - } - true - } - WriteSource::Texture { slot, .. } | WriteSource::Sampler { slot, .. } => { - if !changed(slot) { - continue; - } - false - } - // A fragment texture slot read through a snapshot binds its snapshot beside its - // texture (`render/snapshot.rs`): the changed texture's, through the tables' - // snapshots. - &WriteSource::SnapshotTexels { slot } => { - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: slot, - }; - if !changed(&slot) { - continue; - } - false - } - WriteSource::CombinedImageSampler { image, sampler } => { - let image = match image { - ImageSource::Texture { slot, .. } => changed(slot), - ImageSource::Neutral(_) => false, - }; - let sampler = match sampler { - SamplerSource::Slot { slot, .. } => changed(slot), - SamplerSource::Immutable | SamplerSource::Neutral(_) => false, - }; - if !image && !sampler { - continue; - } - false - } - // A slot's other reads: a changed one's are its caller's to bind whole. - WriteSource::TexelBuffer { slot, .. } - | WriteSource::YCbCrInPlace { slot } - | WriteSource::YCbCrPlanesImage { slot } - | WriteSource::TexelRows { slot, .. } - if changed(slot) => - { - return Ok(false) - } - WriteSource::ArgumentSampler { .. } - if slots.iter().any(|slot| slot.class == SlotClass::Sampler) => - { - return Ok(false) - } - // An unbound slot's uniform view in its texel form names a view of the zero buffer - // made for the write, which its command buffer holds ([`written`]), and a draw carried - // past the commit must name none: bound whole. - WriteSource::Neutral( - NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. }, - ) if vk::DescriptorType::from(planned.ty) - == vk::DescriptorType::UNIFORM_TEXEL_BUFFER => - { - return Ok(false) - } - _ => continue, - }; - let ty: vk::DescriptorType = planned.ty.into(); - let place = (write.set, write.binding, write.element); - if place != (planned.set, planned.binding, planned.array_element) || write.held.is_some() { - return Ok(false); - } - // A changed slot's uniform view in its texel form takes a view made for its write, which - // the command buffer holds ([`written`]): bound whole. - if ty == vk::DescriptorType::UNIFORM_TEXEL_BUFFER { - return Ok(false); - } - let info = match buffer { - true => { - let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces); - match slot_descriptor(command, tables, planned, spaces)? { - Some(info) => { - count_uniform_buffer(device, command, planned, ty); - Info::Buffer(info) - } - None => return Err(internal("a slot's buffer write of another source")), - } - } - false => { - let kept = (&mut *samplers, memo.as_deref_mut()); - Info::Image(image_descriptor(call, device, tables, planned, ty, kept)?) - } - }; - *write = Write { - set: planned.set, - binding: planned.binding, - element: planned.array_element, - ty, - info, - held: None, - }; - dynamic_write(write, dynamic, offsets); - } - Ok(true) -} - -/// One descriptor to write: a buffer's or an image's and sampler's. -pub(super) struct Write { - pub(super) set: u32, - pub(super) binding: u32, - pub(super) element: u32, - pub(super) ty: vk::DescriptorType, - pub(super) info: Info, - /// What keeps what a heap element names while the device's heap set holds it: an argument - /// sampler's `VkSampler`, a function table's words (`heap_sets.rs`). - pub(super) held: Option, -} - -impl Write { - /// A copy of it, where it holds no keeper. - pub(super) fn unheld(&self) -> Option { - self.held.is_none().then_some(Write { - set: self.set, - binding: self.binding, - element: self.element, - ty: self.ty, - info: self.info, - held: None, - }) - } -} - -/// What a descriptor write holds. -#[derive(Clone, Copy)] -pub(super) enum Info { - Buffer(vk::DescriptorBufferInfo), - Image(vk::DescriptorImageInfo), - Texel(vk::BufferView), -} - -impl Info { - /// `write` with this as its one descriptor: pointing at it where it lies, with no copy. - fn written<'a>(&'a self, write: vk::WriteDescriptorSet<'a>) -> vk::WriteDescriptorSet<'a> { - match self { - Info::Buffer(info) => write.buffer_info(std::slice::from_ref(info)), - Info::Image(info) => write.image_info(std::slice::from_ref(info)), - Info::Texel(view) => write.texel_buffer_view(std::slice::from_ref(view)), - } - } -} - -/// What a write holds, as [`SetWrite::same`] compares it: its handles, offset, range and layout, -/// the layout by its raw value (ash's info structures print nothing). -impl std::fmt::Debug for Info { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Info::Buffer(info) => (f.debug_tuple("Buffer")) - .field(&info.buffer) - .field(&info.offset) - .field(&info.range) - .finish(), - Info::Image(info) => (f.debug_tuple("Image")) - .field(&info.sampler) - .field(&info.image_view) - .field(&info.image_layout.as_raw()) - .finish(), - Info::Texel(view) => f.debug_tuple("Texel").field(view).finish(), - } - } -} - -/// One push-constant write: stages, offset, bytes. -pub(super) type PushWrite = (vk::ShaderStageFlags, u32, Vec); - -/// A push hole's address: the stages of the push write it lies in, its offset, the address. -#[derive(Clone, Copy)] -pub(super) struct Hole { - stages: vk::ShaderStageFlags, - offset: u32, - address: u64, -} - -/// What a command records besides its pipeline, its draw or groups, and its descriptor writes -/// ([`bind`]'s). -pub(super) struct Bound { - /// The push holes' addresses, for [`push_writes`]. - pub(super) holes: Vec, - /// The Vulkan samplers the writes name, which the command buffer holds until it completes. - pub(super) samplers: Vec>, -} - -/// The buffer bound at buffer slot `slot`, if any: its read twin where the command reads it -/// through that ([`TwinSlots`]). -fn slot_buffer<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a (Buffer, u64)> { - if let Some(twin) = tables.twins.and_then(|twins| twins.buffer(slot)) { - return Some(twin); - } - stage_buffer(tables.stages, slot) -} - -/// The buffer the table of `stages` of its stage binds at buffer slot `slot`, if any. -fn stage_buffer<'a>( - stages: &[(Stage, &'a ArgumentTable)], - slot: SlotRef, -) -> Option<&'a (Buffer, u64)> { - let table = || { - stages - .iter() - .find(|(of, _)| *of == slot.stage) - .map(|&(_, table)| table) - }; - (slot.class == SlotClass::Buffer) - .then(|| table()?.buffers.get(&slot.index)) - .flatten() -} - -/// The inline bytes set at buffer slot `slot`, if any. -fn slot_bytes<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a InlineBytes> { - (slot.class == SlotClass::Buffer) - .then(|| tables.of(slot.stage)?.bytes.get(&slot.index)) - .flatten() -} - -/// The texture bound at texture slot `slot`, if any: its read twin where the command reads it -/// through that ([`TwinSlots`]). -fn slot_texture<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a Texture> { - if slot.class != SlotClass::Texture { - return None; - } - if let Some(twin) = tables.twins.and_then(|twins| twins.texture(slot)) { - return Some(twin); - } - tables.of(slot.stage)?.textures.get(&slot.index) -} - -/// The tile map of the sparse texture bound at texture slot `slot`, which the plan reads where -/// the slot's shape is sparse: every sparse texture whose type has a tile map keeps one. One -/// without (a view of another type of a cube texture's slices) is refused -/// `NotImplemented(SparseTileMaps)`: the format lays out no cube map. -fn slot_tile_map<'a>(tables: &Tables<'a>, slot: SlotRef) -> Result<&'a Buffer, Error> { - let image = slot_texture(tables, slot) - .and_then(Texture::sparse_image) - .ok_or_else(|| internal("a tile map read of a slot without a sparse texture"))?; - image - .tile_map() - .map(|tile_map| &tile_map.buffer) - .ok_or(Error::NotImplemented(RuntimeGap::SparseTileMaps)) -} - -/// The sampler bound at sampler slot `slot`, if any. -fn slot_sampler<'a>( - tables: &Tables<'a>, - slot: SlotRef, -) -> Option<&'a (SamplerState, Option<[f32; 2]>)> { - (slot.class == SlotClass::Sampler) - .then(|| tables.of(slot.stage)?.samplers.get(&slot.index)) - .flatten() -} - -/// `n` rounded up to 16 bytes, at least 16 (the padding contract). -fn padded(n: usize) -> u64 { - (n as u64).next_multiple_of(16).max(16) -} - -/// The descriptors, uploads, and push hole addresses of `command`, a command (by `call`) of -/// `plan` over `tables`, uploading into the command buffer's `state`: the descriptor writes in -/// `writes`, emptied first, so a caller that keeps the vector writes each command's over the last -/// one's storage (a draw's, `LiveBind::writes`). -pub(super) fn bind( - call: &'static str, - device: &Device, - state: &mut State, - plan: &BindingPlan, - command: &Command<'_>, - tables: &Tables<'_>, - (memo, writes): (Option<&mut BindMemo>, &mut Vec), -) -> Result { - let mut samplers = Vec::new(); - let mut bound = bind_into( - call, - device, - state, - (plan, command, tables), - (memo, writes, &mut samplers), - None, - )?; - bound.samplers = samplers; - Ok(bound) -} - -/// [`bind`]'s, the samplers the writes name in `samplers`, emptied first (its [`Bound`]'s -/// `samplers` left empty), so a caller that keeps the vector fills each command's into the last -/// one's storage (a draw's, `LiveBind::samplers`). With `past`, where the command has a heap and -/// its caller keeps its heap part (`render/heap_part.rs`): the writes it lists, where it lists -/// them, alone, else every write, listed there (the module docs). -pub(super) fn bind_into( - call: &'static str, - device: &Device, - state: &mut State, - (plan, command, tables): (&BindingPlan, &Command<'_>, &Tables<'_>), - (mut memo, writes, samplers): ( - Option<&mut BindMemo>, - &mut Vec, - &mut Vec>, - ), - past: Option<&mut PastHeap>, -) -> Result { - writes.clear(); - writes.reserve(plan.descriptors.len()); - samplers.clear(); - match past.filter(|_| tables.heap.is_some()) { - Some(past) if past.listed => { - // Checked against the writes listed again, in place: a draw's allocations are - // bounded in builds with debug assertions too (`runtime_lane::frame_costs`). - #[cfg(debug_assertions)] - { - let mut kept = past.at.iter(); - for (at, write) in plan.descriptors.iter().enumerate() { - if written_at(call, tables, write, false)?.is_some() { - assert_eq!( - kept.next(), - Some(&(at as u32)), - "a command's writes past its kept heap that are not its own" - ); - } - } - assert_eq!( - kept.next(), - None, - "a command's writes past its kept heap that are not its own" - ); - } - for &at in past.at.iter() { - let write = (plan.descriptors.get(at as usize)) - .ok_or_else(|| internal("a listed write past the plan's"))?; - let element = written_at(call, tables, write, false)? - .ok_or_else(|| internal("a listed write the command does not write"))?; - let kept = (&mut *samplers, memo.as_deref_mut()); - let write = written( - call, - device, - state, - (command, tables), - (write, element), - kept, - )?; - writes.push(write); - } - } - mut past => { - // A check that announced a notice its device announces at every occurrence lists - // nothing: the next command meets it again. - let watch = EachWatch::start(); - if let Some(past) = &mut past { - past.forget(); - } - for (at, write) in plan.descriptors.iter().enumerate() { - let Some(element) = written_at(call, tables, write, true)? else { - continue; - }; - if let Some(past) = &mut past { - past.at.push(at as u32); - } - let kept = (&mut *samplers, memo.as_deref_mut()); - let write = written( - call, - device, - state, - (command, tables), - (write, element), - kept, - )?; - writes.push(write); - } - if let Some(past) = past { - past.listed = !watch.met(); - } - } - } - let mut roots = Vec::with_capacity(command.root_tables.len()); - for &(stages, table) in &command.root_tables { - roots.push(( - stages, - root_table(device, state, table, command.root_writes)?, - )); - } - let mut holes = Vec::with_capacity(command.push_holes.len()); - for hole in command.push_holes { - holes.push(match *hole { - PushHole::RootTableAddress { stages, offset } => Hole { - stages: stages.into(), - offset, - address: roots - .iter() - .find(|(of, _)| *of == stages) - .map(|&(_, address)| address) - .ok_or_else(|| internal("a root-table hole without its stage's root table"))?, - }, - PushHole::ExecutionStatusAddress { stages, offset } => Hole { - stages: stages.into(), - offset, - address: state - .status_address(device)? - .ok_or_else(|| internal("a status hole without device addresses"))?, - }, - // A flat variant's dispatch reads its region record; a device replay's records the - // runtime does not run. - PushHole::ReplayRegionAddress { stages, offset } => Hole { - stages: stages.into(), - offset, - address: tables - .region_record - .ok_or(Error::NotImplemented(RuntimeGap::CommandReplay))?, - }, - PushHole::CommandRecordsAddress { .. } => { - return Err(Error::NotImplemented(RuntimeGap::CommandReplay)); - } - // A de-indexed draw's first index, or a private list's (`Tables::with_indices`). - PushHole::CaptureIndexAddress { stages, offset } => Hole { - stages: stages.into(), - offset, - address: tables - .indices - .ok_or_else(|| internal("an index hole without its indices"))?, - }, - // A merged draw replay's header, which its vertex function finds its command in. - PushHole::MergedDrawAddress { stages, offset } => Hole { - stages: stages.into(), - offset, - address: tables - .merged_header - .ok_or_else(|| internal("a merged draw's hole outside a merged draw"))?, - }, - // Which of a snapshot variant's draws runs: 0 in the plan's bytes, the drawing draw's, - // and set before each draw as it records (`render/snapshot.rs`). - PushHole::SnapshotPhase { .. } if tables.snapshots.is_some() => continue, - PushHole::SnapshotPhase { .. } => { - return Err(internal( - "a snapshot phase hole the runtime did not ask for", - )); - } - }); - } - Ok(Bound { - holes, - samplers: Vec::new(), - }) -} - -/// The indices of a plan's descriptor writes that a command whose caller keeps its heap part -/// writes past its heap's entries (`render/heap_part.rs`): listed by [`bind_into`] at a command -/// that checked each entry and met no notice its device announces at every occurrence, so a -/// later command of the same plan under the same heap part writes those alone. They are a -/// function of the plan and of where its heap writes go (`metal2vulkan::bind::HeapElements`), -/// and an entry's check of its texture and the plan's view, which no call changes. -#[derive(Default)] -pub(super) struct PastHeap { - /// Whether `at` lists them. - listed: bool, - /// Their positions among the plan's writes, ascending. - at: Vec, -} - -impl PastHeap { - /// List none, keeping the list's storage: a heap part worked out again, or let go of. - pub(super) fn forget(&mut self) { - self.listed = false; - self.at.clear(); - } -} - -/// Where `write`, one of its plan's descriptor writes, is written for a command over `tables`: -/// its element, or `None` where the command writes nothing there. A heap's write no handle -/// reaches is none, and in the device's heap set, which holds every texture, every sampler state -/// and the neutrals (the module docs), so are a heap entry, its texture checked as a slot's view -/// is where `check` says so, every other image element (an array's neutral where a member's -/// texture does not fit its class), an argument sampler, and a neutral element -/// (`heap_sets::holds_element`). -fn written_at( - call: &'static str, - tables: &Tables<'_>, - write: &DescriptorWrite, - check: bool, -) -> Result, Error> { - let Some(heap) = tables.heap else { - return Ok(Some(write.array_element)); - }; - // No handle reaches it. - let Some(element) = heap.element(write) else { - return Ok(None); - }; - if write.set != HEAP_SET { - return Ok(Some(element)); - } - match &write.source { - WriteSource::HeapEntry { source, view, .. } => { - if check { - let ty: vk::DescriptorType = write.ty.into(); - let storage = ty == vk::DescriptorType::STORAGE_IMAGE; - heap_texture(tables, *source)?.bound_view(call, view, storage)?; - } - Ok(None) - } - WriteSource::ArgumentSampler { .. } => Ok(None), - _ if heap_sets::holds_element(write.ty.into(), element) => Ok(None), - _ => Ok(Some(element)), - } -} - -/// The write of `write`, one of its plan's descriptor writes, at `element`, for `command` over -/// `tables` ([`bind_into`]): its image descriptor's sampler kept in `samplers`, through `memo`. -fn written( - call: &'static str, - device: &Device, - state: &mut State, - (command, tables): (&Command<'_>, &Tables<'_>), - (write, element): (&DescriptorWrite, u32), - (samplers, mut memo): (&mut Vec>, Option<&mut BindMemo>), -) -> Result { - let ty: vk::DescriptorType = write.ty.into(); - let info = match (&write.source, ty) { - (WriteSource::HeapEntry { .. }, _) => { - return Err(internal("a heap entry outside the heap set")) - } - // A buffer slot's uniform view in its texel form (`DescriptorView::UniformTexel`): a view - // of the range its uniform buffer would bind, made for this write and held until the - // command buffer completed (`uniform_texels.rs`). - ( - WriteSource::Buffer { .. } - | WriteSource::InlineBytes { .. } - | WriteSource::Neutral(NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. }), - vk::DescriptorType::UNIFORM_TEXEL_BUFFER, - ) => { - let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces); - let range = descriptor(device, state, command, tables, (write, spaces))?; - let texels = UniformTexels::new(device, &range)?; - let view = texels.raw(); - state.retain_own(texels); - device.shared().counts.thread().uniform_texels_bound(); - Info::Texel(view) - } - (_, ty) => match ty { - vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::STORAGE_BUFFER => { - let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces); - let info = descriptor(device, state, command, tables, (write, spaces))?; - count_uniform_buffer(device, command, write, ty); - Info::Buffer(info) - } - vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER => { - let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER; - Info::Texel(texel_descriptor(device, command, tables, write, storage)?) - } - _ => Info::Image(image_descriptor( - call, - device, - tables, - write, - ty, - (samplers, memo), - )?), - }, - }; - // What keeps an argument sampler's `VkSampler` or a function table's words while the - // heap set holds them. - let held: Option = match (&write.source, &info) { - (WriteSource::ArgumentSampler { .. }, Info::Image(image)) => samplers - .iter() - .find(|kept| kept.raw() == image.sampler) - .map(|kept| Box::new(Arc::clone(kept)) as Keeper), - (WriteSource::FunctionTable { index }, _) => tables - .function_tables - .get(*index as usize) - .map(|table| Box::new(table.words().clone()) as Keeper), - _ => None, - }; - Ok(Write { - set: write.set, - binding: write.binding, - element, - ty, - info, - held, - }) -} - -/// Make the device's neutral images, texel buffers and samplers that [`bind`] may write or check -/// for `plan`: at its unbound texture, sampler and texel slots, its heap elements whose texture it -/// cannot present (which the device's heap sets hold, so [`bind`] writes none), and its argument -/// sampler elements past the states listed. So binding a command of the plan later makes none: a -/// host step runs no submission of its own and makes no neutral, which it refuses (`neutral.rs`). -pub(super) fn make_neutrals(device: &Device, plan: &BindingPlan) -> Result<(), Error> { - for write in &plan.descriptors { - let ty: vk::DescriptorType = write.ty.into(); - match &write.source { - WriteSource::Neutral(NeutralResource::TexelBuffer { format }) => { - let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER; - device.neutral_texel_view(*format, storage)?; - } - // The zero buffer a read-only binding shares, so a host step binds one already made - // (the module docs' "no wait"), as it finds the images and samplers made. - WriteSource::Neutral( - NeutralResource::ZeroBuffer { min_bytes } | NeutralResource::Sink { min_bytes }, - ) if read_only_buffer(ty) => { - device.neutral_zero_buffer(padded(*min_bytes as usize))?; - } - WriteSource::Neutral(kind @ NeutralResource::Image { .. }) => { - device.neutral_view(*kind)?; - } - WriteSource::Neutral(NeutralResource::Sampler { compare }) - | WriteSource::ArgumentSampler { compare, .. } => { - device.neutral_sampler(*compare)?; - } - WriteSource::CombinedImageSampler { image, sampler } => { - if let ImageSource::Neutral(kind) = image { - device.neutral_view(*kind)?; - } - if let SamplerSource::Neutral(NeutralResource::Sampler { compare }) = sampler { - device.neutral_sampler(*compare)?; - } - } - WriteSource::HeapEntry { - class: HandleClass::Image(image), - .. - } => { - if let Some(kind) = NeutralResource::for_image(image) { - device.neutral_view(kind)?; - } - } - _ => {} - } - } - Ok(()) -} - -/// The texture heap entry `source` names: made resident by the encoder, or bound at a slot. -fn heap_texture<'a>(tables: &Tables<'a>, source: HeapSource) -> Result<&'a Texture, Error> { - match source { - HeapSource::Used(token) => match tables.used(token) { - Some(Used::Texture(texture)) => Ok(texture), - _ => Err(internal( - "a heap entry of a texture the encoder did not use", - )), - }, - HeapSource::Bound(slot) => slot_texture(tables, slot) - .ok_or_else(|| internal("a heap entry of an unbound texture slot")), - } -} - -/// The push writes of `writes` (one region's, or one draw's) with `holes` filled: each hole in -/// the write of its own stages that covers its eight bytes. Its writes' bytes become theirs, in -/// their storage. -pub(super) fn push_writes( - writes: Vec, - holes: &[Hole], -) -> Result, Error> { - let mut filled: Vec = writes - .into_iter() - .map(|write| (write.stages.into(), write.offset, write.bytes)) - .collect(); - fill_holes(&mut filled, holes)?; - Ok(filled) -} - -/// [`push_writes`] of `writes`, written over `filled`: each write's bytes copied into the storage -/// of the write a draw before left at its place, where there is one. -pub(super) fn push_writes_into( - writes: &[PushConstantWrite], - holes: &[Hole], - filled: &mut Vec, -) -> Result<(), Error> { - filled.truncate(writes.len()); - for (at, write) in writes.iter().enumerate() { - let stages = write.stages.into(); - match filled.get_mut(at) { - Some(kept) => { - (kept.0, kept.1) = (stages, write.offset); - kept.2.clear(); - kept.2.extend_from_slice(&write.bytes); - } - None => filled.push((stages, write.offset, write.bytes.clone())), - } - } - fill_holes(filled, holes) -} - -/// Fill each of `holes` in the write of `filled` of its own stages that covers its eight bytes. -fn fill_holes(filled: &mut [PushWrite], holes: &[Hole]) -> Result<(), Error> { - for hole in holes { - let write = filled - .iter_mut() - .find(|(stages, start, bytes)| { - *stages == hole.stages - && *start <= hole.offset - && hole.offset as usize + 8 <= *start as usize + bytes.len() - }) - .ok_or_else(|| internal("no push write of its stages covers a push hole"))?; - let at = (hole.offset - write.1) as usize; - write.2[at..at + 8].copy_from_slice(&hole.address.to_le_bytes()); - } - Ok(()) -} - -/// One descriptor of a pushed set 0: [`Write`]'s, without its set number and keeper. -#[derive(Clone, Copy)] -pub(super) struct SetWrite { - pub(super) binding: u32, - pub(super) element: u32, - pub(super) ty: vk::DescriptorType, - pub(super) info: Info, -} - -impl SetWrite { - /// Set 0's `writes`, then a variant's `immutable` pushes (`VariantObjects::immutable_pushes`): - /// what a draw pushes. - pub(super) fn pushed(writes: &[Write], immutable: &[SetWrite]) -> Vec { - let mut pushed = Vec::new(); - Self::push_into(writes, immutable, &mut pushed); - pushed - } - - /// [`pushed`](Self::pushed) in `pushed`, emptied first: over the last draw's storage, where - /// the caller keeps it (`LiveBind::pushed`). - pub(super) fn push_into(writes: &[Write], immutable: &[SetWrite], pushed: &mut Vec) { - pushed.clear(); - pushed.extend( - writes - .iter() - .map(SetWrite::of) - .chain(immutable.iter().copied()), - ); - } - - /// `write`'s descriptor, without its set number and keeper. - pub(super) fn of(write: &Write) -> SetWrite { - SetWrite { - binding: write.binding, - element: write.element, - ty: write.ty, - info: write.info, - } - } - - /// Its raw write, of no set (a push's), pointing at its info. - pub(super) fn raw(&self) -> vk::WriteDescriptorSet<'_> { - self.info.written( - vk::WriteDescriptorSet::default() - .dst_binding(self.binding) - .dst_array_element(self.element) - .descriptor_type(self.ty), - ) - } - - /// Whether it writes what `other` writes. - pub(super) fn same(&self, other: &SetWrite) -> bool { - (self.binding, self.element, self.ty) == (other.binding, other.element, other.ty) - && match (self.info, other.info) { - (Info::Buffer(a), Info::Buffer(b)) => { - (a.buffer, a.offset, a.range) == (b.buffer, b.offset, b.range) - } - (Info::Image(a), Info::Image(b)) => { - (a.sampler, a.image_view, a.image_layout) - == (b.sampler, b.image_view, b.image_layout) - } - (Info::Texel(a), Info::Texel(b)) => a == b, - _ => false, - } - } -} - -/// `vkCmdPushDescriptorSet` by its core name from Vulkan 1.4 (`api`), else by -/// `VK_KHR_push_descriptor`'s where the device enabled it; none otherwise. -/// -/// # Safety -/// -/// `device` is live, of `instance`, made with `enabled` enabled. -pub(crate) unsafe fn push_descriptor_command( - instance: &ash::Instance, - device: &ash::Device, - api: metal2vulkan::device::ApiVersion, - enabled: &metal2vulkan::device::EnableSet, -) -> Option { - let name: &std::ffi::CStr = if api >= (metal2vulkan::device::ApiVersion { major: 1, minor: 4 }) - { - c"vkCmdPushDescriptorSet" - } else if enabled - .extensions - .contains(&metal2vulkan::device::VkExtension::KhrPushDescriptor) - { - c"vkCmdPushDescriptorSetKHR" - } else { - return None; - }; - // SAFETY: the caller's; a command the device does not have is null. - let command = unsafe { instance.get_device_proc_addr(device.handle(), name.as_ptr()) }?; - // SAFETY: the device gave the command of this name, and both names share its signature. - Some(unsafe { - std::mem::transmute::( - command, - ) - }) -} - -/// Push `writes` as set 0 of `layout` at `point` into `command_buffer`, in one -/// `vkCmdPushDescriptorSet` (`push`): each raw write pointing at its write's own info, the raw -/// writes on the stack up to [`WRITES_AT_ONCE`], else on the heap. -/// -/// # Safety -/// -/// `command_buffer` is recording, `layout`'s set 0 is a push descriptor set layout, and every -/// buffer, view and sampler written stays live while the command buffer can run. -pub(super) unsafe fn push_set( - push: vk::PFN_vkCmdPushDescriptorSetKHR, - command_buffer: vk::CommandBuffer, - point: vk::PipelineBindPoint, - layout: vk::PipelineLayout, - writes: &[SetWrite], -) { - if writes.len() <= WRITES_AT_ONCE { - let mut places = [const { MaybeUninit::uninit() }; WRITES_AT_ONCE]; - let raw = fill_raw(writes.iter().map(SetWrite::raw), &mut places); - // SAFETY: the caller's contract; every info `raw` points at is `writes`', live for the - // call. - unsafe { - push( - command_buffer, - point, - layout, - 0, - raw.len() as u32, - raw.as_ptr(), - ) - }; - } else { - let raw: Vec<_> = writes.iter().map(SetWrite::raw).collect(); - // SAFETY: as above. - unsafe { - push( - command_buffer, - point, - layout, - 0, - raw.len() as u32, - raw.as_ptr(), - ) - }; - } -} - -/// `raw` written into `places`' first places, as many as fit: those places, which nothing else -/// writes or zeroes. -pub(super) fn fill_raw<'a, 'p>( - raw: impl Iterator>, - places: &'p mut [MaybeUninit>; WRITES_AT_ONCE], -) -> &'p [vk::WriteDescriptorSet<'a>] { - let mut count = 0; - for (place, write) in places.iter_mut().zip(raw) { - place.write(write); - count += 1; - } - // SAFETY: the first `count` places were written above, and a `MaybeUninit` has `T`'s - // layout. - unsafe { std::slice::from_raw_parts(places.as_ptr().cast(), count) } -} - -/// The descriptor writes [`push_set`] and [`write_sets`] hand the driver from the stack in one call. -pub(super) const WRITES_AT_ONCE: usize = 16; - -/// Write `writes` into `sets`, the descriptor sets of their layout by set number: in order, -/// [`WRITES_AT_ONCE`] at a time. -/// -/// # Safety -/// -/// No pending or recording command uses `sets`, and every buffer, view and sampler written stays -/// live while a command that binds the sets can run. -pub(super) unsafe fn write_sets( - device: &Device, - sets: &[vk::DescriptorSet], - writes: &[Write], -) -> Result<(), Error> { - if writes.iter().any(|write| write.set as usize >= sets.len()) { - return Err(internal("a descriptor write to a set the layout lacks")); - } - for writes in writes.chunks(WRITES_AT_ONCE) { - let raw = writes.iter().map(|write| { - write.info.written( - vk::WriteDescriptorSet::default() - .dst_set(sets[write.set as usize]) - .dst_binding(write.binding) - .dst_array_element(write.element) - .descriptor_type(write.ty), - ) - }); - let mut places = [const { MaybeUninit::uninit() }; WRITES_AT_ONCE]; - let raw = fill_raw(raw, &mut places); - // SAFETY: the caller's contract; every info `raw` points at is `writes`', live for the - // call. - unsafe { device.shared().vk().update_descriptor_sets(raw, &[]) }; - } - Ok(()) -} - -/// The set 0 an encoder's last command bound from its command buffer's pools -/// (`EncoderCore::set_zero`): the set, its layout and the descriptors written into it, kept once -/// the command records (`EncoderCore::keep_set_zero`) or as it finds the set its command buffer -/// keeps ([`SetCache`]). A later command of the encoder that writes the same descriptors into a -/// set of the same layout binds this set again, and allocates and writes none -/// (`WorkCounts::set_zero_sets_reused`). Exact: -/// -/// - **The set holds what was written.** A set is written once, as it is allocated, and nothing -/// writes it again; set 0's writes hold no keeper (only the heap set's do, `Write::held`). -/// - **No handle it holds names another object.** The set lies in its command buffer's pools, -/// which last until the command buffer completes; so do the objects its writes name, which a -/// command that recorded with them holds (its buffers, textures, views and samplers), the -/// command buffer's arena (uploads) or what it retained (a uniform view's texel buffer view, -/// made for its write: `uniform_texels.rs`), or the device (neutrals). The memo lives with its -/// encoder, inside its command buffer's life. -/// - **The writes compare by value** ([`SetWrite::same`], in order: each binding, element, type -/// and descriptor, a buffer's offset and range, an image's view, sampler and layout), so the set -/// is bound again only where every descriptor written is the one the command writes. -#[derive(Default)] -pub(super) struct LastSetZero { - layout: vk::DescriptorSetLayout, - set: vk::DescriptorSet, - writes: Vec, -} - -impl LastSetZero { - /// The kept set, where it is of `layout` and holds `writes` (set 0's). - pub(super) fn holds( - &self, - layout: vk::DescriptorSetLayout, - writes: &[Write], - ) -> Option { - let same = self.set != vk::DescriptorSet::null() - && self.layout == layout - && self.writes.len() == writes.len() - && (self.writes.iter().zip(writes)) - .all(|(kept, write)| kept.same(&SetWrite::of(write))); - same.then_some(self.set) - } - - /// Keep `set`, of `layout`, as written with `writes` (set 0's), over the last one's storage. - pub(super) fn keep( - &mut self, - layout: vk::DescriptorSetLayout, - set: vk::DescriptorSet, - writes: &[Write], - ) { - self.layout = layout; - self.set = set; - self.writes.clear(); - self.writes.extend(writes.iter().map(SetWrite::of)); - } -} - -/// What a compute encoder's dispatches recorded at the compute bind point of the -/// `VkCommandBuffer` it records into, while it still holds there -/// (`EncoderCore::command_reaching_pushed`): the `VkPipeline` bound last, and set 0 as the -/// dispatches pushed it with a layout. A dispatch binds its first region's pipeline only where -/// another is bound, and pushes only the writes of its set 0 that differ from those set 0 holds -/// ([`carry`](Self::carry)), none where none differs, as a draw does in its secondary command -/// buffer (`render/bound.rs`). Exact, under Vulkan's rules: -/// -/// - **Pushed descriptors last until overwritten.** `vkCmdPushDescriptorSet`: "Push descriptors -/// can be updated incrementally and cause shaders to use the updated descriptors for subsequent -/// bound pipeline commands with the pipeline type set by pipelineBindPoint until the descriptor -/// is overwritten, or else until the set is disturbed as described in Pipeline Layout -/// Compatibility. When the set is disturbed or push descriptors with a different descriptor set -/// layout are set, all push descriptors are undefined." So set 0 is held only as pushed with -/// the same `VkPipelineLayout` (one layout's set 0 is one set layout), of the same bindings and -/// elements in order; a dispatch of another layout forgets what was pushed -/// ([`records_with`](Self::records_with)), whatever it binds (a set 1 bound with a layout not -/// compatible for set 0 disturbs set 0), and so does a bind of set 0 from a set -/// ([`set_bound`](Self::set_bound)). Set 1 bound with the same layout disturbs no set 0, nor does -/// binding a pipeline (Pipeline Layout Compatibility: "When binding a descriptor set ... to set -/// number N, a previously bound descriptor set bound with lower index M than N is disturbed if -/// the pipeline layouts for set M and N are not compatible for set M. Otherwise, the bound -/// descriptor set in M is not disturbed."). -/// - **A pipeline stays bound** until another is bound at the same bind point. -/// - **Nothing else records there meanwhile.** It holds only while the dispatch records into the -/// `VkCommandBuffer` the encoder's last such dispatch recorded into and the encoder recorded -/// nothing else into it since ([`hold`](Self::hold): its count of recordings, bumped by every -/// command, barrier and copy run that takes the `VkCommandBuffer`, `EncoderCore::raw_recording`, -/// and by recorded gather runs), so no other command's pipeline, set or push at the compute bind -/// point (the runtime's own kernels, a flat dispatch's preprocess, which forgets it) comes -/// between; another `VkCommandBuffer` forgets it. Each encoder begins it empty, so one that -/// records on in the `VkCommandBuffer` of a group of encoders (`encoder_fold.rs`) takes nothing -/// the group's earlier encoders recorded there, and a dispatch recorded later into a segment of -/// its own (`pending_dispatch.rs`) pushes set 0 whole. -/// - **Where pushed descriptors go stale across a pipeline bind** -/// (`RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds`), the push after a pipeline -/// bind carries at least one write (set 0's first where none changed), as a draw's does: the -/// dispatch binds its pipeline before it pushes. -#[derive(Default)] -pub(super) struct PushedSetZero { - raw: vk::CommandBuffer, - /// The encoder's count of recordings as the last dispatch that kept this recorded. - mark: u64, - pipeline: vk::Pipeline, - layout: vk::PipelineLayout, - /// Set 0's writes as pushed with `layout`: none where it holds no pushed set 0. - writes: Vec, - /// The writes the last push carried, where it carried fewer than set 0's. - changed: Vec, - /// A pipeline was bound since set 0's last push. - bound_since_push: bool, -} - -impl PushedSetZero { - /// Forget what it held unless the command recording now records into `raw` with the - /// encoder's count of recordings at `mark`, one past the last dispatch's that kept it: that - /// dispatch's command's own taking of `raw` alone came between. - pub(super) fn hold(&mut self, raw: vk::CommandBuffer, mark: u64) { - if self.raw != raw || self.mark.checked_add(1) != Some(mark) { - self.forget(); - } - } - - /// What it holds now holds as recorded into `raw` at the encoder's count of recordings - /// `mark`. - pub(super) fn recorded(&mut self, raw: vk::CommandBuffer, mark: u64) { - (self.raw, self.mark) = (raw, mark); - } - - /// Hold nothing: no pipeline and no pushed set 0 known. - pub(super) fn forget(&mut self) { - self.pipeline = vk::Pipeline::null(); - self.set_bound(); - self.bound_since_push = false; - } - - /// Set 0 was bound from a set: no pushed set 0 held. - pub(super) fn set_bound(&mut self) { - self.layout = vk::PipelineLayout::null(); - self.writes.clear(); - } - - /// A dispatch records its sets and push constants with `layout`: set 0 is held across - /// dispatches of one layout alone, so one of another forgets what was pushed, whatever it - /// binds or pushes. - pub(super) fn records_with(&mut self, layout: vk::PipelineLayout) { - if self.layout != layout { - self.set_bound(); - } - } - - /// Whether `pipeline` must be bound, another being bound or none known: it is bound from now. - pub(super) fn binds(&mut self, pipeline: vk::Pipeline) -> bool { - if self.pipeline == pipeline { - return false; - } - self.pipeline = pipeline; - self.bound_since_push = true; - true - } - - /// The writes a push of set 0's `writes` with `layout` carries: where set 0 holds the same - /// bindings and elements pushed with `layout`, those that differ from what it holds, and - /// where `stale` and a pipeline was bound since the last push at least one (set 0's first - /// where none differs); else every one. Set 0 holds `writes` from now. - pub(super) fn carry<'a>( - &'a mut self, - layout: vk::PipelineLayout, - writes: &'a [SetWrite], - stale: bool, - ) -> &'a [SetWrite] { - let renew = stale && self.bound_since_push; - self.bound_since_push = false; - let held = layout != vk::PipelineLayout::null() - && self.layout == layout - && !self.writes.is_empty() - && self.writes.len() == writes.len() - && (self.writes.iter().zip(writes)) - .all(|(a, b)| (a.binding, a.element, a.ty) == (b.binding, b.element, b.ty)); - if !held { - self.layout = layout; - self.writes.clear(); - self.writes.extend_from_slice(writes); - return writes; - } - self.changed.clear(); - for (old, new) in self.writes.iter_mut().zip(writes) { - if !old.same(new) { - *old = *new; - self.changed.push(*new); - } - } - if let (true, true, Some(&first)) = (renew, self.changed.is_empty(), writes.first()) { - self.changed.push(first); - } - &self.changed - } -} - -/// The most sets 0 one generation of a [`SetCache`] keeps. -const SETS_KEPT: usize = 128; - -/// The sets 0 a [`Generation`] makes room for at its first set; it grows past them to -/// [`SETS_KEPT`]. A command buffer's commands write a few sets as a rule (one per pipeline state -/// and bound resources), so the room for all of them at once (about 27 KB) would be made and let -/// go of at every command buffer. -const SETS_ROOM: usize = 8; - -/// The sets 0 a command buffer's recorded commands allocated and wrote, by what they hold -/// (`EncoderCore::set_zero`): a later command of the command buffer, in any of its encoders, that -/// writes the same descriptors into a set of the same layout binds the set again, and allocates -/// and writes none (`WorkCounts::set_zero_sets_found`). Kept in the command buffer's arena, -/// whose pools hold the sets (`descriptor_arena.rs`), and gone as they go. Exact, as -/// [`LastSetZero`] is: -/// -/// - **A set holds what was written.** Written once, as it is allocated; nothing writes it again. -/// - **No handle it holds names another object.** A set is kept only once its command records, -/// and only while the command buffer holds what its commands took strongly, which is until it -/// is committed (`command_buffer/mod.rs`): every object a kept set's writes name is held by the -/// command (its buffers, textures, views and samplers), the command buffer's arena (uploads) or -/// what it retained (a uniform view's texel buffer view, made for its write: -/// `uniform_texels.rs`), or the device (neutrals), so no such object goes, nor can another take -/// its handle, while its sets are kept. A view is made for one write alone, so no later -/// command finds a set that names one. A refused command's set is never kept. At the commit the holds go weak, so a -/// rebind may let the pages go, and the cache is shut there and keeps and serves nothing again -/// (`DescriptorArena::shut`): every command recorded from the commit on -- an encoder encoded -/// again at a rebind (`command_buffer/reencode.rs`), a host step's -- allocates and writes its -/// own set. -/// - **The writes compare by value** ([`SetWrite::same`], in order), behind a hash of them -/// ([`set_key`]), so a set is bound again only where every descriptor written is the one the -/// command writes. -/// -/// Bounded: two generations of at most [`SETS_KEPT`] sets each. A set found in the older -/// generation moves to the newer one; a newer generation that fills becomes the older one, the -/// older one's sets forgotten (they stay in their pools, unbound by later commands). So a command -/// buffer whose commands write fewer distinct sets than a generation holds allocates each once. -/// A generation keeps its storage as it empties, and makes room for [`SETS_ROOM`] sets at its -/// first: a few allocations a command buffer, none a command but where the room grows. -#[derive(Default)] -pub(crate) struct SetCache { - generations: [Generation; 2], - /// The newer generation's place in `generations`. - newer: usize, -} - -/// One generation of a [`SetCache`]: its sets, each's place by its key (a set of other writes -/// under a key a set holds is not kept), and their writes one after another. -#[derive(Default)] -struct Generation { - by_key: KeyMap, - sets: Vec, - writes: Vec, -} - -/// One set 0 a [`Generation`] keeps: its layout, the set, and where the descriptors written into -/// it lie in the generation's writes. -struct CachedSet { - layout: vk::DescriptorSetLayout, - set: vk::DescriptorSet, - writes: Range, -} - -impl Generation { - /// The set of `layout` that holds `writes` it keeps under `key`, by its place. - fn find(&self, key: u64, layout: vk::DescriptorSetLayout, writes: &[Write]) -> Option { - let &at = self.by_key.get(&key)?; - let kept = &self.sets[at]; - let held = &self.writes[kept.writes.clone()]; - let same = kept.layout == layout - && held.len() == writes.len() - && (held.iter().zip(writes)).all(|(held, write)| held.same(&SetWrite::of(write))); - same.then_some(at) - } - - /// Keep `set`, of `layout`, holding `writes`, under `key`. - fn keep( - &mut self, - key: u64, - (layout, set): (vk::DescriptorSetLayout, vk::DescriptorSet), - writes: impl Iterator, - ) { - if self.sets.capacity() == 0 { - self.by_key.reserve(SETS_ROOM); - self.sets.reserve(SETS_ROOM); - self.writes.reserve(4 * SETS_ROOM); - } - let start = self.writes.len(); - self.writes.extend(writes); - self.by_key.insert(key, self.sets.len()); - self.sets.push(CachedSet { - layout, - set, - writes: start..self.writes.len(), - }); - } - - /// Forget its sets, keeping its storage. - fn clear(&mut self) { - self.by_key.clear(); - self.sets.clear(); - self.writes.clear(); - } -} - -/// The hash a [`SetCache`] keeps a set of `layout` holding `writes` under: of what -/// [`SetWrite::same`] compares. -fn set_key(layout: vk::DescriptorSetLayout, writes: &[Write]) -> u64 { - use ash::vk::Handle; - use std::hash::Hasher; - let mut hasher = crate::key_hash::KeyHasher::default(); - hasher.write_u64(layout.as_raw()); - for write in writes { - hasher.write_u64(u64::from(write.binding) << 32 | u64::from(write.element)); - hasher.write_u64(write.ty.as_raw() as u64); - match write.info { - Info::Buffer(info) => { - hasher.write_u64(info.buffer.as_raw()); - hasher.write_u64(info.offset); - hasher.write_u64(info.range); - } - Info::Image(info) => { - hasher.write_u64(info.image_view.as_raw()); - hasher.write_u64(info.sampler.as_raw()); - hasher.write_u64(info.image_layout.as_raw() as u64); - } - Info::Texel(view) => hasher.write_u64(view.as_raw()), - } - } - hasher.finish() -} - -impl SetCache { - /// The kept set of `layout` that holds `writes` (set 0's), moved to the newer generation - /// where it was in the older one. - pub(super) fn find( - &mut self, - layout: vk::DescriptorSetLayout, - writes: &[Write], - ) -> Option { - let key = set_key(layout, writes); - let newer = &self.generations[self.newer]; - if let Some(at) = newer.find(key, layout, writes) { - return Some(newer.sets[at].set); - } - let older = &self.generations[1 - self.newer]; - let at = older.find(key, layout, writes)?; - let set = older.sets[at].set; - self.keep_under(key, (layout, set), writes); - Some(set) - } - - /// Keep `set`, of `layout`, as written with `writes` (set 0's), once its command recorded. - pub(super) fn keep( - &mut self, - layout: vk::DescriptorSetLayout, - set: vk::DescriptorSet, - writes: &[Write], - ) { - self.keep_under(set_key(layout, writes), (layout, set), writes); - } - - /// Keep the set in the newer generation under `key`: where it is full, it becomes the older - /// one first, the older one's sets forgotten. - fn keep_under( - &mut self, - key: u64, - set: (vk::DescriptorSetLayout, vk::DescriptorSet), - writes: &[Write], - ) { - if self.generations[self.newer].sets.len() >= SETS_KEPT { - self.newer = 1 - self.newer; - self.generations[self.newer].clear(); - } - self.generations[self.newer].keep(key, set, writes.iter().map(SetWrite::of)); - } -} - -/// A set 0 a command allocated and wrote (`EncoderCore::set_zero`), which its encoder keeps for -/// later commands once the command records (`EncoderCore::keep_set_zero`): a refused command's -/// set is never kept. -#[must_use] -pub(super) struct WrittenSet { - pub(super) layout: vk::DescriptorSetLayout, - pub(super) set: vk::DescriptorSet, -} - -/// The texel buffer view of `write`, a storage texel buffer's (`storage`) or a uniform one's. -fn texel_descriptor( - device: &Device, - command: &Command<'_>, - tables: &Tables<'_>, - write: &DescriptorWrite, - storage: bool, -) -> Result { - match &write.source { - WriteSource::TexelBuffer { slot, format, .. } => { - let texture = slot_texture(tables, *slot) - .ok_or_else(|| internal("the plan binds an unbound texture slot"))?; - // A swizzled texture buffer's reads take its swizzle in the function, under the - // slot's `TextureSwizzle` specialization; the plan refuses one at a slot whose stage - // does not apply it. - let texels = texture - .texels() - .ok_or_else(|| internal("a texel buffer write of a texture with an image"))?; - let place = (write.set, write.binding, write.array_element); - let range = command - .descriptor_ranges - .iter() - .find(|r| (r.set, r.binding, r.element) == place) - .ok_or_else(|| internal("a texel buffer write without its range"))? - .range; - // A part of a texture buffer wider than one view holds (`bind::texel_parts`). - if write.array_element > 0 { - device.shared().counts.thread().texel_buffer_parts_bound(); - } - texels.view(*format, storage, range) - } - WriteSource::Neutral(NeutralResource::TexelBuffer { format }) => { - device.neutral_texel_view(*format, storage) - } - // The planes of a two-plane YCbCr texture read in place (`texture/ycbcr_image.rs`). - WriteSource::YCbCrInPlace { slot } => { - let texture = slot_texture(tables, *slot) - .ok_or_else(|| internal("the plan binds an unbound texture slot's planes"))?; - device.shared().counts.thread().ycbcr_planes_bound(); - texture.planes_view() - } - // The rows of a shadowed 2D texture read and written in place - // (`texture/texel_rows.rs`). - WriteSource::TexelRows { slot, format } => { - let texture = slot_texture(tables, *slot) - .ok_or_else(|| internal("the plan binds an unbound texture slot's rows"))?; - device.shared().counts.thread().texel_rows_bound(); - texture.rows_view(*format, storage) - } - other => Err(unexpected(other)), - } -} - -/// The most sampler descriptions a [`BindMemo`] keeps. -const KEPT: usize = 8; - -/// The most views a [`BindMemo`] keeps: once full, it lets them all go and starts again. Each -/// is looked up by its key, so an encoder that binds more textures in turn than a short list -/// holds (a page's tiles) finds every one it bound before. -const KEPT_VIEWS: usize = 256; - -/// The image views and samplers render and compute encoders' last binds made or found -/// ([`image_descriptor`]), kept by everything each is a function of, so that a bind of the same -/// takes them again without working them out. A render encoder that ends gives its memo to its -/// device ([`SpareBindMemos`]), and the next render encoder opened takes it, so a pass that binds -/// the textures and samplers the one before it bound works none out; a compute encoder's goes on -/// with its kept bind state to the next compute encoder (`compute/live.rs`). Every other command -/// (an indirect command buffer's, a host step's, a tile dispatch's) binds with none. A memo holds -/// its textures, sampler states and host cells weakly, so it keeps none alive: -/// -/// - **A view** of a texture slot is a function of the texture (its storage, image, decoded and -/// twin and record are fixed as it is made, but for a shadow over host pages that moves in -/// place once, `texture/storage_form.rs`; its usage shadow is made once and kept), the face -/// it presents where it has two (`texture/faces.rs`, a key of its own each), the -/// view's description, whether the binding is a storage one, and its images' views, which an -/// image keeps once made until it lets them all go under its views lock (a rebind's or a -/// storage form's new `VkImage`, a detach's stand-in, a reattach, a shadow's move in place, -/// after which its views go with it). Each letting go counts in -/// `DeviceShared::views_epoch`: the views are kept while it holds, and all dropped once it -/// moves. A view is kept by its texture's address ([`KeptView`]), which stays the texture's -/// while the memo keeps the view: a texture found there is the one the view is of. -/// - **A sampler's description** (`sampler_desc`'s answer) for a sampler slot is a function of -/// the state bound (its descriptor and its LOD bias, fixed as it is made), the bind's LOD -/// clamps, the address-mode map the slot's textures give it, the facts `sampler_desc` takes -/// beside the device (the use: a comparison, an integer texture, a cube's explicit gradients; -/// the opaque black border; the image's format) and the device. It is kept by the state's -/// address ([`KeptSampler`]), which stays the state's while the memo keeps it, the clamps by -/// their bits, the map and the facts; and kept hashed (`sampler::HashedDesc`). The bind still -/// asks the state for its `VkSampler` of the description (`SamplerState::vk_sampler`), so the -/// state keeps and forgets its samplers as before. -#[derive(Default)] -pub(super) struct BindMemo { - /// The views epoch the views were kept under. - epoch: u64, - views: KeyMap, - samplers: Vec, - /// Where the buffers over host pages its binds' buffer descriptors named lay - /// (`buffer::KeptSpaces`). - spaces: KeptSpaces, -} - -/// What a view a bind made or found is a function of ([`BindMemo`]): a binding of the texture at -/// the address as the view, a storage one where the flag is set, read as [`SlotRead`] says, of the -/// face it presents (`texture/faces.rs`: 0 for a texture without faces). -type ViewKey = (usize, ImageViewDesc, bool, SlotRead, u8); - -/// How a slot binding reads its texture (`Tables::slot_read`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -enum SlotRead { - /// Its own image, or its shadow beyond its usage (`texture/usage_shadow.rs`). - Own, - /// Its copy, as it presents an attachment of the draw's instance (`texture/attached_reads.rs`). - Copy, - /// Its own image's levels apart from the attached ones (`render/attached_levels.rs`). - Levels(NarrowedLevels), -} - -impl SlotRead { - /// The view a binding `view` of `texture` by `call`, of the kind `storage`, reads so. - fn view( - self, - texture: &Texture, - call: &'static str, - view: &ImageViewDesc, - storage: bool, - ) -> Result { - match self { - SlotRead::Levels(levels) => texture.levels_view(call, view, levels.view), - read => texture.slot_view(call, view, storage, read == SlotRead::Copy), - } - } -} - -/// A view a [`BindMemo`] keeps, and its texture, held weakly: a texture that goes leaves its -/// allocation, and so its address, to its weak handles, so no other texture is at the address -/// while the view is kept. -struct KeptView { - texture: Weak, - raw: vk::ImageView, -} - -/// The most bind memos a device keeps for its render encoders to take: one per encoder open at -/// once beyond it starts empty. -const SPARE_BIND_MEMOS: usize = 4; - -/// A device's bind memos that ended render encoders left, which the render encoders it opens -/// next take ([`BindMemo`]): at most [`SPARE_BIND_MEMOS`], the latest given taken first. -#[derive(Default)] -pub(super) struct SpareBindMemos(Mutex>); - -impl SpareBindMemos { - /// The memo a render encoder opening takes: the latest an encoder gave back, else an empty - /// one. - pub(super) fn take(&self) -> BindMemo { - lock(&self.0).pop().unwrap_or_default() - } - - /// Keep `memo`, an ended render encoder's, for the next encoder to take, where fewer than - /// [`SPARE_BIND_MEMOS`] are kept; else it goes. - pub(super) fn give(&self, memo: BindMemo) { - let mut spare = lock(&self.0); - if spare.len() < SPARE_BIND_MEMOS { - spare.push(memo); - } - } -} - -/// A sampler description a bind worked out ([`BindMemo`]): `state`'s, bound with `clamps` -/// through `map` under `facts`. The state is held weakly: a state that goes leaves its -/// allocation, and so its address, to its weak handles, so no other state is at the address while -/// the description is kept. -struct KeptSampler { - state: Weak, - /// The bind's LOD clamps, by their bits. - clamps: Option<[u32; 2]>, - map: Option, - facts: SamplerFacts, - desc: HashedDesc, -} - -/// What `sampler_desc` takes of a binding beside its descriptor and the device. -#[derive(Clone, Copy, PartialEq, Eq)] -struct SamplerFacts { - use_: SamplerUse, - opaque_black: OpaqueBlackBorder, - format: Option, -} - -/// Keep `entry` at the front of `kept`, at most [`KEPT`] entries. -fn keep(kept: &mut Vec, entry: T) { - if kept.len() == KEPT { - kept.pop(); - } - kept.insert(0, entry); -} - -/// The image and sampler descriptor of `write`, a descriptor of type `ty` that is no buffer, for -/// a command (by `call`) over `tables`; the Vulkan samplers it names go to `samplers`. Views and -/// sampler descriptions are taken from `memo` where it keeps them. -fn image_descriptor( - call: &'static str, - device: &Device, - tables: &Tables<'_>, - write: &DescriptorWrite, - ty: vk::DescriptorType, - (samplers, memo): (&mut Vec>, Option<&mut BindMemo>), -) -> Result { - let image = |view: vk::ImageView| { - vk::DescriptorImageInfo::default() - .image_view(view) - .image_layout(vk::ImageLayout::GENERAL) - }; - // A slot a draw reads through a snapshot samples its texture's subresource that the - // instance's color attachment holds in the feedback loop layout, the layout its accesses - // there name (`render_target::moved_barriers`; "This layout is valid only for image - // subresources of images created with the VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT - // usage flag set", which `Texture::snapshot_color` checked); one whose snapshots lead its - // instance, in `GENERAL`, the leading instance's and its own. - let in_feedback = - |slot: SlotRef, info: vk::DescriptorImageInfo| match tables.feedback_slot(slot) { - true => info.image_layout(vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT), - false => info, - }; - // The kept views are dropped once an image of the device let its views go. - let (mut kept_views, mut kept_samplers) = match memo { - Some(memo) => { - let epoch = device.shared().views_epoch.load(Ordering::Acquire); - if memo.epoch != epoch { - memo.views.clear(); - memo.epoch = epoch; - } - (Some(&mut memo.views), Some(&mut memo.samplers)) - } - None => (None, None), - }; - // A texture whose image and usage lack the binding's usage binds its shadow - // (`texture/usage_shadow.rs`). - let mut texture_view = |slot: SlotRef, view: &ImageViewDesc, storage: bool| { - let texture = slot_texture(tables, slot) - .ok_or_else(|| internal("the plan binds an unbound texture slot"))?; - let read = tables.slot_read(texture, slot, storage); - let Some(kept_views) = kept_views.as_deref_mut() else { - device.shared().counts.thread().bind_view_worked_out(); - return read.view(texture, call, view, storage); - }; - let key = (texture.address(), *view, storage, read, texture.face()); - if let Some(kept) = kept_views.get(&key) { - debug_assert_eq!(kept.texture.as_ptr() as usize, key.0); - return Ok(kept.raw); - } - device.shared().counts.thread().bind_view_worked_out(); - let raw = read.view(texture, call, view, storage)?; - if kept_views.len() == KEPT_VIEWS { - kept_views.clear(); - } - let texture = texture.downgrade(); - kept_views.insert(key, KeptView { texture, raw }); - Ok::<_, Error>(raw) - }; - let mut sampler = |slot: SlotRef, use_: SamplerUse, opaque_black, format| { - let (state, clamps) = slot_sampler(tables, slot) - .ok_or_else(|| internal("the plan binds an unbound sampler slot"))?; - // Its address modes as the textures it samples map them. - let map = tables.sampler_maps.map(slot); - let facts = SamplerFacts { - use_, - opaque_black, - format, - }; - let bits = clamps.map(|clamps| clamps.map(f32::to_bits)); - let kept = kept_samplers.as_deref().and_then(|kept| { - kept.iter().find(|k| { - state.is(&k.state) && k.clamps == bits && k.map == map && k.facts == facts - }) - }); - let work_out = || { - let bound = bound_sampler(state, *clamps); - let descriptor = map.map_or(bound, |map| map.sampler(bound)); - let desc = metal2vulkan::bind::sampler_desc( - device.compile_device(), - &descriptor, - state.bound_use(use_), - opaque_black, - format, - ) - .map_err(Error::Bind)?; - Ok::<_, Error>(HashedDesc::new(desc)) - }; - let desc = match kept { - Some(kept) => { - // The kept description is the one the bind works out. - debug_assert_eq!(work_out().ok(), Some(kept.desc)); - kept.desc - } - None => { - device.shared().counts.thread().bind_sampler_worked_out(); - let desc = work_out()?; - if let Some(kept) = kept_samplers.as_deref_mut() { - let entry = KeptSampler { - state: state.downgrade(), - clamps: bits, - map, - facts, - desc, - }; - keep(kept, entry); - } - desc - } - }; - // A state its device's recovery carried past this generation: the neutral - // (`sampler.rs`). - let Some(owned) = state.vk_sampler(device, &desc)? else { - return device.neutral_sampler(use_.compare); - }; - let raw = owned.raw(); - samplers.push(owned); - Ok::<_, Error>(raw) - }; - let neutral_sampler = |kind: &NeutralResource| match *kind { - NeutralResource::Sampler { compare } => device.neutral_sampler(compare), - _ => Err(internal("a neutral sampler of a kind that is no sampler")), - }; - Ok(match &write.source { - WriteSource::Texture { slot, view } => in_feedback( - *slot, - image(texture_view( - *slot, - view, - ty == vk::DescriptorType::STORAGE_IMAGE, - )?), - ), - WriteSource::CombinedImageSampler { - image: source, - sampler: sampler_source, - } => { - let (view, format, slot) = match source { - ImageSource::Texture { slot, view } => ( - texture_view(*slot, view, false)?, - Some(view.format), - Some(*slot), - ), - ImageSource::Neutral(kind) => (device.neutral_view(*kind)?, kind.format(), None), - }; - let raw = match sampler_source { - SamplerSource::Slot { - slot, - compare, - integer, - opaque_black, - } => sampler( - *slot, - SamplerUse::new(*compare, *integer), - *opaque_black, - format, - )?, - SamplerSource::Immutable => vk::Sampler::null(), - SamplerSource::Neutral(kind) => neutral_sampler(kind)?, - }; - match slot { - Some(slot) => in_feedback(slot, image(view).sampler(raw)), - None => image(view).sampler(raw), - } - } - WriteSource::Sampler { - slot, - compare, - integer, - opaque_black, - } => vk::DescriptorImageInfo::default().sampler(sampler( - *slot, - SamplerUse::new(*compare, *integer), - *opaque_black, - None, - )?), - WriteSource::Neutral(kind @ NeutralResource::Image { .. }) => { - image(device.neutral_view(*kind)?) - } - WriteSource::Neutral(kind @ NeutralResource::Sampler { .. }) => { - vk::DescriptorImageInfo::default().sampler(neutral_sampler(kind)?) - } - WriteSource::Attachment { color_index } if ty == vk::DescriptorType::INPUT_ATTACHMENT => { - let (pass, views) = tables - .pass - .filter(|(pass, _)| pass.fetch_inputs) - .ok_or_else(|| internal("an input attachment outside a pass that reads them"))?; - let color = pass - .colors - .get(*color_index as usize) - .and_then(Option::as_ref) - .ok_or_else(|| { - internal("an input attachment of a color index without a texture") - })?; - // The framebuffer's view of the layers the draw renders. - let target = render_target::viewed(&color.target, views); - image(render_target::color_view(&target, true)?) - } - // A tile dispatch's scratch, viewed in the staging format. - WriteSource::TileAttachment { - color_index, - format, - .. - } if ty == vk::DescriptorType::STORAGE_IMAGE && tables.tile_scratch.is_some() => { - let scratch = tables - .tile_scratch - .and_then(|scratch| scratch.iter().find(|(color, _)| color == color_index)) - .map(|(_, target)| target) - .ok_or_else(|| internal("a tile attachment without its scratch"))?; - image(render_target::storage_view_in(scratch, *format)?) - } - // The attachment's own image, or its sample planes (`sample_planes.rs`), which the - // encoder made before the draw. - // Viewed in `view_alias` where the pipeline reads it so (an 8-bit sRGB attachment's - // codes, a BGRA-order one's RGBA-order twin), which the encoder made the image or planes - // mutable to (it held the view to `framebuffer_fetch::storage_view_format`, `render.rs`). - WriteSource::TileAttachment { - color_index, - format, - view, - view_alias, - } if ty == vk::DescriptorType::STORAGE_IMAGE && tables.pass.is_some() => { - let color = tables - .pass - .and_then(|(pass, _)| pass.colors.get(*color_index as usize)) - .and_then(Option::as_ref) - .filter(|color| color.target.format == *format) - .ok_or_else(|| internal("a storage attachment the pass does not have"))?; - let in_format = view_alias.unwrap_or(*format); - match view { - StorageAttachmentView::Attachment => { - image(render_target::storage_view_in(&color.target, in_format)?) - } - StorageAttachmentView::SamplePlanes { layers } => { - let planes = color - .planes - .as_ref() - .filter(|planes| planes.layers == *layers && planes.view == in_format) - .ok_or_else(|| internal("sample planes the pass does not have"))?; - image(planes.draw_view()?) - } - } - } - // The shader-side stencil's shadow, which the encoder made before the draw. - WriteSource::ShadowStencil if ty == vk::DescriptorType::STORAGE_IMAGE => { - match tables.shadow { - Some(shadow) => image(shadow), - None => return Err(internal("a shader-side stencil without its shadow")), - } - } - // The depth stand-in, which the encoder made before the draw. - WriteSource::DepthStandIn if ty == vk::DescriptorType::STORAGE_IMAGE => { - match tables.depth_stand_in { - Some(stand_in) => image(stand_in), - None => return Err(internal("a shader-side depth test without its stand-in")), - } - } - // The stencil's stand-in: the pass's shadow of the stencil, which the encoder made before - // the draw (`shadow_stencil.rs`). - WriteSource::StencilStandIn if ty == vk::DescriptorType::STORAGE_IMAGE => { - match tables.shadow { - Some(shadow) => image(shadow), - None => return Err(internal("a shader-side stencil test without its stand-in")), - } - } - // An extended-range color's `half` shadow, which the encoder made before the draw. - WriteSource::ExtendedShadow { color_index } if ty == vk::DescriptorType::STORAGE_IMAGE => { - match tables - .extended_shadows - .iter() - .find(|(color, _)| color == color_index) - { - Some(&(_, shadow)) => image(shadow), - None => return Err(internal("an extended-range color's shadow the pass lacks")), - } - } - // A slot's snapshot, which the encoder made before the draw, in `GENERAL`. - WriteSource::SnapshotTexels { slot } if ty == vk::DescriptorType::STORAGE_IMAGE => { - let view = tables - .snapshots - .and_then(|s| s.views.iter().find(|(at, _)| at == slot)) - .map(|&(_, view)| view); - match view { - Some(view) => image(view), - None => return Err(internal("a snapshot the draw did not take")), - } - } - // The pass's fragment imageblock storage, which the encoder made before the draw. - WriteSource::Imageblock if ty == vk::DescriptorType::STORAGE_IMAGE => { - match tables.imageblock { - Some(imageblock) => image(imageblock), - None => return Err(internal("a fragment imageblock without its storage")), - } - } - WriteSource::ArgumentSampler { - index, - compare, - integer, - } => match tables.argument_samplers.get(*index as usize) { - Some(state) => { - let desc = metal2vulkan::bind::sampler_desc( - device.compile_device(), - state.descriptor(), - state.bound_use(SamplerUse::new(*compare, *integer)), - OpaqueBlackBorder::Stated, - None, - ) - .map_err(Error::Bind)?; - let raw = match state.vk_sampler(device, &HashedDesc::new(desc))? { - Some(owned) => { - let raw = owned.raw(); - samplers.push(owned); - raw - } - // A state its device's recovery carried past this generation - // (`sampler.rs`). - None => device.neutral_sampler(*compare)?, - }; - vk::DescriptorImageInfo::default().sampler(raw) - } - // An element past the listed states: no handle names it. - None => vk::DescriptorImageInfo::default().sampler(device.neutral_sampler(*compare)?), - }, - // The planes of a two-plane YCbCr texture as the image the device's conversion samples - // (`texture/ycbcr_planes.rs`), its sampler the layout's immutable one of that conversion. - WriteSource::YCbCrPlanesImage { slot } - if ty == vk::DescriptorType::COMBINED_IMAGE_SAMPLER => - { - let texture = slot_texture(tables, *slot) - .ok_or_else(|| internal("the plan binds an unbound texture slot's planes image"))?; - let view = texture.planes_image_view()?; - device.shared().counts.thread().ycbcr_planes_image_bound(); - image(view) - } - _ => return Err(unexpected(&write.source)), - }) -} - -/// The refusal of a write source the runtime does not fill. -fn unexpected(source: &WriteSource) -> Error { - match source { - WriteSource::Imageblock - | WriteSource::TileAttachment { .. } - | WriteSource::ShadowStencil - | WriteSource::DepthStandIn - | WriteSource::StencilStandIn - | WriteSource::ExtendedShadow { .. } => { - Error::NotImplemented(RuntimeGap::RenderAttachments) - } - WriteSource::AccelerationStructure { .. } => { - Error::NotImplemented(RuntimeGap::AccelerationStructures) - } - _ => internal("a descriptor of a type that does not hold its write source"), - } -} - -/// The buffer descriptor of `write`. -/// Whether a buffer descriptor of `ty` is read-only to every shader that binds it: a uniform -/// buffer, whose block Vulkan and SPIR-V make read-only, so no store can reach it, or a uniform -/// texel buffer (a uniform view's texel form), which a shader only fetches. A storage buffer is -/// not, whatever a particular shader does with it. -/// -/// It decides which bindings may share the device's one neutral zero buffer (`neutral.rs`): a -/// writable binding keeps a region of its own, so nothing a shader stores is ever seen by another -/// command. Structural: the descriptor type alone, never a function or shader name. -fn read_only_buffer(ty: vk::DescriptorType) -> bool { - matches!( - ty, - vk::DescriptorType::UNIFORM_BUFFER - | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC - | vk::DescriptorType::UNIFORM_TEXEL_BUFFER - ) -} - -/// Whether `plan` binds a zero region of each command's own: at a writable buffer binding that -/// nothing is bound to ([`read_only_buffer`]), a fresh region of the command buffer's upload -/// arena at every draw (`write_info`). A draw drawn again as it was kept, or rebound, keeps the -/// kept draw's set-0 writes at every slot but those that changed (`rebind_into`), so it would -/// bind the kept draw's region, which that draw may have written: such a draw is not kept -/// (`render/draw_again.rs`), counted as one that may write (`WorkCounts::draws_unkept_writing`). -/// It walks every write of the plan, one for each resource its heap reaches in each heap array, -/// so a draw asks its plan's facts (`render/plan_facts.rs`), which hold the answer. -pub(super) fn binds_own_zeros(plan: &BindingPlan) -> bool { - #[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] - PLAN_WALKS.with(|walks| walks.set(walks.get() + plan.descriptors.len() as u64)); - plan.descriptors.iter().any(|write| { - let neutral = matches!( - write.source, - WriteSource::Neutral(NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. }) - ); - neutral && !read_only_buffer(write.ty.into()) - }) -} - -/// Count `write`, a buffer write of type `ty` for `command`, where it is a bound buffer's uniform -/// view written as a uniform buffer: by its slot's window (`WorkCounts::uniform_buffers_bound_to_16k`). -fn count_uniform_buffer( - device: &Device, - command: &Command<'_>, - write: &DescriptorWrite, - ty: vk::DescriptorType, -) { - let (WriteSource::Buffer { slot }, vk::DescriptorType::UNIFORM_BUFFER) = (&write.source, ty) - else { - return; - }; - let Some(extent) = command.extents.iter().find(|extent| extent.slot == *slot) else { - return; - }; - let len = match extent.window { - Window::Bounded { len, .. } => Some(len), - _ => None, - }; - device.shared().counts.thread().uniform_buffer_bound(len); -} - -/// The range `command` plans for its buffer write at `key` (set and binding). -fn planned_range(command: &Command<'_>, key: (u32, u32)) -> Result { - (command.descriptor_ranges.iter()) - .find(|r| (r.set, r.binding) == key) - .map(|r| r.range) - .ok_or_else(|| internal("a buffer write without its range")) -} - -/// The descriptor of `range` of `buffer`, where it lies read through `spaces` where given -/// (`buffer::KeptSpaces`), else read now (`Buffer::space_read`). A buffer's range is in the -/// buffer's space, which the bind state states it in (`ArgumentTable::stage_table`, -/// `tessellation.rs`): a heap buffer's starts at its offset in the heap's `VkBuffer`. -fn in_space( - buffer: &Buffer, - range: BufferRange, - spaces: Option<&mut KeptSpaces>, -) -> vk::DescriptorBufferInfo { - let (raw, start) = match spaces { - Some(spaces) => buffer.space_kept(spaces), - None => buffer.space_read(), - }; - vk::DescriptorBufferInfo::default() - .buffer(raw) - .offset(start + range.offset) - .range(range.range) -} - -/// The buffer descriptor of `write` where its source is a slot's: the buffer it binds, where it -/// lies read through `spaces` where given (`buffer::KeptSpaces`), or the call's copy of the bytes -/// it sets (whose planned range counts from the region's start), at the range `command` plans; -/// `None` for any other source. It takes nothing of the command buffer's state, so a draw rebound -/// at buffer slots locks none (`binding::rebind_into`). -fn slot_descriptor( - command: &Command<'_>, - tables: &Tables<'_>, - write: &DescriptorWrite, - spaces: Option<&mut KeptSpaces>, -) -> Result, Error> { - let range = || planned_range(command, (write.set, write.binding)); - Ok(Some(match &write.source { - WriteSource::Buffer { slot } => { - let (buffer, _) = slot_buffer(tables, *slot) - .ok_or_else(|| internal("the plan binds an unbound buffer slot"))?; - in_space(buffer, range()?, spaces) - } - WriteSource::InlineBytes { slot } => { - let bytes = slot_bytes(tables, *slot) - .ok_or_else(|| internal("the plan binds inline bytes the slot does not hold"))?; - let range = range()?; - if range.offset + range.range > bytes.region.len() { - return Err(internal("an inline-bytes range past the call's region")); - } - vk::DescriptorBufferInfo::default() - .buffer(bytes.region.raw()) - .offset(bytes.region.offset() + range.offset) - .range(range.range) - } - _ => return Ok(None), - })) -} - -fn descriptor( - device: &Device, - state: &mut State, - command: &Command<'_>, - tables: &Tables<'_>, - (write, spaces): (&DescriptorWrite, Option<&mut KeptSpaces>), -) -> Result { - let key = (write.set, write.binding); - let ty: vk::DescriptorType = write.ty.into(); - let bytes = || { - (command.descriptor_bytes.iter()) - .chain(command.heap_tables) - .find(|d| (d.set, d.binding) == key) - .map(|d| d.bytes.as_slice()) - .ok_or_else(|| internal("a table write without its bytes")) - }; - let whole = |upload: Upload| { - vk::DescriptorBufferInfo::default() - .buffer(upload.raw()) - .offset(upload.offset()) - .range(upload.len()) - }; - if let Some(info) = slot_descriptor(command, tables, write, spaces)? { - return Ok(info); - } - let ranged = - |buffer: &Buffer| Ok::<_, Error>(in_space(buffer, planned_range(command, key)?, None)); - let mut upload = |bytes: &[u8], len: u64| state.uploads.upload(device, bytes, len); - Ok(match &write.source { - WriteSource::TessellationFactors => { - let (buffer, _) = tables - .factors - .ok_or_else(|| internal("a tessellation factor write without a factor buffer"))?; - ranged(buffer)? - } - // The draw's patch index buffer, or zeros the control stage discards. - WriteSource::PatchIndices { min_bytes } => match tables.patch_indices { - Some((buffer, _)) => ranged(buffer)?, - None => whole(upload(&[], padded(*min_bytes as usize))?), - }, - // An emulated mesh draw's records and work buffer, whole: the draw's own regions, or the - // command buffer's records pool (`render/mesh.rs`). - WriteSource::MeshRecords => { - command - .mesh - .ok_or_else(|| internal("a mesh records write without the draw's dispatch"))? - .records - } - WriteSource::MeshWork => { - command - .mesh - .ok_or_else(|| internal("a mesh work write without the draw's dispatch"))? - .work - } - // An emulated tessellation draw's records and work buffer, whole: the draw's own - // regions, or the command buffer's records pool (`render/tessellation_scan.rs`). - WriteSource::TessellationRecords => { - command - .tessellation - .ok_or_else(|| internal("a tessellation records write without the draw's scan"))? - .records - } - WriteSource::TessellationWork => { - command - .tessellation - .ok_or_else(|| internal("a tessellation work write without the draw's scan"))? - .work - } - // A fan-out draw's region table, and a probe's flags (`render/fan_out.rs`). - WriteSource::RateMapRegions => { - command - .fan_out - .ok_or_else(|| internal("a region table write without the draw's fan-out"))? - .regions - } - WriteSource::RateMapFlags => command - .fan_out - .and_then(|fan| fan.flags) - .ok_or_else(|| internal("a probe's flags write without the probe's"))?, - // An indexed patch draw's control-point index buffer. - WriteSource::ControlPointIndices => { - let (buffer, _) = tables.control_point_indices.ok_or_else(|| { - internal("a control-point index write without a control-point index buffer") - })?; - ranged(buffer)? - } - // The pass's tile threadgroup memory, every tile's bytes. - WriteSource::TileMemory { bytes } => { - let buffer = tables - .tile_memory - .ok_or_else(|| internal("a tile memory write without the pass's tile memory"))?; - let (raw, start) = buffer.space(); - vk::DescriptorBufferInfo::default() - .buffer(raw) - .offset(start) - .range(*bytes) - } - WriteSource::ArgumentTable { .. } => { - let bytes = bytes()?; - whole(upload(bytes, padded(bytes.len()))?) - } - // A texture handle table: the device's, every live texture at its ID (`heap_sets.rs`). - WriteSource::HandleTable { .. } - if tables - .texture_table - .is_some_and(|table| table.at.contains(&key)) => - { - tables - .texture_table - .map(|table| table.info) - .ok_or_else(|| internal("a texture table gone"))? - } - // A sampler table: the device's, every live sampler state at its ID (`heap_sets.rs`). - WriteSource::HandleTable { .. } - if tables - .sampler_table - .is_some_and(|table| table.at.contains(&key)) => - { - tables - .sampler_table - .map(|table| table.info) - .ok_or_else(|| internal("a sampler table gone"))? - } - WriteSource::HandleTable { bytes_len, .. } => { - let bytes = bytes()?; - if bytes.len() != *bytes_len as usize { - return Err(internal("a handle table of another length than planned")); - } - let region = upload(bytes, padded(bytes.len()))?; - vk::DescriptorBufferInfo::default() - .buffer(region.raw()) - .offset(region.offset()) - .range(u64::from(*bytes_len)) - } - WriteSource::ConstantBlob { stage } => { - let blob = command - .blobs - .iter() - .find(|(of, _)| of == stage) - .map(|&(_, blob)| blob) - .ok_or_else(|| internal("a constant-blob write without its stage's blob"))?; - whole(upload(blob, padded(blob.len()))?) - } - // The command buffer's status words, the ones every command of it writes, on a device - // that does not address buffers (`status_address` elsewhere). - WriteSource::ExecutionStatus => whole(state.status_words(device)?), - // A read-only binding takes the device's kept zero buffer, made once for its lifetime - // (`neutral.rs`): zeros of a length the device's own limits fix cannot have changed since - // it was made, and before this every draw and dispatch that bound one took a fresh - // zero-filled region, each past half the upload arena's chunk and so a dedicated 64 KiB - // `VkBuffer` allocated and written to zero. A WRITABLE binding keeps its own region, as - // every binding did: the one buffer is shared by every command of the device, so a - // shader that could store through the binding would write zeros another command reads. - WriteSource::Neutral( - NeutralResource::ZeroBuffer { min_bytes } | NeutralResource::Sink { min_bytes }, - ) => { - let bytes = padded(*min_bytes as usize); - match read_only_buffer(ty) { - true => vk::DescriptorBufferInfo::default() - .buffer(device.neutral_zero_buffer(bytes)?) - .offset(0) - .range(bytes), - false => whole(upload(&[], bytes)?), - } - } - WriteSource::HeapEntry { .. } => { - return Err(Error::NotImplemented(RuntimeGap::ResourceHeap)) - } - // The bound sparse texture's tile map, whole. - WriteSource::TileMap { slot } => { - let buffer = slot_tile_map(tables, *slot)?; - let (raw, start) = buffer.space(); - vk::DescriptorBufferInfo::default() - .buffer(raw) - .offset(start) - .range(buffer.length()) - } - // The listed tables' words as they stand now, whole, written again as the command buffer - // commits. - WriteSource::FunctionTableSnapshot => { - let layout = function_table::snapshot_layout(device, tables.function_tables)?; - let bytes = function_table::snapshot_bytes(&layout, tables.function_tables)?; - let region = state.uploads.upload(device, &bytes, padded(bytes.len()))?; - let info = vk::DescriptorBufferInfo::default() - .buffer(region.raw()) - .offset(region.offset()) - .range(layout.byte_len()); - state.snapshot_tables(TableSnapshot::new( - region, - layout, - tables.function_tables.to_vec(), - )); - info - } - // A listed table's words, whole; an element past the list is the null table. The plan of - // tables that may pass `maxStorageBufferRange` reads them at their addresses instead where - // the device has device addresses. - WriteSource::FunctionTable { index } => match tables.function_tables.get(*index as usize) { - Some(table) => { - let len = table.words_len(); - let limit = device - .compile_device() - .profile() - .limits() - .max_storage_buffer_range; - if len > u64::from(limit) { - return Err(function_table::past_storage_buffer_range(device)); - } - let (raw, start) = table.words().space(); - vk::DescriptorBufferInfo::default() - .buffer(raw) - .offset(start) - .range(len) - } - None => whole(upload( - &[], - padded(FunctionTableWords::byte_len(0) as usize), - )?), - }, - other => return Err(unexpected(other)), - }) -} - -/// Upload `table` with a fresh sink's device address in its sink entry, at a 32-byte-aligned -/// device address, noted for its command buffer's resident set (`live_buffers.rs`), read by -/// functions that may write memory where `writes`; its device address. -fn root_table( - device: &Device, - state: &mut State, - table: &RootTable, - writes: bool, -) -> Result { - let no_address = || internal("a root table on a device without device addresses"); - let sink = state - .uploads - .upload(device, &[], u64::from(NeutralResource::SINK_BYTES))?; - let sink = sink.device_address().ok_or_else(no_address)?; - let mut bytes = table.bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - bytes - .get_mut(at..at + 8) - .ok_or_else(|| internal("a root table without a sink entry"))? - .copy_from_slice(&sink.to_le_bytes()); - let len = bytes.len() as u64; - let uploaded = state - .uploads - .upload_aligned(device, &bytes, len, RootTable::ENTRY_ALIGNMENT)?; - let address = uploaded.device_address().ok_or_else(no_address)?; - let noted = NotedTable { - upload: uploaded, - address, - }; - state.root_table(device, noted, table.resident_ranges(), writes)?; - Ok(address) -} - -/// What `command`, a command of `plan` over `tables`, uses, for the tracker: each bound buffer -/// the plan reads or writes, over the bytes the use reaches, each bound texture, over the levels -/// and slices it presents, and a draw's index buffer `index` and argument buffer `indirect` -/// (each with its offset), over the indices and arguments the draw reads (its index buffer's up -/// to where Metal's fetch stops reading it at most, `IndexBufferRef::fetch_end`: positions past -/// there read a zero-padded copy), in the stages the plan names and with the access types of its -/// class. The command's own uploads and the device's neutrals are fresh or never read back, so -/// nothing orders against them; a sampler is no resource. The uses of what the encoder made -/// resident (`UseTarget::Used`) come first. -pub(super) fn command_uses( - call: &'static str, - plan: &BindingPlan, - command: &Command<'_>, - tables: &Tables<'_>, - index: Option<(&Buffer, u64)>, - indirect: Option<(&Buffer, u64)>, -) -> Result { - let mut uses = CommandUses::default(); - uses_into( - call, - (plan, None, command, tables), - (index, indirect), - &mut uses, - )?; - Ok(uses) -} - -/// [`command_uses`] in `into`, over the last command's storage, where the caller keeps it -/// (`LiveBind::uses`): its uses of what the encoder made resident, and the keys they reach, kept -/// from the last command where that command's plan was `plan`, or a plan that lists the same uses -/// (as a pipeline state's plans for draws of different primitive types may), and its residency -/// of the generation `tables`' is. They are a function of those alone: each use's resource is the -/// residency's under its token, whose contents a generation names (`residency.rs`), its access -/// and stages the plan's, and its key and range the resource's own, which no call changes (a -/// resource's identity and length, a texture's levels and slices; `WorkCounts::resident_uses_made` -/// counts those made). Builds with debug assertions check those kept against the uses -/// [`command_uses`] makes whole, at their first uses after they were made and then at powers of -/// two (`kept_checks.rs`). -pub(super) fn command_uses_into( - call: &'static str, - (plan, command, tables): (&Arc, &Command<'_>, &Tables<'_>), - (index, indirect): (Option<(&Buffer, u64)>, Option<(&Buffer, u64)>), - into: &mut CommandUses, -) -> Result<(), Error> { - let kept = (&**plan, Some(plan), command, tables); - let keeps = uses_into(call, kept, (index, indirect), into)?; - #[cfg(debug_assertions)] - if keeps && into.of.as_mut().is_some_and(|of| of.checks.due()) { - // Made whole over the last check's storage: a draw's allocations are bounded in builds - // with debug assertions too (`runtime_lane::frame_costs`). None past the thread's - // thread-locals' end (a program's exit handler, `this_thread.rs`). - let checked = WHOLE_USES.try_with(|whole| { - let whole = &mut *whole.borrow_mut(); - let made = (&**plan, None, command, tables); - uses_into(call, made, (index, indirect), whole)?; - let same = (into.uses == whole.uses && into.sources == whole.sources) - && (into.used == whole.used && into.resident == whole.resident); - assert!( - same, - "a command kept uses of what the encoder made resident not its own" - ); - Ok::<_, Error>(()) - }); - if let Ok(checked) = checked { - checked?; - KEPT_RESIDENT_CHECKS.with(|checks| checks.set(checks.get() + 1)); - } - } - #[cfg(not(debug_assertions))] - let _: bool = keeps; - Ok(()) -} - -#[cfg(debug_assertions)] -thread_local! { - /// The commands whose uses of what the encoder made resident this thread kept (none, where - /// their plan lists none) and checked against those made whole ([`command_uses_into`]), in builds with debug assertions. - static KEPT_RESIDENT_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; - /// The uses [`command_uses_into`]'s check last made whole on this thread, whose storage its - /// next check makes them in ([`command_uses`]'s, as each is made for no kept plan). - static WHOLE_USES: std::cell::RefCell = - std::cell::RefCell::new(CommandUses::default()); -} - -/// How many commands' kept uses of what the encoder made resident this thread checked so far -/// ([`command_uses_into`]). -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn kept_resident_checks() -> u64 { - KEPT_RESIDENT_CHECKS.with(std::cell::Cell::get) -} - -/// What the uses of what an encoder made resident at the start of a [`CommandUses`] were made -/// for (`command_uses_into`): the plan (held weakly, so its allocation names no other plan while -/// this lives) and the residency's generation; and the other plans found to list the plan's -/// uses, or not to, held weakly likewise. -#[derive(Clone)] -struct ResidentOf { - plan: Weak, - generation: Option, - /// Held in place, so a command that switches plan allocates nothing for them: one whose - /// plan lists other uses makes its uses again, and its own `ResidentOf`. - compared: [Option<(Weak, bool)>; COMPARED_PLANS], - /// The commands that kept them since they were made, in builds with debug assertions - /// (`kept_checks.rs`). - #[cfg(debug_assertions)] - checks: KeptChecks, -} - -/// The most plans a [`ResidentOf`] keeps compared with its own: draws of one pipeline state whose -/// primitive types take plans of their own (Metal's five, `MTLPrimitiveType`) find each compared -/// once. -const COMPARED_PLANS: usize = 5; - -impl ResidentOf { - /// Whether its uses are those `plan` makes under `generation`: made for it, or, where they - /// hold some uses of what the encoder made resident (`resident`), for a plan that lists the - /// same uses (`BindingPlan::uses`, which with the residency decide them alone, - /// [`resident_uses_into`]), found once by comparing them. Where they hold none, making them - /// again for another plan walks its uses once, which costs less than that comparison: draws - /// that switch between pipeline states of no resident uses at every few draws compare none. - /// The plans are compared by address, which takes no count of their references. - fn holds(&mut self, plan: &Arc, generation: Option, resident: bool) -> bool { - let at = Arc::as_ptr(plan); - if self.generation != generation { - return false; - } - if self.plan.as_ptr() == at { - return true; - } - if !resident { - return false; - } - let found = (self.compared.iter().flatten()).find(|(of, _)| of.as_ptr() == at); - if let Some(&(_, alike)) = found { - return alike; - } - let alike = (self.plan.upgrade()).is_some_and(|made| made.uses == plan.uses); - if let Some(free) = self.compared.iter_mut().find(|slot| slot.is_none()) { - *free = Some((Arc::downgrade(plan), alike)); - } - alike - } -} - -/// [`command_uses`]' work in `into`: `kept` the plan's `Arc`, where `into` keeps the uses of -/// what the encoder made resident from one command to the next (`command_uses_into`). Whether it -/// kept them. -fn uses_into( - call: &'static str, - (plan, kept, command, tables): ( - &BindingPlan, - Option<&Arc>, - &Command<'_>, - &Tables<'_>, - ), - (index, indirect): (Option<(&Buffer, u64)>, Option<(&Buffer, u64)>), - into: &mut CommandUses, -) -> Result { - // One use at most a resource use of the plan's or the command's. - let resources = plan.uses.len() + command.uses.len(); - if u32::try_from(resources).is_err() { - return Err(internal("a command of 2^32 uses")); - } - let generation = tables.residency.map(Residency::generation); - let resident = into.used > 0; - let holds = |of: &mut ResidentOf| kept.is_some_and(|plan| of.holds(plan, generation, resident)); - into.made = 0; - let keeps = into.of.as_mut().is_some_and(holds); - match keeps { - true => { - into.uses.truncate(into.used); - into.sources.truncate(into.used); - } - false => { - into.of = None; - resident_uses_into(plan, tables, into)?; - into.of = kept.map(|plan| ResidentOf { - plan: Arc::downgrade(plan), - generation, - compared: Default::default(), - #[cfg(debug_assertions)] - checks: KeptChecks::default(), - }); - // Kept from one command to the next alone, so the identity of those kept alone - // (none where there are none: `prefix` reads it only where there are some). - if into.used > 0 { - into.prefix = match kept { - Some(_) => identity(), - None => 0, - }; - } - } - } - let CommandUses { - uses, - sources, - slots, - slots_listed, - others, - reaching, - named_now, - .. - } = into; - uses.reserve(others.len() + command.uses.len()); - // Listed by the first patch that asks (`patch_buffer_uses`). - slots.clear(); - *slots_listed = false; - // Every use but those names its resource (a descriptor, a root table's static, a view): - // the keys of `reaching` named are gathered. - named_now.clear(); - let plan_others = others.iter().map(|&at| (at, &plan.uses[at as usize])); - let commands = (command.uses.iter().enumerate()) - .map(|(at, resource)| ((plan.uses.len() + at) as u32, resource)); - for (source, resource) in plan_others.chain(commands) { - let Some(used) = other_use(call, resource, (index, indirect), tables)? else { - continue; - }; - if !reaching.is_empty() && reaching.contains(&used.key) { - named_now.push(used.key); - } - uses.push(used); - sources.push(source); - } - named_now.sort_unstable(); - named_now.dedup(); - into.settled = into.settle_resident(!keeps); - Ok(keeps) -} - -/// Make the uses of what the encoder made resident `plan` lists, as `tables` hold it, first in -/// `into`'s, emptied: their count, `made`, and of the buffers among them (reached by address) -/// the keys no texture use of them names, `reaching`; their stages, `prefix_stages`; and the -/// positions of the plan's other uses, `others`. -fn resident_uses_into( - plan: &BindingPlan, - tables: &Tables<'_>, - into: &mut CommandUses, -) -> Result<(), Error> { - let CommandUses { - uses, - sources, - used, - made, - others, - reaching, - prefix_stages, - .. - } = into; - uses.clear(); - sources.clear(); - others.clear(); - reaching.clear(); - *used = 0; - let mut named = BTreeSet::new(); - for (at, resource) in plan.uses.iter().enumerate() { - let UseTarget::Used(token) = resource.resource else { - others.push(at as u32); - continue; - }; - if !resource.access.read && !resource.access.write { - continue; - } - let stages: vk::PipelineStageFlags2 = resource.stages.into(); - if stages.is_empty() { - return Err(internal("a command's resource use in no stage")); - } - let access = |flags: vk::AccessFlags2, used: bool| match used { - true => Access::new(stages, flags), - false => Access::NONE, - }; - let buffer = match tables.used(token) { - Some(Used::Buffer(buffer)) => buffer, - Some(Used::Heap { bytes, .. }) => bytes, - Some(Used::IndirectCommandBuffer(icb)) => icb.storage(), - Some(Used::Texture(texture)) => { - // A texture whose writes Metal drops (`metal::format::writes_dropped`: the 4:2:2 - // formats, the subsampled and packed two-plane YCbCr ones) is its neutral in every - // heap storage array (`bind::heap`), which a function's writes through its handle - // reach, as a slot that only writes it takes its neutral. A command whose heap - // holds it at no element, no sampled array either, reaches none of its image and - // names no use of it: a kernel that only writes a two-plane YCbCr texture through - // an argument buffer converts none of its planes, and so announces no conversion - // of them (`ycbcr.rs`, `ycbcr-filter-not-exact`). - if writes_dropped(texture.pixel_format()) && !heap_holds(plan, token, None) { - continue; - } - let (read, write) = image_access(resource.class)?; - let (read, write) = ( - access(read, resource.access.read), - access(write, resource.access.write), - ); - // A 4:4:4 two-plane YCbCr texture a heap's float storage array holds through its - // write shadow (`bind::heap`), written: the shadow, whose copies clear its marks - // and encode the marked texels into the planes, and the texture's own image where - // the command reads it too. - let shadowed = resource.class == AccessClass::StorageImage - && resource.access.write - && texture.takes_ycbcr_writes(true) - && heap_holds(plan, token, Some(ImageAccess::Storage)); - if shadowed { - let used = texture.ycbcr_write_use("useResource:usage:", write)?; - named.insert(used.key); - uses.push(used); - sources.push(at as u32); - if read.is_empty() { - continue; - } - } - let used = match shadowed { - true => texture.bound_use(read, Access::NONE), - false => texture.bound_use(read, write), - }; - named.insert(used.key); - uses.push(used); - sources.push(at as u32); - continue; - } - None => return Err(internal("a use of a resource the encoder did not use")), - }; - let (read, write) = buffer_access(resource.class)?; - let accesses = ( - access(read, resource.access.read), - access(write, resource.access.write), - ); - let used = bytes_use(resource, buffer, 0, accesses); - reaching.insert(used.key); - uses.push(used); - sources.push(at as u32); - } - reaching.retain(|key| !named.contains(key)); - *used = uses.len(); - *made += uses.len(); - *prefix_stages = (uses.iter()).fold(vk::PipelineStageFlags2::empty(), |all, used| { - all | used.read.stages | used.write.stages - }); - Ok(()) -} - -/// Whether `plan` holds the texture it makes resident as token `token` at an element of a heap -/// array of `access` (a `WriteSource::HeapEntry` of such a class), or of any class where `None`. -/// In a storage array a 4:4:4 two-plane YCbCr texture is its write shadow's view (`bind::heap`), -/// which a stage of the plan writes. -fn heap_holds(plan: &BindingPlan, token: u32, access: Option) -> bool { - plan.descriptors.iter().any(|d| { - matches!( - d.source, - WriteSource::HeapEntry { - class: HandleClass::Image(class), - source: HeapSource::Used(used), - .. - } if used == token && access.is_none_or(|access| class.access == access) - ) - }) -} - -/// The use `resource`, a use of the plan's or the command's other than of a resource made -/// resident, makes as `tables` bind it, a draw's index buffer `index` and argument buffer -/// `indirect` (each with its offset): `None` for an unbound slot (a neutral, fresh for the -/// command), a sampler, or a use that neither reads nor writes. -fn other_use( - call: &'static str, - resource: &ResourceUse, - (index, indirect): (Option<(&Buffer, u64)>, Option<(&Buffer, u64)>), - tables: &Tables<'_>, -) -> Result>, Error> { - if !resource.access.read && !resource.access.write { - return Ok(None); - } - let stages: vk::PipelineStageFlags2 = resource.stages.into(); - if stages.is_empty() { - return Err(internal("a command's resource use in no stage")); - } - let access = |flags: vk::AccessFlags2, used: bool| match used { - true => Access::new(stages, flags), - false => Access::NONE, - }; - let (buffer, offset) = match resource.resource { - UseTarget::Slot(slot) => match slot.class { - SlotClass::Buffer => match slot_buffer(tables, slot) { - Some((buffer, offset)) => (buffer, *offset), - // An unbound slot reads a neutral, fresh for the command. - None => return Ok(None), - }, - SlotClass::Texture => { - // An unbound slot takes a neutral image; a texture whose image and usage lack - // the binding's usage, its shadow (`texture/usage_shadow.rs`), as does a draw's - // sampled one its instance renders (`texture/attached_reads.rs`). A two-plane - // YCbCr texture's planes read in place: their bytes, not the image, which - // converts for no such read (`texture/ycbcr_image.rs`). - let Some(texture) = slot_texture(tables, slot) else { - return Ok(None); - }; - if resource.class == AccessClass::YCbCrPlanes { - let read = vk::AccessFlags2::SHADER_SAMPLED_READ; - return texture - .planes_use(access(read, resource.access.read)) - .map(Some); - } - // A shadowed texture's rows read and written in place: their bytes, through a - // uniform or a storage texel buffer, not the shadow (`texture/texel_rows.rs`). - if resource.class == AccessClass::TexelRows { - use vk::AccessFlags2 as A; - let read = A::SHADER_SAMPLED_READ | A::SHADER_STORAGE_READ; - let write = A::SHADER_STORAGE_WRITE; - let read = access(read, resource.access.read); - let write = access(write, resource.access.write); - return texture.rows_use(read, write).map(Some); - } - // Any other slot binds the texture's image: a shadow left unmade is made here, - // before the command's copies are planned from its uses - // (`texture/lazy_shadow.rs`). - texture.made_for_use()?; - let (read, write) = image_access(resource.class)?; - let storage = resource.class == AccessClass::StorageImage; - let accesses = ( - access(read, resource.access.read), - access(write, resource.access.write), - ); - return match tables.slot_read(texture, slot, storage) { - SlotRead::Levels(levels) => { - let levels = levels.first..levels.view; - Ok(Some(texture.levels_use(levels, accesses))) - } - read => (texture.slot_use(call, storage, read == SlotRead::Copy, accesses)) - .map(Some), - }; - } - SlotClass::Sampler => return Ok(None), - }, - UseTarget::IndexBuffer => { - index.ok_or_else(|| internal("an index buffer use of a draw without one"))? - } - UseTarget::Indirect => { - indirect.ok_or_else(|| internal("an indirect use of a command without arguments"))? - } - UseTarget::TileMap(slot) => (slot_tile_map(tables, slot)?, 0), - // Only a plan lists one (`resident_uses_into`). - UseTarget::Used(_) => { - return Err(internal("a command's own use of a resource made resident")) - } - UseTarget::TessellationFactors => tables - .factors - .ok_or_else(|| internal("a tessellation factor use without a factor buffer"))?, - UseTarget::PatchIndices => tables - .patch_indices - .ok_or_else(|| internal("a patch index use of a draw without a buffer"))?, - UseTarget::ControlPointIndices => tables - .control_point_indices - .ok_or_else(|| internal("a control-point index use of a draw without a buffer"))?, - }; - let (read, write) = buffer_access(resource.class)?; - let accesses = ( - access(read, resource.access.read), - access(write, resource.access.write), - ); - Ok(Some(bytes_use(resource, buffer, offset, accesses))) -} - -/// The use `resource` makes of `buffer`'s bytes bound at `offset`, reading and writing as -/// `(read, write)`: its range from the offset (the buffer's rest where it states none; an index -/// buffer's up to its last whole index), as the buffer tracks it (`Buffer::tracked`). -#[inline] -fn bytes_use( - resource: &ResourceUse, - buffer: &Buffer, - offset: u64, - (read, write): (Access, Access), -) -> Use { - let range = match resource.range { - Some(range) => { - let start = offset.saturating_add(range.offset); - start..start.saturating_add(range.len) - } - None => offset..buffer.length().max(offset), - }; - let range = match resource.resource { - UseTarget::IndexBuffer => { - let end = IndexBufferRef::new(0, buffer.length()).fetch_end(range.start); - range.start..range.end.min(end).max(range.start) - } - _ => range, - }; - let (identity, range) = buffer.tracked(range); - Use { - key: identity.key, - tracked: identity.tracked, - range: UseRange::Bytes(range), - read, - write, - } -} - -/// Patch in `into`, as [`command_uses_into`] made it of `plan`'s and `command`'s uses, the uses -/// of the buffer slots `changed`, as the `stages`' tables now bind them, found by `into`'s list of -/// its uses of buffer slots (`CommandUses::slots`), looking at no other use, their positions into -/// `moved.0` and the uses into `moved.1`, both emptied first, in the list's order (every use a call -/// that changed those slots changed): whether it did, which it does -/// where each such slot binds the buffer it bound (its offset may have moved) and `into` holds the -/// uses that function made alone. Its uses are then those `command_uses_into` makes: every other -/// use is of a slot, buffer or texture no call changed, and the keys, so the resident ones, are -/// the same (`render/draw_again/rebound.rs`). The first patch after the uses were made lists them -/// ([`list_slot_uses`]); the patches after it, until they are made again, read that list. Builds -/// with debug assertions check the list against the uses, and count the uses it looked at -/// (`patched_slot_uses`). Where it patched, whether each use it patched in lies inside the bytes -/// of the use it replaced (`Use::covers`, or equals it), as a buffer offset moving along a buffer -/// reads; `None` where it did not. -pub(super) fn patch_buffer_uses( - (plan, command, stages): (&BindingPlan, &Command<'_>, &[(Stage, &ArgumentTable)]), - changed: &[SlotRef], - into: &mut CommandUses, - (moved_at, moved): (&mut Vec, &mut Vec>), -) -> Result, Error> { - moved_at.clear(); - moved.clear(); - if into.sources.len() != into.uses.len() { - return Ok(None); - } - if !into.slots_listed { - list_slot_uses((plan, command), into); - } - #[cfg(debug_assertions)] - { - slot_uses_listed((plan, command), into); - let looked = into.slots.len() as u64; - PATCHED_SLOT_USES.with(|patched| { - let (calls, walked) = patched.get(); - patched.set((calls + 1, walked + looked)); - }); - } - let CommandUses { - uses, - sources, - slots, - .. - } = into; - let mut inside = true; - for &(slot, at) in slots.iter() { - if !changed.contains(&slot) { - continue; - } - let at = at as usize; - let (Some(used), Some(&source)) = (uses.get_mut(at), sources.get(at)) else { - return Err(internal("a use of a buffer slot past the command's uses")); - }; - let source = source as usize; - let resource = match source.checked_sub(plan.uses.len()) { - None => plan.uses.get(source), - Some(at) => command.uses.get(at), - }; - let resource = resource.ok_or_else(|| internal("a use of a resource use since gone"))?; - let Some((buffer, offset)) = stage_buffer(stages, slot) else { - return Ok(None); - }; - // Its reads and writes are its resource use's, as the use made of it holds them. - let now = bytes_use(resource, buffer, *offset, (used.read, used.write)); - if now.key != used.key { - return Ok(None); - } - inside &= *used == now || used.covers(&now); - moved_at.push(at); - moved.push(now.clone()); - *used = now; - } - Ok(Some(inside)) -} - -/// Patch in `into`, as [`command_uses_into`] made it of `plan`'s uses and a command's of the same -/// kind, the uses made of the command's own (`Command::uses`: a draw's index buffer's), as -/// `command`'s and the draw's index buffer `index` (with its offset) now make them, their -/// positions and uses pushed onto `moved.0` and `moved.1` (in their order, after what those -/// hold): whether each lies inside the use it replaced (`Use::covers`), or `None` where they are -/// not those `command_uses_into` would make in their place (another count of them, another -/// resource or key), and the caller makes them whole. Every other use is the plan's, of slots, -/// buffers and textures no call changed, and the keys the same, so the resident ones are -/// (`render/draw_again/rebound.rs`). -pub(super) fn patch_command_uses( - (plan, command): (&BindingPlan, &Command<'_>), - index: Option<(&Buffer, u64)>, - into: &mut CommandUses, - (moved_at, moved): (&mut Vec, &mut Vec>), -) -> Result, Error> { - let CommandUses { uses, sources, .. } = into; - if sources.len() != uses.len() { - return Ok(None); - } - // The command's uses come last, each made of one of its own (`uses_into`), which each read. - let own = plan.uses.len(); - let made = (sources.iter().rev()).take_while(|&&source| source as usize >= own); - let first = sources.len() - made.count(); - if sources.len() - first != command.uses.len() { - return Ok(None); - } - let mut inside = true; - for (at, (used, resource)) in (uses[first..].iter_mut()).zip(command.uses).enumerate() { - let (UseTarget::IndexBuffer, Some((buffer, offset))) = (resource.resource, index) else { - return Ok(None); - }; - if sources[first + at] as usize != own + at { - return Ok(None); - } - // Its reads and writes are its resource use's, as the use made of it holds them. - let now = bytes_use(resource, buffer, offset, (used.read, used.write)); - if now.key != used.key { - return Ok(None); - } - inside &= *used == now || used.covers(&now); - moved_at.push(first + at); - moved.push(now.clone()); - *used = now; - } - Ok(Some(inside)) -} - -/// List in `into`, as [`command_uses_into`] made it of `plan`'s and `command`'s uses, each of its -/// uses of a buffer slot and its position (`CommandUses::slots`): every use past those of what the -/// encoder made resident (of no slot) of a resource use of a buffer slot. Listed at the first -/// patch ([`patch_buffer_uses`]) rather than as the uses are made: a draw whose uses are made -/// again at each draw, as one that binds another texture each time, lists none. Builds with debug -/// assertions count the uses it looked at (`listed_slot_uses`). -fn list_slot_uses((plan, command): (&BindingPlan, &Command<'_>), into: &mut CommandUses) { - let CommandUses { - sources, - slots, - slots_listed, - used, - .. - } = into; - slots.clear(); - // As many sources as uses (`patch_buffer_uses` checks). - for (at, &source) in sources.iter().enumerate().skip(*used) { - let source = source as usize; - let resource = match source.checked_sub(plan.uses.len()) { - None => plan.uses.get(source), - Some(at) => command.uses.get(at), - }; - let Some(resource) = resource else { - continue; - }; - if let UseTarget::Slot(slot) = resource.resource { - if slot.class == SlotClass::Buffer { - slots.push((slot, at as u32)); - } - } - } - *slots_listed = true; - #[cfg(debug_assertions)] - LISTED_SLOT_USES.with(|listed| { - let (calls, walked) = listed.get(); - listed.set((calls + 1, walked + (sources.len() - *used) as u64)); - }); -} - -/// Check that `into`, as [`command_uses_into`] made it of `plan`'s and `command`'s uses, lists -/// each of its uses of a buffer slot at its position (`CommandUses::slots`): every use past those -/// of what the encoder made resident (of no slot) of a resource use of a buffer slot. In builds -/// with debug assertions. -#[cfg(debug_assertions)] -fn slot_uses_listed((plan, command): (&BindingPlan, &Command<'_>), into: &CommandUses) { - let source = |at: usize| { - let source = into.sources[at] as usize; - match source.checked_sub(plan.uses.len()) { - None => plan.uses.get(source), - Some(at) => command.uses.get(at), - } - }; - let listed = (into.used..into.uses.len()).filter_map(|at| match source(at)?.resource { - UseTarget::Slot(slot) if slot.class == SlotClass::Buffer => Some((slot, at as u32)), - _ => None, - }); - assert!( - listed.eq(into.slots.iter().copied()), - "a command's uses of buffer slots other than it lists" - ); -} - -#[cfg(debug_assertions)] -thread_local! { - /// The calls of [`patch_buffer_uses`] that reached its uses on this thread, and the uses of - /// buffer slots they looked at, in builds with debug assertions. - static PATCHED_SLOT_USES: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; - /// The calls of [`list_slot_uses`] on this thread, and the uses they looked at, in builds - /// with debug assertions. - static LISTED_SLOT_USES: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; -} - -/// How many calls of [`patch_buffer_uses`] reached their uses on this thread so far, and how -/// many uses of buffer slots they looked at. -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn patched_slot_uses() -> (u64, u64) { - PATCHED_SLOT_USES.with(std::cell::Cell::get) -} - -/// How many calls of [`list_slot_uses`] this thread made so far, and how many uses they looked -/// at. -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn listed_slot_uses() -> (u64, u64) { - LISTED_SLOT_USES.with(std::cell::Cell::get) -} - -/// A dispatch's or draw's uses (`command_uses`), for the tracker, and the keys among them that -/// the command reaches through its root tables' resident set alone: buffers and heaps an encoder -/// made resident, which no use of the command names. The encoder's core takes both -/// (`EncoderCore::command_reaching`, `note_reaching`); a use added later names its key. The uses -/// of what the encoder made resident come first, kept from one draw to the next while their -/// inputs are the same (`command_uses_into`). -#[derive(Clone, Default)] -pub(super) struct CommandUses { - uses: Vec>, - resident: BTreeSet, - /// Of each use [`command_uses_into`] made, in order, the index among its plan's and command's - /// resource uses of the one it was made of: what [`patch_buffer_uses`] patches by. - sources: Vec, - /// Of each of those uses of a buffer slot, in order, the slot and the use's position, where - /// `slots_listed`: where [`patch_buffer_uses`] finds the uses of the slots a call changed, - /// looking at no other. Listed by the first patch after the uses were made - /// ([`list_slot_uses`]), so uses nothing patches, as those [`command_uses`] makes, list none. - slots: Vec<(SlotRef, u32)>, - /// Whether `slots` lists the uses' buffer slots: `false` once the uses are made again. - slots_listed: bool, - /// How many of `uses` and `sources`, first, are of what the encoder made resident, made for - /// `of` (`command_uses_into`); and how many of those the last call made (0 where it kept - /// them: `WorkCounts::resident_uses_made`). - used: usize, - made: usize, - /// The keys the last call moved into or out of `resident` - /// ([`settle_resident`](Self::settle_resident)). - settled: usize, - of: Option, - /// The positions among the plan's uses of those of anything but what the encoder made - /// resident, ascending. - others: Vec, - /// The keys of the buffers among those uses (reached by address) that none of them names: - /// `resident` is these but those the command's other uses name, `named`, as the last call - /// left them (sorted, each once), `named_now` this call's. - reaching: BTreeSet, - named: Vec, - named_now: Vec, - /// The keys a use added since the last call ([`push`](Self::push)) took out of `resident`, - /// which is `reaching` less `named` and these. - taken: Vec, - /// The identity of the uses of what the encoder made resident ([`ResidentPrefix`]), 0 where - /// they have none: given where [`command_uses_into`] made them, from [`IDENTITIES`]. - prefix: u64, - /// The identity and count of the uses of what the encoder made resident found to share no - /// memory with an attachment of a render pass of the layout of the version beside them - /// ([`apart_from`](Self::apart_from)). - apart: Option<(u64, usize, u64)>, - /// The identity of `resident` while the uses of what the encoder made resident have one - /// ([`ReachingPrefix`]): given where it was worked out again, from [`IDENTITIES`]. - resident_at: u64, - /// The pipeline stages of the uses of what the encoder made resident. - prefix_stages: vk::PipelineStageFlags2, -} - -/// The identities given to [`CommandUses`]' uses of what an encoder made resident, from 1: one of -/// the process's, whose uses no other has. -static IDENTITIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - -/// A new one of [`IDENTITIES`]. -fn identity() -> u64 { - IDENTITIES.fetch_add(1, Ordering::Relaxed) -} - -/// The uses of what an encoder made resident that come first among a draw's -/// ([`CommandUses::prefix`]), by identity: two draws' uses of the same identity begin with the same -/// `len` uses. What takes a draw's uses may take those of the last one's identity once. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct ResidentPrefix { - pub(super) id: u64, - pub(super) len: usize, -} - -/// A draw's [`ResidentPrefix`], with the identity of the keys it reaches through the resident set -/// alone (`resident`) and the stages of those uses ([`CommandUses::reaching_prefix`]): two draws' -/// of the same identities begin with the same uses and reach the same keys so. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(super) struct ReachingPrefix { - pub(super) prefix: ResidentPrefix, - pub(super) resident: u64, - pub(super) stages: vk::PipelineStageFlags2, -} - -impl CommandUses { - /// Add `used`, which names its key. - pub(super) fn push(&mut self, used: Use) { - if self.resident.remove(&used.key) { - self.taken.push(used.key); - } - self.uses.push(used); - } - - /// The uses of what the encoder made resident at its start, by identity; `None` where there - /// are none, or they have no identity (made by [`command_uses`]). - pub(super) fn prefix(&self) -> Option { - let prefix = ResidentPrefix { - id: self.prefix, - len: self.used, - }; - (prefix.len > 0 && prefix.id != 0).then_some(prefix) - } - - /// [`prefix`](Self::prefix), with the identity of the keys the uses reach through the resident - /// set alone and the prefix's stages (`ReachingPrefix`); `None` also where a use added since - /// those keys were worked out took one of them ([`push`](Self::push)). - pub(super) fn reaching_prefix(&self) -> Option { - let prefix = self.prefix()?; - let resident = self.resident_at; - let stages = self.prefix_stages; - (resident != 0 && self.taken.is_empty()).then_some(ReachingPrefix { - prefix, - resident, - stages, - }) - } - - /// How many uses at its start, of what the encoder made resident, were found to share no - /// memory with an attachment of a render pass of the layout of `version` - /// (`EncoderCore::degrade_attachment_reads`): its count of them where they are those of the - /// identity found ([`prefix`](Self::prefix)), else 0. - pub(super) fn apart(&self, version: u64) -> usize { - match (self.prefix(), self.apart) { - (Some(prefix), Some(apart)) if apart == (prefix.id, prefix.len, version) => prefix.len, - _ => 0, - } - } - - /// Note that its uses of what the encoder made resident share no memory with an attachment - /// of a render pass of the layout of `version` ([`apart`](Self::apart)). - pub(super) fn apart_from(&mut self, version: u64) { - self.apart = (self.prefix()).map(|prefix| (prefix.id, prefix.len, version)); - } - - /// How many uses of resources the encoder made resident the last call made: 0 where it kept - /// the last command's (`command_uses_into`). - pub(super) fn made(&self) -> usize { - self.made - } - - /// How many keys the last call moved into or out of those the command reaches through the - /// resident set alone ([`resident`](Self::resident)): 0 where they are the last command's. - pub(super) fn settled(&self) -> usize { - self.settled - } - - /// Set `resident` to `reaching` less `named_now`, which becomes `named`: worked out again - /// only where one of those changed (`made_again`: the uses of what the encoder made resident - /// were), or a use added since took a key out of it. Made whole from `reaching` only where it - /// is new; else only the keys that changed move, so a draw that names other keys of a large - /// resident set than the last one costs the keys named, not the set - /// (`WorkCounts::resident_keys_settled` counts the keys each way moves). - fn settle_resident(&mut self, made_again: bool) -> usize { - if !made_again && self.taken.is_empty() && self.named == self.named_now { - return 0; - } - let moved = match made_again { - true => { - self.resident.clone_from(&self.reaching); - self.taken.clear(); - self.reaching.len() - } - // `reaching` is the last call's: the keys the last call's other uses named, and those - // a use added since took, are each one of it, back in `resident`. - false => { - let back = self.named.len() + self.taken.len(); - self.resident.extend(self.named.iter().copied()); - self.resident.extend(self.taken.drain(..)); - back - } - }; - for key in &self.named_now { - self.resident.remove(key); - } - self.named.clone_from(&self.named_now); - // Their identity, where the uses of what the encoder made resident have one. - if self.used > 0 { - self.resident_at = match self.prefix { - 0 => 0, - _ => identity(), - }; - } - moved + self.named_now.len() - } - - /// Add each of `uses`, which name their keys. - pub(super) fn extend(&mut self, uses: impl IntoIterator>) { - for used in uses { - self.push(used); - } - } - - /// The keys the command reaches through the resident set alone. - pub(super) fn resident(&self) -> &BTreeSet { - &self.resident - } -} - -impl Deref for CommandUses { - type Target = [Use]; - - fn deref(&self) -> &[Use] { - &self.uses - } -} - -/// The read and write access types of a texture used as `class`. -fn image_access(class: AccessClass) -> Result<(vk::AccessFlags2, vk::AccessFlags2), Error> { - use vk::AccessFlags2 as A; - match class { - AccessClass::Sampled => Ok((A::SHADER_SAMPLED_READ, A::NONE)), - AccessClass::StorageImage => Ok((A::SHADER_STORAGE_READ, A::SHADER_STORAGE_WRITE)), - _ => Err(internal("a texture use of a class no texture slot has")), - } -} - -/// The read and write access types of a buffer used as `class`. -fn buffer_access(class: AccessClass) -> Result<(vk::AccessFlags2, vk::AccessFlags2), Error> { - use vk::AccessFlags2 as A; - match class { - AccessClass::Storage => Ok((A::SHADER_STORAGE_READ, A::SHADER_STORAGE_WRITE)), - AccessClass::Uniform => Ok((A::UNIFORM_READ, A::NONE)), - // A uniform view's texel form (`DescriptorView::UniformTexel`), a uniform texel buffer. - AccessClass::Sampled => Ok((A::SHADER_SAMPLED_READ, A::NONE)), - AccessClass::VertexInput => Ok((A::VERTEX_ATTRIBUTE_READ, A::NONE)), - AccessClass::Index => Ok((A::INDEX_READ, A::NONE)), - AccessClass::Indirect => Ok((A::INDIRECT_COMMAND_READ, A::NONE)), - _ => Err(internal("a buffer use of a class no buffer has")), - } -} diff --git a/crates/metal2vulkan-runtime/src/binding_view.rs b/crates/metal2vulkan-runtime/src/binding_view.rs deleted file mode 100644 index a1a7e6f17..000000000 --- a/crates/metal2vulkan-runtime/src/binding_view.rs +++ /dev/null @@ -1,198 +0,0 @@ -//! The Vulkan image views of a texture: what a binding write needs of a texture presenting a -//! [`ViewRecord`], from the binding plan's view. -//! -//! The view composes the record's Metal swizzle on the component mapping that presents the view -//! format's channels (`TextureSwizzleChannels::compose`): Metal applies a swizzle to the channels -//! the view's format gives, border texels included (measured on an Apple M3 Max and M4). A texture -//! whose alpha reads 1 (`TextureDescriptor::alpha_reads_one`) composes the swizzle that reads it so -//! ([`ViewRecord::sampled_swizzle`]), and is, to the binding plan, a texture of that swizzle: a -//! storage slot's function writes it unswizzled, which keeps the alpha it writes. Its usage is -//! restricted to what it serves (`VkImageViewUsageCreateInfo`), so a view format lacking the -//! image's other usages is valid. - -use super::image_plan::{block_family, compatible, ImagePlan}; -use super::pvrtc::holds_for_copies; -use super::view_plan::{ViewProblem, ViewRecord, ViewRefusal}; -use ash::vk; -use metal2vulkan::bind::{ImageViewDesc, TextureFacts}; -use metal2vulkan::device::FormatUsage; -use metal2vulkan::error::{Capability, Feature, Unsupported}; -use metal2vulkan::metal::TextureUsage; -use metal2vulkan::vk::{ - ComponentMapping, Format, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, ImageViewType, -}; - -/// The facts a binding plan reads of a texture presenting `record`. -pub(super) fn texture_facts(record: &ViewRecord) -> TextureFacts { - let mut facts = TextureFacts::new(record.texture_type, record.pixel_format); - facts.sample_count = record.samples; - facts.usage = record.usage; - facts.array_length = record.array_length(); - facts.mipmap_level_count = record.level_count; - // A texture whose alpha reads 1 is read through the swizzle that reads it so. - facts.swizzle = record.sampled_swizzle(); - // A slot a constexpr sampler samples compiles under the map (`VariantKey::address_maps`). - facts.address_modes = record.address_mode_map; - // Metal's texel-offset rule reads the base-level size of the texture whose levels a view - // presents (`SpecKey::OffsetBaseAxes`): the image's. - facts.parent_relative_level = record.base_level; - facts.parent_base_size = record.image_extent; - facts -} - -/// Whether a view of `image` may have format `view`: the image's own format, a listed one, or, -/// for an image that takes any compatible format, one of its compatibility class (`family`: the -/// two Metal formats are of one compressed family, which block-compressed formats need). -pub(super) fn views_as(image: &ImagePlan, view: Format, family: bool) -> bool { - if view == image.format { - return true; - } - if !image.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) { - return false; - } - if image.view_formats.is_empty() { - compatible(image.format, view, family) - } else { - image.view_formats.contains(&view) - } -} - -/// A Vulkan image view of a texture: the key of the texture's view cache. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct VkView { - pub(super) view_type: ImageViewType, - pub(super) format: Format, - pub(super) components: ComponentMapping, - pub(super) aspect: ImageAspectFlags, - pub(super) base_level: u32, - pub(super) level_count: u32, - pub(super) base_layer: u32, - pub(super) layer_count: u32, - /// What the view serves (`VkImageViewUsageCreateInfo`), so a view format lacking the image's - /// other usages is valid. - pub(super) usage: ImageUsageFlags, -} - -impl VkView { - /// The `VkImageViewCreateInfo` of this view of `image`, with its usage chained through - /// `usage` (caller storage). - pub(super) fn create_info<'a, 'b>( - &self, - image: vk::Image, - usage: &'a mut vk::ImageViewUsageCreateInfo<'b>, - ) -> vk::ImageViewCreateInfo<'a> { - *usage = vk::ImageViewUsageCreateInfo::default().usage(self.usage.into()); - vk::ImageViewCreateInfo::default() - .image(image) - .view_type(self.view_type.into()) - .format(self.format.into()) - .components(self.components.into()) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: self.aspect.into(), - base_mip_level: self.base_level, - level_count: self.level_count, - base_array_layer: self.base_layer, - layer_count: self.layer_count, - }) - .push_next(usage) - } -} - -/// The view a binding write needs of a texture whose image is `image` and which presents -/// `record`: `desc` is the binding plan's view of the record's facts, and `storage` says the -/// write is a storage image's. -/// -/// A record whose usage lacks what the binding needs (`ShaderWrite` for a storage image, -/// `ShaderRead` for a sampled one) is bound where the image has the usage, as plain Metal writes -/// and reads such a texture (an M4 under macOS 27.0.1: a write to a `ShaderRead` texture stores, a -/// read of a `ShaderWrite` one reads, and a swizzled view, whose usage Metal strips of -/// `ShaderWrite`, is written through; its validation stops each): the image has it where the -/// texture's usage asked for it, or where adding it cost the image nothing -/// (`Device::with_undeclared_usage`). -/// -/// Refusals: where the image lacks the usage, the texture's usage lacking it too -/// (`NotImplemented(UndeclaredTextureUsage)`, the runtime's gap), the image being a carrier that -/// serves copies alone (`NotImplemented(Format)` naming the texture's format: a PVRTC, ETC2, EAC -/// or 4:2:2 texture without a decoded twin, `pvrtc.rs`) or the device lacking the usage for the -/// format (`Unsupported{Format}`); a view format the image cannot take -/// (`NotImplemented(TextureView)`); a swizzle on a storage image, whose view Vulkan cannot swizzle -/// (`NotImplemented(TextureSwizzle)`), but where the binding plan's function applies it -/// (`ImageViewDesc::shader_swizzle`: a swizzled texture or view at a storage slot, whose reads the -/// function swizzles and whose writes it unswizzles, or one the function only queries, which no -/// swizzle reaches; and the sampled view of a swizzled extended-range texture, whose decoded texels -/// the function swizzles), which leaves a texture made resident for a function reading handles, or -/// a `ulong` atomic's slot. -pub(super) fn binding_view( - image: &ImagePlan, - record: &ViewRecord, - desc: &ImageViewDesc, - storage: bool, -) -> Result { - let (usage, metal, format_usage) = if storage { - ( - ImageUsageFlags::STORAGE, - TextureUsage::SHADER_WRITE, - FormatUsage::StorageImage, - ) - } else { - ( - ImageUsageFlags::SAMPLED, - TextureUsage::SHADER_READ, - FormatUsage::SampledImage, - ) - }; - if !image.usage.contains(usage) && !record.usage.contains(metal) { - return Err(ViewRefusal::Unsupported(Unsupported::not_implemented( - Feature::UndeclaredTextureUsage, - ))); - } - // A carrier serves copies alone (`pvrtc.rs`): a binding reaches it only where no decoded twin - // serves the texture's reads, which is the format's gap, not the view format's. - if !image.usage.contains(usage) && holds_for_copies(image) { - return Err(ViewRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(record.pixel_format), - )); - } - if !image.usage.contains(usage) { - return Err(ViewRefusal::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { - format: desc.format, - usage: format_usage, - }, - ))); - } - let family = block_family(record.pixel_format) == block_family(image.pixel_format); - if !views_as(image, desc.format, family) { - return Err(ViewRefusal::Unsupported(Unsupported::not_implemented( - Feature::TextureView, - ))); - } - // A view whose function applies the texture's swizzle takes none (a storage view; an - // extended-range texture's sampled view). - let components = match desc.shader_swizzle { - true => desc.components, - false => record.sampled_swizzle().compose(desc.components), - }; - if storage && components != ComponentMapping::IDENTITY { - return Err(ViewRefusal::Unsupported(Unsupported::not_implemented( - Feature::TextureSwizzle, - ))); - } - let (base_level, level_count) = match desc.level { - Some(level) if level < record.level_count => (record.base_level + level, 1), - Some(_) => return Err(ViewProblem::LevelRange.into()), - None => (record.base_level, record.level_count), - }; - Ok(VkView { - view_type: desc.view_type, - format: desc.format, - components, - aspect: desc.aspect, - base_level, - level_count, - base_layer: record.base_layer, - layer_count: record.layer_count, - usage, - }) -} diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs deleted file mode 100644 index ae2638c46..000000000 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ /dev/null @@ -1,829 +0,0 @@ -//! `BlitCommandEncoder` (`MTLBlitCommandEncoder`) and its buffer commands; the texture commands are -//! step 5's (`blit_texture.rs`). -//! -//! - **Order.** A blit encoder runs its commands in encoded order over every resource: each command -//! goes through [`BlitCommandEncoder::command`] with what it reads and writes, which records the -//! barrier those uses need after the encoder's earlier commands. -//! - **Copies.** `vkCmdCopyBuffer` copies any byte range, as Metal's copy does. Metal moves -//! overlapping ranges of one buffer as `memmove` does (measured), while Vulkan forbids them, so -//! such a copy goes through a scratch buffer. -//! - **Fills.** `vkCmdFillBuffer` writes only whole 32-bit words at offsets that are multiples of -//! 4, while Metal fills any byte range with one byte value: [`fill_pieces`] splits a fill into -//! the words and the at most 3 bytes before and after them, which are copied from 4 bytes of the -//! value ([`fill_word`]) in a small pattern buffer of the encoder. The words go as one -//! `vkCmdFillBuffer` (`word_fill.rs`). -//! - **Heap shadows** (`shadow.rs`). A heap's texture held as a shadow of the heap's bytes (a -//! depth or stencil texture, or one of a heap over host pages, `texture/heap.rs`), and a tiled -//! texture of more than one level over a buffer's bytes (`Buffer::new_tiled_texture`), is an -//! image to a blit: a command that uses its image copies it in from the bytes first where the -//! encoder has not, and what a command writes through it is copied back by `shadow.rs`'s rules, -//! as the encoder ends at the latest; a tiled texture's copy is taken at use and never copied -//! back (`shadow.rs`'s **Copies taken at use**). A copy that writes every texel such a texture's -//! bytes hold (of a one-level, one-slice one) replaces them (`shadow::overwritten`): it takes no -//! copy in and no keep. A blit writes one destination, so none writes such a texture's bytes -//! two ways. - -use super::blit_fill::FillTiles; -use super::buffer::Buffer; -use super::command_buffer::CommandBuffer; -use super::copy_run::CopyRun; -use super::degradation::Degradation; -use super::encoder::{EncoderCore, HeldCore, Replayed}; -use super::encoder_fold::Joining; -use super::error::{invalid, CopyQueueProblem, Error, Problem}; -use super::fresh_unwritten::FreshRead; -use super::managed_copy::{AtCompletion, CopyBack, Staging, SyncTarget}; -use super::managed_sync::{SyncCopy, Target}; -use super::replay::{BlitCall, CallLog, Replay, Resource}; -use super::resource::{ResourceKey, ResourceRef}; -use super::shadow::{self, Covered, ShadowCopies}; -use super::texture::Texture; -use super::tracker::{Access, Use, UseRange}; -use super::used_resources::EncoderKind; -use super::values::{ResourceOptions, StorageMode}; -use crate::device::functions::Vk; -use ash::vk; -use std::ops::Range; -use std::sync::Arc; - -/// How a fill writes a byte range. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub(super) struct FillPieces { - /// The bytes before the words, fewer than 4. - pub(super) head: Range, - /// The whole 32-bit words at multiples of 4, for `vkCmdFillBuffer`; empty when the range holds - /// none. - pub(super) words: Range, - /// The bytes after the words, fewer than 4. - pub(super) tail: Range, -} - -/// The pieces of a fill of the bytes `range` (offsets in the `VkBuffer`). -pub(super) fn fill_pieces(range: Range) -> FillPieces { - if range.is_empty() { - return FillPieces::default(); - } - // The first word boundary in the range (or its end), and the last one at or after it. - let words_start = range - .start - .checked_next_multiple_of(4) - .map_or(range.end, |at| at.min(range.end)); - let words_end = (range.end / 4 * 4).max(words_start); - FillPieces { - head: range.start..words_start, - words: words_start..words_end, - tail: words_end..range.end, - } -} - -/// The 32-bit word whose four bytes are all `value`: `vkCmdFillBuffer`'s data, and the copy source -/// of a fill's head and tail. -pub(super) fn fill_word(value: u8) -> u32 { - u32::from_ne_bytes([value; 4]) -} - -/// Every blit command runs in the transfer stage. -pub(super) const TRANSFER: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::TRANSFER; - -/// A blit command's read of `range` of `buffer`. -pub(super) fn reads(buffer: &Buffer, range: Range) -> Use { - reads_by( - buffer, - range, - Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ), - ) -} - -/// A blit command's write of `range` of `buffer`. -pub(super) fn writes(buffer: &Buffer, range: Range) -> Use { - writes_by( - buffer, - range, - Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE), - ) -} - -/// A blit command's read of `range` of `buffer` as `read` (a copy of rows that dispatches reads -/// in a shader, `row_copies.rs`). -pub(super) fn reads_by(buffer: &Buffer, range: Range, read: Access) -> Use { - let (identity, range) = buffer.tracked(range); - Use::reads(identity.key, identity.tracked, UseRange::Bytes(range), read) -} - -/// A blit command's write of `range` of `buffer` as `write` ([`reads_by`]). -pub(super) fn writes_by(buffer: &Buffer, range: Range, write: Access) -> Use { - let (identity, range) = buffer.tracked(range); - Use::writes( - identity.key, - identity.tracked, - UseRange::Bytes(range), - write, - ) -} - -/// `offset..offset + size` when it lies in a buffer of `length` bytes. -pub(super) fn bytes_in( - call: &'static str, - offset: u64, - size: u64, - length: u64, -) -> Result, Error> { - match offset.checked_add(size) { - Some(end) if end <= length => Ok(offset..end), - _ => Err(out_of_bounds(call, offset, size, length)), - } -} - -/// The refusal of `size` bytes from `offset` past a buffer of `length` bytes. -fn out_of_bounds(call: &'static str, offset: u64, size: u64, length: u64) -> Error { - invalid( - call, - Problem::RangeOutOfBounds { - offset, - size, - length, - }, - ) -} - -/// One region of `vkCmdCopyBuffer`. -fn region(source: u64, destination: u64, size: u64) -> vk::BufferCopy { - vk::BufferCopy { - src_offset: source, - dst_offset: destination, - size, - } -} - -/// The pattern buffer's length: 4 bytes of each byte value. -const PATTERN_LENGTH: u64 = 4 * 256; - -/// A blit encoder (`MTLBlitCommandEncoder`): `Send`, not `Sync`; `end_encoding` consumes it. Its commands run in encoded -/// order, over every resource. -pub struct BlitCommandEncoder { - core: EncoderCore, - /// 4 bytes of each byte value at offset `4 * value`, the source of an unaligned fill's ends; - /// made at the encoder's first such fill and retained at its end. - pattern: Option, - /// The copies of the heap shadows among the textures the encoder's blits named - /// ([`BlitCommandEncoder::see`]), each once. - shadows: Vec>, - /// Its calls so far (`replay.rs`), which encode it again at a rebind of a buffer over host - /// pages it named, or at a commit whose failure fails some of its group's encoders and not it - /// (`encoder_fold.rs`): `None` where it logs nothing (encoding again). - log: Option>, - /// The protection options it was made under where they end Metal's process at its first - /// command (`command_buffer/protection.rs`): each command is refused. - aborts: Option, - /// The tiles its plain color fills cleared, which its later ones copy from again - /// (`blit_fill.rs`). An encoding again starts with none, so it clears them again. - fill_tiles: FillTiles, - /// Its buffer copies not yet recorded, which later copies between the same two buffers join - /// as one `vkCmdCopyBuffer` (`copy_run.rs`): recorded before its next other command, and at - /// its end. - run: Option, -} - -impl std::fmt::Debug for BlitCommandEncoder { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BlitCommandEncoder") - } -} - -impl CommandBuffer { - /// `blitCommandEncoder`. Refused while another encoder of this command buffer is open, - /// after one was abandoned, and after commit. - pub fn blit_command_encoder(&self) -> Result { - let _for = self.notices_for(); - // It joins the group of compute and blit encoders before it, recording into their - // `VkCommandBuffer`, where it may (`encoder_fold.rs`); and it logs its calls - // (`replay.rs`), which encode it again at a rebind of a buffer over host pages it named, - // or at a commit whose failure fails some of its group's encoders and not it. - // The protection options it dies under at its first command, as Metal's process ends - // there, read under the core's one lock of the state. - let (core, aborts) = EncoderCore::open( - self, - "blit_command_encoder", - EncoderKind::Blit, - (true, Some(Joining::Blit)), - |state| state.protection_aborts(), - )?; - Ok(BlitCommandEncoder { - core, - pattern: None, - shadows: Vec::new(), - log: Some(self.device().shared().scheduler.spare_logs().blit()), - aborts, - fill_tiles: FillTiles::default(), - run: None, - }) - } -} - -impl BlitCommandEncoder { - /// An encoder that encodes an ended one of `command_buffer` again (`replay.rs`): it logs - /// nothing. - pub(super) fn replaying(command_buffer: &CommandBuffer) -> Result { - Ok(BlitCommandEncoder { - core: EncoderCore::replaying(command_buffer, true)?, - pattern: None, - shadows: Vec::new(), - log: None, - aborts: None, - fill_tiles: FillTiles::default(), - run: None, - }) - } - - /// End an encoder made by [`replaying`](Self::replaying): what it recorded. - pub(super) fn finish_replay(self) -> Result { - let BlitCommandEncoder { - mut core, - pattern, - mut run, - .. - } = self; - core.flush_copies(&mut run); - if let Some(pattern) = pattern { - core.retain(pattern); - } - core.finish_replay() - } - - /// Run `run`, a command, logged first as `call` makes it of the log, where the encoder logs - /// (`replay.rs`): where it is refused, its log notes it so (`CallLog::refuse`), and an - /// encoding again refuses it again and goes on. Refused before it is logged, for every - /// command, where the encoder was made under protection options that end Metal's process at - /// its first command (`Invalid`, `Problem::ProtectedEncoder`, `command_buffer/protection.rs`). - pub(super) fn logged( - &mut self, - call: impl FnOnce(&mut CallLog) -> BlitCall, - run: impl FnOnce(&mut Self) -> Result, - ) -> Result { - self.logged_after(true, call, run) - } - - /// [`logged`](Self::logged), the encoder's run of buffer copies recorded first where - /// `flush` (`copy_run.rs`): every command but a buffer copy, which may join it. - fn logged_after( - &mut self, - flush: bool, - call: impl FnOnce(&mut CallLog) -> BlitCall, - run: impl FnOnce(&mut Self) -> Result, - ) -> Result { - let _call = self.core.begin_call(); - let _for = self.core.notices_for(); - self.refuse_aborted()?; - if flush { - self.core.flush_copies(&mut self.run); - } - let copies = self.core.command_buffer().for_copies(); - let at = match self.log.as_mut().filter(|log| !log.muted()) { - Some(log) => { - let call = call(log); - // A queue made for copies takes buffer copies and fills alone, refused before - // they are logged (an encoder made fresh logs every call it takes). - if let (true, Err(name)) = (copies, call.on_copy_engine()) { - let problem = Problem::CopyQueue(CopyQueueProblem::Command); - return Err(invalid(name, problem)); - } - let extra = call.extra(); - Some(log.push(call, extra)) - } - None => None, - }; - let ran = run(self); - if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.log) { - log.refuse(at); - } - ran - } - - /// Refuse a command where the encoder was made under protection options that end Metal's - /// process at its first command (`Invalid`, `Problem::ProtectedEncoder`, - /// `command_buffer/protection.rs`): a command whose first step comes before its log. - pub(super) fn refuse_aborted(&self) -> Result<(), Error> { - match self.aborts { - Some(options) => Err(invalid( - "blit_command_encoder", - Problem::ProtectedEncoder { options }, - )), - None => Ok(()), - } - } - - /// Refuse `call` over `buffers` on a queue made for copies where the copy engine's family - /// does not share one of them: a buffer the caller made not concurrent with that family - /// (`Invalid`, `CopyQueueProblem::Buffer`, `Device::new_command_queue_for_copies`). - fn refuse_unshared(&self, call: &'static str, buffers: &[&Buffer]) -> Result<(), Error> { - let unshared = buffers.iter().any(|buffer| !buffer.copy_engine_shares()); - match unshared && self.core.command_buffer().for_copies() { - true => Err(invalid(call, Problem::CopyQueue(CopyQueueProblem::Buffer))), - false => Ok(()), - } - } - - /// Run `call`, a public call one of the encoder's own makes, unlogged: the call that makes - /// it is logged, and encoded again makes it again. - pub(super) fn unlogged(&mut self, call: impl FnOnce(&mut Self) -> T) -> T { - if let Some(log) = &mut self.log { - log.mute(true); - } - let made = call(self); - if let Some(log) = &mut self.log { - log.mute(false); - } - made - } - - /// The encoder's core. - pub(super) fn core(&mut self) -> &mut EncoderCore { - &mut self.core - } - - /// The tiles its plain color fills keep (`blit_fill.rs`). - pub(super) fn fill_tiles(&mut self) -> &mut FillTiles { - &mut self.fill_tiles - } - - /// Record one blit command that reads and writes `uses`: the copies into the heap shadows - /// it uses that the encoder has not copied in, and the barrier the uses need after the - /// encoder's earlier commands, then the command through `record`. Every blit command goes - /// through here once its checks passed, and its uses name every byte it touches, untracked - /// memory's too (`EncoderCore::command_named`). Refused only as `EncoderCore::plan_shadows` - /// is, for a merge, which no blit needs (the module docs). - pub(super) fn command( - &mut self, - uses: &[Use], - record: impl FnOnce(&Vk, vk::CommandBuffer), - ) -> Result<(), Error> { - self.command_in(TRANSFER, uses, record) - } - - /// [`command`](Self::command) for a blit command that runs in `stages`: a multisampled copy - /// by draws (`sample_copy.rs`) also renders. - pub(super) fn command_in( - &mut self, - stages: vk::PipelineStageFlags2, - uses: &[Use], - record: impl FnOnce(&Vk, vk::CommandBuffer), - ) -> Result<(), Error> { - self.command_in_reading(stages, uses, (&[], &[]), record) - } - - /// [`command`](Self::command) of a blit command that reads the boxes `reads` of its source - /// texture (`FreshUnwritten::reads`): a new texture's unwritten pattern is announced only - /// where a box reaches it (`EncoderCore::command_named`); and writes every texel of the - /// boxes `covered` of its destination's image: a heap shadow whose every texel they cover - /// takes no copy in and no keep, its copy back moving what the command wrote - /// (`shadow::overwritten`). - pub(super) fn command_reading( - &mut self, - uses: &[Use], - boxes: (&[FreshRead], &[Covered]), - record: impl FnOnce(&Vk, vk::CommandBuffer), - ) -> Result<(), Error> { - self.command_in_reading(TRANSFER, uses, boxes, record) - } - - /// [`command_in`](Self::command_in) reading the boxes `reads` and writing every texel of - /// the boxes `covered` ([`command_reading`](Self::command_reading)). - pub(super) fn command_in_reading( - &mut self, - stages: vk::PipelineStageFlags2, - uses: &[Use], - (reads, covered): (&[FreshRead], &[Covered]), - record: impl FnOnce(&Vk, vk::CommandBuffer), - ) -> Result<(), Error> { - // After the copies of the encoder's run, which records first (`copy_run.rs`). - self.core.flush_copies(&mut self.run); - let mut shadows = shadow::copies_used(self.shadows.iter(), uses); - shadow::overwritten(&mut shadows, uses, covered); - let copies = self.core.plan_shadows(&shadows, uses)?; - self.core.shadow_copies(&copies); - self.core.command_named(stages, uses, reads, record); - self.core.shadows_used(&shadows, uses, &[]); - Ok(()) - } - - /// [`command`](Self::command) of a buffer copy, `copy` (its source, its destination and its - /// region) with `uses`, which joins the encoder's run of copies where it may - /// (`EncoderCore::copy_joining`, `copy_run.rs`): the copies into the heap shadows its uses - /// name go first, as for any command, and none joins a run past them. - fn copy_joining( - &mut self, - uses: &[Use], - copy: (vk::Buffer, vk::Buffer, vk::BufferCopy), - ) -> Result<(), Error> { - let mut shadows = shadow::copies_used(self.shadows.iter(), uses); - shadow::overwritten(&mut shadows, uses, &[]); - let copies = self.core.plan_shadows(&shadows, uses)?; - if !copies.is_empty() { - self.core.flush_copies(&mut self.run); - } - self.core.shadow_copies(&copies); - self.core.copy_joining(uses, copy, &mut self.run); - self.core.shadows_used(&shadows, uses, &[]); - Ok(()) - } - - /// Note `texture`, which a blit names: where it is a heap shadow or a tiled texture of more - /// than one level, whose image the blit uses (a texture over a buffer blits on its bytes, - /// `blit_texture.rs`, `Texture::blit_texels`), its commands take its copies. - pub(super) fn see(&mut self, texture: &Texture) { - if texture.blit_texels().is_some() { - return; - } - if let Some(copies) = texture.shadow() { - if !self.shadows.iter().any(|seen| Arc::ptr_eq(seen, copies)) { - self.shadows.push(Arc::clone(copies)); - } - } - } - - /// `copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:`: `size` bytes, at any - /// offsets, as on Metal. - /// - /// Overlapping ranges of one buffer are moved as `memmove` moves them, as Metal does, and so - /// are those of two no-copy buffers made over the same bytes, which lie in one `VkBuffer`. - /// Vulkan forbids such a copy, so it costs more: a scratch buffer of `size` bytes outside the - /// Metal address space, cleared by a fill this call waits for, and a second copy of the range - /// through it. - /// - /// A size of 0 copies nothing, wherever its offsets lie, and the encoder's other commands - /// run, as plain Metal does (Metal's validation stops it). - /// - /// Consecutive copies of the encoder between the same two buffers that need no barrier between - /// them (none reads or writes what an earlier one of the run wrote, nor writes what it read) - /// are one `vkCmdCopyBuffer` of a region each (`WorkCounts::buffer_copies_merged`). The - /// encoder's hazard order keeps eight ranges of a buffer and then one span from the lowest - /// byte of any to the highest, so a copy into that span of the earlier copies' destinations - /// takes a barrier and starts a new run: sort copies by destination offset (a picture's rows - /// in order, tile beside tile) to merge them all. - /// - /// A no-copy source buffer is read past its length to the end of its host pages, the - /// caller's bytes, as plain Metal reads them (its validation stops it). - /// - /// Refused (`Invalid`): a range past either buffer (but that read), a buffer of another - /// device. - pub fn copy_from_buffer_to_buffer( - &mut self, - source_buffer: &Buffer, - source_offset: u64, - destination_buffer: &Buffer, - destination_offset: u64, - size: u64, - ) -> Result<(), Error> { - // A copy may join the encoder's run of copies (`copy_run.rs`). - self.logged_after( - false, - |_| { - BlitCall::CopyBufferToBuffer( - source_buffer.clone(), - source_offset, - destination_buffer.clone(), - destination_offset, - size, - ) - }, - |this| { - const CALL: &str = "copy_from_buffer_to_buffer"; - this.core.check_device(CALL, source_buffer.generation())?; - this.core - .check_device(CALL, destination_buffer.generation())?; - this.refuse_unshared(CALL, &[source_buffer, destination_buffer])?; - if size == 0 { - return Ok(()); - } - // A no-copy buffer's source reads its pages past its length. - let from = bytes_in(CALL, source_offset, size, source_buffer.copy_reach()) - .map_err(|_| { - out_of_bounds(CALL, source_offset, size, source_buffer.length()) - })?; - let to = bytes_in(CALL, destination_offset, size, destination_buffer.length())?; - // A source whose GPU writes are dropped is read in place through its read twin, - // where it has one (`read_twin.rs`). - let twin = this.core.read_source(source_buffer); - let source_buffer = twin.as_ref().unwrap_or(source_buffer); - // Read as a blit's: a no-copy buffer's import released while idle is imported again - // (`host_residency.rs`). - let (source, source_at) = this.core.blit_at(source_buffer, source_offset)?; - let (destination, destination_at) = - this.core.blit_at(destination_buffer, destination_offset)?; - // One buffer's bytes, or two no-copy buffers' made over the same bytes, which lie - // in one import (`host_aliases.rs`): one `VkBuffer` from one byte 0. - let one_bytes = source == destination - && source_at - source_offset == destination_at - destination_offset; - let overlap = one_bytes && from.start < to.end && to.start < from.end; - if overlap { - let scratch = this - .core - .device() - .own_buffer(size, ResourceOptions::private())?; - let (through, through_at) = scratch.at(0); - this.command( - &[reads(source_buffer, from), writes(&scratch, 0..size)], - |device, raw| { - // SAFETY: the encoder's command buffer is recording; the buffers are - // live and retained until it completes, and the regions lie inside - // them. - unsafe { - device.cmd_copy_buffer( - raw, - source, - through, - &[region(source_at, through_at, size)], - ); - } - }, - )?; - this.command( - &[reads(&scratch, 0..size), writes(destination_buffer, to)], - |device, raw| { - // SAFETY: as above. - unsafe { - device.cmd_copy_buffer( - raw, - through, - destination, - &[region(through_at, destination_at, size)], - ); - } - }, - )?; - this.core.retain(scratch); - this.core - .device() - .degrade(Degradation::OverlappingBufferCopy, || { - let object = format!( - "a copy of {size} bytes from offset {source_offset} to offset \ - {destination_offset} of one buffer" - ); - ( - object, - "the ranges overlap, which Vulkan's copy forbids".to_owned(), - ) - }); - } else { - // One region of the run of copies between the two buffers, where it joins - // (`copy_run.rs`); the regions do not overlap. - let uses = [reads(source_buffer, from), writes(destination_buffer, to)]; - let copy = (source, destination, region(source_at, destination_at, size)); - this.copy_joining(&uses, copy)?; - } - Ok(()) - }, - ) - } - - /// `fillBuffer:range:value:`: every byte of `range` becomes `value`, for any range, as on - /// Metal. - /// - /// The range's whole words are filled as one `vkCmdFillBuffer` (`word_fill.rs`); the at most - /// 3 bytes at each end are copied from the encoder's pattern buffer (1 KiB, made at its first - /// unaligned fill). - /// - /// An empty range fills nothing, wherever it lies, and the encoder's other commands run, as - /// plain Metal does (Metal's validation stops it). - /// - /// Refused (`Invalid`): a range past the buffer, a buffer of another device. - pub fn fill_buffer( - &mut self, - buffer: &Buffer, - range: Range, - value: u8, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::FillBuffer(buffer.clone(), range.clone(), value), - |this| { - const CALL: &str = "fill_buffer"; - this.core.check_device(CALL, buffer.generation())?; - this.refuse_unshared(CALL, &[buffer])?; - let size = range.end.saturating_sub(range.start); - if size == 0 { - return Ok(()); - } - let range = bytes_in(CALL, range.start, size, buffer.length())?; - let metal = (range.start, range.end); - // The words and ends are the `VkBuffer`'s: a no-copy buffer's start in it need not - // be a multiple of 4 (`Buffer::base`). Read as a blit's (`host_residency.rs`). - let (destination, start) = this.core.blit_at(buffer, range.start)?; - let pieces = fill_pieces(start..start + size); - let mut uses = vec![writes(buffer, range)]; - let pattern = if pieces.head.is_empty() && pieces.tail.is_empty() { - None - } else { - let pattern = this.pattern()?; - let at = 4 * u64::from(value); - uses.push(reads(&pattern, at..at + 4)); - Some(pattern.at(at)) - }; - let split = pattern.is_some(); - let owner = this.core.device().clone(); - this.command(&uses, |device, raw| { - let ends = [&pieces.head, &pieces.tail]; - let ends = ends.iter().filter(|end| !end.is_empty()); - let from = pattern.map_or(0, |(_, at)| at); - let regions: Vec = ends - .map(|end| region(from, end.start, end.end - end.start)) - .collect(); - // SAFETY: the encoder's command buffer is recording; the buffers are live and - // retained until it completes; the words start and end at multiples of 4 inside - // the buffer, and the ends' regions lie inside both buffers. - unsafe { - if let Some((pattern, _)) = pattern { - device.cmd_copy_buffer(raw, pattern, destination, ®ions); - } - crate::word_fill::record( - &owner, - raw, - destination, - pieces.words.clone(), - fill_word(value), - ); - } - })?; - if split { - this.core - .device() - .degrade(Degradation::SplitBufferFill, || { - let object = - format!("a fill of bytes {}..{} of a buffer", metal.0, metal.1); - let reason = format!( - "they lie at bytes {start}..{} of the buffer's VkBuffer, and Vulkan fills only \ - whole 4-byte words at multiples of 4", - start + size - ); - (object, reason) - }); - } - Ok(()) - }, - ) - } - - /// The encoder's pattern buffer, made on first use: 4 bytes of each byte value at offset - /// `4 * value`, written through its mapping (host-coherent write-combined `Shared` memory, - /// seen by the device at the commit's submission). - fn pattern(&mut self) -> Result { - if let Some(pattern) = &self.pattern { - return Ok(pattern.clone()); - } - let pattern = self.core.device().write_combined_buffer(PATTERN_LENGTH)?; - let Some(contents) = pattern.mapped_contents() else { - return Err(Error::Vulkan(super::error::VkResultCode( - vk::Result::ERROR_MEMORY_MAP_FAILED.as_raw(), - ))); - }; - let bytes: Vec = (0..=u8::MAX).flat_map(|value| [value; 4]).collect(); - // SAFETY: the mapping covers the buffer's `PATTERN_LENGTH` bytes, which nothing else uses - // yet. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; - self.pattern = Some(pattern.clone()); - Ok(pattern) - } - - /// `synchronizeResource:`: the CPU sees the GPU's writes to a `Managed` resource once the - /// command buffer completes. Every command buffer ends with a barrier to the host. On a device - /// with unified memory a managed buffer is host-coherent memory the GPU uses itself, and a - /// texture's CPU access copies from its image, so nothing more is recorded. On one without, a - /// managed buffer's bytes, or a texture's over one, are copied to its host copy, which - /// `contents` maps (`managed.rs`), after the encoder's earlier commands: those the GPU wrote - /// since the buffer's last copy out, every other byte holding there what the GPU's copy holds - /// (`managed_sync.rs`), all of them where those writes are not known. - /// - /// On a resource of another storage mode it records nothing, as plain Metal does (RT2 - /// `managed.synchronize.shared`, `.private`: `Shared` and `Private` buffers - /// and textures; Metal's validation stops it). - /// - /// Refused (`Invalid`): a resource of another device. - pub fn synchronize_resource(&mut self, resource: ResourceRef<'_>) -> Result<(), Error> { - self.logged( - |_| BlitCall::SynchronizeResource(Resource::one(resource)), - |this| { - const CALL: &str = "synchronize_resource"; - this.core.check_device(CALL, resource.device())?; - if resource.storage_mode() != StorageMode::Managed { - return Ok(()); - } - match resource { - ResourceRef::Buffer(buffer) => { - this.synchronize_bytes(buffer, 0..buffer.length()) - } - ResourceRef::Texture(texture) => this.synchronize_texels(texture), - ResourceRef::IndirectCommandBuffer(_) => Ok(()), - } - }, - ) - } - - /// The copy of a `Managed` texture's bytes over a buffer to the buffer's host copy, for - /// `synchronize_resource` and `synchronize_texture`: where the GPU or the CPU finds the texels - /// (an IOSurface plane's two layouts), in the buffer's memory, past its length too where that - /// holds them (`Texels::kept`). Those past it lie in the texture's `Shared` tail, which takes - /// no synchronization (`buffer_texture.rs`), and a texture of an image alone takes none, its - /// CPU access copying from its image. - pub(super) fn synchronize_texels(&mut self, texture: &Texture) -> Result<(), Error> { - let Some(texels) = texture.buffer_texels() else { - return Ok(()); - }; - let span = texels.span(); - let end = span.end.min(texels.kept()); - self.synchronize_bytes(&texels.buffer, span.start.min(end)..end) - } - - /// The copy of `range` of a `Managed` buffer's own bytes to its host copy, which `contents` - /// maps (`managed.rs`), after the encoder's earlier commands, of the bytes the GPU wrote since - /// the buffer's last copy out (`managed_sync.rs`); nothing where it has none (a device with - /// unified memory) or the range is empty. - fn synchronize_bytes(&mut self, buffer: &Buffer, range: Range) -> Result<(), Error> { - let Some(host) = buffer.host_copy() else { - return Ok(()); - }; - if range.is_empty() { - return Ok(()); - } - let device = self.core.device().clone(); - let own = buffer.at(range.start); - let bytes = range.end - range.start; - // A two-copy buffer over the caller's pages (`managed_copy.rs`): the range the program - // asked, which the command copies out of. - if buffer.caller_copy().is_some() { - (device.shared().counts).managed_asked(bytes, false); - } - let read = reads(buffer, range.clone()); - let (to, uses) = match host { - SyncTarget::Own(host) => (Target::Own(host), vec![read]), - // A blit's copy into the buffer over the caller's pages, their import - // (`managed_copy.rs`): a write of them, as a copy into a no-copy buffer. - SyncTarget::Import(import) => { - let (host, at) = self.core.blit_at(&import, range.start)?; - ( - Target::Import(host, at), - vec![read, writes(&import, range.clone())], - ) - } - // Pages no import maps: a copy into a staging buffer, which the command buffer's - // completion copies into them (`managed_copy.rs`). - SyncTarget::Pages(pages) => { - let staging = Staging::new(&device, bytes)?; - let uses = vec![read, writes(&staging.buffer, 0..bytes)]; - self.core.retain_shared(staging.buffer.held()); - (Target::Pages(CopyBack::new(staging, pages)), uses) - } - }; - let copy = Arc::new(SyncCopy::new(&device, buffer, range, own, to)); - // Its completion copies a staging buffer into the pages and lets go of what it took. - (self.core.command_buffer()).at_completion(AtCompletion::Synced(Arc::clone(©))); - // The heap shadows over the bytes it reads, copied back first, as for any command. - let mut shadows = shadow::copies_used(self.shadows.iter(), &uses); - shadow::overwritten(&mut shadows, &uses, &[]); - let copies = self.core.plan_shadows(&shadows, &uses)?; - self.core.shadow_copies(&copies); - self.core.sync_out(TRANSFER, &uses, ©); - self.core.shadows_used(&shadows, &uses, &[]); - self.core.retain_shared(buffer.held()); - Ok(()) - } - - /// `label`: the label [`set_label`](Self::set_label) gave it, or `None`, as Metal's is `nil` - /// until set. - pub fn label(&self) -> Option { - self.core.command_buffer().open_encoder_label() - } - - /// `setLabel:`: label it `label`, which its command buffer's ended encoders keep - /// ([`CommandBuffer::ended_encoders`](crate::CommandBuffer::ended_encoders)) and the - /// runtime's notices naming the command buffer state, as [`CommandBuffer::set_label`](crate::CommandBuffer::set_label)'s. - pub fn set_label(&mut self, label: &str) { - self.core.command_buffer().label_open_encoder(label); - } - - /// `endEncoding`. - pub fn end_encoding(self) -> Result<(), Error> { - let _for = self.core.notices_for(); - // The core's shadows copy back what the blits wrote through heap shadows. The fill tiles - // are their command buffer's, which holds them until it completes. - let BlitCommandEncoder { - mut core, - pattern, - shadows: _, - log, - aborts: _, - fill_tiles: _, - mut run, - } = self; - let _call = core.begin_call(); - core.flush_copies(&mut run); - if let Some(pattern) = pattern { - core.retain(pattern); - } - EncoderCore::end_with_replay( - HeldCore(core), - EncoderKind::Blit, - (None, None), - log.map(Replay::Blit), - None, - ) - } -} diff --git a/crates/metal2vulkan-runtime/src/blit_fill.rs b/crates/metal2vulkan-runtime/src/blit_fill.rs deleted file mode 100644 index 37dcada01..000000000 --- a/crates/metal2vulkan-runtime/src/blit_fill.rs +++ /dev/null @@ -1,1735 +0,0 @@ -//! Metal's private texture fills: `fillTexture:level:slice:region:bytes:length:` -//! ([`BlitCommandEncoder::fill_texture`]) and `fillTexture:level:slice:region:color:` with and -//! without `pixelFormat:` ([`BlitCommandEncoder::fill_texture_color`]), Apple SPI the runtime -//! takes as plain Metal answers it. -//! -//! **Metal's answer** (an Apple M4 under macOS 27.0.1, our own probes; every byte of every level, -//! slice and aspect read back after one fill over bytes of `0xEE`, 112 formats, one case a -//! process; and an Apple M3 Max under macOS 27.0.1, our probes `surface.m`, `tp.m`, `ds.m` and -//! `misc.m`, every byte of the surface, buffer or texture read back). A fill writes the pattern, -//! cut at a unit's bytes or repeated to them, into every unit of the region, and leaves every -//! other byte: -//! - a **compressed** format's unit is a block: the region's origin and size count blocks, cut at -//! the level's blocks (74 formats, PVRTC at square power-of-two extents); -//! - every other format's unit is a texel, and the region counts texels, cut at the level: an -//! ordinary color or depth format's texel (31 formats); a 4:2:2 format's 2 bytes (`GBGR422`, -//! `BGRG422`, at bytes `2x` and `2x + 1` of a row, which the 4:2:2 copies move); a stencil -//! format's 1 byte (`Stencil8`, `X32Stencil8`, an `X32_Stencil8` view's too); `Depth32Float_Stencil8`'s 4 depth bytes, its -//! stencil kept; -//! - a **two-plane YCbCr** texture over a surface's plane (every one of the 24 formats the runtime -//! makes, over plane 0 of `420v` to `x444` and plane 1 of the 4:2:2 and 4:4:4 surfaces) has -//! the plane's code as its unit, 1 byte or 2 (a 10-bit code's word), at the plane's rows, the -//! other plane kept, as its blits move it; a **packed** one's (`YCBCR10_420_2P_PACKED` to -//! `YCBCR10_444_2P_PACKED_sRGB`, over `p420` to `p444`) every fill writes one zero byte at each -//! texel's `x` of its row of the plane, whatever the pattern or color; -//! - a **padded 10-bit** texture (`R10Unorm_X6`, `RG10Unorm_X12` and their `_sRGB` twins, each -//! code in the top bits of its own 16-bit word) has its 2 or 4 bytes as its unit, at its rows; -//! - a **two-plane extended-range** texel (`RGB10A8_2P_XR10` and its sRGB twin) is its color word -//! in plane 0, 4 bytes, its alpha kept. Metal writes row `y` of the region `⌊4 w / 16⌋ · 16` -//! bytes apart (16 below a width of 4), its texel `x` at byte `4 x` of it, `w` level 0's width, -//! at any level, the region cut at the level's extent: where a heap's bytes hold the texture's -//! first level (a 1D, 2D, 1D or 2D array or 3D texture of any level count, -//! `texture/heap_two_planes.rs`), the fill writes those bytes there, rows overlapping included, -//! an array's slice `align(h · align(4 w, 16), 128)` bytes past the texture's first, a 3D -//! texture's depth images as its first, but a mipmapped one's past the first not at all (an -//! Apple M3 Max under macOS 27.0.1: every level of 2D textures 5 to 255 texels wide of 3 to 6 -//! levels, whole and inset regions; slices of 1D and 2D arrays; every depth image of 3D -//! textures of 1 to 4 levels; a one-level 3D texture's fill past its first depth image wrote -//! its first image's bytes, or in some runs none). A texture of its own memory, and a heap's -//! the runtime holds apart from the heap's bytes, takes the same bytes of level 0 of the slice -//! at any level, the region cut at the level's extent (3D: image 0): each -//! word lands on the texel of level 0's rows (`align(4 w, 16)` bytes apart) it meets, or between -//! them, which Metal's blits with a buffer read back and the runtime holds apart for a texture -//! of one level (`two_planes/buffer_rows.rs`; of more, not) (`getBytes` of every texel after fills of 1 to 37 -//! texels wide, 1 to 3 levels, arrays of 2, 1D and 3D, of its own memory and a heap's; a -//! texture's levels and slices past the first lie in bytes that overlap, which Metal's own -//! copies show and the runtime holds apart). A texture over a surface's planes is written at -//! its GPU rows (plane 0's `bytesPerRow` rounded down to 16, the rows Metal's blits address it -//! at) at any width, its alpha plane and every byte between the rows kept (`RGB10A8_2P_XR10` -//! over 7 surfaces and the sRGB twin over one, 16, 33, 37, 61, 64 and the consumer's 384 texels -//! wide, a region, a whole texture with a 3-byte pattern and a region past the level, every -//! byte of each surface read back). -//! -//! A **color fill** packs the color in `pixelFormat:` (the texture's own format without it) by -//! the fill's own rules (`fill_value.rs`), which are not a `Clear` load action's, and fills that -//! pattern. The runtime packs it so, on the host, for every fill with `pixelFormat:` (a capability: -//! Metal's packing in another format). A **plain** fill of a texture of a format whose fill -//! converts a `float` (normalized, sRGB, half, float, small float, shared exponent; -//! `fill_value::device_converts`) and that the device renders, its image holding Metal's bytes, -//! is the device's own conversion of the color instead, as the native-arithmetic rule asks: the -//! device's clear of a color value (`vkCmdClearColorImage`). A fill of whole subresources (every -//! texel of a level's layer, or of a 3D level's depth images) whose image is the texture's own (not -//! a buffer's bytes), made with transfer-destination usage in a format that takes transfer writes -//! in its tiling, is the clear of that image there, and makes nothing. Any other region copies a -//! **tile** the device cleared to the color, of the texture's image format, samples and dimension, -//! into the region of each image the fill writes, side by side from the region's origin, as a -//! blit copy between the textures moves it. The encoder keeps its last 4 tiles for its later -//! fills (each side the power of two at least the region's and 16 texels, no larger than the -//! texture's first level, the longer one halved to hold 1 MiB at most): a fill of a color a kept -//! tile holds copies it; one of another color makes a tile while fewer are kept and clears the -//! least recently used one again past that. So a burst of fills of a few colors makes one tile a -//! color, which the device's recycler gives where an earlier command buffer's went. The clear is -//! announced where the device's conversion may store another texel than Metal's packing -//! (`fill_value::device_apart`, `device-color-conversion`; a half or small-float NaN, -//! `device-nan-encoding`). A texture buffer and every other format are packed on the host. Metal -//! fills the packed texel's bytes, repeated -//! or cut at the texture's texel (12 pairs of formats, 256 colors each: 128 colors packed in each -//! of 70 formats into textures of 18 formats of 1 to 16 bytes; on the M3 Max the 88 formats Metal -//! packs a color in, 1,144 colors each, into `RGBA32Uint` texels). In every other format (213: compressed, 4:2:2, depth, stencil, -//! two-plane, YCbCr, padded, `Invalid` and the private formats) Metal packs nothing and fills -//! bytes of the calling thread's stack, the texel's bytes of a 16-byte buffer the packing writes: -//! a probe that set the stack below its call to one byte read that byte back in every texel, and -//! two consecutive color fills in one encoder find the first's packed texel there. A call between -//! them leaves other bytes: in our probe `slot.m` an encoder's end, a blit or a byte fill between -//! them left pointers of the process (differing between processes), and a plain Objective-C -//! process on the M3 Max (macOS 27.0.1) found the earlier fill's texel only where no call came -//! between the two fills. The runtime holds that buffer per command buffer, zeros at its start, -//! each color fill's packed texel over its first bytes, and fills its bytes there: Metal's bytes -//! for consecutive fills, and bytes the stack may hold elsewhere; announced once -//! (`Degradation::UnpackedFillColor`). Metal's -//! validation stops such a fill ("must be a color format", "is not compatible with the texture -//! format"). -//! -//! **Placement** (31 cases of a byte fill of `RGBA8Unorm` textures of each type, -//! every byte of every slice and level read back): a level past the texture's writes nothing; a 1D, -//! 2D or 3D texture ignores the slice, a cube takes the slice's face modulo 6, and an array (1D, 2D -//! or cube) writes nothing at a slice past its own; a 3D texture writes the region's depth images, -//! cut at the level's depth, and every other type one image, ignoring the region's `z` and depth. A -//! 2D multisample texture ignores the slice, as a 2D one does, and a multisample array writes -//! nothing at a slice past its own. -//! -//! **Texture buffers** (the M3 Max, our probe `tb.m`: 1,493 cases of 5 formats of 1 to 16 bytes -//! a texel, patterns of 1 to 256 bytes and packed colors, over a 12-texel texture at offsets 0 -//! to 68 of a 512-byte buffer, every byte read back, the consumer's cases among them). A fill -//! writes bytes of the buffer, not texels: the `w · b` bytes from the texture's offset plus -//! `x · b` (`b` the texel's bytes), past the texture's width too, cut at the buffer's end; -//! the level, slice, row, height and depth change nothing (a height or depth of 0 writes the row), -//! and a width of 0 writes nothing. The pattern of `n` bytes runs across the region's bytes: byte -//! `j` of the region is `pattern[j & (n - 1)]` (the pattern repeated where `n` is a power of two; -//! `n` 3 writes `p0 p0 p2 p2`), except in each 16-byte chunk of the buffer the region covers -//! whole, which takes 16 bytes of a block from its byte `(j & (n - 1)) & !3`, `j` the chunk's -//! first. The block is the power of two of bytes at least `n` and 16, holding the pattern's whole -//! copies from its start and, past them and past the block, bytes of the calling thread's stack: -//! zeros in every probe of ours, a 9-byte fill after an 8-byte one in the same encoder too, while -//! the consumer's dev-build Rust process, whose sends run objc2's method check first, read an -//! earlier fill's bytes there (not measured in a plain process). The runtime writes zeros there, -//! announced once where a chunk reads them (`Degradation::TextureBufferFillLeftover`). The rule -//! holds byte for byte for long patterns too (our probe `tblf.m`: 18 fills of patterns of 16 to -//! 32752 bytes into `R8Uint`, `R32Uint` and `RGBA32Uint` texture buffers at offsets 4 to 64, up -//! to 100,000 texels wide). A pattern of more than 32752 bytes ends Metal's process in the call, -//! in the blit's dispatch, whatever the format (`R8Uint`, `R32Uint`, `RGBA32Uint`) and region -//! (of 0 texels, past the buffer, up to 100,000 texels; our probes `tblf.m` and `tbz.m`); the -//! runtime refuses it (`Problem::LongTextureBufferFillPattern`). A fill of any other texture -//! takes a pattern of any length (up to 1 MiB in our probe `tl.m`) and reads 16 bytes of it at -//! most. -//! -//! **Multisample textures** (the M3 Max, our probe `ms.m`: 32 formats at 4 samples and 11 at 2, -//! every sample of a 5 x 3 texture or 2-slice array read back through an unsigned view, as its -//! depth's bits or as its stencil): a fill writes every sample of the region's texels and no -//! other, each sample `s` its own `b` bytes (`b` the texel's, or its aspect's: the depth of -//! `Depth32Float_Stencil8`, its stencil kept). Where the `n · b` bytes of a texel's `n` samples -//! are 16 or fewer, the pattern is repeated from its start and cut at `n · b`, and sample `s` -//! takes its bytes from `s · b` (`RGBA8Unorm` at 4 samples a 16-byte pattern's 4 bytes each, -//! `R8Unorm` its first 4 bytes one each); past 16, every sample takes the pattern cut at `b` -//! (`RGBA16Float` at 4 samples, `RGBA32Float` at 2 and 4). A color fill's pattern is the packed -//! texel, which every sample then takes; packed in no format, the 16-byte buffer, which the -//! samples take a part each (`Depth32Float` at 2 and 4). Every value lands as given, a depth's -//! NaN, 2.0, -1.0 and denormal too. -//! -//! An empty pattern Metal's API validation layer stops; plain Metal takes the fill, the layer off, -//! and writes the region all the same, from bytes the call does not give: an ordinary texture's -//! texels a unit read from the pattern's address, a texture buffer's region the fill's leftover -//! bytes, Metal's own (the M3 Max, our probe `emptyfill.m`). The runtime holds neither, so it -//! refuses the fill its own gap (`NotImplemented(RuntimeGap::EmptyFillPattern)`, -//! [`check_pattern`]). -//! -//! **`fillBuffer:range:pattern4:`** ([`BlitCommandEncoder::fill_buffer_pattern4`]; 10 ranges of a -//! 256-byte buffer) writes the 4-byte pattern from the range's start, restarting it at each -//! multiple of 16 bytes of the buffer: byte `k` of the range takes the pattern's byte `k - start` -//! modulo 4 before the first such multiple, and byte `k` modulo 4 from it on. -//! -//! **How.** A plain color fill the device clears is the clear above, of the texture's image or of a -//! tile copied from. Every other fill is copies the encoder already makes: a staging buffer of the -//! pattern's units -//! (4 MiB at most, copied again for a larger region) and `copy_from_buffer_to_texture` into the -//! region's units of each image, so shadows, twins, carriers and two planes take their own paths; -//! a heap's two-plane texture, one copy of the color words into the heap's bytes; a two-plane -//! texture held apart, the plane words' copy (`two_planes.rs`) into the rectangles of texels the -//! words land on; a texture buffer (its bytes before the first whole chunk, its chunks' period -//! repeated, its bytes after the last: units of at most the block's 32 KiB, read from the pattern -//! as they are made, whatever the region's length) and a packed YCbCr texture, copies into the -//! buffer's bytes. A multisample texture's samples: the sample planes' merge writes each sample's -//! bits into a multisampled image of the unsigned-integer format of the texel's size -//! (`sample_planes::BitsCopy::fill`), and a copy between multisampled textures moves the region -//! into the texture (`blit_texture.rs`): a color image's bits by an image copy, or by the sample -//! planes' copies where the device's own converts float NaNs; a depth or stencil aspect by -//! `sample_copy.rs`'s copies or draws, exact or announced as those are (`drawn-depth-copy` into a -//! 32-bit float depth whose driver's fragment depth changes values). A pattern4 fill copies its -//! bytes from a staging buffer. - -use super::blit::{bytes_in, reads, writes, BlitCommandEncoder, TRANSFER}; -use super::blit_plan::BufferLayout; -use super::blit_plan::ImageCopyRegion; -use super::blit_texture; -use super::chroma_pairs::{is_four_two_two, TEXEL_BYTES}; -use super::clear_value; -use super::clear_value::has_channels; -use super::compressed_blit::{self, degrade_compressed_blit, Writer}; -use super::copy_plan::{ - block_bytes, block_extent, level_extent, BlitOption, CopyUnit, ImageRegion, -}; -use super::error::{internal, invalid, Error, Problem, RuntimeGap}; -use super::fill_value::{device_apart, device_converts, device_nan, fill_texel}; -use super::heap::Heap; -use super::image_plan::{sample_count, ImagePlan}; -use super::render_values::ClearColor; -use super::replay::BlitCall; -use super::sample_planes::{BitsCopy, BITS_COPY_STAGES}; -use super::shadow::Covered; -use super::sparse::emulated::Written; -use super::texture::Texture; -use super::texture_descriptor::TextureDescriptor; -use super::tracker::Access; -use super::two_planes; -use super::values::ResourceOptions; -use super::values::{Origin, Region, Size}; -use super::Device; -use super::{Buffer, Degradation}; -use ash::vk; -use metal2vulkan::bind::{clamped_depth, PlanesCopy, YCbCrCodes}; -use metal2vulkan::device::FormatUsage; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{ - byte_format, copies_only, padded_words, ycbcr_format, ClearRoute, ExtendedRange, FormatMapping, -}; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; -use metal2vulkan::vk::{ - Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags, -}; -use std::ops::Range; - -/// The most bytes a fill stages at once: a larger region copies them again. -const STAGING_BYTES: u64 = 4 << 20; - -/// What a fill writes into one unit of a format (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum FillUnit { - /// A compressed format's block of `bytes`, `extent` texels: the region counts blocks. - Blocks { bytes: u32, extent: [u32; 2] }, - /// A texel's `bytes`, which a copy with `option` writes: the region counts texels. - Texels { bytes: u32, option: BlitOption }, - /// A two-plane extended-range texel's color word, its alpha kept. - PlaneWords, - /// A packed two-plane YCbCr texel (`YCBCR10_420_2P_PACKED`, ...): one zero byte at the - /// texel's `x` of its row of the plane, whatever the pattern. - PackedCodes, -} - -/// The fill unit of `pf`, `None` for a format the runtime makes no texture of (`Invalid`, the -/// private formats it holds none of, the 24-bit depth formats, which Apple GPUs make none of) and -/// for one it holds for copies alone (`metal::format::copies_only`), whose fills are refused. -pub(super) fn fill_unit(pf: PixelFormat) -> Option { - use PixelFormat as P; - let texels = |bytes, option| Some(FillUnit::Texels { bytes, option }); - if two_planes::holds_planes(pf) { - return Some(FillUnit::PlaneWords); - } - if let Some(extent) = block_extent(pf) { - return Some(FillUnit::Blocks { - bytes: block_bytes(pf)?, - extent, - }); - } - if is_four_two_two(pf) { - return texels(TEXEL_BYTES, BlitOption::None); - } - // A two-plane YCbCr texel is its plane's code, 1 or 2 bytes, as Metal's blits move it. - if let Some(codes) = ycbcr_format(pf).and_then(YCbCrCodes::of) { - if codes.packed { - return Some(FillUnit::PackedCodes); - } - return texels(codes.bytes, BlitOption::None); - } - // A padded 10-bit texel is its 2 or 4 bytes, the words holding its codes. - if padded_words(pf) { - return texels(block_bytes(pf)?, BlitOption::None); - } - match pf { - P::Stencil8 => texels(1, BlitOption::None), - P::X32Stencil8 => texels(1, BlitOption::StencilFromDepthStencil), - P::Depth32FloatStencil8 => texels(4, BlitOption::DepthFromDepthStencil), - P::Depth16Unorm => texels(2, BlitOption::None), - P::Depth32Float => texels(4, BlitOption::None), - _ if has_channels(pf).is_some() => texels(block_bytes(pf)?, BlitOption::None), - // Every other extended-range texel: a bfloat or 10-bit one's words (color fills of - // single texels and of 4 x 1), `RGB10A2Unorm_sRGB`'s 4 bytes (byte fills, the M3 Max). - _ if ExtendedRange::of(pf).is_some() => texels(block_bytes(pf)?, BlitOption::None), - _ => None, - } -} - -/// `pattern` repeated from its start and cut at `bytes`. -pub(super) fn unit_of(pattern: &[u8], bytes: u32) -> Vec { - pattern - .iter() - .copied() - .cycle() - .take(bytes as usize) - .collect() -} - -/// The bytes of `pattern` a fill of a texture of type `ty` reads, which the encoder's log keeps -/// (`replay.rs`): a texture buffer's fill the whole pattern, up to one byte past -/// [`TEXTURE_BUFFER_PATTERN_BYTES`] (a longer one, refused, is refused again where the call is -/// encoded again); another texture's 16 bytes at most, a unit's or a texel's samples' -/// ([`unit_of`], [`sample_units`]). -pub(super) fn read_pattern(ty: TextureType, pattern: &[u8]) -> &[u8] { - let read = match ty { - TextureType::TextureBuffer => TEXTURE_BUFFER_PATTERN_BYTES + 1, - _ => 16, - }; - &pattern[..pattern.len().min(read)] -} - -/// The bits each sample of a multisampled texel of `bytes` bytes and `samples` samples takes -/// from `pattern` (the module docs): where the samples' bytes are 16 or fewer, the pattern -/// repeated from its start and cut at them, sample `s` its bytes from `s · bytes`; else each -/// sample the pattern cut at `bytes`. -pub(super) fn sample_units(pattern: &[u8], bytes: u32, samples: u32) -> Vec> { - let all = bytes * samples; - let unit = unit_of(pattern, if all <= 16 { all } else { bytes }); - let bytes = bytes as usize; - (0..samples as usize) - .map(|sample| { - let at = sample * bytes % unit.len(); - unit[at..at + bytes].to_vec() - }) - .collect() -} - -/// The texel `unit` (1, 2, 4, 8 or 16 bytes) as the words of a clear value of the -/// unsigned-integer format of its size: one zero-extended word up to 4 bytes, else its words, low -/// bytes first. -pub(super) fn words(unit: &[u8]) -> [u32; 4] { - let mut out = [0; 4]; - for (index, byte) in unit.iter().enumerate() { - out[index / 4] |= u32::from(*byte) << (8 * (index % 4)); - } - out -} - -/// The longest pattern a texture buffer's fill takes: Metal's process ends in the fill of a longer -/// one (the module docs). -pub(super) const TEXTURE_BUFFER_PATTERN_BYTES: usize = 32752; - -/// A fill's refusal for the length of its `pattern` over a texture of type `ty`, in Metal's own -/// order (the module docs). The two lengths fall on either side of what misuse is: -/// -/// - **no bytes at all** is input plain Metal takes, so it is the runtime's own gap -/// ([`RuntimeGap::EmptyFillPattern`]): Metal's API validation layer stops it, and plain Metal -/// writes bytes the call never gave, which the runtime holds none of; -/// - **more than [`TEXTURE_BUFFER_PATTERN_BYTES`] into a texture buffer** is misuse -/// ([`Problem::LongTextureBufferFillPattern`]): Metal's own process ends in the call, whatever -/// the region. A fill of any other texture takes a pattern of any length. -pub(super) fn check_pattern( - call: &'static str, - ty: TextureType, - pattern: &[u8], -) -> Result<(), Error> { - if pattern.is_empty() { - return Err(Error::NotImplemented(RuntimeGap::EmptyFillPattern)); - } - if ty == TextureType::TextureBuffer && pattern.len() > TEXTURE_BUFFER_PATTERN_BYTES { - let length = pattern.len() as u64; - return Err(invalid( - call, - Problem::LongTextureBufferFillPattern { length }, - )); - } - Ok(()) -} - -/// The bytes Metal's fill of a texture buffer writes into its buffer's bytes `start..end` (the -/// region's texels from the texture's offset), from `pattern` of `n` bytes (the module docs): -/// byte `j` of the region (from its first) is `pattern[j & (n - 1)]`, but a 16-byte chunk of the -/// buffer the region covers whole, `j` its first byte's, takes 16 bytes of the fill's block from -/// byte `(j & (n - 1)) & !3`. The block is the power of two of bytes at least `n` and 16, holding -/// the pattern's whole copies from its start; its other bytes, and those after it, are Metal's -/// stack's, zeros in our probes, which the runtime writes. The block is read from the pattern -/// where a byte of it is asked for, never made. -pub(super) struct StreamFill<'a> { - pattern: &'a [u8], - /// The bytes of the pattern's whole copies at the block's start. - copies: u64, -} - -impl<'a> StreamFill<'a> { - /// The fill of `pattern` (not empty). - pub(super) fn new(pattern: &'a [u8]) -> StreamFill<'a> { - let n = pattern.len() as u64; - StreamFill { - pattern, - copies: StreamFill::block_of(n) / n * n, - } - } - - /// The bytes of the block of a pattern of `n` bytes: the power of two at least `n` and 16. - fn block_of(n: u64) -> u64 { - n.next_power_of_two().max(16) - } - - /// The bytes of this fill's block, which are also the period of its chunks' bytes: - /// `j & (n - 1)` repeats every power of two past `n - 1`. - fn block(&self) -> u64 { - StreamFill::block_of(self.pattern.len() as u64) - } - - /// The mask of a byte's index into the pattern. - fn mask(&self) -> u64 { - self.pattern.len() as u64 - 1 - } - - /// Byte `at` of the block and of the bytes after it: the pattern's whole copies, then zeros. - fn block_byte(&self, at: u64) -> u8 { - match at < self.copies { - true => self.pattern[(at % self.pattern.len() as u64) as usize], - false => 0, - } - } - - /// The whole 16-byte chunks of the buffer that `bytes` covers. - fn chunks(bytes: &Range) -> Range { - let first = bytes.start.next_multiple_of(16); - let last = bytes.end / 16 * 16; - if first < last { - first..last - } else { - bytes.end..bytes.end - } - } - - /// Byte `at` of the buffer, of the fill of `bytes`. - pub(super) fn byte(&self, bytes: &Range, at: u64) -> u8 { - let chunks = StreamFill::chunks(bytes); - let j = at - bytes.start; - if chunks.contains(&at) { - let chunk = at / 16 * 16; - let from = ((chunk - bytes.start) & self.mask()) & !3; - self.block_byte(from + at % 16) - } else { - self.pattern[(j & self.mask()) as usize] - } - } - - /// Whether the fill of `bytes` writes a byte of the block past the pattern's whole copies. - pub(super) fn reads_leftover(&self, bytes: Range) -> bool { - let chunks = StreamFill::chunks(&bytes); - (chunks.start..chunks.end.min(chunks.start + self.block())) - .step_by(16) - .any(|chunk| { - let from = ((chunk - bytes.start) & self.mask()) & !3; - from + 16 > self.copies - }) - } - - /// The fill of `bytes` as spans of the buffer, each with the unit it holds repeated from its - /// first byte: the bytes before the first whole chunk (fewer than 16, or fewer than 32 where - /// no chunk is whole), the chunks (a period of them, the block's bytes, at most 32 KiB for a - /// pattern of [`TEXTURE_BUFFER_PATTERN_BYTES`]), and the bytes after the last (fewer than - /// 16): nothing of the region's length. - pub(super) fn spans(&self, bytes: Range) -> Vec<(Range, Vec)> { - let chunks = StreamFill::chunks(&bytes); - let explicit = |span: Range| { - let unit: Vec = span.clone().map(|at| self.byte(&bytes, at)).collect(); - (span, unit) - }; - if chunks.is_empty() { - return vec![explicit(bytes.clone())]; - } - let first = chunks.start..(chunks.start + self.block()).min(chunks.end); - let unit: Vec = first.map(|at| self.byte(&bytes, at)).collect(); - [ - explicit(bytes.start..chunks.start), - (chunks.clone(), unit), - explicit(chunks.end..bytes.end), - ] - .into_iter() - .filter(|(span, _)| !span.is_empty()) - .collect() - } -} - -/// The units `from..from + count` of an axis of `units`, cut there. -fn cut(from: u64, count: u64, units: u64) -> Range { - from.min(units)..from.saturating_add(count).min(units) -} - -/// The texels of a two-plane extended-range level `width` texels wide that a fill of the units -/// `x` by `y` writes (the module docs): each row `y` written at [`two_planes::buffer_blit_rows`] apart, its -/// words landing on the texels of the level's rows `align(4 w, 16)` bytes apart, those past a row's -/// texels in the bytes between the rows. As rectangles `(x, y)` of the level, in rows that -/// ascend. -fn plane_rectangles(width: u64, x: Range, y: Range) -> Vec<(Range, Range)> { - let rows = two_planes::buffer_blit_rows(width, true); - let pitch = (4 * width).next_multiple_of(16); - // The words written, as spans of bytes of the level that ascend and do not meet. - let mut spans: Vec> = Vec::new(); - for row in y { - let span = row * rows + 4 * x.start..row * rows + 4 * x.end; - match spans.last_mut() { - Some(last) if span.start <= last.end => last.end = last.end.max(span.end), - _ => spans.push(span), - } - } - // Each row's runs of texels, in order. - let mut runs: Vec<(u64, Range)> = Vec::new(); - for span in spans { - let mut at = span.start; - while at < span.end { - let row = at / pitch; - let row_end = ((row + 1) * pitch).min(span.end); - let texels = (at - row * pitch) / 4..((row_end - row * pitch) / 4).min(width); - if !texels.is_empty() { - match runs.last_mut() { - Some((last, run)) if *last == row && texels.start <= run.end => { - run.end = run.end.max(texels.end); - } - _ => runs.push((row, texels)), - } - } - at = row_end; - } - } - // Consecutive rows of one run each, the same, make one rectangle. - let mut out: Vec<(Range, Range)> = Vec::new(); - for (i, (row, run)) in runs.iter().enumerate() { - let alone = |j: usize| runs.iter().filter(|(r, _)| *r == runs[j].0).count() == 1; - if let Some((columns, rows)) = out.last_mut() { - if alone(i) && rows.end == *row && columns == run && i > 0 && alone(i - 1) { - rows.end += 1; - continue; - } - } - out.push((run.clone(), *row..row + 1)); - } - out -} - -/// Where a fill of `region` at `level` and `slice` of `texture` writes, as plain Metal places it -/// (the module docs): the slice and the depth images, `None` where it writes nothing. -fn placement( - texture: &Texture, - level: u64, - slice: u64, - region: Region, -) -> Result)>, Error> { - let record = texture.record(); - let Some(level) = u32::try_from(level) - .ok() - .filter(|&level| level < record.level_count) - else { - return Ok(None); - }; - let slices = u64::from(record.layer_count); - let (slice, images) = match texture.texture_type() { - TextureType::Type1D | TextureType::Type2D | TextureType::Type2DMultisample => (0, 0..1), - TextureType::Type3D => { - let depth = u64::from(level_extent(record, level)[2]); - (0, cut(region.origin.z, region.size.depth, depth)) - } - TextureType::Cube => (slice % 6, 0..1), - TextureType::Type1DArray - | TextureType::Type2DArray - | TextureType::CubeArray - | TextureType::Type2DMultisampleArray - | TextureType::TextureBuffer => { - if slice >= slices { - return Ok(None); - } - (slice, 0..1) - } - }; - Ok((!images.is_empty()).then_some((slice, images))) -} - -/// Announce the device's clear of a plain color fill of `pf` to `color` where it may store another -/// texel than Metal's fill packs ([`device_apart`], `device-color-conversion`), and where it -/// converts a half or small-float NaN as the device likes ([`device_nan`], `device-nan-encoding`). -fn degrade_fill_conversion(device: &Device, pf: PixelFormat, color: [f64; 4]) { - if device_apart(pf, color) { - device.degrade(Degradation::DeviceColorConversion, || { - ( - format!("a color fill of a {pf:?} texture to {color:?}"), - "the device clears the region by its own conversion of the color, which Vulkan \ - lets store either of the two codes nearest a normalized channel's value (it asks \ - for the nearest) and which takes an sRGB encode and a float's rounding its own \ - way, where Metal's fill packs it by rules of its own (a tie rounded \ - half up, an sRGB channel the code whose decoded value is nearest): a channel can \ - store a code next to Metal's" - .to_owned(), - ) - }); - } - if device_nan(pf, color) { - device.degrade(Degradation::DeviceNanEncoding, || { - ( - format!("a {pf:?} texture's color fill to a NaN"), - "the device converts it to the format's NaN as it likes, where Metal's fill keeps \ - a half NaN's sign and payload and makes a small float's all ones" - .to_owned(), - ) - }); - } -} - -/// The most bytes of a plain color fill's tile (the module docs): a larger region takes copies of -/// it side by side. -const TILE_BYTES: u64 = 1 << 20; - -/// The most tiles an encoder keeps for its later plain color fills (the module docs). -const KEPT_TILES: usize = 4; - -/// The least side of a plain color fill's tile, where its texture's first level is as large. -const TILE_SIDE: u32 = 16; - -/// What a plain color fill's tile is made as: the pixel format, image format, samples and -/// dimension (a 1D image's, or 2D) of the textures it fills. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct TileShape { - pixel_format: PixelFormat, - format: Format, - samples: u32, - one_row: bool, -} - -/// A tile the device cleared to a color, which plain color fills copy from (the module docs). -pub(super) struct FillTile { - shape: TileShape, - extent: [u32; 2], - /// The color it holds, its channels' bits. - color: [u64; 4], - texture: Texture, -} - -/// A kept tile, taken for a fill. -enum Taken { - /// One holding the fill's color. - Cleared(FillTile), - /// One of another color, for the fill to clear again. - Other(FillTile), -} - -/// The tiles an encoder keeps for its later plain color fills (the module docs), the one used -/// latest last: at most [`KEPT_TILES`]. -#[derive(Default)] -pub(super) struct FillTiles(Vec); - -impl FillTiles { - /// The kept tile of `shape` at least `width` by `height` texels for a fill of `color`, taken - /// out until it is kept again: one holding the color where there is one; else, where it keeps - /// [`KEPT_TILES`] already, the one used least recently, to clear again; else none, and the - /// fill makes one (so as many colors in turn clear each tile once). - fn take( - &mut self, - shape: TileShape, - [width, height]: [u32; 2], - color: [u64; 4], - ) -> Option { - let fits = |tile: &FillTile| { - tile.shape == shape && tile.extent[0] >= width && tile.extent[1] >= height - }; - if let Some(at) = (self.0.iter()).position(|tile| fits(tile) && tile.color == color) { - return Some(Taken::Cleared(self.0.remove(at))); - } - if self.0.len() < KEPT_TILES { - return None; - } - let at = self.0.iter().position(fits)?; - Some(Taken::Other(self.0.remove(at))) - } - - /// Keep `tile`, the one used latest: past [`KEPT_TILES`] the one used least recently goes - /// (its command buffer holds it until it completes all the same). - fn keep(&mut self, tile: FillTile) { - self.0.push(tile); - if self.0.len() > KEPT_TILES { - self.0.remove(0); - } - } -} - -/// The extent of the tile that a plain color fill of `width` by `height` texels, of `bytes` bytes -/// each (a texel's samples' together), copies from, in a texture whose first level is `limit` -/// texels: each side the power of two at least the region's and [`TILE_SIDE`], no larger than the -/// first level's (where the device made an image), then the longer side halved (rounded up) until -/// it holds [`TILE_BYTES`] at most. Fills of near sizes take one tile, and an encoder's fills of -/// growing regions make few. -pub(super) fn tile_extent( - [width, height]: [u32; 2], - bytes: u64, - [wide, high]: [u32; 2], -) -> [u32; 2] { - let side = |side: u32, limit: u32| { - let rounded = side.max(TILE_SIDE).checked_next_power_of_two(); - rounded - .map_or(limit, |rounded| rounded.min(limit)) - .max(side) - .max(1) - }; - let mut extent = [side(width, wide), side(height, high)]; - while u64::from(extent[0]) * u64::from(extent[1]) * bytes > TILE_BYTES && extent != [1, 1] { - let longer = usize::from(extent[1] > extent[0]); - extent[longer] = extent[longer].div_ceil(2); - } - extent -} - -/// The copies out of a tile of `tile` texels that write the `size` texels from `origin` (its -/// depth image's third) of the image's `level` and `layer`: the region cut into parts of the -/// tile's extent from its origin, each copied from the tile's origin. -pub(super) fn tile_copies( - tile: [u32; 2], - origin: [u32; 3], - size: [u32; 2], - (level, layer): (u32, u32), -) -> Vec { - let at = |level, layer, origin, [width, height]: [u32; 2]| ImageRegion { - aspect: ImageAspectFlags::COLOR, - level, - layer, - layers: 1, - origin, - size: [width, height, 1], - }; - let mut copies = Vec::new(); - for top in (0..size[1]).step_by(tile[1].max(1) as usize) { - for left in (0..size[0]).step_by(tile[0].max(1) as usize) { - let part = [tile[0].min(size[0] - left), tile[1].min(size[1] - top)]; - let to = [origin[0] + left, origin[1] + top, origin[2]]; - copies.push(ImageCopyRegion { - src: at(0, 0, [0, 0, 0], part), - dst: at(level, layer, to, part), - }); - } - } - copies -} - -/// Whether a plain color fill of every texel of `texture`'s image at its `level` (`extent` -/// texels) is the device's clear of that image there (the module docs): an image of its own (not -/// a buffer's bytes) of that extent at the level, made with transfer-destination usage -/// ("`image` must have been created with the `VK_IMAGE_USAGE_TRANSFER_DST_BIT` usage flag set", -/// `VUID-vkCmdClearColorImage-image-00002`), whose format takes transfer writes in the image's -/// tiling ("The format features of `image` must contain `VK_FORMAT_FEATURE_TRANSFER_DST_BIT`", -/// `VUID-vkCmdClearColorImage-image-01993`). The fill's formats are color formats, neither -/// compressed nor YCbCr nor of 64-bit channels (`VUID-vkCmdClearColorImage-image-00007`, -/// `-01545`, `-09678`), and every image rests in `GENERAL` -/// (`VUID-vkCmdClearColorImage-imageLayout-01394`: "`imageLayout` must be -/// `VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR`, `VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL` or -/// `VK_IMAGE_LAYOUT_GENERAL`"). -fn in_place(texture: &Texture, level: u32, extent: [u32; 3]) -> Result { - if texture.over_buffer() { - return Ok(false); - } - let plan = texture.image_plan()?; - let planned = plan.extent.map(|axis| (axis >> level.min(31)).max(1)); - if planned != extent || !plan.usage.contains(ImageUsageFlags::TRANSFER_DST) { - return Ok(false); - } - let device = texture.generation(); - let profile = device.compile_device().profile(); - let facts = device.shared().textures.facts(profile); - let features = match texture.linear_image()? { - true => facts.linear(plan.format), - false => facts.optimal(plan.format), - }; - Ok(features.contains(FormatFeatureFlags2::TRANSFER_DST)) -} - -impl BlitCommandEncoder { - /// `fillTexture:level:slice:region:bytes:length:` (Apple SPI): every unit of `region` of the - /// texture's `level` and `slice` becomes `pattern`, repeated from its start and cut at the - /// unit's bytes, as plain Metal writes it (`blit_fill.rs`). A compressed format's unit is a - /// block, and the region's origin and size count blocks; every other format's is a texel (a - /// 4:2:2 format's 2 bytes, a stencil format's 1, the depth of `Depth32Float_Stencil8`, a - /// two-plane YCbCr texture's plane code, a two-plane extended-range texel's color word). A - /// packed two-plane YCbCr texture's texels each take one zero byte, whatever the pattern. The - /// region is cut at the level, and an empty one writes nothing, but a texture buffer's (below). - /// - /// Placed as plain Metal places it (the module docs): a level past the texture's, or a slice - /// past an array's, writes nothing; a 1D, 2D or 3D texture ignores the slice and a cube takes - /// it modulo 6; a 3D texture writes the region's depth images, every other type one image; a - /// texture buffer's fill writes its buffer's bytes from the region's first texel, as many as - /// its texels', past the texture's width and cut at the buffer's end, whatever the level, - /// slice, row, height and depth, the pattern running across them, not started again at each - /// texel (`texture-buffer-fill-leftover` where Metal's bytes are its stack's). A two-plane - /// extended-range texture's rows are Metal's fill rows, and a level past its first writes level - /// 0, as Metal's fills do. A multisample texture's samples each take their own bytes of the - /// pattern where a texel's samples hold 16 bytes or fewer, else the pattern cut at the texel - /// (the module docs). - /// - /// Refused: a texture of another device (`Invalid`), and a texture buffer's fill of a pattern - /// of more than 32752 bytes (`Invalid(LongTextureBufferFillPattern)`), in which Metal's process - /// ends, whatever the region; another texture's fill takes a pattern of any length and reads 16 - /// bytes of it at most. An empty pattern is the runtime's own gap - /// (`NotImplemented(RuntimeGap::EmptyFillPattern)`): Metal's API validation layer stops it, and - /// plain Metal takes the fill and writes bytes the call never gave, a unit read from the - /// pattern's address or, for a texture buffer, the fill's leftovers. A multisample - /// texture's fill is refused, `Unsupported`, where the device cannot run the sample planes' - /// merge (sample-rate shading, the sample count among its integer color attachments') or the - /// copy into the texture (`copy_from_texture`'s refusals of copies between multisampled - /// textures). A texture of a format held for copies alone (`metal::format::copies_only`) has - /// its fill refused `Unsupported(Format, NotImplemented)`: Metal's fills of one are not - /// measured. - pub fn fill_texture( - &mut self, - texture: &Texture, - level: u64, - slice: u64, - region: Region, - pattern: &[u8], - ) -> Result<(), Error> { - self.logged( - |log| { - BlitCall::FillTexture( - Box::new((texture.clone(), level, slice, region)), - log.byte_span(read_pattern(texture.texture_type(), pattern)), - ) - }, - |this| this.fill("fill_texture", texture, (level, slice), region, pattern), - ) - } - - /// `fillTexture:level:slice:region:color:` (`pixel_format` `None`) and - /// `fillTexture:level:slice:region:color:pixelFormat:` (Apple SPI): [`fill_texture`] of the - /// texel `color` packs to in `pixel_format`, the texture's own format without it, as Metal's - /// fills pack it (`fill_value.rs`), which is not how a `Clear` load action converts it: an sRGB - /// channel takes the code whose decoded value is nearest, `RG11B10Float` rounds to nearest - /// even, an integer channel's NaN is 0 or the extreme by its kind, and the extended-range - /// formats are packed. - /// - /// A plain fill (`pixel_format` `None`) of a texture of a normalized, sRGB, half, float or - /// small-float format the device renders is the device's clear of the color over the region - /// (the module docs), placed as the fill: a texel can stand a code from Metal's packing where - /// its conversion is in question, announced (`Degradation::DeviceColorConversion`; a half or - /// small-float NaN `Degradation::DeviceNanEncoding`). - /// - /// A color packed in a format Metal packs no color in (compressed, 4:2:2, depth, stencil, - /// two-plane, YCbCr, padded 10-bit, `Invalid`, the private formats) fills the command buffer's - /// last color fill's packed texel, over zeros at its start (the module docs): Metal fills bytes - /// of the calling thread's stack there, which hold that texel only where no other call used - /// them since. The device announces `Degradation::UnpackedFillColor` once. - /// - /// Refused as [`fill_texture`] refuses. - /// - /// [`fill_texture`]: BlitCommandEncoder::fill_texture - pub fn fill_texture_color( - &mut self, - texture: &Texture, - level: u64, - slice: u64, - region: Region, - color: ClearColor, - pixel_format: Option, - ) -> Result<(), Error> { - const CALL: &str = "fill_texture_color"; - // Refused before the command buffer's fill slot takes the texel, as its log is. - self.refuse_aborted()?; - let packed_in = pixel_format.unwrap_or(texture.pixel_format()); - let channels = [color.red, color.green, color.blue, color.alpha]; - // The texel, which the command buffer's slot takes; else the slot's bytes. - let texel = fill_texel(packed_in, channels); - let slot = self.core().command_buffer().fill_slot(texel.as_deref()); - // A plain fill of a texture of a format the device renders: the device's clear of the - // color (the module docs). Logged as the call, which encoded again clears again. - let cleared = match pixel_format { - None => self.device_fill(texture)?.and_then(|format| { - clear_value::held_color(packed_in, format, channels, ClearRoute::ThroughHalf) - }), - Some(_) => None, - }; - if let Some(value) = cleared { - return self.logged( - |_| { - BlitCall::FillTextureColor(Box::new(( - texture.clone(), - level, - slice, - region, - color, - ))) - }, - |this| this.cleared_fill(CALL, texture, (level, slice), region, (value, channels)), - ); - } - let pattern = texel.clone().unwrap_or(slot.to_vec()); - // Logged as the bytes it fills, which a call encoded again fills again. - self.logged( - |log| { - BlitCall::FillTexture( - Box::new((texture.clone(), level, slice, region)), - log.byte_span(&pattern), - ) - }, - |this| { - this.fill(CALL, texture, (level, slice), region, &pattern)?; - if texel.is_none() { - let format = texture.pixel_format(); - this.core() - .device() - .degrade(Degradation::UnpackedFillColor, || { - ( - format!("a color fill of a {format:?} texture, packed in {packed_in:?}"), - "Metal packs no color there and fills bytes of the calling thread's \ - stack, which hold the last color fill's packed texel only where no \ - other call used them since; the runtime fills the command buffer's last \ - color fill's packed texels, over zeros" - .to_owned(), - ) - }); - } - Ok(()) - }, - ) - } - - /// `fillBuffer:range:pattern4:` (Apple SPI): the bytes of `range` take `pattern`'s 4 bytes, - /// its low byte first, as plain Metal writes them (the module docs): from the range's start, - /// the pattern restarting at each multiple of 16 bytes of the buffer, so byte `k` of the buffer - /// takes the pattern's byte `k` modulo 4 from the range's first such multiple on. - /// - /// An empty range fills nothing. Refused (`Invalid`): a range past the buffer, a buffer of - /// another device. - pub fn fill_buffer_pattern4( - &mut self, - buffer: &Buffer, - range: Range, - pattern: u32, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::FillBufferPattern4(buffer.clone(), range.clone(), pattern), - |this| { - const CALL: &str = "fill_buffer_pattern4"; - this.core().check_device(CALL, buffer.generation())?; - let size = range.end.saturating_sub(range.start); - if size == 0 { - return Ok(()); - } - let range = bytes_in(CALL, range.start, size, buffer.length())?; - let pattern = pattern.to_le_bytes(); - // The bytes before the first multiple of 16, the pattern from the range's start; - // then the pattern from that multiple, in copies of at most `STAGING_BYTES` (a - // multiple of 4, so each starts the pattern again). - let restart = range.start.next_multiple_of(16).min(range.end); - let head = restart - range.start; - let body = range.end - restart; - let chunk = body.min(STAGING_BYTES); - let bytes: Vec = (0..head) - .map(|k| pattern[(k % 4) as usize]) - .chain(pattern.iter().copied().cycle().take(chunk as usize)) - .collect(); - let staging = this.staged(&bytes)?; - let (source, from) = staging.at(0); - // Read as a blit's (`host_residency.rs`): where the range starts in the `VkBuffer`, - // and each byte past it as far on. - let (destination, origin) = this.core().blit_at(buffer, range.start)?; - let mut regions = Vec::new(); - if head > 0 { - regions.push(vk::BufferCopy { - src_offset: from, - dst_offset: origin, - size: head, - }); - } - let mut at = restart; - while at < range.end { - let size = (range.end - at).min(chunk); - regions.push(vk::BufferCopy { - src_offset: from + head, - dst_offset: origin + (at - range.start), - size, - }); - at += size; - } - let length = bytes.len() as u64; - let uses = [reads(&staging, 0..length), writes(buffer, range)]; - this.command(&uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording; the staging buffer and the - // buffer are live and retained until it completes; each region lies inside - // both, and the buffer's regions are disjoint. - unsafe { device.cmd_copy_buffer(raw, source, destination, ®ions) }; - })?; - this.core().retain_shared(staging.held()); - Ok(()) - }, - ) - } - - /// The Vulkan format in which a plain color fill of `texture` is the device's clear of the - /// color (the module docs): its image's, where that holds Metal's bytes of the texture's format - /// (`metal::format::byte_format`), the format's fill converts a `float` - /// ([`device_converts`]), the device renders the format and copies images of it both ways, - /// and the texture is not a texture buffer, whose fill writes its buffer's bytes. `None` where - /// the fill packs the color. - fn device_fill(&mut self, texture: &Texture) -> Result, Error> { - let pf = texture.pixel_format(); - let texels = matches!( - fill_unit(pf), - Some(FillUnit::Texels { - option: BlitOption::None, - .. - }) - ); - if texture.texture_type() == TextureType::TextureBuffer || !texels || !device_converts(pf) { - return Ok(None); - } - let Some(format) = byte_format(pf) else { - return Ok(None); - }; - if texture - .image_plan() - .map_or(true, |plan| plan.format != format) - { - return Ok(None); - } - let device = self.core().device(); - let profile = device.compile_device().profile(); - let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; - let renders = profile.supports_format(format, FormatUsage::ColorAttachment) - && device - .shared() - .textures - .facts(profile) - .optimal(format) - .contains(copies); - Ok(renders.then_some(format)) - } - - /// The device's clear of `color` (its clear value `value`) into `region` of `texture`'s `level` - /// and `slice`, placed as a fill (the module docs). A fill of whole subresources whose image - /// takes a transfer write is the clear of the texture's own image there - /// ([`clear_in_place`](Self::clear_in_place)); any other copies a tile the device cleared to - /// the color ([`cleared_tile`](Self::cleared_tile)) into the region of each depth image the - /// fill writes, side by side from the region's origin, as a blit copy between the two textures - /// moves it. Announced where the device's conversion may store another texel than Metal's - /// fill packs. - fn cleared_fill( - &mut self, - call: &'static str, - texture: &Texture, - (level, slice): (u64, u64), - region: Region, - (value, color): (vk::ClearColorValue, [f64; 4]), - ) -> Result<(), Error> { - self.core().check_device(call, texture.generation())?; - texture.check_plane_copied()?; - self.see(texture); - let Size { - width, - height, - depth, - } = region.size; - if width == 0 || height == 0 || depth == 0 { - return Ok(()); - } - let Some((slice, images)) = placement(texture, level, slice, region)? else { - return Ok(()); - }; - let level = u32::try_from(level).map_err(|_| internal("a fill's level"))?; - let record = texture.record(); - let extent = level_extent(record, level); - let [w, h, d] = extent.map(u64::from); - let x = cut(region.origin.x, width, w); - let y = cut(region.origin.y, height, h); - if x.is_empty() || y.is_empty() { - return Ok(()); - } - let narrow = |v: u64| u32::try_from(v).map_err(|_| internal("a fill's region")); - let [left, top] = [narrow(x.start)?, narrow(y.start)?]; - let size = [narrow(x.end - x.start)?, narrow(y.end - y.start)?]; - let (level, layer) = ( - record.base_level + level, - record.base_layer + narrow(slice)?, - ); - // Every texel of the level's layer, or of a 3D level's depth images. - let whole = x == (0..w) && y == (0..h) && images == (0..d); - if whole && in_place(texture, level, extent)? { - self.clear_in_place(call, texture, (level, layer), extent, value)?; - } else { - let (tile, held) = self.cleared_tile(texture, size, (value, color))?; - let mut copies = Vec::new(); - for z in images { - copies.extend(tile_copies( - held, - [left, top, narrow(z)?], - size, - (level, layer), - )); - } - self.texture_copies(call, &tile, texture, &copies)?; - } - degrade_fill_conversion(self.core().device(), texture.pixel_format(), color); - Ok(()) - } - - /// The device's clear of `value` into every texel of `texture`'s own image at `level` and - /// `layer` (the image's, `extent` texels), one `vkCmdClearColorImage`: nothing is made. Written - /// as a blit's copy into the subresource writes it (a heap shadow's every texel, a sparse - /// texture's scrub), the note of a texture Metal keeps compressed announced as there. - fn clear_in_place( - &mut self, - call: &'static str, - texture: &Texture, - (level, layer): (u32, u32), - [width, height, depth]: [u32; 3], - value: vk::ClearColorValue, - ) -> Result<(), Error> { - let image = texture.raw_image()?; - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - let uses = [texture.image_use(level..level + 1, layer..layer + 1, write, true)?]; - let range = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: level, - level_count: 1, - base_array_layer: layer, - layer_count: 1, - }; - let covered = [Covered { - image, - subresource: vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::COLOR, - mip_level: level, - base_array_layer: layer, - layer_count: 1, - }, - offset: vk::Offset3D::default(), - extent: vk::Extent3D { - width, - height, - depth, - }, - }]; - self.command_reading(&uses, (&[], &covered), |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the image - // is live and retained until it completes, rests in `GENERAL` and was made with - // transfer-destination usage, its format (a color format, neither compressed nor - // YCbCr, nor of 64-bit channels) taking transfer writes in its tiling (`in_place`); - // the range is one of its levels and layers (a 3D image's one). - unsafe { - device.cmd_clear_color_image(raw, image, vk::ImageLayout::GENERAL, &value, &[range]) - }; - })?; - self.core().retain_shared(texture.held()); - let written = ImageRegion { - aspect: ImageAspectFlags::COLOR, - level, - layer, - layers: 1, - origin: [0, 0, 0], - size: [width, height, depth], - }; - self.decode_twin(texture, &[written])?; - self.scrub( - texture, - vec![(vk::ImageAspectFlags::COLOR, Written::of(&written))], - )?; - degrade_compressed_blit(call, texture) - } - - /// A tile the device cleared to `color` (its clear value `value`), of `texture`'s image - /// format, samples and dimension (a 1D image's, or 2D), to copy the region of `size` texels - /// from (the module docs), and its extent: the encoder's tile of that shape and color where - /// it keeps one as large as [`tile_extent`] asks; else, where it keeps [`KEPT_TILES`], its - /// least recently used such tile of another color, cleared again; else a new one, which its - /// command buffer holds until it completes. A tile is cleared whole by the device - /// (`vkCmdClearColorImage`, the device's conversion of a clear value). Kept by the encoder for - /// its later fills ([`FillTiles`]). - fn cleared_tile( - &mut self, - texture: &Texture, - size: [u32; 2], - (value, color): (vk::ClearColorValue, [f64; 4]), - ) -> Result<(Texture, [u32; 2]), Error> { - let pf = texture.pixel_format(); - let (format, one_row) = { - let plan = texture.image_plan()?; - (plan.format, plan.image_type == ImageType::TYPE_1D) - }; - let samples = texture.record().samples; - let shape = TileShape { - pixel_format: pf, - format, - samples, - one_row, - }; - let texel = block_bytes(pf).ok_or_else(|| internal("a fill tile of no texel's bytes"))?; - let first = level_extent(texture.record(), 0); - let extent = tile_extent( - size, - u64::from(texel) * u64::from(samples), - [first[0], first[1]], - ); - let color = color.map(f64::to_bits); - let tile = match self.fill_tiles().take(shape, extent, color) { - Some(Taken::Cleared(tile)) => tile, - Some(Taken::Other(tile)) => { - self.clear_tile(&tile.texture, value)?; - FillTile { color, ..tile } - } - None => { - let texture = self.new_tile(shape, extent)?; - self.clear_tile(&texture, value)?; - FillTile { - shape, - extent, - color, - texture, - } - } - }; - let made = (tile.texture.clone(), tile.extent); - self.fill_tiles().keep(tile); - Ok(made) - } - - /// A tile of `shape` over `width` by `height` texels: a texture the command buffer holds - /// until it completes. - fn new_tile(&mut self, shape: TileShape, [width, height]: [u32; 2]) -> Result { - let TileShape { - pixel_format: pf, - format, - samples, - one_row, - } = shape; - let texture_type = match (one_row, samples > 1) { - (true, _) => TextureType::Type1D, - (false, false) => TextureType::Type2D, - (false, true) => TextureType::Type2DMultisample, - }; - let descriptor = TextureDescriptor { - texture_type, - pixel_format: pf, - width: width.into(), - height: height.into(), - sample_count: samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - // Not a texture Metal keeps compressed, whose blits rewrite texels: the copy out of - // it moves the clear's bits (`compressed_blit.rs`). - allow_gpu_optimized_contents: false, - ..TextureDescriptor::default() - }; - let plan = ImagePlan { - pixel_format: pf, - flags: ImageCreateFlags::empty(), - image_type: match one_row { - true => ImageType::TYPE_1D, - false => ImageType::TYPE_2D, - }, - format, - extent: [width, height, 1], - levels: 1, - layers: 1, - samples: sample_count(samples) - .ok_or_else(|| internal("a fill of a sample count Vulkan lacks"))?, - usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping: FormatMapping::direct(format, ImageAspectFlags::COLOR), - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - Device::new_planned_texture(self.core().command_buffer(), &descriptor, plan) - } - - /// The device's clear of the whole `tile` to `value` (`vkCmdClearColorImage`), after its - /// earlier copies out read it. - fn clear_tile(&mut self, tile: &Texture, value: vk::ClearColorValue) -> Result<(), Error> { - let image = tile.raw_image()?; - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - let uses = [tile.image_use(0..1, 0..1, write, true)?]; - let range = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }; - self.command(&uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the image - // is live until it completes (the command buffer holds the tile), rests in `GENERAL` - // and has transfer-destination usage; the range is its one level and layer, and its - // format, one the device renders, takes transfer writes. - unsafe { - device.cmd_clear_color_image(raw, image, vk::ImageLayout::GENERAL, &value, &[range]) - }; - }) - } - - /// The fill of `pattern` into `region` of `texture`'s `level` and `slice` (the module docs). - fn fill( - &mut self, - call: &'static str, - texture: &Texture, - (level, slice): (u64, u64), - region: Region, - pattern: &[u8], - ) -> Result<(), Error> { - self.core().check_device(call, texture.generation())?; - texture.check_plane_copied()?; - self.see(texture); - check_pattern(call, texture.texture_type(), pattern)?; - let pf = texture.pixel_format(); - // A texture held for copies alone (`metal::format::copies_only`): Metal's fills of one are - // not measured. - if copies_only(pf) { - return Err(Error::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - )); - } - let unit = fill_unit(pf) - .ok_or_else(|| internal("a fill of a format the runtime makes no texture of"))?; - // A texture buffer's fill writes one row whatever the region's height and depth. - if texture.texture_type() == TextureType::TextureBuffer { - return self.texture_buffer_fill(texture, unit, region, pattern); - } - let Size { - width, - height, - depth, - } = region.size; - if width == 0 || height == 0 || depth == 0 { - return Ok(()); - } - let Some((slice, images)) = placement(texture, level, slice, region)? else { - return Ok(()); - }; - let level_u32 = u32::try_from(level).map_err(|_| internal("a fill's level"))?; - let [w, h, _] = level_extent(texture.record(), level_u32).map(u64::from); - let (bytes, extent, option) = match unit { - FillUnit::Blocks { bytes, extent } => (bytes, extent, BlitOption::None), - FillUnit::Texels { bytes, option } => (bytes, [1, 1], option), - FillUnit::PlaneWords => (4, [1, 1], BlitOption::None), - FillUnit::PackedCodes => (1, [1, 1], BlitOption::None), - }; - let [bw, bh] = extent.map(u64::from); - let x = cut(region.origin.x, width, w.div_ceil(bw)); - let y = cut(region.origin.y, height, h.div_ceil(bh)); - if x.is_empty() || y.is_empty() { - return Ok(()); - } - if texture.record().samples > 1 { - return self.sample_fill(call, texture, (level_u32, slice), option, (x, y), pattern); - } - let mut unit_bytes = unit_of(pattern, bytes); - // Into a texture Metal keeps compressed: Metal's encoding of the texel, written as it is. - if compressed_blit::canonical(texture) { - compressed_blit::canonical_fill_unit(&mut unit_bytes); - } - if unit == FillUnit::PackedCodes { - return self.packed_code_fill(texture, (x, y)); - } - if unit == FillUnit::PlaneWords && !texture.over_buffer() { - // Every level's fill writes the heap's bytes of level 0 of the slice, at its rows; a - // mipmapped 3D texture's past its first depth image, none (the module docs). - if let Some((heap, at, layout)) = texture.heap_two_planes() { - if texture.texture_type() == TextureType::Type3D - && layout.levels > 1 - && images.start > 0 - { - return Ok(()); - } - let at = at + slice * layout.color_slice; - return self.plane_heap_fill( - texture, - (heap, at), - layout.width, - (x, y), - &unit_bytes, - ); - } - // Every level is filled as level 0, at Metal's fill rows (the module docs). - return self.plane_texel_fill(texture, slice, (x, y), &unit_bytes); - } - self.fill_rows( - texture, - (level, slice, images), - option, - (x, y), - ([bw, bh], [w, h]), - &unit_bytes, - ) - } - - /// The fill of `pattern` into the texels `x` by `y` of the multisampled `texture`'s `level` - /// and `slice`, in the aspect `option` names (the module docs): each sample its own bits - /// ([`sample_units`]), written by the sample planes' merge into a multisampled image of the - /// unsigned-integer format of the texel's size ([`BitsCopy::fill`]), which a blit copy then - /// moves into the texture's region as a copy between multisampled textures moves it - /// (`blit_texture.rs`: an image copy, the planes' copies where the device's copy converts - /// float NaNs, a depth or stencil aspect's copies or draws, `sample_copy.rs`, exact or - /// announced as there). A 32-bit float depth on a device that may store one outside `[0, 1]` - /// clamped takes its samples' depths clamped on the CPU first, announced - /// `restricted-depth-upload` (`depth_clamp.rs`). - fn sample_fill( - &mut self, - call: &'static str, - texture: &Texture, - (level, slice): (u32, u64), - option: BlitOption, - (x, y): (Range, Range), - pattern: &[u8], - ) -> Result<(), Error> { - let record = texture.record(); - let samples = record.samples; - let CopyUnit { bytes, aspect, .. } = blit_texture::unit(call, texture, option)?; - let copy = match bytes { - 1 => PlanesCopy::R8, - 2 => PlanesCopy::R16, - 4 => PlanesCopy::R32, - 8 => PlanesCopy::Rg32, - 16 => PlanesCopy::Rgba32, - _ => { - return Err(internal( - "a multisampled texel of no unsigned format's size", - )) - } - }; - // A 32-bit float depth on a device that may store a value outside [0, 1] clamped takes - // each sample's depth clamped first, as every upload into such a depth does - // (`depth_clamp.rs`): the copy into the depth image takes no value outside. - let clamps = bytes == 4 && texture.clamps_depth_upload(aspect); - let values: Vec<[u32; 4]> = sample_units(pattern, bytes, samples) - .iter() - .map(|unit| { - let mut words = words(unit); - if clamps { - words[0] = clamped_depth(words[0]); - } - words - }) - .collect(); - if clamps { - texture.degrade_depth_upload(call, aspect, false); - self.core().device().shared().counts.depth_upload_clamped(); - } - let narrow = |range: &Range| -> Result<[u32; 2], Error> { - let start = u32::try_from(range.start).map_err(|_| internal("a fill's origin"))?; - let end = u32::try_from(range.end).map_err(|_| internal("a fill's extent"))?; - Ok([start, end - start]) - }; - let ([left, width], [top, height]) = (narrow(&x)?, narrow(&y)?); - let (scratch, fill) = BitsCopy::fill( - self.core().command_buffer(), - copy, - &values, - [left, top], - [width, height], - )?; - self.command_in(BITS_COPY_STAGES, &fill.uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // scratch image and the fill's planes and objects are live until it completes - // (retained below). - unsafe { fill.record(device, raw) }; - })?; - self.core().retain(vec![fill]); - let slice = u32::try_from(slice).map_err(|_| internal("a fill's slice"))?; - let region = |aspect, level, layer| ImageRegion { - aspect, - level, - layer, - layers: 1, - origin: [left, top, 0], - size: [width, height, 1], - }; - let copy = ImageCopyRegion { - src: region(ImageAspectFlags::COLOR, 0, 0), - dst: region(aspect, record.base_level + level, record.base_layer + slice), - }; - self.texture_copies(call, &scratch, texture, &[copy]) - } - - /// Copy `unit` into the units `x` by `y` of each depth image `images` of `texture`'s `level` - /// and `slice`, `block` texels each (cut at the level's `size`), through `option`: copies - /// from one staging buffer of whole rows of units, in rows of at most `STAGING_BYTES`. - fn fill_rows( - &mut self, - texture: &Texture, - (level, slice, images): (u64, u64, Range), - option: BlitOption, - (x, y): (Range, Range), - (block, size): ([u64; 2], [u64; 2]), - unit: &[u8], - ) -> Result<(), Error> { - let row_bytes = (x.end - x.start) * unit.len() as u64; - let per_copy = (STAGING_BYTES / row_bytes).clamp(1, y.end - y.start); - let staging = self.staging(unit, row_bytes * per_copy)?; - let left = x.start * block[0]; - let width = (x.end * block[0]).min(size[0]) - left; - for z in images { - let mut row = y.start; - while row < y.end { - let end = (row + per_copy).min(y.end); - let top = row * block[1]; - let height = (end * block[1]).min(size[1]) - top; - self.unlogged(|this| { - this.buffer_into_texture( - Writer::Fill, - (&staging, 0, row_bytes, row_bytes * (end - row)), - Size::new(width, height, 1), - (texture, slice, level, Origin::new(left, top, z)), - option, - ) - })?; - row = end; - } - } - Ok(()) - } - - /// Write `word` at each texel `x` by `y` of a level of the two-plane `texture` whose first - /// level, `width` texels wide, has the slice filled lying in `heap`'s bytes from byte `at`, at - /// Metal's fill rows of that first level: the texels' color words, rows that meet merged, in - /// one copy into the heap's bytes. Its alpha bytes are not written. - fn plane_heap_fill( - &mut self, - texture: &Texture, - (heap, at): (&Heap, u64), - width: u64, - (x, y): (Range, Range), - word: &[u8], - ) -> Result<(), Error> { - let Some(bytes) = heap.bytes() else { - return Err(internal("a two-plane texture's bytes in a heap of none")); - }; - let rows = two_planes::buffer_blit_rows(width, true); - // Each row's words, from byte `at + row * rows + 4 x`; rows ascend, so a row that meets - // the one before extends it. - let mut spans: Vec> = Vec::new(); - for row in y { - let span = at + row * rows + 4 * x.start..at + row * rows + 4 * x.end; - match spans.last_mut() { - Some(last) if span.start <= last.end => last.end = last.end.max(span.end), - _ => spans.push(span), - } - } - self.fill_spans(bytes, &spans, word)?; - self.core().retain_shared(texture.held()); - Ok(()) - } - - /// Write `unit` repeated from each span's first byte into the bytes `spans` of `buffer` - /// (ascending, disjoint), in one command of copies from a staging buffer. - fn fill_spans( - &mut self, - buffer: &Buffer, - spans: &[Range], - unit: &[u8], - ) -> Result<(), Error> { - let (Some(first), Some(last)) = (spans.first(), spans.last()) else { - return Ok(()); - }; - let written = first.start..last.end; - // A staging buffer of whole units, so each copy from its start begins the unit again. - let longest = spans.iter().map(|s| s.end - s.start).max().unwrap_or(0); - let whole = unit.len() as u64; - let length = longest.min((STAGING_BYTES / whole).max(1) * whole); - let staging = self.staging(unit, length)?; - let (source, from) = staging.at(0); - // Read as a blit's (`host_residency.rs`). - let (destination, base) = self.core().blit_at(buffer, written.start)?; - let mut regions = Vec::new(); - for span in spans { - let mut start = span.start; - while start < span.end { - let size = (span.end - start).min(length); - regions.push(vk::BufferCopy { - src_offset: from, - dst_offset: base + (start - written.start), - size, - }); - start += size; - } - } - let uses = [reads(&staging, 0..length), writes(buffer, written)]; - self.command(&uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording; the staging buffer and the - // buffer are live and retained until it completes; each region lies inside both, - // and the buffer's regions are disjoint. - unsafe { device.cmd_copy_buffer(raw, source, destination, ®ions) }; - })?; - self.core().retain_shared(staging.held()); - Ok(()) - } - - /// Write `pattern` into the bytes of the texture buffer `texture`'s buffer that the texels `x` - /// to `x + width` of `region` cover from its offset, past its width too (cut at the buffer's - /// end), whatever the level, slice, row, height and depth, as Metal writes them - /// ([`StreamFill`]; the module docs): a width of 0 writes nothing. Its pattern's length is - /// already checked ([`check_pattern`]). - fn texture_buffer_fill( - &mut self, - texture: &Texture, - unit: FillUnit, - region: Region, - pattern: &[u8], - ) -> Result<(), Error> { - let FillUnit::Texels { bytes, .. } = unit else { - return Err(internal("a texture buffer of no texel format")); - }; - let Some(texels) = texture.buffer_texels() else { - return Err(internal("a texture buffer over no buffer")); - }; - let buffer = texels.buffer.clone(); - let bytes = u64::from(bytes); - let length = buffer.length(); - let start = texels - .layout - .offset - .saturating_add(region.origin.x.saturating_mul(bytes)) - .min(length); - let end = start - .saturating_add(region.size.width.saturating_mul(bytes)) - .min(length); - if start >= end { - return Ok(()); - } - let stream = StreamFill::new(pattern); - for (span, unit) in stream.spans(start..end) { - self.fill_spans(&buffer, &[span], &unit)?; - } - if stream.reads_leftover(start..end) { - let format = texture.pixel_format(); - self.core() - .device() - .degrade(Degradation::TextureBufferFillLeftover, || { - ( - format!( - "a fill of a {format:?} texture buffer with a pattern of {} bytes", - pattern.len() - ), - "Metal reads bytes of its stack past the pattern's whole copies there, \ - zeros in our probes and other bytes in other processes; the runtime \ - reads zeros" - .to_owned(), - ) - }); - } - self.core().retain_shared(texture.held()); - Ok(()) - } - - /// Fill the texels `x` by `y` of a packed two-plane YCbCr `texture` over a surface's plane: - /// one zero byte at each texel's `x` of its row of the plane (the module docs). - fn packed_code_fill( - &mut self, - texture: &Texture, - (x, y): (Range, Range), - ) -> Result<(), Error> { - let Some(texels) = texture.buffer_texels() else { - return Err(internal("a packed two-plane texture over no surface")); - }; - let (offset, pitch) = (texels.layout.offset, texels.layout.row_pitch); - let spans: Vec> = y - .map(|row| offset + row * pitch) - .map(|start| start + x.start..start + x.end) - .collect(); - let buffer = texels.buffer.clone(); - self.fill_spans(&buffer, &spans, &[0])?; - self.core().retain_shared(texture.held()); - Ok(()) - } - - /// Write `word` at the texels of level 0 of `slice` of the two-plane extended-range `texture` - /// (of its own memory, or a heap's held apart) that a fill of the units `x` by `y` of any of - /// its levels writes (the module docs): copies of the color words alone, at Metal's fill - /// rows mapped onto the texels' rows. - fn plane_texel_fill( - &mut self, - texture: &Texture, - slice: u64, - (x, y): (Range, Range), - word: &[u8], - ) -> Result<(), Error> { - let [width, height, _] = level_extent(texture.record(), 0).map(u64::from); - let layer = u32::try_from(slice).map_err(|_| internal("a fill's slice"))?; - // The words a fill writes between the level's rows: held where its blits with a buffer - // read them back (one level, `two_planes::rows_held`), as the rows of plane 0 Metal's - // fill writes, rows that meet merged; else not held, noted, so a blit that reads them - // back announces it (`two_planes.rs`). - let size = [x.end - x.start, y.end - y.start]; - let spans = two_planes::row_spans(width, [x.start, y.start], size, true); - if spans - .iter() - .flatten() - .any(|span| two_planes::between_rows(span, width)) - { - if two_planes::rows_held(texture) { - let held = self.held_between_rows(texture, [width, height])?; - let base = slice * height * (4 * width).next_multiple_of(16); - let mut merged: Vec> = Vec::new(); - for span in spans.into_iter().flatten() { - let span = base + span.start..base + span.end; - match merged.last_mut() { - Some(last) if span.start <= last.end => last.end = last.end.max(span.end), - _ => merged.push(span), - } - } - self.fill_spans(&held, &merged, word)?; - } else { - texture.keep_outside(); - } - } - for (columns, rows) in plane_rectangles(width, x, y) { - let w = columns.end - columns.start; - let per_copy = (STAGING_BYTES / (4 * w)).clamp(1, rows.end - rows.start); - let staging = self.staging(word, 4 * w * per_copy)?; - let mut row = rows.start; - while row < rows.end { - let end = (row + per_copy).min(rows.end); - let region = ImageRegion { - aspect: ImageAspectFlags::COLOR, - level: 0, - layer, - layers: 1, - origin: [columns.start, row, 0].map(|v| v as u32), - size: [w, end - row, 1].map(|v| v as u32), - }; - let layout = BufferLayout { - offset: 0, - bytes_per_row: 4 * w, - bytes_per_image: 4 * w * (end - row), - }; - self.plane_words_copy(&staging, texture, ®ion, &layout, true)?; - row = end; - } - self.core().retain(staging); - } - Ok(()) - } - - /// A `Shared` buffer of `length` bytes of `unit` repeated, the source of a fill's copies. - fn staging(&mut self, unit: &[u8], length: u64) -> Result { - let bytes: Vec = unit.iter().copied().cycle().take(length as usize).collect(); - self.staged(&bytes) - } - - /// A `Shared` buffer of `bytes`, written through its mapping (seen by the device at the - /// commit's submission). - fn staged(&mut self, bytes: &[u8]) -> Result { - let buffer = self - .core() - .device() - .write_combined_buffer(bytes.len() as u64)?; - let Some(contents) = buffer.mapped_contents() else { - return Err(Error::Vulkan(super::error::VkResultCode( - vk::Result::ERROR_MEMORY_MAP_FAILED.as_raw(), - ))); - }; - // SAFETY: the mapping covers the buffer's `bytes.len()` bytes, which nothing else uses - // yet. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; - Ok(buffer) - } -} diff --git a/crates/metal2vulkan-runtime/src/blit_indirect.rs b/crates/metal2vulkan-runtime/src/blit_indirect.rs deleted file mode 100644 index 62cb93286..000000000 --- a/crates/metal2vulkan-runtime/src/blit_indirect.rs +++ /dev/null @@ -1,472 +0,0 @@ -//! The blit encoder's indirect command buffer commands (`copyIndirectCommandBuffer:...`, -//! `resetCommandsInBuffer:withRange:`, `optimizeIndirectCommandBuffer:withRange:`). -//! -//! - **What Metal answers** (an M3 Max, with and without `MTL_DEBUG_LAYER`). A copy between buffers -//! of one descriptor copies the commands: the destination's getters and execution read them. -//! Between buffers of different descriptors the copy is garbled, and a copy that runs past the -//! destination's end corrupts its command 0; validation stops neither. A reset resets the -//! commands as `resetWithRange:` does. An optimize changes nothing a getter or an execution -//! observes. -//! - **The runtime.** The commands are records of one format whatever the descriptor, so a copy -//! copies the records' bytes ([`BlitCommandEncoder::copy_from_buffer_to_buffer`], which moves -//! overlapping ranges of one buffer as `memmove` does); a record the destination's descriptor -//! does not allow runs nothing where an execution meets it (`ReplayFaults::RECORD`), the defined -//! answer for Metal's garbled one; it sets the destination commands' written flags -//! (`indirect_commands::written_flag_offset`) by one fill. A reset writes the reset record, all -//! zero (`CommandRecord::default`'s bytes), over each command whose written flag is set, and -//! clears the flag, by dispatches of `bind::icb_reset_module`, one workgroup a command, each -//! dispatch a run of commands whose records one storage-buffer binding holds: every writer of -//! the records sets the flag of each record it writes (a kernel's encoder operations, the CPU's -//! setters, a copy) and the CPU's writes of the reset record clear it, so a clear flag's record -//! holds the reset record already, and a reset of many commands of which few were written -//! stores those few records rather than every record of the range (where the records lie in -//! host memory across a discrete GPU's link, the range's whole bytes over the link). Both write -//! the destination's records on the GPU as the command buffer runs, so the call marks it -//! written by the GPU (`IndirectCommandBuffer::written_by_gpu`): its executions run the records -//! as they stand once the work before them completed. An optimize records nothing. Counted as -//! encoded, in the records' bytes of the range (`COMMAND_BYTES` a command, whatever the -//! descriptor, a reset's flagged or not): `WorkCounts::indirect_record_bytes_gpu_copied` and -//! `indirect_record_bytes_gpu_reset`; and each reset dispatch's GPU time, between timestamps -//! written around it where the device writes them, as a rate-mapped pass's pieces are timed -//! (`rate_mapped_pass::PieceTimes`): `indirect_record_reset_gpu_nanos`. -//! - **What a reset costs** (an RTX 2080 on a PCIe 3.0 x4 link, NVIDIA 620.70.06, release, the -//! median GPU time of 15 command buffers of one reset each, two runs alike). A reset of 45,000 -//! render commands (101 MB of records in host-cached system memory) took 0.26 ms with no command -//! written since the last reset, 1.74 ms with 1,300 written by the CPU, and 60.5 ms with every -//! command written, where one fill of the same records took 56.8 ms whatever was written. So a -//! buffer whose every command is written between resets resets about 6% slower than a fill -//! would, a known gap; the flags' reads alone took 0.26 ms of it. A kernel's flag stores, one -//! per operation, took a kernel that encodes 45,000 render commands (two buffers and a draw -//! each) from 19.80 ms to 20.11 ms. -//! - **A buffer of no command types beside one of command types.** The copy completes and moves -//! nothing, as plain Metal's does. Metal's own answer, read through what the destination then -//! paints rather than through its status (an M3 Max, macOS 27.0.1, build 26A434, the validation -//! layer off, one shape per process, four processes a shape, all four alike, no byte of a 0xEE -//! guard at the next 256-aligned placement-heap offset past the vertex buffer touched; -//! `probes/icb_argument_encode_and_copy_destinations.m`): a copy of 4 commands from a buffer of -//! no command types over a `Draw` buffer whose command 0 held a draw of the whole target -//! completed, status 4 and no error, and the destination still painted 0.75 — so nothing moved, -//! not even the source's reset records. Both controls ran live beside it: the same copy from a -//! fresh `Draw` buffer left -1 (the copy does write), and a copy from a `Draw` buffer that held -//! the draw into a reset `Draw` buffer painted 0.75 (the copy does carry records). The other -//! direction is beyond any public Metal call: a buffer of no command types has no setter Metal -//! survives, no read-back, an execution that paints nothing, and a copy out of it that moves -//! nothing, so a copy into it cannot be read — `Draw` -> none -> `Draw` painted -1 where -//! `Draw` -> `Draw` -> `Draw` painted 0.75, which the second copy alone accounts for. Recording -//! nothing is the one answer that matches every observation there is. Metal places no indirect -//! command buffer in a placement heap, so no guard can sit beside a copy's destination. -//! - **Refused** (`Invalid`, changing nothing): a buffer of another device, and a range past -//! either buffer's size, which Metal runs as a corruption no program relies on. -//! - **What a command holds** (the M4 probe, plain Metal). A copy and a reset hold the -//! records they read and write until the command buffer completes, but not the buffers: a buffer -//! the program releases meanwhile gives its ID back at once, as Metal handed a blit's buffer's ID -//! out again while the blit waited. An optimize holds nothing. - -use super::blit::{reads, writes, writes_by, BlitCommandEncoder}; -use super::error::{internal, Error}; -use super::indirect_command_buffer::{IndirectCommandBuffer, Overflow}; -use super::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet}; -use super::rate_mapped_pass::PieceTimes; -use super::replay::BlitCall; -use super::tracker::Access; -use super::write_routes::GpuWriter; -use ash::vk; -use metal2vulkan::bind::indirect_commands::COMMAND_BYTES; -use metal2vulkan::bind::IcbResetModule; -use std::ops::Range; - -impl BlitCommandEncoder { - /// `copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:`: commands - /// `source_range` of `source` become commands `destination_index..` of `destination` as the - /// command buffer runs, as on Metal (the module docs). An empty range copies nothing. - /// - /// A buffer of no command types beside one of command types copies nothing, as plain Metal's - /// does (the module docs); two buffers of no command types copy as any others, as plain - /// Metal's do. - /// - /// Refused (`Invalid`): a buffer of another device, and a range past either buffer's size - /// (`IndirectCommandBufferProblem::Range`). - pub fn copy_indirect_command_buffer( - &mut self, - source: &IndirectCommandBuffer, - source_range: Range, - destination: &IndirectCommandBuffer, - destination_index: u64, - ) -> Result<(), Error> { - self.logged( - |_| { - BlitCall::CopyIndirectCommandBuffer(Box::new(( - source.clone(), - source_range.clone(), - destination.clone(), - destination_index, - ))) - }, - |this| { - const CALL: &str = "copy_indirect_command_buffer"; - this.core().check_device(CALL, source.generation())?; - this.core().check_device(CALL, destination.generation())?; - let from = source.command_range(CALL, source_range.clone())?; - let count = u64::from(from.end - from.start); - let to = destination.command_range( - CALL, - destination_index..destination_index.saturating_add(count), - )?; - // A buffer of no command types beside one of command types: the records of one - // side are of commands the other's descriptor has no kind for at all, and Metal - // moves none of them (the module docs), so the copy records nothing. - if source.has_no_command_types() != destination.has_no_command_types() { - return Ok(()); - } - if from.is_empty() { - return Ok(()); - } - // The records held where they lie in device-local memory, a copy's as any GPU - // work's (`indirect_command_buffer/home.rs`). - source.hold_records(this.core(), false); - destination.hold_records(this.core(), true); - destination.written_by_gpu(GpuWriter::Copy); - this.core().retain(destination.gpu_write()); - destination.keep_copied(source, from.clone()); - destination.written().copied_from(source.written()).mark(); - // The slots past the records', carried as Metal's copy carries every slot below the - // count. - this.copy_overflow(source, from.clone(), destination, to.start)?; - // The destination commands' written flags, set: a reset writes their records. - let flags = destination.flag_bytes(to.clone()); - let storage = destination.storage(); - let (raw, at) = storage.at(flags.start); - let size = flags.end - flags.start; - this.command(&[writes(storage, flags)], |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording; the storage is live and - // retained until it completes; the flags lie inside it, their offset and size - // multiples of 4 (`u32`s past the records, which end at a multiple of 8). - unsafe { device.cmd_fill_buffer(command_buffer, raw, at, size, 1) }; - })?; - let bytes = IndirectCommandBuffer::record_bytes(from); - let at = IndirectCommandBuffer::record_bytes(to).start; - let counts = &this.core().device().shared().counts; - counts.indirect_record_bytes_gpu_copied(bytes.end - bytes.start); - this.unlogged(|this| { - this.copy_from_buffer_to_buffer( - source.storage(), - bytes.start, - destination.storage(), - at, - bytes.end - bytes.start, - ) - })?; - this.core().retain(source.storage().clone()); - this.core().retain(destination.storage().clone()); - Ok(()) - }, - ) - } - - /// `resetCommandsInBuffer:withRange:`: commands `range` of `buffer` are reset, as a fresh - /// buffer's, as the command buffer runs. An empty range resets nothing. - /// - /// Refused (`Invalid`): a buffer of another device, and a range past its size - /// (`IndirectCommandBufferProblem::Range`). A buffer of no command types is taken as any - /// other, as plain Metal takes it. - pub fn reset_commands_in_buffer( - &mut self, - buffer: &IndirectCommandBuffer, - range: Range, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::ResetCommandsInBuffer(buffer.clone(), range.clone()), - |this| { - const CALL: &str = "reset_commands_in_buffer"; - this.core().check_device(CALL, buffer.generation())?; - let range = buffer.command_range(CALL, range.clone())?; - if range.is_empty() { - return Ok(()); - } - // The records held where they lie in device-local memory, a reset's as any GPU - // work's (`indirect_command_buffer/home.rs`). - buffer.hold_records(this.core(), true); - buffer.written_by_gpu(GpuWriter::Reset); - this.core().retain(buffer.gpu_write()); - let bytes = IndirectCommandBuffer::record_bytes(range.clone()); - let counts = &this.core().device().shared().counts; - counts.indirect_record_bytes_gpu_reset(bytes.end - bytes.start); - this.reset_flagged(buffer, range.clone())?; - this.core().retain(buffer.storage().clone()); - // The slots past the records', cleared as Metal's reset clears every slot. - if let Some(overflow) = buffer.overflow() { - this.clear_overflow(overflow, overflow.bytes(range))?; - } - Ok(()) - }, - ) - } - - /// Reset the flagged commands of `range` of `buffer` (the module docs), by dispatches of the - /// flagged reset, each a run of commands whose records' and flags' bindings start at the - /// device's storage-buffer alignment below them and fit its range and workgroup count. - fn reset_flagged( - &mut self, - buffer: &IndirectCommandBuffer, - range: Range, - ) -> Result<(), Error> { - let device = self.core().device().clone(); - let kernel = device.owned_kernel(OwnedModule::IcbReset)?; - let limits = &device.properties().description.limits; - let align = limits.min_storage_buffer_offset_alignment.max(4); - let most = u64::from(limits.max_storage_buffer_range); - // Commands a run takes: its records from below an aligned offset within the range (at - // least 2^27 bytes, `maxStorageBufferRange`'s least, holds many), and one workgroup each. - let run = most.saturating_sub(align.max(8)) / COMMAND_BYTES as u64; - let run = run.min(u64::from(limits.max_compute_work_group_count[0])); - let run = u32::try_from(run).unwrap_or(u32::MAX).max(1); - let compute = vk::PipelineStageFlags2::COMPUTE_SHADER; - let access = Access::new( - compute, - vk::AccessFlags2::SHADER_STORAGE_READ | vk::AccessFlags2::SHADER_STORAGE_WRITE, - ); - let storage = buffer.storage(); - let mut start = range.start; - while start < range.end { - let end = start.saturating_add(run).min(range.end); - let records = IndirectCommandBuffer::record_bytes(start..end); - let flags = buffer.flag_bytes(start..end); - let (raw, record_at) = storage.at(records.start); - let (_, flag_at) = storage.at(flags.start); - // The records binding holds 8-byte pairs: its offset at a multiple of 8 too, and the - // records at one (`COMMAND_BYTES`: the storage is 8-byte aligned). - if !record_at.is_multiple_of(8) { - return Err(internal( - "an indirect command buffer's records not 8-byte aligned", - )); - } - let record_offset = record_at - record_at % align.max(8); - let flag_offset = flag_at - flag_at % align; - let set = OwnedSet { - images: Vec::new(), - storage_images: Vec::new(), - buffers: vec![ - ( - raw, - record_offset, - record_at - record_offset + (records.end - records.start), - ), - ( - raw, - flag_offset, - flag_at - flag_offset + (flags.end - flags.start), - ), - ], - }; - let binds = OwnedBinds::new(&device, &kernel, &[set])?; - // Each first place below the alignment, a `u32`. - let firsts = IcbResetModule::firsts( - ((record_at - record_offset) / 8) as u32, - ((flag_at - flag_offset) / 4) as u32, - ); - let [x, y, z] = IcbResetModule::groups(end - start); - let uses = [ - writes_by(storage, records, access), - writes_by(storage, flags, access), - ]; - // The dispatch's GPU time, where the device writes timestamps - // (`WorkCounts::indirect_record_reset_gpu_nanos`). - let times = PieceTimes::icb_reset(&device); - self.command_in(compute, &uses, |raw, command_buffer| { - // SAFETY: the encoder's command buffer is recording, outside a render pass; the - // kernel is the device's, and the storage is live and retained until the command - // buffer completes (the caller); the bindings hold the run's records and flags, - // within the device's range and alignment, and the dispatch is one workgroup a - // command of the run; the times are retained with the command buffer below. - unsafe { - if let Some(times) = × { - times.begin(raw, command_buffer, 0); - } - raw.cmd_bind_pipeline( - command_buffer, - vk::PipelineBindPoint::COMPUTE, - kernel.pipeline, - ); - binds.bind(raw, command_buffer, &kernel, 0); - raw.cmd_push_constants( - command_buffer, - kernel.layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &firsts, - ); - raw.cmd_dispatch(command_buffer, x, y, z); - if let Some(times) = × { - times.end(raw, command_buffer, 0); - } - } - })?; - if let Some(times) = times { - self.core().retain(times); - } - if let OwnedBinds::Sets(sets) = binds { - self.core().retain(sets); - } - start = end; - } - Ok(()) - } - - /// Carry the slots past the records' of `source`'s commands `from` into `destination`'s from - /// command `to`, as the copy carries the records: every slot of a stage both hold, and the - /// destination's slots past the source's cleared, which the source holds unset; and the - /// threadgroup lengths and words past the records', lengths 36 and 37 cleared where the - /// destination's commands hold pipeline words, as Metal's copy clears them - /// (`Overflow::copy_clears`). - fn copy_overflow( - &mut self, - source: &IndirectCommandBuffer, - from: Range, - destination: &IndirectCommandBuffer, - to: u32, - ) -> Result<(), Error> { - let Some(into) = destination.overflow() else { - return Ok(()); - }; - let count = from.end - from.start; - let held = match source.overflow() { - None => return self.clear_overflow(into, into.bytes(to..to + count)), - Some(held) if held.same_layout(into) => { - let bytes = held.bytes(from); - let at = into.bytes(to..to).start; - self.unlogged(|this| { - this.copy_from_buffer_to_buffer( - held.storage(), - bytes.start, - into.storage(), - at, - bytes.end - bytes.start, - ) - })?; - self.core().retain(held.storage().clone()); - self.core().retain(into.storage().clone()); - return self.clear_runs(into, to..to + count); - } - Some(held) => held, - }; - // Two layouts, so two buffers: no copy overlaps another. - let read = held.bytes(from.clone()); - let (mut copies, mut clears) = (Vec::new(), Vec::new()); - for (offset, index) in from.enumerate() { - let runs = held.runs(index, into, to + offset as u32); - copies.extend(runs.copies); - clears.extend(runs.clears); - } - let (source_raw, _) = held.storage().at(0); - let (raw, _) = into.storage().at(0); - let regions: Vec = copies - .iter() - .map(|&(read, write, size)| vk::BufferCopy { - src_offset: held.storage().at(read).1, - dst_offset: into.storage().at(write).1, - size, - }) - .collect(); - let fills: Vec<(u64, u64)> = clears - .iter() - .map(|&(at, size)| (into.storage().at(at).1, size)) - .collect(); - let written = into.bytes(to..to + count); - let uses = [reads(held.storage(), read), writes(into.storage(), written)]; - self.command(&uses, |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording; both buffers are live and - // retained until it completes; each region lies inside both, and none overlaps - // another (two buffers). - unsafe { - if !regions.is_empty() { - device.cmd_copy_buffer(command_buffer, source_raw, raw, ®ions); - } - for &(at, size) in &fills { - device.cmd_fill_buffer(command_buffer, raw, at, size, 0); - } - } - })?; - self.core().retain(held.storage().clone()); - self.core().retain(into.storage().clone()); - Ok(()) - } - - /// Clear the runs of commands `range` of `overflow` a copy into them clears after it carried - /// the source's blocks (`Overflow::copy_clears`), by one copy from zeroed bytes of the upload - /// arena: a fill a run costs the device a command each. - fn clear_runs(&mut self, overflow: &Overflow, range: Range) -> Result<(), Error> { - let runs = overflow.copy_clears(range.clone()); - let Some(&(_, size)) = runs.first() else { - return Ok(()); - }; - let device = self.core().device().clone(); - let zeros = vec![0u8; size as usize]; - let upload = self - .core() - .command_buffer() - .state() - .uploads - .upload(&device, &zeros, size)?; - let storage = overflow.storage(); - let regions: Vec = runs - .iter() - .map(|&(at, size)| vk::BufferCopy { - src_offset: upload.offset(), - dst_offset: storage.at(at).1, - size, - }) - .collect(); - let (from, (raw, _)) = (upload.raw(), storage.at(0)); - self.command( - &[writes(storage, overflow.bytes(range))], - |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording; the overflow is live and - // retained until it completes, and the arena's region until the command buffer - // completes; each region lies inside both, and none overlaps another. - unsafe { device.cmd_copy_buffer(command_buffer, from, raw, ®ions) }; - }, - )?; - self.core().retain(storage.clone()); - Ok(()) - } - - /// Clear `bytes` of `overflow`, the slots of commands a reset or a copy clears. - fn clear_overflow(&mut self, overflow: &Overflow, bytes: Range) -> Result<(), Error> { - if bytes.is_empty() { - return Ok(()); - } - let storage = overflow.storage(); - let (raw, at) = storage.at(bytes.start); - let size = bytes.end - bytes.start; - self.command(&[writes(storage, bytes)], |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording; the overflow is live and - // retained until it completes; the range lies inside it, its offset and size multiples - // of 4 bytes. - unsafe { device.cmd_fill_buffer(command_buffer, raw, at, size, 0) }; - })?; - self.core().retain(storage.clone()); - Ok(()) - } - - /// `optimizeIndirectCommandBuffer:withRange:`: nothing Metal's optimize changes is - /// observable, so it records nothing. - /// - /// Refused (`Invalid`): a buffer of another device, and a range past its size - /// (`IndirectCommandBufferProblem::Range`). A buffer of no command types is taken as any - /// other, as plain Metal takes it. - pub fn optimize_indirect_command_buffer( - &mut self, - buffer: &IndirectCommandBuffer, - range: Range, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::OptimizeIndirectCommandBuffer(buffer.clone(), range.clone()), - |this| { - const CALL: &str = "optimize_indirect_command_buffer"; - this.core().check_device(CALL, buffer.generation())?; - buffer.command_range(CALL, range.clone())?; - Ok(()) - }, - ) - } -} diff --git a/crates/metal2vulkan-runtime/src/blit_plan.rs b/crates/metal2vulkan-runtime/src/blit_plan.rs deleted file mode 100644 index 1f8340efe..000000000 --- a/crates/metal2vulkan-runtime/src/blit_plan.rs +++ /dev/null @@ -1,1248 +0,0 @@ -//! The blit encoder's texture copies: `copyFromBuffer:...toTexture:`, -//! `copyFromTexture:...toBuffer:` and the texture-to-texture copies, as Vulkan copy regions, with -//! Metal's rules as `copy_plan.rs` states them. -//! -//! Vulkan takes a buffer layout in texels per row and rows per image, at offsets aligned to the -//! texel block (and to 4 bytes for a depth/stencil image). A layout Vulkan cannot state that way -//! is copied through a tightly packed staging layout ([`Staging`]). -//! -//! A layout off Metal's rules (an offset or `bytesPerRow` off the copy unit, rows of more than -//! one that overlap, or a `bytesPerImage` of more than one image off the copy unit or below the -//! region's rows) is copied where plain Metal copies it (an M4 under macOS 27.0.1; its validation -//! stops it): each row at `offset + z * bytesPerImage + y * bytesPerRow` rounded down to the copy -//! unit or to 4 bytes, whichever is smaller, and a copy into a texture of one image of more than -//! one row, from offset 0, with `bytesPerRow` rounded down to the copy unit a multiple of 16, at -//! that rounded pitch (Metal's aligned path). Out of a texture, rows and images that overlap are -//! written in turn, a later one's bytes over an earlier one's. A region of one image ignores -//! `bytesPerImage`. [`placed_rows`] states what stays refused. - -use super::chroma_pairs::is_four_two_two; -use super::copy_plan::{ - block_bytes, block_extent, check_region, colour_unit, copy_unit, level_extent, shape, - BlitOption, CopyProblem, CopyRefusal, CopyUnit, ImageRegion, Shape, TextureRegion, -}; -use super::error::RuntimeGap; -use super::image_plan::ImagePlan; -use super::linear_plan::{plane_rows_share_bytes, BufferLayout as TexelsLayout}; -use super::pvrtc::is_pvrtc; -use super::two_planes; -use super::view_plan::ViewRecord; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{is_depth_stencil, ycbcr}; -use metal2vulkan::metal::PixelFormat; -use metal2vulkan::vk::ImageAspectFlags; -use std::collections::BTreeMap; -use std::ops::Range; - -/// A buffer's side of a copy: `sourceOffset`, `sourceBytesPerRow`, `sourceBytesPerImage` (or the -/// destination's). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct BufferLayout { - pub(super) offset: u64, - pub(super) bytes_per_row: u64, - pub(super) bytes_per_image: u64, -} - -impl BufferLayout { - /// The offset of row `y` of image `z`, `offset + z * bytesPerImage + y * bytesPerRow`; `None` - /// past `u64::MAX`, where no buffer's byte lies. The layout's values are the caller's, so - /// every row the runtime places is found through this. - pub(super) fn row_at(&self, z: u64, y: u64) -> Option { - let image = z.checked_mul(self.bytes_per_image)?; - let row = y.checked_mul(self.bytes_per_row)?; - self.offset.checked_add(image)?.checked_add(row) - } - - /// The end of the last row of a region of shape `s`, one past its last byte; `None` past - /// `u64::MAX`. Rows lie in order, so every row of the region ends there or before. - fn end(&self, s: &Shape) -> Option { - let last = self.row_at(s.images.saturating_sub(1), s.rows.saturating_sub(1))?; - last.checked_add(s.row_bytes) - } -} - -/// Metal's checks of a buffer layout for a region of `size` in units of `unit`, in a buffer of -/// `buffer_length` bytes; the bytes it spans from its offset. A layout of more than one image -/// reaches it within Metal's `bytesPerImage` rule ([`plan_buffer_copy`] places one off it first; -/// a texture over a buffer, and a depth or stencil format, has one image). -pub(super) fn check_layout( - layout: &BufferLayout, - size: [u32; 3], - unit: &CopyUnit, - buffer_length: u64, -) -> Result { - let s = shape(size, unit); - let bytes = u64::from(unit.bytes); - if !layout.offset.is_multiple_of(bytes) { - return Err(CopyProblem::Offset); - } - if !layout.bytes_per_row.is_multiple_of(bytes) - || (s.rows > 1 && layout.bytes_per_row < s.row_bytes) - { - return Err(CopyProblem::BytesPerRow); - } - if s.row_bytes == 0 || s.rows == 0 || s.images == 0 { - return Ok(0); - } - // A layout whose last row ends past `u64::MAX` runs past every buffer. - match layout.end(&s) { - Some(end) if end <= buffer_length => Ok(end - layout.offset), - _ => Err(CopyProblem::BufferRange), - } -} - -/// One Vulkan buffer-image copy region (`VkBufferImageCopy`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct BufferImageRegion { - pub(super) buffer_offset: u64, - /// Texels per row, or 0 for tightly packed rows. - pub(super) row_length: u32, - /// Texel rows per image, or 0 for tightly packed images. - pub(super) image_height: u32, - pub(super) image: ImageRegion, -} - -/// One buffer-to-buffer copy (`VkBufferCopy`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct BufferRange { - pub(super) src: u64, - pub(super) dst: u64, - pub(super) size: u64, -} - -/// A copy through a tightly packed staging buffer: `rows` move each row (or run of contiguous -/// rows) between the Metal buffer's layout and the staging buffer's, whose `length` bytes the -/// staging buffer holds. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct Staging { - pub(super) length: u64, - /// From the Metal buffer to staging for a copy into the texture; the other way for a copy - /// out of it (`src` is then the staging offset). - pub(super) rows: Vec, -} - -/// How a buffer-texture copy runs: buffer-image regions on the Metal buffer itself, or on a -/// staging buffer filled from it (or emptied into it). The regions' and rows' offsets in the -/// Metal buffer are its `VkBuffer`'s (from the plan's `base`). -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct BufferCopyPlan { - pub(super) regions: Vec, - pub(super) staging: Option, - /// The Metal buffer's bytes the copy reads or writes, padding between rows included. - pub(super) span: Range, -} - -/// Whether `layout` is off Metal's rules for a region of shape `s` in `unit`s: an offset or a -/// `bytesPerRow` off the copy unit, rows (of more than one) that overlap, or, of more than one -/// image, a `bytesPerImage` off the copy unit or below the region's rows. -fn off_rules(layout: &BufferLayout, s: &Shape, unit: &CopyUnit) -> bool { - let bytes = u64::from(unit.bytes); - // Images below the region's rows: an image of rows past `u64::MAX` is above any. - let below_rows = - (layout.bytes_per_row.checked_mul(s.rows)).is_none_or(|rows| layout.bytes_per_image < rows); - let images_off = s.images > 1 && (!layout.bytes_per_image.is_multiple_of(bytes) || below_rows); - !layout.offset.is_multiple_of(bytes) - || !layout.bytes_per_row.is_multiple_of(bytes) - || (s.rows > 1 && layout.bytes_per_row < s.row_bytes) - || images_off -} - -/// The buffer offset of each row of a region of shape `s` (image by image, row by row) where -/// plain Metal's blit reads it (`into_texture`) or writes it, for a layout off Metal's rules -/// (every offset from 0 to 7 and 4 to 12, every `bytesPerRow` from 0 to 38, -/// units of 1 to 16 bytes, `BC1_RGBA`, `Depth32Float`, and images of a 3D texture). -/// -/// Each row is at `offset + z * bytesPerImage + y * bytesPerRow` rounded down to the copy unit or -/// to 4 bytes, whichever is smaller, images of a 3D texture at any `bytesPerImage` too (0, 4, 12 -/// and 18 under a 16-byte image). A copy into a texture of one image of -/// more than one row whose `bytesPerRow` rounded down to the copy unit is a multiple of 16 takes -/// Metal's aligned path from offset 0: its rows at that rounded pitch, one below a row too, each -/// row read whole from there so that the rows overlap in the buffer (an Apple M3 Max under macOS -/// 27.0.1, `probes/short_row_blits.m`: every row of a 32 x 8 texture, 64 x 8 for `R8Unorm`, at -/// every pitch of the texel from 16 bytes below the row and at half the row plus a texel, in -/// eight formats of 1 to 16 bytes a texel, `YCBCR8_422_1P` and `YCBCR10_444_1P` among them, -/// `Private` and `Shared`). -/// -/// A copy out of a texture at a pitch below a row writes each row at its own offset, the rows -/// overlapping in the buffer: Metal writes them in no one order, and the runtime writes them in -/// turn, the later row's bytes over the earlier's (`plan_placed_copy`), one of Metal's own answers -/// (the same probe: copies out at half the row and below, rows `y x bytesPerRow` apart and nothing -/// past their span written, the later rows' bytes standing in about a fifth of its shapes). -/// -/// Refused (`BytesPerRow`): on the aligned path, a pitch of 0 (Metal reads garbage) and an offset -/// of 16 or more (not measured). Refused (`BufferRange`): a row past `u64::MAX`, which lies past -/// every buffer. -fn placed_rows( - layout: &BufferLayout, - s: &Shape, - unit: &CopyUnit, - into_texture: bool, -) -> Result, CopyProblem> { - let bytes = u64::from(unit.bytes); - let word = bytes.min(4); - let bpr = layout.bytes_per_row; - let pitch = bpr - bpr % bytes; - let aligned = into_texture && s.images == 1 && s.rows > 1 && pitch.is_multiple_of(16); - if aligned && layout.offset.is_multiple_of(16) { - if layout.offset != 0 || pitch == 0 { - return Err(CopyProblem::BytesPerRow); - } - return (0..s.rows) - .map(|y| y.checked_mul(pitch).ok_or(CopyProblem::BufferRange)) - .collect(); - } - let mut rows = Vec::with_capacity((s.images * s.rows) as usize); - for z in 0..s.images { - for y in 0..s.rows { - let at = layout.row_at(z, y).ok_or(CopyProblem::BufferRange)?; - rows.push(at - at % word); - } - } - Ok(rows) -} - -/// Whether a layout off Metal's rules copies `pf` where plain Metal places its rows -/// ([`placed_rows`]): a colour format or `Depth32Float` (other depth and stencil formats are not -/// measured, and keep Metal's validation's refusal, but for [`rows_below_row`]). -fn placed(pf: PixelFormat) -> bool { - !is_depth_stencil(pf) || pf == PixelFormat::Depth32Float -} - -/// Whether `layout` is off Metal's rules for a region of shape `s` in `unit`s by a `bytesPerRow` -/// below the region's row alone: rows of more than one, of one image, from an offset on the copy -/// unit, at a nonzero pitch on the copy unit below the row. Plain Metal's blit copies such a -/// layout of each kind of single-sample texture measured, each row whole at -/// `offset + y x bytesPerRow`: read so into the texture, and written so out of it, in no one -/// order where the rows overlap (an Apple M3 Max under macOS 27.0.1, `probes/short_row_kinds.m`: -/// `Depth16Unorm`, `Stencil8`, both aspects of `Depth32Float_Stencil8`, an `RGBA8Unorm` texture -/// over a buffer and `RGB10A8_2P_XR10`, 32 x 8, from offset 0 at half the row, half plus a unit -/// and the row less 16, both ways, twice; the colour formats' rows lie so from other offsets on -/// the unit too, [`placed_rows`]). So a depth or stencil format copies such a layout where -/// [`placed_rows`] places it, and a texture over a buffer as [`plan_rows_copy`] does. -pub(super) fn rows_below_row(layout: &BufferLayout, s: &Shape, unit: &CopyUnit) -> bool { - let bytes = u64::from(unit.bytes); - let bpr = layout.bytes_per_row; - s.rows > 1 - && s.images == 1 - && bpr > 0 - && bpr < s.row_bytes - && bpr.is_multiple_of(bytes) - && layout.offset.is_multiple_of(bytes) -} - -/// The rows of a region of shape `s` laid out as `layout`, image by image and row by row, each -/// `s.row_bytes` long; `None` where one ends past `u64::MAX`. -fn layout_rows(layout: &BufferLayout, s: &Shape) -> Option>> { - let mut rows = Vec::with_capacity((s.images * s.rows) as usize); - for z in 0..s.images { - for y in 0..s.rows { - let start = layout.row_at(z, y)?; - rows.push(start..start.checked_add(s.row_bytes)?); - } - } - Some(rows) -} - -/// Whether Vulkan takes `offset` as a buffer-image copy's buffer offset for `unit` (a multiple of -/// the texel block, and of 4 for a depth/stencil aspect). -fn vulkan_offset(offset: u64, unit: &CopyUnit) -> bool { - let align = if unit.aspect == ImageAspectFlags::COLOR { - u64::from(unit.bytes) - } else { - 4 - }; - offset.is_multiple_of(align) -} - -/// The plan of a copy between a buffer of `buffer_length` bytes laid out as `layout` and -/// `region` of a texture presenting `record`, in units of `unit` (`into_texture` from the buffer -/// into the texture; either way the plan's staging rows run buffer to staging, and the caller -/// reverses them for a copy out of the texture). The buffer's bytes start `base` bytes into its -/// `VkBuffer` (`Buffer::at`): Metal's rules hold of the layout, Vulkan's of the `VkBuffer`'s -/// offsets, so a layout Metal takes is staged where its offset there misses the texel block. A -/// layout off Metal's rules is staged where plain Metal places its rows ([`placed_rows`]), for a -/// colour format or `Depth32Float` (other depth and stencil formats are not measured, and keep -/// Metal's validation's refusal). -pub(super) fn plan_buffer_copy( - record: &ViewRecord, - region: &TextureRegion, - unit: &CopyUnit, - layout: &BufferLayout, - buffer_length: u64, - base: u64, - into_texture: bool, -) -> Result { - let image = check_region(record, region, unit)?; - let s = shape(region.size, unit); - let placed = placed(record.pixel_format) || rows_below_row(layout, &s, unit); - if placed && off_rules(layout, &s, unit) { - return plan_placed_copy(layout, &s, unit, image, buffer_length, base, into_texture); - } - // Every row ends within the buffer (`check_layout`), so no offset below passes `u64::MAX`. - let span = check_layout(layout, region.size, unit, buffer_length)?; - let span = layout.offset..layout.offset + span; - let start = base + layout.offset; - if s.row_bytes == 0 || s.rows == 0 || s.images == 0 { - return Ok(BufferCopyPlan { - regions: Vec::new(), - staging: None, - span, - }); - } - let texels_per_row = |bytes_per_row: u64| { - let texels = (bytes_per_row / u64::from(unit.bytes)).checked_mul(u64::from(unit.extent[0])); - texels.and_then(|texels| u32::try_from(texels).ok()) - }; - // Rows: the pitch in texels, or tight when there is one row. - let row_length = if s.rows == 1 { - Some(0) - } else { - texels_per_row(layout.bytes_per_row) - }; - let images_fit = s.images == 1 - || (layout.bytes_per_row != 0 - && layout.bytes_per_image.is_multiple_of(layout.bytes_per_row)); - let image_height = if s.images == 1 { - Some(0) - } else if images_fit { - let rows = layout.bytes_per_image / layout.bytes_per_row; - (rows.checked_mul(u64::from(unit.extent[1]))).and_then(|rows| u32::try_from(rows).ok()) - } else { - None - }; - if let (Some(row_length), true) = (row_length, vulkan_offset(start, unit)) { - if let Some(image_height) = image_height { - return Ok(BufferCopyPlan { - regions: vec![BufferImageRegion { - buffer_offset: start, - row_length, - image_height, - image, - }], - staging: None, - span, - }); - } - // One region per image, where every image's offset is one Vulkan takes. - if vulkan_offset(layout.bytes_per_image, unit) { - let regions = (0..s.images) - .map(|z| BufferImageRegion { - buffer_offset: start + z * layout.bytes_per_image, - row_length, - image_height: 0, - image: ImageRegion { - origin: [image.origin[0], image.origin[1], image.origin[2] + z as u32], - size: [image.size[0], image.size[1], 1], - ..image - }, - }) - .collect(); - return Ok(BufferCopyPlan { - regions, - staging: None, - span, - }); - } - } - // A tightly packed staging layout: rows of `row_bytes`, images of `rows` rows. - let mut rows = Vec::new(); - for z in 0..s.images { - let src_image = start + z * layout.bytes_per_image; - let dst_image = z * s.rows * s.row_bytes; - if layout.bytes_per_row == s.row_bytes || s.rows == 1 { - rows.push(BufferRange { - src: src_image, - dst: dst_image, - size: s.rows * s.row_bytes, - }); - } else { - rows.extend((0..s.rows).map(|y| BufferRange { - src: src_image + y * layout.bytes_per_row, - dst: dst_image + y * s.row_bytes, - size: s.row_bytes, - })); - } - } - Ok(BufferCopyPlan { - regions: vec![BufferImageRegion { - buffer_offset: 0, - row_length: 0, - image_height: 0, - image, - }], - staging: Some(Staging { - length: s.images * s.rows * s.row_bytes, - rows, - }), - span, - }) -} - -/// A copy of a layout off Metal's rules (shape `s`, of the checked `image`) through a tightly -/// packed staging layout, each row where plain Metal places it ([`placed_rows`]); the rows stay -/// in the buffer. Out of the texture, rows that overlap are written in turn: images closer than -/// the region's rows as plain Metal writes them (in order in every run of 3D textures up to -/// 256x64x4), and rows closer than a row, which Metal writes in no one order, as one of its -/// answers (the later row's bytes standing). Each row's bytes that a later row writes are left -/// out of it ([`later_rows_win`]), so the regions of the one copy into the buffer are disjoint. -fn plan_placed_copy( - layout: &BufferLayout, - s: &Shape, - unit: &CopyUnit, - image: ImageRegion, - buffer_length: u64, - base: u64, - into_texture: bool, -) -> Result { - let starts = placed_rows(layout, s, unit, into_texture)?; - let (Some(&first), Some(&last)) = (starts.iter().min(), starts.iter().max()) else { - return Ok(BufferCopyPlan { - regions: Vec::new(), - staging: None, - span: layout.offset..layout.offset, - }); - }; - let end = (last.checked_add(s.row_bytes)) - .filter(|&end| end <= buffer_length) - .ok_or(CopyProblem::BufferRange)?; - let rows: Vec = starts - .iter() - .enumerate() - .map(|(i, &start)| BufferRange { - src: base + start, - dst: i as u64 * s.row_bytes, - size: s.row_bytes, - }) - .collect(); - let rows = if into_texture { - rows - } else { - later_rows_win(&rows) - }; - Ok(BufferCopyPlan { - regions: vec![BufferImageRegion { - buffer_offset: 0, - row_length: 0, - image_height: 0, - image, - }], - staging: Some(Staging { - length: s.images * s.rows * s.row_bytes, - rows, - }), - span: first..end, - }) -} - -/// `rows` (from the Metal buffer at `src`, in the order Metal writes them) without the bytes a -/// later row writes: each row's pieces that no later row covers, so the regions of one -/// `vkCmdCopyBuffer` into the buffer are disjoint and the buffer ends as Metal's in-order writes -/// leave it. A row wholly covered by later ones copies nothing. -pub(super) fn later_rows_win(rows: &[BufferRange]) -> Vec { - // The buffer's bytes later rows write: disjoint ranges, keyed by start. - let mut covered: BTreeMap = BTreeMap::new(); - let mut kept = Vec::with_capacity(rows.len()); - for row in rows.iter().rev() { - let (start, end) = (row.src, row.src + row.size); - // The covered ranges that meet or touch the row, in order. - let before = covered - .range(..=start) - .next_back() - .filter(|&(_, &e)| e >= start) - .map(|(&s, &e)| (s, e)); - let within: Vec<(u64, u64)> = covered - .range(start + 1..end) - .map(|(&s, &e)| (s, e)) - .collect(); - let mut at = start; - for &(s, e) in before.iter().chain(&within) { - if s > at { - kept.push(BufferRange { - src: at, - dst: row.dst + (at - start), - size: s - at, - }); - } - at = at.max(e); - } - if at < end { - kept.push(BufferRange { - src: at, - dst: row.dst + (at - start), - size: end - at, - }); - } - let merged_start = before.map_or(start, |(s, _)| s); - let merged_end = before - .iter() - .chain(&within) - .map(|&(_, e)| e) - .fold(end, u64::max); - for (s, _) in before.iter().chain(&within) { - covered.remove(s); - } - covered.insert(merged_start, merged_end); - } - kept.reverse(); - kept -} - -/// One Vulkan image-image copy region (`VkImageCopy`). The two regions cover the same blocks; a -/// compressed pair differs in size where one ends at its level's edge inside a block and the -/// other does not (a whole block of a 4 x 2 level and of a larger one). No one extent states -/// such a pair: Vulkan bounds each region by its level's texels and asks each for whole blocks -/// except at its image's edge, so 4 x 2 is a part block inside the larger level and 4 x 4 passes -/// the smaller (`blit_texture.rs` copies such a pair through a buffer). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct ImageCopyRegion { - pub(super) src: ImageRegion, - pub(super) dst: ImageRegion, -} - -/// Metal's copy unit of `pf` between textures, as bytes and a block extent: its texel block; of a -/// depth-only or stencil-only format, or a stencil view, its one aspect (`Depth16Unorm` 2 bytes, -/// `Depth32Float` 4, `Stencil8` and `X32Stencil8` 1). `None` for a combined depth/stencil format, -/// which copies only into its own format. -fn texture_unit(pf: PixelFormat) -> Option<(u32, [u32; 2])> { - use PixelFormat as P; - match pf { - P::Depth16Unorm => Some((2, [1, 1])), - P::Depth32Float => Some((4, [1, 1])), - P::Stencil8 | P::X32Stencil8 => Some((1, [1, 1])), - _ if is_depth_stencil(pf) => None, - _ => block_bytes(pf).map(|bytes| (bytes, block_extent(pf).unwrap_or([1, 1]))), - } -} - -/// Whether Metal copies between textures of `a` and `b` (macOS 26.7's rule): the same format, or -/// two formats of one copy unit, whose bytes it copies, a depth or stencil format's among them -/// (probes), or a compressed format and an uncompressed one whose texel is the bytes of its block -/// (each block into one texel and back, [`source_region`]); formats of units of different bytes -/// are refused. -/// -/// The runtime's gaps: a PVRTC format with an uncompressed one, whose blocks plain Metal moves in -/// an order of its own (our probe on an Apple M3 Max under macOS 27.0.1: neither the rows nor the -/// CPU's Z order), and two compressed formats of one block's bytes and different extents (ASTC -/// 6x5 and BC7), not measured. -fn check_formats(a: PixelFormat, b: PixelFormat) -> Result<(), CopyRefusal> { - // Between two `YCBCR8_420_2P` textures Metal copies both of the surfaces' planes, where the - // runtime's copy moves the luma bytes its texels are: the runtime's - // gap, as is a copy between one and another format, which is not measured. - if ycbcr(a) || ycbcr(b) { - return Err(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(a), - )); - } - if a == b { - return Ok(()); - } - let not_implemented = - || CopyRefusal::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(a)); - match (texture_unit(a), texture_unit(b)) { - (Some(x), Some(y)) if x == y => {} - (Some((x, from)), Some((y, to))) if x == y => { - let texel = |extent: [u32; 2]| extent == [1, 1]; - if texel(from) == texel(to) || is_pvrtc(a) || is_pvrtc(b) { - return Err(not_implemented()); - } - } - _ => return Err(CopyProblem::Format.into()), - } - // Into a 4:2:2 texture from another format of its unit plain Metal writes `0xff` over part - // of each row (`RG8Unorm` into `GBGR422`), no copy of the bytes: the - // runtime's gap. Out of one, and between the two orders, it copies them. - if is_four_two_two(b) && !is_four_two_two(a) { - return Err(CopyRefusal::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))); - } - Ok(()) -} - -/// The two textures of a texture-to-texture copy: what each presents and its image, `None` for -/// a texture buffer, which has none (its format is a colour format: its copy unit is its -/// texel). -#[derive(Clone, Copy, Debug)] -pub(super) struct CopyPair<'a> { - pub(super) src: &'a ViewRecord, - pub(super) src_image: Option<&'a ImagePlan>, - pub(super) dst: &'a ViewRecord, - pub(super) dst_image: Option<&'a ImagePlan>, -} - -impl CopyPair<'_> { - /// Metal's checks of the pair as a whole, and each texture's copy unit: one size, in each - /// texture's own aspect (a depth or stencil format's, else colour). - fn check(&self) -> Result<(CopyUnit, CopyUnit), CopyRefusal> { - if self.src.samples != self.dst.samples { - return Err(CopyProblem::SampleCount.into()); - } - // A two-plane extended-range texture copies both words of its texels into another of the - // pair, which plain Metal copies into (its validation stops the other format); a copy - // between one and a texture of another format is not measured (`two_planes.rs`). - let (src, dst) = (self.src.pixel_format, self.dst.pixel_format); - match (two_planes::holds_planes(src), two_planes::holds_planes(dst)) { - (true, true) => return Ok((two_planes::TEXEL_UNIT, two_planes::TEXEL_UNIT)), - (true, false) => return Err(CopyRefusal::Unsupported(two_planes::unmeasured(src))), - (false, true) => return Err(CopyRefusal::Unsupported(two_planes::unmeasured(dst))), - (false, false) => {} - } - check_formats(src, dst)?; - Ok(( - pair_unit(self.src, self.src_image)?, - pair_unit(self.dst, self.dst_image)?, - )) - } -} - -/// The copy unit of one texture of a texture-to-texture copy: a combined depth/stencil format's -/// both aspects (it copies only into its own format), else its unit as a buffer copy without an -/// option takes it. -fn pair_unit(record: &ViewRecord, image: Option<&ImagePlan>) -> Result { - let Some(image) = image else { - return colour_unit(record.pixel_format); - }; - let both = ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL; - if image.mapping.aspects.contains(both) && record.pixel_format == image.pixel_format { - let block = image - .mapping - .format - .block() - .ok_or(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(record.pixel_format), - ))?; - return Ok(CopyUnit { - bytes: block.size, - extent: [1, 1], - aspect: both, - }); - } - copy_unit(record.pixel_format, &image.mapping, BlitOption::None) -} - -/// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:...`: `region` of -/// the source to the same size at `dst_origin` of `dst_level` and `dst_slice` of the destination, -/// each side as the blocks it starts in ([`check_region`]). Where those end at one side's level -/// edge inside a block and not at the other's, the sides differ in size and cover the same blocks, -/// which plain Metal copies whole (an Apple M3 Max under macOS 26.7, a probe: a whole block of a -/// 4 x 2 level into one of an 8 x 8 level and back, which its validation takes, and 4 x 2 of -/// either, which it stops). Between a compressed and an uncompressed format the region is in the -/// destination's texels ([`source_region`]). -pub(super) fn plan_region_copy( - pair: &CopyPair<'_>, - region: &TextureRegion, - dst_level: u32, - dst_slice: u32, - dst_origin: [u32; 3], -) -> Result, CopyRefusal> { - let (src_unit, dst_unit) = pair.check()?; - let source = source_region(region, &src_unit, &dst_unit)?; - let src = check_region(pair.src, &source, &src_unit)?; - let dst_region = TextureRegion { - level: dst_level, - slice: dst_slice, - origin: dst_origin, - size: region.size, - }; - let dst = check_region(pair.dst, &dst_region, &dst_unit)?; - if region.size.contains(&0) { - return Ok(Vec::new()); - } - Ok(vec![ImageCopyRegion { src, dst }]) -} - -/// The source's region of a region copy of `region` between textures of units `src` and `dst`: -/// `region` itself between units of one extent. Between a compressed format and an uncompressed -/// one (`check_formats`) every coordinate of the copy is in the destination's texels, the source -/// addressed as if it held the destination's format (our probe on an Apple M3 Max under macOS -/// 27.0.1: BC1 with `RG32Uint` and `RGBA16Uint`, BC7, `EAC_RGBA8` and ASTC 6x5 with -/// `RGBA32Uint`, `ETC2_RGB8` with `RG32Uint`, both ways): out of a compressed texture the origin -/// and size count its blocks (an origin of 4 is the fifth block), into one they count the -/// source's texels as the destination's, the origin rounded down to a block's texel and the size -/// up to whole blocks, each on its own (an origin of 1 and a size of 4 copy texel 0 alone). -/// Refused (`Region`) where the source's texels overflow. -fn source_region( - region: &TextureRegion, - src: &CopyUnit, - dst: &CopyUnit, -) -> Result { - let mut out = *region; - for axis in 0..2 { - let (from, to) = (src.extent[axis], dst.extent[axis]); - if from == to { - continue; - } - let (origin, size) = (region.origin[axis], region.size[axis]); - (out.origin[axis], out.size[axis]) = match to { - 1 => ( - origin.checked_mul(from).ok_or(CopyProblem::Region)?, - size.checked_mul(from).ok_or(CopyProblem::Region)?, - ), - _ => (origin / to, size.div_ceil(to)), - }; - } - Ok(out) -} - -/// `copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel: -/// sliceCount:levelCount:`, and `copyFromTexture:toTexture:` ([`plan_whole_copy`]: every level -/// and slice two textures share). Each level pair copies the copy units both levels hold, from -/// their origins. Between a compressed and an uncompressed format (`check_formats`) the runtime's -/// gap (`NotImplemented(Format)`): which level's blocks Metal copies into which level's texels is -/// not measured. -pub(super) fn plan_levels_copy( - pair: &CopyPair<'_>, - src_slice: u32, - src_level: u32, - dst_slice: u32, - dst_level: u32, - slices: u32, - levels: u32, -) -> Result, CopyRefusal> { - let (src_unit, dst_unit) = pair.check()?; - if src_unit.extent != dst_unit.extent { - return Err(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pair.src.pixel_format), - )); - } - let (src, dst) = (pair.src, pair.dst); - let in_range = |start: u32, count: u32, limit: u32| { - start.checked_add(count).is_some_and(|end| end <= limit) - }; - if !in_range(src_level, levels, src.level_count) - || !in_range(dst_level, levels, dst.level_count) - || !in_range(src_slice, slices, src.layer_count) - || !in_range(dst_slice, slices, dst.layer_count) - { - return Err(CopyProblem::Region.into()); - } - let mut out = Vec::with_capacity(levels as usize); - for i in 0..levels { - let (from, to) = ( - level_extent(src, src_level + i), - level_extent(dst, dst_level + i), - ); - // Levels of different sizes copy the copy units both levels hold, from their origins, - // whole: the lesser count of units on each axis, and the rest of the larger level kept, - // as plain Metal copies them. Of a compressed format that is the lesser count of blocks, - // the block that passes the smaller level's edge included (an Apple M3 Max under macOS - // 27.0.1, our probe: BC1, BC3, BC4, BC7, `EAC_RGBA8`, `ETC2_RGB8` and ASTC 6 x 5, each - // into a level of fewer blocks, of more, and of fewer on one axis and more on the other, - // and out of a level that ends inside a block, every one block for block). Vulkan bounds - // a copy by the level's texels, so where the last unit passes the smaller level's edge - // the two sides differ in size and cover the same units, which `blit_texture.rs` copies - // through a buffer. - let block = [src_unit.extent[0], src_unit.extent[1], 1]; - let units = [0, 1, 2].map(|axis| { - from[axis] - .div_ceil(block[axis]) - .min(to[axis].div_ceil(block[axis])) - }); - let whole = |extent: [u32; 3]| { - [0, 1, 2].map(|axis| units[axis].saturating_mul(block[axis]).min(extent[axis])) - }; - let (src_size, dst_size) = (whole(from), whole(to)); - if slices == 0 { - continue; - } - let at = |record: &ViewRecord, unit: &CopyUnit, level: u32, slice: u32, size: [u32; 3]| { - ImageRegion { - aspect: unit.aspect, - level: record.base_level + level, - layer: record.base_layer + slice, - layers: slices, - origin: [0, 0, 0], - size, - } - }; - out.push(ImageCopyRegion { - src: at(src, &src_unit, src_level + i, src_slice, src_size), - dst: at(dst, &dst_unit, dst_level + i, dst_slice, dst_size), - }); - } - Ok(out) -} - -/// `copyFromTexture:toTexture:`: the levels the two textures share, paired by extent -/// ([`aligned_levels`]), and the slices they share, as plain Metal copies them (an M4 under macOS -/// 27.0.1): an 8x8 texture of 4 levels into a 4x4 one of 3 copies its levels 1 to 3, a 2D texture -/// into a 2D array its one slice. The paired levels may lie past the textures' own, since Metal -/// pairs them by the textures' extents shifted and not by their level counts, and then each side -/// copies the levels it has from its paired one: none, where that side's paired level is the one -/// past its last (an Apple M3 Max under macOS 27.0.1, our probe `wh-bc1-16-to-8`, -/// `wh-plain-16-to-8` and `wh-bc1-16-to-32`: a 16 by 16 texture of one level into an 8 by 8 one -/// of one, and into a 32 by 32 one of one, each complete with no error and the destination's own -/// bytes kept). -/// -/// Refused (`Size`): two textures whose extents pair at no level, where plain Metal aborts, and a -/// paired level past the end of its texture's own levels, where plain Metal reads or writes a -/// level the texture does not hold. -pub(super) fn plan_whole_copy(pair: &CopyPair<'_>) -> Result, CopyRefusal> { - let (src, dst) = (pair.src, pair.dst); - let (src_level, dst_level) = aligned_levels(src, dst).ok_or(CopyProblem::Size)?; - if src_level > src.level_count || dst_level > dst.level_count { - return Err(CopyProblem::Size.into()); - } - let levels = (src.level_count - src_level).min(dst.level_count - dst_level); - let slices = src.layer_count.min(dst.layer_count); - plan_levels_copy(pair, 0, src_level, 0, dst_level, slices, levels) -} - -/// The first levels a whole copy pairs: both first levels where they are one extent, else the -/// source's level `k` and the destination's first, or the source's first and the destination's -/// level `k`, at the least `k` where every axis of the two extents is equal. Plain Metal pairs -/// them so (`sz_whole_8l4_to_4l3` pairs the source's level 1 with the destination's 0, -/// `sz_whole_4l3_to_8l4` the source's 0 with the destination's 1, `sz_whole_6l3_to_3l2` and -/// `sz_whole_5l3_to_2l2` its level 1 with 0), and aborts where the extents meet at no level -/// (`sz_whole_8_to_3`, `sz_whole_8x4_to_4x8`, `sz_whole_8x4_to_4x4`). `None` there, and where -/// both directions would pair (unmeasured). -/// -/// The shifts a pair may take are the extent's own, which the texture's level count does not -/// bound: Metal shifts the texture's width, height and depth and asks that one of the two shifts -/// be none (`MTLPickLargestMip`'s postcondition, which its abort names), so a 16 by 16 texture of -/// one level pairs its level 1 with an 8 by 8 destination's level 0 and copies no level at all -/// (our probe's `wh-bc1-16-to-8`). An extent is 1 on every axis by the 31st shift, so the search -/// ends there. -fn aligned_levels(src: &ViewRecord, dst: &ViewRecord) -> Option<(u32, u32)> { - if level_extent(src, 0) == level_extent(dst, 0) { - return Some((0, 0)); - } - let first = |of: &ViewRecord, to: [u32; 3]| (1..32).find(|&k| level_extent(of, k) == to); - match ( - first(src, level_extent(dst, 0)), - first(dst, level_extent(src, 0)), - ) { - (Some(k), None) => Some((k, 0)), - (None, Some(k)) => Some((0, k)), - _ => None, - } -} - -/// A copy of rows of bytes, each from `src`'s row to `dst`'s of the same index: a blit between a -/// buffer's bytes and a texture over a buffer, or between two textures over buffers, which runs on -/// the buffers' bytes at Metal's layout. Offsets are the buffers' own (from their first byte), and -/// rows contiguous in both are one. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct RowsCopy { - pub(super) rows: Vec, - /// The source's bytes from its first row's start to its last row's end. - pub(super) src_span: Range, - /// The destination's, likewise. - pub(super) dst_span: Range, -} - -impl RowsCopy { - /// Each row of `src` into the same row of `dst` (as many rows, each as long). Destination - /// rows overlap in two shapes alone, both a buffer's: rows whose images meet, at a - /// `bytesPerImage` below the region's rows, which `check_layout` takes as plain Metal does, - /// and rows at a `bytesPerRow` below the region's row ([`plan_rows_copy`]). There the later - /// row keeps the bytes they share, as plain Metal writes overlapping images in turn (an M4 - /// under macOS 27.0.1, the `ctb.race.*` cases) and as one of the orders it writes such rows - /// in ([`plan_placed_copy`] states the same rule for a layout off Metal's rules): an earlier - /// row copies only the bytes no later row writes ([`later_rows_win`]). No texture's own rows - /// overlap as the destination: a plane's shared - /// bytes, which have no one Metal order, are refused wherever they would be written - /// (`blit_texture.rs`), and a rotated texture's rows share no byte - /// (`buffer_texture::turned_plane`). A plane's rows do overlap as the source, where they are - /// read: each destination row takes the plane's bytes at its own GPU row, so a shared byte is - /// read once for each row that holds it, and such a row joins neither neighbour into one - /// range. - pub(super) fn new(src: &[Range], dst: &[Range]) -> RowsCopy { - debug_assert_eq!(src.len(), dst.len()); - // Each row as `later_rows_win` takes it: by the bytes it writes. - let mut written: Vec = src - .iter() - .zip(dst) - .map(|(s, d)| { - debug_assert_eq!(s.end - s.start, d.end - d.start); - BufferRange { - src: d.start, - dst: s.start, - size: d.end - d.start, - } - }) - .collect(); - if !dst.windows(2).all(|two| two[0].end <= two[1].start) { - written = later_rows_win(&written); - written.sort_by_key(|row| row.src); - } - let mut rows: Vec = Vec::with_capacity(written.len()); - for row in written { - let (s, d) = (row.dst..row.dst + row.size, row.src..row.src + row.size); - match rows.last_mut() { - Some(last) - if last.src + last.size == s.start && last.dst + last.size == d.start => - { - last.size += s.end - s.start; - } - _ => rows.push(BufferRange { - src: s.start, - dst: d.start, - size: s.end - s.start, - }), - } - } - let span = |r: &[Range]| { - let start = r.iter().map(|r| r.start).min().unwrap_or(0); - start..r.iter().map(|r| r.end).max().unwrap_or(start) - }; - RowsCopy { - rows, - src_span: span(src), - dst_span: span(dst), - } - } - - /// Whether a source row and a destination row share a byte, for a copy within one buffer: - /// Vulkan's copy forbids it, where Metal moves the bytes as a copy through a temporary does (a - /// Metal probe on the M3 Max and an M4). - pub(super) fn meets(&self) -> bool { - let mut src: Vec> = self.rows.iter().map(|r| r.src..r.src + r.size).collect(); - let mut dst: Vec> = self.rows.iter().map(|r| r.dst..r.dst + r.size).collect(); - src.sort_by_key(|r| r.start); - dst.sort_by_key(|r| r.start); - let (mut i, mut j) = (0, 0); - while i < src.len() && j < dst.len() { - if src[i].start < dst[j].end && dst[j].start < src[i].end { - return true; - } - if src[i].end <= dst[j].end { - i += 1; - } else { - j += 1; - } - } - false - } - - /// The bytes the rows hold. - pub(super) fn length(&self) -> u64 { - self.rows.iter().map(|r| r.size).sum() - } - - /// This copy cut where a side's bytes pass `src_cut` or `dst_cut` (a texture's whose texels - /// run past those it keeps in its buffer, whose bytes past them lie in its tail, - /// `buffer_texture.rs`): - /// up to four copies, each `(whether its source rows lie past the source's cut, whether its - /// destination rows lie past the destination's, the copy)`, every row in exactly one of - /// them, cut where it crosses either cut. A side with no cut lies before it whole. - pub(super) fn split( - &self, - src_cut: Option, - dst_cut: Option, - ) -> Vec<(bool, bool, RowsCopy)> { - let (src_cut, dst_cut) = (src_cut.unwrap_or(u64::MAX), dst_cut.unwrap_or(u64::MAX)); - let mut parts: Vec<(bool, bool, Vec)> = Vec::new(); - for row in &self.rows { - // The row's cuts, from its start, where either side's bytes pass their cut. - let mut cuts = vec![0, row.size]; - for (start, cut) in [(row.src, src_cut), (row.dst, dst_cut)] { - if start < cut && cut < start + row.size { - cuts.push(cut - start); - } - } - cuts.sort_unstable(); - cuts.dedup(); - for piece in cuts.windows(2) { - let part = BufferRange { - src: row.src + piece[0], - dst: row.dst + piece[0], - size: piece[1] - piece[0], - }; - let side = (part.src >= src_cut, part.dst >= dst_cut); - match parts.iter_mut().find(|(s, d, _)| (*s, *d) == side) { - Some((.., rows)) => rows.push(part), - None => parts.push((side.0, side.1, vec![part])), - } - } - } - parts - .into_iter() - .map(|(src_past, dst_past, rows)| { - let span = |at: fn(&BufferRange) -> u64| { - let start = rows.iter().map(at).min().unwrap_or(0); - let end = rows.iter().map(|r| at(r) + r.size).max().unwrap_or(start); - start..end - }; - let (src_span, dst_span) = (span(|r| r.src), span(|r| r.dst)); - let copy = RowsCopy { - rows, - src_span, - dst_span, - }; - (src_past, dst_past, copy) - }) - .collect() - } -} - -/// The rows of `region` (a checked region, in `unit`s of one texel or one block) of a texture -/// over a buffer whose texels lie at `texels` (Metal's layout): one range of the buffer's bytes -/// per row, slice by slice. A block-compressed texture's rows are rows of its blocks (a BC texture -/// over an IOSurface plane's rows, `linear_plan.rs`), the region's texels counted in blocks. -pub(super) fn texel_rows( - texels: &TexelsLayout, - unit: &CopyUnit, - region: &ImageRegion, -) -> Vec> { - let bytes = u64::from(unit.bytes); - let ([x, y], [across, down]) = in_units(unit, region); - let width = across * bytes; - let mut rows = Vec::with_capacity(region.layers as usize * down as usize); - for layer in region.layer..region.layer + region.layers { - for row in y..y + down { - let start = - texels.offset + u64::from(layer) * texels.slice_pitch + row * texels.row_pitch; - rows.push(start + x * bytes..start + x * bytes + width); - } - } - rows -} - -/// The origin and size of a checked `region`, across and down, in `unit`s: its texels, or its -/// blocks for a block-compressed unit (the region starts on a block, and its last block of a -/// row or column may cover its texels alone). -fn in_units(unit: &CopyUnit, region: &ImageRegion) -> ([u64; 2], [u64; 2]) { - let [w, h] = unit.extent.map(u64::from); - let origin = [region.origin[0], region.origin[1]].map(u64::from); - let size = [region.size[0], region.size[1]].map(u64::from); - ( - [origin[0] / w, origin[1] / h], - [size[0].div_ceil(w), size[1].div_ceil(h)], - ) -} - -/// The row copy of `copies` between two textures over buffers, each copy's source rows of -/// `from`'s texels and its destination rows of `to`'s, in `unit`s of one texel. Each side is its -/// texture's two layouts, `(gpu, cpu)`: where Metal's GPU finds its texels and where the CPU does -/// (`linear_plan::Placed`). -/// -/// `Err(RuntimeGap::OverlappingSurfaceRows)` where either side's GPU rows share bytes (an -/// IOSurface plane's at a pitch off 16 or wider than its pitch, [`plane_rows_share_bytes`]). The -/// shared bytes take -/// whichever of the two rows Metal's command wrote last, an order that follows the command, the -/// GPU pitch and the row count and that one shape of `copyFromTexture:toTexture:` does not settle -/// from run to run (`linear_plan.rs`'s **Rows that overlap**), so no order a row copy writes them -/// in is Metal's. A source plane alone would be read, not written, as a copy out of a plane into a -/// buffer is (`blit_texture::copy_from_texture_to_buffer`), and so has no such order to miss; what -/// Metal reads out of one between two textures over buffers is unmeasured, and the source stays -/// refused with the destination until it is. -pub(super) fn plan_texels_rows_copy( - from: (&TexelsLayout, &TexelsLayout), - to: (&TexelsLayout, &TexelsLayout), - unit: &CopyUnit, - copies: &[ImageCopyRegion], -) -> Result { - for (gpu, _) in [from, to] { - if plane_rows_share_bytes(gpu) { - return Err(RuntimeGap::OverlappingSurfaceRows); - } - } - let (mut src, mut dst) = (Vec::new(), Vec::new()); - for copy in copies { - src.extend(texel_rows(from.0, unit, ©.src)); - dst.extend(texel_rows(to.0, unit, ©.dst)); - } - Ok(RowsCopy::new(&src, &dst)) -} - -/// The layout of slice `layer` (of the image's) of `region` of a texture over a buffer at -/// `texels`, as a buffer's side of a copy with a texture: its first texel's (or block's) offset, -/// and the texels' row pitch (of a row of blocks, a block-compressed texture's). -pub(super) fn texel_layout( - texels: &TexelsLayout, - unit: &CopyUnit, - region: &ImageRegion, - layer: u32, -) -> BufferLayout { - let ([x, y], _) = in_units(unit, region); - BufferLayout { - offset: texels.offset - + u64::from(layer) * texels.slice_pitch - + y * texels.row_pitch - + x * u64::from(unit.bytes), - bytes_per_row: texels.row_pitch, - bytes_per_image: 0, - } -} - -/// A copy between a buffer of `buffer_length` bytes laid out as `layout` and `region` of a -/// texture over a buffer presenting `record`, whose texels lie at `texels`, in `unit`s of one -/// texel: Metal's checks of both sides (as [`plan_buffer_copy`] makes them), then the rows, from -/// the buffer to the texture (the caller swaps them for a copy out of the texture). A -/// `bytesPerRow` below the row alone ([`rows_below_row`]) is taken as plain Metal takes it, each -/// row at `y x bytesPerRow`: rows that overlap as the source are each read whole, and as the -/// destination are written in turn, the later row's bytes standing ([`RowsCopy::new`]), one of -/// the orders plain Metal's blit leaves. -pub(super) fn plan_rows_copy( - record: &ViewRecord, - region: &TextureRegion, - unit: &CopyUnit, - layout: &BufferLayout, - buffer_length: u64, - texels: &TexelsLayout, -) -> Result<(Vec>, Vec>), CopyProblem> { - let image = check_region(record, region, unit)?; - let s = shape(region.size, unit); - match rows_below_row(layout, &s, unit) { - // The last row ends furthest: rows lie in order. - true => match layout.end(&s) { - Some(end) if end <= buffer_length => {} - _ => return Err(CopyProblem::BufferRange), - }, - false => { - check_layout(layout, region.size, unit, buffer_length)?; - } - } - Ok(( - layout_rows(layout, &s).ok_or(CopyProblem::BufferRange)?, - texel_rows(texels, unit, &image), - )) -} - -/// The position, in blocks from the layout's offset, at which plain Metal lays block (`x`, `y`) -/// of a region `blocks` wide and high out at a `bytesPerRow` of 0 (an M4 under -/// macOS 27.0.1; the reims-vgpu consumer's report of a whole 16 x 16 level on an M3 Max under -/// macOS 26.7): the region's own Morton order, counted from its corner, the x bit lowest. Each axis -/// takes as many bits as its block count needs, and the larger axis's extra bits go on top, so a -/// count that is not a power of two leaves positions no block takes. -pub(super) fn block_order_position(x: u64, y: u64, blocks: [u64; 2]) -> u64 { - let bits = |n: u64| u64::BITS - n.saturating_sub(1).leading_zeros(); - let (nx, ny) = (bits(blocks[0]), bits(blocks[1])); - let (mut position, mut bit) = (0, 0); - for i in 0..nx.max(ny) { - if i < nx { - position |= ((x >> i) & 1) << bit; - bit += 1; - } - if i < ny { - position |= ((y >> i) & 1) << bit; - bit += 1; - } - } - position -} - -/// The plan of a copy between a buffer of `buffer_length` bytes laid out as `layout` (a -/// `bytesPerRow` of 0) and `region` of a PVRTC texture presenting `record`, in units of `unit`, -/// with the blocks in plain Metal's block order ([`block_order_position`]; `base` as -/// [`plan_buffer_copy`] takes it). Either way the plan's staging rows run buffer to staging, and -/// the caller reverses them for a copy out of the texture. Each 2 x 2 blocks the order lays out in turn is one -/// region whose rows are two blocks long, a region one block wide or high is one region, and each -/// other block is a region of its own; a position no block takes is neither read nor written. -/// Where the offset in the `VkBuffer` misses the block the copy runs through staging, which moves -/// only the positions the blocks take. -/// -/// A region off its blocks lays out the blocks [`check_region`] rounds it to (its origin rounded -/// down to its block and its size up to whole blocks, each on its own), in their own Morton -/// order, as plain Metal's copy does (its validation stops it). -/// -/// Refused as Metal's validation refuses it: a region past the level and an offset off the block -/// (`CopyProblem`), and a layout past the buffer (`BufferRange`). A PVRTC texture has no 3D type -/// (`texture_descriptor`), so a region within its level is one image. -pub(super) fn plan_block_order_copy( - record: &ViewRecord, - region: &TextureRegion, - unit: &CopyUnit, - layout: &BufferLayout, - buffer_length: u64, - base: u64, -) -> Result { - let image = check_region(record, region, unit)?; - let bytes = u64::from(unit.bytes); - if !layout.offset.is_multiple_of(bytes) { - return Err(CopyProblem::Offset); - } - let s = shape(region.size, unit); - let blocks = [s.row_bytes / bytes, s.rows]; - let [bw, bh] = unit.extent.map(u64::from); - // A region of blocks `[x, y]` of the grid, `[w, h]` blocks large, at `position`. - let part = |[x, y]: [u64; 2], [w, h]: [u64; 2], position: u64| { - let texels = |at: u64, n: u64, axis: usize, block: u64| { - let start = at * block; - let size = (n * block).min(u64::from(image.size[axis]) - start); - (image.origin[axis] + start as u32, size as u32) - }; - let ((ox, sx), (oy, sy)) = (texels(x, w, 0, bw), texels(y, h, 1, bh)); - let row_length = if h > 1 && w > 1 { (w * bw) as u32 } else { 0 }; - let image_height = if h > 1 && w > 1 { (h * bh) as u32 } else { 0 }; - ( - position, - row_length, - image_height, - ImageRegion { - origin: [ox, oy, image.origin[2]], - size: [sx, sy, 1], - ..image - }, - ) - }; - let mut parts = Vec::new(); - if blocks[0] == 1 || blocks[1] == 1 { - // One axis takes no bit: the order is the region's rows, tightly packed. - parts.push(part([0, 0], blocks, 0)); - } else { - for y in (0..blocks[1]).step_by(2) { - for x in (0..blocks[0]).step_by(2) { - if x + 1 < blocks[0] && y + 1 < blocks[1] { - parts.push(part([x, y], [2, 2], block_order_position(x, y, blocks))); - continue; - } - for (bx, by) in [(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)] { - if bx < blocks[0] && by < blocks[1] { - let position = block_order_position(bx, by, blocks); - parts.push(part([bx, by], [1, 1], position)); - } - } - } - } - } - // The positions each part takes, in order: a 2 x 2 part four, a row or column its blocks. - let taken = |p: &(u64, u32, u32, ImageRegion)| { - let n = u64::from(p.3.size[0].div_ceil(unit.extent[0])) - * u64::from(p.3.size[1].div_ceil(unit.extent[1])); - p.0..p.0 + n - }; - let end = parts.iter().map(|p| taken(p).end).max().unwrap_or(0) * bytes; - match layout.offset.checked_add(end) { - Some(last) if last <= buffer_length => {} - _ => return Err(CopyProblem::BufferRange), - } - let span = layout.offset..layout.offset + end; - let start = base + layout.offset; - let staged = !vulkan_offset(start, unit); - let regions = parts - .iter() - .map( - |&(position, row_length, image_height, image)| BufferImageRegion { - buffer_offset: (if staged { 0 } else { start }) + position * bytes, - row_length, - image_height, - image, - }, - ) - .collect(); - let staging = staged.then(|| { - let mut runs: Vec> = parts.iter().map(taken).collect(); - runs.sort_by_key(|r| r.start); - let mut rows = Vec::::new(); - for run in runs { - match rows.last_mut() { - Some(last) if last.dst + last.size == run.start * bytes => { - last.size += (run.end - run.start) * bytes; - } - _ => rows.push(BufferRange { - src: start + run.start * bytes, - dst: run.start * bytes, - size: (run.end - run.start) * bytes, - }), - } - } - Staging { length: end, rows } - }); - Ok(BufferCopyPlan { - regions, - staging, - span, - }) -} diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs deleted file mode 100644 index 4206ba68a..000000000 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ /dev/null @@ -1,2603 +0,0 @@ -//! The blit encoder's texture commands: copies between buffers and textures and between textures, -//! `generate_mipmaps`, `synchronize_texture`, and the `optimize_contents_*` hints. -//! -//! - **Rules.** Metal's checks are `copy_plan.rs`'s and `blit_plan.rs`'s (measured on an Apple M3 -//! Max and M4). A size of 0 on an axis a texture of the copy lacks (depth on all but 3D textures, -//! height on 1D textures and texture buffers) copies one texel there, and a copy with another -//! axis 0, or of no slices or levels, copies nothing while the encoder's other commands run, as -//! plain Metal does (its validation stops each). A copy into or out of a memoryless texture, of -//! a size of 0 too, and its mipmaps' generation fail the command buffer as plain Metal's do -//! (`CommandBufferError::InvalidResource`: the encoder's run of blit encoders runs nothing, an M3 -//! Max under macOS 27.0.1); a copy of no slices or levels, the mipmaps of one level, the -//! `optimize_contents_*` hints and `synchronize_resource` take one and do nothing, as plain -//! Metal's do (its validation stops each but the hints). -//! - **Recording.** Each copy is one command of the encoder with what it reads and writes: a -//! texture's uses name its image's levels and layers (every aspect), so the encoder's order and -//! the commit's barriers cover views and their textures as one resource. A buffer layout -//! Vulkan cannot state (`blit_plan.rs`) goes through a scratch buffer of the encoder, two -//! commands. -//! - **Depth.** A copy from a buffer into 32-bit float depth copies the bytes as Metal holds -//! them, any `float`, as `Texture::replace_region` does, on a device with -//! `VK_EXT_depth_range_unrestricted` enabled. Elsewhere Vulkan takes no copied value outside -//! `[0, 1]` (`VUID-vkCmdCopyBufferToImage-pRegions-07931`), whatever the driver is measured to -//! keep: the copy's bytes go through a scratch buffer of the encoder (or the staging buffer -//! its plan copies its rows into), where a dispatch clamps each depth into `[0, 1]`, a NaN to -//! 1.0, before the copy into the image (`depth_clamp.rs`), as does a copy into a depth from a -//! colour texture through the scratch buffer below; the copy announces -//! `restricted-depth-upload`. -//! - **Textures over buffers**. A copy that names a texture over a buffer runs on the buffer's -//! bytes at Metal's layout, whatever else holds the texels (an aliasing image, or a shadow image -//! the next encoder that uses it copies in from the bytes): one buffer-to-buffer copy of its -//! texel rows, never of the bytes between them, from or into a buffer, another texture over a -//! buffer, or a texture's image. Where a source row and a destination row of one buffer share -//! bytes, the rows go through a scratch buffer of the encoder, as Metal moves them (the whole -//! source read before any of it is written). -//! - **Depth and stencil with colour**. Metal copies the bytes between a depth or stencil format, -//! or the stencil view `X32Stencil8`, and a colour format of its unit, and between stencil -//! formats (`copy_plan.rs`). Vulkan copies a depth or stencil aspect only into the same aspect of -//! the same format, so each image of the destination that no image of the source copies into -//! takes the regions through a scratch buffer of the encoder, out of the image the source's -//! texels are read from: two copies instead of one. -//! - **Overlap**. A region copied onto itself keeps its texels whatever order Metal copies them in, -//! and nothing is recorded for it. A copy between other overlapping regions of one texture's -//! texels (one image, through any views: the regions in the image's own levels and layers and in -//! one aspect) goes through a scratch buffer, the whole source read before any of it is written, -//! which is `memmove`'s answer: Metal's for regions up to a few hundred texels, where past that -//! its copy races, some texels reading what the copy already wrote, differently from run to run -//! (probes). Announced once (`overlapping-texture-copy-as-memmove`). A -//! multisampled texture, which Vulkan copies into no buffer, stays refused -//! `NotImplemented(OverlappingTextureCopies)`. -//! - **PVRTC**. A copy between a buffer and a PVRTC texture with a nonzero `bytesPerRow` moves its -//! blocks row by row, as Metal's does (and the runtime's carrier holds them, `pvrtc.rs`), with -//! `MTLBlitOptionRowLinearPVRTC` or without it, which plain Metal copies as it copies with it -//! (its validation stops it). With a `bytesPerRow` of 0, with the option or without it, the -//! blocks lie in plain Metal's block order, the region's own Morton order -//! (`blit_plan::block_order_position`; its validation stops that too), a region off its blocks -//! that of the blocks it is rounded to. Another format ignores the option, as plain Metal does. -//! - **Not yet:** a depth or stencil view of another format of its texture, other than the -//! stencil view `X32Stencil8` of `Depth32FloatStencil8`, is refused `NotImplemented`. - -use super::blit::{reads, reads_by, writes, writes_by, BlitCommandEncoder, TRANSFER}; -use super::blit_plan::{ - plan_block_order_copy, plan_buffer_copy, plan_levels_copy, plan_region_copy, plan_rows_copy, - plan_texels_rows_copy, plan_whole_copy, rows_below_row, texel_layout, BufferCopyPlan, - BufferImageRegion, BufferLayout, BufferRange, CopyPair, ImageCopyRegion, RowsCopy, -}; -use super::buffer_texture::Past; -use super::compressed_blit::{self, degrade_compressed_blit, Writer}; -use super::copy_plan::{ - check_region, colour_unit, copy_unit, depth_bytes, level_extent, shape, BlitOption, - CopyProblem, CopyRefusal, CopyUnit, ImageRegion, TextureRegion, -}; -use super::deferred::Deferred; -use super::degradation::Degradation; -use super::depth_clamp; -use super::encoder::{Overwrite, OverwriteBy}; -use super::error::{internal, invalid, Error, Problem, RuntimeGap}; -use super::fresh_unwritten::FreshUnwritten; -use super::image_plan::copies_between; -use super::mipmap::record_blit; -use super::mipmap_plan::{leaves_as_is, plan_mipmaps, MipmapPlan, MipmapRefusal}; -use super::nan_clear; -use super::pvrtc::{image_block_extent, image_buffer_region, image_region, is_pvrtc}; -use super::replay::{BlitCall, BufferToTexture, TextureToBuffer, TextureToTexture}; -use super::row_copies::RowCopies; -use super::sample_copy; -use super::sample_interleave; -use super::sample_planes; -use super::shadow::Covered; -use super::sparse::emulated::{Scrub, Written}; -use super::texture::{buffer_image_copy, texture_aspects, texture_region, Texture}; -use super::tracker::Access; -use super::two_planes; -use super::values::{Origin, Region, ResourceOptions, Size, StorageMode}; -use super::view_plan::ViewRecord; -use super::Buffer; -use crate::device::functions::Vk; -use ash::vk; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{aspects, is_depth_stencil}; -use metal2vulkan::metal::{PixelFormat, TextureType}; -use metal2vulkan::vk::{Format, ImageAspectFlags}; -use std::ops::Range; -use std::sync::Arc; - -/// One side of a copy of rows (`BlitCommandEncoder::rows_copy`): the buffer whose bytes its uses -/// name, and the buffer its rows lie in, `rebase` bytes before their place in the first one's -/// space: the buffer itself, or for a texture's bytes past those it keeps in its buffer the -/// texture's tail (`buffer_texture::Past`). -#[derive(Clone, Copy)] -struct RowsSide<'a> { - uses: &'a Buffer, - bytes: &'a Buffer, - rebase: u64, -} - -impl<'a> RowsSide<'a> { - /// `buffer`'s rows in its own bytes. - fn of(buffer: &'a Buffer) -> RowsSide<'a> { - RowsSide { - uses: buffer, - bytes: buffer, - rebase: 0, - } - } - - /// `buffer`'s rows in a texture's tail where `past` names it, else in the buffer's own bytes. - fn cut(buffer: &'a Buffer, past: Option>) -> RowsSide<'a> { - match past { - Some(past) => RowsSide { - uses: buffer, - bytes: past.tail, - rebase: past.rebase, - }, - None => RowsSide::of(buffer), - } - } -} - -fn copy_error(call: &'static str, refusal: CopyRefusal) -> Error { - match refusal { - CopyRefusal::Invalid(problem) => invalid(call, Problem::Copy(problem)), - CopyRefusal::Unsupported(unsupported) => Error::Unsupported(unsupported), - } -} - -fn read() -> Access { - Access::new(super::blit::TRANSFER, vk::AccessFlags2::TRANSFER_READ) -} - -fn write() -> Access { - Access::new(super::blit::TRANSFER, vk::AccessFlags2::TRANSFER_WRITE) -} - -/// The levels and layers of the image a region of `region`'s level and slices covers. -pub(super) fn subresources(region: &ImageRegion) -> (Range, Range) { - ( - region.level..region.level + 1, - region.layer..region.layer + region.layers, - ) -} - -/// The size a blit copies of `size` between textures of `types`, as plain Metal copies it: an axis -/// of 0 that a texture of the copy lacks, depth on all but 3D textures and height on 1D textures -/// and texture buffers, copies one texel there; `None` for a copy with another axis 0, which copies -/// nothing. -pub(super) fn copy_size(size: Size, types: &[TextureType]) -> Option { - use TextureType::{TextureBuffer, Type1D, Type1DArray, Type3D}; - let any = |lacks: fn(TextureType) -> bool| types.iter().any(|&t| lacks(t)); - let mut size = size; - if size.height == 0 && any(|t| matches!(t, Type1D | Type1DArray | TextureBuffer)) { - size.height = 1; - } - if size.depth == 0 && any(|t| !matches!(t, Type3D)) { - size.depth = 1; - } - (size.width != 0 && size.height != 0 && size.depth != 0).then_some(size) -} - -/// `level` and `slice`, and `origin` and `size`, as a region of a texture; refused as Metal -/// refuses a region past the texture when a value is past any texture. -pub(super) fn region( - call: &'static str, - origin: Origin, - size: Size, - level: u64, - slice: u64, -) -> Result { - texture_region(&Region { origin, size }, level, slice) - .ok_or_else(|| invalid(call, Problem::Copy(CopyProblem::Region))) -} - -/// `copy` without its columns past a destination's first `columns` texels across, which take no -/// write (`Texture::columns_in_place`), its source shrunk in proportion (its texels counted in -/// its own units); `None` where none is left. -fn written_columns(copy: &ImageCopyRegion, columns: u64) -> Option { - let (x, across) = (u64::from(copy.dst.origin[0]), u64::from(copy.dst.size[0])); - let width = columns.saturating_sub(x).min(across); - if width == 0 { - return None; - } - let source = u64::from(copy.src.size[0]) * width / across; - let mut copy = *copy; - // Each is at most the copy's own width, a `u32`. - copy.dst.size[0] = width as u32; - copy.src.size[0] = source as u32; - Some(copy) -} - -/// Refuse a depth or stencil view of another format of its texture, except the stencil view of -/// a combined one (`X32Stencil8` of `Depth32FloatStencil8`, which copies its stencil, probes): -/// Metal's copies through another are not measured. -fn check_depth_view(texture: &Texture) -> Result<(), Error> { - let pf = texture.record().pixel_format; - // A colour texture is no depth view, whatever holds it: a texture buffer has no image. - if !is_depth_stencil(pf) { - return Ok(()); - } - let of = texture.image_plan()?.pixel_format; - let stencil_view = pf == PixelFormat::X32Stencil8 && of == PixelFormat::Depth32FloatStencil8; - if pf != of && !stencil_view { - return Err(Error::NotImplemented(RuntimeGap::Textures)); - } - Ok(()) -} - -/// The aspect a blit between a buffer and the multisampled `texture` with `option` moves: a -/// depth or stencil format's copy unit's ([`unit()`], refused as the single-sample copy refuses -/// it), a colour format's colour. -fn multisampled_aspect( - call: &'static str, - texture: &Texture, - option: BlitOption, -) -> Result { - match is_depth_stencil(texture.record().pixel_format) { - true => Ok(unit(call, texture, option)?.aspect), - false => Ok(ImageAspectFlags::COLOR), - } -} - -/// `region` of the multisampled `texture` (in its own levels and slices) in its image's: Metal's -/// checks of a region past the texture's levels, slices or the level's extent (`Invalid`, as the -/// single-sample copy's `check_region`; a multisampled texture has no blocks), then the view's -/// first level and layer added, as the per-sample copy (`sample_interleave.rs`) and the -/// texture's uses name them. -fn multisampled_region( - call: &'static str, - texture: &Texture, - region: TextureRegion, -) -> Result { - let record = texture.record(); - let refused = || invalid(call, Problem::Copy(CopyProblem::Region)); - if region.level >= record.level_count || region.slice >= record.layer_count { - return Err(refused()); - } - let extent = level_extent(record, region.level); - let axes = || region.origin.iter().zip(®ion.size).zip(&extent); - if axes().any(|((&o, &s), &e)| u64::from(o) + u64::from(s) > u64::from(e)) { - return Err(refused()); - } - Ok(TextureRegion { - level: record.base_level + region.level, - slice: record.base_layer + region.slice, - ..region - }) -} - -/// The box `region` covers (of a multisampled texture's image, in its levels and layers, -/// [`multisampled_region`]), every sample of it. -fn multisampled_texels(region: &TextureRegion) -> Written { - Written { - level: region.level, - layers: region.slice..region.slice + 1, - origin: region.origin, - size: region.size, - } -} - -/// The box a multisampled copy of `region` into `texture`'s `aspect` writes, every sample of it. -fn multisampled_box( - texture: &Texture, - aspect: ImageAspectFlags, - region: &TextureRegion, -) -> Result { - let [x, y, z] = region.origin; - let [width, height, depth] = region.size; - Ok(Covered { - image: texture.raw_image()?, - subresource: vk::ImageSubresourceLayers { - aspect_mask: aspect.into(), - mip_level: region.level, - base_array_layer: region.slice, - layer_count: 1, - }, - offset: vk::Offset3D { - x: x as i32, - y: y as i32, - z: z as i32, - }, - extent: vk::Extent3D { - width, - height, - depth, - }, - }) -} - -/// The copy unit of `texture` copied with `option`. -pub(super) fn unit( - call: &'static str, - texture: &Texture, - option: BlitOption, -) -> Result { - // A texture over a buffer holds a colour format (`linear_plan.rs`): its copy unit is its - // texel, whatever holds it. - if texture.over_buffer() { - // A depth or stencil texture over a surface's plane, or a view of one, moves the aspect - // the plane holds; the stencil of `Depth32Float_Stencil8`, which is not in the plane - // (that texture's with `StencilFromDepthStencil`, or its `X32_Stencil8` view's), is the - // runtime's gap (`linear_plan.rs`). - let pf = texture.record().pixel_format; - if let Some(held) = texture.surface_plane_unit() { - let own = aspects(pf).unwrap_or(ImageAspectFlags::empty()); - let stencil = !own.contains(ImageAspectFlags::DEPTH) - || (own.contains(ImageAspectFlags::STENCIL) - && option == BlitOption::StencilFromDepthStencil); - if stencil && held.aspect == ImageAspectFlags::DEPTH { - return Err(Error::NotImplemented(RuntimeGap::SurfaceDepthStencil { - pixel_format: pf, - })); - } - return Ok(held); - } - // A two-plane extended-range texture over a surface's planes: plane 0's color words, - // which Metal's blits with a buffer move (`texture/surface_two_planes.rs`). - if two_planes::holds_planes(texture.record().pixel_format) { - return Ok(two_planes::UNIT); - } - return colour_unit(texture.record().pixel_format) - .map_err(|refusal| copy_error(call, refusal)); - } - check_depth_view(texture)?; - copy_unit( - texture.record().pixel_format, - &texture.image_plan()?.mapping, - option, - ) - .map_err(|refusal| copy_error(call, refusal)) -} - -/// The plan of a copy between `buffer`, laid out as `layout`, and `region` of `texture` in -/// `unit`s (`into_texture` from the buffer, which reads it to its copy reach). A PVRTC texture's -/// blocks lie row by row at a nonzero `bytesPerRow`, with `MTLBlitOptionRowLinearPVRTC` or -/// without it (plain Metal copies a PVRTC texture without the option, which its validation -/// stops, as with it: our probe on an M4 under macOS 27.0.1, both directions, 4- and -/// 2-bit formats, padded rows and a region; the reims-vgpu consumer's run on an M3 Max under -/// macOS 26.7), and in plain Metal's block order at a `bytesPerRow` of 0, with the option or -/// without it (`plan_block_order_copy`; its validation stops both), a region off its blocks as the -/// blocks it is rounded to. -fn plan_copy( - call: &'static str, - texture: &Texture, - region: &TextureRegion, - unit: &CopyUnit, - layout: &BufferLayout, - buffer: &Buffer, - into_texture: bool, -) -> Result { - let record = texture.record(); - let buffer_length = if into_texture { - buffer.copy_reach() - } else { - buffer.length() - }; - let base = buffer.start(); - if is_pvrtc(texture.pixel_format()) && layout.bytes_per_row == 0 { - return plan_block_order_copy(record, region, unit, layout, buffer_length, base) - .map_err(|problem| invalid(call, Problem::Copy(problem))); - } - plan_buffer_copy( - record, - region, - unit, - layout, - buffer_length, - base, - into_texture, - ) - .map_err(|problem| invalid(call, Problem::Copy(problem))) -} - -/// The Vulkan region of `region`. -pub(super) fn buffer_image_region(region: &BufferImageRegion) -> vk::BufferImageCopy { - vk::BufferImageCopy { - buffer_offset: region.buffer_offset, - buffer_row_length: region.row_length, - buffer_image_height: region.image_height, - ..buffer_image_copy(®ion.image) - } -} - -fn buffer_copy(range: &BufferRange) -> vk::BufferCopy { - vk::BufferCopy { - src_offset: range.src, - dst_offset: range.dst, - size: range.size, - } -} - -/// `region` as one `VkImageCopy`, whose one extent is the source's: regions of one size only -/// (others go through a buffer, `texture_copies_of_bytes`). -fn image_copy(region: &ImageCopyRegion) -> vk::ImageCopy { - debug_assert_eq!(region.src.size, region.dst.size, "one extent, two sizes"); - let layers = |r: &ImageRegion| vk::ImageSubresourceLayers { - aspect_mask: r.aspect.into(), - mip_level: r.level, - base_array_layer: r.layer, - layer_count: r.layers, - }; - let offset = |[x, y, z]: [u32; 3]| vk::Offset3D { - x: x as i32, - y: y as i32, - z: z as i32, - }; - let [width, height, depth] = region.src.size; - vk::ImageCopy { - src_subresource: layers(®ion.src), - src_offset: offset(region.src.origin), - dst_subresource: layers(®ion.dst), - dst_offset: offset(region.dst.origin), - extent: vk::Extent3D { - width, - height, - depth, - }, - } -} - -/// Whether two regions of one texture's texels share texels: of one level, layer and texel, -/// unless one lies in a depth/stencil image's depth and the other in its stencil, which Vulkan -/// keeps apart. -fn regions_meet(a: &ImageRegion, b: &ImageRegion) -> bool { - let meet = |a0: u32, an: u32, b0: u32, bn: u32| { - u64::from(a0) < u64::from(b0) + u64::from(bn) - && u64::from(b0) < u64::from(a0) + u64::from(an) - }; - let depth_stencil = ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL; - let apart = depth_stencil.contains(a.aspect) - && depth_stencil.contains(b.aspect) - && !a.aspect.intersects(b.aspect); - !apart - && a.level == b.level - && meet(a.layer, a.layers, b.layer, b.layers) - && (0..3).all(|i| meet(a.origin[i], a.size[i], b.origin[i], b.size[i])) -} - -impl BlitCommandEncoder { - /// Refuse `texture` of another device; note it for its heap shadow (`BlitCommandEncoder::see`). - pub(super) fn check_texture( - &mut self, - call: &'static str, - texture: &Texture, - ) -> Result<(), Error> { - self.core().check_device(call, texture.generation())?; - self.see(texture); - Ok(()) - } - - /// Whether a texture of the copy is memoryless, a texture buffer too: plain Metal fails the - /// command buffer of a copy into or out of one, of a size of 0 too, and of its mipmaps' - /// generation (`CommandBufferError::InvalidResource`, the encoder's whole run of blit - /// encoders running nothing, an M3 Max under macOS 27.0.1), so the encoder fails it and the - /// copy records nothing. - pub(super) fn fails_on_memoryless(&mut self, textures: &[&Texture]) -> bool { - let memoryless = textures.iter().any(|texture| texture.is_memoryless()); - if memoryless { - self.core().fail_memoryless_use(); - } - memoryless - } - - /// `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture: - /// destinationSlice:destinationLevel:destinationOrigin:options:`: `source_size` texels of - /// the buffer, rows `source_bytes_per_row` apart and images `source_bytes_per_image` apart - /// (read only for more than one image), into the texture's - /// `destination_level` and `destination_slice` at `destination_origin`. A combined - /// depth/stencil texture takes one aspect, which `options` names, and its depth with - /// [`BlitOption::None`]; another texture ignores the option, as plain Metal does (its - /// validation stops both). A compressed region off its blocks copies the blocks it starts in, - /// as plain Metal does. A PVRTC texture's blocks lie in the buffer row by row with a nonzero - /// `source_bytes_per_row`, with [`BlitOption::RowLinearPVRTC`] or without it, and with a - /// `source_bytes_per_row` of 0 in the region's own Morton order, the x bit lowest, a position - /// no block takes neither read nor written, a region off its blocks that of the blocks it is - /// rounded to, as plain Metal lays them out (its validation stops the copy without the option - /// and every copy at 0). - /// - /// An offset or `bytes_per_row` off the copy unit, or rows that overlap, read each row where - /// plain Metal reads it, for a colour format and `Depth32Float`, and so does a - /// `bytes_per_image` of more than one image off the copy unit or below the region's rows. A - /// no-copy buffer is read past its length to the end of its host pages, the caller's bytes, as - /// plain Metal reads them (its validation stops both). - /// - /// A size of 0 copies as the module docs say, as plain Metal does. Refused: what Metal stops - /// (`Invalid`: with a [`CopyProblem`], a region past the level, an offset or `bytes_per_row` - /// off the copy unit of another depth or stencil format or of a texture over a buffer, a - /// layout that runs past the buffer but for that read); a buffer or texture of another - /// device (`Invalid`). 32-bit float depth is copied as `Texture::replace_region` copies it: - /// as Metal holds it, or clamped into `[0, 1]` where the device's depth image would store it - /// so (the module docs). - pub fn copy_from_buffer_to_texture( - &mut self, - source_buffer: &Buffer, - source_offset: u64, - source_bytes_per_row: u64, - source_bytes_per_image: u64, - source_size: Size, - destination_texture: &Texture, - destination_slice: u64, - destination_level: u64, - destination_origin: Origin, - options: BlitOption, - ) -> Result<(), Error> { - self.logged( - |_| { - BlitCall::CopyBufferToTexture(Box::new(BufferToTexture { - source: source_buffer.clone(), - source_offset, - bytes_per_row: source_bytes_per_row, - bytes_per_image: source_bytes_per_image, - size: source_size, - destination: destination_texture.clone(), - slice: destination_slice, - level: destination_level, - origin: destination_origin, - options, - })) - }, - |this| { - // A source whose GPU writes are dropped is read in place through its read twin, - // where it has one (`read_twin.rs`). - let twin = this.core().read_source(source_buffer); - this.buffer_into_texture( - Writer::Blit, - ( - twin.as_ref().unwrap_or(source_buffer), - source_offset, - source_bytes_per_row, - source_bytes_per_image, - ), - source_size, - ( - destination_texture, - destination_slice, - destination_level, - destination_origin, - ), - options, - ) - }, - ) - } - - /// [`copy_from_buffer_to_texture`](Self::copy_from_buffer_to_texture), unlogged, its texels - /// written by `writer`: a blit's copy, or a fill's rows of its texel (`blit_fill.rs`), which - /// differ in what Metal's compression writes of a `BGRA10_XR` texture's texels - /// (`compressed_blit.rs`). - pub(super) fn buffer_into_texture( - &mut self, - writer: Writer, - (source_buffer, source_offset, source_bytes_per_row, source_bytes_per_image): ( - &Buffer, - u64, - u64, - u64, - ), - source_size: Size, - (destination_texture, destination_slice, destination_level, destination_origin): ( - &Texture, - u64, - u64, - Origin, - ), - options: BlitOption, - ) -> Result<(), Error> { - const CALL: &str = "copy_from_buffer_to_texture"; - self.core().check_device(CALL, source_buffer.generation())?; - self.check_texture(CALL, destination_texture)?; - destination_texture.check_plane_copied()?; - if self.fails_on_memoryless(&[destination_texture]) { - return Ok(()); - } - destination_texture.check_rotated_reach()?; - let Some(size) = copy_size(source_size, &[destination_texture.texture_type()]) else { - return Ok(()); - }; - // A BC texture's columns past its texels in place take no write (an IOSurface plane's - // rows of blocks wider than the plane's, `Texture::written_in_place`): the copy reads - // and writes the rest alone, as the x86 Macs' blits do. - let Some(size) = destination_texture.written_in_place(destination_origin, size) else { - return Ok(()); - }; - // Vulkan copies no multisampled image from a buffer, so the buffer-image path below - // cannot take one. The empty copy is the no-op Metal makes (above); a real one into - // a multisampled texture is emulated per sample through a wide image and a scratch - // (`sample_interleave.rs`), or refused typed where the device cannot run that. - let samples = destination_texture.record().samples; - if samples > 1 { - let layout = BufferLayout { - offset: source_offset, - bytes_per_row: source_bytes_per_row, - bytes_per_image: source_bytes_per_image, - }; - let region = region( - CALL, - destination_origin, - size, - destination_level, - destination_slice, - )?; - let region = multisampled_region(CALL, destination_texture, region)?; - let (raw_buffer, base) = self.core().blit_at(source_buffer, 0)?; - let aspect = multisampled_aspect(CALL, destination_texture, options)?; - let planned = sample_interleave::InterleaveCopy::plan( - CALL, - self.core().command_buffer(), - raw_buffer, - base, - source_buffer.copy_reach(), - &layout, - destination_texture, - ®ion, - aspect, - samples, - true, - )?; - return match planned { - Some(copy) => { - // Every sample of the region written: a heap shadow it covers takes no - // copy in. - let covered = [multisampled_box(destination_texture, aspect, ®ion)?]; - let boxes = (&[][..], &covered[..]); - self.command_in_reading(copy.stages, ©.uses, boxes, |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a - // render pass; the buffer (held by `blit_at`), the texture and - // the copy's images and objects (held by the copy; both - // retained below) are live until it completes. - unsafe { copy.record(device, raw) }; - })?; - // A depth written as the single-sample path writes one announces as it - // does. - destination_texture.degrade_depth_upload(CALL, aspect, true); - destination_texture.degrade_depth_denormals(CALL, aspect, false); - copy.announce(self.core().device(), CALL, destination_texture); - let format = destination_texture.pixel_format(); - copy.announce_staging(self.core().device(), format, true); - self.core().retain(copy); - self.core().retain_shared(destination_texture.held()); - // Every sample of the region written, as the single-sample path's. - let written = multisampled_texels(®ion); - self.scrub(destination_texture, vec![(aspect.into(), written)]) - } - None => Err(Error::NotImplemented(RuntimeGap::MultisampledBufferCopy)), - }; - } - let texture = destination_texture; - let layout = BufferLayout { - offset: source_offset, - bytes_per_row: source_bytes_per_row, - bytes_per_image: source_bytes_per_image, - }; - if two_planes::holds_planes(texture.pixel_format()) && !texture.over_buffer() { - let region = region( - CALL, - destination_origin, - size, - destination_level, - destination_slice, - )?; - return self.plane_copy(CALL, source_buffer, texture, ®ion, &layout, true); - } - let unit = unit(CALL, texture, options)?; - let region = region( - CALL, - destination_origin, - size, - destination_level, - destination_slice, - )?; - if let Some(texels) = texture.blit_texels() { - // Rows that share bytes (an IOSurface plane's on Metal's GPU): the row - // copies would write every shared byte from one fixed row, where Metal - // leaves it from whichever row its own command wrote last -- an order that - // follows the command, the GPU pitch and the row count, and that one shape - // does not settle from run to run (`linear_plan.rs`'s **Rows that - // overlap**). The other direction reads those rows instead of writing them - // and is served (`copy_from_texture_to_buffer`). - if texels.plane_rows_overlap() { - return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)); - } - let (from, to) = plan_rows_copy( - texture.record(), - ®ion, - &unit, - &layout, - source_buffer.copy_reach(), - &texels.layout, - ) - .map_err(|problem| invalid(CALL, Problem::Copy(problem)))?; - let copy = RowsCopy::new(&from, &to); - return self.texels_rows_copy( - (source_buffer, None), - (&texels.buffer, texels.past()), - ©, - ); - } - let plan = plan_copy(CALL, texture, ®ion, &unit, &layout, source_buffer, true)?; - let written: Vec = plan.regions.iter().map(|r| r.image).collect(); - self.buffer_texture_copy(source_buffer, texture, plan, true)?; - texture.degrade_depth_upload(CALL, unit.aspect, true); - texture.degrade_depth_denormals(CALL, unit.aspect, false); - // Into a texture Metal keeps compressed: Metal's encoding of what the copy wrote, else - // the device's copy keeps the bytes (a fill's texel was encoded before it, `blit_fill.rs`). - match writer { - Writer::Blit - if compressed_blit::canonical(texture) - && self.canonical_texels(texture, &written)? => {} - Writer::Blit => degrade_compressed_blit(CALL, texture)?, - Writer::Fill => compressed_blit::degrade_compressed_fill(texture), - } - // Into a texture with a decoded twin: the twin's texels of what the copy wrote. - self.decode_twin(texture, &written) - } - - /// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer: - /// destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:`: the - /// texture's region into the buffer, laid out as - /// [`copy_from_buffer_to_texture`](Self::copy_from_buffer_to_texture) reads it. The bytes - /// between rows and images are left as they are; images closer than the region's rows are - /// written in turn, the later image's bytes staying, as plain Metal writes them. Rows closer - /// than a row (a `bytesPerRow` below it, as `MTLPixelFormatGetInfoForDevice` describes a - /// one-plane YCbCr format's) are written in turn too, the later row's bytes staying: plain - /// Metal writes them in no one order, and that is one of its answers. - /// - /// Refused as `copy_from_buffer_to_texture` is, except that depth is copied out on every - /// device. - pub fn copy_from_texture_to_buffer( - &mut self, - source_texture: &Texture, - source_slice: u64, - source_level: u64, - source_origin: Origin, - source_size: Size, - destination_buffer: &Buffer, - destination_offset: u64, - destination_bytes_per_row: u64, - destination_bytes_per_image: u64, - options: BlitOption, - ) -> Result<(), Error> { - self.logged( - |_| { - BlitCall::CopyTextureToBuffer(Box::new(TextureToBuffer { - source: source_texture.clone(), - slice: source_slice, - level: source_level, - origin: source_origin, - size: source_size, - destination: destination_buffer.clone(), - destination_offset, - bytes_per_row: destination_bytes_per_row, - bytes_per_image: destination_bytes_per_image, - options, - })) - }, - |this| { - const CALL: &str = "copy_from_texture_to_buffer"; - this.check_texture(CALL, source_texture)?; - source_texture.check_plane_copied()?; - this.core() - .check_device(CALL, destination_buffer.generation())?; - if this.fails_on_memoryless(&[source_texture]) { - return Ok(()); - } - source_texture.check_rotated_reach()?; - let Some(size) = copy_size(source_size, &[source_texture.texture_type()]) else { - return Ok(()); - }; - let layout = BufferLayout { - offset: destination_offset, - bytes_per_row: destination_bytes_per_row, - bytes_per_image: destination_bytes_per_image, - }; - // Vulkan copies no multisampled image into a buffer, so the buffer-image path below - // cannot take one. The empty copy is the no-op Metal makes (above); a real one out - // of a multisampled texture is emulated per sample through a scratch and a wide - // image (`sample_interleave.rs`), or refused typed where the device cannot run - // that. Rows that overlap out of a multisampled texture race on Metal (no exact - // answer), as out of a single-sample one (`blit_plan::placed_rows`), so the - // emulation's placement of the rows refuses them - // (`sample_interleave::placed_rows`). - let samples = source_texture.record().samples; - if samples > 1 { - let aspect = multisampled_aspect(CALL, source_texture, options)?; - let region = region(CALL, source_origin, size, source_level, source_slice)?; - let region = multisampled_region(CALL, source_texture, region)?; - let (raw_buffer, base) = this.core().blit_at(destination_buffer, 0)?; - let planned = sample_interleave::InterleaveCopy::plan( - CALL, - this.core().command_buffer(), - raw_buffer, - base, - destination_buffer.length(), - &layout, - source_texture, - ®ion, - aspect, - samples, - false, - )?; - // The region's samples alone are read (`fresh_unwritten.rs`). - let boxes = [(aspect.into(), multisampled_texels(®ion))]; - let fresh_reads = - FreshUnwritten::reads(this.core().device(), source_texture, &boxes)?; - return match planned { - Some(copy) => { - this.command_in_reading( - copy.stages, - ©.uses, - (&fresh_reads, &[]), - |device, raw| { - // SAFETY: as in `copy_from_buffer_to_texture`'s emulation. - unsafe { copy.record(device, raw) }; - }, - )?; - let format = source_texture.pixel_format(); - copy.announce_staging(this.core().device(), format, false); - this.core().retain(copy); - this.core().retain_shared(source_texture.held()); - Ok(()) - } - None => Err(Error::NotImplemented(RuntimeGap::MultisampledBufferCopy)), - }; - } - if two_planes::holds_planes(source_texture.pixel_format()) - && !source_texture.over_buffer() - { - let region = region(CALL, source_origin, size, source_level, source_slice)?; - return this.plane_copy( - CALL, - destination_buffer, - source_texture, - ®ion, - &layout, - false, - ); - } - let unit = unit(CALL, source_texture, options)?; - let region = region(CALL, source_origin, size, source_level, source_slice)?; - if let Some(texels) = source_texture.blit_texels() { - // Rows that share bytes (an IOSurface plane's on Metal's GPU) are served - // here, where they are read and not written. The plane is the source; the - // destination is the caller's buffer, whose rows share bytes only at a - // `bytesPerRow` below the region's row, where they are written in turn, the - // later row's bytes standing, as plain Metal's blit may leave them - // (`plan_rows_copy`, `RowsCopy::new`); a plane is a 2D texture of one image, - // so the other way a layout's rows could meet -- images closer than their - // rows -- cannot arise. Each destination row takes the - // plane's bytes at its own GPU row, so a byte two rows share is read once - // for each of them, which is what Metal's own copy reads (an Apple M3 Max - // under macOS 27.0.1, one shape a process, - // `probes/overlapping_plane_row_reads.m`). - // - // Reading rows that overlap is not the mirror of writing them, so the - // direction above stays refused and this one need not: a write has to settle - // which of two rows leaves the shared bytes behind, and Metal settles it no - // one way (`linear_plan.rs`'s **Rows that overlap**), while a read settles - // nothing -- it only says which byte each destination byte comes from, and - // every row that holds a shared byte holds the same byte. - let (to, from) = plan_rows_copy( - source_texture.record(), - ®ion, - &unit, - &layout, - destination_buffer.length(), - &texels.layout, - ) - .map_err(|problem| invalid(CALL, Problem::Copy(problem)))?; - let copy = RowsCopy::new(&from, &to); - return this.texels_rows_copy( - (&texels.buffer, texels.past()), - (destination_buffer, None), - ©, - ); - } - let plan = plan_copy( - CALL, - source_texture, - ®ion, - &unit, - &layout, - destination_buffer, - false, - )?; - this.buffer_texture_copy(destination_buffer, source_texture, plan, false)?; - // Out of a texture Metal keeps compressed: Metal's encoding of what the copy - // wrote, where the device binds the buffer's words, else the device's copy keeps - // the bytes. - if compressed_blit::canonical(source_texture) - && this.canonical_words(destination_buffer, &layout, region.size)? - { - return Ok(()); - } - degrade_compressed_blit(CALL, source_texture) - }, - ) - } - - /// A blit between `buffer`, laid out as `layout`, and `region` of a two-plane - /// extended-range texture (`into_texture` from the buffer; `two_planes.rs`): Metal's checks - /// of the copy in plane 0's color words, then their bands. Refused as other copies are, and - /// `NotImplemented(Format)` for a layout Metal's answer was not measured for. - fn plane_copy( - &mut self, - call: &'static str, - buffer: &Buffer, - texture: &Texture, - region: &TextureRegion, - layout: &BufferLayout, - into_texture: bool, - ) -> Result<(), Error> { - let unit = two_planes::UNIT; - let image = check_region(texture.record(), region, &unit) - .map_err(|problem| invalid(call, Problem::Copy(problem)))?; - // Metal's checks of the buffer's layout, its range among them, as of a 4-byte format. - plan_copy(call, texture, region, &unit, layout, buffer, into_texture)?; - let s = shape(region.size, &unit); - let width = level_extent(texture.record(), region.level)[0]; - let flat = texture.texture_type() != TextureType::Type3D; - if rows_below_row(layout, &s, &unit) && width.is_multiple_of(4) && flat { - return self.plane_short_rows_copy(buffer, texture, &image, layout, into_texture); - } - if !two_planes::measured_layout( - s.row_bytes, - s.rows, - s.images, - layout.bytes_per_row, - layout.bytes_per_image, - layout.offset, - ) { - return Err(Error::Unsupported(two_planes::unmeasured( - texture.pixel_format(), - ))); - } - // At a width that is not a multiple of 4 Metal's blit addresses the level's rows short of - // where they lie, moving texels between rows: at those rows for a 2D texture or array of - // one level (`two_planes/buffer_rows.rs`); for another (more levels, a view, 1D, 3D, a - // surface's), announced, the texels moved as `getBytes` and `replaceRegion` move them. - if !width.is_multiple_of(4) && two_planes::rows_held(texture) { - return self.plane_rows_copy(buffer, texture, &image, layout, into_texture); - } - if !width.is_multiple_of(4) { - let pf = texture.pixel_format(); - self.core() - .device() - .degrade(Degradation::TwoPlaneBufferBlit, || { - let object = format!( - "`{call}` between a buffer and a {} texture level {width} texels wide", - pf.name() - ); - let reason = "a texture of more than one level, a view, a 1D or 3D texture or a surface's: \ - the texels move at the rows the texture holds them in, where \ - Metal's blit addresses its rows floor(4w/16)*16 bytes apart, \ - short of them, and so moves texels between rows" - .to_owned(); - (object, reason) - }); - } - // A two-plane 3D texture (`two_planes.rs`): Metal's blit into it writes each image of - // the region over texel `(x, y)` of its first slice in turn, so the last image stays - // there; its blit out of it reads texel `(0, 0, 0)` at every texel of every image. - if texture.texture_type() == TextureType::Type3D { - let first = ImageRegion { - origin: [image.origin[0], image.origin[1], 0], - size: [image.size[0], image.size[1], 1], - ..image - }; - if !into_texture { - return self.plane_first_texel_copy(buffer, texture, &image, layout); - } - let last = u64::from(image.size[2].saturating_sub(1)); - let layout = BufferLayout { - offset: layout.offset + last * layout.bytes_per_image, - ..*layout - }; - return self.plane_words_copy(buffer, texture, &first, &layout, true); - } - self.plane_words_copy(buffer, texture, &image, layout, into_texture) - } - - /// A blit between `buffer`, laid out as `layout` at a `bytesPerRow` below the region's row - /// alone (`blit_plan::rows_below_row`), and `region` of a two-plane extended-range `texture` - /// whose level is a multiple of 4 texels wide and not 3D, as plain Metal's blit moves it - /// (an Apple M3 Max under macOS 27.0.1, `probes/short_row_kinds.m`: a 32 x 8 - /// `RGB10A8_2P_XR10` texture at half its row, half plus a word and the row less 16): each - /// row's color words at `y x bytesPerRow`. Into the texture each row reads its words whole - /// from there, the rows overlapping in the buffer, which the module reads as any other - /// layout's ([`plane_words_copy`](Self::plane_words_copy)). Out of it Metal writes them in - /// no one order; the rows go in turn, the later row's words standing: the words of every - /// row that no later row writes (its first `bytesPerRow` bytes), then the last row's rest, - /// two copies whose words in the buffer are disjoint. - fn plane_short_rows_copy( - &mut self, - buffer: &Buffer, - texture: &Texture, - region: &ImageRegion, - layout: &BufferLayout, - into_texture: bool, - ) -> Result<(), Error> { - if into_texture { - return self.plane_words_copy(buffer, texture, region, layout, true); - } - let [x, y, z] = region.origin; - let [width, height, _] = region.size; - // A row's words no later row writes: the pitch's, below the region's row. - let pitch = (layout.bytes_per_row / u64::from(two_planes::UNIT.bytes)) as u32; - let heads = ImageRegion { - size: [pitch, height, 1], - ..*region - }; - self.plane_words_copy(buffer, texture, &heads, layout, false)?; - let rest = ImageRegion { - origin: [x + pitch, y + height - 1, z], - size: [width - pitch, 1, 1], - ..*region - }; - let after = BufferLayout { - offset: layout.offset + u64::from(height) * layout.bytes_per_row, - ..*layout - }; - self.plane_words_copy(buffer, texture, &rest, &after, false) - } - - /// Record a checked copy between `buffer` and `texture` (`into_texture`: from the buffer - /// into the texture), through a scratch buffer when the plan stages it. - fn buffer_texture_copy( - &mut self, - buffer: &Buffer, - texture: &Texture, - plan: BufferCopyPlan, - into_texture: bool, - ) -> Result<(), Error> { - let Some(first) = plan.regions.first() else { - unreachable!("an empty copy was refused") - }; - let (levels, layers) = subresources(&first.image); - let image_use = texture.image_use( - levels, - layers, - if into_texture { write() } else { read() }, - into_texture, - )?; - // A copy out of the texture reads its regions alone (`fresh_unwritten.rs`). - let boxes: Vec<_> = match into_texture { - true => Vec::new(), - false => (plan.regions.iter()) - .map(|r| (r.image.aspect.into(), Written::of(&r.image))) - .collect(), - }; - let fresh_reads = FreshUnwritten::reads(self.core().device(), texture, &boxes)?; - // The plan's offsets are the `VkBuffer`'s (`plan_buffer_copy`'s base), its regions in the - // texture's texels, which a 2-bit PVRTC texture's carrier halves across - // (`pvrtc::image_buffer_region`). Read as a blit's (`host_residency.rs`). - let (raw_buffer, _) = self.core().blit_at(buffer, 0)?; - let image = texture.raw_image()?; - let image_plan = texture.image_plan()?; - let regions: Vec = plan - .regions - .iter() - .map(|region| buffer_image_region(&image_buffer_region(image_plan, *region))) - .collect(); - let buffer_use = if into_texture { - reads(buffer, plan.span.clone()) - } else { - writes(buffer, plan.span.clone()) - }; - // A copy into the texture writes every texel of its regions. - let covered = match into_texture { - true => Covered::into_image(image, ®ions), - false => Vec::new(), - }; - // A 32-bit float depth into a depth image that may store one outside [0, 1] clamped, the - // depths clamped first (`depth_clamp.rs`). - let clamps = into_texture && texture.clamps_depth_upload(first.image.aspect); - match plan.staging { - None if clamps => { - let from = (buffer, raw_buffer, plan.span.clone()); - let (scratch, through, staged) = self.clamped_depth_copies(from, ®ions)?; - let uses = [reads(&scratch, 0..scratch.length()), image_use]; - self.command_reading(&uses, (&[], &covered), |device, raw| { - // SAFETY: the encoder's command buffer is recording; the scratch buffer and - // the image are live and retained until it completes, the image is in the - // `GENERAL` layout, and the regions lie in both. - unsafe { - device.cmd_copy_buffer_to_image( - raw, - through, - image, - vk::ImageLayout::GENERAL, - &staged, - ); - } - })?; - self.core().retain(scratch); - } - None => { - let boxes = (&fresh_reads[..], &covered[..]); - self.command_reading(&[buffer_use, image_use], boxes, |device, raw| { - // SAFETY: the encoder's command buffer is recording; the buffer and the image - // are live and retained until it completes, the image is in the `GENERAL` - // layout, and the regions lie in both (checked by the plan). - unsafe { - if into_texture { - device.cmd_copy_buffer_to_image( - raw, - raw_buffer, - image, - vk::ImageLayout::GENERAL, - ®ions, - ); - } else { - device.cmd_copy_image_to_buffer( - raw, - image, - vk::ImageLayout::GENERAL, - raw_buffer, - ®ions, - ); - } - } - })? - } - Some(staging) => { - let scratch = self - .core() - .device() - .own_buffer(staging.length, ResourceOptions::private())?; - // A buffer `own_buffer` makes starts at its `VkBuffer`'s start, where the - // plan's staging offsets are. - let (through, _) = scratch.at(0); - let whole = 0..staging.length; - let rows: Vec = if into_texture { - staging.rows.iter().map(buffer_copy).collect() - } else { - // The plan's rows run buffer to staging; out of the texture they run back. - let back = |r: &BufferRange| BufferRange { - src: r.dst, - dst: r.src, - size: r.size, - }; - staging.rows.iter().map(|r| buffer_copy(&back(r))).collect() - }; - let (src, dst) = if into_texture { - (raw_buffer, through) - } else { - (through, raw_buffer) - }; - let device = self.core().device().clone(); - let rows = RowCopies::new(&device, src, dst, rows); - let move_rows = |device: &Vk, raw: vk::CommandBuffer| { - // SAFETY: as below; the rows lie in both buffers (checked by the plan), the - // staging buffer is another buffer, and the rows written are disjoint (out of - // the texture, `later_rows_win`). - unsafe { rows.record(device, raw) }; - }; - let copy_image = |device: &Vk, raw: vk::CommandBuffer| { - // SAFETY: the encoder's command buffer is recording; the scratch buffer and - // the image are live and retained until it completes, the image is in the - // `GENERAL` layout, and the region lies in both. - unsafe { - if into_texture { - device.cmd_copy_buffer_to_image( - raw, - through, - image, - vk::ImageLayout::GENERAL, - ®ions, - ); - } else { - device.cmd_copy_image_to_buffer( - raw, - image, - vk::ImageLayout::GENERAL, - through, - ®ions, - ); - } - } - }; - let span = plan.span.clone(); - if into_texture { - let uses = [ - reads_by(buffer, span, rows.read()), - writes_by(&scratch, whole.clone(), rows.write()), - ]; - self.command_in(rows.stages(), &uses, move_rows)?; - if clamps { - self.clamp_depths(&scratch, ®ions)?; - } - let uses = [reads(&scratch, whole), image_use]; - self.command_reading(&uses, (&[], &covered), copy_image)?; - } else { - let uses = [image_use, writes(&scratch, whole.clone())]; - self.command_reading(&uses, (&fresh_reads, &[]), copy_image)?; - let uses = [ - reads_by(&scratch, whole, rows.read()), - writes_by(buffer, span, rows.write()), - ]; - self.command_in(rows.stages(), &uses, move_rows)?; - } - if let Some(sets) = rows.retained() { - self.core().retain(sets); - } - self.core().retain(scratch); - let (offset, format) = (plan.span.start, texture.pixel_format()); - self.core() - .device() - .degrade(Degradation::StagedTextureCopy, || { - let object = if into_texture { - format!( - "a copy from a buffer at offset {offset} into a {format:?} texture" - ) - } else { - format!( - "a copy from a {format:?} texture into a buffer at offset {offset}" - ) - }; - let reason = "Vulkan cannot state the buffer's layout: its offset in the \ - VkBuffer is off the texel block (or off 4 bytes for depth and \ - stencil), or its images lie apart by other than a multiple of \ - its row pitch"; - (object, reason.to_owned()) - }); - } - } - self.core().retain_shared(texture.held()); - if into_texture { - let written = (plan.regions.iter()) - .map(|r| (r.image.aspect.into(), Written::of(&r.image))) - .collect(); - self.scrub(texture, written)?; - } - Ok(()) - } - - /// After a command that wrote `written` of `texture` (each box with the aspects it wrote): - /// its texels are no longer a new texture's unwritten pattern (`fresh_unwritten.rs`, by box and - /// aspect); and where it is a sparse texture the runtime zeroes, its scrub, so what the command - /// wrote into unmapped tiles reads zero, as Metal drops it. - /// - /// Measured for a **blit** and not only for a shader's read, on an Apple M3 Max under macOS - /// 27.0.1 (26A434), three runs each in its own process, over a 256 by 256 `R32Uint` sparse - /// texture of 64-texel tiles with eight of its sixteen tiles mapped in a checkerboard: - /// `copyFromBuffer:toTexture:` over the whole level leaves every one of the 4,096 texels of - /// each mapped tile holding the copy's word and every texel of each unmapped tile at **zero**, - /// read back both by `copyFromTexture:toBuffer:` and by a kernel's `read()`, which agree tile - /// for tile. A second such copy after a tile is mapped writes it, so the first reading is not - /// a copy that did nothing. - /// - /// Where this scrub is **not** Metal: a tile mapped **after** a blit covered it while unmapped - /// reads Metal's unwritten pattern rather than zero, because Metal dropped the write and so - /// still holds the tile unwritten, while this call has already marked the blit's whole - /// destination written. `docs/FAST-PATHS.md`'s known gaps carries it with the measurement. - pub(super) fn scrub( - &mut self, - texture: &Texture, - written: Vec<(vk::ImageAspectFlags, Written)>, - ) -> Result<(), Error> { - FreshUnwritten::wrote(self.core().command_buffer(), texture, &written)?; - // A new `Private` texture one box of the command writes whole, every aspect: its batch - // may leave out its first move's zeros where the encoder reads none of it - // (`texture/first_move.rs`, `command_buffer/submit.rs`). - if let Some((key, [width, height], aspects)) = texture.overwritable() { - let whole = written.iter().any(|(wrote, texels)| { - wrote.contains(aspects) - && texels.level == 0 - && texels.layers == (0..1) - && texels.origin == [0, 0, 0] - && texels.size[0] >= width - && texels.size[1] >= height - && texels.size[2] >= 1 - }); - if whole { - let by = OverwriteBy::Blit; - self.core().overwrites(Overwrite { key, by }); - } - } - let written = || written.into_iter().map(|(_, texels)| texels).collect(); - match Scrub::of(texture, written) { - Some(scrub) => self.core().defer(Deferred::SparseScrub(Arc::new(scrub))), - None => Ok(()), - } - } - - /// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture: - /// destinationSlice:destinationLevel:destinationOrigin:`: a region of one texture into - /// another at `destination_origin`. - /// - /// The textures have one sample count and formats of one copy unit (macOS 26.7's rule: the - /// bytes are copied, `RGBA8Unorm` into `RGBA8Uint` or `R32Uint` among them, and - /// `Depth32Float` into `R32Float` or back), or a compressed format and an uncompressed one - /// whose texel is its block's bytes (BC1 and `RG32Uint`, BC7 and `RGBA32Uint`): each block - /// copies into one texel and back, and the origins and size are the destination's texels, the - /// source addressed as if it held the destination's format (our probe on an Apple M3 Max - /// under macOS 27.0.1: out of BC1 an origin of (4, 4) is the block from texel (16, 16); into - /// it an origin of (1, 2) and a size of 2 x 2 copy `RG32Uint` texel (0, 0) alone, into the - /// block a destination origin of (4, 4) names). - /// - /// A size of 0 copies as the module docs say, as plain Metal does, and a compressed region - /// off its blocks copies the blocks it starts in on each side, a whole block of a level - /// smaller than one included, into or out of a larger level too. Refused: what Metal stops - /// (`Invalid`: with a [`CopyProblem`], formats of different copy units, different sample - /// counts, a region past either level); a PVRTC format with an uncompressed one, whose blocks - /// plain Metal moves in an order of its own, and two compressed formats of one block's bytes - /// and different extents, not measured (`NotImplemented(Format)`); a copy between overlapping regions of one - /// multisampled texture (`NotImplemented(OverlappingTextureCopies)`), other than of a region - /// onto itself (one texture's other overlapping regions copy as `memmove` does, the module - /// docs); a copy through a scratch buffer of 24-bit depth, whose bytes Metal's reference GPUs - /// give no answer for (`NotImplemented(Format)`: an Apple M3 Max and an M4 make no - /// `Depth24Unorm_Stencil8` texture); a multisampled copy between a depth or stencil aspect and - /// a colour format, or between two depth/stencil formats, on a device without - /// `VK_KHR_maintenance8` or whose driver - /// copies such images wrong, where its sample-rate draws cannot copy it either: a 16-bit - /// depth, a source the draws cannot sample or a destination they cannot render to (`Unsupported`, - /// `Feature::Format`, naming maintenance8 or the defect); textures of another device - /// (`Invalid`). - pub fn copy_from_texture_to_texture( - &mut self, - source_texture: &Texture, - source_slice: u64, - source_level: u64, - source_origin: Origin, - source_size: Size, - destination_texture: &Texture, - destination_slice: u64, - destination_level: u64, - destination_origin: Origin, - ) -> Result<(), Error> { - self.logged( - |_| { - BlitCall::CopyTextureToTexture(Box::new(TextureToTexture { - source: source_texture.clone(), - source_slice, - source_level, - source_origin, - source_size, - destination: destination_texture.clone(), - destination_slice, - destination_level, - destination_origin, - })) - }, - |this| { - const CALL: &str = "copy_from_texture_to_texture"; - this.check_pair(CALL, source_texture, destination_texture)?; - if this.fails_on_memoryless(&[source_texture, destination_texture]) { - return Ok(()); - } - let types = [ - source_texture.texture_type(), - destination_texture.texture_type(), - ]; - let Some(size) = copy_size(source_size, &types) else { - return Ok(()); - }; - let source = region(CALL, source_origin, size, source_level, source_slice)?; - let at = region( - CALL, - destination_origin, - size, - destination_level, - destination_slice, - )?; - let copies = plan_region_copy( - &pair(source_texture, destination_texture)?, - &source, - at.level, - at.slice, - at.origin, - ) - .map_err(|refusal| copy_error(CALL, refusal))?; - this.texture_copies(CALL, source_texture, destination_texture, &copies) - }, - ) - } - - /// `copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel: - /// sliceCount:levelCount:`: `slice_count` slices of `level_count` levels, whole, each level - /// into a destination level. Levels of different sizes copy the copy units both levels hold, - /// from their origins, the rest of the larger one kept, as plain Metal copies them (an M4 - /// under macOS 27.0.1, and an Apple M3 Max under macOS 27.0.1 for the compressed formats; its - /// validation stops them): of a compressed format the blocks both levels hold, the block that - /// passes the smaller level's edge included. - /// - /// Refused as [`copy_from_texture_to_texture`](Self::copy_from_texture_to_texture) is, and - /// for levels or slices past either texture (`Invalid`), and between a compressed and an - /// uncompressed format (`NotImplemented(Format)`: which levels Metal pairs is not measured). - /// A count of 0 copies nothing, wherever its slices or levels lie, as plain Metal does. - pub fn copy_texture_slices( - &mut self, - source_texture: &Texture, - source_slice: u64, - source_level: u64, - destination_texture: &Texture, - destination_slice: u64, - destination_level: u64, - slice_count: u64, - level_count: u64, - ) -> Result<(), Error> { - self.logged( - |_| { - BlitCall::CopyTextureSlices(Box::new(( - source_texture.clone(), - source_slice, - source_level, - destination_texture.clone(), - destination_slice, - destination_level, - slice_count, - level_count, - ))) - }, - |this| { - const CALL: &str = "copy_texture_slices"; - this.check_pair(CALL, source_texture, destination_texture)?; - // No slices or levels copy nothing, of a memoryless texture too (plain Metal's - // command buffer completes, an M3 Max under macOS 27.0.1). - if slice_count == 0 || level_count == 0 { - return Ok(()); - } - if this.fails_on_memoryless(&[source_texture, destination_texture]) { - return Ok(()); - } - let n = |value: u64| { - u32::try_from(value) - .map_err(|_| invalid(CALL, Problem::Copy(CopyProblem::Region))) - }; - let copies = plan_levels_copy( - &pair(source_texture, destination_texture)?, - n(source_slice)?, - n(source_level)?, - n(destination_slice)?, - n(destination_level)?, - n(slice_count)?, - n(level_count)?, - ) - .map_err(|refusal| copy_error(CALL, refusal))?; - this.texture_copies(CALL, source_texture, destination_texture, &copies) - }, - ) - } - - /// `copyFromTexture:toTexture:`: every level and slice two textures share, as plain Metal - /// copies them: the levels paired by extent from the first pair of one extent (the source's - /// first and the destination's, or one's first and the other's first level of the other's - /// first extent), and the slices both have; a 2D texture into a 2D array copies its one - /// slice. - /// - /// The pairing shifts the textures' own extents, which their level counts do not bound, so - /// two textures of one level each whose extents pair only at a shift copy no level at all, as - /// plain Metal copies them. - /// - /// Refused as [`copy_texture_slices`](Self::copy_texture_slices) is, and for textures whose - /// extents pair at no level (`Invalid`: plain Metal aborts) or whose paired level lies past - /// one texture's own levels (`Invalid`: plain Metal reads or writes a level it does not - /// hold). - pub fn copy_texture( - &mut self, - source_texture: &Texture, - destination_texture: &Texture, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::CopyTexture(source_texture.clone(), destination_texture.clone()), - |this| { - const CALL: &str = "copy_texture"; - this.check_pair(CALL, source_texture, destination_texture)?; - if this.fails_on_memoryless(&[source_texture, destination_texture]) { - return Ok(()); - } - let copies = plan_whole_copy(&pair(source_texture, destination_texture)?) - .map_err(|refusal| copy_error(CALL, refusal))?; - this.texture_copies(CALL, source_texture, destination_texture, &copies) - }, - ) - } - - /// The checks every copy between two textures makes first. - fn check_pair( - &mut self, - call: &'static str, - source: &Texture, - destination: &Texture, - ) -> Result<(), Error> { - self.check_texture(call, source)?; - self.check_texture(call, destination)?; - source.check_plane_copied()?; - destination.check_plane_copied()?; - source.check_rotated_reach()?; - destination.check_rotated_reach()?; - check_depth_view(source)?; - check_depth_view(destination) - } - - /// Record checked copies between two textures. `copies` run between the images [`pair`] - /// presents, each in its texture's aspect. The image holding the destination's texels - /// ([`held`]) takes them from the source's image where Vulkan copies them into it (colour into - /// colour, a depth or stencil aspect into the same aspect of the same format, regions of one - /// size), else through a scratch buffer of the encoder. - pub(super) fn texture_copies( - &mut self, - call: &'static str, - source: &Texture, - destination: &Texture, - copies: &[ImageCopyRegion], - ) -> Result<(), Error> { - // A BC destination's columns past its texels in place take no write (an IOSurface - // plane's rows of blocks wider than the plane's, `Texture::columns_in_place`): each copy - // reads and writes the rest alone, as the x86 Macs' blits do. - let clipped: Vec; - let copies = match destination.columns_in_place() { - Some(columns) => { - clipped = copies - .iter() - .filter_map(|copy| written_columns(copy, columns)) - .collect(); - &clipped[..] - } - None => copies, - }; - if copies.is_empty() { - return Ok(()); - } - self.texture_copies_of_bytes(call, source, destination, copies)?; - // Into a texture with a decoded twin: the twin's texels of what the copies wrote. - let written: Vec = copies.iter().map(|copy| copy.dst).collect(); - self.decode_twin(destination, &written)?; - // Out of or into a texture Metal keeps compressed: Metal's encoding of what the copies - // wrote, where the destination holds its texels in an image of the format or at their - // rows in a buffer's bytes; else the device's copy keeps the bytes. - let canonical = - compressed_blit::canonical(source) || compressed_blit::canonical(destination); - if canonical { - let rewritten = match compressed_blit::holds_canonical(destination) { - true => self.canonical_texels(destination, &written)?, - false => self.canonical_texel_words(destination, copies)?, - }; - if rewritten { - return Ok(()); - } - } - degrade_compressed_blit(call, source)?; - degrade_compressed_blit(call, destination) - } - - /// Record checked copies between two textures, their bytes as the images hold them. - fn texture_copies_of_bytes( - &mut self, - call: &'static str, - source: &Texture, - destination: &Texture, - copies: &[ImageCopyRegion], - ) -> Result<(), Error> { - if source.blit_texels().is_some() || destination.blit_texels().is_some() { - // A two-plane extended-range texture over a surface's planes (the plan paired it with - // another): its bytes as Metal's blit moves them, else refused. - if two_planes::holds_planes(source.pixel_format()) { - return match self.modelled_plane_copies(source, destination, copies)? { - true => Ok(()), - false => Err(internal("a surface's two-plane copy left unmodelled")), - }; - } - return self.texel_copies(call, source, destination, copies); - } - // Two two-plane extended-range textures: their bytes moved as Metal's blit moves them, - // where that was measured; else (announced) both words of each texel, below, a 3D one's - // at its first depth slice, where its texels lie (`two_planes.rs`). - if two_planes::holds_planes(source.pixel_format()) - && self.modelled_plane_copies(source, destination, copies)? - { - return Ok(()); - } - let first_slices: Vec; - let copies = match two_planes::holds_planes(source.pixel_format()) - && [source, destination] - .iter() - .any(|t| t.texture_type() == TextureType::Type3D) - { - true => { - first_slices = copies.iter().map(two_planes::first_slices).collect(); - &first_slices[..] - } - false => copies, - }; - // A region copied onto itself keeps its texels in whatever order Metal copies them - // (probes): nothing is recorded for it. Between other overlapping regions of one texture - // Metal's copy races past a few hundred texels across (probes 7 and 7b). Such a copy goes - // through the scratch buffer below, every source region read before any destination region - // is written: `memmove`'s answer, Metal's for small regions, announced once. A multisampled - // image goes into no buffer: still refused. - let one_storage = source.same_storage(destination); - let overlap = one_storage - && copies.iter().enumerate().any(|(i, a)| { - copies - .iter() - .enumerate() - .any(|(j, b)| regions_meet(&a.src, &b.dst) && !(i == j && a.src == a.dst)) - }); - if overlap && source.record().samples > 1 { - return Err(Error::NotImplemented(RuntimeGap::OverlappingTextureCopies)); - } - let copies: Vec = copies - .iter() - .filter(|copy| !(one_storage && copy.src == copy.dst)) - .copied() - .collect(); - let Some(first) = copies.first() else { - return Ok(()); - }; - let mut uses = Vec::with_capacity(2 * copies.len()); - for copy in &copies { - let (levels, layers) = subresources(©.src); - uses.push(source.image_use(levels, layers, read(), false)?); - let (levels, layers) = subresources(©.dst); - uses.push(destination.image_use(levels, layers, write(), true)?); - } - // The source's regions alone are read (`fresh_unwritten.rs`). - let boxes: Vec<_> = (copies.iter()) - .map(|copy| (copy.src.aspect.into(), Written::of(©.src))) - .collect(); - let fresh_reads = FreshUnwritten::reads(self.core().device(), source, &boxes)?; - // The destination's image takes the regions from the source's where Vulkan copies them - // into it, else through a scratch buffer from the source's texels. - let from = held(source, first.src.aspect)?; - let into = held(destination, first.dst.aspect)?; - let mut direct = Vec::with_capacity(1); - let mut staged = Vec::new(); - // The regions in each image's texels: a 2-bit PVRTC texture's carrier halves them across - // (`pvrtc::image_region`). - let (source_plan, destination_plan) = (source.image_plan()?, destination.image_plan()?); - let in_images: Vec = copies - .iter() - .map(|copy| ImageCopyRegion { - src: image_region(source_plan, copy.src), - dst: image_region(destination_plan, copy.dst), - }) - .collect(); - // A pair of regions of different sizes (a compressed region that ends at its level's edge - // inside a block on one side only, `ImageCopyRegion`) has no one Vulkan extent: it goes - // through the scratch buffer too, which holds the blocks both cover. - let one_extent = in_images.iter().all(|copy| copy.src.size == copy.dst.size); - let samples = source.record().samples; - let mut bits = Vec::new(); - let to = into; - match Some(&from).filter(|from| from.copies_into(&to) && !overlap && one_extent) { - Some(from) => { - let mut regions: Vec = in_images - .iter() - .map(|copy| from.region(&to, copy)) - .collect(); - // Into a multisampled float image whose NaNs the device's copy converts: - // the regions at one origin in both images by the sample planes' copies, - // which move every sample's bits; the rest, or all where those cannot run, - // copied by the device and announced. - let device = self.core().device().clone(); - if nan_clear::converting_copy(&device, to.format, samples) { - let (exact, rest): (Vec<&ImageCopyRegion>, Vec<&ImageCopyRegion>) = regions - .iter() - .partition(|copy| copy.src.origin == copy.dst.origin); - let pairs: Vec<(ImageRegion, ImageRegion)> = - exact.iter().map(|copy| (copy.src, copy.dst)).collect(); - if let Some(copy) = sample_planes::BitsCopy::plan( - self.core().command_buffer(), - source, - destination, - to.format, - &pairs, - samples, - )? { - bits.push(copy); - regions = rest.into_iter().copied().collect(); - } - if !regions.is_empty() { - nan_clear::degrade_converting_copy(&device, to.format, samples, || { - format!( - "a blit copy into a multisampled {:?} texture", - destination.pixel_format() - ) - }); - } - } - if !regions.is_empty() { - let regions: Vec = regions.iter().map(image_copy).collect(); - direct.push((from.image, to.image, regions)); - // A depth that may hold a negative value or a NaN, copied as it is. - if to.aspect == ImageAspectFlags::DEPTH { - destination.degrade_signed_depth(call); - } - } - } - None => staged.push(to), - } - for copy in &bits { - self.command_in_reading( - sample_planes::BITS_COPY_STAGES, - ©.uses, - (&fresh_reads, &[]), - |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // images and the copy's planes and objects are live until it completes - // (retained below). - unsafe { copy.record(device, raw) }; - }, - )?; - } - if !bits.is_empty() { - self.core().retain(bits); - } - // Multisampled images, which Vulkan copies into no buffer, copy through colour images - // of their samples instead, by copies or by draws (`sample_copy.rs`). - if samples > 1 && !staged.is_empty() { - let side = |texture, held: &Held| sample_copy::Side { - texture, - image: held.image, - aspect: held.aspect, - format: held.format, - }; - let mut planned = Vec::with_capacity(staged.len()); - let mut stages = TRANSFER; - for to in &staged { - let regions: Vec<(ImageRegion, ImageRegion)> = in_images - .iter() - .map(|copy| { - let copy = from.region(to, copy); - (copy.src, copy.dst) - }) - .collect(); - let copy = sample_copy::plan( - self.core().command_buffer(), - ®ions, - side(source, &from), - side(destination, to), - samples, - )?; - uses.extend(copy.uses.iter().cloned()); - stages |= copy.stages; - destination.degrade_depth_upload(call, to.aspect, true); - destination.degrade_depth_denormals(call, to.aspect, false); - planned.push(copy); - } - self.command_in_reading(stages, &uses, (&fresh_reads, &[]), |device, raw| { - for (from, to, regions) in &direct { - // SAFETY: the encoder's command buffer is recording; the images are live and - // retained until it completes, in the `GENERAL` layout, and the regions lie - // in both (checked by the plan). - unsafe { - device.cmd_copy_image( - raw, - *from, - vk::ImageLayout::GENERAL, - *to, - vk::ImageLayout::GENERAL, - regions, - ); - } - } - for copy in &planned { - // SAFETY: the encoder's command buffer is recording outside a render pass; - // the images and what the copies go through are live until it completes - // (retained below), in `GENERAL`, and `sample_copy::plan` checked the rest. - unsafe { copy.record(device, raw) }; - } - })?; - for copy in &planned { - copy.announce(self.core().device(), call, destination); - } - self.core().retain(planned); - self.core().retain_shared(source.held()); - if source != destination { - self.core().retain_shared(destination.held()); - } - let written = (copies.iter()) - .map(|copy| (copy.dst.aspect.into(), Written::of(©.dst))) - .collect(); - return self.scrub(destination, written); - } - let staging = match staged.is_empty() { - true => None, - false => Some( - through_buffer( - &in_images, - &from, - image_block_extent(from.format, source.pixel_format()).unwrap_or([1, 1]), - &staged, - ) - .map_err(|refusal| copy_error(call, refusal))?, - ), - }; - let scratch = match &staging { - Some(staging) => { - let length = staging.length; - let scratch = self - .core() - .device() - .own_buffer(length, ResourceOptions::private())?; - let (through, _) = scratch.at(0); - let mut reads_source = Vec::with_capacity(copies.len() + 1); - for copy in &copies { - let (levels, layers) = subresources(©.src); - reads_source.push(source.image_use(levels, layers, read(), false)?); - } - reads_source.push(writes(&scratch, 0..length)); - let (image, out_of) = (from.image, &staging.out_of); - self.command_reading(&reads_source, (&fresh_reads, &[]), |device, raw| { - // SAFETY: the encoder's command buffer is recording; the image and the - // scratch buffer are live and retained until it completes, the image is in - // the `GENERAL` layout, and the regions lie in both. - unsafe { - device.cmd_copy_image_to_buffer( - raw, - image, - vk::ImageLayout::GENERAL, - through, - out_of, - ); - } - })?; - uses.push(reads(&scratch, 0..length)); - for (to, regions) in &staging.into { - destination.degrade_depth_upload(call, to.aspect, true); - destination.degrade_depth_denormals(call, to.aspect, false); - // A depth the scratch takes from a colour texture's texels, which may lie - // outside [0, 1], clamped first where the image may store one so - // (`depth_clamp.rs`). - if depth_clamp::clamps_depth(self.core().device(), to.format, to.aspect) { - self.clamp_depths(&scratch, regions)?; - } - } - Some((scratch, through)) - } - None => None, - }; - // The copies write every texel of their regions. - let mut covered = Vec::new(); - for (_, to, regions) in &direct { - covered.extend(Covered::into_image_from_image(*to, regions)); - } - for (to, regions) in staging.iter().flat_map(|staging| &staging.into) { - covered.extend(Covered::into_image(to.image, regions)); - } - self.command_reading(&uses, (&fresh_reads, &covered), |device, raw| { - // SAFETY: the encoder's command buffer is recording; the images (and the scratch - // buffer) are live and retained until it completes, in the `GENERAL` layout, the - // regions lie in both (checked by the plan), and regions of one image do not overlap. - unsafe { - for (from, to, regions) in &direct { - device.cmd_copy_image( - raw, - *from, - vk::ImageLayout::GENERAL, - *to, - vk::ImageLayout::GENERAL, - regions, - ); - } - if let (Some((_, through)), Some(staging)) = (&scratch, &staging) { - for (to, regions) in &staging.into { - device.cmd_copy_buffer_to_image( - raw, - *through, - to.image, - vk::ImageLayout::GENERAL, - regions, - ); - } - } - } - })?; - if let Some((scratch, ..)) = scratch { - self.core().retain(scratch); - } - self.core().retain_shared(source.held()); - if source != destination { - self.core().retain_shared(destination.held()); - } - if overlap { - let texels: u64 = copies - .iter() - .map(|copy| { - let [w, h, d] = copy.src.size; - u64::from(w) * u64::from(h) * u64::from(d) * u64::from(copy.src.layers) - }) - .sum(); - let format = destination.pixel_format(); - self.core() - .device() - .degrade(Degradation::OverlappingTextureCopyAsMemmove, || { - ( - format!( - "{call} of {texels} texels between overlapping regions of one \ - {format:?} texture" - ), - "Metal's copy reads as memmove's for regions up to a few hundred \ - texels and races past that; the runtime gives memmove's answer" - .to_owned(), - ) - }); - } - let written = (copies.iter()) - .map(|copy| (copy.dst.aspect.into(), Written::of(©.dst))) - .collect(); - self.scrub(destination, written) - } - - /// Record checked copies between two textures of which one or both are over buffers, on the - /// buffers' bytes (the module's note): rows between two textures over buffers, else a - /// buffer-image copy of each slice between the bytes and the other texture's image, as - /// `copy_from_buffer_to_texture` and `copy_from_texture_to_buffer` record one. - fn texel_copies( - &mut self, - call: &'static str, - source: &Texture, - destination: &Texture, - copies: &[ImageCopyRegion], - ) -> Result<(), Error> { - let copy_problem = |problem| invalid(call, Problem::Copy(problem)); - match (source.blit_texels(), destination.blit_texels()) { - (Some(from), Some(to)) => { - let unit = from.unit(); - // Rows that share bytes are refused, on either side - // (`plan_texels_rows_copy`): Metal leaves them from whichever row its own - // command wrote last, which no one order of a row copy reproduces. - let copy = - plan_texels_rows_copy(from.row_layouts(), to.row_layouts(), &unit, copies) - .map_err(Error::NotImplemented)?; - self.texels_rows_copy((&from.buffer, from.past()), (&to.buffer, to.past()), ©) - } - (Some(texels), None) | (None, Some(texels)) => { - // Rows that share bytes are no layout a buffer-image copy states: an IOSurface - // plane's on Metal's GPU, which only its shadow's two regions each way hold, and - // which Metal leaves from whichever row its own command wrote last - // (`linear_plan.rs`'s **Rows that overlap**). - if texels.plane_rows_overlap() { - return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)); - } - let into_texture = source.blit_texels().is_some(); - let texture = if into_texture { destination } else { source }; - let record = texture.record(); - let (unit, buffer) = (texels.unit(), &texels.buffer); - // The image's own unit: of one size, in its aspect (a depth or stencil format's). - let image_unit = self::unit(call, texture, BlitOption::None)?; - for copy in copies { - let (bytes, image) = if into_texture { - (©.src, ©.dst) - } else { - (©.dst, ©.src) - }; - for layer in 0..image.layers { - let region = TextureRegion { - level: image.level - record.base_level, - slice: image.layer + layer - record.base_layer, - origin: image.origin, - size: image.size, - }; - let layout = - texel_layout(&texels.layout, &unit, bytes, bytes.layer + layer); - // Texels past those kept in the buffer lie in its tail: the rows go - // through a scratch buffer of the encoder, as rows of the bytes they lie - // in. - if let Some(past) = texels.past() { - let [width, height, _] = bytes.size; - let row = u64::from(width) * u64::from(unit.bytes); - let rows: Vec> = (0..u64::from(height)) - .map(|y| layout.offset + y * layout.bytes_per_row) - .map(|start| start..start + row) - .collect(); - let packed: Vec> = (0..u64::from(height)) - .map(|y| y * row..(y + 1) * row) - .collect(); - let scratch = (self.core().device()) - .own_buffer(row * u64::from(height), ResourceOptions::private())?; - let through = BufferLayout { - offset: 0, - bytes_per_row: row, - bytes_per_image: 0, - }; - let plan = plan_buffer_copy( - record, - ®ion, - &image_unit, - &through, - scratch.length(), - scratch.start(), - into_texture, - ) - .map_err(copy_problem)?; - if into_texture { - let copy = RowsCopy::new(&rows, &packed); - self.texels_rows_copy( - (buffer, Some(past)), - (&scratch, None), - ©, - )?; - texture.degrade_depth_upload(call, image_unit.aspect, true); - texture.degrade_depth_denormals(call, image_unit.aspect, false); - self.buffer_texture_copy(&scratch, texture, plan, true)?; - } else { - self.buffer_texture_copy(&scratch, texture, plan, false)?; - let copy = RowsCopy::new(&packed, &rows); - self.texels_rows_copy( - (&scratch, None), - (buffer, Some(past)), - ©, - )?; - } - self.core().retain(scratch); - continue; - } - let plan = plan_buffer_copy( - record, - ®ion, - &image_unit, - &layout, - texels.kept(), - buffer.start(), - into_texture, - ) - .map_err(copy_problem)?; - if into_texture { - texture.degrade_depth_upload(call, image_unit.aspect, true); - texture.degrade_depth_denormals(call, image_unit.aspect, false); - } - self.buffer_texture_copy(buffer, texture, plan, into_texture)?; - } - } - Ok(()) - } - (None, None) => Err(internal("texel copies between two images")), - } - } - - /// Record `copy` from `source`'s bytes into `destination`'s, as [`rows_copy`](Self::rows_copy) - /// does, where a side's bytes past those kept in its buffer lie in a texture's tail (`past`, - /// `buffer_texture.rs`): the rows cut there, each part from and into the bytes it lies in, - /// its uses those of the buffer's bytes it stands for. - fn texels_rows_copy( - &mut self, - (source, src_past): (&Buffer, Option>), - (destination, dst_past): (&Buffer, Option>), - copy: &RowsCopy, - ) -> Result<(), Error> { - if src_past.is_none() && dst_past.is_none() { - return self.rows_copy(RowsSide::of(source), RowsSide::of(destination), copy); - } - let cuts = (src_past.map(|p| p.length), dst_past.map(|p| p.length)); - for (src_beyond, dst_beyond, part) in copy.split(cuts.0, cuts.1) { - let (from, to) = ( - RowsSide::cut(source, src_past.filter(|_| src_beyond)), - RowsSide::cut(destination, dst_past.filter(|_| dst_beyond)), - ); - self.rows_copy(from, to, &part)?; - let tails = [ - src_past.filter(|_| src_beyond), - dst_past.filter(|_| dst_beyond), - ]; - for past in tails.into_iter().flatten() { - self.core().retain(past.tail.clone()); - } - } - Ok(()) - } - - /// Record `copy` from `source`'s bytes into `destination`'s, a copy that names a texture - /// over a buffer (the module's note): its rows in one command, or, where a source row and a - /// destination row of one buffer share bytes, through a scratch buffer of the encoder, the - /// whole source read before any of it is written, as Metal moves them. - fn rows_copy( - &mut self, - source: RowsSide<'_>, - destination: RowsSide<'_>, - copy: &RowsCopy, - ) -> Result<(), Error> { - // Read as a blit's (`host_residency.rs`): the command buffer holds the imports. A side's - // rows in a texture's tail lie `rebase` bytes before their place in the buffer's space. - let (src, src_base) = self.core().blit_at(source.bytes, 0)?; - let (dst, dst_base) = self.core().blit_at(destination.bytes, 0)?; - let (src_rebase, dst_rebase) = (source.rebase, destination.rebase); - let (source, destination) = (source.uses, destination.uses); - let device = self.core().device().clone(); - // One buffer's bytes, or two no-copy buffers' made over the same bytes, which lie in one - // import (`host_aliases.rs`): one `VkBuffer` from one byte 0. - if (src, src_base) == (dst, dst_base) && copy.meets() { - let length = copy.length(); - let scratch = self - .core() - .device() - .own_buffer(length, ResourceOptions::private())?; - let (through, through_base) = scratch.at(0); - let (mut into, mut out_of) = (Vec::new(), Vec::new()); - let mut packed = through_base; - for row in ©.rows { - into.push(vk::BufferCopy { - src_offset: src_base + row.src - src_rebase, - dst_offset: packed, - size: row.size, - }); - out_of.push(vk::BufferCopy { - src_offset: packed, - dst_offset: dst_base + row.dst - dst_rebase, - size: row.size, - }); - packed += row.size; - } - let into = RowCopies::new(&device, src, through, into); - let uses = [ - reads_by(source, copy.src_span.clone(), into.read()), - writes_by(&scratch, 0..length, into.write()), - ]; - self.command_in(into.stages(), &uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording; the buffers are live and - // retained until it completes, the rows lie inside them, and the scratch buffer - // is another buffer. - unsafe { into.record(device, raw) }; - })?; - let out_of = RowCopies::new(&device, through, dst, out_of); - let uses = [ - reads_by(&scratch, 0..length, out_of.read()), - writes_by(destination, copy.dst_span.clone(), out_of.write()), - ]; - self.command_in(out_of.stages(), &uses, |device, raw| { - // SAFETY: as above. - unsafe { out_of.record(device, raw) }; - })?; - for sets in [into.retained(), out_of.retained()].into_iter().flatten() { - self.core().retain(sets); - } - self.core().retain(scratch); - let (from, to) = (copy.src_span.clone(), copy.dst_span.clone()); - self.core() - .device() - .degrade(Degradation::OverlappingTexelCopy, || { - let object = format!( - "a copy of texel rows from bytes {from:?} to bytes {to:?} of one buffer" - ); - let reason = "a source row and a destination row share bytes, which Vulkan's \ - copy forbids"; - (object, reason.to_owned()) - }); - } else { - let regions: Vec = copy - .rows - .iter() - .map(|row| vk::BufferCopy { - src_offset: src_base + row.src - src_rebase, - dst_offset: dst_base + row.dst - dst_rebase, - size: row.size, - }) - .collect(); - let rows = RowCopies::new(&device, src, dst, regions); - let uses = [ - reads_by(source, copy.src_span.clone(), rows.read()), - writes_by(destination, copy.dst_span.clone(), rows.write()), - ]; - self.command_in(rows.stages(), &uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording; the buffers are live and - // retained until it completes, the rows lie inside them, the destination rows are - // disjoint (`RowsCopy::new`), and in one buffer no source row meets a destination - // row. - unsafe { rows.record(device, raw) }; - })?; - if let Some(sets) = rows.retained() { - self.core().retain(sets); - } - } - Ok(()) - } - - /// `generateMipmapsForTexture:`: each level after the texture's first from the one above it, - /// by bilinear (in 3D, trilinear) filtering at the scaled texel centres; every slice of an - /// array or cube texture, and on a view its own levels and slices. - /// - /// The device's filter, not Apple's: the device's blit chain (`vkCmdBlitImage` with - /// `VK_FILTER_LINEAR`, one blit a level) for every format its blits filter, and for the others - /// (an extended-range format, an 8-bit sRGB texture the device holds as its UNORM twin, a - /// format without blits or linear filtering) the runtime's compute filter in `float`: a - /// scratch buffer of the levels, one compute dispatch per level, and copies in and out - /// (`mipmap_filter.rs`). Neither gives Metal's bytes exactly, which also differ between - /// Apple's GPUs; announced once per device (`device-filtered-mipmaps`). - /// - /// An integer format, which Metal's API validation stops, takes plain Metal's answer exactly, - /// on every device (an M4 under macOS 27.0.1): each level's texel `i` is the level above's - /// texel `floor((2i + 1) W / 2w)` on each axis (`W` and `w` the two levels' sizes on it), - /// copied as its bytes through a scratch buffer. - /// - /// A texture or view of one level (every texture over a buffer has one), of any format, and - /// a depth or stencil texture of any levels, are left as they are, as Metal's plain call - /// leaves them; Metal's API validation asserts on them. - /// - /// Refused: what Metal stops with no defined answer (`Invalid` with a - /// [`MipmapProblem`](super::MipmapProblem): a compressed format); a format neither the - /// device's blits filter nor the compute filter takes (`Unsupported`, naming the format's - /// linear filter where the device lacks it); a YCbCr or RGBX format, a view of another format - /// than its texture (of another texel size, for an integer format), a texture whose image - /// takes no transfers, and a chain whose scratch buffer or dispatches pass the device's limits - /// (`Unsupported`, `NotImplemented` for `MipmapGeneration`); a texture of another device - /// (`Invalid`). - pub fn generate_mipmaps(&mut self, texture: &Texture) -> Result<(), Error> { - self.logged( - |_| BlitCall::GenerateMipmaps(texture.clone()), - |this| { - // A view that reads its image in the image's own format generates them as a texture - // of that format over the same levels: the same bits, filtered alike (a filter - // takes each channel alone, and `metal::format::swizzle_over` pairs formats of the - // same channels). - match texture.bound_twin()? { - Some(twin) => this.mipmaps(&twin), - None => this.mipmaps(texture), - } - }, - ) - } - - /// [`generate_mipmaps`](Self::generate_mipmaps) of `texture`, logged. - fn mipmaps(&mut self, texture: &Texture) -> Result<(), Error> { - const CALL: &str = "generate_mipmaps"; - // One level, of any format, or a depth or stencil texture: Metal's plain call leaves the - // texture as it is, over a buffer or not, and its API validation asserts. Every texture - // over a buffer has one level but a tiled one, which is an image to a blit, its own copy - // of the bytes (`Texture::blit_texels`). - self.core().check_device(CALL, texture.generation())?; - texture.check_rotated_reach()?; - let record = texture.record(); - let gap = || Error::Unsupported(Unsupported::not_implemented(Feature::MipmapGeneration)); - // A texture of one level, of an extended-range format too: left as it is, a memoryless - // one too (plain Metal's command buffer completes, an M3 Max under macOS 27.0.1). - if leaves_as_is(record) { - return Ok(()); - } - self.check_texture(CALL, texture)?; - texture.check_plane_copied()?; - if self.fails_on_memoryless(&[texture]) { - return Ok(()); - } - let device = self.core().device().clone(); - let facts = device - .shared() - .textures - .facts(device.compile_device().profile()); - let defects = &device.properties().driver_defects; - let blits = match plan_mipmaps(texture.record(), texture.image_plan()?, &facts, defects) { - // An integer format: plain Metal picks texels, which copies give exactly - // (`mipmap_pick.rs`). - Ok(MipmapPlan::Picks(picks)) => { - return self.pick_mipmaps(texture, &picks, read(), write()); - } - // A format the device's blits cannot filter: the compute filter (`mipmap_filter.rs`). - Ok(MipmapPlan::Filter) => { - if !self.filter_mipmaps(texture, &facts, read(), write())? { - return Err(gap()); - } - announce_mipmaps(&device, record, "the runtime's compute filter"); - return Ok(()); - } - Ok(MipmapPlan::Blits(blits)) => blits, - Err(MipmapRefusal::Invalid(problem)) => { - return Err(invalid(CALL, Problem::Mipmap(problem))); - } - Err(MipmapRefusal::Unsupported(unsupported)) => { - return Err(Error::Unsupported(unsupported)) - } - }; - let (image, aspects) = (texture.raw_image()?, texture_aspects(texture.image_plan()?)); - device.shared().counts.pool_compiled( - crate::work_counts::PoolCompiled::ImageBlit, - blits.len() as u64, - ); - for blit in &blits { - let layers = blit.base_layer..blit.base_layer + blit.layers; - let uses = [ - texture.image_use( - blit.src_level..blit.src_level + 1, - layers.clone(), - read(), - false, - )?, - texture.image_use(blit.dst_level..blit.dst_level + 1, layers, write(), true)?, - ]; - self.command(&uses, |device, raw| { - record_blit(device, raw, image, aspects, blit); - })?; - } - self.core().retain_shared(texture.held()); - let written = blits - .iter() - .map(|blit| { - let written = Written { - level: blit.dst_level, - layers: blit.base_layer..blit.base_layer + blit.layers, - origin: [0; 3], - size: blit.dst_extent, - }; - (aspects, written) - }) - .collect(); - self.scrub(texture, written)?; - announce_mipmaps(&device, record, "the device's blit chain"); - Ok(()) - } - - /// Metal's check of a level and slice of `texture` named by a hint or a synchronization. - fn check_level_slice( - &mut self, - call: &'static str, - texture: &Texture, - slice: u64, - level: u64, - ) -> Result<(), Error> { - self.check_texture(call, texture)?; - check_slice_level(call, texture, slice, level) - } - - /// `synchronizeTexture:slice:level:`: the CPU sees the GPU's writes to a level and slice of a - /// `Managed` texture once the command buffer completes. Every command buffer ends with a - /// barrier to the host, and a texture of an image alone copies from its image at each CPU - /// access, so for one nothing more is recorded. A texture over a buffer's bytes, on a device - /// without unified memory, where a `Managed` buffer is two copies (`managed.rs`), has those - /// bytes copied to the buffer's host copy, which its `get_bytes` and the buffer's `contents` - /// read, after the encoder's earlier commands, as - /// [`synchronize_resource`](Self::synchronize_resource) of the texture copies them: every - /// slice's, where it has more than the one asked. A level that lies in its image alone (a - /// tiled texture's past its first, `Buffer::new_tiled_texture`) copies nothing. On a texture - /// of another storage mode it records nothing, whatever the level, as plain Metal does - /// (`Shared` and `Private` textures, level 0 and a level past the texture; Metal's validation - /// stops it). - /// - /// Refused (`Invalid`): a managed texture's slice or level past the texture; a texture of - /// another device. - pub fn synchronize_texture( - &mut self, - texture: &Texture, - slice: u64, - level: u64, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::SynchronizeTexture(texture.clone(), slice, level), - |this| { - const CALL: &str = "synchronize_texture"; - this.check_texture(CALL, texture)?; - if texture.storage_mode() != StorageMode::Managed { - return Ok(()); - } - check_slice_level(CALL, texture, slice, level)?; - if texture.level_in_image(level) { - return Ok(()); - } - this.synchronize_texels(texture) - }, - ) - } - - /// `optimizeContentsForGPUAccess:`: a hint; Vulkan images keep one layout for every access - /// here, so it records nothing. Refused (`Invalid`) for a texture of another device. - pub fn optimize_contents_for_gpu_access(&mut self, texture: &Texture) -> Result<(), Error> { - self.logged( - |_| BlitCall::OptimizeForGpu(texture.clone()), - |this| this.check_texture("optimize_contents_for_gpu_access", texture), - ) - } - - /// `optimizeContentsForGPUAccess:slice:level:`: as - /// [`optimize_contents_for_gpu_access`](Self::optimize_contents_for_gpu_access), and refused - /// (`Invalid`) for a slice or level past the texture. - pub fn optimize_contents_for_gpu_access_slice_level( - &mut self, - texture: &Texture, - slice: u64, - level: u64, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::OptimizeForGpuSliceLevel(texture.clone(), slice, level), - |this| { - const CALL: &str = "optimize_contents_for_gpu_access_slice_level"; - this.check_level_slice(CALL, texture, slice, level) - }, - ) - } - - /// `optimizeContentsForCPUAccess:`: a hint; it records nothing. Refused (`Invalid`) for a - /// texture of another device. - pub fn optimize_contents_for_cpu_access(&mut self, texture: &Texture) -> Result<(), Error> { - self.logged( - |_| BlitCall::OptimizeForCpu(texture.clone()), - |this| this.check_texture("optimize_contents_for_cpu_access", texture), - ) - } - - /// `optimizeContentsForCPUAccess:slice:level:`: as - /// [`optimize_contents_for_cpu_access`](Self::optimize_contents_for_cpu_access), and refused - /// (`Invalid`) for a slice or level past the texture. - pub fn optimize_contents_for_cpu_access_slice_level( - &mut self, - texture: &Texture, - slice: u64, - level: u64, - ) -> Result<(), Error> { - self.logged( - |_| BlitCall::OptimizeForCpuSliceLevel(texture.clone(), slice, level), - |this| { - const CALL: &str = "optimize_contents_for_cpu_access_slice_level"; - this.check_level_slice(CALL, texture, slice, level) - }, - ) - } -} - -/// Refuse (`Invalid`) a slice or level `call` names past `texture`'s. -pub(super) fn check_slice_level( - call: &'static str, - texture: &Texture, - slice: u64, - level: u64, -) -> Result<(), Error> { - let record = texture.record(); - if slice >= u64::from(record.layer_count) || level >= u64::from(record.level_count) { - return Err(invalid(call, Problem::Copy(CopyProblem::Region))); - } - Ok(()) -} - -/// The plan's view of two textures: a texture by its image's plan, a texture buffer by none. -fn pair<'a>(source: &'a Texture, destination: &'a Texture) -> Result, Error> { - let image = |texture: &'a Texture| match texture.texels() { - Some(_) => Ok(None), - None => texture.image_plan().map(Some), - }; - Ok(CopyPair { - src: source.record(), - src_image: image(source)?, - dst: destination.record(), - dst_image: image(destination)?, - }) -} - -/// An image holding a texture's texels for a copy between textures: the image, the aspect the -/// texels are in, and its Vulkan format. -#[derive(Clone, Copy, Debug)] -struct Held { - image: vk::Image, - aspect: ImageAspectFlags, - format: Format, -} - -impl Held { - /// Whether Vulkan copies this image's texels into `to`'s: both in colour (formats of one - /// size, checked by the plan, both alpha formats or neither, `image_plan::copies_between`: - /// an `A8Unorm` view's image is its `R8Unorm` texture's), or in the same depth or stencil - /// aspects of one format. - fn copies_into(&self, to: &Held) -> bool { - self.aspect == to.aspect - && match self.aspect == ImageAspectFlags::COLOR { - true => copies_between(self.format, to.format), - false => self.format == to.format, - } - } - - /// `copy` from this image to `to`, each in its aspect. - fn region(&self, to: &Held, copy: &ImageCopyRegion) -> ImageCopyRegion { - ImageCopyRegion { - src: ImageRegion { - aspect: self.aspect, - ..copy.src - }, - dst: ImageRegion { - aspect: to.aspect, - ..copy.dst - }, - } - } - - /// The bytes of a texel of this image in a buffer, where they are Metal's copy unit: a - /// colour format's texel, 32-bit float or 16-bit normalized depth, a stencil byte. - fn texel_bytes(&self) -> Option { - if self.aspect == ImageAspectFlags::COLOR { - self.format.block().map(|block| block.size) - } else if self.aspect == ImageAspectFlags::DEPTH { - depth_bytes(self.format) - } else if self.aspect == ImageAspectFlags::STENCIL { - Some(1) - } else { - None - } - } -} - -/// The image holding `texture`'s texels, in `aspect`. -fn held(texture: &Texture, aspect: ImageAspectFlags) -> Result { - Ok(Held { - image: texture.raw_image()?, - aspect, - format: texture.image_plan()?.format, - }) -} - -/// A copy between textures through a scratch buffer of the encoder: the buffer's length, the -/// regions from the source's image into it, tightly packed one after another, and from it into -/// each image that takes them. -struct Staging { - length: u64, - out_of: Vec, - into: Vec<(Held, Vec)>, -} - -/// `copies` from `from` into each of `into` through a scratch buffer: Vulkan copies a depth or -/// stencil aspect only into the same aspect of the same format, so the bytes go out of the -/// source and back into each destination image by buffer copies, which carry Metal's copy units -/// as Vulkan lays them out in a buffer; and a compressed pair of regions of different sizes, which -/// no one extent states, goes the same way, the blocks both cover out of one and into the other. -/// `block` is the texel extent of `from`'s blocks ([`image_block_extent`]; 1 x 1 uncompressed), -/// each a texel's bytes in the buffer. Single-sampled textures only: multisampled ones, which -/// Vulkan copies into no buffer, copy through colour images (`sample_copy.rs`). Refused -/// `NotImplemented(Format)` where a side's buffer texels are not the copy unit: both aspects of a -/// combined format, and 24-bit depth, whose bytes in a buffer Metal's reference GPUs give no -/// answer for (an Apple M3 Max and an M4 make no `Depth24Unorm_Stencil8` texture). -fn through_buffer( - copies: &[ImageCopyRegion], - from: &Held, - block: [u32; 2], - into: &[Held], -) -> Result { - let not_implemented = - || CopyRefusal::Unsupported(Unsupported::not_implemented(Feature::Format)); - let bytes = from.texel_bytes().ok_or_else(not_implemented)?; - if into.iter().any(|to| to.texel_bytes() != Some(bytes)) { - return Err(not_implemented()); - } - // Each copy starts where Vulkan takes either side's bytes: at a multiple of the texel block, - // and of 4 for a depth or stencil aspect. - let align = u64::from(if bytes.is_multiple_of(4) { - bytes - } else { - bytes * 4 - }); - let mut length: u64 = 0; - let mut out_of = Vec::with_capacity(copies.len()); - let mut regions = vec![Vec::with_capacity(copies.len()); into.len()]; - for copy in copies { - length = length.next_multiple_of(align); - let [width, height, depth] = copy.src.size; - out_of.push(vk::BufferImageCopy { - buffer_offset: length, - ..buffer_image_copy(&ImageRegion { - aspect: from.aspect, - ..copy.src - }) - }); - for (to, regions) in into.iter().zip(&mut regions) { - regions.push(vk::BufferImageCopy { - buffer_offset: length, - ..buffer_image_copy(&ImageRegion { - aspect: to.aspect, - ..copy.dst - }) - }); - } - let blocks = [width.div_ceil(block[0]), height.div_ceil(block[1])]; - length += [blocks[0], blocks[1], depth, copy.src.layers] - .iter() - .map(|&n| u64::from(n)) - .product::() - * u64::from(bytes); - } - Ok(Staging { - length, - out_of, - into: into.iter().copied().zip(regions).collect(), - }) -} - -/// Announce `generate_mipmaps` of a texture presenting `record` made by `how` (the device's blit -/// chain or the runtime's compute filter) as the device's filter, not Apple's -/// (`device-filtered-mipmaps`); and so a tiled texture's levels its copies taken at use make -/// (`Buffer::new_tiled_texture`). -pub(super) fn announce_mipmaps(device: &super::Device, record: &ViewRecord, how: &str) { - let (pixel_format, texture_type) = (record.pixel_format, record.texture_type); - device.degrade(Degradation::DeviceFilteredMipmaps, || { - ( - format!( - "generate_mipmaps of a {} {texture_type:?} texture", - pixel_format.name() - ), - format!( - "each level is {how}'s linear filter of the one above, not Apple's GPU's, whose \ - bytes differ near rounding boundaries" - ), - ) - }); -} diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs deleted file mode 100644 index 09a382034..000000000 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ /dev/null @@ -1,6324 +0,0 @@ -//! `Buffer` (`MTLBuffer`) and `Device::new_buffer`. -//! -//! A buffer is a `VkBuffer` placed in the device's sub-allocator (one [`MemoryClass`] per storage -//! mode, `Shared`'s by its CPU cache mode, [`buffer_class`]; at a multiple of -//! [`LINEAR_IMAGE_ALIGNMENT`]), or in the caller's host memory for a no-copy buffer (step 4, -//! `host_memory.rs`), and a range of the device's Metal address space, which `gpu_address` -//! answers. The `VkBuffer` is the length rounded up to 16 bytes (the binder's -//! padding contract), and has a Vulkan device address where the device enables -//! `bufferDeviceAddress`: a placed buffer its block's (`memory.rs`, `memory::allocate_addressed`; -//! made without the device-address usage itself, so the driver counts no addressable buffer per -//! program buffer), any other its own. Every new buffer the runtime allocates reads zero, as Metal's do: memory -//! the host reaches is cleared through its mapping, the rest by a fill on the device before -//! `new_buffer` returns. -//! -//! Step 1 makes `Shared` and `Private` buffers, step 2 `Managed` ones (host-coherent memory, -//! cached where the device has it, and on a device without unified memory a device-local copy -//! with such a host copy, [`Mirror`]: `managed.rs`; a `Managed` no-copy buffer there has the -//! caller's pages as its host copy, `managed_copy.rs`), step 4 buffers over host memory and from bytes -//! (`buffer_descriptor.rs`), labels and purgeable state (`attributes.rs`); `Memoryless` is not a -//! buffer's storage mode in Metal (refused `Invalid`). Step 7 places buffers in heaps -//! (`heap.rs`): such a buffer is bytes of its heap's own buffer, from its offset there -//! ([`Bytes::Heap`]), so it has no `VkBuffer`, memory or address range of its own. - -use super::address::{AddressPlacement, GpuAddress, Held, KeptToken, Place, RangeToken}; -use super::attributes::ResourceAttributes; -use super::buffer_texture::TexelViews; -use super::churn_counts::Recycled; -use super::degradation::{Degradation, NoticesFor}; -use super::device::carry::{CallHold, Contents, Left, LostParts, MadeOn, PartsCalls}; -use super::device::{lock, DeviceShared}; -use super::dirty_pages::{DirtySource, PagesLog}; -use super::error::{internal, invalid, nil, vulkan, Error, Problem}; -use super::exit_guard; -use super::fresh_pages; -use super::generated_commands::PREPROCESS_BUFFER; -use super::heap::{Heap, HeapType}; -use super::host_aliases::Alias; -use super::host_bytes::HostBytes; -use super::host_memory::{HeldBack, HostParts, KeepAlive, Release}; -use super::host_ram::RamOnDevice; -use super::host_residency::{Again, Residency}; -use super::linear_plan::METAL_PAGE; -use super::managed_copy::{CallerCopy, SyncTarget}; -use super::memory::{ - BoundMemory, Holds, Mapped, MemoryClass, Placement, BLOCK_BYTES, FD_BLOCKS_HANDLE, - HOST_PAGES_HANDLE, -}; -use super::program_objects::ProgramObject; -use super::rebind::{ImportHold, Unexact}; -use super::recycle::{self, BufferMaking}; -use super::resource::{Identity, ObjectId, ResourceKey}; -use super::retained::HeldBy; -use super::submit_failure::{try_lock, Standing, TypeFlags}; -use super::texture::first_move::{Filled, Keeps, Mine}; -use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; -use super::Device; -use crate::release; -use ash::vk; -use metal2vulkan::bind::ResidentRange; -use metal2vulkan::device::{IndirectRecordsPolicy, ManagedCopyInPolicy}; -use std::any::Any; -use std::mem::ManuallyDrop; -use std::ops::Range; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; -use std::time::Instant; - -/// A Metal buffer (`MTLBuffer`). Cheap to clone (a retain); `Send + Sync`. Two handles are equal -/// when they are the same buffer. -#[derive(Clone)] -pub struct Buffer(Arc); - -/// The distinct host imports a commit's count of them tells apart in place -/// ([`Buffer::distinct_host_imports`]) before it lists them. -const FEW_IMPORTS: usize = 16; - -/// A buffer held without keeping it (`used_resources.rs`). -#[derive(Clone)] -pub(super) struct WeakBuffer(Weak); - -impl WeakBuffer { - /// The buffer, while it lives. - pub(super) fn upgrade(&self) -> Option { - self.0.upgrade().map(Buffer) - } - - /// Whether the buffer lives. - pub(super) fn lives(&self) -> bool { - self.0.strong_count() > 0 - } -} - -struct BufferShared { - /// Its generation of the device: let go of once the buffer was carried to the next one and its - /// parts there went (`device/carry.rs`). - device: MadeOn, - /// The address of its generation's `DeviceShared`, which a command buffer's work names - /// (`Buffer::carried`), read without the device. - generation: usize, - /// Its identity (`object_id`). - object_id: ObjectId, - length: u64, - /// The bytes from byte 0 that Metal's allocation of the buffer holds as its own, which a - /// texture over it reaches in place ([`Buffer::texel_reach`]): for a buffer of at least - /// 16 KiB the program makes of the runtime's memory in the Metal address space, its length - /// rounded up to 16 KiB (Metal's `allocatedSize`), its `VkBuffer` and placement that long and - /// zero when made (`Device::placed_new_buffer`); its length for every other buffer. - allocation: u64, - /// The options with the hazard tracking mode resolved, as `resourceOptions` reports them. - options: ResourceOptions, - address: GpuAddress, - attributes: ResourceAttributes, - bytes: Bytes, - /// The encoder core that holds it from an argument table's retain (`retained::HeldBy`). - held_by: HeldBy, - /// Its `VkBuffer` was handed out (`Buffer::vk_buffer`): the caller's own work may write its - /// bytes, so no shadow over them keeps a standing across command buffers - /// (`shadow_standing.rs`). - handed_out: Arc, - /// Its maker declared that nothing reads the bytes between a texture's rows and slices over - /// it (`BufferDescriptor::padding_unobserved`), set as it is made: an image over such a - /// texture's memory may hold them (`linear_plan::holding`). - padding_unobserved: AtomicBool, - /// Work staged for the device's next submission holds what it reads for this buffer: a - /// staging buffer (`Buffer::fill_first_from`) or its host copy (`Buffer::upload`), each - /// holding the device. Its drop lets that work go with it (`FirstMoves::forget`). - staged: AtomicBool, - /// The buffer's parts on its device's next generation, where its device's recovery carried it - /// (`device/carry.rs`): the same buffer there, its identity, address, range and range token - /// this one's, its own parts that generation's (`Buffer::s`). Set once; held by this one - /// alone, which the program's handles are. - next: OnceLock, - /// `next` is set: read at one relaxed load where nothing was carried ([`Buffer::s`]), `next` - /// with its own ordering where it was. - carried: AtomicBool, - /// The calls outside a command buffer's work under way on these parts ([`Buffer::held_parts`]). - calls: PartsCalls, -} - -/// Where a buffer's bytes are. -enum Bytes { - /// Its own: a `VkBuffer`, memory and a range of the address space, released with it. - Own(OwnBytes), - /// Its heap's (`heap.rs`). - Heap(HeapBytes), -} - -/// A buffer's own bytes. -struct OwnBytes { - /// Where they lie: for good, or a no-copy buffer's host pages, which a rebind replaces - /// (`rebind.rs`). - lie: Lie, - /// The bytes of the Metal address space the buffer holds. - reserved: Held, - identity: Identity, - owner: Owner, - /// A `Managed` buffer's host copy on a device without unified memory: its `VkBuffer` is then - /// in device-local memory, and `contents` maps the copy ([`HostCopy`]). Shared with the - /// submissions that upload from it. - mirror: Option, - /// The caller's token for the buffer's range (a buffer's `range_token`, or its heap's when - /// the buffer is a heap's own), set once as it is made: dropped right after the range is - /// free and the buffer's teardown leaves its exit section, no runtime lock held, on the - /// thread that drops the buffer's last holder, as the program's code (`exit_guard::program`); - /// left to the process's exit with the buffer where the runtime leaves the buffer to it - /// (`BufferShared`'s drop). - range_token: KeptToken, -} - -/// Where a buffer of its own lies: its `VkBuffer` in its memory. -pub(super) struct Pages { - raw: vk::Buffer, - memory: Bound, - /// Where the buffer's bytes start in its placement: a no-copy buffer's offset in its pages. - offset: u64, - /// Where the buffer's byte 0 lies in `raw`: 0, but for a no-copy buffer whose pointer misses - /// the buffer's memory alignment, bound that many bytes below it. - base: u64, - /// The bytes from byte 0 a copy reads ([`Buffer::copy_reach`]). - reach: u64, -} - -/// Where a buffer of its own lies, for good or until a rebind. -enum Lie { - /// The runtime's memory, or the caller's `VkBuffer`. - Fixed(Arc), - /// A no-copy buffer's host pages: the pages it lies in now, which a rebind replaces. - Host(Arc), -} - -/// A no-copy buffer's (or a no-copy heap's own buffer's) hold on its host pages, which -/// `rebind_bytes_no_copy` replaces (`rebind.rs`) and `detach_backing` lets go of (`detach.rs`). -pub(super) struct HostCell { - pages: Mutex, - /// The texel buffer views of the textures over the buffer's bytes (a no-copy heap's: over - /// its buffers'), which view its pages: a rebind empties them. - texels: Mutex>>, - /// The images of the textures over the buffer's bytes (a no-copy heap's: over its buffers' - /// and in it), which a detach makes present stand-ins (`detach.rs`), and the textures being - /// made over them, which a detach refuses while one is. - textures: Mutex, - /// The images in place over the buffer's bytes (a no-copy heap's: over its buffers'), which a - /// rebind makes again over its new pages (`texture/in_place_image.rs`). - in_place: Mutex>, - /// The reasons the buffer's Metal address was handed out for (`Buffer::gpu_address`, - /// `Buffer::exposed_address`), a bit each ([`ReadApart`]): once any is, its import is kept - /// imported for good (`host_residency.rs`), and a call for a reason noted need not look - /// again. - exposed: AtomicU16, - /// The device whose work counts each look at its pages adds to - /// (`WorkCounts::no_copy_lies_read`): its generation, let go of once the buffer was carried - /// to the next one and its pages there went (`device/carry.rs`). - device: MadeOn, - /// Its pages on its lost generation were marked let go of, the buffer carried to the next one - /// and that generation at rest ([`LostHost`]): no call takes them from now on - /// (`Buffer::held_parts`). - released: AtomicBool, - /// They went ([`LostHost`]): it lies in none ([`Lying::Gone`]). - freed: AtomicBool, - /// The GPU's writes to the buffer are dropped, as Metal's private option bit 24 drops them: - /// its pages are imported through a read-only view of them (`read_only_view.rs`), or copied, - /// the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. - drops_writes: bool, - /// The deallocator of the pages its last detach let go of (`detach.rs`), held back until its - /// next rebind or its release, as Metal runs it then ([`Release::hold_back`]). - held_back: Mutex>>, - /// Its read twin, where its GPU writes are dropped (`read_twin.rs`): the runtime's buffer over - /// the same pages in place, which commands that cannot write the buffer read instead of its - /// copy. Let go of as the buffer lies elsewhere ([`HostCell::replace`]). - read_twin: Mutex>, - /// The read twins of the program's textures over its bytes, while it has a read twin - /// (`read_twin.rs`): each the runtime's texture over the read twin's bytes, in place, which - /// the slots that only read the texture bind instead. Let go of with the read twin. - twin_textures: Mutex>, -} - -/// The read twins a buffer let go of as it came to lie elsewhere ([`HostCell::replace`]): its own -/// and its textures'. The caller drops them holding no lock of the device's rebinds: a twin's -/// going forgets its key there (`Rebinds::forget`), so dropping them under that lock, as a rebind -/// or a detach holds it while the buffer moves, would wait for the lock forever. -#[must_use] -pub(super) struct LeftTwins { - _buffer: Option, - _textures: Vec, -} - -/// A texture's read twin, as a no-copy buffer's [`HostCell`] keeps it (`read_twin.rs`): the -/// texture's `ObjectId`, the texture held weakly, and its twin, a `Texture`, each by type erased -/// as [`NotedTexture`] holds a texture. -pub(super) struct TextureTwin { - pub(super) of: ObjectId, - pub(super) texture: Weak, - pub(super) twin: Arc, -} - -/// An image in place over a buffer's host pages ([`HostCell`], `texture/in_place_image.rs`), -/// which a rebind makes again over the new pages: the image (`texture.rs`'s `Image`), held weakly -/// and by type erased as [`NotedTexture`] holds it, where its texels lie in bytes from the pages' -/// first byte, how Metal lays them out from there, whether their rows' padding is the buffer's -/// own (`in_place::Padding`), and the bytes of one texel (whose width picks the check of a -/// shader's writes, `in_place::Access::written`). -#[derive(Clone)] -pub(super) struct InPlaceWatch { - pub(super) image: Weak, - pub(super) from_base: u64, - pub(super) layout: crate::linear_plan::BufferLayout, - pub(super) padding_owned: bool, - pub(super) texel: u64, -} - -impl InPlaceWatch { - /// Whether the image lives. - fn lives(&self) -> bool { - self.image.strong_count() > 0 - } -} - -/// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes -/// present stand-ins, and how many are being made, which a detach refuses while any is -/// (`detach.rs`). -#[derive(Default)] -pub(super) struct TexturesOver { - /// The textures made over them, each its own entry (a view's too). - noted: Vec, - /// How many are being made now ([`TextureMaking`]). - making: u32, -} - -/// A texture over a buffer's host pages (`TexturesOver`): the texture and its image -/// (`texture.rs`'s `TextureShared` and `Image`), held weakly and by type erased: each holds its -/// device, so naming their types here would make the buffer's types recursive through them, -/// which rustdoc's search for their auto traits overflows on. -pub(super) struct NotedTexture { - texture: Weak, - image: Weak, - /// The texture's `ObjectId`. - pub(super) id: ObjectId, - /// Whether a stand-in of zero bytes presents its image exactly: not for an image of texels - /// its copies convert from the bytes (`texture/stand_in.rs`). - exact: bool, - /// Whether its image's stand-in has a sink (its plan has `STORAGE` usage): a read through a - /// storage-class element there reads what an unnamed write left (`Device::note_stale`). - sink: bool, - /// Whether its image keeps its own texels while the bytes are detached, presenting no - /// stand-in: a tiled texture's, a copy of the bytes taken at use (`shadow.rs`). - keeps: bool, -} - -impl NotedTexture { - /// `texture`, whose image is `image`, of object `id`; `exact`, `sink` and `keeps` as the - /// fields say. - pub(super) fn new( - texture: Weak, - image: Weak, - id: ObjectId, - (exact, sink, keeps): (bool, bool, bool), - ) -> NotedTexture { - NotedTexture { - texture, - image, - id, - exact, - sink, - keeps, - } - } - - /// Whether its image's stand-in has a sink (`NotedTexture::sink`). - pub(super) fn sink(&self) -> bool { - self.sink - } - - /// Whether its image keeps its own texels while the bytes are detached - /// (`NotedTexture::keeps`). - pub(super) fn keeps(&self) -> bool { - self.keeps - } - - /// Whether the texture lives. - fn lives(&self) -> bool { - self.texture.strong_count() > 0 - } - - /// The texture, by type erased, while it lives. - pub(super) fn texture(&self) -> Weak { - Weak::clone(&self.texture) - } -} - -impl TexturesOver { - /// The images of the live textures that present stand-ins while the bytes are detached (all - /// but those that keep their own, `NotedTexture::keeps`), each once, by type erased; and - /// whether a stand-in of zero bytes presents each exactly (`NotedTexture::exact`). - pub(super) fn images(&self) -> (Vec>, bool) { - let mut images: Vec> = Vec::new(); - let mut exact = true; - for noted in self.textures().filter(|noted| !noted.keeps) { - let Some(image) = noted.image.upgrade() else { - continue; - }; - exact &= noted.exact; - if !images.iter().any(|held| Arc::ptr_eq(held, &image)) { - images.push(image); - } - } - (images, exact) - } - - /// The live textures. - pub(super) fn textures(&self) -> impl Iterator { - self.noted.iter().filter(|noted| noted.lives()) - } -} - -/// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie -/// elsewhere ([`HostCell::replace`]: rebound or detached), and a rebind settled what lies over -/// its bytes ([`host_cells_settled`]). -static HOST_CELLS_MOVED: AtomicU64 = AtomicU64::new(0); - -/// The count of the times a no-copy buffer of the process came to lie elsewhere (rebound or -/// detached) so far: while it holds, every buffer's binding is what it was (its base, its -/// addresses), which is what an encoder's kept bind state reads of them (`live_bind.rs`). -pub(super) fn host_cells_moved() -> u64 { - HOST_CELLS_MOVED.load(Ordering::Acquire) -} - -/// A rebind closed its publish (`Rebinds::published`): the images, views and texel views over the -/// moved buffer's bytes are made over its new pages, so a binding read since its move, while they -/// were being made, may hold the old pages' ones. Counted in [`host_cells_moved`] as a move: no -/// binding read before it is kept after it (`rebind.rs`, **Other threads**). -pub(super) fn host_cells_settled() { - HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); -} - -/// The most buffers over host pages a [`KeptSpaces`] keeps where they lie. -const KEPT_SPACES: usize = 4; - -/// Where buffers over host pages (no-copy buffers, and no-copy heaps' own buffers, which their -/// placed buffers lie in) lay as an encoder's binds last read them ([`Buffer::space_kept`]): a -/// bind reads where a buffer lies at each draw (`binding::rebind_into`), which for one over host -/// pages locks its pages and takes a hold of them, and a heap's own buffer is one every encoder -/// of its device's threads reads, as the consumer binds its draws' bytes in a heap over the guest's -/// RAM. Each is kept while no no-copy buffer of the process moved since ([`host_cells_moved`]): a -/// buffer lies where it lay until one moves (`HostCell::replace`), and its import, read for a -/// binding once, stays imported (`HostImport::pages`). A buffer is kept by its cell's address, -/// held weakly: a cell that goes leaves its allocation, and so its address, to its weak handles, so -/// no other cell is at the address while it is kept. -#[derive(Default)] -pub(super) struct KeptSpaces { - kept: Vec, - /// The entry the next buffer kept takes once every one is taken. - next: usize, -} - -/// A buffer over host pages a [`KeptSpaces`] keeps: its cell, the count of moves it was read -/// under, and what [`HostCell::binding_pages`] read. -struct KeptSpace { - cell: Weak, - moved: u64, - pages: (vk::Buffer, u64, u64), -} - -impl KeptSpaces { - /// [`HostCell::binding_pages`] of `cell`, kept or read (counted, - /// `WorkCounts::bind_spaces_read`) and kept. - fn of(&mut self, cell: &Arc) -> (vk::Buffer, u64, u64) { - // Read before the cell: a move after it makes the next look read the cell again. - let moved = host_cells_moved(); - let at = Arc::as_ptr(cell); - let found = (self.kept.iter()).find(|kept| kept.moved == moved && kept.cell.as_ptr() == at); - if let Some(kept) = found { - // Unless it moved since `moved` was read, on another thread (`rebind.rs`, **Other - // threads**): the move is counted under the cell's lock, before a reading of it can - // see where it lies now, and the call's hold tells the race apart. - #[cfg(debug_assertions)] - { - let now = cell.binding_pages(); - assert!( - kept.pages == now || host_cells_moved() != moved, - "a buffer kept where it no longer lies: {:?}, lying in {now:?}", - kept.pages - ); - } - return kept.pages; - } - cell.device.shared().counts.thread().bind_space_read(); - let pages = cell.binding_pages(); - let entry = KeptSpace { - cell: Arc::downgrade(cell), - moved, - pages, - }; - // A stale entry or this cell's goes first; else the entries in turn. - let stale = - (self.kept.iter()).position(|kept| kept.moved != moved || kept.cell.as_ptr() == at); - match stale { - Some(index) => self.kept[index] = entry, - None if self.kept.len() < KEPT_SPACES => self.kept.push(entry), - None => { - self.kept[self.next] = entry; - self.next = (self.next + 1) % KEPT_SPACES; - } - } - pages - } -} - -/// A texture being made over a buffer's host pages ([`Buffer::making_texture`]): a detach -/// refuses until it goes, once the texture is noted (`Buffer::note_texture`) or its making -/// failed. -pub(super) struct TextureMaking(Arc); - -impl Drop for TextureMaking { - fn drop(&mut self) { - let mut textures = lock(&self.0.textures); - textures.making = textures.making.saturating_sub(1); - } -} - -/// Where a no-copy buffer (or a no-copy heap's own buffer) lies: in host pages, or detached -/// from them (`detach.rs`). -#[derive(Clone)] -pub(super) enum Lying { - /// The host pages it lies in. - In(Arc), - /// Detached: in no pages. - Detached(Arc), - /// Its pages on a lost generation went at the generation's rest, the buffer carried to the - /// next one ([`LostHost`], `device/carry.rs`), where they lay as the [`Shape`] says: no work - /// of the generation reads them from then on, and every other reach of the buffer goes to - /// where it was carried. - Gone(Shape), -} - -/// A read of a carried no-copy buffer's pages on its lost generation after the generation's rest -/// ([`Lying::Gone`]), which no work makes: none of its command buffers records, and a call that -/// held them keeps them until it ends (`Buffer::held_parts`). -pub(super) fn read_gone() -> ! { - unreachable!("a carried no-copy buffer's pages read on its lost generation after its rest") -} - -/// What a detached no-copy buffer's commands take of it while it is detached (`detach.rs`): the -/// device's stand-in's `VkBuffer`, at the place the buffer's bytes had in the pages it was detached -/// from (their offset, base and reach), and the stand-in's memory. No command that takes it runs: -/// an encoder that names a detached buffer records nothing from that command on, and its submission -/// fails (`EncoderCore::skips`). -pub(super) struct Detached { - /// The stand-in, a small buffer of the runtime's own, kept while a buffer is detached. - _stand_in: Buffer, - pages: Pages, - /// The host address of the first page of the pages it was detached from, the caller's, - /// whose pointer `contents` answers meanwhile (at `pages.offset`); nothing of the runtime's - /// reads or writes through it. - last: Option, - /// The index of the memory type of the pages it was detached from: a texture made over the - /// bytes meanwhile takes the route it would over them (`texture/heap.rs`). - type_index: u32, - /// Whether the pages it was detached from were imported as dma-bufs, for the same. - over_dma_buf: bool, -} - -impl Detached { - /// What a buffer detached from `from` takes: `stand_in`'s `VkBuffer` and memory, at the - /// place its bytes had in `from`. No memory is placed for it: the placement names the - /// stand-in's, unmapped and freed by none, so the runtime maps nothing of it while it is - /// detached (`Buffer::mapped_contents`); `contents` answers `from`'s pointer. - /// Refused (an internal error) for a stand-in placed in a heap. - pub(super) fn new(stand_in: Buffer, from: &HostPages) -> Result { - let Bytes::Own(own) = &stand_in.0.bytes else { - return Err(internal("a detached buffer's stand-in placed in a heap")); - }; - let old = from.import.shape; - let pages = own.with(ReadApart::Binding, |pages| { - let placement = &pages.memory.placement; - Pages { - raw: pages.raw, - memory: Bound { - placement: Placement::caller( - placement.memory, - placement.offset, - placement.size(), - placement.type_index(), - None, - ), - device_address: pages.memory.device_address, - }, - offset: old.offset, - base: old.base, - reach: old.reach, - } - }); - Ok(Detached { - _stand_in: stand_in, - pages, - last: old.mapped, - type_index: from.type_index(), - over_dma_buf: from.over_dma_buf(), - }) - } -} - -impl HostCell { - /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`, `copied.rs`). - pub(super) fn drops_writes(&self) -> bool { - self.drops_writes - } - - /// The pages the buffer lies in now; `None` while it is detached. - pub(super) fn current(&self) -> Option> { - self.device.shared().counts.thread().no_copy_lie_read(); - match &*lock(&self.pages) { - Lying::In(pages) => Some(Arc::clone(pages)), - Lying::Detached(_) | Lying::Gone(_) => None, - } - } - - /// Where the buffer lies now. - pub(super) fn lying(&self) -> Lying { - self.device.shared().counts.thread().no_copy_lie_read(); - lock(&self.pages).clone() - } - - /// The `VkBuffer` its bytes lie in now, where its byte 0 lies there (`Pages::base`), and - /// where they start in their first page (`Shape::base`), read for a binding - /// (`ReadApart::Binding`): what [`Buffer::space`] and [`Buffer::at_for`] read of it. - fn binding_pages(&self) -> (vk::Buffer, u64, u64) { - match self.lying() { - Lying::In(pages) => { - let read = pages.import.pages(ReadApart::Binding); - (read.raw, read.base, pages.import.shape.base) - } - Lying::Detached(detached) => { - let pages = &detached.pages; - (pages.raw, pages.base, Shape::of(pages).base) - } - Lying::Gone(_) => read_gone(), - } - } - - /// The host addresses of the buffer's bytes, from its byte 0 over the bytes a copy reads, - /// where it lies in host pages now; `None` while it is detached. - pub(super) fn host_range(&self) -> Option> { - match self.lying() { - Lying::In(pages) => { - let shape = pages.import.shape; - let mapped = shape.mapped?; - let start = (mapped.as_ptr() as usize).checked_add(shape.offset as usize)?; - Some(start..start.checked_add(shape.reach as usize)?) - } - Lying::Detached(_) | Lying::Gone(_) => None, - } - } - - /// The `N` bytes at `offset` of the buffer's bytes, as the host reads them now through the - /// pages they lie in, which are held while they are read: a detach and a rebind meanwhile let - /// none of them go under the read (their deallocator waits for them, `HeldBack`). `None` while - /// it is detached. The caller holds `offset + N` inside the buffer's length. - fn read(&self, offset: u64) -> Option<[u8; N]> { - let pages = self.current()?; - let shape = pages.import.shape; - let start = shape.mapped?.as_ptr().wrapping_add(shape.offset as usize); - let mut bytes = [0u8; N]; - // SAFETY: the pages map the buffer's bytes from `start`, and the caller holds the `N` - // bytes at `offset` inside its length; `pages` keeps them mapped until the copy ends. A - // write to them meanwhile races, as a read of `contents` does on Metal. - unsafe { - let at = start.wrapping_add(offset as usize); - std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N); - } - drop(pages); - Some(bytes) - } - - /// The caller's pointer of the pages the buffer was detached from, while it is detached. - fn detached_pointer(&self) -> Option> { - match &*lock(&self.pages) { - Lying::Detached(detached) => (detached.last).and_then(|mapped| { - NonNull::new(mapped.as_ptr().wrapping_add(detached.pages.offset as usize)) - }), - Lying::In(_) | Lying::Gone(_) => None, - } - } - - /// Whether the buffer is detached. - pub(super) fn detached(&self) -> bool { - matches!(*lock(&self.pages), Lying::Detached(_)) - } - - /// Where the bytes start in their first page: the pages', or those it was detached from. - pub(super) fn offset(&self) -> u64 { - match &*lock(&self.pages) { - Lying::In(pages) => pages.offset(), - Lying::Detached(detached) => detached.pages.offset, - Lying::Gone(shape) => shape.offset, - } - } - - /// Lie `lying` from now on: where the buffer lay, and the read twins it had over those - /// pages, which the caller lets go of (the twins holding no lock of the rebinds, - /// [`LeftTwins`]). Counted in [`host_cells_moved`]: a buffer binding that reads where it lies - /// (its base, its device address) may change. - pub(super) fn replace(&self, lying: Lying) -> (Lying, LeftTwins) { - let lay = { - let mut pages = lock(&self.pages); - let lay = std::mem::replace(&mut *pages, lying); - HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); - lay - }; - // Its read twins lie over the pages it lay in: taken now, outside the pages' lock, so the - // buffer is its copy alone from now on (`read_twin.rs`), as the copy it lay in is. - let twin = lock(&self.read_twin).take(); - if let (Some(_), Lying::In(pages)) = (&twin, &lay) { - pages.set_copy_twinned(false); - } - let twins = LeftTwins { - _buffer: twin, - _textures: lock(&self.twin_textures).drain(..).collect(), - }; - (lay, twins) - } - - /// Its read twin (`read_twin.rs`), while it lies in the pages the twin was made over. - pub(super) fn read_twin(&self) -> Option { - lock(&self.read_twin).clone() - } - - /// Keep `twin`, its read twin over the pages it lies in now (`read_twin.rs`). - pub(super) fn keep_read_twin(&self, twin: Buffer) { - let earlier = lock(&self.read_twin).replace(twin); - drop(earlier); - } - - /// The read twin of the texture of `id` over its bytes (`read_twin.rs`), by type erased, - /// while the buffer lies in the pages it was made over. - pub(super) fn twin_texture(&self, id: ObjectId) -> Option> { - let textures = lock(&self.twin_textures); - let found = textures.iter().find(|kept| kept.of == id); - found.map(|kept| Arc::clone(&kept.twin)) - } - - /// Keep `kept`, a texture's read twin over the read twin's bytes, while the buffer has that - /// read twin (`read_twin.rs`); those of textures that went are let go of. - pub(super) fn keep_twin_texture(&self, kept: TextureTwin) { - if lock(&self.read_twin).is_none() { - return; - } - let mut textures = lock(&self.twin_textures); - let gone: Vec = textures - .extract_if(.., |kept| kept.texture.strong_count() == 0) - .collect(); - textures.push(kept); - drop(textures); - drop(gone); - } - - /// A detach let go of `pages`: their deallocator is held back until the buffer's next rebind - /// or its release ([`HostCell::release_held_back`]), as Metal never runs it at a detach. - pub(super) fn hold_back(&self, pages: &HostPages) { - let Some(held) = pages.release.get().and_then(Release::hold_back) else { - return; - }; - let earlier = lock(&self.held_back).replace(held); - // Never so: a detached buffer is detached again by no detach, and a rebind runs what - // was held back first. Were it to be, the earlier one is due now. - if let Some(earlier) = earlier { - self.held_back_due(&earlier); - } - } - - /// The buffer's next rebind (inside the call, once its new pages are in place) or its release - /// came: the deallocator its last detach held back runs now, on this thread, as Metal runs it - /// there, or, where the pages it let go of are still imported (a texture's image over them - /// waits for a command buffer that may read it) and no keep-alive keeps them mapped, once - /// their import is freed, announced (`host-deallocator-delayed`). - pub(super) fn release_held_back(&self) { - let held = lock(&self.held_back).take(); - if let Some(held) = held { - self.held_back_due(&held); - } - } - - /// `held` is due ([`HostCell::release_held_back`]). - fn held_back_due(&self, held: &HeldBack) { - if !held.due() { - return; - } - let device = &self.device; - device.shared().counts.host_deallocator_delayed(); - device.degrade_once(Degradation::HostDeallocatorDelayed, || { - ( - "a detached no-copy buffer".to_owned(), - "the pages its detach let go of are still imported as it is rebound or released \ - (a texture's image over them may still be read through its resource ID by a \ - command buffer), and the caller gave no keep-alive: its deallocator runs once \ - their import is freed" - .to_owned(), - ) - }); - } - - /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), forgetting those - /// gone. - fn watch_texture(&self, noted: NotedTexture) { - let mut textures = lock(&self.textures); - textures.noted.retain(NotedTexture::lives); - textures.noted.push(noted); - } - - /// Note `watch`, an image in place over the buffer's bytes, forgetting those gone. - fn watch_in_place(&self, watch: InPlaceWatch) { - let mut in_place = lock(&self.in_place); - in_place.retain(InPlaceWatch::lives); - in_place.push(watch); - } - - /// The live images in place over the buffer's bytes, which a rebind makes again. - pub(super) fn in_place_images(&self) -> Vec { - let mut in_place = lock(&self.in_place); - in_place.retain(InPlaceWatch::lives); - in_place.clone() - } - - /// The textures over the buffer's bytes, locked, where none is being made: none is made - /// while it is held (`Buffer::making_texture`). `None` where one is. - pub(super) fn settled(&self) -> Option> { - let textures = lock(&self.textures); - (textures.making == 0).then_some(textures) - } - - /// The texel views of the live textures over the buffer's bytes. - pub(super) fn texels(&self) -> Vec> { - lock(&self.texels) - .iter() - .filter_map(Weak::upgrade) - .collect() - } - - /// Note `views`, a texture's over the buffer's bytes, forgetting those gone. - fn watch(&self, views: &Arc) { - let mut texels = lock(&self.texels); - texels.retain(|views| views.strong_count() > 0); - texels.push(Arc::downgrade(views)); - } -} - -/// A hold on the pages a buffer of its own lies in (`Buffer::resident`), kept and never read: -/// they stay while it lives. -#[derive(Clone)] -pub(super) enum PagesHold { - Fixed { _pages: Arc }, - Host { _pages: ListedPages }, -} - -/// A live buffers' table's hold on host pages (`PagesHold::Host`), counted -/// (`HostPages::listed`): one left as the buffer is released is a table a command buffer that may -/// reach the pages unnamed holds, past Metal's release (`HostPages::released_listed`). -pub(super) struct ListedPages(Arc); - -impl ListedPages { - fn new(pages: Arc) -> ListedPages { - pages.listed.fetch_add(1, Ordering::AcqRel); - pages.import.note_listed(); - ListedPages(pages) - } -} - -impl Clone for ListedPages { - fn clone(&self) -> ListedPages { - ListedPages::new(Arc::clone(&self.0)) - } -} - -impl Drop for ListedPages { - fn drop(&mut self) { - self.0.listed.fetch_sub(1, Ordering::AcqRel); - } -} - -/// A hold on the memory a buffer's bytes lie in now, and on nothing else of the buffer -/// (`Buffer::memory_hold`), kept and never read: an image bound to them (a texture's over the -/// buffer, a heap's texture's) keeps it while a command buffer may still reach the image, past the -/// buffer and texture objects. Metal frees those at their release: the buffer's range of the -/// address space and its range token go with the buffer, and a no-copy buffer's deallocator runs as -/// its pages go; only the `VkBuffer` and its memory, or host pages' import, stay. -#[derive(Clone)] -pub(super) enum MemoryHold { - Fixed { _pages: Arc }, - Host { _import: Arc }, -} - -/// The pages a buffer of its own lies in for good: its `VkBuffer` and its placement. Held by the -/// buffer, and by each command buffer whose resident set lists them until it completed -/// (`live_buffers.rs`): the last lets go, which parks the `VkBuffer` and its placement for the -/// next buffer of the same making where the recycler noted them (`recycle.rs`), else destroys the -/// `VkBuffer` (unless it is the caller's, `Owner::Vulkan`) and frees the placement. -pub(super) struct FixedPages { - /// Its generation of the device: let go of with the pages on a lost generation - /// ([`FixedPages::release_lost`]). - device: MadeOn, - pages: Pages, - /// The `VkBuffer` is the runtime's to destroy. - owned: bool, - /// Its `VkBuffer` and memory are let go of on its lost generation, its buffer carried to the - /// next one ([`LostBuffer`]): no work meets them from now on. - released: AtomicBool, - /// They went ([`FixedPages::release_lost`]): its drop lets go of nothing. - freed: AtomicBool, - /// The images of textures over them, of the runtime's memory exported as a dma-buf, parked - /// as their textures went (`dma_buf/parked.rs`): released as they go. - #[cfg(unix)] - parked_images: crate::dma_buf::parked::ParkedImages, -} - -impl FixedPages { - /// The images parked under them (`dma_buf/parked.rs`). - #[cfg(unix)] - pub(super) fn parked_images(&self) -> &crate::dma_buf::parked::ParkedImages { - &self.parked_images - } - - /// Destroy the `VkBuffer` and free the memory of the pages of a buffer its device's recovery - /// carried to the next generation, on the lost one at rest, marked let go of - /// ([`LostBuffer`]), and let go of its handle of that generation (`device/carry.rs`). Vulkan - /// leaves a lost device's objects to the program to destroy: "When a device is lost, its - /// child objects are not implicitly destroyed and their handles are still valid. Those - /// objects must still be destroyed before their parents or the device can be destroyed" - /// (vkspec 5.2.3). Nothing recycles them. Left to the process's end while it exits. - fn release_lost(&self) { - let Some(busy) = exit_guard::enter() else { - return; - }; - let shared = self.device.shared(); - // The images parked under them go with them, before their memory (`dma_buf/parked.rs`). - #[cfg(unix)] - crate::dma_buf::parked::release(self.parked_images.take_where(|_| true)); - if self.owned { - // SAFETY: none of the lost generation's command buffers records or is pending, and - // every later one's work reaches the carried buffer's own pages. - unsafe { release::object(shared.vk(), self.pages.raw) }; - } - lock(&shared.memory).free(shared.vk(), &self.pages.memory.placement); - self.freed.store(true, Ordering::Release); - drop(busy); - // SAFETY: as above; the pages' drop reads nothing once they went. - unsafe { self.device.let_go() }; - } -} - -/// A carried buffer's parts on its device's lost generation (`device/carry.rs`): its pages, held -/// until they go whether the program keeps the buffer or not, and its handle of the generation. -struct LostBuffer { - pages: Arc, - buffer: Weak, -} - -impl LostParts for LostBuffer { - fn mark(&self) { - self.pages.released.store(true, Ordering::Release); - } - - fn release(self: Box) { - let Some(buffer) = self.buffer.upgrade() else { - // The buffer went, and with it every call on its parts. - self.pages.release_lost(); - return; - }; - // The last call under way on them lets them go (`Buffer::held_parts`). - if let Some(lost) = buffer.calls.unless_held(self) { - (*lost).release_now(&buffer); - } - } -} - -impl LostBuffer { - /// Let the parts go, no call on them under way, and the buffer's handle of their generation: - /// but where their `VkBuffer` or memory was handed out (`Buffer::vk_buffer`, - /// `Buffer::vk_host_memory`), which the caller may use while the buffer lives, so they go - /// with the buffer, as a refused object's do. - fn release_now(self, buffer: &BufferShared) { - if buffer.handed_out.load(Ordering::Acquire) { - return; - } - self.pages.release_lost(); - // SAFETY: its parts on the generation went, no command buffer of the generation records, - // no call under way reads them (`Buffer::held_parts`), and every other reach of the - // buffer goes to where it was carried (`Buffer::carried`). - unsafe { buffer.device.let_go() }; - } -} - -/// A carried heap buffer's parts on its device's lost generation (`Buffer::carry_placed`): no -/// Vulkan object of their own (their bytes are their heap's own buffer's, which its carry carried -/// apart), their entry among the generation's live buffers, and the buffer's handle of the -/// generation, let go of once none of its command buffers may record. -struct LostPlaced { - buffer: Weak, -} - -impl LostParts for LostPlaced { - fn release(self: Box) { - // The buffer went: its drop on the generation let go of everything there. - let Some(buffer) = self.buffer.upgrade() else { - return; - }; - // The last call under way on them lets them go (`Buffer::held_parts`). - if buffer.calls.unless_held(self).is_none() { - return; - } - let shared = buffer.device.shared(); - (shared.live_buffers).forget(buffer.address.0, buffer.object_id); - // SAFETY: no command buffer of the generation records, no call under way reads its parts - // there (`Buffer::held_parts`), and every other reach of the buffer goes to where it was - // carried (`Buffer::carried`). - unsafe { buffer.device.let_go() }; - } -} - -/// A carried no-copy buffer's parts on a lost generation (`Buffer::carry`): its hold there on the -/// caller's pages (`cell`, its pages' import among them) and the buffer's handle of the -/// generation, let go of once none of the generation's command buffers may record, as a buffer of -/// the generation's goes there: out of its live buffers and its registries of no-copy buffers, -/// its pages let go of, whose release tells what waits for every import of them -/// (`Release::carry_on`). -struct LostHost { - cell: Arc, - buffer: Weak, -} - -impl LostParts for LostHost { - fn mark(&self) { - self.cell.released.store(true, Ordering::Release); - } - - fn release(self: Box) { - // The buffer went: its drop on the generation let go of everything there. - let Some(buffer) = self.buffer.upgrade() else { - return; - }; - // The last call under way on them lets them go (`Buffer::held_parts`). - if let Some(lost) = buffer.calls.unless_held(self) { - (*lost).release_now(&buffer); - } - } -} - -impl LostHost { - /// Let the parts go, no call on them under way, as [`LostBuffer::release_now`] does. - fn release_now(self, buffer: &BufferShared) { - if buffer.handed_out.load(Ordering::Acquire) { - return; - } - // The process is exiting: the parts are left to its end, as every buffer's. - let Some(busy) = exit_guard::enter() else { - return; - }; - let shared = buffer.device.shared(); - shared - .live_buffers - .forget(buffer.address.0, buffer.object_id); - if let Bytes::Own(own) = &buffer.bytes { - shared.rebinds.forget(own.identity.key); - shared.aliases.forget(own.identity.key); - } - drop(busy); - let shape = match self.cell.lying() { - Lying::In(pages) => pages.import.shape, - Lying::Detached(detached) => Shape::of(&detached.pages), - Lying::Gone(shape) => shape, - }; - let (left, twins) = self.cell.replace(Lying::Gone(shape)); - drop(twins); - self.cell.freed.store(true, Ordering::Release); - // The pages go where nothing else holds them, their import freed where none holds it: - // their release tells what waits for every import of them. - drop(left); - // SAFETY: its parts on the generation went, no command buffer of the generation records, - // no call under way reads them (`Buffer::held_parts`), its cell lies in none of them and - // is read no more there (`Lying::Gone`), and every other reach of the buffer goes to - // where it was carried (`Buffer::carried`). - unsafe { - self.cell.device.let_go(); - buffer.device.let_go(); - } - } -} - -/// A call outside a command buffer's work on a buffer's parts on one generation -/// ([`Buffer::held_parts`]), until it goes: the parts stay while it lives (`PartsCalls`), and -/// every read of the buffer's parts on this thread meanwhile answers them. -pub(super) struct HeldParts<'a> { - _call: CallHold<'a>, - _scope: NoticesFor, -} - -impl Drop for FixedPages { - fn drop(&mut self) { - // Let go of on its lost generation already (`FixedPages::release_lost`). - if *self.freed.get_mut() { - return; - } - // The Vulkan teardown is a section of the exit guard. - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the buffer and its memory are left to its end. - return; - }; - let shared = self.device.shared(); - // The images parked under them go first, before their memory is freed or recycled for - // another buffer (`dma_buf/parked.rs`). - #[cfg(unix)] - crate::dma_buf::parked::release(self.parked_images.take_where(|_| true)); - // No pending command buffer uses the pages: one whose commands used the buffer holds it, - // and one whose resident set lists them holds them, until it completed. - let placement = &self.pages.memory.placement; - let parked = match self.owned { - true => { - let mut recycled = lock(&shared.recycled_buffers); - let now = Instant::now(); - let parked = recycled.park(self.pages.raw, placement.handed_over(), now); - // Gone in time where no park or take comes (`idle_sweep.rs`). - if let Some(due) = recycled.due() { - shared.idle_sweep.by(due); - } - parked.ok() - } - false => None, - }; - match parked { - Some(gone) => { - shared.counts.churn.parked(Recycled::Buffer); - self.device.let_go_parked_buffers(gone); - } - None => { - if self.owned { - // SAFETY: as above. - unsafe { release::object(shared.vk(), self.pages.raw) }; - } - // The caller's `VkBuffer`'s placement returns nothing. - lock(&shared.memory).free(shared.vk(), placement); - } - } - drop(busy); - } -} - -/// Host pages a no-copy buffer lies in: its `VkBuffer` over them and their import -/// (`HostImport`), the images a rebind parked, and their release. Held by the buffer while it -/// lies in them and by each command buffer whose commands used them until it completed -/// (`rebind.rs`); the last lets go: the parked images are destroyed, the import let go (destroyed -/// where these pages held it last), and the deallocator run. -/// -/// The import may outlive them: a texture over the pages whose image a command buffer submitted -/// before the texture's release may still read through its resource ID holds it (`heap_sets.rs`). -/// Vulkan requires the pages to stay mapped while imported, so the deallocator runs as they go only -/// where the caller's keep-alive keeps the pages mapped (the import keeps it until freed), or -/// another buffer lies in the import, whose contract keeps them mapped; else it runs once the -/// import is freed, at once where nothing else holds it, and announced where something does -/// (`host-deallocator-delayed`). A keep-alive goes as they go where the import's pages stay mapped -/// without it: another buffer lies in the import, or the import keeps another's keep-alive already -/// (every buffer in it was made over the same bytes, `host_aliases.rs`). So an import keeps one -/// keep-alive at most, however many buffers come and go over its bytes while it lives. -pub(super) struct HostPages { - /// The images and views over them a rebind or a detach replaced (a no-copy heap's textures', - /// texel buffer views), which commands recorded before it may use: destroyed with them, - /// first. - parked: Mutex>>, - /// Their `VkBuffer` and its memory, which no-copy buffers made over the same bytes share - /// (`host_aliases.rs`). - import: Arc, - /// Their release to the caller's deallocator and keep-alive, set once they are the buffer's - /// (a refused rebind drops its pages without it, and the deallocator unrun). - release: OnceLock, - /// The live buffers' tables' holds on them ([`ListedPages`]). - listed: AtomicUsize, - /// The caller's log of the writes to them, where it gave one with their memory - /// (`HostMemory::with_dirty_pages`, `dirty_pages.rs`). - dirty: OnceLock>, - /// The guest RAM their caller resolved them to and the runs of it they are, in their byte - /// order (`HostMemory::with_runs`, `host_ram.rs`), kept until the rebind or the release. - ram_runs: OnceLock<(Arc, Box<[Range]>)>, - /// The key they named to their copy, where they lie in one ([`HostPages::copied_as`]): its - /// naming goes as they go. - named: OnceLock, - /// The caller's memory they were made of, a buffer's (not a heap's own): what its device's - /// recovery makes the buffer again of on the next generation (`Buffer::carry`). - made_of: OnceLock, -} - -/// Where host pages lie in one import of a dma-buf dedicated to nothing -/// ([`HostPages::in_one_dma_buf_import`]). -#[cfg(unix)] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct DmaBufImportAt { - /// The import's memory: `VK_NULL_HANDLE` where it was read as a blit reads it, unexposed. - pub(super) memory: vk::DeviceMemory, - /// Where the pages' bytes start in it. - pub(super) base: u64, - /// Its bytes from there to the end of the pages' placement. - pub(super) room: u64, - /// Its memory type. - pub(super) type_index: u32, -} - -/// How new pages come to lie in an import ([`HostPages::new`]). -#[derive(Clone, Copy, PartialEq, Eq)] -pub(super) enum Joining { - /// The import was made for them. - First, - /// A no-copy buffer's, made over the bytes the import's buffers were made over - /// (`host_aliases.rs`): it reads the import as they do, through the import, so a releasable - /// import stays releasable beside it (`host_residency.rs`). - Buffer, - /// A no-copy heap's own bytes, over the bytes the import's buffers were made over: its - /// placed buffers' addresses are the heap's, handed out with no read of the import noted, so - /// the import is kept imported for good. - Heap, - /// A rebound buffer's (`rebind.rs`): kept imported for good, as a rebind's own import is. - Rebound, -} - -impl HostPages { - /// New pages lying in `import`, with no release yet, `joining` it so. - fn new(import: Arc, joining: Joining) -> HostPages { - let others = import.lying.fetch_add(1, Ordering::AcqRel) > 0; - match (joining, others) { - // Imported for good beside the others (`host_residency.rs`). - (Joining::Heap, true) => { - import.expose(ReadApart::Heap); - } - (Joining::Rebound, true) => { - import.expose(ReadApart::Rebound); - } - (Joining::Buffer, true) => import.note_joined(), - (Joining::First | Joining::Buffer | Joining::Heap | Joining::Rebound, _) => {} - } - HostPages { - parked: Mutex::new(Vec::new()), - import, - release: OnceLock::new(), - listed: AtomicUsize::new(0), - dirty: OnceLock::new(), - ram_runs: OnceLock::new(), - named: OnceLock::new(), - made_of: OnceLock::new(), - } - } - - /// They lie in a copy of the caller's pages, registered as `copied` (`copied.rs`). - pub(super) fn set_copied(&self, copied: crate::copied::Copied) { - self.import.set_copied(copied); - } - - /// Whether a read twin reads them in place, where they lie in a copy of the caller's pages - /// (`copied.rs`'s `Copied::set_twinned`). - pub(super) fn set_copy_twinned(&self, twinned: bool) { - if let Some(copied) = self.import.copied.get() { - copied.set_twinned(twinned); - } - } - - /// Keep the caller's log of the writes to them (`dirty_pages.rs`), given with their memory. - pub(super) fn keep_dirty(&self, dirty: Arc) { - let _kept = self.dirty.set(dirty); - } - - /// Keep the logs of the writes to them (`dirty_pages::PagesLog`), with their import. - pub(super) fn keep_log(&self, log: Arc) { - self.import.keep_log(log); - } - - /// The logs of the writes to them, where their memory came with one. - pub(super) fn log(&self) -> Option<&Arc> { - self.import.log.get() - } - - /// Name `key`, a buffer's (or a heap's bytes') lying in them, to their copy, where they are - /// one: its merges back compare the copy where a batch wrote that key (`copied.rs`), until - /// they go. Once: a second call names nothing. - pub(super) fn copied_as(&self, key: ResourceKey) { - if let Some(copied) = self.import.copied.get() { - if self.named.set(key).is_ok() { - copied.name(key); - } - } - } - - /// Report the GPU's writes through the uses of `key`, a buffer's (or a heap's bytes') lying - /// in them, to their logs (`DirtyShadows::logged_in_place`), where they have one and lie in - /// an import the GPU writes in place: a copy reports its merges back instead (`copied.rs`), - /// and a read-only view takes no write. - pub(super) fn logged_as(&self, key: ResourceKey) { - let import = &self.import; - if import.copied.get().is_some() || import.drops_writes() { - return; - } - if let Some(log) = import.log.get() { - import.device.shared().dirty.logged_in_place(key, log); - } - } - - /// Keep `parts`, the caller's memory they were made of ([`HostPages::made_of`]). - pub(super) fn keep_made_of(&self, parts: HostParts) { - let _kept = self.made_of.set(parts); - } - - /// The caller's memory they were made of, a buffer's (not a heap's own), which its device's - /// recovery makes the buffer again of on the next generation (`Buffer::carry`). - pub(super) fn made_of(&self) -> Option<&HostParts> { - self.made_of.get() - } - - /// Keep the guest RAM and the runs of it their caller resolved them to (`host_ram.rs`). - pub(super) fn keep_runs(&self, runs: (Arc, Box<[Range]>)) { - let _kept = self.ram_runs.set(runs); - } - - /// The caller's log of the writes to them, where it gave one. - pub(super) fn dirty(&self) -> Option<&Arc> { - self.dirty.get() - } - - /// Keep `objects`, over these pages, until they go. - pub(super) fn park(&self, objects: impl Any + Send + Sync) { - lock(&self.parked).push(Box::new(objects)); - } - - /// Their memory and where the bytes start in it (a heap's textures bind images there): a - /// read that keeps the import imported for good (`host_residency.rs`). - pub(super) fn memory(&self) -> (vk::DeviceMemory, u64) { - let pages = self.import.pages(ReadApart::Texture); - let placement = &pages.memory.placement; - (placement.memory, placement.offset + pages.offset) - } - - /// Where the bytes start in their first imported page. - pub(super) fn offset(&self) -> u64 { - self.import.shape.offset - } - - /// Whether they lie in fresh pages the runtime mapped and imported (`fresh_pages.rs`): a copy - /// of the caller's pages that images in place ride on (`Device::copied_pages`). - pub(super) fn over_own_pages(&self) -> bool { - let pages = self.import.pages(ReadApart::Texture); - pages.memory.placement.over_own_pages() - } - - /// The bytes of their memory from where the bytes start to the placement's end: the room an - /// image bound at their bytes has. - pub(super) fn room(&self) -> u64 { - let pages = self.import.pages(ReadApart::Texture); - pages.memory.placement.size().saturating_sub(pages.offset) - } - - /// The index of their memory's type. - pub(super) fn type_index(&self) -> u32 { - self.import.shape.type_index - } - - /// Whether they were imported as dma-bufs (`dma_buf.rs`), not by their pointer. - pub(super) fn over_dma_buf(&self) -> bool { - self.import.shape.over_dma_buf - } - - /// Whether they lie in a copy of the caller's pages (`copied.rs`), not an import of them. - pub(super) fn copied(&self) -> bool { - self.import.copied() - } - - /// Where byte `offset` of the bytes lying in them lies in their import's memory, for the - /// caller ([`Buffer::vk_host_memory`](crate::Buffer::vk_host_memory)): read apart as the - /// buffer's `VkBuffer` is (`ReadApart::VkBuffer`), which keeps a releasable import imported - /// for good. `None` where that memory is not one import of the pages themselves by their - /// pointer, alone or a guest RAM chunk's: a copy of them, imports of dma-bufs, an import of a - /// read-only view of them, or the device's stand-in for an import it could not make again. - fn in_import(&self, offset: u64) -> Option { - let import = &self.import; - if import.copied() || import.drops_writes() || import.shape.over_dma_buf { - return None; - } - let pages = import.pages(ReadApart::VkBuffer); - if matches!(pages, ImportPages::StandIn(_)) { - return None; - } - let placement = &pages.memory.placement; - if placement.over_dma_buf() || placement.over_read_only_view() || placement.over_own_pages() - { - return None; - } - let at = pages.offset + offset; - Some(crate::VkHostMemory { - memory: placement.memory, - offset: placement.offset + at, - size: placement.size().saturating_sub(at), - type_index: placement.type_index(), - handle_type: vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT, - }) - } - - /// Whether they are bound in the device's import of a chunk of a guest RAM (`host_ram.rs`), - /// with no import of their own. - pub(super) fn in_ram_chunk(&self) -> bool { - self.import.shape.in_ram_chunk - } - - /// Where they lie as dma-bufs (`dma_buf.rs`): the imports, with the caller's source; the host - /// address where their bytes start (from which an image over them reckons its texels'); and - /// the imports' memory type. `None` for pages imported by their pointer. Read as a blit reads - /// them (`HostImport::blit_pages`): imported again where the device released them while - /// idle, and left releasable, for an image over a dma-buf of its own pages - /// (`Device::dma_buf_image`), which asks their source and binds none of their memory, so - /// neither it nor a command that uses it holds their import (`host_residency.rs`). Refused - /// where the device cannot import them again. - #[cfg(unix)] - pub(super) fn dma_buf( - &self, - ) -> Result, u64, u32)>, Error> { - let (pages, _) = self.import.blit_pages()?; - let placement = &pages.memory.placement; - let (Some(imports), Some(mapped)) = (placement.dma_buf_pages(), placement.mapped) else { - return Ok(None); - }; - let start = (mapped.as_ptr() as u64).checked_add(pages.offset); - Ok(start.map(|start| { - ( - Arc::clone(imports), - placement.dma_buf_address(start), - placement.type_index(), - ) - })) - } - - /// Where they lie in one import of a dma-buf dedicated to nothing (`dma_buf.rs`), which an - /// image in place over their bytes binds in at its texels' offset, as several buffers bind in - /// one import (`texture/in_place_image.rs`): the import's memory, where their bytes start in - /// it, the bytes of it from there to their placement's end, and its memory type. `None` for - /// pages imported by their pointer, pages bound sparsely over several imports (the memory is - /// then none), and an import dedicated to the buffer bound in it, where the driver refused it - /// dedicated to nothing, which binds no image (`VUID-vkBindImageMemory-memory-10926`). Read as - /// a blit reads them where `expose` is false (`HostImport::blit_pages`), so an image's making - /// asks it before it binds and leaves a releasable import releasable, its memory unnamed - /// (`VK_NULL_HANDLE`); where `expose`, as [`HostPages::memory`] reads them, which keeps the - /// import imported for good from then on (`host_residency.rs`), for the image's bind. - /// Refused where the device cannot import them again. - #[cfg(unix)] - pub(super) fn in_one_dma_buf_import( - &self, - expose: bool, - ) -> Result, Error> { - let pages = match expose { - true => self.import.pages(ReadApart::Texture), - false => self.import.blit_pages()?.0, - }; - let placement = &pages.memory.placement; - let Some(imports) = placement.dma_buf_pages() else { - return Ok(None); - }; - if placement.memory == vk::DeviceMemory::null() || imports.dedicated_to_buffer() { - return Ok(None); - } - Ok(Some(DmaBufImportAt { - memory: match expose { - true => placement.memory, - false => vk::DeviceMemory::null(), - }, - base: placement.offset + pages.offset, - room: placement.size().saturating_sub(pages.offset), - type_index: placement.type_index(), - })) - } - - /// As the buffer that lies in them is released (`BufferShared`'s drop, a no-copy heap's own - /// buffer's included), its listing let go of: a live buffers' table that still lists them is a - /// command buffer's, one that may reach them unnamed (its first submission's, a host step's, - /// or one a root table recorded before its first submission holds, `live_buffers.rs`), and - /// the pages stay until it lets go of it. Where the caller gave a keep-alive, that keeps the - /// pages mapped until the import is freed, so the deallocator runs here, at Metal's moment - /// ([`HostPages::run_kept`]), and the import keeps the keep-alive unless it keeps another's. - /// Else the deallocator waits for the pages to go, where Metal's runs at the release: - /// announced once per device (`Degradation::HostDeallocatorDelayed`). - fn released_listed(&self, device: &Device) { - let Some(release) = self.release.get() else { - return; - }; - if self.listed.load(Ordering::Acquire) == 0 { - return; - } - // The exit guard runs no deallocator and drops no keep-alive: the pages' drop keeps them. - let Some(busy) = exit_guard::enter() else { - return; - }; - drop(busy); - if let Some(keep_alive) = release.keep_alive() { - // These pages still lie in the import, and another buffer lying there may have let go - // of its keep-alive here too: only a keep-alive the import keeps covers this one. - self.run_kept(release, keep_alive, false); - return; - } - if !release.deallocates() { - return; - } - device.shared().counts.host_deallocator_delayed(); - let length = release.length(); - device.degrade_once(Degradation::HostDeallocatorDelayed, || { - ( - format!("a no-copy buffer of {length} bytes"), - "a command buffer that may reach its pages unnamed (a live buffers' table it \ - holds lists them) holds them as it is released, and the caller gave no \ - keep-alive" - .to_owned(), - ) - }); - } - - /// Run `release`'s deallocator now, at Metal's moment, the caller's `keep_alive` keeping the - /// pages mapped until the import is freed: the import keeps it, unless it keeps another's - /// already, or `others` (another buffer lies in the import, whose own contract keeps the same - /// bytes mapped until it is freed); then it is dropped after the deallocator, which may read - /// the bytes. - fn run_kept(&self, release: &Release, keep_alive: ProgramObject, others: bool) { - let counts = &self.import.device.shared().counts; - let covered = { - let mut kept = lock(&self.import.kept); - match others || kept.is_some() { - true => Some(keep_alive), - false => { - // Counted before the free can take it. - counts.host_keep_alive_kept(); - if self.import.held_inside() { - counts.host_release_held_inside(); - } - *kept = Some(keep_alive); - None - } - } - }; - release.run(); - if let Some(keep_alive) = covered { - counts.host_keep_alive_covered(); - exit_guard::program_release(move || drop(keep_alive)); - } - } - - /// Release the pages to `release` when they go. - pub(super) fn release_to(&self, release: Release) { - // A refused set leaves the deallocator unrun, as a refused call does: never reached, - // since each pages' release is set once, as they become a buffer's. - let _ = self.release.set(release); - } - - /// Hold back their release's deallocator and keep-alive for a recovery that carries their - /// buffer to its device's next generation ([`Release::carry_on`]): `None` where it holds - /// neither, or they have none. - pub(super) fn carry_release(&self) -> Option> { - self.release.get().and_then(Release::carry_on) - } - - /// Their import, which a no-copy buffer made over the same bytes shares. - pub(super) fn import(&self) -> &Arc { - &self.import - } -} - -/// The import of host pages one or more no-copy buffers lie in: a `VkBuffer` over them and the -/// memory imported from them. Every no-copy buffer made over the same bytes as a live one, of -/// its memory class, lies in its import (`host_aliases.rs`): one resource to the driver, as one -/// IOSurface's memory is to Metal. The last hold on it destroys the `VkBuffer` and frees the -/// import (in the release, or on a handler thread where a keep-alive alone waits for the free), -/// but for a releasable one's, which the command buffers that read them hold too -/// (`host_residency.rs`). -pub(super) struct HostImport { - device: Device, - /// Where the bytes lie in its `VkBuffer` and memory: the same in each import of them again. - shape: Shape, - /// Its `VkBuffer` and memory: taken as it goes, to be freed in the release or, where a - /// keep-alive alone waits for the free, on a handler thread. - objects: ManuallyDrop, - /// The [`HostPages`] lying in it. - lying: AtomicUsize, - /// The buffers bound inside its memory now, each with no import of its own ([`Inside`]). - inside: AtomicUsize, - /// The reads other than a blit's that took it, a bit each ([`HostImport::note_read_apart`]): - /// counted in `WorkCounts::host_imports_read_apart` and the gauge of each reason while it - /// lives. - read_apart: AtomicU16, - /// Why the device never releases it while idle, for an import it keeps: counted in that - /// reason's `WorkCounts` gauge while it lives. `None` for a releasable one. - kept_because: Option, - /// A rebind's import that no live buffers' table listed yet ([`ListedPages`]): counted in - /// `WorkCounts::host_imports_rebound_unlisted` until one does or it goes. - unlisted: AtomicBool, - /// The keep-alive of the pages that went while it lived with none other lying in it, dropped - /// once it is freed: it keeps the bytes mapped for every buffer made over them, since all were - /// made over the same bytes, so a later one's keep-alive is dropped as its pages go - /// ([`HostPages`]). - kept: Mutex>>, - /// The releases of pages that went while it lived with no keep-alive: their deallocators - /// run once it is freed. - after_free: Mutex>, - /// Its place among its device's copied host buffers, where its memory is a copy of the - /// caller's pages, not their import (`copied.rs`): unregistered as it goes, before its memory. - copied: OnceLock, - /// The logs of the writes to its pages, where their memory came with one - /// (`dirty_pages::PagesLog`): every buffer lying in it shares them. - log: OnceLock>, - /// The images in place over its pages kept as their textures went, for the next texture over - /// them (`dma_buf/parked.rs`): released as it goes, before what waits for its free. - #[cfg(unix)] - parked_images: crate::dma_buf::parked::ParkedImages, -} - -/// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no -/// `VkBuffer`: the same in each import of them again (`host_residency.rs`). -#[derive(Clone, Copy)] -pub(super) struct Shape { - /// Where the bytes start in the first imported page. - pub(super) offset: u64, - /// Where the buffer's byte 0 lies in its `VkBuffer`. - pub(super) base: u64, - /// The bytes from byte 0 a copy reads ([`Buffer::copy_reach`]). - pub(super) reach: u64, - /// The host address of the first imported byte. - pub(super) mapped: Option, - /// The index of the memory's type. - pub(super) type_index: u32, - /// The pages were imported as dma-bufs (`dma_buf.rs`), not by their pointer. - pub(super) over_dma_buf: bool, - /// The bytes are bound in the device's import of a chunk of a guest RAM (`host_ram.rs`), with - /// no import of their own. - pub(super) in_ram_chunk: bool, - /// The pages were imported through a read-only view of them, which drops the GPU's writes - /// (`read_only_view.rs`). - pub(super) drops_writes: bool, -} - -impl Shape { - /// The shape of `pages`. - pub(super) fn of(pages: &Pages) -> Shape { - let placement = &pages.memory.placement; - Shape { - offset: pages.offset, - base: pages.base, - reach: pages.reach, - mapped: placement.mapped, - type_index: placement.type_index(), - over_dma_buf: placement.over_dma_buf(), - in_ram_chunk: placement.over_ram_chunk(), - drops_writes: placement.over_read_only_view(), - } - } - - /// Whether `other` lays the bytes as this does: an import again of them as their first. - pub(super) fn same(&self, other: &Shape) -> bool { - let at = |shape: &Shape| shape.mapped.map(Mapped::as_ptr); - ( - self.offset, - self.base, - self.reach, - self.type_index, - self.over_dma_buf, - self.in_ram_chunk, - self.drops_writes, - ) == ( - other.offset, - other.base, - other.reach, - other.type_index, - other.over_dma_buf, - other.in_ram_chunk, - other.drops_writes, - ) && at(self) == at(other) - } -} - -/// Why a read other than a blit's took a host import ([`HostImport::note_read_apart`]), each -/// counted once per import in its `WorkCounts::host_imports_read_apart_*` gauge while the import -/// lives. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ReadApart { - /// The buffer's Metal address handed out: `gpu_address`, or written for the caller. - Address, - /// The buffer's `VkBuffer` handed out (`Buffer::vk_buffer`). - VkBuffer, - /// A command's read other than a blit's copy: a binding, `use_resource`, or a copy of a - /// texture over the bytes. - Binding, - /// A texture over the bytes: an image bound to the memory, or a texel view over the - /// `VkBuffer`. - Texture, - /// A buffer bound inside its memory, with a `VkBuffer` of its own (`host_aliases.rs`, "One - /// page, one import"). - Inside, - /// A buffer made to share its buffer's range (`BufferDescriptor::range_of`), its Metal - /// address handed to that buffer. - SharedRange, - /// A no-copy heap's own bytes lying in it ([`Joining::Heap`]). - Heap, - /// A rebound buffer lying in it ([`Joining::Rebound`]). - Rebound, - /// No thread to release it while idle (`host_residency.rs`). - Unreleased, -} - -impl ReadApart { - /// How many reasons there are. - pub(crate) const COUNT: usize = 9; - const ALL: [ReadApart; ReadApart::COUNT] = [ - ReadApart::Address, - ReadApart::VkBuffer, - ReadApart::Binding, - ReadApart::Texture, - ReadApart::Inside, - ReadApart::SharedRange, - ReadApart::Heap, - ReadApart::Rebound, - ReadApart::Unreleased, - ]; - - /// Its bit in [`HostImport::read_apart`]. - fn bit(self) -> u16 { - 1 << self as u16 - } -} - -/// Why the device keeps a host import imported whatever reads it, never releasing it while idle -/// (`host_residency.rs`), each counted in its `WorkCounts::host_imports_kept_*` gauge while the -/// import lives. Imports of dma-bufs kept as their descriptors did not fit count apart -/// (`WorkCounts::host_imports_kept_for_fds`), as pointer imports here. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum KeptBecause { - /// A heap's own import. - Heap, - /// A rebind's import (`rebind.rs`). - Rebind, - /// An import by pointer on a device whose submission checks did not find a held pointer - /// import to cost every submission (`submit_check.rs`), or made before they answered, or off - /// Unix. - Pointer, - /// No stand-in buffer for a read of a released one. - NoStandIn, -} - -impl KeptBecause { - /// How many reasons there are. - pub(crate) const COUNT: usize = 4; -} - -/// A host import's `VkBuffer` and memory. -enum Objects { - /// Imported until the import goes. - Fixed(Imported), - /// Released while idle, and imported again at the next read (`host_residency.rs`). - Releasable(Residency), -} - -/// A host import's `VkBuffer` and memory as one read takes them: borrowed from an import that -/// keeps them, or held, from one that may release them, for as long as the read lasts. -pub(super) enum ImportPages<'a> { - Fixed(&'a Pages), - Held(Arc), - /// The device's stand-in, which a read of a released import takes where the device cannot - /// import it again ([`HostImport::pages`]). - StandIn(Arc), -} - -impl std::ops::Deref for ImportPages<'_> { - type Target = Pages; - - fn deref(&self) -> &Pages { - match self { - ImportPages::Fixed(pages) => pages, - ImportPages::Held(imported) => &imported.pages, - ImportPages::StandIn(stand_in) => &stand_in.pages, - } - } -} - -impl HostImport { - /// The import of `pages`, no pages lying in it yet, which the device keeps imported for - /// `because` (`None`: an import of dma-bufs whose descriptors did not fit, counted as such, - /// or pages bound in a guest RAM's chunk imported as a dma-buf, which the RAM's use keeps). - fn new(device: &Device, pages: Pages, because: Option) -> HostImport { - if let Some(because) = because { - device.shared().counts.host_import_kept(because, true); - } - let unlisted = because == Some(KeptBecause::Rebind); - if unlisted { - device.shared().counts.host_import_rebound_unlisted(true); - } - HostImport { - device: device.clone(), - shape: Shape::of(&pages), - objects: ManuallyDrop::new(Objects::Fixed(Imported::new(device, pages))), - lying: AtomicUsize::new(0), - inside: AtomicUsize::new(0), - read_apart: AtomicU16::new(0), - kept_because: because, - unlisted: AtomicBool::new(unlisted), - kept: Mutex::new(None), - after_free: Mutex::new(Vec::new()), - copied: OnceLock::new(), - log: OnceLock::new(), - #[cfg(unix)] - parked_images: Default::default(), - } - } - - /// The import of `pages`, no pages lying in it yet, which the device releases while idle and - /// `again` imports again (`host_residency.rs`). - fn releasable( - device: &Device, - pages: Pages, - again: Again, - stand_in: Arc, - ) -> HostImport { - HostImport { - device: device.clone(), - shape: Shape::of(&pages), - objects: ManuallyDrop::new(Objects::Releasable(Residency::new( - device, pages, again, stand_in, - ))), - lying: AtomicUsize::new(0), - inside: AtomicUsize::new(0), - read_apart: AtomicU16::new(0), - kept_because: None, - unlisted: AtomicBool::new(false), - kept: Mutex::new(None), - after_free: Mutex::new(Vec::new()), - copied: OnceLock::new(), - log: OnceLock::new(), - #[cfg(unix)] - parked_images: Default::default(), - } - } - - /// The images parked under it (`dma_buf/parked.rs`). - #[cfg(unix)] - pub(super) fn parked_images(&self) -> &crate::dma_buf::parked::ParkedImages { - &self.parked_images - } - - /// A live buffers' table listed pages lying in it ([`ListedPages`]): a rebind's import is - /// listed from now on (`WorkCounts::host_imports_rebound_unlisted`). A load once listed. - fn note_listed(&self) { - if self.unlisted.load(Ordering::Relaxed) && self.unlisted.swap(false, Ordering::Relaxed) { - (self.device.shared().counts).host_import_rebound_unlisted(false); - } - } - - /// Whether a buffer bound inside its memory lives now ([`Inside`]): it holds the import past - /// the release of the pages lying in it. - fn held_inside(&self) -> bool { - self.inside.load(Ordering::Acquire) > 0 - } - - /// Its memory is a copy of the caller's pages, registered as `copied` (`copied.rs`), not - /// their import. - pub(super) fn set_copied(&self, copied: crate::copied::Copied) { - // Set once, as the copied buffer is made. - let _ = self.copied.set(copied); - } - - /// Whether its memory is a copy of the caller's pages (`copied.rs`), not their import. - pub(super) fn copied(&self) -> bool { - self.copied.get().is_some() - } - - /// Whether it is an import of dma-bufs of the pages (`dma_buf.rs`), not of their pointer nor - /// a copy of them. - pub(super) fn over_dma_buf(&self) -> bool { - self.shape.over_dma_buf && !self.copied() - } - - /// Whether its memory is a copy of the caller's pages that drops the GPU's writes, as the - /// process cannot write them (`copied.rs`). - pub(super) fn copy_drops_writes(&self) -> bool { - self.copied - .get() - .is_some_and(|copied| copied.drops_writes()) - } - - /// Where the bytes start in its first page: their offset in their host page for an import of - /// them, 0 for a copied host buffer's copy, which lays them from its first byte. - pub(super) fn offset(&self) -> u64 { - self.shape.offset - } - - /// Keep the logs of the writes to its pages (set once, as its first buffer is made), which - /// its copy, where it is one, reports its merges back to (`copied.rs`). - pub(super) fn keep_log(&self, log: Arc) { - if let Some(copied) = self.copied.get() { - copied.set_log(&log); - } - self.device.shared().dirty.note_logged(); - let _ = self.log.set(log); - } - - /// Whether its pages were imported through a read-only view of them, which drops the GPU's - /// writes (`read_only_view.rs`). - pub(super) fn drops_writes(&self) -> bool { - self.shape.drops_writes - } - - /// Its residency, where the device may release it while idle. - pub(super) fn residency(&self) -> Option<&Residency> { - match &*self.objects { - Objects::Fixed(_) => None, - Objects::Releasable(residency) => Some(residency), - } - } - - /// Its `VkBuffer` and memory for a read other than a blit's, for `reason`, which keeps a - /// releasable import imported for good from then on (`host_residency.rs`). Released, it is imported again - /// first; where the device cannot, the device is lost (its work no longer runs) and the read - /// takes the device's stand-in. - pub(super) fn pages(&self, reason: ReadApart) -> ImportPages<'_> { - self.note_read_apart(reason); - match &*self.objects { - Objects::Fixed(imported) => ImportPages::Fixed(&imported.pages), - Objects::Releasable(residency) => match residency.exposed() { - Some(held) => ImportPages::Held(held), - None => { - // No work that read it runs on a lost device. - self.device.mark_lost(); - self.device.shared().counts.host_import_lost(); - ImportPages::StandIn(residency.stand_in()) - } - }, - } - } - - /// Its `VkBuffer` and memory for a blit's command (`Buffer::blit_at`), imported again where - /// released, with what the command buffer holds of them (`rebind::ImportHold`): nothing of an - /// import that keeps them. Refused where the device cannot import them again. - pub(super) fn blit_pages(&self) -> Result<(ImportPages<'_>, Option), Error> { - match &*self.objects { - Objects::Fixed(imported) => Ok((ImportPages::Fixed(&imported.pages), None)), - Objects::Releasable(residency) => { - let held = residency.for_blit()?; - let hold = ImportHold::Held(Arc::clone(&held)); - Ok((ImportPages::Held(held), Some(hold))) - } - } - } - - /// Its `VkBuffer` and memory for a live-table listing (`live_buffers.rs`), which reads them - /// without exposing them: `None` while a releasable import is released. - fn listing(&self) -> Option> { - match &*self.objects { - Objects::Fixed(imported) => Some(ImportPages::Fixed(&imported.pages)), - Objects::Releasable(residency) => residency.listing().map(ImportPages::Held), - } - } - - /// Keep it imported for good from now on, for `reason` (`host_residency.rs`): whether it was - /// ever released, so a range of it noted before may be stale. - pub(super) fn expose(&self, reason: ReadApart) -> bool { - self.note_read_apart(reason); - match &*self.objects { - Objects::Fixed(_) => false, - Objects::Releasable(residency) => residency.expose(), - } - } - - /// Note a read other than a blit's, for `reason` ([`HostImport::pages`], - /// [`HostImport::expose`]): the reads after which the device's residency keeps a releasable - /// import for good (`host_residency.rs`), noted for an import of any kind, counted once while - /// it lives (`WorkCounts::host_imports_read_apart`), and once for each reason. A load once - /// noted. - fn note_read_apart(&self, reason: ReadApart) { - let bit = reason.bit(); - if self.read_apart.load(Ordering::Relaxed) & bit != 0 { - return; - } - let before = self.read_apart.fetch_or(bit, Ordering::Relaxed); - if before & bit != 0 { - return; - } - let counts = &self.device.shared().counts; - if before == 0 { - counts.host_import_read_apart(true); - } - counts.host_import_read_apart_for(reason, true); - } - - /// A no-copy buffer made over its bytes came to lie in it beside another - /// ([`Joining::Buffer`]): counted where it is releasable still, which it stays - /// (`WorkCounts::host_imports_joined_releasable`, `host_residency.rs`). - fn note_joined(&self) { - if self.residency().is_some_and(Residency::releasable) { - (self.device.shared().counts).host_import_joined_releasable(); - } - } -} - -impl Device { - /// On a device that keeps MoltenVK's residency set (`argument_buffers.rs`), a line to the - /// device's message sink (`Verbose`, id name `metal2vulkan-host-import-freed`) for a host - /// import of `bytes` freed: MoltenVK removes its buffer from the set and commits the set at - /// once, with the submissions in flight on the device's queues it names. Elsewhere nothing, - /// and nothing made where the sink hears no `Verbose` message - /// (`MessageSink::with_least_severity`). - pub(super) fn note_import_freed(&self, bytes: u64) { - let severity = super::MessageSeverity::Verbose; - let shared = self.shared(); - let Some(sink) = (shared.instance.sink()).filter(|sink| sink.hears(severity)) else { - return; - }; - let facts = super::device::argument_buffers::Facts::of(&self.properties().description); - if !facts.keeps_residency_set() { - return; - } - let in_flight: usize = shared - .relayed_queues() - .map(|(_, flights)| flights.in_flight()) - .sum(); - sink.deliver(&super::DebugMessage { - severity, - kind: super::MessageKind { - general: true, - ..super::MessageKind::default() - }, - id_name: "metal2vulkan-host-import-freed".into(), - id: 0, - text: format!( - "metal2vulkan: a host import of {bytes} bytes freed with {in_flight} submissions \ - in flight on the device's queues: MoltenVK removes it from its device-wide \ - residency set and commits the set" - ), - degradation: None, - }); - } -} - -impl Drop for HostImport { - fn drop(&mut self) { - // A copy leaves its device's comparisons before its memory can go (`copied.rs`). - drop(self.copied.take()); - // The Vulkan teardown is a section of the exit guard. - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the pages stay imported to its end (`exit_guard`), so no - // deallocator runs and no keep-alive goes. - for release in lock(&self.after_free).iter() { - release.keep(); - } - if let Some(kept) = lock(&self.kept).take() { - std::mem::forget(kept); - } - // SAFETY: dropped once, here, and never read again; its free finds the exit too. - unsafe { ManuallyDrop::drop(&mut self.objects) }; - return; - }; - let shared = self.device.shared(); - let read_apart = self.read_apart.load(Ordering::Relaxed); - if read_apart != 0 { - shared.counts.host_import_read_apart(false); - } - for reason in ReadApart::ALL { - if read_apart & reason.bit() != 0 { - shared.counts.host_import_read_apart_for(reason, false); - } - } - if let Some(because) = self.kept_because { - shared.counts.host_import_kept(because, false); - } - if self.unlisted.load(Ordering::Relaxed) { - shared.counts.host_import_rebound_unlisted(false); - } - drop(busy); - // The images parked under it go first: their imports are of its pages too, which the - // keep-alive and the deallocators below let go of (`dma_buf/parked.rs`). - #[cfg(unix)] - crate::dma_buf::parked::release(self.parked_images.take_where(|_| true)); - // Once freed, the keep-alive goes, and the deallocators that waited for the free run. - let kept = lock(&self.kept).take(); - if kept.is_some() { - shared.counts.host_keep_alive_freed(); - } - let releases: Vec = lock(&self.after_free).drain(..).collect(); - let delayed = releases - .iter() - .find(|release| release.deallocates()) - .map(Release::length); - // The free goes off the releasing thread only where a keep-alive (a runtime extension - // whose drop tells the caller the pages may go) alone waits for it. A deallocator waiting - // for it runs in the release, as Metal runs it there (an M3 Max under macOS 27.0.1 ran an - // unused buffer's deallocator inside its final release, on the releasing thread, every - // time). With nothing waiting the caller may unmap the pages once the release returns, and - // `VK_EXT_external_memory_host` requires the imported range to stay valid for the imported - // memory's whole life (`VkImportMemoryHostPointerInfoEXT`), so the free is made here too. - let posts = - delayed.is_none() && (kept.is_some() || releases.iter().any(Release::keeps_alive)); - // A completed command buffer's release that lets go of the import last, while a - // deallocator or a keep-alive waits for its free, posts the free to the device's free - // thread, which paces it (`free_thread.rs`): NVIDIA's driver holds every other thread's - // `vkQueueSubmit` while it frees memory (docs/FAST-PATHS.md, known gaps), and the caller - // learns that the pages may go from what waits, which goes there after the free. - let waits = delayed.is_some() || posts; - let paced = waits && crate::free_thread::posts_imports(); - let left = AfterImport { - after: Box::new(AfterFree { kept, releases }), - delayed, - waits, - }; - // SAFETY: taken once, here, as the import goes, and never read again. - let objects = unsafe { ManuallyDrop::take(&mut self.objects) }; - let (going, frees): (Box, bool) = match objects { - // No pending command buffer uses the pages: one whose commands used them holds them - // until it completed (`rebind.rs`), one that may read a texture's image over them - // holds the image, which holds the import (`heap_sets.rs`), and every buffer over them - // let go of them. - Objects::Fixed(mut imported) => { - imported.leave(left); - if posts || paced { - imported.hold_for_release(); - } - (Box::new(imported), true) - } - // Its objects go with their last holder, here or the last command buffer that read - // them (a blit's, which holds them and not the buffer once a rebind or detach - // replaced its pages), and what waits for the free with them: a driver may list a - // pointer import's memory in every submission, which fails where its pages were - // unmapped. - Objects::Releasable(residency) => match residency.let_go() { - Some(mut held) => { - held.leave(left); - // Where a command buffer's blit holds them still, that command buffer holds - // the device as the program's, and they go with it. - if posts || paced { - if let Some(imported) = Arc::get_mut(&mut held) { - imported.hold_for_release(); - } - } - (Box::new(held), true) - } - // Released: nothing to free. - None => (left.after, false), - }, - }; - let going = match paced && frees { - true => match post_free(shared, going) { - Ok(()) => return, - Err(going) => going, - }, - false => going, - }; - if posts { - shared.counts.host_import_release_posted(); - // A tuple drops in order: the release, then its count. The release's own handles of - // the device are holders' (the count's, the import's, and its dma-buf imports' where - // it alone holds them), which the program's last drop waits for - // (`device/holds.rs`): so a program that let go of such a buffer, then of the device, - // finds the device gone as that drop returns. - let posted = (going, PostedDone(self.device.held_for_release())); - self.device.let_go_elsewhere(Box::new(posted)); - } else { - drop(going); - } - } -} - -/// Post `objects`, a host import's going at a completed command buffer's release while a -/// deallocator or a keep-alive waits for their free, each handle of the device they hold a -/// holder's, to the device of `shared`'s free thread (`free_thread.rs`, -/// `WorkCounts::host_import_frees_posted`); given back where it refused them. -fn post_free(shared: &DeviceShared, objects: Box) -> Result<(), Box> { - let posted = crate::free_thread::PostedImport { - objects, - holds: Arc::clone(&shared.holds), - }; - (shared.frees.post_import(posted)).map_err(|posted| posted.objects) -} - -/// Counts a host import's release posted to a handler thread (a keep-alive alone waiting for its -/// free) run as it drops, after the release. -struct PostedDone(Device); - -impl Drop for PostedDone { - fn drop(&mut self) { - self.0.shared().counts.host_import_release_done(); - } -} - -/// A host import's `VkBuffer` and memory, which the last holder lets go of, destroying the -/// `VkBuffer` and freeing the memory: the import's own, and a releasable import's, held by the -/// import while it is imported and by each command buffer whose blit read them until it completed -/// (`EncoderCore::blit_at`, `host_residency.rs`). -pub(super) struct Imported { - device: Device, - pub(super) pages: Pages, - /// What goes once its memory is freed, which the import left as it went ([`Imported::leave`]). - after: Mutex>, -} - -/// What a going import leaves with its objects ([`Imported::leave`]): the caller's keep-alive and -/// deallocators, which go once the memory is freed, the length of a deallocator's pages, -/// announced where the free waits for the batches in flight, and whether a deallocator or a -/// keep-alive waits for the free (a completed command buffer that lets go of the objects last -/// posts their free to the free thread then, `rebind::ImportHold`). -pub(super) struct AfterImport { - after: Box, - delayed: Option, - waits: bool, -} - -impl Imported { - /// The objects of `pages`, imported now. - pub(super) fn new(device: &Device, pages: Pages) -> Imported { - Imported { - device: device.clone(), - pages, - after: Mutex::new(None), - } - } - - /// Leave `left` to go once the memory is freed, the import going. - fn leave(&self, left: AfterImport) { - *lock(&self.after) = Some(left); - } - - /// Whether the import went, leaving what waits for the free ([`Imported::leave`]), and a - /// deallocator or a keep-alive among it: its free may go to the free thread then. - pub(super) fn waits_for_free(&mut self) -> bool { - let after = self.after.get_mut().unwrap_or_else(PoisonError::into_inner); - after.as_ref().is_some_and(|after| after.waits) - } - - /// Post the free of `imported`, a completed command buffer's release letting go of it last, - /// to its device's free thread where a deallocator or a keep-alive waits for it - /// (`rebind::ImportHold`); else, or where the thread refuses it, free it here. - pub(super) fn let_go_at_completion(mut imported: Imported) { - if !(crate::free_thread::posts_imports() && imported.waits_for_free()) { - drop(imported); - return; - } - imported.hold_for_release(); - let device = imported.device.clone(); - if let Err(objects) = post_free(device.shared(), Box::new(imported)) { - drop(objects); - } - } - - /// Hold the device through a handle the program's last drop waits for, in place of its own - /// ([`Device::held_for_release`]), and so the dma-buf imports its pages lie in where they - /// alone hold them: the import going, these objects go in a release posted to a handler - /// thread or the free thread. - fn hold_for_release(&mut self) { - self.device = self.device.held_for_release(); - #[cfg(unix)] - self.pages.memory.placement.hold_dma_buf_for_release(); - } -} - -impl Drop for Imported { - fn drop(&mut self) { - let left = (self.after.get_mut()) - .unwrap_or_else(PoisonError::into_inner) - .take(); - let (after, delayed) = match left { - Some(AfterImport { after, delayed, .. }) => (Some(after), delayed), - None => (None, None), - }; - // SAFETY: no pending command buffer uses them: an import's own go as the import goes - // (`HostImport::drop`), a releasable import's as the last command buffer whose blit read - // them completed, and no other read reached them (`host_residency.rs`). - match unsafe { self.pages.release_import(&self.device, after) } { - // Freed now: what waited goes here, or, for imports of the caller's dma-bufs, once - // their last holder (these pages' placement, as it drops after this) frees them. - Some(after) => self.pages.after_free(after), - // Its memory waits for the batches in flight (`freed_memory.rs`), and what the import - // left with it, past Metal's release. - None => { - if let Some(length) = delayed { - deallocator_delayed(&self.device, length); - } - } - } - } -} - -/// Count and announce once that a deallocator of a no-copy buffer of `length` bytes waits for -/// the batches submitted before its release (`freed_memory.rs`): its import's memory, freed, -/// waits for them, and the deallocator with it. -fn deallocator_delayed(device: &Device, length: u64) { - device.shared().counts.host_deallocator_delayed(); - device.degrade_once(Degradation::HostDeallocatorDelayed, || { - ( - format!("a no-copy buffer of {length} bytes"), - "its pages' import, freed, waits for the batches submitted before its release: the \ - device's driver fails pending work whose pipelines read device addresses where \ - such memory is freed, and the caller gave no keep-alive" - .to_owned(), - ) - }); -} - -/// A buffer's hold on the live import of host pages it is bound inside, with no import of its own -/// (`host_aliases.rs`, "One page, one import"; `Placement::in_import`, whose clones share -/// it): counted in the import's `inside` while it lives, so that a release of another buffer's -/// pages that the import outlives for it is counted (`WorkCounts::host_releases_held_inside`) -/// and named in its announcement. -pub(super) struct Inside(Arc); - -impl Inside { - /// A hold on `import` for a buffer bound inside its memory. - pub(super) fn new(import: Arc) -> Inside { - import.inside.fetch_add(1, Ordering::AcqRel); - Inside(import) - } -} - -impl Drop for Inside { - fn drop(&mut self) { - // Before the hold goes: the import may go with it. - self.0.inside.fetch_sub(1, Ordering::AcqRel); - } -} - -/// What goes once a host import's memory is freed: the keep-alive of the pages that went while it -/// lived, and the deallocators that waited for the free, each panic caught. It waits with the -/// memory where that waits for the batches in flight (`freed_memory.rs`). -struct AfterFree { - kept: Option>, - releases: Vec, -} - -impl Drop for AfterFree { - fn drop(&mut self) { - let kept = self.kept.take(); - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the pages stay imported to its end (`exit_guard`), so no - // deallocator runs and no keep-alive goes. - for release in &self.releases { - release.keep(); - } - if let Some(kept) = kept { - std::mem::forget(kept); - } - return; - }; - drop(busy); - if let Some(keep_alive) = kept { - exit_guard::program_release(move || drop(keep_alive)); - } - for release in &self.releases { - release.run(); - } - } -} - -impl Drop for HostPages { - fn drop(&mut self) { - // No command writes their copy through them from now on (`copied.rs`). - if let (Some(key), Some(copied)) = (self.named.get(), self.import.copied.get()) { - copied.unname(*key); - } - // The images and views a rebind or a detach parked go first: they may hold the import. - lock(&self.parked).clear(); - let others = self.import.lying.fetch_sub(1, Ordering::AcqRel) > 1; - let Some(release) = self.release.take() else { - return; - }; - // The exit guard runs no deallocator and drops no keep-alive. - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the pages stay imported to its end (`exit_guard`). - release.keep(); - return; - }; - drop(busy); - let import = &self.import; - match release.keep_alive() { - // The caller's keep-alive keeps the pages mapped until the import is freed: the - // deallocator runs now, at Metal's moment. Where another buffer lies in the import, - // or the import keeps another's keep-alive, that keeps the same bytes mapped until it - // is freed: this one goes now too, after the deallocator, which may read the bytes. (A - // buffer released while a table listed its pages ran this at its release, - // `released_listed`, and left the import a keep-alive: none is left here.) - Some(keep_alive) => self.run_kept(&release, keep_alive, others), - // Another buffer lies in the import, whose contract keeps the pages mapped: the - // deallocator runs now, as with an import of its own (`host_aliases.rs`). - None if others => release.run(), - // The deallocator runs once the import is freed: as these pages let go of it below, - // where nothing else holds it; else later, announced. - None => { - if release.deallocates() && Arc::strong_count(import) > 1 { - let counts = &import.device.shared().counts; - counts.host_deallocator_delayed(); - let inside = import.held_inside(); - if inside { - counts.host_release_held_inside(); - } - let length = release.length(); - import - .device - .degrade_once(Degradation::HostDeallocatorDelayed, || { - let held = match inside { - true => { - "a buffer bound inside its pages' import, over part of its \ - bytes or the same bytes as memory of another class, still \ - lives as it is released (one live import of a page: \ - VK_EXT_external_memory_host leaves a page imported twice \ - undefined)" - } - false => { - "its pages' import is still held as it is released (a \ - texture over them may still be read through its resource \ - ID by a command buffer submitted before the texture's \ - release)" - } - }; - ( - format!("a no-copy buffer of {length} bytes"), - format!("{held}, and the caller gave no keep-alive"), - ) - }); - } - lock(&import.after_free).push(release); - } - } - } -} - -impl Pages { - /// The placement the pages are bound in: what a buffer bound inside their import binds in - /// (`Device::bind_in_import`). - pub(super) fn placement(&self) -> &Placement { - &self.memory.placement - } - - /// Destroy the `VkBuffer` of a host import's pages and free their memory, on `device`, once - /// their sparse binding completed, and note it (`Device::note_import_freed`): an import's - /// last hold lets go. Left to the process's end while it exits. `after` goes once the memory - /// is freed: given back for the caller to let go of ([`after_free`](Self::after_free)), - /// unless it waits with the memory for the batches in flight (`freed_memory.rs`). - /// - /// # Safety - /// - /// No pending command buffer uses the pages, and nothing else frees them. - pub(super) unsafe fn release_import( - &self, - device: &Device, - after: Option>, - ) -> Option> { - // The Vulkan teardown is a section of the exit guard. - let Some(busy) = exit_guard::enter() else { - return after; - }; - let shared = device.shared(); - // A submission that used the pages waited for their sparse binding: waited for here where - // none did. - self.memory.placement.settle(); - // SAFETY: the caller's. - unsafe { release::object(shared.vk(), self.raw) }; - let after = lock(&shared.memory).release_then(shared.vk(), &self.memory.placement, after); - drop(busy); - device.note_import_freed(self.memory.placement.size()); - after - } - - /// Let `after` go once the pages' memory is freed, their import released - /// ([`release_import`](Self::release_import)): at once, but where the memory is imports of - /// the caller's dma-bufs (`dma_buf.rs`), which the placement holds and are freed as their - /// last holder lets go of them, then. Pages bound in a guest RAM's chunk (`host_ram.rs`) free - /// no memory of their own, whatever the chunk's import: at once. - fn after_free(&self, after: Box) { - #[cfg(unix)] - { - let placement = &self.memory.placement; - if let Some(imports) = placement - .dma_buf_pages() - .filter(|_| !placement.over_ram_chunk()) - { - imports.after_free(after); - return; - } - } - drop(after); - } -} - -/// A buffer's bound memory: its placement, and its Vulkan device address where the device -/// enables `bufferDeviceAddress`. -pub(super) struct Bound { - pub(super) placement: Placement, - pub(super) device_address: Option, -} - -impl OwnBytes { - /// `f` of the pages the buffer lies in now: a detached buffer's stand-in (`Detached`). A - /// read of a no-copy buffer's import other than a blit's, for `reason`, which keeps it - /// imported for good (`HostImport::pages`). - fn with(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> R { - match &self.lie { - Lie::Fixed(fixed) => f(&fixed.pages), - Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => f(&pages.import.pages(reason)), - Lying::Detached(detached) => f(&detached.pages), - Lying::Gone(_) => read_gone(), - }, - } - } - - /// [`with`](Self::with) while the buffer lies in pages: `None` while it is detached. - fn with_attached(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> Option { - match &self.lie { - Lie::Fixed(fixed) => Some(f(&fixed.pages)), - Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => Some(f(&pages.import.pages(reason))), - Lying::Detached(_) | Lying::Gone(_) => None, - }, - } - } - - /// Where the bytes lie in the pages the buffer lies in now ([`Shape`]), read without their - /// `VkBuffer`. - fn shape(&self) -> Shape { - match &self.lie { - Lie::Fixed(fixed) => Shape::of(&fixed.pages), - Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => pages.import.shape, - Lying::Detached(detached) => Shape::of(&detached.pages), - Lying::Gone(shape) => shape, - }, - } - } -} - -/// A `Managed` buffer's host copy on a device without unified memory, which `contents` maps and -/// `did_modify_range` and `synchronize_resource` copy to and from (`managed.rs`): the runtime's -/// own ([`Mirror`]), for a buffer the runtime makes, or the caller's pages, for a no-copy buffer -/// (`managed_copy.rs`'s [`CallerCopy`]). -pub(super) enum HostCopy { - Own(Arc), - Caller(Arc), -} - -/// What a copy from a buffer's host copy into its own bytes replaces, which says the batch that -/// takes it (`texture/first_move.rs`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Replaces { - /// Bytes no command buffer can have read: the buffer's making, or its device copy's making - /// on a recovery's new `VkDevice`. Taken as a new buffer's first fill is - /// (`FirstMoves::register_bytes`; on a device without a fill queue, by the device's next - /// submission, whatever its commands reach), so what it copies from (an import of the - /// caller's pages, a staging buffer, the host copy) is held no longer than that. - Unread, - /// Bytes the program's command buffers may have read already, with the stamp of the commit - /// that took the range (`managed.rs`; 0 where none did: a completion's undo, a rebind): only - /// a batch whose commands may reach the buffer takes it, of a command buffer committed at or - /// after that commit (`FirstMoves::register_upload`). - Read(u64), -} - -/// Register with `device`'s first work the copy of `length` bytes of `source` onto `keeper`'s -/// bytes at `onto` (its `VkBuffer`, and where), `held` until the submission that makes it -/// completed, for the batch `replaces` says: whether it staged its bytes and the copies staged now -/// passed their bound (`texture/first_move.rs`, **Bounded**). -fn register_copy_in( - device: &Device, - keeper: Weak, - (onto, source): ((vk::Buffer, u64), (vk::Buffer, u64)), - length: u64, - held: Keeps, - replaces: Replaces, -) -> bool { - let keeper: Weak = keeper; - let moves = &device.shared().textures.first_moves; - match replaces { - Replaces::Unread => moves.register_bytes(keeper, onto, source, length, held), - Replaces::Read(commit) => moves.register_upload(keeper, onto, source, length, held, commit), - } -} - -/// A `Managed` buffer's host copy on a device without unified memory (`managed.rs`): a -/// `VkBuffer` of the buffer's padded length in host-visible, coherent memory, cached where the -/// device has such ([`MemoryClass::Managed`]), which `contents` maps. The GPU uses the buffer's -/// own `VkBuffer`, in device-local memory: Metal's two copies of a managed resource on a device -/// without unified memory, which `did_modify_range` and `synchronize_resource` copy between. -/// Released as the last holder lets it go: its buffer, or a submission that uploads from it. -pub(super) struct Mirror { - raw: vk::Buffer, - placement: Placement, - /// The device it releases its `VkBuffer` and memory into. - device: Device, -} - -impl Drop for Mirror { - fn drop(&mut self) { - // The Vulkan teardown is a section of the exit guard. - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the host copy and its memory are left to its end. - return; - }; - // SAFETY: no pending command uses the host copy: its buffer is gone, and so is every - // submission that uploads from it (each holds it), and a command buffer that copies into - // it holds the buffer. - unsafe { release_mirror(self.device.shared(), self) }; - drop(busy); - } -} - -/// The bytes of a heap a buffer placed in it is: its heap's buffer's from `offset`, a multiple of -/// [`PLACEMENT_ALIGNMENT`](super::heap::PLACEMENT_ALIGNMENT). -struct HeapBytes { - heap: Heap, - /// The heap's own buffer. - bytes: Buffer, - offset: u64, - /// `makeAliasable` was called: an automatic heap's range is free for other resources. Shared - /// by the buffer's parts on each generation its device's recovery carried it to - /// (`Buffer::carry_placed`). - aliasable: Arc, -} - -/// Who owns a buffer's bytes. -pub(super) enum Owner { - /// The runtime: the sub-allocator's memory. - Runtime, - /// The caller: host memory a no-copy buffer wraps ([`HostPages`]), released to its - /// deallocator if it gave one. - Caller, - /// The caller: a `VkBuffer` and the memory it is bound to, which the caller made and keeps - /// (`wrapped_buffer.rs`). The runtime destroys and frees neither. - Vulkan { - /// The caller made it concurrent with the copy engine's queue family, the copy queue's - /// (`Device::new_command_queue_for_copies`), whose commands may then use it. - copy_engine: bool, - }, -} - -/// Whose memory a buffer's bytes are, where they are the caller's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum CallerMemory { - /// Host memory a no-copy buffer imported (`host_memory.rs`). - HostPages, - /// The memory the caller's own `VkBuffer` is bound to (`wrapped_buffer.rs`). - VkBuffer, -} - -impl BufferShared { - /// [`Buffer::memory_hold`]. - fn memory_hold(&self) -> Option { - match &self.bytes { - Bytes::Own(own) => match &own.lie { - Lie::Fixed(fixed) => Some(MemoryHold::Fixed { - _pages: Arc::clone(fixed), - }), - Lie::Host(cell) => cell.current().map(|host| MemoryHold::Host { - _import: Arc::clone(host.import()), - }), - }, - Bytes::Heap(heap) => heap.bytes.memory_hold(), - } - } -} - -impl Filled for BufferShared { - fn memory(&self) -> Option> { - self.memory_hold() - .map(|memory| Box::new(memory) as Box) - } - - /// Its identity's key (`Buffer::identity`): a buffer placed in a heap has the heap's own - /// buffer's. - fn key(&self) -> Option { - Some(match &self.bytes { - Bytes::Own(own) => own.identity.key, - Bytes::Heap(placed) => placed.bytes.identity().key, - }) - } -} - -impl Buffer { - /// What a failed submission's line states of the buffer (`submit_failure.rs`): its identity, - /// length and storage mode, whether its `VkBuffer` or memory was handed out, and where its - /// bytes lie (a heap's range, its memory with `types`' flags for its type, the caller's - /// `VkBuffer`, or a no-copy buffer's host pages and their import), and how that stands: read - /// without waiting for any lock and with no import made again. - pub(super) fn failure_facts(&self, types: &TypeFlags) -> (String, Standing) { - let s = self.s(); - let mut facts = format!( - "buffer #{} of {} bytes, {:?}", - s.object_id.get(), - s.length, - self.storage_mode(), - ); - if s.handed_out.load(Ordering::Relaxed) { - facts.push_str(", handed out"); - } - let standing = match &s.bytes { - Bytes::Heap(placed) => { - let heap = placed.heap.object_id().get(); - facts.push_str(&format!(", in heap #{heap} at {}", placed.offset)); - Standing::Held - } - Bytes::Own(own) => match &own.lie { - Lie::Fixed(fixed) => { - facts.push_str(", "); - facts.push_str(&fixed.pages.memory.placement.failure_facts(types)); - if matches!(own.owner, Owner::Vulkan { .. }) { - facts.push_str(", the caller's VkBuffer"); - } - match fixed.released.load(Ordering::Acquire) { - true => { - facts.push_str(", RELEASED with its lost generation"); - Standing::Released - } - false => Standing::Held, - } - } - Lie::Host(cell) => cell.failure_facts(&mut facts, types), - }, - }; - (facts, standing) - } -} - -impl HostCell { - /// [`Buffer::failure_facts`] of a no-copy buffer's pages, added to `facts`. - fn failure_facts(&self, facts: &mut String, types: &TypeFlags) -> Standing { - facts.push_str(", no-copy"); - if self.drops_writes { - facts.push_str(", its GPU writes dropped"); - } - let Some(lying) = try_lock(&self.pages) else { - facts.push_str(", its pages busy"); - return Standing::Held; - }; - match &*lying { - Lying::In(pages) => pages.import.failure_facts(facts, types), - Lying::Detached(_) => { - facts.push_str(", DETACHED"); - Standing::Released - } - Lying::Gone(_) => { - facts.push_str(", its pages GONE with its lost generation"); - Standing::Gone - } - } - } -} - -impl HostImport { - /// [`Buffer::failure_facts`] of the import a no-copy buffer's pages lie in, added to - /// `facts`: what it imported, its memory, and whether it is released now - /// (`host_residency.rs`). - fn failure_facts(&self, facts: &mut String, types: &TypeFlags) -> Standing { - let shape = &self.shape; - let what = match (self.copied(), shape.over_dma_buf, shape.in_ram_chunk) { - (true, _, _) => "a copy of the caller's pages", - (false, true, _) => "the caller's pages as dma-bufs", - (false, false, true) => "the caller's pages in a guest RAM chunk's import", - (false, false, false) => "the caller's pages by their pointer", - }; - facts.push_str(", over "); - facts.push_str(what); - match &*self.objects { - Objects::Fixed(imported) => { - facts.push_str(", imported for good: "); - facts.push_str(&imported.pages.memory.placement.failure_facts(types)); - Standing::Held - } - Objects::Releasable(residency) => { - facts.push_str(", releasable, memory "); - facts.push_str(&types.of(shape.type_index)); - match residency.held_now() { - Some(true) => { - facts.push_str(", imported now"); - Standing::Held - } - Some(false) => { - facts.push_str(", RELEASED now"); - Standing::Released - } - None => { - facts.push_str(", its residency busy"); - Standing::Held - } - } - } - } - } -} - -impl BufferShared { - /// Its parts on its lost generation were marked let go of, the buffer carried to the next one - /// and that generation at rest (`LostBuffer::mark`): no call takes them from now on - /// ([`Buffer::held_parts`]), and they go once none under way holds them. - fn released(&self) -> bool { - match &self.bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.released.load(Ordering::Acquire), - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => cell.released.load(Ordering::Acquire), - Bytes::Heap(_) => false, - } - } - - /// Whether its parts on a lost generation went (`FixedPages::release_lost`, [`LostHost`], - /// [`LostPlaced`]). - fn freed(&self) -> bool { - match &self.bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.freed.load(Ordering::Acquire), - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => cell.freed.load(Ordering::Acquire), - Bytes::Heap(_) => self.device.gone(), - } - } -} - -impl Drop for BufferShared { - fn drop(&mut self) { - // Carried to the next generation, its parts on this one went with its handle of it - // (`LostBuffer`): its share of its range goes back to the space every generation shares. - if self.device.gone() { - if let Bytes::Own(own) = &self.bytes { - let Some(_busy) = exit_guard::enter() else { - return; - }; - let mut last = &*self; - while let Some(next) = last.next.get() { - last = &next.0; - } - lock(&last.device.shared().addresses).free(own.reserved); - } - return; - } - // Its staged work goes with it, and the staging buffer or host copy that work holds, - // which hold the device: a device whose program let go of it has no submission to wait - // for, and its last handle would otherwise be one of its own. - if *self.staged.get_mut() { - let at: *const BufferShared = self; - self.device.shared().textures.first_moves.forget(at.cast()); - } - let own = match &mut self.bytes { - Bytes::Own(own) => own, - Bytes::Heap(bytes) => { - // An automatic heap's range goes back to it unless `makeAliasable` returned it: - // once, by the buffer's parts on the generation it was carried to last - // (`Buffer::carry_placed`), which go after these. - if self.next.get().is_none() { - bytes - .heap - .release(bytes.offset, self.length, &bytes.aliasable); - } - let live = &self.device.shared().live_buffers; - live.forget(self.address.0, self.object_id); - return; - } - }; - let shared = self.device.shared(); - if let Lie::Host(_) = own.lie { - shared.rebinds.forget(own.identity.key); - shared.aliases.forget(own.identity.key); - } - // The Vulkan teardown is a section of the exit guard. A no-copy buffer's pages go with - // the last hold on them (`HostPages`), which runs their deallocator. - let Some(busy) = exit_guard::enter() else { - // The process is exiting: the buffer and its memory are left to its end. - return; - }; - // The buffer leaves the device's live buffers; its pages go with the last hold on them - // (`FixedPages`, `HostPages`). - shared.live_buffers.forget(self.address.0, self.object_id); - // The host copy goes with its last holder (`Mirror`'s drop). - lock(&shared.addresses).free(own.reserved); - drop(busy); - // The range is free and no lock is held: the caller's token goes, so a creation at the - // range from its drop on succeeds. - own.range_token.release(); - if let Lie::Host(cell) = &own.lie { - if let Lying::In(pages) = cell.lying() { - pages.released_listed(&self.device); - } - // A detached buffer's deallocator runs at its release, as Metal's does. - cell.release_held_back(); - } - } -} - -/// Release `mirror`, a buffer's host copy on `shared`'s device: its `VkBuffer` and memory. -/// -/// # Safety -/// -/// No pending command uses the host copy. -unsafe fn release_mirror(shared: &DeviceShared, mirror: &Mirror) { - // SAFETY: the caller's. - unsafe { release::object(shared.vk(), mirror.raw) }; - lock(&shared.memory).free(shared.vk(), &mirror.placement); -} - -/// A buffer's parts once its `VkBuffer` is bound and its addresses held -/// ([`Device::buffer_of`]). -pub(super) struct BufferParts { - pub(super) raw: vk::Buffer, - /// The placement it is bound to. - pub(super) memory: Placement, - pub(super) offset: u64, - pub(super) base: u64, - pub(super) length: u64, - /// The bytes from byte 0 that Metal's allocation of it holds as its own (`BufferShared`'s - /// `allocation`): its length, or for a buffer of at least 16 KiB the program makes of the - /// runtime's memory in the Metal address space, its length rounded up to 16 KiB, which its - /// `VkBuffer` holds. - pub(super) allocation: u64, - /// The bytes from byte 0 a copy reads in the `VkBuffer` ([`Buffer::copy_reach`]): the - /// length, or a no-copy buffer's bytes to the end of its `VkBuffer` in its pages. - pub(super) reach: u64, - pub(super) modes: Modes, - pub(super) address: GpuAddress, - pub(super) reserved: Held, - pub(super) owner: Owner, - /// A no-copy buffer's release to its caller's deallocator, where it gave one. - pub(super) release: Option, - /// The buffer is a heap's own (`heap.rs`): `Default` hazard tracking resolves to untracked. - pub(super) of_heap: bool, - /// The GPU's writes to a no-copy buffer's pages are dropped, as Metal's private option bit 24 - /// drops them: they are imported through a read-only view of them (`read_only_view.rs`), or - /// copied, the copy's GPU writes never written back (`copied.rs`), and a rebind's are too. - pub(super) drops_writes: bool, - /// A `Managed` buffer's host copy, on a device without unified memory. - pub(super) mirror: Option, - /// What imports a no-copy buffer's dma-bufs again, where the device may release its import - /// while idle (`host_residency.rs`). - pub(super) again: Option, - /// A new buffer, or the same buffer on its device's next generation. - pub(super) naming: Naming, -} - -/// Who a buffer being made is ([`Device::buffer_of`], `Device::buffer_over_host_parts`): a new -/// buffer, with an identity and an `ObjectId` of its own, or a buffer its device's recovery -/// carries (`Buffer::carry`), the same buffer on the next generation, its identity, `ObjectId` -/// and attributes the buffer's; or the runtime's own buffer over the caller's pages that a -/// `Managed` no-copy buffer on a device without unified memory copies to and from -/// (`managed_copy.rs`), new as a new buffer is, which is never a copy of the pages; or the -/// runtime's read twin of a no-copy buffer whose GPU writes are dropped (`read_twin.rs`), new as -/// a new buffer is but of a read twin's identity, which is never a copy of the pages either. -pub(super) enum Naming { - New, - HostCopy, - ReadTwin, - Carried { - object_id: ObjectId, - identity: Identity, - attributes: ResourceAttributes, - }, -} - -impl Naming { - /// The buffer's identity: a new one of `hazard` (a heap's own where `of_heap`), or the - /// carried buffer's. - fn identity(&self, hazard: HazardTrackingMode, of_heap: bool) -> Identity { - match self { - Naming::New | Naming::HostCopy => Identity::new(hazard, of_heap), - Naming::ReadTwin => Identity::read_twin(), - Naming::Carried { identity, .. } => *identity, - } - } -} - -impl std::fmt::Debug for Buffer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Buffer") - .field("length", &self.0.length) - .field("gpu_address", &self.0.address) - .field("options", &self.0.options) - .finish() - } -} - -impl PartialEq for Buffer { - fn eq(&self, other: &Buffer) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -impl Eq for Buffer {} - -impl std::hash::Hash for Buffer { - fn hash(&self, state: &mut H) { - std::ptr::hash(Arc::as_ptr(&self.0), state); - } -} - -/// The three modes of a buffer's resource options, each checked to be one Metal defines. -#[derive(Clone, Copy, Debug)] -pub(super) struct Modes { - pub(super) storage: StorageMode, - pub(super) cache: CpuCacheMode, - pub(super) hazard: HazardTrackingMode, -} - -impl Modes { - /// The modes of `options`; refused when one is not defined. - pub(super) fn of(options: ResourceOptions) -> Result { - Ok(Modes { - storage: options.storage_mode()?, - cache: options.cpu_cache_mode()?, - hazard: options.hazard_tracking_mode()?, - }) - } -} - -/// The alignment every buffer the runtime places in its memory starts at: the largest -/// linear-image alignment measured (256 bytes on RADV, 128 on NVIDIA, 64 on lavapipe, 16 on -/// MoltenVK), so a texture over the buffer aliases its memory whenever the texture's own offset -/// allows. Imported host memory starts at a host page and needs nothing. -pub(super) const LINEAR_IMAGE_ALIGNMENT: u64 = 256; - -/// A buffer's memory `requirements`, placed at a multiple of [`LINEAR_IMAGE_ALIGNMENT`] as well -/// (Vulkan's alignments are powers of two, so the larger one is a multiple of both), and, up to -/// half a pooled block, taking whole units of that alignment. So the next buffer placed in the -/// pool starts where the last ends: a buffer shorter than the alignment would leave the rest of -/// its unit free, a gap no buffer takes, and the pool's first-fit search (`range.rs`) walks every -/// such gap for each later placement, which made each new buffer cost time in proportion to the -/// buffers before it. A buffer past half the largest pooled block keeps its own size: it never -/// lies in a pooled block but takes a block of its own (`memory.rs`'s `place`; a pooled block is -/// at most [`BLOCK_BYTES`], and that on every heap of 1 GiB or more, -/// `memory::pooled_block_bytes`), where nothing follows it. One up to that size takes a block of -/// its own where its memory type's blocks are smaller (a small heap's), its size rounded as -/// here. -/// Rounded up to a heap's 256 KiB (`texture/heap.rs`'s `HEAP_BASE_ALIGNMENT`), the largest heap -/// would ask past the device's `maxMemoryAllocationSize`: 4 GiB on RADV, whose largest allocation -/// is 4 GiB less 4 bytes, and 41,747,218,432 bytes on MoltenVK on an M3 Max, whose largest is -/// 41,747,087,360. -pub(super) fn placed(requirements: vk::MemoryRequirements) -> vk::MemoryRequirements { - let alignment = requirements.alignment.max(LINEAR_IMAGE_ALIGNMENT); - let size = if requirements.size > BLOCK_BYTES / 2 { - requirements.size - } else { - requirements.size.next_multiple_of(alignment) - }; - vk::MemoryRequirements { - alignment, - size, - ..requirements - } -} - -/// The usages every buffer is made with: whatever a Metal buffer can be bound or used as, and the -/// device-address usage where `device_address`. A buffer the runtime places in its memory takes -/// its address from its block's buffer of addresses, which has these usages -/// (`memory::allocate_addressed`), and is made with `usage(false)` itself. -pub(super) fn usage(device_address: bool) -> vk::BufferUsageFlags { - use vk::BufferUsageFlags as U; - let usage = U::TRANSFER_SRC - | U::TRANSFER_DST - | U::UNIFORM_BUFFER - | U::STORAGE_BUFFER - | U::UNIFORM_TEXEL_BUFFER - | U::STORAGE_TEXEL_BUFFER - | U::INDEX_BUFFER - | U::VERTEX_BUFFER - | U::INDIRECT_BUFFER; - if device_address { - usage | U::SHADER_DEVICE_ADDRESS - } else { - usage - } -} - -impl Device { - /// `newBufferWithLength:options:`: a buffer of `length` bytes, all zero. - /// - /// Where it lies follows docs/API.md's "The runtime's memory model": on a device without - /// unified memory, `Shared` storage of the default CPU cache mode lies in host-cached system - /// memory, as on a Mac with a discrete GPU, which the device announces once - /// (`metal2vulkan-degrade-shared-in-system-memory`), and of the write-combined CPU cache - /// mode in device-local memory where the device maps such. - /// - /// Refused: a length of 0 or past the device's `max_buffer_length` (`Nil`, as plain Metal - /// answers nil, its validation stopping it), `Memoryless` storage - /// (`Invalid`). - pub fn new_buffer(&self, length: u64, options: ResourceOptions) -> Result { - self.at_serving(|device| device.new_buffer_now(length, options)) - } - - /// [`Device::new_buffer`] on the generation that serves (`device/line.rs`). - pub(crate) fn new_buffer_now( - &self, - length: u64, - options: ResourceOptions, - ) -> Result { - self.new_buffer_placed(length, options, AddressPlacement::Any) - } - - /// [`Device::new_buffer`] at `placement` in the address space: made, refused, announced and - /// kept among the program's resources as that is, at `AddressPlacement::Outside` for a buffer - /// whose address Metal shows no program, so that no program buffer's address depends on it - /// (`address.rs`). - pub(super) fn new_buffer_placed( - &self, - length: u64, - options: ResourceOptions, - placement: AddressPlacement, - ) -> Result { - self.keep_room(); - let options = self.own_memory_options("new_buffer", options)?; - let placed = (placement.into(), None); - let (buffer, class) = - self.buffer_of_length("new_buffer", length, options, placed, false)?; - self.degrade_system_memory(&buffer, class, || format!("buffer of {length} bytes")); - Ok(self.visible(buffer)) - } - - /// A buffer of `length` bytes, all zero, with `options`, that the runtime makes for its own - /// use: refused as [`Device::new_buffer`] refuses it, and announcing nothing. It lies outside - /// the Metal address space (`AddressPlacement::Outside`), so no program buffer's address - /// depends on it. - pub(super) fn own_buffer( - &self, - length: u64, - options: ResourceOptions, - ) -> Result { - let placed = (AddressPlacement::Outside.into(), None); - Ok(self - .buffer_of_length("new_buffer", length, options, placed, false)? - .0) - } - - /// A `Shared` buffer of `length` bytes, all zero, of the write-combined CPU cache mode, that - /// the runtime makes for its own use ([`Device::own_buffer`]): one the GPU alone uses past - /// the host's zeroes, or that the host only writes (`MemoryClass::WriteCombined`). - pub(super) fn write_combined_buffer(&self, length: u64) -> Result { - self.own_buffer( - length, - ResourceOptions::new( - StorageMode::Shared, - CpuCacheMode::WriteCombined, - HazardTrackingMode::Default, - ), - ) - } - - /// A buffer of `length` bytes, all zero, with `options`, at `placement` in the address space, - /// its byte `aligned` (where given) on a multiple of 256 bytes of its memory, for `call`, and - /// the memory class it took: refused as [`Device::new_buffer`] refuses it, and for a pin the - /// address space cannot honour. Where `padding_unobserved` (its maker declares the bytes - /// between a texture's rows unobserved, `BufferDescriptor::padding_unobserved`), it lies - /// where [`NewBufferOf::Unobserved`] says. - pub(super) fn buffer_of_length( - &self, - call: &'static str, - length: u64, - options: ResourceOptions, - (placement, aligned): (Place, Option), - padding_unobserved: bool, - ) -> Result<(Buffer, MemoryClass), Error> { - let modes = Modes::of(options)?; - let class = buffer_class(call, modes)?; - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(call, Problem::BufferLength { length })); - } - let of = match padding_unobserved { - true => NewBufferOf::Unobserved, - false => NewBufferOf::Runtime(FreshPages::WherePaid), - }; - let buffer = - self.zeroed_buffer_of(call, length, (modes, class), of, (placement, aligned))?; - Ok((buffer, class)) - } - - /// Announce once each where `buffer`, which the program made (`what` names it, after its - /// storage mode) in memory of `class`, lies in system memory: its own bytes overflowed past - /// device-local memory ([`Device::degrade_overflow`]), or it is `Shared` memory a device - /// without unified memory placed there (`MemoryClass::Shared`, - /// [`Degradation::SharedInSystemMemory`]). A heap's buffer is its heap's. - pub(super) fn degrade_system_memory( - &self, - buffer: &Buffer, - class: MemoryClass, - what: impl FnOnce() -> String, - ) { - let what = || format!("a `{:?}` {}", buffer.storage_mode(), what()); - if buffer.own_pages_overflowed() { - self.degrade_overflow(what); - return; - } - if class != MemoryClass::Shared || self.properties().has_unified_memory { - return; - } - if buffer.own_pages_device_local() != Some(false) { - return; - } - self.degrade(Degradation::SharedInSystemMemory, || { - ( - what(), - format!( - "{} has no unified memory, and the default CPU cache mode lets the host \ - read it, so it lies in host-cached system memory; `Private` or `Managed` \ - storage, or the write-combined CPU cache mode, puts the GPU's bytes in \ - device-local memory", - self.name() - ), - ) - }); - } - - /// Announce [`Degradation::DeviceMemoryOverflow`] once for a resource the program made - /// (`what` names it) whose memory overflowed past device-local memory into system memory - /// (`memory.rs`'s `overflow_candidates`). - pub(super) fn degrade_overflow(&self, what: impl FnOnce() -> String) { - self.degrade(Degradation::DeviceMemoryOverflow, || { - ( - what(), - format!( - "no device-local memory type of {} that it takes has room for it, so it lies \ - in system memory, as Metal makes a resource past a discrete GPU's memory \ - rather than refuse it", - self.name() - ), - ) - }); - } - - /// A buffer of `length` bytes (above 0), all zero, in memory of `class` with `modes`, at - /// `placement` in the address space: a heap's own buffer when `of_heap` (`heap.rs`). Its - /// length is the caller's to check. - pub(super) fn zeroed_buffer( - &self, - call: &'static str, - length: u64, - modes: Modes, - class: MemoryClass, - of_heap: bool, - placement: impl Into, - ) -> Result { - let of = match of_heap { - true => NewBufferOf::Heap, - false => NewBufferOf::Runtime(FreshPages::WherePaid), - }; - self.zeroed_buffer_of(call, length, (modes, class), of, (placement.into(), None)) - } - - /// A `Shared` buffer of the runtime's own of `length` bytes, all zero, at `placement`, for an - /// indirect command buffer's records or the slots past them: in fresh pages of its own at any - /// length where the device takes them and [`Device::records_take_own_pages`] says so, so that a - /// recovery's carry keeps its pages and its bytes (`FreshPages::Records`); else where - /// [`zeroed_buffer`](Device::zeroed_buffer) lays such a buffer ([`Buffer::in_own_pages`] - /// tells which). Refused as that is. - pub(super) fn records_buffer( - &self, - call: &'static str, - length: u64, - modes: Modes, - placement: impl Into, - ) -> Result { - let of = NewBufferOf::Runtime(FreshPages::Records); - let placed = (placement.into(), None); - self.zeroed_buffer_of(call, length, (modes, MemoryClass::Shared), of, placed) - } - - /// Whether an indirect command buffer's records made now take fresh pages of the runtime's own - /// where the device takes them (`DevicePolicy::indirect_records`): under - /// `IndirectRecordsPolicy::Untaxed` (the default) only while the device's check has not found - /// that a held pointer import costs every submission (`submit_check.rs`, the import tax: - /// RADV and ANV on i915 pay one), as such an import is held for the buffer's life; under - /// `IndirectRecordsPolicy::Carried` always, so that a recovery keeps them. - pub(super) fn records_take_own_pages(&self) -> bool { - match self.compile_device().policy().indirect_records { - IndirectRecordsPolicy::Carried => true, - _ => !self.pointer_imports_tax_submissions(), - } - } - - /// A `Private` buffer of the runtime's own of `length` bytes at `placement`, for an indirect - /// command buffer's records in device-local memory (`indirect_command_buffer/home.rs`): its - /// bytes as placed, no fill noted, as the caller sets every byte before any use. Refused as - /// [`zeroed_buffer`](Device::zeroed_buffer) is. - pub(super) fn device_records_buffer( - &self, - call: &'static str, - length: u64, - modes: Modes, - placement: impl Into, - ) -> Result { - let modes = Modes { - storage: StorageMode::Private, - ..modes - }; - let of = NewBufferOf::Runtime(FreshPages::WherePaid); - let placed = (placement.into(), None); - let (buffer, _) = - self.placed_new_buffer(call, length, modes, MemoryClass::Private, of, placed)?; - Ok(buffer) - } - - /// [`zeroed_buffer`](Device::zeroed_buffer) for `of`, its byte `aligned` (where given) on a - /// multiple of 256 bytes of its memory ([`Device::placed_new_buffer`]). - fn zeroed_buffer_of( - &self, - call: &'static str, - length: u64, - (modes, class): (Modes, MemoryClass), - of: NewBufferOf, - placed: (Place, Option), - ) -> Result { - let (buffer, bytes) = self.placed_new_buffer(call, length, modes, class, of, placed)?; - // Fresh pages read zero as mapped (`fresh_pages.rs`): nothing is written. - if bytes == NewBytes::Zero { - return Ok(buffer); - } - // Dropping `buffer` on failure releases it. - buffer.clear_first()?; - Ok(buffer) - } - - /// A `Shared` buffer of `length` bytes (above half a pooled block, `FRESH_PAGES_PAST`), all - /// zero, outside the Metal address space, in fresh pages wherever the device takes them, the - /// cost of a held import to its submissions aside ([`FreshPages::Wherever`]): the in-place - /// check's fresh-pages class (`in_place_check.rs`). Where the device takes no such pages, a - /// buffer as ever, not in them (`Buffer::in_fresh_pages`). Refused as [`Device::new_buffer`] - /// refuses its length. - pub(super) fn fresh_pages_check_buffer(&self, length: u64) -> Result { - const CALL: &str = "new_buffer"; - let modes = Modes::of(ResourceOptions::shared())?; - let class = buffer_class(CALL, modes)?; - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(CALL, Problem::BufferLength { length })); - } - let (buffer, bytes) = self.placed_new_buffer( - CALL, - length, - modes, - class, - NewBufferOf::Runtime(FreshPages::Wherever), - (AddressPlacement::Outside.into(), None), - )?; - if bytes == NewBytes::AsPlaced { - buffer.clear_first()?; - } - Ok(buffer) - } - - /// A `Shared` buffer of `length` bytes, all zero, outside the Metal address space, in a - /// block of the runtime's pooled memory that holds `holds`, whatever kind of block the - /// device's own buffers take: `Holds::Buffers` for the in-place check's class of plain - /// pooled memory (`in_place_check.rs`, `PagesClass::Pooled`), whose image names no handle - /// type, and `Holds::FdBuffers` for its class of the blocks allocated exportable - /// (`PagesClass::FdBlocks`), whose image names their handle type (`memory.rs`'s "Buffers in - /// exportable blocks"). Refused as [`Device::new_buffer`] refuses its length. - pub(super) fn pooled_check_buffer(&self, length: u64, holds: Holds) -> Result { - const CALL: &str = "new_buffer"; - let modes = Modes::of(ResourceOptions::shared())?; - let class = buffer_class(CALL, modes)?; - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(CALL, Problem::BufferLength { length })); - } - let placed = (AddressPlacement::Outside.into(), None); - self.zeroed_buffer_of( - CALL, - length, - (modes, class), - NewBufferOf::Check(holds), - placed, - ) - } - - /// A `Private` buffer of `length` bytes that the runtime makes for its own use and whose - /// bytes hold no value before the GPU writes them: made without a submission, so that one of - /// the runtime's sections, a host step's replay of an emulated mesh draw among them, makes - /// it with the exit guard's entry points alone (`exit_guard`). Refused as - /// [`Device::new_buffer`] refuses its length. - pub(super) fn scratch_buffer(&self, length: u64) -> Result { - self.unzeroed_buffer(length, HazardTrackingMode::Untracked) - } - - /// [`scratch_buffer`](Device::scratch_buffer) of hazard tracking `tracking`: the tracker - /// orders its uses as any buffer's of that mode. - pub(super) fn unzeroed_buffer( - &self, - length: u64, - tracking: HazardTrackingMode, - ) -> Result { - let options = - ResourceOptions::new(StorageMode::Private, CpuCacheMode::DefaultCache, tracking); - Ok(self.unzeroed_buffer_with(length, options)?.0) - } - - /// [`unzeroed_buffer`](Device::unzeroed_buffer) with `options`: a buffer of `length` bytes - /// that the runtime makes for its own use, whose bytes hold no value before its owner writes - /// them, in memory `options` asks for, and what its bytes hold as it is made. - /// - /// The upload arena's chunks are such a buffer (`upload.rs`): nothing reads a byte of a chunk - /// outside a region it handed out, and it sets every byte of a region that the region's data - /// does not cover to zero as it hands it out, so what a chunk would pay a creation-time clear - /// for is paid by the region, for the region's bytes alone. A chunk made in fresh pages reads - /// zero unwritten ([`NewBytes::Zero`], `fresh_pages.rs`), so a region of one writes nothing - /// past its data: that is what the second half of the answer is for. - pub(super) fn unzeroed_buffer_with( - &self, - length: u64, - options: ResourceOptions, - ) -> Result<(Buffer, NewBytes), Error> { - const CALL: &str = "new_buffer"; - let modes = Modes::of(options)?; - let class = buffer_class(CALL, modes)?; - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(CALL, Problem::BufferLength { length })); - } - self.placed_new_buffer( - CALL, - length, - modes, - class, - NewBufferOf::Runtime(FreshPages::WherePaid), - (AddressPlacement::Outside.into(), None), - ) - } - - /// [`zeroed_buffer`](Device::zeroed_buffer)'s buffer before its bytes are set to zero, and - /// what they hold: its memory's bytes as placed, or zero where it lies in fresh pages it - /// imported (`fresh_pages.rs`), which `of` says where it takes. A buffer of the runtime's own - /// made where fresh pages are paid for is a parked one of the same making where the recycler - /// holds one, and is noted as one it may park as it goes (`recycle.rs`); one made wherever the - /// device takes them is neither: it is the in-place check's, whose import is held only for its - /// round. - /// - /// Where `aligned` names a byte of it (`BufferDescriptor::aligned_byte`) off a multiple of - /// [`LINEAR_IMAGE_ALIGNMENT`], its `VkBuffer` is bound where its placement starts, a multiple - /// of that alignment, and its bytes start that byte's shortfall from the next multiple into - /// both, so that the byte lies on that multiple: the buffer takes that many more bytes, is - /// never parked nor taken from the parked, and lies in no fresh pages. - fn placed_new_buffer( - &self, - call: &'static str, - length: u64, - modes: Modes, - class: MemoryClass, - of: NewBufferOf, - (placement, aligned): (Place, Option), - ) -> Result<(Buffer, NewBytes), Error> { - let (of_heap, fresh) = match of { - NewBufferOf::Heap => (true, FreshPages::WherePaid), - NewBufferOf::Runtime(fresh) => (false, fresh), - NewBufferOf::Unobserved | NewBufferOf::Check(_) => (false, FreshPages::WherePaid), - }; - let plain = matches!(of, NewBufferOf::Check(_)); - // A buffer whose maker declares its padding unobserved backs textures: its placement starts - // and ends on the device's linear images' memory alignment, so that such an image over its - // texels at offset 0 meets it and one whose size the driver rounds up to it fits in bytes - // the buffer owns (`Buffer::memory_room`). - let granule = match of { - NewBufferOf::Unobserved => self.linear_image_alignment(), - _ => LINEAR_IMAGE_ALIGNMENT, - }; - if self.is_lost() { - return Err(self.lost_refusal()); - } - let shared = self.shared(); - let raw_device = shared.vk(); - // The bytes before the buffer's own in its `VkBuffer` and placement. - let lead = aligned.map_or(0, |byte| { - (LINEAR_IMAGE_ALIGNMENT - byte % LINEAR_IMAGE_ALIGNMENT) % LINEAR_IMAGE_ALIGNMENT - }); - let allocation = - metal_allocation(length, of, placement, self.properties().max_buffer_length); - // Padded to 16 bytes, so a device fill clears every byte too. - let size = allocation - .checked_add(lead) - .and_then(|size| size.checked_next_multiple_of(16)) - .ok_or_else(|| nil(call, Problem::BufferLength { length }))?; - // A heap is never `Managed` (`heap.rs`). - let mirror = if class == MemoryClass::Managed && !self.properties().has_unified_memory { - Some(HostCopy::Own(Arc::new(self.mirror(size)?))) - } else { - None - }; - let class = match mirror { - Some(_) => MemoryClass::Private, - None => class, - }; - // The kind of block it lies in: one of the runtime's own lies where the device's own - // buffers do, whose blocks may be exportable as an opaque file descriptor once the - // device's check of them passed, so that its `VkBuffer` names that handle type there - // (`VUID-vkBindBufferMemory-memory-02726`; `memory.rs`'s `Holds::FdBuffers`); a - // host-visible one in a block of pages the runtime mapped and imported, where the device - // takes such blocks for its class, its check found a held import costs its submissions - // nothing, and its check of fresh pages passed what a texture over such a buffer takes - // that it takes over a plain block's (`in_place.rs`'s `blocks_take`), so that its - // `VkBuffer` names host allocations (`VUID-vkBindBufferMemory-memory-02985`; - // `memory.rs`'s `Holds::PageBuffers`); one whose maker declares its padding unobserved - // in a block of its own kind exportable as a dma-buf too, in which no image is bound, - // where the device's own buffers lie in exportable blocks and it takes such blocks, else - // in a plain block (`Memory::unobserved_buffers`, `Holds::FdDmaBufs`). - let paged = matches!(of, NewBufferOf::Runtime(_)) && { - let takes = lock(&shared.memory).page_buffers(class, self.fresh_pages_pay_now()); - takes && self.page_blocks_taken() - }; - let holds = match of { - NewBufferOf::Runtime(_) if paged => Holds::PageBuffers, - NewBufferOf::Runtime(_) => { - let exportable = lock(&shared.memory).fd_buffer_types.is_ok(); - let checked = exportable && self.fd_blocks_checked(); - lock(&shared.memory).own_buffers(checked) - } - NewBufferOf::Unobserved => { - let exportable = lock(&shared.memory).fd_buffer_types.is_ok(); - let checked = exportable && self.fd_blocks_checked(); - lock(&shared.memory).unobserved_buffers(checked) - } - NewBufferOf::Heap => Holds::Buffers, - NewBufferOf::Check(holds) => holds, - }; - let handle = match holds { - Holds::FdBuffers | Holds::FdDmaBufs => Some(FD_BLOCKS_HANDLE), - Holds::PageBuffers => Some(HOST_PAGES_HANDLE), - _ => None, - }; - let mut external = - vk::ExternalMemoryBufferCreateInfo::default().handle_types(handle.unwrap_or_default()); - // Its device address is its block's (`place_buffer_with`). - let mut info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(false)), - ); - if handle.is_some() { - info = info.push_next(&mut external); - } - // A heap's own buffer lies where its textures can too, and is never parked. A long - // host-visible one of the runtime's own lies in fresh pages where the device takes them - // and its check found a held import adds nothing to its submissions (`fresh_pages.rs`). - // The in-place check's buffer of pooled memory lies in neither. - // An indirect command buffer's records lie in them at any length, as the device's policy - // says where a held import costs its submissions (`FreshPages::Records`). - let (takes, paid) = match fresh { - FreshPages::Records => ( - fresh_pages::class_takes_fresh_pages(class), - self.records_take_own_pages(), - ), - FreshPages::WherePaid => ( - fresh_pages::takes_fresh_pages(size, class), - self.fresh_pages_pay_now(), - ), - FreshPages::Wherever => (fresh_pages::takes_fresh_pages(size, class), true), - }; - let wants_fresh = !of_heap - && !plain - && lead == 0 - && takes - && (shared.host_import.as_ref()).is_ok_and(|importer| importer.pointers().is_some()) - && paid; - let parks = matches!(fresh, FreshPages::WherePaid | FreshPages::Records); - let making = (!of_heap && !plain && lead == 0 && parks).then_some(BufferMaking { - size, - class, - fresh_pages: wants_fresh, - holds, - granule, - }); - let mut taken = making.and_then(|making| self.recycled_buffer(&making)); - let fresh = match (&taken, wants_fresh) { - (None, true) => self.fresh_page_buffer(size, class)?, - _ => None, - }; - // Where the device took no fresh pages, a parked buffer of its own memory, made so as the - // buffer is made below; and for one that would lie in a block allocated exportable, a - // parked one of a plain block, which any buffer may lie in (the device's buffers lie in - // plain blocks until its check answered: `in_place.rs`'s `blocks_take`). Never the - // other way: a buffer that lies in a plain block takes no parked one of a block allocated - // exportable. - if let (None, None, Some(making)) = (&taken, &fresh, making) { - let own = BufferMaking { - fresh_pages: false, - ..making - }; - let plain = BufferMaking { - holds: Holds::Buffers, - ..own - }; - let asked = [ - wants_fresh.then_some(own), - matches!(holds, Holds::FdBuffers | Holds::FdDmaBufs).then_some(plain), - ]; - taken = (asked.into_iter().flatten()).find_map(|making| self.recycled_buffer(&making)); - } - let bytes = match fresh { - Some(_) => NewBytes::Zero, - None => NewBytes::AsPlaced, - }; - // Its range of the address space is a new one, as a new buffer's; the buffer and its - // memory go again where none is left. - let place_address = |raw, memory: Placement| { - let address = self.address_space_for(placement).place(placement, length); - match address { - Ok(address) => Ok((raw, (memory, address))), - Err(error) => { - lock(&shared.recycled_buffers).forget(raw); - recycle::destroy(raw_device, &mut lock(&shared.memory), [(raw, memory)]); - Err(error) - } - } - }; - let made = match (taken, fresh) { - (Some((raw, memory)), _) => place_address(raw, memory), - (None, Some((raw, memory))) => { - if let Some(making) = making { - lock(&shared.recycled_buffers).made(raw, making); - } - place_address(raw, memory) - } - (None, None) => (|| { - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared.counts.buffer_made(info.usage); - let placed = if of_heap { - self.place_heap_buffer(raw, length, class, placement) - } else { - self.place_buffer_in(raw, length, (class, holds, granule), placement) - }; - match placed { - Ok(placed) => { - // Not in fresh pages, whatever was asked: the device took none. - if let Some(making) = making { - let making = BufferMaking { - fresh_pages: false, - ..making - }; - lock(&shared.recycled_buffers).made(raw, making); - } - Ok((raw, placed)) - } - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - Err(error) - } - } - })(), - }; - // On failure the host copy, unused, goes with `mirror` (`Mirror`'s drop). - let (raw, (placement, (address, reserved))) = made?; - let buffer = self.buffer_of(BufferParts { - raw, - memory: placement, - offset: lead, - base: lead, - length, - allocation, - reach: length, - modes, - address, - reserved, - owner: Owner::Runtime, - release: None, - of_heap, - drops_writes: false, - mirror, - again: None, - naming: Naming::New, - }); - Ok((buffer, bytes)) - } - - /// A parked buffer of `making` (`recycle.rs`), now live, where the recycler holds one. - fn recycled_buffer(&self, making: &BufferMaking) -> Option<(vk::Buffer, Placement)> { - let shared = self.shared(); - let (taken, gone) = lock(&shared.recycled_buffers).take(making, Instant::now()); - self.let_go_parked_buffers(gone); - if taken.is_some() { - shared.counts.churn.taken(Recycled::Buffer); - } - taken - } - - /// Destroy the parked buffers the recycler let go of, `gone`, and free their memory. - fn let_go_parked_buffers(&self, gone: recycle::Gone) { - if gone.is_empty() { - return; - } - let shared = self.shared(); - shared.counts.churn.evicted(Recycled::Buffer, gone.len()); - recycle::destroy(shared.vk(), &mut lock(&shared.memory), gone); - } - - /// The device copy of a two-copy buffer (`managed_copy.rs`): a `VkBuffer` of `size` bytes - /// bound at the start of device-local memory of the runtime's own, in a plain block, its - /// device address its block's (`place_buffer_with`). Refused where no device-local memory has - /// room: an allocation refused, or one that overflowed into system memory - /// (`memory.rs`'s `overflow_candidates`), which goes again. - pub(super) fn managed_device_copy(&self, size: u64) -> Result<(vk::Buffer, Placement), Error> { - let shared = self.shared(); - let raw_device = shared.vk(); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(false)), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared.counts.buffer_made(info.usage); - // SAFETY: `raw` is a live buffer of this device. - let requirements = placed(unsafe { raw_device.get_buffer_memory_requirements(raw) }); - let placement = crate::memory::allocate_addressed_in( - &shared.memory, - raw_device, - &requirements, - (MemoryClass::Private, Holds::Buffers), - &shared.counts, - ) - .and_then(|placement| match placement.overflowed() { - true => { - lock(&shared.memory).free(raw_device, &placement); - Err(Error::OutOfMemory(crate::error::MemoryKind::Device)) - } - false => Ok(placement), - }); - let bound = placement.and_then(|placement| { - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - match unsafe { - crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) - } { - Ok(()) => Ok(placement), - Err(error) => { - lock(&shared.memory).free(raw_device, &placement); - Err(vulkan(error)) - } - } - }); - match bound { - Ok(placement) => Ok((raw, placement)), - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - Err(error) - } - } - } - - /// A `Managed` buffer's host copy of `size` bytes (its padded length) on a device without - /// unified memory ([`Mirror`]): copied to and from only. - fn mirror(&self, size: u64) -> Result { - let shared = self.shared(); - let raw_device = shared.vk(); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - let allocated = crate::memory::allocate( - &shared.memory, - raw_device, - &requirements, - MemoryClass::Managed, - ); - let placed = allocated.and_then(|placement| { - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - match unsafe { - crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) - } { - Ok(()) => Ok(placement), - Err(error) => { - lock(&shared.memory).free(raw_device, &placement); - Err(vulkan(error)) - } - } - }); - match placed { - Ok(placement) if placement.mapped.is_some() => Ok(Mirror { - raw, - placement, - device: self.clone(), - }), - Ok(placement) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - lock(&shared.memory).free(raw_device, &placement); - Err(internal("a managed buffer's host copy is not mapped")) - } - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - Err(error) - } - } - } - - /// A buffer of preprocess memory for executions of generated commands - /// (`generated_execute.rs`), as `vkGetGeneratedCommandsMemoryRequirementsEXT` states it in - /// `required` (above 0 bytes): `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT` and device-address - /// usage (`maintenance5`'s usage flags, which the device enabled with - /// `VK_EXT_device_generated_commands`), in device-local memory of a type and at an alignment - /// that meet both the buffer's requirements and `required`. Its contents are the driver's. - pub(super) fn preprocess_buffer( - &self, - required: vk::MemoryRequirements, - ) -> Result { - if self.is_lost() { - return Err(self.lost_refusal()); - } - let modes = Modes::of(ResourceOptions::private())?; - let shared = self.shared(); - let raw_device = shared.vk(); - let mut usage = vk::BufferUsageFlags2CreateInfoKHR::default() - .usage(PREPROCESS_BUFFER | vk::BufferUsageFlags2KHR::SHADER_DEVICE_ADDRESS); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(required.size) - .push_next(&mut usage), - ); - // SAFETY: the device is live and `info` and its chain valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared - .counts - .buffer_made(vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS); - // SAFETY: `raw` is a live buffer of this device. - let own = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - let requirements = vk::MemoryRequirements { - size: own.size, - alignment: own.alignment.max(required.alignment), - memory_type_bits: own.memory_type_bits & required.memory_type_bits, - }; - // Its own address: a preprocess address is one of a buffer of preprocess usage. - let made = self.place_buffer_with( - raw, - requirements, - required.size, - (MemoryClass::Private, Holds::Buffers), - AddressPlacement::Outside.into(), - false, - ); - let (placement, (address, reserved)) = match made { - Ok(made) => made, - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - return Err(error); - } - }; - Ok(self.buffer_of(BufferParts { - raw, - memory: placement, - offset: 0, - base: 0, - length: required.size, - allocation: required.size, - reach: required.size, - modes, - address, - reserved, - owner: Owner::Runtime, - release: None, - of_heap: false, - drops_writes: false, - mirror: None, - again: None, - naming: Naming::New, - })) - } - - /// The buffer of `parts`. Dropping the result releases every part. - pub(super) fn buffer_of(&self, parts: BufferParts) -> Buffer { - let BufferParts { - raw, - memory, - offset, - base, - length, - allocation, - reach, - modes, - address, - reserved, - owner, - release, - of_heap, - drops_writes, - mirror, - again, - naming, - } = parts; - let pages = self.pages_of(raw, memory, offset, base, reach); - let identity = naming.identity(modes.hazard, of_heap); - let lie = match owner { - // A no-copy buffer's pages are its until a rebind (`rebind.rs`). - Owner::Caller => { - // Kept imported where nothing imports it again: a heap's, an import of dma-bufs - // whose descriptors did not fit (counted as such), or one by pointer. - let kept = match (of_heap, pages.memory.placement.over_dma_buf()) { - (true, _) => Some(KeptBecause::Heap), - (false, true) => None, - (false, false) => Some(KeptBecause::Pointer), - }; - let import = self.host_import(pages, again, kept); - self.host_lie( - identity.key, - (import, Joining::First), - release, - drops_writes, - ) - } - Owner::Runtime | Owner::Vulkan { .. } => Lie::Fixed(Arc::new(FixedPages { - device: MadeOn::new(self.clone()), - pages, - owned: matches!(owner, Owner::Runtime), - released: AtomicBool::new(false), - freed: AtomicBool::new(false), - #[cfg(unix)] - parked_images: Default::default(), - })), - }; - let own = OwnBytes { - lie, - reserved, - identity, - owner, - mirror, - range_token: KeptToken::default(), - }; - self.buffer_lying(own, (length, allocation), modes, address, naming) - } - - /// The import of a no-copy buffer's `pages`: one the device releases while idle where - /// `again` imports them again and the device keeps a stand-in for it and a thread to release - /// it (`host_residency.rs`), else one it keeps, for `kept` where nothing imports it again. - fn host_import( - &self, - pages: Pages, - again: Option, - kept: Option, - ) -> Arc { - let Some(again) = again else { - return Arc::new(HostImport::new(self, pages, kept)); - }; - let stand_in = self.detach_stand_in().ok(); - let Some(stand_in) = stand_in.as_ref().and_then(Buffer::fixed_pages) else { - let kept = Some(KeptBecause::NoStandIn); - return Arc::new(HostImport::new(self, pages, kept)); - }; - let import = Arc::new(HostImport::releasable(self, pages, again, stand_in)); - if !self.shared().residency.note(&import) { - // No thread releases it: kept imported. - import.expose(ReadApart::Unreleased); - } - import - } - - /// A no-copy buffer of `length` bytes lying in `import`, the import of the same bytes a live - /// no-copy buffer or heap lies in (`host_aliases.rs`), at `address`, released to `release` - /// once nothing holds it: a heap's own buffer where `of_heap`, of a heap's identity. Dropping - /// the result releases every part but the import, which the last buffer over it releases. - pub(super) fn buffer_in_import( - &self, - import: Arc, - (length, modes, of_heap): (u64, Modes, bool), - (address, reserved): (GpuAddress, Held), - release: Option, - naming: Naming, - ) -> Buffer { - let identity = naming.identity(modes.hazard, of_heap); - let joining = match of_heap { - true => Joining::Heap, - false => Joining::Buffer, - }; - let own = OwnBytes { - lie: self.host_lie(identity.key, (import, joining), release, false), - reserved, - identity, - owner: Owner::Caller, - mirror: None, - range_token: KeptToken::default(), - }; - self.buffer_lying(own, (length, length), modes, address, naming) - } - - /// A no-copy buffer's lie, of `key`: pages of its own in `import`, released to `release` - /// once nothing holds them, which a rebind replaces (`rebind.rs`); the GPU's writes to it - /// dropped where `drops_writes`, or where `import` is of a read-only view of the pages. - fn host_lie( - &self, - key: ResourceKey, - (import, joining): (Arc, Joining), - release: Option, - drops_writes: bool, - ) -> Lie { - let drops_writes = drops_writes || import.drops_writes(); - let host = HostPages::new(import, joining); - if let Some(release) = release { - host.release_to(release); - } - let cell = Arc::new(HostCell { - pages: Mutex::new(Lying::In(Arc::new(host))), - texels: Mutex::new(Vec::new()), - textures: Mutex::new(TexturesOver::default()), - in_place: Mutex::new(Vec::new()), - exposed: AtomicU16::new(0), - device: MadeOn::new(self.clone()), - released: AtomicBool::new(false), - freed: AtomicBool::new(false), - drops_writes, - held_back: Mutex::new(None), - read_twin: Mutex::new(None), - twin_textures: Mutex::new(Vec::new()), - }); - self.shared().rebinds.register(key, &cell); - Lie::Host(cell) - } - - /// The buffer of `own`'s bytes, `length` long, Metal's allocation of it holding `allocation` - /// bytes, of `modes`, at `address`, named by `naming`. - fn buffer_lying( - &self, - own: OwnBytes, - (length, allocation): (u64, u64), - modes: Modes, - address: GpuAddress, - naming: Naming, - ) -> Buffer { - let options = ResourceOptions::new(modes.storage, modes.cache, own.identity.mode()); - let (object_id, attributes) = match naming { - Naming::New | Naming::HostCopy | Naming::ReadTwin => { - (ObjectId::new(), ResourceAttributes::new()) - } - Naming::Carried { - object_id, - attributes, - .. - } => (object_id, attributes), - }; - Buffer(Arc::new(BufferShared { - device: MadeOn::new(self.clone()), - generation: std::ptr::from_ref(self.shared()).addr(), - object_id, - length, - allocation, - options, - address, - attributes, - bytes: Bytes::Own(own), - held_by: HeldBy::default(), - handed_out: Arc::default(), - padding_unobserved: AtomicBool::new(false), - staged: AtomicBool::new(false), - next: OnceLock::new(), - carried: AtomicBool::new(false), - calls: PartsCalls::default(), - })) - } - - /// The pages of a buffer `raw` in `memory`, its bytes `offset` bytes into its placement and - /// `base` bytes into `raw`, `reach` bytes from byte 0 copied out. - pub(super) fn pages_of( - &self, - raw: vk::Buffer, - placement: Placement, - offset: u64, - base: u64, - reach: u64, - ) -> Pages { - let memory = Bound { - // A placed buffer's address is its block's (`place_buffer_with`); any other's its own. - device_address: match placement.address { - Some(address) => Some(address), - // SAFETY: the buffer is bound to the placement, and was made with `usage` - // (`device_address_of`). - None => unsafe { self.device_address_of(raw) }, - }, - placement, - }; - Pages { - raw, - memory, - offset, - base, - reach, - } - } - - /// Host pages a rebind gives a no-copy buffer (`rebind.rs`): `raw` in `memory`, as - /// [`Device::pages_of`] says, without their release, which the rebind sets once they are - /// the buffer's. - pub(super) fn host_pages( - &self, - raw: vk::Buffer, - memory: Placement, - offset: u64, - base: u64, - reach: u64, - ) -> Arc { - let pages = self.pages_of(raw, memory, offset, base, reach); - let import = HostImport::new(self, pages, Some(KeptBecause::Rebind)); - Arc::new(HostPages::new(Arc::new(import), Joining::First)) - } - - /// Host pages a rebind gives a no-copy buffer lying in `import`, the import of the same bytes - /// a live no-copy buffer was made over (`rebind.rs`, `host_aliases.rs`), without their - /// release, as [`Device::host_pages`] gives them. - pub(super) fn pages_in_import(&self, import: Arc) -> Arc { - Arc::new(HostPages::new(import, Joining::Rebound)) - } - - /// The Vulkan device address of `raw`, where the device enables `bufferDeviceAddress`. - /// - /// # Safety - /// - /// `raw` is a buffer of this device made with [`usage`], bound to memory. - pub(super) unsafe fn device_address_of(&self, raw: vk::Buffer) -> Option { - let shared = self.shared(); - shared.device_address.then(|| { - let info = vk::BufferDeviceAddressInfo::default().buffer(raw); - // SAFETY: the buffer was made with `SHADER_DEVICE_ADDRESS` usage (the caller's - // contract) and is bound to memory allocated with the device-address flag. - unsafe { shared.vk().get_buffer_device_address(&info) } - }) - } - - /// Place `raw` (for a buffer of `length` bytes) in memory of `class` and at `at` in the - /// address space; released again when either fails. - pub(super) fn place_buffer( - &self, - raw: vk::Buffer, - length: u64, - class: MemoryClass, - at: Place, - ) -> Result<(Placement, (GpuAddress, Held)), Error> { - let granule = LINEAR_IMAGE_ALIGNMENT; - self.place_buffer_in(raw, length, (class, Holds::Buffers, granule), at) - } - - /// [`place_buffer`](Device::place_buffer) in a block that holds `holds`: `Holds::Buffers`, or - /// `Holds::FdBuffers` or `Holds::FdDmaBufs` for a buffer made for `FD_BLOCKS_HANDLE` - /// (`memory.rs`); its placement starting on `granule` and, short of half a block, ending on it - /// ([`placed`]). - fn place_buffer_in( - &self, - raw: vk::Buffer, - length: u64, - (class, holds, granule): (MemoryClass, Holds, u64), - at: Place, - ) -> Result<(Placement, (GpuAddress, Held)), Error> { - // SAFETY: `raw` is a live buffer of this device. - let own = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; - let requirements = vk::MemoryRequirements { - alignment: own.alignment.max(granule), - ..own - }; - self.place_buffer_with(raw, requirements, length, (class, holds), at, true) - } - - /// The memory alignment the device's linear images take: `VkMemoryRequirements::alignment` of - /// one, a 64 by 8 `R8G8B8A8_UNORM` 2D image to sample and copy, made and released at the first - /// ask and kept for the device's life (`TextureState::linear_image_alignment`); at least - /// [`LINEAR_IMAGE_ALIGNMENT`], which it is where the device makes no such image. Intel's driver - /// for the UHD 630 on Windows answers 4096, and rounds a small linear image's size up to a - /// multiple of it. - pub(super) fn linear_image_alignment(&self) -> u64 { - let textures = &self.shared().textures; - *(textures.linear_image_alignment).get_or_init(|| { - (self.probed_linear_image_alignment()) - .unwrap_or(LINEAR_IMAGE_ALIGNMENT) - .max(LINEAR_IMAGE_ALIGNMENT) - }) - } - - /// [`linear_image_alignment`](Self::linear_image_alignment)'s probe: `None` where the device - /// makes no such image (its format query) or making it failed. - fn probed_linear_image_alignment(&self) -> Option { - let shared = self.shared(); - let raw_device = shared.vk(); - let usage = vk::ImageUsageFlags::SAMPLED - | vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST; - let info = shared.sharing().image( - vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(vk::Format::R8G8B8A8_UNORM) - .extent(vk::Extent3D { - width: 64, - height: 8, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::LINEAR) - .usage(usage) - .initial_layout(vk::ImageLayout::PREINITIALIZED), - ); - let limits = self.image_limits(&info, &[]).ok()?; - let fits = limits.max_extent.width >= 64 - && limits.max_extent.height >= 8 - && limits.sample_counts.contains(vk::SampleCountFlags::TYPE_1); - if !fits { - return None; - } - // SAFETY: the device is live and `info` valid and within the device's limits for it. - let raw = unsafe { crate::creation::image(raw_device, &info) }.ok()?; - // SAFETY: `raw` is a live image of this device. - let requirements = unsafe { raw_device.get_image_memory_requirements(raw) }; - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - Some(requirements.alignment) - } - - /// [`place_buffer`](Device::place_buffer) for a heap's own buffer: where the heap's textures - /// can lie too (`Device::heap_requirements`). - pub(super) fn place_heap_buffer( - &self, - raw: vk::Buffer, - length: u64, - class: MemoryClass, - at: Place, - ) -> Result<(Placement, (GpuAddress, Held)), Error> { - // SAFETY: `raw` is a live buffer of this device. - let own = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; - let requirements = self.heap_requirements(own, class)?; - self.place_buffer_with(raw, requirements, length, (class, Holds::Buffers), at, true) - } - - /// [`place_buffer`](Device::place_buffer) in memory that meets `requirements`, which hold - /// the buffer's own, in a block that holds `holds` ([`Device::place_buffer_in`]). Where - /// `block_address`, `raw` was made without the device-address usage and its device address - /// is its block's (`memory::allocate_addressed`, the placement's `address`); else its own, - /// where it has the usage. - fn place_buffer_with( - &self, - raw: vk::Buffer, - requirements: vk::MemoryRequirements, - length: u64, - (class, holds): (MemoryClass, Holds), - at: Place, - block_address: bool, - ) -> Result<(Placement, (GpuAddress, Held)), Error> { - let shared = self.shared(); - let raw_device = shared.vk(); - let requirements = placed(requirements); - let placement = if block_address { - crate::memory::allocate_addressed_in( - &shared.memory, - raw_device, - &requirements, - (class, holds), - &shared.counts, - )? - } else { - crate::memory::allocate_in(&shared.memory, raw_device, &requirements, class, holds)? - }; - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - let bound = unsafe { - crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) - }; - let address = match bound { - Ok(()) => self.address_space_for(at).place(at, length), - Err(error) => { - lock(&shared.memory).free(raw_device, &placement); - return Err(vulkan(error)); - } - }; - match address { - Ok(address) => Ok((placement, address)), - Err(error) => { - lock(&shared.memory).free(raw_device, &placement); - Err(error) - } - } - } -} - -/// Whose a buffer [`Device::placed_new_buffer`] makes is: a heap's own buffer, one of the -/// runtime's own, with where it lies in fresh pages, one whose maker declares its padding -/// unobserved, or the in-place check's of pooled memory. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum NewBufferOf { - /// A heap's own buffer (`heap.rs`), never in fresh pages, in a block of `Holds::Buffers`. - Heap, - /// A buffer of the runtime's own, in fresh pages where it says, else in a block of the kind - /// the device's own buffers take (`memory.rs`'s `Memory::own_buffers`). - Runtime(FreshPages), - /// A buffer of the runtime's own whose maker declares the bytes between a texture's rows and - /// slices unobserved (`BufferDescriptor::padding_unobserved`): as - /// `Runtime(FreshPages::WherePaid)`, in a block of its own kind exportable as a dma-buf too, - /// in which no image is bound, where the device's own buffers lie in exportable blocks and it - /// takes such blocks (`Holds::FdDmaBufs`), else in a plain block (`Holds::Buffers`; - /// `memory.rs`'s `Memory::unobserved_buffers`): a texture over such a buffer may take a - /// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch, which a block allocated exportable holds - /// only through a dedicated import of its dma-buf (`texture.rs`'s `exported_dma_buf_alias`). - Unobserved, - /// The in-place check's buffer of a class of the runtime's pooled memory - /// (`in_place_check.rs`): in a block that holds this, `Holds::Buffers` for - /// `PagesClass::Pooled` (exported as no handle type) and `Holds::FdBuffers` for - /// `PagesClass::FdBlocks` (allocated exportable, never exported) whatever the class's - /// verdicts, never in fresh pages and never parked. - Check(Holds), -} - -/// What a buffer's carry carries ([`Buffer::carry`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum CarryOf { - /// A buffer of the program's, kept among the next generation's program resources. - Program, - /// A heap's own buffer (`Buffer::carry_heap_bytes`). - Heap, - /// A buffer of the runtime's own whose `contents` pointer no program holds - /// (`Buffer::carry_runtime`). - Runtime, -} - -/// Where [`Device::placed_new_buffer`] lays a long host-visible buffer of the runtime's own in -/// fresh pages (`fresh_pages.rs`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum FreshPages { - /// Where the device takes them and its submission checks found that a held import adds - /// nothing to its submissions: the product's buffers. - WherePaid, - /// Wherever the device takes them: the in-place check's buffer of its fresh-pages class, - /// which lies where a rebind's copy under an image in place lies whatever that cost - /// (`buffer_descriptor.rs`'s `copied_pages`), and whose import lives only for its round. - Wherever, - /// Where the device takes them, at any length, as [`Device::records_take_own_pages`] says: an - /// indirect command buffer's records and slots past them, which a recovery's carry keeps - /// only in the runtime's own pages (`indirect_command_buffer/carry.rs`, `fresh_pages.rs`). - Records, -} - -/// What a new buffer's bytes hold as [`Device::placed_new_buffer`] makes it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum NewBytes { - /// Its memory's bytes as placed: undefined, or a parked buffer's last owner's. - AsPlaced, - /// Zero: fresh pages it imported (`fresh_pages.rs`). - Zero, -} - -/// The bytes Metal's allocation of a buffer of `length` made for `of` at `placement` holds as its -/// own (`BufferShared`'s `allocation`): a buffer of at least 16 KiB the program makes of the -/// runtime's memory (`NewBufferOf::Runtime(FreshPages::WherePaid)`, `NewBufferOf::Unobserved`) at -/// a range of the Metal address space (`AddressPlacement::Any` or a pin) holds its length rounded -/// up to 16 KiB, its `allocatedSize` on Metal, where that stays within `max_length`; every other -/// buffer its length: a shorter one, whose Metal allocation is its length (or a slot of a pool), -/// a heap's own, the runtime's own outside the space, an indirect command buffer's records and -/// the in-place check's. -fn metal_allocation(length: u64, of: NewBufferOf, placement: Place, max_length: u64) -> u64 { - let program = matches!( - of, - NewBufferOf::Runtime(FreshPages::WherePaid) | NewBufferOf::Unobserved - ); - let in_space = matches!( - placement, - Place::At(AddressPlacement::Any | AddressPlacement::At(_)) - ); - match program && in_space && length >= METAL_PAGE { - true => (length.checked_next_multiple_of(METAL_PAGE)) - .filter(|&allocation| allocation <= max_length) - .unwrap_or(length), - false => length, - } -} - -/// The memory class of a buffer of `modes`' storage and CPU cache modes, for `call`: refused for -/// `Memoryless`, which is no buffer's. `Shared` storage is `MemoryClass::WriteCombined` in the -/// write-combined CPU cache mode, which the host does not read. -pub(super) fn buffer_class(call: &'static str, modes: Modes) -> Result { - match modes.storage { - StorageMode::Shared => Ok(match modes.cache { - CpuCacheMode::DefaultCache => MemoryClass::Shared, - CpuCacheMode::WriteCombined => MemoryClass::WriteCombined, - }), - StorageMode::Private => Ok(MemoryClass::Private), - StorageMode::Managed => Ok(MemoryClass::Managed), - StorageMode::Memoryless => Err(invalid(call, Problem::StorageMode)), - } -} - -impl Heap { - /// A buffer of `length` bytes with `options` (checked against the heap's), placed `offset` - /// bytes into the heap: its bytes are the heap's from there, as they are. - pub(super) fn placed_buffer( - &self, - heap_bytes: &Buffer, - offset: u64, - length: u64, - options: ResourceOptions, - ) -> Buffer { - Buffer(Arc::new(BufferShared { - device: MadeOn::new(heap_bytes.generation().clone()), - generation: std::ptr::from_ref(heap_bytes.generation().shared()).addr(), - object_id: ObjectId::new(), - length, - allocation: length, - options, - address: GpuAddress(heap_bytes.gpu_address().0 + offset), - attributes: ResourceAttributes::new(), - bytes: Bytes::Heap(HeapBytes { - heap: self.clone(), - bytes: heap_bytes.clone(), - offset, - // A placement heap's buffer answers aliasable from the start, as Metal's does. - aliasable: Arc::new(AtomicBool::new(self.heap_type() == HeapType::Placement)), - }), - held_by: HeldBy::default(), - handed_out: Arc::default(), - padding_unobserved: AtomicBool::new(false), - staged: AtomicBool::new(false), - next: OnceLock::new(), - carried: AtomicBool::new(false), - calls: PartsCalls::default(), - })) - } -} - -impl Buffer { - /// The buffer's parts as the work at hand reaches them: its own, where its device's recovery - /// never carried it, at one load (`device/carry.rs`). Where it did, inside a command buffer's - /// work (`NoticesFor::generation`) those of that command buffer's generation where the - /// buffer has some, so the lost generation's command buffers record its own handles alone; - /// else those of the generation it was carried to last. - #[inline] - fn s(&self) -> &Arc { - match self.0.carried.load(Ordering::Relaxed) { - false => &self.0, - true => self.carried(), - } - } - - /// [`s`](Self::s) of a buffer its device's recovery carried. - #[cold] - fn carried(&self) -> &Arc { - let records = crate::degradation::NoticesFor::generation(); - let mut shared = &self.0; - loop { - // Not its parts on a lost generation that went: a call under way that holds them - // keeps them until it ends (`Buffer::held_parts`), and no command buffer is made there - // after its rest (`Carry::refuses`). - if records == Some(shared.generation) && !shared.freed() { - return shared; - } - match shared.next.get() { - Some(next) => shared = &next.0, - None => return shared, - } - } - } - - /// The buffer's parts for a call outside a command buffer's work that reaches their Vulkan - /// objects (a texture over its bytes, an export of its memory, an upload, a handle handed - /// out), held until the result goes: those [`s`](Self::s) answers, on the generation that - /// serves where the buffer was carried there, and every read of its parts on this thread - /// meanwhile answers them (`NoticesFor::of_generation`). Where its device's recovery carried - /// it from their generation since, and that generation came to rest, their release waits - /// for the call to end ([`LostBuffer`]); parts let go of already are never held, the call - /// taking those of the generation the buffer was carried to. A call begun on parts of a lost - /// generation completes there: what it makes is that generation's, refused where it meets - /// the next (`RuntimeGap::MadeBeforeRecovery`), as a call that took its arguments before - /// the loss (`Device::at_serving_taking`). Not for command buffers' work, whose queue slot - /// holds the generation (`device/carry.rs`). - pub(super) fn held_parts(&self) -> HeldParts<'_> { - let mut link = self.s(); - loop { - // Parts not marked let go of yet, or whose release a call under way holds back, go - // only once this call ends. - if let Some(call) = link.calls.hold_unless(|| link.released()) { - #[cfg(test)] - held_hook(); - return HeldParts { - _call: call, - _scope: NoticesFor::of_generation(link.generation), - }; - } - // Let go of on their lost generation since this thread read them: the generation - // the buffer was carried to serves its calls. Parts marked were carried. - link = &link - .next - .get() - .expect("a buffer's parts marked let go of were carried") - .0; - } - } - - /// Whether the buffer lies in fresh pages it imported (`fresh_pages.rs`), to which no image - /// is bound: false for a no-copy buffer, a heap's and one over the caller's `VkBuffer`. - pub(super) fn in_fresh_pages(&self) -> bool { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.pages.memory.placement.over_own_pages(), - Bytes::Own(_) | Bytes::Heap(_) => false, - } - } - - /// Whether the buffer lies in pages the runtime mapped and imported, fresh pages of its own or - /// a block of them ([`in_fresh_pages`](Buffer::in_fresh_pages), - /// [`in_page_block`](Buffer::in_page_block)): a recovery's carry of a buffer of the runtime's - /// own imports the same pages again, its bytes and `contents` pointer as they are - /// ([`carry_runtime`](Buffer::carry_runtime)). - pub(super) fn in_own_pages(&self) -> bool { - self.in_fresh_pages() || self.in_page_block() - } - - /// Whether the buffer lies in a block of pages the runtime mapped and imported, among other - /// buffers (`memory.rs`'s `Holds::PageBuffers`): an image over its bytes is made for host - /// allocations, as over fresh pages, under their class's verdicts (`texture/route.rs`). - pub(super) fn in_page_block(&self) -> bool { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.pages.memory.placement.in_page_block(), - Bytes::Own(_) | Bytes::Heap(_) => false, - } - } - - /// Whether the buffer's own pages, of the runtime's memory, overflowed past device-local memory - /// into system memory (`memory.rs`'s `overflow_candidates`): false for a buffer over host - /// pages, which are imported, and for a heap's buffer, whose bytes are its heap's. - pub(super) fn own_pages_overflowed(&self) -> bool { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.pages.memory.placement.overflowed(), - Bytes::Own(_) | Bytes::Heap(_) => false, - } - } - - /// `f` of the placement the buffer's own pages lie in and of the buffer's first byte's offset - /// in it (`exported_memory.rs`); `None` for a heap's buffer, whose bytes are its heap's. - #[cfg(unix)] - pub(super) fn own_placement(&self, f: impl FnOnce(&Placement, u64) -> R) -> Option { - match &self.s().bytes { - Bytes::Own(own) => Some(own.with(ReadApart::Binding, |pages| { - f(&pages.memory.placement, pages.offset) - })), - Bytes::Heap(_) => None, - } - } - - /// Whether the buffer's own pages, of the runtime's memory, lie in device-local memory; `None` - /// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good. - pub(super) fn own_pages_device_local(&self) -> Option { - (self.own_pages_flags()).map(|flags| flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL)) - } - - /// The property flags of the memory type the buffer's own pages lie in; `None` for a heap's - /// buffer, whose bytes are its heap's. - pub(super) fn own_pages_flags(&self) -> Option { - let s = self.s(); - match &s.bytes { - Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { - let memory = lock(&s.device.shared().memory); - Some(memory.flags_of(&pages.memory.placement)) - }), - Bytes::Heap(_) => None, - } - } - - /// Metal's allocation of the buffer padded to 16 bytes (its length, or its length rounded - /// up to 16 KiB, `BufferShared`'s `allocation`): the bytes the `VkBuffer` holds from - /// [`Buffer::base`], which its first fill clears. - pub(super) fn padded_length(&self) -> u64 { - self.s().allocation.next_multiple_of(16) - } - - /// The bytes from byte 0 that a texture over the buffer reaches in place in its memory - /// (`buffer_texture.rs`'s **Tails**; past them its texels lie in its tail): Metal's - /// allocation of a buffer of its own (its length, or its length rounded up to 16 KiB, - /// `BufferShared`'s `allocation`), a no-copy buffer's length, whose pages past it are the - /// caller's, and a heap's buffer's heap to its end, as Metal's texels there are the heap's - /// bytes. - pub(super) fn texel_reach(&self) -> u64 { - match &self.s().bytes { - Bytes::Own(_) => self.s().allocation, - Bytes::Heap(bytes) => bytes.bytes.texel_reach().saturating_sub(bytes.offset), - } - } - - /// The bytes of the buffer's memory from its byte 0 ([`Buffer::memory`]'s offset) to the end - /// of the memory's placement, which no other resource is placed in: its own placement's, at - /// least its `VkBuffer`'s bytes, an import's, for a buffer over host pages (its last page's - /// bytes past the buffer's among them), or a heap's. An image over a texture's texels in that - /// memory may take them all (`texture.rs`'s aliasing image), its driver's bytes past the - /// texels among them: a linear image's size the driver rounds up to its alignment, which a - /// buffer whose maker declares its padding unobserved is placed on - /// (`Device::placed_new_buffer`). - pub(super) fn memory_room(&self) -> u64 { - match &self.s().bytes { - Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { - pages.memory.placement.size().saturating_sub(pages.offset) - }), - Bytes::Heap(bytes) => bytes.bytes.memory_room().saturating_sub(bytes.offset), - } - } - - /// Set the buffer's padded length of bytes to zero: through the mapping for `Shared` and - /// `Managed` storage (host-coherent memory), else by a device fill the call waits for; both - /// for a `Managed` buffer with a host copy ([`Mirror`]). Racing the GPU's use of the buffer - /// is the caller's to avoid. - pub(super) fn clear(&self) -> Result<(), Error> { - let s = self.s(); - let size = self.padded_length(); - if let Some(contents) = self.mapped_contents() { - // SAFETY: the buffer's bytes, its padded length from `contents`, are host-coherent - // memory (`MemoryClass::Shared` and `Managed`, or imported host memory), so the - // device sees the writes at the next submission. - unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, size as usize) }; - if self.mirror().is_none() { - return Ok(()); - } - } - let (raw, start) = self.at(0); - s.device.submit_internal(|device, command_buffer| { - // SAFETY: the internal command buffer is recording; the buffer is live, and its - // padded length (a multiple of 16) lies in the `VkBuffer` from `start`, a multiple - // of 4: 0, or a heap buffer's offset in its heap's (a buffer without contents is - // none over host memory). - unsafe { - crate::word_fill::record(&s.device, command_buffer, raw, start..start + size, 0); - let barrier = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE); - device.cmd_pipeline_barrier( - command_buffer, - vk::PipelineStageFlags::TRANSFER, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::DependencyFlags::empty(), - &[barrier], - &[], - &[], - ); - } - }) - } - - /// Note the acquire of the buffer's `VkBuffer`, whole, from `families`' source, a queue family - /// reserved for external memory, for its target, for the device's next submission to record - /// before any of its commands (`exported_memory.rs`, `Buffer::external_write_done`). - #[cfg(unix)] - pub(super) fn note_acquire(&self, families: (u32, u32)) { - let s = self.s(); - let (raw, _) = self.at(0); - let weak: Weak = Arc::downgrade(s); - let keeper: Weak = weak; - let device = &s.device; - (device.shared().textures.first_moves).register_acquire(keeper, raw, families); - } - - /// Set a new buffer's padded length of bytes to zero as [`clear`](Self::clear) does, without - /// waiting for the GPU: the host's bytes (`Shared` and `Managed` storage, a `Managed` - /// buffer's host copy) at once, so `contents` reads zero before any submission, and bytes the - /// host cannot write (`Private` storage, a `Managed` buffer's device copy) by the device's - /// next submission, before any of its commands (`texture/first_move.rs`). - pub(super) fn clear_first(&self) -> Result<(), Error> { - let s = self.s(); - let size = self.padded_length(); - if let Some(contents) = self.mapped_contents() { - // SAFETY: as in `clear`: the buffer's host-coherent bytes, which nothing else uses - // yet. - unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, size as usize) }; - s.device.shared().counts.new_buffer_cleared(size); - if self.mirror().is_none() { - return Ok(()); - } - } - let (raw, start) = self.at(0); - let device = &s.device; - let weak: Weak = Arc::downgrade(s); - let keeper: Weak = weak; - (device.shared().textures.first_moves).register_fill( - device, - keeper, - raw, - start..start + size, - ) - } - - /// Set the bytes `range` of a new two-copy buffer's device copy to zero (`managed_copy.rs`: - /// the bytes its caller promised read zero, `HostMemory::with_zero_from`), without waiting - /// for the GPU: by the device's next submission, before any of its commands, as - /// [`clear_first`](Self::clear_first) sets a device copy's bytes, and before the copies in - /// registered after it (`texture/first_move.rs`). The fill writes whole words, those `range` - /// touches: one `vkCmdFillBuffer` in the device's memory, never copies of the device's zeros, - /// which lie in host-visible memory. So the copies in of the bytes beside `range` are - /// registered after it, and land over the bytes of its first and last words that lie outside - /// it; the bytes of those words before the buffer's byte 0 or past its device copy's reach - /// are no buffer's (`Device::two_copy_buffer`). - pub(super) fn zero_device_copy_first(&self, range: Range) -> Result<(), Error> { - let s = self.s(); - let (raw, start) = self.at(range.start); - let end = start + (range.end - range.start); - let words = (start - start % 4)..end.next_multiple_of(4); - let device = &s.device; - let weak: Weak = Arc::downgrade(s); - let keeper: Weak = weak; - (device.shared().textures.first_moves).register_fill(device, keeper, raw, words) - } - - /// Give a new buffer whose bytes the host cannot write (`Private` storage) the first `length` - /// bytes `staging` holds, without waiting for the GPU: copied by the device's next - /// submission before any of its commands, after the fill with zeros it took as it was made - /// (`texture/first_move.rs`); that submission holds `staging` until it completed. Past the - /// bound of what is staged, a submission waited for makes it now. - pub(super) fn fill_first_from(&self, staging: Buffer, length: u64) -> Result<(), Error> { - let s = self.s(); - let device = &s.device; - s.staged.store(true, Ordering::Relaxed); - let weak: Weak = Arc::downgrade(s); - let keeper: Weak = weak; - let source = staging.at(0); - let past = (device.shared().textures.first_moves).register_bytes( - keeper, - self.at(0), - source, - length, - Keeps::Staging(Box::new(staging)), - ); - match past { - true => device.submit_internal(|_, _| {}), - false => Ok(()), - } - } - - /// The bytes from byte 0 a copy out of the buffer reads: its length, but for a no-copy - /// buffer the rest of the host pages its range touches, as far as its `VkBuffer` holds them - /// (all of them where the device's buffer of them fits the pages, `host_memory.rs`). Plain - /// Metal reads the caller's bytes there, current ones, from the pointer to its pages' end - /// (an M4 under macOS 27.0.1). Past them, and past another buffer's length, its API validation - /// stops the copy, and plain Metal reads zeros, bytes written past the length, or another - /// resource's: refused (`Invalid`). A read twin's is its length, as its buffer's copy's is - /// (`read_twin.rs`), so a copy refused out of the buffer is refused out of the twin too. - pub(super) fn copy_reach(&self) -> u64 { - let s = self.s(); - match &s.bytes { - Bytes::Own(own) if own.identity.key.is_read_twin() => own.shape().reach.min(s.length), - Bytes::Own(own) => own.shape().reach, - Bytes::Heap(_) => s.length, - } - } - - /// The `VkBuffer`, and where the buffer's byte `offset` lies in it. Every Vulkan use of a - /// buffer takes its offsets from here, since a buffer's byte 0 may lie past the `VkBuffer`'s: - /// a no-copy buffer's ([`Buffer::base`]), and a heap buffer's, which is its heap's. - pub(super) fn at(&self, offset: u64) -> (vk::Buffer, u64) { - self.at_for(offset, ReadApart::Binding) - } - - /// Whether its `VkBuffer` was handed out, shared with what watches it - /// (`shadow_standing::StandingAcross`). - pub(super) fn handed_out(&self) -> Arc { - Arc::clone(&self.s().handed_out) - } - - /// Note that its `VkBuffer` was handed out (`Buffer::vk_buffer`). - pub(super) fn hand_out(&self) { - self.s().handed_out.store(true, Ordering::Release); - } - - /// Make the first work still waiting on its `VkBuffer` `raw` now, by a submission waited for: - /// a new buffer's zeros or staged bytes, or a `Managed` buffer's upload (`clear_first`, - /// `fill_first_from`, `upload`), which the device's next submission would make before its - /// commands (`texture/first_move.rs`), over what the caller's own work wrote through the - /// handle meanwhile. Only the work whose destination is `raw`, in the order it was noted: on - /// the staging queue where the device reserved one, else on its first `VkQueue`, and after no - /// other queue's work (`Device::settle_mine`). Nothing is submitted where none waits: once any - /// submission of the device's took it. `raw` is the caller's: a no-copy buffer's import counts - /// each read of its `VkBuffer` apart for its reason (`HostImport::note_read_apart`), so this - /// reads none. - pub(super) fn settle_first_work(&self, raw: vk::Buffer) -> Result<(), Error> { - let device = &self.s().device; - match device.shared().textures.first_moves.fills_wait(raw) { - true => device.settle_mine( - Mine { - buffer: Some(raw), - image: None, - }, - false, - ), - false => Ok(()), - } - } - - /// Note, as it is made, that its maker declared the bytes between a texture's rows and slices - /// over it unobserved (`BufferDescriptor::padding_unobserved`). - pub(super) fn declare_padding_unobserved(&self) { - self.s().padding_unobserved.store(true, Ordering::Release); - } - - /// Whether its maker declared the bytes between a texture's rows and slices over it - /// unobserved (`BufferDescriptor::padding_unobserved`). - pub(super) fn padding_unobserved(&self) -> bool { - self.s().padding_unobserved.load(Ordering::Acquire) - } - - /// Whether only the device's commands, in the order the runtime records and submits them, - /// write the bytes the GPU uses: a `Private` buffer's, which no CPU maps - /// ([`Buffer::mapped_contents`]), and a `Managed` buffer's own on a device without unified - /// memory ([`HostCopy`]), which the CPU's writes reach only through the copies the device's - /// next submission makes before its commands (`managed.rs`, `managed_copy.rs`). Not one whose - /// `VkBuffer` was handed out (`Buffer::vk_buffer`) or whose memory was made exportable - /// (`exported_memory.rs`), which work of another API's may write. - pub(super) fn gpu_bytes_ordered(&self) -> bool { - let own = self.storage_mode() == StorageMode::Private || self.mirror().is_some(); - own && !self.s().handed_out.load(Ordering::Acquire) && !self.memory_exported() - } - - /// Whether the buffer's memory was allocated exportable (`exported_memory.rs`): never where - /// the system has no handle the runtime exports memory as (file descriptors). - pub(super) fn memory_exported(&self) -> bool { - #[cfg(unix)] - { - self.exported().is_some() - } - #[cfg(not(unix))] - { - false - } - } - - /// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for - /// (`HostImport::note_read_apart`). - pub(super) fn at_for(&self, offset: u64, reason: ReadApart) -> (vk::Buffer, u64) { - match &self.s().bytes { - Bytes::Own(own) => own.with(reason, |pages| (pages.raw, pages.base + offset)), - Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset + offset, reason), - } - } - - /// [`Buffer::at`] while the buffer's bytes lie in pages, read with them at once: `None` while - /// they are detached (`detach.rs`), when its `VkBuffer` is the device's stand-in, which holds - /// none of its bytes. - pub(super) fn attached_at(&self, offset: u64) -> Option<(vk::Buffer, u64)> { - match &self.s().bytes { - Bytes::Own(own) => { - own.with_attached(ReadApart::Binding, |pages| (pages.raw, pages.base + offset)) - } - Bytes::Heap(bytes) => bytes.bytes.attached_at(bytes.offset + offset), - } - } - - /// Where the buffer's byte 0 lies in its `VkBuffer` ([`Buffer::at`]'s offset of byte 0), read - /// without the `VkBuffer`: a no-copy buffer's [`Buffer::base`], a heap buffer's offset in its - /// heap's. - pub(super) fn start(&self) -> u64 { - match &self.s().bytes { - Bytes::Own(own) => own.shape().base, - Bytes::Heap(bytes) => bytes.bytes.start() + bytes.offset, - } - } - - /// The `VkBuffer`, and where the space the bind layer states the buffer in starts in it: - /// 0 for a buffer of its own, a heap buffer's offset in its heap's. The bind layer's offsets - /// (`ArgumentTable::stage_table`) count from there, [`Buffer::base`] bytes before byte 0. - /// A multiple of 256 bytes, so every alignment Vulkan asks of an offset holds of it. - pub(super) fn space(&self) -> (vk::Buffer, u64) { - // `at(0)` less `base()`, from one look at where the buffer lies. - let space = |pages: &Pages, base: u64| (pages.raw, pages.base - base); - match &self.s().bytes { - Bytes::Own(own) => match &own.lie { - Lie::Fixed(fixed) => space(&fixed.pages, Shape::of(&fixed.pages).base), - Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => space( - &pages.import.pages(ReadApart::Binding), - pages.import.shape.base, - ), - Lying::Detached(detached) => { - space(&detached.pages, Shape::of(&detached.pages).base) - } - Lying::Gone(_) => read_gone(), - }, - }, - Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset, ReadApart::Binding), - } - } - - /// [`space`](Self::space), where the buffer lies over host pages (or is placed in a heap that - /// does) read through `kept`, which keeps where such buffers lie ([`KeptSpaces`]): the same - /// answer, with no lock taken and nothing written that other threads read, while no no-copy - /// buffer moved since `kept` read it. - pub(super) fn space_kept(&self, kept: &mut KeptSpaces) -> (vk::Buffer, u64) { - match &self.s().bytes { - Bytes::Own(own) => match &own.lie { - Lie::Host(cell) => { - let (raw, base, shape_base) = kept.of(cell); - (raw, base - shape_base) - } - Lie::Fixed(_) => self.space(), - }, - Bytes::Heap(bytes) => bytes.bytes.at_kept(bytes.offset, kept), - } - } - - /// [`space`](Self::space) for a bind that keeps no [`KeptSpaces`]: counted, where the buffer - /// lies over host pages (or is placed in a heap that does), as a read [`KeptSpaces`] did not - /// keep (`WorkCounts::bind_spaces_read`). - pub(super) fn space_read(&self) -> (vk::Buffer, u64) { - if let Some(cell) = self.space_cell() { - cell.device.shared().counts.thread().bind_space_read(); - } - self.space() - } - - /// The hold on the host pages the buffer's space lies in: a no-copy buffer's own, or the - /// no-copy heap's it is placed in; `None` for any other buffer. - fn space_cell(&self) -> Option<&Arc> { - match &self.s().bytes { - Bytes::Own(own) => match &own.lie { - Lie::Host(cell) => Some(cell), - Lie::Fixed(_) => None, - }, - Bytes::Heap(bytes) => bytes.bytes.space_cell(), - } - } - - /// [`at_for`](Self::at_for) for a binding, read through `kept` as - /// [`space_kept`](Self::space_kept) reads. - fn at_kept(&self, offset: u64, kept: &mut KeptSpaces) -> (vk::Buffer, u64) { - match &self.s().bytes { - Bytes::Own(own) => match &own.lie { - Lie::Host(cell) => { - let (raw, base, _) = kept.of(cell); - (raw, base + offset) - } - Lie::Fixed(_) => self.at_for(offset, ReadApart::Binding), - }, - Bytes::Heap(bytes) => bytes.bytes.at_kept(bytes.offset + offset, kept), - } - } - - /// Where the buffer's byte 0 lies in its bind layer space ([`Buffer::space`]): 0, but for a - /// no-copy buffer whose pointer misses the buffer's memory alignment (bound that many bytes - /// below it). An alignment Vulkan asks of an offset holds of `base` plus Metal's offset. - pub(super) fn base(&self) -> u64 { - match &self.s().bytes { - Bytes::Own(own) => own.shape().base, - Bytes::Heap(_) => 0, - } - } - - /// [`base`](Self::base) and [`device_address`](Self::device_address) together, from one look - /// at where the buffer lies, a no-copy buffer's pages read for `reason` - /// (`HostImport::note_read_apart`): what a binding of it reads (`argument_table::bound_buffer`), - /// each as its own call reads it. - pub(super) fn base_and_device_address(&self, reason: ReadApart) -> (u64, Option) { - let address = |pages: &Pages| Some(pages.memory.device_address? + pages.base); - match &self.s().bytes { - Bytes::Own(own) => match &own.lie { - Lie::Fixed(fixed) => (Shape::of(&fixed.pages).base, address(&fixed.pages)), - Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => { - let read = pages.import.pages(reason); - (pages.import.shape.base, address(&read)) - } - Lying::Detached(detached) => { - (Shape::of(&detached.pages).base, address(&detached.pages)) - } - Lying::Gone(_) => read_gone(), - }, - }, - Bytes::Heap(bytes) => ( - 0, - (bytes.bytes.device_address()).map(|address| address + bytes.offset), - ), - } - } - - /// The external memory the buffer's bytes lie in, from that memory's record, which an image - /// bound there names (`Memory::bound_memory`): a heap's buffer's, its heap's. - pub(super) fn bound_memory(&self) -> BoundMemory { - let s = self.s(); - match &s.bytes { - Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { - lock(&s.device.shared().memory).bound_memory(&pages.memory.placement) - }), - Bytes::Heap(bytes) => bytes.bytes.bound_memory(), - } - } - - /// The memory the buffer's bytes lie in: the `VkDeviceMemory`, the offset of the buffer's - /// first byte in it, and its memory type's index. A texture over the buffer aliases it there - /// (`texture.rs`). - pub(super) fn memory(&self) -> (vk::DeviceMemory, u64, u32) { - match &self.s().bytes { - Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { - let placement = &pages.memory.placement; - ( - placement.memory, - placement.offset + pages.offset, - placement.type_index(), - ) - }), - Bytes::Heap(bytes) => { - let (memory, offset, type_index) = bytes.bytes.memory(); - (memory, offset + bytes.offset, type_index) - } - } - } - - /// A `Managed` buffer's host copy, on a device without unified memory ([`HostCopy`]). - pub(super) fn mirror(&self) -> Option<&HostCopy> { - match &self.s().bytes { - Bytes::Own(own) => own.mirror.as_ref(), - Bytes::Heap(_) => None, - } - } - - /// The caller's pages as the host copy of a `Managed` no-copy buffer on a device without - /// unified memory (`managed_copy.rs`), where the buffer is one. - pub(super) fn caller_copy(&self) -> Option<&Arc> { - match self.mirror() { - Some(HostCopy::Caller(caller)) => Some(caller), - Some(HostCopy::Own(_)) | None => None, - } - } - - /// Where a blit encoder's `synchronize_resource` copies the buffer's bytes to, where it has a - /// host copy ([`HostCopy`]): the runtime's own's `VkBuffer`, whose byte 0 is the buffer's, - /// or the caller's pages (`managed_copy.rs`'s [`SyncTarget`]). - pub(super) fn host_copy(&self) -> Option { - match self.mirror()? { - HostCopy::Own(mirror) => Some(SyncTarget::Own(mirror.raw)), - HostCopy::Caller(caller) => caller.sync_target(), - } - } - - /// The CPU address of the bytes the GPU uses: [`Buffer::contents`], but `None` for a buffer - /// with a host copy ([`HostCopy`]), whose `contents` are that copy. A reader of the GPU's - /// writes takes the bytes from here, else through a device copy. - pub(super) fn device_contents(&self) -> Option> { - match self.mirror() { - Some(_) => None, - None => self.mapped_contents(), - } - } - - /// Copy the bytes `range` of a buffer with a host copy ([`Mirror`]) from that copy to the - /// buffer's own, by the device's next submission whose commands may reach the buffer (or an - /// internal one), before any of its commands, after the commands before it on its `VkQueue` - /// (`texture/first_move.rs`'s `register_upload`), which the call does not wait for: every - /// command buffer committed after the call reads the bytes, and none submitted before that - /// submission on its `VkQueue` sees them land under it. The copy reads the host copy as that - /// submission runs, and the submission holds the host copy until it completed. `replaces` - /// says which batch takes it ([`Replaces`]): where no command buffer can have read the - /// bytes, one that takes a new buffer's first fill (`register_bytes`). The copy stages - /// nothing (`texture/first_move.rs`'s `Keeps::HostCopy`), so it makes no submission, however - /// many bytes wait; pages no import maps are staged (but those a guest RAM's chunk imports - /// hold, which the GPU copies from them), and past the bound of what is staged a submission - /// waited for makes them now (`managed_copy.rs`). Nothing for a buffer without a - /// host copy, nor for an empty range. - pub(super) fn upload(&self, range: Range, replaces: Replaces) -> Result<(), Error> { - let s = self.s(); - let mirror = match self.mirror() { - Some(HostCopy::Own(mirror)) => mirror, - // The caller's pages, through their import or staging (`managed_copy.rs`). - Some(HostCopy::Caller(caller)) => return caller.copy_in(self, range, true, replaces), - None => return Ok(()), - }; - if range.is_empty() { - return Ok(()); - } - let device = &s.device; - s.staged.store(true, Ordering::Relaxed); - let weak: Weak = Arc::downgrade(s); - register_copy_in( - device, - weak, - (self.at(range.start), (mirror.raw, range.start)), - range.end - range.start, - Keeps::HostCopy(Box::new(Arc::clone(mirror))), - replaces, - ); - Ok(()) - } - - /// Copy the bytes `range` of a buffer with a host copy ([`HostCopy`]) to its own, taken at the - /// commit stamped `commit` (`managed.rs`'s `Modified`) for the device's next submission of a - /// command buffer committed at or after it that may reach the buffer, before any of its - /// commands, as the device's policy says (`DevicePolicy::managed_copy_in`): under - /// `ManagedCopyInPolicy::AtSubmission` (the default) the GPU copies them from the host copy as - /// that submission runs ([`upload`](Self::upload)), with no copy on the CPU but of pages no - /// import maps and no guest RAM's chunk imports hold (`managed_copy.rs`); under `AtCommit` the CPU copies them now, as the host copy - /// holds them, into staging memory that submission copies from (`managed_copy::stage_in`), - /// and where that memory is not found the GPU copies them from the host copy as under the - /// default. Nothing for a buffer without a host copy, nor for an empty range, nor for pages - /// detached. - pub(super) fn upload_at_commit(&self, range: Range, commit: u64) { - let replaces = Replaces::Read(commit); - let policy = self.generation().compile_device().policy().managed_copy_in; - let staged = match (policy, self.mirror()) { - (ManagedCopyInPolicy::AtCommit, Some(HostCopy::Caller(caller))) => { - caller.copy_in_now(self, range.clone(), commit) - } - (ManagedCopyInPolicy::AtCommit, Some(HostCopy::Own(_))) => { - match self.mapped_contents() { - Some(contents) => { - super::managed_copy::stage_in(self, contents, range.clone(), true, replaces) - } - None => Ok(()), - } - } - // A range of a few whole words written inline, read from the host copy as the - // submission that takes it is recorded (`managed.rs`). - _ if self.upload_inline(&range, commit) => return, - // Copies from the host copy (or a guest RAM's chunk imports that hold it), which stage - // nothing and go with this commit's batch; pages no import maps staged, a failed - // submission past the bound failing the device, which the commit's own submission - // reports. - _ => { - let _ = self.upload(range, replaces); - return; - } - }; - // As above. - if staged.is_err() { - let _ = self.upload(range, replaces); - } - } - - /// Write `range` of a buffer with a host copy ([`HostCopy`]) into its own bytes inline, taken - /// at the commit stamped `commit`, where it is at most `managed::INLINE_BYTES` of whole words - /// (its start in the buffer's `VkBuffer` and its length multiples of 4) and the host copy is - /// mapped: the device's next submission of a command buffer committed at or after that commit - /// that may reach the buffer reads the bytes from the host copy as it is recorded and writes - /// them before any of its commands, by `vkCmdUpdateBuffer`s in its command stream, as - /// [`upload`](Self::upload) would copy them, counted (`WorkCounts::managed_ranges_inlined`). - /// Whether it did; where not, the range is copied as ever. An unaligned range is copied: a - /// write widened to whole words would put the host copy's bytes over neighbours the GPU may - /// have written since. - fn upload_inline(&self, range: &Range, commit: u64) -> bool { - let s = self.s(); - let device = &s.device; - let length = range.end - range.start; - let onto = self.at(range.start); - let words = onto.1.is_multiple_of(4) && length.is_multiple_of(4); - if length == 0 || length > super::managed::inline_bound(device) || !words { - return false; - } - let (from, keeps): (NonNull, Box) = match self.mirror() { - Some(HostCopy::Own(mirror)) => { - let Some(mapped) = mirror.placement.mapped else { - return false; - }; - // The host copy holds the buffer's bytes from its start, `range` among them. - let at = mapped.as_ptr().wrapping_add(range.start as usize); - let Some(at) = NonNull::new(at) else { - return false; - }; - (at, Box::new(Arc::clone(mirror))) - } - Some(HostCopy::Caller(caller)) => match caller.inline_source(range) { - Some(source) => source, - None => return false, - }, - None => return false, - }; - s.staged.store(true, Ordering::Relaxed); - let weak: Weak = Arc::downgrade(s); - let keeper: Weak = weak; - let moves = &device.shared().textures.first_moves; - // SAFETY: `keeps` keeps the host copy mapped until the submission that reads the bytes - // completed (`FirstMoves::register_inline_upload`), and it holds the range; only the - // program's CPU, outside the runtime's Rust, writes it. - let from = unsafe { HostBytes::new(from, length as usize) }; - moves.register_inline_upload(keeper, onto, from, keeps, commit); - if self.caller_copy().is_some() { - device.shared().counts.managed_copied(length, true); - } - true - } - - /// Copy `range` of the bytes of `source` (a `VkBuffer`, and where the buffer's byte - /// `range.start` lies in it) into the buffer's own, by the device's next submission whose - /// commands may reach the buffer (or an internal one), before any of its commands, after the - /// commands before it on its `VkQueue`, as [`upload`](Self::upload) copies, the submission - /// holding `held` until it completed: a two-copy buffer's copy in from the caller's pages - /// (`managed_copy.rs`), counted (`WorkCounts::managed_bytes_copied_in`), or from staging - /// buffers of a host copy's bytes ([`upload_at_commit`](Self::upload_at_commit)), taken by - /// the batch `replaces` says ([`Replaces`]). Where `bounded` and `held` is a staging buffer - /// ([`Keeps::Staging`]), past the bound of what is staged, a submission waited for makes it - /// now; else it waits for the device's next: a copy from a host copy ([`Keeps::HostCopy`]) - /// stages nothing and makes none. - pub(super) fn copy_in_from( - &self, - source: (vk::Buffer, u64), - range: Range, - held: Keeps, - (bounded, replaces): (bool, Replaces), - ) -> Result<(), Error> { - let s = self.s(); - let device = &s.device; - let bytes = range.end - range.start; - s.staged.store(true, Ordering::Relaxed); - let weak: Weak = Arc::downgrade(s); - let past = register_copy_in( - device, - weak, - (self.at(range.start), source), - bytes, - held, - replaces, - ); - if self.caller_copy().is_some() { - device.shared().counts.managed_copied(bytes, true); - } - match past && bounded { - true => device.submit_internal(|_, _| {}), - false => Ok(()), - } - } - - /// Whether the GPU's writes to the buffer's host pages are dropped (Metal's private option - /// bit 24, or a read-only rebind: `read_only_view.rs`, `copied.rs`); false for a buffer over - /// no host pages. - pub(super) fn drops_writes(&self) -> bool { - let Some(cell) = self.pages_cell() else { - return false; - }; - cell.drops_writes() - || cell.current().is_some_and(|pages| { - pages.import.drops_writes() || pages.import.copy_drops_writes() - }) - } - - /// Keep `token` for the buffer's range, dropped once the range is free (`RangeToken`): a - /// buffer of its own, as a creator makes it. Internal for a buffer of a heap, which holds no - /// range of its own, or one that keeps a token already: no creator gives one so. - pub(super) fn keep_range_token(&self, token: RangeToken) -> Result<(), Error> { - match &self.s().bytes { - Bytes::Own(own) => own.range_token.keep(token), - Bytes::Heap(_) => Err(internal("a range token for a heap's buffer")), - } - } - - /// Another reference to the buffer, which a command buffer holds it by - /// (`EncoderCore::retain_shared`). - pub(super) fn held(&self) -> Arc { - self.0.clone() - } - - /// The address of what [`held`](Self::held) refers to, in host memory: no other object's - /// while it lives (`retained.rs`). - pub(super) fn address(&self) -> usize { - Arc::as_ptr(&self.0).cast::<()>().addr() - } - - /// The encoder core that holds it from an argument table's retain (`retained::HeldBy`). - pub(super) fn held_by(&self) -> &HeldBy { - // The program's buffer's, whatever generation its parts are of: an encoder core's retain - // names the buffer, not its parts. - &self.0.held_by - } - - /// The buffer's identity for hazard tracking: a heap buffer's is its heap's, as Metal tracks - /// a heap's resources as one ([`Buffer::tracked`]). - pub(super) fn identity(&self) -> Identity { - // Every generation's parts keep the buffer's identity (`Buffer::carry`). - match &self.0.bytes { - Bytes::Own(own) => own.identity, - Bytes::Heap(bytes) => bytes.bytes.identity(), - } - } - - /// The key of the host memory a no-copy buffer joined, made over the bytes another covers - /// (`host_aliases.rs`): its uses carry one of that key too. `None` for any other buffer. - pub(super) fn alias(&self) -> Option { - let s = self.s(); - match &s.bytes { - Bytes::Own(own) if matches!(own.lie, Lie::Host(_)) => { - s.device.shared().aliases.of(own.identity.key) - } - Bytes::Own(_) | Bytes::Heap(_) => None, - } - } - - /// The bytes `range` of the buffer as hazard tracking keys them: its identity - /// ([`Buffer::identity`]), and the range in its bytes, or for a heap buffer in its heap's. - pub(super) fn tracked(&self, range: Range) -> (Identity, Range) { - // A heap's buffer is never carried (`Buffer::carry`). - let shift = match &self.0.bytes { - Bytes::Own(_) => 0, - Bytes::Heap(bytes) => bytes.offset, - }; - (self.identity(), range.start + shift..range.end + shift) - } - - /// The Vulkan device address of the buffer's byte 0, where the device enables - /// `bufferDeviceAddress`. - pub(super) fn device_address(&self) -> Option { - match &self.s().bytes { - Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { - let address = pages.memory.device_address?; - Some(address + pages.base) - }), - Bytes::Heap(bytes) => bytes - .bytes - .device_address() - .map(|address| address + bytes.offset), - } - } - - /// The buffer's range for a resident set, where the device gives buffers device addresses: - /// in its `VkBuffer`'s space, as the residency states a used buffer (`residency.rs`), with - /// a hold on its pages that keeps them while a command buffer may reach them. A buffer placed - /// in a heap: its own range, as the residency states it, with a hold on the heap's pages. - pub(super) fn resident(&self) -> Option<(ResidentRange, PagesHold)> { - let s = self.s(); - let own = match &s.bytes { - Bytes::Own(own) => own, - Bytes::Heap(heap) => { - let (whole, held) = heap.bytes.resident()?; - let guest = s.address.0; - let host = whole.host + guest.checked_sub(whole.guest)?; - return Some((ResidentRange::new(host, guest, s.length), held)); - } - }; - let range = |pages: &Pages| { - let host = pages.memory.device_address?; - let guest = s.address.0.checked_sub(pages.base)?; - Some(ResidentRange::new(host, guest, pages.base + s.length)) - }; - match &own.lie { - Lie::Fixed(fixed) => Some(( - range(&fixed.pages)?, - PagesHold::Fixed { - _pages: Arc::clone(fixed), - }, - )), - // A releasable import released is listed without a range: no shader reaches it - // unnamed (`host_residency.rs`). - Lie::Host(cell) => { - let host = cell.current()?; - let listing = host.import.listing()?; - let listed = range(&listing)?; - Some(( - listed, - PagesHold::Host { - _pages: ListedPages::new(host), - }, - )) - } - } - } - - /// A hold on the memory the buffer's bytes lie in now, which keeps nothing else of it - /// ([`MemoryHold`]): a heap's buffer's, its heap's. `None` while its bytes are detached. - pub(super) fn memory_hold(&self) -> Option { - self.s().memory_hold() - } - - /// A handle that does not keep the buffer (`WeakBuffer`). - pub(super) fn downgrade(&self) -> WeakBuffer { - WeakBuffer(Arc::downgrade(&self.0)) - } - - /// The buffer's label and purgeable state. - pub(super) fn attributes(&self) -> &ResourceAttributes { - &self.s().attributes - } - - /// What a buffer made over the same host memory shares of this one (`BufferDescriptor:: - /// range_of`): its address, the range it holds, and the first byte of host memory its bytes - /// are now; `None` but for a no-copy buffer of its own range. - pub(super) fn sharable_range(&self) -> Option<(GpuAddress, Held, NonNull)> { - match &self.s().bytes { - Bytes::Own( - own @ OwnBytes { - owner: Owner::Caller, - .. - }, - ) => Some(( - self.exposed_address(ReadApart::SharedRange), - own.reserved, - self.mapped_contents()?, - )), - Bytes::Own(_) | Bytes::Heap(_) => None, - } - } - - /// Whose memory the buffer's bytes are, where they are the caller's: a no-copy buffer's - /// host pages, or the memory of the caller's `VkBuffer`; a heap buffer's, its heap's (a heap - /// over host pages, `Device::new_heap_with_bytes_no_copy`). - pub(super) fn caller_memory(&self) -> Option { - match &self.s().bytes { - Bytes::Own(OwnBytes { - owner: Owner::Caller, - .. - }) => Some(CallerMemory::HostPages), - Bytes::Own(OwnBytes { - owner: Owner::Vulkan { .. }, - .. - }) => Some(CallerMemory::VkBuffer), - Bytes::Own(_) => None, - // A heap's buffer is its heap's bytes: the caller's where the heap is over them. - Bytes::Heap(bytes) => bytes.bytes.caller_memory(), - } - } - - /// Whether the copy engine's queue family, the copy queue's - /// (`Device::new_command_queue_for_copies`), shares the buffer's `VkBuffer`: every one the - /// runtime made, which is concurrent among the device's families and the staging queue's - /// (`sharing.rs`); a caller's where the caller made it concurrent with that family - /// (`wrapped_buffer.rs`); a heap buffer's, its heap's. - pub(super) fn copy_engine_shares(&self) -> bool { - match &self.s().bytes { - Bytes::Own(OwnBytes { - owner: Owner::Vulkan { copy_engine }, - .. - }) => *copy_engine, - Bytes::Own(_) => true, - Bytes::Heap(bytes) => bytes.bytes.copy_engine_shares(), - } - } - - /// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's - /// `VkBuffer`), under which the images of textures over its exported memory park - /// (`dma_buf/parked.rs`); `None` for a no-copy buffer and a heap's. - pub(super) fn fixed_pages(&self) -> Option> { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => Some(Arc::clone(fixed)), - Bytes::Own(_) | Bytes::Heap(_) => None, - } - } - - /// The buffer's hold on its host pages: a no-copy buffer's, or a no-copy heap's own - /// buffer's; `None` for any other buffer, a heap's buffer among them. - pub(super) fn host_cell(&self) -> Option<&Arc> { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => Some(cell), - Bytes::Own(_) | Bytes::Heap(_) => None, - } - } - - /// Note `views`, a texture's over the buffer's bytes, where a rebind gives those other host - /// pages (a no-copy buffer's, or for a heap's buffer its heap's): the rebind empties them. - pub(super) fn watch_views(&self, views: &Arc) { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => cell.watch(views), - Bytes::Own(_) => {} - Bytes::Heap(bytes) => bytes.bytes.watch_views(views), - } - } - - /// Where the buffer's byte `offset` lies in the device's import of the caller's host pages - /// it lies in now ([`HostPages::in_import`]): `None` for a buffer over no host pages, a - /// detached one, or one whose pages' memory is no such import. - pub(super) fn host_memory_at(&self, offset: u64) -> Option { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => match cell.lying() { - Lying::In(pages) => pages.in_import(offset), - Lying::Detached(_) | Lying::Gone(_) => None, - }, - Bytes::Own(_) => None, - Bytes::Heap(bytes) => bytes.bytes.host_memory_at(bytes.offset + offset), - } - } - - /// The hold on the host pages the buffer's bytes lie in: a no-copy buffer's own, a buffer - /// of a no-copy heap its heap's buffer's; `None` for bytes of the runtime's memory or of the - /// caller's `VkBuffer`. - pub(super) fn pages_cell(&self) -> Option<&Arc> { - match &self.s().bytes { - Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) => Some(cell), - Bytes::Own(_) => None, - Bytes::Heap(bytes) => bytes.bytes.pages_cell(), - } - } - - /// The buffer's Metal address, read for the runtime's own bookkeeping (a live-table key, a - /// lookup), which hands it out to no one: [`Buffer::gpu_address`] without its exposure. - pub(super) fn metal_address(&self) -> GpuAddress { - // Every generation's parts keep it (`Buffer::carry`). - self.0.address - } - - /// Keep a no-copy buffer's import imported for good from now on, its Metal address handed - /// out for `reason` (`host_residency.rs`): imported again now where the device released it, - /// and its live-table range read again where one was noted before a release. - fn expose(&self, reason: ReadApart) { - let Some(cell) = self.host_cell() else { - return; - }; - let bit = reason.bit(); - let before = cell.exposed.load(Ordering::Acquire); - if before & bit != 0 { - return; - } - if let Some(pages) = cell.current() { - match before { - 0 => { - if pages.import.expose(reason) { - self.generation().shared().live_buffers.refresh(self); - } - } - // Kept imported already: the new reason is only counted. - _ => pages.import.note_read_apart(reason), - } - } - cell.exposed.fetch_or(bit, Ordering::Release); - } - - /// [`Buffer::at`] for a blit's command, which reads the `VkBuffer` without exposing the - /// buffer: a no-copy buffer's import the device released while idle is imported again first - /// (`host_residency.rs`). With what the command buffer holds of the import's objects, where - /// the device may release them (`rebind::ImportHold`). Refused where the device cannot import - /// them again. - pub(super) fn blit_at( - &self, - offset: u64, - ) -> Result<((vk::Buffer, u64), Option), Error> { - if let Bytes::Own(OwnBytes { - lie: Lie::Host(cell), - .. - }) = &self.s().bytes - { - if let Lying::In(pages) = cell.lying() { - let (held, hold) = pages.import.blit_pages()?; - return Ok(((held.raw, held.base + offset), hold)); - } - } - Ok((self.at(offset), None)) - } - - /// The host pages the buffer's bytes lie in now ([`Buffer::pages_cell`]): a no-copy - /// buffer's, or a no-copy heap's for a buffer of the heap; `None` for any other buffer, and - /// while they are detached. - pub(super) fn host_pages(&self) -> Option> { - self.pages_cell()?.current() - } - - /// Where the buffer's byte 0 lies from the first byte of the host pages it lies in - /// ([`host_pages`](Self::host_pages)), read without their import: 0 for a no-copy buffer's - /// own pages, the buffer's offset in its heap for a no-copy heap's buffer. - pub(super) fn offset_in_host_pages(&self) -> u64 { - match &self.s().bytes { - Bytes::Own(_) => 0, - Bytes::Heap(bytes) => bytes.bytes.offset_in_host_pages() + bytes.offset, - } - } - - /// The runtime wrote the host addresses `addresses` of the buffer's bytes through its - /// `contents` itself (a `replaceRegion`, an argument encoder's or a rasterization-rate map's - /// write): reported to the logs of the writes to its pages, where their memory came with one - /// (`dirty_pages::PagesLog`, writer 0), so every copy of the pages takes them. The pages are - /// looked at only on a device some of whose pages came with a log. - pub(super) fn wrote_host(&self, addresses: Range) { - if !self.s().device.shared().dirty.logged() { - return; - } - if let Some(log) = self.host_pages().as_ref().and_then(|pages| pages.log()) { - log.wrote_at(addresses); - } - } - - /// The host imports `buffers` lie in now, each counted once however many lie in it - /// (`host_aliases.rs`): a committed command buffer's used buffers' - /// (`WorkCounts::host_imports_used`). Buffers over no host pages count none. The first - /// [`FEW_IMPORTS`] distinct imports are told apart in place, with no list made and nothing - /// sorted; past them, all of them are listed and sorted. An import lives while a buffer of - /// `buffers` holds it, so no two of them share an address. - pub(super) fn distinct_host_imports(buffers: &[Buffer]) -> u64 { - let imports = || { - (buffers.iter()) - .filter_map(|buffer| buffer.host_pages()) - .map(|pages| Arc::as_ptr(&pages.import)) - }; - let mut few = [std::ptr::null::(); FEW_IMPORTS]; - let mut seen = 0; - for import in imports() { - if few[..seen].contains(&import) { - continue; - } - if seen == FEW_IMPORTS { - let mut all: Vec<*const HostImport> = imports().collect(); - all.sort_unstable(); - all.dedup(); - return all.len() as u64; - } - few[seen] = import; - seen += 1; - } - seen as u64 - } - - /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), where they are host - /// pages (a no-copy buffer's, or for a heap's buffer its heap's): a detach makes its image - /// present a stand-in (`detach.rs`). - pub(super) fn note_texture(&self, noted: NotedTexture) { - if let Some(cell) = self.pages_cell() { - // Made over detached bytes, its stand-in's sink may be read through. - if noted.sink && cell.detached() { - let reached = std::iter::once((noted.texture(), noted.id, Unexact::StorageSink)); - self.generation().note_stale(cell, reached); - } - cell.watch_texture(noted); - } - } - - /// Note `watch`, an image in place over the buffer's bytes, where they are host pages (a - /// no-copy buffer's, or for a heap's buffer its heap's): a rebind makes it again over its new - /// pages (`texture/in_place_image.rs`). - pub(super) fn watch_in_place(&self, watch: InPlaceWatch) { - if let Some(cell) = self.pages_cell() { - cell.watch_in_place(watch); - } - } - - /// Whether the buffer's bytes are detached host pages (a no-copy buffer's, or for a heap's - /// buffer its heap's, `detach.rs`). - pub(super) fn detached(&self) -> bool { - self.pages_cell().is_some_and(|cell| cell.detached()) - } - - /// A texture is being made over the buffer's bytes: where they are host pages (a no-copy - /// buffer's, or for a heap's buffer its heap's), a detach, and a rebind of them while they - /// are detached, refuse until the hold goes (`detach.rs`, `buffer_descriptor.rs`), so - /// whether they are detached holds while the texture is made. Take it before the texture - /// binds or views them, and keep it until the texture is noted. - pub(super) fn making_texture(&self) -> Option { - let cell = self.pages_cell()?; - lock(&cell.textures).making += 1; - Some(TextureMaking(Arc::clone(cell))) - } - - /// The index of the memory type of the host pages the buffer's bytes lie in (a no-copy - /// buffer's, or for a heap's buffer its heap's), or lay in while they are detached; else of - /// its memory's. - pub(super) fn pages_type_index(&self) -> u32 { - match self.pages_cell().map(|cell| cell.lying()) { - Some(Lying::In(pages)) => pages.type_index(), - Some(Lying::Detached(detached)) => detached.type_index, - Some(Lying::Gone(_)) => read_gone(), - None => self.memory().2, - } - } - - /// Whether the buffer's bytes lie in a copy of the caller's pages (a copied host buffer, - /// `copied.rs`), not an import of them ([`Buffer::host_backing`]); false for a buffer over no - /// host pages, or detached. - pub(crate) fn copied(&self) -> bool { - self.host_backing() == Some(crate::HostBacking::Copied) - } - - /// Whether the host pages the buffer's bytes lie in (a no-copy buffer's, or for a heap's - /// buffer its heap's), or lay in while they are detached, were imported as dma-bufs - /// (`dma_buf.rs`); false for a buffer over no host pages. - pub(super) fn over_dma_buf(&self) -> bool { - match self.pages_cell().map(|cell| cell.lying()) { - Some(Lying::In(pages)) => pages.over_dma_buf(), - Some(Lying::Detached(detached)) => detached.over_dma_buf, - Some(Lying::Gone(_)) | None => false, - } - } - - /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained - /// device: of the generation the buffer was made on, then of each one the device's recoveries - /// carried the buffer to. The handle is the caller's: it keeps meaning that generation while - /// held, past a recovery that carries the buffer on, its raw handles that generation's - /// `VkDevice`'s, kept alive while held. - pub fn device(&self) -> Device { - self.generation().clone() - } - - /// The generation handle [`device`](Self::device) answers a clone of, borrowed for the - /// runtime's own reads: a caller's handle is `device`'s, as a recovery lets go of the - /// object's handle of a lost generation at that generation's rest (`device/carry.rs`). - pub(crate) fn generation(&self) -> &Device { - &self.s().device - } - - /// `length`: the length the buffer was made with. - pub fn length(&self) -> u64 { - // Every generation's parts keep it (`Buffer::carry`). - self.0.length - } - - /// `contents`: the CPU address of the buffer's bytes, or `None` for `Private` storage. A - /// no-copy buffer's is the caller's pointer. Reading or writing through it while the GPU - /// writes those bytes is a data race, as in Metal. - /// - /// While a no-copy buffer is detached ([`detach_backing`](Buffer::detach_backing); for a - /// heap's buffer, its heap), it answers the caller's pointer of the pages it lay in last (its - /// making's or its last rebind's), as Metal's does: the pages are the caller's, which the - /// runtime reads and writes nothing of until a rebind gives the buffer pages again. - pub fn contents(&self) -> Option> { - self.mapped_contents().or_else(|| self.detached_contents()) - } - - /// [`contents`](Buffer::contents) where the bytes are mapped now, which the runtime reads and - /// writes through: `None` while a no-copy buffer is detached. - pub(crate) fn mapped_contents(&self) -> Option> { - if self.storage_mode() == StorageMode::Private { - return None; - } - match &self.s().bytes { - // A host copy holds the buffer's bytes from its start. - Bytes::Own(OwnBytes { - mirror: Some(HostCopy::Own(mirror)), - .. - }) => mirror - .placement - .mapped - .and_then(|mapped| NonNull::new(mapped.as_ptr())), - // The caller's pages (`managed_copy.rs`): `None` while they are detached. - Bytes::Own(OwnBytes { - mirror: Some(HostCopy::Caller(caller)), - .. - }) => caller.mapped_contents(), - // The offset is inside the placement, which the mapping covers. - Bytes::Own(own) => { - let shape = own.shape(); - let mapped = shape.mapped?; - NonNull::new(mapped.as_ptr().wrapping_add(shape.offset as usize)) - } - // The heap's storage mode is the buffer's, and the offset lies inside the heap. - Bytes::Heap(bytes) => bytes.bytes.mapped_contents().and_then(|contents| { - NonNull::new(contents.as_ptr().wrapping_add(bytes.offset as usize)) - }), - } - } - - /// Whether the host maps the bytes the GPU reads and writes, through which the runtime may - /// read what the GPU wrote once it completed ([`read_mapped`](Buffer::read_mapped)): not a - /// `Private` buffer, nor a `Managed` one's host copy on a device without unified memory - /// ([`HostCopy`]), nor a copy of the caller's pages ([`copied`](Buffer::copied)), whose - /// GPU's bytes are not the pages. - pub(super) fn maps_gpu_bytes(&self) -> bool { - self.storage_mode() != StorageMode::Private && self.mirror().is_none() && !self.copied() - } - - /// The `N` bytes at `offset`, as the host reads them now through the buffer's mapping - /// ([`mapped_contents`](Buffer::mapped_contents)): where they lie in host pages (a no-copy - /// buffer's, or for a heap's buffer its heap's), read with those pages held, so a detach and - /// a rebind meanwhile let none of them go under the read. `None` where nothing maps them now - /// (a `Private` buffer, a detached one), or `offset + N` passes the buffer's length. - pub(super) fn read_mapped(&self, offset: u64) -> Option<[u8; N]> { - if offset.checked_add(N as u64)? > self.length() { - return None; - } - let contents = match &self.s().bytes { - Bytes::Heap(bytes) => return bytes.bytes.read_mapped(bytes.offset + offset), - Bytes::Own(OwnBytes { - mirror: None, - lie: Lie::Host(cell), - .. - }) => return cell.read(offset), - Bytes::Own(_) => self.mapped_contents()?, - }; - let mut bytes = [0u8; N]; - // SAFETY: the mapping holds the buffer's `length` bytes from `contents`, which its own - // memory keeps mapped while the buffer lives, and `offset + N` is at most that. A write - // to them meanwhile races, as a read of `contents` does on Metal. - unsafe { - let at = contents.as_ptr().wrapping_add(offset as usize); - std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N); - } - Some(bytes) - } - - /// The caller's pointer of the pages a detached no-copy buffer lay in last, or for a heap's - /// buffer its offset from its detached heap's: what [`contents`](Buffer::contents) answers - /// while it is detached. `None` for any other buffer. - fn detached_contents(&self) -> Option> { - if self.storage_mode() == StorageMode::Private { - return None; - } - match &self.s().bytes { - Bytes::Own(OwnBytes { - mirror: Some(HostCopy::Caller(caller)), - .. - }) => caller.contents(), - Bytes::Own(OwnBytes { - mirror: Some(HostCopy::Own(_)), - .. - }) => None, - Bytes::Own(own) => match &own.lie { - Lie::Host(cell) => cell.detached_pointer(), - Lie::Fixed(_) => None, - }, - Bytes::Heap(bytes) => bytes.bytes.detached_contents().and_then(|contents| { - NonNull::new(contents.as_ptr().wrapping_add(bytes.offset as usize)) - }), - } - } - - /// The buffer's identity, a runtime extension ([`ObjectId`]): Metal names a buffer by its - /// pointer; this is unique among the process's buffers, textures and heaps for the buffer's - /// life and never reused, where a `gpu_address` is taken again once its buffer is freed. - pub fn object_id(&self) -> ObjectId { - // Every generation's parts keep it (`Buffer::carry`). - self.0.object_id - } - - /// `gpuAddress`: the buffer's address in the device's Metal address space. A heap buffer's - /// is its heap's plus its offset there (`Heap::gpu_address`). - /// - /// A no-copy buffer whose import the device may release while idle and import again at its - /// next blit (an import of dma-bufs: a runtime-internal residency, which nothing of Metal's - /// observes) is kept imported for good from this call on: a command may reach it unnamed by - /// this address. - pub fn gpu_address(&self) -> GpuAddress { - self.exposed_address(ReadApart::Address) - } - - /// [`Buffer::gpu_address`] for the runtime's use that hands the address on for `reason` (a - /// binding's, a buffer sharing the range): the import kept as `gpu_address` keeps it, - /// counted for that reason. - pub(super) fn exposed_address(&self, reason: ReadApart) -> GpuAddress { - self.expose(reason); - self.s().address - } - - /// `resourceOptions`: the options the buffer was made with, its hazard tracking mode - /// resolved (`Default` reports `Tracked` for a buffer made outside a heap, as Metal's do, and - /// a heap buffer reports its heap's). - pub fn resource_options(&self) -> ResourceOptions { - self.s().options - } - - /// `cpuCacheMode`. - pub fn cpu_cache_mode(&self) -> CpuCacheMode { - self.0 - .options - .cpu_cache_mode() - .expect("checked when the buffer was made") - } - - /// `storageMode`. - pub fn storage_mode(&self) -> StorageMode { - self.0 - .options - .storage_mode() - .expect("checked when the buffer was made") - } - - /// `hazardTrackingMode`: `Tracked` or `Untracked`, `Default` resolved as Metal resolves it. - pub fn hazard_tracking_mode(&self) -> HazardTrackingMode { - self.identity().mode() - } - - /// `heap`: the heap the buffer is placed in, if it is. - pub fn heap(&self) -> Option<&Heap> { - match &self.s().bytes { - Bytes::Own(_) => None, - Bytes::Heap(bytes) => Some(&bytes.heap), - } - } - - /// The bytes of the heap the buffer is placed in, and where its byte 0 lies among them: - /// `None` for a buffer outside a heap. - pub(super) fn heap_bytes(&self) -> Option<(&Buffer, u64)> { - match &self.s().bytes { - Bytes::Own(_) => None, - Bytes::Heap(bytes) => Some((&bytes.bytes, bytes.offset)), - } - } - - /// `heapOffset`: where the buffer lies in a placement heap. Metal answers 0 for a buffer of an - /// automatic heap, whatever its place (measured), and for one outside a heap. - pub fn heap_offset(&self) -> u64 { - match &self.s().bytes { - Bytes::Heap(bytes) if bytes.heap.heap_type() == HeapType::Placement => bytes.offset, - Bytes::Heap(_) | Bytes::Own(_) => 0, - } - } - - /// `makeAliasable`: a heap buffer's bytes may be another resource's from now on. An automatic - /// heap gives its range to the next resource it places (which then reads the bytes as they - /// are); a placement heap's buffer is aliasable from the start, so nothing changes. Using the - /// buffer after is the program's error, as in Metal. - /// - /// A buffer outside a heap stays as it is, not aliasable, as plain Metal leaves it where its - /// validation stops the call. - pub fn make_aliasable(&self) -> Result<(), Error> { - let s = self.s(); - let Bytes::Heap(bytes) = &s.bytes else { - return Ok(()); - }; - bytes - .heap - .make_aliasable(bytes.offset, s.length, &bytes.aliasable); - Ok(()) - } - - /// `isAliasable`: whether `make_aliasable` was called on an automatic heap's buffer; true for - /// a placement heap's from the start, and false outside a heap, as Metal answers. - pub fn is_aliasable(&self) -> bool { - match &self.s().bytes { - Bytes::Heap(bytes) => bytes.aliasable.load(Ordering::Acquire), - Bytes::Own(_) => false, - } - } -} - -impl Buffer { - /// Carry the buffer to `to`, its device's next generation, by the recovery that made it or by - /// its maker (`device/carry.rs`): its parts there, the same buffer (its `ObjectId`, hazard - /// key, Metal address with a share of its range, its range token, label and purgeable state), - /// kept among `to`'s program resources and live buffers. A buffer in fresh pages lies in the - /// same pages there, imported again, its contents and `contents` pointer as they were, and so - /// does one in a block of the runtime's own pages (`memory.rs`'s `Holds::PageBuffers`), at its - /// offset in them; a `Private` one in new memory, its contents lost with the `VkDevice` (it - /// reads zero), but one in exportable memory over that memory's payload imported again, at its - /// offset there, reading what the memory holds (`exported_memory.rs`). Its parts on the - /// generation it leaves are let go of once none of that - /// generation's command buffers may record. Left the lost generation's, refused where it meets - /// the next (`RuntimeGap::MadeBeforeRecovery`): a buffer of pooled host-visible memory the - /// device allocated, whose `contents` pointer is its block's mapping (or a `Managed` buffer's - /// host copy's), a detached no-copy buffer, a heap's (its heap's carry carries it, - /// `Heap::carry`), one over the caller's `VkBuffer`, a `Shared` or `Managed` one in exportable - /// memory or one in an opaque descriptor's dedicated allocation, and one whose making there - /// fails. - pub(crate) fn carry(&self, to: &Device) -> Result { - self.carry_as(to, CarryOf::Program) - } - - /// [`Buffer::carry`] of a heap's own buffer (`heap.rs`), for its heap's carry - /// (`Heap::carry`), kept among none of `to`'s program resources or live buffers, as it was - /// among none of its lost generation's: a `Private` one in new memory where the heap's - /// textures can lie too ([`Device::place_heap_buffer`]), its contents lost with the - /// `VkDevice` (it reads zero); one over the caller's host memory made again over the same - /// pages, as a no-copy buffer is, its bytes as they are. Left the lost generation's: a - /// `Shared` one, of pooled host-visible memory (a heap's own buffer never lies in the - /// runtime's own pages), and one over the caller's memory a no-copy buffer's carry leaves. - pub(crate) fn carry_heap_bytes(&self, to: &Device) -> Result { - self.carry_as(to, CarryOf::Heap) - } - - /// [`Buffer::carry`] of a buffer of the runtime's own whose `contents` pointer no program - /// holds, which its owner reads again after the carry (an indirect command buffer's records, - /// a visible function table's words), kept among none of `to`'s program resources or live - /// buffers: in the runtime's own pages, the same pages there, its contents and pointer as - /// they were; in pooled host-visible memory, new memory of its class there, its contents lost - /// with the `VkDevice` (it reads zero) and its pointer that memory's mapping, where a - /// program's buffer stays the lost generation's ([`Left::Pooled`]). - pub(crate) fn carry_runtime(&self, to: &Device) -> Result { - self.carry_as(to, CarryOf::Runtime) - } - - /// [`Buffer::carry`] of a buffer of `of`. - fn carry_as(&self, to: &Device, of: CarryOf) -> Result { - let of_heap = of == CarryOf::Heap; - // The generation it was carried to last: a later recovery carries it on from there. - let mut last = &self.0; - while let Some(next) = last.next.get() { - last = &next.0; - } - if last.device.same(to) { - // Carried already, by its maker. - return Ok(Contents::Kept); - } - let own = match &last.bytes { - Bytes::Own(own) => own, - Bytes::Heap(_) => return Err(Left::Heap), - }; - let fixed = match (&own.owner, &own.lie) { - (Owner::Runtime, Lie::Fixed(fixed)) => fixed, - (Owner::Caller, Lie::Host(cell)) => { - return self.carry_no_copy(last, own, cell, to, of_heap) - } - (Owner::Caller, _) => return Err(Left::NoCopy), - (Owner::Vulkan { .. }, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller), - }; - let from = last.device.shared(); - let placement = &fixed.pages.memory.placement; - let bound = lock(&from.memory).bound_memory(placement); - let runtime_s = matches!( - bound, - BoundMemory::Own | BoundMemory::Blocks | BoundMemory::DmaBufBlocks - ); - // Exportable memory, which another API imports (`exported_memory.rs`). A block of the - // runtime's own buffers allocated exportable is never exported (`Holds::FdBuffers`, - // `Holds::FdDmaBufs`). - let exportable = !runtime_s && !placement.over_own_pages() && !placement.in_page_block(); - let modes = Modes::of(last.options).map_err(|_| Left::Failed)?; - let class = buffer_class("carry", modes).map_err(|_| Left::Failed)?; - let (length, lead, reach) = (last.length, fixed.pages.offset, fixed.pages.reach); - let size = (last.allocation + lead).next_multiple_of(16); - let at = Place::Shared { - address: last.address, - held: own.reserved, - }; - // A two-copy buffer's host copy, made again there (`managed_copy.rs`). - let mut mirror = None; - let (raw, placement, contents) = if exportable { - // A `Private` buffer's memory is its block's payload, imported again there, the - // buffer at its offset in it: the memory the other API imported before, which it - // reaches still, read as it holds it (`exported_memory.rs`). A `Shared` or `Managed` - // one's `contents` pointer is its block's mapping, which new memory cannot keep. - if modes.storage != StorageMode::Private || own.mirror.is_some() { - return Err(Left::Exported); - } - #[cfg(not(unix))] - return Err(Left::Exported); - #[cfg(unix)] - { - let (raw, placement) = - to.buffer_in_carried_export(size, &last.device, placement)?; - if to.address_space_for(at).place(at, length).is_err() { - let shared = to.shared(); - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), raw) }; - lock(&shared.memory).free(shared.vk(), &placement); - return Err(Left::Failed); - } - (raw, placement, Contents::Kept) - } - } else if let Some(HostCopy::Caller(caller)) = &own.mirror { - let carried = caller.carry(to, length, last.options).ok_or(Left::NoCopy)?; - let Ok((raw, placement)) = to.managed_device_copy(carried.device_bytes()) else { - return Err(Left::Failed); - }; - if to.address_space_for(at).place(at, length).is_err() { - let shared = to.shared(); - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), raw) }; - lock(&shared.memory).free(shared.vk(), &placement); - return Err(Left::Failed); - } - mirror = Some(HostCopy::Caller(Arc::new(carried))); - (raw, placement, Contents::Kept) - } else if modes.storage == StorageMode::Private - || (of == CarryOf::Runtime && !placement.over_own_pages() && !placement.in_page_block()) - { - // New memory, as a new buffer's: its contents went with the lost `VkDevice`. In a - // plain block (`Device::place_buffer`), where any of the device's buffers may lie, as - // they do until its check of exportable blocks answered (`Holds::FdBuffers`); a - // heap's where its textures can lie too, as its making placed it. A runtime buffer of - // pooled host-visible memory too: no program holds its `contents` pointer. - let shared = to.shared(); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(false)), - ); - // SAFETY: the device is live and `info` valid. - let raw = - unsafe { crate::creation::buffer(shared.vk(), &info) }.map_err(|_| Left::Failed)?; - shared.counts.buffer_made(info.usage); - // A buffer whose maker declares its padding unobserved on the device's linear images' - // alignment, as its making placed it. - let granule = match last.padding_unobserved.load(Ordering::Acquire) { - true => to.linear_image_alignment(), - false => LINEAR_IMAGE_ALIGNMENT, - }; - let placed = match of_heap { - true => to.place_heap_buffer(raw, length, class, at), - false => to.place_buffer_in(raw, length, (class, Holds::Buffers, granule), at), - }; - match placed { - Ok((placement, _shared_range)) => (raw, placement, Contents::Lost(length)), - Err(_) => { - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), raw) }; - return Err(Left::Failed); - } - } - } else if placement.over_own_pages() { - // The same pages, imported again: the `contents` pointer and the bytes as they are. - let pages = lock(&from.memory).own_pages(placement); - let Some(pages) = pages else { - return Err(Left::Failed); - }; - let Ok(Some((raw, placement))) = to.buffer_over_own_pages(size, class, Some(pages)) - else { - return Err(Left::Failed); - }; - if to.address_space_for(at).place(at, length).is_err() { - let shared = to.shared(); - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), raw) }; - lock(&shared.memory).free(shared.vk(), &placement); - return Err(Left::Failed); - } - (raw, placement, Contents::Kept) - } else if placement.in_page_block() { - // A block of pages the runtime mapped and imported for the program's buffers - // (`memory.rs`'s `Holds::PageBuffers`): the same pages imported again, once for every - // buffer carried from the block, the buffer at its offset in them: the `contents` - // pointer and the bytes as they are. - let pages = lock(&from.memory).page_block_pages(placement); - let Some(pages) = pages else { - return Err(Left::Failed); - }; - let Ok(Some((raw, placement))) = to.buffer_in_carried_pages(size, pages, placement) - else { - return Err(Left::Failed); - }; - if to.address_space_for(at).place(at, length).is_err() { - let shared = to.shared(); - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), raw) }; - lock(&shared.memory).free(shared.vk(), &placement); - return Err(Left::Failed); - } - (raw, placement, Contents::Kept) - } else { - // Pooled host-visible memory the device allocated, or a `Managed` buffer's host copy: - // its `contents` pointer is their mapping, which new memory cannot keep (the module - // docs of `device/carry.rs`). - return Err(Left::Pooled); - }; - let range_token = KeptToken::default(); - own.range_token.hand_to(&range_token); - let carried = Buffer(Arc::new(BufferShared { - device: MadeOn::new(to.clone()), - generation: std::ptr::from_ref(to.shared()).addr(), - object_id: last.object_id, - length, - allocation: last.allocation, - options: last.options, - address: last.address, - attributes: last.attributes.carried(), - bytes: Bytes::Own(OwnBytes { - lie: Lie::Fixed(Arc::new(FixedPages { - device: MadeOn::new(to.clone()), - pages: to.pages_of(raw, placement, lead, lead, reach), - owned: true, - released: AtomicBool::new(false), - freed: AtomicBool::new(false), - #[cfg(unix)] - parked_images: Default::default(), - })), - reserved: own.reserved, - identity: own.identity, - owner: Owner::Runtime, - mirror, - range_token, - }), - held_by: HeldBy::default(), - handed_out: Arc::default(), - padding_unobserved: AtomicBool::new(last.padding_unobserved.load(Ordering::Acquire)), - staged: AtomicBool::new(false), - next: OnceLock::new(), - carried: AtomicBool::new(false), - calls: PartsCalls::default(), - })); - // A two-copy buffer's device copy takes the pages' bytes, its GPU writes not synchronized - // lost with the `VkDevice` (`managed_copy.rs`). - if let Some(caller) = carried.caller_copy() { - if caller - .copy_in(&carried, 0..caller.reach(), true, Replaces::Unread) - .is_err() - { - if let Bytes::Own(parts) = &carried.0.bytes { - parts.range_token.hand_to(&own.range_token); - } - return Err(Left::Failed); - } - } - // Zero, as a new buffer's. Dropping it on failure lets go of its parts and range share, - // and of the range token, which goes back to the buffer left. - if let Contents::Lost(_) = contents { - if carried.clear_first().is_err() { - if let Bytes::Own(parts) = &carried.0.bytes { - parts.range_token.hand_to(&own.range_token); - } - return Err(Left::Failed); - } - } - let lost = LostBuffer { - pages: Arc::clone(fixed), - buffer: Arc::downgrade(last), - }; - let _set = last.next.set(carried); - // Every link before it is carried already. - last.carried.store(true, Ordering::Release); - // Its parts on the lost generation go once none of its command buffers may record. - from.carry.lost(from, Box::new(lost)); - // The program's buffer is the next generation's from now on; a heap's own buffer is its - // heap's, among no program resources. - if of == CarryOf::Program { - let _kept = to.visible(self.clone()); - } - Ok(contents) - } - - /// Carry a buffer placed in a heap to `to`, the generation the heap's own buffer was carried - /// to (`Heap::carry`): the same buffer there (its `ObjectId`, Metal address, label and - /// purgeable state, and the aliasable state it shares with its parts on each generation), - /// at the same offset of the heap's bytes, which are its bytes there as they were here. Its - /// parts on the generation it leaves hold no Vulkan object of their own: their entry among - /// that generation's live buffers and their handle of it go once none of its command - /// buffers may record ([`LostPlaced`]). Nothing where it was carried there already. - pub(crate) fn carry_placed(&self, to: &Device) { - let mut last = &self.0; - while let Some(next) = last.next.get() { - last = &next.0; - } - let Bytes::Heap(placed) = &last.bytes else { - return; - }; - if last.device.same(to) { - return; - } - let carried = Buffer(Arc::new(BufferShared { - device: MadeOn::new(to.clone()), - generation: std::ptr::from_ref(to.shared()).addr(), - object_id: last.object_id, - length: last.length, - allocation: last.allocation, - options: last.options, - address: last.address, - attributes: last.attributes.carried(), - bytes: Bytes::Heap(HeapBytes { - heap: placed.heap.clone(), - bytes: placed.bytes.clone(), - offset: placed.offset, - aliasable: Arc::clone(&placed.aliasable), - }), - held_by: HeldBy::default(), - handed_out: Arc::default(), - padding_unobserved: AtomicBool::new(last.padding_unobserved.load(Ordering::Acquire)), - staged: AtomicBool::new(false), - next: OnceLock::new(), - carried: AtomicBool::new(false), - calls: PartsCalls::default(), - })); - let from = last.device.shared(); - let _set = last.next.set(carried); - // Every link before it is carried already. - last.carried.store(true, Ordering::Release); - let lost = LostPlaced { - buffer: Arc::downgrade(last), - }; - from.carry.lost(from, Box::new(lost)); - } -} - -impl Buffer { - /// [`Buffer::carry`] of a no-copy buffer, or of a no-copy heap's own buffer where `of_heap` - /// (`Device::new_heap_with_bytes_no_copy`, among no program resources), whose parts on the - /// generation it leaves are `last`, `own` their bytes and `cell` their hold on the caller's - /// pages: made again on `to` of the - /// caller's memory its pages were made of ([`HostPages::made_of`]), over the same pages, as its - /// making or last rebind made it (an import of the pointer or of the source's dma-bufs, a run - /// of a guest RAM the device uses, a copy, a read-only view), the caller's gate and resolver - /// asked again there, its `contents` pointer and bytes as they are. Its deallocator and - /// keep-alive wait for its release, or next rebind, there and for the import on each - /// generation to be freed ([`Release::carry_on`]). Left the lost generation's: a buffer - /// detached, or whose last detach's deallocator waits for its next rebind (a detach is not - /// carried), and one whose making there fails. - fn carry_no_copy( - &self, - last: &Arc, - own: &OwnBytes, - cell: &Arc, - to: &Device, - of_heap: bool, - ) -> Result { - let call = match of_heap { - true => "new_heap_with_bytes_no_copy", - false => "new_buffer_with_bytes_no_copy", - }; - if lock(&cell.held_back).is_some() { - return Err(Left::NoCopy); - } - let pages = cell.current().ok_or(Left::NoCopy)?; - let parts = pages.made_of().cloned().ok_or(Left::NoCopy)?; - let pointer = parts.pointer; - let naming = Naming::Carried { - object_id: last.object_id, - identity: own.identity, - attributes: last.attributes.carried(), - }; - let at = Place::Shared { - address: last.address, - held: own.reserved, - }; - let made = (call, last.length, last.options, at); - // SAFETY: the caller's pages stay mapped while the buffer lives, as the contract of the - // memory it was made or rebound over says (`HostMemory::new`). - let carried = unsafe { - to.buffer_over_host_parts( - made, - parts, - None, - of_heap, - cell.drops_writes(), - naming, - None, - ) - } - .map_err(|_| Left::Failed)?; - let (Bytes::Own(carried_own), Some(carried_pages)) = - (&carried.0.bytes, carried.host_pages()) - else { - return Err(Left::Failed); - }; - // What the caller gave back the pages to waits for the buffer's release there and for - // each import of them to be freed. - if let Some(held) = pages.release.get().and_then(Release::carry_on) { - carried_pages.release_to(Release::carried(pointer, last.length, held)); - } - own.range_token.hand_to(&carried_own.range_token); - let unobserved = last.padding_unobserved.load(Ordering::Acquire); - carried - .0 - .padding_unobserved - .store(unobserved, Ordering::Release); - let from = last.device.shared(); - let lost = LostHost { - cell: Arc::clone(cell), - buffer: Arc::downgrade(last), - }; - let _set = last.next.set(carried); - // Every link before it is carried already. - last.carried.store(true, Ordering::Release); - // Its parts on the lost generation go once none of its command buffers may record. - from.carry.lost(from, Box::new(lost)); - // The program's buffer is the next generation's from now on; a heap's own buffer is its - // heap's, among no program resources. - if !of_heap { - let _kept = to.visible(self.clone()); - } - Ok(Contents::Kept) - } - - /// Whether the buffer's parts on the generation it was made on went, carried from there - /// (`FixedPages::release_lost`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn first_parts_freed(&self) -> bool { - match &self.0.bytes { - Bytes::Own(OwnBytes { - lie: Lie::Fixed(fixed), - .. - }) => fixed.freed.load(Ordering::Acquire), - _ => false, - } - } -} - -#[cfg(test)] -thread_local! { - /// A test's hook into [`Buffer::held_parts`], run once by this thread's next call that holds - /// a buffer's parts after the test set it: the test parks that call there across a recovery - /// (`tests/device_recovery_carry.rs`). - pub(crate) static HELD_HOOK: std::cell::RefCell>> = - const { std::cell::RefCell::new(None) }; -} - -/// Run this thread's [`HELD_HOOK`], where a test set it. -#[cfg(test)] -fn held_hook() { - let hook = HELD_HOOK.with(|hook| hook.borrow_mut().take()); - if let Some(hook) = hook { - hook(); - } -} diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs deleted file mode 100644 index 887f07df1..000000000 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ /dev/null @@ -1,3039 +0,0 @@ -//! The buffer constructors that take contents: `newBufferWithBytes:length:options:`, -//! `newBufferWithBytesNoCopy:length:options:deallocator:`, and [`BufferDescriptor`], the runtime -//! extension for Apple's private `newBufferWithDescriptor:` that takes either. Placement (a -//! pinned address) joins the descriptor in step 7. -//! -//! The descriptor is taken by value: a no-copy buffer's deallocator is `FnOnce`, so a descriptor -//! makes one buffer. - -use super::address::{ - AddressPlacement, AddressRange, GpuAddress, Held, Place, PlacementConflict, RangeToken, -}; -use super::address_pool::AddressPool; -use super::buffer::Pages; -use super::buffer::{ - usage, Buffer, BufferParts, HostCell, HostImport, HostPages, Lying, Modes, Naming, Owner, - ReadApart, Replaces, -}; -use super::copied::NotCopied; -use super::device::lock; -use super::dirty_pages::{DirtySource, PagesLog}; -use super::error::MemoryKind; -use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; -use super::heap::{Heap, HeapProblem}; -use super::host_aliases::{Kind, Within}; -use super::host_bytes::HostBytes; -use super::host_memory::{ - based_size, binds_in, buffer_base, import_refused, import_window, not_importable, - refuse_unwritable, refused, unpinnable, Deallocator, HostMemory, HostParts, HostRelease, - ImportRequest, ImportWindow, Importer, KeepAlive, PointerImport, Release, Source, -}; -use super::host_ram::{RamOnDevice, Routed}; -use super::host_residency::Again; -use super::memory::{BoundMemory, ImportFailure, Mapped, MemoryClass, Placement}; -use super::read_only_view::ReadOnlyView; -use super::rebind::RebindProblem; -use super::texture::stand_in::TextureImages; -use super::texture::Remade; -use super::values::{ResourceOptions, StorageMode}; -use super::work_counts::{CopiedBecause, Counters}; -use super::Device; -use crate::release; -use ash::vk; -use metal2vulkan::error::RuntimeDriverDefect; -use std::ptr::NonNull; -use std::sync::Arc; - -/// What a new buffer holds. -#[non_exhaustive] -#[derive(Default)] -pub enum BufferContents<'a> { - /// Zero bytes, as `newBufferWithLength:options:` makes them. - #[default] - Zero, - /// A copy of these bytes (`newBufferWithBytes:length:options:`); their length is the - /// descriptor's. - Copy(&'a [u8]), - /// A copy of the bytes at a pointer, read once into the buffer's memory (or its staging - /// buffer) with no copy of the caller's first (a runtime extension, the same selector: - /// [`HostBytes`], memory that may change while it is read); their length is the - /// descriptor's. - CopyHost(HostBytes<'a>), - /// The caller's host memory itself (`newBufferWithBytesNoCopy:length:options:deallocator:`), - /// given back to `deallocator` when the buffer is released. - NoCopy { - /// The caller's memory: its first byte, of the descriptor's length. - memory: HostMemory, - /// `deallocator`: called when the buffer is released; `None` for none. - deallocator: Option, - /// What keeps the memory mapped (a runtime extension: [`KeepAlive`]), dropped once the - /// device's import of its pages is freed; `None` for none. With one, `deallocator` runs - /// when the buffer is released, as Metal's does; with none, once the import is freed, - /// which may be later (`host-deallocator-delayed`). - keep_alive: Option, - }, -} - -impl std::fmt::Debug for BufferContents<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - BufferContents::Zero => f.write_str("Zero"), - BufferContents::Copy(bytes) => write!(f, "Copy({} bytes)", bytes.len()), - BufferContents::CopyHost(bytes) => write!(f, "CopyHost({} bytes)", bytes.len()), - BufferContents::NoCopy { - memory, - deallocator, - keep_alive, - } => f - .debug_struct("NoCopy") - .field("pointer", &memory.pointer()) - .field("deallocator", &deallocator.is_some()) - .field("keep_alive", &keep_alive.is_some()) - .finish(), - } - } -} - -/// The handle type a buffer's memory is exported as, for another API to import it (a runtime -/// extension: Metal exports no buffer's memory): `BufferDescriptor::exported_as` -/// (`exported_memory.rs`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum MemoryExport { - /// An opaque file descriptor (`VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT`), which CUDA and - /// another `VkDevice` of the same driver import: `Buffer::export_memory_fd`. - OpaqueFd, - /// A dma-buf (`VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT`), which VA-API's `DRM_PRIME_2` - /// surfaces and any other driver's dma-buf imports take: `Buffer::export_memory_dma_buf`. - DmaBuf, -} - -impl MemoryExport { - /// What a device that does not export a buffer's memory as it refuses the making with. - pub(super) fn gap(self) -> RuntimeGap { - match self { - MemoryExport::OpaqueFd => RuntimeGap::ExportableMemory, - MemoryExport::DmaBuf => RuntimeGap::DmaBufExport, - } - } -} - -/// How a buffer of the runtime's own memory a descriptor asks for is made: at `place` in the -/// address space, its byte `aligned` (where given) on a multiple of 256 bytes of its memory, in -/// memory exportable as `export` (where given), and where `buffer.rs`'s `NewBufferOf::Unobserved` -/// says where `padding_unobserved` (`BufferDescriptor::padding_unobserved`). -#[derive(Clone, Copy)] -struct Made { - place: Place, - aligned: Option, - export: Option, - padding_unobserved: bool, -} - -/// `MTLBufferDescriptor` (Apple's private class, a runtime extension): a buffer's length, resource -/// options, contents, and address. Its default is Metal's: length 0, options 0, zero contents, an -/// address the runtime picks (`pinnedGPUAddress` 0). -#[non_exhaustive] -#[derive(Debug, Default)] -pub struct BufferDescriptor<'a> { - /// `length`, in bytes. - pub length: u64, - /// `resourceOptions`: the storage mode, CPU cache mode and hazard tracking mode. - pub resource_options: ResourceOptions, - /// What the buffer holds when made: zeros, a copy, or the caller's memory itself. - pub contents: BufferContents<'a>, - /// `pinnedGPUAddress`: where the buffer goes in the Metal address space (`address.rs`). - pub placement: AddressPlacement, - /// A token the runtime drops once the buffer's range of the address space is free - /// ([`RangeToken`]); `None` for none. A runtime extension: Metal has none. - pub range_token: Option, - /// A live no-copy buffer whose range the buffer shares, at its address: the buffer is a - /// no-copy one over the same first byte of host memory, no longer than it (`address.rs`); - /// `None` for its own range. A runtime extension: Metal answers an IOSurface's address for - /// every buffer over the surface (`newBufferWithIOSurface:`), which a caller standing a - /// surface in with its host memory gives so. - pub range_of: Option<&'a Buffer>, - /// A pool and the offset in it of the slot the buffer goes in (`address.rs`): the buffer - /// answers the pool's address plus the offset and holds its length rounded up to 256 bytes - /// of the pool; `None` for a range of the space. A runtime extension: Metal places a buffer - /// shorter than a page in a slot of a pool of its own, which its API does not name. - pub pool_slot: Option<(&'a AddressPool, u64)>, - /// The maker declares that nothing reads the bytes between the rows of a texture over the - /// buffer, nor between its slices: each row's bytes after its last texel to its pitch, the - /// last row's included, and the bytes from a slice's last row's pitch to the next slice. A - /// texture over the buffer whose rows (or slices) lie apart is then a linear image aliasing - /// the buffer's memory where the device lays one out at its pitches, as one whose rows lie one - /// after another is, or else a `DRM_FORMAT_MOD_LINEAR` image at them where the device makes - /// such images and its in-place check passed for its pooled memory - /// (`WorkCounts::pooled_pitched_images`), not a shadow: its image holds those bytes, and Vulkan lets the image's - /// layout moves and a render pass's load and store operations write them, so they may change - /// to any value whenever the texture is made or used. No other byte changes: one past the - /// image's subresources is reached by no operation on it, and a texel's bytes are the - /// texture's. A texture of an IOSurface plane over the buffer - /// (`Buffer::new_texture_with_iosurface_plane`) takes the declaration too: Metal keeps a - /// plane's padding, but bytes nothing reads cannot tell keeping from changing. Only for a - /// buffer of the runtime's own memory (`Zero`, `Copy` or `CopyHost` contents); refused - /// (`Invalid`, `PaddingUnobservedNoCopy`) with `NoCopy` contents. A buffer - /// the runtime lays in fresh pages it imports (a long one on a device whose pointer imports - /// cost submissions nothing, `WorkCounts::fresh_page_buffers_made`) takes its textures in place - /// where the device's check of such pages passed: there the declaration lets a render pass's - /// load and store change those bytes of a texture whose rows, each to its pitch, share no line - /// of the device's memory with bytes past them, and nothing more. On a unified-memory device - /// whose other buffers lie in blocks allocated exportable (docs/FAST-PATHS.md, the `Private` - /// row) such a buffer lies in blocks of its own, allocated exportable as an opaque file - /// descriptor and a dma-buf where the device's buffer query takes both, in which no image is - /// bound: a texture over it takes a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch bound to a - /// dedicated import of its block's dma-buf (`WorkCounts::exported_dma_buf_images`); elsewhere - /// in a plain block, whose making holds the process's submissions on RADV - /// (`WorkCounts::plain_buffer_blocks_made`). Its placement starts on the device's linear - /// images' memory alignment and takes whole units of it (4096 bytes on Intel's driver for the - /// UHD 630 on Windows, which rounds a small linear image's size up to it; every placement - /// meets the 256 or less of the other devices measured), so an image whose rows fill the - /// buffer lies in bytes the buffer owns, for at most that alignment less one byte more memory. - /// A runtime extension with no Metal counterpart, for a consumer that owns every read of the - /// buffer's bytes; `false` by default, as Metal keeps every byte. - pub padding_unobserved: bool, - /// A byte of the buffer the runtime lays on a multiple of 256 bytes of its memory, the largest - /// linear-image alignment measured (RADV's; the device's own is - /// `Device::minimum_linear_texture_alignment_for_pixel_format`'s answer): a texture over the - /// buffer whose texels start there (and at any multiple of 256 bytes past it) is then the - /// linear image aliasing the buffer's memory where the device lays one out at its pitch, not a - /// shadow, as one at offset 0 is. For a consumer whose textures start at an offset that is no - /// multiple of the alignment, as CoreVideo lays a frame's planes 32 bytes into their surface. - /// The buffer's memory starts that byte's remainder short of the next multiple, at most 255 - /// more bytes of it taken, and its contents (`contents`) with it: where Metal's buffers start - /// on a page, this one's contents start that remainder short of a multiple of 256 (`0xE0` past - /// one for byte `0x20`). Its length, its `gpuAddress` (the runtime's address space's) and - /// Metal's rules of a texture's offset in it (`newTextureWithDescriptor:offset:bytesPerRow:`) - /// are Metal's. Such a buffer is never parked for another making nor laid in fresh pages. - /// Only for a buffer of the runtime's own memory (`Zero`, `Copy` or `CopyHost` contents); - /// refused (`Invalid`, `AlignedByteNoCopy`) with `NoCopy` contents, whose first byte is the - /// caller's. A runtime extension with no Metal counterpart; `None` by default, Metal's - /// placement. - pub aligned_byte: Option, - /// The handle type its memory is exported as, for another API to import it - /// (`Buffer::export_memory_fd`, `Buffer::export_memory_dma_buf`): the buffer lies in memory - /// allocated exportable as it, as `Device::new_exportable_buffer` lays an opaque file - /// descriptor's (`exported_memory.rs`), with the other fields' effects (an aligned byte lies on - /// a multiple of 256 bytes of that memory). Only for a buffer of the runtime's own memory - /// (`Zero`, `Copy` or `CopyHost` contents); refused (`Invalid`, `ExportedNoCopy`) with `NoCopy` - /// contents, and `NotImplemented` on a device that does not export its memory so - /// (`RuntimeGap::ExportableMemory`, `RuntimeGap::DmaBufExport`). A runtime extension with no - /// Metal counterpart; `None` by default, memory no other API imports. - pub exported_as: Option, -} - -impl<'a> BufferDescriptor<'a> { - /// A descriptor of `length` bytes with `resource_options` and `contents`. - pub fn new( - length: u64, - resource_options: ResourceOptions, - contents: BufferContents<'a>, - ) -> BufferDescriptor<'a> { - BufferDescriptor { - length, - resource_options, - contents, - placement: AddressPlacement::Any, - range_token: None, - range_of: None, - pool_slot: None, - padding_unobserved: false, - aligned_byte: None, - exported_as: None, - } - } - - /// This descriptor at `placement` in the address space. - pub fn with_placement(self, placement: AddressPlacement) -> BufferDescriptor<'a> { - BufferDescriptor { placement, ..self } - } - - /// This descriptor with `token`, dropped once the buffer's range is free ([`RangeToken`]). - pub fn with_range_token(self, token: RangeToken) -> BufferDescriptor<'a> { - BufferDescriptor { - range_token: Some(token), - ..self - } - } - - /// This descriptor sharing `buffer`'s range, at its address (`range_of`). - pub fn with_range_of(self, buffer: &'a Buffer) -> BufferDescriptor<'a> { - BufferDescriptor { - range_of: Some(buffer), - ..self - } - } - - /// This descriptor in the slot at `offset` of `pool` (`pool_slot`). - pub fn with_pool_slot(self, pool: &'a AddressPool, offset: u64) -> BufferDescriptor<'a> { - BufferDescriptor { - pool_slot: Some((pool, offset)), - ..self - } - } - - /// This descriptor declaring the bytes between a texture's rows and slices over the buffer - /// unobserved (`padding_unobserved`). - pub fn with_padding_unobserved(self) -> BufferDescriptor<'a> { - BufferDescriptor { - padding_unobserved: true, - ..self - } - } - - /// This descriptor laying byte `byte` of the buffer on a multiple of 256 bytes of its memory - /// (`aligned_byte`). - pub fn with_aligned_byte(self, byte: u64) -> BufferDescriptor<'a> { - BufferDescriptor { - aligned_byte: Some(byte), - ..self - } - } - - /// This descriptor's buffer with its memory exportable as `export` (`exported_as`). - pub fn with_exported_as(self, export: MemoryExport) -> BufferDescriptor<'a> { - BufferDescriptor { - exported_as: Some(export), - ..self - } - } -} - -impl Device { - /// `newBufferWithDescriptor:` (a runtime extension): a buffer of the descriptor's length and - /// options holding its contents, as [`Device::new_buffer`], [`Device::new_buffer_with_bytes`] - /// or [`Device::new_buffer_with_bytes_no_copy`] makes it. - /// - /// Refused as those are; `Copy` bytes of another length than the descriptor's are - /// `Invalid` (`LengthMismatch`); a pinned address whose range meets another resource's bytes, - /// or leaves the space, is `PlacementConflict`. A refused call never runs the deallocator: it - /// is dropped. The descriptor's `range_token` is dropped once the buffer's range is free - /// ([`RangeToken`]), or, for a refused call, before it returns, after any range it took is - /// free again. - /// - /// With `range_of`, the buffer answers that buffer's address and holds its range with it, free - /// once both are gone (each one's token drops with it). Refused: a buffer of another device - /// (`Invalid`, `ForeignObject`); `PlacementConflict::Unshared` unless the contents are `NoCopy` - /// over the first byte of host memory that buffer's bytes are now, of no greater length, that - /// buffer is a no-copy buffer of its own range, and the placement is `Any` or its address. - /// - /// With `pool_slot`, the buffer answers the pool's address plus the offset and holds - /// `round_up(length, 256)` bytes of the pool from there, free once it is gone (its token drops - /// then). Refused: a pool of another device (`Invalid`, `ForeignObject`); - /// `PlacementConflict::OffSlot` for an offset that is not a multiple of 256 or a placement - /// other than `Any` or that address; `OutsidePool` for bytes past the pool's end; `Held` for - /// bytes a live buffer in the pool holds; `Unshared` with `range_of`. - /// - /// With `padding_unobserved`, a texture over the buffer may hold the bytes between its rows - /// and slices in its image (the field's docs). Refused: `Invalid` (`PaddingUnobservedNoCopy`) - /// with `NoCopy` contents. - /// - /// With `aligned_byte`, that byte of the buffer lies on a multiple of 256 bytes of its memory - /// (the field's docs). Refused: `Invalid` (`AlignedByteNoCopy`) with `NoCopy` contents. - /// - /// With `exported_as`, the buffer's memory is exportable as that handle type (the field's - /// docs). Refused: `Invalid` (`ExportedNoCopy`) with `NoCopy` contents; `NotImplemented` - /// ([`RuntimeGap::ExportableMemory`], [`RuntimeGap::DmaBufExport`]) on a device that does not - /// export such memory. - pub fn new_buffer_with_descriptor( - &self, - descriptor: BufferDescriptor<'_>, - ) -> Result { - self.at_serving_taking(descriptor, |device, descriptor| { - device.new_buffer_with_descriptor_now(descriptor) - }) - } - - /// [`Device::new_buffer_with_descriptor`] on the generation that serves (`device/line.rs`). - pub(crate) fn new_buffer_with_descriptor_now( - &self, - descriptor: BufferDescriptor<'_>, - ) -> Result { - const CALL: &str = "new_buffer_with_descriptor"; - self.keep_room(); - let BufferDescriptor { - length, - resource_options, - contents, - placement, - range_token, - range_of, - pool_slot, - padding_unobserved, - aligned_byte, - exported_as, - } = descriptor; - if padding_unobserved && matches!(contents, BufferContents::NoCopy { .. }) { - return Err(invalid(CALL, Problem::PaddingUnobservedNoCopy)); - } - if aligned_byte.is_some() && matches!(contents, BufferContents::NoCopy { .. }) { - return Err(invalid(CALL, Problem::AlignedByteNoCopy)); - } - if exported_as.is_some() && matches!(contents, BufferContents::NoCopy { .. }) { - return Err(invalid(CALL, Problem::ExportedNoCopy)); - } - let place = match (range_of, pool_slot) { - (Some(other), slot) => { - let in_pool = slot.is_some(); - self.shared_place(CALL, other, &contents, length, placement, in_pool)? - } - (None, Some((pool, offset))) => { - if !pool.root_device().same(self) { - return Err(pool.root_device().foreign(CALL, self)); - } - Place::InPool { - pool: pool.gpu_address().0, - offset, - placement, - } - } - (None, None) => Place::At(placement), - }; - let (resource_options, drops_writes) = match contents { - BufferContents::NoCopy { .. } => no_copy_options(resource_options), - _ => (self.own_memory_options(CALL, resource_options)?, false), - }; - let made = Made { - place, - aligned: aligned_byte, - export: exported_as, - padding_unobserved, - }; - let buffer = match contents { - BufferContents::Zero => self.zero_buffer(CALL, length, resource_options, made), - BufferContents::Copy(bytes) => { - if bytes.len() as u64 != length { - return Err(invalid(CALL, Problem::LengthMismatch)); - } - let bytes = HostBytes::from_slice(bytes); - self.buffer_with_bytes(CALL, bytes, resource_options, made) - } - BufferContents::CopyHost(bytes) => { - if bytes.len() as u64 != length { - return Err(invalid(CALL, Problem::LengthMismatch)); - } - self.buffer_with_bytes(CALL, bytes, resource_options, made) - } - // SAFETY: the `HostMemory` constructor's caller vouched for `length` bytes at the - // pointer. - BufferContents::NoCopy { - memory, - deallocator, - keep_alive, - } => unsafe { - self.buffer_over_host_memory( - CALL, - memory, - length, - resource_options, - HostRelease::new(deallocator, keep_alive), - place, - false, - drops_writes, - ) - }, - }?; - if let Some(token) = range_token { - buffer.keep_range_token(token)?; - } - if padding_unobserved { - buffer.declare_padding_unobserved(); - } - Ok(self.visible(buffer)) - } - - /// `newBufferWithBytes:length:options:`: a buffer holding a copy of `bytes`. - /// - /// Refused as [`Device::new_buffer`] is (an empty `bytes` is a length of 0). - pub fn new_buffer_with_bytes( - &self, - bytes: &[u8], - options: ResourceOptions, - ) -> Result { - self.at_serving(|device| device.new_buffer_with_bytes_now(bytes, options)) - } - - /// [`Device::new_buffer_with_bytes`] on the generation that serves (`device/line.rs`). - pub(crate) fn new_buffer_with_bytes_now( - &self, - bytes: &[u8], - options: ResourceOptions, - ) -> Result { - const CALL: &str = "new_buffer_with_bytes"; - self.keep_room(); - let options = self.own_memory_options(CALL, options)?; - let bytes = HostBytes::from_slice(bytes); - let made = Made { - place: AddressPlacement::Any.into(), - aligned: None, - export: None, - padding_unobserved: false, - }; - let buffer = self.buffer_with_bytes(CALL, bytes, options, made)?; - Ok(self.visible(buffer)) - } - - /// `newBufferWithBytesNoCopy:length:options:deallocator:`, its pointer wrapped in `memory` - /// ([`HostMemory`]): a buffer whose bytes are the caller's `length` bytes at - /// `memory.pointer()` (module docs of `host_memory.rs`). `deallocator` runs once, with the - /// pointer and `length`, when the buffer's last reference goes: where that is a command - /// buffer's, in its release on its queue's handler thread, after its completed handlers, where - /// a wait in it for that command buffer returns at once, as Metal's does. A refused call never - /// runs it. - /// - /// Where the device's recovery makes it a new `VkDevice` (`Degradation::DeviceRecovered`), the - /// buffer goes on there, as Metal's goes on across its GPU's recovery: made again over the - /// same pages, as this call or its last rebind made it (the caller's gate, resolver and - /// dma-buf source asked again), its `contents` pointer and its bytes as they were. Its - /// deallocator then runs at its release once no `VkDevice`'s import of the pages is left. A - /// buffer detached at the recovery stays the lost device's, refused where it meets the new one - /// (`RuntimeGap::MadeBeforeRecovery`). - /// - /// The pages are imported here, as Metal wires them when it makes the buffer: the GPU uses - /// the pages mapped at the pointer now, and memory the device cannot import is refused here, - /// as Metal answers nil. The import costs work per page here (on macOS about 11 to 20 ms per - /// GiB measured on an M4 and an M3 Max), where Metal makes the buffer at once and pays at the - /// first command using it (24 to 88 ms per GiB). Where the device refuses the pointer, or - /// imports none (it enables no `VK_EXT_external_memory_host`), and `memory` carries a dma-buf - /// source ([`HostMemory::with_dma_buf`]), the dma-bufs it makes of the pages are imported - /// instead. With Metal's private option bit 24 - /// ([`ResourceOptions::PRIVATE_BIT`]), the GPU's writes to the pages are dropped, as Metal's - /// are: on macOS the pages are imported through a read-only view of them, by their pointer - /// alone; elsewhere the buffer is made over a copy of them whose GPU writes are dropped, - /// announced (`copied-host-pages`): each commit copies in the bytes the CPU changed, the - /// command buffers already submitted read what the GPU wrote, and each batch's completion - /// puts the copy back to the caller's bytes, which the GPU never writes. - /// - /// Where the caller's gate refuses the import ([`HostMemory::with_import_gate`]), where the - /// device refuses the pointer or imports none and no dma-buf of the pages serves (no source - /// given, or one that failed or whose dma-bufs the device refused), or where the import the - /// device and the gate admitted fails (out of memory, another Vulkan error), of the pointer - /// or of the dma-bufs, the buffer is made over a copy of the bytes in memory of the device's - /// own instead, its `contents` still the pointer, announced (`copied-host-pages`): each commit - /// copies in the bytes the CPU changed, and each batch's completion merges back the bytes the - /// GPU changed (`copied.rs`). A copy of pages the process maps read-only drops the GPU's writes - /// instead, as Metal drops them, and writes nothing to the pages. Pages the process cannot read - /// are never copied, and keep the import's refusal. - /// - /// On a device without unified memory - /// ([`DeviceProperties::has_unified_memory`](crate::DeviceProperties::has_unified_memory)) a - /// buffer of `Managed` storage (without bit 24) is two copies, as Metal keeps a managed - /// resource on a Mac with a discrete GPU ([`HostBacking::DeviceCopy`](crate::HostBacking)): - /// the GPU's own in device-local memory, which every command reads and writes, and the - /// caller's pages, its `contents`, copied in now (before any command of a command buffer - /// committed after the call) and by [`did_modify_range`](Buffer::did_modify_range), and copied - /// out by a blit's `synchronize_resource`. The pages are imported as above to be the copies' - /// source and target, but never copied: where the import is not made, the copies go through - /// staging buffers. A CPU write no `did_modify_range` names is not seen by the GPU. Where no - /// device-local memory has room for the GPU's copy, the buffer lies in the pages as a `Shared` - /// one does, announced (`device-memory-overflow`). Where the caller promised the bytes from - /// an offset read zero ([`HostMemory::with_zero_from`]), the GPU's copy takes those bytes as - /// zeros the device writes in its own memory, copied in from the pages only before the - /// offset. - /// - /// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil); - /// `Private` or `Memoryless` storage, as Metal stops them, and an undefined option - /// (`Invalid`); on a device that imports neither pointers (`VK_EXT_external_memory_host`) nor - /// dma-bufs, every memory (`Unsupported`, naming the extension); memory this device cannot - /// import exactly, by its pointer or by its dma-bufs (`Unsupported`, `HostMemory`), among it - /// on Linux a page this process cannot write ([`HostMemory::new`]); - /// dma-bufs that break the source's contract (`Invalid`, `Problem::DmaBuf`); pages past the - /// device's allocation size (`OutOfMemory`). Pages not mapped, or mapped without access, which - /// Metal makes no buffer over (nil), are refused here too, typed as the check or the import - /// answers, though such memory breaks [`HostMemory::new`]'s contract. - /// - /// # Safety - /// - /// `memory` meets the contract of the [`HostMemory`] constructor that made it - /// ([`HostMemory::new`], [`HostMemory::with_dma_buf`]) for `length` bytes. - pub unsafe fn new_buffer_with_bytes_no_copy( - &self, - memory: HostMemory, - length: u64, - options: ResourceOptions, - deallocator: Option, - ) -> Result { - self.at_serving_taking((memory, deallocator), |device, (memory, deallocator)| { - // SAFETY: the caller's contract. - unsafe { - device.new_buffer_with_bytes_no_copy_now(memory, length, options, deallocator) - } - }) - } - - /// [`Device::new_buffer_with_bytes_no_copy`] on the generation that serves (`device/line.rs`). - pub(crate) unsafe fn new_buffer_with_bytes_no_copy_now( - &self, - memory: HostMemory, - length: u64, - options: ResourceOptions, - deallocator: Option, - ) -> Result { - const CALL: &str = "new_buffer_with_bytes_no_copy"; - let (options, drops_writes) = no_copy_options(options); - // SAFETY: the caller's contract. - let buffer = unsafe { - self.buffer_over_host_memory( - CALL, - memory, - length, - options, - HostRelease::new(deallocator, None), - AddressPlacement::Any.into(), - false, - drops_writes, - ) - }?; - Ok(self.visible(buffer)) - } - - /// Tell the device that the pages under the `length` host bytes at `bytes` were replaced (an - /// unmap and a map at the same addresses, as `mmap` with `MAP_FIXED` does): a no-copy buffer - /// (or heap) made after this over any of those bytes imports the pages there then, as each - /// of Metal's `newBufferWithBytesNoCopy:` buffers wires the pages at its address when it is - /// made. Without the call, a no-copy buffer made over exactly the bytes a live one was made - /// over, of its memory class, lies in that one's import (`host_aliases.rs`), and so over the - /// pages that were there when that one was made. Buffers made before the call keep their own - /// imports, and stay ordered with each other as before. A remap under a live buffer breaks - /// [`HostMemory::new`]'s contract, and under a live import of the pointer - /// `VK_EXT_external_memory_host`'s too, which leaves undefined whether the import holds a - /// reference to its pages: what such a buffer's later commands read and write is then - /// unspecified (`docs/FAST-PATHS.md`, known gaps), and this call does not mend it. The pages - /// are replaced or unmapped once every buffer over them signalled that its import went (its - /// keep-alive dropped, or its deallocator ran; docs/HOWTO.md, "Unmapping host memory"). Not a - /// Metal call: Metal needs none. A `length` of 0 tells nothing. - /// - /// The call may come at the unmap or after the new map, but before a buffer is made over the - /// new pages: a buffer made over those bytes while it runs may lie in either pages. The bytes - /// are an address range only, never read: they may be unmapped, and may cover a whole - /// reservation of many buffers. An image in place over a dma-buf of those pages that the - /// device kept as its texture went, for the next texture over them (`HostMemory::with_dma_buf`), - /// goes in the call. The call is safe from any thread while other calls run on - /// others, a no-copy buffer's deallocator among them (the runtime holds no lock this call - /// takes while it runs a deallocator). It is cheap: with no no-copy buffer live it returns at - /// once, and otherwise it finds the buffers over the range by address, whether the range - /// covers none of them or many, never reading them all. - pub fn host_range_remapped(&self, bytes: NonNull, length: u64) { - self.current().host_range_remapped_now(bytes, length) - } - - /// [`Device::host_range_remapped`] on the generation that serves (`device/line.rs`). - pub(crate) fn host_range_remapped_now(&self, bytes: NonNull, length: u64) { - let start = bytes.as_ptr() as u64; - let shared = self.shared(); - // The unit an import's pages round out to: the imports with a page the call covers are - // counted (`WorkCounts::host_imports_remapped`). - let unit = (shared.host_import.as_ref()).map_or(1, Importer::unit); - let end = start.saturating_add(length); - let imports = (shared.aliases).remapped(start, end, unit); - shared.counts.host_range_remapped(imports); - // The images parked over those pages go: a texture made over the new pages asks their - // source (`dma_buf/parked.rs`). - #[cfg(unix)] - shared.residency.remapped(start, end, unit); - } - - /// A buffer of `length` zero bytes made as `made` says, for `call`: refused as - /// [`Device::new_buffer`] is, for a pin the address space cannot honour, and for an export the - /// device does not make; announced as `new_buffer` announces it. - fn zero_buffer( - &self, - call: &'static str, - length: u64, - options: ResourceOptions, - made: Made, - ) -> Result { - let Made { - place, - aligned, - export, - padding_unobserved, - } = made; - if let Some(export) = export { - #[cfg(unix)] - return self.exportable_buffer(call, length, options, (place, aligned), export); - #[cfg(not(unix))] - return Err(Error::NotImplemented(export.gap())); - } - let placed = (place, aligned); - let (buffer, class) = - self.buffer_of_length(call, length, options, placed, padding_unobserved)?; - self.degrade_system_memory(&buffer, class, || format!("buffer of {length} bytes")); - Ok(buffer) - } - - /// A buffer holding a copy of `bytes`, made as `made` says, for `call`: written through its - /// mapping, and from there to a `Managed` buffer's own bytes where it has a host copy - /// (`Buffer::upload`), or for `Private` storage copied from a staging buffer by the device's - /// next submission, before any of its commands, which the call does not wait for - /// (`Buffer::fill_first_from`). - fn buffer_with_bytes( - &self, - call: &'static str, - bytes: HostBytes<'_>, - options: ResourceOptions, - made: Made, - ) -> Result { - let length = bytes.len() as u64; - let buffer = self.zero_buffer(call, length, options, made)?; - // The bytes, read once, through their pointer, into the buffer's memory. - let fill = |target: &Buffer| { - let contents = target - .mapped_contents() - .ok_or_else(|| internal("a host-visible buffer without contents"))?; - // SAFETY: the buffer holds `length` bytes at `contents`, memory of the runtime's own - // that no command uses yet and nothing else reaches. - let into = unsafe { std::slice::from_raw_parts_mut(contents.as_ptr(), bytes.len()) }; - bytes.copy_into(0, into); - Ok::<(), Error>(()) - }; - if buffer.storage_mode() != StorageMode::Private { - fill(&buffer)?; - buffer.upload(0..length, Replaces::Unread)?; - return Ok(buffer); - } - let staging = self.own_buffer(length, ResourceOptions::shared())?; - fill(&staging)?; - buffer.fill_first_from(staging, length)?; - Ok(buffer) - } - - /// A no-copy buffer over `length` bytes of `memory` at `placement`, for `call`, given back to - /// `release` (`host_memory.rs`): a heap's own - /// buffer when `of_heap` (`heap.rs`, `Device::new_heap_with_bytes_no_copy`), whose memory - /// must start at a multiple of the import's unit, the larger of the host page and the - /// device's `minImportedHostPointerAlignment`, so that the heap's offsets are its memory's - /// (`Invalid`, `HeapProblem::HostMemoryAlignment`, elsewhere). Where `drops_writes` (Metal's - /// private option bit 24, [`no_copy_options`]), the pages are imported through a read-only - /// view of them, which drops the GPU's writes (`read_only_view.rs`): an import of its own, - /// which no other buffer lies in or joins, and which the device keeps imported. Where the - /// system maps no such view, the buffer is a copy of the pages whose GPU writes are dropped - /// instead (`copied.rs`), placed but joined by no other buffer. - /// - /// # Safety - /// - /// `memory` meets [`HostMemory::new`]'s contract for `length` bytes. - pub(super) unsafe fn buffer_over_host_memory( - &self, - call: &'static str, - memory: HostMemory, - length: u64, - options: ResourceOptions, - release: HostRelease, - placement: Place, - of_heap: bool, - drops_writes: bool, - ) -> Result { - let zero_from = memory.zero_from(length); - let parts = memory.into_parts(); - let release = release.of(parts.pointer, length); - let made = (call, length, options, placement); - // SAFETY: the caller's contract. - unsafe { - self.buffer_over_host_parts( - made, - parts, - release, - of_heap, - drops_writes, - Naming::New, - zero_from, - ) - } - } - - /// [`Device::buffer_over_host_memory`] of the caller's memory's `parts`, `made` (for its call, - /// of its length and options, at its placement) as the buffer `naming` names, given back to - /// `release`: a new buffer, or one its device's recovery carries to this generation - /// (`Buffer::carry`). A buffer's pages, a heap's own buffer's among them, keep what they were - /// made of, which a recovery makes the buffer again of ([`HostPages::made_of`]). A new `Managed` one on a - /// device without unified memory is two copies (`managed_copy.rs`), its device copy zero from - /// `zero_from` where the caller promised its bytes read zero from there - /// (`HostMemory::with_zero_from`), which nothing else takes: the pages keep no such promise. - /// - /// # Safety - /// - /// The memory of `parts` meets [`HostMemory::new`]'s contract for `length` bytes. - pub(super) unsafe fn buffer_over_host_parts( - &self, - made: (&'static str, u64, ResourceOptions, Place), - parts: HostParts, - release: Option, - of_heap: bool, - drops_writes: bool, - naming: Naming, - zero_from: Option, - ) -> Result { - let (call, length, options, _) = made; - let modes = Modes::of(options)?; - if matches!(naming, Naming::New) && self.two_copies(modes.storage, of_heap, drops_writes) { - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(call, Problem::BufferLength { length })); - } - if self.is_lost() { - return Err(self.lost_refusal()); - } - // SAFETY: the caller's contract. - return unsafe { self.two_copy_buffer(made, parts, release, naming, zero_from) }; - } - // SAFETY: the caller's contract. - unsafe { self.one_copy_buffer(made, parts, release, of_heap, drops_writes, naming) } - } - - /// [`Device::buffer_over_host_parts`] of a buffer that lies in the caller's pages (or a copy - /// of them), never two copies: for a buffer made as [`Naming::HostCopy`] (a two-copy - /// buffer's host copy, `managed_copy.rs`) it is never a copy of them, refused - /// (`managed_copy::uncopied`) where it would be one. - /// - /// # Safety - /// - /// The memory of `parts` meets [`HostMemory::new`]'s contract for `length` bytes. - pub(super) unsafe fn one_copy_buffer( - &self, - (call, length, options, placement): (&'static str, u64, ResourceOptions, Place), - parts: HostParts, - release: Option, - of_heap: bool, - drops_writes: bool, - naming: Naming, - ) -> Result { - let modes = Modes::of(options)?; - let class = host_class(call, modes)?; - if length == 0 || length > self.properties().max_buffer_length { - return Err(nil(call, Problem::BufferLength { length })); - } - if self.is_lost() { - return Err(self.lost_refusal()); - } - let shared = self.shared(); - let importer = shared - .host_import - .as_ref() - .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; - // What the buffer is made of stays with its pages, a heap's own buffer's too, given them - // with the rest below, from the one look at them. - let made_of = parts.clone(); - let HostParts { - pointer, - source, - writable, - dirty, - gate, - runs, - dma_buf_only, - } = parts; - let source = (source, dma_buf_only); - let host = host_window(call, importer, pointer, length, source, drops_writes)?; - // Pages with no route of their own are refused here, but where their runs may lie in a - // guest RAM's chunk (below), refused there where they do not; on a device that imports no - // pointer, they are a copy instead (below), as where a device refuses their pointer. - let no_route = match (host.no_route(importer).filter(|_| !host.pointerless), &runs) { - (Some(refusal), None) => return Err(refusal), - (no_route, _) => no_route, - }; - let window = host.window; - if of_heap && window.offset != 0 { - let alignment = importer.unit(); - let problem = HeapProblem::HostMemoryAlignment { alignment }; - return Err(invalid(call, Problem::Heap(problem))); - } - // A buffer over the bytes a live no-copy buffer was made over, of its memory class, lies - // in its import, and a buffer of either class in its copy where it is a copied host - // buffer and no import of the class lives (`host_aliases.rs`, `copied.rs`): one - // `VkBuffer`, one snapshot and one key, its dma-buf source dropped uncalled and the gate - // unasked, as no page is mapped for it. A heap's own buffer lies so in a live import of - // the same bytes, joining no key (`host_aliases.rs`, "One page, one import"), and copies - // its own; one whose GPU writes are dropped imports or copies its own (its import is a - // read-only view of the pages, or its copy drops them). - let made_over = (pointer.as_ptr() as u64, length); - // A two-copy buffer's host copy lies in no copy of the pages (`managed_copy.rs`), nor - // does a read twin (`read_twin.rs`). - let shares = (!drops_writes) - .then(|| shared.aliases.import(made_over, class)) - .flatten() - .filter(|import| { - !(matches!(naming, Naming::HostCopy | Naming::ReadTwin) && import.copied()) - }) - .filter(|import| !(of_heap && import.copied())); - if let Some(import) = shares { - let address = self.place_window(placement, &window, length)?; - let kind = match import.copied() { - true => Kind::Copy, - false => Kind::Import(class), - }; - let made = (length, modes, of_heap); - let buffer = self.buffer_in_import(Arc::clone(&import), made, address, release, naming); - let key = buffer.identity().key; - // The GPU's writes through it are reported to the import's logs, as through the - // buffer it was made for, over the same bytes (`dirty_pages.rs`), and merged back - // from the copy where it lies in one. Its pages keep what it was made of - // ([`HostPages::made_of`]). - if let Some(pages) = buffer.host_pages() { - pages.logged_as(key); - pages.copied_as(key); - pages.keep_made_of(made_of); - } - if kind == Kind::Copy { - shared.counts.copied_host_buffer_shared(); - self.degrade_copied_shared(call, pointer, length, import.copy_drops_writes()); - } - if of_heap { - shared.aliases.hold(key, made_over, kind, &import); - } else { - shared.aliases.join(key, made_over, kind, &import); - } - shared.aliases.place(key, made_over); - return Ok(buffer); - } - // A copied host buffer made below joins the memory as an import does, so that a later - // buffer over the same bytes lies in its copy; a heap's own copy is placed, joining none. - let noted = |buffer: Buffer| { - let key = buffer.identity().key; - if let (false, Some(pages)) = (of_heap, buffer.host_pages()) { - shared - .aliases - .join(key, made_over, Kind::Copy, pages.import()); - } - shared.aliases.place(key, made_over); - buffer - }; - // Pages the caller resolves to runs of a guest RAM the device uses (`host_ram.rs`): asked - // once, here, holding no lock of the runtime's, before the gate. One run inside one chunk - // is bound in the chunk's import, with no import of its own: no pin, no kernel mapping, - // no gate. Others take the paths below, the runs kept with the buffer. A buffer whose GPU - // writes are dropped is never bound in a chunk: it imports a read-only view of its pages, - // or is a copy of them, whose runs are asked all the same, so that the copy's commits - // copy in only the pages the RAM's log reports written ([`routes_runs`]). - let routed = match &runs { - Some(resolver) if routes_runs(drops_writes) => { - self.route_runs(call, importer, resolver, &window)? - } - _ => None, - }; - // SAFETY: the window's pages are the bytes of the run in the RAM (the resolver's - // contract, `HostMemory::with_runs`). - let in_chunk = (routed.as_ref().filter(|_| !drops_writes)) - .and_then(|routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) }); - let kept_runs = routed.as_ref().map(Routed::kept); - // The logs of the writes to the pages, where their memory came with one or their guest - // RAM did (`dirty_pages::PagesLog`), kept with their import or copy. - let log = pages_log( - (pointer, length), - dirty.as_ref(), - kept_runs.as_ref(), - window.offset, - ); - // One page, one import (`host_aliases.rs`): a buffer (not a heap's own) whose pages a - // live import of another buffer's or heap's holds all of is bound inside that import's - // memory, with no import of its own, no pin and no gate; pages a live import holds some - // of, and not all, and a heap's pages one holds more of, are a copy below, never imported - // again, but where they and every live import that holds some of them are dma-bufs - // ([`Device::imports_beside`]), which import their own. A buffer whose GPU writes are - // dropped imports a read-only view of its own. - let within = match (&in_chunk, drops_writes) { - (None, false) => (shared.aliases).within((window.start, window.size), importer.unit()), - _ => Within::Free, - }; - let inside = match &within { - // SAFETY: the window's pages are the caller's at the addresses the import's pages - // were imported from, which hold all of them (`HostAliases::within`). - Within::Inside(import) if !of_heap => unsafe { - self.bind_in_import(import, &window, length) - }, - _ => None, - }; - let held = inside.is_none() && !matches!(within, Within::Free); - let beside = held && self.imports_beside(&within, &host); - let over_import = held && !beside; - // Imported beside dma-bufs as dma-bufs alone: never by the pointer, nor the gate asked. So - // are pages a guest RAM routes that no chunk binds the buffer in, where the RAM's chunks - // may be imported beside them (`Routed::own_dma_bufs`). - let ram_beside = in_chunk.is_none() - && inside.is_none() - && (routed.as_ref()).is_some_and(|routed| routed.own_dma_bufs(self)); - let dma_bufs_alone = beside || (ram_beside && host.source.is_some()); - let host = HostWindow { - by_pointer: host.by_pointer && !dma_bufs_alone, - ..host - }; - // Pages a guest RAM's chunk import, made or in flight, holds some of, at the RAM's own - // addresses, that no chunk binds the buffer in (its bytes cross a chunk's end, or no run - // resolver routed them): a copy too, never a second import of them (`host_ram.rs`). - // Others the buffer's own import may take are claimed until it is noted below, so that - // no chunk's import takes them meanwhile (`Device::claim_ram_pages`). - let claim = (in_chunk.is_none() && inside.is_none() && !drops_writes) - .then(|| self.claim_ram_pages(window.start..window.start + window.size)); - let over_chunk = matches!(claim, Some(None)); - let (buffer, memory, again) = match (in_chunk, inside) { - // Bound in a chunk's import, or inside a live import: neither is released while the - // buffer lies there. - (Some((buffer, memory)), _) | (None, Some((buffer, memory))) => (buffer, memory, None), - (None, None) => { - if let Some(refusal) = no_route { - return Err(refusal); - } - // A no-copy buffer or heap whose pointer the device would import (not one whose GPU - // writes are dropped) may be a copy instead (`copied.rs`): where the caller's gate - // refuses the import, asked here with the pages it would map, holding no lock of - // the runtime's, before their write permission is asked (a copy pins no page, and - // drops the GPU's writes to pages the process cannot write); where the process - // cannot write them; or where the import it admitted fails, of the pointer or of - // the caller's dma-bufs. - let copyable = !drops_writes; - let copy = (call, pointer, length, modes, placement, of_heap); - // Memory whose GPU writes Metal's private option bit 24 drops, where the system - // maps no read-only view of the pages (`read_only_view.rs`): a copy of them whose - // GPU writes are dropped, the gate unasked and no page pinned. It joins no other - // buffer over the bytes, nor does one lie in it. - // A new one that is no heap's own takes a read twin besides where it can: the - // runtime's buffer over the pages in place, which the commands that cannot write - // it read instead of the copy (`read_twin.rs`). - if drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES { - let twin = (!of_heap && matches!(naming, Naming::New)).then(|| made_of.clone()); - // SAFETY: the caller's contract. - let copied = unsafe { - self.copied_buffer(copy, release, dirty, CopiedFor::ReadOnly, naming) - }?; - let buffer = kept(copied, log, kept_runs, made_of); - if let Some(parts) = twin { - // SAFETY: the parts are the caller's, for the same bytes (the caller's - // contract). - unsafe { self.make_read_twin(&buffer, (call, length, options), parts) }; - } - // Placed after its twin, so that the twin's key is its bytes' (the first - // placed there, `host_aliases.rs`'s `Placements`): a command that reads - // through the twin alone names no use of the copy, whose commit then - // compares none of it, while the copy's uses order against the twin's. - shared.aliases.place(buffer.identity().key, made_over); - return Ok(buffer); - } - // Pages a live import holds some of: a copy, the gate unasked and no page pinned. - if over_import || over_chunk { - let why = match over_import { - true => CopiedFor::OverImport, - false => CopiedFor::OverRamChunk, - }; - // SAFETY: the caller's contract. - let copied = unsafe { self.copied_buffer(copy, release, dirty, why, naming) }; - return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of))); - } - let refused_by_host = copyable - && host.by_pointer - && gate.as_ref().is_some_and(|gate| { - let request = ImportRequest { - start: NonNull::new(window.start as *mut u8).unwrap_or(pointer), - length: window.size, - }; - !gate(request) - }); - if refused_by_host { - // A read twin's refusal makes no copy, and counts as the twin not made alone - // (`WorkCounts::read_twins_unimported`). - if !matches!(naming, Naming::ReadTwin) { - shared.counts.host_import_refused_by_host(); - } - // SAFETY: the caller's contract. - let copied = unsafe { - self.copied_buffer(copy, release, dirty, CopiedFor::Refused, naming) - }; - return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of))); - } - // Only a buffer that imports its pages pins them, and so has their writability - // asked: one that lies in a live import pins none, that import's making asked for - // the same window, and the pages stay writable while imported (`HostMemory::new`). - // Pages the process cannot write are a copy whose GPU writes are dropped, as - // Metal drops them, their source never called ([`unwritable_pages`]). - if unwritable_pages(&host, writable, &shared.counts)? { - // SAFETY: the caller's contract. - let copied = unsafe { - self.copied_buffer(copy, release, dirty, CopiedFor::Unwritable, naming) - }; - return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of))); - } - // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped - // (`HostMemory::new`), and the source's pieces hold them - // (`HostMemory::with_dma_buf`). No lock of the runtime's is held. A no-copy - // buffer's own import of dma-bufs keeps them, so the device may release it while - // idle and import them again (`host_residency.rs`), as it may its own import of the - // pointer where a held pointer import costs every submission; a heap's import - // stays, as does an import of a read-only view. - // Whether the device was asked the pointer, or imports none, whose refusal a - // failed source leaves standing (the window takes it, and the memory is no - // dma-buf-only memory). - #[cfg(unix)] - let pointer_refused = host.by_pointer || host.pointerless; - let imported = - match unsafe { self.import_by_pointer(importer, pointer, length, host, class) } - { - Ok(Ok((buffer, memory))) => { - let again = (!of_heap && !drops_writes) - .then(|| Again::pointer(self, pointer, (length, window, class))) - .flatten(); - Ok((buffer, memory, again)) - } - // A heap's import is dedicated to nothing, as textures placed in the - // heap may be bound in its memory (`texture/heap.rs`); a buffer's own - // takes another buffer over part of its pages (`Device::bind_in_import`) - // and its textures in place only where the driver took it dedicated to - // nothing, else they are a copy or in imports of their own - // (`texture/in_place_image.rs`). - // SAFETY: as above. - #[cfg(unix)] - Ok(Err((source, refusal))) => unsafe { - let kept = (!of_heap, !of_heap); - let window = &window; - self.import_from_source( - call, importer, pointer, length, window, source, class, kept, - ) - } - .map_err(|failed| { - // No dma-buf of the pages served either (the source failed, or the - // device refused its dma-bufs): the device's refusal of the pointer, - // as where no source is given. - let by_device = - pointer_refused && refused(&failed) && refusal == not_importable(); - let error = source_failure(failed, refusal); - ( - FailedImport { - error, - sourced: true, - }, - by_device, - ) - }), - // No source of dma-bufs on this system. - #[cfg(not(unix))] - Ok(Err((source, _))) => match source {}, - // The device's refusal of the pointer, with no source of dma-bufs of the - // pages to take instead. - Err(error) => { - let by_device = error == not_importable(); - let sourced = false; - Err((FailedImport { error, sourced }, by_device)) - } - }; - let (buffer, memory, again) = match imported { - Ok(imported) => { - let unit = importer.unit(); - self.count_import_over_live(&window, unit, routed.as_ref(), beside); - imported - } - // An import the device and the gate admitted that then failed, or pages the - // runtime refused for the driver that no dma-buf of them served, or any failed - // import of dma-bufs alone (beside live ones, or a RAM's chunks: pages a copy - // where none is tried): a copy, announced with the failure. - Err((failed, _)) - if copyable && (dma_bufs_alone || copies_after(&failed.error)) => - { - // SAFETY: the caller's contract. - let copied = unsafe { - self.copied_buffer( - copy, - release, - dirty, - CopiedFor::Failed(failed), - naming, - ) - }; - return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of))); - } - // Pages whose pointer the device refuses (RADV refuses shared memory, a - // `memfd` mapping among it; a device without `VK_EXT_external_memory_host` - // every pointer), with no dma-buf of them served (no source given, a source - // that failed, dma-bufs the device refused): a copy, announced, as Metal makes - // a no-copy buffer over any page. - Err((_, true)) if copyable => { - let why = CopiedFor::DeviceRefused; - // SAFETY: the caller's contract. - let copied = - unsafe { self.copied_buffer(copy, release, dirty, why, naming) }; - return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of))); - } - Err((failed, _)) => return Err(failed.error), - }; - (buffer, memory, again) - } - }; - let (address, reserved) = match self.place_window(placement, &window, length) { - Ok(held) => held, - Err(error) => { - self.discard_import(buffer.raw, memory); - return Err(error); - } - }; - let buffer = self.buffer_of(BufferParts { - raw: buffer.raw, - memory, - offset: window.offset, - base: buffer.base, - length, - allocation: length, - reach: buffer.size - buffer.base, - modes, - address, - reserved, - owner: Owner::Caller, - release, - of_heap, - drops_writes, - mirror: None, - again, - naming, - }); - // A buffer just made lies in its pages (`HostCell::current`), looked at once (their lock, - // `WorkCounts::no_copy_lies_read`) for everything below. - let current = buffer.host_cell().and_then(|cell| cell.current()); - if let Some(pages) = ¤t { - // The caller's log of the pages' writes stays with them (`dirty_pages.rs`). - if let Some(dirty) = dirty { - pages.keep_dirty(dirty); - } - keep_in(pages, &buffer, log, kept_runs, made_of); - } - // A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and - // a later one lies in its import, or inside it over part of them; a heap's own import is - // noted so, joining no key; one whose GPU writes are dropped joins none. - if let (false, Some(current)) = (drops_writes, current) { - let (key, kind) = (buffer.identity().key, Kind::Import(class)); - match of_heap { - true => (shared.aliases).hold(key, made_over, kind, current.import()), - false => { - (shared.aliases).join(key, made_over, kind, current.import()); - } - } - } - // Its uses order against every other key's over bytes they meet, a heap's own buffer's - // too (`host_aliases.rs`). - shared.aliases.place(buffer.identity().key, made_over); - Ok(buffer) - } - - /// Give `buffer`, a no-copy buffer whose hold on its pages is `cell` (`heap`'s own buffer - /// where given), the host memory `memory` of its length from now on, for `call` - /// (`rebind.rs`): imported as [`Device::buffer_over_host_memory`] imports it, the heap's - /// images bound to its bytes made again over it, its deallocator set once the pages are the - /// buffer's. Once the rebind is made, the images swap in, and the old images and the texel - /// views over the old pages go with those pages, once nothing holds them, their deallocator - /// with them. Refused, changing nothing and running no deallocator, as the module says. - /// - /// # Safety - /// - /// `memory` meets [`HostMemory::new`]'s contract for the buffer's length; no command that - /// uses the buffer is encoded or committed meanwhile. - pub(super) unsafe fn rebind_host_pages( - &self, - call: &'static str, - buffer: &Buffer, - cell: &HostCell, - memory: HostMemory, - release: HostRelease, - heap: Option<&Heap>, - ) -> Result<(), Error> { - let class = match buffer.storage_mode() { - StorageMode::Shared => MemoryClass::Shared, - StorageMode::Managed => MemoryClass::Managed, - StorageMode::Private | StorageMode::Memoryless => { - return Err(internal("a no-copy buffer of private storage")) - } - }; - let length = buffer.length(); - if self.is_lost() { - return Err(self.lost_refusal()); - } - // The render encoders' calls and ends that their calls left to the device's lowering - // thread, as the rebind finds them where each call lowers itself (`render/deferral.rs`). - self.shared().deferred.lower_all(); - let key = buffer.identity().key; - let encoded = || invalid(call, Problem::Rebind(RebindProblem::EncodedUses)); - if let Some(refused) = self.rebind_pending(key) { - if let crate::rebind::Unreplaced::Unsubmitted = refused { - self.shared().counts.rebind_refused_unsubmitted(); - } - return Err(encoded()); - } - let shared = self.shared(); - let importer = shared - .host_import - .as_ref() - .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; - let parts = memory.into_parts(); - // What a recovery makes the buffer, or the heap, again of over its new pages - // (`HostPages::made_of`). - let made_of = parts.clone(); - let HostParts { - pointer, - source, - writable, - dirty, - gate, - runs, - dma_buf_only, - } = parts; - // A buffer whose GPU writes are dropped keeps them dropped over its new pages. - let drops_writes = cell.drops_writes(); - let source = (source, dma_buf_only); - let host = host_window(call, importer, pointer, length, source, drops_writes)?; - // As at the buffer's making: refused here, but where the runs may lie in a chunk. - let no_route = match (host.no_route(importer), &runs) { - (Some(refusal), None) => return Err(refusal), - (no_route, _) => no_route, - }; - let window = host.window; - if heap.is_some() && window.offset != 0 { - let alignment = importer.unit(); - let problem = HeapProblem::HostMemoryAlignment { alignment }; - return Err(invalid(call, Problem::Heap(problem))); - } - // The texel views and copies of the textures over the bytes are planned at their offset - // in the `VkBuffer`, the bytes' offset in their page; and their images in place are bound - // where Metal lays their texels out, which keeps their alignment only at that offset. New - // bytes at another offset in their page are given a copy of them laid out at the old - // offset (`copied.rs`), as no import lays them there: the gate is not asked, as nothing is - // imported. A buffer whose GPU writes are dropped is a copy of the new pages where the - // system maps no read-only view of them (`read_only_view.rs`), as at its making, and is - // never one where it imports such a view, which refuses bytes that moved. - let texels = cell.texels(); - let in_place = cell.in_place_images(); - let read_only_copy = drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES; - let copyable = !drops_writes || read_only_copy; - let moved = (!texels.is_empty() || !in_place.is_empty()) && window.offset != cell.offset(); - if moved && !copyable { - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - } - let unit = importer.unit(); - let copy_window = match moved { - true => ImportWindow { - start: (pointer.as_ptr() as u64).wrapping_sub(cell.offset()), - size: cell - .offset() - .checked_add(length) - .and_then(|end| end.checked_next_multiple_of(unit)) - .ok_or_else(not_importable)?, - offset: cell.offset(), - }, - false => window, - }; - // Detached bytes are given pages with no texture being made over them, and none is - // made until the textures that presented stand-ins present their own images again. - let detached_textures = || Error::NotImplemented(RuntimeGap::DetachTextures); - let mut settled = match cell.detached() { - true => Some(cell.settled().ok_or_else(detached_textures)?), - false => None, - }; - // Bytes a live no-copy buffer was made over, of its memory class, are given the pages of - // its import, or of its copy where it is a copied host buffer and no import of the class - // lives, as a buffer made over them lies in it (`host_aliases.rs`), the dma-buf source - // dropped uncalled and the gate unasked: they pin no page, that import's making asked - // about the same window, and the pages stay writable while imported (`HostMemory::new`). - // An import lays the bytes at their offset in their page, so it serves textures planned - // at the old offset only where the bytes did not move in it; a copy lays them from its - // first byte, so it serves textures planned there, and no image in place, whose own copy - // lies in fresh pages it rides on. A heap's own buffer imports its own, whose images - // bound to its bytes are made again over the new import's memory or its dma-bufs, as does - // a buffer whose GPU writes are dropped. - let made_over = (pointer.as_ptr() as u64, length); - let shares = (heap.is_none() && !drops_writes) - .then(|| shared.aliases.import(made_over, class)) - .flatten() - .filter(|import| match import.copied() { - false => !moved, - true => { - in_place.is_empty() && (texels.is_empty() || import.offset() == cell.offset()) - } - }); - // The new pages, what was made again over them, whether they are an import to note over - // the bytes (one of its own, or the live one it lies in), and its claim of them where - // they are a guest RAM's (`host_ram.rs`), held until that import is noted below. - let (pages, remade, noted, claim) = match shares { - Some(import) => { - let noted = !import.copied(); - if import.copied() { - shared.counts.copied_host_buffer_shared(); - self.degrade_copied_shared(call, pointer, length, import.copy_drops_writes()); - } - (self.pages_in_import(import), Remade::default(), noted, None) - } - None => { - // Pages the caller resolves to runs of a guest RAM the device uses - // (`host_ram.rs`), as at the buffer's making: asked once, here, holding no lock of - // the runtime's (the textures over detached bytes let go of meanwhile, and - // settled again after it), before the gate. One run inside one chunk is bound in - // the chunk's import, with no import of its own, no pin and no gate, unless the - // bytes moved in their page, which take the copy laid out at the old offset. - // Others take the paths below, the runs kept with the new pages. A buffer whose - // GPU writes are dropped is never bound in a chunk, but its copy's runs are asked - // for the RAM's log ([`routes_runs`]). - let routed = match &runs { - Some(resolver) if routes_runs(drops_writes) => { - let was_settled = settled.take().is_some(); - let routed = self.route_runs(call, importer, resolver, &window); - if was_settled { - settled = Some(cell.settled().ok_or_else(detached_textures)?); - } - routed? - } - _ => None, - }; - // SAFETY: the window's pages are the bytes of the run in the RAM (the resolver's - // contract, `HostMemory::with_runs`). - let in_chunk = (routed.as_ref().filter(|_| !moved && !drops_writes)).and_then( - |routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) }, - ); - // One page, one import (`host_aliases.rs`), as at a buffer's making: new pages a - // live import holds all of are bound inside it (a buffer's, not a heap's own), - // and pages one holds some of, or a heap's it holds all of, are a copy, the gate - // unasked, but where they and every live import that holds some of them are - // dma-bufs ([`Device::imports_beside`]), which import their own. - let within = match (&in_chunk, moved || drops_writes) { - (None, false) => (shared.aliases).within((window.start, window.size), unit), - _ => Within::Free, - }; - let inside = match &within { - // SAFETY: the window's pages are the caller's at the addresses the import's - // pages were imported from, which hold all of them. - Within::Inside(import) if heap.is_none() => unsafe { - self.bind_in_import(import, &window, length) - }, - _ => None, - }; - // And new pages a guest RAM's chunk import, made or in flight, holds some of at - // the RAM's own addresses, which no chunk binds (`host_ram.rs`), as at a buffer's - // making; others claimed through their import, made below. - let claim = (in_chunk.is_none() && inside.is_none() && !moved && !drops_writes) - .then(|| self.claim_ram_pages(window.start..window.start + window.size)); - let over_chunk = matches!(claim, Some(None)); - let held = inside.is_none() && !matches!(within, Within::Free); - let beside = held && self.imports_beside(&within, &host); - let over_import = held && !beside; - // Imported beside dma-bufs as dma-bufs alone, as at a buffer's making; so are - // pages a guest RAM routes that no chunk binds them in, where its chunks may be - // imported beside them (`Routed::own_dma_bufs`). - let ram_beside = in_chunk.is_none() - && inside.is_none() - && (routed.as_ref()).is_some_and(|routed| routed.own_dma_bufs(self)); - let dma_bufs_alone = beside || (ram_beside && host.source.is_some()); - let host = HostWindow { - by_pointer: host.by_pointer && !dma_bufs_alone, - ..host - }; - let in_chunk = in_chunk.or(inside); - let chunk_bound = in_chunk.is_some(); - let kept_runs = routed.as_ref().map(Routed::kept); - // Whether an import alive now holds every page of them: counted once the import - // is made (`WorkCounts::host_rebind_imports_covered`). - let start = pointer.as_ptr() as u64; - let covered = (shared.aliases).covered(start, start.saturating_add(length), unit); - // New pages whose pointer the device would import (a buffer's or a heap's, not a - // buffer's whose GPU writes are dropped) may be a copy of them instead - // (`copied.rs`): where the caller's gate refuses the import, asked here with the - // pages it would map, holding no lock of the runtime's, before their write - // permission is asked (a copy pins no page, and drops the GPU's writes to pages the - // process cannot write); or where the import it admitted fails, of the pointer or - // of the caller's dma-bufs. Bytes moved in their page are a copy, the gate unasked. - let gate = gate.filter(|_| { - copyable - && !read_only_copy - && host.by_pointer - && !moved - && !chunk_bound - && !over_import - && !over_chunk - }); - let refused_by_host = match gate { - Some(gate) => { - // Asked with no lock of the runtime's held: the textures over detached - // bytes are let go of meanwhile, and settled again after it. - let was_settled = settled.take().is_some(); - let request = ImportRequest { - start: NonNull::new(window.start as *mut u8).unwrap_or(pointer), - length: window.size, - }; - let refused = !gate(request); - if was_settled { - settled = Some(cell.settled().ok_or_else(detached_textures)?); - } - refused - } - None => false, - }; - if refused_by_host { - shared.counts.host_import_refused_by_host(); - } - // Only pages imported here are pinned, and so have their writability asked; pages - // the process cannot write are a copy whose GPU writes are dropped - // ([`unwritable_pages`]). - let imports = !chunk_bound - && !refused_by_host - && !moved - && !read_only_copy - && !over_import - && !over_chunk; - let unwritable = imports && unwritable_pages(&host, writable, &shared.counts)?; - let imports = imports && !unwritable; - // The heap's images bound to its bytes, and the images in place over the bytes, - // are made again over the copy (`Device::rebound_heap_images`, - // `Device::rebound_in_place_images`): its memory holds whole pages from a multiple - // of the import's unit. - let images = (heap.is_some() || !in_place.is_empty()).then_some(unit); - let own_pages = !in_place.is_empty() && self.fresh_pages_take_images(&in_place); - let copy = |failed: Option<&FailedImport>| { - let window = ©_window; - // SAFETY: the caller's contract. - unsafe { - self.copied_pages( - pointer, - length, - window, - (images, own_pages), - failed.map(|failed| &failed.error), - read_only_copy, - ) - } - }; - let imported = match (in_chunk, imports) { - (Some(bound), _) => Ok(Ok(bound)), - (None, false) => Err(None), - // Pages with no route of their own that lie in no chunk (above). - (None, true) => match no_route { - Some(refusal) => return Err(refusal), - // SAFETY: the window lies in the pages of the caller's bytes, which stay - // mapped (`HostMemory::new`, `HostMemory::with_dma_buf`). - None => match unsafe { - self.import_by_pointer(importer, pointer, length, host, class) - } { - Ok(imported) => Ok(imported), - Err(error) if copyable && copies_after(&error) => { - Err(Some(FailedImport { - error, - sourced: false, - })) - } - Err(error) => return Err(error), - }, - }, - }; - // The heap's images bound to its bytes, and the images in place over them, made - // over dma-bufs of their own pages where the new pages lie in imports of - // dma-bufs, each of which their source makes: with no lock held. - let images_again = |placement: &Placement| { - let mut remade = match heap { - Some(heap) => self.dma_buf_images_again(heap, placement, pointer)?, - None => Remade::default(), - }; - self.dma_buf_in_place_again(&in_place, placement, pointer, &mut remade)?; - Ok::<_, Error>(remade) - }; - let imported = match imported { - // Bound in a guest RAM's chunk imported as a dma-buf (`host_ram.rs`): the - // images made again from the RAM's source, with no lock of the runtime's - // held, the textures over detached bytes settled again after it. - Ok(Ok((host, placement))) if placement.over_dma_buf() => { - let was_settled = settled.take().is_some(); - let remade = match images_again(&placement) { - Ok(remade) => remade, - Err(error) => { - self.discard_import(host.raw, placement); - return Err(error); - } - }; - if was_settled { - match cell.settled() { - Some(again) => settled = Some(again), - None => { - drop(remade); - self.discard_import(host.raw, placement); - return Err(detached_textures()); - } - } - } - Ok((host, placement, remade)) - } - Ok(Ok((host, placement))) => Ok((host, placement, Remade::default())), - // The source is called with no lock of the runtime's held (`dma_buf.rs`): - // the textures over detached bytes are let go of meanwhile, and must be - // settled again after it. - #[cfg(unix)] - Ok(Err((source, refusal))) => { - let was_settled = settled.take().is_some(); - // Kept by no descriptor; dedicated as a no-copy buffer's own import is - // where the buffer is no heap's (`Device::buffer_over_host_parts`). - // SAFETY: as above, and the source's pieces hold the pages - // (`HostMemory::with_dma_buf`). - let from_source = unsafe { - let window = &window; - let kept = (false, heap.is_none()); - self.import_from_source( - call, importer, pointer, length, window, source, class, kept, - ) - } - .map_err(|failed| source_failure(failed, refusal)); - let made = match from_source { - Ok((host, placement, _)) => { - // Still with no lock held. - match images_again(&placement) { - Ok(remade) => Ok((host, placement, remade)), - Err(error) => { - self.discard_import(host.raw, placement); - return Err(error); - } - } - } - // An import of the caller's dma-bufs the gate admitted that then - // failed, or that served pages the runtime refused for the driver, or - // any failed import of dma-bufs alone (beside live ones, or a RAM's - // chunks): a copy, as where the pointer's fails. - Err(error) if copyable && (dma_bufs_alone || copies_after(&error)) => { - Err(Some(FailedImport { - error, - sourced: true, - })) - } - Err(error) => return Err(error), - }; - if was_settled { - match cell.settled() { - Some(again) => settled = Some(again), - None => { - if let Ok((host, placement, remade)) = made { - drop(remade); - self.discard_import(host.raw, placement); - } - return Err(detached_textures()); - } - } - } - made - } - // No source of dma-bufs on this system. - #[cfg(not(unix))] - Ok(Err((source, _))) => match source {}, - Err(failed) => Err(failed), - }; - let (host, placement, remade, copied) = match imported { - Ok((host, placement, remade)) => (host, placement, remade, None), - Err(failed) => { - let cause = match (moved, &failed) { - (true, _) => CopiedBecause::Moved, - (false, Some(_)) => CopiedBecause::Failed, - (false, None) if read_only_copy => CopiedBecause::ReadOnly, - (false, None) if unwritable => CopiedBecause::Unwritable, - (false, None) if over_import => CopiedBecause::OverImport, - (false, None) if over_chunk => CopiedBecause::OverRamChunk, - (false, None) => CopiedBecause::Refused, - }; - let (host, placement, copied) = copy(failed.as_ref())?; - let copied = (copied, cause, failed); - (host, placement, Remade::default(), Some(copied)) - } - }; - if !chunk_bound && copied.is_none() { - self.count_import_over_live(&window, unit, routed.as_ref(), beside); - } - // A copy lies at the offset it was laid out at: the old one where the bytes moved. - let offset = match copied { - Some(_) => copy_window.offset, - None => window.offset, - }; - let pages = self.host_pages( - host.raw, - placement, - offset, - host.base, - host.size - host.base, - ); - // An import of the new pages of its own, noted below. - let noted = copied.is_none() && !chunk_bound && !drops_writes; - match copied { - Some((copied, cause, failed)) => { - let drops = copied.drops_writes(); - pages.set_copied(copied); - shared.counts.copied_host_buffer_made(cause); - shared.counts.copied_rebind_pages_made(); - let why = (cause, drops, failed.as_ref()); - self.degrade_copied(call, pointer, length, why); - } - None if chunk_bound => {} - None => shared.counts.host_rebind_import_made(covered), - } - // The logs of the writes to them, and the guest RAM and runs the caller resolved - // them to, stay with them. - let log = pages_log( - (pointer, length), - dirty.as_ref(), - kept_runs.as_ref(), - window.offset, - ); - if let Some(log) = log { - pages.keep_log(log); - } - if let Some(runs) = kept_runs { - pages.keep_runs(runs); - } - (pages, remade, noted, claim) - } - }; - // The heap's images bound to its bytes, made again over the new pages. A refusal drops - // them and the new pages unreleased: the deallocator goes unrun. - let mut remade = remade; - let mut swaps = match heap { - Some(heap) => self.rebound_heap_images(heap, &pages, &mut remade)?, - None => Vec::new(), - }; - // The images in place over the bytes (`texture/in_place_image.rs`), made again over the - // new pages. - if !in_place.is_empty() { - swaps.extend(self.rebound_in_place_images(&in_place, &pages, &mut remade)?); - } - // The caller's log of the new pages' writes stays with them (`dirty_pages.rs`). - if let Some(dirty) = dirty { - pages.keep_dirty(dirty); - } - // The GPU's writes through it from now on are reported to the new pages' logs, and - // merged back from a copy of them. - pages.logged_as(key); - pages.copied_as(key); - // Refused where a hold refuses it, or where a call of an encoder the runtime may not - // encode again stays under way (`rebind::CallGate`): such a call reads the buffer wholly - // before the publish or wholly after it, never across it. - let (old, twins, again) = shared - .rebinds - .replace(key, cell, Arc::clone(&pages)) - .map_err(|refused| { - match refused { - crate::rebind::Unreplaced::Calls => { - shared.counts.rebind_refused_calls_in_flight(); - } - crate::rebind::Unreplaced::Unsubmitted => { - shared.counts.rebind_refused_unsubmitted(); - } - crate::rebind::Unreplaced::Held => {} - } - encoded() - })?; - // The publish is open from here to its close below, and as short as it can be: what lies - // over the bytes is made over the new pages, and nothing goes, nor any deallocator runs, - // until it closes (`rebind.rs`, **Other threads**). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - crate::rebind::pause::at(crate::rebind::pause::Point::Publishing, key); - // The buffer, or the heap's buffers, are reached unnamed again only once a command buffer - // uses it after the rebind, over the new pages. - shared.live_buffers.rebound(buffer, heap); - // Later buffers over the memory it was made over no longer join it. - shared.aliases.leave(key); - // The import its new pages are, its own or the live one it lies in, is noted over them - // as a heap's own import is, joining no key (`host_aliases.rs`, "Not joined"): a page it - // holds is not imported again while it lives (a later buffer over exactly the bytes lies - // in it, and a guest RAM's chunk holding some of them waits, `host_ram.rs`). Its claim - // of them goes once it is noted. - if noted { - (shared.aliases).hold(key, made_over, Kind::Import(class), pages.import()); - } - drop(claim); - // Its uses from now on order against the keys over the new bytes. - shared.aliases.place(key, (pointer.as_ptr() as u64, length)); - if let Some(release) = release.of(pointer, length) { - pages.release_to(release); - } - pages.keep_made_of(made_of); - // What lay in the old pages goes with them: the images swapped out, and the texel views. - // A detached buffer lay in none: what took its stand-in goes with the new pages. - let keeper = match &old { - Lying::In(old) => Arc::clone(old), - Lying::Detached(_) | Lying::Gone(_) => Arc::clone(&pages), - }; - let rebound = !swaps.is_empty() || !texels.is_empty(); - // The textures that presented stand-ins while the bytes were detached present their own - // images again (`texture/stand_in.rs`): those bound to the pages the ones made over the - // new pages, swapped in here; those in memory of their own the images they kept. What - // the stand-ins lent them waits for the command buffers that may read it through the - // heap sets (`heap_sets::retire`), not for the new pages. - let mut stood_in = Vec::new(); - for swap in swaps { - let objects = swap.apply(); - match objects.of_stand_in() { - true => stood_in.push(objects), - false => keeper.park(objects), - } - } - if let Some(settled) = settled { - let images = TextureImages::of(settled.images()); - stood_in.extend(images.present_own()); - debug_assert!( - !images.standing_in(), - "every image over the bytes presents its own again" - ); - drop(settled); - self.forget_stale(cell); - } - for views in &texels { - keeper.park(views.park()); - } - drop(keeper); - // The device's heap sets view the remade images and views of the textures over the - // bytes, and no other texture's elements change (`heap_sets::renew_over`). - if rebound || !stood_in.is_empty() { - super::heap_sets::renew_over(self, key); - } - // Everything over the bytes is made over the new pages: the publish closes, marking the - // command buffers committed while it was open whose encoders named the buffer too. - let mut again = again; - for buffer in shared.rebinds.published(key) { - if !again.iter().any(|had| Arc::ptr_eq(had, &buffer)) { - again.push(buffer); - } - } - if !stood_in.is_empty() { - super::heap_sets::retire(self, Box::new(stood_in)); - } - // Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`). - drop(twins); - // The old pages go now where no command buffer holds them, their deallocator with them; - // the deallocator a detach held back runs now, inside the call, as Metal runs it at the - // replace (`HostCell::release_held_back`). - drop(old); - cell.release_held_back(); - // The command buffers committed before the rebind and not yet first submitted whose - // encoders named the buffer are encoded again over the new pages, in this call, before - // their first submission (`command_buffer/reencode.rs`), as Metal resolves them then. - for buffer in &again { - buffer.reencode(); - } - drop(again); - Ok(()) - } - - /// The `VkBuffer` of a no-copy buffer of `length` bytes at `window.offset` in its window, - /// made for memory of `handle` (host allocations, or dma-bufs for a guest RAM's chunk imported - /// as one, `host_ram.rs`), whose bytes start [`buffer_base`] bytes into it. The memory - /// alignment is a buffer's whatever its size, so the buffer is made first for bytes at 0, - /// and again, at its own size, where its alignment misses the bytes. - /// - /// It holds the rest of the window from its bytes, which a copy out of the buffer reads past - /// its length as plain Metal does (`Buffer::copy_reach`); where the device's memory - /// requirements of that buffer run past the window, it holds its padded length ([`based_size`]) - /// instead. - pub(super) fn host_buffer( - &self, - window: &ImportWindow, - length: u64, - handle: vk::ExternalMemoryHandleTypeFlags, - ) -> Result { - let shared = self.shared(); - let raw_device = shared.vk(); - let make_sized = |base: u64, size: u64| { - let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(handle); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(shared.device_address)) - .push_next(&mut external), - ); - // SAFETY: the device is live and `info` and its chain valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared.counts.buffer_made(info.usage); - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - Ok::<_, Error>(HostBuffer { - raw, - base, - size, - requirements, - }) - }; - let make = |base: u64| { - let padded = based_size(base, length).ok_or_else(not_importable)?; - // The window from `base` bytes below the buffer's bytes to its end: where it binds - // (`binds_in`), the room it has. - let whole = window.size - window.offset + base; - if whole > padded { - let buffer = make_sized(base, whole)?; - if buffer.requirements.size <= whole { - return Ok(buffer); - } - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, buffer.raw) }; - } - make_sized(base, padded) - }; - let first = make(0)?; - let base = buffer_base(window.offset, first.requirements.alignment); - if base == 0 { - return Ok(first); - } - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, first.raw) }; - let buffer = make(base)?; - if buffer_base(window.offset, buffer.requirements.alignment) != base { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, buffer.raw) }; - return Err(not_importable()); - } - Ok(buffer) - } - - /// The pointer's import of `host`'s window ([`Device::import_pointer`]), where the device's - /// import alignment covers it, exactly as ever; and where the device refuses it ([`refused`]: - /// no window, a buffer that does not fit it, no memory type, a driver refusal, the runtime's - /// refusal of pages the kernel cannot pin) and the caller gave a dma-buf source the device can - /// use, the source, uncalled, with the refusal (`Err`), for the caller to call with no lock of - /// the runtime's held (`Device::import_from_source`, `dma_buf.rs`; [`source_failure`]). A - /// refusal without such a source is the pointer's. - /// - /// # Safety - /// - /// The window's pages are host memory of this process that stays mapped until the - /// placement is freed (`HostMemory::new`). - unsafe fn import_by_pointer( - &self, - importer: &Importer, - pointer: NonNull, - length: u64, - host: HostWindow, - class: MemoryClass, - ) -> Result, Error> { - let HostWindow { - window, - by_pointer, - source, - drops_writes, - pointerless: _, - } = host; - let refusal = match (by_pointer, importer.pointers()) { - // SAFETY: the caller's. - (true, Some(pointers)) => match unsafe { - self.import_pointer(pointers, pointer, length, &window, class, drops_writes) - } { - Ok(imported) => return Ok(Ok(imported)), - Err(error) if refused(&error) => error, - Err(error) => return Err(error), - }, - _ => not_importable(), - }; - match source { - #[cfg(unix)] - Some(source) => Ok(Err((source, refusal))), - // No source of dma-bufs on this system. - #[cfg(not(unix))] - Some(source) => match source {}, - None => Err(refusal), - } - } - - /// Count a no-copy buffer's or heap's own import of `window`'s pages, just made (in `unit`s), - /// where a live import held some of them all the same: another buffer's or heap's, made at - /// once and noted after this one looked, or a guest RAM's chunk's at the same addresses - /// (`ObjectChurn::imports_inside_live`), but where it was made of dma-bufs beside live imports - /// of dma-bufs, as `beside` says ([`Device::imports_beside`], - /// `ObjectChurn::dma_buf_imports_beside_live`). And, as evidence, where the object's pages - /// are a guest RAM's at other addresses (`routed`), some of which a live chunk import holds - /// (`ObjectChurn::imports_over_ram_chunk_pages`). - fn count_import_over_live( - &self, - window: &ImportWindow, - unit: u64, - routed: Option<&Routed>, - beside: bool, - ) { - let shared = self.shared(); - let at_ram = self.ram_chunks_hold_any(window.start..window.start + window.size); - let found = (shared.aliases).within((window.start, window.size), unit); - match (at_ram, matches!(found, Within::Free), beside) { - (true, _, _) | (false, false, false) => shared.counts.churn.import_inside_live(), - (false, false, true) => shared.counts.churn.dma_buf_import_beside_live(), - (false, true, _) => {} - } - if !at_ram && routed.is_some_and(|routed| routed.chunks_hold_any(window.size)) { - shared.counts.churn.import_over_ram_chunk_pages(); - } - } - - /// Whether pages that live imports hold some of (`within`: not all, or a heap's) take an - /// import of their own all the same: where every one of those imports is of dma-bufs, the - /// new pages come with a source of dma-bufs the device imports (`host`), and the device's - /// barriers order blits through two imports of the same pages (no - /// `RuntimeDriverDefect::AliasedImportBlitsUnordered`). They are then imported from that - /// source alone, never by their pointer. Elsewhere they are a copy (`CopiedBecause::OverImport`). - /// - /// `VK_EXT_external_memory_host`'s undefined double import is of a host pointer: "Some - /// platforms do not allow locking the same physical pages for device access multiple times" - /// (its issue 6), so no page an import of its pointer holds is imported again, and no page a - /// live import holds is imported by its pointer. Two imports of dma-bufs of the same pages - /// are no such lock: each is a `VkDeviceMemory` aliasing memory "by binding the memory to - /// resources in multiple Vulkan instances or external APIs using external memory handle - /// export and import mechanisms", whose aliases "interpret the contents of the memory in - /// consistent ways, and data written to one alias can be read by the other alias", where "use - /// of an overlapping range by two aliases must be separated by a memory dependency" (Vulkan - /// 1.4, 12.11 Memory Aliasing). `VK_EXT_external_memory_dma_buf` adds no rule against - /// importing two dma-bufs of the same pages. The tracker orders every use of a buffer's bytes - /// against those of every key over bytes they meet, whichever import each lies in - /// (`host_aliases.rs`, "Ordered by the bytes they lie over now"), with global memory - /// barriers, which hold every range; a guest RAM's run imported beside its chunk's - /// (`host_ram.rs`) is the same two dma-bufs of the same pages. - fn imports_beside(&self, within: &Within, host: &HostWindow) -> bool { - let unordered = RuntimeDriverDefect::AliasedImportBlitsUnordered; - host.source.is_some() - && within.held_by().iter().all(|import| import.over_dma_buf()) - && !self.properties().driver_defects.contains(&unordered) - } - - /// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`, whose pages all lie - /// inside those of `import`, a live import of the caller's pages (`host_aliases.rs`, "One - /// page, one import"), bound inside that import's memory where they lie, and its placement, - /// which holds the import: no import of its own, no pin and no gate. Once the buffer is bound - /// there, the import is kept imported for good (another buffer lies in its memory, - /// `host_residency.rs`); until then it is held as a blit's command holds it, so a releasable - /// import the buffer is not bound in stays releasable. - /// An import of dma-bufs takes it as an import of the pointer does where it is one - /// `VkDeviceMemory` dedicated to nothing (a no-copy buffer's own dma-buf, a piece of a shared - /// file's import, a guest RAM chunk's): the buffer is made for dma-bufs, the import's handle - /// type. `None` where the buffer cannot be bound there exactly (its alignment, its memory - /// types, an import of dma-bufs the driver took only dedicated to the buffer bound in it, - /// several bound to a sparse buffer, or a released import the device cannot import again): - /// the pages are then a copy, or, beside imports of dma-bufs alone, an import of their own - /// ([`Device::imports_beside`]). - /// - /// # Safety - /// - /// The window's pages are host memory of this process at the host addresses `import`'s pages - /// were imported from, which hold all of them. - pub(super) unsafe fn bind_in_import( - &self, - import: &Arc, - window: &ImportWindow, - length: u64, - ) -> Option<(HostBuffer, Placement)> { - let shared = self.shared(); - let raw_device = shared.vk(); - // Held, imported again where released, only while the checks and the bind below read it, - // which leave a releasable import releasable: only a bound buffer exposes it (below). - let (pages, _) = import.blit_pages().ok()?; - let within = pages.placement(); - // A dma-buf import the driver took only dedicated to the buffer bound in it binds no other - // (`VUID-vkBindBufferMemory-memory-01508`); one dedicated to nothing binds any buffer made - // for its handle type (`VUID-vkBindBufferMemory-memory-02985`), as a guest RAM chunk's - // does. Several bound to a sparse buffer have no memory to bind in (below). - #[cfg(unix)] - let dedicated = (within.dma_buf_pages()).is_some_and(|pages| pages.dedicated_to_buffer()); - #[cfg(not(unix))] - let dedicated = false; - let mapped = within.mapped.map(|mapped| mapped.as_ptr() as u64); - let (false, false, Some(mapped)) = - (dedicated, within.memory == vk::DeviceMemory::null(), mapped) - else { - return None; - }; - let handle = match lock(&shared.memory).bound_memory(within) { - BoundMemory::External(handle) => handle, - _ => return None, - }; - // Where the window starts in the import's placement. - let into = window.start.checked_sub(mapped)?; - if into.checked_add(window.size)? > within.size() { - return None; - } - let buffer = self.host_buffer(window, length, handle).ok()?; - let requirements = buffer.requirements; - let bound_at = binds_in(window, buffer.base, buffer.size, &requirements) - .ok() - .map(|at| within.offset + into + at) - .filter(|at| at.is_multiple_of(requirements.alignment.max(1))) - .filter(|_| requirements.memory_type_bits & (1 << within.type_index()) != 0); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] - let bound_at = bound_at.filter(|_| !BINDS_IN_IMPORTS_REFUSED.with(std::cell::Cell::get)); - let start = NonNull::new(window.start as *mut u8); - let (Some(bound_at), Some(start)) = (bound_at, start) else { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, buffer.raw) }; - return None; - }; - // SAFETY: the buffer is unbound and made for the import's handle type, and the import's - // memory holds its size and requirements from `bound_at` (`binds_in` against the window, - // which lies in the import's placement). - let bound = unsafe { - crate::creation::bind_buffer(raw_device, buffer.raw, within.memory, bound_at) - }; - if bound.is_err() { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, buffer.raw) }; - return None; - } - // Bound: the buffer reads the import's memory apart from blits while it lives, so the - // import stays imported for good from now on, still held here until it is. - import.expose(ReadApart::Inside); - let placement = Placement::in_import( - Arc::clone(import), - (within, handle), - within.offset + into, - window.size, - Mapped::of_caller(start), - ); - shared.counts.churn.buffer_bound_in_import(); - Some((buffer, placement)) - } - - /// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for host - /// allocations and bound in the import of the window's pages at their pointer - /// (`VK_EXT_external_memory_host`), or of a read-only view of them where `drops_writes` - /// (`read_only_view.rs`), `buffer.base` bytes below the window's offset, as memory of - /// `class`: the buffer and the placement. Released again on failure. - /// - /// # Safety - /// - /// The window's `size` bytes are host memory of this process that stays mapped until the - /// placement is freed. - pub(super) unsafe fn import_pointer( - &self, - pointers: &PointerImport, - pointer: NonNull, - length: u64, - window: &ImportWindow, - class: MemoryClass, - drops_writes: bool, - ) -> Result<(HostBuffer, Placement), Error> { - let host = vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT; - let buffer = self.host_buffer(window, length, host)?; - // The window starts `window.offset` bytes before the pointer, in the pages it touches. - let start = pointer.as_ptr().wrapping_sub(window.offset as usize); - let class = (class, drops_writes); - // SAFETY: the caller's, and the buffer is a new one of this device. - match unsafe { self.import_backing(pointers, &buffer, start, window, class) } { - Ok(placement) => Ok((buffer, placement)), - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(self.shared().vk(), buffer.raw) }; - Err(error) - } - } - } - - /// The pages of a released import of the window's pages at `pointer`, made again there as - /// `again` made it (`host_residency.rs`), on a device whose held pointer imports cost every - /// submission (`Device::pointer_imports_tax_submissions`): a new `VkBuffer` made and bound as - /// the first was, over an import of the pages mapped at the pointer, the kept import's under - /// `HostMemory::new`'s contract. Refused as the first import may be, typed as the import - /// answers (out of memory among them), or with the device lost. - pub(super) fn import_pointer_again( - &self, - pointer: NonNull, - again: &Again, - ) -> Result { - if self.is_lost() { - return Err(self.lost_refusal()); - } - let shared = self.shared(); - let pointers = (shared.host_import.as_ref().ok()) - .and_then(Importer::pointers) - .ok_or_else(|| internal("a pointer import made again on a device that imports none"))?; - let window = &again.window; - // SAFETY: the caller's pages stay mapped at the pointer while the buffer lives - // (`HostMemory::new`), and the buffer outlives the placement: the import holds it, and a - // command buffer that reads it holds the buffer too. An import of a read-only view is - // never made again (`Device::buffer_over_host_memory`). - let (buffer, placement) = unsafe { - self.import_pointer(pointers, pointer, again.length, window, again.class, false) - }?; - Ok(self.pages_of( - buffer.raw, - placement, - window.offset, - buffer.base, - buffer.size - buffer.base, - )) - } - - /// A copy of the `length` bytes at `pointer` for a rebind's new pages (`copied.rs`), laid out - /// as their import of `window` would be: a `VkBuffer` from the window's first page, the bytes - /// `window.offset` into it, in host-visible memory of the device's own, so the texel views - /// planned at the bytes' offset lie where they lay. Its memory's host address is the window's, - /// so the buffer's `contents` stays the pointer. Where images will be bound in it (`images`, - /// the import's unit: a heap's textures bound to its bytes, images in place over the buffer's), - /// its memory holds the window's whole pages from a multiple of that unit, as the import's did, - /// so each image's texels lie at the offset from an aligned start they had there. Where images - /// in place ride on it and the device's check passed for fresh pages and their accesses - /// (`own_pages`, `Device::fresh_pages_take_images`), the copy is fresh pages the runtime maps - /// and imports by their pointer where the device takes them ([`Device::fresh_page_buffer`]), so - /// each image is made for host allocations, as over the caller's pages; else memory the device - /// allocates, each image a linear image of its own. The GPU's writes to the copy are dropped - /// where `read_only` (Metal's private option bit 24). Refused as [`Device::copied_buffer`] - /// refuses its copy. - /// - /// # Safety - /// - /// The caller's bytes meet [`HostMemory::new`]'s contract for `length` bytes. - unsafe fn copied_pages( - &self, - pointer: NonNull, - length: u64, - window: &ImportWindow, - (images, own_pages): (Option, bool), - failed: Option<&Error>, - read_only: bool, - ) -> Result<(HostBuffer, Placement, crate::copied::Copied), Error> { - let shared = self.shared(); - let raw_device = shared.vk(); - let bytes = usize::try_from(length).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; - // Padded to 16 bytes past the bytes, as a buffer of the runtime's own. - let size = (window.offset.checked_add(length)) - .and_then(|end| end.checked_next_multiple_of(16)) - .ok_or(Error::OutOfMemory(MemoryKind::Device))?; - // The caller's pages are read before the copy's memory is made, so no mapping made for the - // copy is among them as they are read (`CopiedBuffers::read`). - // SAFETY: the caller's bytes (the caller's contract). - let first = match unsafe { crate::copied::CopiedBuffers::read(pointer, bytes, read_only) } { - Ok(first) => first, - Err(why) => { - return Err(match why { - NotCopied::Unreadable => failed - .filter(|failed| !refused(failed)) - .cloned() - .unwrap_or_else(not_importable), - NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), - }); - } - }; - let fresh = match own_pages { - true => self.fresh_page_buffer(window.size.max(size), MemoryClass::Shared)?, - false => None, - }; - let (raw, mut memory, requirements) = match fresh { - Some((raw, memory)) => { - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - (raw, memory, requirements) - } - None => self.copy_memory(size, window, images)?, - }; - let discard = |memory: &Placement| { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - lock(&shared.memory).free(raw_device, memory); - }; - let copy = memory - .mapped - .and_then(|mapped| NonNull::new(mapped.as_ptr().wrapping_add(window.offset as usize))); - let Some(copy) = copy else { - discard(&memory); - return Err(internal( - "a copied host buffer's memory is not host-visible", - )); - }; - // SAFETY: the copy is the placement's `length` bytes past the window's offset, mapped, - // which nothing uses yet and which stay mapped while the import holds them; the caller's - // bytes, which `first` read, stay mapped as long (the caller's contract). - let copied = unsafe { shared.copied.add(first, pointer, copy) }; - // The host address of the window's first byte, as an import's: `contents` is the - // pointer, `window.offset` past it. - let start = NonNull::new(pointer.as_ptr().wrapping_sub(window.offset as usize)); - memory.mapped = Some(super::memory::Mapped::of_caller(start.unwrap_or(pointer))); - let host = HostBuffer { - raw, - base: window.offset, - size: window.offset + length, - requirements, - }; - Ok((host, memory, copied)) - } - - /// A `VkBuffer` of `size` bytes bound in host-visible memory the device allocates, of a - /// copy laid out as `window`'s import would be ([`Device::copied_pages`]), with its - /// requirements: holding the window's whole pages from a multiple of `images`' unit where - /// images will be bound in it. - fn copy_memory( - &self, - size: u64, - window: &ImportWindow, - images: Option, - ) -> Result<(vk::Buffer, Placement, vk::MemoryRequirements), Error> { - let shared = self.shared(); - let raw_device = shared.vk(); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(false)), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared.counts.buffer_made(info.usage); - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - let placed = super::buffer::placed(requirements); - let placed = match images { - Some(unit) => vk::MemoryRequirements { - size: placed.size.max(window.size), - alignment: placed.alignment.max(unit), - ..placed - }, - None => placed, - }; - let allocated = crate::memory::allocate_addressed( - &shared.memory, - raw_device, - &placed, - MemoryClass::Shared, - &shared.counts, - ); - let memory = match allocated { - Ok(memory) => memory, - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - return Err(error); - } - }; - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - let bound = - unsafe { crate::creation::bind_buffer(raw_device, raw, memory.memory, memory.offset) }; - if let Err(error) = bound { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - lock(&shared.memory).free(raw_device, &memory); - return Err(vulkan(error)); - } - Ok((raw, memory, requirements)) - } - - /// Announce that `call` made the `length` bytes at `pointer` a copy of the caller's pages - /// (`Degradation::CopiedHostPages`), for `cause`, once per cause; one that `drops` the GPU's - /// writes, as the process cannot write the pages, says so; one made as their import `failed` - /// names the failure ([`FailedImport::cause`]). - fn degrade_copied( - &self, - call: &'static str, - pointer: NonNull, - length: u64, - (cause, drops, failed): (CopiedBecause, bool, Option<&FailedImport>), - ) { - self.degrade_copied_pages(Some(cause), || { - let failure; - let why: &str = match cause { - CopiedBecause::Refused => { - "the caller's import gate (HostMemory::with_import_gate) refused their \ - import" - } - CopiedBecause::DeviceRefused => { - "the device refused their pointer's import (VK_EXT_external_memory_host), as \ - RADV refuses shared memory, or imports no pointer (it enables no \ - VK_EXT_external_memory_host), and no dma-buf of them served it: no source of \ - them was given (HostMemory::with_dma_buf), or it failed, or the device \ - refused its dma-bufs" - } - CopiedBecause::Failed => match failed { - Some(failed) => { - failure = failed.cause(); - failure.as_str() - } - None => "their import failed", - }, - CopiedBecause::Moved => { - "they lie at another offset in their page than the buffer's old bytes, \ - where a texture over the buffer was planned, which no import lays them at" - } - CopiedBecause::ReadOnly => { - "Metal's private option bit 24 (0x1000000) makes them memory the GPU's \ - writes do not reach, and no import of them here keeps the GPU's writes out" - } - CopiedBecause::Unwritable => { - "the process maps some of them read-only, which Linux drivers pin no pointer \ - of, and whose dma-bufs would take the GPU's writes, which Metal drops" - } - CopiedBecause::OverImport => { - "a live import of another no-copy buffer's or heap's pages holds some of \ - their pages and not all (or more than a heap's own bytes), and a second \ - import of a page is undefined where either is of a host pointer \ - (VK_EXT_external_memory_host), and unordered by this device's barriers \ - where both are dma-bufs" - } - CopiedBecause::OverRamChunk => { - "an import of a guest RAM's chunk, made or in flight, holds some of their \ - pages at the RAM's own addresses, and no chunk binds them (they cross a \ - chunk's end, or no run resolver routed them), and \ - VK_EXT_external_memory_host leaves pages imported twice undefined" - } - }; - let dropped = match (drops, cause) { - (true, CopiedBecause::ReadOnly | CopiedBecause::Unwritable) => { - ", whose GPU writes are dropped, as Metal drops them, and never written to \ - the pages" - } - (true, _) => { - ", whose GPU writes are dropped, as Metal drops them, since the process maps \ - some of their pages read-only" - } - (false, _) => "", - }; - ( - format!("{call} over {length:#x} bytes at {pointer:p}"), - format!( - "{why}, so the GPU uses a copy of them in memory of the device's own{dropped}" - ), - ) - }); - } - - /// Announce `copied-host-pages` for `call` over the `length` bytes at `pointer`, a no-copy - /// buffer or rebind that lies in the live copy of the same bytes another buffer was made over - /// (`host_aliases.rs`), whose GPU writes are dropped where `drops`: it makes no copy of its - /// own, but the GPU uses that copy for it, as for the buffer it was made for. Once, a reason - /// of its own beside each copy's cause. - fn degrade_copied_shared( - &self, - call: &'static str, - pointer: NonNull, - length: u64, - drops: bool, - ) { - self.degrade_copied_pages(None, || { - let dropped = match drops { - true => { - ", whose GPU writes are dropped, as Metal drops them, since the process maps \ - some of their pages read-only" - } - false => "", - }; - ( - format!("{call} over {length:#x} bytes at {pointer:p}"), - format!( - "they are the bytes a live copied host buffer was made over, so the GPU uses \ - its copy of them in memory of the device's own{dropped}, as one memory with it" - ), - ) - }); - } - - /// A copied host buffer over the `length` bytes at `pointer` (`copied.rs`), of `modes`, at - /// `placement`, for `call`, a heap's own buffer where `of_heap` (laid where the heap's - /// textures could lie, its hazard identity a heap's), given back to `release`, its caller's - /// log `dirty` kept with it, made `why` says: where the caller's gate refused the pointer's - /// import, where the import the gate and the device admitted failed, or for memory whose GPU - /// writes Metal's private option bit 24 drops where the system maps no read-only view of the - /// pages (`read_only_view.rs`), whose GPU writes the copy drops. Announced - /// (`copied-host-pages`) and counted each way. Refused where its own memory cannot be had - /// (typed as the allocation answers), and where the process cannot read every page (memory - /// Metal makes no buffer over): with the import's failure where there was one, else as not - /// importable. - /// - /// # Safety - /// - /// The caller's bytes meet [`HostMemory::new`]'s contract for `length` bytes. - unsafe fn copied_buffer( - &self, - (call, pointer, length, modes, placement, of_heap): ( - &'static str, - NonNull, - u64, - Modes, - Place, - bool, - ), - release: Option, - dirty: Option>, - why: CopiedFor, - naming: Naming, - ) -> Result { - let read_only = matches!(why, CopiedFor::ReadOnly); - // A read twin is an import of the pages in place or nothing (`read_twin.rs`). - if let Naming::ReadTwin = naming { - return Err(crate::read_twin::uncopied()); - } - // A two-copy buffer's host copy is the pages alone instead (`managed_copy.rs`). - if let Naming::HostCopy = naming { - let drops = read_only || matches!(why, CopiedFor::Unwritable); - let alone = match &why { - CopiedFor::Refused | CopiedFor::DeviceRefused | CopiedFor::Failed(_) => { - crate::managed_copy::AloneBecause::Refused - } - CopiedFor::OverImport | CopiedFor::OverRamChunk => { - crate::managed_copy::AloneBecause::OverImports - } - CopiedFor::ReadOnly | CopiedFor::Unwritable => { - crate::managed_copy::AloneBecause::Unwritable - } - }; - self.shared().counts.managed_pages_alone(alone); - return Err(crate::managed_copy::uncopied(drops)); - } - let (cause, failed): (_, Option) = match why { - CopiedFor::Refused => (CopiedBecause::Refused, None), - CopiedFor::DeviceRefused => (CopiedBecause::DeviceRefused, None), - CopiedFor::Failed(failed) => (CopiedBecause::Failed, Some(failed)), - CopiedFor::ReadOnly => (CopiedBecause::ReadOnly, None), - CopiedFor::Unwritable => (CopiedBecause::Unwritable, None), - CopiedFor::OverImport => (CopiedBecause::OverImport, None), - CopiedFor::OverRamChunk => (CopiedBecause::OverRamChunk, None), - }; - let shared = self.shared(); - let raw_device = shared.vk(); - // The pages' refusal where they cannot be copied: the import's failure, or a refusal of - // them. - let unreadable = |failed: Option| { - failed - .map(|failed| failed.error) - .filter(|failed| !refused(failed)) - .unwrap_or_else(not_importable) - }; - let bytes = usize::try_from(length).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; - // Padded to 16 bytes, so a device fill clears every byte too, as a buffer of its own. - let size = length - .checked_next_multiple_of(16) - .ok_or_else(|| nil(call, Problem::BufferLength { length }))?; - // The caller's pages are read before the copy's memory is made, so no mapping made for the - // copy is among them as they are read (`CopiedBuffers::read`). - // SAFETY: the caller's bytes (the caller's contract). - let first = match unsafe { crate::copied::CopiedBuffers::read(pointer, bytes, read_only) } { - Ok(first) => first, - Err(why) => { - return Err(match why { - NotCopied::Unreadable => unreadable(failed), - NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), - }); - } - }; - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(size) - .usage(usage(false)), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - shared.counts.buffer_made(info.usage); - // A heap's own buffer lies where its textures could too, as an imported heap's. - let placed = match of_heap { - true => self.place_heap_buffer(raw, length, MemoryClass::Shared, placement), - false => self.place_buffer(raw, length, MemoryClass::Shared, placement), - }; - let (mut memory, (address, reserved)) = match placed { - Ok(placed) => placed, - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - return Err(error); - } - }; - // A refusal from here gives back what the placement took: the buffer, its memory and its - // range of the address space, as a refused import's call holds none of them. - let discard = |memory: &Placement| { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - lock(&shared.memory).free(raw_device, memory); - lock(&shared.addresses).free(reserved); - }; - let Some(copy) = memory - .mapped - .and_then(|mapped| NonNull::new(mapped.as_ptr())) - else { - discard(&memory); - return Err(internal( - "a copied host buffer's memory is not host-visible", - )); - }; - // SAFETY: the copy is the placement's `length` bytes, mapped, which nothing uses yet and - // which stay mapped while the import holds them; the caller's bytes, which `first` read, - // stay mapped as long (the caller's contract). - let copied = unsafe { shared.copied.add(first, pointer, copy) }; - // Its `contents` is the caller's pointer, as a no-copy buffer's is. - memory.mapped = Some(super::memory::Mapped::of_caller(pointer)); - let buffer = self.buffer_of(BufferParts { - raw, - memory, - offset: 0, - base: 0, - length, - allocation: length, - reach: length, - modes, - address, - reserved, - owner: Owner::Caller, - release, - of_heap, - drops_writes: read_only, - mirror: None, - again: None, - naming, - }); - let drops = copied.drops_writes(); - if let Some(pages) = buffer.host_pages() { - pages.set_copied(copied); - // The caller's log of the pages' writes stays with them (`dirty_pages.rs`). - if let Some(dirty) = dirty { - pages.keep_dirty(dirty); - } - } - shared.counts.copied_host_buffer_made(cause); - if of_heap { - shared.counts.copied_heap_made(); - } - self.degrade_copied(call, pointer, length, (cause, drops, failed.as_ref())); - Ok(buffer) - } - - /// Release the `VkBuffer` `raw` and its `placement`, an import made for a buffer or rebind - /// that is not made after all, or one made to ask the driver (`host_shared_pointers.rs`, - /// `Device::ram_takes_dma_bufs`): the `VkBuffer` first, once its sparse binding completed. - pub(super) fn discard_import(&self, raw: vk::Buffer, placement: Placement) { - let shared = self.shared(); - placement.settle(); - // SAFETY: the buffer is unused, and its binding completed. - unsafe { release::object(shared.vk(), raw) }; - lock(&shared.memory).free(shared.vk(), &placement); - } - - /// The Metal addresses of a no-copy buffer of `length` bytes `window.offset` bytes into - /// `window`, placed as `address` asks: the window's pages where the program names no address, - /// so that the buffer's address keeps its pointer's offset in its page. - pub(super) fn place_window( - &self, - address: Place, - window: &ImportWindow, - length: u64, - ) -> Result<(GpuAddress, Held), Error> { - let mut addresses = self.address_space_for(address); - match address { - Place::At(AddressPlacement::Any | AddressPlacement::Outside) => addresses - .place(address, window.size) - .map(|(range, held)| (GpuAddress(range.0 + window.offset), held)), - _ => addresses.place(address, length), - } - } - - /// Where a buffer of `length` bytes holding `contents`, at `placement`, goes to share - /// `other`'s range (`BufferDescriptor::range_of`), for `call`: refused as - /// [`Device::new_buffer_with_descriptor`] says, and where it is to go `in_pool`. - fn shared_place( - &self, - call: &'static str, - other: &Buffer, - contents: &BufferContents<'_>, - length: u64, - placement: AddressPlacement, - in_pool: bool, - ) -> Result { - if !other.generation().same(self) { - return Err(other.generation().foreign(call, self)); - } - let unshared = || { - let address = other.exposed_address(ReadApart::SharedRange); - let held = AddressRange::of(address.0, other.length()); - Error::PlacementConflict(PlacementConflict::Unshared { held }) - }; - let (address, held, first) = other.sharable_range().ok_or_else(unshared)?; - let over = match contents { - BufferContents::NoCopy { memory, .. } => memory.pointer() == first, - BufferContents::Zero | BufferContents::Copy(_) | BufferContents::CopyHost(_) => false, - }; - let placed = matches!(placement, AddressPlacement::Any) - || placement == AddressPlacement::At(address); - if !over || length > other.length() || !placed || in_pool { - return Err(unshared()); - } - Ok(Place::Shared { address, held }) - } - - /// Import the window's pages at `start` and bind `buffer` in them, `buffer.base` bytes below - /// the window's offset, as memory of `class`: the placement. Where `drops_writes`, a - /// read-only view of the pages is imported in their place (`read_only_view.rs`); a view the - /// system cannot map is refused as host memory run out. Released again on failure but the - /// buffer. - /// - /// # Safety - /// - /// The window's `size` bytes at `start` are host memory of this process that stays mapped - /// until the placement is freed; `buffer` is an unbound buffer of this device made for host - /// allocations. - unsafe fn import_backing( - &self, - pointers: &PointerImport, - buffer: &HostBuffer, - start: *mut u8, - window: &ImportWindow, - (class, drops_writes): (MemoryClass, bool), - ) -> Result { - let raw_device = self.shared().vk(); - let requirements = &buffer.requirements; - let at = binds_in(window, buffer.base, buffer.size, requirements) - .map_err(|_| not_importable())?; - let start = NonNull::new(start).ok_or_else(not_importable)?; - let view = match drops_writes { - // SAFETY: the window is whole host pages of the caller's mapped memory (the caller's - // contract; `import_window` rounds it out to the host page). - true => Some( - unsafe { ReadOnlyView::of(start, window.size) } - .ok_or(Error::OutOfMemory(MemoryKind::Host))?, - ), - false => None, - }; - let imported = view.as_ref().map_or(start, ReadOnlyView::pointer); - // Pages the kernel cannot pin, never handed to a driver whose failed import of them - // breaks its later allocations. - self.refuse_unpinnable(imported, window.size)?; - // SAFETY: the imported pages are host memory aligned to the import alignment (the - // window's). - let types = - unsafe { pointers.memory_types(raw_device, imported) }.map_err(import_refused)?; - let allowed = types & requirements.memory_type_bits; - // An allocation past the device's, refused before the driver sees it. - let largest = self - .compile_device() - .allocation() - .max_memory_allocation_size; - if window.size > largest { - return Err(Error::OutOfMemory(MemoryKind::Device)); - } - // SAFETY: the caller's contract keeps the window mapped until the placement is freed, - // and the buffer is unbound; the view views the window whole. - unsafe { self.import_now(buffer.raw, (start, view), window.size, allowed, class, at) } - } - - /// Import `size` bytes of host pages at `start` as memory of `class` among the types - /// `allowed`, through `view` where given (`read_only_view.rs`), and bind `raw` in them `at` - /// bytes in: the placement. Released again on failure. - /// - /// # Safety - /// - /// The `size` bytes at `start` are host memory of this process that stays mapped until the - /// placement is freed, and `view`, where given, views them whole; `raw` is an unbound buffer - /// of this device made for host allocations, whose requirements the pages meet from `at`. - unsafe fn import_now( - &self, - raw: vk::Buffer, - pages: (NonNull, Option), - size: u64, - allowed: u32, - class: MemoryClass, - at: u64, - ) -> Result { - let shared = self.shared(); - let raw_device = shared.vk(); - #[cfg(test)] - { - use std::sync::atomic::Ordering; - let failing = &shared.failing_host_imports; - if (failing.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1))) - .is_ok() - { - return Err(Error::OutOfMemory(MemoryKind::Device)); - } - } - // SAFETY: the caller's contract keeps the pages mapped until the placement is freed. - let placement = unsafe { - super::memory::import_host(&shared.memory, raw_device, pages, size, allowed, class) - } - .map_err(|failure| match failure { - ImportFailure::NoMemoryType => not_importable(), - ImportFailure::Vulkan(error) => import_refused(error), - })?; - // SAFETY: the placement is the pages' memory, the buffer's size and requirements of it - // available from `at` (the caller's), and the buffer is unbound. - let bound = unsafe { - crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset + at) - }; - match bound { - Ok(()) => { - shared.counts.host_pointer_import_made(size); - Ok(placement) - } - Err(error) => { - lock(&shared.memory).free(raw_device, &placement); - Err(vulkan(error)) - } - } - } -} - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] -thread_local! { - /// Whether this thread's binds inside live imports are refused ([`refuse_binds_in_imports`]). - static BINDS_IN_IMPORTS_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// A test hook, compiled into the crate's device tests on Linux alone: while `refused`, refuse -/// every bind of a no-copy buffer inside a live import that this thread asks -/// (`Device::bind_in_import`), as a requirement the import's memory misses refuses it, so a test -/// sees what a refused bind leaves of the import on any driver (`tests/pointer_residency.rs`). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] -pub(crate) fn refuse_binds_in_imports(refused: bool) { - BINDS_IN_IMPORTS_REFUSED.with(|cell| cell.set(refused)); -} - -/// `buffer`, the logs of the writes to its pages kept with them (`dirty_pages::PagesLog`), where -/// there are any, which hear of the GPU's writes through it where it lies in them in place; where -/// its pages are a copy, its key named to the copy, whose merges back compare it where a batch -/// wrote that key (`copied.rs`); and the guest RAM and runs its caller resolved its pages to -/// (`host_ram.rs`) kept with them. Its pages are looked at once (their lock, -/// `WorkCounts::no_copy_lies_read`). -fn kept( - buffer: Buffer, - log: Option>, - runs: Option<(Arc, Box<[std::ops::Range]>)>, - made_of: HostParts, -) -> Buffer { - if let Some(pages) = buffer.host_pages() { - keep_in(&pages, &buffer, log, runs, made_of); - } - buffer -} - -/// Give `pages`, the pages `buffer` was just made in, `log`, `runs` and what it was `made_of` to -/// keep ([`HostPages::made_of`]), and name the buffer to their copy where they are one -/// ([`kept`]). -fn keep_in( - pages: &HostPages, - buffer: &Buffer, - log: Option>, - runs: Option<(Arc, Box<[std::ops::Range]>)>, - made_of: HostParts, -) { - let key = buffer.identity().key; - if let Some(log) = log { - pages.keep_log(log); - pages.logged_as(key); - } - pages.copied_as(key); - if let Some(runs) = runs { - pages.keep_runs(runs); - } - pages.keep_made_of(made_of); -} - -/// The logs of the writes to the `length` bytes at `pointer` (`dirty_pages::PagesLog`): their -/// memory's own `dirty`, and the guest RAM's of the `runs` of it their import window is, the -/// bytes at its `offset`; `None` where neither has one. -fn pages_log( - (pointer, length): (NonNull, u64), - dirty: Option<&Arc>, - runs: Option<&(Arc, Box<[std::ops::Range]>)>, - offset: u64, -) -> Option> { - let ram = runs.and_then(|(ram, runs)| Some((ram.dirty()?, &runs[..], offset))); - PagesLog::new((pointer.as_ptr() as u64, length), dirty, ram) -} - -/// The host pages a no-copy buffer (or a heap's own buffer) of some length imports -/// ([`host_window`]). -struct HostWindow { - /// The GPU's writes to them are dropped: they are imported through a read-only view of them - /// (`read_only_view.rs`), by their pointer alone, or where the system maps no such view, they - /// are copied (`copied.rs`). - drops_writes: bool, - /// The pages: the range rounded out to the host page. - window: ImportWindow, - /// Whether the device's import alignment covers them, so that their pointer is imported - /// first (`VK_EXT_external_memory_host`). - by_pointer: bool, - /// The caller's dma-buf source, where it gave one and the device imports dma-bufs. - source: Option, - /// The device imports no pointer (it enables no `VK_EXT_external_memory_host`), and the pages - /// are not the source's dma-bufs alone (`HostMemory::dma_buf_only`): where no dma-buf of them - /// serves, a no-copy buffer or heap over them is a copy (`copied.rs`), as where a device - /// refuses their pointer. - pointerless: bool, -} - -/// Whether a no-copy buffer, heap or rebind whose pages the caller resolves to runs of a guest RAM -/// (`HostMemory::with_runs`) has them asked, where its GPU writes are dropped where `drops_writes`: -/// every one but memory whose GPU writes Metal's private option bit 24 drops on macOS, which -/// imports a read-only view of its pages (`read_only_view.rs`). Elsewhere such memory is a copy -/// of its pages (`copied.rs`), never bound in the RAM's chunk, whose runs give it the RAM's log of -/// the writes to them (`dirty_pages::PagesLog`), so its commits copy in only the pages the log -/// reports written, as a writable copy's do, where they compared every byte. -fn routes_runs(drops_writes: bool) -> bool { - !drops_writes || !crate::read_only_view::VIEWS_DROP_WRITES -} - -/// Whether the process cannot write some of `host`'s pages, asked by a call that imports them -/// itself (not a buffer that lies in a live import of them): such pages are a copy whose GPU -/// writes are dropped (`copied.rs`), on every device, never imported and their dma-buf source -/// never called. Linux drivers pin a pointer's imported pages for writing (RADV refused such a -/// page, NVIDIA failed it as out of device memory, ANV imported it and lost the device at the -/// GPU's first read), and a dma-buf of them would take the GPU's writes, where Metal's leave the -/// CPU's view of them as it was (an M3 Max under macOS 27.0.1, private and shared memory alike). -/// Pages whose write permission the caller vouched for (`vouched`, `HostMemory::assume_writable`) -/// are not asked about. Refused where the process's mappings cannot be asked -/// ([`refuse_unwritable`]); on Linux and Windows the system is asked, on macOS nothing. -fn unwritable_pages(host: &HostWindow, vouched: bool, counts: &Counters) -> Result { - if vouched { - return Ok(false); - } - match refuse_unwritable(&host.window, counts) { - Ok(()) => Ok(false), - Err(error) if refused(&error) => Ok(true), - Err(error) => Err(error), - } -} - -/// The memory class of a no-copy buffer or heap over the caller's bytes of `modes`' storage -/// mode, for `call`: `Shared` (whatever the CPU cache mode) or `Managed`; refused (`Invalid`, -/// `Problem::StorageMode`) for `Private` and `Memoryless`, as Metal stops them. -pub(super) fn host_class(call: &'static str, modes: Modes) -> Result { - match modes.storage { - StorageMode::Shared => Ok(MemoryClass::Shared), - StorageMode::Managed => Ok(MemoryClass::Managed), - StorageMode::Private | StorageMode::Memoryless => Err(invalid(call, Problem::StorageMode)), - } -} - -/// `options` of a no-copy buffer or heap over the caller's bytes without -/// [`ResourceOptions::PRIVATE_BIT`] and [`ResourceOptions::BIT_20`], and whether its memory drops the GPU's writes, as Metal's does -/// where the options set the bit: on macOS the runtime imports the pages through a read-only view -/// of them (`read_only_view.rs`); elsewhere it makes the object over a copy of them whose GPU -/// writes it never writes back (`copied.rs`, announced as `copied-host-pages`). -pub(super) fn no_copy_options(options: ResourceOptions) -> (ResourceOptions, bool) { - options.without_bit_20().without_private_bit() -} - -/// Why a no-copy buffer or heap is made over a copy of the caller's pages (`Device::copied_buffer`). -enum CopiedFor { - /// The caller's gate refused their import (`HostMemory::with_import_gate`). - Refused, - /// The device refused their pointer's import, or imports no pointer (it enables no - /// `VK_EXT_external_memory_host`), and no dma-buf of them served it: the caller gave no - /// source of them (`HostMemory::with_dma_buf`), or its source failed, or the device refused - /// its dma-bufs. - DeviceRefused, - /// The import the device and the gate admitted failed, as this says. - Failed(FailedImport), - /// Metal's private option bit 24 drops the GPU's writes to the memory, and the system maps - /// no read-only view of the pages (`read_only_view.rs`): the copy drops them. - ReadOnly, - /// The process cannot write every page ([`unwritable_pages`]): the copy drops the GPU's - /// writes, as Metal drops them. - Unwritable, - /// A live import of another buffer's or heap's pages holds some of them and not all, or more - /// than a heap's own bytes (`host_aliases.rs`, "One page, one import"), and no import of - /// dma-bufs of them beside it is made ([`Device::imports_beside`]): no page is imported twice. - OverImport, - /// An import of a guest RAM's chunk, made or in flight, holds some of them, at the RAM's own - /// addresses, and no chunk binds the buffer: its bytes cross a chunk's end (the chunks on both - /// sides imported), - /// or no run resolver routed them (`host_ram.rs`). No page is imported twice. - OverRamChunk, -} - -/// An import of a no-copy object's pages that the device and the gate admitted and that failed -/// ([`copies_after`]), leaving the object a copy of them (`CopiedFor::Failed`). -pub(super) struct FailedImport { - /// The failure: out of memory, another Vulkan error, or the runtime's refusal of pages the - /// kernel cannot pin ([`unpinnable`]). - pub(super) error: Error, - /// Whether the caller's dma-bufs of the pages were imported after their pointer was refused - /// (`HostMemory::with_dma_buf`, [`source_failure`]). - pub(super) sourced: bool, -} - -impl FailedImport { - /// The cause the copy's announcement names (`copied-host-pages`): the pages the runtime kept - /// from the driver and why no dma-buf of them served, or the import that failed and its error. - pub(super) fn cause(&self) -> String { - let FailedImport { error, sourced } = self; - match (*error == unpinnable(), *sourced) { - (true, true) => format!( - "{UNPINNABLE}, and no dma-buf of them served: the caller's source \ - (HostMemory::with_dma_buf) made none of them, or the device refused its dma-bufs" - ), - (true, false) => format!( - "{UNPINNABLE}, and no source of dma-bufs of them was asked: the caller gave none \ - (HostMemory::with_dma_buf), or the device imports no dma-buf" - ), - (false, true) => format!( - "the device refused their pointer's import, or the runtime kept their pointer \ - from the driver, and the import of the caller's dma-bufs of them \ - (HostMemory::with_dma_buf) failed: {error}" - ), - (false, false) => format!("their pointer's import failed: {error}"), - } - } -} - -/// Why the runtime keeps pages from the driver ([`unpinnable`]), in a copy's announcement. -const UNPINNABLE: &str = "the kernel cannot pin some of them (a mapping over them is a dma-buf's, \ - VM_PFNMAP, or could not be asked about), and the driver's later allocations fail once it \ - fails to import such a pointer (RuntimeDriverDefect::UnpinnablePagesBreakHostMemory), so the \ - runtime kept their pointer from it"; - -/// Whether `error`, an import's failure that is not the device's refusal of the pages, leaves the -/// no-copy buffer a copy of them (`copied.rs`): out of memory, another Vulkan error, or the -/// runtime's refusal of pages the kernel cannot pin, made for a driver whose failed import of them -/// breaks its later allocations ([`unpinnable`]), which no dma-buf of them served. A lost device -/// does not, nor does misuse. -fn copies_after(error: &Error) -> bool { - matches!(error, Error::OutOfMemory(_) | Error::Vulkan(_)) || *error == unpinnable() -} - -/// What an import of the caller's dma-bufs (`dma_buf.rs`) that `failed` answers, made where the -/// pages' pointer was refused with `refusal` ([`Device::import_by_pointer`]): the runtime's refusal -/// of pages the kernel cannot pin ([`unpinnable`]) where the dma-bufs were refused too (no source -/// answered, or the device refused them), so the object is a copy of the pages as where no source -/// is given ([`copies_after`]); else `failed`, misuse and a lost device among it. -#[cfg(unix)] -fn source_failure(failed: Error, refusal: Error) -> Error { - match refused(&failed) && refusal == unpinnable() { - true => refusal, - false => failed, - } -} - -/// The host pages a no-copy object of `length` bytes at `pointer` imports on the device of -/// `importer`, for `call`: the pages the range touches ([`import_window`]), imported by their -/// pointer where the device imports pointers and its import alignment covers them (but where -/// `dma_buf_only`, `HostMemory::dma_buf_only`), else only as a dma-buf where the caller gave a -/// source the device can use. A source the device cannot use is dropped uncalled, as is any where -/// `drops_writes` (imported through a read-only view, `read_only_view.rs`, or a copy where the -/// system maps none). Refused: memory past the address space's end (`Nil`, as Metal makes no -/// buffer over it). Pages with no route of their own are the caller's to refuse -/// ([`HostWindow::no_route`]). -fn host_window( - call: &'static str, - importer: &Importer, - pointer: NonNull, - length: u64, - (source, dma_buf_only): (Option, bool), - drops_writes: bool, -) -> Result { - let source = source.filter(|_| importer.imports_dma_bufs() && !drops_writes); - let at = pointer.as_ptr() as u64; - let window = import_window(at, length, importer.page, 1) - .map_err(|_| nil(call, Problem::BufferLength { length }))?; - let by_pointer = !dma_buf_only - && (importer.pointers()).is_some_and(|pointers| { - import_window(at, length, importer.page, pointers.alignment).is_ok() - }); - let pointerless = !dma_buf_only && importer.pointers().is_none(); - Ok(HostWindow { - drops_writes, - window, - by_pointer, - source, - pointerless, - }) -} - -impl HostWindow { - /// The refusal of pages with no route of their own: not imported by their pointer, with no - /// usable source, and no copy (memory whose GPU writes are dropped is one where the system - /// maps no read-only view of the pages, `copied.rs`). On a device without - /// `VK_EXT_external_memory_host`, `Unsupported` naming it; elsewhere a range the import - /// alignment cannot cover, or memory imported only as dma-bufs (`Unsupported`, `HostMemory`). - /// `None` where they have a route. Such pages may still lie in a guest RAM's chunk - /// (`HostMemory::with_runs`), which takes no import of their own. A rebind to them takes this - /// refusal; a no-copy buffer or heap over them is a copy instead where the device imports no - /// pointer ([`HostWindow::pointerless`]). - fn no_route(&self, importer: &Importer) -> Option { - let copied = self.drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES; - (!self.by_pointer && self.source.is_none() && !copied).then(|| { - match importer.pointer_import() { - Ok(_) => not_importable(), - Err(refusal) => refusal, - } - }) - } -} - -/// A no-copy buffer's unbound `VkBuffer` (`Device::host_buffer`): `size` bytes, its bytes from -/// `base`, with its memory requirements. -pub(super) struct HostBuffer { - pub(super) raw: vk::Buffer, - pub(super) base: u64, - pub(super) size: u64, - pub(super) requirements: vk::MemoryRequirements, -} diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs deleted file mode 100644 index 5c417c55a..000000000 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ /dev/null @@ -1,3175 +0,0 @@ -//! Textures over buffers: `Buffer::new_texture`, its SPI form `Buffer::new_linear_texture`, and the -//! texture buffers `Device::new_texture` makes. A 2D texture or array over a buffer is a shadow -//! image (`shadow.rs`) over these texels. -//! -//! - **Metal's rules** decide which textures a buffer backs and where they lie in it -//! (`linear_plan.rs`); what Metal stops is refused `Invalid`, and an IOSurface plane past its -//! surface of a shape that keeps no tail (below), which Metal makes, `NotImplemented`. -//! - **Tails.** A texture's texels lie in place up to the bytes its buffer's memory holds for -//! them ([`Texels::kept`], `Buffer::texel_reach`): Metal's allocation of a buffer of the -//! runtime's memory, which for one of at least 16 KiB the program makes in the Metal address -//! space is its length rounded up to 16 KiB, as long a `VkBuffer` and placement, zero when made -//! (`Device::placed_new_buffer`); a heap's buffer's heap to its end, Metal's texels there being -//! the heap's bytes; a no-copy buffer's length, past which its pages are the caller's. A 2D -//! texture, an array or a texture buffer whose texels run past those bytes, which plain Metal -//! makes up to the buffer's allocation (`linear_plan.rs`'s **Length**), and a colour texture of -//! an IOSurface plane whose texels run past the buffer standing for its surface -//! (`linear_plan.rs`'s **Beyond the plane's rows**: announced `SurfaceTexelsTail`), keep the -//! texels' bytes past them in a tail of their own ([`Texels::past`]): a runtime `Shared` buffer -//! of its bytes from the first to the last (a texture buffer's from its functions' first, its -//! offset rounded down to 16), zero when made. Its texels kept in place are the buffer's bytes, -//! as every texture's over a buffer are. A 2D texture or array is a shadow image whose copies -//! go through the tail, as a staging buffer: in, the buffer's bytes kept in place into the tail -//! and the tail into the image; back, the image into the tail and the tail's rows kept in place -//! into the buffer. A texture buffer's bindings view the tail, as a staged texture buffer's view -//! its staging buffer, with the same copies in and back but the image. A merge back takes its -//! current bytes from both and gives them back to both (`shadow_merge.rs`). The CPU's -//! `replace_region` and `get_bytes`, and a blit's rows, take each row's bytes kept in place -//! from the buffer and the rest from the tail; a copy between such texels and an image goes -//! through a scratch buffer of the encoder, as those rows (`blit_texture.rs`). The tail's uses -//! are the buffer's bytes past those kept in place, by the same key, so the tracker orders them -//! as the texels' own. Metal's texels there are memory past the buffer's own: a no-copy -//! buffer's caller pages, or the allocation Metal gives a buffer under 16 KiB (docs/API.md's -//! accepted differences); the tail answers every path alike and reaches no allocation but its -//! own. -//! - **Texture buffers** are the buffer's bytes ([`Texels`]), viewed as a texel buffer where a -//! function binds them: in the format the binding plan names, over the range it gives, made at -//! the first bind that needs it and kept with the texture. Their uses are uses of the buffer's -//! bytes, so the tracker orders them against every other use of the buffer. A -//! `Device::new_texture` texture buffer is a texture buffer over a new buffer of the -//! descriptor's options, as long as its row of texels, outside the Metal address space -//! (`address.rs`): Metal shows no address of a texture's texels, which a function reaches -//! through the texture's binding or its resource ID, so no program buffer's address depends on -//! it. -//! - **CPU access** (`replace_region`, `get_bytes`) reads and writes the buffer's bytes where -//! the texture lies in them, as the buffer's own `contents` would, for every texture over a -//! buffer. -//! - **A texel buffer view in a format of one kind** (a format the device takes for one kind of -//! texel buffer and not the other, as NVIDIA takes `R64_UINT` for storage texel buffers only): -//! the runtime's buffers are made for both kinds, and Vulkan views a buffer only in a format -//! that serves every usage the view has, so such a view names the one usage it needs -//! (`VkBufferUsageFlags2CreateInfoKHR`), which `maintenance5` allows ([`view_usage`]). -//! - **Not yet** (`NotImplemented`): that view on a device that did not enable `maintenance5`; -//! views, blits and mipmaps of textures over buffers. - -use super::address::{AddressPlacement, ObjectsToken}; -use super::apple_only::AppleOnly; -use super::buffer::{Buffer, ReadApart}; -use super::chroma_pairs; -use super::copy_plan::{ - block_extent, surface_depth_unit, CopyProblem, CopyUnit, HostLayout, ImageRegion, -}; -use super::degradation::Degradation; -use super::device::lock; -use super::dma_buf::ModifierMemory; -use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; -use super::exit_guard; -use super::host_backing::HostBacking; -use super::in_place::{Padding, PagesClass, RowEnds}; -use super::key_hash::KeyMap; -use super::linear_plan::{ - apart_from_plane, is_linear, plan_buffer_texture, plane_rows_share_bytes, Allocation, - BufferFacts, BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall, - BufferTextureProblem, Placed, LINEAR_ALIGNMENT, METAL_PAGE, -}; -use super::resource::{Identity, ResourceKey}; -use super::resource_ids::IdPlacement; -use super::rotated::{self, Frame, RotatedCopies}; -use super::shadow::{ - Backing, ShadowBuffer, ShadowCopies, ShadowSource, ShadowStaging, ShadowTarget, -}; -use super::shadow_copy_back::WordView; -use super::shadow_merge::ScratchSpares; -use super::shadow_merge::UnormView; -use super::shadow_standing::StandingAcross; -use super::texture::carry::Remake; -use super::texture::surface_two_planes; -use super::texture::{Bytes, HostLie, IdUse, Pages, Texture}; -use super::texture_descriptor::{ - Creator, Refused, TextureDescriptor, TextureLayout, TextureProblem, -}; -use super::texture_placement::TexturePlacement; -use super::tracker::{Access, ImagePlace, Use, UseRange}; -use super::two_planes; -use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; -use super::view_plan::ViewRecord; -use super::ycbcr::{surface_planes, IoSurfaceYCbCr}; -use super::Device; -use crate::release; -use ash::vk; -use metal2vulkan::bind::{BoundTexture, BufferRange, YCbCrPlanes}; -use metal2vulkan::device::{FormatUsage, VkFeature}; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{byte_format, ycbcr, ycbcr_format}; -use metal2vulkan::metal::{PixelFormat, TextureSwizzleChannels, TextureType, TextureUsage}; -use metal2vulkan::vk::{Format, ImageAspectFlags}; -use std::collections::HashMap; -use std::ops::Range; -use std::sync::atomic::AtomicU64; -use std::sync::{Arc, Mutex}; - -/// A texture's texels in a buffer's bytes, where Metal lays them out. -pub(super) struct Texels { - pub(super) buffer: Buffer, - /// Where the GPU's commands find the texels in the buffer. - pub(super) layout: BufferLayout, - /// Where the CPU's `replace_region` and `get_bytes` find them: `layout`, but for an IOSurface - /// plane whose offset or pitch is not a multiple of 16 (`linear_plan.rs`). - cpu: BufferLayout, - /// Where a function reads and writes a texture buffer's texels: `layout`, but from its offset - /// rounded down to 16 bytes, as plain Metal's functions read and write a texture buffer at an - /// offset off 16 ([`Texels::into_texture_buffer`]). - shader: BufferLayout, - /// The bytes of one texel: of one block of a block-compressed texture (`blocks`). - texel_bytes: u64, - /// A block-compressed texture's blocks (a BC texture over an IOSurface plane's rows, - /// `linear_plan.rs`): `layout`'s rows are rows of them; `None` for every other texture, - /// whose rows are rows of texels. - blocks: Option, - pub(super) allow_gpu_optimized_contents: bool, - /// The texture's resource options, its hazard tracking mode resolved, as `resourceOptions` - /// reports them: the buffer's, which Metal's texture over a buffer takes, but an IOSurface - /// plane's descriptor's (`Buffer::new_texture_with_iosurface_plane`). Its hazard tracking - /// mode is its uses' (`Texels::tracked`). - options: ResourceOptions, - /// The texel buffer views bindings needed, by format, kind (storage or uniform) and range, - /// made at their first bind. A finite set per texture: the formats its plans view it as. - views: Arc, - /// A texture buffer's staging buffer and its copies, where Vulkan views no texels at the - /// texels' offset in the buffer's `VkBuffer` (`Texels::into_texture_buffer`): its bindings view - /// the staging buffer, a shadow the encoders copy the texels into and back (`shadow.rs`). - staged: Option>, - /// What made `buffer` for the texels, where that is not the program. - pub(super) home: TexelsHome, - /// A texture buffer's attachment twins, by the pixel format a render pass renders it in - /// (`Texture::attachment_twin`), made at the first pass that needs each. - twins: Mutex>, - /// The alpha plane a two-plane extended-range texture over a surface's plane 0 keeps its - /// alpha bytes in, where Metal's GPU finds them, `layout` holding its color words - /// (`texture/surface_two_planes.rs`); `None` for every other texture. - alpha: Option, - /// The texture objects over the texels as a texture buffer's (`Storage::Texels`), and the - /// caller's token for a texture buffer's range (`Device::new_texture_with_range_token`). - pub(super) objects: ObjectsToken, - /// The texels lie in an IOSurface's plane (`Buffer::new_texture_with_iosurface_plane`). - surface: bool, - /// The tail of a 2D texture, an array or a texture buffer whose texels run past the bytes - /// they keep in place (`kept`; `linear_plan.rs`'s **Length**), which holds the texels' bytes - /// there: a runtime `Shared` buffer of the bytes from the texels' first to their last, laid - /// out as in the buffer from its start (`Texels::tail_base`), zero when made. Its bytes - /// before `kept` mirror the buffer's for the shadow's copies, which go through it - /// ([`Texels::shadow_copies`], `into_texture_buffer`); every other access to the texels (the - /// CPU's, a blit's rows) takes the bytes kept in place from the buffer and those past them - /// from here ([`Texels::past`]). `None` for texels kept in place whole. - tail: Option, - /// Where the texels' bytes in place end: the bytes a texture over the buffer reaches in its - /// memory (`Buffer::texel_reach`: Metal's allocation of a buffer of its own, which for one - /// of at least 16 KiB runs past its length, a no-copy buffer's length, a heap's buffer's heap - /// to its end), but the buffer's length for an IOSurface plane's, and for a 2D array of more - /// than one slice over a plane, whose slices past the first lie in the tail from their first - /// byte on, that slice's first byte (`linear_plan::Placed::kept`). The tail holds the texels' - /// bytes from here. - kept: u64, -} - -/// Where a texture's texels past the bytes they keep in place lie ([`Texels::past`]): the -/// buffer's bytes from `length` on are the tail's, byte `v` of the buffer's space at `v - rebase` -/// of the tail. `length` is where the texels in place end ([`Texels::kept`]): the bytes the -/// buffer's memory holds for them, its length for an IOSurface plane's, and a 2D array's over a -/// plane whose slices past the first lie in the tail, the second slice's first byte. -#[derive(Clone, Copy)] -pub(super) struct Past<'a> { - pub(super) tail: &'a Buffer, - pub(super) length: u64, - pub(super) rebase: u64, -} - -/// A block-compressed texture's blocks in its texels' layout ([`Texels::blocks`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Blocks { - /// The texels of a block, across and down. - pub(super) extent: [u32; 2], - /// The texture's own texels, across and down, which its last block of a row or of a column - /// may cover only part of. - pub(super) texels: [u32; 2], -} - -/// A texture's texel buffer views, by format, kind (storage or uniform) and range; destroyed -/// with it. Over a buffer's host pages, a rebind empties them, the views of the old pages going -/// with those pages (`rebind.rs`), and the next bind makes them again over the new ones. -pub(super) struct TexelViews { - device: Device, - views: Mutex>, -} - -impl TexelViews { - /// The views made so far, for the pages they view to keep: none from now on. - pub(super) fn park(&self) -> ViewObjects { - let views = lock(&self.views).drain().map(|(_, view)| view).collect(); - ViewObjects { - device: self.device.clone(), - views, - } - } -} - -impl Drop for TexelViews { - fn drop(&mut self) { - // Once the process is exiting, the views are left to its end (`exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - let raw = self.device.shared().vk(); - // SAFETY: no pending command buffer uses a view: a committed command buffer holds every - // texture it binds until it completes, and a gone texture buffer's texels, whose views a - // heap set may hold, wait for every command buffer that may read the set - // (`heap_sets::gone`). - unsafe { - for &view in lock(&self.views).values() { - release::object(raw, view); - } - } - } -} - -/// Texel buffer views of host pages a rebind replaced, destroyed with those pages -/// ([`TexelViews::park`]). -pub(super) struct ViewObjects { - device: Device, - views: Vec, -} - -impl Drop for ViewObjects { - fn drop(&mut self) { - let Some(_busy) = exit_guard::enter() else { - return; - }; - let raw = self.device.shared().vk(); - // SAFETY: the pages that keep them go once every command buffer that used them - // completed. - unsafe { - for &view in &self.views { - release::object(raw, view); - } - } - } -} - -/// Where an IOSurface's plane lies in the buffer that stands for the surface -/// ([`Buffer::new_texture_with_iosurface_plane`], the stand-in for Metal's -/// `newTextureWithDescriptor:iosurface:plane:`, which reads these from the `IOSurfaceRef`). -/// -/// Made with [`IoSurfacePlane::new`] and the `with_` methods (the struct is `#[non_exhaustive]`, so -/// a field added later breaks no caller). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct IoSurfacePlane { - /// The plane's first byte in the buffer, whose first byte is the surface's base: - /// `IOSurfaceGetBaseAddressOfPlane` less `IOSurfaceGetBaseAddress`, or 0 for a surface - /// without planes. - pub offset: u64, - /// The plane's `bytesPerRow`: `IOSurfaceGetBytesPerRowOfPlane`, or `IOSurfaceGetBytesPerRow` - /// for a surface without planes. - pub bytes_per_row: u64, - /// Whether the surface has planes: `IOSurfaceGetPlaneCount` above 0, a surface made with - /// plane info (`kIOSurfacePlaneInfo`, one plane dictionary or more). - pub planar: bool, - /// The value of `kIOSurfaceClientDirection` the surface was made with (an IOSurface - /// property outside the public SDK's headers), `None` for a surface made without the key. A - /// surface with it is refused, whatever the value - /// ([`AppleOnly::SurfaceClientDirection`]). - pub client_direction: Option, - /// The surface's facts a two-plane YCbCr texture over it reads (its OSType, its chroma plane, - /// its YCbCr matrix), `None` where the caller gives none: a texture of such a format is then - /// refused. A two-plane extended-range texture (`RGB10A8_2P_XR10`, `RGB10A8_2P_XR10_sRGB`) - /// reads plane 1's offset and `bytesPerRow` from them too (`chroma_offset`, - /// `chroma_bytes_per_row`). Other formats ignore it. - pub ycbcr: Option, -} - -impl IoSurfacePlane { - /// Refused: a surface made with `kIOSurfaceClientDirection`, whatever the value - /// ([`AppleOnly::SurfaceClientDirection`]). - fn refuse_client_direction(&self) -> Result<(), Error> { - match self.client_direction { - Some(_) => Err(Error::AppleOnly(AppleOnly::SurfaceClientDirection)), - None => Ok(()), - } - } - - /// A plane at `offset` of the buffer standing for the surface, rows `bytes_per_row` apart, - /// of a surface with planes or not (`planar`), made without `kIOSurfaceClientDirection`, - /// with no YCbCr facts. - pub const fn new(offset: u64, bytes_per_row: u64, planar: bool) -> IoSurfacePlane { - IoSurfacePlane { - offset, - bytes_per_row, - planar, - client_direction: None, - ycbcr: None, - } - } - - /// This plane of a surface made with `kIOSurfaceClientDirection` of `direction`. - pub const fn with_client_direction(mut self, direction: u64) -> IoSurfacePlane { - self.client_direction = Some(direction); - self - } - - /// This plane of a surface with `ycbcr`'s facts. - pub const fn with_ycbcr(mut self, ycbcr: IoSurfaceYCbCr) -> IoSurfacePlane { - self.ycbcr = Some(ycbcr); - self - } -} - -/// What made the buffer a texture's texels are the bytes of. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum TexelsHome { - /// The program's buffer, or one the device made for a texture buffer - /// (`newTextureWithDescriptor:`). - Buffer, - /// A heap, which placed it for a texture buffer (`texture/heap.rs`): the texture answers the - /// buffer's heap, offset and aliasing as its own. - Heap, - /// The device, for a shareable texture buffer (`newSharedTextureWithDescriptor:`, - /// `texture/shared.rs`): a texture opened from its handle is the same texels. - Shared, -} - -/// Where the bytes kept in place of texels `placed` lays out in a buffer of `length` bytes end -/// ([`Texels::kept`]): the length, or a 2D array's second slice over an IOSurface plane where -/// that comes first (`linear_plan::Placed::kept`). -fn kept_in(placed: &Placed, length: u64) -> u64 { - placed.kept.map_or(length, |kept| kept.min(length)) -} - -/// Whether texels laid out for the GPU, the CPU and a texture buffer's functions as `layouts` -/// say run past `kept`, the bytes they keep in place ([`Texels::runs_past`]). -fn past_kept(layouts: [&BufferLayout; 3], kept: u64) -> bool { - layouts.iter().map(|layout| layout.end()).max() > Some(kept) -} - -/// Whether the rows' padding of texels laid out as `layout` in a buffer of `length` bytes is the -/// buffer's own ([`Texels::padding_owned`]): the buffer holds their last row to its pitch, and -/// they lie over a buffer's rows, or over an IOSurface plane's (`surface`) where the buffer -/// declares the bytes between a texture's rows unobserved (`unobserved`). -fn owns_padding(layout: &BufferLayout, surface: bool, unobserved: bool, length: u64) -> bool { - let to_pitch = BufferLayout { - row_bytes: layout.row_pitch, - ..*layout - }; - (!surface || unobserved) && to_pitch.end() <= length -} - -/// The bytes of one texel of `pf`, the block of its direct Vulkan format (the bytes Metal's -/// format has, for every format the runtime holds exactly); `None` without one. -pub(super) fn texel_bytes(pf: PixelFormat) -> Option { - byte_format(pf) - .and_then(|format| format.block()) - .map(|block| u64::from(block.size)) -} - -/// The error of `refusal` in `call`. -fn refusal_error(call: &'static str, refusal: BufferRefusal) -> Error { - match refusal { - BufferRefusal::Metal(problem @ BufferTextureProblem::PastAllocation { .. }) => { - nil(call, Problem::BufferTexture(problem)) - } - BufferRefusal::Metal(problem) => invalid(call, Problem::BufferTexture(problem)), - BufferRefusal::TexelsPastLength => { - Error::NotImplemented(RuntimeGap::TexelsPastBufferLength) - } - BufferRefusal::OverlappingRows => Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows), - BufferRefusal::MemorylessPlane => Error::NotImplemented(RuntimeGap::MemorylessSurfacePlane), - BufferRefusal::PlaneShape => Error::NotImplemented(RuntimeGap::SurfacePlaneShape), - } -} - -/// Whose a texture over a buffer is, for its resource ID (`resource_ids.rs`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Whose { - /// The program's: its descriptor's placement gives its ID. - Program, - /// The runtime's own (`Buffer::new_runtime_texture`): no ID. - Runtime, -} - -/// What a texture over a buffer's making does (`Buffer::make_texture_over`): make the texture, or -/// answer where it would lie ([`Buffer::texture_placement`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Goal { - Make, - Ask, -} - -/// What a texture over a buffer's making gives for its [`Goal`]. -enum Over { - Made(Texture), - Asked(TexturePlacement), -} - -impl Whose { - /// How a texture of a descriptor at `placement` takes its ID. - fn id_use(self, placement: IdPlacement) -> IdUse { - match self { - Whose::Program => IdUse::Program(placement), - Whose::Runtime => IdUse::Runtime, - } - } -} - -impl Buffer { - /// `newTextureWithDescriptor:offset:bytesPerRow:`: a texture of `descriptor` whose texels - /// are the buffer's bytes from `offset`, rows `bytes_per_row` apart: a 2D texture or a - /// texture buffer. The texture has the buffer's resource options, whatever the descriptor - /// names, as a plain run of Metal's has (Metal's validation alone stops a descriptor's storage - /// or CPU cache mode other than the buffer's). - /// - /// A 2D texture is a linear image aliasing the bytes where the device lays one out as Metal - /// does, else an image the encoders copy the texels into before the commands that use it - /// and back after the ones that write it; a texture buffer is the bytes themselves. A texture - /// buffer may lie at any offset: at one off 16 bytes, which Metal's validation alone stops, - /// functions read and write it from the offset rounded down to 16, and blits and the CPU at the - /// offset, as on plain Metal. - /// - /// Refused: what Metal stops (`Invalid`, with a [`TextureProblem`] - /// or a [`BufferTextureProblem`]); a format of which plain - /// Metal makes no texture alone (`Nil`, `TextureProblem::NoTextureOfFormat` or - /// `Unspecialized`, once every rule Metal stops passed and before the buffer's own: offset, - /// row pitch, bytes past the buffer); a format with no exact Vulkan format (a 4:2:2 one among - /// them, which plain Metal makes over a buffer), and an image the device lacks (`Unsupported`); - /// a 2D texture of a format the device cannot copy (`NotImplemented`); a swizzle that writes - /// under `write_swizzle_enabled`, which Metal makes (`NotImplemented(WriteSwizzle)`). A texture - /// buffer of more than one level is stopped (`BufferTextureProblem::MipmapLevelCount`), as - /// Metal's validation stops it here. - /// - /// A 2D texture or a texture buffer whose texels run past the buffer's length, which plain - /// Metal makes while its last texel ends inside the buffer's allocation, counted from the - /// buffer's start (and answers nil past it, `Nil` with - /// `BufferTextureProblem::PastAllocation`): the buffer's `allocatedSize` (its length rounded - /// up to 16 KiB), a heap's buffer's heap's size, a no-copy buffer's pages (its pointer's - /// offset in its 16 KiB page plus its length, rounded up to 16 KiB), and no bound under - /// 16 KiB, is made. Its texels are the buffer's memory where that holds them: a buffer of at - /// least 16 KiB this device made holds its whole allocation, zero when made, and a heap's - /// buffer reaches the rest of its heap, so such a texture is made as one inside the length - /// is, its writes past the length landing in that memory as Metal's do. Past a no-copy - /// buffer's length, and past a shorter buffer's, its texels lie in a tail the texture keeps, - /// zero when made, which its functions, blits and CPU calls read and write alike; Metal's - /// texels there are the caller's pages, or memory past the buffer's own, which its writes - /// there change (docs/API.md's accepted differences). Such a 2D texture is a shadow image, - /// announced `shadowed-texture`; such a texture buffer's functions view its tail, announced - /// `staged-texture-buffer`. - pub fn new_texture( - &self, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - self.texture_over( - "new_texture", - descriptor, - offset, - bytes_per_row, - (BufferTextureCall::Texture, Whose::Program), - None, - ) - } - - /// [`new_texture`](Self::new_texture) of a texture of the runtime's own, which no program - /// made: it takes no resource ID (`IdUse::Runtime`, `resource_ids.rs`), whatever the - /// descriptor's placement, so it moves no ID the program's textures take, on whichever thread - /// it is made. The device's check of textures in place makes its textures here - /// (`in_place_check.rs`), as `new_texture`, and a read twin its twin textures - /// (`read_twin.rs`), as `make_twin_texture`: `call` names the making in its errors and the - /// shadow log. - pub(crate) fn new_runtime_texture( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - ) -> Result { - self.texture_over( - call, - descriptor, - offset, - bytes_per_row, - (BufferTextureCall::Texture, Whose::Runtime), - None, - ) - } - - /// `newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:` (SPI): as - /// [`new_texture`](Self::new_texture), and also a 2D array, whose slices Metal lays out - /// itself: each starts `bytes_per_row` × height, rounded up to 128 bytes, after the one - /// before. The bytes-per-image argument is ignored, as plain Metal ignores it: its - /// validation alone asserts that it is a multiple of 128. - /// - /// Refused as [`new_texture`](Self::new_texture) is; an array counts its rounded slices - /// against the buffer's allocation, not its last texel (`Nil`, as Metal answers nil, once its - /// texels run past the length). An array whose texels run past the buffer's length short of - /// that is made as `new_texture` makes a 2D texture there. - pub fn new_linear_texture( - &self, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - _bytes_per_image: u64, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - self.texture_over( - "new_linear_texture", - descriptor, - offset, - bytes_per_row, - (BufferTextureCall::Linear, Whose::Program), - None, - ) - } - - /// `newTiledTextureWithDescriptor:offset:bytesPerRow:` (SPI; the device's - /// `newTiledTextureWithBytesNoCopy:length:descriptor:offset:bytesPerRow:` makes its texture - /// over a no-copy buffer through it): as [`new_texture`](Self::new_texture), and also a 2D - /// texture of more than one level, a copy of the buffer's bytes from `offset`, rows - /// `bytes_per_row` apart, taken at its first use. A texture of one level is the one - /// `new_texture` makes, in place where that is. - /// - /// A texture of more levels is one image of its own holding every level, in the `GENERAL` - /// layout like every image here, as an x86 Mac's is (an AMD Radeon Pro 5300M and an Intel UHD - /// Graphics 630 under macOS 26.7.1, which agreed on both SPI forms, `Shared` and `Managed` - /// descriptors, and `RGBA8Unorm` and `BGRA8Unorm`): - /// - /// - **Taken at use.** The first command of an encoder that uses any of its levels after its - /// making, or after [`Texture::did_modify_data`](crate::Texture::did_modify_data) or a - /// `replace_region` of its first level, takes the copy: before that command, the bytes are - /// copied into its first level and every later level is made from the first as - /// `generate_mipmaps` makes them for its format: the device's blit chain or the compute - /// filter (both announced as `device-filtered-mipmaps`), or for an integer format plain - /// Metal's texel picks. The copy is taken as that command is encoded and runs on the GPU in - /// its command buffer's order, so it reads the bytes as they are when the command buffer - /// runs: a CPU write made after the making and before then is in every level (on the Macs, - /// at once or 100 ms after the making). Between takes nothing moves: a CPU write of the - /// bytes reaches no level, nor does a GPU write of them (not measured on a Mac), and what - /// the GPU writes into any level (a blit, a pass, a function's write) stays in the texture - /// and never reaches the bytes or, written into the first, the later levels. - /// - **CPU calls.** `get_bytes` and `replace_region` of the first level read and write the - /// buffer's bytes, as the Macs' do, whatever the GPU wrote into that level; a - /// `replace_region` there makes the next use take the copy again, as `did_modify_data` - /// does. Of a later level they read and write the image, whose texels the GPU reads until - /// the next take makes that level again. What differs from a Mac: there a `replace_region` - /// of a later level never reaches the GPU, and what `get_bytes` reads there is not - /// measured. - /// - **Formats.** For a format `generate_mipmaps` leaves as it is (a depth or stencil one) or - /// refuses on the device, and where the scratch of its compute filter or its picks passes - /// the device's limits, the copy moves the first level alone and the later levels keep what - /// they hold (docs/FAST-PATHS.md, known gaps). - /// - **What else differs.** It takes the buffer's resource options, as `new_texture`'s - /// texture does, so a texture over a `Shared` buffer answers `Shared`, as the Macs do. A - /// view in a format the image takes no Vulkan view of, and a binding beyond the texture's - /// usage, are refused (`Unsupported`), where a texture of one level over a buffer takes them - /// through a shadow of the bytes. While the buffer's bytes are detached (`detach_backing`) - /// it keeps its image, every level of which its commands read and write, as a Mac's - /// texture's own memory, and its CPU calls the levels past the first; theirs of the first - /// level, the bytes, are refused meanwhile (`NotImplemented(DetachedTexelAccess)`), as a - /// one-level texture's are. A take while they are detached is a copy out of them, a command - /// that names the buffer (`detach.rs`). - /// - /// Announced once (`shadowed-texture`, naming the levels), counted in - /// `WorkCounts::shadowed_textures`, each take's copy in `WorkCounts::shadow_texels_copied_in` - /// (its first level's texels alone) and a take by the compute filter in - /// `WorkCounts::mipmaps_filtered`; nothing is ever counted in - /// `WorkCounts::shadow_texels_copied_back`. A take whose compute filter or picks find no room - /// for their scratch in the device's memory fails its command buffer. - /// - /// Refused as [`new_texture`](Self::new_texture) is, but for the levels: more levels than the - /// extent's full chain (`Invalid`, `TextureProblem`), and a texture buffer of more than one - /// (`BufferTextureProblem::MipmapLevelCount`). A texture buffer's offset is held to 16 bytes, - /// as [`new_linear_texture`](Self::new_linear_texture)'s is: the SPI's is not measured. - pub fn new_tiled_texture( - &self, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - self.texture_over( - "new_tiled_texture", - descriptor, - offset, - bytes_per_row, - (BufferTextureCall::Tiled, Whose::Program), - None, - ) - } - - /// The stand-in for `newTextureWithDescriptor:iosurface:plane:` over the caller's memory: a - /// texture of `descriptor` whose texels are `plane`'s, the buffer standing for the IOSurface - /// (a no-copy buffer over the surface's pages, `IOSurfaceGetBaseAddress` for - /// `IOSurfaceGetAllocSize` bytes, or a buffer holding them): a 2D texture or a texture buffer, - /// and over a plane of a surface with planes also a 1D texture whose row fits and a 2D array - /// of one slice, laid out as the 2D texture of their rows (a texture buffer's texels run on - /// from such a plane's offset however wide). Metal's IOSurface rules apply, measured on the M3 - /// Max and an M4, not [`new_texture`](Self::new_texture)'s buffer rules: - /// - /// - the texture takes and reports the descriptor's resource options, whatever the buffer's - /// (its default hazard tracking mode resolves to tracked), as an M4's plain run and its - /// validation do for `Shared` and `Managed`. Plain Metal also makes a `Private` one, whose - /// GPU and CPU read and write the surface's bytes as a `Shared` one's do, and so does the - /// runtime, over a buffer the CPU reaches; Metal's validation stops it; - /// - a plane of a planar surface takes any offset and any `bytes_per_row` that covers its - /// row; a surface without planes, a `bytes_per_row` that is a multiple of 16, at an offset - /// that is one too (Metal asserts on another pitch). The row the pitch covers is the - /// **texture's** own, whatever the plane holds and whatever the rotation: a rotated - /// texture's plane holds the turned frame, and Metal still holds the pitch to the texture's - /// unturned row (measured on the M3 Max, plain Metal with no validation layer: a 4x8 plane - /// at its tight stride of 16 behind an 8x4 texture ends the process, "bytesPerRow (16) must - /// be greater or equal to (32) bytes"); - /// - `get_bytes` and `replace_region` read and write the plane where the surface lays it out: - /// from its offset, rows `bytes_per_row` apart; - /// - the GPU's commands read and write it as Metal's GPU does: from the offset rounded down to - /// 16, rows `bytes_per_row` rounded down to 16 apart, which are other bytes than the CPU's - /// where either is not a multiple of 16; - /// - under 16 bytes a row, the GPU's rows are 16 bytes apart. There Metal's GPU reads every - /// row past the first as memory-dependent bytes; the runtime's reads them where its writes - /// put them, a near-equivalent announced once - /// ([`Degradation::NarrowSurfaceRows`]); - /// - where that pitch is below the row, the GPU's rows share bytes: 1 to 15 of them, a whole - /// number of texels, between consecutive rows. A plain plane is made, its shadow's copies - /// reproducing the sharing with two regions a slice each way, so that a read sees it as - /// Metal's does and the shared bytes keep the earlier row's where two of its rows write - /// them. Which row Metal leaves there is the order its own command wrote the rows in, which - /// follows the command, the GPU pitch and the row count (`linear_plan.rs`'s **Rows that - /// overlap**); a kernel, the only writer such a plane takes here, moves its winner with the - /// threadgroup shape, so the earlier row's bytes are one of its answers. Announced once by - /// [`Degradation::CollidingSurfaceRowWrites`]; - /// - a colour 2D texture whose rows are wider than the `bytes_per_row` of a plane of a - /// surface with planes at an offset and pitch that are multiples of 16, and a colour 1D - /// texture wider than one row there, are made as the M3 Max lays them out on every path: - /// row `y` from the offset plus `y` x `bytes_per_row`, the whole row, for the GPU and the - /// CPU alike, so the 2D texture's rows share bytes, any whole number of texels, a byte - /// shared by as many rows as reach it. They are held as the rows above that share bytes - /// are, announced once by the same notice. - /// - /// Refused: a surface made with `kIOSurfaceClientDirection`, SPI - /// ([`AppleOnly::SurfaceClientDirection`]); what - /// Metal stops (`Invalid`, with a [`TextureProblem`] or a - /// [`BufferTextureProblem`]: over a surface without planes a - /// type other than 2D or a texture buffer, more than one level, a pitch below the row, another - /// pitch or offset, or rows that end past it, which plain Metal asserts on); what Metal makes - /// over a plane of a surface with planes and lays out no one way across the GPUs measured - /// (`NotImplemented(SurfacePlaneShape)`, which carries the measurements: rows wider than the - /// plane's of a format but a colour one or off 16 bytes, more than one level, a 3D or - /// multisample texture of a format but a colour one, a 2D array of slices of such a format - /// or off 16 bytes, a cube or cube array of such a format or off 16 bytes, another type, a BC - /// texture of 16-byte blocks whose rows of blocks are wider than the plane's or at an offset - /// or pitch off 16 bytes, and one of 8-byte blocks wider than the plane's rows over a plane - /// off 16 bytes, off 8 bytes or under 16 bytes a row); `Memoryless` storage, which plain - /// Metal makes and serves on the CPU while its GPU uses fail the command buffer - /// (`NotImplemented(MemorylessSurfacePlane)`, which carries the measurement); rows that - /// overlap on Metal's GPU where no shadow of the runtime's holds them - /// (`NotImplemented(OverlappingSurfaceRows)`: a plane a render pass stores into, a two-plane - /// YCbCr one over a surface without planes, a two-plane extended-range, 4:2:2, depth or - /// stencil one, and a blit that addresses such a plane's rows as bytes; `linear_plan.rs`); a - /// plane's own rows or its GPU texels past - /// the buffer, of a shape that keeps no tail (`NotImplemented(TexelsPastBufferLength)`: a - /// two-plane YCbCr, two-plane extended-range, 4:2:2, depth, stencil, BC or rotated one); and - /// as [`new_texture`](Self::new_texture) refuses a format or an image. - /// - /// A colour texture of a plane of a surface with planes whose texels run past the buffer - /// standing for the surface is made: Metal makes it and lays those texels out in no one place - /// (its blits read zeros there, its kernels zeros and the plane's rows again 32 KiB on, its - /// `getBytes` other memory, and its writes keep to the surface; an Apple M3 Max under macOS - /// 27.0.1). The runtime keeps them in a tail of the texture's own, zero when made, which every - /// path reads and writes alike, and its texels inside the surface are the buffer's bytes - /// (the module's **Tails**). Announced once by [`Degradation::SurfaceTexelsTail`]. - /// - /// A colour 2D texture of more than one level, a 3D texture and a 2D multisample one over a - /// plane of a surface with planes are made in memory of their own, zero when made in every - /// storage mode, as [`Device::new_texture`](crate::Device::new_texture) makes one otherwise: - /// Metal makes each and lays out its texels in no one place there, its first level's and - /// slice's among them (an Apple M3 Max under macOS 27.0.1, whose GPU reads them from other - /// bytes than its writes and its CPU put them; the x86 Macs keep the first level and slice - /// over the plane). Announced once by [`Degradation::SurfaceTexelsApart`]. - /// - /// A colour 2D array of more than one slice over a plane of a surface with planes whose - /// offset and `bytesPerRow` are multiples of 16 is made with its first slice over the plane, - /// the buffer's bytes as a 2D texture's there, and its slices past the first in a tail of the - /// texture's own, zero when made, which every path reads and writes alike: Metal keeps the - /// first slice over the plane on every path and lays the others out in no one place (the M3 - /// Max's blits and `getBytes` read the second at the plane's offset, its kernels one image - /// on, and its writes land at the plane's offset). Announced once by - /// [`Degradation::SurfaceTexelsTail`]. - /// - /// A colour cube or cube array over a plane of a surface with planes whose offset and - /// `bytesPerRow` are multiples of 16 is made face after face, face `k` (every cube's six, one - /// cube after another) at the plane's offset plus `k` times its rows times `bytesPerRow`, for - /// the GPU and the CPU alike, its faces past the buffer standing for the surface in a tail of - /// the texture's own, zero when made (announced once by - /// [`Degradation::SurfaceTexelsTail`]): the x86 Macs make it and their GPUs lay its faces so - /// inside the plane (an AMD Radeon Pro 5300M and an Intel UHD 630 under macOS 26.7.1, whose - /// GPUs read other bytes for a face past the plane's rows and drop its writes, and whose CPU - /// calls lay the faces two other ways), where plain Metal on an Apple M3 Max asserts on it. - /// A face past the plane's rows but inside the surface is the surface's bytes there, as - /// every texture's rows past its plane's are: the call gives no plane height. - /// - /// A BC texture of 8-byte blocks (`BC1_RGBA`, `BC4_RUnorm` and their kin) whose rows of - /// blocks are wider than the plane's `bytesPerRow`, over a plane at an offset and - /// `bytesPerRow` that are multiples of 16, keeps each row of blocks to the plane's row: its - /// first `bytesPerRow` bytes in place, its blocks past them in no byte, reading zero on every - /// path (a kernel's, a sample's, a blit's and `get_bytes`) and taking no write (a blit's or - /// `replace_region`'s columns there are dropped), as both x86 Macs' blits lay it out (an AMD - /// Radeon Pro 5300M and an Intel UHD 630 under macOS 26.7.1; the UHD 630's samples of those - /// blocks decode other memory). Its texels are a shadow image, never an image over the - /// plane's bytes, which no image holds so. - /// - /// A depth or stencil texture (`Depth16Unorm`, `Depth32Float`, `Depth32Float_Stencil8`, - /// `Stencil8`, `X32_Stencil8`) over a plane of a surface with planes is made as Metal makes - /// it, one aspect's unit a texel in the plane (its depth, else its stencil; the stencil of - /// `Depth32Float_Stencil8` is not in the plane and reads 0): its reads, samples, blits and CPU - /// access take the plane's bytes, and its render passes store it there in Metal's tiled layout, - /// its elements' bytes alone (`texture/surface_depth.rs`), a pass loading the stencil of - /// `Depth32Float_Stencil8` loads 0, and its views render as it does. A blit of that stencil is - /// the runtime's gap (`NotImplemented(SurfaceDepthStencil)`), with what - /// `texture/surface_depth.rs` lists. Over a surface without planes Metal stops it (`Invalid`, - /// `BufferTextureProblem::NotLinear`). - /// - /// A BC1 to BC7 texture over a surface's rows (2D, over a plane of a surface with planes at an - /// offset and pitch that are multiples of 16, or for BC1 and BC4, whose blocks are 8 bytes, - /// at an offset and pitch the block divides, at least 16 a row) is made as the x86 Macs make - /// it, where the M3 Max answers nil: row `j` of its blocks at the plane's offset + `j` x - /// `bytes_per_row`, unrounded, which its samples, blits and CPU calls take (`linear_plan.rs`'s - /// **Block-compressed surfaces**; at an offset off 16 the UHD 630's CPU calls take the plane - /// from byte 0). - /// Over a surface without planes Metal stops a row of blocks wider than the surface's - /// (`RowPitch`) and rows of texels past it (`PastBuffer`). Every other compressed format is - /// stopped as over a buffer (`NotLinear`). - /// - /// A plane of a 4:2:2 format (`GBGR422`, `BGRG422`: a CoreVideo `2vuy` or `yuvs` surface's) - /// is made as Metal makes it, 2 bytes a texel, copied as a 4:2:2 texture of the device's is - /// (`linear_plan.rs`), and read through an image of its texels decoded from the pairs where - /// they lie (`texture/surface_pairs.rs`). - /// - /// A two-plane YCbCr texture of 8 or 10 bits, converted (`YCBCR8_420_2P`, - /// `YCBCR10_444_2P`, ...), through the sRGB curve (their `_sRGB` twins) or read as codes - /// (`RGB8_420_2P`, `RGB10_420_2P`), and the packed 10-bit ones (`YCBCR10_420_2P_PACKED`, ...) - /// and their `_sRGB` twins, over any plane of a surface of any OSType but the lossless - /// compressed ones, or over plane 0 of a surface without planes, given the surface's facts - /// ([`IoSurfacePlane::ycbcr`]), samples the texels Metal reads of the planes, and its copies - /// and CPU calls move the luma codes, as Metal's do (`ycbcr.rs` states its rules and - /// refusals: the luma plane the call's, the chroma plane the facts' plane 1 under plane 0 of a - /// surface with planes, chroma codes 0 under any other, bytes past the buffer zeros). Over a - /// plane of a surface with planes its rows of codes may be wider than the planes' - /// `bytes_per_row` and overlap (a texture wider than its plane, a 10-bit format over 8-bit - /// rows): it reads each row of codes at the planes' rows, `get_bytes` reads the luma rows - /// there and `replace_region` writes them in order, the later row's bytes standing where - /// rows meet, as Metal's do; a blit from a buffer into it, a function's writes that Metal - /// stores into the planes (a 4:4:4 format's) and a render pass into it are refused there - /// (`NotImplemented(OverlappingSurfaceRows)`): what Metal's blit leaves where rows meet follows - /// no one order, and its stores there are not measured. A packed - /// texture's CPU calls move nothing, as Metal's; its blits with a buffer are refused - /// (`NotImplemented(Format)`). A render target of a 4:2:0 or 4:2:2 format of an odd width or - /// height is Metal's nil (`TextureProblem::ExtentForFormat`). Metal makes every two-plane - /// YCbCr format over a surface's plane; another is the runtime's gap - /// (`NotImplemented(Format)`). - /// - /// An `RGB10A8_2P_XR10` or `RGB10A8_2P_XR10_sRGB` texture over plane 0 of a two-plane - /// `'b3a8'` surface, given plane 1's offset and `bytesPerRow` in the surface's facts - /// ([`IoSurfacePlane::ycbcr`]: `chroma_offset`, `chroma_bytes_per_row`), keeps each texel's - /// color word in plane 0 and its alpha byte in plane 1, where Metal's GPU reads and writes - /// them; its CPU calls and its blits with a buffer move plane 0's color words, as Metal's do, - /// and its fills and its blits with another such texture move the surface's bytes as Metal's - /// do. Without the facts, over another surface or plane, and rotated, it is refused - /// (`NotImplemented(Format)`, naming why). - /// - /// Another format of which plain Metal makes no texture alone - /// (`RGBA16Float_XR`, `AnyDepth`, `AnyStencil`, `Unspecialized`) answers `Nil`, as Metal - /// answers nil over a surface's plane, once every rule Metal stops passed - /// and before the surface's own. - pub fn new_texture_with_iosurface_plane( - &self, - descriptor: &TextureDescriptor, - plane: IoSurfacePlane, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - plane.refuse_client_direction()?; - let texture = self.texture_over( - "new_texture_with_iosurface_plane", - descriptor, - plane.offset, - plane.bytes_per_row, - ( - BufferTextureCall::IoSurfacePlane { - planar: plane.planar, - }, - Whose::Program, - ), - plane.ycbcr, - )?; - // Metal's device takes a sampler ID as it makes a surface's texture, as for a texture of - // its own (unlike a buffer's: `resource_ids.rs`). - self.generation().take_device_sampler(); - Ok(texture) - } - - /// Where a texture [`new_texture`](Self::new_texture) makes of the same arguments lies if - /// made now: in place over the buffer's host pages, a shadow pending the device's check, a - /// shadow and why, or a texture the device's check does not decide ([`TexturePlacement`]). A - /// runtime extension: Metal has no such query, as a Mac's GPU works on a texture over the - /// caller's pages in place. - /// - /// The answer is the making's own decision, the same functions' (the device's policy, the - /// texture's usage and texel size, the buffer's bytes detached, copied or past their length, - /// a discrete GPU's device copy, the device's check's verdicts for the pages' kind, the - /// texture's accesses and how its texels lie in the device's lines of memory, and the image - /// in place's making up to its bind: the driver's linear image at the texture's pitch, else - /// the `DRM_FORMAT_MOD_LINEAR` one, its requirements against the bytes' place and memory - /// type, rows that share bytes), taken after every check the making runs before it makes - /// anything: an argument `new_texture` refuses is refused here alike, with the same error. - /// Where the route is the image in place, the query asks first what the device answers - /// without an image (rows that share bytes, and its format, feature and limit queries for each - /// plan the making would try), and where those refuse every plan answers that refusal, making - /// no image; else it makes the image unbound and releases it: one or two `VkImage`s where the - /// texture's declared plan is made in place, a pair more for each wider plan the making would - /// try first (the feedback loop usage, and the storage usage) where it is refused; nothing is - /// bound or submitted. Before a no-copy buffer is made, - /// [`Device::host_pages_texture_placement`] answers by the same steps up to the import. What - /// only the bind shows is not known here: over pages imported as dma-bufs, the caller's - /// source's dma-buf and the driver's import of it ([`TexturePlacement::InPlace`]); and a - /// making that runs out of memory or meets - /// a lost device fails, as this query may in making those images. The answer is the buffer's - /// and the device's state as the call reads them: a detach, a rebind, or the check's verdicts - /// after it may change what a texture made later takes. A pending verdict starts the device's - /// check, as the making's does - /// ([`Device::settle_in_place_checks`](crate::Device::settle_in_place_checks) says when its - /// verdicts are known). It counts and announces nothing. - pub fn texture_placement( - &self, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - let over = (offset, bytes_per_row); - let asked = (BufferTextureCall::Texture, Whose::Program, Goal::Ask); - self.placement_over("new_texture", descriptor, over, asked, None) - } - - /// Where a texture [`new_tiled_texture`](Self::new_tiled_texture) makes of the same arguments - /// lies if made now, as [`texture_placement`](Self::texture_placement) answers it for - /// [`new_texture`](Self::new_texture): for a texture of more than one level, - /// `Shadow(TextureShadowReason::Mipmapped)` over any buffer, its own copy of the bytes taken at - /// use. Refused as that call refuses its arguments. A runtime extension: Metal has no such - /// query. - pub fn tiled_texture_placement( - &self, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - let over = (offset, bytes_per_row); - let asked = (BufferTextureCall::Tiled, Whose::Program, Goal::Ask); - self.placement_over("new_tiled_texture", descriptor, over, asked, None) - } - - /// Where a texture [`new_texture_with_iosurface_plane`](Self::new_texture_with_iosurface_plane) - /// makes of the same arguments lies if made now, as - /// [`texture_placement`](Self::texture_placement) answers it for - /// [`new_texture`](Self::new_texture), and refused as that call refuses its arguments. A - /// runtime extension: Metal has no such query. - pub fn texture_placement_with_iosurface_plane( - &self, - descriptor: &TextureDescriptor, - plane: IoSurfacePlane, - ) -> Result { - // Its parts held while the call reaches them, across a recovery (`Buffer::held_parts`). - let _held = self.held_parts(); - plane.refuse_client_direction()?; - let over = (plane.offset, plane.bytes_per_row); - let form = BufferTextureCall::IoSurfacePlane { - planar: plane.planar, - }; - let asked = (form, Whose::Program, Goal::Ask); - let call = "new_texture_with_iosurface_plane"; - self.placement_over(call, descriptor, over, asked, plane.ycbcr) - } - - /// The placement [`make_texture_over`](Self::make_texture_over) answers for `asked`, for - /// Metal's `call`. - fn placement_over( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - over: (u64, u64), - asked: (BufferTextureCall, Whose, Goal), - ycbcr_surface: Option, - ) -> Result { - match self.make_texture_over(call, descriptor, over, asked, ycbcr_surface)? { - Over::Asked(placement) => Ok(placement), - Over::Made(_) => Err(internal("a texture's placement made the texture")), - } - } - - /// The texture of `descriptor` over the buffer that `call` (made through `form`) makes, over - /// a surface of `surface`'s YCbCr facts where given, `whose` it is. Over a heap's buffer it is - /// among the heap's textures while it lives: `useHeap:` makes every resource the heap holds - /// resident, so an encoder that used the heap makes it resident (`residency.rs`), and a - /// shadow's texels are copied in for its commands. - fn texture_over( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - offset: u64, - bytes_per_row: u64, - (form, whose): (BufferTextureCall, Whose), - ycbcr_surface: Option, - ) -> Result { - let over = (offset, bytes_per_row); - let made = (form, whose, Goal::Make); - let texture = match self.make_texture_over(call, descriptor, over, made, ycbcr_surface)? { - Over::Made(texture) => texture, - Over::Asked(_) => return Err(internal("a texture's making answered a placement")), - }; - if let Some(heap) = self.heap() { - heap.hold_texture(&texture); - } - if whose == Whose::Runtime { - return Ok(texture); - } - let remake = Remake::Over { - buffer: self.clone(), - call, - descriptor: *descriptor, - offset, - bytes_per_row, - form, - ycbcr: ycbcr_surface, - }; - let device = texture.generation().clone(); - let texture = device.kept_texture(texture, remake); - // Over a no-copy buffer with a read twin, its own read twin, which the slots that only - // read it bind instead (`read_twin.rs`): of a plain texture over its rows. - if form == BufferTextureCall::Texture && ycbcr_surface.is_none() { - self.make_twin_texture(&texture, descriptor, (offset, bytes_per_row)); - } - Ok(texture) - } - - /// The texture over the buffer that `call` made through `form`, of `descriptor` at `over` - /// (its offset and bytes per row), over a surface of `ycbcr_surface`'s facts where given, made - /// again as the runtime's own, which takes no ID: a program's texture over the buffer, on - /// the generation a recovery carried the buffer to (`texture/carry.rs`). - pub(super) fn texture_over_again( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - (offset, bytes_per_row): (u64, u64), - form: BufferTextureCall, - ycbcr_surface: Option, - ) -> Result { - let made = (form, Whose::Runtime); - self.texture_over(call, descriptor, offset, bytes_per_row, made, ycbcr_surface) - } - - /// [`texture_over`](Self::texture_over)'s texture, at `offset` with `bytes_per_row` (`over`), - /// made where `goal` makes it; else where it would lie, answered after every check its making - /// runs before it makes anything ([`texture_placement`](Self::texture_placement)): the - /// texture's shape first, which reads nothing of the buffer but its length, options and - /// whether its bytes are detached ([`shape_over`]). - fn make_texture_over( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - (offset, bytes_per_row): (u64, u64), - (form, whose, goal): (BufferTextureCall, Whose, Goal), - ycbcr_surface: Option, - ) -> Result { - // A detach waits for none being made over the bytes (`detach.rs`), nor does a rebind of - // them while they are detached, so whether they are holds while it is made. A question - // holds nothing: its answer is the bytes' state as it reads them. - let _making = match goal { - Goal::Make => self.making_texture(), - Goal::Ask => None, - }; - let facts = OverFacts { - device: self.generation(), - length: self.length(), - allocation: self.allocation(), - detached: self.detached(), - options: self.resource_options(), - }; - let over = (offset, bytes_per_row); - let shape = shape_over(&facts, call, descriptor, over, form, ycbcr_surface)?; - if goal == Goal::Ask && shape.other() { - return Ok(Over::Asked(TexturePlacement::OtherShape)); - } - let Shape { - descriptor, - layout, - options, - surface, - texel_bytes, - texture, - kind, - } = shape; - let descriptor = &descriptor; - let id_use = whose.id_use(descriptor.placement); - let (placed, alpha_plane, converted) = match kind { - // A rotated texture: its plane holds it turned (`shape_over`). - ShapeKind::Rotated { rotation, stored } => { - let rows = Texels::new( - self.clone(), - rotated_rows(&texture), - texel_bytes, - descriptor, - ); - let stored = Texels::placed(self.clone(), stored, texel_bytes, descriptor); - return self - .generation() - .new_rotated_texture( - call, - [rows, stored] - .map(|texels| texels.with_options(options).over_surface(surface)), - descriptor, - (&layout, rotation), - id_use, - ) - .map(Over::Made); - } - ShapeKind::Apart => { - let made = self - .generation() - .surface_texture_apart(call, descriptor, id_use)?; - self.degrade_apart(&layout, offset, bytes_per_row); - return Ok(Over::Made(made)); - } - ShapeKind::Placed { - placed, - alpha, - converted, - } => (placed, alpha, converted), - }; - if let Some(alpha) = alpha_plane { - let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) - .with_options(options) - .over_surface(surface); - return self - .generation() - .new_surface_planes_texture(call, texels, descriptor, &layout, id_use, alpha) - .map(Over::Made); - } - if let Some((planes, span)) = converted { - let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) - .with_options(options) - .over_surface(surface); - return self - .generation() - .new_converted_texture(call, texels, descriptor, &layout, id_use, (&planes, span)) - .map(Over::Made); - } - if layout.texture_type == TextureType::TextureBuffer { - // Over a surface's plane, of the descriptor's options (`Buffer::new_texture_with_iosurface_plane`): - // its CPU calls at the plane's offset and its functions from the offset rounded down - // to 16 (`into_texture_buffer`), as Metal reads a plane's. - let texels = Texels::new(self.clone(), placed.cpu, texel_bytes, descriptor) - .with_options(options) - .over_surface(surface) - .into_texture_buffer()?; - let tail = surface && texels.tail.is_some(); - let texture = texels.texture(descriptor, &layout, id_use); - if tail { - self.degrade_surface_tail(&layout, &placed); - } - Ok(Over::Made(texture)) - } else { - let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) - .with_options(options) - .over_surface(surface); - // Where it would lie: the route its making takes (`texture/route.rs`), with no tail - // made for texels past those kept in place, which the route asks alone. - if goal == Goal::Ask { - let past = texels.runs_past(); - let asked = (descriptor, &layout); - let bytes = Bytes::Texels(&texels); - let placement = (self.generation()).placement_over(call, bytes, asked, past)?; - return Ok(Over::Asked(placement)); - } - // A 4:2:2 texture is an image of its texels, decoded from the pairs where they lie - // (`texture/surface_pairs.rs`), where they lie so. - if let Some(place) = self.generation().pairs_in_place(&texels, &layout) { - let texture = self - .generation() - .new_pairs_texture(call, texels, descriptor, &layout, id_use, place)?; - if placed.narrow { - self.degrade_narrow_rows(&layout, &placed); - } - return Ok(Over::Made(texture)); - } - // Texels past those kept in place lie in a tail of their own (the module's **Tails**). - let texels = texels.with_tail()?; - let tail = surface && texels.tail.is_some(); - let texture = self - .generation() - .new_texture_over_buffer(call, texels, descriptor, &layout, id_use)?; - if tail { - self.degrade_surface_tail(&layout, &placed); - } - if placed.narrow { - self.degrade_narrow_rows(&layout, &placed); - } - if placed.gpu.shared_bytes() != 0 { - self.degrade_colliding_rows(&layout, &placed); - } - Ok(Over::Made(texture)) - } - } -} - -impl Device { - /// Where a texture [`Buffer::new_texture_with_iosurface_plane`] makes of `descriptor` and - /// `plane` lies if made now over a no-copy buffer of `length` bytes from host address - /// `start`, whose pages the device imports as `backing` says - /// ([`HostBacking::ImportedByPointer`] or [`HostBacking::ImportedAsDmaBuf`]), asked before any - /// such buffer is made: a runtime extension with no Metal counterpart (Metal has no such - /// query, as a Mac's GPU works on a texture over the caller's pages in place). - /// - /// The answer is [`Buffer::texture_placement_with_iosurface_plane`]'s over such a buffer - /// wherever the steps before an import or an image decide it, by the same functions: the - /// texture's shape and the call's refusals (the same errors), [`TexturePlacement::OtherShape`], - /// the device's policy ([`Policy`]), a shader's writes of a texel width the device's check - /// stores none of ([`StoreWidth`]), the check's verdicts for the pages' kind, the texture's - /// accesses and how its texels lie in the device's lines of memory from `start` - /// ([`TexturePlacement::Pending`], [`CheckFailed`], [`Unchecked`]), texels past `length` - /// ([`PastLength`]), rows that share bytes ([`Rows`]), and the refusals the device's format, - /// feature and limit queries give before it makes an image ([`Image`], [`Pitch`], and over - /// dma-bufs [`DmaBuf`]). Where only an image or the import decides (the driver's linear - /// image's layout, a `DRM_FORMAT_MOD_LINEAR` image's plane, their requirements against the - /// import's offset, size and memory type, the source's dma-buf and the driver's import of - /// it), it answers [`TexturePlacement::InPlace`]: the texture made then may be a shadow for - /// one of those, as the query of the buffer once made answers. It makes no buffer, import or - /// image, and binds or submits nothing; a pending verdict starts the device's check, as the - /// making's does ([`Device::settle_in_place_checks`] says when its verdicts are known). The - /// buffer's resource options are not asked: a texture over an IOSurface plane takes its - /// descriptor's. - /// - /// Refused as `new_texture_with_iosurface_plane` refuses its arguments, as - /// `new_buffer_with_bytes_no_copy` refuses `length` (`Nil`, `BufferLength`), and (`Invalid`, - /// `HostPagesBacking`) for another `backing`. - /// - /// [`Policy`]: crate::TextureShadowReason::Policy - /// [`StoreWidth`]: crate::TextureShadowReason::StoreWidth - /// [`CheckFailed`]: crate::TextureShadowReason::CheckFailed - /// [`Unchecked`]: crate::TextureShadowReason::Unchecked - /// [`PastLength`]: crate::TextureShadowReason::PastLength - /// [`Rows`]: crate::InPlaceRefusal::Rows - /// [`Image`]: crate::InPlaceRefusal::Image - /// [`Pitch`]: crate::InPlaceRefusal::Pitch - /// [`DmaBuf`]: crate::InPlaceRefusal::DmaBuf - pub fn host_pages_texture_placement( - &self, - backing: HostBacking, - descriptor: &TextureDescriptor, - plane: IoSurfacePlane, - start: u64, - length: u64, - ) -> Result { - let pages = (backing, start, length); - (self.current()).host_pages_texture_placement_now(pages, descriptor, plane) - } - - /// [`Device::host_pages_texture_placement`] on the generation that serves - /// (`device/line.rs`). - fn host_pages_texture_placement_now( - &self, - (backing, start, length): (HostBacking, u64, u64), - descriptor: &TextureDescriptor, - plane: IoSurfacePlane, - ) -> Result { - const CALL: &str = "new_texture_with_iosurface_plane"; - let (class, memory) = match backing { - HostBacking::ImportedByPointer => (PagesClass::Pointer, ModifierMemory::Host), - HostBacking::ImportedAsDmaBuf => (PagesClass::DmaBuf, ModifierMemory::DmaBuf), - _ => { - let call = "host_pages_texture_placement"; - return Err(invalid(call, Problem::HostPagesBacking)); - } - }; - if length == 0 || length > self.properties().max_buffer_length { - let call = "new_buffer_with_bytes_no_copy"; - return Err(nil(call, Problem::BufferLength { length })); - } - plane.refuse_client_direction()?; - // A no-copy buffer made over the pages: of its length, its bytes in pages from `start`, - // its options never read (an IOSurface plane's texture takes its descriptor's). - let facts = OverFacts { - device: self, - length, - allocation: Allocation::Pages { - page_offset: start % METAL_PAGE, - }, - detached: false, - options: ResourceOptions::default(), - }; - let form = BufferTextureCall::IoSurfacePlane { - planar: plane.planar, - }; - let over = (plane.offset, plane.bytes_per_row); - let shape = shape_over(&facts, CALL, descriptor, over, form, plane.ycbcr)?; - if shape.other() { - return Ok(TexturePlacement::OtherShape); - } - let ShapeKind::Placed { placed, .. } = shape.kind else { - return Err(internal("a texture of another shape over host pages")); - }; - // Its texels as `Texels::placed` lays them out in such a buffer, whose bytes start at - // `start` in the device's lines of memory (`Texels::host_lie`): the buffer declares - // nothing of the bytes between rows (`BufferDescriptor::padding_unobserved`), and its bytes - // lie in their pages. - let gpu = placed.gpu; - let past = past_kept([&gpu, &placed.cpu, &gpu], kept_in(&placed, length)); - let line = self.shared().in_place.line(); - let owned = owns_padding(&gpu, shape.surface, false, length); - let lie = HostLie { - class, - rows: RowEnds::of(start, &gpu, line), - padding: Padding::of(start, &gpu, line, owned).declared(false), - texel: shape.texel_bytes, - detached: false, - caller: None, - }; - let pages = Pages { - lie, - layout: gpu, - memory, - }; - let asked = (&shape.descriptor, &shape.layout); - self.placement_over(CALL, Bytes::Pages(&pages), asked, past) - } -} - -/// What the making of a texture over a buffer's bytes reads of the buffer before its bytes, -/// pages or memory ([`shape_over`]): the generation it is made on, its length, what its -/// allocation is ([`Buffer::allocation`]), whether its bytes are detached (`detach.rs`), and its -/// resource options, which a texture over its bytes takes (an IOSurface plane's takes its -/// descriptor's). A no-copy buffer not made yet has them too -/// (`Device::host_pages_texture_placement`). -struct OverFacts<'a> { - device: &'a Device, - length: u64, - allocation: Allocation, - detached: bool, - options: ResourceOptions, -} - -/// A texture over a buffer's bytes as [`shape_over`] checked it, before anything is made: its -/// descriptor, of the options it takes; its checked layout; those options; whether it is an -/// IOSurface plane's; a texel's bytes; its texels as the buffer lays them out (`texture`, of a -/// packed format's planned units); and which making it takes. -struct Shape { - descriptor: TextureDescriptor, - layout: TextureLayout, - options: ResourceOptions, - surface: bool, - texel_bytes: u64, - texture: BufferTexture, - kind: ShapeKind, -} - -/// Which making a texture over a buffer's bytes takes ([`Shape`]). -enum ShapeKind { - /// Rotated: its plane holds it turned at `rotation`, its stored frame laid out as `stored` - /// (`texture/rotation.rs`). - Rotated { rotation: u8, stored: Placed }, - /// Its texels lie apart from its IOSurface plane, in memory of its own (`linear_plan.rs`'s - /// **Beyond the plane's rows**). - Apart, - /// Laid out in the bytes as `placed`: a texture of a surface's two planes, its alpha plane - /// `alpha` (`texture/surface_two_planes.rs`); a converted one, of the planes and span - /// `converted` (`ycbcr.rs`); a texture buffer; or a 2D texture (or array). - Placed { - placed: Placed, - alpha: Option<[u64; 2]>, - converted: Option<(YCbCrPlanes, Range)>, - }, -} - -impl Shape { - /// Whether no image in place takes a texture of this shape, over any bytes - /// ([`TexturePlacement::OtherShape`]): a rotated texture, one apart from its plane, one of a - /// surface's two planes, a converted one (a 4:2:2 one's an image of its decoded texels, - /// `texture/surface_pairs.rs`) and a texture buffer. - fn other(&self) -> bool { - match &self.kind { - ShapeKind::Rotated { .. } | ShapeKind::Apart => true, - ShapeKind::Placed { - alpha, converted, .. - } => { - alpha.is_some() - || converted.is_some() - || chroma_pairs::is_four_two_two(self.layout.pixel_format) - || self.layout.texture_type == TextureType::TextureBuffer - } - } - } -} - -/// The shape of the texture of `descriptor` over the bytes of a buffer of `facts` that `call` -/// (made through `form`) makes, at `offset` with `bytes_per_row`, over a surface of -/// `ycbcr_surface`'s facts where given: every check its making runs before it reads the buffer's -/// bytes, pages or memory, refused as it refuses them. -fn shape_over( - facts: &OverFacts<'_>, - call: &'static str, - descriptor: &TextureDescriptor, - (offset, bytes_per_row): (u64, u64), - form: BufferTextureCall, - ycbcr_surface: Option, -) -> Result { - // A YCbCr format is made over a surface's planes with their facts (`ycbcr.rs`). - let asked_format = descriptor.pixel_format; - let surface = matches!(form, BufferTextureCall::IoSurfacePlane { .. }); - // A two-plane extended-range format reads the surface's plane 1 from the same facts. - let surface_facts = ycbcr_surface; - let ycbcr_surface = ycbcr_surface.filter(|_| ycbcr(asked_format) && surface); - let device = facts.device; - let asked = device.texture_options(call, descriptor)?; - device.check_texture_placement(call, asked.placement, asked.usage, asked.texture_type)?; - let options = asked.resource_options; - let storage = options.storage_mode()?; - let cache = options.cpu_cache_mode()?; - let hazard = options.hazard_tracking_mode()?; - // A plain `newTextureWithDescriptor:offset:bytesPerRow:` takes the buffer's options - // whatever the descriptor names (probe 9d); an IOSurface plane takes its descriptor's, its - // default hazard tracking mode tracked, as the M4's plain run and validation do - // (the plan refuses a memoryless one). - let options = match form { - BufferTextureCall::IoSurfacePlane { .. } => { - let hazard = match hazard { - HazardTrackingMode::Default => HazardTrackingMode::Tracked, - hazard => hazard, - }; - ResourceOptions::new(storage, cache, hazard) - } - BufferTextureCall::Texture | BufferTextureCall::Linear | BufferTextureCall::Tiled => { - facts.options - } - }; - let descriptor = &TextureDescriptor { - resource_options: options, - ..asked - }; - // A texture buffer of more than one level is stopped by `linear_plan`, as Metal's - // buffer creator stops it, not refused as the device's gap. - let rules = device.properties().texture_rules(); - let checked = match ycbcr_surface { - Some(_) => descriptor.check_over_surface(rules), - None => descriptor.check_made(Creator::Buffer, rules), - }; - // A format of which plain Metal makes no texture alone answers nil over a buffer (the - // linear SPI's too) and, but for a two-plane YCbCr one, over a surface's plane, once every - // rule Metal stops passed and before the buffer's or the surface's own. Metal makes every - // two-plane YCbCr format over a surface's plane (`YCBCR8_420_2P` and `YCBCR10_420_2P` over - // a 'BGRA' surface's); the runtime makes those `ycbcr.rs` reads with the surface's facts, - // and the others are its gap. - let layout = match checked { - Err(Refused::Nil(TextureProblem::NoTextureOfFormat)) - if surface && ycbcr_format(asked_format).is_some() => - { - return Err(Error::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(asked_format), - )); - } - checked => checked.map_err(|refused| refused.error(call))?, - }; - // Only an IOSurface plane takes a framebuffer-only texture: plain Metal asserts - // "framebufferOnly == NO" over a buffer, or on its rotation. - if descriptor.framebuffer_only && !surface { - return Err(invalid( - call, - Problem::Texture(TextureProblem::FramebufferOnly), - )); - } - let buffer = BufferFacts { - length: facts.length, - allocation: facts.allocation, - }; - let planar = matches!(form, BufferTextureCall::IoSurfacePlane { planar: true }); - let converted = match &ycbcr_surface { - Some(facts) => Some(surface_planes( - &layout, - ([offset, bytes_per_row], planar), - facts, - buffer.length, - device, - )?), - None => None, - }; - // Metal makes no render target of a 4:2:0 or 4:2:2 format whose chroma blocks do not - // tile it (an odd width, or an odd height; plain Metal answers nil, the M3 Max under - // macOS 27.0.1), and makes any other. - if let Some((planes, _)) = &converted { - let halved = planes.codes.subsampling.halved() != [false, false]; - let odd = planes.size.iter().any(|n| n % 2 != 0); - if halved && odd && descriptor.usage.contains(TextureUsage::RENDER_TARGET) { - return Err(Refused::Nil(TextureProblem::ExtentForFormat).error(call)); - } - } - // A two-plane extended-range texture over a surface's plane 0 keeps its color words in - // the plane and its alpha bytes in the surface's plane 1 (`texture/surface_two_planes.rs`). - let alpha_plane = match form { - BufferTextureCall::IoSurfacePlane { planar } - if two_planes::holds_planes(layout.pixel_format) => - { - Some(surface_two_planes::alpha_plane( - layout.pixel_format, - planar, - surface_facts, - )?) - } - _ => None, - }; - // A format no buffer backs is Metal's refusal, whatever its Vulkan format, but for a - // 4:2:2 one, which a plain run makes over a buffer (its validation asserts; probe 9 - // `fmt.240`, `fmt.241`) and the runtime holds over none: its textures' carrier - // (`chroma_pairs.rs`) is an image of their own. An IOSurface plane's (a CoreVideo `2vuy` or - // `yuvs` surface's) is made, as Metal makes it, 2 bytes a texel (`linear_plan.rs`), read - // through an image of its texels (`texture/surface_pairs.rs`). - let pf = layout.pixel_format; - let four_two_two = chroma_pairs::is_four_two_two(pf); - // A depth or stencil texture over a surface's plane (`linear_plan.rs` stops every other - // buffer's) keeps one aspect's unit a texel there. - let depth_unit = surface_depth_unit(pf).filter(|_| surface); - let texel_bytes = match (texel_bytes(pf), &converted) { - _ if depth_unit.is_some() => depth_unit.map_or(0, |unit| u64::from(unit.bytes)), - (Some(bytes), _) => bytes, - // Its texels are the luma plane's codes, a code's bytes a texel; packed codes' units - // of three (`ycbcr.rs`). - (None, Some((planes, _))) => u64::from(planes.codes.bytes), - // Its texels are plane 0's color words (`two_planes.rs`). - (None, None) if alpha_plane.is_some() => u64::from(two_planes::UNIT.bytes), - (None, None) if four_two_two && surface => u64::from(chroma_pairs::TEXEL_BYTES), - (None, None) if !is_linear(pf) && !four_two_two => 0, - (None, None) => { - return Err(Error::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - )) - } - }; - // A packed format's luma rows are units of three codes, `⌈w / 3⌉` of them a row: the - // plane is planned as those units. - let planned = match &converted { - Some((planes, _)) if planes.codes.packed => { - let [w, h, d] = layout.extent; - let across = planes.codes.units(u64::from(w)) as u32; - TextureLayout { - extent: [across, h, d], - ..layout - } - } - _ => layout, - }; - let texture = BufferTexture { - layout: planned, - texel_bytes, - storage, - offset, - bytes_per_row, - call: form, - usage: descriptor.usage, - }; - // A rotated texture: its plane holds it turned, as Metal checks it, its CPU access and - // blits address the plane as the texture's own extent at the plane's rows, and its - // functions the stored frame (`texture/rotation.rs`). - // A rotated two-plane YCbCr texture is not measured: the runtime's gap. Nor is a rotated - // two-plane extended-range one over a surface. - if (converted.is_some() || alpha_plane.is_some()) && descriptor.rotation != 0 { - return Err(Error::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - )); - } - // Over detached bytes the runtime makes no rotated texture, nor one of a surface's two - // planes (`stand_in.rs`): a two-plane YCbCr texture's converted texels have no stand-in - // of zero bytes. - let apart = converted.is_some() || alpha_plane.is_some() || descriptor.rotation != 0; - if facts.detached && apart { - return Err(Error::NotImplemented(RuntimeGap::DetachTextures)); - } - let rotation = match u8::try_from(descriptor.rotation) { - Ok(0) => None, - Ok(rotation) => Some(turned_plane(call, &texture, rotation, &buffer)?), - Err(_) => return Err(internal("a rotation past the descriptor's check")), - }; - let shape = |kind| Shape { - descriptor: *descriptor, - layout, - options, - surface, - texel_bytes, - texture, - kind, - }; - if let Some((rotation, stored)) = rotation { - if device.is_lost() { - return Err(device.lost_refusal()); - } - return Ok(shape(ShapeKind::Rotated { rotation, stored })); - } - // A texture over a plane whose texels Metal lays out in no one place, its first level's - // and slice's among them, lies in memory of its own (`linear_plan.rs`'s **Beyond the - // plane's rows**). - if apart_from_plane(&texture) { - if storage == StorageMode::Memoryless { - return Err(Error::NotImplemented(RuntimeGap::MemorylessSurfacePlane)); - } - return Ok(shape(ShapeKind::Apart)); - } - let placed = - plan_buffer_texture(&texture, &buffer).map_err(|refusal| refusal_error(call, refusal))?; - if device.is_lost() { - return Err(device.lost_refusal()); - } - Ok(shape(ShapeKind::Placed { - placed, - alpha: alpha_plane, - converted, - })) -} - -/// The plane of a texture of `rotation` made as `texture` (of a rotated descriptor, over an -/// IOSurface plane): `rotation` and where the turned texels lie, checked as Metal checks them, as -/// a 2D texture of the extent it stores (`rotated::stored_extent`) at the plane's offset and -/// rows, with the pitch held to the texture's own row ([`covers_its_row`]), which the stored -/// extent's plan does not hold it to. Refused as that texture is, and -/// (`NotImplemented(RotatedTexture)`) for a plane whose offset or `bytesPerRow` is off 16 bytes, -/// or a format of a texel size other than 1, 2, 4, 8 or 16 bytes (a 4:2:2 one among them), whose -/// rotation is not measured; and (`NotImplemented(TexelsPastBufferLength)`) for a stored frame -/// past the buffer standing for the surface, whose turned texels are not measured there. -/// -/// A rotated plane's `bytesPerRow` must be a multiple of 16 here, so its GPU rows lie at the -/// pitch itself and never share bytes, which no shadow of a turned frame holds -/// (`linear_plan.rs`'s **Rows that overlap**). -/// -/// It reads nothing of the buffer but its length, so a test reaches every refusal from the -/// input's own shape with no device — which the pitch rule needs, the texture it refuses being -/// one that ends Metal's process. -pub(super) fn turned_plane( - call: &'static str, - texture: &BufferTexture, - rotation: u8, - buffer: &BufferFacts, -) -> Result<(u8, Placed), Error> { - let measured = texture.offset.is_multiple_of(LINEAR_ALIGNMENT) - && texture.bytes_per_row.is_multiple_of(LINEAR_ALIGNMENT) - && [1, 2, 4, 8, 16].contains(&texture.texel_bytes) - && !chroma_pairs::is_four_two_two(texture.layout.pixel_format); - if !measured { - return Err(Error::NotImplemented(RuntimeGap::RotatedTexture)); - } - covers_its_row(texture).map_err(|problem| refusal_error(call, problem.into()))?; - let [width, height, depth] = texture.layout.extent; - let [width, height] = rotated::stored_extent(rotation, [width, height]); - let stored = BufferTexture { - layout: TextureLayout { - extent: [width, height, depth], - ..texture.layout - }, - ..*texture - }; - let placed = - plan_buffer_texture(&stored, buffer).map_err(|refusal| refusal_error(call, refusal))?; - // A stored frame past the buffer standing for the surface has no tail: its turned texels - // are not measured there. - if placed.gpu.end().max(placed.cpu.end()) > buffer.length { - return Err(Error::NotImplemented(RuntimeGap::TexelsPastBufferLength)); - } - Ok((rotation, placed)) -} - -/// Whether `texture`'s `bytesPerRow` covers the **texture's** own packed row, which is Metal's -/// rule for a texture over an IOSurface plane whatever the plane holds and whatever the rotation. -/// -/// Measured on the M3 Max under plain Metal with no validation layer: a 4x8 surface at its own -/// tight stride of 16 behind an 8x4 texture ends the process, -/// `_mtlValidateStrideTextureParameters:1938: failed assertion 'Texture Descriptor Validation -/// IOSurface texture: bytesPerRow (16) must be greater or equal to (32) bytes'` — 32 being the -/// texture's row, 8 texels of 4 bytes, not the plane's 16. A rotated texture's plane holds the -/// turned frame, so a quarter turn's plane row is the shorter of the two and -/// [`plan_buffer_texture`]'s own row check, which runs against the stored extent -/// (`Buffer::turned_plane`), passes a pitch Metal asserts on. This rule is the texture's extent -/// alone, so a test reaches it from the input's own shape with no device — which is the only way -/// it can be tested: building the texture Metal asserts on would end the test process. -fn covers_its_row(texture: &BufferTexture) -> Result<(), BufferTextureProblem> { - let row_bytes = u64::from(texture.layout.extent[0]).saturating_mul(texture.texel_bytes); - match texture.bytes_per_row >= row_bytes { - true => Ok(()), - false => Err(BufferTextureProblem::RowPitch { - bytes_per_row: texture.bytes_per_row, - row_bytes, - }), - } -} - -/// The bytes a rotated texture made as `texture` has its CPU access and blits address: its own -/// extent at the plane's offset and rows, as plain Metal addresses them, which may run past the -/// stored frame's last row. One layout for the GPU and the CPU alike, and its rows never share a -/// byte: [`covers_its_row`] holds the pitch to the texture's own row -/// (`tests::buffer_texture::no_rotated_plane_s_gpu_rows_share_bytes`). -pub(super) fn rotated_rows(texture: &BufferTexture) -> BufferLayout { - let [width, height, _] = texture.layout.extent.map(u64::from); - BufferLayout { - offset: texture.offset, - row_pitch: texture.bytes_per_row, - slice_pitch: texture.bytes_per_row.saturating_mul(height), - row_bytes: width.saturating_mul(texture.texel_bytes), - rows: height, - slices: 1, - } -} - -impl Buffer { - /// What holds the buffer's bytes, as Metal's bound on a texture over it reads it - /// (`linear_plan.rs`'s **Length**): a heap's buffer its heap's size; a no-copy buffer (in its - /// pages, copied, two copies or detached) its pointer's offset in its 16 KiB page, which - /// [`contents`](Buffer::contents) answers in every form; any other its own memory. - fn allocation(&self) -> Allocation { - if let Some(heap) = self.heap() { - return Allocation::Heap { size: heap.size() }; - } - match (self.host_backing(), self.contents()) { - (Some(_), Some(pointer)) => Allocation::Pages { - page_offset: pointer.as_ptr() as u64 % METAL_PAGE, - }, - _ => Allocation::Own, - } - } - - /// Announce `NarrowSurfaceRows` for an IOSurface plane of `layout` placed as `placed`, once - /// it is made (`linear_plan.rs`). - fn degrade_narrow_rows(&self, layout: &TextureLayout, placed: &Placed) { - self.generation() - .degrade(Degradation::NarrowSurfaceRows, || { - let [width, height, _] = layout.extent; - let object = format!( - "{width}x{height} {:?} texture of an IOSurface plane at offset {}, {} bytes a row", - layout.pixel_format, placed.cpu.offset, placed.cpu.row_pitch - ); - let reason = format!( - "Metal's GPU writes its rows {} bytes apart from byte {} and reads every row past \ - the first as memory-dependent bytes", - placed.gpu.row_pitch, placed.gpu.offset - ); - (object, reason) - }); - } - - /// Announce `SurfaceTexelsApart` for a texture of `layout` over the IOSurface plane at `offset`, - /// `bytes_per_row` a row, made in memory of its own (`linear_plan.rs`'s **Beyond the plane's - /// rows**). - fn degrade_apart(&self, layout: &TextureLayout, offset: u64, bytes_per_row: u64) { - self.generation() - .degrade(Degradation::SurfaceTexelsApart, || { - let [width, height, depth] = layout.extent; - let object = format!( - "{width}x{height}x{depth} {:?} {:?} texture of {} levels and {} samples over an \ - IOSurface plane at offset {offset}, {bytes_per_row} bytes a row", - layout.texture_type, layout.pixel_format, layout.levels, layout.samples - ); - let reason = - "Metal lays such a texture's texels over a plane in no one place, its \ - first level's and slice's among them: its GPU reads them from other \ - bytes than its writes and its CPU put them" - .to_owned(); - (object, reason) - }); - } - - /// Announce `SurfaceTexelsTail` for an IOSurface plane of `layout` placed as `placed`, whose - /// texels run past the buffer standing for its surface, or a 2D array's slices past its - /// first, into the texture's tail, once it is made (`linear_plan.rs`'s **Beyond the plane's - /// rows**). - fn degrade_surface_tail(&self, layout: &TextureLayout, placed: &Placed) { - self.generation() - .degrade(Degradation::SurfaceTexelsTail, || { - let [width, height, _] = layout.extent; - let slices = match layout.layers { - 1 => String::new(), - layers => format!(" of {layers} slices"), - }; - let object = format!( - "{width}x{height} {:?} texture{slices} of an IOSurface plane at offset {}, {} \ - bytes a row", - layout.pixel_format, placed.cpu.offset, placed.cpu.row_pitch - ); - let end = placed.gpu.end().max(placed.cpu.end()); - let reason = match placed.kept { - Some(kept) => format!( - "Metal lays its slices past the first in no one place: they lie from byte \ - {kept} of the buffer's space on, in the tail" - ), - None => format!( - "its texels run to byte {end} of the {} bytes standing for its surface, and \ - Metal lays those past the surface in no one place", - self.length() - ), - }; - (object, reason) - }); - } - - /// Announce `CollidingSurfaceRowWrites` for an IOSurface plane of `layout` placed as `placed`, - /// whose GPU rows share bytes, once it is made (`linear_plan.rs`'s **Rows that overlap**). - fn degrade_colliding_rows(&self, layout: &TextureLayout, placed: &Placed) { - self.generation() - .degrade(Degradation::CollidingSurfaceRowWrites, || { - let [width, height, _] = layout.extent; - let object = format!( - "{width}x{height} {:?} texture of an IOSurface plane at offset {}, {} bytes a \ - row", - layout.pixel_format, placed.cpu.offset, placed.cpu.row_pitch - ); - let reason = format!( - "Metal's GPU reads and writes its rows {} bytes apart from byte {}, {} bytes \ - of texels each, so consecutive rows share {} bytes, and which row's writes \ - stand there depends on the order Metal writes them in", - placed.gpu.row_pitch, - placed.gpu.offset, - placed.gpu.row_bytes, - placed.gpu.shared_bytes(), - ); - (object, reason) - }); - } -} - -impl Texture { - /// The texture a render pass renders into for this texture buffer (or view of one), as an - /// attachment or a resolve target: a 2D texture of one row in the texture's pixel format - /// over the same bytes of the same buffer, with an aliasing image or a shadow the encoder - /// copies in and back (`render/shadows.rs`), made at the first pass that needs it and kept with - /// the texels. Metal renders into a texture buffer plain, its texels the buffer's bytes and the - /// bytes around them untouched (a probe, an M3 Max and an M4: `tb_device`, `tb_over_buffer`, - /// `tb_over_buffer_load`, `tb_view_r32uint`, `tb_resolve`); its API validation stops a texture - /// buffer made with render target usage ("MTLTextureUsageRenderTarget is not valid for a - /// texture buffer"). - /// - /// Refused `NotImplemented(Render)` past the device's largest framebuffer width, where Metal - /// fails the command buffer (`tb_wide`, 20000 texels: an internal error), and for a texture - /// buffer at an offset off 16 bytes, whose rendering is not measured (its functions read and - /// write from the offset rounded down, its blits at the offset); otherwise as a 2D texture over - /// a buffer is. - pub(super) fn attachment_twin(&self) -> Result { - const CALL: &str = "render_command_encoder"; - let texels = self - .texels() - .ok_or_else(|| internal("an attachment twin of a texture with an image"))?; - let record = self.record(); - let pixel_format = record.pixel_format; - texels.twin(pixel_format, || { - let device = texels.buffer.generation(); - let width = u64::from(record.extent()[0]); - let unmeasured = !texels.layout.offset.is_multiple_of(LINEAR_ALIGNMENT); - if width > u64::from(device.shared().max_framebuffer[0]) || unmeasured { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - let mut descriptor = TextureDescriptor::texture_2d(pixel_format, width, 1, false); - descriptor.usage = TextureUsage::RENDER_TARGET; - descriptor.resource_options = texels.options; - descriptor.allow_gpu_optimized_contents = texels.allow_gpu_optimized_contents; - let layout = descriptor - .check(device.properties().texture_rules()) - .map_err(|refused| refused.error(CALL))?; - let row_bytes = width.saturating_mul(texels.texel_bytes); - let placed = BufferLayout { - offset: texels.layout.offset, - row_pitch: row_bytes, - slice_pitch: row_bytes, - row_bytes, - rows: 1, - slices: 1, - }; - let over = Texels::new( - texels.buffer.clone(), - placed, - texels.texel_bytes, - &descriptor, - ) - .with_options(texels.options) - .over_surface(texels.surface); - device.new_texture_over_buffer(CALL, over, &descriptor, &layout, IdUse::Runtime) - }) - } -} - -impl Device { - /// `newTextureWithDescriptor:` of a texture buffer (`layout`, checked from `descriptor`): a - /// texture buffer over a new buffer of the descriptor's options, as long as its texels; - /// `newSharedTextureWithDescriptor:` of one where `home` is `Shared`. - /// - /// A `Memoryless` descriptor, of which plain Metal makes a texture (an Apple M3 Max under - /// macOS 27.0.1: a 64-texel `RGBA8Unorm` texture buffer of `ShaderRead` usage answers - /// `storageMode` 3, its other getters its descriptor's), lies over a `Private` buffer: no - /// Vulkan buffer takes memory lazily. The texture answers the descriptor's mode, and its uses - /// are a memoryless texture's (`texture.rs`): a command that uses it fails its command - /// buffer, as plain Metal's (a dispatch that reads it and a blit out of it, measured), its - /// views are nil, and its CPU access, at which plain Metal's process faults, is refused. - /// Announced `memoryless-texture-buffer`: the bytes are memory Metal spends none of. - pub(super) fn new_texture_buffer( - &self, - descriptor: &TextureDescriptor, - layout: &TextureLayout, - id_use: IdUse, - home: TexelsHome, - ) -> Result { - let row_bytes = texture_buffer_bytes(layout)?; - let options = descriptor.resource_options; - let bytes = match options.storage_mode()? { - StorageMode::Memoryless => { - self.degrade(Degradation::MemorylessTextureBuffer, || { - let object = format!( - "a memoryless {:?} texture buffer of {} texels", - layout.pixel_format, layout.extent[0] - ); - let why = format!("a Private buffer of its {row_bytes} bytes of texels"); - (object, why) - }); - options.with_storage_mode(StorageMode::Private) - } - _ => options, - }; - // Metal shows no address of a texture's texels: they lie outside the space (`address.rs`). - let buffer = self.new_buffer_placed(row_bytes, bytes, AddressPlacement::Outside)?; - texture_buffer_over(buffer, descriptor, layout, id_use, home) - } -} - -/// The bytes of one texel of a texture buffer of `layout`, over a buffer of its own (a device's, -/// a shareable texture's or a heap's). Refused (`Unsupported`) for a format without a texel -/// size, which no texture buffer has. -fn texture_buffer_texel(layout: &TextureLayout) -> Result { - texel_bytes(layout.pixel_format).ok_or(Error::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(layout.pixel_format), - )) -} - -/// The bytes of a texture buffer of `layout`: its row of texels. Refused as -/// `texture_buffer_texel` refuses the format. -pub(super) fn texture_buffer_bytes(layout: &TextureLayout) -> Result { - Ok(u64::from(layout.extent[0]) * texture_buffer_texel(layout)?) -} - -/// The texture buffer of `descriptor` (checked as `layout`) over the first bytes of `buffer`, as -/// many as `texture_buffer_bytes` answers, its ID as `id_use` says; `home` made `buffer` for it. -/// Refused as `new_buffer` refuses the texels' staging buffer. -pub(super) fn texture_buffer_over( - buffer: Buffer, - descriptor: &TextureDescriptor, - layout: &TextureLayout, - id_use: IdUse, - home: TexelsHome, -) -> Result { - let texel_bytes = texture_buffer_texel(layout)?; - let row_bytes = u64::from(layout.extent[0]) * texel_bytes; - let placed = BufferLayout { - offset: 0, - row_pitch: row_bytes, - slice_pitch: row_bytes, - row_bytes, - rows: 1, - slices: 1, - }; - let mut texels = Texels::new(buffer, placed, texel_bytes, descriptor).into_texture_buffer()?; - texels.home = home; - // A memoryless texture buffer lies over a `Private` buffer (`Device::new_texture_buffer`) and - // answers `Memoryless`, as Metal's does, with the CPU cache and hazard tracking modes the - // buffer resolved: Metal resolves a texture buffer's default tracking to tracked (an M3 Max - // answers `hazardTrackingMode` 2 for a memoryless one). Every other texture buffer takes its - // buffer's options whole, which `Buffer::new_texture` has already made the descriptor's. - if descriptor.resource_options.storage_mode()? == StorageMode::Memoryless { - let options = texels.options.with_storage_mode(StorageMode::Memoryless); - texels = texels.with_options(options); - } - Ok(texels.texture(descriptor, layout, id_use)) -} - -impl Texels { - /// The generation the texels' views are of: that of the texture's parts that hold them, made - /// where the buffer's reach took its parts (`texture/carry.rs`). - pub(super) fn generation(&self) -> &Device { - &self.views.device - } - - /// The texels of a texture of `descriptor` that `placed` lays out in `buffer`, `texel_bytes` - /// each: for the GPU at its GPU layout, for the CPU at its CPU one. - fn placed( - buffer: Buffer, - placed: Placed, - texel_bytes: u64, - descriptor: &TextureDescriptor, - ) -> Texels { - let mut texels = Texels::new(buffer, placed.gpu, texel_bytes, descriptor); - texels.cpu = placed.cpu; - texels.kept = kept_in(&placed, texels.kept); - texels - } - - /// The texels a rotated texture's render passes turn theirs into, these being the texels of - /// its other uses (`width` by `height` of a 2D texture at its plane's offset and rows): the - /// plane's rows from the same offset, of the extent Metal stores the texture as at - /// `rotation`. Both lie on one layout for the GPU and the CPU (the plane's offset and rows - /// are multiples of 16 bytes, `Buffer::turned_plane`). - pub(super) fn turned(&self, rotation: u8, [width, height]: [u32; 2]) -> Texels { - let [width, height] = rotated::stored_extent(rotation, [width, height]); - let row_bytes = u64::from(width) * self.texel_bytes; - let layout = BufferLayout { - row_bytes, - rows: u64::from(height), - slice_pitch: self.layout.row_pitch * u64::from(height), - ..self.layout - }; - let descriptor = TextureDescriptor { - allow_gpu_optimized_contents: self.allow_gpu_optimized_contents, - ..TextureDescriptor::default() - }; - Texels::new(self.buffer.clone(), layout, self.texel_bytes, &descriptor) - .with_options(self.options) - .over_surface(self.surface) - } - - /// These texels' buffer's bytes `span` as one row of `unit`-byte texels, of these texels' - /// options: a depth or stencil texture's tiled twin's (`texture/surface_depth.rs`), whose - /// bytes are Metal's tiles there. - pub(super) fn tiled_span(&self, span: std::ops::Range, unit: u64) -> Texels { - let bytes = span.end - span.start; - let layout = BufferLayout { - offset: span.start, - row_pitch: bytes, - slice_pitch: bytes, - row_bytes: bytes, - rows: 1, - slices: 1, - }; - let descriptor = TextureDescriptor { - allow_gpu_optimized_contents: self.allow_gpu_optimized_contents, - ..TextureDescriptor::default() - }; - Texels::new(self.buffer.clone(), layout, unit, &descriptor) - .with_options(self.options) - .over_surface(self.surface) - } - - /// The attachment twin of `pixel_format` kept with the texels (a texture buffer's, or a - /// rotated texture's), made by `make` at the first pass that needs it, with the twins' - /// lock not held: a twin over dma-buf pages calls the program's source (`dma_buf.rs`). Where - /// another pass made one meanwhile, that one is kept and `make`'s goes, with no lock held. - pub(super) fn twin( - &self, - pixel_format: PixelFormat, - make: impl FnOnce() -> Result, - ) -> Result { - if let Some(twin) = lock(&self.twins).get(&pixel_format) { - return Ok(twin.clone()); - } - let made = make()?; - let kept = (lock(&self.twins).entry(pixel_format)) - .or_insert_with(|| made.clone()) - .clone(); - Ok(kept) - } - - /// The copies of a rotated texture's image of its pass's frame (`image` of `identity`, of - /// `extent`) over these texels, the plane's rows that hold it turned at `rotation` - /// (`rotated.rs`): through a staging buffer of their bytes and the rotation kernel. Refused - /// as `RotatedCopies::new` refuses them. - pub(super) fn rotated_copies( - &self, - image: vk::Image, - identity: Identity, - rotation: u8, - extent: [u32; 2], - ) -> Result { - let layout = &self.layout; - let (buffer, at) = self.buffer.at_for(layout.offset, ReadApart::Texture); - let staging = self.staging(layout, at)?; - let frame = Frame { - rotation, - extent, - texel_bytes: self.texel_bytes, - row_pitch: layout.row_pitch, - span: layout.end() - layout.offset, - }; - let hazard = self.options.hazard_tracking_mode()?; - let turn = Box::new(RotatedCopies::new( - self.buffer.generation(), - &staging, - frame, - hazard, - )?); - let (bytes, tracked) = self.buffer.tracked(layout.offset..layout.end()); - Ok(ShadowCopies { - source: ShadowSource::Bytes { - buffer: ShadowBuffer::of(&self.buffer, buffer), - key: bytes.key, - bytes: tracked, - target: ShadowTarget::Rotated { - image, - staging, - turn, - }, - alias: self.buffer.alias().map(|alias| alias.key), - }, - shadow_key: identity.key, - shadow_range: UseRange::Image { - aspects: vk::ImageAspectFlags::COLOR, - levels: 0..1, - layers: 0..1, - place: ImagePlace::WHOLE, - }, - tracked: self.tracked(), - drops_writes: false, - levels: None, - decode: Default::default(), - backing: self.backing(), - merge_scratch: ScratchSpares::default(), - stood: AtomicU64::new(0), - standing: Default::default(), - }) - } - - /// The bytes of one texel. - pub(super) fn texel_bytes(&self) -> u64 { - self.texel_bytes - } - - /// Over a copied host buffer (`copied.rs`), how the texels lie in the device's lines of memory - /// of `line` bytes over the caller's pages themselves, from their address - /// (`in_place::RowEnds::of`), and whether a shader's writes may change their rows' padding - /// there (`in_place::Padding::of`): as [`rows`](Self::rows) and [`padding`](Self::padding) - /// answer them over an import of the pages, which the buffer's rebind may make, where - /// [`rows`](Self::rows) answers them in its copy. `None` over any other buffer. - pub(super) fn over_caller_pages(&self, line: u64) -> Option<(RowEnds, Padding)> { - if !self.buffer.copied() { - return None; - } - let start = self.buffer.mapped_contents()?.as_ptr().addr() as u64; - let padding = Padding::of(start, &self.layout, line, self.padding_owned()); - Some(( - RowEnds::of(start, &self.layout, line), - padding.declared(self.buffer.padding_unobserved()), - )) - } - - /// How the texels lie over host pages of `class`, in the device's lines of memory of `line` - /// bytes, as the route of a texture over them takes it ([`HostLie`]): their row ends - /// ([`rows`](Self::rows)), their rows' padding ([`padding`](Self::padding)), a texel's bytes, - /// whether their bytes were detached, and over a copied host buffer how they lie over the - /// caller's pages ([`over_caller_pages`](Self::over_caller_pages)). - pub(super) fn host_lie(&self, class: PagesClass, line: u64) -> HostLie { - HostLie { - class, - rows: self.rows(line), - padding: self.padding(line), - texel: self.texel_bytes, - detached: self.buffer.detached(), - caller: self.over_caller_pages(line), - } - } - - /// Whether the texels' buffer is a copied host buffer (`copied.rs`) whose copy lies in fresh - /// pages the runtime mapped and imported by their pointer (`fresh_pages.rs`), not in memory - /// the device allocates. - pub(super) fn copy_in_fresh_pages(&self) -> bool { - self.buffer.copied() - && (self.buffer.host_pages()).is_some_and(|pages| pages.over_own_pages()) - } - - /// Where the buffer's bytes start, for the device's lines of memory: their address, where the - /// CPU addresses them; else, in the runtime's own memory (a `Private` buffer's, or a copied - /// host buffer's copy, which the GPU uses in the stead of the caller's pages, `copied.rs`), - /// their offset in its memory object, from whose start the lines count (a - /// `VkMappedMemoryRange`'s offset is a multiple of `nonCoherentAtomSize` from it, and the - /// runtime maps a block from its start); `None` over the caller's `VkBuffer`. - fn line_start(&self) -> Option { - if self.buffer.copied() { - return Some(self.buffer.memory().1); - } - match self.buffer.mapped_contents() { - Some(at) => Some(at.as_ptr().addr() as u64), - None if self.buffer.caller_memory().is_none() => Some(self.buffer.memory().1), - None => None, - } - } - - /// How the texels lie in the device's lines of memory of `line` bytes - /// (`in_place::RowEnds::of`): from where the buffer's bytes start in them - /// ([`line_start`](Self::line_start)) and where the GPU's commands find the texels - /// (`layout`). Over the caller's `VkBuffer` they share a line as far as anything shows. - pub(super) fn rows(&self, line: u64) -> RowEnds { - match self.line_start() { - Some(start) => RowEnds::of(start, &self.layout, line), - None => RowEnds::InLines, - } - } - - /// Whether a shader's writes may change the texels' rows' padding, in the device's lines of - /// memory of `line` bytes (`in_place::Padding::of`): rows over a buffer's bytes of the CPU's - /// or the runtime's memory ([`line_start`](Self::line_start)) whose padding is the buffer's - /// own ([`Texels::padding_owned`]: an IOSurface plane's only where the buffer declares it - /// unobserved), whose rows, each to its pitch, share no line with bytes past them; and a - /// render pass's too, where the buffer declares that padding unobserved - /// (`in_place::Padding::Unobserved`, `BufferDescriptor::padding_unobserved`). - pub(super) fn padding(&self, line: u64) -> Padding { - match self.line_start() { - Some(start) => { - let padding = Padding::of(start, &self.layout, line, self.padding_owned()); - padding.declared(self.buffer.padding_unobserved()) - } - None => Padding::Kept, - } - } - - /// Whether the texels' rows' padding is their buffer's own (`in_place::Padding`): the buffer - /// holds their last row to its pitch, and they lie over a buffer's rows, or over an IOSurface - /// plane's where the buffer declares the bytes between a texture's rows unobserved - /// (`BufferDescriptor::padding_unobserved`). Metal keeps a plane's padding under every - /// command, but bytes its maker declares nothing reads cannot tell keeping from changing; - /// without the declaration a plane's padding is kept. - pub(super) fn padding_owned(&self) -> bool { - let unobserved = self.buffer.padding_unobserved(); - owns_padding(&self.layout, self.surface, unobserved, self.kept) - } - - /// The texture's resource options (the `options` field), its hazard tracking mode resolved. - pub(super) fn options(&self) -> ResourceOptions { - self.options - } - - /// Whether the texture's uses are tracked: its own hazard tracking mode, the buffer's but for - /// an IOSurface plane's (whose descriptor's Metal takes). A use of the texels keys on the - /// buffer's bytes whatever the mode, so a tracked texture's uses order against the buffer's - /// tracked uses, and an untracked texture's are the program's to order, as Metal's. - pub(super) fn tracked(&self) -> bool { - self.options.hazard_tracking_mode().ok() == Some(HazardTrackingMode::Tracked) - } - - /// These texels as a texture of `options` (its hazard tracking mode resolved) has them. - fn with_options(self, options: ResourceOptions) -> Texels { - Texels { options, ..self } - } - - /// These texels, in an IOSurface's plane where `surface`: their bytes in place end at the - /// buffer's length, past which a plane's lie in its tail whatever the buffer's memory holds - /// (`linear_plan.rs`'s **Beyond the plane's rows**). - fn over_surface(self, surface: bool) -> Texels { - let kept = match surface { - true => self.kept.min(self.buffer.length()), - false => self.kept, - }; - Texels { - surface, - kept, - ..self - } - } - - /// Where the texels' bytes in place end, in bytes of the buffer's space ([`Texels::kept`]): - /// those from here lie in their tail. - pub(super) fn kept(&self) -> u64 { - self.kept - } - - /// Every byte of the buffer the texels lie in, for the GPU or the CPU: from the first to the - /// last of either layout, and of the alpha plane where the texels have one. - pub(super) fn span(&self) -> std::ops::Range { - let (gpu, cpu, shader) = (&self.layout, &self.cpu, &self.shader); - let start = gpu.offset.min(cpu.offset).min(shader.offset); - let end = gpu.end().max(cpu.end()).max(shader.end()); - match &self.alpha { - Some(alpha) => start.min(alpha.offset)..end.max(alpha.end()), - None => start..end, - } - } - - /// Whether the texels lie in the buffer's memory, or past it in their tail (the module's - /// **Tails**): every texture's but a rotated one's whose rows run past it (`rotated_rows`). - pub(super) fn reached(&self) -> bool { - self.tail.is_some() || self.span().end <= self.kept - } - - /// Whether Metal's GPU reads and writes two of the texels' rows over bytes they share: an - /// IOSurface plane's at its pitch rounded down to 16, or wider than its pitch, the shapes - /// that do ([`plane_rows_share_bytes`]). The shadow's copies hold the sharing - /// ([`plane_copy_regions`]); a blit that would write the rows as bytes does not and is refused - /// instead, as is a copy between them and an image texture either way, while a blit that reads - /// them into a buffer is served: a write must settle which of two rows leaves the shared bytes - /// behind and Metal settles it no one way, while a read settles nothing (`blit_texture.rs`). - pub(super) fn plane_rows_overlap(&self) -> bool { - plane_rows_share_bytes(&self.layout) - } - - /// The texels of a texture of `descriptor` at `placed` in `buffer`, `texel_bytes` each. - fn new( - buffer: Buffer, - placed: BufferLayout, - texel_bytes: u64, - descriptor: &TextureDescriptor, - ) -> Texels { - let views = Arc::new(TexelViews { - device: buffer.generation().clone(), - views: Mutex::new(KeyMap::default()), - }); - // A rebind of the buffer's host pages empties the views (`rebind.rs`). - buffer.watch_views(&views); - // The descriptor's checks bound a texture's extent to `u32`s. - let blocks = block_extent(descriptor.pixel_format).map(|extent| Blocks { - extent, - texels: [descriptor.width as u32, descriptor.height as u32], - }); - Texels { - layout: placed, - cpu: placed, - shader: placed, - texel_bytes, - blocks, - allow_gpu_optimized_contents: descriptor.allow_gpu_optimized_contents, - options: buffer.resource_options(), - views, - staged: None, - home: TexelsHome::Buffer, - twins: Mutex::new(HashMap::new()), - alpha: None, - objects: ObjectsToken::default(), - surface: false, - tail: None, - kept: buffer.texel_reach(), - buffer, - } - } - - /// These texels with their tail where they run past the bytes they keep in place (the - /// buffer's length, or a 2D array's second slice, [`Texels::kept`]), made as - /// [`Device::own_buffer`] makes a buffer: all zero. - fn with_tail(self) -> Result { - if !self.runs_past() { - return Ok(self); - } - let end = self.layout.end().max(self.cpu.end()).max(self.shader.end()); - let hazard = self.options.hazard_tracking_mode()?; - let options = ResourceOptions::new(StorageMode::Shared, CpuCacheMode::DefaultCache, hazard); - let span = end - self.tail_base(); - let tail = (self.buffer.generation()).own_buffer(span.next_multiple_of(4), options)?; - Ok(Texels { - tail: Some(tail), - ..self - }) - } - - /// Whether the texels run past the bytes they keep in place (the buffer's length, or a 2D - /// array's second slice, [`Texels::kept`]): where [`with_tail`](Self::with_tail) gives them a - /// tail. - pub(super) fn runs_past(&self) -> bool { - past_kept([&self.layout, &self.cpu, &self.shader], self.kept) - } - - /// Where the texels' bytes past the buffer's length lie, where they run past it: from the - /// buffer's length on (a 2D array's second slice on, [`Texels::kept`]), each byte `v` of the - /// buffer's space at `v - rebase` of the tail. - pub(super) fn past(&self) -> Option> { - self.tail.as_ref().map(|tail| Past { - tail, - length: self.kept, - rebase: self.tail_base(), - }) - } - - /// The byte of the buffer's space the tail's first byte stands for: the texels' first, as - /// the GPU, the CPU or a function lays them out (a texture buffer's functions read it from its - /// offset rounded down to 16 bytes, `into_texture_buffer`). - fn tail_base(&self) -> u64 { - self.layout - .offset - .min(self.cpu.offset) - .min(self.shader.offset) - } - - /// What holds the texels' bytes, as the CPU may write them (`shadow::Backing`). - pub(super) fn backing(&self) -> Backing { - Backing::of(&self.buffer, self.surface) - } - - /// Where the CPU's `replace_region` and `get_bytes` find the texels. - pub(super) fn cpu_layout(&self) -> BufferLayout { - self.cpu - } - - /// The texels' two layouts, `(gpu, cpu)`: where Metal's GPU finds them and where the CPU does - /// (`linear_plan::Placed`), which together say whether its rows share bytes - /// ([`plane_rows_share_bytes`]). A row copy of the texels as the buffer's bytes takes both - /// (`blit_plan::plan_texels_rows_copy`). - pub(super) fn row_layouts(&self) -> (&BufferLayout, &BufferLayout) { - (&self.layout, &self.cpu) - } - - /// The alpha plane of a two-plane extended-range texture over a surface's plane 0, where - /// Metal's GPU finds it (`texture/surface_two_planes.rs`); `None` for every other texture. - pub(super) fn alpha(&self) -> Option<&BufferLayout> { - self.alpha.as_ref() - } - - /// These texels with the alpha plane `alpha` (a two-plane extended-range texture's over a - /// surface's plane 0, `texture/surface_two_planes.rs`). - pub(super) fn with_alpha(self, alpha: BufferLayout) -> Texels { - Texels { - alpha: Some(alpha), - ..self - } - } - - /// These texels as a texture buffer's, of their options and surface. A function reads and - /// writes them from their offset rounded down to 16 bytes, as - /// plain Metal's do where its validation alone stops an offset off 16 (an M4 under macOS - /// 27.0.1), and blits and the CPU at the offset itself (`layout`). Viewed in place where the - /// device's `minTexelBufferOffsetAlignment`, which the binding plan holds a view's offset to, - /// divides the functions' offset in the buffer's `VkBuffer`; else through a staging buffer of - /// their own, at its start (a no-copy buffer's bytes, or Metal's offset, need not lie at a - /// multiple of it), and through their tail where they run past the bytes they keep in place - /// ([`Texels::kept`]), which no view of the buffer reaches. Refused as `new_buffer` refuses - /// the staging buffer. - fn into_texture_buffer(self) -> Result { - let mut texels = self; - let placed = texels.layout; - texels.shader = BufferLayout { - offset: placed.offset - placed.offset % LINEAR_ALIGNMENT, - ..placed - }; - // Texels past those kept in place lie in a tail of their own (the module's **Tails**), - // which their bindings view, as a staging buffer's: no view of the buffer reaches them. - let mut texels = texels.with_tail()?; - let (raw, at) = (texels.buffer).at_for(texels.shader.offset, ReadApart::Texture); - let device = texels.buffer.generation(); - let limits = device.compile_device().profile().limits(); - let past = texels.tail.is_some(); - if !past && at.is_multiple_of(limits.min_texel_buffer_offset_alignment.max(1)) { - return Ok(texels); - } - let staging = texels.staging(&texels.shader, at)?; - let layout = &texels.shader; - let shadow = staging.buffer.identity(); - let (bytes, tracked) = texels.buffer.tracked(layout.offset..layout.end()); - // Every byte of the texels' its bindings view, those past the length among them. - let shadow_range = UseRange::Bytes(0..layout.end() - layout.offset); - let copies = ShadowCopies { - source: ShadowSource::Bytes { - buffer: ShadowBuffer::of(&texels.buffer, raw), - key: bytes.key, - bytes: tracked, - target: ShadowTarget::Buffer(staging), - alias: texels.buffer.alias().map(|alias| alias.key), - }, - shadow_key: shadow.key, - shadow_range, - tracked: texels.tracked(), - drops_writes: false, - levels: None, - decode: Default::default(), - backing: texels.backing(), - merge_scratch: ScratchSpares::default(), - stood: AtomicU64::new(0), - standing: Default::default(), - }; - texels.staged = Some(Arc::new(copies)); - let (offset, alignment) = ( - texels.layout.offset, - limits.min_texel_buffer_offset_alignment, - ); - let kept = texels.kept; - texels - .buffer - .generation() - .degrade(Degradation::StagedTextureBuffer, || { - let object = format!("texture buffer over a buffer at offset {offset}"); - let reason = match past { - true => format!( - "its texels run past byte {kept} of the buffer, where its memory ends for \ - them and no view of the buffer's VkBuffer reaches: those lie in a tail of \ - the texture's own" - ), - false => format!( - "its texels start at byte {at} of the buffer's VkBuffer, and the device \ - views texels only at multiples of {alignment} bytes \ - (minTexelBufferOffsetAlignment)" - ), - }; - (object, reason) - }); - Ok(texels) - } - - /// A texture buffer's staging copies, where its bindings view a staging buffer. - pub(super) fn staged(&self) -> Option<&Arc> { - self.staged.as_ref() - } - - /// The `VkBuffer` the texels' bindings view, and the texels' offset in it. - fn viewed(&self) -> (vk::Buffer, u64) { - match self.staged.as_deref().and_then(ShadowCopies::target) { - Some(ShadowTarget::Buffer(staging)) => (staging.raw(), staging.into.dst_offset), - _ => (self.buffer).at_for(self.shader.offset, ReadApart::Texture), - } - } - - /// The texture buffer of `descriptor` (checked as `layout`) these texels are, its ID as - /// `id_use` says. - fn texture( - self, - descriptor: &TextureDescriptor, - layout: &TextureLayout, - id_use: IdUse, - ) -> Texture { - let record = ViewRecord::of_descriptor(layout, descriptor); - Texture::of_texels(self, record, id_use) - } - - /// The copies of a shadowed texture over the texels (`shadow.rs`), whose image is `image` - /// of `identity`, with `aspects`: one region per slice, the slice's rows of texels. Where - /// the texels start in the buffer's `VkBuffer` at an offset that is not a multiple of their - /// size, which Vulkan copies texels at (a no-copy buffer's bytes need not start at one), the - /// copies go through a staging buffer of the texture's ([`ShadowStaging`]). Its copies back - /// dispatch through `words`, its image's integer view, where given and its one slice is - /// copied in place (`shadow_copy_back.rs`), and its merges read the texels through `unorm`, - /// its image's view of its own 8-bit unsigned normalized format, where given so - /// (`shadow_merge.rs`). Refused as `new_buffer` refuses the staging buffer. - /// Whether these texels take a device copy on `device` (`texture.rs`, `dirty_pages.rs`): on - /// a discrete GPU, a `Managed` texture over a buffer's bytes (not an IOSurface plane's), - /// tracked, over host pages whose memory carries a log, where the shadow's copy in is one - /// region straight from the texels' place in the buffer's `VkBuffer` (one slice, rows that - /// share no bytes, a first texel at a multiple of the texel's size there), the copy in a log - /// decides. A `Managed` resource on a Mac with a discrete GPU is two copies, the system - /// memory's and the GPU's own; a `Shared` texture and an IOSurface's are the system memory's - /// alone, which that GPU reads across the bus, so they take none. - pub(super) fn device_copy(&self, device: &Device) -> bool { - let layout = &self.layout; - // The looks at the pages last: each takes their lock (`WorkCounts::no_copy_lies_read`), - // which a texture on any other GPU never needs. - device.properties().kind == crate::DeviceKind::Discrete - && !self.surface - && matches!(self.options.storage_mode(), Ok(StorageMode::Managed)) - && self.tracked() - && layout.slices == 1 - && layout.shared_bytes() == 0 - && (self.buffer.at_for(layout.offset, ReadApart::Texture).1) - .is_multiple_of(self.texel_bytes) - && (self.buffer.host_pages()).is_some_and(|pages| pages.dirty().is_some()) - } - - pub(super) fn shadow_copies( - &self, - image: vk::Image, - identity: Identity, - aspects: vk::ImageAspectFlags, - (words, unorm): (Option, Option), - ) -> Result { - let layout = &self.layout; - let (buffer, at) = self.buffer.at_for(layout.offset, ReadApart::Texture); - // Vulkan copies a depth or stencil aspect at multiples of 4 bytes only. - let depth = vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL; - let align = match aspects.intersects(depth) { - true => 4, - false => self.texel_bytes, - }; - // Texels past the buffer's length go through their tail, which holds them. - let staging = if at.is_multiple_of(align) && self.tail.is_none() { - None - } else { - Some(self.staging(layout, at)?) - }; - let start = staging - .as_ref() - .map_or(at, |staging| staging.into.dst_offset); - // The descriptor's checks bound a texture's extent and slices to `u32`s. - let slices = layout.slices as u32; - let (regions, back) = - plane_copy_regions(layout, (self.texel_bytes, self.blocks), start, aspects); - // A copy back dispatches, and a merge fetches, over one region copied in place alone. - let one_region = regions.len() == 1 && slices == 1 && staging.is_none(); - let (bytes, tracked) = self.buffer.tracked(layout.offset..layout.end()); - Ok(ShadowCopies { - source: ShadowSource::Bytes { - buffer: ShadowBuffer::of(&self.buffer, buffer), - key: bytes.key, - bytes: tracked, - target: ShadowTarget::Image { - words: words.filter(|_| one_region), - unorm: unorm.filter(|_| one_region), - image, - regions, - back, - staging, - // A block-compressed texture is no color attachment, whose copies alone are - // bounded. - texel: self.blocks.is_none().then_some(self.texel_bytes), - }, - alias: self.buffer.alias().map(|alias| alias.key), - }, - shadow_key: identity.key, - shadow_range: UseRange::Image { - aspects, - levels: 0..1, - layers: 0..slices, - place: ImagePlace::WHOLE, - }, - tracked: self.tracked(), - drops_writes: false, - levels: None, - decode: Default::default(), - backing: self.backing(), - merge_scratch: ScratchSpares::default(), - stood: AtomicU64::new(0), - standing: StandingAcross::over(&self.buffer), - }) - } - - /// The staging buffer of a shadowed texture or a texture buffer over the texels laid out as - /// `layout`, which start at `at` of the buffer's `VkBuffer`: the texels' bytes from the first - /// to the last, at its start, of the texture's hazard tracking, in a buffer of whole 4-byte - /// words (the rotation kernel's, `rotated.rs`, binds them all). Texels past the buffer's - /// length take their tail, whose bytes past the length are the texels' own: the copies - /// between it and the buffer move the bytes inside the length alone ([`inside_rows`]). - fn staging(&self, layout: &BufferLayout, at: u64) -> Result { - let span = layout.end() - layout.offset; - let buffer = match &self.tail { - Some(tail) => tail.clone(), - None => { - let hazard = self.options.hazard_tracking_mode()?; - let options = - ResourceOptions::new(StorageMode::Private, CpuCacheMode::DefaultCache, hazard); - (self.buffer.generation()).own_buffer(span.next_multiple_of(4), options)? - } - }; - let (_, start) = buffer.at(0); - let inside = match self.tail { - Some(_) => self.kept.saturating_sub(layout.offset).min(span), - None => span, - }; - let back = inside_rows(staged_rows_back(layout, start, at), at, inside); - Ok(ShadowStaging { - into: vk::BufferCopy { - src_offset: at, - dst_offset: start, - size: inside, - }, - back, - buffer, - }) - } - - /// The copy unit of CPU access to the texels: one texel, or one block of a block-compressed - /// texture. - pub(super) fn unit(&self) -> CopyUnit { - CopyUnit { - bytes: self.texel_bytes as u32, - extent: self.blocks.map_or([1, 1], |blocks| blocks.extent), - aspect: ImageAspectFlags::COLOR, - } - } - - /// The texels across of each row that lie in place, for a BC texture whose rows of blocks are - /// wider than its plane's `bytesPerRow` (`linear_plan::blocks_kept_to_row`): its layouts' - /// rows, the plane's, of fewer blocks than the texture's row. Its blocks past them lie in no - /// byte: its shadow image holds them, zero when made, which no copy in or back reaches; a - /// blit or `replace_region` writes none of them (`Texture::written_in_place`, - /// [`bytes_in_place`](Self::bytes_in_place)), and `get_bytes` reads them as zeros. `None` for - /// every other texture, whose rows lie whole. - pub(super) fn columns_in_place(&self) -> Option { - let blocks = self.blocks?; - let [w, _] = blocks.extent.map(u64::from); - let across = u64::from(blocks.texels[0]).div_ceil(w); - let kept = self.layout.row_bytes / self.texel_bytes; - (kept < across).then_some(kept * w) - } - - /// The bytes of each of `region`'s rows of `row_bytes` that lie in place: all of them, but - /// past a BC texture's texels in place ([`columns_in_place`](Self::columns_in_place)). - fn bytes_in_place(&self, region: &ImageRegion, row_bytes: u64) -> u64 { - let Some(columns) = self.columns_in_place() else { - return row_bytes; - }; - let [w, _] = self.unit().extent.map(u64::from); - let x = u64::from(region.origin[0]); - (columns.saturating_sub(x) / w * self.texel_bytes).min(row_bytes) - } - - /// What a binding plan reads of a texture buffer of `pixel_format` and `swizzle` over these - /// texels: the texels' offset in the `VkBuffer` its bindings view (`Texels::viewed`), which - /// the plan's view ranges address, the swizzle a function's reads apply, and the texel buffer - /// views its texels take on the device (`bind::texel_buffer_parts`): past one where they - /// pass its `maxTexelBufferElements`, which a slot that reads them through their parts binds - /// (`bind::texel_parts`). - pub(super) fn bound( - &self, - pixel_format: PixelFormat, - swizzle: TextureSwizzleChannels, - ) -> BoundTexture { - let device = self.buffer.generation(); - let limits = device.compile_device().profile().limits(); - let texels = self.shader.row_bytes / self.texel_bytes.max(1); - BoundTexture::Buffer { - pixel_format, - offset: self.viewed().1, - length: self.shader.row_bytes, - bytes_per_row: self.shader.row_pitch, - resource_id: None, - swizzle, - parts: metal2vulkan::bind::texel_buffer_parts(limits, texels), - } - } - - /// Where an image over the texels lies in the bytes of the key it takes, the buffer's - /// (`tracker::ImagePlace`): the buffer's bytes a use of the texels names - /// ([`bound_use`](Self::bound_use)), as the buffer tracks them (`Buffer::tracked`, a heap - /// buffer's in its heap's). Two textures over one buffer's bytes apart share its key and no - /// byte. - pub(super) fn place(&self) -> ImagePlace { - let shader = &self.shader; - ImagePlace::bytes(self.buffer.tracked(shader.offset..shader.end()).1) - } - - /// A use of the texels' bytes of the buffer, reading by `read` and writing by `write`; of - /// the staging buffer, for a texture buffer viewed through one (a shadow's use). - pub(super) fn bound_use(&self, read: Access, write: Access) -> Use { - if let Some(copies) = &self.staged { - return Use { - key: copies.shadow_key, - tracked: copies.tracked, - range: copies.shadow_range.clone(), - read, - write, - }; - } - let shader = &self.shader; - let (identity, range) = self.buffer.tracked(shader.offset..shader.end()); - Use { - key: identity.key, - tracked: self.tracked(), - range: UseRange::Bytes(range), - read, - write, - } - } - - /// The texel buffer view of `range` of the buffer in `format`, a storage texel buffer's - /// (`storage`) or a uniform one's, made at its first use, with the usage [`view_usage`] - /// gives it. - pub(super) fn view( - &self, - format: Format, - storage: bool, - range: BufferRange, - ) -> Result { - self.view_of(format, storage, (range.offset, range.range)) - } - - /// The texel buffer view through which a heap set's texel-buffer array holds these texels, a - /// texture buffer's, in `format`, a storage texel buffer's (`storage`) or a uniform one's - /// (`bind::HeapElement::TexelBuffer`): the view a slot's binding of them takes - /// (`bind::instantiate::texel_ranges`), from their offset over the whole texel blocks of - /// their length. `None` where no command's binding of them would make such a view in place: - /// their bindings view a staging buffer or their tail ([`Texels::staged`]), which only an - /// encoder that binds them copies in and back; their offset is off the device's - /// `minTexelBufferOffsetAlignment`; their length holds no whole block; or they hold more - /// texels than `maxTexelBufferElements`. - pub(super) fn heap_view( - &self, - format: Format, - storage: bool, - ) -> Result, Error> { - if self.staged.is_some() { - return Ok(None); - } - let device = self.buffer.generation(); - let profile = device.compile_device().profile(); - let limits = profile.limits(); - let (_, offset) = self.viewed(); - let block = format - .block() - .ok_or_else(|| internal("a texel view of a format without a block"))?; - let size = u64::from(block.size).max(1); - let blocks = self.shader.row_bytes / size; - let elements = blocks.saturating_mul(u64::from(block.texels)); - if offset % limits.min_texel_buffer_offset_alignment.max(1) != 0 - || blocks == 0 - || elements > u64::from(limits.max_texel_buffer_elements) - { - return Ok(None); - } - self.view_of(format, storage, (offset, blocks * size)) - .map(Some) - } - - /// [`view`](Self::view) of `range` bytes from `offset` in the viewed `VkBuffer`. - pub(super) fn view_of( - &self, - format: Format, - storage: bool, - (offset, range): (u64, u64), - ) -> Result { - let key = (format, storage, offset, range); - let mut views = lock(&self.views.views); - if let Some(&view) = views.get(&key) { - return Ok(view); - } - let device = self.buffer.generation(); - let profile = device.compile_device().profile(); - let usage = view_usage( - |usage| profile.supports_format(format, usage), - storage, - device.enabled().features.contains(&VkFeature::Maintenance5), - )?; - // The range is the viewed `VkBuffer`'s already ([`Texels::bound`]). - let (buffer, _) = self.viewed(); - let mut only = vk::BufferUsageFlags2CreateInfoKHR::default(); - let mut info = vk::BufferViewCreateInfo::default() - .buffer(buffer) - .format(format.into()) - .offset(offset) - .range(range); - if let Some(named) = usage.named() { - only = only.usage(named); - info = info.push_next(&mut only); - } - // SAFETY: the buffer is live and made for both texel buffer usages; `format` serves the - // usages the view has (both, or the one its `VkBufferUsageFlags2CreateInfoKHR` names - // under the `maintenance5` the device enabled, [`view_usage`]); the binding plan aligned - // the range and bounded its texels (`bind::instantiate::texel_ranges`). - let view = - unsafe { device.shared().vk().create_buffer_view(&info, None) }.map_err(vulkan)?; - views.insert(key, view); - Ok(view) - } - - /// The bytes of `region` (in units of one texel) at the texels' place in the buffer, as a - /// layout of the buffer's bytes from the region's first, which starts that many bytes into - /// the buffer. - fn region_layout(&self, region: &ImageRegion, host: &HostLayout) -> (u64, HostLayout) { - let layout = &self.cpu; - let [x, y, _] = region.origin.map(u64::from); - // A block-compressed texture's region starts on a block (the copy's check). - let [w, h] = self.unit().extent.map(u64::from); - let (x, y) = (x / w, y / h); - let start = layout.offset - + layout.slice_pitch * u64::from(region.layer) - + layout.row_pitch * y - + self.texel_bytes * x; - ( - start, - HostLayout { - bytes_per_row: layout.row_pitch, - bytes_per_image: layout.slice_pitch, - ..*host - }, - ) - } - - /// The buffer's bytes `start..start + len` (`None` for more than `u64::MAX`), which lie in it: - /// their first byte and their end. Refused for a buffer the CPU does not reach (`Private`). - fn bytes( - &self, - call: &'static str, - start: u64, - len: Option, - ) -> Result<(*mut u8, u64), Error> { - let contents = self - .buffer - .mapped_contents() - .ok_or_else(|| invalid(call, Problem::Copy(CopyProblem::CpuAccessPrivate)))?; - // The texture lies in the buffer's memory, and so do the rows of a region checked in its - // level. - let end = len.and_then(|len| start.checked_add(len)); - let Some(end) = end.filter(|&end| end <= self.buffer.texel_reach()) else { - return Err(internal("a texture's rows past its buffer")); - }; - // SAFETY: `start` lies in the buffer's mapped bytes (checked above). - Ok((unsafe { contents.as_ptr().add(start as usize) }, end)) - } - - /// `replaceRegion` of `region` from `bytes` laid out as `host` (checked by the texture): into - /// the buffer's mapped bytes, and from there to its own where it has a host copy (a `Managed` - /// buffer on a device without unified memory, `Buffer::upload`), as Metal's `replaceRegion` - /// updates a managed texture for the GPU. - pub(super) fn write( - &self, - call: &'static str, - region: &ImageRegion, - host: &HostLayout, - bytes: &[u8], - ) -> Result<(), Error> { - let mut packed = vec![0u8; host.packed_len() as usize]; - host.pack(bytes, &mut packed); - let (start, inside) = self.region_layout(region, host); - if let Some(past) = self.past() { - return self.write_past(call, (start, &inside), &packed, past); - } - // A row's bytes past a BC texture's texels in place lie in no byte: dropped, as the x86 - // Macs' blits drop them (a texture with a tail holds whole rows: no BC texture keeps - // one, `linear_plan::tail_held`). - let n = self.bytes_in_place(region, host.row_bytes); - if n == 0 { - return Ok(()); - } - let held = HostLayout { - row_bytes: n, - ..inside - }; - let (target, end) = self.bytes(call, start, held.host_len())?; - let n = n as usize; - for (at, from) in inside.rows() { - // SAFETY: every row lies in the buffer's mapped bytes from `start` (`bytes`); a write - // racing the GPU's use of them is the program's, as through `contents`. - unsafe { std::ptr::copy_nonoverlapping(packed[from..].as_ptr(), target.add(at), n) }; - } - // A write of host pages a consumer logs is the runtime's own, which its log does not see: - // reported, so the copies of the pages take it (`dirty_pages.rs`). - let at = target as u64; - self.buffer.wrote_host(at..at + (end - start)); - self.buffer.modified(start..end); - Ok(()) - } - - /// The mapped bytes the CPU reaches the texels' bytes `start..start + len` of the buffer's - /// space through, where the texels run past its length (`past`): the part inside the length - /// in the buffer's, the rest in the tail's, each `(where its bytes go in the run, its first - /// byte, its length)`. Refused as [`bytes`](Self::bytes) refuses the buffer's. - fn past_runs( - &self, - call: &'static str, - (start, len): (u64, u64), - past: Past<'_>, - ) -> Result, Error> { - let private = || invalid(call, Problem::Copy(CopyProblem::CpuAccessPrivate)); - let end = start + len; - let mut runs = Vec::with_capacity(2); - if start < past.length { - let contents = self.buffer.mapped_contents().ok_or_else(private)?; - // SAFETY: `start..past.length` lies in the buffer's mapped bytes. - let first = unsafe { contents.as_ptr().add(start as usize) }; - runs.push((0, first, (end.min(past.length) - start) as usize)); - } - if end > past.length { - let from = start.max(past.length); - let contents = past.tail.mapped_contents().ok_or_else(private)?; - let at = from - past.rebase; - if at + (end - from) > past.tail.length() { - return Err(internal("a texture's rows past its tail")); - } - // SAFETY: `at..at + (end - from)` lies in the tail's mapped bytes (checked above). - let first = unsafe { contents.as_ptr().add(at as usize) }; - runs.push(((from - start) as usize, first, (end - from) as usize)); - } - Ok(runs) - } - - /// [`write`](Self::write) of texels that run past the buffer's length: each row's bytes - /// inside the length into the buffer's, the rest into the tail's. - fn write_past( - &self, - call: &'static str, - (start, inside): (u64, &HostLayout), - packed: &[u8], - past: Past<'_>, - ) -> Result<(), Error> { - let n = inside.row_bytes; - let mut end = start; - for (at, from) in inside.rows() { - let row = start + at as u64; - for (into, target, len) in self.past_runs(call, (row, n), past)? { - // SAFETY: each run lies in the buffer's or the tail's mapped bytes - // (`past_runs`); a write racing the GPU's use of them is the program's. - unsafe { - std::ptr::copy_nonoverlapping(packed[from + into..].as_ptr(), target, len) - }; - } - end = end.max(row + n); - } - // The buffer's own bytes written, as `write` reports and uploads them. - let end = end.min(past.length); - if start < end { - let contents = self - .buffer - .mapped_contents() - .ok_or_else(|| invalid(call, Problem::Copy(CopyProblem::CpuAccessPrivate)))?; - let at = contents.as_ptr() as u64 + start; - self.buffer.wrote_host(at..at + (end - start)); - self.buffer.modified(start..end); - } - Ok(()) - } - - /// `getBytes` of `region` into `bytes` laid out as `host` (checked by the texture): from the - /// buffer's mapped bytes, a host copy's where it has one, which `synchronize_resource` and - /// `synchronize_texture` update, as Metal's managed texture needs `synchronizeTexture` on a - /// device without unified memory. - pub(super) fn read( - &self, - call: &'static str, - region: &ImageRegion, - host: &HostLayout, - bytes: &mut [u8], - ) -> Result<(), Error> { - let mut packed = vec![0u8; host.packed_len() as usize]; - let (start, inside) = self.region_layout(region, host); - if let Some(past) = self.past() { - for (at, to) in inside.rows() { - let row = start + at as u64; - for (into, source, len) in self.past_runs(call, (row, host.row_bytes), past)? { - // SAFETY: as in `write_past`. - unsafe { - std::ptr::copy_nonoverlapping(source, packed[to + into..].as_mut_ptr(), len) - }; - } - } - host.unpack(&packed, bytes); - return Ok(()); - } - // A row's bytes past a BC texture's texels in place lie in no byte: they read zero, as - // the x86 Macs' blits read them. - let n = self.bytes_in_place(region, host.row_bytes); - if n != 0 { - let held = HostLayout { - row_bytes: n, - ..inside - }; - let (source, _) = self.bytes(call, start, held.host_len())?; - let n = n as usize; - for (at, to) in inside.rows() { - // SAFETY: as in `write`. - unsafe { - std::ptr::copy_nonoverlapping(source.add(at), packed[to..].as_mut_ptr(), n) - }; - } - } - host.unpack(&packed, bytes); - Ok(()) - } -} - -/// The usage a texel buffer view of a format of the device's takes, beside the buffer's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum ViewUsage { - /// The buffer's: the format serves both kinds of texel buffer the buffer is made for. - Buffer, - /// Only the view's own kind, a storage texel buffer (`storage`) or a uniform one - /// (`VkBufferUsageFlags2CreateInfoKHR`): the format serves it and not the other. - Only { storage: bool }, -} - -impl ViewUsage { - /// The usage a view of [`ViewUsage::Only`] names, or `None` for the buffer's. - pub(super) fn named(self) -> Option { - match self { - ViewUsage::Buffer => None, - ViewUsage::Only { storage: true } => { - Some(vk::BufferUsageFlags2KHR::STORAGE_TEXEL_BUFFER) - } - ViewUsage::Only { storage: false } => { - Some(vk::BufferUsageFlags2KHR::UNIFORM_TEXEL_BUFFER) - } - } - } -} - -/// The usage of a texel buffer view of a storage texel buffer (`storage`) or a uniform one, in a -/// format `supports` says which kinds of texel buffer the device takes it for, on a device that -/// enabled `maintenance5` or not. The runtime makes every buffer for both kinds (`buffer::usage`), -/// and a view's format must serve every texel buffer usage the view has -/// (`VUID-VkBufferViewCreateInfo-format-08778`, `-08779`): the buffer's where the format serves -/// both, else only the view's own kind, which `maintenance5` lets a view name -/// (`VUID-VkBufferViewCreateInfo-pNext-08780`, `-08781`). Without `maintenance5` that view is -/// not made (`NotImplemented(Textures)`), nor one in a format that does not serve the view's -/// kind, which no binding plan names. -pub(super) fn view_usage( - supports: impl Fn(FormatUsage) -> bool, - storage: bool, - maintenance5: bool, -) -> Result { - let (own, other) = if storage { - ( - FormatUsage::StorageTexelBuffer, - FormatUsage::UniformTexelBuffer, - ) - } else { - ( - FormatUsage::UniformTexelBuffer, - FormatUsage::StorageTexelBuffer, - ) - }; - match (supports(own), supports(other)) { - (true, true) => Ok(ViewUsage::Buffer), - (true, false) if maintenance5 => Ok(ViewUsage::Only { storage }), - _ => Err(Error::NotImplemented(RuntimeGap::Textures)), - } -} - -/// The regions that copy the texels laid out as `layout` from a staging buffer, where they start at -/// `start`, back into the texture's `VkBuffer`, where they start at `at` (`ShadowStaging::back`): -/// one a row, but one for rows that lie one after another or share bytes. -/// -/// A row that shares bytes with the one above (an IOSurface plane's on Metal's GPU, -/// `linear_plan::iosurface_gpu_layout`) extends that row's region rather than opening one of its -/// own: a region of each would write the shared bytes twice in one `vkCmdCopyBuffer`, which no -/// two destination regions of one may do (`VUID-vkCmdCopyBuffer-pRegions-12482`; older releases -/// read it off `-00117`'s union of the destination regions). The staging buffer holds the plane's -/// bytes as they lie, the shadow's copy back having written each of them once -/// ([`plane_copy_regions`]), so one region of the rows' whole span moves them as they are. -pub(super) fn staged_rows_back(layout: &BufferLayout, start: u64, at: u64) -> Vec { - let rows = (0..layout.slices).flat_map(|slice| { - (0..layout.rows).map(move |row| slice * layout.slice_pitch + row * layout.row_pitch) - }); - let mut back: Vec = Vec::new(); - for row in rows { - let end = start + row + layout.row_bytes; - match back.last_mut() { - Some(last) if last.src_offset + last.size >= start + row => { - last.size = end - last.src_offset; - } - _ => back.push(vk::BufferCopy { - src_offset: start + row, - dst_offset: at + row, - size: layout.row_bytes, - }), - } - } - back -} - -/// `back`, copies of rows from a staging buffer into a buffer's `VkBuffer` whose texels start at -/// its byte `at`, cut to the texels' first `inside` bytes: a texture's whose texels run past the -/// buffer's length, whose bytes past it its tail keeps ([`Texels::staging`]). A row past them is -/// dropped, and one across them cut there. -pub(super) fn inside_rows(back: Vec, at: u64, inside: u64) -> Vec { - let end = at + inside; - back.into_iter() - .filter(|row| row.dst_offset < end) - .map(|row| vk::BufferCopy { - size: row.size.min(end - row.dst_offset), - ..row - }) - .collect() -} - -/// The regions that copy the texels laid out as `layout`, `texel_bytes` each (of a block each, -/// where `blocks` gives a block-compressed texture's: its rows of blocks are copied as the texels -/// they hold, its last block of a row and of a column covering its texels alone), starting at -/// `start` of the `VkBuffer` the copies address, into a 2D texture's shadow image of `aspects`, and the -/// regions that copy them back out of it (`shadow.rs`, [`Texels::shadow_copies`]): one region a -/// slice each way, the slice's rows of texels, where each row lies a row apart from the one above -/// or further. Metal's slices lie multiples of 128 bytes apart and its rows multiples of 16, so -/// of every texel size. -/// -/// Where consecutive rows share bytes (an IOSurface plane's on Metal's GPU, -/// `linear_plan::iosurface_gpu_layout`, and a heap's one-plane YCbCr texture's, -/// `texture/heap.rs`'s `heap_planes`: 1 to 15 bytes, a whole number of texels, between -/// consecutive rows alone; and a plane's whose rows are wider than its pitch, any whole number -/// of texels, a byte shared by as many rows as reach it), no one region states a slice: a region -/// addresses its rows one `bufferRowLength` apart, which is at least its width -/// (`VUID-vkCmdCopyBufferToImage-bufferRowLength-00195`), and the shared bytes hold a texel of -/// each of two rows or more. Each slice takes two regions instead, split at the texels the -/// sharing covers: -/// -/// - going in, every row's shared head (in pieces no wider than the pitch, where the head is -/// wider: a region's `bufferRowLength` covers its width) and the rest of every row, which is -/// one pitch wide. Their sources share the bytes, which a copy into an image allows: a memory -/// location may not be read by a source region and written by a destination region of one copy -/// (`VUID-vkCmdCopyBufferToImage-pRegions-00173`), nor written by two destination regions -/// (`-12483`), and the regions' image texels are disjoint and together every texel; -/// - going back, the rest of every row, and the head of row 0 alone (one row, its -/// `bufferRowLength` 0 where the head is wider than the pitch). Those tile the slice's bytes -/// exactly once, so no byte is written by two destination regions -/// (`VUID-vkCmdCopyImageToBuffer-pRegions-12485`), and every shared byte takes the earliest -/// row's that reaches it. Metal leaves there whichever row its own command wrote last, an order -/// that follows the command, the GPU pitch and the row count rather than one rule -/// (`linear_plan.rs`'s **Rows that overlap**); a kernel, the only GPU writer such a plane -/// takes, moves its winner with the threadgroup shape, so the earliest row's bytes are one of -/// its answers ([`Degradation::CollidingSurfaceRowWrites`]). -pub(super) fn plane_copy_regions( - layout: &BufferLayout, - (texel_bytes, blocks): (u64, Option), - start: u64, - aspects: vk::ImageAspectFlags, -) -> (Vec, Vec) { - let shared = layout.shared_bytes(); - let width = (layout.row_bytes / texel_bytes) as u32; - let pitch = (layout.row_pitch / texel_bytes) as u32; - // The descriptor's checks bound a texture's extent and slices to `u32`s. - let (slices, rows) = (layout.slices as u32, layout.rows as u32); - // A block-compressed texture's rows of blocks, as Vulkan copies them: its pitch and offsets - // in texels, its extent its own texels (`VUID-vkCmdCopyBufferToImage-imageExtent-00207`). - let [bw, bh] = blocks.map_or([1, 1], |blocks| blocks.extent); - let texels = |units: u32, side: usize| { - let texels = units * [bw, bh][side]; - blocks.map_or(texels, |blocks| texels.min(blocks.texels[side])) - }; - let region = |slice: u32, at: u64, x: u32, units: u32, height: u32| vk::BufferImageCopy { - buffer_offset: at + layout.slice_pitch * u64::from(slice), - buffer_row_length: pitch * bw, - buffer_image_height: 0, - image_subresource: vk::ImageSubresourceLayers { - aspect_mask: aspects, - mip_level: 0, - base_array_layer: slice, - layer_count: 1, - }, - image_offset: vk::Offset3D { - x: (x * bw) as i32, - y: 0, - z: 0, - }, - image_extent: vk::Extent3D { - width: texels(x + units, 0) - x * bw, - height: texels(height, 1), - depth: 1, - }, - }; - if shared == 0 { - let regions: Vec = (0..slices) - .map(|slice| region(slice, start, 0, width, rows)) - .collect(); - return (regions.clone(), regions); - } - let head = (shared / texel_bytes) as u32; - let (mut into, mut back) = (Vec::new(), Vec::new()); - for slice in 0..slices { - // The head in pieces no wider than the pitch, where rows wider than their pitch share - // more than a pitch's bytes: a region's rows lie its `bufferRowLength` apart. - let mut x = 0; - while x < head { - let units = pitch.min(head - x); - into.push(region( - slice, - start + u64::from(x) * texel_bytes, - x, - units, - rows, - )); - x += units; - } - into.push(region(slice, start + shared, head, width - head, rows)); - // Row 0's head is one row, whose bytes lie one after another however wide it is. - let row_zero = region(slice, start, 0, head, 1); - back.push(match head > pitch { - true => vk::BufferImageCopy { - buffer_row_length: 0, - ..row_zero - }, - false => row_zero, - }); - back.push(region(slice, start + shared, head, width - head, rows)); - } - (into, back) -} diff --git a/crates/metal2vulkan-runtime/src/capabilities.rs b/crates/metal2vulkan-runtime/src/capabilities.rs deleted file mode 100644 index 88ca67bdd..000000000 --- a/crates/metal2vulkan-runtime/src/capabilities.rs +++ /dev/null @@ -1,683 +0,0 @@ -//! Metal's device queries, answered from the Vulkan device. -//! -//! [`DeviceProperties`] holds the device's identity and the public `MTLDevice` properties and -//! queries, each answered from an exact source: -//! - a Vulkan property, limit, feature or format the device was created with (its enabled -//! [`DeviceDescription`]); -//! - the compile layer's answer for the device -//! ([`MetalDeviceProperties`](metal2vulkan::device::MetalDeviceProperties), which the translation -//! itself obeys); -//! - or a value measured on Apple's GPU that the compile layer reproduces. -//! -//! Apple-only features answer missing unless the compile layer emulates them exactly. Metal's GPU -//! families (`supportsFamily:`) are the device's own query, judged row by row against Apple's -//! feature set tables ([`Device::supports_family`](super::Device::supports_family)). -//! -//! Apple's private (SPI) device properties are -//! [`Device::private_properties`](super::Device::private_properties)'s, but for -//! `supportsTextureWriteRoundingMode:`, which a pipeline's translation answers, and -//! `supportsPrimitiveType:`, both here. -//! -//! A query whose runtime piece is not built yet answers the [`RuntimeGap`] it waits on -//! ([`Query::gap`]). The step that builds the piece deletes the gap, and the query then answers the -//! device's value, which this type already holds. -//! -//! The fields are fixed when the device is made. An answer that changes while the device lives is -//! a method of its object's step on `Device` instead: step 5's per-format mipmap verdict, settled -//! by the first mipmap generation of each format. So is one the device's images decide, worked out -//! for every format at the first query of any and fixed from there: -//! `Device::minimum_linear_texture_alignment_for_pixel_format`. - -use super::device::argument_buffers::APPLE; -use super::device::DeviceKind; -use super::driver_defects; -use super::error::{invalid, Error, Problem, RuntimeGap}; -use super::linear_plan::linear_alignment; -use super::sampler::argument_buffer_sampler_count; -use super::texture_descriptor::TextureRules; -use super::values::Size; -use metal2vulkan::device::{DeviceDescription, DriverFact, VkFeature}; -use metal2vulkan::error::RuntimeDriverDefect; -use metal2vulkan::metal::{ArgumentBuffersTier, PixelFormat, ReadWriteTextureTier}; -use metal2vulkan::vk::{ApiVersion, SampleCountFlags}; -use std::collections::BTreeSet; - -/// Rasterization-rate maps of up to this many layers compile: the most Apple's compile was -/// measured with, which is Apple M3's `supportsRasterizationRateMapWithLayerCount:`, and the most -/// Metal's API validation takes on an M3 Max and an M4. -/// [`bind::RasterizationRateMap::new`](metal2vulkan::bind::RasterizationRateMap::new) refuses more, and -/// so does [`Device::new_rasterization_rate_map`](super::Device::new_rasterization_rate_map). -pub(super) const RATE_MAP_LAYERS: u64 = 2; - -/// The largest vertex amplification count Metal supports: `supportsVertexAmplificationCount:` -/// answers yes from 1 to 8 and no from 9 to 16 (a Metal probe: the M3 Max with macOS 26.7 and an M4 -/// with macOS 27.0.1, alike), and yes for 0 (alike). A device with `multiview` draws every such -/// count: as views where multiview draws them as Metal does, else one amplification at a time. -pub(super) const MAX_VERTEX_AMPLIFICATION: u64 = 8; - -/// A device's identity and Metal's public device queries, as the runtime answers them on the -/// Vulkan device. -/// -/// The fields hold final answers. The methods answer the queries whose runtime piece may not be -/// built yet ([`Query`]). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DeviceProperties { - /// `name`: `VkPhysicalDeviceProperties::deviceName`. - pub name: String, - /// The kind of physical device (`VkPhysicalDeviceProperties::deviceType`). - pub kind: DeviceKind, - /// `hasUnifiedMemory`: the device's memory is the host's, from its kind: an integrated GPU's - /// or a CPU implementation's. A discrete GPU answers no, as Metal answers on one, and so do a - /// virtual GPU and any other kind, whose memory Vulkan does not place. `Managed` storage - /// follows Metal's contract for the answer (`managed.rs`), and `Shared` storage lies where a - /// Mac's does (docs/API.md "The runtime's memory model"). - pub has_unified_memory: bool, - /// Whether the Mac the device presents keeps textures losslessly compressed, as an Apple - /// silicon Mac's GPU does, a Mac with an Intel or AMD GPU's does not: true where the device - /// presents [`MacClass::AppleSilicon`], the class - /// [`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class) declares, else the one of - /// the device's GPU ([`MacClass::of_vendor`]). Metal has no property for it: it shows in what - /// a new `Private` texture reads before anything writes it (Metal's fixed pattern or zero, - /// against zero or a released texture's texels), in the encoding a GPU blit through such a - /// texture writes, and in a `half` NaN clear's sign (docs/API.md, the accepted differences). - pub lossless_compression: bool, - /// `VkPhysicalDeviceProperties::vendorID`. - pub vendor_id: u32, - /// `VkPhysicalDeviceProperties::deviceID`. - pub device_id: u32, - /// `VkPhysicalDeviceIDProperties::deviceUUID`, which `registryID` is folded from - /// (`Device::registry_id`). - pub device_uuid: [u8; 16], - /// The device's PCI bus address, as its driver reports it: - /// `VkPhysicalDevicePCIBusInfoPropertiesEXT`'s `pciDomain`, `pciBus`, `pciDevice` and - /// `pciFunction`, in that order, read where the physical device lists - /// `VK_EXT_pci_bus_info`. No Metal counterpart: Metal names no bus, and macOS has no such - /// Vulkan extension, so a MoltenVK device answers `None`. A consumer that must drive another - /// API (a video decoder, a compute runtime) on the same GPU this device draws on addresses it - /// by this. `None` where the physical device does not list the extension, which is the only - /// thing the answer then says: the device still has a bus address, and the runtime does not - /// know it. - pub pci_bus: Option<(u32, u32, u32, u32)>, - /// The device's DRM render node, as its driver reports it: - /// `VkPhysicalDeviceDrmPropertiesEXT`'s `renderMajor` and `renderMinor`, in that order, read - /// where the physical device lists `VK_EXT_physical_device_drm`. No Metal counterpart: DRM is - /// Linux's, and macOS has no such Vulkan extension, so a MoltenVK device answers `None`. A - /// consumer that must open the same GPU through another Linux interface (VA-API, V4L2) opens - /// this node. `None` where the physical device does not list the extension, and `None` where - /// it lists it and reports the device has no render node (`hasRender` false), whose major and - /// minor numbers say nothing; never a pair of zeroes standing for either. - pub drm_render: Option<(i64, i64)>, - /// The Vulkan version the device runs at: the lower of the instance's and the device's. - pub api_version: ApiVersion, - /// `maxBufferLength`: the longest buffer a shader can bind whole, the compile layer's answer - /// (`maxStorageBufferRange` where buffers are reached through descriptors only, else the lower - /// of `maxBufferSize` and `maxMemoryAllocationSize`), at most three quarters of the device's - /// largest device-local heap, rounded down to 16 KiB (`working_set_buffer_bound`). Metal - /// answers three quarters of its `recommendedMaxWorkingSetSize`: 3,208,642,560 of 4,278,190,080 - /// on an AMD Radeon Pro 5300M (4 GiB, macOS 26.7.1), and 41,747,087,360 of 55,662,788,608, to - /// 16 KiB, on an Apple M3 Max (64 GiB, macOS 27.0.1); the runtime holds no working set size and - /// takes the heap for it, so a discrete GPU's answer follows its memory, as Metal's does, where - /// its Vulkan limits alone allow far more (`maxBufferSize` 1 TiB on NVIDIA's 615.71.09). On - /// MoltenVK the bound is above the compile layer's answer, Metal's own. - pub max_buffer_length: u64, - /// `maxThreadsPerThreadgroup`: per axis, `maxComputeWorkGroupSize` capped by - /// `maxComputeWorkGroupInvocations` and by an Apple GPU's 1024. - pub max_threads_per_threadgroup: Size, - /// `maxThreadgroupMemoryLength`: `maxComputeSharedMemorySize`, since a kernel's threadgroup - /// arenas are exactly its Metal allocations, capped by what Metal answers on the class of Mac - /// the device presents ([`MacClass`]): an Apple silicon Mac's 32 KiB, a Mac with an Intel or - /// AMD GPU's 64 KiB. A dispatch takes threadgroup memory up to the device's own limit, so - /// every length this answers runs. - pub max_threadgroup_memory_length: u64, - /// `argumentBuffersSupport`: `Tier2` where buffers are reached by device address and texture - /// and sampler handles through the descriptor heap (descriptor indexing), else `Tier1`. - pub argument_buffers_support: ArgumentBuffersTier, - /// `maxArgumentBufferSamplerCount`: the most live sampler states functions can read through - /// argument buffers, one fewer than the smaller of two counts, each with a slot the states do - /// not take: - /// - the elements of a set-1 sampler array, which holds each live state at an element of its - /// own and the neutral sampler at element 0 - /// ([`heap_sampler_capacity`](metal2vulkan::pipeline::heap_sampler_capacity): the least of - /// the handle table's 65536 entries, `maxDescriptorSetUpdateAfterBindSamplers` and - /// `maxPerStageDescriptorUpdateAfterBindSamplers`, 0 where no function can read one); - /// - `maxSamplerAllocationCount`, the Vulkan samplers the device holds live at once, one past - /// them refused (`Error::SamplerLimit`): the array's neutral sampler and a sampler of each - /// state it holds are among them. - /// - /// It is the most any pipeline reads. Fewer can be: in a pipeline whose set-1 arrays are - /// smaller (its heap has more arrays of a kind, or its set 0 counts descriptors of them), where - /// other Vulkan samplers live (another use's array, a slot's bind, a pipeline's constexpr - /// samplers), and where other holders of sampler IDs (the device's own sampler, a pipeline - /// state's numbered samplers) hold IDs the device's sampler tables reach, IDs 1 to 65535 under - /// plain allocation. A state - /// left out reads the neutral sampler through an argument buffer, announced - /// (`Degradation::UnlistedArgumentSampler`). Every live state counts, with or without - /// `supportArgumentBuffers`, since Metal reads one without it through an argument buffer too; - /// Metal's count is of the states with it. Metal answers 500000 on an Apple M3 Max (macOS - /// 27.0.1), where the runtime answers 65535 on MoltenVK, the handle table's reach. - pub max_argument_buffer_sampler_count: u64, - /// `readWriteTextureSupport`: the highest tier whose every format has a storage-image form - /// on the device. - pub read_write_texture_support: ReadWriteTextureTier, - /// `supports32BitFloatFiltering`: `R32_SFLOAT` supports linear filtering. - pub supports_32bit_float_filtering: bool, - /// `VkPhysicalDeviceLimits::maxViewports`, a documented fact for the consumer (the viewports - /// a draw may select, with the description's `multiViewport`). Metal has no public property - /// for it. - pub max_viewports: u32, - /// `gpuCoreCount` (Apple SPI): the GPU's cores as its driver reports them, read from the - /// device through the one extension its vendor names them by, where the driver lists it: - /// `VK_NV_shader_sm_builtins`' `shaderSMCount` (its streaming multiprocessors), - /// `VK_AMD_shader_core_properties2`' `activeComputeUnitCount` (its active compute units; else - /// `VK_AMD_shader_core_properties`' engines times arrays per engine times compute units per - /// array), or `VK_ARM_shader_core_builtins`' `shaderCoreCount`. `None` where the driver lists - /// none of them (Intel's drivers, MoltenVK and lavapipe among them): the runtime knows no - /// count of the device's, and gives none. Never a number of Apple's GPUs. - pub gpu_core_count: Option, - /// The description the device was created with: what it enables of Vulkan, which is all the - /// translation and the runtime use. The facts a consumer computes Apple's private properties - /// from. - pub description: DeviceDescription, - /// The defects of the device's driver in commands the runtime records for itself, from its - /// identity and release (`driver_defects.rs`): what one breaks is taken another way where an - /// exact one exists, else refused on the device, typed - /// ([`Needs::RuntimeDriverDefect`](metal2vulkan::error::Needs::RuntimeDriverDefect)). - pub driver_defects: BTreeSet, - /// What the device's driver is measured to answer where Vulkan leaves the result undefined, - /// from its identity and GPU ([`DeviceDescription::driver_facts`]): the runtime relies on one - /// only where the driver has it, and elsewhere takes the exact path that needs none. - pub driver_facts: BTreeSet, - /// The pixel interlock is enabled, so every fragment function's raster order groups are - /// ordered. - raster_order_groups: bool, - /// The sample counts every color and depth target supports, as an attachment and as a - /// sampled image, of an Apple GPU's 1, 2 and 4 - /// ([`DeviceProperties::supports_texture_sample_count`]). - texture_sample_counts: SampleCountFlags, - /// The largest vertex amplification count a render pipeline may declare: Metal's - /// (`MAX_VERTEX_AMPLIFICATION`) where `multiview` is enabled, else 1. - max_vertex_amplification_count: u64, - /// Custom sample positions are taken at every texture sample count above 1 - /// (`sample_positions.rs`). - programmable_sample_positions: bool, - /// The compile layer lowers an `interpolant` read at its centroid, a sample or an offset - /// ([`DeviceProperties::supports_pull_model_interpolation`]). - pull_model_interpolation: bool, - /// The class of Mac the device presents ([`presented_class`]). - mac_class: MacClass, -} - -/// What [`DeviceProperties::new`] reads of the physical device itself, beside the description -/// it was created with. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct DeviceIdentity { - /// `VkPhysicalDeviceProperties::deviceName`. - pub name: String, - /// `VkPhysicalDeviceProperties::deviceType`. - pub kind: DeviceKind, - /// `VkPhysicalDeviceProperties::vendorID`. - pub vendor_id: u32, - /// `VkPhysicalDeviceProperties::deviceID`. - pub device_id: u32, - /// `VkPhysicalDeviceIDProperties::deviceUUID`. - pub device_uuid: [u8; 16], - /// The device's PCI bus address ([`DeviceProperties::pci_bus`]). - pub pci_bus: Option<(u32, u32, u32, u32)>, - /// The device's DRM render node ([`DeviceProperties::drm_render`]). - pub drm_render: Option<(i64, i64)>, - /// The lower of the instance's and the device's Vulkan version. - pub api_version: ApiVersion, - /// `VkPhysicalDeviceLimits::maxViewports`. - pub max_viewports: u32, - /// `VkPhysicalDeviceLimits::maxSamplerAllocationCount`: the device's live samplers are held - /// to it (`SamplerCount`), and it bounds - /// [`DeviceProperties::max_argument_buffer_sampler_count`]. - pub max_sampler_allocation_count: u32, - /// The GPU's cores as its driver reports them ([`DeviceProperties::gpu_core_count`]). - pub gpu_core_count: Option, - /// The sample counts every color and depth image can be sampled at: - /// `sampledImageColorSampleCounts & sampledImageDepthSampleCounts`. - pub sampled_sample_counts: SampleCountFlags, - /// The size of the device's largest `DEVICE_LOCAL` memory heap, where it was read - /// (`VkPhysicalDeviceMemoryProperties`): what bounds [`DeviceProperties::max_buffer_length`], - /// and what `PhysicalDeviceIdentity::recommended_max_working_set_size` answers. - pub device_local_heap: Option, -} - -/// The longest buffer Metal's rule allows a device whose working set is `working_set` bytes: -/// three quarters of it, rounded down to 16 KiB ([`DeviceProperties::max_buffer_length`]). -pub(crate) fn working_set_buffer_bound(working_set: u64) -> u64 { - const PAGE: u64 = 16 << 10; - working_set / 4 * 3 / PAGE * PAGE -} - -/// The class of Mac a device presents, whose GPU decides answers Metal gives without a property -/// of its own: what a new `Private` texture reads before anything writes it, the encoding a GPU -/// blit through a compressed texture writes, a `half` NaN clear's sign, how far a `Clear` -/// load reaches past the render area of a pass without a draw call (docs/API.md, the accepted -/// differences), whether a sampler state's `lodBias` moves its samples' level -/// (`SamplerDescriptor::lod_bias`), and the most threadgroup memory a kernel may take -/// ([`DeviceProperties::max_threadgroup_memory_length`]). Every Mac's Metal answers one class's -/// way, by the GPU it has (Apple silicon, or an Intel or AMD GPU); the runtime answers the class -/// the consumer declares -/// ([`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class)), else the one of the device's -/// GPU ([`MacClass::of_vendor`]), and states it as -/// [`DeviceProperties::lossless_compression`]. No Metal counterpart: a Mac's GPU is what it is. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum MacClass { - /// An Apple silicon Mac, whose GPU keeps a texture losslessly compressed where Metal's rule - /// holds (`allowGPUOptimizedContents`, a level 0 of 16 texels or more on its shorter side, a - /// colour format of neither `ShaderWrite` nor `PixelFormatView` usage): a new `Private` such - /// texture reads Metal's fixed pattern over its first levels and zero elsewhere, blits - /// through it write three formats' canonical encodings, and a `half` NaN clear keeps its - /// sign. A `Clear` load in a pass of one layer without a draw call clears such a texture's - /// whole level and slice past the render area, and any other texture's render area rounded - /// up to 32x32 tiles, as a pass with a draw call clears every texture, other levels and - /// slices untouched (our probes and the consumer's on the M3 Max). The runtime writes the pattern and the zeros (a pattern no clear or copy writes - /// exactly reads zero, announced as `fresh-pattern-zeroed`), and clears so. Its GPU samples - /// every level through a sampler state as with no LOD bias, whatever the state's `lodBias` - /// (an Apple M3 Max, Apple9): so does the runtime. Its `maxThreadgroupMemoryLength` is 32 KiB - /// (an Apple M3 Max). - AppleSilicon, - /// A Mac with an Intel or AMD GPU, which keeps no texture compressed: a new `Private` - /// texture reads zero, blits keep the bytes, and a `half` NaN clear goes through `half`. Such - /// a Mac's new `Private` texture holds what its memory held (zero, or a released texture's - /// texels of the same process: an Intel UHD 630 and an AMD Radeon Pro 5300M); the runtime - /// fills it with zeros instead (`WorkCounts::private_textures_zero_filled`), as the memory - /// may have held another process's where a consumer's processes share the device. A `Clear` - /// load in a pass of one layer - /// without a draw call clears the whole level and slice past the render area, the AMD Radeon - /// Pro 5300M's answer; an Intel UHD 630 clears anything from the render area alone to the - /// whole texture there, by format and shape (the consumer's probes). Its GPU adds a sampler - /// state's `lodBias` to every sample's level, an explicit level's, a gradient's and an - /// implicit one's alike, the sum clamped into the texture's levels (both GPUs, the - /// consumer's probes): so does the runtime, through the device's `mipLodBias`, within its - /// `maxSamplerLodBias` (`Degradation::CappedLodBias` past it, and where the device's - /// portability subset withholds `samplerMipLodBias`). Its `maxThreadgroupMemoryLength` is - /// 64 KiB (both GPUs, the consumer's probes). - IntelOrAmd, -} - -impl MacClass { - /// The class of the Mac whose GPU is of PCI vendor `vendor_id` - /// (`VkPhysicalDeviceProperties::vendorID`): an Apple GPU's (`0x106b`, MoltenVK on Apple - /// silicon) is [`AppleSilicon`](Self::AppleSilicon); every other GPU's (Intel, AMD, NVIDIA, a - /// CPU implementation's) is [`IntelOrAmd`](Self::IntelOrAmd), whose GPUs keep no texture - /// compressed, an integrated GPU of unified memory such as Intel's included. The class a - /// device presents where the consumer declares none. No Metal counterpart. - pub fn of_vendor(vendor_id: u32) -> MacClass { - match vendor_id == APPLE { - true => MacClass::AppleSilicon, - false => MacClass::IntelOrAmd, - } - } - - /// The `maxThreadgroupMemoryLength` Metal answers on a Mac of this class: 32,768 bytes on an - /// Apple silicon Mac (an Apple M3 Max, macOS 27.0.1), 65,536 on a Mac with an Intel or AMD - /// GPU (an Intel UHD 630 and an AMD Radeon Pro 5300M, macOS 26.7.1). A device answers the - /// lower of it and its own `maxComputeSharedMemorySize` - /// (`DeviceProperties::max_threadgroup_memory_length`). - pub(crate) fn max_threadgroup_memory_length(self) -> u64 { - match self { - MacClass::AppleSilicon => 32 << 10, - MacClass::IntelOrAmd => 64 << 10, - } - } -} - -/// The class of Mac a device of `identity`, its class declared as `declared`, presents: the one -/// place the runtime decides it. Every answer that differs between an Apple silicon Mac and a Mac -/// with an Intel or AMD GPU reads it: because the first compresses -/// ([`DeviceProperties::lossless_compression`]: a new `Private` texture's contents, a blit's -/// canonical encodings, a `half` NaN clear's sign), because the second adds a sampler's LOD bias -/// to every sample's level (`sampler.rs`), and because their GPUs' threadgroup memory differs -/// ([`DeviceProperties::max_threadgroup_memory_length`]). -fn presented_class(identity: &DeviceIdentity, declared: Option) -> MacClass { - declared.unwrap_or_else(|| MacClass::of_vendor(identity.vendor_id)) -} - -impl DeviceProperties { - /// The properties of the device `identity` names, created with `description` (what it - /// enables), whose compile-layer device is `compile`, presenting the Mac class `mac_class` - /// declares (`None`: its GPU's). - pub(crate) fn new( - identity: DeviceIdentity, - description: DeviceDescription, - compile: &metal2vulkan::device::Device, - mac_class: Option, - ) -> DeviceProperties { - let mac_class = presented_class(&identity, mac_class); - let lossless_compression = mac_class == MacClass::AppleSilicon; - let metal = compile.metal_properties(); - let max_buffer_length = identity - .device_local_heap - .map_or(metal.max_buffer_length, |heap| { - metal.max_buffer_length.min(working_set_buffer_bound(heap)) - }); - let [width, height, depth] = metal.max_threads_per_threadgroup.map(u64::from); - let texture_sample_counts = metal.raster_sample_counts & identity.sampled_sample_counts; - let max_vertex_amplification_count = if description.has(VkFeature::Multiview) { - MAX_VERTEX_AMPLIFICATION - } else { - 1 - }; - DeviceProperties { - name: identity.name, - kind: identity.kind, - has_unified_memory: identity.kind.has_unified_memory(), - lossless_compression, - vendor_id: identity.vendor_id, - device_id: identity.device_id, - device_uuid: identity.device_uuid, - pci_bus: identity.pci_bus, - drm_render: identity.drm_render, - api_version: identity.api_version, - max_buffer_length, - max_threads_per_threadgroup: Size::new(width, height, depth), - max_threadgroup_memory_length: u64::from( - compile.profile().limits().max_compute_shared_memory_size, - ) - .min(mac_class.max_threadgroup_memory_length()), - argument_buffers_support: metal.argument_buffers_tier, - max_argument_buffer_sampler_count: argument_buffer_sampler_count( - metal2vulkan::pipeline::heap_sampler_capacity(compile.profile()), - identity.max_sampler_allocation_count, - ), - read_write_texture_support: metal.read_write_texture_tier, - supports_32bit_float_filtering: metal.supports_32bit_float_filtering, - max_viewports: identity.max_viewports, - gpu_core_count: identity.gpu_core_count, - raster_order_groups: description.has(VkFeature::FragmentShaderPixelInterlock), - texture_sample_counts, - programmable_sample_positions: super::sample_positions::programmable( - compile.profile(), - texture_sample_counts, - ), - max_vertex_amplification_count, - pull_model_interpolation: compile.profile().interpolation_function_needs().is_empty(), - mac_class, - driver_defects: driver_defects::of(&description), - driver_facts: description.driver_facts(), - description, - } - } - - /// The class of Mac the device presents: the one - /// [`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class) declares, else its GPU's - /// ([`MacClass::of_vendor`]). - pub(crate) fn mac_class(&self) -> MacClass { - self.mac_class - } - - /// `areRasterOrderGroupsSupported`: the pixel interlock is enabled - /// (`fragmentShaderPixelInterlock`), so the compile layer orders the raster order groups of - /// every fragment function the device draws as Metal does: its body runs in the pixel's - /// ordered critical section (`PixelInterlockOrderedEXT`). Without it the answer is no: a device - /// with only the sample interlock orders the groups of a function that runs per sample alone, - /// and on any device a group holding only color outputs the function does not read compiles - /// without an interlock, ordered by blending's own rasterization order; neither is every group - /// Metal's answer promises. - pub fn are_raster_order_groups_supported(&self) -> Result { - Query::RasterOrderGroups.answer(self.raster_order_groups) - } - - /// `isDepth24Stencil8PixelFormatSupported`: no, on every device, as Metal answers on an - /// Apple GPU (an M3 Max under macOS 26.7 and an M4 under 27.0.1), whose Metal stops a - /// texture and an attachment of `Depth24Unorm_Stencil8` and `X24_Stencil8` as of no format - /// (it describes neither: [`Device::pixel_format_info`](crate::Device::pixel_format_info)). Every device answers as Apple's GPU, whatever its Vulkan - /// driver's `D24_UNORM_S8_UINT`, so one guest gets one answer on every vendor. - pub fn is_depth24_stencil8_pixel_format_supported(&self) -> Result { - Query::Depth24Stencil8.answer(false) - } - - /// `areProgrammableSamplePositionsSupported`: the device enables `VK_EXT_sample_locations`, - /// has `variableSampleLocations`, and takes custom sample locations - /// (`sampleLocationSampleCounts`) at every sample count above 1 it renders textures at - /// ([`DeviceProperties::supports_texture_sample_count`]), as Metal takes custom positions at - /// those (measured on an M4: 2 and 4, not 1; `sample_positions.rs`). - pub fn are_programmable_sample_positions_supported(&self) -> Result { - Query::ProgrammableSamplePositions.answer(self.programmable_sample_positions) - } - - /// `supportsTextureSampleCount:`: a texture of `count` samples can be a color and a depth - /// render target and be read in a shader as `texture2d_ms` / `depth2d_ms`, which is what - /// Metal's answer promises. `count` is in every one of `framebufferColorSampleCounts`, - /// `framebufferDepthSampleCounts`, `sampledImageColorSampleCounts` and - /// `sampledImageDepthSampleCounts`, and is one an Apple GPU takes: 1, 2 or 4 (Apple9's - /// "Maximum sample count in render passes with MSAA" is 4), so a device that renders 8 or 16 - /// samples answers no to them as Metal does, and stops such a texture. A count that is no - /// Vulkan sample count (0, 3, above 64) is not supported. - /// - /// Integer formats are left out of the answer (`framebufferIntegerColorSampleCounts`, - /// `sampledImageIntegerSampleCounts`), as stencil-only formats are: a device that guarantees - /// every integer format one sample only would otherwise answer no to every count above 1, - /// though some of its integer formats take more. Creating an integer texture at a count its - /// format does not take is refused, `Unsupported` with `Feature::TextureSampleCount` naming - /// the device property it lacks ([`Device::new_texture`](super::Device::new_texture)). - pub fn supports_texture_sample_count(&self, count: u64) -> Result { - Query::TextureSampleCount.answer(sample_count_supported(self.texture_sample_counts, count)) - } - - /// What a texture's descriptor takes of the device (`texture_descriptor`): the sample counts - /// [`supports_texture_sample_count`](Self::supports_texture_sample_count) answers yes for, - /// which a multisample texture takes. - pub(super) fn texture_rules(&self) -> TextureRules { - TextureRules { - sample_counts: self.texture_sample_counts, - } - } - - /// `supportsPullModelInterpolation`: a fragment function may read an `interpolant` through - /// every interpolation function, `interpolate_at_center`, `_centroid`, `_sample` and - /// `_offset`, which the compile layer lowers to `GLSL.std.450`'s interpolation functions: the - /// device has `sampleRateShading`, and on a portability-subset device (MoltenVK) - /// `shaderSampleRateInterpolationFunctions` - /// ([`DeviceProfile::interpolation_function_needs`](metal2vulkan::device::DeviceProfile::interpolation_function_needs) - /// is empty). Without them only `interpolate_at_center` compiles, and a function that reads - /// otherwise is refused, `Unsupported(PullModelInterpolation)`. What differs from Metal: an - /// offset is read on the device's grid and within its range - /// (`PrecisionNote::DeviceInterpolationOffset`), a centroid where Vulkan puts it - /// (`PrecisionNote::MultisamplePosition`), a perspective interpolant read at a sample or an - /// offset on RADV is the driver's extrapolation from the pixel center - /// (`PrecisionNote::ExtrapolatedInterpolation`), and a draw at custom sample positions through - /// a function that reads at a sample is refused - /// ([`RuntimeGap::InterpolateAtSampleWithPositions`]). - pub fn supports_pull_model_interpolation(&self) -> Result { - Query::PullModelInterpolation.answer(self.pull_model_interpolation) - } - - /// `supportsSamplerReductionMode`: no, on every device, as Metal answers on an Apple M4 - /// (macOS 27.0.1). There a sampler's minimum or maximum reduction reads the weighted average - /// (Metal's validation layer refuses one), and so does every sampler the runtime makes and - /// every constexpr sampler the compile layer lowers, whatever the device's - /// `samplerFilterMinmax`. - pub fn supports_sampler_reduction_mode(&self) -> Result { - Query::SamplerReductionMode.answer(false) - } - - /// `supportsVertexAmplificationCount:`: `count` is at most Metal's 8 with `multiview` enabled - /// (1 without it), which render encoders draw as views where multiview draws them as Metal - /// does, else one amplification at a time. A count of 0 is supported, as Metal answers: a draw - /// at it draws nothing, as plain Metal's (`render.rs`). - pub fn supports_vertex_amplification_count(&self, count: u64) -> Result { - Query::VertexAmplificationCount.answer(amplification_count_supported( - self.max_vertex_amplification_count, - count, - )) - } - - /// `supportsRasterizationRateMapWithLayerCount:`: 1 or 2 layers, the layer counts Apple's - /// map compile was measured with and the compile layer reproduces on every device. - pub fn supports_rasterization_rate_map_with_layer_count( - &self, - count: u64, - ) -> Result { - Query::RasterizationRateMapLayerCount.answer(rate_map_layers_supported(count)) - } - - /// `supportsTextureWriteRoundingMode:` (Apple SPI): yes for Metal's raw 0 to 2, every mode - /// a pipeline descriptor's `texture_write_rounding_mode` takes on every device - /// ([`TextureWriteRoundingMode::from_raw`](metal2vulkan::metal::TextureWriteRoundingMode::from_raw)), - /// as an M4 answers (macOS 27.0.1); no for 3 and above. - pub fn supports_texture_write_rounding_mode(&self, mode: u64) -> bool { - metal2vulkan::metal::TextureWriteRoundingMode::from_raw(mode).is_ok() - } - - /// Whether this device keeps the GPU's writes out of read-only memory as Metal does - /// everywhere Metal does: no-copy memory made with - /// [`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT), Metal's private - /// option bit 24, which is what marks a range read-only (the companion of Apple's - /// `replaceBackingWithRanges:readOnly:`). Metal has no query of its own for this: it is one of - /// the runtime's, so that a consumer can tell what it may stop guarding. - /// - /// This answers yes only where the memory itself takes the GPU's writes nowhere, as Metal's - /// does, so that every shape Metal answers holds: a shader's stores through a buffer slot or - /// through an address loaded out of an argument buffer or a pointer, a blit fill and a - /// visibility result all complete and leave the pages as they were, and a colour attachment with - /// [`StoreAction::Store`](crate::StoreAction::Store), a resolve target or a depth or stencil - /// attachment over such memory ends its command buffer in error. On macOS, where the device - /// imports the pages through a read-only view of them, that is yes. Elsewhere the memory is a - /// copy of the pages whose GPU writes are dropped, announced - /// ([`Degradation::CopiedHostPages`](crate::Degradation::CopiedHostPages)), and this answers - /// no: the CPU and the command buffers committed after a writer's completion read the pages' - /// own bytes, but a command buffer committed before it may read the GPU's writes. A render - /// pass's store-out into such memory faults its command buffer on either. - pub fn drops_gpu_writes_to_read_only_memory(&self) -> bool { - crate::read_only_view::VIEWS_DROP_WRITES - } -} - -/// Metal's rule for `minimumLinearTextureAlignmentForPixelFormat:` of `format`: 16 bytes for every -/// format a buffer can back, as Metal answers on an Apple M3 Max and an M4, the least the device -/// answers (`Device::minimum_linear_texture_alignment_for_pixel_format`); refused, `Invalid` with -/// `BufferTextureProblem::NotLinear`, for a compressed, depth or stencil format, on which Metal's -/// query asserts, and for a format Metal describes none of, on which it asserts too. -pub(crate) fn linear_alignment_rule(format: PixelFormat) -> Result { - linear_alignment(format).map_err(|problem| { - invalid( - "minimum_linear_texture_alignment_for_pixel_format", - Problem::BufferTexture(problem), - ) - }) -} - -/// Whether `count` samples is one of the Vulkan sample counts `flags` holds: a power of two whose -/// bit is set (`VkSampleCountFlagBits` are the counts themselves). -pub(super) fn sample_count_supported(flags: SampleCountFlags, count: u64) -> bool { - count.is_power_of_two() - && u32::try_from(count).is_ok_and(|bit| flags.contains(SampleCountFlags::from_raw(bit))) -} - -/// Whether a vertex amplification count of `count` is in `[0, max]`, as Metal answers (0 too). -pub(super) fn amplification_count_supported(max: u64, count: u64) -> bool { - count <= max -} - -/// `supportsRasterizationRateMapWithLayerCount:`: 1 to [`RATE_MAP_LAYERS`], as Metal answers -/// (a map of no layers is made all the same, as Metal makes it). -pub(super) fn rate_map_layers_supported(count: u64) -> bool { - (1..=RATE_MAP_LAYERS).contains(&count) -} - -/// Metal's public device queries whose runtime piece may not be built yet. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Query { - /// `areRasterOrderGroupsSupported`. - RasterOrderGroups, - /// `isDepth24Stencil8PixelFormatSupported`. - Depth24Stencil8, - /// `areProgrammableSamplePositionsSupported`. - ProgrammableSamplePositions, - /// `supportsTextureSampleCount:`. - TextureSampleCount, - /// `supportsVertexAmplificationCount:`. - VertexAmplificationCount, - /// `supportsRasterizationRateMapWithLayerCount:`. - RasterizationRateMapLayerCount, - /// `minimumLinearTextureAlignmentForPixelFormat:`. - MinimumLinearTextureAlignment, - /// `supportsSamplerReductionMode`. - SamplerReductionMode, - /// `supportsPullModelInterpolation`. - PullModelInterpolation, -} - -impl Query { - /// Every query, in declaration order. - pub const ALL: [Query; 9] = [ - Query::RasterOrderGroups, - Query::Depth24Stencil8, - Query::ProgrammableSamplePositions, - Query::TextureSampleCount, - Query::VertexAmplificationCount, - Query::RasterizationRateMapLayerCount, - Query::MinimumLinearTextureAlignment, - Query::SamplerReductionMode, - Query::PullModelInterpolation, - ]; - - /// Metal's selector. - pub fn selector(self) -> &'static str { - match self { - Query::RasterOrderGroups => "areRasterOrderGroupsSupported", - Query::Depth24Stencil8 => "isDepth24Stencil8PixelFormatSupported", - Query::ProgrammableSamplePositions => "areProgrammableSamplePositionsSupported", - Query::TextureSampleCount => "supportsTextureSampleCount:", - Query::VertexAmplificationCount => "supportsVertexAmplificationCount:", - Query::RasterizationRateMapLayerCount => "supportsRasterizationRateMapWithLayerCount:", - Query::MinimumLinearTextureAlignment => "minimumLinearTextureAlignmentForPixelFormat:", - Query::SamplerReductionMode => "supportsSamplerReductionMode", - Query::PullModelInterpolation => "supportsPullModelInterpolation", - } - } - - /// The runtime piece the query's answer waits on, while it is not built; `None` once it is, as - /// every query's is. - pub fn gap(self) -> Option { - match self { - Query::ProgrammableSamplePositions - | Query::RasterOrderGroups - | Query::VertexAmplificationCount - | Query::RasterizationRateMapLayerCount - | Query::Depth24Stencil8 - | Query::TextureSampleCount - | Query::MinimumLinearTextureAlignment - | Query::SamplerReductionMode - | Query::PullModelInterpolation => None, - } - } - - /// The device's answer `device`, or the gap the query waits on. - fn answer(self, device: T) -> Result { - match self.gap() { - Some(gap) => Err(gap), - None => Ok(device), - } - } -} - -#[cfg(test)] -impl DeviceProperties { - /// The device's answers of the gated queries, gaps aside, for tests. - pub(super) fn device_answers(&self) -> DeviceAnswers { - DeviceAnswers { - raster_order_groups: self.raster_order_groups, - texture_sample_counts: self.texture_sample_counts, - max_vertex_amplification_count: self.max_vertex_amplification_count, - pull_model_interpolation: self.pull_model_interpolation, - } - } -} - -/// The device's answers of the gated queries (tests only). -#[cfg(test)] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct DeviceAnswers { - pub raster_order_groups: bool, - pub texture_sample_counts: SampleCountFlags, - pub max_vertex_amplification_count: u64, - pub pull_model_interpolation: bool, -} diff --git a/crates/metal2vulkan-runtime/src/check_draw.rs b/crates/metal2vulkan-runtime/src/check_draw.rs deleted file mode 100644 index 23d6ccd06..000000000 --- a/crates/metal2vulkan-runtime/src/check_draw.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! The draw of the device's in-place check of render targets (`in_place_check.rs`): the crate's -//! own modules (`bind::check_draw_modules`, one triangle writing zero), and for each color format -//! a render pass that loads and stores its one color in `GENERAL` and the pipeline in it, made at -//! the format's first draw and kept for the check's class; drawn into an image in place through a -//! scissor of its last column ([`Texture::draw_in_place_column`](crate::Texture)), so that a -//! device whose draws write back the bytes past a row's last texels fails the check. - -use crate::device::device_error; -use crate::error::{internal, vulkan, Error}; -use crate::{exit_guard, release, Device}; -use ash::vk; -use metal2vulkan::bind::check_draw_modules; - -/// The check draw's objects for one class's rounds: its shader modules and pipeline layout, and -/// each color format's render pass and pipeline. Released as it goes. -pub(crate) struct CheckDraw { - device: Device, - vertex: vk::ShaderModule, - fragment: vk::ShaderModule, - layout: vk::PipelineLayout, - formats: Vec<(vk::Format, vk::RenderPass, vk::Pipeline)>, -} - -/// One draw's target: an image's view and its framebuffer in the format's pass, released as it -/// goes, once its submission completed. -pub(crate) struct CheckTarget<'a> { - draw: &'a CheckDraw, - pass: vk::RenderPass, - pipeline: vk::Pipeline, - view: vk::ImageView, - framebuffer: vk::Framebuffer, - extent: [u32; 2], -} - -impl CheckDraw { - /// The draw's modules and layout on `device`. - pub(crate) fn new(device: &Device) -> Result { - let modules = check_draw_modules(device.compile_device()).map_err(device_error)?; - let raw: &ash::Device = device.shared().vk(); - let mut draw = CheckDraw { - device: device.clone(), - vertex: vk::ShaderModule::null(), - fragment: vk::ShaderModule::null(), - layout: vk::PipelineLayout::null(), - formats: Vec::new(), - }; - let module = |words: &[u32]| { - let info = vk::ShaderModuleCreateInfo::default().code(words); - // SAFETY: the code is live SPIR-V words for the call. - unsafe { raw.create_shader_module(&info, None) }.map_err(vulkan) - }; - draw.vertex = module(&modules.vertex)?; - draw.fragment = module(&modules.fragment)?; - let info = vk::PipelineLayoutCreateInfo::default(); - // SAFETY: `info` is live for the call. - draw.layout = unsafe { raw.create_pipeline_layout(&info, None) }.map_err(vulkan)?; - Ok(draw) - } - - /// The render pass and pipeline of `format`, made at its first draw. - fn of_format(&mut self, format: vk::Format) -> Result<(vk::RenderPass, vk::Pipeline), Error> { - if let Some(&(_, pass, pipeline)) = self.formats.iter().find(|(f, _, _)| *f == format) { - return Ok((pass, pipeline)); - } - let raw: &ash::Device = self.device.shared().vk(); - let general = vk::ImageLayout::GENERAL; - let attachments = [vk::AttachmentDescription::default() - .format(format) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(vk::AttachmentLoadOp::LOAD) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(general) - .final_layout(general)]; - let colors = [vk::AttachmentReference::default() - .attachment(0) - .layout(general)]; - let subpasses = [vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colors)]; - let info = vk::RenderPassCreateInfo::default() - .attachments(&attachments) - .subpasses(&subpasses); - // SAFETY: `info` and its arrays are live for the call. - let pass = unsafe { crate::creation::render_pass(raw, &info) }?; - let pipeline = self.pipeline(pass); - let pipeline = match pipeline { - Ok(pipeline) => pipeline, - Err(error) => { - // SAFETY: nothing used the pass. - unsafe { release::object(raw, pass) }; - return Err(error); - } - }; - self.formats.push((format, pass, pipeline)); - Ok((pass, pipeline)) - } - - /// The draw's pipeline in `pass`: the triangle over the viewport, without blending, writing - /// every component, the viewport and scissor dynamic. - fn pipeline(&self, pass: vk::RenderPass) -> Result { - let raw: &ash::Device = self.device.shared().vk(); - let stages = [ - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(self.vertex) - .name(c"main"), - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::FRAGMENT) - .module(self.fragment) - .name(c"main"), - ]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); - let rasterization = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(vk::PolygonMode::FILL) - .cull_mode(vk::CullModeFlags::NONE) - .front_face(vk::FrontFace::COUNTER_CLOCKWISE) - .line_width(1.0); - let multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::TYPE_1); - let attachments = [vk::PipelineColorBlendAttachmentState::default() - .blend_enable(false) - .color_write_mask(vk::ColorComponentFlags::RGBA)]; - let blend = vk::PipelineColorBlendStateCreateInfo::default().attachments(&attachments); - let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; - let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); - let info = vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&input_assembly) - .viewport_state(&viewport) - .rasterization_state(&rasterization) - .multisample_state(&multisample) - .color_blend_state(&blend) - .dynamic_state(&dynamic) - .layout(self.layout) - .render_pass(pass) - .subpass(0); - // SAFETY: every pointer in `info` outlives the call; no pipeline cache. - let made = - unsafe { raw.create_graphics_pipelines(vk::PipelineCache::null(), &[info], None) }; - let made = made.map_err(|(_, error)| vulkan(error))?; - let made = - (made.first().copied()).ok_or_else(|| internal("the driver made no pipeline"))?; - (self.device.shared()) - .name_pipeline(made, || "metal2vulkan: in-place check draw".to_owned()); - Ok(made) - } - - /// The target of a draw into `image`, a 2D color image of `format` and `extent` with color - /// attachment usage: its view and framebuffer in the format's pass. - pub(crate) fn target( - &mut self, - image: vk::Image, - format: vk::Format, - extent: [u32; 2], - ) -> Result, Error> { - let (pass, pipeline) = self.of_format(format)?; - let raw: &ash::Device = self.device.shared().vk(); - let info = vk::ImageViewCreateInfo::default() - .image(image) - .view_type(vk::ImageViewType::TYPE_2D) - .format(format) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }); - // SAFETY: the image is live, 2D, of `format`, one level and layer at least. - let view = unsafe { crate::creation::image_view(raw, &info) }.map_err(vulkan)?; - let views = [view]; - let [width, height] = extent; - let info = vk::FramebufferCreateInfo::default() - .render_pass(pass) - .attachments(&views) - .width(width) - .height(height) - .layers(1); - // SAFETY: `info` and its array are live for the call; the view is of the pass's format. - let framebuffer = match unsafe { crate::creation::framebuffer(raw, &info) } { - Ok(framebuffer) => framebuffer, - Err(error) => { - // SAFETY: nothing used the view. - unsafe { release::object(raw, view) }; - return Err(error); - } - }; - Ok(CheckTarget { - draw: self, - pass, - pipeline, - view, - framebuffer, - extent, - }) - } -} - -impl Drop for CheckDraw { - fn drop(&mut self) { - // The Vulkan teardown is a section of the exit guard: the check's thread drops it after - // its rounds' sections. - let Some(_busy) = exit_guard::enter() else { - // The process is exiting: the objects are left to its end. - return; - }; - let raw: &ash::Device = self.device.shared().vk(); - // SAFETY: every draw's submission completed (the check waits for each); a null handle is - // a no-op. - unsafe { - for &(_, pass, pipeline) in &self.formats { - release::object(raw, pipeline); - release::object(raw, pass); - } - release::object(raw, self.layout); - release::object(raw, self.fragment); - release::object(raw, self.vertex); - } - } -} - -impl CheckTarget<'_> { - /// Record the draw: the pass over the whole image, loading and storing it, the triangle - /// through a scissor of its last column. - /// - /// # Safety - /// - /// `command_buffer` is recording outside a render pass and only the caller records it; the - /// image is live until it completes, and rests in `GENERAL`. - pub(crate) unsafe fn record(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) { - let [width, height] = self.extent; - let whole = vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent: vk::Extent2D { width, height }, - }; - let column = vk::Rect2D { - offset: vk::Offset2D { - x: width.saturating_sub(1) as i32, - y: 0, - }, - extent: vk::Extent2D { width: 1, height }, - }; - let viewport = vk::Viewport { - x: 0.0, - y: 0.0, - width: width as f32, - height: height as f32, - min_depth: 0.0, - max_depth: 1.0, - }; - let begin = vk::RenderPassBeginInfo::default() - .render_pass(self.pass) - .framebuffer(self.framebuffer) - .render_area(whole); - // SAFETY: the caller's contract; the objects are this draw's, live until it is dropped. - unsafe { - raw.cmd_begin_render_pass(command_buffer, &begin, vk::SubpassContents::INLINE); - raw.cmd_bind_pipeline( - command_buffer, - vk::PipelineBindPoint::GRAPHICS, - self.pipeline, - ); - raw.cmd_set_viewport(command_buffer, 0, &[viewport]); - raw.cmd_set_scissor(command_buffer, 0, &[column]); - raw.cmd_draw(command_buffer, 3, 1, 0, 0); - raw.cmd_end_render_pass(command_buffer); - } - } -} - -impl Drop for CheckTarget<'_> { - fn drop(&mut self) { - // The Vulkan teardown is a section of the exit guard. - let Some(_busy) = exit_guard::enter() else { - // The process is exiting: the objects are left to its end. - return; - }; - let raw: &ash::Device = self.draw.device.shared().vk(); - // SAFETY: the draw's submission completed (the check waits for it). - unsafe { - release::object(raw, self.framebuffer); - release::object(raw, self.view); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/chroma_pairs.rs b/crates/metal2vulkan-runtime/src/chroma_pairs.rs deleted file mode 100644 index 350132a63..000000000 --- a/crates/metal2vulkan-runtime/src/chroma_pairs.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! 4:2:2 textures (`GBGR422`, `BGRG422`): two texels share their chroma, 4 bytes a pair (`G0 B G1 -//! R`, `B G0 R G1`), held as 2-byte texels. -//! -//! - **Metal's answers** (an M4 under macOS 27.0.1, alike plain twice and under -//! API validation where it passes): `newTextureWithDescriptor:` makes either format's 2D -//! texture (of an even width, `texture_descriptor`), `Private` and `Shared`, with `ShaderRead`, -//! `ShaderWrite` or `RenderTarget` usage, at 2 bytes a texel (a 16 x 16 texture allocates 512 -//! bytes). `replaceRegion` and `getBytes`, and blits between a buffer and the texture, move its -//! bytes unchanged. -//! - **The store.** Vulkan's 4:2:2 formats need a sampler Y′CbCr conversion for any view of them -//! (VUID-VkImageViewCreateInfo-format-06415), which neither the binder nor the lowering models -//! (`metal::format`). A 4:2:2 texture's bytes lie in an image of the *carrier*, [`CARRIER`], of -//! the texture's extent, each texel's 2 bytes one carrier texel: a copy's regions and buffer -//! rows are the texture's own, and Vulkan's copies move Metal's bytes. -//! - **What it serves.** Copies: between buffers and the texture, between textures, and the CPU's -//! (`copy_plan.rs`). A storage slot whose function only writes the texture binds the slot's -//! neutral (the binding plan's `IncompatibleBinding` note): plain Metal completes the writes -//! and stores nothing. Refused: a render pipeline state of the format, -//! whose descriptor Metal's validation aborts plain too, and a render pass into the texture. -//! - **Reads and samples** present a decoded twin (`texture/decoded_twin.rs`, announced -//! `carried-decoded-twin`): an `R8G8B8A8_UNORM` image of the texels as Metal reads them -//! (`bind::ChromaDecode`: each texel's own green, its red and blue interpolated with the pair -//! beside it, alpha 1; our probe on an Apple M3 Max under macOS 27.0.1 read, sampled (nearest, -//! linear and bicubic) and gathered both formats bit for bit as such an `RGBA8Unorm` texture), -//! exact, decoded after -//! each write as an ETC2 texture's twin is, on the GPU (`bind::chroma_decode_module`) or a host -//! write's on the CPU. Where the device converts the format itself with Metal's reconstruction -//! (`ycbcr_device.rs`: a sampler Y′CbCr conversion of `G8B8G8R8_422_UNORM` or -//! `B8G8R8G8_422_UNORM` at the midpoint through a linear chroma filter, MoltenVK), the twin holds -//! the device's conversion of the pairs instead, every write's decode a GPU pass that samples -//! the pairs through it (`bind::chroma_sample_module`), announced `decoded-texel-precision` -//! where a command first reads the twin. A texel reads the pair beside it, so a write's decode -//! is of whole rows (a host write of part of a row decodes its rows as the texture then holds -//! them). A heap's texture, a shadow of the heap's bytes in Metal's rows (`texture/heap.rs`), -//! keeps a twin decoded whole after each copy in that moves its rows, through the device's -//! conversion where it converts the pairs, else Metal's decode. Refused: a sparse heap's texture -//! (`RuntimeGap::DecodedHeapTexture`). Only a heap's texture over the caller's host pages has -//! no twin: a command that binds it for a read is refused (`NotImplemented(Format)`, naming the -//! format: `binding_view.rs`). -//! - **Over a buffer's bytes** (an IOSurface plane's, `linear_plan.rs`): no carrier. The bytes -//! are the texture's truth, which its copies, blits and CPU calls move, and its reads and -//! samples present an `R8G8B8A8_UNORM` image of its texels alone, which each copy in writes from -//! the pairs where they lie, Metal's decode or the device's conversion as above -//! (`texture/surface_pairs.rs`), where they lie so; elsewhere it is held in the carrier, and a -//! read of it refused as a heap texture's without a twin is. -//! - **Through handles.** A function that reads texture handles from memory reaches such a -//! texture without a twin as a PVRTC carrier's (`pvrtc.rs`): the neutral texture, announced -//! once ([`Degradation::UnreadableHandleTexture`](super::degradation::Degradation)). - -use super::image_plan::{sample_count, ImageFacts, ImagePlan}; -use super::texture_descriptor::{effective_usage, TextureLayout}; -use metal2vulkan::bind::ChromaDecode; -use metal2vulkan::metal::format::{image_type, FormatMapping}; -use metal2vulkan::metal::{PixelFormat, TextureUsage}; -use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags}; - -/// The format of the image holding a 4:2:2 texture's texels, 2 bytes each (the module docs). -pub(super) const CARRIER: Format = Format::R8G8_UNORM; - -/// The bytes of a 4:2:2 texel. -pub(super) const TEXEL_BYTES: u32 = 2; - -/// Whether `pf` is a 4:2:2 format. -pub(super) fn is_four_two_two(pf: PixelFormat) -> bool { - matches!(pf, PixelFormat::GBGR422 | PixelFormat::BGRG422) -} - -/// The image of a 4:2:2 texture of `layout` with Metal `usage` on a device with `facts`: the -/// carrier's (the module docs), for copies, its reads and samples its decoded twin's; `None` for a -/// texture of another format, or where the device does not copy the carrier (the device's refusal -/// of the format stands). -pub(super) fn plan_pairs( - layout: &TextureLayout, - usage: TextureUsage, - facts: &ImageFacts<'_>, -) -> Option { - let pf = layout.pixel_format; - let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; - if !is_four_two_two(pf) || !facts.optimal(CARRIER).contains(copies) { - return None; - } - let (image_type, flags) = image_type(layout.texture_type)?; - Some(ImagePlan { - pixel_format: pf, - flags, - image_type, - format: CARRIER, - extent: layout.extent, - levels: layout.levels, - layers: layout.layers, - samples: sample_count(layout.samples)?, - usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping: FormatMapping::direct(CARRIER, ImageAspectFlags::COLOR), - // Its decoded twin serves its reads and samples. - unavailable: effective_usage(usage).intersection( - TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, - ), - }) -} - -/// Whether `plan` holds a 4:2:2 texture's texels in the carrier (the module docs). -pub(super) fn holds_pairs(plan: &ImagePlan) -> bool { - is_four_two_two(plan.pixel_format) && plan.format == CARRIER -} - -/// The decode of the 4:2:2 texture whose texels `plan` holds in the carrier; `None` for any other -/// image. -pub(super) fn decode_of(plan: &ImagePlan) -> Option { - ChromaDecode::of(plan.pixel_format).filter(|_| holds_pairs(plan)) -} diff --git a/crates/metal2vulkan-runtime/src/churn_counts.rs b/crates/metal2vulkan-runtime/src/churn_counts.rs deleted file mode 100644 index 397368036..000000000 --- a/crates/metal2vulkan-runtime/src/churn_counts.rs +++ /dev/null @@ -1,567 +0,0 @@ -//! Counts of the objects whose making and release cost a driver more than the call itself, and of -//! the keeps of shadowed textures' merges by who asked for them (`WorkCounts::object_churn`, -//! `WorkCounts::shadow_keeps`), for the lanes and the guest-frame breakdowns: not part of the API. -//! -//! - **Object churn.** MoltenVK 1.4.1 adds each Metal allocation it makes to its device's residency -//! set and commits the set, under one lock for the device (`MVKDevice::makeResident`), and -//! removes and commits again as it lets the allocation go (`removeResidency`): a `VkImage`'s -//! texture (made at its first use), a `VkBuffer` in device-local memory, a buffer view's texture -//! and a host-visible or imported `VkDeviceMemory`'s buffer. So each release counted here is, -//! on MoltenVK, a commit at the release and one at the making before it. The releases of the -//! whole process, by entry point (`release.rs`), and of a device's images and textures, by -//! what owned them. -//! - **Object makings.** The other side of the same ledger: the `vkCreateImage`, -//! `vkCreateBuffer`, `vkCreateImageView`, `vkAllocateMemory`, `vkBindImageMemory` and -//! `vkBindBufferMemory` calls of the whole process, by entry point and by the place in the -//! runtime that asked for one (`creation.rs`, their one door). What a texture or buffer -//! creation made the driver do is then a count of that call's own work, not an inference from a -//! driver floor timed apart, and a count holds under any load where a time does not. Each is -//! also counted for the thread that made it, and a pooled block made ahead for the thread of -//! the call that waited for it, where one did (`ObjectChurn`'s `_this_thread` counts): the -//! device's thread that makes blocks ahead (`memory/ready.rs`) makes them when the device's -//! queue uses pause, so the process's counts over a call take whatever such making fell -//! within it. -//! - **Shadow keeps.** The keeps of merged-back shadows (`shadow_merge.rs`) by the encoder that -//! planned them (a render pass's attachments, a compute dispatch's bindings, a blit), cut to a -//! rectangle or of every texel, and the texels they copy. - -use crate::step_aside::counted_apart; -use crate::work_counts::{CopySite, CopySites, COPY_SITES}; -use std::cell::Cell; -use std::panic::Location; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::LazyLock; - -/// The Vulkan releases of the process MoltenVK commits its residency set at, by entry point. -static VK_RELEASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; - -/// The places in the runtime that released those, the first [`COPY_SITES`] met. -static RELEASE_SITES: LazyLock = LazyLock::new(CopySites::default); - -/// The Vulkan makings of the process a driver charges for, by entry point ([`VkMaking`]). -static VK_MAKINGS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; - -/// The places in the runtime that made those, the first [`COPY_SITES`] met. -static MAKING_SITES: LazyLock = LazyLock::new(CopySites::default); - -/// The releases of [`VK_RELEASES`]'s entry points made on a thread of a device's checks -/// (`step_aside.rs`), which it leaves out: the checks' work, never the program's -/// (`WorkCounts::device_checks`). -static CHECK_RELEASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; - -/// The makings of [`VK_MAKINGS`]'s entry points made on a thread of a device's checks, which it -/// leaves out. -static CHECK_MAKINGS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; - -/// An entry point [`VK_RELEASES`] counts. -#[derive(Clone, Copy)] -pub(crate) enum VkRelease { - Image = 0, - Buffer = 1, - BufferView = 2, - Memory = 3, -} - -/// An entry point [`VK_MAKINGS`] counts: the makings a driver charges for, whose cost one call of -/// the API carries (`creation.rs`). -#[derive(Clone, Copy)] -pub(crate) enum VkMaking { - Image = 0, - Buffer = 1, - ImageView = 2, - Memory = 3, - ImageBinding = 4, - BufferBinding = 5, -} - -/// A release of `what` (`release::object`), called `at`: a check's where a device's check made -/// it ([`CHECK_RELEASES`]). -pub(crate) fn vk_released(what: VkRelease, at: &Location<'static>) { - if counted_apart() { - CHECK_RELEASES[what as usize].fetch_add(1, Ordering::Relaxed); - return; - } - VK_RELEASES[what as usize].fetch_add(1, Ordering::Relaxed); - let command = match what { - VkRelease::Image => "vkDestroyImage", - VkRelease::Buffer => "vkDestroyBuffer", - VkRelease::BufferView => "vkDestroyBufferView", - VkRelease::Memory => "vkFreeMemory", - }; - RELEASE_SITES.count(command, at, 0); -} - -thread_local! { - /// Of [`VK_MAKINGS`], those this thread made, and those another thread made for a call of - /// this thread that waited for them ([`count_on_this_thread`]). - static THIS_THREAD: [Cell; 6] = const { [const { Cell::new(0) }; 6] }; -} - -/// A making of `what` (`creation.rs`), called `at`: a check's where a device's check made it -/// ([`CHECK_MAKINGS`]). -pub(crate) fn vk_made(what: VkMaking, at: &Location<'static>) { - if counted_apart() { - CHECK_MAKINGS[what as usize].fetch_add(1, Ordering::Relaxed); - return; - } - VK_MAKINGS[what as usize].fetch_add(1, Ordering::Relaxed); - THIS_THREAD.with(|counts| { - let count = &counts[what as usize]; - count.set(count.get() + 1); - }); - MAKING_SITES.count(what.command(), at, 0); -} - -/// This thread's makings so far, by [`VkMaking`] ([`THIS_THREAD`]). -pub(crate) fn this_thread_makings() -> [u64; 6] { - THIS_THREAD.with(|counts| counts.each_ref().map(Cell::get)) -} - -/// Count `makings` (by [`VkMaking`]), which another thread made while a call of this one waited -/// for them (a pooled block made ahead, `memory/ready.rs`), as this thread's. -pub(crate) fn count_on_this_thread(makings: [u64; 6]) { - THIS_THREAD.with(|counts| { - for (count, made) in counts.iter().zip(makings) { - count.set(count.get() + made); - } - }); -} - -/// The process's devices' checks' makings of `what` so far. -pub(crate) fn checks_made(what: VkMaking) -> u64 { - CHECK_MAKINGS[what as usize].load(Ordering::Relaxed) -} - -/// The process's devices' checks' releases of `what` so far. -pub(crate) fn checks_released(what: VkRelease) -> u64 { - CHECK_RELEASES[what as usize].load(Ordering::Relaxed) -} - -impl VkMaking { - /// Its Vulkan entry point. - fn command(self) -> &'static str { - match self { - VkMaking::Image => "vkCreateImage", - VkMaking::Buffer => "vkCreateBuffer", - VkMaking::ImageView => "vkCreateImageView", - VkMaking::Memory => "vkAllocateMemory", - VkMaking::ImageBinding => "vkBindImageMemory", - VkMaking::BufferBinding => "vkBindBufferMemory", - } - } -} - -/// What owned an image or a texture as it went. -#[derive(Clone, Copy)] -pub(crate) enum Owned { - /// An image of memory of its own (`Owner::Runtime`). - ImageOwnMemory = 0, - /// A linear image in a buffer's memory (`Owner::Buffer`). - ImageInBuffer = 1, - /// An image in a heap's memory (`Owner::Heap`). - ImageInHeap = 2, - /// A heap's shadow or unaliased image, a view's shadow, a sparse image (its own memory). - ImageOther = 3, - /// A program's texture whose storage was an image (`Storage::Image`), not a heap's. - TextureImage = 4, - /// A heap's texture. - TextureInHeap = 5, - /// A texture over a buffer's bytes in an image of its own (`Storage::Shadow`). - TextureShadow = 6, - /// A texture over a buffer's bytes as a linear image of them (`Storage::Alias`). - TextureAlias = 7, - /// A texture over a buffer's bytes as texels (`Storage::Texels`). - TextureTexels = 8, -} - -/// What a recycler parks (`recycle.rs`). -#[derive(Clone, Copy)] -pub(crate) enum Recycled { - Image = 0, - Buffer = 1, -} - -/// Who planned a keep ([`ShadowKeeps`]). -#[derive(Clone, Copy)] -pub(crate) enum KeepBy { - Render = 0, - Compute = 1, - Blit = 2, -} - -/// A device's counts of the above. -#[derive(Default)] -pub(crate) struct ChurnCounters { - owned: [AtomicU64; 9], - /// By [`Recycled`]: the objects a making took from a recycler, parked there, and let go of - /// past its bounds (`recycle.rs`). - recycled: [[AtomicU64; 3]; 2], - /// Images swapped out of their textures that left the image recycler's book as they went. - swapped_out_forgotten: AtomicU64, - /// Imports made over host addresses a live import holds some of. - imports_inside_live: AtomicU64, - /// Imports of dma-bufs made beside live imports of dma-bufs of some of the same pages. - dma_buf_imports_beside_live: AtomicU64, - /// No-copy buffers bound inside a live import's memory, with no import of their own. - buffers_bound_in_import: AtomicU64, - /// Imports of a no-copy object's own pages whose guest RAM pages a live chunk import holds. - imports_over_ram_chunk_pages: AtomicU64, - /// By [`KeepBy`], then cut or whole: the keeps, then their texels. - keeps: [[AtomicU64; 4]; 3], -} - -impl ChurnCounters { - /// An image or texture `owned` so went. - pub(crate) fn released(&self, owned: Owned) { - self.owned[owned as usize].fetch_add(1, Ordering::Relaxed); - } - - /// An import was made over host addresses a live import holds some of. - pub(crate) fn import_inside_live(&self) { - self.imports_inside_live.fetch_add(1, Ordering::Relaxed); - } - - /// An import of dma-bufs was made beside live imports of dma-bufs of some of its pages. - pub(crate) fn dma_buf_import_beside_live(&self) { - (self.dma_buf_imports_beside_live).fetch_add(1, Ordering::Relaxed); - } - - /// A no-copy buffer was bound inside a live import's memory, with no import of its own. - pub(crate) fn buffer_bound_in_import(&self) { - self.buffers_bound_in_import.fetch_add(1, Ordering::Relaxed); - } - - /// A no-copy object imported its own pages, some of whose guest RAM pages a live chunk - /// import holds. - pub(crate) fn import_over_ram_chunk_pages(&self) { - (self.imports_over_ram_chunk_pages).fetch_add(1, Ordering::Relaxed); - } - - /// A making took a parked object of `what`. - pub(crate) fn taken(&self, what: Recycled) { - self.recycled[what as usize][0].fetch_add(1, Ordering::Relaxed); - } - - /// An object of `what` went to its recycler. - pub(crate) fn parked(&self, what: Recycled) { - self.recycled[what as usize][1].fetch_add(1, Ordering::Relaxed); - } - - /// `count` parked objects of `what` went, past their recycler's bounds. - pub(crate) fn evicted(&self, what: Recycled, count: usize) { - self.recycled[what as usize][2].fetch_add(count as u64, Ordering::Relaxed); - } - - /// An image swapped out of its texture, which the image recycler's book held as live, left - /// the book as it went (`recycle.rs`, "The book"). - pub(crate) fn swapped_out_forgotten(&self) { - self.swapped_out_forgotten.fetch_add(1, Ordering::Relaxed); - } - - /// A keep planned `by`, cut to a rectangle or not, of `texels`. - pub(crate) fn kept(&self, by: KeepBy, cut: bool, texels: u64) { - let row = &self.keeps[by as usize]; - let at = if cut { 0 } else { 2 }; - row[at].fetch_add(1, Ordering::Relaxed); - row[at + 1].fetch_add(texels, Ordering::Relaxed); - } - - /// The counts now. - pub(crate) fn snapshot(&self) -> (ObjectChurn, ShadowKeeps) { - let owned = |o: Owned| self.owned[o as usize].load(Ordering::Relaxed); - let vk = |r: VkRelease| VK_RELEASES[r as usize].load(Ordering::Relaxed); - let made = |m: VkMaking| VK_MAKINGS[m as usize].load(Ordering::Relaxed); - let this_thread = this_thread_makings(); - let mine = |m: VkMaking| this_thread[m as usize]; - let keep = |by: KeepBy, at: usize| self.keeps[by as usize][at].load(Ordering::Relaxed); - let recycled = - |what: Recycled, at: usize| self.recycled[what as usize][at].load(Ordering::Relaxed); - ( - ObjectChurn { - vk_images_destroyed: vk(VkRelease::Image), - vk_buffers_destroyed: vk(VkRelease::Buffer), - vk_buffer_views_destroyed: vk(VkRelease::BufferView), - vk_memory_freed: vk(VkRelease::Memory), - vk_images_made: made(VkMaking::Image), - vk_buffers_made: made(VkMaking::Buffer), - vk_image_views_made: made(VkMaking::ImageView), - vk_memory_allocations: made(VkMaking::Memory), - vk_image_bindings: made(VkMaking::ImageBinding), - vk_buffer_bindings: made(VkMaking::BufferBinding), - vk_images_made_this_thread: mine(VkMaking::Image), - vk_buffers_made_this_thread: mine(VkMaking::Buffer), - vk_image_views_made_this_thread: mine(VkMaking::ImageView), - vk_memory_allocations_this_thread: mine(VkMaking::Memory), - vk_image_bindings_this_thread: mine(VkMaking::ImageBinding), - vk_buffer_bindings_this_thread: mine(VkMaking::BufferBinding), - making_sites: MAKING_SITES.read(), - making_sites_dropped: MAKING_SITES.dropped(), - images_own_memory: owned(Owned::ImageOwnMemory), - images_in_buffers: owned(Owned::ImageInBuffer), - images_in_heaps: owned(Owned::ImageInHeap), - images_other: owned(Owned::ImageOther), - textures_image: owned(Owned::TextureImage), - textures_in_heaps: owned(Owned::TextureInHeap), - textures_shadow: owned(Owned::TextureShadow), - textures_alias: owned(Owned::TextureAlias), - textures_texels: owned(Owned::TextureTexels), - images_recycled: recycled(Recycled::Image, 0), - images_parked: recycled(Recycled::Image, 1), - images_evicted: recycled(Recycled::Image, 2), - swapped_out_images_forgotten: self.swapped_out_forgotten.load(Ordering::Relaxed), - buffers_recycled: recycled(Recycled::Buffer, 0), - buffers_parked: recycled(Recycled::Buffer, 1), - buffers_evicted: recycled(Recycled::Buffer, 2), - imports_inside_live: self.imports_inside_live.load(Ordering::Relaxed), - dma_buf_imports_beside_live: (self.dma_buf_imports_beside_live) - .load(Ordering::Relaxed), - buffers_bound_in_import: self.buffers_bound_in_import.load(Ordering::Relaxed), - imports_over_ram_chunk_pages: self - .imports_over_ram_chunk_pages - .load(Ordering::Relaxed), - release_sites: RELEASE_SITES.read(), - release_sites_dropped: RELEASE_SITES.dropped(), - }, - ShadowKeeps { - render_cut: keep(KeepBy::Render, 0), - render_cut_texels: keep(KeepBy::Render, 1), - render_whole: keep(KeepBy::Render, 2), - render_whole_texels: keep(KeepBy::Render, 3), - compute_cut: keep(KeepBy::Compute, 0), - compute_cut_texels: keep(KeepBy::Compute, 1), - compute_whole: keep(KeepBy::Compute, 2), - compute_whole_texels: keep(KeepBy::Compute, 3), - blit_cut: keep(KeepBy::Blit, 0), - blit_cut_texels: keep(KeepBy::Blit, 1), - blit_whole: keep(KeepBy::Blit, 2), - blit_whole_texels: keep(KeepBy::Blit, 3), - }, - ) - } -} - -/// Released objects MoltenVK commits its residency set for (the module docs): the process's -/// Vulkan releases by entry point, and a device's images and program textures by what owned them. -/// A field of `WorkCounts`, for the lanes: not part of the API. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct ObjectChurn { - /// `vkDestroyImage` calls of the process. - pub vk_images_destroyed: u64, - /// `vkDestroyBuffer` calls of the process. - pub vk_buffers_destroyed: u64, - /// `vkDestroyBufferView` calls of the process. - pub vk_buffer_views_destroyed: u64, - /// `vkFreeMemory` calls of the process. - pub vk_memory_freed: u64, - /// `vkCreateImage` calls of the process (`creation.rs`). An image a making took from the - /// recycler is not one of these, so this and `images_recycled` are separate tallies and do - /// not sum to the images a run used: reading 0 here beside 2 recycled is a run that made - /// none, not a contradiction. - pub vk_images_made: u64, - /// `vkCreateBuffer` calls of the process. As with `vk_images_made`, a buffer taken from the - /// recycler is not one of these; `buffers_recycled` counts those. - pub vk_buffers_made: u64, - /// `vkCreateImageView` calls of the process. - pub vk_image_views_made: u64, - /// `vkAllocateMemory` calls of the process, the tries a caller that walks the memory types - /// made included. - pub vk_memory_allocations: u64, - /// `vkBindImageMemory` calls of the process. - pub vk_image_bindings: u64, - /// `vkBindBufferMemory` calls of the process. - pub vk_buffer_bindings: u64, - /// Of `vk_images_made`, those of the thread that read these counts: its own calls', and - /// those another thread made while a call of it waited for them (a pooled block made ahead - /// that a creation call found none of and waited for, `memory/ready.rs`), counted on the - /// thread that took the block. What that thread's calls had the driver make, without what - /// the device's other threads made meanwhile, such as a block made ahead for a pool that - /// grew, which no call waited for. Each thread reads its own. - pub vk_images_made_this_thread: u64, - /// As `vk_images_made_this_thread`, of `vk_buffers_made` (a block of buffers made ahead - /// carries one where its buffers take device addresses). - pub vk_buffers_made_this_thread: u64, - /// As `vk_images_made_this_thread`, of `vk_image_views_made`. - pub vk_image_views_made_this_thread: u64, - /// As `vk_images_made_this_thread`, of `vk_memory_allocations` (a block made ahead is one). - pub vk_memory_allocations_this_thread: u64, - /// As `vk_images_made_this_thread`, of `vk_image_bindings`. - pub vk_image_bindings_this_thread: u64, - /// As `vk_images_made_this_thread`, of `vk_buffer_bindings`. - pub vk_buffer_bindings_this_thread: u64, - /// The device's images that went, of memory of their own. - pub images_own_memory: u64, - /// Linear images in buffers' memory. - pub images_in_buffers: u64, - /// Images in heaps' memory. - pub images_in_heaps: u64, - /// Heaps' shadow and unaliased images, views' shadows, sparse images. - pub images_other: u64, - /// The program's textures that went whose storage was an image, not a heap's. - pub textures_image: u64, - /// Heaps' textures. - pub textures_in_heaps: u64, - /// Textures over buffers' bytes in images of their own (shadows). - pub textures_shadow: u64, - /// Textures over buffers' bytes as linear images of them. - pub textures_alias: u64, - /// Textures over buffers' bytes as texels. - pub textures_texels: u64, - /// Images a making took from the recycler, rather than making one (`recycle.rs`). - pub images_recycled: u64, - /// Images that went to the recycler as their textures went, rather than being destroyed. - pub images_parked: u64, - /// Parked images destroyed past the recycler's bounds. - pub images_evicted: u64, - /// Images swapped out of their textures (a texture's first image, which its storage form - /// replaced, `texture/storage_form.rs`) that the recycler's book of live images held and that - /// left it as they were destroyed (`recycle.rs`, "The book"): each a handle that, left there, - /// would have named the next image the driver made at it as the old one's making. - pub swapped_out_images_forgotten: u64, - /// The runtime's buffers a making took from the recycler, rather than making one. - pub buffers_recycled: u64, - /// Buffers that went to the recycler as their last holder went, rather than being destroyed. - pub buffers_parked: u64, - /// Parked buffers destroyed past the recycler's bounds. - pub buffers_evicted: u64, - /// Imports made over host addresses a live import held some of all the same - /// (`host_aliases.rs`, "One page, one import"): a no-copy buffer's or heap's own import (a - /// heap's own buffer's among them) over a live import of another no-copy buffer or heap, or - /// over a live import of a guest RAM's chunk (`host_ram.rs`), and a chunk's import over a - /// live import of a no-copy buffer or heap made as the chunk's was being made (a chunk such an - /// import held pages of before is not imported, `WorkCounts::host_ram_chunks_held_back`, but - /// beside imports of dma-bufs, `dma_buf_imports_beside_live`). A - /// page imported twice, which - /// `VK_EXT_external_memory_host` leaves undefined for a host pointer; every other buffer - /// over pages a live import holds lies inside it (`buffers_bound_in_import`, or a chunk's - /// `WorkCounts::chunk_bound_buffers_made`), imports dma-bufs of its own beside imports of - /// dma-bufs (`dma_buf_imports_beside_live`), or is a copy - /// (`WorkCounts::copied_over_live_imports`). Counted by host address, after each import is - /// made: two made at once over the same pages, each looking before the other's was noted, - /// count. A listed RAM's run imported alone while its chunk's import is made (two dma-bufs of - /// the same pages, `WorkCounts::run_imports_live`) does not. - pub imports_inside_live: u64, - /// No-copy buffers' and heaps' own imports of dma-bufs of their pages, made where live - /// imports of another no-copy buffer's or heap's pages, each of dma-bufs, held some of them - /// (`host_aliases.rs`, "One page, one import"), and guest RAM chunks' imports of one dma-buf - /// of the RAM's source made where such imports held some of their pages (`host_ram.rs`, a - /// listed plan's): two dma-bufs of the same pages, which Vulkan aliases as any two imports of - /// external memory, on a device whose barriers order blits through two imports of the same - /// pages (no `RuntimeDriverDefect::AliasedImportBlitsUnordered`). Each object's made where - /// the pages were a copy before (`WorkCounts::copied_over_live_imports`); each chunk's where - /// it was held back (`WorkCounts::host_ram_chunks_held_back`). - pub dma_buf_imports_beside_live: u64, - /// No-copy buffers bound inside the memory of a live import that holds all their pages, at - /// their offset, with no import of their own (`host_aliases.rs`, "One page, one import"): - /// over part of another no-copy buffer's or heap's bytes. - pub buffers_bound_in_import: u64, - /// Evidence, not a defect count: no-copy buffers' and heaps' own imports of their pages at - /// addresses other than their guest RAM's (a view of scattered runs, `HostMemory::with_runs`) - /// where a live import of one of the RAM's chunks held some of the same RAM pages at the - /// RAM's own addresses as the object's import was made. The same physical pages mapped for - /// the device twice, at two host addresses; counted at the object's import, not at a chunk's - /// import made later over the pages of a live view's. - pub imports_over_ram_chunk_pages: u64, - /// The places that released the images, buffers, buffer views and memory counted above, each - /// with its calls (`regions` unused): the first 32 the process met. - pub release_sites: [CopySite; COPY_SITES], - /// The releases counted above made at places past those 32, which no slot holds: while this - /// is 0 the places account for every release counted here, and past it they do not, so a - /// breakdown read from `release_sites` alone is short by this many. The runtime calls these - /// entry points from far more than 32 places, so a long run reaches it. - pub release_sites_dropped: u64, - /// The places that made the images, buffers, views, memory and bindings counted above, each - /// with its calls (`regions` unused): the first 32 the process met. What a creation call of - /// the API made the driver do, and the line of the runtime that asked for it. - pub making_sites: [CopySite; COPY_SITES], - /// The makings counted above made at places past those 32, as `release_sites_dropped` is for - /// the releases: while it is 0 `making_sites` accounts for every making counted here. - pub making_sites_dropped: u64, -} - -/// The keeps of merged-back shadows by who planned them, cut to a rectangle or of every texel -/// (the module docs). A field of `WorkCounts`, for the lanes: not part of the API. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct ShadowKeeps { - /// A render pass's keeps cut to a rectangle. - pub render_cut: u64, - /// Their texels. - pub render_cut_texels: u64, - /// A render pass's keeps of every texel. - pub render_whole: u64, - /// Their texels. - pub render_whole_texels: u64, - /// A compute dispatch's keeps cut to a rectangle. - pub compute_cut: u64, - /// Their texels. - pub compute_cut_texels: u64, - /// A compute dispatch's keeps of every texel. - pub compute_whole: u64, - /// Their texels. - pub compute_whole_texels: u64, - /// A blit's keeps cut to a rectangle. - pub blit_cut: u64, - /// Their texels. - pub blit_cut_texels: u64, - /// A blit's keeps of every texel. - pub blit_whole: u64, - /// Their texels. - pub blit_whole_texels: u64, -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A device check's makings and releases, on its thread, are counted as the checks' alone, so - /// the process's counts (`ObjectChurn`), which a program's or a case's cost reads, carry none - /// of them. The test's own thread is marked: each test has a thread of its own. - #[test] - fn a_check_s_makings_and_releases_are_its_alone() { - let process = || { - let churn = ChurnCounters::default().snapshot().0; - (churn.vk_memory_allocations, churn.vk_memory_freed) - }; - let checks = || { - ( - checks_made(VkMaking::Memory), - checks_released(VkRelease::Memory), - ) - }; - let (before, before_checks) = (process(), checks()); - crate::step_aside::mark_a_check_s_thread(crate::step_aside::Counted::Apart); - vk_made(VkMaking::Memory, Location::caller()); - vk_released(VkRelease::Memory, Location::caller()); - assert_eq!( - process(), - before, - "the process's counts took a check's work" - ); - assert_eq!(checks(), (before_checks.0 + 1, before_checks.1 + 1)); - } - - /// The in-place check's thread, whose paths carry the program's work too, counts its makings - /// and releases as the process's (`step_aside::Counted::AsTheDevice`). - #[test] - fn a_check_s_makings_through_the_program_s_paths_are_the_process_s() { - let process = || { - let churn = ChurnCounters::default().snapshot().0; - (churn.vk_memory_allocations, churn.vk_memory_freed) - }; - let checks = || { - ( - checks_made(VkMaking::Memory), - checks_released(VkRelease::Memory), - ) - }; - let (before, before_checks) = (process(), checks()); - crate::step_aside::mark_a_check_s_thread(crate::step_aside::Counted::AsTheDevice); - vk_made(VkMaking::Memory, Location::caller()); - vk_released(VkRelease::Memory, Location::caller()); - assert_eq!(process(), (before.0 + 1, before.1 + 1)); - assert_eq!( - checks(), - before_checks, - "the checks' counts took the device's work" - ); - } -} diff --git a/crates/metal2vulkan-runtime/src/clear_reach.rs b/crates/metal2vulkan-runtime/src/clear_reach.rs deleted file mode 100644 index baa0a584d..000000000 --- a/crates/metal2vulkan-runtime/src/clear_reach.rs +++ /dev/null @@ -1,1394 +0,0 @@ -//! An attachment larger than its pass's render area: how far Metal's clear reaches past the -//! render area, and what a `DontCare` load leaves. -//! -//! **Metal**, measured on the M3 Max (macOS 26.7) and an M4 (macOS 27.0.1), every answer the -//! same on both, each case with and without API validation, which takes every one (44 cases). A -//! pass renders over its render area, from the origin (the smallest attachment's extent, or the -//! descriptor's target size), but its attachments' stores reach past it: -//! -//! - **A `Clear` load** of an attachment the pass stores clears it from the origin over the render -//! area rounded up to whole tiles of [`TILE`] pixels a side, clipped to the attachment's level, -//! in a pass with a draw call (one whose primitives cover nothing, or of no vertex, included), -//! and in each layer of a layered pass, with a draw call or not; a pass of one layer without a -//! draw call clears the whole level and slice of a texture Metal keeps losslessly compressed, -//! and the render area's tiles of one it keeps uncompressed ([`clears_whole`]). So for every -//! format measured (`R8Unorm` to `RGBA32Float`, 1 to 16 bytes a pixel, and -//! eight `RGBA8Unorm` or four `RGBA32Float` attachments at 4 samples), at 1, 2 and 4 samples, -//! with a descriptor's tile of 16x16, for `Depth32Float`, `Depth16Unorm`, `Stencil8` and -//! `Depth32Float_Stencil8`, at a level or slice past the first, over render areas of 1x1, -//! 33x33, 40x24, 40x40, 96x8 and 100x100, and whichever tiles the draws touch. Separate depth -//! and stencil textures are measured apart (`depth_stencil_scratch.rs`). -//! - **A `DontCare` load** of an attachment the pass stores keeps its texels in a pass without a -//! draw (or whose draws draw nothing, or no vertex). Where a draw's primitives touch a tile -//! (32x32 pixels at 1 and 2 samples, 32x16 at 4, color and depth alike on both chips), the -//! tile holds zero before the draws (a color, every color attachment of the pass) or the -//! attachment's clear value (depth, stencil); the tiles no primitive touches keep their texels. -//! Which tiles those are depends on where the GPU places the vertices. Separate depth and -//! stencil textures alike, each aspect apart, as one `Depth32Float_Stencil8` texture (an M3 -//! Max, macOS 27.0.1: a `Depth32Float` and a `Stencil8` texture of 128x128, either or both -//! loaded `DontCare` and stored, the other loaded and stored, under draws writing both over -//! small rectangles): 32x32 tiles for both aspects. A draw that neither tests nor writes the -//! depth and stencil (a depth test `Always` without writes, the default stencil state) leaves -//! them their texels in every tile it touches, one texture or separate ones, where the runtime -//! clears them (`docs/FAST-PATHS.md`'s known gaps). -//! - **A `DontCare` load's clear depth** is clamped to `[0, 1]` as a `Clear` load's is (2.0 -//! reads 1.0, -1.0 reads 0), and a NaN one is Metal's NaN clear (`nan_clear.rs`): the tiles -//! hold `0x7fc00000` (a 32-bit float depth) or 0 (`Depth16Unorm`), and a draw tests against it -//! as Metal's test orders a NaN, above every value (the M3 Max, macOS 27.0.1, a 32-bit float -//! and a 16-bit depth, one texture and separate ones, stored and not, without API validation; -//! API validation stops such a pass, as one whose `Clear` load holds it: "clear depth (nan) is -//! outside of the range [0..1]"). -//! - **A `DontCare` load** of an attachment the pass does not store (`DontCare`) reads the same -//! wherever a fragment reads it: zero (a color) or the pass's clear value (a stencil), never its -//! earlier texels (an M3 Max, macOS 27.0.1, lane `dont_care_unstored`: an `RG16Float` second -//! color a framebuffer fetch reads and a `Stencil8` a stencil test reads, over 224x128 and -//! 128x128 targets, in a pass whose first draw reaches some tiles and a later one every tile, a -//! pass of the reading draw alone, and a pass of no fetch). Separate depth and stencil textures -//! read the same, each aspect apart (a `Depth32Float` and a `Stencil8` texture read by a depth -//! and a stencil test over the same targets, with and without API validation): an aspect loaded -//! `DontCare` and not stored reads the clear value whether the other aspect is so loaded or is -//! loaded and stored, which reads its texels. -//! - A `Load` keeps the texels past the render area, and a `DontCare` store stores nothing. -//! -//! **The runtime** gives the `Clear` load's answer and the `DontCare` load's near-equivalent, as -//! the encoder ends ([`dont_care_loads`], [`ReachClears`]): a pass has a draw call where the -//! encoder encoded one, whether it draws or not, and draws where a draw call drew vertices, -//! indices, patches or meshes through a pipeline that rasterizes; an execution of an indirect -//! command buffer's render commands, or a tile dispatch, is taken as a draw call that draws (both -//! unmeasured). -//! -//! - A `DontCare`-loaded attachment the pass stores (but memoryless ones) loads in a pass whose -//! draws reach no tile, and clears to zero (a color) or -//! its clear value (depth, stencil) in one whose draws reach every tile, both Metal's answer -//! ([`PassReach`]). In a pass whose draws reach the tiles their primitives touch, it clears -//! too: Metal's answer in each tile a draw touches, and in a tile none touches, where Metal -//! keeps the texels, a near-equivalent announced once per device -//! (`Degradation::DontCareLoadTiles`); the exact path is not taken. Such a pass clears only the -//! tiles its draws' viewports and scissors reach ([`DrawnArea`]), at the encoder's tile size (the -//! pass's `tileWidth` and `tileHeight`, which set Metal's grid, as measured), a clear before the -//! pass, and loads: every other tile keeps its texels, Metal's answer (a draw writes no pixel -//! outside them), and a pass whose draws reach no pixel loads, as one whose draws draw nothing. -//! An aspect of separate depth and stencil textures takes the same answers in the scratch image -//! the pass renders them through (`depth_stencil_scratch.rs`): it loads by the copy into that -//! image, and its tiles are cleared after the copy. Where it cannot be copied in (a multisampled -//! aspect copied by draws) the scratch clears it over the render area, the near-equivalent -//! wherever the draws do not reach every tile, announced (`Degradation::DontCareLoadTiles`). -//! - A depth whose `DontCare` load clears, at a NaN clear depth, which a Vulkan clear value does -//! not hold: a `Depth16Unorm` clears to 0, Metal's answer, and a 32-bit float depth to 1.0, the -//! value Metal's test orders a NaN nearest, where a fragment at exactly 1.0 tests otherwise and -//! the depth stored holds 1.0, announced (`Degradation::SignedDepthTest`). A clear depth out of -//! `[0, 1]` is clamped, Metal's answer (`render_pass.rs`). -//! - A `DontCare`-loaded attachment the pass does not store (but memoryless ones), in a pass whose -//! draws reach a tile, clears to zero (a color) or its clear value (depth, stencil) over the -//! render area under `UnstoredDontCarePolicy::Cleared`, and under the default `Driver` on a -//! driver measured to run that clear no slower than its `DONT_CARE` load -//! (`DriverFact::UnstoredClearNoSlower`) ([`UnstoredLoads`]): by the load operation of the -//! pass's first instance, or before the pass where that instance leaves it out (as below); an -//! aspect of separate depth and stencil textures by the load operation of the scratch image the -//! pass renders them through (`depth_stencil_scratch.rs`), which copies nothing into that -//! aspect, each aspect apart. Metal's answer wherever a fragment reads it, so no notice: no -//! fragment reads a tile no draw touches. What the pass leaves in it is a -//! `DontCare` store's (`kept_bytes.rs`, `dont-care-store`). On every other driver under the -//! default it stays `DontCare`, the driver's faster form, announced -//! (`Degradation::DontCareUnstoredLoad`). In a pass whose draws reach no tile it stays -//! `DontCare`. -//! - A `DontCare`-loaded memoryless color attachment clears to zero in a pass whose draws reach a -//! tile: Metal's answer in every tile a fragment reads it (an Apple M4), and it is -//! never stored, so the answer is exact. -//! - A pass without a draw call whose attachments all load with `Load` or `DontCare` and store -//! with `Store` or `DontCare`, resolving nothing, and that sets no depth/stencil state with depth -//! writes, changes no texel: it records nothing (`render/untouched.rs`), before any of the steps -//! here. -//! - Each `Clear`-loaded attachment (a converted one too) whose clear reaches past the render -//! area ([`reach`]) is cleared there before the pass by a render pass of its own: the attachment -//! alone, loaded and stored, over the pass's layers, `vkCmdClearAttachments` clearing the reach -//! of its cleared aspects, and the pass then loads it ([`ReachClears::load_in_pass`]). Neither -//! is a load operation's clear: on a device that renders through Metal (MoltenVK) that clears -//! a pass without a draw over the whole attachment, as Metal does, so the reach pass's would, -//! and the pass's own would in a pass whose draw calls draw nothing (lane `clear_reach` on -//! MoltenVK). A stand-in's copy back to its texture covers the reach (`attachment_stand_in.rs`). -//! So is a cleared attachment the pass's first instance leaves out where no whole-subresource -//! clear may stand for its load operation (`render.rs`'s `cleared_ahead`), over the render area -//! where it stores nothing. -//! - A depth a pass at custom sample positions clears, on a driver that stores and tests a -//! depth its pass clears at the standard positions there -//! (`DriverFact::ClearedDepthAtStandardPositions`), is cleared before the pass the same way -//! wherever its clear reaches, over the render area where the pass does not store it, a -//! memoryless one too, and the pass then loads it: a pass that loads the depth takes the -//! positions (`sample_positions.rs`). -//! - A pass whose first instance records inline clears none before it: that instance, begun at a -//! draw that records (of a vertex and an instance at least), renders over the reach its colors -//! share, and its load operations' clear reaches it (`render/inline_first.rs`). Unmeasured on -//! MoltenVK past the render area. - -use super::clear_value; -use super::encoder::EncoderCore; -use super::error::Error; -use super::render_pass::{AspectClear, PassLayout, Target}; -use super::render_target::{self, FramebufferObject, RenderPassObject}; -use super::render_values::{LoadAction, StoreAction}; -use super::resource::ResourceKey; -use super::texture::heap_tiled::metal_compresses_layout; -use super::texture_descriptor::TextureLayout; -use super::tracker::{Barrier, Use}; -use super::Device; -use ash::vk; -use metal2vulkan::device::{DriverFact, UnstoredDontCarePolicy}; -use metal2vulkan::metal::format::ClearRoute; -use metal2vulkan::metal::PixelFormat; -use std::collections::BTreeSet; - -/// The side, in pixels, of the tiles a `Clear` load's clear reaches past the render area in, on -/// both axes: Metal's on the M3 Max and an M4, the same at every format, sample count and tile -/// size measured (the module docs). The one place the runtime states it: every device clears as -/// Metal's do. -/// -/// **Executed on a driver that is not Metal.** On MoltenVK this constant is unobservable — the -/// driver is Metal and Metal's own tiles produce the reach whether [`reach`] rounds or not, so -/// replacing the rounding with the render area exactly moves no texel of the conformance suite's -/// `pass-bound-clear-reach` on an M3 Max. On llvmpipe (LLVM 23.1.1, x86-64) the runtime must -/// synthesize the reach, the case replays exact, and that same one-line change moves 511, 960 and -/// 960 texels of the case's `area-33x33`, `area-8x40` and `area-40x8` cells. The `8x40` and `40x8` -/// pair is what pins the side to 32 rather than 16 or 64, and pins the rounding to each axis on its -/// own; `area-33x33` is what pins the clip to the attachment. RADV and ANV are unrun. -pub(super) const TILE: u32 = 32; - -/// The extent from the origin that a `Clear` load of an attachment of `extent` clears in a pass -/// over the render area `area`: the render area rounded up to whole [`TILE`]s, clipped to the -/// attachment; the whole attachment where `whole` (a pass of one layer without a draw, over an -/// attachment [`clears_whole`] holds for). -pub(super) fn reach(area: [u32; 2], extent: [u32; 2], whole: bool) -> [u32; 2] { - if whole { - return extent; - } - [0, 1].map(|axis| { - area[axis] - .div_ceil(TILE) - .saturating_mul(TILE) - .min(extent[axis]) - }) -} - -/// The extent from the origin that a `Clear` load of `target`, an attachment's own level and -/// layers (a stand-in's `own`, of the stand-in's extent), clears in `layout`'s pass, a pass with a -/// draw call where `called`: [`reach`] over its render area. -pub(super) fn cleared(layout: &PassLayout, target: &Target, called: bool) -> [u32; 2] { - let whole = !called && layout.layers == 1 && clears_whole(target); - reach(layout.extent, target.extent, whole) -} - -/// Whether a `Clear` load of `target` in a pass of one layer without a draw call clears its whole -/// level and slice, past the render area's tiles. On a device that presents an Apple silicon -/// Mac's compression (`Device::metal_compresses_textures`), where Metal keeps the attachment's -/// texture (a view's first texture) losslessly compressed (`heap_tiled::metal_compresses_layout` -/// of its type, level 0, samples, usage and `allowGPUOptimizedContents`; never one over a -/// buffer): our probes `clearreach2` and `clearreach3` on the M3 Max (macOS 27.0.1), a new -/// `Private` attachment against an untouched twin, cleared whole where the texture was -/// compressed and over the render area's tiles where it was not, at every one of 16 color -/// formats (1 to 16 bytes a texel, float, unorm and integer), `Depth32Float`, `Depth16Unorm`, -/// `Stencil8` and `Depth32Float_Stencil8` (each aspect), 1, 2 and 4 samples, a level past the -/// first (one under 16 texels a side included), a slice past the first, a cube's face, a 3D -/// texture's plane, a view of the same format, of one level, and of another format, -/// `ShaderWrite` and `PixelFormatView` usage, a level 0 under and at 16 texels a side, and a -/// texture over a buffer, the property on and off; the consumer's probe alike (`tileclear2`, -/// jobs m3-max-12716 and m3-max-12735). On a device that presents a Mac keeping no texture -/// compressed, as a Mac with an Intel or AMD GPU does, always: those Macs disagree (an AMD -/// Radeon Pro 5300M clears the whole level, an Intel UHD 630 anything from the render area to -/// the whole texture: jobs m3-max-12736 and m3-max-12737), and the runtime gives the 5300M's -/// answer. -pub(super) fn clears_whole(target: &Target) -> bool { - let device = target.texture.generation(); - if !device.metal_compresses_textures() { - return true; - } - let mut root = &target.texture; - while let Some(parent) = root.parent_texture() { - root = parent; - } - let narrow = |side: u64| u32::try_from(side).unwrap_or(u32::MAX); - let layout = TextureLayout { - texture_type: root.texture_type(), - pixel_format: root.pixel_format(), - extent: [root.width(), root.height(), root.depth()].map(narrow), - levels: narrow(root.mipmap_level_count()), - layers: narrow(root.array_length()), - samples: narrow(root.sample_count()), - }; - let optimized = root.allow_gpu_optimized_contents(); - !root.over_buffer() && metal_compresses_layout(&layout, root.usage(), optimized) -} - -/// Whether a `Clear` load of an attachment of `extent` that the pass stores, over the render area -/// `area` in a pass with a draw call where `called`, is cleared before the pass and loaded in it -/// though its clear reaches no further than the render area ([`ReachClears`]): in a pass without -/// a draw call over an attachment larger than the render area. A pass's own clear on a device that -/// renders through Metal (MoltenVK) reaches the whole attachment there (lane `fresh_clear_reach` -/// on MoltenVK: an uncompressed 128x128 target cleared over 64x64), where Metal's reaches the -/// render area's tiles of a texture it keeps uncompressed. -fn own_clear_overreaches(area: [u32; 2], extent: [u32; 2], called: bool) -> bool { - !called && (0..2).any(|axis| area[axis] < extent[axis]) -} - -/// Whether Metal's `store` keeps an attachment's texels. -pub(super) fn stores(store: StoreAction) -> bool { - matches!( - store, - StoreAction::Store | StoreAction::StoreAndMultisampleResolve - ) -} - -/// The tiles a render pass's draws reach, where Metal loads and stores its attachments, as far as -/// the host decides them: what a `DontCare` load clears (above) and which tiles a rotated -/// texture's frame turns (`render/shadows.rs`). An execution of an indirect command buffer's -/// render commands, or a tile dispatch, counts as a draw call that draws (unmeasured). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum PassReach { - /// No tile: the pass has no draw call, or its draw calls draw nothing (of no vertex or no - /// instance, or through a pipeline that rasterizes nothing) and no attachment is cleared - /// and stored (`nodraw`, `instances0_t11`, `no_raster_t11`, `clear_c1_store_nodraw`). - Nothing, - /// Every tile, within the render area rounded up to whole tiles: a pass of one layer with a - /// draw call (one that draws nothing too) and an attachment loaded `Clear` and stored (a color, - /// depth and stencil attachment, `clear_c1_store_instances0` and `clear_depth_store_instances0` - /// of no instance). A `Clear` load with another store, a separate depth or stencil texture's, - /// and a pass of more layers are unmeasured: none of them decides it. - Every, - /// The tiles the draws' primitives reach, which the host does not know: each use of it - /// takes every tile and announces it. - Draws, -} - -impl PassReach { - /// The reach of `layout`'s pass, whose store actions are settled and whose `DontCare` loads - /// are not yet given their answers, with a draw call where `called` and one that draws where - /// `drew`. - pub(super) fn of(layout: &PassLayout, called: bool, drew: bool) -> PassReach { - let cleared = |load: LoadAction, store: StoreAction, memoryless: bool| { - load == LoadAction::Clear && store == StoreAction::Store && !memoryless - }; - let colors = layout - .colors - .iter() - .flatten() - .any(|c| cleared(c.load, c.store, c.memoryless)); - let depth_stencil = layout - .depth_stencil - .as_ref() - .filter(|ds| ds.separate.is_none() && !ds.hidden) - .is_some_and(|ds| { - [ds.depth, ds.stencil] - .into_iter() - .flatten() - .any(|a| cleared(a.load, a.store, a.memoryless)) - }); - if !called { - PassReach::Nothing - } else if layout.layers == 1 && (colors || depth_stencil) { - PassReach::Every - } else if drew { - PassReach::Draws - } else { - PassReach::Nothing - } - } -} - -/// Whether `target`'s texture is memoryless. -fn memoryless(target: &Target) -> bool { - target.texture.is_memoryless() -} - -/// The clear value a `DontCare` load that clears gives a color attachment of `pf`: the format's -/// zero as Metal's tile holds it, the texel a `Clear` load of `(0, 0, 0, 0)` writes -/// (`clear_value::color`). An extended-range format's is the code of 0 (384), which reads 0, -/// where zero bits read `-384/510` in color (plain Metal on an M4: a `DontCare`-loaded -/// `RGB10A8_2P_XR10` attachment's cleared texels read 0, the runtime's zero bits read -0.7529); -/// every format held directly takes zero bits. -pub(super) fn dont_care_clear(pf: PixelFormat) -> vk::ClearColorValue { - // A bfloat zero is the code 0 by either release's rule. - clear_value::color(pf, [0.0; 4], ClearRoute::ThroughHalf).unwrap_or_default() -} - -/// Give each `DontCare` load of `layout` that the module docs name its answer in a pass of -/// `reach`: `Load` where it reaches no tile, else `Clear`, to the format's zero for a color -/// attachment ([`dont_care_clear`]) and to its clear value for depth and stencil. One of an -/// attachment the pass does not store takes `Clear` wherever the pass reaches a tile, over its -/// whole render area, by the load operation, where `unstored` clears it (the module docs): no -/// fragment reads past the tiles its draws touch, and no texel is kept; elsewhere it stays -/// `DontCare`, and is named for its notice. Which stored attachments took it, and whether the -/// pass took the near-equivalent (its draws reach the tiles their primitives touch): the -/// attachment it names, for the notice. -/// -/// An aspect of separate depth and stencil textures, which the pass renders through its scratch -/// image (`depth_stencil_scratch.rs`), takes the same answers in that image, each aspect apart. -/// One the pass stores loads by a copy into the image where `copies_in` holds for it (depth, -/// stencil); where it does not, it takes `Clear` over the render area, Metal's answer in a pass -/// whose draws reach every tile and elsewhere the near-equivalent, named for its notice. -/// -/// A depth that takes `Clear` here whose clear depth is a NaN (only a `Clear` load's NaN is -/// written, `nan_clear.rs`) clears to Metal's answer where the device can hold it, 0 for a -/// `Depth16Unorm`, and elsewhere to 1.0, the value Metal's depth test orders a NaN nearest -/// ([`DontCareLoads::cleared_depth`]). -pub(super) fn dont_care_loads( - layout: &mut PassLayout, - reach: PassReach, - unstored: UnstoredLoads, - copies_in: [bool; 2], -) -> DontCareLoads { - let load = match reach { - PassReach::Nothing => LoadAction::Load, - PassReach::Every | PassReach::Draws => LoadAction::Clear, - }; - let drew = reach == PassReach::Draws; - let mut loads = DontCareLoads { - named: None, - unstored: None, - cleared_depth: None, - colors: Vec::new(), - depth: false, - stencil: false, - }; - for (index, color) in layout.colors.iter_mut().enumerate() { - let Some(color) = color.as_mut() else { - continue; - }; - // A memoryless color reads zero in every tile a draw touches, the only tiles where a - // fragment reads it (an Apple M4: a framebuffer fetch of one read 0 in - // 52 runs of 52, also after a pass that cleared other bytes into the tiles), and it is - // never stored: a clear to zero is Metal's answer exactly, in a pass that draws. - if color.load == LoadAction::DontCare && color.memoryless { - if reach != PassReach::Nothing { - color.load = LoadAction::Clear; - color.clear = dont_care_clear(color.target.texture.pixel_format()); - } - continue; - } - if color.load != LoadAction::DontCare || color.memoryless { - continue; - } - if !stores(color.store) { - match (reach, unstored) { - (PassReach::Nothing, _) => {} - (_, UnstoredLoads::Cleared) => { - color.load = LoadAction::Clear; - color.clear = dont_care_clear(color.target.texture.pixel_format()); - } - (_, UnstoredLoads::DontCare) => { - let name = || format!("color attachment {index}"); - loads.unstored.get_or_insert_with(name); - } - } - continue; - } - color.load = load; - color.clear = dont_care_clear(color.target.texture.pixel_format()); - loads.colors.push(index); - if drew { - loads - .named - .get_or_insert_with(|| format!("color attachment {index}")); - } - } - if let Some(ds) = layout.depth_stencil.as_mut() { - // Separate depth and stencil textures render through the pass's own scratch image - // (`depth_stencil_scratch.rs`), whose load operation is each aspect's: each takes the - // same answer there, an aspect the pass stores where it is copied in. - let separate = ds.separate.is_some(); - let depth_dont_care = ds - .depth - .as_ref() - .is_some_and(|depth| depth.load == LoadAction::DontCare); - for ((name, aspect, taken), copies_in) in [ - ("depth", ds.depth.as_mut(), &mut loads.depth), - ("stencil", ds.stencil.as_mut(), &mut loads.stencil), - ] - .into_iter() - .zip(copies_in) - { - let Some(aspect) = aspect else { - continue; - }; - if aspect.load != LoadAction::DontCare || aspect.memoryless { - continue; - } - if !stores(aspect.store) { - match (reach, unstored) { - (PassReach::Nothing, _) => {} - (_, UnstoredLoads::Cleared) => aspect.load = LoadAction::Clear, - (_, UnstoredLoads::DontCare) => { - let name = || format!("the {name} attachment"); - loads.unstored.get_or_insert_with(name); - } - } - continue; - } - // A separate texture's aspect that cannot be copied into the scratch image clears - // over the render area, which the draws do not bound. - if separate && !copies_in { - aspect.load = LoadAction::Clear; - if reach != PassReach::Every { - loads - .named - .get_or_insert_with(|| format!("the {name} attachment")); - } - continue; - } - aspect.load = load; - *taken = true; - if drew { - loads - .named - .get_or_insert_with(|| format!("the {name} attachment")); - } - } - // A depth this took `Clear` for, at a NaN clear depth: 0 for a `Depth16Unorm` (Metal's - // code), 1.0 for a float depth, which Vulkan's clear cannot hold the NaN of. - if let Some(depth) = ds - .depth - .as_mut() - .filter(|depth| depth_dont_care && depth.load == LoadAction::Clear) - { - let nan = matches!(depth.clear, AspectClear::Depth(value) if value.is_nan()); - let float = ds.depth_format != Some(PixelFormat::Depth16Unorm); - if nan { - depth.clear = AspectClear::Depth(if float { 1.0 } else { 0.0 }); - } - if let AspectClear::Depth(value) = depth.clear { - loads.cleared_depth = Some((value, nan && float)); - } - } - } - loads -} - -/// How [`dont_care_loads`] answers a `DontCare` load of an attachment the pass does not store, in -/// a pass whose draws reach a tile: by the device's policy and its driver's measured cost -/// ([`UnstoredLoads::of`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum UnstoredLoads { - /// Cleared over the render area, Metal's answer wherever a draw reads it. - Cleared, - /// Left to the driver's `DONT_CARE` load, the device's faster form, announced. - DontCare, -} - -impl UnstoredLoads { - /// Under `UnstoredDontCarePolicy::Cleared`, or on a driver measured to clear such an - /// attachment no slower than its `DONT_CARE` load (`DriverFact::UnstoredClearNoSlower`), - /// cleared; else left `DontCare`. - pub(super) fn of(policy: UnstoredDontCarePolicy, facts: &BTreeSet) -> Self { - match policy == UnstoredDontCarePolicy::Cleared - || facts.contains(&DriverFact::UnstoredClearNoSlower) - { - true => UnstoredLoads::Cleared, - false => UnstoredLoads::DontCare, - } - } -} - -/// What [`dont_care_loads`] did: the attachment it names for the notice where the pass took the -/// near-equivalent, the attachment it names where it left one the pass does not store `DontCare`, -/// and the color attachments (by index) and depth and stencil aspects whose `DontCare` load it -/// gave an answer. -pub(super) struct DontCareLoads { - pub(super) named: Option, - pub(super) unstored: Option, - /// The depth's clear value where its `DontCare` load took `Clear`, and whether that value - /// stands for a NaN clear depth Metal's tile holds and the device's clear cannot: 1.0, which a - /// fragment at exactly 1.0 tests otherwise than Metal's NaN (`signed-depth-test`). - pub(super) cleared_depth: Option<(f32, bool)>, - colors: Vec, - depth: bool, - stencil: bool, -} - -impl DontCareLoads { - /// Whether [`dont_care_loads`] gave any attachment's `DontCare` load an answer: the only - /// loads the tiles a pass's draws reach bound ([`ReachClears::plan`]). - pub(super) fn any(&self) -> bool { - !self.colors.is_empty() || self.depth || self.stencil - } - - /// Whether [`dont_care_loads`] gave color attachment `index`'s `DontCare` load an answer. - pub(super) fn color(&self, index: usize) -> bool { - self.colors.contains(&index) - } - - /// Whether it gave the depth and the stencil aspects' `DontCare` loads an answer. - pub(super) fn aspects(&self) -> [bool; 2] { - [self.depth, self.stencil] - } -} - -/// The most distinct pixel rectangles [`DrawnArea`] keeps; past them it is the whole render area. -const MOST_RECTS: usize = 1024; - -/// What [`DrawnArea`] worked out on this thread: its tile counts ([`DrawnArea::covered_tiles`]) and -/// its grids of the tiles a pass's draws reach ([`DrawnArea::tiles`]), which a pass end works out -/// only where a count or a clear reads them (`tests/pass_end_tiles.rs`). -#[cfg(test)] -pub(super) mod made { - use std::cell::Cell; - use std::thread::LocalKey; - - thread_local! { - pub(super) static COVERED: Cell = const { Cell::new(0) }; - pub(super) static GRIDS: Cell = const { Cell::new(0) }; - } - - /// One more of `what` on this thread. - pub(super) fn note(what: &'static LocalKey>) { - what.with(|made| made.set(made.get() + 1)); - } - - /// The tile counts and the grids worked out on this thread so far. - pub(crate) fn so_far() -> [u64; 2] { - [COVERED.with(Cell::get), GRIDS.with(Cell::get)] - } -} - -/// The words of a row of tiles in [`DrawnArea::covered_tiles`]: 512 tiles, the 16384 pixels of -/// the widest render area. -const ROW_WORDS: usize = 8; - -/// Set the bits `bits` of `row`, a row of tiles in [`DrawnArea::covered_tiles`], a word at a time. -fn set_bits(row: &mut [u64; ROW_WORDS], bits: std::ops::Range) { - if bits.is_empty() { - return; - } - for word in bits.start / 64..bits.end.div_ceil(64) { - let first = bits.start.max(word * 64) - word * 64; - let past = bits.end.min(word * 64 + 64) - word * 64; - let ones = u64::MAX >> (64 - (past - first)); - row[word as usize] |= ones << first; - } -} - -/// The pixels a pass's draws may write, as far as the host bounds them: each draw that draws -/// writes only inside its viewports' pixels within their scissor rectangles -/// (`EncoderState::vk_scissors`), so a tile none of those reaches is one Metal's draws do not, -/// and keeps its texels (on an Apple M4 under macOS 27.0.1: a sub-rectangle of the -/// viewport or of the scissor zeroes exactly the `DontCare`-loaded tiles it overlaps, and every -/// other tile keeps its texels). The whole render area where a draw's pixels are not bounded so: -/// an execution of render commands, a tile dispatch, a pass through a rasterization-rate map, or -/// more than [`MOST_RECTS`] distinct rectangles. -#[derive(Clone, Debug, Default, PartialEq)] -pub(super) struct DrawnArea { - /// Each distinct `[x0, y0, x1, y1]`, half-open, inside the render area. - rects: Rects, - whole: bool, -} - -/// Distinct pixel rectangles: the first held in place, as a pass's draws mostly reach one (its -/// render area), so such a pass allocates none for them; the others in order, each once, in a -/// list that keeps its room when cleared ([`DrawnArea::clear`]). -#[derive(Clone, Debug, Default, PartialEq)] -struct Rects { - first: Option<[u32; 4]>, - /// Empty while `first` is `None`; never holds `first`. - rest: Vec<[u32; 4]>, -} - -impl Rects { - /// Add `rect`, where it is not here yet. - fn insert(&mut self, rect: [u32; 4]) { - match self.first { - None => self.first = Some(rect), - Some(first) if first == rect => {} - Some(_) => { - if let Err(at) = self.rest.binary_search(&rect) { - self.rest.insert(at, rect); - } - } - } - } - - fn len(&self) -> usize { - usize::from(self.first.is_some()) + self.rest.len() - } - - fn iter(&self) -> impl Iterator { - self.first.iter().chain(&self.rest) - } - - fn clear(&mut self) { - self.first = None; - self.rest.clear(); - } -} - -impl DrawnArea { - /// An area that bounds nothing, an execution's commands' (which the host does not bound). - pub(super) fn unbounded() -> DrawnArea { - DrawnArea { - rects: Rects::default(), - whole: true, - } - } - - /// Add a draw's rectangles, its scissors clipped to its viewports' pixels. - pub(super) fn add(&mut self, rects: &[vk::Rect2D]) { - if self.whole { - return; - } - for r in rects { - let (x, y) = (r.offset.x.max(0) as u32, r.offset.y.max(0) as u32); - let (w, h) = (r.extent.width, r.extent.height); - if w == 0 || h == 0 { - continue; - } - self.rects - .insert([x, y, x.saturating_add(w), y.saturating_add(h)]); - } - if self.rects.len() > MOST_RECTS { - self.everywhere(); - } - } - - /// Whether a pixel of the area may lie inside `area`, `[x0, y0, x1, y1)` (`None` for every - /// pixel): one of its rectangles meets it, or it bounds nothing. - pub(super) fn meets(&self, area: Option<[u32; 4]>) -> bool { - if self.whole { - return true; - } - let Some([b0, b1, b2, b3]) = area else { - return self.rects.len() > 0; - }; - (self.rects.iter()) - .any(|&[a0, a1, a2, a3]| a0.max(b0) < a2.min(b2) && a1.max(b1) < a3.min(b3)) - } - - /// The rectangle `[x0, y0, x1, y1)` bounding every rectangle, half-open in the render area's - /// pixels: `None` where the area bounds nothing, or holds no rectangle. - pub(super) fn bounds(&self) -> Option<[u32; 4]> { - if self.whole { - return None; - } - self.rects - .iter() - .copied() - .reduce(|[a0, a1, a2, a3], [b0, b1, b2, b3]| { - [a0.min(b0), a1.min(b1), a2.max(b2), a3.max(b3)] - }) - } - - /// Of the tiles of [`TILE`] pixels a side, from the render area's origin, that - /// [`bounds`](Self::bounds) reaches, how many its rectangles reach, and how many it reaches: - /// `None` where it bounds nothing. A count (`WorkCounts::shadow_attachment_tiles_covered`): - /// what a copy cut to the rectangles' tiles would leave out of one cut to their bounds. - pub(super) fn covered_tiles(&self) -> Option<(u64, u64)> { - #[cfg(test)] - made::note(&made::COVERED); - let [x0, y0, x1, y1] = self.bounds()?; - let (tx0, ty0) = (x0 / TILE, y0 / TILE); - let (tx1, ty1) = (x1.div_ceil(TILE), y1.div_ceil(TILE)); - let bounded = u64::from(tx1 - tx0) * u64::from(ty1 - ty0); - // A row of tiles in the bits of `ROW_WORDS` words; a wider one, which no render area - // has, counts as covered. - if (tx1 - tx0) as usize > ROW_WORDS * 64 { - return Some((bounded, bounded)); - } - // Each rectangle's tiles: its columns from the bounds' first, and its rows. - let tiled = |&[rx0, ry0, rx1, ry1]: &[u32; 4]| { - (rx0 < rx1 && ry0 < ry1).then(|| { - let columns = rx0 / TILE - tx0..rx1.div_ceil(TILE) - tx0; - (columns, ry0 / TILE..ry1.div_ceil(TILE)) - }) - }; - // The rows where a rectangle's tiles start or end: every row from one such edge to the - // next is reached by the same rectangles, so one row of tiles counts for them all. - let mut edges: Vec = (self.rects.iter().filter_map(tiled)) - .flat_map(|(_, rows)| [rows.start, rows.end]) - .collect(); - edges.sort_unstable(); - edges.dedup(); - let mut covered = 0; - for band in edges.windows(2) { - let (top, bottom) = (band[0], band[1]); - let mut row = [0u64; ROW_WORDS]; - for (columns, rows) in self.rects.iter().filter_map(tiled) { - if rows.contains(&top) { - set_bits(&mut row, columns); - } - } - let tiles: u64 = row.iter().map(|word| u64::from(word.count_ones())).sum(); - covered += u64::from(bottom - top) * tiles; - } - Some((covered, bounded)) - } - - /// Add `other`'s rectangles: anywhere where it bounds nothing. - pub(super) fn join(&mut self, other: &DrawnArea) { - if other.whole { - self.everywhere(); - return; - } - if self.whole { - return; - } - for &rect in other.rects.iter() { - self.rects.insert(rect); - } - if self.rects.len() > MOST_RECTS { - self.everywhere(); - } - } - - /// No rectangle, as a new area: its list's room kept for a next pass's draws - /// (`render/draw_room.rs`). - pub(super) fn clear(&mut self) { - self.whole = false; - self.rects.clear(); - } - - /// The rectangles it holds room for. - pub(super) fn room(&self) -> usize { - self.rects.rest.capacity() - } - - /// Bound nothing: the draws may write anywhere in the render area. - pub(super) fn everywhere(&mut self) { - self.whole = true; - self.rects.clear(); - } - - /// The tiles of `layout`'s pass the rectangles reach, at the encoder's tile size (the pass's - /// `tileWidth` and `tileHeight`, or 32 by 32 pixels, 32 by 16 at 4 samples; the module docs): - /// `None` where that is every tile of the render area rounded up to whole tiles, the area is - /// not bounded, or the pass's sample count has no measured tile size. - pub(super) fn tiles(&self, layout: &PassLayout) -> Option { - #[cfg(test)] - made::note(&made::GRIDS); - let tile = layout.tile.tile.filter(|_| !self.whole)?; - self.tiles_of(tile, layout.extent) - } - - /// Whether [`tiles`](Self::tiles) holds tiles and none is reached: the rectangles reach no - /// tile of `layout`'s pass, which a scan of them answers with no grid made. - pub(super) fn reaches_no_tile(&self, layout: &PassLayout) -> bool { - layout - .tile - .tile - .filter(|_| !self.whole) - .is_some_and(|tile| self.reaches_no_tile_of(tile, layout.extent)) - } - - /// [`reaches_no_tile`](Self::reaches_no_tile) at `tile` pixels a side of a render area of - /// `extent`: a grid of tiles, none of which a rectangle overlaps, as - /// [`tiles_of`](Self::tiles_of) sets them. - fn reaches_no_tile_of(&self, tile: [u32; 2], extent: [u32; 2]) -> bool { - let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis])); - let overlaps = |&[x0, y0, x1, y1]: &[u32; 4]| { - x0 / tile[0] < x1.div_ceil(tile[0]).min(per_row) - && y0 / tile[1] < y1.div_ceil(tile[1]).min(rows) - }; - per_row != 0 && rows != 0 && !self.rects.iter().any(overlaps) - } - - /// The tiles of `tile` pixels a side of a render area of `extent` the rectangles reach: - /// `None` where that is every one ([`tiles`](Self::tiles)). - fn tiles_of(&self, tile: [u32; 2], extent: [u32; 2]) -> Option { - let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis])); - // A rectangle that reaches every tile on its own (a draw over the whole render area, as - // most are): every tile, with no grid made. - let every = |&[x0, y0, x1, y1]: &[u32; 4]| { - x0 < tile[0] - && y0 < tile[1] - && x1.div_ceil(tile[0]) >= per_row - && y1.div_ceil(tile[1]) >= rows - }; - if per_row == 0 || rows == 0 || self.rects.iter().any(every) { - return None; - } - let mut tiles = DrawnTiles { - tile, - per_row, - rows, - words: vec![0; (per_row as usize * rows as usize).div_ceil(32)], - }; - for &[x0, y0, x1, y1] in self.rects.iter() { - for ty in y0 / tile[1]..y1.div_ceil(tile[1]).min(rows) { - for tx in x0 / tile[0]..x1.div_ceil(tile[0]).min(per_row) { - let t = (ty * per_row + tx) as usize; - tiles.words[t / 32] |= 1 << (t % 32); - } - } - } - let all = (0..per_row as usize * rows as usize) - .all(|t| tiles.words[t / 32] & (1 << (t % 32)) != 0); - (!all).then_some(tiles) - } -} - -/// The tiles a pass's draws may reach, of the render area rounded up to whole tiles -/// ([`DrawnArea::tiles`]): `tile` pixels a side, `per_row` by `rows` of them, one bit each, row -/// after row. -#[derive(Clone, Debug)] -pub(super) struct DrawnTiles { - tile: [u32; 2], - per_row: u32, - rows: u32, - words: Vec, -} - -impl DrawnTiles { - /// Whether tile `(tx, ty)` is reached: none past the grid. - pub(super) fn contains(&self, tx: u32, ty: u32) -> bool { - let t = (ty as usize) * (self.per_row as usize) + tx as usize; - tx < self.per_row && ty < self.rows && self.words[t / 32] & (1 << (t % 32)) != 0 - } - - /// The reached tiles as rectangles of pixels, each run of them along a row of tiles, clipped - /// to `extent` from the origin (an attachment's reach). - fn rects(&self, extent: [u32; 2]) -> Vec { - let [tw, th] = self.tile; - let mut out = Vec::new(); - for ty in 0..self.rows { - let mut tx = 0; - while tx < self.per_row { - if !self.contains(tx, ty) { - tx += 1; - continue; - } - let first = tx; - while tx < self.per_row && self.contains(tx, ty) { - tx += 1; - } - let [x0, y0] = [first * tw, ty * th]; - let [x1, y1] = [(tx * tw).min(extent[0]), ((ty + 1) * th).min(extent[1])]; - if x0 < x1 && y0 < y1 { - out.push(vk::Rect2D { - offset: vk::Offset2D { - x: x0 as i32, - y: y0 as i32, - }, - extent: vk::Extent2D { - width: x1 - x0, - height: y1 - y0, - }, - }); - } - } - } - out - } -} - -/// One attachment's clear before its pass: the attachment, a render pass of it alone, its -/// framebuffer over the clear's extent and the pass's layers, the rectangles cleared (the extent, -/// or the tiles a `DontCare` load's draws may reach), the aspects cleared, and the clear value. -struct ReachClear { - attachment: Reached, - pass: RenderPassObject, - framebuffer: FramebufferObject, - area: vk::Rect2D, - rects: Vec, - layers: u32, - aspects: vk::ImageAspectFlags, - value: vk::ClearValue, -} - -/// The attachment a [`ReachClear`] clears: a color attachment's index, or the depth/stencil -/// attachment's depth and stencil aspects, each whether it is cleared. -#[derive(Clone, Copy)] -enum Reached { - Color(usize), - DepthStencil { depth: bool, stencil: bool }, -} - -/// The clears before a pass of its attachments that a `Clear` load clears past the render area -/// (the module docs), and of the cleared attachments its first instance leaves out that no -/// whole-subresource clear may stand for, with the uses they make. The clears are held until the -/// command buffer completes. -pub(super) struct ReachClears { - clears: Vec, - uses: Vec>, -} - -impl ReachClears { - /// The clears of `layout`'s attachments, a pass with a draw call where `called` (the module - /// docs); `left_out` names the color indices whose clear the pass must make before it - /// whatever their store action (its first instance leaves them out, and no whole-subresource - /// clear stands for them). Where `bounded` gives the `DontCare` loads that took a `Clear` and - /// the tiles the pass's draws may reach, each of those clears only those tiles, before the - /// pass. `None` when there is none. - pub(super) fn plan( - device: &Device, - layout: &PassLayout, - called: bool, - left_out: &[u32], - bounded: Option<(&DontCareLoads, &DrawnTiles)>, - ) -> Result, Error> { - let area = layout.extent; - let mut clears = Vec::new(); - let mut uses = Vec::new(); - for (index, color) in layout.colors.iter().enumerate() { - let Some(color) = color else { - continue; - }; - if color.load != LoadAction::Clear || color.memoryless { - continue; - } - let extent = match stores(color.store) { - true => cleared( - layout, - color.stand_in.as_ref().map_or(&color.target, |s| &s.own), - called, - ), - false => area, - }; - // A color held in sample planes keeps its `Clear` load (`load_in_pass`): its tiles - // are not bounded. - let tiles = bounded - .filter(|(loads, _)| loads.colors.contains(&index) && color.planes.is_none()) - .map(|(_, tiles)| tiles); - let overreaches = - stores(color.store) && own_clear_overreaches(area, color.target.extent, called); - if extent == area - && !left_out.contains(&(index as u32)) - && tiles.is_none() - && !overreaches - { - continue; - } - let rects = tiles.map_or_else(|| vec![rect(extent)], |t| t.rects(extent)); - let (pass, framebuffer, made) = - render_target::reach_pass(device, &color.target, false, extent)?; - uses.extend(made); - clears.push(ReachClear { - attachment: Reached::Color(index), - pass, - framebuffer, - area: rect(extent), - rects, - layers: color.target.layers, - aspects: vk::ImageAspectFlags::COLOR, - value: vk::ClearValue { color: color.clear }, - }); - } - // A depth the pass clears at custom sample positions on a driver that stores and tests - // it at the standard ones there (`DriverFact::ClearedDepthAtStandardPositions`): cleared - // before the pass, memoryless or unstored too, so that the pass loads it, which takes the - // positions. One the pass does not store is cleared over the render area alone. - let positioned = !layout.sample_positions.is_empty() - && device - .properties() - .driver_facts - .contains(&DriverFact::ClearedDepthAtStandardPositions); - let positioned_depth = |ds: &super::render_pass::DepthStencilTarget| { - positioned && ds.depth.is_some_and(|a| a.load == LoadAction::Clear) - }; - // Separate depth and stencil textures' scratch image (`depth_stencil_scratch.rs`): only - // the tiles of a bounded `DontCare` load, over the render area its copies cover. - if let Some(ds) = layout.depth_stencil.as_ref().filter(|ds| { - let bounded = bounded.is_some_and(|(loads, _)| loads.depth || loads.stencil); - match ds.separate { - Some(_) => bounded, - None => !memoryless(&ds.target) || positioned_depth(ds), - } - }) { - let cleared_aspect = |aspect: Option<&super::render_pass::AspectTarget>| { - aspect.is_some_and(|a| { - a.load == LoadAction::Clear && !a.memoryless && stores(a.store) - }) - }; - let (depth, stencil) = ( - cleared_aspect(ds.depth.as_ref()), - cleared_aspect(ds.stencil.as_ref()), - ); - let reached = cleared( - layout, - ds.stand_in.as_ref().map_or(&ds.target, |s| &s.own), - called, - ); - let mut value = vk::ClearDepthStencilValue::default(); - for aspect in [ds.depth.as_ref(), ds.stencil.as_ref()] - .into_iter() - .flatten() - { - match aspect.clear { - AspectClear::Depth(depth) => value.depth = depth, - AspectClear::Stencil(stencil) => value.stencil = stencil, - } - } - // The aspects a bounded `DontCare` load cleared clear its tiles alone; the others - // their whole reach, where it passes the render area. - let (tiles, bound) = match bounded { - Some((loads, tiles)) => (Some(tiles), [loads.depth, loads.stencil]), - None => (None, [false, false]), - }; - let separate = ds.separate.is_some(); - let forced = positioned_depth(ds) && !separate; - let parts = [ - ( - [ - depth && !bound[0] && !separate, - stencil && !bound[1] && !separate, - ], - None, - reached, - ), - ( - [depth && bound[0], stencil && bound[1]], - tiles, - if separate { area } else { reached }, - ), - ([forced && !depth, false], None, area), - ]; - let overreaches = own_clear_overreaches(area, ds.target.extent, called); - for ([depth, stencil], tiles, extent) in parts { - let reaches = extent != area || tiles.is_some() || (forced && depth) || overreaches; - if !(depth || stencil) || !reaches { - continue; - } - let rects = tiles.map_or_else(|| vec![rect(extent)], |t| t.rects(extent)); - let (pass, framebuffer, made) = - render_target::reach_pass(device, &ds.target, true, extent)?; - uses.extend(made); - let mut aspects = vk::ImageAspectFlags::empty(); - if depth { - aspects |= vk::ImageAspectFlags::DEPTH; - } - if stencil { - aspects |= vk::ImageAspectFlags::STENCIL; - } - clears.push(ReachClear { - attachment: Reached::DepthStencil { depth, stencil }, - pass, - framebuffer, - area: rect(extent), - rects, - layers: ds.target.layers, - aspects, - value: vk::ClearValue { - depth_stencil: value, - }, - }); - } - } - Ok((!clears.is_empty()).then_some(ReachClears { clears, uses })) - } - - /// Load each attachment these clears clear, a `Clear` load, in `layout`'s pass: the clear - /// before the pass covers the render area as well, and a pass's own clear on a device that - /// renders through Metal (MoltenVK) reaches the whole attachment in a pass without a draw, - /// where Metal's own reaches whole tiles in a pass with a draw call (the module docs). A - /// color attachment held in sample planes keeps its load (`sample_planes.rs` clears them). - pub(super) fn load_in_pass(&self, layout: &mut PassLayout) { - for clear in &self.clears { - match clear.attachment { - Reached::Color(index) => { - if let Some(color) = layout - .colors - .get_mut(index) - .and_then(Option::as_mut) - .filter(|color| color.load == LoadAction::Clear && color.planes.is_none()) - { - color.load = LoadAction::Load; - color.cleared_ahead = true; - } - } - Reached::DepthStencil { depth, stencil } => { - let Some(ds) = layout.depth_stencil.as_mut() else { - continue; - }; - for (cleared, aspect) in - [(depth, ds.depth.as_mut()), (stencil, ds.stencil.as_mut())] - { - if let Some(aspect) = - aspect.filter(|a| cleared && a.load == LoadAction::Clear) - { - aspect.load = LoadAction::Load; - } - } - } - } - } - } - - /// Record the clears in `core`'s command buffer, between barriers from everything before - /// and to everything after, and hold them until it completes. - pub(super) fn record(self, core: &mut EncoderCore) { - let ReachClears { clears, uses } = self; - core.device().shared().counts.pool_compiled( - crate::work_counts::PoolCompiled::AttachmentClear, - clears.len() as u64, - ); - core.barrier(Barrier::everything()); - core.command( - render_target::ATTACHMENT_STAGES, - &uses, - |raw, command_buffer| { - // A bounded clear of no tile clears nothing; its attachment still loads. - for clear in clears.iter().filter(|clear| !clear.rects.is_empty()) { - let begin = vk::RenderPassBeginInfo::default() - .render_pass(clear.pass.raw) - .framebuffer(clear.framebuffer.raw) - .render_area(clear.area); - let attachments = [vk::ClearAttachment { - aspect_mask: clear.aspects, - color_attachment: 0, - clear_value: clear.value, - }]; - let rects: Vec = clear - .rects - .iter() - .map(|&rect| vk::ClearRect { - rect, - base_array_layer: 0, - layer_count: clear.layers, - }) - .collect(); - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // pass, its framebuffer and the attachment are live until it completes (held - // below, and the texture by the encoder); its image rests in `GENERAL`, the - // pass's layout; the area is the framebuffer's, and the layers its own; the - // aspects are the attachment format's, and the subpass's one attachment, color - // 0 or its depth/stencil attachment, is the one cleared; every rectangle lies - // in the area. - unsafe { - raw.cmd_begin_render_pass( - command_buffer, - &begin, - vk::SubpassContents::INLINE, - ); - raw.cmd_clear_attachments(command_buffer, &attachments, &rects); - raw.cmd_end_render_pass(command_buffer); - } - } - }, - ); - core.barrier(Barrier::everything()); - core.retain(clears); - } -} - -/// The rectangle of `extent` from the origin. -fn rect([width, height]: [u32; 2]) -> vk::Rect2D { - vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent: vk::Extent2D { width, height }, - } -} - -#[cfg(test)] -mod tests { - use super::{dont_care_clear, made, DrawnArea}; - use ash::vk; - use metal2vulkan::metal::format::{ClearRoute, ExtendedRange}; - use metal2vulkan::metal::PixelFormat; - - /// A `DontCare` load that clears writes each format's zero as Metal's tile holds it: an - /// extended-range attachment's raw texel of `(0, 0, 0, 0)`, its codes 384, not zero bits; a - /// format held directly, zero bits. - #[test] - fn dont_care_clears_to_the_formats_zero() { - for pf in [ - PixelFormat::RGB10A82PXR10, - PixelFormat::RGB10A82PXR10SRGB, - PixelFormat::BGRA10XR, - PixelFormat::BGRA10XRSRGB, - PixelFormat::BGR10XR, - PixelFormat::BGR10XRSRGB, - ] { - let form = ExtendedRange::of(pf).expect("an extended-range format"); - // SAFETY: every member of the union is four 32-bit values; any bits are a `u32`. - let got = unsafe { dont_care_clear(pf).uint32 }; - assert_eq!( - got, - form.clear_texel([0.0; 4], ClearRoute::ThroughHalf), - "{pf:?}" - ); - assert_ne!(got, [0; 4], "{pf:?}"); - } - for pf in [ - PixelFormat::RGBA16Float, - PixelFormat::BGRA8Unorm, - PixelFormat::R32Uint, - PixelFormat::RGBA16Bfloat, - ] { - // SAFETY: as above. - let got = unsafe { dont_care_clear(pf).uint32 }; - assert_eq!(got, [0; 4], "{pf:?}"); - } - // A bfloat zero is the code 0 by either release's rule. - let form = ExtendedRange::Rgba16Bfloat; - for rule in [ClearRoute::ThroughHalf, ClearRoute::Straight] { - assert_eq!(form.clear_texel([0.0; 4], rule), [0; 4], "{rule:?}"); - } - } - - /// The tiles the rectangles cover, against those their bounding rectangle reaches, are - /// counted in 32-pixel tiles from the origin: two rectangles far apart cover their own - /// tiles alone, where their bounds reach every tile between them. - #[test] - fn covered_tiles_count_the_rectangles_tiles_against_their_bounds() { - let rect = |x: i32, y: i32, w: u32, h: u32| vk::Rect2D { - offset: vk::Offset2D { x, y }, - extent: vk::Extent2D { - width: w, - height: h, - }, - }; - let cases: [(Vec, Option<(u64, u64)>); 6] = [ - (vec![], None), - // A 1920x1080 render area's every tile: 60 by 34. - (vec![rect(0, 0, 1920, 1080)], Some((2040, 2040))), - // Off the grid: tiles 0 to 2 by 0 to 1. - (vec![rect(31, 1, 34, 32)], Some((6, 6))), - // Two corners at either end of a 1920x1080 area, four tiles each. - ( - vec![rect(0, 0, 64, 64), rect(1856, 1024, 64, 56)], - Some((8, 2040)), - ), - // Overlapping rectangles count each tile once. - (vec![rect(0, 0, 96, 32), rect(32, 0, 96, 32)], Some((4, 4))), - // An L: the bounds reach the corner the rectangles leave out. - (vec![rect(0, 0, 64, 32), rect(0, 32, 32, 32)], Some((3, 4))), - ]; - let [counted, _] = made::so_far(); - for (case, (rects, expected)) in cases.iter().enumerate() { - let mut area = DrawnArea::default(); - area.add(rects); - assert_eq!(area.covered_tiles(), *expected, "case {case}"); - } - assert_eq!(DrawnArea::unbounded().covered_tiles(), None); - // Each count is noted on this thread, for the tests that hold a pass end to its counts. - assert_eq!(made::so_far()[0] - counted, cases.len() as u64 + 1); - // Against the tiles counted one at a time, for rectangles spread over a large area. - let mut seed = 0x2545_f491_u64; - let mut next = |below: u32| { - seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); - ((seed >> 33) % u64::from(below)) as u32 - }; - for case in 0..200 { - let rects: Vec = (0..1 + next(24)) - .map(|_| { - rect( - next(3000) as i32, - next(2000) as i32, - 1 + next(900), - 1 + next(700), - ) - }) - .collect(); - let mut area = DrawnArea::default(); - area.add(&rects); - let [x0, y0, x1, y1] = area.bounds().expect("a rectangle"); - let (tx0, ty0, tx1, ty1) = (x0 / 32, y0 / 32, x1.div_ceil(32), y1.div_ceil(32)); - let mut covered = 0; - for ty in ty0..ty1 { - for tx in tx0..tx1 { - let reached = area.rects.iter().any(|&[rx0, ry0, rx1, ry1]| { - rx0 < (tx + 1) * 32 && tx * 32 < rx1 && ry0 < (ty + 1) * 32 && ty * 32 < ry1 - }); - covered += u64::from(reached); - } - } - let bounded = u64::from(tx1 - tx0) * u64::from(ty1 - ty0); - assert_eq!( - area.covered_tiles(), - Some((covered, bounded)), - "case {case}" - ); - } - } - - /// Cleared, an area bounds nothing as a new one does and keeps its list's room; rectangles - /// added to it then are a new area's, in the same order, each once. - #[test] - fn a_cleared_area_is_a_new_one_with_its_room() { - let rect = |x: i32, y: i32| vk::Rect2D { - offset: vk::Offset2D { x, y }, - extent: vk::Extent2D { - width: 8, - height: 8, - }, - }; - let rects = [ - rect(40, 0), - rect(0, 40), - rect(0, 0), - rect(40, 0), - rect(20, 20), - ]; - let mut kept = DrawnArea::default(); - kept.add(&rects); - kept.everywhere(); - kept.clear(); - kept.add(&rects); - let room = kept.room(); - assert!(room >= 3, "{room}"); - kept.clear(); - assert_eq!((kept.bounds(), kept.room()), (None, room)); - let mut reversed = rects; - reversed.reverse(); - kept.add(&reversed); - let mut fresh = DrawnArea::default(); - fresh.add(&reversed); - let all = |area: &DrawnArea| area.rects.iter().copied().collect::>(); - assert_eq!(all(&kept), all(&fresh)); - assert_eq!(all(&fresh).len(), 4); - assert_eq!(kept.room(), room, "no list made again"); - } - - /// The tiles a pass's rectangles reach are the tiles each overlaps, whether one of them - /// reaches every tile (no grid made) or none does: checked tile by tile. - #[test] - fn drawn_tiles_are_the_tiles_the_rectangles_overlap() { - let rect = |x: i32, y: i32, w: u32, h: u32| vk::Rect2D { - offset: vk::Offset2D { x, y }, - extent: vk::Extent2D { - width: w, - height: h, - }, - }; - let tile = [32u32, 16]; - let extent = [100u32, 70]; - let cases = [ - vec![rect(0, 0, 100, 70)], - vec![rect(31, 15, 69, 55)], - vec![rect(32, 0, 68, 70)], - vec![rect(0, 16, 100, 54)], - vec![rect(0, 0, 96, 64)], - vec![rect(0, 0, 97, 65)], - vec![rect(5, 5, 10, 10), rect(0, 0, 100, 70)], - vec![rect(0, 0, 50, 70), rect(50, 0, 50, 70)], - vec![rect(40, 20, 10, 10)], - vec![], - // Past the grid, across and down: no tile. - vec![rect(128, 0, 10, 10)], - vec![rect(0, 80, 10, 10), rect(130, 90, 5, 5)], - vec![rect(96, 64, 4, 6)], - ]; - for (case, rects) in cases.iter().enumerate() { - let mut area = DrawnArea::default(); - area.add(rects); - let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis])); - let reached = |tx: u32, ty: u32| { - area.rects.iter().any(|&[x0, y0, x1, y1]| { - x0 < (tx + 1) * tile[0] - && tx * tile[0] < x1 - && y0 < (ty + 1) * tile[1] - && ty * tile[1] < y1 - }) - }; - let every = (0..rows).all(|ty| (0..per_row).all(|tx| reached(tx, ty))); - // The scan with no grid made answers whether the grid holds none. - let none = (0..rows).all(|ty| (0..per_row).all(|tx| !reached(tx, ty))); - assert_eq!(area.reaches_no_tile_of(tile, extent), none, "case {case}"); - match area.tiles_of(tile, extent) { - None => assert!(every, "case {case}"), - Some(tiles) => { - assert!(!every, "case {case}"); - for ty in 0..rows { - for tx in 0..per_row { - let reach = reached(tx, ty); - assert_eq!(tiles.contains(tx, ty), reach, "case {case}: {tx}, {ty}"); - } - } - } - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/clear_value.rs b/crates/metal2vulkan-runtime/src/clear_value.rs deleted file mode 100644 index 62d4d3957..000000000 --- a/crates/metal2vulkan-runtime/src/clear_value.rs +++ /dev/null @@ -1,1619 +0,0 @@ -//! The Vulkan clear values of Metal's `Clear` load action. -//! -//! Metal takes a clear color as four doubles, a clear depth as a double and a clear stencil as a -//! 32-bit value. Its conversion to each format was measured on an Apple M4 (macOS 27.0.1, by our -//! Metal probes; `tests` holds it as the model the tests compare with): -//! -//! - **Normalized** channels go through `float` (round to nearest even), then NaN is 0, the value -//! is clamped to `[0, 1]` (`[-1, 1]` signed), and scaled to the nearest integer, ties to even. -//! The channels of the packed 16-bit formats (B5G6R5, A1BGR5, ABGR4, BGR5A1) go through `half` -//! too. sRGB channels are encoded with the sRGB curve before the scaling; their alpha is linear. -//! - **Integer** channels truncate the double toward zero and saturate; NaN is 0. No `float` -//! step: 16777217 stays 16777217. -//! - **Half** channels go through `float` and then `half`, each rounding to nearest even. -//! **Float** channels round to nearest even, keeping subnormals; NaN keeps its sign. -//! - **RG11B10** channels truncate their mantissas; **RGB9E5** takes its exponent from the -//! largest channel and truncates every mantissa. -//! - **Depth** goes through `float`; `Depth16Unorm` truncates (0.5 is `0x7fff`). Metal refuses a -//! clear depth outside `[0, 1]` (the caller's check). **Stencil** keeps the low 8 bits. -//! -//! **The device converts a float clear.** A normalized, sRGB, packed 16-bit, half, float or small -//! float channel's clear value is the clear color as a `float` ([`color`]), which the device -//! converts to the format by its own rules, as a depth's is ([`depth`]). Vulkan clamps a -//! normalized value and lets the device store either of the two codes nearest it, asking it to -//! round to nearest ("Implementations should round to nearest"), and leaves a float format's -//! rounding and an sRGB encode's precision to the device. So the device's texel can stand a code -//! from Metal's where the rounding is in question ([`rounds_apart`], announced -//! `device-color-conversion`): a normalized channel's value scaled anywhere off a whole code, on -//! every device (the RTX 5080 Laptop GPU, ANV on the Iris Xe of RPL-P and RADV on the Radeon RX -//! 550 are measured to store the farther code off a midpoint; docs/API.md's -//! `device-color-conversion` entry), an sRGB channel's value inside `(0, 1)`, a half or small -//! float's value it does not hold exactly, and a shared exponent's texel it does not; and a -//! `Depth16Unorm` depth scaled at or -//! within [`TIE`] of a midpoint or above it, which Metal's clear truncates and a device rounding -//! to nearest takes to the code above ([`depth16_rounded`], announced `unorm-depth-rounding`). Vulkan states no conversion of a NaN to a normalized code, or to -//! `RGB9E5Float`, which holds none: such a channel clears as 0, as Metal's does. A `half` or -//! small-float channel's NaN is converted by the device as it likes: RADV and lavapipe write other -//! NaNs than Metal's canonical quiet one (a Metal probe, the M3 Max and an M4 alike: `0x7e00`, and -//! `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped), announced -//! (`nan_clear::degrade_nan_clears`). A `float` NaN keeps the double's sign and top payload bits, -//! quieted, as Metal's conversion to `float` keeps them (`0x7fc00000`, `0xffc00000`), which every -//! device measured writes. -//! -//! **Integer** channels take Metal's conversion of the double ([`color`]): Vulkan's integer clear -//! is an integer, which no device converts from a double. -//! -//! An **extended-range** attachment holds its raw texels in an unsigned integer format, so its -//! clear value is the raw texel Metal stores (`ExtendedRange::clear_texel`): each channel goes -//! through `float` and then `half`, each rounding to nearest even, and the `half` takes the code a -//! kernel's write of it stores (on an M4 under macOS 27.0.1: every texel of 8,192 random clear -//! colors of each of the six formats). That is one of Metal's two routes -//! (`metal::format::ClearRoute`), which a bfloat attachment's codes take too: where Metal keeps the -//! level compressed and the pass has no draw call (`nan_clear::keeps_nan_sign`, the pass's encoder -//! choosing at its end), a bfloat channel's `float` is rounded straight to bfloat, on the M4 under -//! 27.0.1 and the M3 Max under 26.7 alike, and a `BGR10_XR` or `BGRA10_XR` channel's code is -//! straight from its `float`, `BGR10_XR`'s bits 30 and 31 zero (the M4 under 27.0.1); the two-plane -//! formats store the same on either route. -//! -//! A **word** attachment (`metal::format::WordAttachment`: a packed 16-bit, one- or two-channel -//! 8-bit sRGB or `RGB9E5Float` format the device holds but does not render) renders through the -//! view of its word, so its clear value is the word Metal's clear stores ([`word`]). -//! -//! A **two-plane YCbCr** attachment whose store is matched (`metal::format::ycbcr_renders`) renders -//! into floats, which the pass's store encodes into the planes as Metal stores a drawn texel: its -//! clear value is the clear color through `float` and then `half`, each rounding to nearest even -//! (NaN kept), which the store clamps and encodes (every byte of the clears' planes is the encoding -//! of the clear color's `half`s; the 10-bit formats' 320 clears alike; a 4:4:4 `_sRGB` twin's -//! eight clears, each `half` through the sRGB curve first, within a code of Metal's). The store takes a drawn -//! 10-bit texel's `half` toward zero (`bind::ycbcr_store`), which keeps a `half`, so a cleared -//! texel's codes are its `half`s' at either depth. - -use ash::vk; -use metal2vulkan::metal::format::{ - alpha_in_red_format, rotated_channels, to_rotated_image, ycbcr_renders, ClearRoute, - ExtendedRange, WordAttachment, -}; -use metal2vulkan::metal::PixelFormat; -use metal2vulkan::vk::Format; - -/// How Metal converts one clear color channel of a format. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Channel { - /// A channel the format does not have. - Unused, - /// Unsigned normalized, of this many bits, through `float`. - Unorm(u32), - /// Unsigned normalized, of this many bits, through `float` and `half` (the packed 16-bit - /// formats). - HalfUnorm(u32), - /// Signed normalized, of this many bits. - Snorm(u32), - /// An 8-bit sRGB-encoded color channel. - Srgb, - /// Unsigned integer, of this many bits. - Uint(u32), - /// Signed integer, of this many bits. - Sint(u32), - /// IEEE half. - Half, - /// IEEE single. - Float, - /// An unsigned small float with a 5-bit exponent and this many mantissa bits. - Ufloat(u32), - /// A channel of RGB9E5's shared exponent. - Shared, - /// A field of this many bits a fill and a clear write as zeros: an RGBX format's X field of a - /// normalized or integer kind. - Zero(u32), -} - -/// The channels (red, green, blue, alpha) of each color format a pass can render to, or `None` -/// for a format with no Metal clear rule here (a depth, stencil or compressed format). -fn channels(pf: PixelFormat) -> Option<[Channel; 4]> { - use Channel::*; - use PixelFormat as P; - let one = |c| [c, Unused, Unused, Unused]; - let two = |c| [c, c, Unused, Unused]; - let four = |c| [c, c, c, c]; - Some(match pf { - P::A8Unorm => [Unused, Unused, Unused, Unorm(8)], - P::R8Unorm => one(Unorm(8)), - P::R8UnormSRGB => one(Srgb), - P::R8Snorm => one(Snorm(8)), - P::R8Uint => one(Uint(8)), - P::R8Sint => one(Sint(8)), - P::R16Unorm => one(Unorm(16)), - P::R16Snorm => one(Snorm(16)), - P::R16Uint => one(Uint(16)), - P::R16Sint => one(Sint(16)), - P::R16Float => one(Half), - P::RG8Unorm => two(Unorm(8)), - P::RG8UnormSRGB => two(Srgb), - P::RG8Snorm => two(Snorm(8)), - P::RG8Uint => two(Uint(8)), - P::RG8Sint => two(Sint(8)), - P::B5G6R5Unorm => [HalfUnorm(5), HalfUnorm(6), HalfUnorm(5), Unused], - P::A1BGR5Unorm | P::BGR5A1Unorm => [HalfUnorm(5), HalfUnorm(5), HalfUnorm(5), HalfUnorm(1)], - P::ABGR4Unorm => four(HalfUnorm(4)), - // `BGRA4Unorm`'s channels are the same four 4-bit packed unorm channels in another order, - // so the rule the probe measured by channel width (`HalfUnorm`, at 1, 4, 5 and 6 bits over - // the four packed formats) is theirs. Metal's own clear of this format is unmeasured, and - // a device that renders its word is what would reach one. - P::BGRA4Unorm => four(HalfUnorm(4)), - P::R32Uint => one(Uint(32)), - P::R32Sint => one(Sint(32)), - P::R32Float => one(Float), - P::RG16Unorm => two(Unorm(16)), - P::RG16Snorm => two(Snorm(16)), - P::RG16Uint => two(Uint(16)), - P::RG16Sint => two(Sint(16)), - P::RG16Float => two(Half), - P::RGBA8Unorm | P::BGRA8Unorm => four(Unorm(8)), - // Metal clears `ARGB8Unorm` as `RGBA8Unorm`, its channels rotated. - P::ARGB8Unorm => four(Unorm(8)), - P::RGBA8UnormSRGB | P::BGRA8UnormSRGB => [Srgb, Srgb, Srgb, Unorm(8)], - P::RGBA8Snorm => four(Snorm(8)), - P::RGBA8Uint => four(Uint(8)), - P::RGBA8Sint => four(Sint(8)), - P::RGB10A2Unorm | P::BGR10A2Unorm => [Unorm(10), Unorm(10), Unorm(10), Unorm(2)], - P::RGB10A2Uint => [Uint(10), Uint(10), Uint(10), Uint(2)], - P::RG11B10Float => [Ufloat(6), Ufloat(6), Ufloat(5), Unused], - P::RGB9E5Float => [Shared, Shared, Shared, Unused], - P::RG32Uint => two(Uint(32)), - P::RG32Sint => two(Sint(32)), - P::RG32Float => two(Float), - P::RGBA16Unorm => four(Unorm(16)), - P::RGBA16Snorm => four(Snorm(16)), - P::RGBA16Uint => four(Uint(16)), - P::RGBA16Sint => four(Sint(16)), - P::RGBA16Float => four(Half), - P::RGBA32Uint => four(Uint(32)), - P::RGBA32Sint => four(Sint(32)), - P::RGBA32Float => four(Float), - // The RGBX formats: the twin's red, green and blue; the X field zeros where the twin's - // alpha is normalized or an integer, the alpha's value where it is a float (three fill - // colors of each format, beside its RGBA twin; a clear of a whole level by a pass without a - // draw call). - P::RGBX8Unorm => [Unorm(8), Unorm(8), Unorm(8), Zero(8)], - P::RGBX8UnormSRGB => [Srgb, Srgb, Srgb, Zero(8)], - P::RGBX8Snorm => [Snorm(8), Snorm(8), Snorm(8), Zero(8)], - P::RGBX8Uint => [Uint(8), Uint(8), Uint(8), Zero(8)], - P::RGBX8Sint => [Sint(8), Sint(8), Sint(8), Zero(8)], - P::RGBX16Uint => [Uint(16), Uint(16), Uint(16), Zero(16)], - P::RGBX16Sint => [Sint(16), Sint(16), Sint(16), Zero(16)], - P::RGBX16Float => four(Half), - P::RGBX32Uint => [Uint(32), Uint(32), Uint(32), Zero(32)], - P::RGBX32Sint => [Sint(32), Sint(32), Sint(32), Zero(32)], - P::RGBX32Float => four(Float), - _ => return None, - }) -} - -/// The channels (red, green, blue, alpha) color format `pf` has, or `None` for a format a pass -/// cannot render to here. -pub(super) fn has_channels(pf: PixelFormat) -> Option<[bool; 4]> { - Some(channels(pf)?.map(|c| c != Channel::Unused)) -} - -/// The Vulkan clear value of Metal's clear `color` for an attachment of `pf`, whose Vulkan -/// format presents Metal's channels in order (attachment formats do, but an image holding them -/// rotated, `ARGB8Unorm`'s, whose clear value is rotated as its image holds them, -/// `metal::format::to_rotated_image`): an integer format's integers as Metal's conversion makes -/// them, another format's floats, which the device converts (the module docs). An extended-range -/// attachment's codes are by Metal's route `route`. `None` for a format with no clear rule. -pub(super) fn color( - pf: PixelFormat, - color: [f64; 4], - route: ClearRoute, -) -> Option { - // An extended-range attachment holds its raw texels: the clear is the texel Metal stores. - if let Some(form) = ExtendedRange::of(pf) { - return Some(vk::ClearColorValue { - uint32: form.clear_texel(color, route), - }); - } - // A YCbCr attachment's floats, each the clear's `half`: the store encodes them. - if ycbcr_renders(pf) { - return Some(vk::ClearColorValue { - float32: color.map(|c| f16_to_f32(f32_to_f16(c as f32))), - }); - } - let channels = channels(pf)?; - let each = channels.iter().zip(color); - Some(if channels.iter().any(|c| matches!(c, Channel::Uint(_))) { - let mut uint32 = [0u32; 4]; - for (out, (&channel, x)) in uint32.iter_mut().zip(each) { - if let Channel::Uint(bits) = channel { - *out = uint(x, bits); - } - } - vk::ClearColorValue { uint32 } - } else if channels.iter().any(|c| matches!(c, Channel::Sint(_))) { - let mut int32 = [0i32; 4]; - for (out, (&channel, x)) in int32.iter_mut().zip(each) { - if let Channel::Sint(bits) = channel { - *out = sint(x, bits); - } - } - vk::ClearColorValue { int32 } - } else { - let mut float32 = [0f32; 4]; - for (out, (&channel, x)) in float32.iter_mut().zip(each) { - *out = native(channel, x); - } - if rotated_channels(pf) { - float32 = to_rotated_image(float32); - } - vk::ClearColorValue { float32 } - }) -} - -/// The float clear value of Metal's clear value `x` in a channel of `channel` the device converts -/// (the module docs): `x` as a `float`; a NaN 0 where Vulkan states no conversion of it (a -/// normalized or sRGB channel's, a shared exponent's), elsewhere the double's sign and top payload -/// bits, quieted (`0x7ff0000020000000` clears to `0x7fc00001`), which a cast leaves to the -/// platform. 0 in a channel the format does not have or writes as zeros. -fn native(channel: Channel, x: f64) -> f32 { - match channel { - Channel::Unused | Channel::Zero(_) | Channel::Uint(_) | Channel::Sint(_) => 0.0, - Channel::Unorm(_) - | Channel::HalfUnorm(_) - | Channel::Snorm(_) - | Channel::Srgb - | Channel::Shared - if x.is_nan() => - { - 0.0 - } - _ if x.is_nan() => { - let bits = x.to_bits(); - let sign = ((bits >> 32) & 0x8000_0000) as u32; - f32::from_bits(sign | 0x7fc0_0000 | ((bits >> 29) & 0x7f_ffff) as u32) - } - _ => x as f32, - } -} - -/// How near a midpoint between two codes a `Depth16Unorm` clear's scaled depth lies where a -/// device rounding to nearest, as Vulkan asks, may round it either way: a tie, or a value its -/// arithmetic may take across one ([`depth16_rounded`]). -const TIE: f64 = 1.0 / 1024.0; - -/// Whether the device's conversion of [`color`]'s clear value of `color` for an attachment of -/// `pf` may store another texel than Metal's clear (the module docs): a channel whose rounding is -/// in question, a normalized one's anywhere off a whole code, where Vulkan lets the device store -/// either of the two codes closest to it. False for a clear the device converts nothing of (an -/// integer, extended-range or YCbCr format's, or a format with no clear rule), and for a NaN, -/// whose half or small float the device converts as it likes (`nan_clear::degrade_nan_clears`). -pub(super) fn rounds_apart(pf: PixelFormat, color: [f64; 4]) -> bool { - if ExtendedRange::of(pf).is_some() || ycbcr_renders(pf) { - return false; - } - let Some(channels) = channels(pf) else { - return false; - }; - let values: [f32; 4] = std::array::from_fn(|i| native(channels[i], color[i])); - // In question anywhere off a whole code, where the device may store either code nearest it. - // A packed 16-bit channel's whole code is Metal's too: its step through `half` moves the - // scaled value by at most its code range times 2^-11, under half a code. - let apart = |v: f32, lo: f32, max: u64| { - let r = f64::from(v.clamp(lo, 1.0)) * max as f64; - r != r.round() - }; - channels - .iter() - .zip(values) - .any(|(&channel, v)| match channel { - Channel::Unused - | Channel::Zero(_) - | Channel::Uint(_) - | Channel::Sint(_) - | Channel::Float => false, - Channel::Unorm(bits) | Channel::HalfUnorm(bits) => apart(v, 0.0, (1 << bits) - 1), - Channel::Snorm(bits) => apart(v, -1.0, (1 << (bits - 1)) - 1), - Channel::Srgb => v > 0.0 && v < 1.0, - Channel::Half => !v.is_nan() && f16_to_f32(f32_to_f16(v)) != v, - Channel::Ufloat(mantissa) => { - let largest = (2.0 - 1.0 / f64::from(1u32 << mantissa)) * 2f64.powi(15); - let spacing = 2f64.powi(binade(v).max(-14)) / f64::from(1u32 << mantissa); - let held = v.is_nan() - || v <= 0.0 - || v == f32::INFINITY - || (f64::from(v) <= largest && (f64::from(v) / spacing).fract() == 0.0); - !held - } - Channel::Shared => !shared_held(&channels, values), - }) -} - -/// Whether an `RGB9E5Float` clear of `values` (its native clear values, [`native`]) is one texel -/// exactly: each channel, negative values 0, a whole number of the shared exponent's spacing, the -/// largest channel at most 65408, the format's largest value. -fn shared_held(channels: &[Channel; 4], values: [f32; 4]) -> bool { - let shared = || { - channels - .iter() - .zip(values) - .filter(|(&c, _)| c == Channel::Shared) - .map(|(_, v)| f64::from(v.max(0.0))) - }; - let max = shared().fold(0.0, f64::max); - if max > 65408.0 { - return false; - } - // Nine mantissa bits under a shared exponent of `binade(max) + 1`, at least -15. - let spacing = 2f64.powi(binade(max as f32).max(-16) + 1 - 9); - shared().all(|v| (v / spacing).fract() == 0.0) -} - -/// [`color`] for an attachment of `pf` whose image is of Vulkan format `format`: an `A8Unorm` -/// image held in `R8_UNORM` (`metal::format::FormatEmulation::AlphaInRed`) takes the clear's alpha -/// in red, as it holds Metal's alpha (Metal's clear stores the color's alpha, probe `a8`, an M3 -/// Max under macOS 27.0.1). -pub(super) fn held_color( - pf: PixelFormat, - format: Format, - color: [f64; 4], - route: ClearRoute, -) -> Option { - let value = self::color(pf, color, route)?; - if alpha_in_red_format(pf) != Some(format) { - return Some(value); - } - // SAFETY: `color` gives a normalized format's clear as `float32`. - let float32 = unsafe { value.float32 }; - Some(vk::ClearColorValue { - float32: to_rotated_image(float32), - }) -} - -/// The Vulkan clear value of Metal's clear `color` for an attachment of `pf` that renders through -/// the view of its word `word` (`metal::format::WordAttachment`): the word of the codes Metal's -/// clear stores (each channel by Metal's conversion, [`code`]; `RGB9E5Float`'s word of the color -/// through `float`, its mantissas truncated, `WordAttachment::output_word`), in the view's one -/// unsigned component, which the device converts nothing of. `None` for a format with no clear -/// rule. -pub(super) fn word( - pf: PixelFormat, - color: [f64; 4], - word: WordAttachment, -) -> Option { - if word == WordAttachment::Rgb9e5 { - let uint32 = [word.output_word(color.map(|c| c as f32))?, 0, 0, 0]; - return Some(vk::ClearColorValue { uint32 }); - } - let channels = channels(pf)?; - let mut codes = [0u32; 4]; - for (out, (&channel, x)) in codes.iter_mut().zip(channels.iter().zip(color)) { - *out = code(channel, x)?; - } - Some(vk::ClearColorValue { - uint32: [word.pack(codes), 0, 0, 0], - }) -} - -/// Whether a float channel of `value`, the Vulkan clear value [`color`] gives an attachment of -/// `pf`, is a NaN: `Some(true)` where a `half` or small-float one is, whose bits Vulkan leaves to -/// the device's conversion (`nan_clear::degrade_nan_clears`), `Some(false)` where only a 32-bit -/// float one is, which converts nothing. `None` for every other clear. -pub(super) fn nan_channels(pf: PixelFormat, value: &vk::ClearColorValue) -> Option { - let channels = channels(pf)?; - // SAFETY: every member of the union is four 32-bit values; any bits are a valid `f32`. - let float32 = unsafe { value.float32 }; - let nans = || channels.iter().zip(float32).filter(|(_, v)| v.is_nan()); - let narrow = nans().any(|(c, _)| matches!(c, Channel::Half | Channel::Ufloat(_))); - let float = nans().any(|(c, _)| matches!(c, Channel::Float)); - (narrow || float).then_some(narrow) -} - -/// The unsigned-integer format of `texel`'s size (2, 4, 8 or 16 bytes: `R16_UINT`, `R32_UINT`, -/// `R32G32_UINT`, `R32G32B32A32_UINT`) and the clear value whose conversion into it writes -/// exactly `texel`'s bytes, its little-endian 16- or 32-bit words: a texel whose bits no clear -/// of its own format controls is written so, then copied bit-wise into an image of its format -/// (a new multisampled texture's pattern: `first_move::Pattern::Scratch`). -/// `None` for another size. -pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)> { - let format = match texel.len() { - 2 => Format::R16_UINT, - 4 => Format::R32_UINT, - 8 => Format::R32G32_UINT, - 16 => Format::R32G32B32A32_UINT, - _ => return None, - }; - let mut uint32 = [0; 4]; - match texel { - [low, high] => uint32[0] = u32::from(u16::from_le_bytes([*low, *high])), - _ => { - for (word, bytes) in uint32.iter_mut().zip(texel.as_chunks::<4>().0.iter()) { - *word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); - } - } - } - Some((format, vk::ClearColorValue { uint32 })) -} - -/// The code Metal's clear stores in a channel of `channel` of a word attachment, for the clear -/// value `x` (the module docs): a normalized or sRGB code, 0 in a channel the format does not -/// have. `None` for another kind of channel, which no word attachment has. -fn code(channel: Channel, x: f64) -> Option { - Some(match channel { - Channel::Unused | Channel::Zero(_) => 0, - Channel::Unorm(bits) => unorm(x as f32 as f64, bits), - Channel::HalfUnorm(bits) => unorm(f64::from(f16_to_f32(f32_to_f16(x as f32))), bits), - Channel::Srgb => srgb_encode(x as f32 as f64), - _ => return None, - }) -} - -/// `v` as an unsigned normalized code of `bits`: NaN is 0, clamped, nearest (ties to even). -fn unorm(v: f64, bits: u32) -> u32 { - let max = (1u64 << bits) - 1; - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - // Exact: a `float` (or `half`) times a 16-bit integer fits a double's mantissa. - (v * max as f64).round_ties_even() as u32 -} - -/// `x` truncated toward zero and saturated to an unsigned integer of `bits`; NaN is 0. -fn uint(x: f64, bits: u32) -> u32 { - let max = ((1u64 << bits) - 1) as f64; - if x.is_nan() || x <= 0.0 { - 0 - } else if x >= max { - max as u32 - } else { - x.trunc() as u32 - } -} - -/// `x` truncated toward zero and saturated to a signed integer of `bits`; NaN is 0. -fn sint(x: f64, bits: u32) -> i32 { - let max = ((1i64 << (bits - 1)) - 1) as f64; - let min = -(1i64 << (bits - 1)) as f64; - if x.is_nan() { - 0 - } else { - x.trunc().clamp(min, max) as i32 - } -} - -/// The 8-bit sRGB encoding of linear `v`: NaN is 0, clamped, the sRGB curve, nearest. -fn srgb_encode(v: f64) -> u32 { - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - let s = if v <= 0.0031308 { - 12.92 * v - } else { - 1.055 * v.powf(1.0 / 2.4) - 0.055 - }; - (s * 255.0).round_ties_even().clamp(0.0, 255.0) as u32 -} - -/// `v` as an IEEE half's bits, rounding to nearest even; NaN is the canonical quiet NaN. -pub(crate) fn f32_to_f16(v: f32) -> u16 { - if v.is_nan() { - return 0x7e00; - } - let bits = v.to_bits(); - let sign = ((bits >> 16) & 0x8000) as u16; - if v.is_infinite() { - return sign | 0x7c00; - } - let a = f64::from(v.abs()); - // The half nearest `a`, ties to even: scale by the binade's spacing and round. - let exponent = binade(v).max(-14); - let spacing = 2f64.powi(exponent - 10); - let mut steps = (a / spacing).round_ties_even(); - let mut exponent = exponent; - if steps >= 2048.0 { - // Rounded up into the next binade. - exponent += 1; - steps /= 2.0; - } - if exponent > 15 { - return sign | 0x7c00; - } - let steps = steps as u16; - if steps < 1024 { - // Subnormal (only at the lowest exponent). - sign | steps - } else { - sign | (((exponent + 15) as u16) << 10) | (steps - 1024) - } -} - -/// An IEEE half's value. -pub(super) fn f16_to_f32(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let exponent = i32::from((h >> 10) & 0x1f); - let mantissa = f64::from(h & 0x3ff); - let value = match exponent { - 0 => mantissa * 2f64.powi(-24), - 0x1f if mantissa == 0.0 => f64::INFINITY, - 0x1f => return f32::NAN, - e => (1.0 + mantissa / 1024.0) * 2f64.powi(e - 15), - }; - (sign * value) as f32 -} - -/// `floor(log2(|v|))` of a finite `v`, from its bits: exact at every power of two. Zero and the -/// `float` subnormals answer -127, below every binade the callers use. -pub(super) fn binade(v: f32) -> i32 { - let biased = ((v.to_bits() >> 23) & 0xff) as i32; - if biased == 0 { - -127 - } else { - biased - 127 - } -} - -/// The Vulkan clear depth of Metal's `depth` (already checked to lie in `[0, 1]`): the depth as a -/// `float`, which the device converts to the attachment's format (the module docs). -pub(super) fn depth(depth: f64) -> f32 { - depth as f32 -} - -/// Whether the device's conversion of [`depth`]'s clear depth for an attachment of `pf` may store -/// another code than Metal's (`unorm-depth-rounding`): a `Depth16Unorm` depth whose scaled value -/// lies at or within [`TIE`] of a midpoint between two codes or above it, which Metal's clear -/// truncates and a device rounding to nearest takes to the code above. -pub(super) fn depth16_rounded(pf: PixelFormat, depth: f64) -> bool { - let r = f64::from(self::depth(depth)) * 65535.0; - pf == PixelFormat::Depth16Unorm && r - r.floor() >= 0.5 - TIE -} - -/// The Vulkan clear stencil of Metal's `stencil`: its low 8 bits. -pub(super) fn stencil(stencil: u32) -> u32 { - stencil & 0xff -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use PixelFormat as P; - - /// The texel value Metal's conversion gives one channel: an integer, or the bits of a float. - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - enum Texel { - /// A normalized integer `k` of `max` (`k / max` is the value), or a signed one. - Norm { - k: i64, - max: i64, - }, - /// An sRGB-encoded 8-bit value. - Srgb(u32), - Uint(u32), - Sint(i32), - /// A value exactly representable as a `float` (a `half`, small-float or shared-exponent - /// result, decoded), by its bits. - Exact(u32), - } - - /// Each channel's texel under Metal's conversion of `color`: the model of Metal's measured - /// clears the tests compare the runtime's with (the module docs). - fn convert(channels: &[Channel; 4], color: [f64; 4]) -> [Texel; 4] { - let shared = shared_exponent(channels, color); - let mut out = [Texel::Uint(0); 4]; - for (i, (&channel, &x)) in channels.iter().zip(&color).enumerate() { - out[i] = match channel { - Channel::Unused | Channel::Zero(_) => Texel::Uint(0), - Channel::Unorm(bits) => metal_unorm(x as f32 as f64, bits), - Channel::HalfUnorm(bits) => { - metal_unorm(f16_to_f32(f32_to_f16(x as f32)) as f64, bits) - } - Channel::Snorm(bits) => metal_snorm(x as f32 as f64, bits), - Channel::Srgb => Texel::Srgb(srgb_encode(x as f32 as f64)), - Channel::Uint(bits) => Texel::Uint(uint(x, bits)), - Channel::Sint(bits) => Texel::Sint(sint(x, bits)), - // A NaN is the quiet `float` NaN of the double's sign and top payload bits, which - // Metal's clear keeps where it keeps a `half` NaN's sign; every other value is the - // `half`'s. - Channel::Half if x.is_nan() => { - let bits = x.to_bits(); - let sign = ((bits >> 32) & 0x8000_0000) as u32; - let payload = ((bits >> 29) & 0x7f_ffff) as u32; - Texel::Exact(sign | 0x7fc0_0000 | payload) - } - Channel::Half => Texel::Exact(f16_to_f32(f32_to_f16(x as f32)).to_bits()), - // A NaN is the double's sign and top payload bits, quieted: Metal's conversion - // (`0x7ff0000020000000` clears to `0x7fc00001`), which a cast leaves to - // the platform. - Channel::Float if x.is_nan() => { - let bits = x.to_bits(); - let sign = ((bits >> 32) & 0x8000_0000) as u32; - Texel::Exact(sign | 0x7fc0_0000 | ((bits >> 29) & 0x7f_ffff) as u32) - } - Channel::Float => Texel::Exact((x as f32).to_bits()), - Channel::Ufloat(mantissa) => { - Texel::Exact(ufloat_value(x as f32, mantissa).to_bits()) - } - Channel::Shared => Texel::Exact((shared[i] as f32).to_bits()), - }; - } - out - } - - /// `v` as an unsigned normalized integer of `bits`: NaN is 0, clamped, nearest (ties to even). - fn metal_unorm(v: f64, bits: u32) -> Texel { - let max = (1i64 << bits) - 1; - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - // Exact: a `float` (or `half`) times a 16-bit integer fits a double's mantissa. - Texel::Norm { - k: (v * max as f64).round_ties_even() as i64, - max, - } - } - - /// `v` as a signed normalized integer of `bits`: NaN is 0, clamped to `[-1, 1]`, nearest. - fn metal_snorm(v: f64, bits: u32) -> Texel { - let max = (1i64 << (bits - 1)) - 1; - let v = if v.is_nan() { 0.0 } else { v.clamp(-1.0, 1.0) }; - Texel::Norm { - k: (v * max as f64).round_ties_even() as i64, - max, - } - } - - /// Metal's small unsigned float of `mantissa` bits (and a 5-bit exponent) for `v`, decoded: - /// negative values are 0, NaN stays NaN, infinity stays, a finite value past the largest is the - /// largest, and the mantissa is truncated. - fn ufloat_value(v: f32, mantissa: u32) -> f32 { - if v.is_nan() { - return f32::NAN; - } - if v <= 0.0 { - return 0.0; - } - if v.is_infinite() { - return f32::INFINITY; - } - let steps = f64::from(1u32 << mantissa); - let largest = (2.0 - 1.0 / steps) * 2f64.powi(15); - let exponent = binade(v).max(-14); - let v = f64::from(v); - if v >= largest { - return largest as f32; - } - let spacing = 2f64.powi(exponent) / steps; - ((v / spacing).floor() * spacing) as f32 - } - - /// The three channel values of an RGB9E5 clear, decoded (zero where `channels` is not - /// RGB9E5's): NaN and negative values are 0 and values past 65408 are 65408; the exponent is - /// that of the largest channel (at least -16) and every mantissa is truncated. - fn shared_exponent(channels: &[Channel; 4], color: [f64; 4]) -> [f64; 4] { - const LARGEST: f32 = 65408.0; - let mut out = [0.0; 4]; - if !channels.contains(&Channel::Shared) { - return out; - } - let mut values = [0.0f32; 4]; - for (value, (&channel, &x)) in values.iter_mut().zip(channels.iter().zip(&color)) { - if channel == Channel::Shared { - let x = x as f32; - *value = if x.is_nan() { - 0.0 - } else { - x.clamp(0.0, LARGEST) - }; - } - } - let max = values.iter().copied().fold(0.0, f32::max); - let exponent = binade(max).max(-16); - // Nine mantissa bits under a shared exponent of `exponent + 1`. - let spacing = 2f64.powi(exponent + 1 - 9); - for (o, v) in out.iter_mut().zip(values) { - *o = (f64::from(v) / spacing).floor() * spacing; - } - out - } - - /// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`, - /// which is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top - /// mantissa bit), as Metal writes it (a Metal probe on the M3 Max and an M4). - fn ufloat_bits(v: f32, mantissa: u32) -> u64 { - if v.is_nan() { - return (31 << mantissa) | (1 << (mantissa - 1)); - } - if v.is_infinite() { - return 31 << mantissa; - } - if v <= 0.0 { - return 0; - } - let steps = 1u64 << mantissa; - let exponent = binade(v).max(-14); - // Exact: `v` is a whole number of the binade's spacing. - let scaled = (f64::from(v) / 2f64.powi(exponent) * steps as f64) as u64; - match scaled < steps { - true => scaled, - false => (((exponent + 15) as u64) << mantissa) | (scaled - steps), - } - } - - /// The bytes of the texel a clear of `color` writes into an attachment of `pf`: each channel - /// converted as [`convert`] converts it, laid out as Metal lays out `pf`'s texel, - /// little-endian, the fields from the texel's lowest bit in the order the format's name lists - /// them (B5G6R5: blue in bits 0 to 4; RGB9E5: the exponent last). `None` for a format with no - /// clear rule here. - pub(crate) fn texel_bytes(pf: PixelFormat, color: [f64; 4]) -> Option> { - use PixelFormat as P; - let channels = channels(pf)?; - let texels = convert(&channels, color); - let order: &[usize] = match pf { - P::BGRA8Unorm - | P::BGRA8UnormSRGB - | P::BGR10A2Unorm - | P::BGR5A1Unorm - | P::BGRA4Unorm => &[2, 1, 0, 3], - P::B5G6R5Unorm => &[2, 1, 0], - P::A1BGR5Unorm | P::ABGR4Unorm => &[3, 2, 1, 0], - // Alpha in the lowest byte, then red, green and blue (the format scout's color fill on - // an M4 under macOS 27.0.1 wrote `ff 40 80 bf` for (0.25, 0.5, 0.75, 1)). - P::ARGB8Unorm => &[3, 0, 1, 2], - _ => &[0, 1, 2, 3], - }; - // RGB9E5's shared exponent: its largest channel's binade (at least -16), which the decoded - // channels keep, since a truncated mantissa stays in its binade. - let largest = texels[..3] - .iter() - .map(|t| match t { - Texel::Exact(bits) => f32::from_bits(*bits), - _ => 0.0, - }) - .fold(0.0, f32::max); - let shared = binade(largest).max(-16); - let mut bits = 0u128; - let mut at = 0; - let mut put = |value: u64, width: u32| { - bits |= u128::from(value & ((1u64 << width) - 1)) << at; - at += width; - }; - for &i in order { - let (value, width) = match (channels[i], texels[i]) { - (Channel::Unused, _) => continue, - (Channel::Zero(b), _) => (0, b), - ( - Channel::Unorm(b) | Channel::HalfUnorm(b) | Channel::Snorm(b), - Texel::Norm { k, .. }, - ) => (k as u64, b), - (Channel::Srgb, Texel::Srgb(k)) => (u64::from(k), 8), - (Channel::Uint(b), Texel::Uint(v)) => (u64::from(v), b), - (Channel::Sint(b), Texel::Sint(v)) => (v as i64 as u64, b), - (Channel::Half, Texel::Exact(f)) => (u64::from(f32_to_f16(f32::from_bits(f))), 16), - (Channel::Float, Texel::Exact(f)) => (u64::from(f), 32), - (Channel::Ufloat(m), Texel::Exact(f)) => (ufloat_bits(f32::from_bits(f), m), m + 5), - (Channel::Shared, Texel::Exact(f)) => { - // Exact: the value is a whole number of the shared exponent's spacing. - let spacing = 2f64.powi(shared + 1 - 9); - ((f64::from(f32::from_bits(f)) / spacing) as u64, 9) - } - _ => return None, - }; - put(value, width); - } - if channels.contains(&Channel::Shared) { - put((shared + 16) as u64, 5); - } - let bytes = at.div_ceil(8) as usize; - Some(bits.to_le_bytes()[..bytes].to_vec()) - } - - /// A word attachment's clear value ([`word`]) is the little-endian word of the texel Metal's - /// clear writes ([`texel_bytes`]), for every packed 16-bit layout, the one- and two-channel - /// 8-bit sRGB ones and `RGB9E5Float`'s, over colors at and beside each layout's ties, NaN, - /// negative values, values past one and past `RGB9E5Float`'s largest, and tiny ones. - #[test] - fn word_clears_are_metals_texels() { - let values = [ - 0.0, - 1.0, - 0.5, - 0.49, - 0.1, - 0.25, - 0.75, - 1.0 / 3.0, - 0.016, - -0.5, - 2.0, - f64::NAN, - 15.5 / 31.0, - 7.5 / 15.0, - 31.5 / 63.0, - 70000.0, - 3.0e-6, - 1000.3, - ]; - for pf in [ - P::B5G6R5Unorm, - P::A1BGR5Unorm, - P::ABGR4Unorm, - P::BGR5A1Unorm, - P::R8UnormSRGB, - P::RG8UnormSRGB, - P::RGB9E5Float, - ] { - let layout = WordAttachment::layout(pf).expect("a word layout"); - for (i, &r) in values.iter().enumerate() { - let n = values.len(); - let color = [ - r, - values[(i + 3) % n], - values[(i + 7) % n], - values[(i + 11) % n], - ]; - let got = word(pf, color, layout).expect("a clear value"); - // SAFETY: every member of the union is four 32-bit values; any bits are a `u32`. - let got = unsafe { got.uint32 }; - let texel = bytes(pf, color); - let want = - (texel.iter().enumerate()).fold(0u32, |w, (i, &b)| w | u32::from(b) << (8 * i)); - assert_eq!(got, [want, 0, 0, 0], "{pf:?} {color:?}"); - } - } - } - - /// The texels Metal writes, as little-endian bytes. - fn bytes(pf: PixelFormat, c: [f64; 4]) -> Vec { - texel_bytes(pf, c).unwrap_or_else(|| panic!("no packing for {pf:?}")) - } - - fn hex(b: &[u8]) -> String { - b.iter().map(|x| format!("{x:02x}")).collect() - } - - /// Every clear the M4 measured (our Metal probes; the NaNs on an M4 and the M3 Max alike), as - /// the bytes it wrote. - #[test] - fn metal_clears_are_reproduced() { - let n = f64::NAN; - let inf = f64::INFINITY; - let cases: &[(PixelFormat, [f64; 4], &str)] = &[ - (P::RGBA8Unorm, [0.5, 0.25, 1.5, -0.5], "8040ff00"), - ( - P::RGBA8Unorm, - [0.5 / 255.0, 1.5 / 255.0, 2.5 / 255.0, 0.501960784], - "01020380", - ), - (P::RGBA8Unorm, [0.0019, 0.0021, 0.998, 0.996], "0001fefe"), - (P::RGBA8Unorm, [n, inf, -inf, 0.75], "00ff00bf"), - (P::BGRA8Unorm, [0.25, 0.5, 0.75, 1.0], "bf8040ff"), - (P::RGBA8UnormSRGB, [0.5, 0.214, 0.0031308, 1.0], "bc7f0aff"), - (P::RGBA8UnormSRGB, [0.001, 0.01, 0.1, 0.5], "03195980"), - ( - P::RGBA8UnormSRGB, - [0.2158605, 0.2122308, 0.214, 0.25], - "807f7f40", - ), - (P::BGRA8UnormSRGB, [0.5, 0.214, 0.0031308, 0.5], "0a7fbc80"), - (P::RGBA8Snorm, [-1.5, -0.5, 0.5, 1.5 / 127.0], "81c04001"), - (P::RGBA8Snorm, [-1.0, -0.0039, 0.0039, 0.502], "81000040"), - (P::RGBA8Snorm, [n, inf, -inf, -0.0], "007f8100"), - (P::R8Uint, [3.7, 0.0, 0.0, 0.0], "03"), - (P::R8Uint, [300.0, 0.0, 0.0, 0.0], "ff"), - (P::R8Uint, [-1.0, 0.0, 0.0, 0.0], "00"), - (P::R8Uint, [255.5, 0.0, 0.0, 0.0], "ff"), - (P::R8Uint, [1e10, 0.0, 0.0, 0.0], "ff"), - (P::R8Uint, [n, 0.0, 0.0, 0.0], "00"), - (P::R8Uint, [256.0, 0.0, 0.0, 0.0], "ff"), - (P::R8Uint, [-0.5, 0.0, 0.0, 0.0], "00"), - (P::R8Sint, [-3.7, 0.0, 0.0, 0.0], "fd"), - (P::R8Sint, [200.0, 0.0, 0.0, 0.0], "7f"), - (P::R8Sint, [-200.0, 0.0, 0.0, 0.0], "80"), - (P::R8Sint, [127.5, 0.0, 0.0, 0.0], "7f"), - (P::R8Sint, [-128.5, 0.0, 0.0, 0.0], "80"), - (P::R8Sint, [3.7, 0.0, 0.0, 0.0], "03"), - (P::R16Uint, [65535.7, 0.0, 0.0, 0.0], "ffff"), - (P::R16Uint, [70000.0, 0.0, 0.0, 0.0], "ffff"), - (P::R16Uint, [-2.0, 0.0, 0.0, 0.0], "0000"), - (P::R16Sint, [-40000.0, 0.0, 0.0, 0.0], "0080"), - (P::R16Sint, [40000.0, 0.0, 0.0, 0.0], "ff7f"), - (P::R16Sint, [-2.5, 0.0, 0.0, 0.0], "feff"), - (P::R32Uint, [4294967295.0, 0.0, 0.0, 0.0], "ffffffff"), - (P::R32Uint, [4294967296.0, 0.0, 0.0, 0.0], "ffffffff"), - (P::R32Uint, [1e20, 0.0, 0.0, 0.0], "ffffffff"), - (P::R32Uint, [-1.0, 0.0, 0.0, 0.0], "00000000"), - (P::R32Uint, [3.999, 0.0, 0.0, 0.0], "03000000"), - (P::R32Uint, [2147483648.5, 0.0, 0.0, 0.0], "00000080"), - (P::R32Uint, [16777217.0, 0.0, 0.0, 0.0], "01000001"), - (P::R32Uint, [2147483649.0, 0.0, 0.0, 0.0], "01000080"), - (P::R32Uint, [4294967040.5, 0.0, 0.0, 0.0], "00ffffff"), - (P::R32Sint, [-2147483648.0, 0.0, 0.0, 0.0], "00000080"), - (P::R32Sint, [2147483648.0, 0.0, 0.0, 0.0], "ffffff7f"), - (P::R32Sint, [-2.5, 0.0, 0.0, 0.0], "feffffff"), - (P::R32Sint, [2.5, 0.0, 0.0, 0.0], "02000000"), - (P::R32Sint, [-3e9, 0.0, 0.0, 0.0], "00000080"), - (P::R32Sint, [-16777217.0, 0.0, 0.0, 0.0], "fffffffe"), - (P::R32Sint, [16777217.0, 0.0, 0.0, 0.0], "01000001"), - (P::R32Sint, [-2147483520.5, 0.0, 0.0, 0.0], "80000080"), - (P::R16Float, [0.1, 0.0, 0.0, 0.0], "662e"), - (P::R16Float, [70000.0, 0.0, 0.0, 0.0], "007c"), - (P::R16Float, [1e-8, 0.0, 0.0, 0.0], "0000"), - (P::R16Float, [-0.0, 0.0, 0.0, 0.0], "0080"), - (P::R16Float, [n, 0.0, 0.0, 0.0], "007e"), - (P::R16Float, [-n, 0.0, 0.0, 0.0], "007e"), - (P::RG16Float, [n, 1.0, 0.5, n], "007e003c"), - (P::RG16Float, [1.0, n, 2.0, 0.25], "003c007e"), - (P::R16Float, [65520.0, 0.0, 0.0, 0.0], "007c"), - (P::R16Float, [1.001220703125, 0.0, 0.0, 0.0], "013c"), - ( - P::R16Float, - [1.0 + 2f64.powi(-11) + 2f64.powi(-40), 0.0, 0.0, 0.0], - "003c", - ), - (P::R16Float, [1.0 + 2f64.powi(-11), 0.0, 0.0, 0.0], "003c"), - ( - P::R16Float, - [1.0 + 3.0 * 2f64.powi(-11), 0.0, 0.0, 0.0], - "023c", - ), - (P::R32Float, [0.1, 0.0, 0.0, 0.0], "cdcccc3d"), - (P::R32Float, [1e-40, 0.0, 0.0, 0.0], "c2160100"), - (P::R32Float, [1e39, 0.0, 0.0, 0.0], "0000807f"), - (P::R32Float, [n, 0.0, 0.0, 0.0], "0000c07f"), - (P::R32Float, [-n, 0.0, 0.0, 0.0], "0000c0ff"), - ( - P::R32Float, - [1.0 + 2f64.powi(-24), 0.0, 0.0, 0.0], - "0000803f", - ), - ( - P::RGBA16Float, - [0.1, -2.5, 65504.0, 1e-5], - "662e00c1ff7ba800", - ), - (P::RGBA16Float, [-n, -n, -n, -n], "007e007e007e007e"), - (P::RGBA16Float, [n, 1.0, 0.5, n], "007e003c0038007e"), - (P::RGBA16Float, [1.0, n, 2.0, 0.25], "003c007e00400034"), - (P::RG16Snorm, [-1.5, 0.5, 0.0, 0.0], "01800040"), - (P::RG16Snorm, [-1e-5, 0.99999, 0.0, 0.0], "0000ff7f"), - ( - P::RGBA16Unorm, - [0.5, 1.0 / 131070.0, 3.0 / 131070.0, 1.2], - "008000000100ffff", - ), - (P::RGB10A2Unorm, [0.5, 0.25, 1.0, 0.5], "0002f4bf"), - (P::RGB10A2Unorm, [0.0005, 0.9995, 0.33, 0.17], "01f82f55"), - (P::BGR10A2Unorm, [0.5, 0.25, 0.75, 0.4], "ff020460"), - ( - P::RGBA32Float, - [0.1, -1e39, 1e-40, 3.0], - "cdcccc3d000080ffc216010000004040", - ), - ( - P::RGBA32Uint, - [1.5, 4294967296.0, -1.0, 7.0], - "01000000ffffffff0000000007000000", - ), - (P::RG11B10Float, [0.1, -1.0, 70000.0, 0.0], "e602c0f7"), - (P::RG11B10Float, [1e-6, n, inf, 0.0], "01003ff8"), - (P::RG11B10Float, [n, n, n, n], "e0073ffc"), - (P::RG11B10Float, [-n, -n, -n, -n], "e0073ffc"), - (P::RG11B10Float, [n, 1.0, 0.5, n], "e0071e70"), - (P::RG11B10Float, [1.0, n, 2.0, 0.25], "c0033f80"), - (P::RG11B10Float, [65000.0, 0.5, 1e-5, 0.0], "be075c01"), - ( - P::RG11B10Float, - [ - 1.0 + 2f64.powi(-7), - 1.0 + 2f64.powi(-6), - 1.0 + 2f64.powi(-7), - 0.0, - ], - "c00b1e78", - ), - (P::RGB9E5Float, [0.1, 0.5, 2.0, 0.0], "0c80008c"), - (P::RGB9E5Float, [-1.0, 70000.0, 1e-3, 0.0], "00fe03f8"), - (P::RGB9E5Float, [65408.0, 1e-8, 3.0, 0.0], "ff0100f8"), - (P::RGB9E5Float, [n, inf, 1.0, 0.0], "00fe03f8"), - (P::RGB9E5Float, [-n, -n, -n, -n], "00000000"), - (P::RGB9E5Float, [n, 1.0, 0.5, n], "00000282"), - (P::RGB9E5Float, [1.0, n, 2.0, 0.25], "8000008c"), - (P::B5G6R5Unorm, [0.5, 0.25, 0.75, 1.0], "1782"), - (P::A1BGR5Unorm, [0.5, 0.25, 0.75, 0.5], "2e82"), - (P::A1BGR5Unorm, [0.5, 0.25, 0.75, 0.49], "2e82"), - (P::ABGR4Unorm, [0.5, 0.25, 0.75, 0.1], "b184"), - (P::BGR5A1Unorm, [0.5, 0.25, 0.75, 0.6], "17c1"), - ]; - for &(pf, c, want) in cases { - assert_eq!(hex(&bytes(pf, c)), want, "{pf:?} {c:?}"); - } - } - - /// An `A8Unorm` attachment's clear writes the color's alpha (probe `a8`, an M3 Max under - /// macOS 27.0.1: a clear of (0.2, 0.4, 0.6, 0.8) stores 204): in `A8_UNORM`'s alpha, and in an - /// `R8_UNORM` image's red where the image holds Metal's alpha there; another format's image - /// takes [`color`]'s value as it is. - #[test] - fn an_alpha_in_red_clear_takes_the_alpha_in_red() { - let color = [0.2, 0.4, 0.6, 0.8]; - let route = ClearRoute::ThroughHalf; - let code = 204.0 / 255.0; - let held = |pf, format| { - let value = held_color(pf, format, color, route).expect("a clear rule"); - // SAFETY: a normalized format's clear is `float32`. - unsafe { value.float32 } - }; - assert_eq!(held(P::A8Unorm, Format::A8_UNORM), [0.0, 0.0, 0.0, code]); - assert_eq!(held(P::A8Unorm, Format::R8_UNORM), [code, 0.0, 0.0, 0.0]); - assert_eq!( - held(P::R8Unorm, Format::R8_UNORM), - [51.0 / 255.0, 0.0, 0.0, 0.0] - ); - } - - /// A texel's unsigned-integer clear writes its bytes: its little-endian words in the format - /// of its size (`RGBA16Float`'s fresh pattern, half NaNs around a zero, as two 32-bit words). - #[test] - fn uint_texels_clear_to_their_bytes() { - let rgba16 = [0xff, 0xff, 0, 0, 0xff, 0xff, 0xff, 0xff]; - let rgba32: Vec = (1..=16).collect(); - for (texel, format, words) in [ - (&[0x34, 0x12][..], Format::R16_UINT, [0x1234, 0, 0, 0]), - (&[0xff, 0xff, 0, 0][..], Format::R32_UINT, [0xffff, 0, 0, 0]), - (&rgba16[..], Format::R32G32_UINT, [0xffff, u32::MAX, 0, 0]), - ( - &rgba32[..], - Format::R32G32B32A32_UINT, - [0x0403_0201, 0x0807_0605, 0x0c0b_0a09, 0x100f_0e0d], - ), - ] { - let (got, value) = uint_texel(texel).unwrap(); - assert_eq!(got, format, "{texel:?}"); - // SAFETY: every member of the union is four 32-bit values. - assert_eq!(unsafe { value.uint32 }, words, "{texel:?}"); - } - for size in [0, 1, 3, 6, 12, 32] { - assert!(uint_texel(&vec![0xff; size]).is_none(), "{size} bytes"); - } - } - - /// The clear value of a format the device converts is the clear color as a `float`, not - /// Metal's texel's value: a normalized channel's past its range too, which Vulkan clamps, and a - /// normalized channel's NaN 0, which Vulkan states no conversion of. - #[test] - fn the_clear_value_is_the_color_as_a_float() { - // SAFETY (union reads): each arm reads the member `color` wrote for that format. - let float32 = |pf, c| unsafe { - color(pf, c, ClearRoute::ThroughHalf) - .expect("a clear rule") - .float32 - }; - assert_eq!( - float32(P::RGBA8Unorm, [0.5, 0.25, 1.5, -0.5]), - [0.5, 0.25, 1.5, -0.5] - ); - assert_eq!( - float32(P::RGBA8UnormSRGB, [0.5, 0.214, 0.0031308, 1.0]), - [0.5, 0.214, 0.0031308, 1.0] - ); - assert_eq!( - float32(P::RGBA8Snorm, [f64::NAN, 0.1, -1.5, 0.3]), - [0.0, 0.1, -1.5, 0.3] - ); - assert_eq!(float32(P::R16Float, [0.1, 0.0, 0.0, 0.0])[0], 0.1); - assert_eq!( - float32(P::RG11B10Float, [0.1, -1.0, 70000.0, 0.0]), - [0.1, -1.0, 70000.0, 0.0] - ); - assert_eq!( - float32(P::RGB9E5Float, [f64::NAN, 0.5, 3.0, 0.0]), - [0.0, 0.5, 3.0, 0.0] - ); - assert_eq!( - float32(P::B5G6R5Unorm, [0.5, 0.25, 0.75, 1.0])[..3], - [0.5, 0.25, 0.75] - ); - // A float NaN keeps the double's sign and top payload bits, quieted. - let nan = f64::from_bits(0x7ff0_0000_2000_0000); - assert_eq!( - float32(P::R32Float, [nan, 0.0, 0.0, 0.0])[0].to_bits(), - 0x7fc0_0001 - ); - assert_eq!( - float32(P::R16Float, [-f64::NAN, 0.0, 0.0, 0.0])[0].to_bits(), - 0xffc0_0000 - ); - // An integer clear is Metal's conversion of the double. - // SAFETY: an integer format's clear is its integers. - let v = color( - P::R32Uint, - [16777217.0, 0.0, 0.0, 0.0], - ClearRoute::ThroughHalf, - ) - .unwrap(); - assert_eq!(unsafe { v.uint32 }[0], 16777217); - let v = color(P::R8Sint, [-3.7, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf).unwrap(); - assert_eq!(unsafe { v.int32 }[0], -3); - assert!(color(P::Depth32Float, [0.0; 4], ClearRoute::ThroughHalf).is_none()); - } - - /// On every device a clear is in question wherever a normalized channel's scaled value is off - /// a whole code, where Vulkan lets the device store either of the two codes closest to it, as - /// the RTX 5080 Laptop GPU's clears stored (`R16Unorm`'s 0.001 is 65.535 codes, which it - /// stored as 65, Metal 66), a scaled `float` a hair off a whole code included (it may go - /// either way: `RGBA8Unorm`'s 0.2 is 51.0000008 codes). A whole code, and a channel of another - /// kind, is in question as for any other clear. - #[test] - fn every_clear_off_a_whole_code_is_in_question() { - let off = [ - (P::R16Unorm, [0.001, 0.0, 0.0, 0.0]), - (P::RGBA8Unorm, [0.25, 0.0, 0.0, 1.0]), - (P::RGBA8Unorm, [0.2, 0.0, 0.0, 1.0]), - (P::RG8Unorm, [0.0, 0.904, 0.0, 0.0]), - (P::R8Snorm, [-0.3, 0.0, 0.0, 0.0]), - (P::B5G6R5Unorm, [0.7529, 0.0, 0.0, 0.0]), - (P::RGBA8Unorm, [0.5, 0.0, 0.0, 1.0]), - ]; - for (pf, c) in off { - assert!(rounds_apart(pf, c), "{pf:?} {c:?}"); - } - let whole = [ - (P::RGBA8Unorm, [0.0, 1.0, 0.0, 1.0]), - (P::R8Snorm, [-1.0, 0.0, 0.0, 0.0]), - (P::RGBA8Uint, [3.0, 0.0, 0.0, 1.0]), - (P::R32Float, [0.1, 0.0, 0.0, 0.0]), - ]; - for (pf, c) in whole { - assert!(!rounds_apart(pf, c), "{pf:?} {c:?}"); - } - } - - /// A clear whose rounding is in question is the one announced: a normalized value off a whole - /// code (a tie, or a value's `float` a hair off a code), an sRGB value inside its range, a - /// value a half, small float or shared exponent does not hold; not a whole code, a value past - /// the range, a value the format holds, a 32-bit float or an integer. - #[test] - fn a_clear_whose_rounding_is_in_question_is_the_one_announced() { - let apart = [ - (P::RGBA8Unorm, [0.5, 0.0, 0.0, 0.0]), - (P::RGBA8Unorm, [0.0, 0.0, 0.0, 2.5 / 255.0]), - (P::RGBA8Snorm, [0.5 / 127.0, 0.0, 0.0, 0.0]), - (P::RGBA16Unorm, [0.5, 0.0, 0.0, 0.0]), - (P::RGBA8UnormSRGB, [0.25, 0.0, 0.0, 1.0]), - (P::R16Float, [0.1, 0.0, 0.0, 0.0]), - (P::R16Float, [70000.0, 0.0, 0.0, 0.0]), - (P::RG11B10Float, [0.1, 0.0, 0.0, 0.0]), - (P::RG11B10Float, [70000.0, 0.0, 0.0, 0.0]), - (P::RGB9E5Float, [1.0, 2f64.powi(-9), 0.0, 0.0]), - (P::RGB9E5Float, [70000.0, 0.0, 0.0, 0.0]), - (P::B5G6R5Unorm, [15.5 / 31.0, 0.0, 0.0, 0.0]), - (P::RGBA8Unorm, [0.0, 1.0, 0.25, 0.75]), - (P::RGBA8Unorm, [128.0 / 255.0, 0.0, 0.0, 0.0]), - (P::RGBA8Snorm, [-1.0 / 127.0, 0.0, 0.0, 0.0]), - ]; - for (pf, c) in apart { - assert!(rounds_apart(pf, c), "{pf:?} {c:?}"); - } - let held = [ - (P::RGBA8Unorm, [0.0, 1.0, 0.0, 1.0]), - (P::RGBA8Unorm, [1.5, -0.5, f64::NAN, f64::INFINITY]), - (P::RGBA8Snorm, [-1.0, -1.5, 0.0, 1.0]), - (P::RGBA8UnormSRGB, [0.0, 1.0, -0.5, 1.0]), - (P::R16Float, [0.5, 0.0, 0.0, 0.0]), - (P::RGBA16Float, [-2.0, 65504.0, f64::NAN, f64::INFINITY]), - (P::RG11B10Float, [1.0, 0.5, 2.0, 0.0]), - (P::RG11B10Float, [-1.0, f64::NAN, f64::INFINITY, 0.0]), - (P::RGB9E5Float, [1.0, 0.5, 2.0, 0.0]), - (P::RGB9E5Float, [65408.0, 0.0, 65408.0, 1.0]), - (P::R32Float, [0.1, 0.0, 0.0, 0.0]), - (P::R8Uint, [3.7, 0.0, 0.0, 0.0]), - (P::BGRA10XR, [0.1, 0.2, 0.3, 0.4]), - ]; - for (pf, c) in held { - assert!(!rounds_apart(pf, c), "{pf:?} {c:?}"); - } - } - - /// Where no rounding is in question, a normalized channel's value on a whole code, the device - /// stores Metal's code: every normalized and packed 16-bit format, over every value of 1/1024 - /// steps from -0.25 to 1.25 in each channel that lies on one (0 and 1, and those clamped to - /// them); and the clear of an sRGB, half, small-float or shared-exponent value the format - /// holds is Metal's texel. - #[test] - fn where_no_rounding_is_in_question_the_nearest_code_is_metal_s() { - for pf in [ - P::RGBA8Unorm, - P::RGBA8Snorm, - P::RGBA16Unorm, - P::RGBA16Snorm, - P::RGB10A2Unorm, - P::B5G6R5Unorm, - P::A1BGR5Unorm, - P::ABGR4Unorm, - ] { - let channels = channels(pf).expect("a clear rule"); - for step in -256..=1280 { - let x = f64::from(step) / 1024.0; - let c = [x, (x + 0.37) % 1.0, 1.0 - x, x * 0.71]; - let metal = convert(&channels, c); - for (i, &channel) in channels.iter().enumerate() { - let mut one = [0.0; 4]; - one[i] = c[i]; - if rounds_apart(pf, one) { - continue; - } - let v = native(channel, c[i]); - let (lo, max) = match channel { - Channel::Snorm(bits) => (-1.0, (1i64 << (bits - 1)) - 1), - Channel::Unorm(bits) | Channel::HalfUnorm(bits) => { - (0.0, (1i64 << bits) - 1) - } - _ => continue, - }; - let r = f64::from(v.clamp(lo, 1.0)) * max as f64; - let (up, even) = ((r + 0.5).floor() as i64, r.round_ties_even() as i64); - let Texel::Norm { k, .. } = metal[i] else { - panic!("{pf:?}: a normalized channel"); - }; - assert_eq!((up, even), (k, k), "{pf:?} channel {i} of {c:?}"); - } - } - } - for (pf, c) in [ - (P::RGBA8UnormSRGB, [0.0, 1.0, -0.5, 1.0]), - (P::RGBA16Float, [-2.0, 65504.0, 0.5, 6.103515625e-5]), - (P::RG11B10Float, [1.0, 0.5, 2.0, 0.0]), - (P::RGB9E5Float, [1.0, 0.5, 2.0, 0.0]), - ] { - assert!(!rounds_apart(pf, c), "{pf:?} {c:?}"); - // SAFETY (union read): a float format's clear is `float32`. - let value = unsafe { color(pf, c, ClearRoute::ThroughHalf).unwrap().float32 }; - assert_eq!( - bytes(pf, value.map(f64::from)), - bytes(pf, c), - "{pf:?} {c:?}" - ); - } - } - - /// An `ARGB8Unorm` attachment's clear value is the color as a `float`, in the image's red, - /// green, blue and alpha (Metal's bytes alpha, red, green and blue: an M4 under macOS 27.0.1, - /// plain and validated alike), which the nearest code of lands on each of Metal's bytes but - /// where the rounding is in question. - #[test] - fn argb8_clears_are_metals_bytes_rotated() { - let cases: [([f64; 4], [u8; 4]); 8] = [ - ([0.1, 0.2, 0.3, 0.4], [0x66, 0x1a, 0x33, 0x4d]), - ([1.0, 0.0, 0.0, 0.0], [0x00, 0xff, 0x00, 0x00]), - ([0.0, 0.0, 0.0, 1.0], [0xff, 0x00, 0x00, 0x00]), - ( - [127.5 / 255.0, 0.5 / 255.0, 254.5 / 255.0, 1.5 / 255.0], - [0x02, 0x80, 0x01, 0xfe], - ), - ([-0.5, 1.5, 0.25, 0.75], [0xbf, 0x00, 0xff, 0x40]), - ([0.6, 0.4, 0.2, 0.0], [0x00, 0x99, 0x66, 0x33]), - ([0.004, 0.996, 0.502, 0.498], [0x7f, 0x01, 0xfe, 0x80]), - ([f64::NAN, 0.5, 0.5, 0.5], [0x80, 0x00, 0x80, 0x80]), - ]; - let mut compared = 0; - for (clear, bytes) in cases { - // SAFETY (union read): `color` writes `float32` for a normalized format. - let f = unsafe { - color(P::ARGB8Unorm, clear, ClearRoute::ThroughHalf) - .unwrap() - .float32 - }; - let rotated = to_rotated_image(clear.map(|c| native(Channel::Unorm(8), c))); - assert_eq!(f, rotated, "{clear:?}"); - // The image's channel `i` holds Metal's channel `(i + 3) % 4`. - for (i, (x, b)) in f.iter().zip(bytes).enumerate() { - let mut one = [0.0; 4]; - one[(i + 3) % 4] = clear[(i + 3) % 4]; - if rounds_apart(P::ARGB8Unorm, one) { - continue; - } - let code = (f64::from(x.clamp(0.0, 1.0)) * 255.0).round(); - assert_eq!(code, f64::from(b), "{clear:?}: {f:?}"); - compared += 1; - } - } - assert!(compared >= 12, "{compared} bytes compared"); - } - - /// A depth clears as a `float`, which the device converts; a `Depth16Unorm` clear a device - /// rounding to nearest takes above Metal's truncation (probes 1, 2) is the one announced: - /// elsewhere the nearest code is Metal's. Stencil keeps 8 bits. - #[test] - fn depth_and_stencil_clears_are_the_device_s() { - assert_eq!(depth(0.3).to_bits(), 0x3e99999a); - assert_eq!(depth(0.1).to_bits(), 0x3dcccccd); - for (x, k, rounded) in [ - (0.5, 0x7fff, true), - (1.0 / 131070.0, 0, true), - (3.0 / 131070.0, 1, true), - (0.3, 0x4ccc, true), - (1.0, 0xffff, false), - (0.1, 0x1999, true), - (0.0, 0, false), - (0.25, 0x3fff, true), - (0.2, 0x3333, false), - ] { - assert_eq!(depth16_rounded(P::Depth16Unorm, x), rounded, "{x}"); - assert!(!depth16_rounded(P::Depth32Float, x), "{x}"); - let r = f64::from(depth(x)) * 65535.0; - // Metal truncates. - assert_eq!(r.trunc(), f64::from(k), "{x}"); - if !rounded { - assert_eq!(r.round(), f64::from(k), "{x} {r}"); - } - } - for (x, k) in [(0x5a, 0x5a), (0x1ff, 0xff), (0xffff_ffff, 0xff), (0x100, 0)] { - assert_eq!(stencil(x), k); - } - } - - /// The clear colors of our probe `bfp.m`, in its order: 2,048 colors of four - /// channels from its generator (NaNs, specials, `half` values and the midpoints between two - /// with their neighbours, bfloat midpoints with theirs, and random values), the first 38 of - /// them the specials in every channel. - fn bfloat_clear_colors() -> Vec<[f64; 4]> { - const SPECIALS: [f64; 38] = [ - 0.0, - -0.0, - 1.0, - -1.0, - 0.5, - 2.0, - 65504.0, - 65_519.999_999_999_99, - 65520.0, - 65536.0, - 1e10, - -1e10, - 3.402_823_466_385_288_6e38, - 1e39, - -1e39, - 1e-30, - -1e-30, - 5.960_464_477_539_063e-8, - 2.980_232_238_769_531_2e-8, - // The probe's `2.9802322387695315e-08`, the same double. - 2.980_232_238_769_531_2e-8, - 6.103_515_625e-5, - 6.097_555_160_522_461e-5, - 1.401_298_464_324_817e-45, - 1.0 + 1.0 / 256.0, - 1.0 + 3.0 / 256.0, - 1.0 + 1.0 / 2048.0, - 1.0 + 3.0 / 2048.0, - 1.0 + 1.0 / 2048.0 + 1.0 / 1_073_741_824.0, - 1.0 / 3.0, - 255.5, - 0.1, - 0.2, - 0.3, - 1e5, - 70000.0, - 100000.0, - 1e-8, - 1e-6, - ]; - const NANS: [u64; 6] = [ - 0x7ff8_0000_0000_0000, - 0xfff8_0000_0000_0000, - 0x7ff0_0000_0000_0001, - 0x7ff4_0000_0000_0000, - 0xfff0_0400_0000_0000, - 0x7ff8_4000_0000_0000, - ]; - let mut state = 0x9e37_79b9_7f4a_7c15u64; - let mut next = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - let mut value = move || -> f64 { - let r = next(); - let signed = |v: f64| if (r >> 30) & 1 == 1 { -v } else { v }; - match r % 8 { - 0 => f64::from_bits(NANS[((r >> 8) % 6) as usize]), - 1 | 2 => SPECIALS[((r >> 8) % 38) as usize], - 3 => { - // A `half` value, or the midpoint between it and the next, or a neighbour of - // the midpoint. - let h = (next() & 0x7bff) as u16; - let a = f64::from(f16_to_f32(h)); - let b = f64::from(f16_to_f32(h + 1)); - let m = (a + b) / 2.0; - signed(match (r >> 20) % 3 { - 0 => a, - 1 => m, - _ if (r >> 24) & 1 == 1 => m.next_up(), - _ => m.next_down(), - }) - } - 4 => { - // A bfloat midpoint, or a neighbour of it. - let f = f64::from(f32::from_bits((next() & 0x7f7f_0000) as u32 | 0x8000)); - signed(match (r >> 20) % 3 { - 0 => f, - 1 => f.next_up(), - _ => f.next_down(), - }) - } - _ => { - let u = (next() >> 11) as f64 / 9_007_199_254_740_992.0; - match (r >> 20) % 3 { - 0 => -2.0 + 5.0 * u, - 1 => -70000.0 + 140_000.0 * u, - // `ldexp(u, e)`: the power of two exact. - _ => u * f64::from_bits((1023 + (r >> 32) % 200 - 100) << 52), - } - } - } - }; - let mut colors: Vec<[f64; 4]> = (0..2048) - .map(|_| std::array::from_fn(|_| value())) - .collect(); - for (color, special) in colors.iter_mut().zip(SPECIALS) { - *color = [special; 4]; - } - colors - } - - /// FNV-1a of `bytes`. - fn fnv(bytes: impl Iterator) -> u64 { - bytes.fold(0xcbf2_9ce4_8422_2325, |h, b| { - (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) - }) - } - - /// A render pass's `Clear` of a bfloat color attachment (`R16Bfloat`, `RG16Bfloat`, - /// `RGBA16Bfloat`; the consumer's passes) stores Metal's codes for every color of our probe - /// `bfp.m` (an Apple M4 under macOS 27.0.1: 2,048 colors, each into a slice - /// of its own): each channel through `float` and `half`, each to nearest even, then the bfloat - /// code nearest, ties to even, a NaN `0x7fc0` (`ExtendedRange::clear_texel`). Metal's answer - /// is FNV-1a of each format's codes, color after color; the colors' own (their bits, as the - /// probe recorded them) check the generator first. - #[test] - fn bfloat_clears_are_metal_s() { - let colors = bfloat_clear_colors(); - let bits = colors - .iter() - .flat_map(|c| c.iter().flat_map(|v| v.to_le_bytes())); - assert_eq!(fnv(bits), 0xde31_e66e_0a02_d326, "the probe's colors"); - for (pf, channels, metal) in [ - (P::R16Bfloat, 1, 0x787c_c90b_99ff_56ac), - (P::RG16Bfloat, 2, 0x38a9_4edd_d5c8_b90a), - (P::RGBA16Bfloat, 4, 0xe219_6f7b_bcab_e264), - ] { - let codes: Vec = colors - .iter() - .flat_map(|&c| { - // SAFETY: an extended-range attachment's clear value is its `uint32` texel. - let uint32 = unsafe { - color(pf, c, ClearRoute::ThroughHalf) - .expect("a clear rule") - .uint32 - }; - uint32 - .into_iter() - .take(channels) - .map(|w| u16::try_from(w).expect("a code")) - .collect::>() - }) - .collect(); - let bytes = codes.iter().flat_map(|c| c.to_le_bytes()); - assert_eq!(fnv(bytes), metal, "{pf:?}"); - } - // A few of Metal's codes: a bfloat tie that rounds up to even, a `half` tie that - // rounds down, the largest `half` (whose bfloat rounds up), a double whose `float` is the - // `half` overflow (an infinity), `half`'s least and the tie below it, the signed zero, and - // a negative NaN. - for (v, metal) in [ - (1.0 + 3.0 / 256.0, 0x3f82), - (1.0 + 1.0 / 2048.0, 0x3f80), - (65504.0, 0x4780), - (65_519.999_999_999_99, 0x7f80), - (5.960_464_477_539_063e-8, 0x3380), - (2.980_232_238_769_531_2e-8, 0x0000), - (-1e-30, 0x8000), - (f64::from_bits(0xfff8_0000_0000_0000), 0x7fc0), - ] { - // SAFETY: as above. - let uint32 = unsafe { - color(P::R16Bfloat, [v; 4], ClearRoute::ThroughHalf) - .expect("a clear rule") - .uint32 - }; - assert_eq!(uint32[0], metal, "{v:e}"); - } - } - - /// Each of Metal's routes clears a bfloat attachment by its rule (an M4 under macOS 27.0.1; the - /// consumer's M3 Max under 26.7 alike): straight to bfloat (`Nearest`) rounds the color's - /// `float`, subnormals kept, and keeps a NaN's sign and top payload bits; through `half` - /// (`ThroughHalf`) loses them. The consumer's colors, the ties around `1 + 2^-8`, whose `half` - /// is a bfloat tie, and the probe's NaNs, whose codes are the M4's. - #[test] - fn each_route_clears_bfloat_by_its_rule() { - let at = |route: ClearRoute, pf: P, c: [f64; 4]| -> [u32; 4] { - let value = color(pf, c, route).expect("a clear rule"); - // SAFETY: an extended-range attachment's clear value is its `uint32` texel. - unsafe { value.uint32 } - }; - let consumers = [-3e38, 1e-40, 70000.0, -2.5]; - let ties = [ - 1.0 + 1.0 / 256.0, - 1.0 + 3.0 / 256.0, - 1.0 + 1.0 / 256.0 + 2f64.powi(-23), - -0.0, - ]; - for (route, want, tied) in [ - ( - ClearRoute::Straight, - [0xff62, 0x0001, 0x4789, 0xc020], - [0x3f80, 0x3f82, 0x3f81, 0x8000], - ), - ( - ClearRoute::ThroughHalf, - [0xff80, 0x0000, 0x7f80, 0xc020], - [0x3f80, 0x3f82, 0x3f80, 0x8000], - ), - ] { - assert_eq!(at(route, P::RGBA16Bfloat, consumers), want, "{route:?}"); - assert_eq!(at(route, P::RGBA16Bfloat, ties), tied, "{route:?}"); - assert_eq!( - at(route, P::RG16Bfloat, consumers), - [want[0], want[1], 0, 0], - "{route:?}" - ); - assert_eq!( - at(route, P::R16Bfloat, consumers), - [want[0], 0, 0, 0], - "{route:?}" - ); - } - // The probe's NaN doubles (`bcs.m`), and the codes the M4 stored for each in a 16 x 16 - // private `R16Bfloat` target cleared by a pass with no draw call; a 1 x 1 one stored - // `0x7fc0` for each. - for (bits, nearest) in [ - (0x7ff8_0000_0000_0000_u64, 0x7fc0), - (0xfff8_0000_0000_0000, 0xffc0), - (0x7ff8_4000_0000_0000, 0x7fc2), - (0xfffc_0000_0000_0000, 0xffe0), - (0x7ff8_0000_0000_0001, 0x7fc0), - (0x7fff_ffff_ffff_ffff, 0x7fff), - (0xffff_ffff_ffff_ffff, 0xffff), - (0x7ff0_0000_0000_0001, 0x7fc0), - (0xfff0_0000_0000_0001, 0xffc0), - (0x7ff4_0000_0000_0000, 0x7fe0), - (0xfff0_0400_0000_0000, 0xffc0), - (0x7ff7_ffff_ffff_ffff, 0x7fff), - (0xfff7_e000_0000_0000, 0xffff), - ] { - let nan = f64::from_bits(bits); - let c = [nan, 1.0, -2.5, 0.5]; - assert_eq!( - at(ClearRoute::Straight, P::RGBA16Bfloat, c), - [nearest, 0x3f80, 0xc020, 0x3f00], - "{bits:#x}" - ); - assert_eq!( - at(ClearRoute::ThroughHalf, P::RGBA16Bfloat, c), - [0x7fc0, 0x3f80, 0xc020, 0x3f00], - "{bits:#x}" - ); - } - } - - /// The half conversion rounds to nearest even at every boundary it meets. - #[test] - fn halves_round_to_nearest_even() { - assert_eq!(f32_to_f16(1.0), 0x3c00); - assert_eq!(f32_to_f16(65504.0), 0x7bff); - assert_eq!(f32_to_f16(65519.0), 0x7bff); - assert_eq!(f32_to_f16(65520.0), 0x7c00); - assert_eq!(f32_to_f16(2f32.powi(-24)), 0x0001); - assert_eq!(f32_to_f16(2f32.powi(-25)), 0x0000); - assert_eq!(f32_to_f16(3.0 * 2f32.powi(-25)), 0x0002); - assert_eq!(f32_to_f16(-2.0), 0xc000); - assert_eq!(f32_to_f16(f32::NEG_INFINITY), 0xfc00); - for h in [ - 0x0001u16, 0x03ff, 0x0400, 0x3c00, 0x3c01, 0x7bff, 0x8001, 0xfbff, - ] { - assert_eq!(f32_to_f16(f16_to_f32(h)), h); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/color_list.rs b/crates/metal2vulkan-runtime/src/color_list.rs deleted file mode 100644 index f2a89108e..000000000 --- a/crates/metal2vulkan-runtime/src/color_list.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! A list of at most one element per color attachment of a pass, kept inline: a pass's shape -//! (`render_target::PassShape`) is made, compared and copied as each render pass opens and ends, -//! and its lists allocate nothing. - -use super::error::{internal, Error}; -use super::render_pass::MAX_COLOR_ATTACHMENTS; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut}; - -/// At most [`MAX_COLOR_ATTACHMENTS`] elements, inline; compared, hashed and printed as the -/// slice of them. -#[derive(Clone)] -pub(crate) struct ColorList { - len: usize, - /// The elements, then defaults past `len`. - items: [T; MAX_COLOR_ATTACHMENTS], -} - -impl ColorList { - /// The empty list. - pub(crate) fn new() -> ColorList { - ColorList { - len: 0, - items: [T::default(); MAX_COLOR_ATTACHMENTS], - } - } - - /// Add `item` at the end; refused (an invariant) where the list is full. - pub(crate) fn push(&mut self, item: T) -> Result<(), Error> { - let slot = (self.items.get_mut(self.len)) - .ok_or_else(|| internal("more elements than a pass has color attachments"))?; - *slot = item; - self.len += 1; - Ok(()) - } - - /// The list of `items`; refused (an invariant) past [`MAX_COLOR_ATTACHMENTS`] of them. - pub(crate) fn of(items: impl IntoIterator) -> Result, Error> { - let mut list = ColorList::new(); - for item in items { - list.push(item)?; - } - Ok(list) - } -} - -impl Default for ColorList { - fn default() -> ColorList { - ColorList::new() - } -} - -impl Deref for ColorList { - type Target = [T]; - - fn deref(&self) -> &[T] { - &self.items[..self.len] - } -} - -impl DerefMut for ColorList { - fn deref_mut(&mut self) -> &mut [T] { - &mut self.items[..self.len] - } -} - -impl PartialEq for ColorList { - fn eq(&self, other: &ColorList) -> bool { - **self == **other - } -} - -impl PartialEq<&[T]> for ColorList { - fn eq(&self, other: &&[T]) -> bool { - **self == **other - } -} - -impl Eq for ColorList {} - -impl<'a, T> IntoIterator for &'a ColorList { - type Item = &'a T; - type IntoIter = std::slice::Iter<'a, T>; - - fn into_iter(self) -> std::slice::Iter<'a, T> { - self.iter() - } -} - -impl Hash for ColorList { - fn hash(&self, state: &mut H) { - (**self).hash(state); - } -} - -impl fmt::Debug for ColorList { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - (**self).fmt(f) - } -} diff --git a/crates/metal2vulkan-runtime/src/color_reformat.rs b/crates/metal2vulkan-runtime/src/color_reformat.rs deleted file mode 100644 index b4b76fbbd..000000000 --- a/crates/metal2vulkan-runtime/src/color_reformat.rs +++ /dev/null @@ -1,380 +0,0 @@ -//! A render pipeline's color drawn into a pass attachment of another pixel format, as plain Metal -//! stores it. -//! -//! Metal's validation stops such a state at `setRenderPipelineState:`; plain Metal draws it -//! (Metal probes, an M4 under macOS 27.0.1, each case in its own process). Each sample holds one -//! record of the state's colors, packed as `imageblockSampleLength` packs them ([`color_record`]); -//! the pass loads and stores each of its attachments at its own place in its own record. A color -//! written in the state's pixel format is that format's encoding, in red-first order (`BGRA8Unorm` -//! as `RGBA8Unorm`, `BGR10A2Unorm` as `RGB10A2Unorm`), and the pass stores the bytes there into its -//! attachment unchanged, except that a `BGRA8Unorm` or `BGRA8Unorm_sRGB` attachment exchanges bytes -//! 0 and 2 and a `BGR10A2Unorm` attachment its red and blue fields. A blend reads the attachment's -//! bytes as the state's format, and a write mask names the state's channels. -//! -//! Where the attachment's bytes then are the state's encoding in a channel order a Vulkan format -//! names, a draw through a view of that format ([`view_format`]) stores, blends and masks as -//! Metal does: the state's format in the attachment's channel order (`RGBA8Unorm` in a -//! `BGRA8Unorm` pass through `B8G8R8A8_UNORM`, its own; `RGBA8Unorm_sRGB` in a `BGRA8Unorm` pass -//! through `B8G8R8A8_SRGB`). The runtime draws such a color where the view's format is the -//! attachment's own; a view of another format stays refused `AttachmentFormat`. -//! -//! Each state color is drawn into the pass color at its place in the record ([`routing`]): the -//! draws' subpass references that pass color at the state color's location. A pass color at no -//! state color's place is zeroed or kept as Metal's compiled code writes the record -//! ([`uncovered`]), and a state color at no pass color's place is dropped. A color whose bytes -//! Metal stores into part of an attachment, or into more than one, stays refused. - -use super::clear_value::has_channels; -use metal2vulkan::device::{DeviceProfile, FormatUsage}; -use metal2vulkan::metal::format::{color_record, vk_format, FormatEmulation}; -use metal2vulkan::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat}; -use metal2vulkan::pipeline::ColorAttachmentDescriptor; -use metal2vulkan::vk::{Format, NumericFormat}; -use std::collections::{BTreeMap, BTreeSet}; - -/// The fragment output locations a draw can use. -const LOCATIONS: u32 = 8; - -/// The Vulkan format a color attachment of `pf` holds Metal's texels in on `profile`, where it -/// holds them in a format of exactly Metal's layout and numeric format; `None` for a format held -/// otherwise (an extended-range format's planes) or not renderable. -pub(crate) fn held(pf: PixelFormat, profile: &DeviceProfile) -> Option { - let usages: BTreeSet = [FormatUsage::ColorAttachment].into(); - let mapping = vk_format(pf, &usages, profile).ok()?; - (mapping.emulation == FormatEmulation::Direct).then_some(mapping.format) -} - -/// The lowest color index whose place in Metal's per-sample record of a state whose colors are -/// `state` is not its place in the record of the pass whose colors are `pass` -/// ([`color_record`]): a color both have that starts at another byte, or a color of either that -/// overlaps a color of another index of the other. Plain Metal stores the state's bytes at each -/// place into the pass's attachment there (Metal probes: a state of colors 0 and 1 in a pass of -/// color 1 alone stores the state's color 0 into the pass's color 1, and a state of color 1 alone -/// in a pass of colors 0 and 1 its color 1 into the pass's color 0). `None` where every color keeps -/// its place, or where a format has no place in the record. -pub(crate) fn misplaced( - state: &[Option], - pass: &[Option], -) -> Option { - let (state, pass) = (spans(state)?, spans(pass)?); - let mut lowest = None; - for &(index, offset, size) in &state { - for &(other, at, length) in &pass { - let overlaps = offset < at + length && at < offset + size; - let moved = match index == other { - true => offset != at, - false => overlaps, - }; - if moved { - let first = index.min(other); - lowest = Some(lowest.map_or(first, |l: u32| l.min(first))); - } - } - } - lowest -} - -/// How a draw stores a state's per-sample record into its pass's attachments as plain Metal -/// does: each state color into the pass color at its place in the record ([`color_record`]), a -/// pass color at no state color's place as [`uncovered`] says, a state color at no pass color's -/// place nowhere (Metal probes). -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub(crate) struct Routing { - /// The pass color each fragment output location stores into, by location: the draws' - /// subpass's color references. Empty where each location stores into the pass color of its - /// own index. - pub(crate) locations: Vec>, - /// The state colors at a pass color's place, by state color index: that pass color. - pub(crate) placed: BTreeMap, - /// The pass colors no state color lies on, by the location the draws reference each at: its - /// own index where the state has no color there, else the highest location the state has no - /// color at and no other color takes (a fragment function rarely writes there). - pub(crate) uncovered: BTreeMap, - /// The state colors at no pass color's place, whose output is dropped. - pub(crate) dropped: BTreeSet, -} - -impl Routing { - /// Each color at its own index: a color both have placed there, one the pass alone has - /// uncovered at its index, one the state alone has dropped. The draws of a state that writes - /// no color, where the record decides nothing, and of a record of formats without a place. - pub(crate) fn by_index(state: &[Option], pass: &[Option]) -> Routing { - let has = |formats: &[Option], index: u32| { - formats - .get(index as usize) - .copied() - .flatten() - .is_some_and(|pf| pf != PixelFormat::Invalid) - }; - let mut routing = Routing::default(); - for index in 0..state.len().max(pass.len()) as u32 { - match (has(state, index), has(pass, index)) { - (true, true) => { - routing.placed.insert(index, index); - } - (false, true) => { - routing.uncovered.insert(index, index); - } - (true, false) => { - routing.dropped.insert(index); - } - (false, false) => {} - } - } - routing - } - - /// The lowest location whose color index the routing changes, where it changes one. - pub(crate) fn moved(&self) -> Option { - (0u32..) - .zip(&self.locations) - .find(|&(location, index)| *index != Some(location)) - .map(|(location, _)| location) - } -} - -/// How a draw of a state whose colors are `state` stores its record into a pass whose colors are -/// `pass` ([`Routing`]). `None` where Metal's answer is not a color's bytes stored whole into one -/// attachment: a state color overlapping a pass color it does not start at, or more than one; a -/// pass color a state color overlaps but does not lie on; or no free location for an uncovered -/// pass color. A state color starting at a pass color of its own index is placed there whatever -/// their sizes (the format check decides). `None` too where a format has no place in the record. -pub(crate) fn routing( - state: &[Option], - pass: &[Option], -) -> Option { - let (spans_of_state, spans_of_pass) = (spans(state)?, spans(pass)?); - let overlap = |(_, a, x): (u32, u32, u32), (_, b, y): (u32, u32, u32)| a < b + y && b < a + x; - let mut placed = BTreeMap::new(); - let mut dropped = BTreeSet::new(); - for &color in &spans_of_state { - let (index, offset, size) = color; - let over: Vec<(u32, u32, u32)> = spans_of_pass - .iter() - .copied() - .filter(|&other| overlap(color, other)) - .collect(); - match over.as_slice() { - [] => { - dropped.insert(index); - } - [(other, at, length)] if *at == offset && (*length == size || *other == index) => { - placed.insert(index, *other); - } - _ => return None, - } - } - let mut at: BTreeMap = placed.clone(); - let mut uncovered = BTreeMap::new(); - let taken = |location: u32| { - state - .get(location as usize) - .copied() - .flatten() - .is_some_and(|pf| pf != PixelFormat::Invalid) - }; - for &color in &spans_of_pass { - let index = color.0; - if placed.values().any(|&k| k == index) { - continue; - } - if spans_of_state.iter().any(|&other| overlap(color, other)) { - return None; - } - let free = |location: u32, at: &BTreeMap| { - !taken(location) && !at.contains_key(&location) - }; - let location = match free(index, &at) { - true => index, - false => (0..LOCATIONS).rev().find(|&l| free(l, &at))?, - }; - at.insert(location, index); - uncovered.insert(location, index); - } - let locations = match at.iter().all(|(location, index)| location == index) { - true => Vec::new(), - false => { - let length = at.keys().max().map_or(0, |last| last + 1); - (0..length) - .map(|location| at.get(&location).copied()) - .collect() - } - }; - Some(Routing { - locations, - placed, - uncovered, - dropped, - }) -} - -/// What plain Metal stores into a pass color at no state color's place where a draw covers it -/// (Metal probes, an M4): zero where the draw's compiled code writes its whole per-sample record -/// without reading the attachments, their contents otherwise. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Uncovered { - /// Zero: each state color writes every channel of its format (its write mask) and reads no - /// attachment (blending off, or no factor reading the destination and destination factors - /// of zero). - Zeroed, - /// Its contents: a state color writes some of its channels alone, or blends reading the - /// destination whatever the fragment's output (a destination factor of one, of the - /// destination or of the blend color, a source factor of the destination, `Min` or `Max`). - Kept, - /// Its contents, where a state color's only reads of the destination are through a - /// destination factor of the fragment's output (`SourceAlpha`, `OneMinusSourceAlpha`, ...): - /// Metal's compiler folds an output it proves constant, and where the factor folds to zero - /// it stores zero (an alpha of the literal 1 under `OneMinusSourceAlpha`); the same 1 read - /// from a buffer kept them. A near-equivalent. - KeptUnlessFolded, -} - -/// What a pass color at no place of a state whose colors are `colors` holds where a draw covers -/// it ([`Uncovered`]). -pub(crate) fn uncovered<'a>( - colors: impl IntoIterator, -) -> Uncovered { - let mut out = Uncovered::Zeroed; - for color in colors { - if color.pixel_format == PixelFormat::Invalid { - continue; - } - let rule = color_reads(color); - if rule == Uncovered::Kept { - return Uncovered::Kept; - } - if rule == Uncovered::KeptUnlessFolded { - out = rule; - } - } - out -} - -/// Whether state color `color` writes its record place without reading the attachment -/// ([`Uncovered::Zeroed`]), reads it ([`Uncovered::Kept`]), or reads it unless its output folds -/// ([`Uncovered::KeptUnlessFolded`]). -fn color_reads(color: &ColorAttachmentDescriptor) -> Uncovered { - // Metal 4's blend placeholders resolve to their slot's own default, which is the factor and - // the operation the draw blends with, so what the attachment reads is decided from the - // resolved blend rather than from the placeholder ([`ColorAttachmentDescriptor::specialized`]). - let color = &color.specialized(); - let Some(channels) = has_channels(color.pixel_format) else { - return Uncovered::Kept; - }; - let masks = [ - ColorWriteMask::RED, - ColorWriteMask::GREEN, - ColorWriteMask::BLUE, - ColorWriteMask::ALPHA, - ]; - let whole = channels - .iter() - .zip(masks) - .all(|(&has, mask)| !has || color.write_mask.contains(mask)); - if !whole || color.write_mask.contains(ColorWriteMask::UNSPECIALIZED) { - return Uncovered::Kept; - } - if !color.blending_enabled { - return Uncovered::Zeroed; - } - use BlendFactor as F; - let reads_destination = |factor: BlendFactor| { - matches!( - factor, - F::DestinationColor - | F::OneMinusDestinationColor - | F::DestinationAlpha - | F::OneMinusDestinationAlpha - | F::SourceAlphaSaturated - ) - }; - let operations = [color.rgb_blend_operation, color.alpha_blend_operation]; - let sources = [ - color.source_rgb_blend_factor, - color.source_alpha_blend_factor, - ]; - let destinations = [ - color.destination_rgb_blend_factor, - color.destination_alpha_blend_factor, - ]; - let reading_operation = operations - .iter() - .any(|op| matches!(op, BlendOperation::Min | BlendOperation::Max)); - if reading_operation || sources.into_iter().any(reads_destination) { - return Uncovered::Kept; - } - let mut out = Uncovered::Zeroed; - for factor in destinations { - match factor { - F::Zero => {} - F::SourceColor - | F::OneMinusSourceColor - | F::SourceAlpha - | F::OneMinusSourceAlpha - | F::Source1Color - | F::OneMinusSource1Color - | F::Source1Alpha - | F::OneMinusSource1Alpha => out = Uncovered::KeptUnlessFolded, - _ => return Uncovered::Kept, - } - } - out -} - -/// The placed colors of `formats`' record: each one's index, byte offset and size. -fn spans(formats: &[Option]) -> Option> { - let placed = (0u32..).zip(color_record(formats)?); - Some( - placed - .filter_map(|(index, span)| span.map(|(offset, size)| (index, offset, size))) - .collect(), - ) -} - -/// The format of the view through which a draw stores a state's color held in `state` into a -/// pass attachment held in `pass` as plain Metal stores it, both of one texel size (the module -/// docs): the state's encoding in red-first order, in the attachment's channel order. `None` -/// where no Vulkan format stores it so: the attachment's channel order is not red-first and the -/// state's encoding has no format in that order (a `BGRA8Unorm` pass of anything but four 8-bit -/// channels, a `BGR10A2Unorm` pass of anything but `RGB10A2Unorm`), the attachment stores bytes -/// other than the record's (a signed normalized attachment stores -128 as -127, a probe -/// `n_rgba8_in_rgba8snorm`), a packed 16-bit format, which Metal's record holds otherwise -/// (probe 2), or texels of different sizes (unbuilt). -pub(crate) fn view_format(state: Format, pass: Format) -> Option { - let block = |format: Format| format.block(); - let (state_block, pass_block) = (block(state)?, block(pass)?); - let packed_16 = |b: metal2vulkan::vk::FormatBlock| b.packed_bits == Some(16); - if state_block.size != pass_block.size - || packed_16(state_block) - || packed_16(pass_block) - || pass_block.color == Some(NumericFormat::Snorm) - { - return None; - } - let encoding = red_first(state); - match pass { - Format::B8G8R8A8_UNORM | Format::B8G8R8A8_SRGB => match encoding { - Format::R8G8B8A8_UNORM => Some(Format::B8G8R8A8_UNORM), - Format::R8G8B8A8_SRGB => Some(Format::B8G8R8A8_SRGB), - Format::R8G8B8A8_SNORM => Some(Format::B8G8R8A8_SNORM), - Format::R8G8B8A8_UINT => Some(Format::B8G8R8A8_UINT), - Format::R8G8B8A8_SINT => Some(Format::B8G8R8A8_SINT), - _ => None, - }, - Format::A2R10G10B10_UNORM_PACK32 => { - (encoding == Format::A2B10G10R10_UNORM_PACK32).then_some(pass) - } - _ => Some(encoding), - } -} - -/// Metal's encoding of a color held in `format`, in red-first order: the format of the same -/// layout with red and blue in their red-first places. -fn red_first(format: Format) -> Format { - match format { - Format::B8G8R8A8_UNORM => Format::R8G8B8A8_UNORM, - Format::B8G8R8A8_SRGB => Format::R8G8B8A8_SRGB, - Format::A2R10G10B10_UNORM_PACK32 => Format::A2B10G10R10_UNORM_PACK32, - other => other, - } -} diff --git a/crates/metal2vulkan-runtime/src/color_resolve.rs b/crates/metal2vulkan-runtime/src/color_resolve.rs deleted file mode 100644 index 1a5607985..000000000 --- a/crates/metal2vulkan-runtime/src/color_resolve.rs +++ /dev/null @@ -1,1356 +0,0 @@ -//! The crate-owned multisample color resolve, drawn after the pass, where the device's resolve in -//! the pass cannot write the answer at all. -//! -//! A color attachment resolves by the device's `AVERAGE`, which leaves the average's rounding, and -//! an sRGB average's space, to the device: Metal's own resolve where the driver's is Metal's -//! ([`average_is_metals`], `DriverFact::ColorResolveAverageIsMetals`: MoltenVK from 1.4.1 on -//! Apple's GPUs resolves every format by Metal's multisample resolve store action, measured at 2 -//! and 4 samples), elsewhere the device's native answer, announced as `device-rounded-resolve`. So -//! does an attachment a fetching pass's sample planes hold as it ends: the planes are merged back -//! and one more instance of no draws resolves it (`sample_planes.rs`). The crate-owned resolve -//! (`bind::color_resolve_modules`) draws only the two resolves no device's average writes: -//! -//! An extended-range attachment (`BGR10_XR`, `BGRA10_XR`, their `_sRGB` twins and -//! `RGB10A2Unorm_sRGB`, the forms Metal multisamples) is held in its raw format's codes, which no -//! device's resolve averages, so it resolves by the crate-owned resolve at every count -//! ([`extended`]: `bind::ColorResolveFormat::extended_range`, whose docs state -//! Metal's measured rule and the near-equivalents of the channels the codes cannot give, announced -//! as `extended-range-resolve`), from any source below; an image that takes neither input -//! attachment usage nor a copy is refused, as no other resolve reads it. -//! -//! **A resolve into the attachment's format's sRGB twin** ([`twin_rules`], `resolve.rs`), which -//! Metal resolves in the resolve texture's encoding, takes the crate-owned resolve on every -//! device: a subpass's resolve attachment is of its color attachment's own format -//! (`VUID-VkSubpassDescription-pResolveAttachments-00850`), so no device's average writes the -//! twin's encoding. Its rules are the resolve attachment's format's. An sRGB attachment resolving -//! into its UNORM twin is read through its image's view in that twin, whose codes the UNORM rules -//! average. A UNORM attachment resolving into its sRGB twin takes the device's own sRGB decode and -//! encode where the device renders the sRGB format ([`decodes`], -//! `bind::ColorResolveFormat::device_srgb`): the resolve reads the samples through a view in the -//! sRGB format (a UNORM texture's image lists its twin's views, `image_plan.rs`) and writes their -//! average through the resolve attachment's own view, announced as `device-rounded-resolve` on -//! every device, Metal's resolve taking its own 12-bit tables; a device without the format reads -//! the codes in the attachment's own format and takes those tables. Such a resolve reads the -//! attachment itself, never its sample planes, whose copy format holds the codes under the -//! attachment's own format's rules; the attachment's image, and a stand-in a pass renders it into, -//! take the input attachment usage it reads them through where that is free ([`twin_resolved`], -//! [`twin_read_view`]), and samples it can neither read nor copy are not built -//! (`NotImplemented(Render)`). -//! -//! The choice is made with the attachment's resolve ([`of_resolve`], `resolve.rs`), so the pass's -//! shape (`render_target.rs`) leaves such a resolve out of its subpass from its first instance: -//! the pass's last instance stores the attachment's samples, and after the pass one render pass -//! instance of the resolve's own pass per attachment draws a triangle over the render area that -//! reads each pixel's samples and writes the resolve attachment (the resolve texture's level and -//! slice, or the scratch image copied there after, `resolve.rs`): -//! -//! - **From the sample planes** (`sample_planes.rs`) where they hold an extended-range -//! attachment's samples as the pass ends (its last instance's draws fetch it): read through a -//! sampled 2D-array view in their copy format. The planes are not merged back into the -//! attachment unless Metal keeps its samples (`Store`, `StoreAndMultisampleResolve`). -//! - **From the attachment** otherwise: its level and layer as the resolve pass's input -//! attachment 0, loaded and stored. An 8-bit sRGB attachment whose image takes its UNORM twin's -//! view (an sRGB texture's image lists its twin's formats) is read through that view -//! ([`raw_view`], `bind::ResolveSource::RawInputAttachment`), so the resolve reads each sample's -//! code as a unorm code with no table lookup. Its image needs input attachment usage, which a -//! multisampled color render target the runtime makes takes where the device may resolve it so -//! and the usage costs the image nothing, and a memoryless one wherever the device makes the -//! image (`framebuffer_fetch.rs`), as does a stand-in (`attachment_stand_in.rs`). -//! - **From a copy of the attachment's samples** where its image lacks that usage (a caller's -//! image without it, or a device where it would change the image's memory requirements) but -//! takes transfer reads ([`copied`]): its level and the pass's layers over the render area are -//! copied (`vkCmdCopyImage`, one format and sample count) into a scratch image of its format and -//! samples that has the usage (and, for the device's sRGB decode, takes the sRGB twin's view), -//! held by the command buffer until it completes, and the resolve reads the scratch as it reads -//! an attachment. The copy moves each sample's bits; the one -//! device measured to change them, RADV, writes a 16-bit float NaN as `0xfe00` -//! (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`), which the resolve counts as 0 -//! whatever its bits. A caller's image has the transfer usage the runtime's texture of its -//! descriptor has (`texture/wrapped.rs`), so only an image of a format the device copies no -//! image of has neither usage. -//! -//! From any source, an 8-bit sRGB resolve by the tables writes its result through the resolve -//! attachment's view in its UNORM twin where that image takes one ([`raw_view`], -//! `bind::ColorResolveFormat::written_raw`): each code goes out as a unorm code's float, which the -//! twin's store keeps as the code, with no table lookup and no sRGB encode. One by the device's -//! decode writes through the attachment's own view, whose store encodes. -//! -//! A layered pass (`renderTargetArrayLength` 2 or more) resolves each of its layers in a render -//! pass instance of its own, through views of that layer. Its resolve from the sample planes, which -//! hold one layer, is `NotImplemented(LayeredPass)`. -//! -//! The resolve's pipelines and passes are made once per device, format, sample count and source, -//! at the first pass that needs them, and destroyed with the device; each pass's descriptor sets -//! and framebuffers are held by its command buffer until it completes, and, where every resolve of -//! the pass reads its attachment through the attachment's own views, kept by the image it first -//! resolves into for its next pass of the same views ([`KeptResolves`]). Each resolve runs between -//! barriers from everything before and to everything after, as does each copy before them. The -//! runtime announces `shader-resolve` (performance) for the extra pass (naming the copy where the -//! resolve reads one), and `unmeasured-resolve` (precision) at more than 4 samples. - -use super::binding_view::{views_as, VkView}; -use super::blit::TRANSFER; -use super::command_buffer::CommandBuffer; -use super::device::{device_error, lock}; -use super::encoder::EncoderCore; -use super::error::{internal, vulkan, Error, RuntimeGap}; -use super::exit_guard; -use super::image_plan::{srgb_twin, ImagePlan}; -use super::release; -use super::render_pass::{PassLayout, Target}; -use super::render_target::{takes_input, ATTACHMENT_STAGES}; -use super::resolve; -use super::resource::ResourceKey; -use super::sample_planes::{pipeline_layout, set_layout, shader_module}; -use super::tracker::{Access, Barrier, Use}; -use super::Device; -use crate::shader_cache::driver::Making; -use ash::vk; -use metal2vulkan::bind::{color_resolve_modules, ColorResolveFormat, PlanesCopy, ResolveSource}; -use metal2vulkan::device::{DeviceProfile, DriverFact, FormatUsage}; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{direct_format, ExtendedRange, WordAttachment}; -use metal2vulkan::metal::PixelFormat; -use metal2vulkan::vk::{ - ComponentMapping, Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags, ImageViewType, -}; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex}; - -/// The most samples of a texture on Apple's GPUs, so the most whose resolve Metal measures. -pub(super) const METAL_SAMPLES: u32 = 4; - -/// Whether `device`'s own `AVERAGE` resolve of a color attachment of `samples` samples writes -/// Metal's resolve, whatever its format: `DriverFact::ColorResolveAverageIsMetals`, at a count -/// Apple's GPUs make (MoltenVK's resolve is Metal's multisample resolve store action). -pub(super) fn average_is_metals(device: &Device, samples: u32) -> bool { - samples <= METAL_SAMPLES - && device - .properties() - .driver_facts - .contains(&DriverFact::ColorResolveAverageIsMetals) -} - -/// The resolve of a multisampled color attachment of the extended-range format `pf`, held in its -/// raw format's codes, which no device's resolve averages: the crate-owned one at every count (the -/// module docs). `None` for another format. -pub(super) fn extended(pf: PixelFormat) -> Option { - ExtendedRange::of(pf).and_then(ColorResolveFormat::extended_range) -} - -/// The crate-owned resolve of a color attachment of pixel format `pf` held in `format` at -/// `samples`, where it resolves the attachment's own samples into its own format, at every count -/// past one: an extended-range format's ([`extended`]), and a word's ([`word`]). `None` where the -/// device resolves it in the pass. -pub(super) fn shader_rules( - pf: PixelFormat, - format: Format, - samples: u32, -) -> Option { - (samples > 1).then(|| extended(pf).or_else(|| word(pf, format)))? -} - -/// The resolve of a multisampled color attachment of `pf` held in `format`, its word's format -/// (`metal::format::WordAttachment`, `image_plan::word_samples`), which no device's average reads: -/// a packed 16-bit or `RGB9E5Float` word's own ([`ColorResolveFormat::word`]), and an 8-bit sRGB -/// word's format's sRGB rules ([`ColorResolveFormat::of`]), whose codes it reads and writes -/// through the views of its UNORM twin ([`raw_view`]). `None` for another format. -fn word(pf: PixelFormat, format: Format) -> Option { - let word = WordAttachment::layout(pf).filter(|w| w.word_format() == format)?; - ColorResolveFormat::word(word).or_else(|| direct_format(pf).and_then(ColorResolveFormat::of)) -} - -/// Whether `target` is an attachment rendered through the view of its word -/// (`metal::format::WordAttachment`): its view is in the word's format. -fn word_view(target: &Target) -> bool { - WordAttachment::layout(target.texture.pixel_format()) - .is_some_and(|w| w.word_format() == target.format) -} - -/// The crate-owned resolve of the color attachment `source`, where the runtime resolves it so: -/// [`shader_rules`] of its format, view and samples, where the resolve may read its samples: -/// through its image's input attachment usage, or from a copy of them into a scratch image that -/// has it ([`copied`]), unless its sample planes hold them (the module docs). An extended-range or -/// word attachment's image that takes neither is refused: no other resolve reads its codes. -pub(super) fn of_attachment( - device: &Device, - source: &Target, -) -> Result, Error> { - let pf = source.texture.pixel_format(); - match shader_rules(pf, source.format, source.samples) { - Some(rules) if takes_input(source)? || copied(device, source)? => Ok(Some(rules)), - Some(_) => Err(Error::Unsupported(Unsupported::not_implemented( - Feature::Format, - ))), - None => Ok(None), - } -} - -/// The crate-owned resolve of a color attachment resolving into its format's sRGB twin, whose -/// encoding Metal resolves in (`resolve.rs`): the resolve attachment's format's rules, on every -/// device, since a subpass's resolve attachment is of its color attachment's own format and so no -/// device's average writes the twin's encoding. `None` where that format has no rule. -fn twin_rules(into: &Target) -> Option { - ColorResolveFormat::of(into.format) -} - -/// The rules of the crate-owned resolve `resolve` takes from the color attachment `source`: the -/// resolve attachment's format's where it is the attachment's format's sRGB twin -/// ([`twin_rules`], which no device's average writes, so a format with no rule is refused here and -/// samples the resolve cannot read where it plans the pass), their sRGB channels by the device's -/// own decode and encode where it reaches the samples through a view in the sRGB format -/// ([`decodes`]), else the attachment's own ([`of_attachment`]). -pub(super) fn of_resolve( - device: &Device, - source: &Target, - resolve: &resolve::Resolve, -) -> Result, Error> { - if !resolve.twin { - return of_attachment(device, source); - } - let rules = twin_rules(&resolve.attachment).ok_or(Error::NotImplemented(RuntimeGap::Render))?; - let decoded = rules.device_srgb(); - match decoded.decodes_on_device() && decodes(device, source, rules.format())? { - true => Ok(Some(decoded)), - false => Ok(Some(rules)), - } -} - -/// Whether a twin resolve into the sRGB format `srgb` reads the color attachment `source` through -/// the device's own sRGB decode (`bind::ColorResolveFormat::device_srgb`, the module docs): the -/// device renders `srgb`, and the resolve reaches the samples through a view in it, the -/// attachment's where its image takes input attachment usage (an 8-bit UNORM texture's image -/// lists its sRGB twin's views where the device has them, `image_plan.rs`), else a copy's -/// ([`copied`]), whose scratch image takes the view ([`copy_out`]). -fn decodes(device: &Device, source: &Target, srgb: Format) -> Result { - let profile = device.compile_device().profile(); - if !profile.supports_format(srgb, FormatUsage::ColorAttachment) { - return Ok(false); - } - match takes_input(source)? { - true => Ok(views_as(source.texture.image_plan()?, srgb, false)), - false => copied(device, source), - } -} - -/// Whether the crate-owned resolve may read the color attachment `source`, whose image takes no -/// input attachment usage, from a copy of its samples (the module docs): its image takes transfer -/// reads, and the device copies images of its format both ways, which the scratch image the copy -/// writes needs. -fn copied(device: &Device, source: &Target) -> Result { - let usage = source.texture.image_plan()?.usage; - let profile = device.compile_device().profile(); - let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; - Ok(usage.contains(ImageUsageFlags::TRANSFER_SRC) - && device - .shared() - .textures - .facts(profile) - .optimal(source.format) - .contains(copies)) -} - -/// Whether a multisampled color attachment of `pf` may resolve into its format's sRGB twin, which -/// the crate-owned resolve reads it for on every device (`resolve.rs`): the twin's format has -/// Metal's rules (`bind::ColorResolveFormat::of`). Its image, and the stand-in a pass renders it into -/// (`attachment_stand_in.rs`), take the input attachment usage that resolve reads them through -/// where it is free. -pub(super) fn twin_resolved(pf: PixelFormat, samples: u32) -> bool { - samples > 1 - && srgb_twin(pf) - .and_then(direct_format) - .and_then(ColorResolveFormat::of) - .is_some() -} - -/// The view format a twin resolve reads a multisampled color attachment of `pf`, held in -/// `format`, through, where its image must list one: an 8-bit sRGB attachment's UNORM twin, whose -/// codes the resolve texture's UNORM rules average, and an 8-bit UNORM attachment's sRGB twin -/// where `profile` renders it, through which the resolve into that twin takes the device's own -/// decode ([`decodes`]). `None` where the resolve reads the attachment in its own format. -pub(super) fn twin_read_view( - profile: &DeviceProfile, - pf: PixelFormat, - format: Format, - samples: u32, -) -> Option { - use metal2vulkan::metal::format::srgb_raw_twin; - if !twin_resolved(pf, samples) { - return None; - } - let decoded = srgb_twin(pf).and_then(direct_format).filter(|&twin| { - ColorResolveFormat::of(twin).is_some_and(|rules| rules.device_srgb().decodes_on_device()) - && profile.supports_format(twin, FormatUsage::ColorAttachment) - }); - let read = decoded.or_else(|| srgb_raw_twin(pf).and_then(direct_format))?; - (read != format).then_some(read) -} - -/// `plan` with input attachment usage, where the runtime may resolve its image by the crate-owned -/// resolve reading it as an input attachment: a multisampled color attachment whose format and -/// samples [`shader_rules`] resolves, or one whose format's sRGB twin it resolves into whatever -/// the device ([`twin_resolved`]). `None` where it has the usage already, or needs none. -pub(super) fn input_candidate(plan: &ImagePlan) -> Option { - let usage = plan.usage; - let samples = plan.samples.as_raw(); - let resolved = shader_rules(plan.pixel_format, plan.format, samples).is_some() - || twin_resolved(plan.pixel_format, samples); - let candidate = usage.contains(ImageUsageFlags::COLOR_ATTACHMENT) - && !usage.contains(ImageUsageFlags::INPUT_ATTACHMENT) - && resolved; - candidate.then(|| ImagePlan { - usage: usage | ImageUsageFlags::INPUT_ATTACHMENT, - ..plan.clone() - }) -} - -/// Whether the exact resolve of `rules` reaches `target` (the color attachment it reads, or the -/// resolve attachment it writes) through a view in `rules`' raw twin -/// (`ColorResolveFormat::raw_format`, the module docs): an 8-bit sRGB format's UNORM twin, where -/// the image takes a view of it (an sRGB texture's image lists its twin's formats, -/// `image_plan.rs`) and `device` renders it. A target already in the raw twin, which a twin -/// resolve's attachment is (`resolve::Resolve::twin`: the UNORM attachment of sRGB rules holds -/// their codes itself), is reached through a view in its own format. So is a target an 8-bit -/// sRGB texture renders through the view of its word ([`word_view`]), whose image lists its -/// UNORM twin's view (`image_plan.rs`): the word's codes are the twin's. -fn raw_view(device: &Device, target: &Target, rules: ColorResolveFormat) -> Result { - let raw = rules.raw_format(); - let reached = target.format == rules.format() || target.format == raw || word_view(target); - if raw == rules.format() || !reached { - return Ok(false); - } - let profile = device.compile_device().profile(); - Ok(views_as(target.texture.image_plan()?, raw, false) - && profile.supports_format(raw, FormatUsage::ColorAttachment)) -} - -/// Where a resolve reads its samples (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -enum Source { - /// The attachment, as the resolve pass's input attachment 0: through its raw twin's view where - /// `raw` ([`raw_view`]), else in its own format. - Attachment { raw: bool }, - /// The attachment's sample planes, viewed in their copy format. - Planes(PlanesCopy), -} - -impl Source { - fn bind(self) -> ResolveSource { - match self { - Source::Attachment { raw: false } => ResolveSource::InputAttachment, - Source::Attachment { raw: true } => ResolveSource::RawInputAttachment, - Source::Planes(copy) => ResolveSource::Planes(copy), - } - } - - /// The descriptor type of the source's binding. - fn descriptor(self) -> vk::DescriptorType { - match self { - Source::Attachment { .. } => vk::DescriptorType::INPUT_ATTACHMENT, - Source::Planes(_) => vk::DescriptorType::SAMPLED_IMAGE, - } - } - - /// Whether the source is the attachment, as input attachment 0. - fn attachment(self) -> bool { - matches!(self, Source::Attachment { .. }) - } - - /// The format of the view of the attachment the source reads, whose format is `rules`'s: its - /// raw twin through the raw view, else its own. - fn read_format(self, rules: ColorResolveFormat) -> Format { - match self { - Source::Attachment { raw: true } => rules.raw_format(), - Source::Attachment { raw: false } | Source::Planes(_) => rules.format(), - } - } -} - -/// One resolve's objects, the device's: for one format, sample count and source. -#[derive(Clone, Copy, Debug)] -struct ResolvePipeline { - vertex: vk::ShaderModule, - fragment: vk::ShaderModule, - set_layout: vk::DescriptorSetLayout, - layout: vk::PipelineLayout, - render_pass: vk::RenderPass, - pipeline: vk::Pipeline, -} - -impl ResolvePipeline { - const NULL: ResolvePipeline = ResolvePipeline { - vertex: vk::ShaderModule::null(), - fragment: vk::ShaderModule::null(), - set_layout: vk::DescriptorSetLayout::null(), - layout: vk::PipelineLayout::null(), - render_pass: vk::RenderPass::null(), - pipeline: vk::Pipeline::null(), - }; - - /// Destroy every object. - /// - /// # Safety - /// - /// No pending command uses them; a null handle is a no-op. - unsafe fn destroy(&self, raw: &ash::Device) { - // SAFETY: the caller's contract. - unsafe { - release::object(raw, self.pipeline); - release::object(raw, self.render_pass); - release::object(raw, self.layout); - release::object(raw, self.set_layout); - release::object(raw, self.fragment); - release::object(raw, self.vertex); - } - } -} - -/// The resolves' objects one device has made (the module docs): bounded by the formats with -/// closed rules, the sample counts and the planes' copy formats. -#[derive(Default)] -pub(super) struct ColorResolveObjects { - pipelines: Vec<((ColorResolveFormat, u32, Source), ResolvePipeline)>, -} - -impl ColorResolveObjects { - /// Destroy every object; the device is idle, and is destroyed next. - pub(super) fn destroy(&self, raw: &ash::Device) { - for (_, pipeline) in &self.pipelines { - // SAFETY: the device is idle, so no pending command uses them. - unsafe { pipeline.destroy(raw) }; - } - } -} - -impl Device { - /// The resolve's objects for `format` at `samples` from `source`, made on first use. - fn color_resolve_pipeline( - &self, - format: ColorResolveFormat, - samples: u32, - source: Source, - ) -> Result { - let key = (format, samples, source); - // A making's turn before the lock (`budget::helper_turn`): none where it is made. - let _turn = - crate::pipeline::budget::helper_turn(&self.shared().color_resolves, |objects| { - objects.pipelines.iter().any(|(k, _)| *k == key) - }); - let mut objects = lock(&self.shared().color_resolves); - if let Some((_, pipeline)) = objects.pipelines.iter().find(|(k, _)| *k == key) { - return Ok(*pipeline); - } - let modules = color_resolve_modules( - self.compile_device(), - format, - samples, - source.bind(), - Feature::Format, - ) - .map_err(device_error)?; - let raw = self.shared().vk(); - let mut made = ResolvePipeline::NULL; - let result = (|| { - made.vertex = shader_module(raw, &modules.vertex)?; - made.fragment = shader_module(raw, &modules.fragment)?; - made.set_layout = - set_layout(raw, &[source.descriptor()], vk::ShaderStageFlags::FRAGMENT)?; - made.layout = pipeline_layout(raw, made.set_layout)?; - made.render_pass = resolve_pass(raw, format, samples, source)?; - let making = Making::new("color resolve") - .words(&modules.vertex) - .words(&modules.fragment) - .text(&key); - made.pipeline = resolve_pipeline(self, &made, making)?; - Ok(()) - })(); - match result { - Ok(()) => { - objects.pipelines.push((key, made)); - Ok(made) - } - Err(error) => { - // SAFETY: nothing used the objects. - unsafe { made.destroy(raw) }; - Err(error) - } - } - } -} - -/// The resolve's render pass for `rules`'s format at `samples` from `source`: the multisampled -/// attachment as input attachment 0 (loaded and stored, `GENERAL`, in the format of the view the -/// source reads) where it reads it, then the single-sampled resolve attachment in the format of -/// the view the result is written through (`ColorResolveFormat::written_format`), written whole -/// over the render area (`DONT_CARE`, then `STORE`). -fn resolve_pass( - raw: &ash::Device, - rules: ColorResolveFormat, - samples: u32, - source: Source, -) -> Result { - let general = vk::ImageLayout::GENERAL; - let samples_attachment = vk::AttachmentDescription::default() - .format(source.read_format(rules).into()) - .samples(vk::SampleCountFlags::from_raw(samples)) - .load_op(vk::AttachmentLoadOp::LOAD) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(general) - .final_layout(general); - let resolved = vk::AttachmentDescription::default() - .format(rules.written_format().into()) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(vk::AttachmentLoadOp::DONT_CARE) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(general) - .final_layout(general); - let (attachments, color) = match source { - Source::Attachment { .. } => (vec![samples_attachment, resolved], 1), - Source::Planes(_) => (vec![resolved], 0), - }; - let inputs = [vk::AttachmentReference::default() - .attachment(0) - .layout(general)]; - let colors = [vk::AttachmentReference::default() - .attachment(color) - .layout(general)]; - let mut subpass = vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colors); - if source.attachment() { - subpass = subpass.input_attachments(&inputs); - } - let subpasses = [subpass]; - let info = vk::RenderPassCreateInfo::default() - .attachments(&attachments) - .subpasses(&subpasses); - // SAFETY: `info` and its arrays are live for the call. - unsafe { crate::creation::render_pass(raw, &info) } -} - -/// The resolve's pipeline in its pass: the triangle over the viewport at one sample, without -/// blending, writing every component. Its record is the one `making` names. -fn resolve_pipeline( - device: &Device, - made: &ResolvePipeline, - making: Making, -) -> Result { - let shared = device.shared(); - let stages = [ - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(made.vertex) - .name(c"main"), - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::FRAGMENT) - .module(made.fragment) - .name(c"main"), - ]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); - let rasterization = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(vk::PolygonMode::FILL) - .cull_mode(vk::CullModeFlags::NONE) - .front_face(vk::FrontFace::COUNTER_CLOCKWISE) - .line_width(1.0); - let multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::TYPE_1); - let attachments = [vk::PipelineColorBlendAttachmentState::default() - .blend_enable(false) - .color_write_mask(vk::ColorComponentFlags::RGBA)]; - let blend = vk::PipelineColorBlendStateCreateInfo::default().attachments(&attachments); - let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; - let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); - let info = vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&input_assembly) - .viewport_state(&viewport) - .rasterization_state(&rasterization) - .multisample_state(&multisample) - .color_blend_state(&blend) - .dynamic_state(&dynamic) - .layout(made.layout) - .render_pass(made.render_pass) - .subpass(0); - shared.make_graphics_pipeline(making, || "metal2vulkan: color resolve".to_owned(), info) -} - -/// The objects one pass's resolves hold until its command buffer completes, and, kept -/// ([`KeptResolves`]), until the image keeping them lets them go and every command buffer that -/// took them completed: their descriptor sets' pool and, for each resolve and layer, its -/// framebuffer and set. -struct PassObjects { - device: Device, - pool: vk::DescriptorPool, - resolves: Vec, -} - -impl Drop for PassObjects { - fn drop(&mut self) { - // Once the process is exiting, the objects are left to its end (`exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - let raw = self.device.shared().vk(); - // SAFETY: no pending command uses them (a command buffer retains them until it completes); - // the sets are freed with their pool, and a null handle is a no-op. The views they were - // made of may have gone first: an object is destroyed in any order but after its children, - // and its destruction accesses no other object (the Vulkan specification's object - // lifetime: "Applications can: free or destroy objects in any order, except that parent - // objects must: be freed only after all child objects are freed", the parent being the - // first object of the child's creation, here the device; "When destroying or freeing an - // object, implementations must: not access any memory or other objects that may: - // otherwise be accessed when the object is accessed"). - unsafe { - for resolve in &self.resolves { - release::object(raw, resolve.framebuffer); - } - release::object(raw, self.pool); - } - } -} - -/// One attachment's resolve of one layer, planned. -struct Planned { - pipeline: ResolvePipeline, - framebuffer: vk::Framebuffer, - set: vk::DescriptorSet, -} - -/// A pass's exact color resolves, planned before the pass records and recorded after it. -pub(super) struct ShaderResolves { - extent: [u32; 2], - uses: Vec>, - /// The copies of the attachments the resolves read from a scratch image ([`copied`]): - /// `(attachment, scratch, region)` each, and their uses. - copies: Vec<(vk::Image, vk::Image, vk::ImageCopy)>, - copy_uses: Vec>, - objects: Arc, -} - -/// The most passes' resolve objects an image keeps ([`KeptResolves`]). -const KEPT_PASSES: usize = 4; - -/// The resolve objects of the passes that resolved into one image ([`ShaderResolves::plan`]), -/// kept for its next pass of the same views, and the image's key in the passes' keys. -/// -/// A pass whose every resolve reads its attachment through the attachment's own views (not the -/// sample planes, nor a copy of its samples, whose views are the pass's own) is kept by the image -/// it first resolves into, by everything its objects are made of ([`PassKey`]), and a later pass -/// of the same key binds the kept sets and begins the kept framebuffers instead of making its -/// own: the same descriptors of the same views, never written again. A set or framebuffer serves -/// several pending command buffers at once: neither is mutated by the commands that use it (the -/// Vulkan specification: "Any object parameters that are not labeled as externally synchronized -/// are either not mutated by the command or are internally synchronized"; `vkCmdBindDescriptorSets` -/// and `vkCmdBeginRenderPass` label only their command buffer), and a set's contents must only not -/// be altered while a command that bound it may consume them ("Once all pending uses have -/// completed, it is legal to update and reuse a descriptor set"). -/// -/// A key names each image by one no other image had or will have ([`KeptResolves::new`]), so a -/// view of an image that dropped is never taken for a view of another, whatever handle the -/// driver gave either. A view an image lets go while it lives (a rebind's or a storage form's new -/// `VkImage`, a detach's stand-in, a reattach) moves the device's views epoch -/// (`DeviceShared::views_epoch`): a pass kept under an older epoch is never taken, and an image's -/// kept passes all go at its next pass after the epoch moved. A kept pass's objects go once the -/// image lets go of them (as it drops, before its views; as the epoch moves; as a newer pass -/// takes the place of the oldest past [`KEPT_PASSES`]) and every command buffer that took them -/// completed. -pub(super) struct KeptResolves { - image: ResourceKey, - passes: Mutex>, -} - -impl KeptResolves { - /// No passes kept yet, for an image made now. - pub(super) fn new() -> KeptResolves { - KeptResolves { - image: ResourceKey::new(), - passes: Mutex::new(Kept::default()), - } - } - - /// Let every kept pass go. - pub(super) fn clear(&self) { - lock(&self.passes).values.clear(); - } -} - -/// What a kept pass's objects are made of ([`KeptResolves`]): the pass's extent and, for each -/// resolve and layer in the pass's order, the resolve's pipeline (format, samples and source), -/// the view it reads and the view it writes, each as its image's key and the view's description. -#[derive(Clone, Debug, PartialEq, Eq)] -struct PassKey { - extent: [u32; 2], - resolves: Vec, -} - -/// One resolve and layer of a [`PassKey`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct ResolveKey { - pipeline: (ColorResolveFormat, u32, Source), - read: (ResourceKey, VkView), - written: (ResourceKey, VkView), -} - -/// Values kept by key, each under the views epoch it was made in: at most [`KEPT_PASSES`], the -/// newest first, all of one epoch. -struct Kept { - epoch: u64, - values: Vec<(PassKey, Arc)>, -} - -impl Default for Kept { - fn default() -> Kept { - Kept { - epoch: 0, - values: Vec::new(), - } - } -} - -impl Kept { - /// The value kept for `key`, where the views epoch is `epoch` as it was when the value was - /// made; a newer epoch lets every kept value go. - fn find(&mut self, epoch: u64, key: &PassKey) -> Option> { - self.at(epoch); - if epoch != self.epoch { - return None; - } - self.values - .iter() - .find(|(kept, _)| kept == key) - .map(|(_, value)| Arc::clone(value)) - } - - /// Keep `value` for `key`, made under views epoch `epoch`: not where the epoch moved since, - /// and letting the oldest go past [`KEPT_PASSES`]. - fn keep(&mut self, epoch: u64, key: PassKey, value: Arc) { - self.at(epoch); - if epoch != self.epoch { - return; - } - if self.values.len() == KEPT_PASSES { - self.values.pop(); - } - self.values.insert(0, (key, value)); - } - - /// Let every kept value go where `epoch` is newer than theirs. - fn at(&mut self, epoch: u64) { - if epoch > self.epoch { - self.values.clear(); - self.epoch = epoch; - } - } -} - -/// The key of a pass resolving each of `wanted` (its attachment, its resolve attachment, its -/// format's rules and its source) over `extent` in `layers` layers ([`KeptResolves`]); `None` -/// where a resolve reads the sample planes or a copy of its samples, or its targets have other -/// layers than the pass (which [`ShaderResolves::plan`] refuses). -fn pass_key<'a>( - wanted: impl Iterator, - extent: [u32; 2], - layers: u32, -) -> Result, Error> { - let mut resolves = Vec::new(); - for (attachment, into, format, source) in wanted { - let own_views = source.attachment() - && attachment.layers == layers - && into.layers == layers - && takes_input(attachment)?; - if !own_views { - return Ok(None); - } - let read = attachment.texture.kept_resolves()?.image; - let written = into.texture.kept_resolves()?.image; - for layer in 0..layers { - resolves.push(ResolveKey { - pipeline: (format, attachment.samples, source), - read: ( - read, - view_of(attachment, layer, source.read_format(format), INPUT)?, - ), - written: ( - written, - view_of(into, layer, format.written_format(), WRITTEN)?, - ), - }); - } - } - Ok(Some(PassKey { extent, resolves })) -} - -/// The usage of a resolve's view of the samples it reads as its input attachment. -const INPUT: ImageUsageFlags = ImageUsageFlags::INPUT_ATTACHMENT; -/// The usage of a resolve's view of the attachment it writes. -const WRITTEN: ImageUsageFlags = ImageUsageFlags::COLOR_ATTACHMENT; - -/// The use of `samples`' level and `layers` layers by a resolve that reads them as its input -/// attachment. -fn read_use(samples: &Target, layers: u32) -> Result, Error> { - samples.texture.image_use( - samples.level..samples.level + 1, - samples.layer..samples.layer + layers, - Access::new( - vk::PipelineStageFlags2::FRAGMENT_SHADER - | vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT, - vk::AccessFlags2::INPUT_ATTACHMENT_READ - | vk::AccessFlags2::COLOR_ATTACHMENT_READ - | vk::AccessFlags2::COLOR_ATTACHMENT_WRITE, - ), - true, - ) -} - -/// The use of `into`'s level and `layers` layers by the resolve that writes them. -fn written_use(into: &Target, layers: u32) -> Result, Error> { - into.texture.image_use( - into.level..into.level + 1, - into.layer..into.layer + layers, - Access::new( - vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT, - vk::AccessFlags2::COLOR_ATTACHMENT_WRITE, - ), - true, - ) -} - -/// The copy of `samples`' level and `layers` layers over the render area `extent` into a scratch -/// image of its format and samples that the crate-owned resolve reads as its input attachment -/// ([`copied`]), through a view in `view` where one is named (the sRGB twin the device decodes, -/// [`decodes`]): the scratch, the copy, and its uses (the read of the attachment and the write of -/// the scratch). The scratch is `maker`'s, held until it completes. -fn copy_out( - maker: &CommandBuffer, - samples: &Target, - layers: u32, - extent: [u32; 2], - view: Option, -) -> Result< - ( - Target, - (vk::Image, vk::Image, vk::ImageCopy), - [Use; 2], - ), - Error, -> { - let usage = ImageUsageFlags::COLOR_ATTACHMENT - | ImageUsageFlags::INPUT_ATTACHMENT - | ImageUsageFlags::TRANSFER_DST; - let area = Target { - extent, - ..samples.clone() - }; - let scratch = resolve::scratch_viewed(maker, &area, usage, samples.samples, view)?; - let at = |t: &Target| vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::COLOR, - mip_level: t.level, - base_array_layer: t.layer, - layer_count: layers, - }; - let [width, height] = extent; - let region = vk::ImageCopy { - src_subresource: at(samples), - src_offset: vk::Offset3D::default(), - dst_subresource: at(&scratch), - dst_offset: vk::Offset3D::default(), - extent: vk::Extent3D { - width, - height, - depth: 1, - }, - }; - let level = |t: &Target| t.level..t.level + 1; - let on = |t: &Target| t.layer..t.layer + layers; - let uses = [ - samples.texture.image_use( - level(samples), - on(samples), - Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ), - false, - )?, - scratch.texture.image_use( - level(&scratch), - on(&scratch), - Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE), - true, - )?, - ]; - let copy = ( - samples.texture.raw_image()?, - scratch.texture.raw_image()?, - region, - ); - Ok((scratch, copy, uses)) -} - -/// The single-level view of `target`'s layer `layer` (counted from its first) in `format`, -/// serving `usage`. -fn view( - target: &Target, - layer: u32, - format: Format, - usage: ImageUsageFlags, -) -> Result { - target - .texture - .image_view(&view_of(target, layer, format, usage)?) -} - -/// The description of [`view`]'s view. -fn view_of( - target: &Target, - layer: u32, - format: Format, - usage: ImageUsageFlags, -) -> Result { - // A 1D image's layer is a 1D view (a 3D image's planes take 2D ones). - let view_type = match target.texture.image_plan()?.image_type { - metal2vulkan::vk::ImageType::TYPE_1D => ImageViewType::TYPE_1D, - _ => ImageViewType::TYPE_2D, - }; - Ok(VkView { - view_type, - format, - components: ComponentMapping::IDENTITY, - aspect: ImageAspectFlags::COLOR, - base_level: target.level, - level_count: 1, - base_layer: target.layer + layer, - layer_count: 1, - usage, - }) -} - -impl ShaderResolves { - /// The exact resolves of `layout`'s color attachments (its final layout) whose last render - /// pass instance leaves `last_storage` out of its draws' subpass: each from its sample - /// planes where they hold its samples, else from the attachment, or from a copy of its - /// samples where its image takes no input attachment usage (the module docs). `None` where - /// no attachment resolves so. Scratch images are `maker`'s. - pub(super) fn plan( - maker: &CommandBuffer, - layout: &PassLayout, - last_storage: &[u32], - ) -> Result, Error> { - let device = maker.device(); - let mut wanted = Vec::new(); - for (index, color) in layout.colors.iter().enumerate() { - let Some(color) = color else { - continue; - }; - let Some(resolve) = &color.resolve else { - continue; - }; - let Some(format) = resolve.shader else { - continue; - }; - // A twin resolve's rules are the resolve attachment's format's, which the sample - // planes' copy format does not hold the codes under: it reads the attachment itself - // (`resolve::Resolve::twin`). - let planes = color - .planes - .as_ref() - .filter(|_| last_storage.contains(&(index as u32)) && !resolve.twin); - // An attachment read from a copy of its samples ([`copied`]) is read in its own - // format, or in the sRGB twin the device decodes ([`decodes`]): the scratch image - // takes no other view. Its own is the rules' raw form where the attachment is already - // in it, which a twin resolve's UNORM attachment under its sRGB resolve texture's - // tables is. Under the device's decode the samples are read in the rules' format. - let decoded = format.decodes_on_device(); - let raw = !decoded - && raw_view(device, &color.target, format)? - && (takes_input(&color.target)? || color.target.format == format.raw_format()); - let source = match planes { - Some(planes) => Source::Planes(planes.copy), - None => Source::Attachment { raw }, - }; - // The view the source reads the samples through, the rules' own form or its raw - // twin, must be one their image takes: a twin resolve reads an sRGB attachment - // through the UNORM twin its rules are in, and a UNORM one through its own format or, - // under the device's decode, its sRGB twin's. A copy of the samples ([`copied`]) is - // read in the attachment's own format, or in the sRGB twin its scratch image takes - // for the device's decode ([`copy_out`]). - let read_format = source.read_format(format); - let reaches = match source.attachment() { - false => true, - true if takes_input(&color.target)? => { - views_as(color.target.texture.image_plan()?, read_format, false) - } - true => read_format == color.target.format || decoded, - }; - if !reaches { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - // The result goes out through the resolve attachment's raw view where it has one, - // but for the device's encode, which its own view stores. - let format = match !decoded && raw_view(device, &resolve.attachment, format)? { - true => format.written_raw(), - false => format, - }; - wanted.push((color, resolve, format, source, planes)); - } - if wanted.is_empty() { - return Ok(None); - } - // A layered pass resolves each of its layers in a render pass instance of its own. The - // sample planes hold one layer (`sample_planes.rs`), so such a pass's resolve from them - // is not built. - let layers = layout.layers; - if layers > 1 && wanted.iter().any(|w| !w.3.attachment()) { - return Err(Error::NotImplemented(RuntimeGap::LayeredPass)); - } - // A pass whose resolves read their attachments through their own views takes the objects - // the image it first resolves into keeps for a pass of the same key, or keeps the ones it - // makes ([`KeptResolves`]). The views epoch is read before any view is taken, so a pass is - // kept under an epoch no newer than its views'. - let epoch = device.shared().views_epoch.load(Ordering::Acquire); - let targets = wanted - .iter() - .map(|w| (&w.0.target, &w.1.attachment, w.2, w.3)); - let kept = match pass_key(targets, layout.extent, layers)? { - Some(key) => Some((wanted[0].1.attachment.texture.kept_resolves()?, key)), - None => None, - }; - if let Some((memo, key)) = &kept { - if let Some(objects) = lock(&memo.passes).find(epoch, key) { - let mut uses = Vec::with_capacity(2 * wanted.len()); - for (color, resolve, ..) in &wanted { - uses.push(read_use(&color.target, layers)?); - uses.push(written_use(&resolve.attachment, layers)?); - } - device.shared().counts.color_resolve_pass_kept(); - return Ok(Some(ShaderResolves { - extent: layout.extent, - uses, - copies: Vec::new(), - copy_uses: Vec::new(), - objects, - })); - } - } - let raw = device.shared().vk(); - let count = wanted.len() as u32 * layers; - let mut objects = PassObjects { - device: device.clone(), - pool: vk::DescriptorPool::null(), - resolves: Vec::with_capacity(count as usize), - }; - let inputs = wanted.iter().filter(|w| w.3.attachment()).count() as u32 * layers; - let mut sizes = Vec::new(); - for (ty, n) in [ - (vk::DescriptorType::INPUT_ATTACHMENT, inputs), - (vk::DescriptorType::SAMPLED_IMAGE, count - inputs), - ] { - if n > 0 { - sizes.push(vk::DescriptorPoolSize::default().ty(ty).descriptor_count(n)); - } - } - let info = vk::DescriptorPoolCreateInfo::default() - .max_sets(count) - .pool_sizes(&sizes); - // SAFETY: `info` and its array are live for the call. - objects.pool = unsafe { raw.create_descriptor_pool(&info, None) }.map_err(vulkan)?; - let general = vk::ImageLayout::GENERAL; - let mut uses = Vec::new(); - let mut copies = Vec::new(); - let mut copy_uses = Vec::new(); - for (color, resolve, format, source, planes) in wanted { - let attachment = &color.target; - let into = &resolve.attachment; - if attachment.layers != layers || into.layers != layers { - return Err(internal("an exact resolve of other layers than its pass")); - } - // An attachment whose image takes no input attachment usage is read from a copy of - // its samples ([`copied`]). - let read_copy = source.attachment() && !takes_input(attachment)?; - let scratch = match read_copy { - true if copied(device, attachment)? => { - let read_format = source.read_format(format); - let view = (read_format != attachment.format).then_some(read_format); - let (scratch, copy, used) = - copy_out(maker, attachment, layers, layout.extent, view)?; - copies.push(copy); - copy_uses.extend(used); - Some(scratch) - } - // A twin resolve is the one the runtime draws whatever the device's average, so - // an attachment it can neither read nor copy is a resolve the runtime does not - // build, not an invariant ([`of_resolve`] gates every other one). - true if resolve.twin => return Err(Error::NotImplemented(RuntimeGap::Render)), - true => { - return Err(internal( - "an exact resolve of an attachment it can neither read nor copy", - )) - } - false => None, - }; - let samples = scratch.as_ref().unwrap_or(attachment); - let pipeline = device.color_resolve_pipeline(format, samples.samples, source)?; - match (source, planes) { - (Source::Planes(_), Some(planes)) => uses.push(planes.image_use( - Access::new( - vk::PipelineStageFlags2::FRAGMENT_SHADER, - vk::AccessFlags2::SHADER_SAMPLED_READ, - ), - false, - )?), - (Source::Attachment { .. }, _) => uses.push(read_use(samples, layers)?), - (Source::Planes(_), None) => { - return Err(internal("a planes resolve without planes")) - } - } - uses.push(written_use(into, layers)?); - // Each layer of the pass: one set and framebuffer of that layer's views. - for layer in 0..layers { - let layouts = [pipeline.set_layout]; - let allocate = vk::DescriptorSetAllocateInfo::default() - .descriptor_pool(objects.pool) - .set_layouts(&layouts); - // SAFETY: the pool holds a set per resolve and layer, of its source's descriptor - // (counted above). - let set = unsafe { raw.allocate_descriptor_sets(&allocate) } - .map_err(vulkan)? - .first() - .copied() - .ok_or_else(|| internal("the driver allocated no set"))?; - let written = view(into, layer, format.written_format(), WRITTEN)?; - let (read, attachments) = match (source, planes) { - (Source::Planes(copy), Some(planes)) => { - let read = planes.view(copy.format(), ImageUsageFlags::SAMPLED)?; - (read, vec![written]) - } - (Source::Attachment { .. }, _) => { - let read = view(samples, layer, source.read_format(format), INPUT)?; - (read, vec![read, written]) - } - (Source::Planes(_), None) => { - return Err(internal("a planes resolve without planes")) - } - }; - let info = [vk::DescriptorImageInfo::default() - .image_view(read) - .image_layout(general)]; - // SAFETY: the set was just allocated and no command uses it; the view is live - // (the command buffer retains its texture). - unsafe { - raw.update_descriptor_sets( - &[vk::WriteDescriptorSet::default() - .dst_set(set) - .dst_binding(0) - .descriptor_type(source.descriptor()) - .image_info(&info)], - &[], - ) - }; - let [width, height] = layout.extent; - let info = vk::FramebufferCreateInfo::default() - .render_pass(pipeline.render_pass) - .attachments(&attachments) - .width(width) - .height(height) - .layers(1); - // SAFETY: `info` and its array are live for the call; the views are live. - let framebuffer = unsafe { crate::creation::framebuffer(raw, &info) }?; - objects.resolves.push(Planned { - pipeline, - framebuffer, - set, - }); - } - } - device.shared().counts.color_resolve_pass_made(); - let objects = Arc::new(objects); - if let Some((memo, key)) = kept { - lock(&memo.passes).keep(epoch, key, Arc::clone(&objects)); - } - Ok(Some(ShaderResolves { - extent: layout.extent, - uses, - copies, - copy_uses, - objects, - })) - } - - /// Record the resolves in `core`'s command buffer after the pass, between barriers from - /// everything before and to everything after, each copy of an attachment's samples first, - /// between barriers too, and hold their objects until the command buffer completes. - pub(super) fn record(self, core: &mut EncoderCore) { - let ShaderResolves { - extent, - uses, - copies, - copy_uses, - objects, - } = self; - let [width, height] = extent; - let area = vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent: vk::Extent2D { width, height }, - }; - let viewport = vk::Viewport { - x: 0.0, - y: 0.0, - width: width as f32, - height: height as f32, - min_depth: 0.0, - max_depth: 1.0, - }; - core.barrier(Barrier::everything()); - if !copies.is_empty() { - core.command(TRANSFER, ©_uses, |raw, command_buffer| { - let general = vk::ImageLayout::GENERAL; - for &(from, to, region) in &copies { - // SAFETY: the encoder's command buffer is recording outside a render pass; - // both images are live until it completes (the encoder retains the - // attachment's texture, and the command buffer the scratch's) and rest in - // `GENERAL`; the region is the attachment's level and the pass's layers over - // the render area, in both images, of one format and sample count. - unsafe { - raw.cmd_copy_image(command_buffer, from, general, to, general, &[region]) - }; - } - }); - core.barrier(Barrier::everything()); - } - core.command(ATTACHMENT_STAGES, &uses, |raw, command_buffer| { - for resolve in &objects.resolves { - let begin = vk::RenderPassBeginInfo::default() - .render_pass(resolve.pipeline.render_pass) - .framebuffer(resolve.framebuffer) - .render_area(area); - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // pipeline, framebuffer, set and the images they view are live until it completes - // (the device keeps the pipeline, this the framebuffer and set, the encoder the - // textures and planes); every image rests in `GENERAL`. A kept framebuffer and - // set are of views the textures still present ([`KeptResolves`]). - unsafe { - raw.cmd_begin_render_pass(command_buffer, &begin, vk::SubpassContents::INLINE); - raw.cmd_bind_pipeline( - command_buffer, - vk::PipelineBindPoint::GRAPHICS, - resolve.pipeline.pipeline, - ); - raw.cmd_bind_descriptor_sets( - command_buffer, - vk::PipelineBindPoint::GRAPHICS, - resolve.pipeline.layout, - 0, - &[resolve.set], - &[], - ); - raw.cmd_set_viewport(command_buffer, 0, &[viewport]); - raw.cmd_set_scissor(command_buffer, 0, &[area]); - raw.cmd_draw(command_buffer, 3, 1, 0, 0); - raw.cmd_end_render_pass(command_buffer); - } - } - }); - core.barrier(Barrier::everything()); - core.retain(objects); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A pass resolving a view of image `read` into one of image `written`, the same views but - /// for their images. - fn key(read: ResourceKey, written: ResourceKey) -> PassKey { - let view = VkView { - view_type: ImageViewType::TYPE_2D, - format: Format::R8G8B8A8_UNORM, - components: ComponentMapping::IDENTITY, - aspect: ImageAspectFlags::COLOR, - base_level: 0, - level_count: 1, - base_layer: 0, - layer_count: 1, - usage: INPUT, - }; - let format = ColorResolveFormat::of(Format::R8G8B8A8_UNORM).expect("RGBA8's rules"); - PassKey { - extent: [4, 4], - resolves: vec![ResolveKey { - pipeline: (format, 4, Source::Attachment { raw: false }), - read: (read, view), - written: ( - written, - VkView { - usage: WRITTEN, - ..view - }, - ), - }], - } - } - - /// A pass kept of a view of an image that dropped is never taken for the same view of an - /// image made after it, whatever handle the driver gives the new view (it may give the - /// dropped one's again): a key names an image by a key no other image had, and no handle. - #[test] - fn a_new_image_s_view_never_takes_a_dropped_image_s_kept_pass() { - let written = KeptResolves::new(); - let dropped = KeptResolves::new(); - let dropped_key = dropped.image; - let mut kept = Kept::default(); - kept.keep(1, key(dropped_key, written.image), Arc::new(())); - assert!(kept.find(1, &key(dropped_key, written.image)).is_some()); - drop(dropped); - let made_after = KeptResolves::new(); - assert_ne!(made_after.image, dropped_key); - assert!(kept - .find(1, &key(made_after.image, written.image)) - .is_none()); - } - - /// Once an image let views go (the views epoch moved), a kept pass is never taken but made - /// again, every kept one is let go, and one made under the older epoch is not kept. - #[test] - fn a_moved_views_epoch_makes_the_pass_again() { - let (read, written) = (KeptResolves::new().image, KeptResolves::new().image); - let objects = Arc::new(()); - let mut kept = Kept::default(); - kept.keep(3, key(read, written), Arc::clone(&objects)); - assert!(kept.find(3, &key(read, written)).is_some()); - assert!(kept.find(4, &key(read, written)).is_none()); - assert_eq!( - Arc::strong_count(&objects), - 1, - "the kept pass was not let go" - ); - kept.keep(3, key(read, written), Arc::clone(&objects)); - assert!(kept.find(4, &key(read, written)).is_none()); - kept.keep(4, key(read, written), Arc::clone(&objects)); - assert!(kept.find(4, &key(read, written)).is_some()); - } - - /// An image keeps at most `KEPT_PASSES` passes, letting the oldest go first. - #[test] - fn an_image_keeps_its_newest_passes() { - let written = KeptResolves::new().image; - let reads: Vec<_> = (0..=KEPT_PASSES) - .map(|_| KeptResolves::new().image) - .collect(); - let mut kept = Kept::default(); - for &read in &reads { - kept.keep(0, key(read, written), Arc::new(())); - } - assert!(kept.find(0, &key(reads[0], written)).is_none()); - for &read in &reads[1..] { - assert!(kept.find(0, &key(read, written)).is_some()); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/batches.rs b/crates/metal2vulkan-runtime/src/command_buffer/batches.rs deleted file mode 100644 index bf172e861..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/batches.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! A command buffer's batches: its encoders, split where it waits for events or for the caller's -//! binary semaphores, and before the part of an encoder that executes commands the GPU may write, -//! which runs once everything before it completed. -//! -//! A batch is its waits, then its encoders, then its signals, and the scheduler submits each batch -//! once its waits are satisfied. A wait after an encoder or a signal starts a new batch, since -//! everything encoded before it must be able to run, and to signal, while it waits (measured on -//! Metal). An encoder after a signal starts one too, so the signal happens once the encoders before -//! it completed, not the ones after. Within one batch, two waits for one event are the wait for the -//! larger value, and two signals of one event the signal of the larger value, which is what Metal's -//! maximum makes of them. A binary semaphore is waited for or signaled at most once per batch: each -//! wait consumes one signal, so a second wait or signal of the same semaphore starts a new batch, -//! in order. Every command buffer has at least one batch, so even one with nothing encoded -//! completes in its queue's order. - -/// One batch: waits, a run of encoders, and signals, with events of type `E` and binary -/// semaphores of type `S`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct Batch { - /// The events waited for, each once, with the value. - pub(crate) waits: Vec<(E, u64)>, - /// The binary semaphores waited for, each once. - pub(crate) binary_waits: Vec, - /// The number of the command buffer's encoders before this batch's end. - pub(crate) end: usize, - /// The events signaled, each once, with the value. - pub(crate) signals: Vec<(E, u64)>, - /// The binary semaphores signaled, each once. - pub(crate) binary_signals: Vec, -} - -impl Batch { - fn new(end: usize) -> Batch { - Batch { - waits: Vec::new(), - binary_waits: Vec::new(), - end, - signals: Vec::new(), - binary_signals: Vec::new(), - } - } - - /// Whether the batch signals anything. - fn signals_any(&self) -> bool { - !self.signals.is_empty() || !self.binary_signals.is_empty() - } -} - -/// The batches of a command buffer being encoded: the last one is the current one. -#[derive(Debug)] -pub(crate) struct Batches { - batches: Vec>, - /// The encoders of the current batch. - encoders: usize, - /// The resource state encoders the current batch begins with. - binds: usize, - /// The event waits encoded so far (`encodeWaitForEvent:value:`), each call counted. - event_waits: usize, - /// The event signals encoded so far (`encodeSignalEvent:value:`), each call counted. - event_signals: usize, -} - -impl Default for Batches { - fn default() -> Batches { - Batches { - batches: vec![Batch::new(0)], - encoders: 0, - binds: 0, - event_waits: 0, - event_signals: 0, - } - } -} - -impl Batches { - /// An encoder ended. - pub(crate) fn encoder(&mut self) { - if self.current().signals_any() { - self.split(); - } - self.encoders += 1; - self.current().end += 1; - } - - /// The next encoder, the part of one that executes commands the GPU may write, starts a - /// batch of its own: the scheduler submits it once everything before it completed and its - /// host step recorded the commands. - pub(crate) fn host_step(&mut self) { - self.split(); - } - - /// The next encoder goes in a batch of its own, where the current one holds an encoder - /// already: the encoder trail's (`encoder_trail.rs`), whose batches hold one encoder each. - /// The current batch's waits stay with it, and so does the encoder where it holds none. - pub(crate) fn alone(&mut self) { - if self.encoders > 0 { - self.split(); - } - } - - /// The next encoder is a resource state encoder: its updates bind before its batch's work, so - /// it starts a batch unless the current one holds only such encoders and no signal. - pub(crate) fn sparse(&mut self) { - if self.encoders > self.binds || self.current().signals_any() { - self.split(); - } - self.binds += 1; - } - - /// The batches, in order: at least one. - pub(crate) fn all(&self) -> &[Batch] { - &self.batches - } - - /// Whether the current batch signals, so the next encoder starts a batch of its own - /// ([`encoder`](Self::encoder)). - pub(crate) fn signals_pending(&self) -> bool { - self.batches.last().is_some_and(Batch::signals_any) - } - - /// The event waits and the event signals encoded so far, each call counted, binary - /// semaphores' none: an encoder that ends now has them all before it - /// (`CommandBuffer::ended_encoders`). - pub(crate) fn events(&self) -> (usize, usize) { - (self.event_waits, self.event_signals) - } - - /// Signal no event (`CommandBuffer::commit_failed` without signals): every batch keeps its - /// waits, encoders and binary semaphore signals. - pub(crate) fn drop_signals(&mut self) { - for batch in &mut self.batches { - batch.signals.clear(); - } - } - - /// Signal no event after the first `parts` encoders (or parts of them): a command buffer - /// Metal fails from an encoder on signals what was encoded before it. The batches that end - /// past them keep their waits, encoders and binary semaphore signals. - pub(crate) fn drop_signals_after(&mut self, parts: usize) { - for batch in self.batches.iter_mut().filter(|batch| batch.end > parts) { - batch.signals.clear(); - } - } - - fn current(&mut self) -> &mut Batch { - let last = self.batches.len() - 1; - &mut self.batches[last] - } - - fn split(&mut self) { - let end = self.current().end; - self.batches.push(Batch::new(end)); - self.encoders = 0; - self.binds = 0; - } - - /// Start a new batch where a wait cannot join the current one: it has encoders or signals. - fn before_wait(&mut self) { - if self.encoders > 0 || self.current().signals_any() { - self.split(); - } - } -} - -impl Batches { - /// `encodeWaitForEvent:value:`. - pub(crate) fn wait(&mut self, event: E, value: u64) { - self.event_waits += 1; - self.before_wait(); - add_max(&mut self.current().waits, event, value); - } - - /// The runtime's own wait for `event` to reach `value`, which no `encodeWaitForEvent:value:` - /// made: it splits the batches as one does, and is not counted among the event waits - /// ([`events`](Self::events)). - pub(crate) fn hold(&mut self, event: E, value: u64) { - self.before_wait(); - add_max(&mut self.current().waits, event, value); - } - - /// The runtime's own signal of `event` to `value`, which no `encodeSignalEvent:value:` made: - /// it ends the batch as one does, and is not counted among the event signals - /// ([`events`](Self::events)). - pub(crate) fn hold_signal(&mut self, event: E, value: u64) { - add_max(&mut self.current().signals, event, value); - } - - /// `encodeSignalEvent:value:`. - pub(crate) fn signal(&mut self, event: E, value: u64) { - self.event_signals += 1; - add_max(&mut self.current().signals, event, value); - } - - /// A wait for binary semaphore `semaphore` (`encode_wait_for_vk_semaphore`). - pub(crate) fn binary_wait(&mut self, semaphore: S) { - self.before_wait(); - if self.current().binary_waits.contains(&semaphore) { - self.split(); - } - self.current().binary_waits.push(semaphore); - } - - /// A signal of binary semaphore `semaphore` (`encode_signal_vk_semaphore`). - pub(crate) fn binary_signal(&mut self, semaphore: S) { - if self.current().binary_signals.contains(&semaphore) { - self.split(); - } - self.current().binary_signals.push(semaphore); - } -} - -/// Add `event` at `value` to `list`, which holds each event once at its largest value. -fn add_max(list: &mut Vec<(E, u64)>, event: E, value: u64) { - match list.iter_mut().find(|(known, _)| *known == event) { - Some((_, known)) => *known = (*known).max(value), - None => list.push((event, value)), - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/carried.rs b/crates/metal2vulkan-runtime/src/command_buffer/carried.rs deleted file mode 100644 index 0c2c3ded3..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/carried.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! What a command buffer's batches carried into a `vkQueueSubmit` that failed, for the line it -//! logs (`submit_failure.rs`): the command buffer as the runtime's notices name it, and the -//! resources its encoders' uses name and what they made resident, each as what owns its memory -//! (`used_resources.rs`). Read only once the call failed, under the locks its submitter holds. - -use super::{CommandBufferShared, State}; -use crate::submit_failure::{Carried, TypeFlags}; -use crate::used_resources::{failure_facts, resident_keys}; -use std::collections::BTreeSet; -use std::fmt::Write; -use std::ops::Range; - -impl CommandBufferShared { - /// Add the command buffer, `state` its state, to `carried`: named by its identity and as the - /// runtime's notices name it, with its batch `index` where given; the role of each - /// `VkCommandBuffer` of the encoders it recorded at `encoders` (every one it recorded where - /// that is `None`); and the resources those encoders name, or, where it is `None`, every ended - /// encoder of it, stated with `types`' flags for their memory types. - pub(crate) fn carry( - &self, - state: &State, - (index, encoders): (Option, Option>), - carried: &mut Carried, - types: &TypeFlags, - ) { - let queue = self.queue.label(); - let mut named = format!("#{} {}", self.id.get(), state.named(queue.as_deref())); - if let Some(index) = index { - let batches = state.batches.all().len(); - let _ = write!(named, ", its batch {index} of {batches}"); - } - carried.buffers.push(named); - let recorded = match &encoders { - Some(encoders) => &state.recorded[encoders.clone()], - None => &state.recorded[..], - }; - let mut keys = BTreeSet::new(); - for part in recorded { - let kind = match state.ended.get(part.encoder) { - Some(record) => format!("{:?}", record.kind), - None => "open".to_owned(), - }; - let role = format!("encoder {} {kind} of #{}", part.encoder, self.id.get()); - carried - .roles - .extend(part.raws.iter().map(|&raw| (raw, role.clone()))); - if encoders.is_some() { - keys.extend(part.summary.keys()); - } - } - let ended = match encoders { - Some(_) => (recorded.iter()) - .filter_map(|part| state.ended.get(part.encoder)) - .collect(), - None => state.ended.iter().collect::>(), - }; - for record in ended { - keys.extend(&record.keys); - if let Some(residency) = &record.residency { - resident_keys(residency, &mut keys); - } - } - let shared = self.device.shared(); - failure_facts( - shared, - &keys, - types, - (&mut carried.resources, &mut carried.stated), - ); - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs deleted file mode 100644 index 4d138342d..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs +++ /dev/null @@ -1,457 +0,0 @@ -//! A command buffer's submission checks (a runtime extension): a check the program sets runs for -//! each submission of the command buffer as Metal splits it, once its event waits are met, just -//! before the runtime submits it, and may fail it with a code. -//! -//! - **Metal's submissions** ([`metal_submissions`]). Metal splits a command buffer into -//! submissions (measured by a consumer on an M3 Max, macOS 26.7): each render pass is its own; -//! consecutive blit encoders share one, as do consecutive compute encoders; an event wait or -//! signal between two encoders splits a run. Resource state encoders join their own runs, as -//! blits do (unmeasured). The runtime's batches split at every event command too, so a submission -//! begins in one batch; it may run on into later batches, split at a host step, a resource state -//! encoder or a binary semaphore, which Metal does not split at. -//! - **When.** The scheduler holds a batch of a command buffer with a check, as it holds one for -//! its host step, once it is otherwise ready: its binary semaphores' signals submitted, every -//! event value it waits for reached by the host or by a submitted signal, and its host step -//! recorded. Then the event's kind decides, as Metal's submission does (an M3 Max under macOS -//! 27.0.1, the conformance case `event-wait-behind-a-running-signal`: a command buffer waiting -//! for a value only a signal still running on the GPU reaches, its status and scheduled handler -//! read while that signal ran; its `Scheduled` is the proxy for "submitted, and so checked"). An -//! `Event`'s value no host call sets, and Metal submits a command buffer whose `MTLEvent` wait -//! such a signal meets at once: so a wait the batch hands to its `VkQueue` (a signal submitted -//! before it, on its `VkQueue` or one the GPU wait reaches, or reserved by the caller) holds no -//! check, which runs at once and the batch goes with the wait on the `VkQueue`, as a batch -//! without a check does. Metal holds one whose `MTLSharedEvent` wait such a signal meets until -//! the signal lands, as the runtime holds every wait for a value the host may set -//! (`event_timeline.rs`): so a `SharedEvent`'s value reached only by a GPU signal submitted but -//! not yet landed holds the check until it lands, and a resource detached meanwhile fails the -//! submission. A value the host set (or the device reached) needs no wait. On its thread, without -//! its own lock or the command buffer's, it then runs the check of each submission that begins in -//! the batch, and again of each that a host step of the batch recorded commands for (what they -//! reach is known only then), then submits the batch in its order. A thread in -//! `CommandBuffer::commit_and_submit` that makes the submission pass itself runs those checks -//! instead, the same way, just before it submits the batch, where the batch is the first queue's -//! head in commit order ready but for them and behind no earlier commit, with no host step and no -//! group, and every value it waits for reached on the device or by the host or one its `VkQueue` -//! waits for (`scheduler::claim_check`); the rest are the scheduler thread's. Where the scheduler -//! groups batches (`CompletionPolicy::Grouped` on a driver that merges submissions, `group.rs`), -//! it runs the checks of up to three batches right behind a head that goes with the head's, in -//! commit order, each once its batch is otherwise ready and its events' values reached on the -//! device or by the host, none committed after another queue's batch: so they go to the driver -//! together. Such a check runs before the previous batch's `vkQueueSubmit`, in the pass that -//! submits its own batch, where alone it runs after it. `CompletionPolicy::Exact` checks each -//! head alone. -//! - **Stricter than Metal: the re-check after a host step.** Metal checks a submission once, -//! with what it knows as it submits it, and cannot know what the commands the GPU writes into -//! an indirect command buffer reach before they run (an earlier encoder of the same submission -//! may write them). The runtime checks such a submission as it begins and again once the host -//! step recorded those commands; a second check that fails it fails its encoders from that -//! batch on, its first part having run. So a resource reached only through such commands, which -//! Metal would not see, fails what is left of its submission. -//! - **A failed submission.** The encoders of a submission whose check answers a code run -//! nothing from that batch on, with the mechanics of `CommitFailure`'s set -//! (`State::fail_part`): every other encoder runs, the event signals fire, the scheduled and -//! completed handlers run, and the command buffer completes with status `Error` and -//! `CommandBufferError::Injected` of the first failure's code (a `commit_failed`'s before any -//! check's). A check that panics fails its submission with code 1 (`Internal`). The commit of -//! a command buffer with a check encodes again apart the encoders whose commands a shared -//! `VkCommandBuffer` of a group of encoders holds where they lie in more than -//! one submission (`encoder_fold.rs`'s **Failed**), so a failed submission's encoders run -//! nothing alone; where it cannot encode them again so, a failed submission whose commands -//! such a `VkCommandBuffer` holds fails every submission whose commands it holds. -//! - **Behind a hang** (`hang.rs`). A command buffer committed with an event wait while a hang -//! of its queue (a draw of primitive type 9) was in flight is held for this pass too, with or -//! without a check: its first batch's pass, once its waits are met and the batches before it -//! in its queue's order are submitted, runs nothing of it where a hang of its queue is still in -//! flight then, and the command buffer completes with no error, its event signals firing. No -//! check of the program's runs for it then. -//! - **Zero cost without a check.** A command buffer without one holds no submission and its -//! batches are never held for one: the scheduler reads one flag per batch. - -use super::{lock, CommandBuffer, CommandBufferShared, State}; -use crate::error::{invalid, CommandBufferError, Error, Problem}; -use crate::exit_guard; -use crate::resource::ObjectId; -use crate::used_resources::{union_of, EncoderKind, UsedResources}; -use std::num::NonZeroU64; -use std::ops::Range; -use std::sync::Arc; - -/// A command buffer's submission check ([`CommandBuffer::set_submission_check`]): a runtime -/// extension, no Metal type. Called with each submission of the command buffer as Metal splits -/// it, on the device's scheduler thread, or on the thread of a -/// [`CommandBuffer::commit_and_submit`] that submits it, it answers `None` for the submission to -/// run, or the `MTLCommandBufferError` code to fail it with (8, `OutOfMemory`, for one that uses -/// a resource whose memory was taken away, as Metal fails it). -/// -/// It runs with no lock of the runtime's held, and holds back the submissions of the thread that -/// runs it: a commit made meanwhile returns at once, and its batches wait in the inbox for the -/// scheduler thread's next pass, after this check (`scheduler/inbox.rs`). It must take no lock a -/// caller of `commit_and_submit` holds and must not wait for GPU work, a command buffer or a -/// handler, and should be quick. It may call the runtime otherwise. -pub type SubmissionCheck = Arc) -> Option + Send + Sync>; - -/// The `MTLCommandBufferError` code a submission whose check panicked fails with: `Internal`. -const PANICKED: u64 = 1; - -/// One submission of a command buffer as Metal splits it, as its [`SubmissionCheck`] sees it, -/// just before the runtime submits it: a runtime extension, no Metal type. -pub struct Submission<'a> { - command_buffer: &'a CommandBuffer, - kind: EncoderKind, - encoders: Range, -} - -impl Submission<'_> { - /// The command buffer. - pub fn command_buffer(&self) -> &CommandBuffer { - self.command_buffer - } - - /// Its encoders' kind: every encoder of a submission is of one kind. - pub fn kind(&self) -> EncoderKind { - self.kind - } - - /// Its encoders, by their places among the command buffer's ended encoders (the index of - /// [`CommandBuffer::ended_encoders`]). - pub fn encoders(&self) -> Range { - self.encoders.clone() - } - - /// What its encoders' commands use and reach, listed as - /// [`CommandBuffer::used_resources`] lists the command buffer's: what they bound, made - /// resident, copied, attached or mapped, and what the commands of the indirect command - /// buffers they execute reach (recorded at the commit, or by the host step before this - /// check). Listed when asked: a check that does not ask pays nothing for it. - pub fn used_resources(&self) -> UsedResources { - let records = self - .command_buffer - .state() - .read_ended(Some(self.encoders.clone())); - let used = union_of(self.command_buffer.device().shared(), &records); - // Released without the lock: what it holds may be a resource's last handle. - drop(records); - used - } - - /// Whether its encoders' commands use any of `objects`, the identities of what - /// [`used_resources`](Self::used_resources) would list, answered without listing it, as - /// [`CommandBuffer::uses`] answers: no handle is cloned or held. - pub fn uses(&self, objects: &[ObjectId]) -> bool { - let shared = self.command_buffer.device().shared(); - (self.command_buffer.state()).uses(shared, Some(self.encoders.clone()), objects) - } -} - -/// One of Metal's submissions of a committed command buffer with a check. -pub(super) struct Planned { - kind: EncoderKind, - encoders: Range, - /// Its check ran (once at least). - checked: bool, - /// Its check failed it. - failed: bool, -} - -/// The submissions due for checks before a batch, each by its place among Metal's, its kind and -/// its encoders, with the program's check where it set one (`State::due`). -type Due = ( - Option, - Vec<(usize, EncoderKind, Range)>, -); - -/// What a committed command buffer with a check keeps for it. -pub(super) struct Checks { - /// Metal's submissions of its ended encoders, in order, made at the commit. - planned: Vec, - /// The batches whose checks ran, a prefix of them. - batches: usize, -} - -/// Metal's submissions of encoders of `kinds`, each with the event waits and signals encoded -/// before it, in order (the module docs): each submission's kind and encoders. -pub(crate) fn metal_submissions( - encoders: impl IntoIterator, -) -> Vec<(EncoderKind, Range)> { - let mut submissions: Vec<(EncoderKind, Range)> = Vec::new(); - let mut before: Option<(EncoderKind, usize, usize)> = None; - for (at, encoder) in encoders.into_iter().enumerate() { - let joins = - before.is_some_and(|before| before == encoder && encoder.0 != EncoderKind::Render); - match submissions.last_mut() { - Some((_, range)) if joins => range.end = at + 1, - _ => submissions.push((encoder.0, at..at + 1)), - } - before = Some(encoder); - } - submissions -} - -/// The first encoder of the submission among Metal's submissions of `encoders` -/// ([`metal_submissions`]) that holds encoder `at`: `at` itself past them. -pub(crate) fn submission_start( - encoders: impl IntoIterator, - at: usize, -) -> usize { - metal_submissions(encoders) - .into_iter() - .find(|(_, range)| range.contains(&at)) - .map_or(at, |(_, range)| range.start) -} - -impl State { - /// Metal's submissions of its ended encoders ([`metal_submissions`]). - pub(super) fn metal_submissions(&self) -> Vec<(EncoderKind, Range)> { - metal_submissions(self.ended.iter().map(|record| { - ( - record.kind, - record.event_waits_before, - record.event_signals_before, - ) - })) - } - - /// Metal's submissions of its ended encoders, for its check, as it commits; nothing without - /// a check, or a decision of its first batch's submission behind a hang (`hang.rs`). - pub(super) fn plan_checks(&mut self) { - if self.check.is_none() && self.behind_hang.is_none() { - return; - } - let planned = self - .metal_submissions() - .into_iter() - .map(|(kind, encoders)| Planned { - kind, - encoders, - checked: false, - failed: false, - }) - .collect(); - self.checks = Some(Checks { - planned, - batches: 0, - }); - } - - /// The submissions to check before batch `index` is submitted: each that begins in it, and - /// each that a host step of it recorded commands for; each marked checked; with the program's - /// check, where it set one. `None` when the batch needs no check pass. - fn due(&mut self, index: usize) -> Option { - let range = self.batch_range(index); - let parts = &self.recorded[range]; - let encoders: Vec = parts.iter().map(|part| part.encoder).collect(); - let stepped: Vec = parts - .iter() - .filter(|part| { - part.segments - .iter() - .any(|segment| segment.stepped && segment.recorded.is_some()) - }) - .map(|part| part.encoder) - .collect(); - let check = self.check.clone(); - let checks = self.checks.as_mut()?; - if checks.batches > index { - return None; - } - let mut due = Vec::new(); - for (at, planned) in checks.planned.iter_mut().enumerate() { - if planned.failed { - continue; - } - let here = |list: &[usize]| list.iter().any(|e| planned.encoders.contains(e)); - if (!planned.checked && here(&encoders)) || (planned.checked && here(&stepped)) { - planned.checked = true; - due.push((at, planned.kind, planned.encoders.clone())); - } - } - Some((check, due)) - } - - /// The check of submission `at` (`encoders`) failed it with `code`, before batch `index` - /// is submitted: its encoders' parts from that batch on run nothing (`fail_part`), and the - /// command buffer fails with the code unless it failed already. Where one of them lies in a - /// group of encoders recorded into one `VkCommandBuffer` that holds commands of other - /// submissions too, which the commit could not split (`State::split_failure`), every - /// submission whose commands it holds runs nothing with it (`widened`). - fn fail_submission(&mut self, index: usize, at: usize, encoders: &Range, code: u64) { - if let Some(planned) = self - .checks - .as_mut() - .and_then(|checks| checks.planned.get_mut(at)) - { - planned.failed = true; - } - let encoders = self.widened(encoders); - // Encoded again after this, by the commit's split of a group or a rebind, they still - // run nothing (`reencode.rs`). - self.unrunnable.extend(encoders.clone()); - let from = self.batch_range(index).start; - let State { - recorded, - retained, - ended, - .. - } = self; - for part in recorded[from..] - .iter_mut() - .filter(|part| encoders.contains(&part.encoder)) - { - State::fail_part(part, ended, retained); - } - if self.failure.is_none() { - self.failure = Some(CommandBufferError::Injected(code)); - } - } - - /// `encoders`, Metal's submission a check failed, with every submission whose commands the - /// shared `VkCommandBuffer` of a group one of its encoders' commands lie in holds - /// (`State::in_tail`): that `VkCommandBuffer` runs whole or not at all, and each such - /// submission whole, so no unit of command predication runs in part. - fn widened(&self, encoders: &Range) -> Range { - let mut groups: Vec> = - (self.ended.get(encoders.clone()).into_iter().flatten()) - .filter_map(|record| record.group.clone()) - .collect(); - groups.dedup(); - let tail: Vec = (groups.into_iter()) - .map(|group| self.in_tail(group)) - .filter(|tail| tail.iter().any(|encoder| encoders.contains(encoder))) - .flatten() - .collect(); - if tail.iter().all(|encoder| encoders.contains(encoder)) { - return encoders.clone(); - } - (self.metal_submissions().into_iter()) - .map(|(_, submission)| submission) - .filter(|submission| tail.iter().any(|encoder| submission.contains(encoder))) - .fold(encoders.clone(), |failed, submission| { - failed.start.min(submission.start)..failed.end.max(submission.end) - }) - } - - /// Its first batch's submission, batch `index`, found a hang of its queue in flight - /// (`hang.rs`): from that batch on every encoder runs nothing, and it completes with no - /// error, its event signals firing, as one committed during the hang with no event wait - /// does. No check of the program's runs for it. - fn discard_behind_hang(&mut self, index: usize) { - if let Some(checks) = &mut self.checks { - for planned in &mut checks.planned { - planned.checked = true; - planned.failed = true; - } - } - let from = self.batch_range(index).start; - let State { - recorded, - retained, - ended, - .. - } = self; - for part in &mut recorded[from..] { - State::fail_part(part, ended, retained); - } - } - - /// Whether the check of Metal's submission of `encoders` failed it. - pub(super) fn check_failed(&self, encoders: &Range) -> bool { - self.checks.as_ref().is_some_and(|checks| { - checks - .planned - .iter() - .any(|planned| planned.failed && planned.encoders == *encoders) - }) - } - - /// Batch `index`'s checks ran. - fn checked(&mut self, index: usize) { - if let Some(checks) = &mut self.checks { - checks.batches = checks.batches.max(index + 1); - } - } -} - -impl CommandBuffer { - /// Check each submission of the command buffer, as Metal splits it, with `check` just before - /// the runtime submits it (the module docs of `command_buffer/checks.rs`, docs/API.md "A - /// submission checked as it is submitted"): a runtime extension, no Metal call. Metal fails a - /// submission that uses a resource whose memory was taken away by the time it is submitted - /// (Apple's detach, measured by a consumer on an M3 Max, macOS 26.7): its encoders run - /// nothing, every other submission runs, the event signals fire, the handlers run, and the - /// command buffer completes with status `Error` and code 8. A check that answers a code - /// does that to its submission, and [`Submission::used_resources`] says what the submission - /// uses and reaches. Setting another check replaces it. The check runs on the device's - /// scheduler thread, or on the thread of a [`commit_and_submit`](Self::commit_and_submit) - /// that submits the submission ([`SubmissionCheck`]). - /// - /// Refused, changing nothing, once the command buffer is committed (`Invalid`, - /// `Problem::AlreadyCommitted`). - pub fn set_submission_check(&self, check: SubmissionCheck) -> Result<(), Error> { - let mut state = self.state(); - if state.enqueued() || state.committing { - return Err(invalid("set_submission_check", Problem::AlreadyCommitted)); - } - state.check = Some(check); - Ok(()) - } -} - -impl CommandBufferShared { - /// Whether batch `index` waits for its submission checks to run. - pub(crate) fn needs_check(&self, index: usize) -> bool { - let state = lock(&self.state); - state.step_failure.is_none() - && state - .checks - .as_ref() - .is_some_and(|checks| checks.batches <= index) - } - - /// The submission checks before batch `index` is submitted: on the scheduler's thread, or a - /// committing one that submits the batch next (`scheduler::claim_check`), without the - /// scheduler's lock or this command buffer's, inside a section of the exit guard, once the - /// batch is otherwise ready and its host step recorded. Each due check runs as the program's - /// code (`exit_guard::program`); a code it answers, or a panic, fails its submission. - pub(crate) fn run_checks(self: &Arc, index: usize) { - let due = { - let mut state = lock(&self.state); - // Committed with an event wait during a hang of its queue: applied once, here. - let behind_hang = state.behind_hang.take(); - if behind_hang.is_some_and(|verdict| verdict.discards(&self.queue)) { - state.discard_behind_hang(index); - state.checked(index); - return; - } - state.due(index) - }; - let Some((Some(check), due)) = due else { - if due.is_some() { - lock(&self.state).checked(index); - } - return; - }; - let buffer = CommandBuffer(Arc::clone(self)); - let mut failed = Vec::new(); - for (at, kind, encoders) in due { - let submission = Submission { - command_buffer: &buffer, - kind, - encoders, - }; - let mut verdict = NonZeroU64::new(PANICKED); - exit_guard::program(|| verdict = check(&submission)); - if let Some(code) = verdict { - failed.push((at, submission.encoders, code.get())); - } - } - let mut state = lock(&self.state); - for (at, encoders, code) in &failed { - state.fail_submission(index, *at, encoders, *code); - } - state.checked(index); - drop(state); - // Released without the lock: the check may hold a resource's last handle. - drop(check); - drop(buffer); - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs deleted file mode 100644 index bc4f498f5..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ /dev/null @@ -1,1874 +0,0 @@ -//! The device's completion: each submitted batch finishes once its queue's timeline reached the -//! batch's value, which one waiter thread per `VkQueue` watches, and the waiter that sees the -//! value reached finishes it ([`turns`]). -//! -//! - **In each queue's order.** A `VkQueue`'s batches signal its timeline with rising values, and -//! Vulkan's signal operation order makes them complete in that order, so each queue's batches -//! wait in one line, and a value reached finishes every batch up to it. -//! - **What a finished batch does.** Its queue's completed value is published for the tracker -//! (the host saw it before any later submission), the events it signaled are reached, and the -//! batch that ends a command buffer finishes it, once the turn read the command buffer's GPU -//! timestamps and gave their slot back (`gpu_time.rs`): the turn runs its transition to -//! `Completed` itself where that runs none of the program's code but its completion-seen -//! handlers (a runtime extension), else posts it to its queue's context -//! ([`contexts`](crate::contexts)). A turn runs no other handler. -//! - **Finished where seen.** Metal's completion wakes a thread waiting for a command buffer with -//! no completed handler from the thread that saw it complete, and orders it after its queue's -//! earlier completed handlers. Measured on the Apple M3 Max (macOS 27.0.1), 40 runs each: with -//! no handler, the status read `Completed` 91 to 137 us after `GPUEndTime` and -//! `waitUntilCompleted` returned 3 to 10 us after the status; with a completed handler of 20 ms, -//! the status read `Completed` before the handler began (within 10 us) and in it, and the wait -//! returned 10 to 23 us after it ended; a command buffer with no handler behind an earlier one of -//! its queue whose handler ran 20 ms read `Completed`, and its wait returned, 3 to 23 us after -//! that handler ended, 21 to 30 ms after its own `GPUEndTime`. So the turn runs a command -//! buffer's transition itself (`CommandBufferShared::finish_here`) where it has no completed -//! handler (none being added after the commit) and no notice, its queue's context runs on no -//! handler thread and holds only such transitions, which the turn runs first, in order, and the -//! runtime holds none of the program's objects a release drops or runs (`program_objects.rs`): -//! its status, release and gate then come from the waiter, which wakes the program's waiting -//! thread itself. Its completion-seen handlers (`CommandBuffer::add_completion_seen_handler`) -//! then run on the waiter too, once its status is final, for a program that answers the -//! completion where it is seen: one wake where a completed handler's is two (counted: -//! `WorkCounts::completion_seen_handlers_where_seen`). A command buffer with completed handlers -//! too, and no event signal at its end that another queue's command buffer may wait for, runs -//! there to its completion-seen handlers, and the rest, its completed handlers on, is posted -//! to its queue's context, which the waiter runs meanwhile, so the queue's later transitions -//! follow it (`Transition::seen_first`). Everywhere else it is posted, as before, and they run -//! in it on the handler thread. Beside the -//! runtime lane's tests on the M3 Max at the utility clamp, the handler thread's wake between -//! the turn and the program's thread took up to 13 to 55 ms at a light burst's 99th percentile -//! of the queue storm (`runtime_lane::queue_storms`), over Metal's one wake from its completion; -//! counted (`WorkCounts::completed_where_seen`). -//! - **A command buffer finishes at its fence, where it has one.** Where the driver still reads a -//! command buffer's query pools after the value (MoltenVK), the batch that ends it also signals -//! a fence ([`fences`](super::fences)), which the driver signals after those reads: the turn -//! posts the transition, after which what the command buffer used is released, only once the -//! fence is signaled too, and then resets the fence and gives it back. A wait for fences holds -//! up the other queues' batches by as long. Elsewhere Vulkan's value is enough, and the batch -//! has no fence. On MoltenVK every command buffer takes one, not only the ones whose query pools -//! that driver reads late: a relayed queue's failure attribution needs one for every batch, and -//! the host sees the fence sooner than the value there anyway (`fences.rs`, which holds the -//! argument, the reading of MoltenVK's completed handlers and the measurement). -//! - **One waiter per `VkQueue`, each waiting for one object** (replacing the wait for any of the -//! timelines). Each `VkQueue`'s waiter thread waits for its queue's first pending batch past the -//! value it saw reached: for the batch's fence where it has one, else for its queue's timeline to -//! reach the batch's value, a wait of that one fence or that one semaphore (`poll`). Then it -//! reads the timeline and publishes it; a signaled fence's batch reached its value whatever the -//! read shows (lavapipe can show it later). A batch -//! submitted to an idle `VkQueue` is waited for by that queue's own waiter, so it completes when -//! its work does, not when another queue's does. No wait names several objects: MoltenVK 1.4.1's -//! wait for any of several timelines (`vkWaitSemaphores` with `VK_SEMAPHORE_WAIT_ANY_BIT`, -//! `mvkWaitSemaphores`) loses a signal that lands while it is still registering a later timeline -//! (`RuntimeDriverDefect::WaitForAnyObjectLosesASignal`, `driver_defects.rs`), -//! so the waiter saw the batch only when its 100 ms wait ran out (the consumer's guest presented -//! at about a quarter of Metal's rate); its wait for any of several fences has the same flaw. A -//! wait for one timeline or one fence counts its one signal under a lock, and loses none. The -//! value is read again after every wait, so the waiter relies on no wake for the value, only for -//! its timing. Counted by which object the wait named (`WorkCounts::fence_waits`, -//! `WorkCounts::timeline_waits`), and by whether the batch was watched while this waiter was -//! parked, so the wait for it began only after a notify and a thread wake -//! (`WorkCounts::completion_arms` and `WorkCounts::completion_arms_after_a_wake`); a read that -//! ran past the wait's value, and so costs one wait more, by -//! `WorkCounts::completion_reads_ran_ahead`. -//! - **Finished by the waiter that saw it, one turn at a time** ([`turns`]). A waiter whose wait -//! returned with its queue's value reached, or with a failure, makes the turn itself where none -//! is under way: it takes every queue's batches their waiters saw reached (or the failure) and -//! finishes them, and looks again until a look finds none. One turn runs at a time on the device: -//! a waiter that finds one under way leaves what it saw to it, under the lock that turn's last -//! look takes, so nothing is left behind. So a turn keeps every ordering across the queues: -//! events reached before the scheduler is woken, fences settled before the transitions, each -//! queue's batches in value order, and the failure drain over every queue, whose errors so never -//! pass a queue's earlier completions (Metal runs a queue's completed handlers in commit order). -//! No thread is woken between a batch's wait and its transition's run or post: on an Apple M3 Max (macOS -//! 27.0.1, MoltenVK 1.4.1) beside 24 processes spinning at the utility clamp, a separate thread -//! that the waiters woke for their batches took them 8.8 to 15.1 ms after the wake in 4 runs of 6 -//! (22 us at the median), and since a turn finishes every queue's batches, each such wait put -//! every light queue's burst of the queue storm (`runtime_lane::queue_storms`) into its tail. -//! While its waiter makes a turn, a queue's next batch waits for that turn to end before its wait -//! begins; its fence and value stay signaled meanwhile. -//! - **After what it waited for.** Metal's completion follows the GPU's: a command buffer whose -//! work waited, through an event, for another queue's GPU signal completes after the command -//! buffer that signalled, its status, completion-seen handlers and completed handlers too. Here -//! each `VkQueue`'s waiter sees its own batches, and the waiter of a batch that waited may see it -//! before the signaller's waiter sees the signaller (a read of the event's counter let the -//! waiting batch go before the signaller's turn, and its waiter woke first); a turn takes the -//! queues in index order; and two queues' transitions run on two of the handler threads. So a -//! batch records, as it is submitted, the batches of other `VkQueue`s whose kept signals its -//! event waits were met by and whose completion turns had not run then -//! (`EventTimeline::signallers`, [`Submitted::after`]), and a take leaves it, with its queue's -//! later batches, until those are taken, by the same take or a later one ([`reached`]): no waiter -//! makes a turn for it meanwhile ([`front_due`]). Its command buffer's transition to `Completed` -//! then waits for the signallers' transitions to reach their completed handlers, where those lead -//! their contexts (`follow.rs`). A batch that waits for no other queue's costs an empty list, and -//! a take looks at the queues again only while a reached batch waits for another queue's. -//! - **No GPU work: finished where it is taken** ([`Completion::watch_unsubmitted`]). A command -//! buffer that needs no GPU work is taken with no submission (`submit.rs`) and watched at its -//! `VkQueue`'s last submitted value, behind its queue's earlier batches: it finishes in the turn -//! that finishes the batch before it, by the waiter that saw that one complete. Where its queue -//! reached that value already and no turn is under way, no waiter is woken for it: the thread -//! that took it makes the turn itself once it holds no lock ([`Completion::turn_owed`]), the -//! scheduler's, a committing thread's or a thread about to block for a command buffer, which -//! runs only plain transitions (`CommandBufferShared::finish_here`), and makes it before it -//! runs a submission handler or check: one that waited for that completion would otherwise -//! wait for its own return. A turn takes every queue's batches seen -//! reached, so the one turn at a time on the device keeps every order above. Counted: -//! `WorkCounts::completion_turns_where_taken`. -//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes once -//! the batch completed: its last command buffer makes them available to the host -//! (`Barrier::to_host`, or `Barrier::to_all`), before its signal in submission order, and the -//! host's reads come after a host wait for that signal. Vulkan orders host operations after a -//! signal only through a wait: "signal operations happening before host operations that wait on -//! them" system-synchronize-with them (the memory model), and a fence's "execution dependency is -//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by polling -//! on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its value -//! "may immediately be out of date"). So a value the read shows past the one a wait returned for -//! (later batches that completed meanwhile, or the front's after a wait that ran out) is waited -//! for in turn, a wait that returns at once ("If the condition is satisfied when -//! `vkWaitSemaphores` is called, then `vkWaitSemaphores` returns immediately"), before it is -//! published: one call more, and only where the read ran ahead. -//! - **Waits on the GPU are bounded.** A waiter waits for its fence or value at most -//! [`WAIT_SLICE`] at a time, so a lost device is reported by the next wait. A wait that ran out -//! its slice although its fence or value was signaled when the waiter looked again is a wake it -//! missed (or a signal in the slice's last moment), counted -//! (`WorkCounts::missed_completion_wakes`), which the completion test holds to none. -//! - **An idle waiter sleeps until it is woken** ([`wait`]). Parked with no batch of its queue -//! pending, a waiter sleeps on its condition variable with no timeout: every change it waits for -//! notifies it where it sleeps (below), so an idle device's waiters do not wake at all. Parked -//! with a batch pending (left to a turn under way, held by a drain, or a failure pending), it -//! still wakes at least every slice. Counted: `WorkCounts::completion_waiter_parks` and -//! `WorkCounts::completion_waiter_parks_timed_out`, which the idle test holds to none. The -//! changes a parked waiter waits for, each made under `pending`'s lock and each notifying it -//! where `Pending::parked` says it sleeps, or every waiter: a batch watched on its queue -//! ([`Completion::watch`], [`Completion::watch_unsubmitted`] where it owes no turn), a turn's -//! take of its queue's batches that leaves it one to arm for or finds the waiters stopping -//! ([`turns`]), the pending batches given back after a failure ([`take_pending`], every -//! waiter), a stop ([`Completion::stop`], every waiter) and an exit (`exit`, and a waiter that -//! found the process exiting, every waiter). A failure a waiter's wait saw, and a batch owed to -//! the thread that took it, leave the waiters asleep: the turn that finishes them is made by -//! that waiter or that thread, or by the turn under way, and ends in a take (or, for a failure, -//! [`take_pending`]'s wake of every waiter). -//! - **Exit.** Each wait is a section of the exit guard ([`exit_guard`]), so an exit waits at most -//! one slice for it; once the process is exiting, the waiters end. -//! - **A drain waits for the waiters.** A failed wait or read finishes every pending batch, which -//! may destroy their fences (`let_go`); the batches are taken only once no waiter is waiting, -//! and none arms until they are. -//! - **Let go before the waiters return.** A turn holds a command buffer through a [`Hold`], -//! and lets go of everything it holds for a batch (its events, then the command buffer, or -//! hands the hold to the transition it posts) before the next; the command buffer's waiters -//! return once no hold is left ([`gate`](super::gate)). It reaches the device through a pending -//! command buffer only for the wait, and for a failed wait's drain. -//! - **A failed wait drains the queues first**. Its command buffers finish with its error, and let -//! go of what they used, once the device's queues were drained (`Device::drain_queues`): MoltenVK -//! 1.4.1 reports a lost device from the first completed handler of a failed Metal command buffer, -//! while later ones still read the command buffers' pools. -//! - **No self-join.** A turn's drop of a command buffer's last reference can drop the device's -//! last handle on its waiter; stopping from a waiter then joins the others and only asks it to -//! end. -//! - **Woken only where one sleeps, and only the one a change is for.** Each waiter sleeps on a -//! condition variable of its own, and a drain ([`take_pending`]) on another. A change wakes only -//! the sleepers it is for: a batch watched, its queue's waiter; a turn that took a queue's -//! batches, that queue's waiter (its next batch may arm); a wait that ended, a drain waiting for -//! it; the pending batches given back after a failure, a stop or an exit, every one. Each where -//! it sleeps (`Pending::parked`, `Pending::draining`), read under the lock the change is made -//! under: one that sleeps later looks at the change first. A batch watched while its waiter is -//! in its queue's wait, or a turn's look, so costs no system call (a notify is one, sleeper or -//! not), and the waiters of the device's idle `VkQueue`s sleep through the other queues' -//! batches. Counted: `WorkCounts::wakes_completion_waiters`, `WorkCounts::wakes_spared`. - -use super::gate::Hold; -use super::CommandBufferShared; -use crate::copied::CopiesReached; -use crate::device::line::Culprit; -use crate::device::lock; -use crate::error::{CommandBufferError, Error, MemoryKind, VkResultCode}; -use crate::event::EventShared; -use crate::exit_guard::{self, Call}; -use crate::gpu_time; -use crate::rebind::SubmittedHolds; -use crate::release; -use crate::Device; -use ash::vk; -use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; -use std::thread::JoinHandle; -use std::time::{Duration, Instant}; - -/// How long one wait on the timelines lasts. -const WAIT_SLICE: Duration = Duration::from_millis(100); - -/// One device's `VkQueue`s' waiters, which finish its batches. -pub(crate) struct Completion { - watch: Arc, - threads: Mutex>>, -} - -/// What the waiters and the scheduler share. -struct Watch { - pending: Mutex, - /// Per `VkQueue`: its waiter's condition variable, notified where it sleeps on it on a change - /// it waits for (the module docs): a batch watched on its queue, its queue's batches taken by - /// a turn, the pending batches given back after a failure, a stop, an exit. - wakes: Box<[Condvar]>, - /// A drain's ([`take_pending`]), notified where one sleeps on it as a waiter's wait ends, and - /// on a stop or an exit. - drained: Condvar, - /// The notifies made, and those spared as no waiter slept (`WorkCounts`). - woke: AtomicU64, - spared: AtomicU64, - /// A batch watched with no submission ([`Completion::watch_unsubmitted`]) found its queue's - /// value reached and no turn under way, and woke no waiter: the thread that took it makes the - /// turn ([`Completion::turn_owed`]). Set under `pending`'s lock. - owed: AtomicBool, - /// The fence lists of the turns [`Completion::turn_owed`] makes, kept with their room: one - /// turn at a time runs on the device (`turning`), so one thread at a time takes them. - lists: Mutex, - /// The turns made so ([`Completion::turn_owed`], `WorkCounts::completion_turns_where_taken`). - turns_where_taken: AtomicU64, - /// The waiters' sleeps on their condition variables, and those of them that ended at their - /// slice ([`wait`], `WorkCounts`). - parks: AtomicU64, - parks_timed_out: AtomicU64, -} - -impl Watch { - /// Notify `wake` where `asleep` (read under the lock the change was made under) says a thread - /// sleeps on it, counted either way. - fn notify(&self, wake: &Condvar, asleep: bool) { - if asleep { - self.woke.fetch_add(1, Ordering::Relaxed); - wake.notify_all(); - } else { - self.spared.fetch_add(1, Ordering::Relaxed); - } - } - - /// Wake every waiter and drain, wherever they sleep: the pending batches were given back after - /// a failure, or the waiters stop or end. - fn wake_all(&self) { - self.woke.fetch_add(1, Ordering::Relaxed); - for wake in &self.wakes { - wake.notify_all(); - } - self.drained.notify_all(); - } -} - -struct Pending { - /// Per `VkQueue`: the submitted batches not yet finished, in value order. - queues: Vec>, - /// Per `VkQueue`: the largest value its waiter saw its timeline reach. - reached: Vec, - /// Per `VkQueue`: the value of the last batch a turn (or a drain) took from it; every batch - /// up to it is taken. - taken: Vec, - /// Per `VkQueue`: its waiter is in a wait. - waiting: Vec, - /// A waiter's failed wait or read, which every pending batch finishes with. - failed: Option, - /// A failure of the device's loss, which its line recovers from, named the loss's hang - /// ([`fail`]): every later failure's command buffers are that hang's victims. - hung: bool, - /// The pending batches are being taken (`take_pending`): no waiter arms. - holding: bool, - /// A waiter makes a turn ([`turns`]): another leaves what it saw to that turn. - turning: bool, - /// The process is exiting: every waiter ends, and what is pending stays pending. - exiting: bool, - stopping: bool, - /// Per `VkQueue`: its waiter sleeps on its condition variable ([`wait`]). - parked: Vec, - /// The drains sleeping until no waiter is in a wait ([`take_pending`]). - draining: usize, - /// How long no queue's work advanced while some was pending, and each queue's front without - /// its timeline advancing (`stall.rs`). - stall: super::stall::Clock, - /// The `VkQueue` whose front batch went past the watchdog's bound (`stall.rs`): the loss's - /// hang is its command buffer, exactly (`recovery::recovered`). - timed_out: Option, - /// Per `VkQueue`: what the last batch a turn took held, as the encoder trail names it, and - /// when it was taken, where the device's trail is on (`encoder_trail.rs`). - trails: Vec, Instant)>>, -} - -/// A submitted batch its queue's waiter waits for. -pub(crate) struct Submitted { - /// The value its queue's timeline reaches once it completed. - pub(crate) value: u64, - pub(crate) buffer: Hold, - /// It ends its command buffer: finishing it completes the command buffer. - pub(crate) last: bool, - /// The fence its submission signals after the work, when it ends its command buffer where - /// the driver needs one, or its queue's failures are relayed: the command buffer finishes - /// once it is signaled ([`fences`](super::fences)). - pub(crate) fence: Option, - /// The events it signals, with their signal indices. - pub(crate) signals: Vec<(Arc, u64)>, - /// The holds of what its event group's commands took that its completion lets go - /// (`State::holds_until`): at once, or, where it ends its command buffer, as that command - /// buffer's completion is processed, before its completed handlers run - /// (`State::keep_holds`, `CommandBufferShared::complete`). - pub(crate) holds: Vec, - /// The batches of other `VkQueue`s it finishes after: those whose GPU signals its event waits - /// were met by, not finished as it was submitted (the module docs, "After what it waited - /// for"). Empty for most. - pub(crate) after: Vec, - /// A take left it for one of those ([`reached`]): counted once. - pub(crate) held: bool, - /// What its encoders were, as the encoder trail names them, where the device's trail is on - /// (`encoder_trail.rs`). - pub(crate) trail: Option, -} - -/// A batch of another `VkQueue` that a batch waited for and finishes after -/// ([`Submitted::after`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Waited { - /// Its `VkQueue`. - pub(crate) queue: usize, - /// Its value on that queue's timeline. - pub(crate) value: u64, -} - -impl Waited { - /// Whether a turn took it: every batch of its queue up to it is taken. - fn taken(&self, taken: &[u64]) -> bool { - taken[self.queue] >= self.value - } -} - -impl Completion { - /// Start the waiters of a device with `queues` `VkQueue`s, one per `VkQueue`; refused when the - /// host cannot start one. - pub(crate) fn start(queues: usize) -> Result { - let watch = Arc::new(Watch { - pending: Mutex::new(Pending { - queues: (0..queues).map(|_| VecDeque::new()).collect(), - reached: vec![0; queues], - taken: vec![0; queues], - waiting: vec![false; queues], - failed: None, - hung: false, - holding: false, - turning: false, - exiting: false, - stopping: false, - parked: vec![false; queues], - draining: 0, - stall: super::stall::Clock::new(queues), - timed_out: None, - trails: vec![None; queues], - }), - wakes: (0..queues).map(|_| Condvar::new()).collect(), - drained: Condvar::new(), - woke: AtomicU64::new(0), - spared: AtomicU64::new(0), - owed: AtomicBool::new(false), - lists: Mutex::new(FenceLists::default()), - turns_where_taken: AtomicU64::new(0), - parks: AtomicU64::new(0), - parks_timed_out: AtomicU64::new(0), - }); - let completion = Completion { - watch: Arc::clone(&watch), - threads: Mutex::new(Vec::new()), - }; - let spawned: std::io::Result<()> = (|| { - for queue in 0..queues { - let watch = Arc::clone(&watch); - let waiter = exit_guard::spawn_user_interactive( - std::thread::Builder::new().name(format!("metal2vulkan-queue-wait-{queue}")), - move || wait_for_queue(&watch, queue), - )?; - lock(&completion.threads).push(waiter); - } - Ok(()) - })(); - match spawned { - Ok(()) => Ok(completion), - Err(_) => { - completion.stop(); - Err(Error::OutOfMemory(MemoryKind::Host)) - } - } - } - - /// The last batch `VkQueue` `queue` completed of those the encoder trail named, and how long - /// before (`encoder_trail.rs`). - pub(crate) fn trail_last(&self, queue: usize) -> Option<(Arc, Duration)> { - let pending = lock(&self.watch.pending); - let (trail, at) = pending.trails.get(queue)?.as_ref()?; - Some((Arc::clone(trail), at.elapsed())) - } - - /// Wait for `batch`, just submitted to `VkQueue` `queue` (or a failed command buffer's end, - /// at the queue's last submitted value). - pub(crate) fn watch(&self, queue: usize, batch: Submitted) { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::record(|| trace::Traced::Watched { - queue, - value: batch.value, - at: gpu_time::host_nanos(), - }); - let parked = { - let mut pending = lock(&self.watch.pending); - let lost = failed_with_loss(&mut pending, &batch); - pending.queues[queue].push_back(batch); - (!lost).then_some(pending.parked[queue]) - }; - match parked { - Some(parked) => self.watch.notify(&self.watch.wakes[queue], parked), - None => self.watch.wake_all(), - } - } - - /// Wait for `batch`, of a command buffer that needs no GPU work, taken with no submission and - /// watched at the last value submitted to `VkQueue` `queue` (`submit.rs`), with no fence: as - /// [`watch`](Self::watch), but where its queue reached that value already, no failure is - /// pending and no turn is under way, no waiter is woken, and the turn that finishes it is owed - /// to the caller, which makes it once it holds no lock ([`turn_owed`](Self::turn_owed)). A - /// turn under way takes it at its next look, which takes this lock. - pub(crate) fn watch_unsubmitted(&self, queue: usize, batch: Submitted) { - debug_assert!( - batch.fence.is_none(), - "a batch with no submission has no fence" - ); - let parked = { - let mut pending = lock(&self.watch.pending); - let lost = failed_with_loss(&mut pending, &batch); - pending.queues[queue].push_back(batch); - if lost { - drop(pending); - self.watch.wake_all(); - return; - } - let owed = !pending.turning - && !pending.holding - && !pending.exiting - && pending.failed.is_none() - && front_due(&pending, queue); - if owed { - self.watch.owed.store(true, Ordering::SeqCst); - drop(pending); - self.watch.spared.fetch_add(1, Ordering::Relaxed); - return; - } - pending.parked[queue] - }; - self.watch.notify(&self.watch.wakes[queue], parked); - } - - /// Make the turn a batch watched with no submission left to this thread - /// ([`watch_unsubmitted`](Self::watch_unsubmitted)), where one is owed, no turn is under way - /// and a queue's batches are still seen reached: one look at a flag where none is owed. The - /// caller holds no lock of the runtime's: the turn finishes command buffers, takes the - /// scheduler's lock to wake it, and may run their transitions here - /// (`CommandBufferShared::finish_here`). - pub(crate) fn turn_owed(&self) { - let watch = &*self.watch; - if !watch.owed.swap(false, Ordering::SeqCst) { - return; - } - { - let mut pending = lock(&watch.pending); - let reached = (0..pending.queues.len()).any(|queue| front_due(&pending, queue)); - if pending.turning || pending.exiting || !reached { - return; - } - pending.turning = true; - } - watch.turns_where_taken.fetch_add(1, Ordering::Relaxed); - let mut lists = lock(&watch.lists); - turns(watch, &mut lists); - } - - /// The turns made by the thread that took a command buffer needing no GPU work - /// ([`turn_owed`](Self::turn_owed)). - pub(crate) fn turns_where_taken(&self) -> u64 { - self.watch.turns_where_taken.load(Ordering::Relaxed) - } - - /// The waiters' sleeps on their condition variables, and those that ended at their slice - /// ([`wait`]). - pub(crate) fn parks(&self) -> (u64, u64) { - ( - self.watch.parks.load(Ordering::Relaxed), - self.watch.parks_timed_out.load(Ordering::Relaxed), - ) - } - - /// The notifies made to the waiters, and those spared as none slept. - pub(crate) fn wakes(&self) -> (u64, u64) { - ( - self.watch.woke.load(Ordering::Relaxed), - self.watch.spared.load(Ordering::Relaxed), - ) - } - - /// Every pending batch fails as on a lost device, the oldest incomplete one as the hang and - /// the rest as its victims ([`fail`]), at the next turn, where no failure is pending already: - /// a recovery's first step (`device/line.rs`), whose device a waiter's failed wait may not - /// have found lost (the test hook's, `Device::recover_for_test`). - pub(crate) fn fail_in_flight(&self) { - lock(&self.watch.pending) - .failed - .get_or_insert(CommandBufferError::DeviceLost); - self.watch.wake_all(); - } - - /// Whether nothing is pending, no failure waits for its turn and no turn is under way: a - /// recovery's wait for its lost device's command buffers to fail (`device/line.rs`). - pub(crate) fn settled(&self) -> bool { - let pending = lock(&self.watch.pending); - pending.failed.is_none() - && !pending.turning - && !pending.holding - && pending.queues.iter().all(VecDeque::is_empty) - } - - /// Ask the waiters to end once nothing is pending, and wait for each but this one (the - /// device's last handle can drop on one of them, in its turn). - pub(crate) fn stop(&self) { - lock(&self.watch.pending).stopping = true; - self.watch.wake_all(); - let threads: Vec> = lock(&self.threads).drain(..).collect(); - for handle in threads { - if !crate::this_thread::runs(&handle) { - let _ = handle.join(); - } - } - } -} - -/// What a turn's look found: batches whose values their queues reached, or a waiter's failure. -enum Turn { - Finished(Vec<(usize, Submitted)>), - Failed(CommandBufferError), -} - -/// Wait on `queue`'s waiter's condition variable, counted as parked meanwhile: until it is woken -/// where its queue holds no pending batch, else up to one slice (the module docs). -fn wait<'a>( - watch: &'a Watch, - mut pending: std::sync::MutexGuard<'a, Pending>, - queue: usize, -) -> std::sync::MutexGuard<'a, Pending> { - pending.parked[queue] = true; - watch.parks.fetch_add(1, Ordering::Relaxed); - let wake = &watch.wakes[queue]; - let mut pending = match pending.queues[queue].is_empty() || unbounded_parks() { - true => wake - .wait(pending) - .unwrap_or_else(std::sync::PoisonError::into_inner), - false => { - let (pending, waited) = wake - .wait_timeout(pending, WAIT_SLICE) - .unwrap_or_else(std::sync::PoisonError::into_inner); - if waited.timed_out() { - watch.parks_timed_out.fetch_add(1, Ordering::Relaxed); - } - pending - } - }; - pending.parked[queue] = false; - pending -} - -/// Whether every waiter's park waits until it is woken, a batch of its queue pending or not: -/// set by a test, so a change that wakes no parked waiter it should hangs the test instead of -/// waiting out a slice (`tests::completion_wakes`). Never set outside tests. -#[cfg(test)] -static UNBOUNDED_PARKS: AtomicBool = AtomicBool::new(false); - -#[cfg(test)] -fn unbounded_parks() -> bool { - UNBOUNDED_PARKS.load(Ordering::SeqCst) -} - -#[cfg(not(test))] -fn unbounded_parks() -> bool { - false -} - -/// Make every waiter's park of this process wait until it is woken (`unbounded_parks`). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn park_unbounded() { - UNBOUNDED_PARKS.store(true, Ordering::SeqCst); -} - -/// The process is exiting: every waiter ends. -fn exit(watch: &Watch) { - lock(&watch.pending).exiting = true; - watch.wake_all(); -} - -/// Turns, made by the waiter that called this once it set `turning`, or by the thread a batch with -/// no submission left one to ([`Completion::turn_owed`]) (the module docs): each looks -/// for the batches the queues' waiters saw reached, or a waiter's failure, and finishes them -/// ([`finish`]), or finishes every pending batch with the failure ([`fail`]); until a look finds -/// nothing, which clears `turning` under the lock it took: a waiter that saw a value reached while -/// `turning` was set left it to that look. `lists` is the caller's own, kept from turn to turn: a -/// turn fills them again within the room the earlier ones left, so in a steady state it allocates -/// none. False once the process is exiting. -fn turns(watch: &Watch, lists: &mut FenceLists) -> bool { - loop { - let turn = { - let mut pending = lock(&watch.pending); - if pending.exiting { - return false; - } - lists.woken.clear(); - if let Some(error) = pending.failed.take() { - // No waiter arms until the pending batches are taken (`fail`). - pending.holding = true; - Turn::Failed(error) - } else { - let finished = reached(&mut pending); - if finished.is_empty() { - pending.turning = false; - return true; - } - // The last batch of each queue taken, as the encoder trail names it. - for (queue, batch) in &finished { - if let Some(trail) = &batch.trail { - pending.trails[*queue] = Some((Arc::clone(trail.text()), Instant::now())); - } - } - // The waiters of the queues whose batches it took, where they sleep and their - // queue still holds a batch to arm for, or they stop: one whose queue it emptied - // has nothing to do, and the next batch watched wakes it. - for (queue, _) in &finished { - if !lists.woken.contains(queue) { - lists.woken.push(*queue); - } - } - let stopping = pending.stopping; - lists.woken.retain(|&queue| { - pending.parked[queue] && (stopping || !pending.queues[queue].is_empty()) - }); - Turn::Finished(finished) - } - }; - // A waiter whose front finished may arm for its queue's next. - if lists.woken.is_empty() { - watch.spared.fetch_add(1, Ordering::Relaxed); - } - for &queue in &lists.woken { - watch.notify(&watch.wakes[queue], true); - } - match turn { - Turn::Finished(finished) => { - if !finish(watch, lists, finished) { - return false; - } - } - Turn::Failed(error) => fail(watch, Vec::new(), error), - } - } -} - -/// Finish `finished`, the batches a turn took, each queue's in its value order: their events -/// reached, the scheduler told, their fences settled, then, for each that ends its command buffer, -/// its timestamps read and its GPU times placed, and its transition posted. False once the -/// process is exiting. -fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submitted)>) -> bool { - // The host time the batches were seen complete: an uncalibrated command buffer's GPU end - // (`gpu_time.rs`). - let seen = gpu_time::host_nanos(); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - for (queue, batch) in finished.iter().filter(|(_, batch)| batch.last) { - trace::record(|| trace::Traced::Finished { - queue: *queue, - value: batch.value, - seen, - }); - } - // The device, held while the batches finish (each holds it meanwhile). - let Some(device) = finished - .first() - .map(|(_, batch)| batch.buffer.device().clone()) - else { - return true; - }; - // The copies out of two-copy buffers into pages no import maps land in the pages, and pages - // that drop the GPU's writes are copied in again, before anything sees the command buffers - // their batches end complete (`managed_copy.rs`). - for (_, batch) in finished.iter().filter(|(_, batch)| batch.last) { - let buffer = &batch.buffer; - buffer.run_at_completion(buffer.relayed.failure().is_none()); - } - // The GPU's writes into copied host buffers go back to the caller's pages before anything - // sees the batches complete: their event signals, the scheduler, a waiter, their completed - // handlers (`copied.rs`). Only the copies the batches' command buffers may have written are - // compared. - let copied = &device.shared().copied; - if copied.any() { - let mut written = CopiesReached::default(); - for (_, batch) in &finished { - let buffer = &batch.buffer; - if buffer.unnoted.load(Ordering::Relaxed) || lock(&buffer.state).writes_unnamed { - written = CopiesReached::all(); - break; - } - lock(&buffer.dirty).copies_written(&mut written); - } - copied.merge_back(&device.shared().counts, &written); - } - // So do their command buffers' shadows' copies back and merges and writes into logged host - // pages imported in place, to the pages' logs, again now they ran (`dirty_pages.rs`, - // `DirtyShadows::ran`): once a command buffer, at the batch that ends it, and at one before - // it that signals an event, which a copy may follow before the command buffer ends. A batch - // before it that signals nothing tells nothing outside the command buffer that its work ran. - let dirty = &device.shared().dirty; - if dirty.collects() { - for (_, batch) in &finished { - if batch.last || !batch.signals.is_empty() { - dirty.ran(&mut lock(&batch.buffer.dirty), batch.last); - } - } - } - // The holds of the batches that end no command buffer go first, their work completed: a - // detach that sees one of their signals detaches what only they held (`detach.rs`). - for (_, batch) in &mut finished { - if !batch.last { - batch.holds.clear(); - } - } - // Their event signals are seen before the scheduler looks again: a batch whose submission - // checks wait for a GPU signal to land may now go. - for (_, batch) in &finished { - for (event, index) in &batch.signals { - event.reached(*index); - } - } - // A batch held at its gate, or for a GPU signal to land, may now go (`scheduler`). - device.shared().scheduler.completions(&device); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::step("events reached"); - // Every finished batch's fence is waited for: where a queue's failures are relayed each - // batch has one (`device/relay.rs`), signaled after the driver reported its failure. - let mut ending = Vec::new(); - lists.gathered.clear(); - for (queue, batch) in finished { - let Submitted { - buffer, - last, - fence, - holds, - .. - } = batch; - lists.gathered.extend(fence.map(|fence| (queue, fence))); - if last { - let mut state = lock(&buffer.state); - state.times.completed = seen; - state.keep_holds(holds); - drop(state); - ending.push(buffer); - } - } - let settled = settle(&device, lists); - // A test's failed wait for the fences of work that completed, as a real loss fails it. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let settled = match trace::settle_fails(&ending) { - true => Settled::Failed(failure(&device, vk::Result::ERROR_DEVICE_LOST)), - false => settled, - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::step("fences settled"); - // Their GPU times' timestamps are read, and their slots given back, and their GPU times - // placed among their queues' in order, before their transitions are posted: a completed - // handler reads the times. A section, as each poll. - if let Settled::Signaled = settled { - let Some(_busy) = exit_guard::enter() else { - exit(watch); - return false; - }; - for buffer in &ending { - buffer.read_stamps(); - buffer.place_gpu_times(); - buffer.read_encoder_times(); - } - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::step("times placed"); - drop(device); - match settled { - Settled::Signaled => { - for buffer in ending { - CommandBufferShared::finish_here(buffer, Ok(())); - } - } - // What is pending stays pending, as Metal's does. - Settled::Exiting => { - exit(watch); - return false; - } - Settled::Failed(error) => fail(watch, ending, error), - } - true -} - -/// Every pending batch finishes with `error`: a wait or a read failed. The command buffers -/// `ending`, whose work completed (their queues' timelines passed them; their fences let go of -/// already), complete: only the wait for their fences, or the fences' reset, failed. The pending -/// batches' fences are let go of ([`let_go`]). -/// -/// First the device's queues are drained (`Device::drain_queues`): a finished command buffer lets -/// go of its pools as it finishes, and a driver may still read them after the failed wait returned -/// (MoltenVK 1.4.1, from its later completed handlers), until its own completion of the work ran. -/// -/// A lost device its line recovers (`device/line.rs`) answers as Metal's GPU recovery does -/// ([`Answers`]): the command buffer of the oldest incomplete batch fails as the hang -/// (`GpuHang`), counted against its queue (`revocation.rs`), and every other as its victim -/// (`GpuRecoveryVictim`), those of a later failure of the same loss too: a batch on its way to -/// the driver as the device was lost, watched once this failure took the pending ones -/// (`failed_with_loss`), or one the scheduler held and failed with the loss -/// (`scheduler::fail_lost`). The hang's command buffer is marked as the loss names it -/// ([`name_hang`]), so it fails as the hang whichever of these failures finishes it: its front -/// batch may be one of several, its last batch held or watched after. -fn fail(watch: &Watch, ending: Vec>, error: CommandBufferError) { - let failed = take_pending(watch); - let held = (ending.first().map(|buffer| buffer.device())) - .or_else(|| failed.first().map(|(_, batch)| batch.buffer.device())); - let mut answers = Answers::Error(error); - if let Some(device) = held { - // Their writes into copied host buffers are merged back by the next turn, which compares - // every copy (`copied.rs`). - device.shared().copied.owe(); - device.drain_queues(); - if error == CommandBufferError::DeviceLost && device.line().recovers() { - // One loss, one hang: a later failure of the lost device's batches answers victims - // alone, but for the hang's own command buffer. - let (hung, timed_out) = { - let pending = lock(&watch.pending); - (pending.hung, pending.timed_out) - }; - answers = Answers::Recovered; - if !hung && name_hang(device, &failed, timed_out) { - lock(&watch.pending).hung = true; - } - } - } - let failed = failed.into_iter().filter_map(|(queue, batch)| { - let Submitted { - buffer, - last, - fence, - holds, - signals, - .. - } = batch; - // No batch finishes after it any more (`EventShared::signaller`). - for (event, index) in &signals { - event.drained(*index); - } - if let Some(fence) = fence { - let_go(buffer.device(), queue, fence); - } - if last { - lock(&buffer.state).keep_holds(holds); - } - last.then_some(buffer) - }); - // Those whose work completed complete: their queues' timelines passed them, and only the - // wait for their fences or the fences' reset failed. Their GPU times as their work ran, where - // the device still reads them (else their completion's), placed before they finish, in their - // queues' order before the failed ones (`CommandBufferShared::place_gpu_times`). - if let Some(_busy) = (!ending.is_empty()).then(exit_guard::enter).flatten() { - for buffer in &ending { - buffer.read_stamps(); - buffer.place_gpu_times(); - buffer.read_encoder_times(); - } - } - for buffer in ending { - CommandBufferShared::post_finished(buffer, Ok(())); - } - for buffer in failed { - let error = answers.of(&buffer); - CommandBufferShared::post_finished(buffer, Err(error)); - } -} - -/// How the command buffers a failed wait finishes fail ([`fail`]). -enum Answers { - /// Each with the wait's error. - Error(CommandBufferError), - /// A lost device its line recovers: each as the recovery's victim, the hang's command buffer - /// as the hang (`CommandBufferShared::complete_seen`, the hang [`name_hang`] marked). - Recovered, -} - -impl Answers { - /// The error `buffer` fails with, the hang's own answered as it completes. - fn of(&self, buffer: &CommandBufferShared) -> CommandBufferError { - match self { - Answers::Error(error) => *error, - Answers::Recovered => { - // Counted for the recovery's notice (`device/line.rs`). - if !lock(&buffer.state).hang_of_loss { - buffer.device().line().victim(); - } - CommandBufferError::GpuRecoveryVictim - } - } - } -} - -/// Name the hang of a loss of `device` its line recovers from, `failed` the pending batches in -/// each queue's order; whether one was named. It is the command buffer of the front batch of -/// `timed_out`, the `VkQueue` whose front went past the watchdog's bound (`stall.rs`), exactly, -/// where one did; else of the oldest incomplete batch: on one `VkQueue` with work in flight, its -/// first pending batch, exactly (an in-order queue); on two or more, an inference, the first -/// pending batch of the queue whose command buffer was submitted first. The command buffer is -/// marked the loss's hang (`hang_of_loss`): it fails as the hang whichever of the loss's failures -/// finishes it, its front batch being any of its batches. Named on the device's line, for its -/// notice and the hold of its queue (`device/line.rs`). -fn name_hang(device: &Device, failed: &[(usize, Submitted)], timed_out: Option) -> bool { - // Each queue's first pending batch, of a command buffer that was submitted, with its queue. - let mut fronts: Vec<(usize, &Submitted)> = Vec::new(); - let mut queue = None; - for (at, batch) in failed { - if queue != Some(*at) && batch.buffer.kernel.start() > 0 { - queue = Some(*at); - fronts.push((*at, batch)); - } - } - let timed_out = timed_out.and_then(|timed| fronts.iter().find(|(at, _)| *at == timed)); - let culprit = timed_out - .or_else(|| { - fronts - .iter() - .min_by_key(|(_, batch)| batch.buffer.kernel.start()) - }) - .map(|(_, batch)| *batch); - let Some(culprit) = culprit else { - return false; - }; - let buffer = &culprit.buffer; - let queue = buffer.queue.label(); - let named = { - let mut state = lock(&buffer.state); - state.hang_of_loss = true; - state.named(queue.as_deref()) - }; - device.line().named(Culprit { - queue: Arc::downgrade(buffer.queue.common()), - named, - inferred: timed_out.is_none() && fronts.len() > 1, - victims: 0, - }); - true -} - -/// Let go of `fence` of `device`'s `VkQueue` `queue` after a failed wait: released once the -/// device is lost, when every submission counts as completed (out of the queue's submissions in -/// flight first, `device/relay.rs`); otherwise left to the device, since a submission that -/// signals it may still be pending. The release reaches the device's functions inside a section -/// of the exit guard, whether or not the caller is in one ([`fail`] is not: it posts the -/// command buffers' transitions, which a section may not), and once the process is exiting the -/// fence is left to its end. -fn let_go(device: &Device, queue: usize, fence: vk::Fence) { - if device.is_lost() { - let Some(_busy) = exit_guard::enter() else { - return; - }; - let shared = device.shared(); - if let Some(flights) = shared.flights(queue) { - flights.let_go(fence); - } - // SAFETY: the fence is the device's, and the device is lost. - unsafe { release::object(shared.vk(), fence) }; - } -} - -/// How the fences of the command buffers whose work completed ended. -enum Settled { - /// Each is signaled, reset and given back. - Signaled, - /// The process is exiting: the waiters end. - Exiting, - /// A wait or a reset failed: the command buffers finish with this error, and the fences are - /// let go of ([`let_go`]). - Failed(CommandBufferError), -} - -/// A turn's fences, and the waiters it wakes, in lists each waiter keeps from turn to turn -/// ([`turns`]). -#[derive(Default)] -struct FenceLists { - /// The queues whose batches a look took and whose waiters sleep, to wake. - woken: Vec, - /// The fences of the batches the turn finished, each with its `VkQueue`. - gathered: Vec<(usize, vk::Fence)>, - /// Those the turn waits for, then resets and gives back, the relayed queues' marks with them. - waited: Vec, - /// One relayed queue's of `gathered`. - queue: Vec, -} - -/// Wait for `lists.gathered`'s fences of `device` (each of a `VkQueue`) to be signaled, a slice at -/// a time, each wait a section of the exit guard; then reset them and give them back to the -/// device's idle fences, with the marks before them where the queue's failures are relayed -/// (`device/relay.rs`), which leave its submissions in flight first. `lists.waited` and -/// `lists.queue` are filled here. -fn settle(device: &Device, lists: &mut FenceLists) -> Settled { - let FenceLists { - gathered, - waited, - queue: ours, - .. - } = lists; - if gathered.is_empty() { - return Settled::Signaled; - } - waited.clear(); - waited.extend(gathered.iter().map(|&(_, fence)| fence)); - loop { - let Some(_busy) = exit_guard::enter() else { - return Settled::Exiting; - }; - let shared = device.shared(); - let raw = shared.vk(); - // SAFETY: the fences are the device's, each signaled by a submission made. - let signaled = unsafe { raw.wait_for_fences(waited, true, WAIT_SLICE.as_nanos() as u64) }; - exit_guard::called(Call::WaitForFences); - let error = match signaled { - Ok(()) => { - // Out of the queues' submissions in flight before they go back: every - // submission before a signaled fence's completed too. - for (queue, flights) in shared.relayed_queues() { - ours.clear(); - ours.extend( - (gathered.iter()) - .filter(|&&(q, _)| q == queue) - .map(|&(_, fence)| fence), - ); - flights.settled(ours, waited); - } - // SAFETY: each fence is signaled and its submission completed. - let reset = unsafe { raw.reset_fences(waited) }; - exit_guard::called(Call::ResetFences); - match reset { - Ok(()) => { - // SAFETY: each fence is unsignaled and in no pending submission; inside - // a section. - unsafe { shared.fences.give(raw, waited) }; - return Settled::Signaled; - } - Err(error) => error, - } - } - Err(vk::Result::TIMEOUT) => continue, - Err(error) => error, - }; - let failed = failure(device, error); - for &(queue, fence) in gathered.iter() { - let_go(device, queue, fence); - } - return Settled::Failed(failed); - } -} - -/// Each queue's batches whose values its waiter saw its timeline reach, taken from `pending`, in -/// each queue's order, each after the batches of other queues it finishes after -/// ([`Submitted::after`]): one waits, with its queue's later batches, until those are taken, by -/// this take or a later one (the module docs, "After what it waited for"). It looks at the queues -/// again only while a reached batch waits for another queue's and the last look took one, so a -/// take whose reached batches wait for no other queue's makes one look. -fn reached(pending: &mut Pending) -> Vec<(usize, Submitted)> { - let Pending { - queues, - reached, - taken, - .. - } = pending; - let mut finished = Vec::new(); - loop { - let mut took = false; - for (queue, batches) in queues.iter_mut().enumerate() { - while let Some(batch) = batches.front() { - let after = |waited: &Waited| waited.taken(taken); - if batch.value > reached[queue] || !batch.after.iter().all(after) { - break; - } - taken[queue] = taken[queue].max(batch.value); - finished.extend(batches.pop_front().map(|batch| (queue, batch))); - took = true; - } - } - // The reached batches left for other queues' batches they waited for, each counted once. - let mut waiting = false; - for (queue, batches) in queues.iter_mut().enumerate() { - let Some(batch) = batches.front_mut() else { - continue; - }; - if batch.value <= reached[queue] && !batch.after.is_empty() { - waiting = true; - if !batch.held { - batch.held = true; - (batch.buffer.device().shared().counts).batch_held_for_another_queue(); - } - } - } - if !took || !waiting { - return finished; - } - } -} - -/// Whether `batch`, watched under `pending`'s lock, is of a device lost already: it then fails with -/// the loss at the next turn ([`fail`]), as one taken by the loss's failure does, though its -/// submission went to the driver before the loss and its watch comes after that failure took the -/// pending batches. Its own wait need not fail: the test hook's lost `VkDevice` runs it -/// (`Device::recover_for_test`). Read under the lock, after the loss's failure was set under it -/// (`Device::mark_lost`, then `Completion::fail_in_flight`), so one of the two sees the other. -fn failed_with_loss(pending: &mut Pending, batch: &Submitted) -> bool { - let lost = batch.buffer.device().is_lost(); - if lost { - pending.failed.get_or_insert(CommandBufferError::DeviceLost); - } - lost -} - -/// Every pending batch, taken once no waiter is in a wait: a waiter may wait for a pending -/// batch's fence, which the caller may destroy (`let_go`). No waiter arms meanwhile. -fn take_pending(watch: &Watch) -> Vec<(usize, Submitted)> { - let mut pending = lock(&watch.pending); - pending.holding = true; - while pending.waiting.iter().any(|&waiting| waiting) { - pending.draining += 1; - pending = (watch.drained) - .wait_timeout(pending, WAIT_SLICE) - .unwrap_or_else(std::sync::PoisonError::into_inner) - .0; - pending.draining -= 1; - } - let Pending { queues, taken, .. } = &mut *pending; - for (queue, batches) in queues.iter().enumerate() { - if let Some(last) = batches.back() { - taken[queue] = taken[queue].max(last.value); - } - } - let taken = queues - .iter_mut() - .enumerate() - .flat_map(|(queue, batches)| batches.drain(..).map(move |batch| (queue, batch))) - .collect(); - pending.holding = false; - drop(pending); - watch.wake_all(); - taken -} - -/// A queue's first pending batch, as [`poll`] waits for it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Front { - /// The value its queue's timeline reaches once it completed. - value: u64, - /// The fence its submission signals, where it has one. - fence: Option, -} - -/// `VkQueue` `queue`'s waiter (the module docs): it waits for its queue's first pending batch -/// past the value it saw reached, a slice at a time, and makes the turn that finishes what its -/// queue reached, or a failure, where no turn is under way ([`turns`]); else it leaves them to the -/// turn under way. -fn wait_for_queue(watch: &Watch, queue: usize) { - exit_guard::serves_completion(); - // The fence lists of the turns it makes. - let mut lists = FenceLists::default(); - loop { - // Whether the look for a batch to wait for slept first: the batch was watched while this - // waiter was parked, so the wait for it began only after a notify and a thread wake, which - // sit between the submission and the wait (`WorkCounts::completion_arms_after_a_wake`). - let mut slept = false; - // The front to wait for, and the device, reached through it (held only for the wait); or - // none, for a turn: its queue holds batches it reached that no turn took yet (a failed - // command buffer's end, watched at a value its queue reached), or a waiter failed, and no - // turn is under way. - let armed = { - let mut pending = lock(&watch.pending); - loop { - if pending.exiting { - return; - } - if !pending.turning && due(&pending, queue) { - pending.turning = true; - break None; - } - let armable = !pending.holding && pending.failed.is_none(); - let armed = match pending.queues[queue].front() { - Some(batch) if armable && batch.value > pending.reached[queue] => { - let front = Front { - value: batch.value, - fence: batch.fence, - }; - Some((front, batch.buffer.device().clone())) - } - None if pending.stopping => return, - _ => None, - }; - if let Some(armed) = armed { - pending.waiting[queue] = true; - break Some(armed); - } - pending = wait(watch, pending, queue); - slept = true; - } - }; - let Some((front, device)) = armed else { - if !turns(watch, &mut lists) { - return; - } - continue; - }; - device.shared().counts.completion_armed(slept); - // The wait is a section of the exit guard; once the process is exiting the waiters end, - // and what is pending stays pending, as Metal's does. - let polled = match exit_guard::enter() { - Some(busy) => { - let polled = poll(&device, queue, front); - let polled = stalled(watch, &device, queue, front, polled); - drop(busy); - Some(polled) - } - None => None, - }; - // Let go of the device before the report: until then the front is pending (nothing - // finishes or takes it while this waits), and holds the device, so this is never its - // last handle, which goes on the program's or the handlers' threads (`teardown_threads`). - drop(device); - let mut pending = lock(&watch.pending); - pending.waiting[queue] = false; - let Some(polled) = polled else { - pending.exiting = true; - drop(pending); - watch.wake_all(); - return; - }; - match polled { - Ok(value) => { - let reached = &mut pending.reached[queue]; - *reached = (*reached).max(value); - } - Err(error) => { - pending.failed.get_or_insert(error); - } - } - // This waiter finishes what it saw, where no turn is under way; the one under way takes - // it at its next look, which takes this lock. A drain waits for the wait to end. - let turn = !pending.turning && due(&pending, queue); - pending.turning |= turn; - let draining = pending.draining > 0; - drop(pending); - watch.notify(&watch.drained, draining); - if turn && !turns(watch, &mut lists) { - return; - } - } -} - -/// The stall clock and the queue's watchdog clock after `queue`'s waiter's wait for `front` -/// answered `polled` (`stall.rs`): they stop where the queue's timeline advanced, and run where -/// the front is still pending. Past the watchdog's bound the front fails as Metal's timed-out -/// command buffer, whatever any probe answers; past the stall clock's, this waiter probes the GPU -/// where the device has a staging queue, and a probe that finds the generation stopped fails the -/// wait. Either fails it as a lost device's, the generation marked stopped first -/// (`Device::mark_wedged`). What the waiter answers. -fn stalled( - watch: &Watch, - device: &Device, - queue: usize, - front: Front, - polled: Result, -) -> Result { - let Ok(value) = polled else { - return polled; - }; - if device.shared().encoder_trail { - trail(watch, device, queue, front, value); - } - let counts = &device.shared().counts; - let stalled = { - let mut pending = lock(&watch.pending); - if value > pending.reached[queue] || value >= front.value { - if let Some(lasted) = pending.stall.advanced() { - counts.stall_lasted(lasted); - } - pending.stall.front_advanced(queue); - return Ok(value); - } - let held = pending.stall.front_held(queue); - let bound = super::stall::watchdog_after(device); - if held >= bound { - pending.stall.front_advanced(queue); - pending.timed_out.get_or_insert(queue); - drop(pending); - super::stall::timed_out(device, queue, held, bound); - device.mark_wedged(super::stall::Stop::Watchdog); - return Err(failure(device, vk::Result::ERROR_DEVICE_LOST)); - } - let after = super::stall::stall_after(device); - match pending.stall.ran_out(after) { - Some(stalled) if super::stall::probes(device) => stalled, - // No other engine to ask: nothing is probed (`stall.rs`, **Bounds**). - Some(_) => { - pending.stall.probed(); - return Ok(value); - } - None => return Ok(value), - } - }; - let verdict = super::stall::probe(device, queue, (front.value, front.fence), stalled); - lock(&watch.pending).stall.probed(); - match verdict { - super::stall::Verdict::Runs => Ok(value), - super::stall::Verdict::Failed(error) => Err(failure(device, error)), - super::stall::Verdict::Stopped => { - device.mark_wedged(super::stall::Stop::Unanswered); - Err(failure(device, vk::Result::ERROR_DEVICE_LOST)) - } - } -} - -/// The encoder trail's lines (`encoder_trail.rs`), where `queue`'s waiter's wait for `front` read -/// its timeline at `value`, short of it, and no queue's work advanced for -/// [`AFTER`](crate::encoder_trail::AFTER) since: one for each `VkQueue` whose oldest batch is -/// pending, once a stall. What they name is taken under the lock; formatted after it, where the -/// GPU forms' scratch is read (`encoder_trail.rs`, **GPU forms**), and said. -fn trail(watch: &Watch, device: &Device, queue: usize, front: Front, value: u64) { - let (stalled, named) = { - let mut pending = lock(&watch.pending); - if value > pending.reached[queue] || value >= front.value { - return; - } - let Some(stalled) = pending.stall.trail_due(crate::encoder_trail::AFTER) else { - return; - }; - let Pending { - queues, - reached, - trails, - .. - } = &*pending; - let mut named = Vec::new(); - for (queue, batches) in queues.iter().enumerate() { - let Some(oldest) = batches.front().filter(|batch| batch.value > reached[queue]) else { - continue; - }; - let last = - (trails[queue].as_ref()).map(|(trail, at)| (Arc::clone(trail), at.elapsed())); - named.push((queue, oldest.trail.clone(), last)); - } - (stalled, named) - }; - let pool = device.shared().pipeline_pool.queued(); - for (queue, front, last) in named { - let front = front.as_ref().map(crate::encoder_trail::Named::pending); - let last = (last.as_ref()).map(|(trail, ago)| (&**trail, *ago)); - let line = crate::encoder_trail::line(queue, stalled, front.as_deref(), last, pool); - device.inform(crate::encoder_trail::ID_NAME, line); - } -} - -/// Whether a turn has work that `queue`'s waiter sees: a waiter's failure, or its queue's first -/// pending batch due. -fn due(pending: &Pending, queue: usize) -> bool { - pending.failed.is_some() || front_due(pending, queue) -} - -/// Whether `queue`'s first pending batch may be taken: its value is at most the one its waiter saw -/// its timeline reach, and every batch of another queue it finishes after is taken -/// ([`Submitted::after`]). One reached that waits for another queue's is not due: the take of that -/// one takes it too, and its waiter sleeps meanwhile ([`wait`]). -fn front_due(pending: &Pending, queue: usize) -> bool { - pending.queues[queue].front().is_some_and(|batch| { - batch.value <= pending.reached[queue] - && (batch.after.iter()).all(|waited| waited.taken(&pending.taken)) - }) -} - -/// Wait up to one slice for `front`, the first pending batch of `device`'s `VkQueue` `queue`: for -/// its fence where it has one, else for the queue's timeline to reach its value, a -/// wait of that one object (the module docs). Then read the timeline and publish what a host wait -/// returned for ([`seen`]): the front's where its wait returned, and the value read where a wait -/// for it returned too. A failed wait or read is the error every pending command buffer finishes -/// with. -/// -/// MoltenVK signals a fence from its Metal command buffer's completion handler, where it wakes a -/// timeline wait from a shared event's listener (MoltenVK's `MVKSync.mm`; 6 to 11 us later). -/// -/// A signaled fence's batch reached its value whatever its timeline's read shows: a submission's -/// fence signal follows its timeline signal in Vulkan's signal operation order. A driver may show -/// the value later than the fence: lavapipe's emulated timeline shows it once the thread that -/// submitted the batch installed its point, after the batch ran, which a loaded host can hold up -/// past the fence's signal. -fn poll(device: &Device, queue: usize, front: Front) -> Result { - let shared = device.shared(); - let raw = shared.vk(); - let slot = &shared.queues[queue]; - // A wait of up to one slice for the queue's timeline to reach `value`: whether it did. - let reaches = |value: u64| { - let semaphores = [slot.timeline]; - let values = [value]; - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&semaphores) - .values(&values); - // SAFETY: the semaphore is the device's timeline, live while the device is (held here). - let waited = unsafe { raw.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) }; - exit_guard::called(Call::WaitSemaphores); - match waited { - Ok(()) => Ok(true), - Err(vk::Result::TIMEOUT) => Ok(false), - Err(error) => Err(failure(device, error)), - } - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let entered = gpu_time::host_nanos(); - let waited = match front.fence { - Some(fence) => { - // SAFETY: the fence is the device's, in a submission made and not yet reset (its - // batch is pending, and is not taken while this waits: `take_pending`), live while - // the device is (held here). - shared.counts.fence_wait(); - let waited = - unsafe { raw.wait_for_fences(&[fence], true, WAIT_SLICE.as_nanos() as u64) }; - exit_guard::called(Call::WaitForFences); - match waited { - Ok(()) => true, - Err(vk::Result::TIMEOUT) => false, - Err(error) => return Err(failure(device, error)), - } - } - None => { - shared.counts.timeline_wait(); - reaches(front.value)? - } - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::record(|| trace::Traced::Waited { - queue, - value: front.value, - entered, - returned: gpu_time::host_nanos(), - }); - // SAFETY: the semaphore is the device's timeline, live while the device is (held here). - let read = unsafe { raw.get_semaphore_counter_value(slot.timeline) }; - exit_guard::called(Call::GetSemaphoreCounterValue); - let read = read.map_err(|error| failure(device, error))?; - // A wait that ran out its slice although what it waited for was signaled by now: a wake it - // missed, counted (`WorkCounts::missed_completion_wakes`). A timeline is looked at by its - // read; a fence by a wait of no time: "If timeout is zero, then vkWaitForFences does not - // wait, but simply returns the current state of the fences". - if !waited { - let signaled = match front.fence { - Some(fence) => { - // SAFETY: as the wait's above. - let looked = unsafe { raw.wait_for_fences(&[fence], true, 0) }; - exit_guard::called(Call::WaitForFences); - looked.is_ok() - } - None => read >= front.value, - }; - if signaled { - shared.counts.missed_completion_wake(); - } - } - let value = seen( - slot.completed_value(), - waited.then_some(front.value), - read, - |value| { - // The read ran past what this wait returned for: one more wait, to put the host - // operation after a signal ([`seen`]). - shared.counts.completion_read_ran_ahead(); - reaches(value) - }, - )?; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - trace::at(trace::Point::Publish); - slot.completed(value, &shared.counts); - // Freed memory that waits for the batches in flight goes once they completed, on a handler - // thread (`freed_memory.rs`). - if let Some(parking) = shared.parking.get() { - parking.completed(queue, value); - parking.after_completion(device); - } - Ok(value) -} - -/// The value of a queue's timeline the host may publish as reached (the module docs): `known`, -/// the one it published before; `waited`, the one a wait just returned for (a timeline's wait, -/// or the front's fence, whose signal follows its timeline's in signal operation order, whatever -/// the read shows); `read`, the timeline's read after that wait. A read past both is a value -/// no host wait returned for yet: `reaches` waits for it, which returns at once where the read -/// was right, and it is published only where that wait returned. -pub(crate) fn seen( - known: u64, - waited: Option, - read: u64, - reaches: impl FnOnce(u64) -> Result, -) -> Result { - let confirmed = waited.map_or(known, |waited| waited.max(known)); - if read <= confirmed { - return Ok(confirmed); - } - Ok(match reaches(read)? { - true => read, - false => confirmed, - }) -} - -/// The command-buffer error of a failed wait, recording a lost device. -fn failure(device: &Device, error: vk::Result) -> CommandBufferError { - match error { - vk::Result::ERROR_DEVICE_LOST => { - device.mark_lost(); - // A batch held for an event may now be refused. - device.shared().scheduler.wake(); - CommandBufferError::DeviceLost - } - vk::Result::ERROR_OUT_OF_HOST_MEMORY | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { - CommandBufferError::OutOfMemory - } - other => CommandBufferError::Internal(VkResultCode(other.as_raw())), - } -} - -/// The host times of each queue waiter's steps, kept while a test asks for them, in the device -/// tests' builds only: the completion latency's measurement reads them -/// (`tests::completion_latency`). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) mod trace { - use super::super::gate::Hold; - use super::super::{CommandBuffer, CommandBufferShared}; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::{Arc, Mutex}; - - /// The address of the shared part of the command buffer whose completion turn fails as a - /// failed wait for its fence does, once ([`fail_settle_of`]). - static FAIL_SETTLE_OF: Mutex> = Mutex::new(None); - - /// The completion turn that finishes `command_buffer` fails as a wait for its fence fails once - /// its device was lost: its work completed, its queue's timeline past it. A real loss's - /// failed wait, which the test hook (`Device::recover_for_test`) never takes. - pub(crate) fn fail_settle_of(command_buffer: &CommandBuffer) { - *FAIL_SETTLE_OF.lock().unwrap() = Some(Arc::as_ptr(&command_buffer.0).addr()); - } - - /// Whether the turn that finishes `ending` fails so ([`fail_settle_of`]), at most once. - pub(super) fn settle_fails(ending: &[Hold]) -> bool { - let mut armed = FAIL_SETTLE_OF.lock().unwrap(); - let ours = |buffer: &Hold| { - let shared: &CommandBufferShared = buffer; - Some(std::ptr::from_ref(shared).addr()) == *armed - }; - let fails = ending.iter().any(ours); - if fails { - *armed = None; - } - fails - } - - /// The `VkQueue` the command buffer ran on and the host time, in nanoseconds, a completion - /// turn saw it complete (`finish`'s `seen`; 0 before): the completion latency's measurement - /// matches it to its queue waiter's steps (`tests::completion_latency`). - pub(crate) fn seen_of(command_buffer: &CommandBuffer) -> (usize, u64) { - let shared = &command_buffer.0; - let seen = crate::device::lock(&shared.state).times.completed; - (shared.queue.vk_queue(), seen) - } - - /// The address of the shared part of the command buffer whose timestamps read unavailable - /// once ([`unstamp_of`]). - static UNSTAMPED_OF: Mutex> = Mutex::new(None); - - /// The completion turn that reads `command_buffer`'s timestamps takes their availability as - /// 0 (`CommandBufferShared::read_stamps`); the work runs. - pub(crate) fn unstamp_of(command_buffer: &CommandBuffer) { - *UNSTAMPED_OF.lock().unwrap() = Some(Arc::as_ptr(&command_buffer.0).addr()); - } - - /// Whether `buffer`'s timestamps read unavailable so ([`unstamp_of`]), at most once. - pub(crate) fn unstamped(buffer: &CommandBufferShared) -> bool { - let mut armed = UNSTAMPED_OF.lock().unwrap(); - let ours = Some(std::ptr::from_ref(buffer).addr()) == *armed; - if ours { - *armed = None; - } - ours - } - - /// One step, its host time in nanoseconds of the host's clock (`gpu_time::host_nanos`). - #[derive(Clone, Copy, Debug)] - pub(crate) enum Traced { - /// A batch of value `value` was watched on `queue` (`Completion::watch`). - Watched { queue: usize, value: u64, at: u64 }, - /// `queue`'s waiter waited for its front, of value `value`: the driver's wait was entered - /// and returned (`poll`). - Waited { - queue: usize, - value: u64, - entered: u64, - returned: u64, - }, - /// A turn finished the batch of value `value` of `queue` that ends its command buffer; - /// `seen` is the command buffer's completion time (`finish`). - Finished { queue: usize, value: u64, seen: u64 }, - /// The turn that finished the batches reached step `what` of `finish`. - Step { what: &'static str, at: u64 }, - /// A commit's way to its submission reached step `what`: posted to the scheduler, its - /// thread woken, taken in by a pass, the driver's submission called and returned. - Submitting { what: &'static str, at: u64 }, - } - - static ON: AtomicBool = AtomicBool::new(false); - static STEPS: Mutex> = Mutex::new(Vec::new()); - - /// Keep the steps from now on. - pub(crate) fn start() { - *LET_THROUGH.lock().unwrap() = None; - FINISHED_POSTS.lock().unwrap().clear(); - STEPS.lock().unwrap().clear(); - ON.store(true, Ordering::SeqCst); - } - - /// How many batches that end their command buffers turns finished since [`start`] - /// ([`Traced::Finished`]), the steps kept. - pub(crate) fn finished_count() -> usize { - let steps = STEPS.lock().unwrap(); - (steps.iter()) - .filter(|step| matches!(step, Traced::Finished { .. })) - .count() - } - - /// How many commits were posted to the scheduler since [`start`] (`Traced::Submitting` - /// "posted"), the steps kept. - pub(crate) fn posted_count() -> usize { - let steps = STEPS.lock().unwrap(); - (steps.iter()) - .filter(|step| matches!(step, Traced::Submitting { what: "posted", .. })) - .count() - } - - /// Each transition to `Completed` or `Error` posted whole to its queue's context - /// (`CommandBufferShared::post_finished_transition`) since [`start`]: whether it went behind a - /// gate its submission handlers open, and the looks for a thread to run it its post made. - static FINISHED_POSTS: Mutex> = Mutex::new(Vec::new()); - - /// Such a transition was posted, `gated` or not, with `serves` looks for a thread. - pub(crate) fn finished_posted(gated: bool, serves: u64) { - if ON.load(Ordering::Relaxed) { - FINISHED_POSTS.lock().unwrap().push((gated, serves)); - } - } - - /// The posts [`finished_posted`] kept since [`start`]. - pub(crate) fn finished_posts() -> Vec<(bool, u64)> { - FINISHED_POSTS.lock().unwrap().clone() - } - - /// Stop keeping steps, and the steps kept. - pub(crate) fn stop() -> Vec { - ON.store(false, Ordering::SeqCst); - STEPS.lock().unwrap().drain(..).collect() - } - - /// Keep the turn's step `what`, now. - pub(super) fn step(what: &'static str) { - record(|| Traced::Step { - what, - at: crate::gpu_time::host_nanos(), - }); - } - - /// How long the scheduler pauses once a command buffer's `vkQueueSubmit` returned - /// ([`submit_returned`]); none unless a test asks ([`pause_after_submit`]). - static AFTER_SUBMIT: Mutex> = Mutex::new(None); - - /// Pause the scheduler for `pause` each time a command buffer's `vkQueueSubmit` returned, - /// from now on (`None`: no more): a scheduler thread preempted there, while the GPU runs the - /// work. - pub(crate) fn pause_after_submit(pause: Option) { - *AFTER_SUBMIT.lock().unwrap() = pause; - } - - /// A command buffer's `vkQueueSubmit` returned (`submit.rs`): the pause a test asked for. - pub(crate) fn submit_returned() { - let pause = *AFTER_SUBMIT.lock().unwrap(); - if let Some(pause) = pause { - std::thread::sleep(pause); - } - } - - /// A point of the runtime's threads a test holds a thread at ([`hold_at`]) until it lets it go - /// ([`release`]), to force an interleaving. - #[derive(Clone, Copy, PartialEq, Eq, Debug)] - pub(crate) enum Point { - /// A queue's waiter, before it publishes a value its queue's timeline completed (`poll`). - Publish, - /// The scheduler's thread, once `Group::keeps` kept the group held past its pass and - /// before it leaves the group's gate for the completion turns (`scheduler/mod.rs`). - KeptGate, - /// A queue's waiter, once it published a value its queue's timeline completed and before - /// the batches at or below it leave the `VkQueue`'s flight (`QueueSlot::completed`). - Leave, - /// A committing thread, once its command buffer's last command buffer ended (with its - /// batch's end where it may) and before it hands the batches to the scheduler - /// (`CommandBuffer::commit`). - Committing, - /// A committing thread, once it handed the batches to the scheduler and before it hands - /// over its queue's slot (`CommandBuffer::commit`). - Handed, - /// The thread submitting a batch, as its submission enters its first work's take - /// (`submit.rs`, `slow_submissions.rs`). - FirstWork, - /// A steps' thread, before it records the host step handed to it - /// (`scheduler/steps.rs`). - Step, - /// A steps' thread, once it recorded a host step, ended it and woke the scheduler's - /// thread (`scheduler/steps.rs`). - Stepped, - /// The scheduler's thread, once a pass that handed the submission handlers of the command - /// buffer a test names ([`hold_after_hand_off`]) to the device's handler threads let go - /// of the lock and counted out, before the pass's after-work (`scheduler::let_go`). - HandedOff, - /// A thread that committed with `commit_and_submit`, its commit posted, before its own - /// pass (`Scheduler::submit_at_commit`). - AtCommitPass, - } - - /// Of each [`Point`]: whether a test holds threads there, and whether one reached it since. - static POINTS: Mutex<[(bool, bool); 10]> = Mutex::new([(false, false); 10]); - static POINTS_CHANGED: std::sync::Condvar = std::sync::Condvar::new(); - - /// Hold every thread that reaches `point` from now on, until [`release`]. - pub(crate) fn hold_at(point: Point) { - POINTS.lock().unwrap()[point as usize] = (true, false); - } - - /// Let go of the threads held at `point`, and hold none there any more. - pub(crate) fn release(point: Point) { - POINTS.lock().unwrap()[point as usize].0 = false; - POINTS_CHANGED.notify_all(); - } - - /// Whether a thread reached `point`, held there, within `timeout`. - pub(crate) fn reached(point: Point, timeout: std::time::Duration) -> bool { - let points = POINTS.lock().unwrap(); - let (points, _) = POINTS_CHANGED - .wait_timeout_while(points, timeout, |points| !points[point as usize].1) - .unwrap(); - points[point as usize].1 - } - - /// The address of the shared part of the command buffer whose committing thread goes on from - /// [`Point::AtCommitPass`] while it is held ([`let_through`]). - static LET_THROUGH: Mutex> = Mutex::new(None); - - /// Let `command_buffer`'s committing thread go on from [`Point::AtCommitPass`], held there or - /// not yet, while every other stays held (`None`: none). - pub(crate) fn let_through(command_buffer: Option<&CommandBuffer>) { - *LET_THROUGH.lock().unwrap() = command_buffer.map(|it| Arc::as_ptr(&it.0).addr()); - let _points = POINTS.lock().unwrap(); - POINTS_CHANGED.notify_all(); - } - - /// A committing thread is at [`Point::AtCommitPass`] with `buffer`: held there while a test - /// holds it, unless the test lets `buffer`'s through ([`let_through`]). - pub(crate) fn at_commit_pass(buffer: &CommandBufferShared) { - let ours = std::ptr::from_ref(buffer).addr(); - let point = Point::AtCommitPass as usize; - let mut points = POINTS.lock().unwrap(); - if !points[point].0 { - return; - } - points[point].1 = true; - POINTS_CHANGED.notify_all(); - let held = |points: &mut [(bool, bool); 10]| { - points[point].0 && *LET_THROUGH.lock().unwrap() != Some(ours) - }; - drop(POINTS_CHANGED.wait_while(points, held)); - } - - /// A runtime thread is at `point`: held there while a test holds it. - pub(crate) fn at(point: Point) { - let mut points = POINTS.lock().unwrap(); - if !points[point as usize].0 { - return; - } - points[point as usize].1 = true; - POINTS_CHANGED.notify_all(); - drop(POINTS_CHANGED.wait_while(points, |points| points[point as usize].0)); - } - - /// The address of the shared part of the command buffer whose handed-off submission handlers - /// stop the scheduler's thread at [`Point::HandedOff`] ([`hold_after_hand_off`]). - static HAND_OFF_OF: Mutex> = Mutex::new(None); - - thread_local! { - /// The pass this thread makes handed off the submission handlers [`HAND_OFF_OF`] names. - static HANDED_OFF: std::cell::Cell = const { std::cell::Cell::new(false) }; - } - - /// From now on, the scheduler's thread reaches [`Point::HandedOff`] after the pass that hands - /// `command_buffer`'s submission handlers to the device's handler threads (`None`: after no - /// pass): with the point held, a scheduler's thread held once it submitted that command - /// buffer, counted out, as it is while it runs the after-work of a pass. - pub(crate) fn hold_after_hand_off(command_buffer: Option<&CommandBuffer>) { - *HAND_OFF_OF.lock().unwrap() = command_buffer.map(|it| Arc::as_ptr(&it.0).addr()); - } - - /// The scheduler's thread hands `handed`'s submission handlers to the device's handler threads - /// (`scheduler::HandOff::post`), its lock held: noted where [`hold_after_hand_off`] named one. - pub(crate) fn handing_off(handed: &[Hold]) { - let armed = *HAND_OFF_OF.lock().unwrap(); - let ours = |buffer: &Hold| { - let shared: &CommandBufferShared = buffer; - Some(std::ptr::from_ref(shared).addr()) == armed - }; - if armed.is_some() && handed.iter().any(ours) { - HANDED_OFF.set(true); - } - } - - /// The scheduler's thread let go of a pass's lock and counted out (`scheduler::let_go`): at - /// [`Point::HandedOff`] where that pass handed off what [`hold_after_hand_off`] named. - pub(crate) fn let_go() { - if HANDED_OFF.replace(false) { - at(Point::HandedOff); - } - } - - /// Whether the completion turns wake the scheduler's thread for a met wait no more - /// ([`drop_completion_wakes`]). - static COMPLETION_WAKES_DROPPED: AtomicBool = AtomicBool::new(false); - - /// From now on (`true`), or no more, the completion turns never wake the scheduler's thread - /// for what a head waited for (`Scheduler::completions`): a wake lost, whatever its cause. - pub(crate) fn drop_completion_wakes(drop: bool) { - COMPLETION_WAKES_DROPPED.store(drop, Ordering::SeqCst); - } - - /// Whether a test drops the completion turns' wakes ([`drop_completion_wakes`]). - pub(crate) fn completion_wakes_dropped() -> bool { - COMPLETION_WAKES_DROPPED.load(Ordering::SeqCst) - } - - /// Keep the commit's step `what` on its way to its submission, now. - pub(crate) fn submitting(what: &'static str) { - record(|| Traced::Submitting { - what, - at: crate::gpu_time::host_nanos(), - }); - } - - /// Keep the step `step` makes, while a test asks. - pub(super) fn record(step: impl FnOnce() -> Traced) { - if ON.load(Ordering::Relaxed) { - let step = step(); - STEPS.lock().unwrap().push(step); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/copies_again.rs b/crates/metal2vulkan-runtime/src/command_buffer/copies_again.rs deleted file mode 100644 index 5420f6ad4..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/copies_again.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Copied host buffers copied in again after an event wait (`copied.rs`, **Coherence**). -//! -//! A commit copies into each copy its commands reach the bytes the CPU changed in its pages, -//! before any of its work is submitted. A batch that waits for an event runs its commands once -//! the event reaches the value, and Metal's reads there see the pages as they stand then: a CPU -//! write made after the commit and before the signal (the host's, or a command buffer's committed -//! after it) is read. So a batch whose wait the commit found not reached, as it stood before the -//! commit's copy in, copies in again as it is submitted, which the scheduler does only once the -//! wait is met: the copies the command buffer's commands reach, as at the commit, take the bytes -//! the CPU changed since. Counted: `WorkCounts::copied_copy_ins_after_waits`. -//! -//! A batch with no wait, and one whose every wait the commit found reached, copies in nothing -//! more: every CPU write before its commands may run was made before the commit's copy in. A wait -//! a GPU signal meets that a copy's merge back must come before is held on the host until that -//! merge (`event_timeline.rs`), so the copy in again after it takes the merged bytes too. - -use super::batches::Batch; -use super::{lock, recording_error, CommandBufferShared}; -use crate::copied::CopiesReached; -use crate::error::{CommandBufferError, Error, MemoryKind}; -use crate::event::EventShared; -use crate::event_timeline::WaitFor; -use ash::vk; -use std::sync::Arc; - -/// The batches of a committed command buffer that copy in again, and the copies its commands -/// reach. -pub(super) struct CopiesAgain { - /// The batches, by index, not yet submitted. - batches: Vec, - /// The copies its commands may read, and those they may write, as the commit found them - /// (`CopiedBuffers::copy_in`). - reached: Arc<(CopiesReached, CopiesReached)>, -} - -impl CopiesAgain { - /// The indices of `batches` that wait for an event value not reached now. - pub(super) fn unreached(batches: &[Batch, vk::Semaphore>]) -> Vec { - (batches.iter().enumerate()) - .filter(|(_, batch)| { - (batch.waits.iter()) - .any(|(event, value)| event.wait(*value) != Some(WaitFor::Reached)) - }) - .map(|(index, _)| index) - .collect() - } - - /// The copies in again of `batches`, reaching `reached`; `None` where there are none. - pub(super) fn new( - batches: Vec, - reached: (CopiesReached, CopiesReached), - ) -> Option { - (!batches.is_empty()).then(|| CopiesAgain { - batches, - reached: Arc::new(reached), - }) - } -} - -impl CommandBufferShared { - /// Copy in again for batch `index`, where its commit left one for it, once: as it is - /// submitted, its waits met. Copied with no lock of the command buffer's held, as a copy over - /// logged pages waits for the log's publication; where the host has no memory for a copy's - /// base, the command buffer fails as out of memory, as its commit would have. - pub(super) fn copy_in_again(&self, index: usize) -> Result<(), CommandBufferError> { - let reached = { - let mut state = lock(&self.state); - let Some(again) = &mut state.copies_again else { - return Ok(()); - }; - let Some(at) = again.batches.iter().position(|&batch| batch == index) else { - return Ok(()); - }; - again.batches.swap_remove(at); - let reached = Arc::clone(&again.reached); - if again.batches.is_empty() { - state.copies_again = None; - } - reached - }; - let device = &self.device; - let shared = device.shared(); - let (used, written) = &*reached; - let copied_in = shared.copied.copy_in( - &shared.counts, - shared.dirty.tally(), - (used, written), - || shared.dirty.in_flight(), - &mut |length| device.copied_base(length), - ); - if copied_in.is_err() { - return Err(recording_error( - device, - Error::OutOfMemory(MemoryKind::Host), - )); - } - shared.counts.copied_copy_ins_after_waits(); - Ok(()) - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fences.rs b/crates/metal2vulkan-runtime/src/command_buffer/fences.rs deleted file mode 100644 index 93ae47c6c..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/fences.rs +++ /dev/null @@ -1,182 +0,0 @@ -//! The fences that end command buffers, where the driver needs them: the batch that ends a command -//! buffer signals one with its submission, and the completion turn finishes the command buffer -//! only once both its queue's timeline reached the batch's value and the fence is signaled -//! ([`completion`](super::completion)). -//! -//! - **The value is the completion, and Vulkan says so.** A batch's timeline signal follows the -//! batch's commands: "The first synchronization scope of each semaphore signal operation defined -//! by this command includes every command in the same batch that the signal operation is defined -//! in, and all commands that occur earlier in submission order" (`vkQueueSubmit`). A host wait -//! for the value orders the host after that signal: "signal operations happening before host -//! operations that wait on them" system-synchronize-with them (the memory model), where -//! `vkGetSemaphoreCounterValue` alone gives no such dependency (its value "may immediately be -//! out of date"). So once the waiter's `vkWaitSemaphores` returned for the value, the batch's -//! commands completed and what they used may be released, and nothing but the waiter's wait is -//! relied on ([`completion`](super::completion), where the waits are, and what publishes a -//! batch). The waiter waits for one semaphore, never for any of several -//! (`RuntimeDriverDefect::WaitForAnyObjectLosesASignal`). -//! - **MoltenVK reads some of it later, and only some.** MoltenVK signals a timeline semaphore -//! from the GPU (`MVKSemaphoreMTLEvent::encodeSignal`, `[mtlCmdBuff encodeSignalEvent:]`), so -//! the host sees the value before the Metal command buffer's completed handlers run, and it -//! signals a fence from the last of those handlers. What those handlers read decides whether the -//! value alone is enough. Every `addCompletedHandler:` of 1.4.2's source, read in full (the -//! `addScheduledHandler:` of `MVKImage.mm` is a swapchain's, which the runtime makes none of): -//! - `MVKCommandEncoder::finishQueries` (`MVKCommandBuffer.mm`) calls `finishQueries` on every -//! query pool the command buffer reset, began or ended, through a raw `MVKQueryPool*` it does -//! not retain, and that call takes the pool's `_availabilityLock` and writes its -//! `_availability`. **A Vulkan object of the command buffer's**, and the only handler that -//! reads one the runtime may release at the value. Registered only where the encoder -//! collected an activated query (`_pActivatedQueries`, from `addActivatedQueries`), so only -//! for a command buffer that recorded a query command. -//! - `MVKCommandEncoder::getTempMTLBuffer` and `MVKCmdUpdateBuffer::encode` return a -//! `MVKMTLBufferAllocation` to the pool it came from, which lives in the `MVKCommandPool` of -//! the `VkCommandPool` the command buffer was allocated from -//! (`MVKCommandEncoder::getCommandEncodingPool`). The runtime calls -//! `vkDestroyCommandPool` on a command buffer's pool only as the device is torn down, after -//! its queues are idle, and resets a spare with `vkResetCommandPool` of no flag, which leaves -//! `MVKCommandPool`'s encoding pool alone (`MVKCommandPool::reset` trims only for -//! `VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT`, which the runtime never passes; -//! `spares.rs`). So that pool outlives every handler. -//! - `MVKImagePlane::pullFromDeviceOnCompletion` (`MVKImage.mm`) copies a texture into mapped -//! host-coherent memory through its `MVKImagePlane*`, a `VkImage`'s. Registered only from -//! `MVKImagePlane::applyImageMemoryBarrier`, and only where the barrier's destination names -//! `VK_ACCESS_HOST_READ_BIT` or `VK_ACCESS_MEMORY_READ_BIT` into `VK_IMAGE_LAYOUT_GENERAL`; -//! no image memory barrier of the runtime names either (`image_barrier.rs`, which is where -//! all of them are made, held to it by `tests::image_barriers`), so it is registered for none -//! of the runtime's command buffers. -//! - `MVKQueueCommandBufferSubmission::finish` (`MVKQueue.mm`) reads the submission, its -//! `MVKQueue`, and the signal semaphores and fence it retains for exactly this -//! ("We therefore retain() each here to ensure they live long enough for this submission to -//! finish using them"); `MVKQueue::handleMTLCommandBufferError` reads the `MTLCommandBuffer` -//! and the device. Neither reads an object of the command buffer. -//! - `MVKCommandEncoder::getStageCountersMTLFence` releases an `MTLFence` the block retains, and -//! `MVKCmdBlitImage::encode`'s three release an `MTLTexture` the block retains. Metal objects -//! of MoltenVK's own, no Vulkan object. -//! -//! So the hazard is one handler and one object class: the query pools of a command buffer that -//! recorded a query command. The device's driver defects name it -//! (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`, `driver_defects.rs`). -//! - **The fence is kept for every command buffer there all the same, and it is the faster wait.** -//! A command buffer that records no query command could learn its completion from the value -//! alone, which Vulkan makes enough (above). It does not, for two measured reasons. -//! - **The host sees the fence before it sees the value.** MoltenVK signals the fence from the -//! last of the completed handlers, after the GPU signalled the value, but its host wait for a -//! timeline value goes through an `MTLSharedEvent`'s listener while its fence is a condition -//! variable the handler thread broadcasts. On an Apple M3 Max (macOS 27.0.1, MoltenVK 1.4.2, -//! `runtime_lane::commit_costs`) one submission of a barrier alone, waited for 200 times after -//! 20: its fence returned 49.3 us after the submission (p10 44.6, p90 60.1) and its timeline -//! value 58.6 us (p10 48.2, p90 82.6). Waiting for the value in its place would cost about 9 -//! us a command buffer at the median and 22 at the 90th percentile, not save any. For scale, a -//! whole empty command buffer of the runtime completes 32.4 us after its commit there (p90 -//! 43.1), so the handler chain is no hundreds of microseconds. -//! - **A queue whose failures are relayed needs one for every batch** (`device/relay.rs`), and -//! every MoltenVK device the runtime creates relays: MoltenVK reports a command buffer's -//! failure to the instance's messenger from the first of the same completed handlers, before -//! the fence's, and the relay gives the failure to the first submission in flight whose fence -//! is unsignaled. A command buffer finished at its value could be finished before its failure -//! arrived. A device the runtime adopts relays none (`Device::from_raw`: an adopted instance -//! has no messenger of the runtime's), so there the defect above is the whole reason. -//! - **Only there**. Every other driver signals the fence with the value, so a command buffer there -//! ends at its value alone and its commit takes no fence ([`ends_at_fence`]): NVIDIA's -//! `vkCreateFence` on the commit path waited up to 1.9 s for other processes' work. -//! - **Pooled, and bounded.** A fence is taken when the last batch is submitted (made only when -//! none is idle) and given back, reset, once a completion turn saw it signaled. At most -//! [`IDLE`] wait idle; the ones beyond are released. So the fences live are the command buffers -//! in flight plus at most [`IDLE`], whatever the number of command buffers committed. -//! - **The exit guard's doors.** Making one is the scheduler's (inside its section), waiting for -//! and resetting them the queues' waiters' (inside their sections), and every release goes -//! through `release.rs`; each entry point is in the guard's table and primed -//! (`exit_guard`, `device/prime.rs`). - -use crate::device::lock; -use crate::exit_guard::{self, Call}; -use crate::release; -use crate::Device; -use ash::vk; -use metal2vulkan::error::RuntimeDriverDefect; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; - -/// The most fences kept idle. -pub(crate) const IDLE: usize = 16; - -/// Whether a submission to `device`'s `VkQueue` `queue` that ends a command buffer takes a fence: -/// where the driver reads a command buffer's query pools after its signal, or the queue's -/// failures are relayed (the module docs). -pub(crate) fn ends_at_fence(device: &Device, queue: usize) -> bool { - device.shared().flights(queue).is_some() - || (device.properties().driver_defects) - .contains(&RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal) -} - -/// A device's idle fences, each unsignaled and in no pending submission. -#[derive(Default)] -pub(crate) struct Fences { - idle: Mutex>, - /// The fences made, none idle: `WorkCounts::fences_made`. - made: AtomicU64, -} - -impl Fences { - /// An unsignaled fence of `device`: an idle one, else a new one. - /// - /// # Safety - /// - /// The fences are `device`'s; the caller is inside a section of the exit guard. - pub(crate) unsafe fn take(&self, device: &ash::Device) -> Result { - if let Some(fence) = self.take_idle() { - return Ok(fence); - } - // SAFETY: the device is live (the caller holds it). - let made = unsafe { device.create_fence(&vk::FenceCreateInfo::default(), None) }; - exit_guard::called(Call::CreateFence); - self.made.fetch_add(1, Ordering::Relaxed); - made - } - - /// How many fences [`take`](Self::take) made so far. - pub(crate) fn made(&self) -> u64 { - self.made.load(Ordering::Relaxed) - } - - /// Give back `fences` of `device`, each unsignaled (reset, or never submitted) and in no - /// pending submission: kept idle up to [`IDLE`], the rest released. `fences` is left empty, - /// its room kept for the caller's next ones. - /// - /// # Safety - /// - /// As above. - pub(crate) unsafe fn give(&self, device: &ash::Device, fences: &mut Vec) { - self.keep(fences); - for fence in fences.drain(..) { - // SAFETY: the caller's: no pending submission uses it. - unsafe { release::object(device, fence) }; - } - } - - /// Release every idle fence: the device is being torn down. - /// - /// # Safety - /// - /// As above. - pub(crate) unsafe fn release(&self, device: &ash::Device) { - let idle: Vec = lock(&self.idle).drain(..).collect(); - for fence in idle { - // SAFETY: the caller's. - unsafe { release::object(device, fence) }; - } - } - - /// An idle fence, if any. - pub(crate) fn take_idle(&self) -> Option { - lock(&self.idle).pop() - } - - /// Keep `fences` idle up to [`IDLE`], the first of them first; the ones beyond stay in - /// `fences`, for the caller to release. - pub(crate) fn keep(&self, fences: &mut Vec) { - let mut idle = lock(&self.idle); - let kept = IDLE.saturating_sub(idle.len()).min(fences.len()); - idle.extend(fences.drain(..kept)); - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs deleted file mode 100644 index 6cd628d81..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ /dev/null @@ -1,782 +0,0 @@ -//! A command buffer's first submission: Metal resolves what a command buffer's commands reach as it -//! submits it, not as it was committed, so a command buffer committed before a rebind (`rebind.rs`) -//! or a release and submitted after it behaves as one committed after it (the consumer's -//! measurement on the M3 Max, its rebind-reach tables 1 to 3). -//! -//! - **Until then, held weakly.** From the commit to the first submission the command buffer -//! holds the pages its commands took of buffers over host pages (`rebind::Taken`) and the live -//! buffers' table its resident set was made of (`Live`) weakly: a rebind or a release meanwhile -//! lets the pages go, their deallocator run, where no submitted command buffer holds them -//! (the question, answered without revoking anything). The pages an event group's commands took -//! (its batches between event waits and signals, `State::event_group`) are held from that -//! group's first batch's submission until the command buffer completes, so submitted work keeps -//! the pages it took, as Metal's does (table 3: a submitted command buffer never sees the new -//! pages); a detach waits for, or refuses on, that group only until its work completed -//! (`rebind::SubmittedHolds`), as Metal holds a submission's uses. A root table recorded -//! before then, by a rebind's encoding again (`reencode.rs`) or a host step, holds the table -//! (`State::hold_live`) until the first submission, which lets go of it where the list changed -//! meanwhile: at once, as Metal lets a released buffer go, but on a handler thread -//! (`Device::let_go_elsewhere`), as its last hold of a released buffer's pages runs that -//! buffer's deallocator, which may not run on the scheduler's thread under its locks. The -//! deallocator's wait from the release until then, past Metal's, is announced -//! (`host-deallocator-delayed`). -//! - **Resolved again where the list changed.** Where the live buffers' list changed since the -//! commit (a buffer made or gone, a rebind), the submission lists again what the commit listed -//! (`LiveBuffers::reach`, a rebind having ended its use), makes its resident set again of the -//! list as it stands and of what its encoders made resident as it lies now, and points every -//! root table at it: a buffer its encoders made resident reaches the pages it lies in now -//! (case 3, `useResource:` and `useHeap:`, and after two rebinds the second's), and one it -//! reaches only unnamed reads 0 once a rebind ended its use (cases 4 and 4x). A root table's -//! own range whose Metal address the remade set holds anew goes: the buffer lies elsewhere. -//! (A set of any count; before, past the search's 2^16 entries, each root table took back its own -//! set.) -//! - **What it named, encoded again; else typed.** A command that named a buffer over host pages -//! was resolved as it was encoded (a binding's descriptor or root-table static, a blit's -//! operand, an attachment, a vertex, index or indirect buffer, a texture over the pages, an -//! indirect command's resolved buffer), where Metal reaches the pages the buffer lies in at the -//! submission (cases 1, 2 and 5). The rebind encodes the compute, blit and render encoders that -//! named it again before this submission, which waits for them (`reencode.rs`). Where an encoder -//! that could not be encoded again named a buffer that lies in other pages by then, each of -//! Metal's submissions holding such a command (`checks::metal_submissions`, the split) runs -//! nothing and the command buffer completes with `CommandBufferError::EncodedUseRebound`, every -//! other submission running, its signals firing and its handlers running: the gap until the -//! encoded uses resolve at submission, announced once -//! (`Degradation::EncodedUseRebound`). Work recorded on the GPU alone (`gpu_execute.rs`, -//! `render/executions/gpu.rs`) resolves its commands' records through the resident set its -//! preprocess's table names: where the list changed or a buffer of it moved since the commit, -//! the submission points every such table at the set as it lies now, with its entries' -//! extents (`State::point_replay_tables`, `ResidentSet::replay_bytes`), so a rebind or a -//! release meanwhile takes effect in its commands, which are recorded once. What its commands -//! named is encoded or recorded again as an encoder's commands are (`reencode.rs`). -//! - **Each submission at its own batch**. The first submission finds which of Metal's submissions -//! of the first event group are rebound or hold a detached buffer, and each later group's first -//! batch those of its group, against where the buffers lie then, as Metal decides each -//! submission as it submits it (a detach between two submissions fails the later one, code 8, -//! the earlier one having run: the M3 Max under macOS 27.0.1). A rebind before a later group's -//! submission encodes its encoders that named the buffer again, as before the first -//! (`reencode.rs`): Metal's later submission runs over the new pages. The table its first -//! submission fixes serves every later batch: a later group reaches a buffer detached or -//! rebound since then through an address (made resident, or unnamed) through the pages it took, -//! where Metal's reads the new pages or zeros. Each fails only as its own batch is submitted, -//! after that batch's submission checks (`checks.rs`). One its -//! check failed already keeps the check's code (8 for the consumer's detach) and announces -//! nothing, and so does one whose every encoder the commit's failure failed (`commit_failed`'s); -//! the submissions before it run as Metal runs them, and the command buffer fails with the first -//! failure in submission order. Any other rebound submission runs nothing and is announced, -//! though the command buffer failed already and keeps that first code (move14: the consumer's -//! review; Metal runs it over the new pages). - -use super::rebound_use::{ReboundAt, ReboundUse, Recording}; -use super::{write_fields, CommandBufferShared, Resident, State}; -use crate::error::{internal, CommandBufferError, Error}; -use crate::live_buffers::LiveTable; -use crate::rebind::{SubmittedHolds, Submitting}; -use crate::upload::Upload; -use crate::used_resources::UsedResources; -use crate::values::CommandBufferStatus; -use crate::Device; -use metal2vulkan::bind::{ResidentRange, ResidentSet, RootTable}; -use std::collections::{BTreeMap, BTreeSet}; -use std::ops::Range; -use std::sync::{Arc, Weak}; - -/// A root table a command buffer's commands read (`State::root_table`): its upload and its -/// device address. -#[derive(Clone)] -pub(crate) struct NotedTable { - pub(crate) upload: Upload, - pub(crate) address: u64, -} - -/// A replay preprocess's resident root table (`render/executions/gpu.rs`, `gpu_execute.rs`): its -/// upload, where it lies there, and its device address. The command buffer's first submission -/// points it at the resident set as it lies then, where that changed since the commit -/// (`State::point_replay_tables`). -pub(crate) struct ReplayTable { - pub(crate) upload: Upload, - pub(crate) at: u64, - pub(crate) address: u64, -} - -/// The live buffers' table a command buffer's resident set was made of (the module docs). -pub(super) enum Live { - /// Weakly, with the generation of the list it was made of: from the commit to the first - /// submission. - Waiting { - table: Weak, - generation: u64, - }, - /// From the first submission (or a host step before it) until the command buffer completes. - Held(Arc), -} - -impl Live { - /// `table`, as a command buffer holds it: weakly before its first submission (`submitted` - /// false), unless no other holds it (a table made as the list changed meanwhile, which the - /// device keeps not), whose last hold would let pages go here. - pub(super) fn of(table: Arc, submitted: bool) -> Live { - if submitted || Arc::strong_count(&table) == 1 { - return Live::Held(table); - } - Live::Waiting { - generation: table.generation(), - table: Arc::downgrade(&table), - } - } - - /// The table's set, where it is held. - pub(super) fn set(&self) -> Option<&ResidentSet> { - match self { - Live::Held(table) => Some(table.set()), - Live::Waiting { .. } => None, - } - } -} - -/// What a commit listed among the live buffers (`LiveBuffers::reach`), and the generation of the -/// list after it. -pub(super) struct Listing { - used: UsedResources, - generation: u64, -} - -impl Listing { - /// `used`, listed on `device` just now. - pub(super) fn new(device: &Device, used: UsedResources) -> Listing { - Listing { - generation: device.shared().live_buffers.generation(), - used, - } - } -} - -/// The Metal addresses a resident set's ranges hold, to find whether a root table's own range -/// lies in one of them: each range's start, by its order, with the furthest end of every range -/// starting there or before (ranges nest: a heap's holds its buffers'). -struct Covered(Vec<(u64, u64)>); - -impl Covered { - fn of(ranges: impl IntoIterator) -> Covered { - let mut starts: Vec<(u64, u64)> = ranges - .into_iter() - .map(|range| (range.guest, range.guest.saturating_add(range.length.max(1)))) - .collect(); - starts.sort_unstable(); - let mut furthest = 0; - for (_, end) in &mut starts { - furthest = furthest.max(*end); - *end = furthest; - } - Covered(starts) - } - - /// Whether Metal address `guest` lies in one of the ranges. - fn holds(&self, guest: u64) -> bool { - let below = self.0.partition_point(|&(start, _)| start <= guest); - below.checked_sub(1).is_some_and(|at| guest < self.0[at].1) - } -} - -impl State { - /// As the command buffer commits (its segments recorded): what its commands took is held - /// weakly until its first submission, which lists `listing` again where the list changed. - pub(super) fn wait_for_submission(&mut self, listing: Listing) { - for record in &mut self.ended { - record.taken.wait(); - } - let segments = self - .recorded - .iter_mut() - .flat_map(|part| part.segments.iter_mut()) - .filter_map(|segment| segment.recorded.as_mut()); - for done in segments { - done.taken.wait(); - } - self.listing = Some(listing); - } - - /// Hold the live buffers' table its resident set was made of from now on: made again where - /// the list changed since (the module docs). A root table a host step uploads before the - /// first submission is pointed at the set as it stands then. - /// A table held already, by a host step's root table or an encoder encoded again at a rebind - /// before the first submission (`reencode.rs`), is made again where the list changed since - /// it was made: the first submission resolves the set as the list stands then. - pub(super) fn hold_live(&mut self, device: &Device) -> Result<(), Error> { - let now = device.shared().live_buffers.generation(); - match &self.resident { - Some(Resident { - live: Live::Waiting { table, generation }, - .. - }) => { - // The list unchanged, the device keeps the table: the upgrade is not its last - // hold. Changed, the table is not upgraded at all: an upgrade let go of here, - // under the scheduler's lock and this state's, could be the last hold of a gone - // buffer's pages, whose release runs the program's code. - let kept = (*generation == now).then(|| table.upgrade()).flatten(); - if let Some(table) = kept { - if let Some(resident) = &mut self.resident { - resident.live = Live::Held(table); - } - return Ok(()); - } - } - Some(Resident { - live: Live::Held(table), - .. - }) if table.generation() != now => {} - _ => return Ok(()), - } - let fresh = self.fresh_ranges(device); - self.remake_resident(device, &fresh) - } - - /// Its work on the GPU alone, at its first submission: each preprocess's resident root table - /// (`replay_tables`), recorded with the resident set as it lay then, pointed at the set as - /// the live buffers and what its encoders made resident lie now, where that changed - /// (`moved`), with its extents (`ResidentSet::replay_bytes`), uploaded once for all: a - /// rebind or a release since takes effect in its commands, as Metal resolves them at the - /// submission, and nothing is recorded again. The live buffers' table is held until it - /// completes either way, as their ranges lie in its pages. - fn point_replay_tables(&mut self, device: &Device, moved: bool) -> Result<(), Error> { - let live = device.shared().live_buffers.table(device)?; - if moved { - let ranges = live.ranges().chain(self.fresh_ranges(device)); - let (bytes, count) = ResidentSet::replay_bytes(ranges); - let len = bytes.len() as u64; - let upload = - (self.uploads).upload_aligned(device, &bytes, len, RootTable::ENTRY_ALIGNMENT)?; - let set = (upload.device_address()) - .ok_or_else(|| internal("a replay's resident set without a device address"))?; - for table in &self.replay_tables { - let fields = RootTable::resident_fields(table.address, set, count) - .ok_or_else(|| internal("a replay's resident table off its set's alignment"))?; - let at = table.at + u64::from(RootTable::RESIDENT_FIELDS_OFFSET); - table.upload.write_at(at, &fields); - } - let pointed = self.replay_tables.len() as u64; - device.shared().counts.replay_tables_pointed(pointed); - self.retained.push(Box::new(upload)); - } - self.replay_tables.clear(); - self.retained.push(Box::new(live)); - Ok(()) - } - - /// The ranges of what its encoders made resident, as it lies now. - fn fresh_ranges(&mut self, device: &Device) -> Vec { - (self.joined_residency(&device.shared().counts)) - .map(|residency| residency.resident_ranges()) - .unwrap_or_default() - } - - /// Its resident set made again of the live buffers as they stand now and `fresh`, what its - /// encoders made resident as it lies now, and every noted root table pointed at it. A table - /// it held goes at once, on a handler thread. - fn remake_resident(&mut self, device: &Device, fresh: &[ResidentRange]) -> Result<(), Error> { - let live = device.shared().live_buffers.table(device)?; - let set = live.set(); - // A root table's own range whose Metal address the remade set holds goes: the buffer - // there lies as the set says now. - let covered = Covered::of(live.ranges().chain(fresh.iter().copied())); - let mut beyond: Vec = self - .root_ranges - .iter() - .filter(|range| !covered.holds(range.guest)) - .copied() - .collect(); - beyond.extend(fresh.iter().copied()); - beyond.retain(|range| !set.holds(range)); - let (merged, address, count) = match beyond.is_empty() { - true => (None, live.address(), set.len()), - false => { - let merged = set.with(beyond); - let (address, count) = self.upload_set(device, &merged)?; - (Some(merged), Some(address), count) - } - }; - for noted in &self.root_tables { - write_fields( - ¬ed.upload, - noted.address, - address.unwrap_or(noted.address), - count, - )?; - } - let replaced = self.resident.replace(Resident { - live: Live::Held(live), - merged, - address, - count, - }); - // A table held already, made of the list before it changed, may hold a gone buffer's - // pages last, whose release runs the program's code (a deallocator), which may not run - // here: on the scheduler's thread, under its lock and this state's. It goes at once all - // the same, as Metal lets go of a buffer no submitted command buffer holds, on a handler - // thread. - if let Some(Resident { - live: Live::Held(table), - .. - }) = replaced - { - device.let_go_elsewhere(Box::new(table)); - } - Ok(()) - } - - /// As its first batch is submitted (the module docs), on the thread that submits it, under - /// the scheduler's lock and its own, after that batch's checks: Metal's submissions of its first - /// event group ([`State::event_group`]) found rebound, or holding a detached buffer, go to - /// `failing`, each to fail as its own batch is submitted (`State::failing_at`). What the - /// group's commands took is judged and held under one lock of the device's buffers over host - /// pages (`Submitting`), so a detach comes either before (and fails the submission) or after - /// (and waits for the group's work); a later group's is judged and held as its own first - /// batch is submitted (`State::failing_at`). Nothing here lets pages go: the weak holds become - /// strong, and what it held strongly it retains. - /// `Ok(false)`, changing nothing, while a rebind since its commit has encoders of it, which - /// `buffer`'s rebinds mark, to encode again (`reencode.rs`): read under the lock its rebinds - /// mark them under, so a rebind comes either before this submission (which waits for them) - /// or after it (which keeps the old pages for this group). From here it waits for no - /// rebind's replay; its encoders' logs stay until its release - /// (`CommandBufferShared::complete`). - pub(super) fn first_submission( - &mut self, - device: &Device, - buffer: &CommandBufferShared, - ) -> Result { - let shared = device.shared(); - let mut verdicts = BTreeMap::new(); - let mut holds = SubmittedHolds::new(device); - let group = self.event_group(0); - let parts = self.group_parts(&group); - let encoders = self.first_parts(parts.clone()); - let moved = { - let mut submitting = shared.rebinds.submitting(); - if buffer.reencode_pending() { - return Ok(false); - } - self.submitted = true; - self.judged_to = group.end; - if group.end == self.batches.all().len() { - submitting.submitted_now(&shared.rebinds, buffer); - } - self.judge_group( - &mut submitting, - &encoders, - parts.clone(), - &mut verdicts, - &mut holds, - ) - }; - if !holds.is_empty() { - self.submitted_holds.push((group.end - 1, holds)); - } - // Its last group is submitted: a rebind from here keeps the old pages for it. - if group.end == self.batches.all().len() { - self.held_to_submission.clear(); - } - // The list changed since the commit: what it listed is listed again, a rebind having - // ended its use, and its resident set made of the list as it stands. - let changed = self - .listing - .as_ref() - .is_some_and(|listing| listing.generation != shared.live_buffers.generation()); - if changed || moved { - if let Some(listing) = &self.listing { - shared.live_buffers.reach(&listing.used); - } - } - self.hold_live(device)?; - // The tables host steps before now resolved against go at once, off this thread, under - // whose locks the last hold of a released buffer's pages may not go - // (`State::keep_stepped_table`). - for earlier in self.stepped_tables.drain(..) { - device.let_go_elsewhere(Box::new(earlier)); - } - // The resident tables of its work on the GPU alone, pointed at the set as it lies now - // where the list changed or a buffer of it moved since the commit. - if !self.replay_tables.is_empty() { - self.point_replay_tables(device, changed || moved)?; - } - // Found here, against the pages and the table fixed for every later batch; each fails - // at its own batch, after its check. - self.failing = self.failing_submissions(&verdicts); - // Their names let go; the listing released without the lock. - self.judged(&encoders, parts); - let State { - retained, listing, .. - } = self; - // An empty listing (a command buffer that used no no-copy buffer and no heap) holds - // nothing to let go of. - if let Some(Listing { used, .. }) = listing.take() { - if used != UsedResources::default() { - retained.push(Box::new(used)); - } - } - self.root_tables.clear(); - self.root_ranges.clear(); - Ok(true) - } - - /// Metal's submissions (the split) that hold an encoder `verdicts` fails, by their encoders, - /// each with the failure of its encoders: `DetachedBacking` where one holds a detached buffer, - /// else `EncodedUseRebound`. - fn failing_submissions( - &self, - verdicts: &BTreeMap, - ) -> Vec<(Range, CommandBufferError)> { - if verdicts.is_empty() { - return Vec::new(); - } - self.metal_submissions() - .into_iter() - .filter_map(|(_, encoders)| { - let mut failure = None; - for encoder in encoders.clone() { - if let Some(error) = verdicts.get(&encoder) { - judge_one(&mut failure, *error); - } - } - failure.map(|failure| (encoders, failure)) - }) - .collect() - } - - /// As batch `index` is submitted, after the first submission, where it begins a later event - /// group ([`State::event_group`]): that group's commands are judged and held as the first - /// submission judged the first group's, as Metal decides each submission as it submits it, - /// those found rebound or holding a detached buffer going to `failing`. `false`, changing - /// nothing, while a rebind since the last group's submission has encoders of this one, which - /// `buffer`'s rebinds mark, to encode again (`reencode.rs`): read under the lock its rebinds - /// mark them under, so a rebind comes either before this group's submission (which waits for - /// them) or after it. From the last group on it waits for no rebind's replay. - pub(super) fn later_group( - &mut self, - device: &Device, - buffer: &CommandBufferShared, - index: usize, - ) -> bool { - let group = self.event_group(index); - if index == 0 || group.start != index { - return true; - } - let shared = device.shared(); - let parts = self.group_parts(&group); - let encoders = self.first_parts(parts.clone()); - let mut verdicts = BTreeMap::new(); - let mut holds = SubmittedHolds::new(device); - { - let mut submitting = shared.rebinds.submitting(); - if buffer.reencode_pending() { - return false; - } - self.judged_to = group.end; - if group.end == self.batches.all().len() { - submitting.submitted_now(&shared.rebinds, buffer); - } - self.judge_group( - &mut submitting, - &encoders, - parts.clone(), - &mut verdicts, - &mut holds, - ); - } - // Its last group is submitted: a rebind from here keeps the old pages for it. - if group.end == self.batches.all().len() { - self.held_to_submission.clear(); - } - self.judged(&encoders, parts); - let failing = self.failing_submissions(&verdicts); - self.failing.extend(failing); - if !holds.is_empty() { - self.submitted_holds.push((group.end - 1, holds)); - } - true - } - - /// Whether it completed or failed: no rebind encodes it again. - pub(super) fn finished(&self) -> bool { - matches!( - self.status, - CommandBufferStatus::Completed | CommandBufferStatus::Error - ) - } - - /// The first part of the event groups not judged yet ([`State::later_group`]): the parts from - /// it on are what a rebind may encode again (`reencode.rs`). - pub(super) fn unjudged_parts(&self) -> usize { - match self.batches.all().len() { - len if self.judged_to >= len => self.recorded.len(), - _ => self.batch_range(self.judged_to).start, - } - } - - /// As batch `index` is submitted, after its checks ran: the segments a host step recorded - /// for it since the first submission are judged and held as the first submission judged the - /// rest (`State::first_submission`); then each of Metal's submissions found failing that - /// begins in the batch, or that holds such a segment, runs nothing from the batch on - /// (`State::fail_part`), unless its check failed it already, which keeps the check's code, - /// or the commit's failure failed every encoder of it (`State::failed_at_commit`); and the - /// command buffer fails with the first such submission's failure unless it failed already, - /// keeping its first code. Whether one of them failed rebound here (`EncodedUseRebound`), - /// for the caller to announce without the lock: a rebound submission runs nothing where - /// Metal's runs, whatever the command buffer failed with before. - pub(super) fn failing_at(&mut self, device: &Device, index: usize) -> bool { - let range = self.batch_range(index); - let group = self.event_group(index); - let mut later = BTreeMap::new(); - let mut holds = SubmittedHolds::new(device); - let mut found_later = None; - { - let mut submitting = device.shared().rebinds.submitting(); - let State { - recorded, retained, .. - } = self; - for part in &mut recorded[range.clone()] { - let segments = part.segments.iter_mut().filter_map(|s| s.recorded.as_mut()); - for done in segments { - let found = submitting.submit(&mut done.taken, retained, &mut holds); - judge(&mut later, part.encoder, found.failure()); - done.taken.judged(); - // Recorded after the first submission: by a host step. - if found.failure() == Some(CommandBufferError::EncodedUseRebound) { - found_later.get_or_insert((part.encoder, Recording::HostStep)); - } - } - } - } - if let Some((encoder, recording)) = found_later { - if let Some(kind) = self.ended.get(encoder).map(|record| record.kind) { - self.rebound_use.get_or_insert(ReboundUse { - encoder, - kind, - at: ReboundAt::Segment(recording), - }); - } - } - if !holds.is_empty() { - self.submitted_holds.push((group.end - 1, holds)); - } - if self.failing.is_empty() && later.is_empty() { - return false; - } - let here: BTreeSet = self.recorded[range.clone()] - .iter() - .map(|part| part.encoder) - .collect(); - let mut due = Vec::new(); - self.failing.retain(|(encoders, failure)| { - let begins = encoders.clone().any(|encoder| here.contains(&encoder)); - if begins { - due.push((encoders.clone(), *failure)); - } - !begins - }); - due.extend(self.failing_submissions(&later)); - due.retain(|(encoders, _)| !self.check_failed(encoders) && !self.commit_failed(encoders)); - if due.is_empty() { - return false; - } - due.sort_by_key(|(encoders, _)| encoders.start); - let State { - recorded, - retained, - ended, - .. - } = self; - let failing = |encoder: &usize| due.iter().any(|(encoders, _)| encoders.contains(encoder)); - for part in recorded[range.start..] - .iter_mut() - .filter(|part| failing(&part.encoder)) - { - State::fail_part(part, ended, retained); - } - self.unrunnable - .extend(due.iter().flat_map(|(encoders, _)| encoders.clone())); - if self.failure.is_none() { - self.failure = Some(due[0].1); - } - due.iter() - .any(|(_, failure)| *failure == CommandBufferError::EncodedUseRebound) - } - - /// The batches of the event group batch `index` lies in: the run of batches around it that - /// no event (or binary semaphore) wait or signal splits. Metal holds what a group's - /// submissions use from the group's submission until its work completed (a buffer's detach - /// waits for that work, and one with its later work behind a wait detaches at once, measured - /// on the M3 Max), and the runtime judges and holds a group's commands as its first batch is - /// submitted ([`State::first_submission`], [`State::failing_at`]), letting go as its last - /// batch's work completed (`CommandBufferShared::holds_until`). - pub(super) fn event_group(&self, index: usize) -> Range { - let batches = self.batches.all(); - let splits = |at: usize| { - at == 0 - || at >= batches.len() - || !batches[at].waits.is_empty() - || !batches[at].binary_waits.is_empty() - || !batches[at - 1].signals.is_empty() - || !batches[at - 1].binary_signals.is_empty() - }; - let start = (0..=index).rev().find(|&at| splits(at)).unwrap_or(0); - let end = (index + 1..=batches.len()) - .find(|&at| splits(at)) - .unwrap_or(batches.len()); - start..end - } - - /// The parts of the ended encoders the batches of `group` hold. - fn group_parts(&self, group: &Range) -> Range { - let start = self.batch_range(group.start).start; - let end = self.batch_range(group.end - 1).end; - start..end - } - - /// The ended encoders whose first part lies among `parts`, in order. - fn first_parts(&self, parts: Range) -> Vec { - parts - .filter(|&at| at == 0 || self.recorded[at - 1].encoder != self.recorded[at].encoder) - .map(|at| self.recorded[at].encoder) - .collect() - } - - /// Judge and hold what `encoders` took, and the segments of `parts` recorded so far, against - /// where their buffers lie now (`Submitting::submit`): their failures go to `verdicts`, their - /// holds to `holds`, their pages to what the command buffer retains. Whether a buffer one took - /// lies elsewhere now. - fn judge_group( - &mut self, - submitting: &mut Submitting<'_>, - encoders: &[usize], - parts: Range, - verdicts: &mut BTreeMap, - holds: &mut SubmittedHolds, - ) -> bool { - let mut moved = false; - let State { - ended, - recorded, - retained, - rebound_use, - .. - } = self; - for &at in encoders { - let Some(record) = ended.get_mut(at) else { - continue; - }; - let found = submitting.submit(&mut record.taken, retained, holds); - moved |= found.moved; - judge(verdicts, at, found.failure()); - if found.failure() == Some(CommandBufferError::EncodedUseRebound) { - let at_commands = match (&record.replay, &record.refused) { - (None, _) => ReboundAt::Unlogged(record.unlogged), - (Some(_), Some(refusal)) => ReboundAt::Refused(refusal.clone()), - (Some(_), None) => ReboundAt::NotEncodedAgain, - }; - rebound_use.get_or_insert(ReboundUse { - encoder: at, - kind: record.kind, - at: at_commands, - }); - } - } - for part in &mut recorded[parts] { - let kind = ended.get(part.encoder).map(|record| record.kind); - for segment in &mut part.segments { - let recording = match (segment.gpu_alone, segment.stepped) { - (true, _) => Recording::GpuAlone, - (false, true) => Recording::HostStep, - (false, false) => Recording::Commit, - }; - let Some(done) = segment.recorded.as_mut() else { - continue; - }; - let found = submitting.submit(&mut done.taken, retained, holds); - moved |= found.moved; - judge(verdicts, part.encoder, found.failure()); - if let (Some(CommandBufferError::EncodedUseRebound), Some(kind)) = - (found.failure(), kind) - { - rebound_use.get_or_insert(ReboundUse { - encoder: part.encoder, - kind, - at: ReboundAt::Segment(recording), - }); - } - } - } - moved - } - - /// Let go of the names of what `encoders` and the segments of `parts` took, once judged. - fn judged(&mut self, encoders: &[usize], parts: Range) { - for &at in encoders { - if let Some(record) = self.ended.get_mut(at) { - record.taken.judged(); - } - } - let segments = self.recorded[parts] - .iter_mut() - .flat_map(|part| part.segments.iter_mut()) - .filter_map(|segment| segment.recorded.as_mut()); - for done in segments { - done.taken.judged(); - } - } - - /// Whether the commit's failure failed every encoder of Metal's submission of `encoders`. - fn commit_failed(&self, encoders: &Range) -> bool { - self.failed_at_commit - .as_ref() - .is_some_and(|failed| encoders.clone().all(|encoder| failed.fails(encoder))) - } -} - -/// Note `failure`, an encoder's at `at`, among `verdicts`: a detached buffer's over a rebound one. -fn judge( - verdicts: &mut BTreeMap, - at: usize, - failure: Option, -) { - if let Some(failure) = failure { - let mut held = verdicts.remove(&at); - judge_one(&mut held, failure); - if let Some(held) = held { - verdicts.insert(at, held); - } - } -} - -/// `failure` joined to `held`: `DetachedBacking` wins over `EncodedUseRebound`. -fn judge_one(held: &mut Option, failure: CommandBufferError) { - let detached = |error: &CommandBufferError| *error == CommandBufferError::DetachedBacking; - if held - .as_ref() - .is_none_or(|held| !detached(held) && detached(&failure)) - { - *held = Some(failure); - } -} - -impl State { - /// Refuse (internal) to submit batch `range`'s parts where one of an encoder that recorded - /// nothing for a command (`Taken::dead`, of its own or of a segment of it), or of one whose - /// submission failed rebound or detached (`unrunnable`), still holds work: the structural - /// hold, that a command buffer holding a detached or rebound use never submits that use's - /// Vulkan work. A build with debug assertions stops there. - pub(super) fn runs_nothing_unrunnable(&self, range: Range) -> Result<(), Error> { - let held = self.recorded[range].iter().any(|part| { - let dead = self - .ended - .get(part.encoder) - .is_some_and(|record| record.taken.dead()); - (dead || self.unrunnable.contains(&part.encoder)) && !part.raws.is_empty() - }); - debug_assert!(!held, "a detached or rebound use's work submitted"); - match held { - true => Err(crate::error::internal( - "a detached or rebound use's work submitted", - )), - false => Ok(()), - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs deleted file mode 100644 index ca0421d4c..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ /dev/null @@ -1,482 +0,0 @@ -//! A command buffer's groups of encoders recorded into one `VkCommandBuffer` -//! (`encoder_fold.rs`): the group its tail holds, which encoder joins it, its logs, and the -//! failures and left out work that split a group. - -use super::{FailedEncoders, FailedSignals, Failure, State}; -use crate::encoder::Overwrite; -use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Refusal, Stashed}; -use crate::render_target::PassKey; -use crate::replay::Replay; -use crate::resource::ResourceKey; -use crate::tracker::Summary; -use crate::used_resources::EncoderKind; -use crate::work_counts::Counters; -use std::collections::BTreeSet; -use std::ops::Range; - -impl State { - /// The group the encoder opening now joins, asking `joining`, where its - /// command buffer's tail holds one it may join (`encoder_fold.rs`'s **Where**): taken, with - /// the tail, which the encoder records into, and, where it is the group's second encoder, the - /// group's order joined to its first part's summary (`Fold::order`). `None` where it joins - /// none, the group left in place: the encoder's open closes it once it opened - /// ([`close_fold`](Self::close_fold)). A refusal is counted by its reason ([`Refusal`]): the - /// group's, or, where the tail holds none, why the encoder before left none - /// ([`unfolded`](Self::unfolded)); the command buffer's first encoder is refused nothing. On - /// a device that splits at aliases - /// (`alias_split.rs`), a render encoder whose pass records at its end joins as any encoder: - /// the first command it records into the tail at its end, where its pass or a draw of it uses - /// an image over bytes the group's earlier encoders wrote, goes in a new `VkCommandBuffer`. - pub(crate) fn join_fold( - &mut self, - joining: Joining, - trail: bool, - counts: &Counters, - ) -> Option> { - let Some(fold) = self.fold.as_ref() else { - if let Some(why) = self.unfolded { - counts.fold_refused(why); - } - return None; - }; - let refused = if !fold.admits(joining) { - Some(Refusal::Kind) - } else if self.tail != Some(fold.tail) { - Some(Refusal::Tail) - } else if self.batches.all().len() != fold.batches || self.batches.signals_pending() { - Some(Refusal::Batch) - } else if self.predicated || self.protection.options() != 0 || trail { - Some(Refusal::State) - } else { - None - }; - if let Some(why) = refused { - counts.fold_refused(why); - return None; - } - // Its second encoder orders after its first part, as that part's end left it. - let first = match fold.members.len() { - 1 => Some(&self.recorded.get(fold.leader)?.summary), - _ => None, - }; - self.tail = None; - let mut fold = self.fold.take()?; - if let Some(first) = first { - fold.order.join(first); - } - // It records into the tail outside any render pass instance (`encoder_fold.rs`'s - // **Continued passes**). - fold.end_open(); - Some(fold) - } - - /// What the render pass instance the group the tail holds left open renders, where it left - /// one (`encoder_fold.rs`'s **Continued passes**): what a render encoder opening now may - /// continue. - pub(crate) fn open_pass(&self) -> Option { - let fold = self.fold.as_ref()?; - let open = fold.open.as_ref()?; - (self.tail == Some(fold.tail)).then(|| open.key().clone()) - } - - /// The group whose tail holds the render pass instance `key` renders open, taken for the - /// encoder that continues it (`encoder_fold.rs`'s **Continued passes**), as - /// [`join_fold`](Self::join_fold) gives a joining encoder its group, its order noted - /// after the instance's draws so far: where the tail still holds that instance, the group - /// admits an encoder (its tail and batch, the command buffer's command predication and - /// protection options; the encoder trail is the caller's), and `writes` admits the group's - /// order (on a device that splits at aliases, where no image the encoder's pass uses meets - /// the bytes the group's encoders wrote: `AliasWrites::continues`; else nothing). `None` else, - /// the group left in place; one `writes` refused is counted as a split at aliases - /// (`WorkCounts::command_buffers_split_at_aliases`): the pass goes in a `VkCommandBuffer` of - /// its own. - pub(crate) fn continue_pass( - &mut self, - key: &PassKey, - counts: &Counters, - writes: impl FnOnce(&FoldOrder) -> bool, - ) -> Option> { - let fold = self.fold.as_ref()?; - let open = fold.open.as_ref()?; - let admits = *open.key() == *key - && self.tail == Some(fold.tail) - && self.batches.all().len() == fold.batches - && !self.batches.signals_pending() - && !self.predicated - && self.protection.options() == 0; - if !admits { - return None; - } - // Its second encoder orders after its first part, as that part's end left it: joined - // here, and cleared again where `writes` refuses it, so a group of one encoder holds - // its order empty. - let first = match fold.members.len() { - 1 => Some(&self.recorded.get(fold.leader)?.summary), - _ => None, - }; - let fold = self.fold.as_mut()?; - if let Some(first) = first { - fold.order.join(first); - } - if !writes(&fold.order) { - if first.is_some() { - fold.order.clear(); - } - counts.command_buffer_split_at_aliases(); - return None; - } - self.tail = None; - let mut fold = self.fold.take()?; - fold.order.continued(); - // The instance is the encoder's own from here: its pass holds it, and ends it or leaves - // it open again as it ends. - fold.open = None; - counts.render_pass_continued(); - Some(fold) - } - - /// An encoder that asked a group ended (`end`), its last `VkCommandBuffer` the tail: it goes on in the - /// group it joined where the tail is still that group's and it leaves nothing that needs a - /// boundary, else the group closes and it begins one of its own where it may lead one (its - /// one part leaves nothing that needs a boundary, the command buffer used no command - /// predication, and its protection options are 0). Its log, which it did not keep, goes with - /// the group it ends in; the logs that come back are the caller's to give back without this - /// lock ([`close_fold`](Self::close_fold)). - pub(crate) fn fold_ended(&mut self, end: FoldEnd, counts: &Counters) -> Vec { - let FoldEnd { - joining, - fold, - in_tail, - encoder, - ends, - summary, - log, - open, - } = end; - // The group a render encoder that might have continued its open render pass instance - // kept, where it did not (`encoder_fold.rs`'s **Continued passes**), closes first. - let mut unkept = match fold.is_some() { - true => Vec::new(), - false => self.close_fold(counts), - }; - // Why no group goes on past it, where none may. - self.unfolded = match (ends, joining) { - (Some(why), _) => Some(why), - (None, None) => Some(Refusal::State), - (None, Some(_)) if self.predicated || self.protection.options() != 0 => { - Some(Refusal::State) - } - (None, Some(_)) => None, - }; - let leads = joining.filter(|_| self.unfolded.is_none()); - let mut log = log.map(|(log, executions)| Stashed { - encoder, - log, - executions, - }); - // The render pass instance it left open in its last `VkCommandBuffer`, the tail, goes on - // with its group, where the group goes on past it; else it ends here. - let mut open = match open { - Some(open) if Some(open.raw()) != self.tail => { - open.end(); - None - } - open => open, - }; - if let Some(mut fold) = fold { - fold.members.end = encoder + 1; - if let Some(record) = self.ended.get_mut(encoder) { - record.in_tail = in_tail; - } - fold.stashed.extend(log.take()); - let goes_on = self.tail == Some(fold.tail); - if let (Some(joining), Some(summary), true) = (leads, &summary, goes_on) { - fold.went_on(joining, summary); - fold.batches = self.batches.all().len(); - fold.open = open; - self.fold = Some(fold); - return unkept; - } - self.fold = Some(fold); - unkept.extend(self.close_fold(counts)); - } - match (leads, self.tail) { - (Some(joining), Some(tail)) => { - // The tail is its last `VkCommandBuffer`. - if let Some(record) = self.ended.get_mut(encoder) { - record.in_tail = true; - } - let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len()); - // Its stash and its order take the room the command buffer's lists keep - // (`spare_states.rs`). - let mut stashed = self.stash_room.take().unwrap_or_default(); - stashed.extend(log); - let order = self.order_room.take().unwrap_or_else(FoldOrder::none); - let open = open.take(); - self.fold = Some(Box::new(Fold::begun( - tail, - (leader, encoder), - (batches, joining), - (stashed, order, open), - ))); - } - (Some(_), None) => { - self.unfolded = Some(Refusal::Tail); - unkept.extend(log.map(|stashed| stashed.log)); - } - (None, _) => unkept.extend(log.map(|stashed| stashed.log)), - } - if let Some(open) = open { - open.end(); - } - unkept - } - - /// Join `worked`, the uses and fence waits of an encoder whose commands went into the - /// `VkCommandBuffer` of the group it joined, to the summary of that group's first part, - /// `leader`, which the batch's submission plans the group's barrier and waits by; and - /// `overwrites`, its whole writes that stand as that part's would (`Fold::overwrites_join`), - /// to that part's, which the submission judges them by. - pub(crate) fn join_leader( - &mut self, - leader: usize, - worked: Summary, - overwrites: Vec, - ) { - if let Some(part) = self.recorded.get_mut(leader) { - part.summary.join(worked); - part.overwrites.extend(overwrites); - } - } - - /// Close the group the command buffer's tail holds, where it holds one: no encoder joins it - /// any more. Where it holds more than one encoder, each notes the group's encoders, which a - /// failure and a rebind take together (`split_failure`, `reencode.rs`), and the logs its - /// members did not keep are kept where one member kept its own and the command buffer used no - /// command predication, so a rebind can encode the group again; else they are held until the - /// commit, whose failure may split the group ([`split_failure`](Self::split_failure)). A lone - /// encoder's comes back, for the caller to give back to the device's spares without this lock - /// (`replay.rs`). A group of more gives the room of its stash back, emptied, for the next - /// group's; and every group, the room of its order (`spare_states.rs`). - pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec { - let Some(mut fold) = self.fold.take() else { - return Vec::new(); - }; - fold.end_open(); - let Fold { - members, - mut stashed, - mut order, - .. - } = *fold; - order.clear(); - self.order_room = Some(order); - if members.len() < 2 { - return stashed.into_iter().map(|stashed| stashed.log).collect(); - } - for record in &mut self.ended[members.clone()] { - record.group = Some(members.clone()); - } - let logged = (self.ended[members.clone()].iter()).any(|record| record.replay.is_some()); - if !logged || self.predicated { - self.held_logs.append(&mut stashed); - self.stash_room = Some(stashed); - return Vec::new(); - } - let mut unkept = Vec::new(); - for Stashed { - encoder, - log, - executions, - } in stashed.drain(..) - { - let bytes = log.bytes(); - match self.keep_replay(encoder, Some(log), executions) { - Some(log) => unkept.push(log), - None => counts.replay_log_kept(bytes), - } - } - self.stash_room = Some(stashed); - unkept - } - - /// At the commit, `failure` and the work a command-predication record left out - /// (`State::left_out_from`) as the groups of encoders recorded into one `VkCommandBuffer` - /// take them (`encoder_fold.rs`'s **Failed**): a group they fail or leave out in part is - /// split, each encoder of it that runs to be encoded again from its log, kept now, into - /// `VkCommandBuffer`s of its own before the first submission (`reencode.rs`), and the group's - /// shared one never submitted; where one of them cannot be encoded again - /// ([`encodes_again`](Self::encodes_again)), the failure fails that whole group instead (a - /// failure that fails those encoders alone, with no error, where the commit has none). A - /// command buffer with a submission check (`checks.rs`) splits so each group whose shared - /// `VkCommandBuffer` holds commands of more than one of Metal's submissions - /// ([`in_tail`](Self::in_tail)), those commands' encoders encoded again apart, so a check - /// fails one submission's encoders alone; one of them that cannot be encoded again exactly - /// (no log, or work of a segment's, whose encoding again records it otherwise) leaves the group - /// whole, and a check that fails one of those submissions fails each of them - /// (`State::fail_submission`). With the failure, the encoders that run of each group split, - /// the units to encode again. The logs held for the commit that no split takes stay held, - /// for the command buffer's release to give back to the device's spares - /// ([`unsplit_logs`](Self::unsplit_logs)). - pub(super) fn split_failure( - &mut self, - failure: Option, - ) -> (Option, Vec>) { - let mut units = Vec::new(); - let left_out = self.left_out_from; - let checked = self.check.is_some(); - if failure.is_none() && left_out.is_none() && !checked { - return (failure, units); - } - let groups: BTreeSet<(usize, usize)> = (self.ended.iter()) - .filter_map(|record| record.group.as_ref()) - .map(|group| (group.start, group.end)) - .collect(); - // Each ended encoder's submission among Metal's, where a check is set. - let mut submission = Vec::new(); - if checked && !groups.is_empty() { - for (at, (_, encoders)) in self.metal_submissions().into_iter().enumerate() { - submission.extend(encoders.map(|_| at)); - } - } - let mut whole = BTreeSet::new(); - for (start, end) in groups { - let runs = |encoder: &usize| { - Failure::runs(failure.as_ref(), *encoder) - && left_out.is_none_or(|first| *encoder < first) - }; - let running: Vec = (start..end).filter(runs).collect(); - if running.is_empty() { - continue; - } - if running.len() < end - start { - match running.iter().all(|&encoder| self.encodes_again(encoder)) { - true => units.push(self.split_apart(start..end, running)), - false => whole.extend(running), - } - continue; - } - // Nothing fails it: where a check may fail one of the submissions whose commands its - // shared `VkCommandBuffer` holds and not another, those commands' encoders are - // encoded again apart, where each is so exactly, its work no segment's. - let tail = self.in_tail(start..end); - let first = tail.first().and_then(|&encoder| submission.get(encoder)); - let last = tail.last().and_then(|&encoder| submission.get(encoder)); - let exact = |encoder: &usize| { - self.encodes_again(*encoder) - && (self.recorded.iter()) - .filter(|part| part.encoder == *encoder) - .all(|part| part.segments.is_empty()) - }; - if checked && first != last && tail.iter().all(exact) { - units.push(self.split_apart(start..end, tail)); - } - } - if whole.is_empty() { - return (failure, units); - } - let ended = self.ended.len(); - let failure = match failure { - Some(mut failure) => { - failure.encoders = failure.encoders.with(&whole, ended); - failure - } - None => Failure { - encoders: FailedEncoders::Set(whole), - signals: FailedSignals::Every, - error: None, - }, - }; - (Some(failure), units) - } - - /// `encoders` of `group`, a group recorded into one `VkCommandBuffer`, to be encoded again - /// apart, their logs kept: the group's encoders share no `VkCommandBuffer` any more, the - /// others' commands lying in `VkCommandBuffer`s of their own. The unit to encode again. - fn split_apart(&mut self, group: Range, encoders: Vec) -> Vec { - self.keep_held_logs(&encoders); - for record in &mut self.ended[group] { - record.group = None; - } - encoders - } - - /// The encoders of `group`, a group recorded into one `VkCommandBuffer`, whose commands lie - /// there, some or all (`EncoderRecord::in_tail`): its first, and each later one a command of - /// which recorded there. - pub(super) fn in_tail(&self, group: Range) -> Vec { - group - .filter(|&encoder| self.ended.get(encoder).is_some_and(|record| record.in_tail)) - .collect() - } - - /// Whether ended encoder `encoder`, of a group recorded into one `VkCommandBuffer`, may be - /// encoded again apart: it does as its command buffer's command predication holds it - /// ([`encodes_again_apart`](Self::encodes_again_apart)), and its log is kept, or held for the - /// commit. - pub(super) fn encodes_again(&self, encoder: usize) -> bool { - self.encodes_again_apart(encoder) - && (self.ended[encoder].replay.is_some() - || self.held_logs.iter().any(|held| held.encoder == encoder)) - } - - /// Keep the logs held for the commit of `encoders`, each its own, for an encoding again. - pub(super) fn keep_held_logs(&mut self, encoders: &[usize]) { - for &encoder in encoders { - let Some(at) = (self.held_logs.iter()).position(|held| held.encoder == encoder) else { - continue; - }; - let Stashed { - log, executions, .. - } = self.held_logs.swap_remove(at); - if let Some(log) = self.keep_replay(encoder, Some(log), executions.clone()) { - self.held_logs.push(Stashed { - encoder, - log, - executions, - }); - } - } - } - - /// Whether ended encoder `encoder`, of a group recorded into one `VkCommandBuffer`, encodes - /// again apart as the command buffer's command predication holds it: every one where it used - /// none; a compute encoder whose unit nothing reached into or out of (`Predication::alone`); - /// a blit encoder, which belongs to no unit (`predication.rs`). - pub(super) fn encodes_again_apart(&self, encoder: usize) -> bool { - !self.predicated - || (self.ended.get(encoder)).is_some_and(|record| record.kind != EncoderKind::Compute) - || self.predication.alone(encoder) - } - - /// The logs held for the commit that no split took (`split_failure`): for the command - /// buffer's release to give back to the device's spares without this lock, on its queue's - /// handler thread, as it gives back the logs its encoders kept (`replay.rs`). - pub(super) fn unsplit_logs(&mut self) -> Vec { - self.held_logs.drain(..).map(|held| held.log).collect() - } - - /// `encoders`, a group's encoders the commit split that run (`split_failure`), whose - /// encoding again failed: they run nothing after all, as the failure's encoders do, the - /// shared `VkCommandBuffer` among them never submitted (`encoder_fold.rs`'s **Failed**). - pub(super) fn fail_unsplit(&mut self, encoders: &[usize]) { - let failed: BTreeSet = encoders.iter().copied().collect(); - let State { - recorded, - retained, - ended, - .. - } = self; - for part in recorded - .iter_mut() - .filter(|part| failed.contains(&part.encoder)) - { - State::fail_part(part, ended, retained); - } - let ended = self.ended.len(); - self.failed_at_commit = Some(match self.failed_at_commit.take() { - Some(before) => before.with(&failed, ended), - None => FailedEncoders::Set(failed), - }); - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/follow.rs b/crates/metal2vulkan-runtime/src/command_buffer/follow.rs deleted file mode 100644 index b3cdd5881..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/follow.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! A command buffer completes after the command buffer of another queue whose GPU signal its work -//! waited for (`completion.rs`, "After what it waited for"): its transition to `Completed` waits, -//! its place in its own queue's context kept, until that command buffer's transition has its -//! status final and ran its completion-seen handlers, which never block, and reaches its completed -//! handlers, which may. Those and its own then run on two handler threads, the signaller's -//! dispatched first, as Metal runs two queues' handlers on two threads. Which starts first is not -//! guaranteed, as on Metal, which on the M3 Max (macOS 27.0.1) started the waiter's first in 0.1-6% -//! of rounds with plain events. -//! -//! - **Who follows whom.** A command buffer whose last batch keeps GPU signals carries a -//! [`Follow`], which the events hold beside those signals until its transition reaches its -//! completed handlers (`EventTimeline::signallers`). A batch of another queue's command buffer -//! that waits for one of those signals takes it as it is submitted, so its command buffer knows -//! whom it completes after. -//! - **Only behind what blocks nothing.** Metal runs each queue's transitions in their own -//! context: while one of a queue's handlers blocks, another queue's transitions go on -//! (`contexts/mod.rs`). So a transition waits for the signaller's only where the signaller's -//! transition was posted to its context and nothing there before it may block -//! ([`Follow::leads`]): no item before it, nor what a thread runs there, runs a handler of the -//! program's but completion-seen handlers, which never block, or waits for one -//! (`Run::may_block`). An earlier command buffer's transition with no scheduled, submission or -//! completed handler left ends without the program, however long the host keeps the thread -//! that runs it off the CPU, so the waiting transition waits behind it: a program whose command -//! buffer waited on the GPU for another queue's never sees it complete while that one reads -//! short of `Completed` only because a host thread was slow. Its release of what it retained -//! may still run a deallocator of the program's (`program_objects.rs`), which the waiting -//! transition waits behind too. An earlier command buffer of the signaller's queue whose waiters -//! returned runs nothing there any more: a context is done with an item before the item's hold -//! of its command buffer goes, which lets those waiters return (`contexts/mod.rs`). The -//! signaller's transition runs no code of the program's that may block before its completed -//! handlers, so the wait ends once a thread takes it and runs its completion-seen handlers, and -//! it holds no thread meanwhile: a gate in the waiting transition's context -//! (`contexts/lines.rs`). Behind an item that may block, the waiting transition goes on, as -//! Metal's does. The completion turns take the signaller's batch before the waiting one's -//! (`completion.rs`), so the signaller's transition is posted by the time the waiting one's is. -//! Whether it leads is one look at its context's first item and first item that may block -//! (`Lines::leads`), however many items the context holds. -//! - **Nothing of the signaller is held.** A [`Follow`] names its command buffer's transition by -//! its place in its context alone: the waiter that completes the follower never holds the -//! signaller's last reference, so never the device's. - -use super::super::contexts::Contexts; -use super::super::device::lock; -use super::super::event::EventShared; -use super::Item; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; - -/// The command buffer whose last batch's GPU signals another queue's command buffers may wait for, -/// as they complete after it (the module docs). -#[derive(Debug)] -pub(crate) struct Follow { - /// Its queue's identity: its context's. - queue: u64, - /// The gates of the transitions posted behind its own, each a context and a gate's token, - /// until its own reaches its completed handlers; `None` from then on. - gates: Mutex>>, - /// The place its transition to `Completed` or `Error` took in its context as it was posted - /// ([`Follow::posted`], `Contexts::post`); 0 before then, and where it ran without a post. - at: AtomicU64, -} - -/// What a command buffer's transition to `Completed` or `Error` lets go as it reaches its completed -/// handlers: -/// its [`Follow`], and its last batch's kept GPU signals, by event and index, from which no -/// command buffer that waits for one completes after it any more (`EventShared::released`). -pub(super) struct Release { - pub(super) follow: Arc, - pub(super) signals: Vec<(Arc, u64)>, -} - -impl Follow { - /// The follow of a command buffer of the queue `queue`. - pub(super) fn new(queue: u64) -> Follow { - Follow { - queue, - gates: Mutex::new(Some(Vec::new())), - at: AtomicU64::new(0), - } - } - - /// Its queue's identity. - pub(super) fn queue(&self) -> u64 { - self.queue - } - - /// Its transition to `Completed` or `Error` was posted to its context, at the place `at`. - pub(super) fn posted(&self, at: u64) { - self.at.store(at, Ordering::Release); - } - - /// Whether its transition to `Completed` or `Error` has not reached its completed handlers and - /// leads its context: it was posted there, and nothing there before it may block. - pub(super) fn leads(&self, contexts: &Contexts) -> bool { - let gates = lock(&self.gates); - gates.is_some() && self.leads_its_context(contexts) - } - - /// Whether its transition leads its context, where it has not reached its completed handlers, - /// so is not done there. - fn leads_its_context(&self, contexts: &Contexts) -> bool { - let at = self.at.load(Ordering::Acquire); - at > 0 && contexts.leads(self.queue, at) - } - - /// Close `gate` of a transition of `queue`'s context until its own transition reaches its - /// completed handlers, where it has not and leads its context: whether it closed it. - pub(super) fn follow(&self, contexts: &Contexts, (queue, gate): (u64, u64)) -> bool { - let mut gates = lock(&self.gates); - let Some(gates) = gates.as_mut() else { - return false; - }; - if !self.leads_its_context(contexts) || !contexts.close(gate) { - return false; - } - gates.push((queue, gate)); - true - } - - /// Its own transition reached its completed handlers: open the gates closed behind it. - pub(super) fn release(&self, contexts: &Contexts) { - let gates = lock(&self.gates).take(); - for (queue, gate) in gates.into_iter().flatten() { - contexts.open(queue, gate); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/gate.rs b/crates/metal2vulkan-runtime/src/command_buffer/gate.rs deleted file mode 100644 index 12840fb4b..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/gate.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! When a command buffer's waiters return: once it finished (its completed handlers ran) and the -//! runtime's threads let go of every reference they took to it. -//! -//! - **Apart from the command buffer.** The [`Gate`] is not part of what it guards, so a thread -//! lets go of its reference first and leaves the gate after: the gate never opens while a -//! runtime thread still holds the command buffer, or anything it held for it. -//! - **Why.** A program that waits for its last command buffer and then drops its last handles -//! destroys the device on its own thread, before the drop returns. Were a runtime thread to -//! hold the last reference instead, the device would go on that thread, perhaps while the -//! program exits, which drivers do not survive (RADV ended such a process with `SIGSEGV`). -//! - **And what fed its work** (`trails.rs`). A thread that made what the command buffer waited -//! for, and holds what it made it with past its signal, holds the device without holding the -//! command buffer: a pool piece between its making's settle and its give-back (a dispatch's or -//! a draw's pipeline), the reaper with what such a piece gave back to a -//! released state, the twin-decode thread between a decode's end and its job's drop. Each opens -//! a trail before its signal and closes it after its last let-go; the command buffer takes the -//! device's trail mark as it completes, and `wait_until_completed` and its timed form, once the -//! gate opened, wait for the trails below it, so the program's drop right after the wait is the -//! device's last (`tests/teardown_threads.rs` holds a dispatch's piece between the two). The -//! gate itself, the status and the completed handlers do not wait for trails. Metal's -//! `waitUntilCompleted` returns after the completed handlers ended too (the M3 Max: 10 µs at the -//! median, 23 µs at p99, a handler of 20 ms included). -//! - **What it does not cover.** A program that learns of the completion otherwise (from a -//! handler, an event the command buffer signals, or its status) may drop its last handles while -//! the runtime's thread still holds the command buffer; the device then goes on that thread. -//! An exit meanwhile waits for that teardown, or skips it once begun (`exit_guard`). -//! - **Notified only where it opened.** A notify is a system call, and one made while a [`Hold`] -//! is alive wakes every waiting thread to a gate it must find shut and sleep on again. The -//! thread that finishes a command buffer holds one over the whole transition -//! (`Transition::run`), so the finish itself never opens the gate: it sets the flag and leaves -//! the notify to that hold's going, one wake of the program's thread where there were two. -//! Counted: `WorkCounts::gate_waits`, `WorkCounts::gate_waits_slept` and -//! `WorkCounts::gate_wakes_found_shut`, which `tests::gate` holds to none. -//! - **Exit.** Once the process is exiting, the threads that would open a gate end, so a wait -//! answers at once, and one already blocked within `exit_guard::WAKE`. - -use crate::device::lock; -use crate::error::{DeadlockCause, TimedOut}; -use crate::exit_guard; -use std::ops::Deref; -use std::sync::{Arc, Condvar, Mutex}; -use std::time::Instant; - -/// A wait that cannot end: the process is exiting. -#[derive(Debug, PartialEq, Eq)] -pub(crate) struct Exiting; - -/// What one wait for a gate did, for the counters its caller keeps -/// (`WorkCounts::gate_waits_slept` and `WorkCounts::gate_wakes_found_shut`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct Waited { - /// The gate was shut when the wait arrived, so it slept at least once. - pub(crate) slept: bool, - /// Notifies it was woken by that found the gate still shut, and slept again: work the thread - /// that opens the gate did between its notify and the gate opening. A sleep that ran out its - /// slice is not one ([`exit_guard::WAKE`] is 50 ms, far past any completion), so each of these - /// is a notify made while the gate could not yet open. - pub(crate) woke_shut: u64, -} - -impl From for DeadlockCause { - fn from(Exiting: Exiting) -> DeadlockCause { - DeadlockCause::Exiting - } -} - -impl From for crate::error::Error { - fn from(exiting: Exiting) -> crate::error::Error { - DeadlockCause::from(exiting).into() - } -} - -/// One command buffer's gate. -#[derive(Debug, Default)] -pub(crate) struct Gate { - state: Mutex, - changed: Condvar, -} - -#[derive(Debug, Default)] -struct GateState { - /// The command buffer finished: its completed handlers ran. - finished: bool, - /// The [`Hold`]s alive. - held: usize, -} - -impl GateState { - fn open(&self) -> bool { - self.finished && self.held == 0 - } -} - -impl Gate { - /// The command buffer finished; the gate opens once no [`Hold`] is left. Whether it notified - /// the waiters, which it does only where the gate opened here: a notify is a system call, and - /// one made while a [`Hold`] is still alive wakes every waiting thread to a gate it must find - /// shut and sleep on again. The thread that finishes a command buffer holds one over the whole - /// transition (`Transition::run`), so that notify was always such a wake, and the - /// [`leave`](Self::leave) of its hold notifies for it a moment later. - pub(crate) fn finish(&self) -> bool { - let opened = { - let mut state = lock(&self.state); - state.finished = true; - state.open() - }; - if opened { - self.changed.notify_all(); - } - opened - } - - /// Whether the waiters may return. - pub(crate) fn is_open(&self) -> bool { - lock(&self.state).open() - } - - /// Block until the gate opens, answering what the wait did ([`Waited`]). `Err` once the - /// process is exiting and it is not open: the runtime's threads that would open it end - /// (`exit_guard`). - pub(crate) fn wait(&self) -> Result { - self.wait_unless(exit_guard::closed) - } - - /// [`Gate::wait`], with `exiting` saying whether the process is exiting (the exit guard's - /// [`closed`](exit_guard::closed), or a test's own). - pub(crate) fn wait_unless(&self, exiting: impl Fn() -> bool) -> Result { - let mut state = lock(&self.state); - let mut did = Waited::default(); - // Whether the sleep before this look ended at a notify rather than at its slice. - let mut notified = false; - let waited = loop { - if state.open() { - break Ok(did); - } - did.woke_shut += u64::from(notified); - if exiting() { - break Err(Exiting); - } - did.slept = true; - let (woke, how) = self - .changed - .wait_timeout(state, exit_guard::WAKE) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state = woke; - notified = !how.timed_out(); - }; - waited - } - - /// Block until the gate opens, or until `deadline`, answering what the wait did ([`Waited`]); - /// at once once the process is exiting, as [`Gate::wait`]. - pub(crate) fn wait_until(&self, deadline: Instant) -> Result { - let mut state = lock(&self.state); - let mut did = Waited::default(); - // Whether the sleep before this look ended at a notify rather than at its slice. - let mut notified = false; - let waited = loop { - if state.open() { - break Ok(did); - } - did.woke_shut += u64::from(notified); - let left = deadline.saturating_duration_since(Instant::now()); - if left.is_zero() || exit_guard::closed() { - break Err(TimedOut); - } - did.slept = true; - let (woke, how) = self - .changed - .wait_timeout(state, left.min(exit_guard::WAKE)) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state = woke; - notified = !how.timed_out(); - }; - waited - } - - fn enter(&self) { - lock(&self.state).held += 1; - } - - fn leave(&self) { - let mut state = lock(&self.state); - state.held -= 1; - let open = state.open(); - drop(state); - if open { - self.changed.notify_all(); - } - } -} - -/// A reference a runtime thread holds (the scheduler's, a completion turn's, a queue -/// context's transition), counted by a [`Gate`]. Its fields drop in declaration order: the -/// reference first, then the count, so the gate cannot open while the reference is alive. -pub(crate) struct Hold { - value: Arc, - _count: Count, -} - -/// A [`Hold`]'s place in its gate's count: the gate opens only once it went. -pub(crate) struct Count(Arc); - -impl Drop for Count { - fn drop(&mut self) { - self.0.leave(); - } -} - -impl Hold { - /// A new reference to `value`, counted by `gate`. - pub(crate) fn new(value: &Arc, gate: &Arc) -> Hold { - gate.enter(); - Hold { - value: Arc::clone(value), - _count: Count(Arc::clone(gate)), - } - } - - /// Whether `self` and `other` hold the same value. - pub(crate) fn same(&self, other: &Hold) -> bool { - Arc::ptr_eq(&self.value, &other.value) - } - - /// Let go of the reference here unless it is the value's last, answering the hold's place in - /// its gate's count, which leaves the gate as the caller lets it go. `Err` where it is the - /// last: the value, still counted by the gate, for the caller to let go of on another thread - /// ([`Last`]). Whether it is the last is decided as it goes (`Arc::into_inner`), so another - /// holder's drop meanwhile never leaves the value's drop here. - pub(crate) fn let_go_short_of_last(self) -> Result>> { - let Hold { value, _count } = self; - match Arc::into_inner(value) { - Some(value) => Err(Box::new(Last { value, _count })), - None => Ok(_count), - } - } -} - -/// A [`Hold`]'s value where the hold was its last reference ([`Hold::let_go_short_of_last`]), -/// still counted by its gate: dropped, it drops the value, then leaves the gate. -pub(crate) struct Last { - value: T, - _count: Count, -} - -impl Deref for Last { - type Target = T; - - fn deref(&self) -> &T { - &self.value - } -} - -impl Deref for Hold { - type Target = Arc; - - fn deref(&self) -> &Arc { - &self.value - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs deleted file mode 100644 index 0fd8c37b9..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs +++ /dev/null @@ -1,1012 +0,0 @@ -//! Batches that go to the driver in one kernel submission (`CompletionPolicy::Grouped`). -//! -//! On a device whose check found one `vkQueueSubmit` of `VkSubmitInfo`s that signal nothing to -//! cost about one of its submissions (`submit_check.rs`, `Check::Merge`: Mesa's common queue -//! merges each into the next one's kernel submission, `vulkan/runtime/vk_queue.c`), batches that -//! signal nothing but their queue's timeline may wait and go in one call for the cost of one -//! kernel submission. The question is the device's, and its check answers it, never the driver's -//! name nor its GPU's: a device whose check found otherwise, or has not answered, takes the -//! ungrouped path, each batch its own `vkQueueSubmit`, which is what every batch took before -//! grouping and is exact alike -- a group changes when a `vkQueueSubmit` is made and nothing it -//! submits. Each command buffer of a group is exact on every driver by Vulkan's own rules (the -//! bullets below), so the check decides only where grouping pays. -//! -//! - **Marked under `CompletionPolicy::Exact`.** Under `Exact`, a batch waits here only where -//! its command buffer is marked to join the next ([`CommandBuffer::set_completion_joins_next`]); -//! the first batch of its `VkQueue` found ready behind such batches in the same pass that is not -//! marked may go last in their group (`CommandBufferShared::closes_groups`), and the group then -//! goes at once (`GroupEnd::Closed`), that batch's own signals ending it, so it is seen complete -//! at its own end and held back for nothing. No group is kept past its pass under `Exact` -//! ([`Group::keeps`], `Alone::Unkept`): a kept group may reach the GPU after the work ahead of -//! it ended, which would make the unmarked batch behind it complete later. -//! - **What waits.** A batch the scheduler submits waits here, submitted by nothing yet, where it -//! signals nothing but its queue's timeline and its events' semaphores: no binary semaphore, -//! no fence; binds no sparse update; does no first work; moves none of the caller's wrapped -//! images; and waits for no event index a batch held signals (only the group's end would meet -//! it: on one `VkQueue` that wait would never be met). Every other batch goes as before, after -//! the group held on its `VkQueue` went (`Submitting::AfterGroup`), and so does one of another -//! `VkQueue`, so a wait there for a held signal follows the group's submission too. A batch -//! that waits for anything not seen complete (an event, another `VkQueue`'s work, first work) -//! leads a group and never joins one: it goes after a group held, in a submission of its own. -//! An unshared queue's batch on a `VkQueue` other queues' work is held back from -//! (`unshared_hold.rs`) never waits either: held, it would go with the next batch of theirs and -//! be seen complete at that batch's end, however long, and kept, behind the batch the hold let -//! go meanwhile. -//! A group goes at once when it holds [`GROUP_BATCHES`], so no submission holds more. -//! - **Bounded by its expected run.** The driver runs a group as one kernel job, which a kernel's -//! job timeout ends as a whole: Linux's amdgpu ends one past 2 s by default, with no error the -//! device reports (`gpu_time.rs`), where each batch alone may finish within it. So a batch joins -//! only where its queue's expected GPU run is known and keeps the group's expected runs, summed, -//! within [`GROUP_RUN`] (16 ms): merging adds at most that much of the others' expected work to -//! any batch's job. The expected run follows the queue's command buffers' own GPU times as each -//! completes (`CommandBufferShared::place_gpu_times`), by their timestamps, which bracket their -//! own work alone, whatever other `VkDevice`s the GPU ran meanwhile; where the device answers GPU -//! times from the host (`DeviceOptions::gpu_times_from_host`), by those host times, which hold -//! other clients' work on the GPU too, so under contention there a queue's batches may stop -//! grouping. Otherwise the group goes first (`GroupEnd::Long`), and the batch leads the next -//! group where its own run is known and within the bound, else goes alone: a queue whose batches -//! none was seen complete yet, or whose recent ones ran longer, groups none until it has a run -//! within the bound. An expected run is a few recent batches' (raised at once by a longer one, -//! halved toward a shorter one), so a batch longer than its queue's recent ones may still join -//! a group; the others' expected runs it then carries stay within the bound. -//! - **Checked ahead.** A batch with submission checks is ready only once they ran -//! (`checks.rs`), which the scheduler does for each line's head; here it runs those of the -//! batches right behind a head that goes too, so a line of checked batches (the consumer checks -//! every command buffer) is found ready together (`scheduler::check_heads`). -//! - **One submission.** [`Group::submit`] submits every batch held, in order, in one -//! `vkQueueSubmit` where only the last `VkSubmitInfo` signals: each event's semaphore to the -//! highest index a batch held signals it to, then the queue's timeline to the last batch's -//! value. Each is above every other batch's signal of it, so it reaches theirs too ("the -//! semaphore's value is set to the signal value" once the batch's commands complete, and a value -//! reached is reached by every wait for a lower one; the first synchronization scope of a signal -//! holds "every command in the same batch ... and all commands that occur earlier in submission -//! order", `vkQueueSubmit`). An event's indices rise in its signals' submission order -//! (`event_timeline.rs`), so its earlier values land with the group's end, late, never wrong: -//! a wait on another `VkQueue` for one is met by the higher index, and the host's waits, value -//! reads and listeners see the event's value rise once that index is seen. Each batch keeps its -//! own commands, barriers and its end's barrier to the host. Only the first batch may wait for a -//! value not seen complete, for a signal submitted before it, the scheduler's order: the merge -//! gathers every batch's waits before the first one's commands, so a later batch's wait would -//! hold back the earlier ones' start until it is met, and none is held. -//! - **Taken as made.** What a batch's submission changes in the scheduler's state (the tracker's -//! plan, its queue's value, the completed values its queue waited for) is changed as it is held, -//! so the next batch is planned after it. Where it ends its command buffer, on which no switch of -//! storage forms rides, the command buffer's kernel end and its transition to `Scheduled` come as -//! it is held, its submission handlers run before that on the device's handler threads, which -//! the scheduler's thread hands them to as its pass goes on, as a submitted batch's -//! ([`Group::schedule_held`]), as Metal schedules a command -//! buffer committed behind running work at once: on an M3 Max under macOS 27.0.1, each of 8 -//! committed behind a 55 ms kernel on its queue was `Scheduled` 0.04 to 0.18 ms after its commit, -//! its scheduled handler run, about 55 ms before that kernel ended (probe `scheduled`). Its queue -//! waiter's watch comes once the group is submitted. A submission that fails without losing the -//! device changed nothing (`vkQueueSubmit`), so the events' semaphores and the timeline are -//! brought to the group's end by a submission of those signals alone, the waits taken are put -//! back, and each batch's command buffer fails (one already `Scheduled` from there); where that -//! fails too, the device is lost to the runtime, its timeline short of the values its tracker -//! holds. -//! - **Kept while its queue runs earlier work** ([`Group::keeps`]). A pass that finds no batch -//! ready sends the group, unless two or more submissions of its `VkQueue` are not seen complete -//! (`QueueSlot::pending_beyond_one`): the GPU runs those first in any case, in submission order, -//! so the group stays held for the batches committed meanwhile, gated on the value whose -//! completion leaves one submission in flight, at which a completion turn wakes the scheduler. -//! It goes with one in flight rather than two: on the UHD 770 two cut the kernel submissions -//! less (30 a frame against 24, at 67 command buffers a frame committed 1 ms apart behind 1.3 ms -//! of GPU work each) and left the GPU as idle (0.62 ms a frame with either). -//! It goes then, or once it fills, a batch that cannot join sends it, a head waits for the GPU -//! (at a gate, or its checks for a signal to land, which may be the group's), or a thread waits -//! for one of its command buffers' completion (`CommandBuffer::wait_until_completed` marks it -//! and wakes the scheduler: [`CommandBufferShared::waits_for_completion`]). Nor is it kept -//! where the thread runs, once the pass ends, the submission handlers of a command buffer of -//! another logical queue (a batch held, or one submitted, taken by a pass that settled a switch -//! of storage forms: `scheduler::holds_back_another_queue`; every other pass hands them to the -//! device's handler threads, where they hold back none of its passes): it goes first, so no -//! handler that waits for another queue's work holds that work back, as Metal schedules one -//! queue's command buffers whatever another queue's handler does (probe -//! `cross_queue_handler_waits`). The handlers of the batches' own queue keep it held: Metal -//! runs one queue's handlers one at a time, so a handler there that waits for a completed -//! handler of its own queue never sees it either (the probe's `scheduled-one-queue`). A group -//! whose batch ends a command buffer with a switch of storage forms riding on it is never kept: -//! the switch settles by the submission's outcome, before the command buffer is `Scheduled`. -//! Nor is one on a `VkQueue` other queues' work is held back from for an unshared queue -//! (`unshared_hold.rs`): the hold bounds the work ahead there by its expected GPU time, and a -//! group kept past the point the hold let its batches go would leave the GPU idle once the -//! work ahead ended. -//! A head of another queue whose wait is for a value only a batch the group holds signals -//! (`HeldFor::EventValue`: no submitted signal reaches it yet) does not send it: it is held -//! until the group goes, at the completion turn that leaves one submission in flight at the -//! latest, and is then submitted with its wait on the `VkQueue` -//! (`runtime_lane::grouped_submissions`). A kept batch is seen -//! complete late by its group's later batches' GPU time, as any member, and where the one -//! submission left in flight ends before the group reaches the GPU, by that gap besides: at most -//! a completion turn's reaction and the group's `vkQueueSubmit`. Counted: -//! `WorkCounts::groups_kept_pending`, `WorkCounts::groups_sent_for_waits`. -//! - **Counted by its end.** Each group held counts once by what sent it ([`GroupEnd`], -//! `WorkCounts::group_ends_full` and kin): so the consumer's counts say why its groups hold -//! fewer batches than they may. Each batch on a `VkQueue` whose batches group that goes in a -//! kernel submission of its own counts once by why ([`Alone`], -//! `WorkCounts::batches_alone_unshared` and kin): what refused it a place with no group held -//! (counted nowhere else), a committing thread's submission, or, where its group went holding -//! it alone, what sent that group; so the consumer's counts say why its batches did not group. -//! - **No allocation.** A group's submission names at most [`MOST_INFOS`] `VkSubmitInfo`s, built -//! in arrays on the thread's stack; its end's signals and its submissions go to lists the group -//! keeps with their room: the scheduler thread allocates nothing for it -//! (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`). - -use super::submit::Submission; -use super::{submission_error, CommandBuffer, CommandBufferShared}; -use crate::degradation::{Degradation, NoticesFor}; -use crate::device::relay::Relayed; -use crate::error::{invalid, CommandBufferError, Error, Problem}; -use crate::exit_guard::{self, Call}; -use crate::gpu_time; -use crate::submit_failure::{submit_failed, try_lock, Carried, Failed, TypeFlags}; -use crate::Device; -use ash::vk; -use metal2vulkan::device::CompletionPolicy; -use std::sync::atomic::Ordering; -use std::sync::Arc; - -/// The most batches one kernel submission holds: the first is seen complete late by the GPU time -/// of at most this many less one. -pub(crate) const GROUP_BATCHES: usize = 4; - -/// The most expected GPU run, in nanoseconds, of the batches one group holds, summed (the module -/// docs, "Bounded by its expected run"): 16 ms, the owner's line for an intolerable wait, which no -/// member's completion is then seen late by for the others' expected runs. It is 1/125 of the job -/// timeout Linux's amdgpu ends a kernel job at by default (2 s, its `lockup_timeout`, Linux 7.3.3), -/// past which a Radeon 780M's kernel ended a single command buffer of 3.2 s and dropped the one -/// behind it (`gpu_time.rs`). -pub(crate) const GROUP_RUN: u64 = 16_000_000; - -/// The most `VkSubmitInfo`s a batch names: its work's and its finale's (`submit.rs`). -const BATCH_INFOS: usize = 2; - -/// The most `VkSubmitInfo`s one group's `vkQueueSubmit` names: [`BATCH_INFOS`] for each batch -/// held, and for the batch after them its first work's beside its own. -const MOST_INFOS: usize = GROUP_BATCHES * BATCH_INFOS + 1 + BATCH_INFOS; - -/// Whether `device`'s batches on `VkQueue` `queue` may go to the driver in one kernel submission -/// at all: its check found a submission that signals nothing merged into the next (the module -/// docs), the queue's failures are not relayed (each relayed batch takes a fence, -/// `device/relay.rs`), and its encoder trail is off (`encoder_trail.rs`: each batch goes alone). -pub(crate) fn merges(device: &Device, queue: usize) -> bool { - device.submissions_merge_now() - && device.shared().flights(queue).is_none() - // The encoder trail submits each batch alone (`encoder_trail.rs`). - && !device.shared().encoder_trail -} - -/// Whether every batch of `device`'s on `VkQueue` `queue` may wait in a group: its policy groups -/// them (`CompletionPolicy::Grouped`) and they merge ([`merges`]). Under `CompletionPolicy::Exact` -/// only a command buffer marked to join the next may (`CommandBufferShared::groups`). -pub(crate) fn groups(device: &Device, queue: usize) -> bool { - device.compile_device().policy().completion == CompletionPolicy::Grouped - && merges(device, queue) -} - -impl CommandBuffer { - /// Mark the command buffer's completion as joining the next one's: a runtime extension, no - /// Metal call (the crate's README, "Runtime extensions"). Metal has no counterpart; it reports - /// each command buffer complete at its own end. Under `CompletionPolicy::Exact`, on a device - /// whose batches merge (the device's check found one `vkQueueSubmit` of `VkSubmitInfo`s that - /// signal nothing to cost about one of its submissions, `Device::submissions_merge`; its - /// queue's failures not relayed), a batch of a marked command buffer may wait in the - /// scheduler's group as `CompletionPolicy::Grouped` lets every batch wait - /// (`command_buffer/group.rs`): up to four batches of one `VkQueue` found ready together go - /// in one kernel submission, only the last signalling. A batch of a command buffer not - /// marked never waits in a group, and is never held back for one: it may go last in the - /// group held before it, in the same pass and the same call, which then goes at once, and it - /// is seen complete at its own end, as alone. No group is kept past the pass that found it - /// under `Exact` (`CompletionPolicy::Grouped` keeps one while earlier work of its queue - /// runs), so no marked batch waits for later work to be committed. - /// - /// What it delays: the marked command buffer is seen complete (its status, completed - /// handlers and waits), and the event values it signals are reached, once the last batch of - /// its kernel submission completed: late by the GPU time of the batches after it there, at - /// most three, never early and in commit order. Its submission waits for the next batch of - /// its queue found ready in the same pass of the scheduler, at most that pass. The - /// submission checks of the batches right behind it, the first one not marked among them, run - /// with its own, before its submission, so that they are found ready together; each still - /// runs once, in commit order, before its own batch's submission. Its commands, barriers and - /// GPU times are unchanged. The device announces `Degradation::GroupedCompletion` once, at its - /// first such submission. - /// - /// It changes nothing where it cannot apply: under `CompletionPolicy::Grouped`, which groups - /// every batch already; on a device whose check did not find submissions merged, has not - /// answered, or relays its queues' failures (MoltenVK); with the encoder trail on; and for a - /// batch that groups in no case (it signals or waits for a binary semaphore, takes a fence, - /// binds a sparse update, does first work, or is an unshared queue's on a `VkQueue` other - /// queues' work is held back for it). Counted: `WorkCounts::grouped_submissions`, - /// `WorkCounts::batches_grouped`, `WorkCounts::group_ends_closed` and kin. - /// - /// Refused, changing nothing, once the command buffer is committed (`Invalid`, - /// `Problem::AlreadyCommitted`). - pub fn set_completion_joins_next(&self, joins: bool) -> Result<(), Error> { - let state = self.state(); - if state.enqueued() || state.committing { - return Err(invalid( - "set_completion_joins_next", - Problem::AlreadyCommitted, - )); - } - match joins { - true => self.0.group_hold.fetch_or(JOINS_NEXT, Ordering::SeqCst), - false => self.0.group_hold.fetch_and(!JOINS_NEXT, Ordering::SeqCst), - }; - Ok(()) - } -} - -impl CommandBufferShared { - /// Whether its batches may wait in a group: every batch where its queue's batches group - /// ([`groups`]), and under `CompletionPolicy::Exact` those of a command buffer marked to join - /// the next where they merge ([`merges`], [`CommandBuffer::set_completion_joins_next`]); never - /// an unshared queue's on a `VkQueue` other queues' work is held back from (the module docs). - pub(crate) fn groups(&self) -> bool { - let queue = self.queue.vk_queue(); - let may = match self.joins_next() { - true => merges(&self.device, queue), - false => groups(&self.device, queue), - }; - may && self.not_held_apart(queue) - } - - /// Whether a batch of it that waits in no group ([`groups`](Self::groups)) may still go last - /// in the group held before it on its `VkQueue`, which then goes at once: its batches merge - /// ([`merges`]), and it is no unshared queue's on a `VkQueue` other queues' work is held back - /// from. So under `CompletionPolicy::Exact` the command buffer right behind marked ones goes - /// in their kernel submission, seen complete at its own end - /// ([`CommandBuffer::set_completion_joins_next`]). - pub(crate) fn closes_groups(&self) -> bool { - let queue = self.queue.vk_queue(); - merges(&self.device, queue) && self.not_held_apart(queue) - } - - /// Whether it is not an unshared queue's on `VkQueue` `queue` while other queues' work is held - /// back there for it, whose batches never wait in a group (the module docs). - fn not_held_apart(&self, queue: usize) -> bool { - !(self.queue.unshared() && self.device.holds_back_for_unshared(queue)) - } - - /// Whether it is marked to join the next ([`CommandBuffer::set_completion_joins_next`]): set - /// before its commit, read after it. - fn joins_next(&self) -> bool { - self.group_hold.load(Ordering::SeqCst) & JOINS_NEXT != 0 - } - - /// Whether a committing thread submits a batch of it that may wait in a group - /// ([`groups`]) alone, rather than leave it to the scheduler's thread - /// (`scheduler::plain`, `CommandBuffer::commit_and_submit`): where its `VkQueue` runs at most - /// one earlier submission not seen complete, the pass that held it would send the group at its - /// end ([`Group::keeps`]), so it reaches the GPU no later, and the commit saves the scheduler's - /// wake and pass. Where two or more run, the scheduler's thread holds it in the group, with - /// the commits that join it. Read without the queue's lock, as `keeps` reads it: a submission - /// seen complete meanwhile only lowers the count. - pub(crate) fn goes_alone_at_commit(&self) -> bool { - (self.device.shared().queues[self.queue.vk_queue()].pending_beyond_one()).is_none() - } - - /// Whether a committing thread leaves its batches to the scheduler's thread, as its - /// `VkQueue`'s batches' submissions are slow (`device/submit_calls.rs`): read - /// without the queue's lock. - pub(crate) fn submits_slowly(&self) -> bool { - self.device.shared().submits_slowly(self.queue.vk_queue()) - } - - /// Its queue's identity: the logical queue its batches line up on in the scheduler's order - /// (`scheduler/order.rs`). - pub(crate) fn logical_queue(&self) -> u64 { - self.queue.id() - } - - /// A batch of it was held in the scheduler's group. - pub(crate) fn held_in_group(&self) { - self.group_hold.fetch_or(IN_GROUP, Ordering::SeqCst); - } - - /// Its batches held in the group went, or failed. - pub(crate) fn left_group(&self) { - self.group_hold.fetch_and(!IN_GROUP, Ordering::SeqCst); - } - - /// A thread begins to wait for its completion: where a batch of it is held in the group, the - /// scheduler is woken, and sends the group at once ([`Group::keeps`]). The scheduler marks a - /// batch held before it looks for a waiter, and the waiter marks its wait before it looks for - /// a batch held, each on the same word, so one of the two sees the other. - /// - /// Else the thread submits for itself what still waits in the scheduler's inbox, before it - /// sleeps (`Scheduler::submit_before_waiting`): a commit submits nothing, as Metal's returns - /// before its command buffer is scheduled, so a thread that commits and then blocks would - /// otherwise wait for a wake and a whole pass first. - pub(crate) fn waits_for_completion(&self) { - let before = self.group_hold.fetch_or(WAITED_FOR, Ordering::SeqCst); - let scheduler = &self.device.shared().scheduler; - if before & IN_GROUP != 0 { - scheduler.wake(); - return; - } - scheduler.submit_before_waiting(&self.device); - } - - /// A thread begins to wait for its scheduling (`CommandBuffer::wait_until_scheduled`): it - /// submits for itself what still waits in the scheduler's inbox before it sleeps - /// (`Scheduler::submit_before_waiting`), as a thread waiting for the completion does. - /// - /// It marks no wait on the group, where [`waits_for_completion`](Self::waits_for_completion) - /// does: a batch held in a group makes its command buffer `Scheduled` as it is held - /// ([`Group::schedule_held`]), so this wait is answered by the hold, and sending the group for - /// it would spend its kernel submission for nothing. Nor does the pass it makes submit a - /// batch of a queue whose batches group at all (`scheduler::plain_ready`). - pub(crate) fn waits_for_scheduling(&self) { - (self.device.shared().scheduler).submit_before_waiting(&self.device); - } - - /// Whether a thread waits for its completion. - fn is_waited_for(&self) -> bool { - self.group_hold.load(Ordering::SeqCst) & WAITED_FOR != 0 - } -} - -/// A command buffer's `group_hold` bit: a batch of it is held in the scheduler's group. -const IN_GROUP: u8 = 1; - -/// A command buffer's `group_hold` bit: a thread waits for its completion. -const WAITED_FOR: u8 = 2; - -/// A command buffer's `group_hold` bit: it is marked to join the next -/// ([`CommandBuffer::set_completion_joins_next`]). -const JOINS_NEXT: u8 = 4; - -/// Whether a batch of expected run `run` (nanoseconds; `None` where its queue has none yet) may -/// join batches whose expected runs sum to `held`: its run is known and the sum stays within -/// [`GROUP_RUN`] (the module docs, "Bounded by its expected run"). -pub(crate) fn within_run(held: u64, run: Option) -> bool { - run.is_some_and(|run| held.saturating_add(run) <= GROUP_RUN) -} - -/// What sent a group held (`WorkCounts::group_ends_full` and kin). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum GroupEnd { - /// It held [`GROUP_BATCHES`]. - Full, - /// A batch waits: for an event index a batch held signals, which only the group's end meets, - /// or for anything else not seen complete (it goes after the group, never in it). - Wait, - /// A batch that may not wait in a group (a binary semaphore, a fence, a sparse update, a move - /// of bytes that waits for every submission), or one of another `VkQueue`. - Apart, - /// A batch that may join did first work or names a wrapped image: it went last in the group's - /// call. - FirstWork, - /// A batch that may otherwise join is of unknown length, or would take the group's expected - /// run past [`GROUP_RUN`]. - Long, - /// The pass found no batch left to submit. - Drained, - /// The pass found none ready, with submission checks or host steps left for the thread to run. - Checks, - /// The pass found none ready, the rest held for events, gates, binary semaphores or decodes. - Held, - /// A batch of a command buffer not marked to join the next went last in it under - /// `CompletionPolicy::Exact` ([`CommandBuffer::set_completion_joins_next`]): it goes at once. - Closed, -} - -/// Why a batch on a `VkQueue` whose batches group ([`groups`]) went in a kernel submission of its -/// own (`WorkCounts::batches_alone_unshared` and kin): each such batch counted once, by the first -/// reason that holds in this order. The first ten are batches that went with no group held and -/// were never held; the rest were held, and their group went holding them alone. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Alone { - /// An unshared queue's batch on a `VkQueue` other queues' work is held back from for it - /// (`unshared_hold.rs`), which never waits in a group (the module docs). - Unshared, - /// It waits for a binary semaphore (`encode_wait_for_vk_semaphore`, a sync file's wait). - BinaryWait, - /// It signals a binary semaphore (`encode_signal_vk_semaphore`, a completion sync file). - BinarySignal, - /// It binds a sparse update. - Sparse, - /// A segment cut its work into pieces, each a `VkSubmitInfo` of its own. - Pieced, - /// It ends its command buffer at a fence (`fences.rs`). - Fence, - /// Its queue's expected run is unknown: none of its command buffers was seen complete. - RunUnknown, - /// Its queue's expected run alone is past the group's bound. - RunLong, - /// It took the device's first work, staged copies or a fill, or names the caller's wrapped - /// image, with no group held: such a batch goes last in a group's call, never in a group. - FirstWork, - /// A committing thread submitted it alone, its `VkQueue` running at most one earlier - /// submission not seen complete (`CommandBufferShared::goes_alone_at_commit`). - AtCommit, - /// Held; the pass found no batch ready, and its `VkQueue` ran at most one earlier submission - /// not seen complete, so the group was not kept ([`Group::keeps`]). - OnePending, - /// Held; its `VkQueue` holds an unshared queue whose isolation holds other queues' work back - /// there, where no group is kept. - UnsharedHold, - /// Held; a head waited for the GPU (at its gate, or for a signal its checks wait for). - GpuWait, - /// Held; the thread ran another logical queue's submission handlers next. - Handlers, - /// Held; a thread waited for its command buffer's completion. - WaitedFor, - /// Held and kept while its queue ran earlier work, and no batch joined it before one - /// submission was left in flight. - Kept, - /// Held; a batch that may not join it came next: of another `VkQueue`, one refused, one - /// past the group's bound, or one that waits for a signal it holds. - SentByNext, - /// Held; a switch of storage forms rides on it, or the device was lost. - Other, - /// Held, of a command buffer marked to join the next under `CompletionPolicy::Exact` - /// ([`CommandBuffer::set_completion_joins_next`]); the pass found no batch ready, and no - /// group is kept under `Exact`. - Unkept, -} - -impl Alone { - /// How many there are, for the counters' array. - pub(crate) const COUNT: usize = 19; -} - -/// One `VkSubmitInfo`'s lists, kept with their room from batch to batch. -#[derive(Default)] -pub(crate) struct Info { - wait_semaphores: Vec, - wait_values: Vec, - wait_stages: Vec, - buffers: Vec, - signal_semaphores: Vec, - signal_values: Vec, -} - -/// What one `VkSubmitInfo` waits for, runs and signals, borrowed. -pub(crate) struct InfoParts<'a> { - pub(crate) waits: (&'a [vk::Semaphore], &'a [u64], &'a [vk::PipelineStageFlags]), - pub(crate) buffers: &'a [vk::CommandBuffer], - pub(crate) signals: (&'a [vk::Semaphore], &'a [u64]), -} - -impl Info { - fn fill(&mut self, parts: &InfoParts<'_>) { - let (semaphores, values, stages) = parts.waits; - self.wait_semaphores.clear(); - self.wait_semaphores.extend_from_slice(semaphores); - self.wait_values.clear(); - self.wait_values.extend_from_slice(values); - self.wait_stages.clear(); - self.wait_stages.extend_from_slice(stages); - self.buffers.clear(); - self.buffers.extend_from_slice(parts.buffers); - let (semaphores, values) = parts.signals; - self.signal_semaphores.clear(); - self.signal_semaphores.extend_from_slice(semaphores); - self.signal_values.clear(); - self.signal_values.extend_from_slice(values); - } -} - -/// A batch held: its `VkSubmitInfo`s, how many command buffers they hold, its submission, -/// published once the group is submitted, its queue's expected run as it was held, and how long -/// its submission took from its start to its hold, in nanoseconds. -struct Member { - infos: Vec, - buffers: usize, - submission: Submission, - run: u64, - planned: u64, -} - -/// The batches held for one kernel submission on one `VkQueue` (the module docs), in the -/// scheduler's state. -#[derive(Default)] -pub(crate) struct Group { - queue: usize, - members: Vec, - /// It stayed held past a pass for the work its queue ran ([`keeps`](Group::keeps)). - kept: bool, - /// Its last batch held is of a command buffer not marked to join the next, under - /// `CompletionPolicy::Exact` ([`closed`](Group::closed)). - closed: bool, - /// The completed values `queue` waited for before the first batch held: put back where the - /// group's submission fails. - waited: Vec, - /// The events' semaphores the batches held signal, each with the lowest and the highest index - /// they signal it to: the group's end signals the highest (the module docs). - events: Vec<(vk::Semaphore, u64, u64)>, - /// The lists of batches submitted, kept with their room. - spare: Vec>, - /// The end's signals: each event's semaphore, then the queue's timeline, and their values; - /// kept with their room. - end_semaphores: Vec, - end_values: Vec, - /// The batches the group's last submission made, in order, until the scheduler takes them - /// ([`made`](Group::made)); kept with their room. - made: Vec, - /// What the group's last submission did, until the scheduler takes it - /// ([`take_outcome`](Group::take_outcome)): made ([`made`](Group::made)), or failed. - outcome: Option>, -} - -/// A batch submitted after the group, in the same `vkQueueSubmit` ([`Group::submit`]). -pub(crate) struct After<'a> { - /// Its `VkQueue`: the group's, where one is held. - pub(crate) queue: usize, - pub(crate) infos: &'a [vk::SubmitInfo<'a>], - pub(crate) buffers: usize, - /// The value it signals on the queue's timeline. - pub(crate) value: u64, - pub(crate) fence: Option, - /// The host time its batch's submission began (`CommandBufferShared::submit_batch`): a call - /// that carries it alone is timed from there (`device/submit_calls.rs`). - pub(crate) begun: u64, - pub(crate) relayed: &'a Arc, - /// What it carried, for the line its failed submission logs (`submit_failure.rs`): called - /// only once the call failed. - pub(crate) carry: &'a dyn Fn(&mut Carried, &TypeFlags), -} - -impl Group { - /// The `VkQueue` of the batches held. - pub(crate) fn queue(&self) -> usize { - self.queue - } - - /// Whether it holds a batch. - pub(crate) fn holds(&self) -> bool { - !self.members.is_empty() - } - - /// Whether a batch on `VkQueue` `queue` may be submitted now, the group held so far going - /// first: the group is empty, or the batch may wait in it (`joins`) on its queue with room. - pub(crate) fn admits(&self, queue: usize, joins: bool) -> bool { - self.members.is_empty() - || (joins && self.queue == queue && self.members.len() < GROUP_BATCHES) - } - - /// Whether a batch of expected run `run` (nanoseconds; `None` where unknown) may wait in the - /// group as far as its run goes ([`within_run`]). - pub(crate) fn fits(&self, run: Option) -> bool { - within_run(self.members.iter().map(|member| member.run).sum(), run) - } - - /// Whether a batch held signals the event of `semaphore` to `index` or above: only the group's - /// end meets a wait for it, so a batch with that wait goes after the group, in a submission - /// of its own (the module docs). A lower index was signalled before the group. - pub(crate) fn meets(&self, (semaphore, index): (vk::Semaphore, u64)) -> bool { - (self.events.iter()).any(|&(signaled, lowest, _)| signaled == semaphore && index >= lowest) - } - - /// Whether the group holds [`GROUP_BATCHES`]: the scheduler submits it at once. A batch that - /// may join, found with room, goes with at most a batch less held, so no submission holds - /// more. - pub(crate) fn full(&self) -> bool { - self.members.len() >= GROUP_BATCHES - } - - /// Whether its last batch held is of a command buffer that waits in no group, which went last - /// in it ([`CommandBufferShared::closes_groups`]): the scheduler submits it at once, so that - /// batch is held back for nothing. - pub(crate) fn closed(&self) -> bool { - self.closed - } - - /// A batch on `VkQueue` `queue` is held, before its submission changes the scheduler's - /// state: `waited` is what `queue` waited for so far, put back where the group's submission - /// fails. Its lists come once its changes are made ([`hold`](Group::hold)). - pub(crate) fn open(&mut self, queue: usize, waited: &[u64]) { - if self.members.is_empty() { - self.queue = queue; - self.waited.clear(); - self.waited.extend_from_slice(waited); - } - } - - /// The batch [`open`](Group::open) took: its `VkSubmitInfo`s are `infos` (at most - /// [`BATCH_INFOS`]), with `buffers` command buffers, and its submission is published once the - /// group's is made; `run` its queue's expected run ([`fits`](Group::fits)); `planned` how long - /// its submission took from its start to here, in nanoseconds ([`submit`](Group::submit)). It - /// signals each event's semaphore it names to its index, which the group's end signals - /// instead. - pub(crate) fn hold( - &mut self, - infos: &[InfoParts<'_>], - buffers: usize, - submission: Submission, - (run, closes, planned): (u64, bool, u64), - ) { - self.closed = closes; - for (semaphore, index) in submission.event_signals() { - match self.events.iter_mut().find(|(held, ..)| *held == semaphore) { - Some((_, lowest, highest)) => { - *lowest = (*lowest).min(index); - *highest = (*highest).max(index); - } - None => self.events.push((semaphore, index, index)), - } - } - let mut held = self.spare.pop().unwrap_or_default(); - held.resize_with(infos.len(), Info::default); - for (info, parts) in held.iter_mut().zip(infos) { - info.fill(parts); - } - self.members.push(Member { - infos: held, - buffers, - submission, - run, - planned, - }); - } - - /// The batch [`hold`](Group::hold) took last, after the section that held it ended: where it - /// ends its command buffer and no switch of storage forms rides on it, its kernel end and its - /// transition to `Scheduled` now, not once the group is submitted, and its submission - /// handlers for the scheduler's thread to run now, once its lock is free (the module docs): - /// whether it has them. - pub(crate) fn schedule_held(&mut self) -> bool { - (self.members.last_mut()).is_some_and(|member| member.submission.schedule_held()) - } - - /// Whether the batches held stay held past the pass that found no batch ready (the module - /// docs): the group has room, two or more submissions of its `VkQueue` are not seen complete, - /// no batch held ends a command buffer with a switch of storage forms riding on it (it settles - /// by the submission's outcome), no thread waits for one of their command buffers, and the - /// device is not lost. The scheduler asks only where no handler it runs next is of another - /// logical queue's command buffer (the module docs). - /// The value of that queue's timeline whose completion leaves one submission in flight, for - /// the completion turns to wake the scheduler at; else why it goes, for a group of one batch - /// ([`Alone`]). Counted once per group, and once more where a waiter sends a group kept - /// before. - pub(crate) fn keeps(&mut self) -> Result { - let Some(first) = self.members.first() else { - return Err(Alone::Other); - }; - let device = first.submission.buffer().device(); - if self.full() - || device.is_lost() - || (self.members.iter()).any(|member| member.submission.rides_forms()) - { - return Err(Alone::Other); - } - // Under `Exact` its batches are of command buffers marked to join the next, which wait for - // no later commit (`CommandBuffer::set_completion_joins_next`). - if device.compile_device().policy().completion != CompletionPolicy::Grouped { - return Err(Alone::Unkept); - } - if device.holds_back_for_unshared(self.queue) { - return Err(Alone::UnsharedHold); - } - let counts = &device.shared().counts; - if (self.members.iter()).any(|member| member.submission.buffer().is_waited_for()) { - if self.kept { - counts.group_sent_for_wait(); - } - return Err(Alone::WaitedFor); - } - let Some(value) = device.shared().queues[self.queue].pending_beyond_one() else { - return Err(match self.kept { - true => Alone::Kept, - false => Alone::OnePending, - }); - }; - if !self.kept { - self.kept = true; - counts.group_kept_pending(); - } - Ok(value) - } - - /// Whether it holds exactly one batch: a group that goes so saves no kernel submission, and - /// its batch is counted by why it went alone ([`Alone`]). - pub(crate) fn holds_one(&self) -> bool { - self.members.len() == 1 - } - - /// Whether its `VkQueue` has not completed `value` yet, as the host saw ([`keeps`]'s value), - /// read again after the scheduler left its gate for the completion turns. - /// - /// [`keeps`]: Group::keeps - pub(crate) fn pending_through(&self, value: u64) -> bool { - (self.members.first()).is_some_and(|first| { - let device = first.submission.buffer().device(); - device.shared().queues[self.queue].completed_value() < value - }) - } - - /// What the group's last submission did, for the scheduler to publish its batches - /// ([`made`](Group::made)) or fail them. - pub(crate) fn take_outcome(&mut self) -> Option> { - self.outcome.take() - } - - /// The batches the group's last submission made, in order, for the scheduler to publish. - pub(crate) fn made(&mut self) -> std::vec::Drain<'_, Submission> { - self.made.drain(..) - } - - /// Submit every batch held, then `after` where given, in one `vkQueueSubmit` on the group's - /// `VkQueue` of `device`, only the last signalling (the module docs); `waited` is the - /// scheduler's list of what that queue waited for. Inside a section of the exit guard. The - /// held batches' outcome is kept for the scheduler ([`take_outcome`](Group::take_outcome)); - /// the call's own result is `after`'s, as the `vkQueueSubmit` returned it: on success, the - /// host time at which the scheduler called it, the kernel end of a command buffer whose last - /// batch it carried (now where it submitted nothing). Taken as the call is made, never once - /// it returned: the GPU may run the work, and its timestamps place its end, before the call - /// returns (a driver that runs it as it is submitted, lavapipe's or NVIDIA's) or before a - /// scheduler thread preempted after the call takes the time, and Metal's `GPUEndTime` is never - /// earlier than its `kernelEndTime`. - pub(crate) fn submit( - &mut self, - device: &Device, - waited: &mut [u64], - after: Option>, - ) -> Result { - if self.members.is_empty() { - return match after { - None => Ok(gpu_time::host_nanos()), - Some(after) => submit_alone(device, after), - }; - } - let shared = device.shared(); - let raw = shared.vk(); - let queue = self.queue; - let count = self.members.len(); - let alone = after.is_none(); - self.kept = false; - self.closed = false; - let held_value = self.members[count - 1].submission.value(); - // The held batches' end: each event's semaphore to the highest index a batch held - // signals it to, then the queue's timeline to the last one's value. It ends the - // submission, or, where a batch goes after the group and the held ones signal an event, - // their part of it (that batch's infos then follow a signal, so the driver submits them - // apart). - let ends = alone || !self.events.is_empty(); - self.end_semaphores.clear(); - (self.end_semaphores).extend((self.events.iter()).map(|&(semaphore, ..)| semaphore)); - (self.end_semaphores).push(shared.queues[queue].timeline); - self.end_values.clear(); - (self.end_values).extend((self.events.iter()).map(|&(_, _, highest)| highest)); - self.end_values.push(held_value); - let (end_semaphores, end_values) = (&self.end_semaphores, &self.end_values); - // Only the held batches' last `VkSubmitInfo` signals: every other one's signals (its - // queue's timeline and its events') are reached by the end's higher values. - let held = || (self.members.iter()).flat_map(|member| &member.infos); - let infos = held().count(); - let submitting = infos + after.as_ref().map_or(0, |after| after.infos.len()); - // Each batch's `VkSubmitInfo`s are its work's and its finale's (`submit.rs`), and the - // group holds at most `GROUP_BATCHES`: none is left out of the arrays. - assert!( - submitting <= MOST_INFOS, - "{submitting} VkSubmitInfos in one submission" - ); - let signals = |at: usize| ends && at + 1 == infos; - let mut timelines = [vk::TimelineSemaphoreSubmitInfo::default(); MOST_INFOS]; - for (at, (timeline, info)) in timelines.iter_mut().zip(held()).enumerate() { - let values: &[u64] = if signals(at) { end_values } else { &[] }; - *timeline = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&info.wait_values) - .signal_semaphore_values(values); - } - let mut submits = [vk::SubmitInfo::default(); MOST_INFOS]; - let built = submits.iter_mut().zip(timelines.iter_mut()).zip(held()); - for (at, ((submit, timeline), info)) in built.enumerate() { - let semaphores: &[vk::Semaphore] = if signals(at) { end_semaphores } else { &[] }; - *submit = vk::SubmitInfo::default() - .wait_semaphores(&info.wait_semaphores) - .wait_dst_stage_mask(&info.wait_stages) - .command_buffers(&info.buffers) - .signal_semaphores(semaphores) - .push_next(timeline); - } - let mut buffers: usize = (self.members.iter()).map(|member| member.buffers).sum(); - let last = &self.members[count - 1].submission; - let relayed = Arc::clone(match &after { - Some(after) => after.relayed, - None => &last.buffer().relayed, - }); - let (value, fence) = match &after { - Some(after) => { - submits[infos..submitting].copy_from_slice(after.infos); - buffers += after.buffers; - (after.value, after.fence) - } - None => (held_value, None), - }; - let submits = &submits[..submitting]; - // A call of one batch, a group of one, is timed as that batch's whole submission, from as - // far before the call as its submission took to its hold; a call of several is not - // (`device/submit_calls.rs`, "A group's call"). - let begun = (count == 1 && alone) - .then(|| gpu_time::host_nanos().saturating_sub(self.members[0].planned)); - // SAFETY: as each batch's own submission (`submit.rs`): every command buffer is - // executable and submitted once; every wait is for a signal submitted before; the one - // timeline signal is above the queue's value; the `VkQueue` is used under its lock. - let mut called = 0; - let submitted = shared.submit_logged( - (queue, Some(value), buffers, begun), - fence, - &relayed, - |vk_queue| unsafe { - shared.counts.queue_submitted(submits.len(), buffers); - called = gpu_time::host_nanos(); - raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null())) - }, - ); - // Where the device notes queue times, the call's return, for each command buffer a batch - // held ends (`CommandBuffer::submit_returned_time`). - let returned = shared.timing.queue_times().then(gpu_time::host_nanos); - exit_guard::called(Call::QueueSubmit); - self.events.clear(); - let several = count + usize::from(!alone) > 1; - let outcome = match submitted { - Ok(()) => { - for member in self.members.drain(..) { - self.spare.push(member.infos); - member.submission.buffer().kernel.submitted_at(called); - if member.submission.schedules() && !member.submission.scheduled() { - member.submission.buffer().kernel.end_at(called); - } - if let (true, Some(at)) = (member.submission.schedules(), returned) { - member.submission.buffer().kernel.returned_at(at); - } - self.made.push(member.submission); - } - if several { - shared.counts.batches_grouped(count + usize::from(!alone)); - } - Ok(()) - } - Err(error) => { - // Its line, before the end's signals alone move the timelines on. - let what = match alone { - true => "the batches a group held", - false => "the batches a group held, and a batch after them", - }; - let failed = Failed { - what, - queue: Some(queue), - result: error, - infos: submits, - fence, - }; - let (members, events) = (&self.members, &self.end_semaphores); - let after = after.as_ref().map(|after| after.carry); - submit_failed(device, &failed, |carried, types| { - carried.events.extend_from_slice(events); - for member in members { - let buffer = member.submission.buffer(); - // The batch after them may be of one of their command buffers, whose - // state its submitter holds: that one states it. - match try_lock(&buffer.state) { - Some(state) => buffer.carry(&state, (None, None), carried, types), - None => carried.buffers.push(format!("#{}", buffer.id.get())), - } - } - if let Some(carry) = after { - carry(carried, types); - } - }); - for member in self.members.drain(..) { - self.spare.push(member.infos); - } - waited.copy_from_slice(&self.waited); - let failure = submission_error(device, error); - if !device.is_lost() - && signal_alone( - device, - queue, - (&self.end_semaphores, &self.end_values), - &relayed, - ) - .is_err() - { - device.mark_lost(); - } - if matches!(failure, CommandBufferError::DeviceLost) && alone { - device.drain_queues(); - } - Err(failure) - } - }; - if several && outcome.is_ok() { - let batches = count + usize::from(!alone); - // Several command buffers' batches: none of them named. - let _several = NoticesFor::none(); - device.degrade_once(Degradation::GroupedCompletion, || { - ( - format!("{batches} batches of command buffers on one queue"), - "the scheduler found them ready together, on a driver that merges a \ - submission that signals nothing into the next one" - .to_owned(), - ) - }); - } - self.outcome = Some(outcome); - submitted.map(|()| called) - } -} - -/// Submit `after` alone on its `VkQueue` of `device`: the group's submission with no batch held. -/// On success, the host time at which its `vkQueueSubmit` was called ([`Group::submit`]). -fn submit_alone(device: &Device, after: After<'_>) -> Result { - let shared = device.shared(); - let raw = shared.vk(); - let After { - queue, - infos, - buffers, - value, - fence, - begun, - relayed, - carry, - } = after; - let mut called = 0; - // SAFETY: the batch's submission's own (`submit.rs`). - let submitted = shared.submit_logged( - (queue, Some(value), buffers, Some(begun)), - fence, - relayed, - |vk_queue| unsafe { - shared.counts.queue_submitted(infos.len(), buffers); - called = gpu_time::host_nanos(); - raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null())) - }, - ); - exit_guard::called(Call::QueueSubmit); - if let Err(result) = submitted { - let failed = Failed { - what: "a batch of a command buffer", - queue: Some(queue), - result, - infos, - fence, - }; - submit_failed(device, &failed, carry); - } - submitted.map(|()| called) -} - -/// Signal the end a failed group held (its events' semaphores to their indices, then `VkQueue` -/// `queue`'s timeline to its last value) with a submission of nothing else, after the group's -/// submission failed without losing the device (the module docs). -fn signal_alone( - device: &Device, - queue: usize, - (semaphores, values): (&[vk::Semaphore], &[u64]), - relayed: &Arc, -) -> Result<(), vk::Result> { - let shared = device.shared(); - let raw = shared.vk(); - let value = values.last().copied(); - let mut timeline = vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(values); - let info = vk::SubmitInfo::default() - .signal_semaphores(semaphores) - .push_next(&mut timeline); - // SAFETY: a submission of the signals a failed group's end held, each above its semaphore's - // value (no batch signalled them); the `VkQueue` is used under its lock. - let infos = [info]; - let submitted = - shared.submit_logged((queue, value, 0, None), None, relayed, |vk_queue| unsafe { - shared.counts.queue_submitted(1, 0); - raw.queue_submit(vk_queue, &infos, vk::Fence::null()) - }); - exit_guard::called(Call::QueueSubmit); - if let Err(result) = submitted { - let failed = Failed { - what: "the end of a failed group's batches, its signals alone", - queue: Some(queue), - result, - infos: &infos, - fence: None, - }; - submit_failed(device, &failed, |carried, _| { - carried.events.extend_from_slice(semaphores); - }); - } - submitted -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/hang.rs b/crates/metal2vulkan-runtime/src/command_buffer/hang.rs deleted file mode 100644 index a5cf30d99..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/hang.rs +++ /dev/null @@ -1,691 +0,0 @@ -//! A command buffer whose render encoder drew primitive type 9 directly, of 3 vertices or more, -//! at which Metal's GPU hangs (`DrawPrimitiveType::Nine`, `CommandBufferError::GpuHang`), or -//! whose render pass of no draw call over a mutable rasterization-rate map it hangs at -//! (`rate_mapped_pass.rs`), held alike. -//! Measured on the M3 Max (macOS 27.0.1, 33 hangs, queues warmed and not): it read `Scheduled` -//! 0.68 to 13.2 ms after its commit (about 1 ms, or 4.6 ms and more: its submission's own time), -//! and Metal failed it 28.3 to 46.2 ms after its commit, 27.5 to 28.9 ms after it read -//! `Scheduled` in 26 hangs (24.2 to 37.8 in all). Every command buffer of its queue that it -//! scheduled meanwhile completed with no error together with it, in the queue's order, its event -//! signals firing: those committed at once, after the hang read `Scheduled`, 5 and 20 ms on, one -//! writing what the hang's command buffer writes, and ones whose event waits the host or another -//! queue's command buffer met during the hang. Whether their work ran is a race, which the hang's -//! submission time decides most: where it read `Scheduled` within 2 ms their fills ran on the GPU -//! during the hang in 17 of 18 command buffers, and where later in 6 of 62, the rest running -//! nothing or in part (75,648 and 80,064 bytes of a 4 MiB fill); whether the queues were warmed, -//! and whether the command buffers were made before the hang's commit, decided neither. The -//! runtime answers the later submission's outcome: `Scheduled` [`SCHEDULED`] after the commit, -//! and nothing of the others run. One whose event wait was met only after the hang completed -//! ran, as did one of another queue and one committed after. -//! -//! A command buffer Metal's GPU faults at holds the same way, its timing and its queue's others -//! apart ([`Held::Fault`]): an indexed draw of type 9 (`CommandBufferError::PageFault`), an -//! indirect one (failed as a victim of the GPU's recovery, `GpuRecoveryVictim`), and a render -//! encoder's execution of indirect commands under a state that cannot inherit (`PageFault`), each -//! through `State::fault`. Measured on the M3 Max (macOS 27.0.1, 164 faulting command buffers on -//! fresh queues, 44 of them such executions): Metal completed it 6.86 to 10.3 ms after it read -//! `Scheduled`, which came as any command buffer's (0.5 to 1.5 ms after its commit, 6 to 12 ms -//! on a GPU idle before); the queue's command buffers committed meanwhile read `Scheduled` as -//! they were committed, ran, and completed after it. The encoders after the faulting one were -//! lost to the GPU's recovery where the GPU ran just before (127 of 142; every one of 34 right -//! after a hang), ran where it was idle before (the first fault after 3 s idle), and in some -//! shapes ran in part (an encoder after an event signal, a command buffer committed right -//! after); its event signals fired, 164 of 164. -//! The runtime answers the steady state: the faulting encoder and every one after it run nothing, -//! every event signal fires (`Failure::with_faults`); it reads `Scheduled` once its batch before -//! the hold is taken, and its wait goes [`FAULT_FROM_REACHED`] after that and the GPU reached the -//! encoder; the queue's command buffers committed meanwhile join its list, read `Scheduled` -//! early ([`holding`]), and run. -//! -//! Metal's GPU that faulted at an encoder goes on, once it recovered, to the later encoders that -//! fail too ([`Later`]): an indexed draw of type 9 then a direct one of 3 vertices, or another -//! indexed one. Measured on the M3 Max (macOS 27.0.1, 88 such command buffers, each pass its own -//! encoder, fresh processes and warm ones): the command buffer failed with the first fault's -//! error (`PageFault`, 88 of 88), every event signal firing. It read `Scheduled` 14.3 to 21.0 ms -//! after its commit, where one that faulted once read it 8.4 to 9.4 ms after and completed 6.1 to -//! 9.0 ms after that: once the GPU recovered from the fault. It completed 25.8 to 29.1 ms after -//! that where a hang followed the fault (56), 6.05 to 9.67 ms after it where a fault did (17), 12.7 -//! to 16.5 ms where two did (5), and 31.65 to 34.97 ms where a fault then a hang did (5); past a -//! hang the GPU reached nothing (a fault after it added nothing, 27.0 to 27.2 ms, 5). The queue's -//! command buffer committed right after it ran nothing where a hang followed the fault (6 of 6), -//! and in 1 of 2 where a fault did. The encoders between the fault and the later failure ran in -//! that shape, as the ones after a single fault there did. A command buffer whose GPU hangs first -//! fails as a hang alone does (30 of 30: `GpuHang`, 27.0 to 28.1 ms after `Scheduled`, the fault -//! after the hang never reached). The runtime answers: `Scheduled` [`FAULT_FROM_REACHED`] after -//! the GPU reached the fault, its wait going [`FAULT_FROM_REACHED`] after that for each later -//! fault, then [`FROM_REACHED`] for a hang ([`Held::after_recovered`]); the queue's command -//! buffers committed meanwhile run nothing where a hang follows, as during a hang, and run where -//! faults alone do; and from the fault on nothing runs, as after a single fault. -//! -//! - **The hold.** The hanging encoder's end signals an event of the hang's own to 1 after the -//! encoder, and adds the runtime's own wait ([`Batches::hold`]) for 2 after that, so what -//! follows it in the command buffer (its later event signals, its completion) waits; its commit -//! signals 3 after all its work. The signals and the wait are the runtime's, counted among no -//! event command. The encoder and every one after it run nothing (`State::fail_from`). -//! - **`Scheduled`** [`SCHEDULED`] (the earliest Metal's read it) after the commit, not with its -//! last batch, which the wait holds: the hang's thread makes it then, once the batch before the -//! wait was taken, submitted or held in a group (`group.rs`), its submission handlers first -//! ([`Scheduling::Hang`]). Where that batch is not taken within [`SIGNAL_BOUND`] (an event wait -//! before the hang not met), or a switch of storage forms rides on its commit, which settles by -//! its last batch's submission, it reads `Scheduled` with its last batch. -//! - **In flight** from its commit until its work signalled 3, the queue counting it -//! (`CommandQueue::hangs`): a thread of the hang's own makes it `Scheduled`, waits for 1 (the -//! GPU reached the hang), makes the queue's command buffers committed meanwhile `Scheduled` -//! (below) until it lets the wait go ([`FROM_REACHED`] after it read `Scheduled` and the GPU -//! reached the hang, the later of the two: the earliest Metal failed one after it read -//! `Scheduled`), waits for 3, and only then stops counting -//! it, inside a trail (`trails.rs`): a waiter of the command buffer returns once the queue no -//! longer counts it. A command buffer that does not run its hang (its commit refused, a commit -//! failure that fails the encoder or drops its signals, or itself discarded at its commit) sets -//! 3 at once. -//! - **The queue's others.** A command buffer committed on the queue while a hang of it is in -//! flight, with no event wait of its own, runs nothing and completes with no error, its event -//! signals firing, as `commit_failed` of code 0 does ([`discarded`]); it completes after the -//! hang, in the queue's order. One with an event wait is listed with its waits ([`behind`]); -//! the hang's thread decides each listed one just before it lets the hold go, from its events' -//! values then: one whose every wait is met runs nothing so, as Metal ran nothing of one it -//! scheduled during the hang, and one whose waits are not all met runs. Its first batch's -//! submission applies the verdict (`checks.rs`), which no batch of it can reach before the hold -//! goes: they follow the hang's last batch in the queue's order. One committed after the -//! decision but while the hang is still counted is decided at that submission instead, by -//! whether the hang still is. -//! - **Their `Scheduled`**, as Metal's: from the hang's on, as they are committed, each once its -//! event waits are met. Each joins the hang's list at its commit ([`join`]); the hang's thread, -//! once it made the hang `Scheduled`, makes each listed one `Scheduled` in the queue's order, -//! once its waits are met, its submission handlers first and its kernel times then -//! ([`QueueHangs::schedule_early`], [`Scheduling::Behind`]), until it lets the wait go. One -//! whose waits are not met by then, and every one after it, read `Scheduled` with their last -//! batch, after the hang's, as does every one where the hang's own came with its last batch, and -//! one with a switch of storage forms riding on its commit. -//! - **The device's recovery.** As its wait goes, the hold raises the device's recovery from -//! what it holds for: a hang's, and a fault's that a hang follows, from a hang; else from a -//! fault. A fault's that later failures follow raised the fault's already, as it read -//! `Scheduled`. A predicated loop running meanwhile ends there (`recovery.rs`). -//! -//! [`Batches::hold`]: super::batches::Batches::hold - -use super::super::event::{EventShared, SharedEvent}; -use super::super::exit_guard; -use super::super::gpu_time; -use super::super::queue::QueueGen; -use super::super::{Device, Error}; -use super::recovery::Recovery; -use super::{lock, CommandBufferShared, CommitFailure, FailedEncoders, Item, State}; -use std::collections::VecDeque; -use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak}; -use std::time::{Duration, Instant}; - -/// When after its commit a command buffer its GPU hangs at reads `Scheduled`: 5.06 ms, the -/// earliest Metal's read it where its submission took 4.6 ms or more, whose queue then mostly ran -/// nothing of what it scheduled meanwhile (the module docs). -pub(super) const SCHEDULED: Duration = Duration::from_micros(5_060); - -/// The earliest after it read `Scheduled` that Metal failed a command buffer its GPU hung at: -/// 27.5 ms (the module docs). -pub(super) const FROM_REACHED: Duration = Duration::from_micros(27_500); - -/// The earliest after it read `Scheduled` that Metal completed a command buffer its GPU faulted -/// at, or failed as a victim of the GPU's recovery: 6.86 ms (the module docs). -pub(super) const FAULT_FROM_REACHED: Duration = Duration::from_micros(6_860); - -/// How long the hang's thread waits for a signal of the GPU's (1 or 3) before it goes on as if it -/// came: a device that lost its work never signals. -const SIGNAL_BOUND: Duration = Duration::from_secs(10); - -/// A queue's hangs: how many are in flight, the command buffers committed with an event wait -/// meanwhile, not yet decided, and those committed meanwhile, not yet `Scheduled` (the module -/// docs). -#[derive(Default)] -pub(crate) struct QueueHangs { - in_flight: AtomicUsize, - /// Its faults' holds in flight (the module docs): the queue's command buffers committed - /// meanwhile read `Scheduled` early, and run. - holding: AtomicUsize, - behind: Mutex>, - early: Mutex, - /// Signaled as a command buffer joins `early`. - joined: Condvar, -} - -/// The command buffers committed on a queue while a hang of it is in flight, in their order, for -/// the hang's thread to make `Scheduled` early (the module docs); each of the hang it joined -/// under, which the hang's start counts. -#[derive(Default)] -struct Early { - hang: u64, - joined: VecDeque, -} - -/// A command buffer that joined [`Early`]: the hang it joined under, its event waits, and what -/// makes it `Scheduled` ([`behind_scheduled`] of it, held weakly). Held as a closure: a queue's -/// hangs then name no command buffer's type, which would name the queue's again. -struct Joined { - hang: u64, - waits: Vec<(Arc, u64)>, - schedule: Box, -} - -/// A command buffer committed with event waits while a hang of its queue was in flight: its -/// waits, and its verdict. -struct Behind { - waits: Vec<(Arc, u64)>, - verdict: Verdict, -} - -/// A command buffer's verdict behind a hang ([`behind`]): undecided, it runs, or it runs nothing. -#[derive(Clone, Default)] -pub(super) struct Verdict(Arc); - -impl Verdict { - const RUNS: u8 = 1; - const DISCARDED: u8 = 2; - - /// Whether the command buffer runs nothing, as its first batch is about to be submitted on - /// `queue`: as decided, or where undecided, whether a hang of the queue is in flight now. - pub(super) fn discards(&self, queue: &QueueGen) -> bool { - match self.0.load(Ordering::SeqCst) { - Verdict::DISCARDED => true, - Verdict::RUNS => false, - _ => in_flight(queue), - } - } -} - -impl QueueHangs { - /// The count of holds in flight of `held`'s kind. - fn counter(&self, held: Held) -> &AtomicUsize { - match held.discards() { - true => &self.in_flight, - false => &self.holding, - } - } - - /// Until `until`, make the command buffers that joined [`Early`] under hang `hang` - /// `Scheduled`, in their order, each once its event waits are met (the module docs). One - /// whose waits are not met by then, and every one after it, read `Scheduled` with their last - /// batch. - fn schedule_early(&self, hang: u64, until: Instant) { - loop { - let next = { - let mut early = lock(&self.early); - loop { - if let Some(joined) = early.joined.pop_front() { - break Some(joined); - } - let left = until.saturating_duration_since(Instant::now()); - if left.is_zero() || exit_guard::closed() { - break None; - } - early = (self.joined.wait_timeout(early, left)) - .unwrap_or_else(PoisonError::into_inner) - .0; - } - }; - let Some(joined) = next else { - return; - }; - if joined.hang != hang { - continue; - } - let met = (joined.waits.iter()).all(|(event, value)| { - event.wait_until(*value, until.saturating_duration_since(Instant::now())) - }); - if !met { - sleep_until(until); - return; - } - (joined.schedule)(); - } - } - - /// Decide every listed command buffer from its events' values now: one whose every wait is - /// met runs nothing. - fn decide(&self) { - let listed: Vec = lock(&self.behind).drain(..).collect(); - for behind in listed { - let met = behind - .waits - .iter() - .all(|(event, value)| event.value() >= *value); - let verdict = match met { - true => Verdict::DISCARDED, - false => Verdict::RUNS, - }; - behind.verdict.0.store(verdict, Ordering::SeqCst); - } - } -} - -/// What a command buffer's hold holds for (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Held { - /// Metal's GPU hangs at its encoder (`CommandBufferError::GpuHang`). - Hang, - /// Metal's GPU faults at its encoder, or fails it as a victim of its recovery - /// (`CommandBufferError::PageFault`, `GpuRecoveryVictim`), then at the later encoders - /// [`Later`] counts, which it reaches once it recovered. - Fault(Later), -} - -/// The ended encoders after a faulting one that Metal's GPU fails too, which it reaches once it -/// recovered from the fault (the module docs): the faults (victims too) before the first hang, -/// and whether a hang follows them, past which it reaches none. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(super) struct Later { - faults: u32, - hang: bool, -} - -impl Held { - /// Whether the queue's command buffers committed meanwhile run nothing, as during a hang (a - /// hang's hold, and a fault's that a hang follows), or run (a fault's alone, or followed by - /// faults alone) (the module docs). - fn discards(self) -> bool { - matches!(self, Held::Hang | Held::Fault(Later { hang: true, .. })) - } - - /// When after its commit the command buffer reads `Scheduled` at the earliest. - fn scheduled(self) -> Duration { - match self { - Held::Hang => SCHEDULED, - Held::Fault(_) => Duration::ZERO, - } - } - - /// How long after it read `Scheduled` and the GPU reached the encoder its wait goes. - fn after_reached(self) -> Duration { - match self { - Held::Hang => FROM_REACHED, - Held::Fault(_) => FAULT_FROM_REACHED, - } - } - - /// What the GPU recovers from as the wait goes: a hang's, and a fault's that a hang follows, - /// from a hang; else from a fault (`recovery.rs`). - fn recovery(self) -> Recovery { - match self.discards() { - true => Recovery::Hang, - false => Recovery::Fault, - } - } - - /// A fault's that later failures follow: how long after it read `Scheduled`, once the GPU - /// recovered from the fault, its wait goes: [`FAULT_FROM_REACHED`] for each later fault, then - /// [`FROM_REACHED`] for a hang. `None` for a hang's, and a fault's alone. - fn after_recovered(self) -> Option { - match self { - Held::Fault(Later { faults, hang }) if faults > 0 || hang => { - let hang = match hang { - true => FROM_REACHED, - false => Duration::ZERO, - }; - Some(FAULT_FROM_REACHED * faults + hang) - } - _ => None, - } - } -} - -/// A hanging or faulting command buffer's hold: the event of its signals and its wait. -pub(super) struct Hang { - event: SharedEvent, - /// The batch its signal of [`Hang::REACHED`] ends: the last before its wait. - batch: usize, - /// The ended encoder it holds after, the one Metal's GPU hangs or faults at. - encoder: usize, - held: Held, -} - -/// A command buffer's transition to `Scheduled` made apart from its last batch: around a hang of -/// its queue (the module docs), or early behind a host step of its queue's ([`Scheduling::Early`]). -pub(super) enum Scheduling { - /// The hold's own: its thread makes it once the batch before its wait (`batch`, - /// [`Hang::batch`]) was taken, submitted or held in a group (`group.rs`), a hang's no sooner - /// than [`SCHEDULED`] after the commit. - Hang { batch: usize, taken: bool }, - /// One committed while a hang of its queue was in flight: the hang's thread makes it early, - /// or its last batch does, whichever comes first. - Behind { made: bool }, - /// Made `Scheduled` before its last batch was taken, by the scheduler's thread: its remaining - /// batches waited only for a host step of its queue's head behind work already submitted, - /// every earlier command buffer of its queue `Scheduled` (`CommandBufferShared::schedule_early`, - /// `scheduler/mod.rs`, **Scheduled**), as a hang's thread makes the queue's command buffers - /// behind a hang `Scheduled` ([`Scheduling::Behind`]). No batch of it makes it again, and its - /// submission handlers, if any, run in that pass's turn, not with its last batch. - Early, -} - -impl Hang { - /// The value its signal after the hanging encoder sets: the GPU reached the hang. - pub(super) const REACHED: u64 = 1; - /// The value its wait waits for, which its thread sets. - pub(super) const RELEASED: u64 = 2; - /// The value its signal after all its work sets. - pub(super) const DONE: u64 = 3; - - /// A hold of `device` for `held`, its event at 0, whose signal of [`Hang::REACHED`] ends - /// batch `batch`, after ended encoder `encoder`. - pub(super) fn new( - device: &Device, - (batch, encoder): (usize, usize), - held: Held, - ) -> Result { - Ok(Hang { - event: device.new_shared_event_now()?, - batch, - encoder, - held, - }) - } - - /// The ended encoder it holds after. - pub(super) fn encoder(&self) -> usize { - self.encoder - } - - /// Metal's GPU fails a later ended encoder too, hanging there where `hangs`, else faulting: - /// a fault's hold counts it, the GPU reaching it once it recovered, unless a hang came before - /// it, past which the GPU reaches nothing (the module docs). - pub(super) fn fails_later(&mut self, hangs: bool) { - let Held::Fault(later) = &mut self.held else { - return; - }; - match (later.hang, hangs) { - (true, _) => {} - (false, true) => later.hang = true, - (false, false) => later.faults += 1, - } - } - - /// The event of its signals and its wait. - pub(super) fn event(&self) -> &SharedEvent { - &self.event - } - - /// The command buffer does not run its hang: its wait goes at once. - pub(super) fn release(self) { - self.event.set_signaled_value(Hang::DONE); - } - - /// The command buffer `buffer`, of state `state`, committed at `committed`, runs its hold: - /// its queue counts it until its work signalled [`Hang::DONE`] (a hang's, and a fault's that - /// a hang follows, among those that discard the queue's others; another fault's among those - /// that do not); it reads `Scheduled` [`SCHEDULED`] after the commit (a hang's) or at once (a - /// fault's), or later once the batch before its wait was taken ([`Scheduling::Hang`]), and the - /// queue's command buffers committed meanwhile follow ([`QueueHangs::schedule_early`]); its - /// wait goes [`FROM_REACHED`] (a hang's) or [`FAULT_FROM_REACHED`] (a fault's) after it read - /// `Scheduled` and the GPU reached the encoder. A fault's that later failures follow reads - /// `Scheduled` [`FAULT_FROM_REACHED`] after the GPU reached the encoder, and its wait goes - /// [`Held::after_recovered`] after that. One with a switch of storage forms riding on its - /// commit, which settles by its last batch's submission, reads `Scheduled` with that batch, - /// as do the queue's others. Where no thread can be made for that, the wait goes at once, the - /// queue not counting it. - pub(super) fn start( - self, - buffer: &Arc, - state: &mut State, - committed: Instant, - ) { - let queue = &buffer.queue; - let hangs = Arc::clone(queue.hangs()); - let trails = Arc::clone(&queue.device().shared().trails); - let recoveries = Arc::clone(&queue.device().shared().recoveries); - let held = self.held; - hangs.counter(held).fetch_add(1, Ordering::SeqCst); - let hang = { - let mut early = lock(&hangs.early); - early.hang += 1; - early.hang - }; - if state.storage_form.is_none() { - state.hang_scheduling = Some(Scheduling::Hang { - batch: self.batch, - taken: false, - }); - } - let weak = Arc::downgrade(buffer); - let event = self.event.clone(); - let builder = std::thread::Builder::new().name("metal2vulkan-hang".to_owned()); - let ended = crate::exit_guard::spawn(builder, move || { - sleep_until(committed + held.scheduled()); - let (scheduled, release) = match held.after_recovered() { - // A fault that later failures follow reads `Scheduled` once the GPU recovered - // from it, and its wait goes once the GPU recovered from them too. - Some(after) => { - event.wait_until_signaled_value(Hang::REACHED, SIGNAL_BOUND); - std::thread::sleep(FAULT_FROM_REACHED); - recoveries.raise(Recovery::Fault); - (hang_scheduled(weak), Instant::now() + after) - } - None => { - let scheduled = hang_scheduled(weak); - event.wait_until_signaled_value(Hang::REACHED, SIGNAL_BOUND); - (scheduled, Instant::now() + held.after_reached()) - } - }; - match scheduled { - true => hangs.schedule_early(hang, release), - false => sleep_until(release), - } - let trail = trails.open(); - if held.discards() { - hangs.decide(); - } - recoveries.raise(held.recovery()); - event.set_signaled_value(Hang::RELEASED); - event.wait_until_signaled_value(Hang::DONE, SIGNAL_BOUND); - lock(&hangs.early).joined.clear(); - hangs.counter(held).fetch_sub(1, Ordering::SeqCst); - drop(event); - drop(hangs); - drop(trail); - }); - if ended.is_err() { - state.hang_scheduling = None; - if held.discards() { - queue.hangs().decide(); - } - lock(&queue.hangs().early).joined.clear(); - queue.hangs().counter(held).fetch_sub(1, Ordering::SeqCst); - self.event.set_signaled_value(Hang::DONE); - } - } -} - -/// Sleep until `until`, if it is still ahead. -fn sleep_until(until: Instant) { - if let Some(left) = until.checked_duration_since(Instant::now()) { - std::thread::sleep(left); - } -} - -/// The hanging command buffer `buffer` holds, where something still holds it, came to its time to -/// read `Scheduled` ([`Scheduling::Hang`]): it does once the batch before its wait was taken, its -/// submission handlers first on this thread. Where that batch is not taken within -/// [`SIGNAL_BOUND`] (an event wait before the hang not met), its last batch makes it instead, and -/// none where a batch of it could not be submitted (`CommandBufferShared::failed`). Whether it was -/// made here. -fn hang_scheduled(buffer: Weak) -> bool { - let Some(buffer) = buffer.upgrade() else { - return false; - }; - let deadline = Instant::now() + SIGNAL_BOUND; - let made = { - let mut state = lock(&buffer.state); - loop { - let left = deadline.saturating_duration_since(Instant::now()); - match state.hang_scheduling { - Some(Scheduling::Hang { taken: true, .. }) => { - let handlers = !state.submission.is_empty(); - state.submitting = handlers; - break Some(handlers); - } - Some(Scheduling::Hang { taken: false, .. }) - if !left.is_zero() && !exit_guard::closed() => {} - Some(Scheduling::Hang { taken: false, .. }) => { - state.hang_scheduling = None; - break None; - } - _ => break None, - } - state.parked += 1; - state = (buffer - .changed - .wait_timeout(state, left.min(exit_guard::WAKE))) - .unwrap_or_else(PoisonError::into_inner) - .0; - state.parked -= 1; - } - }; - if let Some(handlers) = made { - transition(&buffer, handlers); - } - let_go(buffer); - made.is_some() -} - -/// The command buffer `buffer` holds, where something still holds it, committed while a hang of -/// its queue was in flight, reads `Scheduled` here, where its last batch has not made it -/// ([`Scheduling::Behind`]): its kernel times then, its submission handlers first on this -/// thread. -fn behind_scheduled(buffer: Weak) { - let Some(buffer) = buffer.upgrade() else { - return; - }; - let made = { - let mut state = lock(&buffer.state); - match &mut state.hang_scheduling { - Some(Scheduling::Behind { made }) if !*made => { - *made = true; - let handlers = !state.submission.is_empty(); - state.submitting = handlers; - Some(handlers) - } - _ => None, - } - }; - if let Some(handlers) = made { - buffer.kernel.begin(); - transition(&buffer, handlers); - } - let_go(buffer); -} - -/// `buffer` becomes `Scheduled` here, its kernel end now: its transition, then its submission -/// handlers on this thread, which the transition waits for where `handlers` (the caller set -/// `submitting` under the state's lock). -fn transition(buffer: &Arc, handlers: bool) { - buffer.kernel.end_at(gpu_time::host_nanos()); - buffer.schedule(); - if handlers { - buffer.run_submission_handlers(); - } -} - -/// Let go of `buffer` here, unless this is its last reference, which holds the device: that goes -/// in a context of its own (`Device::let_go_elsewhere`), so the hang's thread never runs the -/// device's teardown. -fn let_go(buffer: Arc) { - if let Some(last) = Arc::into_inner(buffer) { - let (contexts, context) = last.device.elsewhere(); - contexts.post(context, Item::Release(Box::new(last))); - } -} - -/// Whether batch `index` of a command buffer, its last where `last`, makes it `Scheduled` as it -/// is submitted or held in a group ([`Scheduling`]): its last, but where its hang's thread makes -/// it, the hang's thread made it early, or the scheduler's thread did behind a host step -/// ([`Scheduling::Early`]); and whether it is the hang's batch before its wait, -/// taken now, which the hang's thread waits for (on the command buffer's `changed`). -pub(super) fn schedules( - scheduling: &mut Option, - index: usize, - last: bool, -) -> (bool, bool) { - match scheduling { - None => (last, false), - Some(Scheduling::Hang { batch, taken }) => { - let took = index == *batch && !*taken; - *taken |= took; - (false, took) - } - Some(Scheduling::Behind { made }) => { - let makes = last && !*made; - *made |= makes; - (makes, false) - } - Some(Scheduling::Early) => (false, false), - } -} - -/// Whether a command buffer of `scheduling` was made `Scheduled` early by the scheduler's thread -/// ([`Scheduling::Early`]): its submission handlers ran or run in that pass's turn, so a batch of -/// it taken since leaves its flag for them as it is. -pub(super) fn scheduled_early(scheduling: &Option) -> bool { - matches!(scheduling, Some(Scheduling::Early)) -} - -/// The command buffer `buffer`, of state `state`, committed on its queue while a hang of it is in -/// flight with the event waits `waits`, joins the hang's command buffers to make `Scheduled` -/// early ([`QueueHangs::schedule_early`]); not one with a switch of storage forms riding on its -/// commit, which settles by its last batch's submission. -pub(super) fn join( - buffer: &Arc, - state: &mut State, - waits: Vec<(Arc, u64)>, -) { - if state.storage_form.is_some() { - return; - } - state.hang_scheduling = Some(Scheduling::Behind { made: false }); - let hangs = buffer.queue.hangs(); - let mut early = lock(&hangs.early); - let hang = early.hang; - let buffer = Arc::downgrade(buffer); - early.joined.push_back(Joined { - hang, - waits, - schedule: Box::new(move || behind_scheduled(buffer)), - }); - drop(early); - hangs.joined.notify_all(); -} - -/// Whether a hang of `queue` is in flight (the module docs). -pub(super) fn in_flight(queue: &QueueGen) -> bool { - queue.hangs().in_flight.load(Ordering::SeqCst) > 0 -} - -/// Whether a fault's hold of `queue` is in flight (the module docs): a command buffer committed -/// on it now reads `Scheduled` early, and runs. -pub(super) fn holding(queue: &QueueGen) -> bool { - queue.hangs().holding.load(Ordering::SeqCst) > 0 -} - -/// The verdict of a command buffer committed on `queue` with the event waits `waits` gives, -/// listed for the hang's decision where a hang of the queue is in flight; `None` where none is -/// (the module docs). -pub(super) fn behind(queue: &QueueGen, waits: &[(Arc, u64)]) -> Option { - if !in_flight(queue) { - return None; - } - let verdict = Verdict::default(); - lock(&queue.hangs().behind).push(Behind { - waits: waits.to_vec(), - verdict: verdict.clone(), - }); - Some(verdict) -} - -/// How a command buffer committed on `queue` with `event_waits` event waits of its own fails -/// where a hang of the queue is in flight: it runs nothing and completes with no error, its -/// signals firing (the module docs). `None` where none is, or where it waits for an event, which -/// its first batch's submission decides. -pub(super) fn discarded(queue: &QueueGen, event_waits: usize) -> Option { - (in_flight(queue) && event_waits == 0).then_some(CommitFailure { - code: 0, - encoders: FailedEncoders::From(0), - signals: true, - }) -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs b/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs deleted file mode 100644 index 58c8792e3..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs +++ /dev/null @@ -1,463 +0,0 @@ -//! A batch's barrier command buffers, recorded once and submitted again. -//! -//! A batch with encoders submits a command buffer of barriers before each encoder the tracker -//! planned a barrier for (before its first, whatever was planned, where the driver's submissions -//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end did -//! not go into its last encoder's command buffer, one after its last (`Barrier::to_host`, or -//! `Barrier::to_all`: `batch_order.rs`; `submit.rs`): batch after batch, the same few lists of -//! barriers. A timed command buffer's first batch also resets its slot of the device's timestamp -//! pools and writes the start timestamp first, in a command buffer before its first encoder (of the -//! barrier planned for it, or of none), and its last batch writes the end timestamp in its end -//! (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and -//! submitted again by a later batch once the batch that last carried it completed, its queue's -//! timeline at that batch's value as the host saw it: the same commands, in the same place of the -//! same submission, and no command buffer begun for them as a batch is submitted. ANV clears a -//! command buffer's state as its pool resets it and again as it begins it (Mesa 26.2.4, -//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary one's -//! begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's Iris Xe -//! those begins were 53% of the scheduler thread's user time, two a command buffer. -//! -//! - **Never pending twice.** A kept command buffer is recorded without -//! `VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT` and goes to one batch at a time: ANV chains a -//! submission's command buffers into one batch buffer only where none has that flag -//! (`anv_cmd_buffer_is_chainable`), and submits the rest one execbuffer each. The batch that -//! takes one marks it with its own timeline value before it is submitted: a batch whose -//! submission fails leaves that value to the queue's next batch, so the command buffer waits -//! for that one instead. Chained so, a kept command buffer names in each submission every -//! command buffer that ever came next after it, and the submission fails once one of those was -//! trimmed away (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`): there the -//! spares trim their pools only in trim rounds, each once every kept command buffer was marked -//! to be recorded again before a batch takes it ([`KeptBarriers::invalidate`], `spares.rs`). -//! - **Timestamps, per slot.** A command buffer that writes timestamps writes them into one slot's -//! two queries, so it is kept for its slot ([`SlotStamps`]): one per slot and list, taken again -//! only by a batch of a later holding of that slot (`gpu_time::Slot::lease`), once the batch -//! that last took it completed. A slot is taken again only once given back, which its command -//! buffer does after the completion turn read its timestamps (`read_stamps`): so a kept -//! command buffer writes the slot's queries again only after the results the last holding -//! wrote were read, and after the slot was reset on the host as it was taken again -//! (`gpu_time.rs`). On a device that does not reset slots on the host (an adopted one), the -//! start's reset of the slot's two queries stays in the kept command buffer, before its start -//! timestamp. Vulkan (`vkCmdResetQueryPool`): "When executed on a queue, this command sets the -//! status of query indices [firstQuery, firstQuery + queryCount - 1] to unavailable": at each -//! submission of the kept command buffer again. -//! - **Where.** On every `VkQueue` but one whose command buffers end at a fence -//! (`fences::ends_at_fence`): MoltenVK reads a command buffer after its timeline signal and -//! refuses one submitted again before its completed handler ran. A barrier command buffer that -//! moves the caller's images is recorded by its batch, as before. -//! - **Bounded.** At most [`LISTS`] lists of barriers alone per `VkQueue`, each with at most -//! [`KEPT`] command buffers, as many as its batches in flight at once needed, and as many lists -//! that write timestamps, each with at most [`KEPT`] slots' command buffers: past them a batch -//! records its own into its command buffer's pool. They live in a command pool of the queue's -//! family, made at the first, and go with the device once its queues are idle. -//! - **Lists that went out of use give way.** A list met while [`LISTS`] of its kind are kept -//! replaces the one taken least lately among those no batch took in the last [`STALE`] values -//! of the queue's timeline and whose command buffers all completed, so the lists a program's -//! first batches met do not hold the places for its life. Its command buffers are kept for the -//! lists' later recordings, each recorded again from the start (the pool resets one at its -//! begin, `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`). Lists all in use in turn, more -//! than [`LISTS`] of them, replace none: the first kept stay kept and the rest are recorded by -//! their batches, where replacing one at each use would record every list at each of its uses. -//! - **Counted.** `WorkCounts::barrier_buffers_kept` and `WorkCounts::stamped_buffers_kept` count -//! the recordings to keep, `WorkCounts::stamped_buffers_reused` the stamped ones taken again. -//! - **Inside the scheduler's section**: every call is in the exit guard's table. - -use crate::error::{vulkan, Error}; -use crate::exit_guard::{self, Call}; -use crate::release; -use crate::tracker::Barrier; -use crate::work_counts::Begun; -use crate::Device; -use ash::vk; -use std::collections::VecDeque; - -/// The most lists of barriers a `VkQueue` keeps command buffers of. -pub(crate) const LISTS: usize = 8; - -/// The most command buffers a `VkQueue` keeps of one list of barriers. -pub(crate) const KEPT: usize = 128; - -/// How many values of its queue's timeline a list no batch took stays kept for before a new list -/// may replace it: a few frames of a window server's (67 or more batches a frame). -pub(crate) const STALE: u64 = 256; - -/// The scheduler's kept barrier command buffers, by `VkQueue` (`scheduler::State::kept`). -#[derive(Default)] -pub(crate) struct KeptBarriers { - queues: Vec, -} - -/// The timestamps a barrier command buffer writes into a timed command buffer's slot of the -/// device's timestamp pools (`gpu_time::Slot`): with `start`, the slot reset before its barriers -/// and the start timestamp before them at the top of the pipe (`batch_order.rs`: where batches -/// are ordered by their ends, the earlier batch's end barrier holds it), or with `after` after them -/// at the bottom of the pipe; -/// with `end`, the end timestamp after them. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct SlotStamps { - /// The slot's timestamp pool. - pub(crate) queries: vk::QueryPool, - /// Its first query, the start; the end is the next. - pub(crate) first: u32, - /// The holding of the slot the batch is of (`gpu_time::Slot::lease`). - pub(crate) lease: u64, - pub(crate) start: bool, - /// The start written after the barriers, once every command before them completed - /// (`command_buffer/submit.rs`). - pub(crate) after: bool, - pub(crate) end: bool, -} - -/// One `VkQueue`'s. -#[derive(Default)] -pub(crate) struct QueueKept { - /// The pool they are made from; null until the first. - pool: vk::CommandPool, - /// Lists of barriers alone. - lists: Vec, - /// Lists that also write a slot's timestamps, kept per slot. - stamped: Vec, - /// The command buffers of the lists replaced, each completed, for later recordings. - spare: Vec, - /// The times its command buffers were marked to be recorded again - /// ([`invalidate`](Self::invalidate)): one recorded before the last is recorded again before - /// a batch takes it. - epoch: u64, -} - -/// What a batch takes of a `VkQueue`'s kept command buffers ([`QueueKept::take`]). -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum Take { - /// A kept command buffer of the list, whose last batch completed: the batch's now. - Kept(vk::CommandBuffer), - /// A command buffer to record for the list at this index, then kept - /// ([`QueueKept::recorded`]): a spare one where there is one, else one allocated. - Record(usize), - /// None: past the bounds, the batch records its own. - Past, -} - -/// The command buffers of one list of barriers, in the order of the batches that last took them. -struct KeptList { - barriers: Vec, - /// Which timestamps its command buffers write, `(start, after, end)` as [`SlotStamps`] - /// says: none for barriers alone. - stamps: Option<(bool, bool, bool)>, - buffers: VecDeque, -} - -/// A kept command buffer, and the timeline value of the batch that last took it. -struct Kept { - raw: vk::CommandBuffer, - after: u64, - /// Its queue's [`QueueKept::epoch`] as it was recorded. - epoch: u64, - /// Where it writes timestamps: the slot's pool and first query, and the lease of the holding - /// whose batch last took it. - slot: Option<(vk::QueryPool, u32, u64)>, -} - -impl KeptList { - /// The last batch that took one of its command buffers; every one completed with it. - fn last(&self) -> u64 { - self.buffers.back().map_or(0, |kept| kept.after) - } -} - -impl QueueKept { - /// What the batch that signals `at` takes for `barriers`, writing `stamps` where given, its - /// queue's timeline completed through `completed`. - pub(crate) fn take( - &mut self, - barriers: &[Barrier], - stamps: Option, - at: u64, - completed: u64, - ) -> Take { - let kind = stamps.map(|stamps| (stamps.start, stamps.after, stamps.end)); - let lists = match stamps { - Some(_) => &mut self.stamped, - None => &mut self.lists, - }; - let found = lists - .iter() - .position(|list| list.barriers == barriers && list.stamps == kind); - let index = match found { - Some(index) => index, - None if lists.len() < LISTS => { - lists.push(KeptList { - barriers: barriers.to_vec(), - stamps: kind, - buffers: VecDeque::new(), - }); - lists.len() - 1 - } - None => match out_of_use(lists, at, completed) { - Some(index) => { - let list = &mut lists[index]; - self.spare - .extend(list.buffers.drain(..).map(|kept| kept.raw)); - list.barriers.clear(); - list.barriers.extend_from_slice(barriers); - list.stamps = kind; - index - } - None => return Take::Past, - }, - }; - let list = &mut lists[index]; - let Some(stamps) = stamps else { - // The batches that took them did so in their timeline values' order: the first is - // the one that may have completed. - if list.buffers.front().is_some_and(|k| k.after <= completed) { - if let Some(mut taken) = list.buffers.pop_front() { - // Marked to be recorded again: recorded into for this batch. - if taken.epoch < self.epoch { - self.spare.push(taken.raw); - return Take::Record(index); - } - taken.after = at; - let raw = taken.raw; - list.buffers.push_back(taken); - return Take::Kept(raw); - } - } - if list.buffers.len() >= KEPT { - return Take::Past; - } - return Take::Record(index); - }; - // The slot's own: taken again by a later holding of the slot, once it completed. One - // that is not (pending, or this holding's already) leaves the batch to record its own. - let of_slot = list.buffers.iter().position(|kept| { - kept.slot.is_some_and(|(queries, first, _)| { - queries == stamps.queries && first == stamps.first - }) - }); - match of_slot { - Some(at_index) => { - let ready = list.buffers[at_index].after <= completed - && list.buffers[at_index] - .slot - .is_some_and(|(_, _, lease)| lease < stamps.lease); - if !ready { - return Take::Past; - } - let Some(mut taken) = list.buffers.remove(at_index) else { - return Take::Past; - }; - if taken.epoch < self.epoch { - self.spare.push(taken.raw); - return Take::Record(index); - } - taken.after = at; - taken.slot = Some((stamps.queries, stamps.first, stamps.lease)); - let raw = taken.raw; - list.buffers.push_back(taken); - Take::Kept(raw) - } - None if list.buffers.len() >= KEPT => Take::Past, - None => Take::Record(index), - } - } - - /// A spare command buffer to record, where a replaced list left one. - pub(crate) fn spare(&mut self) -> Option { - self.spare.pop() - } - - /// Mark every command buffer kept so far to be recorded again before a batch takes it: once - /// begun again, it names no command buffer that came next after it before (the module docs). - pub(crate) fn invalidate(&mut self) { - self.epoch += 1; - } - - /// `raw`, recorded for the list at `list` ([`Take::Record`]) of the kind `stamps` gives, - /// taken by the batch that signals `at`. - pub(crate) fn recorded( - &mut self, - list: usize, - raw: vk::CommandBuffer, - at: u64, - stamps: Option, - ) { - let lists = match stamps { - Some(_) => &mut self.stamped, - None => &mut self.lists, - }; - lists[list].buffers.push_back(Kept { - raw, - after: at, - epoch: self.epoch, - slot: stamps.map(|stamps| (stamps.queries, stamps.first, stamps.lease)), - }); - } - - /// Each list's barriers and its command buffers in order, those of barriers alone then those - /// that write timestamps, with the spare ones. - #[cfg(test)] - pub(crate) fn lists( - &self, - ) -> ( - Vec<(Vec, Vec)>, - Vec, - ) { - let lists = self - .lists - .iter() - .chain(&self.stamped) - .map(|list| { - let buffers = list.buffers.iter().map(|kept| kept.raw).collect(); - (list.barriers.clone(), buffers) - }) - .collect(); - (lists, self.spare.clone()) - } -} - -/// The list of `lists` a new one replaces, its queue's timeline at `at` and completed through -/// `completed`: of those no batch took since `at - STALE` and whose command buffers all -/// completed, the one taken least lately. -fn out_of_use(lists: &[KeptList], at: u64, completed: u64) -> Option { - lists - .iter() - .enumerate() - .filter_map(|(index, list)| { - let last = list.last(); - (last <= completed && last.saturating_add(STALE) <= at).then_some((last, index)) - }) - .min() - .map(|(_, index)| index) -} - -impl KeptBarriers { - /// A command buffer of `device`'s `VkQueue` `queue` holding only `barriers` (each recorded - /// as [`Barrier::record`] records it), between the timestamps `stamps` gives, for the batch - /// that signals `at` on that queue's timeline: a kept one whose last batch completed (and, - /// with timestamps, of an earlier holding of the slot), else one recorded now and kept. - /// `None` past the bounds (the module docs), where the batch records its own. - pub(crate) fn take( - &mut self, - device: &Device, - queue: usize, - barriers: &[Barrier], - stamps: Option, - at: u64, - ) -> Result, Error> { - let shared = device.shared(); - let completed = shared.queues[queue].completed_value(); - if self.queues.len() <= queue { - self.queues.resize_with(queue + 1, QueueKept::default); - } - let kept = &mut self.queues[queue]; - let list = match kept.take(barriers, stamps, at, completed) { - Take::Kept(raw) => { - if stamps.is_some() { - shared.counts.stamped_buffer_reused(); - } - return Ok(Some(raw)); - } - Take::Past => return Ok(None), - Take::Record(list) => list, - }; - let raw = shared.vk(); - if kept.pool == vk::CommandPool::null() { - // Each command buffer is reset at its begin: a replaced list's are recorded again. - let info = vk::CommandPoolCreateInfo::default() - .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER) - .queue_family_index(shared.queue_family_of(queue)); - // SAFETY: the device is live and `info` valid. - let pool = unsafe { raw.create_command_pool(&info, None) }; - exit_guard::called(Call::CreateCommandPool); - kept.pool = pool.map_err(vulkan)?; - } - let buffer = match kept.spare() { - Some(buffer) => buffer, - None => { - let info = vk::CommandBufferAllocateInfo::default() - .command_pool(kept.pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - device.allocate_command_buffers(&info)?[0] - } - }; - // Submitted again, one batch at a time: neither one-time nor simultaneous. - let begin = vk::CommandBufferBeginInfo::default(); - // SAFETY: the command buffer is the scheduler pool's, used under its lock, and only this - // call records it: just allocated, or a spare one, whose every batch completed (none is - // pending), which its begin resets (the pool's `RESET_COMMAND_BUFFER`). The slot's - // queries are the timestamp pool's, live while the device is. - unsafe { - let begun = raw.begin_command_buffer(buffer, &begin); - exit_guard::called(Call::BeginCommandBuffer); - begun.map_err(vulkan)?; - shared.counts.command_buffer_begun(Begun::KeptBarriers); - if let Some(stamps) = stamps.filter(|stamps| stamps.start) { - if !shared.timing.resets_on_host() { - raw.cmd_reset_query_pool(buffer, stamps.queries, stamps.first, 2); - exit_guard::called(Call::CmdResetQueryPool); - } - if !stamps.after { - let top = vk::PipelineStageFlags::TOP_OF_PIPE; - raw.cmd_write_timestamp(buffer, top, stamps.queries, stamps.first); - exit_guard::called(Call::CmdWriteTimestamp); - } - } - // Of the queue's family: a copy engine's on the copy queue's `VkQueue`. - let reads = shared.memory_reads_of(queue); - for barrier in barriers { - barrier.record_reading(raw, buffer, reads); - exit_guard::called(Call::CmdPipelineBarrier); - } - if let Some(stamps) = stamps.filter(|stamps| stamps.start && stamps.after) { - let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; - raw.cmd_write_timestamp(buffer, bottom, stamps.queries, stamps.first); - exit_guard::called(Call::CmdWriteTimestamp); - } - if let Some(stamps) = stamps.filter(|stamps| stamps.end) { - let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; - raw.cmd_write_timestamp(buffer, bottom, stamps.queries, stamps.first + 1); - exit_guard::called(Call::CmdWriteTimestamp); - } - let ended = raw.end_command_buffer(buffer); - exit_guard::called(Call::EndCommandBuffer); - ended.map_err(vulkan)?; - } - match stamps { - Some(_) => shared.counts.stamped_buffer_kept(), - None => shared.counts.barrier_buffer_kept(), - } - self.queues[queue].recorded(list, buffer, at, stamps); - Ok(Some(buffer)) - } - - /// Whether `raw` is one of `VkQueue` `queue`'s kept command buffers, with the timeline value - /// of the batch that last took it: what a failed submission's line names it by - /// (`submit_failure.rs`). - pub(crate) fn kept(&self, queue: usize, raw: vk::CommandBuffer) -> Option { - let kept = self.queues.get(queue)?; - (kept.lists.iter().chain(&kept.stamped)) - .flat_map(|list| &list.buffers) - .find(|kept| kept.raw == raw) - .map(|kept| kept.after) - } - - /// Mark every `VkQueue`'s kept command buffers to be recorded again before a batch takes one - /// ([`QueueKept::invalidate`]): before a trim round (`spares.rs`), under the scheduler's - /// state, while no batch holds one it took. - pub(crate) fn invalidate(&mut self) { - for kept in &mut self.queues { - kept.invalidate(); - } - } - - /// Release the pools, with every kept command buffer, as the device is torn down after its - /// queues are idle. - pub(crate) fn release(&mut self, raw: &ash::Device) { - for kept in self.queues.drain(..) { - if kept.pool != vk::CommandPool::null() { - // SAFETY: the device's queues are idle: no kept command buffer is pending. - unsafe { release::object(raw, kept.pool) }; - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/labels.rs b/crates/metal2vulkan-runtime/src/command_buffer/labels.rs deleted file mode 100644 index 1a3f9a9e0..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/labels.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! The labels a program gives a command buffer and its encoders (`MTLCommandBuffer.label`, -//! `MTLCommandEncoder.label`), and the command buffer as a notice names it with them: the -//! recovery from a lost device names the command buffer it failed as the hang so -//! (`device/line.rs`). An encoder's label is its command buffer's open encoder's until it ends: -//! a command buffer has one encoder open at a time, and the record of an ended one keeps it -//! ([`CommandBuffer::ended_encoders`]). - -use super::{CommandBuffer, State}; -use crate::EncoderKind; -use std::fmt::Write; - -/// The ended encoders a command buffer's naming lists, at most: it counts the rest. -const NAMED_ENCODERS: usize = 32; - -impl CommandBuffer { - /// `label`: the label [`set_label`](Self::set_label) gave it, or `None`, as Metal's is `nil` - /// until set. - pub fn label(&self) -> Option { - self.state().label.clone() - } - - /// `setLabel:`: label it `label`, at any time, committed or not, as Metal's. The runtime's - /// notices that name the command buffer state it: the recovery from a lost device names the - /// command buffer it failed as the hang by its label, with its encoders' kinds and labels - /// (`Degradation::DeviceRecovered`). - pub fn set_label(&self, label: &str) { - self.state().label = Some(label.to_owned()); - } - - /// Label its open encoder `label` (an encoder's `set_label`). - pub(crate) fn label_open_encoder(&self, label: &str) { - self.state().open_label = Some(label.to_owned()); - } - - /// The label of its open encoder (an encoder's `label`). - pub(crate) fn open_encoder_label(&self) -> Option { - self.state().open_label.clone() - } -} - -impl State { - /// The command buffer as a notice names it, of the queue labeled `queue` where it has a label: - /// its label and its queue's, then each of its first [`NAMED_ENCODERS`] ended encoders by its - /// place, its kind and its label, and the count of the rest. - pub(crate) fn named(&self, queue: Option<&str>) -> String { - let mut named = match &self.label { - Some(label) => format!("command buffer `{label}`"), - None => "a command buffer".to_owned(), - }; - if let Some(queue) = queue { - let _ = write!(named, " of queue `{queue}`"); - } - let count = self.ended.len(); - if count == 0 { - named.push_str(" (no encoder ended)"); - return named; - } - let plural = if count == 1 { "" } else { "s" }; - let _ = write!(named, " (its {count} encoder{plural}:"); - for (place, record) in self.ended.iter().enumerate().take(NAMED_ENCODERS) { - let kind = match record.kind { - EncoderKind::Blit => "blit", - EncoderKind::Compute => "compute", - EncoderKind::Render => "render", - EncoderKind::ResourceState => "resource state", - }; - let comma = if place == 0 { "" } else { "," }; - let _ = write!(named, "{comma} {place} {kind}"); - if let Some(label) = &record.label { - let _ = write!(named, " `{label}`"); - } - } - if count > NAMED_ENCODERS { - let _ = write!(named, ", and {} more", count - NAMED_ENCODERS); - } - named.push(')'); - named - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs deleted file mode 100644 index 0765a14e2..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ /dev/null @@ -1,7912 +0,0 @@ -//! `CommandBuffer` (`MTLCommandBuffer`). -//! -//! A command buffer owns a command pool of its own: each encoder records into a `VkCommandBuffer` -//! from it when its commands are encoded ([`encoder`](super::encoder)). The pool is a spare of -//! the device's where it has one, which a command buffer that completed gave back -//! ([`spares`](super::spares)). Its event waits and signals split its encoders into batches -//! ([`batches`]); `commit` hands them to the device's scheduler ([`scheduler`](super::scheduler)), -//! which submits each once the events it waits for are reached ([`submit`]), and their -//! `VkQueue`'s waiter ([`completion`]) sees them complete. One encoder is open at a time; an -//! encoder dropped without `end_encoding` loses its commands, so the command buffer can no longer -//! be committed. -//! -//! Statuses follow Metal's: `NotEnqueued`, then `Committed` at `commit`, `Scheduled`, and -//! `Completed` or `Error`. The transitions after `Committed` run in the queue's serial context on -//! the device's handler threads ([`contexts`]), in the queue's order: to -//! `Scheduled` once its last batch is submitted (every wait of it satisfied), with its scheduled -//! handlers; to `Completed` once its work completed, with its completed handlers and the release of -//! what it retained. A transition that runs none of the program's code runs where it is seen -//! instead, where its context is free: to `Scheduled` on the scheduler's thread -//! (`CommandBufferShared::schedule`), to `Completed` on the queue waiter -//! (`CommandBufferShared::finish_here`), which also runs one whose only code of the program's is -//! its completion-seen handlers (a runtime extension), right after its status is final. As on -//! Metal, a queue's command buffer whose work completed -//! stays `Committed` while an earlier transition of its queue, a handler, still runs. Its -//! submission handlers (a runtime extension) run before its transition to `Scheduled`, on the -//! thread that took its last batch for its queue (submitted it, or held it for one kernel -//! submission with later batches: `group.rs`), which the transition waits for. -//! -//! Encoders write their commands' own data (tables, neutral buffers) into the command buffer's -//! upload arena ([`upload`](super::upload)), and the execution status words its commands share; the -//! command buffer decodes them when it completes ([`CommandBuffer::execution_report`]) and releases -//! the arena and what it retained. - -pub(super) mod batches; -mod carried; -pub(super) mod checks; -pub(super) mod completion; -mod copies_again; -pub(super) mod fences; -mod first_submission; -mod fold; -pub(super) mod follow; -pub(super) mod gate; -mod group; -pub(super) mod hang; -pub(super) mod kept_barriers; -mod labels; -pub(super) mod own; -mod protection; -pub(super) mod rebound_use; -pub(super) mod recovery; -mod reencode; -pub(super) mod rerun; -pub(super) mod revocation; -pub(super) mod spare_states; -mod stall; -mod storage_form; -mod submit; -#[cfg(unix)] -mod sync_file; - -pub(super) use completion::Completion; -use copies_again::CopiesAgain; -pub(super) use first_submission::{NotedTable, ReplayTable}; -use follow::{Follow, Release}; -#[cfg(test)] -pub(super) use group::{within_run, GROUP_RUN}; -pub(super) use group::{Alone, Group, GroupEnd, GROUP_BATCHES}; -use rebound_use::{ReboundUse, Unlogged}; -use spare_states::{KeptState, Room}; -pub(crate) use stall::Stop; -pub(super) use submit::{BatchLists, Submitting}; - -use super::apple_only::AppleOnly; -use super::commit_times::{self, CommitClock, Phase}; -use super::compute::EncoderState; -use super::contexts::{self, Contexts, Run}; -use super::copied::CopiesReached; -use super::deferred::{Deferred, Prepared, StepInputs}; -use super::degradation::{Degradation, NoticesFor}; -use super::descriptor_arena::DescriptorArena; -use super::device::relay::{self, Relayed}; -use super::device::{lock, DeviceShared}; -use super::dirty_pages::DirtyCommit; -use super::encoder::{Recorded, Segment}; -use super::encoder_fold::FoldOrder; -use super::error::{ - internal, invalid, vulkan, CommandBufferError, DeadlockCause, EncoderCall, Error, - FailedPipeline, FailedState, MemoryKind, MeshRecordsOverflow, PipelineCreationCause, Problem, - TessellationRecordsOverflow, TimedOut, -}; -use super::event::{EventRef, EventShared, SharedEvent}; -use super::execution::Execution; -use super::exit_guard::{self, Call}; -use super::fresh_unwritten::{FreshLog, FreshUnwritten}; -use super::function_table::TableSnapshot; -use super::gpu_pools::{IndexPool, PoolKind, PoolLease}; -use super::gpu_time::{self, KernelTimes, Life, Placement, Stamped, Times}; -use super::heap::Heap; -use super::heap_sets::HeapUse; -use super::kept_commands::KeptContext; -use super::live_buffers::LiveTable; -use super::managed::MayUse; -use super::managed_copy::AtCompletion; -use super::merge_scratch::MergeScratch; -use super::pass_runs::{PassRuns, RunKeep, RunPoint}; -use super::pipeline::budget::Urgency; -use super::pipeline::kept::StepNumbers; -use super::pipeline::{Pending, RawPipeline}; -use super::predication::{Event, Predication}; -use super::program_objects; -use super::queue::{QueueGen, Slot}; -use super::rebind::{Holds, SubmittedHolds, Taken}; -use super::render::{Carried, EndInFlight, NoneKept}; -use super::replay::{CallLog, ComputeCall, Replay}; -use super::residency::Residency; -use super::resource::{ObjectId, ResourceKey}; -use super::retained::Lately; -use super::scheduler::{BatchSync, Hand, StepWaits}; -use super::shadow::{ShadowCarry, Takes}; -use super::spares::{CommandPool, Opened}; -use super::sparse::encoder::SparseUpdate; -use super::sparse::indirect; -use super::submit_failure::{submit_failed, try_lock, Failed}; -use super::texture::faces::TurnPoint; -use super::texture::storage_form::Riding; -use super::texture::Texture; -use super::tracker::{Footprint, Summary, Use}; -use super::unique_identifier::ScheduledWork; -use super::upload::{Upload, Uploads}; -use super::used_resources::{names_any, names_of, EncoderKind, EncoderRecord, Reached, ReadRecord}; -use super::values::CommandBufferStatus; -use super::work_counts::{CarryDropped, Counters, NoneKeptNext}; -use super::write_routes::{AtCommit, Routes}; -use super::{Buffer, CommandQueue, Device}; -use crate::release; -use ash::vk; -use batches::Batches; -use checks::{Checks, SubmissionCheck}; -use completion::Submitted; -use first_submission::{Listing, Live}; -use gate::{Count, Gate, Hold}; -use hang::{Hang, Held, Later}; -use metal2vulkan::bind::{ - ExecutionStatus, IndexBoundsPass, ReplayFaults, ResidentRange, ResidentSet, RootTable, - StatusReport, -}; -use metal2vulkan::device::PipelineWaitPolicy; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::DispatchType; -use own::{ - completed_wait, running, scheduled_wait, Answer, Context, Marker, Running, Step, Target, -}; -use std::any::Any; -use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque}; -use std::ops::Range; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, TryLockError}; -use std::time::{Duration, Instant}; - -/// No batch's host step is handed to the steps' thread (`CommandBufferShared::stepping`). -const NOT_STEPPING: u64 = u64::MAX; - -/// A scheduled or completed handler (`MTLCommandBufferHandler`): called once with the command buffer, on one of the -/// device's handler threads, in its queue's order. A panic inside it is caught. A submission -/// handler ([`CommandBuffer::add_submission_handler`]) is one too, called on the thread that -/// submits the command buffer's last batch, and so is a completion-seen handler -/// ([`CommandBuffer::add_completion_seen_handler`]), called on the thread that saw the command -/// buffer complete. -/// -/// - **macOS.** The handler threads run at the user-interactive quality of service, whatever the -/// class of the thread that committed, as Metal runs its handlers. A thread a handler starts -/// starts at the default class, as a new thread does (``). -/// - **Linux**, which Metal does not run on. Each handler thread asks the kernel to treat it as -/// fully busy, as the user-interactive class does on macOS: a utilization floor of 1024 -/// (`sched_setattr(2)`), its policy and nice value as they were. A kernel built without the -/// clamps refuses it, and the thread runs as before. The thread also has -/// `SCHED_FLAG_RESET_ON_FORK`, so a thread a handler starts begins with no floor, and at -/// `SCHED_OTHER` and nice 0 where the handler thread runs at a real-time policy or a negative -/// nice value; a handler cannot clear the setting without `CAP_SYS_NICE`. The first such floor -/// since the host booted turns the kernel's clamp accounting on for every task until it -/// reboots. -pub type Handler = Box; - -/// A Metal command buffer (`MTLCommandBuffer`). Cheap to clone (a retain); `Send + Sync`. -#[derive(Clone)] -pub struct CommandBuffer(Arc); - -impl std::fmt::Debug for CommandBuffer { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("CommandBuffer") - .field("status", &self.status()) - .finish() - } -} - -/// How a commit runs ([`CommandBuffer::commit_now`]). -#[derive(Clone, Copy, PartialEq, Eq)] -enum CommitRun { - /// Inside `commit` (or `commit_failed`). - AtCall, - /// After `commit` returned, its own work having waited for a render encoder's end - /// (`render/queued_commits.rs`). - Queued, - /// Again after that work refused it (`State::refuse_commit`): nothing of the command buffer - /// runs, and nothing that may fail is made for it (its predication tables, its root tables' - /// pointing, its function-table snapshots, its argument samplers' listing), so it commits. - Refused, -} - -/// A command buffer as the device's commits that wait hold it (`render/queued_commits.rs`): a -/// trait object, whose `Send` and `Sync` its bounds give, made with no allocation. A program's -/// crate proves the device's `Send` and `Sync` within its own recursion limit (rustc's 128 by -/// default), which a path through the command buffer once more passes (`E0275` in the validation -/// crate's statics). -pub(crate) trait Waiting: Send + Sync { - /// The command buffer. - fn command_buffer(self: Arc) -> CommandBuffer; - - /// The command buffer's address, which names it ([`CommandBuffer::is`]). - fn address(&self) -> usize; -} - -impl Waiting for CommandBufferShared { - fn command_buffer(self: Arc) -> CommandBuffer { - CommandBuffer(self) - } - - fn address(&self) -> usize { - CommandBufferShared::address(self) - } -} - -/// A command buffer that a holder does not keep ([`CommandBuffer::downgrade`]). -pub(crate) struct WeakCommandBuffer(std::sync::Weak); - -impl WeakCommandBuffer { - /// The command buffer, where something still holds it. - pub(crate) fn upgrade(&self) -> Option { - self.0.upgrade().map(CommandBuffer) - } -} - -/// Whether a command buffer completed, a handle that holds neither it nor what it holds -/// ([`CommandBuffer::finished`]). -pub(crate) struct Finished(Arc); - -impl Finished { - /// Whether its command buffer completed: the gate `wait_until_completed` waits for opened. - pub(crate) fn completed(&self) -> bool { - self.0.is_open() - } - - /// Whether it is `buffer`'s. - pub(crate) fn of(&self, buffer: &CommandBuffer) -> bool { - Arc::ptr_eq(&self.0, &buffer.0.gate) - } -} - -pub(super) struct CommandBufferShared { - /// Its ID ([`CommandBuffer::object_id`]), which the notices announced for its work name. - id: ObjectId, - /// The generation of its device it was made on (`device/line.rs`), taken once at its making: - /// its encoders' commands reach the device's state through it, at one load, with no kind of - /// handle to tell apart. Declared before `device`, so it goes first. - generation: Arc, - device: Device, - /// Its queue's place on the generation it was made on (`queue.rs`). - queue: QueueGen, - /// Its queue (`commandQueue`). - root: CommandQueue, - /// Its count among `root`'s command buffers, which the runtime tests' default queue limits' - /// check takes apart from the program's handles (`queue.rs`). Declared after `root`. - #[cfg(test)] - _counted: crate::queue::CountedCommandBuffer, - /// Its state: one a released command buffer of its device left, reset, or one built for it - /// where the device kept none; its release resets it for a command buffer made next - /// (`spare_states.rs`). - state: Arc>, - /// The slot of its queue it holds until it completes, or is dropped uncommitted - /// (`queue.rs`). Apart from the state, which a submission of its batches holds through - /// `vkQueueSubmit` (`submit.rs`): its commit hands the slot over once its batches are the - /// scheduler's ([`Slot::handed`]), and so returns while another thread holds the `VkQueue`, - /// as Metal's `commit` returns at once. - slot: Mutex>, - /// Signaled when the command buffer's status changes (`wait_until_scheduled` waits on it). - changed: Condvar, - /// What `wait_until_completed` waits for: the command buffer finished, and the runtime's - /// threads let go of it. - gate: Arc, - /// The `MTLCommandBufferError` code the driver relayed for one of its batches, with Metal's - /// description, empty until one (`device/relay.rs`). - relayed: Arc, - /// What its host step under way noted, where the device's encoder trail is on - /// (`encoder_trail.rs`, **Host steps**): set and taken by `record_host_step` around each - /// segment's step, and read by a submission the step waits for (`rerun.rs`). - step_trail: Mutex>, - /// The numbers its host steps give the variant instances they make, drawn at its commit in - /// the program's call (`pipeline/kept.rs`). - step_numbers: OnceLock, - /// Until when its recordings wait for its draws' and dispatches' pipelines still being made: - /// its commit plus the policy's `pipeline_commit_wait`, set at the commit under - /// `PipelineWaitPolicy::Bounded`; none under `PipelineWaitPolicy::Exact`, where they wait - /// until each is made (`render/pending.rs`, `pending_dispatch.rs`). A cold compile of - /// MoltenVK's on a cold Metal compiler service was measured at 11.6 s inside a state creation - /// a guest's command buffer encoding made (the guest's 10 s FIFO check ended its task); - /// docs/FAST-PATHS.md holds the row. - making_deadline: OnceLock, - /// The makings an execution's replay in its `commit` began itself and found still being - /// made at [`making_deadline`](Self::making_deadline) (`render/pending.rs`), until the pass it - /// replays for takes them and is left to its host step (`DeferredPass::left_for_makings`). - /// Apart from the state, as `own_textures`. - unmade: Mutex>>, - /// The textures its encoders made for their own commands (`Device::new_planned_texture`), - /// held from their making until it completes, whichever of its commands use them (its - /// first batch takes them, `submit.rs`). The device's next submission moves each one's image - /// from `UNDEFINED` to `GENERAL` (`texture/first_move.rs`). Apart from the state, so a texture - /// is made under no lock of the command buffer's. - own_textures: Mutex>, - /// The bytes a color fill of a color Metal packs no color in writes (`blit_fill.rs`): the - /// last color fill's packed texel over the ones before, from zeros. Apart from the state, - /// as `own_textures`. - fill_slot: Mutex<[u8; 16]>, - /// The scratch its ended encoders' merges are done with, lent to its later encoders' merges - /// (`merge_scratch.rs`). Apart from the state, as `own_textures`. - merge_scratch: Arc, - /// Rebinds since its commit, of buffers its replayable encoders named, whose encoders are - /// not yet encoded again (`reencode.rs`): its first submission waits until none is. Raised - /// under the device's lock of its buffers over host pages (`Rebinds::replace`), which its - /// first submission reads it under; apart from the state, which that lock comes after. - reencode: AtomicU64, - /// Held while its encoders are encoded again, one rebind's turn at a time, and while a host - /// step records: the recordings after its commit into its pool take turns, as Vulkan - /// synchronizes a pool's command buffers' recording externally. - reencoding: Mutex<()>, - /// The batch whose host step the scheduler handed to its steps' thread and which has not - /// ended (`scheduler/steps.rs`), [`NOT_STEPPING`] for none: the batch waits for it, and no - /// pass hands it over again. A command buffer steps one batch at a time: only its line's - /// head steps. - stepping: AtomicU64, - /// What its commands did that the device's logs of host pages hear of at its commit - /// (`dirty_pages.rs`), and its copied host buffers' merges back (`copied.rs`): collected - /// only while the device copied a shadow over logged pages in, imports logged pages in place, - /// or keeps a copied host buffer. Apart from the state, which no encoder holds while it - /// records. - pub(super) dirty: Mutex, - /// What its completion does for the two-copy buffers its commands used, before anything sees - /// it complete (`managed_copy.rs`, `completion.rs`): copies out into pages no import maps, - /// and copies in again of pages that drop the GPU's writes. Apart from the state, as `dirty`. - at_completion: Mutex>, - /// A command's uses went unnoted, nothing collecting them then (no copied host buffer, and - /// no log of host pages, lived): the merge back of copied host buffers takes every copy as - /// written by it (`copied.rs`). - pub(super) unnoted: AtomicBool, - /// The `VkCommandBuffer`s of its pool its recordings ended ([`CommandBuffer::end_raw`]): - /// where they are every one the pool handed out and it completed, it gives the pool back - /// with none recording (`spares.rs`). - raws_ended: AtomicU64, - /// The draws its recordings recorded into its pools' `VkCommandBuffer`s, with the state - /// commands they set, its host steps' among them ([`CommandBuffer::recorded`]): where they - /// reach `spares::RECORDED`, its pools free every command buffer they hold as it gives them - /// back (`spares.rs`). - recorded: AtomicU64, - /// Its kernel times, apart from the state, which the scheduler holds while it records and - /// submits a batch: a read waits for neither (`gpu_time.rs`). - kernel: KernelTimes, - /// Its status as `status` answers it, apart from the state for the same reason: each - /// transition of the state's status stores it here under the state's lock - /// ([`CommandBufferShared::answer`]), its raw value with release ordering, and a read loads - /// it with acquire ordering and takes no lock. Metal's reads wait for no submission. - status: AtomicU8, - /// Its error as `error` answers it: set once, by the completion that fails it, before that - /// stores the `Error` status, so a read that loads `Error` finds it. A commit takes nothing - /// here: no lock is taken first at a commit (on Apple's hosts a mutex allocates at its first - /// lock). - error: OnceLock, - /// Whether a batch of it is held in the scheduler's group, and whether a thread waits for its - /// completion: a group kept past a pass goes at once once one does (`group.rs`). - group_hold: AtomicU8, - /// Its commands' reads and writes of new textures' unwritten patterns, in encode order, which - /// its commit takes (`fresh_unwritten.rs`). Apart from the state: its encoders log into it. - fresh: FreshLog, - /// Its batches' footprints as the scheduler had them built, apart from the state: a kept one - /// is read without its lock ([`CommandBufferShared::footprint`]). - footprints: Footprints, -} - -/// The word [`CommandBufferShared::status`] holds for `status`: its raw value. -fn status_word(status: CommandBufferStatus) -> u8 { - status.raw() as u8 -} - -/// The status whose word ([`status_word`]) `word` is: every word stored is one of a status, the -/// last of them `Error`'s. -fn status_of(word: u8) -> CommandBufferStatus { - match word { - 0 => CommandBufferStatus::NotEnqueued, - 1 => CommandBufferStatus::Enqueued, - 2 => CommandBufferStatus::Committed, - 3 => CommandBufferStatus::Scheduled, - 4 => CommandBufferStatus::Completed, - _ => CommandBufferStatus::Error, - } -} - -/// How [`CommandBuffer::commit_failed`] fails a command buffer: a runtime extension, no Metal -/// type. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CommitFailure { - /// The `MTLCommandBufferError` code it fails with: 2 for a GPU hang (`Timeout`), 8 for out - /// of memory, 1 or 16 for a protection fault, among others. 0 for none: the encoders it names - /// run nothing, and it completes with status `Completed` and no error, as Metal completes a - /// command buffer of a queue whose GPU hang is in flight. - pub code: u64, - /// The encoders that run nothing, each by its place among those the command buffer ended, - /// in the order they ended, from 0 (the index of [`CommandBuffer::ended_encoders`]); the - /// others run. - pub encoders: FailedEncoders, - /// Whether its event signals (`encode_signal_event`) fire, as a GPU hang's do; none fires - /// where false, as for a protection fault. - pub signals: bool, -} - -impl CommitFailure { - /// A failure of `code` in which no encoder runs and the event signals fire. - pub fn new(code: u64) -> CommitFailure { - CommitFailure { - code, - encoders: FailedEncoders::From(0), - signals: true, - } - } - - /// Why `commit_failed` refuses the failure, the command buffer having ended `ended` - /// encoders: a set that names an encoder past them. - pub(super) fn problem(&self, ended: usize) -> Option { - let FailedEncoders::Set(set) = &self.encoders else { - return None; - }; - let past = set.range(ended..).next()?; - let saturated = |count: usize| u32::try_from(count).unwrap_or(u32::MAX); - Some(Problem::IndexOutOfRange { - index: saturated(*past), - limit: saturated(ended), - }) - } -} - -/// How a committing command buffer fails: as `commit_failed` asks, from an encoder Metal fails -/// it from (`State::fails_from`), or both. -#[derive(Debug, PartialEq, Eq)] -pub(super) struct Failure { - /// The encoders that run nothing. - pub(super) encoders: FailedEncoders, - /// The event signals that fire. - pub(super) signals: FailedSignals, - /// The error it completes with, if any. - pub(super) error: Option, -} - -/// Which event signals of a failing command buffer fire. -#[derive(Debug, PartialEq, Eq)] -pub(super) enum FailedSignals { - /// Every one (`CommitFailure::signals`). - Every, - /// None. - Dropped, - /// Those encoded before ended encoder `n`: Metal fails a command buffer from a render pass - /// without attachments past 16384 a side, and signals what was encoded before the pass, - /// not after it. - From(usize), -} - -impl Failure { - /// The failure of a command buffer committed on a queue Metal revoked (`revocation.rs`): no - /// encoder runs, no event signal fires, and it completes with - /// `CommandBufferError::AccessRevoked`. - pub(super) fn revoked() -> Failure { - Failure { - encoders: FailedEncoders::From(0), - signals: FailedSignals::Dropped, - error: Some(CommandBufferError::AccessRevoked), - } - } - - /// Whether ended encoder `encoder` runs under `failure`: every one does but those it fails. - pub(super) fn runs(failure: Option<&Failure>, encoder: usize) -> bool { - failure.is_none_or(|failure| !failure.encoders.fails(encoder)) - } - - /// The failure of a command buffer of `ended` ended encoders that `commit_failed` fails as - /// `injected` asks (none for `commit`), and that Metal fails from ended encoder `from` with - /// its error: the encoders either fails, and `injected`'s code where it is given, else - /// `from`'s error. `None` where neither fails it. - pub(super) fn of( - injected: Option, - from: Option<(usize, CommandBufferError)>, - ended: usize, - ) -> Option { - let injected_signals = |signals: bool| match signals { - true => FailedSignals::Every, - false => FailedSignals::Dropped, - }; - // A code of 0 is no error: the command buffer completes without one. - let injected_error = |code: u64| (code != 0).then_some(CommandBufferError::Injected(code)); - Some(match (injected, from) { - (None, None) => return None, - (Some(failure), None) => Failure { - encoders: failure.encoders, - signals: injected_signals(failure.signals), - error: injected_error(failure.code), - }, - (None, Some((from, error))) => Failure { - encoders: FailedEncoders::From(from), - signals: from_signals(from, error), - error: Some(error), - }, - (Some(failure), Some((from, error))) => Failure { - encoders: match failure.encoders { - FailedEncoders::From(first) => FailedEncoders::From(first.min(from)), - FailedEncoders::Set(mut set) => { - set.extend(from..ended); - FailedEncoders::Set(set) - } - }, - signals: match failure.signals { - true => from_signals(from, error), - false => FailedSignals::Dropped, - }, - error: injected_error(failure.code).or(Some(error)), - }, - }) - } - - /// `failure` (`Failure::of`'s) with the encoders Metal's GPU faults, `faulted`, each with - /// its error, of a command buffer of `ended` ended encoders: from the first faulted encoder on - /// they run nothing too, as Metal's GPU's recovery loses them on a GPU that ran just before - /// (`hang.rs`, the fault's hold), and, where nothing else fails it, the command buffer - /// completes with that encoder's error (`CommandBufferError::PageFault`, or - /// `GpuRecoveryVictim`) and every event signal fires, as Metal's does. Where something else - /// fails it too, its error and its signals stand (Metal's error there is not measured). - pub(super) fn with_faults( - failure: Option, - faulted: &BTreeMap, - ended: usize, - ) -> Option { - let Some((&first, &faulted_error)) = faulted.iter().next() else { - return failure; - }; - Some(match failure { - None => Failure { - encoders: FailedEncoders::From(first), - signals: FailedSignals::Every, - error: Some(faulted_error), - }, - Some(failure) => Failure { - // Under a failure of no error, a faulted encoder it lets run faults it. - error: failure - .error - .or_else(|| (!failure.encoders.fails(first)).then_some(faulted_error)), - encoders: match failure.encoders { - FailedEncoders::From(from) => FailedEncoders::From(from.min(first)), - FailedEncoders::Set(mut set) => { - set.extend(first..ended); - FailedEncoders::Set(set) - } - }, - ..failure - }, - }) - } -} - -/// The event signals that fire of a command buffer Metal fails from ended encoder `from` on with -/// `error`: every one at a GPU hang (`hang.rs`), those encoded before the encoder otherwise. -fn from_signals(from: usize, error: CommandBufferError) -> FailedSignals { - match error { - CommandBufferError::GpuHang => FailedSignals::Every, - _ => FailedSignals::From(from), - } -} - -/// The encoders a [`CommitFailure`] fails, each by its place among those the command buffer -/// ended, from 0: a runtime extension, no Metal type. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum FailedEncoders { - /// This encoder and every one after it, as a GPU hang fails the hung encoder's: the - /// encoders before it run. One past the ended encoders fails none. - From(usize), - /// These encoders alone: every other encoder runs, before and after them, as Metal runs - /// every submission but the one that failed (a submission that uses a resource whose - /// memory was taken away, measured by a consumer on an M3 Max, macOS 26.7). Each names an - /// ended encoder; an empty set fails none. - Set(BTreeSet), -} - -impl FailedEncoders { - /// These encoders and `more` besides, of `ended` ended encoders: a first failed encoder that - /// `more` reaches up to from below moves back to the first of them, and stays a suffix where - /// `more` holds no encoder before that; else a set (`encoder_fold.rs`'s **Failed**). - pub(super) fn with(self, more: &BTreeSet, ended: usize) -> FailedEncoders { - match self { - FailedEncoders::From(first) => { - let mut start = first; - while start > 0 && more.contains(&(start - 1)) { - start -= 1; - } - match more.iter().all(|&encoder| encoder >= start) { - true => FailedEncoders::From(start), - false => FailedEncoders::Set( - (first..ended.max(first)) - .chain(more.iter().copied()) - .collect(), - ), - } - } - FailedEncoders::Set(mut set) => { - set.extend(more); - FailedEncoders::Set(set) - } - } - } - - /// Whether encoder `encoder` runs nothing. - pub(super) fn fails(&self, encoder: usize) -> bool { - match self { - FailedEncoders::From(first) => encoder >= *first, - FailedEncoders::Set(set) => set.contains(&encoder), - } - } -} - -/// A part of a command buffer's state that its batches' footprints are built from (its ended -/// encoders' recordings, its batches), with a revision that every mutable access to it moves, -/// shared by both parts ([`Footprints::revision`]): a footprint built from them is kept while the -/// revision holds ([`CommandBufferShared::footprint`]), as nothing changes them but through such -/// an access, which holds the state's lock. Moved before the access returns, so a read of the -/// revision that sees it unmoved, with or without the lock, reads it before the change. -struct Revised { - value: T, - revision: Arc, -} - -impl Revised { - fn new(value: T, revision: &Arc) -> Revised { - Revised { - value, - revision: Arc::clone(revision), - } - } -} - -impl std::ops::Deref for Revised { - type Target = T; - - fn deref(&self) -> &T { - &self.value - } -} - -impl std::ops::DerefMut for Revised { - fn deref_mut(&mut self) -> &mut T { - self.revision.fetch_add(1, Ordering::AcqRel); - &mut self.value - } -} - -/// Each batch's footprint as the scheduler last had it built ([`CommandBufferShared::footprint`]), -/// apart from the state: a kept one is read without the state's lock, which a host step's draws -/// and a commit's work take, so the scheduler's passes, one at each commit and completion on -/// every queue, wait for neither. -struct Footprints { - /// The revision of what they are built from, which the state's [`Revised`] parts move. - revision: Arc, - /// By batch. - kept: Mutex>>, -} - -impl Footprints { - /// Batch `index`'s kept footprint, where what it was built from holds: the revision it was - /// built at, and each of its segments' answers ([`SegmentProbe`]). - fn kept(&self, index: usize) -> Option>> { - let revision = self.revision.load(Ordering::Acquire); - let kept = lock(&self.kept); - let built = kept.get(index)?.as_ref()?; - let holds = built.revision == revision && built.probes.iter().all(SegmentProbe::holds); - holds.then(|| Arc::clone(&built.footprint)) - } - - /// Keep `built` as batch `index`'s, where nothing it was built from moved since. - fn keep(&self, index: usize, built: BuiltFootprint) { - let mut kept = lock(&self.kept); - if self.revision.load(Ordering::Acquire) != built.revision { - return; - } - if kept.len() <= index { - kept.resize_with(index + 1, || None); - } - kept[index] = Some(built); - } - - /// Let go of every kept footprint, with the work of the segments its probes hold - /// ([`SegmentProbe`]): as the command buffer completes, after which the scheduler holds no - /// batch of it to ask for one. Each leaves under the lock and drops without it. - fn let_go(&self) { - loop { - let Some(built) = lock(&self.kept).pop() else { - break; - }; - drop(built); - } - } -} - -/// A batch's footprint as [`CommandBufferShared::footprint`] built it, with what it was built -/// from: the revision of its command buffer's recordings and batches ([`Revised`]), and what its -/// segments' shares turn on besides ([`SegmentProbe`]). Two equal ones build equal footprints: -/// every summary taken lies in the recordings, and which one a segment takes turns on its own -/// fields, which the revision covers, and on its work's and step inputs' answers, which the -/// probes ask again. -struct BuiltFootprint { - revision: u64, - probes: Vec, - footprint: Arc>, -} - -/// What the summary a segment's share of its batch's footprint takes turns on that may move -/// without its command buffer's state: its work's answers (whether the GPU may write what it -/// reads, the CPU rewrote its records, a route encoded since outgrew its recording, its step -/// holds the batch) and whether its recording is due again (`Segment::needs_step`, `rerecords`, -/// `steps_after_the_gpu`), as they were where the footprint was built. A route met since, a -/// host step or a rewrite moves one; a kept footprint stands only where none moved. -struct SegmentProbe { - /// Its answers now, asked of the segment's work and step inputs it holds. Held behind a - /// trait object, so the command buffer's auto-trait proofs reach no segment's work through - /// it: through the work's types they ran past consumers' recursion limit (`Send` of an - /// encoder held in a `Mutex`, `tests/consumer_auto_traits.rs`). - ask: Box [bool; 5] + Send + Sync>, - answers: [bool; 5], -} - -impl SegmentProbe { - fn of(segment: &Segment) -> SegmentProbe { - let rerecord = (segment.inputs.as_ref()) - .filter(|inputs| matches!(inputs, StepInputs::Rerecord(_))) - .cloned(); - let work = segment.work.clone(); - let ask = move || probe_answers(&work, rerecord.as_ref()); - SegmentProbe { - answers: ask(), - ask: Box::new(ask), - } - } - - /// Whether its answers are as they were. - fn holds(&self) -> bool { - (self.ask)() == self.answers - } -} - -/// [`SegmentProbe`]'s answers of `work` and `rerecord`. -fn probe_answers(work: &Deferred, rerecord: Option<&StepInputs>) -> [bool; 5] { - [ - work.gpu_written(), - work.rewritten(), - work.outgrown(), - work.holds(), - rerecord.is_some_and(StepInputs::rerecords), - ] -} - -/// A command buffer's mutable state. -pub(super) struct State { - status: CommandBufferStatus, - error: Option, - /// An encoder is open. - pub(super) encoder_open: bool, - /// Its label (`MTLCommandBuffer.label`), where the program set one (`labels.rs`). - label: Option, - /// The label of its open encoder, where the program set one: the encoder's record takes it - /// as it ends (`labels.rs`). - open_label: Option, - /// An encoder was dropped without `end_encoding`. - pub(super) abandoned: bool, - /// A render encoder's end, which its call left to the device's lowering thread - /// (`render/deferral.rs`): the encoder stays open until it is lowered, and what follows the - /// end in the command buffer lowers it first ([`CommandBuffer::settle_end`]). - ending: Option, - /// The device's lowering thread lowered the end it holds (`ending`). - end_lowered: bool, - /// The kept draw its last render encoder carried for its next render encoder, with that - /// encoder's bind state (`render/carried.rs`): let go by every call that settles the end - /// ([`CommandBuffer::settle_end`]) but a render encoder's opening, which takes it. - carried: Option>, - /// The end of its last render encoder where that drew and kept no draw, for its next render - /// encoder's opening to count what a kept draw of it would have come to (`render/carried.rs`, - /// `WorkCounts::encoders_none_kept_next_*`): counted by every call that settles the end - /// ([`CommandBuffer::settle_end`]) but a render encoder's opening, which takes it. - none_kept: Option>, - /// The commits' own work fails this many more times (a device test's injection of an out of - /// memory, `tests::deferred_calls`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - failures_injected: u32, - /// The error the making of the next draw's pipeline its recording waits for answers, in place - /// of the making's own (a device test's injection, `tests::deferred_calls`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - making_failure_injected: Option, - /// The error its next host step's recording answers, in place of the recording it made (a - /// device test's injection, `tests::tiled_texture_step`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - step_failure_injected: Option, - /// `commit` returned with its own work left to run once a render encoder's end is lowered - /// (`render/queued_commits.rs`), which has not run: to the program, the command buffer is - /// committed. How the work, once run, hands its batches to the scheduler: as the call that - /// left it would have (`commit_and_submit`'s pass, [`Hand::Pass`], made by the thread that - /// runs it). - queued_commit: Option, - /// A render pass of it has a draw call over a `Mutable` rasterization-rate map: its commit - /// lets a later pass of no draw call over such a map run (`rate_mapped_pass.rs`). - pub(super) called_over_mutable_map: bool, - /// `commit` is recording the encoders' segments (`encoder.rs`), outside this lock: nothing - /// else may encode or commit meanwhile. - committing: bool, - /// The pool every `VkCommandBuffer` of this command buffer comes from, with those made from - /// it; `None` until the first, and once given back to the device's spares. - pool: Option, - /// The spare pools it took past `pool`, each once its pools handed out every - /// `VkCommandBuffer` of a level they held, which hand out theirs before `pool` makes one - /// (`spares.rs`); given back with `pool`. - pools_past_first: Vec, - /// The pool of a predicated loop's check while it records again the work its laying left - /// apart (`rerun.rs`): every `VkCommandBuffer` the command buffer hands out meanwhile comes - /// from it, and goes back to it for the next run again. - rerun_pool: Option>>, - /// The context of a chunk of an indirect command buffer's commands the commit records to keep - /// (`kept_commands.rs`), while it does: every `VkCommandBuffer` the command buffer hands out - /// meanwhile comes from its pool, begun for simultaneous use where it is a render pass's - /// secondary or a segment's primary, and every set and upload from its arenas; and how many - /// its pool had handed out when it was lent. - kept: Option<(Arc, usize)>, - /// How many times a command reached what the command buffer alone holds for its commands: its - /// execution status words, index pool and mesh records pool, and the uniform texel buffer - /// views its binds made (`State::retain_own`). A recording that reached them is not kept - /// (`kept_commands.rs`). - own_reached: u64, - /// The ended encoders' recordings, in encoding order. - recorded: Revised>, - /// The last ended encoder's last `VkCommandBuffer`, still recording: its batch's end goes - /// into it as the batch ends ([`CommandBufferShared::close_tail`]), or it ends as it is where - /// a later encoder joins its batch. - pub(super) tail: Option, - /// The group of encoders whose last one's `VkCommandBuffer` is `tail`, which - /// the next such encoder may join, recording on into it (`encoder_fold.rs`); held by that - /// encoder while it is open. - pub(super) fold: Option>, - /// Why the tail holds no group the next encoder may join, where an encoder left none: the - /// reason its join is refused, counted as it opens (`State::join_fold`); `None` before the - /// first encoder, and while a group goes on. - pub(super) unfolded: Option, - /// The first ended encoder a command-predication record left the work of out - /// ([`leave_out_ended`](Self::leave_out_ended)): the commit splits a group it lies past the - /// first of (`fold.rs`'s `split_failure`). - pub(super) left_out_from: Option, - /// The logs of the closed groups' encoders kept for nothing else, held for the commit, whose - /// failure may split a group (`fold.rs`'s `split_failure`), and given back to the device's - /// spares in the release. - pub(super) held_logs: Vec, - /// The storage the next group of its encoders recorded into one `VkCommandBuffer` stashes the - /// logs its members do not keep in (`encoder_fold::Fold`'s `stashed`), empty; `None` while a - /// group holds it. - stash_room: Option>, - /// The order the next group of its encoders recorded into one `VkCommandBuffer` joins its - /// encoders' uses to (`encoder_fold::Fold`'s `order`), empty, the room of the groups before - /// kept (`FoldOrder::clear`); `None` while a group holds it. - order_room: Option>, - /// Cleared logs of compute encoders (`replay.rs`), each with its room in bytes, that the - /// release of a command buffer that held this state kept for the compute encoders of the one - /// that takes it next, at most [`STATE_LOGS`](spare_states::STATE_LOGS): such an encoder - /// takes its log here, under the lock its open takes, and from the device's spares only where - /// none is left. - compute_logs: Vec<(CallLog, usize)>, - /// The room its lists of records (`ended`, `recorded`, `held_logs`, `stash_room`, its command - /// predication's lists and its groups' order) held as the command buffer took the state - /// (`spare_states.rs`): its release counts those that grew past it - /// (`WorkCounts::record_lists_grown`). - room: Room, - /// What its last ended compute encoder parked for its next one, until the commit gives it back - /// to the device (`compute/live.rs`'s `Parked`). - parked_compute: Option, - /// The encoders that run of each group the commit's failure split, which its call encodes - /// again before the first submission (`reencode.rs`). - pub(super) split_units: Vec>, - /// The batches whose end went into their last `VkCommandBuffer` (`submit.rs`): each batch's - /// index, that command buffer, and whether it wrote the command buffer's end timestamp. - folds: Vec, - /// The first encoder's first `VkCommandBuffer`, where its first commands write the start into - /// the slot's third query (`gpu_time.rs`): the first batch writes the start there alone where - /// it plans nothing before that encoder and the command buffer reaches the queue as recorded - /// (`submit.rs`). - pub(super) prefix: Option, - /// The encoders split at the event and binary semaphore waits and signals. - batches: Revised, vk::Semaphore>>, - /// Its scheduled signals, in the order encoded - /// ([`CommandBuffer::encode_signal_event_scheduled`]). - scheduled_signals: Vec<(Arc, u64)>, - scheduled: VecDeque, - /// Its submission handlers ([`CommandBuffer::add_submission_handler`]): run on the thread - /// that takes its last batch for its queue (submits it, or holds it in a group), before its - /// transition to `Scheduled`. - submission: VecDeque, - /// The thread that took its last batch has its submission handlers to run, or the - /// switch of storage forms riding on it to end (`texture/storage_form.rs`): its transition to - /// `Scheduled` waits until it did. - submitting: bool, - /// Its scheduled handlers ran: `wait_until_scheduled` returns, as Metal's does only once - /// they ran. - scheduled_ran: bool, - /// Its transition to `Scheduled` was decided (`CommandBufferShared::schedule`) and its step has - /// not run: the step runs once, in its queue's context, by that transition, or by its - /// transition to `Completed` or `Error` where that one runs first - /// (`CommandBufferShared::run_scheduled`). - scheduled_owed: bool, - /// That transition goes to its queue's context only once its submission handlers ran: the - /// thread that runs them runs or posts it (`CommandBufferShared::run_submission_handlers`). - scheduled_deferred: bool, - /// The gate its transition to `Completed` or `Error` waits behind in its queue's context, its - /// place kept, where that transition came while its submission handlers had not run - /// (`CommandBufferShared::gate_for_handlers`): the thread that runs them opens it - /// (`CommandBufferShared::run_submission_handlers`), and no thread waits meanwhile. - finish_gate: Option, - /// What its encoders did that Metal's identifier allocations follow as it is scheduled - /// (`unique_identifier.rs`). - scheduled_work: ScheduledWork, - /// The threads sleeping on its `changed` condition variable: a change wakes it only where - /// one does ([`CommandBufferShared::wake_parked`]). - parked: usize, - /// Why a batch could not be submitted: the command buffer finishes with it, and its - /// scheduled handlers never run. Or the failure `commit_failed` chose, with which it - /// finishes once its batches completed, its scheduled handlers run. Or a revoked queue's - /// `AccessRevoked`, set at its commit, which a refused batch leaves. - failure: Option, - completed: VecDeque, - /// Its completion-seen handlers ([`CommandBuffer::add_completion_seen_handler`]): run as its - /// transition to `Completed` or `Error` runs, its status final, before its completed handlers. - seen: VecDeque, - /// The handlers of its executions' records as the runtime reads them - /// (`executed_commands.rs`). - pub(crate) executed_handlers: Vec, - /// What the ended encoders' commands use, held until the command buffer completed and its - /// completed handlers ran. A drop may run the caller's code (a no-copy buffer's deallocator), - /// which may use this command buffer, so each is released outside this state's lock. - pub(super) retained: Vec>, - /// The shared objects its last ended encoder held lately, which `retained` holds until it - /// completes: the next encoder it opens holds none of them again (`retained.rs`). - pub(super) held_lately: Lately, - /// What the ended encoders made resident for writing, set and executed that decides, at the - /// commit, whether the GPU may write an indirect command buffer's records (`write_routes.rs`). - pub(super) routes: Routes, - /// What the ended encoders' dispatches and draws executed (`execution.rs`), kept after the - /// command buffer completed. - pub(super) executions: Vec, - /// The commands' own data, released when the command buffer completes. - pub(super) uploads: Uploads, - /// The device's heap sets its commands bound (`heap_sets.rs`), released with the uploads. - pub(super) heaps: HeapUse, - /// Its commands' function-table snapshots, written again as it commits. - table_snapshots: Vec, - /// A command left a live sampler state out of its argument samplers - /// (`State::unlisted_argument_sampler`): counted once - /// (`WorkCounts::unlisted_argument_sampler_buffers`). - unlisted_argument_samplers: bool, - /// The first ended encoder Metal fails the command buffer from, with the error (a render - /// pass without attachments past 16384 a side, `CommandBufferError::RenderTargetSize`, or - /// at a default sample count Metal fails it at, `DefaultRasterSampleCount`): as it commits, - /// that encoder and every one after it run nothing, and it completes with that error. - fails_from: Option<(usize, CommandBufferError)>, - /// The hold of the encoder Metal's GPU hangs at, where one does (`hang.rs`). - hang: Option, - /// Its transition to `Scheduled` around a GPU hang of its queue, from its commit on - /// (`hang.rs`): its own hang's, which the hang's thread makes, or one committed during a - /// hang, which the hang's thread makes early unless its last batch did. Or made early by the - /// scheduler's thread, behind a host step of its queue's head - /// ([`schedule_early`](CommandBufferShared::schedule_early)). - hang_scheduling: Option, - /// It was committed with an event wait while a hang of its queue was in flight: the verdict - /// its first batch's submission applies (`hang.rs`, `checks.rs`). - behind_hang: Option, - /// It was committed on the queue of the hang a loss of its device named, before the - /// recovery (`Line::holds_hang_queue`, `device/line.rs`): it runs nothing and completes with - /// no error, as Metal's command buffers committed on a hang's queue in flight do. - held_by_lost_hang: bool, - /// It is the hang a loss of its device named (`completion.rs`, `name_hang`): it fails as the - /// hang (`GpuHang`) whichever of the loss's failures finishes it, its last batch taken with - /// the loss's failure, watched after it, or held by the scheduler and failed with the loss - /// (`scheduler::fail_lost`). - hang_of_loss: bool, - /// The ended encoders Metal's GPU faults, each with the error it fails the command buffer - /// with (an execution of commands that inherit a pipeline state made without - /// `supportIndirectCommandBuffers`, `CommandBufferError::PageFault`; an indexed or indirect - /// draw of primitive type 9): as it commits, they run nothing, and it completes with the first - /// one's error. - faulted: BTreeMap, - /// The shadowed textures its ended encoders' passes took as attachments - /// (`render/shadows.rs`), each once. - shadow_attachments: Vec, - /// The shadowed textures its ended encoders copied in first (`shadow.rs`), each once. - shadows_copied_in: Vec, - /// The shadowed textures its ended encoders left holding their truth, which its later - /// encoders take instead of copying it in again (`shadow::ShadowCarry`): handed to each - /// encoder as it opens and taken back as it ends, so it is `None` while an encoder is open. - /// An event or semaphore wait drops it, after which Metal shows the work encoded next - /// another writer's bytes; Metal refuses such a wait while an encoder is open, so one never - /// finds it lent out. - shadow_carry: Option, - /// How many batches it had once its last ended encoder joined one: the encoder opening next - /// carries nothing where it starts another ([`State::shadows_to_carry`]). - carry_batches: usize, - /// Its open runs of passes over one attachment merged once: a linear attachment rendered - /// apart, or a shadowed texture merged back (`pass_runs.rs`). - pass_runs: PassRuns, - /// The keeps the encoder being encoded again records after itself, where it leaves a run of - /// passes another pass went on in (`pass_runs.rs`, `command_buffer/reencode.rs`). - pub(super) replaying_keeps: Vec, - /// What the first encoding of the encoder being encoded again decided of its copies taken at - /// use, which its encoding again takes as they did (`shadow::Takes`, - /// `command_buffer/reencode.rs`). - pub(super) replaying_takes: Takes, - /// What the recording a host step records a segment again in place of decided of its copies - /// taken at use, while the step records it: each core the step records into keeps those - /// takes where it meets them (`shadow::ShadowSync::over`, `EncoderCore::segment`). None - /// otherwise. The step holds the turn (`reencoding`), so no other recording into the command - /// buffer's pool meets it. - pub(super) step_takes: Takes, - /// The placed segments' `VkCommandBuffer`s that end a piece of their batch's submission - /// (`RecordedSegment::piece_ends`, `rate_mapped_pass.rs`'s **Pieces**), until the batch's - /// submission submits each apart from what follows it (`submit.rs`). - pub(super) piece_ends: Vec, - /// The pools of its commands' set 0 (`descriptor_arena.rs`), given back or released with - /// the uploads. - pub(super) descriptors: DescriptorArena, - /// The execution status words the commands share, once a command reaches them. - status_words: Option, - /// A direct mesh draw's object grid lay past what runs (`render/mesh_arguments.rs`): the - /// command buffer fails as for `ExecutionStatus`'s `MESH_GRID_PAST_LIMITS`. - mesh_grid_past: bool, - /// The index pool of the commands' index bounds and rewrite passes (`index_bounds.rs`, - /// `index_rewrite.rs`), once a draw needs it: its counter in the arena, starting at 0, and - /// its lease of its queue's block, which its indices lie in (`gpu_pools.rs`). - index_pool: Option<(Upload, PoolLease)>, - /// The records pool of the commands' scanned emulated mesh draws (`render/mesh.rs`), once a - /// draw needs it: its lease of its queue's block (`gpu_pools.rs`); the scans' cursor is a - /// status word. - mesh_pool: Option, - /// The emulated mesh draws numbered so far, each by its order. - mesh_draws: u32, - /// The resident-set misses the segments' recordings found on the host, which the report adds to - /// the words' count. - resident_misses: u32, - /// Why some of the segments' commands ran nothing, which the report states. - faults: ReplayFaults, - /// The dispatches of the segments placed so far, each among the executions. - placed: usize, - /// Why a host step failed: the batch it recorded for is not submitted, and the command buffer - /// finishes with it. - step_failure: Option, - /// The batches that copy copied host buffers in again as they are submitted, after an event - /// wait their commit's copy in came before (`copies_again.rs`). - copies_again: Option, - /// The refusal of a host step that failed so (`CommandBufferError::Refused`). - refusal: Option, - /// The first dispatch's pipeline whose making failed, which a host step met - /// (`CommandBufferError::PipelineCreation`). - failed_pipeline: Option, - /// The first draw's pipeline whose making failed, which its recording dropped - /// (`render/pending.rs`). - dropped_draw: Option, - /// Metal's description of the failure the driver relayed, where the command buffer failed - /// with it (`CommandBuffer::error_description`). - relayed_description: Option, - /// The decoded status words, once the command buffer completed. - report: Option, - /// Its GPU and kernel times (`gpu_time.rs`). - times: Times, - /// The heaps its ended encoders' commands used, which its commit marks used - /// (`Heap::set_purgeable_state`). - used_heaps: Vec, - /// Its ended encoders' holds on the buffers over host pages their commands used - /// (`rebind.rs`): let go at its commit, or, where a host step records commands after it, as - /// it completes. - pub(super) holds: Vec, - /// Those holds from its commit until the submission of its last event group (or its - /// completion), where an encoder no rebind encodes again named a buffer over host pages - /// (`State::unlogged_names_a_pin`): a rebind meanwhile is refused (`EncodedUses`), never - /// failing that submission (`Holds::hold_to_submission`). - pub(super) held_to_submission: Vec, - /// What its ended encoders made resident, every encoder's joined (`residency.rs`): the - /// residency the work its commit and host steps record resolves and binds against. Released - /// with what it retained, as it completes. Its heaps are joined as each encoder ends, and the - /// resources of the encoders from `joined` on where its work first reads it - /// ([`joined_residency`](Self::joined_residency)). - residency: Option, - /// The ended encoders whose resources `residency` holds joined: those before this place. - joined: usize, - /// What its next compute encoder (`[0]`) and render encoder (`[1]`) start with - /// ([`inherited`](Self::inherited)), with the number of ended encoders it took in: kept from - /// one open to the next, so an open looks at the encoders ended since the last alone, not - /// every earlier one. Let go of where `residency` or an ended encoder's residency may change - /// ([`joined_residency`](Self::joined_residency), `splice_replay`). - inherits: [Option<(Residency, usize)>; 2], - /// What its work may write through its residency (`Residency::written_uses`), set at its - /// commit: every resource made resident for writing, by any of its encoders. A function of - /// any of its encoders may write such a resource unnamed (residency is the command - /// buffer's), so the device's tracker takes each of its batches as writing them all: joined - /// to the summary of the batch's first part, in the plan its submission makes (`submit.rs`) - /// and in its footprint ([`CommandBufferShared::footprint`]). A host step's gate then - /// covers such a writer of what it reads (`scheduler/mod.rs`'s `gate_heads`): an earlier - /// batch of its own command buffer, or one of an earlier command buffer of any queue. `None` - /// where no encoder made a resource resident for writing. - resident_writes: Option>, - /// Its ended encoders, in the order they ended, each with what its commands use - /// (`used_resources.rs`): the keys its commands' uses and bindings named, its placed - /// segments' among them, and what it made resident. Their uses are let go as it completes. - ended: Vec, - /// Its root tables, until its first submission points them at its resident set as the - /// live buffers stand then (`first_submission.rs`); the commit points them first. - root_tables: Vec, - /// The ranges of its root tables' own resident sets, each once. - root_ranges: HashSet, - /// The resident set its root tables search, once made; released as it completes. - resident: Option, - /// The live buffers' tables its host steps resolved against (`CommandBuffer::residency`), - /// each once ([`State::keep_stepped_table`]); released as it completes. - stepped_tables: Vec>, - /// What its commit listed among the live buffers (`LiveBuffers::reach`), and the list's - /// generation then: listed again at its first submission where the list changed since. - listing: Option, - /// Its first batch was submitted: from then on it holds what its commands took and the - /// live buffers' table its resident set was made of until it completes. - submitted: bool, - /// The batches before this one lie in event groups judged as they were submitted - /// (`State::first_submission`, `State::later_group`): a rebind encodes again only encoders - /// of the groups from here (`reencode.rs`). - judged_to: usize, - /// What `set_protection_options` left (`protection.rs`). - protection: protection::Protection, - /// Metal's submissions (`checks::metal_submissions`, by their ended encoders) its first - /// submission found to name a buffer rebound since, or to hold a detached one, each with - /// its failure: each fails as its own batch is submitted, after its check - /// (`first_submission.rs`). - failing: Vec<(Range, CommandBufferError)>, - /// Where its first submission, or a later batch's, found the first use rebound, for the - /// notice (`rebound_use.rs`). - rebound_use: Option, - /// The command buffers of other queues whose last batches' GPU signals met its batches' event - /// waits while their transitions to `Completed` had not run up to their completed handlers - /// (`follow.rs`): its own runs after theirs where theirs lead their contexts - /// ([`CommandBufferShared::finish_here`]). - waited: Vec>, - /// What its transition to `Completed` lets go as it reaches its completed handlers, its status - /// final, where its last batch keeps GPU signals; taken then (`follow.rs`). - release: Option, - /// The resident root tables of its work on the GPU alone recorded before its first - /// submission, which that submission points at the set as it lies then - /// (`first_submission.rs`). - replay_tables: Vec, - /// A command of it may write memory no use it noted names: a root table (a function that - /// reaches buffers through addresses), a root table of work on the GPU alone, or work its - /// host steps resolve from records (`Deferred::reaches_unnamed`). - pub(super) reaches_unnamed: bool, - /// The stamp of its commit (`managed.rs`'s `Modified::take_at_commit`): its batches take no - /// `Managed` buffer's upload of bytes a later commit took (`texture/first_move.rs`, - /// `FirstFill::upload`). 0 until it is committed. - pub(super) commit: u64, - /// A command of it may write memory no use it noted names: one that reaches it as above - /// whose functions may write memory (stores or atomic updates, - /// `StageInterface::writes_memory`; the root table of a draw whose vertex and fragment - /// functions store nothing writes nothing through it), work on the GPU alone, or work its host - /// steps resolve from records. The merge back of copied host buffers then takes every copy as - /// written by it (`copied.rs`); a command buffer whose unnamed reach only reads leaves the - /// copies its uses did not write uncompared. - pub(super) writes_unnamed: bool, - /// The ended encoders whose submissions failed so, or failed a submission check - /// (`State::fail_submission`): no part of one goes to a queue with work (`submit.rs` holds it - /// to that), and none takes an encoding again (`reencode.rs`). - unrunnable: BTreeSet, - /// What its batches' commands took of buffers over host pages, held from the submission of - /// their event group's first batch (`rebind::SubmittedHolds`, `State::event_group`), each with - /// the batch whose submission takes it ([`State::holds_until`]): let go as that batch's work - /// completed, and, for its last batch's, as its completion is processed, before its completed - /// handlers run ([`State::keep_holds`], `CommandBufferShared::complete`). A group of its never - /// submitted keeps its holds until then too, since nothing of it will run. - submitted_holds: Vec<(usize, SubmittedHolds)>, - /// The encoders its commit's failure failed (`commit_failed`'s, Metal's own from a render - /// pass, or a faulted encoder's: [`State::fail`]): a submission none of whose encoders - /// runs so is spared its rebound verdict (`first_submission.rs`). - failed_at_commit: Option, - /// The program's submission check (`checks.rs`), released as it completes. - check: Option, - /// Metal's submissions of a committed command buffer with a check, and how far they were - /// checked. - checks: Option, - /// The fetched render targets' switch to their storage form riding on its commit - /// (`texture/storage_form.rs`), until the scheduler settled it and a program thread finished - /// it. - storage_form: Option>, - /// Its units of command predication (`predication.rs`). - pub(super) predication: Predication, - /// The predication of an encoder a rebind encodes again now, which encodes again exactly - /// (`Predication::replaying`, `reencode.rs`): its records and dispatches step and gate there. - pub(super) replaying_predication: Option, - /// An encoder of it used command predication: its commit lets go of the logs of its compute - /// encoders their unit of predication reaches past, or that laid a loop or left work out - /// (`State::keep_replays`). - pub(super) predicated: bool, - /// The device's trail mark as it completed (`trails.rs`): its waiters return once no trail - /// numbered below is open. 0 before, which waits for none. - trail_mark: u64, - /// Its completion as a sync file, where the program asked for one (`sync_file.rs`). - #[cfg(unix)] - sync_file: Option, -} - -/// A batch whose end went into its last `VkCommandBuffer` ([`State::folds`]). -struct Fold { - /// The batch's index. - batch: usize, - /// The command buffer. - raw: vk::CommandBuffer, - /// It wrote the command buffer's end timestamp. - stamped: bool, -} - -/// The resident set a command buffer's root tables search (`live_buffers.rs`): the device's live -/// buffers at its commit, and what its encoders bound and made resident beyond them (`merged`, -/// uploaded to its arena): `count` entries at `address` (`None` for none). -struct Resident { - live: Live, - merged: Option, - address: Option, - count: u64, -} - -impl State { - /// Whether it was committed, its commit's own work waiting or not - /// (`render/queued_commits.rs`): a handler added now would not run - /// (`Problem::HandlerAfterCommit`). - pub(crate) fn enqueued(&self) -> bool { - self.status != CommandBufferStatus::NotEnqueued || self.queued_commit.is_some() - } - - /// How many of the command buffer's encoders ended so far: the place of the next. - pub(super) fn encoders_ended(&self) -> usize { - self.ended.len() - } - - /// A command buffer's state as it starts, its lists of records of no room (`spare_states.rs`), - /// its parts that footprints are built from moving `revision` (`Footprints::revision`). - fn new(revision: &Arc) -> State { - State { - status: CommandBufferStatus::NotEnqueued, - error: None, - encoder_open: false, - label: None, - open_label: None, - abandoned: false, - ending: None, - end_lowered: false, - carried: None, - none_kept: None, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - failures_injected: 0, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - making_failure_injected: None, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - step_failure_injected: None, - queued_commit: None, - called_over_mutable_map: false, - committing: false, - pool: None, - pools_past_first: Vec::new(), - rerun_pool: None, - kept: None, - own_reached: 0, - recorded: Revised::new(Vec::new(), revision), - tail: None, - fold: None, - unfolded: None, - held_logs: Vec::new(), - stash_room: Some(Vec::new()), - order_room: Some(FoldOrder::none()), - compute_logs: Vec::new(), - room: Room::default(), - parked_compute: None, - left_out_from: None, - split_units: Vec::new(), - folds: Vec::new(), - prefix: None, - batches: Revised::new(Batches::default(), revision), - scheduled_signals: Vec::new(), - scheduled: VecDeque::new(), - submission: VecDeque::new(), - submitting: false, - scheduled_ran: false, - scheduled_owed: false, - scheduled_deferred: false, - finish_gate: None, - scheduled_work: ScheduledWork::default(), - parked: 0, - failure: None, - completed: VecDeque::new(), - seen: VecDeque::new(), - executed_handlers: Vec::new(), - retained: Vec::new(), - held_lately: Lately::default(), - routes: Routes::default(), - executions: Vec::new(), - uploads: Uploads::new(), - heaps: HeapUse::default(), - table_snapshots: Vec::new(), - unlisted_argument_samplers: false, - fails_from: None, - faulted: BTreeMap::new(), - hang: None, - hang_scheduling: None, - behind_hang: None, - held_by_lost_hang: false, - hang_of_loss: false, - shadow_attachments: Vec::new(), - shadows_copied_in: Vec::new(), - shadow_carry: Some(ShadowCarry::default()), - carry_batches: 1, - pass_runs: PassRuns::default(), - replaying_keeps: Vec::new(), - replaying_takes: Takes::default(), - step_takes: Takes::default(), - piece_ends: Vec::new(), - descriptors: DescriptorArena::default(), - status_words: None, - mesh_grid_past: false, - index_pool: None, - mesh_pool: None, - mesh_draws: 0, - resident_misses: 0, - faults: ReplayFaults::default(), - placed: 0, - step_failure: None, - copies_again: None, - refusal: None, - failed_pipeline: None, - dropped_draw: None, - relayed_description: None, - report: None, - times: Times::default(), - used_heaps: Vec::new(), - holds: Vec::new(), - held_to_submission: Vec::new(), - residency: None, - joined: 0, - inherits: [None, None], - resident_writes: None, - ended: Vec::new(), - root_tables: Vec::new(), - root_ranges: HashSet::new(), - resident: None, - stepped_tables: Vec::new(), - listing: None, - submitted: false, - judged_to: 0, - protection: protection::Protection::default(), - failing: Vec::new(), - rebound_use: None, - waited: Vec::new(), - release: None, - replay_tables: Vec::new(), - reaches_unnamed: false, - commit: 0, - writes_unnamed: false, - unrunnable: BTreeSet::new(), - submitted_holds: Vec::new(), - failed_at_commit: None, - check: None, - checks: None, - storage_form: None, - predication: Predication::default(), - replaying_predication: None, - predicated: false, - trail_mark: 0, - #[cfg(unix)] - sync_file: None, - } - } - - /// The room its lists of records hold, each list's in entries, and with its kept compute - /// logs' in bytes (`spare_states.rs`). - fn lists_room(&self) -> Room { - let order = (self.order_room.as_ref()).map_or([0; 3], FoldOrder::room); - let logs = self.compute_logs.iter().map(|(_, room)| room).sum(); - Room::new( - [ - self.ended.capacity(), - self.recorded.capacity(), - self.stash_room.as_ref().map_or(0, Vec::capacity), - self.held_logs.capacity(), - ], - self.predication.room(), - order, - logs, - ) - } - - /// A compute encoder's log, opening now: a cleared one this state kept - /// ([`compute_logs`](Self::compute_logs)), where it keeps one. - pub(super) fn kept_compute_log(&mut self) -> Option> { - self.compute_logs.pop().map(|(log, _)| log) - } - - /// Keep `logs`, cleared compute logs with their room in bytes, for the compute encoders of - /// the command buffer that takes this state next, as many as it has room for - /// ([`STATE_LOGS`](spare_states::STATE_LOGS)): those it does not keep come back. - pub(super) fn keep_compute_logs( - &mut self, - mut logs: Vec<(CallLog, usize)>, - ) -> Vec<(CallLog, usize)> { - let room = spare_states::STATE_LOGS.saturating_sub(self.compute_logs.len()); - let from = logs.len().saturating_sub(room); - self.compute_logs.extend(logs.drain(from..)); - logs - } - - /// The state reset in place, by its release, for a command buffer the device makes next - /// (`spare_states.rs`): every part as [`State::new`] makes it, what it held going here, but - /// its lists of records, emptied with their room kept (their entries going first, as they - /// went before the rest), its command predication's lists and its groups' order, emptied in - /// place with their room kept, the compute logs its release kept, and the revision its parts - /// move. Its room is the room the next command buffer starts on. - fn reset(&mut self) { - let State { - status, - error, - encoder_open, - label, - open_label, - abandoned, - ending, - end_lowered, - carried, - none_kept, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - failures_injected, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - making_failure_injected, - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - step_failure_injected, - queued_commit, - called_over_mutable_map, - committing, - pool, - pools_past_first, - rerun_pool, - kept, - own_reached, - recorded: _, - tail, - fold, - unfolded, - held_logs: _, - stash_room: _, - order_room: _, - compute_logs: _, - room: _, - parked_compute, - left_out_from, - split_units, - folds, - prefix, - batches, - scheduled_signals, - scheduled, - submission, - submitting, - scheduled_ran, - scheduled_owed, - scheduled_deferred, - finish_gate, - scheduled_work, - parked, - failure, - completed, - seen, - executed_handlers, - retained, - held_lately, - routes, - executions, - uploads, - heaps, - table_snapshots, - unlisted_argument_samplers, - fails_from, - faulted, - hang, - hang_scheduling, - behind_hang, - held_by_lost_hang, - hang_of_loss, - shadow_attachments, - shadows_copied_in, - shadow_carry, - carry_batches, - pass_runs, - replaying_keeps, - replaying_takes, - step_takes, - piece_ends, - descriptors, - status_words, - mesh_grid_past, - index_pool, - mesh_pool, - mesh_draws, - resident_misses, - faults, - placed, - step_failure, - copies_again, - refusal, - failed_pipeline, - dropped_draw, - relayed_description, - report, - times, - used_heaps, - holds, - held_to_submission, - residency, - joined, - inherits, - resident_writes, - ended: _, - root_tables, - root_ranges, - resident, - stepped_tables, - listing, - submitted, - judged_to, - protection, - failing, - rebound_use, - waited, - release, - replay_tables, - reaches_unnamed, - commit, - writes_unnamed, - unrunnable, - submitted_holds, - failed_at_commit, - check, - checks, - storage_form, - predication: _, - replaying_predication, - predicated, - trail_mark, - #[cfg(unix)] - sync_file, - } = State::new(&self.batches.revision); - self.ended.clear(); - self.recorded.clear(); - self.held_logs.clear(); - self.stash_room.get_or_insert_with(Vec::new).clear(); - (self.order_room.get_or_insert_with(FoldOrder::none)).clear(); - self.status = status; - self.error = error; - self.encoder_open = encoder_open; - self.label = label; - self.open_label = open_label; - self.abandoned = abandoned; - self.ending = ending; - self.end_lowered = end_lowered; - self.carried = carried; - self.none_kept = none_kept; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - self.failures_injected = failures_injected; - self.making_failure_injected = making_failure_injected; - self.step_failure_injected = step_failure_injected; - } - self.queued_commit = queued_commit; - self.called_over_mutable_map = called_over_mutable_map; - self.committing = committing; - self.pool = pool; - self.pools_past_first = pools_past_first; - self.rerun_pool = rerun_pool; - self.kept = kept; - self.own_reached = own_reached; - self.tail = tail; - self.fold = fold; - self.unfolded = unfolded; - self.parked_compute = parked_compute; - self.left_out_from = left_out_from; - self.split_units = split_units; - self.folds = folds; - self.prefix = prefix; - self.batches = batches; - self.scheduled_signals = scheduled_signals; - self.scheduled = scheduled; - self.submission = submission; - self.submitting = submitting; - self.scheduled_ran = scheduled_ran; - self.scheduled_owed = scheduled_owed; - self.scheduled_deferred = scheduled_deferred; - self.finish_gate = finish_gate; - self.scheduled_work = scheduled_work; - self.parked = parked; - self.failure = failure; - self.completed = completed; - self.seen = seen; - self.executed_handlers = executed_handlers; - self.retained = retained; - self.held_lately = held_lately; - self.routes = routes; - self.executions = executions; - self.uploads = uploads; - self.heaps = heaps; - self.table_snapshots = table_snapshots; - self.unlisted_argument_samplers = unlisted_argument_samplers; - self.fails_from = fails_from; - self.faulted = faulted; - self.hang = hang; - self.hang_scheduling = hang_scheduling; - self.behind_hang = behind_hang; - self.held_by_lost_hang = held_by_lost_hang; - self.hang_of_loss = hang_of_loss; - self.shadow_attachments = shadow_attachments; - self.shadows_copied_in = shadows_copied_in; - self.shadow_carry = shadow_carry; - self.carry_batches = carry_batches; - self.pass_runs = pass_runs; - self.replaying_keeps = replaying_keeps; - self.replaying_takes = replaying_takes; - self.step_takes = step_takes; - self.piece_ends = piece_ends; - self.descriptors = descriptors; - self.status_words = status_words; - self.mesh_grid_past = mesh_grid_past; - self.index_pool = index_pool; - self.mesh_pool = mesh_pool; - self.mesh_draws = mesh_draws; - self.resident_misses = resident_misses; - self.faults = faults; - self.placed = placed; - self.step_failure = step_failure; - self.copies_again = copies_again; - self.refusal = refusal; - self.failed_pipeline = failed_pipeline; - self.dropped_draw = dropped_draw; - self.relayed_description = relayed_description; - self.report = report; - self.times = times; - self.used_heaps = used_heaps; - self.holds = holds; - self.held_to_submission = held_to_submission; - self.residency = residency; - self.joined = joined; - self.inherits = inherits; - self.resident_writes = resident_writes; - self.root_tables = root_tables; - self.root_ranges = root_ranges; - self.resident = resident; - self.stepped_tables = stepped_tables; - self.listing = listing; - self.submitted = submitted; - self.judged_to = judged_to; - self.protection = protection; - self.failing = failing; - self.rebound_use = rebound_use; - self.waited = waited; - self.release = release; - self.replay_tables = replay_tables; - self.reaches_unnamed = reaches_unnamed; - self.commit = commit; - self.writes_unnamed = writes_unnamed; - self.unrunnable = unrunnable; - self.submitted_holds = submitted_holds; - self.failed_at_commit = failed_at_commit; - self.check = check; - self.checks = checks; - self.storage_form = storage_form; - self.predication.reset(); - self.replaying_predication = replaying_predication; - self.predicated = predicated; - self.trail_mark = trail_mark; - #[cfg(unix)] - { - self.sync_file = sync_file; - } - self.room = self.lists_room(); - } - - /// An encoder of `kind` ended, its commands' uses and bindings having named `keys`, having - /// made `residency` resident (a compute or render encoder's): it joins the ended encoders, - /// with the event waits and signals encoded before it, and what it made resident joins the - /// command buffer's residency (`Residency::join_encoder`): its heaps now, its resources where - /// the command buffer's work first reads that residency - /// ([`joined_residency`](Self::joined_residency)). `takes` is what its first uses of copies - /// taken at use decided (`shadow::Takes`): an encoding of it again takes each as they did, - /// and a part of it that runs nothing gives its takes back ([`fail_part`](Self::fail_part)). - /// Its place among the ended encoders, which each of its recordings' parts carries. - pub(super) fn encoder_ended( - &mut self, - kind: EncoderKind, - keys: BTreeSet, - residency: Option, - (taken, takes): (Taken, Takes), - ) -> usize { - if let Some(ended) = &residency { - self.residency - .get_or_insert_with(Residency::default) - .join_encoder_heaps(ended, kind == EncoderKind::Compute); - } - let (event_waits_before, event_signals_before) = self.batches.events(); - self.ended.push(EncoderRecord { - kind, - label: self.open_label.take(), - event_waits_before, - event_signals_before, - keys, - residency, - taken, - replay: None, - takes, - executions: 0..0, - held: Vec::new(), - unlogged: None, - refused: None, - group: None, - in_tail: false, - }); - self.ended.len() - 1 - } - - /// Note `table`, the resident root table of work recorded on the GPU alone: its first - /// submission points it at the resident set as it lies then (`first_submission.rs`). One - /// recorded after the first submission searches the set as it lay as it was recorded, which - /// the submitted command buffer holds. - pub(super) fn replay_table(&mut self, table: ReplayTable) { - self.reaches_unnamed = true; - self.writes_unnamed = true; - if !self.submitted { - self.replay_tables.push(table); - } - } - - /// An ended encoder's times, which its completion reads (`encoder_times.rs`). - pub(super) fn encoder_timed(&mut self, timed: crate::encoder_times::Timed) { - self.times.encoders.push(timed); - } - - /// Ended encoder `encoder` kept no log a rebind encodes it again from (`replay.rs`), as - /// `why` says, for the rebound notice (`rebound_use.rs`). - pub(super) fn encoder_unlogged(&mut self, encoder: usize, why: Unlogged) { - if let Some(record) = self.ended.get_mut(encoder) { - record.unlogged = Some(why); - } - } - - /// Ended encoder `encoder` holds the images `held` in their attachment layout - /// (`texture/held_depth.rs`). - pub(super) fn encoder_holds(&mut self, encoder: usize, held: Vec) { - if let Some(record) = self.ended.get_mut(encoder) { - record.held = held; - } - } - - /// Keep `replay`, the log of ended encoder `encoder`, whose executions take `executions` - /// among the command buffer's. One of no such encoder comes back, for the caller to let go - /// of without this lock (what it holds may be the last hold of a no-copy buffer). - pub(super) fn keep_replay( - &mut self, - encoder: usize, - replay: Option, - executions: Range, - ) -> Option { - let replay = replay?; - let Some(record) = self.ended.get_mut(encoder) else { - return Some(replay); - }; - record.replay = Some(Arc::new(replay)); - record.executions = executions; - None - } - - /// Its ended encoders `encoders` (all of them where `None`), each as `used_resources.rs` - /// lists it: its kind, its event counts, every key its commands use and reach, and what it - /// made resident. The keys are its own commands' and bindings', its placed segments', and - /// those of each segment recorded and not yet placed (the commit's recording, or the host - /// step's that replaced it): what the commands of an indirect command buffer it executes - /// reach, from the commit on. - pub(super) fn read_ended(&self, encoders: Option>) -> Vec { - let range = encoders.unwrap_or(0..self.ended.len()); - let Some(records) = self.ended.get(range.clone()) else { - return Vec::new(); - }; - let mut read: Vec = records - .iter() - .map(|record| ReadRecord { - kind: record.kind, - label: record.label.clone(), - event_waits_before: record.event_waits_before, - event_signals_before: record.event_signals_before, - keys: record.keys.clone(), - residency: record.residency.clone(), - }) - .collect(); - let unplaced = self - .recorded - .iter() - .filter(|part| range.contains(&part.encoder)) - .flat_map(|part| { - let keys = part - .segments - .iter() - .filter_map(|segment| segment.recorded.as_ref()) - .flat_map(|done| done.keys.iter().copied()); - keys.map(move |key| (part.encoder - range.start, key)) - }); - for (at, key) in unplaced { - if let Some(record) = read.get_mut(at) { - record.keys.insert(key); - } - } - read - } - - /// Whether what its ended encoders `encoders` (all of them where `None`) use, as - /// [`read_ended`](Self::read_ended) reads it, has an owner among `objects`, as - /// `used_resources.rs` would list it: read in place, under this lock, with no handle cloned - /// or held (`used_resources::names_any`). False for a range past its ended encoders, as - /// `read_ended` reads none there. - pub(super) fn uses( - &self, - shared: &super::device::DeviceShared, - encoders: Option>, - objects: &[ObjectId], - ) -> bool { - let range = encoders.unwrap_or(0..self.ended.len()); - let Some(records) = self.ended.get(range.clone()) else { - return false; - }; - let ended = records - .iter() - .any(|record| names_any(shared, &record.keys, record.residency.as_ref(), objects)); - ended - || (self.recorded.iter()) - .filter(|part| range.contains(&part.encoder)) - .any(|part| { - let keys = (part.segments.iter()) - .filter_map(|segment| segment.recorded.as_ref()) - .flat_map(|done| done.keys.iter()); - names_any(shared, keys, None, objects) - }) - } - - /// Of the owners `wanted` answers for (`count` of them), those its ended encoders' uses name - /// or made resident, as [`uses`](Self::uses) answers for each of them: each encoder's uses - /// read once, under one lock of each registry an encoder's, until all `count` are found. - pub(super) fn named_among( - &self, - shared: &super::device::DeviceShared, - wanted: &dyn Fn(ObjectId) -> bool, - count: usize, - ) -> BTreeSet { - let mut found = BTreeSet::new(); - for record in &self.ended { - if found.len() == count { - return found; - } - names_of( - shared, - &record.keys, - record.residency.as_ref(), - (wanted, &mut found), - ); - } - let ended = self.ended.len(); - for part in (self.recorded.iter()).filter(|part| part.encoder < ended) { - if found.len() == count { - break; - } - let keys = (part.segments.iter()) - .filter_map(|segment| segment.recorded.as_ref()) - .flat_map(|done| done.keys.iter()); - names_of(shared, keys, None, (wanted, &mut found)); - } - found - } - - /// Whether the commands of its recorded parts `parts` (a batch's) may reach memory one of - /// `objects` owns: every memory where a command of it may reach memory no use names - /// ([`reaches_unnamed`](Self::reaches_unnamed)) or a part's encoder has no record; else what - /// their encoders use, as [`uses`](Self::uses) answers. - pub(super) fn parts_reach( - &self, - shared: &super::device::DeviceShared, - parts: Range, - objects: &[ObjectId], - ) -> bool { - let encoders = (self.recorded.get(parts).into_iter().flatten()).map(|part| part.encoder); - let (Some(first), Some(last)) = (encoders.clone().min(), encoders.max()) else { - return false; - }; - self.reaches_unnamed - || last >= self.ended.len() - || self.uses(shared, Some(first..last + 1), objects) - } - - /// What the commands of its ended encoders that `runs` (by their place among them) use and a - /// command reaches unnamed only once used, gathered weakly under this lock ([`Reached`]): what - /// their keys name, as [`read_ended`](Self::read_ended) reads them (each segment's recorded - /// and not yet placed with its encoder's), and what they made resident. - fn reached( - &self, - shared: &super::device::DeviceShared, - runs: impl Fn(usize) -> bool, - ) -> Reached { - let mut reached = Reached::default(); - for (_, record) in (self.ended.iter().enumerate()).filter(|(at, _)| runs(*at)) { - reached.gather(shared, &record.keys, record.residency.as_ref()); - } - for part in self.recorded.iter().filter(|part| runs(part.encoder)) { - let segments = part.segments.iter(); - for done in segments.filter_map(|segment| segment.recorded.as_ref()) { - reached.gather(shared, &done.keys, None); - } - } - reached - } - - /// Hold `table`, the live buffers' table a host step resolves against, each once: so the - /// step's own hold, let go of on the steps' thread, is never the last of a released - /// buffer's pages, whose release runs the program's code (`exit_guard::program_release`). - /// From the first submission on the commands the step records may reach the table's - /// buffers, so the command buffer holds it until it completes, as it holds its first - /// submission's. One a step took before then (a step of commands the GPU may write never - /// runs before it, its batch never the first, `Batches::host_step`; another kind's may) goes - /// at the first submission, at once, as the set is made of the list as it stands then - /// (`first_submission.rs`). `commit` holds none. - fn keep_stepped_table(&mut self, table: &Arc) { - let kept = self - .stepped_tables - .iter() - .any(|kept| Arc::ptr_eq(kept, table)); - if self.status != CommandBufferStatus::NotEnqueued && !kept { - self.stepped_tables.push(Arc::clone(table)); - } - } - - /// Its residency, with the resources of its ended encoders not joined into it yet joined, in - /// the order they ended, each counted (`WorkCounts::resident_resources_joined`): what its - /// work reads. Joined at the first read after they ended, it holds what it would hold had - /// each joined as it ended, in the same order: the textures made in its heaps since join - /// after them ([`sync_heaps`](Self::sync_heaps)), and an encoder encoded again joins first - /// (`reencode.rs`). - pub(super) fn joined_residency(&mut self, counts: &Counters) -> Option<&mut Residency> { - let residency = self.residency.as_mut()?; - // What the next encoders start with is found again from the residency as it is left. - self.inherits = [None, None]; - for record in &self.ended[self.joined..] { - if let Some(ended) = &record.residency { - let compute = record.kind == EncoderKind::Compute; - let joined = residency.join_encoder_resources(ended, compute); - if joined > 0 { - counts.resident_resources_joined(joined as u64); - } - } - } - self.joined = self.ended.len(); - Some(residency) - } - - /// Make resident the textures made in its heaps since (`Residency::sync_heaps`): its ended - /// encoders' resources joined first where it finds any - /// ([`joined_residency`](Self::joined_residency)), so they lie where they would have. - fn sync_heaps(&mut self, counts: &Counters) { - let Some(residency) = &mut self.residency else { - return; - }; - let made = residency.heap_textures(); - if made.is_empty() { - return; - } - if let Some(residency) = self.joined_residency(counts) { - drop(residency.join_heap_textures(made)); - } - } - - /// The residency a new compute or render (`render`) encoder starts with, under the lock its - /// opening takes ([`CommandBuffer::inherited_residency`]). - pub(super) fn inheriting(&mut self, render: bool, counts: &Counters) -> Residency { - self.sync_heaps(counts); - self.inherited(render, counts) - } - - /// Keep `parked`, what a compute encoder's end parks, for the next compute encoder that opens - /// (`compute/live.rs`): one kept already, which no encoder took, comes back. - pub(super) fn park_compute( - &mut self, - parked: crate::compute::Parked, - ) -> Option { - self.parked_compute.replace(parked) - } - - /// What the last compute encoder that ended parked, for a compute encoder that opens; `None` - /// where it is taken or given back already. - pub(super) fn unpark_compute(&mut self) -> Option { - self.parked_compute.take() - } - - /// Note `work` of an encoder it ended, which its scheduling hands to the device's identifier - /// allocations ([`UniqueIdentifiers::scheduled`](crate::unique_identifier::UniqueIdentifiers::scheduled)). - pub(super) fn note_scheduled(&mut self, work: ScheduledWork) { - self.scheduled_work.dispatch |= work.dispatch; - self.scheduled_work.render |= work.render; - } - - /// What its next compute or render (`render`) encoder starts with (`Residency::shadows`): - /// the shadowed textures its ended encoders made resident, those its residency joined and - /// those it has yet to, in the order they were made resident. Kept from the last open of - /// the kind ([`inherits`](Self::inherits)): the encoders ended since are taken in, each once, - /// in the order they ended, each counted (`WorkCounts::ended_residencies_looked_at`); the - /// encoders before it took in left what they hold, and the residency is as it found it. - fn inherited(&mut self, render: bool, counts: &Counters) -> Residency { - let Some(residency) = &mut self.residency else { - return Residency::default(); - }; - let joined = self.joined; - let (shadows, through) = self.inherits[usize::from(render)] - .get_or_insert_with(|| (residency.shadows(render), joined)); - let since = self.ended.get_mut(*through..).unwrap_or_default(); - let mut looked_at = 0; - for record in since { - if let Some(ended) = &mut record.residency { - let compute = record.kind == EncoderKind::Compute; - ended.shadows_onto(shadows, render, compute); - looked_at += 1; - } - } - if looked_at > 0 { - counts.ended_residencies_looked_at(looked_at); - } - *through = self.ended.len(); - shadows.clone() - } - - /// Set [`resident_writes`](Self::resident_writes) from what each ended encoder made resident - /// for writing, read from the encoders' own residencies (joining them into its residency - /// would cost a command buffer whose work never reads that residency the join), with the - /// uses of their host memory `aliases` adds, as an encoder's tracked uses take them: at its - /// commit. - fn note_resident_writes(&mut self, aliases: &super::host_aliases::HostAliases) { - let uses: Vec> = (self.ended.iter()) - .filter_map(|record| record.residency.as_ref()) - .flat_map(Residency::written_uses) - .collect(); - self.resident_writes = match uses.is_empty() { - true => None, - false => { - let uses = aliases.augment(&uses).unwrap_or(uses); - Some(Summary::of_no_stage(uses)).filter(|summary| !summary.is_empty()) - } - }; - } - - /// The bytes of the buffer of `key` its ended encoders' commands may write, as their encoding - /// says: their tracked uses, their segments' (`managed_sync::segment_writes`), and what they - /// made resident for writing, the buffer whole. What a copy out decided as it is encoded - /// copies of its command buffer's commands before it (`managed_sync.rs`); `None` where one may - /// write the buffer unknown: a command that may write memory no use names - /// ([`writes_unnamed`](Self::writes_unnamed)) or whose recording finds its uses. - pub(super) fn written_before( - &self, - device: &Device, - key: ResourceKey, - ) -> Option>> { - if self.writes_unnamed { - return None; - } - let mut written = Vec::new(); - for part in self.recorded.iter() { - crate::managed_sync::writes_of(&part.summary, key, &mut written); - for segment in &part.segments { - if !crate::managed_sync::segment_writes(segment, device, key, &mut written) { - return None; - } - } - } - let resident = (self.ended.iter()) - .filter_map(|record| record.residency.as_ref()) - .any(|residency| (residency.written_uses().iter()).any(|used| used.key == key)); - if resident { - written.push(0..u64::MAX); - } - Some(written) - } - - /// Let go of what its ended encoders' commands use, as it completes: their keys, and what - /// they made resident, for the caller to release without this lock. - fn let_go_of_uses(&mut self) -> Vec { - self.ended - .iter_mut() - .filter_map(|record| { - record.keys.clear(); - record.residency.take() - }) - .collect() - } - - /// Note a root table its commands read, uploaded at `table` (`upload`), whose own resident - /// set is `ranges`: the commit points it at the command buffer's resident set. One a host - /// step uploads after the commit is pointed now, at that set where it holds `ranges`, else - /// at a set of both made for it. `writes`: whether a function that reads it may write memory - /// ([`State::writes_unnamed`]). - pub(super) fn root_table( - &mut self, - device: &Device, - noted: NotedTable, - ranges: Vec, - writes: bool, - ) -> Result<(), Error> { - self.reaches_unnamed = true; - self.writes_unnamed |= writes; - let counts = &device.shared().counts; - counts.root_table_ranges_noted(ranges.len() as u64); - if self.status == CommandBufferStatus::NotEnqueued { - self.root_ranges.extend(ranges); - self.root_tables.push(noted); - return Ok(()); - } - // A host step's before the first submission is noted too, which points it again where - // the live buffers changed by then; the set it is pointed at now is made of the list as - // it stands. - if !self.submitted { - self.root_ranges.extend(ranges.iter().copied()); - self.root_tables.push(noted.clone()); - self.resident(device)?; - self.hold_live(device)?; - } - let NotedTable { - upload, - address: table, - } = noted; - let resident = self.resident(device)?; - // Held from the first submission, and from a host step's before it (above). - let set = resident - .merged - .as_ref() - .or(resident.live.set()) - .ok_or_else(|| internal("a host step's root table before its live table is held"))?; - if ranges.iter().all(|range| set.holds(range)) { - return self.point(&upload, table); - } - let both = set.with(ranges); - let (address, count) = self.upload_set(device, &both)?; - write_fields(&upload, table, address, count) - } - - /// Point every root table noted before the commit at the command buffer's resident set. - fn point_root_tables(&mut self, device: &Device) -> Result<(), Error> { - if self.root_tables.is_empty() { - return Ok(()); - } - self.resident(device)?; - for noted in &self.root_tables { - self.point(¬ed.upload, noted.address)?; - } - Ok(()) - } - - /// The command buffer's resident set, made on first need: the device's live buffers, and - /// the ranges its root tables noted and its encoders made resident beyond them. - fn resident(&mut self, device: &Device) -> Result<&Resident, Error> { - if self.resident.is_none() { - let resident = self.make_resident(device)?; - self.resident = Some(resident); - } - self.resident - .as_ref() - .ok_or_else(|| internal("a command buffer's resident set not made")) - } - - fn make_resident(&mut self, device: &Device) -> Result { - let live = device.shared().live_buffers.table(device)?; - let set = live.set(); - let mut beyond: Vec = self.root_ranges.iter().copied().collect(); - if let Some(residency) = self.joined_residency(&device.shared().counts) { - beyond.extend(residency.resident_ranges()); - } - beyond.retain(|range| !set.holds(range)); - let (merged, address, count) = match beyond.is_empty() { - true => (None, live.address(), set.len()), - false => { - let merged = set.with(beyond); - let (address, count) = self.upload_set(device, &merged)?; - (Some(merged), Some(address), count) - } - }; - // Held weakly until the first submission, which makes the set again where the list - // changed since. - Ok(Resident { - live: Live::of(live, self.submitted), - merged, - address, - count, - }) - } - - /// `set` uploaded to the arena at a 32-byte-aligned device address: that address and its - /// count. - fn upload_set(&mut self, device: &Device, set: &ResidentSet) -> Result<(u64, u64), Error> { - let bytes = set.bytes(); - let upload = self.uploads.upload_aligned( - device, - &bytes, - bytes.len() as u64, - RootTable::ENTRY_ALIGNMENT, - )?; - let address = upload - .device_address() - .ok_or_else(|| internal("a resident set without a device address"))?; - Ok((address, set.len())) - } - - /// Point the root table at `table` (`upload`) at the command buffer's resident set, once - /// made. - fn point(&self, upload: &Upload, table: u64) -> Result<(), Error> { - match &self.resident { - Some(resident) => write_fields( - upload, - table, - resident.address.unwrap_or(table), - resident.count, - ), - None => Ok(()), - } - } - - /// Note `heaps`, which an ended encoder's commands used. - pub(super) fn use_heaps(&mut self, heaps: Vec) { - for heap in heaps { - if !self.used_heaps.contains(&heap) { - self.used_heaps.push(heap); - } - } - } - - /// Why nothing more can be encoded or committed now: the command buffer was committed (its - /// commit's own work waiting or not, `render/queued_commits.rs`), an encoder is open, or one - /// was abandoned. - pub(super) fn refusal(&self) -> Option { - match self.queued_commit { - Some(_) => Some(Problem::AlreadyCommitted), - None => self.commit_refusal(), - } - } - - /// [`refusal`](Self::refusal), but of a commit whose own work waited - /// (`render/queued_commits.rs`), as it runs. - fn commit_refusal(&self) -> Option { - if self.status != CommandBufferStatus::NotEnqueued || self.committing { - Some(Problem::AlreadyCommitted) - } else if self.encoder_open { - Some(Problem::EncoderOpen) - } else if self.abandoned { - Some(Problem::EncoderAbandoned) - } else { - None - } - } - - /// Keep a command's function-table `snapshot` to write again as the command buffer commits. A - /// snapshot a host step writes after the commit already holds the words as they stand then. - pub(super) fn snapshot_tables(&mut self, snapshot: TableSnapshot) { - if self.status == CommandBufferStatus::NotEnqueued { - self.table_snapshots.push(snapshot); - } - } - - /// A command left a live sampler state out of its argument samplers: its variant's set-1 - /// sampler arrays hold fewer elements than the live states (`heap_sets::fit_samplers`), so - /// its function reads the neutral sampler where Metal's reaches the state by its ID. The - /// command buffer is counted once (`WorkCounts::unlisted_argument_sampler_buffers`). - pub(super) fn unlisted_argument_sampler(&mut self, device: &Device) { - if !self.unlisted_argument_samplers { - self.unlisted_argument_samplers = true; - device.shared().counts.unlisted_argument_sampler_buffer(); - } - } - - /// The place among the ended encoders the open encoder takes as it ends: one encoder is open - /// at a time, and one dropped before it ended abandons the command buffer, which then - /// commits nothing. - pub(super) fn open_encoder_place(&self) -> usize { - self.ended.len() - } - - /// The encoders, or parts of them, ended so far. - pub(super) fn parts(&self) -> usize { - self.recorded.len() - } - - /// The predication the open encoder's records and dispatches use: that of an encoder a rebind - /// encodes again now ([`replaying_predication`](Self::replaying_predication)), else the - /// command buffer's. - pub(super) fn predication_mut(&mut self) -> &mut Predication { - match &mut self.replaying_predication { - Some(replaying) => replaying, - None => &mut self.predication, - } - } - - /// [`predication_mut`](Self::predication_mut), with the upload arena. - pub(super) fn predication_and_uploads(&mut self) -> (&mut Predication, &mut Uploads) { - let predication = match &mut self.replaying_predication { - Some(replaying) => replaying, - None => &mut self.predication, - }; - (predication, &mut self.uploads) - } - - /// A compute encoder of `dispatch_type` opened: it joins the unit of command predication of - /// the compute encoder that ended just before it, of its dispatch type with no event wait or - /// signal between and no fence update in it, taking the bodies of the loops it left open, or - /// starts the next (`predication.rs`). - pub(super) fn enter_predication( - &mut self, - dispatch_type: DispatchType, - ) -> Vec> { - let place = self.open_encoder_place(); - self.predication - .enter(place, self.batches.events(), dispatch_type) - } - - /// The failure of the making of a draw's pipeline a device test injected - /// ([`CommandBuffer::fail_draw_making`]), taken here. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn injected_making_failure(&mut self) -> Option { - self.making_failure_injected.take() - } - - /// Keep `error`, a render encoder's call's refused as it was lowered - /// (`CommandBufferError::CallRefused`): the first such call's. - pub(super) fn refuse_call(&mut self, error: Error) { - self.refusal.get_or_insert(error); - } - - /// The open render encoder's end, lowered after its call, refused for `error` - /// (`render/deferral.rs`): the encoder, which its end's refusal dropped unended, ends here - /// with nothing of it run, and the command buffer fails from it on as a refusal of one of its - /// calls does (`CommandBufferError::CallRefused` of `call`, its error kept), commits, and - /// runs nothing of it or after it. - pub(super) fn refuse_end(&mut self, call: EncoderCall, error: Error) { - self.encoder_open = false; - self.abandoned = false; - let place = self.open_encoder_place(); - self.fail_from(place, CommandBufferError::CallRefused(call)); - self.refuse_call(error); - } - - /// The commit's own work, which waited (`render/queued_commits.rs`), refused it for - /// `error`, found after `commit` returned: nothing of the command buffer runs, and it fails - /// as its first refused call names it (`CommandBufferError::CallRefused`): the commit, as - /// `commit` at index 0, where no call of its encoders was refused before. The refusal's - /// error is kept, as a call's is. - fn refuse_commit(&mut self, error: Error) { - let commit = CommandBufferError::CallRefused(EncoderCall::new("commit", 0)); - let first = self.fails_from.map_or(commit, |(_, first)| first); - self.fails_from = Some((0, first)); - self.refuse_call(error); - } - - /// Ended encoder `encoder` fails the command buffer from it on with `error` (`fails_from`). - pub(super) fn fail_from(&mut self, encoder: usize, error: CommandBufferError) { - self.fails_from.get_or_insert((encoder, error)); - } - - /// Ended encoder `encoder`, the last, fails the command buffer with `error` from the first - /// encoder of the submission Metal holds it in on (`checks::metal_submissions`: a render pass - /// alone, a run of blit or of compute encoders that no event command splits), as Metal fails - /// a submission that uses a memoryless texture (`CommandBufferError::InvalidResource`); an - /// earlier failure keeps its error, from the earlier of the two encoders. - pub(super) fn fail_submission_from(&mut self, encoder: usize, error: CommandBufferError) { - let records = self.ended.iter().map(|record| { - ( - record.kind, - record.event_waits_before, - record.event_signals_before, - ) - }); - let first = checks::submission_start(records, encoder); - self.fails_from = Some(match self.fails_from { - Some((from, earlier)) => (from.min(first), earlier), - None => (first, error), - }); - } - - /// Note the shadowed textures an ended encoder's pass took as attachments: how many of them - /// no pass of the command buffer took before. - pub(super) fn shadows_attached(&mut self, keys: &[ResourceKey]) -> usize { - let mut first = 0; - for &key in keys { - if !self.shadow_attachments.contains(&key) { - self.shadow_attachments.push(key); - first += 1; - } - } - first - } - - /// Note the shadowed textures an ended encoder copied in first, each copy's texture and - /// texels: the texels of those an earlier encoder of the command buffer copied in too. - pub(super) fn shadows_copied_in(&mut self, copies: &[(ResourceKey, u64)]) -> u64 { - let earlier = self.shadows_copied_in.len(); - let mut again = 0; - for &(key, texels) in copies { - if self.shadows_copied_in[..earlier].contains(&key) { - again += texels; - } else if !self.shadows_copied_in.contains(&key) { - self.shadows_copied_in.push(key); - } - } - again - } - - /// What its ended encoders left shadowed textures' images holding, for the encoder opening - /// now (`shadow::ShadowCarry`): the command buffer carries nothing until it is handed back - /// by [`shadows_carried`](Self::shadows_carried), so an encoder abandoned without ending - /// leaves it carrying none and every texture copies in again. Nothing either where this - /// encoder runs in another batch than the last ended one: the batches split since (a wait, a - /// host step, a resource state encoder) or the current one signals, so this encoder starts - /// the next (`Batches::encoder`). Another queue's batch may run between the two, and its - /// writes reach the truth the image no longer holds. - pub(super) fn shadows_to_carry(&mut self) -> ShadowCarry { - let mut carry = self.shadow_carry.take().unwrap_or_default(); - if self.batches.all().len() != self.carry_batches || self.batches.signals_pending() { - carry.clear(); - } - carry - } - - /// Take back what an ended encoder leaves its command buffer's later encoders - /// (`shadow::ShadowSync::ended`). - pub(super) fn shadows_carried(&mut self, carry: ShadowCarry) { - self.shadow_carry = Some(carry); - } - - /// Where an encoder ending now ends among its encoders and batches (`pass_runs.rs`). - pub(super) fn run_point(&self) -> RunPoint { - RunPoint { - ended: self.recorded.len(), - batches: self.batches.all().len(), - signals: self.batches.signals_pending(), - } - } - - /// Its open runs of passes over one attachment merged once (`pass_runs.rs`). - pub(super) fn pass_runs(&mut self) -> &mut PassRuns { - &mut self.pass_runs - } - - /// Carry no shadowed texture's image on: the work encoded next reads what another writer the - /// wait orders before it left in the truth, which every texture copies in again to hold - /// (`shadow::ShadowCarry`). - pub(super) fn shadows_not_carried(&mut self) { - if let Some(carry) = &mut self.shadow_carry { - carry.clear(); - } - } - - /// Metal's GPU faults ended encoder `encoder`, failing the command buffer with `error` from - /// it on (`faulted`, `Failure::with_faults`); where nothing failed it from an earlier encoder - /// and no earlier encoder faulted, the work before the encoder signals the fault's hold and - /// what follows waits for it (`hang.rs`), so the command buffer completes when Metal's does. - /// Where an earlier encoder faulted, the GPU reaches this one once it recovered: the earlier - /// fault's hold counts it (`Hang::fails_later`). - pub(super) fn fault( - &mut self, - encoder: usize, - error: CommandBufferError, - device: &Device, - ) -> Result<(), Error> { - if self.fails_from.is_none() && self.hang.is_none() { - self.hold(device, encoder, Held::Fault(Later::default()))?; - } else if !self.faulted.contains_key(&encoder) { - if let Some(hang) = &mut self.hang { - hang.fails_later(false); - } - } - self.faulted.entry(encoder).or_insert(error); - Ok(()) - } - - /// Ended encoder `encoder` drew primitive type 9 directly, at which Metal's GPU hangs - /// (`hang.rs`): the command buffer fails from it on with `CommandBufferError::GpuHang`, and, - /// where nothing failed it from an earlier encoder, the work before the encoder signals the - /// hang's event and what follows waits for the hang's hold. Where an earlier encoder faulted, - /// it fails from the fault with the fault's error (`State::fault`), and the GPU reaches it - /// once it recovered: the fault's hold counts it (`Hang::fails_later`). - pub(super) fn hang_from(&mut self, encoder: usize, device: &Device) -> Result<(), Error> { - if !self.faulted.is_empty() { - if let Some(hang) = &mut self.hang { - hang.fails_later(true); - } - return Ok(()); - } - if self.fails_from.is_none() && self.hang.is_none() { - self.hold(device, encoder, Held::Hang)?; - } - self.fail_from(encoder, CommandBufferError::GpuHang); - Ok(()) - } - - /// Hold what follows ended encoder `encoder`, the last, of the hold `held`: its batch signals - /// the hold's event, and the next batch waits for its release (`hang.rs`). - fn hold(&mut self, device: &Device, encoder: usize, held: Held) -> Result<(), Error> { - let hang = Hang::new(device, (self.batches.all().len() - 1, encoder), held)?; - let event = || Arc::clone(EventRef::Shared(hang.event()).shared()); - self.batches.hold_signal(event(), Hang::REACHED); - self.batches.hold(event(), Hang::RELEASED); - self.hang = Some(hang); - Ok(()) - } - - /// The holds of what its commands took that batch `index`'s work lets go as it completes - /// (`State::submitted_holds`), for its submission to carry (`completion::Submitted`). - pub(super) fn holds_until(&mut self, index: usize) -> Vec { - if self.submitted_holds.is_empty() { - return Vec::new(); - } - let (now, later): (Vec<_>, Vec<_>) = self - .submitted_holds - .drain(..) - .partition(|(until, _)| *until <= index); - self.submitted_holds = later; - now.into_iter().map(|(_, holds)| holds).collect() - } - - /// The holds of its last batch, whose work completed: kept until its completion is processed, - /// which lets go of every hold it still counts before its completed handlers run - /// (`State::submitted_holds`, `CommandBufferShared::complete`). - pub(super) fn keep_holds(&mut self, holds: Vec) { - for held in holds { - self.submitted_holds.push((usize::MAX, held)); - } - } - - /// The encoders (or parts of them) of batch `index`. - pub(super) fn batch_range(&self, index: usize) -> Range { - let batches = self.batches.all(); - let start = index.checked_sub(1).map_or(0, |before| batches[before].end); - start..batches[index].end - } - - /// The next encoder, a part of one that executes commands the GPU may write, starts a batch - /// of its own, which waits for a host step. - pub(super) fn host_step(&mut self) { - self.batches.host_step(); - } - - /// A resource state encoder of `command_buffer` ended with `recorded`: it starts a batch of - /// its own, unless the batch so far holds only such encoders, so its updates bind before - /// every encoder after it. - pub(super) fn end_sparse_encoder( - &mut self, - command_buffer: &CommandBuffer, - recorded: Recorded, - ) { - self.batches.sparse(); - self.end_encoder(command_buffer, recorded); - } - - /// Whether a command of an encoder that ended so far wrote one of `keys`: what its batch's - /// submission reads of the encoders before an encoder (`submit.rs`'s `stands`), read as the - /// next encoder records. - pub(super) fn ended_encoders_write_any(&self, keys: &[ResourceKey]) -> bool { - (self.recorded.iter()).any(|recorded| recorded.summary.writes_any(keys)) - } - - /// An encoder of `command_buffer` ended with `recorded`: it joins the current batch, or a - /// new one after the batch's signals. The tail before it ends: with its batch's end where - /// that batch ended before this encoder ([`CommandBufferShared::close_tail`]). - pub(super) fn end_encoder(&mut self, command_buffer: &CommandBuffer, recorded: Recorded) { - self.recorded.push(recorded); - // Each encoder in a batch of its own, where the encoder trail is on (`encoder_trail.rs`). - if command_buffer.device().shared().encoder_trail { - self.batches.alone(); - } - self.batches.encoder(); - self.carry_batches = self.batches.all().len(); - self.encoder_open = false; - let joined = self.recorded.len() - 1; - command_buffer.0.close_tail(self, Some(joined)); - } - - /// The batch that holds part `part` of the ended encoders. - fn batch_of(&self, part: usize) -> usize { - let batches = self.batches.all(); - batches - .iter() - .position(|batch| batch.end > part) - .unwrap_or(batches.len() - 1) - } - - /// Whether batch `index`'s end may go into its last `VkCommandBuffer` (`submit.rs`): its - /// parts leave no segment or sparse update for its submission (whose recordings go among or - /// after the parts' own), nor its last part a write into an ASTC carrier (whose second twin's - /// decode its submission may record after it, `texture/decoded_twin.rs`), and name no texture - /// over the caller's image that moves between layouts (whose move back its submission plans - /// before the end), while no texture's turn may leave its submission a copy after its work - /// (`texture/faces.rs`); none begins before the batch's submission, a turn waiting for the - /// device's only uncommitted command buffer, which counts this one until the scheduler holds - /// its batches (`queue.rs`'s `Uncommitted`), and for a scheduler that holds no batch. An - /// event's kept signal that waits for another queue's still - /// goes after that wait, in an end of its own at the submission (`submit.rs`). - fn may_fold(&self, device: &Device, index: usize) -> bool { - let parts = &self.recorded[self.batch_range(index)]; - !device.shared().face_swaps.any() - && parts - .iter() - .all(|part| part.segments.is_empty() && part.sparse.is_empty()) - && parts.last().is_none_or(|part| part.twin_writes.is_empty()) - && device - .shared() - .interop - .wrapped - .among(parts.iter().flat_map(|part| part.summary.keys())) - .is_empty() - } - - /// The `VkCommandBuffer` batch `index`'s end went into, and whether it wrote the command - /// buffer's end timestamp; `None` where it went into none. - pub(super) fn fold(&self, index: usize) -> Option<(vk::CommandBuffer, bool)> { - self.folds - .iter() - .find(|fold| fold.batch == index) - .map(|fold| (fold.raw, fold.stamped)) - } - - /// Fail the command buffer as `failure` says ([`CommandBuffer::commit_failed`], or an - /// encoder Metal fails it from, `fails_from`), before `commit` hands its work on the segments - /// of the encoders that run to them: the recordings of the encoders `failure.encoders` names - /// (every part of each) are released unrun, each part keeping its place among the batches - /// with its fences' waits and updates alone; the event signals `failure.signals` drops are - /// not signaled; and the command buffer finishes with `failure.error`, where it has one - /// (a code-0 `commit_failed` has none). - fn fail(&mut self, failure: Failure) { - let State { - recorded, - retained, - ended, - .. - } = self; - for part in recorded - .iter_mut() - .filter(|part| failure.encoders.fails(part.encoder)) - { - State::fail_part(part, ended, retained); - } - match failure.signals { - FailedSignals::Every => {} - FailedSignals::Dropped => self.batches.drop_signals(), - FailedSignals::From(encoder) => { - // The parts before the encoder's first, which the batches count. - let parts = self - .recorded - .iter() - .take_while(|part| part.encoder < encoder) - .count(); - self.batches.drop_signals_after(parts); - } - } - if let Some(error) = failure.error { - self.failure = Some(error); - } - self.failed_at_commit = Some(failure.encoders); - } - - /// A command-predication record dropped what the ended encoders from `first` on recorded, - /// its unit's earlier encoders (`predication.rs`): each of their parts runs nothing, as a - /// failed encoder's ([`fail_part`](Self::fail_part)). A group of encoders recorded into one - /// `VkCommandBuffer` whose first lies before `first` holds their commands in that one, which - /// its first part runs: the commit splits it (`fold.rs`'s `split_failure`). - pub(super) fn leave_out_ended(&mut self, first: usize) { - self.left_out_from = Some(self.left_out_from.map_or(first, |from| from.min(first))); - let State { - recorded, - retained, - ended, - .. - } = self; - for part in recorded.iter_mut().filter(|part| part.encoder >= first) { - State::fail_part(part, ended, retained); - } - } - - /// Its command pools, taken out to go back to the device's spares: its first, then those it - /// took past it (`spares.rs`); none where it has no pool. - fn pools(&mut self) -> Vec { - let past = self.pools_past_first.drain(..); - self.pool.take().into_iter().chain(past).collect() - } - - /// Give back every take of a copy taken at use its ended encoders and the recordings of - /// their segments took (`shadow::Takes::give_back`): none of them runs. - fn give_back_takes(&self) { - for record in &self.ended { - record.takes.give_back(); - } - let segments = self.recorded.iter().flat_map(|part| &part.segments); - for done in segments.filter_map(|segment| segment.recorded.as_ref()) { - done.takes.give_back(); - } - } - - /// Batch `index` and every later one never run, the command buffer failed at that batch's - /// submission (`CommandBufferShared::never_runs_from`): the copies taken at use the encoders - /// of their parts and those parts' segments' recordings took are given back, so the next use - /// takes each (`shadow::Takes::give_back`), every one such an encoder took, whichever of its - /// parts recorded it, as [`fail_part`](Self::fail_part) gives them back. - pub(super) fn give_back_from(&self, index: usize) { - if index >= self.batches.all().len() { - return; - } - let parts = &self.recorded[self.batch_range(index).start..]; - let encoders: BTreeSet = parts.iter().map(|part| part.encoder).collect(); - for record in encoders.iter().filter_map(|&at| self.ended.get(at)) { - record.takes.give_back(); - } - let segments = parts.iter().flat_map(|part| &part.segments); - for done in segments.filter_map(|segment| segment.recorded.as_ref()) { - done.takes.give_back(); - } - } - - /// A failed encoder's recorded `part` runs nothing: its segments (with their recordings), - /// sparse updates and writes into ASTC carriers go to `retained`, released with what the - /// command buffer retained without this lock, its `VkCommandBuffer`s are left unsubmitted, - /// and it keeps its place among the batches with its fences' waits and updates alone. The - /// copies taken at use its encoder (among the `ended`) and its segments' recordings took are - /// given back, so the next use takes each (`shadow::Takes::give_back`): every one its encoder - /// took, whichever of its parts recorded it. - pub(super) fn fail_part( - part: &mut Recorded, - ended: &[EncoderRecord], - retained: &mut Vec>, - ) { - if let Some(record) = ended.get(part.encoder) { - record.takes.give_back(); - } - for segment in part.segments.drain(..) { - retained.push(Box::new((segment.work, segment.inputs))); - if let Some(mut done) = segment.recorded { - done.takes.give_back(); - retained.extend(done.retained.into_entry()); - done.taken.retain_into(retained); - } - } - for update in part.sparse.drain(..) { - retained.push(Box::new(update)); - } - // Its writes into ASTC carriers ran nothing, so nothing of them is decoded. - for write in part.twin_writes.drain(..) { - retained.push(Box::new(write)); - } - // It writes nothing whole: its batch keeps the zeros (`submit.rs`). - part.overwrites.clear(); - part.raws.clear(); - part.summary = part.summary.fences_only(); - } - - /// Join the GPU forms `commit`'s recording of each segment took (`forms`, one list per - /// segment in encoding order) to the encoder trail's name of the part that holds it - /// (`encoder_trail.rs`, **GPU forms**). - fn trail_forms(&mut self, forms: Vec>>) { - let mut forms = forms.into_iter(); - for part in self.recorded.iter_mut() { - for _ in &part.segments { - let took = forms.next().unwrap_or_default(); - if let Some(trail) = part.trail.as_mut().filter(|_| !took.is_empty()) { - trail.join_forms(took); - } - } - } - } - - /// Hand `commit`'s work on the segments, one per segment in encoding order, to them: the - /// recording of a segment `commit` made, for good where no host step records it, and what a - /// host step needs. - fn prepare(&mut self, prepared: Vec) { - let segments = self - .recorded - .iter_mut() - .flat_map(|encoder| encoder.segments.iter_mut()); - let mut checks = Vec::new(); - for (segment, prepared) in segments.zip(prepared) { - let Prepared { - recorded, - for_good, - inputs, - retained, - pipelines, - bound, - held, - } = prepared; - segment.host |= held; - segment.gpu_alone = for_good && recorded.is_some(); - segment.bound = bound; - segment.recorded = recorded; - segment.stepped |= for_good; - segment.pipelines |= pipelines; - segment.inputs = Some(inputs); - self.retained.extend(retained); - if let Deferred::Loop(check) = &segment.work { - checks.push(Arc::clone(check)); - } - } - // A loop's check learns how a run again records the work its laying left apart, from - // the segments the laying's parts hold, each prepared now (`rerun.rs`). - for check in checks { - check.learn(self.recorded.get(check.from()..).unwrap_or_default()); - } - } - - /// Put the segments of encoders (or parts of them) `range`, each recorded, in their places as - /// their batch is submitted: each `VkCommandBuffer` among its part's, its uses joined to the - /// part's summary, its dispatches among the executions in encoding order, and what it used - /// retained. Refused, changing nothing, where a segment is not recorded. - fn place(&mut self, range: Range) -> Result<(), Error> { - let State { - recorded, - executions, - retained, - resident_misses, - faults, - placed, - ended, - piece_ends, - .. - } = self; - let encoders = &mut recorded[range]; - if encoders - .iter() - .flat_map(|encoder| &encoder.segments) - .any(|segment| segment.recorded.is_none()) - { - return Err(internal("a segment submitted unrecorded")); - } - // A segment that recorded nothing for a command (a buffer it named was detached) is - // never placed: its submission failed (`State::failing_at`). - let dead = encoders - .iter() - .flat_map(|encoder| &encoder.segments) - .filter_map(|segment| segment.recorded.as_ref()) - .any(|done| done.taken.dead()); - debug_assert!(!dead, "a segment that named a detached buffer submitted"); - if dead { - return Err(internal("a segment that named a detached buffer submitted")); - } - for encoder in encoders { - // The segments' command buffers placed so far, each segment's after the part's own - // before it and the segments' before it. - let mut before = 0; - for segment in encoder.segments.drain(..) { - let Segment { - at, - executions_at, - work, - inputs, - recorded, - .. - } = segment; - // Released with what the command buffer retained, without this lock. - retained.push(Box::new((work, inputs))); - let Some(mut done) = recorded else { - continue; - }; - // The pages its commands took, held until the command buffer completes. - done.taken.retain_into(retained); - let raws = done.raws.len(); - piece_ends.extend(done.piece_ends); - encoder.raws.splice(at + before..at + before, done.raws); - before += raws; - encoder.summary.join(done.summary); - let at = executions_at + *placed; - *placed += done.executions.len(); - executions.splice(at..at, done.executions); - retained.extend(done.retained.into_entry()); - // The segment's keys are its encoder's, and so are its takes of copies taken at - // use, given back with the encoder's where its batch never runs - // ([`give_back_from`](Self::give_back_from)). - if let Some(record) = ended.get_mut(encoder.encoder) { - record.keys.extend(done.keys); - record.takes.join(done.takes); - } - *resident_misses = resident_misses.wrapping_add(done.resident_misses); - *faults = ReplayFaults(faults.0 | done.faults.0); - } - } - Ok(()) - } - - /// What the segments a failed command buffer never placed retained, for its release. - fn unplaced(&mut self) { - let leftover: Vec<_> = self - .recorded - .iter_mut() - .flat_map(|encoder| encoder.segments.drain(..)) - .collect(); - for segment in leftover { - let Segment { - work, - inputs, - recorded, - .. - } = segment; - self.retained.push(Box::new((work, inputs))); - if let Some(mut done) = recorded { - self.retained.extend(done.retained.into_entry()); - done.taken.retain_into(&mut self.retained); - } - } - } - - /// Whether a chunk's context is lent (`CommandBuffer::lend_kept`): the command buffers it - /// hands out are begun for simultaneous use. - pub(super) fn keeping(&self) -> bool { - self.kept.is_some() - } - - /// The device address of the command buffer's execution status words, uploaded (all zero, - /// `ExecutionStatus::initial`) when a command first reaches them; `None` on a device without - /// device addresses. - pub(super) fn status_address(&mut self, device: &Device) -> Result, Error> { - Ok(self.status_words(device)?.device_address()) - } - - /// A direct mesh draw's object grid lies past what the device launches - /// (`render/mesh_arguments.rs`): the command buffer fails. - pub(crate) fn mesh_grid_past_limits(&mut self) { - self.mesh_grid_past = true; - } - - /// Hold `object`, which one of its commands made for itself alone (a uniform view's texel - /// buffer view, `uniform_texels.rs`), until the command buffer completed, with what it - /// retained: what the command buffer alone holds, so a recording that reached it is not kept - /// for another command buffer to run (`own_reached`). - pub(super) fn retain_own(&mut self, object: impl Any + Send + Sync) { - self.own_reached += 1; - self.retained.push(Box::new(object)); - } - - /// The command buffer's execution status words, uploaded (all zero, `ExecutionStatus::initial`) - /// when a command first reaches them. - pub(super) fn status_words(&mut self, device: &Device) -> Result { - self.own_reached += 1; - if let Some(words) = &self.status_words { - return Ok(words.clone()); - } - let words = self.uploads.upload( - device, - &ExecutionStatus::initial(), - ExecutionStatus::BYTES as u64, - )?; - self.status_words = Some(words.clone()); - Ok(words) - } - - /// The command buffer's index pool (`index_bounds.rs`, `index_rewrite.rs`), taken when a - /// draw first needs it: its counter, `IndexBoundsPass::POOL_HEADER_BYTES` of the arena, zero; - /// and the block its indices lie in, from the block's - /// `IndexBoundsPass::POOL_HEADER_BYTES` on, its queue's (`queue`, the command buffer's - /// `CommandQueue::id`), leased from the device (`gpu_pools.rs`): the block's `VkBuffer` and - /// bytes, the header's included. - pub(super) fn index_pool(&mut self, device: &Device, queue: u64) -> Result { - self.own_reached += 1; - if let Some((counter, block)) = &self.index_pool { - return Ok(IndexPool::of(counter, block)); - } - let header = IndexBoundsPass::POOL_HEADER_BYTES; - let counter = self - .uploads - .upload(device, &vec![0; header as usize], header)?; - let block = device.lease_pool(PoolKind::Index, queue)?; - let pool = IndexPool::of(&counter, &block); - self.index_pool = Some((counter, block)); - Ok(pool) - } - - /// The command buffer's mesh records pool (`render/mesh.rs`): a block of the device's - /// budget, leased when a scanned emulated mesh draw first needs it, a host step's replay of - /// one among them (`gpu_pools.rs`): its `VkBuffer` and bytes. Its words need no value before - /// the scans reserve them. - pub(super) fn mesh_pool( - &mut self, - device: &Device, - queue: u64, - ) -> Result<(vk::Buffer, u64), Error> { - self.own_reached += 1; - if let Some(pool) = &self.mesh_pool { - return Ok((pool.raw(), pool.bytes())); - } - let pool = device.lease_pool(PoolKind::MeshRecords, queue)?; - let leased = (pool.raw(), pool.bytes()); - self.mesh_pool = Some(pool); - Ok(leased) - } - - /// The number of the command buffer's next emulated mesh draw: its order among them, from 0 - /// (`MeshDispatch::DRAW_ID`). - pub(super) fn next_mesh_draw(&mut self) -> u32 { - let number = self.mesh_draws; - self.mesh_draws = number.saturating_add(1); - number - } -} - -impl Drop for CommandBufferShared { - fn drop(&mut self) { - // A sync file's semaphore its completion did not take: one never committed, or whose - // work never ended (`sync_file.rs`). - #[cfg(unix)] - { - let taken = lock(&self.state).take_sync_file(); - self.release_sync_file(taken); - } - // A command buffer that still holds its pool was never submitted, or ended before its - // completion gave the pool back: a committed command buffer is held by the scheduler until - // its batches were submitted, and by its queue's waiter until they completed, so - // nothing of its pool is pending. The device's spares keep it (`spares.rs`), which - // release it only with the device. A timestamp slot it still holds goes back with its - // state. - let pool = { - let mut state = lock(&self.state); - // One never committed ran nothing, as Metal runs nothing of it: each take of a copy - // taken at use goes back, so the texture's next use takes the copy. - if state.status == CommandBufferStatus::NotEnqueued { - state.give_back_takes(); - } - state.pools() - }; - let shared = self.device.shared(); - // A turn of a texture's faces its pass made whose part no submission ran: the next batch - // that names the face turned to takes the copy (`texture/faces.rs`). - shared.face_swaps.ran_nothing(self.address()); - let recorded = self.recorded.load(Ordering::Relaxed); - for pool in pool { - shared - .spares - .give_command_pool(shared, pool, false, recorded); - } - // Its state goes on to a command buffer the device makes next, reset here, what it held - // going and its lists of records keeping their room (`spare_states.rs`): where the device - // has a place for it. Only this command buffer holds it. - let Some(state) = Arc::get_mut(&mut self.state).and_then(|state| state.get_mut().ok()) - else { - return; - }; - let room = state.lists_room(); - shared.counts.record_lists_grown(state.room.grown(room)); - if !shared.spare_states.wants(room) { - return; - } - state.reset(); - let revision = Arc::clone(&self.footprints.revision); - let kept = KeptState::new(Arc::clone(&self.state), revision, room); - if shared.spare_states.give(kept) { - shared.counts.record_storage_kept(); - } - } -} - -/// Point the root table at `table` (`upload`) at `count` entries of a resident set at `set`. -fn write_fields(upload: &Upload, table: u64, set: u64, count: u64) -> Result<(), Error> { - let fields = RootTable::resident_fields(table, set, count).ok_or_else(|| { - internal("a root table not a whole number of entries from its resident set") - })?; - upload.write_at(u64::from(RootTable::RESIDENT_FIELDS_OFFSET), &fields); - Ok(()) -} - -impl CommandBuffer { - /// A new command buffer of `root`, on its place `queue`, holding `slot` of it. - pub(super) fn new(queue: &QueueGen, root: &CommandQueue, slot: Slot) -> CommandBuffer { - // A state a released command buffer left, reset (`spare_states.rs`). - let shared = queue.device().shared(); - let KeptState { - state, revision, .. - } = shared.spare_states.take().unwrap_or_else(|| { - shared.counts.command_buffer_state_made(); - KeptState::fresh() - }); - CommandBuffer(Arc::new(CommandBufferShared { - id: ObjectId::new(), - generation: Arc::clone(queue.device().shared_arc()), - device: queue.device().clone(), - queue: queue.clone(), - // Counted before its handle is taken, as its handle goes before its count: the count - // reads one fewer of the program's handles for a moment, never one more. - #[cfg(test)] - _counted: crate::queue::CountedCommandBuffer::new(root), - root: root.clone(), - state, - slot: Mutex::new(Some(slot)), - changed: Condvar::new(), - gate: Arc::default(), - relayed: Arc::default(), - step_trail: Mutex::new(None), - step_numbers: OnceLock::new(), - making_deadline: OnceLock::new(), - unmade: Mutex::new(Vec::new()), - own_textures: Mutex::new(Vec::new()), - fill_slot: Mutex::new([0; 16]), - merge_scratch: Arc::default(), - reencode: AtomicU64::new(0), - reencoding: Mutex::new(()), - stepping: AtomicU64::new(NOT_STEPPING), - dirty: Mutex::new(DirtyCommit::default()), - at_completion: Mutex::new(Vec::new()), - unnoted: AtomicBool::new(false), - raws_ended: AtomicU64::new(0), - recorded: AtomicU64::new(0), - kernel: KernelTimes::default(), - status: AtomicU8::new(status_word(CommandBufferStatus::NotEnqueued)), - error: OnceLock::new(), - group_hold: AtomicU8::new(0), - fresh: FreshLog::default(), - footprints: Footprints { - revision, - kept: Mutex::new(Vec::new()), - }, - })) - } - - /// `device`. - pub fn device(&self) -> &Device { - &self.0.device - } - - /// The command buffer's ID: a runtime extension, no Metal property. Metal names a command - /// buffer by its pointer, which another object may take once it is freed. This number is one - /// of the process's object IDs (as a buffer's, texture's or heap's, never another object's), - /// the command buffer's for its whole life (a clone is the same command buffer): what a degrade - /// notice announced for its work names ([`DegradeNotice::command_buffer`]), so a program can - /// fail the one command buffer a notice was about. - /// - /// [`DegradeNotice::command_buffer`]: crate::DegradeNotice::command_buffer - pub fn object_id(&self) -> ObjectId { - self.0.id - } - - /// This thread doing the command buffer's work until the guard goes: the notices announced - /// meanwhile name it ([`NoticesFor`]). - pub(crate) fn notices_for(&self) -> NoticesFor { - self.0.notices_for() - } - - /// Do `work` at the command buffer's completion, before anything sees it complete - /// (`managed_copy.rs`, `completion.rs`); dropped undone where it never completes. - pub(crate) fn at_completion(&self, work: AtCompletion) { - lock(&self.0.at_completion).push(work); - } - - /// The state of the generation of its device it was made on, its device's - /// ([`CommandBufferShared::generation`]): what its encoders' commands reach, at one load. - #[inline] - pub(crate) fn generation(&self) -> &DeviceShared { - &self.0.generation - } - - /// The color fill slot (`fill_slot`), after a color fill packed `packed` (`None` for one - /// that packs nothing): its first bytes become the texel's. - pub(super) fn fill_slot(&self, packed: Option<&[u8]>) -> [u8; 16] { - let mut slot = lock(&self.0.fill_slot); - if let Some(texel) = packed { - let n = texel.len().min(slot.len()); - slot[..n].copy_from_slice(&texel[..n]); - } - *slot - } - - /// Hold `texture`, which one of its encoders made for its own commands, as its - /// `own_textures` says. - pub(super) fn hold_own_texture(&self, texture: Texture) { - lock(&self.0.own_textures).push(texture); - } - - /// Hold `texture`, one of the runtime's that another command buffer made and one of its - /// encoders' commands use (`Texture::snapshot_texels`), as `own_textures` holds those its - /// encoders made, once. - pub(super) fn hold_used_texture(&self, texture: &Texture) { - let mut own = lock(&self.0.own_textures); - if !(own.iter()).any(|held| held.address() == texture.address()) { - own.push(texture.clone()); - } - } - - /// The pool of the scratch its merges are done with (`merge_scratch.rs`). - pub(super) fn merge_scratch(&self) -> &Arc { - &self.0.merge_scratch - } - - /// `commandQueue`. - pub fn command_queue(&self) -> &CommandQueue { - &self.0.root - } - - /// Submit `raws`, ended, in order, on its `VkQueue` with a fence, for the host to wait for - /// later ([`wait_fenced`](Self::wait_fenced)): a host step's own submission, a part of its - /// probe of a rate-mapped pass's draws (`render/executions.rs`, - /// `DeferredPass::probe_parts`), as a predicated loop's run again is (`rerun.rs`), `what` - /// naming it for the encoder trail (`encoder_trail.rs`). `None` where the process is exiting, - /// with nothing submitted. - /// - /// # Safety - /// - /// Each of `raws` is a command buffer of its pool, ended, in no pending submission, and - /// recorded for this submission alone; what it uses lives until it completed, which a wait - /// for it sees. - pub(crate) unsafe fn submit_fenced( - &self, - raws: &[vk::CommandBuffer], - what: &str, - ) -> Result, Error> { - // SAFETY: the caller's. - match unsafe { rerun::submit_fenced(&self.0, raws, what) } { - Ok(fenced) => Ok(Some(fenced)), - Err(rerun::Waited::Failed(error)) => Err(self.device().failed(error)), - Err(_) => Ok(None), - } - } - - /// Wait for every submission of `fenced` ([`submit_fenced`](Self::submit_fenced)'s) to - /// complete, `what` naming them for the encoder trail: whether they completed, `false` where - /// the driver relayed a failure for them, which fails the command buffer at its completion, - /// or the process is exiting. - pub(crate) fn wait_fenced(&self, fenced: &[rerun::Fenced], what: &str) -> Result { - match rerun::wait_fenced(&self.0, fenced, what) { - rerun::Waited::Completed => Ok(true), - rerun::Waited::Relayed | rerun::Waited::Exiting => Ok(false), - rerun::Waited::Failed(error) => Err(self.device().failed(error)), - } - } - - /// Run `made`, a segment's recording at `commit`, and return what it made and the GPU forms - /// it took, where the device's encoder trail is on (`encoder_trail.rs`, **GPU forms**): it - /// notes as a host step does, and `commit` keeps the forms alone. - fn noting_forms( - &self, - made: impl FnOnce() -> T, - ) -> (T, Vec>) { - if !self.device().shared().encoder_trail { - return (made(), Vec::new()); - } - *lock(&self.0.step_trail) = Some(crate::encoder_trail::Step::new(None)); - let made = made(); - let step = lock(&self.0.step_trail).take(); - ( - made, - step.map(crate::encoder_trail::Step::into_forms) - .unwrap_or_default(), - ) - } - - /// The text of each GPU form its encoders' parts took, as the encoder trail reads it now - /// (`encoder_trail.rs`, **GPU forms**): a device test's view. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn trail_form_texts(&self) -> Vec { - (self.state().recorded.iter()) - .filter_map(|part| part.trail.as_ref()) - .flat_map(crate::encoder_trail::Named::forms) - .collect() - } - - /// Note, for the encoder trail, the states of `notes` that its host step under way read its - /// commands to name (`encoder_trail.rs`, **Host steps**), or that `commit`'s recording of a - /// segment noted (`noting_forms`); nothing outside either. - pub(crate) fn trail_step(&self, notes: crate::encoder_trail::Notes) { - if let Some(step) = lock(&self.0.step_trail).as_mut() { - step.noted(notes); - } - } - - /// Its queue's place on the generation it was made on, which its commands' pools and kept - /// images are of (`queue.rs`). - pub(crate) fn queue_place(&self) -> &QueueGen { - &self.0.queue - } - - /// The log its commit takes of its commands' reads and writes of new textures' unwritten - /// patterns (`fresh_unwritten.rs`). - pub(crate) fn fresh_log(&self) -> &FreshLog { - &self.0.fresh - } - - /// The state, locked: a lock its encoders on other threads share (counted, in builds with - /// debug assertions: `state_locks`). - pub(super) fn state(&self) -> MutexGuard<'_, State> { - #[cfg(debug_assertions)] - STATE_LOCKS.with(|locks| locks.set(locks.get() + 1)); - lock(&self.0.state) - } - - /// Note a command's `uses` for the device's logs of host pages, where it keeps any - /// (`dirty_pages.rs`): its writes let go, at the commit, of the holds of the shadows they meet, - /// and those into logged pages imported in place are reported to their logs; and for its - /// copied host buffers, where any lives, whose merges back compare those its writes reach - /// (`copied.rs`). - pub(super) fn note_dirty(&self, uses: &[Use]) { - let shared = self.generation(); - match shared.dirty.collects() || shared.copied.any() { - true => lock(&self.0.dirty).note(uses, &shared.dirty), - false => self.0.unnoted.store(true, Ordering::Relaxed), - } - } - - /// Whether a command's uses went unnoted ([`note_dirty`](Self::note_dirty)), nothing - /// collecting them then. - pub(super) fn uses_unnoted(&self) -> bool { - self.0.unnoted.load(Ordering::Relaxed) - } - - /// What its commands did so far that the device's logs of host pages hear of at its commit. - pub(super) fn dirty(&self) -> MutexGuard<'_, DirtyCommit> { - lock(&self.0.dirty) - } - - /// Whether a buffer over host pages a command of its ended encoder at `encoder` named lies - /// elsewhere now than the command took it (`Rebinds::rebound_now`): a rebind since its commit - /// that no encoding again reached. The submission holding that encoder runs nothing and the - /// command buffer fails `CommandBufferError::EncodedUseRebound` (`first_submission.rs`), so - /// work of the encoder a host step records resolved as it was encoded records nothing - /// (`pending_dispatch.rs`): the descriptors it would record name a `VkBuffer` the rebind - /// freed. Read without the state's lock held, as the lock each submission reads it under is - /// taken inside this one. - pub(super) fn encoder_rebound(&self, encoder: usize) -> bool { - let rebinds = &self.0.device.shared().rebinds; - if !rebinds.any() { - return false; - } - let state = self.state(); - let Some(record) = state.ended.get(encoder) else { - return false; - }; - rebinds.rebound_now(&record.taken) - } - - /// This command buffer as the device's commits that wait hold it ([`Waiting`]). - pub(crate) fn waiting(self) -> Arc { - self.0 - } - - /// Fail the work of its next `count` commits (not one run again with nothing of it run), as - /// out of memory: a device test's injection (`tests::deferred_calls`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn fail_commit_work(&self, count: u32) { - self.state().failures_injected = count; - } - - /// Answer the making of the next draw's pipeline its recording waits for - /// (`render/pending.rs`) with `error`, as the driver's failure: a device test's injection - /// (`tests::deferred_calls`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn fail_draw_making(&self, error: Error) { - self.state().making_failure_injected = Some(error); - } - - /// Answer its next host step's recording with `error`, as a failure of that recording's: a - /// device test's injection (`tests::tiled_texture_step`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn fail_host_step(&self, error: Error) { - self.state().step_failure_injected = Some(error); - } - - /// Relay the device's loss to it, as the relay does to every batch in flight where it cannot - /// read which one failed (`device/relay.rs`): a device test's injection - /// (`tests::device_recovery`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn relay_loss(&self) { - self.0.relayed.lost(); - } - - /// Its state, locked, as a host step's draw or a commit's work holds it: a device test's - /// (`tests::footprint_locks`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn locked_state(&self) -> MutexGuard<'_, State> { - lock(&self.0.state) - } - - /// Which state it holds, by its address, and the room its lists of records hold, in bytes - /// (`spare_states.rs`): a device test's (`tests::spare_states`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn held_state(&self) -> (usize, usize) { - let room = lock(&self.0.state).lists_room(); - (Arc::as_ptr(&self.0.state) as usize, room.bytes()) - } - - /// Whether another thread holds its state's lock now, as a submission of its batch holds it - /// through `vkQueueSubmit` (`submit.rs`): a device test's (`tests::scheduler_wakes`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn state_held(&self) -> bool { - matches!(self.0.state.try_lock(), Err(TryLockError::WouldBlock)) - } - - /// Batch `index`'s footprint as the scheduler asks for it - /// ([`CommandBufferShared::footprint`]): a device test's (`tests::footprint_locks`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn footprint(&self, index: usize) -> Option>> { - self.0.footprint(index) - } - - /// Whether the device's scheduler began submitting its first batch, noted before the driver's - /// submission is called, where `kernel_start_time` shows 0 until its kernel end is known, - /// after that call returned: a device test's (`tests::queue_share_device`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn submission_began(&self) -> bool { - self.0.kernel.start() != 0 - } - - /// A weak reference to the work of each segment its ended encoders left and its batches' - /// submissions have not placed yet, in encoding order: a device test's view of what still - /// holds that work (`tests::host_ram_copy_device`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn segment_works(&self) -> Vec> { - (self.state().recorded.iter()) - .flat_map(|part| &part.segments) - .map(|segment| segment.work.weak()) - .collect() - } - - /// How many segments the batches' kept footprints probe ([`Footprints`]): a device test's - /// view (`tests::host_ram_copy_device`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn kept_footprint_probes(&self) -> usize { - (lock(&self.0.footprints.kept).iter()) - .flatten() - .map(|built| built.probes.len()) - .sum() - } - - /// The bytes its upload arena's regions took: a device test's measure (`tests::rerun_arenas`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn upload_bytes(&self) -> u64 { - self.state().uploads.bytes() - } - - /// Give its command pool back to the device's spares now, whatever its work's state, as a - /// command buffer that never completed would: a device test's deliberate early give-back, - /// which the device's pending audit finds (`tests::pending_audit_device`). Whether it held - /// one. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn give_pool_back_early(&self) -> bool { - let pools = self.state().pools(); - let shared = self.0.device.shared(); - let held = !pools.is_empty(); - let recorded = self.0.recorded.load(Ordering::Relaxed); - for pool in pools { - shared - .spares - .give_command_pool(shared, pool, false, recorded); - } - held - } - - /// Whether `waiting` holds this command buffer. - pub(crate) fn is(&self, waiting: &dyn Waiting) -> bool { - self.0.address() == waiting.address() - } - - /// Where a render pass opening now opens, for its textures' turns (`render/face_swap.rs`). - pub(crate) fn turn_point(&self) -> TurnPoint { - let state = self.state(); - TurnPoint { - owner: self.0.address(), - part: state.recorded.len(), - bound_heaps: state.heaps.may_bind(), - } - } - - /// A handle that does not keep the command buffer: a render encoder's, which its end in - /// flight hands the command buffer (`render/deferral.rs`), so that hold makes no cycle. - pub(crate) fn downgrade(&self) -> WeakCommandBuffer { - WeakCommandBuffer(Arc::downgrade(&self.0)) - } - - /// A handle that tells whether it completed, holding nothing else of it. - pub(crate) fn finished(&self) -> Finished { - Finished(Arc::clone(&self.0.gate)) - } - - /// Hold `ending`, the open render encoder's end, which its call left to the device's - /// lowering thread, until what follows it in the command buffer lowers it - /// ([`settle_end`](Self::settle_end)). - pub(crate) fn hold_end(&self, ending: EndInFlight) { - let mut state = self.state(); - let held = state.ending.replace(ending); - debug_assert!(held.is_none(), "two render encoders' ends in flight"); - state.end_lowered = false; - } - - /// The render encoder's end the command buffer holds was lowered (`render/deferral.rs`), on - /// the device's lowering thread (`by_thread`) or the program's: a commit whose own work - /// waited for it runs now, on this thread, with those ready behind it - /// (`render/queued_commits.rs`). Then this handle goes, off the lowering thread where it is - /// the last ([`let_go_off_thread`](Self::let_go_off_thread)). - pub(crate) fn end_lowered(self, by_thread: bool) { - let queued = { - let mut state = self.state(); - state.end_lowered = true; - state.queued_commit.is_some() - }; - let commits = self.0.device.shared().deferred.commits(); - if let Some(commits) = commits.filter(|commits| queued && commits.ready(&self)) { - commits.run(by_thread); - } - if by_thread { - self.let_go_off_thread(); - } - } - - /// Let go of this handle on the device's lowering thread, which has just lowered a render - /// encoder's end (`render/deferral.rs`): where it is the command buffer's last, the command - /// buffer goes on one of the device's handler threads (`Device::let_go_elsewhere`), as it would - /// go on the program's thread that let go of it last, since its drop gives the encoder's slot - /// back, whose logged calls may hold the program's objects' last handles. - pub(crate) fn let_go_off_thread(self) { - let device = self.0.device.clone(); - if let Some(shared) = Arc::into_inner(self.0) { - device.let_go_elsewhere(Box::new(shared)); - } - } - - /// Lower, on this thread, the end of the render encoder that ended last, where its call - /// left it to the device's lowering thread and the thread has not lowered it (with whatever - /// of its calls the thread has not lowered): first in each call that follows an encoder's end - /// in the command buffer (another encoder's opening, an event or a semaphore, the commit, a - /// read of what its encoders left), as if the end had been lowered inside its call. - /// - /// A kept draw the last render encoder carried for the next is let go (`render/carried.rs`), - /// counted as one another call came before (`WorkCounts::kept_draws_carry_dropped_between`), - /// and so is the end of one that kept none (`WorkCounts::encoders_none_kept_next_between`). - pub(crate) fn settle_end(&self) { - self.settle_ended(); - self.let_go_carried(CarryDropped::Between); - self.count_none_kept(NoneKeptNext::Between); - } - - /// `state`, its state locked, as [`settle_end`](Self::settle_end) leaves it: where the last - /// render encoder's end waits, or it carried a kept draw or held an end that kept none, the - /// lock is let go of, the end settled, and the lock taken again; else nothing is, and the - /// lock is the one taken (an encoder's opening after a compute or blit encoder). - pub(crate) fn settled<'a>(&'a self, state: MutexGuard<'a, State>) -> MutexGuard<'a, State> { - if state.ending.is_none() && state.carried.is_none() && state.none_kept.is_none() { - return state; - } - drop(state); - self.settle_end(); - self.state() - } - - /// [`settle_end`](Self::settle_end) at a commit: a kept draw carried goes to the queue, for a - /// later command buffer's render encoder, and the one the queue held longest, which none took, - /// is let go where it held its most (`render/carried.rs`, `queue::CARRIES`, - /// `WorkCounts::kept_draws_carry_dropped_commit`). - fn settle_end_committing(&self) { - commit_times::phase(Phase::Lowering, || { - self.settle_ended(); - self.count_none_kept(NoneKeptNext::Last); - let carried = self.state().carried.take(); - let earlier = carried.and_then(|carried| self.0.queue.hold_carried(carried.across())); - if let Some(earlier) = earlier { - let counts = &self.0.device.shared().counts; - counts.kept_draw_carry_dropped(CarryDropped::Commit); - earlier.let_go(&self.0.device); - } - }); - } - - /// [`settle_end`](Self::settle_end), but a kept draw the last render encoder carried stays - /// (`render/carried.rs`): for a render encoder's opening, which takes it, and a read of what - /// the encoders left, which records nothing between them. - pub(crate) fn settle_ended(&self) { - let ending = self.state().ending.take(); - if let Some(ending) = ending { - ending.finish(); - } - } - - /// The kept draw the last render encoder carried for the next, taken (`render/carried.rs`). - pub(crate) fn take_carried(&self) -> Option> { - self.state().carried.take() - } - - /// The latest of the kept draws its queue holds from command buffers committed on it that - /// `fits` tells fits a render encoder's pass, taken (`render/carried.rs`). - pub(crate) fn take_queue_carried( - &self, - fits: impl FnMut(&Carried) -> bool, - ) -> Option> { - self.0.queue.take_carried(fits) - } - - /// The end of the last render encoder where it kept no draw, taken (`render/carried.rs`). - pub(crate) fn take_none_kept(&self) -> Option> { - self.state().none_kept.take() - } - - /// Hold `none_kept`, the end of a render encoder ending that kept no draw, for the next - /// render encoder's opening (`render/carried.rs`). - pub(crate) fn hold_none_kept(&self, none_kept: Box) { - self.state().none_kept = Some(none_kept); - } - - /// Count the end of the last render encoder where it kept no draw, where it holds one, as - /// `next` says, and let it go (`render/carried.rs`). - fn count_none_kept(&self, next: NoneKeptNext) { - let none_kept = self.state().none_kept.take(); - if none_kept.is_some() { - self.0.device.shared().counts.encoder_none_kept_next(next); - } - } - - /// Hold `carried`, the kept draw of a render encoder ending, for the next render encoder - /// (`render/carried.rs`). - pub(crate) fn carry(&self, carried: Box) { - let earlier = self.state().carried.replace(carried); - // None is held: the opening of the encoder ending took the one before. - if let Some(earlier) = earlier { - earlier.let_go(&self.0.device); - } - } - - /// Let go of the kept draw the last render encoder carried, where it holds one, to the - /// device's spares, counted as `why` says (`render/carried.rs`). - fn let_go_carried(&self, why: CarryDropped) { - let carried = self.state().carried.take(); - if let Some(carried) = carried { - self.0.device.shared().counts.kept_draw_carry_dropped(why); - carried.let_go(&self.0.device); - } - } - - /// The residency a new compute or render (`render`) encoder starts with - /// (`Residency::shadows`): the shadowed textures its ended encoders made resident, those in - /// the heaps they used made since included. - pub(super) fn inherited_residency(&self, render: bool) -> Residency { - let counts = &self.0.device.shared().counts; - self.state().inheriting(render, counts) - } - - /// What its ended encoders made resident, every encoder's joined (`residency.rs`): what the - /// work its commit and host steps record resolves and binds against. - pub(super) fn residency(&self) -> Result { - let counts = &self.0.device.shared().counts; - let residency = (self.state().joined_residency(counts).cloned()).unwrap_or_default(); - // With the device's live buffers, which an address in no resource made resident - // resolves against (`live_buffers.rs`): a host step's, the command buffer holds until it - // completes. - let device = &self.0.device; - let live = device.shared().live_buffers.table(device)?; - self.state().keep_stepped_table(&live); - Ok(residency.with_live(live)) - } - - /// The queue family of its queue's `VkQueue`. - pub(super) fn queue_family(&self) -> u32 { - let shared = self.0.device.shared(); - shared.queue_family_of(self.0.queue.vk_queue()) - } - - /// The reads a global memory barrier recorded for its queue's `VkQueue` names in its - /// destination: those of that queue's family (`image_barrier::MemoryReads`), a copy engine's - /// transfers alone on a queue made for copies (`Device::new_command_queue_for_copies`). - pub(crate) fn memory_reads(&self) -> crate::image_barrier::MemoryReads { - let shared = self.0.device.shared(); - shared.memory_reads_of(self.0.queue.vk_queue()) - } - - /// Refuse `call` with `problem` where its queue was made for copies - /// (`Device::new_command_queue_for_copies`): its commands run on a queue family of transfers - /// alone (`Invalid`, `Problem::CopyQueue`). - pub(crate) fn refuse_for_copies( - &self, - call: &'static str, - problem: crate::error::CopyQueueProblem, - ) -> Result<(), Error> { - match self.0.queue.for_copies() { - true => Err(invalid(call, Problem::CopyQueue(problem))), - false => Ok(()), - } - } - - /// Whether its queue was made for copies (`Device::new_command_queue_for_copies`). - pub(crate) fn for_copies(&self) -> bool { - self.0.queue.for_copies() - } - - /// Lend `context` to the command buffer while the commit records a chunk to keep - /// (`State::kept`), its arenas taking every set and upload meanwhile; `None`: take back the - /// one lent, each `VkCommandBuffer` it handed out meanwhile ended there and counted as ended - /// among the command buffer's own (`CommandBufferShared::end_raw`), which no longer counts it. - pub(super) fn lend_kept(&self, context: Option<&Arc>) { - let mut state = self.state(); - state - .uploads - .lend(context.map(|context| Arc::clone(&context.uploads))); - state - .descriptors - .lend(context.map(|context| Arc::clone(&context.descriptors))); - let lent = match context { - Some(context) => state - .kept - .replace((Arc::clone(context), context.handed_out())), - None => state.kept.take(), - }; - if let (None, Some((context, handed))) = (context, lent) { - let ended = context.handed_out().saturating_sub(handed) as u64; - self.0.raws_ended.fetch_sub(ended, Ordering::Relaxed); - } - } - - /// How many times a command reached what the command buffer alone holds for its commands - /// (`State::own_reached`). - pub(super) fn own_reached(&self) -> u64 { - self.state().own_reached - } - - /// An encoder's primary command buffer, from this command buffer's pool, made on first use: - /// the encoder records into it at each call, on the program's thread. The caller holds - /// `state` (the pool is externally synchronized). - #[cfg_attr(test, track_caller)] - pub(super) fn allocate_raw(&self, state: &mut State) -> Result { - self.0 - .allocate_encoder(state, vk::CommandBufferLevel::PRIMARY) - } - - /// An encoder's own primary `VkCommandBuffer` from this command buffer's pool, and whether it - /// is begun: one of the pool's primaries begun ahead where it holds any (`spares.rs`), else as - /// [`allocate_raw`](Self::allocate_raw) hands one out, to begin. The caller holds `state`. - pub(super) fn encoder_primary( - &self, - state: &mut State, - ) -> Result<(vk::CommandBuffer, bool), Error> { - self.0.encoder_primary(state) - } - - /// Write the start into `raw`, the first encoder's first `VkCommandBuffer`, just begun, where - /// the command buffer is timed and the encoder opens its first batch (`gpu_time.rs`). - pub(super) fn open_start(&self, state: &mut State, raw: vk::CommandBuffer) { - self.0.open_start(state, raw); - } - - /// End `raw`, a `VkCommandBuffer` of this command buffer's pool, counted among those its - /// recordings ended: every `vkEndCommandBuffer` of one goes through here - /// (`CommandBufferShared::end_raw`). - /// - /// # Safety - /// `raw` is recording, and only the caller records it, or any command buffer of its pool: - /// Vulkan synchronizes both externally. - pub(super) unsafe fn end_raw(&self, raw: vk::CommandBuffer) -> Result<(), vk::Result> { - // SAFETY: the caller's. - unsafe { self.0.end_raw(raw) } - } - - /// `commands` more recorded into its pools' `VkCommandBuffer`s: draws, a rate-mapped pass's - /// region by region, and the state commands they set (`render.rs`). What a command buffer's - /// recording takes of its driver's device-wide pools stays taken until it is begun again, - /// reset or freed, so its pools free their command buffers as they go back where these - /// reach `spares::RECORDED` (`spares.rs`). - pub(super) fn recorded(&self, commands: u64) { - self.0.recorded.fetch_add(commands, Ordering::Relaxed); - } - - /// Give up `raw`, a secondary command buffer recording that nothing will execute (a render - /// pass instance its pass replaced or gave up before running it, or the one instance of a - /// pass that changes nothing): it ends ([`end_raw`](Self::end_raw)), so its pool goes back - /// to the device's spares unreset (`spares.rs`). Nothing executes it, so the GPU does the - /// same work and every byte it writes is the same. - /// - /// # Safety - /// As [`end_raw`](Self::end_raw)'s, and no command buffer executes `raw`. - pub(super) unsafe fn give_up_raw(&self, raw: vk::CommandBuffer) -> Result<(), vk::Result> { - // SAFETY: the caller's. - unsafe { self.end_raw(raw) } - } - - /// A secondary command buffer (a render encoder's draws), from this command buffer's pool as - /// [`allocate_raw`](Self::allocate_raw)'s. The caller holds `state`. - pub(super) fn allocate_secondary(&self, state: &mut State) -> Result { - self.0 - .allocate_encoder(state, vk::CommandBufferLevel::SECONDARY) - } - - /// `addScheduledHandler:`: call `handler` once the command buffer is scheduled, on one of the - /// device's handler threads, at the user-interactive class on macOS as in Metal, and with a - /// utilization floor on Linux ([`Handler`]). Refused once the command buffer is committed. - pub fn add_scheduled_handler(&self, handler: Handler) -> Result<(), Error> { - let mut state = self.state(); - if state.enqueued() { - return Err(invalid( - "add_scheduled_handler", - Problem::HandlerAfterCommit, - )); - } - state.scheduled.push_back(handler); - Ok(()) - } - - /// Call `handler` once the runtime took the command buffer's last batch for its `VkQueue`, - /// on the thread that took it, before the command buffer becomes `Scheduled`: a runtime - /// extension, no Metal call (the crate's README, "Runtime extensions"). The batch is taken - /// where it is submitted, or held for one kernel submission with the batches - /// committed after it (`CompletionPolicy::Grouped`, on a driver that merges submissions): its - /// commands and its place in its queue's order are fixed then, so nothing committed later on - /// the queue runs before it. Metal submits on its own thread and tells a program of it only - /// through `Scheduled`; a program that models what Metal does as it - /// submits takes that point here. A command buffer whose GPU hangs (a draw of primitive type - /// 9, `hang.rs`) runs them as it becomes `Scheduled` before its last batch, which the hang - /// holds: once the batch before the hang is taken and Metal's time to read `Scheduled` came. - /// So does one whose remaining batches wait only for its queue's host step behind work - /// already submitted, every earlier command buffer of its queue `Scheduled` - /// (`scheduler/mod.rs`, **Scheduled**): Metal's dependencies are resolved there, and its - /// commands and place are fixed; the step records them later. - /// - /// - **The thread.** Where its own [`commit_and_submit`](Self::commit_and_submit) call took - /// its last batch: that call's thread, inside the call. Otherwise one of the device's - /// handler threads, those that run its scheduled and completed handlers: the device's - /// scheduler thread, which takes the batches `commit` leaves it (`commit` returns at once, - /// as Metal's does, and submits nothing itself), and a later `commit_and_submit` call whose - /// pass takes the last batch, hand the handlers there once the batch is taken, before they - /// look for the next one, and go on submitting. Two cases run them elsewhere: where that thread's pass settled a switch of a - /// fetched target's storage form before it took the batch, the scheduler thread itself, once - /// the switch ended (`texture/storage_form.rs`); and behind a GPU hang, the hang's own thread - /// where the time came after the batch was taken. Whichever it is, the handlers of every - /// command buffer run in submission order, with no lock of the runtime's held, after the - /// submission's call returned. A thread about to block for a command buffer's completion - /// submits what still waits in the scheduler's inbox itself, but never a batch of a command - /// buffer with a handler of any kind, which stays the scheduler thread's to submit: no - /// handler of the program's ever runs on a thread blocking in - /// [`wait_until_completed`](Self::wait_until_completed). - /// - **Before.** Its handlers run, in the order added, before the status reads `Scheduled`, - /// before [`wait_until_scheduled`](Self::wait_until_scheduled) returns, before its - /// scheduled handlers run, and before it can complete. The GPU may run the work meanwhile: - /// a value of an event its work signals can rise before they ran. - /// - **Never** for a command buffer that fails before its last batch is taken (a submission - /// or host step that fails, a lost device); they are dropped with it. One whose last batch - /// was held ran them, and fails from `Scheduled` where the group's submission fails; so - /// does one made `Scheduled` behind a host step, where a later batch of it fails. A - /// command buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its - /// batches and runs them. - /// - **Keep it short.** It holds back its command buffer's scheduling, and the submission - /// handlers and scheduling of every command buffer submitted after it. Inside its - /// `commit_and_submit` call, or on the scheduler thread (the storage-form case above), it - /// holds back the device's other submissions too, among them those of a commit made - /// meanwhile, which that thread takes in only after its handlers (`scheduler/inbox.rs`); on - /// a handler thread it holds back no submission. A wait in it - /// for a command buffer, or for a slot of a full queue, that has not happened yet is refused - /// (`WaitWouldDeadlock` of [`DeadlockCause::SubmissionHandler`]); it must not wait for GPU - /// work otherwise. What the runtime took before it runs is never held back by it for - /// another command queue: batches held for one kernel submission go to the driver before - /// the scheduler thread runs a handler of a command buffer of another queue than theirs, as - /// Metal schedules a queue's command buffers whatever another queue's handler does; and a - /// command buffer taken with no submission (it needs no GPU work) whose `VkQueue` has no - /// work in flight has its completion turn made before the thread that took it runs a - /// handler, so its completion never waits for one. Those of its own queue may wait for it, - /// as Metal runs one queue's handlers one at a time. - /// - /// Refused once the command buffer is committed (`Invalid`, `Problem::HandlerAfterCommit`), - /// as [`add_scheduled_handler`](Self::add_scheduled_handler) is. - pub fn add_submission_handler(&self, handler: Handler) -> Result<(), Error> { - let mut state = self.state(); - if state.enqueued() { - return Err(invalid( - "add_submission_handler", - Problem::HandlerAfterCommit, - )); - } - state.submission.push_back(handler); - Ok(()) - } - - /// `encodeSignalEvent:value:`: once the work encoded before it completed, the event's value - /// becomes at least `value`. Refused while an encoder is open (Metal asserts), after commit, - /// after an abandoned encoder, and for another device's event. - pub fn encode_signal_event(&self, event: EventRef<'_>, value: u64) -> Result<(), Error> { - self.event_command("encode_signal_event", event, |batches, event| { - batches.signal(event, value); - }) - } - - /// `encodeSignalEventScheduled:value:`, private: once the command buffer is scheduled, the - /// event's value becomes at least `value`, set as [`SharedEvent::set_signaled_value`] sets it: - /// before its status reads `Scheduled`, before any of its scheduled handlers runs (one added - /// before this call too) and before [`wait_until_scheduled`](Self::wait_until_scheduled) - /// returns, as Metal's (an M3 Max, macOS 27.0.1); several in the order encoded. No handler - /// thread is woken for it: a command buffer whose transition to `Scheduled` has nothing else - /// to run makes it on the thread that submitted its last batch. One that fails before it is - /// scheduled sets nothing, as it runs no scheduled handler. - /// - /// Called once the command buffer is committed and before it completed, it does nothing, as - /// Metal's (measured before and after the command buffer was scheduled). Refused once it - /// completed or failed (`Invalid`, `Problem::ScheduledSignalAfterCompletion`), where Metal's - /// process ends; while an encoder is open (Metal asserts), after an abandoned encoder, and for another - /// device's event, as [`encode_signal_event`](Self::encode_signal_event) is. Metal ends the - /// process for an `MTLEvent`, which this call does not take. - pub fn encode_signal_event_scheduled( - &self, - event: &SharedEvent, - value: u64, - ) -> Result<(), Error> { - const CALL: &str = "encode_signal_event_scheduled"; - let event = EventRef::Shared(event); - let event = event.shared(); - if !event.device().same(&self.0.device) { - return Err(event.device().foreign(CALL, &self.0.device)); - } - self.settle_end(); - let mut state = self.state(); - match state.refusal() { - None => state.scheduled_signals.push((Arc::clone(event), value)), - Some(Problem::AlreadyCommitted) - if matches!( - state.status, - CommandBufferStatus::Completed | CommandBufferStatus::Error - ) => - { - return Err(invalid(CALL, Problem::ScheduledSignalAfterCompletion)) - } - Some(Problem::AlreadyCommitted) => {} - Some(problem) => return Err(invalid(CALL, problem)), - } - Ok(()) - } - - /// `encodeWaitForEvent:value:`: the work encoded after it starts once the event's value - /// reached `value`. Refused as [`CommandBuffer::encode_signal_event`] is. - pub fn encode_wait_for_event(&self, event: EventRef<'_>, value: u64) -> Result<(), Error> { - self.event_command("encode_wait_for_event", event, |batches, event| { - batches.wait(event, value); - }) - .inspect(|()| self.state().shadows_not_carried()) - } - - /// Wait for the caller's binary semaphore `semaphore` before the work encoded after it: the - /// acquire of a swapchain image, or a signal of the caller's own submission. It splits the - /// command buffer's batches as [`encode_wait_for_event`](Self::encode_wait_for_event) does, and - /// the batch waits in all its stages. The device's scheduler submits the batch in its order: - /// never before the signals of `semaphore` that command buffers of this device committed before - /// this one are submitted. - /// - /// Refused as [`encode_signal_event`](Self::encode_signal_event) is (an encoder open, after - /// commit, after an abandoned encoder), and for what the runtime can tell is no binary - /// semaphore of the device: a null handle, or one of its own timeline semaphores (`Invalid` - /// with a [`SemaphoreProblem`](super::SemaphoreProblem)). - /// - /// # Safety - /// - /// - `semaphore` is a binary semaphore of this device, and lives until the command buffer - /// completed. - /// - The signal this wait consumes was submitted to the device before `commit` (by the - /// caller: `vkAcquireNextImageKHR`, or its own `vkQueueSubmit`), or is the last one an - /// [`encode_signal_vk_semaphore`](Self::encode_signal_vk_semaphore) of a command buffer of - /// this device committed before this one encodes. No other wait consumes it. - pub unsafe fn encode_wait_for_vk_semaphore( - &self, - semaphore: vk::Semaphore, - ) -> Result<(), Error> { - self.binary_command("encode_wait_for_vk_semaphore", semaphore, |batches| { - batches.binary_wait(semaphore); - }) - .inspect(|()| self.state().shadows_not_carried()) - } - - /// Signal the caller's binary semaphore `semaphore` once the work encoded before it - /// completed: the semaphore a present waits for. It closes the batch as - /// [`encode_signal_event`](Self::encode_signal_event) does; a wrapped image the batch uses - /// is back in its home layout before the signal - /// ([`Device::new_texture_with_vk_image`](super::Device::new_texture_with_vk_image)). - /// - /// The signal is submitted with its batch, by the device's scheduler: a wait the caller - /// submits for it (`vkQueuePresentKHR`, its own `vkQueueSubmit`) comes after the command - /// buffer is scheduled ([`wait_until_scheduled`](Self::wait_until_scheduled), or a - /// scheduled handler), which Vulkan requires of a binary semaphore. - /// - /// Refused as [`encode_wait_for_vk_semaphore`](Self::encode_wait_for_vk_semaphore) is. - /// - /// # Safety - /// - /// `semaphore` is a binary semaphore of this device, unsignaled with no signal pending when - /// the batch runs (every earlier signal of it waited for), and lives until the command buffer - /// completed. - pub unsafe fn encode_signal_vk_semaphore(&self, semaphore: vk::Semaphore) -> Result<(), Error> { - self.binary_command("encode_signal_vk_semaphore", semaphore, |batches| { - batches.binary_signal(semaphore); - }) - } - - /// Add a binary semaphore wait or signal to the batches, after the runtime's checks. - fn binary_command( - &self, - call: &'static str, - semaphore: vk::Semaphore, - add: impl FnOnce(&mut Batches, vk::Semaphore>), - ) -> Result<(), Error> { - if let Some(problem) = self.0.device.binary_semaphore_problem(semaphore) { - return Err(invalid(call, Problem::Semaphore(problem))); - } - self.settle_end(); - let mut state = self.state(); - if let Some(problem) = state.refusal() { - return Err(invalid(call, problem)); - } - add(&mut state.batches); - Ok(()) - } - - /// Add an event wait or signal to the batches, after the checks Metal makes. - fn event_command( - &self, - call: &'static str, - event: EventRef<'_>, - add: impl FnOnce(&mut Batches, vk::Semaphore>, Arc), - ) -> Result<(), Error> { - let event = event.shared(); - if !event.device().same(&self.0.device) { - return Err(event.device().foreign(call, &self.0.device)); - } - self.settle_end(); - let mut state = self.state(); - if let Some(problem) = state.refusal() { - return Err(invalid(call, problem)); - } - add(&mut state.batches, Arc::clone(event)); - Ok(()) - } - - /// `addCompletedHandler:`: call `handler` once the command buffer completed or failed, on one - /// of the device's handler threads, at the user-interactive class on macOS as in Metal, and - /// with a utilization floor on Linux ([`Handler`]). Refused once the command buffer is - /// committed. - pub fn add_completed_handler(&self, handler: Handler) -> Result<(), Error> { - let mut state = self.state(); - if state.enqueued() { - return Err(invalid( - "add_completed_handler", - Problem::HandlerAfterCommit, - )); - } - state.completed.push_back(handler); - Ok(()) - } - - /// Call `handler` once the command buffer completed or failed, its status, error and GPU - /// times final, on the runtime's thread that saw it complete, where its transition to - /// `Completed` runs there: a runtime extension, no Metal call (the crate's README, "Runtime - /// extensions"). Metal tells a program of a completion only on its handler threads, a thread - /// wake after the thread that saw it; a program that answers each completion at once (a - /// paravirtualized device's interrupt) takes it here, and a command buffer with such - /// handlers and no completed handler finishes with no handler thread woken. - /// - /// - **The thread.** The queue's waiter that saw the command buffer's work complete; for one - /// that needs no GPU work (nothing it encoded recorded work, and it waits for and signals no - /// event), taken with no submission where its queue had no work in flight, the scheduler's - /// thread that took it. A command buffer with completed handlers too runs these there all - /// the same, its status final, and the rest of its transition, its completed handlers on, - /// goes to its queue's handler thread, where its queue's later transitions wait for it (one - /// wake fewer before these handlers; counted: `WorkCounts::completed_where_seen`). Where its - /// transition to `Completed` runs on its queue's handler thread instead, so do these - /// handlers, at the same point of it: where it has a completed handler and signals at its - /// end an event that another queue's command buffer may wait for (that one completes after - /// it, `follow.rs`), an earlier transition of its queue still runs or waits there (a - /// scheduled or completed handler), or the runtime holds a deallocator of the program's - /// ([`Device::new_buffer_with_bytes_no_copy`](super::Device::new_buffer_with_bytes_no_copy)), - /// which no thread that sees command buffers complete may run (counted: - /// `WorkCounts::completion_seen_handlers_run` and - /// `WorkCounts::completion_seen_handlers_where_seen`). - /// - **Order.** Its handlers run in the order added, once its status reads `Completed` or - /// `Error` and its GPU times are placed, before its completed handlers, before - /// [`wait_until_completed`](Self::wait_until_completed) returns, and before its queue's next - /// command buffer completes: in its queue's commit order, as completed handlers run. - /// - **Keep it short, and never block.** On a queue's waiter it holds back the completion of - /// every queue's command buffers until it returns; on the scheduler's thread, their - /// submission too. A wait in it for what has not happened (a - /// command buffer's scheduling or completion, a slot of a full queue) is refused, wherever it - /// runs (`WaitWouldDeadlock` of [`DeadlockCause::CompletionSeenHandler`]); it must not wait - /// otherwise, nor take a lock that a thread holds while it waits for the device. What it - /// holds goes as it returns, on that thread: no last handle of an object whose release runs - /// the program's code (a no-copy buffer's deallocator). - /// - /// Refused once the command buffer is committed (`Invalid`, `Problem::HandlerAfterCommit`), as - /// [`add_completed_handler`](Self::add_completed_handler) is. - pub fn add_completion_seen_handler(&self, handler: Handler) -> Result<(), Error> { - let mut state = self.state(); - if state.enqueued() { - return Err(invalid( - "add_completion_seen_handler", - Problem::HandlerAfterCommit, - )); - } - state.seen.push_back(handler); - Ok(()) - } - - /// `commit`: hand the batches to the device's scheduler, which submits them in the queue's - /// commit order, each once the events it waits for are reached. It returns at once, as - /// Metal's does: the scheduler's thread makes every submission, so no driver call holds it - /// (`scheduler/inbox.rs`), but the build of a decode kernel of the runtime's own that a - /// carried texture made, viewed or written since the last submission needs, once per device - /// for each decode, before the scheduler's section (`texture/decoded_twin.rs`), which no - /// texture's making builds. - /// - /// The indirect command buffers' commands the encoders execute are recorded first, from - /// their records as they are now: each through the plan path, as a dispatch of the encoder - /// would be. A command such a dispatch would refuse refuses the commit with that error, and - /// nothing is submitted; a command that runs nothing on Metal (no dispatch, an empty or - /// oversized threadgroup) is left out. - /// - /// Refused (and nothing submitted) when the command buffer was committed already, an - /// encoder is open, or an encoder was abandoned (`Invalid`), and as that decode kernel's - /// making is (out of memory, a pipeline the device refuses). A submission the device fails - /// completes the command buffer with that error ([`CommandBuffer::error`]), as Metal reports - /// it on the command buffer. A command buffer that encoded a render pass without attachments - /// past 16384 a side fails from that pass on, as Metal's does - /// ([`CommandBufferError::RenderTargetSize`]): the encoders before it run and the event - /// signals encoded before it fire, and nothing from the pass on runs or signals. One with an - /// encoder Metal's GPU faults fails as Metal's does ([`CommandBufferError::PageFault`]): that - /// encoder runs nothing, and the others run and every signal fires. - /// - /// Under `RenderLoweringPolicy::Worker`, where the device's lowering thread has not lowered - /// the last render encoder's end, or a commit of the device waits for one, it makes the - /// checks above that refuse at the call (committed already, an encoder open, one abandoned) - /// and returns, its status `Committed`: its own work runs - /// once the end is lowered, after the commits that wait, on the thread that lowers it - /// (docs/API.md section 1). A refusal only that work finds (an executed indirect command's, - /// out of memory) fails the command buffer with nothing of it run - /// ([`CommandBufferError::CallRefused`] of `commit`, where no call of it was refused before; - /// [`refusal`](Self::refusal) keeps the error): it completes in its queue's order, its - /// completed handlers run. - pub fn commit(&self) -> Result<(), Error> { - let _clock = CommitClock::start(&self.0.device); - self.commit_as("commit", None, Hand::Wake) - } - - /// Commit the command buffer as [`commit`](Self::commit) does, then submit what is ready on - /// this thread: a runtime extension, no Metal call (the crate's README, "Runtime - /// extensions"). Metal's `commit` returns before its command buffer is scheduled and submits - /// on a thread of its own; the runtime's hands it to its scheduler thread, a wake and a pass - /// away. Here, where no other submission pass is under way, this thread makes it: it submits - /// the device's ready batches in commit order, this one's among them, each needing no host - /// step and no switch of a storage form, up to the pass's bound. A batch of a `VkQueue` whose - /// batches' submissions are slow (its last 15 that submitted command buffers 100 us or more at - /// their median, as timed from each one's start to its `vkQueueSubmit`'s return: a driver that - /// lists every host import in each kernel submission) is left to the scheduler's thread, which submits it while this one goes on - /// (`WorkCounts::scheduler_at_commit_left_slow_calls`). Under - /// `CompletionPolicy::Grouped`, on a driver whose batches may wait in a group for one kernel - /// submission, a batch goes alone where its `VkQueue` runs at most one earlier submission not - /// seen complete (the group would go at once), and is left to the scheduler's thread, which - /// holds it in the group, where two or more run. A batch held back - /// (another queue's, for its checks, an event value or a host step) holds back only the later - /// commits that wait behind it, as on the scheduler's thread: those of its own queue, and - /// another queue's whose resources it uses. What it leaves goes to the scheduler's thread, - /// which it wakes; it wakes that thread too after submitting alone a batch that may wait in a - /// group, as the batch's hand-off to it would have. Where a pass is under way, that pass takes - /// this commit in, as for `commit`. - /// - /// - **Its submission checks run here**, inside this call, for the batches it submits - /// ([`set_submission_check`](Self::set_submission_check)): each just before its batch's - /// submission, with no lock of the runtime's held, in commit order, as the scheduler's thread - /// runs them, and a code one answers fails its submission as there. A batch whose checks - /// wait for a GPU signal to land (an event value only a submitted GPU signal reaches) is the - /// scheduler thread's, which waits for it, and so is what is behind it. They must take no - /// lock the caller holds and wait for no GPU work, as a submission handler. - /// - **Its submission handlers run here**, inside this call, where it submitted this command - /// buffer's last batch: after the submission, with no lock of the runtime's held, in - /// submission order with every other command buffer's - /// ([`add_submission_handler`](Self::add_submission_handler)), before the command buffer - /// reads `Scheduled`. They must take no lock the caller holds and wait for no GPU work, as - /// there. Those of another command buffer whose last batch its pass submits go to the - /// device's handler threads as the pass goes on, as the scheduler thread's passes hand - /// theirs, so none waits for the rest of the pass. Where this command buffer has submission - /// handlers, its pass ends right after its last batch, so they wait for no later batch's - /// submission; what else is ready goes to the scheduler's thread, which it wakes before they - /// run, and which may submit it before or while they run - /// (`WorkCounts::scheduler_passes_at_commit_ended_early`). - /// - **Scheduled.** Where this call submitted its last batch and it has no scheduled and no - /// submission handler, it reads `Scheduled` before this returns, unless its queue's handler - /// thread holds an earlier transition. Otherwise its transition to `Scheduled` runs on its - /// queue's handler thread, after its submission handlers, and its scheduled handlers with - /// it, as for `commit`. - /// - **Called from the runtime's own threads** (a handler run by the scheduler's thread or a - /// queue's waiter), it commits as `commit` does and submits nothing itself. - /// - **Left to wait for a render encoder's end** (`RenderLoweringPolicy::Worker`, an end the - /// device's lowering thread has not lowered yet), it returns once Metal's checks of `commit` - /// are made, as `commit` does, and the thread that runs the commit's own work once the end is - /// lowered makes the pass instead: the lowering thread, or a thread that waits for the - /// command buffer. The submission checks of what that pass submits run on that thread, and - /// this command buffer's submission handlers; other command buffers' go to the device's - /// handler threads. - /// - /// Refused, changing nothing, as [`commit`](Self::commit) is. Counted: - /// `WorkCounts::scheduler_passes_at_commit`, `WorkCounts::batches_submitted_at_commit`, - /// `WorkCounts::batches_checked_at_commit`; timed, phase by phase, as every commit call is: - /// `WorkCounts::commit_nanos` and kin. - pub fn commit_and_submit(&self) -> Result<(), Error> { - let device = &self.0.device; - if exit_guard::serving_completion() { - return self.commit(); - } - let _clock = CommitClock::start(device); - self.commit_as("commit_and_submit", None, Hand::Pass)?; - device.shared().scheduler.submit_at_commit(device, &self.0); - Ok(()) - } - - /// Commit the command buffer as failed with `failure`: a runtime extension, no Metal call - /// (docs/API.md, "A command buffer committed as failed"), for layered validation, error - /// injection and paravirtualization. It fails as Metal's failed command buffers do (measured - /// by a consumer on an M3 Max, macOS 26.7): the encoders `failure.encoders` names run - /// nothing, not even a render pass's load, clear or store actions, and every other encoder - /// runs, before and after them ([`FailedEncoders`]: a GPU hang's suffix, or the set of a - /// failed submission); its event waits hold it as they hold one committed; its event signals - /// fire where `failure.signals` says so, and none fires where not (the caller's binary - /// semaphores are signaled either way); its scheduled handlers run; and it completes in its - /// queue's order, with status `Error` and [`CommandBufferError::Injected`] of - /// `failure.code`, which its completed handlers see. A code of 0 completes it with status - /// `Completed` and no error instead, as Metal completes a command buffer of a queue whose GPU - /// hang is in flight (measured by the consumer on an M3 Max, 11 hangs at a draw of primitive - /// type 9: it runs nothing, its event signals fire and its completed handlers see `Completed` - /// and no error). The indirect command buffers the failing encoders execute are neither - /// recorded nor checked. [`ended_encoders`](Self::ended_encoders) tells the encoders apart: - /// each one's kind, its place among the event waits and signals, and what it uses. A command - /// buffer Metal fails from a render pass on ([`commit`](Self::commit)) fails from there too, - /// whatever `failure` names, and signals no event after the pass; it completes with - /// `failure.code`. Compute encoders recorded into one `VkCommandBuffer` - /// (`WorkCounts::encoders_folded`) that `failure` fails in part are recorded again apart at - /// the commit, so exactly the encoders it names run nothing. Differs: where such a group's - /// unit of command predication laid a loop or left work out, a failure inside the group fails - /// the whole group (docs/API.md, section 10). - /// - /// Refused, changing nothing, as [`commit`](Self::commit) is; and for a set naming an - /// encoder past the ended ones (`Invalid`, `Problem::IndexOutOfRange`, its `limit` the - /// number ended). (A code of 0 was refused, `Problem::UndefinedValue`.) - pub fn commit_failed(&self, failure: CommitFailure) -> Result<(), Error> { - let _clock = CommitClock::start(&self.0.device); - self.commit_as("commit_failed", Some(failure), Hand::Wake) - } - - /// Which of the owners `wanted` answers for (`count` of them: those of the `Managed` buffers - /// whose ranges are noted) its commands may use, for the copies in of those ranges at its - /// commit (`managed.rs`): all where a command may reach memory no use names or its last - /// encoder's end is still with the device's lowering thread (its uses not read yet); else - /// those its encoders' uses name or made resident, as `State::uses` answers for each, its - /// uses read once ([`State::named_among`]). - fn may_use(&self, wanted: &dyn Fn(ObjectId) -> bool, count: usize) -> MayUse { - let shared = self.0.device.shared(); - let state = self.state(); - if state.reaches_unnamed || (state.ending.is_some() && !state.end_lowered) { - return MayUse::All; - } - MayUse::Of(state.named_among(shared, wanted, count)) - } - - /// [`commit`](Self::commit) for `call`, or, with `failure`, - /// [`commit_failed`](Self::commit_failed), its batches handed to the scheduler as `hand` says. - fn commit_as( - &self, - call: &'static str, - failure: Option, - hand: Hand, - ) -> Result<(), Error> { - let shared = self.0.device.shared(); - // The kernels of the decode passes staged or queued for the device's next submissions, - // made here, on the committing thread, before the scheduler's section, where no other - // queue's submission waits for the compile (`texture/decoded_twin.rs`). - self.0.device.make_pending_decodes()?; - // An unshared queue's commit holds other queues' batches back from its `VkQueue` for a - // while (`unshared_hold.rs`), from before its own batches reach the scheduler. - if self.0.queue.unshared() { - shared.queues[self.0.queue.vk_queue()] - .share - .unshared_committed(); - } - // The bytes of the ranges `did_modify_range` noted of the buffers this command buffer may - // use, as the host copies hold them now, for its submission that may use them, or a later - // commit's, never an earlier one's (`managed.rs`); and its commit's stamp, which bounds - // the uploads its batches take. - let modified = &shared.modified; - let commit = modified.take_at_commit(|wanted, count| self.may_use(wanted, count)); - self.state().commit = commit; - // Left to wait for the last render encoder's end, where its call left it to the device's - // lowering thread and the thread has not lowered it, or for the commits left so. - if failure.is_none() && self.queue_commit(call, hand)? { - return Ok(()); - } - // The last render encoder's end, where its call left it to the device's lowering thread. - self.settle_end_committing(); - self.commit_settled(call, failure, CommitRun::AtCall, hand) - } - - /// Under `RenderLoweringPolicy::Worker`, where the command buffer holds a render encoder's - /// end the device's lowering thread has not lowered, or a commit of the device waits for one - /// (`render/queued_commits.rs`): make Metal's checks of `commit` at the call, of the command - /// buffer as the program sees it (its last encoder ended), returning their refusal, and leave - /// the commit's own work to run after the end, and after the commits that wait, its batches - /// handed to the scheduler then as `hand` says. Whether it did. - fn queue_commit(&self, call: &'static str, hand: Hand) -> Result { - let Some(commits) = self.0.device.shared().deferred.commits() else { - return Ok(false); - }; - let mut state = self.state(); - let end_in_flight = state.ending.is_some() && !state.end_lowered; - let queued = commits.lock(); - if !end_in_flight && queued.idle() { - return Ok(false); - } - // The encoder open is the one whose end is in flight, which ended. - let refusal = match state.refusal() { - Some(Problem::EncoderOpen) if end_in_flight => None, - refusal => refusal, - }; - if let Some(problem) = refusal { - return Err(invalid(call, problem)); - } - state.queued_commit = Some(hand); - self.0.status.store( - status_word(CommandBufferStatus::Committed), - Ordering::Release, - ); - let runs = queued.push(self.clone(), !end_in_flight); - drop(state); - if runs { - commits.run(false); - } - Ok(true) - } - - /// Run the commit's own work, which waited for a render encoder's end - /// (`render/queued_commits.rs`), the end lowered: on the device's lowering thread - /// (`by_thread`) or the program's. A refusal it finds fails the command buffer - /// (`State::refuse_commit`), which then commits again with nothing of it run and nothing that - /// may fail made for it ([`CommitRun::Refused`]): it completes, in its queue's order, with - /// that error, and its completed handlers run, as every committed command buffer of Metal's - /// does. - /// - /// Left by `commit_and_submit`, this thread then makes that call's pass - /// (`Scheduler::submit_at_commit`), as the call would have: it submits what is ready, this - /// command buffer's batches among them, and runs their submission checks and handlers, with no - /// wake of the scheduler's thread for them. Not on a thread command buffers' completion - /// depends on (a handler the scheduler's thread runs reads the work counts), which posts the - /// batches to that thread, as `commit_and_submit` called there does. - pub(crate) fn commit_queued(&self, by_thread: bool) { - let shared = self.0.device.shared(); - shared.counts.render_log_commit_run(by_thread); - let hand = match exit_guard::serving_completion() { - true => Hand::Wake, - false => self.state().queued_commit.unwrap_or(Hand::Wake), - }; - self.settle_end_committing(); - if let Err(error) = self.commit_settled("commit", None, CommitRun::Queued, hand) { - self.state().refuse_commit(error); - let committed = self.commit_settled("commit", None, CommitRun::Refused, hand); - debug_assert!( - committed.is_ok(), - "a refused commit's commit of nothing failed: {committed:?}" - ); - } - if hand == Hand::Pass { - shared.scheduler.submit_at_commit(&self.0.device, &self.0); - } - } - - /// Before a wait for the command buffer: where its commit's own work waits - /// (`render/queued_commits.rs`), lower on this thread the ends it and the commits before it - /// wait for, which runs it here where the device's lowering thread has not. - fn settle_commit(&self) { - if self.state().queued_commit.is_none() { - return; - } - let Some(commits) = self.0.device.shared().deferred.commits() else { - return; - }; - for command_buffer in commits.unready_through(self) { - command_buffer.settle_end_committing(); - } - } - - /// The commit, the last render encoder's end lowered, run as `run` says. - fn commit_settled( - &self, - call: &'static str, - failure: Option, - run: CommitRun, - hand: Hand, - ) -> Result<(), Error> { - let _for = self.notices_for(); - // The waiting fetched render targets take their storage form at this commit where it - // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread - // ends the switch once it submitted the command buffer. None where nothing of it runs. - let injected = failure.is_some() || run == CommitRun::Refused; - if !self.take_storage_forms(injected) { - return self.commit_now(call, failure, run, hand); - } - let committed = self.commit_now(call, failure, run, hand); - if committed.is_err() { - self.give_up_storage_forms(); - } - committed - } - - /// Mark the indirect command buffers its encoders made resident for writing where a route that - /// may write their records met them (`write_routes.rs`), before its work is recorded or - /// stepped and outside its lock, as the mark settles the host steps of executions committed - /// before (`IndirectCommandBuffer::written_by_gpu`). Those it leaves unmarked are counted, and - /// held, where it executed indirect commands, until it completes. - fn mark_gpu_written(&self) { - let (decided, followed) = self.state().routes.at_commit(); - followed.mark(); - let AtCommit { marked, unmarked } = decided; - for (icb, writer) in marked { - icb.written_by_gpu(writer); - } - let (count, held) = unmarked; - if count > 0 { - (self.0.device.shared().counts).indirect_write_residencies_unmarked(count); - } - if let Some(held) = held { - self.state().retained.push(Box::new(held)); - } - } - - /// [`commit_settled`](Self::commit_settled) itself. - fn commit_now( - &self, - call: &'static str, - failure: Option, - run: CommitRun, - hand: Hand, - ) -> Result<(), Error> { - let device = &self.0.device; - let committed = Instant::now(); - // From here its `commit` waits for a pipeline still being made a bound at most: a - // driver's cold compile can outlast a guest's watchdog (`PipelineWaitPolicy`). - let policy = device.compile_device().policy(); - if policy.pipeline_waits == PipelineWaitPolicy::Bounded { - let _ = self - .0 - .making_deadline - .set(committed + policy.pipeline_commit_wait); - } - // Textures' host shadows hold their images' texels only until the program gives the device - // GPU work of its own, which is what a commit is: raised here, before anything of this - // command buffer can run, so a `getBytes` after the commit reads the image and not a - // shadow this command buffer may write over (`texture/host_shadow.rs`). Raised even where - // the checks below refuse the commit: the cost of a shadow read again is a submission, and - // a refusal that left the count behind would be a correctness question. - device.shared().program_gave_gpu_work(); - self.mark_gpu_written(); - // No encoder joins the group its tail holds from here (`encoder_fold.rs`): its - // encoders take a failure and a rebind together, and the logs it keeps for that are kept. - // What its last compute encoder parked goes back to the device (`compute/live.rs`). - let (unkept, parked) = { - let mut state = self.state(); - let unkept = state.close_fold(&device.shared().counts); - (unkept, state.unpark_compute()) - }; - for log in unkept { - device.shared().scheduler.spare_logs().give(log); - } - if let Some(parked) = parked { - parked.give_back(device); - } - let (segments, places, failure, reached, hangs, split): ( - Vec<(Deferred, bool)>, - Vec, - _, - _, - _, - _, - ) = { - let mut state = self.state(); - let refusal = match run { - CommitRun::AtCall => state.refusal(), - CommitRun::Queued | CommitRun::Refused => state.commit_refusal(), - }; - if let Some(problem) = refusal { - return Err(invalid(call, problem)); - } - let ended = state.ended.len(); - if let Some(problem) = failure.as_ref().and_then(|failure| failure.problem(ended)) { - return Err(invalid(call, problem)); - } - // A pass with a draw call over a mutable map lets later passes of none run on Metal's - // GPU (`rate_mapped_pass.rs`). - if state.called_over_mutable_map { - (device.shared().mutable_rate_map_called).store(true, Ordering::Release); - } - // Metal's GPU fails a command buffer an encoder of which was made under protection - // options as a failure given to `commit_failed` fails it, with no signal firing - // (`protection.rs`); one given such a failure besides is not measured. - let protected = state.protection.failure(); - let failure = match (failure, &protected) { - (Some(_), Some(_)) => return Err(Error::AppleOnly(AppleOnly::ProtectedContent)), - (Some(failure), None) => Some(failure), - (None, Some((encoders, _))) => Some(CommitFailure { - code: 0, - encoders: encoders.clone(), - signals: false, - }), - (None, None) => None, - }; - // Its last unit of command predication ends, and each step's gates are listed for it. - if run != CommitRun::Refused { - let held = &mut *state; - held.predication.commit(&mut held.uploads, device)?; - } - // One committed on its queue while a hang of it is in flight runs nothing, decided - // here without an event wait and at its first batch's submission with one; its own - // hang hangs where its encoder runs and its signals fire under what it was committed - // as (`hang.rs`). - // Either reads `Scheduled` early, from the hang's on, once its waits are met. - // One committed on a queue Metal revoked runs nothing and completes at once, its - // signals dropped (`revocation.rs`). - let revoked = run != CommitRun::Refused && self.0.queue.errors().revoked(); - // One committed on the queue of the hang a loss of its device named, before the - // recovery, runs nothing and completes with no error, as on Metal's hang's queue: its - // batches meet the lost device, which fails them, and its completion answers it - // (`complete_seen`). - state.held_by_lost_hang = run != CommitRun::Refused - && !revoked - && device.is_lost() - && device.line().holds_hang_queue(self.0.queue.common()); - let event_waits = state.batches.events().0; - let discarded = match failure { - None if run != CommitRun::Refused && !revoked => { - hang::discarded(&self.0.queue, event_waits) - } - _ => None, - }; - let joins = discarded.is_some(); - let failure = failure.or(discarded); - let behind = run != CommitRun::Refused - && !revoked - && failure.is_none() - && event_waits > 0 - && hang::in_flight(&self.0.queue); - let waits: Vec<(Arc, u64)> = match behind { - true => (state.batches.all().iter()) - .flat_map(|batch| batch.waits.iter().cloned()) - .collect(), - false => Vec::new(), - }; - state.behind_hang = match behind { - true => hang::behind(&self.0.queue, &waits), - false => None, - }; - // One committed while a fault's hold of the queue is in flight runs, and reads - // `Scheduled` early, from the fault's on, once its waits are met. - let joins_hold = !joins - && !behind - && run != CommitRun::Refused - && !revoked - && hang::holding(&self.0.queue); - let waits = match joins_hold { - true => (state.batches.all().iter()) - .flat_map(|batch| batch.waits.iter().cloned()) - .collect(), - false => waits, - }; - if joins || joins_hold || state.behind_hang.is_some() { - hang::join(&self.0, &mut state, waits); - } - // Its hold runs where its encoder runs and its signals fire under what it was - // committed as. - let hangs = run != CommitRun::Refused - && !revoked - && state.hang.as_ref().is_some_and(|hang| { - (failure.as_ref()) - .is_none_or(|f| f.signals && !f.encoders.fails(hang.encoder())) - }); - if let (true, Some(hang)) = (hangs, &state.hang) { - let event = Arc::clone(EventRef::Shared(hang.event()).shared()); - state.batches.hold_signal(event, Hang::DONE); - } - let mut failure = Failure::of(failure, state.fails_from, ended); - if let (Some(failure), Some((_, error))) = (&mut failure, protected) { - failure.error = Some(error); - } - let failure = Failure::with_faults(failure, &state.faulted, ended); - let failure = match revoked { - true => Some(Failure::revoked()), - false => failure, - }; - // A group of encoders in one `VkCommandBuffer` the failure fails, or a - // command-predication record left out, in part is split: its encoders that run are - // encoded again apart before the first submission (`encoder_fold.rs`'s **Failed**). - let (failure, split) = state.split_failure(failure); - // The encoders that run: all but those `failure` fails. - let runs = |encoder: usize| Failure::runs(failure.as_ref(), encoder); - state.committing = true; - // Its heaps reach every texture they hold now, for the work recorded below and by its - // host steps. - state.sync_heaps(&self.0.device.shared().counts); - // Each of its batches writes what any of its encoders made resident for writing, for - // the device's tracker (`State::resident_writes`). - state.note_resident_writes(&device.shared().aliases); - let (segments, places): (Vec<(Deferred, bool)>, Vec) = state - .recorded - .iter() - .filter(|recorded| runs(recorded.encoder)) - .flat_map(|recorded| (recorded.segments.iter()).map(|at| (at, recorded.encoder))) - .map(|(segment, encoder)| ((segment.work.clone(), segment.needs_step()), encoder)) - .unzip(); - if segments.iter().any(|(work, _)| work.reaches_unnamed()) { - state.reaches_unnamed = true; - state.writes_unnamed = true; - } - // What of it the live buffers list once used, held weakly: the device's registries' - // locks, which take no other, inside this one. - let reached = state.reached(device.shared(), runs); - // The device's logs of host pages hear of its writes and gated copies in, in commit - // order, and of the shadows its end left holding their truth (`dirty_pages.rs`). - // One that waits for an event or a semaphore may run after work committed later, - // whose writes no commit before it noted: its copies in count on no hold, and its - // writes keep the logs they meet from holding until it completes. - if device.shared().dirty.collects() { - let held = match (&failure, &state.shadow_carry) { - (None, Some(carry)) => carry.held_whole(), - _ => Vec::new(), - }; - let waits = (state.batches.all().iter()) - .any(|batch| !batch.waits.is_empty() || !batch.binary_waits.is_empty()); - // Such a one whose writes went unnoted, nothing collecting them as it encoded, - // counts as writing everything (`dirty_pages.rs`, **A waiting writer**). - let unnoted = self.0.unnoted.load(Ordering::Relaxed); - device - .shared() - .dirty - .committed(&mut lock(&self.0.dirty), &held, waits, unnoted); - } - (segments, places, failure, reached, hangs, split) - }; - // What the commands of its encoders that run use is resident from its commit on, as - // Metal's is: a no-copy buffer or a heap among it is reached unnamed from here, by its - // own commands too, the work recorded below included (`live_buffers.rs`). Listed without - // the lock: what it upgrades may be a resource's last hold. - let used = reached.list(); - device.shared().live_buffers.reach(&used); - // A two-copy buffer whose pages drop the GPU's writes takes its pages again at its - // completion: what its commands wrote reaches no later command buffer - // (`managed_copy.rs`). - for buffer in &used.buffers { - if buffer - .caller_copy() - .is_some_and(|caller| caller.drops_writes()) - { - self.at_completion(AtCompletion::Undo(buffer.clone())); - } - } - let shared = device.shared(); - (shared.counts).commit_used_host_imports(Buffer::distinct_host_imports(&used.buffers)); - // Listed again at its first submission where the list changed since (a rebind ends a - // use). - let listing = Listing::new(device, used); - // Recorded, or settled for their host steps, with the lock free: their dispatches take it, - // and announce degradations. The GPU forms each recording took, for the encoder trail - // (`encoder_trail.rs`, **GPU forms**). - let mut forms = Vec::new(); - let prepared: Result, Error> = match segments.is_empty() { - true => Ok(Vec::new()), - false => commit_times::phase(Phase::Recording, || { - (segments.iter().zip(&places)) - .map(|((work, host), _)| { - let (prepared, took) = self.noting_forms(|| work.prepare(self, *host)); - forms.push(took); - prepared - }) - .collect() - }), - }; - let prepared = match prepared { - Ok(prepared) => prepared, - Err(error) => { - self.state().committing = false; - return Err(error); - } - }; - // The first segment a host step records, which the device announces (a loop's check, a - // staged scatter's CPU copy and a splice's record nothing). - let announced = segments - .iter() - .zip(&prepared) - .find(|((work, host), prepared)| { - *host - && !prepared.for_good - && !matches!( - work, - Deferred::Loop(_) | Deferred::ScatterDrain(_) | Deferred::ShadowSplice(_) - ) - }) - .map(|((work, _), _)| work.clone()); - // A host step may record commands after the commit (a segment not recorded for good). - let stepped = prepared.iter().any(|prepared| !prepared.for_good); - // Until the command buffer completes, the buffers its host steps' commands use keep their - // pages, where a step resolves what it records as it records it, and a rebind of one is - // refused meanwhile (`RebindProblem::EncodedUses`). Work whose step records only what its - // calls resolved holds nothing past the commit (`Deferred::resolved_at_its_calls`): a - // dispatch whose pipelines were being made (`pending_dispatch.rs`), and a render pass left - // for the pipelines its draws and tile dispatches record - // (`render/pending_tile.rs`). Metal's replace fails for neither, and a rebind encodes - // their encoder again instead (`command_buffer/reencode.rs`); where it cannot, their - // recording records nothing of the encoder (`DeferredPass::record_forms`). Nor does a - // predicated loop's check whose laying left no work apart, whose runs again submit the - // laying as encoded, over the pages its first submission took (`rerun.rs`). - let steps_hold = (segments.iter().zip(&prepared)).any(|((work, _), prepared)| { - !prepared.for_good && !work.resolved_at_its_calls(prepared.pipelines) - }); - // The segments a host step records once the pipelines they record are made. - let made_later: Vec = segments - .iter() - .zip(&prepared) - .filter(|(_, prepared)| prepared.pipelines) - .map(|((work, _), _)| work.clone()) - .collect(); - // Every byte the CPU changed in the pages of a copied host buffer this command buffer's - // commands use is in its copy before any of its work is submitted (`copied.rs`): every - // copy where its uses went unnoted, or a command may reach memory no use names. Copied - // in with no lock of the command buffer's held, as a copy over logged pages waits for - // the log's publication. - // Each such copy its commands may write takes a base of the bytes it then holds, before - // any of its work is submitted; where the host has no memory for one, the command - // buffer runs nothing (`copied.rs`, "A base once it may"). - // A batch that waits for an event value not reached before this copy in copies in again - // as it is submitted, after the wait (`copies_again.rs`). - let mut copies_again = None; - if shared.copied.any() { - let (mut used, mut written) = (CopiesReached::default(), CopiesReached::default()); - let unnoted = self.0.unnoted.load(Ordering::Relaxed); - // The state's lock goes before the dirty log's is taken. - let (reaches, writes, unreached) = { - let state = self.state(); - let unreached = CopiesAgain::unreached(state.batches.all()); - (state.reaches_unnamed, state.writes_unnamed, unreached) - }; - // A reach of memory no use names compares every copy, its uses' keys kept beside, so - // the copy in counts the copies that reach alone compares, and those a read twin - // reads in place where no function of the command buffer may store through an - // address (`CopiesReached::reached_unnamed`). - match (unnoted, reaches) { - (true, _) => used.reached_all(), - (false, true) => { - self.dirty().copies_used(&mut used); - used.reached_unnamed(!writes); - } - (false, false) => self.dirty().copies_used(&mut used), - } - match unnoted || writes { - true => written.reached_all(), - false => self.dirty().copies_written(&mut written), - } - let copied_in = shared.copied.copy_in( - &shared.counts, - shared.dirty.tally(), - (&used, &written), - || shared.dirty.in_flight(), - &mut |length| device.copied_base(length), - ); - if copied_in.is_err() { - self.state().committing = false; - return Err(Error::OutOfMemory(MemoryKind::Host)); - } - copies_again = CopiesAgain::new(unreached, (used, written)); - } - let (waits, away, reaches, unreplayable, (reset, splits, raced)) = { - let mut state = self.state(); - state.committing = false; - state.copies_again = copies_again; - if let Some(failure) = failure { - state.fail(failure); - } - state.prepare(prepared); - state.trail_forms(forms); - state.plan_checks(); - // A refused commit's commands run nothing: none of what follows is made for them. - if run == CommitRun::Refused { - state.table_snapshots.clear(); - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if run != CommitRun::Refused && state.failures_injected > 0 { - state.failures_injected -= 1; - return Err(vulkan(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY)); - } - // Its root tables search every live buffer of its own on the device, and what its - // encoders bound and made resident (`live_buffers.rs`). - if run != CommitRun::Refused { - state.point_root_tables(device)?; - } - // The function-table snapshots read the tables' words as they stand now. - for snapshot in &state.table_snapshots { - snapshot.refresh()?; - } - state.table_snapshots.clear(); - // Until it completes, an image retired from the device's heap waits for it, where - // its commands, or its host steps', may read the heap (`heap_sets.rs`). The ticket - // taken here holds what a rebind or a detach replaces; its first submission takes the - // one gone textures wait for (`submit.rs`). - if state.heaps.bound() || stepped { - let ticket = state.heaps.commit(device); - state.retained.push(Box::new(ticket)); - } - state.status = CommandBufferStatus::Committed; - // Its completion's sync file, where one was asked for, is signaled after everything - // its batches hold, past every refusal of the commit (`sync_file.rs`). - #[cfg(unix)] - state.place_sync_file(); - // No run of passes goes on past the commit: each lets go of its scratch and kept - // image, its merge recorded at its batch's submission (`pass_runs.rs`). - for held in state.pass_runs.close() { - held.end(); - } - // Its set-0 cache is shut here, before anything records again: from the commit on it - // holds what its commands took only weakly (below), so no handle a kept set holds is - // held against another object taking it -- which is the cache's own precondition - // (`binding::SetCache`). A rebind frees the import a kept set was written for and - // records the commands over the new one in the same call (`reencode.rs`), and the new - // import's `VkBuffer` may take the freed one's handle, all the cache compares; so - // every command recorded from here -- an encoder encoded again, a host step's -- - // allocates and writes its own set. The commands recorded before the commit keep the - // sets they bound. - state.descriptors.shut(); - state.queued_commit = None; - if let Some(hang) = state.hang.take() { - match hangs { - true => hang.start(&self.0, &mut state, committed), - false => hang.release(), - } - } - self.0.answer(&state); - for heap in state.used_heaps.drain(..) { - heap.mark_used(); - } - // A rebind before its first submission of a buffer its replayable encoders, or its - // work on the GPU alone, named encodes or records them again (`reencode.rs`): noted - // while their holds still refuse one. So does a reset of a rasterization-rate map - // their passes are over (`rate_mapped_pass.rs`): noted first, then a reset before the - // commit found here, marked before the scheduler sees the command buffer. - let kept = state.keep_replays(); - if !kept.keys.is_empty() || !kept.maps.is_empty() { - device - .shared() - .rebinds - .wait_for_replay(&self.0, kept.keys, kept.maps); - } - let to_submission = kept.to_submission; - let unreplayable = kept.gone; - let reset = state.rate_maps_reset(); - if reset.0 { - self.0.mark_reencode(); - } - // So are the encoders that run of a group its failure split, encoded again in this - // call, before the scheduler sees the command buffer's batches. - let splits = !split.is_empty(); - if splits { - state.split_units = split; - self.0.mark_reencode(); - } - // So are its encoders a call of which raced a rebind on another thread of a buffer - // it took (`rebind.rs`, **Other threads**), over where the buffer lies now; one that - // kept no log fails `EncodedUseRebound` at its submission. - let raced = state.raced_again(); - if raced { - self.0.mark_reencode(); - } - let raced_unlogged = state.raced_unreplayable(); - if raced_unlogged > 0 { - (device.shared().counts).encoders_raced_unreplayable(raced_unlogged); - } - if let Some(slot) = lock(&self.0.slot).as_mut() { - slot.committed(); - } - self.0.time(&mut state); - // The last encoder's last command buffer ends, with its batch's end where it may - // (`submit.rs`), the slot taken. - self.0.close_tail(&mut state, None); - // Its submissions record their barriers from its pool, inside sections, where no - // spare is taken: one that encoded nothing takes a spare now, if one is free. - self.0.take_spare_pool(&mut state); - // Until its first submission it holds what its commands took weakly: a rebind or a - // release meanwhile lets the pages go, and the submission finds them moved. Only once - // its last command buffer ended: what lay in pages a detach replaced while an encoder - // held them goes with them (`detach.rs`), and its tail's commands recorded above - // name the views of an attachment recorded inline (`render/inline_first.rs`). - state.wait_for_submission(listing); - // Committed, its commands recorded for good: a rebind of what they used takes - // effect after them (`rebind.rs`); one a host step records holds until completion - // (`steps_hold`). - // One whose encoder no rebind encodes again named a buffer over host pages holds - // until its last event group is submitted (`held_to_submission`), so a rebind - // meanwhile is refused rather than failing that submission. Nothing for one whose - // encoders a rebind encodes again. - if steps_hold { - let held = &mut *state; - let kept = held - .holds - .drain(..) - .map(|holds| Box::new(holds) as Box); - held.retained.extend(kept); - } else if to_submission { - let held = &mut *state; - for holds in &mut held.holds { - holds.hold_to_submission(); - } - held.held_to_submission.append(&mut held.holds); - } else { - state.holds.clear(); - } - let waits = state - .batches - .all() - .iter() - .enumerate() - .map(|(index, batch)| BatchSync { - waits: batch.waits.clone(), - binary_waits: batch.binary_waits.clone(), - binary_signals: batch.binary_signals.clone(), - // A batch holds segments, or may come to: a rebind before its submission - // encodes an encoder of it again from its log, and the encoding again leaves - // a segment of its own where a pipeline it records is being made, though the - // first encoding left none (`command_buffer/reencode.rs`, - // `render/pending_tile.rs`). The scheduler reads this as a gate alone and - // asks the command buffer itself whether a step is due - // ([`needs_host_step`](Self::needs_host_step)), so a batch that gains none - // waits for nothing. - segments: state.recorded[state.batch_range(index)] - .iter() - .any(|encoder| { - !encoder.segments.is_empty() - || encoder.sparse.iter().any(SparseUpdate::needs_step) - || (state.ended.get(encoder.encoder)) - .is_some_and(|record| record.replay.is_some()) - }), - checked: state.checks.is_some(), - }) - .collect(); - // A texture over the caller's image that rests out of `GENERAL`: each batch that - // uses it moves it. - let away = device - .shared() - .interop - .wrapped - .among(state.recorded.iter().flat_map(|r| { - let segments = r.segments.iter().filter_map(|s| s.recorded.as_ref()); - r.summary - .keys() - .chain(segments.flat_map(|done| done.summary.keys())) - })) - .into_iter() - .find(|image| image.rests_out_of_general()); - // Its commands may reach every texture through its resource ID where one bound a - // heap set. - ( - waits, - away, - state.heaps.bound(), - unreplayable, - (reset, splits, raced), - ) - }; - // Each making the batches wait for wakes the scheduler as it finishes, with no lock - // held (`render/pending.rs`), registered before the scheduler first looks at the batches: - // a making that finished between that look and a later registration left the batch held - // with nothing to wake the scheduler (17 lane tests timed out). - if !made_later.is_empty() { - let waker = device.shared().scheduler.waker(); - for work in &made_later { - work.when_made(&waker); - // Its batch waits for them now: they go before the makings nothing waits for. - work.hasten(Urgency::Committed); - } - } - drop(unreplayable); - // The storage-sink degrade's trigger decides, in the program's call, before the - // scheduler sees the command buffer (`detach.rs`). - device.reach_storage_sinks(reaches); - // Its host steps' instances take their numbers from here, in the program's call, before - // the scheduler can run one. - let _ = self.0.step_numbers.set(StepNumbers::reserve()); - // Its reads and writes of new textures' patterns, in commit order: announced in the - // committing call, before the scheduler sees it (`fresh_unwritten.rs`). - FreshUnwritten::commit(device, &self.0.fresh, run != CommitRun::Refused); - // A device test holds the commit here, its last command buffer ended and its batches not - // yet the scheduler's (`completion::trace::Point::Committing`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - completion::trace::at(completion::trace::Point::Committing); - // The scheduler's lock is taken before a command buffer's, never under it. - device - .shared() - .scheduler - .commit(&self.0, self.0.queue.id(), waits, hand); - // A device test holds the commit here, its batches the scheduler's and its slot not - // handed over (`completion::trace::Point::Handed`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - completion::trace::at(completion::trace::Point::Handed); - // Only now, its batches the scheduler's, it leaves the device's uncommitted command - // buffers (`queue.rs`'s `Uncommitted`): until then no texture's face turns and no storage - // form switches beside it, whose commands, recorded for good and their batches' ends - // folded where they may, would meet the turn's copies or the switch as their batches are - // submitted. - if let Some(slot) = lock(&self.0.slot).as_mut() { - slot.handed(); - } - // Its passes that took a rasterization-rate map since reset, encoded again in this call - // as a reset's are, and its encoders that raced a rebind; its first submission waits for - // them (marked above). Those it cannot encode again are announced. - let (again, unencoded) = reset; - if again || splits || raced { - self.0.reencode(); - } - for unlogged in unencoded { - crate::rate_mapped_pass::degrade_unencoded(device, unlogged); - } - if let Some(image) = away { - device.degrade(Degradation::WrappedImageLayoutTransitions, || { - image.notice() - }); - } - if let Some(work) = announced { - work.degrade(device); - } - Ok(()) - } - - /// `status`. Like Metal's, the read waits for no submission in progress and no GPU work. - pub fn status(&self) -> CommandBufferStatus { - status_of(self.0.status.load(Ordering::Acquire)) - } - - /// `error`: why the command buffer failed, once its status is `Error`. Like Metal's, the - /// read waits for no submission in progress and no GPU work. - pub fn error(&self) -> Option { - match self.status() { - CommandBufferStatus::Error => self.0.error.get().copied(), - _ => None, - } - } - - /// `error.localizedDescription`, where the driver relayed Metal's failure of the command - /// buffer's work ([`CommandBufferError::Execution`], and the `PageFault` and `DeviceLost` it - /// maps codes 3 and 11 to): Metal's description, as MoltenVK's message gave it after the - /// code (`device/relay.rs`), empty where the message had none; and Metal's for - /// [`CommandBufferError::PredicationOpenAtUnitEnd`], as measured. `None` for every other - /// failure, and before one. - pub fn error_description(&self) -> Option { - self.state().relayed_description.clone() - } - - /// Why a host step refused the command buffer's commands, once it failed with - /// [`CommandBufferError::Refused`]: the refusal, typed as [`commit`](Self::commit) types it - /// where the CPU wrote the records (`Invalid`, `Unsupported`, `NotImplemented` and the - /// others). Once it failed with [`CommandBufferError::CallRefused`]: the error the render - /// encoder's call refused as it was lowered would have returned at the call. No Metal - /// counterpart. - pub fn refusal(&self) -> Option { - self.settle_ended(); - self.state().refusal.clone() - } - - /// Once the command buffer failed with [`CommandBufferError::PipelineCreation`]: the - /// dispatch whose `VkPipeline` the driver did not make, by its encoder and its order there, - /// the state and the variant it ran, and the driver's error, which the dispatch returned - /// where the runtime made the pipeline at the dispatch (`FailedPipeline`). The first such - /// dispatch, in encoding order: Metal reports one error per command buffer. No Metal - /// counterpart. - pub fn failed_pipeline(&self) -> Option { - self.settle_ended(); - self.state().failed_pipeline.clone() - } - - /// The first draw, in encoding order, whose `VkPipeline` the driver did not make after the - /// draw returned (the runtime makes a draw's pipeline while the draw goes on, - /// `render/pending.rs`): the draw ran nothing, the command buffer running on, without error. - /// Named as [`failed_pipeline`](Self::failed_pipeline) names a dispatch. Counted, each such - /// draw: `WorkCounts::draws_dropped_unmade`. Every draw and dispatch waits for its making, - /// however long it takes (`render/pending.rs`). No Metal counterpart: Metal makes a state's - /// pipelines as it makes the state. - pub fn dropped_draw(&self) -> Option { - self.settle_ended(); - self.state().dropped_draw.clone() - } - - /// Keep `failed`, a dispatch's pipeline whose making failed, which a host step met - /// (`pending_dispatch.rs`, `render/pending_tile.rs`), unless one was kept already: the steps - /// record in encoding order and stop at the first failure, so the one kept is the first. - pub(super) fn fail_pipeline(&self, failed: FailedPipeline) { - let mut held = self.state(); - if held.failed_pipeline.is_none() { - held.failed_pipeline = Some(failed); - } - } - - /// Note `failed`, a draw's pipeline whose making failed, whose recording drops the draw - /// (`render/pending.rs`): kept where it is the first, counted - /// (`WorkCounts::draws_dropped_unmade`). - pub(super) fn drop_draw(&self, failed: FailedPipeline) { - let device = self.device(); - device.shared().counts.draw_dropped_unmade(); - device.degrade(Degradation::DrawDroppedUnmade, || { - let state = match &failed.state { - FailedState::Render(state) => format!( - "render pipeline state {}{}", - state.unique_identifier(), - state - .label() - .map(|label| format!(" `{label}`")) - .unwrap_or_default() - ), - FailedState::Compute(state) => { - format!("compute pipeline state {}", state.unique_identifier()) - } - }; - let variant = { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - failed.variant.hash(&mut hasher); - failed.specialization.hash(&mut hasher); - hasher.finish() - }; - ( - format!( - "draw {} of render encoder {} of a command buffer, of {state}, variant and \ - specialization {variant:016x}", - failed.draw, failed.encoder - ), - format!("the driver failed to make its pipeline: {}", failed.error), - ) - }); - self.keep_dropped(failed); - } - - /// Keep `dropped` as the command buffer's first draw that ran nothing, unless one - /// was kept already: the recordings run in encoding order. - fn keep_dropped(&self, dropped: FailedPipeline) { - let mut held = self.state(); - if held.dropped_draw.is_none() { - held.dropped_draw = Some(dropped); - } - } - - /// Until when its `commit` waits for the pipelines of a pass that executes render commands the - /// CPU writes, and an execution's replay in its `commit` for a making it begins itself, which - /// leave the pass to its host step past it (`render/pending.rs`): set at its commit under - /// `PipelineWaitPolicy::Bounded`, none before it or under `Exact`. Every other making its - /// commands record is waited for until made, under either. - pub(crate) fn making_deadline(&self) -> Option { - self.0.making_deadline.get().copied() - } - - /// Keep `making`, which an execution's replay in its `commit` began itself and found still - /// being made at [`making_deadline`](Self::making_deadline), for the pass it replays for - /// (`DeferredPass::left_for_makings`), whose recording it ends. - pub(crate) fn leave_unmade(&self, making: Pending) { - lock(&self.0.unmade).push(making); - } - - /// The makings [`leave_unmade`](Self::leave_unmade) kept since the last call: none where the - /// recording of the pass that takes them ended for another cause. - pub(crate) fn take_unmade(&self) -> Vec> { - lock(&self.0.unmade).drain(..).collect() - } - - /// What the command buffer's execution status words report, once it completed: resident-set - /// misses of argument-buffer pointers, and the other conditions [`StatusReport`] names. They - /// are facts of the run, not errors; `None` before completion and when the command buffer - /// failed. No Metal counterpart. - pub fn execution_report(&self) -> Option { - self.state().report - } - - /// What the ended encoders' dispatches and draws executed, in encoding order (`execution.rs`): - /// validation's executor reads it; no Metal call answers it. Empty unless the device was made - /// with [`DeviceOptions::record_executions`](crate::DeviceOptions::record_executions): its - /// encoders build no record otherwise. - #[doc(hidden)] - pub fn executions(&self) -> Vec { - self.settle_ended(); - self.state().executions.clone() - } - - /// `GPUStartTime`: the host time, in seconds of [`host_time`](super::host_time)'s clock, at - /// which the GPU began the command buffer's work, once it completed; 0 before, and when it - /// failed (`gpu_time.rs`). - /// - /// On a device with calibrated timestamps (`VK_KHR_calibrated_timestamps` or - /// `VK_EXT_calibrated_timestamps`, enabled where listed) it is Metal's answer, within the - /// calibration's deviation; where that deviation is still above 20 us once the calibration was - /// read again (four readings at most: a loaded host states more), the device announces - /// `Degradation::LooselyCalibratedGpuTimes` once. Without, it is the end below less the GPU's - /// duration, which stays exact, and the device announces `Degradation::UncalibratedGpuTimes` - /// once; so is it where the calibration would place the times outside the command buffer's - /// life, from its first submission to its completion, by more than its deviation and the - /// clocks' drift (a calibration that disagrees with the device's own timestamps, - /// `gpu_time.rs`). A device - /// whose queue family writes no timestamps refuses it (`Unsupported`, `Feature::GpuTimes`). - /// So does a command buffer committed while others held every slot of the device's - /// timestamp pools and no pool more could be made (2048 on MoltenVK; elsewhere only where - /// the device refused a pool, `gpu_time.rs`), and the device announces - /// `Degradation::UntimedCommandBuffer` once. - /// - /// A command buffer that encoded nothing and waits for nothing writes no timestamps: its GPU - /// start and end are where its queue reached it, its kernel end time or the GPU end of the - /// queue's command buffer before it where later, a zero duration, as Metal answers for one. - /// On a device made with `gpu_times_from_host` ([`DeviceOptions`](crate::DeviceOptions), - /// [`RawDevice`](crate::RawDevice)), and on a driver whose timestamps wait for every - /// queue's (MoltenVK 1.4.1 on Apple's GPUs), none writes them: the start is the host time the - /// scheduler called the first driver's submission that carried its work (the kernel end time - /// where one submission carried it all; or the queue's latest GPU end before it, where later) - /// and the end the host time the runtime saw it complete, and the device announces - /// `Degradation::GpuTimesFromHost` once. - pub fn gpu_start_time(&self) -> Result { - self.gpu_times().map(|(start, _)| gpu_time::seconds(start)) - } - - /// `GPUEndTime`: the host time at which the GPU finished the command buffer's work, as - /// [`gpu_start_time`](Self::gpu_start_time) says. Without calibrated timestamps, it is the - /// host time at which the runtime saw the command buffer complete: late by that latency. - pub fn gpu_end_time(&self) -> Result { - self.gpu_times().map(|(_, end)| gpu_time::seconds(end)) - } - - /// `kernelStartTime`: the host time, in seconds of [`host_time`](super::host_time)'s clock, - /// at which the device's scheduler began submitting the command buffer's work to Vulkan; 0 - /// before, and until its [`kernel_end_time`](Self::kernel_end_time) is known, also while it - /// waits for an event: as Metal's, no read shows a start without an end. Where its first - /// command waits for an event, the start is the submission after the event's signal; Metal's - /// is the time it began scheduling the command buffer, at about its commit. Like Metal's, the - /// read waits for no submission in progress and no GPU work. - pub fn kernel_start_time(&self) -> f64 { - gpu_time::seconds(self.0.kernel.shown_start()) - } - - /// `kernelEndTime`: the host time at which the device's scheduler called Vulkan's submission - /// of the command buffer's last batch (the call's start: a driver may run the work before the - /// call returns, and the GPU end is never earlier, as Metal's is not), or held that batch for - /// one kernel submission with later ones (`CompletionPolicy::Grouped`), or found its - /// remaining batches waiting only for its queue's host step behind work already submitted - /// (`scheduler/mod.rs`, **Scheduled**; its start then too, where no batch of it began); it is - /// then `Scheduled`; 0 before. Like Metal's, the read waits for no submission in progress and - /// no GPU work. - pub fn kernel_end_time(&self) -> f64 { - gpu_time::seconds(self.0.kernel.end()) - } - - /// A diagnostic of the runtime's, no Metal call's: the host time, in seconds of - /// [`host_time`](super::host_time)'s clock, at which the command buffer's first batch became - /// the first of its queue's batches the device's scheduler had not taken (every batch - /// committed before it on its queue taken, and it taken in), where the process set - /// `METAL2VULKAN_QUEUE_TIMES`; 0 before, and where it did not. From its commit to this time - /// it waited behind its queue's earlier work; from this time to its - /// [`kernel_start_time`](Self::kernel_start_time) it was held at the head of its queue. - #[doc(hidden)] - pub fn queue_head_time(&self) -> f64 { - gpu_time::seconds(self.0.kernel.head()) - } - - /// A diagnostic of the runtime's, no Metal call's: the host time at which the driver's - /// submission that carried the command buffer's last batch returned, where the process set - /// `METAL2VULKAN_QUEUE_TIMES`; 0 before, where it did not, and where its work went with no - /// submission. Its [`kernel_end_time`](Self::kernel_end_time) is that call's start, so the - /// two bracket the driver's time in it. - #[doc(hidden)] - pub fn submit_returned_time(&self) -> f64 { - gpu_time::seconds(self.0.kernel.returned()) - } - - /// The GPU start and end, in nanoseconds of the host's clock: placed from the command - /// buffer's timestamps once it completed, then kept; 0 and 0 before, when it failed, or when - /// the GPU wrote none. One that wrote no timestamps answers the times placed as it completed - /// (`place_gpu_times`, `gpu_time.rs`). Refused where the device writes no timestamps (and - /// does not answer from the host), and for a command buffer that found no slot of the - /// device's timestamp pools free at its commit, and no pool more. - fn gpu_times(&self) -> Result<(u64, u64), Error> { - let _for = self.notices_for(); - let device = &self.0.device; - let shared = device.shared(); - let untimed = || Error::Unsupported(Unsupported::not_representable(Feature::GpuTimes)); - let clock = shared.timing.clock(); - if clock.is_none() && !shared.timing.answers_from_host() { - return Err(untimed()); - } - let mut state = self.state(); - if let Some(times) = state.times.gpu { - return Ok(times); - } - if state.status != CommandBufferStatus::Completed { - return Ok((0, 0)); - } - let (start, end) = match state.times.stamped { - // Placed as it completed (`place_gpu_times`). - Stamped::NoWork => return Ok(state.times.placed.unwrap_or((0, 0))), - Stamped::FromHost => { - let Some(times) = state.times.placed else { - return Ok((0, 0)); - }; - state.times.gpu = Some(times); - drop(state); - let because = shared - .timing - .host_clock_reason() - .map_or("", |from| from.because()); - device.degrade(Degradation::GpuTimesFromHost, || { - ( - "a command buffer's GPU times".to_owned(), - because.to_owned(), - ) - }); - return Ok(times); - } - Stamped::Read(Some(ticks)) => ticks, - Stamped::Read(None) | Stamped::Unread => return Ok((0, 0)), - Stamped::NoSlot => { - drop(state); - let slots = shared.timing.slots(); - device.degrade(Degradation::UntimedCommandBuffer, || { - let why = if slots == 0 { - "the device could make no timestamp pool at its commit".to_owned() - } else { - format!( - "every one of the device's {slots} timestamp slots was held by a \ - command buffer in flight at its commit, and it could make no pool \ - more" - ) - }; - ("a command buffer's GPU times".to_owned(), why) - }); - return Err(untimed()); - } - Stamped::Failed(error) => return Err(device.failed(error)), - }; - // Read timestamps came from the device's clock. - let clock = clock.ok_or_else(untimed)?; - let (times, placement) = clock.span( - state.times.pair, - start, - end, - life(&self.0.kernel, &state.times), - ); - state.times.gpu = Some(times); - drop(state); - if let Some((kind, reason)) = placement.read(clock, &shared.counts) { - device.degrade(kind, || ("a command buffer's GPU times".to_owned(), reason)); - } - Ok(times) - } - - /// `waitUntilScheduled`: block until the command buffer's scheduled handlers ran, or it - /// failed. As Metal's (measured on an M4, macOS 27.0.1), it returns only - /// once every scheduled handler returned, though [`status`](Self::status) reads `Scheduled` - /// just before they start. - /// - /// As [`wait_until_completed`](Self::wait_until_completed) does, it submits for itself what - /// still waits in the scheduler's inbox before it sleeps, where no handler of the program's - /// would run on this thread for it (`Scheduler::submit_before_waiting`). It sends no group - /// held: a batch held for one kernel submission makes its command buffer `Scheduled` as it is - /// held, so this wait is already answered by the hold. - /// - /// From a handler or a release on the device's handler threads it answers as Metal's does - /// where measured: once the command buffer's transition to `Scheduled` ran, it returns. Its own - /// scheduled handlers' wait, and a wait for a later command buffer of the handler's queue, are - /// refused (`WaitWouldDeadlock` of [`DeadlockCause::OwnQueue`]): that transition comes after - /// the handler in the queue's order, and Metal's never returns there. A wait for another - /// queue's command buffer waits, unless it would deadlock (as - /// [`CommandBuffer::wait_until_completed`] says). From a submission handler - /// ([`add_submission_handler`](Self::add_submission_handler)), a wait for one not yet scheduled - /// is refused ([`DeadlockCause::SubmissionHandler`]). Once the process is exiting, it answers - /// as that one does. - pub fn wait_until_scheduled(&self) -> Result<(), Error> { - let scheduled_now = scheduled(&self.state()); - let _blocked = match scheduled_wait(running(), self.0.target(), scheduled_now) { - Answer::Refuse(cause) => return Err(cause.into()), - Answer::Return | Answer::Wait => None, - Answer::Block(from) => Some(contexts::block(from, self.0.context())?), - }; - self.settle_commit(); - self.0.waits_for_scheduling(); - let mut state = self.state(); - while !scheduled(&state) { - if exit_guard::closed() { - return Err(DeadlockCause::Exiting.into()); - } - state.parked += 1; - state = self - .0 - .changed - .wait_timeout(state, exit_guard::WAKE) - .unwrap_or_else(std::sync::PoisonError::into_inner) - .0; - state.parked -= 1; - } - Ok(()) - } - - /// `waitUntilCompleted`: block until the command buffer completed or failed and its - /// completed handlers ran. It returns on device loss (the status is then `Error`). Where a - /// batch of it is held for one kernel submission with later ones while its queue's earlier - /// work runs (`CompletionPolicy::Grouped`), the wait sends it at once. - /// - /// It returns only once the runtime's threads let go of the command buffer, and of what they - /// held to make what its work waited for (a pipeline made on the device's pool, a texture's - /// CPU decode, `trails.rs`), so dropping the last handles after it destroys the device on the - /// dropping thread, before the drop returns. Such a thread lets go a few drops after its - /// signal, so this adds to the wait only where it lost its CPU in between; the completion, - /// the status and the completed handlers do not wait for it. A program that learns of the - /// completion otherwise (a completed handler, an event the command buffer signals, its - /// status) may drop them while a runtime thread still holds the command buffer; the device - /// then goes on that thread. An exit meanwhile waits for that teardown, or leaves the device - /// to the process's end. - /// - /// Once the process is exiting (its exit handlers run), the runtime's threads that finish - /// command buffers have ended, and no Vulkan call is made: a wait for a command buffer that - /// did not finish answers `WaitWouldDeadlock` of [`DeadlockCause::Exiting`] at once, on any - /// thread, and one already blocked within 50 ms, so that nothing the exit runs waits for - /// those threads ([`process_exiting`](crate::process_exiting) answers whether it is so). - /// - /// From a handler or a release on the device's handler threads it answers as Metal's does - /// where measured: - /// - a deallocator that runs as this command buffer releases what it retained gets `Ok` at - /// once (the status is `Completed` or `Error`); - /// - a handler's wait for its own command buffer, or for a later one of its queue, is - /// refused (`WaitWouldDeadlock` of [`DeadlockCause::OwnQueue`]): that transition comes - /// after the handler in the queue's order, and Metal's never returns there; - /// - a wait for another queue's command buffer blocks the handler's thread until it - /// completed, as Metal's does. It is refused (`WaitWouldDeadlock`) only where it would - /// deadlock: when that queue's handlers wait, through the queues they wait for, for this - /// one ([`DeadlockCause::Cycle`]), or when it would leave the device's handler threads - /// with none that is not blocked so ([`DeadlockCause::HandlerThreadCap`]: the 512th, where - /// Metal's handler threads run out and it hangs). - pub fn wait_until_completed(&self) -> Result<(), Error> { - let _blocked = match self.completed_wait() { - Answer::Return => { - return self - .trailed(None) - .map_err(|_| DeadlockCause::Exiting.into()) - } - Answer::Refuse(cause) => return Err(cause.into()), - Answer::Wait => None, - Answer::Block(from) => Some(contexts::block(from, self.0.context())?), - }; - self.settle_commit(); - self.0.waits_for_completion(); - let waited = self.0.gate.wait()?; - self.0.device.shared().counts.gate_waited(waited); - self.trailed(None) - .map_err(|_| DeadlockCause::Exiting.into()) - } - - /// [`CommandBuffer::wait_until_completed`] for at most `timeout`, which bounds the whole call; - /// a timeout past what the host's clock holds waits until the completion comes. Where that is - /// refused, it ends at once with `TimedOut`, as it does once the process is exiting. - pub fn wait_until_completed_for(&self, timeout: Duration) -> Result<(), TimedOut> { - let deadline = Instant::now().checked_add(timeout); - let _blocked = match self.completed_wait() { - Answer::Return => return self.trailed(deadline).map_err(|_| TimedOut), - Answer::Refuse(_) => return Err(TimedOut), - Answer::Wait => None, - Answer::Block(from) => { - Some(contexts::block(from, self.0.context()).map_err(|_| TimedOut)?) - } - }; - self.settle_commit(); - self.0.waits_for_completion(); - let waited = match deadline { - Some(deadline) => self.0.gate.wait_until(deadline)?, - // Only an exiting process ends a wait with no deadline: that wait's `TimedOut`. - None => self.0.gate.wait().map_err(|_| TimedOut)?, - }; - self.0.device.shared().counts.gate_waited(waited); - self.trailed(deadline).map_err(|_| TimedOut) - } - - /// Once its gate opened, wait until the trails opened before it completed closed - /// (`trails.rs`): what the runtime's threads held for the work it waited for is let go. At - /// most until `deadline` where one is given. A wait answered before the gate opened (a - /// deallocator's, as it releases what it retained) waits for none. - fn trailed(&self, deadline: Option) -> Result<(), crate::trails::Ended> { - if !self.0.gate.is_open() { - return Ok(()); - } - let mark = self.state().trail_mark; - let shared = self.0.device.shared(); - let waited = shared.trails.wait_below(mark, deadline)?; - shared.counts.trail_waited(waited); - Ok(()) - } - - /// What a wait for completion answers on this thread. - fn completed_wait(&self) -> Answer { - completed_wait(running(), self.0.target(), self.0.gate.is_open()) - } -} - -impl CommandBufferShared { - /// The device. - pub(super) fn device(&self) -> &Device { - &self.device - } - - /// Where a batch of it, otherwise ready, is held back from its `VkQueue` for an unshared - /// queue there (`unshared_hold.rs`): that `VkQueue`'s index, the value of the oldest batch in - /// flight there the host has not seen complete, and in how many nanoseconds the work left - /// ahead there falls under the budget where it does before that batch completes; `None` where - /// it may go, as on a lost device, whose submissions fail at once. The budget is 2 ms while an - /// unshared queue there committed within `unshared_hold::ACTIVE`, else 16 ms (counted where - /// only that let it go). - pub(crate) fn held_for_unshared(&self) -> Option<(usize, u64, Option)> { - let index = self.held_back_on()?; - let shared = self.device.shared(); - let slot = &shared.queues[index]; - let now = crate::gpu_time::host_nanos(); - let active = crate::unshared_hold::active(slot.share.unshared_commit(), now); - match slot.waits.hold_ahead(|| slot.completed_value(), active) { - crate::unshared_hold::Room::Go => None, - crate::unshared_hold::Room::Idle => { - shared.counts.head_let_go_unshared_idle(); - None - } - crate::unshared_hold::Room::Hold { after, through } => Some((index, through, after)), - } - } - - /// Where a batch of it, otherwise ready, is held back from its `VkQueue` for its turn there - /// (`queue_turns.rs`): that `VkQueue`'s index, the value of the oldest batch in flight there - /// the host has not seen complete, and in how many nanoseconds its own queue's work left there - /// falls under the budget where it does before that batch completes; `None` where it may go, - /// as on a lost device, whose submissions fail at once, and for an unshared queue's. The - /// budget is 2 ms while another command queue took a batch there within - /// `unshared_hold::ACTIVE`, else 16 ms (counted where only that let it go). - /// - /// Only its first batch (`index` 0) takes a turn: once that one went, each later batch goes as - /// it is ready, as Metal schedules a command buffer whole. Held behind its own first batch, - /// a command buffer whose first batch waits on the GPU for a signal still to come would not - /// read `Scheduled` (its last batch's submission) until that signal came, nor could another - /// queue's command buffer that waits for its later signal go meanwhile, where Metal schedules - /// both at once (`queue_turns.rs`, "Whole command buffers"). - pub(crate) fn held_for_turn(&self, index: usize) -> Option<(usize, u64, Option)> { - if index > 0 || self.device.is_lost() || !self.takes_turns() { - return None; - } - let index = self.queue.vk_queue(); - let shared = self.device.shared(); - let slot = &shared.queues[index]; - let own = (self.queue.id(), &**self.queue.expected()); - match slot.waits.turn_ahead(own, || slot.completed_value()) { - crate::unshared_hold::Room::Go => None, - crate::unshared_hold::Room::Idle => { - shared.counts.head_let_go_turn_idle(); - None - } - crate::unshared_hold::Room::Hold { after, through } => Some((index, through, after)), - } - } - - /// Whether `reaches` holds for an event signal of batch `index` or a later one, given its event - /// and value (`scheduler/mod.rs`'s `mark_awaited_signals`). - pub(crate) fn signals_any_from( - &self, - index: usize, - mut reaches: impl FnMut(&Arc, u64) -> bool, - ) -> bool { - let state = lock(&self.state); - let batches = state.batches.all(); - (batches.get(index..).unwrap_or_default().iter()) - .flat_map(|batch| &batch.signals) - .any(|(event, value)| reaches(event, *value)) - } - - /// Whether its batches take turns on their `VkQueue` (`queue_turns.rs`): its queue is not - /// unshared, and the device's queues take turns on a `VkQueue` other command queues share. - pub(crate) fn takes_turns(&self) -> bool { - !self.queue.unshared() && self.device.takes_turns_on(self.queue.vk_queue()) - } - - /// Whether a batch of it goes before other queues' batches a pass finds ready with it - /// (`scheduler/order.rs`, "Heads put first"): its queue is unshared, and its `VkQueue` holds - /// other queues' work back for it (`unshared_hold.rs`). - pub(crate) fn goes_ahead_of_held_work(&self) -> bool { - self.queue.unshared() && self.device.holds_back_for_unshared(self.queue.vk_queue()) - } - - /// Whether its queue keeps commit order across queues: a queue made for copies - /// (`Device::new_command_queue_for_copies`), whose batches wait in the scheduler's order behind - /// an earlier commit of another queue they conflict with, though it gives way - /// (`scheduler/order.rs`, **But not to a queue made for copies**). - pub(crate) fn keeps_commit_order(&self) -> bool { - self.queue.for_copies() - } - - /// The index of its `VkQueue` where its queue is unshared: its commit counts there as posted - /// to the scheduler's inbox, then as taken into the order (`SlotShare::unshared_commits`), and - /// its batches carry its place among the commits posted there - /// (`SlotShare::posted_unshared`). - pub(crate) fn unshared_vk_queue(&self) -> Option { - self.queue.unshared().then(|| self.queue.vk_queue()) - } - - /// Where a batch of it is held back from its `VkQueue` for an unshared queue there - /// ([`held_for_unshared`](Self::held_for_unshared)'s conditions), that `VkQueue`'s index, with - /// its unshared commits posted to the scheduler's inbox and taken into its order so far - /// (`unshared_hold::behind_commits`); `None` where none is held back. - pub(crate) fn unshared_commits(&self) -> Option<(usize, (u64, u64))> { - let index = self.held_back_on()?; - Some(( - index, - self.device.shared().queues[index].share.unshared_commits(), - )) - } - - /// The index of its `VkQueue` where its batches are held back there for an unshared queue - /// (`unshared_hold.rs`): its own queue is not unshared, the device is not lost, and an - /// unshared queue holds that `VkQueue` under `UnsharedIsolationPolicy::Bounded`; `None` - /// elsewhere. - pub(crate) fn held_back_on(&self) -> Option { - if self.queue.unshared() || self.device.is_lost() { - return None; - } - let index = self.queue.vk_queue(); - self.device.holds_back_for_unshared(index).then_some(index) - } - - /// This thread doing the command buffer's work until the guard goes - /// ([`CommandBuffer::notices_for`]). - pub(super) fn notices_for(&self) -> NoticesFor { - NoticesFor::new(self.id, &self.generation) - } - - /// Do what its completion does for the two-copy buffers its commands used - /// ([`CommandBuffer::at_completion`]): its last batch finished, `completed` where no failure - /// was relayed for its work. - pub(super) fn run_at_completion(&self, completed: bool) { - let work: Vec = lock(&self.at_completion).drain(..).collect(); - for work in work { - work.run(completed); - } - } - - /// This command buffer's address, which names it to [`own`]'s marker. - fn address(&self) -> usize { - self as *const CommandBufferShared as usize - } - - /// Its queue's serial context. - fn context(&self) -> Context { - self.queue.context() - } - - /// This command buffer as the target of a wait. - fn target(&self) -> Target { - Target { - context: self.context(), - buffer: self.address(), - } - } - - /// The marker of `step` of this command buffer. - fn marker(&self, step: Step) -> Marker { - Marker { - context: self.context(), - buffer: self.address(), - step, - } - } - - /// A reference for a runtime thread: the command buffer's waiters wait until it is gone. - pub(crate) fn hold(self: &Arc) -> Hold { - Hold::new(self, &self.gate) - } - - /// Whether batch `index` waits for a host step: a segment of it executes commands the GPU may - /// write, or its step records it (a copy staged through the CPU, `host_ram/copy.rs`), not - /// recorded since, or an indirect sparse update of it reads regions the GPU may write, not - /// read since. - pub(crate) fn needs_host_step(&self, index: usize) -> bool { - if self.stepping(index) { - return true; - } - let state = lock(&self.state); - // After a failed step the batch goes to its submission, which fails. - if state.step_failure.is_some() { - return false; - } - let range = state.batch_range(index); - let recorded = &state.recorded[range]; - recorded - .iter() - .flat_map(|encoder| &encoder.segments) - .any(Segment::needs_step) - || recorded - .iter() - .flat_map(|encoder| &encoder.sparse) - .any(SparseUpdate::needs_step) - } - - /// The scheduler handed batch `index`'s host step to its steps' thread (`scheduler/steps.rs`): - /// the batch waits for it until [`end_step`](Self::end_step). - pub(crate) fn begin_step(&self, index: usize) { - self.stepping.store(index as u64, Ordering::Release); - } - - /// The steps' thread ended the host step it was handed ([`begin_step`](Self::begin_step)). - pub(crate) fn end_step(&self) { - self.stepping.store(NOT_STEPPING, Ordering::Release); - } - - /// Whether the steps' thread holds batch `index`'s host step, handed to it and not ended. - pub(crate) fn stepping(&self, index: usize) -> bool { - self.stepping.load(Ordering::Acquire) == index as u64 - } - - /// Its first batch became the first of its queue's batches the scheduler has not taken: - /// noted where its device notes queue times (`METAL2VULKAN_QUEUE_TIMES`, - /// [`CommandBuffer::queue_head_time`]); else nothing, not even a read of the clock. - pub(crate) fn became_head(&self) { - self.kernel - .became_head(self.device.shared().timing.queue_times()); - } - - /// What the host step of batch `index` waits for ([`needs_host_step`](Self::needs_host_step)): - /// the work submitted before it, where the GPU may write what a segment or an indirect - /// sparse update of it reads, or the host bytes a gather of it staged through the CPU reads - /// (`Deferred::steps_after_the_gpu_now`), its own `VkQueue`'s alone where those are loops' - /// checks; and the pipelines its segments record, while one is being made, and what a loop's - /// check runs again. - pub(crate) fn step_waits(&self, index: usize) -> StepWaits { - let state = lock(&self.state); - let recorded = &state.recorded[state.batch_range(index)]; - let segments = || recorded.iter().flat_map(|encoder| &encoder.segments); - let sparse = recorded - .iter() - .flat_map(|encoder| &encoder.sparse) - .any(SparseUpdate::needs_step); - let staged = segments() - .filter(|segment| segment.needs_step()) - .any(|segment| segment.work.steps_after_the_gpu_now(&self.device)); - // A loop's check reads only what its laying, on its own `VkQueue`, wrote (`rerun.rs`). - let checks_alone = !sparse - && !staged - && segments() - .filter(|segment| segment.steps_after_the_gpu()) - .all(|segment| matches!(segment.work, Deferred::Loop(_))); - // Its step records the draws and dispatches once their pipelines are made, past its bound - // too (`render/pending.rs`, `pending_dispatch.rs`, `render/pending_tile.rs`): no command is - // dropped for its making's time. - StepWaits { - gpu: segments().any(Segment::steps_after_the_gpu) || sparse || staged, - queue_alone: checks_alone.then(|| self.queue.vk_queue()), - pipelines: segments().any(Segment::steps_after_pipelines), - } - } - - /// What the host step of batch `index` reads on the host of what the GPU may write, where its - /// gate may be the batches that last wrote it alone (`scheduler/mod.rs`'s `gate_heads`): each - /// segment whose step waits for the GPU is an execution, or a render pass of executions, - /// whose uses `commit` bounded (`Segment::bound`), and its reads are their records and ranges - /// (`Deferred::host_reads`), with the host aliases of their bytes. `None` where the step waits - /// for more: an indirect sparse update or a staged gather of the batch reads what the GPU may - /// write, or another segment's step waits for the GPU (an indirect dispatch's, a loop's check, - /// an execution inside a block of command predication): its gate is every queue's work. - pub(crate) fn step_reads(&self, index: usize) -> Option>> { - self.reads_of_step(index, true) - } - - /// What the host step of batch `index` reads on the host of what the GPU may write, as - /// [`step_reads`](Self::step_reads) answers, and also where `commit` could not bound a - /// segment's uses (`Segment::bound`'s `None`: what its recording may use on the GPU is not - /// known): its records and ranges are still all its step reads on the host. For the - /// scheduler's order across queues once the step took its gate (`scheduler/mod.rs`'s - /// `place_of`). `None` where the step waits for more, as there. - pub(crate) fn step_host_reads(&self, index: usize) -> Option>> { - self.reads_of_step(index, false) - } - - /// [`step_reads`](Self::step_reads)'s answer where `bounded`, else - /// [`step_host_reads`](Self::step_host_reads)'s. - fn reads_of_step(&self, index: usize, bounded: bool) -> Option>> { - let state = lock(&self.state); - let recorded = &state.recorded[state.batch_range(index)]; - let mut sparse = recorded.iter().flat_map(|encoder| &encoder.sparse); - if sparse.any(SparseUpdate::needs_step) { - return None; - } - let mut reads = Vec::new(); - for segment in recorded.iter().flat_map(|encoder| &encoder.segments) { - if segment.needs_step() && segment.work.steps_after_the_gpu_now(&self.device) { - return None; - } - if segment.steps_after_the_gpu() { - if bounded { - segment.bound.as_ref()?; - } - reads.extend(segment.work.host_reads()?); - } - } - drop(state); - let aliases = &self.device.shared().aliases; - Some(aliases.augment(&reads).unwrap_or(reads)) - } - - /// Raise the makings of the pipelines batch `index`'s host step records, still being made, - /// to a queue's first held batch's (`budget::Urgency::Head`): the scheduler found the batch - /// first in its queue's line, every batch after it there waiting behind it. The makings are - /// read under the command buffer's lock and hastened with it released, as `commit` hastens - /// them. - pub(crate) fn hasten_head(&self, index: usize) { - let works: Vec = { - let state = lock(&self.state); - state.recorded[state.batch_range(index)] - .iter() - .flat_map(|encoder| &encoder.segments) - .filter(|segment| segment.steps_after_pipelines()) - .map(|segment| segment.work.clone()) - .collect() - }; - for work in &works { - work.hasten(Urgency::Head); - } - } - - /// What batch `index` uses, for the scheduler's order across queues (`scheduler/order.rs`): - /// its encoders' summaries and its segments' recordings, with what the command buffer's work - /// may write through its residency where the batch has a part (`State::resident_writes`), - /// and for a segment its host step - /// records for the pipelines it waits for alone, what its work uses, known at encode time - /// (`Segment::known_summary`): Metal makes the pipeline at `newRenderPipelineState`, so only a - /// batch that shares a resource with it waits for it; and for a segment its host step records - /// for what the GPU may write, what `commit` bounded its uses by (`Segment::bound`: what Metal - /// orders its commands' reach by, the resources made resident, the records and the bindings - /// they inherit), so a later - /// batch of another queue that shares nothing with it is not held behind its gate and step. - /// `None` while some of it is not known: such a segment `commit` could not bound, one its - /// submission records (a scrub), or a resource state encoder's update, whose uses its - /// submission adds. A loop's check adds what its laying's parts use, which it may run again. - /// - /// Built where a pass first asks, and kept ([`Footprints`]): a later ask takes the kept one - /// while what it was built from holds ([`BuiltFootprint`]), so the scheduler's passes, one at - /// each commit and completion on every queue, build each batch's once, not once a pass - /// (`WorkCounts::footprints_built`). A kept one is read without the command buffer's state - /// lock, which a host step's draws and a commit's work take, so an ask waits for neither; a - /// build copies its uses out under the lock (an ask that found it taken counted, - /// `WorkCounts::footprint_lock_waits`) and sorts them without it. A footprint a segment's - /// known uses join is built at each ask, as those are made from the device's aliases as - /// they stand (`DeferredPass::known_summary`). - pub(crate) fn footprint(&self, index: usize) -> Option>> { - if let Some(kept) = self.footprints.kept(index) { - return Some(kept); - } - let counts = &self.device.shared().counts; - let (built, gathered) = { - let state = match self.state.try_lock() { - Ok(state) => state, - Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), - Err(TryLockError::WouldBlock) => { - counts.footprint_lock_waited(); - lock(&self.state) - } - }; - // Read under the lock, before anything it is built from: a change since moves it. - let revision = self.footprints.revision.load(Ordering::Acquire); - let range = state.batch_range(index); - let recorded = &state.recorded[range.clone()]; - let mut summaries = Vec::new(); - let mut known = Vec::new(); - let mut probes = Vec::new(); - // What its work may write through its residency, as its submission's plan takes it - // (`State::resident_writes`). - if !recorded.is_empty() { - summaries.extend(&state.resident_writes); - } - for (at, encoder) in recorded.iter().enumerate() { - if !encoder.sparse.is_empty() { - return None; - } - summaries.push(&encoder.summary); - for segment in &encoder.segments { - probes.push(SegmentProbe::of(segment)); - // A loop's check may run its laying again: what the laying's parts use - // (`rerun.rs`). - if let Deferred::Loop(check) = &segment.work { - let laying = state.recorded.get(check.from()..range.start + at); - summaries.extend(laying.into_iter().flatten().map(|part| &part.summary)); - continue; - } - match &segment.recorded { - // One recorded again on the GPU alone uses what its recording does; one a - // route outgrew, what its host step finds. - Some(recording) - if !segment.needs_step() - || (segment.rerecords() && !segment.work.outgrown()) => - { - summaries.push(&recording.summary); - } - // One its host step records for what the GPU may write: what `commit` - // bounded its recording's uses by, where it could (`Segment::bound`). - _ if segment.steps_after_the_gpu() => { - summaries.push(segment.bound.as_ref()?) - } - _ => known.push(segment.known_summary(&self.device)?), - } - } - } - if !known.is_empty() { - counts.footprint_built(); - let all = summaries.into_iter().chain(&known); - return Some(Arc::new(Footprint::of(all))); - } - let built = (revision, probes); - (built, Footprint::gathered(summaries)) - }; - let footprint = Arc::new(gathered.sorted()); - counts.footprint_built(); - let (revision, probes) = built; - let kept = BuiltFootprint { - revision, - probes, - footprint: Arc::clone(&footprint), - }; - self.footprints.keep(index, kept); - Some(footprint) - } - - /// The host step of batch `index` (`deferred.rs`): on the steps' thread (`scheduler/steps.rs`), - /// without the scheduler's lock, - /// inside a section of the exit guard, once every batch submitted before it completed. Each - /// segment of the batch that needs it is recorded from what its work reads as it stands now and - /// what `commit` left for the step (`Deferred::step`); the recording `commit` made of one, if - /// any, is dropped. A failure is kept for the batch's submission, which fails the command - /// buffer with it. - pub(crate) fn host_step(self: &Arc, index: usize) { - let _for = self.notices_for(); - // A rebind's encoding again of its encoders records into its pool too: one at a time. - let _turn = lock(&self.reencoding); - // Its instances numbered from its commit's place among the program's calls. - let step = || exit_guard::host_step(|| self.record_host_step(index)); - match self.step_numbers.get() { - Some(numbers) => numbers.numbering(step), - None => step(), - } - } - - /// [`host_step`](Self::host_step)'s recording, marked: every notice it announces, those - /// asked for at every occurrence included, is announced here, on this thread, before the - /// batch is submitted, completes or is scheduled. - fn record_host_step(self: &Arc, index: usize) { - let device = &self.device; - let steps: Vec<_> = { - let state = lock(&self.state); - let range = state.batch_range(index); - let first = range.start; - state.recorded[range] - .iter() - .enumerate() - .flat_map(|(encoder, recorded)| { - recorded - .segments - .iter() - .enumerate() - .filter(|(_, segment)| segment.needs_step()) - .map(move |(at, segment)| { - ( - (first + encoder, at), - segment.work.clone(), - segment.inputs.clone(), - ) - }) - }) - .collect() - }; - self.read_mappings(index); - if steps.is_empty() { - return; - } - // The first segment a host step records for what the GPU may write, which the device - // announces: a recording on the GPU alone made again announces nothing - // (`gpu_execute::Rerecord`), unless a route outgrew it (`Deferred::outgrown`), which the - // step records from the records; nor does work recorded again for the CPU's writes since - // the commit alone (`Deferred::rewritten`), or for its pipelines alone; nor a loop's check, - // which records nothing, nor a staged copy's steps (`host_ram/copy.rs`). - let announced = steps - .iter() - .find(|(_, work, inputs)| { - work.gpu_written() - && (!matches!(inputs, Some(StepInputs::Rerecord(_))) || work.outgrown()) - && !matches!(inputs, Some(StepInputs::Loop | StepInputs::Staged)) - }) - .map(|(_, work, _)| work.clone()); - let buffer = CommandBuffer(Arc::clone(self)); - for ((encoder, at), work, inputs) in steps { - let Some(inputs) = inputs else { - let error = internal("a committed segment without what its host step needs"); - lock(&self.state).step_failure = Some(recording_error(device, error)); - break; - }; - // The step's recording keeps the takes of copies taken at use of the one `commit` - // made, which never runs (`shadow::ShadowSync::over`). - { - let mut state = lock(&self.state); - let segment = &state.recorded[encoder].segments[at]; - let replaced = segment.recorded.as_ref().map(|done| done.takes.clone()); - state.step_takes = replaced.unwrap_or_default(); - // What the step records, as the encoder trail names it (`encoder_trail.rs`). - if device.shared().encoder_trail { - let ended = state.recorded[encoder].trail.clone(); - *lock(&self.step_trail) = Some(crate::encoder_trail::Step::new(ended)); - } - } - let recorded = work.step(&buffer, &inputs); - let stepped = match device.shared().encoder_trail { - true => lock(&self.step_trail).take(), - false => None, - }; - // A device test's failure of the recording (`CommandBuffer::fail_host_step`), the - // recording it made dropped without the lock. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let recorded = { - let injected = lock(&self.state).step_failure_injected.take(); - match injected { - Some(error) => recorded.and(Err(error)), - None => recorded, - } - }; - let mut state = lock(&self.state); - state.step_takes.clear(); - match recorded { - Ok(done) => { - // The encoder as its batch's trail names it, the states its commands named - // after its own (`encoder_trail.rs`). - if let Some(trail) = stepped.as_ref().and_then(|step| step.stepped()) { - state.recorded[encoder].trail = Some(trail); - } - let segment = &mut state.recorded[encoder].segments[at]; - segment.stepped = true; - // Its recording is the step's now, which a rebind does not record again. - segment.gpu_alone = false; - let before = segment.recorded.replace(done); - if let Some(mut before) = before { - // What `commit`'s took that the step's did not meet goes back. - if let Some(now) = &segment.recorded { - before.takes.give_back_unheld(&now.takes); - } - state.retained.extend(before.retained.into_entry()); - before.taken.retain_into(&mut state.retained); - } - } - Err(error) => { - // A draw's pipeline whose making failed fails the command buffer so. - state.step_failure = Some(match &state.failed_pipeline { - Some(failed) => CommandBufferError::PipelineCreation( - PipelineCreationCause::of(&failed.error), - ), - None => step_error(device, error, &mut state.refusal), - }); - break; - } - } - drop(state); - // A loop's check that runs its laying again holds the batch: the segments after it - // read what the laying leaves, and step once it ends (`rerun.rs`). - let holds = work.holds(); - // Dropped without the lock: what it holds may be a state's last handle. - drop((work, inputs)); - if holds { - break; - } - } - drop(buffer); - if let Some(announced) = announced { - announced.degrade(device); - } - } - - /// The host step's reading of batch `index`'s indirect sparse updates (`sparse/indirect.rs`), - /// before its segments' steps: each is replaced, in its place, by the updates its arguments - /// state now, and held until the command buffer completes. A refusal is kept for the batch's - /// submission, which fails the command buffer with it, and the rest stay unread. - fn read_mappings(self: &Arc, index: usize) { - let device = &self.device; - let unread: Vec<(usize, usize, SparseUpdate)> = { - let state = lock(&self.state); - if state.step_failure.is_some() { - return; - } - let range = state.batch_range(index); - let first = range.start; - state.recorded[range] - .iter() - .enumerate() - .flat_map(|(encoder, recorded)| { - recorded - .sparse - .iter() - .enumerate() - .filter(|(_, update)| update.needs_step()) - .map(move |(at, update)| (first + encoder, at, update.clone())) - }) - .collect() - }; - if unread.is_empty() { - return; - } - // Read without the lock, the last of an encoder first, so the places of those before - // it stay where they were. - for (encoder, at, update) in unread.into_iter().rev() { - let SparseUpdate::Indirect { - texture, - mode, - buffer, - offset, - } = &update - else { - continue; - }; - let read = indirect::resolve(device, texture, *mode, buffer, *offset); - let mut state = lock(&self.state); - match read { - Ok(updates) => { - // The update read goes to `retained`: its texture and buffer are held until - // the command buffer completes, as Metal's command buffer holds what its - // encoders were given, though its arguments map nothing; and it is released - // outside this lock (the buffer's last release may run a deallocator). - let read: Vec = state.recorded[encoder] - .sparse - .splice(at..at + 1, updates) - .collect(); - state - .retained - .extend(read.into_iter().map(|update| Box::new(update) as Box<_>)); - } - Err(error) => { - state.step_failure = Some(recording_error(device, error)); - break; - } - } - } - indirect::degrade(device); - } - - /// A primary `VkCommandBuffer` from this command buffer's pool, made on first use. The - /// caller holds `state` (the pool is externally synchronized). - #[cfg_attr(test, track_caller)] - fn allocate_raw(&self, state: &mut State) -> Result { - self.allocate(state, vk::CommandBufferLevel::PRIMARY) - } - - /// End `state`'s tail, if it has one ([`State::tail`]). Where its batch ended (before part - /// `joined`, which just ended, or at the commit, `joined` `None`) and may end there - /// ([`State::may_fold`]), the batch's end goes into it first, as `submit.rs` would record it - /// in a command buffer of its own: the barrier to the host, then, at the commit of a timed - /// command buffer whose last batch it ends, the end timestamp. Elsewhere it ends as it is. - /// A failure to end it abandons the command buffer as an encoder's does (`encoder.rs`); at - /// the commit, it fails the command buffer's first submission, before any batch goes to the - /// queue. - fn close_tail(&self, state: &mut State, joined: Option) { - let Some(raw) = state.tail.take() else { - return; - }; - // A render pass instance its group left open in it ends first (`encoder_fold.rs`'s - // **Continued passes**). - if let Some(fold) = state.fold.as_mut().filter(|fold| fold.tail == raw) { - fold.end_open(); - } - let part = joined.unwrap_or(state.recorded.len()).saturating_sub(1); - let batch = state.batch_of(part); - let ended = joined.is_none_or(|joined| state.batch_of(joined) != batch); - let fold = ended && state.may_fold(&self.device, batch); - let last = joined.is_none() && batch + 1 == state.batches.all().len(); - let stamp = match (fold && last, &state.times.slot) { - (true, Some(slot)) => Some((slot.queries(), slot.first())), - _ => None, - }; - let device = self.device.shared().vk(); - if fold { - let reads = self.device.shared().memory_reads_of(self.queue.vk_queue()); - // SAFETY: the tail is recording, outside any render pass (its encoder's passes began - // and ended in its own recordings), and only this call records it, under the state - // lock; the slot's queries were reset by the batch's start, before it in submission - // order (`submit.rs`). - unsafe { - let end = crate::batch_order::end(self.device.shared().by_ends); - end.record_reading(device, raw, reads); - if let Some((queries, first)) = stamp { - let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; - device.cmd_write_timestamp(raw, bottom, queries, first + 1); - } - } - } - // SAFETY: as above. - match unsafe { self.end_raw(raw) } { - Ok(()) if fold => state.folds.push(Fold { - batch, - raw, - stamped: stamp.is_some(), - }), - Ok(()) => {} - Err(_) if joined.is_some() => state.abandoned = true, - Err(error) => { - let error = recording_error(&self.device, vulkan(error)); - state.step_failure.get_or_insert(error); - } - } - } - - /// End `raw`, a `VkCommandBuffer` of its pool, counted where it ended: its pool goes back to - /// the device's spares unreset only where every one the pool handed out ended (`spares.rs`). - /// - /// # Safety - /// As [`CommandBuffer::end_raw`]. - unsafe fn end_raw(&self, raw: vk::CommandBuffer) -> Result<(), vk::Result> { - // SAFETY: the caller's. - let ended = unsafe { self.device.shared().vk().end_command_buffer(raw) }; - if ended.is_ok() { - self.raws_ended.fetch_add(1, Ordering::Relaxed); - } - ended - } - - /// Give a command buffer without a pool yet (one that encoded nothing) a spare pool of the - /// device's where one is free, on the committing thread: its submissions, which record its - /// barriers inside sections where no spare is taken, then make no `VkCommandPool` of their - /// own (one made and destroyed per such command buffer before). Where none is free, or the - /// spare's reset fails, the submission makes one as before and answers any failure then. - fn take_spare_pool(&self, state: &mut State) { - if state.pool.is_some() { - return; - } - let shared = self.device.shared(); - let family = shared.queue_family_of(self.queue.vk_queue()); - if let Ok(Some(spare)) = shared.spares.command_pool(shared, family) { - state.pool = Some(spare); - } - } - - /// An encoder's command buffer of `level`, a driver's the encoder records into at each call: - /// one from this command buffer's pool ([`allocate`](Self::allocate)), or one of a - /// predicated loop's check's pool while it records again (`rerun.rs`). - #[cfg_attr(test, track_caller)] - fn allocate_encoder( - &self, - state: &mut State, - level: vk::CommandBufferLevel, - ) -> Result { - if let Some((context, _)) = &state.kept { - return context.hand_out(level).map(|(raw, _)| raw); - } - if let Some(pool) = &state.rerun_pool { - return hand_out(&self.device, &mut lock(pool), level); - } - self.allocate(state, level) - } - - /// A `VkCommandBuffer` of `level` from this command buffer's pools, its first made on first - /// use: a spare of the device's, or a new one. A command buffer a pool made before this - /// command buffer took it is handed out again before a new one is made; its begin resets it - /// (the pool's `VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`, `spares.rs`). Once its - /// pools handed out every one of `level` they held, it takes the spare holding the most of - /// them, up to `TAKEN_PAST_FIRST` past its first, inside a section of the exit guard one that - /// needs no reset; where none holds one, it makes what it lacks in the last it took, else in - /// its first, up to `POOL_HOLDS` of `level` there, past which it takes a pool for more, a - /// spare holding none of them or a new one; past `TAKEN_PAST_FIRST` it makes them in the last - /// (`spares.rs`). The caller holds `state` (the pools are externally synchronized). - #[cfg_attr(test, track_caller)] - fn allocate( - &self, - state: &mut State, - level: vk::CommandBufferLevel, - ) -> Result { - let first = self.pool(state)?; - if let Some(buffer) = first.reuse(level) { - return Ok(buffer); - } - for pool in state.pools_past_first.iter_mut().rev() { - if let Some(buffer) = pool.reuse(level) { - return Ok(buffer); - } - } - if state.pools_past_first.len() < crate::spares::TAKEN_PAST_FIRST { - let shared = self.device.shared(); - let family = shared.queue_family_of(self.queue.vk_queue()); - if let Some(spare) = shared.spares.command_pool_holding(shared, family, level)? { - state.pools_past_first.push(spare); - } else { - // No spare holds one: it grows in the last it took, else in its first, up to - // `POOL_HOLDS` of the level there. - let holds = match state.pools_past_first.last() { - Some(last) => last.holds(level), - None => self.pool(state)?.holds(level), - }; - if holds >= crate::spares::POOL_HOLDS { - state - .pools_past_first - .push(command_pool(&self.device, family)?); - } - } - } - match state.pools_past_first.last_mut() { - Some(last) => hand_out(&self.device, last, level), - None => hand_out(&self.device, self.pool(state)?, level), - } - } - - /// [`CommandBuffer::encoder_primary`]: a primary its pool's begin ahead missed counted - /// (`WorkCounts::encoder_primaries_begun_ahead_missed`). - fn encoder_primary(&self, state: &mut State) -> Result<(vk::CommandBuffer, bool), Error> { - match self.pool(state)?.open_encoder() { - Opened::Begun(buffer) => return Ok((buffer, true)), - Opened::Missed => (self.device.shared().counts).encoder_primary_begun_ahead_missed(), - Opened::Own => {} - } - Ok((self.allocate_raw(state)?, false)) - } - - /// This command buffer's pool, taken on first use: a spare of the device's, or a new one. - /// The caller holds `state` (the pool is externally synchronized). - fn pool<'a>(&self, state: &'a mut State) -> Result<&'a mut CommandPool, Error> { - if state.pool.is_none() { - let family = self.device.shared().queue_family_of(self.queue.vk_queue()); - state.pool = Some(command_pool(&self.device, family)?); - } - state - .pool - .as_mut() - .ok_or_else(|| internal("a command buffer without its command pool")) - } - - /// Ready `state`'s times at its commit, on the program's thread: where the device writes - /// timestamps, the slot of the device's timestamp pools the batches write its start and end - /// into. Without a slot free (and no pool more), it has no timestamps. Its calibration pair - /// is taken as it completes (`place_gpu_times`): no reading of the GPU's clock here. One - /// that encoded nothing and waits for nothing, and every one where the device answers GPU - /// times from the host, writes none (`gpu_time.rs`). - fn time(&self, state: &mut State) { - let shared = self.device.shared(); - let timing = &shared.timing; - if timing.clock().is_none() && !timing.answers_from_host() { - return; - } - let waits = state - .batches - .all() - .iter() - .any(|batch| !batch.waits.is_empty() || !batch.binary_waits.is_empty()); - if state.recorded.is_empty() && !waits { - state.times.stamped = Stamped::NoWork; - state.times.slot = None; - return; - } - if timing.answers_from_host() { - state.times.stamped = Stamped::FromHost; - return; - } - if !self.take_slot(state) { - state.times.stamped = Stamped::NoSlot; - } - } - - /// Whether `state` holds a slot of the device's timestamp pools: the one its first encoder - /// took as it opened, or one taken now; `false` where every slot is held and no pool more can - /// be made. - fn take_slot(&self, state: &mut State) -> bool { - if state.times.slot.is_some() { - return true; - } - let shared = self.device.shared(); - // SAFETY: the device is live. - let Some(slot) = (unsafe { shared.timing.slot(shared.vk(), &shared.counts) }) else { - return false; - }; - shared.counts.timestamp_slot_taken(); - state.times.slot = Some(slot); - true - } - - /// Where the device writes timestamps into slots of three queries and `raw`, just begun, is the - /// first `VkCommandBuffer` of the command buffer's first encoder, which opens its first batch: - /// take the slot now, and write the start into its third query as `raw`'s first commands, the - /// reset of the end and of that query (where the device does not reset the slot on the host as - /// it takes it), then the timestamp at the top of the pipe (`batch_order.rs`; `gpu_time.rs`). - /// The first batch's submission decides which start is read (`submit.rs`). - fn open_start(&self, state: &mut State, raw: vk::CommandBuffer) { - let timing = &self.device.shared().timing; - let first_batch = match state.batches.all() { - [batch] => batch.signals.is_empty() && batch.binary_signals.is_empty(), - _ => false, - }; - if !state.recorded.is_empty() - || !first_batch - || !timing.prefixed() - || timing.clock().is_none() - || timing.answers_from_host() - || !self.take_slot(state) - { - return; - } - let Some((queries, prefix)) = (state.times.slot.as_ref()) - .and_then(|slot| slot.prefix().map(|prefix| (slot.queries(), prefix))) - else { - return; - }; - let device = self.device.shared().vk(); - // SAFETY: `raw` was just begun, under the state lock, outside any render pass, and only - // this call records it now; the end's query is the one before the prefix's, and both are - // reset before the timestamp is written, on the host as the slot was taken or here - // (`vkCmdResetQueryPool`: "sets the status of query indices [firstQuery, firstQuery + - // queryCount - 1] to unavailable"). - unsafe { - if !timing.resets_on_host() { - device.cmd_reset_query_pool(raw, queries, prefix - 1, 2); - exit_guard::called(Call::CmdResetQueryPool); - } - let top = vk::PipelineStageFlags::TOP_OF_PIPE; - device.cmd_write_timestamp(raw, top, queries, prefix); - exit_guard::called(Call::CmdWriteTimestamp); - } - state.prefix = Some(raw); - } - - /// Read the command buffer's timestamps, now that its work completed, and give its slot - /// back: in the completion turn, inside its section. One read unavailable reads as no times - /// ([`Stamped::Read`], which its completion counts). - pub(super) fn read_stamps(&self) { - let mut state = lock(&self.state); - let Some(slot) = state.times.slot.take() else { - return; - }; - // The start its first batch wrote: the prefix's where its first encoder wrote it alone, - // else the one before the barriers (`gpu_time.rs`); then the end, after the first start. - let start = match (state.times.prefixed, slot.prefix()) { - (true, Some(prefix)) => prefix, - _ => slot.first(), - }; - let device = self.device.shared().vk(); - // Each query's value, then its availability. - let read = |query: u32| { - let mut result = [[0u64; 2]; 1]; - // SAFETY: the query was reset and written by work that completed; the result is - // 64-bit with availability, two words. - let read = unsafe { - device.get_query_pool_results( - slot.queries(), - query, - &mut result, - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WITH_AVAILABILITY, - ) - }; - exit_guard::called(Call::GetQueryPoolResults); - match read { - Ok(()) | Err(vk::Result::NOT_READY) => { - let [[value, available]] = result; - Ok((available != 0).then_some(value)) - } - Err(error) => Err(error), - } - }; - let read = read(start).and_then(|start| Ok(start.zip(read(slot.first() + 1)?))); - // A test's timestamps unavailable, as a driver's that has not made them available. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let read = match completion::trace::unstamped(self) { - true => read.map(|_| None), - false => read, - }; - state.times.stamped = match read { - Ok(both) => Stamped::Read(both), - Err(error) => Stamped::Failed(error), - }; - } - - /// Read its encoders' times, now that its work completed, where its device times its encoders - /// (`encoder_times.rs`), and give their slots back: in the completion turn, inside its - /// section, after its own timestamps were read. The lines due are said. - pub(super) fn read_encoder_times(&self) { - let shared = self.device.shared(); - let times = shared.timing.encoders(); - if !times.on() { - return; - } - let (timed, span) = { - let mut state = lock(&self.state); - let span = match state.times.stamped { - Stamped::Read(Some(span)) => Some(span), - _ => None, - }; - (std::mem::take(&mut state.times.encoders), span) - }; - let Some(clock) = shared.timing.clock().filter(|_| !timed.is_empty()) else { - return; - }; - // SAFETY: the device is live; the work that writes the slots' queries completed (this - // turn's), or never ran. - let lines = unsafe { times.completed(shared.vk(), clock, (self.id.get(), span), timed) }; - for line in lines { - self.device.inform(crate::encoder_times::ID_NAME, line); - } - } - - /// Publish the state's status, and its error where it failed, for `status` and `error` to - /// read ([`CommandBufferShared::status`]), under the state's lock, so in the order of its - /// transitions: the error first, set once (only the completion fails it, and nothing - /// follows that), then the status. - fn answer(&self, state: &State) { - if let Some(error) = state.error { - // Set at most once: a second set would be of the same completion's error. - let _ = self.error.set(error); - } - self.status - .store(status_word(state.status), Ordering::Release); - } - - /// Place its GPU times among its queue's, now that it completed: in the completion turn, - /// after its timestamps were read, in its queue's order (`gpu_time.rs`). One that wrote no - /// timestamps takes its times here: encoder-less, where its queue reached it; answered from - /// the host, the first submission that carried its work (its kernel end where one carried it - /// all; or its queue's latest end, where later) and its completion. Every one moves - /// its queue's latest GPU end: its own, or its completion where it has none (an upper bound - /// of its GPU end). One whose timestamps say its GPU work ran for over - /// `queue_share::LONG_HEAD`, or whose `VkQueue` held it for longer from the submission of a - /// batch of it that waited on the GPU for another `VkQueue`'s work to its GPU end, marks its - /// queue long, before the turn finishes it (`queue_share.rs`). - pub(super) fn place_gpu_times(&self) { - let shared = self.device.shared(); - let mut state = lock(&self.state); - let times = &mut state.times; - // Its GPU end in the host's time, where its timestamps were read and placed. - let mut gpu_end = None; - // The device's calibration pair, taken now, where the GPU that ran the work is awake - // (`gpu_time.rs`). - if let Stamped::Read(Some(_)) = times.stamped { - times.pair = shared.timing.pair(&shared.counts); - } - self.queue.place_gpu_times(|latest_end| { - let (kernel_end, completed) = (self.kernel.end(), times.completed); - match times.stamped { - Stamped::NoWork => { - let at = kernel_end.max(latest_end); - times.placed = Some((at, at)); - at - } - // From the first submission that carried its work, one after another, as Metal's - // serial queue can run them (`gpu_time.rs`). - Stamped::FromHost => { - let start = self.kernel.first_submitted().max(latest_end); - let end = completed.max(start); - times.placed = Some((start, end)); - end - } - Stamped::Read(Some((start, end))) => match shared.timing.clock() { - Some(clock) => { - let ((_, end), placement) = - clock.span(times.pair, start, end, life(&self.kernel, times)); - if let Placement::Disagreed { .. } = placement { - shared.counts.calibration_disagreed(); - } - gpu_end = Some(end); - end - } - None => completed, - }, - Stamped::Unread | Stamped::NoSlot | Stamped::Read(None) | Stamped::Failed(_) => { - completed - } - } - }); - let long = match (state.times.stamped, shared.timing.clock()) { - (Stamped::Read(Some((start, end))), Some(clock)) => { - clock.duration(start, end) > crate::queue_share::LONG_HEAD - || (state.times.waited_across.zip(gpu_end)).is_some_and(|(from, end)| { - end.saturating_sub(from) > crate::queue_share::LONG_HEAD - }) - } - _ => false, - }; - // Its GPU run, for its queue's expected one, which bounds the groups its batches join - // (`group.rs`): by its own timestamps, which bracket its own work alone, whatever else the - // GPU ran before it; where the device answers GPU times from the host, by those, which - // also hold the work of other `VkDevice`s the GPU ran meanwhile. - let run = match (state.times.stamped, shared.timing.clock()) { - (Stamped::Read(Some((start, end))), Some(clock)) => Some(clock.duration(start, end)), - (Stamped::FromHost, _) => (state.times.placed).map(|(start, end)| end - start), - _ => None, - }; - drop(state); - if let Some(run) = run { - self.queue.group_run().observed(run); - } - if long { - self.queue.went_long(); - } - } - - /// The scheduler submitted the last batch, or held it in a group (`group.rs`): in the queue's - /// context, once the submitting thread ran its submission handlers, set the scheduled signals' - /// values, in the order encoded, then become `Scheduled`, then run the scheduled handlers on - /// this thread, in the order added, then let `wait_until_scheduled` return. Metal's status - /// reads `Scheduled` just before its first scheduled handler starts, and its wait returns - /// once the last returned (an M4, macOS 27.0.1); its scheduled signals' values show before - /// its status reads `Scheduled` (an M3 Max, macOS 27.0.1). - /// - /// The step runs once: where its transition to `Completed` or `Error` ran first in its - /// queue's context, that one ran it first, and this one does nothing; one never owed (a - /// command buffer that failed before it was scheduled) runs none. Its submission handlers ran - /// before either: the transition to `Scheduled` goes to the context only once they ran - /// ([`schedule`](Self::schedule)), and one to `Completed` or `Error` that came first waited - /// behind a gate they open, its place kept, with no thread waiting - /// ([`gate_for_handlers`](Self::gate_for_handlers)). - fn run_scheduled(self: &Arc) { - { - let mut state = lock(&self.state); - if !state.scheduled_owed { - return; - } - state.scheduled_owed = false; - debug_assert!( - !state.submitting, - "a transition to `Scheduled` ran before its submission handlers" - ); - if !state.scheduled_signals.is_empty() { - // Set without the command buffer's lock: a set wakes the scheduler, whose lock - // comes first. - let signals = std::mem::take(&mut state.scheduled_signals); - drop(state); - for (event, value) in signals { - event.set(value); - } - state = lock(&self.state); - } - // Metal's dispatch and render work take their identifier allocations as the command - // buffer is scheduled, before its status reads so (`unique_identifier.rs`). - self.device - .shared() - .identifiers - .scheduled(state.scheduled_work); - state.status = CommandBufferStatus::Scheduled; - self.answer(&state); - } - let buffer = CommandBuffer(Arc::clone(self)); - { - let _running = Running::enter(self.marker(Step::ScheduledHandlers)); - loop { - let Some(handler) = lock(&self.state).scheduled.pop_front() else { - break; - }; - exit_guard::program(|| handler(&buffer)); - } - } - drop(buffer); - let parked = { - let mut state = lock(&self.state); - state.scheduled_ran = true; - state.parked > 0 - }; - self.wake_parked(parked); - } - - /// Wake the threads sleeping on `changed`, where `parked` (read under the state's lock the - /// change was made under) says one does: a thread that sleeps later looks at the change - /// first, and a notify is a system call, sleeper or not. Counted: - /// `WorkCounts::wakes_command_buffer_waiters`, `WorkCounts::wakes_spared`. - fn wake_parked(&self, parked: bool) { - self.device.shared().counts.command_buffer_wake(parked); - if parked { - self.changed.notify_all(); - } - } - - /// Its last batch was submitted, or held in a group: run its submission handlers on this - /// thread, which holds no lock of the runtime's (the one that took the batch, or a handler - /// thread it handed them to, `scheduler::Posted`), in the order added, then let its - /// transition to `Scheduled` run ([`CommandBuffer::add_submission_handler`]): where it was - /// held back for them ([`schedule`](Self::schedule)), it runs here or goes to its queue's - /// context now ([`scheduled_now`](Self::scheduled_now)); where its transition to `Completed` - /// or `Error` came first and waits behind a gate for them - /// ([`gate_for_handlers`](Self::gate_for_handlers)), the gate opens, and that one - /// runs the step to `Scheduled` first. - pub(crate) fn run_submission_handlers(self: &Arc) { - let buffer = CommandBuffer(Arc::clone(self)); - { - let _running = Running::enter(self.marker(Step::SubmissionHandlers)); - loop { - let Some(handler) = lock(&self.state).submission.pop_front() else { - break; - }; - exit_guard::program(|| handler(&buffer)); - } - } - drop(buffer); - let (parked, deferred, gate) = { - let mut state = lock(&self.state); - state.submitting = false; - // Its transition to `Completed` or `Error` that came first, waiting behind a gate in - // its queue's context, goes now and runs the step to `Scheduled` first; else its - // transition to `Scheduled`, held back for them, goes now. - let gate = state.finish_gate.take(); - let deferred = state.scheduled_deferred && state.scheduled_owed && gate.is_none(); - state.scheduled_deferred = false; - ( - state.parked > 0, - deferred.then(|| plain_transition(&state)), - gate, - ) - }; - self.wake_parked(parked); - if let Some(gate) = gate { - (self.device.shared().contexts).open(self.queue.id(), gate); - } else if let Some(plain) = deferred { - self.scheduled_now(plain); - } - } - - /// Its transition to `Completed` or `Error` goes to its queue's context behind `gate` (made - /// by the caller, which holds a closing of it until the transition is posted, - /// `Contexts::gate`): where its submission handlers have not run, its transition to - /// `Scheduled` still owed, the gate is closed once more for them, and the thread that runs - /// them opens it ([`run_submission_handlers`](Self::run_submission_handlers)). The transition - /// keeps its place, so its queue's later items stay behind it, as Metal completes a queue's - /// command buffers in order, and runs the step to `Scheduled` first; no thread waits for the - /// handlers meanwhile, so none of the handler threads, which may run them, is held by it. - fn finish_after_handlers(&self, contexts: &Contexts, gate: u64) { - let mut state = lock(&self.state); - if state.submitting && state.scheduled_owed && contexts.close(gate) { - state.finish_gate = Some(gate); - } - } - - /// Where its submission handlers have not run, its transition to `Scheduled` still owed: a new - /// gate for its transition to `Completed` or `Error`, closed once for the caller, who posts - /// the transition behind it and opens that closing (`Contexts::post_gated`), and once for the - /// handlers, whose thread opens it ([`run_submission_handlers`](Self::run_submission_handlers)). - /// `None` where they ran: the transition is posted plainly, and runs the step to `Scheduled` - /// first where that is still owed. - fn gate_for_handlers(&self, contexts: &Contexts) -> Option { - let mut state = lock(&self.state); - if !(state.submitting && state.scheduled_owed) { - return None; - } - let gate = contexts.gate(); - if contexts.close(gate) { - state.finish_gate = Some(gate); - } - Some(gate) - } - - /// Post the transition to `Completed` or `Error` of `buffer`, which moves into it, to its - /// queue's context: behind a gate its submission handlers open where they have not run - /// ([`gate_for_handlers`](Self::gate_for_handlers)), plainly otherwise, with one look for a - /// thread to run it either way. The caller keeps no other reference: once the transition - /// ran, the command buffer may go, with its device, on the handler thread. Its place there - /// (`Contexts::post`). - fn post_finished_transition( - contexts: &Contexts, - buffer: Hold, - result: Result<(), CommandBufferError>, - ) -> u64 { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let serves = contexts::serves_here(); - let (gate, queue) = (buffer.gate_for_handlers(contexts), buffer.queue.id()); - let item = Item::Transition(Transition::finished(buffer, result)); - let at = match gate { - Some(gate) => contexts.post_gated(queue, item, gate), - None => contexts.post(queue, item), - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - completion::trace::finished_posted(gate.is_some(), contexts::serves_here() - serves); - at - } - - /// Its batch `index` failed at its submission (a host step's recording or the `vkQueueSubmit` - /// among it, [`failed`](Self::failed)), so it and every later batch never run: the copies - /// taken at use their encoders took are given back (`State::give_back_from`). - pub(crate) fn never_runs_from(&self, index: usize) { - lock(&self.state).give_back_from(index); - } - - /// A batch could not be submitted (the scheduler dropped the rest): the command buffer - /// finishes with `error` (one committed on a revoked queue with its `AccessRevoked`) once - /// what it submitted before completed, at its `VkQueue`'s last - /// submitted value in `values`, and, where a command buffer ends at a fence - /// ([`fences::ends_at_fence`]), at one submitted after it, as a command buffer whose last - /// batch was submitted finishes; at the value alone when the queue takes no such fence (a - /// lost device). Its submission and scheduled handlers never run; they are dropped with it, - /// unless it became `Scheduled` as its last batch was held in a group (`group.rs`), or before - /// it behind its GPU hang (`hang.rs`) or behind a host step - /// ([`schedule_early`](Self::schedule_early)), which then fails from `Scheduled`. - pub(crate) fn failed(self: &Arc, error: CommandBufferError, values: &[u64]) { - let vk_queue = self.queue.vk_queue(); - { - let mut state = lock(&self.state); - // One committed on a queue Metal revoked answers `AccessRevoked` from its commit, as - // Metal's does, which no GPU work decides (`revocation.rs`): a refusal of its batches, - // a lost device's among them, leaves it so. - if state.failure != Some(CommandBufferError::AccessRevoked) { - state.failure = Some(error); - } - // Its hold's batch before the wait, not taken yet, never is (`hang.rs`). - if matches!( - state.hang_scheduling, - Some(hang::Scheduling::Hang { taken: false, .. }) - ) { - state.hang_scheduling = None; - self.changed.notify_all(); - } - } - let fence = fences::ends_at_fence(&self.device, vk_queue) - .then(|| self.fence_after_submitted(vk_queue)) - .flatten(); - self.device.shared().completion.watch( - vk_queue, - Submitted { - value: values[vk_queue], - buffer: self.hold(), - last: true, - fence, - signals: Vec::new(), - holds: Vec::new(), - after: Vec::new(), - held: false, - trail: None, - }, - ); - } - - /// A fence of the device's, submitted to `VkQueue` `queue` with no work: it is signaled once - /// everything submitted there before completed. `None` when the process is exiting or the - /// submission fails. A section of the exit guard of its own. - fn fence_after_submitted(&self, queue: usize) -> Option { - let _busy = exit_guard::enter()?; - let shared = self.device.shared(); - let raw = shared.vk(); - // SAFETY: the device's fences, inside a section. - let fence = unsafe { shared.fences.take(raw) }.ok()?; - // SAFETY: a submission of no batch with an unsignaled fence in no pending submission; - // the `VkQueue` is used under its lock. - shared.counts.queue_submitted(0, 0); - let submitted = shared.submit_logged( - (queue, None, 0, None), - Some(fence), - &self.relayed, - |vk_queue| unsafe { raw.queue_submit(vk_queue, &[], fence) }, - ); - exit_guard::called(Call::QueueSubmit); - match submitted { - Ok(()) => Some(fence), - Err(error) => { - let failed = Failed { - what: "a fence after the VkQueue's work, for a command buffer", - queue: Some(queue), - result: error, - infos: &[], - fence: Some(fence), - }; - submit_failed(&self.device, &failed, |carried, types| { - match try_lock(&self.state) { - Some(state) => self.carry(&state, (None, None), carried, types), - None => carried.buffers.push(format!("#{}", self.id.get())), - } - }); - // SAFETY: as for a failed batch's fence (`submit.rs`). - unsafe { release::object(raw, fence) }; - let _ = self.device.failed(error); - None - } - } - } - - /// The command buffer's last batch is submitted, or held in a group (`group.rs`), or it is - /// made `Scheduled` early ([`schedule_early`](Self::schedule_early)), on the - /// scheduler's thread under its lock: its transition to `Scheduled` is owed from now on - /// (`State::scheduled_owed`). Where it waits for its submission handlers, it goes to its - /// queue's context only once they ran, from the thread that runs them - /// ([`run_submission_handlers`](Self::run_submission_handlers)): parked in that context - /// meanwhile, it would hold every later item there, the completion of the queue's command - /// buffer before it among them, until then (on a Radeon 780M under a guest's steady commits, - /// up to a pass of that thread's submissions, 240 to 270 us each). Else it is scheduled now - /// ([`scheduled_now`](Self::scheduled_now)). - pub(crate) fn schedule(self: &Arc) { - let plain = { - let mut state = lock(&self.state); - state.scheduled_owed = true; - if state.submitting { - state.scheduled_deferred = true; - return; - } - plain_transition(&state) - }; - self.scheduled_now(plain); - } - - /// Its owed transition to `Scheduled` goes now: it runs here where it is - /// [`plain`](Transition::plain) (it has no scheduled handler, none is added after the commit, - /// and it waits for no submission handler) and its queue's context runs on no thread and holds - /// nothing (`Contexts::run_alone`): its status reads `Scheduled`, and `wait_until_scheduled` - /// returns, as its last batch goes or its submission handlers ran, with no handler thread - /// woken for it. Else it is posted to that context. The caller's own holds of the command - /// buffer outlive the transition's, so it never lets go of the last one here. Counted: - /// `WorkCounts::scheduled_where_submitted`. - fn scheduled_now(self: &Arc, plain: bool) { - let shared = self.device.shared(); - let item = Item::Transition(Transition { - buffer: self.hold(), - to: To::Scheduled, - plain, - where_seen: plain, - may_block: !plain, - }); - match shared.contexts.run_alone(self.queue.id(), item) { - Ok(()) => shared.counts.scheduled_where_submitted(), - Err(item) => { - shared.contexts.post(self.queue.id(), item); - } - } - } - - /// The scheduler's thread, under its lock, found the command buffer's remaining batches - /// waiting only for a host step of its queue's head behind work already submitted, and every - /// earlier command buffer of its queue `Scheduled` (`scheduler/mod.rs`, **Scheduled**): it - /// becomes `Scheduled` now, as Metal's does once its dependencies are resolved, before its - /// last batch is submitted ([`hang::Scheduling::Early`]), as the command buffers committed - /// behind a GPU hang are made early by the hang's thread (`hang.rs`, its - /// `Scheduling::Behind`): its kernel end now, its start too where no batch of it began, its - /// transition posted, which waits for its submission handlers where it has some, for the - /// caller to run once the scheduler's lock is free. `Some(true)` where it has them; - /// `Some(false)` where it has none, or was made so before; `None` where it is not made so: a - /// hang of its queue is in flight or holds it, whose thread orders the queue's `Scheduled` - /// (`hang.rs`), a switch of storage forms rides on it, which settles by its last batch's - /// submission, or it fails already. Counted: `WorkCounts::scheduled_behind_host_steps`. - pub(crate) fn schedule_early(self: &Arc) -> Option { - if hang::in_flight(&self.queue) || hang::holding(&self.queue) { - return None; - } - let handlers = { - let mut state = lock(&self.state); - match state.hang_scheduling { - Some(hang::Scheduling::Early) => return Some(false), - Some(_) => return None, - None if state.storage_form.is_some() || state.failure.is_some() => return None, - None => {} - } - state.hang_scheduling = Some(hang::Scheduling::Early); - let handlers = !state.submission.is_empty(); - state.submitting = handlers; - handlers - }; - if self.kernel.start() == 0 { - self.kernel.begin(); - } - self.kernel.end_at(gpu_time::host_nanos()); - self.schedule(); - self.device.shared().counts.scheduled_behind_host_step(); - Some(handlers) - } - - /// Whether a thread about to block for the command buffer's completion may submit a batch of - /// it itself (`scheduler::plain_ready`): nothing of the program's runs where it is submitted - /// and published. Its transition to `Scheduled` is [`plain`](plain_transition), it has no - /// submission handler, which runs once its last batch is taken, and - /// no switch of a fetched target's storage form rides on it, which that thread settles and - /// announces (`texture/storage_form.rs`). Handlers are refused once it is committed, so none - /// comes after this read ([`CommandBuffer::add_submission_handler`]). - pub(crate) fn submits_without_the_program(&self) -> bool { - let state = lock(&self.state); - plain_transition(&state) && state.submission.is_empty() && state.storage_form.is_none() - } - - /// Whether the thread that just committed it may submit a batch of it itself - /// (`scheduler::plain_ready`, `CommandBuffer::commit_and_submit`): no switch of a fetched - /// target's storage form rides on it, which the scheduler's thread settles and announces - /// (`texture/storage_form.rs`). That thread runs its submission handlers where it is that - /// thread's own command buffer, and hands them to the device's handler threads otherwise; a - /// transition to `Scheduled` with scheduled handlers goes to its queue's context. - pub(crate) fn submits_at_commit(&self) -> bool { - lock(&self.state).storage_form.is_none() - } - - /// The last batch of the command buffer `buffer` holds finished with `result` (or a batch - /// failed before): post its transition to `Completed` or `Error` to its queue's context, - /// behind its submission handlers where they have not run - /// ([`post_finished_transition`](Self::post_finished_transition)). The hold moves into the - /// transition, and the caller keeps no other reference: once the transition ran, the command - /// buffer may go, with its device, on the handler thread. - pub(crate) fn post_finished( - buffer: Hold, - result: Result<(), CommandBufferError>, - ) { - let contexts = buffer.device.shared().contexts.clone(); - let own = (lock(&buffer.state).release.as_ref()).map(|release| Arc::clone(&release.follow)); - let at = CommandBufferShared::post_finished_transition(&contexts, buffer, result); - if let Some(own) = own { - own.posted(at); - } - } - - /// The last batch of the command buffer `buffer` holds finished with `result`, as the queue - /// waiter on this thread saw: its transition to `Completed` or `Error` runs here, where it is - /// [`plain`](Transition::plain), or runs none of the program's code but its completion-seen - /// handlers ([`where_seen`](Transition::where_seen)) on a thread command buffers' completion - /// depends on (`exit_guard::serving_completion`), its queue's context runs on no thread and - /// holds only such items, which run here before it (`Contexts::run_here`), and the runtime - /// holds none of the program's objects a release drops or runs (`program_objects.rs`), so its - /// release runs none of the program's code. A thread waiting for it is then woken from here, - /// as Metal's completion wakes it, with no handler thread woken between. Else it is posted, as - /// [`post_finished`](Self::post_finished) posts it. - /// - /// Where the transition of a command buffer of another queue whose GPU signal it waited for has - /// not run up to its completed handlers and leads its context (nothing there before it may - /// block, `Run::may_block`), its own is posted behind a gate that transition opens there - /// (`Follow::follow`), its place in its own context kept: Metal's completion follows the GPU's - /// (`completion.rs`, "After what it waited for"). Behind an item there that may block, Metal - /// runs the other queue's transitions on, and so does this. - /// - /// The waiter takes no handle of the device here, and lets each transition's hold go short of - /// its command buffer's last reference ([`Transition::run`]): the device's last handle never - /// goes here, and none is left here once the gate opens. - pub(crate) fn finish_here( - buffer: Hold, - result: Result<(), CommandBufferError>, - ) { - let (contexts, queue) = (buffer.device.shared().contexts.clone(), buffer.queue.id()); - let (signallers, own): (Vec>, _) = { - let state = lock(&buffer.state); - let signallers = (state.waited.iter()) - .filter(|signaller| signaller.leads(&contexts)) - .cloned() - .collect(); - let own = (state.release.as_ref()).map(|release| Arc::clone(&release.follow)); - (signallers, own) - }; - // Its own transition is posted, or runs, below: another queue's command buffer that waited - // for its signal may follow it once it was posted, at its place. - let posted = |at| own.iter().for_each(|own| own.posted(at)); - if !signallers.is_empty() { - // Closed by this thread until the item is posted behind it. - let gate = contexts.gate(); - let mut behind = false; - for signaller in &signallers { - behind |= signaller.follow(&contexts, (queue, gate)); - } - if behind { - (buffer.device.shared().counts).command_buffer_completed_after_another_queue(); - } - buffer.finish_after_handlers(&contexts, gate); - let item = Item::Transition(Transition::finished(buffer, result)); - posted(contexts.post_behind(queue, item, gate)); - contexts.open(queue, gate); - return; - } - // A thread that may block for a command buffer runs none of the program's code here. A - // queue's waiter runs a transition with no completed handler here, and, of one with - // completed handlers and completion-seen handlers and no other queue's command buffer to - // complete after it (no `Follow`), its part to those handlers, posting the rest - // (`Transition::seen_first`): the handlers that may block run on the handler thread, and - // those that answer the completion where it is seen run where it is. - // - // Its transition to `Scheduled` still owed (`schedule`) is run first by this one, in its - // queue's context, never here; where its submission handlers have not run either, this - // one waits for them behind a gate they open, its place kept, holding no thread - // ([`gate_for_handlers`](Self::gate_for_handlers)). - let serving = exit_guard::serving_completion(); - let (seen_first, owed) = { - let state = lock(&buffer.state); - (seen_first(&state), state.scheduled_owed) - }; - if owed { - posted(CommandBufferShared::post_finished_transition( - &contexts, buffer, result, - )); - return; - } - let item = match serving && own.is_none() && seen_first { - true => Item::Transition(Transition::seen_first(buffer, result)), - false => Item::Transition(Transition::finished(buffer, result)), - }; - let may_run: fn(&Item) -> bool = match serving { - true => Item::runs_where_seen, - false => Item::plain, - }; - let item = match program_objects::Unheld::enter() { - Some(unheld) => { - let ran = contexts.run_here(queue, item, may_run); - drop(unheld); - match ran { - Ok(()) => return, - Err(item) => item, - } - } - None => item, - }; - posted(contexts.post(queue, item.whole())); - } - - /// Finish the command buffer with `result` (or the failure of a batch): take the device's - /// trail mark (`trails.rs`), set its status, decode its status words, run its completion-seen - /// handlers ([`complete_seen`](Self::complete_seen)), then its completed handlers on this - /// thread, give its queue's slot back, release its uploads, pools and heap versions, what it - /// retained and its encoders' logs, then open its gate, which releases its waiters once the - /// transition's [`Hold`] (and every other) is gone, and they wait for the trails below the - /// mark ([`complete_rest`](Self::complete_rest)). Waits from inside these steps answer as - /// [`own`] says. - fn complete(self: &Arc, result: Result<(), CommandBufferError>) { - let rest = self.complete_seen(result); - self.complete_rest(rest); - } - - /// The first part of [`complete`](Self::complete), to its completion-seen handlers: its - /// status final, they ran. What the rest needs is answered. - fn complete_seen(self: &Arc, result: Result<(), CommandBufferError>) -> Rest { - // A thread sleeps on `changed`, as the state's lock below reads. - let parked; - // Its first command pool, where it settled, posted to the device's begin-ahead thread once - // its completed handlers ran (below). - let mut settled_pool = None; - // The heap versions its commands bound, let go of once its completed handlers ran. - let released_versions; - // The holds its batches' commands took of buffers over host pages, let go of here, before - // its completed handlers run: dropped without the state's lock (`detach.rs`). - let submitted_holds; - // The holds kept for a group never submitted (`held_to_submission`), dropped with them. - let held_to_submission: Vec; - // Its sync file's semaphore, given back once its work ended (`sync_file.rs`). - #[cfg(unix)] - let sync_file; - // No rebind encodes it again from here: a group that was never submitted runs nothing. - self.device.shared().rebinds.no_replays(self); - { - let mut state = lock(&self.state); - // Every trail of the work it waited for (a pipeline's making, a twin's decode) was - // opened before its batches went, so before now: its waiters wait for those to close - // (`trails.rs`). - state.trail_mark = self.device.shared().trails.mark(); - // A failure the driver relayed for one of its batches is Metal's answer for its work - // (`device/relay.rs`). The device's loss is not: where a recovery from it answered - // already (`completion.rs`, its command buffers as the hang's victims, as its notice - // names them), that answer stands. - let recovered = result == Err(CommandBufferError::GpuRecoveryVictim); - let result = match (state.failure, self.relayed.failure()) { - (Some(error), _) => Err(error), - (None, Some((relay::DEVICE_REMOVED, _))) if recovered => result, - (None, Some((code, description))) => { - state.relayed_description = description; - Err(CommandBufferError::of_metal_code(code)) - } - (None, None) => result, - }; - // The hang a loss of the device named fails as the hang whichever of the loss's - // failures finished it (`hang_of_loss`): its last batch's, one its batch's refused - // submission set, or the scheduler's (`scheduler::fail_lost`). Counted against its - // queue as Metal counts a hang (`revocation.rs`). - let result = match result { - Err(CommandBufferError::DeviceLost | CommandBufferError::GpuRecoveryVictim) - if state.hang_of_loss => - { - Err(CommandBufferError::GpuHang) - } - result => result, - }; - // Its queue's timeline passed its last batch while a timestamp of it read - // unavailable: counted, its GPU times 0, and it completes. A signal with its - // timestamps unavailable is no loss of the GPU: an Intel UHD Graphics 630 (Windows - // driver 101.2145) read one so among a burst's 2,010 submissions, its device going on - // with no error (`gpu_time.rs`). - if result.is_ok() && state.times.stamped == Stamped::Read(None) { - self.device.shared().counts.command_buffer_unrun(); - } - let lost_hang = state.hang_of_loss && result == Err(CommandBufferError::GpuHang); - // The logs of host pages hear of its shadows' copies back and its writes in place - // again where its last batch's completion did not tell them (`completion.rs`), and let - // go of the holds a failed one's copies in set (`dirty_pages.rs`). - if self.device.shared().dirty.collects() { - let dirty = lock(&self.dirty); - (self.device.shared().dirty).completed(&dirty, result.is_err()); - } - match result { - Ok(()) => { - state.status = CommandBufferStatus::Completed; - // The queue's timeline reached the last batch's value, and every batch ends - // with a barrier to the host. - let words = state - .status_words - .as_ref() - .map_or(ExecutionStatus::initial(), Upload::read); - let mut report = ExecutionStatus::decode(&words); - if state.resident_misses != 0 { - report.resident_miss = true; - report.resident_misses = - report.resident_misses.wrapping_add(state.resident_misses); - } - if state.faults != ReplayFaults::default() { - report.replay_fault = true; - report.replay_faults = - ReplayFaults(report.replay_faults.0 | state.faults.0); - } - // An index bounds pass drew nothing of a draw its pool could not hold - // (`index_bounds.rs`): the command buffer failed. - if report.index_pool_overflow { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::IndexPoolOverflow); - } - // A unit of command predication ended with a live block open where its - // commands skipped (`predication.rs`): Metal's GPU recovery failed the command - // buffer. - if let (Some(record), None) = - (state.predication.open_at_unit_end(), state.error) - { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::PredicationOpenAtUnitEnd { record }); - state.relayed_description = Some( - CommandBufferError::PREDICATION_OPEN_AT_UNIT_END_DESCRIPTION.to_owned(), - ); - } - // An indirect mesh draw's object grid was one Metal's GPU discards - // (`render/mesh_arguments.rs`): the command buffer failed as Metal's. - if report.mesh_grid_discarded && state.error.is_none() { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::GpuRecoveryVictim); - } - // A mesh draw's grid lay past what the device launches - // (`render/mesh_arguments.rs`): the command buffer failed. - if (report.mesh_grid_past_limits || state.mesh_grid_past) - && state.error.is_none() - { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::MeshGridPastLimits); - } - // A scanned emulated mesh draw drew nothing of records its pool could not - // hold (`render/mesh.rs`): the command buffer failed. - if let Some(fault) = report.mesh_records_overflow { - let budget = state.mesh_pool.as_ref().map_or(0, PoolLease::bytes); - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::MeshRecordsOverflow( - MeshRecordsOverflow { - draw: fault.draw, - object_threadgroups: fault.object_threadgroups, - mesh_threadgroups: fault.mesh_threadgroups, - budget, - }, - )); - } - // A scanned emulated tessellation draw drew nothing of records the same pool - // could not hold (`render/tessellation_scan.rs`): the command buffer failed. - if let Some(fault) = report.tessellation_records_overflow { - let budget = state.mesh_pool.as_ref().map_or(0, PoolLease::bytes); - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::TessellationRecordsOverflow( - TessellationRecordsOverflow { - draw: fault.draw, - records: fault.records, - budget, - }, - )); - } - // A function that read an argument its function constants removed took zero - // for it, Metal's answer under its debug layer: the command buffer completes, - // and its report states the read. A function sampled through a cubic sampler an - // argument buffer named, whose bicubic filter it does not emulate there: no - // result is then Metal's. - if report.cubic_argument_sampler && state.error.is_none() { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::CubicArgumentSampler); - } - state.report = Some(report); - } - // One committed on the queue of the hang a loss named, before the recovery, ran - // nothing and completes with no error (`held_by_lost_hang`). - Err(_) if state.held_by_lost_hang => { - state.status = CommandBufferStatus::Completed; - } - Err(error) => { - state.status = CommandBufferStatus::Error; - // Its device lost, where the device's line recovers past it, it fails as a - // victim of the GPU's recovery, as Metal's command buffers in flight there do - // (`device/line.rs`). - let victim = error == CommandBufferError::DeviceLost - && (self.device.line()).recovers_past(self.device.shared().generation); - state.error = Some(match victim { - true => CommandBufferError::GpuRecoveryVictim, - false => error, - }); - } - } - // A GPU error the command buffer caused counts against its queue, which Metal revokes - // at the second, from before its status reads final (`revocation.rs`); a relayed one - // is the driver's queue's. - let caused = match lost_hang { - true => Some(CommandBufferError::GpuHang), - false => state.failure, - }; - self.queue.errors().completed(caused); - // An injected page fault or hang stands for it: the GPU recovers from it now, which - // ends a predicated loop running meanwhile (`recovery.rs`). - if let Some(recovered) = state.failure.and_then(recovery::injected) { - self.device.shared().recoveries.raise(recovered); - } - // The final status, with its error, once: a read sees no `Completed` that a decoded - // failure turns to `Error`. - self.answer(&state); - state.status_words = None; - // Its heap versions, uploads, pools and descriptor pools go once its completed - // handlers ran (below). - released_versions = state.heaps.clear(); - // Its work ended, so nothing of it holds a buffer over host pages any longer: every - // hold goes as its completion is processed, before its completed handlers run, as - // Metal releases what a completion processes (`detach.rs`). A buffer's detach waiting - // for its work answers `false`; one made from here on detaches. Dropped below, - // without this lock, which no hold may be let go under (`Rebinds::wait_ran`). - submitted_holds = state.holds_until(usize::MAX); - // A group never submitted runs nothing: no rebind fails it from here. - held_to_submission = std::mem::take(&mut state.held_to_submission); - // Its work ended (its fences were signaled, or its queues drained after a failed - // wait), so nothing of its pools is pending: its command pool goes to the device's - // spares whatever its status, never released on this thread (`spares.rs`); its - // descriptor pools go once its completed handlers ran (below). - let mut pools = state.pools(); - if !pools.is_empty() { - // None of the pools' command buffers is recording where it completed and ended - // every one the pools handed out: a recording it left unused leaves one so. - let ended = self.raws_ended.load(Ordering::Relaxed); - let handed: usize = pools.iter().map(CommandPool::handed_out).sum(); - let settled = state.status == CommandBufferStatus::Completed - && u64::try_from(handed).is_ok_and(|handed| handed == ended); - // Its first, whose primaries its encoders took, is posted to the device's - // begin-ahead thread once its completed handlers ran (below, `begin_ahead.rs`). - if settled { - pools[0].begin_ahead_due(); - settled_pool = Some(pools[0].raw); - } - let shared = self.device.shared(); - let recorded = self.recorded.load(Ordering::Relaxed); - for pool in pools { - shared - .spares - .give_command_pool(shared, pool, settled, recorded); - } - } - state.unplaced(); - #[cfg(unix)] - { - sync_file = state.take_sync_file(); - } - parked = state.parked > 0; - } - // The holds taken above go here, with no lock of the command buffer's held, before any - // handler of its runs: a detach from one of them detaches (`detach.rs`). - drop(submitted_holds); - drop(held_to_submission); - #[cfg(unix)] - self.release_sync_file(sync_file); - self.wake_parked(parked); - let buffer = CommandBuffer(Arc::clone(self)); - // Its completion-seen handlers first, on this thread, its status final: the thread that - // saw it complete where this transition runs there, else its queue's handler thread - // (`CommandBuffer::add_completion_seen_handler`). - { - let _running = Running::enter(self.marker(Step::CompletionSeenHandlers)); - let where_seen = !contexts::on_handler_thread(); - loop { - let Some(handler) = lock(&self.state).seen.pop_front() else { - break; - }; - self.device - .shared() - .counts - .completion_seen_handler_ran(where_seen); - exit_guard::program(|| handler(&buffer)); - } - } - Rest { - settled_pool, - released_versions, - } - } - - /// The rest of [`complete`](Self::complete), once its status is final and its completion-seen - /// handlers ran ([`complete_seen`](Self::complete_seen)): its completed handlers, its queue's - /// slot, its releases and its gate. - fn complete_rest(self: &Arc, rest: Rest) { - let Rest { - settled_pool, - released_versions, - } = rest; - let buffer = CommandBuffer(Arc::clone(self)); - // Its status is final and its completion-seen handlers, which never block, ran: the - // command buffers of other queues that waited on the GPU for its signals complete from here - // on, after it, as its completed handlers start, which may block (`follow.rs`). - let release = lock(&self.state).release.take(); - if let Some(Release { follow, signals }) = release { - for (event, index) in signals { - event.released(index); - } - follow.release(&self.device.shared().contexts); - } - // Each handler leaves the queue under the lock and runs without it, in the order added - // (a handler may query the command buffer). - { - let _running = Running::enter(self.marker(Step::CompletedHandlers)); - loop { - let Some(handler) = lock(&self.state).completed.pop_front() else { - break; - }; - exit_guard::program(|| handler(&buffer)); - } - } - let handled = Instant::now(); - drop(buffer); - // Its queue's slot comes back as its last completed handler returns, as Metal's does: a - // make blocked on its full queue returns then, never while a completed handler runs, nor - // from one on its own full queue, and does not wait for what the commands used to be - // released below (a no-copy buffer's deallocator may run long there); a make after - // `wait_until_completed` returned never blocks (probe `slotdealloc`: - // `queue.rs`). - let slot = lock(&self.slot).take(); - drop(slot); - let nanos = u64::try_from(handled.elapsed().as_nanos()).unwrap_or(u64::MAX); - self.device.shared().counts.slot_returned(nanos); - // What the commands used goes after the completed handlers, as Metal releases it (a - // no-copy buffer's deallocator runs after them), and before the gate opens, so a waiter - // returns after it, but for the frees of host imports posted to the free thread (below), - // whose deallocators and keep-alives run after their frees there. Each leaves under the - // lock and drops without it. - { - let _running = Running::enter(self.marker(Step::Release)); - // A host import it lets go of last, a deallocator or a keep-alive waiting for its - // free, is freed on the device's free thread, paced (`free_thread.rs`): this thread - // runs the next command buffers' completed handlers. - let _frees = crate::free_thread::AtCompletion::enter(); - // Its live buffers' tables first: a buffer whose last hold goes below then counts - // only the tables of other command buffers, which may still reach its pages, as - // holding them past its release (`HostPages::released_listed`); this one's wait ends - // here, at its completion, where Metal's hold of what it retained ends too. - let resident = lock(&self.state).resident.take(); - drop(resident); - loop { - let Some(table) = lock(&self.state).stepped_tables.pop() else { - break; - }; - drop(table); - } - // Its batches' kept footprints, whose probes hold their segments' work (`Footprints`): - // nothing asks for one once it completed. Before what it retained, which holds that - // work too, so the work goes with what it retained. - self.footprints.let_go(); - // Its resource state encoders' updates, which their batches bound as they were - // submitted (`submit.rs`) and nothing reads since: the textures they map and an - // indirect update's buffer, which Metal lets go of as it completes. - let updates: Vec = (lock(&self.state).recorded.iter_mut()) - .flat_map(|part| part.sparse.drain(..)) - .collect(); - drop(updates); - loop { - let Some(resource) = lock(&self.state).retained.pop() else { - break; - }; - drop(resource); - } - // Its encoders' logs go here too, those they kept and those held for its commit - // (`fold.rs`), cleared without the state's lock (`replay.rs`): they hold what their - // calls named, which Metal holds until the command buffer completed (a binding - // replaced before any command among it), and no thread but this one may hold such a - // handle past the completion. Its state keeps the compute ones, as many as it keeps, - // for the compute encoders of the command buffer that takes it next - // (`spare_states.rs`); the rest go back to the device's spares. - let logs: Vec> = (lock(&self.state).ended.iter_mut()) - .filter_map(|record| record.replay.take()) - .collect(); - let held = lock(&self.state).unsplit_logs(); - let spares = self.device.shared().scheduler.spare_logs(); - let logs = logs.into_iter().filter_map(Arc::into_inner).chain(held); - let compute = spares.cleared_compute(logs); - let unkept = match compute.is_empty() { - true => compute, - false => lock(&self.state).keep_compute_logs(compute), - }; - spares.give_compute(unkept); - let residency = lock(&self.state).residency.take(); - drop(residency); - let residencies = lock(&self.state).let_go_of_uses(); - drop(residencies); - let check = lock(&self.state).check.take(); - drop(check); - // Then the runtime's own: its uploads, its index and mesh records pools' blocks, its - // heap versions and its descriptor pools, none of them the program's, last. Each may - // take a driver's lock as it goes (MoltenVK's `vkDestroyBuffer`, `vkFreeMemory` and - // `vkDestroyDescriptorPool` take the lock of its device's residency set, which its - // `vkBindBufferMemory` holds across a commit that took 24 to 39 ms for a 1 GiB block - // on the M3 Max, `gpu_pools.rs`), so they go after the completed handlers, which wait - // for none of them, and after what the program's commands used. - let (uploads, index_pool, mesh_pool, mut descriptors, completed) = { - let mut state = lock(&self.state); - ( - state.uploads.take(), - state.index_pool.take(), - state.mesh_pool.take(), - state.descriptors.take(), - state.status == CommandBufferStatus::Completed, - ) - }; - drop((uploads, index_pool, mesh_pool, released_versions)); - // A command buffer that completed gives its descriptor pools back to the device's - // spares; one that failed releases them. - if completed { - descriptors.give_back(); - } else { - descriptors.release(); - } - } - // The gate notifies its waiters only where it opened here, which this transition's own - // hold holds it from: the notify for them is that hold's, as it goes (`gate.rs`). - let notified = self.gate.finish(); - self.device.shared().counts.command_buffer_wake(notified); - // Its pool's primaries begun ahead, where no command buffer took the pool since - // (`spares.rs`), on the device's begin-ahead thread: this thread only posts the pool, so - // neither a waiter's return nor the queue's next transitions wait for a begin - // (`begin_ahead.rs`). - if let Some(pool) = settled_pool { - let shared = self.device.shared(); - (shared.begin_ahead).post(pool, || shared.spares.begin_targets(shared)); - } - } -} - -/// A command buffer's transition, run in its queue's context. -pub(crate) struct Transition { - /// The command buffer, held until the transition ran. - buffer: Hold, - to: To, - /// It runs none of the program's code but what a release of the program's objects runs - /// (`program_objects.rs`): no handler and no notice. - plain: bool, - /// It runs none of the program's code but that and its completion-seen handlers, which a - /// thread that saw its command buffer complete may run - /// ([`CommandBuffer::add_completion_seen_handler`]): plain, a transition to `Completed` - /// with no completed handler, or one that runs to its completion-seen handlers ([`To::Seen`]). - where_seen: bool, - /// It may block a thread that runs it, or wait for the program before it runs - /// (`Run::may_block`): it runs a scheduled or completed handler of its command buffer's, or - /// waits for a submission handler. Another queue's transition waits behind one that does - /// neither (`follow.rs`). - may_block: bool, -} - -/// The status a transition goes to. -enum To { - Scheduled, - /// `Completed`, or `Error`. - Finished(Result<(), CommandBufferError>), - /// `Completed`, or `Error`, run by a queue's waiter to its completion-seen handlers, the rest - /// posted to its queue's context behind it ([`Transition::seen_first`]). Never posted itself: - /// where it cannot run where seen it goes whole ([`Item::whole`]). - Seen(Result<(), CommandBufferError>), - /// The rest of a transition to `Completed` or `Error` that ran to its completion-seen handlers - /// where seen: its completed handlers, its releases and its gate, on a handler thread. - Rest(Rest), -} - -/// What a command buffer's transition to `Completed` or `Error` still does once its status is -/// final and its completion-seen handlers ran (`CommandBufferShared::complete_rest`). -pub(crate) struct Rest { - /// Its first command pool, where it settled, whose primaries the device's begin-ahead thread - /// begins once its completed handlers ran (`begin_ahead.rs`). - settled_pool: Option, - /// The heap versions its commands bound, let go of once its completed handlers ran. - released_versions: Vec>, -} - -impl Transition { - /// The transition of the command buffer `buffer` holds to `Completed` or `Error`, with - /// `result`: it runs where seen where it has no completed handler, and is plain where it has - /// no completion-seen handler either (none is added after the commit). It may block where it - /// has a completed handler, or a scheduled or submission handler not run yet, whose step it - /// may run or wait for ([`run_scheduled`](CommandBufferShared::run_scheduled)). - fn finished(buffer: Hold, result: Result<(), CommandBufferError>) -> Self { - let (where_seen, plain, may_block) = { - let state = lock(&buffer.state); - let where_seen = state.completed.is_empty(); - let may_block = !(where_seen && plain_transition(&state)); - (where_seen, where_seen && state.seen.is_empty(), may_block) - }; - Transition { - buffer, - to: To::Finished(result), - plain, - where_seen, - may_block, - } - } - - /// The transition of the command buffer `buffer` holds to `Completed` or `Error`, with - /// `result`, for a queue's waiter to run where its command buffer has completed handlers and - /// completion-seen handlers: its status and completion-seen handlers where seen, the rest - /// ([`To::Rest`]) posted to its queue's context, which it runs, so the queue's later items wait - /// for it (`CommandBufferShared::finish_here`). - fn seen_first( - buffer: Hold, - result: Result<(), CommandBufferError>, - ) -> Self { - Transition { - buffer, - to: To::Seen(result), - plain: false, - where_seen: true, - may_block: false, - } - } - - fn run(self) -> Kept { - let on_handler_thread = contexts::on_handler_thread(); - let Transition { buffer, to, .. } = self; - match to { - To::Scheduled => buffer.run_scheduled(), - To::Finished(result) => { - if !on_handler_thread { - buffer.device.shared().counts.completed_where_seen(); - } - // Its step to `Scheduled`, where its own transition has not run it yet: Metal's - // command buffer reads `Scheduled`, and runs its scheduled handlers, before it - // completes (`schedule`). - buffer.run_scheduled(); - buffer.complete(result); - } - To::Seen(result) => { - buffer.device.shared().counts.completed_where_seen(); - let rest = buffer.complete_seen(result); - // Posted while this thread runs the queue's context (`Contexts::run_here`): it - // runs there next, on a handler thread, and the queue's later items after it. Its - // own hold keeps the gate shut until it ran. - let rest = Item::Transition(Transition { - buffer: buffer.hold(), - to: To::Rest(rest), - plain: false, - where_seen: false, - may_block: true, - }); - (buffer.device.shared().contexts).post(buffer.queue.id(), rest); - } - To::Rest(rest) => buffer.complete_rest(rest), - } - // The hold goes after the transition, once its context is done with it: the gate opens - // then. On a queue's waiter (`CommandBufferShared::finish_here`) it goes short of the - // command buffer's last reference, which holds the device: that last one goes on a - // handler thread, so the device's teardown, which stops the waiters, never runs on one, - // and the waiter holds nothing of the device once the gate opened, so a program's drop - // after its wait is the device's last. - if on_handler_thread { - return Kept { - _hold: Some(buffer), - _count: None, - }; - } - match buffer.let_go_short_of_last() { - Ok(count) => Kept { - _hold: None, - _count: Some(count), - }, - Err(last) => { - let (contexts, context) = last.device.elsewhere(); - contexts.post(context, Item::Release(last)); - Kept::default() - } - } - } -} - -/// What an item kept once it ran, which its runner lets go of once the item's context is done -/// with it (`Run::Held`): a transition's hold of its command buffer, whose going opens the -/// command buffer's gate where it finished, so its waiters return only once its context runs -/// nothing of it (`command_buffer/follow.rs`). -#[derive(Default)] -pub(crate) struct Kept { - /// The hold, on a handler thread: its reference may be the command buffer's last. - _hold: Option>, - /// Elsewhere, the hold's place in its gate's count, its reference let go of short of the last - /// (`Hold::let_go_short_of_last`). Neither, for a release, and for a transition whose hold was - /// its command buffer's last, which went to a context of its own with its count. - _count: Option, -} - -/// An item of the device's handler threads (`contexts`). -pub(crate) enum Item { - /// A command buffer's transition, in its queue's context. - Transition(Transition), - /// What a thread that may run none of the program's code let go of, dropped in a context of - /// its own (`Device::let_go_elsewhere`): it holds no command buffer, so nothing waits for it - /// and it waits for nothing. - Release(Box), - /// Submission handlers a pass of the scheduler's thread took, handed to the handler threads - /// in a context of their own (`scheduler::Posted`): they run in their turn, in submission - /// order, and each command buffer's transition to `Scheduled` goes after its own. - Submissions(crate::scheduler::Posted), -} - -impl Item { - /// The item to post where a queue's waiter could not run it: a transition to its - /// completion-seen handlers ([`To::Seen`]) goes whole, its completed handlers and all, to its - /// queue's handler thread. - fn whole(self) -> Item { - match self { - Item::Transition(Transition { - buffer, - to: To::Seen(result), - .. - }) => Item::Transition(Transition { - buffer, - to: To::Finished(result), - plain: false, - where_seen: false, - may_block: true, - }), - item => item, - } - } -} - -impl Run for Item { - type Held = Kept; - - fn run(self) -> Kept { - match self { - Item::Transition(transition) => transition.run(), - Item::Release(held) => { - drop(held); - Kept::default() - } - Item::Submissions(posted) => { - posted.run(); - Kept::default() - } - } - } - - fn plain(&self) -> bool { - match self { - Item::Transition(transition) => transition.plain, - Item::Release(_) | Item::Submissions(_) => false, - } - } - - fn runs_where_seen(&self) -> bool { - match self { - Item::Transition(transition) => transition.where_seen, - Item::Release(_) | Item::Submissions(_) => false, - } - } - - fn may_block(&self) -> bool { - match self { - Item::Transition(transition) => transition.may_block, - Item::Release(_) | Item::Submissions(_) => true, - } - } -} - -/// Whether a queue's waiter runs a command buffer's transition to `Completed` or `Error` to its -/// completion-seen handlers and posts the rest ([`Transition::seen_first`]): it has completed -/// handlers, which may block, and completion-seen handlers, which answer the completion where it -/// is seen. None is added after the commit. -fn seen_first(state: &State) -> bool { - !state.completed.is_empty() && !state.seen.is_empty() -} - -/// Whether a command buffer's transition runs none of the program's code ([`Transition::plain`]): -/// it has no scheduled handler, none is added after its commit, and it waits for no submission -/// handler. -fn plain_transition(state: &State) -> bool { - state.scheduled.is_empty() && !state.submitting -} - -/// Whether `wait_until_scheduled` returns: the command buffer's scheduled handlers ran (Metal's -/// wait returns only then), or it finished, or failed without being scheduled. -fn scheduled(state: &State) -> bool { - state.scheduled_ran - || matches!( - state.status, - CommandBufferStatus::Completed | CommandBufferStatus::Error - ) -} - -/// A command pool of `device` for queue family `family`: a spare of the device's (outside a -/// section of the exit guard), or a new one, whose command buffers are reset as they are begun -/// again (`spares.rs`). -pub(super) fn command_pool(device: &Device, family: u32) -> Result { - let shared = device.shared(); - if let Some(spare) = shared.spares.command_pool(shared, family)? { - return Ok(spare); - } - let info = vk::CommandPoolCreateInfo::default() - .flags( - vk::CommandPoolCreateFlags::TRANSIENT - | vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, - ) - .queue_family_index(family); - // SAFETY: the device is live and `info` valid. - let pool = unsafe { shared.vk().create_command_pool(&info, None) }; - exit_guard::called(Call::CreateCommandPool); - shared.counts.command_pool_made(); - Ok(CommandPool::new(pool.map_err(vulkan)?, family)) -} - -/// A `VkCommandBuffer` of `level` from `pool`, of `device`: one it made before and has not -/// handed out since it was taken, whose begin resets it, else a new one. The caller holds the -/// pool alone (Vulkan synchronizes it externally). -#[cfg_attr(test, track_caller)] -pub(super) fn hand_out( - device: &Device, - pool: &mut CommandPool, - level: vk::CommandBufferLevel, -) -> Result { - if let Some(buffer) = pool.reuse(level) { - return Ok(buffer); - } - let info = vk::CommandBufferAllocateInfo::default() - .command_pool(pool.raw) - .level(level) - .command_buffer_count(1); - let buffer = device.allocate_command_buffers(&info)?[0]; - pool.made(level, buffer); - Ok(buffer) -} - -/// The command-buffer error of a barrier command buffer that could not be allocated, or of a -/// recording that failed otherwise (a heap texture's moves' images, `EncoderCore::sample_moves`), -/// recording a lost device. `allocate_raw` fails only with a Vulkan result; any other error is -/// internal, `VK_ERROR_UNKNOWN` as a submission's would be. Either is logged as a warning -/// (`submit_failure.rs`, id name `metal2vulkan-recording-failed`) with the error it was, which -/// the command buffer's error does not keep: so a command buffer failed with a raw `VkResult` -/// says whether its `vkQueueSubmit` failed (that call's own line) or its recording did. -pub(super) fn recording_error(device: &Device, error: Error) -> CommandBufferError { - let failed = match error { - Error::DeviceLost => return submission_error(device, vk::Result::ERROR_DEVICE_LOST), - Error::OutOfMemory(_) => return CommandBufferError::OutOfMemory, - Error::Vulkan(code) => CommandBufferError::Internal(code), - _ => CommandBufferError::Internal(super::error::VkResultCode( - vk::Result::ERROR_UNKNOWN.as_raw(), - )), - }; - let text = format!( - "metal2vulkan: a command buffer's recording failed: {error} ({error:?}); it fails as \ - {failed:?}, with no vkQueueSubmit" - ); - crate::submit_failure::warn(device, RECORDING_FAILED, text); - failed -} - -/// The id name of a failed recording's warning ([`recording_error`]). -pub(crate) const RECORDING_FAILED: &str = "metal2vulkan-recording-failed"; - -/// The command-buffer error of a host step whose recording failed with `error`: a refusal, what -/// `commit` refuses where the CPU wrote the records, is [`CommandBufferError::Refused`], kept in -/// `refusal`; a Vulkan failure, a lost device, memory, and the runtime's own broken invariant fail -/// it as a recording does ([`recording_error`]). -fn step_error(device: &Device, error: Error, refusal: &mut Option) -> CommandBufferError { - let refused = match &error { - Error::Compile(metal2vulkan::error::Error::Internal(_)) => false, - Error::Invalid(_) - | Error::Unsupported(_) - | Error::Bind(_) - | Error::Compile(_) - | Error::NotImplemented(_) - | Error::AppleOnly(_) - | Error::SamplerLimit(_) => true, - _ => false, - }; - if !refused { - return recording_error(device, error); - } - *refusal = Some(error); - CommandBufferError::Refused -} - -/// The command-buffer error of a failed submission, recording a lost device. -fn submission_error(device: &Device, error: vk::Result) -> CommandBufferError { - match device.failed(error) { - Error::DeviceLost => CommandBufferError::DeviceLost, - Error::OutOfMemory(_) => CommandBufferError::OutOfMemory, - _ => CommandBufferError::Internal(super::error::VkResultCode(error.as_raw())), - } -} - -/// The life of the command buffer whose kernel times are `kernel` and other times `times`, as its -/// timestamps are checked against it (`gpu_time.rs`, `GpuClock::span`). -fn life(kernel: &KernelTimes, times: &Times) -> Life { - Life { - kernel_start: kernel.start(), - completed: times.completed, - } -} - -#[cfg(debug_assertions)] -thread_local! { - /// The locks this thread took of command buffers' states (`CommandBuffer::state`), in builds - /// with debug assertions. - static STATE_LOCKS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// How many command buffers' states this thread locked so far (`CommandBuffer::state`). -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn state_locks() -> u64 { - STATE_LOCKS.with(std::cell::Cell::get) -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/own.rs b/crates/metal2vulkan-runtime/src/command_buffer/own.rs deleted file mode 100644 index f24603650..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/own.rs +++ /dev/null @@ -1,253 +0,0 @@ -//! Waits from inside the runtime's handler threads: what a command buffer wait answers when it is -//! called from a scheduled handler, a completed handler, or a deallocator that runs as a command -//! buffer releases what it retained. -//! -//! Those run in their queue's serial context ([`contexts`](crate::contexts)): a queue's -//! transitions to `Scheduled` and to `Completed`, with their handlers, run one at a time in the -//! queue's order. A wait there for a transition still to come in the same queue would wait for -//! itself. -//! -//! Metal's answers (measured on an M4 with macOS 27.0.1, with and without API validation): -//! - a deallocator run as Metal releases a buffer returns from its wait for the completion of the -//! command buffer that held it; the runtime returns too; -//! - a completed handler returns from its wait for its command buffer's scheduling; so does the -//! runtime (that transition ran before); -//! - a handler's wait for its own command buffer's transition in progress, and for any later -//! transition of its queue (a command buffer committed after its own, before or inside the -//! handler), never returns, even when that command buffer's work already ran. The runtime does -//! not copy the hang: it refuses those waits at once (`Error::WaitWouldDeadlock` of -//! `DeadlockCause::OwnQueue`, or `TimedOut` for the bounded wait); -//! - a handler's wait for a command buffer of another queue returns, whether that command buffer -//! was committed before the handler or inside it; so does the runtime's. It blocks the handler's -//! thread, counted ([`Waits`]), and is refused only where it would deadlock: when it would -//! close a cycle of such waits, or leave its device's pool with no thread that is not blocked -//! so (`contexts::block`). -//! -//! A submission handler (a runtime extension, Metal has none) runs on the thread that took its -//! command buffer's last batch for its queue, and that command buffer's transition to `Scheduled`, -//! with every later transition of its queue, waits for it. On the scheduler thread, the device's -//! later submissions wait for it too. So any wait there for what has not happened (a command -//! buffer's scheduling or completion, a slot of a full queue no uncommitted command buffer holds) -//! is refused at once (`DeadlockCause::SubmissionHandler`); one for what happened returns. -//! -//! A completion-seen handler (a runtime extension, Metal has none) runs as its command buffer's -//! transition to `Completed` runs: on the thread that saw the command buffer complete (a queue's -//! waiter, the scheduler's thread, or the committing thread for one that needs no GPU work) where -//! that transition runs there, else on its queue's handler thread. That thread's turn finishes -//! every queue's command buffers, so a wait there for what has not happened would wait for itself, -//! and its waits are refused as a submission handler's are, wherever it runs -//! (`DeadlockCause::CompletionSeenHandler`); one for what happened returns. - -use crate::error::DeadlockCause; -use std::cell::Cell; - -/// A step of a command buffer's transitions. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Step { - /// Its scheduled handlers. - ScheduledHandlers, - /// Its completed handlers. - CompletedHandlers, - /// The release of what it retained (a no-copy buffer's deallocator may run here). - Release, - /// Its submission handlers, on the thread that took its last batch (the scheduler's, - /// or a committing one, which may be a handler thread): its transition to `Scheduled`, and - /// so every later transition of its queue, waits for them. - SubmissionHandlers, - /// Its completion-seen handlers, as its transition to `Completed` or `Error` runs: on the - /// thread that saw it complete, or its queue's handler thread. - CompletionSeenHandlers, -} - -impl Step { - /// The cause a wait for what has not happened is refused with from this step: a submission - /// handler's or a completion-seen handler's, which the device's other work waits for. `None` - /// for the steps of a handler thread, whose waits answer by their queues. - fn refuses(self) -> Option { - match self { - Step::SubmissionHandlers => Some(DeadlockCause::SubmissionHandler), - Step::CompletionSeenHandlers => Some(DeadlockCause::CompletionSeenHandler), - Step::ScheduledHandlers | Step::CompletedHandlers | Step::Release => None, - } - } -} - -/// A logical queue's serial context: its device (by the shared state's address) and the queue's -/// identity there. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Context { - pub(crate) device: usize, - pub(crate) queue: u64, -} - -/// What a handler thread runs: a step of a command buffer (by its shared state's address) in its -/// queue's context. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Marker { - pub(crate) context: Context, - pub(crate) buffer: usize, - pub(crate) step: Step, -} - -/// The command buffer a wait is for, in its queue's context. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Target { - pub(crate) context: Context, - pub(crate) buffer: usize, -} - -thread_local! { - static RUNNING: Cell> = const { Cell::new(None) }; -} - -/// This thread runs a marked step until the value is dropped; the marker before it comes back -/// then. -pub(crate) struct Running { - previous: Option, -} - -impl Running { - /// Mark this thread as running `marker`'s step. - pub(crate) fn enter(marker: Marker) -> Running { - let previous = RUNNING.get(); - RUNNING.set(Some(marker)); - Running { previous } - } -} - -impl Drop for Running { - fn drop(&mut self) { - RUNNING.set(self.previous); - } -} - -/// The step this thread runs, if any. -pub(crate) fn running() -> Option { - RUNNING.get() -} - -/// What a wait answers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Answer { - /// Wait as usual: this is not a handler thread, or what it waits for happened. - Wait, - /// Return at once, as Metal does. - Return, - /// Refuse, for its cause: what it waits for comes later in this thread's own context - /// (`DeadlockCause::OwnQueue`). - Refuse(DeadlockCause), - /// Wait for another queue's context, from this one: counted while it blocks, and refused - /// where it would deadlock. - Block(Context), -} - -/// What `wait_until_completed` on `target` answers on a thread running `marker`; `finished` -/// says whether its waiters may already return. -pub(crate) fn completed_wait(marker: Option, target: Target, finished: bool) -> Answer { - let Some(marker) = marker else { - return Answer::Wait; - }; - if finished { - Answer::Wait - } else if let Some(cause) = marker.step.refuses() { - Answer::Refuse(cause) - } else if marker.buffer == target.buffer && marker.step == Step::Release { - Answer::Return - } else if marker.context == target.context { - Answer::Refuse(DeadlockCause::OwnQueue) - } else { - Answer::Block(marker.context) - } -} - -/// What `wait_until_scheduled` on `target` answers on a thread running `marker`; `scheduled` -/// says whether its transition to `Scheduled` ran. -pub(crate) fn scheduled_wait(marker: Option, target: Target, scheduled: bool) -> Answer { - let Some(marker) = marker else { - return Answer::Wait; - }; - if marker.buffer == target.buffer && marker.step == Step::ScheduledHandlers { - // That transition is in progress: Metal's never returns there. - Answer::Refuse(DeadlockCause::OwnQueue) - } else if scheduled { - Answer::Wait - } else if let Some(cause) = marker.step.refuses() { - Answer::Refuse(cause) - } else if marker.context == target.context { - Answer::Refuse(DeadlockCause::OwnQueue) - } else { - Answer::Block(marker.context) - } -} - -/// What a new command buffer's wait for a slot of the full queue `queue` answers on a thread -/// running `marker` (`CommandQueue::command_buffer`); `open` says whether a command buffer not -/// committed holds one of the queue's slots, which the program may give back by dropping it. -/// -/// A committed command buffer gives its slot back only in its queue's context, after its -/// completed handlers. In that context, then, no committed command buffer can give one back: -/// Metal's make never returns there (a completed handler's make on its own full -/// queue). The runtime refuses it, unless an uncommitted command buffer may still be dropped. -pub(crate) fn slot_wait(marker: Option, queue: Context, open: bool) -> Answer { - let Some(marker) = marker else { - return Answer::Wait; - }; - if let Some(cause) = marker.step.refuses() { - return if open { - Answer::Wait - } else { - Answer::Refuse(cause) - }; - } - if marker.context != queue { - Answer::Block(marker.context) - } else if open { - Answer::Wait - } else { - Answer::Refuse(DeadlockCause::OwnQueue) - } -} - -/// The handler threads' waits for other contexts, as edges from the waiting context to the -/// awaited one. A context runs one item at a time, so it has at most one edge out. -#[derive(Debug)] -pub(crate) struct Waits { - edges: Vec<(Context, Context)>, -} - -impl Waits { - /// No wait. - pub(crate) const fn new() -> Waits { - Waits { edges: Vec::new() } - } - - /// Whether a wait of `from` for `to` would close a cycle: `to` waits, through the contexts - /// it waits for, for `from`. - pub(crate) fn closes_cycle(&self, from: Context, to: Context) -> bool { - let mut at = to; - // Each step follows a distinct edge, unless the edges hold a cycle already (they never - // do: no wait that closes one is added). - for _ in 0..=self.edges.len() { - if at == from { - return true; - } - match self.edges.iter().find(|(waiting, _)| *waiting == at) { - Some(&(_, next)) => at = next, - None => return false, - } - } - true - } - - /// `from` waits for `to`. - pub(crate) fn insert(&mut self, from: Context, to: Context) { - self.edges.push((from, to)); - } - - /// `from` no longer waits for `to`. - pub(crate) fn remove(&mut self, from: Context, to: Context) { - if let Some(at) = self.edges.iter().position(|&edge| edge == (from, to)) { - self.edges.swap_remove(at); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/protection.rs b/crates/metal2vulkan-runtime/src/command_buffer/protection.rs deleted file mode 100644 index 935e91a33..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/protection.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Protection options (`setProtectionOptions:`, SPI) as Metal's GPU answers them, measured by a -//! consumer on an M3 Max (macOS 26.7) over every option below 0x10, 0x10 to 0x100, 0x11, 0x13, -//! `u32::MAX`, `1 << 63`, `u64::MAX - 1` and `u64::MAX`. The runtime has no protected content; -//! what Metal does with the options, it does. -//! -//! - **An encoder made under options other than 0** runs nothing, nor does any encoder after it, -//! and the command buffer fails with [`CommandBufferError::ProtectedEncoder`]: code 16 -//! ("Protection Violation") below 0x10, 1 (`MTLCommandBufferErrorInternal`, "Invalid Input") -//! from 0x10 up, none of its event signals firing. An encoder made before the options runs. -//! - **Options from 0x10 up** fail it so with no encoder made under them too, every encoder -//! running. -//! - **Options 1, 3 and 7** end the process where a compute or render encoder is made under them, -//! and at a blit encoder's first command (SIGABRT, no message): `Invalid`, -//! [`Problem::ProtectedEncoder`]. -//! - **Refused**: the call while an encoder is open, as Metal asserts -//! (`exec_protection_envelope_open_encoder`; `Problem::EncoderOpen`), and after the commit; -//! options changed once an encoder was made under some, or after options from 0x10 up, and a -//! resource state encoder made under 1, 3 or 7, none measured -//! ([`AppleOnly::ProtectedContent`]). - -use super::{CommandBuffer, FailedEncoders, State}; -use crate::apple_only::AppleOnly; -use crate::error::{invalid, CommandBufferError, Error, Problem}; -use std::collections::BTreeSet; - -/// What `setProtectionOptions:` left on a command buffer. -#[derive(Clone, Copy, Debug, Default)] -pub(super) struct Protection { - /// The options set last: 0 until one is set. - options: u64, - /// The place among the ended encoders of the first encoder made under options other than 0. - first: Option, -} - -/// Whether `options` end the process where an encoder is made under them: a compute or render -/// encoder's creation, a blit encoder's first command. -fn aborts(options: u64) -> bool { - matches!(options, 1 | 3 | 7) -} - -impl Protection { - /// The options set last. - pub(super) fn options(&self) -> u64 { - self.options - } - - /// Set `options`; refused where an encoder was made under options already, or options from - /// 0x10 up were set, and `options` differ: not measured. - fn set(&mut self, options: u64) -> Result<(), AppleOnly> { - let kept = self.first.is_some() || self.options >= 0x10; - if kept && options != self.options { - return Err(AppleOnly::ProtectedContent); - } - self.options = options; - Ok(()) - } - - /// An encoder was made at `place` among the ended encoders, under the options set now. - fn made(&mut self, place: usize) { - if self.options != 0 { - self.first.get_or_insert(place); - } - } - - /// How the options fail the command buffer at its commit: the encoders that run nothing, and - /// its error. `None` where they fail nothing. - pub(super) fn failure(&self) -> Option<(FailedEncoders, CommandBufferError)> { - let encoders = match self.first { - Some(first) => FailedEncoders::From(first), - None if self.options >= 0x10 => FailedEncoders::Set(BTreeSet::new()), - None => return None, - }; - Some((encoders, CommandBufferError::ProtectedEncoder(self.options))) - } -} - -impl State { - /// An encoder opened now, at its place among the ended encoders, under the options set now. - pub(crate) fn protected_made(&mut self) { - let place = self.open_encoder_place(); - self.protection.made(place); - } - - /// The options set now where they end Metal's process where an encoder is made under them (a - /// compute or render encoder's creation, a blit encoder's first command); `None` for any - /// others. - pub(crate) fn protection_aborts(&self) -> Option { - let options = self.protection.options(); - aborts(options).then_some(options) - } - - /// Refuse `call`, a compute or render encoder's creation, where the options set now end the - /// process there (`Invalid`, [`Problem::ProtectedEncoder`]), as Metal's do. - pub(crate) fn refuse_protected(&self, call: &'static str) -> Result<(), Error> { - match self.protection_aborts() { - Some(options) => Err(invalid(call, Problem::ProtectedEncoder { options })), - None => Ok(()), - } - } -} - -impl CommandBuffer { - /// `setProtectionOptions:` (SPI): the options the encoders made after it are made under, which - /// fail the command buffer as Metal's GPU fails it, or end the process where Metal's does - /// (`command_buffer/protection.rs`: an encoder made under options other than 0 runs nothing, - /// nor does any after it, and the command buffer fails with - /// [`CommandBufferError::ProtectedEncoder`], none of its event signals firing; under options - /// from 0x10 up it fails so with no such encoder too). Refused: while an encoder is open - /// (`Invalid`, `Problem::EncoderOpen`, as Metal asserts) and after the commit - /// (`Problem::AlreadyCommitted`); options changed once an encoder was made under some, or - /// after options from 0x10 up, which nothing measured ([`AppleOnly::ProtectedContent`]). - pub fn set_protection_options(&self, options: u64) -> Result<(), Error> { - self.settle_end(); - let mut state = self.state(); - if let Some(problem) = state.refusal() { - return Err(invalid("set_protection_options", problem)); - } - state.protection.set(options).map_err(Error::AppleOnly) - } - - /// Refuse `call`, a compute or render encoder's creation, where the protection options end - /// the process there (`Invalid`, [`Problem::ProtectedEncoder`]), as Metal's do. - pub(crate) fn refuse_protected_encoder(&self, call: &'static str) -> Result<(), Error> { - self.state().refuse_protected(call) - } - - /// Refuse a resource state encoder's creation under options that end the process where a - /// compute or render encoder is made: what Metal does there is not measured - /// ([`AppleOnly::ProtectedContent`]). - pub(crate) fn refuse_protected_state_encoder(&self) -> Result<(), Error> { - match self.state().protection_aborts() { - Some(_) => Err(Error::AppleOnly(AppleOnly::ProtectedContent)), - None => Ok(()), - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs deleted file mode 100644 index bc09303a2..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! Where a command buffer's first submission found a use rebound -//! (`CommandBufferError::EncodedUseRebound`, `first_submission.rs`), and why no rebind encoded or -//! recorded it again (`reencode.rs`): the notice names it (`Device::degrade_encoded_use_rebound`), -//! the first one found, as the host step's notice names its rule. - -use crate::used_resources::EncoderKind; -use std::fmt; - -/// Why an ended encoder kept no log a rebind encodes it again from (`replay.rs`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Unlogged { - /// It logged no calls: a blit or render encoder that opened while the device had no buffer - /// over host pages, a compute encoder that recorded a loop of command predication - /// (`predication.rs`), or one of a kind that logs none (a resource state encoder's). - NoCalls, - /// It left work for later that an encoding again does not record at once: a GPU-written - /// indirect dispatch's host step (`Segment::records_again`). - Segments, - /// The command buffer's failure fails it, or a fault of its own, as it commits. - Fails, - /// A compute encoder of a command buffer that used command predication whose unit laid a - /// step before it opened, or one of its own that the unit's later encoders read, or a loop, - /// or left work out (`Predication::alone`): a command encoded again after the commit would - /// run outside its block, or leave a command of the unit's reading a gate nothing writes. - Predicated, -} - -/// How a segment's recording the first submission judged was made (`encoder.rs`'s segments). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Recording { - /// At the commit, on the GPU alone, for good (`Deferred::record_on_gpu`). - GpuAlone, - /// At the commit, from the CPU's records or as a dispatch whose pipelines were made. - Commit, - /// By a host step. - HostStep, -} - -/// Which of an encoder's recordings held the rebound use. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum ReboundAt { - /// A command of the encoder's own named the buffer, and the encoder kept no log: why, where - /// known. - Unlogged(Option), - /// A command of the encoder's own named it, and its encoding again was refused (a call that - /// answered otherwise than at its encoding, a recording unlike the first, work no longer on the - /// GPU alone): the refusal. - Refused(String), - /// A command of the encoder's own named it; the encoder kept its log, and no rebind encoded it - /// again. - NotEncodedAgain, - /// Work it left for later named it. - Segment(Recording), -} - -/// Where the first submission found a use rebound: the command buffer's ended encoder `encoder`, -/// of `kind`, and which of its recordings. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct ReboundUse { - pub(crate) encoder: usize, - pub(crate) kind: EncoderKind, - pub(crate) at: ReboundAt, -} - -impl fmt::Display for Unlogged { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(match self { - Unlogged::NoCalls => { - "it logged no calls (a blit or render encoder opened with no buffer over host \ - pages, a compute encoder that recorded a predicated loop, or a kind that logs \ - none)" - } - Unlogged::Segments => "it left work for later an encoding again does not record", - Unlogged::Fails => "its command buffer fails it as it commits", - Unlogged::Predicated => { - "its unit of command predication laid a step before it opened, or one of its \ - own that the unit's later encoders read, or a loop, or left work out" - } - }) - } -} - -impl fmt::Display for ReboundUse { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let kind = match self.kind { - EncoderKind::Blit => "blit", - EncoderKind::Compute => "compute", - EncoderKind::Render => "render", - EncoderKind::ResourceState => "resource state", - }; - write!(f, "found in its {kind} encoder {}: ", self.encoder)?; - match &self.at { - ReboundAt::Unlogged(Some(why)) => { - write!( - f, - "a command of its own named it, not encoded again as {why}" - ) - } - ReboundAt::Unlogged(None) => { - f.write_str("a command of its own named it, and it kept no log") - } - ReboundAt::Refused(refusal) => write!( - f, - "a command of its own named it, and its encoding again was refused: {refusal}" - ), - ReboundAt::NotEncodedAgain => { - f.write_str("a command of its own named it; its log was kept, no rebind encoded it") - } - ReboundAt::Segment(Recording::GpuAlone) => f.write_str( - "work its commit recorded on the GPU alone named it, and no rebind recorded it \ - again", - ), - ReboundAt::Segment(Recording::Commit) => { - f.write_str("work its commit recorded named it, which a rebind does not record") - } - ReboundAt::Segment(Recording::HostStep) => { - f.write_str("work a host step recorded named it, which a rebind does not record") - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/recovery.rs b/crates/metal2vulkan-runtime/src/command_buffer/recovery.rs deleted file mode 100644 index b813dfdc1..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/recovery.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! The recoveries of a device's GPU from a fault or a hang, as Metal's GPU makes them, and what -//! they do to a predicated loop that runs again meanwhile (`rerun.rs`). -//! -//! Metal's GPU recovers from a page fault or a hang device-wide: a predicated loop running on the -//! device when it does stops there. Measured on the M3 Max (macOS 27.0.1): a `While` loop of -//! 160,000 passes, its unit's encoder followed by a mark and a blit, committed on a queue; 50 ms on, -//! two command buffers drawing primitive type 9 committed on that queue or another one. -//! - A fault (an indexed draw, `PageFault`; 6 runs, committed 50 ms on or at once) failed the -//! loop's command buffer as a victim (`MTLCommandBufferErrorInternal`, -//! `CommandBufferError::GpuRecoveryVictim`) 0.0 to 0.02 ms before the faulting one completed, -//! 3,463 to 39,098 passes in. The loop ran on through the fault's 8 ms hold, and nothing after -//! its encoder ran. -//! - A hang (a direct draw, `GpuHang`; 2 runs) ended the loop with no error 0.05 to 0.08 ms -//! before the hanging one failed, about 53,450 passes in. Its command buffer completed cleanly -//! and nothing after the loop's encoder ran. -//! - A loop committed behind faults that recovered before it started ran all its passes. -//! -//! The runtime answers so: each hold (`hang.rs`) raises the device's recovery from what it holds -//! for as its wait goes, the GPU's recovery ([`Recoveries::raise`]). A fault's hold that later -//! failures follow raises the fault's once it read `Scheduled`, and the later ones' as its wait -//! goes. A command buffer a program commits as failed with Metal's code of a page fault or a hang -//! (`CommandBuffer::commit_failed`, `CommandBufferError::Injected` of 3 or 2) stands for that -//! error: the recovery from it is raised as it completes, beside its queue's count -//! (`revocation.rs`, [`injected`]). Before each run again a loop asks for the first recovery -//! since its command buffer's first submission ([`Recoveries::since`]): -//! - after a fault's, it fails as a victim; -//! - after a hang's, it stops with no error ([`cut`]): from the check's part on, nothing of the -//! command buffer runs, and it completes cleanly. Whether its later event signals fire is not -//! measured; they fire. -//! -//! A fault committed on the loop's own queue behind the loop waits for the loop to end in the -//! runtime, as every batch of a queue does, where Metal's GPU runs it during the loop -//! (`docs/FAST-PATHS.md`, known gaps). - -use super::super::gpu_time; -use super::rerun::LoopCheck; -use super::{lock, CommandBufferShared, State}; -use crate::deferred::Deferred; -use crate::encoder::Recorded; -use crate::error::CommandBufferError; -use std::sync::atomic::{AtomicU64, Ordering}; - -/// A device's GPU recoveries (the module docs): when the last from a fault and the last from a -/// hang came, in host nanoseconds (`gpu_time::host_nanos`); 0 for none. -#[derive(Default)] -pub(crate) struct Recoveries { - fault: AtomicU64, - hang: AtomicU64, -} - -/// What the GPU recovered from. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Recovery { - /// A page fault, or a draw it fails as a victim of its recovery - /// (`CommandBufferError::PageFault`, `GpuRecoveryVictim`). - Fault, - /// A hang (`CommandBufferError::GpuHang`). - Hang, -} - -impl Recoveries { - /// The GPU recovered from `recovery`, now. - pub(super) fn raise(&self, recovery: Recovery) { - let at = match recovery { - Recovery::Fault => &self.fault, - Recovery::Hang => &self.hang, - }; - at.fetch_max(gpu_time::host_nanos(), Ordering::AcqRel); - } - - /// The GPU's first recovery after host time `since` (nanoseconds), of each kind's last: - /// `None` where none came since. - pub(super) fn since(&self, since: u64) -> Option { - let after = |at: &AtomicU64| Some(at.load(Ordering::Acquire)).filter(|&at| at > since); - match (after(&self.fault), after(&self.hang)) { - (Some(fault), Some(hang)) if hang < fault => Some(Recovery::Hang), - (Some(_), _) => Some(Recovery::Fault), - (None, Some(_)) => Some(Recovery::Hang), - (None, None) => None, - } - } -} - -/// What the GPU recovers from as a command buffer that failed with `error` completes: a page -/// fault or a hang a program committed as failed in its place by its Metal code (the module -/// docs); `None` for every other error. The runtime's own raise theirs at their hold's release -/// (`hang.rs`). -pub(super) fn injected(error: CommandBufferError) -> Option { - let CommandBufferError::Injected(code) = error else { - return None; - }; - match code { - _ if code == CommandBufferError::PageFault.metal_code() => Some(Recovery::Fault), - _ if code == CommandBufferError::GpuHang.metal_code() => Some(Recovery::Hang), - _ => None, - } -} - -/// The first recovery of `buffer`'s device since its first submission (the module docs). -pub(super) fn recovered(buffer: &CommandBufferShared) -> Option { - let since = buffer.kernel.start(); - buffer.device.shared().recoveries.since(since) -} - -/// The loop of `check` stopped at a hang's recovery (the module docs): every part of `buffer` -/// from the one holding the check on runs nothing, each keeping its place among the batches with -/// its fences' waits and updates alone (`State::fail_part`), and the command buffer completes -/// with no error. -pub(super) fn cut(buffer: &CommandBufferShared, check: &LoopCheck) { - let mut state = lock(&buffer.state); - let State { - recorded, - retained, - ended, - .. - } = &mut *state; - let holds_check = |part: &Recorded| { - part.segments.iter().any(|segment| match &segment.work { - Deferred::Loop(held) => std::ptr::eq(&**held, check), - _ => false, - }) - }; - let Some(from) = recorded.iter().position(holds_check) else { - return; - }; - for part in &mut recorded[from..] { - State::fail_part(part, ended, retained); - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs deleted file mode 100644 index 373f7fec7..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ /dev/null @@ -1,965 +0,0 @@ -//! A committed command buffer's encoders encoded again at a rebind, before the submission of their -//! event group (the logs are `replay.rs`'s). -//! -//! - **Marked under the rebind's lock.** Its commit notes the command buffer, with the keys of -//! the buffers over host pages its replayable encoders named, while its encoders' holds still -//! refuse a rebind of them (`Rebinds::wait_for_replay`), until its last event group is -//! submitted or it completes. A rebind of one of them marks it (`reencode`) under the device's -//! lock of those buffers, the lock each group's submission reads the mark under -//! (`State::first_submission`, `State::later_group`): that submission came before the rebind, -//! and keeps the old pages (Metal's table 3), or it waits, held at its place in the -//! scheduler's order, until the mark is gone. A later group's encoders are encoded again as -//! the first's are: Metal's later submission of a command buffer whose earlier one ran reaches -//! the new pages (the M3 Max under macOS 27.0.1). -//! - **Encoded again in the rebind's call.** The rebind then encodes again, on its own thread -//! (the program's call, under no lock of the runtime's), each encoder of the command buffer's -//! groups not yet submitted a command of which named a buffer that lies elsewhere now than it -//! took it, from its log, into -//! new `VkCommandBuffer`s of the command buffer's pool, and puts what it recorded in the -//! encoder's place: its recordings, uses, executions, keys and what its commands took (held -//! weakly, as the commit holds them). The first recording is never submitted. No GPU work is -//! waited for, and no pipeline's making: a dispatch whose pipelines are being made leaves a -//! segment of its own, as the first encoding left one (`pending_dispatch.rs`), and so does a -//! render pass of a draw's or a tile dispatch's being made (`render/pending_tile.rs`), which -//! the submission or the host step records once they are made, so no Metal compile runs or is -//! waited for on the program's thread inside the rebind's call. -//! Rebinds on two threads take turns (`reencoding`); a rebind during another's -//! turn marks the command buffer again, and its own turn encodes what moved since. A host step -//! of the command buffer, which records into its pool on the scheduler's thread, takes the -//! same turns: Vulkan synchronizes a pool's recordings externally. -//! - **Work recorded on the GPU alone, recorded again.** Work its commit recorded on the GPU -//! alone, for good (a GPU-written execution's preprocess and its dispatches or draws, -//! `gpu_execute.rs`, `render/executions/gpu.rs`), reaches what its commands' records name -//! through the resident set its preprocess's table names, which the first submission points -//! at the set as it lies then (`first_submission.rs`): no rebind or release records it again -//! for that. What its commands named (the pass's attachments, say) was resolved as it was -//! recorded: an encoder that left such work keeps its log as one that left none does, and its -//! encoding again records that work at once, on the GPU alone, in segments of the same parts -//! (`EncoderCore::finish_replay`), its own commands (a render pass's shadowed textures' -//! copies and its other steps among them) recorded again around them. Its commit notes the -//! keys that work named too (`State::keep_replays`): a rebind of one of them before the first -//! submission (which alone points those tables) records the work of the encoders it does not -//! encode again in its place, as the commit did, over where the buffers lie now: its recording, what its commands took and what -//! its host step needs. Work a host step recorded again since (with the barriers between its -//! commands, `gpu_execute::Rerecord`, or as a route outgrew it, `DeferredPass::outgrown`) -//! keeps that step's recording. -//! - **Faces as first met.** Each encoding again (and each recording again on the GPU alone) -//! meets the faces of the command buffer's turns as its first encoding met them: a texture a -//! later pass of the command buffer turned presents the face from before the turn, and the -//! turning pass takes its turn again (`texture/faces.rs`, **Encoded again**). -//! - **Copies taken at use.** A tiled texture's copy of its bytes taken at use (`shadow.rs`) is -//! taken by the first use encoded after its mark was set, which clears it. An encoder encoded -//! again takes it where the use in its place in its first encoding took it, whose recording is -//! never submitted, and leaves the mark as it finds it: set by a `did_modify_data` since, it is -//! the next use's to take (`shadow::Takes`). -//! - **Runs of passes.** An encoder encoded again that was a pass of a run of passes merged once -//! (a shadowed texture's or a linear attachment's, `pass_runs.rs`) leaves the run once it is -//! put in place: the merge of the run's pass before it, which it took over, records after all, -//! and it keeps the run's scratch after its own merge where a later pass went on over it, a -//! linear attachment's run's box copied in again first (`State::replaying_keeps`, recorded by -//! `EncoderCore::finish_replay`). Its run's other passes are not encoded again. -//! - **Groups whole.** The encoders of a group recorded into one -//! `VkCommandBuffer` (`encoder_fold.rs`) are encoded again together: a rebind that moves one -//! encodes each again, into `VkCommandBuffer`s of its own, and puts them in their places -//! together, or puts none where one of them kept no log, is refused or does not fit its place. -//! A group one of whose encoders kept no log, or cannot be encoded again apart in its command -//! buffer's command predication, is split where each such encoder lies in one of Metal's -//! submissions that holds one of them the rebind moved, which runs nothing anyway -//! (`State::split_rebound`): the group's other encoders are encoded again apart, as a split at -//! the commit's are (below). -//! - **Split at the commit.** A commit whose failure fails some of a group's encoders and not the -//! others, after a command-predication record left out the work of some of them, or with a -//! submission check where the group's `VkCommandBuffer` holds commands of two of Metal's -//! submissions (`encoder_fold.rs`'s **Failed**), marks the command buffer as a rebind does, and -//! its own call encodes those of the group's encoders that run again, each into -//! `VkCommandBuffer`s of its own, before the first submission, which waits for it; where one -//! cannot be encoded again or does not fit its place, those encoders run nothing after all -//! (`State::fail_unsplit`), as the whole group would have. A submission check may run on the -//! scheduler's thread before that call's encodings take their places: an encoder whose -//! submission it failed (`State::fail_submission`) takes no encoding again, here or in a -//! rebind's turn, and the others of its unit take theirs. -//! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a compute -//! encoder of a command buffer that used command predication whose unit laid a step before it -//! opened, or one of its own that the unit's later encoders read, or a loop, or left work out; -//! one failed at the commit) or whose second -//! encoding is refused or records otherwise (`EncoderCore::finish_replay`), its work among -//! them where it no longer runs on the GPU alone, keeps its first recording, which the first -//! submission finds rebound: `CommandBufferError::EncodedUseRebound`, as before. So does work -//! on the GPU alone the rebind no longer records there. - -use super::rebound_use::Unlogged; -use super::{lock, CommandBuffer, CommandBufferShared, State}; -use crate::deferred::{Deferred, StepInputs}; -use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; -use crate::pass_runs::RunMerge; -use crate::pipeline::budget::Urgency; -use crate::predication::Predication; -use crate::replay::Replay; -use crate::residency::Residency; -use crate::resource::ResourceKey; -use crate::texture::faces::with_faces_as_of; -use crate::used_resources::EncoderKind; -use crate::work_counts::Counters; -use std::collections::BTreeSet; -use std::ops::Range; -use std::sync::atomic::Ordering; -use std::sync::Arc; - -impl CommandBufferShared { - /// A rebind since its commit, of a buffer one of its replayable encoders named, has them - /// to encode again ([`reencode`](Self::reencode)) before the submission of their event group: - /// marked under - /// the device's lock of its buffers over host pages (`Rebinds::replace`). - pub(crate) fn mark_reencode(&self) { - self.reencode.fetch_add(1, Ordering::AcqRel); - } - - /// Whether the submission of its next event group waits for its encoders encoded again (the - /// module docs). - pub(crate) fn reencode_pending(&self) -> bool { - self.reencode.load(Ordering::Acquire) > 0 - } - - /// Encode again each encoder of its event groups not yet submitted that a command of named a - /// buffer over host pages that lies elsewhere now than the command took it, and record again - /// the work its commit recorded on the GPU alone before the first submission (the module - /// docs), on the rebind's thread, with no lock of the runtime's held; then the submission of - /// its next group may go, and the scheduler looks again. Nothing here fails the rebind: an - /// encoder it cannot encode again, or work it cannot record on the GPU alone again, keeps its - /// first recording, which its group's submission fails. A command buffer that completed - /// encodes nothing again. An encoder whose encoding again raced a rebind of a buffer it took - /// (`Taken::raced`, `rebind.rs`'s **Other threads**) is encoded again once no rebind's - /// publish is open (`Rebinds::wait_published`), until one does not race. - pub(crate) fn reencode(self: &Arc) { - let _for = self.notices_for(); - let turn = lock(&self.reencoding); - let marked = self.reencode.load(Ordering::Acquire); - if marked == 0 { - return; - } - while self.encode_moved() { - self.device.shared().rebinds.wait_published(); - } - // Its next group's submission may go, unless a rebind marked it meanwhile: that rebind's - // turn comes next and encodes what moved since. - let _ = self - .reencode - .compare_exchange(marked, 0, Ordering::AcqRel, Ordering::Acquire); - drop(turn); - self.device.shared().scheduler.wake(); - } - - /// One turn of [`reencode`](Self::reencode), its caller holding the turn: each encoder that - /// moved encoded again and put in place, and the work on the GPU alone recorded again. - /// Whether an encoder it put in place raced a rebind as it was encoded again. - fn encode_moved(self: &Arc) -> bool { - let device = &self.device; - // The encoders of its event groups not submitted yet: those before were judged, and run - // over the pages they took. - // So are those whose pass took a rasterization-rate map since reset; one that kept no - // log draws by the map as it took it, announced (`rate_mapped_pass.rs`). - let mut unencoded = Vec::new(); - // Each unit with whether the commit's failure split it from its group: its encoders run - // nothing where they cannot all be encoded again (`encoder_fold.rs`'s **Failed**). - let units: Vec<(bool, Vec<(usize, Arc)>)> = { - let mut state = lock(&self.state); - match state.finished() { - true => Vec::new(), - false => { - let open: BTreeSet = (state.recorded[state.unjudged_parts()..].iter()) - .map(|part| part.encoder) - .collect(); - let split = std::mem::take(&mut state.split_units); - let splitting: BTreeSet = split.iter().flatten().copied().collect(); - let mut units = Vec::new(); - for unit in split { - // An encoder whose submission a check failed before this turn - // (`State::fail_submission`) runs nothing: it takes no encoding again. - let unit: Vec = (unit.into_iter()) - .filter(|at| !state.unrunnable.contains(at)) - .collect(); - if unit.is_empty() { - continue; - } - let logs: Option)>> = (unit.iter()) - .map(|&at| { - let log = state.ended.get(at)?.replay.as_ref()?; - Some((at, Arc::clone(log))) - }) - .collect(); - match logs { - Some(logs) => units.push((true, logs)), - None => state.fail_unsplit(&unit), - } - } - let submitting = device.shared().rebinds.submitting(); - // Its open encoders, logged or not, a command of which named a buffer that - // lies elsewhere now. - let encodes = |at: &usize| { - open.contains(at) - && !splitting.contains(at) - && !state.unrunnable.contains(at) - }; - let rebound: BTreeSet = (state.ended.iter().enumerate()) - .filter(|(at, _)| encodes(at)) - .filter(|(_, record)| submitting.rebound(&record.taken)) - .map(|(at, _)| at) - .collect(); - let moved: Vec<(usize, Arc)> = (state.ended.iter().enumerate()) - .filter(|(at, _)| encodes(at)) - .filter_map(|(at, record)| { - let reset = record.taken.rate_map_reset(); - let Some(replay) = record.replay.as_ref() else { - if reset { - unencoded.push(record.unlogged); - } - return None; - }; - let moved = rebound.contains(&at) || reset; - moved.then(|| (at, Arc::clone(replay))) - }) - .collect(); - let counts = &device.shared().counts; - units.extend(state.encoded_together(moved, &rebound, counts)); - units - } - } - }; - for unlogged in unencoded { - crate::rate_mapped_pass::degrade_unencoded(device, unlogged); - } - let handle = CommandBuffer(Arc::clone(self)); - // The encoders encoded again, whose segments the encoding again recorded. - let mut spliced = Vec::new(); - // Each unit's encoders are encoded again before any takes its place: a group of encoders - // recorded into one `VkCommandBuffer` takes its places whole or not at all - // (`encoder_fold.rs`). - for (split, unit) in units { - let members: Vec = unit.iter().map(|(at, _)| *at).collect(); - let mut again = Vec::new(); - for (at, replay) in &unit { - match self.encode_again(&handle, *at, replay) { - Some(done) => again.push(done), - None => break, - } - } - if again.len() < unit.len() { - if split { - lock(&self.state).fail_unsplit(&members); - } else if unit.len() > 1 { - let mut state = lock(&self.state); - for (at, _) in &unit { - let record = &mut state.ended[*at]; - record.refused.get_or_insert_with(|| TOGETHER.to_owned()); - } - for _ in &again { - device.shared().counts.reencode_refused(); - } - } - // What the encodings held goes after the lock. - drop(again); - continue; - } - let counts = &device.shared().counts; - // What a refused splice held goes after the lock. - let unspliced = { - let mut state = lock(&self.state); - // An encoder whose submission a check failed meanwhile runs nothing: its encoding - // again takes no place, and the unit's others take theirs. - let (failed, kept): (Vec, Vec) = - (again.into_iter()).partition(|done| state.unrunnable.contains(&done.at)); - again = kept; - let fits = again - .iter() - .all(|done| state.splice_fits(done.at, &done.replayed)); - match fits { - true => { - for done in again.drain(..) { - // Its residency joins what the first encoding made resident before - // the encoding again takes that one's place - // (`State::joined_residency`). - if done.residency.is_some() { - state.joined_residency(counts); - } - let spliced_now = - state.splice_replay(done.at, done.replayed, done.residency); - if let (Ok(()), Some(predication)) = (&spliced_now, done.predication) { - state.predication.take_checks(predication); - } - match spliced_now { - Ok(()) => { - counts.encoder_reencoded(); - spliced.push(done.at); - for run in &done.runs { - run.leave(); - } - } - Err(unspliced) => { - counts.reencode_refused(); - state.ended[done.at].refused = Some(UNFIT.to_owned()); - if split { - state.fail_unsplit(&[done.at]); - } - drop(unspliced); - } - } - } - // Encoded again, each in `VkCommandBuffer`s of its own, the group's - // encoders share none any more. - for (at, _) in &unit { - state.ended[*at].group = None; - } - failed - } - false => { - if split { - state.fail_unsplit(&members); - } - for done in &again { - counts.reencode_refused(); - let refusal = match unit.len() { - 1 => UNFIT, - _ => TOGETHER, - }; - state.ended[done.at].refused = Some(refusal.to_owned()); - } - again.extend(failed); - again - } - } - }; - let reset = { - let state = lock(&self.state); - (unspliced.iter()).any(|done| state.ended[done.at].taken.rate_map_reset()) - }; - drop(unspliced); - if reset { - crate::rate_mapped_pass::degrade_unencoded(device, None); - } - } - // Each making a spliced segment now waits for wakes the scheduler as it - // finishes, with no lock held, registered before the scheduler looks at the batches again - // (the wake at the end of this turn): a making that finished between that look and a - // later registration would leave the batch held with nothing to wake the scheduler. Its - // batch waits for them now, so they go before the makings nothing waits for, at the rank - // the commit asks for the first encoding's (`CommandBuffer::commit`). - let pending: Vec = { - let state = lock(&self.state); - (state.recorded.iter()) - .filter(|part| spliced.contains(&part.encoder)) - .flat_map(|part| part.segments.iter()) - .filter(|segment| segment.steps_after_pipelines()) - .map(|segment| segment.work.clone()) - .collect() - }; - if !pending.is_empty() { - let waker = device.shared().scheduler.waker(); - for work in &pending { - work.when_made(&waker); - work.hasten(Urgency::Committed); - } - } - // Its work recorded on the GPU alone in encoders not encoded again that named a buffer - // over host pages that lies elsewhere now, before its first submission (which alone - // points their resident tables), each segment by its part and its place there, which - // hold through this turn: only the first submission places segments, and - // it waits for the turn; a host step, which records one, takes the turn too. What it - // reaches through its resident set its first submission points it at as it lies then. - let alone: Vec<((usize, usize), Deferred)> = { - let state = lock(&self.state); - match state.submitted { - true => Vec::new(), - false => { - let submitting = device.shared().rebinds.submitting(); - let moved = |segment: &Segment| { - segment.gpu_alone - && (segment.recorded.as_ref()) - .is_some_and(|done| submitting.rebound(&done.taken)) - }; - (state.recorded.iter().enumerate()) - .filter(|(_, recorded)| !spliced.contains(&recorded.encoder)) - .flat_map(|(part, recorded)| { - let segments = recorded.segments.iter().enumerate(); - segments - .filter(|(_, segment)| moved(segment)) - .map(move |(at, segment)| ((part, at), segment.work.clone())) - }) - .collect() - } - } - }; - for (place, work) in alone { - // Its notices were announced as it committed (`replay::is_replaying`), and its - // commands take what they use without holding it. - let (part, _) = place; - let again = with_faces_as_of(device, (self.address(), part..part + 1), || { - crate::replay::replaying(|| work.record_on_gpu(&handle)) - }); - let counts = &device.shared().counts; - let Ok(Some((recorded, inputs))) = again else { - counts.reencode_refused(); - continue; - }; - let put = lock(&self.state).splice_segment(place, recorded, inputs); - match put { - Ok(()) => counts.segment_recorded_again(), - Err(unspliced) => { - counts.reencode_refused(); - drop(unspliced); - } - } - } - drop(handle); - let state = lock(&self.state); - (spliced.iter()).any(|&at| state.ended[at].taken.raced()) - } - - /// Encode ended encoder `at` again from `replay`, its log, on the rebind's thread (the module - /// docs), for the caller to put in its place. `None` where the encoding again is refused, the - /// refusal noted on the encoder and counted. - fn encode_again( - &self, - handle: &CommandBuffer, - at: usize, - replay: &Replay, - ) -> Option { - let device = &self.device; - // A compute encoder of a command buffer that used command predication, which - // encodes again exactly, does so in its unit begun anew - // (`Predication::replaying`). - // The merges its first encoding left to runs of passes (`pass_runs.rs`): encoded again, - // it leaves them, and keeps after itself what a later pass of a run went on over. - let (residency, runs, parts) = { - let mut state = lock(&self.state); - state.replaying_predication = match state.predicated { - true => state.predication.replaying(at), - false => None, - }; - let runs: Vec> = (state.recorded.iter()) - .filter(|part| part.encoder == at) - .flat_map(|part| &part.segments) - .filter_map(|segment| match &segment.work { - Deferred::RunMerge(merge) => Some(Arc::clone(merge)), - _ => None, - }) - .collect(); - state.replaying_keeps = runs.iter().filter_map(|run| run.keep_after()).collect(); - // Its first encoding's takes of copies taken at use, taken again where they were: - // that encoding's recording is never submitted (`shadow::Takes`). - state.replaying_takes = state.ended[at].takes.clone(); - // Its parts, by which the encoding again meets the faces of the command buffer's - // turns as its first encoding met them (`texture/faces.rs`, **Encoded again**). - let mut parts = (state.recorded.iter().enumerate()) - .filter(|(_, part)| part.encoder == at) - .map(|(index, _)| index); - let first = parts.next().unwrap_or(state.recorded.len()); - let parts = first..parts.next_back().map_or(first + 1, |last| last + 1); - (state.residency_before(at, replay.kind()), runs, parts) - }; - let run = with_faces_as_of(device, (self.address(), parts), || { - replay.run(handle, residency) - }); - { - let mut state = lock(&self.state); - state.replaying_keeps.clear(); - state.replaying_takes.clear(); - } - // Its steps' gates listed as the commit lists the first encoding's. - let run = { - let mut state = lock(&self.state); - let state = &mut *state; - match (run, state.replaying_predication.take()) { - (Ok(replayed), Some(mut predication)) => predication - .commit(&mut state.uploads, device) - .map(|()| (replayed, Some(predication))), - (run, _) => run.map(|replayed| (replayed, None)), - } - }; - match run { - Ok(((replayed, residency), predication)) => Some(EncodedAgain { - at, - replayed, - residency, - predication, - runs, - }), - Err(error) => { - device.shared().counts.reencode_refused(); - let reset = { - let mut state = lock(&self.state); - state.ended[at].refused = Some(error.to_string()); - state.ended[at].taken.rate_map_reset() - }; - if reset { - crate::rate_mapped_pass::degrade_unencoded(device, None); - } - None - } - } - } -} - -/// Why an encoder encoded again keeps its first recording where its place holds other parts or -/// work than its encoding again's. -const UNFIT: &str = "its place holds other parts or work than its encoding again's"; - -/// Why an encoder of a group of encoders recorded into one `VkCommandBuffer` -/// keeps its first recording where the group cannot be encoded again whole (`encoder_fold.rs`). -const TOGETHER: &str = "it records into one VkCommandBuffer with encoders around it, \ - which are not all encoded again"; - -/// An ended encoder encoded again, for its place ([`State::splice_replay`]). -struct EncodedAgain { - /// The encoder. - at: usize, - /// What it recorded. - replayed: Replayed, - /// What it made resident. - residency: Option, - /// Its unit of command predication begun anew, whose gates its place takes. - predication: Option, - /// The runs of passes it leaves once in place. - runs: Vec>, -} - -impl State { - /// The residency an ended encoder `at` of `kind` started with, as the command buffer's - /// encoders ended before it leave it (`CommandBuffer::inherited_residency`): none for a blit - /// encoder, which makes nothing resident. - pub(super) fn residency_before(&self, at: usize, kind: EncoderKind) -> Residency { - if kind == EncoderKind::Blit { - return Residency::default(); - } - let mut joined = Residency::default(); - for record in self.ended.iter().take(at) { - if let Some(residency) = &record.residency { - joined.join_encoder(residency, record.kind == EncoderKind::Compute); - } - } - // The textures made in its heaps since, as the commit's sync made them resident. - drop(joined.sync_heaps()); - joined.shadows(kind == EncoderKind::Render) - } - - /// The units the rebind's turn encodes again of `moved`, the ended encoders it moved, with - /// their logs, in order, each with whether it splits a group: each encoder alone, but an - /// encoder of a group of encoders recorded into one `VkCommandBuffer` with every encoder of - /// its group (`encoder_fold.rs`), whose shared recording none may leave - /// alone. A group one of whose encoders kept no log, or cannot be encoded again apart in its - /// command buffer's command predication (`State::encodes_again_apart`), is split where each - /// such encoder lies in one of Metal's submissions that runs nothing anyway - /// ([`split_rebound`](Self::split_rebound)); else it is encoded again by none: its moved - /// encoders keep their first recording, the refusal noted and counted. - pub(super) fn encoded_together( - &mut self, - moved: Vec<(usize, Arc)>, - rebound: &BTreeSet, - counts: &Counters, - ) -> Vec<(bool, Vec<(usize, Arc)>)> { - let mut units = Vec::new(); - let mut reached = 0; - for (at, replay) in moved { - let Some(group) = self.ended[at].group.clone() else { - units.push((false, vec![(at, replay)])); - continue; - }; - if group.start < reached { - continue; - } - reached = group.end; - let logs: Option)>> = (group.clone()) - .map(|member| { - let log = self.ended.get(member)?.replay.as_ref()?; - Some((member, Arc::clone(log))) - }) - .collect(); - let apart = (group.clone()).all(|member| self.encodes_again_apart(member)); - if let Some(unit) = logs.filter(|_| apart) { - units.push((false, unit)); - continue; - } - if let Some(unit) = self.split_rebound(group.clone(), rebound) { - units.push((true, unit)); - continue; - } - for record in &mut self.ended[group] { - if record.replay.is_some() { - counts.reencode_refused(); - } - record.refused.get_or_insert_with(|| TOGETHER.to_owned()); - } - } - units - } - - /// `group`, a group of encoders recorded into one `VkCommandBuffer` some of - /// whose encoders cannot be encoded again ([`State::encodes_again`]), split by a rebind: where - /// each of those lies in one of Metal's submissions (`checks::metal_submissions`) that holds - /// one of them that named a buffer the rebinds moved (`rebound`), which the first submission - /// finds rebound and runs nothing of (`first_submission.rs`), the group's encoders outside - /// those submissions, with their logs, kept now, to encode again apart; their submissions - /// run, as Metal's do, and the shared `VkCommandBuffer` is never submitted. `None` where one - /// of those encoders runs, or none of the group does. - fn split_rebound( - &mut self, - group: Range, - rebound: &BTreeSet, - ) -> Option)>> { - let stuck: Vec = (group.clone()) - .filter(|&member| !self.encodes_again(member)) - .collect(); - let failing: Vec> = (self.metal_submissions().into_iter()) - .map(|(_, encoders)| encoders) - .filter(|encoders| { - (stuck.iter()).any(|member| encoders.contains(member) && rebound.contains(member)) - }) - .collect(); - let fails = |member: &usize| failing.iter().any(|encoders| encoders.contains(member)); - let running: Vec = group.clone().filter(|member| !fails(member)).collect(); - if running.is_empty() || !stuck.iter().all(fails) { - return None; - } - self.keep_held_logs(&running); - let unit = (running.iter()) - .map(|&member| Some((member, Arc::clone(self.ended[member].replay.as_ref()?)))) - .collect::>>()?; - // Encoded again apart, or running nothing, its encoders share no `VkCommandBuffer` any - // more. - for record in &mut self.ended[group] { - record.group = None; - } - Some(unit) - } - - /// The parts of ended encoder `at`, in order. - fn parts_of(&self, at: usize) -> Vec { - (self.recorded.iter().enumerate()) - .filter(|(_, part)| part.encoder == at) - .map(|(index, _)| index) - .collect() - } - - /// Whether `replayed`, ended encoder `at` encoded again, may take its place - /// ([`splice_replay`](Self::splice_replay)). - fn splice_fits(&self, at: usize, replayed: &Replayed) -> bool { - let parts = self.parts_of(at); - let replaces = |part: &usize| { - let recorded = &self.recorded[*part]; - recorded.sparse.is_empty() - && (recorded.segments.iter()).all(|segment| { - segment.keeps_pipelines() - || segment.work.left_for_pipelines() - || segment.gpu_alone - || segment.work.joins_a_run() - || segment.work.recorded_by_an_encoding_again() - || segment.work.left_again_by_an_encoding_again() - }) - }; - let unjudged = self.unjudged_parts(); - !self.finished() - && !parts.is_empty() - && parts.iter().all(|&part| part >= unjudged) - && parts.len() == replayed.parts.len() - && parts.iter().all(replaces) - && !self.unrunnable.contains(&at) - && self - .ended - .get(at) - .is_some_and(|record| record.replay.is_some()) - } - - /// Put `replayed`, ended encoder `at` encoded again, and what it made resident in its place, - /// before the submission of its event group: each of its parts' recordings, uses and segments - /// (recorded on the GPU alone), its executions (the later encoders' and segments' places - /// among them moved by the difference), its keys, and what its commands and its segments' - /// took (held weakly until that submission). What its first recording retained stays retained, - /// and so does what its first segments recorded and what their host steps needed; its - /// `VkCommandBuffer`s go with the pool unsubmitted. Refused, changing nothing and giving - /// `replayed` back, where its place holds other parts than the encoding again's, or a segment - /// but one whose pipelines are being made (which goes, the encoding again having left one of - /// its own in its place), a render pass left for its draws' pipelines alone and recorded or - /// not since they were made (which goes, the encoding again having recorded those draws, or - /// left a segment of its own where it found them still being made), work its commit recorded - /// on the GPU alone, a run's merge (which - /// goes, the encoding again merging after itself, `pass_runs.rs`), a staged gather (which - /// goes, the encoding again copying through the imports, or staging it again where the - /// imports would not copy it, `host_ram/copy.rs`), or a splice's or a merge on the host's CPU - /// part (which goes, the encoding again leaving its own over the new pages, - /// `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again staging it - /// again, `host_ram/copy.rs`), or a shadow's gated copy in (which goes, the encoding again - /// copying in for itself, `shadow::GatedCopyIn`), or a sparse texture's scrub (which goes, the - /// encoding again leaving its own, `sparse/emulated.rs`), or its group was submitted, or the - /// command buffer completed. - pub(super) fn splice_replay( - &mut self, - at: usize, - replayed: Replayed, - residency: Option, - ) -> Result<(), Box<(Replayed, Option)>> { - if !self.splice_fits(at, &replayed) { - return Err(Box::new((replayed, residency))); - } - let parts = self.parts_of(at); - let Replayed { - parts: mut replayed_parts, - held, - retained, - executions, - keys, - mut taken, - heaps, - } = replayed; - // Held weakly until its group's submission, as the commit held what the first recording - // and its segments took. - taken.wait(); - let segments = (replayed_parts.iter_mut()) - .flat_map(|part| part.segments.iter_mut()) - .filter_map(|segment| segment.recorded.as_mut()); - for done in segments { - done.taken.wait(); - } - let first = self.ended[at].executions.clone(); - for (&part, replayed) in parts.iter().zip(replayed_parts) { - let ReplayedPart { - raws, - summary, - segments, - } = replayed; - let recorded = &mut self.recorded[part]; - recorded.raws = raws; - recorded.summary = summary; - // Its first segments go: the encoding again left a segment of its own in each - // pending dispatch's, each splice's or merge on the host's, each staged copy step's it - // staged again, each gated copy in's and each scrub's place, and its work on the GPU - // alone in segments of its own, and recorded each other staged gather's copy at once. - // What the commit recorded of one stays retained, never submitted, as the first - // recording does. - for segment in recorded.segments.drain(..) { - if let Some(mut before) = segment.recorded { - self.retained.extend(before.retained.into_entry()); - before.taken.retain_into(&mut self.retained); - } - self.retained.push(Box::new((segment.work, segment.inputs))); - } - for mut segment in segments { - segment.executions_at += first.start; - recorded.segments.push(segment); - } - } - // Its executions in its place; an encoder that met a detached buffer at its first - // encoding may have recorded fewer. - let count = executions.len(); - self.executions.splice(first.clone(), executions); - if count != first.len() { - let moved = |place: usize| place - first.end + first.start + count; - for later in self.ended[at + 1..].iter_mut() { - if later.replay.is_some() { - later.executions = moved(later.executions.start)..moved(later.executions.end); - } - } - let last = parts.last().copied().unwrap_or_default(); - let segments = self.recorded[last + 1..] - .iter_mut() - .flat_map(|later| later.segments.iter_mut()); - for segment in segments { - segment.executions_at = moved(segment.executions_at); - } - } - // What the next encoders start with is found again from the residencies as they are left. - self.inherits = [None, None]; - let record = &mut self.ended[at]; - record.executions = first.start..first.start + count; - record.keys = keys; - record.held = held; - record.taken = taken; - if let Some(residency) = residency { - if let Some(first) = record.residency.replace(residency) { - self.retained.push(Box::new(first)); - } - } - self.retained.extend(retained.into_entry()); - self.retained.push(Box::new(heaps)); - Ok(()) - } - - /// Put `recorded`, segment `at` of part `part` recorded again on the GPU alone, in its place - /// before the first submission, with `inputs`, what its host step needs now: what its - /// commands took held weakly until the first submission, as the commit holds them. What the first - /// recording retained, its executions and its host step's inputs stay retained; its - /// `VkCommandBuffer`s go with the pool unsubmitted, and what its commands took, held weakly, - /// goes. Refused, changing nothing and giving `recorded` and `inputs` back, where the place - /// holds no such segment, or the command buffer was submitted. - pub(super) fn splice_segment( - &mut self, - (part, at): (usize, usize), - mut recorded: RecordedSegment, - inputs: StepInputs, - ) -> Result<(), Box<(RecordedSegment, StepInputs)>> { - let fits = !self.submitted - && (self.recorded.get(part)) - .and_then(|recorded| recorded.segments.get(at)) - .is_some_and(|segment| segment.gpu_alone && segment.recorded.is_some()); - if !fits { - return Err(Box::new((recorded, inputs))); - } - recorded.taken.wait(); - let segment = &mut self.recorded[part].segments[at]; - let first = segment.recorded.replace(recorded); - let before = segment.inputs.replace(inputs); - if let Some(first) = first { - let RecordedSegment { - retained, - executions, - .. - } = first; - self.retained.extend(retained.into_entry()); - self.retained.push(Box::new(executions)); - } - if let Some(before) = before { - self.retained.push(Box::new(before)); - } - Ok(()) - } - - /// As it commits: the logs of encoders no rebind encodes again go, for the caller to let go - /// of without this lock: where an encoder used command predication, those of the compute - /// encoders their unit of predication reaches past, or that laid a loop or left work out - /// (`Predication::alone`: a command of theirs encoded again after the commit would run - /// outside its block, or leave a command of their unit's reading a gate nothing writes); and those of - /// encoders the commit's failure fails (they run nothing). The keys of buffers over host pages - /// the encoders whose logs stay named, and the work its commit recorded on the GPU alone, - /// sorted, each once, and the identities of the rasterization-rate maps its encoders' passes - /// are over, logged or not (a reset encodes the one again, or announces the other: - /// `Rebinds::wait_for_replay`). - pub(super) fn keep_replays(&mut self) -> KeptReplays { - let mut gone = Vec::new(); - let mut keys = Vec::new(); - let mut maps = Vec::new(); - for (at, record) in self.ended.iter_mut().enumerate() { - let fails = self - .failed_at_commit - .as_ref() - .is_some_and(|failed| failed.fails(at)); - maps.extend(record.taken.rate_map_id()); - let predicated = self.predicated - && record.kind == EncoderKind::Compute - && !self.predication.alone(at); - if predicated || fails { - if let Some(log) = record.replay.take() { - gone.push(log); - record.unlogged = Some(match predicated { - true => Unlogged::Predicated, - false => Unlogged::Fails, - }); - } - continue; - } - if record.replay.is_some() { - keys.extend(record.taken.named_pins()); - } - } - let alone = (self.recorded.iter()) - .flat_map(|part| &part.segments) - .filter(|segment| segment.gpu_alone) - .filter_map(|segment| segment.recorded.as_ref()); - for done in alone { - keys.extend(done.taken.named_pins()); - } - keys.sort_unstable(); - keys.dedup(); - maps.sort_unstable(); - maps.dedup(); - let to_submission = self.unlogged_names_a_pin(); - KeptReplays { - gone, - keys: keys.into_boxed_slice(), - maps: maps.into_boxed_slice(), - to_submission, - } - } - - /// Whether an encoder that keeps no log, once its replays are kept ([`State::keep_replays`]), - /// named a buffer over host pages, by a command of its own or by work it left for later that - /// its commit did not record on the GPU alone: no rebind encodes or records that again, so the - /// command buffer holds its encoders' holds until its last event group is submitted - /// (`held_to_submission`), refusing a rebind meanwhile, which would fail that submission. - fn unlogged_names_a_pin(&self) -> bool { - // One its commit fails runs nothing whatever the rebind: it holds nothing past the commit. - let held = - |r: &super::EncoderRecord| r.replay.is_none() && r.unlogged != Some(Unlogged::Fails); - let unlogged = |at: usize| self.ended.get(at).is_some_and(held); - let own = (self.ended.iter()).any(|r| held(r) && r.taken.names_a_pin()); - own || (self.recorded.iter()) - .filter(|part| unlogged(part.encoder)) - .flat_map(|part| &part.segments) - .filter(|segment| !segment.gpu_alone) - .filter_map(|segment| segment.recorded.as_ref()) - .any(|done| done.taken.names_a_pin()) - } - - /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder a - /// call of which raced a rebind of a buffer it took (`Taken::raced`) is to be encoded again, - /// in the commit's call, before its first submission, its log kept. One that kept none keeps - /// its first recording, which that submission fails (`EncodedUseRebound`). - pub(super) fn raced_again(&self) -> bool { - (self.ended.iter()).any(|record| record.taken.raced() && record.replay.is_some()) - } - - /// As it commits, once its replays are kept: how many encoders a call of which raced a - /// rebind kept no log (`WorkCounts::encoders_raced_unreplayable`), each failing - /// `EncodedUseRebound` at its submission. None where every encoder that may keep none had its - /// calls gated (`rebind::CallGate`). - pub(super) fn raced_unreplayable(&self) -> usize { - (self.ended.iter()) - .filter(|record| record.taken.raced() && record.replay.is_none()) - .count() - } - - /// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder - /// whose pass took a rasterization-rate map since reset, before the commit, is to be encoded - /// again before its first submission, its log kept (`rate_mapped_pass.rs`); and why each that - /// kept no log did not, which draws by the map as it took it, for the caller to announce - /// without this lock (`rate-map-reset-unencoded`). - pub(super) fn rate_maps_reset(&self) -> (bool, Vec>) { - let mut again = false; - let mut unencoded = Vec::new(); - for record in &self.ended { - if !record.taken.rate_map_reset() { - continue; - } - match record.replay { - Some(_) => again = true, - None => unencoded.push(record.unlogged), - } - } - (again, unencoded) - } -} - -/// What [`State::keep_replays`] keeps and lets go of. -pub(super) struct KeptReplays { - /// The logs no rebind encodes again, for the caller to let go of without the lock. - pub(super) gone: Vec>, - /// The keys of the buffers over host pages the kept logs' encoders named. - pub(super) keys: Box<[ResourceKey]>, - /// The identities of the rasterization-rate maps its encoders' passes are over. - pub(super) maps: Box<[usize]>, - /// An encoder that keeps no log named a buffer over host pages - /// (`State::unlogged_names_a_pin`): its holds stay until its last group's submission. - pub(super) to_submission: bool, -} - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -impl CommandBuffer { - /// Hold its turn of encodings again (`reencoding`), as a rebind's turn holds it: a commit or a - /// rebind that encodes its encoders again waits until the guard drops. A test's. - pub(crate) fn hold_reencoding(&self) -> std::sync::MutexGuard<'_, ()> { - lock(&self.0.reencoding) - } - - /// Whether a failure of it is noted (`State::failure`): a check's, once - /// `State::fail_submission` marked the encoders it failed. A test's. - pub(crate) fn failure_noted(&self) -> bool { - lock(&self.0.state).failure.is_some() - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs deleted file mode 100644 index 34ce020f8..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs +++ /dev/null @@ -1,690 +0,0 @@ -//! The check after a predicated loop laid down as copies (`predication.rs`): where the step past -//! its last copy halted its unit (the loop would run another pass), the check runs the loop's -//! laying again, from the halted loop's copy on (the halt word, `bind::PredicationOp::WhileFirst`), -//! until the loop ends, as Metal runs a loop on; then the command buffer goes on. Metal never ends -//! a loop that runs without bound (an M3 Max with macOS 27.0.1 ran an endless While and DoWhile for -//! 180 s, each, with no error), and neither does the check. -//! -//! - **The laying** is its own run of pieces ([`Piece`]), in encoding order: the -//! `VkCommandBuffer`s the encoders recorded it into, each begun to be submitted again, and the -//! work they left apart between them (`Deferred`: an indirect dispatch or an indirect command -//! buffer's execution a host step records, or a dispatch whose variant records in a command -//! buffer of its own). The encoder cut its command buffer at the outermost loop's start -//! (`EncoderCore::cut_reusable`), at each later encoder of its unit and after each work apart -//! (`EncoderCore::continuation`), each behind a barrier from everything before it, and ends it at -//! the check (`EncoderCore::end_laying`), behind one to every later command and to the host; the -//! textures it shadows are copied back at each cut. A run again so repeats nothing encoded before -//! the loop (a render pass's load and store actions, a blit, an event's signal or wait) and -//! copies in again what it shadows; every dispatch in it is gated, and every step holds until -//! the halted loop's copy starts. -//! - **The work apart runs again as it first ran** ([`LoopCheck::learn`], at the commit, from the -//! segment each left): a run again submits the laying's command buffers up to it, and where its -//! first run waited for the work before it to complete (a host step that reads what the GPU -//! wrote: an indirect dispatch's arguments, an execution's records or its block's counter), waits -//! for them too, then records it again as its host step did (`Deferred::step`), or as the commit -//! did on the GPU alone (`Deferred::record_on_gpu`), and goes on. Those recordings come from a -//! command pool of the check's own, and take their descriptor sets and uploads from arenas of -//! its own, lent to the command buffer meanwhile ([`RunArenas`]); once the run again completed, -//! the pool is taken back, the sets' pools reset and the uploads let go (their chunks parked -//! for the next run, `recycle.rs`), so a loop that runs on holds no more of them than one run. -//! - **The check** is a host step (`Deferred::Loop`), its segment the first of the batch after the -//! laying: once the work before it completed, it reads the unit's halt word. 0: the batch goes. -//! Else a thread of its own ([`run_again`]) runs the laying again on the command buffer's -//! `VkQueue`, each submission with a fence of the device's, logged for the command buffer's -//! relayed failures (`device/relay.rs`), and reads the word again once the run completed, until -//! it is 0; then it wakes the scheduler. Meanwhile the batch waits as for a pipeline's making -//! (`Segment::steps_after_pipelines`), and the scheduler goes on with every other line; a batch -//! committed later on another queue that conflicts with the laying's uses waits behind it -//! (`CommandBufferShared::footprint`), as behind any host step. The batch's other segments step -//! once the check ends: they read what the laying leaves. -//! - **A rebind meanwhile** (`rebind.rs`). The check reads only the halt word, in the command -//! buffer's arena, and a laying that left no work apart is submitted again as it was encoded: -//! its command buffers name the pages of buffers over host pages that their first submission -//! took, which the command buffer holds until it completes, and the batch the check holds keeps -//! it from completing before the loop ends. So its commit holds none of those pages -//! (`Deferred::resolved_at_its_calls`): a rebind after that submission keeps the old pages for -//! every run again, as Metal's loop reads the pages its submission found, the loop's word -//! included; one before it fails that submission (`EncodedUseRebound`), its encoders keeping -//! no log to be encoded again from. Work apart is recorded again at each run, resolving the -//! buffers as they lie then, so a laying that left some holds every page its command buffer -//! used until it completes, and a rebind meanwhile is refused (`RebindProblem::EncodedUses`). -//! - **Ends.** As Metal's GPU runs a loop without bound on after the program let go of every -//! handle of its queue and its device, so does the thread, which holds the command buffer, and -//! through it the queue and the device. It stops only at a lost device, the GPU's recovery -//! from a fault or a hang anywhere on the device, as Metal's loop does (`recovery.rs`), a -//! failed submission, wait or recording (each failing the command buffer as its submission or -//! host step would), or the process's exit, which it never holds up: it waits in slices of -//! [`WAIT_SLICE`], each inside a section of the exit guard, and does nothing more once the -//! guard closes. Each run again is counted (`WorkCounts::predicated_loop_runs_again`). - -use super::gate::Hold; -use super::recovery::{self, Recovery}; -use super::{ - command_pool, recording_error, step_error, submission_error, CommandBuffer, CommandBufferShared, -}; -use crate::deferred::{Deferred, StepInputs}; -use crate::descriptor_arena::DescriptorArena; -use crate::device::lock; -use crate::encoder::{Recorded, RecordedSegment, Segment}; -use crate::error::{internal, CommandBufferError, Error}; -use crate::exit_guard::{self, Call}; -use crate::retained::Retained; -use crate::spares::CommandPool; -use crate::submit_failure::{submit_failed, try_lock, Failed}; -use crate::tracker::EncoderUses; -use crate::upload::{Upload, Uploads}; -use ash::vk; -use metal2vulkan::bind::ReplayFaults; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::Duration; - -/// How long one wait for a run again's fence lasts before the thread looks for an exit. -const WAIT_SLICE: Duration = Duration::from_millis(100); - -/// One piece of a loop's laying, in encoding order (the module docs). -pub(crate) enum Piece { - /// A `VkCommandBuffer` an encoder recorded the laying into, begun to be submitted again. - Raw(vk::CommandBuffer), - /// Work the encoder left apart there, which each run again records again. - Apart(Deferred), -} - -/// The arenas a check's runs again take their descriptor sets and uploads from, each lent to the -/// command buffer while a run's work apart records (`Uploads::lend`, `DescriptorArena::lend`), -/// and emptied once the run completed ([`settle`](Self::settle)). -struct RunArenas { - uploads: Arc>, - descriptors: Arc>, -} - -impl RunArenas { - /// Empty arenas. - fn new() -> RunArenas { - RunArenas { - uploads: Arc::new(Mutex::new(Uploads::new())), - descriptors: Arc::new(Mutex::new(DescriptorArena::default())), - } - } - - /// Lend the arenas to the command buffer of `state`, or (`false`) take them back. - fn lend(&self, state: &mut super::State, lent: bool) { - state.uploads.lend(lent.then(|| Arc::clone(&self.uploads))); - state - .descriptors - .lend(lent.then(|| Arc::clone(&self.descriptors))); - } - - /// The run again completed, so nothing uses what it took: the sets' pools reset for the next - /// run, and the uploads let go, without a lock of the command buffer (a chunk's last holder - /// parks it, `recycle.rs`). Inside a section of the exit guard; refused as the reset is. - fn settle(&self) -> Result<(), Error> { - let uploads = lock(&self.uploads).take(); - drop(uploads); - lock(&self.descriptors).reset() - } -} - -/// How a run again records a piece of work apart: as its first run did. -enum Again { - /// As its host step did, from `inputs`, after the work before it completed where `waits`. - Step { inputs: StepInputs, waits: bool }, - /// As the commit did, on the GPU alone. - OnGpu, -} - -impl Again { - /// How a run again records the work of `segment`, prepared by the commit: `None` where the - /// commit left it nothing a step takes. - fn of(segment: &Segment) -> Option { - if segment.gpu_alone { - return Some(Again::OnGpu); - } - let inputs = segment.inputs.clone()?; - Some(Again::Step { - inputs, - waits: segment.host || segment.work.gpu_written(), - }) - } -} - -/// The check after a loop's laying (the module docs). -pub(crate) struct LoopCheck { - /// The unit's skip counter: its halt word lies 4 bytes past it. - counter: Upload, - /// The laying, as encoded. - pieces: Vec, - /// How each of its pieces of work apart runs again, in order: learned at the commit. - agains: OnceLock>>, - /// The command buffer's parts before the laying's first: the laying lies in the parts from - /// there to the check's. - from: usize, - rounds: Mutex, -} - -/// Where a check stands. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Rounds { - /// Its host step has not read the halt word yet. - Unchecked, - /// Its thread runs the laying again. - Running, - /// The loop ended, or the check stopped. - Ended, -} - -/// Why a run again stopped short of reading the halt word. -enum Stop { - /// A failure the driver relayed for it: the command buffer fails with it at its completion. - Relayed, - /// The command buffer fails so. - Failed(CommandBufferError), - /// The process is exiting: the thread does nothing more. - Exiting, -} - -/// How one run again ended. -enum Round { - /// The loop would run on. - Again, - /// The loop ended, or a relayed failure ends the command buffer. - Ended, - /// The command buffer fails so. - Failed(CommandBufferError), - /// The loop stopped with no error, and nothing after it runs (`recovery.rs`). - Cut, - /// The process is exiting: the thread does nothing more. - Exiting, -} - -impl LoopCheck { - /// The check of the laying `pieces`, after `from` of the command buffer's parts, of the loop - /// of the unit of skip counter `counter`. - pub(crate) fn new(counter: Upload, pieces: Vec, from: usize) -> LoopCheck { - LoopCheck { - counter, - pieces, - agains: OnceLock::new(), - from, - rounds: Mutex::new(Rounds::Unchecked), - } - } - - /// The command buffer's parts before the laying's first. - pub(crate) fn from(&self) -> usize { - self.from - } - - /// Whether its laying left work apart, which each run again records again: a host step's - /// resolves the buffers its encoder named as it records, and work on the GPU alone records - /// over the buffers as they lie then (`Deferred::resolved_at_its_calls`). - pub(crate) fn leaves_work_apart(&self) -> bool { - (self.pieces.iter()).any(|piece| matches!(piece, Piece::Apart(_))) - } - - /// At the commit, with its segments prepared: learn how each piece of work apart runs again - /// from the segment it left among `parts`, the laying's parts and those after it. - pub(crate) fn learn(&self, parts: &[Recorded]) { - let segments = || parts.iter().flat_map(|part| &part.segments); - let agains = (self.pieces.iter()) - .filter_map(|piece| match piece { - Piece::Apart(work) => Some(work), - Piece::Raw(_) => None, - }) - .map(|work| segments().find(|segment| segment.work.same(work))) - .map(|segment| segment.and_then(Again::of)) - .collect(); - drop(self.agains.set(agains)); - } - - /// Whether its thread runs the laying again: its batch waits. - pub(crate) fn running(&self) -> bool { - *lock(&self.rounds) == Rounds::Running - } - - /// Whether the unit is halted: its halt word is not 0. Read once the work that writes it - /// completed. - fn halted(&self) -> bool { - self.counter.read::<8>()[4..] != [0; 4] - } - - /// Its host step, once the laying completed: nothing to record; where the loop halted its - /// unit, its thread starts running the laying again. Refused where the thread cannot start. - pub(crate) fn step( - self: &Arc, - command_buffer: &CommandBuffer, - ) -> Result { - if !self.halted() { - *lock(&self.rounds) = Rounds::Ended; - return Ok(nothing()); - } - *lock(&self.rounds) = Rounds::Running; - let check = Arc::clone(self); - let buffer = command_buffer.0.hold(); - // One of the threads that take a command buffer to its handlers (`exit_guard.rs`). - let builder = std::thread::Builder::new().name("metal2vulkan-loop".to_owned()); - let spawned = - exit_guard::spawn_user_interactive(builder, move || run_again(&check, buffer)); - if spawned.is_err() { - *lock(&self.rounds) = Rounds::Ended; - return Err(internal( - "a predicated loop's check could not start its thread", - )); - } - Ok(nothing()) - } - - /// Run the laying again on `buffer`'s `VkQueue`, its work apart recorded from `pool` and - /// `arenas`, and read the halt word. - fn run_once( - &self, - buffer: &Hold, - (pool, arenas): (&Arc>, &RunArenas), - ) -> Round { - let mut recordings = Vec::new(); - let ran = self.run_pieces(buffer, (pool, arenas), &mut recordings); - // Its recordings' command buffers go back to the pool for the next run: they ended there, - // none of the command buffer's own pool (`CommandBufferShared::end_raw` counted them). - let ended: usize = recordings.iter().map(|done| done.raws.len()).sum(); - buffer.raws_ended.fetch_sub(ended as u64, Ordering::Relaxed); - { - let mut state = lock(&buffer.state); - for done in &recordings { - state.faults = ReplayFaults(state.faults.0 | done.faults.0); - state.resident_misses = state.resident_misses.wrapping_add(done.resident_misses); - } - } - if ran.is_ok() { - lock(pool).taken(); - } - // Dropped without a lock: what it holds may be a state's last handle. - drop(recordings); - match ran { - Ok(()) => {} - Err(Stop::Relayed) => return Round::Ended, - Err(Stop::Failed(error)) => return Round::Failed(error), - Err(Stop::Exiting) => return Round::Exiting, - } - { - let Some(_busy) = exit_guard::enter() else { - return Round::Exiting; - }; - if let Err(error) = arenas.settle() { - return Round::Failed(recording_error(&buffer.device, error)); - } - } - buffer.device.shared().counts.predicated_loop_ran_again(); - match self.halted() { - true => Round::Again, - false => Round::Ended, - } - } - - /// The laying's pieces, in order: its command buffers submitted, up to each piece of work - /// apart whose first run waited for the work before it, which completes first; each piece of - /// work apart recorded again, its recording kept in `recordings` until the run completed. - fn run_pieces( - &self, - buffer: &Hold, - sources: (&Arc>, &RunArenas), - recordings: &mut Vec, - ) -> Result<(), Stop> { - let device = &buffer.device; - let unlearned = || { - let error = internal("a predicated loop's work apart without how it runs again"); - Stop::Failed(recording_error(device, error)) - }; - let agains = self.agains.get().ok_or_else(unlearned)?; - let mut agains = agains.iter(); - let mut submits = Vec::new(); - for piece in &self.pieces { - match piece { - Piece::Raw(raw) => submits.push(*raw), - Piece::Apart(work) => { - let again = (agains.next().and_then(Option::as_ref)).ok_or_else(unlearned)?; - if matches!(again, Again::Step { waits: true, .. }) && !submits.is_empty() { - self.submit(buffer, &submits)?; - submits.clear(); - } - let done = self.record(buffer, sources, work, again)?; - submits.extend(&done.raws); - recordings.push(done); - } - } - } - self.submit(buffer, &submits) - } - - /// Record `work` again as `again` says, its command buffers from `pool` and its sets and - /// uploads from `arenas`, as a host step: on this thread, inside a section of the exit guard, - /// with no lock of the command buffer held. - fn record( - &self, - buffer: &Hold, - (pool, arenas): (&Arc>, &RunArenas), - work: &Deferred, - again: &Again, - ) -> Result { - let _for = buffer.notices_for(); - let device = &buffer.device; - let Some(_busy) = exit_guard::enter() else { - return Err(Stop::Exiting); - }; - let _turn = lock(&buffer.reencoding); - let command_buffer = CommandBuffer(Arc::clone(buffer)); - { - let mut state = lock(&buffer.state); - state.rerun_pool = Some(Arc::clone(pool)); - arenas.lend(&mut state, true); - } - let record = || { - exit_guard::host_step(|| match again { - Again::OnGpu => (work.record_on_gpu(&command_buffer)?) - .map(|(recorded, _)| recorded) - .ok_or_else(|| internal("a predicated loop's work apart off the GPU")), - Again::Step { inputs, .. } => work.step(&command_buffer, inputs), - }) - }; - let recorded = match buffer.step_numbers.get() { - Some(numbers) => numbers.numbering(record), - None => record(), - }; - let mut state = lock(&buffer.state); - state.rerun_pool = None; - arenas.lend(&mut state, false); - match recorded { - // Its first run named no detached buffer, or the command buffer failed there. - Ok(done) if done.taken.dead() => { - drop(state); - let error = internal("a predicated loop's run again named a detached buffer"); - Err(Stop::Failed(recording_error(device, error))) - } - Ok(done) => Ok(done), - Err(error) => Err(Stop::Failed(step_error(device, error, &mut state.refusal))), - } - } - - /// Submit `raws` (ended, in order) on `buffer`'s `VkQueue` and wait for them to complete. - fn submit(&self, buffer: &CommandBufferShared, raws: &[vk::CommandBuffer]) -> Result<(), Stop> { - // SAFETY: each command buffer was begun to be submitted again (the laying's) or recorded - // for this submission alone (a run again's), ended, and is in no pending submission: the - // laying's batch completed before the check's step, and each submission of a run again - // before the next. - match unsafe { submit_waited(buffer, raws, "a predicated loop's check, run again") } { - Waited::Completed => Ok(()), - Waited::Relayed => Err(Stop::Relayed), - Waited::Failed(error) => Err(Stop::Failed(submission_error(&buffer.device, error))), - Waited::Exiting => Err(Stop::Exiting), - } - } -} - -/// How a submission the host waited for ended ([`submit_waited`]). -pub(super) enum Waited { - Completed, - /// A failure the driver relayed for it: the command buffer fails with it at its completion. - Relayed, - /// Its submission or its wait failed so. - Failed(vk::Result), - /// The process is exiting: nothing more is done. - Exiting, -} - -/// Submit `raws` (ended, in order) on `buffer`'s `VkQueue` and wait for them to complete, in -/// slices: a predicated loop's run again ([`LoopCheck`]). `what` names it for the encoder trail's -/// line, where the device's trail is on and it ran for its bound (`encoder_trail.rs`, **Host -/// steps**). -/// -/// # Safety -/// -/// As [`submit_fenced`]'s. -pub(super) unsafe fn submit_waited( - buffer: &CommandBufferShared, - raws: &[vk::CommandBuffer], - what: &str, -) -> Waited { - // SAFETY: the caller's. - match unsafe { submit_fenced(buffer, raws, what) } { - Ok(fenced) => wait_fenced(buffer, &[fenced], what), - Err(ended) => ended, - } -} - -/// A submission of [`submit_fenced`]'s, not yet waited for: its fence, of the device's, in the -/// relay's log until [`wait_fenced`] sees it signaled and gives it back. -pub(crate) struct Fenced { - fence: vk::Fence, - queue: usize, -} - -/// Submit `raws` (ended, in order) on `buffer`'s `VkQueue` with a fence of the device's, logged -/// for the command buffer's relayed failures (`device/relay.rs`), for the host to wait for later -/// ([`wait_fenced`]): a host step's probe of a rate-mapped pass, in parts (`render/executions.rs`, -/// `DeferredPass::probe_parts`). Its submission's failure, or the process's exit, ends it so. -/// -/// # Safety -/// -/// Each of `raws` is a command buffer of `buffer`'s device, ended, in no pending submission, and -/// begun to be submitted again or recorded for this submission alone; what it uses lives until -/// it completes, which a wait for it ([`wait_fenced`]) sees. -pub(super) unsafe fn submit_fenced( - buffer: &CommandBufferShared, - raws: &[vk::CommandBuffer], - what: &str, -) -> Result { - let device = &buffer.device; - let Some(_busy) = exit_guard::enter() else { - return Err(Waited::Exiting); - }; - let shared = device.shared(); - let raw = shared.vk(); - // SAFETY: the device's fences, inside a section. - let fence = match unsafe { shared.fences.take(raw) } { - Ok(fence) => fence, - Err(error) => return Err(Waited::Failed(error)), - }; - let queue = buffer.queue.vk_queue(); - let submits = [vk::SubmitInfo::default().command_buffers(raws)]; - shared.counts.queue_submitted(1, raws.len()); - // SAFETY: the `VkQueue` is used under its lock; each command buffer is the caller's; the - // fence is unsignaled and in no pending submission. - let submitted = shared.submit_logged( - (queue, None, raws.len(), None), - Some(fence), - &buffer.relayed, - |vk_queue| unsafe { raw.queue_submit(vk_queue, &submits, fence) }, - ); - exit_guard::called(Call::QueueSubmit); - if let Err(error) = submitted { - let failed = Failed { - what, - queue: Some(queue), - result: error, - infos: &submits, - fence: Some(fence), - }; - submit_failed(device, &failed, |carried, types| { - // Its submitter may hold the command buffer's state: then it is named alone. - match try_lock(&buffer.state) { - Some(state) => buffer.carry(&state, (None, None), carried, types), - None => carried.buffers.push(format!("#{}", buffer.id.get())), - } - }); - // SAFETY: a fence no submission took. - unsafe { crate::release::object(raw, fence) }; - return Err(Waited::Failed(error)); - } - Ok(Fenced { fence, queue }) -} - -/// Wait, in slices, until every submission of `fenced` (each [`submit_fenced`]'s on `buffer`'s -/// `VkQueue`) completed, then give their fences back: how they ended. `what` names them for the -/// encoder trail's line, as [`submit_waited`]'s. -pub(super) fn wait_fenced(buffer: &CommandBufferShared, fenced: &[Fenced], what: &str) -> Waited { - let Some(last) = fenced.last() else { - return Waited::Completed; - }; - let device = &buffer.device; - let shared = device.shared(); - let mut fences: Vec = fenced.iter().map(|fenced| fenced.fence).collect(); - // The encoder trail's line is due once, past its bound. - let began = std::time::Instant::now(); - let mut trailed = !shared.encoder_trail; - loop { - let Some(_busy) = exit_guard::enter() else { - return Waited::Exiting; - }; - // The device's functions, reached inside a section (`DeviceShared::vk`). - let raw = shared.vk(); - // SAFETY: the device's fences, each submitted by `submit_fenced`. - let waited = unsafe { raw.wait_for_fences(&fences, true, WAIT_SLICE.as_nanos() as u64) }; - exit_guard::called(Call::WaitForFences); - match waited { - Ok(()) => break, - Err(vk::Result::TIMEOUT) => { - if !trailed && began.elapsed() >= crate::encoder_trail::AFTER { - trailed = true; - trail_waited(buffer, last.queue, what, began.elapsed()); - } - continue; - } - // The fences stay in the relay's log, as a failed batch's do, never released. - Err(error) => return Waited::Failed(error), - } - } - let Some(_busy) = exit_guard::enter() else { - return Waited::Exiting; - }; - let raw = shared.vk(); - // Out of the relay's log before they go back: their submissions completed. - for fenced in fenced { - if let Some(flights) = shared.flights(fenced.queue) { - flights.let_go(fenced.fence); - } - } - // SAFETY: the fences are signaled and their submissions completed. - let reset = unsafe { raw.reset_fences(&fences) }; - exit_guard::called(Call::ResetFences); - match reset { - // SAFETY: unsignaled and in no pending submission; inside a section. - Ok(()) => unsafe { shared.fences.give(raw, &mut fences) }, - Err(_) => { - for fence in fences { - // SAFETY: in no pending submission. - unsafe { crate::release::object(raw, fence) }; - } - } - } - // A failure the driver relayed for them fails the command buffer at its completion. - match buffer.relayed.failure() { - Some(_) => Waited::Relayed, - None => Waited::Completed, - } -} - -/// The encoder trail's line of `what`, a submission on `VkQueue` `queue` of `buffer`'s that the host -/// waits for and that ran for `ran` (`encoder_trail.rs`, **Host steps**): the encoder whose host -/// step made it, where one did, with the states its commands named so far. -fn trail_waited(buffer: &CommandBufferShared, queue: usize, what: &str, ran: Duration) { - let device = &buffer.device; - let step = lock(&buffer.step_trail) - .as_ref() - .map(|step| step.described()); - let what = match step { - Some(step) => format!("{what} of a host step of {step}"), - None => format!("{what} of command buffer {}", buffer.id.get()), - }; - let last = device.shared().completion.trail_last(queue); - let last = last.as_ref().map(|(trail, ago)| (&**trail, *ago)); - let line = crate::encoder_trail::waited_line(queue, &what, ran, last); - device.inform(crate::encoder_trail::ID_NAME, line); -} - -/// A recording of nothing: a check records no command. -fn nothing() -> RecordedSegment { - RecordedSegment { - raws: Vec::new(), - summary: EncoderUses::new(true).finish(), - retained: Retained::default(), - executions: Vec::new(), - keys: Default::default(), - taken: Default::default(), - resident_misses: 0, - faults: ReplayFaults::default(), - takes: Default::default(), - piece_ends: Vec::new(), - } -} - -/// The loop's decision before each run again: `None` where it runs again; else how it ends -/// without running. It stops once its device is lost (the module docs), and at the GPU's -/// recovery from a fault (as a victim) or a hang (cut) since its command buffer's first -/// submission (`recovery.rs`). -fn before_round(buffer: &CommandBufferShared) -> Option { - if buffer.device.is_lost() { - return Some(Round::Failed(CommandBufferError::DeviceLost)); - } - match recovery::recovered(buffer)? { - Recovery::Fault => Some(Round::Failed(CommandBufferError::GpuRecoveryVictim)), - Recovery::Hang => Some(Round::Cut), - } -} - -/// The check's thread (the module docs): run the laying again until the loop ends, or the check -/// stops ([`before_round`]); then the scheduler takes the batch again. -fn run_again(check: &LoopCheck, buffer: Hold) { - let device = &buffer.device; - let waker = device.shared().scheduler.waker(); - // A new one, made inside a section as every Vulkan call of the runtime's threads is (a spare - // of the device's is taken outside one alone), given to the device's spares at the end. - let family = device.shared().queue_family_of(buffer.queue.vk_queue()); - let pool = { - let Some(_busy) = exit_guard::enter() else { - // What it holds stays held to the process's end, as the scheduler's does. - return std::mem::forget(buffer); - }; - command_pool(device, family).map(|pool| Arc::new(Mutex::new(pool))) - }; - let arenas = RunArenas::new(); - let (failure, settled) = match &pool { - Ok(pool) => loop { - let round = - before_round(&buffer).unwrap_or_else(|| check.run_once(&buffer, (pool, &arenas))); - match round { - Round::Again => continue, - Round::Ended => break (None, true), - // A recording it left unended leaves the pool to be reset. - Round::Failed(error) => break (Some(error), false), - Round::Cut => { - recovery::cut(&buffer, check); - break (None, true); - } - // What it holds stays held to the process's end, as the scheduler's does. - Round::Exiting => { - std::mem::forget(arenas); - return std::mem::forget(buffer); - } - } - }, - Err(error) => (Some(recording_error(device, error.clone())), true), - }; - if let Some(error) = failure { - lock(&buffer.state).step_failure.get_or_insert(error); - } - // Nothing of it is pending: each submission completed before the thread went on. - if let Ok(pool) = pool { - if let Ok(pool) = Arc::try_unwrap(pool) { - let pool = pool - .into_inner() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let shared = device.shared(); - let recorded = buffer.recorded.load(Ordering::Relaxed); - shared - .spares - .give_command_pool(shared, pool, settled, recorded); - } - } - *lock(&check.rounds) = Rounds::Ended; - waker(); - drop(buffer); -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/revocation.rs b/crates/metal2vulkan-runtime/src/command_buffer/revocation.rs deleted file mode 100644 index 18c38e1c5..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/revocation.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! A queue Metal stops serving after GPU errors its command buffers caused. -//! -//! Measured on the M3 Max with macOS 27.0.1 (about sixty command buffers over five runs; each a -//! blit, a pass of one draw of primitive type 9, a blit, an event signal and a blit, then one -//! committed at once, one committed some milliseconds on, and one committed after the first -//! completed, on queues used in turn): -//! -//! - **Caused errors count, per queue.** A command buffer that fails with -//! `MTLCommandBufferErrorPageFault` (3) or `MTLCommandBufferErrorTimeout` (2, a GPU hang) -//! counts against its queue. One that fails as a victim of the GPU's recovery -//! (`MTLCommandBufferErrorInternal`, "Discarded (victim of GPU error/recovery)") does not: -//! three on one queue, and a victim then a fault, left the queue serving. A command buffer -//! Metal's watchdog fails counts too: on the same Mac two command buffers of one queue, each -//! waiting for a shared event no one signalled, failed in turn with -//! `MTLCommandBufferErrorTimeout` ("Caused GPU Timeout Error -//! (00000002:kIOGPUCommandBufferCallbackErrorTimeout)") 5.00 s after their commits, and the -//! fill committed after them failed with `MTLCommandBufferErrorAccessRevoked` 0.24 ms after its -//! commit, nothing of it run, where a new queue's ran. -//! - **The second one revokes the queue.** Once the queue's second command buffer with a caused -//! error completes (two faults, two hangs, a hang then a fault), every command buffer committed -//! on the queue after that fails at its commit: `Scheduled` and completed 0.02 to 0.06 ms after -//! its commit, with status `Error` and `MTLCommandBufferErrorAccessRevoked` (4, "Ignored (for -//! causing prior/excessive GPU errors) -//! (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored)"); none of its work runs, none -//! of its event signals fires, and its GPU and kernel times span nothing. Two seconds on it was -//! so still. One committed before that completion, 4.5 ms into the second fault, ran; one -//! committed 0.5 ms after it, and later ones, did not. -//! - **Other queues serve on.** A new queue of the same device ran normally after others were -//! revoked, its own first fault or hang leaving it serving. -//! - The second faulting command buffer itself answers as the first did (its other encoders ran -//! in 9 of 11 runs, nothing of it in 2), as does one committed at once after it. -//! -//! The runtime counts the command buffers of a queue that complete with a failure of its own -//! making that Metal's GPU causes: [`CommandBufferError::PageFault`] as the runtime fails an -//! encoder Metal's GPU faults (a draw of primitive type 9 over indices, a render encoder's -//! execution of an indirect command buffer under a state it cannot inherit), and -//! [`CommandBufferError::GpuHang`]; and one a program commits as failed in their place -//! (`CommandBuffer::commit_failed`, [`CommandBufferError::Injected`] of Metal's code of either, -//! 3 or 2), which stands for what Metal's GPU caused. The watchdog's `GpuHang` (`stall.rs`) counts -//! as Metal's timeout does. The count is the queue's over every place of it: a recovery's new -//! place of the queue keeps it (`queue.rs`), as Metal's queue, which no recovery replaces, keeps -//! its own. Of the other codes it counts none: a -//! victim's (1) does not count on Metal, and the rest are not caused GPU errors or not measured. -//! A failure the driver relays is the driver's own queue's, which Metal counts itself under -//! MoltenVK. From the completion of the second one, before its -//! status reads final, the queue is revoked: a command buffer committed on it then fails with -//! [`CommandBufferError::AccessRevoked`] as its commit's work, from its first encoder, its event -//! signals dropped (`commit_now`). One committed before runs as committed, whatever its event -//! waits (Metal's answer for one held by a wait across the revocation is not measured). - -use crate::error::CommandBufferError; -use std::sync::atomic::{AtomicU32, Ordering}; - -/// The command buffers whose GPU error Metal counts against their queue that revoke it. -const REVOKING: u32 = 2; - -/// A queue's count of its command buffers that completed with a GPU error they caused (the -/// module docs). -#[derive(Default)] -pub(crate) struct QueueErrors { - caused: AtomicU32, -} - -impl QueueErrors { - /// A command buffer of the queue completes with `error` (`None` for none), before its status - /// reads final: counted where the GPU caused it ([`caused`]). - pub(super) fn completed(&self, error: Option) { - if error.is_some_and(caused) { - self.caused.fetch_add(1, Ordering::SeqCst); - } - } - - /// Whether Metal ignores the queue's command buffers committed now: its second command buffer - /// with a caused error completed. - pub(super) fn revoked(&self) -> bool { - self.caused.load(Ordering::SeqCst) >= REVOKING - } -} - -/// Whether a command buffer that completed with `error` counts against its queue (the module -/// docs): a page fault or a hang, the runtime's or one a program injected in its place by its -/// Metal code. -pub(crate) fn caused(error: CommandBufferError) -> bool { - let of = |caused: CommandBufferError| caused.metal_code(); - match error { - CommandBufferError::PageFault | CommandBufferError::GpuHang => true, - CommandBufferError::Injected(code) => { - code == of(CommandBufferError::PageFault) || code == of(CommandBufferError::GpuHang) - } - _ => false, - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/spare_states.rs b/crates/metal2vulkan-runtime/src/command_buffer/spare_states.rs deleted file mode 100644 index 2f06e3cba..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/spare_states.rs +++ /dev/null @@ -1,198 +0,0 @@ -//! The states of a device's released command buffers, kept for the command buffers it makes -//! next. A released command buffer's state is reset in place by the thread that releases it -//! ([`State::reset`]): what it held goes as it went before, at the release, and its lists of what -//! its encoders ended with (its ended encoders' records, their recordings, the logs of a group of -//! encoders recorded into one `VkCommandBuffer` its members did not keep, `encoder_fold.rs`'s -//! `Fold`, and those held for its commit, `fold.rs`), its command predication's lists -//! (`predication.rs`) and its groups' order (`FoldOrder`, its map and its resources' lists) are -//! emptied with their room kept. A command buffer being made takes a kept state whole -//! ([`SpareStates::take`]): its making neither allocates nor fills one, and its encoders' ends push -//! into room the lists already had rather than grow them one reallocation at a time over fresh -//! pages. Its release also keeps up to [`STATE_LOGS`] of its compute encoders' logs, cleared, in -//! the state (`State::compute_logs`): the compute encoders of the command buffer that takes it -//! take those, under the lock their open takes, rather than the device's spares' (`replay.rs`), -//! whose lock the queues' handler threads take as they give logs back. A state goes on only to -//! command buffers of the device generation that made it, and the kept ones go with that -//! generation. - -use std::sync::atomic::AtomicU64; -use std::sync::{Arc, Mutex}; - -use super::State; -use crate::device::lock; -use crate::encoder::Recorded; -use crate::encoder_fold::{FoldOrder, Stashed}; -use crate::predication::Predication; -use crate::resource::ResourceKey; -use crate::used_resources::EncoderRecord; - -/// The states a device keeps, at most: one per uncompleted command buffer of a queue of Metal's -/// default `maxCommandBufferCount`, so the releases of a queue's whole run of command buffers -/// serve the makings after them. -const SPARE_STATES: usize = 64; - -/// The room a kept state's lists hold, at most, in bytes: a command buffer of more encoders than -/// that room holds lets its state go. A command buffer of a few thousand one-dispatch encoders -/// fits. -const STATE_ROOM_BYTES: usize = 8 << 20; - -/// The room the kept states' lists hold together, at most, in bytes. -const SPARE_ROOM_BYTES: usize = 2 * STATE_ROOM_BYTES; - -/// The cleared compute logs a state keeps, at most (`State::compute_logs`): each holds at most -/// `SPARE_LOG_BYTES` (64 KiB, `replay.rs`), and their room counts toward the state's -/// ([`STATE_ROOM_BYTES`]). -pub(super) const STATE_LOGS: usize = 32; - -/// The lists of records a state keeps the room of ([`Room`]). -const LISTS: usize = 12; - -/// The room of each of a state's lists of records, in entries (its ended encoders' records, their -/// recordings, its stash of a group's logs, the logs it holds for its commit, its command -/// predication's five lists, and its groups' order's map, boxes and priors), and the room they -/// and the compute logs it keeps hold, in bytes. -#[derive(Clone, Copy, Default)] -pub(super) struct Room { - lists: [usize; LISTS], - bytes: usize, -} - -impl Room { - /// The room of a state's lists: of its lists of records `records` (its ended encoders' - /// records, their recordings, its stash and the logs it holds for its commit), of its command - /// predication's lists `predication` (`Predication::room`), of its groups' order `order` - /// (`FoldOrder::room`), each in entries, and of the compute logs it keeps, `logs` bytes. - pub(super) fn new( - records: [usize; 4], - predication: [usize; 5], - order: [usize; 3], - logs: usize, - ) -> Room { - let [ended, recorded, stashed, held_logs] = records; - let bytes = ended * std::mem::size_of::() - + recorded * std::mem::size_of::() - + (stashed + held_logs) * std::mem::size_of::() - + Predication::room_bytes(predication) - + FoldOrder::::room_bytes(order) - + logs; - let [runs, open_checks, opened, alone, opened_fresh] = predication; - let [map, boxes, priors] = order; - let lists = [ - ended, - recorded, - stashed, - held_logs, - runs, - open_checks, - opened, - alone, - opened_fresh, - map, - boxes, - priors, - ]; - Room { lists, bytes } - } - - /// How many of the lists hold more room in `now` than in this: those that grew since. - pub(super) fn grown(self, now: Room) -> u64 { - let grown = (self.lists.iter().zip(now.lists)).filter(|&(&was, now)| now > was); - grown.count() as u64 - } - - /// The room, in bytes. - pub(super) fn bytes(self) -> usize { - self.bytes - } -} - -/// A released command buffer's state, reset, as a device keeps it: the state, the revision its -/// parts that footprints are built from move (`Footprints::revision`), which the command buffer -/// that takes it builds its footprints against, and the room its lists hold, in bytes. -pub(super) struct KeptState { - pub(super) state: Arc>, - pub(super) revision: Arc, - bytes: usize, -} - -impl KeptState { - /// `state`, reset, whose parts move `revision` and whose lists hold `room`. - pub(super) fn new(state: Arc>, revision: Arc, room: Room) -> KeptState { - KeptState { - state, - revision, - bytes: room.bytes(), - } - } - - /// A state built for a command buffer being made, where the device keeps none: lists of no - /// room, under a revision of its own. - pub(super) fn fresh() -> KeptState { - let revision = Arc::default(); - let state = Arc::new(Mutex::new(State::new(&revision))); - KeptState { - state, - revision, - bytes: 0, - } - } -} - -/// A device's states of its released command buffers, which the command buffers it makes next -/// take (the module docs): at most [`SPARE_STATES`], whose lists hold at most -/// [`SPARE_ROOM_BYTES`] together and [`STATE_ROOM_BYTES`] each, the latest given taken first. -#[derive(Default)] -pub(crate) struct SpareStates(Mutex); - -/// What [`SpareStates`] holds. -#[derive(Default)] -struct Spare { - kept: Vec, - /// The room the kept states' lists hold, in bytes. - bytes: usize, -} - -impl Spare { - /// Whether it has a place for a state whose lists hold `bytes`. - fn fits(&self, bytes: usize) -> bool { - bytes <= STATE_ROOM_BYTES - && self.kept.len() < SPARE_STATES - && self.bytes + bytes <= SPARE_ROOM_BYTES - } -} - -impl SpareStates { - /// The state a command buffer being made takes: the latest a released one left, if any. - pub(super) fn take(&self) -> Option { - let mut spare = lock(&self.0); - let kept = spare.kept.pop()?; - spare.bytes -= kept.bytes; - Some(kept) - } - - /// Whether it would keep a state whose lists hold `room` now: a released command buffer's - /// state is reset only where it would. - pub(super) fn wants(&self, room: Room) -> bool { - lock(&self.0).fits(room.bytes()) - } - - /// Keep `kept`, a released command buffer's state, reset, where it has a place for it; else - /// it goes with the command buffer. Whether it was kept. - pub(super) fn give(&self, kept: KeptState) -> bool { - let mut spare = lock(&self.0); - if !spare.fits(kept.bytes) { - return false; - } - spare.bytes += kept.bytes; - spare.kept.push(kept); - true - } - - /// The states it keeps, and the room their lists hold, in bytes: a device test's - /// (`tests::spare_states`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn held(&self) -> (usize, usize) { - let spare = lock(&self.0); - (spare.kept.len(), spare.bytes) - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs b/crates/metal2vulkan-runtime/src/command_buffer/stall.rs deleted file mode 100644 index 241004639..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs +++ /dev/null @@ -1,312 +0,0 @@ -//! A GPU that stopped: work pending that never completes, and no error from the driver. -//! -//! Metal fails GPU work that runs too long: the command buffer fails with -//! `MTLCommandBufferErrorTimeout` (code 2, the runtime's `GpuHang`) and the device goes on. On an -//! Apple M3 Max (macOS 27.0.1) a kernel of 2^29 threadgroups finished in 4.98 s and one of 2^30 -//! did not finish (`error.rs`, `GpuRecoveryVictim`); a command buffer that waited for an event -//! (shared and signalled by the host, or plain and signalled by a command buffer of another -//! queue) that no one signalled failed with code 2 ("Caused GPU Timeout Error -//! (00000002:kIOGPUCommandBufferCallbackErrorTimeout)") 5.00 s after its commit, none of its work -//! run, and the second such one of a queue revoked it (`revocation.rs`). On x86 Macs an AMD GPU -//! failed long work after 20.2 s and an Intel one after 16.1 s, where an 8 s kernel completed on -//! both (`kIOAccelCommandBufferCallbackErrorTimeout`, code 2). Vulkan has no such bound: a driver -//! ends a hang as a lost device (`VK_ERROR_DEVICE_LOST`), which the device's line recovers from -//! (`device/line.rs`). On NVIDIA's driver after an Xid 109 (a context switch timeout) the -//! device's queues stopped instead: no batch completed, and every wait of the completion's -//! waiters answered `VK_TIMEOUT` (`WAIT_SLICE`, `completion.rs`), never a loss, so the program's -//! command buffers waited without end. On an RTX 3090 (620.70.06) its copy engine ran on: a probe -//! there completed in under a millisecond while the graphics queue's batch never did. -//! -//! - **The stall clock** ([`Clock`]): one per device, the completion's waiters' own, under their -//! lock. It runs while a waiter's wait ran out with its queue's front batch pending, and stops -//! whenever any queue's timeline advances, so it measures how long no work of the device -//! advanced while some was pending. Counted: `WorkCounts::longest_stall_nanos`. -//! - **The probe** ([`probe`]). Past [`STALL`], one waiter sends a probe to another engine: the -//! staging queue (`device/staging.rs`; NVIDIA's copy engine), a submission of nothing that waits -//! for nothing but the staging submissions before it, which wait for no work in flight. For up -//! to [`PROBE`] it looks, each [`LOOK`], at the probe's answer and at the stuck front's: its -//! fence (a wait of no time, which answers its status) and its queue's timeline -//! (`vkGetSemaphoreCounterValue`). A loss either read answers takes the failed wait's path at -//! once, as the device's own signal. One informational message names the stall, the probe's -//! answer and the last result of each read (`metal2vulkan-stall-probe`). Counted: -//! `WorkCounts::stall_probes_sent`. -//! - **The verdict.** Where the probe completed or the front advanced, the GPU runs: nothing -//! fails, and the clock starts again. Where neither did within [`PROBE`], the generation -//! stopped ([`Stop::Unanswered`]): it is marked so and lost (`Device::mark_wedged`), and the -//! waiter's wait fails as a lost device's: the oldest command buffer in flight fails as the hang -//! (`GpuHang`) and the rest as its victims (`GpuRecoveryVictim`), and the line recovers on a new -//! `VkDevice`, announced (`Degradation::DeviceRecovered`, which says the generation stopped). -//! Counted: `WorkCounts::wedges_declared`. -//! - **The watchdog**, Metal's own bound on a command buffer. Each queue's front batch has its -//! own clock ([`Clock::front_held`]), which runs while its waiter's waits run out with it -//! pending and stops whenever its queue's timeline advances, whatever the probe or another -//! engine answers. Past [`WATCHDOG`] the front fails as Metal's timed-out command buffer does -//! (`GpuHang`, code 2, which counts against its queue as Metal counts a timeout: the M3 Max's -//! above), the rest in flight as its victims (`GpuRecoveryVictim`), and the generation is -//! marked stopped ([`Stop::Watchdog`]), parked and recovered from as above: a channel that ran -//! nothing for so long is not trusted with more. The clock counts an event wait, as Metal's -//! does. Said once (`metal2vulkan-watchdog`); counted: `WorkCounts::watchdog_timeouts`. -//! - **Parked, never destroyed.** The stopped generation's work never completes, so nothing of -//! it may be destroyed (each `vkDestroy*` asks that nothing pending use the object) and no wait -//! for its queues returns: its `VkDevice` is parked (`release.rs`), none of its objects is -//! released from then on, the device itself included, and nothing waits for its queues -//! (`DeviceShared::queues_idle`). A consumer that holds its handles (`Device::raw`) asks -//! [`Device::is_parked`](crate::Device::is_parked) to leave them likewise. A leak of what the -//! generation held, and a driver may wait for its work at the process's exit (NVIDIA's did: -//! docs/FAST-PATHS.md, known gaps). -//! - **Bounds.** [`STALL`] is 10 s, twice the M3 Max's bound and under the x86 Macs'; a stopped -//! generation whose probe goes unanswered fails after 12 s at least. [`WATCHDOG`] is 20.2 s, -//! the largest of Metal's measured bounds (the x86 AMD GPU's), so no work that Metal completes -//! on any of the GPUs measured is failed; the M3 Max fails it from 5 s, the runtime from -//! 20.2 s. A device without a staging queue sends no probe, and a stop there is found by the -//! watchdog alone (docs/FAST-PATHS.md, known gaps). - -use crate::exit_guard::{self, Call}; -use crate::Device; -use ash::vk; -use std::time::{Duration, Instant}; - -/// How long no queue's work may advance, with some pending, before a probe asks whether the GPU -/// still runs anything (the module docs). -pub(super) const STALL: Duration = Duration::from_secs(10); - -/// How long a probe waits for an answer before the generation counts as stopped. -pub(super) const PROBE: Duration = Duration::from_secs(2); - -/// How long a queue's front batch may go without its timeline advancing before it fails as -/// Metal's timed-out command buffer (the module docs): the largest of Metal's measured bounds. -pub(super) const WATCHDOG: Duration = Duration::from_millis(20_200); - -/// How long one look of a probe waits for its answer. -const LOOK: Duration = Duration::from_millis(100); - -/// Why a generation stopped (`Device::mark_wedged`, the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Stop { - /// No work of it advanced, and a probe on another engine did not complete. - Unanswered, - /// A queue's front batch went past [`WATCHDOG`] without its timeline advancing. - Watchdog, -} - -/// The device's stall clock and its queues' watchdog clocks (the module docs), under the -/// completion's lock. -pub(super) struct Clock { - /// Since when no queue's timeline advanced while a front was pending. - since: Option, - /// A waiter probes: no other does meanwhile. - probing: bool, - /// Per `VkQueue`: since when its front batch has gone without its timeline advancing. - fronts: Vec>, - /// The encoder trail named this stall's stuck encoders (`encoder_trail.rs`). - trailed: bool, -} - -impl Clock { - /// The clocks of a device of `queues` `VkQueue`s, none running. - pub(super) fn new(queues: usize) -> Clock { - Clock { - since: None, - probing: false, - fronts: vec![None; queues], - trailed: false, - } - } - - /// `queue`'s timeline advanced: its front's watchdog clock stops. - pub(super) fn front_advanced(&mut self, queue: usize) { - self.fronts[queue] = None; - } - - /// `queue`'s waiter's wait ran out with its front pending: how long the front has gone - /// without its timeline advancing, as its waiter saw it. - pub(super) fn front_held(&mut self, queue: usize) -> Duration { - self.fronts[queue] - .get_or_insert_with(Instant::now) - .elapsed() - } - - /// A queue's timeline advanced: the clock stops. How long it ran, where it ran. - pub(super) fn advanced(&mut self) -> Option { - self.trailed = false; - self.since.take().map(|since| since.elapsed()) - } - - /// A waiter's wait ran out with its queue's front pending, the device's encoder trail on - /// (`encoder_trail.rs`): the clock runs. How long it has run where it passed `after` and the - /// trail named this stall's encoders no time before, now named. - pub(super) fn trail_due(&mut self, after: Duration) -> Option { - let stalled = self.since.get_or_insert_with(Instant::now).elapsed(); - let due = !self.trailed && stalled >= after; - self.trailed |= due; - due.then_some(stalled) - } - - /// A waiter's wait ran out with its queue's front pending: the clock runs. How long it has run - /// where it passed `after` and no waiter probes, this one then probing. - pub(super) fn ran_out(&mut self, after: Duration) -> Option { - let stalled = self.since.get_or_insert_with(Instant::now).elapsed(); - let due = !self.probing && stalled >= after; - self.probing |= due; - due.then_some(stalled) - } - - /// The probe ended, the GPU running: the clock starts again. - pub(super) fn probed(&mut self) { - self.probing = false; - self.since = Some(Instant::now()); - } -} - -/// What a probe found ([`probe`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Verdict { - /// The front advanced or the probe completed (or could not be sent, which proves nothing). - Runs, - /// A read answered this failure: the failed wait's path takes it. - Failed(vk::Result), - /// Neither within [`PROBE`]: the generation stopped. - Stopped, -} - -/// How long the clock runs before a probe on `device`: [`STALL`], or what a device test set -/// (`device/line.rs`'s hooks). -pub(super) fn stall_after(device: &Device) -> Duration { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if let Some(after) = *crate::device::lock(&device.line().hooks.stall_after) { - return after; - } - let _ = device; - STALL -} - -/// How long a queue's front may go without its timeline advancing on `device`: [`WATCHDOG`], or -/// what a device test set (`device/line.rs`'s hooks). -pub(super) fn watchdog_after(device: &Device) -> Duration { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if let Some(after) = *crate::device::lock(&device.line().hooks.watchdog_after) { - return after; - } - let _ = device; - WATCHDOG -} - -/// Say that the front batch of `device`'s `VkQueue` `queue` went `held` without its timeline -/// advancing, past the watchdog's bound `after` (the module docs). -pub(super) fn timed_out(device: &Device, queue: usize, held: Duration, after: Duration) { - device.inform( - "metal2vulkan-watchdog", - format!( - "metal2vulkan: the front batch of VkQueue {queue} went {held:?} without its timeline \ - advancing, past Metal's watchdog bound ({after:?}), whatever another engine \ - answered: its command buffer fails as Metal's timed-out one (`GpuHang`), the rest in \ - flight as its victims, and the generation stops and is parked" - ), - ); -} - -/// Whether `device` sends probes: where it has a staging queue (the module docs, **Bounds**), or a -/// device test has no probe seen answered (`device/line.rs`'s hooks). -pub(super) fn probes(device: &Device) -> bool { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if (device.line().hooks.probe_unanswered).load(std::sync::atomic::Ordering::Acquire) { - return true; - } - device.has_staging_queue() -} - -/// Probe `device` after `stalled` with no queue's work advancing (the module docs), the stuck -/// front the batch of `VkQueue` `queue` that signals `value`, and `fence` where it has one. -pub(super) fn probe( - device: &Device, - queue: usize, - (value, fence): (u64, Option), - stalled: Duration, -) -> Verdict { - let shared = device.shared(); - shared.counts.stall_probe_sent(stalled); - let raw = shared.vk(); - let timeline = shared.queues[queue].timeline; - let sent = device - .staging_lock() - .and_then(|mut staging| staging.probe()); - let began = Instant::now(); - let mut fence_read: Option = None; - let mut timeline_read: Result; - let mut answered: Result = Ok(false); - let verdict = loop { - if let Some(fence) = fence { - // SAFETY: the fence is the device's, in a submission made and not yet reset (its batch - // is pending, and is not taken while its waiter probes), live while the device is - // (held here). A wait of no time answers its status. - let looked = unsafe { raw.wait_for_fences(&[fence], true, 0) }; - exit_guard::called(Call::WaitForFences); - fence_read = Some(looked.err().unwrap_or(vk::Result::SUCCESS)); - } - // SAFETY: the semaphore is the device's timeline, live while the device is (held here). - timeline_read = unsafe { raw.get_semaphore_counter_value(timeline) }; - exit_guard::called(Call::GetSemaphoreCounterValue); - let failed = match (fence_read, timeline_read) { - (Some(error @ vk::Result::ERROR_DEVICE_LOST), _) | (_, Err(error)) => Some(error), - _ => None, - }; - if let Some(error) = failed { - break Verdict::Failed(error); - } - if fence_read == Some(vk::Result::SUCCESS) || timeline_read.is_ok_and(|read| read >= value) - { - break Verdict::Runs; - } - answered = match &sent { - Ok(sent) => device - .staging_reached(*sent, LOOK) - .map_err(|e| e.to_string()), - Err(error) => Err(error.to_string()), - }; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if device - .line() - .hooks - .probe_unanswered - .load(std::sync::atomic::Ordering::Acquire) - { - answered = Ok(false); - std::thread::sleep(LOOK); - } - match answered { - Ok(true) => break Verdict::Runs, - // A probe that could not be sent, or whose wait failed, answers nothing: no verdict. - Err(_) => break Verdict::Runs, - Ok(false) if began.elapsed() >= PROBE => break Verdict::Stopped, - Ok(false) => {} - } - }; - let probe = match &answered { - Ok(true) => format!("completed in {:?}", began.elapsed()), - Ok(false) if verdict == Verdict::Stopped => format!("did not complete in {PROBE:?}"), - Ok(false) => "was still pending".to_owned(), - Err(error) => format!("answered nothing ({error})"), - }; - let fence_read = match fence_read { - Some(result) => format!("{result:?}"), - None => "none".to_owned(), - }; - let timeline_read = match timeline_read { - Ok(read) => format!("{read} of {value}"), - Err(error) => format!("{error:?}"), - }; - let said = match verdict { - Verdict::Runs => "the GPU runs: nothing fails".to_owned(), - Verdict::Failed(error) => format!("a read answered {error:?}: the device is lost"), - Verdict::Stopped => "the generation stopped: its work fails, and it is parked".to_owned(), - }; - device.inform( - "metal2vulkan-stall-probe", - format!( - "metal2vulkan: no work of the device advanced for {stalled:?} with some pending on \ - VkQueue {queue}; a probe on the staging queue {probe}; the stuck batch's fence \ - read {fence_read}, its timeline {timeline_read}: {said}" - ), - ); - verdict -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs deleted file mode 100644 index 4d21c3678..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! A commit that takes the waiting fetched render targets' storage forms -//! (`texture/storage_form.rs`): where the committing command buffer allows it, a last part of it -//! copies each target's image into its storage form, and the switch rides on the command buffer -//! ([`Riding`]) until its scheduler settles it at the submission of its last batch. - -use super::{lock, CommandBuffer, CommandBufferShared, State}; -use crate::encoder::{EncoderCore, Recorded}; -use crate::texture::storage_form::Riding; - -impl State { - /// Whether its commit may take a switch (`texture/storage_form.rs`), as far as its state - /// tells: it may be committed and ended an encoder; every encoder of it may run; it waits for - /// no event or binary semaphore and leaves no segment and no sparse update to a host step, so - /// the scheduler submits all of it once its submission checks (if it has any) ran; and it - /// bound no heap set. - fn takes_storage_forms(&self) -> bool { - self.refusal().is_none() - && !self.ended.is_empty() - && self.fails_from.is_none() - && self.faulted.is_empty() - && !self.heaps.bound() - && self.recorded.iter().all(|part| { - part.segments.is_empty() && part.sparse.iter().all(|update| !update.needs_step()) - }) - && self - .batches - .all() - .iter() - .all(|batch| batch.waits.is_empty() && batch.binary_waits.is_empty()) - } -} - -impl CommandBuffer { - /// Take the switch of the waiting textures' storage forms at this commit (with an `injected` - /// failure or not), where the command buffer and the device allow it now: their copies - /// appended to the command buffer as its last part, and the switch riding on it. Whether it - /// did; nothing appended (one atomic read) where no texture waits. - pub(super) fn take_storage_forms(&self, injected: bool) -> bool { - let device = &self.0.device; - if injected || !device.storage_forms_wanted() { - return false; - } - // It holds a slot of its queue too, so it counts among the device's uncommitted command - // buffers. - let parts = { - let state = self.state(); - if !state.takes_storage_forms() || lock(&self.0.slot).is_none() { - return false; - } - state.recorded.len() - }; - let Some(switch) = device.storage_form_switch() else { - return false; - }; - let Ok(mut core) = EncoderCore::segment(self, true) else { - device.put_back_switch(switch); - return false; - }; - let prepared = switch.prepare(device, &mut core); - if prepared.is_empty() { - drop(core); - device.give_up_switch(switch, prepared); - return false; - } - let Ok(recorded) = core.end_segment() else { - device.give_up_switch(switch, prepared); - return false; - }; - let mut state = self.state(); - // Nothing else ended meanwhile (a program that encodes on another thread as it commits). - let encoder = state.ended.len().checked_sub(1); - let (Some(encoder), true) = ( - encoder, - state.recorded.len() == parts && state.takes_storage_forms(), - ) else { - drop(state); - // The images made go unused, never submitted. - drop(recorded); - device.give_up_switch(switch, prepared); - return false; - }; - state.end_encoder( - self, - Recorded { - encoder, - raws: recorded.raws, - barriered: None, - segments: Vec::new(), - summary: recorded.summary, - sparse: Vec::new(), - twin_writes: Vec::new(), - overwrites: Vec::new(), - trail: (device.shared().encoder_trail) - .then(|| crate::encoder_trail::Named::new("the runtime's storage form switch")), - }, - ); - state.retained.extend(recorded.retained.into_entry()); - // What its commands took is the encoder's, as the switch's commands are. - if let Some(record) = state.ended.get_mut(encoder) { - record.taken.join(recorded.taken); - } - state.storage_form = Some(Riding::new(device, switch, prepared)); - true - } - - /// The commit refused the command buffer, on which a switch rode: given up, nothing swaps. - pub(super) fn give_up_storage_forms(&self) { - let riding = self.state().storage_form.take(); - // With the lock free: its drop gives the switch up under the device's switch lock. - drop(riding); - } -} - -impl CommandBufferShared { - /// Its last batch was submitted, or it failed (the scheduler, under its lock): settle the - /// switch riding on it (`texture/storage_form.rs`), the verdict whether every encoder of it - /// ran (no check failed a submission of it, and its submission did not fail). Whether one - /// rode on it. - pub(crate) fn settle_storage_forms(&self) -> bool { - let _for = self.notices_for(); - let state = lock(&self.state); - let Some(riding) = &state.storage_form else { - return false; - }; - riding.settle(state.failure.is_none()); - true - } -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs deleted file mode 100644 index 9c82a9fdd..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ /dev/null @@ -1,2563 +0,0 @@ -//! Submitting one batch of a command buffer, on the scheduler's thread, in its order, under its -//! lock. -//! -//! One `vkQueueSubmit` of two `VkSubmitInfo`s on the queue's `VkQueue`: -//! 1. The work: the batch's waits, Vulkan waits for its events' signal indices, for the caller's -//! binary semaphores and the tracker's waits for other `VkQueue`s' timelines, then its encoders' -//! `VkCommandBuffer`s (an encoder's segments among its own), each encoder after the barrier the -//! tracker planned for it. What completed work wrote is made visible by a wait or a barrier, -//! see below. -//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]), or, -//! where batches are ordered by their ends (`batch_order.rs`), to the host and to every later -//! command of the `VkQueue` ([`Barrier::to_all`]; so a later batch there plans no barrier from -//! this one's accesses, `tracker.rs`), then the signals: the events' kept signal indices, the -//! caller's binary semaphores and the queue's timeline value. When an event's previous kept -//! signal is pending on another `VkQueue`, this part waits for it, so the event's semaphore is -//! signaled in index order without holding back the work. -//! -//! **Grouped** ([`Submitting::Grouped`], `group.rs`). Where the scheduler groups batches (under -//! `CompletionPolicy::Grouped`, on a driver that merges submissions), a batch that signals nothing -//! but its queue's timeline and its events, past its first work, without a fence or a wrapped -//! image to move, and waits for no event index a batch held signals, is not submitted: its two -//! `VkSubmitInfo`s are held, its signals left to the group's end, and it is tracked as submitted -//! (its events keep their signals' indices). One that may join but took first work or names a -//! wrapped image goes with the held group, in its call, last; one that may not, or finds the -//! group of another `VkQueue`, changes nothing ([`Submitting::AfterGroup`]): the scheduler -//! submits the group and offers the batch again. -//! -//! **What completed work wrote.** The tracker forgets a batch once the host saw its queue's -//! timeline pass it, and the device's own submissions outside the batches (`device/submit.rs`, -//! `device/staging.rs`) it never tracks: their writes are ordered before a later batch by their -//! completion alone. The work waits for each such timeline, each `VkQueue`'s and the device's two -//! own, at the value the host saw it reach, where a batch of its `VkQueue` did not wait for that -//! value already: a wait that is satisfied as it is submitted. The signal made the writes -//! available ("The first access scope includes all memory access performed by the device", -//! semaphore signaling), and the wait makes them visible: the submission's "second -//! synchronization scope of each semaphore wait operation defined by this command includes every -//! command in the same batch that the wait operation is defined in, and all commands that occur -//! later in submission order", and the wait's "second access scope includes all memory access -//! performed by the device" (`vkQueueSubmit`, semaphore waiting). So one wait per value serves -//! every later batch of its `VkQueue`. A batch with nothing planned before its first encoder then -//! needs no command buffer before it, a timed command buffer's first batch included where its -//! first encoder wrote the start (**GPU times**, below): on an RTX 5080 and a Radeon 780M, nearly -//! every batch of a frame of draws, and of command buffers committed from several threads. A wait costs CPU in `vkQueueSubmit`: about -//! 1.1 us on ms01's Iris Xe (ANV), 1.6 us on a Radeon 780M (RADV) and 0.5 us on an RTX 5080, -//! where a command buffer of barriers cost about 12 us of the Iris Xe's GPU. Counted: -//! `WorkCounts::completed_waits`, `WorkCounts::bare_starts` (the batches with work that began -//! with no command buffer of barriers). -//! -//! A driver measured to stall its submissions on semaphore operations -//! (`DriverFact::SemaphoreOperationsStallSubmits`: NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU -//! and the RTX 3090, about 2 ms of CPU in one `vkQueueSubmit` in about every thousand waits and -//! signals) takes no such wait: each batch with work starts instead with a command buffer of -//! barriers whose first is [`Barrier::after_completed`], which makes what completed batches -//! wrote visible to every later command. Where every batch waited, about twice as many of its -//! submissions took that long as where batches only signal. -//! -//! **The staging queue's copies.** On every driver, a batch waits on the GPU for the staging -//! queue's last submission while the host has not seen it complete (`Device::staging_wait`), -//! unless a batch of its `VkQueue` already waited for that submission: the wait's second -//! synchronization scope holds every command later in submission order there, so one wait per -//! `VkQueue` makes the copies visible to every later batch of it, as one wait per value does for -//! completed work above. A submission that carries the copies a burst of host calls queued is -//! made just before the batch and waited for on the GPU, not the host -//! (`texture/staging_copy.rs`). The batches after the one that waits may then join a group -//! (**Grouped**, above), which a batch with a wait for work the host has not seen complete only -//! leads. Counted: `WorkCounts::staging_gpu_waits`. -//! -//! Each barrier goes in a command buffer of barriers alone, which the scheduler records once per -//! list of barriers and submits again once the batch that last carried it completed -//! ([`kept_barriers`](super::kept_barriers)); one that also writes a command buffer's timestamps -//! once per list and slot, submitted again only by a later holding of the slot; one that moves -//! the caller's images is recorded by its batch. -//! -//! **The end in the work's last command buffer.** An encoder's last `VkCommandBuffer` stays -//! recording after the encoder ended, as its command buffer's tail, until an encoder after it -//! joins its batch, its batch ends at encode time, or the command buffer commits -//! (`CommandBufferShared::close_tail`). Where its batch ended there, the end goes into it before -//! it ends: the barrier to the host, then, in the last batch of a timed command buffer, the end -//! timestamp, as the end's own command buffer holds them. Only where the batch leaves its -//! submission no segment or sparse update (recorded at the submission, among or before the -//! work's command buffers), and names no texture over the caller's image that moves between -//! layouts (its move back is planned at the submission, before the end). The batch's submission -//! then has no end of its own, unless an event's kept signal waits for another `VkQueue`'s -//! (above): its end then holds the barrier to the host alone, between that wait and the signals, -//! the work's end timestamp written. Else the signals join the work's `VkSubmitInfo`: "The first -//! synchronization scope of each semaphore signal operation defined by this command includes -//! every command in the same batch that the signal operation is defined in, and all commands that -//! occur earlier in submission order" (`vkQueueSubmit`). Where that command buffer does not go -//! to the queue as recorded (its encoder runs nothing, or a rebind encoded it again), the end is -//! a command buffer of its own, as every other batch's. Each command buffer a submission holds -//! costs GPU time of its own: a probe of one 1x1 copy took 42.6 us of GPU time as three primary -//! command buffers (a start, the copy, an end) and 25.6 us as one on ms01's Iris Xe (ANV), 19.6 -//! and 13.6 cold on a Radeon 780M (RADV), 15.4 to 17.4 and 7.9 to 9.0 on an RTX 5080. Counted: -//! `WorkCounts::finales_folded`, `WorkCounts::finales_apart`. -//! -//! A batch with no work is one `VkSubmitInfo` of every wait, the end and the signals: a wait -//! orders only its own `VkSubmitInfo`'s commands, and a signal follows commands, not waits -//! (`vkQueueSubmit`'s synchronization scopes), so a signal after a wait needs both in one, with -//! the end's barrier, a command, between. Where it has no wait, no image to move back and no -//! timestamp to write either (an empty command buffer's batch that carries the device's first -//! work, one of signals alone), its end -//! records nothing and the `VkSubmitInfo` holds no `VkCommandBuffer`: none of its commands wrote -//! anything, every batch before it made its own writes visible to the host before its signals, -//! and its signals follow every command submitted before them. ANV on i915 lists every -//! `VkDeviceMemory` of the device, and its own buffer objects, in each kernel submission of -//! commands, and two objects in one of none (Mesa 26.2.4, `i915/anv_batch_chain.c`). -//! -//! **The caller's images** ([`Device::new_texture_with_vk_image`]). A batch whose encoders use a -//! wrapped image that is not at rest in `GENERAL` moves it there before its first encoder and back -//! to its home layout in the end, before the signals. The moves are planned with the encoders, as -//! writes of the whole image outside them -//! ([`WrappedImage::transition_use`](crate::texture::wrapped::WrappedImage::transition_use)), -//! so the tracker orders them against every other use of the image on any queue, and each is -//! recorded as an image memory barrier from all commands before to all commands after. -//! -//! **Held depths** (`texture/held_depth.rs`). Before each encoder that names a held multisampled -//! depth, the encoder's command buffer of barriers moves it into the layout the encoder needs -//! where the batches submitted before, or the batch's earlier encoders, left it in another. The -//! moves are planned with the encoders as the caller's images' are, each a write of the whole -//! image outside the encoder joined to its summary, and recorded the same way, after the barrier -//! the tracker planned for the encoder. The layouts the batch leaves count from its submission on. -//! -//! **Writes through the residency** (`State::resident_writes`). Residency is the command -//! buffer's (`residency.rs`), so a function of any of its encoders may write a resource any of -//! them made resident for writing, in an encoder whose commands name it nowhere. Each batch with a -//! part plans those writes with its first part, as writes of each whole resource in every stage -//! that widen none of the stages the part's fences cover: the tracker then holds the batch as their -//! last writer, so what reads them later on any queue, and a later host step's gate -//! (`scheduler/mod.rs`'s `gate_heads`), orders after it. A resource made resident for reading -//! alone is planned as the commands that name it use it. -//! -//! **New resources' first work** (`texture/first_move.rs`). Every batch first does the first GPU -//! work of the resources made since the device's last submission: each new image's move to -//! `GENERAL`, and the zeros a new texture, stand-in or buffer reads. It runs before every command -//! of the batch, whether a use names the resource or not (a command may reach a texture through its -//! resource ID, a buffer through its address), and the batch holds what it worked on until it -//! completes. On a device of several `VkQueue`s every batch on another one waits for it until it -//! completed. It is recorded first in the command buffer that leads the batch's work's -//! `VkSubmitInfo` (in a batch with no work, its end's) -- its own, or, where the batch also has -//! host calls' staged copies, the one that holds the copies after it -- so it waits for what the -//! work waits for: Vulkan's -//! submission order puts it before every command of the batch ("the order in which command -//! buffers are specified in the pCommandBuffers member of VkSubmitInfo ... determines their -//! submission order", the Vulkan specification, Submission Order), and its last barrier, -//! recorded outside a render pass, orders it before them all: "the first synchronization scope -//! includes all commands that occur earlier in submission order ... the second synchronization -//! scope includes all commands that occur later in submission order" (`vkCmdPipelineBarrier`). -//! MoltenVK 1.4.1 runs each `VkSubmitInfo` as a Metal command buffer of its own -//! (`MVKQueue::submit`), each about 65 us of a thread of Metal's on an M3 Max, so the first work -//! adds none (`WorkCounts::submit_infos`). It takes no barrier that names a host read of an image -//! (`image_barrier.rs`), the one MoltenVK took for a read back over a heap texture's own storage -//! at its Metal command buffer's completion. A failed `vkQueueSubmit` made none of it, or lost -//! the device. -//! -//! [`Device::new_texture_with_vk_image`]: crate::Device::new_texture_with_vk_image -//! -//! The submission of the batch that ends a command buffer also signals a fence of the device's -//! where its driver reads the command buffer's objects after its value -//! ([`fences`](super::fences)), at which the command buffer then finishes. -//! -//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at the -//! top of the pipe, before every barrier and encoder of its first batch. Where that batch has first -//! work (**New resources' first work**, above: zeros, moves, `Managed` copies in), the work's own -//! command buffer writes it first, after an execution barrier from every command before ("the -//! first synchronization scope includes all commands that occur earlier in submission order ... -//! the second synchronization scope includes all commands that occur later in submission order", -//! `vkCmdPipelineBarrier`), so the start follows every earlier command of the queue and precedes -//! the work, whose GPU time is the command buffer's: on an RX 7900 XTX, a command buffer's copies -//! in of the ranges `did_modify_range` named ran 4.5 to 36.5 ms before a start written after them. -//! (Whether Metal's span holds a `Managed` copy in on a Mac with a discrete GPU is not measured.) -//! Elsewhere it is written by its first encoder's -//! first command buffer, which wrote it into its slot's third query as it opened, where the batch -//! plans nothing before that encoder (no barrier, no image moved, and no -//! [`Barrier::after_completed`] where the driver stalls on semaphore operations) and the command -//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the batch's -//! first command buffer, a command buffer of barriers, which resets the slot's first two queries -//! first. Where the batch plans a barrier before its first encoder for earlier work (the encoder's -//! own, or the one before the images it moves), the start is written after that barrier instead, at -//! the bottom of the pipe: once every command submitted before it on the queue completed. Vulkan -//! (`vkCmdWriteTimestamp`): its "first synchronization scope includes all commands that occur -//! earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT` "is equivalent to -//! `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when specified in the first -//! synchronization scope". So a command buffer whose first encoder depends on work still running -//! starts after that work ended, as Metal's does: on an M3 Max under macOS 27.0.1, a fill committed -//! behind a running fill of the same bytes started 0.5 to 0.9 us after the first's `GPUEndTime` (10 -//! of 10), and one of other bytes while the first ran (probe `gpustart`). Where batches are ordered -//! by their ends (`batch_order.rs`), the end barrier of the batch before ([`Barrier::to_all`], all -//! commands to all commands) holds every start, at the top of the pipe, until the batches before it -//! ended, as such a driver starts no batch before them; one written at the bottom of the pipe there -//! read late on RADV. The end of its last batch writes the end -//! timestamp at the bottom of the pipe, after its barriers. The scheduler's host times as it begins -//! the first batch and ends the last submission are the kernel times. -//! -//! The tracker keeps the plan, and the events their kept signals, only once the submission is -//! made; a batch that is not submitted changes neither. -//! -//! The submission is a section of the exit guard ([`exit_guard`]). What it did is published -//! ([`CommandBufferShared::publish`]: the transition to `Scheduled`, which runs the scheduled -//! handlers and ends waits for scheduling, and the queue waiter's watch) only after that -//! section ended. A section ends by registering the exit hook again when its calls may have -//! registered destructors, so an exit the program makes once it learned of the submission runs -//! the hook before them. -//! -//! The submission of a command buffer's last batch, or its hold in a group (`group.rs`), leaves its -//! submission handlers to the submitting thread: a committing thread runs them once the -//! scheduler's lock is free, and the scheduler's thread hands them to the device's handler -//! threads as its pass goes on (`scheduler/mod.rs`); its transition to `Scheduled` waits for -//! them. -//! -//! **No GPU work, no submission** ([`State::needs_no_gpu`]). A command buffer whose encoders -//! recorded nothing and whose one batch waits for and signals no event and no binary semaphore (so -//! presents no drawable) is taken, once it leads its logical queue's line, no group is held and -//! no first work of the device's waits but fills of the program's memory (`texture/first_move.rs`: -//! a new `Private` buffer's zeros, which only the GPU reads, and which a later batch or internal -//! submission takes before its commands), with no `vkQueueSubmit`: its batch is watched at its -//! `VkQueue`'s last submitted value, so it -//! completes in its queue's order, once the queue's work before it completed, or at once where the -//! queue has none in flight (`Completion::watch_unsubmitted`). Everything else its last batch's -//! taking does is done as for a submitted one: its kernel times, its scheduling (by a hang's -//! thread where one makes it), its submission handlers, its holds. Metal completes such a command -//! buffer without its GPU too: on the M3 Max (macOS 27.0.1) one committed and waited for on an -//! idle queue returned in 15 us at the median of 1000, its `GPUStartTime` equal to its -//! `GPUEndTime` (within 0.3 us) 1 to 2 us after its `kernelEndTime`; one committed behind a fill -//! completed after the fill, its GPU times 65 to 135 us after the fill's `GPUEndTime`. Counted: -//! `WorkCounts::command_buffers_unsubmitted`. - -use super::completion::{Submitted, Waited}; -use super::follow::{Follow, Release}; -use super::gate::Hold; -use super::group::{After, Alone, GroupEnd, InfoParts}; -use super::hang; -use super::kept_barriers::{KeptBarriers, SlotStamps}; -use super::{lock, recording_error, submission_error, CommandBufferShared, State}; -use crate::deferred::Deferred; -use crate::encoder::{count_shadow_copies, OverwriteBy, Recorded, RecordedSegment}; -use crate::encoder_fold::GroupPlaces; -use crate::error::CommandBufferError; -use crate::error::{internal, Error}; -use crate::event::EventShared; -use crate::event_timeline::Signal; -use crate::exit_guard::{self, Call}; -use crate::gpu_time; -use crate::managed_copy::AtCompletion; -use crate::managed_sync::SyncCopy; -use crate::release; -use crate::resource::{ObjectId, ResourceKey}; -use crate::scheduler; -use crate::shadow::ShadowCopies; -use crate::shadow_standing::{LetGo, Missed, Unskipped}; -use crate::slow_submissions::{self, Phase, Watch}; -use crate::sparse::bind::{bind_batch, BindFailure, Bound}; -use crate::sparse::encoder::SparseUpdate; -use crate::submit_failure::{Carried, TypeFlags}; -use crate::texture::decoded_twin::{SecondDecode, TwinWrite}; -use crate::texture::faces::FaceFix; -use crate::texture::first_move::{last_of_each, Earlier, FillTake, Later}; -use crate::texture::wrapped::Transition; -use crate::texture::Texture; -use crate::tracker::{Access, Barrier, Point, Summary}; -use crate::used_resources::{EncoderKind, EncoderRecord}; -use crate::work_counts::Begun; -use ash::vk; -use std::collections::BTreeSet; -use std::sync::Arc; -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -use {crate::tracker::Footprint, std::sync::Mutex}; - -/// The command buffers a device test watches (`tests::kept_heap_uses`), by the address of their -/// shared state, and the footprints of the batches the scheduler planned of each, in order. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -static PLANNED: Mutex>)>> = Mutex::new(Vec::new()); - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -impl super::CommandBuffer { - /// Note the footprint of each batch of it the scheduler plans from now on: a device test's - /// (`tests::kept_heap_uses`), before its commit. - pub(crate) fn watch_planned(&self) { - lock(&PLANNED).push((Arc::as_ptr(&self.0) as usize, Vec::new())); - } - - /// The footprints of its batches the scheduler planned since [`watch_planned`]: their tracked - /// uses, as the tracker planned them. Watched no more. - /// - /// [`watch_planned`]: Self::watch_planned - pub(crate) fn planned(&self) -> Vec> { - let mut planned = lock(&PLANNED); - let at = Arc::as_ptr(&self.0) as usize; - match planned.iter().position(|(of, _)| *of == at) { - Some(index) => planned.swap_remove(index).1, - None => Vec::new(), - } - } -} - -/// The lists a batch's submission fills and empties, kept in the scheduler's state from batch to -/// batch with their room, so that a submission allocates none of them once they have room for -/// what it puts in them ([`CommandBufferShared::submit_batch`]). -#[derive(Default)] -pub(crate) struct BatchLists { - /// What each timeline whose writes the tracker forgets completed through as the host saw - /// it, each `VkQueue`'s, then the device's own: none where it is at 0. - reached: Vec>, - /// The work's waits. - waits: BatchWaits, - /// Of `reached`, the timelines (by place) and values the work waits for. - waited: Vec<(usize, u64)>, -} - -/// A `VkSubmitInfo`'s waits: the semaphores, their values and their stages. -#[derive(Default)] -struct BatchWaits { - semaphores: Vec, - values: Vec, - stages: Vec, -} - -/// A batch submitted, which nothing has seen yet: for the scheduler to -/// [`publish`](CommandBufferShared::publish). -#[must_use = "a batch not published never finishes its command buffer"] -pub(crate) struct Submission { - /// Its `VkQueue`. - queue: usize, - batch: Submitted, - /// It ends a command buffer with submission handlers, or with a switch of storage forms riding - /// on it, which the submitting thread still runs or ends once the scheduler's lock is free - /// ([`Submission::runs_handlers`]); false once a hold in a group gave them to the thread - /// ([`schedule_held`](Submission::schedule_held)). - handlers: bool, - /// It ends a command buffer with a switch of storage forms riding on it, which settles by its - /// submission's outcome ([`Submission::rides_forms`]). - forms: bool, - /// It makes its command buffer `Scheduled`: it ends it, and no hang's thread makes or made it - /// (`hang::schedules`). - schedules: bool, - /// Its command buffer became `Scheduled` as it was held in a group - /// ([`schedule_held`](Submission::schedule_held)). - scheduled: bool, - /// It was taken with no `vkQueueSubmit`: its command buffer needs no GPU work - /// ([`State::needs_no_gpu`]). - unsubmitted: bool, -} - -/// What [`CommandBufferShared::submit_batch`] did with a batch. -#[must_use = "a batch submitted or held must be published, one held back must be put back"] -pub(crate) enum Submitting { - /// Submitted, alone or after the group held before it: for the scheduler to publish. - Submitted(Submission), - /// Held in the scheduler's group (`group.rs`), its submission's changes made: its command - /// buffer's transition to `Scheduled` as it is held, where it ends it - /// ([`Submission::schedule_held`]), the rest published once the group is submitted. - Grouped, - /// Nothing submitted or changed: the submission of its event group waits for encoders of it a - /// rebind encodes again (`reencode.rs`). - Later, - /// Nothing submitted or changed: the group held goes first, sent by what this says. - AfterGroup(GroupEnd), -} - -impl Submission { - /// The value its queue's timeline reaches once it completed. - pub(super) fn value(&self) -> u64 { - self.batch.value - } - - /// Whether it makes its command buffer `Scheduled` ([`Submission::schedules`]). - pub(super) fn schedules(&self) -> bool { - self.schedules - } - - /// Its command buffer. - pub(super) fn buffer(&self) -> &Hold { - &self.batch.buffer - } - - /// Each event's semaphore it signals, with the signal's index. - pub(super) fn event_signals(&self) -> impl Iterator + '_ { - (self.batch.signals.iter()).map(|(event, index)| (event.semaphore(), *index)) - } - - /// Whether the submitting thread runs its command buffer's submission handlers - /// ([`CommandBufferShared::run_submission_handlers`]) once it holds no lock, after it ended - /// the switch of storage forms riding on it: its transition to `Scheduled` waits for them. - pub(crate) fn runs_handlers(&self) -> bool { - self.handlers - } - - /// Whether it ends a command buffer on which a switch of storage forms rides - /// (`texture/storage_form.rs`): the switch settles by its submission's outcome, so it is - /// `Scheduled` and its submission handlers run only once the group holding it was submitted. - pub(super) fn rides_forms(&self) -> bool { - self.forms - } - - /// It was held in a group (`group.rs`), on the scheduler's thread under its lock, after the - /// section that held it ended: where it ends its command buffer and no switch of storage - /// forms rides on it, the command buffer's kernel end and its transition to `Scheduled` now, - /// which [`publish`](CommandBufferShared::publish) then leaves out, and its submission - /// handlers go to the scheduler's thread to run once its lock is free, before that - /// transition, as a submitted batch's do: whether they do (none is left for the group's - /// submission). Its tracker plan, its queue's value and its events' signal indices were - /// taken as it was held, so nothing committed later on its queue goes before it; only its - /// kernel submission and its queue waiter's watch wait for the group. - pub(super) fn schedule_held(&mut self) -> bool { - if !self.schedules || self.forms || self.scheduled { - return false; - } - self.scheduled = true; - self.batch.buffer.kernel.end_at(gpu_time::host_nanos()); - self.batch.buffer.schedule(); - let handlers = self.handlers; - self.handlers = false; - handlers - } - - /// Whether its command buffer became `Scheduled` as it was held. - pub(super) fn scheduled(&self) -> bool { - self.scheduled - } -} - -impl State { - /// Whether the command buffer needs no GPU work (the module docs): none of its encoders - /// recorded anything (none ended, and no storage form's switch rides on it with a part of its - /// own), and its one batch waits for and signals no event and no binary semaphore. Read from - /// what it recorded, never from a name. - pub(super) fn needs_no_gpu(&self) -> bool { - let [batch] = self.batches.all() else { - return false; - }; - self.recorded.is_empty() - && self.storage_form.is_none() - && batch.waits.is_empty() - && batch.signals.is_empty() - && batch.binary_waits.is_empty() - && batch.binary_signals.is_empty() - } -} - -impl CommandBufferShared { - /// Submit batch `index` of the command buffer (`last` when it ends it) after the Vulkan waits - /// `event_waits` for its events, against the scheduler's tracker and timeline values. The - /// batch is for the caller to [`publish`](Self::publish) once its section ended - /// ([`Submitting::Submitted`]), or waits in the scheduler's group for one kernel submission - /// with the batches after it, its submission's changes made ([`Submitting::Grouped`], - /// `group.rs`). Nothing submitted or changed while the submission of its event group waits for - /// encoders of it a rebind encodes again (`reencode.rs`, [`Submitting::Later`]), or while the - /// group held must go first ([`Submitting::AfterGroup`]): the caller holds the batch back at its - /// place. Where the group went in this batch's submission, its outcome is the group's - /// (`Group::take_outcome`). With `alone`, it never waits in the group: a thread other than - /// the scheduler's submits it (`scheduler::submit_plain_ready`). - pub(crate) fn submit_batch( - self: &Arc, - index: usize, - last: bool, - event_waits: &[(vk::Semaphore, u64)], - alone: bool, - scheduler: &mut scheduler::State, - ) -> Result { - let _for = self.notices_for(); - let device = &self.device; - if device.is_lost() { - return Err(CommandBufferError::DeviceLost); - } - // Its start: a call that carries it alone times its whole submission, the cost a - // committing thread weighs (`device/submit_calls.rs`). - let begun = gpu_time::host_nanos(); - // Where the device notes queue times, the submission timed phase by phase on this thread - // (`slow_submissions.rs`). - let mut watch = Watch::start(device.shared().timing.queue_times()); - // A batch that waits for an event value its commit's copy in came before copies the - // copied host buffers in again, its wait met (`copies_again.rs`). - self.copy_in_again(index)?; - let shared = device.shared(); - // Where the spares' frees left their pools holding command buffers untrimmed past their - // bound, a trim round, before any batch takes a kept barrier command buffer - // (`scheduler::State::trim_round`). Not while the group holds batches, whose kept ones - // are taken and not yet submitted. - if shared.spares.trim_due() && !scheduler.group.holds() { - scheduler.trim_round(shared); - } - let raw = shared.vk(); - let queue = self.queue.vk_queue(); - let mut state = lock(&self.state); - // What its encoders were, as the encoder trail names them (`encoder_trail.rs`). - let trail = match shared.encoder_trail { - true => batch_trail(&state.recorded[state.batch_range(index)]), - false => None, - }; - // Whether the batch may wait in the scheduler's group for one kernel submission with the - // batches after it (`group.rs`), as far as is known before anything changes; first work - // it takes still sends it now. One that may not, or of another `VkQueue`, waits, - // nothing changed, for the group to go first. Its event signals ride to the group's end; - // a wait for an event a batch held signals, which only that end meets, goes after it. - let met = (event_waits.iter()).any(|&wait| scheduler.group.meets(wait)); - // Whether it may wait in a group, or else go last in the one held on its `VkQueue`, which - // then goes at once: under `CompletionPolicy::Exact`, a command buffer not marked to join - // the next behind marked ones (`CommandBuffer::set_completion_joins_next`), seen complete - // at its own end. - let holds = self.groups(); - let closes = !holds - && scheduler.group.holds() - && scheduler.group.queue() == queue - && self.closes_groups(); - // A batch whose work a segment cut into pieces goes in a submission of its own, whose - // pieces are `VkSubmitInfo`s of their own (below). - let pieced = (state.recorded[state.batch_range(index)].iter()) - .flat_map(|recorded| &recorded.segments) - .filter_map(|segment| segment.recorded.as_ref()) - .any(|done| !done.piece_ends.is_empty()); - // What refuses it a place in any group, of what it is (`group::Alone`), in the order its - // count takes: each read only where none before it refuses. - let refused = { - let sync = &state.batches.all()[index]; - let sparse = || { - (state.recorded[state.batch_range(index)].iter()) - .any(|recorded| !recorded.sparse.is_empty()) - }; - if !holds && !closes { - Some(Alone::Unshared) - } else if !sync.binary_waits.is_empty() { - Some(Alone::BinaryWait) - } else if !sync.binary_signals.is_empty() { - Some(Alone::BinarySignal) - } else if sparse() { - Some(Alone::Sparse) - } else if pieced { - Some(Alone::Pieced) - } else if last && super::fences::ends_at_fence(device, queue) { - Some(Alone::Fence) - } else { - None - } - }; - let may_join = !alone && !met && refused.is_none(); - // Its queue's expected GPU run: a batch of unknown length, or one that would take the - // group's past `GROUP_RUN`, joins none (`group.rs`). - let run = self.queue.group_run().nanos(); - let fits = scheduler.group.fits(run); - let joins = may_join && fits; - // Where its `VkQueue`'s batches group at all, why it goes alone if it goes with no group - // held: what refuses it, or its run, else first work or a wrapped image (found below), - // else a committing thread's submission (`WorkCounts::batches_alone_unshared` and kin). - let counts_alone = super::group::groups(device, queue) || holds; - let alone_for = refused.or(match run { - None => Some(Alone::RunUnknown), - Some(_) if !fits => Some(Alone::RunLong), - Some(_) => None, - }); - if !scheduler.group.admits(queue, joins) { - let long = may_join && !fits && scheduler.group.queue() == queue; - let end = match (met, long) { - (true, _) => GroupEnd::Wait, - (false, true) => GroupEnd::Long, - (false, false) => GroupEnd::Apart, - }; - return Ok(Submitting::AfterGroup(end)); - } - // A host step that failed fails the command buffer here; else the batch's segments go in - // their places. - if let Some(error) = state.step_failure.take() { - return Err(error); - } - // Its first submission resolves what its commands reach as Metal's does, before any of - // its batches goes to the `VkQueue` (`first_submission.rs`). - if !state.submitted { - let first = state - .first_submission(device, self) - .map_err(|error| recording_error(device, error))?; - if !first { - return Ok(Submitting::Later); - } - } - // A later event group's, as its first batch is submitted, unless a rebind encodes - // encoders of it again. - if !state.later_group(device, self, index) { - return Ok(Submitting::Later); - } - // Each of Metal's submissions it found rebound, or holding a detached buffer, fails as - // its own batch is submitted, after the batch's checks: one a check failed keeps the - // check's code. - let rebound = state.failing_at(device, index); - // One that needs no GPU work goes with no submission, in its queue's order (the module - // docs); behind a group held, it goes with the group as any batch that joins does, and - // where the device's first work waits, it carries it as any batch does, but the fills of - // the program's memory, which it leaves waiting: a later batch takes them before any of - // its commands (any batch on a device without a fill queue, one whose commands may reach - // them on a device with one: `texture/first_move.rs`, `FillTake`), and an internal - // submission takes every one. - let programs = |key: ResourceKey| crate::used_resources::owner_of(shared, key).is_some(); - if !rebound - && !scheduler.group.holds() - && state.needs_no_gpu() - && (shared.textures.first_moves).none_waiting_but(programs) - { - let taken = self.take_unsubmitted(&mut state, index, last, scheduler); - return Ok(Submitting::Submitted(taken)); - } - let range = state.batch_range(index); - // A batch that begins with resource state encoders binds their updates first, after its - // waits, which its work then waits for through the bind. - let updates: Vec = state.recorded[range.clone()] - .iter() - .flat_map(|recorded| recorded.sparse.iter().cloned()) - .collect(); - // Where the updates leave work on emulated textures or tile maps and bind nothing, the - // values the work waits for in the bind's place: every queue's last. - let mut after_all = None; - let bound = if updates.is_empty() { - None - } else { - let binary = &state.batches.all()[index].binary_waits; - let waits: Vec<(vk::Semaphore, u64)> = event_waits - .iter() - .copied() - .chain(binary.iter().map(|&semaphore| (semaphore, 0))) - .collect(); - let Bound { - unbound, - signalled, - mappings, - } = bind_batch(device, queue, &updates, &waits, &scheduler.values) - .map_err(|failure| bind_error(device, failure))?; - state.retained.push(Box::new(unbound)); - if !mappings.is_empty() { - // The work's first command buffer, in the first resource state encoder's place, - // which the tracker sees write what it writes. - let uses = mappings - .uses() - .map_err(|error| recording_error(device, error))?; - let raw = self.record_raw(&mut state, |state, buffer| { - // SAFETY: the command buffer is recording; the textures are live (the - // command buffer holds them), in `GENERAL`; the work waits for the bind, or - // for every queue's last value. - let held = unsafe { mappings.record(device, &mut state.uploads, buffer) }?; - if !held.is_empty() { - state.retained.push(Box::new(held)); - } - Ok(()) - })?; - let first = &mut state.recorded[range.start]; - first.raws.push(raw); - first.summary.join(Summary::outside_encoders(uses)); - if !signalled { - after_all = Some(scheduler.values.clone()); - } - } - signalled.then(|| { - scheduler.values[queue] += 1; - scheduler.values[queue] - }) - }; - // The scrubs of emulated textures' writes, as mapped now; then every segment in its - // place. - self.record_scrubs(&mut state, range.clone())?; - state - .place(range.clone()) - .map_err(|error| recording_error(device, error))?; - // No work of an encoder that recorded nothing for a command (a buffer it named was - // detached), nor of one whose submission failed rebound or detached, goes to the queue. - state - .runs_nothing_unrunnable(range.clone()) - .map_err(|error| recording_error(device, error))?; - // The copies out of buffers with a host copy its parts hold, settled by the writes noted - // so far; then its own writes noted. - let at = Point { - queue, - value: scheduler.values[queue] + 1, - }; - self.settle_syncs_out(&mut state, range.clone(), at)?; - // The decodes into ASTC carriers' second decoded twins: those queued, before its work; - // its blits' writes', after each part. - self.record_second_decodes(&mut state, range.clone())?; - // The copies between textures' faces around its work, for turns whose passes have not - // run (`texture/faces.rs`). - self.record_face_fixes(&mut state, range.clone())?; - // What each timeline whose writes the tracker forgets completed through as the host saw - // it, each `VkQueue`'s, then the device's own (the module docs): read once, for the - // tracker and for the work's waits alike. - let BatchLists { - reached, - waits, - waited, - } = &mut scheduler.lists; - reached.clear(); - for (slot, vk_queue) in shared.queues.iter().enumerate() { - let value = vk_queue.completed_value(); - scheduler.tracker.completed(slot, value); - reached.push((value > 0).then_some((vk_queue.timeline, value))); - } - reached.extend(device.own_completed()); - // The batches before it on its queue that the host has not seen complete, as of the value - // the tracker just took, which its plan orders by: each took the next value - // (`WorkCounts::batches_with_none_pending` and kin). A second read of the queue's value - // could see a completion the plan did not. - (shared.counts).batch_submitted_behind(scheduler.tracker.pending_before(at)); - if self.queue.unshared() { - shared.counts.unshared_batch(); - } - // One a hang's thread made `Scheduled` early began then (`hang.rs`). - if index == 0 && self.kernel.start() == 0 { - self.kernel.begin(); - } - let slot = state - .times - .slot - .as_ref() - .map(|slot| (slot.queries(), slot.first(), slot.lease())); - // The start timestamp goes into the first command buffer of the first batch, a barrier - // one (with the barrier planned before its first encoder, if any), or into its end when - // it has no work, unless its first encoder wrote it (below). - let mut start_stamp = slot.filter(|_| index == 0); - let batches = state.batches.all(); - let (start, end) = (range.start, range.end); - let binary_waits = batches[index].binary_waits.clone(); - let binary_signals = batches[index].binary_signals.clone(); - // Whether its `VkQueue` waits on the GPU for work of another `VkQueue`'s the host had not - // seen complete: an event's signal pending there (below, the tracker's and the first - // work's waits too), which holds the `VkQueue` until that work ends (`queue_share.rs`). - let mut across = !event_waits.is_empty() - && (batches[index].waits.iter()) - .any(|(event, value)| event.waits_across(*value, queue)); - let mut kept = Vec::new(); - let mut order_waits = Vec::new(); - for (event, value) in &batches[index].signals { - if let Signal::Kept { - index: signal, - after, - } = event.signal(*value, queue) - { - if let Some(after) = after { - order_waits.push((event.semaphore(), after)); - } - kept.push((Arc::clone(event), signal, *value)); - } - } - let images = shared.interop.wrapped.among( - state.recorded[start..end] - .iter() - .flat_map(|recorded| recorded.summary.keys()), - ); - // The textures its encoders made for their own commands (`Device::new_planned_texture`), - // which it holds until it completes. - let own: Vec = lock(&self.own_textures).drain(..).collect(); - if !own.is_empty() { - state.retained.push(Box::new(own)); - } - let encoders = &state.recorded[start..end]; - let mut entries = Vec::new(); - let mut exits = Vec::new(); - let (mut entry_uses, mut exit_uses) = (Vec::new(), Vec::new()); - for image in &images { - let (entry, exit) = image.transitions(); - if let Some(entry) = entry { - entries.push(entry); - entry_uses.push(image.transition_use()); - } - if let Some(exit) = exit { - exits.push(exit); - exit_uses.push(image.transition_use()); - } - } - // The new resources' first work, before every command (`texture/first_move.rs`), given - // back if the submission is not made. A batch's commands may reach every texture - // unnamed, so it takes every move, those of images bound to host pages among them, whose - // pages it then holds. Its commands bind the heap sets, so it holds the texture slots' - // writes until its submission was made (`heap_sets::hold`). - slow_submissions::enter(&mut watch, Phase::FirstWork); - // A test holds the thread here to stand in for a slow first work's take. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - super::completion::trace::at(super::completion::trace::Point::FirstWork); - let firsts = &shared.textures.first_moves; - // On a device with a fill queue it takes the fills of memory its commands may reach - // alone, and of memory no use of the program's names (`FillTake::Reached`): the rest wait - // for a batch that may reach them, so this one neither makes them nor waits for them. - // Either way it learns what owns the memory of the work it takes. - let owner_of = |key: ResourceKey| crate::used_resources::owner_of(shared, key); - let reaches = |owner: ObjectId| state.parts_reach(shared, start..end, &[owner]); - // An upload of bytes a later commit took waits for that commit's batches. - let commit = state.commit; - let fill_take = match device.has_fill_queue() { - true => FillTake::Reached { - owner_of: &owner_of, - reaches: &reaches, - commit, - }, - false => FillTake::Owned { - owner_of: &owner_of, - reaches: &reaches, - commit, - }, - }; - let hold = || crate::heap_sets::hold(device); - // The new textures its commands' first use writes whole before any reads them: their - // moves' zeros go unrecorded (`texture/first_move.rs`). - let overwritten = first_overwrites(encoders, &state.ended); - let overwrites = |key: ResourceKey| overwritten.contains(&key); - // A batch of a queue made for copies takes buffers' fills alone, which its family of - // transfers alone records: its commands name every buffer they reach and no image, and - // the moves and staged copies wait for the device's next submission elsewhere. - let mut first_work = match self.queue.for_copies() { - true => firsts.take_fills_alone(fill_take), - false => firsts.take_holding(|_| true, fill_take, hold, overwrites), - }; - let every_fill = first_work.every_fill(); - // What owns the memory of the first work it took, its fills for the fill queue among it. - let taken_owners = first_work.owners(); - // Whether it took a move that keeps a buffer's bytes by copies around its transition. - let keeps = first_work.keeps(); - // Its buffers' fills go to the device's fill queue where it has one with a command buffer - // free, in a submission of their own that the batch waits for (below, - // `device/staging.rs`), where they write at least `FILL_QUEUE_LEAST` bytes in all: not - // where a group holds batches of this `VkQueue`, whose values that submission would wait - // for before their signals were submitted, nor where the batch waits for a binary - // semaphore, which its one wait consumes. - let fills = (!scheduler.group.holds() - && binary_waits.is_empty() - && first_work.has_first() - && device.fill_queue_has_room()) - .then(|| first_work.take_fills(crate::device::FILL_QUEUE_LEAST)) - .flatten(); - // The copies queued for the staging queue, submitted there first, which the batch waits - // for on the GPU (below), holding what they copied until it completed - // (`texture/staging_copy.rs`). - slow_submissions::enter(&mut watch, Phase::Staging); - let staged = device - .flush_staging() - .map_err(|error| recording_error(device, error))?; - slow_submissions::enter(&mut watch, Phase::Planning); - let entry = (!entries.is_empty()).then(|| Summary::outside_encoders(entry_uses)); - let exit = (!exits.is_empty()).then(|| Summary::outside_encoders(exit_uses)); - // The held depths' moves before each encoder that names one, into the layout it needs - // (`texture/held_depth.rs`): writes the tracker plans with the encoder's uses, before - // them, so each waits for what came before it and orders what follows. Those of an - // encoder whose commands a group's shared `VkCommandBuffer` holds go before the group - // (`encoder_fold::GroupPlaces`). - let unnamed = BTreeSet::new(); - let mut places = GroupPlaces::default(); - let held_moves = - (shared.textures.held).moves(encoders.iter().enumerate().map(|(at, recorded)| { - match state.ended.get(recorded.encoder) { - Some(record) => ( - places.place(at, recorded.encoder, record.group.as_ref()), - &record.keys, - record.held.as_slice(), - ), - None => (at, &unnamed, &[][..]), - } - })); - // Each encoder's summary with its moves' uses joined, where it has moves; the first's - // with what the command buffer's work may write through its residency, which any of its - // encoders may write (`State::resident_writes`). - let resident_writes = state.resident_writes.as_ref(); - let moved: Vec>> = - match held_moves.is_empty() && resident_writes.is_none() { - true => Vec::new(), - false => (encoders.iter().enumerate()) - .map(|(at, recorded)| { - let uses = held_moves.uses(at); - let writes = resident_writes.filter(|_| at == 0); - (!uses.is_empty() || writes.is_some()).then(|| { - let mut summary = recorded.summary.clone(); - if !uses.is_empty() { - summary.join(Summary::outside_encoders(uses.to_vec())); - } - if let Some(writes) = writes { - summary.join(writes.clone()); - } - summary - }) - }) - .collect(), - }; - let summaries = (encoders.iter().enumerate()).map(|(at, recorded)| { - let moved = moved.get(at).and_then(Option::as_ref); - moved.unwrap_or(&recorded.summary) - }); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - let summaries = (encoders.iter().enumerate()).map(|(at, recorded)| { - let moved = moved.get(at).and_then(Option::as_ref); - moved.unwrap_or(&recorded.summary) - }); - let address = Arc::as_ptr(self) as usize; - let mut planned = lock(&PLANNED); - if let Some((_, batches)) = planned.iter_mut().find(|(of, _)| *of == address) { - batches.push(Footprint::of(entry.iter().chain(summaries).chain(&exit))); - } - } - let plan = scheduler - .tracker - .plan(entry.iter().chain(summaries).chain(&exit), at); - // One barrier per summary planned: the entry's, the encoders', the exit's. - let mut barriers = plan.barriers(); - let mut entry_barrier = None; - if let (Some(_), Some((&first, rest))) = (&entry, barriers.split_first()) { - entry_barrier = first; - barriers = rest; - } - let mut exit_barrier = None; - if let (Some(_), Some((&last, rest))) = (&exit, barriers.split_last()) { - exit_barrier = last; - barriers = rest; - } - // Where the driver's submissions stall on semaphore operations, the first command buffer - // of barriers makes what completed work wrote visible, in place of the work's waits (the - // module docs). - let by_barrier = shared.completed_by_barrier; - let mut completed_barrier = by_barrier.then(Barrier::after_completed); - // A first batch with first work (new resources' first moves and fills, copies in) writes - // the start in that work's command buffer, before the work, which runs in the batch's - // submission before its commands: the command buffer's GPU work begins there - // (**GPU times**, the module docs). - let first_start = start_stamp.filter(|_| first_work.has_first() || first_work.has_staged()); - if first_start.is_some() { - start_stamp = None; - } - // The first encoder's prefix wrote the start where the batch plans nothing before that - // encoder (no barrier, no image moved, no barrier for completed work) and its first - // command buffer goes to the queue as recorded (`gpu_time.rs`): then no command buffer of - // barriers starts the batch for the timestamp's sake. - let prefix = state.prefix; - let prefixed = start_stamp.is_some() - && completed_barrier.is_none() - && entry.is_none() - && barriers.first().is_some_and(Option::is_none) - && held_moves.transitions(0).is_empty() - && prefix.is_some_and(|raw| { - state - .recorded - .get(start) - .and_then(|first| first.raws.first()) - == Some(&raw) - }); - if prefixed { - start_stamp = None; - } - if index == 0 { - state.times.prefixed = prefixed; - } - let mut work = Vec::with_capacity(2 * (end - start) + 1); - // Whether a command buffer of barriers goes before the first encoder. - let mut started = false; - // A barrier planned before the first encoder, for earlier work that may still run, or a - // held depth's move there, which waits for all of it: the start goes after the last such - // barrier, once every command before it completed (the module docs). - let encoder_behind = - barriers.first().is_some_and(Option::is_some) || !held_moves.transitions(0).is_empty(); - if entry.is_some() { - started = true; - let globals: Vec = completed_barrier - .take() - .into_iter() - .chain(entry_barrier) - .collect(); - let stamps = Stamps { - start: start_stamp.filter(|_| !encoder_behind), - after: entry_barrier.is_some(), - end: None, - }; - if stamps.start.is_some() { - start_stamp = None; - } - work.push(self.record_barriers(&mut state, &globals, &entries, stamps)?); - } - for (offset, barrier) in barriers.iter().enumerate() { - let moves = held_moves.transitions(offset); - // An encoder whose own command buffer leads it, begun with a barrier from everything - // before (`encoder.rs`, past `PLANNED_BARRIERS`), holds the barrier planned before - // it: no command buffer of barriers goes there, but one that also carries the - // completed work's barrier, the start or a held depth's move. - let part = &state.recorded[start + offset]; - let barriered = (part.barriered).is_some_and(|raw| part.raws.first() == Some(&raw)); - if barriered && completed_barrier.is_none() && start_stamp.is_none() && moves.is_empty() - { - work.extend(&part.raws); - continue; - } - let globals: Vec = completed_barrier - .take() - .into_iter() - .chain(*barrier) - .collect(); - if !globals.is_empty() || start_stamp.is_some() || !moves.is_empty() { - started |= offset == 0; - let stamps = Stamps { - start: start_stamp.take(), - after: barrier.is_some() || !moves.is_empty(), - end: None, - }; - let kept = &mut scheduler.kept; - work.push(self.barrier_buffer(&mut state, kept, at, &globals, moves, stamps)?); - } - work.extend(&state.recorded[start + offset].raws); - } - // The first work goes first in the batch's work, or in a batch with no work in its end - // (the module docs). Host calls' staged copies go at the batch's start, after it, in the - // same command buffer: the two went in two command buffers of one `VkSubmitInfo`, which - // puts them in the same submission order one command buffer's recording order does ("the - // order in which command buffers are specified in the pCommandBuffers member of - // VkSubmitInfo ... determines their submission order", the Vulkan specification, - // Submission Order; inside one command buffer, the order they were recorded), and a - // command buffer boundary is no dependency of its own, so the copies' own leading barrier - // (`FirstMoves::record_staged`) covers the moves recorded before it either way. One - // command buffer where the batch has both (counted: - // `WorkCounts::command_buffers_begun_batch_work`). - let has_first = first_work.has_first(); - let has_staged = first_work.has_staged(); - // First work of uploads alone takes no barrier from the commands before it, nor does the - // start written before it, where the device orders its batches by their ends and no - // internal submission may still run: the end of the batch before it on its `VkQueue` - // orders every command before it ahead of them (`first_move::Earlier::Ended`), and holds - // the start as it holds a first encoder's prefix's (`gpu_time.rs`). Read while the batch - // holds its place in the first work's order, which an internal submission takes before - // it is made, so none is made between this and the batch's submission. - let ended = shared.by_ends || unbarriered_forced(shared); - let earlier = match ended && first_work.uploads_only() && !shared.internal_running() { - true => Earlier::Ended, - false => Earlier::Barriered, - }; - // And, on a device that orders its batches by their ends, no barrier to every later - // command after them, but to the batch's own commands' uses of the buffers they write - // (`first_move::Later::Batch`): the batch's end orders every later batch. - let later = match (earlier, shared.by_ends) { - (Earlier::Ended, true) => upload_readers(&state, start..end, first_work.upload_keys()), - _ => Later::All, - }; - #[cfg(test)] - if let Later::Batch(stages, access) = later { - lock(&shared.upload_scopes).push((stages, access)); - } - let recorded = (has_first || has_staged) - .then(|| { - self.record_raw(&mut state, |_, buffer| { - if let Some((queries, first, _)) = first_start { - // SAFETY: the command buffer is recording, outside a render pass, and is - // submitted first in the batch; the slot is the command buffer's, which - // only its batches write; with no barrier only after the end of the batch - // before (`Earlier::Ended`). - let barrier = earlier == Earlier::Barriered; - unsafe { record_first_start(shared, buffer, (queries, first), barrier) }; - } - if has_first { - // SAFETY: the command buffer is recording, outside a render pass; it is - // submitted first in the batch, before any later one, and every batch on - // another `VkQueue` waits for the batch (`FirstMoves::waits`); `earlier` - // as `Earlier::Ended` says (above). - unsafe { - let family = shared.queue_flags_of(queue); - let order = (earlier, later); - first_work.record((raw, &shared.counts), buffer, family, order); - }; - } - if has_staged { - // SAFETY: the command buffer is recording, outside a render pass; every - // image's move is in this command buffer, before it, or a submission - // before. - unsafe { first_work.record_staged(raw, buffer) }; - } - Ok(()) - }) - }) - .transpose()?; - // Where it holds staged copies it goes at the batch's start, as they did, so the batch - // has work; the first work alone goes first in the work, or in the end where the batch - // has none (below). - let lead = match has_staged { - true => { - work.insert(0, recorded.expect("recorded where there are staged copies")); - None - } - false => recorded, - }; - let BatchWaits { - semaphores: wait_semaphores, - values: wait_values, - stages: wait_stages, - } = waits; - wait_semaphores.clear(); - wait_values.clear(); - wait_stages.clear(); - if let Some(value) = bound { - // The bind waited for the batch's waits; the work waits for the bind. - wait_semaphores.push(shared.queues[queue].timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } else { - for &(semaphore, value) in event_waits { - wait_semaphores.push(semaphore); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - for &semaphore in &binary_waits { - // A binary semaphore's value is ignored. - wait_semaphores.push(semaphore); - wait_values.push(0); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - for (slot, &value) in shared.queues.iter().zip(after_all.iter().flatten()) { - if value > 0 { - wait_semaphores.push(slot.timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - } - } - for wait in plan.waits() { - across |= wait.at.queue != queue; - wait_semaphores.push(shared.queues[wait.at.queue].timeline); - wait_values.push(wait.at.value); - wait_stages.push(wait.legacy_stages()); - } - // Every batch on another `VkQueue` that did new resources' first work whose memory its - // commands, or the first work it took, may reach, until it completed: memory a resource - // its encoders' uses name or make resident owns, every memory where a command may reach - // memory no use names or where that work's owner is unknown, and the memory of the first - // work it took, which comes after that work's. Counted (`WorkCounts::first_work_waits`). - let completed = |point: Point| shared.queues[point.queue].completed_value() >= point.value; - let first_reaches = |owners: Option<&[ObjectId]>| match (owners, taken_owners.as_deref()) { - (Some(owners), Some(taken)) => { - owners.iter().any(|owner| taken.contains(owner)) - || state.parts_reach(shared, start..end, owners) - } - _ => true, - }; - let first_waits: Vec = (firsts.waits(queue, completed).into_iter()) - .filter(|(_, owners)| first_reaches(owners.as_deref())) - .map(|(point, _)| point) - .collect(); - if !first_waits.is_empty() { - shared.counts.first_work_waited(true); - } - for point in last_of_each(first_waits) { - across |= point.queue != queue; - wait_semaphores.push(shared.queues[point.queue].timeline); - wait_values.push(point.value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - // And, where it took a move that keeps a buffer's bytes by copies around its transition - // (`texture/first_move.rs`'s `GpuKeep`), every earlier submission on the device's other - // `VkQueue`s not seen complete, whose commands may access those bytes while the - // transition rewrites them. - if keeps { - for (other, slot) in shared.queues.iter().enumerate() { - let value = slot.submitted_value(); - if other != queue && value > slot.completed_value() { - across = true; - wait_semaphores.push(slot.timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - } - } - // And the internal submission on the first `VkQueue` that did some, until it completed. - if let Some((timeline, value)) = firsts.internal_wait().filter(|_| queue != 0) { - wait_semaphores.push(timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - // And the last binding of a no-copy buffer's dma-bufs, on every `VkQueue`, the first - // too (a binding is ordered with no later submission), until it completed. - if let Some((timeline, value)) = device.binding_wait() { - wait_semaphores.push(timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - // And the staging queue's last submission, until the host saw it complete: what it - // copied may be among what the work reads (`device/staging.rs`). Where a batch of this - // `VkQueue` already waited for it, every later command there follows that wait in - // submission order, this batch's too (the module docs): one wait serves them all. The - // staging queue's place among the timelines follows the `VkQueue`s' and the internal - // submissions' (`Device::own_completed`). - let staging_place = shared.queues.len() + 1; - let staging_wait = (device.staging_wait()) - .filter(|&(_, value)| value > scheduler.waited[queue][staging_place]); - if let Some((timeline, value)) = staging_wait { - wait_semaphores.push(timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - shared.counts.staging_gpu_wait(); - } - // And the last of the fill queue's submissions that the host may not have seen complete - // and whose fills its commands may reach, as the staging queue's, its place after the - // staging queue's (`device/staging.rs`): what it filled may be among what the work - // reads. Each of them where a command may reach memory no use names, or where it took - // every fill waiting; else those of memory its encoders' uses name. - let fill_place = shared.queues.len() + 2; - let fill_reaches = |owners: Option<&[ObjectId]>| { - every_fill || owners.is_none_or(|owners| state.parts_reach(shared, start..end, owners)) - }; - let fill_wait = - device.fill_queue_wait_for(scheduler.waited[queue][fill_place], fill_reaches); - if let Some((timeline, value)) = fill_wait { - wait_semaphores.push(timeline); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - // Its own fills, there: after the batches before it on its `VkQueue` (through the value - // before its own), what it waits for and what completed, as at the start of its work - // (`device/staging.rs`); its work waits for them. - let filled = match fills { - None => None, - Some(fills) => { - let before = (shared.queues[queue].timeline, at.value - 1); - let after: Vec<(vk::Semaphore, u64)> = (wait_semaphores.iter().copied()) - .zip(wait_values.iter().copied()) - .chain(reached.iter().flatten().copied()) - .chain([before]) - .collect(); - (device.submit_fills(fills, &after)) - .map_err(|error| recording_error(device, error))? - } - }; - if let Some(filled) = &filled { - wait_semaphores.push(filled.timeline); - wait_values.push(filled.value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - } - // Whether its commands may reach what the fill-queue submissions it waits for filled, - // counted (`WorkCounts::fill_queue_waits`): its own, and those of the others' it waits - // for that the host may not have seen complete. - if fill_wait.is_some() || filled.is_some() { - let own = - (filled.as_ref()).is_some_and(|filled| fill_reaches(filled.owners.as_deref())); - let after = scheduler.waited[queue][fill_place]; - let others = fill_wait.is_some_and(|(_, value)| { - device - .fill_queue_reached((after, value), fill_reaches) - .is_some() - }); - shared.counts.fill_queue_waited(own || others); - } - let mut order_semaphores: Vec = - order_waits.iter().map(|&(s, _)| s).collect(); - let mut order_values: Vec = order_waits.iter().map(|&(_, value)| value).collect(); - let mut order_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; order_waits.len()]; - // No work: every wait goes with the end, which it then orders. - let single = work.is_empty(); - if single { - order_semaphores.append(wait_semaphores); - order_values.append(wait_values); - order_stages.append(wait_stages); - } - // The work waits for what completed, where its `VkQueue` did not already and no barrier - // made it visible (the module docs); the waits are taken as made once the submission is. - waited.clear(); - if !single && !by_barrier { - for (source, &timeline) in reached.iter().enumerate() { - let Some((semaphore, value)) = timeline else { - continue; - }; - if value > scheduler.waited[queue][source] { - wait_semaphores.push(semaphore); - wait_values.push(value); - wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); - waited.push((source, value)); - } - } - } - // The end went into the work's last command buffer as the batch ended (the module docs), - // where that command buffer goes to the queue as recorded: then the batch has no end of - // its own. One that does not go (its encoder runs nothing, or was encoded again) leaves - // the end to its own command buffer, as every other batch's. - let in_work = match state.fold(index).filter(|(raw, _)| work.contains(raw)) { - None => false, - Some((raw, stamped)) => { - let ends = work.last() == Some(&raw) - && exit_barrier.is_none() - && exits.is_empty() - && start_stamp.is_none() - && stamped == (last && slot.is_some()); - debug_assert!(ends, "a batch's end recorded where the batch does not end"); - if !ends { - let error = internal("a batch's end recorded where the batch does not end"); - return Err(recording_error(device, error)); - } - true - } - }; - // An event's kept signal that waits for another `VkQueue`'s earlier one goes after that - // wait, in an end of its own (the module docs): the end the work holds made its writes - // visible and wrote its end timestamp, so that one records the barrier alone. - let folded = in_work && order_semaphores.is_empty(); - // The end, where the batch has something to end. A batch with no work, no wait, no image - // to move back and no timestamp records none: none of its commands wrote anything, every - // batch before it on any `VkQueue` made its own writes visible to the host before its - // signals, and its signals follow every command submitted before them. A wait needs it: - // a wait orders the commands of its batch, and a signal follows those, not the wait. - let stamps = Stamps { - start: start_stamp.take(), - after: false, - end: slot.filter(|_| last && !in_work), - }; - let ends = !single - || !order_semaphores.is_empty() - || exit_barrier.is_some() - || !exits.is_empty() - || stamps.start.is_some() - || stamps.end.is_some(); - let mut finale: Vec = match ends && !folded { - true => { - let finale_barriers: Vec = exit_barrier - .into_iter() - .chain([crate::batch_order::end(shared.by_ends)]) - .collect(); - let kept = &mut scheduler.kept; - vec![self.barrier_buffer(&mut state, kept, at, &finale_barriers, &exits, stamps)?] - } - false => Vec::new(), - }; - let signal_semaphores: Vec = kept - .iter() - .map(|(event, _, _)| event.semaphore()) - .chain(binary_signals.iter().copied()) - .chain([shared.queues[queue].timeline]) - .collect(); - let signal_values: Vec = kept - .iter() - .map(|&(_, signal, _)| signal) - .chain(binary_signals.iter().map(|_| 0)) - .chain([at.value]) - .collect(); - // A batch whose end its work holds signals with its work. - let (work_signals, work_signal_values) = match folded { - true => (&signal_semaphores[..], &signal_values[..]), - false => (&[][..], &[][..]), - }; - // The first work, first in the batch's work or, where it has none, in its end: it waits - // for what the batch's commands wait for (a heap's fill another queue did comes before a - // move of an image placed in it; an event the program waits for before reusing a heap's - // memory). - if let Some(lead) = lead { - match single { - true => finale.insert(0, lead), - false => work.insert(0, lead), - } - } - // The pieces the batch's segments cut its work into (`RecordedSegment::piece_ends`, - // `rate_mapped_pass.rs`'s **Pieces**): each but the last a `VkSubmitInfo` of its own that - // signals its `VkQueue`'s timeline of pieces (`QueueSlot::pieces`), so no driver merges it - // into the next, as Mesa's common queue merges a submission that signals nothing into the - // next one's kernel submission (`group.rs`). The first takes the work's waits, the last - // its signals. Each piece runs after the one before it in submission order, and begins - // with a barrier from everything before (`EncoderCore::cut_piece`). - let cuts: Vec = (1..work.len()) - .filter(|&at| state.piece_ends.contains(&work[at - 1])) - .collect(); - state.piece_ends.retain(|raw| !work.contains(raw)); - let pieces = cuts.len(); - if pieces > 0 { - shared.counts.rate_map_pieces(pieces as u64); - } - let piece_from = match pieces { - 0 => 0, - count => shared.queues[queue].piece_values(count as u64), - }; - let piece_values: Vec = (0..pieces as u64).map(|k| piece_from + k).collect(); - let piece_semaphore = [shared.queues[queue].pieces]; - let starts: Vec = [0].into_iter().chain(cuts.iter().copied()).collect(); - let ends: Vec = cuts.iter().copied().chain([work.len()]).collect(); - let mut work_timelines: Vec = (0..=pieces) - .map(|k| { - let waits: &[u64] = match k { - 0 => &wait_values[..], - _ => &[], - }; - let signals: &[u64] = match piece_values.get(k) { - Some(value) => std::slice::from_ref(value), - None => work_signal_values, - }; - vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(waits) - .signal_semaphore_values(signals) - }) - .collect(); - let mut infos: Vec = Vec::with_capacity(pieces + 2); - for (k, timeline) in work_timelines.iter_mut().enumerate() { - let (waits, stages): (&[vk::Semaphore], &[vk::PipelineStageFlags]) = match k { - 0 => (&wait_semaphores[..], &wait_stages[..]), - _ => (&[], &[]), - }; - let signals: &[vk::Semaphore] = match k < pieces { - true => &piece_semaphore, - false => work_signals, - }; - infos.push( - vk::SubmitInfo::default() - .wait_semaphores(waits) - .wait_dst_stage_mask(stages) - .command_buffers(&work[starts[k]..ends[k]]) - .signal_semaphores(signals) - .push_next(timeline), - ); - } - // The fence the last batch signals where the driver reads a command buffer's objects - // after its value, and every batch where the queue's failures are relayed - // (`device/relay.rs`): taken before the submission, given back if it fails. Elsewhere - // the batch takes none (`fences::ends_at_fence`). - let fence = if (last || shared.flights(queue).is_some()) - && super::fences::ends_at_fence(device, queue) - { - // SAFETY: the device's fences, inside the scheduler's section. - Some( - unsafe { shared.fences.take(raw) } - .map_err(|error| submission_error(device, error))?, - ) - } else { - None - }; - let mut end_timeline = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&order_values) - .signal_semaphore_values(&signal_values); - let second = vk::SubmitInfo::default() - .wait_semaphores(&order_semaphores) - .wait_dst_stage_mask(&order_stages) - .command_buffers(&finale) - .signal_semaphores(&signal_semaphores) - .push_next(&mut end_timeline); - match (single, folded) { - (true, _) => infos = vec![second], - (false, true) => {} - (false, false) => infos.push(second), - } - let submits = &infos[..]; - let buffers = (submits.iter()) - .map(|info| info.command_buffer_count as usize) - .sum(); - // From here its heap set versions may be pending: nothing writes them any more, and its - // first batch takes the ticket a texture that goes from now on waits for - // (`heap_sets.rs`). One committed and not yet submitted holds no gone texture. - if let Some(ticket) = state.heaps.submit(device) { - state.retained.push(Box::new(ticket)); - } - if let Some(staged) = staged { - state.retained.push(Box::new(staged)); - } - // The batch waits in the group, its submission's changes made below, where it may and - // took no first work, the device wrapped no image of the caller's it names since it was - // found ready, and it waits for nothing but values seen complete where a group is held: a - // batch with a wait leads a group, never joins one, so the merge, which gathers every - // batch's waits before the first one's commands, never holds back an earlier batch for - // another's wait. Else it goes now, after the group where one is held. - let waits = wait_semaphores.len() - waited.len() + order_semaphores.len(); - let leads = !scheduler.group.holds() || waits == 0; - let grouped = joins - && leads - && !first_work.has_first() - && !first_work.has_staged() - && filled.is_none() - && images.is_empty(); - // What the batch's submission carries, to its value, from here: the device's pending - // audit's (`pending_audit.rs`), where it is on. - let carried = (shared.queues[queue].timeline, at.value); - if let Some(audit) = raw.pending_audit() { - audit.submitted(raw, carried, &[work.as_slice(), finale.as_slice()]); - } - // The host time its submission was called, where it went now (`Group::submit`). - let mut called = None; - if grouped { - scheduler.group.open(queue, &scheduler.waited[queue]); - // A watched submission held its thread long before the group took it in the call's - // place: its line (`slow_submissions.rs`). - if let Some(watch) = watch.take() { - let batches = state.batches.all().len(); - watch.held(device, (index, batches), queue, gpu_time::host_nanos()); - } - } else { - // SAFETY: every command buffer is executable and submitted once; every wait is for a - // signal already submitted (the scheduler's order, and for a binary semaphore the - // caller's contract of `encode_wait_for_vk_semaphore`); every signal of a timeline is - // above its value and any earlier one (the queue's values rise, and an event's kept - // indices rise and wait for the previous one on another queue), and every binary one - // is of an unsignaled semaphore with no signal pending (`encode_signal_vk_semaphore`); - // every transition is of a live image of the caller's in the layout it is in (its - // contract, `new_texture_with_vk_image`); the fence is unsignaled and in no pending - // submission; the `VkQueue` is used under its lock (`Group::submit`). - if scheduler.group.holds() { - let end = match leads { - true => GroupEnd::FirstWork, - false => GroupEnd::Wait, - }; - shared.counts.group_ended(end); - } else if counts_alone { - let first = first_work.has_first() - || first_work.has_staged() - || filled.is_some() - || !images.is_empty(); - let why = (alone_for) - .or(first.then_some(Alone::FirstWork)) - .or(alone.then_some(Alone::AtCommit)); - if let Some(why) = why { - shared.counts.batch_alone(why); - } - } - // What the batch carried, for the line its failed submission logs - // (`submit_failure.rs`): read only once the call failed. - let kept_signals = kept.len(); - let kept_barriers = &scheduler.kept; - let carry = |carried: &mut Carried, types: &TypeFlags| { - carried - .binary - .extend(binary_waits.iter().chain(&binary_signals)); - carried - .events - .extend(event_waits.iter().map(|&(semaphore, _)| semaphore)); - carried - .events - .extend(signal_semaphores[..kept_signals].iter()); - carried.events.extend(order_semaphores.iter()); - self.carry(&state, (Some(index), Some(start..end)), carried, types); - let roles = &mut carried.roles; - roles.extend(recorded.map(|raw| (raw, "first work".to_owned()))); - roles.extend(finale.iter().map(|&raw| (raw, "end".to_owned()))); - for &raw in &work { - if roles.iter().any(|(known, _)| *known == raw) { - continue; - } - let role = match kept_barriers.kept(queue, raw) { - Some(taken) => format!("kept barriers, taken for {taken}"), - None => "barriers".to_owned(), - }; - roles.push((raw, role)); - } - }; - let after = After { - queue, - infos: submits, - buffers, - value: at.value, - fence, - begun, - relayed: &self.relayed, - carry: &carry, - }; - let submitted = - scheduler - .group - .submit(device, &mut scheduler.waited[queue], Some(after)); - // A watched submission held its thread long before the call: its line - // (`slow_submissions.rs`). - if let (Some(watch), Ok(at)) = (watch.take(), &submitted) { - let batches = state.batches.all().len(); - watch.called( - device, - (index, batches), - queue, - (*at, gpu_time::host_nanos()), - ); - } - // Where the device notes queue times, the call's return, for the command buffer this - // batch ends (`CommandBuffer::submit_returned_time`). - if last && submitted.is_ok() && shared.timing.queue_times() { - self.kernel.returned_at(gpu_time::host_nanos()); - } - // A test's stand-in for a scheduler thread preempted once the call returned. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - super::completion::trace::submit_returned(); - if let Err(error) = submitted { - if let Some(audit) = raw.pending_audit() { - audit.withdrawn(carried, &[work.as_slice(), finale.as_slice()]); - } - if let Some(fence) = fence { - // SAFETY: the failed submission is not pending; inside the section. - // Released, not kept: Vulkan leaves a fence's state after a failed - // submission unsaid. - unsafe { release::object(raw, fence) }; - } - // A `vkQueueSubmit` that fails leaves what its submissions reference as it was, - // or loses the device: the first work goes back, still to be done, as - // `first_work` drops. Where the device is lost, its command buffers, of this - // command buffer's pool that goes as the command buffer fails, go once the - // driver's own completion of what the call ran did (`Device::drain_queues`). - let error = submission_error(device, error); - if matches!(error, CommandBufferError::DeviceLost) { - device.drain_queues(); - } - return Err(error); - } - called = submitted.ok(); - // A sync file's signal among its signals is now submitted (`sync_file.rs`). - #[cfg(unix)] - self.sync_file_submitted(&mut state, &binary_signals); - // The first call that carried a batch of it: the earliest its GPU work began at, - // where GPU times are answered from the host (`place_gpu_times`). - if let Some(at) = called { - self.kernel.submitted_at(at); - } - } - // From the first batch whose `VkQueue` waits on the GPU for another's work, its `VkQueue` - // holds it: its long mark counts from that batch's submission (`place_gpu_times`). - if across && state.times.waited_across.is_none() { - state.times.waited_across = Some(called.unwrap_or_else(gpu_time::host_nanos)); - } - // It makes its command buffer `Scheduled` where it ends it, unless a hang's thread makes - // it (`hang.rs`): the command buffer's own hang's, once this batch, the one before the - // hang's wait, is taken (the thread waits for it on `changed`), or, for one committed - // during a hang, early, where it did not wait past the hang. Its kernel end is the host - // time its submission was called, which no GPU end of its work can precede - // (`Group::submit`); a held batch's is its group's. - let (schedules, took) = hang::schedules(&mut state.hang_scheduling, index, last); - if took { - let parked = state.parked > 0; - self.wake_parked(parked); - } - if let (true, Some(at)) = (schedules, called) { - self.kernel.end_at(at); - } - if !single { - match folded { - true => shared.counts.finale_folded(), - false => shared.counts.finale_apart(), - } - } - for &(source, value) in waited.iter() { - scheduler.waited[queue][source] = value; - } - // Its staging wait, made or held: a held group goes to its `VkQueue` before any later - // batch there, and one whose submission fails puts the values back. - if let Some((_, value)) = staging_wait { - scheduler.waited[queue][staging_place] = value; - } - let fill_waited = fill_wait.map(|(_, value)| value); - let fill_waited = fill_waited.max(filled.as_ref().map(|filled| filled.value)); - if let Some(value) = fill_waited { - scheduler.waited[queue][fill_place] = value; - } - // What its fills hold, until it completed. - if let Some(filled) = filled { - state.retained.push(Box::new(filled)); - } - shared.counts.completed_waited(waited.len()); - if !single && !started { - shared.counts.bare_start(); - } - if prefixed { - shared.counts.prefixed_start(); - } - // Its submission handlers run on a committing thread once the scheduler's lock is free, - // or on the device's handler threads, which the scheduler's thread hands them to; a - // switch of storage forms riding on it ends on the submitting thread first, which then - // runs them itself (`scheduler/mod.rs`). Its transition to `Scheduled`, posted as it is - // published or held, waits for them. One made `Scheduled` behind a host step ran them, - // or runs them, in that pass's turn: its flag stays as that pass left it. - let forms = last && state.storage_form.is_some(); - let handlers = (schedules && !state.submission.is_empty()) || forms; - if !hang::scheduled_early(&state.hang_scheduling) { - state.submitting = handlers; - } - scheduler.tracker.apply(plan); - // The standings across command buffers, in the order the tracker took the batch - // (`shadow_standing.rs`): its writes let go of those they meet; then, where it ends the - // command buffer with its last encoder and nothing failed it or reached memory unnamed, - // the shadows its end left holding every texel of their truth stand. - let unnamed = state.reaches_unnamed; - let clean = state.failure.is_none() - && state.fails_from.is_none() - && state.faulted.is_empty() - && state.hang.is_none() - && !rebound; - let ends = last && start < end && end == state.recorded.len() && clean && !unnamed; - // Each shadow the end carries that it leaves no standing notes why - // (`shadow_standing::Missed`). - let held = match (last, &state.shadow_carry) { - (true, Some(carry)) => carry.standing_at_end(ends), - _ => Vec::new(), - }; - let summaries = (state.recorded[start..end].iter()).map(|recorded| &recorded.summary); - shared.standings.submitted(summaries, unnamed, &held); - held_moves.submitted(); - shared.counts.held_depths_released(held_moves.released); - let several = shared.queues.len() > 1; - let held = first_work.submitted(several.then_some(at)); - if !held.is_empty() { - state.retained.push(Box::new(held)); - } - scheduler.values[queue] = at.value; - // A batch on the copy engine's `VkQueue` (`Device::new_command_queue_for_copies`). - if shared.copy_slot() == Some(queue) { - shared.counts.copy_queue_batch(); - } - // Its command buffer's wait behind another command queue's batch there, from its first - // batch's submission or hold (`queue_wait.rs`). - let on = &shared.queues[queue]; - let first = (index == 0).then(|| crate::queue_wait::First { - since: called.unwrap_or_else(gpu_time::host_nanos), - unshared: self.queue.unshared(), - }); - let completed = || on.completed_value(); - // Its place in the `VkQueue`'s flight, where an unshared queue holds it - // (`unshared_hold.rs`) or the device's queues take turns (`queue_turns.rs`). - let of = (self.queue.id(), self.queue.unshared()); - let flies = device.flies(queue, of, self.queue.expected()); - let taken = (at.value, self.queue.id(), flies); - (on.waits).taken(taken, first, completed, &shared.counts); - for image in &images { - image.submitted(); - // One that rests in `GENERAL` from now on (an encode-time image after its first - // batch) is moved by no later batch. - if image.settled() { - shared.interop.wrapped.forget(image); - } - } - // Its signals are seen at its completion turn alone where it may write a copied host - // buffer, whose bytes reach the pages there (`event_timeline.rs`). - let behind_merge = !kept.is_empty() && shared.copied.any(); - if behind_merge { - shared.counts.event_signals_behind_merge(kept.len()); - } - // A last batch's signals name its command buffer, which another queue's command buffer - // that waits for one completes after; its transition to `Completed` lets them go - // (`follow.rs`). - let follow = (last && !kept.is_empty()).then(|| Arc::new(Follow::new(self.queue.id()))); - for (event, signal, value) in &kept { - event.keep( - *signal, - *value, - (queue, at.value), - follow.clone(), - behind_merge, - ); - } - if let Some(follow) = follow { - let signals = (kept.iter()).map(|(event, signal, _)| (Arc::clone(event), *signal)); - let signals = signals.collect(); - state.release = Some(Release { follow, signals }); - } - // Its commands may reach every texture through its resource ID where one bound a heap - // set: the stale-reach degrade's trigger decides (`detach.rs`). - let reaches = state.heaps.bound(); - let rebound_use = state.rebound_use.clone(); - // The holds its completion lets go (`State::holds_until`). - let holds = state.holds_until(index); - // What it completes after: the batches of other `VkQueue`s whose GPU signals its event - // waits were met by, not finished yet, and the command buffers of other queues they end - // (`completion.rs`, "After what it waited for"). - let after = { - let State { - batches, waited, .. - } = &mut *state; - finishes_after(&batches.all()[index].waits, (queue, self), waited) - }; - drop(state); - if rebound { - device.degrade_encoded_use_rebound(rebound_use); - } - device.reach_stale_detached(reaches); - let submission = Submission { - queue, - batch: Submitted { - value: at.value, - buffer: self.hold(), - last, - fence, - signals: kept - .into_iter() - .map(|(event, signal, _)| (event, signal)) - .collect(), - holds, - after, - held: false, - trail, - }, - handlers, - forms, - schedules, - scheduled: false, - unsubmitted: false, - }; - if !grouped { - return Ok(Submitting::Submitted(submission)); - } - let first = InfoParts { - waits: (wait_semaphores, wait_values, wait_stages), - buffers: &work, - signals: (work_signals, work_signal_values), - }; - let second = InfoParts { - waits: (&order_semaphores, &order_values, &order_stages), - buffers: &finale, - signals: (&signal_semaphores, &signal_values), - }; - let parts = [first, second]; - let parts = match (single, folded) { - (true, _) => &parts[1..], - (false, true) => &parts[..1], - (false, false) => &parts[..], - }; - // How long its submission took to here: a group's call that carries this batch alone is - // timed from as far before it (`Group::submit`). - let planned = gpu_time::host_nanos().saturating_sub(begun); - scheduler.group.hold( - parts, - buffers, - submission, - (run.unwrap_or(0), closes, planned), - ); - Ok(Submitting::Grouped) - } - - /// Take batch `index` (`last` where it ends the command buffer) of a command buffer that needs - /// no GPU work ([`State::needs_no_gpu`]) with no submission, as its submission would take it - /// but for the `vkQueueSubmit` (the module docs): its batch is watched at its `VkQueue`'s last - /// submitted value in `scheduler`, with no fence and no signal. - fn take_unsubmitted( - self: &Arc, - state: &mut State, - index: usize, - last: bool, - scheduler: &scheduler::State, - ) -> Submission { - let device = &self.device; - let queue = self.queue.vk_queue(); - if index == 0 && self.kernel.start() == 0 { - self.kernel.begin(); - } - // What it holds until it completes, as a submitted batch takes it. - let own: Vec = lock(&self.own_textures).drain(..).collect(); - if !own.is_empty() { - state.retained.push(Box::new(own)); - } - if let Some(ticket) = state.heaps.submit(device) { - state.retained.push(Box::new(ticket)); - } - // Scheduled by its last batch's taking, unless a hang's thread makes it (`hang.rs`). - let (schedules, took) = hang::schedules(&mut state.hang_scheduling, index, last); - if took { - let parked = state.parked > 0; - self.wake_parked(parked); - } - if schedules { - self.kernel.end_at(gpu_time::host_nanos()); - } - let forms = last && state.storage_form.is_some(); - let handlers = (schedules && !state.submission.is_empty()) || forms; - if !hang::scheduled_early(&state.hang_scheduling) { - state.submitting = handlers; - } - let holds = state.holds_until(index); - device.shared().counts.command_buffer_unsubmitted(); - Submission { - queue, - batch: Submitted { - value: scheduler.values[queue], - buffer: self.hold(), - last, - fence: None, - signals: Vec::new(), - holds, - after: Vec::new(), - held: false, - trail: None, - }, - handlers, - forms, - schedules, - scheduled: false, - unsubmitted: true, - } - } - - /// Publish a batch [`submit_batch`](Self::submit_batch) submitted, after the section that - /// submitted it ended: when it ends the command buffer, its transition to `Scheduled` - /// (`CommandBufferShared::schedule`) unless it made it as it was held in a group - /// ([`Submission::schedule_held`]), then its queue waiter's watch for it. From the watch - /// on, the command buffer may complete and run its release on its queue's handler thread - /// before the caller lets go of anything it took, so the caller holds nothing of what its - /// commands or encoders took (`scheduler::Spent`). - pub(crate) fn publish(self: &Arc, submission: Submission) { - let Submission { - queue, - batch, - schedules, - scheduled, - unsubmitted, - .. - } = submission; - if schedules && !scheduled { - // Before a completion turn can see it finish, so the queue's context runs its - // transition to `Scheduled` first. - self.schedule(); - } - let completion = &self.device.shared().completion; - match unsubmitted { - // The caller makes the turn that finishes it where its queue reached its value and no - // turn is under way, once it holds no lock (`Completion::turn_owed`). - true => completion.watch_unsubmitted(queue, batch), - false => completion.watch(queue, batch), - } - } - - /// A command buffer of this command buffer's pool holding what `record` records into it, - /// with the state at hand. - fn record_raw( - &self, - state: &mut State, - record: impl FnOnce(&mut State, vk::CommandBuffer) -> Result<(), Error>, - ) -> Result { - let device = &self.device; - let raw = device.shared().vk(); - let buffer = self - .allocate_raw(state) - .map_err(|error| recording_error(device, error))?; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer was just allocated from the pool, under the state lock, and - // only this call records it. - let begun = unsafe { raw.begin_command_buffer(buffer, &begin) }; - exit_guard::called(Call::BeginCommandBuffer); - begun.map_err(|error| submission_error(device, error))?; - device - .shared() - .counts - .command_buffer_begun(Begun::BatchWork); - record(state, buffer).map_err(|error| recording_error(device, error))?; - // SAFETY: as above. - let ended = unsafe { self.end_raw(buffer) }; - exit_guard::called(Call::EndCommandBuffer); - ended.map_err(|error| submission_error(device, error))?; - Ok(buffer) - } - - /// Record the copies between textures' faces that the batch of parts `range` takes around - /// its work for turns whose passes have not run (`texture/faces.rs`, `FaceSwaps::fixes`): - /// each from the face that holds the truth into the face the batch names, in a command buffer - /// before its first part's own, and back after its last part's where the batch may write the - /// face it names, each joined to its part's summary, so the tracker orders them with the - /// batch's work and the standings across command buffers count their writes. The faces are - /// held until the command buffer completes. A part that runs nothing (its encoder failed, or - /// its use was rebound) leaves a turn of its pass to the next batch that names its face. - fn record_face_fixes( - &self, - state: &mut State, - range: std::ops::Range, - ) -> Result<(), CommandBufferError> { - let device = &self.device; - let swaps = &device.shared().face_swaps; - if !swaps.any() || range.is_empty() { - return Ok(()); - } - let unnamed = state.reaches_unnamed || state.heaps.bound(); - let parts = &state.recorded[range.clone()]; - let summaries = parts.iter().map(|part| &part.summary); - let ran = |part: usize| { - let at = part.checked_sub(range.start); - (at.and_then(|at| parts.get(at))).is_some_and(|part| !part.raws.is_empty()) - }; - let fixes = swaps.fixes(self.address(), (range.clone(), &ran), summaries, unnamed); - if fixes.is_empty() { - return Ok(()); - } - let raw = device.shared().vk(); - let (front, back): (Vec<_>, Vec<_>) = fixes.iter().map(FaceFix::uses).unzip(); - let record = |state: &mut State, forward: bool| { - self.record_raw(state, |_, buffer| { - for fix in fixes.iter().filter(|fix| forward || fix.back) { - // SAFETY: the command buffer is recording, outside a render pass; both faces - // are live (held below until the command buffer completes) and rest in - // `GENERAL`. - unsafe { fix.record(raw, buffer, forward) }; - } - Ok(()) - }) - }; - let before = record(state, true)?; - let first = &mut state.recorded[range.start]; - first.raws.insert(0, before); - for summary in front { - first.summary.join(summary); - } - let back: Vec> = back.into_iter().flatten().collect(); - if !back.is_empty() { - let after = record(state, false)?; - let last = &mut state.recorded[range.end - 1]; - last.raws.push(after); - for summary in back { - last.summary.join(summary); - } - } - let counts = &device.shared().counts; - for fix in &fixes { - let texels = fix.texels(); - counts.attached_read_swap_fix(texels); - if fix.back { - counts.attached_read_swap_fix(texels); - } - } - state.retained.push(Box::new(fixes)); - Ok(()) - } - - /// Record the segments of encoders `range` that their batch's submission records: the - /// scrubs (`Deferred::SparseScrub`), with the mappings it applied, and the gated copies in - /// (`Deferred::GatedCopyIn`), with the regions their logs say changed since the commit's - /// stamp, published by now; and the merges of runs of passes over a linear attachment or a - /// shadowed texture (`Deferred::RunMerge`), each the run's last pass's (or the last before a - /// pass encoded again), the ones taken over recording nothing. - fn record_scrubs( - &self, - state: &mut State, - range: std::ops::Range, - ) -> Result<(), CommandBufferError> { - let mut scrubs = Vec::new(); - for (encoder, recorded) in state.recorded[range.clone()].iter().enumerate() { - for (at, segment) in recorded.segments.iter().enumerate() { - let at_submission = matches!( - segment.work, - Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) - ); - if at_submission && segment.recorded.is_none() { - scrubs.push((range.start + encoder, at, segment.work.clone())); - } - } - } - let device = &self.device; - for (encoder, at, work) in scrubs { - // A run's merge a later pass took over records nothing (`pass_runs.rs`). - if let Deferred::RunMerge(merge) = &work { - if merge.taken() { - state.recorded[encoder].segments[at].recorded = - Some(RecordedSegment::submitted(Vec::new())); - continue; - } - } - // A copy in its shadow's standing decides moves nothing where the image stands now, - // or the texels inside the rectangle it stands stale in alone - // (`shadow_standing.rs`). - let standing = match &work { - Deferred::GatedCopyIn(copy) => copy.standing(), - _ => None, - }; - let decided = standing.map(|copies| self.stands(state, encoder, copies)); - let stands = decided.and_then(Result::ok); - let raw = self.record_raw(state, |state, buffer| { - match &work { - // SAFETY: the command buffer is recording; the texture is live (its encoder's - // command buffer holds it), in `GENERAL`, and its batch's updates applied. - Deferred::SparseScrub(scrub) => { - let held = unsafe { scrub.record(device, buffer) }?; - if !held.is_empty() { - state.retained.push(Box::new(held)); - } - } - // SAFETY: the command buffer is recording, outside a render pass; the - // shadowed texture is live (its encoder's command buffer holds it), its - // image in `GENERAL`. - Deferred::GatedCopyIn(copy) => unsafe { - copy.record(device.shared().vk(), buffer, stands) - }, - // SAFETY: the command buffer is recording, outside a render pass; the merge, - // its images and its scratch are held until it completes (its pass's encoder - // retains them, and the segment its copies), and the images rest in - // `GENERAL`. - Deferred::RunMerge(merge) => { - unsafe { merge.record(device.shared().vk(), buffer) }; - let counts = &device.shared().counts; - match merge.shadow() { - Some(copy) => count_shadow_copies(counts, std::slice::from_ref(copy)), - None => counts.linear_merge_recorded(), - } - } - _ => {} - } - Ok(()) - })?; - state.recorded[encoder].segments[at].recorded = - Some(RecordedSegment::submitted(vec![raw])); - if let (Some(decided), Deferred::GatedCopyIn(copy)) = (decided, &work) { - let counts = &device.shared().counts; - let (texels, moved) = (copy.texels(), copy.texels_moved(stands)); - counts.shadow_copy_in_against_standing(stands.is_some(), texels - moved); - match decided { - Err((at, let_go, missed)) => { - counts.shadow_copy_in_unskipped(at, let_go, missed, texels); - } - Ok(Some(_)) if moved > 0 => { - let missed = - standing.map_or(Missed::Unmet, |copies| copies.standing.last_missed()); - counts.shadow_copy_in_unskipped( - Unskipped::StaleWithin, - None, - missed, - moved, - ); - } - Ok(_) => {} - } - } - } - Ok(()) - } - - /// Settle the copies out of buffers with a host copy that the blits of parts `range` decided - /// and recorded as they were encoded (`managed_sync.rs`, **What the encoding cannot see**): - /// the writes of other command buffers noted since each one's encoding go into a - /// `VkCommandBuffer` just before its part, where any were. Then note the parts' writes, the - /// command buffer's writes through its residency, and where it may write memory no use names, - /// the batch at `at`. - fn settle_syncs_out( - &self, - state: &mut State, - range: std::ops::Range, - at: Point, - ) -> Result<(), CommandBufferError> { - let shared = self.device.shared(); - let writes = &shared.gpu_writes; - let completed = |point: Point| { - (shared.queues.get(point.queue)).is_some_and(|on| on.completed_value() >= point.value) - }; - let by = self.id.get(); - let copies: Vec> = (lock(&self.at_completion).iter()) - .filter_map(|work| match work { - AtCompletion::Synced(copy) => Some(Arc::clone(copy)), - AtCompletion::Undo(_) => None, - }) - .collect(); - for part in range.clone() { - for copy in &copies { - if !copy.unsettled_in(&state.recorded[part].raws) { - continue; - } - let top_up = copy.settle(writes, by, &completed); - if top_up.is_empty() { - continue; - } - let raw = self.record_raw(state, |_, buffer| { - // SAFETY: the command buffer is recording, outside a render pass; it goes to - // the queue just before the part that holds the copy's command, whose encoder - // holds the buffer and the copy's target until it completes. - unsafe { copy.record_top_up(shared.vk(), buffer, &top_up) }; - Ok(()) - })?; - state.recorded[part].raws.insert(0, raw); - } - } - if writes.keeps_any() { - let parts = state.recorded[range].iter().map(|part| &part.summary); - writes.note(parts.chain(&state.resident_writes), by); - } - if state.writes_unnamed { - writes.note_unnamed(at, &completed); - } - Ok(()) - } - - /// Whether `copies`' image stands across command buffers (`shadow_standing.rs`) for a copy - /// in of encoder `encoder`, submitted now: it stands, no earlier encoder of the command - /// buffer wrote the truth or the image, and none of its commands may reach memory no use - /// names; and the rectangle it stands stale inside alone, where it does - /// (`Standings::standing`). Where not, where that was decided, what its standing held - /// (`shadow_standing::Unskipped`, `LetGo`; none where it stood) and what last kept a command - /// buffer's end from leaving it standing (`Missed`). - fn stands( - &self, - state: &State, - encoder: usize, - copies: &ShadowCopies, - ) -> Result, (Unskipped, Option, Missed)> { - let missed = copies.standing.last_missed(); - if !copies.stands_across() { - return Err((Unskipped::Unstanding, None, missed)); - } - let keys = copies.standing_keys(); - let wrote = - (state.recorded[..encoder].iter()).any(|recorded| recorded.summary.writes_any(&keys)); - let standing = self.device.shared().standings.standing(copies); - match (state.reaches_unnamed || wrote, standing) { - (false, Ok(stale)) => Ok(stale), - (true, standing) => Err((Unskipped::CommandBuffer, standing.err(), missed)), - (false, Err(let_go)) => Err((Unskipped::LetGo, Some(let_go), missed)), - } - } - - /// Record the decodes into ASTC carriers' second decoded twins (`texture/decoded_twin.rs`) of - /// the batch of encoders `range`, a batch with work: those queued (as each twin was made, - /// and after host calls wrote its carrier), in one command buffer before the first part's - /// own, their uses joined to its summary, so the barrier and waits planned before that part - /// order them after the earlier writes of their images; but those of an image a part of the - /// batch wrote without a decode (the image had no second twin as the write was encoded), which - /// stay queued for a later batch: a twin made since reads the carrier as this batch leaves it. - /// Then after each part's own command buffers, the decodes its writes made as they were - /// encoded, their uses joined to its summary. Nothing, and no command buffer, where there is - /// none (counted: `WorkCounts::second_twin_checks`, `WorkCounts::second_twin_decodes`). - fn record_second_decodes( - &self, - state: &mut State, - range: std::ops::Range, - ) -> Result<(), CommandBufferError> { - let device = &self.device; - let counts = &device.shared().counts; - if range.is_empty() { - return Ok(()); - } - let held: Vec = state.recorded[range.clone()] - .iter() - .flat_map(|part| &part.twin_writes) - .filter_map(TwinWrite::without_decode) - .collect(); - let queued = device.take_second_decodes(|key| held.contains(&key)); - if !queued.is_empty() { - let raw = self.record_raw(state, |_, buffer| { - for decode in &queued { - // SAFETY: the command buffer is recording, outside a render pass, on the - // device's queue family; the decode is retained until the command buffer - // completes. - unsafe { decode.record(device.shared().vk(), buffer) }; - } - Ok(()) - })?; - let uses = queued.iter().flat_map(|decode| decode.uses()).cloned(); - let first = &mut state.recorded[range.start]; - first.raws.insert(0, raw); - first - .summary - .join(Summary::outside_encoders(uses.collect())); - counts.second_twin_decodes(queued.len()); - state.retained.push(Box::new(queued)); - } - for part in range { - let mut checked = 0; - let mut decodes: Vec = Vec::new(); - for write in state.recorded[part].twin_writes.drain(..) { - checked += 1; - decodes.extend(write.into_decode()); - } - counts.second_twin_checks(checked); - if decodes.is_empty() { - continue; - } - let raw = self.record_raw(state, |_, buffer| { - for decode in &decodes { - // SAFETY: as above. - unsafe { decode.record(device.shared().vk(), buffer) }; - } - Ok(()) - })?; - let uses = decodes.iter().flat_map(|decode| decode.uses()).cloned(); - let recorded = &mut state.recorded[part]; - recorded.raws.push(raw); - recorded - .summary - .join(Summary::outside_encoders(uses.collect())); - counts.second_twin_decodes(decodes.len()); - state.retained.push(Box::new(decodes)); - } - Ok(()) - } - - /// A command buffer holding only `barriers`, in order, then `transitions` of the caller's - /// images or of held depths, between the `stamps` it writes, for the batch that signals `at`: where it moves no - /// image, one the scheduler keeps (`kept_barriers.rs`; one that writes timestamps, kept for - /// their slot) on a queue whose command buffers end at their timeline's value - /// (`fences::ends_at_fence`), and else, or past the kept ones' bounds, one recorded into this - /// command buffer's pool ([`record_barriers`](Self::record_barriers)). - fn barrier_buffer( - &self, - state: &mut State, - kept: &mut KeptBarriers, - at: Point, - barriers: &[Barrier], - transitions: &[Transition], - stamps: Stamps, - ) -> Result { - let device = &self.device; - if transitions.is_empty() && !super::fences::ends_at_fence(device, at.queue) { - let taken = kept - .take(device, at.queue, barriers, stamps.kept(), at.value) - .map_err(|error| recording_error(device, error))?; - if let Some(buffer) = taken { - return Ok(buffer); - } - } - self.record_barriers(state, barriers, transitions, stamps) - } - - /// A command buffer of this command buffer's pool holding only `barriers`, in order, then - /// `transitions` of the caller's images or of held depths, from all commands before to all - /// commands after, between the `stamps` it writes. - fn record_barriers( - &self, - state: &mut State, - barriers: &[Barrier], - transitions: &[Transition], - stamps: Stamps, - ) -> Result { - let device = &self.device; - let raw = device.shared().vk(); - let buffer = self - .allocate_raw(state) - .map_err(|error| recording_error(device, error))?; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer was just allocated from the pool, under the state lock, and - // only this call records it. - unsafe { - let begun = raw.begin_command_buffer(buffer, &begin); - exit_guard::called(Call::BeginCommandBuffer); - begun.map_err(|error| submission_error(device, error))?; - device - .shared() - .counts - .command_buffer_begun(Begun::BatchBarriers); - if let Some((queries, first, _)) = stamps.start { - // The slot's start and end, where it was not reset on the host (`gpu_time.rs`). - if !device.shared().timing.resets_on_host() { - raw.cmd_reset_query_pool(buffer, queries, first, 2); - exit_guard::called(Call::CmdResetQueryPool); - } - if !stamps.after { - let top = vk::PipelineStageFlags::TOP_OF_PIPE; - raw.cmd_write_timestamp(buffer, top, queries, first); - exit_guard::called(Call::CmdWriteTimestamp); - } - } - // Of its queue's family: a copy engine's on a queue made for copies. - let reads = device.shared().memory_reads_of(self.queue.vk_queue()); - for barrier in barriers { - barrier.record_reading(raw, buffer, reads); - exit_guard::called(Call::CmdPipelineBarrier); - } - if !transitions.is_empty() { - let family = device.shared().queue_flags_of(self.queue.vk_queue()); - let images: Vec> = (transitions.iter()) - .map(|transition| transition.barrier(family)) - .collect(); - let all = vk::PipelineStageFlags::ALL_COMMANDS; - raw.cmd_pipeline_barrier( - buffer, - all, - all, - vk::DependencyFlags::empty(), - &[], - &[], - &images, - ); - exit_guard::called(Call::CmdPipelineBarrier); - } - if let Some((queries, first, _)) = stamps.start.filter(|_| stamps.after) { - let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; - raw.cmd_write_timestamp(buffer, bottom, queries, first); - exit_guard::called(Call::CmdWriteTimestamp); - } - if let Some((queries, first, _)) = stamps.end { - let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; - raw.cmd_write_timestamp(buffer, bottom, queries, first + 1); - exit_guard::called(Call::CmdWriteTimestamp); - } - let ended = self.end_raw(buffer); - exit_guard::called(Call::EndCommandBuffer); - ended.map_err(|error| submission_error(device, error))?; - } - Ok(buffer) - } -} - -/// The command buffer's failure for a batch's sparse binding that failed: the device's memory, or -/// the bind itself. -fn bind_error(device: &crate::Device, failure: BindFailure) -> CommandBufferError { - match failure { - BindFailure::Memory(error) => recording_error(device, error), - BindFailure::Vulkan(error) => submission_error(device, error), - } -} - -/// What a batch of `state`'s parts `parts` whose first work is uploads alone into the buffers -/// of `keys` makes that work visible to (`first_move::Later`): the stages and access types its -/// encoders' uses of those buffers name, joined; every later command where a command of the -/// command buffer may reach memory no use names, it binds a heap's set, its work may write -/// through its residency, an upload names no key (`None`), or the batch's uses name none of one -/// of them. -fn upload_readers( - state: &State, - parts: std::ops::Range, - keys: Option>, -) -> Later { - let Some(keys) = keys else { - return Later::All; - }; - if state.reaches_unnamed || state.heaps.bound() || state.resident_writes.is_some() { - return Later::All; - } - let mut used = Access::NONE; - for key in keys { - let of_key = (state.recorded[parts.clone()].iter()) - .flat_map(|part| part.summary.uses()) - .filter(|used| used.key == key) - .fold(Access::NONE, |all, used| { - all.union(used.read).union(used.write) - }); - if of_key.stages.is_empty() { - return Later::All; - } - used = used.union(of_key); - } - let (stages, access) = used.legacy(); - Later::Batch(stages, access) -} - -/// Whether a test forces first work of uploads alone to take no barrier from the commands before -/// it, the batches not ordered by their ends (`DeviceShared::uploads_unbarriered_forced`). -#[cfg(test)] -fn unbarriered_forced(shared: &crate::device::DeviceShared) -> bool { - (shared.uploads_unbarriered_forced).load(std::sync::atomic::Ordering::Relaxed) -} - -/// No test forces it. -#[cfg(not(test))] -fn unbarriered_forced(_: &crate::device::DeviceShared) -> bool { - false -} - -/// Record a first batch's start into `buffer`, the command buffer of its first work, before that -/// work: the reset of the slot's start and end where the device does not reset it on the host as -/// it is taken, where `barrier` an execution barrier from every command before to every command -/// after, then the start into query `first` of `queries` at the top of the pipe (**GPU times**, -/// the module docs). -/// -/// # Safety -/// -/// `buffer` is recording, outside a render pass, and is submitted first in its batch; the slot is -/// the command buffer's, which no other command buffer writes meanwhile; with no `barrier` only -/// where the end of the batch before it on its `VkQueue` orders every command before it -/// (`first_move::Earlier::Ended`). -unsafe fn record_first_start( - shared: &crate::device::DeviceShared, - buffer: vk::CommandBuffer, - (queries, first): (vk::QueryPool, u32), - barrier: bool, -) { - let raw = shared.vk(); - let all = vk::PipelineStageFlags::ALL_COMMANDS; - // SAFETY: the caller's contract. - unsafe { - if !shared.timing.resets_on_host() { - raw.cmd_reset_query_pool(buffer, queries, first, 2); - exit_guard::called(Call::CmdResetQueryPool); - } - if barrier { - raw.cmd_pipeline_barrier( - buffer, - all, - all, - vk::DependencyFlags::empty(), - &[], - &[], - &[], - ); - exit_guard::called(Call::CmdPipelineBarrier); - } - let top = vk::PipelineStageFlags::TOP_OF_PIPE; - raw.cmd_write_timestamp(buffer, top, queries, first); - exit_guard::called(Call::CmdWriteTimestamp); - } -} - -/// The timestamps a barrier command buffer writes into its command buffer's slot of the device's -/// timestamp pools, each the slot's pool, its first query and the holding's lease -/// (`gpu_time::Slot::lease`): the start (after resetting the slot) before its barriers at the top -/// of the pipe, or with `after` after them at the bottom of the pipe; the end after them. -#[derive(Clone, Copy)] -struct Stamps { - start: Option<(vk::QueryPool, u32, u64)>, - after: bool, - end: Option<(vk::QueryPool, u32, u64)>, -} - -impl Stamps { - /// What a kept command buffer writes for these (`kept_barriers.rs`): `None` where they are - /// none. - fn kept(self) -> Option { - let (queries, first, lease) = self.start.or(self.end)?; - Some(SlotStamps { - queries, - first, - lease, - start: self.start.is_some(), - after: self.after, - end: self.end.is_some(), - }) - } -} - -/// The batches of `VkQueue`s other than `queue` that a batch of `buffer` waiting for `waits` -/// finishes after: for each wait, the batch whose kept GPU signal reaches its value, where that -/// batch's completion turn has not run; and, added to `waited`, the command buffers of other queues -/// those batches end, whose transitions to `Completed` have not run up to their completed handlers -/// (`EventShared::signallers`, `follow.rs`). None, and nothing allocated, for a batch that waits -/// for no event. -fn finishes_after( - waits: &[(Arc, u64)], - (queue, buffer): (usize, &CommandBufferShared), - waited: &mut Vec>, -) -> Vec { - let mut after: Vec = Vec::new(); - for (event, value) in waits { - let (batch, signaller) = event.signallers(*value); - if let Some((other, value)) = batch.filter(|(other, _)| *other != queue) { - let signaller = Waited { - queue: other, - value, - }; - if !after.contains(&signaller) { - after.push(signaller); - } - } - // Of another queue: one of its own queue's is before it in its context. - let other_queue = |signaller: &Arc| signaller.queue() != buffer.queue.id(); - if let Some(signaller) = signaller.filter(other_queue) { - if !waited.iter().any(|known| Arc::ptr_eq(known, &signaller)) { - waited.push(signaller); - } - } - } - after -} - -/// What a batch's encoders (or parts of them) `recorded` were, as the encoder trail names them -/// (`encoder_trail.rs`): each noted one, in order; `None` where none was noted. -fn batch_trail(recorded: &[Recorded]) -> Option { - crate::encoder_trail::Named::joined(recorded.iter().filter_map(|part| part.trail.as_ref())) -} - -/// The images whose first use among `parts` (a batch's, in order) writes every texel before any -/// command reads one, by its encoder's own description (`Recorded::overwrites`), whose first -/// moves' zeros the batch's take leaves out (`FirstMoves::take_holding`): an overwrite by a part -/// with no segment (work recorded later, which may go before its commands), that only blit -/// parts with no segment naming nothing of the image come before (any other encoder's commands -/// may reach a texture through its resource ID, unnamed), and whose own uses read nothing of the -/// image but its attachment's own reads after its load (a pass's; a copy into or out of an image -/// standing in for it, or a shadow's copy, reads it otherwise) or nothing at all (a blit's). Empty, and -/// nothing allocated, where no part has an overwrite. -fn first_overwrites(parts: &[Recorded], ended: &[EncoderRecord]) -> Vec { - if parts.iter().all(|part| part.overwrites.is_empty()) { - return Vec::new(); - } - // An attachment's own reads in its pass, after its load: blending, the depth and stencil - // tests, a fetch through an input attachment. - let attachment_reads = vk::AccessFlags2::COLOR_ATTACHMENT_READ - | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_READ - | vk::AccessFlags2::INPUT_ATTACHMENT_READ; - let mut named = BTreeSet::new(); - let mut overwritten = Vec::new(); - for part in parts { - for overwrite in &part.overwrites { - let reads = (part.summary.uses().iter()) - .filter(|used| used.key == overwrite.key) - .fold(vk::AccessFlags2::NONE, |reads, used| { - reads | used.read.access - }); - let unread = match overwrite.by { - OverwriteBy::Pass => (reads & !attachment_reads).is_empty(), - OverwriteBy::Blit => reads.is_empty(), - }; - if unread && part.segments.is_empty() && !named.contains(&overwrite.key) { - overwritten.push(overwrite.key); - } - } - let blit = (ended.get(part.encoder)).is_some_and(|record| record.kind == EncoderKind::Blit); - if !blit || !part.segments.is_empty() { - break; - } - named.extend(part.summary.keys()); - } - overwritten -} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs b/crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs deleted file mode 100644 index e2c79326d..000000000 --- a/crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs +++ /dev/null @@ -1,352 +0,0 @@ -//! A command buffer's completion as a sync file (a runtime extension: Metal has none): a binary -//! semaphore its last batch signals, exported as `VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT`, -//! which a `VkDevice` of another driver imports and waits for on its own GPU -//! ([`CommandBuffer::add_completion_sync_file`], [`CommandBuffer::export_completion_sync_file`]). -//! -//! - **The signal.** Asked for before the commit, the semaphore (one of the device's idle ones, or -//! a new one: `exported_semaphore.rs`) is signaled by the command buffer's last batch: the -//! commit adds it to the batches as a signal of one of the caller's binary semaphores -//! (`Batches::binary_signal`), after its last encoder and past every point where the commit may -//! still be refused, so it goes into the last batch's end with the queue's timeline value, after -//! the barrier that makes every write available to the host (`submit.rs`). A batch that -//! signals a binary semaphore never waits in a group for one kernel submission (`group.rs`), -//! and a command buffer with one needs a submission even with no GPU work: a submission of the -//! signals alone, after every earlier submission of its `VkQueue`, so it completes in its -//! queue's order. Every host step runs before the batch it records for, so none follows the -//! last batch's submission. -//! - **The export** waits for that submission only, never for the GPU, then exports the payload -//! (`vkGetSemaphoreFdKHR`), which Vulkan allows once the signal operation, and every signal -//! operation it depends on, was submitted (`VUID-VkSemaphoreGetFdInfoKHR-handleType-03254`): -//! every wait of the runtime's batches is for a signal submitted before it, but for a signal the -//! caller reserved (`Event::reserve_vk_signal`), whose submission that call's contract orders -//! before such an export. The export moves the payload out, as a wait would (copy transference), -//! so a command buffer's sync file is exported once. -//! - **Ends the GPU does not see.** A command buffer that finished (`Completed` or `Error`) before -//! its signal was submitted (a failed submission or host step, a lost device, a revoked queue, -//! its GPU hang holding its last batch) or before the export looked answers a sync file already -//! signaled (`None`): it ended. One whose completion writes the caller's pages on the host after -//! its GPU work (a copied host buffer's merge back, `copied.rs`; a two-copy buffer's copy out -//! into pages no import maps, `managed_copy.rs`) cannot be ordered on the GPU: its export waits -//! for its completion on the host and answers `None`, announced -//! (`sync-file-after-host-copies`). -//! - **The semaphore's end.** Its command buffer's completion takes it, every batch that names it -//! completed: back among the device's idle ones where an export moved its payload out and the -//! command buffer completed, so it is unsignaled with nothing pending; else released. A command -//! buffer never committed gives it back as it goes. - -use super::own::{running, scheduled_wait, Answer}; -use super::{CommandBuffer, CommandBufferShared, State}; -use crate::contexts; -use crate::copied::CopiesReached; -use crate::degradation::Degradation; -use crate::device::lock; -use crate::error::{internal, invalid, DeadlockCause, Error, Problem, RuntimeGap, SyncFileProblem}; -use crate::exit_guard; -use crate::managed_copy::AtCompletion; -use crate::release; -use crate::values::CommandBufferStatus; -use ash::vk; -use std::os::fd::OwnedFd; -use std::sync::atomic::Ordering; - -/// A command buffer's completion sync file ([`State::sync_file`]). -pub(super) struct SyncFile { - /// Its binary semaphore, made exportable as a sync file, until its command buffer's - /// completion or release takes it. - semaphore: Option, - /// The commit added its signal to the last batch. - placed: bool, - /// The batch that signals it was submitted. - submitted: bool, - /// An export answered. - taken: bool, - /// An export moved its payload out (`vkGetSemaphoreFdKHR` returned). - exported: bool, -} - -/// Whether the command buffer finished: its transition to `Completed` or `Error` ran. -fn finished(state: &State) -> bool { - matches!( - state.status, - CommandBufferStatus::Completed | CommandBufferStatus::Error - ) -} - -/// Whether an export may answer now: the sync file's signal was submitted, or the command buffer -/// finished. -fn answerable(state: &State) -> bool { - finished(state) || state.sync_file.as_ref().is_some_and(|sync| sync.submitted) -} - -impl State { - /// The commit: the sync file's signal goes into the last batch, where one was asked for. - pub(super) fn place_sync_file(&mut self) { - let Some(sync) = &mut self.sync_file else { - return; - }; - if let (Some(semaphore), false) = (sync.semaphore, sync.placed) { - self.batches.binary_signal(semaphore); - sync.placed = true; - } - } - - /// The command buffer's work ended: its sync file's semaphore, to give back - /// ([`CommandBufferShared::release_sync_file`]), and whether the device may keep it idle. - pub(super) fn take_sync_file(&mut self) -> Option<(vk::Semaphore, bool)> { - let completed = self.status == CommandBufferStatus::Completed; - let sync = self.sync_file.as_mut()?; - let idle = !sync.placed || (completed && sync.exported); - sync.semaphore.take().map(|semaphore| (semaphore, idle)) - } -} - -impl CommandBufferShared { - /// Batch submitted with `signals`: where they hold the sync file's, it was submitted, and an - /// export waiting for that is woken. - pub(super) fn sync_file_submitted(&self, state: &mut State, signals: &[vk::Semaphore]) { - let Some(sync) = &mut state.sync_file else { - return; - }; - if sync - .semaphore - .is_some_and(|semaphore| signals.contains(&semaphore)) - { - sync.submitted = true; - let parked = state.parked > 0; - self.wake_parked(parked); - } - } - - /// Give back the sync file's semaphore `taken` ([`State::take_sync_file`]), nothing pending - /// using it: kept idle by the device where the flag says it may be, else released. Once the - /// process is exiting it is left to its end. - pub(super) fn release_sync_file(&self, taken: Option<(vk::Semaphore, bool)>) { - let Some((semaphore, idle)) = taken else { - return; - }; - let Some(_busy) = exit_guard::enter() else { - return; - }; - let shared = self.device.shared(); - let Some(sync_fd) = &shared.sync_fd_semaphores else { - return; - }; - // SAFETY: the device's semaphore, made by `take`; its command buffer's work ended (or was - // never submitted), so nothing pending uses it; an idle one is unsignaled: never - // signaled, or its payload moved out by an export after its signal completed. - unsafe { - match idle { - true => sync_fd.give(shared.vk(), semaphore), - false => { - release::object(shared.vk(), semaphore); - } - } - } - } - - /// Whether its completion writes the caller's pages on the host after its GPU work: a copy - /// out of a two-copy buffer into pages no import maps, or the merge back of a copied host - /// buffer its commands may have written (`completion.rs`'s `finish`). `writes_unnamed` is - /// its state's. Read once its last batch was submitted, its writes all noted. - fn host_copies_after(&self, writes_unnamed: bool) -> bool { - if lock(&self.at_completion) - .iter() - .any(AtCompletion::writes_pages) - { - return true; - } - let copied = &self.device.shared().copied; - if !copied.any() { - return false; - } - let mut written = CopiesReached::default(); - match self.unnoted.load(Ordering::Relaxed) || writes_unnamed { - true => written.reached_all(), - false => lock(&self.dirty).copies_written(&mut written), - } - copied.merges_back(&written) - } -} - -impl CommandBuffer { - /// No Metal counterpart (a runtime extension): ask for the command buffer's completion as a - /// sync file, which [`export_completion_sync_file`](Self::export_completion_sync_file) hands - /// out once the command buffer is committed. Its last batch then also signals a binary - /// semaphore of the device's, exportable as `VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT` - /// (`VK_KHR_external_semaphore_fd`), which a `VkDevice` of any driver imports: that device's - /// submission waits on its own GPU for this command buffer's work to end, where a wait for - /// [`wait_until_completed`](Self::wait_until_completed) blocks a thread. A second call - /// changes nothing. - /// - /// The signal comes after every command of the command buffer, behind the barrier that makes - /// their writes available to the host, and after every earlier submission of its queue's - /// `VkQueue`. It costs the command buffer a submission where it needs no GPU work, and its last - /// batch never joins a grouped submission (`CompletionPolicy::Grouped`). - /// - /// Refused after the commit (`Invalid`, [`SyncFileProblem::Committed`]), on a lost device - /// (`DeviceLost`), and `NotImplemented` ([`RuntimeGap::SyncFileExport`]) on a device without - /// `VK_KHR_external_semaphore_fd` or that exports no binary semaphore as a sync file: Metal - /// on Apple's GPUs (MoltenVK) among them. The driver's failure to make the semaphore refuses - /// it too. - pub fn add_completion_sync_file(&self) -> Result<(), Error> { - const CALL: &str = "add_completion_sync_file"; - let device = &self.0.device; - let shared = device.shared(); - let Some(sync_fd) = &shared.sync_fd_semaphores else { - return Err(Error::NotImplemented(RuntimeGap::SyncFileExport)); - }; - if device.is_lost() { - return Err(device.lost_refusal()); - } - let mut state = self.state(); - if state.enqueued() { - return Err(invalid(CALL, Problem::SyncFile(SyncFileProblem::Committed))); - } - if state.sync_file.is_some() { - return Ok(()); - } - // SAFETY: the device is live: this command buffer holds it. - let semaphore = unsafe { sync_fd.take(shared.vk()) }?; - state.sync_file = Some(SyncFile { - semaphore: Some(semaphore), - placed: false, - submitted: false, - taken: false, - exported: false, - }); - Ok(()) - } - - /// No Metal counterpart (a runtime extension): the command buffer's completion as a sync - /// file, which [`add_completion_sync_file`](Self::add_completion_sync_file) asked for before - /// the commit: a new descriptor (`vkGetSemaphoreFdKHR`, - /// `VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT`), the caller's to close, which a `VkDevice` - /// of any driver imports (`VK_SEMAPHORE_IMPORT_TEMPORARY_BIT`) and waits for. `None` is a sync - /// file already signaled, which Vulkan imports as the descriptor -1: there is nothing to wait - /// for. - /// - /// It blocks only until the command buffer's last batch, which signals the semaphore, was - /// submitted (as [`wait_until_scheduled`](Self::wait_until_scheduled) blocks, without waiting - /// for the scheduled handlers), never for the GPU's work: after - /// [`commit_and_submit`](Self::commit_and_submit) it answers at once. Its answers: - /// - a descriptor (or the driver's -1, `None`) once the signal was submitted; - /// - `None` where the command buffer finished first, `Completed` or `Error`: a failed - /// submission or host step, a lost device or a revoked queue, which never submit the - /// signal, or a completion before the export looked; - /// - `None` once the command buffer completed, where its completion writes the caller's pages - /// on the host after its GPU work, which no GPU wait orders: the merge back of a copied host - /// buffer its commands may have written, or a two-copy buffer's copy out into pages no - /// import maps. That export blocks until the completion, announced - /// ([`Degradation::SyncFileAfterHostCopies`]). - /// - /// The importer orders after its wait only what its own memory access makes visible: the - /// command buffer's writes are available to the host as its work ends. On a device loss the - /// command buffer fails; what an importer's wait for a descriptor handed out before does - /// then is its driver's. - /// - /// Refused for a command buffer no `add_completion_sync_file` asked for (`Invalid`, - /// `Problem::NotExportable`); before its commit ([`SyncFileProblem::NotCommitted`]); after an - /// export answered ([`SyncFileProblem::Exported`]: one export per command buffer, as the - /// export moves the payload out; duplicate the descriptor instead); where its wait would - /// deadlock, as `wait_until_scheduled`'s (`WaitWouldDeadlock`), or the host copies' wait for - /// the completion, as `wait_until_completed`'s; and for the driver's failure. - pub fn export_completion_sync_file(&self) -> Result, Error> { - const CALL: &str = "export_completion_sync_file"; - let ready = { - let state = self.state(); - match &state.sync_file { - None => return Err(invalid(CALL, Problem::NotExportable)), - Some(sync) if sync.taken => { - return Err(invalid(CALL, Problem::SyncFile(SyncFileProblem::Exported))) - } - Some(_) => {} - } - if !state.enqueued() { - return Err(invalid( - CALL, - Problem::SyncFile(SyncFileProblem::NotCommitted), - )); - } - answerable(&state) - }; - if !ready { - self.wait_for_sync_file()?; - } - let (done, writes_unnamed) = { - let state = self.state(); - (finished(&state), state.writes_unnamed) - }; - let device = &self.0.device; - let shared = device.shared(); - if !done && self.0.host_copies_after(writes_unnamed) { - device.degrade(Degradation::SyncFileAfterHostCopies, || { - ( - "a command buffer's completion sync file".to_owned(), - "its completion writes the caller's pages on the host after its GPU work \ - (a copied host buffer's merge back, or a two-copy buffer's copy out into \ - pages no import maps), which no GPU wait orders" - .to_owned(), - ) - }); - self.wait_until_completed()?; - let mut state = self.state(); - let Some(sync) = state.sync_file.as_mut().filter(|sync| !sync.taken) else { - return Err(invalid(CALL, Problem::SyncFile(SyncFileProblem::Exported))); - }; - sync.taken = true; - shared.counts.sync_file_after_host_copies(); - return Ok(None); - } - let mut state = self.state(); - let done = finished(&state); - let Some(sync) = state.sync_file.as_mut().filter(|sync| !sync.taken) else { - return Err(invalid(CALL, Problem::SyncFile(SyncFileProblem::Exported))); - }; - let semaphore = match (done, sync.semaphore) { - (false, Some(semaphore)) => semaphore, - _ => { - sync.taken = true; - return Ok(None); - } - }; - // A sync file was asked for on this device, which so exports one. - let sync_fd = (shared.sync_fd_semaphores.as_ref()) - .ok_or_else(|| internal("a sync file asked for on a device that exports none"))?; - // SAFETY: the semaphore lives until the command buffer's completion takes it, under the - // state's lock this export holds, and the command buffer has not finished; its signal was - // submitted, and so was every signal its batch waits for (the module docs); nothing waits - // for it. - let file = unsafe { sync_fd.export(semaphore) }?; - sync.taken = true; - sync.exported = true; - shared.counts.sync_file_exported(); - Ok(file) - } - - /// Block until the sync file's signal was submitted or the command buffer finished, as - /// [`wait_until_scheduled`](Self::wait_until_scheduled) blocks. - fn wait_for_sync_file(&self) -> Result<(), Error> { - let _blocked = match scheduled_wait(running(), self.0.target(), false) { - Answer::Refuse(cause) => return Err(cause.into()), - Answer::Return | Answer::Wait => None, - Answer::Block(from) => Some(contexts::block(from, self.0.context())?), - }; - self.settle_commit(); - self.0.waits_for_scheduling(); - let mut state = self.state(); - while !answerable(&state) { - if exit_guard::closed() { - return Err(DeadlockCause::Exiting.into()); - } - state.parked += 1; - state = self - .0 - .changed - .wait_timeout(state, exit_guard::WAKE) - .unwrap_or_else(std::sync::PoisonError::into_inner) - .0; - state.parked -= 1; - } - Ok(()) - } -} diff --git a/crates/metal2vulkan-runtime/src/commit_times.rs b/crates/metal2vulkan-runtime/src/commit_times.rs deleted file mode 100644 index 1ce3ba2ce..000000000 --- a/crates/metal2vulkan-runtime/src/commit_times.rs +++ /dev/null @@ -1,140 +0,0 @@ -//! What a program's commit calls spend, phase by phase (`WorkCounts::commit_nanos` and kin): the -//! time a call of `CommandBuffer::commit`, `commit_and_submit` or `commit_failed` holds the -//! program's thread, and how much of it each phase took. Not part of the API. -//! -//! - **One clock a call.** Each such call runs under a [`CommitClock`], this thread's while it -//! lasts: its whole time, and each phase's own time as the call enters it ([`phase`]). Each -//! phase is timed apart from the phases inside it: a phase entered inside another pauses that -//! one until it ends, so the phases' times never overlap and sum to at most the call's. A -//! commit inside a call (a submission handler's) runs under a clock of its own, its whole time -//! counted in the phase of the outer call that ran it. -//! - **Nowhere else.** Outside such a call (the scheduler's thread, the lowering thread, a thread -//! that waits) a phase costs one read of this thread's clock and is timed by nothing, so the -//! paths it marks pay nothing more. A call pays two `Instant` reads for itself and two for each -//! phase it enters: none per draw or per command. - -use std::cell::Cell; -use std::time::{Duration, Instant}; - -use crate::device::Device; - -/// A phase of a commit call, in [`Times`]'s order (`WorkCounts::commit_lowering_nanos` and kin). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Phase { - /// The encoders' calls left to the device's lowering thread, lowered on this one. - Lowering, - /// The work its encoders left to the commit, recorded or settled for its host steps. - Recording, - /// That recording's waits for its draws' pipelines being made. - PipelineWait, - /// Taking the scheduler's lock for the pass at commit. - LockWait, - /// That pass, but its submissions. - Pass, - /// Its submissions, with the submission checks and handlers it runs. - Submit, -} - -/// How many phases there are. -const PHASES: usize = 6; - -impl Phase { - /// Its place in [`Times`]. - fn at(self) -> usize { - match self { - Phase::Lowering => 0, - Phase::Recording => 1, - Phase::PipelineWait => 2, - Phase::LockWait => 3, - Phase::Pass => 4, - Phase::Submit => 5, - } - } -} - -/// Nanoseconds a call spent in each phase, by [`Phase`]'s place. -pub(crate) type Times = [u64; PHASES]; - -/// A call's clock: its phases' times so far, and the phase it is in, since when. -#[derive(Clone, Copy)] -struct Clock { - times: Times, - current: Option<(Phase, Instant)>, -} - -impl Clock { - /// `phase` took `spent` more. - fn add(&mut self, phase: Phase, spent: Duration) { - self.times[phase.at()] += nanos(spent); - } -} - -thread_local! { - /// The clock of the commit call this thread runs, where it runs one. - static CLOCK: Cell> = const { Cell::new(None) }; -} - -/// `spent` in nanoseconds, saturated. -fn nanos(spent: Duration) -> u64 { - u64::try_from(spent.as_nanos()).unwrap_or(u64::MAX) -} - -/// A commit call's clock on this thread, from its making until it goes, which counts the call -/// and its phases' times in its device's work counts (the module docs). -pub(crate) struct CommitClock<'a> { - device: &'a Device, - started: Instant, - /// The clock of the call this one runs inside, where it does, which it puts back. - outer: Option, -} - -impl CommitClock<'_> { - /// A commit call of `device`'s starts now on this thread. - pub(crate) fn start(device: &Device) -> CommitClock<'_> { - let fresh = Clock { - times: [0; PHASES], - current: None, - }; - let outer = CLOCK.replace(Some(fresh)); - CommitClock { - device, - started: Instant::now(), - outer, - } - } -} - -impl Drop for CommitClock<'_> { - /// The call returns: counted, with its phases' times, and the outer call's clock back. - fn drop(&mut self) { - let whole = nanos(self.started.elapsed()); - let clock = CLOCK.replace(self.outer.take()); - let times = clock.map_or([0; PHASES], |clock| clock.times); - self.device.shared().counts.commit_timed(whole, ×); - } -} - -/// Run `run`, the commit call's `phase`, timed apart from the phase it runs inside, which it -/// pauses meanwhile; timed by nothing outside a commit call (the module docs). -pub(crate) fn phase(phase: Phase, run: impl FnOnce() -> R) -> R { - let Some(mut clock) = CLOCK.get() else { - return run(); - }; - let now = Instant::now(); - let outer = clock.current.replace((phase, now)); - if let Some((was, since)) = outer { - clock.add(was, now - since); - } - CLOCK.set(Some(clock)); - let ran = run(); - let end = Instant::now(); - // The clock as `run` left it: its phases inside added, `phase` current again. - if let Some(mut clock) = CLOCK.get() { - if let Some((was, since)) = clock.current { - clock.add(was, end - since); - } - clock.current = outer.map(|(was, _)| (was, end)); - CLOCK.set(Some(clock)); - } - ran -} diff --git a/crates/metal2vulkan-runtime/src/compressed_blit.rs b/crates/metal2vulkan-runtime/src/compressed_blit.rs deleted file mode 100644 index 520e47f2f..000000000 --- a/crates/metal2vulkan-runtime/src/compressed_blit.rs +++ /dev/null @@ -1,286 +0,0 @@ -//! Blits through a texture Metal keeps losslessly compressed. -//! -//! **Metal's answers** (an Apple M4 under macOS 27.0.1, plain; random bytes through every blit -//! direction, every level, slice and texture type, heap textures and views; the package share-cblit -//! on an Apple M3 Max under 26.7 and the M3 Max under 27.0.1 alike). Metal keeps a texture -//! losslessly compressed where `texture/heap_tiled.rs`'s rule holds (`metal_compresses`: -//! `allowGPUOptimizedContents`, the shorter side of level 0 16 texels or more, a colour format of -//! neither `ShaderWrite` nor `PixelFormatView` usage). A GPU blit that reads or writes such a -//! texture (a buffer into it, it into a buffer, a texture into another either way) moves its texels -//! through the compression, which writes three families' texels in their canonical encoding, the -//! same value: `BGRA10_XR` (and its `_sRGB` twin) each 16-bit field's low six bits cleared and the -//! alpha code clamped to `[384, 894]`, `RG11B10Float` a NaN field made the quiet NaN, `RGB9E5Float` -//! the shared exponent lowered to the least that holds the texel's value. The 70 other formats the -//! census tried keep their bytes, and so do a texture over a buffer or of an IOSurface and CPU -//! copies (`replace_region`, `get_bytes`) of any texture. -//! -//! **On a device that presents a Mac keeping no texture compressed** -//! (`Device::metal_compresses_textures`), as a Mac with an Intel or AMD GPU is, no texture is one -//! of these: Metal's own uncompressed texture keeps the bytes through every blit, so the device's -//! copy is Metal's answer there, and no blit or fill announces a note or, under -//! `ExtendedRangeBlitPolicy::Canonical`, rewrites a texel. That answer is expected, not measured: -//! no Intel or AMD Mac's blits were probed. The usage the runtime gives an image MoltenVK copies -//! ([`Device::copy_exact_usage`]) follows the host's own Metal, not the Mac the device presents, -//! and stays. -//! -//! Metal's fill (`fillTexture:...`, Apple SPI) of such a `BGRA10_XR` texture clears each field's -//! low six bits and leaves the alpha code as the texel gives it (the M3 Max under 27.0.1: the -//! patterns `0x0123456789abcdef` and all ones keep alpha codes 4 and 1023); a colour fill's texel -//! is the same either way. -//! -//! **The runtime's answer** is the device's copy, which keeps the bytes it read: the canonical -//! encoding is Metal's compressor's, not the format's (Metal's own uncompressed texture of the -//! format keeps the bytes through the same blit), and a texel whose bytes no Metal write left -//! (uploaded or copied bytes) reads the same value either way: alpha reads clamped and the low six -//! bits unread for `BGRA10_XR`, a NaN for `RG11B10Float`, the value for `RGB9E5Float`. A blit through -//! such a texture announces the note of its format ([`kept_encoding`]: `extended-range-bits-kept`, -//! `device-nan-encoding`, `shared-exponent-kept`), once per device, except where the device's own -//! copy is Metal's blit of a compressed image ([`copy_rewrites`]). -//! -//! **Under `ExtendedRangeBlitPolicy::Canonical`** (`DevicePolicy::extended_range_blits`, which -//! `exact_answers()` selects) a `BGRA10_XR` texture's blits and fills write Metal's encoding -//! ([`canonical`], `extended_canonical.rs`): a fill's texel is encoded before the fill writes it -//! ([`canonical_fill_unit`]); after a blit into such a texture, or out of one into another texture -//! of the format whose texels are an image, a dispatch rewrites the region the blit wrote in a -//! scratch copy of it; after a blit out of one into a buffer, or into a texture over a buffer's -//! bytes, a dispatch rewrites the words the blit wrote in place. A blit out of one into a buffer -//! whose words the device cannot bind there, or into a texture over a buffer whose rows share -//! bytes (an IOSurface plane's), keeps the bytes and announces the note as before. -//! -//! **MoltenVK** (`RuntimeDriverDefect::CompressedImageCopiesRewriteTexels`): its copies of an -//! image are Metal's blits, so a copy of a compressed `RG11B10Float` or `RGB9E5Float` image writes -//! the canonical encoding. A CPU copy, which the runtime makes a Vulkan copy, would make it too, so -//! the image of a `Shared` or `Managed` texture that Metal compresses is made uncompressed there -//! (`PixelFormatView` usage, [`Device::copy_exact_usage`]), and so is a device's own texture's -//! without `allowGPUOptimizedContents`, whose blits Metal makes on an uncompressed texture: its -//! image of the texture's own usage would be compressed (a heap's texture still takes the -//! compressed image's bytes of the heap). - -use super::error::Error; -use super::texture::heap_tiled::metal_compresses; -use super::texture::Texture; -use super::texture_descriptor::{TextureDescriptor, TextureLayout}; -use super::values::StorageMode; -use super::{Degradation, Device}; -use metal2vulkan::device::ExtendedRangeBlitPolicy; -use metal2vulkan::error::RuntimeDriverDefect; -use metal2vulkan::metal::format::is_depth_stencil; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; -use metal2vulkan::vk::{Format, ImageCreateFlags, ImageUsageFlags}; - -/// The note a blit through a compressed texture of `pf` announces, whose texels Metal's -/// compression writes in their canonical encoding (the module docs); `None` for a format whose -/// blits keep their bytes on Metal too. -fn kept_encoding(pf: PixelFormat) -> Option { - match pf { - PixelFormat::BGRA10XR | PixelFormat::BGRA10XRSRGB => { - Some(Degradation::ExtendedRangeBitsKept) - } - PixelFormat::RG11B10Float => Some(Degradation::DeviceNanEncoding), - PixelFormat::RGB9E5Float => Some(Degradation::SharedExponentKept), - _ => None, - } -} - -/// Whether Metal keeps a texture of `pixel_format` losslessly compressed and its blits rewrite -/// its texels ([`kept_encoding`]): a texture (a view's first) of `texture_type`, its level 0 -/// `width` by `height`, of `samples` samples and the `(usage, allowGPUOptimizedContents)` of -/// `optimized`. -fn rewritten( - pixel_format: PixelFormat, - texture_type: TextureType, - [width, height]: [u64; 2], - samples: u64, - (usage, allow_gpu_optimized_contents): (TextureUsage, bool), -) -> bool { - let one_row = matches!(texture_type, TextureType::Type1D | TextureType::Type1DArray); - let level0 = [width, if one_row { 1 } else { height }]; - let colour = !is_depth_stencil(pixel_format); - samples == 1 - && kept_encoding(pixel_format).is_some() - && metal_compresses(colour, usage, allow_gpu_optimized_contents, level0) -} - -/// What wrote a texture's texels through a buffer: a blit's copy, or a fill's rows of its texel -/// (`blit_fill.rs`), whose encodings Metal's compression writes otherwise (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Writer { - /// A blit's copy. - Blit, - /// A fill's rows of its texel. - Fill, -} - -/// Whether Metal keeps `texture` losslessly compressed and its blits rewrite its texels (the -/// module docs): on a device that presents an Apple silicon Mac's compression -/// (`Device::metal_compresses_textures`), not a texture over a buffer, its root's type, level 0, -/// usage and `allowGPUOptimizedContents` and its own samples ([`rewritten`]). -fn compressed(texture: &Texture) -> bool { - if texture.over_buffer() || !texture.generation().metal_compresses_textures() { - return false; - } - let mut root = texture; - while let Some(parent) = root.parent_texture() { - root = parent; - } - rewritten( - texture.pixel_format(), - root.texture_type(), - [root.width(), root.height()], - texture.sample_count(), - (root.usage(), root.allow_gpu_optimized_contents()), - ) -} - -/// Whether `texture`'s format is `BGRA10_XR` or its sRGB twin, whose canonical encoding the -/// runtime writes ([`canonical`]). -pub(super) fn extended(pixel_format: PixelFormat) -> bool { - matches!( - pixel_format, - PixelFormat::BGRA10XR | PixelFormat::BGRA10XRSRGB - ) -} - -/// Whether a blit or fill through `texture` writes Metal's canonical encoding of its texels: the -/// device's policy asks for it (`ExtendedRangeBlitPolicy::Canonical`), and `texture` is a -/// `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (the module docs). -pub(super) fn canonical(texture: &Texture) -> bool { - let policy = texture.generation().compile_device().policy(); - policy.extended_range_blits == ExtendedRangeBlitPolicy::Canonical - && extended(texture.pixel_format()) - && compressed(texture) -} - -/// Whether `texture` holds its texels in an image of a `BGRA10_XR` format of one sample, which -/// the canonical encoding's dispatch rewrites through a scratch copy (`extended_canonical.rs`). -pub(super) fn holds_canonical(texture: &Texture) -> bool { - !texture.over_buffer() && extended(texture.pixel_format()) && texture.sample_count() == 1 -} - -/// `unit`, a fill's texel of a `BGRA10_XR` texture, as Metal's fill through its compression -/// writes it: each 16-bit field's low six bits cleared, the alpha code as it is (the module -/// docs). -pub(super) fn canonical_fill_unit(unit: &mut [u8]) { - for field in unit.as_chunks_mut::<2>().0 { - let code = u16::from_le_bytes(*field) & 0xFFC0; - *field = code.to_le_bytes(); - } -} - -/// Announce, for a fill through `texture` whose texel the device writes as it is, the note of a -/// `BGRA10_XR` texture Metal keeps losslessly compressed, whose fill clears each field's low six -/// bits (the module docs); nothing where the fill wrote Metal's encoding ([`canonical`]). -pub(super) fn degrade_compressed_fill(texture: &Texture) { - if !extended(texture.pixel_format()) || !compressed(texture) || canonical(texture) { - return; - } - let pf = texture.pixel_format(); - texture - .generation() - .degrade(Degradation::ExtendedRangeBitsKept, || { - ( - format!("a fill of a {pf:?} texture Metal keeps losslessly compressed"), - "the device's fill keeps the texel's bytes, where Metal's fill through its \ - compression clears each field's low six bits: the same value in another \ - encoding" - .to_owned(), - ) - }); -} - -/// Whether a driver of `RuntimeDriverDefect::CompressedImageCopiesRewriteTexels` rewrites texels -/// in its copies of a compressed image of `format`: the Vulkan formats MoltenVK makes Metal's -/// `RG11B10Float` and `RGB9E5Float` textures of. `BGRA10_XR`'s images are of a format whose -/// copies keep their bytes. -fn copies_rewrite(format: Format) -> bool { - matches!( - format, - Format::B10G11R11_UFLOAT_PACK32 | Format::E5B9G9R9_UFLOAT_PACK32 - ) -} - -/// Whether `texture`'s own copies write Metal's canonical encoding: on a driver whose copies of a -/// compressed image rewrite texels, an image of such a format that Metal keeps compressed (neither -/// `STORAGE` usage nor `MUTABLE_FORMAT`). -fn copy_rewrites(texture: &Texture) -> Result { - let defects = &texture.generation().properties().driver_defects; - if !defects.contains(&RuntimeDriverDefect::CompressedImageCopiesRewriteTexels) { - return Ok(false); - } - let plan = texture.image_plan()?; - Ok(copies_rewrite(plan.format) - && !plan.usage.contains(ImageUsageFlags::STORAGE) - && !plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT)) -} - -/// Announce, for a blit (`call`) that reads or writes `texture`, the note of its format's -/// canonical encoding where Metal keeps the texture losslessly compressed and the device's copy -/// keeps the bytes (the module docs). -pub(super) fn degrade_compressed_blit(call: &'static str, texture: &Texture) -> Result<(), Error> { - let pf = texture.pixel_format(); - let Some(kind) = kept_encoding(pf).filter(|_| compressed(texture)) else { - return Ok(()); - }; - if copy_rewrites(texture)? { - return Ok(()); - } - let what = match kind { - Degradation::ExtendedRangeBitsKept => { - "clears each field's low six bits and clamps the alpha code to [384, 894]" - } - Degradation::DeviceNanEncoding => "makes a NaN field the quiet NaN", - _ => "lowers the shared exponent to the least that holds the texel's value", - }; - texture.generation().degrade(kind, || { - ( - format!("{call} through a {pf:?} texture Metal keeps losslessly compressed"), - format!( - "the device's copy keeps the texels' bytes, where Metal's blit through its \ - compression {what}: the same value in another encoding" - ), - ) - }); - Ok(()) -} - -impl Device { - /// `usage`, the usage of the image of `format` of a texture of `descriptor` (checked as - /// `layout`), with `PixelFormatView` where this device's copies of the image would rewrite - /// texels Metal keeps (`RuntimeDriverDefect::CompressedImageCopiesRewriteTexels`): an image - /// of a format whose copies rewrite, which the device's Metal keeps compressed (an image of - /// `usage` with GPU-optimized contents, [`rewritten`]), of a texture whose bytes Metal keeps - /// through such a copy: a `Shared` or `Managed` texture, which CPU copies read and write, or - /// one without `allowGPUOptimizedContents`, which Metal keeps uncompressed, so that its GPU - /// blits keep the bytes too. Metal keeps an image of that usage uncompressed (MoltenVK makes a - /// `PixelFormatView` Metal texture of a `MUTABLE_FORMAT` image with no list of formats), so its - /// copies keep the bytes. `None` elsewhere: a `Private` texture with GPU-optimized contents, - /// whose bytes no CPU copy reads or writes, keeps the compression. - pub(super) fn copy_exact_usage( - &self, - descriptor: &TextureDescriptor, - layout: &TextureLayout, - format: Format, - usage: TextureUsage, - ) -> Option { - let properties = self.properties(); - let defect = RuntimeDriverDefect::CompressedImageCopiesRewriteTexels; - let reachable = matches!( - descriptor.resource_options.storage_mode(), - Ok(StorageMode::Shared | StorageMode::Managed) - ); - let [width, height, _] = layout.extent; - let compressed = rewritten( - layout.pixel_format, - layout.texture_type, - [u64::from(width), u64::from(height)], - u64::from(layout.samples), - (usage, true), - ); - let kept = reachable || !descriptor.allow_gpu_optimized_contents; - let rewrites = properties.driver_defects.contains(&defect) - && kept - && copies_rewrite(format) - && compressed; - rewrites.then_some(usage | TextureUsage::PIXEL_FORMAT_VIEW) - } -} diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs deleted file mode 100644 index eba003db4..000000000 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ /dev/null @@ -1,3469 +0,0 @@ -//! `ComputeCommandEncoder` (`MTLComputeCommandEncoder`). -//! -//! The encoder keeps Metal's argument tables (the pipeline state, buffers with their offsets, -//! threadgroup memory lengths) and the stage-in region, and records each dispatch when it is -//! encoded: -//! -//! 1. Metal's checks: a pipeline state is set (plain Metal faults at a dispatch without one). -//! Where plain Metal gives a measured answer its API validation asserts at, the encoder gives -//! it (an M4): a threadgroup whose size, the axes' wrapping 64-bit product, is 0 or above the -//! state's `max_total_threads_per_threadgroup`, or whose axes modulo `2^32` hold other threads -//! than that size, runs nothing, and a later dispatch runs; grid, threadgroup count and stage-in -//! region axes past 32 bits are taken modulo `2^32`, and so is a per-bind attribute stride; a -//! threadgroup memory length that is not a multiple of 16 is taken (the binder rounds every -//! length up to 16, as Metal does). `set_imageblock_size` is checked where Metal checks it, at -//! the call. -//! 2. The tables become a `bind::BindState`, brought in place from the one the encoder's last -//! dispatch of the same pipeline state bound, where the encoder set it aside, else from its -//! last dispatch's (`compute/live.rs`); the pipeline state's kept plans give the plan of its -//! shape, on the variant the dispatch runs on (compiled when first needed), and -//! `instantiate_dispatch` the command's regions, bytes, and push holes. -//! 3. [`binding`] gives the descriptors, uploads, and push bytes (an encoder's own dispatch -//! through the views, sampler descriptions and host pages its binds kept, -//! `binding::BindMemo`); the variant gives set 0 and one `VkPipeline` per region -//! specialization, and the command buffer set 1, the heap, which its dispatches on the variant -//! share ([`heap_sets`]). -//! 4. Only then is anything recorded, through the tracker's per-command entry -//! ([`EncoderCore::command`]) with the buffers the dispatch reads and writes: a serial encoder -//! is an ordered one, so a dispatch gets the barrier its uses need after the encoder's earlier -//! dispatches (tracked buffers per resource and range, untracked memory as one class); a -//! concurrent encoder leaves that order to the program's memory barriers. Then each region, with -//! a barrier between regions (which only adds an ordering Metal's one dispatch allows). A -//! refused dispatch records nothing and changes nothing. -//! -//! The command buffer retains what the dispatch uses (buffers, textures, sampler states and -//! their Vulkan samplers, pipeline objects, descriptor pool) until it completes, and what -//! `use_resource(s)` and `use_heap(s)` made resident (`residency`): every -//! later dispatch's resident set holds those buffers and heaps' ranges, and its handle tables and -//! heap those textures, each at the element of its resource ID (`HeapPlacement::ResourceId`), -//! with every live sampler state. `set_bytes` copies its bytes into the command buffer's upload -//! arena at the call (`upload.rs`), and every later dispatch binds that copy at the index until -//! the index is bound again. -//! -//! An indirect dispatch (`dispatch_threadgroups_indirect`, `dispatch_threads_indirect`) is -//! checked as Metal checks it when it is encoded. A kernel that does not observe its threadgroup -//! partition, on a device with device addresses, runs on its flat variant there, behind a -//! preprocess that reads the arguments on the device; any other kernel's threadgroup dispatch runs -//! there on its folded variant of the call's threadgroup size, behind the same preprocess; any -//! other dispatch's arguments are copied there, and a host step records it as the direct dispatch -//! they state once the work before it completed (`indirect_dispatch`). -//! -//! A dispatch of an inert kernel (`ComputePipelineState::inert`: its module holds no loop and -//! writes nothing but its invocations' own and its threadgroups' memory) records no Vulkan -//! dispatch, direct, indirect or an indirect command buffer's alike (`record`): nothing it does -//! outlasts it, so nothing later reads it, and the runtime samples no counter that would count its -//! threads (`RuntimeGap::CounterSampleBuffers`). Everything else of a dispatch's steps 1 to 3 -//! stays: it is checked and planned as any, and the command buffer uses what it binds, as Metal's -//! does (`EncoderCore::name_uses`). Its uses are named, so the commit copies in the ranges -//! `did_modify_range` noted of the `Managed` buffers it binds and its batch makes their fills and -//! first work, where a program that dispatches an empty kernel over its buffers to upload them -//! ahead of its timed work wants them; and a detached or rebound buffer among them fails the -//! command buffer. Its uses take no hazard tracking and note no write. The encoder's barriers, -//! fences and the command buffer's events and completion stay as they are -//! (`WorkCounts::dispatches_skipped_inert`). - -use super::address_map::{self, SamplerMaps}; -use super::argument_table::{check_index, ArgumentTable, Stamp}; -use super::binding; -use super::buffer::Buffer; -use super::command_buffer::CommandBuffer; -use super::deferred::Deferred; -use super::degradation::{BoundFormats, CompiledPipeline, Degradation}; -use super::device::Device; -use super::encoder::{EncoderCore, Replayed}; -use super::encoder_fold::Joining; -use super::error::{internal, invalid, Error, IndirectRule, Problem, RuntimeGap}; -use super::execution::{ExecutedPipeline, Execution}; -use super::fetch_reach; -use super::function_table::VisibleFunctionTable; -use super::heap::Heap; -use super::heap_sets; -use super::indirect_command_buffer::{ - IndirectCommandBuffer, IndirectCommandCheck, IndirectCommandCheckNeeds, -}; -use super::indirect_dispatch::{ - self, ArgumentDispatch, Arguments, FlatCall, FlatPreprocess, HostDispatch, - STAGE_IN_REGION_BYTES, -}; -use super::indirect_execute::{self, Execute, ExecutionRange}; -use super::live_bind::ValueKinds; -use super::pending_dispatch::{PendingDispatch, Recording}; -use super::pipeline::{ - flat_dispatch, BufferForms, ComputePipelineState, Direct, GridClass, Planned, RawPipeline, - RegionKey, RegionPipeline, Variant, VariantObjects, -}; -use super::predication::{self, Captures, Event}; -use super::pvrtc::degrade_unreadable; -use super::replay::{CallLog, ComputeCall, Replay, Resource, SamplersWithLodClamps}; -use super::residency::Residency; -use super::resource::ResourceRef; -use super::sampler::{ArgumentSamplers, SamplerState}; -use super::shadow; -use super::texture::Texture; -use super::used_resources::EncoderKind; -use super::values::{Region, Size}; -use ash::vk; -use metal2vulkan::bind::{ - BindShape, BindState, BindingPlan, Dispatch, DispatchCommands, FlatIndirect, HeapPlacement, - ImageblockSize, StageInRegion, UseTarget, -}; -use metal2vulkan::error::{BindError, RuntimeDriverDefect}; -use metal2vulkan::metal::{BarrierScope, DispatchType, RenderStages, ResourceUsage}; -use metal2vulkan::pipeline::Stage; -use std::borrow::Cow; -use std::cell::Cell; -use std::collections::BTreeMap; -use std::ops::Range; -use std::sync::atomic::AtomicU64; -use std::sync::{Arc, Mutex, OnceLock, Weak}; - -mod live; - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) use live::SET_ASIDE_BYTES; -use live::{Across, LiveDispatch}; -pub(crate) use live::{Parked, Parking, SpareLiveDispatches}; - -/// Entries of a compute encoder's threadgroup memory table. -pub(super) const THREADGROUP_SLOTS: u32 = 31; - -/// The most cells `setImageblockWidth:height:` takes (Metal's API validation on an M3 and an M4). -const MAX_IMAGEBLOCK_CELLS: u64 = 1024; - -/// The longest side plain Metal's answer to `setImageblockWidth:height:` is measured at: Metal may -/// keep fewer bits of a longer one. -const MAX_MEASURED_IMAGEBLOCK_SIDE: u64 = 65536; - -/// The imageblock size Metal's API validation takes, the same on an M3 and an M4 and whatever the -/// pipeline: a width and a height that are powers of two (0 excluded), of at most -/// [`MAX_IMAGEBLOCK_CELLS`] cells; the rest refused. An indirect command's size is held to it, -/// plain Metal's answer there being unmeasured. -pub(super) fn validated_imageblock_size( - width: u64, - height: u64, -) -> Result { - let refused = Problem::ImageblockSize { width, height }; - if !width.is_power_of_two() || !height.is_power_of_two() { - return Err(refused); - } - match (u32::try_from(width), u32::try_from(height)) { - (Ok(w), Ok(h)) if width.saturating_mul(height) <= MAX_IMAGEBLOCK_CELLS => { - Ok(ImageblockSize::new(w, h)) - } - _ => Err(refused), - } -} - -/// The imageblock size `setImageblockWidth:height:` sets on a compute encoder, as plain Metal sets -/// it where its API validation asserts (the M3 Max and the M4 alike): a side of 0 makes it 1 by 1; -/// else each side is rounded up to a power of two, and a size of more than [`MAX_IMAGEBLOCK_CELLS`] -/// cells in one row or one column is 1 by 1. Refused, as validation refuses it: more than -/// [`MAX_IMAGEBLOCK_CELLS`] cells over more rows and columns (Metal reads 1024 by 1 there, its -/// cells reading 0), and a side past [`MAX_MEASURED_IMAGEBLOCK_SIDE`]. -pub(super) fn imageblock_size(width: u64, height: u64) -> Result { - if width == 0 || height == 0 { - return Ok(ImageblockSize::new(1, 1)); - } - if width.max(height) > MAX_MEASURED_IMAGEBLOCK_SIDE { - return Err(Problem::ImageblockSize { width, height }); - } - let (w, h) = (width.next_power_of_two(), height.next_power_of_two()); - if w * h > MAX_IMAGEBLOCK_CELLS && (w == 1 || h == 1) { - return Ok(ImageblockSize::new(1, 1)); - } - validated_imageblock_size(w, h).map_err(|_| Problem::ImageblockSize { width, height }) -} - -/// A compute encoder (`MTLComputeCommandEncoder`): `Send`, not `Sync`; `end_encoding` consumes -/// it. Each object a call binds is held until its command buffer completes (or, never committed, -/// is released), as Metal holds what an encoder was handed: one a later call replaced or unbound -/// before any dispatch used it, and one bound after the last dispatch, too. -pub struct ComputeCommandEncoder { - /// Its state, in a box of its own: the encoder moves, from its open to its end, as a pointer - /// to it (`tests::encoder_moves`). - body: Box, -} - -/// A compute encoder's state, which the encoder holds in a box ([`ComputeCommandEncoder`]). -struct Body { - /// In a box of its own (`EncoderCore::boxed`), which its end empties and gives the device back - /// for the next encoder (`encoder::SpareCores`): the core goes from its open to its end as a - /// pointer to it. - core: Box, - dispatch_type: DispatchType, - pipeline: Option, - table: ArgumentTable, - threadgroup_lengths: BTreeMap, - /// `setImageblockWidth:height:`'s size, 1 by 1 until set: what a kernel of Metal's reads - /// when no size was set. - imageblock: ImageblockSize, - /// `setStageInRegion:`'s region, which a kernel with `[[stage_in]]` reads. - stage_in_region: Option, - /// `setStageInRegionWithIndirectBuffer:indirectBufferOffset:`'s buffer and offset, in place - /// of `stage_in_region` until the next `setStageInRegion:`. - indirect_stage_in: Option<(Buffer, u64)>, - residency: Residency, - /// The bodies of the predicated loops it opened and has not closed (`predication.rs`). - captures: Captures, - /// Its calls so far (`replay.rs`): `None` where it logs no longer. - log: Option>, - /// Its dispatches encoded so far: the next one's order among them, which one whose - /// pipelines are being made keeps for its failure (`FailedPipeline::draw`). - dispatches: usize, - /// Its bind state as its last dispatch that settled bound it, with what that one settled - /// (`compute/live.rs`, [`DispatchMemo`]): in the box the device's spares hand on from one - /// encoder to the next (`SpareLiveDispatches`). - live: Box, - /// The residency's generation as a command last noted the heaps of what it made resident - /// (`command_encoded`): no command notes them again before it changes. - heaps_noted: Option, -} - -/// The state of a compute encoder a command ran with, which a predicated loop's copies replay it -/// with (`predication.rs`): what its setters set. What it made resident is not part of it: a -/// copy runs with what the encoder made resident by the loop's end. -#[derive(Clone)] -pub(super) struct EncoderState { - pipeline: Option, - table: ArgumentTable, - threadgroup_lengths: BTreeMap, - imageblock: ImageblockSize, - stage_in_region: Option, - indirect_stage_in: Option<(Buffer, u64)>, -} - -impl std::fmt::Debug for ComputeCommandEncoder { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ComputeCommandEncoder") - .field("dispatch_type", &self.body.dispatch_type) - .finish() - } -} - -impl CommandBuffer { - /// `computeCommandEncoder`: a serial compute encoder. Refused while another encoder of this - /// command buffer is open, after one was abandoned, and after commit. - pub fn compute_command_encoder(&self) -> Result { - self.open_compute("compute_command_encoder", DispatchType::Serial) - } - - /// `computeCommandEncoderWithDispatchType:`: a serial encoder orders its dispatches as - /// Metal's does (the tracker's order inside an encoder); a concurrent one leaves their order - /// to the program's memory barriers. Refused as [`CommandBuffer::compute_command_encoder`] is. - pub fn compute_command_encoder_with_dispatch_type( - &self, - dispatch_type: DispatchType, - ) -> Result { - self.open_compute("compute_command_encoder_with_dispatch_type", dispatch_type) - } - - /// `computeCommandEncoderWithDispatchType:`, or `computeCommandEncoderWithDescriptor:` of a - /// pass descriptor's `dispatchType`, with the raw `MTLDispatchType` value `raw`, any of its 64 - /// bits: Metal makes a concurrent encoder of 1 and a serial one of every other value (2, 7, - /// `u32::MAX`, `1 << 32`, `(1 << 32) | 1`, `u64::MAX`, ...), whose `dispatchType` answers - /// serial and which skips a nil resource of `useResources:count:usage:` as a serial encoder - /// does, where a concurrent one ends the process (the M3 Max under macOS 27.0.1); so does - /// the runtime. Refused as [`CommandBuffer::compute_command_encoder`] is. - pub fn compute_command_encoder_with_raw_dispatch_type( - &self, - raw: u64, - ) -> Result { - let dispatch_type = match raw == u64::from(DispatchType::Concurrent.as_raw()) { - true => DispatchType::Concurrent, - false => DispatchType::Serial, - }; - self.open_compute( - "compute_command_encoder_with_raw_dispatch_type", - dispatch_type, - ) - } - - fn open_compute( - &self, - call: &'static str, - dispatch_type: DispatchType, - ) -> Result { - let _for = self.notices_for(); - // Refused where Metal's process ends here under some protection options - // (`command_buffer/protection.rs`), as the core opens. It joins the group of compute and - // blit encoders before it, recording into their `VkCommandBuffer`, where it may - // (`encoder_fold.rs`); and it logs its calls (`replay.rs`), which encode it again at a - // rebind of a buffer over host pages it named, or at a commit whose failure fails some of - // its group's encoders and not it. - let joining = Joining::Compute(dispatch_type); - let serial = dispatch_type == DispatchType::Serial; - let counts = &self.device().shared().counts; - // Under the core's one lock of the state: it joins its command buffer's unit of command - // predication, carrying on the loops open across its start, or starts the next; it starts - // with the residency the ended encoders left (`State::inheriting`); it takes what the - // command buffer's last compute encoder parked (`compute/live.rs`); and it takes a log its - // state kept (`spare_states.rs`), where it kept one. - // The core is made in the box the command buffer's last compute encoder parked, beside its - // bind state (`compute/live.rs`); else in a box of the device's spares, beside one of its - // bind states (`EncoderCore::open_placed`). - let (mut core, (live, carried, residency, predicated, log)) = EncoderCore::open_placed( - self, - call, - EncoderKind::Compute, - (serial, Some(joining)), - |state| { - let carried = state.enter_predication(dispatch_type); - let residency = state.inheriting(false, counts); - let parked = state.unpark_compute(); - let log = state.kept_compute_log(); - (carried, residency, state.predicated, parked, log) - }, - |opened, (carried, residency, predicated, parked, log)| { - let (core, live) = match parked { - Some(parked) => { - counts.parked_compute_taken(); - let (room, live) = parked.into_parts(); - (opened.boxed_in(room), live) - } - None => { - let live = self.device().shared().live_dispatches.take(); - (opened.boxed(), live) - } - }; - (core, (live, carried, residency, predicated, log)) - }, - )?; - // A record of command predication of its unit, or a dispatch it leaves to its host step, - // may leave it one the runtime cannot encode again, though its calls before were - // encoded: its calls no rebind's publish overlaps (`rebind::CallGate`). - core.gate_calls(); - // The laying of a loop open across its start goes on in a command buffer of its own, which - // the loop's check may submit again (`predication.rs`). - if !carried.is_empty() && self.state().predication.laying() { - let raw = core.cut_reusable()?; - self.state().predication.laid_into(raw); - } - let body = Box::new(Body { - core, - dispatch_type, - pipeline: None, - table: ArgumentTable::compute(), - threadgroup_lengths: BTreeMap::new(), - imageblock: ImageblockSize::new(1, 1), - stage_in_region: None, - indirect_stage_in: None, - residency, - captures: Captures::carried(carried, predicated), - log: Some( - log.unwrap_or_else(|| self.device().shared().scheduler.spare_logs().compute()), - ), - dispatches: 0, - live, - heaps_noted: None, - }); - Ok(ComputeCommandEncoder { body }) - } -} - -impl ComputeCommandEncoder { - /// An encoder of `dispatch_type` that encodes an ended one of `command_buffer` again, - /// starting with `residency` as it started (`replay.rs`): it logs nothing. - pub(super) fn replaying( - command_buffer: &CommandBuffer, - dispatch_type: DispatchType, - residency: Residency, - ) -> Result { - let replaying = - EncoderCore::replaying(command_buffer, dispatch_type == DispatchType::Serial)?; - let body = Box::new(Body { - core: replaying.boxed(), - dispatch_type, - pipeline: None, - table: ArgumentTable::compute(), - threadgroup_lengths: BTreeMap::new(), - imageblock: ImageblockSize::new(1, 1), - stage_in_region: None, - indirect_stage_in: None, - residency, - captures: Captures::default(), - log: None, - dispatches: 0, - live: command_buffer.device().shared().live_dispatches.take(), - heaps_noted: None, - }); - Ok(ComputeCommandEncoder { body }) - } - - /// End an encoder made by [`replaying`](Self::replaying): what it recorded, and what it made - /// resident. - pub(super) fn finish_replay(mut self) -> Result<(Replayed, Option), Error> { - // Its unit of command predication takes what it encoded again, as at its end - // (`predication.rs`). - self.end_predication()?; - self.body.table.let_go_all(&mut self.body.core); - let Body { - core, - residency, - live, - .. - } = *self.body; - // Its bind state goes on to the device's next compute encoder (`compute/live.rs`). - core.device().shared().live_dispatches.give(live); - let replayed = EncoderCore::unboxed(core).finish_replay()?; - Ok((replayed, Some(residency))) - } - - /// Log the call `call` makes of the log, before it runs, where the encoder logs - /// (`replay.rs`): its place in the log. - pub(super) fn log( - &mut self, - call: impl FnOnce(&mut CallLog) -> ComputeCall, - ) -> Option { - let log = self.body.log.as_mut()?; - let call = call(log); - let extra = call.extra(); - Some(log.push(call, extra)) - } - - /// Run `run`, a public call, logged first as `call` makes it of the log - /// ([`log`](Self::log)): where it is refused, its log notes it so (`CallLog::refuse`), and an - /// encoding again refuses it again and goes on (`replay.rs`). - pub(super) fn logged( - &mut self, - call: impl FnOnce(&mut CallLog) -> ComputeCall, - run: impl FnOnce(&mut Self) -> Result, - ) -> Result { - let _call = self.body.core.begin_call(); - let _for = self.body.core.notices_for(); - let at = self.log(call); - let ran = run(self); - if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.body.log) { - log.refuse(at); - } - ran - } - - /// Note in the log the answer `result` of the call logged at `at` (`call` of it), or its - /// refusal: encoded again, the call must answer so (`replay.rs`). - pub(super) fn answered( - &mut self, - at: Option, - result: &Result, - call: fn(bool) -> ComputeCall, - ) { - let (Some(at), Some(log)) = (at, &mut self.body.log) else { - return; - }; - match result { - Ok(answer) => log.calls[at] = call(*answer), - Err(_) => log.refuse(at), - } - } - - /// The encoder logs nothing more, and will not be encoded again: it records a loop of - /// command predication (`predication.rs`), whose laying its check submits again and whose - /// copies encode its own calls again. - pub(super) fn stop_logging(&mut self) { - self.body.log = None; - } -} - -/// Announce how a recorded dispatch of `kernel` degraded: run as `regions` Vulkan dispatches, or -/// on the kernel's emulated-simdgroups variant (`emulated`). On its partial-threadgroups variant -/// (`partial`) a ragged grid runs its regions at one threadgroup size, so only its group counts -/// split it. -fn degrade_dispatch( - device: &Device, - kernel: &str, - dispatch: &Dispatch, - (regions, partial): (usize, bool), - emulated: bool, -) { - let object = || format!("a dispatch of kernel `{kernel}`"); - let threads_per_group = dispatch.threads_per_group(); - if regions > 1 { - device.degrade(Degradation::SplitDispatch, || { - let reason = match *dispatch { - Dispatch::Threads { threads, .. } - if !partial - && threads - .iter() - .zip(threads_per_group) - .any(|(&n, group)| !n.is_multiple_of(group)) => - { - format!( - "its grid of {threads:?} threads is not a whole number of threadgroups \ - of {threads_per_group:?}" - ) - } - _ => "a group count is past the device's maxComputeWorkGroupCount".to_owned(), - }; - (object(), reason) - }); - } - if emulated { - device.degrade(Degradation::EmulatedSimdgroups, || { - let reason = format!( - "its threadgroups of {threads_per_group:?} threads are not whole subgroups of \ - the size the kernel's simdgroups run on" - ); - (object(), reason) - }); - } -} - -impl ComputeCommandEncoder { - /// `dispatchType`. - pub fn dispatch_type(&self) -> DispatchType { - self.body.dispatch_type - } - - /// `setComputePipelineState:`. A state of another device is refused. - pub fn set_compute_pipeline_state( - &mut self, - state: &ComputePipelineState, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::PipelineState(state.clone()), - |this| { - this.body - .core - .check_device("set_compute_pipeline_state", state.bound_device()?)?; - this.body.pipeline = Some(state.clone()); - if let Some(trail) = this.body.core.trail() { - trail.compute(state); - } - if let Some(times) = this.body.core.times() { - times.compute(state); - } - (this.body.core.routes).state_set(state.indirect_command_writes(), || { - vec![state.function_name().to_owned()] - }); - Ok(()) - }, - ) - } - - /// `setBuffer:offset:atIndex:` (`None` unbinds the index). A buffer bound past its length is - /// held, as plain Metal binds it, and a dispatch whose kernel reads the slot is refused - /// (`Invalid(OffsetOutOfRange)`: Metal's read is past the buffer). Refused: an index past the - /// table (plain Metal writes past its own table: a texture at 128 faulted), a buffer of another - /// device. - pub fn set_buffer( - &mut self, - buffer: Option<&Buffer>, - offset: u64, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Buffer(buffer.cloned(), offset, index), - |this| { - this.body - .table - .set_buffer(&mut this.body.core, "set_buffer", buffer, offset, index) - }, - ) - } - - /// `setBuffers:offsets:withRange:`: `buffers[i]` at offset `offsets[i]` at index - /// `first + i`. Refused as [`ComputeCommandEncoder::set_buffer`] is, and when the slices' - /// lengths differ; a refusal binds none of them. - pub fn set_buffers( - &mut self, - buffers: &[Option<&Buffer>], - offsets: &[u64], - first: u32, - ) -> Result<(), Error> { - self.logged( - |log| ComputeCall::Buffers(log.buffer_span(buffers), log.word_span(offsets), first), - |this| { - this.body.table.set_buffers( - &mut this.body.core, - "set_buffers", - buffers, - offsets, - first, - ) - }, - ) - } - - /// `setBufferOffset:atIndex:`, which clears the index's attribute stride - /// ([`set_buffer_offset_with_stride`](Self::set_buffer_offset_with_stride)). An offset past - /// the buffer's length is held as [`set_buffer`](Self::set_buffer) holds one; at an index - /// with no buffer it changes nothing, as plain Metal's. At an index holding a visible-function - /// table, the kernel then reads the null table there (size 0, every entry null) until a table - /// or buffer is bound at the index again, as plain Metal reads it (an M4). At an index holding - /// inline bytes ([`set_bytes`](Self::set_bytes)), they then read as zeros at any offset until - /// the index is bound again, as plain Metal reads them (an M4; its debug layer asserts there is - /// no buffer). Refused: an index past the table. - pub fn set_buffer_offset(&mut self, offset: u64, index: u32) -> Result<(), Error> { - self.logged( - |_| ComputeCall::BufferOffset(offset, index), - |this| { - this.body.table.set_buffer_offset( - &mut this.body.core, - "set_buffer_offset", - offset, - index, - ) - }, - ) - } - - /// `setBuffer:offset:attributeStride:atIndex:`: as [`set_buffer`](Self::set_buffer), the - /// buffer read at `stride` by a kernel's stage-in layout of `MTLBufferLayoutStrideDynamic`. - /// Only such a layout reads a stride, and one bound without a stride (`set_buffer`) reads at - /// stride 0; a layout of a fixed stride reads its own whatever the bind's (as an M4 reads - /// them). A stride past 32 bits is taken modulo `2^32`, as plain Metal reads it and its - /// validation takes it (an M4 and an M3 Max), and `MTLAttributeStrideStatic` (`u64::MAX`) with - /// it: such a layout reads the element at the bind offset for the first element and zero for - /// every element past it, which lies `2^32 - 1` bytes on, past the buffer, as plain Metal on an - /// M3 Max under macOS 27.0.1 answered it. Refused as `set_buffer` is. - pub fn set_buffer_with_stride( - &mut self, - buffer: Option<&Buffer>, - offset: u64, - stride: u64, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::BufferWithStride(buffer.cloned(), offset, stride, index), - |this| { - this.body.table.set_buffer_with_stride( - &mut this.body.core, - "set_buffer_with_stride", - buffer, - offset, - stride, - index, - ) - }, - ) - } - - /// `setBuffers:offsets:attributeStrides:withRange:`: `buffers[i]` at offset `offsets[i]` and - /// stride `strides[i]` at index `first + i`, each as - /// [`set_buffer_with_stride`](Self::set_buffer_with_stride). Refused as that is, and when the - /// slices' lengths differ; a refusal binds none of them. - pub fn set_buffers_with_strides( - &mut self, - buffers: &[Option<&Buffer>], - offsets: &[u64], - strides: &[u64], - first: u32, - ) -> Result<(), Error> { - self.logged( - |log| { - let (buffers, offsets) = (log.buffer_span(buffers), log.word_span(offsets)); - ComputeCall::BuffersWithStrides(buffers, offsets, log.word_span(strides), first) - }, - |this| { - this.body.table.set_buffers_with_strides( - &mut this.body.core, - "set_buffers_with_strides", - buffers, - offsets, - Some(strides), - first, - ) - }, - ) - } - - /// `setBufferOffset:attributeStride:atIndex:`: as [`set_buffer_offset`](Self::set_buffer_offset), - /// with the index's stride set as [`set_buffer_with_stride`](Self::set_buffer_with_stride) - /// sets it, `MTLAttributeStrideStatic` included. `set_buffer_offset` clears the stride. - /// Refused as both are. - pub fn set_buffer_offset_with_stride( - &mut self, - offset: u64, - stride: u64, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::BufferOffsetWithStride(offset, stride, index), - |this| { - this.body.table.set_buffer_offset_with_stride( - &mut this.body.core, - "set_buffer_offset_with_stride", - offset, - stride, - index, - ) - }, - ) - } - - /// `setBytes:length:atIndex:`: `bytes`, copied now, at buffer index `index` in place of - /// anything bound there, so a later write of the caller's memory reaches no dispatch, as - /// Metal copies them at the call. Every later dispatch reads the copy until the index is - /// bound again; a kernel's stage-in layout of `MTLBufferLayoutStrideDynamic` reads it at - /// stride 0, as a buffer bound without a stride. A slot the kernel reaches through a pointer - /// loaded from memory (one of a device-address form) cannot read inline bytes: - /// `Bind(MissingDeviceAddress)`, at the dispatch. Refused: an index past the table, and more - /// than 4096 bytes, Metal's limit for inline bytes (`Invalid(InlineBytesLength)`). - pub fn set_bytes(&mut self, bytes: &[u8], index: u32) -> Result<(), Error> { - self.logged( - |log| ComputeCall::Bytes(log.byte_span(bytes), index), - |this| { - this.body - .table - .set_bytes(&mut this.body.core, "set_bytes", bytes, None, index) - }, - ) - } - - /// `setBytes:length:attributeStride:atIndex:`: as [`set_bytes`](Self::set_bytes), the - /// bytes read at `stride`, its low 32 bits, by a kernel's stage-in layout of - /// `MTLBufferLayoutStrideDynamic`, as [`set_buffer_with_stride`](Self::set_buffer_with_stride) - /// reads a buffer: at `MTLAttributeStrideStatic` (`u64::MAX`) such a layout reads element 0 of - /// the bytes and zero past it, as an M4 and an M3 Max read them. Refused as `set_bytes` is. - pub fn set_bytes_with_stride( - &mut self, - bytes: &[u8], - stride: u64, - index: u32, - ) -> Result<(), Error> { - self.logged( - |log| ComputeCall::BytesWithStride(log.byte_span(bytes), stride, index), - |this| { - this.body.table.set_bytes( - &mut this.body.core, - "set_bytes_with_stride", - bytes, - Some(stride), - index, - ) - }, - ) - } - - /// `setVisibleFunctionTable:atBufferIndex:` (`None` unbinds the index): the table at buffer - /// index `index`, in place of any buffer there. Refused: an index past the buffer table, a - /// table of another device. A dispatch whose function reads a buffer at the index, or a table - /// where a buffer is bound, is refused (`Invalid(FunctionTable)`), as Metal's validation - /// stops it. - pub fn set_visible_function_table( - &mut self, - table: Option<&VisibleFunctionTable>, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::FunctionTable(table.cloned(), index), - |this| { - this.body.table.set_function_tables( - &mut this.body.core, - "set_visible_function_table", - &[table], - index, - ) - }, - ) - } - - /// `setVisibleFunctionTables:withBufferRange:`: `tables[i]` at buffer index `first + i`. - /// Refused as [`ComputeCommandEncoder::set_visible_function_table`] is; a refusal binds none - /// of them. - pub fn set_visible_function_tables( - &mut self, - tables: &[Option<&VisibleFunctionTable>], - first: u32, - ) -> Result<(), Error> { - self.logged( - |_| { - ComputeCall::FunctionTables( - tables.iter().map(|table| table.cloned()).collect(), - first, - ) - }, - |this| { - this.body.table.set_function_tables( - &mut this.body.core, - "set_visible_function_tables", - tables, - first, - ) - }, - ) - } - - /// `setTexture:atIndex:` (`None` unbinds the index). Refused: an index past the table, a - /// texture of another device. What a bound texture's usage allows is checked at the - /// dispatch, against the function's use of the slot. - pub fn set_texture(&mut self, texture: Option<&Texture>, index: u32) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Texture(texture.cloned(), index), - |this| { - this.body - .table - .set_textures(&mut this.body.core, "set_texture", &[texture], index) - }, - ) - } - - /// `setTextures:withRange:`: `textures[i]` at index `first + i`. Refused as - /// [`ComputeCommandEncoder::set_texture`] is; a refusal binds none of them. - pub fn set_textures(&mut self, textures: &[Option<&Texture>], first: u32) -> Result<(), Error> { - self.logged( - |log| ComputeCall::Textures(log.texture_span(textures), first), - |this| { - this.body - .table - .set_textures(&mut this.body.core, "set_textures", textures, first) - }, - ) - } - - /// `setSamplerState:atIndex:` (`None` unbinds the index). Refused: an index past the table, a - /// state of another device. - pub fn set_sampler_state( - &mut self, - sampler: Option<&SamplerState>, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Sampler(sampler.cloned(), index), - |this| { - this.body.table.set_samplers( - &mut this.body.core, - "set_sampler_state", - &[sampler], - None, - index, - ) - }, - ) - } - - /// `setSamplerStates:withRange:`: `samplers[i]` at index `first + i`. Refused as - /// [`ComputeCommandEncoder::set_sampler_state`] is; a refusal binds none of them. - pub fn set_sampler_states( - &mut self, - samplers: &[Option<&SamplerState>], - first: u32, - ) -> Result<(), Error> { - self.logged( - |_| { - ComputeCall::Samplers( - samplers.iter().map(|sampler| sampler.cloned()).collect(), - first, - ) - }, - |this| { - this.body.table.set_samplers( - &mut this.body.core, - "set_sampler_states", - samplers, - None, - first, - ) - }, - ) - } - - /// `setSamplerState:lodMinClamp:lodMaxClamp:atIndex:`: the state with its LOD clamps - /// replaced by these, at `index`. Metal takes any clamps: inverted ones read the upper clamp's - /// level, as Metal's do; a sampler whose clamps are NaN is refused at the dispatch that samples - /// through it (what Metal samples then is not measured). Refused as - /// [`ComputeCommandEncoder::set_sampler_state`] is. - pub fn set_sampler_state_with_lod_clamps( - &mut self, - sampler: Option<&SamplerState>, - lod_min_clamp: f32, - lod_max_clamp: f32, - index: u32, - ) -> Result<(), Error> { - self.logged( - |_| { - ComputeCall::SamplerWithLodClamps( - sampler.cloned(), - lod_min_clamp, - lod_max_clamp, - index, - ) - }, - |this| { - this.body.table.set_samplers( - &mut this.body.core, - "set_sampler_state_with_lod_clamps", - &[sampler], - Some((&[lod_min_clamp], &[lod_max_clamp])), - index, - ) - }, - ) - } - - /// `setSamplerStates:lodMinClamps:lodMaxClamps:withRange:`: `samplers[i]` with LOD clamps - /// `lod_min_clamps[i]` and `lod_max_clamps[i]` at index `first + i`. Refused as - /// [`ComputeCommandEncoder::set_sampler_state_with_lod_clamps`] is, and when the slices' - /// lengths differ; a refusal binds none of them. - pub fn set_sampler_states_with_lod_clamps( - &mut self, - samplers: &[Option<&SamplerState>], - lod_min_clamps: &[f32], - lod_max_clamps: &[f32], - first: u32, - ) -> Result<(), Error> { - self.logged( - |_| { - ComputeCall::SamplersWithLodClamps(Box::new(SamplersWithLodClamps { - samplers: samplers.iter().map(|sampler| sampler.cloned()).collect(), - mins: lod_min_clamps.into(), - maxes: lod_max_clamps.into(), - first, - })) - }, - |this| { - this.body.table.set_samplers( - &mut this.body.core, - "set_sampler_states_with_lod_clamps", - samplers, - Some((lod_min_clamps, lod_max_clamps)), - first, - ) - }, - ) - } - - /// `setThreadgroupMemoryLength:atIndex:`. A length that is not a multiple of 16 bytes is - /// taken, rounded up to 16 at the dispatch, as plain Metal takes it (lengths of 4, 8 and 20 - /// held their threads' words on an M4); Metal's API validation asserts. Refused: an index past - /// the table. The device's limit is checked at the dispatch. - pub fn set_threadgroup_memory_length(&mut self, length: u32, index: u32) -> Result<(), Error> { - self.logged( - |_| ComputeCall::ThreadgroupMemoryLength(length, index), - |this| { - const CALL: &str = "set_threadgroup_memory_length"; - check_index(CALL, index, THREADGROUP_SLOTS)?; - this.body.threadgroup_lengths.insert(index, length); - Ok(()) - }, - ) - } - - /// `setImageblockWidth:height:`: the cells of each threadgroup's explicit imageblock in the - /// encoder's later dispatches, whichever pipeline state they use. Until it is called a - /// dispatch's imageblock is 1 by 1, as Metal's is. Its bytes count against the device's - /// threadgroup memory beside the threadgroup memory lengths, checked at the dispatch. - /// - /// A side of 0 sets 1 by 1, a side that is not a power of two is rounded up to one, and more - /// than 1024 cells in one row or column set 1 by 1, as plain Metal sets them (Metal's API - /// validation stops them). Refused (`Invalid`), as validation refuses it, changing nothing: - /// more than 1024 cells over more rows and columns, which Metal runs as 1024 by 1 with its - /// cells reading 0, and a side past 65536 (unmeasured). - pub fn set_imageblock_size(&mut self, width: u64, height: u64) -> Result<(), Error> { - self.logged( - |_| ComputeCall::ImageblockSize(width, height), - |this| { - this.body.imageblock = imageblock_size(width, height) - .map_err(|p| invalid("set_imageblock_size", p))?; - Ok(()) - }, - ) - } - - /// `setStageInRegion:`: the region whose origin each thread's position in the grid is added - /// to, to find the element its `[[stage_in]]` attributes are fetched from, and which - /// `[[grid_origin]]` and `[[grid_size]]` read. It holds for the encoder's later dispatches. A - /// dispatch of a kernel that reads it with none set is refused (`Bind(MissingStageInRegion)`). - /// An origin or size axis past 32 bits is taken modulo `2^32`, as Metal takes it with or - /// without its API validation (an origin of `2^32 + 1` read 1 and fetched element 1 on an M4). - pub fn set_stage_in_region(&mut self, region: Region) -> Result<(), Error> { - self.logged( - |_| ComputeCall::StageInRegion(region), - |this| { - let Region { origin, size } = region; - let origin = Size::new(origin.x, origin.y, origin.z).truncated(); - this.body.stage_in_region = Some(StageInRegion::new(origin, size.truncated())); - this.body.indirect_stage_in = None; - Ok(()) - }, - ) - } - - /// `setStageInRegionWithIndirectBuffer:indirectBufferOffset:`: the encoder's later - /// dispatches read their stage-in region from the `MTLStageInRegionIndirectArguments` at - /// `indirect_buffer_offset` (the origin's three `u32`s, then the size's) as each runs, until a - /// `set_stage_in_region`. A host step reads them once the work before the dispatch - /// completed, and records the dispatch with the region they state - /// (`indirect_dispatch`), as it does an indirect dispatch's - /// arguments; a region the binder refuses there fails the command buffer, as an indirect - /// command's dispatch does. - /// - /// An offset that is not a multiple of 4 reads at the multiple below, as plain Metal reads - /// it (Metal's API validation stops it). Arguments past the buffer's length are read out of - /// its allocation, as an indirect dispatch's are measured to be - /// (`indirect_dispatch::arguments_offset`, which carries the measurement; the region's own - /// read is unmeasured, and follows it as the same read of a `u32` at the same kind of - /// address). Refused, changing nothing (`Invalid`): arguments past the bytes the runtime - /// holds there (`Buffer::copy_reach`), and a buffer of another device. - pub fn set_stage_in_region_indirect( - &mut self, - indirect_buffer: &Buffer, - indirect_buffer_offset: u64, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::StageInRegionIndirect(indirect_buffer.clone(), indirect_buffer_offset), - |this| { - const CALL: &str = "set_stage_in_region_indirect"; - this.body - .core - .check_device(CALL, indirect_buffer.generation())?; - let offset = indirect_dispatch::arguments_offset( - CALL, - (indirect_buffer.length(), indirect_buffer.copy_reach()), - indirect_buffer_offset, - STAGE_IN_REGION_BYTES, - )?; - this.body.indirect_stage_in = Some((indirect_buffer.clone(), offset)); - this.body.stage_in_region = None; - Ok(()) - }, - ) - } - - /// `dispatchThreadgroups:threadsPerThreadgroup:`. A threadgroup Metal runs nothing for (its - /// size 0 or above the state's maximum, the module docs) records nothing; a count axis past - /// 32 bits is taken modulo `2^32`, and one that is 0 runs nothing. A dispatch of an inert - /// kernel (no loop, and no write but to its threads' own and its threadgroups' memory) records - /// no Vulkan dispatch: what it computes ends with it, and Metal's counter sampling, which - /// could count its threads, is the runtime's gap (`RuntimeGap::CounterSampleBuffers`). The - /// command buffer still uses what it binds, as Metal's does (the `Managed` buffers' copies in - /// among it), and the encoder's barriers and fences stay as they are. Refused: no pipeline - /// state set (plain Metal faults). - pub fn dispatch_threadgroups(&mut self, groups: Size, threads: Size) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Threadgroups(groups, threads), - |this| { - const CALL: &str = "dispatch_threadgroups"; - if this.fails_on_memoryless() { - return Ok(()); - } - let Some(threads_per_group) = this.threadgroup(CALL, threads)? else { - return Ok(()); - }; - this.dispatch( - CALL, - Dispatch::Threadgroups { - groups: groups.truncated(), - threads_per_group, - }, - )?; - this.worked(); - this.capture(|| Event::Threadgroups(groups, threads)); - Ok(()) - }, - ) - } - - /// `dispatchThreads:threadsPerThreadgroup:`: a grid of `threads`, its edges in partial - /// threadgroups. Its threadgroup and grid are taken as - /// [`dispatch_threadgroups`](Self::dispatch_threadgroups) takes its threadgroup and counts. - pub fn dispatch_threads(&mut self, threads: Size, per_group: Size) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Threads(threads, per_group), - |this| { - const CALL: &str = "dispatch_threads"; - if this.fails_on_memoryless() { - return Ok(()); - } - let Some(threads_per_group) = this.threadgroup(CALL, per_group)? else { - return Ok(()); - }; - this.dispatch( - CALL, - Dispatch::Threads { - threads: threads.truncated(), - threads_per_group, - }, - )?; - this.worked(); - this.capture(|| Event::Threads(threads, per_group)); - Ok(()) - }, - ) - } - - /// `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:`: - /// threadgroups of `threads` threads, as many on each axis as the - /// `MTLDispatchThreadgroupsIndirectArguments` at `indirect_buffer_offset` state when the - /// dispatch runs. A host step reads them once the work before the dispatch completed, and - /// records the dispatch as `dispatch_threadgroups` of the encoder's tables now - /// (`indirect_dispatch`); a zero count runs nothing. - /// - /// An offset that is not a multiple of 4 reads at the multiple below, as plain Metal reads - /// it. Refused, recording nothing, as `dispatch_threadgroups` refuses `threads`, and as Metal's - /// API validation refuses arguments past the buffer's length from there (`Invalid`); and for - /// a buffer of another device. - pub fn dispatch_threadgroups_indirect( - &mut self, - indirect_buffer: &Buffer, - indirect_buffer_offset: u64, - threads: Size, - ) -> Result<(), Error> { - self.logged( - |_| { - ComputeCall::ThreadgroupsIndirect( - indirect_buffer.clone(), - indirect_buffer_offset, - threads, - ) - }, - |this| { - const CALL: &str = "dispatch_threadgroups_indirect"; - let Some(threads_per_group) = this.threadgroup(CALL, threads)? else { - // A threadgroup that runs nothing fails as a direct dispatch's does. - this.fails_on_memoryless(); - return Ok(()); - }; - let arguments = Arguments::Threadgroups { threads_per_group }; - this.dispatch_indirect(CALL, indirect_buffer, indirect_buffer_offset, arguments)?; - this.worked(); - this.capture(|| { - Event::ThreadgroupsIndirect( - indirect_buffer.clone(), - indirect_buffer_offset, - threads, - ) - }); - Ok(()) - }, - ) - } - - /// `dispatchThreadsWithIndirectBuffer:indirectBufferOffset:` (the encoder's SPI; Metal 4's - /// `dispatchThreadsWithIndirectBuffer:`): a grid of threads, its edges in partial - /// threadgroups, as the `MTLDispatchThreadsIndirectArguments` at `indirect_buffer_offset` - /// state when the dispatch runs (`threadsPerGrid`, then `threadsPerThreadgroup`). A host - /// step reads them once the work before the dispatch completed, and records the dispatch as - /// `dispatch_threads` of the encoder's tables now - /// (`indirect_dispatch`). A zero grid axis, and a threadgroup with a zero axis or more threads - /// than Metal's limit for the state, run nothing, as Metal's do; one past only the state's - /// `max_total_threads_per_threadgroup` (this device's lower limit) is refused typed as the - /// device's gap. - /// - /// An offset that is not a multiple of 4 reads at the multiple below, as plain Metal reads - /// it. Refused, recording nothing, with no pipeline state set, and as Metal's API validation - /// refuses arguments past the buffer's length from there (`Invalid`); and for a buffer of - /// another device. - pub fn dispatch_threads_indirect( - &mut self, - indirect_buffer: &Buffer, - indirect_buffer_offset: u64, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::ThreadsIndirect(indirect_buffer.clone(), indirect_buffer_offset), - |this| { - const CALL: &str = "dispatch_threads_indirect"; - let arguments = Arguments::Threads; - this.dispatch_indirect(CALL, indirect_buffer, indirect_buffer_offset, arguments)?; - this.worked(); - this.capture(|| { - Event::ThreadsIndirect(indirect_buffer.clone(), indirect_buffer_offset) - }); - Ok(()) - }, - ) - } - - /// Check an indirect dispatch of `arguments` at `offset` of `buffer`, and record it on its - /// kernel's flat variant, or else copy them where it is encoded and leave the dispatch to its - /// host step (`indirect_dispatch.rs`); with every texture the encoder's heaps hold resident. - fn dispatch_indirect( - &mut self, - call: &'static str, - buffer: &Buffer, - offset: u64, - arguments: Arguments, - ) -> Result<(), Error> { - self.sync_heaps(); - let reads = self - .body - .pipeline - .as_ref() - .is_some_and(ComputePipelineState::reads_texture_handles); - self.dispatch_indirect_resident(call, buffer, offset, arguments)?; - self.command_encoded(reads); - self.body.dispatches += 1; - if let Some(times) = self.body.core.times() { - times.worked(); - } - Ok(()) - } - - /// [`dispatch_indirect`](Self::dispatch_indirect) with the heaps' textures resident. - fn dispatch_indirect_resident( - &mut self, - call: &'static str, - buffer: &Buffer, - offset: u64, - arguments: Arguments, - ) -> Result<(), Error> { - let Some(pipeline) = self.body.pipeline.clone() else { - return Err(invalid(call, Problem::NoPipelineState)); - }; - self.body.core.check_device(call, buffer.generation())?; - let offset = indirect_dispatch::arguments_offset( - call, - (buffer.length(), buffer.copy_reach()), - offset, - arguments.bytes(), - )?; - if self.fails_on_memoryless() { - return Ok(()); - } - let tables = DispatchTables { - pipeline: &pipeline, - table: &self.body.table, - threadgroup_lengths: &self.body.threadgroup_lengths, - imageblock: self.body.imageblock, - stage_in_region: self.body.stage_in_region, - residency: &self.body.residency, - forms: BufferForms::Bound, - }; - let flat = FlatCall { - buffer, - offset, - arguments, - }; - if self.body.indirect_stage_in.is_none() - && record( - &mut self.body.core, - &tables, - call, - Counts::Flat(flat), - Some((self.body.dispatches, &mut *self.body.live)), - )? - { - return Ok(()); - } - let copy = indirect_dispatch::copy_arguments( - &mut self.body.core, - buffer, - offset, - arguments.bytes(), - )?; - self.defer_dispatch(call, pipeline, HostDispatch::Indirect { arguments, copy }) - } - - /// Leave `dispatch` of `pipeline` to its host step, with the encoder's tables now and a copy - /// of its indirect stage-in region where one is set (`indirect_dispatch.rs`). - /// - /// The dispatch uses what its tables bind from its call, as a recorded one does: the encoder - /// retains them now (`ArgumentTable::retain`), keeping their keys and holding each buffer over - /// host pages among them, which its commit keeps until the command buffer completes - /// (`steps_hold`), as the host step resolves them as it records. So a rebind of one from this - /// call on is refused (`RebindProblem::EncodedUses`), never failing the step's recording at its - /// submission (`EncodedUseRebound`): the hold is taken in this call, which no rebind's publish - /// overlaps (`rebind::CallGate`). - fn defer_dispatch( - &mut self, - call: &'static str, - pipeline: ComputePipelineState, - dispatch: HostDispatch, - ) -> Result<(), Error> { - self.body.table.retain(&mut self.body.core); - let stage_in_copy = match &self.body.indirect_stage_in { - Some((buffer, offset)) => Some(indirect_dispatch::copy_arguments( - &mut self.body.core, - buffer, - *offset, - STAGE_IN_REGION_BYTES, - )?), - None => None, - }; - let gate = self - .body - .core - .command_buffer() - .state() - .predication_mut() - .host_gate(); - self.body - .core - .defer(Deferred::Dispatch(Arc::new(ArgumentDispatch { - call, - dispatch, - stage_in_copy, - pipeline, - table: self.body.table.clone(), - threadgroup_lengths: self.body.threadgroup_lengths.clone(), - imageblock: self.body.imageblock, - stage_in_region: self.body.stage_in_region, - ordered: self.body.dispatch_type == DispatchType::Serial, - gate, - }))) - } - - /// `memoryBarrierWithScope:`: every write of the encoder's earlier dispatches to the kinds - /// of resource `scope` names is visible to its later dispatches, however they read it - /// (storage, uniform, or indirect arguments). One global memory barrier covers buffers and - /// textures alike, from the shader writes to the shader reads and writes; a later dispatch - /// that reads a uniform buffer or indirect arguments takes, before itself, a barrier to those - /// accesses too, so no dispatch waits on a cache or a stage it does not use. Render targets - /// are not a compute encoder's, so a scope of only `RENDER_TARGETS` records nothing. On a - /// serial encoder, which orders its dispatches anyway, it adds nothing Metal would not do. - pub fn memory_barrier_with_scope(&mut self, scope: BarrierScope) { - let _for = self.body.core.notices_for(); - self.log(|_| ComputeCall::BarrierWithScope(scope)); - if !scope.intersects(BarrierScope::BUFFERS.union(BarrierScope::TEXTURES)) { - return; - } - self.body.core.memory_barrier(); - self.capture(|| Event::Barrier); - } - - /// `useResource:usage:`: the encoder's later dispatches may reach `resource` through an - /// address or a resource ID held in memory, reading or writing as `usage` says - /// (`residency`). A memoryless texture, a texture buffer too, fails the command buffer as - /// plain Metal's does, with no dispatch after it too (`CommandBufferError::InvalidResource`: - /// the encoder's run of compute encoders runs nothing, an M3 Max under macOS 27.0.1). - /// - /// Refused, changing nothing: a resource of another device (`Invalid`). - pub fn use_resource( - &mut self, - resource: ResourceRef<'_>, - usage: ResourceUsage, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::UseResource(Resource::one(resource), usage), - |this| this.use_all("use_resource", &[resource], usage), - ) - } - - /// `useResources:count:usage:`: [`use_resource`](Self::use_resource) of each of - /// `resources`, refused, changing nothing, as it is for any of them. - pub fn use_resources( - &mut self, - resources: &[ResourceRef<'_>], - usage: ResourceUsage, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::UseResources(Resource::all(resources), usage), - |this| this.use_all("use_resources", resources, usage), - ) - } - - fn use_all( - &mut self, - call: &'static str, - resources: &[ResourceRef<'_>], - usage: ResourceUsage, - ) -> Result<(), Error> { - for resource in resources { - self.body.core.check_device(call, resource.device())?; - } - if resources.iter().any(ResourceRef::is_memoryless) { - self.body.core.fail_memoryless_use(); - return Ok(()); - } - // A texture's shadow left unmade is made as the encoder makes it resident: its resource - // ID reads it from then on (`texture/lazy_shadow.rs`). - for resource in resources { - if let ResourceRef::Texture(texture) = resource { - texture.made_for_use()?; - } - } - for &resource in resources { - // Its records held where they lie in device-local memory, before any listing of - // them reads where they lie (`indirect_command_buffer/home.rs`). - if let ResourceRef::IndirectCommandBuffer(icb) = resource { - icb.hold_records(&mut self.body.core, usage.contains(ResourceUsage::WRITE)); - } - let used = self - .body - .residency - .use_resource(resource, usage, RenderStages::empty()); - if let Some(used) = used { - self.body.core.made_resident(used); - } - if let ResourceRef::IndirectCommandBuffer(icb) = resource { - if usage.contains(ResourceUsage::WRITE) { - self.body.core.routes.writable(icb); - self.body.core.retain(icb.gpu_write()); - } - } - } - Ok(()) - } - - /// `useHeap:`: the encoder's later dispatches may read every buffer placed in `heap` - /// through an address held in memory, and every texture made in it or over a buffer placed - /// in it through its resource ID, as Metal's contract makes a heap's resources resident for - /// reading only (`residency`): the textures that live now, and each made later, from the first - /// dispatch encoded after it is made. As Metal's, it holds the heap, not its textures: one the - /// program released, which only command buffers that used the heap hold, is not made resident - /// again. The heap's whole range is one used resource, ordered as the one resource its - /// tracked buffers and textures are. - /// - /// A sparse heap holds no buffer: its live sparse textures are made resident, as - /// `use_resource` with `READ` makes each. - /// - /// Refused, changing nothing (`Invalid`): a heap of another device. - pub fn use_heap(&mut self, heap: &Heap) -> Result<(), Error> { - self.logged( - |_| ComputeCall::UseHeap(heap.clone()), - |this| this.use_heaps_of("use_heap", &[heap]), - ) - } - - /// `useHeaps:count:`: [`use_heap`](Self::use_heap) of each of `heaps`, refused, changing - /// nothing, as it is for any of them. - pub fn use_heaps(&mut self, heaps: &[&Heap]) -> Result<(), Error> { - self.logged( - |_| ComputeCall::UseHeaps(heaps.iter().map(|&heap| heap.clone()).collect()), - |this| this.use_heaps_of("use_heaps", heaps), - ) - } - - fn use_heaps_of(&mut self, call: &'static str, heaps: &[&Heap]) -> Result<(), Error> { - for heap in heaps { - self.body.core.check_device(call, heap.generation())?; - } - for heap in heaps { - for used in self.body.residency.use_heap(heap, RenderStages::empty()) { - self.body.core.made_resident(used); - } - } - Ok(()) - } - - /// `executeCommandsInBuffer:withRange:`: run commands `range` of `icb` here, as their - /// records stand when the command buffer is committed, or, where an encoder made `icb` resident - /// for writing (`use_resource` with `WRITE`), once the work before them completed, as a kernel - /// wrote them (a host step the device announces once, - /// `Degradation::HostReplayedIndirectCommands`). Each runs as this encoder's dispatch would, - /// with its own pipeline state, buffers and lengths, or the encoder's pipeline state and - /// buffers as they are now where `icb` inherits them, and the resources the encoder made - /// resident so far, which its buffers' addresses resolve against: an address in none misses, - /// reading zero and dropping writes, and the execution report counts it. The encoder's commands - /// before run before them and its commands after run after them. Among themselves the commands - /// run in no order but where a command's record sets a barrier (`set_barrier`), which orders it - /// after every earlier command of the range, whatever the encoder's dispatch type: Metal's - /// serial encoder adds a barrier before and after the range alone. - /// - /// Refused, changing nothing (`Invalid`): a buffer of another device, a range that ends - /// past its size (`IndirectCommandBufferProblem::Range`), and, for a range that is not - /// empty, no pipeline state set where `icb` inherits it. A buffer of render command types is - /// `NotImplemented(IndirectRenderCommands)`: Metal's validation lets it through, and what its - /// commands do in a compute encoder is not measured. An empty range runs nothing, whatever - /// the encoder's pipeline state, and so does a buffer of no command types, as plain Metal's. - /// What a command's dispatch would be refused refuses the commit ([`CommandBuffer::commit`]). - pub fn execute_commands_in_buffer( - &mut self, - icb: &IndirectCommandBuffer, - range: Range, - ) -> Result<(), Error> { - self.execute_range(icb, range, None) - } - - /// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) with a check of the - /// commands it runs (a runtime extension; Metal has none), which looks for what `needs` names - /// ([`IndirectCommandCheckNeeds`]; a compute command draws no points): where the commit records - /// the execution from the CPU's records, or a host step from the records as the GPU and the CPU - /// left them (a route that may write `icb`'s records met it, - /// `IndirectCommandBuffer::gpu_written`, or the execution lies inside a block of command - /// predication), it first calls `check` with each command it will record, in order, - /// before it records any of them ([`IndirectCommandCheck`]). Where what the records may hold - /// leaves the check nothing to see, neither calls it, and an execution a host step would record - /// may run on the GPU alone, as an unchecked one may; a route encoded after the commit that - /// gives the check something to see before the batch is submitted sends it to the host step. - /// Refused as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses. - pub fn execute_commands_in_buffer_checked( - &mut self, - icb: &IndirectCommandBuffer, - range: Range, - check: IndirectCommandCheck, - needs: IndirectCommandCheckNeeds, - ) -> Result<(), Error> { - self.execute_range(icb, range, Some((check, needs))) - } - - /// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer), with `check` for its - /// host step where one is given, and what it looks for. - fn execute_range( - &mut self, - icb: &IndirectCommandBuffer, - range: Range, - check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::Execute(icb.clone(), range.clone()), - |this| { - const CALL: &str = indirect_execute::CALL; - this.body.core.check_device(CALL, icb.generation())?; - if icb.is_render() { - return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands( - IndirectRule::OtherEncoderKind, - ))); - } - let range = icb.command_range(CALL, range.clone())?; - // An empty range runs nothing before the inherited pipeline state is looked at, as - // plain Metal's with none set. - if range.is_empty() { - return Ok(()); - } - let pipeline = this.inherited_pipeline(CALL, icb)?; - // A buffer of no command types runs nothing, as plain Metal's. - if icb.has_no_command_types() { - return Ok(()); - } - let fixed = u64::from(range.start)..u64::from(range.end); - this.defer_execution(icb, ExecutionRange::Fixed(range), pipeline, check)?; - this.worked(); - this.capture(|| Event::Execute(icb.clone(), fixed)); - Ok(()) - }, - ) - } - - /// `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`: run the commands of `icb` - /// that the `MTLIndirectCommandBufferExecutionRange` at `offset` of `range_buffer` - /// (`location`, then `length`, each a `u32`) names as the execution runs, after what the - /// encoder's commands before it wrote there, as Metal runs them: from the location, clamped at - /// the buffer's size, so a location at the size runs nothing and a length past it runs to its - /// end. A location past the size, or a range past `2^32 - 1`, which Metal's GPU faults on, runs - /// nothing, and the command buffer's execution report states `ReplayFaults::RANGE`. The - /// commands run as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer)'s that a - /// function may write do: by a host step once the work that wrote them and the range completed, - /// which the device announces once (`Degradation::HostReplayedIndirectCommands`). The step - /// reads the range in place where the host maps the bytes of `range_buffer` the GPU writes (a - /// `Shared` buffer, a `Managed` one on unified memory); else the encoder copies it where it is - /// encoded, behind a barrier from everything before, and the step reads the copy. - /// - /// A range plain Metal takes and the runtime has no exact answer for is its own gap, not - /// misuse: 8 bytes that run past `range_buffer`, which Metal reads from whatever follows it - /// (`NotImplemented(ExecutionRangePastBuffer)`), and an `offset` that is not a multiple of 4 - /// bytes, which Metal's GPU faults the command buffer over where the range read there runs a - /// command (`NotImplemented(ExecutionRangeOffFour)`; both carry the measurement). - /// - /// Refused, changing nothing (`Invalid`): a buffer of another device, and no pipeline state - /// set where `icb` inherits it. A buffer of render command types is refused as - /// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses it. A buffer of - /// no command types runs nothing, its range unread, as plain Metal's. What a command's dispatch - /// would be refused fails the command buffer. - pub fn execute_commands_in_buffer_indirect( - &mut self, - icb: &IndirectCommandBuffer, - range_buffer: &Buffer, - offset: u64, - ) -> Result<(), Error> { - self.execute_indirect_range(icb, range_buffer, offset, None) - } - - /// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) with a - /// check of the commands its host step runs, which always records it, looking for what `needs` - /// names: the step first calls `check` with each command of the range it read that it will - /// record, in order, before it records any of them, as - /// [`execute_commands_in_buffer_checked`](Self::execute_commands_in_buffer_checked)'s does - /// ([`IndirectCommandCheck`]), unless what the records may hold then leaves the check nothing - /// to see ([`IndirectCommandCheckNeeds`]). Refused as - /// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect) refuses. - pub fn execute_commands_in_buffer_indirect_checked( - &mut self, - icb: &IndirectCommandBuffer, - range_buffer: &Buffer, - offset: u64, - check: IndirectCommandCheck, - needs: IndirectCommandCheckNeeds, - ) -> Result<(), Error> { - self.execute_indirect_range(icb, range_buffer, offset, Some((check, needs))) - } - - /// [`execute_commands_in_buffer_indirect`](Self::execute_commands_in_buffer_indirect), with - /// `check` for its host step where one is given, and what it looks for. - fn execute_indirect_range( - &mut self, - icb: &IndirectCommandBuffer, - range_buffer: &Buffer, - offset: u64, - check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, - ) -> Result<(), Error> { - self.logged( - |_| ComputeCall::ExecuteIndirect(icb.clone(), range_buffer.clone(), offset), - |this| { - const CALL: &str = indirect_execute::CALL_INDIRECT; - this.body.core.check_device(CALL, icb.generation())?; - this.body - .core - .check_device(CALL, range_buffer.generation())?; - if icb.is_render() { - return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands( - IndirectRule::OtherEncoderKind, - ))); - } - indirect_execute::check_range_buffer(range_buffer.length(), offset)?; - let pipeline = this.inherited_pipeline(CALL, icb)?; - // A buffer of no command types runs nothing, as plain Metal's; its range is not - // read. - if icb.has_no_command_types() { - return Ok(()); - } - let range = - indirect_execute::range_from(&mut this.body.core, range_buffer, offset)?; - this.defer_execution(icb, range, pipeline, check)?; - this.worked(); - this.capture(|| Event::ExecuteIndirect(icb.clone(), range_buffer.clone(), offset)); - Ok(()) - }, - ) - } - - /// The encoder's pipeline state where `icb` inherits it (refused `NoPipelineState` where - /// none is set), else `None`. - fn inherited_pipeline( - &self, - call: &'static str, - icb: &IndirectCommandBuffer, - ) -> Result, Error> { - match (&self.body.pipeline, icb.descriptor().inherit_pipeline_state) { - (_, false) => Ok(None), - (Some(pipeline), true) => Ok(Some(pipeline.clone())), - (None, true) => Err(invalid(call, Problem::NoPipelineState)), - } - } - - /// Leave the execution of `range` of `icb` to record later (`indirect_execute.rs`), with - /// the encoder's pipeline state `pipeline` where `icb` inherits it, its bound buffers where - /// `icb` inherits them, and what it made resident so far, and `check` for its host step. - fn defer_execution( - &mut self, - icb: &IndirectCommandBuffer, - range: ExecutionRange, - pipeline: Option, - check: Option<(IndirectCommandCheck, IndirectCommandCheckNeeds)>, - ) -> Result<(), Error> { - if let Some(trail) = self.body.core.trail() { - trail.execution(range.given()); - } - icb.hold_records(&mut self.body.core, false); - self.sync_heaps(); - // Its commands bind the heap sets as they record, later. - self.body - .core - .command_buffer() - .state() - .heaps - .executes_later(); - // Its commands run the states their records name, where it inherits none. - if !icb.descriptor().inherit_pipeline_state { - self.body.core.routes.executed(icb); - } - let table = if icb.descriptor().inherit_buffers { - self.body.table.clone() - } else { - ArgumentTable::default() - }; - // Inside a block of command predication: the host step's check of the counter, and the - // gate the GPU-alone path's preprocess of a fixed range runs from (`gpu_execute.rs`), one - // invocation per command where the counter is 0. - let (gate, further, preprocess_gate) = { - let device = self.body.core.device().clone(); - let mut state = self.body.core.command_buffer().state(); - let (predication, uploads) = state.predication_and_uploads(); - let gate = predication.host_gate(); - let (further, preprocess_gate) = match (&gate, &range) { - (Some(_), ExecutionRange::Fixed(range)) if !range.is_empty() => { - let count = [range.len() as u32, 1, 1]; - let (further, mut gates) = predication.gates(uploads, &device, &[count])?; - (further, gates.pop()) - } - _ => (None, None), - }; - (gate, further, preprocess_gate) - }; - if let Some(step) = further { - predication::record_further(&mut self.body.core, &step)?; - } - self.body.core.defer(Deferred::Execute(Arc::new(Execute { - icb: icb.clone(), - range, - pipeline, - table, - gate, - preprocess_gate, - check: check.map(|(check, needs)| (Mutex::new(check), needs)), - unchecked: Mutex::new(None), - read_at: AtomicU64::new(indirect_execute::NOT_READ), - })))?; - // Its commands may name any pipeline state. - self.command_encoded(true); - Ok(()) - } - - /// Make resident the textures made since the encoder's last command in the heaps it used - /// (`Residency::sync_heaps`), held until the command buffer completes: a command reaches - /// every texture its heaps hold as it is encoded. - fn sync_heaps(&mut self) { - self.body.residency.sync_heaps(); - } - - /// Once a command was encoded, note the heaps the encoder used; and where it reads texture - /// handles from memory (`reads`), the textures it reaches whose blocks a carrier holds. - fn command_encoded(&mut self, reads: bool) { - // The command, encoded, used the heaps of what the encoder made resident: noted once a - // change of it, as an earlier command noted those it held then. - let generation = self.body.residency.generation(); - if self.body.heaps_noted != Some(generation) { - self.body.core.touch_heaps(self.body.residency.heaps()); - self.body.heaps_noted = Some(generation); - } - if !reads { - return; - } - // A texture the kernel's handles reach whose blocks a carrier holds reads as the neutral: - // among those made resident, as the encoder keeps the first (`compute/live.rs`). - let bound = self.body.table.textures.values(); - let resident = - (self.body.live.unreadable).of(self.body.core.device(), &self.body.residency); - degrade_unreadable( - self.body.core.device(), - resident.into_iter().chain(bound), - "a dispatch", - ); - } - - /// The encoder's core. - pub(super) fn core(&mut self) -> &mut EncoderCore { - &mut self.body.core - } - - /// The encoder's state now, which a predicated loop's copies replay a command with. - pub(super) fn encoder_state(&self) -> EncoderState { - EncoderState { - pipeline: self.body.pipeline.clone(), - table: self.body.table.clone(), - threadgroup_lengths: self.body.threadgroup_lengths.clone(), - imageblock: self.body.imageblock, - stage_in_region: self.body.stage_in_region, - indirect_stage_in: self.body.indirect_stage_in.clone(), - } - } - - /// Set the encoder's state back to `state`: what the table it replaces binds is held until - /// the command buffer completes (`ArgumentTable::let_go_all`). - pub(super) fn restore_state(&mut self, state: EncoderState) { - self.body.table.let_go_all(&mut self.body.core); - self.body.pipeline = state.pipeline; - self.body.table = state.table; - self.body.threadgroup_lengths = state.threadgroup_lengths; - self.body.imageblock = state.imageblock; - self.body.stage_in_region = state.stage_in_region; - self.body.indirect_stage_in = state.indirect_stage_in; - } - - /// The bodies of the predicated loops the encoder has open. - pub(super) fn captures(&mut self) -> &mut Captures { - &mut self.body.captures - } - - /// What the encoder made resident so far, which a predicated loop carried to its unit's next - /// encoder replays its commands with (`predication.rs`). - pub(super) fn residency_now(&self) -> Residency { - self.body.residency.clone() - } - - /// Make resident here what `residency`, an earlier encoder's of the unit, made resident: a - /// predicated loop's copy replays that encoder's commands here (`predication.rs`). - pub(super) fn carry_residency(&mut self, residency: &Residency) { - self.body.residency.carry(residency); - } - - /// `label`: the label [`set_label`](Self::set_label) gave it, or `None`, as Metal's is `nil` - /// until set. - pub fn label(&self) -> Option { - self.body.core.command_buffer().open_encoder_label() - } - - /// `setLabel:`: label it `label`, which its command buffer's ended encoders keep - /// ([`CommandBuffer::ended_encoders`](crate::CommandBuffer::ended_encoders)) and the - /// runtime's notices naming the command buffer state, as [`CommandBuffer::set_label`](crate::CommandBuffer::set_label)'s. - pub fn set_label(&mut self, label: &str) { - self.body.core.command_buffer().label_open_encoder(label); - } - - /// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds - /// what an encoder was handed. - pub fn end_encoding(mut self) -> Result<(), Error> { - let _call = self.body.core.begin_call(); - let _for = self.body.core.notices_for(); - // Its unit of command predication takes what it encoded (`predication.rs`): as its core - // ends, under the one lock that takes, where its command buffer has no record. - let unit_work = self.body.captures.unpredicated_work(); - if unit_work.is_none() { - self.end_predication()?; - } - self.body.table.let_go_all(&mut self.body.core); - let Body { - core, - dispatch_type, - residency, - log, - live, - .. - } = *self.body; - // Its log, which its command buffer keeps where a rebind may need it (`replay.rs`). - let replay = log.map(|log| Replay::Compute { dispatch_type, log }); - // Its core's box, emptied as the core ends, and its bind state go on to its command - // buffer's next compute encoder (`compute/live.rs`). What it made resident joins its - // command buffer's (`residency.rs`), and is its own (`CommandBuffer::ended_encoders`). - EncoderCore::end_with_replay( - core, - EncoderKind::Compute, - (Some(residency), Some(Parking::new(live))), - replay, - unit_work, - ) - } - - /// The threadgroup size `threads` of a dispatch in `call` with the pipeline state set, or - /// `None` where plain Metal runs nothing for it (an M4; its API validation asserts): a size, - /// the axes' wrapping 64-bit product, of 0 or above Metal's limit for the state (Apple's 1024, - /// or the function's or the descriptor's lower one). A size within Metal's limit but above the - /// state's `max_total_threads_per_threadgroup`, where this device's limit is lower, Metal runs: - /// it is the device's gap, which the binder refuses typed (`Bind`, `Unsupported`) where the - /// dispatch is planned, never a dispatch run as nothing. Metal runs the axes modulo `2^32` - /// where the size passes (`2^62 + 1` by 4 ran 4 threads), and nothing where those axes hold - /// other threads than the size counts (an M4 under macOS 27.0.1, both dispatch forms: `2^64 - - /// 1` by `2^64 - 1`, `2^64 - 2` by `2^64 - 2`, and `2^64 - 1` by 1 by `2^64 - 1`, of sizes 1, 4 - /// and 1). The two counts agree modulo `2^32`, so such axes hold at least - /// `2^32` threads, past any state's limit: a threadgroup the GPU cannot run. - /// - /// Refused: no pipeline state set (plain Metal faults). - fn threadgroup(&self, call: &'static str, threads: Size) -> Result, Error> { - let Some(pipeline) = &self.body.pipeline else { - return Err(invalid(call, Problem::NoPipelineState)); - }; - let total = threads.wrapping_volume(); - let limit = pipeline.metal_max_total_threads_per_threadgroup(); - if total == 0 || total > u64::from(limit) { - return Ok(None); - } - let axes = threads.truncated(); - if axes.iter().map(|&axis| u64::from(axis)).product::() != total { - return Ok(None); - } - // A size other than the state's required one runs as given, as plain Metal runs it - // (Metal's API validation stops it). - Ok(Some(axes)) - } - - /// Whether the kernel statically uses a texture slot that holds a memoryless texture, a - /// texture buffer's too: plain Metal fails the command buffer of such a dispatch, of no - /// threadgroups or of an empty threadgroup too, the encoder's run of compute encoders running - /// nothing (`CommandBufferError::InvalidResource`, an M3 Max under macOS 27.0.1), so the - /// encoder fails it and the dispatch records nothing (`EncoderCore::fail_memoryless_use`). - fn fails_on_memoryless(&mut self) -> bool { - let uses = (self.body.pipeline.as_ref()).is_some_and(|state| { - self.body - .table - .uses_memoryless(state.interface(), Stage::Kernel) - }); - if uses { - self.body.core.fail_memoryless_use(); - } - uses - } - - /// Plan, bind, and record `dispatch` with the encoder's tables (the module's steps 2 to 4), - /// with every texture the encoder's heaps hold resident. - fn dispatch(&mut self, call: &'static str, dispatch: Dispatch) -> Result<(), Error> { - self.sync_heaps(); - let reads = self - .body - .pipeline - .as_ref() - .is_some_and(ComputePipelineState::reads_texture_handles); - self.dispatch_resident(call, dispatch)?; - self.command_encoded(reads); - self.body.dispatches += 1; - if let Some(times) = self.body.core.times() { - times.worked(); - } - Ok(()) - } - - /// [`dispatch`](Self::dispatch) with the heaps' textures resident. - fn dispatch_resident(&mut self, call: &'static str, dispatch: Dispatch) -> Result<(), Error> { - let Some(pipeline) = &self.body.pipeline else { - return Err(invalid(call, Problem::NoPipelineState)); - }; - if self.body.indirect_stage_in.is_some() { - let pipeline = pipeline.clone(); - return self.defer_dispatch(call, pipeline, HostDispatch::Direct(dispatch)); - } - let tables = DispatchTables { - pipeline, - table: &self.body.table, - threadgroup_lengths: &self.body.threadgroup_lengths, - imageblock: self.body.imageblock, - stage_in_region: self.body.stage_in_region, - residency: &self.body.residency, - forms: BufferForms::Bound, - }; - record( - &mut self.body.core, - &tables, - call, - Counts::Direct(dispatch), - Some((self.body.dispatches, &mut *self.body.live)), - ) - .map(drop) - } -} - -/// What a dispatch binds and runs with: a compute encoder's tables, or an indirect command's -/// (`indirect_execute.rs`). -pub(super) struct DispatchTables<'a> { - pub(super) pipeline: &'a ComputePipelineState, - /// The buffers, textures and samplers, with each buffer's attribute stride where it is not - /// its layout's own (`setBuffer:offset:attributeStride:atIndex:`, an indirect command's - /// `setKernelBuffer:offset:attributeStride:atIndex:`). - pub(super) table: &'a ArgumentTable, - pub(super) threadgroup_lengths: &'a BTreeMap, - pub(super) imageblock: ImageblockSize, - pub(super) stage_in_region: Option, - pub(super) residency: &'a Residency, - /// The buffer forms its variant takes: the large-buffer form for an indirect command the - /// GPU may write. - pub(super) forms: BufferForms, -} - -impl DispatchTables<'_> { - /// The address-mode maps the dispatch binds its runtime samplers with (`address_map.rs`). - fn sampler_maps(&self) -> Result { - address_map::sampler_maps( - self.pipeline.base_layout(), - &[(Stage::Kernel, self.table)], - Some(self.residency), - ) - .map_err(Error::NotImplemented) - } - - /// The tables as a bind state, with the device's argument samplers and the live - /// visible-function tables the pipeline state made. The imageblock size is the plan's only for - /// a kernel with an explicit imageblock; one without plans with none, so its shape is the one - /// the executor computes for it. - fn bind_state( - &self, - argument_samplers: &[SamplerState], - function_tables: &[VisibleFunctionTable], - ) -> BindState { - // A buffer where the kernel reads a table reads as a null table. - let views = self.pipeline.at_bind_views(); - let mut table = - (self.table).stage_table_reading(Stage::Kernel, self.pipeline.interface(), views); - table.threadgroup_lengths = self.threadgroup_lengths.clone(); - let mut state = BindState::default(); - state.stages.insert(Stage::Kernel, table); - state.view_base_alignment = views.alignment(); - state.uniform_views_at_residual = views.at_residual(); - if self.pipeline.imageblock_cell_bytes().is_some() { - state.imageblock_size = self.imageblock; - } - state.stage_in_region = self.stage_in_region; - state.used_resources = self.residency.used_resources(); - state.used_in_token_order = true; - state.resident_apart = true; - state.argument_samplers = heap_sets::listed(argument_samplers); - state.function_tables = function_tables - .iter() - .map(VisibleFunctionTable::listed) - .collect(); - state.heap_placement = HeapPlacement::ResourceId; - state - } -} - -/// Make, on `device`, the variants a dispatch of `tables` in their buffer forms may run on, -/// whatever its threadgroup size (`ComputePipelineState::prepare`): in the large-buffer form -/// whatever buffers it binds. And the device's neutrals their plans may bind -/// (`binding::make_neutrals`). -pub(super) fn prepare_variants( - device: &Device, - tables: &DispatchTables<'_>, -) -> Result>, Error> { - let mut state = tables.bind_state( - &device.argument_samplers(), - &tables.pipeline.function_tables(), - ); - tables.sampler_maps()?.apply(&mut state); - let prepared = tables.pipeline.prepare(&state.shape(), tables.forms)?; - let mut variants = Vec::with_capacity(prepared.len()); - for (variant, plan) in prepared { - binding::make_neutrals(device, &plan)?; - variants.push(variant); - } - Ok(variants) -} - -/// Plan, bind, and record `dispatch` with `tables` into `core` (the module's steps 2 to 4), for -/// Metal's `call`: an execution's or a host step's, which waits for its pipelines' makings. -pub(super) fn record_dispatch( - core: &mut EncoderCore, - tables: &DispatchTables<'_>, - call: &'static str, - dispatch: Dispatch, -) -> Result<(), Error> { - record(core, tables, call, Counts::Direct(dispatch), None).map(drop) -} - -/// Where a recorded dispatch's group counts come from. -enum Counts<'a> { - /// The dispatch's own, each region's (`vkCmdDispatch`). - Direct(Dispatch), - /// Metal's indirect arguments, which the flat or folded variant's preprocess reads on the - /// device (`indirect_dispatch.rs`). - Flat(FlatCall<'a>), -} - -/// The variant an indirect dispatch's GPU path runs on, its plan for `shape`, and the -/// preprocess's description (`indirect_dispatch.rs`): the kernel's flat variant, else, for the -/// threadgroups form, its folded variant of the call's threadgroup size. `None` where neither -/// takes the dispatch, which then takes its host step. -fn settle_indirect( - pipeline: &ComputePipelineState, - call: FlatCall<'_>, - shape: &BindShape, -) -> Result, Arc, FlatIndirect)>, Error> { - if let Some(indirect) = call.indirect(pipeline) { - let local = indirect.threads_per_threadgroup; - let flat = flat_dispatch(local); - if let Some((variant, plan)) = pipeline.settle_flat(shape, local, &flat, false)? { - return Ok(Some((variant, plan, indirect))); - } - } - let Some(indirect) = call.folded(pipeline) else { - return Ok(None); - }; - let local = indirect.threads_per_threadgroup; - Ok(pipeline - .settle_folded(shape, local)? - .map(|(variant, plan)| (variant, plan, indirect))) -} - -/// The flat variant (`VariantKey::flat_grid`) a direct `dispatchThreads:` runs on, with its plan -/// for `shape`: one Vulkan dispatch of the call's own threadgroup size, every invocation taking -/// the grid thread it counts to and one past the grid's last returning before the body, in place -/// of the interior and ragged-edge regions a split plans — Metal's own one dispatch, on one -/// `VkPipeline`, with no barrier between regions and no `Degradation::SplitDispatch`. -/// -/// So a grid narrower than one threadgroup on an axis, which the split runs as one region of the -/// grid's own size, a `VkPipeline` of each width, takes the flat form's one `VkPipeline` of the -/// call's size too: on a guest's run on an RX 7900 XTX, a kernel dispatched at 64 such widths -/// made 185,566 `VkPipeline`s in 45 s while its variant kept 32 (`pipeline::REGION_PIPELINES`). -/// -/// A kernel that observes its partition through its simdgroups alone -/// (`KernelFacts::partition_simdgroups`: a simdgroup barrier, function or lane builtin, and nothing -/// of its threadgroup) runs a one-row grid in threadgroups of one row on the flat variant of the -/// call's threadgroups (`VariantKey::call_threadgroups`): its workgroups are Metal's threadgroups, -/// its simdgroups Metal's, the last one's lanes past the grid returned before the body. So a -/// kernel compiled once does not compile a second `VkPipeline` for its ragged edge. -/// -/// `None`, so the dispatch keeps its exact split, where its grid is already a whole number of -/// threadgroups on every axis (the split is one region of the call's size, which the flat form -/// cannot better) or is empty, where the kernel observes its threadgroup partition (through its -/// simdgroups alone, where the grid or its threadgroups are not one row, or where the module would -/// hold a workgroup barrier or emulate its simdgroups) or the device -/// reaches no memory by device address -/// (the compile layer's refusal, which the state remembers), where the flat form cannot cover the -/// grid within the device's `maxComputeWorkGroupCount`, or in the large-buffer form, whose key -/// `settle_flat` does not take. -fn flat_direct( - pipeline: &ComputePipelineState, - shape: &BindShape, - dispatch: &Dispatch, - forms: BufferForms, -) -> Result, Arc)>, Error> { - let Dispatch::Threads { - threads_per_group, .. - } = *dispatch - else { - return Ok(None); - }; - if forms != BufferForms::Bound { - return Ok(None); - } - // The split's regions per axis: its interior where whole threadgroups fill it, and an edge of - // the remainder, of a local size of its own. A remainder on any axis, the edge alone where the - // grid is narrower than one threadgroup, is what the flat form replaces with its one region. - // The grid's class says so (`GridClass`), as a later dispatch of the class asks of it. - let Some(class) = GridClass::of(dispatch).filter(|class| !class.whole()) else { - return Ok(None); - }; - // The variant of any threadgroups, else, for one row in threadgroups of one row, the call's. - let mut settled = pipeline.settle_flat(shape, threads_per_group, dispatch, false); - if class.one_row() && matches!(settled, Ok(None)) { - settled = pipeline.settle_flat(shape, threads_per_group, dispatch, true); - } - match settled { - Ok(settled) => Ok(settled), - // A grid the flat form cannot cover within the device's group-count limits: the split - // covers it exactly, region by region. - Err(Error::Bind(BindError::Unsupported(_))) | Err(Error::Unsupported(_)) => Ok(None), - Err(error) => Err(error), - } -} - -/// The partial-threadgroups variant (`VariantKey::partial_threadgroups`) a direct -/// `dispatchThreads:` runs on where no flat variant does, with its plan for `shape`: the -/// threadgroups its threads fill, rounded up, at the call's threadgroup size, one Vulkan dispatch -/// per chunk of group counts, the last threadgroup along an axis answering Metal's partial -/// threadgroup's threads (`lower::dispatch`'s partial threadgroups of a kernel), in place of the -/// interior and edge regions a split plans, each edge a `VkPipeline` of its remainder's size. So a -/// kernel that observes its threadgroup partition runs every ragged grid of a threadgroup size on -/// one `VkPipeline` beside its state's, and with no `Degradation::SplitDispatch` where its group -/// counts fit the device's. -/// -/// **A large kernel's whole grids.** A kernel whose base module holds `compile_memory`'s -/// `COUNTED_WORDS` (65,536) SPIR-V words or more runs its whole grids there too, every thread live -/// (`ComputePipelineState::whole_on_partial`): a `dispatchThreads:` of a whole number of -/// threadgroups and a `dispatchThreadgroups:`, where its ragged grids of the same form run on the -/// variant (no flat variant runs them, [`flat_direct`]). So one `VkPipeline` of a threadgroup size -/// runs all its direct dispatches, where the plain pipeline's for its whole grids would be a second -/// driver compile of the module: on a guest's run on an RX 7900 XTX, the plain pipeline's compile -/// of a kernel of 2,415,531 words was 26.9 s of a 39.8 s warm pass. Its cost on the GPU, measured -/// once on the same GPU (RADV) over 1,048,576 threads in threadgroups of 64, the fastest of three -/// command buffers of eight dispatches each: 0.997 to 1.020 times the plain pipeline's time over -/// four straight-line kernels, three of 40,000 fused multiply-adds (behind a threadgroup barrier -/// and a simdgroup sum, a threadgroup barrier alone, or neither) and a light one, their words the -/// plain pipeline's. A smaller kernel's whole grids keep the plain pipeline and its speed: its -/// compile is cheap. Both forms give the same answers, so no switch chooses between them. -/// -/// `None`, so the dispatch keeps its exact split or its plain pipeline, where its grid is empty or, -/// but for such a kernel, a whole number of threadgroups, in the large-buffer form, where the -/// variant would emulate its simdgroups (`ComputePipelineState::settle_partial`), where the -/// compile layer refuses the kernel the variant, which the state remembers, or where the device's -/// limits cannot hold its threadgroups. -fn partial_direct( - pipeline: &ComputePipelineState, - shape: &BindShape, - dispatch: &Dispatch, - forms: BufferForms, -) -> Result, Arc)>, Error> { - if forms != BufferForms::Bound { - return Ok(None); - } - // An empty grid takes none; the grid's class (`GridClass`) chooses as a later dispatch of the - // class asks of it. - let (local, class) = match (*dispatch, GridClass::of(dispatch)) { - ( - Dispatch::Threads { - threads_per_group, .. - } - | Dispatch::Threadgroups { - threads_per_group, .. - }, - Some(class), - ) => (threads_per_group, class), - _ => return Ok(None), - }; - // A grid of one row in threadgroups of one row, which the call's flat variant runs for a - // kernel that observes its partition through its simdgroups alone (`flat_direct`). - if class.whole() && !pipeline.whole_on_partial(class.one_row()) { - return Ok(None); - } - match pipeline.settle_partial(shape, local, dispatch) { - Ok(settled) => Ok(settled), - // Threadgroups the device's limits cannot hold: the split's own refusal answers. - Err(Error::Bind(BindError::Unsupported(_))) => Ok(None), - Err(error) => Err(error), - } -} - -/// Whether `dispatch` is a direct dispatch of whole threadgroups: a `dispatchThreadgroups:`, or a -/// `dispatchThreads:` whose grid is a whole number of threadgroups on every axis. -fn whole_grid(dispatch: &Dispatch) -> bool { - match *dispatch { - Dispatch::Threadgroups { .. } => true, - Dispatch::Threads { - threads, - threads_per_group, - } => (0..3).all(|i| threads[i].is_multiple_of(threads_per_group[i])), - _ => false, - } -} - -/// The variant a direct dispatch of a bind state of `shape` in `forms` runs on, and its plan for -/// `shape`: its flat variant where it takes one ([`flat_direct`]), else its partial-threadgroups -/// variant where it takes one ([`partial_direct`]), else `ComputePipelineState::settle`'s. A program's dispatch plans so ([`plan_now`]), and so does a -/// warm pass's dispatch of a record (`pipeline/dispatch_record.rs`), so both ask for the same -/// variant and its regions' keys. A program's dispatch, of the bind state and bound formats -/// `bound`, in the bound form, then takes that variant's unit-axes variant where its plan offers -/// one and it is made (`ComputePipelineState::unit_axes`); a warm pass makes that one beside it. -pub(crate) fn settle_direct( - pipeline: &ComputePipelineState, - shape: &BindShape, - dispatch: &Dispatch, - forms: BufferForms, - bound: Option<(&BindState, BoundFormats<'_>)>, -) -> Result { - let settled = match flat_direct(pipeline, shape, dispatch, forms)? { - Some(flat) => flat, - None => match partial_direct(pipeline, shape, dispatch, forms)? { - Some(partial) => partial, - None => pipeline.settle(shape, dispatch, forms)?, - }, - }; - match (bound, forms) { - (Some(bound), BufferForms::Bound) => pipeline.unit_axes(settled, (shape, dispatch), bound), - _ => Ok(Direct::of(settled)), - } -} - -/// Whether a dispatch of `objects`'s variant records in a `VkCommandBuffer` of its own, its -/// pipelines made: where its layout bakes samplers, which the device's driver loses after a copy -/// in the same `VkCommandBuffer` (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`). -fn apart_samplers(device: &Device, objects: &VariantObjects) -> bool { - objects.bakes_samplers() - && device - .properties() - .driver_defects - .contains(&RuntimeDriverDefect::ImmutableSamplersLostAfterCopies) -} - -/// What a dispatch settles before it binds ([`settle_dispatch`], [`settle_live`]): the device's -/// sampler states it lists (less those at IDs no set-1 sampler array of the variant holds, -/// `unlisted` saying so: `heap_sets::fit_samplers`), where it took them -/// (`sampler::ArgumentSamplers`), the visible-function tables its state made, -/// its runtime samplers' address-mode maps, and what it planned: the state's shape, and the variant -/// it runs on with its plan, for `planned.dispatch`. Its bind state is apart: the encoder's kept one -/// (`compute/live.rs`), or one of its own. -pub(super) struct SettledDispatch { - /// `None` where it took none: an encoder's dispatch whose kept state lists every live state - /// at the count of their slots' changes that holds, of a variant with no set-1 arrays, or an - /// entry parked in its command buffer ([`DispatchMemo::unlist_samplers`]). - argument_samplers: Option>, - function_tables: Vec, - unlisted: Option<(u64, u64)>, - sampler_maps: SamplerMaps, - planned: Arc, -} - -/// A flat indirect call and its preprocess's description (`indirect_dispatch.rs`). -type Flat<'a> = Option<(FlatCall<'a>, FlatIndirect)>; - -/// What a dispatch of `tables` that keeps no bind state (an indirect command's, a host step's), -/// of `direct` group counts or of a flat indirect call (`gpu`), settles ([`SettledDispatch`]) -/// with `function_tables`, its state's, and `samplers`, the device's sampler states, and the bind -/// state it settled, made whole: the flat call's preprocess description beside it, and `None` where -/// the GPU path does not take an indirect dispatch (`indirect_dispatch.rs`). A direct dispatch -/// whose bind state has the shape one its pipeline state planned lately for the same dispatch and -/// buffer forms, compared in place (`ComputePipelineState::planned_of`), takes what that one -/// planned ([`Planned`]); one that plans keeps what it planned for the next. -fn settle_dispatch<'a>( - tables: &DispatchTables<'_>, - (direct, gpu): (Option, Option>), - function_tables: Vec, - samplers: Vec, -) -> Result)>, Error> { - let pipeline = tables.pipeline; - // The device's sampler states, less those at IDs no set-1 sampler array of the variant - // holds (each array has the variant's heap capacity of elements): a degradation where - // the variant has sampler arrays, and nothing reads them where it has none. - let mut argument_samplers = samplers; - let mut unlisted = None; - // Its runtime samplers' address modes as the textures they sample map them. - let sampler_maps = tables.sampler_maps()?; - let (state, planned, as_before, flat) = loop { - let mut state = tables.bind_state(&argument_samplers, &function_tables); - sampler_maps.apply(&mut state); - let last = direct.and_then(|dispatch| pipeline.planned_of(&state, &dispatch, tables.forms)); - let (planned, as_before, flat) = match last { - Some(last) => (last, true, None), - None => { - let shape = Arc::new(state.shape()); - let bound = (&state, tables); - match plan_now(pipeline, tables.forms, shape, (direct, gpu), bound)? { - Some((planned, flat)) => (planned, false, flat), - None => return Ok(None), - } - } - }; - let set = planned.variant.pipeline().layout.sets.get(1); - if heap_sets::fit_samplers(set, &mut argument_samplers, &mut unlisted) { - break (state, planned, as_before, flat); - } - }; - planned_as_before(pipeline, &planned, as_before, direct); - let settled = SettledDispatch { - argument_samplers: Some(argument_samplers), - function_tables, - unlisted, - sampler_maps, - planned, - }; - Ok(Some((state, settled, flat))) -} - -/// [`settle_dispatch`] of a compute encoder's own dispatch, through the encoder's kept bind state -/// `live`, brought in place (`LiveDispatch::refresh`), with the device's sampler states `samplers` -/// taken only where the dispatch needs them (`sampler::ArgumentSamplers`), at `changed` changes of -/// their slots: where the kept state lists every live state at that count, of a variant with no -/// set-1 arrays, it takes none. The state's shape kept where nothing brought in may have changed -/// it, else found among those the pipeline state planned for lately or made -/// (`LiveDispatch::shape`), and what it planned for that shape, the very one looked for first -/// (`ComputePipelineState::planned_for`). Where `refreshed` holds the table's samplers' maps, the -/// state was brought in place with them and `samplers` already (`LiveDispatch::settled_across`'s -/// `Across::Refreshed`), which it is not again. Beside what it settled, the count of slot changes -/// its listing is of: the states', where it took them. -fn settle_live<'a>( - live: &mut LiveDispatch, - tables: &DispatchTables<'_>, - (direct, gpu): (Option, Option>), - function_tables: Vec, - ((changed, mut samplers), refreshed): ((u64, ArgumentSamplers), Option), -) -> Result, u64)>, Error> { - let pipeline = tables.pipeline; - let device = pipeline.generation(); - let counts = device.shared().counts.thread(); - let mut unlisted = None; - let (sampler_maps, mut in_place) = match refreshed { - Some(maps) => (maps, true), - None => (tables.sampler_maps()?, false), - }; - let (planned, as_before, flat) = loop { - if !in_place { - let listing = (changed, &mut samplers); - live.refresh(tables, &sampler_maps, listing, &function_tables, counts); - } - in_place = false; - let shape = live.shape(counts, |state| pipeline.planned_shape(state)); - let last = - direct.and_then(|dispatch| pipeline.planned_for(&shape, &dispatch, tables.forms)); - let (planned, as_before, flat) = match last { - Some(last) => (last, true, None), - None => { - let bound = (&*live.state, tables); - match plan_now(pipeline, tables.forms, shape, (direct, gpu), bound)? { - Some((planned, flat)) => (planned, false, flat), - None => return Ok(None), - } - } - }; - let set = planned.variant.pipeline().layout.sets.get(1); - if samplers.fit(set, &mut unlisted) { - break (planned, as_before, flat); - } - // A variant of set-1 arrays writes the listed states' elements: it takes the states, - // listed again against them (alike, where the kept listing is current). - samplers.take(device); - }; - planned_as_before(pipeline, &planned, as_before, direct); - let listed = samplers.taken_at().unwrap_or(changed); - let settled = SettledDispatch { - argument_samplers: samplers.into_states(), - function_tables, - unlisted, - sampler_maps, - planned, - }; - Ok(Some((settled, flat, listed))) -} - -/// What a dispatch of a bind state of `shape` in `forms` plans now, of `direct` group counts or of -/// a flat indirect call (`gpu`): the direct dispatch's variant as [`settle_direct`] settles it for -/// the bind state `bound`'s, binding what `bound`'s tables bind; the indirect one's flat or folded -/// variant, with its preprocess description, or `None` where neither takes it, which then takes -/// its host step. -fn plan_now<'a>( - pipeline: &ComputePipelineState, - forms: BufferForms, - shape: Arc, - (direct, gpu): (Option, Option>), - (state, tables): (&BindState, &DispatchTables<'_>), -) -> Result, Flat<'a>)>, Error> { - match (direct, gpu) { - (Some(dispatch), _) => { - // What the dispatch binds, as its specialized notices name it. - let stages = [(Stage::Kernel, tables.table)]; - let bound = binding::Tables::new(&stages).with_residency(tables.residency); - let formats: BoundFormats<'_> = &|slot| bound.bound_format(slot); - let settled = - settle_direct(pipeline, &shape, &dispatch, forms, Some((state, formats)))?; - // Every region of the call's threadgroup size, so the grid's class names the variant - // and plan (`GridClass`): not a ragged grid's exact split. - let key = settled.variant.key(); - let grids = GridClass::of(&dispatch).filter(|class| { - forms == BufferForms::Bound - && (key.flat_grid || key.partial_threadgroups || class.whole()) - }); - let planned = Planned { - key: shape.key_beside_used(), - shape, - dispatch, - forms, - grids, - variant: settled.variant, - plan: settled.plan, - meanwhile: settled.meanwhile, - made: OnceLock::new(), - twins: binding::TwinProofs::default(), - }; - Ok(Some((Arc::new(planned), None))) - } - (None, Some(gpu)) => { - let Some((variant, plan, indirect)) = settle_indirect(pipeline, gpu, &shape)? else { - return Ok(None); - }; - let planned = Planned { - key: shape.key_beside_used(), - shape, - dispatch: flat_dispatch(indirect.threads_per_threadgroup), - forms, - grids: None, - variant, - plan, - meanwhile: false, - made: OnceLock::new(), - twins: binding::TwinProofs::default(), - }; - Ok(Some((Arc::new(planned), Some((gpu, indirect))))) - } - (None, None) => Err(internal("a dispatch of no counts")), - } -} - -/// Count a direct dispatch that took what its pipeline state planned before (`as_before`), for -/// another grid of its class where it was (`Planned::grids`), or keep what one planned now for -/// the next, but where it is for now alone (`Planned::meanwhile`); a flat dispatch's variant and -/// plan are the flat path's, none a direct one takes. -fn planned_as_before( - pipeline: &ComputePipelineState, - planned: &Arc, - as_before: bool, - direct: Option, -) { - match (as_before, direct) { - (true, direct) => { - let counts = (pipeline.generation().shared().counts).thread(); - counts.dispatch_planned_as_before(); - if direct.is_some_and(|dispatch| dispatch != planned.dispatch) { - counts.dispatch_planned_across_grids(); - } - } - (false, Some(_)) if !planned.meanwhile => pipeline.keep_planned(Arc::clone(planned)), - (false, _) => {} - } -} - -/// What a compute encoder's last dispatch that settled settled ([`SettledDispatch`]), its -/// commands, and the `VkPipeline`s its regions found made, kept with what they are a function of -/// beside the encoder's kept bind state, which that dispatch brought in place and binds -/// (`compute/live.rs`): a later dispatch of the encoder of the same inputs settles, plans and -/// instantiates nothing again, brings no state in place and looks no pipeline up -/// (`WorkCounts::dispatches_settled_as_before`). Exact: -/// -/// - **The bind state** is a function of the pipeline state (its interface, view base alignment -/// and imageblock among it), of what the table binds (its stamp: every call that may change it -/// draws a new one, `argument_table::Stamp`), of what each bound object's binding reads of it -/// (a texture's and a sampler's facts, fixed as it is made; a buffer's length, base and -/// addresses, which only a no-copy buffer's move changes: `buffer::host_cells_moved`), of the -/// threadgroup lengths, imageblock size and stage-in region set, of what the encoder made -/// resident (its generation, which every change of it draws anew, `Residency::generation`; -/// what a used resource states of it beyond that, its buffers' addresses, which only a no-copy -/// buffer's move changes, and whether each indirect command buffer holds its ID's slot, which a -/// buffer made later with the ID takes: `Residency::holds_slots_as`), of the device's live -/// sampler states (`DeviceShared::sampler_slots_changed`), of the state's visible-function tables -/// (none: a dispatch of a state that made one takes no memo), and of the sampler maps, which -/// are the table's and the residency's. The kept state is this entry's: a dispatch that brings -/// it in place keeps its own entry or none (`LiveDispatch::let_go`). -/// - **The variant and plan** are `ComputePipelineState::settle`'s of the shape, the dispatch and -/// the buffer forms (the entry keeps the dispatch: what it planned may be of another grid of -/// its class, `Planned::grids`); **the commands** are the plan's instantiation for the state and -/// the dispatch, their regions keyed by the variant for the device (`Variant::keyed_regions`). -/// - **A region's `VkPipeline`** found made is its variant's for the region's key, which its -/// making never changes; regions not all made are looked up again at the next dispatch. -/// - **Another encoder's table.** The entry goes on with the state to the command buffer's next -/// compute encoder (`compute/live.rs`'s **Parked in its command buffer**), and a dispatch there -/// whose new table, read, brings in the very state the entry settled (no value of any kind -/// changed, the samplers' maps the same), with every other input above the same, takes it under -/// the new table's stamp (`WorkCounts::dispatches_settled_across_encoders`). -/// - **A dispatch that settles again** (another table, another residency) takes the variant, the -/// plan and the made `VkPipeline`s of one of its pipeline state's latest direct dispatches that -/// planned, where its bind state has that one's shape ([`Planned`], [`settle_live`]): so does one -/// whose buffers' offsets alone moved, an encoder's first dispatch of the state, and one of -/// another grid of that one's class where its plan names its variant for the grid -/// (`pipeline::GridClass`, `WorkCounts::dispatches_planned_across_grids`). -#[derive(Default)] -pub(super) struct DispatchMemo(Option); - -/// A [`DispatchMemo`]'s entry and what it was settled under. -pub(super) struct KeptDispatch { - /// The pipeline state, held so that no other state is this one while the entry is kept. - pipeline: ComputePipelineState, - /// The dispatch it settled, whose grid its commands run: what it planned may be of another - /// grid of its class (`Planned::grids`). - dispatch: Dispatch, - stamp: Stamp, - threadgroup_lengths: BTreeMap, - imageblock: ImageblockSize, - stage_in_region: Option, - forms: BufferForms, - /// The residency's generation (`Residency::generation`). - residency: u64, - /// `buffer::host_cells_moved` and `DeviceShared::sampler_slots_changed` as it was settled. - counted: (u64, u64), - settled: SettledDispatch, - /// Its commands: those the encoder's kept state keeps where they are of its planned - /// ([`Instantiated`]), else instantiated. - commands: OnceLock>, - /// Each region's `VkPipeline`, where all were found made, each its own key's: never a key's - /// residual form, which serves a dispatch only while its own is made. - made: OnceLock>>, -} - -impl DispatchMemo { - /// Whether the entry is of a dispatch of `tables` and `dispatch` at `counted` moves and - /// sampler slot changes, `state` the kept bind state it settled. - fn holds( - &self, - state: &BindState, - tables: &DispatchTables<'_>, - dispatch: &Dispatch, - counted: (u64, u64), - ) -> bool { - (self.0.as_ref()).is_some_and(|kept| kept.stamp == tables.table.stamp()) - && self.holds_but_stamp(state, tables, dispatch, counted) - } - - /// [`holds`](Self::holds) in every input but the table's stamp: a table of another encoder - /// of the command buffer (`LiveDispatch::settled_across`). - fn holds_but_stamp( - &self, - state: &BindState, - tables: &DispatchTables<'_>, - dispatch: &Dispatch, - counted: (u64, u64), - ) -> bool { - self.0.as_ref().is_some_and(|kept| { - kept.pipeline == *tables.pipeline - && kept.dispatch == *dispatch - && kept.counted == counted - && kept.forms == tables.forms - && kept.imageblock == tables.imageblock - && kept.stage_in_region == tables.stage_in_region - && kept.threadgroup_lengths == *tables.threadgroup_lengths - && kept.residency == tables.residency.generation() - && (tables.residency).holds_slots_as(&state.used_resources) - }) - } - - /// Keep `settled`, a dispatch of `tables` and `dispatch` at `counted` moves and sampler slot - /// changes, in place of the entry. - fn keep( - &mut self, - (tables, dispatch): (&DispatchTables<'_>, Dispatch), - counted: (u64, u64), - settled: SettledDispatch, - ) { - self.0 = Some(KeptDispatch { - pipeline: tables.pipeline.clone(), - dispatch, - stamp: tables.table.stamp(), - threadgroup_lengths: tables.threadgroup_lengths.clone(), - imageblock: tables.imageblock, - stage_in_region: tables.stage_in_region, - forms: tables.forms, - residency: tables.residency.generation(), - counted, - settled, - commands: OnceLock::new(), - made: OnceLock::new(), - }); - } - - /// The entry, where one is kept. - fn entry(&self) -> Option<&KeptDispatch> { - self.0.as_ref() - } - - /// The entry goes on under `stamp`, the stamp of a table that brings in the very state it - /// settled (`LiveDispatch::settled_across`), its sampler states listed again where its - /// parking let them go ([`unlist_samplers`](Self::unlist_samplers)) and its variant has set-1 - /// arrays, which write their elements: `samplers`, taken from `device` where they were not, - /// at the count of sampler slot changes the entry was settled at, so the very states it - /// listed (`DeviceShared::sampler_slots_changed`). - fn restamp(&mut self, stamp: Stamp, (samplers, device): (&mut ArgumentSamplers, &Device)) { - if let Some(kept) = &mut self.0 { - kept.stamp = stamp; - let settled = &mut kept.settled; - let arrays = settled - .planned - .variant - .pipeline() - .layout - .sets - .get(1) - .is_some(); - if arrays && settled.argument_samplers.is_none() { - settled.argument_samplers = Some(samplers.take(device).clone()); - } - } - } - - /// Let go of the device's sampler states the entry listed, as its encoder's state parks in its - /// command buffer, which holds none of them (`compute/live.rs`'s `Parked`): a dispatch that - /// takes the entry lists them again ([`restamp`](Self::restamp)), at the same count of - /// sampler slot changes, which every other use of the entry compares first. - fn unlist_samplers(&mut self) { - if let Some(kept) = &mut self.0 { - kept.settled.argument_samplers = None; - } - } -} - -/// The commands a compute encoder's last direct dispatch that instantiated made (its regions keyed -/// for the device: `Variant::keyed_regions`), kept with the encoder's bind state -/// (`compute/live.rs`), whose kept state goes on to the next compute encoder: a later -/// dispatch, of the encoder or a later one, of the same grid that takes the very [`Planned`] that -/// one took takes them while the state binds the values they read, instantiating nothing -/// (`WorkCounts::dispatches_instantiated_as_before`). Exact: -/// -/// - **What they are a function of.** `BindingPlan::instantiate_dispatch` of the plan, for the -/// bind state and the dispatch, keyed by the variant for the device. The planned names the -/// plan and the variant, and the shape they were settled for, which is the state's -/// (`settle_live`); the entry keeps the dispatch, as the planned may serve other grids of its -/// class (`Planned::grids`); the device is the state's, as a kept state is its device's -/// (`SpareLiveDispatches`). -/// - **The planned, by identity.** The entry holds it weakly: while the entry lasts, no other -/// planned lies where it lay, so one there is the very one. It holds none alive, nor anything -/// else (the commands are values). -/// - **The state, by the kinds of values that changed.** Each bringing of the state in place -/// notes the kinds of its values it changed (`live_bind::ValueKinds`: the bindings of each slot -/// class, and every other field), and a kind the plan's commands may read lets the entry go -/// (`BindingPlan::dispatch_reads`: every field and buffer binding; texture bindings only where -/// the plan reads a texel buffer, a texture's in-place planes or a handle table's member bound -/// at a slot; sampler bindings never). Within one planned the shape is one, so a kind the plan -/// does not read changed only in values its commands do not read: a program that binds two -/// textures of one shape in turn, an encoder for each dispatch, keeps them. Checked in builds -/// with debug assertions, where each dispatch that takes them instantiates again and compares. -/// - **Their storage, kept where the entry goes.** Commands no longer of the state stay as the -/// storage the next direct dispatch's instantiation writes over -/// (`BindingPlan::instantiate_dispatch_into`, `WorkCounts::dispatches_instantiated_in_place`) -/// where nothing else holds them (the memo's entry they were taken into goes before: a dispatch -/// that instantiates settled anew), so a program that binds a buffer at another offset at each -/// dispatch, an encoder for each, makes its commands' lists once. Exact: the method sets every -/// field as `instantiate_dispatch` does, which builds with debug assertions instantiate again -/// to compare. -#[derive(Default)] -pub(super) struct Instantiated(Option); - -/// An [`Instantiated`]'s entry: its commands, and what they are of, where they still are. -struct KeptCommands { - /// `None` where a value they may read moved since: the commands are then storage alone. - of: Option, - commands: Arc, -} - -/// What a [`KeptCommands`]' commands are of. -struct CommandsOf { - planned: Weak, - /// The dispatch they run: what it planned may be of another grid of its class - /// (`Planned::grids`). - dispatch: Dispatch, - /// The kinds of the state's values the commands may read. - reads: ValueKinds, -} - -impl CommandsOf { - fn new(planned: &Arc, dispatch: Dispatch) -> CommandsOf { - CommandsOf { - planned: Arc::downgrade(planned), - dispatch, - reads: ValueKinds::dispatch_reads(&planned.plan), - } - } -} - -impl Instantiated { - /// The commands kept, where they are of `planned` and `dispatch`. - fn of(&self, planned: &Arc, dispatch: &Dispatch) -> Option<&Arc> { - let kept = self.0.as_ref()?; - let of = kept.of.as_ref()?; - let same = std::ptr::eq(of.planned.as_ptr(), Arc::as_ptr(planned)); - (same && of.dispatch == *dispatch).then_some(&kept.commands) - } - - /// The commands of a direct dispatch of `planned` and `dispatch`, kept in place of the - /// entry's: `over` writes them over the kept commands' storage where nothing else holds it - /// (with whether it did), else `fresh` makes them. - fn instantiate( - &mut self, - (planned, dispatch): (&Arc, Dispatch), - fresh: impl FnOnce() -> Result, - over: impl FnOnce(&mut DispatchCommands) -> Result<(), Error>, - ) -> Result<(Arc, bool), Error> { - if let Some(kept) = &mut self.0 { - if let Some(commands) = Arc::get_mut(&mut kept.commands) { - // Of nothing while they are written, and after an error. - kept.of = None; - over(commands)?; - kept.of = Some(CommandsOf::new(planned, dispatch)); - return Ok((Arc::clone(&kept.commands), true)); - } - } - let commands = Arc::new(fresh()?); - self.0 = Some(KeptCommands { - of: Some(CommandsOf::new(planned, dispatch)), - commands: Arc::clone(&commands), - }); - Ok((commands, false)) - } - - /// The state's values of the kinds `moved` names changed: the commands are of nothing where - /// they may read one, and are kept as storage alone. - fn moved(&mut self, moved: ValueKinds) { - if let Some(kept) = &mut self.0 { - if (kept.of.as_ref()).is_some_and(|of| of.reads.meets(moved)) { - kept.of = None; - } - } - } -} - -/// Plan, bind, and record the dispatch of `counts` with `tables` into `core` (the module's steps -/// 2 to 4), for Metal's `call`: `Ok(false)`, recording nothing, where the GPU path does not take -/// an indirect dispatch (`indirect_dispatch.rs`); a direct one is always recorded or refused. -/// An encoder's own dispatch (`own`: its order among the encoder's dispatches, and the encoder's -/// kept bind state) inside a block of command predication runs from the gates its unit's step -/// writes (`predication.rs`), binds the kept state brought in place (`compute/live.rs`), and a -/// direct one takes what its last dispatch settled where it has the same inputs -/// ([`DispatchMemo`]). And one whose `VkPipeline`s are not made yet hands their making to the -/// device's pool and records later (`pending_dispatch.rs`): an execution's or a host step's -/// dispatch waits for them. A dispatch of an inert kernel is planned and its uses made as any, -/// then named alone, recording nothing, and answers `Ok(true)`, taken (the module docs). -fn record( - core: &mut EncoderCore, - tables: &DispatchTables<'_>, - call: &'static str, - counts: Counts<'_>, - own: Option<(usize, &mut LiveDispatch)>, -) -> Result { - let pipeline = tables.pipeline; - let (direct, gpu) = match counts { - Counts::Direct(dispatch) => (Some(dispatch), None), - Counts::Flat(gpu) => (None, Some(gpu)), - }; - // The live visible-function tables the pipeline state made: the encoder's, or an indirect - // command's own state's. - let function_tables = pipeline.function_tables(); - let (own, mut live) = match own { - Some((own, live)) => (Some(own), Some(live)), - None => (None, None), - }; - // What a dispatch that takes no memo entry settled, and the bind state one that keeps none - // made. - let mut settled_here = None; - let mut state_here = None; - let mut flat = None; - // An encoder's own dispatch started from its pipeline state's state set aside - // (`compute/live.rs`). - let mut from_aside = false; - match live.as_deref_mut() { - Some(live) => { - // It starts from its pipeline state's own bind state, where its encoder set one aside. - from_aside = live.select(pipeline); - if from_aside { - core.counts().dispatch_from_set_aside(); - } - // A direct dispatch, of a state that made no table, takes the memo. - let memo = direct.filter(|_| function_tables.is_empty()); - let moved = super::buffer::host_cells_moved(); - let changed = core.generation().sampler_slots_changed(); - let held = memo.is_some_and(|dispatch| { - live.memo - .holds(&live.state, tables, &dispatch, (moved, changed)) - }); - // The device's sampler states, taken only where the dispatch needs them - // (`sampler::ArgumentSamplers`). - let mut samplers = ArgumentSamplers::untaken(); - // Else an entry an earlier compute encoder of the command buffer settled and parked, - // where the table, read now, brings in the very state it settled (`compute/live.rs`). - let across = match memo.filter(|_| !held) { - Some(dispatch) => { - let thread = pipeline.generation().shared().counts.thread(); - live.settled_across( - tables, - (&dispatch, (moved, changed)), - &mut samplers, - &function_tables, - thread, - )? - } - None => Across::Missed, - }; - if held { - core.counts().dispatch_settled_as_before(); - } else if let Across::Taken = across { - core.counts().dispatch_settled_across_encoders(); - } else { - let refreshed = match across { - Across::Refreshed(maps) => Some(maps), - Across::Taken | Across::Missed => None, - }; - let settling = ((changed, samplers), refreshed); - let settled = settle_live(live, tables, (direct, gpu), function_tables, settling); - // The kept state is no longer what the memo's entry settled. - let Some((settled, flat_call, changed)) = settled.inspect_err(|_| live.let_go())? - else { - live.let_go(); - return Ok(false); - }; - // What a dispatch settled for now alone is no entry's (`Planned::meanwhile`). - match memo.filter(|_| !settled.planned.meanwhile) { - Some(dispatch) => live - .memo - .keep((tables, dispatch), (moved, changed), settled), - None => { - live.let_go(); - settled_here = Some(settled); - flat = flat_call; - } - } - } - } - None => { - let samplers = core.device().argument_samplers(); - let Some((state, settled, flat_call)) = - settle_dispatch(tables, (direct, gpu), function_tables, samplers)? - else { - return Ok(false); - }; - state_here = Some(state); - settled_here = Some(settled); - flat = flat_call; - } - } - let (kept, kept_state, resident_shadows, (kept_uses, bind_memo, kept_commands)) = match live { - Some(live) => { - let (state, memo, shadows, (uses, bind_memo, commands)) = live.parts(); - let kept = (Some(uses), Some(bind_memo), Some(commands)); - (memo.entry(), Some(state), Some(shadows), kept) - } - None => (None, None, None, (None, None, None)), - }; - let settled = match (kept, &settled_here) { - (Some(kept), _) => &kept.settled, - (None, Some(settled)) => settled, - (None, None) => return Err(internal("a dispatch settled nowhere")), - }; - let state = match (&state_here, kept_state) { - (Some(state), _) => state, - (None, Some(state)) => state, - (None, None) => return Err(internal("a dispatch's bind state nowhere")), - }; - let SettledDispatch { - argument_samplers, - function_tables, - unlisted, - sampler_maps, - planned, - } = settled; - let Planned { - shape, - variant, - plan, - dispatch, - twins: proofs, - .. - } = &**planned; - // The call's own grid, where what it planned may be of another of its class - // (`Planned::grids`); a flat indirect dispatch's, its planned's. - let (unlisted, dispatch) = (*unlisted, direct.unwrap_or(*dispatch)); - let interface = &variant.pipeline().interface; - // A notice that names a state of pixel coordinates lists the states, taken here where the - // dispatch settled without them. - let stages = std::slice::from_ref(&variant.pipeline().stage); - if core - .device() - .argument_pixel_samplers_noted(stages) - .is_some() - { - let mut taken = ArgumentSamplers::untaken(); - let states = match argument_samplers { - Some(states) => states, - None => &*taken.take(core.device()), - }; - core.device() - .degrade_argument_pixel_samplers(stages, states); - } - tables - .table - .check_function_tables(call, Stage::Kernel, interface)?; - tables.table.check_offsets(call, Stage::Kernel, interface)?; - let kernel = pipeline.function_name(); - // The commands, their regions keyed (`Variant::keyed_regions`): those the memo's entry holds, - // where it holds them; else those the encoder's kept state keeps of what the dispatch planned - // ([`Instantiated`]), else instantiated (and kept there, for a direct dispatch). - let mut instantiated = None; - let commands = match kept.and_then(|kept| kept.commands.get()) { - Some(commands) => { - if from_aside { - core.counts().set_aside_commands_kept(); - } - commands - } - None => { - let instantiate = || -> Result { - let mut commands = plan - .instantiate_dispatch(state, &dispatch) - .map_err(Error::Bind)?; - variant.keyed_regions(core.device(), &mut commands); - Ok(commands) - }; - let counts = core.counts(); - let kept_of = kept_commands.as_deref(); - let commands = match kept_of.and_then(|kept| kept.of(planned, &dispatch)) { - Some(commands) => { - debug_assert!( - instantiate().is_ok_and(|again| again == **commands), - "a dispatch's kept commands that are not those it instantiates" - ); - counts.dispatch_instantiated_as_before(); - if from_aside { - counts.set_aside_commands_kept(); - } - Arc::clone(commands) - } - None => { - // A direct dispatch's are kept, over the storage of those kept before where - // nothing else holds it. - let commands = match (kept_commands, direct) { - (Some(memo), Some(_)) => { - let over = |commands: &mut DispatchCommands| { - (plan.instantiate_dispatch_into(state, &dispatch, commands)) - .map_err(Error::Bind)?; - variant.keyed_regions(core.device(), commands); - debug_assert!( - instantiate().is_ok_and(|again| again == *commands), - "a dispatch's commands written over kept ones that are not \ - those it instantiates" - ); - Ok(()) - }; - let (commands, in_place) = - memo.instantiate((planned, dispatch), instantiate, over)?; - if in_place { - counts.dispatch_instantiated_in_place(); - } - commands - } - _ => Arc::new(instantiate()?), - }; - counts.dispatch_instantiated(); - if from_aside { - counts.set_aside_commands_instantiated(); - } - commands - } - }; - match kept { - Some(kept) => kept.commands.get_or_init(|| commands), - None => &*instantiated.insert(commands), - } - } - }; - // A `[[stage_in]]` attribute's 32-bit displacement past 4 GiB of its buffer - // (`fetch_reach.rs`): the grid of a direct dispatch, any where GPU memory states it. - fetch_reach::check_stage_in_reach( - pipeline, - interface, - tables.table, - tables.stage_in_region, - direct.as_ref().and_then(fetch_reach::grid), - )?; - // A direct dispatch reads no indirect arguments; a flat one is one region, whose group - // counts its preprocess writes (`indirect_dispatch.rs`). A host step reads an indirect - // dispatch's arguments first. - let indirect = commands - .regions - .iter() - .filter(|region| region.indirect.is_some()) - .count(); - let expected = match flat { - None => 0, - Some(_) => 1, - }; - if commands.indirect_clamp.is_some() - || indirect != expected - || (flat.is_some() && commands.regions.len() != 1) - { - return Err(internal( - "a dispatch's commands read indirect arguments it does not state", - )); - } - if commands.regions.is_empty() { - core.executed(|| { - Execution::new( - ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())), - Arc::clone(shape), - Vec::new(), - ) - }); - return Ok(true); - } - // Set 1, the heap: its writes at the elements of their resource IDs, and the device's texture - // and sampler tables at the handle tables. - let compiled = variant.pipeline(); - let heap = heap_sets::heap_elements(&compiled.layout, plan, state)?; - // What the variant's layout binds of the device's tables, worked out once (`heap_sets.rs`). - let heap_tables = (variant.objects()).heap_tables(&compiled.layout, &compiled.dependencies); - (variant.objects()).bind_sampler_tables(&compiled.layout, &compiled.dependencies); - let texture_table = heap_tables.texture_table(core.device())?; - let sampler_table = heap_tables.sampler_table(core.device())?; - let stages = [(Stage::Kernel, tables.table)]; - let untwinned = binding::Tables::new(&stages) - .with_residency(tables.residency) - .with_texture_table(texture_table.as_ref()) - .with_sampler_table(sampler_table.as_ref()) - .with_sampler_maps(sampler_maps.clone()); - // The slots the dispatch only reads through read twins (`read_twin.rs`). - let cb = core.command_buffer(); - let roots = commands.root_table.iter().next().is_some(); - // The plan's proofs, kept with what the dispatch planned (`Planned::twins`). - let twins = proofs.slots(cb, (&**plan, &commands.uses, roots), &untwinned); - let mut bound_tables = match &twins { - Some(twins) => untwinned.with_twins(twins), - None => untwinned, - }; - // The flat dispatch's preprocess: its scratch holds the region record the variant reads. - let preprocess = match &flat { - Some((_, indirect)) => { - let preprocess = FlatPreprocess::new(core, indirect)?; - bound_tables.region_record = Some(preprocess.record); - Some(preprocess) - } - None => None, - }; - // A direct dispatch on a flat variant reads the record the plan states, in the command's own - // upload (16-aligned, as the variant reads it): the grid in threads is the call's, so nothing - // on the device writes it. - if let Some(bytes) = commands.region_record { - let record = { - let mut state = core.command_buffer().state(); - state - .uploads - .upload_aligned(core.device(), &bytes, bytes.len() as u64, 16)? - }; - let Some(address) = record.device_address() else { - return Err(internal( - "a flat dispatch's region record without a device address", - )); - }; - bound_tables.region_record = Some(address); - } - // The listed function tables: set 1's elements, or the snapshot a variant without the - // function-table array reads in set 0, which has no heap of its own. - bound_tables = bound_tables.with_function_tables(function_tables); - if let Some(heap) = &heap { - // Taken as the dispatch settled: its variant has set-1 arrays. - let states = (argument_samplers.as_deref()) - .ok_or_else(|| internal("a heap's dispatch without its argument samplers"))?; - bound_tables = bound_tables.with_heap(states, heap); - } - let pipeline_stage = &variant.pipeline().stage; - // A flat dispatch's indirect arguments are its preprocess's command, in the command's own - // upload, which the preprocess writes between barriers: nothing else orders against it. Its - // read of Metal's arguments is the command's use instead (`FlatCall::reads`). - let command_uses: Vec<_> = commands - .uses - .iter() - .filter(|resource| flat.is_none() || resource.resource != UseTarget::Indirect) - .copied() - .collect(); - let command = binding::Command { - descriptor_bytes: &commands.descriptor_bytes, - heap_tables: &[], - descriptor_ranges: &commands.descriptor_ranges, - extents: &commands.extents, - root_tables: commands - .root_table - .iter() - .map(|table| (metal2vulkan::vk::ShaderStageFlags::COMPUTE, table)) - .collect(), - // A kernel's artifact states no proof that it stores nothing. - root_writes: true, - push_holes: &commands.push_holes, - uses: &command_uses, - blobs: pipeline_stage - .constant_blob - .iter() - .map(|blob| (Stage::Kernel, blob)) - .collect(), - mesh: None, - tessellation: None, - fan_out: None, - }; - // An encoder's own dispatch makes its uses over the last one's, in their storage - // (`LiveDispatch::uses`), those of what the encoder made resident kept where they are the - // last dispatch's, as a draw does (`LiveBind::uses`); an indirect command's state makes them - // whole. - let mut made_whole; - let uses = match kept_uses { - Some(uses) => { - let inputs = (plan, &command, &bound_tables); - binding::command_uses_into(call, inputs, (None, None), uses)?; - uses - } - None => { - made_whole = binding::command_uses(call, plan, &command, &bound_tables, None, None)?; - &mut made_whole - } - }; - if let Some((call, _)) = &flat { - uses.push(call.reads()); - } - let uses: &binding::CommandUses = uses; - // A dispatch that names a detached buffer records nothing: its submission fails. - let named = uses - .iter() - .map(|used| used.key) - .filter(|key| !uses.resident().contains(key)); - if core.skips(named) { - tables.table.retain(core); - return Ok(true); - } - // A dispatch of an inert kernel records nothing; the command buffer uses what it binds, as - // Metal's does (the module docs). - if pipeline.inert() { - core.name_uses(uses, uses.resident()); - tables.table.retain(core); - core.counts().dispatch_skipped_inert(); - return Ok(true); - } - // The device through the command buffer's handle, borrowed at each use (`core.device()`): no - // handle of its own, whose count every encoding thread's handles share. - // Inside a block of command predication, each command runs from its gate: the flat path's - // preprocess (whose command then stays zero), else each region's dispatch. Their group - // counts are listed only for a unit that gates them. - let gates = match own.is_some() { - true => { - let (further, gates) = { - let mut state = core.command_buffer().state(); - let (predication, uploads) = state.predication_and_uploads(); - match predication.gates_dispatches() { - true => { - let counts: Vec<[u32; 3]> = match &preprocess { - Some(_) => vec![[1, 1, 1]], - None => commands - .regions - .iter() - .map(|region| region.group_count) - .collect(), - }; - predication.gates(uploads, core.device(), &counts)? - } - false => (None, Vec::new()), - } - }; - if let Some(step) = further { - predication::record_further(core, &step)?; - } - gates - } - false => Vec::new(), - }; - let mut writes = Vec::new(); - // An encoder's own dispatch binds through the views, sampler descriptions and host pages its - // binds kept (`binding::BindMemo`, `compute/live.rs`). - let bound = { - let mut state = core.command_buffer().state(); - binding::bind( - call, - core.device(), - &mut state, - plan, - &command, - &bound_tables, - (bind_memo, &mut writes), - )? - }; - let mut push = Vec::with_capacity(commands.regions.len()); - for region in &commands.regions { - let writes = binding::push_writes(region.push_constants.clone(), &bound.holes)?; - push.push((region.group_count, writes)); - } - let objects = variant.objects(); - // Set 1 the device's (written below, once nothing refuses). - let (heap_writes, mut writes): (Vec<_>, Vec<_>) = - writes.into_iter().partition(|write| write.set > 0); - // The dispatch binds the variant: the kinds its making announces at every occurrence. - let formats: BoundFormats<'_> = &|slot| bound_tables.bound_format(slot); - // An encoder's own dispatch waits for no making: where one of its regions' pipelines is not - // made, it records later (`pending_dispatch.rs`). An encoder encoded again (`replay.rs`) - // waits for none either, and leaves the same segment: the making is its submission's to wait - // for, as the first encoding left it, never the rebind's call on the program's thread. - // Where the driver loses a layout's baked samplers after a copy in the same - // `VkCommandBuffer` (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`), a variant that - // bakes them records in one of its own, as one being made does. - // Those the memo's entry holds, else those found made for what the dispatch planned, of its - // regions' keys ([`Planned`]). - let kept_made = kept - .and_then(|kept| kept.made.get()) - .or_else(|| planned.made_for(commands)) - .filter(|_| !apart_samplers(core.device(), objects)); - // Inside a predicated loop's laying, it waits for them too, so the laying, which its check - // may submit again (`command_buffer/rerun.rs`), is not split for it; but where its variant - // records in one of its own. - let laying = core.command_buffer().state().predication_mut().laying(); - let waits = laying && !apart_samplers(core.device(), objects); - let (pipelines, pending) = match (own.filter(|_| !waits), kept_made) { - (Some(_), Some(made)) => { - if let Some(kept) = kept.filter(|kept| kept.made.get().is_none()) { - drop(kept.made.set(made.clone())); - } - (Cow::Borrowed(made.as_slice()), None) - } - (Some(dispatch), None) => { - let begun: Vec<_> = commands - .regions - .iter() - .map(|region| { - let pipeline = pipeline.begin_region_pipeline(variant, region, formats); - (RegionKey::of(region), pipeline) - }) - .collect(); - let made: Option> = begun - .iter() - .map(|(_, pipeline)| match pipeline { - RegionPipeline::Made(made) => Some(Arc::clone(made)), - RegionPipeline::Making(_) => None, - }) - .collect(); - // A direct dispatch whose pipelines were not all made: the state's to record, for a - // later process's warm pass (`pipeline/dispatch_record.rs`). - if let (None, Some(direct)) = (&made, &direct) { - pipeline.record_dispatch(direct, state); - } - match made { - Some(made) if !apart_samplers(core.device(), objects) => { - // Kept with the entry, which the next dispatch of its inputs takes, and with - // what it planned, which the next dispatch of its shape takes; but never a - // key's residual form, which serves only while its own is made: a later - // dispatch of either asks its regions' pipelines again, as this one did, and - // takes its own key's once made (`tests::residual_memo`). The check costs one - // look in the variant's memo a region, on this path alone (no pipelines kept - // for the dispatch); a dispatch that takes kept ones looks at none. - let own = (begun.iter().zip(&made)) - .all(|((key, _), made)| variant.made_as(key, made)); - if own { - if let Some(kept) = kept { - drop(kept.made.set(made.clone())); - } - if planned.made.get().is_none() { - let keys = begun.iter().map(|(key, _)| key.clone()).collect(); - drop(planned.made.set((keys, made.clone()))); - } - } - (Cow::Owned(made), None) - } - Some(_) => { - core.device() - .shared() - .counts - .thread() - .baked_sampler_dispatch_apart(); - (Cow::Owned(Vec::new()), Some((dispatch, begun))) - } - None => (Cow::Owned(Vec::new()), Some((dispatch, begun))), - } - } - (None, _) => { - let mut made = Vec::with_capacity(commands.regions.len()); - for region in &commands.regions { - made.push(variant.region_pipeline(region, formats)?); - } - (Cow::Owned(made), None) - } - }; - // Set 0: pushed, or the encoder's last set where it holds the same writes, else one from the - // command buffer's arena, written (`EncoderCore::set_zero`), with its dynamic offsets. - let mut offsets = Vec::new(); - let ((set, written), pushed) = match objects.pushes_set_zero() { - true => ( - (None, None), - binding::SetWrite::pushed(&writes, objects.immutable_pushes()), - ), - false => ( - core.set_zero(objects, (&mut writes, &mut offsets))?, - Vec::new(), - ), - }; - // The shadowed textures the dispatch binds, at the first draw or dispatch of each, its - // shadow made now (`shadow_log.rs`). - crate::shadow_log::dispatched(core.device(), variant.pipeline(), tables.table); - // The resident textures' shadows as the encoder keeps them (`compute/live.rs`). - let textures = tables.table.textures.values(); - let shadows = match resident_shadows { - Some(kept) => { - shadow::shadow_uses_of(textures, kept.of(core.device(), tables.residency), uses) - } - None => shadow::shadow_uses(textures.chain(tables.residency.textures()), uses), - }; - let copies = core.plan_shadows(&shadows, uses)?; - let heap_set = match heap { - Some(_) => Some( - heap_sets::bind( - core.device(), - objects, - &mut core.command_buffer().state().heaps, - heap_writes, - uses, - )? - .set, - ), - None => None, - }; - // A dispatch that records later goes on in a new `VkCommandBuffer`, made now. - let pending = match pending { - Some((dispatch, begun)) => Some((dispatch, begun, core.continuation()?)), - None => None, - }; - // Recording starts here: nothing below can be refused (but a `VkCommandBuffer` that does not - // end, which abandons the command buffer). - if let Some(written) = written { - core.keep_set_zero(written, &writes); - } - core.shadow_copies(&copies); - // A dispatch recorded later pushes its set 0 whole, into a segment of its own; one recorded - // here, what its push carries (`binding::PushedSetZero`). - let pushes = !pushed.is_empty(); - if pushes && pending.is_some() { - (core.device().shared().counts.thread()).dispatch_pushing_set_zero(pushed.len() as u64); - } - let recording = Recording { - layout: objects.layout(), - set, - offsets, - pushed, - heap: heap_set, - preprocess, - gates, - regions: push, - }; - let stages = vk::PipelineStageFlags2::COMPUTE_SHADER; - let regions = &commands.regions; - (core.device().shared().counts.thread()).dispatch_tracked(uses.len() as u64); - match pending { - Some((dispatch, begun, next)) => { - // Tracked here, as a command recorded here is; its execution recorded here, its - // creation times set as its segment records. - let creation = core.records_executions().then(|| Arc::new(OnceLock::new())); - if let Some(barrier) = core.command_later(stages, uses, uses.resident()) { - let encoder = core.command_buffer().state().open_encoder_place(); - let pending = PendingDispatch { - variant: Arc::clone(variant), - pipelines: begun, - recording, - barrier, - creation: creation.clone(), - state: pipeline.clone(), - encoder, - dispatch, - }; - core.pend(next, pending)?; - } - core.shadows_used(&shadows, uses, &[]); - if let Some(creation) = creation { - core.executed(|| { - Execution::made_later( - ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())), - Arc::clone(shape), - creation, - ) - }); - } - } - None => { - let made = &*pipelines; - let stale = core.device().shared().pushes_after_pipeline_binds; - let resident = uses.resident(); - let carried = Cell::new(0); - core.command_reaching_pushed(stages, uses, resident, |raw, command_buffer, held| { - // SAFETY: the encoder's command buffer is recording outside a render pass; - // every object recorded is live until the command buffer completes (retained - // below), the pipelines are the variant's, one per region, and `held` is what - // its compute bind point holds (`EncoderCore::command_reaching_pushed`). - let pushed = unsafe { recording.record(raw, command_buffer, made, (held, stale)) }; - carried.set(carried.get() + pushed); - }); - if pushes { - (core.device().shared().counts.thread()).dispatch_pushing_set_zero(carried.get()); - } - core.shadows_used(&shadows, uses, &[]); - core.executed(|| { - Execution::new( - ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())), - Arc::clone(shape), - pipelines.iter().map(|made| made.created_in).collect(), - ) - }); - } - } - objects.degrade_bound_formats( - std::slice::from_ref(&variant.pipeline().stage), - Some(formats), - ); - // Each specialization the dispatch's regions take, once. - for (n, region) in regions.iter().enumerate() { - if regions[..n] - .iter() - .all(|earlier| earlier.specialization != region.specialization) - { - core.device().degrade_bound_values( - std::slice::from_ref(&variant.pipeline().stage), - ®ion.specialization, - &|k| plan.specialized_value(k), - Some(formats), - ); - } - } - core.device() - .degrade_cross_class(&plan.diagnostics, formats); - core.device() - .degrade_astc_storage(&plan.diagnostics, formats); - objects.announce_bound( - ( - std::slice::from_ref(&variant.pipeline().stage), - CompiledPipeline::Kernel(variant.pipeline()), - ), - regions - .iter() - .map(|region| (®ion.specialization, Some(formats))), - ); - // Held by reference, each once while the encoder held it lately (`retained.rs`): a - // dispatch of the objects of the one before it holds none again, nor touches their counts. - pipeline.retain_in(core); - core.retain_shared_of(objects); - for made in pipelines.iter() { - core.retain_shared_of(made); - } - tables.table.retain(core); - for sampler in bound.samplers { - core.retain_shared(sampler); - } - if let Some((call, _)) = &flat { - core.retain_shared(call.buffer.held()); - } - // The tables the heap's function-table array may name: their IDs stay theirs until the - // command buffer completes. - if heap.is_some() && !function_tables.is_empty() { - core.retain(function_tables.clone()); - } - let emulated = variant.emulates_simdgroups(); - let split = (regions.len(), variant.runs_partial_threadgroups()); - degrade_dispatch(core.device(), kernel, &dispatch, split, emulated); - // A large kernel's whole grid on its partial-threadgroups variant ([`partial_direct`]). - if variant.runs_partial_threadgroups() && whole_grid(&dispatch) { - core.counts().whole_dispatch_on_partial_variant(); - } - if let Some(unlisted) = unlisted { - heap_sets::degrade_unlisted( - core.device(), - unlisted, - &format!("kernel `{kernel}`'s dispatches"), - ); - // It runs with the states its sampler arrays hold. - let mut held = core.command_buffer().state(); - held.unlisted_argument_sampler(core.device()); - } - Ok(true) -} diff --git a/crates/metal2vulkan-runtime/src/compute/live.rs b/crates/metal2vulkan-runtime/src/compute/live.rs deleted file mode 100644 index c677240bb..000000000 --- a/crates/metal2vulkan-runtime/src/compute/live.rs +++ /dev/null @@ -1,634 +0,0 @@ -//! A compute encoder's bind state, kept between its dispatches: each dispatch that does not take -//! what the last one settled (`DispatchMemo`) brings the state the encoder's last such dispatch -//! bound to its own in place, and makes its bind shape again only where a change may have changed -//! it, as a render encoder's draw does (`live_bind.rs`). -//! -//! - **Brought in place.** The kernel's slots are derived again from the encoder's table and -//! compared with the kept ones (`ArgumentTable::refresh_reading`), at each dispatch whose table -//! may bring in another: a table read last through the same pipeline state's interface and -//! samplers' maps, that no call changed since (its stamp, `argument_table::Stamp`), whose slots -//! that tell the device's view base alignment apart the state still holds as they were read -//! (`argument_table::AtBindViews`), and that no rebind or detach of a no-copy buffer may have -//! changed (`buffer::host_cells_moved`), is not read again ([`ReadFrom`]; checked whole in debug -//! builds). Where only calls changed it since it was so read, and the table keeps the slots they -//! changed (`ArgumentTable::refresh_changed`), only those slots are brought in. Every other field -//! is computed as before and compared ([`Reshape::field`]); the stage-in region, which no shape -//! reads, changes no shape ([`Reshape::unshaped`]). The new value is always stored, so the state -//! is the dispatch's exactly. While the same slots stay bound, nothing is allocated. The kinds -//! of values a dispatch brought in changed ([`Reshape::moved`]) let go of the commands kept -//! below where they may read them. -//! - **What the encoder made resident, listed once a change.** The state's used resources are -//! listed again (`Residency::used_resources`, `WorkCounts::dispatch_used_resources_listed`) only -//! where the residency changed its generation since they were listed (`Residency::generation`: -//! each change of what it holds draws a new one), a no-copy buffer moved since (their -//! addresses), or an indirect command buffer made resident no longer holds its ID's slot as they -//! state (`Residency::holds_slots_as`): what they are a function of, but for those, is the -//! residency's contents, which a generation names. Checked whole in debug builds. -//! - **The shape found again only where it may have changed.** Where no change brought in may have -//! changed the shape, it is the kept one (`WorkCounts::dispatch_shapes_made` and -//! `dispatch_shapes_found` stay); after any other change, it is one the pipeline state planned -//! for lately where it has it (`ComputePipelineState::planned_shape`, compared in place), else it -//! is made again, whole. The pipeline state's plan of a kept shape is found by identity first -//! (`ComputePipelineState::planned_for`), so a dispatch whose offsets alone moved compares no -//! shape at all, however many resources the encoder made resident. -//! - **One per pipeline state lately dispatched.** Beside the state its last dispatch brought in -//! place, the encoder sets aside the states of up to `live_bind::SET_ASIDE` (15) pipeline states -//! it dispatched before that one ([`LiveDispatch::select`]), each under the pipeline state whose -//! dispatch left it (held weakly), with its shape, what its table was read from, what its last -//! dispatch settled (`DispatchMemo`) and the commands it kept (`Instantiated`); a dispatch -//! starts from its pipeline state's, where one is set aside, as a render encoder's draw does -//! (`live_bind::start_from` chooses for both): dispatches that switch between pipeline states, -//! an encoder for each as a guest's are, each find their own state's shape kept, their table read -//! through their own interface, their commands kept while no value they may read moved, and, -//! within a command buffer, their own state's last settle (`WorkCounts::dispatches_from_set_aside` -//! and its split). Exact for the reason a dispatch's is: whichever state a dispatch starts from, -//! it brings every field in place, and a kept settle or kept commands are taken only under the -//! rules above. They go on with the state from one encoder to the next and to the device's -//! spares, as the state does, every one's memo let go or its sampler states unlisted where the -//! state's is. -//! - **Kept from one encoder to the next.** An encoder that ends leaves its state, with its shape, -//! to its command buffer's next compute encoder (**Parked in its command buffer**, below), and -//! the commit gives it to its device ([`SpareLiveDispatches`]), whose next compute encoder opened -//! starts from it, as a dispatch starts from the one before it: exact for the reason a dispatch's -//! is, every field of the state a dispatch binds being derived again at each dispatch that -//! settles. The memo of what its last dispatch settled goes as the device takes it -//! ([`LiveDispatch::let_go`]): it holds the pipeline state, sampler states and pipelines, where the -//! state holds values alone (its bindings, its used resources and argument samplers as a bind -//! state lists them, its table's pipeline state held weakly), so a kept one holds nothing alive. -//! The lists of its resident textures' shadows and carriers go at each end -//! ([`ResidentShadows`], [`ResidentUnreadable`]). -//! - **Commands kept while the state binds what they read.** The commands its last direct dispatch -//! that instantiated made are kept, with what that dispatch planned held weakly -//! (`compute::Instantiated`), and go on with the state to the next encoder: a later dispatch of -//! what the same dispatch planned takes them while no change since moved a kind of value they -//! may read, so dispatches that bind two textures in turn, one encoder each, instantiate once. -//! - **Views, sampler descriptions and host pages kept for its binds.** The views, the sampler -//! descriptions and where the buffers over host pages lie that its dispatches' binds made or -//! found are kept (`binding::BindMemo`), by everything each is a function of, and go on with the -//! state to the next encoder: a dispatch that binds what one before it bound works none out -//! again. The memo holds its textures, sampler states and host cells weakly, so a kept one holds -//! nothing alive. -//! - **Parked in its command buffer.** A compute encoder's end parks its state, with what its last -//! dispatch settled, and the box of its core in its command buffer ([`Parked`]); the command -//! buffer's next compute encoder opens on them rather than on the device's spares -//! (`WorkCounts::parked_compute_taken`), and the commit gives them back to the device, the memo let -//! go. The memo's entry so goes on, and a dispatch whose new table, read, brings in the very state -//! the entry settled takes it ([`LiveDispatch::settled_across`], -//! `WorkCounts::dispatches_settled_across_encoders`): one encoder for each dispatch of the same -//! bindings settles once. Exact: the entry is a function of the bind state and of the inputs -//! `DispatchMemo` compares beside its table's stamp (`compute::DispatchMemo`), and the table's -//! stamp stands for the table-derived part of that state alone; bringing the state in place -//! notes every value it changed ([`Reshape::moved`]), so where it changed none, and the samplers' -//! maps (the table's and the residency's) are the entry's, the state is the one it settled. A -//! parked entry holds nothing its command buffer does not: its pipeline state, variant and -//! `VkPipeline`s the command buffer's dispatch held until it completes. The device's sampler -//! states the entry listed are let go as it parks, as are the resident textures' lists, and the -//! dispatch that takes it lists them again: those the device lists at the count of sampler slot -//! changes the entry compares, so the very states it listed. -//! - **Resident textures looked at once a change.** A dispatch's look at the shadows of the -//! textures the encoder made resident (`shadow::shadow_uses_of`), and a reading of texture -//! handles' look for one a carrier holds (`pvrtc::degrade_unreadable`), read the lists kept here, -//! made again only where they may have changed. - -use metal2vulkan::bind::{BindShape, BindState, Dispatch, HeapPlacement, ImageblockSize}; -use metal2vulkan::pipeline::Stage; -use std::sync::{Arc, Mutex}; - -use super::{DispatchMemo, DispatchTables, Instantiated}; -use crate::address_map::SamplerMaps; -use crate::argument_table::Stamp; -use crate::binding::{BindMemo, CommandUses}; -use crate::device::{lock, Device}; -use crate::encoder::{CoreBox, EncoderCore}; -use crate::error::Error; -use crate::function_table::VisibleFunctionTable; -use crate::heap_sets; -use crate::live_bind::{start_from, Reshape, Seat, ValueKinds, SET_ASIDE}; -use crate::pipeline::{ComputePipelineState, WeakComputePipelineState}; -use crate::pvrtc::ResidentUnreadable; -use crate::sampler::ArgumentSamplers; -use crate::shadow::ResidentShadows; -use crate::work_counts::Counting; - -/// The most bind states a device keeps for its compute encoders to start from: one per encoder -/// open at once beyond it starts empty, as every encoder did before. -const SPARE_LIVE_DISPATCHES: usize = 4; - -/// A compute encoder's bind state as its last dispatch that settled bound it, its shape while no -/// change may have changed it, and what that dispatch settled (the module docs). -#[derive(Default)] -pub(in crate::compute) struct LiveDispatch { - /// The state. Each dispatch that settles brings it to its own through [`Reshape`] - /// ([`refresh`](Self::refresh)). Boxed, so a dispatch of another pipeline state changes it - /// for one set aside by its address ([`select`](Self::select)). - pub(in crate::compute) state: Box, - /// The state's shape, `None` where a change may have changed it. - shape: Option>, - /// The count of the device's sampler IDs' slots' changes (`DeviceShared::sampler_slots_changed`) - /// at which the state's argument samplers are every live sampler state, `None` where they are - /// not (none listed yet, or those a variant's set-1 arrays hold alone). - listed_at: Option, - /// What the state's kernel table was read from ([`ReadFrom`]). - read_from: ReadFrom, - /// What the dispatch that last brought the state in place settled, where it is kept for the - /// next dispatch of the same inputs (`DispatchMemo`): of this state, so a dispatch that takes - /// it binds this state. - pub(in crate::compute) memo: DispatchMemo, - /// The shadows' copies of the textures the encoder made resident. - pub(in crate::compute) shadows: ResidentShadows, - /// The first texture the encoder made resident whose bytes a carrier holds for copies alone. - pub(in crate::compute) unreadable: ResidentUnreadable, - /// The last dispatch's uses (`binding::command_uses_into`), whose storage the next one's - /// take, as a draw's take the last draw's (`LiveBind::uses`). - uses: CommandUses, - /// The views, sampler descriptions and host pages its dispatches' binds made or found - /// (`binding::BindMemo`). - bind: BindMemo, - /// The commands its last direct dispatch that instantiated made, while the state binds what - /// they read (`Instantiated`). - instantiated: Instantiated, - /// The pipeline state whose dispatch last brought the state in place - /// ([`select`](Self::select)), named without holding it; `None` before any did. - dispatched: Option, - /// The states the encoder's dispatches of other pipeline states brought in place, each as its - /// pipeline state's last dispatch left it ([`select`](Self::select)). - set_aside: [SetAside; SET_ASIDE], - /// How many times a state went aside: each set aside holds the count as it went, so the one - /// set aside longest holds the least. - asides: u64, -} - -/// The bytes a state set aside takes beside its bind state's slots and lists, which grow with -/// what its dispatches bind: its own, and its bind state's box (read by -/// `tests::compute_set_aside`). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) const SET_ASIDE_BYTES: usize = - std::mem::size_of::() + std::mem::size_of::(); - -/// A bind state a [`LiveDispatch`] set aside, with what [`LiveDispatch`] holds of its last -/// dispatch's state beside it: its shape, its listing's count, what its table was read from, what -/// its last dispatch settled and the commands it kept, and the pipeline state that left it. -#[derive(Default)] -struct SetAside { - state: Box, - shape: Option>, - listed_at: Option, - read_from: ReadFrom, - memo: DispatchMemo, - instantiated: Instantiated, - dispatched: Option, - /// [`LiveDispatch::asides`] as it went aside. - at: u64, -} - -/// What a kept state's kernel table was read from at the dispatch that read it last -/// ([`LiveDispatch::refresh`]): the encoder's table by its stamp, the pipeline state whose -/// interface it was read through, the samplers' address-mode maps, and the count of no-copy -/// buffers' moves (`buffer::host_cells_moved`); and the generation of the residency the state's -/// used resources were listed of (`Residency::generation`). A table that keeps its stamp, read -/// through the same state with the same maps while no no-copy buffer moved, brings in what it -/// brought in then where the state's slots that tell the view base alignment apart are still those -/// it read under (`AtBindViews::holds`): a slot's binding is a function of the object bound there, -/// of the table's other entries, of the function's reading of the slot (the interface), of the -/// maps, and of those slots. -#[derive(Default)] -struct ReadFrom { - /// The table's stamp. - table: Option, - /// The pipeline state it was read through, held weakly: while it is held, no other state lies - /// where that one lay, so a state it names is the very one. - pipeline: Option, - /// The maps it was read with. - maps: SamplerMaps, - /// The count of no-copy buffers' moves as it was read. - moved: u64, - /// The generation of the residency the state's used resources were listed of, at `moved` - /// moves; `None` before any were. - resident: Option, -} - -impl ReadFrom { - /// Whether the table was read through `pipeline` with `maps` at `moved` moves: then a table - /// that keeps its stamp brings in what it brought in. - fn reads(&self, pipeline: &ComputePipelineState, maps: &SamplerMaps, moved: u64) -> bool { - self.moved == moved - && (self.pipeline.as_ref()).is_some_and(|read| read.names(pipeline)) - && self.maps == *maps - } -} - -impl LiveDispatch { - /// Start a dispatch of `pipeline` from the state [`start_from`] picks (that pipeline state's - /// last dispatch left, where one is set aside): it and the state in place change places, and - /// the one it starts from it takes as `pipeline`'s. Whether it started from its pipeline - /// state's own state set aside. Exact whichever a dispatch starts from, as it brings every - /// field of the state in place (the module docs), so this chooses only what the dispatch may - /// keep and which reads it skips. - pub(in crate::compute) fn select(&mut self, pipeline: &ComputePipelineState) -> bool { - if self.dispatches(pipeline) { - return false; - } - let lives = |dispatched: &Option| { - (dispatched.as_ref()).is_some_and(WeakComputePipelineState::lives) - }; - // A compute state's table is read through its own interface alone (`ReadFrom::reads`). - let in_place = Seat { - own: false, - lives: lives(&self.dispatched), - through: false, - at: 0, - }; - let aside = self.set_aside.iter().map(|aside| Seat { - own: (aside.dispatched.as_ref()).is_some_and(|it| it.names(pipeline)), - lives: lives(&aside.dispatched), - through: false, - at: aside.at, - }); - let from = start_from(in_place, aside); - let own = from.is_some_and(|at| { - let aside = &self.set_aside[at].dispatched; - aside.as_ref().is_some_and(|it| it.names(pipeline)) - }); - if let Some(at) = from { - self.swap_aside(at); - } - if !self.dispatches(pipeline) { - self.dispatched = Some(pipeline.downgrade()); - } - own - } - - /// Whether the state in place is the one `pipeline`'s last dispatch left, which a dispatch of - /// it starts from ([`select`](Self::select) keeps it). - fn dispatches(&self, pipeline: &ComputePipelineState) -> bool { - (self.dispatched.as_ref()).is_some_and(|it| it.names(pipeline)) - } - - /// Change the state in place for the one set aside at `at`. - fn swap_aside(&mut self, at: usize) { - self.asides += 1; - let aside = &mut self.set_aside[at]; - std::mem::swap(&mut self.state, &mut aside.state); - std::mem::swap(&mut self.shape, &mut aside.shape); - std::mem::swap(&mut self.listed_at, &mut aside.listed_at); - std::mem::swap(&mut self.read_from, &mut aside.read_from); - std::mem::swap(&mut self.memo, &mut aside.memo); - std::mem::swap(&mut self.instantiated, &mut aside.instantiated); - std::mem::swap(&mut self.dispatched, &mut aside.dispatched); - aside.at = self.asides; - } - - /// Bring the state to the one a dispatch of `tables` binds, in place (the module docs): the - /// kernel's table read as the pipeline state's interface reads it (a buffer where the kernel - /// reads a visible-function table reads as a null table: `ArgumentTable::refresh_reading`), - /// its samplers bound as `maps` binds them, its threadgroup memory lengths, the imageblock size - /// for a kernel with an explicit imageblock (one without plans with none, so its shape is the - /// one the executor computes for it), the stage-in region, the resources the encoder made - /// resident, the device's sampler states listed (those `samplers` took, which it takes where - /// the kept listing is not of every live state at `changed` changes of their slots: - /// `sampler::ArgumentSamplers`), and the live tables the pipeline state made. Each change that - /// may change the shape is noted, and the shape kept only where none may have. The kinds of - /// values it changed. - pub(in crate::compute) fn refresh( - &mut self, - tables: &DispatchTables<'_>, - maps: &SamplerMaps, - (changed, samplers): (u64, &mut ArgumentSamplers), - function_tables: &[VisibleFunctionTable], - counts: Counting<'_>, - ) -> ValueKinds { - let mut reshape = Reshape::default(); - let pipeline = tables.pipeline; - let views = pipeline.at_bind_views(); - let state = &mut self.state; - reshape.field(&mut state.view_base_alignment, views.alignment()); - state.uniform_views_at_residual = views.at_residual(); - let moved = crate::buffer::host_cells_moved(); - let same = self.read_from.reads(pipeline, maps, moved); - // The state's used resources are what the encoder made resident still where the residency - // kept its generation since they were listed of it (`Residency::generation`), no no-copy - // buffer moved since (their addresses), and each indirect command buffer made resident - // holds its ID's slot as they state (`Residency::holds_slots_as`). - let residency = tables.residency; - let generation = residency.generation(); - let resident = self.read_from.moved == moved - && self.read_from.resident == Some(generation) - && residency.holds_slots_as(&state.used_resources); - let table = tables.table; - let read = (Stage::Kernel, pipeline.interface()); - let kept = state.stages.entry(Stage::Kernel).or_default(); - // Its slots that tell the view base alignment apart are as the state holds them - // (`AtBindViews::holds`): another table's offsets may have left some out since. - let views_held = views.holds(Stage::Kernel, kept); - let read_under = self.read_from.table.filter(|_| same && views_held); - if read_under == Some(table.stamp()) { - #[cfg(debug_assertions)] - table.check_reading(kept, read, (maps, views)); - } else { - // Only the slots calls changed since it was read, where the table keeps them. - let in_part = read_under.is_some_and(|stamp| { - let kept = (&mut *kept, stamp); - table.refresh_changed(kept, read, (maps, views), &mut reshape, counts) - }); - if !in_part { - table.refresh_reading(kept, read, (maps, views), &mut reshape); - } - } - reshape.field_from(&mut kept.threadgroup_lengths, tables.threadgroup_lengths); - self.read_from.table = Some(table.stamp()); - if !(self.read_from.pipeline.as_ref()).is_some_and(|read| read.names(pipeline)) { - self.read_from.pipeline = Some(pipeline.downgrade()); - } - if self.read_from.maps != *maps { - self.read_from.maps = maps.clone(); - } - self.read_from.moved = moved; - let imageblock = match pipeline.imageblock_cell_bytes() { - Some(_) => tables.imageblock, - None => ImageblockSize::default(), - }; - reshape.field(&mut state.imageblock_size, imageblock); - // No shape reads it (`BindState::stage_in_region`). - reshape.unshaped(&mut state.stage_in_region, tables.stage_in_region); - debug_assert!( - !resident || state.used_resources == residency.used_resources(), - "a dispatch's kept used resources that are not its residency's" - ); - if !resident { - counts.dispatch_used_resources_listed(); - reshape.field(&mut state.used_resources, residency.used_resources()); - } - self.read_from.resident = Some(generation); - // Listed again only where the device's sampler states changed since: not where the - // listing kept is of every live state at the count of their slots' changes that holds; - // else they are taken and compared state by state. - let current = samplers.states().is_none() && self.listed_at == Some(changed); - if !current { - let states = samplers.take(tables.pipeline.generation()); - if !heap_sets::lists(&state.argument_samplers, states) { - reshape.field(&mut state.argument_samplers, heap_sets::listed(states)); - } - self.listed_at = samplers.listed_at(); - } - let listed = function_tables - .iter() - .map(VisibleFunctionTable::listed) - .collect(); - reshape.field(&mut state.function_tables, listed); - // Values no shape reads (`BindState::heap_placement`, `used_in_token_order`, - // `resident_apart`): the residency lists its used resources in token order, and root tables - // the commit points elsewhere keep them out, as a dispatch's whole state has them. - reshape.unshaped(&mut state.heap_placement, HeapPlacement::ResourceId); - reshape.unshaped(&mut state.used_in_token_order, true); - reshape.unshaped(&mut state.resident_apart, true); - #[cfg(debug_assertions)] - self.check_whole(tables, maps, samplers.states(), function_tables); - if reshape.may_reshape() { - self.shape = None; - } - self.instantiated.moved(reshape.moved()); - reshape.moved() - } - - /// Whether the memo's entry, which an earlier compute encoder of the command buffer settled - /// and parked (the module docs, **Parked in its command buffer**), serves a direct dispatch of - /// `tables` and `dispatch` at `counted` moves and sampler slot changes: it holds in every - /// input but its table's stamp (`DispatchMemo::holds_but_stamp`), and the table, read now with - /// its samplers' maps and the device's sampler states `samplers` takes where it needs them - /// ([`refresh`](Self::refresh)), brings in the very state it settled, no value of any kind - /// changed, with the samplers' maps it was settled with. Then it goes on under the table's stamp ([`Across::Taken`]). Where the - /// entry holds but for the stamp, the state is brought in place either way, and a dispatch that - /// takes it not settles from the state as it lies ([`Across::Refreshed`]). - pub(in crate::compute) fn settled_across( - &mut self, - tables: &DispatchTables<'_>, - (dispatch, counted): (&Dispatch, (u64, u64)), - samplers: &mut ArgumentSamplers, - function_tables: &[VisibleFunctionTable], - counts: Counting<'_>, - ) -> Result { - if !(self.memo).holds_but_stamp(&self.state, tables, dispatch, counted) { - return Ok(Across::Missed); - } - let maps = tables.sampler_maps()?; - let listing = (counted.1, &mut *samplers); - let moved = self.refresh(tables, &maps, listing, function_tables, counts); - let same = moved == ValueKinds::default() - && (self.memo.entry()).is_some_and(|kept| kept.settled.sampler_maps == maps); - if !same { - return Ok(Across::Refreshed(maps)); - } - debug_assert!( - (self.memo.entry()) - .is_some_and(|kept| *kept.settled.planned.shape == self.state.shape()), - "a parked dispatch memo taken for a state of another shape" - ); - let device = tables.pipeline.generation(); - self.memo.restamp(tables.table.stamp(), (samplers, device)); - Ok(Across::Taken) - } - - /// That the state brought in place is the one a dispatch of `tables` makes whole - /// (`DispatchTables::bind_state` with `maps` applied), field by field (debug builds): the - /// kernel's table as `ArgumentTable::check_reading` compares it (a float's sign told apart, - /// every NaN alike), the argument samplers as `samplers` lists them where the dispatch took - /// the device's (else the kept listing is of every live state at the count that holds), and - /// every other field equal. - #[cfg(debug_assertions)] - fn check_whole( - &self, - tables: &DispatchTables<'_>, - maps: &SamplerMaps, - samplers: Option<&[crate::sampler::SamplerState]>, - function_tables: &[VisibleFunctionTable], - ) { - // As `ArgumentTable::check_reading`: not in a call that raced a rebind on another thread. - if crate::rebind::call_may_have_raced() { - return; - } - let mut whole = tables.bind_state(samplers.unwrap_or_default(), function_tables); - maps.apply(&mut whole); - let state = &self.state; - let kept = &state.stages[&Stage::Kernel]; - let read = (Stage::Kernel, tables.pipeline.interface()); - let views = tables.pipeline.at_bind_views(); - tables.table.check_reading(kept, read, (maps, views)); - const DIFFERS: &str = "a dispatch's bind state brought in place that is not the one made"; - assert!( - kept.threadgroup_lengths == whole.stages[&Stage::Kernel].threadgroup_lengths, - "{DIFFERS}: its threadgroup lengths" - ); - assert!( - samplers.is_none_or(|samplers| heap_sets::lists(&state.argument_samplers, samplers)), - "{DIFFERS}: its argument samplers" - ); - // Every other field equal, the table and the listing compared above, as their values - // print (a NaN LOD clamp equals none). - let mut rest = BindState::clone(state); - for of in [&mut whole, &mut rest] { - of.stages.clear(); - of.argument_samplers.clear(); - } - assert!(whole == rest, "{DIFFERS}"); - } - - /// The state's shape: the kept one, else the one `found` finds of the state, else made again - /// (counted in `counts`, found or made). - pub(in crate::compute) fn shape( - &mut self, - counts: Counting<'_>, - found: impl FnOnce(&BindState) -> Option>, - ) -> Arc { - if let Some(shape) = &self.shape { - debug_assert!( - **shape == self.state.shape(), - "a kept bind shape that is not its state's" - ); - return Arc::clone(shape); - } - let shape = match found(&self.state) { - Some(shape) => { - debug_assert!( - *shape == self.state.shape(), - "a bind shape found that is not its state's" - ); - counts.dispatch_shape_found(); - shape - } - None => { - counts.dispatch_shape_made(); - Arc::new(self.state.shape()) - } - }; - self.shape = Some(Arc::clone(&shape)); - shape - } - - /// Let go of what its last dispatch settled (`DispatchMemo`), which holds the objects it - /// bound: the state alone, which holds values, is kept for the next encoder. - pub(in crate::compute) fn let_go(&mut self) { - self.memo = DispatchMemo::default(); - } - - /// [`let_go`](Self::let_go) of the state in place and of every state set aside: what each - /// one's last dispatch settled goes, as the device takes them (`SpareLiveDispatches::give`). - fn let_go_all(&mut self) { - self.let_go(); - for aside in &mut self.set_aside { - aside.memo = DispatchMemo::default(); - } - } - - /// Let go of the device's sampler states the memo of the state in place and of every state set - /// aside listed (`DispatchMemo::unlist_samplers`), as they park in their command buffer. - fn unlist_samplers(&mut self) { - self.memo.unlist_samplers(); - for aside in &mut self.set_aside { - aside.memo.unlist_samplers(); - } - } - - /// Its state and memo, read, beside the shadows of its resident textures, the last - /// dispatch's uses, its bind memo and its instantiated commands, kept. - pub(in crate::compute) fn parts( - &mut self, - ) -> ( - &BindState, - &DispatchMemo, - &mut ResidentShadows, - (&mut CommandUses, &mut BindMemo, &mut Instantiated), - ) { - let kept = (&mut self.uses, &mut self.bind, &mut self.instantiated); - (&*self.state, &self.memo, &mut self.shadows, kept) - } -} - -/// A device's bind states that ended compute encoders left, which the compute encoders it opens -/// next start from (the module docs): at most [`SPARE_LIVE_DISPATCHES`], the latest given taken -/// first. Each lies in a box an encoder takes and gives back whole, so its open and end allocate -/// none, and move a pointer rather than the state. -#[derive(Default)] -pub(crate) struct SpareLiveDispatches(Mutex>); - -/// A kept bind state in the box the next compute encoder takes whole. -struct LiveRoom(Box); - -impl SpareLiveDispatches { - /// The state a compute encoder opening starts from: the latest an encoder gave back, else an - /// empty one in a box of its own. - pub(in crate::compute) fn take(&self) -> Box { - let room = lock(&self.0).pop(); - room.map_or_else(Box::default, |LiveRoom(live)| live) - } - - /// Keep `live`, an ended compute encoder's state, for the next encoder to start from, its - /// memo and those of the states it set aside let go ([`LiveDispatch::let_go_all`]) and its - /// resident textures' lists emptied (its bind memo kept), where fewer than - /// [`SPARE_LIVE_DISPATCHES`] are kept; else it goes. - pub(in crate::compute) fn give(&self, mut live: Box) { - live.let_go_all(); - live.shadows.let_go(); - live.unreadable.let_go(); - let mut spare = lock(&self.0); - if spare.len() < SPARE_LIVE_DISPATCHES { - spare.push(LiveRoom(live)); - } - } -} - -/// What [`LiveDispatch::settled_across`] found of a dispatch. -pub(in crate::compute) enum Across { - /// The memo's entry serves it, under its table's stamp now. - Taken, - /// The entry holds but for the stamp, and the state was brought in place with these maps of - /// the table's samplers and the device's sampler states untrimmed; a value moved, or the maps - /// are not the entry's: the dispatch settles from the state as it lies, which a refresh of the - /// same inputs leaves as it is (`compute::settle_live`). - Refreshed(SamplerMaps), - /// The entry does not hold but for the stamp: nothing was done. - Missed, -} - -/// What a compute encoder's end parks in its command buffer for the command buffer's next compute -/// encoder, in place of the device's spares (the module docs, **Parked in its command buffer**): -/// the box of its core, emptied, and its bind state with what its last dispatch settled. -pub(crate) struct Parked { - room: CoreBox, - live: Box, -} - -/// An ending compute encoder's bind state on its way to its command buffer's park, which the box -/// of its core joins, emptied, as the core ends (`EncoderCore::end_with_replay`): [`Parked`]. -pub(crate) struct Parking(Box); - -impl Parking { - /// `live`, an ending compute encoder's: the lists of its resident textures' shadows and - /// carriers emptied, as the device's spares empty them, and the sampler states its memo's entry - /// and those of the states it set aside listed let go (the device's live ones, which its - /// command buffer holds none of: `DispatchMemo::unlist_samplers`). - pub(in crate::compute) fn new(mut live: Box) -> Parking { - live.shadows.let_go(); - live.unreadable.let_go(); - live.unlist_samplers(); - Parking(live) - } - - /// Parked with `room`, the box of the encoder's core, emptied. - pub(crate) fn with_room(self, room: CoreBox) -> Parked { - Parked { room, live: self.0 } - } -} - -impl Parked { - /// The core's box and the bind state, for the compute encoder that opens on them. - pub(in crate::compute) fn into_parts(self) -> (CoreBox, Box) { - (self.room, self.live) - } - - /// Give them back to `device`'s spares as their command buffer commits: the box to its - /// cores', the state to its bind states', its memo let go ([`SpareLiveDispatches::give`]). - pub(crate) fn give_back(self, device: &Device) { - EncoderCore::give_room(device, self.room); - device.shared().live_dispatches.give(self.live); - } -} diff --git a/crates/metal2vulkan-runtime/src/contexts/lines.rs b/crates/metal2vulkan-runtime/src/contexts/lines.rs deleted file mode 100644 index 9c977f7c5..000000000 --- a/crates/metal2vulkan-runtime/src/contexts/lines.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! The queues' serial contexts as a pure structure: one first-in-first-out line of items per -//! logical queue, each line run by at most one thread at a time, and the lines waiting for a thread -//! in the order they became ready. -//! -//! A line is ready when it holds an item, its first item's gate is open, and no thread runs it. A -//! thread takes the first ready line's first item and runs it; until it is done with it, that -//! line's later items wait, while every other line can be taken by another thread. A line that is -//! done and still holds items is ready again, behind the lines that became ready meanwhile. -//! -//! **Gates.** An item may be pushed behind a gate ([`Lines::push_behind`]), which holds it, and its -//! line's later items, until every closing of the gate is opened again ([`Lines::close_new`], -//! [`Lines::close`], [`Lines::open`]): it keeps its place in its line meanwhile. -//! -//! **Places.** Each item pushed takes the next place, whatever its line, so places rise along a -//! line. A line keeps the places of its items that may block a thread that runs them (the -//! `may_block` of [`Lines::new`]), and whether what a thread runs of it may: whether an item -//! leads its line ([`Lines::leads`]) is a look at the line's first item and first such place, -//! however many items the line holds. - -use std::collections::{HashMap, VecDeque}; - -/// The items not yet run, by logical queue. -#[derive(Debug)] -pub(crate) struct Lines { - /// Each queue's line while it holds an item or a thread runs it, by the queue's identity. - lines: HashMap>, - /// The ready lines, in the order they became ready. - ready: VecDeque, - /// The gates not yet open, by token: how many closings each still holds. - closed: HashMap, - /// The places taken so far: the last item pushed took this one, the first 1. - placed: u64, - /// Whether an item may block a thread that runs it ([`Lines::new`]). - may_block: fn(&I) -> bool, -} - -#[derive(Debug)] -struct Line { - items: VecDeque>, - /// The places of the items it holds that may block, in order. - blocking: VecDeque, - /// A thread runs the line's first item. - running: bool, - /// What that thread runs may block: false where no thread runs the line. - running_blocks: bool, -} - -impl Line { - fn new(running: bool, running_blocks: bool) -> Line { - Line { - items: VecDeque::new(), - blocking: VecDeque::new(), - running, - running_blocks, - } - } -} - -#[derive(Debug)] -struct Entry { - item: I, - /// The gate it waits behind, if any ([`Lines::push_behind`]). - gate: Option, - /// Its place ([`Lines::push`]). - place: u64, -} - -impl Lines { - /// Lines in which `may_block` tells whether an item may block a thread that runs it: what - /// [`Lines::leads`] looks past. - pub(crate) fn new(may_block: fn(&I) -> bool) -> Lines { - Lines { - lines: HashMap::new(), - ready: VecDeque::new(), - closed: HashMap::new(), - placed: 0, - may_block, - } - } - - /// Append `item` to `queue`'s line: its place. - pub(crate) fn push(&mut self, queue: u64, item: I) -> u64 { - self.push_entry(queue, item, None) - } - - /// Close the new gate `token` once ([`Lines::push_behind`]). - pub(crate) fn close_new(&mut self, token: u64) { - self.closed.insert(token, 1); - } - - /// Append `item` to `queue`'s line behind the gate `token` ([`Lines::close_new`]): it runs once - /// every closing of the gate is opened ([`Lines::open`]). Its place. - pub(crate) fn push_behind(&mut self, queue: u64, item: I, token: u64) -> u64 { - self.push_entry(queue, item, Some(token)) - } - - fn push_entry(&mut self, queue: u64, item: I, gate: Option) -> u64 { - self.placed += 1; - let place = self.placed; - let blocks = (self.may_block)(&item); - let entry = Entry { item, gate, place }; - let open = self.open_entry(&entry); - let line = (self.lines.entry(queue)).or_insert_with(|| Line::new(false, false)); - if line.items.is_empty() && !line.running && open { - self.ready.push_back(queue); - } - if blocks { - line.blocking.push_back(place); - } - line.items.push_back(entry); - place - } - - /// Whether `entry` waits behind no gate that is still closed. - fn open_entry(&self, entry: &Entry) -> bool { - entry - .gate - .is_none_or(|token| !self.closed.contains_key(&token)) - } - - /// Close the gate `token` once more, where it is not open yet: whether it was not. - pub(crate) fn close(&mut self, token: u64) -> bool { - match self.closed.get_mut(&token) { - Some(closings) => { - *closings += 1; - true - } - None => false, - } - } - - /// Open one closing of the gate `token`, whose item is in `queue`'s line: once none is left, - /// the line is ready where that item is its first and no thread runs it. - pub(crate) fn open(&mut self, queue: u64, token: u64) { - let Some(closings) = self.closed.get_mut(&token) else { - return; - }; - *closings -= 1; - if *closings > 0 { - return; - } - self.closed.remove(&token); - let Some(line) = self.lines.get(&queue) else { - return; - }; - let first = line - .items - .front() - .is_some_and(|entry| entry.gate == Some(token)); - if first && !line.running { - self.ready.push_back(queue); - } - } - - /// Take the first item of the first ready line: the line is running until - /// [`Lines::done`]. `None` when no line is ready. - pub(crate) fn take(&mut self) -> Option<(u64, I)> { - let queue = self.ready.pop_front()?; - let line = self.lines.get_mut(&queue)?; - line.running = true; - let entry = line.items.pop_front()?; - line.running_blocks = line.blocking.front() == Some(&entry.place); - if line.running_blocks { - line.blocking.pop_front(); - } - Some((queue, entry.item)) - } - - /// The thread running `queue`'s line is done with the item it took: the line is ready again - /// if it holds more and the first of them is open, and is forgotten if it holds none. - pub(crate) fn done(&mut self, queue: u64) { - let Some(line) = self.lines.get_mut(&queue) else { - return; - }; - line.running = false; - line.running_blocks = false; - let Some(first) = line.items.front() else { - self.lines.remove(&queue); - return; - }; - let open = first - .gate - .is_none_or(|token| !self.closed.contains_key(&token)); - if open { - self.ready.push_back(queue); - } - } - - /// Take `queue`'s line for the calling thread, where no thread runs it and `plain` holds for - /// each item it holds, none behind a closed gate: those items, in order, which the caller - /// runs before anything it runs in the line itself (which may block where `blocks`); the - /// line is running until [`Lines::done`]. `None` otherwise, changing nothing. - pub(crate) fn take_plain( - &mut self, - queue: u64, - plain: impl Fn(&I) -> bool, - blocks: bool, - ) -> Option> { - if let Some(line) = self.lines.get(&queue) { - let runs = |entry: &Entry| plain(&entry.item) && self.open_entry(entry); - if line.running || !line.items.iter().all(runs) { - return None; - } - } - let (items, blocking) = match self.lines.remove(&queue) { - Some(line) => { - let items: VecDeque = line.items.into_iter().map(|entry| entry.item).collect(); - (items, !line.blocking.is_empty()) - } - None => (VecDeque::new(), false), - }; - if !items.is_empty() { - // A line that holds an item and runs on no thread is ready, once. - self.ready.retain(|ready| *ready != queue); - } - self.lines - .insert(queue, Line::new(true, blocking || blocks)); - Some(items) - } - - /// Take `queue`'s line for the calling thread where it holds no item and no thread runs it, - /// for what may block where `blocks`: the line is running until [`Lines::done`]. False - /// otherwise, changing nothing. - pub(crate) fn take_idle(&mut self, queue: u64, blocks: bool) -> bool { - if self.lines.contains_key(&queue) { - return false; - } - self.lines.insert(queue, Line::new(true, blocks)); - true - } - - /// Whether the item placed at `at` in `queue`'s line ([`Lines::push`]), which the caller knows - /// is not done, leads the line: where it waits there, no item before it may block, nor what a - /// thread runs of the line; where it no longer waits there, a thread runs it. One look at the - /// line's first item and first place that may block, however many items the line holds. - pub(crate) fn leads(&self, queue: u64, at: u64) -> bool { - let Some(line) = self.lines.get(&queue) else { - return false; - }; - let waits = line.items.front().is_some_and(|first| first.place <= at); - match waits { - true => { - let before = line.blocking.front().is_some_and(|&place| place < at); - !line.running_blocks && !before - } - false => line.running, - } - } - - /// How many lines are ready. - pub(crate) fn ready(&self) -> usize { - self.ready.len() - } - - /// Whether a line is ready. - pub(crate) fn is_ready(&self) -> bool { - !self.ready.is_empty() - } - - /// Whether no line holds an item or is running. - #[cfg(test)] - pub(crate) fn is_empty(&self) -> bool { - self.lines.is_empty() - } -} diff --git a/crates/metal2vulkan-runtime/src/contexts/mod.rs b/crates/metal2vulkan-runtime/src/contexts/mod.rs deleted file mode 100644 index e928c0200..000000000 --- a/crates/metal2vulkan-runtime/src/contexts/mod.rs +++ /dev/null @@ -1,621 +0,0 @@ -//! The device's handler threads: each logical queue's serial context, run on a pool of threads, as -//! Metal runs its queues' handlers. -//! -//! - **What a context runs.** In its queue's order, each command buffer's transitions: to -//! `Scheduled` with its scheduled handlers, and to `Completed` (or `Error`) with its completed -//! handlers and the release of what it retained. The scheduler posts them ([`Contexts::post`]), -//! and so does a completion turn, but for a transition that runs none of the program's code: the -//! turn runs such a transition to `Completed` itself where the context runs on no thread and -//! holds only such transitions, in order after them ([`Contexts::run_here`], -//! `command_buffer/completion.rs`), and the scheduler such a transition to `Scheduled` where the -//! context runs on no thread and holds nothing ([`Contexts::run_alone`], -//! `CommandBufferShared::schedule`); neither runs a handler. (A transition to `Scheduled` follows -//! its command buffer's submission handlers, which a `commit_and_submit` call that took its last -//! batch runs on its thread, and the scheduler's thread hands to these threads, in a context of -//! their own (`scheduler::Posted`); it is posted, or run alone, by the thread that ran them once -//! they ran. Where the command buffer's transition to `Completed` comes first, it waits behind a -//! gate those handlers open, its place kept, holding no thread -//! (`CommandBufferShared::gate_for_handlers`), and makes it `Scheduled` first.) A release the -//! scheduler's thread hands off (`Device::let_go_elsewhere`) runs in a context of its own, behind -//! no queue's handlers. A transition to `Completed` of a command buffer that waited on the GPU -//! for another queue's command buffer may be posted behind a gate ([`Contexts::gate`], -//! [`Contexts::post_behind`]), its place in its context kept, until that command buffer's -//! transition, which nothing that may block precedes in its own context ([`Contexts::leads`], -//! [`Run::may_block`]), reaches its handlers (`command_buffer/follow.rs`): a gate holds no -//! thread. -//! - **Done with an item before what it held goes.** The thread that ran an item marks its context -//! done with it, and only then lets go of what the item still holds ([`Run::Held`]): a -//! transition's hold of its command buffer, whose going lets that command buffer's waiters -//! return. So a program whose wait for a command buffer returned finds that command buffer's -//! context running nothing of it, however long the host keeps that thread off the CPU after the -//! hold went: the transition of the queue's next command buffer leads the context, and another -//! queue's command buffer that waited on the GPU for its signal completes after it. -//! - **Metal's order** (measured on an M4, macOS 27.0.1): while one of a -//! queue's handlers blocks, the queue's later transitions wait, even of a command buffer whose -//! work already ran; another queue's transitions and handlers go on, on another thread. Metal -//! ran 256 queues' handlers blocked at once, on 256 threads, and reached no limit. On the M3 -//! Max under macOS 27.0.1 it ran 511 queues' handlers blocked at once in a wait for another -//! queue's command buffer, and those waits returned once it completed; with 512 blocked so (the -//! process's 512 dispatch threads), no handler ran after and the command buffer they waited for -//! never completed: a hang. -//! - **Threads.** One thread starts with the device and stays. Another starts when a context is -//! ready and no thread is free, up to [`THREADS`]; one that found nothing to run for [`IDLE`] -//! ends. The cap is Metal's 512. Each has a stack of [`STACK`] bytes. -//! - **Waits that would deadlock** ([`block`]). A handler's wait for another queue's command -//! buffer blocks its thread. It is refused when it would close a cycle of such waits (across -//! every device) or leave the device's pool with no thread that is not blocked so, the 512th, -//! where Metal's hangs; then at least one thread can always run the contexts the blocked waits -//! wait for. -//! - **Stopping.** The device's drop stops the threads, which end once no item is left: a -//! transition holds its command buffer, which holds the device, so none is left by then; a -//! release may hold nothing of the device, and runs before its thread ends. A drop on one of the -//! threads (its item held the last reference) does not wait for itself. -//! -//! - **Woken only where one sleeps.** A post wakes a thread only where a line is ready and a -//! thread sleeps waiting for one (`State::parked`), read under the state's lock: a thread that -//! sleeps later looks at the lines first. A post to a context a thread is running, or while -//! every thread runs, so costs no system call (a notify is one, sleeper or not). Counted: -//! `WorkCounts::wakes_handler_threads`, `WorkCounts::wakes_spared`. -//! -//! Locks: a pool's state, then its census; the waits' graph, then a census. No call made under -//! either takes the state again. - -pub(crate) mod lines; - -use super::command_buffer::own::{Context, Waits}; -use super::device::lock; -use super::error::{DeadlockCause, Error, MemoryKind}; -use super::exit_guard; -use lines::Lines; -use std::cell::RefCell; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; -use std::time::Duration; - -/// The most threads a device's pool runs at once: Metal's 512 dispatch threads, of which 511 -/// handlers blocked at once in waits for other queues and their waits returned, where 512 hung -/// (the module docs). -pub(crate) const THREADS: usize = 512; - -/// Each thread's stack, in bytes. -pub(crate) const STACK: usize = 512 * 1024; - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -thread_local! { - /// The looks for a thread to run a ready context this thread made ([`Contexts::serve`]). - static SERVES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// The looks for a thread to run a ready context the calling thread made so far, in the device -/// tests' builds. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn serves_here() -> u64 { - SERVES.with(std::cell::Cell::get) -} - -/// A device test's cap on the threads of the pools of devices made from now on, where not 0 -/// ([`device_limit`]): a test drives the pool at its cap with a few contexts. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) static TEST_LIMIT: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// The most threads a device's pool runs at once: [`THREADS`], or a device test's cap -/// (`TEST_LIMIT`). -pub(crate) fn device_limit() -> usize { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if let limit @ 1.. = TEST_LIMIT.load(Ordering::Relaxed) { - return limit; - } - THREADS -} - -/// How long a thread other than the first finds nothing to run before it ends. -const IDLE: Duration = Duration::from_secs(2); - -/// An item of a queue's context: run once, on one of the device's handler threads, or on the -/// thread that runs the context itself ([`Contexts::run_here`]). -pub(crate) trait Run: Send + 'static { - /// What the item still holds once it ran, which its runner lets go of only once the item's - /// context is done with it: what a thread waiting for the item's end waits for (a - /// transition's hold of its command buffer, whose going lets that command buffer's waiters - /// return). So a thread that saw an item end finds its context running nothing of it. - type Held: Send; - - /// Run the item, answering what it still holds ([`Run::Held`]). - fn run(self) -> Self::Held; - - /// Whether the item runs none of the program's code (no handler, no notice, no release of - /// the program's), so that a thread that may run none can run it: none by default. - fn plain(&self) -> bool { - false - } - - /// Whether the item may run on a runtime thread that saw its command buffer complete: it - /// runs none of the program's code but its completion-seen handlers - /// (`CommandBuffer::add_completion_seen_handler`). Every plain item does. - fn runs_where_seen(&self) -> bool { - self.plain() - } - - /// Whether the item may block a thread that runs it, or wait for the program before it runs: - /// it runs a handler of the program's other than its completion-seen handlers, which never - /// block, or waits for one (a scheduled, submission or completed handler). Every item may by - /// default. A transition of another queue waits behind one that may not - /// (`command_buffer/follow.rs`). - fn may_block(&self) -> bool { - true - } -} - -/// One device's handler threads. A clone is another handle of the same pool, which holds nothing -/// of the device. -pub(crate) struct Contexts { - shared: Arc>, -} - -impl Clone for Contexts { - fn clone(&self) -> Contexts { - Contexts { - shared: Arc::clone(&self.shared), - } - } -} - -struct Shared { - state: Mutex>, - /// Signaled when a line becomes ready, where a thread sleeps, or the pool stops. - wake: Condvar, - census: Arc, - /// The notifies made, and those spared as no thread slept or no line was ready. - woke: AtomicU64, - spared: AtomicU64, - /// The identity the next context takes ([`Contexts::fresh`]). - next: AtomicU64, - /// The context whose items a thread pauses after, once it let go of what one held, before it - /// looks at the lines again, until the test lets it go: a test's stand-in for a thread the - /// host took the CPU from there ([`Contexts::pause_after_items`]). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pause: Mutex, - /// Signaled when a pause begins and when pauses are let go. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - paused: Condvar, -} - -/// A test's pause of the pool's threads after the items of one context -/// ([`Contexts::pause_after_items`]). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -#[derive(Default)] -struct Pause { - /// The context's logical queue. - after: Option, - /// The pauses begun: each takes the next number, from 1. - made: u64, - /// The pauses let go: those numbered up to this one end. - released: u64, -} - -struct State { - lines: Lines, - /// The token the next gate takes ([`Contexts::gate`]). - gates: u64, - /// The threads that run no item: waiting for one, or starting. - free: usize, - /// The threads sleeping on the condition variable, waiting for a line. - parked: usize, - stopping: bool, -} - -/// What a pool counts, shared with the waits its threads block in. -pub(crate) struct Census { - count: Mutex, - /// Signaled when a thread ends. - gone: Condvar, -} - -struct Count { - /// The threads alive. - threads: usize, - /// The threads blocked in a wait for another queue's command buffer. - blocked: usize, - /// The most threads: [`THREADS`], or the count reached when the host refused another. - limit: usize, -} - -thread_local! { - /// The census of the pool this thread belongs to, on a handler thread. - static POOL: RefCell>> = const { RefCell::new(None) }; -} - -/// The waits of every handler thread for another queue's context. -static WAITS: Mutex = Mutex::new(Waits::new()); - -impl Contexts { - /// A pool of at most `limit` threads (the device's: [`THREADS`]), with its first thread; - /// refused when the host cannot start it. - pub(crate) fn start(limit: usize) -> Result, Error> { - let shared = Arc::new(Shared { - state: Mutex::new(State { - lines: Lines::new(|item: &I| item.may_block()), - gates: 0, - free: 1, - parked: 0, - stopping: false, - }), - wake: Condvar::new(), - woke: AtomicU64::new(0), - spared: AtomicU64::new(0), - next: AtomicU64::new(0), - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pause: Mutex::default(), - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - paused: Condvar::new(), - census: Arc::new(Census { - count: Mutex::new(Count { - threads: 1, - blocked: 0, - limit, - }), - gone: Condvar::new(), - }), - }); - spawn(&shared, true).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; - Ok(Contexts { shared }) - } - - /// A context's identity, each call a new one: a logical queue's, or a release's of its own - /// (`Device::let_go_elsewhere`). - pub(crate) fn fresh(&self) -> u64 { - self.shared.next.fetch_add(1, Ordering::Relaxed) - } - - /// Append `item` to the context of logical queue `queue`; start a thread when a context is - /// ready that no free thread will take, below the cap. Its place there ([`Lines::push`]). - pub(crate) fn post(&self, queue: u64, item: I) -> u64 { - let mut state = lock(&self.shared.state); - let place = state.lines.push(queue, item); - self.serve(state); - place - } - - /// Run `item` in the context of logical queue `queue` on this thread, after the items that - /// context holds, where no thread runs that context and `may_run` holds for those items and - /// `item` ([`plain`](Run::plain), or, on a thread that may run completion-seen handlers, - /// [`runs_where_seen`](Run::runs_where_seen)): the context runs on this thread meanwhile, so - /// the items posted to it wait for `item`, then run on the pool's threads. Else give `item` - /// back, changing nothing. - pub(crate) fn run_here(&self, queue: u64, item: I, may_run: fn(&I) -> bool) -> Result<(), I> { - if !may_run(&item) { - return Err(item); - } - let blocks = item.may_block(); - let taken = lock(&self.shared.state) - .lines - .take_plain(queue, may_run, blocks); - let Some(before) = taken else { - return Err(item); - }; - let earlier: Vec = before.into_iter().map(Run::run).collect(); - let held = item.run(); - let mut state = lock(&self.shared.state); - state.lines.done(queue); - self.serve(state); - drop((earlier, held)); - Ok(()) - } - - /// A new gate, closed once by the caller, who opens it ([`Contexts::open`]) once it posted - /// the item behind it ([`Contexts::post_behind`]) and closed it for whatever else the item - /// waits for ([`Contexts::close`]). Its token. - pub(crate) fn gate(&self) -> u64 { - let mut state = lock(&self.shared.state); - state.gates += 1; - let token = state.gates; - state.lines.close_new(token); - token - } - - /// Append `item` to the context of logical queue `queue` behind the gate `token` - /// ([`Contexts::gate`]): the item keeps its place in its context, and it and the items after it - /// run once the gate is open. Its place there ([`Lines::push`]). - pub(crate) fn post_behind(&self, queue: u64, item: I, token: u64) -> u64 { - let mut state = lock(&self.shared.state); - let place = state.lines.push_behind(queue, item, token); - self.serve(state); - place - } - - /// Append `item` to the context of logical queue `queue` behind the gate `token` - /// ([`Contexts::gate`]) and open the caller's closing of it, under one lock: one look for a - /// thread to run it ([`post_behind`](Self::post_behind) and [`open`](Self::open) make one - /// each). It runs in its turn once the gate's other closings opened. Its place there. - pub(crate) fn post_gated(&self, queue: u64, item: I, token: u64) -> u64 { - let mut state = lock(&self.shared.state); - let place = state.lines.push_behind(queue, item, token); - state.lines.open(queue, token); - self.serve(state); - place - } - - /// Close the gate `token` once more, where it is not open yet: whether it was not. - pub(crate) fn close(&self, token: u64) -> bool { - lock(&self.shared.state).lines.close(token) - } - - /// Open one closing of the gate `token` of an item of the context of `queue`; once none is - /// left, the item runs there in its turn. - pub(crate) fn open(&self, queue: u64, token: u64) { - let mut state = lock(&self.shared.state); - state.lines.open(queue, token); - self.serve(state); - } - - /// Whether the item posted at the place `at` in the context of `queue`, which the caller knows - /// is not done, leads it: nothing there that may block runs before it ([`Lines::leads`], - /// [`Run::may_block`]). - pub(crate) fn leads(&self, queue: u64, at: u64) -> bool { - lock(&self.shared.state).lines.leads(queue, at) - } - - /// Hold the context of logical queue `queue`, which holds no item and runs on no thread (a - /// command queue's new place's, `queue.rs`), as a thread that runs it does: what is posted - /// there waits until [`release`](Self::release). False where it held an item or ran, changing - /// nothing. - pub(crate) fn hold(&self, queue: u64) -> bool { - // What it waits for may run the program's handlers. - lock(&self.shared.state).lines.take_idle(queue, true) - } - - /// Let the context [`hold`](Self::hold) held run what was posted there meanwhile, in order. - pub(crate) fn release(&self, queue: u64) { - let mut state = lock(&self.shared.state); - state.lines.done(queue); - self.serve(state); - } - - /// Run `item` in the context of logical queue `queue` on this thread, where no thread runs - /// that context, it holds no item, and `item` is [`plain`](Run::plain): the context runs on - /// this thread meanwhile, so the items posted to it wait for `item`, then run on the pool's - /// threads. Else give `item` back, changing nothing. - pub(crate) fn run_alone(&self, queue: u64, item: I) -> Result<(), I> { - let blocks = item.may_block(); - if !item.plain() || !lock(&self.shared.state).lines.take_idle(queue, blocks) { - return Err(item); - } - let held = item.run(); - let mut state = lock(&self.shared.state); - state.lines.done(queue); - self.serve(state); - drop(held); - Ok(()) - } - - /// Start a thread where a context is ready that no free thread will take, below the cap, and - /// wake one where one sleeps and a context is ready: `state` was just changed. - fn serve(&self, mut state: std::sync::MutexGuard<'_, State>) { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - SERVES.with(|serves| serves.set(serves.get() + 1)); - if state.lines.ready() > state.free { - let start = { - let mut count = lock(&self.shared.census.count); - let start = count.threads < count.limit; - if start { - count.threads += 1; - } - start - }; - if start { - if spawn(&self.shared, false).is_ok() { - state.free += 1; - } else { - // The host's threads ran out: the pool keeps those it has, and so does the - // cap on blocked waits. - let mut count = lock(&self.shared.census.count); - count.threads -= 1; - count.limit = count.threads; - } - } - } - let wake = state.parked > 0 && state.lines.is_ready(); - drop(state); - if wake { - self.shared.woke.fetch_add(1, Ordering::Relaxed); - self.shared.wake.notify_one(); - } else { - self.shared.spared.fetch_add(1, Ordering::Relaxed); - } - } - - /// The notifies made to the threads, and those spared. - pub(crate) fn wakes(&self) -> (u64, u64) { - ( - self.shared.woke.load(Ordering::Relaxed), - self.shared.spared.load(Ordering::Relaxed), - ) - } - - /// Stop the threads and wait for them to end, but for this one when it is one of them: each - /// runs the items left first. The device is being dropped, so no transition is left. - pub(crate) fn stop(&self) { - lock(&self.shared.state).stopping = true; - self.shared.wake.notify_all(); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - self.release_pauses(u64::MAX); - let census = &self.shared.census; - // A thread whose thread-locals are gone (an exiting thread's, whose `exit` destroys them - // before the exit handlers run, `this_thread.rs`) is no handler thread. - let own = POOL - .try_with(|pool| { - pool.borrow() - .as_ref() - .is_some_and(|pool| Arc::ptr_eq(pool, census)) - }) - .unwrap_or(false); - let floor = usize::from(own); - let mut count = lock(&census.count); - while count.threads > floor { - count = census - .gone - .wait(count) - .unwrap_or_else(std::sync::PoisonError::into_inner); - } - } - - /// Make a pool's thread pause once it let go of what an item of the context of logical queue - /// `queue` held, before it looks at the lines again, as a thread the host took the CPU from - /// there would, until [`Contexts::release_pauses`] lets its pause go (as the pool stops, every - /// pause goes). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn pause_after_items(&self, queue: u64) { - lock(&self.shared.pause).after = Some(queue); - } - - /// How many pauses the pool's threads began ([`Contexts::pause_after_items`]). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn pauses_made(&self) -> u64 { - lock(&self.shared.pause).made - } - - /// Wait until the pool's threads began `pauses` pauses, or `within` passed: the pauses begun. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn await_pauses(&self, pauses: u64, within: Duration) -> u64 { - let pause = lock(&self.shared.pause); - let (pause, _) = (self.shared.paused) - .wait_timeout_while(pause, within, |pause| pause.made < pauses) - .unwrap_or_else(std::sync::PoisonError::into_inner); - pause.made - } - - /// Let the pauses numbered up to `through` go (each pause takes the next number, from 1). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn release_pauses(&self, through: u64) { - let mut pause = lock(&self.shared.pause); - pause.released = pause.released.max(through); - drop(pause); - self.shared.paused.notify_all(); - } - - /// The threads alive and the threads blocked in a wait. - #[cfg(test)] - pub(crate) fn census(&self) -> (usize, usize) { - let count = lock(&self.shared.census.count); - (count.threads, count.blocked) - } -} - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -impl Shared { - /// The pause a test asked for once a thread let go of what an item of the context of - /// logical queue `queue` held, until the test lets it go ([`Contexts::pause_after_items`]). - fn pause_after_item(&self, queue: u64) { - let mut pause = lock(&self.pause); - if pause.after != Some(queue) { - return; - } - pause.made += 1; - let number = pause.made; - self.paused.notify_all(); - drop( - (self.paused) - .wait_while(pause, |pause| pause.released < number) - .unwrap_or_else(std::sync::PoisonError::into_inner), - ); - } -} - -/// Start one of `shared`'s threads (counted already); `first` stays until the pool stops. -fn spawn(shared: &Arc>, first: bool) -> std::io::Result<()> { - let shared = Arc::clone(shared); - exit_guard::spawn_user_interactive( - std::thread::Builder::new() - .name("metal2vulkan-handlers".into()) - .stack_size(STACK), - move || run(&shared, first), - ) - .map(drop) -} - -/// A thread's loop: run the ready contexts' items, one at a time. -fn run(shared: &Shared, first: bool) { - POOL.with(|pool| *pool.borrow_mut() = Some(Arc::clone(&shared.census))); - let mut state = lock(&shared.state); - loop { - if let Some((queue, item)) = state.lines.take() { - state.free -= 1; - drop(state); - let held = item.run(); - // Its line is done with it before what it holds goes ([`Run::Held`]). - lock(&shared.state).lines.done(queue); - drop(held); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - shared.pause_after_item(queue); - state = lock(&shared.state); - state.free += 1; - continue; - } - if state.stopping { - break; - } - state.parked += 1; - let (next, waited) = shared - .wake - .wait_timeout(state, IDLE) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state = next; - state.parked -= 1; - if waited.timed_out() && !first && !state.lines.is_ready() && !state.stopping { - break; - } - } - state.free -= 1; - drop(state); - POOL.with(|pool| *pool.borrow_mut() = None); - let mut count = lock(&shared.census.count); - count.threads -= 1; - drop(count); - shared.census.gone.notify_all(); -} - -/// Whether this thread is one of a pool's handler threads: not where its thread-locals are gone -/// (an exiting thread's, whose `exit` destroys them before the exit handlers run, -/// `this_thread.rs`). -pub(crate) fn on_handler_thread() -> bool { - POOL.try_with(|pool| pool.borrow().is_some()) - .unwrap_or(false) -} - -/// A handler thread's wait for another queue's context, counted until dropped. -pub(crate) struct Blocked { - census: Arc, - from: Context, - to: Context, -} - -/// Count a wait of this handler thread, which runs `from`'s item, for `to`'s context. Refused, -/// with its cause: when it would close a cycle of such waits (`Cycle`), and when it would leave -/// this thread's pool with no thread that is not blocked so, or this is not a handler thread -/// (`HandlerThreadCap`). -pub(crate) fn block(from: Context, to: Context) -> Result { - let census = POOL - .with(|pool| pool.borrow().clone()) - .ok_or(DeadlockCause::HandlerThreadCap)?; - let mut waits = lock(&WAITS); - if waits.closes_cycle(from, to) { - return Err(DeadlockCause::Cycle); - } - { - let mut count = lock(&census.count); - if count.blocked + 1 >= count.limit { - return Err(DeadlockCause::HandlerThreadCap); - } - count.blocked += 1; - } - waits.insert(from, to); - Ok(Blocked { census, from, to }) -} - -impl Drop for Blocked { - fn drop(&mut self) { - lock(&WAITS).remove(self.from, self.to); - lock(&self.census.count).blocked -= 1; - } -} diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs deleted file mode 100644 index 7d6647183..000000000 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ /dev/null @@ -1,2691 +0,0 @@ -//! Copied host buffers: a no-copy buffer whose import of the caller's pages the caller's gate -//! refused ([`HostMemory::with_import_gate`](crate::HostMemory)), whose pointer the device refused -//! with no dma-buf of the pages serving it (no source of them given, or one that failed or whose -//! dma-bufs the device refused; RADV refuses shared memory, a `memfd` mapping among it, and a -//! device without `VK_EXT_external_memory_host` every pointer), or whose import the gate and the -//! device admitted and that then failed (out of memory, another Vulkan error, or the runtime's -//! refusal of pages the kernel cannot pin on a driver whose failed import of them breaks it, -//! `RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, that no dma-buf of them served), is made -//! all the same over a copy of its bytes (`Device::buffer_over_host_memory`), announced -//! (`copied-host-pages`). No import maps the pages, so they take no kernel mapping. -//! -//! - **The copy.** A `VkBuffer` of the buffer's length in host-visible, coherent memory of the -//! runtime's own ([`MemoryClass::Shared`](crate::memory::MemoryClass)), which the GPU uses; the -//! buffer's `contents` stays the caller's pointer, as Metal's is. Made over pages the process -//! reads ([`read_caller`]): the first copy reads them through the kernel ([`read_pages`]), and -//! where the kernel fails the read, with plain loads where the process maps every page with -//! read permission ([`mapped_readable`]): on Linux the kernel reads no page it cannot pin, such -//! as a mapping of a dma-buf (`VM_PFNMAP`). Pages not mapped, or mapped without read permission -//! (memory Metal makes no buffer over), keep the import's own refusal. -//! - **One memory, one copy.** A no-copy buffer made over exactly the bytes (the same first byte -//! and length) a live copied buffer was made over lies in its copy, of either storage mode, as -//! one made over a live import's bytes lies in that import (`host_aliases.rs`): one `VkBuffer`, -//! one base, one hazard key, the gate not asked and no page read. So two textures over one -//! surface's pages are ordered as one resource's accesses are, with no trip through the pages. -//! A rebind to such bytes lies in the copy too where its textures were planned at the copy's -//! offset (its first byte) and no image in place rides on it. Counted: -//! `WorkCounts::copied_host_buffers_shared`. A heap's own buffer and a buffer whose GPU writes -//! are dropped keep their own (`host_aliases.rs`, "Not joined"). -//! - **Coherence.** The runtime keeps, for each copy, the bytes the pages and the copy last agreed -//! on. At each commit, before any of the command buffer's work is submitted, every byte the CPU -//! changed in the pages since then is written into each copy its commands use, or into every copy -//! where one may reach memory no use names (a function that reaches buffers through addresses, -//! work on the GPU alone; [`CopiedBuffers::copy_in`]): a copy the command buffer does not use -//! takes the CPU's writes at the first commit that uses it. A batch that waits for an event value -//! not reached before that copy in runs its commands after the wait, where Metal's read the -//! pages as they stand then: it copies in again the same way as it is submitted, its wait met -//! (`command_buffer/copies_again.rs`, `WorkCounts::copied_copy_ins_after_waits`), so a CPU -//! write made before the signal reaches it. At each batch's completion, before -//! its events are seen signaled, the scheduler is told, its handlers run or a waiter returns, -//! every byte the GPU changed in the copy is written back into the pages, where the CPU did not -//! change that byte since ([`CopiedBuffers::merge_back`]): a byte both changed keeps the CPU's, -//! which the next commit copies in. The completion compares only the copies its batches may have -//! written: one whose buffer's (or heap's) key a use of their command buffers' commands wrote, -//! and every copy where one of those may have written memory no use names (the loaded addresses -//! of a function that may store or update memory atomically, an indirect command buffer's -//! executions; `CopiesReached`), or kept its writes not all apart. Counted: -//! `WorkCounts::copied_merges_compared`, `copied_merges_skipped`. Inside a block that differs, a -//! comparison compares bytes 16 at a time (8 off x86-64) with the bytes the pages and the copy -//! agreed on, and stores only those that changed and that the other side did not change since: -//! all 16 in one store where every one of them is to be written, else those alone in one masked -//! store on an x86-64 host with AVX-512BW, and elsewhere in the fewest stores of 8, 4, 2 and 1 -//! bytes (of 8 and 1 off x86-64; `merge_block`), so no byte one side did not change is ever -//! written, and a byte the other side writes meanwhile is stored over only where the first side -//! changed it too, in the window between the comparison's read of it and its store. So a CPU -//! write to the pages made before the completion reads its block is always kept; one made while -//! the merge runs is kept but for a byte the GPU also changed, which then keeps the CPU's or the -//! GPU's. Only a program that writes a byte of the buffer from the CPU that a command buffer -//! still running writes too meets that window, a race Metal leaves to the later write. Each batch -//! ends with a barrier that makes its writes visible to the host (`tracker::Barrier::to_host`). -//! Where the pages' memory came with a log of the writes to them (`HostMemory::with_dirty_pages`, -//! or its guest RAM's, `HostRam::with_dirty_pages`), each merge back reports the blocks of 4 KiB -//! it wrote to the log as the copy's own writes, in one call (`DirtyPages::wrote_runs_as`, a -//! writer of the copy's own) before it returns: the log sees no write the runtime makes, and -//! every other copy and shadow of the pages takes them. -//! - **The copy is the base until the GPU may write it.** Only copies in write a copy until a -//! command buffer that may write it is committed, so until then it holds the bytes its pages -//! and it agree on, and a copy in compares the pages with the copy itself, a page (4 KiB) at a -//! time, and writes in the bytes that differ. A copy the GPU only reads (no use of a committed -//! command buffer wrote one of its keys, and none may have written memory no use names) holds -//! nothing beyond itself, and no completion compares it. -//! - **A base once it may.** At the first commit whose command buffer may write the copy (its -//! commands wrote one of its keys, or may write memory no use names), after its copy in and -//! before any of its work is submitted, the copy takes a base of the bytes it then holds -//! ([`Base`]): a 128-bit tag of each 1 KiB block ([`tag`]: two NH sums keyed by a random key of -//! the process's, `TAG_BLOCK`), kept in host memory (a 64th of the copy's length), and the bytes -//! themselves, kept in the device's memory where it has room for them, else in the host's -//! (`Device::copied_base`): device-local memory the host maps, coherent, in a heap of 1 GiB or -//! more (a resizable BAR makes it the device's memory; without one it is a window of about 256 -//! MiB, which no base takes; nor does a device with unified memory, where that memory is the -//! host's), while the runtime's blocks in that heap and the base stay within half of it. From -//! then on each comparison reads one side and its tags: a commit's copy in reads the pages' -//! blocks, and only a block whose tag changed reads the copy's block; a completion's merge back -//! reads the copy's blocks, and only a block whose tag changed reads the pages' block. The base's -//! bytes are the other side's block where its tag still agrees, and are read from the base only -//! for a block both sides changed since they agreed (where they are in the device's memory, a -//! read across the bus the host does not cache, with streaming loads on an x86-64 host with -//! SSE4.1, and slower still while the GPU idles in a low power state). A comparison leaves such -//! blocks for a second pass ([`two_passes`]), which reads them through one copy into host memory -//! on the device's staging queue where they are `READ_BACK_BLOCKS` or more (a base lies in the -//! device's memory only on a device with one, a queue that waits for no work of the -//! program's), and the host reads each where they are fewer or that copy is not made -//! (`WorkCounts::copied_base_blocks_read_back`). A block of the device's memory so read is kept -//! in host memory from then on -//! (`HostBlock`), its later reads and writes the host's, so a block both sides write again and -//! again crosses the bus once, and the host bytes such a base holds are its tags and those blocks -//! (where the host has no memory for one, the block stays in the device's). The base then takes -//! each block that changed. A block whose tag agrees is taken as unchanged: for a block that -//! changed, that happens with a chance of at most 2^-64 at each comparison ([`tag`]), the only -//! place the runtime takes a tag for the bytes; a copy without a base compares bytes. Where the -//! host has no memory for a base, the commit fails with `Error::OutOfMemory` and runs nothing, as -//! Metal fails a command buffer for memory, and the copy keeps none (it holds what its pages and -//! it agree on). Counted: `WorkCounts::copied_bases_made`, `copied_bases_refused`, -//! `copied_base_blocks_read`, and the gauges `copied_base_host_bytes`, `copied_base_device_bytes` -//! and `copied_base_host_blocks`. -//! - **Copies in the log gates.** Where the pages' memory came with such a log (a copy that drops -//! the GPU's writes included: its guest RAM's runs are asked as a writable copy's are), a -//! commit's copy in compares only the pages the log reports written since the copy's last copy -//! in, and the -//! bytes no log keeps (a guest RAM's runs that miss some of them): a stamp of each log is asked -//! at the commit, once for every copy, its publication waited for (bounded) with no lock of -//! the copies' or the command buffer's held, and the copy synced to it -//! ([`CopiedBuffers::copy_in`]); every write made before the commit is in that publication, -//! the GPU's in place through other imports of the pages and the runtime's own CPU writes among -//! them, which the runtime reports (`dirty_pages.rs`). A copy compares every byte at its first -//! copy in after its watch began, and where a log cannot say. Counted: -//! `WorkCounts::copied_copy_in_bytes_skipped`. -//! - **Pages the process cannot write** (read-only pages, as a consumer's alias of a read-only -//! replace, `replaceBackingWithRanges:readOnly:`, maps them), asked of the system as the copy is -//! made ([`mapped_writable`]), and memory of Metal's private option bit 24 where the system maps -//! no read-only view of the pages (`read_only_view.rs`, copied whatever the gate would answer): -//! the GPU's writes to the copy are dropped, as Metal drops the GPU's writes to read-only -//! memory. At each batch's completion every byte the -//! GPU changed in the copy takes back the byte the pages and the copy last agreed on -//! ([`CopiedBuffers::merge_back`]), and nothing is written to the pages: later commands of the -//! same batch read the write back, and a later command buffer the pages' bytes. The CPU's writes -//! to the pages through another mapping are copied in at each commit, as above. Counted: -//! `WorkCounts::copied_dropped_bytes`. -//! - **Between copies, GPU to GPU** (`docs/FAST-PATHS.md`, known gaps). A copy and another copy, or -//! an import, of pages that overlap without being the same bytes (a rebind's bytes inside a -//! surface's, a guest RAM chunk's import over a copy's pages, a buffer whose texture moved in -//! its page, the bytes again after a reported remap), and a copy beside a live import of the same -//! bytes for the other storage mode's class (a `Managed` buffer's import, then a `Shared` -//! buffer's copy where the gate refused its own), are two memories, which agree only through -//! the pages: at the writer's completion (its merge back, or its writes in place) and at the -//! reader's commit (its copy in), or a batch's submission after an event wait its commit came -//! before (its copy in again, above). A read committed before the write completed reads the -//! bytes as of its commit, wherever the tracker orders it after the write: in one command -//! buffer, and in one queue's command buffers in flight together. Of two such copies written in -//! flight, the second's merge back takes a byte the first merged for the CPU's write, which a -//! merge keeps, so the first write stays where Metal keeps the later. -//! - **Event signals.** A batch's event signals, submitted while a copy is live, are seen at its -//! completion turn alone, after the merge: no read of the value observes them earlier, and a -//! wait for them is held on the host until that turn (`event_timeline.rs`), so the GPU's writes -//! before a signal are in the pages once its value is seen, as Metal's are. No submission is -//! added; a reader sees the value a completion turn later than the semaphore's counter shows it. -//! - **Cost.** A copy is compared whole at each batch's completion that may have written it, and at -//! each commit where its pages carry no log: O(bytes) per such batch, and per commit without a -//! log, a fallback's cost (`docs/FAST-PATHS.md`, known gaps). A command buffer whose functions -//! read addresses may write every copy. Without a base, a page that agrees costs one read of each -//! side and a slice comparison; with one, a block that agrees costs one read of one side and its -//! tag (SSE2 on x86-64, about 55 GB/s over a block in the first-level cache on a Ryzen 7 7840HS). -//! A comparison of at least twice `SPLIT_BYTES` (2 MiB) of a copy, with a base or without (a -//! commit's copy in of every byte of a copy the GPU only reads, whose pages carry no log), splits -//! its blocks into runs of at least that many, one for each of up to eight threads, the calling -//! one among them: it starts at most seven, each with a 256 KiB stack, and they end before it -//! returns, so a device's comparisons, which its copies' lock keeps one at a time, hold at most -//! seven more threads at once (`WorkCounts::copied_compare_threads`). On that host, on four -//! threads, a 256 MiB copy with a base that agrees took 5.8-6.1 ms each way; where every byte -//! changed on both sides 25.7-26.4 ms in and 25.9-27.3 ms back; where every float of it was -//! rewritten as `x + i` (the GPU's side alone), 25.5-27.5 ms back, and 40.1-47.4 ms without the -//! host's masked stores; with other work running, 680 MiB of copies that agree 29-30 ms each -//! way, their logged copy in 0.2 ms where no page changed and 4.2 ms where 1% of the pages -//! changed on each side; a merge back of no copy written, none (`tests/copied_bench.rs`; -//! `docs/FAST-PATHS.md` has the snapshot's figures they replaced). Counted: -//! `WorkCounts::copied_copy_in_bytes`, `WorkCounts::copied_merge_back_bytes`, -//! `WorkCounts::copied_dropped_bytes`. -//! - **Heaps and rebinds.** A no-copy heap's own buffer is copied as a buffer is, where the heap's -//! textures could lie, with a heap's hazard identity; its buffers lie in the copy at their -//! offsets, and its textures are shadows of its bytes (`AliasRoute::MemoryShadow` or Metal's -//! tiles). A buffer's or heap's rebind gives it a copy of its new pages laid out as their import -//! would be (`Device::copied_pages`), so texel views planned at the bytes' offset lie where they -//! lay, and at the old offset where the bytes moved in their page under a texture; the heap's -//! textures bound to its bytes and the images in place over the buffer are made again over the -//! copy: in fresh pages the runtime imported where an image in place rides on it, made as over -//! the caller's pages; else linear images of its memory that start `PREINITIALIZED`. -//! - **What is not copied.** On macOS, memory whose GPU writes Metal's private option bit 24 drops -//! imports a read-only view of its pages (`read_only_view.rs`). -//! - **Textures over a copy.** A texture made over a copied buffer is a linear image over the copy, -//! bound in its memory at the texels' offset, where the device's in-place check passed for the -//! caller's pages (a rebind may import them; and the device's store path, which renders and -//! writes into the copy take too) and the copy's memory, for the texture's accesses and how its -//! texels lie in lines there (`in_place.rs`, `texture/route.rs`; counted: -//! `WorkCounts::copied_textures_in_place`): in fresh pages the runtime imported, the image made -//! for host allocations, as over the caller's pages, under the fresh pages' check; in memory the -//! device allocates, the driver's own linear image that starts `PREINITIALIZED`, so its first -//! move keeps the copy's bytes, else a `DRM_FORMAT_MOD_LINEAR` one at Metal's pitch, made -//! `UNDEFINED`, under the check of the runtime's pooled memory too (`PagesClass::Pooled`). Its -//! hazard identity is the buffer's, so its uses name the copy as the buffer's do: each commit -//! copies the CPU's writes in, and each completion that may have written it merges the GPU's -//! back. Elsewhere it is a shadow of the copy's bytes (`shadowed-texture`). - -use crate::device::lock; -use crate::dirty_pages::{new_writer, DirtySource, DirtyTally, PagesLog}; -use crate::host_memory::{mapped_readable, mapped_writable}; -use crate::key_hash::KeyMap; -use crate::memory_log::{copied_line, MemoryLog}; -use crate::resource::ResourceKey; -use crate::work_counts::Counters; -use crate::DirtyStamp; -use std::collections::HashMap; -use std::hash::BuildHasher; -use std::num::NonZeroU64; -use std::ops::{Deref, Range}; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, PoisonError}; - -/// A device's live copied host buffers, compared at each commit and each batch's completion. -#[derive(Default)] -pub(crate) struct CopiedBuffers { - entries: Mutex>, - /// How many are live: a commit or completion looks no further where none is. - live: AtomicUsize, - /// The next copy's id. - next: AtomicU64, - /// A batch finished with no merge back (a failed wait): the next merge back compares every - /// copy, whatever its batches wrote. - owed: AtomicBool, - /// The host bytes the live copies' bases hold ([`Base`]): their tags, and the agreed bytes - /// of those kept in host memory. A gauge (`WorkCounts::copied_base_host_bytes`). - base_host_bytes: AtomicU64, - /// The device bytes the live copies' bases hold: the agreed bytes of those kept in the - /// device's memory. A gauge (`WorkCounts::copied_base_device_bytes`). - base_device_bytes: AtomicU64, - /// The blocks of the live copies' bases in the device's memory that are kept in host memory - /// ([`HostBlock`]). A gauge (`WorkCounts::copied_base_host_blocks`). - base_host_blocks: AtomicU64, - /// The tests' stand-in for a host with no memory for a base ([`CopiedBuffers::refuse_bases`]). - #[cfg(test)] - bases_refused: AtomicBool, - /// The device's memory log, where it is on: each copy's making and going are lines of it - /// (`memory_log.rs`). - log: Option, -} - -/// The copies commands reached, by the keys of their uses, or every copy: what the batches a -/// completion turn finishes may have written ([`CopiedBuffers::merge_back`], the keys their -/// command buffers' commands wrote, `DirtyCommit::copies_written`), or what a committed command -/// buffer's commands may read or write ([`CopiedBuffers::copy_in`], the keys they used, -/// `DirtyCommit::copies_used`). -#[derive(Default)] -pub(crate) struct CopiesReached { - keys: KeyMap, - all: bool, - /// Where every copy may have been reached through memory no use names alone - /// ([`reached_unnamed`](Self::reached_unnamed)): the keys stay those the uses named, and - /// whether no function of the command buffer may store through an address. - unnamed: Option, -} - -impl CopiesReached { - /// Every copy may have been reached. - pub(crate) fn all() -> CopiesReached { - CopiesReached { - keys: KeyMap::default(), - all: true, - unnamed: None, - } - } - - /// A command reached the bytes of `key`. - pub(crate) fn reached(&mut self, key: ResourceKey) { - if !self.all { - self.keys.insert(key, ()); - } - } - - /// Some command may have reached a copy no use of it names. - pub(crate) fn reached_all(&mut self) { - self.all = true; - self.unnamed = None; - self.keys.clear(); - } - - /// Some command may have reached a copy no use of it names through memory no use names (a - /// loaded address), where every use was noted: every copy may have been reached, and the keys - /// the uses named so far stay, so a copy in tells the copies that reach alone compares - /// (`WorkCounts::copied_unnamed_reach_copy_ins`). `reads_only`: no function of the command - /// buffer may store through an address (`State::writes_unnamed`). - pub(crate) fn reached_unnamed(&mut self, reads_only: bool) { - if !self.all { - self.unnamed = Some(reads_only); - } - self.all = true; - } - - /// Where the copy whose uses take `keys` was reached through memory no use names alone - /// ([`reached_unnamed`](Self::reached_unnamed)): whether that reach only reads. - fn unnamed_alone(&self, keys: &[(ResourceKey, usize)]) -> Option { - let named = keys.iter().any(|(key, _)| self.keys.contains_key(key)); - self.unnamed.filter(|_| !named) - } - - /// Whether a command may have reached the copy whose uses take `keys`. - fn meets(&self, keys: &[(ResourceKey, usize)]) -> bool { - self.all || keys.iter().any(|(key, _)| self.keys.contains_key(key)) - } -} - -/// The caller's bytes as a copy's first read of them took them ([`CopiedBuffers::read`]), before -/// the copy's memory was made: the bytes the copy and the pages first agree on, written into the -/// copy and let go of as it is registered ([`CopiedBuffers::add`]), and whether the GPU's writes -/// to the copy are dropped. -pub(crate) struct FirstRead { - bytes: Box<[u8]>, - drops_writes: bool, -} - -impl FirstRead { - /// `length` bytes at `pages`, read by `read`, which answers whether it read every one. - /// - /// # Safety - /// - /// `read` reads `pages` as [`CopiedBuffers::read`]'s contract lets it. - pub(crate) unsafe fn of( - pages: NonNull, - length: usize, - read: impl FnOnce(NonNull, &mut [u8]) -> bool, - drops_writes: bool, - ) -> Result { - let mut bytes = Vec::new(); - if bytes.try_reserve_exact(length).is_err() { - return Err(NotCopied::OutOfHostMemory); - } - bytes.resize(length, 0u8); - let mut bytes = bytes.into_boxed_slice(); - if !read(pages, &mut bytes) { - return Err(NotCopied::Unreadable); - } - Ok(FirstRead { - bytes, - drops_writes, - }) - } -} - -/// Why a copy was not made ([`CopiedBuffers::read`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum NotCopied { - /// A page is not mapped, or mapped without read permission: memory Metal makes no buffer over. - Unreadable, - /// The host has no memory for the copy's first read of the pages, or for its base - /// ([`CopiedBuffers::copy_in`]). - OutOfHostMemory, -} - -/// A copy and the caller's pages it mirrors. -struct Entry { - id: u64, - /// The caller's bytes (the buffer's `contents`). - pages: NonNull, - /// The copy's bytes, mapped. - copy: NonNull, - /// How many bytes the pages and the copy are. - length: usize, - /// The bytes the pages and the copy last agreed on, once a commit whose command buffer may - /// write the copy made it ([`CopiedBuffers::copy_in`]). Until then the copy holds them: only - /// copies in write it. - base: Option, - /// The process cannot write the pages: the GPU's writes to the copy are dropped, never merged - /// back. - drops_writes: bool, - /// The logs of the writes to the pages, where their memory came with one, and the writer its - /// merges back are reported as ([`Copied::set_log`]). - log: Option, - /// The keys whose uses' writes reach the copy, each with how many pages lying in it named it - /// ([`Copied::name`]): the buffer's, or the heap's bytes' (whose buffers' and textures' uses - /// carry it), each buffer's that lies in it besides (`host_aliases.rs`), a buffer's again after - /// a rebind. A key goes with the last pages that named it ([`Copied::unname`]), so the keys are - /// those of the buffers lying in the copy now, however many came and went. - keys: Vec<(ResourceKey, usize)>, - /// A read twin reads the copy's pages in place while its buffer lies in it (`read_twin.rs`, - /// [`Copied::set_twinned`]): counted where a command buffer's reach of memory no use names - /// alone compares the copy (`WorkCounts::copied_unnamed_reach_twin_copy_ins`). - twinned: bool, -} - -/// A copy's logs of its pages, and its writer in them. -struct CopyLog { - pages: Arc, - writer: NonZeroU64, - /// Its watches of the pages in each log, held while the copy lives. - _watches: Vec>, - /// The copy's bytes no log keeps the writes to: every copy in compares them. - unlogged: Arc<[Range]>, - /// The stamps, one of each log in [`PagesLog::sources`]' order, as of which the copy holds - /// every byte the CPU wrote in the pages: a copy in compares only the pages the logs report - /// written since. `None` until a copy in compared every byte after the watches began, and - /// after one some log could not answer for. - since: Option>, - /// The bytes its merges back wrote into the pages since `since`: at [`ASKS_APART`] or more, - /// its copy in asks the logs for the pages any writer but it wrote - /// ([`DirtyPages::changed_except`](crate::DirtyPages)), where a copy otherwise takes the - /// pages every writer wrote, asked once per log and stamp for every copy, and compares again - /// the pages it merged. - merged: u64, -} - -/// A test's clock of the copies' comparisons (`tests/copied_bandwidth_bench.rs`): the time each -/// copy in, merge back and read back of a base's blocks took whole, and of every [`SAMPLE`]th -/// block a comparison looked at, the time each of its phases took, in nanoseconds since the -/// process began. Global: a benchmark reads it about calls it alone makes. -/// -/// [`SAMPLE`]: clock::SAMPLE -#[cfg(test)] -pub(crate) mod clock { - use std::sync::atomic::{AtomicU64, Ordering}; - use std::time::Instant; - - /// One block in this many is timed. - pub(crate) const SAMPLE: usize = 64; - /// [`WHOLE`]'s and [`PHASES`]' index of copies in. - pub(crate) const COPY_IN: usize = 0; - /// Their index of merges back. - pub(crate) const MERGE_BACK: usize = 1; - /// [`WHOLE`]'s index of reads back. - pub(crate) const READ_BACK: usize = 2; - /// Whole calls: copies in, merges back, reads back. - pub(crate) static WHOLE: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; - /// The sampled blocks' phases, of copies in and of merges back: finding that the block - /// changed (its tag, and its bytes read where it did), the other side's block (its bytes, its - /// tag, and the base's bytes where both changed), the stores of the bytes that changed, and - /// the base's taking of the block. - pub(crate) static PHASES: [[AtomicU64; 4]; 2] = [const { [const { AtomicU64::new(0) }; 4] }; 2]; - - /// Add the time since `since` to `WHOLE[which]`. - pub(crate) fn whole(which: usize, since: Instant) { - WHOLE[which].fetch_add(since.elapsed().as_nanos() as u64, Ordering::Relaxed); - } - - /// One block's phases, timed where it is sampled: each [`Lap::next`] ends one, and the drop - /// the last begun. - pub(crate) struct Lap { - of: usize, - phase: usize, - at: Option, - } - - impl Lap { - /// The phases of the block at `index` of a comparison `of`. - pub(crate) fn new(of: usize, index: usize) -> Lap { - Lap { - of, - phase: 0, - at: index.is_multiple_of(SAMPLE).then(Instant::now), - } - } - - /// End the phase running. - pub(crate) fn next(&mut self) { - if let Some(at) = self.at { - let now = Instant::now(); - let spent = (now - at).as_nanos() as u64; - PHASES[self.of][self.phase].fetch_add(spent, Ordering::Relaxed); - self.at = Some(now); - } - self.phase = (self.phase + 1).min(3); - } - } - - impl Drop for Lap { - fn drop(&mut self) { - if let Some(at) = self.at { - let spent = at.elapsed().as_nanos() as u64; - PHASES[self.of][self.phase].fetch_add(spent, Ordering::Relaxed); - } - } - } -} - -/// The bytes a copy's merges back wrote since its last copy in from which its copy in asks the -/// logs apart, for every writer's pages but its own (one more question of each log, which a -/// consumer answers by a pass over its watches), rather than compare its own writes again -/// (about 40 µs a MiB on an M3 Max). Both are exact. -const ASKS_APART: u64 = 1 << 20; - -/// The bytes of a block a copy's base tags and compares at once ([`Base`]). -pub(crate) const TAG_BLOCK: usize = 1024; - -/// A block's tag ([`tag`]). -type Tag = [u64; 2]; - -/// The words of the key of [`tag`]: one for each word of a block, and four more for its second -/// sum's key, the first's shifted by four words. -const KEY_WORDS: usize = TAG_BLOCK / 4 + 4; - -/// The key of every [`tag`] in the process: random words, made once, which no caller sees. -pub(crate) fn key() -> &'static [u32; KEY_WORDS] { - static KEY: OnceLock<[u32; KEY_WORDS]> = OnceLock::new(); - KEY.get_or_init(|| { - // The standard library's hasher keyed from the system's randomness, as a keyed function - // of each pair of words' place. - let random = std::collections::hash_map::RandomState::new(); - std::array::from_fn(|at| (random.hash_one(at / 2) >> (32 * (at % 2))) as u32) - }) -} - -/// A block's tag: two NH sums of its bytes (RFC 4418's NH: each 32-byte stretch's little-endian -/// words `m0` to `m7`, `(m_i + k_i) * (m_{i+4} + k_{i+4})` for `i` from 0 to 3, the words and -/// their key words added modulo 2^32, the products summed modulo 2^64), the second's key the -/// first's shifted by four words (RFC 4418's Toeplitz iteration), keyed by the process's random -/// [`key`]. NH of 32-bit words is 2^-32-almost-universal, and its Toeplitz extension to two sums -/// 2^-64 (the UMAC paper, Black, Halevi, Krawczyk, Krovetz and Rogaway, 1999): for any two -/// different blocks, which no key decides, their tags agree with a chance of at most 2^-64. A -/// block a copy's base takes as unchanged may have changed with that chance. -/// -/// The sums run as SSE2 on an x86-64 host ([`x86`]), and one word pair at a time elsewhere -/// (`tag_portable`): the same tag either way. -pub(crate) fn tag(block: &[u8; TAG_BLOCK]) -> Tag { - #[cfg(target_arch = "x86_64")] - { - // SAFETY: the block's bytes; every x86-64 host has SSE2. - unsafe { x86::tag_sse2(block.as_ptr(), key()) } - } - #[cfg(not(target_arch = "x86_64"))] - tag_portable(block) -} - -/// [`tag`] of the `span` bytes at `from` (at most [`TAG_BLOCK`], zero past them): read in place -/// where the block is whole, as each block of a comparison is once, else through `scratch`. -/// -/// # Safety -/// -/// `from` is `span` bytes of mapped memory the host reads. -unsafe fn tag_in_place(from: *const u8, span: usize, scratch: &mut [u8; TAG_BLOCK]) -> Tag { - #[cfg(target_arch = "x86_64")] - if span == TAG_BLOCK { - // SAFETY: the caller's; every x86-64 host has SSE2. - return unsafe { x86::tag_sse2(from, key()) }; - } - // SAFETY: the caller's. - unsafe { read_block(from, span, scratch) }; - tag(scratch) -} - -/// [`tag`] one word pair at a time: the host's answer where it has no SIMD form, and the -/// reference the SIMD form is tested against. -#[cfg(any(test, not(target_arch = "x86_64")))] -pub(crate) fn tag_portable(block: &[u8; TAG_BLOCK]) -> Tag { - let key = key(); - let (mut first, mut second) = ([0u64; 4], [0u64; 4]); - for (stretch, bytes) in block.as_chunks::<32>().0.iter().enumerate() { - let word = |at: usize| { - u32::from_le_bytes([ - bytes[4 * at], - bytes[4 * at + 1], - bytes[4 * at + 2], - bytes[4 * at + 3], - ]) - }; - let keys = &key[8 * stretch..8 * stretch + 12]; - let lanes = first.iter_mut().zip(second.iter_mut()).enumerate(); - for (lane, (first, second)) in lanes { - let (low, high) = (word(lane), word(lane + 4)); - let one = u64::from(low.wrapping_add(keys[lane])) - * u64::from(high.wrapping_add(keys[lane + 4])); - let two = u64::from(low.wrapping_add(keys[lane + 4])) - * u64::from(high.wrapping_add(keys[lane + 8])); - *first = first.wrapping_add(one); - *second = second.wrapping_add(two); - } - } - let sum = |lanes: [u64; 4]| lanes.iter().fold(0u64, |sum, &lane| sum.wrapping_add(lane)); - [sum(first), sum(second)] -} - -/// [`tag`]'s sums as SSE2, which every x86-64 host has, one 32-byte stretch to a step: its words -/// `m0` to `m3` sit in one register and `m4` to `m7` in another, each added to its key words; -/// `_mm_mul_epu32` multiplies the even words of the two (`m0` by `m4`, `m2` by `m6`) into 64-bit -/// lanes, and again after a shift by 32 bits the odd ones. Each sum keeps its products in two -/// registers' lanes, added together at the end: the same sums modulo 2^64 as -/// `tag_portable`'s, in another order. (An AVX2 form, two stretches to a step, ran slower on a -/// Ryzen 7 7840HS and a Core Ultra 9 275HX, 41 GB/s against SSE2's 52-54 over a block in the -/// first-level cache.) -#[cfg(target_arch = "x86_64")] -pub(crate) mod x86 { - use super::{Tag, KEY_WORDS, TAG_BLOCK}; - use std::arch::x86_64::{ - __m128i, _mm_add_epi32, _mm_add_epi64, _mm_cmpeq_epi8, _mm_loadu_si128, - _mm_mask_storeu_epi8, _mm_movemask_epi8, _mm_mul_epu32, _mm_setzero_si128, _mm_srli_epi64, - _mm_storeu_si128, - }; - - /// [`tag`](super::tag) of the [`TAG_BLOCK`] bytes at `block` under `key`, read with plain loads. - /// - /// # Safety - /// - /// `block` is [`TAG_BLOCK`] bytes of mapped memory the host reads. - #[target_feature(enable = "sse2")] - pub(crate) unsafe fn tag_sse2(block: *const u8, key: &[u32; KEY_WORDS]) -> Tag { - let words = block.cast::<__m128i>(); - let keys = key.as_ptr().cast::<__m128i>(); - let (mut first, mut second) = ([_mm_setzero_si128(); 2], [_mm_setzero_si128(); 2]); - for stretch in 0..TAG_BLOCK / 32 { - // SAFETY: unaligned loads of the block's 16-byte pieces `2 * stretch` and the next - // (at most its 63rd of 64: the caller's), and of the key's 4-word pieces - // `2 * stretch` to two after it (at most its 64th of 65: words 256 to 259). - let (low, high, low_key, high_key, next_key) = unsafe { - ( - _mm_loadu_si128(words.add(2 * stretch)), - _mm_loadu_si128(words.add(2 * stretch + 1)), - _mm_loadu_si128(keys.add(2 * stretch)), - _mm_loadu_si128(keys.add(2 * stretch + 1)), - _mm_loadu_si128(keys.add(2 * stretch + 2)), - ) - }; - let (low_first, high_first) = - (_mm_add_epi32(low, low_key), _mm_add_epi32(high, high_key)); - let (low_second, high_second) = - (_mm_add_epi32(low, high_key), _mm_add_epi32(high, next_key)); - first[0] = _mm_add_epi64(first[0], _mm_mul_epu32(low_first, high_first)); - first[1] = _mm_add_epi64( - first[1], - _mm_mul_epu32( - _mm_srli_epi64::<32>(low_first), - _mm_srli_epi64::<32>(high_first), - ), - ); - second[0] = _mm_add_epi64(second[0], _mm_mul_epu32(low_second, high_second)); - second[1] = _mm_add_epi64( - second[1], - _mm_mul_epu32( - _mm_srli_epi64::<32>(low_second), - _mm_srli_epi64::<32>(high_second), - ), - ); - } - let sum = |lanes: [__m128i; 2]| { - let mut words = [0u64; 2]; - // SAFETY: a 16-byte store into two u64s. - unsafe { - _mm_storeu_si128(words.as_mut_ptr().cast(), _mm_add_epi64(lanes[0], lanes[1])) - }; - words[0].wrapping_add(words[1]) - }; - [sum(first), sum(second)] - } - - /// [`merge_block`](super::merge_block) 16 bytes at a time: the bytes that differ from `was` - /// as a mask (`_mm_cmpeq_epi8`, `_mm_movemask_epi8`), and where `keep_to` those of `to` that - /// still hold `was`'s; 16 in one store where every byte is to be written, else those the mask - /// sets in one masked store where the host has one ([`store_masked_avx512`]), else in the - /// fewest stores of 8, 4, 2 and 1 bytes ([`store_masked`]); `was` takes all 16 of `now` (the - /// bytes that did not change are the same). The rest past the last 16, 8 at a time - /// ([`merge_words`](super::merge_words)). The bytes written. - /// - /// # Safety - /// - /// As [`merge_block`](super::merge_block)'s. - #[target_feature(enable = "sse2")] - pub(super) unsafe fn merge_sse2(now: &[u8], to: *mut u8, was: &mut [u8], keep_to: bool) -> u64 { - let whole = now.len() / 16 * 16; - let mut written = 0u64; - let masked = masked_stores(); - for at in (0..whole).step_by(16) { - // SAFETY: 16 bytes at `at` of `now` and of `was` (as long), and of `to` (the - // caller's). - let (fresh, agreed) = unsafe { - ( - _mm_loadu_si128(now.as_ptr().add(at).cast()), - _mm_loadu_si128(was.as_ptr().add(at).cast()), - ) - }; - let changed = !(_mm_movemask_epi8(_mm_cmpeq_epi8(fresh, agreed)) as u32) & 0xFFFF; - if changed == 0 { - continue; - } - let mut stores = changed; - if keep_to { - // SAFETY: as above. - let there = unsafe { _mm_loadu_si128(to.add(at).cast()) }; - stores &= _mm_movemask_epi8(_mm_cmpeq_epi8(there, agreed)) as u32; - } - written += u64::from(stores.count_ones()); - // SAFETY: as above; `masked` where the host has AVX-512BW and AVX-512VL. - unsafe { - match (stores, masked) { - (0xFFFF, _) => _mm_storeu_si128(to.add(at).cast(), fresh), - (_, true) => store_masked_avx512(fresh, to.add(at), stores), - (_, false) => store_masked(&now[at..at + 16], to.add(at), stores), - } - _mm_storeu_si128(was.as_mut_ptr().add(at).cast(), fresh); - } - } - // SAFETY: the rest of the caller's bytes. - written - + unsafe { - super::merge_words(&now[whole..], to.add(whole), &mut was[whole..], keep_to) - } - } - - /// Whether the host stores the bytes a mask selects of 16 in one store (AVX-512BW and - /// AVX-512VL, [`store_masked_avx512`]), unless a test turned it off. - fn masked_stores() -> bool { - #[cfg(test)] - if MASKED_STORES_OFF.load(std::sync::atomic::Ordering::Relaxed) { - return false; - } - std::is_x86_feature_detected!("avx512bw") && std::is_x86_feature_detected!("avx512vl") - } - - /// A test's switch that turns [`masked_stores`] off, so a benchmark measures the stores of - /// a host without them on one that has them. - #[cfg(test)] - pub(crate) static MASKED_STORES_OFF: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - - /// Store the bytes of `fresh` at `to` whose bits `stores` sets, and no other byte of `to`, in - /// one masked store (`VMOVDQU8`). - /// - /// # Safety - /// - /// `to` is 16 bytes of mapped memory; the host has AVX-512BW and AVX-512VL. - #[target_feature(enable = "avx512bw,avx512vl")] - unsafe fn store_masked_avx512(fresh: __m128i, to: *mut u8, stores: u32) { - // SAFETY: the caller's; the mask's bits past 16 are clear. - unsafe { _mm_mask_storeu_epi8(to.cast(), stores as u16, fresh) }; - } - - /// Store the bytes of `now` (16) at `to` whose bits `stores` sets (not all 16), and no other - /// byte of `to`: each 8 whose bytes are all set in one store, and of the others each 4 bytes - /// in the fewest stores of 4, 2 and 1 bytes that write those set alone. - /// - /// # Safety - /// - /// `to` is 16 bytes of mapped memory. - #[target_feature(enable = "sse2")] - unsafe fn store_masked(now: &[u8], to: *mut u8, stores: u32) { - let byte = |at: usize| { - // SAFETY: a byte of `to` (the caller's). - unsafe { to.add(at).write_volatile(now[at]) } - }; - for half in [0, 8] { - if (stores >> half) & 0xFF == 0xFF { - // SAFETY: 8 bytes of `to` from `half`. - unsafe { store_run::<8>(now, to, half) }; - continue; - } - for at in [half, half + 4] { - // SAFETY: bytes of `to` from `at`, of the 4 there. - unsafe { - match (stores >> at) & 0xF { - 0 => {} - 0xF => store_run::<4>(now, to, at), - 0x3 => store_run::<2>(now, to, at), - 0x6 => store_run::<2>(now, to, at + 1), - 0xC => store_run::<2>(now, to, at + 2), - 0x7 => { - store_run::<2>(now, to, at); - byte(at + 2); - } - 0xB => { - store_run::<2>(now, to, at); - byte(at + 3); - } - 0xD => { - byte(at); - store_run::<2>(now, to, at + 2); - } - 0xE => { - byte(at + 1); - store_run::<2>(now, to, at + 2); - } - bits => (0..4) - .filter(|b| (bits >> b) & 1 == 1) - .for_each(|b| byte(at + b)), - } - } - } - } - } - - /// Store `N` bytes of `now` from `at` at `to`'s `at`, in one store. - /// - /// # Safety - /// - /// `to` is mapped memory over `at..at + N`, which lies in `now`. - unsafe fn store_run(now: &[u8], to: *mut u8, at: usize) { - let mut run = [0u8; N]; - run.copy_from_slice(&now[at..at + N]); - // SAFETY: the caller's; an unaligned store. - unsafe { to.add(at).cast::<[u8; N]>().write_unaligned(run) }; - } -} - -/// The bytes the pages and a copy last agreed on, made at the first commit whose command buffer -/// may write the copy ([`CopiedBuffers::copy_in`]), from the copy, which held them until then: -/// a tag of each [`TAG_BLOCK`] block, which the comparisons read in place of the bytes, and the -/// bytes themselves, which a comparison reads only for a block both sides changed since they -/// agreed, in the device's memory where it has room for them ([`BaseBytes::device`]), else in -/// the host's. -struct Base { - tags: Box<[Tag]>, - bytes: BaseBytes, - /// The blocks of bytes in the device's memory that a comparison read (both sides changed - /// them), kept in host memory from then on, by their index ([`HostBlock`]). - on_host: HashMap, -} - -impl Base { - /// The base of the `length` bytes of the copy at `copy`, which holds the bytes the pages - /// and it agree on: its bytes kept in `device`, where the device had room for them, else in - /// the host's memory. `None` where the host has no memory for its tags or bytes. - /// - /// # Safety - /// - /// `copy` is `length` bytes of mapped memory, and `device` holds as many. - unsafe fn of_copy(copy: NonNull, length: usize, device: Option) -> Option { - let blocks = length.div_ceil(TAG_BLOCK); - let mut tags = Vec::new(); - tags.try_reserve_exact(blocks).ok()?; - let mut host = Vec::new(); - if device.is_none() { - host.try_reserve_exact(length).ok()?; - } - let mut block = [0u8; TAG_BLOCK]; - for index in 0..blocks { - let at = index * TAG_BLOCK; - let span = (length - at).min(TAG_BLOCK); - // SAFETY: `span` bytes at `at` lie in the copy (the caller's). - unsafe { read_block(copy.as_ptr().add(at), span, &mut block) }; - tags.push(tag(&block)); - match &device { - // SAFETY: as above, in the device's bytes. - Some(bytes) => unsafe { bytes.write(at, &block[..span]) }, - None => host.extend_from_slice(&block[..span]), - } - } - let bytes = match device { - Some(bytes) => bytes, - None => BaseBytes::host(host.into_boxed_slice()), - }; - Some(Base { - tags: tags.into_boxed_slice(), - bytes, - on_host: HashMap::new(), - }) - } - - /// The host's bytes it holds: its tags, and its bytes where they are in the host's memory, - /// else the blocks of them kept there ([`HostBlock`]). - fn host_bytes(&self) -> u64 { - let tags = (self.tags.len() * size_of::()) as u64; - match self.bytes.on_device { - true => tags + (self.on_host.len() * TAG_BLOCK) as u64, - false => tags + self.bytes.length as u64, - } - } - - /// The device's bytes it holds: its bytes where they are in the device's memory. - fn device_bytes(&self) -> u64 { - match self.bytes.on_device { - true => self.bytes.length as u64, - false => 0, - } - } -} - -/// Where a copy's base keeps the agreed bytes ([`Base`]): memory the host maps, the host's own, -/// or the device's (`Device::copied_base`), held while the base lives. -pub(crate) struct BaseBytes { - at: NonNull, - length: usize, - on_device: bool, - held: Box, -} - -/// What keeps a base's bytes ([`BaseBytes`]), mapped while it lives; of the device's memory, it -/// copies runs of them into host memory on the GPU, for a comparison that reads many blocks -/// there, which the host reads uncached ([`READ_BACK_BLOCKS`]). -pub(crate) trait Held: Send { - /// The bytes of `runs` (byte ranges of the base, in order, apart), copied into host memory - /// on the GPU, one after another with nothing between: `None` where they are not, and the - /// host reads them itself (memory the host's own, the device lost, no memory for the copy). - fn read_back(&self, runs: &[Range]) -> Option>> { - let _ = runs; - None - } -} - -// SAFETY: `at` names the memory `held` keeps mapped and nothing else uses, reached only under -// the copies' lock ([`CopiedBuffers`]): by the thread that holds it, or by the threads of its -// comparison, each its own blocks ([`split`]). -unsafe impl Send for BaseBytes {} - -impl BaseBytes { - /// The host's memory of `bytes`. - fn host(bytes: Box<[u8]>) -> BaseBytes { - let length = bytes.len(); - let raw = NonNull::from(Box::leak(bytes)); - BaseBytes { - at: raw.cast(), - length, - on_device: false, - held: Box::new(HostBaseBytes(raw)), - } - } - - /// `length` bytes of the device's memory at `at`, which the host maps, held by `held`. - /// - /// # Safety - /// - /// `at` is `length` bytes of memory the host reads and writes (coherent, needing no flush), - /// which nothing else uses and which stays mapped until `held` goes, and whose runs `held` - /// reads back ([`Held::read_back`]). - pub(crate) unsafe fn device(at: NonNull, length: usize, held: Box) -> BaseBytes { - BaseBytes { - at, - length, - on_device: true, - held, - } - } - - /// Read `into.len()` of the bytes from `offset` into `into`. Of the device's memory, a read - /// across the bus that the host does not cache (`memory::host_cached`), made only for a block - /// both sides changed: on an x86-64 host with SSE4.1, with streaming loads ([`stream_read`]). - /// - /// # Safety - /// - /// `offset..offset + into.len()` lies in the bytes. - pub(crate) unsafe fn read(&self, offset: usize, into: &mut [u8]) { - // SAFETY: the caller's. - let from = unsafe { self.at.as_ptr().add(offset) }; - #[cfg(target_arch = "x86_64")] - if self.on_device && std::is_x86_feature_detected!("sse4.1") { - // SAFETY: the caller's; the host has SSE4.1. - return unsafe { stream_read(from, into) }; - } - // SAFETY: the caller's; `into` is the caller's own, apart. - unsafe { std::ptr::copy_nonoverlapping(from, into.as_mut_ptr(), into.len()) }; - } - - /// The bytes of `runs` copied into host memory on the GPU, where they lie in the device's - /// memory and it copies them ([`Held::read_back`]). - fn read_back(&self, runs: &[Range]) -> Option>> { - match self.on_device { - true => self.held.read_back(runs), - false => None, - } - } - - /// Its first byte, for a test that writes the device's bytes under the base. - #[cfg(test)] - pub(crate) fn first(&self) -> NonNull { - self.at - } - - /// [`BaseBytes::read`] with plain loads, whatever the memory: a benchmark's measure of the - /// streaming loads against them (`tests/copied_base_device.rs`). - /// - /// # Safety - /// - /// As [`BaseBytes::read`]'s. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) unsafe fn read_plain(&self, offset: usize, into: &mut [u8]) { - // SAFETY: the caller's; `into` is the caller's own, apart. - unsafe { - std::ptr::copy_nonoverlapping( - self.at.as_ptr().add(offset), - into.as_mut_ptr(), - into.len(), - ) - }; - } - - /// Write `from` into the bytes from `offset`. - /// - /// # Safety - /// - /// `offset..offset + from.len()` lies in the bytes. - pub(crate) unsafe fn write(&self, offset: usize, from: &[u8]) { - // SAFETY: the caller's; `from` is the caller's own, apart. - unsafe { - std::ptr::copy_nonoverlapping(from.as_ptr(), self.at.as_ptr().add(offset), from.len()) - }; - } -} - -/// Read `into.len()` bytes at `from`, the device's memory the host maps uncached, with streaming -/// loads (`MOVNTDQA`) of each 16 bytes where `from` lies on 16 bytes: of write-combining memory, -/// the host may fetch a streaming load's whole 64-byte line once into a buffer that the line's -/// next streaming loads read (Intel's SDM), where each plain load crosses the bus. A full fence -/// first orders them after the host's earlier writes of the bytes. The bytes past the last 16, -/// and every byte where `from` lies off 16, are copied with plain loads. -/// -/// # Safety -/// -/// `from` is `into.len()` bytes of mapped memory, apart from `into`; the host has SSE4.1. -#[cfg(target_arch = "x86_64")] -#[target_feature(enable = "sse4.1")] -unsafe fn stream_read(from: *const u8, into: &mut [u8]) { - use std::arch::x86_64::{__m128i, _mm_mfence, _mm_storeu_si128, _mm_stream_load_si128}; - let whole = match from.addr() % 16 { - 0 => into.len() / 16 * 16, - _ => 0, - }; - _mm_mfence(); - for at in (0..whole).step_by(16) { - // SAFETY: 16 bytes at `at` of the caller's memory, on 16 bytes, into `into`'s own. - unsafe { - let bytes = _mm_stream_load_si128(from.add(at).cast::<__m128i>()); - _mm_storeu_si128(into.as_mut_ptr().add(at).cast(), bytes); - } - } - let rest = into.len() - whole; - // SAFETY: the caller's, past the bytes streamed. - unsafe { std::ptr::copy_nonoverlapping(from.add(whole), into.as_mut_ptr().add(whole), rest) }; -} - -/// Host memory of a base's bytes, freed as it goes: reached through [`BaseBytes`]' pointer alone. -struct HostBaseBytes(NonNull<[u8]>); - -// SAFETY: the memory is this value's own, reached only through its base's pointer. -unsafe impl Send for HostBaseBytes {} - -impl Held for HostBaseBytes {} - -impl Drop for HostBaseBytes { - fn drop(&mut self) { - // SAFETY: the box `BaseBytes::host` leaked, freed once, here. - drop(unsafe { Box::from_raw(self.0.as_ptr()) }); - } -} - -/// A block of a base whose bytes lie in the device's memory, kept in host memory from the first -/// comparison that read it there (a block both sides changed since they agreed, whose read -/// crosses the bus uncached): its later reads and writes are the host's, so a block both sides -/// write again and again pays one read across the bus. Kept for the base's life. -struct HostBlock(NonNull<[u8; TAG_BLOCK]>); - -impl HostBlock { - /// A block of host memory; `None` where the host has none, and the block stays in the - /// device's memory. - fn new() -> Option { - // SAFETY: the layout's size is not zero. - let at = unsafe { std::alloc::alloc(std::alloc::Layout::new::<[u8; TAG_BLOCK]>()) }; - NonNull::new(at.cast()).map(HostBlock) - } - - /// Its first byte. - fn at(&self) -> *mut u8 { - self.0.as_ptr().cast() - } -} - -impl Drop for HostBlock { - fn drop(&mut self) { - let layout = std::alloc::Layout::new::<[u8; TAG_BLOCK]>(); - // SAFETY: allocated by `HostBlock::new` with this layout, freed once, here. - unsafe { std::alloc::dealloc(self.0.as_ptr().cast(), layout) }; - } -} - -// SAFETY: the memory is this value's own, reached only under the copies' lock, by the thread -// that holds it or by the one thread of its comparison whose run holds its block ([`split`]). -unsafe impl Send for HostBlock {} -// SAFETY: as above. -unsafe impl Sync for HostBlock {} - -/// Read `span` bytes at `from` into `into`, the rest of it zero: a block the tags read whole. -/// -/// # Safety -/// -/// `from` is `span` bytes of mapped memory, `span` at most [`TAG_BLOCK`]. -unsafe fn read_block(from: *const u8, span: usize, into: &mut [u8; TAG_BLOCK]) { - // SAFETY: the caller's; `into` is the caller's own, apart. - unsafe { std::ptr::copy_nonoverlapping(from, into.as_mut_ptr(), span) }; - into[span..].fill(0); -} - -// SAFETY: the pointers name the caller's pages, which stay mapped while the buffer's import lives -// (`HostMemory::new`), and the copy's mapped memory, which the import holds; both are reached only -// under the registry's lock, which the import's drop takes before either goes ([`Copied`]). -unsafe impl Send for Entry {} - -/// A live copy's place in its device's [`CopiedBuffers`]: dropped (unregistered) before the copy's -/// memory is freed, so no comparison reads it after (`HostImport`'s drop). -pub(crate) struct Copied { - buffers: Arc, - id: u64, - drops_writes: bool, -} - -impl Copied { - /// Whether the GPU's writes to the copy are dropped: the process cannot write the pages. - pub(crate) fn drops_writes(&self) -> bool { - self.drops_writes - } - - /// Keep `log`, the logs of the writes to the copy's pages (`dirty_pages::PagesLog`), with a - /// writer of its own: each merge back reports the bytes it wrote to them as that writer's - /// ([`CopiedBuffers::merge_back`]). Set once. - /// - /// Its pages are watched in each log from here on ([`DirtyPages::watch`](crate::DirtyPages)), - /// asked with no lock of the copies' held: its copies in compare every byte until one did - /// after the watches began ([`CopiedBuffers::copy_in`]). - pub(crate) fn set_log(&self, log: &Arc) { - let Some(writer) = new_writer() else { - return; - }; - let watches = log.watch(); - let unlogged: Arc<[Range]> = log.unlogged().into(); - let mut entries = lock(&self.buffers.entries); - let entry = entries.iter_mut().find(|entry| entry.id == self.id); - let unkept = match entry { - Some(entry) if entry.log.is_none() => { - entry.log = Some(CopyLog { - pages: Arc::clone(log), - writer, - _watches: watches, - unlogged, - since: None, - merged: 0, - }); - None - } - _ => Some(watches), - }; - // A watch's end is the consumer's call: made with no lock of the copies' held. - drop(entries); - drop(unkept); - } - - /// The uses of `key` (a buffer's or a heap's bytes' lying in the copy) write the copy: a - /// completion turn merges it back only where a batch it finishes wrote one of its keys, or - /// may have written memory its uses do not name ([`CopiedBuffers::merge_back`]). Named once - /// by each pages lying in the copy, until they go ([`Copied::unname`]). - pub(crate) fn name(&self, key: ResourceKey) { - let mut entries = lock(&self.buffers.entries); - if let Some(entry) = entries.iter_mut().find(|entry| entry.id == self.id) { - match entry.keys.iter_mut().find(|(named, _)| *named == key) { - Some((_, count)) => *count += 1, - None => entry.keys.push((key, 1)), - } - } - } - - /// Whether a read twin reads the copy's pages in place (`read_twin.rs`): from its making, until - /// its buffer lies elsewhere. - pub(crate) fn set_twinned(&self, twinned: bool) { - let mut entries = lock(&self.buffers.entries); - if let Some(entry) = entries.iter_mut().find(|entry| entry.id == self.id) { - entry.twinned = twinned; - } - } - - /// Pages that named `key` ([`Copied::name`]) went: no command writes the copy through them - /// from now on, as every command buffer that used them completed, its batches' writes merged - /// back first (`command_buffer/completion.rs`). The key goes with the last such pages. - pub(crate) fn unname(&self, key: ResourceKey) { - let mut entries = lock(&self.buffers.entries); - if let Some(entry) = entries.iter_mut().find(|entry| entry.id == self.id) { - if let Some(at) = entry.keys.iter().position(|(named, _)| *named == key) { - entry.keys[at].1 -= 1; - if entry.keys[at].1 == 0 { - entry.keys.swap_remove(at); - } - } - } - } - - /// How many keys the copy holds ([`Copied::name`]). - #[cfg(test)] - pub(crate) fn keys(&self) -> usize { - let entries = lock(&self.buffers.entries); - let entry = entries.iter().find(|entry| entry.id == self.id); - entry.map_or(0, |entry| entry.keys.len()) - } -} - -impl Drop for Copied { - fn drop(&mut self) { - let mut entries = lock(&self.buffers.entries); - let removed = match entries.iter().position(|entry| entry.id == self.id) { - Some(index) => { - self.buffers.live.fetch_sub(1, Ordering::Relaxed); - Some(entries.swap_remove(index)) - } - None => None, - }; - if let Some(base) = removed.as_ref().and_then(|entry| entry.base.as_ref()) { - (self.buffers.base_host_bytes).fetch_sub(base.host_bytes(), Ordering::Relaxed); - (self.buffers.base_device_bytes).fetch_sub(base.device_bytes(), Ordering::Relaxed); - let blocks = base.on_host.len() as u64; - (self.buffers.base_host_blocks).fetch_sub(blocks, Ordering::Relaxed); - } - // Its watches end, and its base's memory goes, with no lock of the copies' held: a - // watch's end is the consumer's call, and the device's memory takes its own lock. So - // does its log line, which the consumer's sink takes. - drop(entries); - if let (Some(log), Some(entry)) = (&self.buffers.log, &removed) { - let at = (entry.pages.as_ptr() as usize, entry.length); - log.line(copied_line( - "gone", - entry.id, - at, - entry.copy.as_ptr() as usize, - )); - } - drop(removed); - } -} - -impl CopiedBuffers { - /// None yet, each copy's making and going said to `log` where the device's memory log is on. - pub(crate) fn logged(log: Option) -> CopiedBuffers { - CopiedBuffers { - log, - ..CopiedBuffers::default() - } - } - - /// Whether a copy is live: a batch submitted now may write one, so its event signals are seen - /// at its completion turn alone (`event_timeline.rs`). - pub(crate) fn any(&self) -> bool { - self.live.load(Ordering::Relaxed) > 0 - } - - /// The first read of the `length` bytes at `pages` for a copy of them ([`read_caller`]: - /// through the kernel, or where it fails, with plain loads of pages mapped readable), made - /// before the copy's memory is: a mapping the runtime makes for the copy may land where a - /// page of the caller's is not mapped, and a read after it would find every byte mapped and - /// copy memory Metal makes no buffer over. Where the process cannot write every page - /// ([`mapped_writable`]), or `read_only` (memory of Metal's private option bit 24), the GPU's - /// writes to the copy are dropped (the module docs). Refused where the process cannot read - /// every page, or the host has no memory for the bytes the copy and the pages last agreed on. - /// - /// # Safety - /// - /// `pages` are the caller's bytes, which stay mapped while their copy lives - /// (`HostMemory::new`), and which the CPU reads without a fault wherever the process maps - /// them with read permission. - pub(crate) unsafe fn read( - pages: NonNull, - length: usize, - read_only: bool, - ) -> Result { - let read = |pages: NonNull, into: &mut [u8]| { - // SAFETY: the caller's bytes, read with plain loads only where the process maps them - // readable (the caller's contract). - unsafe { read_caller(pages, into, read_pages, mapped_readable) } - }; - let start = pages.as_ptr() as u64; - let drops_writes = - read_only || !mapped_writable(start, start.saturating_add(length as u64)); - // SAFETY: the caller's. - unsafe { FirstRead::of(pages, length, read, drops_writes) } - } - - /// Register the copy at `copy` of the caller's bytes at `pages` that `first` read, its bytes - /// those `first` took, which it holds as the bytes the pages and it agree on: it has no base - /// until a commit whose command buffer may write it ([`CopiedBuffers::copy_in`]). - /// - /// # Safety - /// - /// `copy` is as many bytes as `first` read of mapped memory nothing else uses yet, which stays - /// mapped until the answer is dropped; `pages` are the bytes `first` read, which stay mapped - /// as long (`HostMemory::new`). - pub(crate) unsafe fn add( - self: &Arc, - first: FirstRead, - pages: NonNull, - copy: NonNull, - ) -> Copied { - let FirstRead { - bytes, - drops_writes, - } = first; - let length = bytes.len(); - // SAFETY: the copy is `length` bytes nothing else uses yet (the caller's). - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), copy.as_ptr(), length) }; - // The copy holds the bytes from here on: no base until a command buffer may write it. - drop(bytes); - let id = self.next.fetch_add(1, Ordering::Relaxed); - lock(&self.entries).push(Entry { - id, - pages, - copy, - length, - base: None, - drops_writes, - log: None, - keys: Vec::new(), - twinned: false, - }); - self.live.fetch_add(1, Ordering::Relaxed); - if let Some(log) = &self.log { - let at = (pages.as_ptr() as usize, length); - log.line(copied_line("made", id, at, copy.as_ptr() as usize)); - } - Copied { - buffers: Arc::clone(self), - id, - drops_writes, - } - } - - /// At a commit, before any of the command buffer's work is submitted, and again as a batch - /// that waits for an event value not reached before the commit's copy in is submitted - /// (`command_buffer/copies_again.rs`): write into each copy the command buffer's commands may - /// reach (`used`: the keys they used, `DirtyCommit::copies_used`, or every copy where one may - /// reach memory no use names) the bytes the CPU changed in its pages since they last agreed. - /// A copy none of them reaches is neither compared nor - /// asked of its logs, and keeps the stamp it last synced to, so the first commit whose - /// commands reach it takes every write since: a command buffer reads only the resources its - /// commands use, as Metal's GPU reaches only those (counted: - /// `WorkCounts::copied_copy_ins_unused`). - /// - /// A copy with no base yet (no command buffer that may write it was committed) holds the bytes - /// its pages and it agree on: its pages are compared with it, and the bytes that differ written - /// in. Each copy the command buffer's commands may write (`written`: the keys they wrote, - /// `DirtyCommit::copies_written`, or every copy where one may write memory no use names), and - /// that has none, then takes its base ([`Base`]), before any of its work is submitted: its - /// bytes in the device's memory where `device` gives them (`Device::copied_base`), else in the - /// host's. A copy with a base compares its pages' blocks' tags with its base's, and only a - /// block whose tag changed reads the copy's, and the base's bytes only where the copy's changed - /// too: the bytes the CPU changed are written in, and the base takes the block. Counted: - /// `WorkCounts::copied_bases_made`, `copied_base_blocks_read`. Where the host has no memory for - /// a base, the copy keeps none and the answer is `Err(NotCopied::OutOfHostMemory)`: the command - /// buffer runs nothing (`WorkCounts::copied_bases_refused`), and the copy still holds what its - /// pages and it agree on, for the next commit. - /// - /// A copy whose pages' memory came with a log of the writes to them ([`Copied::set_log`]) - /// compares only the pages the log reports written since the stamp its last copy in synced - /// to, and the bytes no log keeps: a stamp of each log is asked now, once for every copy - /// (`DirtyPages::request`), and its publication waited for (`DirtyPages::wait`, bounded), - /// with no lock of the copies' held; the pages written since are asked once per log and - /// stamp for every copy (`DirtyPages::changed`), but by a copy whose merges back wrote - /// [`ASKS_APART`] bytes or more of the pages since, which asks for every writer's but its - /// own (`DirtyPages::changed_except`). - /// Every write made before this call is in a publication the wait found, so the copy takes - /// each. Every byte is compared where the copy has no earlier copy in to count on, or a log - /// answered `false`. `tally` counts the stamps and waits (`WorkCounts::dirty_stamps_asked` - /// and kin). A logged copy also compares the bytes at the host addresses `in_flight` gives, - /// asked before the stamps: those committed command buffers wrote in place whose writes were - /// not reported as run yet (`DirtyShadows::in_flight`), which the program may know ran (a - /// host wait for an event they signal) before the logs hear it. - /// - /// A copy only a reach of memory no use names took ([`CopiesReached::reached_unnamed`]) is - /// counted apart, and so is one of them a read twin reads in place where that reach only reads - /// (`WorkCounts::copied_unnamed_reach_copy_ins`, `copied_unnamed_reach_twin_copy_ins`): what a - /// resident set listing the twins in their buffers' place would leave uncompared. - pub(crate) fn copy_in( - &self, - counts: &Counters, - tally: &DirtyTally, - (used, written): (&CopiesReached, &CopiesReached), - in_flight: impl FnOnce() -> Vec>, - device: &mut dyn FnMut(usize) -> Option, - ) -> Result<(), NotCopied> { - if self.live.load(Ordering::Relaxed) == 0 { - return Ok(()); - } - #[cfg(test)] - let began = std::time::Instant::now(); - let reaches = |entry: &Entry| used.meets(&entry.keys) || written.meets(&entry.keys); - let in_flight = in_flight(); - let asked: Vec = (lock(&self.entries).iter()) - .filter(|entry| reaches(entry)) - .filter_map(|entry| { - let log = entry.log.as_ref()?; - Some(Asked { - id: entry.id, - length: entry.length as u64, - pages: Arc::clone(&log.pages), - writer: log.writer, - unlogged: Arc::clone(&log.unlogged), - since: log.since.clone(), - merged: log.merged, - }) - }) - .collect(); - let plans = planned(asked, tally, &in_flight); - let (mut moved, mut skipped, mut unused, mut read) = (0u64, 0u64, 0u64, 0u64); - let (mut made, mut refused, mut started, mut read_back) = (0u64, 0u64, 0u64, 0u64); - let (mut copies, mut bytes_compared) = (0u64, 0u64); - // The copies a reach of memory no use names alone compared, and those of them a read twin - // reads in place where that reach only reads: copies and bytes. - let (mut unnamed, mut twinned) = ((0u64, 0u64), (0u64, 0u64)); - for entry in lock(&self.entries).iter_mut() { - if !reaches(entry) { - unused += 1; - continue; - } - copies += 1; - let plan = match &entry.log { - Some(_) => (plans.binary_search_by_key(&entry.id, |(id, _)| *id).ok()) - .map(|at| &plans[at].1), - None => None, - }; - let (pages, copy, length) = (entry.pages, entry.copy, entry.length); - let whole = 0..length as u64; - let ranges = match plan.and_then(|plan| plan.bytes.as_ref()) { - Some(bytes) => &bytes[..], - None => std::slice::from_ref(&whole), - }; - let mut compared = 0u64; - for range in ranges { - let bytes = range.start as usize..range.end as usize; - // The entry's pointers are live while it is registered (`Entry`), and `bytes` - // lies in its bytes (`blocks`), from a multiple of `SYNC_BLOCK`. - moved += match &mut entry.base { - Some(Base { - tags, - bytes: agreed, - on_host, - }) => { - let sides = Sides { - pages, - copy, - length, - bytes: agreed, - on_host, - }; - // SAFETY: as above; `sides` and `tags` are the entry's base's. - let tally = two_passes(sides, |fetch| unsafe { - copy_in_tagged(sides, tags, bytes.clone(), fetch) - }); - (read, started) = (read + tally.read, started + tally.started); - read_back += tally.read_back; - // SAFETY: as above. - unsafe { self.keep_on_host((agreed, on_host), length, tally.kept) }; - tally.written - } - None => { - // SAFETY: as above; the copy has no base, so no command buffer - // committed writes it, and its copies in hold the copies' lock. - let tally = unsafe { copy_in_untagged(pages, copy, bytes) }; - started += tally.started; - tally.written - } - }; - compared += range.end - range.start; - } - bytes_compared += compared; - skipped += length as u64 - compared; - if let Some(reads_only) = used.unnamed_alone(&entry.keys) { - unnamed = (unnamed.0 + 1, unnamed.1 + compared); - if reads_only && entry.twinned { - twinned = (twinned.0 + 1, twinned.1 + compared); - } - } - if let (Some(log), Some(plan)) = (&mut entry.log, plan) { - log.since = plan.stamps.clone(); - log.merged = 0; - } - if entry.base.is_none() && written.meets(&entry.keys) { - // SAFETY: the entry's copy is live while it is registered (`Entry`), and the - // device's bytes are as many as its own. - let base = unsafe { Base::of_copy(copy, length, device(length)) }; - #[cfg(test)] - let base = base.filter(|_| !self.bases_refused.load(Ordering::Relaxed)); - match base { - Some(base) => { - (self.base_host_bytes).fetch_add(base.host_bytes(), Ordering::Relaxed); - (self.base_device_bytes).fetch_add(base.device_bytes(), Ordering::Relaxed); - entry.base = Some(base); - made += 1; - } - None => refused += 1, - } - } - } - counts.copied_copied_in(moved); - counts.copied_copy_in_skipped(skipped); - counts.copied_copy_ins_unused(unused); - counts.copied_copy_ins_compared(copies, bytes_compared); - counts.copied_unnamed_reach(unnamed, twinned); - counts.copied_bases(made, refused, read); - counts.copied_base_blocks_read_back(read_back); - counts.copied_compare_threads(started); - #[cfg(test)] - clock::whole(clock::COPY_IN, began); - match refused { - 0 => Ok(()), - _ => Err(NotCopied::OutOfHostMemory), - } - } - - /// At a batch's completion: write back into each copy's pages the bytes the GPU changed in the - /// copy since they last agreed, where the CPU did not change them since, before anything sees - /// the batch complete. A copy of pages the process cannot write takes back instead the bytes - /// they last agreed on wherever the GPU changed it: the GPU's writes are dropped, and nothing - /// is written to the pages. - /// - /// Only the copies the finished batches may have written are compared (`written`): one a - /// use of their command buffers' commands wrote by one of its keys ([`Copied::name`]), and - /// every copy where a command may have written memory no use names (the loaded addresses of - /// a function that may store or update memory atomically, `StageInterface::writes_memory`; an - /// indirect command buffer's executions), or where its command buffer's writes were not all - /// kept apart. Each batch's writes are done by its own completion turn, which - /// compares what they reach; a copy no batch wrote since its last comparison holds what its - /// pages do, but for the CPU's writes, which the next commit copies in. After a batch finished - /// with no merge (a failed wait, [`CopiedBuffers::owe`]), the next compares every copy. A copy - /// with no base was written by no command buffer, as its commit would have made one - /// ([`CopiedBuffers::copy_in`]), and is not compared. Counted: - /// `WorkCounts::copied_merges_compared`, `copied_merges_skipped`. - /// - /// A copy's blocks' tags are compared with its base's, and only a block whose tag changed - /// reads its pages' block, and the base's bytes only where the pages' changed too - /// (`WorkCounts::copied_base_blocks_read`); the base takes the copy's block. - /// - /// The bytes written into pages whose memory came with a log are reported to it, as the - /// copy's own writes: the blocks of [`SYNC_BLOCK`] bytes it wrote a byte of, adjacent ones - /// joined, in one call to each log for each copy - /// ([`DirtyPages::wrote_runs_as`](crate::DirtyPages::wrote_runs_as)), before this returns: - /// the log sees no write the runtime makes, and every other copy and shadow of those pages - /// must take them, while the copy's own copies in need not. - pub(crate) fn merge_back(&self, counts: &Counters, written: &CopiesReached) { - if self.live.load(Ordering::Relaxed) == 0 { - return; - } - #[cfg(test)] - let began = std::time::Instant::now(); - let owed = self.owed.swap(false, Ordering::AcqRel); - let (mut moved, mut dropped, mut read, mut read_back) = (0u64, 0u64, 0u64, 0u64); - let (mut compared, mut skipped, mut started) = (0u64, 0u64, 0u64); - let mut reports = Vec::new(); - for entry in lock(&self.entries).iter_mut() { - let Some(base) = entry.base.as_mut() else { - skipped += 1; - continue; - }; - if !owed && !written.meets(&entry.keys) { - skipped += 1; - continue; - } - compared += 1; - let Base { - tags, - bytes, - on_host, - } = base; - let (copy, pages, length) = (entry.copy, entry.pages, entry.length); - let sides = Sides { - pages, - copy, - length, - bytes, - on_host, - }; - let drops = entry.drops_writes; - // SAFETY: the entry's pointers are live while it is registered (`Entry`), and - // `sides` and `tags` are its base's. - let tally = two_passes(sides, |fetch| unsafe { - match drops { - true => restore_tagged(sides, tags, fetch), - false => merge_tagged(sides, tags, fetch), - } - }); - read += tally.read; - read_back += tally.read_back; - started += tally.started; - // SAFETY: as above. - unsafe { self.keep_on_host((bytes, on_host), length, tally.kept) }; - if entry.drops_writes { - dropped += tally.written; - continue; - } - moved += tally.written; - if let (Some(log), false) = (&mut entry.log, tally.wrote.is_empty()) { - let wrote: u64 = (tally.wrote.iter()) - .map(|bytes| bytes.end - bytes.start) - .sum(); - log.merged = log.merged.saturating_add(wrote); - reports.push((Arc::clone(&log.pages), log.writer, tally.wrote)); - } - } - // Reported with no lock of the copies' held. - for (log, writer, blocks) in reports { - log.wrote_as(&blocks, writer); - } - counts.copied_merged_back(moved); - counts.copied_dropped(dropped); - counts.copied_merges(compared, skipped); - counts.copied_bases(0, 0, read); - counts.copied_base_blocks_read_back(read_back); - counts.copied_compare_threads(started); - #[cfg(test)] - clock::whole(clock::MERGE_BACK, began); - } - - /// Keep `kept`, the blocks of a base in the device's memory (`bytes`, of a copy of `length` - /// bytes) that a comparison read, now held in host memory, in the base's map `on_host`, and - /// count them (`WorkCounts::copied_base_host_blocks`, `copied_base_host_bytes`). Where the - /// host has no memory for the map's entries, their bytes go back into the device's memory. - /// - /// # Safety - /// - /// The copies' lock is held, and no comparison of the base runs. - unsafe fn keep_on_host( - &self, - (bytes, on_host): (&BaseBytes, &mut HashMap), - length: usize, - kept: Vec<(usize, HostBlock)>, - ) { - if kept.is_empty() { - return; - } - if on_host.try_reserve(kept.len()).is_err() { - for (index, block) in kept { - let span = (length - index * TAG_BLOCK).min(TAG_BLOCK); - // SAFETY: the block's `span` bytes, written by the comparison, back into the - // base's bytes, which hold as many from `index * TAG_BLOCK`. - unsafe { - bytes.write( - index * TAG_BLOCK, - std::slice::from_raw_parts(block.at(), span), - ) - }; - } - return; - } - let blocks = kept.len() as u64; - on_host.extend(kept); - self.base_host_blocks.fetch_add(blocks, Ordering::Relaxed); - (self.base_host_bytes).fetch_add(blocks * TAG_BLOCK as u64, Ordering::Relaxed); - } - - /// The blocks of the live copies' bases in the device's memory that are kept in host memory - /// (`WorkCounts::copied_base_host_blocks`). - pub(crate) fn base_host_blocks(&self) -> u64 { - self.base_host_blocks.load(Ordering::Relaxed) - } - - /// Find no memory for a base from now on where `refused`: a test's stand-in for a host out of - /// memory ([`CopiedBuffers::copy_in`]). - #[cfg(test)] - pub(crate) fn refuse_bases(&self, refused: bool) { - self.bases_refused.store(refused, Ordering::Relaxed); - } - - /// The host's and the device's bytes the live copies' bases hold - /// (`WorkCounts::copied_base_host_bytes`, `copied_base_device_bytes`). - pub(crate) fn base_bytes(&self) -> (u64, u64) { - ( - self.base_host_bytes.load(Ordering::Relaxed), - self.base_device_bytes.load(Ordering::Relaxed), - ) - } - - /// Whether the merge back at the completion of work that wrote `written` may write the - /// caller's pages: a live copy with a base whose keys `written` meets, as - /// [`merge_back`](Self::merge_back) compares (`command_buffer/sync_file.rs`). - #[cfg(unix)] - pub(crate) fn merges_back(&self, written: &CopiesReached) -> bool { - self.live.load(Ordering::Relaxed) > 0 - && (lock(&self.entries).iter()) - .any(|entry| entry.base.is_some() && written.meets(&entry.keys)) - } - - /// A batch finished with no merge back (its queue's wait failed): the next merge back - /// compares every copy. - pub(crate) fn owe(&self) { - self.owed.store(true, Ordering::Release); - } -} - -/// What a logged copy asks its logs at a copy in ([`CopiedBuffers::copy_in`]). -struct Asked { - id: u64, - length: u64, - pages: Arc, - writer: NonZeroU64, - unlogged: Arc<[Range]>, - since: Option>, - merged: u64, -} - -/// A logged copy's copy in, as its logs answered: the bytes it compares (`None`: every byte), -/// and the stamps it syncs to (`None`: a log could not say). -struct Plan { - bytes: Option>>, - stamps: Option>, -} - -/// One stamp of a log at a copy in, and whether its publication was found. -struct Stamped { - source: Arc, - stamp: DirtyStamp, - published: bool, -} - -/// The copies in of the copies `asked`, by their ids, in order: a stamp of each log asked, then -/// waited for (counted in `tally`); the pages each log reports written since a copy's stamp -/// asked once per log and stamp (or for one copy, of a copy whose merge back wrote its pages), -/// with no lock of the copies' held; and the bytes at the host addresses `in_flight` -/// ([`CopiedBuffers::copy_in`]). -fn planned(asked: Vec, tally: &DirtyTally, in_flight: &[Range]) -> Vec<(u64, Plan)> { - let mut stamped: Vec = Vec::new(); - for source in asked.iter().flat_map(|asked| asked.pages.sources()) { - if !stamped.iter().any(|s| Arc::ptr_eq(&s.source, source)) { - stamped.push(Stamped { - source: Arc::clone(source), - stamp: source.request(tally), - published: false, - }); - } - } - for stamp in &mut stamped { - stamp.published = stamp.source.wait(stamp.stamp, tally); - } - // The pages each log reports written since a stamp, by every writer: asked once per log and - // stamp. - let mut written: Vec<(*const DirtySource, DirtyStamp, Vec>)> = Vec::new(); - let mut plans: Vec<(u64, Plan)> = Vec::with_capacity(asked.len()); - for asked in asked { - let of: Vec<&Stamped> = (asked.pages.sources()) - .filter_map(|source| stamped.iter().find(|s| Arc::ptr_eq(&s.source, source))) - .collect(); - let now: Option> = (of.iter()) - .map(|stamped| stamped.published.then_some(stamped.stamp)) - .collect(); - // Copies over the same logs sync to one set of stamps. - let stamps: Option> = - now.map( - |now| match plans.last().and_then(|(_, plan)| plan.stamps.as_ref()) { - Some(last) if last[..] == now[..] => Arc::clone(last), - _ => now.into(), - }, - ); - let bytes = match (&asked.since, &stamps) { - (Some(since), Some(_)) if since.len() == of.len() => { - let mut bytes: Vec> = asked.unlogged.to_vec(); - let mut own = Vec::new(); - for (index, (stamped, since)) in of.iter().zip(since.iter()).enumerate() { - let changed: &[Range] = match asked.merged >= ASKS_APART { - true => { - own.clear(); - let writer = Some(asked.writer); - stamped.source.changed(*since, writer, &mut own); - joined(&mut own); - &own - } - false => { - let key = (Arc::as_ptr(&stamped.source), *since); - let at = match (written.iter()).position(|w| (w.0, w.1) == key) { - Some(at) => at, - None => { - let mut runs = Vec::new(); - stamped.source.changed(*since, None, &mut runs); - joined(&mut runs); - written.push((key.0, key.1, runs)); - written.len() - 1 - } - }; - &written[at].2 - } - }; - asked.pages.bytes_of(index, changed, |run| bytes.push(run)); - } - bytes.extend(in_flight.iter().filter_map(|at| asked.pages.bytes_at(at))); - Some(blocks(bytes, asked.length)) - } - _ => None, - }; - plans.push((asked.id, Plan { bytes, stamps })); - } - plans.sort_by_key(|(id, _)| *id); - plans -} - -/// `runs` sorted by start, those that meet or touch joined. -fn joined(runs: &mut Vec>) { - runs.retain(|run| run.start < run.end); - runs.sort_by_key(|run| run.start); - let mut kept: Vec> = Vec::with_capacity(runs.len()); - for run in runs.drain(..) { - match kept.last_mut() { - Some(last) if run.start <= last.end => last.end = last.end.max(run.end), - _ => kept.push(run), - } - } - *runs = kept; -} - -/// `bytes` of a copy of `length` bytes, each widened to the [`SYNC_BLOCK`]s it meets (counted -/// from the copy's first byte) and cut to the copy, sorted and joined. -fn blocks(mut bytes: Vec>, length: u64) -> Vec> { - let block = SYNC_BLOCK as u64; - for run in &mut bytes { - let start = run.start / block * block; - let end = run.end.div_ceil(block).saturating_mul(block).min(length); - *run = start.min(end)..end; - } - joined(&mut bytes); - bytes -} - -/// The bytes a copy with no base compares of its pages and itself at once ([`copy_in_untagged`]), -/// and the unit a merge back reports its writes to a log in: a host page. -pub(crate) const SYNC_BLOCK: usize = 4096; - -/// A copy's pages and the copy, both mapped, which a comparison with no base shares among its -/// threads ([`copy_in_untagged`]). -#[derive(Clone, Copy)] -struct Ends { - pages: NonNull, - copy: NonNull, -} - -// SAFETY: the pointers are an entry's, live while it is registered (`Entry`), and a comparison -// holds the copies' lock until each thread it started has ended ([`in_threads`]); each thread -// reads and writes only its own bytes of the copy. -unsafe impl Send for Ends {} -// SAFETY: as above. -unsafe impl Sync for Ends {} - -/// A copy in of a copy with no base, which holds the bytes its pages and it agree on: write into -/// `copy` each byte of `pages` that differs from it, in `bytes` (from a multiple of -/// [`SYNC_BLOCK`]), split across threads as a comparison with a base is ([`split`]): into at most -/// one run for each of [`split_threads`], each a whole number of [`SYNC_BLOCK`]s of at least -/// [`SPLIT_BYTES`] but the last, so `bytes` of less than twice [`SPLIT_BYTES`] are compared on the -/// calling thread alone. The bytes written, and the threads started. -/// -/// # Safety -/// -/// `pages` and `copy` are mapped memory over `bytes`, and no other thread writes the copy's. -unsafe fn copy_in_untagged(pages: NonNull, copy: NonNull, bytes: Range) -> Tally { - let ends = Ends { pages, copy }; - let length = bytes.end - bytes.start; - let threads = (length / SPLIT_BYTES).clamp(1, split_threads()); - // SAFETY: the caller's, for each run's own bytes. - let run = |run: Range| Tally { - written: unsafe { copy_in_run(ends, run) }, - ..Tally::default() - }; - if threads == 1 { - return run(bytes); - } - let each = length.div_ceil(threads).next_multiple_of(SYNC_BLOCK); - let runs = (bytes.clone().step_by(each)).map(|start| start..(start + each).min(bytes.end)); - in_threads(threads, runs, run) -} - -/// [`copy_in_untagged`] of the bytes `bytes`, on the calling thread: read a block of -/// [`SYNC_BLOCK`] bytes of each side at a time, compared whole (slice equality, which the compiler -/// vectorizes); a block that differs takes the pages' block whole, in one copy. No command buffer -/// committed writes a copy with no base (the first that may write it makes one, after its copy -/// in), and its copies in hold the copies' lock, so nothing writes the copy's block meanwhile: -/// its bytes that agree with the pages' are stored as they are, which changes nothing a reader -/// of it sees, in place of the stores of the bytes that differ alone ([`merge_block`]). The bytes -/// that differ. -/// -/// # Safety -/// -/// As [`copy_in_untagged`]'s, and no other thread reaches these bytes of the copy. -unsafe fn copy_in_run(ends: Ends, bytes: Range) -> u64 { - let (pages, copy) = (ends.pages.as_ptr(), ends.copy.as_ptr()); - let mut written = 0u64; - let (mut now, mut was) = ([0u8; SYNC_BLOCK], [0u8; SYNC_BLOCK]); - let mut at = bytes.start; - while at < bytes.end { - let span = (bytes.end - at).min(SYNC_BLOCK); - // SAFETY: `span` bytes at `at` lie in both (the caller's); the blocks are this call's own. - unsafe { - std::ptr::copy_nonoverlapping(pages.add(at), now.as_mut_ptr(), span); - std::ptr::copy_nonoverlapping(copy.add(at), was.as_mut_ptr(), span); - } - let (fresh, held) = (&now[..span], &was[..span]); - if fresh != held { - written += fresh.iter().zip(held).filter(|(a, b)| a != b).count() as u64; - // SAFETY: as above; nothing else writes the copy's bytes meanwhile (the caller's). - unsafe { std::ptr::copy_nonoverlapping(fresh.as_ptr(), copy.add(at), span) }; - } - at += span; - } - written -} - -/// The most threads one comparison of a copy runs on ([`split`], [`copy_in_untagged`]), the -/// calling thread among them. On the RTX 5080 Laptop GPU's host (a Core Ultra 9 275HX) a commit's -/// copy in of 256 MiB with no base takes 8.4 ms on eight threads and 11.2 ms on four, of 64 MiB -/// 2.2 and 2.9 ms (`tests/copied_bandwidth_bench.rs`, `copied` and `copied-t4`). -const SPLIT_THREADS: usize = 8; - -/// The fewest bytes of a copy each thread of a split comparison takes ([`split`], -/// [`copy_in_untagged`]): fewer than twice as many are compared on the calling thread alone. -pub(crate) const SPLIT_BYTES: usize = 2 << 20; - -/// The stack of each thread a split comparison starts ([`in_threads`]): a run's two blocks and -/// its calls' frames. -const SPLIT_STACK: usize = 256 << 10; - -/// The memory one comparison of a copy with a base reaches, which [`split`] shares among its -/// threads: the pages and the copy, both `length` bytes of mapped memory, and the base's bytes. -#[derive(Clone, Copy)] -struct Sides<'a> { - pages: NonNull, - copy: NonNull, - length: usize, - bytes: &'a BaseBytes, - on_host: &'a HashMap, -} - -// SAFETY: the pointers are an entry's, live while it is registered (`Entry`), and a comparison -// holds the copies' lock until each thread it started has ended ([`split`]); each thread reads -// and writes only its own blocks of the pages, the copy and the base's bytes. -unsafe impl Send for Sides<'_> {} -// SAFETY: as above. -unsafe impl Sync for Sides<'_> {} - -impl Sides<'_> { - /// The block at `index` of the base's bytes where it is kept in host memory ([`HostBlock`]). - fn kept(&self, index: usize) -> Option<*mut u8> { - match self.on_host.is_empty() { - true => None, - false => self.on_host.get(&index).map(HostBlock::at), - } - } - - /// Read the base's bytes of the block at `index` into `into` (as many as it holds): from host - /// memory where the block is kept there (`kept`, [`Sides::kept`]) or the base's bytes lie - /// there; else, of the device's memory, as `fetch` says, and keep the block in host memory - /// from then on, returned (`Some(None)` where the host has no memory for it). `None` where - /// `fetch` leaves the block for the comparison's second pass, and nothing was read. - /// - /// # Safety - /// - /// The block lies in the base's bytes, and no other thread reaches it. - unsafe fn read_base( - &self, - index: usize, - kept: Option<*mut u8>, - into: &mut [u8], - fetch: Fetch<'_>, - ) -> Option> { - if let Some(at) = kept { - // SAFETY: a block of host memory as long, the caller's alone. - unsafe { std::ptr::copy_nonoverlapping(at, into.as_mut_ptr(), into.len()) }; - return Some(None); - } - let at = index * TAG_BLOCK; - if !self.bytes.on_device { - // SAFETY: the caller's. - unsafe { self.bytes.read(at, into) }; - return Some(None); - } - match fetch { - Fetch::Defer => return None, - // SAFETY: the caller's. - Fetch::Read(_) => unsafe { self.bytes.read(at, into) }, - Fetch::ReadBack(deferred, read) => match deferred.binary_search(&index) { - // At its place among the blocks read back ([`ReadBack`]). - Ok(place) => into.copy_from_slice(&read.bytes[read.at[place]..][..into.len()]), - // SAFETY: the caller's. - Err(_) => unsafe { self.bytes.read(at, into) }, - }, - } - Some(HostBlock::new()) - } - - /// Write `from` as the base's bytes of the block at `index`: into host memory where it is - /// kept there (`kept`), else into the base's bytes. - /// - /// # Safety - /// - /// As [`Sides::read_base`]'s. - unsafe fn write_base(&self, index: usize, kept: Option<*mut u8>, from: &[u8]) { - match kept { - // SAFETY: a block of host memory as long, the caller's alone. - Some(at) => unsafe { std::ptr::copy_nonoverlapping(from.as_ptr(), at, from.len()) }, - // SAFETY: the caller's. - None => unsafe { self.bytes.write(index * TAG_BLOCK, from) }, - } - } -} - -/// What a run of a copy's blocks did: the bytes it wrote, the base's blocks it read -/// (`WorkCounts::copied_base_blocks_read`), and, of a merge back, the blocks of [`SYNC_BLOCK`] -/// bytes of the pages it wrote a byte of, in order, adjacent ones joined; and of a comparison -/// split across threads, those it started (`WorkCounts::copied_compare_threads`); and the blocks -/// of a base in the device's memory it read, now kept in host memory ([`HostBlock`]); of a first -/// pass, the blocks it left for the second, in order ([`Fetch::Defer`]); and of a comparison, the -/// blocks it read through the GPU's copy (`WorkCounts::copied_base_blocks_read_back`). -#[derive(Default)] -struct Tally { - written: u64, - read: u64, - wrote: Vec>, - started: u64, - kept: Vec<(usize, HostBlock)>, - deferred: Vec, - read_back: u64, -} - -impl Tally { - /// Note the write of a byte of the [`SYNC_BLOCK`] at `start` of a copy of `length` bytes, - /// after those noted before it. - fn wrote(&mut self, start: u64, length: usize) { - let end = (start + SYNC_BLOCK as u64).min(length as u64); - self.joined(start..end); - } - - /// `run` after the runs this one holds, joined with the last where they meet. - fn joined(&mut self, run: Range) { - match self.wrote.last_mut() { - Some(last) if last.end >= run.start => last.end = last.end.max(run.end), - _ => self.wrote.push(run), - } - } - - /// This run's tally and then `later`'s, of the blocks after its own. - fn and(mut self, later: Tally) -> Tally { - self.written += later.written; - self.read += later.read; - self.started += later.started; - self.read_back += later.read_back; - self.kept.extend(later.kept); - self.deferred.extend(later.deferred); - for run in later.wrote { - self.joined(run); - } - self - } - - /// A first pass's tally and its second's (`second`), over blocks among its own: the blocks - /// the first left for the second are done. - fn with(self, second: Tally) -> Tally { - let mut wrote: Vec> = self.wrote.into_iter().chain(second.wrote).collect(); - wrote.sort_unstable_by_key(|run| run.start); - let mut both = Tally { - written: self.written + second.written, - read: self.read + second.read, - started: self.started + second.started, - read_back: self.read_back + second.read_back, - kept: self.kept.into_iter().chain(second.kept).collect(), - ..Tally::default() - }; - for run in wrote { - both.joined(run); - } - both - } -} - -/// How a comparison takes the base's bytes of a block in the device's memory that no host block -/// holds ([`Sides::read_base`]), which the host reads uncached: its first pass leaves each such -/// block for its second ([`two_passes`]), which reads them together. -#[derive(Clone, Copy)] -enum Fetch<'a> { - /// Leave the block for the second pass ([`Tally::deferred`]). - Defer, - /// The second pass of the blocks listed, in order: each read there by the host. - Read(&'a [usize]), - /// The second pass of the blocks listed, in order: each taken from the bytes the GPU copied - /// them into. - ReadBack(&'a [usize], ReadBack<'a>), -} - -impl<'a> Fetch<'a> { - /// The blocks a second pass compares, in order; `None` for a first pass, which compares - /// every block. - fn deferred(self) -> Option<&'a [usize]> { - match self { - Fetch::Defer => None, - Fetch::Read(deferred) | Fetch::ReadBack(deferred, _) => Some(deferred), - } - } -} - -/// The bytes the GPU copied a second pass's blocks into ([`Fetch::ReadBack`]): each block's -/// bytes at `bytes[at[place]..]`, its place that in the blocks' list. -#[derive(Clone, Copy)] -struct ReadBack<'a> { - bytes: &'a [u8], - at: &'a [usize], -} - -/// The most blocks between two runs of blocks a second pass reads back that are copied with -/// them, the two copied as one ([`runs_of`]): a region of a copy costs more than that many bytes -/// of it (on the RX 7900 XTX's staging queue about 6.6 us a region of 1 KiB, on the RTX 5080 -/// Laptop GPU's about 2.5 us, where 16 KiB at their links' rates takes about 1.6 and 0.7 us). -pub(crate) const JOIN_GAP: usize = 16; - -/// The fewest blocks of a base in the device's memory one comparison reads that it copies into -/// host memory on the GPU, in one submission on the device's staging queue it waits for, rather -/// than read each on the host ([`two_passes`]): the host reads that memory uncached, a block at -/// a time across the bus, where the copy costs a submission and its wait, then the bytes at the -/// bus's rate. A cost choice between two exact reads, the host's below it, measured on the -/// devices with a resizable BAR (`tests::copied_base_device::copied_read_back_bench`): at 32 -/// blocks the two cost the same within a millisecond on the RTX 5080 Laptop GPU and the RX 7900 -/// XTX, from 64 the copy costs less on the 5080 and no more on the XTX, and on the 5080's host, -/// whose reads of that memory slow about tenfold while its GPU idles, the copy costs less from 16 -/// after three seconds idle. -const READ_BACK_BLOCKS: usize = 32; - -/// A test's switch that sets [`read_back_blocks`] in place of [`READ_BACK_BLOCKS`] where not -/// zero. -#[cfg(test)] -pub(crate) static READ_BACK_FROM: AtomicUsize = AtomicUsize::new(0); - -/// [`READ_BACK_BLOCKS`], unless a test set another. -fn read_back_blocks() -> usize { - #[cfg(test)] - match READ_BACK_FROM.load(Ordering::Relaxed) { - 0 => {} - blocks => return blocks, - } - READ_BACK_BLOCKS -} - -/// The byte runs a read back of the blocks `blocks` (in order) of a copy of `length` bytes copies, -/// each run joined with the next where at most [`JOIN_GAP`] blocks lie between them (copied -/// too, unread), and where each block's bytes land among the runs copied one after another. -pub(crate) fn runs_of(blocks: &[usize], length: usize) -> (Vec>, Vec) { - let mut runs: Vec> = Vec::new(); - let mut at = Vec::with_capacity(blocks.len()); - let mut before = 0; - for &index in blocks { - let start = index * TAG_BLOCK; - let end = (start + TAG_BLOCK).min(length); - match runs.last_mut() { - Some(last) if last.end + JOIN_GAP * TAG_BLOCK >= start => last.end = end, - Some(last) => { - before += last.end - last.start; - runs.push(start..end); - } - None => runs.push(start..end), - } - let first = runs.last().map_or(start, |run| run.start); - at.push(before + start - first); - } - (runs, at) -} - -/// A comparison of `sides` in two passes, each `pass` with how it takes the base's bytes -/// ([`Fetch`]): the first leaves each block of a base in the device's memory that no host block -/// holds, and that it would read, for the second; the second reads those together, copied into -/// host memory on the GPU where they are [`read_back_blocks`] or more and the copy is made -/// ([`Held::read_back`]), else each by the host, and compares them. The two passes' tallies, the -/// blocks read back counted ([`Tally::read_back`]). -fn two_passes(sides: Sides<'_>, mut pass: impl FnMut(Fetch<'_>) -> Tally) -> Tally { - let first = pass(Fetch::Defer); - if first.deferred.is_empty() { - return first; - } - let deferred = &first.deferred[..]; - let (runs, at) = runs_of(deferred, sides.length); - let bytes: usize = runs.iter().map(|run| run.end - run.start).sum(); - #[cfg(test)] - let began = std::time::Instant::now(); - let back = match deferred.len() >= read_back_blocks() { - true => sides.bytes.read_back(&runs), - false => None, - }; - #[cfg(test)] - clock::whole(clock::READ_BACK, began); - let back = back.filter(|back| back.len() == bytes); - let mut second = match &back { - Some(back) => pass(Fetch::ReadBack( - deferred, - ReadBack { - bytes: back, - at: &at, - }, - )), - None => pass(Fetch::Read(deferred)), - }; - if back.is_some() { - second.read_back += deferred.len() as u64; - } - first.with(second) -} - -/// Call `one` with each block of a run of a comparison's blocks whose tags are `tags`, from block -/// `first`, and its tag: every block of the run where `deferred` is `None` (a first pass), else -/// those of them it lists (in order: a second pass's). -fn each_block( - first: usize, - tags: &mut [Tag], - deferred: Option<&[usize]>, - mut one: impl FnMut(usize, &mut Tag), -) { - let Some(deferred) = deferred else { - for (index, agreed) in (first..).zip(tags) { - one(index, agreed); - } - return; - }; - let end = first + tags.len(); - let from = deferred.partition_point(|&index| index < first); - for &index in deferred[from..].iter().take_while(|&&index| index < end) { - one(index, &mut tags[index - first]); - } -} - -/// A test's switch that sets the most threads a comparison runs on ([`split_threads`]) in place -/// of [`SPLIT_THREADS`] where not zero: a benchmark's measure of another count. -#[cfg(test)] -pub(crate) static SPLIT_THREADS_FROM: AtomicUsize = AtomicUsize::new(0); - -/// The threads a comparison may run on: [`SPLIT_THREADS`], or as many as the host runs at once -/// where fewer. -fn split_threads() -> usize { - static HOST: OnceLock = OnceLock::new(); - let host = *HOST - .get_or_init(|| std::thread::available_parallelism().map_or(1, |threads| threads.get())); - #[cfg(test)] - match SPLIT_THREADS_FROM.load(Ordering::Relaxed) { - 0 => {} - threads => return host.min(threads), - } - host.min(SPLIT_THREADS) -} - -/// Run `work` over the blocks of a copy whose tags are `tags`, from its block `first`, split into -/// at most one run for each of [`split_threads`], each a whole number of [`SYNC_BLOCK`]s of at -/// least [`SPLIT_BYTES`] but the last, which may be shorter, on as many threads ([`in_threads`]). -/// `work` takes a run's first block and its tags. The runs' tallies, joined in order. -fn split( - tags: &mut [Tag], - first: usize, - work: impl Fn(usize, &mut [Tag]) -> Tally + Sync, -) -> Tally { - let threads = (tags.len() * TAG_BLOCK / SPLIT_BYTES).clamp(1, split_threads()); - if threads == 1 { - return work(first, tags); - } - let each = (tags.len().div_ceil(threads)).next_multiple_of(SYNC_BLOCK / TAG_BLOCK); - let runs = (tags.chunks_mut(each).enumerate()).map(|(index, run)| (first + index * each, run)); - in_threads(threads, runs, |(first, run)| work(first, run)) -} - -/// Run `work` over each of `runs` on `threads` threads (two or more), the calling one among them: -/// it takes runs, and so does each thread started for the others (`exit_guard::spawn_scoped`, -/// raised to at least the user-initiated class), all ended before this returns; a thread the -/// system does not start leaves its runs to the rest. The runs' tallies, joined in the runs' -/// order, and the threads started ([`Tally::started`]). -fn in_threads( - threads: usize, - runs: impl Iterator + Send, - work: impl Fn(R) -> Tally + Sync, -) -> Tally { - let runs = Mutex::new(runs.enumerate()); - let tallies = Mutex::new(Vec::with_capacity(threads)); - let pull = || { - loop { - // The lock is let go before the run's work: a `while let` would hold it throughout. - let next = lock(&runs).next(); - let Some((index, run)) = next else { - return; - }; - let tally = work(run); - lock(&tallies).push((index, tally)); - } - }; - let started = std::thread::scope(|scope| { - let pull = &pull; - let started = (1..threads).filter(|_| { - let builder = std::thread::Builder::new() - .name("m2v-copied-compare".to_owned()) - .stack_size(SPLIT_STACK); - // One the system does not start leaves its runs to the others. - let thread = crate::exit_guard::spawn_scoped(scope, builder, move || { - crate::exit_guard::raise_to_user_initiated(); - pull() - }); - thread.is_ok() - }); - let started = started.count() as u64; - pull(); - started - }); - let mut tallies = tallies.into_inner().unwrap_or_else(PoisonError::into_inner); - tallies.sort_by_key(|(index, _)| *index); - let started = Tally { - started, - ..Tally::default() - }; - (tallies.into_iter()).fold(started, |tally, (_, run)| tally.and(run)) -} - -/// A copy in of a copy with a base whose tags are `tags`, over `bytes` (from a multiple of -/// [`SYNC_BLOCK`]) of `sides`, split across threads ([`split`]), one pass of [`two_passes`] -/// (`fetch`): each block of the pages whose tag differs from the base's is compared with the -/// base's bytes, and each byte that differs written into the copy. The base's bytes are the -/// copy's block where its tag still agrees (the GPU did not change it since), else read from the -/// base. The base then holds the block as written, the pages' bytes over the base's. -/// -/// # Safety -/// -/// `sides` holds an entry's live pointers and its base's bytes, `tags` the base's tags, and -/// `bytes` lies in the copy. -unsafe fn copy_in_tagged( - sides: Sides<'_>, - tags: &mut [Tag], - bytes: Range, - fetch: Fetch<'_>, -) -> Tally { - let (first, end) = (bytes.start / TAG_BLOCK, bytes.end.div_ceil(TAG_BLOCK)); - // SAFETY: the caller's, for the run's own blocks. - split(&mut tags[first..end], first, |first, tags| unsafe { - copy_in_blocks(sides, first, tags, fetch) - }) -} - -/// [`copy_in_tagged`] of the blocks whose tags are `tags`, from the copy's block `first`. -/// -/// # Safety -/// -/// As [`copy_in_tagged`]'s, and no other thread reaches these blocks. -unsafe fn copy_in_blocks( - sides: Sides<'_>, - first: usize, - tags: &mut [Tag], - fetch: Fetch<'_>, -) -> Tally { - let (pages, copy) = (sides.pages.as_ptr(), sides.copy.as_ptr()); - let mut tally = Tally::default(); - let (mut now, mut was) = ([0u8; TAG_BLOCK], [0u8; TAG_BLOCK]); - each_block(first, tags, fetch.deferred(), |index, agreed| { - #[cfg(test)] - let mut lap = clock::Lap::new(clock::COPY_IN, index); - let at = index * TAG_BLOCK; - let span = (sides.length - at).min(TAG_BLOCK); - // SAFETY: `span` bytes at `at` lie in the pages (the caller's). - if unsafe { tag_in_place(pages.add(at), span, &mut now) } == *agreed { - return; - } - // The block's bytes, read once: those merged, and those the base takes. - // SAFETY: as above. - unsafe { read_block(pages.add(at), span, &mut now) }; - let changed = tag(&now); - if changed == *agreed { - // Written back since its tag was read. - return; - } - #[cfg(test)] - lap.next(); - // SAFETY: as above, in the copy. - unsafe { read_block(copy.add(at), span, &mut was) }; - let copy_agrees = tag(&was) == *agreed; - let (mut kept, mut moved) = (sides.kept(index), None); - if !copy_agrees { - // SAFETY: as above, the block of the base's bytes, this run's own. - let read = unsafe { sides.read_base(index, kept, &mut was[..span], fetch) }; - let Some(read) = read else { - tally.deferred.push(index); - return; - }; - moved = read; - kept = kept.or(moved.as_ref().map(HostBlock::at)); - tally.read += 1; - } - #[cfg(test)] - lap.next(); - // SAFETY: as above, in the copy. - tally.written += - unsafe { merge_block(&now[..span], copy.add(at), &mut was[..span], false) }; - #[cfg(test)] - lap.next(); - // The pages' block over the base's: the pages' own where the copy's agreed. - *agreed = match copy_agrees { - true => changed, - false => tag(&was), - }; - // SAFETY: as above. - unsafe { sides.write_base(index, kept, &was[..span]) }; - tally.kept.extend(moved.map(|block| (index, block))); - }); - tally -} - -/// A merge back of a copy with a base whose tags are `tags` (that keeps the GPU's writes), of -/// `sides`, split across threads ([`split`]), one pass of [`two_passes`] (`fetch`): each block of -/// the copy whose tag differs from the base's is compared with the agreed bytes, and each byte -/// that differs written into the pages, unless the pages' byte differs from the agreed one -/// already (the CPU wrote it since: [`merge_block`]), and the blocks of [`SYNC_BLOCK`] bytes it -/// wrote a byte of noted. The agreed bytes are the pages' block where its tag still agrees (the -/// CPU did not change it since), else read from the base. The base then holds the copy's block. -/// -/// # Safety -/// -/// `sides` holds an entry's live pointers and its base's bytes, and `tags` the base's tags. -unsafe fn merge_tagged(sides: Sides<'_>, tags: &mut [Tag], fetch: Fetch<'_>) -> Tally { - // SAFETY: the caller's, for the run's own blocks. - split(tags, 0, |first, tags| unsafe { - merge_blocks(sides, first, tags, fetch) - }) -} - -/// [`merge_tagged`] of the blocks whose tags are `tags`, from the copy's block `first`. -/// -/// # Safety -/// -/// As [`merge_tagged`]'s, and no other thread reaches these blocks. -unsafe fn merge_blocks( - sides: Sides<'_>, - first: usize, - tags: &mut [Tag], - fetch: Fetch<'_>, -) -> Tally { - let (copy, pages) = (sides.copy.as_ptr(), sides.pages.as_ptr()); - let mut tally = Tally::default(); - let (mut now, mut was) = ([0u8; TAG_BLOCK], [0u8; TAG_BLOCK]); - each_block(first, tags, fetch.deferred(), |index, agreed| { - #[cfg(test)] - let mut lap = clock::Lap::new(clock::MERGE_BACK, index); - let at = index * TAG_BLOCK; - let span = (sides.length - at).min(TAG_BLOCK); - // SAFETY: `span` bytes at `at` lie in the copy (the caller's). - if unsafe { tag_in_place(copy.add(at), span, &mut now) } == *agreed { - return; - } - // The block's bytes, read once: those merged, and those the base takes. - // SAFETY: as above. - unsafe { read_block(copy.add(at), span, &mut now) }; - let changed = tag(&now); - if changed == *agreed { - return; - } - #[cfg(test)] - lap.next(); - // The agreed bytes: the pages' block, read once, where its tag still agrees (the CPU - // did not change it since), else the base's (both sides changed it). - // SAFETY: as above, in the pages. - unsafe { read_block(pages.add(at), span, &mut was) }; - let (mut kept, mut moved) = (sides.kept(index), None); - if tag(&was) != *agreed { - // SAFETY: as above, the block of the base's bytes, this run's own. - let read = unsafe { sides.read_base(index, kept, &mut was[..span], fetch) }; - let Some(read) = read else { - tally.deferred.push(index); - return; - }; - moved = read; - kept = kept.or(moved.as_ref().map(HostBlock::at)); - tally.read += 1; - } - #[cfg(test)] - lap.next(); - // SAFETY: as above, in the pages. - let merged = unsafe { merge_block(&now[..span], pages.add(at), &mut was[..span], true) }; - #[cfg(test)] - lap.next(); - if merged > 0 { - tally.wrote((at / SYNC_BLOCK * SYNC_BLOCK) as u64, sides.length); - } - tally.written += merged; - *agreed = changed; - // SAFETY: as above. - unsafe { sides.write_base(index, kept, &now[..span]) }; - tally.kept.extend(moved.map(|block| (index, block))); - }); - tally -} - -/// A merge back of a copy with a base whose tags are `tags` and whose GPU writes are dropped, of -/// `sides`, split across threads ([`split`]), one pass of [`two_passes`] (`fetch`): each block of -/// the copy whose tag differs from the base's takes back the base's bytes wherever it differs -/// from them, and nothing is written to the pages or the base. The base's bytes are the pages' -/// block where its tag still agrees, else read from the base. -/// -/// # Safety -/// -/// `sides` holds an entry's live pointers and its base's bytes, and `tags` the base's tags. -unsafe fn restore_tagged(sides: Sides<'_>, tags: &mut [Tag], fetch: Fetch<'_>) -> Tally { - // SAFETY: the caller's, for the run's own blocks. - split(tags, 0, |first, tags| unsafe { - restore_blocks(sides, first, tags, fetch) - }) -} - -/// [`restore_tagged`] of the blocks whose tags are `tags`, from the copy's block `first`: their -/// tags are not changed. -/// -/// # Safety -/// -/// As [`restore_tagged`]'s, and no other thread reaches these blocks. -unsafe fn restore_blocks( - sides: Sides<'_>, - first: usize, - tags: &mut [Tag], - fetch: Fetch<'_>, -) -> Tally { - let (copy, pages) = (sides.copy.as_ptr(), sides.pages.as_ptr()); - let mut tally = Tally::default(); - let (mut now, mut agreed) = ([0u8; TAG_BLOCK], [0u8; TAG_BLOCK]); - each_block(first, tags, fetch.deferred(), |index, tagged| { - let at = index * TAG_BLOCK; - let span = (sides.length - at).min(TAG_BLOCK); - // SAFETY: `span` bytes at `at` lie in the copy (the caller's). - if unsafe { tag_in_place(copy.add(at), span, &mut now) } == *tagged { - return; - } - // SAFETY: as above. - unsafe { read_block(copy.add(at), span, &mut now) }; - // SAFETY: as above, in the pages. - unsafe { read_block(pages.add(at), span, &mut agreed) }; - if tag(&agreed) != *tagged { - let kept = sides.kept(index); - // SAFETY: as above, the block of the base's bytes, this run's own. - let read = unsafe { sides.read_base(index, kept, &mut agreed[..span], fetch) }; - let Some(moved) = read else { - tally.deferred.push(index); - return; - }; - tally.read += 1; - if let Some(block) = moved { - // SAFETY: as above; the block is this run's new one. - unsafe { sides.write_base(index, Some(block.at()), &agreed[..span]) }; - tally.kept.push((index, block)); - } - } - // SAFETY: as above, in the copy. - tally.written += - unsafe { merge_block(&agreed[..span], copy.add(at), &mut now[..span], false) }; - }); - tally -} - -/// One block whose bytes `now` (read of one side) differ from the agreed bytes `was`: each byte of -/// `now` that differs from `was` written into `to` (where `keep_to`, unless `to`'s byte differs -/// from `was` already: the other side wrote it since) and taken into `was`, so no byte that did -/// not change is written. The bytes written. On an x86-64 host 16 bytes at a time -/// ([`x86::merge_sse2`]), else 8 ([`merge_words`]). -/// -/// # Safety -/// -/// `to` is `now.len()` bytes of mapped memory, `was` as long. -pub(crate) unsafe fn merge_block(now: &[u8], to: *mut u8, was: &mut [u8], keep_to: bool) -> u64 { - #[cfg(target_arch = "x86_64")] - { - // SAFETY: the caller's; every x86-64 host has SSE2. - unsafe { x86::merge_sse2(now, to, was, keep_to) } - } - #[cfg(not(target_arch = "x86_64"))] - { - // SAFETY: the caller's. - unsafe { merge_words(now, to, was, keep_to) } - } -} - -/// [`merge_block`] 8 bytes at a time, and in each 8 that differ, byte by byte: eight in one store -/// where all eight differ (and, where `keep_to`, none of `to`'s does). The bytes written. -/// -/// # Safety -/// -/// As [`merge_block`]'s. -unsafe fn merge_words(now: &[u8], to: *mut u8, was: &mut [u8], keep_to: bool) -> u64 { - let mut written = 0u64; - let mut at = 0; - while at < now.len() { - let span = (now.len() - at).min(8); - let (now, was) = (&now[at..at + span], &mut was[at..at + span]); - if now != was { - let mut there = [0u8; 8]; - if keep_to { - // SAFETY: `span` bytes at `at` lie in `to` (the caller's). - unsafe { std::ptr::copy_nonoverlapping(to.add(at), there.as_mut_ptr(), span) }; - } - // Eight bytes that all changed, none of them written in `to` since: the same bytes - // the loop below writes, in one store. - let every = now.iter().zip(was.iter()).all(|(now, was)| now != was); - if let (Ok(word), true) = (<[u8; 8]>::try_from(now), every) { - if !keep_to || there[..] == was[..] { - // SAFETY: as above; `[u8; 8]` is aligned to 1. - unsafe { to.add(at).cast::<[u8; 8]>().write_volatile(word) }; - written += 8; - was.copy_from_slice(now); - at += span; - continue; - } - } - for byte in 0..span { - if now[byte] == was[byte] { - continue; - } - if !keep_to || there[byte] == was[byte] { - // SAFETY: as above. - unsafe { to.add(at + byte).write_volatile(now[byte]) }; - written += 1; - } - was[byte] = now[byte]; - } - } - at += span; - } - written -} - -/// Read the caller's `into.len()` bytes at `pages` into `into`: through the kernel (`kernel`, -/// [`read_pages`]), and where it fails, with plain loads where every page of them is mapped with -/// read permission (`readable`, asked for the bytes' addresses, [`mapped_readable`]). Whether -/// they were read: `false` where the kernel failed and a page is not mapped readable. -/// -/// The kernel's read is a test that faults on nothing, but on Linux it pins each page, and no -/// page of a `VM_PFNMAP` or `VM_IO` mapping can be pinned: a mapping of a dma-buf (udmabuf's on -/// Linux 7.2, measured) is mapped readable and fails it all the same. The plain loads are the -/// access a copy's comparisons make at each commit ([`CopiedBuffers::copy_in`]). -/// -/// # Safety -/// -/// `pages` is `into.len()` bytes the CPU reads without a fault wherever `readable` answers `true` -/// for them. -pub(crate) unsafe fn read_caller( - pages: NonNull, - into: &mut [u8], - kernel: impl FnOnce(NonNull, &mut [u8]) -> bool, - readable: impl FnOnce(u64, u64) -> bool, -) -> bool { - if kernel(pages, into) { - return true; - } - let start = pages.as_ptr() as u64; - if !readable(start, start + into.len() as u64) { - return false; - } - // SAFETY: the bytes are mapped readable (the caller's); `into` is the runtime's own, apart. - unsafe { std::ptr::copy_nonoverlapping(pages.as_ptr(), into.as_mut_ptr(), into.len()) }; - true -} - -/// Read the caller's `into.len()` bytes at `pages` into `into` through the kernel, which answers a -/// page the process cannot read (unmapped, or mapped without read permission) with a failure, not a -/// fault: `false` then. On Linux `process_vm_readv` of the process's own pages; on macOS -/// `mach_vm_read_overwrite` of its own task's; on Windows `ReadProcessMemory` of its own. -#[cfg(target_os = "linux")] -pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { - let mut done = 0; - while done < into.len() { - let local = libc::iovec { - iov_base: into[done..].as_mut_ptr().cast(), - iov_len: into.len() - done, - }; - let remote = libc::iovec { - iov_base: pages.as_ptr().wrapping_add(done).cast(), - iov_len: into.len() - done, - }; - // SAFETY: the local vector names `into`'s bytes, which the call writes; the remote one is - // read through the kernel, which answers an unreadable page with an error. - let read = unsafe { libc::process_vm_readv(libc::getpid(), &local, 1, &remote, 1, 0) }; - if read <= 0 { - return false; - } - done += read as usize; - } - true -} - -/// [`read_pages`] on macOS. -#[cfg(target_os = "macos")] -pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { - unsafe extern "C" { - /// ``: the port of this process's task. - static mach_task_self_: libc::mach_port_t; - fn mach_vm_read_overwrite( - target_task: libc::vm_map_t, - address: libc::mach_vm_address_t, - size: libc::mach_vm_size_t, - data: libc::mach_vm_address_t, - outsize: *mut libc::mach_vm_size_t, - ) -> libc::kern_return_t; - } - let mut read = 0; - // SAFETY: the call writes `into`'s bytes alone, and answers an unreadable page of the source - // with an error. - let answer = unsafe { - mach_vm_read_overwrite( - mach_task_self_, - pages.as_ptr() as u64, - into.len() as u64, - into.as_mut_ptr() as u64, - &mut read, - ) - }; - answer == libc::KERN_SUCCESS && read == into.len() as u64 -} - -/// [`read_pages`] on Windows: `ReadProcessMemory` of the process's own pages, which answers a -/// page it cannot read with a failure. -#[cfg(windows)] -pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { - use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; - use windows_sys::Win32::System::Threading::GetCurrentProcess; - let mut read = 0; - // SAFETY: the call writes `into`'s bytes alone, through the pseudo-handle of this process, - // and answers an unreadable page of the source with a failure. - let answer = unsafe { - ReadProcessMemory( - GetCurrentProcess(), - pages.as_ptr().cast(), - into.as_mut_ptr().cast(), - into.len(), - &mut read, - ) - }; - answer != 0 && read == into.len() -} diff --git a/crates/metal2vulkan-runtime/src/copied_base.rs b/crates/metal2vulkan-runtime/src/copied_base.rs deleted file mode 100644 index 92c74829e..000000000 --- a/crates/metal2vulkan-runtime/src/copied_base.rs +++ /dev/null @@ -1,175 +0,0 @@ -//! The device's memory of a copied host buffer's base (`copied.rs`, "A base once it may"): the -//! bytes the pages and the copy last agreed on, in device-local memory the host maps, where the -//! device has such memory with room ([`memory::allocate_copied_base`]) and a staging queue -//! (`device/staging.rs`), so that a copy the GPU writes holds no second copy of its bytes in the -//! host's memory. The host writes the base a block at a time where a block changed, and reads it -//! only for a block the CPU and the GPU both changed since they agreed: itself, uncached, a block -//! at a time, where a comparison reads few, and through one copy into host memory on the staging -//! queue where it reads many ([`Held::read_back`]). The staging queue waits for no work of the -//! program's, so a completion's merge back that copies there waits for its copy alone. - -use crate::copied::{BaseBytes, Held}; -use crate::device::lock; -use crate::exit_guard; -use crate::memory::{self, Placement}; -use crate::release; -use crate::texture::{staging_buffer, transfer_barrier}; -use crate::Device; -use ash::vk; -use std::ops::{Deref, Range}; -use std::ptr::NonNull; - -/// A base's bytes in the device's memory, and the buffer over them its reads back copy from: -/// freed as it goes. -struct DeviceBase { - device: Device, - raw: vk::Buffer, - placement: Placement, -} - -impl Drop for DeviceBase { - fn drop(&mut self) { - // The process is exiting: the memory goes with the device. - let Some(busy) = exit_guard::enter() else { - return; - }; - let shared = self.device.shared(); - // SAFETY: no submission uses the buffer: each read back was waited for before it - // returned, and nothing else uses it. - unsafe { release::object(shared.vk(), self.raw) }; - lock(&shared.memory).free(shared.vk(), &self.placement); - drop(busy); - } -} - -impl Held for DeviceBase { - /// The base's bytes of `runs`, copied on the device's staging queue into a host-visible - /// buffer of the device's in memory the host caches where it has such (`MemoryClass::Shared`), - /// in one submission waited for here: `None` where the process is exiting, the device is - /// lost, or no memory holds the buffer. - fn read_back(&self, runs: &[Range]) -> Option>> { - let _busy = exit_guard::enter()?; - let len: usize = runs.iter().map(|run| run.end - run.start).sum(); - let read = ReadBack::new(&self.device, len)?; - let mut at = 0u64; - let regions: Vec = (runs.iter()) - .map(|run| { - let size = (run.end - run.start) as u64; - let region = vk::BufferCopy { - src_offset: run.start as u64, - dst_offset: at, - size, - }; - at += size; - region - }) - .collect(); - let (from, to) = (self.raw, read.raw); - let mut staging = self.device.staging_lock().ok()?; - let value = staging.submit(|raw, command_buffer, _| { - transfer_barrier(raw, command_buffer, true); - // SAFETY: the staging command buffer is recording, outside a render pass; both - // buffers are live and shared with the staging queue's family, the base's bytes - // written by the host before this submission, and the regions lie in each. - unsafe { raw.cmd_copy_buffer(command_buffer, from, to, ®ions) }; - transfer_barrier(raw, command_buffer, false); - }); - drop(staging); - self.device.wait_staging(value.ok()?).ok()?; - Some(Box::new(read)) - } -} - -/// A host-visible buffer a base's read back copies into, released when dropped. -struct ReadBack { - device: Device, - raw: vk::Buffer, - placement: Placement, - len: usize, -} - -impl ReadBack { - /// A buffer of `len` bytes; `None` where no memory holds it. - fn new(device: &Device, len: usize) -> Option { - let (raw, placement) = staging_buffer(device, len as u64).ok()?; - Some(ReadBack { - device: device.clone(), - raw, - placement, - len, - }) - } -} - -impl Deref for ReadBack { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - let Some(mapped) = self.placement.mapped else { - unreachable!("checked when the staging buffer was made"); - }; - // SAFETY: the mapping covers the placement's `len` bytes, which only this buffer uses; - // the memory is host-coherent, and the copy into it completed, seen by the host - // (`Device::wait_staging`), before it was handed out. - unsafe { std::slice::from_raw_parts(mapped.as_ptr(), self.len) } - } -} - -impl Drop for ReadBack { - fn drop(&mut self) { - // Once the process is exiting, the buffer is left to its end (`exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - let shared = self.device.shared(); - // SAFETY: the submission that used it completed, or the device was lost. - unsafe { release::object(shared.vk(), self.raw) }; - lock(&shared.memory).free(shared.vk(), &self.placement); - } -} - -impl Device { - /// The bytes of a copied host buffer's base of `length` bytes in the device's memory - /// ([`memory::allocate_copied_base`]), with a buffer over them that its reads back copy from - /// on the staging queue: `None` where the device has no staging queue or no such memory with - /// room for them, and they lie in the host's. - pub(crate) fn copied_base(&self, length: usize) -> Option { - if !self.has_staging_queue() { - return None; - } - let shared = self.shared(); - let raw_device = shared.vk(); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(length as u64) - .usage(vk::BufferUsageFlags::TRANSFER_SRC), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.ok()?; - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - let Some(placement) = - memory::allocate_copied_base(&shared.memory, raw_device, &requirements) - else { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - return None; - }; - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - let bound = unsafe { - crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) - }; - let at = placement.mapped.map(|mapped| mapped.as_ptr()); - let held = DeviceBase { - device: self.clone(), - raw, - placement, - }; - bound.ok()?; - let at = NonNull::new(at?)?; - // SAFETY: the placement is `length` bytes of device-local memory the host maps, coherent - // (`Memory::copied_base_type`), that nothing else uses, mapped until `held` frees it, - // and the buffer over it is `held`'s, which reads it back. - Some(unsafe { BaseBytes::device(at, length, Box::new(held)) }) - } -} diff --git a/crates/metal2vulkan-runtime/src/copy_plan.rs b/crates/metal2vulkan-runtime/src/copy_plan.rs deleted file mode 100644 index 684ceddba..000000000 --- a/crates/metal2vulkan-runtime/src/copy_plan.rs +++ /dev/null @@ -1,617 +0,0 @@ -//! Texture copies: Metal's blit copies between buffers and textures and between textures, and -//! `replaceRegion` and `getBytes`, as Vulkan copy regions. -//! -//! A copy moves Metal's **copy units**: a pixel of an uncompressed format, a block of a compressed -//! one, and of a combined depth/stencil format the aspect the blit option names (a depth texel as -//! a 4-byte float, a stencil texel as a byte). Vulkan's buffer layout for the same aspect of the -//! image's format is the same bytes for every format the runtime holds exactly, so a copy is a -//! byte copy in both APIs, whatever view emulation the image uses for sampling. -//! -//! Metal's rules (API validation, measured on an Apple M3 Max and M4): -//! -//! - **Regions** stay in the level, a compressed region in the level's blocks: a level that ends -//! inside a block holds that whole block, so a region may name it past the level's texels (4 x 4 -//! of a 4 x 2 level). Metal's validation takes such a region out of a texture, between textures -//! and of the CPU, and stops it into a texture from a buffer, which plain Metal copies all the -//! same (an Apple M3 Max under macOS 26.7, a probe). A compressed region starts on a block and -//! covers whole blocks, except where it reaches the level's edge. Plain Metal copies a region off -//! its blocks as the blocks it starts in: the origin rounded down to its block and the size -//! rounded up to whole blocks, each on its own, so does the runtime, ending -//! at the level's edge where the blocks pass it, in every copy between buffers and textures, -//! between textures, and of the CPU. -//! - **Buffer layouts:** the offset and `bytesPerRow` are multiples of the copy unit; -//! `bytesPerRow` covers a row when the region has more than one; `bytesPerImage` is a multiple -//! of the copy unit covering the region's rows when the region has more than one image (one -//! image ignores it); the bytes stay in the buffer. A blit of an offset, `bytesPerRow` or -//! `bytesPerImage` off them copies where plain Metal places its rows (`blit_plan.rs`). -//! - **Blit options:** a combined depth/stencil texture is copied by one aspect, named by -//! `DepthFromDepthStencil` or `StencilFromDepthStencil`; no other texture takes an option. The -//! stencil view of a combined one (`X32Stencil8`) copies its stencil whatever the option, as -//! plain Metal does (a probe; its validation stops `DepthFromDepthStencil`). Plain Metal copies -//! the other forms its validation stops, and so does the runtime (an M4 under macOS 27.0.1): a -//! combined depth/stencil texture without an option copies its depth, and an option that names an -//! aspect the format lacks is ignored (a colour format copies its texels, `Depth32Float` its -//! depth, `Stencil8` its stencil). `RowLinearPVRTC` lays a PVRTC texture's blocks out row by row, -//! and another format ignores it, as plain Metal does (its validation stops it on another -//! compressed format). -//! - **Texture to texture:** sample counts match, and the formats are equal (macOS 27.0.1's -//! validation) or of one copy unit (macOS 26.7's; both copy the bytes without validation). The -//! runtime takes macOS 26.7's rule. A depth-only or stencil-only format, or the stencil view -//! `X32Stencil8`, has its one aspect's unit (2 bytes for `Depth16Unorm`, 4 for `Depth32Float`, -//! 1 for stencil), and Metal copies its bytes to and from colour formats of that unit and -//! between stencil formats (probes on an M3 Max and an M4: every value, NaN payloads, denormals -//! and depth outside `[0, 1]` included); a combined depth/stencil format copies only into its own -//! format, both aspects. A copy of levels and slices copies at each pair of levels the copy -//! units both levels hold, from their origins, whole: of a compressed format the blocks both -//! hold, the block that passes the smaller level's edge included (an Apple M3 Max under macOS -//! 27.0.1, our probe, over BC1, BC3, BC4, BC7, `EAC_RGBA8`, `ETC2_RGB8` and ASTC 6 x 5). -//! - **CPU access:** `replaceRegion` and `getBytes` refuse a private texture and a combined -//! depth/stencil format (a depth-only or stencil-only format is copied), and take the buffer -//! layout rules above without an offset. Plain Metal copies a combined format's depth, as a -//! blit without an option does, the stencil left as it is, and so does the runtime. A -//! `bytesPerRow` or `bytesPerImage` off the rules is taken as plain Metal takes it -//! ([`plan_host_copy`]). -//! -//! `replaceRegion` and `getBytes` copy through a tightly packed staging layout, packed on the -//! host ([`HostLayout`]); the blit encoder's copies are `blit_plan.rs`'s. - -use super::chroma_pairs::{is_four_two_two, TEXEL_BYTES}; -use super::host_bytes::HostBytes; -use super::pvrtc::{is_pvrtc, BLOCK_BYTES}; -use super::view_plan::ViewRecord; -use metal2vulkan::bind::{AstcDecode, YCbCrCodes}; -use metal2vulkan::error::{Feature, Unsupported}; -use metal2vulkan::metal::format::{ - aspects, byte_format, is_depth_stencil, ycbcr_format, FormatMapping, -}; -use metal2vulkan::metal::{PixelFormat, TextureType}; -use metal2vulkan::vk::{Format, ImageAspectFlags}; - -/// `MTLBlitOption`, as far as copies take one. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum BlitOption { - /// `MTLBlitOptionNone`. - #[default] - None, - /// `MTLBlitOptionDepthFromDepthStencil`: the depth of a combined depth/stencil texture. - DepthFromDepthStencil, - /// `MTLBlitOptionStencilFromDepthStencil`: the stencil of a combined depth/stencil texture. - StencilFromDepthStencil, - /// `MTLBlitOptionRowLinearPVRTC`: a PVRTC texture's blocks lie in the buffer row by row, as - /// every other compressed format's do (Metal lays them out in block order without it). - /// Another format ignores it, as plain Metal does. - RowLinearPVRTC, -} - -/// A copy Metal's API validation stops. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum CopyProblem { - /// `replaceRegion` or `getBytes` of a private texture. Plain Metal answers by the texture's - /// private layout, which no descriptor rule predicts (an M4 under macOS 27.0.1): a texture of - /// up to 8 KiB copies as a shared one, most of 16 KiB and more end the process, a 64x64 one - /// with `ShaderWrite` of 4 bytes a texel copies nothing, and a combined depth/stencil one - /// copies nothing at 2x2. - /// - /// Basis: metal-takes (an M4, macOS 27.0.1: plain Metal copies a private texture of up to 8 KiB - /// as a shared one, so the refusal reaches past it; most of 16 KiB and more end the process). - CpuAccessPrivate, - /// A level or slice past the texture, or a region past its level (a compressed region past - /// the level's last block). - /// - /// Basis: unknown (plain Metal's answer for a blit level, slice or region past the texture is - /// unmeasured). - Region, - /// A buffer offset that is not a multiple of the copy unit, of a blit whose plain Metal - /// answer is not measured: a depth or stencil format other than `Depth32Float`, or a - /// texture over a buffer (other blits copy where plain Metal places the rows). - /// - /// Basis: unknown (plain Metal's answer for a buffer offset off the copy unit of these blits is - /// not measured). - Offset, - /// A `bytesPerRow` that is not a multiple of the copy unit, or that does not cover a row, - /// where plain Metal's answer is undefined or not measured: Metal's aligned path into a - /// texture at a pitch of 0 (it reads garbage) or from an offset of 16 or more, a depth or - /// stencil format other than `Depth32Float` or a texture over a buffer at a pitch off the - /// copy unit or of 0 for more than one row, a multisampled texture's copy out at a pitch - /// below a row (where its rows lie is not measured), and a CPU copy of a texture over a - /// buffer or of a pitch of 0 for more than one row and image (other layouts copy where plain - /// Metal places the rows, a blit's rows out of a texture that overlap in turn, the later - /// row's bytes standing). - /// - /// Basis: unknown (undefined or unmeasured by the shapes listed above). - BytesPerRow, - /// Bytes past the end of the buffer: of a no-copy buffer read from, past the end of its - /// host pages, which plain Metal reads up to. Past that, and past another buffer's length, - /// plain Metal reads zeros, bytes a write past the length left, or another resource's bytes (an - /// M4 under macOS 27.0.1). - /// - /// Basis: metal-takes (an M4, macOS 27.0.1: plain Metal reads past the buffer rather than - /// refusing — zeros, bytes a write past the length left, or another resource's bytes). - BufferRange, - /// Two textures whose formats a copy does not take. Plain Metal copies the source's bytes - /// in the GPU's own texel layout, which differs between formats of different units (an M4 - /// under macOS 27.0.1): no defined answer. - /// - /// Basis: metal-takes (an M4, macOS 27.0.1: plain Metal copies the source's bytes in the GPU's - /// own texel layout rather than refusing, which differs between formats of different units: no - /// defined answer). - Format, - /// Two textures of different sample counts. Plain Metal copies the bytes of the GPU's own - /// sample layout, which is the device's and not the API's: no answer a Vulkan device can be - /// held to. Of a source whose every (texel, sample) holds a value naming it, a copy out of a - /// 1- or 2-sample texture lands each source value at the destination byte of the same offset - /// in the GPU's Morton-twiddled layout, sample `s` of texel `(x, y)` at - /// `unit * (samples * morton(x, y) + s)`, and out of a 4-sample texture it lands bytes that - /// decode to no source value at all, the GPU's own compressed 4-sample form (an Apple M3 Max - /// under macOS 27.0.1, our probe `copy_sample_counts_and_block_sizes.m`: 1 to 2, 1 to 4, 2 to - /// 1 and 2 to 4 each match that layout exactly, 4 to 1 and 4 to 2 match nothing, and the - /// matched copies beside them reproduce every sample; 12 processes of each read alike, and the - /// destination's storage mode and heap placement change nothing). The same device makes no - /// 8-sample texture at all, so no copy of one exists there to measure. - /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal completes the copy with no - /// error rather than refusing it, so the refusal reaches past Metal; what it stores is its own - /// texel twiddling and sample compression, which neither Metal nor Vulkan defines, so the - /// runtime has no exact answer to put in its place). - SampleCount, - /// A copy of whole textures whose extents pair at no level, where plain Metal aborts, or - /// whose paired level lies past the end of one texture's own levels, where plain Metal reads - /// or writes a level that texture does not hold. (Levels of different sizes copy the copy - /// units both hold, compressed or not, and whole textures the levels and slices they share, - /// paired by extent, as plain Metal copies them: `blit_plan.rs`.) - /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1, our probe - /// `copy_sample_counts_and_block_sizes.m`, 12 processes of every shape alike. The first shape - /// is Metal's own refusal: `wh-plain-8x8-to-8x4`, `wh-plain-8l4-to-3l2` and - /// `wh-astc65-18x15-to-12x10` each end the process, SIGABRT, on `MTLPickLargestMip`'s - /// `Postcondition does not hold`, where every pairing shape beside them completes. The second - /// reaches past Metal: `wh-bc1-16-to-4`, `wh-bc1-32-to-4`, `wh-plain-16-to-4` and - /// `wh-plain-32-to-8`, each a source of one level paired at its level 2 or 3, all four - /// complete with no error and write the destination's level 0 from the source's level 0, a - /// level the pairing did not name, which is Metal's own answer for an out-of-range level - /// offset and not one the runtime can put in its place; the mirrored `wh-bc1-4-to-16` and - /// `wh-plain-4-to-16` write nothing at all). - Size, -} - -/// Why a copy cannot be made. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(super) enum CopyRefusal { - Invalid(CopyProblem), - Unsupported(Unsupported), -} - -impl From for CopyRefusal { - fn from(problem: CopyProblem) -> CopyRefusal { - CopyRefusal::Invalid(problem) - } -} - -/// What one Metal copy unit is: its bytes, its extent in texels, and the Vulkan aspect it copies. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct CopyUnit { - pub(super) bytes: u32, - pub(super) extent: [u32; 2], - pub(super) aspect: ImageAspectFlags, -} - -/// The texel extent of a block of the compressed format `pf` (`None` for an uncompressed -/// format). -/// -/// The translator owns the fact ([`metal2vulkan::metal::format::block_extent`]), since it is a -/// property of the `MTLPixelFormat` and not of a copy: this is the name this module reads it by. -pub(super) use metal2vulkan::metal::format::block_extent; - -/// The bytes of a block (a texel, uncompressed) of the colour format `pf`: its byte format's -/// (`metal::format::byte_format`, the format whose image holds Metal's bytes), a PVRTC block's 8 -/// and an ASTC block's 16, which the device may hold in a carrier of no PVRTC or ASTC format -/// (`pvrtc.rs`, `astc.rs`). -pub(super) fn block_bytes(pf: PixelFormat) -> Option { - if is_pvrtc(pf) { - return Some(BLOCK_BYTES); - } - // An ASTC block is 16 bytes at every footprint, Apple's 4x2 and 8x4 among them, which no - // Vulkan format holds (their carrier does, `astc.rs`). - if AstcDecode::of(pf).is_some() { - return Some(AstcDecode::BLOCK_BYTES); - } - // Plain Metal copies a 4:2:2 texture's 2-byte texels at any x, width, offset and pitch (its - // validation asks for 2 x 1 blocks of 4 bytes), which its carrier holds - // one to an image texel (`chroma_pairs.rs`). - if is_four_two_two(pf) { - return Some(TEXEL_BYTES); - } - // A two-plane YCbCr texture's texels are its surface's luma codes, a code's bytes a texel (1 - // for `YCBCR8_420_2P`, 2 for the 10-bit formats), which Metal's blits and CPU calls move - // (`ycbcr.rs`). A packed one's blits with a buffer move bytes at places that follow no rule - // found, by the buffer's bytes per row: no block, so they are refused - // (`NotImplemented(Format)`). - if let Some(codes) = ycbcr_format(pf).and_then(YCbCrCodes::of) { - return (!codes.packed).then_some(codes.bytes); - } - byte_format(pf) - .and_then(|f| f.block()) - .map(|block| block.size) -} - -/// The bytes of the depth Vulkan copies of `format`'s depth aspect, when they are Metal's: -/// a 4-byte float for 32-bit float depth, 2 bytes for 16-bit normalized depth. -pub(super) fn depth_bytes(format: Format) -> Option { - match format { - Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT => Some(4), - Format::D16_UNORM | Format::D16_UNORM_S8_UINT => Some(2), - _ => None, - } -} - -/// The unit a depth or stencil texture of `pf` over a plane of a surface with planes keeps in -/// the plane, which its blits with a buffer and its shadow's copies move (`linear_plan.rs`): its -/// depth where the format has one (`Depth16Unorm`'s 2 bytes, a 32-bit float depth's 4), else its -/// stencil (a byte), as Metal's GPU lays them in the plane (an M4 under macOS 27.0.1). `None` for a -/// format of neither aspect or of a 24-bit depth. -pub(super) fn surface_depth_unit(pf: PixelFormat) -> Option { - let held = aspects(pf)?; - let (aspect, bytes) = match pf { - PixelFormat::Depth16Unorm => (ImageAspectFlags::DEPTH, 2), - PixelFormat::Depth32Float | PixelFormat::Depth32FloatStencil8 => { - (ImageAspectFlags::DEPTH, 4) - } - _ if held == ImageAspectFlags::STENCIL => (ImageAspectFlags::STENCIL, 1), - _ => return None, - }; - Some(CopyUnit { - bytes, - extent: [1, 1], - aspect, - }) -} - -/// Metal's copy unit of a texture of `pf`, a format that is not depth or stencil, with any blit -/// option (plain Metal ignores one): its texel block, whatever holds it (an image, or a buffer's -/// bytes for a texture buffer). Refused as [`copy_unit`] refuses it. -pub(super) fn colour_unit(pf: PixelFormat) -> Result { - let bytes = block_bytes(pf).ok_or(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - ))?; - Ok(CopyUnit { - bytes, - extent: block_extent(pf).unwrap_or([1, 1]), - aspect: ImageAspectFlags::COLOR, - }) -} - -/// Metal's copy unit of a texture of `pf` held as `mapping`, copied with `option`: plain -/// Metal's aspect, the stencil where the option names it and the format has one, else the depth -/// where the format has one, else the stencil. -/// -/// Refusals: `NotImplemented(Format)` for depth whose Metal bytes Vulkan's buffer layout of the -/// image does not give (24-bit depth). -pub(super) fn copy_unit( - pf: PixelFormat, - mapping: &FormatMapping, - option: BlitOption, -) -> Result { - if !is_depth_stencil(pf) { - return colour_unit(pf); - } - // A depth format's texels lie in its depth and stencil aspects, never in colour. - if mapping.aspects == ImageAspectFlags::COLOR { - return Err(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - )); - } - // The stencil view of a combined depth/stencil texture (`X32Stencil8` of - // `Depth32FloatStencil8`) copies the stencil of the image it shares, a byte a texel, whatever - // the option: plain Metal's answer on an M3 Max and an M4 (a probe; their API validation stops - // `DepthFromDepthStencil`). - let both = ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL; - if aspects(pf) == Some(ImageAspectFlags::STENCIL) && mapping.aspects.contains(both) { - return Ok(CopyUnit { - bytes: 1, - extent: [1, 1], - aspect: ImageAspectFlags::STENCIL, - }); - } - // Plain Metal's aspect (an M4 under macOS 27.0.1; its validation stops - // all but the named aspect of a combined format): a combined format without an option copies - // its depth, and an option naming an aspect the format lacks is ignored. - let has = |a: ImageAspectFlags| mapping.aspects.contains(a); - let aspect = match option { - BlitOption::StencilFromDepthStencil if has(ImageAspectFlags::STENCIL) => { - ImageAspectFlags::STENCIL - } - _ if has(ImageAspectFlags::DEPTH) => ImageAspectFlags::DEPTH, - _ => ImageAspectFlags::STENCIL, - }; - let bytes = if aspect == ImageAspectFlags::STENCIL { - 1 - } else { - // Metal's depth bytes are its format's (Depth16Unorm 2, 32-bit float depth 4); the image - // must hold that depth for Vulkan to copy the same bytes. - let metal = match pf { - PixelFormat::Depth16Unorm => Some(2), - PixelFormat::Depth32Float | PixelFormat::Depth32FloatStencil8 => Some(4), - _ => None, - }; - match (metal, depth_bytes(mapping.format)) { - (Some(m), Some(v)) if m == v => m, - _ => { - return Err(CopyRefusal::Unsupported( - Unsupported::not_implemented(Feature::Format).naming_format(pf), - )) - } - } - }; - Ok(CopyUnit { - bytes, - extent: [1, 1], - aspect, - }) -} - -/// A region of one level and slice of a texture, in the texture's own levels and slices -/// (`MTLRegion` with a level and slice). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct TextureRegion { - pub(super) level: u32, - pub(super) slice: u32, - pub(super) origin: [u32; 3], - pub(super) size: [u32; 3], -} - -/// A checked region in the image's levels and layers. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) struct ImageRegion { - pub(super) aspect: ImageAspectFlags, - pub(super) level: u32, - pub(super) layer: u32, - pub(super) layers: u32, - pub(super) origin: [u32; 3], - pub(super) size: [u32; 3], -} - -/// The extent of the record's `level` (counted from its first). -pub(super) fn level_extent(record: &ViewRecord, level: u32) -> [u32; 3] { - let e = record.extent(); - let mut out = e.map(|axis| (axis >> level.min(31)).max(1)); - if record.texture_type != TextureType::Type3D { - out[2] = 1; - } - out -} - -/// Metal's checks of `region` of a texture presenting `record`, copied in units of `unit`; the -/// region in the image's levels and layers, as the blocks it starts in. -/// -/// A compressed region off its blocks is copied as plain Metal copies it (an M4 under macOS -/// 27.0.1; its validation stops it): the origin rounded down to its block and -/// the size rounded up to whole blocks, each on its own (an origin of 5 and a size of 4 copy the -/// one block from 4), ending at the level's edge where the blocks pass it. The region's blocks, and -/// so its buffer layout ([`shape`]), are the same. -/// -/// A compressed region is bounded by the level's blocks, not its texels: a level that ends inside -/// a block holds that whole block, and a region of it past the level's texels (4 x 4 of a 4 x 2 -/// level, or 4 x 2 from y = 2) copies the block, ending at the level's edge, as plain Metal copies -/// it (an Apple M3 Max under macOS 26.7, a probe; Metal's validation takes a whole block of such a -/// level out of a texture, between textures and of the CPU). Its blocks, and so its buffer layout, -/// are the whole block's. Vulkan bounds a copy by the level's texels, hence the edge; between two -/// textures where only one region ends at its level's edge inside a block, the two regions differ -/// in size and cover the same blocks (`blit_texture.rs` copies them through a buffer). -pub(super) fn check_region( - record: &ViewRecord, - region: &TextureRegion, - unit: &CopyUnit, -) -> Result { - if region.level >= record.level_count || region.slice >= record.layer_count { - return Err(CopyProblem::Region); - } - let extent = level_extent(record, region.level); - let block = [unit.extent[0], unit.extent[1], 1]; - let blocks = [0, 1, 2].map(|axis| extent[axis].div_ceil(block[axis]) * block[axis]); - let axes = || region.origin.iter().zip(®ion.size).zip(&blocks); - if axes().any(|((&o, &s), &b)| u64::from(o) + u64::from(s) > u64::from(b)) { - return Err(CopyProblem::Region); - } - let (mut origin, mut size) = (region.origin, region.size); - for axis in 0..2 { - let b = block[axis]; - origin[axis] -= origin[axis] % b; - // Only an empty region starts past the level's edge (at the blocks' end). - size[axis] = (size[axis].div_ceil(b) * b).min(extent[axis].saturating_sub(origin[axis])); - } - Ok(ImageRegion { - aspect: unit.aspect, - level: record.base_level + region.level, - layer: record.base_layer + region.slice, - layers: 1, - origin, - size, - }) -} - -/// The rows and images of a region, in copy units. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct Shape { - pub(super) row_bytes: u64, - pub(super) rows: u64, - pub(super) images: u64, -} - -pub(super) fn shape(size: [u32; 3], unit: &CopyUnit) -> Shape { - let blocks = |texels: u32, block: u32| u64::from(texels.div_ceil(block)); - Shape { - row_bytes: blocks(size[0], unit.extent[0]) * u64::from(unit.bytes), - rows: blocks(size[1], unit.extent[1]), - images: u64::from(size[2]), - } -} - -/// A host buffer's layout for `replaceRegion` and `getBytes`, against the tightly packed staging -/// layout the runtime copies through. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct HostLayout { - pub(super) row_bytes: u64, - pub(super) rows: u64, - pub(super) images: u64, - pub(super) bytes_per_row: u64, - pub(super) bytes_per_image: u64, -} - -impl HostLayout { - /// The bytes of the tightly packed staging layout. - pub(super) fn packed_len(&self) -> u64 { - self.row_bytes * self.rows * self.images - } - - /// The tightly packed layout of the same rows and images: host bytes - /// [`pack`](Self::pack) wrote, read as the host buffer. - pub(super) fn packed(&self) -> HostLayout { - HostLayout { - bytes_per_row: self.row_bytes, - bytes_per_image: self.row_bytes * self.rows, - ..*self - } - } - - /// Whether the host buffer's layout is the tightly packed one: each row at its packed - /// offset, so the packed bytes are the host buffer's first [`packed_len`](Self::packed_len), - /// and a copy may read or write them in place. - pub(super) fn is_packed(&self) -> bool { - (self.rows <= 1 || self.bytes_per_row == self.row_bytes) - && (self.images <= 1 || self.bytes_per_image == self.row_bytes * self.rows) - } - - /// The bytes of the host buffer the layout reads or writes; `None` past `u64::MAX`, more - /// than any buffer holds. Rows lie in order, so the last ends past every other: a host buffer - /// of these bytes holds every row [`rows`](Self::rows) gives. - pub(super) fn host_len(&self) -> Option { - if self.row_bytes == 0 || self.rows == 0 || self.images == 0 { - return Some(0); - } - let images = (self.images - 1).checked_mul(self.bytes_per_image)?; - let rows = (self.rows - 1).checked_mul(self.bytes_per_row)?; - images.checked_add(rows)?.checked_add(self.row_bytes) - } - - /// Each row: its offset in the host buffer and in the packed layout, of a layout whose - /// [`host_len`](Self::host_len) a host buffer holds. - pub(super) fn rows(&self) -> impl Iterator + '_ { - (0..self.images).flat_map(move |z| { - (0..self.rows).map(move |y| { - ( - (z * self.bytes_per_image + y * self.bytes_per_row) as usize, - ((z * self.rows + y) * self.row_bytes) as usize, - ) - }) - }) - } - - /// Packs the host bytes `host` (at least [`host_len`](Self::host_len)) into `packed` (at - /// least [`packed_len`](Self::packed_len)). - pub(super) fn pack(&self, host: &[u8], packed: &mut [u8]) { - let n = self.row_bytes as usize; - for (h, p) in self.rows() { - packed[p..p + n].copy_from_slice(&host[h..h + n]); - } - } - - /// [`pack`](Self::pack) from bytes at a pointer (at least [`host_len`](Self::host_len)), - /// each row read once, straight into `packed`. - pub(super) fn pack_from(&self, host: HostBytes<'_>, packed: &mut [u8]) { - let n = self.row_bytes as usize; - for (h, p) in self.rows() { - host.copy_into(h, &mut packed[p..p + n]); - } - } - - /// Whether the host bytes `host` of 32-bit float texels (a depth's) hold a nonzero - /// denormal in a row. - pub(super) fn holds_denormal(&self, host: &[u8]) -> bool { - let n = self.row_bytes as usize; - self.rows().any(|(h, _)| { - host[h..h + n].as_chunks::<4>().0.iter().any(|word| { - let bits = u32::from_le_bytes([word[0], word[1], word[2], word[3]]); - bits & 0x7f80_0000 == 0 && bits & 0x007f_ffff != 0 - }) - }) - } - - /// Whether the host bytes `host` of 32-bit float texels (a depth's) hold a negative value other - /// than a zero or a denormal, or a NaN of either sign, in a row. - pub(super) fn holds_negative_or_nan(&self, host: &[u8]) -> bool { - let n = self.row_bytes as usize; - self.rows().any(|(h, _)| { - host[h..h + n].as_chunks::<4>().0.iter().any(|word| { - let bits = u32::from_le_bytes(*word); - let exponent = bits & 0x7f80_0000; - let nan = exponent == 0x7f80_0000 && bits & 0x007f_ffff != 0; - nan || (bits & 0x8000_0000 != 0 && exponent != 0) - }) - }) - } - - /// Unpacks `packed` into the host bytes `host`, leaving the bytes between rows untouched; - /// rows that overlap are written in order, image by image and row by row, so the later - /// row's bytes stay. - pub(super) fn unpack(&self, packed: &[u8], host: &mut [u8]) { - let n = self.row_bytes as usize; - for (h, p) in self.rows() { - host[h..h + n].copy_from_slice(&packed[p..p + n]); - } - } -} - -/// The plan of `replaceRegion` or `getBytes` of `region` of a texture presenting `record`, in -/// units of `unit`, with the host's `bytes_per_row` and `bytes_per_image`; `private` for a -/// texture in private storage, `over_buffer` for a texture over a buffer. `None`: the call -/// copies nothing. -/// -/// A `bytes_per_row` off Metal's rules is the host's pitch as plain Metal takes it (an M4 under -/// macOS 27.0.1; its validation stops it): any pitch of a row or more exactly, off the copy unit -/// too; 0, every row at the image's first byte (`replaceRegion` reads each row there, `getBytes` -/// writes each there in order, so the last row stays); between 0 and a row, nothing copied, -/// whatever the rows (the AGX driver logs a failed assertion and goes on). Refused (`BytesPerRow`, -/// not measured): a pitch off Metal's rules of a texture over a buffer, and a pitch of 0 for a -/// region of more than one row and more than one image. -/// -/// `bytes_per_image` is taken as plain Metal takes it (an M4 under macOS 27.0.1; its validation -/// stops all but a multiple of the copy unit that covers the region's -/// rows): a region of one image ignores it; the images of a region of more than one are exactly -/// `bytes_per_image` apart, off the copy unit and below an image too, and `getBytes` writes them in -/// order, a later image's bytes over an earlier one's ([`HostLayout::unpack`]). -pub(super) fn plan_host_copy( - record: &ViewRecord, - region: &TextureRegion, - unit: &CopyUnit, - bytes_per_row: u64, - bytes_per_image: u64, - private: bool, - over_buffer: bool, -) -> Result, CopyProblem> { - if private { - return Err(CopyProblem::CpuAccessPrivate); - } - let image = check_region(record, region, unit)?; - let s = shape(region.size, unit); - let bytes = u64::from(unit.bytes); - let below_row = bytes_per_row < s.row_bytes; - let metal_rules = bytes_per_row.is_multiple_of(bytes) && !(s.rows > 1 && below_row); - if !metal_rules && (over_buffer || (bytes_per_row == 0 && s.images > 1)) { - return Err(CopyProblem::BytesPerRow); - } - if !over_buffer && bytes_per_row != 0 && below_row { - return Ok(None); - } - Ok(Some(( - image, - HostLayout { - row_bytes: s.row_bytes, - rows: s.rows, - images: s.images, - bytes_per_row, - bytes_per_image, - }, - ))) -} diff --git a/crates/metal2vulkan-runtime/src/copy_run.rs b/crates/metal2vulkan-runtime/src/copy_run.rs deleted file mode 100644 index bf1f098cd..000000000 --- a/crates/metal2vulkan-runtime/src/copy_run.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! A blit encoder's run of buffer copies recorded as one `vkCmdCopyBuffer` -//! (`BlitCommandEncoder::copy_from_buffer_to_buffer`). -//! -//! - **Which copies join.** A copy between the same two `VkBuffer`s as the run's, which the -//! encoder's order needs no barrier after (`EncoderCore::copy_joining`): no copy of the run -//! wrote what it reads or reads or writes what it writes, per resource and range, untracked -//! resources' too (a blit's uses name every byte it touches, `tracker.rs`). The run's regions -//! then touch no byte both as a source and as a destination -//! (`VUID-vkCmdCopyBuffer-pRegions-00117`), and no two of them write one byte, so their order -//! inside the command is no order Metal sees. A program that copies tiles side by side, one copy -//! per row, makes one `vkCmdCopyBuffer` of all of them. -//! - **What ends a run.** Any other command of the encoder, a barrier, a copy between other -//! buffers, and the encoder's end: the run records first, in the `VkCommandBuffer` its first copy -//! would have recorded into, so every command keeps its place in encoded order. -//! - **Where a run breaks.** The encoder's order keeps at most eight ranges of a resource, then -//! merges them into one span, from the lowest byte of any to the highest -//! (`tracker::ENTRIES_PER_KEY`). A copy whose destination lies inside that span of the earlier -//! writes, though it meets none of them, takes a barrier there and starts a new run; so does one -//! whose source lies inside it where both are one buffer's. Copies whose destination offsets rise -//! from one copy to the next (a picture's rows in order, tile beside tile) join whole: sort them -//! by destination offset to merge them all. -//! - **Counted.** Each copy that joined a run as another region -//! (`WorkCounts::buffer_copies_merged`). - -use crate::device::functions::Vk; -use crate::work_counts::Counters; -use ash::vk; - -/// A run of copies from one `VkBuffer` into another, recorded as one `vkCmdCopyBuffer` (the -/// module docs). -pub(crate) struct CopyRun { - /// The `VkCommandBuffer` its first copy took, which records it. - raw: vk::CommandBuffer, - source: vk::Buffer, - destination: vk::Buffer, - regions: Vec, -} - -impl CopyRun { - /// A run of `region` of `source` into `destination`, to record into `raw`. - pub(crate) fn new( - raw: vk::CommandBuffer, - (source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy), - ) -> CopyRun { - CopyRun { - raw, - source, - destination, - regions: vec![region], - } - } - - /// Join `copy` to the run where it copies between its two buffers and records into `raw`, the - /// run's own: whether it joined. - pub(crate) fn join( - &mut self, - raw: vk::CommandBuffer, - (source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy), - ) -> bool { - let joins = self.raw == raw && self.source == source && self.destination == destination; - if joins { - self.regions.push(region); - } - joins - } - - /// Record the run: one `vkCmdCopyBuffer` of its regions, each past the first counted. - /// - /// # Safety - /// - /// The run's command buffer is recording, outside a render pass, and nothing was recorded - /// into it since the run's first copy; both buffers live until it completes, and every - /// region lies inside both. - pub(crate) unsafe fn record(self, device: &Vk, counts: &Counters) { - // SAFETY: the caller's contract; the regions touch no byte as both a source and a - // destination (the module docs). - unsafe { - device.cmd_copy_buffer(self.raw, self.source, self.destination, &self.regions); - } - counts.buffer_copies_merged(self.regions.len() as u64 - 1); - } -} diff --git a/crates/metal2vulkan-runtime/src/creation.rs b/crates/metal2vulkan-runtime/src/creation.rs deleted file mode 100644 index 96be06ab7..000000000 --- a/crates/metal2vulkan-runtime/src/creation.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! The runtime's one door to `vkCreateImage`, `vkCreateRenderPass`, `vkCreateRenderPass2` and -//! `vkCreateFramebuffer`, so their entry points stay in the exit guard's tables; and to the other -//! makings a driver charges for — `vkCreateBuffer`, `vkCreateImageView`, `vkAllocateMemory`, -//! `vkBindImageMemory` and `vkBindBufferMemory` — so each counts itself where it is called. -//! -//! Each is made where it is first needed: on the program's thread, in a section of the device's -//! lowering thread, which lowers render encoders' calls (`render/lowering_worker.rs`), or in a host -//! step (`exit_guard::host_step`) on the steps' thread (`scheduler/steps.rs`), an object no earlier -//! settle made (a -//! state made after its command buffer's commit, whose run needs an attachment's stand-in, a -//! shadow, or a pass and framebuffer of its own shape). So the four, and an image's memory -//! requirements and binding, are in the guard's table (`exit_guard::Call`) and among the calls a -//! host step makes (`exit_guard::HOST_STEP`). The device's priming (`device/prime.rs`) makes its -//! own, on the thread that makes the device. No other file calls these entry points: a source test -//! fails when one does (`tests/exit_guard.rs`). -//! -//! **Each making is counted at its caller's place** (`churn_counts.rs`, as the releases are), so -//! what one call of the API made the driver do is a count of that call's own work rather than an -//! inference from a separately timed driver floor: a 256x256 texture's `vkCreateImage` and its -//! binding, a buffer's `vkCreateBuffer` and whether its memory came from a pool or a fresh -//! `vkAllocateMemory`. A count is deterministic, so a test can hold a call to it where a time -//! cannot. - -use crate::allocations; -use crate::churn_counts::{vk_made, VkMaking}; -use crate::error::{vulkan, Error}; -use ash::prelude::VkResult; -use ash::vk; -use std::panic::Location; - -/// A `VkImage` of `info`, made by `device`. -/// -/// # Safety -/// -/// As `vkCreateImage`'s: `device` is live, and `info` and its chain are valid for it. -#[track_caller] -pub(crate) unsafe fn image( - device: &ash::Device, - info: &vk::ImageCreateInfo<'_>, -) -> Result { - vk_made(VkMaking::Image, Location::caller()); - // SAFETY: the caller's. - unsafe { device.create_image(info, None) }.map_err(vulkan) -} - -/// A `VkImage` of `info`, made by `device`, or the driver's refusal of it: an image whose making -/// the driver may refuse for its parameters alone (one of a DRM format modifier's explicit -/// layout, `dma_buf.rs`), whose caller takes another way then. A lost device is -/// `Error::DeviceLost`. -/// -/// # Safety -/// -/// As `vkCreateImage`'s: `device` is live, and `info` and its chain are valid for it. -#[track_caller] -#[cfg(unix)] -pub(crate) unsafe fn image_or_refusal( - device: &ash::Device, - info: &vk::ImageCreateInfo<'_>, -) -> Result, Error> { - vk_made(VkMaking::Image, Location::caller()); - // SAFETY: the caller's. - match unsafe { device.create_image(info, None) } { - Ok(raw) => Ok(Ok(raw)), - Err(vk::Result::ERROR_DEVICE_LOST) => Err(Error::DeviceLost), - Err(refusal) => Ok(Err(refusal)), - } -} - -/// A `VkBuffer` of `info`, made by `device`, with the driver's result as it gave it: the callers -/// read a refusal differently (a staging buffer's caller takes another way, a program's buffer -/// turns it into `Error`). -/// -/// # Safety -/// -/// As `vkCreateBuffer`'s: `device` is live, and `info` and its chain are valid for it. -#[track_caller] -pub(crate) unsafe fn buffer( - device: &ash::Device, - info: &vk::BufferCreateInfo<'_>, -) -> VkResult { - vk_made(VkMaking::Buffer, Location::caller()); - // SAFETY: the caller's. - unsafe { device.create_buffer(info, None) } -} - -/// A `VkImageView` of `info`, made by `device`. -/// -/// # Safety -/// -/// As `vkCreateImageView`'s: `device` is live, and `info` and its chain are valid for it. -#[track_caller] -pub(crate) unsafe fn image_view( - device: &ash::Device, - info: &vk::ImageViewCreateInfo<'_>, -) -> VkResult { - vk_made(VkMaking::ImageView, Location::caller()); - // SAFETY: the caller's. - unsafe { device.create_image_view(info, None) } -} - -/// `VkDeviceMemory` of `info`, allocated by `device`: one call of `vkAllocateMemory`, counted -/// whether or not the driver gave it, because a caller that tries memory types in turn pays for -/// each try. Refused (`ERROR_TOO_MANY_OBJECTS`) with no call where the device has -/// `maxMemoryAllocationCount` allocations live (`allocations.rs`). The call is the device's work -/// in progress for its checks to step aside for (`step_aside.rs`). -/// -/// # Safety -/// -/// As `vkAllocateMemory`'s: `device` is live, and `info` and its chain are valid for it and live -/// for the call. -#[track_caller] -pub(crate) unsafe fn allocate_memory( - device: &ash::Device, - info: &vk::MemoryAllocateInfo<'_>, -) -> VkResult { - let Some(admitted) = allocations::before_allocation(device.handle()) else { - return Err(vk::Result::ERROR_TOO_MANY_OBJECTS); - }; - vk_made(VkMaking::Memory, Location::caller()); - let busy = allocations::Busy::of(admitted.as_deref()); - // SAFETY: the caller's. - let memory = unsafe { device.allocate_memory(info, None) }; - drop(busy); - allocations::allocated(admitted, memory.is_ok()); - memory -} - -/// `image` bound to `memory` at `offset`. -/// -/// # Safety -/// -/// As `vkBindImageMemory`'s: `device` is live, `image` is its unbound image, and `memory` is its -/// memory of a type the image takes, long enough for it from `offset`. -#[track_caller] -pub(crate) unsafe fn bind_image( - device: &ash::Device, - image: vk::Image, - memory: vk::DeviceMemory, - offset: vk::DeviceSize, -) -> VkResult<()> { - vk_made(VkMaking::ImageBinding, Location::caller()); - // SAFETY: the caller's. - unsafe { device.bind_image_memory(image, memory, offset) } -} - -/// `buffer` bound to `memory` at `offset`. -/// -/// # Safety -/// -/// As `vkBindBufferMemory`'s: `device` is live, `buffer` is its unbound buffer, and `memory` is -/// its memory of a type the buffer takes, long enough for it from `offset`. -#[track_caller] -pub(crate) unsafe fn bind_buffer( - device: &ash::Device, - buffer: vk::Buffer, - memory: vk::DeviceMemory, - offset: vk::DeviceSize, -) -> VkResult<()> { - vk_made(VkMaking::BufferBinding, Location::caller()); - // SAFETY: the caller's. - unsafe { device.bind_buffer_memory(buffer, memory, offset) } -} - -/// A `VkRenderPass` of `info`, made by `device`. -/// -/// # Safety -/// -/// As `vkCreateRenderPass`'s: `device` is live, and `info` and its chain are valid for it. -pub(crate) unsafe fn render_pass( - device: &ash::Device, - info: &vk::RenderPassCreateInfo<'_>, -) -> Result { - // SAFETY: the caller's. - unsafe { device.create_render_pass(info, None) }.map_err(vulkan) -} - -/// A `VkRenderPass` of `info` (`vkCreateRenderPass2`), made by `device`. -/// -/// # Safety -/// -/// As `vkCreateRenderPass2`'s: `device` is live and of Vulkan 1.2 or later, and `info` and its -/// chain are valid for it. -pub(crate) unsafe fn render_pass2( - device: &ash::Device, - info: &vk::RenderPassCreateInfo2<'_>, -) -> Result { - // SAFETY: the caller's. - unsafe { device.create_render_pass2(info, None) }.map_err(vulkan) -} - -/// A `VkFramebuffer` of `info`, made by `device`. -/// -/// # Safety -/// -/// As `vkCreateFramebuffer`'s: `device` is live, and `info` and its chain are valid for it. -pub(crate) unsafe fn framebuffer( - device: &ash::Device, - info: &vk::FramebufferCreateInfo<'_>, -) -> Result { - // SAFETY: the caller's. - unsafe { device.create_framebuffer(info, None) }.map_err(vulkan) -} diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs deleted file mode 100644 index f50b3f7b6..000000000 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ /dev/null @@ -1,990 +0,0 @@ -//! The work an encoder leaves to record later: what one segment of it records (`encoder.rs`). Each -//! kind states what `commit` makes of it, whether the GPU may write what it reads (so a host step -//! records it once the work before it completed, `scheduler`), how that step records it, and what -//! the device announces for the step. The command buffer handles every kind alike -//! (`command_buffer`). - -use super::command_buffer::rerun::LoopCheck; -use super::command_buffer::CommandBuffer; -use super::commit_times::{self, Phase}; -use super::device::lock; -use super::encoder::RecordedSegment; -use super::error::{internal, Error}; -use super::gpu_execute::{self, Rerecord}; -use super::host_ram::copy::{StagedGather, StagedScatter}; -use super::indirect_dispatch::ArgumentDispatch; -use super::indirect_execute::{self, Execute, Settled, Unforeseen}; -use super::pass_runs::RunMerge; -use super::pending_dispatch::PendingDispatch; -use super::pipeline::ComputePipelineState; -use super::render::DeferredPass; -use super::resource::ResourceKey; -use super::shadow::GatedCopyIn; -use super::shadow_splice::ShadowSplices; -use super::sparse::emulated::Scrub; -use super::tracker::{EncoderUses, Summary, Use}; -use super::Device; -use super::IndirectCommandBuffer; -use crate::pipeline::budget::Urgency; -use std::any::Any; -use std::sync::Arc; - -/// Work an encoder left to record later: one segment's. -#[derive(Clone)] -pub(super) enum Deferred { - /// An indirect command buffer's execution (`indirect_execute.rs`). - Execute(Arc), - /// An indirect dispatch, whose arguments the GPU may write (`indirect_dispatch.rs`). - Dispatch(Arc), - /// The scrub of a blit's or a render pass's writes of a sparse texture the runtime zeroes - /// (`sparse/emulated.rs`): neither `commit` nor a host step records it, but its batch's - /// submission, with the mappings the batch applied. - SparseScrub(Arc), - /// A shadow's copy in over host pages a consumer logs, whose regions the log decides: as with - /// a scrub, neither `commit` nor a host step records it, but its batch's submission, once the - /// commit's stamp is published (`shadow::GatedCopyIn`, `dirty_pages.rs`). - GatedCopyIn(Arc), - /// The merge of a run's pass over a linear attachment rendered apart, or over a shadowed - /// texture merged back (`pass_runs.rs`): as with a scrub, neither `commit` nor a host step - /// records it, but its batch's submission, unless a later pass of the run took it over. - RunMerge(Arc), - /// A render pass that executes render commands (`render/executions.rs`). - RenderPass(Arc), - /// A compute encoder's dispatch whose pipelines were being made (`pending_dispatch.rs`). - Pending(Arc), - /// The check after a predicated loop's laying, which runs it again while the loop would run - /// on (`command_buffer/rerun.rs`): it records nothing, and its batch waits for it. - Loop(Arc), - /// A gather from a guest RAM staged through the CPU (`host_ram/copy.rs`, - /// [`StagedGather::stage`]): its batch's host step takes the staging, fills it by the CPU and - /// records the GPU's copy from it, so the staging's memory is not made on the encoding thread; - /// it waits for the work before it only where the GPU may write the pages it reads. - GatherStage(Arc), - /// A scatter into a guest RAM staged through the CPU, its GPU's copy into the staging - /// (`host_ram/copy.rs`, [`StagedScatter::stage`]): its batch's host step records it, waiting - /// for no work on the GPU, so the staging's memory is not made on the encoding thread. - ScatterStage(Arc), - /// The same scatter's CPU copy from the staging into the pages - /// ([`StagedScatter::drain`]): the host step of a batch of its own records nothing, once the - /// work before it completed. - ScatterDrain(Arc), - /// The CPU's part of an encoder's copies back spliced and merges on the host at one place - /// (`shadow_splice.rs`, [`ShadowSplices::drain`]): its texels' bytes in lines the GPU's - /// copies left, copied from the arena into the pages, and the bytes its merges' commands - /// changed, stored there, by the host step of a batch of its own, which records nothing, - /// once the work before it completed. - ShadowSplice(Arc), -} - -// SAFETY: a `Deferred` holds one `Arc` of its variant's work, which is `Send` and `Sync` for every -// work that is both; the constant below makes the compiler prove that of each variant's work, its -// match naming every variant (one added fails it until its work is proved too), so these impls -// claim nothing it does not check. Written out, they end the compiler's walk of a segment's work -// where a program's crate proves its own objects' `Send` and `Sync`: the walk from an encoder's -// segments down the work's types runs past rustc's default recursion limit -// (`recursion_depth_exceeding_limit`), which a program's crate keeps -// (`tests/consumer_auto_traits.rs`). -unsafe impl Send for Deferred {} -// SAFETY: as for `Send` above. -unsafe impl Sync for Deferred {} - -// The compiler's proof of what `Deferred`'s `Send` and `Sync` impls rest on: each variant's work. -const _: fn(&Deferred) = |work| { - fn shared(_: &T) {} - match work { - Deferred::Execute(work) => shared(work), - Deferred::Dispatch(work) => shared(work), - Deferred::SparseScrub(work) => shared(work), - Deferred::GatedCopyIn(work) => shared(work), - Deferred::RunMerge(work) => shared(work), - Deferred::RenderPass(work) => shared(work), - Deferred::Pending(work) => shared(work), - Deferred::Loop(work) => shared(work), - Deferred::GatherStage(work) => shared(work), - Deferred::ScatterStage(work) => shared(work), - Deferred::ScatterDrain(work) => shared(work), - Deferred::ShadowSplice(work) => shared(work), - } -}; - -/// What `commit` left a segment for its host step. -#[derive(Clone)] -pub(super) enum StepInputs { - /// An execution's: the pipeline states its records may name, as `commit` settled them. - Settled(Vec), - /// An execution `commit` recorded from the CPU's records, which its buffer watches for a host - /// step `commit` did not foresee (`indirect_execute::Unforeseen`). - Unforeseen(Arc), - /// An indirect dispatch's: nothing past the work itself, which holds the encoder's tables. - /// And a dispatch's whose pipelines were being made, which holds its recording. - Dispatch, - /// A scrub's: none, as it has no host step. - None, - /// A render pass's: nothing past the pass itself, which holds the encoder's state at each - /// execution; its step names states among those alive then, and compiles only what `commit` - /// could not settle (`DeferredPass::settle`). - RenderPass, - /// A loop's check: nothing past the check itself. - Loop, - /// A staged gather's or scatter's copies: nothing past the work itself. - Staged, - /// An execution `commit` recorded on the GPU alone with no barrier between its commands, which - /// its batch's submission records again with them where a route encoded since may set a - /// barrier in a record (`gpu_execute::Rerecord`); no work on the GPU is waited for. - Rerecord(Arc), -} - -impl StepInputs { - /// Whether the segment's recording must be made again before its batch is submitted, though - /// a recording is in place: [`Rerecord::due`]. - pub(super) fn rerecords(&self) -> bool { - matches!(self, StepInputs::Rerecord(rerecord) if rerecord.due()) - } -} - -/// What `commit` made of a segment's work ([`Deferred::prepare`]). -pub(super) struct Prepared { - /// Its recording, where `commit` recorded it. - pub(super) recorded: Option, - /// `commit` recorded it for good, though the GPU may write what it reads: it runs on the GPU - /// alone (`gpu_execute.rs`, `render/executions/gpu.rs`), and no host step records it. - pub(super) for_good: bool, - /// What its host step needs. - pub(super) inputs: StepInputs, - /// What the command buffer holds until it completes. - pub(super) retained: Option>, - /// `commit` left its recording to a host step for the pipelines it records, being made (or - /// failed) then (`render/pending.rs`). - pub(super) pipelines: bool, - /// Where its host step records it for what the GPU may write, what the step's recording may - /// use that Metal orders (`Segment::bound`). - pub(super) bound: Option>, - /// `commit`'s recording of it was refused, though a route met later may write the records it - /// read first ([`Deferred::prepare`]): its host step records it once the work before it - /// completed (`Segment::host`). - pub(super) held: bool, -} - -/// Whether `commit`'s refused recording of an execution of `executed`, buffers read from the CPU's -/// records, is held for its host step: where its command buffer made one of them resident for -/// writing (`residency`, its), as a route met after the commit may still write the records before -/// the work runs (another queue's command buffer it waits for through an event, encoded after this -/// commit: the probe `crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m`), and Metal -/// runs what that route wrote. The step records the work from the records as they stand once the -/// work before it completed, and fails the command buffer, at the batch's submission, only where -/// they are still refused (`WorkCounts::commit_refusals_held`). A refusal of another buffer's -/// records stands at `commit`. -fn held<'a>( - residency: &crate::residency::Residency, - executed: impl IntoIterator, -) -> bool { - let writable = residency.writable_indirect_command_buffers(); - executed.into_iter().any(|icb| writable.contains(icb)) -} - -impl Deferred { - /// Whether `self` and `other` are the same work: one segment's. - pub(super) fn same(&self, other: &Deferred) -> bool { - match (self, other) { - (Deferred::Execute(a), Deferred::Execute(b)) => Arc::ptr_eq(a, b), - (Deferred::Dispatch(a), Deferred::Dispatch(b)) => Arc::ptr_eq(a, b), - (Deferred::SparseScrub(a), Deferred::SparseScrub(b)) => Arc::ptr_eq(a, b), - (Deferred::GatedCopyIn(a), Deferred::GatedCopyIn(b)) => Arc::ptr_eq(a, b), - (Deferred::RunMerge(a), Deferred::RunMerge(b)) => Arc::ptr_eq(a, b), - (Deferred::RenderPass(a), Deferred::RenderPass(b)) => Arc::ptr_eq(a, b), - (Deferred::Pending(a), Deferred::Pending(b)) => Arc::ptr_eq(a, b), - (Deferred::Loop(a), Deferred::Loop(b)) => Arc::ptr_eq(a, b), - (Deferred::GatherStage(a), Deferred::GatherStage(b)) => Arc::ptr_eq(a, b), - (Deferred::ScatterStage(a), Deferred::ScatterStage(b)) => Arc::ptr_eq(a, b), - (Deferred::ScatterDrain(a), Deferred::ScatterDrain(b)) => Arc::ptr_eq(a, b), - (Deferred::ShadowSplice(a), Deferred::ShadowSplice(b)) => Arc::ptr_eq(a, b), - _ => false, - } - } - - /// Whether the encoder copies back its shadowed textures before the work and forgets them - /// (`EncoderCore::defer`): work recorded apart, with copies of its own. A render pass that - /// executes render commands is not: its shadowed textures are its encoder's, copied in - /// before it and back as the encoder ends (`render/shadows.rs`). - /// Nor is a dispatch whose pipelines were being made: its shadowed textures were copied in - /// at the dispatch, and its writes are its encoder's to copy back. Nor is a gated copy in, - /// which is one of the encoder's shadow copies, nor a run's merge (`pass_runs.rs`): a linear - /// attachment's touches no shadowed texture, and a shadowed texture's is the copy back its - /// encoder took out of its shadows to leave there. A staged copy's do: a gather's writes the - /// buffer, a scatter's reads it and writes the pages, after every command before them. A - /// splice's CPU part does not: it ends copies back its encoder just recorded. - pub(super) fn leaves_shadows(&self) -> bool { - match self { - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) => true, - Deferred::RenderPass(_) - | Deferred::Pending(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// Whether the GPU may write what the work reads now: a host step records it, before its - /// batch is submitted. For an execution, whether a route that may write its buffer's records - /// met it (`IndirectCommandBuffer::gpu_written`, for good), or it reads its range from a buffer - /// (`Execute::indirect`), or it lies inside a block of command predication, whose counter its - /// host step reads (`Execute::predicated`); an indirect dispatch's arguments always are GPU - /// memory the work - /// before it may write. A render pass's, whether such a route met the buffer of one of its - /// executions, or one of them reads its range from a buffer. A staged scatter's CPU copy - /// reads the staging the GPU's copy before it wrote; a staged gather's reads guest RAM pages - /// a command before it may write (`StagedGather::after_the_gpu`); a splice's CPU part reads - /// the region its copies back wrote. - pub(super) fn gpu_written(&self) -> bool { - match self { - Deferred::Execute(execute) => { - execute.icb.gpu_written() || execute.indirect() || execute.predicated() - } - Deferred::Dispatch(_) - | Deferred::Loop(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => true, - Deferred::GatherStage(gather) => gather.after_the_gpu(), - Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::ScatterStage(_) => false, - Deferred::RenderPass(pass) => pass.gpu_written(), - } - } - - /// `commit`'s work on it, with no lock of `command_buffer` held: for a segment its host step - /// records (`step`), what the step needs; else its recording. An execution its step would - /// record runs on the GPU alone instead where every record it may hold is covered - /// (`gpu_execute.rs`), recorded now for good; otherwise its step needs the states its - /// records may name and their variants ([`Execute::settle`]). An execution recorded now from - /// the CPU's records is watched by its buffer for a host step `commit` did not foresee. An - /// indirect dispatch's step needs its variants ([`ArgumentDispatch::settle`]); it is never - /// recorded before its step. A render pass is recorded now from the CPU's records, unless - /// its step records it; a pass its step would record is recorded now for good where its - /// executions run on the GPU alone (`DeferredPass::record_on_gpu`); otherwise the step's draws - /// need the variants and pipelines of the states its records may name - /// ([`DeferredPass::settle`]). - pub(super) fn prepare( - &self, - command_buffer: &CommandBuffer, - step: bool, - ) -> Result { - let device = command_buffer.device(); - match self { - Deferred::Execute(execute) if step => { - // On the GPU alone where it is total (`gpu_execute.rs`): not a checked execution - // whose check may see something, whose step reads its records for the check, nor - // one inside a block of command predication without its preprocess's gate, whose - // step reads the counter. A checked one's host step, where a route encoded since - // gives its check something to see (`Execute::outgrown`), is settled now. - if let Some((recorded, inputs)) = self.record_on_gpu(command_buffer)? { - let retained: Option> = match &execute.check { - Some(_) => { - let residency = command_buffer.residency()?.kernel(); - let Settled { states, variants } = - execute.settle(device, execute.states(device), &residency); - *lock(&execute.unchecked) = Some(states); - Some(Box::new(variants)) - } - None => None, - }; - return Ok(Prepared { - recorded: Some(recorded), - for_good: true, - inputs, - retained, - pipelines: false, - bound: None, - held: false, - }); - } - let residency = command_buffer.residency()?.kernel(); - let Settled { states, variants } = - execute.settle(device, execute.states(device), &residency); - Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Settled(states), - retained: Some(Box::new(variants)), - pipelines: false, - bound: execute.bound(&residency), - held: false, - }) - } - Deferred::Execute(execute) => { - let recorded = match execute.record(command_buffer, None) { - Ok(recorded) => recorded, - // Held for its host step (`held`). - Err(error) => { - let residency = command_buffer.residency()?; - if !held(&residency, [&execute.icb]) { - return Err(error); - } - device.shared().counts.commit_refusal_held(); - let residency = residency.kernel(); - let Settled { states, variants } = - execute.settle(device, execute.states(device), &residency); - return Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Settled(states), - retained: Some(Box::new(variants)), - pipelines: false, - bound: execute.bound(&residency), - held: true, - }); - } - }; - let residency = command_buffer.residency()?.kernel(); - let unforeseen = Unforeseen::new(device, execute, residency); - execute.icb.watch(&unforeseen); - Ok(Prepared { - recorded: Some(recorded), - for_good: false, - inputs: StepInputs::Unforeseen(unforeseen), - retained: None, - pipelines: false, - bound: None, - held: false, - }) - } - Deferred::Dispatch(dispatch) if step => Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Dispatch, - retained: Some(Box::new( - dispatch.settle(device, &command_buffer.residency()?.kernel()), - )), - pipelines: false, - bound: None, - held: false, - }), - Deferred::Dispatch(_) => Err(internal( - "an indirect dispatch recorded before the work it waits for completed", - )), - Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) => { - Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::None, - retained: None, - pipelines: false, - bound: None, - held: false, - }) - } - // Recorded now for good where every execution whose records the GPU may write runs - // on the GPU alone (`render/executions/gpu.rs`). Otherwise its step's draws compile - // what `commit` cannot foresee alone: it settles their variants and pipelines now - // (`DeferredPass::settle`), held until the command buffer completes. - // The step waits for the pipelines its draws record too (`render/pending.rs`). - // And makes now what the step would make (`render/executions/ahead.rs`). - Deferred::RenderPass(pass) if step => { - if let Some((recorded, inputs)) = self.record_on_gpu(command_buffer)? { - return Ok(Prepared { - recorded: Some(recorded), - for_good: true, - inputs, - retained: None, - pipelines: false, - bound: None, - held: false, - }); - } - pass.make_ahead(command_buffer); - Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::RenderPass, - retained: Some(Box::new(pass.settle(command_buffer))), - pipelines: pass.making() || pass.failed(), - bound: pass.bound(device, &command_buffer.residency()?), - held: false, - }) - } - // A pass of draws whose pipelines are being made, or one of which failed, is - // recorded by a host step once they are made, which drops the draw of a failed one - // (`render/pending.rs`). One whose executions read the CPU's records as they stand now - // waits for them first, until the command buffer's bound at most; so does its - // executions' replay for a making it begins itself, which leaves the pass to the host - // step past that bound (`DeferredPass::left_for_makings`). - Deferred::RenderPass(pass) => { - let left = Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::RenderPass, - retained: None, - pipelines: true, - bound: None, - held: false, - }; - if pass.reads_at_commit() { - let deadline = command_buffer.making_deadline(); - commit_times::phase(Phase::PipelineWait, || pass.wait_made(deadline)); - } - if pass.making() || pass.failed() { - return Ok(left); - } - let recorded = match pass.record(command_buffer, false) { - Ok(recorded) => recorded, - Err(_) if pass.left_for_makings(command_buffer) => return Ok(left), - // Held for its host step (`held`), as a step's pass is prepared above. - Err(error) => { - let residency = command_buffer.residency()?; - if !held(&residency, pass.executed()) { - return Err(error); - } - device.shared().counts.commit_refusal_held(); - pass.make_ahead(command_buffer); - return Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::RenderPass, - retained: Some(Box::new(pass.settle(command_buffer))), - pipelines: false, - bound: pass.bound(device, &residency), - held: true, - }); - } - }; - Ok(Prepared { - recorded: Some(recorded), - for_good: false, - inputs: StepInputs::RenderPass, - retained: None, - pipelines: false, - bound: None, - held: false, - }) - } - // Its host step reads the unit's halt word once the laying completed. - Deferred::Loop(_) => Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Loop, - retained: None, - pipelines: false, - bound: None, - held: false, - }), - // Recorded by host steps: a gather's and a scatter's GPU copy by its batch's - // (`records_at_its_step`); a scatter's CPU copy, and a splice's, which record nothing - // on the GPU, once the work before it completed. Their uses are their encoder's, noted - // at the call (`host_ram/copy.rs`, `EncoderCore::shadow_copies`): the steps' - // recordings name none of their own. - Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Staged, - retained: None, - pipelines: false, - bound: match self { - Deferred::ScatterDrain(_) | Deferred::ShadowSplice(_) => { - Some(EncoderUses::new(true).finish()) - } - _ => None, - }, - held: false, - }), - // Recorded now where its pipelines are made; else by a host step once they are, - // which makes again one whose making failed. - Deferred::Pending(dispatch) => { - let later = step || dispatch.making() || dispatch.failed(); - Ok(Prepared { - recorded: match later { - true => None, - false => Some(dispatch.record(command_buffer)?), - }, - for_good: false, - inputs: StepInputs::Dispatch, - retained: None, - pipelines: later, - bound: None, - held: false, - }) - } - } - } - - /// Whether it is a run's pass's merge (`pass_runs.rs`), which an encoding again of its pass - /// replaces with that pass's own merge (`command_buffer/reencode.rs`). - pub(super) fn joins_a_run(&self) -> bool { - matches!(self, Deferred::RunMerge(_)) - } - - /// Whether `commit` leaves its recording to its batch's host step, which waits for no work on - /// the GPU but where [`steps_after_the_gpu_now`](Self::steps_after_the_gpu_now) says: a - /// staged gather's or scatter's GPU copy, whose region of the arena that step takes, so its - /// memory is made on neither the encoding nor the committing thread (`host_ram/copy.rs`). - pub(super) fn records_at_its_step(&self) -> bool { - matches!(self, Deferred::GatherStage(_) | Deferred::ScatterStage(_)) - } - - /// Whether its host step, not yet run, waits for the work submitted before it to complete - /// though the work is not GPU-written for good ([`gpu_written`](Self::gpu_written)): a staged - /// gather's where the GPU may write the pages it reads now (`StagedGather::waits_for_the_gpu`). - pub(super) fn steps_after_the_gpu_now(&self, device: &Device) -> bool { - match self { - Deferred::GatherStage(gather) => gather.waits_for_the_gpu(device), - _ => false, - } - } - - /// What its host step reads on the host of what the GPU may write, where that is all the - /// step waits for of the work before it (`CommandBufferShared::step_reads`): an execution's - /// records and range (`ExecutionRange::host_reads`), outside a block of command predication, - /// whose counter its step reads too; a render pass's executions'. `None` for every other - /// work, whose step waits for all the work submitted before it. - pub(super) fn host_reads(&self) -> Option>> { - match self { - Deferred::Execute(execute) => execute.host_reads(), - Deferred::RenderPass(pass) => Some(pass.host_reads()), - Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => None, - } - } - - /// Whether a rebind's encoding again of its encoder records it at once in its place, leaving - /// no segment of it (`command_buffer/reencode.rs`): a staged gather, which an encoder encoded - /// again copies through the imports (`host_ram/copy.rs`), but one over a chunk that takes no - /// import or in a part of its own (`StagedGather::encoded_again_through_imports`), which it - /// stages again ([`left_again_by_an_encoding_again`](Self::left_again_by_an_encoding_again)). - /// The encoding again's parts are the first's: such a gather's segment starts none. - pub(super) fn recorded_by_an_encoding_again(&self) -> bool { - match self { - Deferred::GatherStage(gather) => gather.encoded_again_through_imports(), - _ => false, - } - } - - /// Whether a rebind's encoding again of its encoder leaves a segment of its own in its place - /// (`command_buffer/reencode.rs`): a splice's and a merge on the host's CPU part - /// (`shadow_splice.rs`), which the encoding again's copies back plan over the pages the - /// buffer lies in then and leave again, in a part as the first's (a rebind keeps the bytes' - /// offset in their page, `rebind.rs`, so the copies cut alike); a staged scatter's two - /// steps, which the encoding again stages again from where the buffer lies then, its CPU - /// copy in a part of its own as the first's; and a staged gather the imports would not copy - /// as the first staged it (over a chunk that takes no import, or in a part of its own: - /// `StagedGather::encoded_again_through_imports`), staged again so (`host_ram/copy.rs`'s - /// `HostRamCall::staged_again`); and a shadow's copy in left to its batch's submission - /// (`shadow::GatedCopyIn`), which the encoding again's copy in leaves again, gated as it - /// decides then (or records in place, where it decides to copy every texel): its gate of a - /// log, made after the commit's decisions (`DirtyShadows::committed`), holds no stamp and - /// copies every region (`CopyInGate::regions`); and a sparse texture's scrub, left for its - /// batch's submission (`sparse::emulated::Scrub`), which the blit or the pass encoded again - /// leaves again over the same texture. The first's go unrun. - pub(super) fn left_again_by_an_encoding_again(&self) -> bool { - match self { - Deferred::ShadowSplice(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::GatedCopyIn(_) - | Deferred::SparseScrub(_) => true, - Deferred::GatherStage(gather) => !gather.encoded_again_through_imports(), - _ => false, - } - } - - /// Whether a commit may record it on the GPU alone, for good - /// ([`record_on_gpu`](Self::record_on_gpu)): an execution's, or a render pass's that executes - /// render commands. - pub(super) fn may_run_on_gpu_alone(&self) -> bool { - matches!(self, Deferred::Execute(_) | Deferred::RenderPass(_)) - } - - /// Its recording on the GPU alone, for good, with what its host step needs, where it runs - /// there over the buffers as they lie now (`gpu_execute.rs`, `DeferredPass::record_on_gpu`); - /// `None` where it does not, or is work that never runs there. With no lock of - /// `command_buffer` held: at the commit, and at a rebind before the command buffer's first - /// submission, which records it again (`command_buffer/reencode.rs`). - pub(super) fn record_on_gpu( - &self, - command_buffer: &CommandBuffer, - ) -> Result, Error> { - match self { - Deferred::Execute(execute) => { - let recorded = gpu_execute::record(command_buffer, execute)?; - Ok(recorded.map(|(recorded, rerecord)| { - let inputs = match rerecord { - Some(rerecord) => StepInputs::Rerecord(rerecord), - None => StepInputs::Settled(Vec::new()), - }; - (recorded, inputs) - })) - } - Deferred::RenderPass(pass) => Ok(pass - .record_on_gpu(command_buffer)? - .map(|recorded| (recorded, StepInputs::RenderPass))), - Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => Ok(None), - } - } - - /// Its host step, on the steps' thread (`scheduler/steps.rs`) with no lock of `command_buffer` - /// held: its - /// recording from what it reads now and `inputs`. An execution's records name their states - /// among those `commit` settled, or for one `commit` recorded from the CPU's records, those - /// `use_resource` settled since. An indirect dispatch's arguments state its size. A render - /// pass's executions read their records as the GPU and the CPU left them. - pub(super) fn step( - &self, - command_buffer: &CommandBuffer, - inputs: &StepInputs, - ) -> Result { - match self { - Deferred::Execute(execute) => { - // Recorded on the GPU alone with a check a route encoded since gave something to - // see: recorded from the records as the GPU and the CPU left them, naming states - // among those `commit` settled, for good. - if let Some(states) = execute.take_outgrown() { - return execute.record(command_buffer, Some(&states)); - } - let states = match inputs { - StepInputs::Settled(states) => states.clone(), - StepInputs::Unforeseen(unforeseen) => { - unforeseen.states(command_buffer.device()) - } - // Recorded again on the GPU alone, with the barriers: no record is read. - StepInputs::Rerecord(rerecord) => { - return rerecord.record(command_buffer, execute); - } - StepInputs::Dispatch - | StepInputs::None - | StepInputs::RenderPass - | StepInputs::Loop - | StepInputs::Staged => { - return Err(internal("an execution's host step without its states")); - } - }; - // The states go after the recording, with no lock held: one may be a state's - // last handle. - execute.record(command_buffer, Some(&states)) - } - Deferred::Dispatch(dispatch) => dispatch.record(command_buffer), - Deferred::SparseScrub(_) => Err(internal("a sparse scrub's host step")), - Deferred::GatedCopyIn(_) => Err(internal("a gated copy in's host step")), - Deferred::RunMerge(_) => Err(internal("a run's merge's host step")), - Deferred::RenderPass(pass) => pass.record(command_buffer, true), - Deferred::Pending(dispatch) => dispatch.record(command_buffer), - Deferred::Loop(check) => check.step(command_buffer), - Deferred::GatherStage(gather) => gather.stage(command_buffer), - Deferred::ScatterStage(scatter) => scatter.stage(command_buffer), - Deferred::ScatterDrain(scatter) => scatter.drain(command_buffer.device()), - Deferred::ShadowSplice(splices) => Ok(splices.drain(command_buffer.device())), - } - } - - /// Whether a route encoded since `commit` recorded the work for good on the GPU may write - /// more than `commit` decided on (`DeferredPass::outgrown`), or gives the check of an - /// execution recorded there something to see (`Execute::outgrown`): its host step records it - /// instead, before its batch is submitted. A render pass's executions' GPU form, and an - /// execution's on the GPU alone with a check. - pub(super) fn outgrown(&self) -> bool { - match self { - Deferred::RenderPass(pass) => pass.outgrown(), - Deferred::Execute(execute) => execute.outgrown(), - Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// Whether `commit` recorded it from the CPU's records of an indirect command buffer the CPU - /// wrote since (`Execute::rewritten`, `DeferredPass::rewritten`): its host step records it - /// again from the records as they stand then, before its batch is submitted, waiting for no - /// work on the GPU. - pub(super) fn rewritten(&self) -> bool { - match self { - Deferred::Execute(execute) => execute.rewritten(), - Deferred::RenderPass(pass) => pass.rewritten(), - Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// Whether its batch waits for it after its host step: a loop's check while it runs the - /// laying again (`command_buffer/rerun.rs`), which wakes the scheduler as it ends. - pub(super) fn holds(&self) -> bool { - match self { - Deferred::Loop(check) => check.running(), - Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::RenderPass(_) - | Deferred::Pending(_) => false, - } - } - - /// Whether it is a render pass left for its draws' or tile dispatches' pipelines alone, made - /// since or not (`DeferredPass::left_for_pipelines`): an encoding again records those draws - /// where it finds their pipelines made, and leaves a segment of its own where they are still - /// being made, so it takes such a pass's place (`State::splice_replay`). - pub(super) fn left_for_pipelines(&self) -> bool { - match self { - Deferred::RenderPass(pass) => pass.left_for_pipelines(), - _ => false, - } - } - - /// Whether a pipeline the work records is still being made (`render/pending.rs`). - pub(super) fn making(&self) -> bool { - match self { - Deferred::RenderPass(pass) => pass.making(), - Deferred::Pending(dispatch) => dispatch.making(), - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// Whether its recording may write memory no use its command buffer noted names, so the merge - /// back of copied host buffers takes every copy as written by it (`copied.rs`): an indirect - /// command buffer's execution and a render pass that executes render commands, whose - /// commands its step resolves from records, an indirect dispatch and a scrub, which their - /// steps or submissions record. A dispatch whose pipelines were being made records the uses - /// its encoding noted, a gated copy in writes the shadow it names, a run's merge - /// the bytes its pass noted it writes, a loop's check records nothing, and a staged copy's - /// steps write the runtime's staging and the buffer or pages its call noted. - pub(super) fn reaches_unnamed(&self) -> bool { - match self { - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => true, - Deferred::RenderPass(pass) => pass.executes(), - Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// Whether a host step records it from what its calls resolved alone, nothing of the buffers - /// it names read again then: the buffers over host pages its commands used let their pages go - /// at the commit instead of keeping them until it completes (`CommandBuffer::commit`'s - /// `steps_hold`, `rebind.rs`), so a rebind of one is not refused but encodes its encoder - /// again (`command_buffer/reencode.rs`). A dispatch whose pipelines were being made records - /// what its encoding resolved (`pending_dispatch.rs`), and so does a render pass `commit` - /// left for the pipelines its draws and tile dispatches record (`pipelines`) that executes no - /// render commands, whose instances' commands its calls recorded - /// (`render/pending_tile.rs`). So does a run's merge (`pass_runs.rs`), which writes only the - /// bytes its encoder's commands named (a linear attachment's, none over host pages; a - /// shadowed texture's truth, whose uses its pass noted): a rebind of them encodes that - /// encoder again, the merge with it. So do a staged copy's steps, between the buffer its call - /// resolved (`blit_at`) and the pages it named, and a splice's and a merge on the host's CPU - /// part (`shadow_splice.rs`), which writes the pages the truth's buffer lay in at its - /// encoder's call, a shadow's gated copy in, which copies from the truth's `VkBuffer` as its - /// encoder's call found it (`shadow::GatedCopyIn`), and a sparse texture's scrub, which zeroes - /// tiles of its texture alone, as its batch mapped them, and reads no buffer - /// (`sparse::emulated::Scrub`): a rebind before the command buffer's submission encodes that - /// encoder again, its CPU part, its copy in or its scrub with it, and one after it keeps the - /// old pages until the command buffer completes (`rebind.rs`). So does a predicated loop's - /// check whose laying left no work apart (`command_buffer/rerun.rs`): its step reads only its - /// unit's halt word, in the command buffer's arena, and each run again submits the laying's - /// command buffers again as they were encoded, over the pages their first submission took, - /// which the command buffer holds until it completes. A rebind after that submission keeps - /// the old pages for every run again, as Metal's loop reads the pages its submission found; - /// one before it fails that submission (`EncodedUseRebound`, - /// `command_buffer/first_submission.rs`), as the laying's encoders keep no log to be encoded - /// again from (`predication.rs`). - /// Everything else its step resolves as it records (an execution, a dispatch left to its host - /// step, a loop's check whose laying left work apart, which each run again records again as - /// it records: a host step's work resolving the buffers its encoder named then, work on the - /// GPU alone over the buffers as they lie then): a rebind meanwhile is refused - /// (`RebindProblem::EncodedUses`), a known gap (`docs/FAST-PATHS.md`). - pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool { - match self { - Deferred::Pending(_) - | Deferred::RunMerge(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) - | Deferred::GatedCopyIn(_) - | Deferred::SparseScrub(_) => true, - Deferred::RenderPass(pass) => pipelines && !pass.executes(), - Deferred::Loop(check) => !check.leaves_work_apart(), - Deferred::Execute(_) | Deferred::Dispatch(_) => false, - } - } - - /// Whether the making of a pipeline the work records failed (`DeferredPass::failed`, - /// `PendingDispatch::failed`): a dispatch's, which its recording makes again, on the thread - /// that records it, the command buffer completing with - /// `CommandBufferError::PipelineCreation` where that fails too; a draw's, which its - /// recording drops (`render/pending.rs`). - pub(super) fn failed(&self) -> bool { - match self { - Deferred::RenderPass(pass) => pass.failed(), - Deferred::Pending(dispatch) => dispatch.failed(), - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => false, - } - } - - /// What its recording uses, on `device`, where that is known before it records - /// (`DeferredPass::known_summary`): a render pass's that executes no render commands. `None` - /// for the rest, whose uses their recording finds: an execution's or an indirect dispatch's - /// from the records and arguments it reads, a scrub's at its submission; a loop's check's are - /// its laying's (`CommandBufferShared::footprint`). A staged copy's GPU copy uses none past - /// what its call noted in its encoder's part. - pub(super) fn known_summary(&self, device: &Device) -> Option> { - match self { - Deferred::RenderPass(pass) => pass.known_summary(device), - Deferred::Pending(dispatch) => Some(dispatch.known_summary()), - Deferred::GatherStage(_) | Deferred::ScatterStage(_) => { - Some(EncoderUses::new(true).finish()) - } - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Loop(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => None, - } - } - - /// Run `waker` each time the making of a pipeline the work records finishes. - pub(super) fn when_made(&self, waker: &(impl Fn() + Clone + Send + 'static)) { - match self { - Deferred::RenderPass(pass) => pass.when_made(waker), - Deferred::Pending(dispatch) => dispatch.when_made(waker), - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => {} - } - } - - /// Run the makings of the pipelines the work records before the device's pool's pieces of a - /// lower rank than `urgency` (`pipeline/pool.rs`): its submission waits for them. - pub(super) fn hasten(&self, urgency: Urgency) { - match self { - Deferred::RenderPass(pass) => pass.hasten(urgency), - Deferred::Pending(dispatch) => dispatch.hasten(urgency), - Deferred::Execute(_) - | Deferred::Dispatch(_) - | Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => {} - } - } - - /// A weak reference to its work, which holds none of it: a device test's view of what still - /// holds the work (`tests::host_ram_copy_device`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(super) fn weak(&self) -> std::sync::Weak { - fn weak(work: &Arc) -> std::sync::Weak { - Arc::::downgrade(work) - } - match self { - Deferred::Execute(work) => weak(work), - Deferred::Dispatch(work) => weak(work), - Deferred::SparseScrub(work) => weak(work), - Deferred::GatedCopyIn(work) => weak(work), - Deferred::RunMerge(work) => weak(work), - Deferred::RenderPass(work) => weak(work), - Deferred::Pending(work) => weak(work), - Deferred::Loop(work) => weak(work), - Deferred::GatherStage(work) => weak(work), - Deferred::ScatterStage(work) => weak(work), - Deferred::ScatterDrain(work) => weak(work), - Deferred::ShadowSplice(work) => weak(work), - } - } - - /// Announce on `device`, once, that a host step records such work. - pub(super) fn degrade(&self, device: &Device) { - match self { - Deferred::Execute(execute) => indirect_execute::degrade_host_replay(device, execute), - Deferred::Dispatch(dispatch) => dispatch.degrade(device), - Deferred::SparseScrub(_) - | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) - | Deferred::Pending(_) - | Deferred::Loop(_) - | Deferred::GatherStage(_) - | Deferred::ScatterStage(_) - | Deferred::ScatterDrain(_) - | Deferred::ShadowSplice(_) => {} - Deferred::RenderPass(pass) => pass.degrade(device), - } - } -} diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs deleted file mode 100644 index d1d0a59b3..000000000 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ /dev/null @@ -1,5950 +0,0 @@ -//! Degrade notices. Where the runtime gives Metal's answer at a cost Metal does not pay (a copy, a -//! staging or scratch resource, an extra pass), gives a recorded near-equivalent of it, or gives it -//! through use of the device its driver does not advertise, it says so once per device and kind -//! ([`Degradation`]): through the device's message sink when it has one -//! (`DeviceOptions::messages`), as a warning whose `id_name` is the kind's code and whose -//! [`DebugMessage::degradation`] carries the [`DegradeNotice`]; else on stderr, the same text. -//! Nothing queries them (the user, 2026-10-05: downgrades are allowed, but each must be visible at -//! least once and decodable, without log spam). -//! -//! - **One closed vocabulary.** [`Degradation`] lists every kind once, with its code, category -//! and cost, in `degradations!`; its precision kinds include one per -//! [`PrecisionNote`] a pipeline stage records, named alike, which the macro maps both -//! ways, so a note without a kind (or two kinds of one note) does not compile. The note a -//! sampler state carries, `CappedLodBias`, maps to the runtime kind of its name, which -//! announces it where the device makes the state. `DeviceReconvergence`, which only a profile -//! `Device::from_queries` built records and so no stage of this runtime holds, maps to -//! `ImplementationDefinedReconvergence`, which this runtime announces from the stage's -//! reconvergence. docs/API.md's catalogue lists every code, closed both ways by a test. -//! - **Codes are a contract.** `metal2vulkan-degrade-`, never renamed; a new degradation is -//! a new kind. A kind that no longer fires is removed, with its code. -//! - **The payload.** The object degraded (the first one the device met), the reason (with that -//! object's numbers), and the kind's fixed cost. A consumer decodes a notice by its -//! [`Degradation`], never by parsing its text. -//! - **Once, unless the device's options ask for each.** A bit per kind and device, set by the -//! first announcement; a later occurrence costs one atomic load. A kind in -//! `DeviceOptions::announce_each` (or `RawDevice::announce_each`) is announced at every -//! occurrence instead, the same notice through the same sink, on the thread whose call announces -//! it: a bit per kind beside those, read first. `copied-host-pages` is announced once per -//! reason rather than once per kind (a consumer acts on a refused import, a failed one and a -//! move apart): a bit per reason beside them ([`Device::degrade_copied_pages`]); and -//! `host-replayed-indirect-commands` once per cause, the rule that kept a render pass from the -//! GPU form among them (a walk sees why each GPU-driven pass steps, not only the first): a list -//! of the causes announced beside them ([`Device::degrade_host_step`]). For a kind a -//! variant's making announces (a -//! stage's precision notes, specialized or not, `ycbcr-filter-not-exact`, a shader's color -//! conversions, reconvergence that is not Metal's, unadvertised vertex simdgroups), an occurrence -//! is each dispatch or draw that binds the variant (an indirect command's too, where its -//! execution records it, and an execution the GPU alone runs, once), announced there with the -//! making's object and reason and not at the making, since the device memoizes a variant and -//! makes it once. A variant keeps the kinds its making may announce as a mask (`Kinds`), which a -//! bind ANDs with the device's before it describes any. -//! - **Where.** Each site announces once the command or object it degrades can no longer be -//! refused. A pipeline stage's precision notes, and reconvergence that is not Metal's, are -//! announced where the runtime makes a variant's objects (`pipeline/objects.rs`), for compute and -//! render pipeline states alike, but for a note the stage records only under some -//! specializations, announced where the runtime makes a `VkPipeline` whose specialization (the -//! bound formats' classes and samplers' words) takes it; a render pipeline's vertex simdgroups on -//! a driver that runs them without advertising the vertex stage, where the runtime makes a render -//! variant, before its shader modules (`pipeline/render.rs`, from the pipeline's requirements); a -//! render pass's degradations where its encoder ends (`render.rs`), from the pass's layout, its -//! render pass instances and the storage it kept; a rasterization-rate map that is not the -//! identity where the device makes it (`rate_map.rs`); a draw's use of an attachment's memory in -//! place where the draw records (`render.rs`); a draw's copy of its index buffer or arguments -//! where the copy records (`draw_source.rs`), and its zeroed index positions where it records -//! (`render.rs`, `index_bounds.rs`); work a host step records (an indirect command buffer's -//! execution, an indirect dispatch) where its command buffer commits and where the step records -//! it (`deferred.rs`); a `Shared` buffer or heap in system memory where the device makes it -//! (`buffer.rs`, `heap.rs`); a texture whose blocks a carrier holds, which a command reading -//! texture handles reaches, once the command is encoded (`pvrtc.rs`, from `compute.rs` and -//! `render/arguments.rs`); native device maths that rounds a tiny product before its flush where -//! the device is made (`device/float_tininess.rs`); a sampler state whose anisotropy the device -//! filters otherwise than Metal where the device makes it (`sampler.rs`); a BC texture whose -//! texels the device decodes otherwise than Metal where the device makes it (`texture.rs`, -//! `texture/shared.rs`, `texture/heap.rs`). - -use super::attachment_stand_in::{Cause, StandIn}; -use super::binding::{CommandUses, ResidentPrefix}; -use super::color_resolve; -use super::device::{DebugMessage, Device, DeviceShared, MessageKind, MessageSeverity}; -use super::error::Error; -use super::fragment_imageblock::PassImageblock; -use super::pipeline::objects::{ - may_pass_support, set_layout_support, unordered_bind, SetSupport, UnorderedBind, -}; -use super::render_pass::{ColorTarget, PassLayout, Target}; -use super::render_target::{self, depth_stencil_steps, HandedDontCare, PassShape}; -use super::render_values::{LoadAction, StoreAction}; -use super::resolve::ResolveMode; -use super::resource::{ObjectId, ResourceKey}; -use super::texture::heap_tiled::Untiled; -use super::texture_descriptor::TextureDescriptor; -use super::tracker::Use; -use super::values::ResourceOptions; -use super::work_counts::CopiedBecause; -use crate::error::EncoderCall; -use metal2vulkan::bind::PlanDiagnostic; -use metal2vulkan::cache::SpecializationKey; -use metal2vulkan::device::{DriverFact, FunctionStorage, VkProperty}; -use metal2vulkan::metal::PixelFormat; -use metal2vulkan::pipeline::{ - ComputePipeline, PrecisionNote, Reconvergence, RenderPipeline, SlotRef, SpecKey, StageModule, -}; -use metal2vulkan::vk::{ImageAspectFlags, ShaderStage}; -use std::cell::Cell; -use std::collections::BTreeSet; -use std::mem::Discriminant; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; - -/// The pixel format of the texture a draw or dispatch binds at a texture slot, where it binds -/// one: what a specialized notice names ([`Device::degrade_specialized`]). -pub(crate) type BoundFormats<'a> = &'a dyn Fn(SlotRef) -> Option; - -/// The texture slots a clause of `clauses` tests by their bound format's class -/// (`SpecKey::TexelFormat`, or `SpecKey::UnmeasuredTexels` on a device that samples through -/// Metal's own texture unit, or the bound texture's own, `SpecKey::BoundTexelFormat`), each once, -/// in order. -fn tested_slots<'a>( - clauses: impl IntoIterator, -) -> std::collections::BTreeSet { - clauses - .into_iter() - .flat_map(|clause| &clause.all) - .filter_map(|test| match test.key { - SpecKey::TexelFormat(slot) - | SpecKey::UnmeasuredTexels(slot) - | SpecKey::BoundTexelFormat(slot) => Some(slot), - _ => None, - }) - .collect() -} - -/// Whether `note` is a filter note (`PrecisionNote::HalfSampleFilter`, `FloatSampleFilter`): its -/// clauses test a two-plane YCbCr format bound at a slot that Metal's own sampler filters -/// (`metal2vulkan::lower`'s `filter_note`), announced as [`Degradation::YCbCrFilterNotExact`]. -fn filter_note(note: PrecisionNote) -> bool { - matches!( - note, - PrecisionNote::HalfSampleFilter | PrecisionNote::FloatSampleFilter - ) -} - -/// The format a draw or dispatch binds at each texture slot a specialized note tests -/// (`VariantObjects::tested_formats`), kept past the bind's tables. -pub(crate) type TestedFormats = Vec<(SlotRef, Option)>; - -/// The texture slots a specialized note of `stages` tests, each once, in order: those whose -/// formats [`Device::degrade_specialized`] may name. -pub(crate) fn tested_slots_of(stages: &[StageModule]) -> Vec { - tested_slots( - stages - .iter() - .flat_map(|stage| &stage.specialized_notes) - .flat_map(|note| ¬e.when), - ) - .into_iter() - .collect() -} - -/// Whether a degradation costs time and memory, or exactness. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum DegradationCategory { - /// Metal's answer, at a cost Metal does not pay: copies, staging or scratch resources, - /// extra passes or prepasses, a slower variant. - Performance, - /// A recorded near-equivalent: Metal's answer is not given exactly. - Precision, - /// Metal's answer, exactly, through use of the device that its driver does not advertise - /// but runs as Metal does, measured (a `metal2vulkan::error::DriverDeviation`, or a - /// `metal2vulkan::error::RuntimeDriverDefect` of a query that refuses what the driver runs): - /// Vulkan does not allow the use on the device as the driver describes it, so the validation - /// layer reports it. - Validity, -} - -/// The cost of every precision-note kind. -const NOTE_COST: &str = "results can differ from Metal's as the note's documentation states"; - -/// Defines [`Degradation`] from its kinds: the runtime's own (`code`, category, cost), then one -/// per precision note (named as the note, with its code). -macro_rules! degradations { - ( - runtime { - $( - $(#[doc = $doc:literal])* - $kind:ident = $code:literal, $category:ident, $cost:literal; - )* - } - notes { - $( - $(#[doc = $note_doc:literal])* - $note:ident = $note_code:literal; - )* - } - ) => { - /// A kind of degradation the runtime announces (the module docs). Its - /// [`code`](Degradation::code) is a stable contract: never renamed. - #[non_exhaustive] - #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] - pub enum Degradation { - $($(#[doc = $doc])* $kind,)* - $( - #[doc = concat!( - "A pipeline stage records [`PrecisionNote::", - stringify!($note), - "`]." - )] - $(#[doc = $note_doc])* - $note, - )* - } - - impl Degradation { - /// Every kind, in declaration order. - pub const ALL: &'static [Degradation] = - &[$(Degradation::$kind,)* $(Degradation::$note,)*]; - - /// The kind's code, `metal2vulkan-degrade-`: the notice's `id_name`. - pub const fn code(self) -> &'static str { - match self { - $(Degradation::$kind => concat!("metal2vulkan-degrade-", $code),)* - $(Degradation::$note => concat!("metal2vulkan-degrade-", $note_code),)* - } - } - - /// Whether the kind costs time and memory, or exactness. - pub const fn category(self) -> DegradationCategory { - match self { - $(Degradation::$kind => DegradationCategory::$category,)* - $(Degradation::$note => DegradationCategory::Precision,)* - } - } - - /// What the kind costs, the same for every occurrence. - pub const fn cost(self) -> &'static str { - match self { - $(Degradation::$kind => $cost,)* - $(Degradation::$note => NOTE_COST,)* - } - } - - /// The precision note the kind announces, for a note's kind: one a pipeline stage - /// records. [`Degradation::CappedLodBias`], which announces the note a sampler state - /// carries ([`PrecisionNote::CappedLodBias`]) where the device makes the state, is a - /// runtime kind and answers none. - pub const fn precision_note(self) -> Option { - match self { - $(Degradation::$kind => None,)* - $(Degradation::$note => Some(PrecisionNote::$note),)* - } - } - - /// The kind announcing `note`. [`PrecisionNote::SnormMinimumKept`], which only a - /// profile of `Device::from_queries` records, announces this runtime's kind for the - /// same codes, [`Degradation::SnormMinimumKept`]; [`PrecisionNote::DepthDenormals`], - /// which `metal2vulkan-rt`'s depth-stencil state carries, announces - /// [`Degradation::DepthDenormals`]; [`PrecisionNote::DeviceFilteredMipmaps`], which its - /// blit encoder carries, [`Degradation::DeviceFilteredMipmaps`]; - /// [`PrecisionNote::CompressedTexelDecode`], which its block-compressed textures carry, - /// [`Degradation::CompressedTexelDecode`]; and [`PrecisionNote::SharedExponentKept`], - /// which only a profile of `Device::from_queries` records, - /// [`Degradation::SharedExponentKept`]. - pub const fn from_precision_note(note: PrecisionNote) -> Degradation { - match note { - $(PrecisionNote::$note => Degradation::$note,)* - PrecisionNote::CappedLodBias => Degradation::CappedLodBias, - PrecisionNote::SnormMinimumKept => Degradation::SnormMinimumKept, - PrecisionNote::DepthDenormals => Degradation::DepthDenormals, - PrecisionNote::DeviceFilteredMipmaps => Degradation::DeviceFilteredMipmaps, - PrecisionNote::DeviceRoundedResolve => Degradation::DeviceRoundedResolve, - PrecisionNote::CompressedTexelDecode => Degradation::CompressedTexelDecode, - PrecisionNote::SharedExponentKept => Degradation::SharedExponentKept, - PrecisionNote::DeviceReconvergence => { - Degradation::ImplementationDefinedReconvergence - } - } - } - } - }; -} - -degradations! { - runtime { - /// A 2D texture over a buffer is a shadow image: the buffer is over host pages (a no-copy - /// buffer's, imported by their pointer or as dma-bufs, or the fresh pages a host-visible - /// buffer of the runtime's own longer than 32 MiB lies in, `fresh_pages.rs`), where an - /// image bound to them would start `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`) and - /// Vulkan lets its layout transitions (its first move among them) read and write any byte - /// bound to it, where Metal keeps every CPU write, and the device takes no image in place - /// there (`in_place.rs`): the policy keeps the exact form - /// ([`metal2vulkan::device::HostPageTexturePolicy::Shadow`]), the texture's usage renders - /// into it or writes it (`RenderTarget`, `ShaderWrite`, `ShaderAtomic`), the device's - /// check that the move keeps every byte over that kind of pages, for texels that share a - /// line of the device's memory (`nonCoherentAtomSize`) with bytes beside them or not as - /// the texture's do, has not answered yet, found a byte changed or made no image, or no - /// image in place serves the texels (its rows - /// share bytes, the device lays no linear image's rows at the buffer's pitch, the image's - /// placement or memory misses the pages, the bytes were detached, or no dma-buf of the - /// texture's own pages serves); the notice names which; or its rows (or an array's slices) lie with the buffer's - /// bytes between them, which an image over them would hold in its subresource, where - /// Vulkan lets the image's layout transitions read and write any byte of its subresources, - /// and a render pass's load and store operations read and write back any byte of an - /// attachment's image subresource, and Metal leaves them as the program writes them (but - /// for a texture that renders nothing, or renders on a device whose check of renders over - /// its pooled memory passed, over a buffer only the device's ordered commands - /// write, a `Private` one or a `Managed` one's own on a device without unified memory, - /// whose linear image, made `PREINITIALIZED`, keeps them through its one layout - /// transition, or whose `DRM_FORMAT_MOD_LINEAR` image at the buffer's pitch keeps them by - /// copies around its first move: docs/API.md); or no - /// linear image of the device lays its texels out as Metal does in the buffer's memory, - /// holding no byte past them; or the buffer is over the caller's `VkBuffer`, whose memory - /// backs no image of the runtime's; or it is a tiled texture of more than one level - /// (`Buffer::new_tiled_texture`), over any buffer: no image over the buffer's memory holds - /// levels past the first, so one image of its own holds every level, a copy of the bytes - /// taken at its first use and after each `did_modify_data`, as an x86 Mac's texture is - /// (the notice names the levels). Also a heap's - /// texture over host pages imported as - /// dma-bufs where the device makes no image over a dma-buf of the texture's own pages (the - /// notice names why). A heap's texture is a shadow of the heap's bytes in its range in - /// three more shapes, each announced with its own reason (`texture/heap.rs`). A - /// single-sample depth or stencil texture whose texels fit the bytes its image takes, on a - /// device whose driver lays such images apart from the memory they are bound to - /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]): one no such shadow - /// serves, a multisampled one among them, lies apart from those bytes instead - /// (`heap-depth-stencil-apart`). A texture the device binds no image of to the heap's - /// memory where the heap places it: its optimal image takes no memory type of the heap's - /// and no linear image of the device serves (a `Shared` heap's depth texture on MoltenVK), - /// or the heap lies over host pages that no linear image over them serves, or its images - /// ask more than Metal's answer for the texture (every 4:2:2 texture among them) and a - /// shadow of its rows serves. And a heap's `RGB10A8_2P_XR10` texture, or its sRGB twin, of - /// a 1D, 2D, 1D array, 2D array or 3D type, of any level count, of one sample, whose moves - /// fit the device: its image holds each texel's colour word and alpha byte side by side - /// where Metal keeps two planes in the heap's bytes, so the image is a shadow of those - /// planes (a mipmapped one's levels past the first, and a 1D array's texels, lie in the - /// image alone: `heap-two-plane-layout`). Where Metal's layout of the texture in the heap's - /// bytes is measured and the moves fit the device, the first two shadow Metal's tiles there - /// (the texture's elements, a multisample texture's samples) rather than its rows, and so - /// do two textures that would otherwise need no shadow: one whose image the driver keeps - /// GPU-optimized where Metal's texture is not - /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesStayGpuOptimized`]), and a - /// multisample texture whose image lies in memory of its own. - ShadowedTexture = "shadowed-texture", Performance, - "its texels are copied into an image before each use and back after each write \ - (over a buffer's bytes but a tracked private buffer's, kept before a write and merged \ - back after it; over a tracked private buffer of the runtime's own, copied in again \ - only once another command buffer wrote it; a tiled texture of more than one level, \ - copied in only at its first use and the first after each did_modify_data, and never \ - back)"; - /// A texture buffer is viewed through a staging buffer: its texels start where the - /// device views none (`minTexelBufferOffsetAlignment`), or run past the bytes its - /// buffer's memory holds for them (a no-copy buffer's or a buffer's under 16 KiB length), - /// where its staging buffer is its tail. - StagedTextureBuffer = "staged-texture-buffer", Performance, - "its texels are copied into a staging buffer before each use and back after each \ - write"; - /// One command writes a buffer's bytes through a shadowed texture or a staged texture - /// buffer and also another way (`shadow_merge.rs`). - ShadowMerge = "shadow-merge", Performance, - "the shadow's texels are kept in a scratch buffer of one to three times the texture's \ - bytes (or an image of the texture's size) before the command, and after it a \ - dispatch merges the bytes it changed through the texture into the buffer's, in place \ - where the texture's bytes start and end in whole words of the buffer: one to three \ - copies and a dispatch in place of one copy back"; - /// A draw's index buffer or indirect arguments start where Vulkan reads neither. - CopiedDrawBytes = "copied-draw-bytes", Performance, - "they are copied into a buffer of the command buffer before the pass, and the draw \ - reads the copy"; - /// An indexed draw reads index positions past where Metal's fetch stops reading its - /// index buffer (its length rounded up to 4 bytes), for which Vulkan states no index - /// (`draw_source.rs`): a direct draw whose positions run past there, on every device; or an - /// indirect draw that stays one draw (a driver measured to read zero past the bound range, - /// `DriverFact::RobustIndexFetchReadsZero`) on a device that enables `robustBufferAccess2` - /// but not `maintenance5`, whose bound range runs to the end of the index buffer's - /// `VkBuffer`, on past the bytes into its padding or into a heap's bytes after a placed - /// buffer. - IsolatedIndexBytes = "isolated-index-bytes", Performance, - "its whole indices inside the buffer are copied into a buffer of the command buffer \ - before the pass, between two barriers, and the draw reads the copy: a direct draw's \ - at its start, every position past them zero"; - /// An indexed indirect draw reads arguments or indices a draw of its encoder wrote, with - /// no memory barrier in the encoder before it, a race Metal does not order - /// (`draw_source.rs`); or a draw's vertex stage reads a buffer of its vertex table a - /// fragment stage of its render pass wrote (`render/pass_start_reads.rs`). - UnorderedDrawBytes = "unordered-draw-bytes", Performance, - "they are copied into a buffer of the command buffer before the pass, between two \ - barriers, and the draw reads the bytes from before the write, which Metal's draw \ - read in every run measured"; - /// A draw biases a `Depth16Unorm` depth by a constant, or by a slope alone, which brings - /// Metal's constant unit, on a device whose driver is not measured to store Metal's codes - /// so (`DriverDeviation::MetalDepth16BiasedStores`, `render_state.rs`): the device biases - /// by Metal's constant in its own unit and converts the depth. - UnormDepthBias = "unorm-depth-bias", Precision, - "a biased depth can store another code than Metal's: the device biases by the \ - constant c in its own unit, up to twice 2^-16, where Metal biases by c + 1 units of \ - 1/65535 (c - 1 below 0, one unit for a slope alone), and rounds the biased sum its \ - own way"; - /// A draw tests or writes a `Depth16Unorm` depth on a device whose driver is not measured - /// to convert a depth to Metal's code (`DriverDeviation::MetalDepth16Stores`, - /// `render_state.rs`), or a pass clears one to a depth that a device rounding to nearest - /// takes above Metal's truncation (`clear_value.rs`): the device converts the depth. - UnormDepthRounding = "unorm-depth-rounding", Precision, - "a depth near a code's midpoint can store the code next to Metal's: the device \ - converts the depth to the 16-bit code its own way, where Metal's draw rounds to \ - nearest, a tie up, and its clear truncates"; - /// A draw of points keeps Vulkan's clipping of points, where Metal's guard band cannot be - /// emulated: in a rate-mapped pass, on a device without `shaderClipDistance` or with too - /// few clip distances beside the vertex function's own, or through a viewport whose - /// widened Vulkan viewport would leave the device's limits or not be a `float` exactly - /// (`render_state.rs`). - PointGuardBand = "point-guard-band", Precision, - "a point whose center lies past its viewport, within Metal's guard band of 1.5 times \ - the viewport's half-size, is culled where Metal draws it, and a wide point can lose \ - pixels at a fractional viewport edge by the device's own clipping"; - /// A draw whose fragment function writes its depth, in depth clamp mode through a range - /// above 0, keeps the device's clamp of that depth, where the function cannot clamp it - /// itself under a Vulkan clamp that holds 0: on a device without - /// `VK_EXT_depth_clamp_control` whose vertex stage cannot compensate the depth exactly, a - /// mesh pipeline there, through viewports of different clamps or depth ranges, under a - /// depth bias that saturates or offsets the range, or past the device's clip distances - /// (`render_state.rs`). And a draw whose fragment function writes its depth under a - /// stencil depth-failure operation: a positive NaN depth, which fails Metal's depth - /// test and runs that operation, discards the fragment instead. - NanDepth = "nan-depth", Precision, - "a NaN depth the fragment function writes: a negative one in depth clamp mode stores \ - the depth clamp range's low end, where Metal stores 0; a positive one runs no \ - stencil operation, where Metal runs the depth-failure one"; - /// A draw of triangles in depth clip mode under a depth bias of a constant or slope - /// factor other than 0, on a device that enabled `VK_EXT_depth_range_unrestricted` but - /// lacks `depthClamp`, `VK_EXT_depth_clip_enable` or `VK_EXT_depth_clamp_control` - /// (`render_state.rs`, `announce_unclamped_bias`): such a device stores a depth the bias - /// takes past `[0, 1]` unclamped, where Metal clamps it. - BiasedDepthPastUnitRange = "biased-depth-past-unit-range", Precision, - "a depth a bias takes past [0, 1] in depth clip mode is stored unclamped, where Metal \ - stores 0 or 1"; - /// A draw of lines or triangles whose vertex stage clamps each vertex's depth as Metal - /// does, through a viewport depth range with a negative depth in depth clip mode or past - /// `[0, 1]` in depth clamp mode (`render_state.rs`, `VertexClamp`): Metal clips a - /// primitive at its near and far planes and at its guard band first, and clamps the - /// depths of the pieces' vertices. - ClippedDepthPieces = "clipped-depth-pieces", Precision, - "a primitive that crosses Metal's near or far plane, or its guard band of 1.5 times \ - the viewport's half-size, stores the interpolation of its own vertices' clamped \ - depths, where Metal clamps the depths of the pieces it clips the primitive into"; - /// A draw of lines or triangles through such a range whose vertex stage cannot clamp - /// each vertex's depth: its fragment function reads its position's depth, a mesh - /// pipeline, on a device without `shaderClipDistance` or past its clip distances, or - /// through viewports whose depths need different compensations on a device that takes - /// the ranges natively (`render_state.rs`, `VertexClamp`); and a draw of triangles in depth - /// clamp mode under a depth bias that moves the depth through a range inside `[0, 1]`, - /// where Metal adds the bias to each vertex's depth clamped to `[0, 1]`, which a primitive - /// past its near or far plane shows. - SampleDepthClamp = "sample-depth-clamp", Precision, - "a sloped primitive's depth is clamped at each sample, where Metal clamps each \ - vertex's depth before the interpolation, at 0 in depth clip mode and to [0, 1] in \ - depth clamp mode"; - /// A draw of triangles in depth clamp mode through a viewport depth range whose larger - /// depth lies past 1, under a depth bias of factors, whose Vulkan clamp holds at most 1 - /// (`render_state.rs`, `VertexClamp`). - DepthBiasPastOne = "depth-bias-past-one", Precision, - "a depth the bias moves past 1 stores 1, where Metal clamps it to the range's larger \ - depth"; - /// A draw's vertex stage reads in place bytes a fragment stage of its render pass wrote, - /// through an argument buffer or a resident resource, of a buffer another stage of the - /// pass or the vertex function writes, or in an execution of render commands - /// (`render/pass_start_reads.rs`). - InPlaceVertexReads = "in-place-vertex-reads", Precision, - "the device may order the fragments' write before the read, where Metal's vertex \ - stages read the bytes from before the pass's fragments in every run measured"; - /// A draw's object or mesh stage reads in place bytes a fragment stage of its render pass - /// wrote (through an argument buffer or a resident resource, or of a buffer another stage - /// of the pass or the stage's function writes; an emulated stage's where its work records - /// after the pass's earlier render pass instances), or a draw's vertex, object or mesh - /// stage writes bytes a fragment stage of its render pass read or wrote - /// (`render/pass_start_reads.rs`): Metal's GPUs run every draw's vertex, object and mesh - /// functions before any draw's fragments of the pass. - FragmentsBeforeGeometry = "fragments-before-geometry", Precision, - "the device may run the pass's earlier fragments before the draw's stage, and does \ - across a split of the pass (a command's barrier, a memory barrier): the read sees \ - their write, their read misses the write, or the write outlasts theirs, where \ - Metal's fragments run after every draw's vertex, object and mesh functions in every \ - run measured"; - /// An indexed indirect draw whose index fetch nothing bounds (the device lacks - /// `robustBufferAccess2`, its driver is not measured to read zero past the bound range, - /// `DriverFact::RobustIndexFetchReadsZero`, or the index offset lies at or past the - /// buffer's length) is bounded on the GPU before the pass (`index_bounds.rs`). - IndirectIndexBoundsPass = "indirect-index-bounds-pass", Performance, - "two dispatches before the pass write two draws' arguments and the indices past the \ - buffer into the command buffer's index pool (a sixty-fourth of the device's largest \ - device-local heap), between barriers, two for a run of such draws over one arguments \ - and one index buffer, and the draw is two indirect draws; a draw the pool cannot \ - hold fails the command buffer"; - /// A mesh render pipeline's draws on a device without `VK_EXT_mesh_shader` - /// (`render/mesh.rs`). - EmulatedMeshDraws = "emulated-mesh-draws", Performance, - "the object and mesh functions run as compute dispatches before the pass, between \ - barriers, writing records a synthesized vertex stage draws; a draw whose mesh \ - threadgroups the GPU decides is scanned first and reserves its records in the \ - command buffer's records pool (a sixty-fourth of the device's largest device-local \ - heap), and a draw the pool cannot hold fails the command buffer"; - /// A tessellation pipeline's patch draws on a device without `tessellationShader` - /// (`render/tessellation_scan.rs`). - EmulatedTessellationDraws = "emulated-tessellation-draws", Performance, - "each patch draw runs a scan dispatch before the pass, between barriers: one \ - workgroup that processes the draw's patches, instance by instance, into records in \ - order, so its GPU time grows with the draw's patches times its instances, apart \ - from its draw; the draw then draws the tessellator's triangles with the \ - post-tessellation vertex function as a plain vertex function, up to 2^30 triangles \ - per indirect draw; an indirect draw reserves its records in the command buffer's \ - records pool (a sixty-fourth of the device's largest device-local heap), and a draw \ - the pool cannot hold fails the command buffer"; - /// A render pipeline state whose draws run a synthesized geometry stage - /// (`RuntimeFact::SynthesizedGeometry`): its fragment function reads - /// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric`, or its vertex - /// function selects its primitive's render target slice or viewport on a device that - /// cannot store `Layer` or `ViewportIndex` from a vertex function. - SynthesizedGeometryStage = "synthesized-geometry-stage", Performance, - "each draw runs a geometry stage of its topology class between the vertex and \ - fragment stages, which emits each primitive's vertices with the barycentric weights \ - or the first vertex's slice and viewport"; - /// Visibility results start where Vulkan writes no query result. - LandedVisibilityResults = "landed-visibility-results", Performance, - "they land in an upload region, into which the buffer's words are copied first \ - where they accumulate, and are copied on into the buffer after the pass"; - /// A blit copies between overlapping ranges of one buffer, which Vulkan's copy forbids. - OverlappingBufferCopy = "overlapping-buffer-copy", Performance, - "the range goes through a scratch buffer of its size, which its creation clears by \ - a fill it waits for: two copies instead of one"; - /// A blit fills bytes that are not whole 4-byte words at multiples of 4. - SplitBufferFill = "split-buffer-fill", Performance, - "the words are filled and the up to 3 bytes at each end copied from a 1-KiB \ - pattern buffer the encoder makes once"; - /// A blit copies between a buffer and a texture in a layout Vulkan cannot state. - StagedTextureCopy = "staged-texture-copy", Performance, - "the rows go through a tightly packed scratch buffer: two copies instead of one, \ - and for a single-sample texture the scratch's creation clears it by a fill it \ - waits for"; - /// A blit copies texel rows of a texture over a buffer to or from bytes of the same - /// buffer that they share, which Vulkan's copy forbids. - OverlappingTexelCopy = "overlapping-texel-copy", Performance, - "the rows go through a tightly packed scratch buffer, which its creation clears by \ - a fill it waits for: two copies instead of one"; - /// A dispatch is more than one Vulkan dispatch: its grid is not a whole number of - /// threadgroups, or a group count is past the device's `maxComputeWorkGroupCount`. - SplitDispatch = "split-dispatch", Performance, - "one Vulkan dispatch per region (the interior and each partial edge, per chunk of \ - group counts), each on its own specialized pipeline, a barrier between each two"; - /// A dispatch whose threadgroups are not whole subgroups of the kernel's pinned - /// subgroup size runs on the kernel's emulated-simdgroups variant. A threadgroup of one - /// row of a kernel whose only simdgroup semantics are lockstep barriers that order pairs - /// meeting across rows (`RuntimeFact::RowLockstep`) runs on the kernel's one-row variant - /// (`VariantKey::one_row`), which has none of those barriers and pins no subgroup size. - EmulatedSimdgroups = "emulated-simdgroups", Performance, - "a second compile of the kernel whose simdgroup operations go through threadgroup \ - memory between barriers"; - /// A pass of separate depth and stencil textures, or of a stencil-only texture alone at - /// custom sample positions, renders into a scratch image of a combined format - /// (`depth_stencil_scratch.rs`). - SeparateDepthStencil = "separate-depth-stencil", Performance, - "each loaded aspect is copied into the scratch image before the pass and each stored \ - one back after it, through a staging buffer, or a multisampled colour image for \ - multisampled textures, or sample-rate draws where the device's copies of those are \ - missing or wrong"; - /// A pass resolves a combined depth/stencil attachment one aspect at a time, on a - /// device that resolves the two aspects only together or only in one mode, or where its - /// aspects resolve into different textures (separate textures). - OneAspectResolve = "one-aspect-resolve", Performance, - "a scratch image per aspect, the second aspect resolved after the pass in a render \ - pass of its own from the stored samples, and each resolved aspect copied into the \ - resolve texture after the pass through a staging buffer"; - /// A pass resolves into a texture that cannot be an attachment (its usage lacks - /// `RenderTarget`), or a layered pass into a texture whose slices from the resolve slice - /// hold fewer layers than the pass's, or a pass resolves color into a 3D texture's planes - /// past its first, or into more than one, on a device whose resolve into a 2D view of a - /// 3D image is written where the view begins only at its first plane - /// (`RuntimeDriverDefect::VolumeResolveFirstPlane`: RADV, NVIDIA's). - ResolveScratch = "resolve-scratch", Performance, - "the pass resolves into a scratch image, whose render area is copied into the \ - texture after the pass"; - /// A multisample color resolve drawn after the pass by the crate-owned resolve: of an - /// extended-range attachment, whose codes no device's resolve averages, or into the - /// attachment's format's sRGB twin, whose encoding no device's resolve writes - /// (`color_resolve.rs`); or a - /// stencil resolved by `DepthResolvedSample` after `Min` or `Max`, which no Vulkan - /// resolve mode states, or a `Min` or `Max` depth on a device without the mode, drawn - /// after the pass (`depth_stencil_resolve.rs`). - ShaderResolve = "shader-resolve", Performance, - "one more render pass instance after the pass reads the stored samples (or the \ - sample planes) and writes the resolve texture, where the device would resolve in \ - the pass; where the attachment's image takes no input attachment usage, a copy of \ - its samples over the render area into a scratch image first"; - /// A fragment function writes a float to a half-float color attachment of a pipeline - /// under `TextureWriteRoundingMode::NearestEven`, whose rounding no device's conversion - /// gives (`StageModule::rounded_colors`). - ShaderColorConversion = "shader-color-conversion", Performance, - "the fragment function rounds each such channel to nearest even before it writes it: \ - about 35 more instructions per channel"; - /// A Metal render pass runs as several Vulkan render pass instances (`render.rs`): a - /// framebuffer fetch through the pixel interlock keeps its attachment out of its draws' - /// subpass, and the pass's draws leave different attachments out, or its last draws - /// leave out an attachment that resolves, which resolves in one more instance; or a - /// fetch through input attachments reads an attachment whose image takes no input - /// attachment usage (a caller's) after other draws recorded, and the stand-in that has - /// it makes it an input attachment of the later draws' subpass alone; or a tile dispatch - /// runs between two instances; or some of its draws render some of its layers (vertex - /// amplification as multiview, or a view mapping that moves a draw to one layer), each run - /// of them in an instance over those layers; or a memory barrier over buffers or textures - /// orders its draws after it behind those before it, which a barrier between instances - /// does; or a draw reads a color attachment's texture after a memory barrier, and reads - /// what the pass's load actions and earlier draws stored where the barrier orders them - /// (`texture/attached_reads.rs`), but for a read of the clear alone before any draw of - /// the pass, whose copy is cleared to it instead where it can be - /// (`WorkCounts::attachment_read_clears`); or a draw reads and writes a color through the - /// pixel interlock after an earlier draw of its instance wrote it, on a driver whose such - /// draws race under load (`DriverFact::InterlockedDrawsRaceUnderLoad`), and records into - /// an instance after the one that wrote it. Not where the interlock alone splits the pass, - /// on a device whose driver ran such a pass no slower split than whole - /// (`DriverFact::InterlockedPassSplitNoSlower`): its faster form. - RenderPassSplit = "render-pass-split", Performance, - "each instance after the first loads the attachments and each before the last \ - stores them, with a barrier from everything before to everything after between \ - them: on a tiler, a tile flush per split"; - /// A draw under vertex amplification that Vulkan multiview cannot express (view - /// mappings that offset the viewport or name layers out of order, more amplifications - /// than the device's views, or a pipeline that chooses or reads its render target - /// slice) draws one amplification at a time (`bind::DrawCommands::amplifications`). - AmplificationDraws = "amplification-draws", Performance, - "one Vulkan draw per amplification, each after the amplification's push data, on \ - the pipeline state's variant that reads it, where multiview would draw them all \ - at once"; - /// A memoryless attachment renders into a backing image of the device's own memory, - /// because a framebuffer fetch through the pixel interlock reads it or the pass splits - /// (`attachment_stand_in.rs`); not for a split `render-pass-split` leaves unannounced. A - /// color's backing is one its command queue keeps for its passes of the attachment's - /// format, samples and size (`attachment_stand_in::pooled_backing`). - MemorylessBacked = "memoryless-backed", Performance, - "a scratch image, a color's kept by its command queue for its passes of that shape \ - and a depth or stencil one's per pass: memory, and the bandwidth to write and read \ - it, that Metal does not spend on a memoryless texture"; - /// A memoryless texture buffer (`newTextureWithDescriptor:` of a `TextureBuffer` - /// descriptor of `MTLStorageModeMemoryless`, which plain Metal makes), whose texels are a - /// buffer's bytes (`buffer_texture.rs`): the buffer is a `Private` one of the device's, - /// since no Vulkan buffer takes memory lazily. The texture answers the descriptor's - /// memoryless mode, as Metal's does, and a command that uses it fails its command buffer, - /// as plain Metal's (`Texture::is_memoryless`). - MemorylessTextureBuffer = "memoryless-texture-buffer", Performance, - "a Private buffer of the texture's row of texels: memory Metal spends none of on a \ - memoryless texture. Nothing reaches those bytes"; - /// A color render target that a framebuffer fetch reads lacks the usage the fetch's form - /// needs, so its pass renders into a scratch image that has it - /// (`attachment_stand_in.rs`): `STORAGE` in the pixel interlock, or for its sample - /// planes sampled usage with a view of its texel size's unsigned-integer format, either - /// of which the runtime gives a texture only where it leaves the image's layout (its - /// compression) alone; or input attachment usage, which a caller's image may lack. - /// Announced once, at the first such pass: a runtime texture may take its storage form - /// later (`fetched-target-storage`), its later passes then fetching it in place. Only a - /// fetch's scratch: the notice names the draw that fetched it first (its fragment function, - /// and the color's blend state and write mask). - FetchThroughScratch = "fetch-through-scratch", Performance, - "a scratch image per pass, the texture copied into it before the pass on a `Load` \ - and back after it on a `Store`"; - /// A runtime texture that a pass rendered into a scratch image for want of `STORAGE` - /// (`fetch-through-scratch` through the pixel interlock), or whose draw that read it at - /// its own pixels after a barrier split its pass for want of it (`render/snapshot.rs`), - /// took its storage form: its image - /// made again with `STORAGE` and its texels copied in once, at the commit of the device's - /// only uncommitted command buffer (`texture/storage_form.rs`); with a submission check, - /// once that command buffer's checks ran at its submission and every encoder of it ran. - /// Announced once per device, whatever `DeviceOptions::announce_each` says, before that - /// command buffer is scheduled: on the scheduler's thread once it submitted it, outside any - /// program call or host step, or in the call that makes a command buffer meanwhile. - FetchedTargetStorage = "fetched-target-storage", Performance, - "the texture's image laid out as one with `STORAGE` usage from then on (on MoltenVK \ - `ShaderWrite`, without lossless compression), and one copy of its texels, where \ - Metal's texture keeps its usage"; - /// A depth/stencil render target whose image was not made for the pass's custom sample - /// positions (a caller's image without - /// `VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT`, which Vulkan needs to - /// rasterize a depth/stencil attachment at them), or was on a driver that keeps a depth - /// rendered at them per sample only through a copy - /// ([`metal2vulkan::device::DriverFact::PositionedDepthReadAtStandardPositions`]: NVIDIA's, - /// measured), renders into a scratch image made for them (`attachment_stand_in.rs`). - PositionsThroughScratch = "positions-through-scratch", Performance, - "a scratch image per pass, each aspect copied into it before the pass on a `Load` \ - and back after it on a `Store`"; - /// A framebuffer fetch through the pixel interlock in a multisampled pass, on a device - /// without multisampled storage images, reads and writes the attachment as its sample - /// planes (`sample_planes.rs`): a single-sampled array image of one layer per sample. - SamplePlanes = "sample-planes", Performance, - "a planes image per fetched attachment and pass; a compute dispatch copies the \ - samples into it before the draws that fetch (on a `Load`, or after other draws \ - rendered it) and a sample-rate pass copies them back after those draws (before \ - other draws render it, and where the pass keeps or resolves it)"; - /// A render pass's draws test and write the stencil in the fragment shader, on a device - /// without `VK_EXT_shader_stencil_export` (`shadow_stencil.rs`): the function's - /// `[[stencil]]` output is Metal's stencil reference, which only that extension hands the - /// fixed-function test. - ShaderSideStencil = "shader-side-stencil", Performance, - "an 8-bit shadow image of the stencil per pass, which the stencil is copied into \ - before each run of such draws and back from after it (through a staging buffer at \ - one sample), each run in a render pass instance of its own, its fragment shader \ - testing and writing the shadow in the pixel interlock"; - /// A tile dispatch stages its pass's attachments through storage views in their staging - /// formats, which it takes of a scratch image of each attachment's format: each is - /// copied into its scratch before the dispatch and back after it - /// (`render/tile_dispatch.rs`). - TileDispatchScratch = "tile-dispatch-scratch", Performance, - "a scratch image per staged attachment and pass, over the pixels the dispatch \ - covers, which each dispatch copies the attachment into before it and back from \ - after it, between barriers from everything before to everything after: memory and \ - bandwidth that Metal's tile memory does not spend"; - /// A render pass's draws' fragment functions declare an explicit imageblock, which they - /// read and write in a storage image of the render area (`fragment_imageblock.rs`). - FragmentImageblockStorage = "fragment-imageblock-storage", Performance, - "an R32Uint array image per pass over the render area, a layer per 4 bytes of a \ - pixel's imageblock and per sample, cleared before the pass, which the draws read \ - and write in the pixel interlock: memory and bandwidth that Metal's tile memory \ - does not spend"; - /// A command buffer uses a texture over the caller's image whose home layout is not - /// `GENERAL` (`Device::new_texture_with_vk_image`): every image the runtime uses rests in - /// `GENERAL`. - WrappedImageLayoutTransitions = "wrapped-image-layout-transitions", Performance, - "two whole-image barriers per batch that uses it: into GENERAL before its first \ - encoder, and back to its home layout at its end"; - /// An execution of an indirect command buffer (`executeCommandsInBuffer:withRange:`) whose - /// commands are known only once the work before it completed: a route that may write its - /// records met the buffer (`write_routes.rs`: its command buffer made it resident for - /// writing and set a pipeline state whose functions may call an indirect-command - /// operation, or executed commands whose records may name one; or a blit copied or reset - /// commands into it), so the GPU may write them, and the notice names that route; it reads - /// its range from a buffer; or it lies inside a block of command predication. The runtime - /// records such an execution on the CPU then where the GPU cannot run it alone. A render - /// execution: where its records may hold, at the commit or as its batch is ready, more - /// than draws of one primitive type under the encoder's state, or what its check looks for, - /// and, with its range read from a buffer or indexed draws among its records, where its - /// commands do not merge into one draw (a strip type, a `[[primitive_id]]` its fragment - /// function reads, or another rule of the merged form), or, for a range read from a - /// buffer, the CPU alone writes its records (`render/executions/gpu.rs`); its notice names - /// the first rule that kept it from the GPU alone, then every rule past it the pass breaks - /// too, each judged as though the rules before it were kept - /// (`render/executions/cause.rs`), and is announced once per first rule. A - /// compute execution: with a caller's check (`execute_commands_in_buffer_checked`) - /// that may see what it looks for (`IndirectCommandCheckNeeds`: a state that may encode - /// indirect commands, the encoder's where the buffer inherits it, else one its records may - /// name), at the commit or as its batch is ready; with its range read from a buffer; of a - /// buffer that inherits the encoder's buffers where the encoder binds a visible-function - /// table; where its records may name a pipeline state whose - /// kernel observes its threadgroup partition or fetches `[[stage_in]]` attributes, or a - /// state the CPU set that the program released since; and, on a device without - /// `VK_EXT_device_generated_commands`, where the host step is faster: where its commands - /// run with no barrier between them and its commands times the pipeline states its records - /// may name past four pass 256 (the states: every live one made with - /// `supportIndirectCommandBuffers`, or the encoder's where the buffer inherits it), where - /// they run with one and its commands times the states past twelve pass 512, and where its - /// commands times its states pass 32,768. Every other execution runs on the GPU alone and - /// announces nothing. - HostReplayedIndirectCommands = "host-replayed-indirect-commands", Performance, - "a GPU-to-CPU round trip: the batches that last wrote its records and its range \ - complete before the CPU records its commands from their records, on a thread of \ - the runtime's, and submits the rest, so a command buffer's executions behind one \ - writer wait for it once (where Metal tracks neither, or the step reads more, as \ - inside a block of command predication: its command buffer's work before it, and \ - every batch submitted before that on any queue); meanwhile the device's other \ - batches go, but for a later one that shares a resource the execution may reach \ - (one made resident, the records; where what it may reach is not known, through an \ - inherited visible-function table, tile memory, a visibility query or a shadowed \ - texture, a later commit of another queue goes ahead of it but where it writes the \ - records or the range or shares a fence with it), and the first command of a threadgroup size or threadgroup lengths its pipeline state has not \ - dispatched makes that VkPipeline then, as does a render command's draw of a state \ - the CPU set on none of the commands. In a rate-mapped pass whose host step fans \ - its triangles out, a render execution kept from the GPU alone by the rate map alone \ - has its records decoded on the GPU at the step, which reads back each command's \ - draw arguments and index buffer and none of its records, and each command is drawn \ - in its replay variant, indexed where it is (WorkCounts::rate_map_gpu_routes): a \ - second round trip, for the decode, comes before the probe's. Other commands run in the large-buffer form \ - (their range-limited buffer slots at device addresses, with in-shader bounds \ - checks), whose variants the commit compiles for every pipeline state a record may \ - name (for a render execution, every state the CPU set on its commands; or, for an \ - execution committed before a route that may write the records met the buffer, the \ - call that met it: a later commit, a blit's, or a CPU setter's); without device \ - addresses, a command's first buffer shape compiles its variant then"; - /// A host access of an indirect command buffer's records (a setter, a getter, a CPU - /// reset, a commit or host step that reads them) on a device without unified memory, - /// where the records lie in device-local memory and must stay there: a `Private` - /// buffer's, whose records never leave it, or a `Shared` one's that the GPU used first - /// while a command buffer that used them is not complete or dropped - /// (`indirect_command_buffer/home.rs`). An access that only reads records the GPU never - /// wrote is not one: it reads host memory in place, which holds what device-local memory - /// does. A `Shared` buffer's records move into host memory at its first host access once - /// no command buffer holds them, and stay there. To avoid it, touch a `Shared` buffer from - /// the CPU before the GPU uses it. - StagedIndirectRecords = "staged-indirect-records", Performance, - "a round trip through the device's staging queue for each such access: the records it \ - reads are copied into host memory first where the GPU may have written them, and \ - those it writes copied back after, each copy waited for, where Metal's CPU reads and \ - writes the records in place"; - /// A command buffer's GPU times on a device that calibrates its timestamps against no - /// host clock the runtime reads (no `VK_KHR_calibrated_timestamps` or - /// `VK_EXT_calibrated_timestamps` with the device's time domain and a monotonic host - /// one), whose calibration failed as it completed, or whose calibration placed them outside - /// the command buffer's life (before its first submission, after its completion) by more - /// than its stated deviation and the clocks' drift allow (`gpu_time.rs`). - UncalibratedGpuTimes = "uncalibrated-gpu-times", Precision, - "the end is the host time the runtime saw the command buffer complete, late by that \ - latency, and the start the GPU's exact duration before it"; - /// A command buffer's GPU times on a device whose calibration pair, taken as the command - /// buffer completed, stated a deviation above 20 us though the runtime read it again, - /// four readings at most, and placed them inside the command buffer's life by the - /// reading of the least deviation (`gpu_time.rs`). A reading's deviation holds the time - /// its thread spent off the CPU between its two values, so a loaded host states more: an - /// RX 7900 XTX (RADV) under full parallel test suites stated 93 and 125 us after four - /// readings. - LooselyCalibratedGpuTimes = "loosely-calibrated-gpu-times", Precision, - "each GPU time may stand from the moment the GPU wrote it by up to the deviation its \ - reason states, more than the 20 us a settled calibration reading keeps to; the \ - duration between them stays exact"; - /// A command buffer's GPU times on a device whose timestamp pools had no slot free at - /// the command buffer's commit, and which could make no pool more: every slot was held - /// by a command buffer in flight (`gpu_time.rs`). - UntimedCommandBuffer = "untimed-command-buffer", Precision, - "its GPU start and end times are refused (`Unsupported`, `GpuTimes`), where Metal \ - gives them; its kernel times stay"; - /// A command buffer's GPU times on a device told to answer them from the host - /// (`DeviceOptions::gpu_times_from_host`, `RawDevice::gpu_times_from_host`), or whose - /// driver's timestamps wait for every queue's (`DriverFact::TimestampsWaitForEveryQueue`: - /// MoltenVK 1.4.1 on Apple's GPUs, 1.4.2 on the M3 Max), which writes no GPU timestamps - /// of its own (`gpu_time.rs`). Every - /// answer is one Metal could give: seconds of Metal's clock (`mach_absolute_time`'s, on - /// macOS); its commit, kernel start, kernel end, GPU start, GPU end and the moment its - /// completion is observable in that order, but for one whose work went as several - /// submissions, which starts at its first, before its kernel end, the call of its last; - /// and a queue's command buffers one after another, none starting before the one before - /// it ended. The start can be early by the - /// time from the submission's end to the GPU's start, or late by the time the runtime took - /// to see the queue's command buffer before it complete; the end is late by the time it - /// took to see this one complete. - GpuTimesFromHost = "gpu-times-from-host", Precision, - "its GPU start is the call of the first submission that carried its work (its kernel \ - end time where one carried it all; or its queue's latest GPU end before it) and its \ - GPU end the host time the runtime saw it complete: a window its work ran in, \ - which holds the submission's and the completion's latencies, not the GPU's own start \ - and end"; - /// A multisample color resolve averages through Vulkan's `AVERAGE` mode, which leaves - /// the rounding of the average (and the sRGB encoding) to the device, on a device not - /// measured to round as Metal does: any color attachment but an extended-range one and one - /// resolving into its format's sRGB twin (each resolved after the pass, - /// `color_resolve.rs`), one a fetching pass's sample planes hold as it ends included (the - /// planes merged back first). Not where - /// `DriverFact::ColorResolveAverageIsMetals` holds, for any format: MoltenVK's resolve is - /// Metal's own. Also, on every device, a resolve into an 8-bit UNORM attachment's sRGB - /// twin where the device has the sRGB format: the crate-owned resolve reads the samples - /// through the device's sRGB decode and writes their average through its encode - /// (`bind::ColorResolveFormat::device_srgb`), where Metal's resolve takes its own 12-bit - /// tables; with correctly rounded conversions 1,758 of the 65,536 pairs of codes at 2 - /// samples land one code from Metal's. Measured by - /// `runtime_lane::resolve_rounding::a_twin_resolve_into_srgb_rounds_as_announced`, which - /// holds the bound: MoltenVK 1.4.2 on the M3 Max, 696 of the 262,144 channels of every - /// pair of codes at 2 samples one code below Metal's (880 of 524,288 at 4); lavapipe (Mesa - /// 26.0.8, at 4 samples) 57,865 of 524,288, above and below; none past one code. - /// Measured against Metal's rules at 2 and 4 samples - /// (`runtime_lane::resolve_rounding::the_device_resolve_rounds_as_announced`, which holds - /// the bound) on RADV (Mesa 26.0.8, the Radeon 780M and the RX 7900 XTX), ANV (Mesa - /// 26.2.4, the Iris Xe), NVIDIA (615.71, the RTX 5080 Laptop GPU) and lavapipe (Mesa - /// 26.2.4, at 4 samples): every unorm, snorm and packed 16-bit unorm channel within one - /// code of Metal's, an sRGB channel within two (NVIDIA's at 4 samples; one elsewhere). - /// Each rounds an 8-bit unorm tie down (RADV and ANV: 32512 of `R8Unorm`'s 65536 pairs of - /// samples one code below at 2 samples); an sRGB or packed channel lands above Metal's - /// code in some texels and below in others. A float channel's average differs in its - /// last bits, counted and not bounded (RADV: 8565 of `R32Float`'s 65536 channels at 2 - /// samples). - /// The device also decides what a NaN or infinite sample makes of the average, where - /// Metal's resolve counts a NaN of a `half` or small-float channel as 0 and an infinite - /// `half` as 65536 of its sign, and makes any NaN of a 32-bit float channel `0x7fc00000`; - /// lavapipe's average keeps a `half` NaN. - DeviceRoundedResolve = "device-rounded-resolve", Precision, - "a resolved channel can differ from Metal's by one code (an sRGB channel by two) \ - where the average lies near a rounding boundary, a float channel in its last bits, \ - and wholly where a sample is a NaN or an infinity: Metal's resolve counts a half or \ - small-float NaN as 0 and a half infinity as 65536 of its sign, and makes any 32-bit \ - float NaN 0x7fc00000, where the device's average may keep them"; - /// A multisample color resolve of more than 4 samples, of which Apple's GPUs make no - /// texture: no Metal answer is measured there (`color_resolve.rs`); likewise a stencil - /// resolved by `DepthResolvedSample` after `Min` or `Max` (`depth_stencil_resolve.rs`), - /// whose pick among equal depths is measured at 2 and 4 samples. - UnmeasuredResolve = "unmeasured-resolve", Precision, - "the resolve is the device's average, or after the pass the rules Metal's resolve \ - follows at 2 and 4 samples, which no Metal answer confirms at this count"; - /// A multisample resolve of an extended-range color attachment whose resolve Metal - /// averages from values finer than the codes the attachment holds (`BGRA10_XR`'s alpha, - /// an `_sRGB` twin's color, `RGB10A2Unorm_sRGB`'s channels; - /// `bind::ColorResolveFormat::extended_range`): the crate-owned resolve - /// (`color_resolve.rs`) writes a near-equivalent from the codes where a pixel's samples - /// differ, and Metal's code where they hold one. Measured against Metal's resolve on the - /// M3 Max under macOS 27.0.1 (our probe `xr`, 4096 texels per format at 2 and 4 samples, - /// each sample its own value): `BGRA10_XR`'s alpha Metal's in 84% and 88% of texels and - /// within a code in every one; an `_sRGB` twin's color in 81% and 85% of channels and - /// within a code in 99.5%, at most 7 codes off where the samples' values nearly cancel; - /// `RGB10A2Unorm_sRGB`'s colors in 83% and 87%, within 2, and its alpha in 94% and 97%, - /// within one (`runtime_lane::extended_range_resolve`). A linear form's color is Metal's - /// rule, every texel. - ExtendedRangeResolve = "extended-range-resolve", Precision, - "where a pixel's samples differ, a resolved alpha, or an sRGB color, can differ from \ - Metal's by a code (an sRGB color by a few where the samples' values nearly cancel): \ - Metal averages values finer than the codes the attachment holds"; - /// A multisample resolve of a packed 16-bit color attachment (`A1BGR5Unorm`, - /// `ABGR4Unorm`, the other packed 16-bit formats) the device renders only through the view - /// of its word, held in the word's format (`image_plan.rs`, - /// `bind::ColorResolveFormat::word`): the crate-owned resolve (`color_resolve.rs`) averages - /// each field's codes, a tie rounded down (a one-bit field's up), where Metal averages its - /// tile's values, the outputs as `half`s, finer than the codes, from the pass that drew - /// them. A pixel whose samples hold one word resolves to it. Measured against Metal's - /// resolve on the M3 Max under macOS 27.0.1 (our probe `msaa_word_formats.m`, 256 pixels - /// at 2 and 4 samples per format): Metal's code in 74% to 88% of the channels resolved in - /// the pass that drew them, 90% to 99% (every one-bit alpha) of those a pass only loaded, - /// and within one code in every channel (`runtime_lane::word_samples_msaa`). - /// `RGB9E5Float`'s and an 8-bit sRGB format's word resolve is Metal's, every pixel. - WordResolve = "word-resolve", Precision, - "where a pixel's samples differ, a resolved channel can differ from Metal's by a code: \ - Metal averages its tile's values, finer than the codes the attachment's words hold"; - /// An attachment stored with `DontCare` (or the multisampled attachment of - /// `MultisampleResolve`) is Vulkan's `DONT_CARE`, where Apple's GPU keeps the earlier - /// texels unless its tiler overflows. Only on a driver measured to keep the earlier texel - /// or the stored one at each texel (`DriverFact::DontCareStoreIsOneOfMetals`); every other - /// device stores it (`STORE`), Metal's answer where its tiler overflows - /// (`render_target.rs`). Not a texture over a buffer the pass renders through an image it - /// copies nothing back from (a shadow, a stand-in: `kept_bytes.rs`), which keeps the - /// buffer's bytes, Metal's answer, nor, under `DontCareColorPolicy::Kept`, a texture's own - /// image stored `DontCare` that the pass renders through a backing its queue keeps - /// (`kept_bytes.rs`), which keeps its earlier texels, Metal's answer; only one whose image - /// the pass renders in place. Where the pass also loads the attachment `DontCare` and the - /// runtime clears it (`UnstoredDontCarePolicy`, `clear_reach.rs`), a tile no draw touches - /// holds zero (a color) or the clear value (depth, stencil) after the pass, where Metal's - /// holds its earlier texels. - DontCareStore = "dont-care-store", Precision, - "the attachment's texels after the pass are each its earlier texel or the one the \ - pass rendered, both Metal's answers, but not always the one Metal's tiler keeps; \ - where the pass loads it `DontCare` and clears it, a tile no draw touches holds zero \ - or the clear value"; - /// An attachment loaded with `DontCare` and stored, in a pass that draws, is cleared - /// before the draws to zero (a color) or its clear value (depth, stencil) over the render - /// area and the tiles past it a clear reaches (`clear_reach.rs`), where Metal clears only - /// the tiles a draw's primitives touch and keeps the texels of the others. An aspect of - /// separate depth and stencil textures the scratch image the pass renders them through - /// cannot load by a copy in (a multisampled aspect copied by draws, - /// `depth_stencil_scratch.rs`) is cleared over the render area in a pass whose draws do - /// not reach every tile, also one without a draw. Not one the pass does not store - /// (`dont-care-unstored-load`). - DontCareLoadTiles = "dont-care-load-tiles", Precision, - "the tiles no draw touches hold zero or the clear value where Metal keeps their \ - texels"; - /// An attachment loaded with `DontCare` and not stored (not memoryless; an aspect of - /// separate depth and stencil textures in the scratch image the pass renders them - /// through), in a pass whose draws reach a tile, is left to the driver's `DONT_CARE` load - /// under `UnstoredDontCarePolicy::Driver`, the default, on a driver not measured to clear - /// it no slower (`DriverFact::UnstoredClearNoSlower`), where Metal's draws read zero (a - /// color) or the clear value (depth, stencil) wherever they read it (`clear_reach.rs`). - /// Cleared, Metal's answer, and not announced on a driver with the fact and under - /// `UnstoredDontCarePolicy::Cleared`. - DontCareUnstoredLoad = "dont-care-unstored-load", Precision, - "the pass's draws read what the driver's `DONT_CARE` load leaves in the attachment \ - (on lavapipe its earlier texels) where Metal's read zero or the clear value"; - /// On a device that presents an Apple silicon Mac's compression - /// (`DeviceProperties::lossless_compression`, `MacClass::AppleSilicon`; never on one that - /// presents a Mac with an Intel or AMD GPU, whose new `Private` texture holds what its - /// memory held or reads zero), a new `Private` texture Metal keeps - /// losslessly compressed reads a fixed pattern in Metal - /// (`texture/heap_tiled.rs`'s `fresh_pattern`), which the device cannot write - /// exactly into its image: a NaN depth where a copy into a depth image may store it - /// clamped or the image is multisampled, a NaN texel of a multisampled image (whose bits - /// a clear leaves to the device), or an image holding other bytes than Metal's texel. The - /// texture reads zero there. Announced where a command first reads a texel of that content - /// no clear, resolve or blit covered (a pass that loads it, a blit or a shader that reads - /// it), in the order the command buffers are committed, whatever order or thread they were - /// encoded in: at the commit of the command buffer that holds the read, not as the - /// texture is made (`fresh_unwritten.rs`). - FreshPatternZeroed = "fresh-pattern-zeroed", Precision, - "the new texture reads zero where Metal reads its fixed pattern until a write"; - /// An indexed draw from an index offset at or past its index buffer's length draws index - /// 0 plus the base vertex at each position, a direct draw from a zero-padded copy - /// (`draw_source.rs`) and an indirect one through the index bounds pass - /// (`index_bounds.rs`), where Metal reads the memory past the buffer. - ZeroedIndexFetch = "zeroed-index-fetch", Precision, - "each index position draws index 0 plus the base vertex, where Metal reads whatever \ - memory follows the buffer"; - /// A pipeline stage's reconvergence after divergence is implementation-defined on the - /// device, where Metal's is maximal - /// ([`Reconvergence::ImplementationDefined`](metal2vulkan::pipeline::Reconvergence)). - ImplementationDefinedReconvergence = "implementation-defined-reconvergence", Precision, - "simdgroup operations after divergent control flow can see other lanes active than \ - Metal's"; - /// A live sampler state the device's sampler tables do not map to it for some commands - /// (`heap_sets.rs`), which reach every other live state by its ID as they run: one whose - /// element no set-1 sampler array can hold, as more states live than it holds (each - /// takes the lowest element no live state holds, `resource_ids.rs`), the device's as the - /// state is made, or a pipeline's as a command is encoded or the state made - /// (`sampler.rs`, `compute.rs`, `heap_sets.rs`), each such command buffer counted once - /// (`WorkCounts::unlisted_argument_sampler_buffers`); one at an ID neither window of the - /// tables reaches (IDs 0 to 32767, and 32768 from the first ID past them, a - /// reservation's); one whose Vulkan sampler for an array's use the device cannot make or - /// the use refuses (a feature the device lacks), that array holding the neutral at its - /// element; a cubic state, for a command whose stage does not test the states it reaches - /// for a cubic filter (a fragment stage never does); and one whose elements could not be - /// written. Where it happens: past the device's update-after-bind sampler limit or the - /// heap capacity of a pipeline (65536 on the M3 Max under MoltenVK), past 32768 live - /// states above a reservation, a cubic state live while a render pipeline samples - /// argument samplers, or a device's sampler limit (`maxSamplerAllocationCount`). - UnlistedArgumentSampler = "unlisted-argument-sampler", Precision, - "a function reading the state through its ID in an argument buffer reads the \ - neutral sampler, where Metal's reads the state"; - /// An upload (`replace_region`, a blit from a buffer, a copy from a colour texture, a fill - /// of a multisampled texture) into the 32-bit float depth of a texture's depth image, on - /// a device without `VK_EXT_depth_range_unrestricted` enabled (ANV on the Iris Xe, - /// MoltenVK on the M3 Max), where Vulkan takes no copied value outside `[0, 1]`: the - /// upload clamps each value into `[0, 1]`, a NaN to 1.0, as the device stores it - /// (`depth_clamp.rs`). And a render pass's NaN clear depth on such a device, which Metal stores as `0x7fc00000`, cleared to 1.0 - /// (`nan_clear.rs`). And a heap's texture of such a depth whose shadow's copies in move the - /// heap's bytes into its image, announced as it is made: the copies in clamp each value - /// into `[0, 1]`, a NaN to 1.0, as the device stores it, and its copies back write each - /// value as the image stored it, one no command wrote too (`texture/heap_tiled.rs`). - RestrictedDepthUpload = "restricted-depth-upload", Precision, - "a value outside [0, 1] may be stored clamped to [0, 1], where Metal's keeps it, so \ - reads, samples, comparisons and depth tests of it can differ"; - /// An indirect dispatch (`dispatchThreadgroupsWithIndirectBuffer:...`, - /// `dispatchThreadsWithIndirectBuffer:...`; `indirect_dispatch.rs`), or a dispatch after - /// `setStageInRegionWithIndirectBuffer:indirectBufferOffset:`: its arguments or its - /// stage-in region are GPU memory the work before it may write, so they are known only once - /// that work completed. - HostReadDispatchArguments = "host-read-dispatch-arguments", Performance, - "one GPU-to-CPU round trip per dispatch: a copy of its arguments where it is \ - encoded, then its command buffer's work before it, and every batch submitted \ - before that on any queue, completes before the CPU reads them and records the \ - dispatch they state; the device's scheduler submits nothing else meanwhile, and a \ - threadgroup size its pipeline state has not dispatched makes that VkPipeline then"; - /// A sparse texture (`sparse/texture.rs`) on a device whose sparse residency is not - /// `residencyNonResidentStrict`. - NonStrictResidency = "non-strict-residency", Precision, - "a read of a texel no mapped tile holds, by a function or a copy, answers the \ - device's value where Metal's reads zero, and a write to one may be kept where \ - Metal's drops it"; - /// An indirect mapping update of a sparse texture (`sparse/indirect.rs`), whose regions the - /// host reads. - HostReadMappingArguments = "host-read-mapping-arguments", Performance, - "one GPU-to-CPU round trip per batch of such updates: the command buffer's work \ - before it, and every batch submitted before that on any queue, completes before \ - the CPU reads the regions (through a copy for a Private buffer) and binds them; \ - the device's scheduler submits nothing else meanwhile"; - /// A sparse texture (`sparse/emulated.rs`) the device makes no sparse image of (MoltenVK - /// binds no sparse memory), where no function reads an image's own residency (the device - /// does not enable `shaderResourceResidency`): an ordinary image whose unmapped tiles the - /// runtime keeps at zero, which gives Metal's answers. - EmulatedSparseTexture = "emulated-sparse-texture", Performance, - "the texture holds its whole image's memory from when it is made, where Metal's backs \ - only its mapped tiles; each batch that changes its mappings zeroes the tiles it \ - unmaps and rewrites its tile map before its work, and each blit that writes it \ - zeroes the unmapped tiles it wrote"; - /// A `Shared` buffer or heap the program makes with the default CPU cache mode, on a - /// device without unified memory (`DeviceProperties::has_unified_memory`), lies in - /// host-cached system memory, which the host reads quickly (`memory.rs`'s - /// `MemoryClass::Shared`), as a shared resource's on a Mac with a discrete GPU. - SharedInSystemMemory = "shared-in-system-memory", Performance, - "the GPU reads and writes it across the bus, as a discrete Mac's GPU does a shared \ - resource: coalesced accesses at the bus's speed, and scattered writes far slower \ - (4-byte stores 12 bytes apart at 0.08 GB/s on an RTX 3090, where device-local \ - memory takes them at 850 GB/s)"; - /// A buffer or heap of `Private` storage the program makes, a `Managed` buffer's own bytes - /// on a device without unified memory (`managed.rs`), or a texture's image, of any storage - /// mode (`image_plan.rs` places each in `Private` memory), lies in system memory: no - /// device-local memory type the resource takes had room for it, and it takes a type that - /// is not device-local (`memory.rs`'s `overflow_candidates`), as Metal makes such a - /// resource past a discrete GPU's memory rather than refuse it. Each such placement is - /// counted (`WorkCounts::device_memory_overflows`). A `Managed` no-copy buffer there, - /// whose GPU copy found no room in device-local memory, lies in the caller's pages as a - /// `Shared` one does (`managed_copy.rs`, `WorkCounts::managed_device_copies_in_place`). A driver may instead page device-local - /// memory out to make room rather than fail the allocation - /// (`VK_EXT_pageable_device_local_memory`, enabled where the device lists it with its - /// feature); what it pages, it places, and nothing overflows. - DeviceMemoryOverflow = "device-memory-overflow", Performance, - "the GPU reads and writes it across the bus, at the bus's speed, for as long as it \ - lives; resources made once device-local memory has room again lie there"; - /// `generate_mipmaps` of a filtered format (not an integer one, whose texels are picked as - /// plain Metal picks them): each level is the device's linear filter of the one above at - /// the scaled texel centres, its blit chain (`vkCmdBlitImage` with `VK_FILTER_LINEAR`, - /// `mipmap_plan.rs`) where its blits filter the image's format, else the runtime's - /// bilinear (trilinear in 3D) filter in `float` (`mipmap_filter.rs`): an extended-range - /// format, an 8-bit sRGB texture held as its UNORM twin, or a format without blits or - /// linear filtering, by the device's arithmetic: its products and sums as it contracts - /// them, an 8-bit or extended-range sRGB code through the MSL transfer by its `Pow` (as - /// `srgb-texel-decode` reads the twin), a half by its widening and narrowing, a NaN its - /// own (`metal2vulkan::bind::MipmapFilterChain::outside_bound` states the bound). Neither - /// is Apple's datapath, whose answers also differ between Apple's GPUs (an M3 Max's and an M4's by up to a unit in the last place, and wholly - /// where a box averages a float format's largest and smallest values). Announced once per - /// device; no bound against Metal's answer is measured. - DeviceFilteredMipmaps = "device-filtered-mipmaps", Precision, - "each level is the device's linear filter of the one above (its blit, or a bilinear \ - filter in float where its blits cannot filter the format), not Apple's: a channel \ - can differ from Metal's where the filtered value lies near a rounding boundary, and \ - wholly where a box averages infinities, NaNs or a float format's extremes"; - /// A depth or stencil texture made in a heap on a device whose driver lays depth and - /// stencil images apart from the memory they are bound to - /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]) that no shadow of the - /// heap's bytes serves: a multisampled texture, which Vulkan copies to and from no buffer, - /// or one whose texels do not fit its bytes. The texture aliases - /// none of the heap's other resources, where Metal's lies in the heap's bytes. - HeapDepthStencilApart = "heap-depth-stencil-apart", Precision, - "the texture's texels lie apart from the heap's bytes: a write through a buffer or \ - texture over its bytes changes none of them, and its writes change none of those \ - resources' bytes, where Metal's texture aliases them"; - /// A colour texture made in a heap on a device whose driver's compressed images hide - /// writes through an alias - /// ([`metal2vulkan::device::DriverFact::CompressedImagesHideAliasedWrites`]), whose image - /// takes host-transfer usage, which the driver keeps uncompressed in the heap's bytes - /// ([`metal2vulkan::device::DriverFact::HostTransferImagesKeepTheirBytes`]). Also, on any - /// device, a single-sample colour texture Metal keeps compressed, or whose layout Metal's - /// model does not state, whose image of the route it first took takes more bytes or a - /// coarser alignment than Metal's answer, where this one fits the answer: it lies in the - /// heap's bytes in place of a shadow of them (`texture/heap.rs`). - HeapTextureHostTransfer = "heap-texture-host-transfer", Performance, - "the texture's image is kept uncompressed, so writes through the heap's buffers and \ - textures over its bytes show in it as Metal's do: a clear of it loses the driver's \ - fast clear (334.5 us where a compressed 2048x2048 RGBA8Unorm image's took 4.1 us on \ - an RPL-S), while its copies, sampling and blending measured no slower"; - /// A colour texture made in a heap on such a device whose image takes no host-transfer - /// usage (the device did not enable `hostImageCopy`, or an adopted device's consumer did - /// not say so, or the format or shape takes none there): a linear image, which the driver does not compress, where one does all the - /// optimal image does for the texture. Also, on any device, a single-sample colour - /// texture whose image of the route it first took takes more bytes or a coarser - /// alignment than Metal's answer, where no image of host-transfer usage fits the answer - /// and a linear one does: it lies in the heap's bytes in place of a shadow of them - /// (`texture/heap.rs`). Of a texture Metal keeps uncompressed, whose bytes are Metal's - /// tiles, only a linear image whose every element lies where those tiles place it (a - /// level of one element or one row), and no image of host-transfer usage. - HeapTextureLinear = "heap-texture-linear", Performance, - "the texture's image is linear, so writes through the heap's buffers and textures \ - over its bytes show in it as Metal's do: its reads and writes go without the \ - optimal tiling's locality and compression (3.9 to 9.6 times the host-transfer \ - image's time for copies, clears and draws of a 2048x2048 RGBA8Unorm texture on an \ - RPL-S)"; - /// A colour texture made in a heap on such a device whose image takes neither - /// host-transfer usage nor linear tiling: an optimal image the driver may compress, a - /// near-equivalent recorded open. - HeapTextureHidesAliasedWrites = "heap-texture-hides-aliased-writes", Precision, - "the driver may compress the texture's image: a write through a buffer or texture \ - over its bytes may leave texels as they were, and its writes may show in those \ - resources' bytes compressed, where Metal's texture aliases them byte for byte"; - /// A colour texture made in a heap on such a device that Metal keeps losslessly - /// compressed too (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or - /// `ShaderAtomic` usage, 16 texels or more a side), under - /// [`metal2vulkan::device::HeapCompressionPolicy::Compressed`], the default: the - /// driver's compressed optimal image, its fast clears kept. - HeapTextureCompressed = "heap-texture-compressed", Precision, - "the driver may compress the texture's image, as Metal compresses the texture: a \ - write through a buffer or texture over its bytes may leave texels as they were, \ - where Metal's texture reads opaque magenta (0xffff00ff) in every texel of drawn \ - content the write covered and the written bytes where it held only a clear (an M3 \ - Max), and its writes may show in those bytes compressed otherwise than Metal's; \ - HeapCompressionPolicy::Uncompressed keeps the image uncompressed in the heap's bytes, \ - whose clears then lose the driver's fast clear"; - /// A render creation that fails on a binary-archive miss, made from one add's vertex - /// stage and another add's fragment stage: Metal's vertex key holds the vertex outputs - /// its compiler finds the fragment reading, which the runtime's lookup does not decode - /// (`binary_archive::metal_key`). - CombinedArchiveStages = "combined-archive-stages", Precision, - "the pipeline is made where Metal may refuse it with a binary-archive miss: Metal \ - misses when the two adds' fragment functions read different vertex outputs"; - /// A texture view is an image of its own, a shadow of the viewed image's texels, where - /// that image takes no Vulkan view of its format: a view of another component layout on - /// a device whose Vulkan views reinterpret no image's components (a portability subset - /// without `imageViewFormatReinterpretation`, or an adopted device whose consumer did not - /// say it enabled it), or a view of a texture made without `PixelFormatView` usage in - /// another format than the texture's own, its sRGB twin's and, where the texture renders - /// and is `RGBA8Unorm`, `BGRA8Unorm` or a twin of one, its channel-order sibling's and - /// that sibling's twin's (`texture/view_shadow.rs`). - /// A view in other channels of its image's bits (an `A8Unorm` view of an `R8Unorm` - /// texture) is the image itself to its bindings, through a swizzle, and takes a shadow - /// only for a pass that renders into it: Vulkan views the image in no format of the - /// view's. - ShadowedTextureView = "shadowed-texture-view", Performance, - "its texels are copied from its texture's image before each use and back after each \ - write"; - /// A render encoder executes an indirect command buffer's commands from a command it - /// executed them from before with another length, each range given - /// (`executeCommandsInBuffer:withRange:`) or read from a buffer - /// (`executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`; - /// `render/executions.rs`): Metal's executions then do not each run their own range, and - /// not the same way from run to run, on an Apple M3 Max and an Apple M4 alike, so no - /// stable answer exists. - RepeatedExecutionStart = "repeated-execution-start", Precision, - "each execution runs its own range, as Metal documents, where Metal's GPU may run \ - one execution with the other's length, so commands run more or fewer times than \ - the ranges name, differently from run to run"; - /// A command predication record (`encode_start_if`, a loop's start, a live DoWhile's - /// end) whose condition word lies past its buffer's end, past the 256 bytes Metal rounds - /// a lone buffer up to, or past the end of the heap the buffer lies in - /// (`predication.rs`): Metal reads whatever its own address space holds there, a - /// neighbouring buffer's bytes or zero, which depends on where Metal placed memory - /// unrelated to the buffer. - PredicationWordPastBuffer = "predication-word-past-buffer", Precision, - "the record reads its word as zero, where Metal reads what lies at that address in its \ - own address space: zero where nothing is there, another buffer's bytes where Metal \ - placed one"; - /// A heap of the runtime's memory or an indirect command buffer made with - /// `MTLResourceOptions` bit 24 - /// ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), which Metal - /// makes and keeps the GPU's - /// writes from the memory of (the M3 Max under macOS 27.0.1, `read_only_view.rs`: what a - /// shader or the blit engine writes reaches neither the CPU nor a later command buffer, - /// which read the memory's bytes -- a blit's fill, a kernel's stores, a vertex- or - /// fragment-stage store, and a store through an address loaded out of an argument buffer, - /// each completing with no error; a later command of the same command buffer may read them, - /// as the GPU's caches hold them, which is not stable; while what a render pass's own - /// machinery writes **faults** the command buffer -- a colour attachment over that memory, - /// a resolve into it, a depth or stencil attachment in a heap of the bit, and a blit into a - /// texture over or in it), is - /// made as without it, and reports its options without it, as Metal's does. A no-copy - /// buffer or heap with the bit drops the GPU's writes as Metal's does: on macOS its pages - /// imported through a read-only view of them (`read_only_view.rs`), announcing nothing; - /// elsewhere made over a copy of them that drops them (`copied-host-pages`). - /// A buffer of the runtime's memory or a texture descriptor with the bit is refused, as - /// Metal ends the process there; a buffer placed in a heap without the bit is made as - /// without it, as Metal's is, announcing nothing. - PrivateResourceOption = "private-resource-option", Precision, - "the GPU's writes reach the resource's memory, the CPU and later command buffers, \ - where Metal's never reach them"; - /// A depth or stencil texture with `allowGPUOptimizedContents` off sized or made in a heap - /// (never a device's own texture, whose layout nothing shows), on a device whose driver - /// keeps depth and stencil images GPU-optimized whatever their create info - /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesStayGpuOptimized`]), that no - /// shadow of Metal's tiles in the heap's bytes serves (a multisample texture, a format - /// whose layout is not measured; `texture/heap.rs`): Metal lays the texture out - /// without its compression metadata, and the runtime's image keeps it. - OptimizedDepthStencilTexture = "optimized-depth-stencil-texture", Precision, - "the texture's image keeps the GPU-optimized layout Metal drops with the property \ - off, so its bytes in the heap are not Metal's layout of its texels (where they lie \ - instead, and what moving them costs, heap-texture-untiled-layout and \ - shadowed-texture name for the shapes they cover); heap_texture_size_and_align \ - answers Metal's own size and alignment for the descriptor wherever the runtime \ - models them, and the larger of the images' and Metal's for a texture whose images \ - need more bytes or a coarser alignment that no shadow of the heap's bytes holds it \ - to, where a heap sized by Metal's answers holds fewer such textures"; - /// A texture of an IOSurface plane of more than one row under 16 bytes a row - /// (`Buffer::new_texture_with_iosurface_plane`, `linear_plan.rs`): Metal's GPU writes its - /// rows 16 bytes apart and reads every row past the first as memory-dependent bytes - /// (zeros in a fresh process; after a write, bytes neither the surface's nor written). - NarrowSurfaceRows = "narrow-surface-rows", Precision, - "a GPU read of a row past the first reads the bytes the GPU's writes put there, 16 \ - bytes a row apart, where Metal's GPU reads memory-dependent bytes; CPU access and \ - the GPU's writes and first row are Metal's"; - /// A texture of an IOSurface plane whose rows share bytes on Metal's GPU - /// (`Buffer::new_texture_with_iosurface_plane`, `linear_plan.rs`): more than one row of - /// over 16 bytes whose `bytesPerRow` rounded down to 16 is below the row, so consecutive - /// rows share 1 to 15 bytes, a whole number of texels; or, over a plane whose offset and - /// `bytesPerRow` are multiples of 16, rows wider than `bytesPerRow`, which share bytes on - /// the CPU too, any whole number of texels, a byte shared by as many rows as reach it. - /// Metal's reads see the sharing and so do the runtime's, through a shadow whose copy - /// regions hold it; but where rows' writes meet the shared bytes take whichever row - /// Metal's command wrote last, and that order is no one order (an Apple M3 Max under - /// macOS 27.0.1, one case a process, `probes/overlapping_plane_row_writes.m`): it follows - /// the command, the GPU pitch and the row count, a kernel's winner moving with the - /// threadgroup shape. A kernel is the only GPU writer such a plane takes here, every blit - /// into one being refused (`linear_plan.rs`'s **Rows that overlap**), so the earliest - /// row's bytes are one of the rows a kernel of Metal's leaves there. The CPU's writes of - /// rows wider than the pitch leave the latest row's, as Metal's `replaceRegion` does. - CollidingSurfaceRowWrites = "colliding-surface-row-writes", Precision, - "where the plane's rows write the bytes they share the earliest row's stand, one of \ - the rows a kernel of Metal's leaves there, whose winner moves with the threadgroup \ - shape; reads, CPU access and every other byte are Metal's"; - /// A texture of an IOSurface plane of a surface with planes, which Metal makes, some of - /// whose texels it lays out in no one place (`Buffer::new_texture_with_iosurface_plane`, - /// `linear_plan.rs`'s **Beyond the plane's rows**; an Apple M3 Max under macOS 27.0.1, - /// `probes/surface_texture_envelope.m`): its texels past the buffer standing for its - /// surface, where its blits read zeros, its kernels zeros and, 32 KiB past the plane, the - /// plane's rows again, its `getBytes` zeros and other memory, and its writes change no - /// byte of the surface; and a 2D array's slices past its first, which its blits and - /// `getBytes` read at the plane's offset, over the first slice, its kernels one image on, - /// and its writes put at the plane's offset. - SurfaceTexelsTail = "surface-texels-tail", Precision, - "those texels lie in a tail of the texture's own, zero when made, which every path \ - reads and writes alike and which reaches no byte of the surface; its texels in place \ - are Metal's"; - /// A texture over a plane of an IOSurface with planes whose texels Metal lays out in no - /// one place, its first level's and slice's among them - /// (`Buffer::new_texture_with_iosurface_plane`, `linear_plan.rs`'s **Beyond the plane's - /// rows**): a 2D texture of more than one level, a 3D texture and a 2D multisample one. - /// Metal makes it, and on an Apple M3 Max under macOS 27.0.1 - /// (`probes/surface_texture_envelope.m`) its GPU reads those texels from other bytes than - /// its writes and its CPU put them; the x86 Macs under macOS 26.7.1 keep its first level - /// and slice over the plane. - SurfaceTexelsApart = "surface-texels-apart", Precision, - "its texels lie in memory of its own, zero when made, which every path reads and \ - writes alike, and no byte of the surface's; Metal's GPU and CPU reach the surface's \ - bytes in no one place"; - /// A pipeline state's function may read an argument its function constants removed (a - /// texture's read, sample, gather, query or atomic, or a sample through a removed - /// sampler; `RuntimeFact::AbsentArgumentRead`), which Metal gives no value: its compiler - /// drops or folds such a read, and with its debug layer every such read is zero (measured - /// on an M3 Max and an M4). - AbsentArgumentRead = "absent-argument-read", Precision, - "such a read takes zero, Metal's answer under its debug layer, and the command \ - buffer completes, its execution report stating the read (absent_argument_read); \ - without the layer Metal's compiler drops or folds the read instead"; - /// A render pass whose one depth/stencil texture stores and resolves its depth - /// (`StoreAndMultisampleResolve`) while it resolves its stencil alone - /// (`MultisampleResolve`), which Metal's validation stops (`resolve::layout_patterned`). - MixedDepthStencilResolve = "mixed-depth-stencil-resolve", Precision, - "both aspects resolve and the depth's samples are kept, as the store actions \ - document, and the stencil's samples are kept too, where Metal's GPU overwrites the \ - depth's samples and its resolve texture with a layout pattern of the resolved depth \ - and leaves the stencil's texels (measured on an Apple M4)"; - /// A draw whose functions read or write, other than as an attachment, memory an - /// attachment of its render pass instance renders, where no copy or snapshot serves the - /// access (`texture/attached_reads.rs`): a texture reached through a handle or an - /// argument buffer, a storage binding of a color attachment's texture, the depth or - /// stencil attachment's texture, a texture buffer or a buffer over its bytes, a texture - /// whose copy is not served, or an execution's command. Announced where the - /// draw records; the payload names its call. - AttachmentReadInPlace = "attachment-read-in-place", Precision, - "the access sees the attachment as the device holds it inside its render pass \ - instance, which Vulkan leaves undefined (`VUID-vkCmdDraw-None-10795`), where Metal's \ - read at the draw's own pixel gives the texel from before the pass"; - /// A sampler state whose `maxAnisotropy`, which Metal's validation stops past 16, plain - /// Metal samples with an anisotropy past the device's largest (`maxSamplerAnisotropy`): - /// 17 to 31 in its low five bits, which Metal samples with 32 (`sampler.rs`). - CappedAnisotropy = "capped-anisotropy", Precision, - "it filters with the device's largest anisotropy (16 on every venue measured), where \ - Metal filters with 32: a footprint more than 16 times as long as it is wide reads a \ - coarser level than Metal's (one level coarser at 32 to 1 and beyond)"; - /// A sampler state whose `lodBias` the GPU of the Mac the device presents adds to every - /// sample's level (`MacClass::IntelOrAmd`), where the device's samplers cannot add it as - /// it is (`metal2vulkan::metal::sampler::DeviceLodBias`, whose state carries - /// `PrecisionNote::CappedLodBias`): past the device's - /// `maxSamplerLodBias` (an infinity included), a NaN, or a bias other than 0 where the - /// device's portability subset withholds `samplerMipLodBias` (MoltenVK). Announced once, - /// where the device makes the state; the payload names the bias and what the device's - /// samplers add for it. - CappedLodBias = "capped-lod-bias", Precision, - "its samples add the device's limit of the bias's sign where the bias is past it, and \ - no bias where the device withholds it or the bias is NaN: a sample whose level with \ - what the device adds has not reached the last level the sampler reads (a positive \ - bias) or level 0 (a negative one) reads another level than Metal's, which adds the \ - whole bias and then clamps the level into the texture's levels; what Metal samples \ - for a NaN bias is not measured"; - /// A sampler state with anisotropy, no mip filter (`NotMipmapped`) and different - /// minification and magnification filters, on a device that samples through Metal's own - /// sampler (MoltenVK on Apple's GPU, `DriverDeviation::MetalSampler`): Vulkan has no - /// sampler without mipmapping, so the device's sampler takes a nearest mip filter with the - /// level clamp `[0, 0.25]`, which keeps Metal's choice of filter, and Metal's anisotropic - /// filter reads no such clamp as Metal's `NotMipmapped` (`sampler.rs`). Announced once, - /// where the device makes the state; the payload names its anisotropy and filters. A - /// constexpr sampler of that shape records `NotMipmappedAnisotropicFilter` instead. - NotMipmappedAnisotropicSampler = "not-mipmapped-anisotropic-sampler", Precision, - "a sample at an implicit level or with gradients through it filters another \ - anisotropic footprint than Metal's at `maxAnisotropy` 2 to 16"; - /// A command whose function reads texture handles from memory (an argument buffer, or - /// any memory holding a texture's resource ID) has a texture the runtime holds as raw - /// blocks for copies (a PVRTC texture on a device without its format, `pvrtc.rs`) - /// made resident, or bound in a stage that reads handles: the handle's element is the - /// neutral texture, as the runtime does not know which of the textures it reaches the - /// function reads. - UnreadableHandleTexture = "unreadable-handle-texture", Precision, - "a read or sample of the texture through its handle reads the neutral texture where \ - Metal's decodes its blocks; a function that reads it at a slot is refused \ - (Unsupported(Format))"; - /// A texture that a heap array's class fits, but whose format the array cannot view (one - /// the device cannot sample, or store without a format, or one whose raw texels need its - /// function's decode): the device's heap set holds the class's neutral at its ID, which a - /// command that names the texture refuses instead (`heap_sets.rs`). A texture buffer a - /// texel-buffer class fits that no texel view of its bytes in place reaches (its - /// bindings view a staging buffer or its tail, its offset is off - /// `minTexelBufferOffsetAlignment`, it holds more texels than `maxTexelBufferElements`), - /// or whose swizzle or format a texel view cannot present, is the class's neutral there - /// too, whether a command names it or not (`buffer_texture.rs`). - UnnamedTextureUnviewable = "unnamed-texture-unviewable", Precision, - "a function reading the texture through its ID, in a command that does not name it \ - (bind it, or make it resident), reads the neutral texture where Metal's reads the \ - texture"; - /// A shadowed texture (a buffer's texels or a view's, which a shadow image holds as the - /// encoders that name it copy them in, `shadow.rs`) in the device's heap set - /// (`heap_sets.rs`). An encoder names it by binding it or making it resident, and so does - /// each later compute or render encoder of a command buffer that made it resident - /// (Metal's residency lasts the command buffer). Announced at the first command that binds - /// a heap set holding its view while neither naming it nor making it resident; one that - /// does has its shadow copied in, and a set no command binds announces nothing. - UnnamedShadowedTexture = "unnamed-shadowed-texture", Precision, - "a function reading the texture through its ID, in a command that does not name it, \ - reads the texels an encoder that named it last copied in (undefined before any \ - did), where Metal's reads the texels as they stand"; - /// A live texture whose resource ID is past the elements of a pipeline's set-1 heap - /// arrays (their count, the device's update-after-bind limits shared among the - /// pipeline's arrays), so the texture table a command binds misses it (`heap_sets.rs`). - UnnamedTexturesPastCapacity = "unnamed-textures-past-capacity", Precision, - "a function of such a pipeline reading the texture through its ID reads the neutral \ - texture where Metal's reads the texture; a command that names it is refused \ - (Bind(HeapTooLarge))"; - /// A heap set on a device without `descriptorBindingUpdateUnusedWhilePending`, which - /// writes no set a pending command buffer binds: each command buffer binds a copy of its - /// own, written as it first binds the set and until it commits (`heap_sets.rs`). - HeapSetCopied = "heap-set-copied", Precision, - "each command buffer's first command that binds the set writes a copy of it (every \ - element a texture's ID may name, and every sampler array's, per array); a function \ - reading a texture through its ID reads the texture that held the ID as its command \ - buffer committed, and one reading a sampler state the state that held it as the \ - command buffer's first batch was submitted (the neutral where none did, or where it \ - was released before that submission), where Metal's reads the one holding it as \ - the function runs"; - /// A draw of a render pipeline state in a pass with a color at no place of the state's - /// per-sample record, under a state color that blends through a destination factor of - /// the fragment's output (`SourceAlpha`, `OneMinusSourceAlpha`, `SourceColor`, ...) and - /// reads the destination no other way (`color_reformat.rs`). - UncoveredColorKept = "uncovered-color-kept", Precision, - "the pass's color keeps its contents where the draw covers it, as Metal keeps them \ - for an output it computes; where Metal's compiler folds the output to a constant that \ - zeroes the factor (an alpha of the literal 1 under `OneMinusSourceAlpha`), Metal \ - stores zero there (measured on an Apple M4)"; - /// A blit copy into a multisampled 32-bit float depth texture from a colour one, a render - /// pass's separate multisampled 32-bit float depth texture copied to and from its scratch - /// image (`depth_stencil_scratch.rs`), or a heap's such texture held as a shadow of its - /// samples in Metal's tiles, which takes the heap's bytes (`texture/heap_tiled.rs`; then a - /// value the draw changes is written back to the heap's bytes changed, announced as the - /// texture is made), by the sample-rate `FragDepth` draw (`sample_copy.rs`, - /// `depth_copy.rs`), on a device whose copies go by draws and whose - /// driver's fragment depth is not measured to store every value unchanged - /// (`depth_copy::drawn`): measured to change some values (MoltenVK, NVIDIA's), or not - /// measured at all (any other driver, and lavapipe releases not measured). Both copies - /// take the one decision and announce through `depth_copy::announce_changes`. The reason - /// names the values that driver changes, or, on a driver not measured, those Vulkan leaves - /// to it (outside `[0, 1]`, denormals, -0). - DrawnDepthCopy = "drawn-depth-copy", Precision, - "each sample's depth is written by a fragment-depth draw, where Metal copies its \ - bytes: the values the driver's fragment depth changes or may change, which the \ - reason names, can land changed; every other value lands as Metal's copy leaves it"; - /// A texture bound by a slot as a storage image without `ShaderWrite` usage, or as a - /// sampled one without `ShaderRead`, whose image lacks that usage because adding it - /// would cost the image its size or the driver's compression, or, for an image in place - /// over host pages, because the device's check failed for what the usage lets reach them - /// (`texture/in_place_image.rs`): the binding takes an image of its own with both shader - /// usages, a shadow of the texture's texels (`texture/usage_shadow.rs`). Also a texture - /// without `RenderTarget` usage that a render pass renders as an attachment, through a - /// scratch image that has it (`attachment_stand_in.rs`), but one in place whose image took - /// the attachment usage where the device's check passed for renders over its pages. - UndeclaredUsageShadow = "undeclared-usage-shadow", Performance, - "its texels are copied into an image of its own before each command that binds it \ - beyond its declared usage, and back after each write through it"; - /// A texture of `RGB10A8_2P_XR10` or its sRGB twin made in a heap (`texture/heap.rs`) - /// whose planes no shadow of the heap's bytes holds: one whose moves pass the device's - /// limits (`texture/heap_two_planes.rs`). Its one image holds each texel's - /// colour word and alpha byte side by side, more than Metal's two planes take in the - /// heap, so it lies in memory of its own. - HeapTwoPlaneTexture = "heap-two-plane-texture", Precision, - "the texture's size and alignment answers are Metal's and its reads, writes and \ - copies as outside a heap, but its texels lie in memory of its own, apart from the \ - heap's bytes: a buffer or texture over its range of the heap neither sees nor \ - changes them, where Metal's texture keeps its two planes there"; - /// A texture of `RGB10A8_2P_XR10` or its sRGB twin made in a heap whose first level's - /// planes lie in the heap's bytes (`texture/heap_two_planes.rs`), of more than one level, - /// or a 1D array: Metal's paths address the texture's levels past the first at bytes that - /// differ by path (its CPU copies at its first level's rows from past that level, its - /// blits and an array's GPU writes over the first level's bytes, a 2D texture's GPU - /// writes nowhere, its GPU reads at other bytes again), and a 1D array's GPU reads every - /// texel at the texture's first word. The runtime keeps the first level's slices in the - /// heap's bytes, as Metal's CPU copies and GPU writes lay them, and the other levels in the - /// texture's image alone. - HeapTwoPlaneLayout = "heap-two-plane-layout", Precision, - "the first level's texels lie in the heap's bytes as Metal's CPU copies and GPU \ - writes lay them, and read as written; the later levels' texels lie apart from the \ - heap's bytes, and a 1D array's GPU reads read each texel, where Metal's paths \ - address those texels at bytes that differ by path"; - /// A texture of one of Apple's one-plane YCbCr formats (`YCBCR8_422_1P`, - /// `YCBCR10_444_1P` and their twins, held for copies alone) made in a heap whose texels - /// lie otherwise than Metal's blits lay them (`texture/heap.rs`; an Apple M3 Max under - /// macOS 27.0.1, `probes/one_plane_ycbcr_heap_rows.m`): a 2D texture or array of more - /// than one row whose row is under 16 bytes, whose rows Metal lays 16 bytes apart, past - /// the texture's answer, and whose copies out read none of the rows past the first back - /// from there, where the runtime lays them one packed row apart, as that answer counts - /// them; and a mipmapped or 3D texture, whose texels Metal lays at bytes that differ by - /// path, its first level past its answer, where the runtime keeps them in memory of its - /// own, apart from the heap's bytes. Every other such texture lies as Metal lays it, rows - /// of 16 bytes or more off a multiple of 16 the row rounded down to 16 bytes apart among - /// them. Announced once per device, in the call that made the first such texture. - HeapOnePlaneLayout = "heap-one-plane-layout", Precision, - "the texture's size and alignment answers are Metal's and its copies read what they \ - wrote, but its texels lie in the heap's bytes one packed row apart, or apart from \ - the heap's bytes, where Metal's blits lay its rows 16 bytes apart or its levels at \ - bytes that differ by path: a buffer over the heap meets them at other bytes than on \ - Metal"; - /// A MoltenVK device at a release whose `pipelineCacheUUID` layout the runtime has not - /// read (`device/argument_buffers.rs`): whether MoltenVK binds through Metal argument - /// buffers is unknown, so a device without them is not refused (as at a read release). - /// Announced when the device is made. - MoltenVkArgumentBuffersUnread = "moltenvk-argument-buffers-unread", Precision, - "whether MoltenVK binds through Metal argument buffers is not read at this release: \ - with MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS off, Metal's compiler can crash on large \ - fragment functions' pipelines, and argument buffers hold fewer resources than \ - Metal's"; - /// A blit between two textures of `RGB10A8_2P_XR10` or its sRGB twin - /// (`two_planes.rs`) whose answer is not Metal's measured one: one the runtime copies - /// texel for texel (textures of more than one level or slice, a copy within one - /// texture, a level larger than a storage buffer), or one whose rows overlap in the - /// destination, or of a texture narrower than 4 texels, where Metal's blit writes in an - /// order that varies or reads bytes from outside the planes, or one reading bytes outside - /// the source's texels that an earlier blit wrote there (or a heap's texture's), which - /// Metal's blit keeps and reads back. Into a heap's texture whose planes lie in the - /// heap's bytes (`two_planes/heap_bytes.rs`): a copy whose alpha bytes pass the heap's end, - /// which Metal's blit writes past it, one reading a source's alpha bytes past its heap's - /// end, and one whose bytes pass a storage buffer, copied texel for texel. - TwoPlaneTextureCopy = "two-plane-texture-copy", Precision, - "where Metal's answer was measured (2D textures of one level and one slice) the \ - copy moves both planes' bytes as Metal's blit does, at its own rows; here it \ - copies both words of each texel, where Metal's blit moves bytes at those rows and \ - so loses or moves texels, or it keeps the later row where the copy's rows overlap \ - (Metal's blit writes them in an order that varies), or it reads as 0 the bytes \ - Metal's blit reads from outside the texels: from outside the planes below a width \ - of 4, and those an earlier blit left in a row's padding or past a plane, which \ - Metal keeps"; - /// A draw in a render pass that loads a color attachment of an extended-range, padded - /// 10-bit or bfloat format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, - /// `RG10Unorm_X12` and their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat` - /// and `RGBA16Bfloat`) and does not discard it at the store (`render/tile_store.rs`). - /// Metal's pass, once it draws, writes each 32 x 32 tile a draw reaches back with the bits - /// its codes leave unused made canonical, a padded sRGB twin's codes through Metal's table - /// and a bfloat code through `half` (a NaN to `0x7fc0`), the texels no fragment writes and - /// the channels a write mask leaves out too (on an Apple M4 and an Apple M3 Max), where - /// the device's pass keeps the bytes its draws do not write, on every device. Announced at - /// every draw, an indirect command buffer's executed commands' too, naming every such - /// attachment of the pass. Also a GPU blit into, out of or between textures of which one - /// is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed, and a - /// fill of one (`compressed_blit.rs`): Metal's blit moves the texels through the - /// compression, which clears the same bits and clamps the same alpha (its fill clears the - /// bits alone), where the device's copy keeps the bytes; once per device, under - /// `ExtendedRangeBlitPolicy::Kept` (the default). Under `Canonical` the runtime writes - /// Metal's encoding, and announces only a blit out of one into a buffer whose words the - /// device cannot bind or into a texture over a buffer whose rows share bytes. - ExtendedRangeBitsKept = "extended-range-bits-kept", Precision, - "the texels the pass's draws do not write keep their bytes; Metal's pass rewrites, in \ - each tile a draw reaches, the bits their codes leave unused (BGR10_XR's bits 30 and \ - 31 to ones, BGRA10_XR's low six bits of each field, the two-plane color word's top \ - two bits and a padded word's low six bits to zeros), clamps BGRA10_XR's alpha code \ - to [384, 894], moves a padded sRGB twin's code through its table and a bfloat code \ - through half (out of half's range to an infinity or zero, a NaN to 0x7fc0): a texel \ - whose bytes no Metal write left (uploaded bytes, an alpha code past 894, a bfloat \ - code off half's grid) keeps bytes Metal's pass would change, and a blit through a \ - BGRA10_XR texture Metal compresses keeps the bytes Metal's blit rewrites so; an \ - extended-range texel reads the same value either way, a bfloat code off half's grid \ - reads its own value where Metal's reads the half it was moved to"; - /// A draw in a render pass that loads a single-sampled color attachment of a signed - /// normalized format (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, - /// `RGBA16Snorm`) and does not discard it at the store (`render.rs`). Metal's pass, once - /// it draws, writes each 32 x 32 tile a draw reaches back through its channels' values, - /// so a channel's minimum code (-128, or -32768), which reads as -1.0 as the code above - /// it does, is stored as that code (-127, or -32767), in the texels no fragment writes - /// too (measured on an Apple M3 Max under macOS 27.0.1: every such code of each tile a - /// draw reaches, none in other tiles, none in a pass that draws nothing or through a - /// blit), where the device's pass keeps the bytes its draws do not write. Announced at - /// every draw, an indirect command buffer's executed commands' too, naming every such - /// attachment of the pass. Not where `DriverFact::TileStoreIsMetals` holds (MoltenVK's - /// pass is a Metal pass, whose tile store rewrites the codes as Metal's does). - SnormMinimumKept = "snorm-minimum-kept", Precision, - "the texels the pass's draws do not write keep their bytes; Metal's pass rewrites a \ - channel's minimum code (-128, or -32768 for 16 bits) as the code above it (-127, \ - -32767) in each tile a draw reaches: a texel whose bytes no Metal write left \ - (uploaded or copied bytes) keeps a code Metal's pass would change"; - /// A draw in a render pass that loads a single-sampled `RGB9E5Float` color attachment and - /// does not discard it at the store (`render.rs`). Metal's pass, once it draws, writes - /// each 32 x 32 tile a draw reaches back through its texels' values, so a word whose - /// largest mantissa is below 256 under an exponent above 0 is stored normalized: its - /// mantissas shifted up a bit as its exponent steps down one, until the largest reaches - /// 256 or the exponent 0 (measured on an Apple M3 Max under macOS 27.0.1: the format - /// scout's draw over uploaded words, 22 of 143 untouched texels of the reached tile - /// normalized, none other changed), where the device's pass keeps the bytes its draws do - /// not write. Announced at every draw, an indirect command buffer's executed commands' - /// too, naming every such attachment of the pass. Not where `DriverFact::TileStoreIsMetals` - /// holds (MoltenVK's pass is a Metal pass). Also a GPU blit into, out of or between - /// textures of which one is an `RGB9E5Float` texture Metal keeps losslessly compressed - /// (`compressed_blit.rs`): Metal's blit moves the texels through the compression, which - /// normalizes every word so, where the device's copy keeps the bytes; once per device, and - /// not where the device's copy of the compressed image is Metal's blit - /// (`RuntimeDriverDefect::CompressedImageCopiesRewriteTexels`: MoltenVK). - SharedExponentKept = "shared-exponent-kept", Precision, - "the texels the pass's draws do not write keep their words; Metal's pass normalizes \ - a word whose largest mantissa is below 256 (its exponent above 0) in each tile a \ - draw reaches, and Metal's blit through an RGB9E5Float texture it compresses every \ - such word: a texel whose bytes no Metal write left (uploaded or copied words) keeps \ - a word Metal would change, of the same value"; - /// A blit between a buffer and a level of `RGB10A8_2P_XR10` or its sRGB twin whose width - /// is not a multiple of 4 (`two_planes.rs`), where Metal's blit addresses the level's rows - /// `⌊4 w / 16⌋ · 16` bytes apart, short of where they lie, and so moves texels into and - /// out of other rows and the bytes between them. A 2D texture or array of one level is - /// blitted at Metal's rows (`two_planes/buffer_rows.rs`), the row whose bytes Metal's GPU - /// leaves where two meet standing; announced here are a blit into a texture 32 texels wide - /// or wider whose rows meet, which keeps the earlier row's bytes where Metal's GPU writes - /// the two in an order that varies from run to run (narrower, `two-plane-buffer-blit-order`), - /// and a blit out of a texture of the - /// device's memory that reads bytes between its rows after a copy from another texture - /// wrote some there, which reads them as its fills and blits with a buffer left them (held - /// apart, `Texture::between_rows`). Any other such texture (more levels, a view, 1D, 3D, - /// a surface's) moves the texels at the rows the texture holds them in, announced. - TwoPlaneBufferBlit = "two-plane-buffer-blit", Precision, - "where rows meet in a blit into a texture 32 texels wide or wider the earlier row's \ - bytes stand, where Metal's GPU writes them in an order that varies from run to run, \ - at some sizes never all the earlier row's; a blit out of a \ - texture of the device's memory reads the bytes between its rows that a copy from \ - another texture wrote as its fills and blits with a buffer left them, where Metal's \ - reads the copy's back; and a texture of more than one level, a \ - view, a 1D or 3D texture or a surface's moves its texels at the rows it holds them in, \ - where Metal's blit addresses its rows floor(4w/16)*16 bytes apart"; - /// A blit from a buffer into a level of `RGB10A8_2P_XR10` or its sRGB twin narrower than 32 - /// texels, at a width not a multiple of 4, whose rows meet between Metal's groups of 32 - /// rows of the region (`two_planes/buffer_rows.rs`): Metal's GPU writes the two rows there - /// in an order that varies from run to run (the earlier row's bytes at 556 of 560 such - /// meetings in our probes), and in its fixed order at every other meeting. The runtime - /// keeps the earlier row's bytes there and Metal's order elsewhere: Metal's most frequent - /// whole outcome. - TwoPlaneBufferBlitOrder = "two-plane-buffer-blit-order", Precision, - "where the rows of two of Metal's groups of 32 meet the earlier row's bytes stand, \ - where Metal's GPU leaves either row's from run to run"; - /// A render pipeline state whose vertex function runs simdgroup functions on a driver - /// measured to run a vertex function's subgroup operations as Metal does though its - /// `subgroupSupportedStages` leaves the vertex stage out - /// ([`metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups`]): its pipeline - /// requires `VkProperty::MetalVertexSimdgroups` in place of the vertex stage's subgroups. - UnadvertisedVertexSimdgroups = "unadvertised-vertex-simdgroups", Validity, - "the device runs them as Metal does, but its driver leaves the vertex stage out of \ - subgroupSupportedStages, so Vulkan's validation layer reports each shader module of \ - the function (VUID-RuntimeSpirv-None-06343)"; - /// A descriptor set layout the device's driver refuses through - /// `vkGetDescriptorSetLayoutSupport` though it makes and runs it, a heap's set 1 past - /// `maxPerSetDescriptors` ([`metal2vulkan::error::RuntimeDriverDefect::SetLayoutSupportUnderstated`]): - /// the runtime makes it there as the driver runs it (`pipeline/objects.rs`). - SetPastLayoutSupport = "set-past-layout-support", Validity, - "the device runs the set as Metal runs the argument buffer it is encoded in, but its \ - driver's vkGetDescriptorSetLayoutSupport refuses the layout, so Vulkan's validation \ - layer reports each such layout (VUID-vkCreateDescriptorSetLayout-support-09582)"; - /// A render pipeline state whose fragment function writes a storage buffer of set 0 - /// inside its interlock (a buffer in a raster order group, or one a function that reads - /// its color attachment writes), on a driver that orders such a buffer between - /// overlapping fragments only where set 0 is pushed - /// ([`metal2vulkan::error::RuntimeDriverDefect::InterlockedBoundBuffersUnordered`]: - /// MoltenVK), where its set 0 is bound: the device has no push command, its set 0 is no - /// push descriptor set layout's, or a stage reads a buffer's length, which that driver's - /// pushed sets do not hold (`RuntimeDriverDefect::PushedBufferSizesUnset`; - /// `pipeline/objects.rs`'s `unordered_bind`). Every other such state pushes set 0 there, - /// and its fragments read each other's writes in order. - InterlockedBufferOrder = "interlocked-buffer-order", Precision, - "a fragment may read such a buffer as it was before an earlier overlapping fragment \ - of the draw wrote it, where Metal orders a raster order group's buffer after every \ - earlier fragment of the pixel"; - /// An indirect command naming the ID of a pipeline state the program released is - /// executed where the runtime cannot run what Metal runs (`indirect_command_buffer.rs`, - /// `released_programs.rs`). A command holds the program of the state the CPU set on it, - /// and runs it while its record names the state's ID, whoever took the ID since, as - /// Metal's command the CPU encoded does; a record whose pipeline a kernel wrote - /// (`CommandRecord::kernel_pipeline`) runs the state that held the ID as the GPU last could - /// write the buffer's records, released since or not, as Metal's GPU write resolves the ID - /// to the state that took it last and its record runs that state after: the device keeps - /// the program of each freed ID's last holder while an indirect command buffer of it - /// lives, and a buffer the GPU may write keeps those and the ones released since. Those are - /// announced nowhere. Announced: a record the GPU wrote whose ID's holder then was a state - /// of the command's kind the program released, whose program the buffer does not keep - /// (released while no indirect command buffer of the device lived, or past the ID's last - /// four holders), which Metal runs, so the command runs nothing. A state of the other kind - /// holding the ID runs nothing, as on Metal, unannounced. Announced by the execution - /// alone, where the runtime records it: in `commit` of its command buffer, on the - /// committing thread, for one recorded from the CPU's records; in the host step, on a - /// thread of the runtime's, for one recorded there (records the GPU may write, a range a - /// buffer holds, or a render pass whose pipelines were still being made at the commit). - /// Reading the commands (`IndirectCommandBuffer::commands`) announces nothing. - ReleasedCommandState = "released-command-state", Precision, - "a command whose record the GPU wrote naming a state released while no indirect \ - command buffer of the device lived, or past the ID's last four holders, runs \ - nothing, where Metal runs that state's program"; - /// A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of - /// its planes where the device converts their format (`ycbcr_device.rs`): Vulkan's chroma - /// reconstruction at Metal's midpoint through a linear chroma filter, and the range - /// expansion and model conversion at the device's precision, unclamped where the device - /// does not clamp. Each channel lies within the device's precision of Vulkan's conversion - /// and off Metal's fixed-point read (lavapipe, Mesa 26.0.8, its 8-bit 4:4:4 layout, - /// random planes, every texel: within 0.04/2048 of Vulkan's conversion past the `half` - /// its image stores, and of Metal's within 6/2048 where the result lies in `[0, 1]`; - /// outside it by what Metal's clamp takes off). Announced at the texture's first - /// conversion, naming its layout: a texture whose planes every function reads in place - /// converts none, and announces nothing. So do the samples of a texture whose planes are read in place - /// through the device's conversion of a linear image of them (`texture/ycbcr_planes.rs`), - /// the device's filter of the codes too: announced where the image is made. - /// - /// And a pipeline stage's filtered sample of a texture slot bound to a two-plane YCbCr - /// texture, on a device that samples through Metal's own sampler (MoltenVK, - /// `VkProperty::MetalSampler`), does not take Metal's exact filter of the format: the stage - /// records `PrecisionNote::HalfSampleFilter` or `FloatSampleFilter` under any two-plane - /// YCbCr format bound there (`lower::sampler::linear`), the format the slot's binding - /// presents (a view in its texture's own format as another type, and a texture over a P3 - /// surface, present the code-reading format of their codes, whose image Metal's sampler - /// filters as that format's, so neither is announced), whose converted texels Metal's - /// sampler filters as an `RGBA16Float` or `RGBA32Float` texture's: within one step of the - /// format's grid of Metal's filter of the format, a `half` result within one `half` unit in - /// the last place (plain Metal on an Apple M3 Max under macOS 27.0.1, `YCBCR8_420_2P` and - /// its `_sRGB` twin against such a texture of the same texels). A device that samples - /// natively filters such a texture as its own sampler does, announced as `device-sampling`. - /// Announced, in place of those notes' own notices for the slot, where the specialized - /// pipeline is made, or at a draw or dispatch that binds such a texture there (through a - /// runtime sampler slot, only where the sampler bound there filters: a linear - /// minification, magnification or mip filter, anisotropy, or a cubic filter; one that - /// reads one texel of one level takes the texel the view holds, Metal's read), naming the - /// slot and the format; and at a draw or dispatch whose function filters a texture an - /// argument buffer holds where a texture the command makes resident or binds that its - /// handles can name is two-plane YCbCr, through an argument buffer's sampler only where a - /// live sampler state filters (which state the buffer's memory names is not read). - /// - /// And, on any device, a linear sample of a 4:2:0 texture whose planes the function reads - /// in place through a texel buffer by Vulkan's Y′CbCr model of the codes - /// (`YCbCrInPlacePolicy::Model`, the default; `lower::sampler::in_place`): the stage - /// records the same notes under the bound converted 4:2:0 format (through a runtime - /// sampler slot, only where the bound word filters linearly and addresses no border), - /// announced as above at a draw or dispatch that binds such a texture there. - YCbCrFilterNotExact = "ycbcr-filter-not-exact", Precision, - "where the device converts the planes' format, the texels are its own Y′CbCr \ - conversion's, at its precision and unclamped where it does not clamp, not Metal's \ - fixed-point read; elsewhere the texels \ - hold Metal's reads exactly, but the sample filters them as the device does, off the \ - grid Metal sums the format's steps on, so a filtered result can miss Metal's by a \ - step of that grid or more"; - /// A render pass that draws loads and stores a rotated texture of rotation 4, whose load - /// is the plane transposed and whose store is rotation 1's (`rotated.rs`): every tile of - /// the frame lands mirrored, where Metal loads and stores only the 32x32 tiles a draw's - /// primitives reach and keeps the texels of the others in place. - RotatedLoadTiles = "rotated-load-tiles", Precision, - "the tiles no draw reaches land mirrored as the tiles it reaches do, where Metal keeps \ - their texels in place"; - /// A render pass that draws loads and stores a two-plane YCbCr texture - /// (`metal::format::ycbcr_renders`) whose draws reach the tiles their primitives touch - /// (`ycbcr.rs`): the pass stores every 32x32 tile of the rectangle bounding its draws' - /// scissors, each texel's codes re-encoded from the texel it loaded (its chroma the - /// filtered pairs), where Metal stores only the tiles a draw's primitives reach (the M3 - /// Max under macOS 27.0.1) and keeps the planes' bytes of the others. Announced at the - /// pass's end, naming the attachment. - YCbCrLoadTiles = "ycbcr-load-tiles", Precision, - "in the tiles no draw reaches the planes' codes are re-encoded from the texels the \ - pass loaded, the chroma from its filtered pairs, where Metal keeps their bytes"; - /// A draw that blends into a color attachment of a two-plane YCbCr texture - /// (`metal::format::ycbcr_renders`, `ycbcr.rs`): the device blends the pass's floats, - /// where Metal's tile blends halves, an 8-bit format's in half arithmetic (the source and - /// its alpha rounded to `half`, each product, and a fused sum), a 10-bit one's in `float` - /// rounded toward zero to `half` (the M3 Max under macOS 27.0.1, every code of 4096 - /// blended texels matched by those rules). Announced at the draw, naming the attachment. - YCbCrBlendRounding = "ycbcr-blend-rounding", Precision, - "a blended texel's codes can miss Metal's by one, where Metal's blend in half \ - arithmetic rounds otherwise than the device's in float, or over a texel an earlier \ - draw of the pass wrote (Metal holds it as a half)"; - /// A command buffer's command named a buffer over the caller's host pages (a binding, a - /// blit's operand, an attachment, a texture over the pages, an indirect command's - /// resolved buffer) that was rebound (`rebind_bytes_no_copy`) after the command was - /// encoded and before the command buffer was first submitted, or that a rebind on another - /// thread raced the command's encoding of (its call held the buffer while the rebind was - /// making what lies over its bytes again, or after, having begun before: `rebind.rs`'s - /// **Other threads**, `WorkCounts::encoders_raced_rebind`: a blit or logged render - /// encoder whose commit failed it or whose encoding again a call that answers otherwise - /// refused, as the calls of compute encoders and of render encoders that keep no log are - /// gated, `rebind::CallGate`, and never race one; and a rebind after the commit of a - /// command buffer with an encoder that keeps no log that named the buffer is refused - /// until its last submission, `Holds::hold_to_submission`) - /// (`CommandBufferError::EncodedUseRebound`, `command_buffer/first_submission.rs`), in an - /// encoder the runtime could not encode again (a compute encoder its unit of command - /// predication reaches past: one whose unit laid a step before it opened, or one of its - /// own that the unit's later encoders read, or whose unit holds a loop or leaves work - /// out; a render pass a host step records; work - /// recorded on the GPU alone that no longer runs there; a call that answers otherwise than - /// at its encoding; `replay.rs`). Its reason names where the first such submission found - /// the use (the encoder, and its own commands or work it left for later) and why no rebind - /// encoded or recorded it again. Announced once, as the first such submission is made, on - /// the scheduler's thread, which makes it: `DeviceOptions::announce_each` does not repeat - /// it, as no program call or host step meets it. - EncodedUseRebound = "encoded-use-rebound", Precision, - "each of Metal's submissions of the command buffer holding such a command runs \ - nothing and the command buffer fails (EncodedUseRebound), where Metal resolves the \ - use as it submits the command buffer and reaches the pages the buffer lies in then; \ - the rebind encodes compute, blit and render encoders again, but not this one"; - /// A command buffer that bound a heap set, whose commands may reach any texture through - /// its resource ID without naming it, was submitted while a texture's bytes (a no-copy - /// buffer's or heap's, the texture over them or in it) were detached - /// (`detach_backing`) after a submitted command buffer made them resident. Announced - /// once per device, at the first such submission, on the thread that makes it, with the - /// first texture's ID ([`DegradeNotice::object_id`]), whatever - /// `DeviceOptions::announce_each` says; each texture counted once - /// ([`Device::degraded_objects`](crate::Device::degraded_objects)). - StaleDetachedReach = "stale-detached-reach", Precision, - "a read of the texture that does not name it reads zero bytes (the stand-in its \ - detached bytes present), where Metal's reads the pages the program gave back, \ - which a correct program never relies on"; - /// A command buffer that bound a heap set, whose commands may reach any texture through - /// its resource ID without naming it, was committed while a texture of storage usage - /// was over detached bytes (`detach_backing`; made before the detach or while - /// detached): its stand-in has a sink its storage-class elements name. Announced once - /// per device, in the first such `commit`, with the first texture's ID - /// ([`DegradeNotice::object_id`]), or for each texture, in its first such `commit`, - /// where `DeviceOptions::announce_each` asks; each texture counted once - /// ([`Device::degraded_objects`](crate::Device::degraded_objects)). - DetachedStorageKeepsWrites = "detached-storage-keeps-writes", Precision, - "a read of the texture through a storage-class element (read or read_write access) \ - that does not name it reads what an earlier such write left in the stand-in's \ - sink, where Metal drops those writes and reads zero; a sampled read, and a size \ - query, are Metal's"; - /// A draw in a render pass over a rasterization-rate map of no layers that was made after - /// the device released a map of one or more layers, or reset from one of layers - /// (`rate_mapped_pass.rs`). The draw - /// writes nothing, where Metal draws: an Apple M4 and an Apple M3 Max drew a 64-pixel - /// map's physical rows 0 to 15 over a 64-pixel target at the positions of a pass with no - /// map, whatever map was released. Announced at the draw. - ZeroLayerMapAfterRelease = "zero-layer-map-after-release", Precision, - "the draws write nothing, where Metal draws rows of the pass (a 64-pixel map's rows 0 \ - to 15, at the positions of a pass with no map)"; - /// A render pass over a rasterization-rate map that was reset - /// (`RasterizationRateMap::reset_using_descriptor`) after the pass took it and before - /// its command buffer was submitted, in an encoder the runtime could not encode again - /// (it kept no log: a render encoder opened while a buffer of the device was detached, - /// or one that left work for a host step; - /// `rate_mapped_pass.rs`). The pass draws by the map as it took it, where Metal's GPU - /// reads the map as it runs the pass (the M3 Max under macOS 27.0.1). Announced at the - /// commit, or at the reset where the command buffer was committed. - RateMapResetUnencoded = "rate-map-reset-unencoded", Precision, - "the pass draws by the map as it took it, where Metal's GPU draws by the map as \ - reset"; - /// A texture made in a heap over host pages (`new_heap_with_bytes_no_copy`), or a depth - /// or stencil texture made in any heap as a shadow of Metal's tiles (on a driver that - /// lays such images apart from their memory or keeps them GPU-optimized: MoltenVK), that - /// Metal keeps losslessly compressed (`allowGPUOptimizedContents`, the shorter side of - /// level 0 16 texels or more, and a colour format of neither `ShaderWrite` nor - /// `PixelFormatView` usage, or a depth or stencil format): its bytes on Metal are no - /// layout of its texels, so the runtime lays them out as its own, its uncompressed tiles - /// where it tiles them (`texture/heap_tiled.rs`). A multisample texture so (its sample - /// grid's shorter side 16 or more) holds its samples in its uncompressed tiles, or, where - /// the device does not move its samples to and from a buffer, lies in memory of its own, - /// the heap's bytes keeping what they held. Also such a texture whose image lies in a heap - /// over the device's memory: the image, of the runtime's usage, need not be compressed as - /// Metal's. - /// Announced once per device, in the call that made the first such texture, with its ID - /// ([`DegradeNotice::object_id`]), or for each texture where `DeviceOptions::announce_each` - /// asks; each texture counted - /// ([`Device::degraded_objects`](crate::Device::degraded_objects)). - HeapTextureLosslessLayout = "heap-texture-lossless-layout", Precision, - "the texture's reads, writes and copies are Metal's, but its bytes in the heap are \ - not Metal's compressed bytes (its texels or samples in the runtime's layout, or a \ - multisample texture's image in memory of its own, the heap's bytes keeping what \ - they held): a buffer or texture over them reads and writes other bytes than Metal's \ - would"; - /// A texture of a block-compressed format made in a heap over host pages whose blocks' - /// placement is not measured: Metal places a format family's blocks in each level by a - /// rule that differs by family and by release (`texture/heap_tiled.rs`), measured at the - /// release every device answers as for the BC, ETC2, EAC, ASTC and PVRTC families (an - /// Apple M3 Max, and an Apple M4 alike but PVRTC), whose textures lie as Metal lays them - /// out; a format of none of them lies in the runtime's layout. Its size and alignment - /// answers are its device's. Announced once per device, in the call that made the first such - /// texture, with its ID ([`DegradeNotice::object_id`]), or for each texture where - /// `DeviceOptions::announce_each` asks; each texture counted - /// ([`Device::degraded_objects`](crate::Device::degraded_objects)). - HeapTextureBlockCompressedLayout = "heap-texture-block-compressed-layout", Precision, - "the texture's reads, writes and copies are Metal's, but its blocks lie in the \ - heap's bytes in the runtime's layout, where Metal tiles them: a buffer or texture \ - over them meets the blocks at other bytes than on Metal"; - /// A texture made in a heap over host pages that Metal lays out tiled where the runtime - /// does not (`texture/heap_tiled.rs`): its linear image bound to the pages, in the - /// driver's rows with no copy, wherever one serves (`texture/heap.rs`: Apple documents a - /// texture's layout in a heap's bytes as Metal's own, so a shadow of Metal's tiles there - /// is a fallback alone); a layout not measured (a format whose layout in - /// Metal's heaps is not probed), an image that holds other bytes than Metal's elements, - /// moves past the device's limits, or a multisample texture whose samples the device does - /// not move to and from a buffer (a 16-bit depth where its multisampled copies go by - /// draws whose codes the driver is not measured to keep), in memory of its own. Also a - /// texture made in any other heap (over the device's - /// memory) whose bytes there are not Metal's layout (`texture/heap.rs`): its image bound - /// there in the driver's layout, on a driver whose colour images are not measured to lie as - /// Metal's heap textures - /// ([`metal2vulkan::device::DriverFact::ColorImagesLieAsMetalHeapTextures`], and - /// [`metal2vulkan::device::DriverFact::MultisampleColorImagesLieAsMetalHeapTextures`] for - /// a multisample one) or of a depth or stencil texture there; its image a shadow of the - /// bytes in rows; or a layout not measured. The notice's reason names which (the first - /// texture's). Announced once per device, in the call that made the first such texture, - /// with its ID ([`DegradeNotice::object_id`]), or for each texture where - /// `DeviceOptions::announce_each` asks; each texture counted - /// ([`Device::degraded_objects`](crate::Device::degraded_objects)). - HeapTextureUntiledLayout = "heap-texture-untiled-layout", Precision, - "the texture's reads, writes and copies are Metal's, but its texels lie in the \ - heap's bytes in the runtime's layout, where Metal tiles them: a buffer or texture \ - over them meets the texels at other bytes than on Metal"; - /// A render pass's draws test the depth in the fragment shader (`depth_stand_in.rs`): a - /// fragment function that stores a color through the pixel interlock before Vulkan's tests, - /// in a draw whose depth test may drop the fragment, tests the fragment's depth itself - /// against a stand-in of the depth, so it stores only what passes, as Metal stores only - /// after the tests. (Where the draw's stencil test acts too, it runs that first, against a - /// stand-in of the stencil.) - ShaderSideDepthTest = "shader-side-depth-test", Performance, - "a 32-bit float stand-in image of the depth per pass, which the depth is copied into \ - before each run of such draws and back from after it (through a staging buffer at \ - one sample, image to image or by a compute split and a fragment-depth draw at \ - more), each run in a render pass instance of its own under depth `ALWAYS` without \ - writes, its fragment shader testing and writing the stand-in in the pixel \ - interlock; where the stencil test acts too, an 8-bit stand-in of the stencil per \ - pass, copied in and back the same way (image to image at more than one sample) \ - under the stencil test off"; - /// A blit copy between overlapping regions of one texture's texels, other than a region - /// onto itself (`blit_texture.rs`): Metal's copy reads as `memmove`'s for regions up to a - /// few hundred texels across, but past that some texels read what another part of the - /// copy already wrote, differently from run to run. The runtime gives - /// `memmove`'s answer every time: the source regions go through a scratch buffer, read - /// whole before any destination texel is written. - OverlappingTextureCopyAsMemmove = "overlapping-texture-copy-as-memmove", Precision, - "the destination holds the source's texels as they were before the copy, memmove's \ - answer, which is Metal's for small regions, where Metal's copy of a larger region \ - races and differs from run to run; the source goes through a scratch buffer, two \ - copies instead of one"; - /// A draw whose render pipeline state blends into, or reads (a framebuffer fetch, or the - /// interlocked storage form an extended-range blend takes), a color attachment of an - /// extended-range format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB - /// twins) or a padded 10-bit one (`R10Unorm_X6`, `RG10Unorm_X12`, their sRGB twins, - /// `RGB10A2Unorm_sRGB`) that an earlier draw or execution of render commands of the same - /// render pass may have written, or whose clear Metal's tile holds between two codes - /// (`render.rs`); an execution of render commands in a pass with such an attachment, - /// whose commands may blend onto each other. Metal's tile memory holds such an attachment - /// as `half` through the pass (a clear's, a load's, a write's or a blend's value rounded - /// to `half`; a padded one's past `[0, 1]` unclamped) and rounds it to its codes once, at the store (on - /// an Apple M4; the M3 Max's run of the same probes, and for the padded formats the M3 - /// Max's), where the runtime stores the codes at each draw, so a later blend or read sees - /// the stored codes. Not a color whose `half` shadow the runtime holds, which is never a - /// padded one's (`render/extended_shadow.rs`): in a pass of one layer on a - /// device that orders framebuffer fetch through the pixel interlock alone, or through - /// input attachments (lavapipe) with the pixel interlock, fragment stores and `Rgba16f` - /// storage images (multisampled ones at more than one sample), from the pass's clear or - /// (at one sample) its load, a draw's blend or read sees the `half` Metal's tile holds. - /// In a multisampled pass that loads the color, and once a draw ends the shadow, the - /// codes stay. Over input attachments in a pass that holds no shadow it also names a draw - /// that writes some of an extended-range word's codes under a mask (`BGR10_XR`'s, a - /// two-plane format's color word), whose function reads the word only to keep the other - /// codes, exactly: the pipeline's state does not tell that read from the function's own - /// fetch. - ExtendedRangeBlendsStoredCodes = "extended-range-blends-stored-codes", Precision, - "a blend into, or a read of, an extended-range or padded 10-bit color an earlier \ - draw of the pass wrote sees the codes the runtime stored at that draw (each channel \ - rounded to its 10-bit code, the two-plane format's alpha to its byte), where Metal's tile memory \ - holds the color as half through the pass and rounds it once at the store: a \ - blended or read value can differ from Metal's by a code, and the difference can \ - grow over many draws that blend onto each other"; - /// A heap texture sized or made (`heap_texture_size_and_align`, `Heap::new_texture`) whose - /// size Metal's layout the runtime does not model (`texture/heap_tiled.rs`): a format or a - /// sample count whose layout in Metal's heaps is not measured (8 samples; a mipmapped - /// texture Metal compresses and a `Depth32Float_Stencil8` one are). - /// The runtime answers its device's image's size and alignment there, which can differ from - /// Metal's either way. - UnmeasuredHeapTextureSize = "unmeasured-heap-texture-size", Precision, - "heap_texture_size_and_align answers the device's own image's size and alignment, \ - which may be larger or smaller than Metal's, so a heap sized by Metal's answers \ - may hold more or fewer such textures and they lie at other offsets"; - /// A program's call answered the `uniqueIdentifier` (`unique_identifier.rs`) of a - /// pipeline state made without `supportIndirectCommandBuffers` - /// (`ComputePipelineState::unique_identifier`, `RenderPipelineState::unique_identifier`, - /// a tile state's too). Metal's is an address of its allocations that differs from run - /// to run; the runtime's is one value of a count past every other identifier, with - /// Metal's relations: one value for the state's life, another state's another. - PlainStateUniqueIdentifier = "plain-state-unique-identifier", Precision, - "the identifier is one value of the runtime's count, unique and fixed for the \ - state's life, where Metal's is an address that differs from run to run"; - /// A program's call answered a `uniqueIdentifier` (`unique_identifier.rs`) Metal answers - /// alike in every run of one program started alike, which the runtime's is not measured - /// to be: a pipeline state's made with `supportIndirectCommandBuffers` - /// (`ComputePipelineState::unique_identifier`, `RenderPipelineState::unique_identifier`, - /// an indirect command's state identifier other than 0), or an indirect command buffer's - /// made after a command buffer of its device that encoded a render encoder was scheduled, - /// or after a resource state encoder opened (`IndirectCommandBuffer::unique_identifier`). - /// Metal's is an address of its own allocation: a state's follows how the process was - /// started (an M3 Max's first such compute state answered `0x1000000280` from a test - /// binary, `0x100` more from a shell), the states' functions and what the process made; a - /// buffer's lies past the ranges Metal's own encoders took, a render pass's run by its - /// targets' sizes and what the device drew before. The runtime's keeps the relations a - /// program can rely on (a compute state's from one step into Metal's range, no workload's - /// first). A buffer made before answers Metal's number, quietly, past the pieces Metal's - /// blit, compute and render encoders took. - UnmeasuredUniqueIdentifier = "unmeasured-unique-identifier", Precision, - "the identifier is unique and fixed for its holder's life, and a released one is \ - reused as Metal reuses it, but it is not the number Metal answers there, which \ - follows how the process was started, what it made and Metal's own encoders' \ - allocations"; - /// A draw or dispatch that binds, at a texture slot, a texture whose format's numeric - /// class (float, signed or unsigned integer) is not the class the function declares there - /// and that its plan has no exact answer for (`PlanDiagnostic::CrossClassNeutral`): a - /// depth, stencil, extended-range or YCbCr texture, a depth slot, an atomic or `ulong` - /// access, a written storage slot over a swizzled texture, or an integer write to an - /// `RGB9E5Float` texture. The slot binds the declared type's neutral. Every other color - /// texture (storage slots, texture buffers, multisampled and sparse textures, writes, - /// `short` and `ushort` results and queries included) answers Metal's words and its real - /// size (the slot's `cross_class` variant) and announces nothing. Likewise a texture of - /// another numeric class an argument buffer names that the command reaches - /// (`PlanDiagnostic::CrossClassHeapNeutral`), where the function samples, gathers, writes - /// or atomically updates its heap class, or reads it with no exact answer (a storage or - /// multisampled texture, a `short`, `ushort` or `ulong` result, or a depth, stencil, - /// extended-range or two-plane texture); its reads and queries of a sampled color texture - /// of one sample answer Metal's words and announce nothing. - CrossClassTextureNeutral = "cross-class-texture-neutral", Precision, - "the function reads the slot's neutral texture (zero texels; zero size), where plain \ - Metal reads the texture in its format's own class and hands back its words as the \ - declared type"; - /// A draw or dispatch that binds an ASTC texture (LDR, sRGB or HDR, of any footprint, in - /// its own block or in a carrier) at a storage slot its function writes, or reads and - /// writes (`PlanDiagnostic::AstcStorageNeutral`): no Vulkan format of a block is a - /// storage image's, so the slot binds the declared type's neutral, and the writes leave - /// the texture's blocks as they were. Plain Metal completes the writes and stores bytes - /// no format defines into the blocks, the same for the same written value, and reads - /// the blocks' decode through a `read_write` slot (an Apple M3 Max under macOS 27.0.1, - /// our probe `astc_passes_writes_footprints`). A pass rendering into such a texture - /// announces nothing: Metal's leaves its blocks as they were too. - AstcStorageNeutral = "astc-storage-neutral", Precision, - "the function's writes to the texture are dropped, leaving its blocks as they were, \ - and its reads and size queries through the slot answer the neutral texture's (zero \ - texels), where plain Metal stores bytes no format defines into the blocks and reads \ - their decode"; - /// An execution of an indirect command buffer replayed on the host ran a command that - /// holds a nil buffer set at an offset whose low 32 bits are not 0. Metal's function sees - /// those bits as the buffer's address (a pointer into no buffer); the host replay binds - /// no buffer there, so the function sees none. An execution the GPU replays alone passes - /// the bits, as Metal does. - IndirectNilBufferOffset = "indirect-nil-buffer-offset", Precision, - "the function sees no buffer, a null address, where Metal's sees the nil buffer's \ - offset as its address; neither holds a buffer, so only the address's value \ - differs"; - /// A texture of a BC format (`BC1_RGBA` to `BC7_RGBAUnorm_sRGB`) made on a device whose - /// driver is not measured to decode its texels as Metal does (BC1 to BC3 - /// `DriverFact::ColorBlockDecodeIsMetals`: MoltenVK on Apple's GPUs, RADV on the 780M and - /// the RX 7900 XTX; BC4 and BC5 `DriverFact::ChannelBlockDecodeIsMetals`: MoltenVK on - /// Apple's GPUs; BC6H `DriverFact::Bc6hBlockDecodeIsMetals` and BC7 - /// `DriverFact::Bc7BlockDecodeIsMetals`: MoltenVK on Apple's GPUs, NVIDIA's on the RTX 3090 - /// and RTX 5080 Laptop GPU, RADV on the 780M, ANV on the Iris Xe of Raptor Lake-P, and - /// lavapipe's BC6H). Its image is its own BC image, which the device samples through its - /// own decode: a BC texture keeps no decoded twin (`texture/decoded_twin.rs` keeps twins of - /// carried textures alone). The bounds are the largest differences from Metal's texels - /// measured on random blocks of every format; a driver not named is unmeasured, and - /// validation derives no tolerance from them. - CompressedTexelDecode = "compressed-texel-decode", Precision, - "a read, sample or gather of its texels answers the device's decode of its blocks \ - (an sRGB form's code through the device's sRGB decode), where Metal interpolates \ - with 6-bit weights: a BC1 to BC3 channel up to 4/255 off Metal's on NVIDIA (615.71.09, the RTX \ - 3090 and RTX 5080 Laptop GPU; BC3's alpha 6/255), 3/255 on lavapipe, 1/255 on ANV; a \ - BC4 or BC5 channel up to 7.4/255 (signed 0.065) on NVIDIA, 1.3/255 (signed 0.013) on \ - ANV, 2.4/255 (signed 0.022) on lavapipe, and on RADV (Mesa 26.2.4, the Radeon \ - 780M) a signed texel with an endpoint of -128 up to 1.7/255; a BC7 channel a \ - `float` ulp on lavapipe; its blocks' bytes, copies and sizes are Metal's"; - /// A CPU copy into a texture with a decoded twin (`replace_region`) whose CPU copies go - /// on the host or the staging queue: its region is decoded on the CPU, on the device's - /// decode thread, and copied into the twin; the first command buffer that may read the - /// texture waits at its submission for that (every command buffer, where the texture is - /// untracked). The call itself waits for no GPU work, as Metal's does not: only for room, - /// while 256 MiB of written blocks wait for the thread (`texture/twin_decode.rs`). - CpuBlockDecode = "cpu-block-decode", Performance, - "the written blocks decoded on the CPU, on the device's decode thread split over up \ - to 8 threads, and their texels copied into the decoded twin on the host or the \ - staging queue: the first command buffer that may read the texture waits at its \ - submission for that (every command buffer, where the texture is untracked), and the \ - call waits only for room, while 256 MiB of written blocks wait for the thread"; - /// A texture of an ASTC LDR format (`ASTC_4x4_LDR` to `ASTC_12x12_LDR`, the sRGB forms - /// too) made on a device without that ASTC format (`textureCompressionASTC_LDR`), of an - /// ASTC HDR format (`ASTC_4x4_HDR` to `ASTC_12x12_HDR`) on a device without its `SFLOAT` - /// block (`textureCompressionASTC_HDR`; of the committed device profiles, every one but - /// MoltenVK's), of a - /// PVRTC format on a device without it (`VK_IMG_format_pvrtc`'s RGBA formats; the RGB ones - /// on every device), or of an ETC2 or EAC format on a device without them - /// (`textureCompressionETC2`): its blocks lie in an image of a carrier format whose blocks - /// are also 16 (ASTC, `EAC_RGBA8`, `RG11`) or 8 (PVRTC, the other ETC2 and EAC formats) - /// bytes, which copies and `get_bytes` move unchanged, and its samples read a decoded - /// twin, Metal's decode of the blocks (an ASTC error block's magenta, or an HDR one's NaN, - /// included) in codes: an ASTC LDR texture's and an EAC 11-bit one's each nearest Metal's - /// value (`decoded-texel-precision`), a PVRTC texture's, an ASTC sRGB one's and an 8-bit - /// ETC2 or EAC one's 8-bit codes, exact, an ASTC HDR texture's halves, exact, decoded - /// after each write into it (a PVRTC - /// texture's whole levels); a heap's texture whose image is a shadow of the heap's bytes - /// (`texture/heap.rs`), its whole twin after each copy in that moves its blocks. An ASTC - /// texture's first view in its other colour space gives - /// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`, - /// `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler - /// Y′CbCr conversion: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds - /// its texels as 8-bit codes, decoded in whole rows: the device's own conversion of its - /// pairs where it converts the format with Metal's reconstruction - /// (`decoded-texel-precision`; every decode then a GPU pass, its CPU copies through - /// submissions), else Metal's texels, exact; a heap's such texture, a shadow of the - /// heap's bytes in Metal's rows, its whole twin after each copy in that moves its rows. - /// One over a buffer's bytes (an IOSurface - /// plane's) has no carrier: its samples read an image of its texels alone, written from - /// the pairs where they lie at each copy in (`texture/surface_pairs.rs`). - CarriedDecodedTwin = "carried-decoded-twin", Performance, - "a carrier image of its blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), \ - and a decoded twin of 4 bytes a texel (R8G8B8A8; an ASTC HDR texture's halves, 8 \ - bytes a texel; an EAC 11-bit texture's \ - 16-bit codes, 2 bytes a channel, or its floats, 4 bytes a channel, where the device \ - does not take those codes), two for an ASTC texture viewed in both colour \ - spaces, and a decode after each write into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \ - submission; on the CPU, on the device's decode thread, where its CPU copies go on \ - the host or the staging queue; and a pass on the GPU after each copy in that moves \ - the blocks or rows of a heap's texture whose image shadows the heap's bytes"; - /// A texture with an ASTC LDR decoded twin (`carried-decoded-twin`) of 8-bit codes, or an - /// EAC 11-bit one of 16-bit codes: Metal decodes an ASTC LDR channel - /// to a 12-bit value (`C >> 4` over 4095 of the 16-bit interpolated channel `C`), which the - /// twin's R8G8B8A8 texels hold as the nearest 8-bit code (at most 1/510 off Metal's value). - /// It reads an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which the twin holds - /// as the nearest 16-bit normalized code (at most half a 16-bit step off). (An ASTC sRGB - /// texture's twin holds Metal's own 8-bit codes, which its slots read through the twin's - /// sRGB view, the device's decode: `srgb-texel-decode`.) And a 4:2:2 texture's twin where - /// the device converts its format with Metal's reconstruction (`ycbcr_device.rs`): it - /// holds the device's own sampler Y′CbCr conversion of the pairs (the identity model, the - /// chroma at the midpoint through a linear filter: 3 parts the texel's pair and 1 the pair - /// beside it, Metal's weights, at the device's precision), each channel as the nearest - /// 8-bit code with ties to even, where Metal's `(3 c + n + 2) >> 2` rounds its ties up: - /// within a code of Metal's where the device's sum is within half a code of the exact one - /// (MoltenVK 1.4.2 samples through Metal's own `GBGR422` and `BGRG422` texture unit). - /// Announced where a command may first read such a twin, not where the texture is made - /// (copies, blits, fills and CPU accesses move the carrier's blocks and read no twin): at - /// a command's sampled binding of the texture or of a view of it, at the first command - /// that binds a heap set holding the twin's view (a function may read it through its - /// resource ID, named or not), or as the view is placed in a heap set that a command - /// buffer which bound it and has not completed may read through. - DecodedTexelPrecision = "decoded-texel-precision", Precision, - "a read, sample or gather of its texels answers the nearest 8-bit code to Metal's \ - 12-bit value, at most 1/510 off it; an EAC 11-bit texture's, the nearest 16-bit \ - normalized code to Metal's 11-bit value, at most half a 16-bit step off it; a 4:2:2 \ - texture's, where the device converts its format, the nearest 8-bit code to the \ - device's own Y′CbCr conversion of its pairs, not Metal's decode"; - /// A command queue made for presenting - /// ([`Device::new_command_queue_for_presenting`](crate::Device::new_command_queue_for_presenting)) - /// on a device that reserved no `VkQueue` for presenting: its queue family has no queue - /// past the ones the round robin takes (MoltenVK's four families of one queue, RADV's and - /// lavapipe's single graphics queue). - SharedPresentQueue = "shared-present-queue", Performance, - "it submits to a `VkQueue` other command queues share, so a present that blocks under \ - its lock (FIFO on a window the compositor does not show, a wait for the queue's \ - idle at a resize) holds their submissions until it returns, where Metal's present \ - holds no other queue"; - /// A command queue moved onto a `VkQueue` with another command queue's work in flight - /// (`QueueSharingPolicy::Adaptive`, the default, on a device whose own check found its - /// GPU idle when consecutive work comes from another `VkQueue`: NVIDIA's driver, 56 to 62 - /// us a switch on the RTX 5080 Laptop GPU; `queue_share.rs`), as it made a command buffer - /// while it held no other uncompleted one. Announced once per device, on the thread that - /// made that command buffer, in `CommandQueue::command_buffer`, as the first such move is - /// made. Never on a device that has no two `VkQueue`s of one family to share (MoltenVK, - /// RADV, lavapipe), nor for a queue made for presenting or with - /// `Device::new_command_queue_unshared`, which never move and which no queue joins. - QueueSharing = "queue-sharing", Performance, - "its command buffers run in one `VkQueue`'s order with those of the command queues \ - that share it, where Metal's queues wait for each other only inside one command: \ - the first command buffer of each such queue whose GPU work, or whose wait on the \ - GPU for another `VkQueue`'s work, runs over 2 ms holds the command buffers the \ - others committed behind it for its whole length, and its later ones while its \ - queue holds work, until that queue moves at its next idle point; a command buffer's GPU start time includes the other queues' \ - work before it; QueueSharingPolicy::PerQueue keeps each command queue on the \ - `VkQueue` it took at its creation"; - /// A heap texture sized or made (`heap_texture_size_and_align`, `Heap::new_texture`) - /// whose images on the device need more bytes or a coarser alignment than Metal's answer, - /// which the runtime models (`texture/heap_tiled.rs`): under the default - /// `HeapAnswerPolicy::Device`, a texture whose image binds into the heap's memory, which - /// lies in that image (`texture/heap::device_heap_answer`); under - /// `HeapAnswerPolicy::Metal`, one that no shadow of its bytes holds to Metal's answer - /// (`texture/heap::held_to_metal`): not a multisample texture, whose image lies in memory - /// of its own, nor one whose planes or Metal's tiles fit its bytes. The answer is then the - /// larger of the two, since no image binds at Metal's offsets. Every other such texture - /// answers Metal's numbers and announces nothing here. Not where - /// `optimized-depth-stencil-texture` says why. - HeapTextureLargerThanMetal = "heap-texture-larger-than-metal", Precision, - "heap_texture_size_and_align answers more bytes or a coarser alignment than Metal's, \ - so a heap sized by Metal's answers holds fewer such textures, and they lie at other \ - offsets; each texture keeps its own bytes"; - /// A pass renders a color attachment whose texture's image is linear (a texture over a - /// buffer's memory, a no-copy buffer's host pages included) through an image its texture - /// keeps, where the device renders such an image only under - /// `VK_NV_linear_color_attachment`'s rule, that every color attachment of the render pass - /// instance be linear, and the pass breaks it: another of its color attachments is not - /// linear, or it resolves a multisampled attachment into the texture. The notice names - /// which. Where the pass loads it, the words the pass changed are merged back into the - /// texture's bytes, so no pixel its draws left as they were is written (`linear_merge.rs`). - LinearAttachmentCopies = "linear-attachment-copies", Performance, - "its texels are copied into an image the pass renders, and what the pass wrote is \ - merged or copied back after it"; - /// A pass renders a color attachment that it stores with `DontCare` (or resolves alone, - /// `MultisampleResolve`) and whose texture's image lies over the buffer the texture lies - /// in (a linear image over an ordinary buffer's memory) through an image its texture keeps, so that the buffer keeps its bytes, as - /// Metal's does (`kept_bytes.rs`): rendered in place, the pass would write them. Not where - /// the pass hands the attachment to a driver that stores `DONT_CARE` as Metal's own - /// `DontCare` (`DriverFact::DontCareStoreIsMetals`), one render pass instance the driver - /// runs unbroken: Metal keeps the bytes itself. - DontCareStandIn = "dont-care-stand-in", Performance, - "an image of the attachment's size, which its texture keeps for the queue, renders the \ - pass; a `Load` copies the buffer's texels over the render area into it before the \ - pass, and nothing is copied back"; - /// A no-copy buffer or heap released with a deallocator while a command buffer that may - /// still reach its pages holds them. Metal runs the deallocator at the release, even while - /// a command buffer in flight reaches the buffer unnamed, and that command buffer's later - /// accesses reach nothing (the M3 Max under macOS 27.0.1, probe `dealloc-probe4`: through a - /// loaded pointer, and through an indirect command the GPU encoded with the buffer's - /// address). Vulkan frees no memory that submitted commands may still use - /// (`VUID-vkFreeMemory-memory-00677`: all submitted commands that refer to memory must - /// have completed execution), and keeps imported pages mapped while imported, so the pages - /// stay, and the deallocator runs once they go (`buffer.rs`): - /// - with no keep-alive ([`KeepAlive`](crate::KeepAlive)), while the device's import of - /// them is held: a command buffer submitted before a texture over them was released may - /// still read that texture through its resource ID, and its image holds the import until - /// the command buffer completes (`heap_sets.rs`); - /// - with no keep-alive, while a buffer made over part of its bytes, or over the same - /// bytes as memory of another class, while it lived is bound inside its import and holds - /// it (one live import of a page, as `VK_EXT_external_memory_host` leaves a page imported - /// twice into one device undefined: `buffer.rs`'s `Inside`; - /// `WorkCounts::host_releases_held_inside`), until that buffer goes; - /// - with no keep-alive, while a live buffers' table that lists them is held: a command - /// buffer whose commands may reach the buffer unnamed holds its first submission's table - /// and its host steps' until it completes, and one a rebind encoded again, or a host - /// step recorded, before its first submission until then (`live_buffers.rs`); - /// - with no keep-alive, on a device whose driver fails pending work where memory a - /// device-address buffer lay in is freed - /// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`: MoltenVK), while the - /// batches submitted before the import's memory went are in flight (`freed_memory.rs`); - /// - with no keep-alive, a detached buffer's or heap's rebind or release while the pages - /// its detach let go of are still imported, as above: the deallocator its detach held - /// back (Metal runs it at the replace or the release) runs once they go (`detach.rs`). - /// - /// With a keep-alive the deallocator runs at the release, as Metal's, and the import keeps - /// the keep-alive, which keeps the pages mapped, until it is freed: not announced. - /// - /// Announced once per device, on the thread that lets go of the buffer last, whatever - /// `DeviceOptions::announce_each` says: that may be a runtime thread, as a command - /// buffer that used the buffer completes, outside any program call or host step. - HostDeallocatorDelayed = "host-deallocator-delayed", Precision, - "the deallocator runs once every command buffer that may still reach the pages \ - (through a texture over them, or a table of the live buffers it holds) lets go of \ - them, every buffer bound inside their import goes, or the batches submitted before \ - the import's memory went complete, where Metal's runs at the release; the pages stay \ - mapped until then"; - /// A no-copy buffer, a no-copy heap or a buffer's rebind was made over a copy of the - /// caller's host pages in memory of the device's own, which no import maps (`copied.rs`; - /// a heap's textures shadows of its bytes): the caller's gate - /// (`HostMemory::with_import_gate`) refused the pages' import, or the device refused the - /// pointer's import and no dma-buf of the pages served it, the caller giving no source of - /// them (`HostMemory::with_dma_buf`) or one that failed or whose dma-bufs the device - /// refused (RADV refuses shared memory, a `memfd` mapping among it, and a device without - /// `VK_EXT_external_memory_host` every pointer, - /// `WorkCounts::copied_host_buffers_device_refused`), or the import the device - /// and the gate admitted failed, of the pointer or of the caller's dma-bufs (out of - /// memory, or another Vulkan error, such as a driver out of the mappings the host kernel - /// allows), or the runtime kept pages the kernel cannot pin from a driver whose failed - /// import of them breaks it (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`) and no - /// dma-buf of them served; or, on Linux, the process maps some of the pages read-only, - /// whose pointer drivers pin for writing and whose dma-bufs would take the GPU's writes - /// (`WorkCounts::copied_unwritable_pages`), the gate asked first where the pointer would - /// be imported; or, off macOS, the memory is of Metal's private option bit 24 - /// (`ResourceOptions::PRIVATE_BIT`), which no import there keeps the GPU's writes from, and - /// which is copied without asking the gate (`WorkCounts::copied_read_only_memory`). A copy - /// of pages the process maps read-only, or of bit-24 memory, drops the GPU's writes, as - /// Metal drops them: never written to the pages (`WorkCounts::copied_dropped_bytes`; the - /// detail says so). The reason names which of these it was; for a failed import, the - /// import's error, or the pages' unpinnable mapping and whether a dma-buf source was asked. - /// A copy whose own allocation fails refuses the call (`OutOfMemory`). - /// Announced once per device for each reason the detail names (the gate's refusal, the - /// device's, a failed import, bytes moved in their page, bit-24 memory, pages mapped - /// read-only, and a buffer lying in another's live copy), by the call that makes it, or - /// at each such call where `DeviceOptions::announce_each` asks. Counted: - /// `WorkCounts::copied_host_buffers_made`. - /// Each such buffer, and each buffer placed in such a heap, answers - /// [`Buffer::host_backing`](crate::Buffer::host_backing) with `HostBacking::Copied` until - /// its next rebind or detach. - CopiedHostPages = "copied-host-pages", Precision, - "the GPU uses a copy of the bytes, into which each commit writes every byte the CPU \ - changed in the pages since, and from which each batch's completion writes back \ - every byte the GPU changed, where Metal's GPU reads and writes the pages \ - themselves: a CPU write the GPU reads mid-command-buffer, or a GPU write the CPU \ - reads before the batch completes, is not seen; each commit compares, of the copies \ - its command buffer uses (every copy where a command may reach memory no use \ - names), every byte of one whose pages carry no log of their writes (only the pages \ - its log reports written where they do), and each completion every copy its batches \ - may have written"; - /// Batches of command buffers committed on one queue that the scheduler found ready - /// together, or held while two or more earlier submissions of their queue ran, went to the - /// driver in one `vkQueueSubmit`, only the last signalling its queue's timeline and their - /// events (`CompletionPolicy::Grouped`, the default, on a driver whose queue - /// merges a submission that signals nothing into the next one: Mesa's drivers; - /// `command_buffer/group.rs`; under `CompletionPolicy::Exact`, batches of command buffers - /// marked to join the next, `CommandBuffer::set_completion_joins_next`, and the batch - /// found ready behind them): one kernel submission for up to four batches. Announced - /// once per device, on the scheduler's thread, as the first such submission is made, - /// whatever `DeviceOptions::announce_each` says: no program call or host step meets it. - GroupedCompletion = "grouped-completion", Precision, - "each command buffer of the submission but the last is seen complete (its status, \ - completed handlers and waits), and the event values it signals are reached, once \ - the last completed, late by the GPU time of the batches after it, at most three, \ - never early and in commit order, and a submission held while earlier ones of its \ - queue ran late besides by any gap between the last of those and its own start on \ - the GPU, at most a completion turn's reaction and its vkQueueSubmit; and the \ - submission checks of the batches behind \ - a queue's next one run with its own, before the batch before them is submitted; \ - their commands, barriers and GPU times are unchanged; CompletionPolicy::Exact \ - submits and checks each batch alone but those of a command buffer marked to join \ - the next (CommandBuffer::set_completion_joins_next), which go with the batches \ - found ready behind them in the same pass, the last of those seen complete at its \ - own end"; - /// A command buffer's completion sync file (`CommandBuffer::export_completion_sync_file`) - /// whose command buffer's completion writes the caller's pages on the host after its GPU - /// work: the merge back of a copied host buffer its commands may have written - /// (`copied-host-pages`), or the copy out of a two-copy buffer into pages no import maps - /// (`managed_copy.rs`). A GPU signal would come before those writes, so the export waits on - /// the host for the command buffer's completion and answers a sync file already signaled - /// (`None`). Announced once per device by the export that meets it, or at each where - /// `DeviceOptions::announce_each` asks. Counted: - /// `WorkCounts::sync_files_after_host_copies`. - SyncFileAfterHostCopies = "sync-file-after-host-copies", Performance, - "the export blocks the calling thread until the command buffer completed and its \ - host copies landed, where an export after its GPU work's submission returns at once \ - and the importer waits on its own GPU"; - /// A draw whose `VkPipeline` the driver failed to make after the draw returned (the - /// runtime makes a draw's pipeline while the draw goes on, `render/pending.rs`) ran - /// nothing: its recording records the barriers and the visibility query around it and no - /// draw, and the command buffer runs on without error. Metal makes a render state's - /// pipelines inside `newRenderPipelineState`, which fails there, so none of its draws - /// meets such a failure. The notice names the draw, its state, the variant and the - /// driver's error. Announced where the draw is recorded: in the program's `commit`, or - /// the command buffer's host step. - DrawDroppedUnmade = "draw-dropped-unmade", Precision, - "the draw's commands ran nothing, where Metal's draw renders; the draws after it that \ - need the same pipeline make it again; CommandBuffer::dropped_draw names the first \ - such draw with the driver's error, and WorkCounts::draws_dropped_unmade counts \ - them"; - /// In a build without debug assertions, a notice announced where the runtime's rule - /// announces none ([`DegradeNotice::misplaced`] names its kind and [`NoticePlace`]): - /// inside a pipeline pool's piece, or, for a kind announced at every occurrence, outside - /// the program's call and outside a host step. The notice itself reaches the sink - /// unchanged, from the runtime's notice thread, which holds no runtime lock, and this one - /// follows it there. A build with debug assertions ends the process instead, with the - /// rule's line, so every lane and gate fails on it. - MisplacedNotice = "misplaced-notice", Performance, - "the notice reached the message sink from the runtime's notice thread after the call \ - that met it, not in the program's order on the thread that met it; Metal's answers \ - are unchanged"; - /// A write that may store a denormal in the 32-bit float depth of a depth image (a pass's - /// clear to one, a blit's copy into a `Depth32Float` or `Depth32Float_Stencil8` texture's - /// depth, a `replace_region` whose bytes hold one), on a device whose driver stores one a - /// write on the GPU gives it as a zero (no `DriverFact::DepthImageKeepsDenormals`: RADV, - /// ANV; a host copy keeps it) or whose depth test compares one otherwise than Metal's (no - /// `DriverFact::DepthTestKeepsDenormals`: every driver measured but MoltenVK on an Apple - /// M4). Metal's texel keeps it, and its depth test compares a positive one above zero and - /// a negative one not below zero. A draw at a denormal depth stores zero on Metal too, and - /// announces nothing. - DepthDenormals = "depth-denormals", Precision, - "a denormal depth may read, sample and copy out as a zero, or the depth test may \ - compare it as zero (a positive one) or below zero (a negative one), where Metal \ - keeps it and compares a positive one above zero and a negative one not below it"; - /// A depth test that may compare a negative value or a NaN stored in the 32-bit float depth - /// of a render target as it is, or a pass with depth writes that may store such a value - /// with its sign. Metal's depth test compares the fragment's depth with the stored value's - /// magnitude, as the integers of their low 31 bits: a stored -0.5 passes `Equal` for a - /// fragment at 0.5, and a stored NaN orders above +inf (probe `depthkeep`, the M3 Max under - /// macOS 27.0.1: 270 of 270 outcomes); and a pass that sets a depth/stencil state with - /// depth writes stores each texel no fragment wrote without its sign (probe `depthstore`). - /// Vulkan's compares the stored value as it is, and its pass keeps it. Announced at a write - /// that may give a render target's depth such a value (a `replace_region` whose bytes hold - /// one, a blit into its depth, a pass's written NaN clear), or at the commit of the command - /// buffer of a pass that loads a new texture's pattern (a NaN with the sign set) before a - /// write covered it in commit order (`fresh_unwritten.rs`), on a device that keeps such a - /// value there (`VK_EXT_depth_range_unrestricted` enabled; elsewhere a copy clamps it and - /// `restricted-depth-upload` is announced). Such a device whose depth test compares - /// magnitudes as Metal's (`DriverFact::DepthTestComparesMagnitudes`: MoltenVK, whose test - /// and store are the GPU's own Metal ones, were it to enable the extension) announces it - /// instead at a pass that loads and stores the depth and sets a state with depth writes - /// but draws under none, which its pass leaves signed. A render - /// pass's NaN clear depth, which Metal stores as - /// `0x7fc00000` and tests above every value, is written into the depth before the pass and - /// loaded (`nan_clear.rs`); where the device writes no such word (a memoryless depth, a - /// multisampled one without maintenance8's colour copies or an exact `FragDepth`, a pass - /// that does not store it on a device that keeps the earlier texels there), it is cleared - /// to 1.0, announced here; so is a `DontCare` load's NaN clear depth where the pass clears - /// that load (`clear_reach.rs`). - SignedDepthTest = "signed-depth-test", Precision, - "a depth test against the stored value, or the value a pass with depth writes stores, \ - can differ from Metal's in the pass or target named: the device compares a negative \ - value below zero and a NaN by its own rule and keeps the value's sign, where Metal \ - compares the value's magnitude, orders a NaN above every value and stores the value \ - without its sign; or a NaN clear depth is stored and tested as 1.0, where Metal \ - stores 0x7fc00000"; - /// The device's first sparse texture made (`Heap::new_texture` in a sparse heap) on a - /// device whose driver's first sparse resource waits for the work submitted before it on - /// every queue (`DriverFact::FirstSparseResourceWaitsForQueues`: ANV through TR-TT, Mesa - /// 26.2.4 on Intel's GPUs): `vkCreateImage` sets the driver's sparse translation tables - /// up with a batch on each queue and waits for it. Later sparse textures wait for nothing. - FirstSparseResourceWait = "first-sparse-resource-wait", Performance, - "the call returns only once every queue finished the work submitted before it, once \ - per device, where Metal's returns at once; what the texture holds and reads is \ - Metal's"; - /// A device the runtime makes whose driver it cannot make with the driver's internal - /// pipeline cache off (`VkDevicePipelineBinaryInternalCacheControlKHR`): its driver lists - /// no `VK_KHR_pipeline_binary`, reports no `pipelineBinaryInternalCacheControl`, or the - /// device enables no `VK_KHR_maintenance5`, which the extension requires. Announced once, - /// as the device is made; the payload names the device and why. Not on MoltenVK, whose - /// kept cache is Metal's own shader cache: that device sends the informational message - /// `metal2vulkan-driver-pipeline-cache-kept` instead. - DriverPipelineCacheKept = "driver-pipeline-cache-kept", Performance, - "the driver keeps its own cache of the device's pipelines beside the shader cache's \ - records, with whatever it writes to disk and holds in memory for it; the pipelines \ - made are the same"; - /// A device the driver refused to make for want of its resources with the `VkQueue`s of - /// its queue plan (`vkCreateDevice` answering `VK_ERROR_TOO_MANY_OBJECTS`, - /// `VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or - /// `VK_ERROR_OUT_OF_HOST_MEMORY`: on NVIDIA's driver, other devices of the GPU, in this - /// process or others, holding what it needs, such as its channels), made with those of its - /// least plan: a round robin of one `VkQueue` and none reserved for presenting, beside the - /// plan's extra, staging and fill queues and as many reserved queues as the plan reserves, - /// no more (`DeviceOptions::queue_limits` of one and none, without its informational - /// messages). Announced once, as the device is made; the payload names the device, the - /// `VkQueue`s of each plan and the driver's answer. A device the driver refuses with its - /// least plan too is refused (`Error::DeviceRefused`). - LeastQueuePlan = "least-queue-plan", Performance, - "its command queues, presenting ones included, share one `VkQueue`, so one queue's \ - command buffers wait behind another's whole command buffer where Metal's run beside \ - each other; what each command buffer does is the same"; - /// A device whose `VkDevice` was lost made a new one behind it, as Metal's device - /// survives its GPU's recovery (`device/line.rs`): its command buffers in flight failed, - /// the oldest incomplete one as the hang (`GpuHang`) and the rest as its victims - /// (`GpuRecoveryVictim`); every later call goes to the new `VkDevice`. Announced at each - /// recovery, from the call that made it; the payload names the culprit by its label and - /// its queue's, with its ended encoders' kinds and labels (`command_buffer/labels.rs`; - /// where two or more `VkQueue`s had work in flight it is an inference, and says so) and - /// the recovery's - /// time, and the objects it carried to the new `VkDevice` and left refused, by kind - /// (`device/carry.rs`). Announced as well, at most once each per recovery, whatever an - /// earlier recovery announced: where a call waited past 10 seconds for the recovery under - /// way (it waits on), where its command buffers in flight took past 10 seconds to fail (it - /// waits on), and where its new `VkDevice` could not be made (the device then answers as - /// a lost one). A `VkDevice` whose work stopped with no loss from the driver (no work of it - /// advanced for 10 seconds with some pending, and a probe on the staging queue did not - /// complete in 2 seconds: `command_buffer/stall.rs`) is recovered from the same way; the - /// payload then says it stopped and was parked (`Device::is_parked`). - DeviceRecovered = "device-recovered", Performance, - "the events, fences, depth/stencil states, libraries, functions, dynamic libraries, \ - binary archives, address pools, rasterization rate maps, argument encoders, uses of \ - guest RAM, no-copy buffers, `Private` buffers, buffers in the runtime's own pages \ - (fresh pages, and the blocks of pages the `Shared` and `Managed` buffers lie in where \ - the device's checks found a held host-page import costs its submissions nothing and \ - textures over such pages take what they take over its own memory), `Private` heaps \ - and heaps over the caller's memory with the buffers and textures placed in them, \ - textures of `new_texture`, textures over the buffers carried and views of them, \ - pipeline and sampler states, indirect command buffers and visible function tables \ - made before it go on, the contents of a `Private` \ - buffer or heap lost (it reads zero) but an exportable buffer's, re-imported over \ - its own memory, which keeps whatever that memory holds, and of a texture of \ - `new_texture` or of a `Private` heap of any storage mode (it reads as a new one) but \ - a texture buffer over its texels' buffer carried, a heap over the caller's memory \ - and what is placed in it reading the same pages, and of an indirect command \ - buffer's records on a device that imports no host pointer, where their import \ - failed, or, under the default `DevicePolicy::indirect_records = \ - IndirectRecordsPolicy::Untaxed`, on a device whose check found a held host-pointer \ - import costs every submission (RADV, ANV on i915), where they lie in pooled memory \ - (every command reset; the notice counts such buffers), where Metal's are kept, as \ - they are in the runtime's own pages everywhere else and under \ - `IndirectRecordsPolicy::Carried`, which `exact_answers()` selects \ - (docs/FAST-PATHS.md); the other objects made before it are refused \ - (`MadeBeforeRecovery`), where Metal's go on; the calls during it wait for it"; - /// Apple's private device properties the device has no answer for - /// (`private_properties.rs`): no document describes them and nothing the device reports - /// maps to them. Announced once, when `Device::private_properties` is first read; the - /// payload names the selectors. - PrivatePropertiesUnknown = "private-properties-unknown", Precision, - "the device gives no answer for them (`PrivateAnswer::value` is `None`); Metal's \ - measured answers on Apple's GPUs ride beside, never as this device's"; - /// A color fill (`BlitCommandEncoder::fill_texture_color`) whose color is packed in a - /// format Metal packs no color in: compressed, 4:2:2, depth, stencil, two-plane, YCbCr, - /// padded 10-bit, `Invalid` or a private format (`blit_fill.rs`). Metal fills bytes of the - /// calling thread's stack there, which hold the last color fill's packed texel only where - /// no other call used them since. The runtime fills the command buffer's last color fill's - /// packed texel, over zeros. - UnpackedFillColor = "unpacked-fill-color", Precision, - "every unit of the region holds the command buffer's last packed texel over zeros, \ - whatever the color, where Metal's bytes are its stack's"; - /// A fill of a texture buffer (`BlitCommandEncoder::fill_texture`, - /// `BlitCommandEncoder::fill_texture_color`) whose 16-byte chunks read bytes of its block - /// past the pattern's whole copies, or past the block (`blit_fill.rs`): most patterns - /// whose length is not a power of two, and most regions whose first byte is not at a - /// multiple of 16 of the buffer. Metal reads bytes of the calling - /// thread's stack there: zeros in our probes, an earlier fill's bytes in the consumer's - /// process. The runtime writes zeros there. - TextureBufferFillLeftover = "texture-buffer-fill-leftover", Precision, - "those bytes of each chunk are zeros, where Metal's are its stack's"; - /// A draw of points that rasterizes, of some vertices and instances, under a render - /// pipeline state whose vertex function writes no `[[point_size]]` and whose input - /// primitive topology class is not the point class (`render.rs`'s `draw_settings`): a - /// direct draw, an indirect one, or an indirect command's in an execution. Metal sizes - /// none of those points, and what it draws is undefined (measured by the consumer on an - /// M3 Max: most draws draw nothing, some a few of the points or a box whose size changes - /// from run to run; probes on an M4 drew nothing). The runtime rasterizes none of them, the - /// vertex function run for every point: one of Metal's answers. Announced at the draw's - /// call, and for an execution's command where the runtime records it: in `commit`, on the - /// committing thread, for the CPU's records; in the host step, on a thread of the - /// runtime's, for records the GPU may write. - UnsizedPoints = "unsized-points", Precision, - "the points rasterize nothing, the vertex function run for each, where what Metal \ - draws is undefined: most of its draws draw nothing, and some a few of the points \ - or a box"; - /// A draw of triangles in fill mode `TriangleFillMode::Points` (the raw value 2, which - /// Apple's GL renderer sends), whose vertices the device draws as points, under a render - /// pipeline state whose vertex function writes `[[point_size]]` - /// (`render/draw_shape.rs`): a direct draw, an indirect one, or an indirect command's in - /// an execution. The device sizes each point by the size the vertex function writes where its - /// `polygonModePointSize` is set (every device profiled), where Metal draws one pixel - /// whatever the function writes (measured on an Apple M3 Max). A vertex function that - /// writes none draws points of one pixel: its module writes 1. - TrianglePointSize = "triangle-point-size", Precision, - "each vertex can draw at the point size the vertex function writes, where Metal \ - draws one pixel"; - /// A draw of lines at a width other than 1 (Apple's `setLineWidth:`), or of a triangle's - /// edges in fill mode `Lines` or of a mesh draw, drawn by the device's own lines - /// (`render/line_width.rs`), which no device's are taken to draw as Metal's - /// parallelogram: strict lines (the rectangle the width spans across the segment, square - /// ends), lines Vulkan does not state as parallelograms - /// (`nonStrictWideLinesUseParallelogram` unset, or a width below 1), a width off the - /// device's `lineWidthGranularity`, which rounds it, and a driver's parallelograms, whose - /// ends and endpoints' snap are the driver's (RADV on the Radeon RX 7900 XTX draws 21 of - /// 48 scattered lines at width 2.5 a row or a column off Metal's at an end). Under - /// `WideLinePolicy::Exact` a draw of lines or of a triangle's edges takes the band variant - /// instead, on a device with `tessellationShader`. - DeviceWideLines = "device-wide-lines", Precision, - "the lines can cover pixels Metal's parallelogram does not, and miss others, at each \ - end and along each edge"; - /// A draw of lines at a width other than 1 (Apple's `setLineWidth:`), or of a triangle's - /// edges in fill mode `Lines` or of a mesh draw, that neither the device's own lines at - /// that width nor the band variant draws (`render/line_width.rs`), drawn by the device's - /// own lines at the width nearest it they draw: the width clamped into `lineWidthRange` - /// and put on the nearer step of `lineWidthGranularity`'s grid from its bottom (never 0) - /// where the device enables `wideLines`, else 1. A mesh draw's lines and edges and a - /// tessellated patch draw's edges, which the band does not draw, where the device's lines - /// do not draw the width (every such draw on a device without `wideLines`, MoltenVK among - /// them); lines and edges on a device without `tessellationShader` whose lines do not draw - /// them, or of a pipeline state or a draw whose band variant the translator refuses (and - /// the state's later draws of a draw so refused); a band under - /// vertex amplification above 1; and every line in a rasterization-rate-mapped pass or of - /// an execution's command, whose width Metal's answer is not measured for. The reason - /// names which, and both widths. - LinesAtNearestWidth = "lines-at-nearest-width", Precision, - "the lines are drawn at another width than Metal's: thinner (1 pixel without \ - wideLines) or wider, so they cover fewer or more pixels across each line"; - /// A draw of a triangle's edges in fill mode `Lines` at a width other than 1 (Apple's - /// `setLineWidth:`) drawn as the band variant (`render/line_width.rs`) under a depth bias - /// the device can apply otherwise than Metal: a slope factor, or a constant factor over a - /// float depth. Metal biases the edges by the triangle's depth slope and its largest - /// depth's exponent (the probe `line_widths.m`'s `edges`); the device biases each of the - /// band's triangles by its own slope and its own largest depth's exponent (Vulkan's depth - /// bias), the device's native arithmetic. A constant factor over a unorm depth, which is - /// one unit in either API, is not announced. - WideEdgeDepthBias = "wide-edge-depth-bias", Precision, - "the edges' fragments are biased by another depth than Metal's, along the edges as \ - their slope along them differs from the triangle's, and near a vertex of a smaller \ - depth exponent than the triangle's largest by a smaller unit"; - /// A draw whose lines, or a triangle's edges in fill mode `Lines`, the device's own lines - /// draw at width 1 (Metal's default width, or the nearest width a device without - /// `wideLines` draws) on a driver not measured to break a tie at a vertex two pixels' - /// diamonds share as Metal does - /// ([`metal2vulkan::device::DriverFact::LineTiesAreMetals`], `render/line_width.rs`): a - /// line through such a vertex exits neither pixel's diamond, which Vulkan's rule leaves - /// open, so the driver chooses the pixel it covers, where Metal covers the lower one. - DeviceLineTies = "device-line-ties", Precision, - "a line through a vertex two pixels' diamonds share covers the pixel the device \ - chooses, where Metal covers the lower one, so such a pixel, and the rest of a line \ - that runs along such vertices, can lie a row or a column from Metal's"; - /// A draw whose lines, or a triangle's edges in fill mode `Lines`, the runtime's band draws - /// (a width other than 1 the device's own lines do not draw as Metal's) on a driver not - /// measured to snap a vertex half a step off its 1/256-pixel subpixel grid as Metal snaps - /// a line's endpoint ([`metal2vulkan::device::DriverFact::SubpixelSnapIsMetals`], - /// `render/line_width.rs`): the band's corners, the endpoints offset by a multiple of 1/32 - /// pixel, are snapped by the device's rasterizer, where Metal snaps the endpoints up first, - /// so the two differ only where an endpoint lies half a step off the grid. - DeviceSubpixelSnap = "device-subpixel-snap", Precision, - "a line's band whose endpoint lies half a 1/256-pixel step off the subpixel grid is \ - snapped the way the device rounds, where Metal rounds the endpoint up, so a pixel \ - whose centre lies within that half step of the band's edge can be drawn, or left \ - out, a row or a column from Metal's"; - /// A draw of lines, or an emulated mesh draw of lines, under Apple's last provoking vertex - /// (`setProvokingVertexMode:` 1), of a pipeline state that reads it (a flat input, or a - /// slice or viewport its vertex function selects), on a device without - /// `VK_EXT_provoking_vertex`'s last vertex (or whose pipelines of one render pass instance - /// share one mode): each line is drawn from its last vertex to its first, so a first-vertex - /// pipeline reads Metal's provoking vertex (`render/provoking.rs`). Announced once per kind - /// of draw. - ProvokingVertexLines = "provoking-vertex-lines", Precision, - "each line's flat inputs are Metal's, but it can cover other pixels and interpolate \ - its smooth inputs otherwise than Metal's line from its first vertex to its last"; - /// A draw under Apple's last provoking vertex (`setProvokingVertexMode:` 1) the runtime - /// draws otherwise than Metal (`render/provoking.rs`). On a device without - /// `VK_EXT_provoking_vertex`'s last vertex (or whose pipelines of one render pass instance - /// share one mode), what no list the runtime draws holds as Metal draws it: a draw of - /// triangles, or an emulated mesh draw of triangles, whose fragment function reads flat - /// inputs and `[[barycentric_coord]]`, each drawn from its last vertex, its second and - /// third weights taken back to Metal's order from the drawn triangle's, Metal's but for - /// rounding; patches, and mesh draws through `VK_EXT_mesh_shader`, whose pipeline state - /// reads flat inputs: they read the first vertex. On a device with it, a strip whose vertex - /// function computes `[[primitive_id]]` into its varying (a device without `geometryShader` - /// and `tessellationShader`), whose IDs read each primitive's last vertex; and a slice or - /// viewport a vertex function selects where the pipeline selects it in a synthesized - /// geometry stage (a device without `shaderOutputLayer` or `shaderOutputViewportIndex`, an - /// index that differs between a primitive's vertices, or weights the stage writes), from - /// each primitive's first vertex. And on every device, a draw at a mode past 1, which - /// Metal draws a third way and the runtime as mode 1, whose shape and pipeline state Metal - /// draws otherwise than mode 1 (a strip's odd triangles, every line's flat inputs and - /// `[[primitive_id]]` 0, sized points, the middle vertex of a triangle whose pipeline - /// selects its slice or viewport, mesh draws unmeasured): announced at the draw. - ProvokingVertexUnmatched = "provoking-vertex-unmatched", Precision, - "flat inputs or a computed primitive ID read another vertex than Metal's, or \ - barycentric weights come in another order than Metal's or round otherwise"; - /// A draw counted by a `Counting` visibility result whose fragment variant writes more - /// than one color attachment, on a device whose driver counts each sample once per color - /// output ([`metal2vulkan::error::RuntimeDriverDefect::OcclusionCountPerColorOutput`]: - /// ANV). Announced at the draw's call, or where the runtime records an execution's - /// command; the payload names the draw and its colors. - VisibilityCountPerColor = "visibility-count-per-color", Precision, - "the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \ - result keeps its contract"; - /// A draw that fetches a vertex layout in fixed function where its indices or arguments - /// state how far it fetches (a per-vertex layout of an indexed draw of 32-bit indices, - /// any layout of an indirect draw) and may reach past `2^32` bytes of the bind offset, on - /// a device whose fixed-function vertex input takes an element's displacement modulo - /// `2^32` ([`metal2vulkan::error::RuntimeDriverDefect::VertexFetchWrapsPast4GiB`]: - /// lavapipe), under [`metal2vulkan::device::VertexReachPolicy::Bounded`] - /// (`render/vertex_reach.rs`). Announced at the draw; the payload names the draw and the - /// buffer. - VertexFetchMayWrap = "vertex-fetch-may-wrap", Precision, - "an element past 2^32 bytes of the buffer's bind offset reads the bytes at its \ - displacement's low 32 bits, where Metal reads zero past a buffer that ends before \ - them"; - /// A draw under a visibility result (`Counting` or `Boolean`) whose fragment function - /// declares `[[early_fragment_tests]]` and writes the `SampleMask` output - /// ([`metal2vulkan::pipeline::GraphicsState::writes_sample_mask`]: the render pipeline's - /// private sample mask or coverage, which the function applies itself under early tests, - /// or its own `[[sample_mask]]` return), on a device that does not state - /// `earlyFragmentMultisampleCoverageAfterSampleCounting` - /// ([`metal2vulkan::device::Limits::early_fragment_multisample_coverage_after_sample_counting`]: - /// ANV on the Iris Xe of RPL-P), where Vulkan lets the fragment shading and its mask come - /// before sample counting. Metal counts every sample the early tests pass, the private - /// masks applied to the colors alone; the device's query may leave out the samples the - /// mask drops. No other form keeps Metal's count at no cost to the draws: the colors' - /// masks are the function's `SampleMask` output or a discard, both fragment operations the - /// device may count after, so only a second draw of each counted draw, without the masks - /// and its writes, would count as Metal does. Announced at the draw's call, and counted - /// (`WorkCounts::draws_counted_past_early_masks`); the payload names the draw. - VisibilityPastEarlyMask = "visibility-past-early-mask", Precision, - "the result may leave out the samples the fragment function's sample mask drops, \ - which Metal counts under early tests: a `Counting` result counts fewer, and a \ - `Boolean` one may be 0 where Metal's passed"; - /// A pass writes a `Boolean` visibility result (`visibility.rs`): where a sample passed, - /// its word is the device's occlusion query result without - /// `VK_QUERY_CONTROL_PRECISE_BIT`, which Vulkan states only as nonzero ("When any samples - /// are passed, boolean queries will return a non-zero result value, otherwise a result - /// value of zero is returned", `occlusionQueryPrecise`), ORed over the pass's render pass - /// instances (and, under `Accumulate`, into the word the buffer held); where none passed, - /// 0 (the word, under `Accumulate`). That is Metal's `Boolean` contract, and Metal's own - /// nonzero value is not one value either: an Apple M3 Max (macOS 27.0.1) writes 1, Metal - /// on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 26.7.1) the samples - /// that passed. The device's value is the only form; no dispatch rewrites it. Announced - /// where the pass's results record; the payload names the pass's first `Boolean` offset. - DeviceBooleanVisibility = "device-boolean-visibility", Precision, - "a `Boolean` visibility result where a sample passed is the device's nonzero value, \ - which can be other than the 1 an Apple M3 Max writes; where none passed it is 0"; - /// A device whose float functions are not Metal's own (not MoltenVK, - /// `DriverDeviation::MetalFloatFunctions`): Metal flushes a `float` product, fused - /// multiply-add or `ldexp` whose exact value lies below `2^-126` to the zero of its sign, - /// deciding tininess before rounding, and the device rounds before it decides (measured on - /// RADV, ANV, NVIDIA and lavapipe, whether they flush denormals or keep them), so the - /// device's multiply and fused multiply-add answer `2^-126` there, and so does `ldexp`, - /// whose result below `2^-126` is the device's product (`device/float_tininess.rs`). - /// Announced once, as the device is made; the payload names the device. - FloatTininessAfterRounding = "float-tininess-after-rounding", Precision, - "a `float` product, fused multiply-add or `ldexp` whose exact value lies within half a \ - unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its \ - sign"; - /// An entry of the device's shader cache directory was not written: the directory, a - /// temporary file in it or the rename over the entry failed, on the device's cache thread - /// or on the thread that handed the entry over past the queue's bound - /// (`shader_cache/store.rs`, `shader_cache/worker.rs`). A full or read-only directory, a - /// cap no entry fits in, or a write another process won. Or the device has no directory - /// to write to: its options named none and the platform's default does not exist (the - /// variable it is found by is unset or not absolute) or takes no write, so it keeps its - /// cache in memory alone (`shader_cache/mod.rs`); that is announced as the device is made, - /// the payload naming the default directory and why. The work is never ended by it: the - /// pipeline state, the translation and the compile are the directory's regardless, and - /// the entry's absence costs only the next process that wants it. Announced once per - /// device; the payload names the directory, its cap and the largest entry it takes. Later - /// failures are counted alone - /// ([`ShaderCacheStatistics::write_failures`](crate::ShaderCacheStatistics::write_failures)). - ShaderCacheEntryNotWritten = "shader-cache-entry-not-written", Performance, - "what the entry would hold is made again by the next process that needs it; what this \ - process computes is unchanged"; - } - notes { - F16FmaDoubleRounding = "f16-fma-double-rounding"; - F16IntConvDoubleRounding = "f16-int-conv-double-rounding"; - GradFromBias = "grad-from-bias"; - DeviceTranscendentals = "device-transcendentals"; - ReductionOrder = "reduction-order"; - DeviceDenormals = "device-denormals"; - PixelSamplerScaling = "pixel-sampler-scaling"; - DeviceArithmetic = "device-arithmetic"; - DeviceSignedZeroInfNan = "device-signed-zero-inf-nan"; - DeviceRayIntersection = "device-ray-intersection"; - FastMathRewrites = "fast-math-rewrites"; - TessellationWinding = "tessellation-winding"; - /// A tessellation pipeline of a fractional partition on `metal2vulkan-rt`'s device - /// tessellator: where the spacing places its vertices is the device's. - TessellationFractionalSpacing = "tessellation-fractional-spacing"; - TessellationFactorEdgeCases = "tessellation-factor-edge-cases"; - TessellationFactorScale = "tessellation-factor-scale"; - TessellationFactorInstance = "tessellation-factor-instance"; - Fp8Value = "fp8-value"; - MultisamplePosition = "multisample-position"; - RasterizationRateMap = "rasterization-rate-map"; - BicubicFilterArithmetic = "bicubic-filter-arithmetic"; - SparseResidency = "sparse-residency"; - DeviceNanEncoding = "device-nan-encoding"; - RestrictedDepthRange = "restricted-depth-range"; - CubeGradientFootprint = "cube-gradient-footprint"; - HalfTexelConversion = "half-texel-conversion"; - HalfSampleFilter = "half-sample-filter"; - SrgbTexelDecode = "srgb-texel-decode"; - FloatSampleFilter = "float-sample-filter"; - FunctionStorageAssumed = "function-storage-assumed"; - QuadsCountedBeforeDiscard = "quads-counted-before-discard"; - ViewBaseTexelOffset = "view-base-texel-offset"; - /// Class: native colour conversion. The device converts a fragment function's colour into - /// the attachment, blended or not, or a function's `float` texel into a storage texture, - /// where it is not measured to make Metal's codes: near a tie between two codes it may - /// store the other one. Recorded bound past one code, on lavapipe against plain Metal on - /// an Apple M3 Max: a blend into an 8-bit unorm attachment within 2 codes; a function that - /// fetches an 8-bit sRGB attachment and writes it again within 2 codes; a blend into an - /// 8-bit sRGB attachment within 4 codes; a blend into a multisampled packed 16-bit - /// attachment within 2 codes over a sample stored a code from Metal's. Another device is - /// not bounded past one code. - DeviceColorConversion = "device-color-conversion"; - DeviceInterpolation = "device-interpolation"; - DeviceInterpolationOffset = "device-interpolation-offset"; - ExtrapolatedInterpolation = "extrapolated-interpolation"; - QuadsSplitByClipping = "quads-split-by-clipping"; - VertexSimdgroupGrouping = "vertex-simdgroup-grouping"; - FragmentSimdgroupGrouping = "fragment-simdgroup-grouping"; - BlendedWriteRounding = "blended-write-rounding"; - RotatedBlendRounding = "rotated-blend-rounding"; - LinkedSamplerNumbering = "linked-sampler-numbering"; - ComputedSampleDepth = "computed-sample-depth"; - ArgumentPixelSamplerScaling = "argument-pixel-sampler-scaling"; - HalfOutputPrecision = "half-output-precision"; - ExtendedRangeBlendSource = "extended-range-blend-source"; - DiscardDropsSimdgroupStores = "discard-drops-simdgroup-stores"; - HelperBranchDropsSimdgroupStores = "helper-branch-drops-simdgroup-stores"; - ExtendedRangeFloatBlendSource = "extended-range-float-blend-source"; - AnisotropicFilter = "anisotropic-filter"; - DeviceAnisotropicFilter = "device-anisotropic-filter"; - DevicePointSize = "device-point-size"; - ClippedCoverageSplit = "clipped-coverage-split"; - LoopedSampleOutputs = "looped-sample-outputs"; - HalfOutputFastMathBlend = "half-output-fast-math-blend"; - /// Class: native device sampling. The device's own sampler answers the pipeline's - /// samples, gathers and comparisons on a device whose sampler is not Metal's. Recorded - /// bound, measured against an Apple M4 on 2D textures of one level in seven formats - /// under four address modes: a linear filter within 0.919 of a code (1/255) of Metal's on NVIDIA's 615.71.09, 0.548 on RADV, - /// 0.918 on ANV and 1.0 on lavapipe (Mesa 26.2.4); an sRGB texture's within 1.832, 0.764, - /// 0.912 and 0.781; a nearest sample's texel the neighbour of Metal's at 0.1% of the - /// probe's coordinates on NVIDIA and ANV, 0.02% on RADV and none on lavapipe. Level - /// selection, anisotropy, cube maps, 3D textures, gathers, comparisons and offsets are - /// not measured. - DeviceSampling = "device-sampling"; - /// Class: native device maths. The device's `GLSL.std.450` instruction answers a `float` or - /// `half` math-library call that is not Metal's own function on the device, and the - /// device's `Sqrt` answers `fast::sqrt`, Metal's `x · rsqrt(x)`. Recorded bound: Vulkan's - /// precision table for the instruction: `Exp2` and `Exp` 3 + 2·|x| ulp; `Log2` and `Log` 3 - /// ulp outside `[0.5, 2]`, `2^-21` absolute inside; `Pow` from `Exp2(y · Log2(x))`; `Sqrt` - /// from `1 / InverseSqrt`; `InverseSqrt` 2 ulp; `Sin` and `Cos` `2^-11` absolute in - /// `[-Ï€, Ï€]`; `Tan` from `Sin / Cos`; `Asin`, `Acos`, `Atan` and `Atan2` 4096 ulp. - NativeTranscendentals = "native-transcendentals"; - /// Class: native device maths. The device's `OpFDiv` answers a precise or fast `float` or - /// `half` division, where Metal's is its correctly rounded quotient or its `x` times its - /// fast reciprocal. Recorded bound: 2.5 ulp of the quotient (a precise division's operands - /// past a divisor of `2^126` scaled into Vulkan's range exactly); a `half` quotient within - /// one unit in its last place. - NativeDivision = "native-division"; - /// Class: native device maths. The device's `GLSL.std.450 Fma` answers a `half` fused - /// multiply-add, or a `float` one on a device without `OpFmaKHR`, where Metal's rounds - /// once. Recorded bound: a `half` result within one unit in its last place of Metal's; a - /// `float` one within half a unit in the last place of the product plus half a unit in - /// the last place of the result. - NativeFma = "native-fma"; - /// Class: native device sampling. The device's own conversion of a texel's codes answers - /// the pipeline's reads, samples and gathers with a `float` result, on a device whose - /// sampler is not Metal's. Recorded bound, of a texel whose access reads one texel of one - /// level: an 8-, 10- or 16-bit normalized code within one `f32` ulp of Metal's - /// `c / (2^b - 1)` where measured (lavapipe's reciprocal product), a 10-bit one within - /// 0.015 of a code where the device widens it by replicating its bits to 16 (NVIDIA); a - /// 4-, 5- or 6-bit - /// channel within one `f32` ulp where the device converts it by the reciprocal (lavapipe), - /// and within 0.18 of a code where it widens a 5- or 6-bit channel by replicating its bits - /// (ANV, NVIDIA; a 4-bit channel's replication exact); a half-float or small-float NaN in - /// the device's encoding, where Metal answers `0x7fc00000`. - DeviceTexelConversion = "device-texel-conversion"; - /// Class: native vertex input. The device's fixed-function vertex input converts a - /// normalized vertex attribute's codes (the 8- and 16-bit normalized formats of either - /// sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) - /// through its `UNORM` or `SNORM` vertex format, where Metal's fetch answers the code over - /// its maximum correctly rounded (an `Int1010102Normalized` 10-bit field times - /// `float(1/511)`). Not recorded for a `float` attribute on a profile that takes - /// `DriverDeviation::MetalNormalizedVertexFetch` (MoltenVK on the Apple M3 Max's macOS 27 - /// identity, measured Metal's at every code). Recorded bound: within one `f32` ulp where - /// measured (lavapipe's reciprocal product reads some 8-bit unsigned codes one ulp high; - /// RADV's unsigned formats are Metal's), but lavapipe's per-instance fetch reads the most - /// negative code of an 8- or 16-bit signed format unclamped (-128/127, -32768/32767) where - /// Metal reads -1; a 16-bit format read as `half`, one `half` ulp at four codes; the signed - /// formats on RADV, ANV and NVIDIA are unmeasured. Also recorded, on every device, for a - /// normalized attribute the shader pulls from its buffer (a kernel's `[[stage_in]]` - /// attribute included), which is the module's product of the code and its maximum's - /// reciprocal: within one `f32` ulp of Metal's quotient (some 8-bit unsigned codes one ulp - /// high, some signed, 10-bit and 16-bit codes one ulp toward zero), but for - /// `Int1010102Normalized` read as `float` and an 8- or 10-bit format read as `half`, which - /// are Metal's and record nothing. - DeviceVertexConversion = "device-vertex-conversion"; - /// Class: native half rounding. The device's own conversion of a `float` to 16 bits - /// rounds the pipeline's `half` results, on a device with `shaderFloat16` whose float - /// controls do not make that conversion Metal's `half(float)`; and the device's widening - /// reads a `half` from its bits (a load, a reinterpretation, a texel's bits) where it is - /// neither under those controls nor measured to be Metal's: NVIDIA's and lavapipe's - /// conversion, and `UnpackHalf2x16` on every device without `shaderFloat16`. Recorded - /// bound: a finite result within one unit in the last place of the `half` (to nearest - /// even on NVIDIA's RTX 5080 Laptop GPU, toward zero on its RTX 3090 and lavapipe); where - /// the device rounds toward zero, 65504 from 65520 up where Metal answers infinity; a - /// result below `2^-14`, or a `half` denormal read, the zero of its sign on a device that - /// flushes 16-bit denormals; a NaN's encoding (`0x7FFF` on the RTX 5080, where Metal - /// answers `0x7E00`) and the sign of a zero result the device's. - NativeHalfConversion = "native-half-conversion"; - /// Class: native half rounding. The device's `OpQuantizeToF16` alone rounds the - /// pipeline's `half` results computed in `float` on every device without `shaderFloat16`, - /// its quantize measured or not; an integer's `half` rounds exactly. Recorded bound: a - /// finite result within one unit in the last place of the `half`; 65504 to 65520 possibly - /// infinity where Metal answers 65504; a value below `2^-14` possibly a zero of either - /// sign where Metal answers the `half` denormal, or `2^-14` from just below it; a NaN's - /// encoding the device's. - NativeHalfQuantize = "native-half-quantize"; - /// Class: native device maths. The device's NaN answers a `float` or `half` operation's - /// NaN result where Metal answers a NaN the device is not measured to answer (every NaN - /// but the canonical one on a device measured to answer Metal's canonical NaN); and every - /// pipeline that reads a `half` from its bits, on every device, widens it by the device - /// (`OpFConvert` with `shaderFloat16`, `UnpackHalf2x16` without), a NaN to a NaN of the - /// device's bits. Recorded bound: where Metal answers a NaN the device answers a NaN, its - /// sign and payload the device's own, where Metal answers `0x7fc00000` (`0x7e00` as - /// `half`), an operand's bits, or the canonical NaN with an operand's sign, and where - /// Metal widens a `half` NaN to `0x7fc00000`; a `half` stored back unchanged keeps its - /// bits; every other result unchanged. - NativeNanEncoding = "native-nan-encoding"; - /// Class: native device maths. The device's `NMin`, `NMax` or `NClamp` answers Metal's - /// `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on - /// `float` or `half` on a device not measured to answer Metal's operand, and `median3` of - /// them on every device. Recorded bound: an operand, Metal's but at three ties: of two - /// NaNs a NaN (Metal: the second operand's bits), of `+0` and `-0` either zero (Metal: the - /// second), and an `f32` denormal beside a zero or another denormal compared by its value - /// where the device's `NMin` and `NMax` keep denormals, whether or not its arithmetic - /// flushes them (Metal compares it as a zero and answers the second). - NativeMinMax = "native-min-max"; - /// Class: native device maths. The device's `OpDot` answers Metal's `dot` on `float` and - /// `half` (summed in `float`, rounded once to `half`) on every device but for a `float` one - /// on MoltenVK, where Metal's is the fused chain of its products. Recorded - /// bound: a `float` `dot` of `n` lanes within `(3n - 1) * 2^-24 * sum |a_i * b_i|` of - /// Metal's chain, plus `n * 2^-126` where a product is an `f32` denormal the device keeps; - /// a `half` one within `(n + 3) * 2^-11 * sum |a_i * b_i| + (n + 2) * 2^-25`. - NativeDot = "native-dot"; - /// Class: native device maths. The device's `FMix` answers Metal's `mix(x, y, t)` on - /// `float` and `half` (computed in `float`, rounded once to `half`) on every device but for - /// a `float` one on MoltenVK, where Metal's is - /// `fma(t, y, fma(-t, x, x))`. Recorded bound: a `float` result within `2^-21 * (|x * - /// (1 - t)| + |y * t|)` of Metal's; a `half` one within `3 * 2^-10 * (|x * (1 - t)| + |y * - /// t|) + 2^-23`. - NativeMix = "native-mix"; - /// Class: native device maths (a conversion). The device's conversion answers - /// `air.pack` and `air.unpack` of a normalized format: `GLSL.std.450`'s `Pack` and - /// `Unpack` instructions for `unorm4x8`, `snorm4x8`, `unorm2x16` and `snorm2x16`, their - /// definition by the device's clamp, multiply, `RoundEven` and reciprocal for `rgb10a2` - /// and `rgb565`, and the MSL transfer functions by the device's `Pow` for - /// `unorm4x8_srgb`'s colour (also an 8-bit sRGB storage texture's write through its UNORM - /// alias), where Metal rounds the exact product, divides correctly rounded and takes an - /// sRGB colour through its twelve-bit table. Recorded bound: a packed - /// code within one of Metal's, apart only near a half-integer; an unpacked value within - /// 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a - /// twelve-bit step (`1 / 8190`) of Metal's step `k / 4095`, beyond its division's and - /// `Pow`'s bounds; a NaN channel's code the device's, where Metal's is 0. Also every - /// conversion of an extended-range, padded 10-bit or bfloat texel, on every device (no - /// Vulkan format holds them): a linear value within one `f32` ulp of Metal's, an encoded - /// code within one (`R10Unorm_X6_sRGB`'s and `RGB10A2Unorm_sRGB`'s colour within two - /// below `0.0031308`), a `half` result within one `half` ulp. A texture a heap holds - /// by its raw texels alone, which a function's `float` read, sample or gather through an - /// argument buffer decodes so, is announced naming the texture, at the first command that - /// binds a heap set holding it, whether or not its function reads it; and by the stage - /// that decodes it, at a draw or dispatch whose command makes such a texture resident or - /// binds one (`SpecKey::HeapRawTextures`). - DevicePackConversion = "device-pack-conversion"; - /// A render pipeline whose color attachments the device draws in more than one group: - /// each draw runs once per group, each group's variant over its own copy of the pass's - /// depth and stencil. Recorded bound: groups past the first may differ at discard or - /// depth edges if the driver compiles the variants differently; nothing broader. - ColorAttachmentGroups = "color-attachment-groups"; - /// A tessellation pipeline drawn through the device's tessellation stages, on a device - /// whose tessellator is not Apple's (every one but MoltenVK on an Apple GPU): the device's - /// tessellator orders each patch's triangles, picks their first corners and joins its - /// rings where Vulkan leaves that to the implementation, not as Metal's tessellator does. - /// The domain points are Metal's; flat varyings, interpolation across another - /// triangulation and the order a patch's triangles blend in may differ. On a device - /// without `tessellationShader` the emulation draws Metal's order and records none. - TessellationTriangleOrder = "tessellation-triangle-order"; - /// A function holds a branch whose arms hold a quad or simdgroup operation that Metal's - /// backend makes answer over every lane of the branch's block when it speculates the arms, - /// where no measurement says whether it speculates them (an arm of an instruction, size or - /// shape no probe covers): the branch keeps the AIR's lanes, so that operation may answer - /// over the lanes that take the arm where Metal's answers over the block's. Nothing else - /// in the stage changes. - UnmeasuredGroupSpeculation = "unmeasured-group-speculation"; - /// A sample at an implicit level or with gradients through a constexpr sampler with - /// anisotropy, no mip filter and different minification and magnification filters, on a - /// device that samples through Metal's own sampler (MoltenVK on Apple's GPU): no level - /// clamp the device's sampler takes reads Metal's `NotMipmapped` footprint at - /// `maxAnisotropy` 2 to 16, so the sample filters another anisotropic footprint. - NotMipmappedAnisotropicFilter = "not-mipmapped-anisotropic-filter"; - /// A sample whose level the device's level arithmetic chooses (a fragment function's - /// implicit-level sample, its bias within the device's limit; a sample with explicit - /// gradients; a fragment function's LOD query; an explicit level Metal's level rule is not - /// handed on, such as an integer texture's), of a texture other than a cube, without - /// comparison, where no sample-filter note covers it: the device's level of detail and its - /// rounding of a level may read another level or filter than Metal's near a boundary, and - /// the query answers the device's level. - DeviceSampleLevel = "device-sample-level"; - /// A render pipeline covers by alpha under `textureWriteRoundingMode` 2, and its fragment - /// function writes a `float` alpha to a half-float attachment 0 that stores it as written: - /// the function rounds the alpha to the nearest-even half Metal stores, and the coverage - /// reads the rounded alpha where Metal's reads the alpha before rounding, so a fragment - /// whose alpha lies within half a `half` step of a coverage threshold may cover one - /// sample more or fewer. - CoverageReadsRoundedAlpha = "coverage-reads-rounded-alpha"; - /// Class: native device coverage. A render pipeline covers by alpha on a device not - /// measured to cover as Metal does (every device but MoltenVK on Apple's GPUs of the Apple M3 - /// Max's macOS 27 identity): the device - /// converts the alpha to its coverage mask by its own algorithm, which Vulkan does not - /// specify, where Metal covers a pixel at one sample above an alpha of 1/2 and at two and - /// four samples `ceil(alpha * n - t)` samples by a 2x2 ordered dither `t` (an Apple M3 - /// Max). Recorded bound: on lavapipe every pixel within one sample of Metal's and Metal's - /// where `alpha * n` is an integer; at one sample a whole fragment stored or dropped - /// where its alpha lies between its own dither threshold and 1/2, at four samples one - /// sample apart only within an `f32` ulp of a threshold. Unmeasured elsewhere (NVIDIA - /// stores a fragment of alpha 1/2 at one sample). - DeviceAlphaCoverage = "device-alpha-coverage"; - /// The blend of a color attachment the fragment function reads, computed by the shader in - /// the pixel interlock's storage form, of a format whose Metal blend arithmetic is not - /// built (a 32-bit float, 16-bit normalized, 8-bit signed normalized, 10-bit, packed - /// float or `A8Unorm` format, among others, an 8-bit unorm one written by fewer than four - /// lanes, or a 16-bit float or 8-bit unorm one under a blend of the second source): in - /// `float`, each step rounded, the sources and the blend color clamped to a normalized - /// format's range, the device's conversion storing the result; or of an 8-bit sRGB format - /// under a blend of the second source, or a one- or two-channel one under a lerp, in a - /// module compiled with fast math, or written by fewer than four lanes, in the 8-bit unorm - /// blend's rounded forms over the decoded texel. Metal's blend for these is not measured. - UnmeasuredFetchBlend = "unmeasured-fetch-blend"; - /// A fragment function reads a color attachment on a device with neither - /// rasterization-order color attachment access nor the pixel interlock: through its input - /// attachment, ordered after the draws before by a barrier between them, but not after an - /// overlapping earlier fragment of its own draw, which Metal orders in primitive order. - /// Exact for a draw whose primitives do not overlap at a pixel. - UnorderedFetchWithinDraw = "unordered-fetch-within-draw"; - /// Class: native logic operation. A render pipeline's private logic operation is drawn - /// by the device's `logicOp` into an `RGB10A2Unorm`, `BGR10A2Unorm` or signed normalized - /// attachment, which operates on the channels' stored codes themselves, where Metal - /// operates on a 10-bit (and 2-bit) code widened to 16 bits and narrows the result, and - /// reads and stores a signed channel's lowest code as the code above it: a channel may - /// store another code (lavapipe's xor, green 938 where Metal's rule gives 937, and `0x60` - /// over a signed `0x80` where Metal's gives `0x61`). Not bounded: the result follows the - /// codes' bits. - NativeLogicOperation = "native-logic-operation"; - /// Class: native 8-bit float. A tensor's 8-bit float element widens through the device's - /// own 8-bit float (`shaderFloat8`), whose encodings are OCP's: an e4m3 `0x7F` or `0xFF` - /// reads as a NaN, where Metal reads 480 and -480, and an e5m2 NaN's bits are the - /// device's, where Metal reads `0x7FC00000`. Not bounded: a NaN in a sum makes the sum a - /// NaN. - NativeFloat8 = "native-float8"; - /// A draw of triangles under a depth bias on `metal2vulkan-rt`, whose render encoder - /// carries the note: the biased depth is the device's. This runtime announces its own - /// depth bias kinds instead. - DeviceDepthBias = "device-depth-bias"; - /// A sampler that reads an opaque-black border on `metal2vulkan-rt`, whose sampler state, - /// or the pipeline of a constexpr one, carries the note: through a swizzled view, on a - /// device without `borderColorSwizzleFromImage`, the border texel is the device's. This - /// runtime makes the sampler for the view's mapping, or refuses the pair, instead. - SwizzledOpaqueBlackBorder = "swizzled-opaque-black-border"; - } -} - -impl Degradation { - /// The kind of `code`, if any. - pub fn from_code(code: &str) -> Option { - Degradation::ALL - .iter() - .copied() - .find(|kind| kind.code() == code) - } - - /// The kind's bit: its word in [`Announced`], and the bit in it. - fn bit(self) -> (usize, u64) { - let index = self as usize; - (index / 64, 1 << (index % 64)) - } -} - -/// A degrade notice's payload: what [`DebugMessage::degradation`] carries. No Metal counterpart: -/// Metal has no near-equivalents to announce. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DegradeNotice { - /// What was degraded: match on it, not on the text. - pub degradation: Degradation, - /// The object degraded, the first the device met: its kind and what identifies it. - pub object: String, - /// Why, with the object's numbers. - pub reason: String, - /// What it costs: the kind's [`cost`](Degradation::cost). - pub cost: &'static str, - /// The object's ID, for a kind met once per object, whose objects - /// [`Device::degraded_objects`] counts ([`Degradation::StaleDetachedReach`], - /// [`Degradation::DetachedStorageKeepsWrites`], [`Degradation::HeapTextureLosslessLayout`], - /// [`Degradation::HeapTextureBlockCompressedLayout`] and - /// [`Degradation::HeapTextureUntiledLayout`]: the texture's, the first the device met, or - /// each's where `DeviceOptions::announce_each` asks); `None` for every other kind. - pub object_id: Option, - /// For [`Degradation::MisplacedNotice`], the misplaced notice's kind and where it was - /// announced; `None` for every other kind. - pub misplaced: Option, - /// The render encoder's call whose lowering announced it, where the runtime lowered the call - /// after it returned (`RenderLoweringPolicy::Worker`, the default): its Metal selector and - /// its place among the encoder's calls. `None` for a notice announced inside the program's - /// call itself, and for every other notice. - pub call: Option, - /// The command buffer whose work announced it: its ID - /// ([`CommandBuffer::object_id`](crate::CommandBuffer::object_id)). A runtime extension; - /// Metal has no notices, and reports a command buffer's errors on the command buffer - /// (`MTLCommandBuffer.error`). Set for a notice announced while the runtime - /// does one command buffer's work on the announcing thread: a call of one of its encoders, - /// that call's lowering after it returned (`RenderLoweringPolicy::Worker`, on whichever - /// thread lowers it), the opening of an encoder of it, its commit (at the call, or once a - /// render encoder's end it waited for was lowered), the submission of a batch of it and the - /// settling of what rode on that batch, a host step of it on the scheduler's steps thread (an - /// indirect command buffer's execution recorded there among them) and a predicated loop's run - /// again of what such steps recorded, on that loop's thread, an encoding again of its - /// encoders at a rebind, and a read of its GPU times once it completed - /// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time), - /// [`CommandBuffer::gpu_end_time`](crate::CommandBuffer::gpu_end_time)). A notice a bind - /// announces at every occurrence (`DeviceOptions::announce_each`) names the command buffer of - /// that bind, not of the bind that first made it. `None` for every other notice: one - /// announced by the device, a library, a pipeline state, a resource or a queue outside any - /// command buffer's work (making, releasing, rebinding or detaching one, and the pages of a - /// detached or released no-copy buffer); one about several command buffers' batches together - /// ([`Degradation::GroupedCompletion`]); and one of a recovery of the device - /// ([`Degradation::DeviceRecovered`]), whichever call met it. The program's code the runtime - /// calls (a handler, a submission check, an indirect command check, a message sink) is no - /// command buffer's work: what its calls announce names none, but a call of an encoder, which - /// names the encoder's command buffer. - pub command_buffer: Option, -} - -/// A notice announced where the runtime's rule announces none -/// ([`Degradation::MisplacedNotice`]'s payload). No Metal counterpart. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct MisplacedNotice { - /// The misplaced notice's kind, which reached the sink unchanged just before. - pub kind: Degradation, - /// Where it was announced. - pub place: NoticePlace, -} - -/// Where a notice was announced against the runtime's rule ([`MisplacedNotice::place`]). No -/// Metal counterpart. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum NoticePlace { - /// Inside a pipeline pool's piece, where no kind is announced: what the program sees is - /// decided on its own thread, in its call. - PipelinePoolPiece, - /// A kind announced at every occurrence (`DeviceOptions::announce_each`), on a thread - /// outside the program's call and outside a command buffer's host step. - OutsideProgramCall, -} - -impl NoticePlace { - /// The line a build with debug assertions ends the process with. - pub(crate) fn line(self) -> &'static str { - match self { - NoticePlace::PipelinePoolPiece => { - "metal2vulkan-runtime: a degradation was announced inside a pipeline pool piece" - } - NoticePlace::OutsideProgramCall => { - "metal2vulkan-runtime: a degradation asked for at every occurrence was announced \ - outside the program's call and outside a host step" - } - } - } - - /// Where, in words. - pub(crate) fn words(self) -> &'static str { - match self { - NoticePlace::PipelinePoolPiece => "inside a pipeline pool's piece", - NoticePlace::OutsideProgramCall => { - "outside the program's call and outside a command buffer's host step" - } - } - } -} - -impl DegradeNotice { - /// The notice of `degradation` for `object`, degraded for `reason`. - pub(super) fn new(degradation: Degradation, object: String, reason: String) -> DegradeNotice { - DegradeNotice { - degradation, - object, - reason, - cost: degradation.cost(), - object_id: None, - misplaced: None, - call: crate::render::lowering::current(), - command_buffer: NoticesFor::current(), - } - } - - /// The notice as announced now, by a bind that announces it again as made by an earlier bind - /// (`Device::announce_bound`): the call being lowered and the command buffer whose work runs - /// on this thread now, in place of the earlier bind's. - fn announced_here(&self) -> Option { - let (call, command_buffer) = (crate::render::lowering::current(), NoticesFor::current()); - if self.call == call && self.command_buffer == command_buffer { - return None; - } - Some(DegradeNotice { - call, - command_buffer, - ..self.clone() - }) - } - - /// The notice as a message: a warning of the performance kind (a performance degradation) - /// or the general kind (a precision or validity one), its `id_name` the code, its text - /// `metal2vulkan: : ; []`. - pub(super) fn message(self) -> DebugMessage { - let code = self.degradation.code(); - let performance = self.degradation.category() == DegradationCategory::Performance; - DebugMessage { - severity: MessageSeverity::Warning, - kind: MessageKind { - general: !performance, - performance, - ..MessageKind::default() - }, - id_name: code.to_owned(), - id: 0, - text: format!( - "metal2vulkan: {}: {}; {} [{code}]", - self.object, self.reason, self.cost - ), - degradation: Some(self), - } - } -} - -/// The words of [`Announced`]. -const WORDS: usize = Degradation::ALL.len().div_ceil(64); - -/// The kinds a device announced, a bit each, and those it announces at every occurrence -/// (`DeviceOptions::announce_each`), a bit each; the reasons it announced `copied-host-pages` -/// for, a bit each ([`Device::degrade_copied_pages`]); the causes it announced -/// `host-replayed-indirect-commands` for ([`Device::degrade_host_step`]); and the kinds of the -/// messages it says once that are no degradation ([`Told`]) it said, a bit each. -#[derive(Debug, Default)] -pub(super) struct Announced { - seen: [AtomicU64; WORDS], - each: [u64; WORDS], - copied: AtomicU64, - host_steps: Mutex>, - told: AtomicU64, -} - -/// What a host step's `host-replayed-indirect-commands` notice names as its cause, which the -/// device announces once each ([`Device::degrade_host_step`]): a render pass's rule that kept it -/// from the GPU form (`render/executions/cause.rs`'s `HostStepCause`), by its words, its draw -/// replay rule's variant, or its class; a render pass's step that names none; or a compute -/// execution's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum HostStepKey { - Rule(&'static str), - Replay(Discriminant), - Check, - Refused, - Outgrown, - Render, - Compute, -} - -impl Announced { - /// The record of a device that announces the kinds of `each` at every occurrence. - pub(super) fn new(each: &BTreeSet) -> Announced { - let mut words = [0; WORDS]; - for kind in each { - let (word, bit) = kind.bit(); - words[word] |= bit; - } - Announced { - seen: Default::default(), - each: words, - copied: AtomicU64::new(0), - host_steps: Mutex::new(Vec::new()), - told: AtomicU64::new(0), - } - } - - /// Whether a message of kind `told` is said now: for the first time on the device, once per - /// kind, whatever `DeviceOptions::announce_each` says (which names degradations alone). - fn first(&self, told: Told) -> bool { - let bit = 1 << told as u32; - let said = &self.told; - said.load(Ordering::Relaxed) & bit == 0 && said.fetch_or(bit, Ordering::Relaxed) & bit == 0 - } - - /// Whether `degradation` is announced now: at each occurrence of a kind the device announces - /// at each (met at every occurrence, [`EachWatch`]), else for the first time, once per kind. - /// Never on a warm pass's threads, which count nothing announced (`warm/pass.rs`): what it - /// makes is no program's, and the creation it makes ahead announces as its own. - pub(super) fn now(&self, degradation: Degradation) -> bool { - if crate::warm::warming() { - return false; - } - let (word, bit) = degradation.bit(); - if self.each[word] & bit != 0 { - met_each(); - return true; - } - let seen = &self.seen[word]; - seen.load(Ordering::Relaxed) & bit == 0 && seen.fetch_or(bit, Ordering::Relaxed) & bit == 0 - } - - /// Whether `degradation` is announced now for the first time, once per kind, whether or not - /// the device announces it at each occurrence: a kind met where no program call or host step - /// is (`Device::degrade_encoded_use_rebound`). Never on a warm pass's threads, as - /// [`now`](Self::now). - fn once(&self, degradation: Degradation) -> bool { - if crate::warm::warming() { - return false; - } - let (word, bit) = degradation.bit(); - let seen = &self.seen[word]; - seen.load(Ordering::Relaxed) & bit == 0 && seen.fetch_or(bit, Ordering::Relaxed) & bit == 0 - } - - /// Whether `copied-host-pages` is announced now for the reason `reason` - /// ([`Device::degrade_copied_pages`]): as [`now`](Self::now) answers for a kind, or, where - /// `replaying`, as [`once`](Self::once) does, but for the first time per reason. - fn copied_now(&self, reason: Option, replaying: bool) -> bool { - if crate::warm::warming() { - return false; - } - if !replaying && self.each(Degradation::CopiedHostPages) { - met_each(); - return true; - } - // A buffer lying in another's live copy is a reason of its own, beside each cause. - let bit = 1u64 << reason.map_or(0, |cause| cause as u32 + 1); - let seen = &self.copied; - seen.load(Ordering::Relaxed) & bit == 0 && seen.fetch_or(bit, Ordering::Relaxed) & bit == 0 - } - - /// Whether `host-replayed-indirect-commands` would be announced for the cause `key` outside - /// a call encoded again ([`host_step_now`](Self::host_step_now)), without counting it - /// announced. - pub(super) fn host_step_unannounced(&self, key: HostStepKey) -> bool { - let kind = Degradation::HostReplayedIndirectCommands; - !crate::warm::warming() - && (self.each(kind) || !crate::device::lock(&self.host_steps).contains(&key)) - } - - /// Whether `host-replayed-indirect-commands` is announced now for the cause `key` - /// ([`Device::degrade_host_step`]): as [`now`](Self::now) answers for a kind, or, where - /// `replaying`, as [`once`](Self::once) does, but for the first time per cause. Its kind's - /// bit is set too, as `now`'s is. - pub(super) fn host_step_now(&self, key: HostStepKey, replaying: bool) -> bool { - let kind = Degradation::HostReplayedIndirectCommands; - if crate::warm::warming() { - return false; - } - if !replaying && self.each(kind) { - met_each(); - return true; - } - let mut announced = crate::device::lock(&self.host_steps); - if announced.contains(&key) { - return false; - } - announced.push(key); - let (word, bit) = kind.bit(); - self.seen[word].fetch_or(bit, Ordering::Relaxed); - true - } - - /// Whether `degradation` would be announced now ([`Announced::now`]), without counting it - /// announced: a kind the device announces at every occurrence, or one not announced yet. - /// Never on a warm pass's threads, as [`now`](Self::now). - fn pending(&self, degradation: Degradation) -> bool { - if crate::warm::warming() { - return false; - } - let (word, bit) = degradation.bit(); - self.each[word] & bit != 0 || self.seen[word].load(Ordering::Relaxed) & bit == 0 - } - - /// Whether the device announces `degradation` at every occurrence. - fn each(&self, degradation: Degradation) -> bool { - let (word, bit) = degradation.bit(); - self.each[word] & bit != 0 - } - - /// Whether the device announces any kind of `kinds` at every occurrence: an AND a word. - fn any_each(&self, kinds: &Kinds) -> bool { - self.each - .iter() - .zip(&kinds.0) - .any(|(each, kinds)| each & kinds != 0) - } -} - -/// A message the runtime says that is no degradation (a refusal Metal makes silently, a failure -/// of the runtime's own work, a call Metal ignores, a change the device's options made), said once -/// per device and kind as a degradation is: the first occurrence of its kind on the device is -/// said ([`Device::tell`]), and each later one is counted in the kind's `WorkCounts` field -/// instead, never said. The message itself (its id name, severity and text) is the call site's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Told { - /// A placement heap's texture it does not make at an offset inside it - /// (`metal2vulkan-heap-texture-refused`, `Device::new_heap_texture`): - /// `WorkCounts::heap_texture_refused_withheld`. - HeapTextureRefused, - /// A decoded twin's CPU decode that failed (`metal2vulkan-twin-decode-failed`, - /// `texture/decoded_twin.rs`): `WorkCounts::twin_decode_failed_withheld`. - TwinDecodeFailed, - /// A reservation of resource IDs made too late, which is ignored - /// (`metal2vulkan-late-reservation`, `resource_ids.rs`): - /// `WorkCounts::late_reservation_withheld`. - LateReservation, - /// A placement, or a read of the queue sharing, that the device's queue limits changed from - /// its queue plan's (`metal2vulkan-queue-limits-reached`, `DeviceOptions::queue_limits`): - /// `WorkCounts::queue_limits_reached_withheld`. - QueueLimitsReached, -} - -thread_local! { - /// The command buffer whose work this thread does now, and its generation ([`NoticesFor`]). - static NOTICES_FOR: Cell = const { - Cell::new(Scope { - command_buffer: 0, - generation: 0, - }) - }; -} - -/// What a thread's [`NoticesFor`] names: the command buffer whose work it does (its -/// `ObjectId`'s number), and that command buffer's generation of its device, the address of its -/// `DeviceShared`, which a buffer its device's recovery carried answers its parts of -/// (`Buffer::carried`, `device/carry.rs`); 0 for none of either. Two words, as one optional -/// `ObjectId` is, which each scope of a command buffer's work sets and puts back. -#[derive(Clone, Copy)] -struct Scope { - command_buffer: u64, - generation: usize, -} - -/// This thread doing one command buffer's work, from its making until it is dropped: every notice -/// announced meanwhile names that command buffer ([`DegradeNotice::command_buffer`]), and a -/// buffer its device's recovery carried answers its parts of that command buffer's generation -/// ([`NoticesFor::generation`]). Made where the runtime holds the command buffer, at each place -/// that does its work (`CommandBuffer::notices_for`); one made inside another names its own -/// command buffer until it goes, then the other's again, and [`NoticesFor::none`] names none -/// meanwhile, the generation left as it was. Neither `Send` nor `Sync`: it is this thread's. -pub(crate) struct NoticesFor { - outer: Scope, - _thread: std::marker::PhantomData<*const ()>, -} - -impl NoticesFor { - /// The work of the command buffer of ID `command_buffer`, made on `generation`, from now. - pub(crate) fn new(command_buffer: ObjectId, generation: &DeviceShared) -> NoticesFor { - let scope = Scope { - command_buffer: command_buffer.get(), - generation: std::ptr::from_ref(generation).addr(), - }; - NoticesFor { - outer: NOTICES_FOR.with(|current| current.replace(scope)), - _thread: std::marker::PhantomData, - } - } - - /// This thread's reads of a carried object's parts answer those of the generation at - /// `generation` (the address of its `DeviceShared`), until the scope goes, inside whatever - /// command buffer's work it does: a call outside command buffers' work that holds a buffer's - /// parts there (`Buffer::held_parts`). - pub(crate) fn of_generation(generation: usize) -> NoticesFor { - let outer = NOTICES_FOR.with(|current| { - let outer = current.get(); - current.set(Scope { - generation, - ..outer - }); - outer - }); - NoticesFor { - outer, - _thread: std::marker::PhantomData, - } - } - - /// Work for no command buffer, from now, inside one's: what is announced about several - /// command buffers, or about the device. The work is the outer command buffer's generation's - /// still, where it is inside one's. - pub(crate) fn none() -> NoticesFor { - let outer = NOTICES_FOR.with(|current| { - let outer = current.get(); - current.set(Scope { - command_buffer: 0, - ..outer - }); - outer - }); - NoticesFor { - outer, - _thread: std::marker::PhantomData, - } - } - - /// The command buffer whose work this thread does now, if any. - pub(crate) fn current() -> Option { - NOTICES_FOR.with(|current| ObjectId::of_number(current.get().command_buffer)) - } - - /// The generation whose command buffer's work this thread does now, if any: the address of - /// its `DeviceShared`. - pub(crate) fn generation() -> Option { - NOTICES_FOR.with(|current| Some(current.get().generation).filter(|&at| at != 0)) - } -} - -impl Drop for NoticesFor { - fn drop(&mut self) { - NOTICES_FOR.with(|current| current.set(self.outer)); - } -} - -thread_local! { - /// How many notices this thread met that their device announces, or refuses, at every - /// occurrence ([`EachWatch`]). - static MET_EACH: Cell = const { Cell::new(0) }; -} - -#[cfg(debug_assertions)] -thread_local! { - /// The messages delivered on this thread (builds with debug assertions). - static DELIVERED: Cell = const { Cell::new(0) }; -} - -/// How many messages were delivered on this thread so far (builds with debug assertions): what a -/// check that some work announced nothing compares (`render/draw_again.rs`). -#[cfg(debug_assertions)] -pub(crate) fn announced_here() -> u64 { - DELIVERED.with(Cell::get) -} - -/// Count a notice met on this thread that its device announces, or refuses, at every occurrence. -fn met_each() { - MET_EACH.with(|met| met.set(met.get().wrapping_add(1))); -} - -/// A watch over the notices the calling thread meets, from its start, that their device announces -/// at every occurrence (`DeviceOptions::announce_each`: [`Announced::now`], a bind's notices) or -/// refuses at every occurrence while it lowers a render encoder's call -/// (`DeviceOptions::lowering_refuses`, wherever it is met). Work that met none while watched announced nothing its -/// next run from the same inputs would announce again, so a memo may keep what it derived and a -/// later use take it without deriving it again (`render/draw_shape.rs`): every other kind is -/// announced once per device, which its first derivation did. It needs no list of the kinds the -/// work may announce, so it cannot drift from the work's code. -pub(crate) struct EachWatch(u64); - -impl EachWatch { - /// A watch from now. - pub(crate) fn start() -> EachWatch { - EachWatch(MET_EACH.with(Cell::get)) - } - - /// Whether this thread met such a notice since the watch started. - pub(crate) fn met(&self) -> bool { - MET_EACH.with(Cell::get) != self.0 - } -} - -/// `recorded`, the reason of a stage that records `PrecisionNote::FunctionStorageAssumed`, with -/// the private memory a thread of the stage keeps, `private_bytes`, and the Function storage the -/// device holds, `held`, measured or the floor of a device not measured: numbers only. -pub(crate) fn function_storage_reason( - recorded: &str, - private_bytes: u64, - held: FunctionStorage, -) -> String { - let evidence = match held { - FunctionStorage::Measured(_) => "measured on this device", - _ => "the floor of a device whose Function storage is not measured", - }; - format!( - "{recorded}: it keeps {private_bytes} bytes of private memory a thread, past the {} bytes \ - a thread {evidence}", - held.bytes() - ) -} - -/// Kinds of degradation, a bit each: those a variant's making may announce -/// (`VariantObjects::kinds`), which a bind of the variant tests against the kinds the device -/// announces at every occurrence before it announces any. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct Kinds([u64; WORDS]); - -impl Kinds { - /// The kinds `stages` (a variant's) may announce where the variant or a `VkPipeline` of it is - /// made (`Device::degrade_stages`, `Device::degrade_specialized`), and those of the variant's - /// `pipeline` (`Device::degrade_pipeline`): every note's, a specialized one's under any - /// specialization (a filter note's two-plane YCbCr kind among them), each other kind a - /// stage's or the pipeline's records state, [`Degradation::SetPastLayoutSupport`] where a - /// set of the pipeline's layout is one its driver may refuse though it runs it - /// (`may_pass_support`, on a driver that `understated` its support), and - /// [`Degradation::InterlockedBufferOrder`] where the variant binds a set 0 whose interlocked - /// buffers its driver orders only pushed (`unordered`, `objects::unordered_bind`), whatever - /// else the variant records: a bind announces only kinds held here. - pub(crate) fn of( - stages: &[StageModule], - pipeline: CompiledPipeline<'_>, - (understated, unordered): (bool, bool), - ) -> Kinds { - let mut kinds = Kinds::default(); - for stage in stages { - let notes = stage.precision_notes.iter().copied(); - for note in notes.chain(stage.specialized_notes.iter().map(|s| s.note)) { - kinds.add(Degradation::from_precision_note(note)); - if filter_note(note) { - kinds.add(Degradation::YCbCrFilterNotExact); - } - } - if !stage.rounded_colors.is_empty() { - kinds.add(Degradation::ShaderColorConversion); - } - if stage.reconvergence == Reconvergence::ImplementationDefined { - kinds.add(Degradation::ImplementationDefinedReconvergence); - } - } - let sets = &pipeline.layout().sets; - if sets.iter().any(|set| { - let total = set.bindings.iter().map(|b| u64::from(b.count)).sum(); - may_pass_support(total, understated) - }) { - kinds.add(Degradation::SetPastLayoutSupport); - } - if unordered { - kinds.add(Degradation::InterlockedBufferOrder); - } - if let CompiledPipeline::Render(render) = pipeline { - if render - .requirements - .properties - .contains(&VkProperty::MetalVertexSimdgroups) - { - kinds.add(Degradation::UnadvertisedVertexSimdgroups); - } - } - kinds - } - - fn add(&mut self, kind: Degradation) { - let (word, bit) = kind.bit(); - self.0[word] |= bit; - } - - /// Whether `kind` is among them. - #[cfg(test)] - pub(crate) fn holds(&self, kind: Degradation) -> bool { - let (word, bit) = kind.bit(); - self.0[word] & bit != 0 - } -} - -/// A variant's compiled pipeline, whose records beside its stages its making and binds announce -/// (`Device::degrade_pipeline`): a render state's (vertex or mesh) or a compute state's (kernel or -/// tile). -#[derive(Clone, Copy)] -pub(crate) enum CompiledPipeline<'a> { - Render(&'a RenderPipeline), - Kernel(&'a ComputePipeline), -} - -impl<'a> CompiledPipeline<'a> { - /// The pipeline's layout. - fn layout(self) -> &'a metal2vulkan::pipeline::PipelineLayout { - match self { - CompiledPipeline::Render(p) => &p.layout, - CompiledPipeline::Kernel(p) => &p.layout, - } - } - - /// The kind of pipeline state a notice of the pipeline names, from its structure: a render - /// pipeline with an object or mesh stage, or with the records of an emulated mesh, is a mesh - /// render pipeline state's; a compute pipeline of a tile function - /// (`RuntimeFact::TileFunction`) a tile render pipeline state's. - fn object(self) -> &'static str { - match self { - CompiledPipeline::Render(p) => { - let meshes = p.graphics.mesh_records.is_some() - || p.stages.iter().any(|s| { - s.stage == ShaderStage::TASK_EXT || s.stage == ShaderStage::MESH_EXT - }); - if meshes { - "a mesh render pipeline state" - } else { - "a render pipeline state" - } - } - CompiledPipeline::Kernel(p) => { - let tile = p - .dependencies - .iter() - .any(|d| d.fact == metal2vulkan::pipeline::RuntimeFact::TileFunction); - if tile { - "a tile render pipeline state" - } else { - "a compute pipeline state" - } - } - } - } -} - -/// Where a variant's notices are announced: as the variant (or a `VkPipeline` of it) is made, -/// or as a dispatch or draw binds it. -#[derive(Clone, Copy)] -pub(crate) enum Occurrence<'a> { - /// The making: every kind but those the device announces at every occurrence, once. - Made, - /// A bind: the kinds the device announces at every occurrence, at each, made into the - /// bind's notices, which the bind announces (`Device::bound_notices`). - Bound(&'a std::cell::RefCell>), - /// A dispatch or draw that binds values its functions read as data, which no making knows: - /// every kind, once, or at each occurrence where the device announces it so - /// ([`Device::degrade`]). - Drawn, -} - -/// One notice a bind of a variant announces (`Device::bound_notices`): its kind, and the message -/// the device's sink hears. -pub(crate) type BoundNotice = (Degradation, DebugMessage); - -/// Whether a kind announced at every occurrence (`each`) may be announced on this thread now: -/// in a host step (`exit_guard::host_step`), or in the program's call -/// (`exit_guard::in_program_call`) outside a pipeline pool's piece. Any kind otherwise. -pub(crate) fn each_in_order(each: bool) -> bool { - !each - || crate::exit_guard::in_host_step() - || (crate::exit_guard::in_program_call() && !crate::pipeline::pool::in_piece()) -} - -/// Where an announcement on this thread now breaks the rule, `None` where it keeps it: no kind is -/// announced inside a pipeline pool's piece (whatever the program sees is decided on its own -/// thread, in its call; a piece makes its pipelines with the notices announced, or announced at the -/// first draw), and a kind asked for at every occurrence (`each`) only in the program's call or a -/// host step ([`each_in_order`]). -pub(crate) fn announcement_breach(each: bool) -> Option { - if crate::pipeline::pool::in_piece() { - Some(NoticePlace::PipelinePoolPiece) - } else if !each_in_order(each) { - Some(NoticePlace::OutsideProgramCall) - } else { - None - } -} - -/// `Invalid` (`Problem::UndefinedValue`) where `options` set [`ResourceOptions::PRIVATE_BIT`], -/// or, where `bit_20`, [`ResourceOptions::BIT_20`]. -fn refuse_private_bit( - call: &'static str, - options: ResourceOptions, - bit_20: bool, -) -> Result<(), Error> { - let with_bit_20 = bit_20 && options.without_bit_20() != options; - match options.without_private_bit().1 || with_bit_20 { - true => Err(crate::error::invalid( - call, - crate::error::Problem::UndefinedValue { - ty: "MTLResourceOptions", - raw: options.raw(), - }, - )), - false => Ok(()), - } -} - -/// Whether a misplaced announcement ends the process: in builds with debug assertions, which -/// every lane and gate runs. -pub(crate) const MISPLACED_ENDS: bool = cfg!(debug_assertions); - -/// Where announcing `degradation` on this thread now breaks the rule ([`announcement_breach`]), -/// `None` where it keeps it. A breach ends the process, naming `degradation`, in builds with debug -/// assertions ([`MISPLACED_ENDS`]), so every lane and gate fails on it. In other builds its place -/// is answered, and the announcement goes to the notice thread (`misplaced_notices.rs`): a handler -/// may end the process at a notice, which on this thread would end it out of the program's order -/// and perhaps under a lock of the runtime's, and a sink keeping what it heard in the program's -/// thread's state would miss it. -pub(crate) fn check_announcement(degradation: Degradation, each: bool) -> Option { - placement(degradation, each, MISPLACED_ENDS) -} - -/// [`check_announcement`], ending the process at a breach where `ends`. -pub(crate) fn placement(degradation: Degradation, each: bool, ends: bool) -> Option { - let place = announcement_breach(each)?; - if ends { - eprintln!("{}: {degradation:?}", place.line()); - std::process::abort(); - } - Some(place) -} - -/// The notice of a draw of `call` that reads or writes memory an attachment of its render pass -/// instance renders (`Degradation::AttachmentReadInPlace`). -fn attachment_read_notice(call: &'static str) -> (String, String) { - ( - format!("a draw ({call})"), - "a function of the draw reads or writes, other than as an attachment, memory an \ - attachment of its render pass instance renders" - .to_owned(), - ) -} - -impl super::encoder::EncoderCore { - // A draw's checks, of the generation its command buffer holds (`CommandBuffer::generation`). - - /// Announce `AttachmentReadInPlace` where `uses`, what a draw of `call` binds or reaches, - /// share memory with an attachment of its render pass instance, as `shares` answers - /// (`render_target::shares_attachment`, or a render encoder's `AttachedMemo` of it). The check - /// runs only while the kind would be announced: once it was, a device that announces it once - /// skips it. - pub(super) fn degrade_attachment_reads( - &self, - call: &'static str, - shares: impl FnOnce(&[Use]) -> Result, - uses: &[Use], - ) -> Result<(), Error> { - let kind = Degradation::AttachmentReadInPlace; - if !self.generation().announced.pending(kind) || !shares(uses)? { - return Ok(()); - } - self.device().degrade(kind, || attachment_read_notice(call)); - Ok(()) - } - - /// [`degrade_attachment_reads`](Self::degrade_attachment_reads) of a draw whose `uses` differ - /// from those of the last draw of its encoder, drawn against the same attachments, only in - /// `moved` (a draw moved: `render/draw_again/rebound.rs`): of those alone, as each other use - /// is that draw's, which the check found sharing none while it ran (checked in builds with - /// debug assertions). - pub(super) fn degrade_moved_attachment_reads( - &self, - call: &'static str, - mut shares: impl FnMut(&[Use]) -> Result, - (moved, uses): (&[Use], &[Use]), - ) -> Result<(), Error> { - let kind = Degradation::AttachmentReadInPlace; - if !self.generation().announced.pending(kind) { - return Ok(()); - } - let shared = shares(moved)?; - #[cfg(debug_assertions)] - assert_eq!( - shared, - shares(uses)?, - "a draw moved's uses but the moved ones share memory with an attachment" - ); - #[cfg(not(debug_assertions))] - let _ = uses; - if shared { - self.device().degrade(kind, || attachment_read_notice(call)); - } - Ok(()) - } - - /// [`degrade_attachment_reads`](Self::degrade_attachment_reads) of a draw whose `uses` begin - /// with those of what its encoder made resident of the identity `prefix`: of those, the uses - /// past them alone where they were found to share none with a layout of `version` - /// (`CommandUses::apart`), `None` for one of no version - /// (`WorkCounts::resident_uses_against_attachments` counts those it walked). - pub(super) fn degrade_resident_attachment_reads( - &self, - call: &'static str, - (mut shares, version): ( - impl FnMut(&[Use]) -> Result, - Option, - ), - (uses, prefix): (&mut CommandUses, ResidentPrefix), - ) -> Result<(), Error> { - let kind = Degradation::AttachmentReadInPlace; - if !self.generation().announced.pending(kind) { - return Ok(()); - } - let past = version.map_or(0, |version| uses.apart(version)); - let shared = shares(&uses[past..])?; - #[cfg(debug_assertions)] - assert_eq!( - shared, - shares(uses)?, - "a draw's uses checked against the attachments by their identity less than its uses" - ); - if past == 0 { - let counts = self.generation().counts.thread(); - counts.resident_uses_against_attachments(prefix.len as u64); - if let Some(version) = version.filter(|_| !shared) { - uses.apart_from(version); - } - } - if shared { - self.device().degrade(kind, || attachment_read_notice(call)); - } - Ok(()) - } -} - -impl Device { - /// Say the message `message` makes, of kind `told`, unless the device said one of that kind - /// before: through the device's message sink, else on stderr, on the calling thread. A later - /// one is counted ([`Told`]) and not made. - #[cold] - pub(crate) fn tell(&self, told: Told, message: impl FnOnce() -> DebugMessage) { - let shared = self.shared(); - if !shared.announced.first(told) { - shared.counts.told_withheld(told); - return; - } - let message = message(); - match shared.instance.sink() { - Some(sink) => sink.deliver(&message), - None => eprintln!("{}", message.text), - } - } - - /// Announce `degradation` unless the device announced it before (but a kind its options ask - /// for at each occurrence, `DeviceOptions::announce_each`), `describe` giving the object and - /// the reason: through the device's message sink, else on stderr, on the calling thread (the - /// module docs). - #[cold] - pub(super) fn degrade( - &self, - degradation: Degradation, - describe: impl FnOnce() -> (String, String), - ) { - let first = |announced: &Announced, replaying: bool| match replaying { - true => announced.once(degradation), - false => announced.now(degradation), - }; - self.degrade_where(degradation, first, describe); - } - - /// Announce `copied-host-pages` for `reason` as [`degrade`](Self::degrade) announces a kind, - /// but once per reason rather than once per kind: the cause of a copy (`CopiedBecause`), or - /// `None` for a buffer lying in the live copy another buffer was made over. A consumer acts on - /// a refused import, a failed one and a move apart, so each is heard. - #[cold] - pub(super) fn degrade_copied_pages( - &self, - reason: Option, - describe: impl FnOnce() -> (String, String), - ) { - let first = |announced: &Announced, replaying| announced.copied_now(reason, replaying); - self.degrade_where(Degradation::CopiedHostPages, first, describe); - } - - /// Announce `host-replayed-indirect-commands` for the cause `key` as - /// [`degrade`](Self::degrade) announces a kind, but once per cause rather than once per kind: - /// the rule that kept a render pass from the GPU form, which its notice names, a render pass's - /// step that names none, or a compute execution's. A walk of a program sees why each of its - /// GPU-driven passes takes the host step, not only the first one met. - #[cold] - pub(crate) fn degrade_host_step( - &self, - key: HostStepKey, - describe: impl FnOnce() -> (String, String), - ) { - let first = |announced: &Announced, replaying| announced.host_step_now(key, replaying); - self.degrade_where(Degradation::HostReplayedIndirectCommands, first, describe); - } - - /// Whether [`degrade_host_step`](Self::degrade_host_step) would describe its notice for the - /// cause `key` now, outside a call encoded again: where the device refuses the kind while - /// lowering a call, or the cause is not announced yet (each time, where the device announces - /// the kind at every occurrence). Counts nothing announced: what a notice names that costs - /// its finding is found only then (`render/executions/cause.rs`). - pub(crate) fn announces_host_step(&self, key: HostStepKey) -> bool { - let shared = self.shared(); - shared.lowering_refuses(Degradation::HostReplayedIndirectCommands) - || shared.announced.host_step_unannounced(key) - } - - /// Announce `degradation` where `first` answers it is announced now, given the device's - /// record and whether a call is encoded again at a rebind ([`degrade`](Self::degrade)). - #[cold] - fn degrade_where( - &self, - degradation: Degradation, - first: impl FnOnce(&Announced, bool) -> bool, - describe: impl FnOnce() -> (String, String), - ) { - let shared = self.shared(); - // A kind the device refuses while lowering a call after it returned refuses the call, - // at every occurrence, rather than being announced (`render/deferral.rs`): met at every - // occurrence wherever it is met ([`EachWatch`]), as a call met in one place may be - // lowered in the other. - let refuses = shared.lowering_refuses(degradation); - if refuses { - met_each(); - } - if refuses && crate::render::lowering::refusing() { - let (object, reason) = describe(); - crate::render::lowering::refuse(DegradeNotice::new(degradation, object, reason)); - return; - } - // A call encoded again at a rebind met what the program's call met, which announced it: - // each kind at most once there (`replay.rs`). - if !first(&shared.announced, crate::replay::is_replaying()) { - return; - } - // No kind is announced inside a pipeline pool's piece, and a kind asked for at every - // occurrence is announced inside the program's own call that met it, or in a command - // buffer's host step, a serial point of its stream before the batch is submitted: a - // consumer's handler may end the process at it, which a pipeline pool's piece, or any - // other thread of the runtime's, would do out of the program's order (the owner's HITCH - // rule 1), and a sink keeping what it heard in its thread's state would miss it. - let misplaced = check_announcement(degradation, shared.announced.each(degradation)); - let (object, reason) = describe(); - let message = DegradeNotice::new(degradation, object, reason).message(); - self.deliver_placed(degradation, message, misplaced); - } - - /// Announce a recovery of the device from the loss of its `VkDevice` - /// (`Degradation::DeviceRecovered`, `device/line.rs`): at each, whatever the kind's record - /// says, since each names its own culprit; inside the program's call that made it. - pub(super) fn degrade_recovered(&self, describe: impl FnOnce() -> (String, String)) { - let degradation = Degradation::DeviceRecovered; - let misplaced = check_announcement(degradation, true); - let (object, reason) = describe(); - // The device's, whichever command buffer's work met it. - let _device = NoticesFor::none(); - let message = DegradeNotice::new(degradation, object, reason).message(); - self.deliver_placed(degradation, message, misplaced); - } - - /// Announce a step of a recovery of the device that went past its bound or failed - /// (`Degradation::DeviceRecovered`, `device/line.rs`): a call's wait for the recovery past - /// `RECOVERY_NOTICE`, its command buffers in flight taking past it to fail, or its new - /// `VkDevice`'s failure. Whatever the kind's record says, as each recovery's notices are its - /// own, the line announcing each step at most once per recovery; met where no program call - /// may be (a runtime thread's call waiting for the recovery), as `degrade_once`'s kinds are. - pub(super) fn degrade_recovery_step(&self, describe: impl FnOnce() -> (String, String)) { - let degradation = Degradation::DeviceRecovered; - let misplaced = check_announcement(degradation, false); - let (object, reason) = describe(); - // The device's, whichever command buffer's work met it. - let _device = NoticesFor::none(); - let message = DegradeNotice::new(degradation, object, reason).message(); - self.deliver_placed(degradation, message, misplaced); - } - - /// Announce `degradation` once per device, whatever `DeviceOptions::announce_each` says, - /// `describe` giving the object and the reason: for a kind met where no program call or host - /// step may be (a runtime thread letting go of what it held). - pub(super) fn degrade_once( - &self, - degradation: Degradation, - describe: impl FnOnce() -> (String, String), - ) { - if !self.shared().announced.once(degradation) { - return; - } - let misplaced = check_announcement(degradation, false); - let (object, reason) = describe(); - let message = DegradeNotice::new(degradation, object, reason).message(); - self.deliver_placed(degradation, message, misplaced); - } - - /// Announce, once, that a command buffer's command named a buffer rebound after it was - /// encoded and before the command buffer was first submitted - /// (`CommandBufferError::EncodedUseRebound`), where its first submission `found` the first - /// such use, and why no rebind encoded it again (`command_buffer/rebound_use.rs`): on the - /// thread that submits it, with no lock of the command buffer's held. - pub(super) fn degrade_encoded_use_rebound( - &self, - found: Option, - ) { - let shared = self.shared(); - if !shared.announced.once(Degradation::EncodedUseRebound) { - return; - } - let misplaced = check_announcement(Degradation::EncodedUseRebound, false); - let mut reason = "a buffer over host pages they named was rebound after they were \ - encoded and before the command buffer was submitted, and their use was \ - resolved as encoded" - .to_owned(); - if let Some(found) = found { - reason.push_str(&format!(" ({found})")); - } - let message = DegradeNotice::new( - Degradation::EncodedUseRebound, - "a command buffer's commands".to_owned(), - reason, - ) - .message(); - self.deliver_placed(Degradation::EncodedUseRebound, message, misplaced); - } - - /// Announce `kind` (`StaleDetachedReach` or `DetachedStorageKeepsWrites`) for the texture of - /// `texture`, which a command buffer may reach without naming it while its bytes are - /// detached (`Device::reach_stale_detached`, `Device::reach_storage_sinks`, which meet each - /// texture once and count it): with no lock of the command buffer's held. Once per kind, - /// naming the first texture; `DetachedStorageKeepsWrites` at each texture where the device's - /// options ask (it is met in the program's `commit`), `StaleDetachedReach` once whatever - /// they say (a submission may run on the scheduler's thread, outside any program call or - /// host step). - pub(super) fn degrade_detached_reach(&self, kind: Degradation, texture: ObjectId) { - let shared = self.shared(); - let each = kind != Degradation::StaleDetachedReach && shared.announced.each(kind); - let now = match each { - true => shared.announced.now(kind), - false => shared.announced.once(kind), - }; - if !now { - return; - } - let misplaced = check_announcement(kind, each); - let reason = match kind { - Degradation::StaleDetachedReach => { - "its bytes were detached after a submitted command buffer made them resident, and \ - a submitted command buffer bound a heap set, through which its commands may read \ - it without naming it" - } - _ => { - "its bytes are detached and its stand-in has a sink, and a committed command \ - buffer bound a heap set, through which its commands may write and read it \ - without naming it" - } - }; - let mut notice = DegradeNotice::new( - kind, - format!("texture of object ID {}", texture.get()), - reason.to_owned(), - ); - notice.object_id = Some(texture); - self.deliver_placed(kind, notice.message(), misplaced); - } - - /// Count the texture of `texture`, made in a heap in this program call, as laid out - /// otherwise than Metal lays it in the heap's bytes, for `untiled`'s reason - /// (`heap-texture-*-layout`, `texture/heap_tiled.rs`, `texture/heap.rs`), and announce it, with - /// its ID, where it is the first of its kind (or at each texture, where the device's options - /// ask). - pub(super) fn degrade_heap_layout(&self, untiled: Untiled, texture: ObjectId) { - let shared = self.shared(); - let kind = untiled.kind; - shared.counts.heap_layout_degraded(kind); - if !shared.announced.now(kind) { - return; - } - let misplaced = check_announcement(kind, shared.announced.each(kind)); - let mut notice = DegradeNotice::new( - kind, - format!("texture of object ID {}", texture.get()), - untiled.reason.to_owned(), - ); - notice.object_id = Some(texture); - self.deliver_placed(kind, notice.message(), misplaced); - } - - /// How many objects this device met as `kind` so far, for a kind it meets once per object - /// and announces once (naming the first object, [`DegradeNotice::object_id`]), so that a - /// census counts them without a notice each: the textures made in heaps laid out otherwise - /// than Metal lays them in the heap's bytes ([`Degradation::HeapTextureLosslessLayout`], - /// [`Degradation::HeapTextureBlockCompressedLayout`] and - /// [`Degradation::HeapTextureUntiledLayout`], each counted as it is made), and the textures - /// over detached bytes a command buffer could reach unnamed - /// ([`Degradation::StaleDetachedReach`] and [`Degradation::DetachedStorageKeepsWrites`], each - /// counted once, where first reached). `None` for every other kind, which the device - /// announces once without counting. Counted whether or not the device's options ask for - /// each occurrence (`DeviceOptions::announce_each`). No Metal counterpart. - pub fn degraded_objects(&self, kind: Degradation) -> Option { - self.current().degraded_objects_now(kind) - } - - /// [`Device::degraded_objects`] on the generation that serves (`device/line.rs`). - pub(crate) fn degraded_objects_now(&self, kind: Degradation) -> Option { - self.shared().counts.degraded_objects(kind) - } - - /// `degrade` a variant's notice `at` its making or a bind: a kind the - /// device announces at every occurrence at a bind alone, every other kind at the making - /// alone. - fn degrade_at( - &self, - at: Occurrence<'_>, - degradation: Degradation, - describe: impl FnOnce() -> (String, String), - ) { - let each = self.shared().announced.each(degradation); - match at { - Occurrence::Made if !each => self.degrade(degradation, describe), - // Made into the bind's notices, which it announces as `degrade` would: a kind the - // device announces at every occurrence is announced at each. - Occurrence::Bound(notices) if each => { - let (object, reason) = describe(); - let message = DegradeNotice::new(degradation, object, reason).message(); - notices.borrow_mut().push((degradation, message)); - } - Occurrence::Made | Occurrence::Bound(_) => {} - Occurrence::Drawn => self.degrade(degradation, describe), - } - } - - /// Whether a bind of a variant of `kinds` (`Kinds::of`) announces any of them: whether the - /// device's options ask for any at every occurrence (`DeviceOptions::announce_each`), an AND - /// a word. A bind that would take work to describe its notices (the formats it binds) asks - /// first. - pub(crate) fn binds_each(&self, kinds: &Kinds) -> bool { - self.shared().announced.any_each(kinds) - } - - /// The notices a dispatch's or draw's bind of a variant announces - /// ([`announce_bound`](Self::announce_bound)): those its making announces whose kinds the - /// device's options ask for at every occurrence (`DeviceOptions::announce_each`), with the - /// making's object and reason, in the order the making announces them (a memoized variant is - /// made once, so its making alone would announce them once). `stages` are the variant's - /// stages, `pipeline` its compiled pipeline, and `specializations` the specializations and - /// bound formats of the `VkPipeline`s the bind takes (`Device::degrade_specialized`). - pub(crate) fn bound_notices( - &self, - (stages, pipeline): (&[StageModule], CompiledPipeline<'_>), - specializations: &[(&SpecializationKey, Option>)], - ) -> Vec { - let notices = std::cell::RefCell::new(Vec::new()); - let at = Occurrence::Bound(¬ices); - self.degrade_pipeline(pipeline, at); - self.degrade_stages(stages, at); - for (n, &(specialization, formats)) in specializations.iter().enumerate() { - // A specialization the bind takes twice (a split dispatch's regions) announces once. - if specializations[..n] - .iter() - .any(|&(earlier, _)| earlier == specialization) - { - continue; - } - self.degrade_specialized(stages, specialization, formats, at); - } - notices.into_inner() - } - - /// Announce `notices`, a bind's ([`bound_notices`](Self::bound_notices)), on the calling - /// thread, each as [`degrade`](Self::degrade) announces a kind the device announces at every - /// occurrence: through the device's message sink, else on stderr. - pub(crate) fn announce_bound(&self, notices: &[BoundNotice]) { - // A warm pass announces nothing ([`Announced::now`]). - if crate::warm::warming() { - return; - } - for (degradation, message) in notices { - met_each(); - // Made by an earlier bind: named as this one's. - let here = (message.degradation.as_ref()) - .and_then(DegradeNotice::announced_here) - .map(|notice| DebugMessage { - degradation: Some(notice), - ..message.clone() - }); - let message = here.as_ref().unwrap_or(message); - match check_announcement(*degradation, true) { - None => self.deliver(message), - misplaced => self.deliver_placed(*degradation, message.clone(), misplaced), - } - } - } - - /// Hand `message` to the device's message sink, else write it on stderr. - fn deliver(&self, message: &DebugMessage) { - #[cfg(debug_assertions)] - DELIVERED.with(|delivered| delivered.set(delivered.get() + 1)); - match self.shared().instance.sink() { - Some(sink) => sink.deliver(message), - None => eprintln!("{}", message.text), - } - } - - /// Hand `message`, of `degradation`, to the device's message sink on this thread where its - /// announcement keeps the rule (`misplaced` is `None`); else, in a build without debug - /// assertions, to the notice thread, with the device's `misplaced-notice` after it - /// ([`misplaced_notices::deliver`](crate::misplaced_notices::deliver)). - fn deliver_placed( - &self, - degradation: Degradation, - message: DebugMessage, - misplaced: Option, - ) { - match misplaced { - None => self.deliver(&message), - Some(place) => { - let shared = self.shared(); - crate::misplaced_notices::deliver( - shared.instance.sink(), - &shared.announced, - MisplacedNotice { - kind: degradation, - place, - }, - message, - ); - } - } - } - - /// `options` as the runtime makes `call`'s resource of them where Metal makes it with - /// [`ResourceOptions::PRIVATE_BIT`] and keeps the GPU's writes from its memory (a heap of - /// the runtime's memory; an indirect command buffer, whose GPU-written records under it are - /// not measured): without the bit, announced once ([`Degradation::PrivateResourceOption`]). - pub(super) fn take_options( - &self, - call: &'static str, - options: ResourceOptions, - ) -> ResourceOptions { - // Bit 20 is dropped unannounced, as Metal makes a heap with it and reports it without. - let (taken, private) = options.without_bit_20().without_private_bit(); - if private { - self.degrade(Degradation::PrivateResourceOption, || { - ( - format!("`{call}` with resource options {:#x}", options.raw()), - "the resource is made as without Metal's private option bit 24 (0x1000000), \ - and its options read without it" - .to_owned(), - ) - }); - } - taken - } - - /// `options` of `call`'s resource whose memory the runtime gives it (a buffer of a length or - /// of bytes, a Vulkan buffer of the caller's): refused where they set - /// [`ResourceOptions::PRIVATE_BIT`] (`Invalid`, `Problem::UndefinedValue`), as Metal ends the - /// process there (the M3 Max under macOS 27.0.1: `newBufferWithLength:options:` and - /// `newBufferWithBytes:length:options:`, `Shared` or `Private`, assert in the buffer's - /// suballocator, "Different MTLResourceOptions used for the same heap index"); without - /// [`ResourceOptions::BIT_20`], as Metal makes such a buffer with it and reports it without. - pub(super) fn own_memory_options( - &self, - call: &'static str, - options: ResourceOptions, - ) -> Result { - refuse_private_bit(call, options, false)?; - Ok(options.without_bit_20()) - } - - /// `descriptor`, refused where its options set [`ResourceOptions::PRIVATE_BIT`] (`Invalid`, - /// `Problem::UndefinedValue`), as Metal's texture descriptor validation ends the process there - /// for every texture (the M3 Max under macOS 27.0.1: "MTLResourceOptions (0x1000000) contains - /// unknown bits", a device's texture, `Shared` or `Private`, a heap's, a buffer's and a - /// shareable one alike), or [`ResourceOptions::BIT_20`], with which Metal's suballocator ends - /// the process for a device's texture (the M3 Max under macOS 27.0.1, `Shared`). - pub(super) fn texture_options( - &self, - call: &'static str, - descriptor: &TextureDescriptor, - ) -> Result { - refuse_private_bit(call, descriptor.resource_options, true)?; - Ok(*descriptor) - } - - /// Announce what `stages` (a variant's) record, `at` its making or a bind - /// ([`Occurrence`]): each precision note no specialization removes (the specialized ones are - /// [`Device::degrade_specialized`]'s), and reconvergence that is not Metal's. - pub(super) fn degrade_stages(&self, stages: &[StageModule], at: Occurrence<'_>) { - for stage in stages { - let object = || stage_object(stage.stage).to_owned(); - for ¬e in &stage.precision_notes { - if stage.specialized_notes.iter().any(|s| s.note == note) { - continue; - } - // Announced at a draw or dispatch that lists a state needing it - // (`Device::degrade_argument_pixel_samplers`), not at the making or a bind. - if note == PrecisionNote::ArgumentPixelSamplerScaling { - continue; - } - // Announced at a draw that rasterizes points (`Device::degrade_point_size`), the - // one primitive a point size sizes, not at the making or a bind. - if note == PrecisionNote::DevicePointSize { - continue; - } - self.degrade_at(at, Degradation::from_precision_note(note), || { - (object(), self.stage_note_reason(note, stage)) - }); - } - if !stage.rounded_colors.is_empty() { - self.degrade_at(at, Degradation::ShaderColorConversion, || { - ( - object(), - format!( - "the pipeline rounds the half-float channels of color \ - attachment(s) {:?} to nearest even (its texture write rounding \ - mode), which the device's conversion does not", - stage.rounded_colors - ), - ) - }); - } - if stage.reconvergence == Reconvergence::ImplementationDefined { - self.degrade_at(at, Degradation::ImplementationDefinedReconvergence, || { - ( - object(), - "it reads subgroup state after divergence, and the device does not \ - reconverge maximally" - .to_owned(), - ) - }); - } - } - } -} - -impl Device { - /// Announce, `at` its variant's making or a bind ([`Occurrence`]), what a variant's `pipeline` - /// records beside its stages: for a render variant, requirements that hold a vertex - /// function's subgroup operations on a driver that runs them as Metal does without advertising - /// the vertex stage ([`Degradation::UnadvertisedVertexSimdgroups`]), and, for any, a set - /// layout its driver refuses though it runs it ([`Degradation::SetPastLayoutSupport`], before - /// any layout of the variant is made), naming the pipeline state's kind (render, mesh render, - /// tile render or compute), and for a render variant a bound set 0 whose interlocked buffers - /// its driver orders only pushed ([`Degradation::InterlockedBufferOrder`]); for the base - /// variant and every other alike, each pipeline by its own records. - pub(super) fn degrade_pipeline(&self, pipeline: CompiledPipeline<'_>, at: Occurrence<'_>) { - if self - .shared() - .announced - .pending(Degradation::SetPastLayoutSupport) - { - for set in &pipeline.layout().sets { - if set_layout_support(self, set) != SetSupport::Understated { - continue; - } - let total: u64 = set.bindings.iter().map(|b| u64::from(b.count)).sum(); - self.degrade_at(at, Degradation::SetPastLayoutSupport, || { - ( - pipeline.object().to_owned(), - format!( - "its set {} holds {total} descriptors, which {} makes and runs as \ - Metal runs the argument buffer it encodes the set in (measured, \ - `RuntimeDriverDefect::SetLayoutSupportUnderstated`) though its \ - driver's vkGetDescriptorSetLayoutSupport refuses the layout", - set.set, - self.name() - ), - ) - }); - } - } - let CompiledPipeline::Render(render) = pipeline else { - return; - }; - let kind = Degradation::InterlockedBufferOrder; - let unordered = match self.shared().announced.pending(kind) { - true => unordered_bind(self, &render.layout, &render.stages, pipeline), - false => None, - }; - if let Some(why) = unordered { - self.degrade_at(at, kind, || { - let why = match why { - UnorderedBind::NoPushCommand => "the device has no push command", - UnorderedBind::SetZero => "its set 0 is no push descriptor set layout's", - UnorderedBind::Lengths => { - "a stage reads a buffer's length, which its driver's pushed sets do not \ - hold (`RuntimeDriverDefect::PushedBufferSizesUnset`)" - } - }; - ( - stage_object(ShaderStage::FRAGMENT).to_owned(), - format!( - "it writes a storage buffer of set 0 inside its interlock, which {} \ - orders between overlapping fragments only where set 0 is pushed \ - (`RuntimeDriverDefect::InterlockedBoundBuffersUnordered`), and its set 0 \ - is bound: {why}", - self.name() - ), - ) - }); - } - if render - .requirements - .properties - .contains(&VkProperty::MetalVertexSimdgroups) - { - self.degrade_at(at, Degradation::UnadvertisedVertexSimdgroups, || { - ( - stage_object(ShaderStage::VERTEX).to_owned(), - format!( - "it runs simdgroup functions, which {} runs as Metal does in a vertex \ - function (measured, `DriverDeviation::MetalVertexSimdgroups`) though \ - its driver does not list the vertex stage among its subgroup stages", - self.name() - ), - ) - }); - } - } -} - -impl Device { - /// Announce, once, a pipeline state whose `dependencies` state that a stage may read an - /// argument its function constants removed, naming that stage's function by `name` - /// ([`Degradation::AbsentArgumentRead`]). - pub(super) fn degrade_absent_reads( - &self, - dependencies: &[metal2vulkan::pipeline::RuntimeDependency], - name: impl Fn(metal2vulkan::pipeline::Stage) -> String, - ) { - let Some(stage) = dependencies.iter().find_map(|d| match d.fact { - metal2vulkan::pipeline::RuntimeFact::AbsentArgumentRead { stage } => Some(stage), - _ => None, - }) else { - return; - }; - self.degrade(Degradation::AbsentArgumentRead, || { - ( - format!("the {stage:?} function {}", name(stage)), - "it reads an argument its function constants removed where something observes \ - the read" - .to_owned(), - ) - }); - } - - /// Announce, once, a render pipeline state `object` whose `dependencies` state that its draws - /// run a synthesized geometry stage ([`Degradation::SynthesizedGeometryStage`]), naming why: - /// the barycentric weights its fragment function reads, or the slice or viewport its vertex - /// function selects. - pub(super) fn degrade_synthesized_geometry( - &self, - dependencies: &[metal2vulkan::pipeline::RuntimeDependency], - object: impl FnOnce() -> String, - ) { - let Some((weights, layer, viewport)) = dependencies.iter().find_map(|d| match d.fact { - metal2vulkan::pipeline::RuntimeFact::SynthesizedGeometry { - weights, - layer, - viewport, - } => Some((weights, layer, viewport)), - _ => None, - }) else { - return; - }; - self.degrade(Degradation::SynthesizedGeometryStage, || { - let mut why = Vec::new(); - if weights { - why.push( - "its fragment function reads [[barycentric_coord]] on a device without \ - fragmentShaderBarycentric", - ); - } - if layer { - why.push( - "its vertex function selects its primitive's render target slice on a device \ - that cannot store Layer from a vertex function", - ); - } - if viewport { - why.push( - "its vertex function selects its primitive's viewport on a device that cannot \ - store ViewportIndex from a vertex function", - ); - } - (object(), why.join(", and ")) - }); - } - - /// Announce the specialized notes of `stages` (a variant's) that hold under `specialization`, - /// the one a `VkPipeline` of the variant is made with, `at` its making or a bind - /// ([`Occurrence`]): the notes the bound formats and samplers leave on an arm that is not - /// Metal's (`StageModule::precision_notes_under`). The reason names each texture slot a holding - /// clause tests (`StageModule::note_clauses_under`) and, where the command that makes the - /// pipeline knows them (`formats`), the format it binds there, so the notice says which bound - /// format is left. - pub(super) fn degrade_specialized( - &self, - stages: &[StageModule], - specialization: &SpecializationKey, - formats: Option>, - at: Occurrence<'_>, - ) { - for stage in stages.iter().filter(|s| !s.specialized_notes.is_empty()) { - for s in &stage.specialized_notes { - // A clause of the bound formats alone is `degrade_bound_formats`', at each draw or - // dispatch: its pipeline's key does not tell it. - // Nor does it tell a clause of a value the function reads as data: - // `degrade_bound_values`', at each draw or dispatch. - let clauses: Vec<_> = stage - .note_clauses_under(s.note, specialization) - .into_iter() - .filter(|c| !c.tests_bound_formats() && !c.tests_bound_values()) - .collect(); - self.degrade_clauses( - stage, - s.note, - &clauses, - formats, - at, - "under the formats and samplers its pipeline was made for", - ); - } - } - } - - /// Whether a note of `stages` has a clause that tests a value its function reads as data - /// (`SpecClause::tests_bound_values`): where none has, - /// [`degrade_bound_values`](Self::degrade_bound_values) tests no clause, announces nothing - /// and answers quiet, so a caller may leave it out. - pub(crate) fn tests_bound_values(stages: &[StageModule]) -> bool { - stages.iter().any(|stage| { - stage - .specialized_notes - .iter() - .any(|s| s.when.iter().any(|c| c.tests_bound_values())) - }) - } - - /// Announce, at a draw or dispatch that binds a pipeline of `stages` made under - /// `specialization`, each specialized note one of whose clauses tests a value its function - /// reads as data or a bound sampler's word (`SpecClause::tests_bound_values`: a bound - /// texture's format class, `SpecKey::BoundSamplerWord`) and holds where the draw's plan gives - /// the values `bound` gives (`BindingPlan::specialized_value`; - /// `StageModule::note_clauses_bound`; and what the command's handles can name, - /// `SpecKey::HeapYCbCrTextures`, `SpecKey::HeapRawTextures` and - /// `SpecKey::FilteringArgumentSampler`, which the plan gives too: a filter note's heap - /// texture, a heap decode's raw one), the class of the format `formats` binds at each - /// texture slot such a clause also tests (`SpecKey::BoundTexelFormat`: a filter note's - /// two-plane YCbCr format under a runtime sampler's filtering word). A clause testing a slot - /// bound to nothing does not hold, as [`degrade_bound_formats`](Self::degrade_bound_formats) - /// reads it; a command whose formats are not known (`None`) holds each such test. No - /// pipeline's key carries those values, so no making can announce such a clause: one - /// `VkPipeline` serves every bound value. The reason names each texture slot a holding clause - /// tests and, where the command knows them, the format it binds there. A kind already - /// announced costs one atomic load (a filter note's kind `ycbcr-filter-not-exact`, which its - /// clauses announce). - /// - /// Whether it was quiet: no clause of a note it tested held. Which clauses hold is a function - /// of `stages`, `specialization`, `bound` and the formats at the slots they test, which the - /// plan whose values `bound` gives fixes (each bound texture's format is in the shape it is - /// planned for), and a note it skipped as announced stays skipped (a kind announced at every - /// occurrence is never skipped), so another call with the same three after a quiet one - /// announces nothing: a caller may leave it out (`render.rs`, `QuietBoundValues`). - pub(crate) fn degrade_bound_values( - &self, - stages: &[StageModule], - specialization: &SpecializationKey, - bound: &dyn Fn(SpecKey) -> Option, - formats: Option>, - ) -> bool { - // The plan's values, and the class of each format the command binds. - let values = |key: SpecKey| match key { - SpecKey::BoundTexelFormat(slot) => formats - .and_then(|f| f(slot)) - .map(|pf| u64::from(metal2vulkan::metal::format::bound_texel_format(pf))), - key => bound(key), - }; - // A slot bound to nothing reads zero: a clause testing one does not hold. - let unbound = |slot: SlotRef| formats.is_some_and(|f| f(slot).is_none()); - let mut quiet = true; - for stage in stages { - for s in &stage.specialized_notes { - let kind = match filter_note(s.note) { - true => Degradation::YCbCrFilterNotExact, - false => Degradation::from_precision_note(s.note), - }; - if !s.when.iter().any(|c| c.tests_bound_values()) - || !self.shared().announced.pending(kind) - { - continue; - } - let clauses: Vec<_> = stage - .note_clauses_bound(s.note, specialization, &values) - .into_iter() - .filter(|c| c.tests_bound_values()) - .filter(|c| { - !c.all.iter().any( - |t| matches!(t.key, SpecKey::BoundTexelFormat(slot) if unbound(slot)), - ) - }) - .collect(); - quiet &= clauses.is_empty(); - self.degrade_clauses( - stage, - s.note, - &clauses, - formats, - Occurrence::Drawn, - "under the formats and samplers it binds", - ); - } - } - quiet - } - - /// Announce `note` of `stage`, `at` ([`Occurrence`]), where `clauses`, the clauses of its - /// specialized note that hold, are not empty: a filter note's slot bound to a two-plane YCbCr - /// texture (or, where the command's formats are not known, `formats` `None`, to the format its - /// clause tests, a two-plane YCbCr one), and its clause of a heap's texture - /// (`SpecKey::HeapYCbCrTextures`), as its own kind, and the note's kind where a clause that - /// holds tests another slot, or none, the reason naming each such slot (with its bound - /// format, where `formats` knows it) after `under`. - fn degrade_clauses( - &self, - stage: &StageModule, - note: PrecisionNote, - clauses: &[&metal2vulkan::pipeline::SpecClause], - formats: Option>, - at: Occurrence<'_>, - under: &str, - ) { - if clauses.is_empty() { - return; - } - let all = tested_slots(clauses.iter().copied()); - // A filter note's slot bound to a two-plane YCbCr texture: its own kind, naming the slot - // and the format; the note's own where a clause that holds tests another slot, or none. - let ycbcr: Vec<(SlotRef, Option)> = all - .iter() - .filter(|_| filter_note(note)) - .filter_map(|&slot| match formats { - Some(f) => { - let format = f(slot)?; - metal2vulkan::metal::format::ycbcr_format(format).map(|_| (slot, Some(format))) - } - None => Some((slot, None)), - }) - .collect(); - let held = |slot: &SlotRef| ycbcr.iter().any(|(y, _)| y == slot); - for &(slot, format) in &ycbcr { - self.degrade_at(at, Degradation::YCbCrFilterNotExact, || { - let bound = match format { - Some(format) => format!("bound as {format:?}"), - None => "of a format the GPU's commands bind".to_owned(), - }; - ( - stage_object(stage.stage).to_owned(), - format!( - "a filtered sample of texture {} {bound} takes the device's filter, not \ - Metal's exact filter of the format: {}", - slot.index, - self.note_reason(note) - ), - ) - }); - } - // A filter note's clause of a heap's texture: a two-plane YCbCr texture the stage's - // handles can name (`SpecKey::HeapYCbCrTextures`), its own kind too. - let heap = |c: &&metal2vulkan::pipeline::SpecClause| { - filter_note(note) - && (c.all.iter()).any(|t| matches!(t.key, SpecKey::HeapYCbCrTextures(_))) - }; - if clauses.iter().any(heap) { - self.degrade_at(at, Degradation::YCbCrFilterNotExact, || { - ( - stage_object(stage.stage).to_owned(), - format!( - "a filtered sample of a texture its argument buffers name takes the \ - device's filter, not Metal's exact filter of the format, and a texture \ - the command makes resident or binds that they can name is two-plane \ - YCbCr: {}", - self.note_reason(note) - ), - ) - }); - } - let covered = |c: &&metal2vulkan::pipeline::SpecClause| { - let tested = tested_slots([*c]); - heap(c) || (!tested.is_empty() && tested.iter().all(held)) - }; - if clauses.iter().all(covered) { - return; - } - self.degrade_at(at, Degradation::from_precision_note(note), || { - let bound: Vec = all - .iter() - .filter(|slot| !held(slot)) - .map(|&slot| match formats.map(|f| f(slot)) { - Some(Some(format)) => format!("texture {} bound as {format:?}", slot.index), - Some(None) => format!("texture {} bound to no texture", slot.index), - None => format!("texture {}", slot.index), - }) - .collect(); - let named = match bound.is_empty() { - true => String::new(), - false => format!(" ({})", bound.join(", ")), - }; - ( - stage_object(stage.stage).to_owned(), - format!("{} {under}{named}", self.note_reason(note)), - ) - }); - } - - /// Announce, at a draw or dispatch that binds a pipeline of `stages`, each specialized note - /// one of whose clauses tests only the formats bound at texture slots - /// (`SpecClause::tests_bound_formats`, `SpecKey::BoundTexelFormat`) and holds of the classes - /// of the formats `formats` binds there (`metal::format::bound_texel_format`), a command - /// whose formats are not known (`None`: an execution of commands the GPU writes) holding. A - /// slot bound to nothing reads zero and holds no NaN, so a clause testing it does not hold. - /// Such a clause is announced here alone: no pipeline's key tells it. A filter note's (a - /// two-plane YCbCr texture that Metal's own sampler filters) is announced as - /// `ycbcr-filter-not-exact`. A kind already announced costs one atomic load. Whether any - /// note named a format (`VariantObjects::degrade_bound_formats` keeps the formats under which - /// none did). - pub(crate) fn degrade_bound_formats( - &self, - stages: &[StageModule], - formats: Option>, - ) -> bool { - let mut named = false; - for stage in stages { - for s in &stage.specialized_notes { - // A filter note's clauses of the bound formats test a two-plane YCbCr format - // alone (`metal2vulkan::lower`'s filter of such a texture by Metal's own sampler): - // its own kind. - let filter = filter_note(s.note); - let kind = match filter { - true => Degradation::YCbCrFilterNotExact, - false => Degradation::from_precision_note(s.note), - }; - if !s.when.iter().any(|c| c.tests_bound_formats()) - || !self.shared().announced.pending(kind) - { - continue; - } - let class = |slot: SlotRef| { - formats - .and_then(|f| f(slot)) - .map(metal2vulkan::metal::format::bound_texel_format) - }; - // A slot bound to nothing holds no format, so no NaN: a clause testing one fails. - let unbound = |slot: SlotRef| formats.is_some_and(|f| f(slot).is_none()); - let held: Vec<_> = stage - .bound_format_clauses(s.note, &class) - .into_iter() - .filter(|c| { - !c.all.iter().any( - |t| matches!(t.key, SpecKey::BoundTexelFormat(slot) if unbound(slot)), - ) - }) - .collect(); - if held.is_empty() { - continue; - } - let slots = tested_slots(held.iter().copied()); - named = true; - self.degrade(kind, || { - let bound: Vec = slots - .iter() - .map(|&slot| match formats.and_then(|f| f(slot)) { - Some(format) => format!("texture {} bound as {format:?}", slot.index), - None => format!( - "texture {} of a format the GPU's commands bind", - slot.index - ), - }) - .collect(); - let bound = bound.join(", "); - let reason = self.note_reason(s.note); - let message = match s.note { - _ if filter => format!( - "a filtered sample of {bound} takes the device's filter of its \ - texels, not Metal's exact filter of the format: {reason}" - ), - PrecisionNote::DeviceNanEncoding => { - format!("{reason} where it binds a texture whose format may hold one ({bound})") - } - _ => format!("{reason} where it binds {bound}"), - }; - (stage_object(stage.stage).to_owned(), message) - }); - } - } - named - } - - /// Announce `cross-class-texture-neutral` at a draw or dispatch whose plan binds a slot's - /// declared neutral where a texture of another numeric class is bound - /// (`PlanDiagnostic::CrossClassNeutral` among `diagnostics`), naming the first such slot - /// and the format `formats` binds there. A kind already announced costs one atomic load. - pub(crate) fn degrade_cross_class( - &self, - diagnostics: &[PlanDiagnostic], - formats: BoundFormats<'_>, - ) { - let Some(first) = diagnostics.iter().find(|d| { - matches!( - d, - PlanDiagnostic::CrossClassNeutral { .. } - | PlanDiagnostic::CrossClassHeapNeutral { .. } - ) - }) else { - return; - }; - self.degrade(Degradation::CrossClassTextureNeutral, || match *first { - PlanDiagnostic::CrossClassHeapNeutral { stage, element, .. } => ( - format!( - "the {stage:?} function's argument-buffer texture (heap element {element})" - ), - "a texture whose numeric class is not the one the function declares, which the \ - function samples, gathers, writes or reads where its access has no exact answer \ - for it" - .to_owned(), - ), - PlanDiagnostic::CrossClassNeutral { slot, .. } => { - let bound = match formats(slot) { - Some(format) => format!("{format:?}"), - None => "a format the commands bind".to_owned(), - }; - ( - format!("the {:?} function's texture {}", slot.stage, slot.index), - format!( - "bound to a texture of {bound}, whose numeric class is not the declared \ - one, where the slot's accesses have no exact answer for it" - ), - ) - } - _ => (String::new(), String::new()), - }); - } - - /// Announce `astc-storage-neutral` at a draw or dispatch whose plan binds a storage slot's - /// neutral where an ASTC texture is bound (`PlanDiagnostic::AstcStorageNeutral` among - /// `diagnostics`), naming the first such slot and the format `formats` binds there. A kind - /// already announced costs one atomic load. - pub(crate) fn degrade_astc_storage( - &self, - diagnostics: &[PlanDiagnostic], - formats: BoundFormats<'_>, - ) { - let Some(slot) = diagnostics.iter().find_map(|d| match d { - PlanDiagnostic::AstcStorageNeutral { slot, .. } => Some(*slot), - _ => None, - }) else { - return; - }; - self.degrade(Degradation::AstcStorageNeutral, || { - let bound = match formats(slot) { - Some(format) => format!("{format:?}"), - None => "an ASTC format".to_owned(), - }; - ( - format!("the {:?} function's texture {}", slot.stage, slot.index), - format!("a storage slot bound to a texture of {bound}, whose blocks it cannot store into"), - ) - }); - } - - /// Announce `PrecisionNote::ArgumentPixelSamplerScaling` at a draw or dispatch of a variant - /// of `stages` whose commands list `samplers` (the device's live sampler states its sampler - /// table lists): where a stage records the note and a listed state has pixel coordinates, the - /// states whose access through an argument buffer may hand the device a scaled coordinate. A - /// listed state is any an argument buffer the commands read may name by its ID; which ones a - /// program's argument buffers hold, the CPU or the GPU writing them, the runtime does not - /// see. Nothing else - /// announces the note: a pipeline that records it but never runs while such a state lives - /// announces nothing. - pub(crate) fn degrade_argument_pixel_samplers( - &self, - stages: &[StageModule], - samplers: &[crate::SamplerState], - ) { - const NOTE: PrecisionNote = PrecisionNote::ArgumentPixelSamplerScaling; - let Some(stage) = self.argument_pixel_samplers_noted(stages) else { - return; - }; - let Some(state) = samplers.iter().find(|s| s.scales_in_an_argument_buffer()) else { - return; - }; - self.degrade(Degradation::ArgumentPixelSamplerScaling, || { - ( - stage_object(stage.stage).to_owned(), - format!( - "{}: it samples through an argument buffer's sampler while sampler state {} \ - of pixel coordinates lives, which a program's argument buffer may name", - self.note_reason(NOTE), - state.gpu_resource_id().0 - ), - ) - }); - } - - /// Announce `PrecisionNote::DevicePointSize` at `call`'s draw of a state of `stages` that - /// rasterizes points: where a stage records the note, the size it writes past the device's - /// largest point draws at that bound. `[[point_size]]` sizes points alone (Metal has no point - /// fill mode, and Vulkan reads `PointSize` only where it rasterizes points), so a draw of - /// lines or triangles of the same state is Metal's exactly and announces nothing. Nothing else - /// announces the note. - pub(crate) fn degrade_point_size(&self, call: &'static str, stages: &[StageModule]) { - const NOTE: PrecisionNote = PrecisionNote::DevicePointSize; - let Some(stage) = stages.iter().find(|s| s.precision_notes.contains(&NOTE)) else { - return; - }; - self.degrade(Degradation::DevicePointSize, || { - ( - stage_object(stage.stage).to_owned(), - format!( - "{}: {call} draws points of the size it writes", - self.note_reason(NOTE) - ), - ) - }); - } - - /// The stage of `stages` whose note [`degrade_argument_pixel_samplers`] may announce: one - /// that records `PrecisionNote::ArgumentPixelSamplerScaling`, where the device has not - /// announced it yet; `None` where it would announce nothing, whatever the states. - /// - /// [`degrade_argument_pixel_samplers`]: Self::degrade_argument_pixel_samplers - pub(crate) fn argument_pixel_samplers_noted<'a>( - &self, - stages: &'a [StageModule], - ) -> Option<&'a StageModule> { - const NOTE: PrecisionNote = PrecisionNote::ArgumentPixelSamplerScaling; - let stage = stages.iter().find(|s| s.precision_notes.contains(&NOTE))?; - self.shared() - .announced - .pending(Degradation::ArgumentPixelSamplerScaling) - .then_some(stage) - } - - /// Why `stage`, which records `note`, degrades: [`note_reason`](Self::note_reason)'s, and for - /// `PrecisionNote::FunctionStorageAssumed` the private memory a thread of the stage keeps and - /// the Function storage the device's profile holds, measured or the floor of a device not - /// measured, in bytes. - fn stage_note_reason(&self, note: PrecisionNote, stage: &StageModule) -> String { - let recorded = self.note_reason(note); - if note != PrecisionNote::FunctionStorageAssumed { - return recorded; - } - let held = self.compile_device().profile().function_storage(); - function_storage_reason(&recorded, stage.private_bytes, held) - } - - /// Why a stage that records `note` degrades: the note, and for - /// `PrecisionNote::FragmentSimdgroupGrouping` the device's grouping. - fn note_reason(&self, note: PrecisionNote) -> String { - let recorded = format!("its translation records `PrecisionNote::{note:?}`"); - if note == PrecisionNote::FragmentSimdgroupGrouping { - return format!( - "{recorded}: {}'s fragment subgroups are not Apple's simdgroups, so its simdgroup \ - lanes and operations group other pixels than an Apple GPU's, and a quad of a \ - function that discards holds every covered pixel where an Apple GPU may run some \ - as helpers", - self.name() - ); - } - recorded - } - - /// Announce what the pass `layout` (an ended encoder's, recorded) degrades: separate depth - /// and stencil textures, a depth/stencil resolve one aspect at a time, a resolve into a - /// scratch image, a device-rounded color resolve, and a `DontCare` store, which a pass - /// recorded `whole` may store as Metal's own. - pub(super) fn degrade_pass(&self, layout: &PassLayout, whole: Option) { - let depth_stencil = layout.depth_stencil.as_ref(); - if let Some((ds, separate)) = - depth_stencil.and_then(|ds| ds.separate.as_ref().map(|separate| (ds, separate))) - { - self.degrade(Degradation::SeparateDepthStencil, || { - match &separate.depth { - Some(depth) => ( - format!( - "a render pass of a {:?} depth texture and a {:?} stencil texture", - depth.texture.pixel_format(), - separate.stencil.texture.pixel_format() - ), - format!( - "a Vulkan subpass has one depth/stencil attachment, so the pass renders \ - into a {:?} scratch image", - ds.target.format - ), - ), - None => ( - format!( - "a render pass of a {:?} stencil texture alone at custom sample positions", - separate.stencil.texture.pixel_format() - ), - format!( - "Vulkan lets no image without a depth aspect take custom sample \ - positions, so the pass renders into a {:?} scratch image", - ds.target.format - ), - ), - } - }); - } - if let Some((ds, resolve)) = depth_stencil - .and_then(|ds| ds.resolve.as_ref().map(|resolve| (ds, resolve))) - .filter(|(_, resolve)| resolve.steps.iter().any(|step| step.one_aspect)) - { - self.degrade(Degradation::OneAspectResolve, || { - let reason = if resolve.split { - format!( - "its depth ({}) and its stencil ({}) resolve into different textures, \ - each a subpass resolves through a scratch image of its own", - resolve_mode(resolve.depth_mode), - resolve_mode(resolve.stencil_mode) - ) - } else { - format!( - "the device cannot resolve its depth ({}) and its stencil ({}) in one \ - subpass (`independentResolve`, `independentResolveNone`)", - resolve_mode(resolve.depth_mode), - resolve_mode(resolve.stencil_mode) - ) - }; - ( - format!( - "a render pass resolving its {:?} depth/stencil attachment", - ds.target.texture.pixel_format() - ), - reason, - ) - }); - } - let colors = layout.colors.iter().flatten(); - let into_scratch = colors - .clone() - .filter_map(|color| color.resolve.as_ref()) - .chain( - depth_stencil_steps(layout) - .filter(|step| !step.one_aspect) - .map(|step| &step.resolve), - ) - .chain( - depth_stencil - .and_then(|ds| ds.resolve.as_ref()) - .and_then(|resolve| resolve.drawn_into.as_ref()), - ) - .find_map(|resolve| resolve.copy_to.as_ref().map(|to| (to, &resolve.attachment))); - if let Some((texture, scratch)) = into_scratch { - self.degrade(Degradation::ResolveScratch, || { - let depth_stencil = !super::texture::image_aspects(scratch.format) - .contains(ImageAspectFlags::COLOR); - let reason = if texture.layers < scratch.layers && depth_stencil { - format!( - "a layered pass of {} layers resolves its depth and stencil from the \ - first alone, as Metal does", - scratch.layers - ) - } else if texture.layers < scratch.layers { - format!( - "a layered pass of {} layers resolves into {} slices of it, the layers that fit", - scratch.layers, texture.layers - ) - } else if super::resolve::is_volume(texture) && super::resolve::first_plane_only(self) { - "the device's resolve into a 2D view of a 3D image is written where the view \ - begins only at its first depth plane (RuntimeDriverDefect::VolumeResolveFirstPlane)" - .to_owned() - } else { - "its image cannot be an attachment: the texture's usage lacks `RenderTarget`" - .to_owned() - }; - ( - format!( - "a resolve into a {:?} texture", - texture.texture.pixel_format() - ), - reason, - ) - }); - } - let exact = colors - .clone() - .find(|color| color.resolve.as_ref().is_some_and(|r| r.shader.is_some())); - if let Some(color) = exact { - self.degrade(Degradation::ShaderResolve, || { - // An attachment whose image takes no input attachment usage is resolved from a - // copy of its samples (`color_resolve.rs`). - let copied = color.planes.is_none() - && matches!(render_target::takes_input(&color.target), Ok(false)); - ( - format!( - "a resolve of a {:?} color attachment of {} samples", - color.target.texture.pixel_format(), - color.target.samples - ), - format!( - "{}{}", - match color_resolve::shader_rules( - color.target.texture.pixel_format(), - color.target.format, - color.target.samples, - ) { - Some(_) => format!( - "no device's resolve averages the codes {:?} holds", - color.target.format - ), - // The twin resolve (`resolve.rs`), the only other. - None => "no device's resolve writes a resolve texture in another \ - format's encoding" - .to_owned(), - }, - match copied { - true => { - "; the attachment's image takes no input attachment usage, so its \ - samples are first copied into a scratch image that has it" - } - false => "", - } - ), - ) - }); - } - // An extended-range or a word resolve whose rule the codes cannot give - // (`color_resolve.rs`). - let near = |word: bool| { - colors.clone().find(move |color| { - color - .resolve - .as_ref() - .and_then(|r| r.shader) - .is_some_and(|rules| !rules.exact() && rules.held_word().is_some() == word) - }) - }; - if let Some(color) = near(true) { - self.degrade(Degradation::WordResolve, || { - ( - format!( - "a resolve of a {:?} color attachment of {} samples", - color.target.texture.pixel_format(), - color.target.samples - ), - "Metal averages its tile's values, finer than the words the attachment \ - holds, from a pass that drew them; the resolve averages the words' codes" - .to_owned(), - ) - }); - } - if let Some(color) = near(false) { - self.degrade(Degradation::ExtendedRangeResolve, || { - ( - format!( - "a resolve of a {:?} color attachment of {} samples", - color.target.texture.pixel_format(), - color.target.samples - ), - "Metal averages the samples' values, finer than the codes the attachment \ - holds; the resolve averages the codes" - .to_owned(), - ) - }); - } - let unmeasured = colors.clone().find(|color| { - color.resolve.is_some() && color.target.samples > color_resolve::METAL_SAMPLES - }); - if let Some(color) = unmeasured { - self.degrade(Degradation::UnmeasuredResolve, || { - ( - format!( - "a resolve of a {:?} color attachment of {} samples", - color.target.texture.pixel_format(), - color.target.samples - ), - format!( - "Apple's GPUs make no texture of more than {} samples", - color_resolve::METAL_SAMPLES - ), - ) - }); - } - // A depth the device has no mode for, drawn after the pass (`depth_stencil_resolve.rs`). - if let Some((ds, ResolveMode::Picked(pick))) = layout - .depth_stencil - .as_ref() - .and_then(|ds| ds.resolve.as_ref().map(|r| (ds, r.depth_mode))) - { - self.degrade(Degradation::ShaderResolve, || { - let mode = format!("{pick:?}").to_uppercase(); - ( - format!( - "a depth resolve of a {:?} attachment of {} samples by `{pick:?}`", - ds.target.texture.pixel_format(), - ds.target.samples - ), - format!( - "the device has no `{mode}` depth resolve mode (`supportedDepthResolveModes`)" - ), - ) - }); - } - // A stencil picked by depth, drawn after the pass (`depth_stencil_resolve.rs`). - if let Some((ds, ResolveMode::Picked(pick))) = layout - .depth_stencil - .as_ref() - .and_then(|ds| ds.resolve.as_ref().map(|r| (ds, r.stencil_mode))) - { - let what = || { - format!( - "a stencil resolve of a {:?} attachment of {} samples by \ - `DepthResolvedSample` after `{pick:?}`", - ds.target.texture.pixel_format(), - ds.target.samples - ) - }; - self.degrade(Degradation::ShaderResolve, || { - ( - what(), - "no Vulkan resolve mode takes the stencil of the sample the depth filter took" - .to_owned(), - ) - }); - if ds.target.samples > color_resolve::METAL_SAMPLES { - self.degrade(Degradation::UnmeasuredResolve, || { - ( - what(), - format!( - "Apple's GPUs make no texture of more than {} samples", - color_resolve::METAL_SAMPLES - ), - ) - }); - } - } - // A resolve the device makes where its average is not measured to be Metal's. - // Whatever the format: where the device's average is Metal's (MoltenVK's is Metal's own - // resolve), a format without a closed rule resolves as Metal's too. - let rounded = colors.clone().find(|color| { - color.resolve.as_ref().is_some_and(|r| r.shader.is_none()) - && !color_resolve::average_is_metals(self, color.target.samples) - }); - if let Some(color) = rounded { - self.degrade(Degradation::DeviceRoundedResolve, || { - ( - format!( - "a resolve of a {:?} color attachment of {} samples", - color.target.texture.pixel_format(), - color.target.samples - ), - format!( - "Vulkan's `AVERAGE` resolve of {:?} leaves the average's rounding, and \ - what a NaN or infinite sample makes of it, to the device", - color.target.format, - ), - ) - }); - } - // A resolve into the attachment's format's sRGB twin by the device's own sRGB decode and - // encode (`color_resolve.rs`), on every device: Metal's resolve takes its own tables. - let decoded = colors.clone().find(|color| { - color - .resolve - .as_ref() - .and_then(|r| r.shader) - .is_some_and(|rules| rules.decodes_on_device()) - }); - if let Some(color) = decoded { - self.degrade(Degradation::DeviceRoundedResolve, || { - ( - format!( - "a resolve of a {:?} color attachment of {} samples into its format's \ - sRGB twin", - color.target.texture.pixel_format(), - color.target.samples - ), - "the resolve decodes the samples and encodes their average by the device's \ - own sRGB conversions, where Metal's resolve takes its 12-bit tables" - .to_owned(), - ) - }); - } - // A separate texture stored `DontCare` keeps its texels (`depth_stencil_scratch.rs`), and - // a memoryless one keeps none in Metal either. - let dont_care = |store| { - matches!( - store, - StoreAction::DontCare | StoreAction::MultisampleResolve - ) - }; - // Whether the attachment `pick` names, loaded by `load` and stored by `store`, is stored - // as Metal's (`HandedToMetal`). - let handed = HandedToMetal::of(self, layout, whole); - let metals = |pick: &dyn Fn(&HandedDontCare) -> bool, load, store| { - handed - .as_ref() - .is_some_and(|handed| handed.stores(pick, load, store)) - }; - // An attachment cleared and resolved into another pixel format by a pass without a draw - // call renders into a backing of its own, which copies nothing back: its texture keeps - // its texels, as Metal's keeps them there (`render.rs`). So does one whose samples a - // resolve after the pass reads, rendered through the image its texture keeps, from which - // the pass copies nothing back either (`resolve::keep_samples`), and, under - // `DontCareColorPolicy::Kept`, a texture's own image stored `DontCare` through a backing - // its queue keeps (`kept_bytes.rs`). - let kept = |color: &ColorTarget| { - (color.clears_and_resolves_across_formats() - && color.stand_in.as_ref().is_some_and(|s| !s.copies())) - || (color.stand_in.as_ref()) - .is_some_and(|s| matches!(s.cause, Cause::KeptSamples | Cause::KeptTexels)) - }; - // A texture over a buffer rendered through an image the pass copies nothing back from - // where it does not store it (a shadow, `render/shadows.rs`; a stand-in, which copies - // back only what Metal stores) keeps the buffer's bytes, Metal's answer (`kept_bytes.rs`). - let keeps_bytes = |target: &Target, stand_in: Option<&StandIn>| { - let own = stand_in.map_or(target, |s| &s.own); - own.texture.buffer_texels().is_some() - && (stand_in.is_some_and(StandIn::copies) || own.texture.shadow().is_some()) - }; - let color = layout.colors.iter().enumerate().find_map(|(index, color)| { - color - .as_ref() - .filter(|color| !color.memoryless && dont_care(color.store) && !kept(color)) - .filter(|color| !keeps_bytes(&color.target, color.stand_in.as_ref())) - .filter(|color| !handed.as_ref().is_some_and(|h| h.color(index, color))) - .map(|color| { - ( - StoredAttachment::Color(index), - color.target.texture.pixel_format(), - color.store, - ) - }) - }); - let patterned = depth_stencil.filter(|ds| { - ds.separate.is_none() - && ds.depth.zip(ds.stencil).is_some_and(|(depth, stencil)| { - super::resolve::layout_patterned(depth.store, stencil.store) - }) - }); - // A pass's hidden depth and stencil are the runtime's own image, of no texture of the - // program's (`DepthStencilTarget::hidden`). - let aspect = depth_stencil - .filter(|ds| ds.separate.is_none() && !ds.hidden) - .filter(|ds| !keeps_bytes(&ds.target, ds.stand_in.as_ref())) - .and_then(|ds| { - let stored_stencil = patterned.is_some(); - let picks: [(&str, _, fn(&HandedDontCare) -> bool); 2] = [ - ("depth", ds.depth, |h| h.depth), - ("stencil", ds.stencil.filter(|_| !stored_stencil), |h| { - h.stencil - }), - ]; - picks.into_iter().find_map(|(name, aspect, pick)| { - aspect - .filter(|aspect| !aspect.memoryless && dont_care(aspect.store)) - .filter(|aspect| !metals(&pick, aspect.load, aspect.store)) - .map(|aspect| { - ( - StoredAttachment::Aspect(name), - ds.target.texture.pixel_format(), - aspect.store, - ) - }) - }) - }); - if let Some((which, format, store)) = color.or(aspect) { - let how = match render_target::DontCare::of(self) { - render_target::DontCare::Discarded => "which is Vulkan's `DONT_CARE`", - render_target::DontCare::Stored => { - "which the runtime stores (Vulkan's `STORE`), as the device's `DONT_CARE` \ - is not measured to keep one of Metal's answers" - } - }; - self.degrade(Degradation::DontCareStore, || { - let which = match which { - StoredAttachment::Color(index) => format!("color attachment {index}"), - StoredAttachment::Aspect(name) => format!("the {name} attachment"), - }; - ( - format!("{which} of a render pass, a {format:?} texture"), - format!("it is stored with `{store:?}`, {how}"), - ) - }); - } - if let Some(ds) = patterned { - self.degrade(Degradation::MixedDepthStencilResolve, || { - ( - format!( - "a render pass's {:?} depth/stencil attachment", - ds.target.texture.pixel_format() - ), - "its depth is stored and resolved (`StoreAndMultisampleResolve`) while its \ - stencil is resolved alone (`MultisampleResolve`), which Metal's validation \ - stops" - .to_string(), - ) - }); - } - } -} - -/// The attachment a `DontCare` store's notice names (`Device::degrade_pass`), named only where -/// the notice is made: a color attachment by index, or the depth or the stencil aspect. -#[derive(Clone, Copy)] -enum StoredAttachment { - Color(usize), - Aspect(&'static str), -} - -/// A pass recorded as one render pass instance in which the runtime recorded nothing a driver -/// restarts its Metal pass for (`Device::degrade_pass`, `DriverFact::DontCareStoreIsMetals`): -/// no execution of render commands, no barrier between draws, no tessellated draw, no views, -/// and the device's own sample positions. -#[derive(Clone, Copy)] -pub(super) struct WholePass<'a> { - /// The instance's shape. - pub(super) shape: &'a PassShape, - /// The pass draws (the render encoder's `drew`). - pub(super) drew: bool, -} - -/// What a pass recorded whole ([`WholePass`]) hands a driver that stores `DONT_CARE` as Metal's -/// own `DontCare` on the same GPU (`DriverFact::DontCareStoreIsMetals`): the attachments it -/// stores so, as Metal's (`Device::degrade_pass`; a texture over a buffer keeps its bytes there, -/// `kept_bytes.rs`). But an attachment the pass clears, draws nothing into, and resolves alone: -/// Metal leaves the clear in it where it compresses the texture and keeps its texels where it -/// does not, and the driver's image of the texture may be compressed otherwise. -pub(super) struct HandedToMetal { - /// The attachments the pass hands the driver as `DONT_CARE`. - handed: HandedDontCare, - /// The pass draws. - drew: bool, -} - -impl HandedToMetal { - /// What `layout`'s pass, recorded `whole`, hands `device`'s driver as Metal's; `None` for a - /// pass not recorded whole or a driver without the fact. - pub(super) fn of( - device: &Device, - layout: &PassLayout, - whole: Option, - ) -> Option { - let facts = &device.properties().driver_facts; - whole - .filter(|_| facts.contains(&DriverFact::DontCareStoreIsMetals)) - .map(|whole| HandedToMetal { - handed: render_target::handed_dont_care(device, layout, whole.shape), - drew: whole.drew, - }) - } - - /// Whether the attachment `pick` names, loaded by `load` and stored by `store`, is stored as - /// Metal's. - fn stores( - &self, - pick: &dyn Fn(&HandedDontCare) -> bool, - load: LoadAction, - store: StoreAction, - ) -> bool { - let resolved_clear = load == LoadAction::Clear && store == StoreAction::MultisampleResolve; - pick(&self.handed) && (self.drew || !resolved_clear) - } - - /// Whether color attachment `index`, `color`, is stored as Metal's. - pub(super) fn color(&self, index: usize, color: &ColorTarget) -> bool { - let pick = |h: &HandedDontCare| index < 32 && h.colors & 1 << index != 0; - self.stores(&pick, color.load, color.store) - } -} - -/// A depth or stencil resolve mode as a notice names it. -fn resolve_mode(mode: ResolveMode) -> String { - if mode == ResolveMode::None { - "not resolved".to_owned() - } else { - format!("by {mode:?}") - } -} - -/// The object a stage's notice names: the stage's function and its pipeline state's kind. -fn stage_object(stage: ShaderStage) -> &'static str { - if stage == ShaderStage::COMPUTE { - "the kernel of a compute pipeline state" - } else if stage == ShaderStage::VERTEX { - "the vertex function of a render pipeline state" - } else if stage == ShaderStage::FRAGMENT { - "the fragment function of a render pipeline state" - } else if stage == ShaderStage::TESSELLATION_CONTROL - || stage == ShaderStage::TESSELLATION_EVALUATION - { - "a tessellation stage of a render pipeline state" - } else if stage == ShaderStage::TASK_EXT { - "the object function of a mesh render pipeline state" - } else if stage == ShaderStage::MESH_EXT { - "the mesh function of a mesh render pipeline state" - } else { - "a stage of a pipeline state" - } -} - -/// What split an ended encoder's pass between its render pass instances, beside its -/// attachments' roles (`Device::degrade_instances`). -#[derive(Clone, Copy, Debug, Default)] -pub(super) struct SplitCauses { - /// Some of its draws test the stencil in the shader (`shadow_stencil.rs`). - pub(super) shadow: bool, - /// Some of its draws test the depth in the shader (`depth_stand_in.rs`). - pub(super) shader_tests: bool, - /// The tile dispatches it runs between its instances (`render/tile_dispatch.rs`). - pub(super) dispatches: usize, - /// The splits the program's memory barriers made (`fence.rs`), and its indirect render - /// commands' barriers (`render/executions.rs`). - pub(super) barriers: usize, - /// The splits between draws that reach the pass's tile threadgroup memory - /// (`render/tile_memory.rs`). - pub(super) tile_memory: usize, - /// The splits before a draw that reaches interlocked storage an earlier draw of its instance - /// wrote, on a driver whose such draws race under load - /// (`DriverFact::InterlockedDrawsRaceUnderLoad`, `render.rs`'s `InterlockedStorage`). - pub(super) interlocked_writes: usize, - /// The splits before a draw that reads a color attachment's texture after a memory barrier, - /// the pass's load actions included where the barrier came before its first draw - /// (`texture/attached_reads.rs`). - pub(super) attached_reads: usize, - /// Some of its instances render some of its layers. - pub(super) viewed: bool, -} - -impl Device { - /// Announce what the render pass instances of an ended encoder's pass degrade, `layout` its - /// layout with its attachments' stand-ins and `shapes` its instances' shapes in order: a split - /// (more than one instance, for the first of `causes` that holds), a memoryless attachment's - /// backing image, a fetched color render target's scratch image, and a depth/stencil render - /// target's made for custom sample positions (`render.rs`, `attachment_stand_in.rs`). A split - /// the interlock alone makes on a device that runs it no slower than whole is not announced, - /// nor the backing it gives a memoryless attachment. - pub(super) fn degrade_instances>( - &self, - layout: &PassLayout, - shapes: &[S], - causes: SplitCauses, - ) { - // An instance's shape, whether the caller holds the shapes or references to them. - fn of>(shape: &S) -> &PassShape { - shape.borrow() - } - let SplitCauses { - shadow, - shader_tests, - dispatches, - barriers, - tile_memory, - interlocked_writes, - attached_reads, - viewed, - } = causes; - let instances = shapes.len(); - let colors = layout.colors.iter().flatten().count(); - let pass = - || format!("a render pass of {colors} color attachments in {instances} instances"); - // The first color attachment whose role changes between two instances: left out of the - // draws' subpass (the interlock), or read as an input attachment. - let changed = shapes.windows(2).find_map(|pair| { - let pair = [of(&pair[0]), of(&pair[1])]; - let role = |shape: &PassShape, index: &u32| { - ( - shape.storage.contains(index), - shape.no_inputs.contains(index), - ) - }; - let indices = pair - .into_iter() - .flat_map(|shape| shape.storage.iter().chain(&shape.no_inputs)); - indices.copied().find_map(|index| { - let (before, after) = (role(pair[0], &index), role(pair[1], &index)); - (before != after).then_some((index, before.0 != after.0)) - }) - }); - // The pass's hidden depth and stencil, arriving after its first instance. - let hidden = shapes.windows(2).any(|pair| { - of(&pair[0]).depth_stencil.is_none() && of(&pair[1]).depth_stencil.is_some() - }); - // On a device whose driver ran a pass the interlock splits no slower split than whole - // (`DriverFact::InterlockedPassSplitNoSlower`), a split the interlock alone makes (each - // instance's shape differs from the one before in the colors its subpass leaves out - // alone, and no other cause holds) is the device's faster form: announced neither as a - // split nor by the memoryless backing it gives an attachment. - let split_form = self - .properties() - .driver_facts - .contains(&DriverFact::InterlockedPassSplitNoSlower); - let storage_alone = |pair: &[S]| { - let (a, b) = (of(&pair[0]), of(&pair[1])); - a.storage != b.storage - && PassShape { - storage: b.storage.clone(), - ..a.clone() - } == *b - }; - let chosen = split_form - && instances > 1 - && shapes.windows(2).all(storage_alone) - && !shadow - && !shader_tests - && dispatches == 0 - && barriers == 0 - && tile_memory == 0 - && interlocked_writes == 0 - && attached_reads == 0; - if instances > 1 && !chosen { - let color = changed.and_then(|(index, interlock)| { - let color = layout.colors.get(index as usize)?.as_ref()?; - Some(( - index, - interlock, - color.stand_in.as_ref().map_or(&color.target, |s| &s.own), - )) - }); - self.degrade(Degradation::RenderPassSplit, || { - let reason = match color { - Some((index, true, target)) => format!( - "some of its draws read color attachment {index} ({}) through the pixel \ - interlock, which keeps it out of their subpass, and other draws, or its \ - resolve, need it in theirs, so it runs as {instances} Vulkan render \ - pass instances", - described(target) - ), - Some((index, false, target)) => format!( - "a draw reads color attachment {index} ({}) as an input attachment \ - after others drew it, and its image takes no input attachment usage: \ - a stand-in that has it makes it an input attachment of the later \ - draws' subpass alone, so it runs as {instances} Vulkan render pass \ - instances", - described(target) - ), - None if hidden => format!( - "a draw after others uses depth or the stencil it has no attachment for, \ - which Metal tests against a hidden depth and stencil: they are an \ - attachment of the draws' subpass from that draw on, so it runs as \ - {instances} Vulkan render pass instances" - ), - None if shadow => format!( - "some of its draws test the stencil in the fragment shader, each run of \ - them between the stencil's copies to and from its shadow, so it runs \ - as {instances} Vulkan render pass instances" - ), - None if shader_tests => format!( - "some of its draws test the depth in the fragment shader, each run of \ - them between the depth's copies to and from its stand-in, so it runs as \ - {instances} Vulkan render pass instances" - ), - None if dispatches > 0 => format!( - "it runs {dispatches} tile dispatches, each outside a render pass \ - instance after the one before it, so it runs as {instances} Vulkan \ - render pass instances" - ), - None if barriers > 0 => format!( - "memory barriers between its draws end {barriers} of its Vulkan \ - render pass instances (whose own barriers order framebuffer-space \ - stages alone), so it runs as {instances} Vulkan render pass instances" - ), - None if tile_memory > 0 => format!( - "draws that read and write its tile threadgroup memory see each other's \ - writes in order, which Vulkan gives one draw of another's storage writes \ - across render pass instances alone, ending {tile_memory} of them, so it \ - runs as {instances} Vulkan render pass instances" - ), - None if interlocked_writes > 0 => format!( - "draws that read and write a color through the pixel interlock after an \ - earlier draw of their Vulkan render pass instance wrote it, whose order \ - the driver does not keep under load, each run in an instance after the \ - one that wrote it, ending {interlocked_writes} of them, so it runs as \ - {instances} Vulkan render pass instances" - ), - None if attached_reads > 0 => format!( - "draws that read a color attachment's texture after a memory barrier read \ - what its load actions and the draws before the barrier stored, in a \ - Vulkan render pass instance after theirs, ending {attached_reads} of \ - them, so it runs as {instances} Vulkan render pass instances" - ), - None if viewed => format!( - "some of its draws render some of its layers (vertex amplification as \ - Vulkan multiview, or a view mapping that moves a draw to one layer), \ - each run of them in a render pass instance over those layers, so it \ - runs as {instances} Vulkan render pass instances" - ), - None => format!( - "its draws keep different attachments out of their subpass, so it runs \ - as {instances} Vulkan render pass instances" - ), - }; - (pass(), reason) - }); - } - let fetched = |index: usize| { - shapes - .iter() - .any(|shape| of(shape).storage.iter().any(|&i| i as usize == index)) - }; - let colors = layout - .colors - .iter() - .enumerate() - .filter_map(|(index, color)| { - let color = color.as_ref()?; - let stand_in = color.stand_in.as_ref()?; - Some((Some(index), &color.target, stand_in, color.memoryless)) - }); - // Whether the attachment is memoryless: a backing of one that is not is the kept backing, - // whose pass keeps the texture's texels as Metal's and announces nothing, never - // `memoryless-backed`'s "a memoryless texture". - let depth_stencil = layout.depth_stencil.iter().filter_map(|ds| { - let memoryless = [ds.depth, ds.stencil] - .iter() - .flatten() - .any(|aspect| aspect.memoryless); - Some((None, &ds.target, ds.stand_in.as_ref()?, memoryless)) - }); - for (index, target, stand_in, memoryless) in colors.chain(depth_stencil) { - let own = &stand_in.own; - // What the pass renders into, in words: made only where a notice is announced. - let image = || match target.texture.placed_bytes() { - Some(bytes) => format!("a scratch image of {bytes} bytes"), - None => "a scratch image".to_owned(), - }; - let planes = index - .and_then(|index| layout.colors.get(index)?.as_ref()) - .is_some_and(|color| color.planes.is_some()); - // A depth/stencil stand-in that copies is the one made for custom sample positions: - // for an image not made for them, or for one that was on a driver that keeps the - // depth per sample only through a copy. - // By the stand-in's cause: a fetched texture's scratch alone is - // `fetch-through-scratch`, naming the draw that fetched it; a texture without render - // target usage is `undeclared-usage-shadow`; a bound linear attachment's kept image - // was announced by `linear_attachment.rs`. Before, every stand-in that copies was - // announced as a fetch's, a linear texture rendered through copies among them (read - // "through the pixel interlock" where no draw read it). - if stand_in.cause == Cause::Positions { - self.degrade(Degradation::PositionsThroughScratch, || { - let image = image(); - let made = own.texture.image_plan().is_ok_and(|plan| { - plan.flags.contains( - metal2vulkan::vk::ImageCreateFlags::SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_EXT, - ) - }); - let why = match own.texture.callers_image() { - true => " (the caller made it without it)", - false => "", - }; - let reason = match made { - true => format!( - "{} renders at custom sample positions, and this device's driver \ - answers a later read of a depth rendered there with the depth at the \ - standard positions, and a later pass at other positions with the \ - depth at its own (`DriverFact::PositionedDepthReadAtStandardPositions`), \ - keeping each sample's depth only through a copy, so the pass renders \ - into {image}", - pass() - ), - false => format!( - "{} renders at custom sample positions, at which Vulkan rasterizes a \ - depth/stencil attachment only where its image was made with \ - `VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT`, and \ - this one's was not{why}, so the pass renders into {image}", - pass() - ), - }; - ( - format!("a {} depth/stencil render target", described(own)), - reason, - ) - }); - } else if stand_in.cause == Cause::Unattachable { - self.degrade(Degradation::UndeclaredUsageShadow, || { - let image = image(); - let attachment = match index { - Some(index) => format!("color attachment {index}"), - None => "depth/stencil attachment".to_owned(), - }; - ( - format!("a {} texture", described(own)), - format!( - "{} renders it as its {attachment}, which its usage does not declare \ - (no `RenderTarget`), so the pass renders into {image}", - pass() - ), - ) - }); - } else if let Cause::Fetch { by } = &stand_in.cause { - self.degrade(Degradation::FetchThroughScratch, || { - let image = image(); - let (form, missing) = if layout.fetch_inputs { - ("as an input attachment", "input attachment") - } else if planes { - ( - "through the pixel interlock as sample planes", - "sampled usage with a view of its texel size's unsigned-integer \ - format, which the copies to and from the planes take,", - ) - } else { - ("through the pixel interlock", "`STORAGE`") - }; - // The runtime's own placed images take input attachment usage wherever the - // fetch reads input attachments (`image_plan.rs`). - let why = if own.texture.callers_image() { - "the caller made it without that usage" - } else if own.texture.placed_bytes().is_none() { - "a texture over a buffer's bytes is a linear image without it" - } else { - "the device lays its image out otherwise with it" - }; - ( - format!("a {} render target", described(own)), - format!( - "{by} in {} reads it {form}, and its image has no {missing} usage \ - ({why}), so the pass renders into {image}", - pass() - ), - ) - }); - } else if matches!( - stand_in.cause, - Cause::Linear | Cause::KeptBytes | Cause::KeptSamples | Cause::KeptTexels - ) { - // Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image. - // An image that keeps an attachment's samples for a resolve after the pass makes - // the pass Metal's, which no notice names (`resolve::keep_samples`), as does a - // backing that keeps a texture's texels (`kept_bytes.rs`). - } else if memoryless - && (index.is_some_and(fetched) || (index.is_none() && shadow) || !chosen) - { - // Not for a split the device chose (`chosen`). - self.degrade(Degradation::MemorylessBacked, || { - let image = image(); - let why = if index.is_some_and(fetched) { - "a framebuffer fetch through the pixel interlock reads it".to_owned() - } else if index.is_none() && shadow { - "a draw tests its stencil in the fragment shader, which copies it to and \ - from a shadow" - .to_owned() - } else { - format!("its render pass splits into {instances} instances") - }; - ( - format!("a memoryless {} texture", described(own)), - format!("{why}, so it renders into {image}"), - ) - }); - } - } - } -} - -impl Device { - /// Announce the shader-side stencil of an ended encoder's pass, `layout` its layout with its - /// attachments' stand-ins, when some of its draws test the stencil in the fragment shader - /// (`shadow`, `shadow_stencil.rs`). - pub(super) fn degrade_shadow_stencil(&self, layout: &PassLayout, shadow: bool) { - let Some(ds) = layout.depth_stencil.as_ref().filter(|_| shadow) else { - return; - }; - self.degrade(Degradation::ShaderSideStencil, || { - let own = ds.stand_in.as_ref().map_or(&ds.target, |s| &s.own); - ( - format!("a {} stencil attachment", described(own)), - "a draw's fragment function returns `[[stencil]]` on a device without \ - `VK_EXT_shader_stencil_export`, so it tests and writes a shadow of the stencil \ - itself" - .to_owned(), - ) - }); - } - - /// Announce the depth stand-in of an ended encoder's pass whose draws test the depth in the - /// shader (`tests`, `depth_stand_in.rs`), once. - pub(super) fn degrade_shader_tests(&self, layout: &PassLayout, tests: bool) { - let Some(ds) = layout.depth_stencil.as_ref().filter(|_| tests) else { - return; - }; - self.degrade(Degradation::ShaderSideDepthTest, || { - let own = ds.stand_in.as_ref().map_or(&ds.target, |s| &s.own); - ( - format!("a {} depth attachment", described(own)), - "a draw's fragment function stores a color through the pixel interlock before \ - the depth and stencil tests, which may drop the fragment, so it runs them \ - itself against stand-ins of the depth and, where the draw's stencil test acts, \ - of the stencil" - .to_owned(), - ) - }); - } - - /// Announce a tile dispatch's scratch images (`render/tile_dispatch.rs`): it stages `staged`, - /// the pass's attachment `own` among them, through scratch images over `area`. - pub(super) fn degrade_tile_scratch(&self, own: &Target, staged: usize, area: [u32; 2]) { - self.degrade(Degradation::TileDispatchScratch, || { - let [width, height] = area; - ( - format!("a tile dispatch's {} color attachment", described(own)), - format!( - "its tile function stages {staged} attachment(s) through storage views in \ - their staging formats, of scratch images over the {width}x{height} pixels \ - the dispatch covers, which each attachment is copied into and back from" - ), - ) - }); - } - - /// Announce the fragment imageblock storage of an ended encoder's pass - /// (`fragment_imageblock.rs`). - pub(super) fn degrade_fragment_imageblock(&self, imageblock: &PassImageblock) { - self.degrade(Degradation::FragmentImageblockStorage, || { - let (words, [width, height], bytes) = imageblock.described(); - let image = match bytes { - Some(bytes) => format!("an R32Uint array image of {words} layers, {bytes} bytes"), - None => format!("an R32Uint array image of {words} layers"), - }; - ( - format!("a {width}x{height} render pass's fragment imageblock"), - format!( - "its draws' fragment functions or its tile functions declare an explicit \ - imageblock of {words} words a pixel, which Metal keeps in tile memory, so \ - they read and write it in {image}" - ), - ) - }); - } - - /// Announce the sample planes of an ended encoder's pass, `layout` its layout with its - /// attachments' stand-ins and planes (`sample_planes.rs`). - pub(super) fn degrade_planes(&self, layout: &PassLayout) { - let planes = layout.colors.iter().enumerate().find_map(|(index, color)| { - let color = color.as_ref()?; - Some((index, color, color.planes.as_ref()?)) - }); - if let Some((index, color, planes)) = planes { - self.degrade(Degradation::SamplePlanes, || { - let own = color.stand_in.as_ref().map_or(&color.target, |s| &s.own); - let image = match planes.texture.placed_bytes() { - Some(bytes) => { - format!("an array image of {} layers, {bytes} bytes", planes.layers) - } - None => format!("an array image of {} layers", planes.layers), - }; - ( - format!("a multisampled {} render target", described(own)), - format!( - "a render pass reads color attachment {index} through the pixel \ - interlock on a device without multisampled storage images, so its \ - draws read and write its samples in {image}, one sample per layer" - ), - ) - }); - } - } -} - -/// `target`'s pixel format, extent and samples, for a notice. -fn described(target: &Target) -> String { - let [width, height] = target.extent; - format!( - "{:?} {width}x{height} of {} sample(s)", - target.texture.pixel_format(), - target.samples - ) -} diff --git a/crates/metal2vulkan-runtime/src/depth_clamp.rs b/crates/metal2vulkan-runtime/src/depth_clamp.rs deleted file mode 100644 index 9e5a9c6fd..000000000 --- a/crates/metal2vulkan-runtime/src/depth_clamp.rs +++ /dev/null @@ -1,437 +0,0 @@ -//! 32-bit float depths clamped into `[0, 1]` before a copy takes them into a depth image, on a -//! device without `VK_EXT_depth_range_unrestricted` enabled (`ImageFacts::depth_clamps`: ANV on -//! the Iris Xe, MoltenVK on the M3 Max, which does not expose it). -//! -//! - **Why.** Vulkan takes no value outside `[0, 1]` into a depth image by a copy there -//! (`VUID-vkCmdCopyBufferToImage-pRegions-07931`), whatever a driver is measured to keep (ANV -//! stores one clamped, MoltenVK keeps it; no copy relies on either). Metal's -//! `Depth32Float` texel keeps any `float`. The clamp is `bind::clamped_depth` on a depth's bits: -//! a NaN of either sign 1.0, `-0.0` as it is, another negative value 0, a value above 1.0 1.0, -//! no denormal flushed. Announced `restricted-depth-upload` by the upload. -//! - **Where.** Every copy of a depth from a buffer or the host into a depth plane of a -//! `D32_SFLOAT` or `D32_SFLOAT_S8_UINT` image ([`clamps_depth`]): `replace_region`'s packed -//! bytes on the CPU, whichever way they go on (a host copy, the staging queue, a submission; -//! `texture.rs`), so no depth image holds a value outside `[0, 1]` that a later copy of its -//! texels moves on; a blit's copy from a buffer into the texture, through a scratch buffer of -//! the encoder that takes the copy's bytes, or through the staging buffer its plan copies its -//! rows into; and a copy between textures whose texels go through the encoder's scratch buffer -//! into a depth (a colour texture of its unit, `blit_texture.rs`). A multisampled texture's -//! fill clamps each sample's depth on the CPU before its bits are written (`blit_fill.rs`). A -//! heap's tiled texels clamp as they move into their image (`texture/heap_tiled.rs`). Not on another device: each value -//! is copied as Metal holds it. -//! - **How**, on the GPU ([`BlitCommandEncoder::clamp_depths`]): one dispatch of -//! `bind::depth_clamp_module` per region (or per piece of one that its binding cannot hold -//! whole), each its own command over the bytes it rewrites in place, which the encoder's -//! tracker orders after the copy that wrote them and before the copy that reads them on. -//! - **Counted.** `WorkCounts::depth_uploads_clamped`: one a `replace_region`'s clamp, one a -//! blit copy's clamp of the depths it copies into an image, and one a multisampled fill's. - -use super::blit::{reads, writes, writes_by, BlitCommandEncoder}; -use super::buffer::Buffer; -use super::error::{internal, Error}; -use super::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet}; -use super::tracker::Access; -use super::values::ResourceOptions; -use super::Device; -use ash::vk; -use metal2vulkan::bind::{clamped_depth, DepthClampModule}; -use metal2vulkan::vk::{Format, ImageAspectFlags}; -use std::ops::Range; - -/// Whether a copy into `aspect` of an image of `format` on `device` clamps its 32-bit float -/// depths (the module docs): the depth of a `D32_SFLOAT` or `D32_SFLOAT_S8_UINT` image, on a -/// device without `VK_EXT_depth_range_unrestricted`. -pub(super) fn clamps_depth(device: &Device, format: Format, aspect: ImageAspectFlags) -> bool { - let profile = device.compile_device().profile(); - aspect == ImageAspectFlags::DEPTH - && matches!(format, Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT) - && device.shared().textures.facts(profile).depth_clamps() -} - -/// Clamp each 32-bit float depth of `bytes`, packed 4 bytes a depth, in place (the CPU's clamp, -/// `bind::clamped_depth`). -pub(super) fn clamp_depth_bytes(bytes: &mut [u8]) { - for word in bytes.as_chunks_mut::<4>().0 { - *word = clamped_depth(u32::from_le_bytes(*word)).to_le_bytes(); - } -} - -/// The depths a copy `region` from a buffer into a depth image reads: the depths a row, its rows -/// and images, and the rows and images apart in words. -#[derive(Clone, Copy)] -struct Depths { - width: u32, - rows: u32, - images: u32, - row_words: u32, - image_words: u32, -} - -impl Depths { - /// `region`'s depths; `None` for a region of none. - fn of(region: &vk::BufferImageCopy) -> Result, Error> { - let extent = region.image_extent; - let images = extent - .depth - .checked_mul(region.image_subresource.layer_count) - .ok_or_else(|| internal("a depth copy's images past u32"))?; - if extent.width == 0 || extent.height == 0 || images == 0 { - return Ok(None); - } - let row_words = match region.buffer_row_length { - 0 => extent.width, - length => length, - }; - let image_rows = match region.buffer_image_height { - 0 => extent.height, - height => height, - }; - let image_words = row_words - .checked_mul(image_rows) - .ok_or_else(|| internal("a depth copy's images apart past u32"))?; - Ok(Some(Depths { - width: extent.width, - rows: extent.height, - images, - row_words, - image_words, - })) - } - - /// The bytes from the first depth to past the last of `images` images of `rows` rows. - fn reach(&self, images: u32, rows: u32) -> u64 { - let images = u64::from(images - 1) * u64::from(self.image_words); - let rows = u64::from(rows - 1) * u64::from(self.row_words); - 4 * (images + rows + u64::from(self.width)) - } -} - -/// One dispatch of the kernel: its binding's buffer, offset and range, its shape and workgroups, -/// and the bytes it rewrites, of the scratch buffer's own. -struct Dispatch { - binding: (vk::Buffer, u64, u64), - shape: [u8; 16], - groups: [u32; 3], - bytes: Range, -} - -/// The device's bounds on a dispatch: the binding's offset alignment, its range, and the -/// workgroups along each axis. -struct Bounds { - align: u64, - most: u64, - groups: [u32; 3], -} - -impl Bounds { - fn of(device: &Device) -> Bounds { - let limits = &device.properties().description.limits; - Bounds { - align: limits.min_storage_buffer_offset_alignment.max(4), - most: u64::from(limits.max_storage_buffer_range), - groups: limits.max_compute_work_group_count, - } - } - - /// The dispatch over `images` images of `rows` rows of `depths` from byte `start` of `raw` - /// (the scratch buffer's `VkBuffer`, which starts at its byte `base`); `None` where its - /// binding or workgroups pass the device's bounds. - fn dispatch( - &self, - (raw, base): (vk::Buffer, u64), - start: u64, - depths: &Depths, - [rows, images]: [u32; 2], - ) -> Option { - let reach = depths.reach(images, rows); - let offset = start - start % self.align; - let range = start - offset + reach; - let groups = DepthClampModule::groups(depths.width, rows, images); - if range > self.most || groups.iter().zip(self.groups).any(|(g, m)| *g > m) { - return None; - } - let first = u32::try_from((start - offset) / 4).ok()?; - let shape = - DepthClampModule::shape(first, depths.width, depths.row_words, depths.image_words); - let at = start.checked_sub(base)?; - Some(Dispatch { - binding: (raw, offset, range), - shape, - groups, - bytes: at..at + reach, - }) - } - - /// The dispatches over `depths` from byte `start` of `raw`: all its images at once, else an - /// image at a time, else rows of an image at a time, as many as the device binds. - fn dispatches( - &self, - raw: (vk::Buffer, u64), - start: u64, - depths: &Depths, - into: &mut Vec, - ) -> Result<(), Error> { - let past = || internal("a depth copy's row past the device's storage buffer range"); - if let Some(whole) = self.dispatch(raw, start, depths, [depths.rows, depths.images]) { - into.push(whole); - return Ok(()); - } - let image_bytes = 4 * u64::from(depths.image_words); - let row_bytes = 4 * u64::from(depths.row_words); - for image in 0..u64::from(depths.images) { - let at = start + image * image_bytes; - if let Some(one) = self.dispatch(raw, at, depths, [depths.rows, 1]) { - into.push(one); - continue; - } - // Rows of the image, as many as one binding holds (a row at least). - let slack = self.align - 4; - let fit = (self - .most - .saturating_sub(slack + 4 * u64::from(depths.width)) - / row_bytes) - .saturating_add(1) - .min(u64::from(self.groups[1])); - let fit = u32::try_from(fit.max(1)).map_err(|_| past())?; - let mut row = 0; - while row < depths.rows { - let rows = fit.min(depths.rows - row); - let at = at + u64::from(row) * row_bytes; - into.push(self.dispatch(raw, at, depths, [rows, 1]).ok_or_else(past)?); - row += rows; - } - } - Ok(()) - } -} - -impl BlitCommandEncoder { - /// The copies `regions` from `buffer`'s `VkBuffer` `raw` (the regions' offsets in it), of the - /// buffer's bytes `span`, into a depth image, with their depths clamped (the module docs): - /// each region's bytes copied into a scratch buffer of the encoder at an offset the device - /// binds, and clamped there. The scratch buffer, its `VkBuffer`, and the regions of the copy - /// from it into the image; the caller records that copy and retains the scratch buffer. - pub(super) fn clamped_depth_copies( - &mut self, - (buffer, raw, span): (&Buffer, vk::Buffer, Range), - regions: &[vk::BufferImageCopy], - ) -> Result<(Buffer, vk::Buffer, Vec), Error> { - let device = self.core().device().clone(); - let align = Bounds::of(&device).align; - // Each region's bytes, from its first depth to past its last, at its place in the scratch. - let mut placed = Vec::with_capacity(regions.len()); - let mut length = 0u64; - for region in regions { - let reach = match Depths::of(region)? { - Some(depths) => depths.reach(depths.images, depths.rows), - None => 0, - }; - let at = length.next_multiple_of(align); - placed.push((at, reach)); - length = at + reach; - } - let scratch = device.own_buffer(length.max(4), ResourceOptions::private())?; - let (through, base) = scratch.at(0); - let moves: Vec = (regions.iter().zip(&placed)) - .filter(|(_, (_, reach))| *reach > 0) - .map(|(region, &(at, reach))| vk::BufferCopy { - src_offset: region.buffer_offset, - dst_offset: base + at, - size: reach, - }) - .collect(); - let uses = [reads(buffer, span), writes(&scratch, 0..length.max(4))]; - self.command(&uses, |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording outside a render pass; both - // buffers are live and retained until it completes, each move lies in both (the - // regions' bytes, which the plan checked, and the scratch's places), and the scratch - // is another buffer whose places do not overlap. - unsafe { device.cmd_copy_buffer(command_buffer, raw, through, &moves) }; - })?; - let staged: Vec = (regions.iter().zip(&placed)) - .map(|(region, &(at, _))| vk::BufferImageCopy { - buffer_offset: base + at, - ..*region - }) - .collect(); - self.clamp_depths(&scratch, &staged)?; - Ok((scratch, through, staged)) - } - - /// Clamp the depths of `regions`, copies from `scratch` (their offsets in its `VkBuffer`) into - /// a depth image, in place (the module docs), before the copy: one command a dispatch. - pub(super) fn clamp_depths( - &mut self, - scratch: &Buffer, - regions: &[vk::BufferImageCopy], - ) -> Result<(), Error> { - let device = self.core().device().clone(); - let bounds = Bounds::of(&device); - let raw = scratch.at(0); - let mut dispatches = Vec::new(); - for region in regions { - if let Some(depths) = Depths::of(region)? { - bounds.dispatches(raw, region.buffer_offset, &depths, &mut dispatches)?; - } - } - if dispatches.is_empty() { - return Ok(()); - } - let kernel = device.owned_kernel(OwnedModule::DepthClamp)?; - let sets: Vec = (dispatches.iter()) - .map(|dispatch| OwnedSet { - images: Vec::new(), - storage_images: Vec::new(), - buffers: vec![dispatch.binding], - }) - .collect(); - let binds = OwnedBinds::new(&device, &kernel, &sets)?; - let stage = vk::PipelineStageFlags2::COMPUTE_SHADER; - for (index, dispatch) in dispatches.iter().enumerate() { - let mut words = writes_by( - scratch, - dispatch.bytes.clone(), - Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_WRITE), - ); - words.read = Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_READ); - let (binds, kernel) = (&binds, &kernel); - self.command_in(stage, &[words], |functions, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // kernel is the device's, the bound words are the scratch's, live and retained - // until it completes, and the shape and its workgroups stay inside the binding - // (`Bounds::dispatch`). - unsafe { - functions.cmd_bind_pipeline( - raw, - vk::PipelineBindPoint::COMPUTE, - kernel.pipeline, - ); - binds.bind(functions, raw, kernel, index); - functions.cmd_push_constants( - raw, - kernel.layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &dispatch.shape, - ); - let [x, y, z] = dispatch.groups; - functions.cmd_dispatch(raw, x, y, z); - } - })?; - } - if let OwnedBinds::Sets(sets) = binds { - self.core().retain(sets); - } - device.shared().counts.depth_upload_clamped(); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::{clamp_depth_bytes, Bounds, Depths, Dispatch}; - use ash::vk; - use metal2vulkan::bind::clamped_depth; - use std::collections::BTreeSet; - - /// The bytes of the depths `dispatch` clamps, by its binding and shape: each a 4-byte word's - /// first byte in the `VkBuffer`. - fn clamped_words(dispatch: &Dispatch) -> Vec { - let word = |i: usize| { - let bytes = &dispatch.shape[4 * i..4 * i + 4]; - u64::from(u32::from_le_bytes(bytes.try_into().unwrap())) - }; - let (first, width, row_words, image_words) = (word(0), word(1), word(2), word(3)); - let (_, offset, range) = dispatch.binding; - let [_, rows, images] = dispatch.groups.map(u64::from); - let mut words = Vec::new(); - for z in 0..images { - for y in 0..rows { - for x in 0..width { - let at = offset + 4 * (first + z * image_words + y * row_words + x); - assert!(at + 4 <= offset + range, "a word past the binding"); - words.push(at); - } - } - } - words - } - - /// The pieces of a region of 3 images of 5 rows of 37 depths, rows 40 words apart and images - /// 230, from byte 1028 of the buffer, under bounds that bind it whole, an image at a time, and - /// rows at a time: every depth of the region clamped once, no other word, each binding at the - /// alignment and within the range: 1, 3, 9 (two rows a piece) and 15 pieces. - #[test] - fn pieces_clamp_each_depth_of_a_region_once() { - let region = vk::BufferImageCopy { - buffer_offset: 1028, - buffer_row_length: 40, - buffer_image_height: 0, - image_subresource: vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::DEPTH, - mip_level: 0, - base_array_layer: 0, - layer_count: 3, - }, - image_offset: vk::Offset3D::default(), - image_extent: vk::Extent3D { - width: 37, - height: 5, - depth: 1, - }, - }; - let depths = Depths::of(®ion).unwrap().unwrap(); - let want: Vec = (0..3u64) - .flat_map(|z| (0..5u64).flat_map(move |y| (0..37u64).map(move |x| (z, y, x)))) - .map(|(z, y, x)| 1028 + 4 * (z * 200 + y * 40 + x)) - .collect(); - for (most, pieces) in [(1 << 20, 1), (1024, 3), (400, 9), (330, 15)] { - let bounds = Bounds { - align: 64, - most, - groups: [65535; 3], - }; - let mut dispatches = Vec::new(); - let raw = (vk::Buffer::null(), 1024); - bounds - .dispatches(raw, region.buffer_offset, &depths, &mut dispatches) - .unwrap(); - assert_eq!(dispatches.len(), pieces, "pieces under a range of {most}"); - let mut got: Vec = dispatches.iter().flat_map(clamped_words).collect(); - let unique: BTreeSet = got.iter().copied().collect(); - assert_eq!( - unique.len(), - got.len(), - "a depth clamped twice under {most}" - ); - got.sort_unstable(); - assert_eq!(got, want, "the depths clamped under {most}"); - for dispatch in &dispatches { - let (_, offset, range) = dispatch.binding; - assert_eq!(offset % 64, 0, "a binding off the alignment"); - assert!(range <= most, "a binding past the range"); - let words = clamped_words(dispatch); - let (low, high) = (words[0] - 1024, words[words.len() - 1] + 4 - 1024); - assert_eq!(dispatch.bytes, low..high, "the bytes its use names"); - } - } - } - - /// The CPU's clamp of packed depths: each word as `bind::clamped_depth` gives it. - #[test] - fn packed_depths_clamp_word_by_word() { - let words = [ - 1.5f32.to_bits(), - 0x7fc0_0000, - 0.25f32.to_bits(), - 0xbf80_0000, - ]; - let mut bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - clamp_depth_bytes(&mut bytes); - let got: Vec = (bytes.as_chunks::<4>().0.iter()) - .map(|w| u32::from_le_bytes(*w)) - .collect(); - assert_eq!(got, words.map(clamped_depth)); - assert_eq!(got, [0x3f80_0000, 0x3f80_0000, 0.25f32.to_bits(), 0]); - } -} diff --git a/crates/metal2vulkan-runtime/src/depth_copy.rs b/crates/metal2vulkan-runtime/src/depth_copy.rs deleted file mode 100644 index 8bb16faa7..000000000 --- a/crates/metal2vulkan-runtime/src/depth_copy.rs +++ /dev/null @@ -1,931 +0,0 @@ -//! A multisampled depth copied without colour copies: where maintenance8's depth-stencil/colour -//! `vkCmdCopyImage` is missing or runs wrong -//! (`RuntimeDriverDefect::MultisampledDepthStencilColourCopies`), the separate textures' depth -//! moves between its texture and the scratch image (`depth_stencil_scratch.rs`) by a draw. -//! -//! - **The draw** ([`DepthDraw`]): a render pass of the destination alone, its depth and stencil -//! loaded and stored, of one sample-rate draw of `bind::depth_stencil_copy_modules`' -//! [`DepthStencilCopy::Depth`], which reads each sample of the source's depth aspect through a -//! sampled view and writes it as the sample's `FragDepth`, under depth compare `ALWAYS` with -//! depth writes on and the stencil test off. -//! - **Where it is exact** ([`copies_exactly`]): a 32-bit float depth, on a driver whose fragment -//! depth stores every depth value unchanged: each value in `[0, 1]` it is given, and, for the -//! rest, the value it stored when given it again. -//! `runtime_lane::separate_samples::fragment_depth_stores_depth_values_unchanged` probes that -//! with signed zero, denormals, 1, values outside `[0, 1]`, infinities and NaN payloads, and the -//! driver fact [`DriverFact::FragmentDepthStoresUnchanged`] lists each driver where it held, -//! from the release measured (`device/driver_facts.rs`). And a 16-bit unsigned normalized depth, -//! on a driver whose fragment depth stores each code's fetched `float` as that code -//! (`fragment_depth_keeps_every_16_bit_code` probes every code; the fact -//! [`DriverFact::FragmentDepthKeepsDepth16Codes`]). Elsewhere a 32-bit float depth has no exact -//! form on a device whose copies go by draws (Vulkan writes a multisampled depth image's -//! samples by no other means there), so the draw runs as an announced near-equivalent -//! (`drawn-depth-copy`, [`drawn`]): a blit copy into such a depth, and the separate textures' -//! depth copies. Its reason names the values the driver is measured to change -//! ([`fragment_depth_changes`]: MoltenVK, NVIDIA's), or, on a driver whose fragment depth is not -//! measured (another driver, or a release of lavapipe not measured), those Vulkan leaves to the -//! driver ([`UNMEASURED_FLOAT_DEPTH`]). A 16-bit depth is drawn only where its codes are -//! measured kept; elsewhere its consumer refuses, typed. -//! -//! - **The bits draws** ([`DepthDraw::bits`]): the other way, a depth or stencil aspect's samples -//! into a multisampled unsigned colour image of their bits (`R32_UINT`, `R16_UINT`, `R8_UINT`), -//! for the multisampled blit copies between depth/stencil and colour textures -//! (`sample_copy.rs`). A render pass of the colour image alone, of one sample-rate draw of -//! [`DepthStencilCopy::DepthBits`], [`DepthStencilCopy::Depth16Bits`] or -//! [`DepthStencilCopy::StencilBits`], which fetches each sample through a sampled view of the -//! aspect and writes its bits (a 32-bit float depth's `f32` bit-cast, a 16-bit normalized -//! depth's code, a stencil's value) as the sample's colour. Exact wherever the fetch returns -//! the texel: the same fetch reads the samples back in every lane and in the -//! `FragmentDepthStoresUnchanged` and `FragmentDepthKeepsDepth16Codes` probes above. The draw -//! back reads its depth from such a colour image ([`DepthDraw::from_colour`], -//! [`depth_carrier`]): a 32-bit float depth's floats from an `R32_SFLOAT` one, a 16-bit -//! normalized depth's codes from the `R16_UINT` one. -//! -//! A 16-bit depth crosses as its **codes** and never as floats, which is what makes both -//! halves exact by construction rather than by a measured tolerance: the draw back's -//! `code / 65535` is bit for bit the depth the `FragmentDepthKeepsDepth16Codes` probe stores, -//! and the bits draw's `round(depth * 65535)` recovers every one of the 65536 codes -//! (`bind::depth_stencil_copy`'s module docs carry the margin and the exhaustive check). -//! -//! - **The depth stand-in's copies** (`depth_stand_in.rs`): a pass's depth samples into an -//! `R32_SFLOAT` stand-in, multisampled or sample planes, by a dispatch of -//! `bind::depth_split_module` ([`DepthSplit`]), and back by the `FragDepth` draw of -//! [`DepthStencilCopy::DepthFromStandIn`] ([`DepthDraw::from_stand_in`]), which reads the -//! stand-in as a storage image; exact or announced as the draw above is. -//! -//! The draws read and write a render area anywhere in their attachment -//! (`stencil_copy::DrawArea`). The shaders of each draw and each draw, format and sample count's -//! render pass and pipeline are made once per device, at first use, and destroyed with the -//! device; a copy's descriptor set and framebuffer are its own, held by its command buffer until -//! it completes. - -use super::binding_view::VkView; -use super::degradation::Degradation; -use super::device::{device_error, lock}; -use super::error::{internal, Error}; -use super::release; -use super::render_pass::Target; -use super::sample_planes::{pipeline_layout, set_layout, shader_module}; -use super::stencil_copy::{aspect_view, draw_framebuffer, record_draws_in, DrawArea, PassObjects}; -use super::texture::image_aspects; -use super::Device; -use crate::shader_cache::driver::Making; -use ash::vk; -use metal2vulkan::bind::{ - depth_split_module, depth_stencil_copy_modules, DepthSplitModule, DepthStandInForm, - DepthStencilCopy, DepthStencilCopyModules, -}; -use metal2vulkan::cache::Hash256; -use metal2vulkan::device::DriverFact; -use metal2vulkan::error::Feature; -use metal2vulkan::vk::{ - ComponentMapping, DriverId, Format, ImageAspectFlags, ImageUsageFlags, ImageViewType, -}; -use std::collections::BTreeSet; -use std::sync::Arc; - -/// Whether `format`'s depth is a 32-bit float's, the one depth the `FragDepth` draw writes. -pub(super) fn float_depth(format: Format) -> bool { - matches!(format, Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT) -} - -/// Whether `format`'s depth is a 16-bit unsigned normalized one's. -pub(super) fn unorm16_depth(format: Format) -> bool { - matches!(format, Format::D16_UNORM | Format::D16_UNORM_S8_UINT) -} - -/// The colour format a multisampled colour image carries `format`'s depth in, between the bits -/// draw that reads the aspect and the draw that writes it back (the module docs): a 32-bit float -/// depth's own floats in `R32_SFLOAT`, and a 16-bit unsigned normalized depth's **codes** in -/// `R16_UINT`, which is what makes that pair exact by construction -/// (`bind::DepthStencilCopy::Depth16Code`). `None` for a depth no draw writes. -pub(super) fn depth_carrier(format: Format) -> Option { - if float_depth(format) { - return Some(Format::R32_SFLOAT); - } - unorm16_depth(format).then_some(Format::R16_UINT) -} - -/// Whether the draw copies a depth aspect of `format` exactly on `device` (the module docs): a -/// 32-bit float depth, where the device's driver has -/// [`DriverFact::FragmentDepthStoresUnchanged`], and a 16-bit unsigned normalized one, where it -/// has [`DriverFact::FragmentDepthKeepsDepth16Codes`]. -pub(super) fn copies_exactly(device: &Device, format: Format) -> bool { - copies_exactly_by(&device.properties().driver_facts, format) -} - -/// [`copies_exactly`] on a driver with `facts`. -fn copies_exactly_by(facts: &BTreeSet, format: Format) -> bool { - (float_depth(format) && facts.contains(&DriverFact::FragmentDepthStoresUnchanged)) - || (unorm16_depth(format) && facts.contains(&DriverFact::FragmentDepthKeepsDepth16Codes)) -} - -/// What the draw does to a depth aspect it writes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Drawn { - /// Every value stored unchanged ([`copies_exactly`]). - Exact, - /// The values the draw may change, named: those the driver's fragment depth is measured to - /// change ([`fragment_depth_changes`]), or those Vulkan leaves to a driver not measured. - /// Metal's copy keeps them, so the copy is the announced near-equivalent `drawn-depth-copy`. - Changes(&'static str), -} - -/// What the draw does to a depth aspect of `format` on `device` ([`Drawn`]): exact where -/// [`copies_exactly`]; a 32-bit float depth on a driver measured to change some values changes -/// them, and on any other driver may change the values Vulkan leaves to it. `None` for any other -/// depth (a 16-bit one whose codes are not measured kept), where the copy is refused. -pub(super) fn drawn(device: &Device, format: Format) -> Option { - let description = &device.properties().description; - drawn_by( - &device.properties().driver_facts, - description.driver_id, - format, - ) -} - -/// [`drawn`] on a driver of `driver` with `facts`. -pub(super) fn drawn_by( - facts: &BTreeSet, - driver: Option, - format: Format, -) -> Option { - if copies_exactly_by(facts, format) { - return Some(Drawn::Exact); - } - float_depth(format) - .then(|| Drawn::Changes(fragment_depth_changes(driver).unwrap_or(UNMEASURED_FLOAT_DEPTH))) -} - -/// What the `FragDepth` draw may change of a 32-bit float depth on a driver whose fragment depth -/// is not measured: what Vulkan leaves to the driver. A fragment depth outside the depth range -/// `[0, 1]` is undefined (the fragment operations chapter: "If zf is not in the range -/// [zmin, zmax], then zf is undefined"), a denormal may be flushed to zero, and the probe found -/// -0 stored as +0 on a driver (MoltenVK); every other value is stored as the shader wrote it. -pub(super) const UNMEASURED_FLOAT_DEPTH: &str = "its driver's fragment depth is not measured: \ - Vulkan leaves undefined a value outside [0, 1] (past 1, below 0, an infinity or a NaN), \ - which it may store clamped, as a value of its own or not at all, and it may flush a \ - denormal to zero or store -0 as +0; every other value lands as Metal's copy leaves it"; - -/// What the `FragDepth` draw changes on drivers measured to store some depth values otherwise -/// (`runtime_lane::separate_samples::fragment_depth_stores_depth_values_unchanged`, signed zero, -/// denormals, 1, values outside `[0, 1]`, infinities and NaN payloads, each stored once and -/// again; `DriverFact::FragmentDepthStoresUnchanged`'s record): the driver, and the values it -/// changes. Where the multisampled copies go by draws, a copy into a 32-bit float depth runs -/// on these as the announced `drawn-depth-copy`, naming them; on a driver neither here nor exact -/// it runs announced too, naming what Vulkan leaves to the driver ([`UNMEASURED_FLOAT_DEPTH`]). -const FRAGMENT_DEPTH_CHANGES: &[(DriverId, &str)] = &[ - // MoltenVK 1.4.1 on an M3 Max and an M4 (the NaNs by our probe on an M4, which drew them - // over a depth of 0.25: changed). - ( - DriverId::MOLTENVK, - "its driver's fragment depth changes values: a value with the sign bit set (-0, a \ - negative value, -inf, a negative NaN) is stored as +0, a value past 1 and +inf as 1, \ - and a positive NaN writes nothing, the sample keeping the depth it held", - ), - // NVIDIA's 615.71.09 on the RTX 3090, with `VK_EXT_depth_range_unrestricted`: values outside - // `[0, 1]` are kept. - ( - DriverId::NVIDIA_PROPRIETARY, - "its driver's fragment depth changes values: denormals are flushed to zero of their \ - sign, and NaN is stored as -inf", - ), -]; - -/// The values the `FragDepth` draw changes on a driver of `driver`, where they are measured -/// ([`FRAGMENT_DEPTH_CHANGES`]); `None` where they are not. -fn fragment_depth_changes(driver: Option) -> Option<&'static str> { - let driver = driver?; - FRAGMENT_DEPTH_CHANGES - .iter() - .find(|(of, _)| *of == driver) - .map(|(_, changes)| *changes) -} - -/// Announce `drawn-depth-copy` once for `what`, a copy whose `FragDepth` draw may change the -/// values `changes` names ([`Drawn::Changes`]): the one notice of every copy the draw makes -/// inexactly, a blit copy into a multisampled depth and a pass's separate depth texture's copies -/// to and from its scratch image. -pub(super) fn announce_changes( - device: &Device, - changes: &'static str, - what: impl FnOnce() -> String, -) { - device.degrade(Degradation::DrawnDepthCopy, || { - ( - what(), - format!( - "the device copies a multisampled depth by a fragment-depth draw, and {changes}" - ), - ) - }); -} - -/// A draw's shaders, the device's. -#[derive(Clone, Copy, Debug)] -struct DepthShaders { - vertex: vk::ShaderModule, - fragment: vk::ShaderModule, - set_layout: vk::DescriptorSetLayout, - layout: vk::PipelineLayout, - /// The digest of its modules' SPIR-V words, which its pipelines' records are named by - /// (`shader_cache/driver.rs`). - words: Hash256, -} - -/// A draw's render pass and pipeline for one destination format and sample count. -#[derive(Clone, Copy, Debug)] -struct DepthPipeline { - render_pass: vk::RenderPass, - pipeline: vk::Pipeline, -} - -/// The depth copies' objects one device has made (the module docs): each draw's shaders, and -/// its pipelines for each destination format and sample count. -#[derive(Default)] -pub(super) struct DepthCopyObjects { - shaders: Vec<(DepthStencilCopy, DepthShaders)>, - pipelines: Vec<((DepthStencilCopy, Format, u32), DepthPipeline)>, - /// The depth split of each stand-in form. - splits: Vec<(DepthStandInForm, SplitKernel)>, -} - -/// The depth split's kernel for one stand-in form, the device's. -#[derive(Clone, Copy, Debug)] -struct SplitKernel { - module: vk::ShaderModule, - set_layout: vk::DescriptorSetLayout, - layout: vk::PipelineLayout, - pipeline: vk::Pipeline, -} - -/// The descriptor types of the depth split's set, in binding order. -const SPLIT_SET: [vk::DescriptorType; 2] = [ - vk::DescriptorType::SAMPLED_IMAGE, - vk::DescriptorType::STORAGE_IMAGE, -]; - -/// The descriptor type of the source of the draw `copy`: the stand-in a -/// [`DepthStencilCopy::DepthFromStandIn`] reads is a storage image, every other source sampled. -fn draw_source(copy: DepthStencilCopy) -> vk::DescriptorType { - match copy { - DepthStencilCopy::DepthFromStandIn { .. } => vk::DescriptorType::STORAGE_IMAGE, - _ => vk::DescriptorType::SAMPLED_IMAGE, - } -} - -impl DepthCopyObjects { - /// Destroy every object; the device is idle, and is destroyed next. - pub(super) fn destroy(&self, raw: &ash::Device) { - // SAFETY: the device is idle, so no pending command uses the objects; destroying a null - // handle is a no-op. - unsafe { - for (_, made) in &self.pipelines { - release::object(raw, made.pipeline); - release::object(raw, made.render_pass); - } - for (_, shaders) in &self.shaders { - release::object(raw, shaders.layout); - release::object(raw, shaders.set_layout); - release::object(raw, shaders.fragment); - release::object(raw, shaders.vertex); - } - for (_, kernel) in &self.splits { - release::object(raw, kernel.pipeline); - release::object(raw, kernel.layout); - release::object(raw, kernel.set_layout); - release::object(raw, kernel.module); - } - } - } -} - -impl Device { - /// The shaders of `copy` (the `FragDepth` draw or a bits draw) and its pipeline for a - /// destination of `format` at `samples`, made on first use; refused naming `feature` where - /// the device lacks what they need. - fn depth_draw( - &self, - copy: DepthStencilCopy, - format: Format, - samples: u32, - feature: &Feature, - ) -> Result<(DepthShaders, DepthPipeline), Error> { - self.depth_draw_by(copy, (format, samples), feature, true) - } - - /// The depth stand-in's copies of `form` for a depth target of `format` at `samples`: the - /// draw back from the stand-in and the depth split, made by a render pipeline state's - /// creation (`depth_stand_in::make_copies`) so that its first tested draw makes neither. - /// Each refusal is left to that draw, which meets it again. - pub(super) fn make_stand_in_copies( - &self, - form: DepthStandInForm, - (format, samples): (Format, u32), - feature: &Feature, - ) { - let back = DepthStencilCopy::DepthFromStandIn { form }; - let _ = self.depth_draw_by(back, (format, samples), feature, false); - let _ = self.depth_split(form, feature, false); - } - - /// [`depth_draw`](Self::depth_draw), counting a stand-in's copy back made by a draw's - /// encoding where `at_draw`, else by a state's creation (`WorkCounts::stand_in_copies_made`). - fn depth_draw_by( - &self, - copy: DepthStencilCopy, - (format, samples): (Format, u32), - feature: &Feature, - at_draw: bool, - ) -> Result<(DepthShaders, DepthPipeline), Error> { - // A making's turn before the lock (`budget::helper_turn`): none where it is made. - let _turn = crate::pipeline::budget::helper_turn(&self.shared().depth_copies, |objects| { - objects - .pipelines - .iter() - .any(|(key, _)| *key == (copy, format, samples)) - }); - let mut objects = lock(&self.shared().depth_copies); - let shared = self.shared(); - let raw = shared.vk(); - let made_shaders = objects - .shaders - .iter() - .find(|(of, _)| *of == copy) - .map(|(_, shaders)| *shaders); - let shaders = match made_shaders { - Some(shaders) => shaders, - None => { - let modules = - depth_stencil_copy_modules(self.compile_device(), copy, feature.clone()) - .map_err(device_error)?; - if DepthStencilCopyModules::SET != 0 || DepthStencilCopyModules::SOURCE_BINDING != 0 - { - return Err(internal("the depth copy's binding out of its set layout")); - } - let mut shaders = DepthShaders { - vertex: vk::ShaderModule::null(), - fragment: vk::ShaderModule::null(), - set_layout: vk::DescriptorSetLayout::null(), - layout: vk::PipelineLayout::null(), - words: Making::new("depth copy modules") - .words(&modules.vertex) - .words(&modules.fragment) - .finish(), - }; - let made = (|| { - shaders.vertex = shader_module(raw, &modules.vertex)?; - shaders.fragment = shader_module(raw, &modules.fragment)?; - shaders.set_layout = - set_layout(raw, &[draw_source(copy)], vk::ShaderStageFlags::FRAGMENT)?; - shaders.layout = pipeline_layout(raw, shaders.set_layout)?; - Ok(()) - })(); - if let Err(error) = made { - // SAFETY: nothing used the objects; destroying a null handle is a no-op. - unsafe { - release::object(raw, shaders.layout); - release::object(raw, shaders.set_layout); - release::object(raw, shaders.fragment); - release::object(raw, shaders.vertex); - } - return Err(error); - } - objects.shaders.push((copy, shaders)); - shaders - } - }; - if let Some((_, made)) = objects - .pipelines - .iter() - .find(|(key, _)| *key == (copy, format, samples)) - { - return Ok((shaders, *made)); - } - let mut made = DepthPipeline { - render_pass: vk::RenderPass::null(), - pipeline: vk::Pipeline::null(), - }; - // Which draws write a colour attachment rather than a depth one. Stated as a match over - // every variant, not a `matches!` that falls through to false: a new bits draw left out - // of a fallthrough list builds a depth render pass over its colour image, which is how - // `Depth16Bits` first shipped broken. - let colour = - match copy { - DepthStencilCopy::DepthBits - | DepthStencilCopy::StencilBits - | DepthStencilCopy::Depth16Bits => true, - DepthStencilCopy::Depth - | DepthStencilCopy::Depth16Code - | DepthStencilCopy::StencilPlane { .. } - | DepthStencilCopy::StencilExport { .. } - | DepthStencilCopy::DepthFromStandIn { .. } => false, - // `DepthStencilCopy` is `#[non_exhaustive]`, so a variant added in the translator - // crate reaches here. A bits draw must say so above; defaulting to a depth pass is - // the failure this match exists to stop, so refuse rather than guess. - _ => return Err(internal( - "a depth/stencil copy draw whose attachment kind this runtime does not state", - )), - }; - let result = (|| { - made.render_pass = match colour { - true => bits_pass(raw, format, samples)?, - false => depth_pass(raw, format, samples)?, - }; - let making = Making::new("depth copy") - .digest(&shaders.words) - .text(&(copy, format, samples)); - made.pipeline = - depth_pipeline(self, &shaders, made.render_pass, samples, (colour, making))?; - Ok(()) - })(); - match result { - Ok(()) => { - objects.pipelines.push(((copy, format, samples), made)); - if let DepthStencilCopy::DepthFromStandIn { .. } = copy { - shared.counts.stand_in_copy_made(at_draw); - } - Ok((shaders, made)) - } - Err(error) => { - // SAFETY: nothing used the objects; destroying a null handle is a no-op. - unsafe { - release::object(raw, made.pipeline); - release::object(raw, made.render_pass); - } - Err(error) - } - } - } - - /// The depth split into a stand-in of `form`, made on first use, by a draw's encoding where - /// `at_draw` (`WorkCounts::stand_in_copies_made`); refused naming `feature` where the device - /// lacks what it needs. - fn depth_split( - &self, - form: DepthStandInForm, - feature: &Feature, - at_draw: bool, - ) -> Result { - let _turn = crate::pipeline::budget::helper_turn(&self.shared().depth_copies, |objects| { - objects.splits.iter().any(|(of, _)| *of == form) - }); - let mut objects = lock(&self.shared().depth_copies); - if let Some((_, kernel)) = objects.splits.iter().find(|(of, _)| *of == form) { - return Ok(*kernel); - } - let module = depth_split_module(self.compile_device(), form, feature.clone()) - .map_err(device_error)?; - if DepthSplitModule::SOURCE_BINDING != 0 || DepthSplitModule::DESTINATION_BINDING != 1 { - return Err(internal( - "the depth split's bindings out of their set layout's order", - )); - } - let shared = self.shared(); - let raw = shared.vk(); - let mut kernel = SplitKernel { - module: vk::ShaderModule::null(), - set_layout: vk::DescriptorSetLayout::null(), - layout: vk::PipelineLayout::null(), - pipeline: vk::Pipeline::null(), - }; - let made = (|| { - kernel.module = shader_module(raw, &module.spirv)?; - kernel.set_layout = set_layout(raw, &SPLIT_SET, vk::ShaderStageFlags::COMPUTE)?; - kernel.layout = pipeline_layout(raw, kernel.set_layout)?; - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(kernel.module) - .name(c"main"); - let info = vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(kernel.layout); - kernel.pipeline = shared.make_compute_pipeline( - Making::new("depth split").words(&module.spirv), - || "metal2vulkan: depth split".to_owned(), - info, - )?; - Ok(()) - })(); - match made { - Ok(()) => { - objects.splits.push((form, kernel)); - shared.counts.stand_in_copy_made(at_draw); - Ok(kernel) - } - Err(error) => { - // SAFETY: nothing used the objects; destroying a null handle is a no-op. - unsafe { - release::object(raw, kernel.pipeline); - release::object(raw, kernel.layout); - release::object(raw, kernel.set_layout); - release::object(raw, kernel.module); - } - Err(error) - } - } - } -} - -/// The storage view of a depth stand-in `stand_in` of `form`: 2D, or 2D-array of its planes (its -/// `layers` from its `layer`). -pub(super) fn stand_in_view( - stand_in: &Target, - form: DepthStandInForm, -) -> Result { - let (view_type, layers) = match form { - DepthStandInForm::Multisampled => (ImageViewType::TYPE_2D, 1), - DepthStandInForm::SamplePlanes => (ImageViewType::TYPE_2D_ARRAY, stand_in.layers), - }; - stand_in.texture.image_view(&VkView { - view_type, - format: Format::R32_SFLOAT, - components: ComponentMapping::IDENTITY, - aspect: ImageAspectFlags::COLOR, - base_level: stand_in.level, - level_count: 1, - base_layer: stand_in.layer, - layer_count: layers, - usage: ImageUsageFlags::STORAGE, - }) -} - -/// One copy of a depth aspect's samples into a depth stand-in by the depth split (the module -/// docs). -#[derive(Clone)] -pub(super) struct DepthSplit { - /// The descriptor set's pool, held until the command buffer completes (dropping the last - /// handle frees it). - _objects: Arc, - kernel: SplitKernel, - set: vk::DescriptorSet, - /// The workgroups the dispatch runs. - groups: [u32; 3], -} - -impl DepthSplit { - /// The split of `source`'s depth aspect, sampled, into `stand_in` of `form` over the area - /// `area` from the origin. Refused naming `feature` where the device lacks what the kernel - /// needs. - pub(super) fn new( - device: &Device, - source: &Target, - stand_in: &Target, - form: DepthStandInForm, - area: [u32; 2], - feature: &Feature, - ) -> Result { - if !image_aspects(source.format).contains(ImageAspectFlags::DEPTH) - || stand_in.format != Format::R32_SFLOAT - { - return Err(internal("a depth split from no depth or into no stand-in")); - } - let kernel = device.depth_split(form, feature, true)?; - let source_view = aspect_view(source, ImageAspectFlags::DEPTH)?; - let destination = stand_in_view(stand_in, form)?; - let (objects, set) = PassObjects::with_set( - device, - kernel.set_layout, - &[ - (vk::DescriptorType::SAMPLED_IMAGE, source_view), - (vk::DescriptorType::STORAGE_IMAGE, destination), - ], - )?; - let size = DepthSplitModule::LOCAL_SIZE; - let [width, height] = area; - Ok(DepthSplit { - _objects: Arc::new(objects), - kernel, - set, - groups: [width.div_ceil(size), height.div_ceil(size), source.samples], - }) - } - - /// Record, outside a render pass, the dispatch. - /// - /// # Safety - /// - /// `raw` is the device's command buffer, recording outside a render pass, which only the - /// caller records; the source, the stand-in and this split's objects are live until it - /// completes and rest in `GENERAL`. - pub(super) unsafe fn record(&self, device: &ash::Device, raw: vk::CommandBuffer) { - let compute = vk::PipelineBindPoint::COMPUTE; - device.cmd_bind_pipeline(raw, compute, self.kernel.pipeline); - device.cmd_bind_descriptor_sets(raw, compute, self.kernel.layout, 0, &[self.set], &[]); - let [x, y, z] = self.groups; - device.cmd_dispatch(raw, x, y, z); - } -} - -/// The draw's render pass for a destination of `format` at `samples`: the destination alone, -/// `GENERAL` throughout, its depth and stencil loaded and stored. -pub(super) fn depth_pass( - raw: &ash::Device, - format: Format, - samples: u32, -) -> Result { - let general = vk::ImageLayout::GENERAL; - let attachments = [vk::AttachmentDescription::default() - .format(format.into()) - .samples(vk::SampleCountFlags::from_raw(samples)) - .load_op(vk::AttachmentLoadOp::LOAD) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::LOAD) - .stencil_store_op(vk::AttachmentStoreOp::STORE) - .initial_layout(general) - .final_layout(general)]; - let depth_stencil = vk::AttachmentReference::default() - .attachment(0) - .layout(general); - let subpasses = [vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .depth_stencil_attachment(&depth_stencil)]; - let info = vk::RenderPassCreateInfo::default() - .attachments(&attachments) - .subpasses(&subpasses); - // SAFETY: `info` and its arrays are live for the call. - unsafe { crate::creation::render_pass(raw, &info) } -} - -/// A bits draw's render pass for a colour image of `format` at `samples`: the image alone, -/// `GENERAL` throughout, not loaded (the draw writes every sample of the render area) and stored. -fn bits_pass(raw: &ash::Device, format: Format, samples: u32) -> Result { - let general = vk::ImageLayout::GENERAL; - let attachments = [vk::AttachmentDescription::default() - .format(format.into()) - .samples(vk::SampleCountFlags::from_raw(samples)) - .load_op(vk::AttachmentLoadOp::DONT_CARE) - .store_op(vk::AttachmentStoreOp::STORE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(general) - .final_layout(general)]; - let colour = [vk::AttachmentReference::default() - .attachment(0) - .layout(general)]; - let subpasses = [vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colour)]; - let info = vk::RenderPassCreateInfo::default() - .attachments(&attachments) - .subpasses(&subpasses); - // SAFETY: `info` and its arrays are live for the call. - unsafe { crate::creation::render_pass(raw, &info) } -} - -/// The draw in `render_pass` at `samples`: the triangle over the viewport at sample rate, the -/// depth written under compare `ALWAYS` with the stencil test off, or, for a bits draw -/// (`colour`), the colour written whole, unblended, with no depth/stencil attachment. -/// Its record is the one `making` names. -fn depth_pipeline( - device: &Device, - shaders: &DepthShaders, - render_pass: vk::RenderPass, - samples: u32, - (colour, making): (bool, Making), -) -> Result { - let shared = device.shared(); - let stages = [ - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(shaders.vertex) - .name(c"main"), - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::FRAGMENT) - .module(shaders.fragment) - .name(c"main"), - ]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); - let rasterization = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(vk::PolygonMode::FILL) - .cull_mode(vk::CullModeFlags::NONE) - .front_face(vk::FrontFace::COUNTER_CLOCKWISE) - .line_width(1.0); - let mask = [u32::MAX]; - let multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::from_raw(samples)) - .sample_shading_enable(true) - .min_sample_shading(1.0) - .sample_mask(&mask); - let depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default() - .depth_test_enable(true) - .depth_write_enable(true) - .depth_compare_op(vk::CompareOp::ALWAYS) - .stencil_test_enable(false); - let written = [vk::PipelineColorBlendAttachmentState::default() - .blend_enable(false) - .color_write_mask(vk::ColorComponentFlags::RGBA)]; - let blend = match colour { - true => vk::PipelineColorBlendStateCreateInfo::default().attachments(&written), - false => vk::PipelineColorBlendStateCreateInfo::default(), - }; - let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; - let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); - let info = vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&input_assembly) - .viewport_state(&viewport) - .rasterization_state(&rasterization) - .multisample_state(&multisample) - .color_blend_state(&blend) - .dynamic_state(&dynamic) - .layout(shaders.layout) - .render_pass(render_pass) - .subpass(0); - let info = match colour { - true => info, - false => info.depth_stencil_state(&depth_stencil), - }; - shared.make_graphics_pipeline(making, || "metal2vulkan: depth copy".to_owned(), info) -} - -/// Make, where they are not yet made, the draw's objects for a destination of `format` at -/// `samples`: refused naming `feature` where the device lacks what the draw needs. -pub(super) fn depth_draw_runs( - device: &Device, - format: Format, - samples: u32, - feature: &Feature, -) -> Result<(), Error> { - device - .depth_draw(DepthStencilCopy::Depth, format, samples, feature) - .map(|_| ()) -} - -/// One copy of a depth aspect into a depth/stencil target's by the draw, or of a depth or -/// stencil aspect into a colour target by a bits draw (the module docs). -#[derive(Clone)] -pub(super) struct DepthDraw { - objects: Arc, - shaders: DepthShaders, - made: DepthPipeline, - set: vk::DescriptorSet, - /// The render area. - area: DrawArea, -} - -impl DepthDraw { - /// The draw that writes `source`'s depth aspect, sampled, into `destination`'s over the - /// render area `area`, which both cover. Refused naming `feature` where the device lacks - /// what the draw needs. - pub(super) fn new( - device: &Device, - source: &Target, - destination: &Target, - area: [u32; 2], - feature: &Feature, - ) -> Result { - let depth = - |target: &Target| image_aspects(target.format).contains(ImageAspectFlags::DEPTH); - if source.samples != destination.samples || !depth(source) || !depth(destination) { - return Err(internal( - "a depth copy between targets of other samples or without depth", - )); - } - let view = aspect_view(source, ImageAspectFlags::DEPTH)?; - let area = DrawArea::whole(area); - DepthDraw::of_view( - device, - DepthStencilCopy::Depth, - view, - destination, - area, - feature, - ) - } - - /// The draw that writes the depths the stand-in `stand_in` of `form` holds at each pixel and - /// sample of the area `area` from the origin into `destination`'s depth there. - pub(super) fn from_stand_in( - device: &Device, - stand_in: &Target, - form: DepthStandInForm, - destination: &Target, - area: [u32; 2], - feature: &Feature, - ) -> Result { - if stand_in.format != Format::R32_SFLOAT - || !image_aspects(destination.format).contains(ImageAspectFlags::DEPTH) - { - return Err(internal( - "a depth copy from no stand-in or into a target without depth", - )); - } - let view = stand_in_view(stand_in, form)?; - DepthDraw::of_view( - device, - DepthStencilCopy::DepthFromStandIn { form }, - view, - destination, - DrawArea::whole(area), - feature, - ) - } - - /// The draw that writes the depths `source`, a multisampled colour target, holds at each - /// pixel of `area` into `destination`'s depth there: an `R32_SFLOAT` source's floats into a - /// 32-bit float depth, or an `R16_UINT` source's codes into a 16-bit unsigned normalized one - /// ([`DepthStencilCopy::Depth16Code`], the module docs). - pub(super) fn from_colour( - device: &Device, - source: &Target, - destination: &Target, - area: DrawArea, - feature: &Feature, - ) -> Result { - let copy = match unorm16_depth(destination.format) { - true => DepthStencilCopy::Depth16Code, - false => DepthStencilCopy::Depth, - }; - let carrier = depth_carrier(destination.format) - .ok_or_else(|| internal("a depth copy into a target of no drawn depth"))?; - if source.samples != destination.samples - || source.format != carrier - || !image_aspects(destination.format).contains(ImageAspectFlags::DEPTH) - { - return Err(internal( - "a depth copy from a colour target of other samples or another format", - )); - } - let view = aspect_view(source, ImageAspectFlags::COLOR)?; - DepthDraw::of_view(device, copy, view, destination, area, feature) - } - - /// The bits draw that writes the bits of `source`'s `aspect` (a 32-bit float depth's `f32` - /// bit-cast, a 16-bit unsigned normalized depth's code, a stencil's value) at each pixel of - /// `area` into `destination` there: a multisampled `R32_UINT` colour target for a 32-bit - /// float depth, `R16_UINT` for a 16-bit one, `R8_UINT` for a stencil. - pub(super) fn bits( - device: &Device, - source: &Target, - aspect: ImageAspectFlags, - destination: &Target, - area: DrawArea, - feature: &Feature, - ) -> Result { - let (copy, format) = match aspect { - ImageAspectFlags::DEPTH if unorm16_depth(source.format) => { - (DepthStencilCopy::Depth16Bits, Format::R16_UINT) - } - ImageAspectFlags::DEPTH => (DepthStencilCopy::DepthBits, Format::R32_UINT), - _ => (DepthStencilCopy::StencilBits, Format::R8_UINT), - }; - if source.samples != destination.samples - || !image_aspects(source.format).contains(aspect) - || destination.format != format - { - return Err(internal( - "a bits copy between targets of other samples or formats", - )); - } - let view = aspect_view(source, aspect)?; - DepthDraw::of_view(device, copy, view, destination, area, feature) - } - - /// The draw of `copy` reading `view` into `destination` over `area`. - fn of_view( - device: &Device, - copy: DepthStencilCopy, - view: vk::ImageView, - destination: &Target, - area: DrawArea, - feature: &Feature, - ) -> Result { - let (shaders, made) = - device.depth_draw(copy, destination.format, destination.samples, feature)?; - let (mut objects, set) = - PassObjects::with_set(device, shaders.set_layout, &[(draw_source(copy), view)])?; - draw_framebuffer(&mut objects, made.render_pass, destination, area.end())?; - Ok(DepthDraw { - objects: Arc::new(objects), - shaders, - made, - set, - area, - }) - } - - /// Record, outside a render pass, the draw's render pass. - /// - /// # Safety - /// - /// `raw` is the device's command buffer, recording outside a render pass, which only the - /// caller records; the source, the destination and this draw's objects are live until it - /// completes and rest in `GENERAL`. - pub(super) unsafe fn record(&self, device: &ash::Device, raw: vk::CommandBuffer) { - record_draws_in( - device, - raw, - (self.made.render_pass, self.objects.framebuffer), - (self.shaders.layout, self.set), - &[self.made.pipeline], - self.area, - ); - } -} diff --git a/crates/metal2vulkan-runtime/src/depth_stand_in.rs b/crates/metal2vulkan-runtime/src/depth_stand_in.rs deleted file mode 100644 index 01c4192d5..000000000 --- a/crates/metal2vulkan-runtime/src/depth_stand_in.rs +++ /dev/null @@ -1,598 +0,0 @@ -//! The depth stand-in: what a render encoder keeps for a pipeline whose fragment function runs the -//! draw's depth test itself (`GraphicsState::shader_tests`), as [`ShaderTestsUse`]'s contract asks -//! of a consumer, the shader-side stencil's shadow's twin (`shadow_stencil.rs`). -//! -//! - **The stand-in** is an `R32_SFLOAT` image of the depth attachment's extent, in `GENERAL` -//! like every runtime image, holding pixel `(x, y)`'s depth at texel `(x, y)` as the pipeline's -//! [`StandInView`] says: a 2D image of the pipeline's samples (single-sample at one), or, on a -//! device without multisampled storage images, a single-sample 2D array of one layer per -//! sample. Made at the pass's first such draw and bound where the plan writes -//! `WriteSource::DepthStandIn`. -//! - **The instances.** Such draws record into render pass instances of their own (`render.rs`): -//! consecutive ones share an instance, and a draw of another pipeline after them starts the -//! next. During one the pipelines' depth test is `ALWAYS` without writes, and the stencil test -//! is off (`render.rs`'s `draw_fixed`), so the pass never changes the depth: the function is -//! the test. Before each such instance the stand-in is filled, and after it the stand-in is -//! copied back into the depth aspect, outside the render pass, between barriers from -//! everything before and to everything after. An instance that runs the pass's load actions -//! fills it from the depth's load action instead of the attachment: the clear depth where it -//! clears (the attachment's clear runs only as the instance begins), nothing where Metal's -//! depth is undefined (`DontCare`), the attachment where it loads. So a memoryless depth, which -//! renders into its backing in such a pass (`attachment_stand_in.rs`), is read only where an -//! earlier instance of the pass rendered it. A depth that resolves is resolved by one more -//! instance, of no draws, after the last copy back. -//! - **The copies.** Of one sample, through a staging buffer of 4 bytes a texel of the render -//! area: the depth aspect into the buffer, then the buffer into the stand-in, and back the same -//! way. Of more, in the multisampled form on a device whose maintenance8 depth/colour copies -//! move a multisampled aspect (`depth_stencil_scratch::colour_copies_refused`: RADV, ANV), one -//! `vkCmdCopyImage` each way between the depth aspect and the stand-in. Elsewhere (lavapipe, -//! MoltenVK and Ampere GA10x, whose copies run wrong, a device without maintenance8, and the -//! sample planes), by the kernel and the draw of `depth_copy.rs`: the depth split, which reads -//! the depth aspect through a sampled view into the stand-in, and the `FragDepth` draw of -//! `DepthStencilCopy::DepthFromStandIn` back, exact where the driver's fragment depth stores -//! every value unchanged (lavapipe), and elsewhere, for a 32-bit float depth, the announced -//! near-equivalent `drawn-depth-copy` (what MoltenVK's and NVIDIA's are measured to change, or -//! Vulkan leaves to a driver not measured: values outside `[0, 1]`, denormals, signed zero, NaN, -//! none of which a depth test stores in the clip mode's range); a 16-bit depth is refused. The -//! split reads an image with `SAMPLED`, which a multisampled depth/stencil render target the -//! runtime makes takes on such a device where it costs the image nothing -//! (`depth_stencil_scratch::sampled_candidate`); a draw whose instance needs the copy in of an -//! image without it is refused, typed, naming why the copies cannot run. -//! -//! [`ShaderTestsUse`]: metal2vulkan::pipeline::ShaderTestsUse - -use super::attachment_stand_in; -use super::blit::{reads, writes, TRANSFER}; -use super::buffer::Buffer; -use super::command_buffer::CommandBuffer; -use super::depth_copy::{self, stand_in_view, DepthDraw, DepthSplit, Drawn}; -use super::depth_stencil_scratch::colour_copies_refused; -use super::error::{internal, Error}; -use super::image_plan::{sample_count, ImagePlan}; -use super::render_pass::{AspectClear, Target}; -use super::render_values::LoadAction; -use super::resource::ResourceKey; -use super::stencil_copy::{self, attachment_use}; -use super::texture::{image_aspects, Texture}; -use super::texture_descriptor::TextureDescriptor; -use super::tracker::{Access, Barrier, Use}; -use super::values::ResourceOptions; -use super::Device; -use crate::device::functions::Vk; -use ash::vk; -use metal2vulkan::bind::DepthStandInForm; -use metal2vulkan::device::VkProperty; -use metal2vulkan::error::{Capability, Feature, Unsupported}; -use metal2vulkan::metal::format::FormatMapping; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; -use metal2vulkan::pipeline::{StandInUse, StandInView}; -use metal2vulkan::vk::{Format, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags}; - -/// The feature a refusal of the stand-in's copies names: the compile layer's for the in-shader -/// test (`pipeline::link::shader_tests`). -const FEATURE: Feature = Feature::FramebufferFetch; - -/// How a stand-in is copied (the module docs, [`route`]). -struct Route { - form: DepthStandInForm, - /// `Ok(true)` image to image, `Ok(false)` through a buffer, or `Err` by the kernel and the - /// draw, naming why the image copies cannot. - image_copies: Result, - /// Where by the kernel and the draw, what the draw back changes (`depth_copy::drawn`). - drawn: Option, -} - -/// How a stand-in of view `view` of a depth target of Vulkan format `format` and `samples` -/// samples is copied (the module docs); refused where the copies by the kernel and the draw are -/// not measured to run. -fn route( - device: &Device, - (view, samples): (StandInView, u32), - format: Format, -) -> Result { - let form = match (view, samples) { - (StandInView::Image, _) => DepthStandInForm::Multisampled, - (StandInView::SamplePlanes { layers }, _) if layers == samples && samples > 1 => { - DepthStandInForm::SamplePlanes - } - _ => { - return Err(internal( - "a depth stand-in of another view than its samples", - )) - } - }; - let planes = form == DepthStandInForm::SamplePlanes; - // How the samples move (the module docs): `Err` where by the kernel and the draw, naming why - // the image copies cannot. - let image_copies = match ( - samples, - colour_copies_refused(device, FEATURE, ImageAspectFlags::DEPTH), - ) { - (1, _) => Ok(false), - (_, None) if !planes => Ok(true), - (_, None) => Err(Unsupported::needs( - FEATURE, - Capability::Property(VkProperty::StorageImageSampleCount(samples)), - )), - (_, Some(refused)) => Err(refused), - }; - let drawn = match &image_copies { - Ok(_) => None, - Err(refused) => match depth_copy::drawn(device, format) { - Some(drawn) => Some(drawn), - None => return Err(Error::Unsupported(refused.clone())), - }, - }; - Ok(Route { - form, - image_copies, - drawn, - }) -} - -/// Make, at a render pipeline state's creation, the pipelines its tested draws' depth stand-in -/// copies by, where they go by the kernel and the draw (the module docs): the draw back and the -/// depth split, each made once per device, as Metal compiles at creation. The caller's state has -/// a depth attachment of Vulkan format `format` and `samples` samples, and a draw of it whose -/// depth test alone can drop fragments runs the variant whose fragment function tests the depth -/// itself (`GraphicsState::make_stand_in_copies`), so these are what its first such draw would -/// otherwise make while it encodes (on MoltenVK two Metal compiles). The stand-in holds the -/// samples as the compile layer's depth test reads them (`lower::fragment::depth_test_form`): as -/// sample planes at more than one sample on a device without multisampled storage images, as one -/// image otherwise. Whatever is refused here is left to that draw, which meets it again. -pub(crate) fn make_copies(device: &Device, samples: u32, format: Format) { - let planes = samples > 1 - && !device - .compile_device() - .profile() - .images() - .storage_multisample; - let view = match planes { - true => StandInView::SamplePlanes { layers: samples }, - false => StandInView::Image, - }; - if let Ok(Route { - form, - image_copies: Err(_), - drawn: Some(_), - }) = route(device, (view, samples), format) - { - device.make_stand_in_copies(form, (format, samples), &FEATURE); - } -} - -/// How the stand-in and the depth aspect are copied (the module docs). -#[derive(Clone)] -enum Copies { - /// One sample: through a buffer of 4 bytes a texel of the render area. - Buffer(Buffer), - /// Image to image, by maintenance8's depth/colour copies. - Image, - /// The depth split in, where the depth's image is sampled, and the `FragDepth` draw back. - Drawn { - split: Option, - back: DepthDraw, - }, -} - -/// A pass's depth stand-in, and how it is copied. -#[derive(Clone)] -pub(super) struct DepthStandIn { - /// The stand-in, as the storage target its view is made of. - stand_in: Target, - form: DepthStandInForm, - copies: Copies, - /// Why the depth cannot be copied into the stand-in, where it cannot: a draw whose instance - /// needs the copy in is refused with it. - no_copy_in: Option, - /// The render area, from the origin: what the copies cover. - area: [u32; 2], -} - -impl DepthStandIn { - /// The stand-in `used` names of `depth`, the pass's depth/stencil target, over the render - /// area `area`, made at the pass's first draw of such a pipeline (the module docs). `depth` - /// must have a depth aspect of a 32-bit float, the use's samples and one layer (link and the - /// binder state no stand-in otherwise). Refused (`NotImplemented(Render)`) where `depth`'s - /// image does not copy both ways where the copies need it (a caller's image without transfer - /// usage); where the copies go by the kernel and the draw, refused naming why the device's - /// copies cannot move the samples where its fragment depth is not measured, and naming - /// what the device lacks where it lacks what they need. - pub(super) fn new( - maker: &CommandBuffer, - used: &StandInUse, - depth: &Target, - area: [u32; 2], - ) -> Result { - let device = maker.device(); - let samples = depth.samples; - if used.format != Format::R32_SFLOAT - || used.samples != samples - || depth.layers != 1 - || !image_aspects(depth.format).contains(ImageAspectFlags::DEPTH) - || !depth_copy::float_depth(depth.format) - { - return Err(internal( - "a shader-side depth test whose stand-in the pass's depth cannot be", - )); - } - let Route { - form, - image_copies, - drawn, - } = route(device, (used.view, used.samples), depth.format)?; - let planes = form == DepthStandInForm::SamplePlanes; - let (layers, image_samples) = match planes { - true => (samples, 1), - false => (1, samples), - }; - if image_copies.is_ok() { - // Copied by transfers both ways (a caller's image may lack the usage). - attachment_stand_in::check_copies(depth)?; - } - let [width, height] = depth.extent; - let samples_flag = sample_count(image_samples) - .ok_or_else(|| internal("an attachment of a sample count Vulkan lacks"))?; - let descriptor = TextureDescriptor { - texture_type: match (image_samples > 1, planes) { - (true, _) => TextureType::Type2DMultisample, - (false, true) => TextureType::Type2DArray, - (false, false) => TextureType::Type2D, - }, - pixel_format: PixelFormat::R32Float, - width: width.into(), - height: height.into(), - array_length: layers.into(), - sample_count: image_samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - ..TextureDescriptor::default() - }; - let plan = ImagePlan { - pixel_format: PixelFormat::R32Float, - flags: ImageCreateFlags::empty(), - image_type: ImageType::TYPE_2D, - format: Format::R32_SFLOAT, - extent: [width, height, 1], - levels: 1, - layers, - samples: samples_flag, - usage: ImageUsageFlags::STORAGE - | ImageUsageFlags::TRANSFER_SRC - | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping: FormatMapping::direct(Format::R32_SFLOAT, ImageAspectFlags::COLOR), - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::RENDER_TARGET - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - let texture = Device::new_planned_texture(maker, &descriptor, plan)?; - let stand_in = Target { - texture, - level: 0, - layer: 0, - layers, - format: Format::R32_SFLOAT, - samples: image_samples, - extent: [width, height], - }; - let mut no_copy_in = None; - let copies = match (image_copies, drawn) { - (Ok(false), _) => { - let [w, h] = area; - let bytes = 4 * u64::from(w) * u64::from(h); - Copies::Buffer(device.own_buffer(bytes, ResourceOptions::private())?) - } - (Ok(true), _) => Copies::Image, - (Err(refused), drawn) => { - if let Some(Drawn::Changes(changes)) = drawn { - depth_copy::announce_changes(device, changes, || { - format!( - "the depth stand-in's copies back into a {samples}-sample {:?} \ - attachment", - depth.format - ) - }); - } - let back = - DepthDraw::from_stand_in(device, &stand_in, form, depth, area, &FEATURE)?; - let split = match stencil_copy::sampled(depth)? { - true => Some(DepthSplit::new( - device, depth, &stand_in, form, area, &FEATURE, - )?), - false => { - no_copy_in = Some(refused); - None - } - }; - Copies::Drawn { split, back } - } - }; - Ok(DepthStandIn { - stand_in, - form, - copies, - no_copy_in, - area, - }) - } - - /// Refuse a draw whose instance, the first of the pass where `first`, fills the stand-in - /// from the depth `load`s (the module docs) where the depth cannot be copied in: refused - /// (`Unsupported`) naming why the device's copies cannot move its samples. - pub(super) fn check_filled(&self, first: bool, load: Option) -> Result<(), Error> { - let reads = !first || !matches!(load, Some(LoadAction::Clear | LoadAction::DontCare)); - match (&self.no_copy_in, reads) { - (Some(refused), true) => Err(Error::Unsupported(refused.clone())), - _ => Ok(()), - } - } - - /// The storage view the plan's `WriteSource::DepthStandIn` binds. - pub(super) fn view(&self) -> Result { - stand_in_view(&self.stand_in, self.form) - } - - /// A draw's uses of the stand-in: the fragment shader reads and writes it. - pub(super) fn draw_uses(&self) -> Result>, Error> { - let stage = vk::PipelineStageFlags2::FRAGMENT_SHADER; - let read = Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_READ); - let write = Access::new(stage, vk::AccessFlags2::SHADER_STORAGE_WRITE); - let layers = 0..self.stand_in.layers; - let texture = &self.stand_in.texture; - Ok(vec![ - texture.image_use(0..1, layers.clone(), read, false)?, - texture.image_use(0..1, layers, write, true)?, - ]) - } - - /// The copies' uses, both ways, between the stand-in and `depth`, and the stand-in's clear. - pub(super) fn copy_uses(&self, depth: &Target) -> Result>, Error> { - let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - let levels = depth.level..depth.level + 1; - let depth_layers = depth.layer..depth.layer + 1; - let layers = 0..self.stand_in.layers; - let texture = &self.stand_in.texture; - let mut uses = vec![texture.image_use(0..1, layers.clone(), write, true)?]; - match &self.copies { - Copies::Buffer(_) | Copies::Image => { - uses.push(texture.image_use(0..1, layers, read, false)?); - uses.push(depth.texture.image_use( - levels.clone(), - depth_layers.clone(), - read, - false, - )?); - uses.push(depth.texture.image_use(levels, depth_layers, write, true)?); - } - Copies::Drawn { split, .. } => { - let compute = vk::PipelineStageFlags2::COMPUTE_SHADER; - let fragment = vk::PipelineStageFlags2::FRAGMENT_SHADER; - if split.is_some() { - let sampled = Access::new(compute, vk::AccessFlags2::SHADER_SAMPLED_READ); - let stored = Access::new(compute, vk::AccessFlags2::SHADER_STORAGE_WRITE); - uses.push( - depth - .texture - .image_use(levels, depth_layers, sampled, false)?, - ); - uses.push(texture.image_use(0..1, layers.clone(), stored, true)?); - } - let read = Access::new(fragment, vk::AccessFlags2::SHADER_STORAGE_READ); - uses.push(texture.image_use(0..1, layers, read, false)?); - uses.push(attachment_use(depth)?); - } - } - if let Copies::Buffer(staging) = &self.copies { - let length = staging.length(); - uses.push(writes(staging, 0..length)); - uses.push(reads(staging, 0..length)); - } - Ok(uses) - } - - /// What the copies go through, which the command buffer holds until it completes. - pub(super) fn held( - &self, - ) -> ( - Texture, - Option, - Option, - Option, - ) { - let texture = self.stand_in.texture.clone(); - match &self.copies { - Copies::Buffer(staging) => (texture, Some(staging.clone()), None, None), - Copies::Image => (texture, None, None, None), - Copies::Drawn { split, back } => (texture, None, split.clone(), Some(back.clone())), - } - } - - /// The copies between the stand-in and `depth`, the pass's depth/stencil target at the end - /// of its encoder, whose depth the pass loads by `load` and clears to `clear` where it - /// clears. - pub(super) fn copies( - &self, - depth: &Target, - load: Option, - clear: Option, - ) -> Result { - let [width, height] = self.area; - let fill = match (load, clear) { - (Some(LoadAction::Clear), Some(AspectClear::Depth(value))) => FirstFill::Clear(value), - (Some(LoadAction::Clear), _) => { - return Err(internal("a cleared depth without its clear value")) - } - (Some(LoadAction::DontCare), _) => FirstFill::Nothing, - _ => FirstFill::Copy, - }; - let (staging, split, back) = match &self.copies { - Copies::Buffer(staging) => (Some(staging.at(0)), None, None), - Copies::Image => (None, None, None), - Copies::Drawn { split, back } => (None, split.clone(), Some(back.clone())), - }; - Ok(StandInCopies { - stand_in: self.stand_in.texture.raw_image()?, - attachment: depth.texture.raw_image()?, - staging, - depth_layers: vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::DEPTH, - mip_level: depth.level, - base_array_layer: depth.layer, - layer_count: 1, - }, - layers: self.stand_in.layers, - extent: vk::Extent3D { - width, - height, - depth: 1, - }, - fill, - split, - back, - }) - } -} - -/// How the instance that runs the pass's load actions fills the stand-in (the module docs). -#[derive(Clone, Copy, Debug, PartialEq)] -enum FirstFill { - /// The depth clears: to the clear depth. - Clear(f32), - /// Metal's depth is undefined (`DontCare`): nothing. - Nothing, - /// The depth loads: the copy in. - Copy, -} - -/// The recorded form of a pass's copies between its depth and its stand-in -/// ([`DepthStandIn::copies`]). -pub(super) struct StandInCopies { - stand_in: vk::Image, - attachment: vk::Image, - /// The staging buffer and the offset of its range, for a stand-in of one sample. - staging: Option<(vk::Buffer, u64)>, - depth_layers: vk::ImageSubresourceLayers, - /// The stand-in's layers: its sample planes, or 1. - layers: u32, - extent: vk::Extent3D, - fill: FirstFill, - /// The split in and the draw back, where the samples move by them. - split: Option, - back: Option, -} - -impl StandInCopies { - /// Record, outside a render pass, the stand-in's filling before an instance of such draws: - /// from the depth's load action where the instance runs the pass's load actions (`first`), - /// else the copy of the depth aspect (the module docs). Between barriers from everything - /// before and to everything after. - /// - /// # Safety - /// - /// `raw` is `device`'s command buffer, recording outside a render pass, which only this - /// encoder records; the stand-in, its staging buffer, the depth's image and the copies' - /// objects live until it completes and rest in `GENERAL`; the encoder refused every draw - /// whose instance needs a copy in that cannot run ([`DepthStandIn::check_filled`]). - pub(super) unsafe fn record_in(&self, device: &Vk, raw: vk::CommandBuffer, first: bool) { - let fill = match first { - true => self.fill, - false => FirstFill::Copy, - }; - Barrier::everything().record(device, raw); - match fill { - FirstFill::Clear(value) => { - let colour = vk::ClearColorValue { - float32: [value, 0.0, 0.0, 0.0], - }; - let range = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: self.layers, - }; - let general = vk::ImageLayout::GENERAL; - device.cmd_clear_color_image(raw, self.stand_in, general, &colour, &[range]); - } - FirstFill::Nothing => {} - FirstFill::Copy => match &self.split { - Some(split) => split.record(device, raw), - None if self.back.is_some() => {} - None => self.copy(device, raw, true), - }, - } - Barrier::everything().record(device, raw); - } - - /// Record, outside a render pass, the copy of the stand-in back into the depth aspect after - /// an instance of such draws, between barriers from everything before and to everything - /// after. - /// - /// # Safety - /// - /// As for [`StandInCopies::record_in`]. - pub(super) unsafe fn record_out(&self, device: &Vk, raw: vk::CommandBuffer) { - Barrier::everything().record(device, raw); - match &self.back { - Some(back) => back.record(device, raw), - None => self.copy(device, raw, false), - } - Barrier::everything().record(device, raw); - } - - /// Record the transfer copy of the render area between the depth aspect and the stand-in: - /// into the stand-in (`inward`) or back; through the staging buffer at one sample. - /// - /// # Safety - /// - /// As for [`StandInCopies::record_in`]. - unsafe fn copy(&self, device: &Vk, raw: vk::CommandBuffer, inward: bool) { - let general = vk::ImageLayout::GENERAL; - let stand_in_layers = vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::COLOR, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }; - let ((from, from_layers), (to, to_layers)) = if inward { - ( - (self.attachment, self.depth_layers), - (self.stand_in, stand_in_layers), - ) - } else { - ( - (self.stand_in, stand_in_layers), - (self.attachment, self.depth_layers), - ) - }; - match self.staging { - Some((buffer, offset)) => { - let region = |layers| vk::BufferImageCopy { - buffer_offset: offset, - buffer_row_length: 0, - buffer_image_height: 0, - image_subresource: layers, - image_offset: vk::Offset3D::default(), - image_extent: self.extent, - }; - device.cmd_copy_image_to_buffer(raw, from, general, buffer, &[region(from_layers)]); - Barrier::everything().record(device, raw); - device.cmd_copy_buffer_to_image(raw, buffer, to, general, &[region(to_layers)]); - } - None => { - let region = vk::ImageCopy { - src_subresource: from_layers, - src_offset: vk::Offset3D::default(), - dst_subresource: to_layers, - dst_offset: vk::Offset3D::default(), - extent: self.extent, - }; - device.cmd_copy_image(raw, from, general, to, general, &[region]); - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/depth_stencil.rs b/crates/metal2vulkan-runtime/src/depth_stencil.rs deleted file mode 100644 index ae3014bd3..000000000 --- a/crates/metal2vulkan-runtime/src/depth_stencil.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! `DepthStencilState` (`MTLDepthStencilState`) and `Device::new_depth_stencil_state` -//! (step 6's second part). -//! -//! A depth/stencil state is its descriptor (the compile layer's [`DepthStencilDescriptor`], Metal's -//! properties) and the Vulkan depth/stencil state it stands for -//! ([`metal2vulkan::metal::state::depth_stencil_state`]): a render encoder's draws take it as the -//! pipeline's static depth/stencil state, or as dynamic state where the pipeline makes it dynamic -//! (`render.rs`). Metal makes a state of any descriptor, masks wider than the 8-bit stencil -//! included (measured on an M4), so creation refuses nothing. A state holds no Vulkan object, so -//! it goes on past the device's recovery, as Metal's state does, the recovery carrying its handle -//! of the device alone (`device/carry.rs`'s `LineDevice`). -//! -//! A state's `gpuResourceID` below Apple10 is the release's answer, not a refusal: Metal's API -//! validation stops the call ("Obtaining the resourceID of a DepthStencilState object requires -//! support for MTLGPUFamilyApple10", an M4 under macOS 27.0.1), but plain Metal is what the -//! runtime answers as, and the two differ. The plain call of the release every device answers as -//! answers 0 for every state asked below Apple10 (our probe on an M3 Max, and an earlier run of -//! three states over two runs; `metal_release.rs`). What the ID names on Apple10, a depth/stencil -//! state an indirect render command sets, is not built. - -use super::device::carry::LineDevice; -use super::error::{Error, IndirectRule, RuntimeGap}; -use super::families::GpuFamily; -use super::metal_release::DEPTH_STENCIL_RESOURCE_ID; -use super::resource_ids::ResourceId; -use super::Device; -use metal2vulkan::metal::state::{depth_stencil_state, DepthStencilDescriptor, StencilDescriptor}; -use metal2vulkan::metal::{CompareFunction, StencilOperation}; -use std::sync::Arc; - -/// `MTLDepthStencilState`: cheap to clone, `Send` and `Sync`. -#[derive(Clone)] -pub struct DepthStencilState(Arc); - -struct Shared { - /// The device: its root handle, which the encoders' checks match by its line, and the - /// generation handle `device` answers. - device: LineDevice, - descriptor: DepthStencilDescriptor, - vulkan: metal2vulkan::metal::state::DepthStencilState, -} - -impl std::fmt::Debug for DepthStencilState { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("DepthStencilState") - .field("descriptor", &self.0.descriptor) - .finish() - } -} - -impl PartialEq for DepthStencilState { - /// The same state object (Metal's identity), not an equal descriptor. - fn eq(&self, other: &DepthStencilState) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -impl Device { - /// `newDepthStencilStateWithDescriptor:`: a state of `descriptor` (the module docs). - pub fn new_depth_stencil_state( - &self, - descriptor: &DepthStencilDescriptor, - ) -> Result { - self.at_serving(|device| device.new_depth_stencil_state_now(descriptor)) - } - - /// [`Device::new_depth_stencil_state`] on the generation that serves (`device/line.rs`). - pub(crate) fn new_depth_stencil_state_now( - &self, - descriptor: &DepthStencilDescriptor, - ) -> Result { - Ok(DepthStencilState(Arc::new(Shared { - device: LineDevice::new(self), - descriptor: *descriptor, - vulkan: depth_stencil_state(descriptor), - }))) - } -} - -impl DepthStencilState { - /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained - /// device: of the generation the state was made on, then of each one the device's recoveries - /// carried the state to. The handle is the caller's: it keeps meaning that generation while - /// held, past a recovery that carries the state on, its raw handles that generation's - /// `VkDevice`'s, kept alive while held. - pub fn device(&self) -> Device { - self.0.device.generation().clone() - } - - /// A root handle of the state's device, which an encoder of any of its generations matches. - pub(super) fn root_device(&self) -> &Device { - self.0.device.root() - } - - /// The descriptor the state was made with. No Metal counterpart: Metal's state keeps none. - pub fn descriptor(&self) -> &DepthStencilDescriptor { - &self.0.descriptor - } - - /// `gpuResourceID` (the module docs): on a device that does not claim Apple10 - /// ([`Device::supports_family`]), what plain Metal answers there, 0. Refused - /// `NotImplemented(IndirectRenderCommands)` on a device that claims Apple10: indirect render - /// commands that set a depth/stencil state are not built. - pub fn gpu_resource_id(&self) -> Result { - if (self.0.device.root()).supports_family(GpuFamily::Apple10.raw()) { - return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands( - IndirectRule::CommandRenderStates, - ))); - } - Ok(DEPTH_STENCIL_RESOURCE_ID) - } - - /// The Vulkan depth/stencil state the state stands for. - pub(super) fn vulkan(&self) -> metal2vulkan::metal::state::DepthStencilState { - self.0.vulkan - } - - /// What the state does with depth in a pass without a depth attachment (measured on an M4): - /// Metal's validation stops a draw that writes depth or compares other than `Always` and - /// `Never`, which plain Metal tests against the pass's hidden depth. Under `Never` every - /// fragment fails, where Vulkan, with no attachment to test, would pass it - /// ([`DepthStencilState::failing_depth`]). - pub(super) fn depth_without_attachment(&self) -> DepthUse { - let descriptor = &self.0.descriptor; - match descriptor.depth_compare_function { - _ if descriptor.depth_write_enabled => DepthUse::Stops, - CompareFunction::Always => DepthUse::None, - CompareFunction::Never => DepthUse::FailsAll, - _ => DepthUse::Stops, - } - } - - /// The descriptor that stands for the state where every fragment fails Metal's depth test - /// ([`DepthUse::FailsAll`]) and the fragment function runs (probes): no depth test, and each - /// face's pass operation its depth-failure operation, since a fragment that passes the stencil - /// test then fails the depth test. A fragment that fails the stencil test takes its failure - /// operation, as before, and one the function drops takes none. - pub(super) fn failing_depth(&self) -> DepthStencilDescriptor { - let mut descriptor = self.0.descriptor; - descriptor.depth_compare_function = CompareFunction::Always; - descriptor.depth_write_enabled = false; - for face in [ - &mut descriptor.front_face_stencil, - &mut descriptor.back_face_stencil, - ] { - face.depth_stencil_pass_operation = face.depth_failure_operation; - } - descriptor - } - - /// How a draw under the state runs where every fragment fails Metal's depth test - /// ([`FailingDraw`]), in a pass with (or without) a stencil attachment (`stencil`), of a - /// pipeline whose fragment function declares `[[early_fragment_tests]]` (`early`), writes - /// attachments or an imageblock in its body (`body_writes`: color attachments as storage - /// images, or the pass's imageblock, which no write mask stops), or writes memory - /// (`writes_memory`: `GraphicsState::fragment_writes_memory`). Under early tests, where - /// the stencil operation depends on the stored value ([`DepthStencilState::failing_early`]), - /// a function that writes neither runs as one without early tests does - /// ([`FailingDraw::Runs`]): Vulkan's early tests take each fragment's operation before the - /// function as Metal's do, and the run, its colors masked, leaves nothing Metal's never-run - /// function would not. Refused `NotImplemented(DepthNeverWithoutAttachment)` for a function - /// that runs and writes in its body, and for one under early tests that writes there or - /// writes memory whose stencil operation depends on the stored value. - pub(super) fn failing_draw( - &self, - early: bool, - stencil: bool, - (body_writes, writes_memory): (bool, bool), - ) -> Result { - let refused = Error::NotImplemented(RuntimeGap::DepthNeverWithoutAttachment); - match early { - true => match self.failing_early(stencil) { - Some(draw) => Ok(draw), - None if !body_writes && !writes_memory => { - Ok(FailingDraw::Runs(self.failing_depth())) - } - None => Err(refused), - }, - false if body_writes => Err(refused), - false => Ok(FailingDraw::Runs(self.failing_depth())), - } - } - - /// How a draw under the state runs where every fragment fails Metal's depth test and the - /// fragment function declares `[[early_fragment_tests]]`, which Metal then never runs - /// (probes), in a pass with (or without) a stencil attachment (`stencil`): each fragment still - /// takes the face's depth-failure operation where it passes the stencil test and its failure - /// operation where it fails it. `None` where that depends on the stored value (a comparison - /// other than `Always` and `Never` whose two operations differ and write), which no Vulkan test - /// that every fragment fails gives. - fn failing_early(&self, stencil: bool) -> Option { - let descriptor = &self.0.descriptor; - if !stencil { - return Some(FailingDraw::Untouched); - } - let front = early_operation(&descriptor.front_face_stencil)?; - let back = early_operation(&descriptor.back_face_stencil)?; - if front == StencilOperation::Keep && back == StencilOperation::Keep { - return Some(FailingDraw::Untouched); - } - let mut failing = *descriptor; - failing.depth_compare_function = CompareFunction::Always; - failing.depth_write_enabled = false; - for (face, operation) in [ - (&mut failing.front_face_stencil, front), - (&mut failing.back_face_stencil, back), - ] { - face.stencil_compare_function = CompareFunction::Never; - face.stencil_failure_operation = operation; - face.depth_failure_operation = StencilOperation::Keep; - face.depth_stencil_pass_operation = StencilOperation::Keep; - } - Some(FailingDraw::Fails(failing)) - } - - /// Whether the state uses the stencil on either face: a draw under it needs a stencil - /// attachment (measured: Metal's validation stops such a draw in a pass without one, which - /// plain Metal tests against the pass's hidden stencil). - pub(super) fn uses_stencil(&self) -> bool { - let descriptor = &self.0.descriptor; - uses(&descriptor.front_face_stencil) || uses(&descriptor.back_face_stencil) - } -} - -/// What a depth/stencil state does with depth in a pass without a depth attachment. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum DepthUse { - /// Nothing: the default compare, `Always`, without writes. - None, - /// Metal's validation stops the draw; plain Metal tests it against the pass's hidden depth. - Stops, - /// Every fragment fails (`Never`): Metal writes no attachment, takes each face's - /// depth-failure operation where the stencil test passes, and counts no sample; it runs the - /// fragment function unless the function declares `[[early_fragment_tests]]`. - FailsAll, -} - -/// How a draw runs where Metal's depth test fails every fragment, a compare of `Never` in a -/// pass without a depth attachment (probes, the M3 Max and an M4 alike): Metal writes no -/// attachment, counts no sample, and runs the vertex function; each fragment takes the face's -/// depth-failure operation where it passes the stencil test and its failure operation where it -/// fails it, and one the fragment function drops takes none. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum FailingDraw { - /// The fragment function runs for every fragment (it does not declare - /// `[[early_fragment_tests]]`, or it does and writes nothing): under this descriptor's state - /// ([`DepthStencilState::failing_depth`]), every color write mask empty, no visibility query - /// counting it. - Runs(DepthStencilDescriptor), - /// The function declares early tests and runs for no fragment: under this descriptor's - /// state, whose stencil test every fragment fails, each taking the operation Metal takes - /// before the function. - Fails(DepthStencilDescriptor), - /// The function declares early tests and no fragment changes the stencil: the draw reaches - /// no fragment (its scissors are empty). - Untouched, -} - -/// The one stencil operation every fragment of a face takes where every fragment fails Metal's -/// depth test before the function runs: the depth-failure operation where the face's stencil -/// test passes, the failure operation where it fails, `Keep` where the write mask leaves the -/// 8-bit stencil alone. `None` where the two can both apply and differ. -fn early_operation(face: &StencilDescriptor) -> Option { - let (fail, depth_fail) = (face.stencil_failure_operation, face.depth_failure_operation); - match face.stencil_compare_function { - _ if face.write_mask & 0xff == 0 => Some(StencilOperation::Keep), - CompareFunction::Never => Some(fail), - CompareFunction::Always => Some(depth_fail), - _ => (fail == depth_fail).then_some(fail), - } -} - -/// Whether a face's stencil descriptor tests or writes (measured: Metal's validation stops it -/// without a stencil attachment when it compares other than `Always`, or its depth-failure or -/// pass operation is other than `Keep`; masks, and a failure operation under `Always`, which -/// never fails, are free). -fn uses(face: &StencilDescriptor) -> bool { - face.stencil_compare_function != CompareFunction::Always - || face.depth_failure_operation != StencilOperation::Keep - || face.depth_stencil_pass_operation != StencilOperation::Keep -} diff --git a/crates/metal2vulkan-runtime/src/depth_stencil_resolve.rs b/crates/metal2vulkan-runtime/src/depth_stencil_resolve.rs deleted file mode 100644 index e23c9c4e3..000000000 --- a/crates/metal2vulkan-runtime/src/depth_stencil_resolve.rs +++ /dev/null @@ -1,526 +0,0 @@ -//! Metal's depth and stencil resolves no Vulkan resolve mode makes, drawn after the pass. -//! -//! Metal resolves a `DepthResolvedSample` stencil to the stencil of the sample whose depth the -//! depth filter took: of equal depths, the last sample after `Min` and the first after `Max` -//! (a probe, an M3 Max and an M4 alike). No Vulkan resolve mode states it. And a device may have no -//! `MIN` or `MAX` depth resolve mode (lavapipe). `resolve.rs` marks each such aspect -//! `ResolveMode::Picked`: the pass's subpass resolves the other aspects (the depth by `MIN` or -//! `MAX` where the device has the mode, the picked ones `NONE`), and after the pass these draws -//! write the picked aspects into the same resolve attachment (the resolve texture's level and -//! slice, or the scratch image copied there after them), or into one of their own where the -//! subpass resolves nothing: -//! -//! - **The draws**: a render pass of the resolve attachment alone, one invocation per pixel, each -//! reading every sample's depth (and stencil) of the multisampled attachment through sampled -//! views and taking Metal's sample by depth ([`DepthPick`]), of the draws of -//! `bind::depth_stencil_resolve_modules`. A picked depth is [`ResolveWrite::Depth`]'s draw, its -//! `FragDepth` written under compare `ALWAYS` with the stencil test off: only where -//! `depth_copy::copies_exactly` holds (a 32-bit float depth, on a driver whose fragment depth -//! stores every value unchanged, `DriverFact::FragmentDepthStoresUnchanged`, or a 16-bit one -//! whose codes it keeps, `DriverFact::FragmentDepthKeepsDepth16Codes`), which -//! `resolve.rs` checks before it picks; elsewhere the device's missing mode stays refused. A -//! picked stencil is the eight bit-plane draws ([`ResolveWrite::StencilPlane`]) over the -//! stencil cleared to 0 over the render area: each survives where its sample's stencil has its -//! bit, which the draw sets under write mask [`StencilBit::mask`], reference 0xFF, compare -//! `ALWAYS` and pass op `REPLACE`, the depth test off; exact on every device, stencil export or -//! not. The pass loads and stores the depth (drawn first where it is picked), and loads and -//! stores the stencil where only the depth is drawn. -//! - **The samples**: the pass's last instance stores the aspects the draws read -//! (`render_target::final_pass`), whatever Metal's store action, and the attachment's image -//! must be sampled (`SAMPLED` usage, which a texture made for shader reads has, and a -//! multisampled depth/stencil render target the runtime makes takes where it costs nothing); -//! elsewhere the pass is refused `NotImplemented(DepthStencilResolve)` when the encoder opens. -//! A layered pass's draws read its first layer alone, which Metal resolves alone (a probe; -//! `resolve.rs`). -//! -//! The shaders and each pick, sample count, resolve format and set of drawn aspects' render pass -//! and pipelines are made once per device, at first use (when a pass that needs them opens), and -//! destroyed with the device; a resolve's descriptor set and framebuffer are its own, held by its -//! command buffer until it completes. The draws run between barriers from everything before and to -//! everything after. - -use super::device::{device_error, lock}; -use super::encoder::EncoderCore; -use super::error::{internal, Error, RuntimeGap}; -use super::release; -use super::render_pass::{PassLayout, Target}; -use super::resource::ResourceKey; -use super::sample_planes::{pipeline_layout, set_layout, shader_module}; -use super::stencil_copy::{ - aspect_view, attachment_use, draw_framebuffer, record_draws, sampled, sampled_use, PassObjects, - DRAW_STAGES, -}; -use super::texture::image_aspects; -use super::tracker::{Barrier, Use}; -use super::Device; -use crate::shader_cache::driver::Making; -use ash::vk; -use metal2vulkan::bind::{ - depth_stencil_resolve_modules, DepthPick, DepthStencilResolveDraw, DepthStencilResolveModules, - ResolveWrite, StencilBit, -}; -use metal2vulkan::cache::Hash256; -use metal2vulkan::error::Feature; -use metal2vulkan::vk::{Format, ImageAspectFlags}; - -/// The aspects the draws write (the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Drawn { - Depth, - Stencil, - Both, -} - -impl Drawn { - /// The draws writing `aspects`: `None` for neither aspect. - pub(super) fn of(aspects: ImageAspectFlags) -> Option { - match ( - aspects.contains(ImageAspectFlags::DEPTH), - aspects.contains(ImageAspectFlags::STENCIL), - ) { - (true, false) => Some(Drawn::Depth), - (false, true) => Some(Drawn::Stencil), - (true, true) => Some(Drawn::Both), - (false, false) => None, - } - } - - fn depth(self) -> bool { - self != Drawn::Stencil - } - - fn stencil(self) -> bool { - self != Drawn::Depth - } - - /// The draws, in recording order: the depth's, then each [`StencilBit`]'s plane. - pub(super) fn writes(self) -> Vec { - let depth = self.depth().then_some(ResolveWrite::Depth); - let planes = StencilBit::ALL - .into_iter() - .filter(|_| self.stencil()) - .map(ResolveWrite::StencilPlane); - depth.into_iter().chain(planes).collect() - } - - /// The descriptor types of the draws' set, in binding order (`SET`): the depth aspect's - /// alone where the stencil is not drawn. - pub(super) fn set(self) -> &'static [vk::DescriptorType] { - match self.stencil() { - true => &SET, - false => &SET[..1], - } - } -} - -/// The draws' shaders for one pick, sample count and set of drawn aspects, the device's. -#[derive(Clone, Debug)] -struct Shaders { - vertex: vk::ShaderModule, - /// One per draw, in `Drawn::writes`' order. - fragments: Vec, - set_layout: vk::DescriptorSetLayout, - layout: vk::PipelineLayout, - /// The digest of its modules' SPIR-V words, which its pipelines' records are named by - /// (`shader_cache/driver.rs`). - words: Hash256, -} - -/// The draws' render pass and pipelines for one pick, sample count, resolve format and set of -/// drawn aspects. -#[derive(Clone, Debug)] -struct Pipelines { - render_pass: vk::RenderPass, - /// One per draw, in `Drawn::writes`' order. - pipelines: Vec, -} - -/// The resolves' objects one device has made (the module docs): bounded by the two picks, the -/// sample counts, the depth/stencil formats and the three sets of drawn aspects. -#[derive(Default)] -pub(super) struct DepthStencilResolveObjects { - shaders: Vec<((DepthPick, u32, Drawn), Shaders)>, - pipelines: Vec<((DepthPick, u32, Format, Drawn), Pipelines)>, -} - -impl DepthStencilResolveObjects { - /// Destroy every object; the device is idle, and is destroyed next. - pub(super) fn destroy(&self, raw: &ash::Device) { - // SAFETY: the device is idle, so no pending command uses the objects; destroying a null - // handle is a no-op. - unsafe { - for (_, made) in &self.pipelines { - destroy_pipelines(raw, made); - } - for (_, shaders) in &self.shaders { - destroy_shaders(raw, shaders); - } - } - } -} - -/// Destroy `shaders`' objects. -/// -/// # Safety -/// -/// No pending command uses them; a null handle is a no-op. -unsafe fn destroy_shaders(raw: &ash::Device, shaders: &Shaders) { - // SAFETY: the caller's contract. - unsafe { - release::object(raw, shaders.layout); - release::object(raw, shaders.set_layout); - for &fragment in &shaders.fragments { - release::object(raw, fragment); - } - release::object(raw, shaders.vertex); - } -} - -/// Destroy `made`'s objects. -/// -/// # Safety -/// -/// As for `destroy_shaders`. -unsafe fn destroy_pipelines(raw: &ash::Device, made: &Pipelines) { - // SAFETY: the caller's contract. - unsafe { - for &pipeline in &made.pipelines { - release::object(raw, pipeline); - } - release::object(raw, made.render_pass); - } -} - -/// The descriptor types of the draws' set, in binding order: the depth aspect, then the stencil -/// aspect, each sampled. -const SET: [vk::DescriptorType; 2] = [vk::DescriptorType::SAMPLED_IMAGE; 2]; - -impl Device { - /// The `drawn` draws' shaders taking `pick` of `samples` samples, and their pipelines for a - /// resolve attachment of `format`, made on first use; refused (`Unsupported`, naming - /// `Feature::Format`) where the device lacks what they need. - fn resolve_draws( - &self, - pick: DepthPick, - drawn: Drawn, - samples: u32, - format: Format, - ) -> Result<(Shaders, Pipelines), Error> { - // A making's turn before the lock (`budget::helper_turn`): none where it is made. - let _turn = crate::pipeline::budget::helper_turn( - &self.shared().depth_stencil_resolves, - |objects| { - objects - .pipelines - .iter() - .any(|(key, _)| *key == (pick, samples, format, drawn)) - }, - ); - let mut objects = lock(&self.shared().depth_stencil_resolves); - let shared = self.shared(); - let raw = shared.vk(); - let made_shaders = objects - .shaders - .iter() - .find(|(key, _)| *key == (pick, samples, drawn)) - .map(|(_, shaders)| shaders.clone()); - let shaders = match made_shaders { - Some(shaders) => shaders, - None => { - if DepthStencilResolveModules::SET != 0 - || DepthStencilResolveModules::DEPTH_BINDING != 0 - || DepthStencilResolveModules::STENCIL_BINDING != 1 - { - return Err(internal( - "the depth/stencil resolve's bindings out of their set layout's order", - )); - } - let writes = drawn.writes(); - let mut modules = Vec::with_capacity(writes.len()); - for &write in &writes { - let draw = DepthStencilResolveDraw::new(pick, samples, write); - modules.push( - depth_stencil_resolve_modules(self.compile_device(), draw, Feature::Format) - .map_err(device_error)?, - ); - } - let vertex_words = modules - .first() - .map(|m| m.vertex.clone()) - .ok_or_else(|| internal("a resolve of no draw"))?; - let words = modules - .iter() - .fold( - Making::new("depth/stencil resolve modules").words(&vertex_words), - |making, module| making.words(&module.fragment), - ) - .finish(); - let mut shaders = Shaders { - vertex: vk::ShaderModule::null(), - fragments: Vec::with_capacity(modules.len()), - set_layout: vk::DescriptorSetLayout::null(), - layout: vk::PipelineLayout::null(), - words, - }; - let made = (|| { - shaders.vertex = shader_module(raw, &vertex_words)?; - for module in &modules { - shaders - .fragments - .push(shader_module(raw, &module.fragment)?); - } - shaders.set_layout = - set_layout(raw, drawn.set(), vk::ShaderStageFlags::FRAGMENT)?; - shaders.layout = pipeline_layout(raw, shaders.set_layout)?; - Ok(()) - })(); - if let Err(error) = made { - // SAFETY: nothing used the objects. - unsafe { destroy_shaders(raw, &shaders) }; - return Err(error); - } - objects - .shaders - .push(((pick, samples, drawn), shaders.clone())); - shaders - } - }; - if let Some((_, made)) = objects - .pipelines - .iter() - .find(|(key, _)| *key == (pick, samples, format, drawn)) - { - return Ok((shaders, made.clone())); - } - let mut made = Pipelines { - render_pass: vk::RenderPass::null(), - pipelines: Vec::with_capacity(shaders.fragments.len()), - }; - let result = (|| { - // The stencil drawn is cleared first; a depth drawn alone keeps the stencil. - made.render_pass = match drawn.stencil() { - true => super::stencil_copy::planes_pass(raw, format, 1)?, - false => super::depth_copy::depth_pass(raw, format, 1)?, - }; - for (&fragment, write) in shaders.fragments.iter().zip(drawn.writes()) { - let making = Making::new("depth/stencil resolve") - .digest(&shaders.words) - .text(&(pick, samples, format, drawn, write)); - let pipeline = - draw_pipeline(self, &shaders, fragment, made.render_pass, (write, making))?; - made.pipelines.push(pipeline); - } - Ok(()) - })(); - match result { - Ok(()) => { - objects - .pipelines - .push(((pick, samples, format, drawn), made.clone())); - Ok((shaders, made)) - } - Err(error) => { - // SAFETY: nothing used the objects. - unsafe { destroy_pipelines(raw, &made) }; - Err(error) - } - } - } -} - -/// The draw of `write`, whose fragment stage is `fragment`, in `render_pass`: the triangle over -/// the viewport at one sample; for the depth, the depth written under compare `ALWAYS` with the -/// stencil test off; for a stencil plane, the depth test off and the stencil set to the reference -/// where the fragment lives, under the bit's write mask. -/// Its record is the one `making` names. -fn draw_pipeline( - device: &Device, - shaders: &Shaders, - fragment: vk::ShaderModule, - render_pass: vk::RenderPass, - (write, making): (ResolveWrite, Making), -) -> Result { - let shared = device.shared(); - let stages = [ - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(shaders.vertex) - .name(c"main"), - vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::FRAGMENT) - .module(fragment) - .name(c"main"), - ]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - let input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let viewport = vk::PipelineViewportStateCreateInfo::default() - .viewport_count(1) - .scissor_count(1); - let rasterization = vk::PipelineRasterizationStateCreateInfo::default() - .polygon_mode(vk::PolygonMode::FILL) - .cull_mode(vk::CullModeFlags::NONE) - .front_face(vk::FrontFace::COUNTER_CLOCKWISE) - .line_width(1.0); - let multisample = vk::PipelineMultisampleStateCreateInfo::default() - .rasterization_samples(vk::SampleCountFlags::TYPE_1); - let depth_stencil = match write { - ResolveWrite::Depth => vk::PipelineDepthStencilStateCreateInfo::default() - .depth_test_enable(true) - .depth_write_enable(true) - .depth_compare_op(vk::CompareOp::ALWAYS) - .stencil_test_enable(false), - ResolveWrite::StencilPlane(bit) => { - let face = vk::StencilOpState::default() - .fail_op(vk::StencilOp::KEEP) - .pass_op(vk::StencilOp::REPLACE) - .depth_fail_op(vk::StencilOp::KEEP) - .compare_op(vk::CompareOp::ALWAYS) - .compare_mask(0xff) - .write_mask(bit.mask()) - .reference(0xff); - vk::PipelineDepthStencilStateCreateInfo::default() - .depth_test_enable(false) - .depth_write_enable(false) - .stencil_test_enable(true) - .front(face) - .back(face) - } - _ => return Err(internal("a resolve draw the runtime does not record")), - }; - let blend = vk::PipelineColorBlendStateCreateInfo::default(); - let dynamic_states = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; - let dynamic = vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); - let info = vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&input_assembly) - .viewport_state(&viewport) - .rasterization_state(&rasterization) - .multisample_state(&multisample) - .depth_stencil_state(&depth_stencil) - .color_blend_state(&blend) - .dynamic_state(&dynamic) - .layout(shaders.layout) - .render_pass(render_pass) - .subpass(0); - shared.make_graphics_pipeline( - making, - || "metal2vulkan: depth/stencil resolve".to_owned(), - info, - ) -} - -/// Whether the draws can resolve `aspects` of `source` by `pick` into `into`, and their objects -/// made (the module docs): `source` a multisampled attachment of one layer whose image is -/// sampled, with a depth and each drawn aspect, and `into` a single-sampled one with each drawn -/// aspect. Refused as the module docs say, or `Unsupported` where the device lacks what the draws -/// need. -pub(super) fn draws_run( - device: &Device, - source: &Target, - into: &Target, - pick: DepthPick, - aspects: ImageAspectFlags, -) -> Result<(), Error> { - let drawn = Drawn::of(aspects).ok_or_else(|| internal("a drawn resolve of no aspect"))?; - if !image_aspects(source.format).contains(aspects | ImageAspectFlags::DEPTH) - || !image_aspects(into.format).contains(aspects) - || into.samples != 1 - { - return Err(internal("a drawn resolve of other aspects or samples")); - } - if !sampled(source)? { - return Err(Error::NotImplemented(RuntimeGap::DepthStencilResolve)); - } - device - .resolve_draws(pick, drawn, source.samples, into.format) - .map(|_| ()) -} - -/// A pass's drawn depth/stencil resolve, planned before the pass records and recorded after it. -pub(super) struct DrawnResolve { - objects: PassObjects, - shaders: Shaders, - made: Pipelines, - set: vk::DescriptorSet, - /// The render area, from the origin. - area: [u32; 2], - uses: Vec>, -} - -impl DrawnResolve { - /// The draws of `layout`'s (its final layout) depth/stencil resolve whose aspects are picked - /// by depth (`ResolveMode::Picked`), into its first step's resolve attachment or its own; - /// `None` where it has none. - pub(super) fn plan( - device: &Device, - layout: &PassLayout, - ) -> Result, Error> { - let Some(ds) = layout.depth_stencil.as_ref() else { - return Ok(None); - }; - let Some(resolve) = ds.resolve.as_ref() else { - return Ok(None); - }; - let Some((pick, aspects)) = resolve.picked() else { - return Ok(None); - }; - let into = &resolve - .drawn_target() - .ok_or_else(|| internal("a drawn resolve without its attachment"))? - .attachment; - let source = &ds.target; - draws_run(device, source, into, pick, aspects)?; - let drawn = Drawn::of(aspects).ok_or_else(|| internal("a drawn resolve of no aspect"))?; - let (shaders, made) = device.resolve_draws(pick, drawn, source.samples, into.format)?; - let mut views = vec![(SET[0], aspect_view(source, ImageAspectFlags::DEPTH)?)]; - if drawn.stencil() { - views.push((SET[1], aspect_view(source, ImageAspectFlags::STENCIL)?)); - } - let (mut objects, set) = PassObjects::with_set(device, shaders.set_layout, &views)?; - draw_framebuffer(&mut objects, made.render_pass, into, layout.extent)?; - Ok(Some(DrawnResolve { - objects, - shaders, - made, - set, - area: layout.extent, - uses: vec![sampled_use(source)?, attachment_use(into)?], - })) - } - - /// Record the draws in `core`'s command buffer after the pass, between barriers from - /// everything before and to everything after, and hold their objects until the command - /// buffer completes. - pub(super) fn record(self, core: &mut EncoderCore) { - let DrawnResolve { - objects, - shaders, - made, - set, - area, - uses, - } = self; - let framebuffer = objects.framebuffer; - core.barrier(Barrier::everything()); - core.command(DRAW_STAGES, &uses, |device, raw| { - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // pipelines, framebuffer, set and the images they view are live until it completes - // (the device keeps the pipelines, these objects the framebuffer and set, the encoder - // the textures); every image rests in `GENERAL`. - unsafe { - record_draws( - device, - raw, - (made.render_pass, framebuffer), - (shaders.layout, set), - &made.pipelines, - area, - ); - } - }); - core.barrier(Barrier::everything()); - core.retain(objects); - } -} diff --git a/crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs b/crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs deleted file mode 100644 index 4ef5d089f..000000000 --- a/crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs +++ /dev/null @@ -1,1046 +0,0 @@ -//! Separate depth and stencil textures in one pass (step 6's second part). -//! -//! Metal renders a pass whose depth and stencil attachments are two textures: measured on an M4 -//! (macOS 27.0.1), `Depth32Float` with `Stencil8` and `Depth16Unorm` with `Stencil8` both test and -//! store each aspect in its own texture. A Vulkan subpass has one depth/stencil attachment, so such -//! a pass renders into a scratch image of the combined format whose depth aspect holds the depth -//! texture's bits: `D32_SFLOAT_S8_UINT` for 32-bit float depth, `D16_UNORM_S8_UINT` for 16-bit, -//! `D24_UNORM_S8_UINT` for 24-bit. Stencil is 8 bits in every format. -//! -//! - **Before the pass**, each aspect loaded with `Load` is copied from its texture into the -//! scratch image; `Clear` and `DontCare` load as the scratch's own operations. An aspect loaded -//! `DontCare` that the pass does not store, in a pass whose draws reach a tile, takes the answer -//! of any attachment so loaded (`clear_reach.rs`, `UnstoredDontCarePolicy`), each aspect apart: -//! the scratch's `Clear` to the aspect's clear value, Metal's answer (an M3 Max under macOS -//! 27.0.1, `runtime_lane::dont_care_unstored`), or its `DONT_CARE`, announced -//! `dont-care-unstored-load`. One the pass stores takes the single texture's answer too -//! (`clear_reach.rs`, measured alike on the M3 Max under macOS 27.0.1): its texels where the -//! draws reach no tile, else the clear value in the tiles the draws touch, where the pass -//! writes the aspect, and its texels in the rest. The scratch loads it by the copy in, and its -//! tiles are cleared after the copy; where it cannot be copied in ([`copies_in`]: a -//! multisampled aspect copied by draws) the scratch clears it over the render area, announced -//! `dont-care-load-tiles`. -//! - **After it**, each aspect stored with `Store`, `StoreAndMultisampleResolve` or -//! `CustomSampleDepthStore` is copied back (a resolve of the scratch image into the separate -//! resolve textures is `resolve.rs`'s split resolve). An aspect stored `DontCare` is not: its -//! texture keeps its texels, which is what Metal left in every case measured, so this is closer -//! to Metal than Vulkan's `DONT_CARE` on one attachment. -//! - **The copies** are bit-wise, in two steps, since Vulkan copies no image of one depth/stencil -//! format into another of a different one. A single-sampled aspect goes through a staging -//! buffer. A multisampled one goes through a multisampled colour image whose format matches the -//! aspect ([`colour_twin`]), with `vkCmdCopyImage` (equal sample counts), which maintenance8's -//! "Compatible Formats for Depth-Stencil to/from Color Copies" allows; Vulkan copies no -//! multisampled image to or from a buffer. They cover the render area, which the scratch image -//! is at least as large as. The render encoder's commands are unordered, so each direction's -//! copies take a barrier from everything before and one to everything after, and one between -//! their two steps. -//! - **Multisampled aspects without colour copies.** Where the device lacks maintenance8 or its -//! driver runs its depth-stencil/colour copies wrong -//! (`RuntimeDriverDefect::MultisampledDepthStencilColourCopies`), each aspect is copied by -//! sample-rate draws instead: the stencil by `stencil_copy.rs`'s plane draws, exact, and the -//! depth by `depth_copy.rs`'s `FragDepth` draw, where the device's fragment depth is measured -//! to store it unchanged (`depth_copy::copies_exactly`: a 32-bit float depth, and, a 16-bit one's -//! codes); a 32-bit float depth elsewhere, which the draw may change, as the announced -//! near-equivalent `drawn-depth-copy` (`depth_copy::drawn`: the values MoltenVK's and NVIDIA's -//! are measured to change, or those Vulkan leaves to a driver not measured). In, -//! from the texture's aspect, sampled, into the scratch image's (the depth first, then the -//! stencil); out, from the scratch image's, which is then made sampled, into the texture's. No -//! byte crosses between texels of different sizes. -//! - The scratch image is the pass's own, made with the encoder, and its command buffer holds it -//! until it completes. -//! - **Textures of different sizes**, which Metal's validation stops ("When both depth (8 x 8) and -//! stencil (4 x 4) are used from separate textures, they must have identical dimensions") and -//! plain Metal renders over the smaller (an M4 with macOS 27.0.1, one sample, -//! without draws; Metal probe `separate_sizes` on an M4, with one): the scratch image is the -//! smaller, the render area at most that, and its copies move the render area. Metal's clear of -//! the larger reaches past the render area to the end of its tiles, by 32 pixels a side for -//! `Depth32Float` and 16 for `Stencil8` (a 64x64 depth cleared at 0..31, a 64x64 stencil at -//! 0..15, an 8x8 depth whole, each beside a 4x4 texture; and 32 alike under 16x16 tiles). A -//! texture that ends inside those tiles, cleared and stored, is cleared whole before the copies -//! back (`cleared_whole`); one past them, of another format, or of more samples, unmeasured, is -//! `NotImplemented(Render)` (`check_sizes`). -//! - **A layered pass** (`renderTargetArrayLength` 2 or more) renders through a scratch image of -//! its layers, each texture's from its slice, and the copies move every layer; the copies' draws, -//! each of one layer, run once per layer. -//! -//! - **A resolve drawn after the pass** (`depth_stencil_resolve.rs`: a `Min` or `Max` depth on a -//! device without the mode) reads the scratch image's samples, so the image is sampled where -//! such a resolve may run and the device samples its format (`resolve::may_draw`). -//! -//! Refused: a device without the combined format as a depth/stencil attachment that copies both -//! ways (and, where the scratch image is read back by draws, is sampled), or, for multisampled -//! aspects copied through colour images, without a matching colour format it renders to and -//! copies both ways (`Unsupported`, naming the format); and, on a device without maintenance8 (`Unsupported`, -//! `Feature::SeparateMultisampledDepthStencil`, naming the feature) or whose driver copies a -//! multisampled depth/stencil image to or from a colour one wrong (the same feature, naming -//! `RuntimeDriverDefect::MultisampledDepthStencilColourCopies`, `driver_defects.rs`), a -//! multisampled depth that is loaded or may be stored where its draw is not measured (a driver -//! the fragment-depth probe of the depth's format has not measured), and a multisampled -//! aspect loaded from a texture that is not sampled. A device that lacks what the draws need -//! refuses the copies naming what it lacks. - -use super::blit::{reads, writes, TRANSFER}; -use super::buffer::Buffer; -use super::command_buffer::CommandBuffer; -use super::depth_copy::{self, DepthDraw, Drawn}; -use super::encoder::EncoderCore; -use super::error::{internal, Error, RuntimeGap}; -use super::image_plan::{sample_count, ImagePlan}; -use super::render_pass::{AspectClear, AspectTarget, Target}; -use super::render_values::{LoadAction, StoreAction}; -use super::resource::ResourceKey; -use super::sample_positions; -use super::stencil_copy::{self, StencilPlanes}; -use super::texture::{copy_units, ImageMaker, Texture}; -use super::texture_descriptor::TextureDescriptor; -use super::tracker::{Access, Barrier, Use}; -use super::values::ResourceOptions; -use super::Device; -use ash::vk; -use metal2vulkan::bind::CopySource; -use metal2vulkan::device::{DeviceProfile, FormatUsage, VkFeature}; -use metal2vulkan::error::{Capability, Feature, RuntimeDriverDefect, Unsupported}; -use metal2vulkan::metal::format::FormatMapping; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; -use metal2vulkan::vk::{ - Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags, -}; - -/// The depth and stencil textures of a pass that renders them through a scratch image: two -/// textures, or a stencil-only one alone at custom sample positions (no depth). -#[derive(Clone, Debug)] -pub(super) struct Separate { - pub(super) depth: Option, - pub(super) stencil: Target, -} - -impl Separate { - /// The textures the pass renders through the scratch image, the depth's first. - pub(super) fn targets(&self) -> impl Iterator { - self.depth.iter().chain(std::iter::once(&self.stencil)) - } -} - -/// The combined formats a stencil-only attachment's scratch image may take, in the order tried: -/// each with a depth aspect, so the flag custom sample positions need, and Metal's name for it. -const STENCIL_SCRATCH: [(Format, PixelFormat); 3] = [ - ( - Format::D32_SFLOAT_S8_UINT, - PixelFormat::Depth32FloatStencil8, - ), - (Format::D24_UNORM_S8_UINT, PixelFormat::Depth24UnormStencil8), - // Metal has no such format; nothing reads the scratch texture's pixel format. - (Format::D16_UNORM_S8_UINT, PixelFormat::Depth16Unorm), -]; - -/// The scratch format of a stencil-only attachment at custom sample positions (`samples`): the -/// first of [`STENCIL_SCRATCH`] the device renders and copies both ways (and samples, where -/// `sampled`), made with the custom-location flag at the count. Refused -/// `NotImplemented(SamplePositionsAtBegin)` where none is, as the pass was before. -fn stencil_scratch( - device: &Device, - samples: metal2vulkan::vk::SampleCountFlags, - sampled: bool, -) -> Result<(Format, PixelFormat), Error> { - let profile = device.compile_device().profile(); - let facts = device.shared().textures.facts(profile); - let mut needs = FormatFeatureFlags2::DEPTH_STENCIL_ATTACHMENT - | FormatFeatureFlags2::TRANSFER_SRC - | FormatFeatureFlags2::TRANSFER_DST; - if sampled { - needs |= FormatFeatureFlags2::SAMPLED_IMAGE; - } - STENCIL_SCRATCH - .into_iter() - .find(|&(format, _)| { - facts.optimal(format).contains(needs) - && sample_positions::compatible_depth(profile, format, samples) - .contains(ImageCreateFlags::SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_EXT) - }) - .ok_or(Error::NotImplemented(RuntimeGap::SamplePositionsAtBegin)) -} - -/// The combined format whose depth aspect holds the bits of `depth`'s depth aspect. -fn combined(depth: Format) -> Option { - match depth { - Format::D32_SFLOAT | Format::D32_SFLOAT_S8_UINT => Some(Format::D32_SFLOAT_S8_UINT), - Format::D16_UNORM | Format::D16_UNORM_S8_UINT => Some(Format::D16_UNORM_S8_UINT), - Format::X8_D24_UNORM_PACK32 | Format::D24_UNORM_S8_UINT => Some(Format::D24_UNORM_S8_UINT), - _ => None, - } -} - -/// Whether an aspect with this load and store action copies between its texture and the scratch -/// image: it is loaded with `Load`, or its store action stores the samples (an `Unknown` one may -/// still become `Store`; `MultisampleResolve` leaves them, its resolve copying from a scratch -/// image of its own, `resolve.rs`). -fn aspect_copies(load: LoadAction, store: StoreAction) -> bool { - load == LoadAction::Load || stores_samples(store) -} - -/// Whether an aspect stored with `store` is copied back from the scratch image: an action that -/// keeps the samples, or `Unknown`, which may still become one. -fn stores_samples(store: StoreAction) -> bool { - matches!( - store, - StoreAction::Store - | StoreAction::StoreAndMultisampleResolve - | StoreAction::CustomSampleDepthStore - | StoreAction::Unknown - ) -} - -/// `plan` with `SAMPLED` usage, where the copies without colour copies read its image: a -/// multisampled depth/stencil attachment, not transient and not yet sampled, of a format the -/// device samples, on a device whose colour copies cannot move its aspects -/// ([`colour_copies_refused`]). Its separate texture's aspects are then copied by draws, and its -/// shader-side stencil's shadow (`shadow_stencil.rs`) by the split and the planes, where it -/// would be refused unsampled. `Device::with_free_usage` gives the image the usage only where it -/// costs nothing. `None` otherwise. -pub(super) fn sampled_candidate(plan: &ImagePlan, device: &Device) -> Option { - let aspects = super::texture::image_aspects(plan.format); - let refused = - colour_copies_refused(device, Feature::SeparateMultisampledDepthStencil, aspects).is_some(); - sampled_candidate_on(plan, device.compile_device().profile(), refused) -} - -/// [`sampled_candidate`] on a device of `profile` whose colour copies cannot move a -/// multisampled aspect where `copies_refused`. -pub(super) fn sampled_candidate_on( - plan: &ImagePlan, - profile: &DeviceProfile, - copies_refused: bool, -) -> Option { - let usage = plan.usage; - let candidate = copies_refused - && plan.samples.as_raw() > 1 - && usage.contains(ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT) - && !usage.intersects(ImageUsageFlags::SAMPLED | ImageUsageFlags::TRANSIENT_ATTACHMENT) - && profile.supports_format(plan.format, FormatUsage::SampledImage); - candidate.then(|| ImagePlan { - usage: usage | ImageUsageFlags::SAMPLED, - ..plan.clone() - }) -} - -/// Why maintenance8's depth-stencil/colour copies cannot move the multisampled `aspects` on -/// `device`: it lacks maintenance8, or its driver runs them wrong (every aspect's, or, the -/// stencil's alone), refused naming `feature`. `None` where they can. -pub(super) fn colour_copies_refused( - device: &Device, - feature: Feature, - aspects: ImageAspectFlags, -) -> Option { - if !device.enabled().features.contains(&VkFeature::Maintenance8) { - return Some(Unsupported::needs( - feature, - Capability::Feature(VkFeature::Maintenance8), - )); - } - copies_defect(&device.properties().driver_defects, aspects) - .map(|defect| Unsupported::runtime_driver_defect(feature, defect)) -} - -/// The defect of a driver with `defects` that copies the multisampled `aspects` wrong through -/// maintenance8's depth-stencil/colour copies, if any: one that runs every aspect's wrong, or a -/// stencil's alone where `aspects` holds the stencil. -pub(super) fn copies_defect( - defects: &std::collections::BTreeSet, - aspects: ImageAspectFlags, -) -> Option { - let every = RuntimeDriverDefect::MultisampledDepthStencilColourCopies; - let stencil = RuntimeDriverDefect::MultisampledStencilColourCopies; - if defects.contains(&every) { - Some(every) - } else { - (aspects.contains(ImageAspectFlags::STENCIL) && defects.contains(&stencil)) - .then_some(stencil) - } -} - -/// The tile, in pixels a side, through which Metal clears and stores a separate texture of -/// `pixel_format` past the render area of a pass of `samples` (the module docs): measured at one -/// sample for `Depth32Float`, the tile every other attachment's clear reaches in -/// (`clear_reach::TILE`), and `Stencil8`, whose separate texture's is smaller. -fn clear_tile(pixel_format: PixelFormat, samples: u32) -> Option { - match (pixel_format, samples) { - (PixelFormat::Depth32Float, 1) => Some(super::clear_reach::TILE), - (PixelFormat::Stencil8, 1) => Some(16), - _ => None, - } -} - -/// Whether `target`, a separate texture of a pass of `samples` over the render area `extent`, -/// lies past the render area but inside the tiles Metal's clear reaches (the module docs). -pub(super) fn cleared_whole(target: &Target, extent: [u32; 2], samples: u32) -> bool { - let past = (0..2).any(|axis| target.extent[axis] > extent[axis]); - past && clear_tile(target.texture.pixel_format(), samples).is_some_and(|tile| { - (0..2).all(|axis| target.extent[axis] <= extent[axis].div_ceil(tile).saturating_mul(tile)) - }) -} - -/// `separate`'s textures of different sizes in a pass of `samples` over the render area -/// `extent`: each that lies past the render area must end inside the tiles Metal's clear reaches -/// (`cleared_whole`), else the pass is `NotImplemented(Render)` (the module docs). -pub(super) fn check_sizes( - separate: &Separate, - extent: [u32; 2], - samples: u32, -) -> Result<(), Error> { - let mut extents = separate.targets().map(|target| target.extent); - let first = extents.next(); - if extents.all(|extent| Some(extent) == first) { - return Ok(()); - } - for target in separate.targets() { - let past = (0..2).any(|axis| target.extent[axis] > extent[axis]); - if past && !cleared_whole(target, extent, samples) { - return Err(Error::NotImplemented(RuntimeGap::Render)); - } - } - Ok(()) -} - -/// Whether the multisampled `aspect` of a pass of `samples` is copied by draws -/// (`stencil_copy.rs`, `depth_copy.rs`) rather than through colour images: the colour copies -/// cannot move it ([`colour_copies_refused`]). -fn by_draws(device: &Device, samples: u32, aspect: ImageAspectFlags) -> bool { - samples > 1 - && colour_copies_refused(device, Feature::SeparateMultisampledDepthStencil, aspect) - .is_some() -} - -/// Whether each aspect of `separate` (depth, stencil) can load by a copy into the scratch image -/// that its load did not ask for: a `DontCare` load of an aspect the pass stores, which loads -/// the texture's texels and clears the tiles the draws touch (`clear_reach::dont_care_loads`). -/// A single-sampled aspect, and a multisampled one the colour copies move, which its copy back -/// already needs; not one copied by draws, whose copy in needs a sampled texture and draws the -/// store does not. -pub(super) fn copies_in(device: &Device, separate: &Separate) -> [bool; 2] { - let samples = separate.depth.as_ref().unwrap_or(&separate.stencil).samples; - [ImageAspectFlags::DEPTH, ImageAspectFlags::STENCIL] - .map(|aspect| samples == 1 || !by_draws(device, samples, aspect)) -} - -/// The scratch image `separate`'s pass renders into, as its depth/stencil target, whose depth and -/// stencil aspects load with `loads` and store with `stores`, and whose samples a resolve drawn -/// after the pass may read where `drawn` (`resolve::may_draw`). Refused as the module docs say. -pub(super) fn scratch( - maker: &CommandBuffer, - separate: &Separate, - loads: [LoadAction; 2], - stores: [StoreAction; 2], - drawn: bool, -) -> Result { - let device = maker.device(); - // The first texture: both have the pass's samples and layers, and the scratch image the - // smaller extent (textures of different sizes: the module docs). - let first = separate.depth.as_ref().unwrap_or(&separate.stencil); - let extent = separate.targets().fold(first.extent, |least, target| { - [ - least[0].min(target.extent[0]), - least[1].min(target.extent[1]), - ] - }); - let samples = first.samples; - let multisampled = samples > 1; - let samples_flag = sample_count(samples) - .ok_or_else(|| internal("an attachment of a sample count Vulkan lacks"))?; - let (format, pixel_format) = match &separate.depth { - Some(depth) => ( - combined(depth.format).ok_or_else(|| internal("a depth attachment without depth"))?, - depth.texture.pixel_format(), - ), - // A stencil-only texture at custom positions: its stencil, copied by draws, reads the - // scratch image back where it may store. - None => stencil_scratch( - device, - samples_flag, - by_draws(device, samples, ImageAspectFlags::STENCIL) - && stores[1] != StoreAction::DontCare, - )?, - }; - // The scratch image has the pass's layers (a layered pass's: added). - let layers = first.layers; - let feature = Feature::SeparateMultisampledDepthStencil; - let facts = device - .shared() - .textures - .facts(device.compile_device().profile()); - let lacks = |features: FormatFeatureFlags2, usage: FormatUsage| match facts - .optimal(format) - .contains(features) - { - true => Ok(()), - false => Err(Error::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { format, usage }, - ))), - }; - // The scratch image is an attachment the copies write, checked before a draw's objects are - // made for its format: a render pass of a format the device does not render to is invalid - // (lavapipe, RADV and ANV make no `D16_UNORM_S8_UINT` attachment). - lacks( - FormatFeatureFlags2::DEPTH_STENCIL_ATTACHMENT - | FormatFeatureFlags2::TRANSFER_SRC - | FormatFeatureFlags2::TRANSFER_DST, - FormatUsage::DepthStencilAttachment, - )?; - // Each aspect's copies through colour images where they move it, else by draws: in, from - // its texture, which is read, where it loads; out, from the scratch image, which is then - // read, where it may store. - let mut read_scratch = false; - let aspects = [ - (0, separate.depth.as_ref(), ImageAspectFlags::DEPTH), - (1, Some(&separate.stencil), ImageAspectFlags::STENCIL), - ]; - for (index, target, aspect) in aspects { - let Some(target) = target else { - continue; - }; - if !multisampled || !aspect_copies(loads[index], stores[index]) { - continue; - } - let Some(refused) = - colour_copies_refused(device, Feature::SeparateMultisampledDepthStencil, aspect) - else { - usable_twin(device, target, aspect)?; - continue; - }; - let is_depth = aspect == ImageAspectFlags::DEPTH; - // The depth's draw is exact only where its fragment depth is measured so; a 32-bit float - // depth runs it elsewhere as the announced near-equivalent, a 16-bit one not - // (`depth_copy::drawn`). - if is_depth && depth_copy::drawn(device, target.format).is_none() { - return Err(Error::Unsupported(refused)); - } - let draws_run = |destination: Format| { - if is_depth { - depth_copy::depth_draw_runs(device, destination, samples, &feature) - } else { - stencil_copy::plane_draws_run( - device, - CopySource::Aspect, - destination, - samples, - &feature, - ) - } - }; - if loads[index] == LoadAction::Load { - if !stencil_copy::sampled(target)? { - return Err(Error::Unsupported(refused)); - } - draws_run(format)?; - } - if stores_samples(stores[index]) { - draws_run(target.format)?; - read_scratch = true; - } - } - if read_scratch { - lacks( - FormatFeatureFlags2::SAMPLED_IMAGE, - FormatUsage::SampledImage, - )?; - } - // A resolve drawn after the pass reads the samples too, where the device samples the format; - // elsewhere that resolve is refused (`depth_stencil_resolve::draws_run`). - let sampled = read_scratch - || (drawn - && multisampled - && facts - .optimal(format) - .contains(FormatFeatureFlags2::SAMPLED_IMAGE)); - let samples = samples_flag; - let [width, height] = extent; - // The descriptor states the image's size and samples; its pixel format is the depth - // texture's, which nothing reads of an image only the pass uses (Metal has no format of - // some combined images, `D16_UNORM_S8_UINT` among them). - let descriptor = TextureDescriptor { - texture_type: match (first.samples > 1, layers > 1) { - (false, false) => TextureType::Type2D, - (false, true) => TextureType::Type2DArray, - (true, false) => TextureType::Type2DMultisample, - (true, true) => TextureType::Type2DMultisampleArray, - }, - pixel_format, - width: width.into(), - height: height.into(), - array_length: layers.into(), - sample_count: first.samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - ..TextureDescriptor::default() - }; - let plan = ImagePlan { - pixel_format: descriptor.pixel_format, - // The pass's depth/stencil attachment, made for its custom sample positions where the - // device takes them. - flags: sample_positions::compatible_depth( - device.compile_device().profile(), - format, - samples, - ), - image_type: ImageType::TYPE_2D, - format, - extent: [width, height, 1], - levels: 1, - layers, - samples, - usage: ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT - | ImageUsageFlags::TRANSFER_SRC - | ImageUsageFlags::TRANSFER_DST - | if sampled { - ImageUsageFlags::SAMPLED - } else { - ImageUsageFlags::empty() - }, - view_formats: Vec::new(), - mapping: FormatMapping::direct(format, ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL), - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - let texture = Device::new_planned_texture(maker, &descriptor, plan)?; - Ok(Target { - texture, - level: 0, - layer: 0, - layers, - format, - samples: first.samples, - extent, - }) -} - -/// The colour format whose texels hold the bits of `format`'s `aspect`, and Metal's name for it, -/// through which a multisampled aspect is copied: `R32_SFLOAT` for 32-bit and 24-bit depth, -/// `R16_UNORM` for 16-bit depth, `R8_UNORM` for stencil (maintenance8's "Compatible Formats for -/// Depth-Stencil to/from Color Copies"). Float and normalized formats, so the device's colour -/// sample counts govern them, not its narrower integer ones. -pub(super) fn colour_twin( - format: Format, - aspect: ImageAspectFlags, -) -> Option<(Format, PixelFormat)> { - let block = format.block()?; - if aspect == ImageAspectFlags::STENCIL { - return block - .stencil - .map(|_| (Format::R8_UNORM, PixelFormat::R8Unorm)); - } - block.depth?; - match format { - Format::D32_SFLOAT - | Format::D32_SFLOAT_S8_UINT - | Format::X8_D24_UNORM_PACK32 - | Format::D24_UNORM_S8_UINT => Some((Format::R32_SFLOAT, PixelFormat::R32Float)), - Format::D16_UNORM | Format::D16_UNORM_S8_UINT => { - Some((Format::R16_UNORM, PixelFormat::R16Unorm)) - } - _ => None, - } -} - -/// The colour twin of `target`'s `aspect` ([`colour_twin`]), checked: a colour attachment format -/// the device copies both ways. Refused, naming the format, where it is not. -fn usable_twin( - device: &Device, - target: &Target, - aspect: ImageAspectFlags, -) -> Result<(Format, PixelFormat), Error> { - let twin = colour_twin(target.format, aspect) - .ok_or_else(|| internal("a separate attachment without its aspect"))?; - let features = FormatFeatureFlags2::COLOR_ATTACHMENT - | FormatFeatureFlags2::TRANSFER_SRC - | FormatFeatureFlags2::TRANSFER_DST; - let facts = device - .shared() - .textures - .facts(device.compile_device().profile()); - if !facts.optimal(twin.0).contains(features) { - return Err(Error::Unsupported(Unsupported::needs( - Feature::Format, - Capability::Format { - format: twin.0, - usage: FormatUsage::ColorAttachment, - }, - ))); - } - Ok(twin) -} - -/// A multisampled colour image of `format` (Metal's `pixel_format`), `samples`, `extent` and -/// `layers`, which only the copies of a pass use: a colour attachment (so it may have more than -/// one sample) that copies both ways ([`usable_twin`]). Refused where the device does not make it -/// (a sample count its colour attachments of the format do not take). -pub(super) fn colour_image( - maker: &dyn ImageMaker, - (format, pixel_format): (Format, PixelFormat), - samples: u32, - [width, height]: [u32; 2], - layers: u32, -) -> Result { - let samples_flag = sample_count(samples) - .ok_or_else(|| internal("an attachment of a sample count Vulkan lacks"))?; - let descriptor = TextureDescriptor { - texture_type: if layers > 1 { - TextureType::Type2DMultisampleArray - } else { - TextureType::Type2DMultisample - }, - pixel_format, - width: width.into(), - height: height.into(), - array_length: layers.into(), - sample_count: samples.into(), - usage: TextureUsage::RENDER_TARGET, - resource_options: ResourceOptions::private(), - ..TextureDescriptor::default() - }; - let plan = ImagePlan { - pixel_format, - flags: ImageCreateFlags::empty(), - image_type: ImageType::TYPE_2D, - format, - extent: [width, height, 1], - levels: 1, - layers, - samples: samples_flag, - usage: ImageUsageFlags::COLOR_ATTACHMENT - | ImageUsageFlags::TRANSFER_SRC - | ImageUsageFlags::TRANSFER_DST, - view_formats: Vec::new(), - mapping: FormatMapping::direct(format, ImageAspectFlags::COLOR), - unavailable: TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::PIXEL_FORMAT_VIEW, - }; - Device::new_planned_texture(maker, &descriptor, plan) -} - -/// One step of an aspect's copy. -enum Step { - /// From an image into the staging buffer. - ToBuffer(vk::Image, vk::BufferImageCopy), - /// From the staging buffer into an image. - FromBuffer(vk::Image, vk::BufferImageCopy), - /// From one image into another of the same samples. - Image(vk::Image, vk::Image, vk::ImageCopy), - /// A clear of an image's aspect, a texture larger than the render area (`cleared_whole`). - Clear( - vk::Image, - vk::ClearDepthStencilValue, - vk::ImageSubresourceRange, - ), -} - -/// One direction of a pass's copies between its separate textures and its scratch image, over -/// the render area: into the scratch image before the pass, or back after it. -pub(super) struct ScratchCopy { - /// What the copies go through, held until the command buffer completes: a staging buffer - /// (single-sampled aspects) or multisampled colour images. - staging: Option, - colours: Vec, - /// Each aspect's first step, then its second, a barrier between. - first: Vec, - second: Vec, - /// A multisampled depth the colour copies cannot move: its draw of each layer, each after a - /// barrier. - depth: Vec, - /// A multisampled stencil the colour copies cannot move: its plane draws of each layer, each - /// after a barrier (and after the depth's draws). - planes: Vec, - uses: Vec>, - /// The values the depth's draws change or may change, where the driver's fragment depth is - /// not measured to keep every value (`depth_copy::Drawn::Changes`), and the depth texture's - /// pixel format: the copy announces `drawn-depth-copy` as it is recorded. - inexact_depth: Option<(&'static str, PixelFormat)>, -} - -impl ScratchCopy { - /// The copies of `separate`'s aspects into `scratch` (`into_scratch`, the aspects - /// `depth` and `stencil` load with `Load`) or back (the ones they store with `Store`), over - /// the render area `extent`; `None` when no aspect asks for one. - pub(super) fn plan( - maker: &CommandBuffer, - separate: &Separate, - scratch: &Target, - actions: [Option<&AspectTarget>; 2], - extent: [u32; 2], - into_scratch: bool, - ) -> Result, Error> { - let device = maker.device(); - let aspects = [ - (separate.depth.as_ref(), actions[0], ImageAspectFlags::DEPTH), - ( - Some(&separate.stencil), - actions[1], - ImageAspectFlags::STENCIL, - ), - ]; - let actions: Vec<_> = aspects - .into_iter() - .filter_map(|(texture, action, aspect)| Some((texture?, action?, aspect))) - .filter(|(_, action, _)| { - // `StoreAndMultisampleResolve` keeps the samples too, and - // `CustomSampleDepthStore` stores a depth as `Store` does. - if into_scratch { - action.load == LoadAction::Load - } else { - matches!( - action.store, - StoreAction::Store - | StoreAction::StoreAndMultisampleResolve - | StoreAction::CustomSampleDepthStore - ) - } - }) - .collect(); - let wanted: Vec<_> = actions - .iter() - .map(|&(texture, _, aspect)| (texture, aspect)) - .collect(); - if wanted.is_empty() { - return Ok(None); - } - let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); - let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); - // Every layer of the pass's (the scratch image's), each texture's from its slice. - let count = scratch.layers; - let at = |target: &Target| target.level..target.level + 1; - let on = |target: &Target| target.layer..target.layer + count; - let layers = |target: &Target, aspect: ImageAspectFlags| vk::ImageSubresourceLayers { - aspect_mask: aspect.into(), - mip_level: target.level, - base_array_layer: target.layer, - layer_count: count, - }; - let [width, height] = extent; - let size = vk::Extent3D { - width, - height, - depth: 1, - }; - let mut uses = Vec::new(); - let (mut first, mut second) = (Vec::new(), Vec::new()); - if scratch.samples == 1 { - let texels = u64::from(width) * u64::from(height); - let mut length = 0u64; - let mut offsets = Vec::new(); - for &(texture, aspect) in &wanted { - let bytes = copy_units(texture.format, texture.texture.pixel_format()) - .into_iter() - .find(|unit| unit.0 == aspect) - .map(|unit| u64::from(unit.1)) - .ok_or_else(|| internal("a separate attachment without its aspect"))?; - // A depth/stencil copy's buffer offset is a multiple of 4; its layers lie one - // after another. - let offset = length.next_multiple_of(4); - length = offset + bytes * texels * u64::from(count); - offsets.push(offset); - } - let staging = device.own_buffer(length, ResourceOptions::private())?; - uses.push(writes(&staging, 0..length)); - uses.push(reads(&staging, 0..length)); - // A texture larger than the render area, cleared and stored, inside the tiles - // Metal's clear reaches, is cleared whole before its copy back (the module docs). - for &(texture, action, aspect) in &actions { - if into_scratch - || action.load != LoadAction::Clear - || !cleared_whole(texture, extent, scratch.samples) - { - continue; - } - let value = match action.clear { - AspectClear::Depth(depth) => vk::ClearDepthStencilValue { depth, stencil: 0 }, - AspectClear::Stencil(stencil) => vk::ClearDepthStencilValue { - depth: 0.0, - stencil, - }, - }; - let range = vk::ImageSubresourceRange { - aspect_mask: aspect.into(), - base_mip_level: texture.level, - level_count: 1, - base_array_layer: texture.layer, - layer_count: count, - }; - first.push(Step::Clear(texture.texture.raw_image()?, value, range)); - } - for (&(texture, aspect), offset) in wanted.iter().zip(offsets) { - let region = |target: &Target| vk::BufferImageCopy { - buffer_offset: staging.at(offset).1, - buffer_row_length: 0, - buffer_image_height: 0, - image_subresource: layers(target, aspect), - image_offset: vk::Offset3D::default(), - image_extent: size, - }; - let (from, to) = if into_scratch { - (texture, scratch) - } else { - (scratch, texture) - }; - uses.push(from.texture.image_use(at(from), on(from), read, false)?); - uses.push(to.texture.image_use(at(to), on(to), write, true)?); - first.push(Step::ToBuffer(from.texture.raw_image()?, region(from))); - second.push(Step::FromBuffer(to.texture.raw_image()?, region(to))); - } - return Ok(Some(ScratchCopy { - staging: Some(staging), - colours: Vec::new(), - first, - second, - depth: Vec::new(), - planes: Vec::new(), - uses, - inexact_depth: None, - })); - } - let mut colours = Vec::new(); - let (mut depth, mut planes) = (Vec::new(), Vec::new()); - let mut inexact_depth = None; - for &(texture, aspect) in &wanted { - let by_draws = by_draws(device, scratch.samples, aspect); - let (from, to) = if into_scratch { - (texture, scratch) - } else { - (scratch, texture) - }; - if by_draws { - let feature = Feature::SeparateMultisampledDepthStencil; - if aspect == ImageAspectFlags::DEPTH { - match depth_copy::drawn(device, texture.format) { - Some(Drawn::Exact) => {} - Some(Drawn::Changes(changes)) => { - inexact_depth = Some((changes, texture.texture.pixel_format())) - } - None => { - return Err(internal( - "a multisampled depth copy its draw does not copy at all", - )) - } - } - } - // The draws are of one layer: each layer of the pass's its own, from each - // target's first. - for i in 0..count { - let layer = |target: &Target| Target { - layer: target.layer + i, - layers: 1, - ..target.clone() - }; - let (from, to) = (layer(from), layer(to)); - uses.push(stencil_copy::sampled_use(&from)?); - uses.push(stencil_copy::attachment_use(&to)?); - if aspect == ImageAspectFlags::DEPTH { - depth.push(DepthDraw::new(device, &from, &to, extent, &feature)?); - } else { - planes.push(StencilPlanes::from_aspect( - device, &from, &to, extent, &feature, - )?); - } - } - continue; - } - let twin = usable_twin(device, texture, aspect)?; - let colour = colour_image(maker, twin, scratch.samples, extent, count)?; - let colour_target = Target { - texture: colour.clone(), - level: 0, - layer: 0, - layers: count, - format: twin.0, - samples: scratch.samples, - extent, - }; - let copy = |src: &Target, src_aspect, dst: &Target, dst_aspect| vk::ImageCopy { - src_subresource: layers(src, src_aspect), - src_offset: vk::Offset3D::default(), - dst_subresource: layers(dst, dst_aspect), - dst_offset: vk::Offset3D::default(), - extent: size, - }; - uses.push(from.texture.image_use(at(from), on(from), read, false)?); - uses.push(colour.image_use(0..1, 0..count, write, true)?); - uses.push(colour.image_use(0..1, 0..count, read, false)?); - uses.push(to.texture.image_use(at(to), on(to), write, true)?); - let colour_raw = colour.raw_image()?; - first.push(Step::Image( - from.texture.raw_image()?, - colour_raw, - copy(from, aspect, &colour_target, ImageAspectFlags::COLOR), - )); - second.push(Step::Image( - colour_raw, - to.texture.raw_image()?, - copy(&colour_target, ImageAspectFlags::COLOR, to, aspect), - )); - colours.push(colour); - } - Ok(Some(ScratchCopy { - staging: None, - colours, - first, - second, - depth, - planes, - uses, - inexact_depth, - })) - } - - /// Record the copies in `core`'s command buffer, between barriers from everything before and - /// to everything after, and hold what they go through until the command buffer completes. - pub(super) fn record(self, core: &mut EncoderCore) { - let ScratchCopy { - staging, - colours, - first, - second, - depth, - planes, - uses, - inexact_depth, - } = self; - if let Some((changes, format)) = inexact_depth { - depth_copy::announce_changes(core.device(), changes, || { - format!( - "a render pass's separate multisampled {format:?} depth texture, copied to \ - and from its scratch image" - ) - }); - } - let stages = if !depth.is_empty() || !planes.is_empty() { - TRANSFER | stencil_copy::DRAW_STAGES - } else { - TRANSFER - }; - // A multisampled pass's copies take no buffer. - let buffer = staging - .as_ref() - .map_or(vk::Buffer::null(), |staging| staging.at(0).0); - core.barrier(Barrier::everything()); - core.command(stages, &uses, |device, raw| { - let general = vk::ImageLayout::GENERAL; - let step = |step: &Step| match step { - // SAFETY: the encoder's command buffer is recording outside a render pass; the - // images and the staging buffer are live until it completes (the encoder retains - // the textures, and this what the copies go through); every image rests in - // `GENERAL`; each region lies in its images and in the buffer, and an image copy's - // images have one sample count and formats of one size whose aspects - // maintenance8 lets it copy (planned above). - Step::ToBuffer(image, region) => unsafe { - device.cmd_copy_image_to_buffer(raw, *image, general, buffer, &[*region]) - }, - // SAFETY: as above. - Step::FromBuffer(image, region) => unsafe { - device.cmd_copy_buffer_to_image(raw, buffer, *image, general, &[*region]) - }, - // SAFETY: as above. - Step::Image(from, to, region) => unsafe { - device.cmd_copy_image(raw, *from, general, *to, general, &[*region]) - }, - // SAFETY: as above; the range is the texture's level and the pass's layers, and - // its image takes transfer writes (its copy back is one). - Step::Clear(image, value, range) => unsafe { - device.cmd_clear_depth_stencil_image(raw, *image, general, value, &[*range]) - }, - }; - first.iter().for_each(step); - // SAFETY: the encoder's command buffer, of this device, is recording, and only this - // encoder records it. - unsafe { Barrier::everything().record(device, raw) }; - second.iter().for_each(step); - // SAFETY: as above; the draws' sources and destinations and their objects are live - // until the command buffer completes (the encoder retains the textures, and this the - // draws' objects). - unsafe { - for depth in &depth { - Barrier::everything().record(device, raw); - depth.record(device, raw); - } - for planes in &planes { - Barrier::everything().record(device, raw); - planes.record(device, raw); - } - } - }); - core.barrier(Barrier::everything()); - core.retain(staging); - core.retain(colours); - core.retain(depth); - core.retain(planes); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Each depth format's combined format holds its depth bits; a format without depth has none. - #[test] - fn combined_formats_keep_the_depth_bits() { - assert_eq!( - combined(Format::D32_SFLOAT), - Some(Format::D32_SFLOAT_S8_UINT) - ); - assert_eq!( - combined(Format::D32_SFLOAT_S8_UINT), - Some(Format::D32_SFLOAT_S8_UINT) - ); - assert_eq!(combined(Format::D16_UNORM), Some(Format::D16_UNORM_S8_UINT)); - assert_eq!( - combined(Format::D24_UNORM_S8_UINT), - Some(Format::D24_UNORM_S8_UINT) - ); - assert_eq!(combined(Format::S8_UINT), None); - } - - /// Each aspect's colour twin is Metal's format of the Vulkan one, one of the aspect's bits - /// (maintenance8's table); an aspect the format lacks has none. - #[test] - fn colour_twins_hold_each_aspects_bits() { - use metal2vulkan::metal::format::direct_format; - let (depth, stencil) = (ImageAspectFlags::DEPTH, ImageAspectFlags::STENCIL); - for (format, aspect, twin) in [ - (Format::D32_SFLOAT, depth, Format::R32_SFLOAT), - (Format::D32_SFLOAT_S8_UINT, depth, Format::R32_SFLOAT), - (Format::D32_SFLOAT_S8_UINT, stencil, Format::R8_UNORM), - (Format::D24_UNORM_S8_UINT, depth, Format::R32_SFLOAT), - (Format::D24_UNORM_S8_UINT, stencil, Format::R8_UNORM), - (Format::X8_D24_UNORM_PACK32, depth, Format::R32_SFLOAT), - (Format::D16_UNORM, depth, Format::R16_UNORM), - (Format::D16_UNORM_S8_UINT, depth, Format::R16_UNORM), - (Format::D16_UNORM_S8_UINT, stencil, Format::R8_UNORM), - (Format::S8_UINT, stencil, Format::R8_UNORM), - ] { - let (vk, metal) = colour_twin(format, aspect).expect("a twin"); - assert_eq!(vk, twin, "{format:?} {aspect:?}"); - assert_eq!(direct_format(metal), Some(twin), "{format:?} {aspect:?}"); - } - assert_eq!(colour_twin(Format::S8_UINT, depth), None); - assert_eq!(colour_twin(Format::D32_SFLOAT, stencil), None); - assert_eq!(colour_twin(Format::R32_SFLOAT, depth), None); - } - - /// An aspect copies when it loads, or may store. - #[test] - fn copies_follow_the_actions() { - use LoadAction::{Clear, DontCare as NoLoad, Load}; - use StoreAction::{DontCare, Store, Unknown}; - assert!(!aspect_copies(Clear, DontCare)); - assert!(!aspect_copies(NoLoad, DontCare)); - assert!(aspect_copies(Load, DontCare)); - assert!(aspect_copies(Clear, Store)); - assert!(aspect_copies(Clear, Unknown)); - assert!(!aspect_copies(Clear, StoreAction::MultisampleResolve)); - assert!(aspect_copies( - Clear, - StoreAction::StoreAndMultisampleResolve - )); - } -} diff --git a/crates/metal2vulkan-runtime/src/derived.rs b/crates/metal2vulkan-runtime/src/derived.rs deleted file mode 100644 index 739e74485..000000000 --- a/crates/metal2vulkan-runtime/src/derived.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! A derivation an object holds once, and the count that holds it to once. -//! -//! A Metal object answers a getter from what it already made. Several of ours answer from a -//! derivation over the object's inputs -- a decode of a function's AIR, a reflection over its -//! bindings -- and a getter that derives per call pays the whole of it per call, where Metal pays -//! nothing. Where every input of a derivation is fixed when the object is made, the object holds -//! the answer and derives it once: [`Derived`] for one answer, [`DerivedMap`] for one per key. -//! -//! # Why each memo counts its derivations -//! -//! A memo is proven by a **count**, never by a time. However many getters read a derivation and -//! however often, the object must derive it once, which is a fact of the structure and holds on -//! any host under any load; a ratio against Metal is a measurement of two machines and moves with -//! both. So every memo here counts the derivations that ran, and one table-driven test reads the -//! count for a list of getters (`tests::derived_once`). A getter added to an object joins that -//! list as a row. -//! -//! The count is of this object alone and of nothing that ran before it in the process: it needs no -//! quiet host, no warm cache and no ordering between tests. - -use crate::device::lock; -use std::collections::BTreeMap; -use std::sync::Mutex; - -/// One derivation an object holds, with how many times it has been derived. -/// -/// `Default` is "not derived yet", which is what an object is made with: making an object derives -/// nothing, as making Metal's does not. -#[derive(Debug)] -pub(crate) struct Derived { - held: Option, - derived: u32, -} - -impl Default for Derived { - fn default() -> Derived { - Derived { - held: None, - derived: 0, - } - } -} - -impl Derived { - /// The held answer, else `derive`'s, kept. - /// - /// `derive` runs with no lock held, so a slow derivation blocks no other reader; two readers - /// that race both derive and the first to finish is kept, which answers both the same value - /// and is why the count is of derivations that **ran**. A refusal is not kept: a derivation - /// refused under a fixed budget refuses the same way again, so the error path is left exactly - /// as it was without a memo. - pub(crate) fn or_derive( - memo: &Mutex>, - derive: impl FnOnce() -> Result, - ) -> Result { - if let Some(held) = lock(memo).held.clone() { - return Ok(held); - } - let made = derive()?; - let mut memo = lock(memo); - memo.derived += 1; - Ok(memo.held.get_or_insert(made).clone()) - } - - /// How many times the answer has been derived: 1 however many getters have read it. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn derived(memo: &Mutex>) -> u32 { - lock(memo).derived - } -} - -/// One derivation an object holds per key -- an argument buffer's index, a function's name -- with -/// how many times it has derived any of them. [`Derived`]'s rules, per key. -#[derive(Debug)] -pub(crate) struct DerivedMap { - held: BTreeMap, - derived: u32, -} - -impl Default for DerivedMap { - fn default() -> DerivedMap { - DerivedMap { - held: BTreeMap::new(), - derived: 0, - } - } -} - -impl DerivedMap { - /// The answer held for `key`, else `derive`'s, kept under it. - pub(crate) fn or_derive( - memo: &Mutex>, - key: K, - derive: impl FnOnce() -> Result, - ) -> Result { - if let Some(held) = lock(memo).held.get(&key).cloned() { - return Ok(held); - } - let made = derive()?; - let mut memo = lock(memo); - memo.derived += 1; - Ok(memo.held.entry(key).or_insert(made).clone()) - } - - /// How many times an answer has been derived, over every key: one per key read, however many - /// getters read each. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn derived(memo: &Mutex>) -> u32 { - lock(memo).derived - } -} diff --git a/crates/metal2vulkan-runtime/src/descriptor_arena.rs b/crates/metal2vulkan-runtime/src/descriptor_arena.rs deleted file mode 100644 index e0afbf4e3..000000000 --- a/crates/metal2vulkan-runtime/src/descriptor_arena.rs +++ /dev/null @@ -1,410 +0,0 @@ -//! A command buffer's descriptor pools: the set-0 set of each dispatch, draw and tile dispatch it -//! encodes comes from them (but one's that pushes its set 0, `pipeline::objects:: -//! pushes_set_zero`), and they go when the command buffer completes, with its uploads and heap -//! sets (`heap_sets.rs` keeps set 1, one per variant). -//! -//! Before, each such command made a `VkDescriptorPool` of its own, which its command buffer -//! released as it completed: on RADV, ANV and NVIDIA a pool is device memory of its own, so a -//! pool per command cost more than the rest of its encoding (2000 dispatches in -//! one command buffer took 14.5 to 17.8 us each to encode on a Radeon 780M). -//! -//! - **Sizing.** A pool holds [`FIRST`] sets of the needs (descriptor counts by type, and pool -//! flags) of the allocation that opened it in a command buffer's first pool, and twice as many -//! in each pool the command buffer opens after, up to [`MOST`] sets, and never more than -//! [`MOST_DESCRIPTORS`] descriptors unless one set needs them. So a command buffer of `n` -//! commands of one variant opens about `log2(n / FIRST)` pools, and one of a single command one -//! pool, as before. -//! - **Room is counted, not tried.** Each pool counts the sets and the descriptors of each type it -//! has left; an allocation takes the newest pool with room for all of its needs, so no -//! allocation relies on `VK_ERROR_OUT_OF_POOL_MEMORY`. A set is never freed alone (no -//! `FREE_DESCRIPTOR_SET`): a refused command's set stays allocated until its pool goes. -//! - **Spares**. A pool to open is a spare of the device's, reset, where one has room for the set -//! (`spares.rs`), whatever the size it was made with; a command buffer that completed gives its -//! pools back to the device's spares, and one that failed or was dropped unsubmitted releases -//! them. -//! - **Fitted arenas.** The sets of the runtime's own kernels (`owned_kernel.rs`) come from an -//! arena of their own, which a command buffer or a resource holds as long as it holds the sets -//! and then gives back. It takes and gives back spares of a list of the fitted arenas' own -//! (`spares.rs`), which a command buffer's arena never takes, and only a spare that holds no -//! more descriptors than the pool it would open ([`DescriptorArena::fitted`]), so a texture that -//! holds its sets for its life holds no larger pool than its own. - -use super::binding::{SetCache, Write}; -use super::device::lock; -use super::error::{vulkan, Error}; -use super::spares::{release_in_section, DescriptorPool}; -use super::Device; -use ash::vk; -use std::sync::{Arc, Mutex}; - -/// The sets of a command buffer's first pool. -pub(super) const FIRST: u32 = 16; - -/// The most sets a pool is opened for. -pub(super) const MOST: u32 = 1024; - -/// The most descriptors a pool is opened for, unless one set needs more. -pub(super) const MOST_DESCRIPTORS: u64 = 1 << 16; - -/// What one set of a layout takes from a pool: its descriptors by type (each binding's whole -/// count) and the pool flags its layout needs. -#[derive(Clone, Default, PartialEq, Eq)] -pub(super) struct SetNeeds { - /// By raw descriptor type, ascending, each count above 0. - pub(super) counts: Vec<(i32, u32)>, - pub(super) flags: vk::DescriptorPoolCreateFlags, -} - -impl SetNeeds { - /// Whether the set takes nothing from a pool (a layout of no descriptors): no set is made. - pub(super) fn is_empty(&self) -> bool { - self.counts.is_empty() - } - - /// The pool sizes of `sets` such sets. - pub(super) fn sizes(&self, sets: u32) -> Vec { - self.counts - .iter() - .map(|&(ty, count)| { - vk::DescriptorPoolSize::default() - .ty(vk::DescriptorType::from_raw(ty)) - .descriptor_count(count.saturating_mul(sets)) - }) - .collect() - } - - /// The descriptors one set takes, of every type. - fn descriptors(&self) -> u64 { - self.counts.iter().map(|&(_, count)| u64::from(count)).sum() - } - - /// The descriptors a pool of `sets` such sets holds, of every type: [`Room::of`]'s - /// [`Room::descriptors`], counted without the room's list. - pub(super) fn pool_descriptors(&self, sets: u32) -> u64 { - (self.counts.iter()) - .map(|&(_, count)| u64::from(count.saturating_mul(sets))) - .sum() - } -} - -/// What a pool has left: its sets and descriptors by type, and its flags (`Book`'s pure part). -#[derive(Clone, PartialEq, Eq)] -pub(super) struct Room { - pub(super) flags: vk::DescriptorPoolCreateFlags, - pub(super) sets: u32, - /// By raw descriptor type, ascending. - pub(super) counts: Vec<(i32, u32)>, -} - -impl Room { - /// The room of a pool of `sets` sets of `needs`. - pub(super) fn of(needs: &SetNeeds, sets: u32) -> Room { - Room { - flags: needs.flags, - sets, - counts: needs - .counts - .iter() - .map(|&(ty, count)| (ty, count.saturating_mul(sets))) - .collect(), - } - } - - /// Whether one set of `needs` fits. - pub(super) fn fits(&self, needs: &SetNeeds) -> bool { - self.flags == needs.flags - && self.sets > 0 - && needs.counts.iter().all(|&(ty, count)| { - self.counts - .iter() - .any(|&(left_ty, left)| left_ty == ty && left >= count) - }) - } - - /// The descriptors left, of every type. - pub(super) fn descriptors(&self) -> u64 { - self.counts.iter().map(|&(_, count)| u64::from(count)).sum() - } - - /// Take one set of `needs`, which fits. - fn take(&mut self, needs: &SetNeeds) { - self.sets -= 1; - for &(ty, count) in &needs.counts { - if let Some((_, left)) = self.counts.iter_mut().find(|(left_ty, _)| *left_ty == ty) { - *left -= count; - } - } - } -} - -/// The pools' rooms, in opening order: which pool an allocation takes, and the size of a pool -/// it opens. -#[derive(Default)] -pub(super) struct Book { - pub(super) rooms: Vec, -} - -impl Book { - /// The pool one set of `needs` comes from: `Ok(index)` of the newest with room, or - /// `Err(sets)`, the sets of the pool to open for it (which [`Book::opened`] then records). - pub(super) fn place(&self, needs: &SetNeeds) -> Result { - match self.rooms.iter().rposition(|room| room.fits(needs)) { - Some(at) => Ok(at), - None => { - // `FIRST << 16` is past `MOST`, and far from overflowing. - let opened = self.rooms.len().min(16) as u32; - let doubled = (u64::from(FIRST) << opened).min(u64::from(MOST)); - let by_descriptors = MOST_DESCRIPTORS / needs.descriptors().max(1); - let sets = doubled.min(by_descriptors).max(1); - // At most `MOST`, so it fits. - Err(sets as u32) - } - } - } - - /// A pool of `room` was opened, last. - pub(super) fn opened(&mut self, room: Room) { - self.rooms.push(room); - } - - /// One set of `needs` was allocated from pool `at`, which [`Book::place`] gave. - pub(super) fn take(&mut self, at: usize, needs: &SetNeeds) { - self.rooms[at].take(needs); - } -} - -/// A command buffer's pools ([`Book`] and the pools, in the same order), with the device they -/// are of once the first is opened. -#[derive(Default)] -pub(crate) struct DescriptorArena { - book: Book, - pools: Vec, - device: Option, - /// Whether it takes only spares no larger than the pools it opens (the module docs). - fitted: bool, - /// The sets 0 of its pools the command buffer's recorded commands wrote, by what they hold - /// (`binding::SetCache`), from its first command that looks one up: forgotten as the pools - /// go. Boxed, so a fitted arena, which keeps none, stays small. - sets: Option>, - /// Whether its command buffer is committed, from which point it keeps and serves no set of - /// its own ([`shut`](Self::shut)): the cache's exactness rests on a hold the commit lets go - /// of. - shut: bool, - /// The arena of a predicated loop's check, lent while it records a run again - /// (`command_buffer/rerun.rs`): every set is allocated from it, and kept there, meanwhile, - /// and its pools are reset once that run completed ([`reset`](Self::reset)). - lent: Option>>, -} - -impl DescriptorArena { - /// An arena that takes a spare only where the spare holds no more descriptors than the pool - /// it would open for the set (the module docs). - pub(crate) fn fitted() -> DescriptorArena { - DescriptorArena { - book: Book::default(), - pools: Vec::new(), - device: None, - fitted: true, - sets: None, - shut: false, - lent: None, - } - } - - /// Allocate every set from `lent`, a predicated loop's check's arena, and keep it there, - /// while it is lent; `None`: from this one again. - pub(crate) fn lend(&mut self, lent: Option>>) { - self.lent = lent; - } - - /// One set of `layout`, whose needs are `needs` (not empty), from the newest pool with room - /// for it, or a pool opened for it: a spare of the device's with room, else a new one. - pub(crate) fn allocate( - &mut self, - device: &Device, - layout: vk::DescriptorSetLayout, - needs: &SetNeeds, - ) -> Result { - if let Some(lent) = &self.lent { - return lock(lent).allocate(device, layout, needs); - } - let raw = device.shared().vk(); - let at = match self.book.place(needs) { - Ok(at) => at, - Err(sets) => { - let shared = device.shared(); - let most = self.fitted.then(|| needs.pool_descriptors(sets)); - let pool = match shared.spares.descriptor_pool(shared, needs, most)? { - Some(spare) => spare, - None => { - let sizes = needs.sizes(sets); - let info = vk::DescriptorPoolCreateInfo::default() - .flags(needs.flags) - .max_sets(sets) - .pool_sizes(&sizes); - // SAFETY: `info` is live for the call. - let raw_pool = - unsafe { raw.create_descriptor_pool(&info, None) }.map_err(vulkan)?; - shared.counts.arena_pool_made(); - DescriptorPool { - raw: raw_pool, - room: Room::of(needs, sets), - } - } - }; - self.book.opened(pool.room.clone()); - self.pools.push(pool); - self.device.get_or_insert_with(|| device.clone()); - self.pools.len() - 1 - } - }; - let layouts = [layout]; - let info = vk::DescriptorSetAllocateInfo::default() - .descriptor_pool(self.pools[at].raw) - .set_layouts(&layouts); - // The set straight into a local: `ash`'s wrapper collects it into a `Vec`. - let mut set = vk::DescriptorSet::null(); - // SAFETY: the pool has room for the set (counted); its sets go with it. `info` names one - // layout, so the driver writes one set. - unsafe { (raw.fp_v1_0().allocate_descriptor_sets)(raw.handle(), &info, &mut set) } - .result() - .map_err(vulkan)?; - self.book.take(at, needs); - Ok(set) - } - - /// The set 0 of `layout` holding `writes` that one of the command buffer's recorded commands - /// wrote (`binding::SetCache::find`): of its own pools, or of the arena lent, which its own - /// outlive. None of its own once it is [`shut`](Self::shut). - pub(crate) fn find( - &mut self, - layout: vk::DescriptorSetLayout, - writes: &[Write], - ) -> Option { - let own = match self.shut { - true => None, - false => (self.sets.as_mut()).and_then(|sets| sets.find(layout, writes)), - }; - match &self.lent { - Some(lent) if own.is_none() => lock(lent).find(layout, writes), - _ => own, - } - } - - /// Keep `set`, of `layout`, written with `writes`, once its command recorded - /// (`binding::SetCache::keep`): in the arena lent where one is, whose pools it came from. - /// Kept in none of its own once it is [`shut`](Self::shut). - pub(crate) fn keep( - &mut self, - layout: vk::DescriptorSetLayout, - set: vk::DescriptorSet, - writes: &[Write], - ) { - match (&self.lent, self.shut) { - (Some(lent), _) => lock(lent).keep(layout, set, writes), - (None, false) => self.sets.get_or_insert_default().keep(layout, set, writes), - (None, true) => {} - } - } - - /// Forget the sets 0 its command buffer's commands wrote, and keep and serve none of its own - /// again: its command buffer is committed, so from here it holds what its commands took only - /// weakly (`command_buffer/mod.rs`) and the cache's second invariant -- no object a kept - /// set's handles name can go, nor another take its handle (`binding::SetCache`) -- no longer - /// holds. A rebind frees the import a kept set was written for and then records the commands - /// over the new one in the same call (`buffer_descriptor.rs`, `command_buffer/reencode.rs`), - /// and the new import's `VkBuffer` may take the freed one's handle, which with its offset and - /// range is all the cache compares; so every command recorded from the commit on -- an - /// encoder encoded again, a host step's -- allocates and writes its own set. Shut for good: - /// a command recorded again keeps no set either, or the next rebind would find that one - /// stale. Its pools are untouched; the sets already bound by commands recorded before the - /// commit stay theirs. - pub(crate) fn shut(&mut self) { - self.shut = true; - self.sets = None; - } - - /// How many pools it holds (a device test's measure). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn pools(&self) -> usize { - self.pools.len() - } - - /// Reset every pool, for the sets of the commands recorded next: no command uses their sets - /// any more (the run again of a predicated loop's check completed, `command_buffer/rerun.rs`). - /// Inside a section of the exit guard. Refused as `vkResetDescriptorPool` refuses, the pools - /// then released. - pub(crate) fn reset(&mut self) -> Result<(), Error> { - self.sets = None; - let Some(device) = &self.device else { - return Ok(()); - }; - let raw = device.shared().vk(); - for pool in &self.pools { - // SAFETY: no pending command uses the pool's sets (the caller's), and only this arena - // holds it. - let reset = unsafe { - raw.reset_descriptor_pool(pool.raw, vk::DescriptorPoolResetFlags::empty()) - }; - if let Err(error) = reset { - self.release(); - return Err(vulkan(error)); - } - } - self.book.rooms = self.pools.iter().map(|pool| pool.room.clone()).collect(); - Ok(()) - } - - /// Every pool, taken out, for the caller to give back or release where it holds no lock: to - /// the spares' list the arena takes from (fitted or not). - pub(crate) fn take(&mut self) -> DescriptorArena { - self.book.rooms.clear(); - self.sets = None; - DescriptorArena { - book: Book::default(), - pools: std::mem::take(&mut self.pools), - device: self.device.clone(), - fitted: self.fitted, - sets: None, - shut: self.shut, - lent: None, - } - } - - /// Give every pool to the device's spares: the command buffer completed, so no command uses - /// their sets any more. - pub(crate) fn give_back(&mut self) { - self.book.rooms.clear(); - self.sets = None; - let Some(device) = &self.device else { - return; - }; - let shared = device.shared(); - for pool in self.pools.drain(..) { - shared - .spares - .give_descriptor_pool(shared, pool, self.fitted); - } - } - - /// Release every pool: no command uses their sets any more (the command buffer failed, or - /// was never submitted). - pub(crate) fn release(&mut self) { - self.book.rooms.clear(); - self.sets = None; - let Some(device) = &self.device else { - return; - }; - for pool in self.pools.drain(..) { - // SAFETY: no pending command uses the pool's sets: the arena goes when its command - // buffer completed, or was dropped unsubmitted; the sets are freed with it. - unsafe { release_in_section(device.shared(), pool.raw) }; - } - } -} - -impl Drop for DescriptorArena { - fn drop(&mut self) { - self.release(); - } -} diff --git a/crates/metal2vulkan-runtime/src/detach.rs b/crates/metal2vulkan-runtime/src/detach.rs deleted file mode 100644 index 33bfdec55..000000000 --- a/crates/metal2vulkan-runtime/src/detach.rs +++ /dev/null @@ -1,380 +0,0 @@ -//! Detaching a no-copy buffer, or a heap over the caller's host memory, from its host pages -//! (a runtime extension in the shape of Metal's `detachBacking`, the companion of -//! `rebind_bytes_no_copy`, `rebind.rs`). -//! -//! A consumer that moves its pages lets go of the old ones before it has the new: the buffer or -//! heap lies in no pages until a rebind gives it some. Metal's answers (the consumer's rebind -//! probe on the M3 Max, tables 1 to 3, and the M3 Max under macOS 27.0.1), which the runtime -//! keeps: -//! -//! - **The call.** It detaches at once, and answers `true`, unless submitted work holds the -//! buffer or heap: a submission whose command named it (one of a heap's buffers included), or -//! whose encoder made it resident (`use_resource`, `use_heap`), holds it from its submission -//! until its work completed, which for the command buffer's last submissions is as its -//! completion is processed, before its completed handlers run (`rebind::SubmittedHolds`, -//! `CommandBufferShared::complete`; an event wait or signal splits the submissions, -//! `State::event_group`). Then a buffer's call blocks until the work of each such submission -//! completed and answers `false`, detaching nothing; a heap's answers `false` at once. A later -//! submission of a command buffer, behind an event wait, holds nothing until it is submitted: a -//! detach while it waits detaches at once, whatever the command buffer's earlier submissions -//! held, which keep their pages until they complete. A lost device ends the wait: where the -//! device recovers from the loss, refused as made before the recovery -//! (`NotImplemented(MadeBeforeRecovery)`, `device/line.rs`), else `Err(DeviceLost)`. The wait -//! holds no lock of the runtime's: a completion turn lets each -//! submission's hold go without one. -//! - **A detach in a completed handler is a race on Metal, whose deterministic side is `true`.** -//! Metal releases what a command buffer used as it processes the completion, and that release -//! races the start of the completed handlers: a detach that lands before it answers `false`, one -//! after it `true`. Measured on the M3 Max under macOS 27.0.1 over 2672 runs, a detach made *at -//! once* in a handler answered `false` between 1 and 43 times in 50 as unrelated host load -//! changed, and timed from `GPUEndTime` the two answers overlap between 50 and 99 us: neither is -//! Metal's answer there. Every `false` was transient — all 467 detached on a retry 2 us later. -//! Once the use has retired Metal always detaches: 684 of 684 at 20 us or more into the handler, -//! 152 of 152 at 100 us or more with 32 command buffers queued, the first `true` within 117 us -//! of a handler's start. So the runtime lets a submission's hold go as the completion is -//! processed, which answers a detach in a completed handler `true`, Metal's answer wherever -//! Metal's is deterministic; nothing here or in a test rests on either side of the race. -//! - **Pending work.** A submission that comes after the detach, the command buffer's first or a -//! later one, whose commands named the buffer or made it resident (a render pass whose -//! attachment lies in the bytes names them from its open), encoded before the detach or after -//! it, fails with `CommandBufferError::DetachedBacking` (Metal's code 8) and runs nothing of it, -//! its other submissions running; one that only reaches the bytes unnamed reads zeros there -//! (`live_buffers.rs` no longer lists them) and runs, where its command buffer's first -//! submission came after the detach. A rebind before the first submission gives a command -//! encoded while detached `EncodedUseRebound` instead, the gap until encoded uses resolve at -//! submission; so does a rebind before a later submission whose commands named the buffer, -//! which the rebind does not encode again. -//! - **The deallocator** of the pages a detach lets go of runs at the buffer's (or heap's) next -//! rebind, inside the call, on its thread, or at its release, on the releasing thread, never at -//! the detach, as Metal's (`HostCell::hold_back`): their import goes at the detach, once nothing -//! holds it; a keep-alive goes once both the deallocator ran and the import is freed, so the -//! deallocator may read the bytes. -//! - **No memory.** A detached buffer takes the device's stand-in, a small buffer of the -//! runtime's own shared by every detached buffer (`buffer::Detached`), never memory of its -//! size. No command that takes the stand-in runs: an encoder whose command names a detached -//! buffer records nothing from that command on (`EncoderCore::skips`), and its submission -//! fails as above. `contents` answers the caller's pointer of the pages it was detached from, -//! as Metal's does, through which the runtime reads and writes nothing until a rebind. -//! - **Textures**. A texture over the bytes (over the buffer, or over one of a heap's buffers, or -//! in the heap) stays, and presents a stand-in of its image's plan while they are detached -//! (`texture/stand_in.rs`): its size and level queries answer its own, an unnamed read reads zero -//! bytes and an unnamed write lands where nothing reads. Its images bound to the old pages and -//! its views go with them, once nothing holds the pages: an open encoder that named them (a -//! render pass over them from its open, whose first instance may have recorded with those -//! images, `render/inline_first.rs`) and a submitted command buffer hold them. A command that -//! names it fails as one naming the buffer does. A texture being made over the bytes refuses -//! the detach (`NotImplemented(DetachTextures)`), and no texture is made over detached bytes -//! yet. -//! - **Tiled textures** (`Buffer::new_tiled_texture`, more than one level): the image of its own -//! that holds every level, a copy of the bytes taken at use (`shadow.rs`'s **Copies taken at -//! use**), presents no stand-in, and keeps every level through the detach, which its reads, -//! writes and CPU calls take, as a Mac's texture's own memory does. -//! - **Attaching again.** `rebind_bytes_no_copy` gives a detached buffer or heap pages again. - -use super::buffer::{Buffer, Detached, HostCell, Lying}; -use super::degradation::Degradation; -use super::device::lock; -use super::error::{invalid, Error, Problem, RuntimeGap}; -use super::heap::Heap; -use super::rebind::{RebindProblem, StaleTexture, Unexact}; -use super::resource::ObjectId; -use super::texture::stand_in::TextureImages; -use super::Device; -use std::any::Any; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Weak}; - -/// The bytes of the device's stand-in (`Device::detach_stand_in`): room for the widest element -/// a command could take, which no command that takes it reads. -const STAND_IN_BYTES: u64 = 256; - -impl Buffer { - /// `detachBacking` (Metal's private `MTLBuffer` method; the module docs of `detach.rs` state - /// the rule): let the no-copy buffer lie in no host pages until - /// [`rebind_bytes_no_copy`](Buffer::rebind_bytes_no_copy) gives it some. `true` once it is - /// detached (at once, or it was already). Where submitted work holds the buffer (a submission - /// that named it or made it resident, from its submission until its work completed, which for - /// the command buffer's last submissions is as its completion is processed, before its - /// completed handlers run), the call blocks until - /// that work completed and answers `false`, detaching nothing, as Metal's does. So a detach - /// made in a completed handler detaches, as Metal's does once the use has retired; Metal's - /// answer to one made at the very start of a handler is a race of its own release against the - /// handler, and this one is the side of it Metal settles on (the module docs). The old - /// memory's import goes once nothing holds it; its deallocator runs at the buffer's next - /// rebind, inside the call, or at its release, never at the detach, as Metal's. The buffer, its - /// `gpu_address`, its options and its `contents` stay: `contents` answers the caller's pointer - /// of the pages it was detached from, as Metal's does (a heap's buffer, its offset from its - /// heap's), and the runtime reads and writes nothing through it until a rebind. - /// - /// A submission after the call, the command buffer's first or a later one behind an event - /// wait, whose commands named the buffer or made it resident (a render pass whose attachment - /// lies over it names it from its open) fails there, `CommandBufferError::DetachedBacking`, and - /// runs nothing of it; one whose command buffer reaches the buffer only by its address reads - /// zeros there, where its first submission came after the call. - /// - /// A texture over the buffer's bytes stays, and presents a stand-in until the buffer lies in - /// pages again: its queries answer its own descriptor, an unnamed read reads zeros, and a - /// command that names it fails as one that names the buffer. - /// - /// A `Managed` no-copy buffer on a device without unified memory is two copies - /// ([`HostBacking::DeviceCopy`](crate::HostBacking::DeviceCopy)): the call lets go of its host - /// copy (an import of the pages answers as above; pages no import maps detach at once) and - /// keeps the GPU's copy, which commands go on reading and writing, with no stand-in and no - /// failed command buffer; `synchronize_resource` copies nothing out until a rebind gives it - /// pages again, which it copies in whole. - /// - /// Refused: a buffer that is not a no-copy buffer of its own (`Invalid`, - /// [`RebindProblem::NotHostMemory`]); a buffer with a texture being made over its bytes - /// (`NotImplemented(DetachTextures)`); a texture over it whose stand-in the device makes none - /// of (`NotImplemented(DetachTextures)`, a multi-planar format), or out of memory for one; a - /// lost device, also while the call waits. - pub fn detach_backing(&self) -> Result { - const CALL: &str = "detach_backing"; - let Some(cell) = self.host_cell() else { - // A two-copy buffer's host copy lets go of its pages; the GPU's copy stays - // (`managed_copy.rs`). - if let Some(caller) = self.caller_copy() { - return caller.detach(); - } - return Err(invalid(CALL, Problem::Rebind(RebindProblem::NotHostMemory))); - }; - self.generation().detach_host_pages(self, cell, None) - } -} - -impl Heap { - /// `detachBacking` of a heap over the caller's host memory - /// (`Device::new_heap_with_bytes_no_copy`; Metal's private `MTLHeap` method), as - /// [`Buffer::detach_backing`] detaches a no-copy buffer: every buffer placed in it stays, at - /// its offset, and lies in no pages until [`rebind_bytes_no_copy`](Heap::rebind_bytes_no_copy) - /// gives the heap some. Where submitted work holds the heap or a buffer placed in it, the call - /// answers `false` at once, detaching nothing, as Metal's does. The deallocator of the heap's - /// memory runs at its next rebind or its release, as a buffer's. - /// - /// Its textures, and those over its buffers, stay and present stand-ins as a buffer's do. - /// - /// Refused: a heap not over the caller's host memory (`Invalid`, - /// [`RebindProblem::NotHostMemory`]); a heap with a texture being made in it, or over one of - /// its buffers, and a texture whose stand-in the device makes none of - /// (`NotImplemented(DetachTextures)`), or out of memory for one; a lost device. - pub fn detach_backing(&self) -> Result { - const CALL: &str = "detach_backing"; - let Some((own, cell)) = self - .bytes() - .and_then(|own| own.host_cell().map(|cell| (own, cell))) - else { - return Err(invalid(CALL, Problem::Rebind(RebindProblem::NotHostMemory))); - }; - self.generation().detach_host_pages(own, cell, Some(self)) - } -} - -impl Device { - /// Detach `buffer`, a no-copy buffer whose hold on its pages is `cell` (`heap`'s own buffer - /// where given), as the module docs say: `true` once detached; `false` where submitted work - /// holds it, after waiting for that work to complete unless it is a heap's. - fn detach_host_pages( - &self, - buffer: &Buffer, - cell: &Arc, - heap: Option<&Heap>, - ) -> Result { - if self.is_lost() { - return Err(self.lost_refusal()); - } - let shared = self.shared(); - // The render encoders' calls and ends that their calls left to the device's lowering - // thread, as the detach finds them where each call lowers itself (`render/deferral.rs`). - shared.deferred.lower_all(); - let rebinds = &shared.rebinds; - let key = buffer.identity().key; - // Submitted work holds it: a buffer's call waits for that work, a heap's not. - let refuse = || { - if heap.is_none() { - rebinds.wait_ran(self, key)?; - } - Ok(false) - }; - if rebinds.submitted(key) { - return refuse(); - } - let Lying::In(from) = cell.lying() else { - return Ok(true); - }; - // No texture is being made over the bytes while this is held, and those over them - // present stand-ins once they are detached, each made now, before anything changes. - let no_textures = || Error::NotImplemented(RuntimeGap::DetachTextures); - let textures = cell.settled().ok_or_else(no_textures)?; - let images = TextureImages::of(textures.images()); - let stand_ins = images.stand_ins(self)?; - let detached = Arc::new(Detached::new(self.detach_stand_in()?, &from)?); - drop(from); - let Some((old, twins, resident)) = rebinds.detach(key, cell, detached) else { - drop(textures); - return refuse(); - }; - // Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`). - drop(twins); - // What the textures over the old pages made of them goes: the images bound there and - // every view (the texel views of texture buffers too, made again over pages the next - // bind finds). - let gone = images.present_stand_ins(stand_ins); - let texels = cell.texels(); - // Pages a submitted command buffer made resident stay Metal's textures' unnamed reads; - // and a stand-in's sink holds what unnamed writes left. A texture whose image keeps its - // own texels presents no stand-in. - let presenting = textures.textures().filter(|noted| !noted.keeps()); - let stale = presenting.flat_map(|noted| { - let pages = resident.then_some(Unexact::StalePages); - let sink = noted.sink().then_some(Unexact::StorageSink); - let (texture, id) = (noted.texture(), noted.id); - pages - .into_iter() - .chain(sink) - .map(move |why| (Weak::clone(&texture), id, why)) - }); - self.note_stale(cell, stale); - drop(textures); - if let Lying::In(pages) = &old { - for views in &texels { - pages.park(views.park()); - } - } - // The buffer, or the heap's buffers, are reached unnamed again only once a command buffer - // uses it after it lies in pages again (`live_buffers.rs`): until then, unnamed reads - // read zeros. - shared.live_buffers.rebound(buffer, heap); - // Later buffers over the memory it was made over no longer join it. - shared.aliases.leave(key); - // It lies over no host bytes: its uses take its stand-in. - shared.aliases.unplace(key); - // The device's heap sets view the stand-ins of the textures over the bytes, and no other - // texture's elements change (`heap_sets::renew_over`); the images and views they named - // before wait for the command buffers that may read them through the sets, and the old - // pages, which the images bound there read, wait with them. - if !images.is_empty() || !texels.is_empty() { - super::heap_sets::renew_over(self, key); - } - // What lay in the old pages goes with them, as a rebind's swapped images do: once the - // command buffers that may read them through the heap sets completed, and once nothing - // holds the pages: an open encoder that took them (a render pass's attachments from its - // open, whose first instance may have recorded with their images, - // `render/inline_first.rs`), and a submitted command buffer until it completes. - if !gone.is_empty() { - match &old { - Lying::In(pages) => { - pages.park(gone); - super::heap_sets::retire(self, Box::new(Arc::clone(pages))); - } - Lying::Detached(_) | Lying::Gone(_) => { - super::heap_sets::retire(self, Box::new(gone)) - } - } - } - // The old pages go now where no command buffer holds them, their import freed; their - // deallocator waits for the next rebind or the release (`HostCell::hold_back`). - if let Lying::In(pages) = &old { - cell.hold_back(pages); - } - drop(old); - Ok(true) - } - - /// The device's stand-in, which detached buffers take (`buffer::Detached`): made once - /// while one is detached, and again once every one let go of it. - pub(super) fn detach_stand_in(&self) -> Result { - let mut stand_in = lock(&self.shared().rebinds.stand_in); - if let Some(buffer) = stand_in.as_ref().and_then(|weak| weak.upgrade()) { - return Ok(buffer); - } - let buffer = self.scratch_buffer(STAND_IN_BYTES)?; - *stand_in = Some(buffer.downgrade()); - Ok(buffer) - } -} - -impl Device { - /// Note `textures` (by type erased, with their objects' IDs), over the bytes `cell` holds the - /// pages of, detached, whose unnamed reads may not be Metal's, each for why (`Unexact`): - /// detached after a submitted command buffer made their pages resident, or presenting a - /// stand-in with a sink. Each is announced at the first submission, or commit, that may - /// reach it (`Device::reach_stale_detached`, `Device::reach_storage_sinks`). - pub(super) fn note_stale( - &self, - cell: &Arc, - textures: impl Iterator, ObjectId, Unexact)>, - ) { - let rebinds = &self.shared().rebinds; - let mut stale = lock(&rebinds.stale); - stale.retain(|held| held.texture.strong_count() > 0); - stale.extend(textures.map(|(texture, id, why)| StaleTexture { - texture, - id, - cell: Arc::downgrade(cell), - why, - })); - rebinds.stale_count.store(stale.len(), Ordering::Release); - } - - /// The bytes `cell` holds the pages of lie in pages again (`buffer_descriptor.rs`): their - /// textures are no longer over detached bytes. - pub(super) fn forget_stale(&self, cell: &HostCell) { - let rebinds = &self.shared().rebinds; - if rebinds.stale_count.load(Ordering::Acquire) == 0 { - return; - } - let mut stale = lock(&rebinds.stale); - stale.retain(|held| { - !std::ptr::eq(held.cell.as_ptr(), cell) && held.texture.strong_count() > 0 - }); - rebinds.stale_count.store(stale.len(), Ordering::Release); - } - - /// The stale-reach degrade's trigger, the one place it is decided: a submission whose command - /// buffer bound a heap set (`reaches`) may reach every texture through its resource ID unnamed, - /// so each texture whose bytes were detached after a submitted command buffer made them - /// resident is announced now, once - /// ([`Degradation::StaleDetachedReach`], with its - /// ID), and counted (`WorkCounts::stale_detached_reaches`). Metal's unnamed read of such a - /// texture reads the pages the program gave back, which a correct program never relies on; - /// the stand-in's reads zero. The trigger is reachability, not a read. On the submitting - /// thread, with no lock of the command buffer's held; one load while no texture is noted. - pub(super) fn reach_stale_detached(&self, reaches: bool) { - for texture in self.reached(reaches, Unexact::StalePages) { - self.shared().counts.stale_detached_reach(); - self.degrade_detached_reach(Degradation::StaleDetachedReach, texture.id); - } - } - - /// The storage-sink degrade's trigger, the one place it is decided: a command buffer that bound - /// a heap set (`reaches`) may reach every texture through its resource ID unnamed, so each - /// texture over detached bytes whose stand-in has a sink is announced as it commits, once - /// ([`Degradation::DetachedStorageKeepsWrites`], - /// with its ID), and counted (`WorkCounts::detached_storage_reaches`): a read through a - /// storage-class element there reads what an unnamed write left in the sink, where Metal's - /// reads zero. In the program's `commit`, with no lock held, so a handler asked for each - /// occurrence may end the process there. - pub(super) fn reach_storage_sinks(&self, reaches: bool) { - for texture in self.reached(reaches, Unexact::StorageSink) { - self.shared().counts.detached_storage_reach(); - self.degrade_detached_reach(Degradation::DetachedStorageKeepsWrites, texture.id); - } - } - - /// The live textures noted for `why`, where a command buffer `reaches` them, no longer - /// noted: each is announced once. One load while no texture is noted. - fn reached(&self, reaches: bool, why: Unexact) -> Vec { - let rebinds = &self.shared().rebinds; - if !reaches || rebinds.stale_count.load(Ordering::Acquire) == 0 { - return Vec::new(); - } - let mut stale = lock(&rebinds.stale); - let (reached, kept): (Vec, Vec) = stale - .drain(..) - .filter(|held| held.texture.strong_count() > 0) - .partition(|held| held.why == why); - stale.extend(kept); - rebinds.stale_count.store(stale.len(), Ordering::Release); - reached - } -} diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs deleted file mode 100644 index 78363970e..000000000 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ /dev/null @@ -1,411 +0,0 @@ -//! Adopting the consumer's Vulkan device: `unsafe Device::from_raw`. -//! -//! The consumer made the instance and the device and keeps them: the runtime loads their -//! function pointers through the consumer's `vkGetInstanceProcAddr`, reads the physical device -//! into a description, restricts it to the [`EnableSet`] the consumer enabled, and builds its -//! compile device from that. Dropping the runtime device destroys only what the runtime made -//! from the device (its pools, memory and objects); the instance and the `VkDevice` stay the -//! consumer's. - -use super::{device_error, Device, InstanceShared, Parts}; -use crate::error::Error; -use crate::gpu_time; -use crate::image_barrier::MemoryReads; -use crate::loader_word::DeviceWord; -use crate::shader_cache::{CacheSetup, ShaderCacheOptions}; -use crate::sparse::device::SparseFeatures; -use ash::vk; -use metal2vulkan::device::{DeviceDescription, DevicePolicy, EnableSet, VkExtension}; -use std::collections::BTreeSet; -use std::ffi::{CStr, CString}; -use std::sync::Arc; - -/// The consumer's Vulkan objects a runtime device adopts ([`Device::from_raw`]). No Metal -/// counterpart: an interop hook. -#[non_exhaustive] -#[derive(Clone)] -pub struct RawDevice { - /// The `vkGetInstanceProcAddr` the instance was made through. - pub get_instance_proc_addr: vk::PFN_vkGetInstanceProcAddr, - /// The consumer's instance. - pub instance: vk::Instance, - /// The `VkApplicationInfo::apiVersion` the instance was created with. - pub instance_api_version: metal2vulkan::vk::ApiVersion, - /// The physical device the device was made on. - pub physical_device: vk::PhysicalDevice, - /// The consumer's device, made with what [`enabled`](Self::enabled) states. - pub device: vk::Device, - /// The queue family the runtime submits to: it must support graphics and compute work. - pub queue_family: u32, - /// The queue of that family the runtime submits to (0 by default). The runtime takes it - /// under its own lock; the consumer must not submit to it concurrently. - pub queue_index: u32, - /// Exactly what the consumer enabled at `vkCreateDevice`, in the compile layer's vocabulary. - pub enabled: EnableSet, - /// The extensions outside that vocabulary the consumer enabled that the runtime uses (none - /// by default): `VK_KHR_calibrated_timestamps` or `VK_EXT_calibrated_timestamps` places - /// command buffers' GPU times on the host's clock - /// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time)); - /// `VK_NV_linear_color_attachment`, with its `linearColorAttachment` feature enabled beside - /// it (and, below Vulkan 1.3, `VK_KHR_format_feature_flags2`, which it requires there), makes - /// a texture over a buffer's memory render into its linear image in place; - /// `VK_KHR_external_memory_fd` with `VK_EXT_external_memory_dma_buf` serve - /// `HostMemory::with_dma_buf`, and with them `VK_EXT_image_drm_format_modifier` with - /// `VK_EXT_queue_family_foreign` make textures over its pages images rather than shadows; - /// those two with `VK_EXT_queue_family_foreign` make buffers whose memory is exported as a - /// dma-buf (`MemoryExport::DmaBuf`). - pub device_extensions: Vec, - /// Where the device keeps translated shaders: by default, the platform's per-user cache - /// directory. - pub shader_cache: ShaderCacheOptions, - /// The sparse members of the core features the consumer enabled (`sparseBinding`, - /// `sparseResidencyImage2D`, `sparseResidencyImage3D`, `sparseResidency2Samples` to - /// `16Samples`; every other member is ignored), outside the compile layer's vocabulary: the - /// runtime makes sparse heaps on what they enable, where the queue family binds sparse - /// memory. None by default. - pub sparse_features: SparseFeatures, - /// Whether the consumer enabled the portability subset's `imageViewFormatReinterpretation` - /// (`VkPhysicalDevicePortabilitySubsetFeaturesKHR`), outside the compile layer's vocabulary: - /// false by default, the answer that is never wrong. On a device whose `enabled` lists - /// `VK_KHR_portability_subset` (MoltenVK), the runtime makes a texture view of another - /// component layout than its texture's (`RGBA8Unorm` as `R32Uint`, `RGB10A2Unorm` as - /// `RGB10A2Uint`) only where this is true, and refuses it where it is false (`Unsupported`, - /// `Feature::ViewFormatReinterpretation`): Vulkan makes no such view on a device the feature - /// was not enabled on. A device without the subset makes such views whatever this says. - pub view_format_reinterpretation: bool, - /// Whether the consumer enabled `hostImageCopy` (`VkPhysicalDeviceHostImageCopyFeatures`, - /// with `VK_EXT_host_image_copy` and the extensions it requires below Vulkan 1.4), outside - /// the compile layer's vocabulary: false by default, the answer that is never wrong. Where - /// it is true, a `Shared` or `Managed` texture's `replace_region` and `get_bytes` copy on the - /// host, with no submission and no wait for the GPU, where the format and the memory take - /// host-transfer usage; where it is false they copy on a submission. On a driver whose - /// compressed images hide writes through an alias and that keeps a host-transfer image's bytes - /// (ANV), a heap's colour texture takes host-transfer usage only where this is true, and where - /// it is false a linear image where one serves, else the optimal image, a recorded - /// near-equivalent (`heap-texture-hides-aliased-writes`). - pub host_image_copy: bool, - /// Answer command buffers' GPU times from the host's clock instead of GPU timestamps, as - /// [`DeviceOptions::gpu_times_from_host`](crate::DeviceOptions::gpu_times_from_host) says: - /// false by default, Metal's answer, except on a driver whose timestamps wait for every - /// queue's, which answers from the host's clock whatever this says. Metal has no such - /// setting. - pub gpu_times_from_host: bool, - /// The class of Mac the device presents, as - /// [`DeviceOptions::mac_class`](crate::DeviceOptions::mac_class) says: `None` by default, - /// the class of the device's GPU. No Metal counterpart. - pub mac_class: Option, - /// The degradation kinds the device announces at every occurrence, not once, as - /// [`DeviceOptions::announce_each`](crate::DeviceOptions::announce_each) says: none by - /// default. - pub announce_each: BTreeSet, - /// The degradation kinds that refuse a render encoder's call met while lowering it after it - /// returned, as - /// [`DeviceOptions::lowering_refuses`](crate::DeviceOptions::lowering_refuses) says: none by - /// default. - pub lowering_refuses: BTreeSet, - /// Where the device hands its pipeline records, as - /// [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) says: `None` - /// by default, no record made. Metal has no such setting. - pub pipeline_records: Option>, - /// Load no dynamic library from a file, as - /// [`DeviceOptions::load_no_dynamic_library_file`](crate::DeviceOptions::load_no_dynamic_library_file) - /// says: false by default, Metal's behaviour. No Metal counterpart. - pub load_no_dynamic_library_file: bool, -} - -impl std::fmt::Debug for RawDevice { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // Every field is named, so a field added later is written here or this fails to compile. - let RawDevice { - get_instance_proc_addr, - instance, - instance_api_version, - physical_device, - device, - queue_family, - queue_index, - enabled, - device_extensions, - shader_cache, - sparse_features, - view_format_reinterpretation, - host_image_copy, - gpu_times_from_host, - mac_class, - announce_each, - lowering_refuses, - pipeline_records, - load_no_dynamic_library_file, - } = self; - f.debug_struct("RawDevice") - .field("get_instance_proc_addr", get_instance_proc_addr) - .field("instance", instance) - .field("instance_api_version", instance_api_version) - .field("physical_device", physical_device) - .field("device", device) - .field("queue_family", queue_family) - .field("queue_index", queue_index) - .field("enabled", enabled) - .field("device_extensions", device_extensions) - .field("shader_cache", shader_cache) - .field("sparse_features", sparse_features) - .field("view_format_reinterpretation", view_format_reinterpretation) - .field("host_image_copy", host_image_copy) - .field("gpu_times_from_host", gpu_times_from_host) - .field("mac_class", mac_class) - .field("announce_each", announce_each) - .field("lowering_refuses", lowering_refuses) - .field( - "pipeline_records", - &pipeline_records.as_ref().map(|_| "hook"), - ) - .field("load_no_dynamic_library_file", load_no_dynamic_library_file) - .finish() - } -} - -impl RawDevice { - /// The objects of one device, its queue family's first queue. - pub fn new( - get_instance_proc_addr: vk::PFN_vkGetInstanceProcAddr, - instance: vk::Instance, - instance_api_version: metal2vulkan::vk::ApiVersion, - physical_device: vk::PhysicalDevice, - device: vk::Device, - queue_family: u32, - enabled: EnableSet, - ) -> RawDevice { - RawDevice { - get_instance_proc_addr, - instance, - instance_api_version, - physical_device, - device, - queue_family, - queue_index: 0, - enabled, - device_extensions: Vec::new(), - shader_cache: ShaderCacheOptions::default(), - sparse_features: SparseFeatures::default(), - view_format_reinterpretation: false, - host_image_copy: false, - gpu_times_from_host: false, - mac_class: None, - announce_each: BTreeSet::new(), - lowering_refuses: BTreeSet::new(), - pipeline_records: None, - load_no_dynamic_library_file: false, - } - } -} - -impl Device { - /// Adopt the consumer's device: a runtime device that works on `raw`, with its compile - /// device made with `policy` from the description restricted to `raw.enabled`. - /// - /// Errors: a shader cache directory that cannot be used (`ShaderCache`), a device the - /// compile layer refuses (below Vulkan 1.2, or `raw.enabled` not a valid set for the device: - /// `Unsupported` or `Compile`), one whose timeline semaphores step less than Vulkan - /// requires (`Unsupported`, `Feature::TimelineSemaphores`), and a MoltenVK device without - /// Metal argument buffers (`DriverSetting`): the consumer's instance must leave MoltenVK's - /// `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` on. - /// - /// # Safety - /// - /// - `raw.instance` was created through `raw.get_instance_proc_addr` with - /// `raw.instance_api_version`, `raw.physical_device` was enumerated from it, and - /// `raw.device` was created on that physical device with exactly `raw.enabled` enabled, - /// the extensions `raw.device_extensions` names among the others it enabled, and queue - /// `raw.queue_index` of family `raw.queue_family`. - /// - The device also enabled `timelineSemaphore` (core in Vulkan 1.2, outside the compile - /// layer's vocabulary): events and the completion of command buffers are timeline - /// semaphores. - /// - `raw.view_format_reinterpretation` is true only if the device enabled the portability - /// subset's `imageViewFormatReinterpretation`. - /// - `raw.host_image_copy` is true only if the device enabled `hostImageCopy`, with - /// `VK_EXT_host_image_copy` where the device's Vulkan version (the instance's or the - /// physical device's, the lower) is below 1.4, and `VK_KHR_copy_commands2` and - /// `VK_KHR_format_feature_flags2` where it is below 1.3. - /// - All of them outlive the runtime device and every object made from it. - /// - The device's first word is still the one the loader wrote (no driver has overwritten - /// it). - /// - The consumer does not use the queue, or any object the runtime makes, concurrently - /// with the runtime. - pub unsafe fn from_raw(raw: RawDevice, policy: DevicePolicy) -> Result { - let cache = CacheSetup::of(&raw.shader_cache, "from_raw")?; - let static_fn = ash::StaticFn { - get_instance_proc_addr: raw.get_instance_proc_addr, - }; - // SAFETY: the caller's contract: the loader's (or a driver's) `vkGetInstanceProcAddr`. - let entry = unsafe { ash::Entry::from_static_fn(static_fn) }; - // SAFETY: the caller's contract: the instance was made through this entry point. - let instance = unsafe { ash::Instance::load(entry.static_fn(), raw.instance) }; - // SAFETY: the caller's contract. - let description = unsafe { - DeviceDescription::query(&instance, raw.physical_device, raw.instance_api_version) - } - .map_err(device_error)?; - // SAFETY: the caller's contract. - unsafe { super::create::timeline_conformant(&instance, raw.physical_device) }?; - super::create::argument_buffers_kept(&description)?; - let mut enabled = description - .with_enabled(&raw.enabled) - .map_err(device_error)?; - // The vocabulary does not say whether `VK_EXT_device_generated_commands` was enabled: - // the runtime makes none of its objects on such a device. - enabled.generated_commands = None; - let compile = - metal2vulkan::device::Device::new(enabled.clone(), policy).map_err(device_error)?; - // SAFETY: the caller's contract: the word is still the loader's. - let loader_word = unsafe { DeviceWord::of_device(raw.device) }; - // SAFETY: the device is live; the loader's `vkGetDeviceProcAddr` reads the word, which - // is the loader's. - let device = - unsafe { loader_word.restored(|| ash::Device::load(instance.fp_v1_0(), raw.device)) }; - // The vocabulary does not say whether a portability subset's - // `imageViewFormatReinterpretation` was enabled: the consumer says so beside it, and a - // device with the subset whose consumer does not reinterprets nothing. - let view_reinterpretation = raw.view_format_reinterpretation - || !raw - .enabled - .extensions - .contains(&VkExtension::KhrPortabilitySubset); - // Nor whether `hostImageCopy` was: the consumer says so beside it. - let host_image_copy = raw.host_image_copy; - // Nor whether `VK_NV_linear_color_attachment` was: the consumer lists it with its feature - // (`RawDevice::device_extensions`), at any version, as a made device takes it: a device - // made with it enabled has what it requires (Vulkan 1.3, or `VK_KHR_format_feature_flags2`, - // whose formats' properties the description then reads). - let linear_color_attachment = raw - .device_extensions - .iter() - .any(|name| name.as_c_str() == ash::nv::linear_color_attachment::NAME); - // Nor whether `VK_EXT_graphics_pipeline_library` was: the consumer lists it and - // `VK_KHR_pipeline_library` with its feature, and the device's properties say whether it - // links fast, as a made device takes it. - let listed: BTreeSet = raw.device_extensions.iter().cloned().collect(); - // Nor whether the dma-buf route's were (`dma_buf.rs`): the consumer lists them. - let dma_buf = super::create::dma_buf_names(&listed).is_some(); - let dma_buf_images = super::create::dma_buf_image_names(&listed).is_some(); - // Nor whether `VK_KHR_external_memory_fd` was (`exported_memory.rs`): the consumer lists - // it. - #[cfg(unix)] - let memory_fd = super::create::memory_fd_name(&listed).is_some(); - // Nor whether `VK_EXT_queue_family_foreign` was beside the dma-buf route's - // (`exported_memory.rs`): the consumer lists them. - #[cfg(unix)] - let foreign_family = super::create::foreign_family_name(&listed).is_some(); - // Nor whether `VK_KHR_external_semaphore_fd` was (`exported_semaphore.rs`). - #[cfg(unix)] - let semaphore_fd = super::create::semaphore_fd_name(&listed).is_some(); - let graphics_pipeline_library = super::create::graphics_pipeline_library(&listed, || { - // SAFETY: the consumer's physical device of its instance, which lists the - // extension (the consumer enabled it), at Vulkan 1.2 or later. - unsafe { - super::create::graphics_pipeline_library_supported(&instance, raw.physical_device) - } - }); - // The reads its global memory barriers name: those of the family the runtime submits to, - // which supports graphics and compute work, with every extension the consumer enabled - // that the description or the consumer names. - // SAFETY: the caller's contract: the physical device was enumerated from the instance. - let families = - unsafe { instance.get_physical_device_queue_family_properties(raw.physical_device) }; - let family = (families.get(raw.queue_family as usize)).map_or( - vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE, - |family| family.queue_flags, - ); - let mut named: Vec<&CStr> = (raw.enabled.extensions.iter()) - .flat_map(|&extension| crate::enables::names_of(extension)) - .collect(); - named.extend(raw.device_extensions.iter().map(CString::as_c_str)); - let memory_reads = MemoryReads::of(family, named); - let extensions = raw.device_extensions.clone(); - let parts = Parts { - instance: Arc::new(InstanceShared { - entry, - raw: instance, - api_version: raw.instance_api_version, - extensions: Vec::new(), - owned: false, - messenger: None, - relay: None, - settings: [0; 32], - dropped_layers: Vec::new(), - }), - physical: raw.physical_device, - raw: device, - loader_word, - queue_family: raw.queue_family, - queues: vec![(raw.queue_family, raw.queue_index)], - present_queues: 0, - planned: None, - least_plan: false, - staging: None, - fill: None, - copies: None, - reserved_queues: Vec::new(), - extra_queues: Vec::new(), - compile, - description: enabled, - enabled: raw.enabled, - extensions, - creation_feedback: raw - .device_extensions - .iter() - .any(|name| name.as_c_str() == ash::ext::pipeline_creation_feedback::NAME), - dma_buf, - dma_buf_images, - #[cfg(unix)] - memory_fd, - #[cfg(unix)] - foreign_family, - #[cfg(unix)] - semaphore_fd, - calibration: gpu_time::Extension::among(&raw.device_extensions.into_iter().collect()), - gpu_times_from_host: raw.gpu_times_from_host, - mac_class: raw.mac_class, - // An adopted device keeps no execution record: validation makes its own devices. - record_executions: false, - load_no_dynamic_library_file: raw.load_no_dynamic_library_file, - pipeline_records: raw.pipeline_records, - fail_in_place_check: false, - #[cfg(test)] - view_facts: Some(std::collections::BTreeSet::new()), - assume_submissions_merge: false, - // On where `METAL2VULKAN_PENDING_AUDIT` is set (`assemble`). - pending_audit: false, - // On where `METAL2VULKAN_ENCODER_TRAIL` is set (`assemble`). - encoder_trail: false, - announce_each: raw.announce_each, - lowering_refuses: raw.lowering_refuses, - view_reinterpretation, - generated_commands: false, - host_image_copy, - // Nor whether `zeroInitializeDeviceMemory` was: none of its images start in memory the - // driver zeroed. - zero_initialize_device_memory: false, - linear_color_attachment, - graphics_pipeline_library, - // Nor whether `samplerYcbcrConversion` was: its YCbCr textures convert through - // Metal's arithmetic. - ycbcr_conversion: false, - ycbcr_444: false, - sparse_features: raw.sparse_features.features(), - memory_reads, - owned: false, - cache, - // The consumer made the `VkDevice`: the runtime cannot make it again once it is - // lost (`line.rs`). - line: None, - recipe: None, - }; - // SAFETY: the caller's contract. - let device = unsafe { Device::assemble(parts) }?; - // The consumer made the instance, so a layer's exit handler registered at its - // `vkCreateInstance` may follow the hook's last registration: the hook registers again, - // after it (`exit_guard::instance_made`). - crate::exit_guard::instance_made(); - Ok(device.root()) - } -} diff --git a/crates/metal2vulkan-runtime/src/device/argument_buffers.rs b/crates/metal2vulkan-runtime/src/device/argument_buffers.rs deleted file mode 100644 index a10356fa5..000000000 --- a/crates/metal2vulkan-runtime/src/device/argument_buffers.rs +++ /dev/null @@ -1,214 +0,0 @@ -//! MoltenVK's Metal argument buffers. -//! -//! Metal always binds through argument buffers. MoltenVK makes a pooled descriptor set a Metal -//! argument buffer only while its setting `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` is on, the -//! default (`MVKEnvironment.h`); with it off (an environment variable, or a layer setting) every -//! set's resources reach Metal as discrete arguments, and two things change: -//! -//! - Metal's compiler crashes (`MTLCompilerService` stops with `EXC_BAD_ACCESS` in its back end) on -//! the discrete form of large fragment functions whose argument-buffer form it compiles -//! (measured on an Apple M3 Max and an Apple M4), so their pipelines fail. -//! - The update-after-bind limits fall to the per-stage ones (128 textures), so argument buffers -//! hold far fewer resources than Metal's tier 2. -//! -//! So an instance the runtime creates asks MoltenVK for argument buffers through -//! `VK_EXT_layer_settings` where the instance lists it ([`setting`]), ahead of the consumer's own -//! settings: MoltenVK applies layer settings over the environment, and in order, so a consumer's -//! own setting wins. Then at device open, on every path (an adopted device too), a MoltenVK device -//! running without them is refused ([`check`], [`DriverSetting::MoltenVkArgumentBuffersOff`]). -//! -//! The state is read from the device's limits, at each release [`READ`] lists: MoltenVK's -//! `initProperties` (`MVKDevice.mm`) reports `maxPerStageDescriptorUpdateAfterBindSampledImages` -//! as 1,000,000 where `isTier2MetalArgumentBuffers()` (argument buffers in use on a tier-2 GPU), -//! else as `maxPerStageDescriptorSampledImages`; and every Apple GPU a Mac has is tier 2, so on -//! one the per-stage value means argument buffers are off. Measured on 1.4.1 on an Apple M3 Max: -//! 1,000,000 (and 256 per stage) with the setting on, 128 and 128 with it off. 1.4.2's -//! `initProperties`, `isTier2MetalArgumentBuffers` and `initMetalFeatures` are 1.4.1's on these -//! (read in its source), and on an Apple M3 Max it reports 1,000,000 with the setting on and is -//! refused with it off (`runtime_lane::degrade_notices`). Not from -//! `pipelineCacheUUID`, whose argument-buffer bit `initPipelineCacheUUID` writes before -//! `initMetalFeatures` sets the flag, so it is 1 either way (read in 1.4.1's source, and measured). -//! Any other release, or another GPU's vendor, or limits of neither shape, is -//! [`ArgumentBuffers::Unread`], announced once -//! (`metal2vulkan-degrade-moltenvk-argument-buffers-unread`), never refused. - -use super::create::{LayerSetting, LayerSettingValue}; -use crate::error::{DriverSetting, Error}; -use metal2vulkan::device::DeviceDescription; -use metal2vulkan::vk::DriverId; -use std::ffi::CStr; - -/// MoltenVK's layer name for its settings (`kMVKMoltenVKDriverLayerName`). -pub(crate) const LAYER: &CStr = c"MoltenVK"; - -/// MoltenVK's setting that makes descriptor sets Metal argument buffers (`MVKConfigMembers.def`: -/// `useMetalArgumentBuffers`, a `VkBool32`). -pub(crate) const SETTING: &CStr = c"MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS"; - -/// The MoltenVK releases (`driverVersion`, `major * 10000 + minor * 100 + patch`) whose -/// `initProperties` and `initMetalFeatures` were read for the limits the module docs decode. -pub(crate) const READ: &[u32] = &[10401, 10402]; - -/// `maxPerStageDescriptorUpdateAfterBindSampledImages` with tier-2 argument buffers in use, at -/// each release [`READ`] lists (`1e6` in `initProperties`). -pub(crate) const TIER_2_UPDATE_AFTER_BIND: u32 = 1_000_000; - -/// Apple's PCI vendor ID: MoltenVK's `vendorID` on an Apple GPU, each of which a Mac has is a -/// tier-2 argument buffer GPU. -pub(crate) const APPLE: u32 = 0x106b; - -/// Whether a device's driver binds through Metal argument buffers. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ArgumentBuffers { - /// Not MoltenVK. - NotMoltenVk, - /// MoltenVK, binding through Metal argument buffers. - On, - /// MoltenVK, with `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` off. - Off, - /// MoltenVK, but its state is not read (the module docs). - Unread, -} - -/// The device's facts the state is read from. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Facts { - pub(crate) driver: Option, - /// `driverVersion`. - pub(crate) release: u32, - /// `vendorID`. - pub(crate) vendor: u32, - /// `maxPerStageDescriptorUpdateAfterBindSampledImages`. - pub(crate) update_after_bind: u32, - /// `maxPerStageDescriptorSampledImages`. - pub(crate) per_stage: u32, -} - -impl Facts { - /// The facts of a device of `description`. - pub(crate) fn of(description: &DeviceDescription) -> Facts { - let limits = &description.limits; - Facts { - driver: description.driver_id, - release: description.driver_version, - vendor: description.vendor_id, - update_after_bind: limits.max_per_stage_descriptor_update_after_bind_sampled_images, - per_stage: limits.max_per_stage_descriptor_sampled_images, - } - } - - /// Whether the device binds through Metal argument buffers (the module docs). - pub(crate) fn argument_buffers(self) -> ArgumentBuffers { - if self.driver != Some(DriverId::MOLTENVK) { - return ArgumentBuffers::NotMoltenVk; - } - if !READ.contains(&self.release) { - return ArgumentBuffers::Unread; - } - if self.update_after_bind == TIER_2_UPDATE_AFTER_BIND { - ArgumentBuffers::On - } else if self.vendor == APPLE && self.update_after_bind == self.per_stage { - ArgumentBuffers::Off - } else { - ArgumentBuffers::Unread - } - } -} - -/// The macOS release from which MoltenVK 1.4.1 makes its device-wide `MTLResidencySet` -/// (`initMetalFeatures` sets `residencySets` from macOS 15 on an Apple GPU, and `initQueues` -/// makes the set where argument buffers are in use; read in 1.4.1's source). -const RESIDENCY_SETS_FROM_MACOS: u32 = 15; - -impl Facts { - /// Whether the device keeps MoltenVK's device-wide residency set: MoltenVK binding through - /// Metal argument buffers ([`ArgumentBuffers::On`]) on macOS 15 or later. Such a device adds - /// every memory, buffer and image the driver makes to the set, and removes each one freed, - /// committing the set at once (`MVKDevice::makeResident`, `removeResidency`). - pub(crate) fn keeps_residency_set(self) -> bool { - self.argument_buffers() == ArgumentBuffers::On - && macos_major().is_some_and(|major| major >= RESIDENCY_SETS_FROM_MACOS) - } -} - -/// The running macOS's major release (`kern.osproductversion`); `None` elsewhere, or unread. -fn macos_major() -> Option { - #[cfg(target_os = "macos")] - { - let mut text = [0u8; 32]; - let mut length = text.len(); - // SAFETY: a nul-terminated name, and a buffer of `length` bytes the call writes at most. - let read = unsafe { - libc::sysctlbyname( - c"kern.osproductversion".as_ptr(), - text.as_mut_ptr().cast(), - &mut length, - std::ptr::null_mut(), - 0, - ) - }; - if read != 0 { - return None; - } - let version = std::str::from_utf8(text.get(..length)?).ok()?; - version - .trim_end_matches('\0') - .split('.') - .next()? - .parse() - .ok() - } - #[cfg(not(target_os = "macos"))] - { - None - } -} - -/// The layer setting that asks MoltenVK for argument buffers, chained ahead of the consumer's. -pub(crate) fn setting() -> LayerSetting { - LayerSetting::new( - LAYER.to_owned(), - SETTING.to_owned(), - LayerSettingValue::Bool(true), - ) -} - -/// Refuse a MoltenVK device running without argument buffers (the module docs). -pub(crate) fn check(state: ArgumentBuffers) -> Result<(), Error> { - match state { - ArgumentBuffers::Off => Err(Error::DriverSetting( - DriverSetting::MoltenVkArgumentBuffersOff, - )), - _ => Ok(()), - } -} - -impl super::Device { - /// Announce `moltenvk-argument-buffers-unread` once where the device is MoltenVK whose state - /// is not read (the module docs). - pub(super) fn degrade_argument_buffers_unread(&self) { - let description = &self.properties().description; - let facts = Facts::of(description); - if facts.argument_buffers() != ArgumentBuffers::Unread { - return; - } - let read: Vec = READ.iter().map(u32::to_string).collect(); - self.degrade( - crate::degradation::Degradation::MoltenVkArgumentBuffersUnread, - || { - ( - format!( - "the device's MoltenVK at driverVersion {} (vendorID {:#x})", - facts.release, facts.vendor - ), - format!( - "its argument buffers are read at driverVersion {} on Apple GPUs only; \ - maxPerStageDescriptorUpdateAfterBindSampledImages is {}", - read.join(", "), - facts.update_after_bind - ), - ) - }, - ); - } -} diff --git a/crates/metal2vulkan-runtime/src/device/carry.rs b/crates/metal2vulkan-runtime/src/device/carry.rs deleted file mode 100644 index a95ddac23..000000000 --- a/crates/metal2vulkan-runtime/src/device/carry.rs +++ /dev/null @@ -1,1331 +0,0 @@ -//! What a device's recovery carries to its next generation (`line.rs`): the program's events, its -//! uses of guest RAM, its keeps of shared dma-bufs (`dma_buf/kept.rs`: each file kept on the new -//! generation, imported there at the first buffer over a piece of it), its no-copy buffers, the buffers of the runtime's memory whose bytes no -//! pointer of the program's reaches or whose pages the runtime owns, its `Private` heaps and its -//! heaps over the caller's memory with the buffers placed in them, its textures made by a call -//! the recovery makes again (those placed in the heaps it carries among them) -//! (`texture/carry.rs`), its pipeline states (`pipeline/carry.rs`) and its sampler states -//! (`sampler.rs`), each the same object on the new `VkDevice`, as Metal keeps its objects across its GPU's recovery. A fence, a depth/stencil state, a library, a function, an address -//! pool, a dynamic library, a binary archive and a rasterization rate map hold no Vulkan object -//! (`fence.rs`, `depth_stencil.rs`, `library.rs`, `address_pool.rs`, `dynamic_library.rs`, -//! `binary_archive`, `rate_map.rs`), and an argument encoder (`argument_encoder.rs`): the -//! recovery carries their handle of the device alone ([`LineDevice`]), and the device's note -//! that it released a map of layers. After the pipeline states, its indirect command buffers -//! (`indirect_command_buffer/carry.rs`) and its visible function tables -//! (`function_table/carry.rs`), each the same object there, their records and words buffers of -//! the runtime's own carried as such (`Buffer::carry_runtime`). -//! -//! - **Kept as made.** Each event (`EventShared::new`), heap (`Device::new_heap`) and texture of -//! the program's (`Texture::made`) is kept here, held weakly, by the generation it was made on; -//! each buffer the program made of its own (`Device::visible`) is -//! kept among the generation's program resources already (`Owners::buffer`), which the -//! recovery reads ([`Carry::take`]), so making one costs a load of a flag more and no lock. -//! - **Carried before the next generation serves.** The recovery takes the lost generation's live -//! objects ([`Carry::take`]) and carries each to the new one before the line serves it -//! ([`Device::carry_to`]), so no call meets the device half carried; a call that waits for the -//! recovery meets every object carried. -//! - **None left behind.** A call that took its arguments before the loss completes on the lost -//! generation (`Device::at_serving_taking`), and what it makes after the recovery took the -//! generation's objects its maker carries ([`Device::carry_late`]). The take names the buffers -//! it took under the registry's lock, which a maker that finds the generation taken asks -//! ([`Carry::late_buffer`]), and an event or heap is kept under it, so each object is carried -//! once, by one or the other; a texture's maker sets how it is made again before it asks -//! ([`Carry::late_texture`]), and a texture carried already is carried no more. A buffer placed in a heap as the heap is carried finds its bytes -//! carried under the lock the heap's carry takes its buffers under, and carries itself -//! (`Heap::carry`). -//! - **What each kind becomes.** An event: a new timeline semaphore at the value the host saw -//! (`EventShared::carry`). A `Private` buffer: new memory, its contents lost with the -//! `VkDevice` (it reads zero); but one in exportable memory, which another API imports -//! (`exported_memory.rs`): its block's payload, exported once from the lost `VkDevice` and kept, -//! imported again once for every buffer carried from the block, the buffer at its offset there, -//! the memory the other API's imports reach still, which it reads as it holds it (an -//! exportable buffer re-imported over its own memory keeps whatever that memory holds). A buffer in fresh pages (`fresh_pages.rs`): the same pages -//! imported again, its contents and its `contents` pointer as they were (`Buffer::carry`). A -//! `Shared` or `Managed` buffer in a block of the runtime's own pages (`memory.rs`'s -//! `Holds::PageBuffers`): the block's pages imported again, once for every buffer carried from -//! it, the buffer at its offset there, its contents and `contents` pointer as they were. A -//! no-copy buffer: made again over the caller's pages it lies in, of the memory they were given -//! as (`HostPages::made_of`), as its making or last rebind made it there (the caller's gate and -//! resolver of guest RAM runs asked again, on the recovering thread), its contents and -//! `contents` pointer as they were; its deallocator and keep-alive wait for its release there -//! and for its pages' import on each generation to be freed (`Release::carry_on`). A use of -//! guest RAM (`HostRamUse`), before the buffers: made again on the new device, the lost one's -//! let go of. Each buffer keeps its identity: its `ObjectId`, hazard key, Metal address (a -//! share of its range) and range token, its label and purgeable state. A `Private` heap, after -//! the buffers: its own buffer in new memory where its textures can lie too, its contents lost -//! (it reads zero); a heap over the caller's memory, its own buffer made again over the same -//! pages as a no-copy buffer is, its bytes as they are; either's identity kept as a buffer's, -//! registered there by its key; each buffer -//! placed in it that lives, the same buffer there at its offset in the heap's carried bytes, -//! its identity and aliasable state kept, its range in an automatic heap given back once, by its -//! parts on the generation it was carried to last (`Heap::carry`, `Buffer::carry_placed`). A -//! texture, after the heaps: its call made again there as a texture of the runtime's own, which -//! holds its parts there, a view's after its parent's, a heap's at its range of the heap -//! carried; a texture of its own image's contents (a `Private` heap's too) lost whatever its -//! storage mode, as its image in the lost `VkDevice`'s memory was their only copy, one placed in -//! a heap over the caller's memory reading the pages, one over a carried buffer (a texture buffer of `Device::new_texture` over its texels' -//! buffer too) reading the buffer's bytes; its identity, resource ID, label and purgeable state -//! kept (`Texture::carry`). A pipeline state, after the textures, the compute and tile states -//! first, then the drawing ones: its base variant's objects (and a drawing state's -//! large-buffer form's) made there from the pipeline its creation compiled, so nothing is -//! translated again, the `VkPipeline` its creation predicted queued on the making pool with no -//! wait (a drawing state's neutrals and depth stand-in copies made as at its creation); the -//! lost generation's memo of compiled pipelines taken first where both generations compile -//! alike (`PipelineMemo::carry_from`), where alone a state is made again; its identity, ID, -//! `uniqueIdentifier` and label kept (`ComputePipelineState::carry`, `GraphicsState::carry`). -//! One whose making there failed stays the lost generation's, refused where bound -//! (`RuntimeGap::RemadeAfterRecoveryFailed`). A sampler state, first after the handles: its -//! handle of the device linked to the new generation's, the `VkSampler`s it kept forgotten (its -//! binds make them there as they need them), and the state placed there as at its making, in -//! every heap set and sampler table and in the map of live states an equal request shares; its -//! descriptor, resource ID and element kept (`SamplerState::carry`), its placement on the lost -//! generation taken out at that generation's rest. Where the generations compile otherwise, it -//! stays the lost generation's. -//! - **The bytes kept are the pages'.** A buffer or texture carried with its contents reads the -//! pages it lies in, imported again. Vulkan makes the content of external memory imported to a -//! lost device undefined (vkspec 5.2.3, "Lost Device"): read here as the hung work's writes, -//! which may have landed in part, as a hung Metal command buffer's may. Once the lost -//! generation's import is let go of, the pages are the runtime's or the caller's memory alone, -//! and the new generation reads what they hold; no promise is made about the bytes the hung -//! work was writing. -//! - **What stays the lost generation's**, refused where it meets the next -//! (`RuntimeGap::MadeBeforeRecovery`): a buffer of pooled host-visible memory (`Shared`, and -//! `Managed`) the device allocated, whose `contents` pointer is its block's mapping, which -//! Vulkan gives no way to keep over new memory (where the device takes no blocks of the -//! runtime's own pages for it: it imports no host pointer, its check found that a held import -//! costs its submissions, its check of fresh pages refused what a texture over such a buffer -//! takes, one of them has not answered, or no memory type of the buffer's class takes such -//! pages; and a `Managed` buffer's host copy without unified memory); a detached no-copy -//! buffer, or one whose last detach's deallocator waits for its next rebind; a `Shared` heap, -//! whose bytes are such pooled memory (a heap's own buffer lies where its textures can, never -//! in the runtime's own pages), a detached heap over the caller's memory and a sparse heap, -//! each with the buffers and textures placed in it; a texture over the -//! caller's `VkImage`, a sparse or shareable texture, one over a buffer left, and a view of -//! each (`texture/carry.rs`); a buffer over the caller's -//! `VkBuffer`, an object of the lost `VkDevice` that only the caller can make again on the -//! new one; a `Shared` or `Managed` buffer in exported memory, whose `contents` pointer is that -//! memory's mapping, and a buffer in an opaque descriptor's dedicated allocation, whose import -//! is dedicated to a buffer "identical to the buffer associated with the imported memory" -//! (`VUID-VkMemoryDedicatedAllocateInfo-buffer-01879`), which Vulkan defines no buffer of another -//! device to be (`exported_memory.rs`); an event whose semaphore was made exportable, -//! whose importers hold the lost semaphore; and a visible function table whose pipeline state -//! stays the lost generation's (`function_table/carry.rs`). The recovery's notice counts the -//! buffers, heaps, textures and events it carried and left by kind -//! (`Degradation::DeviceRecovered`): a heap's buffers with their heap. -//! - **Each generation's work reaches its own parts** (`NoticesFor::generation`). A command buffer of the -//! lost generation may still record once the recovery carried its objects: an encoder a -//! program's thread opened before the loss, a render encoder's end on the lowering thread. -//! Inside a command buffer's work, a carried buffer or texture answers its parts of that -//! command buffer's generation while it has them there; elsewhere, those of the generation it -//! was carried to last. Such a command buffer fails as its device's lost one does. A carried event answers -//! the generation it was carried to last everywhere: a command buffer of the lost generation -//! that waits for or signals it after the carry refuses it, as its device is the next -//! generation (`Device::foreign`). A call outside command buffers' work that reaches a buffer's -//! Vulkan objects (a texture over its bytes, an export of its memory, an upload, a handle -//! handed out) holds the parts it read (`Buffer::held_parts`), and a call on a texture or a -//! pipeline state outside command buffers' work holds the object's parts (`Texture::hold`, -//! `ComputePipelineState::hold`; [`PartsCalls`]): their release at the generation's rest waits -//! for the call to end, and the call completes on the generation it began on. A handle handed -//! out (`Buffer::vk_buffer`, `Texture::vk_image`, `Event::vk_semaphore`), which the caller may -//! use while the object lives, keeps its parts, and the lost `VkDevice`, until the object goes. -//! - **The lost generation goes once nothing records on it.** A command buffer holds its queue's -//! slot on the generation from its making to its completion, or to its drop where it never -//! completed (`queue.rs`'s `Slot`); the registry knows the generation's queues' slots -//! ([`Carry::queue`]) and looks at them as the last of a queue's slots comes back once the -//! recovery took the generation's objects ([`RestWatch`]). So a generation never recovered pays -//! a load of a flag as a command buffer is made and as a queue's last slot comes back, and -//! nothing more. Once the line serves past it and no slot is held, the carried buffers' `VkBuffer`s there -//! are destroyed and their memory freed, a carried event's semaphore once no host call on it is -//! under way, and each carried object lets go of its handle of the generation ([`MadeOn`]): -//! "When a device is lost, its child objects are not implicitly destroyed and their handles are -//! still valid. Those objects must still be destroyed before their parents or the device can be -//! destroyed" (vkspec 5.2.3, "Lost Device"). Its device-level objects of work, what it keeps -//! for reuse and its kept empty blocks go then too, and no command buffer is made on it again -//! (`DeviceShared::keep_nothing`). A carried texture's parts there and a carried pipeline -//! state's program there go then too (`texture/carry.rs`, `pipeline/carry.rs`; -//! `WorkCounts::lost_textures_released`, `WorkCounts::lost_programs_released`). So a carried -//! object holds nothing of the lost generation but a handle handed out: the lost `VkDevice` -//! goes with the last object left on it (a pooled buffer, a texture or pipeline state left -//! there, a handle handed out), through the teardown every generation's goes through, and holds -//! its own objects alone meanwhile (`WorkCounts::vk_devices_live`). - -use super::{lock, Device, DeviceShared}; -use crate::buffer::Buffer; -#[cfg(unix)] -use crate::dma_buf::KeptFile; -use crate::event::EventShared; -use crate::function_table::carry::WeakFunctionTable; -use crate::function_table::VisibleFunctionTable; -use crate::heap::{Heap, WeakHeap}; -use crate::host_ram::RamUseCell; -use crate::indirect_command_buffer::carry::WeakIndirectCommandBuffer; -use crate::indirect_command_buffer::IndirectCommandBuffer; -use crate::pipeline::carry::{compiles_alike, StateCarried}; -use crate::pipeline::{ - ComputePipelineState, GraphicsState, WeakComputePipelineState, WeakRenderPipelineState, -}; -use crate::queue::Slots; -use crate::resource::ObjectId; -use crate::sampler::{SamplerShared, SamplerState}; -use crate::texture::carry::{Remade, TextureLeft, WeakTexture}; -use crate::texture::Texture; -use crate::Error; -use std::cell::UnsafeCell; -use std::collections::HashSet; -use std::convert::Infallible; -use std::mem::ManuallyDrop; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, Weak}; - -/// The least size at which the registry drops gone objects' entries. -const PRUNE_FLOOR: usize = 256; - -/// One carried object's parts on a lost generation, which it lets go of once nothing records on it -/// (the module docs): their Vulkan objects, their memory, and the object's handle of the -/// generation ([`MadeOn`]). -pub(crate) trait LostParts: Send { - /// Under the registry's lock: mark the parts let go of, so that the work of a command buffer - /// made on the generation from now on meets them nowhere. - fn mark(&self) {} - - /// Then, with no lock held: destroy their Vulkan objects, free their memory and let go of - /// the object's handle of the generation. - fn release(self: Box); -} - -/// A generation's registry of what its recovery carries, and of the carried objects' parts it lets -/// go of once none of its command buffers may record (the module docs). -#[derive(Default)] -pub(crate) struct Carry { - state: Mutex, - /// `State::taken`, read without the lock as a buffer or a command buffer is made - /// ([`Carry::taken`]), and as a queue's last slot comes back ([`RestWatch`]). - taken: Arc, -} - -#[derive(Default)] -struct State { - events: Vec>, - /// The program's uses of guest RAM (`host_ram.rs`'s `HostRamUse`), held weakly: few, so their - /// gone entries are dropped at each keeping. - ram_uses: Vec>, - /// The program's keeps of shared dma-bufs (`dma_buf/kept.rs`'s `SharedDmaBufImport`), held - /// weakly: as `ram_uses`. - #[cfg(unix)] - kept_files: Vec>, - /// The program's heaps, held weakly: as `ram_uses`. - heaps: Vec, - /// The program's textures and views (`texture/carry.rs`), held weakly, in the order they were - /// kept: a view after the texture it was made from. - textures: Vec, - /// The handles of the device that the objects holding no Vulkan object answer - /// ([`LineDevice`]), held weakly. - links: Vec>, - /// The program's compute states, tile states' kernels among them (`pipeline/carry.rs`), held - /// weakly. - compute_states: Vec, - /// The program's drawing states, mesh ones and twins among them (`pipeline/render/carry.rs`), - /// held weakly. - render_states: Vec, - /// The program's sampler states (`sampler.rs`), held weakly. - samplers: Vec>, - /// The program's indirect command buffers (`indirect_command_buffer/carry.rs`), held weakly: - /// few, so their gone entries are dropped at each keeping. - indirect_command_buffers: Vec, - /// The program's visible function tables (`function_table/carry.rs`), held weakly: as - /// `indirect_command_buffers`. - function_tables: Vec, - /// The size at which the next keeping drops the gone events' entries. - prune_at: usize, - /// The size at which the next keeping drops the gone textures' entries. - textures_prune_at: usize, - /// The size at which the next keeping drops the gone handles' entries. - links_prune_at: usize, - /// The size at which the next keeping drops the gone compute states' entries. - states_prune_at: usize, - /// The size at which the next keeping drops the gone drawing states' entries. - render_states_prune_at: usize, - /// The size at which the next keeping drops the gone sampler states' entries. - samplers_prune_at: usize, - /// The recovery took the generation's objects ([`Carry::take`]): what is kept from now on, - /// its maker carries. - taken: bool, - /// The buffers the recovery took ([`Carry::take`]), which their makers leave to it - /// ([`Carry::late_buffer`]). - took: HashSet, - /// The slots of the generation's queues, which its command buffers hold while they may - /// record ([`Carry::queue`]). - queues: Vec>, - /// The carried objects' parts on this generation, let go of once none of its command buffers - /// may record. - lost: Vec>, - /// The line serves a later generation ([`Carry::served_past`]): no call's command buffer is - /// made here any more but one that passed its loss check before the loss. - past: bool, - /// None of its command buffers recorded once the line served past it: what it keeps for reuse - /// and its device-level objects went (`DeviceShared::keep_nothing`), and no command buffer is - /// made here again ([`Carry::refuses`]). - at_rest: bool, -} - -impl State { - /// Drop the gone events' entries once the registry reached its size for that. - fn prune(&mut self) { - if self.events.len() < self.prune_at { - return; - } - self.events.retain(|event| event.strong_count() > 0); - self.prune_at = (2 * self.events.len()).max(PRUNE_FLOOR); - } - - /// Whether a command buffer of the generation holds a slot of one of its queues. - fn slot_held(&self) -> bool { - (self.queues.iter()) - .filter_map(Weak::upgrade) - .any(|slots| slots.held_any()) - } -} - -/// The live objects of a lost generation, which its recovery carries ([`Carry::take`]). -pub(crate) struct Taken { - buffers: Vec, - events: Vec>, - ram_uses: Vec>, - #[cfg(unix)] - kept_files: Vec>, - heaps: Vec, - textures: Vec, - links: Vec>, - compute_states: Vec, - render_states: Vec, - samplers: Vec, - indirect_command_buffers: Vec, - function_tables: Vec, -} - -impl Carry { - /// Whether the recovery took the generation's objects ([`Carry::take`]): one load, which a - /// maker of a buffer reads once the buffer is among the generation's program resources, and a - /// maker of a command buffer once it holds its slot. - pub(crate) fn taken(&self) -> bool { - self.taken.load(Ordering::Acquire) - } - - /// Whether the maker of `buffer`, which the program made on this generation and which is - /// among its program resources (`Owners::buffer`), carries it ([`Device::carry_late`]): the - /// recovery took the generation's objects ([`taken`](Self::taken)) and not this one. Its - /// take reads the program resources under this lock: a buffer it missed was kept there after - /// it read them, so after it set the flag, which its maker then finds set. - pub(crate) fn late_buffer(&self, buffer: &Buffer) -> bool { - let state = lock(&self.state); - state.taken && !state.took.contains(&buffer.object_id()) - } - - /// Keep `event`, made on this generation: as [`late_buffer`](Self::late_buffer). - pub(crate) fn event(&self, event: &Arc) -> bool { - let mut state = lock(&self.state); - state.prune(); - state.events.push(Arc::downgrade(event)); - state.taken - } - - /// Keep `cell`, a use of guest RAM made on this generation: as [`event`](Self::event). - pub(crate) fn ram_use(&self, cell: &Arc) -> bool { - let mut state = lock(&self.state); - state.ram_uses.retain(|cell| cell.strong_count() > 0); - state.ram_uses.push(Arc::downgrade(cell)); - state.taken - } - - /// Keep `cell`, a keep of a shared dma-buf made or carried to this generation: as - /// [`ram_use`](Self::ram_use). - #[cfg(unix)] - pub(crate) fn kept_file(&self, cell: &Arc) -> bool { - let mut state = lock(&self.state); - state.kept_files.retain(|cell| cell.strong_count() > 0); - state.kept_files.push(Arc::downgrade(cell)); - state.taken - } - - /// Keep `heap`, made on this generation: as [`ram_use`](Self::ram_use). - pub(crate) fn heap(&self, heap: &Heap) -> bool { - let mut state = lock(&self.state); - state.heaps.retain(WeakHeap::lives); - state.heaps.push(heap.downgrade()); - state.taken - } - - /// Keep `texture`, a program's texture or view on this generation, as it is made or carried - /// here (`texture/carry.rs`): as [`event`](Self::event), its gone entries dropped as the - /// registry grows. - pub(crate) fn texture(&self, texture: &Texture) -> bool { - let mut state = lock(&self.state); - if state.textures.len() >= state.textures_prune_at { - state.textures.retain(WeakTexture::lives); - state.textures_prune_at = (2 * state.textures.len()).max(PRUNE_FLOOR); - } - state.textures.push(WeakTexture::of(texture)); - state.taken - } - - /// Whether the recovery took the generation's objects, read under the lock the take sets it - /// under: a texture whose way to be made again was set before this read was in the take, its - /// way read there; one set after, its maker carries (`Device::kept_texture`). - pub(crate) fn late_texture(&self) -> bool { - lock(&self.state).taken - } - - /// Keep `state`, a compute state made or carried here (`pipeline/carry.rs`): as - /// [`event`](Self::event), its gone entries dropped as the registry grows. - pub(crate) fn compute_state(&self, state: &ComputePipelineState) -> bool { - let mut state_list = lock(&self.state); - if state_list.compute_states.len() >= state_list.states_prune_at { - state_list - .compute_states - .retain(WeakComputePipelineState::lives); - state_list.states_prune_at = (2 * state_list.compute_states.len()).max(PRUNE_FLOOR); - } - state_list.compute_states.push(state.downgrade()); - state_list.taken - } - - /// Keep `state`, a drawing state made or carried here (`pipeline/render/carry.rs`): as - /// [`compute_state`](Self::compute_state). - pub(crate) fn render_state(&self, state: &GraphicsState) -> bool { - let mut state_list = lock(&self.state); - if state_list.render_states.len() >= state_list.render_states_prune_at { - state_list - .render_states - .retain(WeakRenderPipelineState::lives); - state_list.render_states_prune_at = - (2 * state_list.render_states.len()).max(PRUNE_FLOOR); - } - state_list.render_states.push(state.downgrade()); - state_list.taken - } - - /// Keep `state`, a sampler state made or carried here (`sampler.rs`): as - /// [`compute_state`](Self::compute_state). - pub(crate) fn sampler_state(&self, state: &SamplerState) -> bool { - let mut state_list = lock(&self.state); - if state_list.samplers.len() >= state_list.samplers_prune_at { - state_list.samplers.retain(|state| state.strong_count() > 0); - state_list.samplers_prune_at = (2 * state_list.samplers.len()).max(PRUNE_FLOOR); - } - state_list.samplers.push(state.downgrade()); - state_list.taken - } - - /// Keep `icb`, an indirect command buffer made or carried here - /// (`indirect_command_buffer/carry.rs`): as [`ram_use`](Self::ram_use). - pub(crate) fn indirect_command_buffer(&self, icb: &IndirectCommandBuffer) -> bool { - let mut state = lock(&self.state); - (state.indirect_command_buffers).retain(WeakIndirectCommandBuffer::lives); - state.indirect_command_buffers.push(icb.downgrade()); - state.taken - } - - /// Keep `table`, a visible function table made or carried here (`function_table/carry.rs`): - /// as [`ram_use`](Self::ram_use). - pub(crate) fn function_table(&self, table: &VisibleFunctionTable) -> bool { - let mut state = lock(&self.state); - state.function_tables.retain(WeakFunctionTable::lives); - state.function_tables.push(table.downgrade()); - state.taken - } - - /// Keep `link`, this generation's handle of the device an object holding no Vulkan object - /// answers ([`LineDevice`]): as [`event`](Self::event), its gone entries dropped as the - /// registry grows. - fn link(&self, link: &Arc) -> bool { - let mut state = lock(&self.state); - if state.links.len() >= state.links_prune_at { - state.links.retain(|link| link.strong_count() > 0); - state.links_prune_at = (2 * state.links.len()).max(PRUNE_FLOOR); - } - state.links.push(Arc::downgrade(link)); - state.taken - } - - /// The live objects of `shared`, this generation, for its recovery to carry: its events, its - /// uses of guest RAM, its heaps and its program resources' buffers (`Owners::buffers`). From - /// now on, each one made is its maker's to carry. - fn take(&self, shared: &DeviceShared) -> Taken { - let mut state = lock(&self.state); - state.taken = true; - self.taken.store(true, Ordering::SeqCst); - let buffers = shared.owners.buffers(); - state.took = buffers.iter().map(Buffer::object_id).collect(); - Taken { - buffers, - events: state.events.iter().filter_map(Weak::upgrade).collect(), - ram_uses: state.ram_uses.iter().filter_map(Weak::upgrade).collect(), - #[cfg(unix)] - kept_files: state.kept_files.iter().filter_map(Weak::upgrade).collect(), - heaps: state.heaps.iter().filter_map(WeakHeap::upgrade).collect(), - textures: (state.textures.iter()) - .filter_map(WeakTexture::upgrade) - .collect(), - links: state.links.iter().filter_map(Weak::upgrade).collect(), - compute_states: (state.compute_states.iter()) - .filter_map(WeakComputePipelineState::upgrade) - .collect(), - render_states: (state.render_states.iter()) - .filter_map(WeakRenderPipelineState::graphics) - .collect(), - samplers: (state.samplers.iter()) - .filter_map(SamplerState::upgrade) - .collect(), - indirect_command_buffers: (state.indirect_command_buffers.iter()) - .filter_map(WeakIndirectCommandBuffer::upgrade) - .collect(), - function_tables: (state.function_tables.iter()) - .filter_map(WeakFunctionTable::upgrade) - .collect(), - } - } - - /// Know `slots`, the slots of a queue of `shared`, this generation, which its command - /// buffers hold while they may record: what watches them for the generation's rest, which a - /// queue's last slot to come back reads. - pub(crate) fn queue(&self, shared: &Arc, slots: &Arc) -> RestWatch { - let mut state = lock(&self.state); - state.queues.retain(|queue| queue.strong_count() > 0); - state.queues.push(Arc::downgrade(slots)); - RestWatch { - taken: Arc::clone(&self.taken), - generation: Arc::downgrade(shared), - } - } - - /// Whether a command buffer made on this generation, holding its slot, is refused: the - /// generation is at rest, its device-level objects of work gone ([`let_go_at_rest`]), for a - /// call that passed its loss check before the loss to refuse as on the lost device. A load of - /// a flag on a generation never recovered. The rest looks at the slots held under this lock, - /// so a command buffer that holds its slot as the generation comes to rest is either seen - /// there or sees the rest here. - /// - /// [`let_go_at_rest`]: Self::let_go_at_rest - pub(crate) fn refuses(&self) -> bool { - self.taken() && lock(&self.state).at_rest - } - - /// Whether the generation came to rest ([`let_go_at_rest`](Self::let_go_at_rest)). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn at_rest(&self) -> bool { - lock(&self.state).at_rest - } - - /// A carried object's `parts` on `shared`, this generation, let go of once none of its - /// command buffers may record: here where none may. - pub(crate) fn lost(&self, shared: &DeviceShared, parts: Box) { - lock(&self.state).lost.push(parts); - self.let_go_at_rest(shared); - } - - /// The line serves the generation `shared`'s recovery made, past `shared`, this one: let go - /// of what it may ([`let_go_at_rest`](Self::let_go_at_rest)). - pub(super) fn served_past(&self, shared: &DeviceShared) { - lock(&self.state).past = true; - self.let_go_at_rest(shared); - } - - /// On `shared`, this generation, once the line serves past it and none of its command - /// buffers may record: let go of the carried objects' parts, and the first time, of what it - /// keeps for reuse and its device-level objects (`DeviceShared::keep_nothing`). The parts are - /// marked under the registry's lock, which a command buffer made after that takes - /// ([`Carry::refuses`]), so its work meets none of them (`Buffer::s`), and released after - /// it. Called with none of a command buffer's locks held, by a holder of the generation. - fn let_go_at_rest(&self, shared: &DeviceShared) { - let (lost, first) = { - let mut state = lock(&self.state); - if !state.taken || !state.past || state.slot_held() { - return; - } - let mut lost = Vec::with_capacity(state.lost.len()); - for parts in state.lost.drain(..) { - parts.mark(); - lost.push(parts); - } - let first = !state.at_rest; - state.at_rest = true; - // A maker that finds the generation taken now finds it at rest: the recovery carried - // what it took before the line served past it. - state.took.clear(); - state.took.shrink_to_fit(); - (lost, first) - }; - if first { - shared.keep_nothing(); - } - for parts in lost { - parts.release(); - } - } -} - -impl DeviceShared { - /// A lost generation whose recovery carried its objects on, the line serving past it and none - /// of its command buffers left to record, on which no work is made again: its device-level - /// objects of work (the internal submissions' and the staging queue's pools, the runtime's own - /// kernels, the GPU pools' blocks, the mipmap scratch, the live buffers' table, - /// `LiveBuffers::close`), its parked buffers and images and the - /// empty blocks it keeps go, and it parks and keeps none from now on. So the objects left on - /// it hold the bare `VkDevice` and their own memory alone, and a carried object's memory there - /// goes back to the device (`Recycler::close`, `memory::keep_none`). Its teardown destroys the - /// rest, and the `VkDevice`, as ever (`DeviceShared`'s drop). Left to the process's end while - /// it exits. - fn keep_nothing(&self) { - let Some(_busy) = crate::exit_guard::enter() else { - return; - }; - // Its queues idle, each under its lock: its submission checks' thread may submit there - // still (`DeviceShared::queues_idle`). - self.queues_idle(); - // Before the recycler closes: the table's buffers park there, and go with it. - self.live_buffers.close(); - if let Some(internal) = lock(&self.internal).take() { - internal.destroy(self.vk()); - } - if let Some(staging) = &self.staging { - staging.destroy(self.vk()); - } - lock(&self.owned_kernels).destroy(self.vk()); - lock(&self.mipmap_scratch).destroy(self.vk(), &mut lock(&self.memory)); - self.gpu_pools.destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.recycled_buffers).close(self.vk(), &mut lock(&self.memory)); - lock(&self.textures.recycled).close(self.vk(), &mut lock(&self.memory)); - crate::memory::keep_none(&self.memory, self.vk()); - } -} - -/// What a queue's slots on a generation read as the last of them comes back (`queue.rs`'s -/// `Slot`): whether the recovery took the generation's objects, and if so, the generation, to let -/// go of the carried objects' parts there where no slot of its queues is held now -/// ([`Carry::let_go_at_rest`]). -pub(crate) struct RestWatch { - taken: Arc, - generation: Weak, -} - -impl RestWatch { - /// The last of the queue's slots came back, with no lock of the queue's held: a load of a - /// flag on a generation never recovered. - pub(crate) fn last_slot_back(&self) { - if !self.taken.load(Ordering::Acquire) { - return; - } - if let Some(shared) = self.generation.upgrade() { - shared.carry.let_go_at_rest(&shared); - } - } -} - -/// Why a buffer stays the lost generation's ([`Buffer::carry`]; the module docs). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Left { - /// Its bytes are pooled host-visible memory (`Shared`, `Managed`), its `contents` pointer its - /// block's mapping. - Pooled, - /// A no-copy buffer detached from the caller's pages, or whose last detach's deallocator - /// waits for its next rebind. - NoCopy, - /// A heap's buffer, which its heap's carry carries or leaves (`Heap::carry`). - Heap, - /// Over the caller's `VkBuffer` (`wrapped_buffer.rs`), which is an object of the lost - /// `VkDevice`, made by the caller. - Caller, - /// A `Shared` or `Managed` buffer in memory another API imports (`exported_memory.rs`), - /// allocated exportable on the lost `VkDevice`, its `contents` pointer that memory's mapping. - Exported, - /// Its making on the new generation failed (out of memory, the driver's refusal). - Failed, - /// A buffer whose memory another API imports as an opaque descriptor, which is the buffer's - /// dedicated allocation (`exported_memory.rs`): an import of it is dedicated to a buffer - /// "identical to the buffer associated with the imported memory" - /// (`VUID-VkMemoryDedicatedAllocateInfo-buffer-01879`), and Vulkan defines no buffer of - /// another device so. - #[cfg(unix)] - DedicatedOpaqueFd, -} - -/// Why a heap stays the lost generation's, with the buffers placed in it (`Heap::carry`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum HeapLeft { - /// A `Shared` heap: its bytes are pooled host-visible memory, whose mapping its buffers' - /// `contents` pointers are, as a pooled buffer's ([`Left::Pooled`]). - Pooled, - /// A heap over the caller's host memory (`Device::new_heap_with_bytes_no_copy`). - NoCopy, - /// A sparse heap, whose textures' tiles the lost `VkDevice` bound. - Sparse, - /// Its making on the new generation failed. - Failed, -} - -impl HeapLeft { - /// Why a heap stays, its own buffer's carry having answered `left`. - pub(crate) fn of(left: Left) -> HeapLeft { - match left { - Left::Pooled => HeapLeft::Pooled, - Left::NoCopy => HeapLeft::NoCopy, - Left::Heap | Left::Caller | Left::Exported | Left::Failed => HeapLeft::Failed, - #[cfg(unix)] - Left::DedicatedOpaqueFd => HeapLeft::Failed, - } - } -} - -/// What the carry of a buffer did with its contents ([`Buffer::carry`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Contents { - /// They are where they were: the same pages, imported again. - Kept, - /// Lost with the `VkDevice`: these bytes of new memory, which read zero. - Lost(u64), -} - -/// What one recovery carried, for its notice (`line.rs`). -#[derive(Default)] -pub(crate) struct Carried { - events: u64, - /// The buffers whose contents were kept. - kept: u64, - /// The buffers whose contents were lost, and their bytes. - lost: (u64, u64), - /// The events left the lost generation's: their semaphores were made exportable. - events_left: u64, - /// The uses of guest RAM carried, and those the new generation refused. - ram_uses: (u64, u64), - /// The buffers left the lost generation's, by why. - left: [u64; 7], - /// The `Private` heaps carried, their bytes, which read zero, and the buffers placed in them - /// carried with them. - heaps: (u64, u64, u64), - /// The heaps over the caller's memory carried over the same pages, and the buffers placed in - /// them carried with them. - host_heaps: (u64, u64), - /// The heaps left the lost generation's, by why. - heaps_left: [u64; 4], - /// The textures carried, by what was made again ([`Remade`]): those whose contents were lost - /// by storage mode, then those over carried buffers, views, and those placed in heaps over - /// the caller's memory. - textures: [u64; 6], - /// The textures left the lost generation's, by why. - textures_left: [u64; 7], - /// The pipeline states made again there, and those whose making there failed. - states: (u64, u64), - /// The sampler states carried, and those left the lost generation's: it compiles otherwise. - samplers: (u64, u64), - /// The indirect command buffers carried with their records, those whose records were lost, - /// and those left the lost generation's. - indirect_command_buffers: (u64, u64, u64), - /// The visible function tables carried, and those left the lost generation's. - function_tables: (u64, u64), -} - -impl Carried { - /// The objects carried and left, as the recovery's notice says them: the pooled buffers - /// left always, every other kind left where some was, and the uses of guest RAM where any - /// lived. - pub(crate) fn say(&self) -> String { - let (lost, lost_bytes) = self.lost; - let (ram_uses, ram_uses_left) = self.ram_uses; - let kinds = [ - "pooled `Shared` or `Managed` buffers", - "detached no-copy buffers", - "heaps' buffers", - "buffers over the caller's `VkBuffer`", - "`Shared` or `Managed` buffers in exportable memory", - "buffers whose making there failed", - "buffers in a dedicated opaque-fd allocation (Vulkan defines no identical buffer on \ - another device)", - ]; - let heap_kinds = [ - "`Shared` heaps", - "no-copy heaps", - "sparse heaps", - "heaps whose making there failed", - ]; - let texture_kinds = [ - "heaps' textures", - "textures over the caller's `VkImage`", - "sparse textures", - "shareable textures", - "textures over the buffers left", - "textures whose making there failed", - "textures of calls no recovery makes again", - ]; - let left = (kinds.iter().zip(self.left).enumerate()) - .filter(|&(at, (_, count))| at == Left::Pooled as usize || count > 0) - .map(|(_, (kind, count))| format!("{count} {kind}")) - .chain( - (heap_kinds.iter().zip(self.heaps_left)) - .filter(|&(_, count)| count > 0) - .map(|(kind, count)| format!("{count} {kind}")), - ) - .chain( - (texture_kinds.iter().zip(self.textures_left)) - .filter(|&(_, count)| count > 0) - .map(|(kind, count)| format!("{count} {kind}")), - ) - .chain( - (self.events_left > 0) - .then(|| format!("{} events made exportable", self.events_left)), - ) - .chain( - (ram_uses_left > 0) - .then(|| format!("{ram_uses_left} guest RAM uses the new device refused")), - ) - .chain((self.samplers.1 > 0).then(|| { - format!( - "{} sampler states of a device that compiles otherwise", - self.samplers.1 - ) - })) - .chain((self.indirect_command_buffers.2 > 0).then(|| { - format!( - "{} indirect command buffers whose making there failed", - self.indirect_command_buffers.2 - ) - })) - .chain((self.function_tables.1 > 0).then(|| { - format!( - "{} visible function tables of states left or whose making there failed", - self.function_tables.1 - ) - })) - .collect::>() - .join(", "); - let ram = match ram_uses { - 0 => String::new(), - _ => format!("{ram_uses} guest RAM uses, "), - }; - let heaps = match self.heaps { - (0, ..) => String::new(), - (heaps, bytes, buffers) => format!( - ", and {heaps} `Private` heaps ({bytes} bytes) with the {buffers} buffers placed \ - in them, whose contents were lost too" - ), - }; - let host_heaps = match self.host_heaps { - (0, _) => String::new(), - (heaps, buffers) => format!( - ", and {heaps} no-copy heaps with the {buffers} buffers placed in them, over the \ - same pages (their contents kept)" - ), - }; - let textures = match self.textures { - [0, 0, 0, 0, 0, 0] => String::new(), - [shared, managed, private, over, views, in_host_heaps] => format!( - ", and {} textures whose contents were lost too (they read as new ones: {shared} \ - `Shared`, {managed} `Managed`, {private} `Private` or memoryless), {over} \ - textures over the buffers carried, {in_host_heaps} textures placed in the \ - no-copy heaps carried and {views} texture views", - shared + managed + private - ), - }; - let states = match self.states { - (0, 0) => String::new(), - (made, failed) => format!( - ", and {made} pipeline states made again (their predicted pipelines queued), \ - {failed} more whose making there failed (refused where bound: \ - `RemadeAfterRecoveryFailed`)" - ), - }; - let samplers = match self.samplers.0 { - 0 => String::new(), - carried => format!(", and {carried} sampler states"), - }; - let icbs = match self.indirect_command_buffers { - (0, 0, _) => String::new(), - (kept, lost, _) => format!( - ", and {} indirect command buffers, {lost} of them whose records were lost (every \ - command reset)", - kept + lost - ), - }; - let tables = match self.function_tables.0 { - 0 => String::new(), - carried => format!(", and {carried} visible function tables with their entries"), - }; - format!( - "it carried {} events, {ram}{} buffers with their contents and {lost} `Private` \ - buffers ({lost_bytes} bytes) whose contents were lost (they read zero){heaps}\ - {host_heaps}{textures}{states}{samplers}{icbs}{tables}; left refused \ - (`MadeBeforeRecovery`): \ - {left}", - self.events, self.kept - ) - } - - /// One buffer's carry. - fn buffer(&mut self, carried: Result) { - match carried { - Ok(Contents::Kept) => self.kept += 1, - Ok(Contents::Lost(bytes)) => { - self.lost.0 += 1; - self.lost.1 += bytes; - } - Err(left) => self.left[left as usize] += 1, - } - } - - /// One heap's carry: its bytes and the buffers placed in it carried, or why it was left. - fn heap(&mut self, carried: Result, HeapLeft>) { - match carried { - Ok(Some((Contents::Lost(bytes), buffers))) => { - self.heaps.0 += 1; - self.heaps.1 += bytes; - self.heaps.2 += buffers; - } - Ok(Some((Contents::Kept, buffers))) => { - self.host_heaps.0 += 1; - self.host_heaps.1 += buffers; - } - Ok(None) => {} - Err(left) => self.heaps_left[left as usize] += 1, - } - } - - /// One texture's carry: what was made again, or why it was left. - fn texture(&mut self, carried: Result, TextureLeft>) { - match carried { - Ok(Some(remade)) => self.textures[remade as usize] += 1, - Ok(None) => {} - Err(left) => self.textures_left[left as usize] += 1, - } - } - - /// One pipeline state's carry. - fn state(&mut self, carried: StateCarried) { - match carried { - Some(Ok(())) => self.states.0 += 1, - Some(Err(_)) => self.states.1 += 1, - None => {} - } - } - - /// One indirect command buffer's carry. - fn indirect_command_buffer(&mut self, carried: Result) { - match carried { - Ok(Contents::Kept) => self.indirect_command_buffers.0 += 1, - Ok(Contents::Lost(_)) => self.indirect_command_buffers.1 += 1, - Err(_) => self.indirect_command_buffers.2 += 1, - } - } - - /// One visible function table's carry. - fn function_table(&mut self, carried: Result) { - match carried { - Ok(_) => self.function_tables.0 += 1, - Err(_) => self.function_tables.1 += 1, - } - } - - /// One sampler state's carry. - fn sampler(&mut self, carried: Option) { - match carried { - Some(true) => self.samplers.0 += 1, - Some(false) => self.samplers.1 += 1, - None => {} - } - } - - /// One event's carry. - fn event(&mut self, carried: Result<(), Error>) { - match carried { - Ok(()) => self.events += 1, - Err(_) => self.events_left += 1, - } - } - - /// One use of guest RAM's carry. - fn ram_use(&mut self, carried: Result<(), Error>) { - match carried { - Ok(()) => self.ram_uses.0 += 1, - Err(_) => self.ram_uses.1 += 1, - } - } -} - -impl Device { - /// Carry this generation's live events, buffers and heaps, lost, to `next`, the generation - /// its recovery made, before `next` serves (the module docs): what was carried and left, for - /// the recovery's notice. - pub(super) fn carry_to(&self, next: &Device) -> Carried { - let shared = self.shared(); - let Taken { - buffers, - events, - ram_uses, - #[cfg(unix)] - kept_files, - heaps, - textures, - links, - compute_states, - render_states, - samplers, - indirect_command_buffers, - function_tables, - } = shared.carry.take(shared); - for link in &links { - link.carry(next); - } - // A map of no layers made after a map of layers was released is one whose passes Metal - // draws from the memory it left, before the recovery or after (`rate_map.rs`). - if shared.layered_rate_map_released.load(Ordering::Relaxed) { - (next.shared().layered_rate_map_released).store(true, Ordering::Relaxed); - } - let mut carried = Carried::default(); - // The sampler states: each placed there as at its making (`sampler.rs`). - for state in &samplers { - carried.sampler(state.carry(next)); - } - // The lost generation's compiled functions and pipelines, the next's too where both - // compile alike: a creation there, or a state's remaking, translates nothing again. - if compiles_alike(self, next) { - next.shared() - .shader_cache - .memo - .carry_from(&shared.shader_cache.memo); - } - for event in &events { - carried.event(event.carry(next)); - } - // Before the buffers: a no-copy buffer over a piece of a kept file imports it kept there. - #[cfg(unix)] - for cell in &kept_files { - cell.carry(next); - } - // Before the buffers: a no-copy buffer over a RAM's pages lies in its chunks there. - for cell in &ram_uses { - carried.ram_use(cell.carry(next)); - } - for buffer in &buffers { - carried.buffer(buffer.carry(next)); - } - for heap in &heaps { - carried.heap(heap.carry(next)); - } - // After the buffers, which textures lie over; the textures before the views of them, as - // they were kept (a view's carry carries its parent where it was not). - for texture in &textures { - carried.texture(texture.carry(next)); - } - // The compute states, tile states' kernels among them: each its base variant's objects - // made there from its compiled pipeline (`pipeline/carry.rs`). - for state in &compute_states { - carried.state(state.carry(next)); - } - // Then the drawing states, mesh ones and twins among them, alike - // (`pipeline/render/carry.rs`). - for state in &render_states { - carried.state(state.carry(next)); - } - // After the states: the programs their commands run, and the tables' states, are there. - for icb in &indirect_command_buffers { - carried.indirect_command_buffer(icb.carry(next)); - } - for table in &function_tables { - carried.function_table(table.carry(next)); - } - carried - } - - /// Carry an object made on this generation after its recovery took the generation's objects - /// (`Carry::late_buffer`, `Carry::event`) with `carry`, to the generation that serves once that - /// recovery made it (the module docs). Nothing where no later generation serves: a line that - /// cannot recover, or a thread command buffers' completion depends on, whose calls reach the - /// lost generation (`Line::current`). - pub(crate) fn carry_late(&self, carry: impl FnOnce(&Device) -> Result) { - let serving = self.line().current(self); - if serving.same(self) { - return; - } - // A refusal leaves the object the lost generation's, refused where it meets the next. - let _carried = carry(&serving); - } -} - -/// The device of an object a recovery may carry (a buffer, its pages, an event): the generation it -/// was made on, as every object's device is, until the object's parts there were let go of -/// (`Carry::lost`); then let go of itself ([`LetGo::let_go`]), so a carried object holds the lost -/// generation no longer and that generation goes with the objects left on it (the module docs). -/// Read as a [`Device`] at one indirection, as the field it stands for. No borrow of it reaches -/// the program, which may hold one past the generation's rest: an object's `device` answers a -/// clone. -pub(crate) type MadeOn = LetGo; - -/// A carried object's part on one generation (its device handle, [`MadeOn`]; a pipeline state's -/// program there, `pipeline/carry.rs`; a texture's parts there, `texture/carry.rs`): the object's -/// own, read in place at one indirection as the field it stands for, until its parts on that -/// generation were let go of at the generation's rest (`Carry::lost`); then dropped in place -/// ([`let_go`](Self::let_go)), the object living on, and read no more: every reach of the object -/// from then on goes to where it was carried, and the work of a command buffer of the generation -/// meets it nowhere ([`gone`](Self::gone)). -pub(crate) struct LetGo { - value: UnsafeCell>, - /// It was let go of. - gone: AtomicBool, -} - -// SAFETY: it is a `T`, which is `Send` and `Sync`, read through shared references, and let go of -// once, when nothing reads it any more (`LetGo::let_go`'s contract). -unsafe impl Sync for LetGo {} - -impl LetGo { - /// `value`, held until it is let go of. - pub(crate) fn new(value: T) -> LetGo { - LetGo { - value: UnsafeCell::new(ManuallyDrop::new(value)), - gone: AtomicBool::new(false), - } - } - - /// Whether it was let go of: the object's parts on the generation went, the object carried. - pub(crate) fn gone(&self) -> bool { - self.gone.load(Ordering::Acquire) - } - - /// Let go of it, once. - /// - /// # Safety - /// - /// Nothing reads it from now on but [`gone`](Self::gone): its object's parts on the - /// generation were let go of and no work of the generation's reaches them - /// (`Carry::let_go_at_rest`), no call under way holds them (`PartsCalls`), and every other - /// reach of the object goes to where it was carried. - pub(crate) unsafe fn let_go(&self) { - if self.gone.swap(true, Ordering::AcqRel) { - return; - } - // SAFETY: the caller's: no reference to the value is left, and none is taken again. - unsafe { ManuallyDrop::drop(&mut *self.value.get()) }; - } -} - -impl std::ops::Deref for LetGo { - type Target = T; - - #[inline(always)] - fn deref(&self) -> &T { - // SAFETY: it lives until `let_go`, after which nothing reads it (its contract). - unsafe { &*self.value.get() } - } -} - -impl Drop for LetGo { - fn drop(&mut self) { - if !*self.gone.get_mut() { - // SAFETY: not let go of, and the last reference. - unsafe { ManuallyDrop::drop(self.value.get_mut()) }; - } - } -} - -/// The calls outside command buffers' work under way on a carried object's parts (a buffer's on -/// one generation, `Buffer::held_parts`; a pipeline state's programs, `pipeline/carry.rs`; a -/// texture's, `texture/carry.rs`), and the releases of its parts on lost generations that wait for -/// them to end: the parts a call reached stay while it is under way, and the last call to end lets -/// go of those whose generation came to rest meanwhile ([`CallHold`]). A command buffer's work -/// holds no call: its queue slot holds its generation, whose rest waits for it (the module docs). -#[derive(Default)] -pub(crate) struct PartsCalls(Mutex); - -#[derive(Default)] -struct Calls { - under_way: usize, - waiting: Vec>, -} - -impl PartsCalls { - /// A call on the parts from now until the hold goes: none where `released`, read under the - /// lock their release takes, answers that the parts were marked let go of (`LostParts::mark`) - /// and no call under way holds their release back (one this thread is inside, say); else - /// their release waits for the call to end. - pub(crate) fn hold_unless(&self, released: impl FnOnce() -> bool) -> Option> { - let mut calls = lock(&self.0); - if calls.under_way == 0 && released() { - return None; - } - calls.under_way += 1; - Some(CallHold(self)) - } - - /// A call on whichever of the parts it reaches from now until the hold goes: those of the - /// generation the object was carried to last, never let go of, or those it reached before a - /// carry, whose release waits for the call to end. - pub(crate) fn hold(&self) -> CallHold<'_> { - lock(&self.0).under_way += 1; - CallHold(self) - } - - /// `parts`, back to their release to let go of now, where no call is under way on the - /// object's parts; else none, the parts kept for the last call under way to let go of as it - /// ends ([`CallHold`]). - pub(crate) fn unless_held(&self, parts: Box

) -> Option> { - let mut calls = lock(&self.0); - if calls.under_way > 0 { - calls.waiting.push(parts); - return None; - } - Some(parts) - } -} - -/// A call under way on a carried object's parts ([`PartsCalls`]), until it goes: the last to go -/// lets go of the parts whose release waited for it, unless one began since. -pub(crate) struct CallHold<'a>(&'a PartsCalls); - -impl Drop for CallHold<'_> { - fn drop(&mut self) { - let waiting = { - let mut calls = lock(&self.0 .0); - calls.under_way -= 1; - match calls.under_way { - 0 => std::mem::take(&mut calls.waiting), - _ => Vec::new(), - } - }; - for lost in waiting { - lost.release(); - } - } -} - -/// The device of an object that holds no Vulkan object (a fence, a depth/stencil state, a library -/// and its functions, an address pool, a dynamic library, a binary archive, a rasterization rate -/// map, an argument encoder), which a recovery carries as its handle of the device -/// alone: a root handle, which the object's own calls and checks go through -/// ([`root`](Self::root): of whatever generation serves, matched by its line), and the generation -/// handle its `device` answers ([`generation`](Self::generation)): the generation it was made on, -/// then each one the device's recoveries carried it to. A handle taken of it keeps meaning that -/// generation, as any object's device does: its raw handles are that generation's `VkDevice`'s, -/// kept alive while the caller holds it. The object lets go of a lost generation's handle at that -/// generation's rest ([`MadeOn`]), so it holds nothing of it after. -#[derive(Clone)] -pub(crate) struct LineDevice { - root: Device, - first: Arc, -} - -/// One generation's handle of a [`LineDevice`], linked to the next generation's once a recovery -/// carried the object there. -pub(crate) struct GenerationLink { - device: MadeOn, - next: OnceLock>, -} - -impl LineDevice { - /// The device of an object made on `made_on`, a generation handle: its handle kept by the - /// generation's registry for its recovery to carry ([`Carry::take`]), or carried by its maker - /// where the recovery took the generation's objects before then ([`Device::carry_late`]). - pub(crate) fn new(made_on: &Device) -> LineDevice { - LineDevice { - root: made_on.root(), - first: GenerationLink::kept(made_on), - } - } - - /// The device of an object made on `made_on` whose own carry carries its handle, as it does - /// more there than carry the handle (a sampler state, `sampler.rs`): as [`new`](Self::new), - /// kept by no registry ([`link_unkept`](Self::link_unkept)). - pub(crate) fn unkept(made_on: &Device) -> LineDevice { - LineDevice { - root: made_on.root(), - first: GenerationLink::unkept(made_on), - } - } - - /// The root handle: of whatever generation serves, as the object is no generation's. - pub(crate) fn root(&self) -> &Device { - &self.root - } - - /// The generation handle of the generation the object was carried to last, else of the one - /// it was made on. - pub(crate) fn generation(&self) -> &Device { - &self.last().device - } - - /// The link of the generation the object was carried to last, else of the one it was made on. - fn last(&self) -> &Arc { - let mut link = &self.first; - while let Some(next) = link.next.get() { - link = next; - } - link - } - - /// Link an [`unkept`](Self::unkept) handle to `to`, the generation a recovery made, after the - /// last: the lost generation's handle, to hand that generation's registry (`Carry::lost`) with - /// no lock of the object's held, which lets go of it at the generation's rest. `None` where it - /// was linked there already, or another carry linked one first. - pub(crate) fn link_unkept(&self, to: &Device) -> Option> { - let last = self.last(); - if last.device.same(to) || last.next.set(GenerationLink::unkept(to)).is_err() { - return None; - } - Some(Box::new(LostHandle(Arc::clone(last)))) - } -} - -impl std::fmt::Debug for LineDevice { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.generation().fmt(f) - } -} - -impl GenerationLink { - /// `device`'s handle, a generation handle, kept by its generation's registry; carried by - /// this maker where that generation's recovery took its objects before. - fn kept(device: &Device) -> Arc { - let link = GenerationLink::unkept(device); - if device.shared().carry.link(&link) { - device.carry_late(|serving| { - link.carry(serving); - Ok::<(), Infallible>(()) - }); - } - link - } - - /// `device`'s handle, a generation handle, kept by no registry. - fn unkept(device: &Device) -> Arc { - Arc::new(GenerationLink { - device: MadeOn::new(device.clone()), - next: OnceLock::new(), - }) - } - - /// Carry the handle to `to`, the generation this one's recovery made: `to`'s handle linked - /// after it, and this one let go of at the lost generation's rest. Nothing where it was - /// carried already. - fn carry(self: &Arc, to: &Device) { - if self.next.get().is_some() { - return; - } - if self.next.set(GenerationLink::kept(to)).is_err() { - // Another carry of it came first. - return; - } - let lost = Device::clone(&self.device); - let parts = Box::new(LostHandle(Arc::clone(self))); - lost.shared().carry.lost(lost.shared(), parts); - } -} - -/// A [`LineDevice`]'s handle of a lost generation, let go of once none of the generation's command -/// buffers may record. -struct LostHandle(Arc); - -impl LostParts for LostHandle { - fn release(self: Box) { - // SAFETY: its next link is set, so the object's device answers a later generation's handle - // (`LineDevice::generation`), and its own calls and checks go through its root handle or - // that later one: no reach of the object reads this handle any more. - unsafe { self.0.device.let_go() }; - } -} diff --git a/crates/metal2vulkan-runtime/src/device/compiles.rs b/crates/metal2vulkan-runtime/src/device/compiles.rs deleted file mode 100644 index 17f28ab6c..000000000 --- a/crates/metal2vulkan-runtime/src/device/compiles.rs +++ /dev/null @@ -1,993 +0,0 @@ -//! The device's pipeline makings at the user-initiated class (a concurrency change). MoltenVK -//! compiles a pipeline's shaders on a dispatch queue that takes the class of the thread asking. A -//! pipeline made on a thread at the default class or below therefore compiles at that class in -//! Metal's compiler service, behind the host's busier threads. So each `vkCreateGraphicsPipelines` -//! and `vkCreateComputePipelines` the runtime makes on a device runs at the user-initiated quality -//! of service or above, whichever thread asks: -//! -//! - **One door.** The device's functions, as made or adopted (`Device::assemble`), hold this -//! module's two entry points in place of the driver's ([`route`]), and so does the exit guard's -//! table made from them (`functions.rs`, [`entry`]). Every pipeline the runtime makes on the -//! device comes here, priming's too. Each entry point finds its device's own and calls it. -//! - **On a stack with room.** A driver compiles on the thread that makes the call, and its -//! compiler can take more stack than a thread has: ANV's on the Iris Xe recurses about 80 bytes -//! deep for each value of a chain of dependent values (a kernel of a 40,000-value chain -//! overflowed a pool thread's 2 MiB at 25,972 frames and 2.09 MB, and takes about 3.2 MB), and -//! compiles the device's priming kernel inside its making (`prime.rs`), on the thread that makes -//! the device. Metal compiles in a service of its own, so no program's stack takes its compiles. -//! A call runs on the asking thread only where its stack has [`COMPILE_ROOM`] left -//! (`this_thread::stack_room`): a program's main thread on Linux or macOS, and the pipeline -//! pool's threads, started with [`COMPILE_STACK`]. A thread with less (a Rust thread's 2 MiB, a -//! macOS secondary thread's 512 KiB, a Windows main thread's 1 MiB) or where the system does -//! not say hands the call to a thread of the runtime's own, as below, started with -//! [`COMPILE_STACK`]. -//! - **On the asking thread at that class**: a thread of the pipeline pool's (`pipeline/pool.rs`), -//! or a program's thread at the user-initiated or user-interactive class, its stack with room. -//! - **Else on a thread of the runtime's own, the asking thread waiting** ([`at_user_initiated`]): -//! a thread started for the call at the user-initiated class, with [`COMPILE_STACK`]. It makes -//! the one Vulkan call with the asking thread's arguments, hands back its result, and is joined -//! before the call returns (a full join). Nothing else is done there: what to make, in what -//! order, and what the program sees are decided on the asking thread, before and after. The -//! asking thread's class, overrides and scheduling stay as found. -//! - **The driver's measured diagnostics.** The driver reports a message on the thread that makes -//! the call, and the diagnostics the asking thread's call is measured to report are withheld -//! inside that call alone (`driver_facts.rs`). So the thread takes the asking thread's -//! expectation for its one call, and the asking thread counts what it withheld. -//! - **The program's code stays on the asking thread** (the consumer's review). The only code of -//! the program's a driver call reaches is the device's message sink, which the driver's debug -//! messenger calls on the thread that makes the call (`create.rs`'s `deliver`). On the runtime's -//! thread each such message is held ([`held`]) and delivered on the asking thread once the call -//! returns, in the order raised, before the asking thread's Vulkan call returns: the sink runs -//! where it ran before, so a lock the program holds across the creation, which the sink takes -//! again, does not deadlock against the full join. A messenger the program registered itself on -//! an adopted instance is not the runtime's: the driver calls it on the thread that makes the -//! call, the runtime's here. An asking thread that itself holds its call's messages (a -//! self-check's, [`holding`]) keeps those its runtime thread held, for the self-check to read. -//! - **The exit guard.** The thread is one of the runtime's (`exit_guard::spawn_scoped`) and makes -//! the call inside a section of its own. Where the host starts no thread, or once the process is -//! exiting (the guard closed), the asking thread makes the call itself, as before. Each driver -//! call that returned, on whichever thread made it, registers the exit hook again -//! (`exit_guard::pipelines_made`), after the destructors the driver's compiler registered in it. -//! - **No compile outlives its call.** The runtime's thread is joined before the call returns -//! (`std::thread::scope`). Each device counts the calls in progress here, and in builds with -//! debug assertions the runtime's last hold of the device ([`unregister`], in the teardown just -//! before `vkDestroyDevice`) checks that none is. -//! - **The time in the driver is counted.** Each call's nanoseconds inside the driver's entry -//! point are added to its device's record, graphics and compute apart ([`driver_nanos`], -//! `WorkCounts::render_pipeline_create_nanos` and `compute_pipeline_create_nanos`). The clock is -//! read on whichever thread makes the call, just before and just after the driver's one call, so -//! a call relayed to a thread of the runtime's is counted there and none is dropped; the relay's -//! own thread start and join, which the asking thread pays, lie outside the window and are the -//! runtime's. -//! - Elsewhere than macOS there is no class: every call is made on the asking thread where its -//! stack has the room. -//! -//! The device's creation (`create.rs`) runs `vkCreateDevice` through [`at_user_initiated`] too, -//! since MoltenVK compiles its own command shaders there. The compiles MoltenVK makes inside -//! `vkQueueSubmit` stay at their caller's class. - -use crate::exit_guard::{self, Call}; -use crate::{DebugMessage, MessageSink}; -use ash::vk; -use std::cell::RefCell; -use std::ffi::{c_void, CStr}; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, PoisonError, RwLock}; - -/// A device whose pipeline makings come here: its driver's entry points, the runtime's holds of -/// it, its calls in progress, and the time they spent in the driver. -struct Driver { - device: vk::Device, - /// The runtime's devices over it: adopting one `VkDevice` twice holds it twice. - holds: usize, - graphics: vk::PFN_vkCreateGraphicsPipelines, - compute: vk::PFN_vkCreateComputePipelines, - in_progress: Arc, - nanos: Arc, -} - -/// The time a routed device's pipeline makings spent inside its driver's entry points, by call -/// ([`driver_nanos`], `WorkCounts::render_pipeline_create_nanos` and -/// `compute_pipeline_create_nanos`). One record per `VkDevice`, so a `VkDevice` the runtime holds -/// twice counts each making in both its devices' figures. -#[derive(Default)] -struct Nanos { - graphics: AtomicU64, - compute: AtomicU64, -} - -/// Every device routed here and not yet let go ([`route`], [`unregister`]). -static DRIVERS: RwLock> = RwLock::new(Vec::new()); - -/// `device`'s functions with this module's pipeline makings in place of the driver's, which it -/// keeps for the device until the runtime lets go of it ([`unregister`]). -/// -/// # Safety -/// -/// `device` is a live device, and its functions are its driver's (or its topmost layer's), not -/// already routed. -pub(super) unsafe fn route(device: ash::Device) -> ash::Device { - let handle = device.handle(); - let functions = device.fp_v1_0(); - let graphics: vk::PFN_vkCreateGraphicsPipelines = create_graphics_pipelines; - debug_assert!( - !std::ptr::fn_addr_eq(functions.create_graphics_pipelines, graphics), - "a device routed twice" - ); - { - let mut drivers = DRIVERS.write().unwrap_or_else(PoisonError::into_inner); - match drivers.iter_mut().find(|driver| driver.device == handle) { - // The same device again: the same entry points. - Some(driver) => { - driver.holds += 1; - driver.graphics = functions.create_graphics_pipelines; - driver.compute = functions.create_compute_pipelines; - } - None => drivers.push(Driver { - device: handle, - holds: 1, - graphics: functions.create_graphics_pipelines, - compute: functions.create_compute_pipelines, - in_progress: Arc::default(), - nanos: Arc::default(), - }), - } - } - let mut routed = functions.clone(); - routed.create_graphics_pipelines = create_graphics_pipelines; - routed.create_compute_pipelines = create_compute_pipelines; - ash::Device::from_parts_1_3( - handle, - routed, - device.fp_v1_1().clone(), - device.fp_v1_2().clone(), - device.fp_v1_3().clone(), - ) -} - -/// The entry point this module holds in place of the driver's `name`, if any: the exit guard's -/// table (`functions.rs`) holds it too. -pub(super) fn entry(name: &CStr) -> Option<*const c_void> { - let graphics: vk::PFN_vkCreateGraphicsPipelines = create_graphics_pipelines; - let compute: vk::PFN_vkCreateComputePipelines = create_compute_pipelines; - if name == Call::CreateGraphicsPipelines.name() { - Some(graphics as *const c_void) - } else if name == Call::CreateComputePipelines.name() { - Some(compute as *const c_void) - } else { - None - } -} - -/// The runtime lets go of one hold of `device` ([`route`]), just before it destroys the device -/// or as it stops using it; the device's record goes with its last hold. -pub(super) fn unregister(device: vk::Device) { - let mut drivers = DRIVERS.write().unwrap_or_else(PoisonError::into_inner); - let Some(at) = drivers.iter().position(|driver| driver.device == device) else { - return; - }; - drivers[at].holds -= 1; - if drivers[at].holds == 0 { - let driver = drivers.swap_remove(at); - debug_assert_eq!( - driver.in_progress.load(Ordering::SeqCst), - 0, - "a pipeline making outlived its call: its device went with it in progress" - ); - } -} - -/// Nanoseconds `device`'s pipeline makings spent inside its driver's entry points so far, graphics -/// then compute; zeroes for a device not routed (`WorkCounts::render_pipeline_create_nanos`). -pub(super) fn driver_nanos(device: vk::Device) -> (u64, u64) { - let drivers = DRIVERS.read().unwrap_or_else(PoisonError::into_inner); - match drivers.iter().find(|driver| driver.device == device) { - Some(driver) => ( - driver.nanos.graphics.load(Ordering::Relaxed), - driver.nanos.compute.load(Ordering::Relaxed), - ), - None => (0, 0), - } -} - -/// One call in progress on a routed device, counted until it returns. -struct InProgress(Arc); - -impl InProgress { - /// `device`'s driver entry points and its record of their time, with this call counted in - /// progress; none for a device not routed. - fn of( - device: vk::Device, - ) -> Option<( - vk::PFN_vkCreateGraphicsPipelines, - vk::PFN_vkCreateComputePipelines, - Arc, - InProgress, - )> { - let drivers = DRIVERS.read().unwrap_or_else(PoisonError::into_inner); - let driver = drivers.iter().find(|driver| driver.device == device)?; - driver.in_progress.fetch_add(1, Ordering::SeqCst); - Some(( - driver.graphics, - driver.compute, - Arc::clone(&driver.nanos), - InProgress(Arc::clone(&driver.in_progress)), - )) - } -} - -/// `call`, the driver's one pipeline-making call, with the nanoseconds it took added to `counter`: -/// the clock is read on whichever thread makes the call, just before and just after it, so the -/// whole of the driver's work is in the window and nothing else of the runtime's is. The pair -/// costs 27 ns on an M3 Max, against a driver's hundred microseconds and more. -fn counting(counter: &AtomicU64, call: impl FnOnce() -> R) -> R { - let entered = crate::gpu_time::host_nanos(); - let made = call(); - let taken = crate::gpu_time::host_nanos().saturating_sub(entered); - counter.fetch_add(taken, Ordering::Relaxed); - made -} - -impl Drop for InProgress { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::SeqCst); - } -} - -/// The asking thread's arguments to a call made on the runtime's thread for it: alive, and -/// untouched by the asking thread, until the call returns, since it waits for it. -pub(super) struct Sent(T); - -// SAFETY: the asking thread waits for the call that takes these, and does nothing else meanwhile -// (`at_user_initiated`): they are used on one thread at a time. -unsafe impl Send for Sent {} - -impl Sent { - /// Wrap the asking thread's arguments. - pub(super) fn new(arguments: T) -> Sent { - Sent(arguments) - } - - /// The arguments. A method, so a closure that calls it captures the whole wrapper rather than - /// its field alone. - pub(super) fn into_inner(self) -> T { - self.0 - } -} - -thread_local! { - /// The messages for the device's message sink the driver raised on this thread while it - /// makes a call for an asking thread ([`at_user_initiated`]), in order; `None` elsewhere. - static HELD: RefCell>> = const { RefCell::new(None) }; -} - -/// Whether `message`, for `sink`, is held for the asking thread: on a thread of the runtime's -/// making a call for one ([`at_user_initiated`]), which then delivers it on the asking thread -/// once the call returns (the module docs). -pub(super) fn held(sink: &MessageSink, message: &DebugMessage) -> bool { - HELD.try_with(|held| { - let Ok(mut held) = held.try_borrow_mut() else { - return false; - }; - match held.as_mut() { - Some(messages) => { - messages.push((sink.clone(), message.clone())); - true - } - None => false, - } - }) - .unwrap_or(false) -} - -/// `call`, with this thread holding the sink messages the driver raises in it ([`held`]): its -/// result, and the messages in the order raised, whichever thread made the driver call -/// ([`at_user_initiated`] holds a relayed call's messages here). A thread of the runtime's making -/// a call for an asking thread holds them for it; a self-check holds its own driver call's, whose -/// failure is the answer it asked for (`pipeline::objects::takes_multi_variable_dynamic`). A -/// holding inside another keeps the outer one's messages as they were. -pub(crate) fn holding(call: impl FnOnce() -> R) -> (R, Vec<(MessageSink, DebugMessage)>) { - type Messages = Option>; - /// Puts the outer holding back however `call` ends. - struct Restore(Messages); - impl Drop for Restore { - fn drop(&mut self) { - let outer = self.0.take(); - let _ = HELD.try_with(|held| *held.borrow_mut() = outer); - } - } - // Past this thread's thread-locals' end (a program's exit handler, `this_thread.rs`), `call` - // alone: its messages are delivered as they are raised. - let Ok(outer) = HELD.try_with(|held| held.borrow_mut().replace(Vec::new())) else { - return (call(), Vec::new()); - }; - let restore = Restore(outer); - let made = call(); - let messages = HELD - .try_with(|held| held.borrow_mut().take()) - .ok() - .flatten() - .unwrap_or_default(); - drop(restore); - (made, messages) -} - -/// The stack each thread of the runtime's own that makes a driver's compile starts with (the -/// module's **On a stack with room**): the 8 MiB the GNU C library gives a thread by default (the -/// customary `RLIMIT_STACK`), on which drivers' own compile threads run (Mesa's `util_queue`). -/// Address space alone: the system commits a stack's pages as they are touched. -pub(crate) const COMPILE_STACK: usize = 8 << 20; - -/// The room a thread's stack must have left below the asking frame for a driver's compile to run -/// on it (the module's **On a stack with room**): half of [`COMPILE_STACK`], which a Linux or macOS -/// program's main thread has. ANV's compiler on the Iris Xe recurses about 80 bytes deep for each -/// value of a chain of dependent values: a kernel of a 40,000-value chain takes about 3.2 MB of -/// it (`tests::partial_threadgroups`). -pub(crate) const COMPILE_ROOM: usize = COMPILE_STACK / 2; - -/// Run `call`, one Vulkan call that may compile, at the user-initiated quality of service or -/// above and on a stack with [`COMPILE_ROOM`] left (the module docs). It runs here where this -/// thread is at that class and its stack has that room, and otherwise on a thread of the -/// runtime's own at that class, started with [`COMPILE_STACK`], while this thread waits. It runs -/// here too where no thread starts or the process is exiting. -pub(super) fn at_user_initiated(call: impl FnOnce() -> R + Send) -> R { - let room = crate::this_thread::stack_room().is_some_and(|room| room >= COMPILE_ROOM); - if room && exit_guard::at_least_user_initiated() { - return call(); - } - // The driver diagnostics this thread's call is measured to report: the driver reports them - // on the thread that makes the call (`driver_facts.rs`). - let expected = crate::driver_facts::expected_here(); - let mut asked = Some(call); - let made = std::thread::scope(|scope| { - let taken = &mut asked; - let thread = exit_guard::spawn_scoped( - scope, - std::thread::Builder::new() - .name("metal2vulkan-compile".into()) - .stack_size(COMPILE_STACK), - move || { - exit_guard::raise_to_user_initiated(); - let _busy = exit_guard::enter()?; - let call = taken.take()?; - Some(holding(|| crate::driver_facts::expecting(expected, call))) - }, - ); - match thread { - Ok(thread) => thread - .join() - .unwrap_or_else(|panic| std::panic::resume_unwind(panic)), - Err(_) => None, - } - }); - match (made, asked) { - (Some(((made, withheld), messages)), _) => { - crate::driver_facts::withheld_for_here(withheld); - // The program's sink, on the asking thread, in the order the driver raised them: - // held again where this thread holds its call's own ([`holding`]). - for (sink, message) in messages { - if !held(&sink, &message) { - sink.deliver(&message); - } - } - made - } - (None, Some(call)) => call(), - (None, None) => unreachable!("the runtime's thread took the call and made it"), - } -} - -/// `vkCreateGraphicsPipelines` of a routed device: its driver's, at the user-initiated class. -unsafe extern "system" fn create_graphics_pipelines( - device: vk::Device, - pipeline_cache: vk::PipelineCache, - create_info_count: u32, - p_create_infos: *const vk::GraphicsPipelineCreateInfo<'_>, - p_allocator: *const vk::AllocationCallbacks<'_>, - p_pipelines: *mut vk::Pipeline, -) -> vk::Result { - let Some((driver, _, nanos, _in_progress)) = InProgress::of(device) else { - return vk::Result::ERROR_UNKNOWN; - }; - let asked = Sent::new(( - pipeline_cache, - create_info_count, - p_create_infos, - p_allocator, - p_pipelines, - )); - at_user_initiated(move || { - let (cache, count, infos, allocator, pipelines) = asked.into_inner(); - // SAFETY: the caller's arguments, alive and untouched while it waits for this call. - let made = counting(&nanos.graphics, || unsafe { - driver(device, cache, count, infos, allocator, pipelines) - }); - exit_guard::called(Call::CreateGraphicsPipelines); - exit_guard::pipelines_made(); - made - }) -} - -/// `vkCreateComputePipelines` of a routed device: its driver's, at the user-initiated class. -unsafe extern "system" fn create_compute_pipelines( - device: vk::Device, - pipeline_cache: vk::PipelineCache, - create_info_count: u32, - p_create_infos: *const vk::ComputePipelineCreateInfo<'_>, - p_allocator: *const vk::AllocationCallbacks<'_>, - p_pipelines: *mut vk::Pipeline, -) -> vk::Result { - let Some((_, driver, nanos, _in_progress)) = InProgress::of(device) else { - return vk::Result::ERROR_UNKNOWN; - }; - let asked = Sent::new(( - pipeline_cache, - create_info_count, - p_create_infos, - p_allocator, - p_pipelines, - )); - at_user_initiated(move || { - let (cache, count, infos, allocator, pipelines) = asked.into_inner(); - // SAFETY: the caller's arguments, alive and untouched while it waits for this call. - let made = counting(&nanos.compute, || unsafe { - driver(device, cache, count, infos, allocator, pipelines) - }); - exit_guard::called(Call::CreateComputePipelines); - exit_guard::pipelines_made(); - made - }) -} - -#[cfg(test)] -mod tests { - use super::{route, unregister}; - use ash::vk::{self, Handle}; - use std::cell::Cell; - use std::ffi::c_void; - - thread_local! { - /// The test's asking thread. - static ASKING: Cell = const { Cell::new(false) }; - } - - /// This thread's quality of service class (0 where there is none). - fn class() -> u32 { - #[cfg(target_os = "macos")] - { - use libc::qos_class_t as Q; - let mut class = Q::QOS_CLASS_UNSPECIFIED; - let mut relative = 0; - // SAFETY: the calling thread's own handle, and two out-parameters that live for the - // call. - let read = unsafe { - libc::pthread_get_qos_class_np(libc::pthread_self(), &mut class, &mut relative) - }; - assert_eq!(read, 0, "pthread_get_qos_class_np"); - class as u32 - } - #[cfg(not(target_os = "macos"))] - 0 - } - - /// A driver's `vkCreateGraphicsPipelines` that makes each pipeline's handle say where it ran: - /// the class of its thread, and whether that is the asking thread (bit 32). - unsafe extern "system" fn told( - _: vk::Device, - _: vk::PipelineCache, - count: u32, - _: *const vk::GraphicsPipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - pipelines: *mut vk::Pipeline, - ) -> vk::Result { - let asking = u64::from(ASKING.with(Cell::get)); - for at in 0..count as usize { - // SAFETY: the caller's array of `count` pipelines. - unsafe { - *pipelines.add(at) = vk::Pipeline::from_raw(u64::from(class()) | asking << 32) - }; - } - vk::Result::SUCCESS - } - - /// A driver's `vkCreateGraphicsPipelines` that reports MoltenVK's measured warning of a - /// dynamic restart on the thread it runs on, as MoltenVK does, and makes each pipeline's - /// handle say whether the runtime withheld it (1) or relayed it to the sink (0). - unsafe extern "system" fn reports( - _: vk::Device, - _: vk::PipelineCache, - count: u32, - _: *const vk::GraphicsPipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - pipelines: *mut vk::Pipeline, - ) -> vk::Result { - let warning = restart_warning(); - let message = crate::DebugMessage { - severity: crate::MessageSeverity::Warning, - kind: crate::MessageKind { - validation: true, - ..Default::default() - }, - id_name: warning.id_name.into(), - id: warning.id, - text: warning.text.into_owned(), - degradation: None, - }; - let withheld = u64::from(crate::driver_facts::withholds(&message)); - for at in 0..count as usize { - // SAFETY: the caller's array of `count` pipelines. - unsafe { *pipelines.add(at) = vk::Pipeline::from_raw(withheld) }; - } - vk::Result::SUCCESS - } - - /// MoltenVK's warning of a pipeline whose restart is dynamic. - fn restart_warning() -> metal2vulkan::device::DriverDiagnostic { - use metal2vulkan::vk::{DynamicState as D, PrimitiveTopology as T}; - metal2vulkan::device::DriverFact::DynamicRestartWarns - .pipeline_creation_diagnostics( - &[D::PRIMITIVE_TOPOLOGY, D::PRIMITIVE_RESTART_ENABLE], - T::TRIANGLE_LIST, - &[], - ) - .pop() - .expect("the warning of a dynamic restart") - } - - /// How long a slow driver's pipeline making spends in the driver, in nanoseconds: a sleep, so - /// the call takes at least this however loaded the host is. - const SPENT: u64 = 2_000_000; - - /// The makings of each kind [`a_making_s_time_in_the_driver_is_counted_by_the_call_it_made`] - /// asks for. - const MAKINGS: u64 = 3; - - /// Spend [`SPENT`] nanoseconds, as a driver's compile does. - fn spend() { - std::thread::sleep(std::time::Duration::from_nanos(SPENT)); - } - - /// A driver's `vkCreateGraphicsPipelines` that spends [`SPENT`] nanoseconds and makes nothing. - unsafe extern "system" fn slow_graphics( - _: vk::Device, - _: vk::PipelineCache, - _: u32, - _: *const vk::GraphicsPipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - _: *mut vk::Pipeline, - ) -> vk::Result { - spend(); - vk::Result::SUCCESS - } - - /// A driver's `vkCreateComputePipelines` that spends [`SPENT`] nanoseconds and makes nothing. - unsafe extern "system" fn slow_compute( - _: vk::Device, - _: vk::PipelineCache, - _: u32, - _: *const vk::ComputePipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - _: *mut vk::Pipeline, - ) -> vk::Result { - spend(); - vk::Result::SUCCESS - } - - /// A device of handle `handle` whose driver has both slow makings, routed. - fn routed_slow(handle: u64) -> ash::Device { - let graphics: vk::PFN_vkCreateGraphicsPipelines = slow_graphics; - let compute: vk::PFN_vkCreateComputePipelines = slow_compute; - // SAFETY: a table of the two slow makings and ash's stubs; no other entry point is called. - let driver = unsafe { - ash::Device::load_with( - |name| { - if name == c"vkCreateGraphicsPipelines" { - graphics as *const c_void - } else if name == c"vkCreateComputePipelines" { - compute as *const c_void - } else { - std::ptr::null() - } - }, - vk::Device::from_raw(handle), - ) - }; - // SAFETY: its functions are the driver's. - unsafe { route(driver) } - } - - /// The time a pipeline making spends inside the driver is counted on whichever thread makes - /// the call, and by the call it made: makings of one kind leave the other kind's figure - /// untouched, so a render-heavy run and a dispatch-heavy one are told apart. Each making here - /// sleeps [`SPENT`] nanoseconds in the driver, so the floor holds however loaded the host is; - /// a door that timed nothing would read zero for both. - #[test] - fn a_making_s_time_in_the_driver_is_counted_by_the_call_it_made() { - let device = routed_slow(0x6d32_7600_0010); - let handle = device.handle(); - assert_eq!( - super::driver_nanos(handle), - (0, 0), - "a device just routed has made nothing" - ); - let graphics_info = vk::GraphicsPipelineCreateInfo::default(); - for _ in 0..MAKINGS { - // SAFETY: the routed device's making is the slow driver's, which reads no argument. - let _ = unsafe { - device.create_graphics_pipelines(vk::PipelineCache::null(), &[graphics_info], None) - }; - } - let (graphics, compute) = super::driver_nanos(handle); - assert!( - graphics >= MAKINGS * SPENT, - "{MAKINGS} graphics makings of {SPENT} ns each read {graphics} ns" - ); - assert_eq!( - compute, 0, - "a graphics making is not counted as a compute one" - ); - let compute_info = vk::ComputePipelineCreateInfo::default(); - for _ in 0..MAKINGS { - // SAFETY: as above. - let _ = unsafe { - device.create_compute_pipelines(vk::PipelineCache::null(), &[compute_info], None) - }; - } - let (graphics_after, compute_after) = super::driver_nanos(handle); - assert!( - compute_after >= MAKINGS * SPENT, - "{MAKINGS} compute makings of {SPENT} ns each read {compute_after} ns" - ); - assert_eq!( - graphics_after, graphics, - "a compute making is not counted as a graphics one" - ); - unregister(handle); - assert_eq!( - super::driver_nanos(handle), - (0, 0), - "the record went with the device's last hold" - ); - } - - /// A device of handle `handle` whose driver has only `driver` ([`told`] or [`reports`]), - /// routed. - fn routed(handle: u64, driver: vk::PFN_vkCreateGraphicsPipelines) -> ash::Device { - // SAFETY: a table of `driver` and ash's stubs; no other entry point is called. - let driver = unsafe { - ash::Device::load_with( - |name| { - if name == c"vkCreateGraphicsPipelines" { - driver as *const c_void - } else { - std::ptr::null() - } - }, - vk::Device::from_raw(handle), - ) - }; - // SAFETY: its functions are the driver's. - unsafe { route(driver) } - } - - /// `ask`'s answer on a thread that ran `set` first and marked itself the asking thread: a - /// thread started as the runtime starts its own (`exit_guard::spawn_scoped`), standing for a - /// program's thread here, since nothing on the way to the driver asks which it is. Its stack - /// is [`COMPILE_STACK`](super::COMPILE_STACK), with the room a call made on it takes. - fn asked(set: impl FnOnce() + Send, ask: impl FnOnce() -> R + Send) -> R { - asked_on(super::COMPILE_STACK, set, ask) - } - - /// [`asked`] on a thread of `stack` bytes of stack. - fn asked_on( - stack: usize, - set: impl FnOnce() + Send, - ask: impl FnOnce() -> R + Send, - ) -> R { - std::thread::scope(|scope| { - let thread = std::thread::Builder::new().stack_size(stack); - crate::exit_guard::spawn_scoped(scope, thread, || { - set(); - ASKING.with(|asking| asking.set(true)); - ask() - }) - .unwrap() - .join() - .unwrap() - }) - } - - /// A driver's `vkCreateGraphicsPipelines` that makes each pipeline's handle say the room its - /// thread's stack had left (`this_thread::stack_room`, 0 where none is known), and whether - /// that is the asking thread (bit 63). - unsafe extern "system" fn roomed( - _: vk::Device, - _: vk::PipelineCache, - count: u32, - _: *const vk::GraphicsPipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - pipelines: *mut vk::Pipeline, - ) -> vk::Result { - let asking = u64::from(ASKING.with(Cell::get)); - let room = crate::this_thread::stack_room().unwrap_or(0) as u64; - for at in 0..count as usize { - // SAFETY: the caller's array of `count` pipelines. - unsafe { *pipelines.add(at) = vk::Pipeline::from_raw(room | asking << 63) }; - } - vk::Result::SUCCESS - } - - /// A pipeline asked for on a thread whose stack has less than - /// [`COMPILE_ROOM`](super::COMPILE_ROOM) left (one of 256 KiB, as a program's thread that - /// makes a device may have) is made on a thread of the runtime's, whose stack has that room; - /// one asked for on a thread with that room (of [`COMPILE_STACK`](super::COMPILE_STACK) - /// bytes), on the asking thread (at the user-initiated class on macOS). A thread of 2 MiB goes - /// by the room it has: the GNU C library may give a thread a stack an ended thread left, up - /// to four times the size asked (8 MiB for 2 MiB). The asking thread's own stack never takes - /// a driver's compile without the room: ANV's compiler overflowed a 256 KiB and a 2 MiB one. - #[test] - fn a_pipeline_asked_for_on_a_small_stack_is_made_on_a_stack_with_the_room() { - let device = routed(0x6d32_7600_0005, roomed); - let room = super::COMPILE_ROOM; - let set = || { - #[cfg(target_os = "macos")] - at(libc::qos_class_t::QOS_CLASS_USER_INITIATED)(); - }; - for stack in [256 << 10, 2 << 20, super::COMPILE_STACK] { - let (asker, raw) = asked_on(stack, set, || { - (crate::this_thread::stack_room().unwrap_or(0), make(&device)) - }); - let (ran, asking) = ((raw & !(1 << 63)) as usize, raw >> 63 == 1); - assert!( - asking == (asker >= room) && ran >= room, - "asked on {stack} bytes with {asker} bytes of room: made on the asking thread \ - {asking}, {ran} bytes of room" - ); - if stack == 256 << 10 { - assert!(!asking, "on 256 KiB: on the runtime's thread"); - } - if stack == super::COMPILE_STACK { - assert!(asking, "on the compile stack: on the asking thread"); - } - } - unregister(device.handle()); - } - - /// The handle of a pipeline the routed device made. - fn make(device: &ash::Device) -> u64 { - let info = vk::GraphicsPipelineCreateInfo::default(); - // SAFETY: the routed device's `vkCreateGraphicsPipelines` is a fake driver's behind - // `compiles.rs`; it reads no argument but the pipelines. - let made = - unsafe { device.create_graphics_pipelines(vk::PipelineCache::null(), &[info], None) } - .unwrap(); - made[0].as_raw() - } - - /// Sets the calling thread's class to `start`. - #[cfg(target_os = "macos")] - fn at(start: libc::qos_class_t) -> impl FnOnce() + Send { - move || { - // SAFETY: sets the calling thread's own class; no pointer. - assert_eq!(unsafe { libc::pthread_set_qos_class_self_np(start, 0) }, 0); - } - } - - /// Where the routed device made a pipeline asked for on a thread that ran `set` first: the - /// class it ran at, whether on the asking thread, and the asking thread's class after. - fn made_from(device: &ash::Device, set: impl FnOnce() + Send) -> (u32, bool, u32) { - asked(set, || { - let raw = make(device); - (raw as u32, raw >> 32 == 1, class()) - }) - } - - /// A pipeline asked for on a thread below the user-initiated class is made on a thread of - /// the runtime's at that class, the asking thread's class untouched; at that class or above, - /// on the asking thread. Elsewhere than macOS, always on the asking thread, whose stack has - /// the room ([`asked`]). - #[test] - fn a_pipeline_is_made_at_the_user_initiated_class_and_the_asker_is_left_as_found() { - let device = routed(0x6d32_7600_0001, told); - #[cfg(target_os = "macos")] - { - use libc::qos_class_t as Q; - let initiated = Q::QOS_CLASS_USER_INITIATED as u32; - for start in [ - Q::QOS_CLASS_BACKGROUND, - Q::QOS_CLASS_UTILITY, - Q::QOS_CLASS_DEFAULT, - ] { - let (ran, asking, after) = made_from(&device, at(start)); - assert_eq!((ran, asking), (initiated, false), "from {start:?}"); - assert_eq!( - after, start as u32, - "the asking thread's class, from {start:?}" - ); - } - for start in [Q::QOS_CLASS_USER_INITIATED, Q::QOS_CLASS_USER_INTERACTIVE] { - let (ran, asking, after) = made_from(&device, at(start)); - assert_eq!( - (ran, asking, after), - (start as u32, true, start as u32), - "from {start:?}" - ); - } - } - #[cfg(not(target_os = "macos"))] - assert_eq!(made_from(&device, || {}), (0, true, 0)); - unregister(device.handle()); - } - - /// A device routed twice keeps its record until the runtime let go of both; then its - /// pipeline makings fail, as for any device never routed. - #[test] - fn a_device_s_record_goes_with_its_last_hold() { - let first = routed(0x6d32_7600_0002, told); - let second = routed(0x6d32_7600_0002, told); - unregister(first.handle()); - // Made: `made_from` unwraps the result. - made_from(&second, || {}); - unregister(second.handle()); - let info = vk::GraphicsPipelineCreateInfo::default(); - // SAFETY: as in `made_from`; the call fails before any driver is reached. - let made = - unsafe { second.create_graphics_pipelines(vk::PipelineCache::null(), &[info], None) }; - assert_eq!( - made.map_err(|(_, error)| error), - Err(vk::Result::ERROR_UNKNOWN) - ); - } - - /// A driver diagnostic the asking thread's call is measured to report is withheld where the - /// driver reports it, on the thread that makes the call for it, and counted as the asking - /// thread's call's; in a call that expects none it relays. - #[test] - fn a_measured_diagnostic_is_withheld_on_whichever_thread_makes_the_call() { - let device = &routed(0x6d32_7600_0003, reports); - let warning = restart_warning(); - let expecting = |expected: Vec| { - move || crate::driver_facts::expecting(expected, || make(device)) - }; - #[cfg(target_os = "macos")] - { - use libc::qos_class_t as Q; - for start in [ - Q::QOS_CLASS_BACKGROUND, - Q::QOS_CLASS_UTILITY, - Q::QOS_CLASS_DEFAULT, - Q::QOS_CLASS_USER_INITIATED, - ] { - assert_eq!( - asked(at(start), expecting(vec![warning.clone()])), - (1, 1), - "withheld and counted, from {start:?}" - ); - assert_eq!( - asked(at(start), expecting(Vec::new())), - (0, 0), - "relayed, from {start:?}" - ); - } - } - assert_eq!(asked(|| {}, expecting(vec![warning.clone()])), (1, 1)); - assert_eq!(asked(|| {}, expecting(Vec::new())), (0, 0)); - unregister(device.handle()); - } - - /// The sink [`reports_to_sink`] reports to. - static SINK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - - /// A driver's `vkCreateGraphicsPipelines` that raises two messages, "first" then "second", - /// through the device's messenger callback to the sink at [`SINK`], on the thread that makes - /// the call, as a driver does. - unsafe extern "system" fn reports_to_sink( - _: vk::Device, - _: vk::PipelineCache, - count: u32, - _: *const vk::GraphicsPipelineCreateInfo<'_>, - _: *const vk::AllocationCallbacks<'_>, - pipelines: *mut vk::Pipeline, - ) -> vk::Result { - use vk::DebugUtilsMessageSeverityFlagsEXT as S; - use vk::DebugUtilsMessageTypeFlagsEXT as K; - let sink = SINK.load(std::sync::atomic::Ordering::SeqCst) as *mut c_void; - for text in [c"first", c"second"] { - let data = vk::DebugUtilsMessengerCallbackDataEXT::default() - .message_id_name(c"m2v-test") - .message(text); - // SAFETY: the callback data lives for the call, and `sink` is the test's sink, leaked. - unsafe { super::super::create::deliver(S::WARNING, K::VALIDATION, &data, sink) }; - } - for at in 0..count as usize { - // SAFETY: the caller's array of `count` pipelines. - unsafe { *pipelines.add(at) = vk::Pipeline::from_raw(1) }; - } - vk::Result::SUCCESS - } - - /// A lock its holder may take again, as a program's recursive mutex. - #[derive(Default)] - struct Reentrant { - state: std::sync::Mutex<(Option, u32)>, - freed: std::sync::Condvar, - } - - impl Reentrant { - fn take(&self) { - let me = std::thread::current().id(); - let mut state = self.state.lock().unwrap(); - loop { - match state.0 { - None => { - *state = (Some(me), 1); - return; - } - Some(owner) if owner == me => { - state.1 += 1; - return; - } - Some(_) => state = self.freed.wait(state).unwrap(), - } - } - } - - fn give(&self) { - let mut state = self.state.lock().unwrap(); - state.1 -= 1; - if state.1 == 0 { - state.0 = None; - self.freed.notify_all(); - } - } - } - - /// A program that holds a lock across a pipeline's creation, whose message sink takes that - /// lock too, is not deadlocked by the full join: the sink sees the messages the driver raised - /// in the call on the asking thread, in their order, before the call returns. On macOS the - /// asking thread is at the utility class, so the call is made on the runtime's thread. - #[test] - fn a_sink_taking_a_lock_the_asker_holds_sees_its_messages_on_the_asking_thread() { - let device = routed(0x6d32_7600_0004, reports_to_sink); - let lock = std::sync::Arc::new(Reentrant::default()); - type Seen = Vec<(std::thread::ThreadId, String)>; - let seen: std::sync::Arc> = std::sync::Arc::default(); - let sink: &'static crate::MessageSink = Box::leak(Box::new({ - let (lock, seen) = (lock.clone(), seen.clone()); - crate::MessageSink::new(move |message| { - lock.take(); - let me = std::thread::current().id(); - seen.lock().unwrap().push((me, message.text.clone())); - lock.give(); - }) - })); - SINK.store( - std::ptr::from_ref(sink) as usize, - std::sync::atomic::Ordering::SeqCst, - ); - let (sent, got) = std::sync::mpsc::channel(); - let asking = { - let (lock, device) = (lock.clone(), device.clone()); - crate::exit_guard::spawn(std::thread::Builder::new(), move || { - #[cfg(target_os = "macos")] - at(libc::qos_class_t::QOS_CLASS_UTILITY)(); - lock.take(); - let made = make(&device); - lock.give(); - sent.send((std::thread::current().id(), made)).unwrap(); - }) - .unwrap() - }; - let (asker, made) = got - .recv_timeout(std::time::Duration::from_secs(30)) - .expect("the creation deadlocked: the sink ran off the asking thread"); - asking.join().unwrap(); - assert_eq!(made, 1); - let seen = seen.lock().unwrap().clone(); - assert_eq!( - seen, - [(asker, "first".to_string()), (asker, "second".to_string())] - ); - unregister(device.handle()); - } -} diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs deleted file mode 100644 index b8cd3d313..000000000 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ /dev/null @@ -1,3232 +0,0 @@ -//! Devices the runtime creates: `Device::system_default` and `Device::all` -//! (`MTLCreateSystemDefaultDevice`, `MTLCopyAllDevices`) and their `_with` forms, which take -//! [`DeviceOptions`]. -//! -//! The runtime makes a Vulkan 1.2 instance, with `VK_KHR_portability_enumeration` where the loader -//! lists it, then one `VkDevice` per qualifying physical device with the description's -//! [`recommended_enables`](metal2vulkan::device::DeviceDescription::recommended_enables) for the -//! options' policy plus the extensions the options name, and adopts each (create is built on -//! adopt). The compile device is made before `vkCreateDevice`, so a device the compile layer -//! refuses is never opened. -//! -//! Once a device has been made through a loader library, the runtime keeps that library and every -//! Vulkan driver it loaded for the life of the process (`keeper.rs`), so later devices never -//! reload a driver. -//! -//! A physical device has one runtime device per options while any handle to it lives, as Metal -//! has one `MTLDevice` per GPU (an M3 Max and an M4: `MTLCreateSystemDefaultDevice()` twice is one -//! object, `MTLCopyAllDevices()[0]` that object, by pointer and `registryID`). -//! `system_default_with` and `all_with` with equal options ([`DeviceOptions`]' fields, the -//! message sink by identity) hand out the devices they made that still live (`MADE`, held -//! weakly), made from one instance; a device still tears down with its last handle, and a later -//! call makes a fresh one. Devices of other options are other devices (an event handle does not -//! cross to them, `SharedEventAcrossDevices`), as is every adopted device. -//! -//! Everything a caller can change here is an explicit option: layers and their settings, -//! extensions, recommended features and extensions to withhold, where debug-utils messages go, -//! which loader opens, which kind of physical device qualifies, and the shader cache directory. -//! Nothing is read from the environment, except where the platform keeps the default shader cache -//! directory (`LOCALAPPDATA` on Windows, `HOME` on macOS, `XDG_CACHE_HOME` and `HOME` elsewhere) -//! and, on macOS, where the Vulkan SDK is (`VULKAN_SDK`), one of the places the default loader is -//! looked for (`default_loaders`). - -use super::instance_requirements::instance_requirements_met; -use super::keeper::keep_drivers_loaded; -use super::line::{Line, Recipe}; -use super::properties::{DeviceKind, PhysicalDeviceIdentity}; -use super::{device_error, holds, lock, Device, InstanceShared, Parts}; -use crate::degradation::{Degradation, DegradeNotice, Told}; -use crate::enables::{host_image_copy_names, listed_reported, listed_structures, Enables}; -use crate::error::{ - vulkan, DeviceRefused, Error, InstanceApiVersion, LoaderNotFound, VkResultCode, -}; -use crate::exit_guard; -use crate::gpu_time; -use crate::image_barrier::MemoryReads; -use crate::loader_word::DeviceWord; -use crate::memory::MemoryClass; -use crate::release; -use crate::shader_cache::{CacheSetup, ShaderCacheOptions}; -use crate::sparse; -use ash::vk; -use metal2vulkan::device::{ - ApiVersion, DeviceDescription, DevicePolicy, EnableSet, VkExtension, VkFeature, -}; -use metal2vulkan::error::{Feature, Unsupported}; -use sha2::Digest; -use std::collections::BTreeSet; -use std::ffi::{c_char, c_void, CStr, CString}; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, Weak}; - -/// How the runtime creates its instance and devices. No Metal counterpart: these choose the -/// Vulkan side (`MTLCreateSystemDefaultDevice` takes nothing). -#[non_exhaustive] -#[derive(Clone)] -pub struct DeviceOptions { - /// The policy each device's compile device is made with, and whose - /// `recommended_enables` each device enables. - pub policy: DevicePolicy, - /// Instance layers to enable, in order (the first is nearest the application). A layer that - /// is not installed fails creation. - pub layers: Vec, - /// Settings of those layers, chained at instance creation through `VK_EXT_layer_settings`, - /// which the instance then enables (a layer that takes settings provides it; without one, - /// creation fails). - pub layer_settings: Vec, - /// Instance extensions beyond the ones the runtime enables itself. - pub instance_extensions: Vec, - /// Device extensions beyond the recommended enables (a swapchain, for example). Where one - /// is an extension whose feature structure the runtime knows (`VK_KHR_` or - /// `VK_EXT_swapchain_maintenance1`: `swapchainMaintenance1`; `VK_KHR_` or - /// `VK_EXT_present_mode_fifo_latest_ready`: `presentModeFifoLatestReady`; - /// `VK_KHR_video_maintenance1`: `videoMaintenance1`; `VK_KHR_video_maintenance2`: - /// `videoMaintenance2`; `VK_KHR_unified_image_layouts`: `unifiedImageLayouts` and - /// `unifiedImageLayoutsVideo`) and the device lists it, the device enables the structure's - /// features too; a device that lacks one Vulkan requires of every device listing the - /// extension (all of them but `unifiedImageLayoutsVideo`) is refused - /// ([`Error::ExtensionFeature`]) rather than enable the - /// extension without it. `unifiedImageLayoutsVideo` is enabled where the device has it - /// (`vkGetPhysicalDeviceFeatures2` on [`DeviceHandles`](crate::DeviceHandles) answers - /// whether it does). One whose registry dependency names an instance extension the - /// instance would not enable (`VK_KHR_swapchain` without `VK_KHR_surface` in - /// `instance_extensions`, for example) refuses the options before the instance is made - /// ([`Error::InstanceExtensionRequired`]). - pub device_extensions: Vec, - /// Device extensions each device enables only where it can, never refused for one: where the - /// device lists it, the instance enables every instance extension its registry dependency - /// names (as for `device_extensions`), and, for an extension whose feature structure the - /// runtime knows (as for `device_extensions`), the device has every required feature of it, - /// which it then enables too, with each optional one it has (`unifiedImageLayoutsVideo`). - /// Elsewhere the device leaves it out, and is made all the same. Which a - /// device enabled, [`Device::enables_extension`](crate::Device::enables_extension) answers - /// (window-system extensions, for a consumer whose windows present where the device can). - /// One also in `device_extensions` is that list's. Metal has no such setting. - pub optional_device_extensions: Vec, - /// Features of the recommended enables a created device leaves disabled (the robustness - /// features, for a run of the in-shader containment encoding, for example). The compile - /// device is made from what is enabled, so it compiles for that. Withholding a feature another - /// enabled feature requires refuses the device (`DeviceDescription::with_enabled`'s check). - pub withheld_features: BTreeSet, - /// Extensions a created device leaves disabled, of the recommended enables and - /// `VK_EXT_external_memory_host` (a run without `VK_EXT_shader_stencil_export`, the - /// shader-side stencil's, for example). The compile device is made from what is enabled, so it - /// compiles for that. Withholding an extension an enabled feature or another enabled extension - /// requires refuses the device (`DeviceDescription::with_enabled`'s check). - pub withheld_extensions: BTreeSet, - /// Where the instance's `VK_EXT_debug_utils` messages of warning and error severity go. When - /// set, the instance enables `VK_EXT_debug_utils` and reports through it from its creation - /// to its destruction. Its devices announce their degradations here too, once per device and - /// kind ([`DebugMessage::degradation`]); without a sink, on stderr. - pub messages: Option, - /// The Vulkan loader library to open instead of the default ones: by default the platform's - /// own by name, then on macOS `libvulkan.1.dylib` in the Vulkan SDK (`VULKAN_SDK`), - /// Homebrew's `/opt/homebrew/lib` and `/usr/local/lib`. A loader that opens from none of - /// them is [`Error::LoaderNotFound`], naming each. - pub loader: Option, - /// Only physical devices of these kinds qualify; empty admits every kind. - pub kinds: Vec, - /// Where the devices keep translated shaders: by default, the platform's per-user cache - /// directory. - pub shader_cache: ShaderCacheOptions, - /// Leave `VK_EXT_device_generated_commands` disabled on a device that has it. The runtime - /// enables it otherwise (with `VK_KHR_maintenance5`, which it requires), and runs an - /// execution of commands a kernel writes on the GPU alone where every record it may hold is - /// covered; without it every such execution takes the host step. The compile device states the - /// extension only where it is enabled. - pub withhold_generated_commands: bool, - /// Make no Vulkan view of an image in another component layout, on any device, as a device - /// whose `VK_KHR_portability_subset` withholds `imageViewFormatReinterpretation` makes none: - /// a texture view of another layout (`RGBA8Unorm` as `R32Uint`) then holds its texels apart, - /// in a shadow the encoders copy (`Degradation::ShadowedTextureView`), and the subset's - /// feature stays disabled. For runs of the path such a device takes. - pub withhold_view_reinterpretation: bool, - /// Load no dynamic library from a file: the device opens no file a library's install names - /// name, nor the file [`Device::new_dynamic_library_with_url`](crate::Device::new_dynamic_library_with_url) - /// names. For a consumer whose libraries come from a party that must not read the host's - /// files (a guest's). A pipeline state's creation then links only the libraries its function - /// descriptors give (`libraries.preloaded`, and `libraries.loaded` by install name): an - /// install name `loaded` lacks loads nothing, and the creation fails where an import - /// survives specialization (`Compile(NeedsInput(DynamicLibrary))`), as Metal's fails for a - /// file it cannot load; `new_dynamic_library_with_url` is refused - /// (`DynamicLibrary(NoFileLoading)`). Off by default: Metal's behaviour, each install name's - /// file read at each creation. No Metal counterpart. - pub load_no_dynamic_library_file: bool, - /// The Vulkan API version the instance requests (`VkApplicationInfo::apiVersion`), at which - /// the runtime reads each physical device's description; Vulkan 1.2 when `None`. Metal has - /// no such setting: it is a Vulkan-side option, for a consumer whose layers read later - /// structures only under a later instance version (the profiles layer reads a profile's - /// Vulkan 1.3 and later structures only then). A request below 1.2, the runtime's floor, or - /// above the version the loader reports (`vkEnumerateInstanceVersion`) refuses creation - /// (`Error::InstanceApiVersion`); the runtime never clamps it. - pub instance_api_version: Option, - /// Answer command buffers' `GPUStartTime` and `GPUEndTime` from the host's clock instead of - /// GPU timestamps, which no command buffer then writes for its own times (a rate-mapped pass - /// recorded in pieces, and a host step's probe, still time theirs: - /// `WorkCounts::rate_map_piece_gpu_nanos`). Off by default: Metal's answer, - /// except on a driver whose timestamps wait for every queue's - /// (`DriverFact::TimestampsWaitForEveryQueue`: MoltenVK 1.4.1 on Apple's GPUs), which answers - /// from the host's clock whatever this says. There, a command buffer with work answers as its - /// GPU start the host time the first driver's submission that carried its work was called (its - /// `kernelEndTime` where one submission carried it all; or its queue's latest GPU end before - /// it, where later) and as its GPU end the host time the runtime saw it complete: the window - /// its work ran in, which keeps every rule of Metal's own times (`gpu_time.rs`), but not the - /// GPU's own times. The - /// device announces `Degradation::GpuTimesFromHost` once, at the first such answer. It spares - /// each command buffer its two timestamps, which cost about 150 us of latency on MoltenVK; a - /// device whose queue family writes no timestamps then answers GPU times instead of refusing - /// them. Metal has no such setting. - pub gpu_times_from_host: bool, - /// The class of Mac each device presents ([`MacClass`](crate::MacClass)), whose Metal's - /// answers it gives where a Mac's GPU decides them: what a new `Private` texture reads before - /// anything writes it, the encoding a GPU blit through a compressed texture writes, and a - /// `half` NaN clear's sign ([`DeviceProperties::lossless_compression`](crate::DeviceProperties::lossless_compression) - /// states it), whether a sampler state's `lodBias` moves its samples' level, and the most - /// threadgroup memory a kernel may take - /// ([`DeviceProperties::max_threadgroup_memory_length`](crate::DeviceProperties::max_threadgroup_memory_length)). - /// `None` by default: the class of the device's GPU - /// ([`MacClass::of_vendor`](crate::MacClass::of_vendor): an Apple GPU presents an Apple - /// silicon Mac, every other GPU a Mac with an Intel or AMD GPU). A consumer that presents - /// another Mac than its GPU's (an x86-64 macOS guest, an Intel or AMD Mac, on an Apple GPU) - /// declares it. No Metal counterpart: a Mac's GPU is what it is. - pub mac_class: Option, - /// The degradation kinds each device announces at every occurrence, not once (empty by - /// default: each kind once per device). Each occurrence's notice is the same - /// [`DegradeNotice`] through the same sink (or stderr), on the thread whose call announces - /// it, so a program that runs tasks on threads over one device sees each task's: where each - /// kind's notice surfaces is in its [`Degradation`] docs. A kind a - /// pipeline variant's making announces (a stage's precision notes, specialized or not, and - /// the other kinds its stages or requirements state) occurs at each dispatch or draw that - /// binds the variant, which announces it on the encoding thread (on the committing or - /// scheduler thread for an indirect command's), not at the making: the device makes a - /// variant once. No Metal counterpart. - pub announce_each: BTreeSet, - /// The kinds of degradation that, met while the runtime lowers a render encoder's call after - /// it returned (`RenderLoweringPolicy::Worker`), refuse the call rather than - /// being announced: at every occurrence there, the call fails its command buffer - /// (`CommandBufferError::CallRefused`), whose refusal is the notice - /// (`Error::Degraded`), and nothing of that encoder or of any after it runs. Empty by default, - /// where every degradation is announced and the work runs; a consumer that ends its program - /// at a kind's notice in the call names that kind here, so the work it ends at never runs. - /// No Metal counterpart. - pub lowering_refuses: BTreeSet, - /// Keep each command buffer's execution record - /// ([`CommandBuffer::executions`](crate::CommandBuffer::executions)): the pipeline each - /// dispatch and draw ran, the bind shape it was planned for, and its `VkPipeline`s' creation - /// times. Off by default: the device's encoders build no record and keep nothing for one, so - /// a draw pays nothing for a record no one reads. Validation's executor and lanes turn it on. - /// No Metal counterpart. - #[doc(hidden)] - pub record_executions: bool, - /// Make each device's check of the first move of an image over host pages fail whatever the - /// moves did (`in_place_check.rs`), and keep no record of it: every texture over host pages - /// is then a shadow, its notice naming the failed check. Off by default. A test hook, for the - /// lanes that hold the shadow to a failed check. No Metal counterpart. - #[doc(hidden)] - pub fail_in_place_check: bool, - /// Take each device's submission check of merged submissions (`submit_check.rs`, - /// `Check::Merge`) as holding without its answer, and keep no record of its checks: under - /// `CompletionPolicy::Grouped` its batches then wait in groups whatever the timing it - /// measured, where a driver that runs one `vkQueueSubmit` of several `VkSubmitInfo`s as - /// several kernel submissions runs them as correctly, saving none. Its import tax and follows - /// checks answer as ever. Off by default. A test hook, for the lanes that hold a device to the - /// grouped path on every run. No Metal counterpart. - #[doc(hidden)] - pub assume_submissions_merge: bool, - /// Turn each device's pending audit on: a diagnostic that checks, at each begin of a - /// `VkCommandBuffer`, reset or give-back of its pool and submission of it again, that the - /// GPU completed every submission that carries it, and logs each one that did not (id name - /// `metal2vulkan-pending-audit`, `pending_audit.rs`); it changes no work. Off by default; - /// `METAL2VULKAN_PENDING_AUDIT`, set, turns it on for every device too. For the tests that - /// hold it to a finding. No Metal counterpart. - #[doc(hidden)] - pub pending_audit: bool, - /// Turn each device's encoder trail on: a diagnostic that submits each encoder in a - /// `vkQueueSubmit` of its own and, once no work of the device advanced for 2 s while some was - /// pending, names the encoder each stuck `VkQueue`'s oldest batch holds and the last one it - /// completed (id name `metal2vulkan-encoder-trail`, `encoder_trail.rs`); it changes when work - /// goes to the driver, never what it computes. Off by default; `METAL2VULKAN_ENCODER_TRAIL`, - /// set, turns it on for every device too. For the tests that hold it to its line. No Metal - /// counterpart. - #[doc(hidden)] - pub encoder_trail: bool, - /// Color formats each device takes as no color attachment, as a device without the - /// attachment feature of them does: their tilings' `COLOR_ATTACHMENT` and blend features and - /// their attachment sample counts are left out of the description the device plans and - /// compiles by (`withhold_attachments`). Empty by default. A test hook, for the lanes that run - /// the path a device that renders a format only through the view of its word takes - /// (`metal::format::WordAttachment`, its multisampled textures held in the word's format) on a - /// device that renders the format. No Metal counterpart. - #[doc(hidden)] - pub withheld_attachment_formats: BTreeSet, - /// The most color attachments, and fragment outputs, each device draws at once, where it is - /// below the device's own: the device's `maxColorAttachments` and - /// `maxFragmentOutputAttachments` are held to it in the description the device plans and - /// compiles by (`hold_color_attachments`), so a render pass of more colors draws in color - /// groups (`render/color_groups.rs`) as on a device of that many. `None` by default. A test - /// hook, for the lanes that run the color groups on a device that draws eight. No Metal - /// counterpart. - #[doc(hidden)] - pub color_attachment_limit: Option, - /// Where each device hands its pipeline records: one [`PipelineRecord`](crate::PipelineRecord) - /// per pipeline state creation that made its state (compute, render, mesh render and tile - /// render, and the additional-binary-functions forms; and the one-sample or factor-scaling - /// twin the runtime makes of a render state where a draw first needs it), on the creating - /// thread before the call returns, as the program's own code (a panic in it is caught). A - /// creation that fails, a binary archive's add and a warm pass's make none. A consumer keeps - /// them, in the order they came, and hands a later process's device them - /// ([`Device::warm`](crate::Device::warm)) to make the same translations and `VkPipeline`s - /// before its program asks. `None` by default: no record is made. Devices of one hook are - /// devices of one option (it is compared by identity, as [`messages`](Self::messages) is). - /// No Metal counterpart: Metal keeps its own compiled pipelines in the OS's caches. - pub pipeline_records: Option>, - /// Queues each device makes for the caller beside its own, one per entry, of a family whose - /// flags contain the entry's (`VIDEO_DECODE_KHR` for a consumer's video decode, for - /// example), which [`DeviceHandles::extra_queues`](crate::DeviceHandles::extra_queues) - /// returns. Each is a queue no runtime work uses: of the first family whose flags contain - /// the entry's and that has a queue the device's own plan leaves free, at its lowest free - /// index; where no such family has one left, the last queue of such a family the device would - /// take for itself, which it then leaves to the caller (a queue reserved for presenting - /// first, then the round robin's last, then the staging queue's), never its first queue, - /// where internal submissions go. A device with no queue for an entry (no family whose flags - /// contain it, empty flags, or only the device's first queue) is made all the same, without - /// it, and says so once in an informational message - /// (`metal2vulkan-extra-queues-absent`, through [`messages`](Self::messages) or on stderr). - /// The runtime never submits to these queues: the caller is their only submitter, and - /// orders its work against the runtime's through semaphores - /// ([`Event::reserve_vk_signal`](crate::Event::reserve_vk_signal), - /// [`Event::vk_wait`](crate::Event::vk_wait), and a shared event's same hooks). The runtime's - /// own buffers and images stay shared among its own queue families - /// ([`DeviceHandles::queue_families`](crate::DeviceHandles::queue_families)), which need not - /// include an extra queue's: a submission to an extra queue of another family uses only - /// objects made to be shared with that family, the caller's own (which Metal-side code - /// reaches through [`Device::new_buffer_with_vk_buffer`](crate::Device::new_buffer_with_vk_buffer) - /// or [`Device::new_texture_with_vk_image_plane`](crate::Device::new_texture_with_vk_image_plane)). - /// Empty by default. No Metal counterpart: a Vulkan-side option. - pub extra_queues: Vec, - /// How many queues of its own queue families each device reserves for the caller, which - /// [`DeviceHandles::reserved_queues`](crate::DeviceHandles::reserved_queues) returns: queues - /// it would otherwise lend the round robin its command queues share - /// ([`CommandQueue`](crate::CommandQueue)), so that round robin shrinks by each one reserved, - /// and the runtime never submits to one (no command queue, presenting or not, takes one; no - /// internal or staging copy goes there). They are the round robin's last queues: it keeps its - /// first four, and the two queues reserved for presenting queues keep theirs, so a device - /// reserves only queues past those six (on an RTX 5080, whose graphics family has 16, one - /// reserved queue leaves the round robin 13 and presenting 2). A family with queues past the - /// round robin's ceiling of 16 and presenting's two gives those first, and its round robin - /// does not shrink. A device with fewer to spare reserves those it has (none on MoltenVK's - /// four families of one queue each, which its round robin takes, or lavapipe's one queue), is - /// made all the same, and says so once in an informational message - /// (`metal2vulkan-reserved-queues-absent`, through [`messages`](Self::messages) or on - /// stderr). They are reserved before the [`extra_queues`](Self::extra_queues) are placed, so - /// no extra queue takes one. - /// - /// A reserved queue's family is one of the device's own - /// ([`DeviceHandles::queue_families`](crate::DeviceHandles::queue_families)), which its - /// buffers and images are shared among (`EXCLUSIVE` on a device of one family, `CONCURRENT` - /// among them otherwise): a submission there may use the runtime's buffers and images - /// ([`Buffer::vk_buffer`](crate::Buffer::vk_buffer), - /// [`Texture::vk_image`](crate::Texture::vk_image)) as well as the caller's, with no - /// ownership transfer, under those handles' contracts: while the object lives, ordered - /// against the runtime's work on it through semaphores - /// ([`Event::vk_wait`](crate::Event::vk_wait), - /// [`Event::reserve_vk_signal`](crate::Event::reserve_vk_signal), a shared event's same - /// hooks, [`CommandBuffer::encode_wait_for_vk_semaphore`](crate::CommandBuffer::encode_wait_for_vk_semaphore), - /// [`CommandBuffer::encode_signal_vk_semaphore`](crate::CommandBuffer::encode_signal_vk_semaphore)) - /// or completion, and an image the runtime made left in `VK_IMAGE_LAYOUT_GENERAL`. The caller - /// is the queue's only submitter: its submissions there sit in no command queue's order, and - /// hold none back. 0 by default. No Metal counterpart: a Vulkan-side option. - pub reserved_queues: u32, - /// Fewer `VkQueue`s for each device than its queue plan takes: at most - /// [`round_robin`](QueueLimits::round_robin) for the round robin its command queues share, - /// and at most [`presenting`](QueueLimits::presenting) reserved for presenting queues. `None` - /// (the default) takes the plan: the round robin up to 16 (at least four where the families - /// have them, NVIDIA's graphics family of 16 giving it 14) and two for presenting. - /// - /// What it changes: how many `VkQueue`s the device makes, and so what making and dropping it - /// cost. Each queue is made with the device and destroyed with it: on an RTX 5080 Laptop GPU - /// (NVIDIA 615.71.09), whose plan takes 18 queues (14 for the round robin, 2 for presenting, - /// the staging and fill queues), one device made and dropped at a time, a device of 17 (all but - /// the fill queue) took 445 ms in `vkCreateDevice` and 110 ms in `vkDestroyDevice`, and one of - /// 2 (one for the round robin and the staging queue) 145 ms and 44 ms, about 20 ms a queue to - /// make; and the driver makes devices one at a time across processes. On a device whose - /// families have no queue to spare (RADV's and lavapipe's one graphics queue) the limits leave - /// the plan as it is. - /// - /// What it costs a program: its command queues share `VkQueue`s past the limit, so one - /// queue's command buffers wait behind another's whole command buffer where Metal's would not - /// ([`CommandQueue`](crate::CommandQueue)); a queue made by - /// [`Device::new_command_queue_unshared`](crate::Device::new_command_queue_unshared) may share - /// too, and one made for presenting past the limit's shares with the round robin - /// (`shared-present-queue`) or with an earlier presenting queue. The reserved and extra - /// queues take the queues the limits leave. Wherever the limits change a placement from what - /// the plan gives, the device says so in an informational message - /// (`metal2vulkan-queue-limits-reached`, through [`messages`](Self::messages) or on stderr), - /// at the first such change alone, each later one counted - /// (`WorkCounts::queue_limits_reached_withheld`): - /// a command queue the program makes, unshared or not, that takes a `VkQueue` another took - /// where the plan gives it one of its own (counted among the program's queues: the runtime's - /// own, its in-place check's, shares as it does on a device of one queue); a presenting queue past the limit's where the plan reserves it one; - /// reserved or extra queues placed otherwise than the plan places them (as the device is - /// made); and each read of the device's queue sharing (`Device::settle_queue_switch_check`, - /// `Device::queue_switch_check_report`) on a device whose queues the limits changed. No Metal - /// counterpart: a Vulkan-side option, for tests and tools that make many devices. - pub queue_limits: Option, - /// In the runtime's own tests, the view check's facts (`view_check.rs`): `Some` fixes them, - /// with no check run, so a test's compiles take one profile from the device's first pipeline - /// to its last (none by default: a uniform view stays a uniform buffer, as on a device whose - /// check found no fact); `None` runs the check as a device outside the tests does. - #[cfg(test)] - pub(crate) view_facts: Option>, -} - -/// The most `VkQueue`s a device takes for its command queues ([`DeviceOptions::queue_limits`]). -/// No Metal counterpart: a Vulkan-side option. -/// -/// The limits bound the program's queues alone. The staging queue, where the device's plan -/// reserves one (of a family of transfers alone, or, where no memory the host caches may hold a -/// texture's image, as on an RX 7900 XTX, of a family of compute work beside the device's own), is -/// the runtime's own queue for textures' CPU copies, which no command queue shares: the device -/// makes it under any limits as it does without them, it counts against neither limit, and the -/// limits' message never names it. A device made with limits of one and none copies its textures -/// as one made without them does. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct QueueLimits { - /// The most the round robin its command queues share takes: at least one (0 is taken as 1), - /// and the plan's ceiling of 16 at most. - pub round_robin: u32, - /// The most reserved for presenting queues: the plan's two at most. - pub presenting: u32, -} - -impl std::fmt::Debug for DeviceOptions { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // Every field is named, so a field added later is written here or this fails to compile. - let DeviceOptions { - policy, - layers, - layer_settings, - instance_extensions, - device_extensions, - optional_device_extensions, - withheld_features, - withheld_extensions, - messages, - loader, - kinds, - shader_cache, - withhold_generated_commands, - withhold_view_reinterpretation, - load_no_dynamic_library_file, - instance_api_version, - gpu_times_from_host, - mac_class, - announce_each, - lowering_refuses, - record_executions, - fail_in_place_check, - assume_submissions_merge, - pending_audit, - encoder_trail, - withheld_attachment_formats, - color_attachment_limit, - pipeline_records, - extra_queues, - reserved_queues, - queue_limits, - #[cfg(test)] - view_facts, - } = self; - let mut out = f.debug_struct("DeviceOptions"); - out.field("policy", policy) - .field("layers", layers) - .field("layer_settings", layer_settings) - .field("instance_extensions", instance_extensions) - .field("device_extensions", device_extensions) - .field("optional_device_extensions", optional_device_extensions) - .field("withheld_features", withheld_features) - .field("withheld_extensions", withheld_extensions) - .field("messages", messages) - .field("loader", loader) - .field("kinds", kinds) - .field("shader_cache", shader_cache) - .field("withhold_generated_commands", withhold_generated_commands) - .field( - "withhold_view_reinterpretation", - withhold_view_reinterpretation, - ) - .field("load_no_dynamic_library_file", load_no_dynamic_library_file) - .field("instance_api_version", instance_api_version) - .field("gpu_times_from_host", gpu_times_from_host) - .field("mac_class", mac_class) - .field("announce_each", announce_each) - .field("lowering_refuses", lowering_refuses) - .field("record_executions", record_executions) - .field("fail_in_place_check", fail_in_place_check) - .field("assume_submissions_merge", assume_submissions_merge) - .field("pending_audit", pending_audit) - .field("encoder_trail", encoder_trail) - .field("withheld_attachment_formats", withheld_attachment_formats) - .field("color_attachment_limit", color_attachment_limit) - .field( - "pipeline_records", - &pipeline_records.as_ref().map(|_| "hook"), - ) - .field( - "extra_queues", - &(extra_queues.iter()) - .map(|&flags| super::handles::QueueFlagsText(flags)) - .collect::>(), - ) - .field("reserved_queues", reserved_queues) - .field("queue_limits", queue_limits); - #[cfg(test)] - out.field("view_facts", view_facts); - out.finish() - } -} - -impl Default for DeviceOptions { - fn default() -> DeviceOptions { - // Every field is named, so a field added later is written here or this fails to compile. - DeviceOptions { - policy: Default::default(), - layers: Default::default(), - layer_settings: Default::default(), - instance_extensions: Default::default(), - device_extensions: Default::default(), - optional_device_extensions: Default::default(), - withheld_features: Default::default(), - withheld_extensions: Default::default(), - messages: Default::default(), - loader: Default::default(), - kinds: Default::default(), - shader_cache: Default::default(), - withhold_generated_commands: Default::default(), - withhold_view_reinterpretation: Default::default(), - load_no_dynamic_library_file: Default::default(), - instance_api_version: Default::default(), - gpu_times_from_host: Default::default(), - mac_class: Default::default(), - announce_each: Default::default(), - lowering_refuses: Default::default(), - record_executions: Default::default(), - fail_in_place_check: Default::default(), - assume_submissions_merge: Default::default(), - pending_audit: Default::default(), - encoder_trail: Default::default(), - withheld_attachment_formats: Default::default(), - color_attachment_limit: Default::default(), - pipeline_records: Default::default(), - extra_queues: Default::default(), - reserved_queues: Default::default(), - queue_limits: default_queue_limits(), - #[cfg(test)] - view_facts: Some(BTreeSet::new()), - } - } -} - -/// The default of [`DeviceOptions::queue_limits`]: `None`, the queue plan, outside the runtime's -/// own tests; [`TEST_QUEUE_LIMITS`] in them. -fn default_queue_limits() -> Option { - cfg!(test).then_some(TEST_QUEUE_LIMITS) -} - -/// The queue limits of the devices the runtime's own tests make by default -/// (`DeviceOptions::default()` in its test build, nowhere else): a round robin of two `VkQueue`s -/// and none reserved for presenting, beside the staging and fill queues, so four on NVIDIA's -/// families where the plan takes 18. NVIDIA's driver makes and destroys a process's device while -/// every other process's waits: on an RTX 3090 (NVIDIA 620.70.06), devices of the plan took 540 to -/// 575 ms in `vkCreateDevice` and 163 ms in `vkDestroyDevice` each alone, and 55 device tests at -/// 12 threads took 66.9 s, 1.2 s each, no less than one at a time, their `vkCreateDevice` a median -/// of 8.1 s and their `vkDestroyDevice` 2.8 s. A device of fewer queues costs less of both -/// (`DeviceOptions::queue_limits`'s measurement). A test whose work needs more than these limits -/// give on a device with queues to spare (a command queue of the program's, unshared or not, made -/// while it holds two others, which would share a `VkQueue` with one of them; a presenting queue, which -/// would share the round robin's; reserved or extra queues, placed otherwise) panics where it -/// asks for it, on every device (`needs_the_queue_plan`), and makes its device with -/// `queue_limits: None`, the plan: as the runtime lane's tests make theirs past its -/// `LANE_QUEUE_LIMITS`. A read of the device's queue sharing reads what the plan's would: its check -/// measures two `VkQueue`s of the round robin, which these limits keep. A device made with limits -/// equal to these is taken for one of the default. -pub(crate) const TEST_QUEUE_LIMITS: QueueLimits = QueueLimits { - round_robin: 2, - presenting: 0, -}; - -/// In the runtime's own tests, a device made with [`TEST_QUEUE_LIMITS`] whose test's work asks for -/// more than they give on a device with queues to spare, `what` saying what: the test fails here, -/// on every device, so that it makes its device with the plan (`queue_limits: None`) rather than -/// run on a device whose queues share where the plan's would not. -#[cfg(test)] -#[track_caller] -pub(crate) fn needs_the_queue_plan(what: &str) -> ! { - panic!( - "this test's device takes the runtime tests' default queue limits (TEST_QUEUE_LIMITS: \ - a round robin of {} VkQueue(s), {} for presenting) and {what}, which needs more on a \ - device with queues to spare (NVIDIA's plan takes 18): make the device with \ - `queue_limits: None`, the queue plan", - TEST_QUEUE_LIMITS.round_robin, TEST_QUEUE_LIMITS.presenting - ) -} - -/// One setting of an instance layer (`VkLayerSettingEXT`). -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct LayerSetting { - /// The layer, as [`DeviceOptions::layers`] names it. - pub layer: CString, - /// The setting's name, as the layer documents it. - pub name: CString, - /// The setting's value. - pub value: LayerSettingValue, -} - -impl LayerSetting { - /// `layer`'s setting `name` of `value`. - pub fn new(layer: CString, name: CString, value: LayerSettingValue) -> LayerSetting { - LayerSetting { layer, name, value } - } -} - -/// A layer setting's value. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LayerSettingValue { - /// One `VkBool32`. - Bool(bool), - /// Strings. - Strings(Vec), -} - -/// The `VkLayerSettingEXT`s of `settings`, pointing into them and into `bools`, which holds one -/// `VkBool32` per setting (its value for a boolean one), and `strings`, which holds each setting's -/// string pointers (empty for a boolean one): both made by [`setting_values`]. -pub(crate) fn layer_settings<'a>( - settings: &'a [LayerSetting], - bools: &'a [vk::Bool32], - strings: &'a [Vec<*const c_char>], -) -> Vec> { - settings - .iter() - .zip(bools.iter().zip(strings)) - .map(|(setting, (value, pointers))| { - let mut raw = vk::LayerSettingEXT::default() - .layer_name(&setting.layer) - .setting_name(&setting.name); - // `LayerSettingEXT::values` counts bytes, not values: the count is set directly. - match &setting.value { - LayerSettingValue::Bool(_) => { - raw = raw.ty(vk::LayerSettingTypeEXT::BOOL32); - raw.value_count = 1; - raw.p_values = std::ptr::from_ref(value).cast(); - } - LayerSettingValue::Strings(_) => { - raw = raw.ty(vk::LayerSettingTypeEXT::STRING); - raw.value_count = pointers.len() as u32; - raw.p_values = pointers.as_ptr().cast(); - } - } - raw - }) - .collect() -} - -/// The values [`layer_settings`] points at: per setting, its `VkBool32` and its string pointers. -pub(crate) fn setting_values( - settings: &[LayerSetting], -) -> (Vec, Vec>) { - settings - .iter() - .map(|setting| match &setting.value { - LayerSettingValue::Bool(value) => (vk::Bool32::from(*value), Vec::new()), - LayerSettingValue::Strings(strings) => ( - vk::FALSE, - strings.iter().map(|string| string.as_ptr()).collect(), - ), - }) - .unzip() -} - -/// No Metal counterpart: a receiver of the instance's debug-utils messages, and of its devices' -/// degrade notices. It is called on whichever thread the driver, the layer, or the runtime -/// reports from, so it must be `Send + Sync`; a panic inside it is caught. -#[derive(Clone)] -pub struct MessageSink { - receive: Arc, - /// The least severity of the messages it hears, but degrade notices - /// ([`with_least_severity`](Self::with_least_severity)). - least: MessageSeverity, -} - -impl MessageSink { - /// A sink calling `receive` with each message, of every severity. - pub fn new(receive: impl Fn(&DebugMessage) + Send + Sync + 'static) -> MessageSink { - MessageSink { - receive: Arc::new(receive), - least: MessageSeverity::Verbose, - } - } - - /// No Metal counterpart: the sink, hearing no message of a severity below `least` but the - /// devices' degrade notices ([`DebugMessage::degradation`]), which it hears whatever `least` - /// says. The runtime makes none of the messages of its own the sink skips: it formats no text - /// for them (a host import freed on a device that keeps MoltenVK's residency set, a `Verbose` - /// line, `metal2vulkan-host-import-freed`, the only one that may come at every call). - pub fn with_least_severity(self, least: MessageSeverity) -> MessageSink { - MessageSink { least, ..self } - } - - /// Whether `other` is this sink (a clone of it, hearing the same severities), not merely one - /// that does the same. - pub(crate) fn same(&self, other: &MessageSink) -> bool { - Arc::ptr_eq(&self.receive, &other.receive) && self.least == other.least - } - - /// Whether the sink hears messages of `severity` that are no degrade notice. - pub(crate) fn hears(&self, severity: MessageSeverity) -> bool { - severity >= self.least - } - - /// Hand `message` to the sink, where it hears it; a panic inside it is caught. On a thread - /// inside a passing hold of the device's resources, once its outermost ended - /// (`resource_ids.rs`): the program's code runs in none. - pub(crate) fn deliver(&self, message: &DebugMessage) { - if message.degradation.is_none() && !self.hears(message.severity) { - return; - } - if crate::resource_ids::held_past_passing_hold(self, message) { - return; - } - crate::exit_guard::program(|| (self.receive)(message)); - } -} - -impl std::fmt::Debug for MessageSink { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("MessageSink") - } -} - -/// One debug-utils message, or a device's degrade notice. No Metal counterpart. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DebugMessage { - /// The message's severity; a degrade notice's is `Warning`. - pub severity: MessageSeverity, - /// What the message is about. - pub kind: MessageKind, - /// `pMessageIdName` (a validation message's VUID), empty when absent; a degrade notice's - /// code. - pub id_name: String, - /// `messageIdNumber`; 0 for a degrade notice. - pub id: i32, - /// `pMessage`; a degrade notice's text. - pub text: String, - /// The runtime's own notice of a degradation it takes, once per device and kind: never a - /// driver's or a layer's message. Match its [`Degradation`], not the text. - pub degradation: Option, -} - -/// A message's severity. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum MessageSeverity { - /// `VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT`. - Verbose, - /// `VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT`. - Info, - /// `VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT`, and the runtime's degrade notices. - Warning, - /// `VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT`. - Error, -} - -/// What a message is about (`VkDebugUtilsMessageTypeFlagsEXT`). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct MessageKind { - /// A general event. - pub general: bool, - /// A violation of the specification (a validation message). - pub validation: bool, - /// A use that is valid but not optimal. - pub performance: bool, -} - -/// The instance's persistent messenger and the sink it reports to. -pub(super) struct Messenger { - loader: ash::ext::debug_utils::Instance, - handle: vk::DebugUtilsMessengerEXT, - /// The callback's user data; it outlives the instance (dropped after `vkDestroyInstance`, - /// which reports through the messenger chained at creation). - sink: Box, -} - -impl Messenger { - /// The sink the messenger reports to. - pub(super) fn sink(&self) -> &MessageSink { - &self.sink - } - - /// Destroy the persistent messenger; the instance is destroyed next. - pub(super) fn destroy(&self) { - // SAFETY: the messenger belongs to the live instance and is destroyed once. - unsafe { release::messenger(&self.loader, self.handle) }; - } -} - -/// The debug-utils callback: hands the message to the [`MessageSink`] at `user`. -pub(super) unsafe extern "system" fn deliver( - severity: vk::DebugUtilsMessageSeverityFlagsEXT, - types: vk::DebugUtilsMessageTypeFlagsEXT, - data: *const vk::DebugUtilsMessengerCallbackDataEXT<'_>, - user: *mut c_void, -) -> vk::Bool32 { - let text = |pointer: *const c_char| { - if pointer.is_null() { - String::new() - } else { - // SAFETY: the layer passes NUL-terminated strings that live for the call. - unsafe { CStr::from_ptr(pointer) } - .to_string_lossy() - .into_owned() - } - }; - if data.is_null() || user.is_null() { - return vk::FALSE; - } - // SAFETY: `data` is the layer's callback data for this call. - let data = unsafe { &*data }; - // SAFETY: `user` is the boxed sink the messenger was created with, alive with the instance. - let sink = unsafe { &*user.cast::() }; - use vk::DebugUtilsMessageSeverityFlagsEXT as S; - use vk::DebugUtilsMessageTypeFlagsEXT as T; - let message = DebugMessage { - severity: if severity.contains(S::ERROR) { - MessageSeverity::Error - } else if severity.contains(S::WARNING) { - MessageSeverity::Warning - } else if severity.contains(S::INFO) { - MessageSeverity::Info - } else { - MessageSeverity::Verbose - }, - kind: MessageKind { - general: types.contains(T::GENERAL), - validation: types.contains(T::VALIDATION), - performance: types.contains(T::PERFORMANCE), - }, - id_name: text(data.p_message_id_name), - id: data.message_id_number, - text: text(data.p_message), - degradation: None, - }; - // A driver diagnostic the device's driver facts measure this thread's current call to - // report is withheld, and counted (`driver_facts.rs`). - if crate::driver_facts::withholds(&message) { - return vk::FALSE; - } - // On the runtime's thread making a call for an asking thread, held: the asking thread - // delivers it once the call returns (`compiles.rs`). - if super::compiles::held(sink, &message) { - return vk::FALSE; - } - // A panic must not unwind into the driver. - sink.deliver(&message); - vk::FALSE -} - -/// The instance extensions a loader lists, read with one `vkEnumerateInstanceExtensionProperties`: -/// the loader scans its driver and layer manifests again at each such call, and loads and asks -/// each driver it finds, so the making of an instance reads the list once and answers every -/// question of it from this. -pub(crate) struct ListedExtensions(Vec); - -/// The room [`ListedExtensions::of`] gives its first call: more extensions than a loader lists -/// (20 on lavapipe's alone, 26 with RADV's beside it). -pub(crate) const LISTED_ROOM: usize = 64; - -impl ListedExtensions { - /// The instance extensions `entry`'s loader lists, read in one call into room for - /// [`LISTED_ROOM`] of them, and again into twice the room while the loader answers - /// `VK_INCOMPLETE`. Not the usual two-call read (the count, then the list), which is two - /// scans of the manifests. - pub(crate) fn of(entry: &ash::Entry) -> Result { - let enumerate = entry.fp_v1_0().enumerate_instance_extension_properties; - let mut room = LISTED_ROOM; - loop { - let mut listed = vec![vk::ExtensionProperties::default(); room]; - let mut count = u32::try_from(room).unwrap_or(u32::MAX); - // SAFETY: a global command of a loaded entry, for no layer, into `count` properties. - let answer = unsafe { enumerate(std::ptr::null(), &mut count, listed.as_mut_ptr()) }; - match answer { - vk::Result::SUCCESS => { - listed.truncate(count as usize); - return Ok(ListedExtensions(listed)); - } - vk::Result::INCOMPLETE => room *= 2, - error => return Err(vulkan(error)), - } - } - } - - /// Whether the loader listed the instance extension `name`. - pub(crate) fn lists(&self, name: &CStr) -> bool { - self.0 - .iter() - .any(|extension| extension.extension_name_as_c_str() == Ok(name)) - } -} - -/// The instance API version `requested` asks for (`DeviceOptions::instance_api_version`): -/// Vulkan 1.2 when `None`. Refused below 1.2, and above `loader`'s answer, the version the -/// loader reports, asked only for a request. -pub(crate) fn instance_version( - requested: Option, - loader: impl FnOnce() -> Result, -) -> Result { - let Some(requested) = requested else { - return Ok(ApiVersion::V1_2); - }; - if requested < ApiVersion::V1_2 { - return Err(Error::InstanceApiVersion(InstanceApiVersion::BelowFloor { - requested, - })); - } - let loader = loader()?; - if requested > loader { - return Err(Error::InstanceApiVersion(InstanceApiVersion::AboveLoader { - requested, - loader, - })); - } - Ok(requested) -} - -/// The Vulkan loader libraries the runtime tries, in order, when the options name none: the -/// platform's own by name, which the dynamic linker searches for, then on macOS -/// `libvulkan.1.dylib` in the Vulkan SDK's `lib` directory (`vulkan_sdk`, the `VULKAN_SDK` -/// variable, where set), in Homebrew's `/opt/homebrew/lib` and in `/usr/local/lib`, which no -/// default search path holds there. -pub(crate) fn default_loaders(vulkan_sdk: Option<&Path>) -> Vec { - if cfg!(target_os = "macos") { - let directories = vulkan_sdk - .map(|sdk| sdk.join("lib")) - .into_iter() - .chain(["/opt/homebrew/lib", "/usr/local/lib"].map(PathBuf::from)); - ["libvulkan.dylib", "libvulkan.1.dylib"] - .map(PathBuf::from) - .into_iter() - .chain(directories.map(|directory| directory.join("libvulkan.1.dylib"))) - .collect() - } else if cfg!(windows) { - vec![PathBuf::from("vulkan-1.dll")] - } else if cfg!(target_os = "android") { - vec![PathBuf::from("libvulkan.so")] - } else { - vec![PathBuf::from("libvulkan.so.1")] - } -} - -/// The Vulkan loader: `loader` where the options name one, else the first of -/// [`default_loaders`] that opens. [`Error::LoaderNotFound`] names each library tried. -pub(crate) fn open_loader(loader: Option<&Path>) -> Result { - let tried = match loader { - Some(path) => vec![path.to_path_buf()], - None => default_loaders(std::env::var_os("VULKAN_SDK").as_deref().map(Path::new)), - }; - for path in &tried { - // SAFETY: opening the loader runs its initialization; the runtime assumes nothing else. - if let Ok(entry) = unsafe { ash::Entry::load_from(path) } { - return Ok(entry); - } - } - Err(Error::LoaderNotFound(LoaderNotFound { tried })) -} - -/// `vkCreateInstance` of `info` from `entry`: every instance the runtime creates, its devices' and -/// the drivers' keeper's (`keeper.rs`), is made here, and the exit guard's hook registers again -/// after it, whatever it answered ([`exit_guard::instance_made`]): a layer registers an exit -/// handler at each such call. -/// -/// # Safety -/// -/// `info` and everything it points at live for the call. -pub(super) unsafe fn new_instance( - entry: &ash::Entry, - info: &vk::InstanceCreateInfo<'_>, -) -> ash::prelude::VkResult { - // SAFETY: the caller's. - let made = unsafe { entry.create_instance(info, None) }; - exit_guard::instance_made(); - made -} - -/// The instance of `options`. -fn create_instance(options: &DeviceOptions) -> Result, Error> { - instance_of(open_loader(options.loader.as_deref())?, options) -} - -/// The instance of `options` from the loader `entry`, which lists its instance extensions once -/// ([`ListedExtensions`]). -pub(crate) fn instance_of( - entry: ash::Entry, - options: &DeviceOptions, -) -> Result, Error> { - let listed = ListedExtensions::of(&entry)?; - let portability = listed.lists(ash::khr::portability_enumeration::NAME); - let mut extensions: Vec<&CStr> = Vec::new(); - if portability { - extensions.push(ash::khr::portability_enumeration::NAME); - } - // The relay of a driver's command-buffer failures needs a messenger of its own - // (`relay.rs`): debug utils wherever the instance lists them. - let relays = listed.lists(ash::ext::debug_utils::NAME); - if options.messages.is_some() || relays { - extensions.push(ash::ext::debug_utils::NAME); - } - // MoltenVK's Metal argument buffers, asked for where the instance can take layer settings, - // ahead of the consumer's own, which win (`argument_buffers.rs`); and, where the relay hears - // its failures, that it keep a device after a command buffer fails (`relay.rs`). - let asks = listed.lists(ash::ext::layer_settings::NAME); - let chained_settings: Vec = asks - .then(super::argument_buffers::setting) - .into_iter() - .chain((asks && relays).then(super::relay::setting)) - .chain(options.layer_settings.iter().cloned()) - .collect(); - if !chained_settings.is_empty() { - extensions.push(ash::ext::layer_settings::NAME); - } - for extra in &options.instance_extensions { - if !extensions.contains(&extra.as_c_str()) { - extensions.push(extra); - } - } - // The instance extensions the caller's device extensions require: one the instance would - // not enable refuses the options before the instance is made, where a driver need not. - instance_requirements_met(&options.device_extensions, &extensions)?; - let extension_names: Vec<*const c_char> = extensions.iter().map(|n| n.as_ptr()).collect(); - let api_version = instance_version(options.instance_api_version, || { - // SAFETY: a global command of a loaded entry. - let version = unsafe { entry.try_enumerate_instance_version() }.map_err(vulkan)?; - // A loader without `vkEnumerateInstanceVersion` is a Vulkan 1.0 loader. - Ok(version.map_or(ApiVersion { major: 1, minor: 0 }, ApiVersion::from_packed)) - })?; - let application = vk::ApplicationInfo::default() - .engine_name(c"metal2vulkan") - .api_version(api_version.packed()); - let sink = options.messages.clone().map(Box::new); - let mut messenger_info = sink.as_ref().map(|sink| { - use vk::DebugUtilsMessageSeverityFlagsEXT as S; - use vk::DebugUtilsMessageTypeFlagsEXT as T; - vk::DebugUtilsMessengerCreateInfoEXT::default() - .message_severity(S::WARNING | S::ERROR) - .message_type(T::GENERAL | T::VALIDATION | T::PERFORMANCE) - .pfn_user_callback(Some(deliver)) - .user_data(std::ptr::from_ref::(sink).cast_mut().cast()) - }); - let mut chained = messenger_info; - let (bools, strings) = setting_values(&chained_settings); - let settings = layer_settings(&chained_settings, &bools, &strings); - let mut settings_info = vk::LayerSettingsCreateInfoEXT::default().settings(&settings); - let layer_names: Vec<*const c_char> = options.layers.iter().map(|n| n.as_ptr()).collect(); - let mut info = vk::InstanceCreateInfo::default() - .application_info(&application) - .enabled_extension_names(&extension_names) - .enabled_layer_names(&layer_names) - .flags(if portability { - vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR - } else { - vk::InstanceCreateFlags::empty() - }); - // The chain is built once, before the attempts below: `push_next` writes the pushed - // structure's own `pNext`, so pushing these onto a second create info would leave the one - // pushed last pointing at the one pushed first, whose `pNext` the second push then sets to - // itself -- a cycle the loader walks without end, allocating as it goes. - if let Some(chained) = chained.as_mut() { - info = info.push_next(chained); - } - if !settings.is_empty() { - info = info.push_next(&mut settings_info); - } - // A layer the loader cannot provide is not something the device lacks: the layers are - // diagnostics, so a caller that asked for a device gets one. The instance of the layers asked - // for and, where the loader answers `VK_ERROR_LAYER_NOT_PRESENT` ([`drops_layers`]), of no - // layer at all, whose answer is the caller's: two `vkCreateInstance` calls at most, the same - // create info but for its layer list, which the second has none of, so the arm cannot run - // twice. What was left out is announced as each device is made ([`layers_dropped`]). - let mut layers: &[CString] = &options.layers; - let mut dropped: Vec = Vec::new(); - let raw = loop { - // SAFETY: `info` and everything it points at live for the call. - match unsafe { new_instance(&entry, &info) } { - Ok(raw) => break raw, - Err(vk::Result::ERROR_INCOMPATIBLE_DRIVER) => return Err(Error::NoDevice), - Err(error) if drops_layers(error, layers) => { - dropped = options.layers.clone(); - layers = &[]; - info = info.enabled_layer_names(&[]); - } - Err(error) => return Err(vulkan(error)), - } - }; - let messenger = match (sink, messenger_info.as_mut()) { - (Some(sink), Some(info)) => { - let loader = ash::ext::debug_utils::Instance::new(&entry, &raw); - // SAFETY: the instance enabled `VK_EXT_debug_utils`; the sink lives in the messenger. - match unsafe { loader.create_debug_utils_messenger(info, None) } { - Ok(handle) => Some(Messenger { - loader, - handle, - sink, - }), - Err(error) => { - // SAFETY: nothing was made from the instance. - unsafe { release::instance(&raw) }; - return Err(vulkan(error)); - } - } - } - _ => None, - }; - let relay = if relays { - // SAFETY: the instance is live, from `entry`, and enabled `VK_EXT_debug_utils`. - match unsafe { super::relay::Messenger::new(&entry, &raw) } { - Ok(relay) => Some(relay), - Err(error) => { - if let Some(messenger) = &messenger { - messenger.destroy(); - } - // SAFETY: nothing else was made from the instance. - unsafe { release::instance(&raw) }; - return Err(vulkan(error)); - } - } - } else { - None - }; - let settings = sha2::Sha256::digest(format!("{chained_settings:?}").as_bytes()).into(); - Ok(Arc::new(InstanceShared { - entry, - raw, - api_version, - extensions: extensions.iter().map(|&name| name.to_owned()).collect(), - owned: true, - messenger, - relay, - settings, - dropped_layers: dropped, - })) -} - -/// Whether `error`, which `vkCreateInstance` of `layers` answered, is answered by creating the -/// instance again with no layer at all: a missing layer's answer alone, and only where a layer was -/// asked for (`VK_ERROR_LAYER_NOT_PRESENT` with none asked for is the loader's own answer, with -/// nothing of ours to drop). Every other failure is the caller's. -pub(crate) fn drops_layers(error: vk::Result, layers: &[CString]) -> bool { - error == vk::Result::ERROR_LAYER_NOT_PRESENT && !layers.is_empty() -} - -/// The informational message a device of an instance created without the layers `dropped`, which -/// its caller asked for and the loader could not provide, sends as it is made: no degrade notice, -/// as nothing of Metal's answers differs (the layers are diagnostics). `None` where none was -/// dropped. -pub(crate) fn layers_dropped(dropped: &[CString], device: &str) -> Option { - if dropped.is_empty() { - return None; - } - let names: Vec = dropped - .iter() - .map(|name| name.to_string_lossy().into_owned()) - .collect(); - Some(format!( - "metal2vulkan: the device on {device} was made without the instance layer(s) {}, which \ - the loader answered VK_ERROR_LAYER_NOT_PRESENT for: a layer it does not list, or one it \ - lists and cannot load (a layer manifest naming its library by a bare filename, which the \ - loader looks for on the system library search path). The device is the same in every \ - other way and its answers are Metal's; what those layers would have reported is missing \ - [{LAYERS_DROPPED}]", - names.join(", ") - )) -} - -/// The id name of the informational message a device made without the layers its caller asked for -/// sends as it is made ([`layers_dropped`]). -pub(crate) const LAYERS_DROPPED: &str = "metal2vulkan-instance-layers-dropped"; - -/// The physical devices of `instance` that `options` admit, in the order -/// `Device::system_default` prefers them (by [`DeviceKind`], then enumeration order). -fn ranked( - instance: &InstanceShared, - options: &DeviceOptions, -) -> Result, Error> { - // SAFETY: the instance is live. - let physical = unsafe { instance.raw.enumerate_physical_devices() }.map_err(vulkan)?; - let mut ranked: Vec<(u8, vk::PhysicalDevice)> = physical - .into_iter() - .filter_map(|physical| { - // SAFETY: `physical` was enumerated from the instance. - let ty = unsafe { instance.raw.get_physical_device_properties(physical) }.device_type; - let kind = DeviceKind::of(ty); - (options.kinds.is_empty() || options.kinds.contains(&kind)) - .then_some((kind.preference(), physical)) - }) - .collect(); - ranked.sort_by_key(|&(preference, _)| preference); - Ok(ranked.into_iter().map(|(_, physical)| physical).collect()) -} - -/// The registry ID (`Device::registry_id`) of each of `physical`, physical devices of `instance`, -/// in their order: from its `deviceUUID` (`VkPhysicalDeviceIDProperties`, core in Vulkan 1.1); -/// one below Vulkan 1.2, of which the runtime makes no device, is left out. -fn identified( - instance: &InstanceShared, - physical: Vec, -) -> Vec<(u64, vk::PhysicalDevice)> { - physical - .into_iter() - .filter_map(|physical| { - // SAFETY: `physical` was enumerated from the instance. - let core = unsafe { instance.raw.get_physical_device_properties(physical) }; - let api = metal2vulkan::vk::ApiVersion::from_packed(core.api_version); - if api < metal2vulkan::vk::ApiVersion::V1_2 { - return None; - } - let mut id = vk::PhysicalDeviceIDProperties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut id); - // SAFETY: as above; the instance is at Vulkan 1.2 or later, and the device too, so - // the structure (core in 1.1) may be chained. - unsafe { (instance.raw).get_physical_device_properties2(physical, &mut properties) }; - Some((super::properties::registry_id(&id.device_uuid), physical)) - }) - .collect() -} - -/// The fewest `VkQueue`s a created device takes for the round robin logical queues share, where -/// the families taken have that many. -pub(crate) const LEAST_QUEUES: u32 = 4; - -/// The most it takes for that round robin, where the families taken have queues to spare past -/// [`PRESENT_QUEUES`]. -/// -/// Two logical queues that share a `VkQueue` submit to one Vulkan queue, which runs its -/// submissions in order, so one's command buffers wait for the other's whole command buffer, -/// where Metal's queues wait for each other only inside one command (`queue.rs`, measured). A -/// device with queues to spare therefore gives each logical queue one of its own rather than -/// leaving them idle. -/// -/// The ceiling is NVIDIA's graphics family of 16, the largest measured. What a further queue -/// costs is its `VkQueue`'s lock, timeline semaphore and four counters, and, on a driver that -/// takes cross-queue timeline waits, one wait in a batch's `vkQueueSubmit` the first time it sees -/// that queue's value move (about 0.5 us on an RTX 5080, 1.1 us on ms01's Iris Xe, 1.6 us on a -/// Radeon 780M). The one driver measured with queues to spare, NVIDIA's 615.71.09, stalls its -/// submissions on semaphore operations (`DriverFact::SemaphoreOperationsStallSubmits`) and so -/// takes no such wait at all: its batches begin with a barrier instead, whose cost does not grow -/// with the queues. -pub(crate) const ROUND_ROBIN_CEILING: u32 = 16; - -/// The most `VkQueue`s a created device reserves for presenting queues -/// (`Device::new_command_queue_for_presenting`), outside the round robin: the taken families' -/// queues past the round robin's, where they have them, before any reserved for the caller. -const PRESENT_QUEUES: u32 = 2; - -/// The queues a created device takes ([`queue_plan`]). -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct QueuePlan { - /// The first family that does graphics and compute work (and so transfers): the device's - /// primary family, its first queue's. - pub(crate) primary: u32, - /// The queues, each its family and index there, the primary family's first queue first. - pub(crate) queues: Vec<(u32, u32)>, - /// The queues reserved for presenting queues, after `queues` in the same order: at most - /// [`PRESENT_QUEUES`], none where the families taken have no more. - pub(crate) present: Vec<(u32, u32)>, - /// The queues reserved for the caller (`DeviceOptions::reserved_queues`), after `present` in - /// the same order: at most as many as asked, none where the families taken have no more. - pub(crate) reserved: Vec<(u32, u32)>, - /// The queue reserved for staging copies (`device/staging.rs`), of a family none of the - /// queues above are of, whose copies take any texel (a granularity of one texel): the first - /// queue of the first family of transfers alone (a copy engine); else, where a texture's - /// image has no memory the host caches, of the first family of graphics or compute work; - /// `None` where there is none ([`queue_plan`]). - pub(crate) staging: Option<(u32, u32)>, - /// The queue reserved for the runtime's own copies from host memory into a resource's device - /// memory that follow the work before them (`device/staging.rs`, the fill queue): the - /// staging queue's family's second queue, where that family is of transfers alone and has - /// one; `None` otherwise. An extra queue the caller asks for takes it as a queue the plan - /// leaves free ([`extra_queue_places`]). - pub(crate) fill: Option<(u32, u32)>, - /// The queue the program's command queues made for copies submit to - /// (`Device::new_command_queue_for_copies`), of the staging queue's family where that family - /// is of transfers alone (a copy engine), has a second queue and writes timestamps of the - /// primary family's valid bits: its first queue past the staging and fill queues where it has - /// one, else the fill queue's, which the fill queue's submissions and those command queues' - /// then share under one lock (`device/staging.rs`); never the staging queue's, which waits - /// for no work in flight. `None` otherwise. An extra queue the caller asks for takes it as a - /// queue the plan leaves free ([`extra_queue_places`]). - pub(crate) copies: Option<(u32, u32)>, -} - -/// The queues a device of `families` takes: where every family is equivalent to the first that -/// does graphics and compute work (the same flags, queue count, timestamp bits and transfer -/// granularity: MoltenVK's four families of one queue each, one Metal command queue per queue), -/// one queue of each family first, then the families' next queues in turn; otherwise that -/// family's queues alone. Queues of another family are -/// another Metal command queue on MoltenVK, whose command buffers the GPU runs beside the -/// first's; queues of one family there share one. -/// -/// The round robin logical queues share takes those queues less [`PRESENT_QUEUES`] and less the -/// `reserved` the caller asks for (`DeviceOptions::reserved_queues`), at least [`LEAST_QUEUES`] -/// and at most [`ROUND_ROBIN_CEILING`], so a family with queues to spare lends them to the round -/// robin rather than leaving them idle (NVIDIA's 16 give 14) and no device takes fewer than it -/// took before. The next queues in that order, at most [`PRESENT_QUEUES`], are reserved for -/// presenting queues, and the next, at most `reserved`, for the caller: the round robin keeps its -/// first [`LEAST_QUEUES`] and presenting its queues before the caller has any (NVIDIA's 16 with -/// one reserved give the round robin 13). -/// -/// A queue of a family of transfers alone is reserved for staging copies (`device/staging.rs`): -/// a copy engine, which runs beside the graphics family's work where another of its queues waits -/// behind it. Where the device has none, a queue of another family that does graphics or compute -/// work is, only where a texture's image has no memory the host caches (`cached` false, -/// `memory::host_cached_placement`: a discrete GPU with no device-local type the host caches, an -/// RX 7900 XTX), whose textures' CPU copies would otherwise read and write through the host's -/// mapping of uncached memory: most 1920 x 1080 `get_bytes` calls took 1.26 to 1.71 s that way on -/// the XTX, and 2.0 to 2.2 ms on its compute family's queue (`device/staging.rs`). Such -/// an asynchronous compute queue's work may wait behind a kernel that fills the GPU (up to 1.05 s -/// on a Radeon 780M and 1.19 s on an RTX 3090), so where a texture's image has memory the host -/// caches its copies stay on the host, and no such queue stages. Such a copy engine's second -/// queue, where it has one, is reserved for the runtime's own copies from host memory into a -/// resource's device memory that follow the work before them, a batch's of 1 MiB or more -/// (`device/staging.rs`, the fill queue): beside another queue's kernels on an RTX 3090, a frame -/// that copied a `Managed` buffer's 1 MiB in took 1.80 ms (p50) through it and 3.53 ms through -/// the graphics family's queue (`tests::managed_copies_bench`). `None` where no family does -/// graphics and compute work. -pub(crate) fn queue_plan( - families: &[vk::QueueFamilyProperties], - reserved: u32, - cached: bool, -) -> Option { - queue_plan_within(families, reserved, None, cached) -} - -/// [`queue_plan`] within `limits` (`DeviceOptions::queue_limits`): the round robin at most -/// `limits.round_robin` (at least one, its floor of [`LEAST_QUEUES`] no more than that) and at -/// most `limits.presenting` queues reserved for presenting, limits past the plan's taking the -/// plan's. `None` is the plan. The staging queue is the plan's whatever the limits (`cached` as -/// [`queue_plan`] takes it): a queue of the runtime's own that no command queue shares -/// ([`QueueLimits`]). -pub(crate) fn queue_plan_within( - families: &[vk::QueueFamilyProperties], - reserved: u32, - limits: Option, - cached: bool, -) -> Option { - let (ceiling, presenting) = match limits { - None => (ROUND_ROBIN_CEILING, PRESENT_QUEUES), - Some(limits) => ( - limits.round_robin.clamp(1, ROUND_ROBIN_CEILING), - limits.presenting.min(PRESENT_QUEUES), - ), - }; - let wanted = vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE; - let (primary, first) = families - .iter() - .enumerate() - .find(|(_, family)| family.queue_count > 0 && family.queue_flags.contains(wanted))?; - let equivalent = |family: &vk::QueueFamilyProperties| { - family.queue_flags == first.queue_flags - && family.queue_count == first.queue_count - && family.timestamp_valid_bits == first.timestamp_valid_bits - && family.min_image_transfer_granularity == first.min_image_transfer_granularity - }; - let taken: Vec = if families.iter().all(equivalent) { - (0..families.len() as u32).collect() - } else { - vec![primary as u32] - }; - let mut order = (0..first.queue_count) - .flat_map(|index| taken.iter().map(move |&family| (family, index))) - .collect::>(); - let past = (presenting as usize).saturating_add(reserved as usize); - let round_robin = (order.len().saturating_sub(past)) - .clamp(LEAST_QUEUES.min(ceiling) as usize, ceiling as usize) - .min(order.len()); - let mut rest = order.split_off(round_robin).into_iter(); - let present = rest.by_ref().take(presenting as usize).collect(); - let reserved = rest.take(reserved as usize).collect(); - // Copies of any texel, on a family none of the queues above are of. - let unit = vk::Extent3D { - width: 1, - height: 1, - depth: 1, - }; - let stages = |index: usize, family: &vk::QueueFamilyProperties| { - !taken.contains(&(index as u32)) - && family.queue_count > 0 - && family.min_image_transfer_granularity == unit - }; - // Transfers alone (sparse binding and protected memory aside: no graphics, compute, video or - // optical flow work). - let besides = - vk::QueueFlags::TRANSFER | vk::QueueFlags::SPARSE_BINDING | vk::QueueFlags::PROTECTED; - let copy_engine = (families.iter().enumerate()).find(|&(index, family)| { - stages(index, family) - && family.queue_flags.contains(vk::QueueFlags::TRANSFER) - && (family.queue_flags & !besides).is_empty() - }); - // A family of graphics or compute work transfers too, whether or not it lists the bit. - let work = vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE; - let beside = || match cached { - true => None, - false => (families.iter().enumerate()) - .find(|&(index, family)| stages(index, family) && family.queue_flags.intersects(work)), - }; - // The fill queue: a copy engine's second queue. - let fill = copy_engine - .filter(|(_, family)| family.queue_count > 1) - .map(|(index, _)| (index as u32, 1)); - let staging = copy_engine - .or_else(beside) - .map(|(index, _)| (index as u32, 0)); - // The copy queue: a copy engine's third queue, else its second, the fill queue's. - let copies = copy_engine - .filter(|(_, family)| { - family.queue_count > 1 && family.timestamp_valid_bits == first.timestamp_valid_bits - }) - .map(|(index, family)| (index as u32, if family.queue_count > 2 { 2 } else { 1 })); - // Where every family is equivalent, the primary is family 0, so either way the primary - // family's first queue leads (internal submissions go there). - Some(QueuePlan { - primary: primary as u32, - queues: order, - present, - reserved, - staging, - fill, - copies, - }) -} - -impl QueuePlan { - /// The copy queue's place where it is a `VkQueue` of its own, not the fill queue's: one more - /// queue the device takes (`families_taken`, [`vk_queues`]). - pub(crate) fn copy_queue_apart(&self) -> Option<(u32, u32)> { - self.copies.filter(|&place| Some(place) != self.fill) - } -} - -/// What the queue plan gives a device of `families` whose queue limits -/// (`DeviceOptions::queue_limits`) gave it `plan` and `extra_places`, for `reserved` reserved and -/// `extra` extra queues asked for, on a device whose textures' images may lie in memory the host -/// caches or not (`cached`, as [`queue_plan`] takes it): where the limits changed any of it, the -/// plan's; `None` where they changed nothing. The staging queue is the same in both before the -/// extra queues are placed ([`queue_plan_within`]). -pub(crate) fn planned_queues( - families: &[vk::QueueFamilyProperties], - reserved: u32, - extra: &[vk::QueueFlags], - plan: &QueuePlan, - extra_places: &[Option<(u32, u32)>], - cached: bool, -) -> Option { - let mut planned = queue_plan(families, reserved, cached)?; - let planned_extra = extra_queue_places(families, &mut planned, extra); - let changed = planned != *plan || planned_extra != extra_places; - changed.then_some(PlannedQueues { - round_robin: planned.queues.len(), - presenting: planned.present.len(), - reserved: planned.reserved, - extra: planned_extra, - }) -} - -/// What the queue plan gives a device whose queue limits changed its queues ([`planned_queues`]). -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct PlannedQueues { - /// The round robin's `VkQueue`s. - pub(crate) round_robin: usize, - /// The `VkQueue`s reserved for presenting queues. - pub(crate) presenting: usize, - /// The queues reserved for the caller, each its family and index there. - pub(crate) reserved: Vec<(u32, u32)>, - /// Each extra queue's place, `None` for one the device has none of. - pub(crate) extra: Vec>, -} - -/// A device's queues: its queue plan, and its extra queues' places -/// (`DeviceOptions::extra_queues`, [`extra_queue_places`]), `None` for one the device has none of. -pub(crate) type PlacedQueues = (QueuePlan, Vec>); - -/// The queue limits of a device's least queue plan ([`made_within_resources`]): a round robin of -/// one `VkQueue`, none reserved for presenting. -pub(crate) const LEAST_QUEUE_LIMITS: QueueLimits = QueueLimits { - round_robin: 1, - presenting: 0, -}; - -/// The least queue plan of a device of `families` made with `options`, its textures' images in -/// memory the host caches or not (`cached`, as [`queue_plan`] takes it): the plan within -/// [`LEAST_QUEUE_LIMITS`], with as many reserved queues as the device's own plan (within -/// `options`' queue limits) reserves of those `options` asks for, no more, and the extra queues -/// it asks for, placed as [`extra_queue_places`] places them. The least plan's round robin of -/// one leaves room for more reserved queues than the plan's floor of [`LEAST_QUEUES`] and -/// presenting's [`PRESENT_QUEUES`] do, but a device the driver refuses for want of its resources -/// takes no more queues for the caller than the plan gives: what the caller is given does not -/// change with the driver's answer (on an RTX 2080 asked for 11, 10 by the plan, not 11). -pub(crate) fn least_queue_plan( - families: &[vk::QueueFamilyProperties], - options: &DeviceOptions, - cached: bool, -) -> Option { - let planned = queue_plan_within( - families, - options.reserved_queues, - options.queue_limits, - cached, - )?; - // At most the family's queue count, so within `u32`. - let reserved = planned.reserved.len() as u32; - let limits = Some(LEAST_QUEUE_LIMITS); - let mut plan = queue_plan_within(families, reserved, limits, cached)?; - let extra = extra_queue_places(families, &mut plan, &options.extra_queues); - Some((plan, extra)) -} - -/// The `VkQueue`s a device of `placed` makes: its round robin's, those reserved for presenting -/// and for the caller, its staging and fill queues and its extra queues. -pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize { - plan.queues.len() - + plan.present.len() - + plan.reserved.len() - + usize::from(plan.staging.is_some()) - + usize::from(plan.fill.is_some()) - + usize::from(plan.copy_queue_apart().is_some()) - + extra.iter().flatten().count() -} - -/// The families a device of `plan` and `extra_places` takes queues of, each with how many: one -/// `VkDeviceQueueCreateInfo` each. -fn families_taken(plan: &QueuePlan, extra_places: &[Option<(u32, u32)>]) -> Vec<(u32, usize)> { - let mut taken: Vec<(u32, usize)> = Vec::new(); - let copies = plan.copy_queue_apart(); - let all = (plan.queues.iter().chain(&plan.present)) - .chain(&plan.reserved) - .chain(&plan.staging) - .chain(&plan.fill) - .chain(&copies) - .chain(extra_places.iter().flatten()); - for &(family, _) in all { - match taken.iter_mut().find(|(at, _)| *at == family) { - Some((_, count)) => *count += 1, - None => taken.push((family, 1)), - } - } - taken -} - -/// A device made with its least queue plan's `VkQueue`s, the driver having refused its queue -/// plan's ([`made_within_resources`], `Degradation::LeastQueuePlan`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct LeastPlanTaken { - /// The `VkQueue`s of the queue plan. - pub(crate) planned: usize, - /// The driver's answer to them. - pub(crate) refusal: vk::Result, - /// The `VkQueue`s of the least plan, which the device took. - pub(crate) least: usize, -} - -/// Whether `result` is a driver's refusal of a device for want of its resources, of which a -/// device of fewer `VkQueue`s needs less: `VK_ERROR_TOO_MANY_OBJECTS` (Vulkan's answer where the -/// device-specific resources a logical device needs run out), `VK_ERROR_INITIALIZATION_FAILED`, -/// `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`. NVIDIA's driver answers the -/// second or the last where other devices hold its GPU's channels: on an RTX 2080 -/// (NVIDIA 620.70.06), beside 60 devices of 3 `VkQueue`s, a device of 18 was refused with -/// `VK_ERROR_OUT_OF_HOST_MEMORY`, and beside 62 or 64 with `VK_ERROR_INITIALIZATION_FAILED`; a -/// device of 3 was made beside each (`examples/queue_plan_cost.rs`, `--fills`). -fn for_want_of_resources(result: vk::Result) -> bool { - matches!( - result, - vk::Result::ERROR_TOO_MANY_OBJECTS - | vk::Result::ERROR_INITIALIZATION_FAILED - | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY - | vk::Result::ERROR_OUT_OF_HOST_MEMORY - ) -} - -/// The device `make` makes with the queues of `planned`, with them and `None`; where the driver -/// refuses it for want of its resources ([`for_want_of_resources`]) and `least`, the least queue -/// plan's queues ([`least_queue_plan`]), takes fewer `VkQueue`s ([`vk_queues`]), the device made -/// once more with `least`'s, with them and what it took ([`LeastPlanTaken`]). Refused, naming the -/// device (`device`) and each attempt ([`Error::DeviceRefused`]), where the driver refuses the -/// least plan's for want of resources too, or where the least plan takes no fewer; any other -/// failure is the driver's ([`vulkan`]). On an RTX 2080 (NVIDIA 620.70.06), of sixteen processes -/// started 3 s apart each making one device, seven made it with 17 `VkQueue`s, two with 2 -/// (one for the round robin and the staging queue), and the driver refused the rest with both -/// (`VK_ERROR_INITIALIZATION_FAILED`), the kernel logging that it could not allocate a channel's -/// instance block; in one process it refused the eighth device with either plan, there and on an -/// RTX 3090. -/// -/// The least plan at once, not plans between it and the plan's: what one refused device takes the -/// next is refused. One device per process (`examples/queue_plan_cost.rs`, `--runtime-fill`), an -/// RTX 2080 on Thunderbolt made 11 devices of the plan and 3 of the least plan, where a round -/// robin halved on each refusal (18, then 11, 7 and 3 `VkQueue`s) made the 12th with 11 and -/// refused the 13th; an RTX 3090 made 58 of the plan and the 59th of the least plan either way, -/// the steps adding 0.42 s to it and 0.21 s to the refused 60th. Beside 12 runtime devices, a -/// refused `vkCreateDevice` of 7 to 15 `VkQueue`s took 237 to 270 ms on the RTX 2080, about what -/// making one of 11 takes there alone (249 ms). -pub(crate) fn made_within_resources( - device: &str, - planned: PlacedQueues, - least: Option, - mut make: impl FnMut(&PlacedQueues) -> Result, -) -> Result<(D, PlacedQueues, Option), Error> { - let refusal = match make(&planned) { - Ok(made) => return Ok((made, planned, None)), - Err(result) if for_want_of_resources(result) => result, - Err(result) => return Err(vulkan(result)), - }; - let asked = vk_queues(&planned); - let refused = |attempts: &[(usize, vk::Result)]| { - Error::DeviceRefused(DeviceRefused { - device: device.to_owned(), - attempts: (attempts.iter()) - .map(|&(queues, result)| (queues, VkResultCode(result.as_raw()))) - .collect(), - }) - }; - let Some(least) = least.filter(|least| vk_queues(least) < asked) else { - return Err(refused(&[(asked, refusal)])); - }; - let fewer = vk_queues(&least); - match make(&least) { - Ok(made) => { - let taken = LeastPlanTaken { - planned: asked, - refusal, - least: fewer, - }; - Ok((made, least, Some(taken))) - } - Err(result) if for_want_of_resources(result) => { - Err(refused(&[(asked, refusal), (fewer, result)])) - } - Err(result) => Err(vulkan(result)), - } -} - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -thread_local! { - /// How many of the next `vkCreateDevice` calls of this thread a test refuses before they - /// reach the driver ([`refuse_next_devices`]). - static REFUSED: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Refuse this thread's next `count` `vkCreateDevice` calls as the driver refuses one for want of -/// its resources (`VK_ERROR_INITIALIZATION_FAILED`): a test's stand-in for a GPU whose other -/// devices hold what it needs, such as its channels ([`made_within_resources`]). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn refuse_next_devices(count: u32) { - REFUSED.with(|refused| refused.set(count)); -} - -/// The stand-in's refusal of this `vkCreateDevice` call, where [`refuse_next_devices`] asked for -/// one. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -fn refusal_stand_in() -> Option { - REFUSED.with(|refused| { - let left = refused.get(); - (left > 0).then(|| { - refused.set(left - 1); - vk::Result::ERROR_INITIALIZATION_FAILED - }) - }) -} - -/// Whether the `made`th queue counted from 0 of the round robin, or of the presenting queues, -/// that the limits give `limited` `VkQueue`s takes one another took where the plan's `planned` -/// give it one of its own (`DeviceOptions::queue_limits`). -pub(crate) fn shares_past_limit(made: u64, limited: usize, planned: usize) -> bool { - made >= limited as u64 && made < planned as u64 -} - -/// The informational message a device whose queue limits changed what the queue plan gives says -/// where they did, `what` saying what (`DeviceOptions::queue_limits`). -pub(crate) fn queue_limits_reached(device: &str, what: &str) -> String { - format!( - "metal2vulkan: on {device}, {what}: the device's queue limits \ - (DeviceOptions::queue_limits) changed that from what its queue plan gives \ - [{QUEUE_LIMITS_REACHED}]" - ) -} - -/// The id name of the informational message of [`queue_limits_reached`]. -pub(crate) const QUEUE_LIMITS_REACHED: &str = "metal2vulkan-queue-limits-reached"; - -/// The queue of each of `asked` (`DeviceOptions::extra_queues`) on a device of `families` whose -/// own queues are `plan`'s, in `asked`'s order, `None` for one the device has none of: a queue the -/// plan leaves free, of the first family whose flags contain the asked flags and that has one, -/// at its lowest free index; else the last queue the plan reserved for presenting, then the last -/// of the round robin's but its first (internal submissions go there), then the staging queue, of -/// such a family, which `plan` then gives up; never a queue reserved for the caller. The fill -/// queue and the copy queue are queues the plan leaves free: an extra queue may take either, and -/// the plan then gives it up (and the copy queue with the fill queue, where it is the fill -/// queue's, or with the staging queue). Flags that are empty, or that no family's contain, take -/// none. -pub(crate) fn extra_queue_places( - families: &[vk::QueueFamilyProperties], - plan: &mut QueuePlan, - asked: &[vk::QueueFlags], -) -> Vec> { - let mut extra: Vec<(u32, u32)> = Vec::new(); - let mut places = Vec::with_capacity(asked.len()); - for &flags in asked { - let serves = |family: u32| { - !flags.is_empty() - && (families.get(family as usize)).is_some_and(|f| f.queue_flags.contains(flags)) - }; - let taken = |place: (u32, u32)| { - plan.queues.contains(&place) - || plan.present.contains(&place) - || plan.reserved.contains(&place) - || plan.staging == Some(place) - || extra.contains(&place) - }; - let free = (0..families.len() as u32) - .filter(|&family| serves(family)) - .find_map(|family| { - (0..families[family as usize].queue_count) - .map(|index| (family, index)) - .find(|&place| !taken(place)) - }); - let place = free.or_else(|| { - if let Some(at) = plan.present.iter().rposition(|&(f, _)| serves(f)) { - return Some(plan.present.remove(at)); - } - let round_robin = plan.queues.iter().skip(1).rposition(|&(f, _)| serves(f)); - if let Some(at) = round_robin { - return Some(plan.queues.remove(at + 1)); - } - plan.staging.filter(|&(f, _)| serves(f)).inspect(|_| { - plan.staging = None; - }) - }); - if let Some(place) = place { - extra.push(place); - // The fill and copy queues are queues the plan leaves free to the caller's extra - // queues. - if plan.fill == Some(place) { - plan.fill = None; - } - if plan.copies == Some(place) { - plan.copies = None; - } - } - places.push(place); - } - // The copy queue's buffers are those shared with the staging queue's family (`sharing.rs`): - // it goes with that queue. - if plan.staging.is_none() { - plan.copies = None; - } - places -} - -/// The informational message a device made with extra queues it has none of for `absent` -/// (`DeviceOptions::extra_queues`) sends as it is made; `None` where it made every one. -pub(crate) fn extra_queues_absent(absent: &[vk::QueueFlags], device: &str) -> Option { - if absent.is_empty() { - return None; - } - let flags: Vec = (absent.iter()) - .map(|&flags| format!("{:?}", super::handles::QueueFlagsText(flags))) - .collect(); - Some(format!( - "metal2vulkan: the device on {device} has no queue for the extra queue(s) of {} the \ - options asked for (no queue family whose flags contain them, or none left past the \ - device's first queue); the device was made without them, and \ - DeviceHandles::extra_queues leaves them out [{EXTRA_QUEUES_ABSENT}]", - flags.join("; ") - )) -} - -/// The id name of the informational message a device made without some of the extra queues its -/// options asked for sends as it is made ([`extra_queues_absent`]). -pub(crate) const EXTRA_QUEUES_ABSENT: &str = "metal2vulkan-extra-queues-absent"; - -/// The informational message a device that reserved only `reserved` of the `asked` queues -/// (`DeviceOptions::reserved_queues`) sends as it is made; `None` where it reserved every one. -pub(crate) fn reserved_queues_absent(asked: u32, reserved: usize, device: &str) -> Option { - if reserved >= asked as usize { - return None; - } - Some(format!( - "metal2vulkan: the device on {device} reserved {reserved} of the {asked} queue(s) of its \ - own queue families the options asked for: its round robin keeps its first \ - {LEAST_QUEUES} queues and presenting its {PRESENT_QUEUES} before the caller has any, \ - and its families have no more; the device was made with those it reserved, which \ - DeviceHandles::reserved_queues holds [{RESERVED_QUEUES_ABSENT}]" - )) -} - -/// The id name of the informational message a device made with fewer reserved queues than its -/// options asked for sends as it is made ([`reserved_queues_absent`]). -pub(crate) const RESERVED_QUEUES_ABSENT: &str = "metal2vulkan-reserved-queues-absent"; - -/// `description` with its `maxColorAttachments` and `maxFragmentOutputAttachments` held to -/// `limit` where it is lower (`DeviceOptions::color_attachment_limit`); as it is for `None`. -pub(crate) fn hold_color_attachments(description: &mut DeviceDescription, limit: Option) { - if let Some(limit) = limit { - let limits = &mut description.limits; - limits.max_color_attachments = limits.max_color_attachments.min(limit); - limits.max_fragment_output_attachments = limits.max_fragment_output_attachments.min(limit); - } -} - -/// `description` with each of `withheld` no color attachment -/// (`DeviceOptions::withheld_attachment_formats`): its tilings' `COLOR_ATTACHMENT` and blend -/// features and its attachment sample counts left out. -pub(crate) fn withhold_attachments( - description: &mut DeviceDescription, - withheld: &BTreeSet, -) { - use metal2vulkan::vk::{FormatFeatureFlags2, SampleCountFlags}; - let attachment = - FormatFeatureFlags2::COLOR_ATTACHMENT | FormatFeatureFlags2::COLOR_ATTACHMENT_BLEND; - for format in withheld { - if let Some(properties) = description.formats.formats.get_mut(format) { - properties.optimal_tiling = properties.optimal_tiling.difference(attachment); - properties.linear_tiling = properties.linear_tiling.difference(attachment); - properties.color_attachment_sample_counts = SampleCountFlags::empty(); - } - } -} - -/// What a device of `description` the runtime creates under `options` enables: the -/// description's recommended enables for the options' policy and `VK_EXT_external_memory_host` -/// where listed (the runtime's own need: buffers over host memory without a copy), less -/// the withheld features and extensions. `DeviceDescription::with_enabled` checks it is a valid -/// set. -pub(crate) fn enable_set(description: &DeviceDescription, options: &DeviceOptions) -> EnableSet { - let mut set = description.recommended_enables(&options.policy); - set.features - .retain(|feature| !options.withheld_features.contains(feature)); - let host_memory = VkExtension::ExtExternalMemoryHost; - if description.extensions.contains(&host_memory) { - set.extensions.insert(host_memory); - } - set.extensions - .retain(|extension| !options.withheld_extensions.contains(extension)); - set -} - -/// The extensions of the dma-buf route (`dma_buf.rs`) of a device listing `listed`: -/// `VK_KHR_external_memory_fd` and the `VK_EXT_external_memory_dma_buf` that requires it, where the -/// device lists both. The runtime's own need, outside the vocabulary, so outside the enable set, -/// the compile profile and its fingerprint (the shader cache's key). -pub(crate) fn dma_buf_names(listed: &BTreeSet) -> Option<[&'static CStr; 2]> { - let names = [ - ash::khr::external_memory_fd::NAME, - ash::ext::external_memory_dma_buf::NAME, - ]; - names - .iter() - .all(|name| listed.contains(*name)) - .then_some(names) -} - -/// The extension of buffers whose memory another API imports (`exported_memory.rs`) of a device -/// listing `listed`: `VK_KHR_external_memory_fd`, where the device lists it. The runtime's own -/// need, outside the vocabulary as the dma-buf route's are ([`dma_buf_names`], which enable it -/// too). -pub(crate) fn memory_fd_name(listed: &BTreeSet) -> Option<&'static CStr> { - let name = ash::khr::external_memory_fd::NAME; - listed.contains(name).then_some(name) -} - -/// The extension of the acquire of a dma-buf-exportable buffer's memory from the foreign agent -/// that wrote it (`exported_memory.rs`, `Buffer::external_write_done`) of a device listing -/// `listed`: `VK_EXT_queue_family_foreign`, where the device lists it and the dma-buf route's -/// ([`dma_buf_names`]). The runtime's own need, outside the vocabulary as the route's are; the -/// route's image extensions name it too ([`dma_buf_image_names`]), which enable it then. -pub(crate) fn foreign_family_name(listed: &BTreeSet) -> Option<&'static CStr> { - let name = ash::ext::queue_family_foreign::NAME; - (dma_buf_names(listed).is_some() && listed.contains(name)).then_some(name) -} - -/// The extension of shared events whose timeline semaphore another API imports -/// (`exported_semaphore.rs`) of a device listing `listed`: `VK_KHR_external_semaphore_fd`, where -/// the device lists it. The runtime's own need, outside the vocabulary. -pub(crate) fn semaphore_fd_name(listed: &BTreeSet) -> Option<&'static CStr> { - let name = ash::khr::external_semaphore_fd::NAME; - listed.contains(name).then_some(name) -} - -/// The extension that brings `VK_ATTACHMENT_STORE_OP_NONE` (core in Vulkan 1.3) to a device -/// listing `listed`: `VK_KHR_load_store_op_none`, else `VK_EXT_load_store_op_none`, of no -/// requirement and no feature member, outside the vocabulary (`render/snapshot.rs`, leading -/// snapshots). -pub(crate) fn store_none_name(listed: &BTreeSet) -> Option<&'static CStr> { - STORE_NONE_NAMES - .into_iter() - .find(|&name| listed.contains(name)) -} - -/// The names of the extensions that bring `VK_ATTACHMENT_STORE_OP_NONE`, as [`store_none_name`] -/// prefers them. -pub(crate) const STORE_NONE_NAMES: [&CStr; 2] = - [c"VK_KHR_load_store_op_none", c"VK_EXT_load_store_op_none"]; - -/// The extensions of the images of textures over the dma-buf route's pages (`dma_buf.rs`) of a -/// device listing `listed`: `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`, -/// where the device lists both and the route's two ([`dma_buf_names`]). Outside the vocabulary as -/// the route's are; what they require is core at the runtime's Vulkan 1.2 floor. -pub(crate) fn dma_buf_image_names(listed: &BTreeSet) -> Option<[&'static CStr; 2]> { - let names = [ - ash::ext::image_drm_format_modifier::NAME, - ash::ext::queue_family_foreign::NAME, - ]; - (dma_buf_names(listed).is_some() && names.iter().all(|name| listed.contains(*name))) - .then_some(names) -} - -/// Whether a device of `description` the runtime creates under `options` enables -/// `VK_EXT_device_generated_commands`: where the description states it (the extension and its -/// `deviceGeneratedCommands`), `options` do not withhold it, and `set` enables -/// `bufferDeviceAddress`, which it requires. `set` then gains `VK_KHR_maintenance5` and its -/// feature, which it requires too, unless they are withheld or the device lacks them, when it is -/// not enabled. -pub(crate) fn generated_commands( - description: &DeviceDescription, - options: &DeviceOptions, - set: &mut EnableSet, -) -> bool { - let maintenance5 = (VkExtension::KhrMaintenance5, VkFeature::Maintenance5); - let enabled = description.generated_commands.is_some() - && !options.withhold_generated_commands - && set.features.contains(&VkFeature::BufferDeviceAddress) - && description.extensions.contains(&maintenance5.0) - && description.features.contains(&maintenance5.1) - && !options.withheld_extensions.contains(&maintenance5.0) - && !options.withheld_features.contains(&maintenance5.1); - if enabled { - set.extensions.insert(maintenance5.0); - set.features.insert(maintenance5.1); - } - enabled -} - -/// Whether a device the runtime creates enables `hostImageCopy`, with the extensions `names` -/// (`enables::host_image_copy_names` of its version), the runtime's own need outside the -/// vocabulary: where the device lists `names`, and `supported`, asked only then, answers that it -/// has the feature. A `Shared` or `Managed` texture's CPU copies run on the host there -/// (`texture/host_copy.rs`), and a heap's colour texture takes host-transfer usage where its driver -/// serves it (`texture/heap.rs`). -pub(crate) fn host_image_copy( - names: &[&CStr], - listed: &BTreeSet, - supported: impl FnOnce() -> bool, -) -> bool { - names.iter().all(|&name| listed.contains(name)) && supported() -} - -/// Whether `physical` has `hostImageCopy`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, and the instance uses it at Vulkan 1.4 or later or -/// it lists `VK_EXT_host_image_copy`. -unsafe fn host_image_copy_supported( - instance: &InstanceShared, - physical: vk::PhysicalDevice, -) -> bool { - let mut host = vk::PhysicalDeviceHostImageCopyFeaturesEXT::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut host); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_features2(physical, &mut features) - }; - host.host_image_copy == vk::TRUE -} - -/// Whether `physical` has `zeroInitializeDeviceMemory`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_EXT_zero_initialize_device_memory`. -unsafe fn zero_initialize_device_memory_supported( - instance: &InstanceShared, - physical: vk::PhysicalDevice, -) -> bool { - let mut zero = crate::enables::ZeroInitializeDeviceMemoryFeatures::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut zero); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_features2(physical, &mut features) - }; - zero.zero_initialize_device_memory == vk::TRUE -} - -/// Whether a device that lists `listed` links its render pipelines from graphics pipeline -/// libraries: it lists `VK_EXT_graphics_pipeline_library` and `VK_KHR_pipeline_library`, which it -/// requires, and `supported` (asked only then) says it has the feature, links fast and takes each -/// library's interpolation decorations independently. -pub(crate) fn graphics_pipeline_library( - listed: &BTreeSet, - supported: impl FnOnce() -> bool, -) -> bool { - crate::enables::GRAPHICS_PIPELINE_LIBRARY - .iter() - .all(|name| listed.contains(*name)) - && supported() -} - -/// Whether `physical` has `graphicsPipelineLibrary`, and links libraries fast -/// (`graphicsPipelineLibraryFastLinking`) with each library's interpolation decorations its own -/// (`graphicsPipelineLibraryIndependentInterpolationDecoration`): a library of a fragment -/// function is then linked with any pre-rasterization library, whatever decorations its outputs -/// carry. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_EXT_graphics_pipeline_library`. -pub(super) unsafe fn graphics_pipeline_library_supported( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> bool { - let mut library = vk::PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut library); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { instance.get_physical_device_features2(physical, &mut features) }; - let mut linking = vk::PhysicalDeviceGraphicsPipelineLibraryPropertiesEXT::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut linking); - // SAFETY: as above. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - library.graphics_pipeline_library == vk::TRUE - && linking.graphics_pipeline_library_fast_linking == vk::TRUE - && linking.graphics_pipeline_library_independent_interpolation_decoration == vk::TRUE -} - -/// Whether `physical` has `samplerYcbcrConversion` (Vulkan 1.1's). -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.2 or later. -unsafe fn ycbcr_conversion_supported( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> bool { - let mut v11 = vk::PhysicalDeviceVulkan11Features::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut v11); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { instance.get_physical_device_features2(physical, &mut features) }; - v11.sampler_ycbcr_conversion == vk::TRUE -} - -/// Whether `physical` has `VK_EXT_ycbcr_2plane_444_formats`' `ycbcr2plane444Formats`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.2 or later, and lists the -/// extension. -unsafe fn ycbcr_444_supported(instance: &ash::Instance, physical: vk::PhysicalDevice) -> bool { - let mut formats = vk::PhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut formats); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { instance.get_physical_device_features2(physical, &mut features) }; - formats.ycbcr2plane444_formats == vk::TRUE -} - -/// Whether a device that lists `listed` enables `VK_EXT_pageable_device_local_memory` and its -/// `pageableDeviceLocalMemory`: it lists the extension and `VK_EXT_memory_priority`, which it -/// requires, and has the feature (`supported`, asked only then). -pub(crate) fn pageable_device_local_memory( - listed: &BTreeSet, - supported: impl FnOnce() -> bool, -) -> bool { - (crate::enables::PAGEABLE_DEVICE_LOCAL_MEMORY.iter()).all(|&name| listed.contains(name)) - && supported() -} - -/// Whether `physical` has `pageableDeviceLocalMemory`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_EXT_pageable_device_local_memory`. -unsafe fn pageable_device_local_memory_supported( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> bool { - let mut pageable = vk::PhysicalDevicePageableDeviceLocalMemoryFeaturesEXT::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut pageable); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { instance.get_physical_device_features2(physical, &mut features) }; - pageable.pageable_device_local_memory == vk::TRUE -} - -/// Whether a device of version `api` (its own, capped by the instance's) that lists `listed` -/// enables `VK_NV_linear_color_attachment` and its `linearColorAttachment`: it lists the -/// extension and has what it requires, `VK_KHR_format_feature_flags2` or Vulkan 1.3, where that -/// is core, and has the feature (`supported`, asked only then). Below Vulkan 1.3 too, where it -/// lists `VK_KHR_format_feature_flags2`, which it enables with it -/// (`enables::linear_color_attachment_names`); the runtime's instance is at Vulkan 1.2 unless the -/// consumer asks another, so NVIDIA's devices never enabled it (the consumer's probe). -pub(crate) fn linear_color_attachment( - api: ApiVersion, - listed: &BTreeSet, - supported: impl FnOnce() -> bool, -) -> bool { - (api >= ApiVersion::V1_3 || listed.contains(c"VK_KHR_format_feature_flags2")) - && listed.contains(ash::nv::linear_color_attachment::NAME) - && supported() -} - -/// Whether `physical` has `linearColorAttachment`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_NV_linear_color_attachment`. -unsafe fn linear_color_attachment_supported( - instance: &InstanceShared, - physical: vk::PhysicalDevice, -) -> bool { - let mut linear = vk::PhysicalDeviceLinearColorAttachmentFeaturesNV::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut linear); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_features2(physical, &mut features) - }; - linear.linear_color_attachment == vk::TRUE -} - -/// Why a device whose set is `set` and that lists `listed` keeps its driver's internal pipeline -/// cache, `None` where the runtime makes it with that cache off -/// ([`Enables::turn_driver_pipeline_cache_off`]): it lists `VK_KHR_pipeline_binary`, `set` enables -/// `VK_KHR_maintenance5`, which the extension requires below Vulkan 1.4 (the runtime's instance is -/// at Vulkan 1.2 unless the consumer asks another), and the driver allows it (`control`, asked -/// only then: `pipelineBinaryInternalCacheControl`). -pub(crate) fn driver_cache_kept( - api: ApiVersion, - set: &EnableSet, - listed: &BTreeSet, - control: impl FnOnce() -> bool, -) -> Option<&'static str> { - let maintenance5 = api >= ApiVersion { major: 1, minor: 4 } - || set.extensions.contains(&VkExtension::KhrMaintenance5); - if !listed.contains(crate::enables::PIPELINE_BINARY) { - Some("its driver lists no `VK_KHR_pipeline_binary`, whose device structure turns it off") - } else if !maintenance5 { - Some( - "the device enables no `VK_KHR_maintenance5`, which `VK_KHR_pipeline_binary` \ - requires", - ) - } else if !control() { - Some("its driver's `pipelineBinaryInternalCacheControl` is false: it keeps the cache on") - } else { - None - } -} - -/// Whether `physical`'s driver lets a device be made with its internal pipeline cache off -/// (`pipelineBinaryInternalCacheControl`). -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_KHR_pipeline_binary`. -unsafe fn internal_cache_control(instance: &InstanceShared, physical: vk::PhysicalDevice) -> bool { - let mut binary = crate::enables::PipelineBinaryProperties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut binary); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_properties2(physical, &mut properties) - }; - binary.internal_cache_control == vk::TRUE -} - -/// Whether `physical` has `pipelineBinaries`. -/// -/// # Safety -/// -/// As [`internal_cache_control`]. -unsafe fn pipeline_binaries_supported( - instance: &InstanceShared, - physical: vk::PhysicalDevice, -) -> bool { - let mut binary = crate::enables::PipelineBinaryFeatures::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut binary); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_features2(physical, &mut features) - }; - binary.pipeline_binaries == vk::TRUE -} - -/// Whether `physical`'s portability subset has `imageViewFormatReinterpretation`. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, made at Vulkan 1.1 or later, and lists -/// `VK_KHR_portability_subset`. -unsafe fn reinterpretation_supported( - instance: &InstanceShared, - physical: vk::PhysicalDevice, -) -> bool { - let mut subset = vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default(); - let mut features = vk::PhysicalDeviceFeatures2::default().push_next(&mut subset); - // SAFETY: the caller's contract; the chain lives for the call. - unsafe { - instance - .raw - .get_physical_device_features2(physical, &mut features) - }; - subset.image_view_format_reinterpretation == vk::TRUE -} - -/// The `maxTimelineSemaphoreValueDifference` Vulkan requires of every device (its required -/// limits): `2^31 - 1`. -const MIN_TIMELINE_VALUE_DIFFERENCE: u64 = (1 << 31) - 1; - -/// Refuses a device whose timeline semaphores cannot step as Vulkan requires: one whose -/// `maxTimelineSemaphoreValueDifference` (`available`) is below Vulkan's minimum is not conformant -/// (`Unsupported`, `Feature::TimelineSemaphores` naming the value). The runtime's command buffers -/// and events are timeline semaphores, and its first signal, priming the device (`prime.rs`), is -/// already a step. -pub(crate) fn timeline_difference(available: u64) -> Result<(), Error> { - if available >= MIN_TIMELINE_VALUE_DIFFERENCE { - return Ok(()); - } - Err(Error::Unsupported(Unsupported::not_representable( - Feature::TimelineSemaphores { - max_value_difference: available, - }, - ))) -} - -/// [`timeline_difference`] of `physical`'s `maxTimelineSemaphoreValueDifference`. -/// -/// # Safety -/// `physical` was enumerated from `instance`, made at Vulkan 1.2 or later. -pub(super) unsafe fn timeline_conformant( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> Result<(), Error> { - let mut timeline = vk::PhysicalDeviceTimelineSemaphoreProperties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut timeline); - // SAFETY: the caller's; the structure is core in Vulkan 1.2. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - timeline_difference(timeline.max_timeline_semaphore_value_difference) -} - -/// Refuse a MoltenVK device of `description` running without Metal argument buffers -/// (`argument_buffers.rs`). -pub(super) fn argument_buffers_kept(description: &DeviceDescription) -> Result<(), Error> { - use super::argument_buffers::{check, Facts}; - check(Facts::of(description).argument_buffers()) -} - -/// A device on `physical`, made from `instance`. -/// A device of `physical` made with `options`, a generation handle of it: the first generation of -/// a new line, or with `recovering`, the next generation of that line (`line.rs`), made the same -/// way. -pub(super) fn create_on( - instance: &Arc, - physical: vk::PhysicalDevice, - options: &DeviceOptions, - cache: &CacheSetup, - recovering: Option<&Arc>, -) -> Result { - // In the runtime's own tests, a device of their default limits asks for no reserved or extra - // queue, which a device of its plan places otherwise (`TEST_QUEUE_LIMITS`): before anything - // is made. - #[cfg(test)] - if options.queue_limits == Some(TEST_QUEUE_LIMITS) - && (options.reserved_queues > 0 || !options.extra_queues.is_empty()) - { - needs_the_queue_plan("asks for reserved or extra queues"); - } - // SAFETY: `physical` was enumerated from the instance, created at `api_version`. - let mut description = - unsafe { DeviceDescription::query(&instance.raw, physical, instance.api_version) } - .map_err(device_error)?; - withhold_attachments(&mut description, &options.withheld_attachment_formats); - hold_color_attachments(&mut description, options.color_attachment_limit); - // SAFETY: as above. - unsafe { timeline_conformant(&instance.raw, physical) }?; - argument_buffers_kept(&description)?; - // SAFETY: `physical` was enumerated from the instance. - let families = unsafe { - instance - .raw - .get_physical_device_queue_family_properties(physical) - }; - // Whether a texture's image may lie in memory the host caches, which decides whether a queue - // of compute work stages its CPU copies where no copy engine does (`queue_plan`), within the - // queue limits or not (`QueueLimits`). - // SAFETY: as above. - let (memory, ty) = unsafe { - let raw = &instance.raw; - let ty = raw.get_physical_device_properties(physical).device_type; - (raw.get_physical_device_memory_properties(physical), ty) - }; - let types = - &memory.memory_types[..(memory.memory_type_count as usize).min(vk::MAX_MEMORY_TYPES)]; - let unified = DeviceKind::of(ty).has_unified_memory(); - let cached = - crate::memory::host_cached_placement(types, u32::MAX, MemoryClass::Private, unified) - .is_some(); - let mut plan = queue_plan_within( - &families, - options.reserved_queues, - options.queue_limits, - cached, - ) - .ok_or(Error::NoDevice)?; - let extra_places = extra_queue_places(&families, &mut plan, &options.extra_queues); - let planned = options.queue_limits.and_then(|_| { - planned_queues( - &families, - options.reserved_queues, - &options.extra_queues, - &plan, - &extra_places, - cached, - ) - }); - let queue_family = plan.primary; - let api = description.api_version; - let mut set = enable_set(&description, options); - let generated_commands = generated_commands(&description, options, &mut set); - let mut enabled = description.with_enabled(&set).map_err(device_error)?; - if !generated_commands { - enabled.generated_commands = None; - } - let compile = - metal2vulkan::device::Device::new(enabled.clone(), options.policy).map_err(device_error)?; - // SAFETY: as above. - let listed: BTreeSet = - unsafe { instance.raw.enumerate_device_extension_properties(physical) } - .map_err(vulkan)? - .iter() - .filter_map(|extension| extension.extension_name_as_c_str().ok()) - .map(CStr::to_owned) - .collect(); - // The runtime's own need, outside the vocabulary, where listed: GPU times on the host's - // clock (`gpu_time.rs`). - let calibration = gpu_time::Extension::among(&listed); - // The runtime's own need, outside the vocabulary, wherever listed (Not only on a driver that - // compiles every library of saved cache data at load): which stages a variant's cache held - // (`shader_cache/variant.rs`), and whether the driver's cache held a pipeline - // (`shader_cache/mod.rs`). Listed, not core 1.3: the runtime's instance is Vulkan 1.2 by - // default. - let feedback_name = ash::ext::pipeline_creation_feedback::NAME; - let creation_feedback = listed.contains(feedback_name); - let feedback_asked = options - .device_extensions - .iter() - .any(|name| name.as_c_str() == feedback_name); - // The runtime's own needs, outside the vocabulary, where listed (`dma_buf.rs`). - let dma_buf = dma_buf_names(&listed); - let dma_buf_images = dma_buf_image_names(&listed); - // Wherever listed (`exported_memory.rs`); the dma-buf route's names enable it already. - let memory_fd = memory_fd_name(&listed); - // Beside the route, wherever listed (`exported_memory.rs`); the route's image names enable it - // already where they are enabled. - let foreign_family = foreign_family_name(&listed); - // Wherever listed (`exported_semaphore.rs`). - let semaphore_fd = semaphore_fd_name(&listed); - // Below Vulkan 1.3, where listed: `VK_ATTACHMENT_STORE_OP_NONE`, which the passes of - // leading snapshots store with (`render_target::leading_pass`); core from 1.3. - let store_none = store_none_name(&listed).filter(|_| api < ApiVersion::V1_3); - let extra: Vec = options - .device_extensions - .iter() - .cloned() - .chain(calibration.map(|extension| extension.name().to_owned())) - .chain((creation_feedback && !feedback_asked).then(|| feedback_name.to_owned())) - .chain(dma_buf.into_iter().flatten().map(CStr::to_owned)) - .chain((memory_fd.filter(|_| dma_buf.is_none())).map(CStr::to_owned)) - .chain(semaphore_fd.map(CStr::to_owned)) - .chain(store_none.map(CStr::to_owned)) - .chain(dma_buf_images.into_iter().flatten().map(CStr::to_owned)) - .chain((foreign_family.filter(|_| dma_buf_images.is_none())).map(CStr::to_owned)) - .collect(); - let mut enables = Enables::of(&set, api, &listed, &extra)?; - // The features of the caller's extensions whose structures the runtime knows, as the device - // has them: one it lacks refuses the device. - // An extension the device does not list is not asked about: the create call refuses it. - let caller: Vec<_> = listed_structures(&options.device_extensions) - .into_iter() - .filter(|(name, _)| listed.contains(*name)) - .collect(); - // The caller's optional extensions the device may enable: those it lists whose instance - // requirements the instance enables, enabled where it has their features. - let instance_names: Vec<&CStr> = instance.extensions.iter().map(CString::as_c_str).collect(); - let optional: Vec = (options.optional_device_extensions.iter()) - .filter(|name| listed.contains(*name) && !options.device_extensions.contains(name)) - .filter(|name| { - instance_requirements_met(std::slice::from_ref(name), &instance_names).is_ok() - }) - .cloned() - .collect(); - let asked: Vec<_> = caller - .iter() - .copied() - .chain(listed_structures(&optional)) - .collect(); - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists each - // extension `asked` names. - let reported = - (!asked.is_empty()).then(|| unsafe { listed_reported(&instance.raw, physical, &asked) }); - let has = |feature: &'static str| reported.as_ref().is_some_and(|reported| reported(feature)); - enables.enable_listed(&caller, has)?; - enables.enable_where_featured(&optional, has); - // The runtime's own need, outside the vocabulary: Metal's views of another component layout - // (`view_plan.rs`), which a portability subset allows only with - // `imageViewFormatReinterpretation`, enabled where it has it, unless the options withhold - // such views (then shadowed, `texture/view_shadow.rs`). - let portability = set.extensions.contains(&VkExtension::KhrPortabilitySubset); - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // subset's extension. - let view_reinterpretation = !options.withhold_view_reinterpretation - && (!portability || unsafe { reinterpretation_supported(instance, physical) }); - if portability && view_reinterpretation { - enables.enable_view_reinterpretation(); - } - if generated_commands { - enables.enable_generated_commands(); - } - let host_names = host_image_copy_names(api); - let host_image_copy = host_image_copy(host_names, &listed, || { - // SAFETY: `physical` was enumerated from the instance, which uses it at `api`; asked - // only where `api` makes the feature core or the device lists its extension. - unsafe { host_image_copy_supported(instance, physical) } - }); - if host_image_copy { - enables.enable_host_image_copy(host_names); - } - // The runtime's own need, outside the vocabulary, where listed with its feature: a `Shared` - // or `Managed` texture's image that copies on the host starts in memory the driver zeroed - // (`texture/host_copy.rs`). - let zero_initialize_device_memory = host_image_copy - && listed.contains(crate::enables::ZERO_INITIALIZE_DEVICE_MEMORY) - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // extension. - && unsafe { zero_initialize_device_memory_supported(instance, physical) }; - if zero_initialize_device_memory { - enables.enable_zero_initialize_device_memory(); - } - // The runtime's own need, outside the vocabulary, where listed with its feature and what it - // requires: textures over buffers' memory render into their linear images in place - // (`linear_attachment.rs`). - let linear_color_attachment = linear_color_attachment(api, &listed, || { - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // extension. - unsafe { linear_color_attachment_supported(instance, physical) } - }); - if linear_color_attachment { - enables.enable_linear_color_attachment(crate::enables::linear_color_attachment_names(api)); - } - // The runtime's own need, outside the vocabulary, where the device lists the extensions and - // links libraries fast: its render pipelines are linked from libraries of their parts - // (`pipeline/libraries.rs`). - let graphics_pipeline_library = graphics_pipeline_library(&listed, || { - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // extensions. - unsafe { graphics_pipeline_library_supported(&instance.raw, physical) } - }); - if graphics_pipeline_library { - enables.enable_graphics_pipeline_library(); - } - // The runtime's own need, outside the vocabulary, where the device has it: two-plane YCbCr - // textures convert through the device's own conversion (`ycbcr_device.rs`). - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2. - let ycbcr_conversion = unsafe { ycbcr_conversion_supported(&instance.raw, physical) }; - if ycbcr_conversion { - enables.enable_ycbcr_conversion(); - } - // And its two-plane 4:4:4 formats: core from Vulkan 1.3, else where the device lists - // `VK_EXT_ycbcr_2plane_444_formats` with its feature. - let ycbcr_444 = ycbcr_conversion - && (api >= ApiVersion::V1_3 - || listed.contains(ash::ext::ycbcr_2plane_444_formats::NAME) - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and - // lists the extension. - && unsafe { ycbcr_444_supported(&instance.raw, physical) }); - if ycbcr_444 && api < ApiVersion::V1_3 { - enables.enable_ycbcr_2plane_444(); - } - // The runtime's own need, outside the vocabulary, where listed with its feature: the driver - // may move device-local memory to host-local memory to make room rather than fail an - // allocation, as Metal pages a discrete GPU's resources (`memory.rs`'s - // `overflow_candidates`, which places them past a full device-local heap where it fails). On - // an RTX 5080 Laptop GPU (Linux) with it, 72 `Private` buffers of 256 MiB, past its 17.09 GB - // device-local heap, were made in device-local memory; without it the 60th overflowed. - let pageable = pageable_device_local_memory(&listed, || { - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // extension. - unsafe { pageable_device_local_memory_supported(&instance.raw, physical) } - }); - if pageable { - enables.enable_pageable_device_local_memory(); - } - // The runtime's own need, outside the vocabulary: the device's pipelines are cached in the - // shader cache's records alone, the driver's internal cache off where it allows; else the - // device says once that the driver keeps it. - let cache_kept = driver_cache_kept(api, &set, &listed, || { - // SAFETY: `physical` was enumerated from the instance, made at Vulkan 1.2, and lists the - // extension. - unsafe { internal_cache_control(instance, physical) } - }); - if cache_kept.is_none() { - // SAFETY: as above. - let binaries = unsafe { pipeline_binaries_supported(instance, physical) }; - enables.turn_driver_pipeline_cache_off(binaries); - } - // The runtime's own need, outside the vocabulary: sparse heaps (`sparse/device.rs`), where - // the queue family binds sparse memory (every family taken is equivalent to the primary). - // SAFETY: `physical` was enumerated from the instance. - let available = unsafe { instance.raw.get_physical_device_features(physical) }; - let sparse_features = families - .get(queue_family as usize) - .filter(|family| family.queue_flags.contains(vk::QueueFlags::SPARSE_BINDING)) - .map_or_else(vk::PhysicalDeviceFeatures::default, |_| { - sparse::device::wanted(&available) - }); - enables.enable_sparse(&sparse_features); - // The device of the plan's queues, else, where the driver refuses it for want of its - // resources, of the least plan's (`made_within_resources`). - let least = least_queue_plan(&families, options, cached); - let make = |(plan, extra_places): &PlacedQueues| { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if let Some(refused) = refusal_stand_in() { - return Err(refused); - } - // One create info per family taken, of as many queues as the plan takes of it. - let taken = families_taken(plan, extra_places); - // One priority per queue of the family the plan and the extra queues take most of, so - // the slice each create info names is always within it: the round robin alone takes up - // to `ROUND_ROBIN_CEILING` of one family, presenting `PRESENT_QUEUES` more, and the - // reserved and extra queues at most the family's own count. - let priorities = vec![1.0f32; taken.iter().map(|&(_, count)| count).max().unwrap_or(0)]; - let queues: Vec> = taken - .iter() - .map(|&(family, count)| { - vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities[..count]) - }) - .collect(); - // At the user-initiated class: MoltenVK compiles its command shaders as it makes the - // device. - enables.with_create_info(&queues, |info| { - let asked = super::compiles::Sent::new(info); - let instance = &instance.raw; - super::compiles::at_user_initiated(move || { - // SAFETY: the create info and its chain live for the call, and the asking thread - // waits for it; `physical` is the instance's. - unsafe { instance.create_device(physical, asked.into_inner(), None) } - }) - }) - }; - let name = &enabled.device_name; - let (raw, (plan, extra_places), took_least) = - made_within_resources(name, (plan, extra_places), least, make)?; - // A device was made from the instance: the drivers stay loaded from now on, kept before the - // device is primed and registers the exit hook, so what the keeper's instance loads is - // loaded before that registration (`keeper.rs`). - keep_drivers_loaded(instance); - // The least plan's queues are the runtime's own choice, not the caller's limits: no limits' - // messages ([`LeastPlanTaken`]). - let planned = planned.filter(|_| took_least.is_none()); - // SAFETY: the device was just created: its word is the loader's. - let loader_word = unsafe { DeviceWord::of_device(raw.handle()) }; - let primary = families.get(queue_family as usize); - let memory_reads = MemoryReads::of( - primary.map_or(vk::QueueFlags::empty(), |family| family.queue_flags), - enables.names(), - ); - let reserved = plan.reserved.len(); - let plan_reserved = plan.reserved.clone(); - let parts = Parts { - instance: Arc::clone(instance), - physical, - raw, - loader_word, - queue_family, - present_queues: plan.present.len(), - planned: (planned.as_ref()).map(|planned| (planned.round_robin, planned.presenting)), - least_plan: took_least.is_some(), - queues: plan.queues.into_iter().chain(plan.present).collect(), - staging: plan.staging, - fill: plan.fill, - copies: plan.copies, - reserved_queues: plan.reserved, - extra_queues: (options.extra_queues.iter().zip(&extra_places)) - .filter_map(|(&flags, place)| place.map(|(family, index)| (flags, family, index))) - .collect(), - compile, - description: enabled, - enabled: set, - extensions: enables.names().map(CStr::to_owned).collect(), - calibration, - gpu_times_from_host: options.gpu_times_from_host, - mac_class: options.mac_class, - announce_each: options.announce_each.clone(), - lowering_refuses: options.lowering_refuses.clone(), - record_executions: options.record_executions, - load_no_dynamic_library_file: options.load_no_dynamic_library_file, - pipeline_records: options.pipeline_records.clone(), - fail_in_place_check: options.fail_in_place_check, - #[cfg(test)] - view_facts: options.view_facts.clone(), - assume_submissions_merge: options.assume_submissions_merge, - pending_audit: options.pending_audit, - encoder_trail: options.encoder_trail, - view_reinterpretation, - generated_commands, - host_image_copy, - zero_initialize_device_memory, - linear_color_attachment, - graphics_pipeline_library, - ycbcr_conversion, - ycbcr_444, - creation_feedback: creation_feedback || feedback_asked, - dma_buf: dma_buf.is_some(), - dma_buf_images: dma_buf_images.is_some(), - #[cfg(unix)] - memory_fd: memory_fd.is_some(), - #[cfg(unix)] - foreign_family: foreign_family.is_some(), - #[cfg(unix)] - semaphore_fd: semaphore_fd.is_some(), - sparse_features, - memory_reads, - owned: true, - cache: cache.clone(), - line: recovering.cloned(), - recipe: match recovering { - Some(_) => None, - None => Some(Recipe { - instance: Arc::clone(instance), - physical, - options: options.clone(), - cache: cache.clone(), - }), - }, - }; - // SAFETY: the device was made from these parts just now. - let device = unsafe { Device::assemble(parts) }?; - if let Some(text) = layers_dropped(&instance.dropped_layers, device.name()) { - device.inform(LAYERS_DROPPED, text); - } - let absent: Vec = (options.extra_queues.iter().zip(&extra_places)) - .filter(|(_, place)| place.is_none()) - .map(|(&flags, _)| flags) - .collect(); - if let Some(text) = extra_queues_absent(&absent, device.name()) { - device.inform(EXTRA_QUEUES_ABSENT, text); - } - if let Some(text) = reserved_queues_absent(options.reserved_queues, reserved, device.name()) { - device.inform(RESERVED_QUEUES_ABSENT, text); - } - if let Some(taken) = took_least { - device.degrade(Degradation::LeastQueuePlan, || { - ( - format!("the device, on {}", device.name()), - format!( - "the driver refused it with its queue plan's {} VkQueue(s) ({:?}); it took \ - its least plan's {}", - taken.planned, taken.refusal, taken.least - ), - ) - }); - } - // In the runtime's own tests, a device of their default limits fails its test where its work - // needs more (`TEST_QUEUE_LIMITS`). - #[cfg(test)] - if options.queue_limits == Some(TEST_QUEUE_LIMITS) { - (device.shared().test_queue_limits).store(true, std::sync::atomic::Ordering::Relaxed); - } - let reserved_places = &plan_reserved; - if let Some(planned) = &planned { - if planned.reserved != *reserved_places { - device.inform_once(Told::QueueLimitsReached, QUEUE_LIMITS_REACHED, || { - let what = format!( - "the queues reserved for the caller are {reserved_places:?} (family, index), \ - where the plan reserves {:?}", - planned.reserved - ); - queue_limits_reached(device.name(), &what) - }); - } - if planned.extra != extra_places { - device.inform_once(Told::QueueLimitsReached, QUEUE_LIMITS_REACHED, || { - let what = format!( - "the extra queues are at {extra_places:?} (family, index), where the plan \ - places them at {:?}", - planned.extra - ); - queue_limits_reached(device.name(), &what) - }); - } - } - if let Some(why) = cache_kept { - let object = format!("the device, on {}", device.name()); - if kept_cache_is_metals(device.properties().description.driver_id) { - device.inform( - METAL_CACHE_KEPT, - format!( - "metal2vulkan: {object}: {why}; its internal pipeline cache is Metal's own \ - shader cache, which every Metal program on the host keeps: nothing differs \ - from Metal [{METAL_CACHE_KEPT}]" - ), - ); - } else { - device.degrade(Degradation::DriverPipelineCacheKept, || { - (object, why.to_owned()) - }); - } - } - Ok(device) -} - -/// The id name of the informational message a device whose driver keeps its internal pipeline -/// cache, that cache being Metal's own ([`kept_cache_is_metals`]), sends as it is made. -pub(crate) const METAL_CACHE_KEPT: &str = "metal2vulkan-driver-pipeline-cache-kept"; - -/// Whether the internal pipeline cache a driver of identity `driver` keeps is Metal's own shader -/// cache: MoltenVK's, whose pipelines are Metal pipeline states that Metal caches on the host -/// for every Metal program alike, so keeping it is Metal's behaviour exactly. Every other -/// driver's is a second cache beside the shader cache's records, which costs a warm making -/// and announces `driver-pipeline-cache-kept`. -pub(crate) fn kept_cache_is_metals(driver: Option) -> bool { - driver == Some(metal2vulkan::vk::DriverId::MOLTENVK) -} - -/// The devices `system_default_with` and `all_with` made, by the options they were made with -/// (the module docs): each group's instance and its devices by physical device, held weakly. A -/// group whose instance is gone has no device left (each device holds its instance), and is -/// dropped at the next call. -static MADE: Mutex> = Mutex::new(Vec::new()); - -/// One group of `MADE`: the devices made with equal options. -struct Made { - /// The options, less the message sink, which the instance holds (`InstanceShared::sink`), - /// and the pipeline records' hook, which `records` names: the group keeps neither alive past - /// its devices. - options: DeviceOptions, - /// The options' pipeline records' hook, which each of the group's devices holds. - records: Option>, - instance: Weak, - devices: Vec<(vk::PhysicalDevice, Weak)>, -} - -impl Made { - /// The group's instance, while a device of it lives, where it was made with `options`. - fn instance_for(&self, options: &DeviceOptions) -> Option> { - let instance = self.instance.upgrade()?; - let sinks = match (&options.messages, instance.sink()) { - (None, None) => true, - (Some(asked), Some(made)) => asked.same(made), - _ => false, - }; - let records = match (&options.pipeline_records, &self.records) { - (None, None) => true, - (Some(asked), Some(made)) => std::sync::Weak::ptr_eq(&Arc::downgrade(asked), made), - _ => false, - }; - (sinks && records && same_options(&self.options, options)).then_some(instance) - } - - /// The live device of `physical`, if the group has one: a root handle of its line. - fn device(&self, physical: vk::PhysicalDevice) -> Option { - self.devices - .iter() - .find(|(of, _)| *of == physical) - .and_then(|(_, line)| line.upgrade()) - .and_then(holds::revive_root) - } -} - -/// The live devices of the group of `options` (equal options and the same message sink), for the -/// tests: none where no such group lives. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn live_devices_with(options: &DeviceOptions) -> usize { - let made = lock(&MADE); - let of = made - .iter() - .find(|group| group.instance_for(options).is_some()); - of.map_or(0, |group| { - let devices = group.devices.iter(); - devices.filter(|(_, line)| line.strong_count() > 0).count() - }) -} - -/// Whether `a` and `b` are equal options, but for their message sinks and pipeline records' -/// hooks (compared by `Made`). -fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { - // Every field is named, so a field added later is compared or this fails to compile. - let DeviceOptions { - policy, - layers, - layer_settings, - instance_extensions, - device_extensions, - optional_device_extensions, - withheld_features, - withheld_extensions, - messages: _, - loader, - kinds, - shader_cache, - withhold_generated_commands, - withhold_view_reinterpretation, - load_no_dynamic_library_file, - instance_api_version, - gpu_times_from_host, - mac_class, - announce_each, - lowering_refuses, - record_executions, - fail_in_place_check, - assume_submissions_merge, - pending_audit, - encoder_trail, - withheld_attachment_formats, - color_attachment_limit, - pipeline_records: _, - extra_queues, - reserved_queues, - queue_limits, - #[cfg(test)] - view_facts, - } = a; - let same = *policy == b.policy - && *layers == b.layers - && *layer_settings == b.layer_settings - && *instance_extensions == b.instance_extensions - && *device_extensions == b.device_extensions - && *optional_device_extensions == b.optional_device_extensions - && *withheld_features == b.withheld_features - && *withheld_extensions == b.withheld_extensions - && *loader == b.loader - && *kinds == b.kinds - && *shader_cache == b.shader_cache - && *withhold_generated_commands == b.withhold_generated_commands - && *withhold_view_reinterpretation == b.withhold_view_reinterpretation - && *load_no_dynamic_library_file == b.load_no_dynamic_library_file - && *instance_api_version == b.instance_api_version - && *gpu_times_from_host == b.gpu_times_from_host - && *mac_class == b.mac_class - && *announce_each == b.announce_each - && *lowering_refuses == b.lowering_refuses - && *record_executions == b.record_executions - && *fail_in_place_check == b.fail_in_place_check - && *assume_submissions_merge == b.assume_submissions_merge - && *pending_audit == b.pending_audit - && *encoder_trail == b.encoder_trail - && *withheld_attachment_formats == b.withheld_attachment_formats - && *color_attachment_limit == b.color_attachment_limit - && *extra_queues == b.extra_queues - && *reserved_queues == b.reserved_queues - && *queue_limits == b.queue_limits; - #[cfg(test)] - let same = same && *view_facts == b.view_facts; - same -} - -/// The group of `made` for `options`: the live one, or a new one on a new instance. Its index. -fn group( - made: &mut Vec, - options: &DeviceOptions, -) -> Result<(usize, Arc), Error> { - made.retain(|group| group.instance.strong_count() > 0); - if let Some(found) = made - .iter() - .enumerate() - .find_map(|(at, group)| group.instance_for(options).map(|instance| (at, instance))) - { - return Ok(found); - } - let instance = create_instance(options)?; - made.push(Made { - options: DeviceOptions { - messages: None, - pipeline_records: None, - ..options.clone() - }, - records: options.pipeline_records.as_ref().map(Arc::downgrade), - instance: Arc::downgrade(&instance), - devices: Vec::new(), - }); - Ok((made.len() - 1, instance)) -} - -/// The device of `physical` in `group`: its live one, or one made now and kept there. -fn device_of( - group: &mut Made, - instance: &Arc, - physical: vk::PhysicalDevice, - options: &DeviceOptions, - cache: &CacheSetup, -) -> Result { - if let Some(device) = group.device(physical) { - return Ok(device); - } - let device = create_on(instance, physical, options, cache, None)?.root(); - group.devices.retain(|(_, line)| line.strong_count() > 0); - group - .devices - .push((physical, Arc::downgrade(device.line()))); - Ok(device) -} - -impl Device { - /// `MTLCreateSystemDefaultDevice`: [`Device::system_default_with`] the default options. - pub fn system_default() -> Result { - Device::system_default_with(&DeviceOptions::default()) - } - - /// The device of the preferred qualifying physical device (discrete, then integrated, - /// virtual, CPU): the first one, in that order, the runtime can create. The error of the - /// first refusal when none can be, and [`Error::NoDevice`] when there is none. - /// - /// A physical device has one device per options, as Metal's GPU has one `MTLDevice`: while - /// a handle to the device this or [`Device::all_with`] made with equal options lives (the - /// same message sink, a clone of it, and every other field equal), the call returns that - /// device. Once its last handle drops, the device tears down, and the next call makes a - /// fresh one. - /// - /// Once it has made a device, the runtime keeps the loader library and every Vulkan driver - /// it loaded for the life of the process: one bare instance, with no layers and no - /// messenger, is never destroyed. The loader would otherwise unload the drivers with the - /// last device and load them again for the next, which some drivers cannot do indefinitely. - pub fn system_default_with(options: &DeviceOptions) -> Result { - let cache = CacheSetup::of(&options.shader_cache, "system_default_with")?; - Device::system_default_set_up(options, &cache) - } - - /// [`Device::system_default_with`] with its shader cache set up already as `cache`, which a - /// test sets up from an environment of its own (`tests::shader_cache_no_directory`). - pub(crate) fn system_default_set_up( - options: &DeviceOptions, - cache: &CacheSetup, - ) -> Result { - let mut made = lock(&MADE); - let (at, instance) = group(&mut made, options)?; - let mut refusal = None; - for physical in ranked(&instance, options)? { - match device_of(&mut made[at], &instance, physical, options, cache) { - Ok(device) => return Ok(device), - Err(error) => { - refusal.get_or_insert(error); - } - } - } - Err(refusal.unwrap_or(Error::NoDevice)) - } - - /// The identity of the physical device [`Device::system_default_with`] makes its device of - /// with `options`, read without making any device: the first of - /// [`Device::identities_with`]'s, whose order (the preferred qualifying kind, then - /// enumeration order) and physical devices are the ones that call tries, so the two cannot - /// name different physical devices. A runtime extension, no Metal call (Metal's program holds - /// an `MTLDevice` to ask it anything). - /// - /// The physical device named is the one [`Device::system_default_with`] tries first. Where - /// that call then refuses it as it makes its device (unsupported, or without a graphics and - /// compute queue) it falls to the next, and makes a device of another physical device than - /// the one named here, as [`Device::registry_ids_with`] lists such a physical device all the - /// same. - /// - /// [`Error::NoDevice`] where `options` admit no physical device at Vulkan 1.2 or later, of - /// which the runtime makes no device: that call answers `NoDevice` too where they admit none - /// at all, and the refusal of the physical device it tried where they admit one the runtime - /// cannot make a device of. - pub fn system_default_identity_with( - options: &DeviceOptions, - ) -> Result { - let first = Device::identities_with(options)?.into_iter().next(); - first.ok_or(Error::NoDevice) - } - - /// The registry IDs ([`Device::registry_id`], `registryID`) of the physical devices - /// [`Device::all_with`] makes its devices of, in its order, read without making any device: a - /// runtime extension, no Metal call (Metal lists its devices, not their IDs). They are the - /// [`PhysicalDeviceIdentity::registry_id`]s of [`Device::identities_with`], one per physical - /// device it lists: one the runtime refuses as it makes its device (unsupported, or without a - /// graphics and compute queue), which [`Device::all_with`] leaves out, is listed all the - /// same, and [`Device::with_registry_id`] answers its refusal. - pub fn registry_ids_with(options: &DeviceOptions) -> Result, Error> { - let identities = Device::identities_with(options)?.into_iter(); - Ok(identities.map(|identity| identity.registry_id).collect()) - } - - /// The identity of each physical device `options` admit, in [`Device::system_default_with`]'s - /// order (the preferred qualifying kind, then enumeration order), read without making any - /// device. No Metal call: a runtime extension, - /// whose nearest Metal counterpart is `MTLCopyAllDevices`, which answers devices that exist - /// where this answers what a device of each physical device would answer, before any is - /// made, so a consumer can choose a GPU and make only its device - /// ([`Device::with_registry_id`]). - /// - /// The physical devices of `options.kinds` at Vulkan 1.2 or later are listed. Each identity - /// is read by the property reads the device made of it takes its own from - /// (`properties::query`), with no `vkCreateDevice`, no compile device and no queue. One the - /// runtime refuses as it makes its device (unsupported, or without a graphics and compute - /// queue), which [`Device::all_with`] leaves out, is listed all the same, and - /// [`Device::with_registry_id`] answers its refusal. The instance is the one of the devices of - /// equal options while one lives (as [`Device::system_default_with`] takes it), else one made - /// for the call, which goes with it. [`Device::registry_ids_with`] and - /// [`Device::system_default_identity_with`] answer from this list. - pub fn identities_with(options: &DeviceOptions) -> Result, Error> { - let mut made = lock(&MADE); - let (_, instance) = group(&mut made, options)?; - let ranked = ranked(&instance, options)?; - let identities = identified(&instance, ranked) - .into_iter() - .map(|(_, physical)| { - // SAFETY: `physical` was enumerated from the instance, created at Vulkan 1.2 or - // later, and `identified` kept only physical devices at Vulkan 1.2 or later. - let (identity, _) = unsafe { - super::properties::query(&instance.raw, physical, instance.api_version) - }; - PhysicalDeviceIdentity::of(&identity) - }); - let identities = identities.collect(); - drop(made); - // The instance made for the call goes here, outside the lock. - drop(instance); - Ok(identities) - } - - /// The device of the physical device whose registry ID ([`Device::registry_id`]) is - /// `registry_id`, among those [`Device::registry_ids_with`] lists for `options` (the first, - /// in its order, where two share one), making no device of any other: a runtime extension - /// (Metal's program finds the device of an ID among `MTLCopyAllDevices`'s, all of which exist - /// already). As [`Device::system_default_with`] makes its device: while a handle to the - /// device of equal options lives, it is that device, and the drivers stay loaded once a - /// device was made. [`Error::NoDevice`] where no listed physical device has the ID; the - /// refusal of the device where the runtime cannot make it. - pub fn with_registry_id(registry_id: u64, options: &DeviceOptions) -> Result { - let cache = CacheSetup::of(&options.shader_cache, "with_registry_id")?; - let mut made = lock(&MADE); - let (at, instance) = group(&mut made, options)?; - let ranked = ranked(&instance, options)?; - let Some((_, physical)) = - (identified(&instance, ranked).into_iter()).find(|&(id, _)| id == registry_id) - else { - return Err(Error::NoDevice); - }; - device_of(&mut made[at], &instance, physical, options, &cache) - } - - /// `MTLCopyAllDevices`: [`Device::all_with`] the default options. - pub fn all() -> Result, Error> { - Device::all_with(&DeviceOptions::default()) - } - - /// One device per qualifying physical device, in the order of - /// [`Device::system_default_with`], sharing one instance. A physical device the runtime or - /// the compile layer cannot use (unsupported, or without a graphics and compute queue) is - /// left out; any other failure fails the call. Once it has made a device, the runtime keeps - /// the drivers loaded for the life of the process, as [`Device::system_default_with`] does. - /// A device of equal options that lives is returned again, as there (Metal's - /// `MTLCopyAllDevices()[0]` is `MTLCreateSystemDefaultDevice()`). - pub fn all_with(options: &DeviceOptions) -> Result, Error> { - let cache = CacheSetup::of(&options.shader_cache, "all_with")?; - let mut made = lock(&MADE); - let (at, instance) = group(&mut made, options)?; - let mut devices = Vec::new(); - for physical in ranked(&instance, options)? { - match device_of(&mut made[at], &instance, physical, options, &cache) { - Ok(device) => devices.push(device), - Err(Error::Unsupported(_) | Error::NoDevice) => {} - Err(error) => return Err(error), - } - } - Ok(devices) - } -} - -#[cfg(test)] -mod tests { - use super::{deliver, MessageSink}; - use ash::vk; - use metal2vulkan::device::{DriverDiagnostic, DriverFact}; - use metal2vulkan::vk::{DynamicState as D, PrimitiveTopology as T}; - use std::ffi::CString; - use std::sync::{Arc, Mutex}; - - /// The callback withholds a diagnostic the thread's current call is measured to report - /// (MoltenVK 1.4.1's warning of a pipeline whose restart is dynamic), and counts it, inside - /// that call alone: the same message outside it, from another thread while it runs, at - /// another severity or kind, or with another text, reaches the sink, as every message does - /// in a call that expects none. - #[test] - fn a_measured_diagnostic_is_withheld_inside_its_call_alone() { - let warning = DriverFact::DynamicRestartWarns - .pipeline_creation_diagnostics( - &[D::PRIMITIVE_TOPOLOGY, D::PRIMITIVE_RESTART_ENABLE], - T::TRIANGLE_LIST, - &[], - ) - .pop() - .expect("the warning of a dynamic restart"); - let received: Arc>> = Arc::default(); - let sink = { - let received = Arc::clone(&received); - MessageSink::new(move |message| { - received - .lock() - .unwrap() - .push(format!("{} {}", message.id_name, message.text)) - }) - }; - let user = std::ptr::from_ref(&sink) as usize; - use vk::DebugUtilsMessageSeverityFlagsEXT as S; - use vk::DebugUtilsMessageTypeFlagsEXT as K; - let report = |severity: S, kind: K, text: &str| sent(user, &warning, severity, kind, text); - let delivered = || received.lock().unwrap().len(); - report(S::WARNING, K::VALIDATION, &warning.text); - assert_eq!(delivered(), 1, "outside the call"); - let ((), withheld) = crate::driver_facts::expecting(vec![warning.clone()], || { - report(S::WARNING, K::VALIDATION, &warning.text); - assert_eq!(delivered(), 1, "inside the call"); - // Another thread, started as the runtime starts its own and joined before the sink - // goes. - let other = warning.clone(); - crate::exit_guard::spawn(std::thread::Builder::new(), move || { - sent(user, &other, S::WARNING, K::VALIDATION, &other.text) - }) - .unwrap() - .join() - .unwrap(); - assert_eq!(delivered(), 2, "from another thread"); - report(S::ERROR, K::VALIDATION, &warning.text); - report(S::WARNING, K::GENERAL, &warning.text); - report( - S::WARNING, - K::VALIDATION, - "VK_ERROR_FEATURE_NOT_PRESENT: Metal does not support something else.", - ); - assert_eq!(delivered(), 5, "another severity, kind or text"); - report(S::WARNING, K::VALIDATION, &warning.text); - }); - assert_eq!(withheld, 2, "withheld inside the call"); - report(S::WARNING, K::VALIDATION, &warning.text); - assert_eq!(delivered(), 6, "after the call"); - let ((), withheld) = crate::driver_facts::expecting(Vec::new(), || { - report(S::WARNING, K::VALIDATION, &warning.text); - }); - assert_eq!((withheld, delivered()), (0, 7), "a call that expects none"); - } - - /// A kept internal pipeline cache is Metal's own on MoltenVK alone, which says so in an - /// informational message; every other driver's is a second cache beside the shader cache's - /// records, announced as `driver-pipeline-cache-kept`. - #[test] - fn a_kept_cache_is_metals_on_moltenvk_alone() { - assert!(super::kept_cache_is_metals(Some( - metal2vulkan::vk::DriverId::MOLTENVK - ))); - let others = [ - Some(metal2vulkan::vk::DriverId::NVIDIA_PROPRIETARY), - Some(metal2vulkan::vk::DriverId::MESA_RADV), - Some(metal2vulkan::vk::DriverId::INTEL_OPEN_SOURCE_MESA), - Some(metal2vulkan::vk::DriverId::MESA_LLVMPIPE), - None, - ]; - for driver in others { - assert!(!super::kept_cache_is_metals(driver), "{driver:?}"); - } - } - - /// A sink with a least severity hears no message below it but degrade notices, which it hears - /// whatever their severity; a sink of `MessageSink::new` hears every severity; and a sink with - /// another least severity is not the same sink, though it calls the same receiver. - #[test] - fn a_sink_hears_no_message_below_its_least_severity_but_notices() { - use super::{DebugMessage, MessageKind, MessageSeverity as S}; - use crate::{Degradation, DegradeNotice}; - let received: Arc>> = Arc::default(); - let every = { - let received = Arc::clone(&received); - MessageSink::new(move |message| { - let notice = message.degradation.is_some(); - received.lock().unwrap().push((message.severity, notice)) - }) - }; - let message = |severity, notice: bool| { - let mut message = DebugMessage { - severity, - kind: MessageKind::default(), - id_name: String::new(), - id: 0, - text: String::new(), - degradation: None, - }; - if notice { - let kind = Degradation::UnsizedPoints; - let notice = DegradeNotice::new(kind, String::new(), String::new()); - message = DebugMessage { - severity, - ..notice.message() - }; - } - message - }; - let all = [S::Verbose, S::Info, S::Warning, S::Error]; - for least in all { - let sink = every.clone().with_least_severity(least); - assert_eq!(sink.same(&every), least == S::Verbose, "{least:?}"); - for severity in all { - assert_eq!(sink.hears(severity), severity >= least); - for notice in [false, true] { - sink.deliver(&message(severity, notice)); - let heard = received.lock().unwrap().pop(); - let expected = (notice || severity >= least).then_some((severity, notice)); - assert_eq!(heard, expected, "{least:?}: {severity:?}, notice {notice}"); - } - } - } - } - - /// Deliver `warning`'s name and number with `text` at `severity` and `kind` to the sink at - /// `user`. - fn sent( - user: usize, - warning: &DriverDiagnostic, - severity: vk::DebugUtilsMessageSeverityFlagsEXT, - kind: vk::DebugUtilsMessageTypeFlagsEXT, - text: &str, - ) { - let id_name = CString::new(warning.id_name).unwrap(); - let text = CString::new(text).unwrap(); - let data = vk::DebugUtilsMessengerCallbackDataEXT::default() - .message_id_name(&id_name) - .message_id_number(warning.id) - .message(&text); - // SAFETY: the callback data and its strings live for the call, and `user` is the sink, - // alive until every call of the test returned. - unsafe { deliver(severity, kind, &data, user as *mut std::ffi::c_void) }; - } -} diff --git a/crates/metal2vulkan-runtime/src/device/float_tininess.rs b/crates/metal2vulkan-runtime/src/device/float_tininess.rs deleted file mode 100644 index 6ab64cd53..000000000 --- a/crates/metal2vulkan-runtime/src/device/float_tininess.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! `float-tininess-after-rounding`: where the device's own `float` multiply and fused multiply-add -//! answer for Metal's. Metal flushes a `float` product, fused multiply-add or `ldexp` whose exact -//! value lies below `2^-126` to the zero of its sign, deciding tininess before rounding; every -//! Vulkan device measured off MoltenVK (RADV, ANV, NVIDIA and lavapipe, whether they flush -//! denormals or keep them) rounds before it decides, so an exact value within half a unit below -//! `2^-126` answers `2^-126`. The translation takes the device's, which every pipeline of a `float` -//! multiply may meet, and a `float` `ldexp`'s result below `2^-126` is the device's product, so the -//! device announces it once, as it is made, rather than each pipeline. - -use crate::degradation::Degradation; -use metal2vulkan::error::DriverDeviation; - -/// Whether `compile` takes the device's own `float` multiply and fused multiply-add where they -/// round a tiny result before flushing it: its float functions are not Metal's own -/// (`DriverDeviation::MetalFloatFunctions`, MoltenVK). -pub(crate) fn rounds_before_flushing(compile: &metal2vulkan::device::Device) -> bool { - !compile - .profile() - .takes_driver_deviation(DriverDeviation::MetalFloatFunctions) -} - -impl super::Device { - /// Announce `float-tininess-after-rounding` once where the device takes the device's own - /// `float` multiply and fused multiply-add ([`rounds_before_flushing`]). - pub(super) fn degrade_float_tininess(&self) { - if !rounds_before_flushing(self.compile_device()) { - return; - } - self.degrade(Degradation::FloatTininessAfterRounding, || { - ( - format!("the device {}", self.name()), - "its `float` multiply and fused multiply-add round before they flush".to_owned(), - ) - }); - } -} diff --git a/crates/metal2vulkan-runtime/src/device/functions.rs b/crates/metal2vulkan-runtime/src/device/functions.rs deleted file mode 100644 index b98722200..000000000 --- a/crates/metal2vulkan-runtime/src/device/functions.rs +++ /dev/null @@ -1,417 +0,0 @@ -//! The device's functions, the only door to them: `DeviceShared::vk` hands them out through -//! [`Functions::get`], which checks the caller (`exit_guard::check`) and, inside one of the -//! runtime's sections, hands out the exit guard's table alone ([`Call`]): the same device, loaded -//! with only the table's entry points, every other one ash's stub, which panics where unwinding -//! cannot pass and so ends the process. In builds with debug assertions (every test run), a section -//! that calls an entry point outside the table therefore fails the lane that reaches it, so the -//! table holds every entry point a section calls, and priming, which makes each before the exit -//! hook is registered (`prime.rs`), covers them all. Other builds hand out every function. -//! -//! Each is a [`Vk`]: the `ash::Device`, which it dereferences to, the reads the commands of the -//! device's queue family for encoders make, which the runtime's global memory barriers name in -//! their destination (`tracker::Barrier::record`, `image_barrier::MemoryReads`), the push -//! command where the device has it (`binding::push_descriptor_command`), and -//! `vkSetDebugUtilsObjectNameEXT` where its instance reports messages (`pipeline/graphics.rs`). -//! Its copy commands count each place in the runtime that records them ([`CopySites`]). Where the -//! device's pending audit is on (`pending_audit.rs`), its `vkBeginCommandBuffer` checks the command -//! buffer first and its `vkCmdExecuteCommands` notes the secondaries each primary executes: both -//! tables hold the audit, so every begin and execution made through them reaches it. -//! -//! Each `vkCmdCopyBuffer` region over [`SPLIT_ABOVE`] bytes whose size is no multiple of -//! [`SPLIT_UNIT`] is recorded as two regions of the same command: its bytes up to the last whole -//! multiple of [`SPLIT_UNIT`], and the rest. The same bytes are copied, by the same command, so -//! every caller's stages and accesses hold as they are (`WorkCounts::copy_regions_split`). A -//! driver's recording CPU for one region may grow with its size at some sizes and not at others: -//! on ANV, Mesa 26.2.4, on the UHD 770 (`row_copies::span_copy_cost` in the validation crate's -//! runtime lane, the recording thread's CPU time a frame of one blit of one region) 8,294,411 bytes -//! (a prime) took 28-40 ms and 6.0 ms of GPU time, 8,294,576 (16 times a prime) 1.5-2.4 ms and -//! 3,110,608 (16 times a prime) 0.74-0.91 ms, against 0.006-0.035 ms for 8,294,400 (2025 times -//! 4 KiB); split so, 8,294,411 bytes took 0.018-0.060 ms and 0.64-0.76 ms of GPU time. RADV -//! (Mesa 26.0.8) recorded the split in the same CPU time; its GPU time was 5 to 9 us (0.3-1.1%) -//! more on the RX 7900 XTX at 3.1 and 8.3 MB, and on the Radeon 780M up to 9% more at some sizes -//! and 25% less at others (8,294,411 bytes: 242-243 us split, 320-328 us whole). NVIDIA's -//! 615.71.09 on the RTX 3090 likewise: within 3 us of the GPU time, and 8,294,411 bytes 1.52 ms -//! split against 6.05-6.06 ms whole. - -use crate::exit_guard::{self, Call}; -use crate::image_barrier::MemoryReads; -use crate::pending_audit::PendingAudit; -use crate::recorder::Slot; -use crate::work_counts::{CopySite, CopySites, COPY_SITES}; -use ash::vk; -use std::ffi::{c_void, CStr}; -use std::ops::Deref; -use std::panic::Location; -use std::sync::Arc; - -/// The bytes past which a `vkCmdCopyBuffer` region whose size is no multiple of [`SPLIT_UNIT`] is -/// two (the module docs). Measured no slower up to it: on ANV, Mesa 26.2.4, on the UHD 770 one -/// region of 16,381 bytes (a prime) took 0.016-0.036 ms of the recording CPU, as 4,093 and 4,095 -/// bytes did. -const SPLIT_ABOVE: u64 = 16 * 1024; - -/// What the longer of a region's two parts is a whole multiple of (the module docs): 4 KiB, whose -/// multiples ANV recorded as quickly as 8,294,400 bytes (8,302,592 and 16,764,928 bytes, 4 KiB -/// times a prime, in 0.020-0.077 ms), and under which the rest's time stays short. -const SPLIT_UNIT: u64 = 4096; - -/// `region` as its two parts, where it is split (the module docs). -fn split(region: &vk::BufferCopy) -> Option<[vk::BufferCopy; 2]> { - let rest = region.size % SPLIT_UNIT; - if region.size <= SPLIT_ABOVE || rest == 0 { - return None; - } - let head = region.size - rest; - Some([ - vk::BufferCopy { - size: head, - ..*region - }, - vk::BufferCopy { - src_offset: region.src_offset + head, - dst_offset: region.dst_offset + head, - size: rest, - }, - ]) -} - -/// A device's functions as the runtime records commands with them: the `ash::Device`, the reads -/// a global memory barrier recorded into a command buffer of the device's queue family for -/// encoders names in place of `MEMORY_READ`, the push command and the naming of an object, and -/// the places that recorded its copy commands, and the device's pending audit where it is on (the -/// module docs). -#[derive(Clone)] -pub(crate) struct Vk { - device: ash::Device, - reads: MemoryReads, - push_descriptor: Option, - object_name: Option, - copies: Arc, - audit: Option>, -} - -impl Vk { - /// `device`'s functions, whose global memory barriers name `reads`, with `push_descriptor`, - /// its push command where it has one, and `object_name`, its naming of an object where its - /// instance reports messages, whose copy commands count their places in `copies`, auditing - /// with `audit` where given: for the work the runtime records before the device's functions - /// are made (`prime.rs`), with none. - pub(super) fn new( - device: ash::Device, - reads: MemoryReads, - push_descriptor: Option, - object_name: Option, - copies: Arc, - audit: Option>, - ) -> Vk { - Vk { - device, - reads, - push_descriptor, - object_name, - copies, - audit, - } - } - - /// The device's pending audit, where it is on (`pending_audit.rs`). - pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { - self.audit.as_deref() - } - - /// `vkBeginCommandBuffer`, the command buffer checked first by the device's pending audit - /// where it is on (the module docs). - /// - /// # Safety - /// - /// As `ash::Device::begin_command_buffer`'s. - pub(crate) unsafe fn begin_command_buffer( - &self, - command_buffer: vk::CommandBuffer, - begin_info: &vk::CommandBufferBeginInfo<'_>, - ) -> ash::prelude::VkResult<()> { - if let Some(audit) = &self.audit { - audit.begins(&self.device, command_buffer, begin_info.flags); - } - // SAFETY: the caller's contract. - unsafe { (self.device).begin_command_buffer(command_buffer, begin_info) } - } - - /// `vkCmdExecuteCommands`, noted by the device's pending audit where it is on (the module - /// docs). - /// - /// # Safety - /// - /// As `ash::Device::cmd_execute_commands`'s. - pub(crate) unsafe fn cmd_execute_commands( - &self, - primary_command_buffer: vk::CommandBuffer, - secondary_command_buffers: &[vk::CommandBuffer], - ) { - if let Some(audit) = &self.audit { - audit.executes(primary_command_buffer, secondary_command_buffers); - } - // SAFETY: the caller's contract. - unsafe { - (self.device).cmd_execute_commands(primary_command_buffer, secondary_command_buffers); - } - } - - /// The reads a global memory barrier's destination names. - pub(crate) fn reads(&self) -> MemoryReads { - self.reads - } - - /// `vkCmdPushDescriptorSet`, where the device has it: what a dispatch and a tile dispatch - /// that push their set 0 record it with (`binding::push_set`). - pub(crate) fn push_descriptor(&self) -> Option { - self.push_descriptor - } - - /// `vkSetDebugUtilsObjectNameEXT`, where the device's instance reports messages: what names - /// every pipeline for the layers' messages (`DeviceShared::name_pipeline`). - pub(crate) fn object_name(&self) -> Option { - self.object_name - } - - /// The places that recorded its copy commands so far (`WorkCounts::copy_sites`). - pub(crate) fn copy_sites(&self) -> [CopySite; COPY_SITES] { - self.copies.read() - } - - /// The `vkCmdCopyBuffer` regions it split so far (`WorkCounts::copy_regions_split`). - pub(crate) fn copy_regions_split(&self) -> u64 { - self.copies.regions_split() - } - - /// `vkCmdCopyBuffer`, counted at the place in the runtime that calls it ([`CopySites`]), its - /// long regions split (the module docs). - /// - /// # Safety - /// - /// As `ash::Device::cmd_copy_buffer`'s. - #[track_caller] - pub(crate) unsafe fn cmd_copy_buffer( - &self, - command_buffer: vk::CommandBuffer, - src: vk::Buffer, - dst: vk::Buffer, - regions: &[vk::BufferCopy], - ) { - (self.copies).count("vkCmdCopyBuffer", Location::caller(), regions.len()); - let splits = regions - .iter() - .filter(|region| split(region).is_some()) - .count(); - if splits > 0 { - self.copies.split(splits); - } - // One region split needs no list of its own. - let one = match (splits, regions) { - (1, [region]) => split(region), - _ => None, - }; - // SAFETY: the caller's contract; a region's two parts are its bytes, in the same buffers. - unsafe { - match (splits, one) { - (0, _) => (self.device).cmd_copy_buffer(command_buffer, src, dst, regions), - (_, Some(parts)) => (self.device).cmd_copy_buffer(command_buffer, src, dst, &parts), - (_, None) => { - let mut parts = Vec::with_capacity(regions.len() + splits); - for region in regions { - match split(region) { - Some(two) => parts.extend(two), - None => parts.push(*region), - } - } - (self.device).cmd_copy_buffer(command_buffer, src, dst, &parts); - } - } - } - } - - /// `vkCmdCopyBufferToImage`, counted at the place in the runtime that calls it - /// ([`CopySites`]). - /// - /// # Safety - /// - /// As `ash::Device::cmd_copy_buffer_to_image`'s. - #[track_caller] - pub(crate) unsafe fn cmd_copy_buffer_to_image( - &self, - command_buffer: vk::CommandBuffer, - src: vk::Buffer, - dst: vk::Image, - layout: vk::ImageLayout, - regions: &[vk::BufferImageCopy], - ) { - (self.copies).count("vkCmdCopyBufferToImage", Location::caller(), regions.len()); - // SAFETY: the caller's contract. - unsafe { - (self.device).cmd_copy_buffer_to_image(command_buffer, src, dst, layout, regions); - } - } - - /// `vkCmdCopyImageToBuffer`, counted at the place in the runtime that calls it - /// ([`CopySites`]). - /// - /// # Safety - /// - /// As `ash::Device::cmd_copy_image_to_buffer`'s. - #[track_caller] - pub(crate) unsafe fn cmd_copy_image_to_buffer( - &self, - command_buffer: vk::CommandBuffer, - src: vk::Image, - layout: vk::ImageLayout, - dst: vk::Buffer, - regions: &[vk::BufferImageCopy], - ) { - (self.copies).count("vkCmdCopyImageToBuffer", Location::caller(), regions.len()); - // SAFETY: the caller's contract. - unsafe { - (self.device).cmd_copy_image_to_buffer(command_buffer, src, layout, dst, regions); - } - } - - /// `vkCmdCopyImage`, counted at the place in the runtime that calls it ([`CopySites`]). - /// - /// # Safety - /// - /// As `ash::Device::cmd_copy_image`'s. - #[track_caller] - pub(crate) unsafe fn cmd_copy_image( - &self, - command_buffer: vk::CommandBuffer, - src: vk::Image, - src_layout: vk::ImageLayout, - dst: vk::Image, - dst_layout: vk::ImageLayout, - regions: &[vk::ImageCopy], - ) { - (self.copies).count("vkCmdCopyImage", Location::caller(), regions.len()); - // SAFETY: the caller's contract. - unsafe { - (self.device).cmd_copy_image(command_buffer, src, src_layout, dst, dst_layout, regions); - } - } -} - -impl Deref for Vk { - type Target = ash::Device; - - fn deref(&self) -> &ash::Device { - &self.device - } -} - -/// A device's functions: all of them, and the exit guard's table alone. -#[derive(Clone)] -pub(crate) struct Functions { - all: Vk, - sectioned: Vk, - /// The address of each device-level entry point of the table, in its order (0 for an - /// instance-level one, or one the device has not): the topmost layer's where layers run, - /// else the driver's. - entry_points: Vec, -} - -impl Functions { - /// The functions of `all`'s device, made from `instance`, whose global memory barriers name - /// `reads`, with `push_descriptor`, its push command where it has one, and `object_name`, its - /// naming of an object where its instance reports messages, whose commands go through - /// `recording`, its slot where it has one (`recorder`), auditing with `audit` where given - /// (`pending_audit.rs`). - /// - /// # Safety - /// - /// `all` is a live device of `instance`, routed (`compiles::route`, and through `recording` - /// where it is set, `recorder::route`), and the loader serves `vkGetDeviceProcAddr` for it - /// (its loader word is in place). - pub(super) unsafe fn new( - instance: &ash::Instance, - all: ash::Device, - reads: MemoryReads, - push_descriptor: Option, - object_name: Option, - recording: Option<&Slot>, - audit: Option>, - ) -> Functions { - let handle = all.handle(); - let get = instance.fp_v1_0().get_device_proc_addr; - // SAFETY: the caller's contract; a missing function is null, as ash loads it. - let address = |name: &CStr| unsafe { - std::mem::transmute::(get(handle, name.as_ptr())) - }; - // Only the device-level functions ash asks for are looked up: asking the device for an - // instance-level one (the table's instance and messenger releases) is an error the - // validation layer reports. - let mut entry_points = vec![0; Call::ALL.len()]; - let load = |name: &CStr| -> *const c_void { - match Call::ALL.iter().position(|call| call.name() == name) { - Some(at) => { - let pointer = address(name); - entry_points[at] = pointer as usize as u64; - // The pipeline makings come through `compiles.rs`, and the commands through - // the device's slot, as `all`'s do. - super::compiles::entry(name) - .or_else(|| recording.and_then(|slot| slot.entry(name))) - .unwrap_or(pointer) - } - None => std::ptr::null(), - } - }; - // SAFETY: as above: each pointer is the device's function of that name, or null. - let sectioned = unsafe { ash::Device::load_with(load, handle) }; - // The naming is no `ash::Device` function: its entry point, where the device has it. - if let (Some(at), Some(name)) = ( - Call::ALL - .iter() - .position(|&call| call == Call::SetDebugUtilsObjectName), - object_name, - ) { - entry_points[at] = name as usize as u64; - } - // Both count their copies' places together. - let copies = Arc::new(CopySites::default()); - Functions { - all: Vk::new( - all, - reads, - push_descriptor, - object_name, - Arc::clone(&copies), - audit.clone(), - ), - sectioned: Vk::new( - sectioned, - reads, - push_descriptor, - object_name, - copies, - audit, - ), - entry_points, - } - } - - /// The address of each entry point of the exit guard's table, in its order. - pub(super) fn entry_points(&self) -> &[u64] { - &self.entry_points - } - - /// The device's pending audit, where it is on, which both tables hold (the module docs). - pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { - self.all.pending_audit() - } - - /// The device's functions for this thread now (see the module). - pub(crate) fn get(&self) -> &Vk { - exit_guard::check(); - if cfg!(debug_assertions) && exit_guard::in_section() { - &self.sectioned - } else { - &self.all - } - } -} diff --git a/crates/metal2vulkan-runtime/src/device/handles.rs b/crates/metal2vulkan-runtime/src/device/handles.rs deleted file mode 100644 index 59769ca73..000000000 --- a/crates/metal2vulkan-runtime/src/device/handles.rs +++ /dev/null @@ -1,278 +0,0 @@ -//! The raw Vulkan objects of a runtime device (`Device::raw`). - -use super::Device; -use ash::vk; -use std::ffi::CStr; - -/// No Metal counterpart: the Vulkan objects behind a runtime device, with the function tables the -/// runtime loaded for them: what the caller needs to read the device, or to make its own objects -/// on it (a surface's swapchain, for example). The runtime keeps owning all of them; the -/// references live as long as the borrow of the device. A root handle's are of the `VkDevice` -/// that served at the [`Device::raw`] call: after a recovery from its loss, that `VkDevice` stays -/// alive until a later `raw` call of a root handle, so what the caller made with it is destroyed -/// first (`Device::raw`). -#[non_exhaustive] -#[derive(Clone, Copy)] -pub struct DeviceHandles<'a> { - /// The loader entry the instance was made through: its `vkGetInstanceProcAddr`. - pub entry: &'a ash::Entry, - /// The instance, with its instance-level commands. - pub instance: &'a ash::Instance, - /// The `VkApplicationInfo::apiVersion` the instance was created with. - pub instance_api_version: metal2vulkan::vk::ApiVersion, - /// The physical device the device was made on. - pub physical_device: vk::PhysicalDevice, - /// The device, with its device-level commands as the runtime loaded them. - pub device: &'a ash::Device, - /// The device's primary queue family: the first of [`DeviceHandles::queue_families`], and, - /// on a device of one family, the family every `VkQueue` of the device's queues belongs to. - pub queue_family: u32, - /// Every queue family the device's queues belong to, the primary first, each once, the - /// families of its [`reserved_queues`](Self::reserved_queues) among them. A device - /// the runtime creates where every queue family is equivalent (the same flags, queue count, - /// timestamp bits and transfer granularity, as MoltenVK's) takes queues of all of them, so - /// its queues run side by side; its buffers and images are then concurrent among all these - /// families, and a buffer or image the caller wraps must be too. Where it also reserved a - /// queue of another family for its staging copies (a family of transfers alone, a copy - /// engine; or, where no memory the host caches holds a texture's image, one of compute work, - /// as on an RX 7900 XTX), its own buffers are concurrent among these families and that one. An adopted device has its one - /// family. [`CommandQueue::with_vk_queue`](super::super::CommandQueue::with_vk_queue) - /// names the family of each queue's own `VkQueue`. - pub queue_families: &'a [u32], - /// The extra queues the device made for the caller - /// ([`DeviceOptions::extra_queues`](super::DeviceOptions::extra_queues)), in the options' - /// order, leaving out each the device had no queue for: none for an adopted device. The - /// runtime never submits to them. - pub extra_queues: &'a [ExtraQueue], - /// The queues of its own families the device reserved for the caller - /// ([`DeviceOptions::reserved_queues`](super::DeviceOptions::reserved_queues)), as many as - /// it had to spare, at most as many as asked: none for an adopted device. The runtime never - /// submits to them. - pub reserved_queues: &'a [ReservedQueue], -} - -/// No Metal counterpart: one of the queues of its own queue families a created device reserved -/// for the caller out of the round robin its command queues share -/// ([`DeviceOptions::reserved_queues`](super::DeviceOptions::reserved_queues)), which -/// [`DeviceHandles::reserved_queues`] returns. Metal has no queue a program owns apart from its -/// command queues: a `CommandQueue` here may share its `VkQueue` with another command queue -/// (`WorkCounts::queues_sharing_a_vk_queue`), and the runtime submits to that `VkQueue` itself, -/// while no runtime work ever goes to this one. No command queue takes it, presenting or not, -/// and no internal or staging copy goes there: the caller is its only submitter, and -/// synchronizes its submissions to it externally, as Vulkan requires. Its family is one of -/// [`DeviceHandles::queue_families`], which the device's buffers and images are shared among, so -/// a submission to it may use them with no ownership transfer, under their handles' contracts -/// ([`Buffer::vk_buffer`](crate::Buffer::vk_buffer), -/// [`Texture::vk_image`](crate::Texture::vk_image)): while the object lives, ordered against the -/// runtime's work on it through semaphores or completion, and an image the runtime made left in -/// `VK_IMAGE_LAYOUT_GENERAL`. It lives as long as the device. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ReservedQueue { - /// The queue's family, one of [`DeviceHandles::queue_families`]. - pub family: u32, - /// The queue. - pub queue: vk::Queue, -} - -/// No Metal counterpart: one of the queues a created device made for the caller beside its own -/// ([`DeviceOptions::extra_queues`](super::DeviceOptions::extra_queues)), which -/// [`DeviceHandles::extra_queues`] returns. The runtime never submits to it: the caller is its -/// only submitter, and synchronizes its submissions to it externally, as Vulkan requires. It -/// lives as long as the device. Where its family is not one of -/// [`DeviceHandles::queue_families`], the device's own images are not shared with it, nor its -/// buffers unless its family is that of the queue the device reserved for its staging copies: -/// a submission to it uses only the caller's objects made to be shared with its family. -#[non_exhaustive] -#[derive(Clone, Copy, PartialEq, Eq)] -pub struct ExtraQueue { - /// The flags the options asked for, which the family's contain. - pub flags: vk::QueueFlags, - /// The queue's family. - pub family: u32, - /// The queue. - pub queue: vk::Queue, -} - -impl std::fmt::Debug for ExtraQueue { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ExtraQueue") - .field("flags", &QueueFlagsText(self.flags)) - .field("family", &self.family) - .field("queue", &self.queue) - .finish() - } -} - -/// `VkQueueFlags` as text: its bits' names joined by `|`, any bit without a name in hex (`ash`'s -/// flags print only with its `debug` feature, which the runtime leaves off). -pub(crate) struct QueueFlagsText(pub(crate) vk::QueueFlags); - -impl std::fmt::Debug for QueueFlagsText { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - const NAMES: [(vk::QueueFlags, &str); 8] = [ - (vk::QueueFlags::GRAPHICS, "GRAPHICS"), - (vk::QueueFlags::COMPUTE, "COMPUTE"), - (vk::QueueFlags::TRANSFER, "TRANSFER"), - (vk::QueueFlags::SPARSE_BINDING, "SPARSE_BINDING"), - (vk::QueueFlags::PROTECTED, "PROTECTED"), - (vk::QueueFlags::VIDEO_DECODE_KHR, "VIDEO_DECODE_KHR"), - (vk::QueueFlags::VIDEO_ENCODE_KHR, "VIDEO_ENCODE_KHR"), - (vk::QueueFlags::OPTICAL_FLOW_NV, "OPTICAL_FLOW_NV"), - ]; - let mut parts: Vec = (NAMES.iter()) - .filter(|(bit, _)| self.0.contains(*bit)) - .map(|(_, name)| (*name).to_owned()) - .collect(); - let named = NAMES - .iter() - .fold(vk::QueueFlags::empty(), |all, (bit, _)| all | *bit); - let rest = self.0.as_raw() & !named.as_raw(); - if rest != 0 || parts.is_empty() { - parts.push(format!("{rest:#x}")); - } - f.write_str(&parts.join(" | ")) - } -} - -impl std::fmt::Debug for DeviceHandles<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("DeviceHandles") - .field("instance", &self.instance.handle()) - .field("instance_api_version", &self.instance_api_version) - .field("physical_device", &self.physical_device) - .field("device", &self.device.handle()) - .field("queue_family", &self.queue_family) - .field("queue_families", &self.queue_families) - .field("extra_queues", &self.extra_queues) - .field("reserved_queues", &self.reserved_queues) - .finish_non_exhaustive() - } -} - -impl Device { - /// The device's raw Vulkan objects: the consumer's own for an adopted device, the runtime's - /// for one it created. - /// - /// # Safety - /// - /// The objects stay their owner's: the caller destroys none of them, uses them only while - /// the device lives, and submits to the queues the runtime submits to only through - /// [`CommandQueue::with_vk_queue`](super::super::CommandQueue::with_vk_queue) (the extra and - /// reserved queues are the caller's alone). On MoltenVK, a - /// device with a debug-utils messenger may find its first word overwritten: the calls the - /// Vulkan loader serves for the device itself (`vkAllocateCommandBuffers`, `vkGetDeviceQueue`, - /// `vkGetDeviceProcAddr`, `vkDestroyDevice`, `vkCreateSwapchainKHR`: - /// [`Device::with_loader_word`] lists them) then fault, even through - /// [`DeviceHandles::device`], so the caller loads its commands through - /// [`Device::device_proc_addr`] and makes those calls inside [`Device::with_loader_word`]. - /// - /// A root handle's (the device the program made, and its clones) are of the `VkDevice` that - /// serves at the call. Once a recovery made a new one (`Degradation::DeviceRecovered`, - /// [`Device::recover_for_test`]), they stay valid until a later call of a root handle's - /// returns the new one's; after that the caller uses them no more. The lost `VkDevice` stays - /// alive until then, though the runtime's own objects made on it went, so the caller - /// destroys what it made with these handles (a swapchain, an import) before that call. A - /// queue lent through [`CommandQueue::with_vk_queue`](super::super::CommandQueue::with_vk_queue) - /// comes with the `VkDevice` it belongs to: the new one from the recovery on. - pub unsafe fn raw(&self) -> DeviceHandles<'_> { - let shared = match &self.0 { - super::Pin::Generation(shared) => &**shared, - super::Pin::Root(root) => root.line.lend(&self.current()), - }; - let instance = &shared.instance; - DeviceHandles { - entry: &instance.entry, - instance: &instance.raw, - instance_api_version: instance.api_version, - physical_device: shared.physical, - device: shared.vk(), - queue_family: shared.queue_family, - queue_families: &shared.queue_families, - extra_queues: &shared.extra_queues, - reserved_queues: &shared.reserved_queues, - } - } -} - -impl Device { - /// No Metal counterpart: `vkGetDeviceProcAddr` of the device command `name`, with the - /// device's loader word put back first ([`Device::with_loader_word`]). The caller's own - /// command tables (`VK_KHR_swapchain`'s, `VK_EXT_metal_objects`', or any other extension the - /// options enabled) load here at any time, one name at a time, as ash's table loaders ask: - /// `ash::khr::swapchain::DeviceFn::load(|name| device.device_proc_addr(name)...)`. Through - /// [`DeviceHandles::instance`] the same load faults on MoltenVK once a message named the - /// device. `None` is Vulkan's null: a command of an extension the device did not enable, or - /// no device command of that name. - /// - /// Which commands a loaded pointer reaches is the loader's: most are the driver's own (on - /// MoltenVK `vkAcquireNextImageKHR`, `vkQueuePresentKHR`, `vkGetSwapchainImagesKHR`, - /// `vkDestroySwapchainKHR`, `vkExportMetalObjectsEXT`), which read no word, but some are the - /// loader's own and read it at every call; the caller makes those inside - /// [`Device::with_loader_word`], which lists them. - pub fn device_proc_addr(&self, name: &CStr) -> vk::PFN_vkVoidFunction { - self.current().device_proc_addr_now(name) - } - - /// [`Device::device_proc_addr`] on the generation that serves (`device/line.rs`). - pub(crate) fn device_proc_addr_now(&self, name: &CStr) -> vk::PFN_vkVoidFunction { - let shared = self.shared(); - let handle = shared.vk().handle(); - self.with_loader_word_now(|| { - // SAFETY: the device is live while `self` is, made from this instance, and its first - // word is the loader's again; `name` is NUL-terminated. - unsafe { - shared - .instance - .raw - .get_device_proc_addr(handle, name.as_ptr()) - } - }) - } - - /// No Metal counterpart: `call`'s answer, with the device's first word put back first, as the - /// Vulkan loader wrote it. MoltenVK 1.4.1 writes `ICD_LOADER_MAGIC` over it whenever it names - /// the device in a message to a debug-utils messenger. A device the runtime creates has one - /// wherever the loader lists `VK_EXT_debug_utils` (the relay's, `device/relay.rs`), an adopted - /// one where its consumer registered one. The loader's own entry points for the device read the - /// word as their dispatch table: - /// - /// - those `vkGetDeviceProcAddr` hands out for the device itself, which fault on the magic: - /// `vkGetDeviceProcAddr`, `vkGetDeviceQueue`, `vkGetDeviceQueue2`, - /// `vkAllocateCommandBuffers`, `vkDestroyDevice`; - /// - its terminators, which find the device by comparing first words, not handles: - /// `vkCreateSwapchainKHR`, `vkCreateSharedSwapchainsKHR`, - /// `vkGetDeviceGroupSurfacePresentModesKHR`, `vkGetDeviceGroupSurfacePresentModes2EXT`, and - /// `VK_EXT_debug_utils`' and `VK_EXT_debug_marker`'s object naming and tagging. A device - /// whose word holds the magic matches the first device in the loader's lists whose word - /// holds it too, and the call takes that device's driver entry and unwraps the surface for - /// that device's instance (loader 1.4.357: `loader_get_icd_and_device`, - /// `wsi_unwrap_icd_surface`): right with one such device in the process, wrong with two; - /// - with a layer between the loader and the driver (the validation layer), every command: - /// the layer finds its state by the word. - /// - /// The caller makes such calls inside `call`. The loader's entry points for a queue or a - /// command buffer read that object's own word: a queue's is put back by - /// [`CommandQueue::with_vk_queue`](super::super::CommandQueue::with_vk_queue). `call` runs - /// under the word's lock, which the runtime's own calls the loader serves take too, and its - /// submission checks' thread across its submissions, and across each whole step of theirs on a - /// device whose word was found overwritten, the driver's completion of their submissions - /// included (on MoltenVK, with each activity logged at once, each names the device): none of - /// them writes the word between this restore and the loader's read, and `call` may wait for - /// one such step. So `call` makes the loader's calls alone, and uses none of the runtime's - /// queues: a [`CommandQueue::with_vk_queue`](super::super::CommandQueue::with_vk_queue) - /// inside it may wait for the checks' thread, which waits for `call`. A driver thread that - /// writes the word on its own between the restore and the loader's read for work other than - /// the checks' (a message about the device as one of the program's command buffers completes, - /// from MoltenVK's completion handlers) is not guarded against. On every other driver the - /// word never changes, and the restore writes nothing. - pub fn with_loader_word(&self, call: impl FnOnce() -> R) -> R { - self.current().with_loader_word_now(call) - } - - /// [`Device::with_loader_word`] on the generation that serves (`device/line.rs`). - pub(crate) fn with_loader_word_now(&self, call: impl FnOnce() -> R) -> R { - // SAFETY: the device is live while `self` is. - unsafe { self.shared().loader_word.restored(call) } - } -} diff --git a/crates/metal2vulkan-runtime/src/device/holds.rs b/crates/metal2vulkan-runtime/src/device/holds.rs deleted file mode 100644 index 5c2322a48..000000000 --- a/crates/metal2vulkan-runtime/src/device/holds.rs +++ /dev/null @@ -1,324 +0,0 @@ -//! The runtime's own holds of a device: its check of textures in place (`in_place_check.rs`), its -//! check of what linear images cost (`tiling_check.rs`) and its warm pass (`warm/pass.rs`), each -//! on a thread of its own, and a pool piece's making of a -//! render execution's draw replay kernels ahead (`owned_kernel.rs`), which hold the device while -//! they make objects on it and let it go between their steps; and a release it posts to a handler -//! thread for the program, a host import's that a keep-alive alone waits for (`buffer.rs`). -//! -//! - **Two counts.** Every handle of the device is counted here, as the program's or as a -//! holder's. A handle a holder takes ([`WeakDevice::hold`]) is a holder's, and so is each handle -//! cloned from one (the device of every object the holder makes), and each handle of its own a -//! posted release holds ([`Device::held_for_release`]); every other is the program's (the -//! device's own, its objects', and a runtime thread's upgrade of a weak handle). Measured: with -//! the program's handles in such a release, a test's drop of its device right after its no-copy -//! buffers with keep-alives returned with the `VkDevice` live in 31 of 32 runs on lavapipe, 12 -//! of 12 on the Radeon 780M and 80 of 80 on the RTX 3090: the last handle went on the handler -//! thread, and the process's exit then left its teardown (`exit_guard.rs`), which on NVIDIA's -//! driver can fault in the driver's own exit handler (docs/FAST-PATHS.md, known gaps). -//! - **The program's last drop tears the device down.** The drop that leaves the program no -//! handle stops the holds, and on a thread of the program's waits until the holders' handles -//! went, so the device goes with it, on that thread, before it returns. A consumer that adopted -//! the `VkDevice` destroys it once the last drop returned, and Vulkan requires every object -//! made from it destroyed first. On one of the runtime's own threads (a completed handler's -//! release of the program's last command buffer) it waits for nothing: those threads serve the -//! work the holds may wait for, and the program's work there ends where it ends already. -//! - **The wait is a step.** A holder reads the stop between its steps -//! ([`Device::holds_go_on`]): the check between its rounds, the warm pass between its records. -//! So the wait is at most the check's round in progress (and its release of its buffer), or the -//! record the pass is making; a posted release is one step, which a handler thread runs at -//! once: the import's free and the keep-alive's drop. It happens only at teardown. -//! - **Exact.** A holder's take and a holder's handle's clone and drop count under the registry's -//! lock; a holder's handle is counted gone only once its share of the device went ([`Share`]), -//! so the program's last drop, waiting for that, holds the device's last share. A program -//! handle's drop counts without the lock, and only the last takes it, to stop the holds and wait: -//! a holder that took its hold before that drop's lock is waited for, as one that took it before -//! the drop. So the drops of the program's handles, which its objects, command buffers and -//! encoders make at every turn on every thread, share no lock. A program handle is counted gone -//! before its share goes: a program handle another thread drops at once may go last, inside that -//! drop. A program handle's clone counts without the lock (it clones a handle that is counted), -//! and so does a runtime thread's upgrade, which keeps the device as before: one made while the -//! last drop waits goes on that thread. -//! - **A stopped device is gone.** Once stopped, no holder takes the device, and a device made on -//! the same physical device makes a new one (`create.rs`) rather than revive it. - -use super::line::Line; -use super::{lock, Device, DeviceShared, Pin, WeakDevice}; -use crate::exit_guard; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex}; - -/// The runtime's holders of a device, each of whose steps reads the stop. -#[derive(Clone, Copy, Debug)] -pub(crate) enum Holder { - /// The check of textures in place, between its rounds. - InPlaceCheck, - /// The warm pass, between its records. - WarmPass, - /// The pool's making of a render execution's draw replay kernels ahead - /// (`Device::begin_draw_replay_kernels`), between its kernels. - DrawReplayKernels, - /// The pool's making of the rate-map routes' kernel ahead - /// (`Device::begin_route_counts_kernel`), before it. - RouteCountsKernel, - /// The check of what linear images cost against optimal ones, between its rounds - /// (`tiling_check.rs`). - TilingCheck, - /// The check of what a `constant` window's views cost, between its rounds - /// (`view_check.rs`). - ViewCheck, -} - -/// The holders: one test hold each ([`Holds::held`]). -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -const HOLDERS: usize = Holder::ViewCheck as usize + 1; - -/// A device's registry of its handles and the runtime's own holds (the module docs). -#[derive(Default)] -pub(crate) struct Holds { - /// The program's handles. - program: AtomicUsize, - /// The holders' handles, and whether the program's last drop stopped the holds. - state: Mutex, - /// Signalled as the last holder's handle goes. - released: Condvar, - /// Whether the holds were stopped: read between a holder's steps without the lock. - stopping: AtomicBool, - /// How long the program's last drop waited for the holds, in nanoseconds: 0 where it waited - /// for none. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - waited: std::sync::atomic::AtomicU64, - /// The crate's device tests' holds of each holder between its steps - /// (`tests/teardown_threads.rs`). - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - held: [crate::freed_memory::held::Held; HOLDERS], -} - -/// The registry's count of the holders' handles, and its stop. -#[derive(Default)] -struct State { - /// The holders' handles: taken by a holder or cloned from one, their share of the device not - /// yet gone. - holders: usize, - /// The program's last drop stopped the holds. - stopped: bool, -} - -/// A handle's place in the registry (the module docs): the registry where it is a holder's, -/// `None` where it is the program's (whose drop reaches the registry through the device). -pub(super) struct Share(Option>); - -impl Holds { - /// Whether the program's last drop stopped the holds. - pub(crate) fn stopping(&self) -> bool { - self.stopping.load(Ordering::SeqCst) - } - - /// How long the program's last drop waited for the holds; `None` where it waited for none. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn waited(&self) -> Option { - match self.waited.load(Ordering::Acquire) { - 0 => None, - nanos => Some(std::time::Duration::from_nanos(nanos)), - } - } - - /// The test hold of `holder`. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn held(&self, holder: Holder) -> &crate::freed_memory::held::Held { - &self.held[holder as usize] - } - - /// Run `run` with the registry's lock held, for the crate's device tests. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn locked(&self, run: impl FnOnce() -> R) -> R { - let _state = lock(&self.state); - run() - } - - /// Let `holder`'s test hold go once the holds were stopped, or once it was let go already. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn release_once_stopping(&self, holder: Holder) { - self.held(holder).release_once(&self.stopping); - } -} - -/// The program's generation handle of `shared`, counted (`line.rs`). -#[inline] -pub(super) fn program(shared: Arc) -> Device { - shared.holds.program.fetch_add(1, Ordering::SeqCst); - Device(Pin::Generation(shared), Share(None)) -} - -/// The program's root handle of `line`, counted (`line.rs`): a new device's first handle, and -/// each clone of a root. -#[inline] -pub(super) fn root(line: Arc) -> Device { - line.holds.program.fetch_add(1, Ordering::SeqCst); - Device(Pin::Root(super::RootCell::new(line)), Share(None)) -} - -/// A root handle of `line` for the program, a live device's again (`create.rs`): `None` where its -/// holds were stopped, so that it goes, and a device made on the same physical device is a new -/// one. -pub(super) fn revive_root(line: Arc) -> Option { - let state = lock(&line.holds.state); - if state.stopped { - return None; - } - drop(state); - Some(root(line)) -} - -/// The registry a new device's handles share. -pub(super) fn holds() -> Arc { - Arc::new(Holds::default()) -} - -/// `weak`'s device for the program (a runtime thread's upgrade among them), counted, while it -/// lives. -pub(super) fn upgrade(weak: &WeakDevice) -> Option { - weak.0.upgrade().map(program) -} - -impl WeakDevice { - /// The device for a step of one of the runtime's holders, counted as the holder's (the module - /// docs): `None` where it went, or the program's last drop stopped the holds. - pub(crate) fn hold(&self) -> Option { - let mut state = lock(&self.1.state); - if state.stopped { - return None; - } - let shared = self.0.upgrade()?; - state.holders += 1; - Some(Device( - Pin::Generation(shared), - Share(Some(Arc::clone(&self.1))), - )) - } -} - -impl Device { - /// Whether `holder`, which holds the device through [`WeakDevice::hold`], goes on with its - /// next step: `false` once the program's last drop stopped the holds. - pub(crate) fn holds_go_on(&self, holder: Holder) -> bool { - let shared = self.shared(); - let holds = &shared.holds; - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - holds.held(holder).pass(); - let _ = holder; - // A lost generation's holders stop too: the generation serves nothing more (`line.rs`). - !holds.stopping() && !shared.lost() - } - - /// A handle of the device for a release the runtime posts to another thread for the program - /// (a host import's, where a keep-alive alone waits for its free, `buffer.rs`), held as a - /// holder's: the program's last drop waits for it as for the holders' (the module docs), so - /// that release runs before the device goes, on the thread of that drop. A holder's handle's - /// clone where this one is a holder's; the program's where the holds were stopped (a runtime - /// thread's upgrade past the last drop, whose device goes where it goes already). - pub(crate) fn held_for_release(&self) -> Device { - match &(self.1).0 { - Some(holds) => holder_clone(self, holds), - None => self.downgrade().hold().unwrap_or_else(|| self.clone()), - } - } -} - -impl Clone for Device { - // Inlined where it is the program's, as every handle but the holders' is: its count alone. - #[inline] - fn clone(&self) -> Device { - match (&self.0, &(self.1).0) { - (_, Some(holds)) => holder_clone(self, holds), - (Pin::Generation(shared), None) => program(Arc::clone(shared)), - (Pin::Root(cell), None) => { - cell.line.holds.program.fetch_add(1, Ordering::SeqCst); - Device(Pin::Root(Arc::clone(cell)), Share(None)) - } - } - } -} - -/// A clone of `device`, a holder's handle of the holds `holds` (the module docs). -#[cold] -#[inline(never)] -fn holder_clone(device: &Device, holds: &Arc) -> Device { - let mut state = lock(&holds.state); - state.holders += 1; - Device( - Pin::Generation(Arc::clone(device.shared_arc())), - Share(Some(Arc::clone(holds))), - ) -} - -impl Drop for Device { - // A program handle's drop: the program's last stops the holds and waits for them - // (`last_drop`). A holder's handle is counted gone by its `Share`, once the device's share went - // before it. Inlined: every drop but the program's last counts alone. - #[inline] - fn drop(&mut self) { - if (self.1).0.is_some() { - return; - } - // The line's holds, which each generation holds too: a generation handle reads them at - // its own generation, as it reads the rest. - let holds = match &self.0 { - Pin::Generation(shared) => &shared.holds, - Pin::Root(root) => &root.line.holds, - }; - if holds.program.fetch_sub(1, Ordering::SeqCst) > 1 { - return; - } - last_drop(holds); - // The line lets go of the generation it serves, which goes once nothing else holds it: - // there, or as this handle's own share goes (`line.rs`). - self.line().release(); - } -} - -/// The program's last drop of its handles of the device whose holds are `holds`: it stops the -/// holds and, on a thread of the program's, waits for the holders' handles to go (the module docs). -#[cold] -#[inline(never)] -fn last_drop(holds: &Holds) { - let mut state = lock(&holds.state); - state.stopped = true; - holds.stopping.store(true, Ordering::SeqCst); - if state.holders == 0 || exit_guard::on_runtime_thread() { - return; - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let waiting = std::time::Instant::now(); - while state.holders > 0 { - state = (holds.released.wait(state)).unwrap_or_else(std::sync::PoisonError::into_inner); - } - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - { - let nanos = u64::try_from(waiting.elapsed().as_nanos()).unwrap_or(u64::MAX); - holds.waited.store(nanos.max(1), Ordering::Release); - } - // The device's share goes as the drop returns, the last: the teardown runs there. -} - -impl Drop for Share { - // A holder's handle is counted gone here, after the device's share it held went (fields go - // in their order): the program's last drop, which waits for this, then holds the last share. - // Inlined: a program handle's has nothing to count. - #[inline] - fn drop(&mut self) { - if let Some(holds) = &self.0 { - holder_gone(holds); - } - } -} - -/// A holder's handle of the holds `holds` gone ([`Share`]'s drop). -#[cold] -#[inline(never)] -fn holder_gone(holds: &Holds) { - let mut state = lock(&holds.state); - state.holders -= 1; - if state.holders == 0 { - holds.released.notify_all(); - } -} diff --git a/crates/metal2vulkan-runtime/src/device/instance_requirements.rs b/crates/metal2vulkan-runtime/src/device/instance_requirements.rs deleted file mode 100644 index fe91a9e8f..000000000 --- a/crates/metal2vulkan-runtime/src/device/instance_requirements.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! The instance extensions a device extension requires. -//! -//! Enabling a device extension whose registry dependency names an instance extension is valid -//! only on an instance that enables that instance extension -//! (`VUID-vkCreateDevice-ppEnabledExtensionNames-01387`). The validation layer checks it at -//! `vkCreateDevice`; a driver need not, and makes the device or fails as it likes. So where -//! `DeviceOptions::device_extensions` lists such an extension and the instance the runtime would -//! make enables (from `DeviceOptions::instance_extensions` and its own) not every instance -//! extension it requires, the runtime refuses it typed -//! ([`Error::InstanceExtensionRequired`]) before it makes the instance. -//! -//! [`REQUIRES`] is the registry's list, transcribed from `vk.xml` at header 357 (Vulkan 1.4.357): -//! every device extension whose `depends` names an instance extension that Vulkan 1.1 did not -//! make core, with those instance extensions. The runtime's instance is at least Vulkan 1.2 -//! (`create::instance_version`), so the core ones hold; in each of the 17 the rest are plain -//! conjuncts, which the registry requires all of. A device extension's dependencies on other -//! device extensions are not checked here. - -use crate::error::{Error, InstanceExtensionRequired}; -use std::ffi::{CStr, CString}; - -/// Each device extension of the registry whose dependency names an instance extension Vulkan 1.1 -/// did not make core, with every such instance extension, in the registry's order. -const REQUIRES: [(&str, &[&str]); 17] = [ - ("VK_KHR_swapchain", &["VK_KHR_surface"]), - ("VK_KHR_display_swapchain", &["VK_KHR_display"]), - ("VK_EXT_debug_marker", &["VK_EXT_debug_report"]), - ( - "VK_NV_external_memory", - &["VK_NV_external_memory_capabilities"], - ), - ( - "VK_EXT_display_control", - &["VK_EXT_display_surface_counter"], - ), - ( - "VK_KHR_shared_presentable_image", - &["VK_KHR_get_surface_capabilities2"], - ), - ("VK_GGP_frame_token", &["VK_GGP_stream_descriptor_surface"]), - ( - "VK_EXT_present_timing", - &["VK_KHR_get_surface_capabilities2"], - ), - ( - "VK_AMD_display_native_hdr", - &["VK_KHR_get_surface_capabilities2"], - ), - ( - "VK_EXT_full_screen_exclusive", - &["VK_KHR_surface", "VK_KHR_get_surface_capabilities2"], - ), - ( - "VK_EXT_swapchain_maintenance1", - &["VK_EXT_surface_maintenance1"], - ), - ( - "VK_NV_present_barrier", - &["VK_KHR_surface", "VK_KHR_get_surface_capabilities2"], - ), - ( - "VK_NV_acquire_winrt_display", - &["VK_EXT_direct_mode_display"], - ), - ( - "VK_EXT_device_address_binding_report", - &["VK_EXT_debug_utils"], - ), - ( - "VK_KHR_present_id2", - &["VK_KHR_get_surface_capabilities2", "VK_KHR_surface"], - ), - ( - "VK_KHR_present_wait2", - &["VK_KHR_get_surface_capabilities2", "VK_KHR_surface"], - ), - ( - "VK_KHR_swapchain_maintenance1", - &["VK_KHR_surface_maintenance1"], - ), -]; - -/// Whether an instance enabling `instance_extensions` may enable every one of -/// `device_extensions` on its devices: the refusal names the first of `device_extensions`, in -/// their order, with an instance extension it requires that `instance_extensions` lacks, and the -/// first such instance extension in the registry's order. -pub(crate) fn instance_requirements_met( - device_extensions: &[CString], - instance_extensions: &[&CStr], -) -> Result<(), Error> { - let enabled = |name: &str| { - instance_extensions - .iter() - .any(|enabled| enabled.to_bytes() == name.as_bytes()) - }; - for listed in device_extensions { - let Some(&(extension, requires)) = REQUIRES - .iter() - .find(|(name, _)| listed.as_bytes() == name.as_bytes()) - else { - continue; - }; - if let Some(&missing) = requires.iter().find(|&&required| !enabled(required)) { - return Err(Error::InstanceExtensionRequired( - InstanceExtensionRequired { - extension, - instance_extension: missing, - }, - )); - } - } - Ok(()) -} diff --git a/crates/metal2vulkan-runtime/src/device/keeper.rs b/crates/metal2vulkan-runtime/src/device/keeper.rs deleted file mode 100644 index 42b0ec681..000000000 --- a/crates/metal2vulkan-runtime/src/device/keeper.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! The drivers' keeper: once the runtime has made a device through a Vulkan loader library, one -//! bare instance of that library lives for the rest of the process, so the loader keeps every -//! driver it loaded for it. -//! -//! The loader unloads a driver when the last instance using it is destroyed and loads it again -//! for the next. Not every driver survives that: NVIDIA's Linux driver takes a new piece of -//! glibc's static TLS at each load and never gives it back, so after enough device lifetimes in -//! one process the loader cannot load it and ignores it, and the runtime finds no device. Metal -//! never fails to make a device, and most applications keep their instance for the process's life -//! anyway. -//! -//! The keeper is bare: no layers, no messenger, and no extension but -//! `VK_KHR_portability_enumeration` where the device's instance enabled it, which the runtime does -//! where the loader lists it (without it, a loader that sees only a portability driver refuses the -//! instance): the keeper asks the loader nothing of its own. Nothing is made from it and it is -//! never destroyed. It is made once a device was made (`vkCreateDevice`), while that device's -//! instance is alive, and before the device is primed and registers the exit hook -//! (`exit_guard.rs`); adopted devices never make one. Its instance can still load drivers -//! (measured on a host with Intel, lavapipe and NVIDIA drivers and no Intel GPU: both Intel -//! drivers, which the loader unloaded as it made the device's instance, loaded again for the -//! keeper's). Made before the registration, what it loads comes before the load count the -//! registration keeps, so the next device made on what stays loaded is not primed again -//! (`tests::primed_devices`). - -use super::create::new_instance; -use super::{lock, InstanceShared}; -use ash::vk; -use std::sync::Mutex; - -/// One value per key, made at most once, under one lock. -pub(crate) struct Kept { - entries: Mutex>, -} - -impl Kept { - /// No value kept. - pub(crate) const fn new() -> Kept { - Kept { - entries: Mutex::new(Vec::new()), - } - } - - /// Keep the value `make` makes for `key`, unless one is kept already. `make` runs under the - /// lock, so concurrent first calls make one value; when it makes none, nothing is kept and - /// the next call tries again. Whether a value is kept for `key` afterwards. - pub(crate) fn keep(&self, key: K, make: impl FnOnce() -> Option) -> bool { - let mut entries = lock(&self.entries); - if entries.iter().any(|(kept, _)| *kept == key) { - return true; - } - match make() { - Some(value) => { - entries.push((key, value)); - true - } - None => false, - } - } - - /// How many values are kept. - #[cfg(test)] - pub(crate) fn len(&self) -> usize { - lock(&self.entries).len() - } -} - -/// A loader library and its bare instance, kept for the life of the process. -struct Keeper { - /// Keeps the loader library loaded. - _entry: ash::Entry, - /// Never destroyed: while it lives, the loader keeps its drivers. - _instance: vk::Instance, -} - -/// One keeper per loader library, keyed by the library itself: the address of its -/// `vkGetInstanceProcAddr`. The OS loads a library once however it is named (a symlink, a -/// searched name, an explicit path), and the keeper holds it loaded, so the address names one -/// library for the life of the process. -static KEEPERS: Kept = Kept::new(); - -/// Keep the drivers of `instance`'s loader library loaded for the life of the process. Called -/// once a device was made from `instance`, which the runtime created, while it is alive, before -/// that device is primed (the module docs). A keeper that cannot be made leaves the device as it -/// is, and the next device tries again. -pub(super) fn keep_drivers_loaded(instance: &InstanceShared) { - let entry = &instance.entry; - let library = entry.static_fn().get_instance_proc_addr as usize; - let portability = instance - .extensions - .iter() - .any(|name| name.as_c_str() == ash::khr::portability_enumeration::NAME); - KEEPERS.keep(library, || { - #[cfg(test)] - if LOAD_AS_KEPT.load(std::sync::atomic::Ordering::SeqCst) { - crate::loaded::force(); - } - let instance = bare_instance(entry, portability)?; - Some(Keeper { - _entry: entry.clone(), - _instance: instance, - }) - }); -} - -/// Tests: count a load (`loaded::force`) as the keeper is made, as a driver the device's -/// instance let go loads again for the keeper's on a host with several drivers. -#[cfg(test)] -pub(crate) static LOAD_AS_KEPT: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - -/// A bare instance of `entry`: no layers, no messenger, portability enumeration where -/// `portability` says the device's instance enabled it. -fn bare_instance(entry: &ash::Entry, portability: bool) -> Option { - let extensions = [ash::khr::portability_enumeration::NAME.as_ptr()]; - let application = vk::ApplicationInfo::default() - .engine_name(c"metal2vulkan") - .api_version(metal2vulkan::vk::ApiVersion::V1_2.packed()); - let info = vk::InstanceCreateInfo::default().application_info(&application); - let info = if portability { - info.enabled_extension_names(&extensions) - .flags(vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR) - } else { - info - }; - // SAFETY: `info` and everything it points at live for the call. - let instance = unsafe { new_instance(entry, &info) }.ok()?; - Some(instance.handle()) -} diff --git a/crates/metal2vulkan-runtime/src/device/line.rs b/crates/metal2vulkan-runtime/src/device/line.rs deleted file mode 100644 index c336f303e..000000000 --- a/crates/metal2vulkan-runtime/src/device/line.rs +++ /dev/null @@ -1,929 +0,0 @@ -//! A device's line of generations: the one Metal device (`MTLDevice`) a program holds across its -//! GPU's recoveries, each recovery a new `VkDevice` behind it. -//! -//! Metal's `MTLDevice` survives a GPU recovery: the hung command buffer fails, the others in -//! flight fail as its victims, and the program goes on with the same device. Vulkan's device does -//! not: once a call returned `VK_ERROR_DEVICE_LOST`, the `VkDevice` serves nothing more (vkspec -//! 5.2.3, "Lost Device"), and only a new one serves again. So the runtime's device is a line of -//! generations, each a [`DeviceShared`] over its own `VkDevice`: -//! -//! - **Two kinds of handle.** A *root* handle (the device the program made, `Device::system_default` -//! and the rest, and every clone of it) holds the line and no generation: every call made -//! through it goes to the generation serving when it is made (the public calls' -//! [`Device::current`]), and again to the one serving next where that one was lost under the -//! call and refused it for that ([`Device::at_serving`]; a call that takes host memory or a -//! range token, which it cannot take twice, is not refused for a loss once it took them, -//! [`Device::at_serving_taking`]). A *generation* handle holds one generation: the device of -//! every object made on it (a buffer's, a pipeline state's), through which the object's Vulkan -//! calls reach its own `VkDevice` alone, its drop included. So no object's Vulkan handle ever -//! reaches another generation's `VkDevice`: the recovery carries the program's objects of the -//! kinds `carry.rs` lists to the new generation, each the same object with its own parts there, -//! and any other object made before it is refused where it meets the new generation -//! (`RuntimeGap::MadeBeforeRecovery`, `error.rs`). -//! - **The states.** [`State`]: the line serves one generation (`Live`); once it is lost, the -//! first call that needs the device recovers it (`Lost`, then claimed), while every other call -//! waits for that recovery, the first to wait past [`RECOVERY_NOTICE`] announcing it and waiting -//! on; a line that cannot recover (a device the consumer made, `Device::from_raw`, or one whose -//! new `VkDevice` failed) answers as the lost device does (`Failed`). -//! - **The recovery** ([`Line::recover`]), on the program's thread whose call claimed it: the lost -//! generation's command buffers in flight fail through its completion path, the oldest -//! incomplete batch's as the hang and the others as its victims (`command_buffer/completion.rs`), -//! and so do those its scheduler holds unsubmitted, whatever they wait for (an event value, a -//! making, a host step), in each queue's commit order (`scheduler/mod.rs`'s `fail_lost`); -//! its queues waited idle, each under its lock; then a new `VkDevice` of the same physical -//! device, options, queue families and extensions (`create.rs`, the same making as the first), -//! whose device-level objects are made as the first generation's were, the shader cache's -//! records kept on disk warm. It carries the program's objects it can to the new generation -//! before that serves (`carry.rs`). The calls waiting go on with it, the command queues made -//! before take a new place on it at their next command buffer (`queue.rs`), and it announces -//! `Degradation::DeviceRecovered`. -//! - **Each recovery's notices are its own.** The kinds a device announced go on across its -//! generations, each kind announced once for the device, but a recovery's notices -//! (`Degradation::DeviceRecovered`) are announced at every recovery, whatever an earlier one -//! announced: the recovery itself, and at most one each of a call's wait for it past -//! [`RECOVERY_NOTICE`], its command buffers in flight taking past it to fail, and its new -//! `VkDevice`'s failure. So a slow second recovery says so as the first did, and repeated losses -//! announce a few notices each, never one per waiting call. -//! - **What goes on across generations**: the line's handles and holds (`holds.rs`), its counts -//! (`WorkCounts`), the Metal address space with its reserved pools, the resource IDs and the -//! `uniqueIdentifier`s, so nothing made after a recovery takes an address or an identity one made -//! before holds. -//! - **At most two `VkDevice`s.** A generation is destroyed when its last handle goes: the lost -//! one once the objects left on it went (a carried object lets go of it once none of its -//! command buffers records, `carry.rs`), and, where `Device::raw` of a root handle answered its -//! handles, once a later such call answered the new one's (`Line::lend`), the new one serving -//! meanwhile. Counted: `WorkCounts::vk_devices_live`. A second recovery while objects left on -//! the first's lost generation still live keeps their `VkDevice` as well, counted there too. - -use super::create; -use super::{holds, lock, Device, DeviceOptions, DeviceShared, InstanceShared}; -use crate::address::AddressSpace; -use crate::capabilities::DeviceProperties; -use crate::degradation::Announced; -use crate::error::{invalid, Error, Problem, RuntimeGap}; -use crate::resource_ids::{PassingHolds, ResourceIds}; -use crate::shader_cache::CacheSetup; -use crate::unique_identifier::UniqueIdentifiers; -use crate::work_counts::Counters; -use ash::vk; -use metal2vulkan::device::EnableSet; -use std::cell::Cell; -use std::ffi::CString; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, Weak}; -use std::time::{Duration, Instant}; - -/// How long a call waits for a recovery under way before it announces the wait -/// (`Degradation::DeviceRecovered`, once per recovery), and how long a recovery waits for its -/// command buffers in flight to fail before it announces that; each waits on past it. -pub(crate) const RECOVERY_NOTICE: Duration = Duration::from_secs(10); - -/// What a line's every generation answers alike: they are made of the same physical device with -/// the same options. A root handle reads them without a generation; each generation holds a copy. -#[derive(Clone)] -pub(crate) struct Invariant { - pub(crate) properties: DeviceProperties, - pub(crate) compile: metal2vulkan::device::Device, - pub(crate) enabled: EnableSet, - pub(crate) extensions: Vec, - /// The shader cache's directory (`Device::shader_cache_directory`); `None` where it keeps - /// none. - pub(crate) cache_directory: Option, - /// The view check (`view_check.rs`): its answer, and the compile device of its measured - /// facts once it holds any, which every compile then takes (`Device::compile_device`). - pub(crate) views: Arc, -} - -/// How the line makes its next `VkDevice`: what the first was made of (`create.rs`). None for a -/// device the consumer made, which the runtime cannot make again. -pub(crate) struct Recipe { - pub(super) instance: Arc, - pub(super) physical: vk::PhysicalDevice, - pub(super) options: DeviceOptions, - pub(super) cache: CacheSetup, -} - -/// What every generation of a line goes on with (the module docs). -pub(super) struct Carried { - /// The Metal address space and its reserved pools. - pub(super) addresses: Arc>, - /// The resource IDs of textures and sampler states, and the caller's reservations of them. - pub(super) resource_ids: Arc>, - /// The passing holds a making waits out before it takes a resource ID: of every generation, - /// as the IDs are (`resource_ids.rs`). - pub(super) passing_holds: Arc, - /// The `uniqueIdentifier`s. - pub(super) identifiers: Arc, - /// The counts of the commit path's work (`WorkCounts`). - pub(super) counts: Arc, - /// The kinds of degradation announced, so each is announced once for the device, not once per - /// generation (`degradation.rs`); a recovery's notices are announced at each recovery - /// (`Device::degrade_recovered`, `Device::degrade_recovery_step`; the module docs). - pub(super) announced: Arc, -} - -/// The generations' counts every generation shares, read without the line: which generation -/// serves, and how many `VkDevice`s the line made and keeps. -#[derive(Default)] -pub(crate) struct Lineage { - /// The generation that serves, or that a recovery makes: a generation handle of an earlier - /// one goes to the line for its calls ([`Device::current`]). - current: AtomicU64, - /// The line's `VkDevice`s alive (`WorkCounts::vk_devices_live`). - live: AtomicU64, - /// The line's `VkDevice`s made, the first among them (`WorkCounts::vk_devices_made`). - made: AtomicU64, - /// Its recoveries that made a new `VkDevice` (`WorkCounts::device_recoveries`). - recoveries: AtomicU64, - /// The carried states' programs let go of at a lost generation's rest - /// (`WorkCounts::lost_programs_released`). - programs_released: AtomicU64, - /// The carried textures' parts let go of at a lost generation's rest - /// (`WorkCounts::lost_textures_released`). - textures_released: AtomicU64, -} - -impl Lineage { - /// The generation that serves, or that a recovery makes. A relaxed load: a handle's check of - /// its own generation against it is the one load a call pays where nothing was lost. - pub(crate) fn current(&self) -> u64 { - self.current.load(Ordering::Relaxed) - } - - /// A `VkDevice` of the line was made: its generation's number. - pub(super) fn made(&self) -> u64 { - self.live.fetch_add(1, Ordering::AcqRel); - self.made.fetch_add(1, Ordering::AcqRel); - self.current.load(Ordering::Acquire) - } - - /// A `VkDevice` of the line was destroyed. - pub(super) fn destroyed(&self) { - self.live.fetch_sub(1, Ordering::AcqRel); - } - - /// A carried state's program on a lost generation was let go of at its rest. - pub(crate) fn program_released(&self) { - self.programs_released.fetch_add(1, Ordering::Relaxed); - } - - /// A carried texture's parts on a lost generation were let go of at its rest. - pub(crate) fn texture_released(&self) { - self.textures_released.fetch_add(1, Ordering::Relaxed); - } - - /// The carried states' programs and textures' parts let go of at lost generations' rest - /// (`WorkCounts`). - pub(crate) fn released(&self) -> (u64, u64) { - ( - self.programs_released.load(Ordering::Relaxed), - self.textures_released.load(Ordering::Relaxed), - ) - } - - /// The `VkDevice`s alive, made, and the recoveries (`WorkCounts`). - pub(crate) fn counts(&self) -> (u64, u64, u64) { - ( - self.live.load(Ordering::Acquire), - self.made.load(Ordering::Acquire), - self.recoveries.load(Ordering::Acquire), - ) - } -} - -/// Where a line is (the module docs). -enum State { - /// Its first `VkDevice` is being made: no handle of it exists yet. - Making, - /// It serves this generation. - Live(Arc), - /// This generation was lost; `claimed` once a call took its recovery on; `culprit` the - /// command buffer its completion failed as the hang, once it named one; `waited` once a call - /// announced its wait for this recovery past [`RECOVERY_NOTICE`], which no other call waiting - /// for it announces again. - Lost { - lost: Arc, - claimed: bool, - culprit: Option, - waited: bool, - }, - /// It cannot recover (a device the consumer made, or one whose new `VkDevice` failed): this - /// lost generation answers every call, as a lost device does. - Failed(Arc), - /// The program's last handle went. - Gone, -} - -/// The command buffer a loss named the hang (`command_buffer/completion.rs`), for the notice and -/// for the hold of its queue. -pub(crate) struct Culprit { - /// Its command queue's part every generation of the queue shares (`queue.rs`). - pub(crate) queue: Weak, - /// It as the notice names it: by its label and its queue's, with its ended encoders' kinds - /// and labels (`command_buffer/labels.rs`). - pub(crate) named: String, - /// The queue was picked among two or more with work in flight: an inference, the queue whose - /// oldest incomplete batch was submitted first. - pub(crate) inferred: bool, - /// The command buffers that failed as its victims, counted as each failed ([`Line::victim`]). - pub(crate) victims: usize, -} - -/// A device's line (the module docs). -pub(crate) struct Line { - /// The registry of the handles every generation's share (`holds.rs`). - pub(super) holds: Arc, - pub(crate) invariant: Invariant, - pub(super) carried: Carried, - pub(crate) lineage: Arc, - recipe: Option, - state: Mutex, - /// Signalled as the line serves a generation again, or fails. - changed: Condvar, - /// The command queues made on the device, which each recovery has take a new place on the new - /// generation at their next command buffer (`queue.rs`). - queues: Mutex>>, - /// The generation a root handle's `Device::raw` lent (`Line::lend`). - lent: Mutex, - /// What the device tests set of its recoveries ([`hooks`]), in their builds only. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) hooks: hooks::Hooks, -} - -/// What a line lent a root handle's `Device::raw` ([`Line::lend`]). -enum Lent { - /// No generation yet. - Nothing, - /// This generation, kept until a later call lends another. - To(Arc), - /// The program's last handle went ([`Line::release`]). - Released, -} - -impl Line { - /// A new line, its first `VkDevice` being made. - pub(super) fn new( - holds: Arc, - invariant: Invariant, - announced: Announced, - recipe: Option, - ) -> Arc { - Arc::new(Line { - holds, - invariant, - carried: Carried { - addresses: Arc::new(Mutex::new(AddressSpace::new())), - resource_ids: Arc::default(), - passing_holds: Arc::default(), - identifiers: Arc::default(), - counts: Arc::default(), - announced: Arc::new(announced), - }, - lineage: Arc::default(), - recipe, - state: Mutex::new(State::Making), - changed: Condvar::new(), - queues: Mutex::default(), - lent: Mutex::new(Lent::Nothing), - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - hooks: hooks::Hooks::default(), - }) - } - - /// How long a call waits for a recovery under way, or a recovery for its command buffers in - /// flight to fail, before it announces the wait: [`RECOVERY_NOTICE`], or in the device tests' - /// builds what a test set (`hooks::Hooks::notice_after`). - fn notice_after(&self) -> Duration { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if let Some(after) = *lock(&self.hooks.notice_after) { - return after; - } - RECOVERY_NOTICE - } - - /// Whether the line makes a new `VkDevice` once one is lost: a device the runtime made. - pub(crate) fn recovers(&self) -> bool { - self.recipe.is_some() - } - - /// Whether the line went past `generation`, lost, to a later one it serves or recovers to: - /// not where it cannot recover, nor where its new `VkDevice` failed. - pub(crate) fn recovers_past(&self, generation: u64) -> bool { - self.recovers() - && self.lineage.current() != generation - && !matches!(*lock(&self.state), State::Failed(_)) - } - - /// Its first generation, made: the line serves it. - pub(super) fn first(&self, first: &Arc) { - let mut state = lock(&self.state); - if let State::Making = *state { - *state = State::Live(Arc::clone(first)); - } - } - - /// `lost`, a generation of the line, was lost: the line's next call that needs the device - /// recovers it, where the line recovers, and each generation handle of it goes to the line - /// for its calls from now on. Nothing where the line no longer serves it. - pub(super) fn lose(&self, lost: &DeviceShared) { - let mut state = lock(&self.state); - let State::Live(serving) = &*state else { - return; - }; - if !std::ptr::eq(Arc::as_ptr(serving), lost) { - return; - } - let serving = Arc::clone(serving); - *state = match self.recovers() { - true => { - // Past the lost one: its handles go to the line, which recovers. - (self.lineage.current).store(lost.generation + 1, Ordering::Release); - State::Lost { - lost: serving, - claimed: false, - culprit: None, - waited: false, - } - } - false => State::Failed(serving), - }; - drop(state); - self.changed.notify_all(); - } - - /// The generation a call of `device`'s goes to: the serving one, after the recovery of a lost - /// one, made here where no call took it on yet, else waited for (the module docs); a line that - /// cannot recover answers with its lost generation. A handle for the call, counted as the - /// program's. - pub(super) fn current(self: &Arc, device: &Device) -> Device { - let mut began: Option = None; - let mut state = lock(&self.state); - loop { - match &mut *state { - State::Live(serving) => { - // A generation the relay found lost (`relay.rs`), which no failed wait has - // reported yet. - if serving.lost() { - let serving = Arc::clone(serving); - drop(state); - self.lose(&serving); - state = lock(&self.state); - continue; - } - return holds::program(Arc::clone(serving)); - } - State::Failed(lost) => return holds::program(Arc::clone(lost)), - // A thread command buffers' completion depends on, which the recovery waits for, - // neither recovers nor waits: its call reaches the lost generation, and answers as - // a lost device does (`exit_guard::serving_completion`). - State::Lost { lost, .. } if crate::exit_guard::serving_completion() => { - return holds::program(Arc::clone(lost)); - } - State::Lost { lost, claimed, .. } if !*claimed => { - *claimed = true; - let lost = Arc::clone(lost); - drop(state); - return self.recover(lost); - } - State::Lost { lost, waited, .. } => { - let began = *began.get_or_insert_with(Instant::now); - let after = self.notice_after(); - // The first call to wait past the bound for this recovery announces it, once - // per recovery whatever an earlier recovery announced (the module docs). - if !*waited && began.elapsed() >= after { - *waited = true; - let lost = Arc::clone(lost); - drop(state); - holds::program(lost).degrade_recovery_step(|| { - ( - "a call made during the device's recovery".to_owned(), - format!( - "it waited {:?} for the recovery under way, and waits on", - began.elapsed() - ), - ) - }); - state = lock(&self.state); - continue; - } - let timeout = match *waited { - true => RECOVERY_NOTICE, - false => after.saturating_sub(began.elapsed()), - }; - let (next, _) = (self.changed) - .wait_timeout(state, timeout) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state = next; - } - // No handle of a line in either exists but the caller's own: it answers. - State::Making | State::Gone => return device.clone(), - } - } - } - - /// Recover from the loss of `lost`, which this call claimed (the module docs): the generation - /// serving next, or `lost` where the new `VkDevice` failed (the line then fails). - fn recover(self: &Arc, lost: Arc) -> Device { - let began = Instant::now(); - let old = holds::program(Arc::clone(&lost)); - // Its command buffers in flight fail through its completion path: the hang and its - // victims (`command_buffer/completion.rs`). - old.fail_in_flight(); - // Its queues idle, each under its lock: a wait on a lost device returns in finite time - // (vkspec 5.2.3), and on one the test hook marked lost waits for the work it ran. - old.drain_queues(); - let made = match &self.recipe { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - Some(_) if self.hooks.making_fails.swap(false, Ordering::AcqRel) => { - Err(Error::DeviceLost) - } - Some(recipe) => create::create_on( - &recipe.instance, - recipe.physical, - &recipe.options, - &recipe.cache, - Some(self), - ), - None => Err(Error::DeviceLost), - }; - let next = match made { - Ok(next) => next, - Err(error) => { - *lock(&self.state) = State::Failed(lost); - self.changed.notify_all(); - old.degrade_recovery_step(|| { - ( - "the device".to_owned(), - format!( - "its new VkDevice could not be made ({error}): every later call is \ - refused as on a lost device" - ), - ) - }); - return old; - } - }; - // The program's events and buffers go on with it before it serves (`carry.rs`). - let carried = old.carry_to(&next); - let previous = { - let mut state = lock(&self.state); - std::mem::replace(&mut *state, State::Live(Arc::clone(next.shared_arc()))) - }; - self.lineage.recoveries.fetch_add(1, Ordering::AcqRel); - self.changed.notify_all(); - // The lost generation lets go of the carried objects' parts and its device-level objects - // of work once none of its command buffers records (`carry.rs`). - old.shared().carry.served_past(old.shared()); - let culprit = match previous { - State::Lost { culprit, .. } => culprit, - _ => None, - }; - // The lost generation goes once the objects made on it went; a stopped one is parked - // (`command_buffer/stall.rs`): its teardown leaves its `VkDevice` and objects. - let stopped = lost.stopped(); - drop(old); - drop(lost); - // The command queues take a new place on the new generation at their next command buffer. - let queues: Vec<_> = lock(&self.queues).drain(..).collect(); - let mut kept = Vec::with_capacity(queues.len()); - for queue in queues { - if let Some(line) = queue.upgrade() { - line.retire(); - kept.push(queue); - } - } - lock(&self.queues).extend(kept); - let took = began.elapsed(); - let generation = next.shared().generation; - next.degrade_recovered(|| { - let culprit = match culprit { - Some(culprit) => { - let named = culprit.named; - let inferred = match culprit.inferred { - true => { - " (an inference: work was in flight on two or more `VkQueue`s, and \ - its queue's oldest incomplete batch was submitted first)" - } - false => "", - }; - format!( - "{named} failed as the hang (`GpuHang`){inferred}, and {} more in flight \ - as its victims (`GpuRecoveryVictim`)", - culprit.victims - ) - } - None => "no command buffer was in flight".to_owned(), - }; - let cause = match stopped { - Some(crate::command_buffer::Stop::Unanswered) => { - "stopped (no work of it advanced, and a probe on another engine did not \ - complete: the driver answered no loss), was parked (never destroyed, its \ - queues never waited for: `Device::is_parked`)," - } - Some(crate::command_buffer::Stop::Watchdog) => { - "stopped (a queue's front batch went past Metal's watchdog bound without its \ - timeline advancing, whatever another engine answered: the driver answered no \ - loss), was parked (never destroyed, its queues never waited for: \ - `Device::is_parked`)," - } - None => "was lost", - }; - ( - "the device".to_owned(), - format!( - "its VkDevice {cause} and made again in {took:?} (generation \ - {generation}): {culprit}; {}", - carried.say() - ), - ) - }); - next - } - - /// Name the command buffer a loss failed as the hang, for the notice and the hold of its queue - /// (`command_buffer/completion.rs`): the first named, until the recovery. - pub(crate) fn named(&self, named: Culprit) { - if let State::Lost { culprit, .. } = &mut *lock(&self.state) { - culprit.get_or_insert(named); - } - } - - /// Count a command buffer that failed as the victim of the hang the loss named, for the - /// recovery's notice: each failure of the loss counts its own (`command_buffer/completion.rs`). - pub(crate) fn victim(&self) { - if let State::Lost { - culprit: Some(culprit), - .. - } = &mut *lock(&self.state) - { - culprit.victims += 1; - } - } - - /// Whether a command buffer committed now on the queue whose shared part is `queue` is held as - /// Metal holds the queue of a hang in flight: it runs nothing and completes with no error. So - /// from the loss that named one of its command buffers the hang until the recovery. - pub(crate) fn holds_hang_queue(&self, queue: &Arc) -> bool { - match &*lock(&self.state) { - State::Lost { - culprit: Some(culprit), - .. - } => std::ptr::eq(culprit.queue.as_ptr(), Arc::as_ptr(queue)), - _ => false, - } - } - - /// The generation that serves, lent to a root handle's [`Device::raw`]: kept until a later - /// call lends another, so the handles that call returned stay valid until then. - pub(super) fn lend(&self, serving: &Device) -> &DeviceShared { - let shared = Arc::clone(serving.shared_arc()); - let pointer = Arc::as_ptr(&shared); - let previous = { - let mut lent = lock(&self.lent); - match &*lent { - Lent::To(kept) if Arc::ptr_eq(kept, &shared) => None, - _ => Some(std::mem::replace(&mut *lent, Lent::To(shared))), - } - }; - drop(previous); - // SAFETY: the line keeps the generation in `lent` until a later call lends another, which - // `Device::raw`'s contract puts past every use of the handles it returned; the line lives - // as long as the root handle the reference is borrowed from. - unsafe { &*pointer } - } - - /// A command queue made on the device, which each recovery has take a new place (`queue.rs`). - pub(crate) fn queue_made(&self, queue: Weak) { - let mut queues = lock(&self.queues); - queues.retain(|queue| queue.strong_count() > 0); - queues.push(queue); - } - - /// How many of the command queues the program made it holds a handle of - /// (`QueueLine::held_by_the_program`), for the runtime tests' default queue limits' check - /// (`Device::test_program_queue`). The upgrades go after the lock, so no queue's last - /// reference drops under it. - #[cfg(test)] - pub(crate) fn program_queues_held(&self) -> u64 { - let queues: Vec<_> = lock(&self.queues) - .iter() - .filter_map(Weak::upgrade) - .collect(); - let held = queues - .iter() - .filter(|line| crate::queue::QueueLine::held_by_the_program(line)); - held.count() as u64 - } - - /// The program's last handle went (`holds.rs`): the generation it serves goes once nothing - /// else holds it, here or as the last handle drops. - pub(super) fn release(&self) { - let released = std::mem::replace(&mut *lock(&self.state), State::Gone); - drop(released); - let lent = std::mem::replace(&mut *lock(&self.lent), Lent::Released); - drop(lent); - } -} - -thread_local! { - /// The generation the thread's public call runs on past its check of the generation's loss, - /// its arguments taken ([`Device::at_serving_taking`]): the address of its `DeviceShared`. - static RUNS_ON: Cell = const { Cell::new(0) }; -} - -/// The thread's public call running on a generation past its check of the generation's loss -/// ([`Device::at_serving_taking`]): while it lives, the generation is not lost to the call's own -/// checks ([`runs_on`]). What it replaced comes back as it drops. -struct RunsOn(usize); - -impl RunsOn { - fn enter(shared: &DeviceShared) -> RunsOn { - let address = std::ptr::from_ref(shared).addr(); - RunsOn(RUNS_ON.with(|runs| runs.replace(address))) - } -} - -impl Drop for RunsOn { - fn drop(&mut self) { - RUNS_ON.with(|runs| runs.set(self.0)); - } -} - -/// Whether the thread's public call runs on `shared` past its check of its loss ([`RunsOn`]): -/// a loss of it since follows the call, which its checks do not refuse (`Device::is_lost`). -#[cold] -pub(super) fn runs_on(shared: &DeviceShared) -> bool { - RUNS_ON.with(|runs| runs.get() == std::ptr::from_ref(shared).addr()) -} - -/// The device a call goes to ([`Device::current`]): the caller's own handle, or one of the -/// generation that serves. -pub(crate) enum Current<'a> { - This(&'a Device), - Serving(Device), -} - -impl std::ops::Deref for Current<'_> { - type Target = Device; - - fn deref(&self) -> &Device { - match self { - Current::This(device) => device, - Current::Serving(device) => device, - } - } -} - -impl Device { - /// No Metal counterpart: run the device's recovery from the loss of its `VkDevice` with no - /// GPU fault, as a real loss runs it, for tests of what survives one. The command buffers in - /// flight fail, the one of the oldest incomplete batch as the hang (`GpuHang`, counted against - /// its queue as Metal counts a hang, so a queue's second revokes it, `AccessRevoked`) and the - /// rest as its victims (`GpuRecoveryVictim`); the runtime makes a new `VkDevice` of the same - /// physical device, options, queue families and extensions, and every later call of the - /// device, and of its command queues, goes to it. The objects made before of the kinds the - /// recovery carries go on there as the same objects (`device/carry.rs` lists the kinds); any - /// other object made before is refused where it meets it (`RuntimeGap::MadeBeforeRecovery`). - /// Announced (`Degradation::DeviceRecovered`). - /// Returns once the new `VkDevice` serves; where it could not be made, `DeviceLost`, and the - /// device answers as a lost one from then on. - /// - /// Refused on a device the consumer made (`Device::from_raw`), which the runtime cannot make - /// again: `RuntimeGap::AdoptedDeviceRecovery`, the device left as it was. Called from a thread - /// the device's command buffers' completion depends on (a completion-seen handler), it marks - /// the device lost and returns: the next call from another thread recovers it. - pub fn recover_for_test(&self) -> Result<(), Error> { - let device = self.current(); - let line = device.line(); - if !line.recovers() { - return Err(Error::NotImplemented(RuntimeGap::AdoptedDeviceRecovery)); - } - device.mark_lost(); - if crate::exit_guard::serving_completion() { - return Ok(()); - } - let next = line.current(&device); - match next.generation_serves() && !next.is_lost() { - true => Ok(()), - false => Err(Error::DeviceLost), - } - } - - /// No Metal counterpart (a runtime-only query): whether `device`, a `VkDevice` whose handles - /// [`raw`](Self::raw) answered, stopped and is parked. No work of it advanced while some was - /// pending and a probe on another engine of the GPU did not complete, the driver answering no - /// loss (`command_buffer/stall.rs`), so its command buffers in flight failed as a lost - /// device's do (`GpuHang`, `GpuRecoveryVictim`) and the device recovered on a new `VkDevice` - /// (`Degradation::DeviceRecovered`, whose notice says it stopped). A parked `VkDevice` is - /// never destroyed and none of its objects is released, since its work never completes: a - /// consumer holding its handles waits for none of its queues and destroys none of its - /// objects, its swapchains among them, and leaves them likewise. False for any other - /// `VkDevice`, one lost to a driver's `VK_ERROR_DEVICE_LOST` among them. - pub fn is_parked(&self, device: vk::Device) -> bool { - crate::release::parked(device) - } - - /// The generation this call goes to (the module docs): this handle's own where it is a - /// generation's that serves, at one relaxed load; else the line's, after its recovery. - #[inline] - pub(crate) fn current(&self) -> Current<'_> { - match self.generation_serves() { - true => Current::This(self), - false => Current::Serving(self.line().current(self)), - } - } - - /// Run `call`, a public call of this handle, on the generation it goes to - /// ([`current`](Self::current)), and again on the one serving next wherever the generation it - /// ran on was lost under it and refused it for that ([`lost_under`](Self::lost_under)): a - /// call of the device Metal keeps across a recovery is not refused because the generation it - /// took was lost while it ran. Refused so, a run kept nothing it made, so the call runs whole - /// again. Bounded as the line's waits are: each run is on a later generation than the one - /// before, after its recovery, which [`Line::current`] waits for (announced past - /// [`RECOVERY_NOTICE`]); a line that cannot recover answers the loss. - pub(crate) fn at_serving( - &self, - mut call: impl FnMut(&Device) -> Result, - ) -> Result { - loop { - let device = self.current(); - match call(&device) { - Err(refused) if device.lost_under(&refused) => continue, - answer => return answer, - } - } - } - - /// [`at_serving`](Self::at_serving) of a call that takes `taken`, arguments it consumes (host - /// memory and what gives it back, a range token), which a run refused for a loss could not - /// give a later one: they go to the generation the call goes to once it is not lost, else to - /// the one serving next, and the call then runs on it whole, a loss of it from then on - /// following the call, as one after the call returned would. Its checks of the generation's - /// loss answer so ([`RunsOn`]): the call is not refused for a loss once it took its - /// arguments, and answers as on a generation lost after it: its objects of that generation, - /// carried to the next by their maker where a recovery carries such (`carry.rs`), else refused - /// where they meet the next (`RuntimeGap::MadeBeforeRecovery`). A line that cannot recover - /// refuses it as before. - pub(crate) fn at_serving_taking( - &self, - taken: A, - call: impl FnOnce(&Device, A) -> Result, - ) -> Result { - loop { - let device = self.current(); - if device.shared().lost() { - let refused = device.lost_refusal(); - if device.lost_under(&refused) { - continue; - } - return Err(refused); - } - let _runs = RunsOn::enter(device.shared()); - return call(&device, taken); - } - } - - /// Whether `refused`, a call's answer on this generation, is the refusal of its loss - /// (`DeviceLost`, or `RuntimeGap::MadeBeforeRecovery` as [`lost_refusal`](Self::lost_refusal) - /// answers it) and the line went past it: the call goes to the generation serving next - /// ([`at_serving`](Self::at_serving)). A call refused for an object of an earlier generation - /// while its own still serves is answered so, as is one of a thread command buffers' - /// completion depends on, whose calls reach the lost generation ([`Line::current`]). - #[cold] - fn lost_under(&self, refused: &Error) -> bool { - !crate::exit_guard::serving_completion() - && self.line().recovers_past(self.shared().generation) - && (*refused == Error::DeviceLost || *refused == self.lost_refusal()) - } - - /// The refusal of a call that reaches this generation after its loss: where the device's line - /// recovers past it, the call's object was made before the recovery - /// (`RuntimeGap::MadeBeforeRecovery`); else the lost device's (`DeviceLost`). - #[cold] - pub(crate) fn lost_refusal(&self) -> Error { - match self.line().recovers_past(self.shared().generation) { - true => Error::NotImplemented(RuntimeGap::MadeBeforeRecovery), - false => Error::DeviceLost, - } - } - - /// The refusal of `call` for an object of this device that `other` met, which is not this - /// device: where both are of one line, generations a recovery parts, the object was made - /// before the recovery (`RuntimeGap::MadeBeforeRecovery`), or the call's object was; else the - /// object is another device's (`Invalid`, `ForeignObject`). Out of line, so that a bind's - /// check, whose refusal this is, inlines where the bind makes it. - #[cold] - #[inline(never)] - pub(crate) fn foreign(&self, call: &'static str, other: &Device) -> Error { - match self.same_line(other) { - true => Error::NotImplemented(RuntimeGap::MadeBeforeRecovery), - false => invalid(call, Problem::ForeignObject), - } - } - - /// Whether this is a generation handle of the generation that serves: one relaxed load of - /// the line's generation. Its loss moves the line past it at once where the line recovers - /// (`Line::lose`, under `Device::mark_lost`); a line that cannot recover answers with the lost - /// generation, which so serves on. - #[inline] - pub(crate) fn generation_serves(&self) -> bool { - match &self.0 { - super::Pin::Generation(shared) => shared.lineage.current() == shared.generation, - super::Pin::Root(..) => false, - } - } - - /// The device's command buffers in flight fail through its completion path, and the batches - /// its scheduler holds, whatever each waits for, through the same (`scheduler/mod.rs`'s - /// `fail_lost`), and this waits until its scheduler holds none and its completion took them - /// all (`command_buffer/completion.rs`): the first step of a recovery, the device lost. So - /// every command buffer committed before the loss that did not complete fails, as the hang or - /// its victim, before the next generation serves its queue's later ones. - fn fail_in_flight(&self) { - let shared = self.shared(); - shared.completion.fail_in_flight(); - shared.scheduler.wake(); - let began = Instant::now(); - let after = self.line().notice_after(); - let mut announced = false; - // The scheduler's first: what it failed was watched before it holds none, so the - // completion's look after sees it. - while !(shared.scheduler.holds_none() && shared.completion.settled()) { - std::thread::sleep(Duration::from_millis(1)); - // Once per recovery: only the call that claimed it fails its command buffers. - if !announced && began.elapsed() >= after { - announced = true; - self.degrade_recovery_step(|| { - ( - "the device's recovery".to_owned(), - format!( - "its command buffers in flight took {:?} to fail, and it waits on", - began.elapsed() - ), - ) - }); - } - } - } -} - -/// The device tests' hooks into a line's recoveries (`tests::device_recovery`) and its render -/// encoders' draws (`tests::draw_again`), in those tests' builds only: each set on one device, so -/// a test's settings reach no other test's device. -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) mod hooks { - use super::lock; - use std::sync::atomic::AtomicBool; - use std::sync::Mutex; - use std::time::Duration; - - /// What runs at a draw's keeping ([`Hooks::at_keep`]). - pub(crate) type AtKeep = Box; - - /// What a test set of a line's recoveries. - #[derive(Default)] - pub(crate) struct Hooks { - /// How long a call waits for a recovery under way, or a recovery for its command buffers - /// in flight to fail, before it announces the wait, in place of - /// [`RECOVERY_NOTICE`](super::RECOVERY_NOTICE): zero announces every such wait. - pub(crate) notice_after: Mutex>, - /// The next recovery's new `VkDevice` fails to be made, as a driver's refusal fails it: - /// the line fails, and answers as the lost device does from then on. - pub(crate) making_fails: AtomicBool, - /// How long no queue's work advances before a probe (`command_buffer/stall.rs`), in place - /// of its `STALL`. - pub(crate) stall_after: Mutex>, - /// No probe is seen answered (`command_buffer/stall.rs`), as on a GPU whose every engine - /// stopped: a stall past `stall_after` stops the generation. - pub(crate) probe_unanswered: AtomicBool, - /// How long a queue's front batch may go without its timeline advancing before it fails - /// as Metal's timed-out command buffer (`command_buffer/stall.rs`), in place of its - /// `WATCHDOG`. - pub(crate) watchdog_after: Mutex>, - /// Run once, on the thread that lowers it, as the draw that is the count's (from zero) - /// to take every step since it was set reaches its keeping, after its uses' noting: what - /// another thread may do at that moment (`render/draw_again.rs`). - pub(crate) at_keep: Mutex>, - } - - impl Hooks { - /// A draw that took every step reached its keeping: run [`at_keep`](Self::at_keep)'s - /// hook where it is this draw's, without its lock. - pub(crate) fn reach_keep(&self) { - let mut at_keep = lock(&self.at_keep); - let hook = match at_keep.as_mut() { - Some((0, _)) => at_keep.take(), - Some((count, _)) => { - *count -= 1; - None - } - None => None, - }; - drop(at_keep); - if let Some((_, hook)) = hook { - hook(); - } - } - } -} diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs deleted file mode 100644 index e135f2b12..000000000 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ /dev/null @@ -1,3632 +0,0 @@ -//! `Device` (`MTLDevice`). -//! -//! A runtime device owns or adopts the Vulkan instance, physical device, `VkDevice` and its -//! queue, and holds what every object made from it shares: the compile-and-plan layer's -//! [`metal2vulkan::device::Device`] (built from the description restricted to what was actually -//! enabled), the memory sub-allocator, the Metal address space, the scheduler, the queues' -//! waiters, and the handler threads. -//! -//! - **Create** ([`Device::system_default`], [`Device::all`], `create.rs`) makes the instance and -//! one device per physical device with the description's recommended enables, then adopts -//! them. -//! - **Adopt** ([`Device::from_raw`], `adopt.rs`) takes the consumer's instance, physical -//! device, device and queue family with the [`EnableSet`] it enabled. The consumer keeps -//! ownership: dropping the runtime device destroys only what the runtime made. -//! - Every `new_*` constructor lives with its object (`buffer.rs` has [`Device::new_buffer`], -//! `queue.rs` [`Device::new_command_queue`], and so on). - -mod adopt; -pub(super) mod argument_buffers; -pub(crate) mod carry; -mod compiles; -pub(super) mod create; -pub(super) mod float_tininess; -pub(super) mod functions; -pub(crate) mod handles; -pub(crate) mod holds; -pub(super) mod instance_requirements; -pub(super) mod keeper; -pub(crate) mod line; -pub(super) mod prime; -pub(super) mod properties; -pub(crate) mod queue_quiet; -pub(crate) mod relay; -mod staging; -pub(super) mod submit; -pub(crate) mod submit_calls; -pub(crate) mod submit_stalls; - -pub use adopt::RawDevice; -#[cfg(test)] -pub(crate) use compiles::COMPILE_ROOM; -pub(crate) use compiles::{holding, COMPILE_STACK}; -pub(crate) use create::{queue_limits_reached, QUEUE_LIMITS_REACHED}; -pub use create::{ - DebugMessage, DeviceOptions, LayerSetting, LayerSettingValue, MessageKind, MessageSeverity, - MessageSink, QueueLimits, -}; -pub use handles::{DeviceHandles, ExtraQueue, ReservedQueue}; -pub use properties::{DeviceKind, PhysicalDeviceIdentity}; -pub(crate) use staging::FILL_QUEUE_LEAST; -pub(crate) use submit::OWN_TIMELINES; - -use super::address::AddressSpace; -use super::attachmentless::KeptPasses; -use super::capabilities::DeviceProperties; -use super::color_resolve::ColorResolveObjects; -use super::command_buffer::fences::Fences; -use super::command_buffer::{Completion, Item}; -use super::contexts::{self, Contexts}; -use super::degradation::{Announced, Degradation, Told}; -use super::depth_copy::DepthCopyObjects; -use super::depth_stencil_resolve::DepthStencilResolveObjects; -use super::draw_source::{sized_index_bind, SizedIndexBind}; -use super::dynamic_state::{ColorWriteMasks, ExtendedDynamicState}; -use super::error::{internal, vulkan, DeadlockCause, Error}; -use super::exit_guard::{self, Call}; -use super::freed_memory::Parking; -use super::function_table::TableShared; -use super::generated_commands::Commands; -use super::gpu_pools::GpuPools; -use super::gpu_time::{self, FromHost, Timing}; -use super::heap_sets::DeviceHeaps; -use super::host_memory::Importer; -use super::interop::Interop; -use super::loader_word::{DeviceWord, LoaderWord}; -use super::memory::Memory; -use super::memory_log::MemoryLog; -use super::mipmap_scratch::MipmapScratch; -use super::owned_kernel::OwnedKernels; -use super::pending_audit::PendingAudit; -use super::recycle::{self, BufferMaking, Recycler}; -use super::released_programs::Keepers; -use super::render_state::DepthRanges; -use super::render_target::KeptRenderPasses; -use super::resource_ids::{PassingHolds, ResourceIds, SamplerIdReads}; -use super::sample_planes::PlanesObjects; -use super::sampler::{LiveSamplers, SamplerCount}; -use super::scheduler::Scheduler; -use super::shader_cache::driver::Making; -use super::shader_cache::{found_in_cache, CacheSetup, ShaderCache, REPORTED_STAGES}; -use super::sharing::Sharing; -use super::spares::Spares; -use super::sparse::device::SparseDevice; -use super::stencil_copy::StencilCopyObjects; -use super::texture::TextureState; -use super::unique_identifier::UniqueIdentifiers; -use crate::image_barrier::MemoryReads; -use crate::recorder::{Command, CountDraws, MeshDraws, MultiDraws, Slot}; -use crate::release; -use ash::vk::{self, Handle}; -use functions::{Functions, Vk}; -use metal2vulkan::bind::RegionLimits; -use metal2vulkan::device::{DeviceDescription, EnableSet}; -use metal2vulkan::error::RuntimeDriverDefect; -use relay::Flights; -use staging::Role; -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak}; -use std::time::{Duration, Instant}; -use submit::{Internal, OwnTimeline}; - -/// A Metal device (`MTLDevice`) on a Vulkan device. Cheap to clone (a retain); `Send + Sync`. -/// -/// The program's last drop of its handles (the device's own and its objects'), on a thread of the -/// program's, stops the runtime's own background work on the device and waits for it: at most the -/// round of its check of textures over host pages in progress, or the record its warm pass is -/// making ([`Device::warm`]). So the device is torn down on that thread before the drop returns, -/// and a consumer that adopted the `VkDevice` ([`Device::from_raw`]) may destroy it then. -pub struct Device( - Pin, - /// The handle's place in the registry of the runtime's own holds (`holds.rs`). - holds::Share, -); - -/// What a device handle holds (`line.rs`): one generation, or the device's line alone. -pub(crate) enum Pin { - /// A generation's handle: the device of the objects made on it, whose Vulkan calls reach that - /// generation's `VkDevice` alone. - Generation(Arc), - /// A root handle: the program's device, whose calls go to the generation that serves. - Root(Arc), -} - -impl Pin { - /// The address of the cell it holds, a generation's or a root's: two handles of one cell - /// hold the same address, and no generation's is a root's. - #[inline(always)] - fn address(&self) -> *const () { - match self { - Pin::Generation(shared) => Arc::as_ptr(shared).cast(), - Pin::Root(root) => Arc::as_ptr(root).cast(), - } - } -} - -/// What a root handle holds, its clones sharing it: the device's line, and the generation a reach -/// of the handle's state pinned, for the cell's life ([`Device::shared`]). The public calls never -/// reach it; a test's may. -pub(crate) struct RootCell { - pub(super) line: Arc, - pinned: std::sync::OnceLock>, -} - -impl RootCell { - /// A root handle's cell of `line`, pinning nothing. - pub(super) fn new(line: Arc) -> Arc { - Arc::new(RootCell { - line, - pinned: std::sync::OnceLock::new(), - }) - } -} - -/// A handle on a device that does not keep it ([`Device::downgrade`]), with the registry of its -/// holds (`holds.rs`). -#[derive(Clone)] -pub(crate) struct WeakDevice(Weak, Arc); - -impl WeakDevice { - /// The device, while it lives. - pub(crate) fn upgrade(&self) -> Option { - holds::upgrade(self) - } -} - -impl std::fmt::Debug for Device { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Device") - .field("name", &self.name()) - .field("registry_id", &self.registry_id()) - .finish() - } -} - -/// The Vulkan instance a device came from. -pub(super) struct InstanceShared { - /// Keeps the loader (and its function pointers) alive. - entry: ash::Entry, - pub(super) raw: ash::Instance, - /// The `VkApplicationInfo::apiVersion` the instance was created with. - pub(super) api_version: metal2vulkan::vk::ApiVersion, - /// The instance extensions the runtime created it with; none for an adopted instance. - pub(super) extensions: Vec, - /// The runtime created the instance and destroys it with its last device. - owned: bool, - messenger: Option, - /// The relay's messenger, on an instance the runtime created with `VK_EXT_debug_utils` - /// (`relay.rs`). - relay: Option, - /// The SHA-256 of the layer settings the runtime chained at the instance's creation (none for - /// an adopted instance): part of a making's pipeline cache record's name - /// (`shader_cache/driver.rs`). - pub(super) settings: metal2vulkan::cache::Hash256, - /// The instance layers the caller asked for that the loader could not provide, which the - /// instance was created without (`create::layers_after`), in the order asked: each device - /// made of the instance says so as it is made (`create::layers_dropped`). Empty for an - /// instance created with every layer asked for, for one adopted, and where none was asked - /// for. - pub(super) dropped_layers: Vec, -} - -impl InstanceShared { - /// The sink the instance's messenger reports to, if it has one. - pub(super) fn sink(&self) -> Option<&MessageSink> { - self.messenger.as_ref().map(create::Messenger::sink) - } - - /// The relay of the instance's failures, if it has one (`relay.rs`). - pub(super) fn relay(&self) -> Option<&relay::Relay> { - self.relay.as_ref().map(relay::Messenger::relay) - } -} - -impl Drop for InstanceShared { - fn drop(&mut self) { - if !self.owned { - return; - } - // Once the process is exiting, the instance is left to its end (`exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - if let Some(messenger) = &self.messenger { - messenger.destroy(); - } - if let Some(relay) = &self.relay { - relay.destroy(); - } - // SAFETY: the runtime created the instance, and every device and messenger made from it - // is destroyed (devices hold this instance, so they dropped first). - unsafe { release::instance(&self.raw) }; - } -} - -/// Everything one device's objects share: one generation of the device's line, over its own -/// `VkDevice` (`line.rs`). -pub(super) struct DeviceShared { - /// The line the generation is of. Its state holds the generation it serves, a cycle the - /// program's last drop of its handles breaks (`holds.rs`, `Line::release`). - pub(crate) line: Arc, - /// The line's counts of its generations, read without the line (`line::Lineage`). - pub(crate) lineage: Arc, - /// The generation's number on its line: 0 for the first `VkDevice`. - pub(crate) generation: u64, - /// The instance outlives the device. - pub(super) instance: Arc, - pub(super) physical: vk::PhysicalDevice, - /// The device's functions: through [`DeviceShared::vk`] only, or a share that holds nothing - /// of the device ([`DeviceShared::functions`]). - functions: Arc, - /// The primary queue family: its first queue's, where internal submissions go. - pub(super) queue_family: u32, - /// The `VkQueue`s the runtime submits to, the primary family's first queue first: at least - /// one. Shared with the scheduler's thread where it takes the driver's stalls idle - /// (`submit_stalls.rs`). - pub(super) queues: Arc<[QueueSlot]>, - /// The families of those queues and of the caller's reserved queues, the primary first, each - /// once: what the device's buffers and images are shared among (`sharing.rs`). - pub(super) queue_families: Vec, - /// Those families, then the staging queue's where the device reserved one: what the device's - /// buffers are shared among (`sharing.rs`). - pub(super) buffer_families: Vec, - /// How many of `queues`, the first, logical queues share round robin; the rest are reserved - /// for presenting queues, but the copy queue's. - round_robin: usize, - /// The index of the copy queue's `VkQueue` among `queues`, the last, where the device has - /// one (`queue.rs`, `Device::new_command_queue_for_copies`). - copy_slot: Option, - /// The logical queues made round robin so far, unshared ones among them: the next one's turn - /// among the round robin's `VkQueue`s the fewest live queues hold is this modulo - /// `round_robin` (`Device::take_round_robin`). - round_robin_made: AtomicU64, - /// The presenting queues made so far on the reserved `VkQueue`s: the next one takes the - /// reserved queue this modulo their number. - presenting_made: AtomicU64, - /// Where the device's queue limits changed its queues (`DeviceOptions::queue_limits`), the - /// queue plan's round robin and presenting `VkQueue`s: what the device's notes of the limits - /// compare with (`Device::next_queue`). - planned: Option<(usize, usize)>, - /// The driver refused the device with its queue plan's `VkQueue`s, and it took its least - /// plan's: the reason a presenting queue shares one (`Device::place_queue`). - pub(super) least_plan: bool, - /// The presenting queues made so far, on a reserved `VkQueue` or not, counted only where - /// `planned` is. - presenting_asked: AtomicU64, - /// The program's command queues made round robin so far, unshared ones among them, counted - /// only where `planned` is: the runtime's own are not. - program_queues_made: AtomicU64, - /// The program's command queues live on this generation, of every kind - /// (`WorkCounts::command_queues_live_most`). - pub(crate) program_queues_live: AtomicU64, - /// Whether its command queues share `VkQueue`s, and its check's verdict - /// (`queue_share.rs`). Shared with the check's thread, which holds no device handle - /// (`queue_switch_check.rs`). - pub(crate) queue_switch: Arc, - /// What the compile device's profile takes of viewport depth ranges past `[0, 1]`, which draws read - /// (`render_state::native_depth_range`). - pub(super) depth_ranges: DepthRanges, - /// What every generation of its line answers alike, its own copy: a generation handle reads - /// it here, at one hop as it reads the rest (`line.rs`). - invariant: line::Invariant, - /// The kinds of degradation the device announced (`degradation.rs`): its line's, so a kind is - /// announced once across its recoveries (`line.rs`). - pub(super) announced: Arc, - /// The kinds that refuse a render encoder's call met while lowering it after it returned - /// (`DeviceOptions::lowering_refuses`, `render/deferral.rs`). - lowering_refuses: BTreeSet, - /// Its render encoders whose calls are logged, lowered before a read of what their lowering - /// leaves (`render/deferral.rs`). - pub(crate) deferred: crate::render::DeferredEncoders, - /// Buffers carry Vulkan device addresses (`bufferDeviceAddress` is enabled). - pub(super) device_address: bool, - /// The alignment of every upload (`upload.rs`): 16 bytes, and the device's storage and - /// uniform buffer offset alignments. - pub(super) upload_alignment: u64, - /// The most dynamic uniform and storage buffers a pipeline layout takes - /// (`maxDescriptorSetUniformBuffersDynamic`, `maxDescriptorSetStorageBuffersDynamic`), which - /// the set-0 bindings a variant makes dynamic stay within (`pipeline/objects.rs`). - pub(super) dynamic_buffers: [u32; 2], - /// Shared with the releases of freed memory posted to the handler threads, which hold - /// nothing of the device (`freed_memory.rs`). - pub(super) memory: Arc>, - /// The Metal address space, the line's: every generation's buffers take their addresses from - /// it, so none made after a recovery takes one an object made before holds (`line.rs`). - pub(super) addresses: Arc>, - /// Parked buffers of the runtime's own memory, and the makings of the live recyclable ones - /// (`recycle.rs`). - pub(super) recycled_buffers: Arc>>, - /// The resource IDs of textures and sampler states (`resource_ids.rs`). - pub(super) resource_ids: Arc>, - /// The runtime's passing holds of the program's textures and sampler states, which a - /// program's making waits out before it takes its ID (`resource_ids.rs`): the line's, as the - /// IDs are. - pub(super) passing_holds: Arc, - /// The buffers whose records the GPU may write, which keep the programs of the pipeline - /// states the program releases (`released_programs.rs`). - pub(super) keepers: Keepers, - /// The `uniqueIdentifier`s the device allocates from 2^36 (`unique_identifier.rs`). - pub(super) identifiers: Arc, - /// How many holders hold a sampler ID now and the sampler pool's size (`resource_ids.rs`), - /// read without the IDs' lock ([`Device::sampler_ids_live`], - /// [`Device::sampler_id_pool_size`]). - pub(super) sampler_ids: SamplerIdReads, - /// The live sampler states, by what decides whether a request shares one (`sampler.rs`): - /// an equal request gets the live state, as Metal's does. - pub(super) samplers: Mutex, - /// The device's live Vulkan samplers, held to `maxSamplerAllocationCount` - /// (`DeviceShared::create_sampler`). - pub(super) sampler_count: SamplerCount, - /// The device's live `VkDeviceMemory` allocations, held to `maxMemoryAllocationCount` - /// (`allocations.rs`). - pub(crate) allocations: crate::allocations::Registered, - /// The thread the blocks of its memory that go are freed on (`free_thread.rs`). - pub(crate) frees: Arc, - /// The immutable sampler sets of the variants' layouts, by their samplers - /// (`pipeline/objects.rs`, `pipeline/content_keyed.rs`). - pub(crate) sampler_sets: Mutex, - /// The heap sets and the texture table every command buffer shares (`heap_sets.rs`). Its - /// lock is taken before `resource_ids`', never under it. - pub(super) heaps: Mutex, - /// The live visible-function tables, by resource ID: an argument buffer can name each, for - /// a dispatch of the state that made it (`function_table.rs`). - pub(super) function_tables: Mutex>>, - internal: Mutex>, - /// The internal submissions' timeline as the host saw it complete (`submit.rs`). - internal_done: OwnTimeline, - /// Each batch with work makes what completed work wrote visible by a command buffer of - /// barriers that starts it, and waits for no timeline the host saw complete: the driver's - /// submissions stall on semaphore operations (`DriverFact::SemaphoreOperationsStallSubmits`, - /// `command_buffer/submit.rs`). - pub(super) completed_by_barrier: bool, - /// Each batch ends with `Barrier::to_all`, so a later batch of its `VkQueue` plans no barrier - /// for its accesses, and holds a later batch's start timestamp, at the top of the pipe, until - /// it ended (`batch_order.rs`). - pub(crate) by_ends: bool, - /// The last sparse binding of a no-copy buffer's dma-bufs (`dma_buf.rs`) the host has not - /// seen complete: the internal timeline and the value it signals, which every later - /// submission that may use the buffer waits for (`submit.rs`). - bound_at: Mutex>, - /// The queue reserved for staging copies, where the device has one (`staging.rs`). - staging: Option, - /// The queue reserved for fills, where the device has one (`staging.rs`). - fill_queue: Option, - /// The caller's extra queues (`DeviceOptions::extra_queues`), to which the runtime never - /// submits (`handles.rs`). - pub(super) extra_queues: Vec, - /// The queues of its own families reserved for the caller (`DeviceOptions::reserved_queues`), - /// outside `queues`: the runtime never submits to them (`handles.rs`). - pub(super) reserved_queues: Vec, - pub(super) scheduler: Scheduler, - /// The scheduler's nudge, a timeline semaphore its wakers signal where its thread waits for - /// the GPU (`scheduler/mod.rs`): made on every device, used where the driver's wait for any - /// of several semaphores loses no signal (not MoltenVK's). - nudge: vk::Semaphore, - pub(super) completion: Completion, - /// The idle fences the batches that end command buffers signal (`command_buffer/fences.rs`). - /// Shared with the queue-switch check's thread, whose uses of a queue take them where its - /// failures are relayed (`queue_switch_check.rs`). - pub(super) fences: Arc, - /// The queues' serial contexts: every command buffer's transitions and handlers run there, - /// and the releases handed off a thread that may run none of the program's code - /// ([`Device::let_go_elsewhere`]). - pub(super) contexts: Contexts, - /// Shared with the queue-switch check's thread, which allocates command buffers - /// (`queue_switch_check.rs`). - pub(super) loader_word: Arc, - /// The runtime created the `VkDevice` and destroys it. - owned: bool, - /// The device was lost: no further submission. Shared with the relay (`relay.rs`), which - /// records a loss it hears of. - lost: Arc, - /// The generation stopped and is parked, and why (`command_buffer/stall.rs`): no work of its - /// advanced while some was pending and a probe on another engine did not complete, or a - /// queue's front batch went past Metal's watchdog bound. It counts as lost (`lost` is set - /// too), and besides nothing waits for its queues and nothing of it is destroyed, the - /// `VkDevice` itself included (`release.rs`). - stopped: OnceLock, - pub(super) textures: super::texture::TextureState, - /// The translated-shader cache on disk and the driver's pipeline cache. - pub(super) shader_cache: ShaderCache, - /// Its check of the first move of an image over host pages, per class of pages, and its - /// verdicts (`in_place.rs`). - pub(crate) in_place: crate::in_place::InPlaceChecks, - /// Its check of what its linear images cost its GPU against its optimal ones, and its answer - /// (`tiling_check.rs`). - pub(crate) tiling: crate::tiling_check::TilingCheck, - /// Its checks of what its submissions cost (whether submissions that signal nothing merge, - /// and whether a held pointer import adds to each), and their verdicts (`submit_check.rs`). - pub(crate) submit_checks: Arc, - /// How no-copy buffers import host memory, or why they are refused. - pub(super) host_import: Result, - /// How it exports an exportable buffer's memory as an opaque file descriptor; `None` where - /// it enables no `VK_KHR_external_memory_fd` or exports no buffer's memory so - /// (`exported_memory.rs`). - #[cfg(unix)] - pub(super) opaque_fd: Option, - /// How it exports a dma-buf-exportable buffer's memory as a dma-buf; `None` where it enables - /// not the dma-buf route's extensions and `VK_EXT_queue_family_foreign`, or exports no - /// buffer's memory so (`exported_memory.rs`). - #[cfg(unix)] - pub(super) dma_buf_export: Option, - /// How it exports an exportable shared event's timeline semaphore as an opaque file - /// descriptor; `None` where it enables no `VK_KHR_external_semaphore_fd` or exports no - /// timeline semaphore so (`exported_semaphore.rs`). - #[cfg(unix)] - pub(super) opaque_fd_semaphores: Option, - /// How it exports a binary semaphore as a sync file, with the semaphores it keeps idle for its - /// command buffers' sync files; `None` where it enables no `VK_KHR_external_semaphore_fd` or - /// exports no binary semaphore so (`exported_semaphore.rs`, `command_buffer/sync_file.rs`). - #[cfg(unix)] - pub(super) sync_fd_semaphores: Option, - /// Whether the device imports a pointer to shared memory, once asked - /// (`Device::imports_shared_host_pointers`). - pub(super) shared_pointer_imports: OnceLock, - /// The commands of a render pipeline's extended dynamic states, where the device has them - /// (`dynamic_state.rs`). - pub(super) extended_dynamic_state: Option, - /// The command that binds an index buffer range of a size, where the device enabled - /// `maintenance5` (`draw_source.rs`). - pub(super) sized_index_bind: Option, - /// The mesh draw commands, where the device enabled `meshShader` (`render/mesh.rs`). - pub(super) mesh_draws: Option, - /// The multi-draw commands a rate-mapped pass's draw records its regions with several at a - /// time, where the device enabled `multiDraw`, `multiViewport`, `shaderOutputViewportIndex` - /// and `shaderDrawParameters` and one command may draw at least two regions - /// (`rate_mapped_pass.rs`). - pub(super) multi_draws: Option, - /// The indirect-count draw commands a draw the GPU routes records its routes with, where the - /// device enabled `drawIndirectCount` and `multiDrawIndirect` (`render/gpu_routes.rs`). - pub(super) count_draws: Option, - /// `vkCmdPushDescriptorSet`, from Vulkan 1.4 or `VK_KHR_push_descriptor` - /// (`binding::push_set`). Where the driver has `RuntimeDriverDefect::PushedBufferSizesUnset` - /// only the variants `pipeline::objects::pushes_set_zero` names push with it there, and no - /// runtime kernel (`OwnedKernel::pushed`). - pub(super) push_descriptor: Option, - /// A draw after a pipeline bind pushes at least one of set 0's descriptors, the first where - /// none changed (`render/bound.rs`), where the driver has - /// `RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds`. - pub(super) pushes_after_pipeline_binds: bool, - /// The command that sets a draw's color write masks, where the device enabled everything a - /// draw that reads its own pass's texture through a snapshot takes (`render/snapshot.rs`). - pub(super) color_write_masks: Option, - /// The device's slot among those its commands go through (`recorder`), where it took one: - /// let go of after `vkDestroyDevice` (it drops after the teardown, `Drop`). Its counts are - /// `WorkCounts::commands_recorded`. - recording: Option, - /// The reasons a draw that reads its pass's texture took the split that the device said - /// already, each with the clauses that left its slots out where it is - /// `SplitReason::UnreadableOwnPixel`, where `METAL2VULKAN_LOG_PIPELINES` is set - /// (`render/snapshot.rs`). - pub(super) snapshot_fallbacks: - Mutex>, - /// The draws the area rule weighed, by size, where `METAL2VULKAN_LOG_PIPELINES` is set - /// (`render/snapshot.rs`, `reader_sizes.rs`). - pub(super) reader_sizes: Mutex, - /// The command buffers' index and mesh records pools: their bytes and spare blocks - /// (`gpu_pools.rs`). - pub(super) gpu_pools: GpuPools, - /// The most bytes of images each command queue keeps for its heaps' multisample textures' - /// moves: a sixty-fourth of the largest device-local heap, as a GPU pool's - /// (`texture/copy_images.rs`, `gpu_pools::device_share`). - pub(super) copy_images_bytes: u64, - /// The largest framebuffer: `maxFramebufferWidth`, `maxFramebufferHeight` and - /// `maxFramebufferLayers` (`render_pass.rs`). - pub(super) max_framebuffer: [u32; 3], - /// The viewport limits a rate-mapped pass's regions keep within: `maxViewportDimensions` and - /// `viewportBoundsRange` (`rate_mapped_pass.rs`). - pub(super) region_limits: RegionLimits, - /// Whether the device rasterizes at Vulkan's standard sample locations - /// (`standardSampleLocations`), which a rate-mapped pass's boxes of regions rest on - /// (`render/fan_out.rs`, **Region-copy variant**). - pub(super) standard_sample_locations: bool, - /// Whether a rasterization-rate map of one or more layers was released (`rate_map.rs`): a - /// map of no layers made after it is one Metal may draw from the released map's memory. - pub(super) layered_rate_map_released: AtomicBool, - /// Whether a command buffer holding a render pass with a draw call over a `Mutable` - /// rasterization-rate map was committed (`rate_mapped_pass.rs`): before one, Metal's GPU hangs - /// at a pass of no draw call over such a map. - pub(super) mutable_rate_map_called: AtomicBool, - /// Whether the runtime made a sparse image on the device: the driver's first sparse resource - /// may wait for every queue's work (`DriverFact::FirstSparseResourceWaitsForQueues`). - pub(super) sparse_image_made: AtomicBool, - /// How much GPU work of the program's own the device has been given: every commit of a command - /// buffer raises it, and so does the program's own use of a `VkQueue` - /// (`CommandQueue::with_vk_queue`). A texture's host shadow holds the image's texels only - /// while it stands where it stood when the shadow was read (`texture/host_shadow.rs`): a - /// commit is the only way a command of the program's reaches the device, so this one count - /// stands for every route its GPU work could write a texture by. - gpu_work: AtomicU64, - /// Whether the device takes a set-0 buffer binding whose entry point uses it through more - /// than one variable as a **dynamic** descriptor, asked of the device the first time a - /// variant has such a binding and kept for its lifetime - /// (`pipeline::objects::takes_multi_variable_dynamic`). `None` until then, and on a device no - /// variant has asked. - pub(super) dynamic_multi_variable: OnceLock, - /// The crate-owned compute kernels the runtime dispatches for itself, made on first use - /// (`owned_kernel.rs`). - pub(super) owned_kernels: Mutex, - /// A pass's first draw the GPU routes began the routes' kernel on the device's pool - /// (`Device::begin_route_counts_kernel`): no later draw begins it again. - pub(super) route_counts_begun: AtomicBool, - /// The two-plane YCbCr formats the device converts itself (`ycbcr_device.rs`). - pub(super) ycbcr_formats: crate::ycbcr_device::YCbCrFormats, - /// The spare scratch block of `generate_mipmaps`' filter chains (`mipmap_scratch.rs`). - pub(super) mipmap_scratch: Mutex, - /// The sample planes' copy kernels and merge pipelines, made on first use - /// (`sample_planes.rs`). - pub(super) planes: Mutex, - /// The buffer<->multisampled-texture copy's interleave kernels and merge pipelines, made on - /// first use (`sample_interleave.rs`). - pub(super) interleave: Mutex, - /// Released variants' objects and `VkPipeline`s, kept for a state made again - /// (`pipeline/kept.rs`). - pub(super) kept: Mutex, - /// The region `VkPipeline`s its compute variants keep, a released variant's kept instance - /// included, under one bound (`pipeline/region_ledger.rs`). - pub(super) region_ledger: Arc, - /// The variants' shader modules by their exact SPIR-V, shared device-wide - /// (`pipeline/content_keyed.rs`). - pub(super) shader_modules: Mutex, - /// The compiled pipelines' stage words' digests, kept past their variants - /// (`pipeline/objects.rs`, `WordsDigests`). - pub(super) words_digests: Mutex, - /// The variants' pipeline layouts by their exact definition, shared device-wide - /// (`pipeline/shared_layouts.rs`). - pub(crate) pipeline_layouts: Mutex, - /// The variants' makings in the air, by their compile, which a twin's waits for to land - /// (`pipeline/flight.rs`). - pub(crate) flights: crate::pipeline::flight::Flights, - /// The exact color resolve's pipelines and passes, made on first use (`color_resolve.rs`). - pub(super) color_resolves: Mutex, - /// The multisampled stencil's copies without colour copies: the split kernel and the plane - /// draws, made on first use (`stencil_copy.rs`). - pub(super) stencil_copies: Mutex, - /// The multisampled depth's copies without colour copies: the draw's shaders and pipelines, - /// made on first use (`depth_copy.rs`). - pub(super) depth_copies: Mutex, - /// The stencil resolves picked by depth: the draws' shaders and pipelines, made on first use - /// (`depth_stencil_resolve.rs`). - pub(super) depth_stencil_resolves: Mutex, - /// The render passes of its passes without attachments, one per sample count, made on first - /// use (`attachmentless.rs`). - pub(super) attachmentless: Mutex, - /// The render passes it keeps: compatible ones and those instances begin, by what each is - /// made of (`render_target::KeptRenderPasses`). - pub(super) render_passes: Mutex, - /// The caller's images that move between layouts, and the events' timeline semaphores - /// (`interop.rs`). - pub(super) interop: Interop, - /// Its heaps with bytes of their own, by the key their resources' uses name (`heap.rs`). - pub(super) heap_keys: super::heap::HeapKeys, - /// The buffers over host pages, and the holds of uncommitted command buffers on them. - pub(super) rebinds: super::rebind::Rebinds, - /// The no-copy buffers by the host memory they were made over (`host_aliases.rs`). - pub(super) aliases: super::host_aliases::HostAliases, - /// The guest RAMs it uses, and their chunks it imported (`host_ram.rs`). - pub(crate) host_ram: super::host_ram::RamSource, - /// Its copied host buffers, compared at each commit and each batch's completion - /// (`copied.rs`). - pub(crate) copied: Arc, - /// The ranges of buffers with a host copy the CPU named since the last commit, which the next - /// commit copies in (`managed.rs`). - pub(crate) modified: super::managed::Modified, - /// The GPU's writes to buffers with a host copy since their last copy out, which decide the - /// next copy out of each (`managed_sync.rs`). - pub(super) gpu_writes: super::managed_sync::GpuWrites, - /// How many of the next imports of host pages by their pointer fail as the driver's out of - /// device memory: for the tests of `copied.rs` (`Device::fail_next_host_imports`). - #[cfg(test)] - pub(crate) failing_host_imports: std::sync::atomic::AtomicU64, - /// How many of the next `vkQueueSubmit`s of its command buffers' work fail, never made: for - /// the device tests of a failed submission (`Device::fail_next_submissions`). - #[cfg(test)] - pub(crate) failing_submissions: std::sync::atomic::AtomicU64, - /// The `VkResult` they fail with: the driver's out of device memory where 0 - /// (`Device::fail_next_submissions_with`). - #[cfg(test)] - pub(crate) failing_result: std::sync::atomic::AtomicI32, - /// How long each `vkQueueSubmit` of a batch of command buffers takes more, in nanoseconds, - /// slept inside its timed call: the device tests' stand-in for a driver whose calls of - /// commands are slow (`Device::slow_submit_calls`). - #[cfg(test)] - pub(crate) submit_call_pause: AtomicU64, - /// Of those calls, each how manyth is not lengthened, and those counted since it was set: the - /// device tests' stand-in for a short call of commands among slow ones - /// (`Device::fast_submit_call_every`); 0 for none. - #[cfg(test)] - pub(crate) submit_call_fast: (AtomicU64, AtomicU64), - /// The submission cost at or above which a committing thread leaves a `VkQueue`'s batches to - /// the scheduler's thread, where a device test set one (`Device::leave_calls_from`); 0 for - /// `submit_calls::SLOW_NANOS`. - #[cfg(test)] - pub(crate) slow_calls_from: AtomicU64, - /// Every linear image of a render target renders as a color attachment only under - /// `VK_NV_linear_color_attachment`'s rule, whatever the device's facts: for the tests of - /// `merge_scratch.rs` on a device that renders one beside any other - /// (`linear_attachment::bound`). - #[cfg(test)] - pub(crate) linear_rule_forced: AtomicBool, - /// Its encoders split at aliases as on a device whose driver has - /// `DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`, whatever its facts: for the - /// tests of `tests/render_fold.rs` on a device without it (`splits_at_aliases`). - #[cfg(test)] - pub(crate) aliases_split_forced: AtomicBool, - /// No linear image takes feedback loop usage (`texture::linear_feedback_candidate`), as - /// NVIDIA's drivers make none with it: for the tests of `tests/leading_snapshots.rs` on a - /// device that makes them so, whose readers then take leading snapshots - /// (`render/snapshot.rs`). - #[cfg(test)] - pub(crate) linear_feedback_withheld: AtomicBool, - /// No draw takes leading snapshots (`render/snapshot.rs`): its reader splits the pass and - /// reads the split's copy, as on a device without `VK_ATTACHMENT_STORE_OP_NONE`, for the - /// tests of `tests/leading_snapshots.rs` that compare the two. - #[cfg(test)] - pub(crate) leading_snapshots_withheld: AtomicBool, - /// `STORAGE` costs every image whose plan lacks it something (`Device::if_free`), whatever - /// the device lays out: for the tests of `tests/self_read_storage.rs` on a device that gives a - /// render target `STORAGE` for nothing. - #[cfg(test)] - pub(crate) storage_costs_forced: AtomicBool, - /// `SAMPLED` costs every image whose plan lacks it something (`Device::if_free`), whatever - /// the device lays out: for the test of `tests/surface_depth_usage_shadow.rs`, whose texture's - /// shadow then lacks it and is sampled through a usage shadow. - #[cfg(test)] - pub(crate) sampled_costs_forced: AtomicBool, - /// The most bytes of a range `did_modify_range` names that is written inline - /// (`managed::inline_bound`): `managed::INLINE_BYTES`, but where a test sets another (0: none - /// is), for the tests and the bench of `tests/managed_inline.rs`. - #[cfg(test)] - pub(crate) managed_inline_bound: std::sync::atomic::AtomicU64, - /// A batch's first work of uploads alone takes no barrier from the commands before it on any - /// device, its batches ordered by their ends or not (`first_move::Earlier::Ended`): the - /// negative control of `tests/managed_inline.rs`'s write-after-read test, under the exact - /// batch order. - #[cfg(test)] - pub(crate) uploads_unbarriered_forced: AtomicBool, - /// The second scopes of the barriers that made batches' uploads visible to their own uses - /// alone (`first_move::Later::Batch`), in the order recorded: for the test of - /// `tests/managed_inline.rs` that the scope names every stage its batch uses the buffer in. - #[cfg(test)] - pub(crate) upload_scopes: Mutex>, - /// Its encoders record a command that writes a read twin, which they refuse otherwise: the - /// negative control of the tests of `tests/read_twin_device.rs` (`read_twin::refuses_writes`). - #[cfg(test)] - pub(crate) read_twin_unguarded: AtomicBool, - /// Its commands bind a read twin at a slot they may write, which they never do otherwise: the - /// negative control of the slots' proof in `tests/read_twin_device.rs` - /// (`read_twin::binds_unproven`). - #[cfg(test)] - pub(crate) read_twin_unproven: AtomicBool, - /// Its passes storing out into memory whose GPU writes are dropped complete, which fault - /// their command buffers otherwise: the negative control of the tests of - /// `tests/store_out_device.rs` (`store_out::faults`). - #[cfg(test)] - pub(crate) store_out_unfaulted: AtomicBool, - /// The route a test takes for images over dma-buf pages, whatever the driver answers of an - /// explicit plane's offset (`dma_buf.rs`'s `PlaneRoute`, as its `u8`): for the tests of - /// `tests/dma_buf_plane_offset.rs` on a driver that answers the offset asked. - #[cfg(all(test, unix))] - pub(crate) plane_route_forced: std::sync::atomic::AtomicU8, - /// The device takes its driver for one whose shaders read an explicit - /// `DRM_FORMAT_MOD_LINEAR` plane's rows at another pitch where they lie a number of bytes - /// apart that is no multiple of 32 (`RuntimeDriverDefect::ExplicitPlanePitchMisread`, - /// `Device::explicit_plane_pitch`): for the tests of `tests/read_twin_device.rs` on a driver - /// that reads them right. - #[cfg(all(test, unix))] - pub(crate) explicit_plane_pitch_misread_forced: AtomicBool, - /// Where not 0, no image lies in place over host pages or a copy of them whose rows are not - /// that many bytes apart or whose texels do not start at that many bytes' multiple in their - /// buffer, whatever the driver answers (`Device::unplaced`): RADV's rule for a - /// `DRM_FORMAT_MOD_LINEAR` plane (256 on GFX9 to GFX11), for the tests of - /// `tests/read_twin_device.rs` on a driver that lays such rows in place. - #[cfg(test)] - pub(crate) linear_pitch_rule_forced: AtomicU64, - /// Made with the runtime tests' default queue limits (`create::TEST_QUEUE_LIMITS`), whose - /// test then fails where its work needs more (`create::needs_the_queue_plan`). - #[cfg(test)] - pub(crate) test_queue_limits: AtomicBool, - /// The logs of its shadows over host pages a consumer logs the writes to - /// (`dirty_pages.rs`). - pub(super) dirty: super::dirty_pages::DirtyShadows, - /// The writes that let go of its shadows' standings across command buffers - /// (`shadow_standing.rs`). - pub(super) standings: super::shadow_standing::Standings, - /// The new textures that read zero where Metal reads its pattern, until a command observes - /// or covers that (`fresh_unwritten.rs`). - pub(super) fresh: super::fresh_unwritten::FreshUnwritten, - /// The program's resources by key, with what owns their memory (`used_resources.rs`). - pub(super) owners: super::used_resources::Owners, - /// The program's live buffers of their own, and their resident set (`live_buffers.rs`). - pub(super) live_buffers: super::live_buffers::LiveBuffers, - /// What its recovery carries to the next generation, and what it lets go of once nothing - /// records on it (`carry.rs`). - pub(crate) carry: carry::Carry, - /// The imports of the caller's dma-bufs it releases while idle, and the thread that releases - /// them (`host_residency.rs`). - pub(super) residency: super::host_residency::Sweeper, - /// Its one import of each dma-buf a caller's source shares among the chunks of several - /// buffers and heaps, by the file's identity (`dma_buf.rs`'s `DmaBufFiles`). - #[cfg(unix)] - pub(super) dma_buf_files: super::dma_buf::DmaBufFiles, - /// What lets go of its kept empty memory blocks and parked objects once their time passed, - /// whether or not the program makes anything more, and its thread (`idle_sweep.rs`). - pub(super) idle_sweep: crate::idle_sweep::IdleSweep, - /// The thread its settled spare command pools' primaries are begun ahead on - /// (`begin_ahead.rs`). - pub(crate) begin_ahead: crate::begin_ahead::BeginAhead, - /// How its command buffers are timed on the GPU (`gpu_time.rs`). - pub(super) timing: Timing, - /// Its Vulkan views may present an image in another component layout: it has no portability - /// subset, or the subset's `imageViewFormatReinterpretation` is enabled, by the runtime on a - /// device it made or, on an adopted one, by the consumer, who says so - /// (`RawDevice::view_format_reinterpretation`; `view_plan.rs`), and a made device's options - /// do not withhold such views (`DeviceOptions::withhold_view_reinterpretation`). Where not, - /// Metal's views of another layout are shadowed (`texture/view_shadow.rs`). - pub(super) view_reinterpretation: bool, - /// `VK_EXT_device_generated_commands`'s commands, where the runtime enabled the extension - /// (`create.rs`): an execution of commands a kernel writes runs on the GPU alone through - /// them where every record it may hold is covered and the product sets their path up for its - /// variants (`generated_execute.rs`), and by indirect dispatches elsewhere (`gpu_execute.rs`). - pub(super) generated_commands: Option, - /// The device enabled `hostImageCopy`: the runtime on a device it creates that has it - /// (`create.rs`), the consumer on one it adopts that says so (`adopt.rs`). A heap's colour - /// texture takes host-transfer usage on a driver that serves it (`texture/heap.rs`). - pub(super) host_image_copy: bool, - /// The host image copy functions, where the device enabled `hostImageCopy` and copies on the - /// host to and from images in `GENERAL`: a new `Shared` or `Managed` texture's image is - /// moved and zeroed on the host, and its CPU copies run there (`texture/host_copy.rs`). - pub(super) host_copies: Option, - /// The device enabled `zeroInitializeDeviceMemory` (`create.rs`): memory it allocates with - /// `VK_MEMORY_ALLOCATE_ZERO_INITIALIZE_BIT_EXT` reads zero, and an image made in such memory - /// starts in `VK_IMAGE_LAYOUT_ZERO_INITIALIZED_EXT` (`texture/host_copy.rs`). - pub(super) zero_initialize_device_memory: bool, - /// What it has of sparse binding and residency (`sparse/device.rs`). - pub(super) sparse: SparseDevice, - /// The command pools and descriptor pools command buffers that completed gave back, for the - /// next to take (`spares.rs`). - pub(super) spares: Spares, - /// The bind states its ended render encoders left, which the next ones start from - /// (`live_bind.rs`). - pub(super) live_binds: crate::live_bind::SpareLiveBinds, - /// The occlusion query pools no render pass holds, which a pass that measures what its - /// readers cover takes (`render/coverage.rs`). - pub(super) coverage_pools: crate::render::coverage::SparePools, - /// The bind states its ended compute encoders left, which the next ones start from - /// (`compute/live.rs`). - pub(super) live_dispatches: crate::compute::SpareLiveDispatches, - /// The states its released command buffers left, reset, which the next ones take - /// (`command_buffer/spare_states.rs`). - pub(super) spare_states: crate::command_buffer::spare_states::SpareStates, - /// The usage shadows its textures made (`texture/usage_shadow.rs`): a kept list of resident - /// textures' shadows is listed again where it moved (`shadow::ResidentShadows`). - pub(super) usage_shadows_made: std::sync::atomic::AtomicU64, - /// Its textures' turns between their faces whose passes may not have run, and the flag a - /// turn raises (`texture/faces.rs`). - pub(crate) face_swaps: crate::texture::faces::FaceSwaps, - /// One past the highest resource ID a texture is placed at in its heap sets, 0 for none, - /// stored under `heaps` as it changes and read without it (`heap_sets::TextureTableAt`). - pub(super) heap_textures_end: std::sync::atomic::AtomicU64, - /// The bind memos its ended render encoders left, which the next ones take (`binding.rs`). - pub(super) bind_memos: crate::binding::SpareBindMemos, - /// The boxes of its ended render encoders' cores, emptied, which the next ones take - /// (`encoder::SpareCores`). - pub(super) cores: crate::encoder::SpareCores, - /// The rooms its ended render encoders' draws gathered into, which the next ones take - /// (`render/draw_room.rs`). - pub(super) draw_rooms: crate::render::SpareDrawRooms, - /// The rooms of the draws its render encoders kept for instances recorded inline after a - /// split, which the next such instances take (`render/inline_splits.rs`). - pub(super) kept_rooms: crate::render::SpareKept, - /// Counts of its commit path's work, for the lanes (`work_counts.rs`). Shared with the - /// queue-switch check's thread (`queue_switch_check.rs`) and the begin-ahead thread - /// (`begin_ahead.rs`). - pub(super) counts: Arc, - /// Its uses of its `VkQueue`s seen as one, which its blocks made ahead wait on for a moment - /// right after a burst of submissions (`queue_quiet.rs`, `memory/ready.rs`). Shared with - /// each of its queues' slots. - pub(crate) queue_quiet: Arc, - /// Where the driver fails pending work as memory a device-address buffer lay in is freed, - /// the record of its batches the memory's blocks that go wait by (`freed_memory.rs`). - pub(crate) parking: OnceLock>, - /// Its command buffers made and not committed, over all its queues (`queue.rs`). - pub(super) uncommitted: Arc, - /// The threads that make `VkPipeline`s ahead of the draws that record them - /// (`pipeline/pool.rs`). - pub(super) pipeline_pool: crate::pipeline::pool::Pool, - /// The thread that lets go of what a released state's pool pieces gave back as they ended - /// (`pipeline/reaper.rs`). - pub(super) reaper: Arc, - /// The trails its threads open between a signal and their last let-go of what they held for - /// the work, which a command buffer's waiters wait for (`trails.rs`). - pub(crate) trails: Arc, - /// Its GPU's recoveries from faults and hangs, which end a predicated loop running meanwhile - /// (`command_buffer/recovery.rs`). - pub(crate) recoveries: Arc, - /// Its graphics pipeline libraries, by part and content, where it links its render - /// pipelines from libraries (`pipeline/libraries.rs`, `create.rs`); `None` where it makes - /// each whole. - pub(crate) libraries: Option, - /// Its command buffers keep execution records (`DeviceOptions::record_executions`): where - /// not, its encoders build none (`EncoderCore::executed`). - pub(crate) record_executions: bool, - /// Its encoder trail is on (`DeviceOptions::encoder_trail`, or `METAL2VULKAN_ENCODER_TRAIL` - /// set; `encoder_trail.rs`): each encoder goes in a submission of its own, and a stall's line - /// names the encoder each stuck queue holds. - pub(crate) encoder_trail: bool, - /// Its driver's image uses miss a write through a buffer over their memory recorded before - /// them in the same `VkCommandBuffer` - /// (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`): its encoders record such a - /// use in a new one (`alias_split.rs`). Read through - /// [`splits_at_aliases`](Self::splits_at_aliases). - driver_splits_at_aliases: bool, - /// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`, - /// `dynamic_library.rs`). - pub(crate) load_no_dynamic_library_file: bool, - /// Counts the times an image of the device let its views go, under its views lock (a - /// rebind's or a storage form's new `VkImage`, a detach's stand-in, a reattach, a shadow's - /// move in place, whose views go after it): a view kept by what it was made of - /// (`binding::BindMemo`) is current while this holds. - pub(crate) views_epoch: AtomicU64, - /// Its pipeline records: the hook they go to, and the counts (`warm/record.rs`). - pub(crate) pipeline_recording: crate::warm::Recording, - /// Its warm calls: the records queued, its warm thread, and the counts (`warm/pass.rs`). - pub(crate) warmer: crate::warm::Warmer, - /// The registry of the runtime's own holds of the device, which its handles share - /// (`holds.rs`). - pub(crate) holds: Arc, -} - -impl DeviceShared { - /// Wait each of the device's queues idle, each under its lock, as every use of a queue is - /// made: a thread of the device's may submit meanwhile (its submission checks, - /// `submit_check.rs`), where `vkDeviceWaitIdle` would need every queue externally - /// synchronized (vkspec 7.8, "Host access to all VkQueue objects created from device that are - /// not created with VK_DEVICE_QUEUE_CREATE_INTERNALLY_SYNCHRONIZED_BIT_KHR must be externally - /// synchronized"). A wait on a lost device returns in finite time (vkspec 5.2.3). Called - /// inside a section of the exit guard. - pub(super) fn queues_idle(&self) { - // A parked generation's work never ends: a wait for its queues would never return. - if self.wedged() { - return; - } - let raw = self.vk(); - for slot in self.queues.iter() { - // SAFETY: the queue is the device's, used under its lock, inside a section. Its - // answer is not needed: the device is lost, or the work it waited for ended. - let _ = slot.with(|queue| unsafe { raw.queue_wait_idle(queue) }); - exit_guard::called(Call::QueueWaitIdle); - } - } - - /// Whether a committing thread leaves the batches of `VkQueue` `queue` to the scheduler's - /// thread: its batches' last submissions took `submit_calls::SLOW_NANOS` or more at their - /// median, as timed (`submit_calls.rs`). - pub(crate) fn submits_slowly(&self, queue: usize) -> bool { - let bound = submit_calls::SLOW_NANOS; - #[cfg(test)] - let bound = match self.slow_calls_from.load(Ordering::Relaxed) { - 0 => bound, - set => set, - }; - self.queues[queue].calls.slow(bound) - } - - /// How long the device's work has been quiet, for a step of its view check that the work - /// must never wait on (`view_check.rs`): `None` while a batch committed waits for its - /// submission, a batch submitted is not seen complete on its `VkQueue`, or a use of one of - /// its `VkQueue`s is under way; else the time since the last such use ended - /// (`queue_quiet.rs`). - pub(crate) fn work_quiet_for(&self) -> Option { - quiet_for( - &self.queues, - || self.scheduler.holds_none(), - &self.queue_quiet, - ) - } - - /// Whether a batch submitted to one of the device's `VkQueue`s is not seen complete there. - pub(crate) fn batch_in_flight(&self) -> bool { - in_flight(&self.queues) - } - - /// A share of what tells whether its work is quiet, for a thread that holds no device - /// (`submit_check.rs`). - pub(crate) fn work_share(&self) -> WorkShare { - WorkShare { - queues: Arc::clone(&self.queues), - holds: self.scheduler.holds_share(), - uses: Arc::clone(&self.queue_quiet), - } - } -} - -/// What tells whether a device's work is quiet ([`DeviceShared::work_quiet_for`]), shared with a -/// thread that holds no device: its `VkQueue`s, the scheduler's holds and its queue uses. -pub(crate) struct WorkShare { - queues: Arc<[QueueSlot]>, - holds: crate::scheduler::HoldsShare, - uses: Arc, -} - -impl WorkShare { - /// [`DeviceShared::work_quiet_for`]. - pub(crate) fn quiet_for(&self) -> Option { - quiet_for(&self.queues, || self.holds.holds_none(), &self.uses) - } -} - -/// Whether a batch submitted to one of `queues` is not seen complete there. -fn in_flight(queues: &[QueueSlot]) -> bool { - (queues.iter()).any(|slot| slot.completed_value() < slot.submitted_value()) -} - -/// How long the work of a device of `queues`, whose scheduler holds none of it where `holds_none` -/// and whose queue uses are `uses`, has been quiet ([`DeviceShared::work_quiet_for`]). -fn quiet_for( - queues: &[QueueSlot], - holds_none: impl FnOnce() -> bool, - uses: &queue_quiet::QueueQuiet, -) -> Option { - if in_flight(queues) || !holds_none() { - return None; - } - uses.unused_for() -} - -impl DeviceShared { - /// Whether its encoders record a use of an image after a write through a buffer over its - /// memory in a new `VkCommandBuffer` (`alias_split.rs`): where its driver's image uses miss - /// such writes inside one (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`). - pub(crate) fn splits_at_aliases(&self) -> bool { - #[cfg(test)] - if self.aliases_split_forced.load(Ordering::Relaxed) { - return true; - } - self.driver_splits_at_aliases - } - - /// Whether the generation's `VkDevice` was lost. - pub(crate) fn lost(&self) -> bool { - self.lost.load(Ordering::Acquire) - } - - /// Whether the generation stopped and is parked (`command_buffer/stall.rs`): lost, its queues - /// never waited for, nothing of it destroyed. - pub(crate) fn wedged(&self) -> bool { - self.stopped.get().is_some() - } - - /// Why the generation stopped and is parked, where it did ([`wedged`](Self::wedged)). - pub(crate) fn stopped(&self) -> Option { - self.stopped.get().copied() - } - - /// Whether `kind`, met while lowering a render encoder's call after it returned, refuses the - /// call (`DeviceOptions::lowering_refuses`). - pub(crate) fn lowering_refuses(&self, kind: Degradation) -> bool { - self.lowering_refuses.contains(&kind) - } - - /// What `create` makes with the `VkPipelineCache` it is handed, its `vkCreate*Pipelines` call: - /// the device's cache of the record `making` names, seeded from that record - /// (`ShaderCache::make_pipelines`, `shader_cache/driver.rs`). `create` returns, with what it - /// made, whether the driver found its pipeline in the cache it was handed - /// (`shader_cache::found_in_cache`, `None` where it reports nothing). A making from its record - /// that the driver reports found reads no data back and writes nothing - /// (`shader_cache/driver.rs`). On a pool's thread the exit waits for it longer - /// (`exit_guard::driver_making`). `None`, `create` unrun, once the process's exit ended the - /// makings (`exit_guard::driver_making`). - pub(crate) fn make_pipelines_reported( - &self, - making: Making, - create: impl FnOnce(vk::PipelineCache) -> (Result, Option), - ) -> Option> { - // What every making is measured to report, withheld inside it (`driver_facts.rs`); a - // render pipeline's making expects them with its own. - let expected = crate::driver_facts::making_diagnostics(&self.invariant.properties); - crate::driver_facts::expecting_where_unset(expected, || { - crate::exit_guard::driver_making(|| { - self.shader_cache.make_pipelines(self.vk(), making, create) - }) - }) - } - - /// The words of the process's limit on large makings in flight that a making of `words` - /// SPIR-V words holds around its driver call (`pipeline/compile_memory.rs`): `None` where it - /// does not count. One that waited for them counts in - /// `WorkCounts::makings_held_for_compile_memory`, its wait in `compile_memory_held_nanos`. - /// Dropped after the call, it hands the free heap the compile left back where it is large - /// (`WorkCounts::heap_trims`). - pub(crate) fn compile_memory( - &self, - words: usize, - ) -> Option> { - let (held, waited) = crate::pipeline::compile_memory::hold(words)?; - if let Some(waited) = waited { - self.counts.making_held_for_compile_memory(waited); - } - Some(crate::pipeline::compile_memory::LargeMaking { - _words: held, - counts: &self.counts, - }) - } - - /// The compute pipeline of `info`, made as - /// [`make_pipelines_reported`](Self::make_pipelines_reported) makes one under the record - /// `making` names, with what its driver reports of it where the device's makings report - /// (`VK_EXT_pipeline_creation_feedback`, counted in `driver_pipeline_hits` and `misses`): one - /// found in a cache loaded from its record reads no data back and writes nothing, whatever - /// bytes the driver's data holds after it. A program's compute pipelines and the runtime's - /// own kernels, each named `name`'s answer ([`name_pipeline`](Self::name_pipeline)). - pub(crate) fn make_compute_pipeline( - &self, - making: Making, - name: impl FnOnce() -> String, - info: vk::ComputePipelineCreateInfo<'_>, - ) -> Result { - let reports = self.shader_cache.driver_reports(); - let mut whole = vk::PipelineCreationFeedback::default(); - let mut stage = [vk::PipelineCreationFeedback::default()]; - let made = self.make_pipelines_reported(making, |cache| { - let mut feedback = vk::PipelineCreationFeedbackCreateInfo::default() - .pipeline_creation_feedback(&mut whole) - .pipeline_stage_creation_feedbacks(&mut stage); - let mut info = info; - if reports { - info = info.push_next(&mut feedback); - } - // SAFETY: what `info` points to outlives it, and so the call; the cache is the - // device's of the record, or none. - let made = unsafe { self.vk().create_compute_pipelines(cache, &[info], None) }; - let found = reports.then(|| found_in_cache(&whole, &stage)).flatten(); - (made, found) - }); - let made = made.ok_or(DeadlockCause::Exiting)?; - let made = self.made_one(made, reports.then_some((&whole, &stage[..])))?; - self.name_pipeline(made, name); - Ok(made) - } - - /// The graphics pipeline, or graphics pipeline library, of `info`, made and reported as - /// [`make_compute_pipeline`](Self::make_compute_pipeline) makes a compute pipeline: a library - /// of shaders of a render pipeline linked from libraries (`pipeline/graphics.rs`), and the - /// runtime's own draws (its copies, resolves and planes steps). - pub(crate) fn make_graphics_pipeline( - &self, - making: Making, - name: impl FnOnce() -> String, - info: vk::GraphicsPipelineCreateInfo<'_>, - ) -> Result { - let reports = self.shader_cache.driver_reports(); - // Its stages' feedback where it has at most `REPORTED_STAGES`, none where more (a count of - // 0 is valid, one equal to `stageCount` else: - // VUID-VkGraphicsPipelineCreateInfo-pipelineStageCreationFeedbackCount-06594). - let mut whole = vk::PipelineCreationFeedback::default(); - let mut stages = [vk::PipelineCreationFeedback::default(); REPORTED_STAGES]; - let count = info.stage_count as usize; - let reported = if count <= REPORTED_STAGES { count } else { 0 }; - let made = self.make_pipelines_reported(making, |cache| { - let mut feedback = vk::PipelineCreationFeedbackCreateInfo::default() - .pipeline_creation_feedback(&mut whole) - .pipeline_stage_creation_feedbacks(&mut stages[..reported]); - let mut info = info; - if reports { - info = info.push_next(&mut feedback); - } - // SAFETY: as `make_compute_pipeline`'s. - let made = unsafe { self.vk().create_graphics_pipelines(cache, &[info], None) }; - let found = reports - .then(|| found_in_cache(&whole, &stages[..reported])) - .flatten(); - (made, found) - }); - let made = made.ok_or(DeadlockCause::Exiting)?; - let made = self.made_one(made, reports.then_some((&whole, &stages[..reported])))?; - self.name_pipeline(made, name); - Ok(made) - } - - /// The one pipeline a making `made`, with what its driver reported of it, `reported`, counted - /// where the making chained the reports and made it. - fn made_one( - &self, - made: Result, (Vec, vk::Result)>, - reported: Option<( - &vk::PipelineCreationFeedback, - &[vk::PipelineCreationFeedback], - )>, - ) -> Result { - let made = made.map_err(|(_, error)| vulkan(error))?; - if let Some((whole, stages)) = reported { - self.shader_cache.driver_reported(whole, stages); - } - made.first() - .copied() - .ok_or_else(|| internal("the driver made no pipeline")) - } - - /// The device's functions. The runtime's own threads reach them only inside a section of - /// the exit guard, or while they run the program's code, and a section reaches only the exit - /// guard's table of entry points; builds with debug assertions end the process otherwise - /// (`functions.rs`). - pub(crate) fn vk(&self) -> &Vk { - self.functions.get() - } - - /// The device's pending audit, where it is on (`pending_audit.rs`): read with no call of the - /// device's, on any thread; its checks read the device's timelines through [`vk`](Self::vk). - pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { - self.functions.pending_audit() - } - - /// Nanoseconds the device's pipeline makings spent inside its driver, graphics then compute - /// (`compiles.rs`, `WorkCounts::render_pipeline_create_nanos` and - /// `compute_pipeline_create_nanos`). - pub(super) fn pipeline_create_nanos(&self) -> (u64, u64) { - compiles::driver_nanos(self.vk().handle()) - } - - /// How much GPU work of the program's own the device has been given - /// ([`gpu_work`](Self::gpu_work) field): the count a texture's host shadow is read against - /// (`texture/host_shadow.rs`). - pub(crate) fn gpu_work(&self) -> u64 { - self.gpu_work.load(Ordering::Acquire) - } - - /// The program gave the device GPU work of its own: a command buffer's commit, or its own use - /// of a `VkQueue`. Called before the work can run, so a host shadow read after it is read - /// against the new count (`texture/host_shadow.rs`). - pub(crate) fn program_gave_gpu_work(&self) { - self.gpu_work.fetch_add(1, Ordering::AcqRel); - } - - /// A share of the device's functions, which holds nothing of the device: for the releases - /// posted to its handler threads, which its teardown waits for (`freed_memory.rs`). Reached - /// through [`Functions::get`] alone, as [`vk`](Self::vk) reaches them. - pub(crate) fn functions(&self) -> Arc { - Arc::clone(&self.functions) - } - - /// The commands recorded through its slot so far, by kind (`recorder`); none where it took - /// no slot. - pub(crate) fn commands_recorded(&self) -> crate::CommandsRecorded { - self.recording - .as_ref() - .map_or_else(Default::default, Slot::counts) - } - - /// The recorder's slot the device's commands go through, where it took one (`recorder`). - pub(crate) fn recording(&self) -> Option<&Slot> { - self.recording.as_ref() - } - - /// `vkAllocateCommandBuffers` of `info`: the loader serves it and reads the device's loader - /// word first ([`DeviceWord::restored`]). Counted by the place that asked, for the crate's - /// device tests (`Spares::churn`). - #[cfg_attr(test, track_caller)] - pub(super) fn allocate_command_buffers( - &self, - info: &vk::CommandBufferAllocateInfo<'_>, - ) -> Result, Error> { - let allocated = allocate_command_buffers(self.vk(), &self.loader_word, &self.counts, info); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - if allocated.is_ok() { - (self.spares).allocated(std::panic::Location::caller(), info.command_buffer_count); - } - allocated - } - - /// Name `pipeline`, just made and held by this thread alone, for the layers' messages: - /// `name`'s answer, asked only where the device's instance reports messages - /// (`Vk::object_name`), so a device without them works out no name. Every `VkPipeline` the - /// runtime makes is named: a program's by its Metal functions' names - /// (`VariantObjects::pipeline_name`), the runtime's own `metal2vulkan: ` and its kernel or - /// step. The loader serves the call and reads the device's loader word first - /// ([`DeviceWord::restored`]). An empty name, one holding NUL, or a failure to name it leaves - /// it unnamed: the name serves messages alone, and nothing the runtime does reads it. - pub(crate) fn name_pipeline(&self, pipeline: vk::Pipeline, name: impl FnOnce() -> String) { - let functions = self.vk(); - let Some(object_name) = functions.object_name() else { - return; - }; - let Ok(name) = std::ffi::CString::new(name()) else { - return; - }; - if name.is_empty() { - return; - } - let info = vk::DebugUtilsObjectNameInfoEXT::default() - .object_handle(pipeline) - .object_name(&name); - // SAFETY: the device is live and `pipeline` its own, which no other thread holds yet; the - // instance enables `VK_EXT_debug_utils` (it reports messages), and the function is the - // device's. - let _ = unsafe { - self.loader_word - .restored(|| object_name(functions.handle(), &info)) - }; - exit_guard::called(Call::SetDebugUtilsObjectName); - } - - /// How the device's buffers and images are shared among its queue families (`sharing.rs`). - pub(crate) fn sharing(&self) -> Sharing<'_> { - Sharing::with_buffers(&self.queue_families, &self.buffer_families) - } - - /// The family of the device's `VkQueue` at `index` (a logical queue's), which the command - /// pools of what it runs are made for. - pub(crate) fn queue_family_of(&self, index: usize) -> u32 { - self.queues[index].family - } - - /// The queue flags of the family of the device's `VkQueue` at `index`. - pub(crate) fn queue_flags_of(&self, index: usize) -> vk::QueueFlags { - self.queues[index].flags - } - - /// The reads a global memory barrier recorded for the device's `VkQueue` at `index` names - /// (`image_barrier::MemoryReads`): its family's. - pub(crate) fn memory_reads_of(&self, index: usize) -> MemoryReads { - self.queues[index].reads - } - - /// Whether an internal submission (`submit.rs`) was made that the host has not seen - /// complete: its commands may still run on the device's first `VkQueue`, and end with no - /// barrier to the commands after them there. Read where no internal submission can be made - /// meanwhile (a batch's place in the first work's order, `texture/first_move.rs`), it holds - /// until that place goes. - pub(crate) fn internal_running(&self) -> bool { - self.internal_done.running() - } - - /// How many of its `VkQueue`s, the first, the round robin lends logical queues; the rest are - /// reserved for presenting queues, but the copy queue's. - pub(crate) fn round_robin(&self) -> usize { - self.round_robin - } - - /// How many of its `VkQueue`s, after the round robin's, are reserved for presenting queues. - pub(crate) fn presenting(&self) -> usize { - self.queues.len() - self.round_robin - usize::from(self.copy_slot.is_some()) - } - - /// The index of the copy queue's `VkQueue`, where the device has one: the last of its - /// `VkQueue`s, of a family of transfers alone (`queue.rs`, - /// `Device::new_command_queue_for_copies`). - pub(crate) fn copy_slot(&self) -> Option { - self.copy_slot - } - - /// Where the device's queue limits changed its round robin's or presenting queues' - /// `VkQueue`s from the queue plan's (`DeviceOptions::queue_limits`), how many it took of - /// each and how many the plan gives. - pub(crate) fn queues_limited(&self) -> Option<((usize, usize), (usize, usize))> { - let planned = self.planned?; - let taken = (self.round_robin, self.presenting()); - (taken != planned).then_some((taken, planned)) - } - - /// A Vulkan sampler of `info`, counted against the device's `maxSamplerAllocationCount` - /// (`SamplerCount`): refused, `Error::SamplerLimit`, where that many are live. Whoever - /// destroys it gives the count back (`DeviceShared::sampler_destroyed`). - /// - /// # Safety - /// - /// `info` and its chain are valid for the device and live for the call. - pub(crate) unsafe fn create_sampler( - &self, - info: &vk::SamplerCreateInfo<'_>, - ) -> Result { - self.sampler_count.take()?; - // SAFETY: the caller's. - match unsafe { self.vk().create_sampler(info, None) } { - Ok(sampler) => Ok(sampler), - Err(result) => { - self.sampler_count.give(); - Err(vulkan(result)) - } - } - } - - /// A sampler of `DeviceShared::create_sampler`'s was destroyed. - pub(crate) fn sampler_destroyed(&self) { - self.sampler_count.give(); - } -} - -impl Drop for DeviceShared { - fn drop(&mut self) { - // The whole teardown is one section of the exit guard: once the process is exiting, the - // device, its threads and its objects are left to its end, and an exit that begins - // meanwhile waits for the teardown, which leaves the rest at its next step (below, - // `exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - // The queue-switch check holds nothing of the device either: it stops at its next step, - // and its objects go before the wait returns (`queue_switch_check.rs`). - self.queue_switch.stop(); - // So do the submission checks (`submit_check.rs`). Where a submission of theirs stalled - // and still has not completed, the device's work cannot be waited for: the device is - // left to the process's end (below). - let checks_ended = self.submit_checks.stop(self.vk()); - // The watch of the program's marks and the releases of freed memory, posted to the - // handler threads, hold nothing of the device: those that begin from here on call - // nothing, and the threads' stop below waits for those running (`freed_memory.rs`). - if let Some(parking) = self.parking.get() { - parking.close(); - } - // The draws the snapshot's area rule weighed since the last line (`reader_sizes.rs`). - if let Some(text) = lock(&self.reader_sizes).last_line() { - let sink = self.instance.sink(); - crate::driver_facts::inform_through(sink, "metal2vulkan-snapshot-readers", text); - } - // Nothing of the device is in flight: its failures are no longer relayed. - if let Some(relay) = self.instance.relay() { - relay.forget(&self.lost); - } - // Every command buffer holds its device, so none is held or pending: the threads only - // stop. - self.scheduler.stop(); - // Every open render encoder holds the device too: none is left to lower. - self.deferred.stop(); - // Every decode job holds its image, and so the device: none is left. - self.textures.twin_decodes.stop(); - // What the reaper is handed holds the device: none is left, and it only stops, unless - // this teardown runs on its thread. - self.reaper.stop(); - // What the residency thread releases holds the device: none is left. - self.residency.stop(); - // The idle sweep holds nothing of the device: it ends before the parked objects and the - // memory go below (`idle_sweep.rs`). - self.idle_sweep.stop(); - self.completion.stop(); - self.contexts.stop(); - // No command buffer is left to post a pool to the begin-ahead thread, which holds nothing - // of the device: it ends before the spares go below (`begin_ahead.rs`). - self.begin_ahead.stop(); - // The encoder times' last summary, where they are on: no completion tallies more - // (`encoder_times.rs`). - for line in self.timing.encoders().last() { - let sink = self.instance.sink(); - crate::driver_facts::inform_through(sink, crate::encoder_times::ID_NAME, line); - } - // An exit that began meanwhile waits for this teardown (`exit_guard`): from here on the - // device, its objects and its memory are left to the process's end, as where the exit - // began first, so that the exit waits for no more of the teardown than its step in - // progress (the wait for idle, and `vkDestroyDevice` above all, take long beside other - // processes' work on the GPU). - if exit_guard::closed() { - return; - } - // Likewise where a submission of the submission checks never completed: the wait for - // idle would never return, and its objects are still pending. The instance, which may - // not go before its devices, is kept to the process's end with the device. - // So where the generation stopped and is parked (`command_buffer/stall.rs`): its work - // never ends. - if !checks_ended || self.wedged() { - std::mem::forget(Arc::clone(&self.instance)); - return; - } - // SAFETY: the device is live; waiting for idle covers any work the consumer of an - // adopted device did not wait for before dropping the runtime's last handle. No batch is - // pending then, so no timeline is in use. - unsafe { - let _ = self.vk().device_wait_idle(); - exit_guard::called(Call::DeviceWaitIdle); - // The scheduler's thread, which waited on its nudge, has stopped. - release::object(self.vk(), self.nudge); - for queue in self.queues.iter() { - release::object(self.vk(), queue.timeline); - release::object(self.vk(), queue.pieces); - // The marks after the last uses of the queue outside a batch (`relay.rs`). - for fence in queue.flights.get().map(|f| f.drain()).unwrap_or_default() { - release::object(self.vk(), fence); - } - } - // Nor the marks of the program's uses of the queues (`freed_memory.rs`). - if let Some(parking) = self.parking.get() { - parking.release(self.vk()); - } - // No fence is pending either: each command buffer's was given back as it finished. - self.fences.release(self.vk()); - // Nor a sync file's semaphore: each command buffer gave its own back as it finished, - // or with its state (`command_buffer/sync_file.rs`). - #[cfg(unix)] - if let Some(sync_fd) = &self.sync_fd_semaphores { - sync_fd.release(self.vk()); - } - // Nor a timestamp slot: each command buffer gave its slot back as it finished, or - // with its state. - self.timing.release(self.vk()); - // Nor a coverage query pool: each pass's came back as its command buffer finished. - self.coverage_pools.release(self.vk()); - } - // Nor a kept barrier command buffer, nor a submission taking a driver's stall idle: the - // queues are idle. - self.scheduler.release_kept(self.vk()); - self.scheduler.release_idle(self.vk()); - // No command buffer is left to give back a spare, or to hold one; the spare command pools - // whose command buffers the free thread frees are kept again once it did (`spares.rs`). - self.frees.drain(); - self.spares.release(self); - if let Some(internal) = lock(&self.internal).take() { - internal.destroy(self.vk()); - } - for staging in self.staging.iter().chain(&self.fill_queue) { - staging.destroy(self.vk()); - } - lock(&self.textures.neutrals).destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.textures.recycled).destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.recycled_buffers).destroy(self.vk(), &mut lock(&self.memory)); - // No framebuffer is left to hold a placeholder (`storage_placeholder.rs`). - lock(&self.textures.storage_placeholders).destroy(self.vk(), &mut lock(&self.memory)); - // The zeros new resources' first work copied from (`texture/first_move.rs`). - (self.textures.first_moves).destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.heaps).destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.owned_kernels).destroy(self.vk()); - lock(&self.mipmap_scratch).destroy(self.vk(), &mut lock(&self.memory)); - self.gpu_pools.destroy(self.vk(), &mut lock(&self.memory)); - lock(&self.planes).destroy(self.vk()); - lock(&self.interleave).destroy(self.vk()); - lock(&self.color_resolves).destroy(self.vk()); - lock(&self.stencil_copies).destroy(self.vk()); - lock(&self.depth_copies).destroy(self.vk()); - lock(&self.depth_stencil_resolves).destroy(self.vk()); - lock(&self.attachmentless).destroy(self.vk()); - lock(&self.render_passes).destroy(self.vk()); - // What released variants left (`pipeline/kept.rs`). - lock(&self.kept).destroy(self); - // The linked pipelines, then the graphics pipeline libraries they linked: each variant's - // pipeline holds the device, and the kept ones went above. - if let Some(libraries) = &self.libraries { - libraries.drain(&*self); - } - // The shader modules, every one the map holds, destroyed here while the device lives: no - // variant is left but one dropping this device right now (whose share then calls - // nothing), and the kept ones let go of theirs above (`pipeline/content_keyed.rs`). - let modules = lock(&self.shader_modules).drain(); - modules.destroy(&*self); - // The pipeline layouts, likewise (`pipeline/shared_layouts.rs`). - let layouts = lock(&self.pipeline_layouts).drain(); - layouts.destroy(&*self); - // The immutable sampler sets, likewise, each counted back as its samplers go: the - // layouts that baked them are gone. - let sampler_sets = lock(&self.sampler_sets).drain(); - sampler_sets.destroy(&*self); - // Likewise once the exit began: the caches' records stay unwritten, and the memory's - // blocks stay with their deallocators unrun, as a release after the exit leaves them - // (`exit_guard`). - if exit_guard::closed() { - return; - } - // Every other pipeline was destroyed with its state (each holds this device), so the - // `VkPipelineCache` the cache keeps for each record goes, and the cache thread stops. - // SAFETY: the device is live and no making is left to be handed a cache. - unsafe { self.shader_cache.close(self.vk()) }; - // What waited with blocks of its memory (a host import's deallocators) goes once they are - // freed, with no lock held. - let after = lock(&self.memory).destroy(self.vk()); - drop(after); - // Every free posted to the free thread runs, and the thread ends (`free_thread.rs`). - self.frees.stop(); - // And the device itself. - if exit_guard::closed() { - return; - } - // The device's record of pipeline makings goes, before `vkDestroyDevice`: in builds with - // debug assertions, no making is in progress (`compiles.rs`). - compiles::unregister(self.vk().handle()); - if self.owned { - // SAFETY: the runtime created the device, every object made from it is destroyed, - // and the loader's `vkDestroyDevice` reads the device's loader word first. - unsafe { - self.loader_word.restored(|| { - release::object(self.vk(), release::WholeDevice); - }) - } - } - self.lineage.destroyed(); - } -} - -/// One of the device's `VkQueue`s. -pub(crate) struct QueueSlot { - /// The queue, under its lock: submissions are externally synchronized. With it, its place in - /// its driver's period of stalls (`submit_stalls.rs`), which each use under the lock moves. - raw: Mutex<(vk::Queue, submit_stalls::Period)>, - /// Its place's `Period::may_be_due`, as of the last use: read without the lock. - stall_due: AtomicBool, - /// Its batches' last submissions' times and their median (`submit_calls.rs`): kept under - /// the lock, the median read without it. - pub(crate) calls: submit_calls::SubmitCalls, - /// The queue's family, which the command pools of what it runs are made for. - pub(super) family: u32, - /// The family's queue flags: the commands it runs, and so the accesses a barrier recorded - /// for it may name (`image_barrier.rs`). - flags: vk::QueueFlags, - /// The reads a global memory barrier recorded for it names: its family's - /// (`image_barrier::MemoryReads`), a copy engine's transfers alone on the copy queue's. - reads: MemoryReads, - /// The queue's loader word, which MoltenVK overwrites where a message names the queue - /// (`relay.rs`): put back before each use. - word: LoaderWord, - /// Its submissions in flight, where the relay relays its failures (`relay.rs`): set once the - /// device is primed. - pub(super) flights: OnceLock>, - /// The timeline semaphore every batch submitted here signals, with rising values: Vulkan's - /// signal operation order makes them complete in that order. - pub(super) timeline: vk::Semaphore, - /// The timeline semaphore each piece of a batch's work but its last signals, with rising - /// values, which nothing waits for: a submission that signals no semaphore is one a driver - /// may merge into the next (`command_buffer/submit.rs`, `rate_mapped_pass.rs`'s - /// **Pieces**). - pub(crate) pieces: vk::Semaphore, - /// The last value a piece signalled `pieces` to. Taken under the scheduler's lock, which - /// every batch's submission holds, so the values rise in submission order. - piece_value: AtomicU64, - /// The value through which every batch submitted here completed, as the host saw. - completed: AtomicU64, - /// The value of the last batch submitted here: what the exit hook waits for on a device - /// whose queues run in this process ([`exit_guard::InProcess`]). - submitted: AtomicU64, - /// The value of the submission before the last that signalled the timeline here: while it is - /// not seen complete, two or more submissions here are in flight - /// ([`pending_beyond_one`](Self::pending_beyond_one)). - submitted_before: AtomicU64, - /// Its part in the command queues' sharing of `VkQueue`s (`queue_share.rs`). - pub(crate) share: crate::queue_share::SlotShare, - /// Its command buffers' waits behind other command queues' batches (`queue_wait.rs`). - pub(crate) waits: crate::queue_wait::QueueWaits, - /// The device's queue uses, which each hold of the queue's lock counts (`queue_quiet.rs`). - quiet: Arc, -} - -impl QueueSlot { - /// `f` with the queue, under its lock, its loader word put back first: a use whose - /// signalling calls are not counted, so its place in its driver's period is forgotten - /// (`submit_stalls.rs`). - pub(super) fn with(&self, f: impl FnOnce(vk::Queue) -> R) -> R { - self.hold().with(f) - } - - /// `f` with the queue and its place in its driver's period, under its lock, its loader word - /// put back first: `f` counts each signalling call it makes (`Period::called`). For a use of - /// `caller`'s, also the wait for the lock where it waited behind a stall taken idle - /// (`Period::entered`). - pub(crate) fn with_counted( - &self, - caller: submit_stalls::Caller, - f: impl FnOnce(vk::Queue, &mut submit_stalls::Period) -> R, - ) -> (R, Option) { - self.hold().with_counted(caller, f) - } - - /// The queue's lock, held until the hold drops, the wait for it timed: each use under it is - /// made through the hold ([`SlotHold::with`], [`SlotHold::with_counted`]). A caller that - /// holds several queues at once (`QueueUses::use_queues_kept`) takes their locks in index - /// order. - pub(super) fn hold(&self) -> SlotHold<'_> { - let asked = gpu_time::host_nanos(); - let raw = lock(&self.raw); - let waited = gpu_time::host_nanos().saturating_sub(asked); - self.quiet.began(); - SlotHold { - slot: self, - raw, - waited, - } - } - - /// `f` with the queue's place in its driver's period alone, under the queue's lock. - pub(crate) fn with_period(&self, f: impl FnOnce(&mut submit_stalls::Period) -> R) -> R { - let mut held = lock(&self.raw); - let answer = f(&mut held.1); - self.stall_due.store(held.1.may_be_due(), Ordering::Relaxed); - answer - } - - /// Whether its driver's next stall may be due within `submit_stalls::MOST_EMPTY` calls, as of - /// its last use (`Period::may_be_due`), read without its lock. - pub(crate) fn stall_may_be_due(&self) -> bool { - self.stall_due.load(Ordering::Relaxed) - } - - /// The host saw the timeline reach `value`: published, then the waits behind other command - /// queues' batches it ends are timed (`queue_wait.rs`). - pub(super) fn completed(&self, value: u64, counts: &crate::work_counts::Counters) { - if self.completed.fetch_max(value, Ordering::AcqRel) < value { - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - crate::command_buffer::completion::trace::at( - crate::command_buffer::completion::trace::Point::Leave, - ); - self.share.completed(); - self.waits.completed(value, counts); - } - } - - /// The values `count` pieces of a batch's work signal [`pieces`](Self::pieces) to, the - /// first of them, each above every earlier one: under the scheduler's lock. - pub(crate) fn piece_values(&self, count: u64) -> u64 { - self.piece_value.fetch_add(count, Ordering::Relaxed) + 1 - } - - /// The value through which every batch completed, as the host saw. - pub(super) fn completed_value(&self) -> u64 { - self.completed.load(Ordering::Acquire) - } - - /// A batch signalling `value` was submitted here, inside its section of the exit guard: the - /// hook, which waits for that section, sees it. Submissions here are made under the queue's - /// lock, so the last two values move together. - pub(super) fn submitted(&self, value: u64) { - let before = self.submitted.fetch_max(value, Ordering::AcqRel); - if before < value { - self.submitted_before.store(before, Ordering::Release); - self.share.submitted(self.completed_value() >= before); - } - } - - /// Where two or more submissions that signalled the timeline here are not seen complete, the - /// value of the one before the last, whose completion leaves one in flight: each submission - /// signals a higher value, and the timeline completes them in order - /// (`command_buffer/group.rs`). Read without the queue's lock, so a submission made meanwhile - /// is seen or not. - pub(super) fn pending_beyond_one(&self) -> Option { - let before = self.submitted_before.load(Ordering::Acquire); - (self.completed_value() < before).then_some(before) - } - - /// The value of the last batch submitted here; 0 before the first. - pub(super) fn submitted_value(&self) -> u64 { - self.submitted.load(Ordering::Acquire) - } -} - -/// A hold of a [`QueueSlot`]'s lock ([`QueueSlot::hold`]), let go as it drops: one use of the -/// device's queues (`queue_quiet.rs`) while it lasts. -pub(super) struct SlotHold<'a> { - slot: &'a QueueSlot, - raw: MutexGuard<'a, (vk::Queue, submit_stalls::Period)>, - /// How long the hold waited for the lock, in nanoseconds: the first counted use's wait - /// (`Period::entered`), 0 for the later ones. - waited: u64, -} - -impl Drop for SlotHold<'_> { - fn drop(&mut self) { - self.slot.quiet.ended(); - } -} - -impl SlotHold<'_> { - /// [`QueueSlot::with`], under this hold. - pub(super) fn with(&mut self, f: impl FnOnce(vk::Queue) -> R) -> R { - self.raw.1.forget(); - self.slot.stall_due.store(false, Ordering::Relaxed); - // SAFETY: the queue lives while its slot does. - unsafe { self.slot.word.restore() }; - f(self.raw.0) - } - - /// [`QueueSlot::with_counted`], under this hold. - pub(super) fn with_counted( - &mut self, - caller: submit_stalls::Caller, - f: impl FnOnce(vk::Queue, &mut submit_stalls::Period) -> R, - ) -> (R, Option) { - let behind = match caller { - submit_stalls::Caller::Work => { - let waited = self.waited; - self.waited = 0; - self.raw.1.entered(waited) - } - submit_stalls::Caller::Empty => None, - }; - // SAFETY: the queue lives while its slot does. - unsafe { self.slot.word.restore() }; - let (queue, period) = &mut *self.raw; - let used = f(*queue, period); - self.slot - .stall_due - .store(period.may_be_due(), Ordering::Relaxed); - (used, behind) - } -} - -#[cfg(debug_assertions)] -thread_local! { - /// The locks this thread took of what its draws share with draws on other threads (builds - /// with debug assertions): a pipeline state's settles, the device's function tables, a - /// variant's quiet formats. - static SHARED_DRAW_LOCKS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// [`lock`] of something draws on other threads share (`SHARED_DRAW_LOCKS`, counted in builds -/// with debug assertions): what a test of a draw that takes none counts. -pub(super) fn shared_draw_lock(mutex: &Mutex) -> MutexGuard<'_, T> { - #[cfg(debug_assertions)] - SHARED_DRAW_LOCKS.with(|locks| locks.set(locks.get() + 1)); - lock(mutex) -} - -/// How many [`shared_draw_lock`]s this thread took so far. -#[cfg(all(test, debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] -pub(super) fn shared_draw_locks() -> u64 { - SHARED_DRAW_LOCKS.with(std::cell::Cell::get) -} - -/// `mutex`'s guard; a lock poisoned by a panicking holder is taken over (the runtime's state is -/// updated before any call that can panic). -pub(super) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { - mutex - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) -} - -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -impl Device { - /// Fail the next `count` imports of host pages by their pointer as the driver's out of device - /// memory: the tests' stand-in for an import the device and the gate admitted that then fails - /// (`copied.rs`). - pub(crate) fn fail_next_host_imports(&self, count: u64) { - (self.shared().failing_host_imports).store(count, Ordering::Relaxed); - } - - /// Fail the next `count` `vkQueueSubmit`s of its command buffers' work as the driver's out of - /// device memory, none of them made: the tests' stand-in for a submission the driver refuses - /// (`DeviceShared::submit_logged`). - pub(crate) fn fail_next_submissions(&self, count: u64) { - (self.shared().failing_submissions).store(count, Ordering::Relaxed); - } - - /// [`fail_next_submissions`](Self::fail_next_submissions), each failing with `result`. - pub(crate) fn fail_next_submissions_with(&self, count: u64, result: vk::Result) { - (self.shared().failing_result).store(result.as_raw(), Ordering::Relaxed); - self.fail_next_submissions(count); - } - - /// Make each `vkQueueSubmit` of a batch that submits command buffers take `pause` more, inside - /// its timed call, from now on (`None`: no more): the tests' stand-in for a driver whose calls - /// of commands are slow, a call of none not (`submit_calls.rs`). - pub(crate) fn slow_submit_calls(&self, pause: Option) { - let nanos = pause.map_or(0, |pause| pause.as_nanos() as u64); - (self.shared().submit_call_pause).store(nanos, Ordering::Relaxed); - } - - /// Of the calls [`slow_submit_calls`](Self::slow_submit_calls) lengthens, leave each `every`th - /// from now on at the driver's own time, the first the `every`th to come (`None`: lengthen - /// each): the tests' stand-in for short calls of commands among slow ones - /// (`submit_calls.rs`, "Measured, not named"). - pub(crate) fn fast_submit_call_every(&self, every: Option) { - let (fast, counted) = &self.shared().submit_call_fast; - counted.store(0, Ordering::Relaxed); - fast.store(every.unwrap_or(0), Ordering::Relaxed); - } - - /// A committing thread leaves a `VkQueue`'s batches to the scheduler's thread where their - /// last submissions took `bound` nanoseconds or more at their median, from now on (`None`: - /// `submit_calls::SLOW_NANOS` again): 1 leaves every batch of a queue whose submissions were - /// timed, `u64::MAX` none. - pub(crate) fn leave_calls_from(&self, bound: Option) { - (self.shared().slow_calls_from).store(bound.unwrap_or(0), Ordering::Relaxed); - } -} - -impl Device { - /// `registryID`: an identifier of the physical device, from its `deviceUUID`. - pub fn registry_id(&self) -> u64 { - properties::registry_id(&self.properties().device_uuid) - } - - /// `name`. - pub fn name(&self) -> &str { - &self.properties().name - } - - /// The device's identity and Metal's public device queries, with the documented facts a - /// consumer computes Apple's private ones from: the same through a recovery of its GPU - /// ([`Device::recover_for_test`]), which makes the new `VkDevice` of the same physical device. - pub fn properties(&self) -> &DeviceProperties { - &self.invariant().properties - } - - /// What every generation of the device answers alike (`line.rs`): a generation handle's own - /// copy, a root handle's line's. - #[inline(always)] - fn invariant(&self) -> &line::Invariant { - match &self.0 { - Pin::Generation(shared) => &shared.invariant, - Pin::Root(root) => &root.line.invariant, - } - } - - /// The device's line (`line.rs`). - #[inline(always)] - pub(crate) fn line(&self) -> &Arc { - match &self.0 { - Pin::Generation(shared) => &shared.line, - Pin::Root(root) => &root.line, - } - } - - /// A root handle of the device (`line.rs`): one whose calls go to the generation that serves. - pub(crate) fn root(&self) -> Device { - holds::root(Arc::clone(self.line())) - } - - /// The generation of a generation handle (`line.rs`); of a root handle, the one its first - /// such reach pinned ([`Device::shared`]). - pub(super) fn shared_arc(&self) -> &Arc { - match &self.0 { - Pin::Generation(shared) => shared, - Pin::Root(root) => root.pinned.get_or_init(|| self.pin_root(&root.line)), - } - } - - /// The generation a root handle pins at its first reach of a generation's state: the one - /// that serves then. The runtime's own code holds generation handles alone, and every public - /// call of a root handle goes to the generation that serves ([`Device::current`]); only a - /// test reaches a root's state, and keeps that generation while the root's cell lives. - #[cold] - #[inline(never)] - fn pin_root(&self, line: &Arc) -> Arc { - Arc::clone(line.current(self).shared_arc()) - } - - /// A handle on the device that does not keep it: a generation handle's, of its generation. - pub(crate) fn downgrade(&self) -> WeakDevice { - let shared = self.shared_arc(); - WeakDevice(Arc::downgrade(shared), Arc::clone(&shared.holds)) - } - - /// The compile-and-plan device this device compiles and plans for now. No Metal counterpart. - /// Its profile is the device description's until the device's view check answers with a fact - /// (`view_check.rs`); from then on, the description's with the check's facts measured - /// ([`Device::view_costs`]), whose profile fingerprint differs. Read it once for one compile - /// and its link. - pub fn compile_device(&self) -> &metal2vulkan::device::Device { - let invariant = self.invariant(); - (invariant.views.measured()).unwrap_or(&invariant.compile) - } - - /// The device's view check (`view_check.rs`). - pub(crate) fn view_check(&self) -> &crate::view_check::ViewCheck { - &self.invariant().views - } - - /// What the Vulkan device enabled, in the compile layer's vocabulary. No Metal counterpart. - pub fn enabled(&self) -> &EnableSet { - &self.invariant().enabled - } - - /// Whether the Vulkan device enabled the device extension `name`: one the options asked for - /// (`DeviceOptions::device_extensions`, and each of `optional_device_extensions` the device - /// could enable), or one the runtime enabled itself (of the vocabulary's names, the one the - /// device listed). An adopted device answers for its `RawDevice::device_extensions`. No Metal - /// counterpart. - pub fn enables_extension(&self, name: &std::ffi::CStr) -> bool { - (self.invariant().extensions.iter()).any(|enabled| enabled.as_c_str() == name) - } - - /// The generation a generation handle holds (`line.rs`). The runtime reaches a device's - /// generation through generation handles: every public call of a root handle goes to the - /// generation that serves first ([`Device::current`]). A root handle answers with the one - /// it pinned ([`shared_arc`](Self::shared_arc)). - #[inline(always)] - pub(super) fn shared(&self) -> &DeviceShared { - match &self.0 { - Pin::Generation(shared) => shared, - Pin::Root(..) => self.root_shared(), - } - } - - /// [`shared`](Self::shared) of a root handle: out of line, as only a test reaches it. - #[cold] - #[inline(never)] - fn root_shared(&self) -> &DeviceShared { - self.shared_arc() - } - - /// Keep room in the memory pools the runtime's encodings and commits place their own - /// resources in, and make their blocks ahead while they grow (`memory::keep_room`, - /// `memory/ready.rs`): called by the creation calls that may wait (a queue's, a pipeline - /// state's, a buffer's, a texture's, a heap's), so that no encoding or commit makes a memory - /// block, whose `vkAllocateMemory` waited 2.37 s for other processes' GPU work on NVIDIA's - /// driver. Nothing in a host step, a serial point of the command buffers' stream that makes - /// only what it needs. - pub(crate) fn keep_room(&self) { - if crate::exit_guard::in_host_step() { - return; - } - let shared = self.shared(); - // The idle sweep's thread, from the device's first such call on (`idle_sweep.rs`). - shared.idle_sweep.start(|| crate::idle_sweep::SweepTargets { - memory: Arc::clone(&shared.memory), - images: Arc::clone(&shared.textures.recycled), - buffers: Arc::clone(&shared.recycled_buffers), - functions: Arc::clone(&shared.functions), - counts: Arc::clone(&shared.counts), - }); - let copies = || self.copies_color_on_the_host(); - let memory = &shared.memory; - // The kind of block the runtime's own buffers take now (`buffer.rs`'s - // `placed_new_buffer`), asked as their making asks it but counting nothing. - let exportable = lock(memory).fd_buffer_types.is_ok(); - let own = lock(memory).own_buffers(exportable && self.fd_blocks_taken()); - // And whether its host-visible ones take blocks of its own pages. - let pay = self.fresh_pages_pay_now() && self.page_blocks_taken(); - let pages = lock(memory).page_blocks(pay); - crate::memory::keep_room( - memory, - shared.vk(), - &shared.counts, - (&shared.functions, &shared.queue_quiet), - (copies, own, pages), - ); - } - - /// Whether `other` is this device (the same generation, not merely the same physical - /// device); of two handles one of which is a root, whether they are of the same line. - #[inline(always)] - pub(super) fn same(&self, other: &Device) -> bool { - // The common answer, a bind's, at one compare: the same generation (or root cell). - self.0.address() == other.0.address() || self.same_apart(other) - } - - /// [`same`](Self::same) of two handles that hold different cells: of one line where one is a - /// root; two generations are two devices. - #[cold] - #[inline(never)] - fn same_apart(&self, other: &Device) -> bool { - match (&self.0, &other.0) { - (Pin::Generation(_), Pin::Generation(_)) => false, - _ => self.same_line(other), - } - } - - /// Whether `other` is of this device's line: this device, or one generation of it made before - /// or after a recovery (`line.rs`). - pub(super) fn same_line(&self, other: &Device) -> bool { - Arc::ptr_eq(self.line(), other.line()) - } - - /// Whether the device was lost: not to a public call that took its arguments on it before - /// its loss, which the loss follows (`Device::at_serving_taking`, `line.rs`). - pub(super) fn is_lost(&self) -> bool { - let shared = self.shared(); - shared.lost() && !line::runs_on(shared) - } - - /// Record that the device stopped, for `stop` (`command_buffer/stall.rs`): its `VkDevice` is - /// parked, so nothing of it is destroyed from now on, the device itself included - /// (`release.rs`), and nothing waits for its queues; then it is lost, as - /// [`mark_lost`](Self::mark_lost) records. The first stop is the generation's. Counted: - /// `WorkCounts::wedges_declared` or `WorkCounts::watchdog_timeouts`, by the stop, and - /// `WorkCounts::vk_devices_parked`. - pub(crate) fn mark_wedged(&self, stop: crate::command_buffer::Stop) { - let shared = self.shared(); - if shared.stopped.set(stop).is_ok() { - crate::release::park(shared.vk().handle()); - match stop { - crate::command_buffer::Stop::Unanswered => shared.counts.wedge_declared(), - crate::command_buffer::Stop::Watchdog => shared.counts.watchdog_timed_out(), - } - } - self.mark_lost(); - } - - /// Record that the device was lost: its line recovers at the next call that needs the device, - /// where it recovers (`line.rs`). - pub(super) fn mark_lost(&self) { - let shared = self.shared(); - shared.lost.store(true, Ordering::Release); - shared.line.lose(shared); - } - - /// Wait for the work submitted to each of the device's queues to end, each queue under its - /// lock, the waits one section of the exit guard: what a completion turn does after a - /// failed wait, before that wait's command buffers let go of what they used - /// (`command_buffer/completion.rs`). Once the process is exiting it waits for nothing, and - /// the releases that follow make no Vulkan call. - /// - /// Vulkan lets go of a lost device's objects at once. MoltenVK 1.4.1 (`MVKQueue.mm`, - /// `MVKCommandBuffer.mm`) does not: a failed Metal command buffer's first completed handler - /// marks the device lost, so a wait for its fence returns `VK_ERROR_DEVICE_LOST` while its - /// later handlers have yet to run, and one of them returns each scratch buffer a command - /// such as `vkCmdUpdateBuffer` took to its `VkCommandPool`'s pool; with that command pool - /// destroyed first, the process aborted there (`mutex lock failed`). Its - /// `vkQueueWaitIdle` commits an empty Metal command buffer to the queue and waits for it, - /// lost or not, and Metal completes a queue's command buffers in order, so the earlier - /// ones' handlers have run when it returns. Another driver's returns at once on a lost - /// device, and waits for the work on a device that is not: work that completes with no more - /// work of the host's, since none of the runtime's waits on a queue whose lock is free for a - /// signal the host has yet to make (the queue-switch check holds its round's queues until it - /// signalled the round's gate, `queue_switch_check.rs`). - pub(super) fn drain_queues(&self) { - let Some(_busy) = exit_guard::enter() else { - return; - }; - let shared = self.shared(); - shared.queues_idle(); - shared.counts.queue_drain(); - } - - /// Let go of `held` at once on one of the device's handler threads, in a context of its own - /// (an identity no logical queue takes, so it waits behind no queue's handlers): what the - /// scheduler's thread lets go of under its locks where its drop may run the program's code, - /// which may not run there (`exit_guard::program_release`). Its drop runs there as on the - /// program's own thread, with no command buffer's step marked. - pub(crate) fn let_go_elsewhere(&self, held: Box) { - let (contexts, context) = self.elsewhere(); - contexts.post(context, Item::Release(held)); - } - - /// Where [`let_go_elsewhere`](Self::let_go_elsewhere) posts: the device's handler threads, - /// and a context of its own. The handle of the pool holds nothing of the device, so what holds - /// the device can be posted with no handle of it taken here. - pub(crate) fn elsewhere(&self) -> (Contexts, u64) { - ( - self.shared().contexts.clone(), - self.shared().contexts.fresh(), - ) - } - - /// A new logical queue's identity, and the index of the `VkQueue` it submits to, counted - /// there as one of the command queues it holds: of the device's queues that are not reserved - /// for presenting (the round robin's), the one the fewest live command queues hold, of those - /// no unshared queue holds, in turn among equals (`Device::take_round_robin`). `noted` names - /// a queue the program made, `None` the runtime's own and a presenting queue's, which - /// `Device::next_presenting_queue` notes ([`note_past_limits`](Self::note_past_limits)). - pub(super) fn next_queue(&self, noted: Option<&str>) -> (u64, usize) { - let (id, made) = self.round_robin_turn(); - let vk_queue = self.take_round_robin(made, false); - self.note_past_limits(noted, vk_queue); - (id, vk_queue) - } - - /// A new unshared queue's identity, and the index of the `VkQueue` it submits to, counted - /// there as an unshared queue: one of the round robin's no command queue holds where one is - /// free (`Device::place_unshared`), else the one the fewest hold - /// (`Device::take_round_robin`). A queue the program made, as - /// [`next_queue`](Self::next_queue)'s. - pub(super) fn next_unshared_queue(&self) -> (u64, usize) { - let (id, made) = self.round_robin_turn(); - let vk_queue = (self.place_unshared()).unwrap_or_else(|| self.take_round_robin(made, true)); - self.note_past_limits(Some("an unshared command queue"), vk_queue); - (id, vk_queue) - } - - /// A new round robin's or unshared queue's identity, and how many such the device made before - /// it: its turn among equals (`Device::take_round_robin`). One made past the round robin's - /// queues takes one an earlier logical queue took, whose submissions this queue's wait - /// behind where Metal's queues would not where that queue still lives - /// (`device/create.rs`'s `ROUND_ROBIN_CEILING`): counted, - /// `WorkCounts::queues_sharing_a_vk_queue`. - fn round_robin_turn(&self) -> (u64, u64) { - let id = self.shared().contexts.fresh(); - let made = self - .shared() - .round_robin_made - .fetch_add(1, Ordering::Relaxed); - if made >= self.shared().round_robin as u64 { - self.shared().counts.queue_shared_a_vk_queue(); - } - (id, made) - } - - /// Where the device's queue limits changed its round robin (`DeviceOptions::queue_limits`) - /// and the queue that took `VkQueue` `vk_queue` is one the program made, `noted` naming it, - /// say so where the program's queues made so far reach past the limits' `VkQueue`s and the - /// plan gives this one its own: once per device ([`Told::QueueLimitsReached`]). - fn note_past_limits(&self, noted: Option<&str>, vk_queue: usize) { - if let (Some(queue), Some((planned, _))) = (noted, self.shared().planned) { - let program = (self.shared().program_queues_made).fetch_add(1, Ordering::Relaxed); - if create::shares_past_limit(program, self.shared().round_robin, planned) { - self.inform_once( - Told::QueueLimitsReached, - create::QUEUE_LIMITS_REACHED, - || { - let what = format!( - "{queue}, the program's command queue {} on a round robin of {} \ - VkQueue(s), took VkQueue {vk_queue}, which another took, where the \ - plan's {planned} give it one of its own", - program + 1, - self.shared().round_robin - ); - create::queue_limits_reached(self.name(), &what) - }, - ); - } - } - } - - /// Whether the device was made with the runtime tests' default queue limits - /// (`create::TEST_QUEUE_LIMITS`). - #[cfg(test)] - pub(crate) fn test_queue_limited(&self) -> bool { - self.shared().test_queue_limits.load(Ordering::Relaxed) - } - - /// On a device of the runtime tests' default queue limits, a new command queue of the - /// program's, `queue` naming it, before anything places it (`queue.rs`; not the place a - /// recovery's queue takes again, counted where it was made): where the program holds handles - /// of as many of its queues as the limits' round robin has `VkQueue`s - /// (`Line::program_queues_held`: the handles its command buffers hold not counted, so the - /// answer follows the test's code, not when the runtime lets a completed command buffer go), - /// the test fails here (`create::needs_the_queue_plan`), as this one would share a `VkQueue` - /// with one of them where a plan of queues to spare gives it one of its own. - #[cfg(test)] - pub(crate) fn test_program_queue(&self, queue: &str) { - if !self.test_queue_limited() { - return; - } - let held = self.line().program_queues_held(); - if held >= u64::from(create::TEST_QUEUE_LIMITS.round_robin) { - let what = format!("made {queue} while the program holds {held} of its command queues"); - create::needs_the_queue_plan(&what); - } - } - - /// A new presenting queue's identity, and the index of the `VkQueue` it submits to: the - /// queues reserved for presenting, in turn. `None` where the device reserved none. - pub(super) fn next_presenting_queue(&self) -> Option<(u64, usize)> { - #[cfg(test)] - if self.test_queue_limited() { - create::needs_the_queue_plan("made a command queue for presenting"); - } - let reserved = self.shared().presenting(); - if let Some((_, planned)) = self.shared().planned { - let asked = (self.shared().presenting_asked).fetch_add(1, Ordering::Relaxed); - if create::shares_past_limit(asked, reserved, planned) { - self.inform_once( - Told::QueueLimitsReached, - create::QUEUE_LIMITS_REACHED, - || { - let what = format!( - "presenting queue {} shares a VkQueue, the device's queue limits \ - reserving {reserved} for presenting queues, where the plan reserves \ - {planned}", - asked + 1 - ); - create::queue_limits_reached(self.name(), &what) - }, - ); - } - } - if reserved == 0 { - return None; - } - let id = self.shared().contexts.fresh(); - let made = self - .shared() - .presenting_made - .fetch_add(1, Ordering::Relaxed); - Some(( - id, - self.shared().round_robin + (made % reserved as u64) as usize, - )) - } - - /// `vkAllocateCommandBuffers` of `info` (`DeviceShared::allocate_command_buffers`). - #[cfg_attr(test, track_caller)] - pub(super) fn allocate_command_buffers( - &self, - info: &vk::CommandBufferAllocateInfo<'_>, - ) -> Result, Error> { - self.shared().allocate_command_buffers(info) - } -} - -/// `vkAllocateCommandBuffers` of `info` through `vk`: the loader serves it and reads the device's -/// loader word `word` first ([`DeviceWord::restored`]); counted in `counts`. The device's -/// ([`DeviceShared::allocate_command_buffers`]), and its begin-ahead thread's, which holds no -/// device (`spares.rs`'s `BeginTargets`). -pub(crate) fn allocate_command_buffers( - vk: &Vk, - word: &DeviceWord, - counts: &super::work_counts::Counters, - info: &vk::CommandBufferAllocateInfo<'_>, -) -> Result, Error> { - // SAFETY: the device is live; `info` names one of its pools, which the caller holds - // exclusively. - let allocated = unsafe { word.restored(|| vk.allocate_command_buffers(info)) }; - exit_guard::called(Call::AllocateCommandBuffers); - if allocated.is_ok() { - counts.command_buffers_made(info.command_buffer_count); - } - allocated.map_err(super::error::vulkan) -} - -/// The parts [`DeviceShared`] is built from, by `create.rs` and `adopt.rs` alike. -pub(super) struct Parts { - pub(super) instance: Arc, - pub(super) physical: vk::PhysicalDevice, - pub(super) raw: ash::Device, - /// The device's loader word as it stood when the device reached the runtime. - pub(super) loader_word: DeviceWord, - /// The primary queue family, the first queue's. - pub(super) queue_family: u32, - /// The queues the runtime submits to, each its family and index there, the primary family's - /// first queue first: at least one. - pub(super) queues: Vec<(u32, u32)>, - /// How many of `queues`, the last, are reserved for presenting queues (fewer than all). - pub(super) present_queues: usize, - /// Where the device's queue limits changed its queues (`DeviceOptions::queue_limits`), the - /// queue plan's round robin and presenting `VkQueue`s; `None` for an adopted device. - pub(super) planned: Option<(usize, usize)>, - /// The driver refused the device with its queue plan's `VkQueue`s, and it took its least - /// plan's (`create.rs`'s `made_within_resources`, `Degradation::LeastQueuePlan`). - pub(super) least_plan: bool, - /// The queue reserved for staging copies, its family and index there, outside `queues` - /// (`staging.rs`): `None` for an adopted device, or where the families have no more. - pub(super) staging: Option<(u32, u32)>, - /// The queue reserved for fills, its family (the staging queue's) and index there, outside - /// `queues` (`staging.rs`): `None` for an adopted device, or where the staging queue's family - /// is not of transfers alone or has no second queue. - pub(super) fill: Option<(u32, u32)>, - /// The queue the program's command queues made for copies submit to - /// (`create.rs`'s `QueuePlan::copies`), its family (the staging queue's) and index there, - /// outside `queues`: the fill queue's where `fill` is the same place, which the two then - /// share; `None` for an adopted device, or where the plan has none. - pub(super) copies: Option<(u32, u32)>, - /// The queues reserved for the caller (`DeviceOptions::reserved_queues`), each its family and - /// index there, of `queues`' families, outside `queues` and `staging`: none for an adopted - /// device. - pub(super) reserved_queues: Vec<(u32, u32)>, - /// The caller's extra queues (`DeviceOptions::extra_queues`), each the flags asked for, its - /// family and its index there, outside `queues` and `staging`: none for an adopted device. - pub(super) extra_queues: Vec<(vk::QueueFlags, u32, u32)>, - pub(super) compile: metal2vulkan::device::Device, - /// The description `compile` was built from: what the device enables. - pub(super) description: DeviceDescription, - pub(super) enabled: EnableSet, - /// The names of the device extensions it enables ([`Device::enables_extension`]). - pub(super) extensions: Vec, - /// The form of `VK_KHR_calibrated_timestamps` it enables, outside `enabled`'s vocabulary. - pub(super) calibration: Option, - /// It answers GPU times from the host, writing no timestamps for command buffers' own times - /// (`gpu_time.rs`). - pub(super) gpu_times_from_host: bool, - /// The class of Mac it presents, as the consumer declared it (`None`: its GPU's, - /// `capabilities.rs`). - pub(super) mac_class: Option, - /// The degradation kinds it announces at every occurrence (`degradation.rs`). - pub(super) announce_each: BTreeSet, - /// The degradation kinds that refuse a render encoder's call met while lowering it after it - /// returned (`render/deferral.rs`). - pub(super) lowering_refuses: BTreeSet, - /// Its command buffers keep execution records (`DeviceOptions::record_executions`). - pub(super) record_executions: bool, - /// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`). - pub(super) load_no_dynamic_library_file: bool, - /// Where its pipeline records go (`DeviceOptions::pipeline_records`, `warm/record.rs`). - pub(super) pipeline_records: Option, - /// Its check of the first move over host pages fails whatever the moves did - /// (`DeviceOptions::fail_in_place_check`). - pub(super) fail_in_place_check: bool, - /// In the runtime's own tests, its view check's facts, fixed (`DeviceOptions::view_facts`). - #[cfg(test)] - pub(super) view_facts: - Option>, - /// Its submission check of merged submissions holds without its answer - /// (`DeviceOptions::assume_submissions_merge`). - pub(super) assume_submissions_merge: bool, - /// Its pending audit is on (`DeviceOptions::pending_audit`; `pending_audit.rs`), as it is - /// where `METAL2VULKAN_PENDING_AUDIT` is set. - pub(super) pending_audit: bool, - /// Its encoder trail is on (`DeviceOptions::encoder_trail`; `encoder_trail.rs`), as it is - /// where `METAL2VULKAN_ENCODER_TRAIL` is set. - pub(super) encoder_trail: bool, - /// Its views may reinterpret an image's components ([`DeviceShared`]'s field), outside - /// `enabled`'s vocabulary. - pub(super) view_reinterpretation: bool, - /// It enables `VK_EXT_device_generated_commands` (`create.rs`), outside `enabled`'s - /// vocabulary. - pub(super) generated_commands: bool, - /// It enables `hostImageCopy` where a heap's colour texture takes host-transfer usage - /// (`create.rs`; `adopt.rs`), outside `enabled`'s vocabulary. - pub(super) host_image_copy: bool, - /// It enables `VK_EXT_zero_initialize_device_memory` and its `zeroInitializeDeviceMemory` - /// (`create.rs`; never on a device the consumer made, `adopt.rs`), outside `enabled`'s - /// vocabulary. - pub(super) zero_initialize_device_memory: bool, - /// It enables `VK_NV_linear_color_attachment` and its `linearColorAttachment` (`create.rs`; - /// `adopt.rs`, where the consumer lists it), outside `enabled`'s vocabulary: a linear image - /// renders in place where the instance's color attachments are all linear - /// (`linear_attachment.rs`). - pub(super) linear_color_attachment: bool, - /// It enables `VK_EXT_graphics_pipeline_library` and links its libraries fast (`create.rs`; - /// `adopt.rs`, where the consumer lists it), outside `enabled`'s vocabulary: its render - /// pipelines are linked from libraries (`pipeline/libraries.rs`). - pub(super) graphics_pipeline_library: bool, - /// It enables `samplerYcbcrConversion` (`create.rs`), outside `enabled`'s vocabulary: a - /// two-plane YCbCr texture's planes convert through the device's own conversion where it - /// converts their format (`ycbcr_device.rs`). An adopted device's consumer does not say, so - /// it is false there. - pub(super) ycbcr_conversion: bool, - /// It takes the two-plane 4:4:4 formats with that conversion: Vulkan 1.3, or - /// `VK_EXT_ycbcr_2plane_444_formats` enabled with its feature (`create.rs`). - pub(super) ycbcr_444: bool, - /// It enables `VK_EXT_pipeline_creation_feedback` (`create.rs`), outside `enabled`'s - /// vocabulary, wherever listed: each making of a program's pipeline reads whether its cache - /// held the pipeline (`shader_cache/mod.rs`). - pub(super) creation_feedback: bool, - /// It enables the dma-buf route's extensions (`create.rs`'s `dma_buf_names`), outside - /// `enabled`'s vocabulary (`dma_buf.rs`). - pub(super) dma_buf: bool, - /// It enables the route's image extensions (`create.rs`'s `dma_buf_image_names`), likewise. - pub(super) dma_buf_images: bool, - /// It enables `VK_KHR_external_memory_fd` (`create.rs`'s `memory_fd_name`; `adopt.rs`, where - /// the consumer lists it), outside `enabled`'s vocabulary (`exported_memory.rs`). - #[cfg(unix)] - pub(super) memory_fd: bool, - /// It enables `VK_EXT_queue_family_foreign` beside the dma-buf route's extensions - /// (`create.rs`'s `foreign_family_name`; `adopt.rs`, where the consumer lists them), outside - /// `enabled`'s vocabulary (`exported_memory.rs`). - #[cfg(unix)] - pub(super) foreign_family: bool, - /// It enables `VK_KHR_external_semaphore_fd` (`create.rs`'s `semaphore_fd_name`; `adopt.rs`, - /// where the consumer lists it), outside `enabled`'s vocabulary (`exported_semaphore.rs`). - #[cfg(unix)] - pub(super) semaphore_fd: bool, - /// The sparse members of the core features it enables, outside `enabled`'s vocabulary - /// (`sparse/device.rs`). - pub(super) sparse_features: vk::PhysicalDeviceFeatures, - /// The reads its global memory barriers name (`image_barrier::MemoryReads`): those of the - /// primary queue family's commands with the extensions it enables. - pub(super) memory_reads: MemoryReads, - pub(super) owned: bool, - /// The shader cache, its directory opened before any Vulkan object was made. - pub(super) cache: CacheSetup, - /// The line a recovery makes this generation of (`line.rs`); `None` for a device made now. - pub(super) line: Option>, - /// How a device made now makes its next `VkDevice` once one is lost (`create.rs`); `None` - /// for one the consumer made, and for a recovery's, whose line has it. - pub(super) recipe: Option, -} - -impl Device { - /// The device of `parts`: create is built on adopt, so both end here, and so does a - /// recovery's new generation (`line.rs`). A generation handle of it, which the program's - /// calls that made a device turn into a root handle ([`Device::root`]). - /// - /// # Safety - /// - /// `parts.raw` is a live device of `parts.physical`, made from `parts.instance` with - /// `parts.enabled` enabled (and `timelineSemaphore`) and the queues `parts.queues`, and - /// `parts.loader_word` is its loader word. When this fails, a device - /// the runtime owns is destroyed. - unsafe fn assemble(parts: Parts) -> Result { - let Parts { - instance, - physical, - raw, - loader_word, - queue_family, - queues: queue_places, - present_queues, - planned, - least_plan, - staging: staging_place, - fill: fill_place, - copies: copy_place, - reserved_queues: reserved_places, - extra_queues: extra_places, - compile, - description, - enabled, - extensions, - calibration, - gpu_times_from_host, - mac_class, - announce_each, - lowering_refuses, - record_executions, - load_no_dynamic_library_file, - pipeline_records, - fail_in_place_check, - #[cfg(test)] - view_facts, - assume_submissions_merge, - pending_audit, - encoder_trail, - view_reinterpretation, - generated_commands, - host_image_copy, - zero_initialize_device_memory, - linear_color_attachment, - graphics_pipeline_library, - ycbcr_conversion, - ycbcr_444, - creation_feedback, - dma_buf, - dma_buf_images, - #[cfg(unix)] - memory_fd, - #[cfg(unix)] - foreign_family, - #[cfg(unix)] - semaphore_fd, - sparse_features, - memory_reads, - owned, - cache, - line: recovering, - recipe, - } = parts; - // The copy queue's `VkQueue`, where the device has one, is the last of those the runtime - // submits to, after presenting's (`queue.rs`, `Device::new_command_queue_for_copies`). - let copy_slot = copy_place.map(|_| queue_places.len()); - let queue_places: Vec<(u32, u32)> = queue_places.into_iter().chain(copy_place).collect(); - // Every pipeline made on the device from here on is made at the user-initiated class. - // SAFETY: the device is live (the caller's contract), and its functions are its own. - let raw = unsafe { compiles::route(raw) }; - // Every command recorded with the device's functions goes through a slot of its own - // (`recorder`), dropped with the device after `vkDestroyDevice`. - // SAFETY: as above; its functions were routed for its pipeline makings alone. - let (raw, recording) = unsafe { crate::recorder::route(raw) }; - // What the runtime made from the device, destroyed with it when a later step fails. - let undo = |timelines: &[vk::Semaphore]| { - // The record of pipeline makings first, as in the teardown (`compiles.rs`). - compiles::unregister(raw.handle()); - // SAFETY: nothing submitted uses the semaphores, and nothing else the runtime made - // from the device remains. - unsafe { - for &timeline in timelines { - release::object(&raw, timeline); - } - if owned { - loader_word.restored(|| { - release::object(&raw, release::WholeDevice); - }) - } - } - }; - // Each `VkQueue`'s timeline, then the scheduler's nudge (`scheduler/mod.rs`), then each - // `VkQueue`'s timeline of pieces. - let mut timelines = Vec::with_capacity(2 * queue_places.len() + 1); - for _ in 0..=2 * queue_places.len() { - let mut kind = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); - // SAFETY: the device is live and enables `timelineSemaphore` (the caller's contract). - match unsafe { raw.create_semaphore(&info, None) } { - Ok(timeline) => timelines.push(timeline), - Err(error) => { - undo(&timelines); - return Err(super::error::vulkan(error)); - } - } - } - // Each batch ends with a barrier that orders all its commands before every later one of - // its queue, where the driver runs a queue's submissions one after another anyway - // (`batch_order.rs`). - let by_ends = crate::batch_order::by_ends(compile.policy(), description.driver_id); - let threads = - Contexts::start(contexts::device_limit()).and_then(|contexts| match Completion::start( - queue_places.len(), - ) { - Ok(completion) => match Scheduler::start(queue_places.len(), by_ends) { - Ok(scheduler) => Ok((contexts, completion, scheduler)), - Err(error) => { - completion.stop(); - contexts.stop(); - Err(error) - } - }, - Err(error) => { - contexts.stop(); - Err(error) - } - }); - let (contexts, completion, scheduler) = match threads { - Ok(threads) => threads, - Err(error) => { - undo(&timelines); - return Err(error); - } - }; - // SAFETY: `physical` belongs to `instance`. - let families = unsafe { - instance - .raw - .get_physical_device_queue_family_properties(physical) - }; - let flags_of = |family: u32| { - (families.get(family as usize)).map_or(vk::QueueFlags::empty(), |p| p.queue_flags) - }; - let nudge = timelines[queue_places.len()]; - let queue_quiet = Arc::new(queue_quiet::QueueQuiet::default()); - // Whether the driver stalls in one signalling call of every 1024 to a queue: its calls' - // CPU time tells its stall (`submit_stalls.rs`). - let stalls = (description.driver_facts()) - .contains(&metal2vulkan::device::DriverFact::SignallingSubmitsStallEvery1024); - let piece_timelines = &timelines[queue_places.len() + 1..]; - let queues: Vec = queue_places - .iter() - .zip(timelines.iter().zip(piece_timelines)) - .map(|(&(family, index), (&timeline, &pieces))| { - // SAFETY: the queue exists (the caller's contract), and the loader serves the - // call after the word is put back. - let queue = unsafe { loader_word.restored(|| raw.get_device_queue(family, index)) }; - QueueSlot { - raw: Mutex::new((queue, submit_stalls::Period::new(stalls))), - stall_due: AtomicBool::new(false), - calls: submit_calls::SubmitCalls::default(), - family, - flags: flags_of(family), - reads: memory_reads.for_family(flags_of(family)), - // SAFETY: the queue was just returned, its word the loader's. - word: unsafe { LoaderWord::of_handle(queue.as_raw()) }, - flights: OnceLock::new(), - timeline, - pieces, - piece_value: AtomicU64::new(0), - completed: AtomicU64::new(0), - submitted: AtomicU64::new(0), - submitted_before: AtomicU64::new(0), - share: crate::queue_share::SlotShare::default(), - waits: crate::queue_wait::QueueWaits::default(), - quiet: Arc::clone(&queue_quiet), - } - }) - .collect(); - let mut queue_families: Vec = Vec::with_capacity(queues.len()); - let reserved_families = reserved_places.iter().map(|&(family, _)| family); - // Not the copy queue's family: its command buffers use buffers alone, which are shared - // with it as the staging queue's family (below); images keep the device's own families. - let own_queues = &queues[..copy_slot.unwrap_or(queues.len())]; - for family in own_queues - .iter() - .map(|slot| slot.family) - .chain(reserved_families) - { - if !queue_families.contains(&family) { - queue_families.push(family); - } - } - let buffer_families: Vec = (queue_families.iter().copied()) - .chain(staging_place.map(|(family, _)| family)) - .collect(); - let staging = staging_place.map(|(family, index)| { - // SAFETY: the queue exists (the caller's contract), and the loader serves the call - // after the word is put back; it was just returned, its word the loader's. - unsafe { - loader_word.restored(|| { - let queue = raw.get_device_queue(family, index); - let flags = flags_of(family); - staging::StagingQueue::new(Role::Staging, family, flags, queue, &queue_families) - }) - } - }); - // The fill queue, of the staging queue's family, whose sharing every buffer has. Where the - // copy queue's `VkQueue` is its own, its submissions take that queue's lock. - let fill_queue = fill_place.map(|(family, index)| { - // SAFETY: as the staging queue's. - let fills = unsafe { - loader_word.restored(|| { - let queue = raw.get_device_queue(family, index); - staging::StagingQueue::new(Role::Fills, family, flags_of(family), queue, &[]) - }) - }; - match copy_place == Some((family, index)) { - true => fills.sharing_slot(copy_slot), - false => fills, - } - }); - let reserved_queues = (reserved_places.iter()) - .map(|&(family, index)| handles::ReservedQueue { - family, - // SAFETY: the queue exists (the caller's contract), and the loader serves the - // call after the word is put back. - queue: unsafe { loader_word.restored(|| raw.get_device_queue(family, index)) }, - }) - .collect(); - let extra_queues = (extra_places.iter()) - .map(|&(flags, family, index)| handles::ExtraQueue { - flags, - family, - // SAFETY: the queue exists (the caller's contract), and the loader serves the - // call after the word is put back. - queue: unsafe { loader_word.restored(|| raw.get_device_queue(family, index)) }, - }) - .collect(); - let family = (families.get(queue_family as usize).copied()).unwrap_or_default(); - let timestamp_bits = family.timestamp_valid_bits; - // SAFETY: as above. - let sparse_properties = - unsafe { instance.raw.get_physical_device_properties(physical) }.sparse_properties; - let sparse = SparseDevice::of(&sparse_features, family.queue_flags, &sparse_properties); - let device_address = enabled - .features - .contains(&metal2vulkan::device::VkFeature::BufferDeviceAddress); - let generated_commands = if generated_commands { - // SAFETY: the device enables the extension; the loader serves `vkGetDeviceProcAddr` - // once the word is put back. - unsafe { - loader_word.restored(|| { - Commands::load(raw.handle(), |name| { - instance - .raw - .get_device_proc_addr(raw.handle(), name.as_ptr()) - }) - }) - } - .map(|commands| commands.routed(recording.as_ref())) - } else { - None - }; - // At least one write of set 0 pushed after each pipeline bind where the driver's pushed - // descriptors go stale across one - // (`RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds`). - let pushes_after_pipeline_binds = crate::driver_defects::of(&description).contains( - &metal2vulkan::error::RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds, - ); - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let push_descriptor = unsafe { - loader_word.restored(|| { - crate::binding::push_descriptor_command( - &instance.raw, - &raw, - description.api_version, - &enabled, - ) - }) - } - .map(|push| { - // SAFETY: the device's own command of that name. - unsafe { - crate::recorder::through(recording.as_ref(), Command::CmdPushDescriptorSet, push) - } - }); - // Its naming of an object, where its instance reports messages: every pipeline is named - // for the layers' messages (`DeviceShared::name_pipeline`). - let object_name = match instance.sink() { - // SAFETY: as above; the instance enables `VK_EXT_debug_utils` where it reports - // messages, and the loader serves `vkGetDeviceProcAddr` once the word is put back. - Some(_) => unsafe { - loader_word.restored(|| { - instance.raw.get_device_proc_addr( - raw.handle(), - c"vkSetDebugUtilsObjectNameEXT".as_ptr(), - ) - }) - }, - None => None, - } - .map(|function| { - // SAFETY: the device gave the function of this name. - unsafe { - std::mem::transmute::< - unsafe extern "system" fn(), - vk::PFN_vkSetDebugUtilsObjectNameEXT, - >(function) - } - }); - // Its calibrated timestamps, where its queue family writes timestamps: a completion turn - // reads them (`gpu_time.rs`). - // SAFETY: the device enables `calibration`'s form where it is set; the loader serves - // `vkGetDeviceProcAddr` once the word is put back. - let calibrated = unsafe { - loader_word.restored(|| { - gpu_time::calibrated(&instance.entry, &instance.raw, physical, &raw, calibration) - }) - } - .filter(|_| timestamp_bits > 0); - // The render encoder's commands of extensions and of Vulkan 1.3, which priming makes too. - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let extended_dynamic_state = unsafe { - loader_word.restored(|| { - ExtendedDynamicState::load( - &instance.raw, - &raw, - description.api_version, - &enabled, - recording.as_ref(), - ) - }) - }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let sized_index_bind = - unsafe { loader_word.restored(|| sized_index_bind(&instance.raw, &raw, &enabled)) } - .map(|bind| { - // SAFETY: the device's own command of that name. - unsafe { - crate::recorder::through( - recording.as_ref(), - Command::CmdBindIndexBuffer2, - bind, - ) - } - }); - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let color_write_masks = unsafe { - loader_word.restored(|| ColorWriteMasks::load(&instance.raw, &raw, &enabled)) - } - .map(|ColorWriteMasks(masks)| { - // SAFETY: the device's own command of that name. - ColorWriteMasks(unsafe { - crate::recorder::through(recording.as_ref(), Command::CmdSetColorWriteMask, masks) - }) - }); - // The YCbCr formats the device converts itself, where it enables the conversion. - let ycbcr_formats = match ycbcr_conversion { - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later, and the - // device enables `samplerYcbcrConversion`. - true => unsafe { - crate::ycbcr_device::YCbCrFormats::of(&instance.raw, physical, ycbcr_444) - }, - false => crate::ycbcr_device::YCbCrFormats::default(), - }; - let drawn = prime::PrimedDraws { - dynamic: extended_dynamic_state, - color_write_masks, - sized_index_bind, - }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. - let functions = unsafe { - loader_word.restored(|| { - Functions::new( - &instance.raw, - raw.clone(), - memory_reads, - push_descriptor, - object_name, - recording.as_ref(), - PendingAudit::new(pending_audit, instance.sink()), - ) - }) - }; - // The device's identity to the exit guard, by which the hook is registered (below) where - // the device can have made statics since its last registration: its driver's and its own - // UUIDs, and the entry points its sections reach. - // SAFETY: as above. - let uuids = unsafe { properties::uuids(&instance.raw, physical) }; - let guard_identity: Vec = uuids - .iter() - .flat_map(|uuid| uuid.chunks(8)) - .map(|half| u64::from_le_bytes(half.try_into().unwrap_or_default())) - .chain(functions.entry_points().iter().copied()) - .collect(); - // Where the device registers the hook, before it: the first call of each entry point of - // the exit guard's table (`prime.rs`), counted as the first since a load of a shared - // object where the device is the first after one. A device that registers nothing (one - // of an identity registered since the last load) is not primed: an earlier device's - // priming made those calls first, on what stays loaded. - let primes = exit_guard::before_priming(&guard_identity); - if let Err(error) = match primes { - false => Ok(()), - // SAFETY: the device is live, of `physical`, and enables timeline semaphores, and - // `bufferDeviceAddress` where `device_address` says so; `queues` holds at least one - // of its queues, which nothing uses yet. - true => unsafe { - prime::prime( - &instance.raw, - physical, - &Vk::new( - raw.clone(), - memory_reads, - push_descriptor, - object_name, - Default::default(), - None, - ), - &loader_word, - queue_family, - &queues, - Sharing::with_buffers(&queue_families, &buffer_families), - drawn.has(prime::Has { - timestamps: timestamp_bits > 0, - // A device the runtime created enables it (`enables.rs`). - host_query_reset: owned, - device_addresses: device_address, - generated_commands: generated_commands.is_some(), - sparse_binding: sparse.binds(), - push_descriptor: push_descriptor.is_some(), - calibration: calibrated.is_some(), - object_names: object_name.is_some(), - extended_dynamic_state: false, - primitive_restart: false, - color_write_masks: false, - sized_index_bind: false, - ycbcr_conversion: ycbcr_formats.primer().is_some(), - }), - generated_commands.as_ref(), - push_descriptor, - calibrated, - drawn, - ycbcr_formats.primer(), - ) - }, - } { - scheduler.stop(); - completion.stop(); - contexts.stop(); - undo(&timelines); - return Err(error); - } - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later (the compile - // device exists, so the description's version passed the floor). - let (identity, max_allocation) = - unsafe { properties::query(&instance.raw, physical, instance.api_version) }; - // The limit the device's live samplers are held to, the one - // `DeviceProperties::max_argument_buffer_sampler_count` is derived from. - let sampler_limit = identity.max_sampler_allocation_count; - let properties = DeviceProperties::new(identity, description, &compile, mac_class); - // SAFETY: as above. - let memory_properties = - unsafe { instance.raw.get_physical_device_memory_properties(physical) }; - // Freed memory waits for the batches in flight, and a buffer of addresses goes with no - // submission inside its `vkQueueSubmit`, where the driver fails pending work as memory a - // device-address buffer lay in is freed, or a submission as such a buffer is destroyed - // meanwhile (`freed_memory.rs`). - let parking = [ - RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork, - RuntimeDriverDefect::DestroyedAddressBufferFailsSubmission, - ] - .iter() - .any(|defect| properties.driver_defects.contains(defect)) - .then(|| Arc::new(Parking::new(queues.len()))); - let mut memory = Memory::new( - &memory_properties, - max_allocation, - device_address, - properties.has_unified_memory, - queue_families.clone(), - parking.clone(), - properties.description.driver_id, - ); - memory.share_buffers_among(buffer_families.clone()); - memory.log_to(MemoryLog::new(instance.sink())); - // Its copied host buffers' lines go to the same log (`copied.rs`). - let copied = Arc::new(super::copied::CopiedBuffers::logged(MemoryLog::new( - instance.sink(), - ))); - if zero_initialize_device_memory { - memory.zero_image_blocks(); - } - // SAFETY: as above. - let physical_properties = unsafe { instance.raw.get_physical_device_properties(physical) }; - let limits = physical_properties.limits; - // Counted from here, past the priming, which freed all it allocated. - let allocations = - crate::allocations::register(raw.handle(), limits.max_memory_allocation_count); - let upload_alignment = [ - 16, - limits.min_storage_buffer_offset_alignment, - limits.min_uniform_buffer_offset_alignment, - limits.min_texel_buffer_offset_alignment, - ] - .into_iter() - .fold(1, u64::max); - let textures = TextureState::new( - &properties.description, - limits.buffer_image_granularity, - linear_color_attachment, - ); - // SAFETY: as above; the device is live, made with `enabled` enabled, and `loader_word` - // is its loader word. - let host_import = unsafe { - Importer::new( - &instance.raw, - physical, - &raw, - &enabled, - super::buffer::usage(device_address), - &loader_word, - dma_buf, - dma_buf_images, - ) - }; - // The program's host-visible buffers lie in blocks of pages the runtime maps and imports - // by their pointer, in the memory types the device imports such pages as, once its - // submission check found that a held import costs its submissions nothing (`memory.rs`'s - // "Buffers in the runtime's own pages"). - let (page_types, page_unit) = match host_import.as_ref().ok().and_then(Importer::pointers) { - Some(pointers) => { - let unit = pointers.unit(); - // SAFETY: `raw` is the import's device. - let types = unsafe { crate::fresh_pages::own_page_types(pointers, &raw, unit) }; - (types, unit) - } - None => (Err("the device imports no host pointer"), 1), - }; - memory.page_buffer_blocks(&raw, page_types, page_unit)?; - // How the device exports a buffer's memory as an opaque file descriptor, and as a dma-buf, - // where it enables the extensions each needs and exports a buffer's memory so - // (`exported_memory.rs`). - #[cfg(unix)] - let (opaque_fd, dma_buf_export) = { - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put - // back, and the device enables the extension. - let functions = memory_fd.then(|| unsafe { - loader_word - .restored(|| ash::khr::external_memory_fd::Device::new(&instance.raw, &raw)) - }); - let usage = super::buffer::usage(device_address); - let handle = crate::buffer_descriptor::MemoryExport::OpaqueFd; - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later. - let opaque = unsafe { - crate::exported_memory::FdExport::new( - &instance.raw, - physical, - functions.clone(), - (usage, handle), - ) - }; - // The device's own buffers lie in blocks exportable as opaque file descriptors, - // never exported, where it exports such a descriptor of a pooled buffer's memory for - // the usage of those buffers and of a buffer of addresses, and its policy takes - // textures over memory of an export in place by its check; in the memory types its - // linear image made for one takes as its own linear image does (`memory.rs`'s - // "Buffers in exportable blocks"). - let in_place = compile.policy().host_page_textures - == metal2vulkan::device::HostPageTexturePolicy::InPlace; - let usages = [ - Some(super::buffer::usage(false)), - device_address.then_some(usage), - ]; - // Whether the device exports each usage's pooled memory as an opaque file descriptor. - let pooled = |functions: &ash::khr::external_memory_fd::Device| { - (usages.into_iter().flatten()).all(|usage| { - // SAFETY: as above. - let export = unsafe { - crate::exported_memory::FdExport::new( - &instance.raw, - physical, - Some(functions.clone()), - (usage, handle), - ) - }; - export.is_some_and(|export| export.pooled()) - }) - }; - let exports = match &functions { - None => Err("the device enables no VK_KHR_external_memory_fd"), - Some(_) if !in_place => { - Err("the device's policy shadows every texture over memory of an export") - } - Some(functions) if !pooled(functions) => Err( - "the device exports an opaque file descriptor of no pooled buffer's memory of \ - the runtime's usages", - ), - Some(_) => Ok(()), - }; - let types = crate::memory::fd_buffer_types( - &memory_properties, - properties.has_unified_memory, - exports, - ); - let blocks = match types { - // SAFETY: as above; the device enables `VK_KHR_external_memory_fd` where - // `exports` passed. - Ok(types) => match unsafe { - crate::memory::fd_image_types((&instance.raw, physical), &raw, types) - }? { - (0, dropped) => ( - Err(dropped.map_or("no memory type takes such blocks", |(_, why)| why)), - None, - ), - (kept, dropped) => (Ok(kept), dropped), - }, - Err(why) => (Err(why), None), - }; - memory.fd_buffer_blocks(blocks); - // As a dma-buf where it enables the route's extensions, which name - // `VK_KHR_external_memory_fd`, and the foreign family its acquire names. - let dma_buf_functions = functions.filter(|_| dma_buf && foreign_family); - let handle = crate::buffer_descriptor::MemoryExport::DmaBuf; - // SAFETY: as above. - let dma_buf_export = unsafe { - crate::exported_memory::FdExport::new( - &instance.raw, - physical, - dma_buf_functions, - (usage, handle), - ) - }; - // The own buffers' exportable blocks are exportable as dma-bufs too where the device - // exports a pooled buffer's memory of those usages as both, so that the buffers that - // declare their padding unobserved lie there (`memory.rs`'s `FD_BLOCKS_DMA_BUF`). - let usages: Vec<_> = usages.into_iter().flatten().collect(); - // SAFETY: as above. - memory.fd_blocks_dma_buf(unsafe { - crate::exported_memory::fd_blocks_dma_buf( - &instance.raw, - physical, - dma_buf_export.as_ref(), - &usages, - ) - }); - (opaque, dma_buf_export) - }; - // How the device exports a timeline semaphore as an opaque file descriptor, where it - // enables `VK_KHR_external_semaphore_fd` and exports one so (`exported_semaphore.rs`). - // And a binary semaphore as a sync file, for its command buffers' completions - // (`command_buffer/sync_file.rs`). - #[cfg(unix)] - let (opaque_fd_semaphores, sync_fd_semaphores) = { - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put - // back, and the device enables the extension. - let functions = semaphore_fd.then(|| unsafe { - loader_word - .restored(|| ash::khr::external_semaphore_fd::Device::new(&instance.raw, &raw)) - }); - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later. - unsafe { - ( - crate::exported_semaphore::OpaqueFdSemaphores::new( - &instance.raw, - physical, - functions.clone(), - ), - crate::exported_semaphore::SyncFdSemaphores::new( - &instance.raw, - physical, - functions, - ), - ) - } - }; - // The host image copy functions, where the device enabled `hostImageCopy` and copies to - // and from `GENERAL` on the host: by their core names from Vulkan 1.4, else by the - // extension's, which the device then enabled. - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later. - let general = host_image_copy - && unsafe { crate::texture::host_copy::reaches_general(&instance.raw, physical) }; - let host_copies = general.then(|| { - let handle = raw.handle(); - let load = |name: &std::ffi::CStr| { - let bytes = name.to_bytes(); - let core = std::ffi::CString::new(bytes.strip_suffix(b"EXT").unwrap_or(bytes)) - .unwrap_or_default(); - // SAFETY: the device is live; a name it does not serve answers null. - let function = unsafe { - (instance.raw.get_device_proc_addr(handle, core.as_ptr())) - .or_else(|| instance.raw.get_device_proc_addr(handle, name.as_ptr())) - }; - function.map_or(std::ptr::null(), |function| { - function as *const std::ffi::c_void - }) - }; - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put - // back. - unsafe { loader_word.restored(|| ash::ext::host_image_copy::DeviceFn::load(load)) } - }); - // The mesh draw commands, which exist where `meshShader` is enabled (it needs - // `VK_EXT_mesh_shader`). - let mesh_draws = if enabled - .features - .contains(&metal2vulkan::device::VkFeature::MeshShader) - { - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put - // back. - let loaded = unsafe { - loader_word.restored(|| ash::ext::mesh_shader::Device::new(&instance.raw, &raw)) - }; - Some(MeshDraws::new(&loaded, recording.as_ref())) - } else { - None - }; - // The multi-draw commands, where a rate-mapped pass may draw its regions with them - // (`rate_mapped_pass.rs`). - let multi_draws = { - use metal2vulkan::device::VkFeature as F; - let needs = [ - F::MultiDraw, - F::MultiViewport, - F::ShaderOutputViewportIndex, - F::ShaderDrawParameters, - ]; - match needs.iter().all(|f| enabled.features.contains(f)) { - true => { - let mut multi = vk::PhysicalDeviceMultiDrawPropertiesEXT::default(); - let mut properties = - vk::PhysicalDeviceProperties2::default().push_next(&mut multi); - // SAFETY: `physical` belongs to `instance`, created at Vulkan 1.2 or later, - // and the device enabled `VK_EXT_multi_draw`, whose properties these are. - unsafe { - instance - .raw - .get_physical_device_properties2(physical, &mut properties) - }; - let copies = multi.max_multi_draw_count.saturating_sub(1); - let batch = limits.max_viewports.min(copies); - (batch >= 2).then(|| { - // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the - // word is put back. - let loaded = unsafe { - loader_word - .restored(|| ash::ext::multi_draw::Device::new(&instance.raw, &raw)) - }; - MultiDraws::new(&loaded, recording.as_ref(), [batch, copies]) - }) - } - false => None, - } - }; - // The indirect-count draw commands, where a draw the GPU routes records its routes with - // them (`render/gpu_routes.rs`): `multiDrawIndirect` makes `maxDrawIndirectCount` at - // least 65535, past any count a route reads. - let count_draws = { - use metal2vulkan::device::VkFeature as F; - let needs = [F::DrawIndirectCount, F::MultiDrawIndirect]; - (needs.iter().all(|f| enabled.features.contains(f))) - .then(|| CountDraws::new(&raw, recording.as_ref())) - }; - let budget = |header| { - crate::gpu_pools::pool_budget( - &memory_properties, - limits.max_storage_buffer_range, - max_allocation, - header, - ) - }; - let index_header = metal2vulkan::bind::IndexBoundsPass::POOL_HEADER_BYTES; - // The index pool's bytes are a `u32`'s, its counter's. - let index_pool_bytes = budget(index_header).min(u64::from(u32::MAX) / 4 * 4); - let gpu_pools = GpuPools::new(index_pool_bytes, budget(0)); - let copy_images_bytes = crate::gpu_pools::device_share(&memory_properties); - // From the host's clock where the options say, and on a driver whose timestamps wait for - // every queue's whatever they say (`gpu_time.rs`). - let from_host = if gpu_times_from_host { - Some(FromHost::Asked) - } else if properties - .description - .driver_facts() - .contains(&metal2vulkan::device::DriverFact::TimestampsWaitForEveryQueue) - { - Some(FromHost::Driver) - } else { - None - }; - // What completed work wrote is made visible to a batch by a barrier where semaphore - // operations stall the driver's submissions, else by waits (`command_buffer/submit.rs`). - let completed_by_barrier = properties - .description - .driver_facts() - .contains(&metal2vulkan::device::DriverFact::SemaphoreOperationsStallSubmits); - // A use of an image after a write through a buffer over its memory goes in a new - // `VkCommandBuffer` where the driver's image uses miss such writes inside one - // (`alias_split.rs`). - let splits_at_aliases = - crate::alias_split::splits_at_aliases(&properties.description.driver_facts()); - // One timestamp pool at most where each is one of Metal's scarce counter sample buffers. - let scarce_pools = properties - .description - .driver_facts() - .contains(&metal2vulkan::device::DriverFact::TimestampPoolsAreCounterSampleBuffers); - let timing = Timing::new( - timestamp_bits, - limits.timestamp_period, - calibrated, - from_host, - scarce_pools, - // A command buffer's first encoder writes its start where its first batch can begin - // with no command buffer of barriers (`gpu_time.rs`). - !completed_by_barrier, - // Its slots are reset on the host where the device enables `hostQueryReset`: every - // device the runtime created (`enables.rs`). - owned, - ); - let shader_cache = match ShaderCache::start( - cache, - &physical_properties, - compile.profile_fingerprint(), - (instance.settings, creation_feedback), - instance.sink().cloned(), - ) { - Ok(shader_cache) => shader_cache, - Err(error) => { - scheduler.stop(); - completion.stop(); - contexts.stop(); - undo(&timelines); - return Err(error); - } - }; - // The device's driver and layers are loaded and primed: the exit hook, registered (again) - // after them when the device can have made statics since its last registration, runs - // before their destructors. - exit_guard::register_device(guard_identity, primes); - let in_process = properties.kind == DeviceKind::Cpu; - // A device whose driver reports a command buffer's execution failure through the - // instance's messenger alone, and whose instance has the relay, has its queues' failures - // relayed to the command buffers that failed (`relay.rs`), from its first batch on. The - // question is the driver's, and the fact answers it, never the driver's name: a defect - // fact, so a driver with a row takes it at every release and on every GPU. - let lost = Arc::new(AtomicBool::new(false)); - let relays = (properties.description.driver_facts()) - .contains(&metal2vulkan::device::DriverFact::QueueFailuresReportedByMessenger); - // Read before the properties move into the device's shared state (below): whether the - // scheduler's thread waits for the GPU itself (`scheduler::waits_on_gpu`). - let waits_on_gpu = crate::scheduler::waits_on_gpu(&properties.driver_defects); - // And whether a spare command pool is trimmed after its frees: not where a trim fails the - // kept barriers (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`, - // `spares.rs`). - let trims_spares = !properties - .driver_defects - .contains(&RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission); - if let (Some(relay), true) = (instance.relay(), relays) { - for slot in &queues { - let queue = slot.with(|queue| queue); - // SAFETY: the queue is the device's, live, and its word was put back just now. - let flights = - Arc::new(unsafe { Flights::new(queue, functions.clone(), lost.clone()) }); - if slot.flights.set(Arc::clone(&flights)).is_ok() { - relay.watch(flights); - } - } - } - // The blocks of its memory that go are freed on a thread of the device's, counted against - // its heaps and its allocations until they are (`free_thread.rs`). - let functions = Arc::new(functions); - let frees = Arc::new(crate::free_thread::FreeThread::new(Arc::clone(&functions))); - memory.post_frees_to(Arc::clone(&frees)); - // Its kept empty blocks go once their time passed, on its idle sweep's thread where no - // call of the program's comes (`idle_sweep.rs`). - let idle_sweep = crate::idle_sweep::IdleSweep::default(); - memory.sweep_through(idle_sweep.due()); - (allocations.allocations).wait_for_frees_on(Arc::clone(&frees)); - // The device's line: a new one for a device made now, else the line this generation - // recovers, whose address space, resource IDs, identifiers and counts it goes on with - // (`line.rs`). - let views = Arc::new(crate::view_check::ViewCheck::new( - properties.description.clone(), - *compile.policy(), - )); - let invariant = line::Invariant { - properties, - compile, - enabled, - extensions, - cache_directory: shader_cache.directory_root(), - views, - }; - let line = match recovering { - Some(line) => line, - None => line::Line::new( - holds::holds(), - invariant.clone(), - Announced::new(&announce_each), - recipe, - ), - }; - let carried = &line.carried; - let announced = Arc::clone(&carried.announced); - let resource_ids = Arc::clone(&carried.resource_ids); - let passing_holds = Arc::clone(&carried.passing_holds); - let sampler_ids = lock(&resource_ids).sampler_id_reads(); - let depth_ranges = DepthRanges::of(invariant.compile.profile()); - let lineage = Arc::clone(&line.lineage); - let generation = lineage.made(); - let region_ledger = Arc::new(crate::pipeline::region_ledger::RegionLedger::new( - crate::pipeline::region_ledger::DEVICE_REGION_PIPELINES, - Arc::clone(&carried.counts), - )); - let shared = Arc::new(DeviceShared { - addresses: Arc::clone(&carried.addresses), - identifiers: Arc::clone(&carried.identifiers), - counts: Arc::clone(&carried.counts), - queue_quiet, - holds: Arc::clone(&line.holds), - line, - lineage, - generation, - instance, - physical, - functions, - queue_family, - round_robin: queues.len() - present_queues - usize::from(copy_slot.is_some()), - copy_slot, - queues: queues.into(), - queue_families, - buffer_families, - round_robin_made: AtomicU64::new(0), - presenting_made: AtomicU64::new(0), - planned, - least_plan, - presenting_asked: AtomicU64::new(0), - program_queues_made: AtomicU64::new(0), - program_queues_live: AtomicU64::new(0), - queue_switch: Arc::new(crate::queue_share::QueueSwitch::new( - invariant.compile.policy().queue_sharing, - )), - depth_ranges, - invariant, - announced, - lowering_refuses, - deferred: crate::render::DeferredEncoders::default(), - record_executions, - encoder_trail: encoder_trail || metal2vulkan::env_vars::encoder_trail(), - driver_splits_at_aliases: splits_at_aliases, - load_no_dynamic_library_file, - views_epoch: AtomicU64::new(0), - pipeline_recording: crate::warm::Recording::new(pipeline_records), - warmer: crate::warm::Warmer::default(), - device_address, - upload_alignment, - dynamic_buffers: [ - limits.max_descriptor_set_uniform_buffers_dynamic, - limits.max_descriptor_set_storage_buffers_dynamic, - ], - memory: Arc::new(Mutex::new(memory)), - recycled_buffers: Arc::new(Mutex::new(Recycler::new(recycle::BUFFERS))), - resource_ids, - passing_holds, - keepers: Keepers::default(), - sampler_ids, - samplers: Mutex::default(), - sampler_count: SamplerCount::new(sampler_limit), - allocations, - frees, - sampler_sets: Mutex::default(), - heaps: Mutex::default(), - function_tables: Mutex::default(), - internal: Mutex::new(None), - internal_done: OwnTimeline::default(), - completed_by_barrier, - by_ends, - bound_at: Mutex::new(None), - staging, - fill_queue, - extra_queues, - reserved_queues, - scheduler, - nudge, - completion, - fences: Arc::default(), - contexts, - loader_word: Arc::new(loader_word), - owned, - lost, - stopped: OnceLock::new(), - textures, - shader_cache, - in_place: crate::in_place::InPlaceChecks::new( - fail_in_place_check, - limits.non_coherent_atom_size, - ), - tiling: crate::tiling_check::TilingCheck::new(), - submit_checks: Arc::new(crate::submit_check::SubmitChecks::new( - assume_submissions_merge, - )), - host_import, - #[cfg(unix)] - opaque_fd, - #[cfg(unix)] - dma_buf_export, - #[cfg(unix)] - opaque_fd_semaphores, - #[cfg(unix)] - sync_fd_semaphores, - shared_pointer_imports: OnceLock::new(), - extended_dynamic_state, - sized_index_bind, - mesh_draws, - multi_draws, - count_draws, - push_descriptor, - pushes_after_pipeline_binds, - color_write_masks, - recording, - snapshot_fallbacks: Mutex::new(Vec::new()), - reader_sizes: Mutex::new(Default::default()), - gpu_pools, - copy_images_bytes, - max_framebuffer: [ - limits.max_framebuffer_width, - limits.max_framebuffer_height, - limits.max_framebuffer_layers, - ], - region_limits: RegionLimits::new( - limits.max_viewport_dimensions, - limits.viewport_bounds_range, - ), - standard_sample_locations: limits.standard_sample_locations == vk::TRUE, - layered_rate_map_released: AtomicBool::new(false), - mutable_rate_map_called: AtomicBool::new(false), - sparse_image_made: AtomicBool::new(false), - gpu_work: AtomicU64::new(0), - dynamic_multi_variable: OnceLock::new(), - owned_kernels: Mutex::new(OwnedKernels::default()), - route_counts_begun: AtomicBool::new(false), - ycbcr_formats, - mipmap_scratch: Mutex::default(), - planes: Mutex::new(PlanesObjects::default()), - interleave: Mutex::default(), - kept: Mutex::default(), - region_ledger, - shader_modules: Mutex::default(), - words_digests: Mutex::new(crate::pipeline::WordsDigests::counted( - crate::pipeline::WORDS_DIGESTS, - )), - pipeline_layouts: Mutex::default(), - flights: crate::pipeline::flight::Flights::default(), - color_resolves: Mutex::new(ColorResolveObjects::default()), - stencil_copies: Mutex::new(StencilCopyObjects::default()), - depth_copies: Mutex::new(DepthCopyObjects::default()), - depth_stencil_resolves: Mutex::new(DepthStencilResolveObjects::default()), - attachmentless: Mutex::default(), - render_passes: Mutex::default(), - interop: Interop::default(), - heap_keys: Default::default(), - rebinds: Default::default(), - aliases: Default::default(), - host_ram: Default::default(), - copied, - modified: Default::default(), - gpu_writes: Default::default(), - #[cfg(test)] - failing_host_imports: Default::default(), - #[cfg(test)] - failing_submissions: Default::default(), - #[cfg(test)] - failing_result: Default::default(), - #[cfg(test)] - submit_call_pause: Default::default(), - #[cfg(test)] - submit_call_fast: Default::default(), - #[cfg(test)] - slow_calls_from: Default::default(), - #[cfg(test)] - linear_rule_forced: Default::default(), - #[cfg(test)] - aliases_split_forced: Default::default(), - #[cfg(test)] - linear_feedback_withheld: Default::default(), - #[cfg(test)] - leading_snapshots_withheld: Default::default(), - #[cfg(test)] - storage_costs_forced: Default::default(), - #[cfg(test)] - sampled_costs_forced: Default::default(), - #[cfg(test)] - managed_inline_bound: crate::managed::INLINE_BYTES.into(), - #[cfg(test)] - uploads_unbarriered_forced: Default::default(), - #[cfg(test)] - upload_scopes: Default::default(), - #[cfg(test)] - read_twin_unguarded: Default::default(), - #[cfg(test)] - read_twin_unproven: Default::default(), - #[cfg(test)] - store_out_unfaulted: Default::default(), - #[cfg(all(test, unix))] - plane_route_forced: Default::default(), - #[cfg(all(test, unix))] - explicit_plane_pitch_misread_forced: Default::default(), - #[cfg(test)] - linear_pitch_rule_forced: Default::default(), - #[cfg(test)] - test_queue_limits: Default::default(), - dirty: Default::default(), - standings: Default::default(), - fresh: Default::default(), - owners: Default::default(), - live_buffers: Default::default(), - carry: Default::default(), - residency: Default::default(), - #[cfg(unix)] - dma_buf_files: Default::default(), - idle_sweep, - begin_ahead: Default::default(), - timing, - view_reinterpretation, - generated_commands, - host_image_copy, - host_copies, - zero_initialize_device_memory, - sparse, - spares: Spares::new(trims_spares), - live_binds: Default::default(), - coverage_pools: Default::default(), - live_dispatches: Default::default(), - spare_states: Default::default(), - usage_shadows_made: Default::default(), - face_swaps: Default::default(), - heap_textures_end: Default::default(), - bind_memos: Default::default(), - cores: Default::default(), - draw_rooms: Default::default(), - kept_rooms: Default::default(), - parking: parking.map_or_else(OnceLock::new, OnceLock::from), - uncommitted: Arc::default(), - pipeline_pool: Default::default(), - reaper: Default::default(), - trails: Arc::default(), - recoveries: Arc::default(), - libraries: graphics_pipeline_library.then(Default::default), - }); - // A CPU device runs the work submitted to it on the process's own threads: the exit hook - // waits for that work before the destructors run under it (`exit_guard`). - if in_process { - let device: Weak = Arc::::downgrade(&shared); - exit_guard::runs_in_process(device); - } - // The scheduler's thread waits for the GPU itself where heads wait for signals to land, - // but not where the driver loses a signal that lands while its wait for any of several - // objects registers a later one (`RuntimeDriverDefect::WaitForAnyObjectLosesASignal`, - // `driver_defects.rs`): there the turns wake it. A defect fact, never the driver's name. - if waits_on_gpu { - (shared.scheduler).wait_on_gpu(Functions::clone(&shared.functions), shared.nudge); - } - // Where the driver stalls in one signalling submission of every 1024 to a `VkQueue` - // (`DriverFact::SignallingSubmitsStallEvery1024`), the scheduler's thread takes the - // stalls while idle, each queue's empty submissions signalling a semaphore of its own - // (`submit_stalls.rs`); a device that cannot make the semaphores takes none. - let stalls = metal2vulkan::device::DriverFact::SignallingSubmitsStallEvery1024; - if shared.invariant.properties.driver_facts.contains(&stalls) { - if let Some(semaphores) = submit_stalls::semaphores(shared.vk(), shared.queues.len()) { - let functions = Functions::clone(&shared.functions); - let queues = Arc::clone(&shared.queues); - let idle = submit_stalls::IdleStalls::new(functions, queues, semaphores); - shared.scheduler.take_stalls_idle(idle); - } - } - // The line serves its first generation; a recovery's serves it once it is made. - shared.line.first(&shared); - let device = holds::program(shared); - // What the device allocated ahead goes back once its allocations come near the limit. - device.give_back_ahead_near_the_limit(); - // The verdicts of its check of textures over host pages, where a record holds them. - device.recall_in_place_checks(); - // Its check's verdict of the GPU idling between `VkQueue`s, where none is to be measured - // or a record holds it (`queue_share.rs`). - device.recall_queue_switch_check(); - // Its submission checks' verdicts, where a record holds them; else the checks start - // (`submit_check.rs`). - device.recall_submit_checks(); - // Its view check's facts, where a record holds them; else the check starts - // (`view_check.rs`). In the runtime's own tests, the options' facts. - #[cfg(test)] - let forced = view_facts; - #[cfg(not(test))] - let forced = None; - device.recall_view_check(forced); - device.degrade_argument_buffers_unread(); - device.degrade_float_tininess(); - Ok(device) - } -} - -impl exit_guard::InProcess for DeviceShared { - /// Wait on each `VkQueue`'s timeline for the value of the last batch submitted there. - fn drain(&self, deadline: Option) -> bool { - let (timelines, values): (Vec, Vec) = self - .queues - .iter() - .map(|queue| (queue.timeline, queue.submitted_value())) - .filter(|&(_, value)| value != 0) - .unzip(); - if timelines.is_empty() { - return true; - } - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&timelines) - .values(&values); - // No deadline is the longest timeout, `UINT64_MAX` nanoseconds. - let timeout = deadline.map_or(u64::MAX, |deadline| { - let left = deadline.saturating_duration_since(Instant::now()); - u64::try_from(left.as_nanos()).unwrap_or(u64::MAX) - }); - // SAFETY: the timelines are the device's, live while this handle holds it; a wait for - // values already signalled or submitted to be (each batch signals its queue's). - let waited = unsafe { self.vk().wait_semaphores(&info, timeout) }; - waited.is_ok() - } -} - -/// The runtime error of a refusal by the compile layer's device: an unsupported device is -/// `Unsupported`, anything else (an inconsistent description) `Compile`. -pub(super) fn device_error(error: metal2vulkan::error::Error) -> Error { - match error { - metal2vulkan::error::Error::Unsupported(unsupported) => Error::Unsupported(unsupported), - other => Error::Compile(other), - } -} diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs deleted file mode 100644 index 051f84bca..000000000 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ /dev/null @@ -1,1712 +0,0 @@ -//! Priming a new device for the exit guard: before the exit hook is registered for it, the creating -//! thread makes the first call of each Vulkan entry point the runtime calls in its sections, the -//! exit guard's table ([`Call`]), shaped as the runtime makes it. A driver or layer that makes a -//! static at such a call's first use (the validation layer's table of stages by queue flags, which -//! its synchronization checks read in barriers, submissions and waits) registers the static's -//! destructor then, before the hook, which therefore runs first. So neither a section in progress -//! as the process exits, nor the program's own calls before it, is the first to make such a static. -//! -//! **Only a device that registers the hook is primed** (`exit_guard::before_priming`): the -//! process's first device, the first after a load of a shared object, and one of an identity new -//! since. A device made again on what stays loaded, after a device of its identity registered, -//! registers nothing, and its calls are not the first: the earlier device's priming made each. -//! Priming costs a device's making the driver's time for its objects: on NVIDIA's 620.70.06 on -//! the RTX 3090, 120 to 160 ms, nearly all in `vkCreateIndirectCommandsLayoutEXT` (112 to 144 ms) -//! where the device generates commands, so a device made again there takes that much less. -//! -//! Measured: without it, at 175dd511 on lavapipe x86_64, an exit right after committing 256 -//! command buffers ended by `SIGSEGV` in one of 10 rounds. The core's stack: the scheduler's -//! `vkCmdPipelineBarrier` (its first submission's barriers) faulting inside the validation -//! layer, a static it reads made after the hook's last registration and destroyed first. -//! -//! **The set is the table's, checked.** Inside a section the device's functions are the table's -//! alone (`functions.rs`), and each priming checks, in builds with debug assertions, that it made -//! every entry point of the table but [`UNPRIMED`]: an entry point added to the table and not made -//! here fails every lane at its first device. The calls: a batch's (a command pool and a command -//! buffer of it, begun, with the barrier every batch ends with and, where the queue family writes -//! timestamps, the reset and the two timestamps of a command buffer's GPU times -//! ([`TIMESTAMP_CALLS`], made only there; their reset on the host before, where the device enables -//! `hostQueryReset`, [`HOST_QUERY_RESET_CALLS`]), ended, submitted after each queue's timeline at 0 -//! and signalling a timeline of its own and a new fence; the wait for the timeline, a read of every -//! timeline, the wait for the fence and its reset, a wait for the queue to be idle (its drain after -//! a failed wait), and the read of the two timestamps and, where the device calibrates them, a -//! calibration reading ([`CALIBRATION_CALLS`]), as a completion turn makes them); a sampler, an -//! occlusion query pool, a buffer in host-visible memory, mapped (and, where the device has device -//! addresses, [`DEVICE_ADDRESS_CALLS`], its address read), and an image with their memory and -//! views, a depth image, a render pass of each form (`vkCreateRenderPass`, `vkCreateRenderPass2`) -//! and a framebuffer, a descriptor set layout, a pipeline -//! layout with a push constant range and a descriptor pool with a set written (and reset before its -//! release), and a compute -//! pipeline made with a pipeline cache from a shader module, its stage specialized as the runtime's -//! makings are ([`SPECIALIZED`]), whose data is read; a command buffer, recorded and never -//! submitted, with what a host step records: the pipeline and the set bound (and, where the device -//! has the push command, the set's write pushed first, [`PUSH_DESCRIPTOR_CALLS`]), a push constant, -//! a dispatch and one from the buffer's arguments, a copy within the buffer, a copy from the buffer -//! to the image and back with a barrier between them, a copy between the image's texels and the -//! image's clear (a render host step's pass steps) and the depth image's (a batch's first work's), -//! then a render host step's: a graphics pipeline that rasterizes nothing, its stage specialized -//! too (and named, where the instance reports messages, [`NAMING_CALLS`]), drawn in a secondary -//! command buffer, directly and from the buffer's arguments, with a -//! vertex buffer and the states a draw sets, inside a query of the occlusion pool, which the render -//! pass's subpass executes; where the queues bind sparse memory, an empty `vkQueueBindSparse` -//! ([`SPARSE_CALLS`]); a wait for the device to be idle; and the release of each object made. -//! Nothing of it outlives the call. -//! -//! **Specialized, with an extended instruction, as the runtime's makings are.** A stage with -//! specialization constants takes paths of its own: in a driver's compiler, and in the Khronos -//! validation layer's checks of the stage, which run `spirv-opt`'s passes and the SPIR-V validator -//! over the module specialized at each pipeline's creation. A module the layer validated before, in -//! any process, it skips at its creation (its validation cache, kept on disk), and priming's are -//! the same in every process: so without a specialized stage, priming ran no validator at all, and -//! the process's first making of a specialized pipeline made the validator's statics. And the -//! validator makes one of them only at an operand naming an untyped definition made before it, -//! such as an extended instruction's set: so priming's modules take `GLSL.std.450`'s `UMin` of -//! their constant, as translated modules take that set's instructions. Measured on the M3 Max -//! (macOS 27.0.1, MoltenVK 1.4.1, the layer and `spirv-tools` 1.4.357.0 from Homebrew), in a lane -//! process that exited while a pool's making of a host step's variant was in progress: `SIGSEGV` at -//! `0x50` inside `spvtools::val::InstructionCanHaveTypeOperand`, its function-local -//! `std::unordered_set` already destroyed (`CoreChecks::ValidateShaderStage`, from -//! `vkCreateComputePipelines` on the pool's thread, in its making section). A diagnostic interposer -//! of the C library's exit handlers showed the validator's two such sets (that one and -//! `InstructionRequiresTypeOperand`'s) made after the hook's first registration in each of 10 runs, -//! the second after its last, by a making on the program's thread or the pool's; with priming -//! specialized and taking the extended instruction, both made in priming, before the hook's first -//! registration, in each of 10. -//! -//! Priming makes each entry point once, in the runtime's shapes; it cannot promise that a layer -//! makes no new static on a code path a later call takes with other parameters. The calls it made -//! count as the first since the load (`exit_guard::primed`), and a section's first call of an -//! entry point it did not make registers the hook again; a static a later call makes is the -//! hook's hole (`exit_guard`, "Registered again"). - -use crate::draw_source::SizedIndexBind; -use crate::dynamic_state::{ColorWriteMasks, ExtendedDynamicState}; -use crate::error::{vulkan, Error}; -use crate::exit_guard::{Call, Calls}; -use crate::generated_commands::{ - Commands, ExecutionSetCreateInfo, ExecutionSetPipelineInfo, ExecutionSetToken, - LayoutCreateInfo, LayoutToken, EXECUTION_SET_PIPELINES, INDIRECT_BINDABLE, TOKEN_DISPATCH, - TOKEN_EXECUTION_SET, -}; -use crate::gpu_time::Calibration; -use crate::loader_word::DeviceWord; -use crate::memory; -use crate::release::{self, Generated, Released}; -use crate::sharing::Sharing; -use crate::tracker::Barrier; -use ash::vk; -use std::time::{Duration, Instant}; - -use super::functions::Vk; -use super::QueueSlot; - -/// The table's entry points priming cannot make before the hook is registered for the device it -/// primes: the release of a device, an instance and a messenger, the commands of a mesh draw -/// and of an execution of commands the GPU generates, which take pipelines of their own kinds, and -/// the layout of a linear image, of which a device need make none of any format. The first -/// release of each in the process, the first call of each command in a section, and the first -/// layout read in a section, registers the hook again as its section ends -/// (`exit_guard::called`). -pub(crate) const UNPRIMED: [Call; 9] = [ - Call::DestroyDevice, - Call::DestroyDebugUtilsMessenger, - Call::DestroyInstance, - Call::CmdDrawMeshTasks, - Call::CmdDrawMeshTasksIndirect, - Call::CmdDrawMeshTasksIndirectCount, - Call::CmdExecuteGeneratedCommands, - Call::CmdPreprocessGeneratedCommands, - Call::GetImageSubresourceLayout, -]; - -/// The table's entry points a queue family that writes no timestamps (`timestampValidBits` 0) -/// never calls, nor primes: a command buffer's GPU times (`gpu_time.rs`). -pub(crate) const TIMESTAMP_CALLS: [Call; 3] = [ - Call::CmdResetQueryPool, - Call::CmdWriteTimestamp, - Call::GetQueryPoolResults, -]; - -/// The table's entry points a device that writes no timestamps, or does not enable -/// `hostQueryReset` (an adopted one), never calls, nor primes: a timestamp slot's reset on the -/// host (`gpu_time.rs`). -pub(crate) const HOST_QUERY_RESET_CALLS: [Call; 1] = [Call::ResetQueryPool]; - -/// The table's entry points a device without device addresses (`bufferDeviceAddress`) never -/// calls, nor primes: a buffer's address (`buffer.rs`). -pub(crate) const DEVICE_ADDRESS_CALLS: [Call; 1] = [Call::GetBufferDeviceAddress]; - -/// The table's entry points a device without `VK_EXT_device_generated_commands` never calls, -/// nor primes: the release of the extension's objects (`generated_commands.rs`). -pub(crate) const GENERATED_COMMANDS_CALLS: [Call; 2] = [ - Call::DestroyIndirectExecutionSet, - Call::DestroyIndirectCommandsLayout, -]; - -/// The table's entry points a device that binds no sparse memory never calls, nor primes: a -/// batch's sparse binding (`sparse/bind.rs`). -pub(crate) const SPARSE_CALLS: [Call; 1] = [Call::QueueBindSparse]; - -/// The table's entry points a device without the push command (Vulkan 1.4, or -/// `VK_KHR_push_descriptor`) never calls, nor primes: a host step's set 0 pushed -/// (`pipeline::objects::pushes_set_zero`). -pub(crate) const PUSH_DESCRIPTOR_CALLS: [Call; 1] = [Call::CmdPushDescriptorSet]; - -/// The table's entry points a device that calibrates no timestamps never calls, nor primes: a -/// completion turn's calibration reading (`gpu_time.rs`). -pub(crate) const CALIBRATION_CALLS: [Call; 1] = [Call::GetCalibratedTimestamps]; - -/// The table's entry points a device whose instance reports no messages never calls, nor primes: -/// a graphics pipeline's debug name (`pipeline/graphics.rs`). -pub(crate) const NAMING_CALLS: [Call; 1] = [Call::SetDebugUtilsObjectName]; - -/// The table's entry points a device without extended dynamic state (Vulkan 1.3, or -/// `VK_EXT_extended_dynamic_state`) never calls, nor primes: a render encoder's dynamic states -/// (`dynamic_state.rs`). -pub(crate) const EXTENDED_DYNAMIC_STATE_CALLS: [Call; 9] = [ - Call::CmdSetCullMode, - Call::CmdSetFrontFace, - Call::CmdSetPrimitiveTopology, - Call::CmdBindVertexBuffers2, - Call::CmdSetDepthTestEnable, - Call::CmdSetDepthWriteEnable, - Call::CmdSetDepthCompareOp, - Call::CmdSetStencilTestEnable, - Call::CmdSetStencilOp, -]; - -/// The table's entry points a device without a dynamic primitive restart (Vulkan 1.3, or -/// `VK_EXT_extended_dynamic_state2`) never calls, nor primes (`dynamic_state.rs`). -pub(crate) const PRIMITIVE_RESTART_CALLS: [Call; 1] = [Call::CmdSetPrimitiveRestartEnable]; - -/// The table's entry points a device without the dynamic color write mask never calls, nor -/// primes: a snapshot draw's masks (`dynamic_state.rs`, `render/snapshot.rs`). -pub(crate) const COLOR_WRITE_MASK_CALLS: [Call; 1] = [Call::CmdSetColorWriteMask]; - -/// The table's entry points a device without `maintenance5` never calls, nor primes: an index -/// buffer bound with its size (`draw_source.rs`). -pub(crate) const SIZED_INDEX_BIND_CALLS: [Call; 1] = [Call::CmdBindIndexBuffer2]; - -/// The table's entry points a device that converts no YCbCr format itself never calls, nor -/// primes: the release of a YCbCr sample kernel's conversion (`ycbcr_device.rs`). -pub(crate) const YCBCR_CONVERSION_CALLS: [Call; 1] = [Call::DestroySamplerYcbcrConversion]; - -/// The debug name of a render host step's pipeline that priming makes, where the instance reports -/// messages ([`NAMING_CALLS`]). -const PRIMING_PIPELINE: &std::ffi::CStr = - c"metal2vulkan: a priming pipeline that rasterizes nothing"; - -/// The debug name of a compute pipeline that priming makes, as [`PRIMING_PIPELINE`]. -const PRIMING_KERNEL: &std::ffi::CStr = c"metal2vulkan: a priming kernel"; - -/// The debug name of the indirect-bindable compute pipeline that priming makes for -/// device-generated commands, as [`PRIMING_PIPELINE`]. -const PRIMING_GENERATED_KERNEL: &std::ffi::CStr = - c"metal2vulkan: a priming kernel of device-generated commands"; - -/// The longest the priming submission is waited for: it holds two barriers. -const LIMIT: Duration = Duration::from_secs(10); - -/// How long one wait lasts before it is repeated, as a queue waiter's. -const WAIT_SLICE: Duration = Duration::from_millis(100); - -/// The smallest compute shader with a specialization constant ([`SPECIALIZED`]) and an extended -/// instruction: `main`, of one invocation, takes `GLSL.std.450`'s `UMin` of the constant and -/// returns (SPIR-V 1.0). Also the words of a host step's own module in -/// `tests/teardown_threads.rs`. -pub(crate) const SHADER: [u32; 60] = [ - 0x0723_0203, - 0x0001_0000, - 0, - 10, - 0, - // OpCapability Shader - 0x0002_0011, - 1, - // %8 = OpExtInstImport "GLSL.std.450" - 0x0006_000b, - 8, - 0x4c53_4c47, - 0x6474_732e, - 0x3035_342e, - 0, - // OpMemoryModel Logical GLSL450 - 0x0003_000e, - 0, - 1, - // OpEntryPoint GLCompute %1 "main" - 0x0005_000f, - 5, - 1, - 0x6e69_616d, - 0, - // OpExecutionMode %1 LocalSize 1 1 1 - 0x0006_0010, - 1, - 17, - 1, - 1, - 1, - // OpDecorate %5 SpecId 0 - 0x0004_0047, - 5, - 1, - 0, - // %2 = OpTypeVoid; %3 = OpTypeFunction %2 - 0x0002_0013, - 2, - 0x0003_0021, - 3, - 2, - // %6 = OpTypeInt 32 0; %5 = OpSpecConstant %6 0 - 0x0004_0015, - 6, - 32, - 0, - 0x0004_0032, - 6, - 5, - 0, - // %1 = OpFunction %2 None %3; %4 = OpLabel; %9 = OpExtInst %6 %8 UMin %5 %5; OpReturn; - // OpFunctionEnd - 0x0005_0036, - 2, - 1, - 0, - 3, - 0x0002_00f8, - 4, - 0x0007_000c, - 6, - 9, - 8, - 38, - 5, - 5, - 0x0001_00fd, - 0x0001_0038, -]; - -/// The smallest vertex shader with a specialization constant ([`SPECIALIZED`]) and an extended -/// instruction: `main` takes `GLSL.std.450`'s `UMin` of the constant and returns (SPIR-V 1.0), for -/// a pipeline that rasterizes nothing. -const VERTEX_SHADER: [u32; 54] = [ - 0x0723_0203, - 0x0001_0000, - 0, - 10, - 0, - // OpCapability Shader - 0x0002_0011, - 1, - // %8 = OpExtInstImport "GLSL.std.450" - 0x0006_000b, - 8, - 0x4c53_4c47, - 0x6474_732e, - 0x3035_342e, - 0, - // OpMemoryModel Logical GLSL450 - 0x0003_000e, - 0, - 1, - // OpEntryPoint Vertex %1 "main" - 0x0005_000f, - 0, - 1, - 0x6e69_616d, - 0, - // OpDecorate %5 SpecId 0 - 0x0004_0047, - 5, - 1, - 0, - // %2 = OpTypeVoid; %3 = OpTypeFunction %2 - 0x0002_0013, - 2, - 0x0003_0021, - 3, - 2, - // %6 = OpTypeInt 32 0; %5 = OpSpecConstant %6 0 - 0x0004_0015, - 6, - 32, - 0, - 0x0004_0032, - 6, - 5, - 0, - // %1 = OpFunction %2 None %3; %4 = OpLabel; %9 = OpExtInst %6 %8 UMin %5 %5; OpReturn; - // OpFunctionEnd - 0x0005_0036, - 2, - 1, - 0, - 3, - 0x0002_00f8, - 4, - 0x0007_000c, - 6, - 9, - 8, - 38, - 5, - 5, - 0x0001_00fd, - 0x0001_0038, -]; - -/// The constant [`SHADER`] and the vertex shader declare, specialized as the runtime's makings -/// specialize their modules' (`pipeline/objects.rs`, `pipeline/graphics.rs`): a specialized stage -/// takes paths of its own, in a driver's compiler and in a layer's checks of the stage, which a -/// making then reaches first (the module docs). -const SPECIALIZED: [vk::SpecializationMapEntry; 1] = [vk::SpecializationMapEntry { - constant_id: 0, - offset: 0, - size: 4, -}]; - -/// The value of [`SPECIALIZED`]'s constant. -const SPECIALIZED_VALUE: [u8; 4] = 1u32.to_le_bytes(); - -/// The specialization of each priming stage: [`SPECIALIZED`] at [`SPECIALIZED_VALUE`]. -fn specialization() -> vk::SpecializationInfo<'static> { - vk::SpecializationInfo::default() - .map_entries(&SPECIALIZED) - .data(&SPECIALIZED_VALUE) -} - -/// What the device primed has: a queue family that writes timestamps, `hostQueryReset`, device -/// addresses, `VK_EXT_device_generated_commands`, sparse binding on its queues, the push command, -/// calibrated timestamps, and the render encoder's commands of [`PrimedDraws`]. -#[derive(Clone, Copy)] -pub(crate) struct Has { - pub(crate) timestamps: bool, - pub(crate) host_query_reset: bool, - pub(crate) device_addresses: bool, - pub(crate) generated_commands: bool, - pub(crate) sparse_binding: bool, - pub(crate) push_descriptor: bool, - pub(crate) calibration: bool, - pub(crate) object_names: bool, - pub(crate) extended_dynamic_state: bool, - pub(crate) primitive_restart: bool, - pub(crate) color_write_masks: bool, - pub(crate) sized_index_bind: bool, - pub(crate) ycbcr_conversion: bool, -} - -/// The commands a render encoder records that the device has where it has their feature or -/// extension, which the priming's render host step makes (a host step records them inside a -/// section). -#[derive(Clone, Copy, Default)] -pub(crate) struct PrimedDraws { - pub(crate) dynamic: Option, - pub(crate) color_write_masks: Option, - pub(crate) sized_index_bind: Option, -} - -impl PrimedDraws { - /// `has`, with what it says of these commands set from them. - pub(crate) fn has(&self, has: Has) -> Has { - Has { - extended_dynamic_state: self.dynamic.is_some(), - primitive_restart: self - .dynamic - .is_some_and(|dynamic| dynamic.primitive_restart_enable.is_some()), - color_write_masks: self.color_write_masks.is_some(), - sized_index_bind: self.sized_index_bind.is_some(), - ..has - } - } -} - -/// Prime `device` of `physical`, made from `instance`, whose queues are `queues`, the first of -/// its primary family `queue_family`, its buffers and images shared as `sharing` says, on this -/// thread; `has` says what the device has, `generated` holds the commands of -/// `VK_EXT_device_generated_commands` where it has them, `drawn` the render encoder's commands -/// it has, and `ycbcr` a Y′CbCr conversion of a format it converts, where it converts one. -/// -/// # Safety -/// -/// The device is live and enables timeline semaphores, and `bufferDeviceAddress` where `has` -/// says it has device addresses; `queues` holds at least one of its queues, which nothing else -/// uses yet; `generated` is the device's, which enables the extension and `maintenance5`; -/// `loader_word` is the device's loader word; the device enables `samplerYcbcrConversion` and -/// converts `ycbcr`'s format with its chroma location where `ycbcr` is given. -pub(super) unsafe fn prime( - instance: &ash::Instance, - physical: vk::PhysicalDevice, - device: &Vk, - loader_word: &DeviceWord, - queue_family: u32, - queues: &[QueueSlot], - sharing: Sharing<'_>, - has: Has, - generated: Option<&Commands>, - push: Option, - calibration: Option, - drawn: PrimedDraws, - ycbcr: Option>, -) -> Result<(), Error> { - let mut primer = Primer { - device, - loader_word, - sharing, - push, - calibration, - drawn, - // SAFETY: the caller's. - memory: unsafe { instance.get_physical_device_memory_properties(physical) }, - calls: Calls::NONE, - held: Vec::new(), - }; - // SAFETY: the caller's. - let primed = unsafe { - primer - .batch(queue_family, queues, has.timestamps, has.host_query_reset) - .and_then(|()| primer.objects(queue_family, has.device_addresses)) - .and_then(|()| match generated { - Some(commands) => primer.generated(commands), - None => Ok(()), - }) - .and_then(|()| primer.sparse(queues, has.sparse_binding)) - .and_then(|()| primer.ycbcr(ycbcr)) - }; - // SAFETY: the submission completed, or was never made, or the device is lost; nothing else - // uses the objects held. - unsafe { - let _ = device.device_wait_idle(); - primer.made(Call::DeviceWaitIdle); - while let Some(release) = primer.held.pop() { - let call = release(device); - primer.made(call); - } - } - // The first calls since the last load, made before the device registers the exit hook: a - // section's later call of one registers nothing again. - crate::exit_guard::primed(primer.calls); - if primed.is_ok() && cfg!(debug_assertions) { - let missing = missing(primer.calls, has); - assert!( - missing.is_empty(), - "the exit guard's entry points {missing:?} are not primed (device/prime.rs)" - ); - } - primed -} - -/// The table's entry points, but [`UNPRIMED`], those of [`TIMESTAMP_CALLS`] where the device -/// has no timestamps, those of [`HOST_QUERY_RESET_CALLS`] where it has no timestamps or does not -/// enable `hostQueryReset`, those of [`DEVICE_ADDRESS_CALLS`] where it has no device addresses, -/// those of [`GENERATED_COMMANDS_CALLS`] where it has no generated commands, those of -/// [`SPARSE_CALLS`] where it binds no sparse memory, those of [`PUSH_DESCRIPTOR_CALLS`] where it -/// has no push command, those of [`CALIBRATION_CALLS`] where it calibrates no timestamps, those -/// of [`NAMING_CALLS`] where its instance reports no messages, and those of -/// [`EXTENDED_DYNAMIC_STATE_CALLS`], [`PRIMITIVE_RESTART_CALLS`], -/// [`COLOR_WRITE_MASK_CALLS`] and [`SIZED_INDEX_BIND_CALLS`] where it has -/// not their commands, and those of [`YCBCR_CONVERSION_CALLS`] where it converts no YCbCr format, -/// that `calls` (one bit each) does not hold. -pub(crate) fn missing(calls: Calls, has: Has) -> Vec { - Call::ALL - .iter() - .copied() - .filter(|&call| { - !calls.holds(call) - && !UNPRIMED.contains(&call) - && (has.timestamps || !TIMESTAMP_CALLS.contains(&call)) - && ((has.timestamps && has.host_query_reset) - || !HOST_QUERY_RESET_CALLS.contains(&call)) - && (has.device_addresses || !DEVICE_ADDRESS_CALLS.contains(&call)) - && (has.generated_commands || !GENERATED_COMMANDS_CALLS.contains(&call)) - && (has.sparse_binding || !SPARSE_CALLS.contains(&call)) - && (has.push_descriptor || !PUSH_DESCRIPTOR_CALLS.contains(&call)) - && (has.calibration || !CALIBRATION_CALLS.contains(&call)) - && (has.object_names || !NAMING_CALLS.contains(&call)) - && (has.extended_dynamic_state || !EXTENDED_DYNAMIC_STATE_CALLS.contains(&call)) - && (has.primitive_restart || !PRIMITIVE_RESTART_CALLS.contains(&call)) - && (has.color_write_masks || !COLOR_WRITE_MASK_CALLS.contains(&call)) - && (has.sized_index_bind || !SIZED_INDEX_BIND_CALLS.contains(&call)) - && (has.ycbcr_conversion || !YCBCR_CONVERSION_CALLS.contains(&call)) - }) - .collect() -} - -/// What a render host step's priming records with ([`Primer::render_step`]): the never-submitted -/// command buffer, its pool, the render pass and framebuffer, the pipeline layout and cache, and -/// the buffer it binds as a vertex buffer. -struct RenderStep { - recorded: vk::CommandBuffer, - commands: vk::CommandPool, - render_pass: vk::RenderPass, - framebuffer: vk::Framebuffer, - layout: vk::PipelineLayout, - cache: vk::PipelineCache, - buffer: vk::Buffer, - /// The occlusion query pool, whose query the secondary begins and ends around its draw. - queries: vk::QueryPool, -} - -/// A release of an object a priming made, which answers its entry point. -type Release = Box Call>; - -/// A priming in progress. -struct Primer<'a> { - device: &'a Vk, - /// The device's loader word, put back before each call the loader serves. - loader_word: &'a DeviceWord, - /// How the device's buffers and images are shared among its queue families. - sharing: Sharing<'a>, - /// The push command, where the device has it (`binding::push_descriptor_command`). - push: Option, - /// The device's calibrated timestamps, where its queue family writes timestamps. - calibration: Option, - /// The render encoder's commands the device has. - drawn: PrimedDraws, - memory: vk::PhysicalDeviceMemoryProperties, - /// The table's entry points called, one bit each. - calls: Calls, - /// What was made, released last first. - held: Vec, -} - -impl Primer<'_> { - /// `call` was made. - fn made(&mut self, call: Call) { - self.calls = self.calls.with(call); - } - - /// Name `pipeline` `name`, where the instance reports messages ([`NAMING_CALLS`]), as a - /// making names its pipeline (`DeviceShared::name_pipeline`): the loader serves the call. - /// - /// # Safety - /// - /// `pipeline` is the device's, made by this priming, which no other thread holds. - unsafe fn name(&mut self, pipeline: vk::Pipeline, name: &std::ffi::CStr) { - let device = self.device; - let Some(object_name) = device.object_name() else { - return; - }; - let info = vk::DebugUtilsObjectNameInfoEXT::default() - .object_handle(pipeline) - .object_name(name); - // SAFETY: the caller's; the instance enables `VK_EXT_debug_utils` (it reports messages), - // and the function is the device's. - let _ = unsafe { - self.loader_word - .restored(|| object_name(device.handle(), &info)) - }; - self.made(Call::SetDebugUtilsObjectName); - } - - /// The command buffer `vkAllocateCommandBuffers` allocates of `info`, the device's loader - /// word put back first: the loader serves the call and reads the word, which MoltenVK 1.4.1 - /// overwrites whenever it names the device in a message, as this priming's own submission makes - /// it do where its performance tracking logs each activity at once (a - /// `SIGSEGV` at `0x1cdc0de` in the loader's `vkAllocateCommandBuffers`). - /// - /// # Safety - /// - /// `info` names a command pool of the device's, which this priming holds. - unsafe fn allocate_command_buffer( - &self, - info: &vk::CommandBufferAllocateInfo<'_>, - ) -> Result { - // SAFETY: the caller's; the device is live while it is primed. - let buffers = unsafe { - self.loader_word - .restored(|| self.device.allocate_command_buffers(info)) - }; - Ok(buffers.map_err(vulkan)?[0]) - } - - /// Release `object` with the others, last first. - fn hold(&mut self, object: T) { - self.held.push(Box::new(move |device: &ash::Device| { - // SAFETY: the object is the device's, and the device is idle when the priming - // releases what it holds. - unsafe { release::object(device, object) }; - T::CALL - })); - } - - /// Reset `pool` before it is released, as a predicated loop's run again resets its arena's - /// pools: held right after the pool, so released before it, and after the command pool - /// whose never-submitted command buffer binds the pool's set, which is held later. - fn hold_reset(&mut self, pool: vk::DescriptorPool) { - self.held.push(Box::new(move |device: &ash::Device| { - // SAFETY: the pool is the device's, the device is idle when the priming releases what - // it holds, and the command buffer that bound the pool's set is freed before this. - let _ = unsafe { - device.reset_descriptor_pool(pool, vk::DescriptorPoolResetFlags::empty()) - }; - Call::ResetDescriptorPool - })); - } - - /// A batch's sparse binding, where the device binds sparse memory: an empty bind on the first - /// queue, which the device's idle wait after the priming waits for. - /// - /// # Safety - /// - /// As [`prime`]'s; with `sparse_binding`, the queue family binds sparse memory. - unsafe fn sparse(&mut self, queues: &[QueueSlot], sparse_binding: bool) -> Result<(), Error> { - if !sparse_binding { - return Ok(()); - } - let device = self.device; - let info = [vk::BindSparseInfo::default()]; - // SAFETY: the caller's; the bind binds nothing, waits for nothing and signals nothing, - // and the queue is used under its lock. - queues[0] - .with(|queue| unsafe { device.queue_bind_sparse(queue, &info, vk::Fence::null()) }) - .map_err(vulkan)?; - self.made(Call::QueueBindSparse); - Ok(()) - } - - /// A batch's calls: a command buffer of a new pool with the barriers every batch begins and - /// ends with (and, with `timestamps`, the reset of a timestamp query pool of two and a - /// timestamp before and after them, as a command buffer's GPU times are written), submitted - /// to the first queue after every queue's timeline at 0, signalling a timeline semaphore to 1 - /// and a new fence; the wait for the timeline, a read of every timeline, the wait for the - /// fence and its reset, and, with `timestamps`, the read of the two timestamps; with - /// `host_reset` too, their reset on the host first, as a timestamp slot's (`gpu_time.rs`). - /// - /// # Safety - /// - /// As [`prime`]'s; with `host_reset`, the device enables `hostQueryReset`. - unsafe fn batch( - &mut self, - queue_family: u32, - queues: &[QueueSlot], - timestamps: bool, - host_reset: bool, - ) -> Result<(), Error> { - let device = self.device; - let mut kind = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); - // SAFETY: the caller's. - let signal = unsafe { device.create_semaphore(&info, None) }.map_err(vulkan)?; - self.made(Call::CreateSemaphore); - self.hold(signal); - let pool_info = vk::CommandPoolCreateInfo::default() - .flags(vk::CommandPoolCreateFlags::TRANSIENT) - .queue_family_index(queue_family); - // SAFETY: the caller's. - let pool = unsafe { device.create_command_pool(&pool_info, None) }.map_err(vulkan)?; - self.made(Call::CreateCommandPool); - self.hold(pool); - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - // SAFETY: the pool is this priming's. - let buffer = unsafe { self.allocate_command_buffer(&allocate) }?; - self.made(Call::AllocateCommandBuffers); - let queries = if timestamps { - let info = vk::QueryPoolCreateInfo::default() - .query_type(vk::QueryType::TIMESTAMP) - .query_count(2); - // SAFETY: the caller's. - let queries = unsafe { device.create_query_pool(&info, None) }.map_err(vulkan)?; - self.hold(queries); - if host_reset { - // SAFETY: the device enables `hostQueryReset` (the caller's); nothing uses the - // new pool's queries. - unsafe { device.reset_query_pool(queries, 0, 2) }; - self.made(Call::ResetQueryPool); - } - Some(queries) - } else { - None - }; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer was just allocated and only this call records it. - unsafe { - device - .begin_command_buffer(buffer, &begin) - .map_err(vulkan)?; - self.made(Call::BeginCommandBuffer); - if let Some(queries) = queries { - device.cmd_reset_query_pool(buffer, queries, 0, 2); - self.made(Call::CmdResetQueryPool); - device.cmd_write_timestamp(buffer, vk::PipelineStageFlags::TOP_OF_PIPE, queries, 0); - } - Barrier::to_host().record(device, buffer); - self.made(Call::CmdPipelineBarrier); - if let Some(queries) = queries { - device.cmd_write_timestamp( - buffer, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - queries, - 1, - ); - self.made(Call::CmdWriteTimestamp); - } - device.end_command_buffer(buffer).map_err(vulkan)?; - self.made(Call::EndCommandBuffer); - } - let waits: Vec = queues.iter().map(|queue| queue.timeline).collect(); - let wait_values = vec![0; waits.len()]; - let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; waits.len()]; - let signals = [signal]; - let signal_values = [1]; - let buffers = [buffer]; - let mut timeline = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&wait_values) - .signal_semaphore_values(&signal_values); - let submit = vk::SubmitInfo::default() - .wait_semaphores(&waits) - .wait_dst_stage_mask(&wait_stages) - .command_buffers(&buffers) - .signal_semaphores(&signals) - .push_next(&mut timeline); - // SAFETY: the caller's. - let fence = unsafe { device.create_fence(&vk::FenceCreateInfo::default(), None) } - .map_err(vulkan)?; - self.made(Call::CreateFence); - self.hold(fence); - // SAFETY: the command buffer is executable; every wait is for a value the timeline holds - // already; the signal raises the semaphore; the fence is new; the queue is used under its - // lock. - queues[0] - .with(|queue| unsafe { device.queue_submit(queue, &[submit], fence) }) - .map_err(vulkan)?; - self.made(Call::QueueSubmit); - let start = Instant::now(); - let semaphores = [signal]; - let values = [1]; - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&semaphores) - .values(&values); - loop { - // SAFETY: the semaphore is live; its signal was submitted. - match unsafe { device.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) } { - Ok(()) => break, - Err(vk::Result::TIMEOUT) if start.elapsed() < LIMIT => {} - Err(error) => return Err(vulkan(error)), - } - } - self.made(Call::WaitSemaphores); - // A waker's nudge of the scheduler's thread (`scheduler/mod.rs`): the semaphore, at 1, - // raised from the host, with no signal of it pending. - let raised = vk::SemaphoreSignalInfo::default() - .semaphore(signal) - .value(2); - // SAFETY: the semaphore is live, its one submitted signal landed, and 2 is above it. - unsafe { device.signal_semaphore(&raised) }.map_err(vulkan)?; - self.made(Call::SignalSemaphore); - for queue in queues { - // SAFETY: the timeline is live. - unsafe { device.get_semaphore_counter_value(queue.timeline) }.map_err(vulkan)?; - } - self.made(Call::GetSemaphoreCounterValue); - let fences = [fence]; - loop { - // SAFETY: the fence is live; its submission was made. - match unsafe { device.wait_for_fences(&fences, true, WAIT_SLICE.as_nanos() as u64) } { - Ok(()) => break, - Err(vk::Result::TIMEOUT) if start.elapsed() < LIMIT => {} - Err(error) => return Err(vulkan(error)), - } - } - self.made(Call::WaitForFences); - // SAFETY: the fence is signaled and its submission completed. - unsafe { device.reset_fences(&fences) }.map_err(vulkan)?; - self.made(Call::ResetFences); - // A completion turn's drain of the queues after a failed wait - // (`Device::drain_queues`). - // SAFETY: the queue is used under its lock; its one submission completed. - queues[0] - .with(|queue| unsafe { device.queue_wait_idle(queue) }) - .map_err(vulkan)?; - self.made(Call::QueueWaitIdle); - // A spare pool's command buffers freed and the pool trimmed as a command buffer gives it - // back (`spares.rs`). Trimmed on every device: no command buffer submitted again ever - // came before the priming's (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`). - // SAFETY: the command buffer is the priming's pool's, its one submission completed, and - // the pool is the priming's alone. - unsafe { - release::object( - device, - release::PoolBuffers { - pool, - buffers: &buffers, - trim: true, - }, - ) - }; - self.made(Call::FreeCommandBuffers); - self.made(Call::TrimCommandPool); - if let Some(queries) = queries { - let mut results = [[0u64; 2]; 2]; - // SAFETY: the pool's two queries were written by the submission, which completed; - // 64-bit results with availability, two words a query. - let read = unsafe { - device.get_query_pool_results( - queries, - 0, - &mut results, - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WITH_AVAILABILITY, - ) - }; - match read { - Ok(()) | Err(vk::Result::NOT_READY) => {} - Err(error) => return Err(vulkan(error)), - } - self.made(Call::GetQueryPoolResults); - } - if let Some(calibration) = self.calibration { - let _ = calibration.reading(); - self.made(Call::GetCalibratedTimestamps); - } - Ok(()) - } - - /// Release `object`, made through `commands`, with the others, last first. - fn hold_generated(&mut self, commands: Commands, object: Generated) { - let call = match object { - Generated::ExecutionSet(_) => Call::DestroyIndirectExecutionSet, - Generated::CommandsLayout(_) => Call::DestroyIndirectCommandsLayout, - }; - self.held.push(Box::new(move |_: &ash::Device| { - // SAFETY: the object is this priming's, and the device is idle when the priming - // releases what it holds. - unsafe { release::generated(&commands, object) }; - call - })); - } - - /// An execution set and an indirect commands layout of `VK_EXT_device_generated_commands`, - /// over an indirect-bindable pipeline of the smallest shader, which the runtime releases - /// through `commands` (`generated_commands.rs`). - /// - /// # Safety - /// - /// As [`prime`]'s, `commands` the device's. - unsafe fn generated(&mut self, commands: &Commands) -> Result<(), Error> { - let device = self.device; - // SAFETY: the caller's, for every call below; each object is this priming's, and each - // create info and what it points at live for its call. - unsafe { - let module_info = vk::ShaderModuleCreateInfo::default().code(&SHADER); - let module = device - .create_shader_module(&module_info, None) - .map_err(vulkan)?; - self.hold(module); - let layout = device - .create_pipeline_layout(&vk::PipelineLayoutCreateInfo::default(), None) - .map_err(vulkan)?; - self.hold(layout); - let mut flags = - vk::PipelineCreateFlags2CreateInfoKHR::default().flags(INDIRECT_BINDABLE); - let specialization = specialization(); - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(module) - .name(c"main") - .specialization_info(&specialization); - let info = vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(layout) - .push_next(&mut flags); - let pipeline = device - .create_compute_pipelines(vk::PipelineCache::null(), &[info], None) - .map_err(|(_, error)| vulkan(error))?[0]; - self.hold(pipeline); - self.name(pipeline, PRIMING_GENERATED_KERNEL); - let pipelines = ExecutionSetPipelineInfo::new(pipeline, 1); - let set = commands - .create_execution_set(&ExecutionSetCreateInfo::new(&pipelines)) - .map_err(vulkan)?; - self.hold_generated(*commands, Generated::ExecutionSet(set)); - let set_token = ExecutionSetToken { - kind: EXECUTION_SET_PIPELINES, - shader_stages: vk::ShaderStageFlags::COMPUTE, - }; - let tokens = [ - LayoutToken::new( - TOKEN_EXECUTION_SET, - std::ptr::from_ref(&set_token).cast(), - 0, - ), - LayoutToken::new(TOKEN_DISPATCH, std::ptr::null(), 4), - ]; - let layout_info = LayoutCreateInfo::new(16, layout, &tokens); - let commands_layout = commands - .create_commands_layout(&layout_info) - .map_err(vulkan)?; - self.hold_generated(*commands, Generated::CommandsLayout(commands_layout)); - } - Ok(()) - } - - /// A Y′CbCr conversion of `info`, a format the device converts, where it converts one - /// ([`YCBCR_CONVERSION_CALLS`]). - /// - /// # Safety - /// - /// As [`prime`]'s; the device enables `samplerYcbcrConversion` where `info` is given, and - /// converts its format with its chroma location. - unsafe fn ycbcr( - &mut self, - info: Option>, - ) -> Result<(), Error> { - let Some(info) = info else { - return Ok(()); - }; - // SAFETY: the caller's. - let conversion = - unsafe { self.device.create_sampler_ycbcr_conversion(&info, None) }.map_err(vulkan)?; - self.hold(conversion); - Ok(()) - } - - /// An object of every other kind the runtime releases, the read of a pipeline cache's data, - /// and a command buffer of a pool of `queue_family` recorded as a host step records one; - /// `device_addresses` where the device has them. - /// - /// # Safety - /// - /// As [`prime`]'s. - unsafe fn objects(&mut self, queue_family: u32, device_addresses: bool) -> Result<(), Error> { - let device = self.device; - // SAFETY: the caller's, for every call below; each object is this priming's. - unsafe { - let sampler = device - .create_sampler(&vk::SamplerCreateInfo::default(), None) - .map_err(vulkan)?; - self.made(Call::CreateSampler); - self.hold(sampler); - - let info = vk::QueryPoolCreateInfo::default() - .query_type(vk::QueryType::OCCLUSION) - .query_count(1); - let queries = device.create_query_pool(&info, None).map_err(vulkan)?; - self.made(Call::CreateQueryPool); - self.hold(queries); - - // A storage buffer, and a texel buffer of `R32_UINT`, whose uniform texel buffer use - // every device has, in host-visible memory, which every buffer may take, mapped; the - // indirect dispatch's and draw's arguments too. - let mut usage = vk::BufferUsageFlags::STORAGE_BUFFER - | vk::BufferUsageFlags::UNIFORM_TEXEL_BUFFER - | vk::BufferUsageFlags::VERTEX_BUFFER - | vk::BufferUsageFlags::INDEX_BUFFER - | vk::BufferUsageFlags::INDIRECT_BUFFER - | vk::BufferUsageFlags::TRANSFER_SRC - | vk::BufferUsageFlags::TRANSFER_DST; - if device_addresses { - usage |= vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS; - } - let info = self - .sharing - .buffer(vk::BufferCreateInfo::default().size(256).usage(usage)); - let buffer = device.create_buffer(&info, None).map_err(vulkan)?; - self.made(Call::CreateBuffer); - let requirements = device.get_buffer_memory_requirements(buffer); - self.made(Call::GetBufferMemoryRequirements); - let mut requirements2 = vk::MemoryRequirements2::default(); - let query = vk::BufferMemoryRequirementsInfo2::default().buffer(buffer); - device.get_buffer_memory_requirements2(&query, &mut requirements2); - self.made(Call::GetBufferMemoryRequirements2); - let host = - vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; - let memory = match self.allocate(requirements, host, device_addresses) { - Ok(memory) => memory, - Err(error) => { - release::object(device, buffer); - return Err(error); - } - }; - self.hold(buffer); - device - .bind_buffer_memory(buffer, memory, 0) - .map_err(vulkan)?; - self.made(Call::BindBufferMemory); - // Unmapped as the memory is freed. - device - .map_memory(memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) - .map_err(vulkan)?; - self.made(Call::MapMemory); - if device_addresses { - let info = vk::BufferDeviceAddressInfo::default().buffer(buffer); - device.get_buffer_device_address(&info); - self.made(Call::GetBufferDeviceAddress); - } - let info = vk::BufferViewCreateInfo::default() - .buffer(buffer) - .format(vk::Format::R32_UINT) - .range(vk::WHOLE_SIZE); - let view = device.create_buffer_view(&info, None).map_err(vulkan)?; - self.made(Call::CreateBufferView); - self.hold(view); - - // A color attachment of `R8G8B8A8_UNORM`, which every device can sample, draw to and - // copy, two texels wide for a copy between its texels. - let format = vk::Format::R8G8B8A8_UNORM; - let info = vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(format) - .extent(vk::Extent3D { - width: 2, - height: 1, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::OPTIMAL) - .usage( - vk::ImageUsageFlags::COLOR_ATTACHMENT - | vk::ImageUsageFlags::SAMPLED - | vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST, - ) - .initial_layout(vk::ImageLayout::UNDEFINED); - let info = self.sharing.image(info); - let image = device.create_image(&info, None).map_err(vulkan)?; - self.made(Call::CreateImage); - let requirements = device.get_image_memory_requirements(image); - self.made(Call::GetImageMemoryRequirements); - let mut requirements2 = vk::MemoryRequirements2::default(); - let query = vk::ImageMemoryRequirementsInfo2::default().image(image); - device.get_image_memory_requirements2(&query, &mut requirements2); - self.made(Call::GetImageMemoryRequirements2); - let memory = match self.allocate(requirements, vk::MemoryPropertyFlags::empty(), false) - { - Ok(memory) => memory, - Err(error) => { - release::object(device, image); - return Err(error); - } - }; - self.hold(image); - device.bind_image_memory(image, memory, 0).map_err(vulkan)?; - self.made(Call::BindImageMemory); - let info = vk::ImageViewCreateInfo::default() - .image(image) - .view_type(vk::ImageViewType::TYPE_2D) - .format(format) - .subresource_range(vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }); - let view = device.create_image_view(&info, None).map_err(vulkan)?; - self.made(Call::CreateImageView); - self.hold(view); - // A depth image of `D16_UNORM`, which every device can draw to and clear, for a - // batch's first work's clear of a neutral depth image. - let info = vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(vk::Format::D16_UNORM) - .extent(vk::Extent3D { - width: 1, - height: 1, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::OPTIMAL) - .usage( - vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT - | vk::ImageUsageFlags::TRANSFER_DST, - ) - .initial_layout(vk::ImageLayout::UNDEFINED); - let info = self.sharing.image(info); - let depth = device.create_image(&info, None).map_err(vulkan)?; - let requirements = device.get_image_memory_requirements(depth); - let memory = match self.allocate(requirements, vk::MemoryPropertyFlags::empty(), false) - { - Ok(memory) => memory, - Err(error) => { - release::object(device, depth); - return Err(error); - } - }; - self.hold(depth); - device.bind_image_memory(depth, memory, 0).map_err(vulkan)?; - let attachments = [vk::AttachmentDescription::default() - .format(format) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(vk::AttachmentLoadOp::DONT_CARE) - .store_op(vk::AttachmentStoreOp::DONT_CARE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(vk::ImageLayout::UNDEFINED) - .final_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)]; - let colors = [vk::AttachmentReference { - attachment: 0, - layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, - }]; - let subpasses = [vk::SubpassDescription::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colors)]; - let info = vk::RenderPassCreateInfo::default() - .attachments(&attachments) - .subpasses(&subpasses); - let render_pass = device.create_render_pass(&info, None).map_err(vulkan)?; - self.made(Call::CreateRenderPass); - self.hold(render_pass); - // The same in `vkCreateRenderPass2`'s form, a render encoder's pass's - // (`render_target.rs`). - let attachments = [vk::AttachmentDescription2::default() - .format(format) - .samples(vk::SampleCountFlags::TYPE_1) - .load_op(vk::AttachmentLoadOp::DONT_CARE) - .store_op(vk::AttachmentStoreOp::DONT_CARE) - .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) - .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) - .initial_layout(vk::ImageLayout::UNDEFINED) - .final_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)]; - let colors = [vk::AttachmentReference2::default() - .attachment(0) - .layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL) - .aspect_mask(vk::ImageAspectFlags::COLOR)]; - let subpasses = [vk::SubpassDescription2::default() - .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colors)]; - let info = vk::RenderPassCreateInfo2::default() - .attachments(&attachments) - .subpasses(&subpasses); - let render_pass2 = device.create_render_pass2(&info, None).map_err(vulkan)?; - self.made(Call::CreateRenderPass2); - self.hold(render_pass2); - let views = [view]; - let info = vk::FramebufferCreateInfo::default() - .render_pass(render_pass) - .attachments(&views) - .width(1) - .height(1) - .layers(1); - let framebuffer = device.create_framebuffer(&info, None).map_err(vulkan)?; - self.made(Call::CreateFramebuffer); - self.hold(framebuffer); - - // A compute pipeline with one storage buffer binding and a push constant range, - // made with a pipeline cache. - let bindings = [vk::DescriptorSetLayoutBinding::default() - .binding(0) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .descriptor_count(1) - .stage_flags(vk::ShaderStageFlags::COMPUTE)]; - let info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings); - let mut support = vk::DescriptorSetLayoutSupport::default(); - device.get_descriptor_set_layout_support(&info, &mut support); - self.made(Call::GetDescriptorSetLayoutSupport); - let set_layout = device - .create_descriptor_set_layout(&info, None) - .map_err(vulkan)?; - self.made(Call::CreateDescriptorSetLayout); - self.hold(set_layout); - let set_layouts = [set_layout]; - let push = [vk::PushConstantRange { - stage_flags: vk::ShaderStageFlags::COMPUTE, - offset: 0, - size: 4, - }]; - let info = vk::PipelineLayoutCreateInfo::default() - .set_layouts(&set_layouts) - .push_constant_ranges(&push); - let layout = device.create_pipeline_layout(&info, None).map_err(vulkan)?; - self.made(Call::CreatePipelineLayout); - self.hold(layout); - let sizes = [vk::DescriptorPoolSize { - ty: vk::DescriptorType::STORAGE_BUFFER, - descriptor_count: 1, - }]; - let info = vk::DescriptorPoolCreateInfo::default() - .max_sets(1) - .pool_sizes(&sizes); - let pool = device.create_descriptor_pool(&info, None).map_err(vulkan)?; - self.made(Call::CreateDescriptorPool); - self.hold(pool); - self.hold_reset(pool); - // A set of it, written: the runtime releases its pools with their sets. - let info = vk::DescriptorSetAllocateInfo::default() - .descriptor_pool(pool) - .set_layouts(&set_layouts); - let set = device.allocate_descriptor_sets(&info).map_err(vulkan)?[0]; - self.made(Call::AllocateDescriptorSets); - let buffers = [vk::DescriptorBufferInfo { - buffer, - offset: 0, - range: vk::WHOLE_SIZE, - }]; - let writes = [vk::WriteDescriptorSet::default() - .dst_set(set) - .dst_binding(0) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .buffer_info(&buffers)]; - device.update_descriptor_sets(&writes, &[]); - self.made(Call::UpdateDescriptorSets); - let info = vk::ShaderModuleCreateInfo::default().code(&SHADER); - let module = device.create_shader_module(&info, None).map_err(vulkan)?; - self.made(Call::CreateShaderModule); - self.hold(module); - let cache = device - .create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), None) - .map_err(vulkan)?; - self.made(Call::CreatePipelineCache); - self.hold(cache); - let specialization = specialization(); - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(module) - .name(c"main") - .specialization_info(&specialization); - let info = [vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(layout)]; - let pipeline = device - .create_compute_pipelines(cache, &info, None) - .map_err(|(_, error)| vulkan(error))?[0]; - self.made(Call::CreateComputePipelines); - self.hold(pipeline); - self.name(pipeline, PRIMING_KERNEL); - device.get_pipeline_cache_data(cache).map_err(vulkan)?; - self.made(Call::GetPipelineCacheData); - - // A host step's recording, in a command buffer never submitted, which its pool - // releases. - let info = vk::CommandPoolCreateInfo::default() - .flags(vk::CommandPoolCreateFlags::TRANSIENT) - .queue_family_index(queue_family); - let commands = device.create_command_pool(&info, None).map_err(vulkan)?; - self.hold(commands); - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(commands) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - let recorded = self.allocate_command_buffer(&allocate)?; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - device - .begin_command_buffer(recorded, &begin) - .map_err(vulkan)?; - device.cmd_bind_pipeline(recorded, vk::PipelineBindPoint::COMPUTE, pipeline); - self.made(Call::CmdBindPipeline); - // Where the device has the push command, the set's write pushed with a layout whose - // set 0 takes push descriptors, before the set is bound with the pipeline's layout - // (which disturbs it). The push ignores the write's `dstSet`. - if let Some(push) = self.push { - let info = vk::DescriptorSetLayoutCreateInfo::default() - .flags(vk::DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR_KHR) - .bindings(&bindings); - let pushed_set = device - .create_descriptor_set_layout(&info, None) - .map_err(vulkan)?; - self.hold(pushed_set); - let pushed_sets = [pushed_set]; - let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&pushed_sets); - let pushed = device.create_pipeline_layout(&info, None).map_err(vulkan)?; - self.hold(pushed); - push( - recorded, - vk::PipelineBindPoint::COMPUTE, - pushed, - 0, - writes.len() as u32, - writes.as_ptr(), - ); - self.made(Call::CmdPushDescriptorSet); - } - device.cmd_bind_descriptor_sets( - recorded, - vk::PipelineBindPoint::COMPUTE, - layout, - 0, - &[set], - &[], - ); - self.made(Call::CmdBindDescriptorSets); - device.cmd_push_constants(recorded, layout, vk::ShaderStageFlags::COMPUTE, 0, &[0; 4]); - self.made(Call::CmdPushConstants); - device.cmd_dispatch(recorded, 1, 1, 1); - self.made(Call::CmdDispatch); - // An emulated mesh command's dispatch from its scan's arguments. - device.cmd_dispatch_indirect(recorded, buffer, 0); - self.made(Call::CmdDispatchIndirect); - let region = [vk::BufferCopy { - src_offset: 0, - dst_offset: 128, - size: 4, - }]; - device.cmd_copy_buffer(recorded, buffer, buffer, ®ion); - self.made(Call::CmdCopyBuffer); - let region = [vk::BufferImageCopy::default() - .image_subresource(vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::COLOR, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }) - .image_extent(vk::Extent3D { - width: 1, - height: 1, - depth: 1, - })]; - device.cmd_copy_buffer_to_image( - recorded, - buffer, - image, - vk::ImageLayout::GENERAL, - ®ion, - ); - self.made(Call::CmdCopyBufferToImage); - // The image's write before its read, and the buffer's reads before its write: the - // validation layer checks a recording's order without its submission. - Barrier::everything().record(device, recorded); - device.cmd_copy_image_to_buffer( - recorded, - image, - vk::ImageLayout::GENERAL, - buffer, - ®ion, - ); - self.made(Call::CmdCopyImageToBuffer); - // A copy of its first texel to its second, after the read. - Barrier::everything().record(device, recorded); - let texel = vk::ImageSubresourceLayers { - aspect_mask: vk::ImageAspectFlags::COLOR, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }; - let region = [vk::ImageCopy { - src_subresource: texel, - src_offset: vk::Offset3D::default(), - dst_subresource: texel, - dst_offset: vk::Offset3D { x: 1, y: 0, z: 0 }, - extent: vk::Extent3D { - width: 1, - height: 1, - depth: 1, - }, - }]; - let general = vk::ImageLayout::GENERAL; - device.cmd_copy_image(recorded, image, general, image, general, ®ion); - self.made(Call::CmdCopyImage); - // A clear of the image after the copy, as a render host step's pass steps clear a - // sample plane or a stencil shadow (`render/pass_steps.rs`). - Barrier::everything().record(device, recorded); - let whole = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::COLOR, - base_mip_level: 0, - level_count: 1, - base_array_layer: 0, - layer_count: 1, - }; - let black = vk::ClearColorValue::default(); - device.cmd_clear_color_image(recorded, image, general, &black, &[whole]); - self.made(Call::CmdClearColorImage); - // A clear of the depth image, as a batch's first work clears a neutral depth image. - let depth_whole = vk::ImageSubresourceRange { - aspect_mask: vk::ImageAspectFlags::DEPTH, - ..whole - }; - let zero = vk::ClearDepthStencilValue::default(); - device.cmd_clear_depth_stencil_image(recorded, depth, general, &zero, &[depth_whole]); - self.made(Call::CmdClearDepthStencilImage); - // What an encoder records that no host step does: a buffer's fill and its inline - // update, each at bytes - // of its own, a copy of the query's result, and a blit of the image's first texel to - // its second after the clear. - device.cmd_fill_buffer(recorded, buffer, 192, 4, 0); - self.made(Call::CmdFillBuffer); - device.cmd_update_buffer(recorded, buffer, 208, &[0; 4]); - self.made(Call::CmdUpdateBuffer); - let results = vk::QueryResultFlags::empty(); - device.cmd_copy_query_pool_results(recorded, queries, 0, 1, buffer, 224, 4, results); - self.made(Call::CmdCopyQueryPoolResults); - Barrier::everything().record(device, recorded); - let corner = |x| vk::Offset3D { x, y: 0, z: 0 }; - let far = |x| vk::Offset3D { x, y: 1, z: 1 }; - let blit = [vk::ImageBlit { - src_subresource: texel, - src_offsets: [corner(0), far(1)], - dst_subresource: texel, - dst_offsets: [corner(1), far(2)], - }]; - device.cmd_blit_image( - recorded, - image, - general, - image, - general, - &blit, - vk::Filter::NEAREST, - ); - self.made(Call::CmdBlitImage); - // The image's read before the pass's layout transition of it. - Barrier::everything().record(device, recorded); - self.render_step(RenderStep { - recorded, - commands, - render_pass, - framebuffer, - layout, - cache, - buffer, - queries, - })?; - device.end_command_buffer(recorded).map_err(vulkan)?; - } - Ok(()) - } - - /// A render host step's recording into `step.recorded` (`render/executions.rs`): a graphics - /// pipeline that rasterizes nothing, made with the pipeline cache and drawn in a secondary - /// command buffer after each state a draw records is set, and the pass's begin, the - /// secondary's execution and its end. - /// - /// # Safety - /// - /// As [`prime`]'s; `step.recorded` is recording outside a render pass, and the objects are - /// this priming's. - unsafe fn render_step(&mut self, step: RenderStep) -> Result<(), Error> { - let device = self.device; - let RenderStep { - recorded, - commands, - render_pass, - framebuffer, - layout, - cache, - buffer, - queries, - } = step; - // SAFETY: the caller's, for every call below. - unsafe { - let info = vk::ShaderModuleCreateInfo::default().code(&VERTEX_SHADER); - let module = device.create_shader_module(&info, None).map_err(vulkan)?; - self.hold(module); - let specialization = specialization(); - let stages = [vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::VERTEX) - .module(module) - .name(c"main") - .specialization_info(&specialization)]; - let vertex_input = vk::PipelineVertexInputStateCreateInfo::default(); - // Triangles: a point list's vertex shader must write the point size where the device - // does not enable `maintenance5`. - let assembly = vk::PipelineInputAssemblyStateCreateInfo::default() - .topology(vk::PrimitiveTopology::TRIANGLE_LIST); - let raster = vk::PipelineRasterizationStateCreateInfo::default() - .rasterizer_discard_enable(true) - .polygon_mode(vk::PolygonMode::FILL) - .line_width(1.0); - let info = [vk::GraphicsPipelineCreateInfo::default() - .stages(&stages) - .vertex_input_state(&vertex_input) - .input_assembly_state(&assembly) - .rasterization_state(&raster) - .layout(layout) - .render_pass(render_pass) - .subpass(0)]; - let pipeline = device - .create_graphics_pipelines(cache, &info, None) - .map_err(|(_, error)| vulkan(error))?[0]; - self.made(Call::CreateGraphicsPipelines); - self.hold(pipeline); - self.name(pipeline, PRIMING_PIPELINE); - - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(commands) - .level(vk::CommandBufferLevel::SECONDARY) - .command_buffer_count(1); - let draws = self.allocate_command_buffer(&allocate)?; - let inheritance = vk::CommandBufferInheritanceInfo::default() - .render_pass(render_pass) - .subpass(0); - let begin = vk::CommandBufferBeginInfo::default() - .flags( - vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT - | vk::CommandBufferUsageFlags::RENDER_PASS_CONTINUE, - ) - .inheritance_info(&inheritance); - device.begin_command_buffer(draws, &begin).map_err(vulkan)?; - // The states a draw records, each set before the pipeline is bound: one that - // rasterizes nothing keeps them all static, and a state set before a bind may be - // static in the pipeline bound. - let extent = vk::Extent2D { - width: 1, - height: 1, - }; - let viewport = vk::Viewport { - x: 0.0, - y: 0.0, - width: 1.0, - height: 1.0, - min_depth: 0.0, - max_depth: 1.0, - }; - device.cmd_set_viewport(draws, 0, &[viewport]); - self.made(Call::CmdSetViewport); - let area = vk::Rect2D { - offset: vk::Offset2D { x: 0, y: 0 }, - extent, - }; - device.cmd_set_scissor(draws, 0, &[area]); - self.made(Call::CmdSetScissor); - device.cmd_set_depth_bias(draws, 0.0, 0.0, 0.0); - self.made(Call::CmdSetDepthBias); - device.cmd_set_blend_constants(draws, &[0.0; 4]); - self.made(Call::CmdSetBlendConstants); - let faces = vk::StencilFaceFlags::FRONT_AND_BACK; - device.cmd_set_stencil_compare_mask(draws, faces, 0xff); - self.made(Call::CmdSetStencilCompareMask); - device.cmd_set_stencil_write_mask(draws, faces, 0xff); - self.made(Call::CmdSetStencilWriteMask); - device.cmd_set_stencil_reference(draws, faces, 0); - self.made(Call::CmdSetStencilReference); - // The extended dynamic states and the extension states the device has, set before - // the bind too. - let drawn = self.drawn; - if let Some(dynamic) = drawn.dynamic { - (dynamic.cull_mode)(draws, vk::CullModeFlags::NONE); - self.made(Call::CmdSetCullMode); - (dynamic.front_face)(draws, vk::FrontFace::COUNTER_CLOCKWISE); - self.made(Call::CmdSetFrontFace); - (dynamic.primitive_topology)(draws, vk::PrimitiveTopology::TRIANGLE_LIST); - self.made(Call::CmdSetPrimitiveTopology); - (dynamic.depth_test_enable)(draws, vk::FALSE); - self.made(Call::CmdSetDepthTestEnable); - (dynamic.depth_write_enable)(draws, vk::FALSE); - self.made(Call::CmdSetDepthWriteEnable); - (dynamic.depth_compare_op)(draws, vk::CompareOp::ALWAYS); - self.made(Call::CmdSetDepthCompareOp); - (dynamic.stencil_test_enable)(draws, vk::FALSE); - self.made(Call::CmdSetStencilTestEnable); - let keep = vk::StencilOp::KEEP; - (dynamic.stencil_op)(draws, faces, keep, keep, keep, vk::CompareOp::ALWAYS); - self.made(Call::CmdSetStencilOp); - if let Some(restart) = dynamic.primitive_restart_enable { - restart(draws, vk::FALSE); - self.made(Call::CmdSetPrimitiveRestartEnable); - } - } - if let Some(ColorWriteMasks(masks)) = drawn.color_write_masks { - let all = [vk::ColorComponentFlags::RGBA]; - masks(draws, 0, all.len() as u32, all.as_ptr()); - self.made(Call::CmdSetColorWriteMask); - } - // A clear of the attachment inside the pass, as a render encoder's clear of a stand-in - // records it. - let clear = [vk::ClearAttachment { - aspect_mask: vk::ImageAspectFlags::COLOR, - color_attachment: 0, - clear_value: vk::ClearValue::default(), - }]; - let rect = [vk::ClearRect { - rect: area, - base_array_layer: 0, - layer_count: 1, - }]; - device.cmd_clear_attachments(draws, &clear, &rect); - self.made(Call::CmdClearAttachments); - device.cmd_bind_pipeline(draws, vk::PipelineBindPoint::GRAPHICS, pipeline); - device.cmd_bind_vertex_buffers(draws, 0, &[buffer], &[0]); - self.made(Call::CmdBindVertexBuffers); - if let Some(dynamic) = drawn.dynamic { - let (buffers, offsets) = ([buffer], [0]); - let none = std::ptr::null(); - (dynamic.bind_vertex_buffers2)( - draws, - 0, - 1, - buffers.as_ptr(), - offsets.as_ptr(), - none, - none, - ); - self.made(Call::CmdBindVertexBuffers2); - } - // An execution under a visibility result mode counts its draws in a query begun and - // ended in its secondary. - device.cmd_begin_query(draws, queries, 0, vk::QueryControlFlags::empty()); - self.made(Call::CmdBeginQuery); - device.cmd_draw(draws, 3, 1, 0, 0); - self.made(Call::CmdDraw); - // An emulated mesh command's draw from its scan's arguments. - device.cmd_draw_indirect(draws, buffer, 0, 1, 16); - self.made(Call::CmdDrawIndirect); - // A draw recorded once its pipeline is made (`render/pending.rs`): indexed, direct - // and from its arguments. - device.cmd_bind_index_buffer(draws, buffer, 0, vk::IndexType::UINT32); - self.made(Call::CmdBindIndexBuffer); - if let Some(bind) = drawn.sized_index_bind { - bind(draws, buffer, 0, 256, vk::IndexType::UINT32); - self.made(Call::CmdBindIndexBuffer2); - } - device.cmd_draw_indexed(draws, 3, 1, 0, 0, 0); - self.made(Call::CmdDrawIndexed); - device.cmd_draw_indexed_indirect(draws, buffer, 0, 1, 20); - self.made(Call::CmdDrawIndexedIndirect); - device.cmd_end_query(draws, queries, 0); - self.made(Call::CmdEndQuery); - device.end_command_buffer(draws).map_err(vulkan)?; - - let begin = vk::RenderPassBeginInfo::default() - .render_pass(render_pass) - .framebuffer(framebuffer) - .render_area(area); - device.cmd_begin_render_pass( - recorded, - &begin, - vk::SubpassContents::SECONDARY_COMMAND_BUFFERS, - ); - self.made(Call::CmdBeginRenderPass); - device.cmd_execute_commands(recorded, &[draws]); - self.made(Call::CmdExecuteCommands); - device.cmd_end_render_pass(recorded); - self.made(Call::CmdEndRenderPass); - } - Ok(()) - } - - /// Memory of the first type `requirements` allow with `properties`, with the device-address - /// flag where `device_addresses`, held (released after what is bound to it). - /// - /// # Safety - /// - /// As [`prime`]'s. - unsafe fn allocate( - &mut self, - requirements: vk::MemoryRequirements, - properties: vk::MemoryPropertyFlags, - device_addresses: bool, - ) -> Result { - let types = &self.memory.memory_types[..self.memory.memory_type_count as usize]; - let index = (0_u32..) - .zip(types) - .find(|&(index, kind)| { - requirements.memory_type_bits & (1 << index) != 0 - && memory::allocatable(kind.property_flags) - && kind.property_flags.contains(properties) - }) - .map(|(index, _)| index) - .ok_or_else(|| vulkan(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY))?; - let mut flags = - vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let mut info = vk::MemoryAllocateInfo::default() - .allocation_size(requirements.size) - .memory_type_index(index); - if device_addresses { - info = info.push_next(&mut flags); - } - // SAFETY: the caller's; the type is one the requirements allow. - let memory = unsafe { self.device.allocate_memory(&info, None) }.map_err(vulkan)?; - self.made(Call::AllocateMemory); - self.hold(memory); - Ok(memory) - } -} diff --git a/crates/metal2vulkan-runtime/src/device/properties.rs b/crates/metal2vulkan-runtime/src/device/properties.rs deleted file mode 100644 index 841eb373b..000000000 --- a/crates/metal2vulkan-runtime/src/device/properties.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! What a device reports about itself: the Vulkan facts `query` reads of the physical device, from -//! which `Device::assemble` builds the [`DeviceProperties`](crate::DeviceProperties) Metal's device -//! queries answer from (`capabilities.rs`). -//! -//! The same read answers [`PhysicalDeviceIdentity`] of a physical device no device was made of -//! ([`Device::identities_with`](crate::Device::identities_with)), so the identity a consumer reads -//! before making a device is the one the device then answers. - -use crate::capabilities::DeviceIdentity; -use ash::vk; -use metal2vulkan::vk::ApiVersion; - -/// The kind of physical device, from `VkPhysicalDeviceType`. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum DeviceKind { - /// A discrete GPU. - Discrete, - /// A GPU integrated with the host. - Integrated, - /// A GPU of a virtual machine. - Virtual, - /// A CPU implementation (lavapipe, SwiftShader). - Cpu, - /// Any other device. - Other, -} - -impl DeviceKind { - pub(super) fn of(ty: vk::PhysicalDeviceType) -> DeviceKind { - match ty { - vk::PhysicalDeviceType::DISCRETE_GPU => DeviceKind::Discrete, - vk::PhysicalDeviceType::INTEGRATED_GPU => DeviceKind::Integrated, - vk::PhysicalDeviceType::VIRTUAL_GPU => DeviceKind::Virtual, - vk::PhysicalDeviceType::CPU => DeviceKind::Cpu, - _ => DeviceKind::Other, - } - } - - /// Whether a device of the kind shares the host's memory (`hasUnifiedMemory`): an integrated - /// GPU and a CPU implementation do; a discrete GPU does not, and a virtual GPU or another kind - /// is not known to. - pub(crate) fn has_unified_memory(self) -> bool { - matches!(self, DeviceKind::Integrated | DeviceKind::Cpu) - } - - /// The order `Device::system_default` prefers kinds in: discrete, integrated, virtual, CPU, - /// other. - pub(super) fn preference(self) -> u8 { - match self { - DeviceKind::Discrete => 0, - DeviceKind::Integrated => 1, - DeviceKind::Virtual => 2, - DeviceKind::Cpu => 3, - DeviceKind::Other => 4, - } - } -} - -/// `registryID` of a device with `uuid`: its two halves, little-endian, exclusive-ored, and 1 -/// when that is 0 (Metal never answers 0). -pub(crate) fn registry_id(uuid: &[u8; 16]) -> u64 { - let half = |at: usize| { - let mut bytes = [0; 8]; - bytes.copy_from_slice(&uuid[at..at + 8]); - u64::from_le_bytes(bytes) - }; - match half(0) ^ half(8) { - 0 => 1, - id => id, - } -} - -/// A physical device's identity, read without making a device -/// ([`Device::identities_with`](crate::Device::identities_with), -/// [`Device::system_default_identity_with`](crate::Device::system_default_identity_with)). -/// -/// No Metal counterpart: Metal's program holds an `MTLDevice` and asks it, so every one of these -/// is a property of a device that exists. The runtime answers them of the physical device alone, -/// so a consumer can tell which GPU it is about to get before paying for it. Every field but -/// [`recommended_max_working_set_size`](Self::recommended_max_working_set_size), which no device -/// property answers, is the one the device made of that physical device answers. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PhysicalDeviceIdentity { - /// `name`: `VkPhysicalDeviceProperties::deviceName` - /// ([`DeviceProperties::name`](crate::DeviceProperties::name)). - pub name: String, - /// The kind of physical device (`VkPhysicalDeviceProperties::deviceType`), which the order - /// [`Device::system_default_with`](crate::Device::system_default_with) prefers physical - /// devices in is taken from. No Metal counterpart - /// ([`DeviceProperties::kind`](crate::DeviceProperties::kind)). - pub kind: DeviceKind, - /// `VkPhysicalDeviceProperties::vendorID` - /// ([`DeviceProperties::vendor_id`](crate::DeviceProperties::vendor_id)). - pub vendor_id: u32, - /// `VkPhysicalDeviceProperties::deviceID` - /// ([`DeviceProperties::device_id`](crate::DeviceProperties::device_id)). - pub device_id: u32, - /// `VkPhysicalDeviceIDProperties::deviceUUID` - /// ([`DeviceProperties::device_uuid`](crate::DeviceProperties::device_uuid)). - pub device_uuid: [u8; 16], - /// `registryID`: the ID [`Device::registry_id`](crate::Device::registry_id) of the device of - /// this physical device answers, and [`Device::with_registry_id`](crate::Device::with_registry_id) - /// opens it by. - pub registry_id: u64, - /// The Vulkan version the device of this physical device runs at: the lower of the instance's - /// and the physical device's. No Metal counterpart - /// ([`DeviceProperties::api_version`](crate::DeviceProperties::api_version)). - pub api_version: ApiVersion, - /// The physical device's PCI bus address - /// ([`DeviceProperties::pci_bus`](crate::DeviceProperties::pci_bus)). - pub pci_bus: Option<(u32, u32, u32, u32)>, - /// The physical device's DRM render node - /// ([`DeviceProperties::drm_render`](crate::DeviceProperties::drm_render)). - pub drm_render: Option<(i64, i64)>, - /// The size in bytes of the physical device's largest `DEVICE_LOCAL` memory heap - /// (`VkPhysicalDeviceMemoryProperties::memoryHeaps`), as its Vulkan driver reports it; the - /// device's [`DeviceProperties::max_buffer_length`](crate::DeviceProperties::max_buffer_length) - /// is at most three quarters of it, to 16 KiB. Named after Metal's nearest counterpart, - /// `recommendedMaxWorkingSetSize`, which it is not: Metal's is its estimate of the memory the - /// GPU can use without hurting its performance, and this is the heap's whole size, fixed for - /// the physical device, with nothing taken off for the system or for other processes' use - /// (what `VK_EXT_memory_budget` would report) and no device made to read it. On an Apple M3 - /// Max of 64 GiB (macOS 27.0.1, MoltenVK 1.4.2) it is 68,719,476,736, the host's whole - /// memory, where Metal's `recommendedMaxWorkingSetSize` is 55,662,788,608. No device - /// property answers it. `None` only where the driver reports no `DEVICE_LOCAL` heap, which - /// Vulkan requires one of. - pub recommended_max_working_set_size: Option, -} - -impl PhysicalDeviceIdentity { - /// The identity in `identity`, which [`query`] read of a physical device: the fields the - /// device made of it answers, from the one read. - pub(crate) fn of(identity: &DeviceIdentity) -> PhysicalDeviceIdentity { - PhysicalDeviceIdentity { - name: identity.name.clone(), - kind: identity.kind, - vendor_id: identity.vendor_id, - device_id: identity.device_id, - device_uuid: identity.device_uuid, - registry_id: registry_id(&identity.device_uuid), - api_version: identity.api_version, - pci_bus: identity.pci_bus, - drm_render: identity.drm_render, - recommended_max_working_set_size: identity.device_local_heap, - } - } -} - -/// The identity of `physical`, and its largest memory allocation -/// (`VkPhysicalDeviceVulkan11Properties::maxMemoryAllocationSize`), which the sub-allocator -/// reads. -/// -/// # Safety -/// -/// `physical` was enumerated from `instance`, created at `instance_api_version`, which is -/// Vulkan 1.2 or later. -pub(super) unsafe fn query( - instance: &ash::Instance, - physical: vk::PhysicalDevice, - instance_api_version: metal2vulkan::vk::ApiVersion, -) -> (DeviceIdentity, u64) { - let mut v11 = vk::PhysicalDeviceVulkan11Properties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut v11); - // SAFETY: the caller's contract; `VkPhysicalDeviceVulkan11Properties` is core in 1.2. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - let core = properties.properties; - // SAFETY: the caller's contract. - let (pci_bus, drm_render) = unsafe { bus_addresses(instance, physical) }; - // SAFETY: the caller's contract. - let memory = unsafe { instance.get_physical_device_memory_properties(physical) }; - let heaps = - &memory.memory_heaps[..(memory.memory_heap_count as usize).min(vk::MAX_MEMORY_HEAPS)]; - let device_local_heap = heaps - .iter() - .filter(|heap| heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL)) - .map(|heap| heap.size) - .max(); - let identity = DeviceIdentity { - name: core - .device_name_as_c_str() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(), - kind: DeviceKind::of(core.device_type), - vendor_id: core.vendor_id, - device_id: core.device_id, - device_uuid: v11.device_uuid, - pci_bus, - drm_render, - api_version: metal2vulkan::vk::ApiVersion::from_packed(core.api_version) - .min(instance_api_version), - max_viewports: core.limits.max_viewports, - max_sampler_allocation_count: core.limits.max_sampler_allocation_count, - // SAFETY: the caller's contract. - gpu_core_count: unsafe { gpu_core_count(instance, physical) }, - sampled_sample_counts: metal2vulkan::vk::SampleCountFlags::from_raw( - (core.limits.sampled_image_color_sample_counts - & core.limits.sampled_image_depth_sample_counts) - .as_raw(), - ), - device_local_heap, - }; - (identity, v11.max_memory_allocation_size) -} - -/// The PCI bus address and the DRM render node of `physical` -/// ([`DeviceProperties::pci_bus`](crate::DeviceProperties::pci_bus), -/// [`DeviceProperties::drm_render`](crate::DeviceProperties::drm_render)): each read through its -/// own extension, and only where the driver lists it (a query of properties enables nothing); -/// `None` where it lists none, and `None` for both where the extensions cannot be listed at all. -/// -/// # Safety -/// -/// As [`query`]'s. -unsafe fn bus_addresses( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> (Option<(u32, u32, u32, u32)>, Option<(i64, i64)>) { - // SAFETY: the caller's contract. - let listed = unsafe { instance.enumerate_device_extension_properties(physical) }; - let Ok(listed) = listed else { - return (None, None); - }; - let has = |name: &std::ffi::CStr| { - listed - .iter() - .any(|extension| extension.extension_name_as_c_str() == Ok(name)) - }; - let pci = has(ash::ext::pci_bus_info::NAME); - let drm = has(ash::ext::physical_device_drm::NAME); - if !(pci || drm) { - return (None, None); - } - let mut bus = vk::PhysicalDevicePCIBusInfoPropertiesEXT::default(); - let mut nodes = vk::PhysicalDeviceDrmPropertiesEXT::default(); - let mut properties = vk::PhysicalDeviceProperties2::default(); - if pci { - properties = properties.push_next(&mut bus); - } - if drm { - properties = properties.push_next(&mut nodes); - } - // SAFETY: the caller's contract; each structure chained is of an extension the device lists. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - bus_addresses_of(pci.then_some(&bus), drm.then_some(&nodes)) -} - -/// The PCI bus address in `bus` and the DRM render node in `nodes`, the structures the driver -/// filled for the extensions it lists ([`bus_addresses`]): `None` for one the driver does not -/// list, and `None` for the render node of a driver that reports the device has none -/// (`hasRender` false), whose `renderMajor` and `renderMinor` say nothing. -pub(crate) fn bus_addresses_of( - bus: Option<&vk::PhysicalDevicePCIBusInfoPropertiesEXT>, - nodes: Option<&vk::PhysicalDeviceDrmPropertiesEXT>, -) -> (Option<(u32, u32, u32, u32)>, Option<(i64, i64)>) { - let pci = bus.map(|bus| { - ( - bus.pci_domain, - bus.pci_bus, - bus.pci_device, - bus.pci_function, - ) - }); - let render = nodes - .filter(|nodes| nodes.has_render == vk::TRUE) - .map(|nodes| (nodes.render_major, nodes.render_minor)); - (pci, render) -} - -/// `gpuCoreCount` of `physical` as its driver reports it -/// ([`DeviceProperties::gpu_core_count`](crate::DeviceProperties::gpu_core_count)): through the -/// first of NVIDIA's, AMD's and Arm's extensions that the driver lists, each read only where -/// listed (a query of properties enables nothing); `None` where it lists none, or reports 0. -/// -/// # Safety -/// -/// As [`query`]'s. -unsafe fn gpu_core_count(instance: &ash::Instance, physical: vk::PhysicalDevice) -> Option { - // SAFETY: the caller's contract. - let listed = unsafe { instance.enumerate_device_extension_properties(physical) }.ok()?; - let has = |name: &std::ffi::CStr| { - listed - .iter() - .any(|extension| extension.extension_name_as_c_str() == Ok(name)) - }; - let nvidia = has(ash::nv::shader_sm_builtins::NAME); - let amd = has(ash::amd::shader_core_properties::NAME); - let amd_active = has(ash::amd::shader_core_properties2::NAME); - let arm = has(ash::arm::shader_core_builtins::NAME); - let mut sms = vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV::default(); - let mut cores = vk::PhysicalDeviceShaderCorePropertiesAMD::default(); - let mut active = vk::PhysicalDeviceShaderCoreProperties2AMD::default(); - let mut arm_cores = vk::PhysicalDeviceShaderCoreBuiltinsPropertiesARM::default(); - let mut properties = vk::PhysicalDeviceProperties2::default(); - if nvidia { - properties = properties.push_next(&mut sms); - } - if amd { - properties = properties.push_next(&mut cores); - } - if amd_active { - properties = properties.push_next(&mut active); - } - if arm { - properties = properties.push_next(&mut arm_cores); - } - if !(nvidia || amd || amd_active || arm) { - return None; - } - // SAFETY: the caller's contract; each structure chained is of an extension the device lists. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - let amd_total = cores - .shader_engine_count - .saturating_mul(cores.shader_arrays_per_engine_count) - .saturating_mul(cores.compute_units_per_shader_array); - [ - (nvidia, sms.shader_sm_count), - (amd_active, active.active_compute_unit_count), - (amd, amd_total), - (arm, arm_cores.shader_core_count), - ] - .into_iter() - .find_map(|(listed, count)| (listed && count > 0).then_some(count)) -} - -/// The `driverUUID` and `deviceUUID` of `physical`. -/// -/// # Safety -/// -/// As [`query`]'s. -pub(super) unsafe fn uuids( - instance: &ash::Instance, - physical: vk::PhysicalDevice, -) -> [[u8; 16]; 2] { - let mut v11 = vk::PhysicalDeviceVulkan11Properties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut v11); - // SAFETY: the caller's contract; `VkPhysicalDeviceVulkan11Properties` is core in 1.2. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - [v11.driver_uuid, v11.device_uuid] -} diff --git a/crates/metal2vulkan-runtime/src/device/queue_quiet.rs b/crates/metal2vulkan-runtime/src/device/queue_quiet.rs deleted file mode 100644 index c23ab93b4..000000000 --- a/crates/metal2vulkan-runtime/src/device/queue_quiet.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! The device's uses of its `VkQueue`s seen as one: how many are under way, and when the last one -//! ended, for work that holds every submission of the device while it runs, so that it begins -//! right after a burst of submissions returned rather than beside one. -//! -//! **What it is for.** A pooled block's `vkAllocateMemory` holds the device's submissions on some -//! drivers: on RADV (a Radeon 780M, kernel 7.3.1) the kernel allocates a block's pages under the -//! reservation of the device's GPU address space, which every submission of the device takes, so -//! a submission made meanwhile waited up to 29 ms for a 64 MiB block, and on NVIDIA's driver each -//! `vkAllocateMemory` holds every submission until it returns (`memory.rs`). Blocks made ahead -//! (`memory/ready.rs`) wait here for a moment ([`QueueQuiet::wait_after_burst`]). -//! -//! **What counts as a use.** A hold of a queue's lock (`SlotHold`), which every use of one of the -//! device's `VkQueue`s the runtime makes takes, and a submission to its staging queue. The -//! program's own uses of its reserved or extra queues, and of an adopted device's, are not seen. - -use crate::gpu_time; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::time::{Duration, Instant}; - -/// How long no use may be under way, after one ended, before a burst of uses is taken to have -/// ended: the gap that begins a burst (`submit_stalls::IDLE_NANOS`). -pub(crate) const SETTLE: Duration = Duration::from_nanos(super::submit_stalls::IDLE_NANOS); - -/// How often a wait looks again while a use is under way. -const LOOK_EVERY: Duration = Duration::from_micros(250); - -/// The device's queue uses (the module docs). -#[derive(Default)] -pub(crate) struct QueueQuiet { - /// The uses under way. - in_use: AtomicU32, - /// When the last use ended, in [`gpu_time::host_nanos`]; 0 before the first. - ended_at: AtomicU64, -} - -/// How a [`QueueQuiet::wait_after_burst`] ended. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Waited { - /// No use was under way as the wait began, and none had ended for its bound: the device had - /// no submissions to fit between. - Idle, - /// A burst of uses ended after the wait began, and [`SETTLE`] passed with none under way. - AfterBurst, - /// The wait's bound passed first. - Bound, - /// The caller's `now` said to stop waiting. - Asked, -} - -impl QueueQuiet { - /// A use begins. - pub(crate) fn began(&self) { - self.in_use.fetch_add(1, Ordering::AcqRel); - } - - /// How long no use has been under way: `None` while one is, the time since the last one ended - /// otherwise, [`Duration::MAX`] before the first. - pub(crate) fn unused_for(&self) -> Option { - if self.in_use.load(Ordering::Acquire) > 0 { - return None; - } - match self.ended_at.load(Ordering::Acquire) { - 0 => Some(Duration::MAX), - ended_at => Some(Duration::from_nanos( - gpu_time::host_nanos().saturating_sub(ended_at), - )), - } - } - - /// A use that [began](Self::began) ends. - pub(crate) fn ended(&self) { - self.ended_at - .store(gpu_time::host_nanos().max(1), Ordering::Release); - self.in_use.fetch_sub(1, Ordering::AcqRel); - } - - /// Wait for a burst of uses to end after the call: a use ended since, and none has been under - /// way for [`SETTLE`] since the last one ended. At most `most`, and no longer once `now` says - /// so (asked between looks). None at all where no use is under way and none ended within - /// `most`: a device that has not used its queues for that long has no submissions to fit - /// between, and whenever the work runs it is as likely to meet the next one. - pub(crate) fn wait_after_burst(&self, most: Duration, now: impl Fn() -> bool) -> Waited { - let began = Instant::now(); - let seen = self.ended_at.load(Ordering::Acquire); - let since = gpu_time::host_nanos().saturating_sub(seen); - let idle = seen == 0 || Duration::from_nanos(since) >= most; - if idle && self.in_use.load(Ordering::Acquire) == 0 { - return Waited::Idle; - } - loop { - if now() { - return Waited::Asked; - } - let left = most.saturating_sub(began.elapsed()); - if left.is_zero() { - return Waited::Bound; - } - let ended_at = self.ended_at.load(Ordering::Acquire); - let pause = match self.in_use.load(Ordering::Acquire) { - 0 if ended_at != seen => { - let since = gpu_time::host_nanos().saturating_sub(ended_at); - match SETTLE.checked_sub(Duration::from_nanos(since)) { - None => return Waited::AfterBurst, - Some(pause) => pause, - } - } - _ => LOOK_EVERY, - }; - std::thread::sleep(pause.min(LOOK_EVERY).min(left)); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs deleted file mode 100644 index 2b63714e1..000000000 --- a/crates/metal2vulkan-runtime/src/device/relay.rs +++ /dev/null @@ -1,929 +0,0 @@ -//! MoltenVK's command-buffer failures, relayed to the command buffer that failed. -//! -//! **Metal.** A GPU fault fails the command buffer it struck, and the queue runs on: our probe (an -//! M4 with macOS 27.0.1, plain Metal) measured a blit into a buffer over -//! read-only pages failing with `MTLCommandBufferErrorInternal` (1, "Discarded (victim of GPU -//! error/recovery)"), as did the command buffer committed after it while it ran, the later ones -//! completing; an execution range past its buffer failing with `PageFault` (3), the next command -//! buffer completing. The consumer measured the blit's `PageFault` on an M3 Max with 26.7. -//! -//! **MoltenVK 1.4.1** runs each `VkSubmitInfo` as a Metal command buffer, in order on one Metal -//! queue per `VkQueue`. When one fails, its completed handler reports it to the instance's -//! debug-utils messengers, naming the `VkQueue` (`": Lost|Resumed VkDevice after -//! MTLCommandBuffer \"