From ea1ed367c4ffaf11670a1bb8333425104fb9ca49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wies=C5=82aw=20=C5=A0olt=C3=A9s?= Date: Sat, 19 Sep 2026 11:10:45 +0200 Subject: [PATCH] Add exact Dawn Vulkan device query --- .github/actions/graphics-sdk/action.yml | 2 +- .../linux-exact-native-device-hook-646.md | 43 +++++++ .../linux-external-image-interop-28.md | 38 +++---- eng/graphics/DawnSymbolBoundary.cmake | 14 ++- eng/graphics/README.md | 2 +- eng/graphics/build.py | 60 +++++++++- eng/graphics/dawn_exports.py | 9 +- eng/graphics/dawn_native_device.cpp | 107 ++++++++++++++++++ eng/graphics/dawn_native_device_internal.h | 10 ++ eng/graphics/tests/test_dawn_exports.py | 12 +- eng/graphics/verify-sdk.py | 19 ++++ .../CMakeLists.txt | 3 +- .../graphics/dawn_linux_external_provider.h | 83 +++++++++++++- .../graphics/webscene/dawn_native_device.h | 61 ++++++++++ ...linux_external_provider_contract_tests.cpp | 16 +++ src/WebScene.Sdk/cmake/LinuxSDK.cmake | 3 +- .../cmake/WebSceneLinuxConfig.cmake | 2 +- src/WebScene.Sdk/cmake/WebSceneLinuxSDK.cmake | 3 +- 18 files changed, 454 insertions(+), 33 deletions(-) create mode 100644 docs/validation/linux-exact-native-device-hook-646.md create mode 100644 eng/graphics/dawn_native_device.cpp create mode 100644 eng/graphics/dawn_native_device_internal.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h diff --git a/.github/actions/graphics-sdk/action.yml b/.github/actions/graphics-sdk/action.yml index 396cae0ae..d15abc047 100644 --- a/.github/actions/graphics-sdk/action.yml +++ b/.github/actions/graphics-sdk/action.yml @@ -20,7 +20,7 @@ runs: name: Resolve graphics SDK cache identity shell: bash env: - SDK_INPUTS: ${{ hashFiles('eng/graphics/dependencies.lock.json', 'eng/graphics/windows-runtime.json', 'eng/graphics/build.py', 'eng/graphics/DawnSymbolBoundary.cmake', 'eng/graphics/dawn_exports.py', 'eng/graphics/install-windows-sdk.ps1', '.github/actions/graphics-sdk/action.yml') }} + SDK_INPUTS: ${{ hashFiles('eng/graphics/dependencies.lock.json', 'eng/graphics/windows-runtime.json', 'eng/graphics/build.py', 'eng/graphics/DawnSymbolBoundary.cmake', 'eng/graphics/dawn_exports.py', 'eng/graphics/dawn_native_device.cpp', 'eng/graphics/dawn_native_device_internal.h', 'experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h', 'eng/graphics/install-windows-sdk.ps1', '.github/actions/graphics-sdk/action.yml') }} run: | set -euo pipefail { diff --git a/docs/validation/linux-exact-native-device-hook-646.md b/docs/validation/linux-exact-native-device-hook-646.md new file mode 100644 index 000000000..5da9387fa --- /dev/null +++ b/docs/validation/linux-exact-native-device-hook-646.md @@ -0,0 +1,43 @@ +# Exact Dawn Vulkan device hook + +Issue: #646. The pinned Linux Dawn build exports +`websceneDawnQueryVulkanDeviceV1`, a product-neutral C ABI that accepts only a +live `WGPUDevice` created by that build. It returns borrowed opaque +`VkPhysicalDevice`, `VkDevice` and `VkQueue` identities, the graphics queue +family, exact public adapter/device tokens, and Vulkan device/driver UUIDs. + +Dawn's existing instance device list is the lifecycle authority. A transient, +pin-specific build patch registers and unregisters devices at the same add/remove +methods. The query checks the registry before dereferencing a token, retains the +device during inspection, holds its guard, and rejects foreign, lost, +non-Vulkan or incomplete identities. SDK verification covers the installed +header, bridge sources, export allowlist and cache inputs. AppScene includes no +Dawn private header. + +`bind_dawn_linux_external_device` is the factory consumption point. It copies +the `wgpu::Device` into the lifetime anchor and requires the same shared atomic +loss flag used by the host's Dawn device-lost callback. Allocation, begin, +end and export operations fail closed after loss. Native handles remain +Dawn-owned and borrowed; allocators may use them but never destroy them. + +Per the directed checkpoint policy, the authored build and contract gates were +not run. Validation for this change is limited to `git diff --check`. + +## Focused follow-up issue draft + +**Title:** Implement exact-device Linux Vulkan external-memory allocator + +Create the AppScene `dawn_linux_external_device_factory` around a Dawn Vulkan +device bound through `bind_dawn_linux_external_device`. Allocate exportable +opaque-FD and supported DMA-BUF images on the returned exact `VkDevice` and +queue family; retain `VkImage`, memory and create-info chains; export owned +memory and synchronization FDs; and adopt them through +`owned_dawn_linux_external_allocation`. Reject unsupported formats, modifiers, +handle types, queue ownership, UUID mismatches and device loss. Do not accept +ordinary Dawn textures and do not add CPU readback/upload fallback. + +Acceptance requires real Linux Vulkan hardware evidence for both supported +handle routes, BeginAccess/EndAccess layout and synchronization rotation, +negative foreign-device and device-loss cases, X11 and Wayland presentation, +resize teardown, a 30-minute FD/residency plateau, and zero CPU transfer in +ordinary frames. diff --git a/docs/validation/linux-external-image-interop-28.md b/docs/validation/linux-external-image-interop-28.md index 67a066238..c7c8411dd 100644 --- a/docs/validation/linux-external-image-interop-28.md +++ b/docs/validation/linux-external-image-interop-28.md @@ -68,23 +68,25 @@ provider seam around the pinned public Dawn ABI: `linux_external_image_provider`. Failed or partial handoffs publish nothing and RAII closes every already-exported FD. -The installed Dawn C ABI exposes only Vulkan `driverVersion` in -`AdapterPropertiesVk`. The pinned `dawn/native/VulkanBackend.h` adds only -`GetInstance` and `GetInstanceProcAddr`; it exposes no `VkDevice`, -`VkPhysicalDevice`, `VkQueue`, queue family or device/driver UUID, and Dawn's -adapter creates its own `VkDevice` rather than wrapping one supplied by a host. -The implementations that expose these objects live under Dawn's private -`src/dawn/native/vulkan` tree and are not an SDK contract. WebScene therefore -does not infer device identity from the Vulkan instance, adapter properties or -matching UUIDs. +The pinned public Dawn API still has no supported `VkDevice`, +`VkPhysicalDevice`, `VkQueue` or queue-family accessor. The WebScene-owned +Linux Dawn build now adds one narrow, versioned C ABI query at that private/public +boundary. Dawn registers devices on its authoritative `InstanceBase` add/remove +path. The query rejects tokens absent from that live registry before +dereferencing them, rejects lost and non-Vulkan devices, and returns the exact +public adapter/device tokens, borrowed native tuple, queue family and Vulkan +device/driver UUIDs. The SDK ships only `webscene/dawn_native_device.h`; no Dawn +private header crosses into AppScene. The SDK now exposes `dawn_linux_external_device_factory`. An AppScene host with an exact-device Dawn integration creates the WebGPU instance/adapter/device and native allocator atomically, and returns one `dawn_linux_external_device_lifetime` shared by the allocator and every -allocation. That lifetime carries the exact public `WGPUAdapter`/`WGPUDevice` tokens, +allocation. `bind_dawn_linux_external_device` populates it from the exact Dawn +device and retains a copied `wgpu::Device`. That lifetime carries the exact public `WGPUAdapter`/`WGPUDevice` tokens, opaque identities for the native device/physical-device/queue, device/driver -UUIDs, Dawn queue family and a host-owned lifetime anchor for that tuple. +UUIDs, Dawn queue family, a host-owned lifetime anchor for that tuple and the +same atomic device-loss state installed in the factory callback. Provider creation rejects a copied lifetime object, mismatched device token, UUID or queue family. @@ -125,14 +127,12 @@ FD/residency plateau, and proof of zero CPU readback/upload in ordinary frames. ## Remaining concrete blocker -Implement `dawn_linux_external_device_factory` in AppScene against a supported -exact-device Dawn integration. The current pinned public Dawn library cannot do -this by itself, so the host needs a narrowly supported Dawn SDK hook (or an -equivalent host-owned Dawn build) that returns the exact native device, -physical-device, queue and queue family for the created `WGPUDevice`. The host -then allocates/exports opaque-FD or DMA-BUF storage on those handles, adopts it -through `owned_dawn_linux_external_allocation`, and negotiates hardware support -per format, modifier, handle type and synchronization route. Real Linux Vulkan +Implement the AppScene factory's real Vulkan allocator against the exact native +tuple returned by `bind_dawn_linux_external_device`. It must allocate and export +opaque-FD or DMA-BUF storage on those handles, retain every `VkImage` and +`VkDeviceMemory`, adopt it through `owned_dawn_linux_external_allocation`, and +negotiate hardware support per format, modifier, handle type and synchronization +route. Real Linux Vulkan hardware/driver execution is still required for pixels, negative identity and layout cases, device loss, FD/residency plateau and zero-readback evidence. Unsupported routes remain explicit and cannot fall back to CPU presentation diff --git a/eng/graphics/DawnSymbolBoundary.cmake b/eng/graphics/DawnSymbolBoundary.cmake index f8f392390..c44a14e71 100644 --- a/eng/graphics/DawnSymbolBoundary.cmake +++ b/eng/graphics/DawnSymbolBoundary.cmake @@ -11,11 +11,23 @@ function(webscene_isolate_dawn) set_property(TARGET webgpu_dawn_objects PROPERTY ${property} "${definitions}") endif() endforeach() + if(UNIX AND NOT APPLE) + # This source is compiled inside Dawn so it can use the pinned private + # types. Consumers receive only its versioned C ABI header. + target_sources(dawn_native_objects PRIVATE + "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/dawn_native_device.cpp") + target_include_directories(dawn_native_objects PRIVATE + "${CMAKE_CURRENT_FUNCTION_LIST_DIR}" + "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../experiments/WebScene.NativeEngine.Probe/native/graphics") + target_compile_definitions(dawn_native_objects PRIVATE + WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE=1) + endif() if(APPLE) file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports" "_wgpu*\n") target_link_options(webgpu_dawn PRIVATE "LINKER:-exported_symbols_list,${CMAKE_BINARY_DIR}/webscene-dawn.exports") elseif(UNIX) - file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports" "{ global: wgpu*; local: *; };\n") + file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports" + "{ global: wgpu*; websceneDawnQueryVulkanDeviceV1; local: *; };\n") target_link_options(webgpu_dawn PRIVATE "LINKER:--version-script=${CMAKE_BINARY_DIR}/webscene-dawn.exports") endif() # Windows exports only functions decorated by WGPU_SHARED_LIBRARY; diff --git a/eng/graphics/README.md b/eng/graphics/README.md index c3b774c8f..cb3657dc7 100644 --- a/eng/graphics/README.md +++ b/eng/graphics/README.md @@ -6,7 +6,7 @@ Implements part of [#23](https://github.com/wieslawsoltes/WebScene/issues/23), t `dependencies.lock.json` pins Dawn (including Tint and generated WebGPU headers), ANGLE, depot_tools, WebGPU CTS, Khronos WebGL and WPT to exact commits. Dawn's own pinned `DEPS` supplies its transitive source revisions; ANGLE uses its pinned `DEPS` through gclient with depot_tools self-update disabled. The installed package records the transitive Git revision graph, exact CMake/GN settings, tool identities, source licenses/notices and hashes of every installed header/library. There is no ProGPU or renderer replacement dependency. -Dawn uses a shared `webgpu_dawn` monolith exporting only WebGPU C entry points. Static co-linkage with V8 exposed conflicting unversioned Abseil symbols and caused native runtime hangs; the shared boundary keeps those implementations private. `DawnSymbolBoundary.cmake` applies the export policy without patching upstream sources, and the builder checks actual binary exports before sealing the SDK. ANGLE uses shared EGL/GLESv2 with static internal dependencies and C ABI entry points. Windows release builds use static CRT for Dawn, matching the existing native engine/V8; ANGLE's non-component Chromium configuration controls its runtime. Windows build/link and runtime dependency validation (including D3D shader compiler packaging) remain hardware-runner gates. Never exchange CRT-owned allocations between these libraries. +Dawn uses a shared `webgpu_dawn` monolith exporting WebGPU C entry points. On Linux it also exports the single versioned `websceneDawnQueryVulkanDeviceV1` C entry point, which returns borrowed native identities only for a live device created by this exact Dawn build. Static co-linkage with V8 exposed conflicting unversioned Abseil symbols and caused native runtime hangs; the shared boundary keeps those implementations private. `DawnSymbolBoundary.cmake` applies the export policy, and the builder checks actual binary exports before sealing the SDK. The Linux builder temporarily connects Dawn's authoritative device add/remove path to the query registry and restores the pinned source before provenance sealing. No private Dawn header enters the installed SDK. ANGLE uses shared EGL/GLESv2 with static internal dependencies and C ABI entry points. Windows release builds use static CRT for Dawn, matching the existing native engine/V8; ANGLE's non-component Chromium configuration controls its runtime. Windows build/link and runtime dependency validation (including D3D shader compiler packaging) remain hardware-runner gates. Never exchange CRT-owned allocations between these libraries. `GraphicsDependencies.cmake` verifies the SDK before importing it, including revision, RID, lock, settings, complete installed file inventory and content hashes. CMake cannot silently choose another `Dawn_DIR`. A dependency roll requires rebuilding headers and libraries together. Package manifests prove integrity and provenance, not API conformance or hardware execution. diff --git a/eng/graphics/build.py b/eng/graphics/build.py index f3da663f1..c5dc7fb91 100644 --- a/eng/graphics/build.py +++ b/eng/graphics/build.py @@ -18,6 +18,10 @@ LOCK_PATH = Path(__file__).with_name("dependencies.lock.json") LOCK = json.loads(LOCK_PATH.read_text()) WINDOWS_RUNTIME_PIN_PATH = Path(__file__).with_name("windows-runtime.json") +DAWN_NATIVE_DEVICE_HEADER = (ROOT / "experiments/WebScene.NativeEngine.Probe/native/graphics/" + "webscene/dawn_native_device.h") +DAWN_NATIVE_DEVICE_SOURCE = Path(__file__).with_name("dawn_native_device.cpp") +DAWN_NATIVE_DEVICE_INTERNAL = Path(__file__).with_name("dawn_native_device_internal.h") WINDOWS_DEVELOPER_ENVIRONMENT_KEYS = { "COMMANDPROMPTTYPE", "DEVENVDIR", "EXTENSIONSDKDIR", "EXTERNAL_INCLUDE", "FRAMEWORK40VERSION", "FRAMEWORKDIR", "FRAMEWORKDIR64", "FRAMEWORKVERSION", @@ -187,6 +191,49 @@ def seal(component, source, sdk, rid, settings, tools, env=None): (sdk / "webscene-graphics-package.json").write_text(json.dumps(manifest, indent=2) + "\n") +@contextmanager +def patched_dawn_native_device_bridge(source): + """Temporarily connect the pinned Dawn device registry to WebScene's bridge.""" + instance = source / "src/dawn/native/Instance.cpp" + original = instance.read_bytes() + include = b'#include "src/dawn/native/Device.h"\n' + include_patch = (include + b'#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE)\n' + b'#include "dawn_native_device_internal.h"\n' + b'#endif\n') + methods = b'''void InstanceBase::AddDevice(DeviceBase* device) { + mDevicesList.Use([&](auto deviceList) { deviceList->insert(device); }); +} + +void InstanceBase::RemoveDevice(DeviceBase* device) { + mDevicesList.Use([&](auto deviceList) { deviceList->erase(device); }); +} +''' + methods_patch = b'''void InstanceBase::AddDevice(DeviceBase* device) { + mDevicesList.Use([&](auto deviceList) { deviceList->insert(device); }); +#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE) + webscene::dawn_bridge::register_device(device); +#endif +} + +void InstanceBase::RemoveDevice(DeviceBase* device) { +#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE) + webscene::dawn_bridge::unregister_device(device); +#endif + mDevicesList.Use([&](auto deviceList) { deviceList->erase(device); }); +} +''' + if original.count(include) != 1 or original.count(methods) != 1: + raise ValueError( + "Pinned Dawn Instance device registry changed unexpectedly; " + "review the exact native-device bridge against the new source") + patched = original.replace(include, include_patch).replace(methods, methods_patch) + try: + instance.write_bytes(patched) + yield + finally: + instance.write_bytes(original) + + def dawn(args): source = args.sources / "dawn" checkout("dawn", source) @@ -204,13 +251,24 @@ def dawn(args): f"-DCMAKE_INSTALL_PREFIX={sdk}", f"-DCMAKE_PROJECT_Dawn_INCLUDE={symbol_policy}", "-DCMAKE_SHARED_LINKER_FLAGS="] + [f"-D{k}={v}" for k, v in settings.items()]) repair_dawn_dependencies(source) - run(["cmake", "--build", output, "--parallel", args.jobs]) + bridge = (patched_dawn_native_device_bridge(source) + if args.rid.startswith("linux-") else nullcontext()) + with bridge: + run(["cmake", "--build", output, "--parallel", args.jobs]) # Old installed headers/libraries must not survive a dependency roll. if sdk.exists(): remove_sdk(sdk) run(["cmake", "--install", output]) sdk.joinpath("build-info").mkdir() shutil.copy2(symbol_policy, sdk / "build-info/DawnSymbolBoundary.cmake") + if args.rid.startswith("linux-"): + sdk.joinpath("include/webscene").mkdir() + shutil.copy2(DAWN_NATIVE_DEVICE_HEADER, sdk / "include/webscene/dawn_native_device.h") + bridge_info = sdk / "build-info/webscene-dawn-native-device" + bridge_info.mkdir() + for path in (DAWN_NATIVE_DEVICE_HEADER, DAWN_NATIVE_DEVICE_SOURCE, + DAWN_NATIVE_DEVICE_INTERNAL): + shutil.copy2(path, bridge_info / path.name) binary = sdk / {"win-x64": "bin/webgpu_dawn.dll", "osx-arm64": "lib/libwebgpu_dawn.dylib", "linux-x64": "lib/libwebgpu_dawn.so"}[args.rid] (sdk / "build-info/exports.json").write_text(json.dumps(inspect_exports(binary, args.rid), indent=2) + "\n") diff --git a/eng/graphics/dawn_exports.py b/eng/graphics/dawn_exports.py index 2f0f961da..62248c9ea 100644 --- a/eng/graphics/dawn_exports.py +++ b/eng/graphics/dawn_exports.py @@ -19,7 +19,12 @@ def inspect_exports(library, rid): if match: symbol = match.group(1) symbols.append(symbol[1:] if rid.startswith("osx-") and symbol.startswith("_") else symbol) - unexpected = [name for name in symbols if not re.fullmatch(r"wgpu[A-Z][A-Za-z0-9]*", name)] - if unexpected or not {"wgpuCreateInstance", "wgpuGetProcAddress"} <= set(symbols): + allowed_bridge = ({"websceneDawnQueryVulkanDeviceV1"} + if rid.startswith("linux-") else set()) + unexpected = [name for name in symbols + if not re.fullmatch(r"wgpu[A-Z][A-Za-z0-9]*", name) + and name not in allowed_bridge] + required = {"wgpuCreateInstance", "wgpuGetProcAddress"} | allowed_bridge + if unexpected or not required <= set(symbols): raise ValueError(f"Dawn C export boundary failed: unexpected={unexpected[:20]}, exports={len(symbols)}") return {"status": "passed", "command": command, "exports": sorted(symbols)} diff --git a/eng/graphics/dawn_native_device.cpp b/eng/graphics/dawn_native_device.cpp new file mode 100644 index 000000000..a18ac4c11 --- /dev/null +++ b/eng/graphics/dawn_native_device.cpp @@ -0,0 +1,107 @@ +#include "dawn_native_device_internal.h" +#include "webscene/dawn_native_device.h" + +#include +#include +#include + +#include "src/dawn/common/Ref.h" +#include "src/dawn/native/Adapter.h" +#include "src/dawn/native/Device.h" +#include "src/dawn/native/PhysicalDevice.h" +#include "src/dawn/native/vulkan/DeviceVk.h" +#include "src/dawn/native/vulkan/Forward.h" +#include "src/dawn/native/vulkan/PhysicalDeviceVk.h" +#include "src/dawn/native/vulkan/QueueVk.h" + +namespace { +struct live_devices { + std::mutex mutex; + std::unordered_map values; +}; + +live_devices& devices() { + // Dawn devices may outlive other process statics. Keep the registry alive + // until process teardown rather than racing its destructor at shutdown. + static auto* value=new live_devices; + return *value; +} + +dawn::Ref find_device(WGPUDevice token) noexcept { + auto& registry=devices(); + std::lock_guard lock(registry.mutex); + const auto found=registry.values.find(token); + if(found==registry.values.end()||!found->second->TryAddRef())return {}; + return dawn::AcquireRef(found->second); +} + +bool nonzero_uuid(const uint8_t* value) noexcept { + for(size_t index=0;indexsecond==device)registry.values.erase(found); +} +} + +extern "C" webscene_dawn_native_device_status_v1 websceneDawnQueryVulkanDeviceV1( + WGPUDevice token,webscene_dawn_native_device_v1* result) { + if(!token||!result)return WEBSCENE_DAWN_NATIVE_DEVICE_INVALID_ARGUMENT_V1; + if(result->struct_sizeversion!=WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION) + return WEBSCENE_DAWN_NATIVE_DEVICE_INCOMPATIBLE_ABI_V1; + auto base=find_device(token); + if(!base)return WEBSCENE_DAWN_NATIVE_DEVICE_FOREIGN_DEVICE_V1; + auto guard=base->GetGuard(); + if(base->GetState()!=dawn::native::DeviceBase::State::Alive||!base->GetQueue()) + return WEBSCENE_DAWN_NATIVE_DEVICE_LOST_V1; + if(base->GetPhysicalDevice()->GetBackendType()!=wgpu::BackendType::Vulkan) + return WEBSCENE_DAWN_NATIVE_DEVICE_NOT_VULKAN_V1; + + auto* device=dawn::native::vulkan::ToBackend(base.Get()); + auto* physical=dawn::native::vulkan::ToBackend(base->GetPhysicalDevice()); + auto* queue=dawn::native::vulkan::ToBackend(base->GetQueue()); + VkPhysicalDeviceIDProperties ids{}; + ids.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES; + VkPhysicalDeviceProperties2 properties{}; + properties.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; + properties.pNext=&ids; + device->fn.GetPhysicalDeviceProperties2(physical->GetVkPhysicalDevice(),&properties); + if(!nonzero_uuid(ids.deviceUUID)||!nonzero_uuid(ids.driverUUID)) + return WEBSCENE_DAWN_NATIVE_DEVICE_INVALID_IDENTITY_V1; + + webscene_dawn_native_device_v1 value{}; + value.struct_size=sizeof(value); + value.version=WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION; + value.adapter=dawn::native::ToAPI(base->GetAdapter()); + value.device=token; + value.vk_physical_device=reinterpret_cast(physical->GetVkPhysicalDevice()); + value.vk_device=reinterpret_cast(device->GetVkDevice()); + value.vk_queue=reinterpret_cast(queue->GetVkQueue()); + value.queue_family=device->GetGraphicsQueueFamily(); + std::memcpy(value.device_uuid,ids.deviceUUID,VK_UUID_SIZE); + std::memcpy(value.driver_uuid,ids.driverUUID,VK_UUID_SIZE); + *result=value; + return WEBSCENE_DAWN_NATIVE_DEVICE_SUCCESS_V1; +} diff --git a/eng/graphics/dawn_native_device_internal.h b/eng/graphics/dawn_native_device_internal.h new file mode 100644 index 000000000..d7f782cd1 --- /dev/null +++ b/eng/graphics/dawn_native_device_internal.h @@ -0,0 +1,10 @@ +#pragma once + +namespace dawn::native { +class DeviceBase; +} + +namespace webscene::dawn_bridge { +void register_device(dawn::native::DeviceBase*) noexcept; +void unregister_device(dawn::native::DeviceBase*) noexcept; +} diff --git a/eng/graphics/tests/test_dawn_exports.py b/eng/graphics/tests/test_dawn_exports.py index 6e61d72ed..8a0203365 100644 --- a/eng/graphics/tests/test_dawn_exports.py +++ b/eng/graphics/tests/test_dawn_exports.py @@ -17,7 +17,8 @@ def inspect(self, text, rid): def test_native_symbol_formats(self): for rid, text in [ ("osx-arm64", "00001000 T _wgpuCreateInstance\n00001010 T _wgpuGetProcAddress\n"), - ("linux-x64", "00001000 T wgpuCreateInstance\n00001010 T wgpuGetProcAddress\n"), + ("linux-x64", "00001000 T wgpuCreateInstance\n00001010 T wgpuGetProcAddress\n" + "00001020 T websceneDawnQueryVulkanDeviceV1\n"), ("win-x64", " 1 0 00001000 wgpuCreateInstance\n 2 1 00001010 wgpuGetProcAddress\n")]: with self.subTest(rid=rid): self.assertEqual(self.inspect(text, rid)["status"], "passed") @@ -26,6 +27,15 @@ def test_bundled_dependency_export_is_rejected(self): with self.assertRaises(ValueError): self.inspect("1000 T wgpuCreateInstance\n1010 T wgpuGetProcAddress\n1020 T AbslInternalSpinLockDelay\n", "linux-x64") + def test_linux_bridge_is_required_and_exact(self): + for text in [ + "1000 T wgpuCreateInstance\n1010 T wgpuGetProcAddress\n", + "1000 T wgpuCreateInstance\n1010 T wgpuGetProcAddress\n" + "1020 T websceneDawnQueryVulkanDeviceV2\n", + ]: + with self.subTest(text=text), self.assertRaises(ValueError): + self.inspect(text, "linux-x64") + def test_unrecognized_or_partial_output_is_not_a_pass(self): for text in ["", "unexpected symbol tool output", "1000 T _wgpuCreateInstance\n"]: with self.subTest(text=text), self.assertRaises(ValueError): diff --git a/eng/graphics/verify-sdk.py b/eng/graphics/verify-sdk.py index 5f9be81ad..0ebc0e578 100644 --- a/eng/graphics/verify-sdk.py +++ b/eng/graphics/verify-sdk.py @@ -7,6 +7,7 @@ import sys LOCK_PATH = Path(__file__).with_name("dependencies.lock.json") +ROOT = Path(__file__).resolve().parents[2] def sha(path): @@ -75,6 +76,24 @@ def verify(sdk, component, rid): raise ValueError("dawn: pinned Windows shader compiler or license mismatch") if sha(sdk / "build-info/DawnSymbolBoundary.cmake") != sha(LOCK_PATH.with_name("DawnSymbolBoundary.cmake")): raise ValueError("dawn: symbol isolation policy mismatch; rebuild the SDK") + if rid.startswith("linux-"): + bridge_files = { + "include/webscene/dawn_native_device.h": + ROOT / "experiments/WebScene.NativeEngine.Probe/native/graphics/" + "webscene/dawn_native_device.h", + "build-info/webscene-dawn-native-device/dawn_native_device.h": + ROOT / "experiments/WebScene.NativeEngine.Probe/native/graphics/" + "webscene/dawn_native_device.h", + "build-info/webscene-dawn-native-device/dawn_native_device.cpp": + LOCK_PATH.with_name("dawn_native_device.cpp"), + "build-info/webscene-dawn-native-device/dawn_native_device_internal.h": + LOCK_PATH.with_name("dawn_native_device_internal.h"), + } + required |= set(bridge_files) + for installed, canonical in bridge_files.items(): + if files.get(installed) != sha(canonical): + raise ValueError( + f"dawn: exact native-device bridge mismatch: {installed}") if not required <= set(files): raise ValueError(f"{component}: required headers/libraries missing: {sorted(required - set(files))}") print(f"Verified {component} {manifest['revision']} for {rid}: {len(files)} files") diff --git a/experiments/WebScene.NativeEngine.Probe/CMakeLists.txt b/experiments/WebScene.NativeEngine.Probe/CMakeLists.txt index 2ee514058..eb91a2677 100644 --- a/experiments/WebScene.NativeEngine.Probe/CMakeLists.txt +++ b/experiments/WebScene.NativeEngine.Probe/CMakeLists.txt @@ -380,7 +380,8 @@ if(WEBSCENE_NATIVE_ENGINE_ENABLE_GRAPHICS) tests/graphics_dawn_linux_external_provider_contract_tests.cpp) target_compile_features(webscene_graphics_dawn_linux_external_provider_contract_tests PRIVATE cxx_std_20) target_compile_definitions(webscene_graphics_dawn_linux_external_provider_contract_tests PRIVATE - WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1) + WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1 + WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION=1) target_include_directories(webscene_graphics_dawn_linux_external_provider_contract_tests PRIVATE native) target_link_libraries(webscene_graphics_dawn_linux_external_provider_contract_tests PRIVATE dawn::webgpu_dawn) diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/dawn_linux_external_provider.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/dawn_linux_external_provider.h index 803f161b3..68591cc84 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/dawn_linux_external_provider.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/dawn_linux_external_provider.h @@ -1,6 +1,8 @@ #pragma once #include "dawn_shared_image.h" #include "linux_external_image.h" +#include "webscene/dawn_native_device.h" +#include #include namespace webscene::graphics { @@ -28,7 +30,9 @@ enum class dawn_linux_external_status : uint32_t { uninitialized_handoff, unsupported_fence, fence_export_failed, - invalid_device_factory + invalid_device_factory, + native_device_query_failed, + device_lost }; struct dawn_linux_external_device_lifetime { @@ -42,11 +46,64 @@ struct dawn_linux_external_device_lifetime { std::array device_uuid{}; std::array driver_uuid{}; uint32_t dawn_queue_family{UINT32_MAX}; + // Set by the Dawn device-lost callback before the host releases its device. + std::shared_ptr> device_lost; // Host-defined owner for the exact native device/physical-device/queue // tuple. It must outlive every allocation made from those Vulkan handles. std::shared_ptr native_owner; }; +struct dawn_linux_external_native_device_owner { + explicit dawn_linux_external_native_device_owner(const wgpu::Device& value):device(value) {} + wgpu::Device device; +}; + +// Populate the factory lifetime directly from the WebScene-pinned Dawn build. +// The copied wgpu::Device keeps every returned borrowed Vulkan identity alive. +inline dawn_linux_external_status bind_dawn_linux_external_device( + const wgpu::Adapter& adapter,const wgpu::Device& device, + std::shared_ptr> device_lost, + std::shared_ptr& result) { + result.reset(); + if(!adapter||!device||!device_lost) + return dawn_linux_external_status::invalid_argument; + if(device_lost->load(std::memory_order_acquire)) + return dawn_linux_external_status::device_lost; + webscene_dawn_native_device_v1 native{}; + native.struct_size=sizeof(native); + native.version=WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION; + const auto status=websceneDawnQueryVulkanDeviceV1(device.Get(),&native); + if(status==WEBSCENE_DAWN_NATIVE_DEVICE_LOST_V1) + return dawn_linux_external_status::device_lost; + if(status==WEBSCENE_DAWN_NATIVE_DEVICE_NOT_VULKAN_V1) + return dawn_linux_external_status::not_vulkan; + if(status!=WEBSCENE_DAWN_NATIVE_DEVICE_SUCCESS_V1) + return dawn_linux_external_status::native_device_query_failed; + if(native.adapter!=adapter.Get()||native.device!=device.Get()|| + !native.vk_physical_device||!native.vk_device||!native.vk_queue|| + native.queue_family==UINT32_MAX) + return dawn_linux_external_status::native_device_query_failed; + auto lifetime=std::make_shared(); + lifetime->dawn_adapter_token=native.adapter; + lifetime->dawn_device_token=native.device; + lifetime->vk_physical_device=native.vk_physical_device; + lifetime->vk_device=native.vk_device; + lifetime->vk_queue=native.vk_queue; + for(size_t index=0;indexdevice_uuid.size();++index) { + lifetime->device_uuid[index]=native.device_uuid[index]; + lifetime->driver_uuid[index]=native.driver_uuid[index]; + } + lifetime->dawn_queue_family=native.queue_family; + lifetime->device_lost=std::move(device_lost); + lifetime->native_owner=std::make_shared(device); + if(!nonzero_uuid(lifetime->device_uuid)||!nonzero_uuid(lifetime->driver_uuid)) + return dawn_linux_external_status::native_device_query_failed; + if(lifetime->device_lost->load(std::memory_order_acquire)) + return dawn_linux_external_status::device_lost; + result=std::move(lifetime); + return dawn_linux_external_status::success; +} + struct dawn_linux_external_allocator; // Atomic result of host-owned Dawn/Vulkan device creation. The pinned public @@ -147,6 +204,8 @@ inline bool same_dawn_linux_external_identity( const std::shared_ptr& expected, const std::shared_ptr& actual) noexcept { return expected&&expected==actual&&expected->native_owner&& + expected->device_lost&& + !expected->device_lost->load(std::memory_order_acquire)&& expected->dawn_adapter_token&&expected->dawn_device_token&& expected->dawn_adapter_token==actual->dawn_adapter_token&& expected->dawn_device_token==actual->dawn_device_token&& @@ -155,6 +214,12 @@ inline bool same_dawn_linux_external_identity( expected->dawn_queue_family!=UINT32_MAX; } +inline bool dawn_linux_external_device_is_lost( + const std::shared_ptr& value) noexcept { + return value&&value->device_lost&& + value->device_lost->load(std::memory_order_acquire); +} + inline bool dawn_linux_snapshot_matches_device( const linux_external_image_snapshot& snapshot, const dawn_linux_external_device_lifetime& device) noexcept { @@ -213,7 +278,8 @@ class owned_dawn_linux_external_allocation final : public dawn_linux_external_al } bool export_image(const image_metadata& expected, linux_external_image_snapshot& result) const override { - if(!same_image_metadata(expected,snapshot_.metadata))return false; + if(!same_dawn_linux_external_identity(device_,device_)|| + !same_image_metadata(expected,snapshot_.metadata))return false; result=snapshot_;return true; } @@ -405,7 +471,8 @@ class dawn_linux_external_provider final : public linux_external_image_provider public: bool export_image(const image_metadata& expected, linux_external_image_snapshot& result) const override { - if(!complete_||!same_image_metadata(expected,published_.metadata))return false; + if(!same_dawn_linux_external_identity(device_lifetime_,device_lifetime_)|| + !complete_||!same_image_metadata(expected,published_.metadata))return false; result=published_;return true; } const wgpu::Texture& texture() const noexcept{return shared_->texture();} @@ -419,6 +486,8 @@ class dawn_linux_external_provider final : public linux_external_image_provider const auto support=inspect_dawn_linux_external_capabilities(adapter,device,capabilities); if(support!=dawn_linux_external_status::native_device_provider_required)return support; const auto lifetime=allocator.device_lifetime(); + if(dawn_linux_external_device_is_lost(lifetime)) + return dawn_linux_external_status::device_lost; if(!same_dawn_linux_external_identity(lifetime,lifetime)|| adapter.Get()!=lifetime->dawn_adapter_token|| !valid_dawn_linux_external_binding(device.Get(), @@ -427,6 +496,8 @@ class dawn_linux_external_provider final : public linux_external_image_provider std::shared_ptr allocation; auto status=allocator.allocate(metadata,format,usage,allocation); if(status!=dawn_linux_external_status::success)return status; + if(dawn_linux_external_device_is_lost(lifetime)) + return dawn_linux_external_status::device_lost; if(!allocation||!same_dawn_linux_external_identity( lifetime,allocation->device_lifetime())|| !valid_dawn_linux_external_binding(device.Get(), @@ -492,6 +563,8 @@ class dawn_linux_external_provider final : public linux_external_image_provider } dawn_linux_external_status begin_access() { + if(!same_dawn_linux_external_identity(device_lifetime_,device_lifetime_)) + return dawn_linux_external_status::device_lost; if(active_||complete_)return dawn_linux_external_status::begin_failed; linux_external_image_snapshot source; if(!allocation_->export_image(published_.metadata,source)|| @@ -512,6 +585,10 @@ class dawn_linux_external_provider final : public linux_external_image_provider dawn_linux_external_status end_access() { if(!active_)return dawn_linux_external_status::end_failed; + if(!same_dawn_linux_external_identity(device_lifetime_,device_lifetime_)) { + active_=false; + return dawn_linux_external_status::device_lost; + } wgpu::SharedTextureMemoryVkImageLayoutEndState layout{}; wgpu::SharedTextureMemoryEndAccessState handoff{};handoff.nextInChain=&layout; if(!shared_->end(handoff)){active_=false;return dawn_linux_external_status::end_failed;} diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h new file mode 100644 index 000000000..1ecb6175d --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h @@ -0,0 +1,61 @@ +#pragma once +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION +#define WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION 1U +#endif + +typedef uint32_t webscene_dawn_native_device_status_v1; +enum { + WEBSCENE_DAWN_NATIVE_DEVICE_SUCCESS_V1 = 0, + WEBSCENE_DAWN_NATIVE_DEVICE_INVALID_ARGUMENT_V1 = 1, + WEBSCENE_DAWN_NATIVE_DEVICE_INCOMPATIBLE_ABI_V1 = 2, + WEBSCENE_DAWN_NATIVE_DEVICE_FOREIGN_DEVICE_V1 = 3, + WEBSCENE_DAWN_NATIVE_DEVICE_NOT_VULKAN_V1 = 4, + WEBSCENE_DAWN_NATIVE_DEVICE_LOST_V1 = 5, + WEBSCENE_DAWN_NATIVE_DEVICE_INVALID_IDENTITY_V1 = 6 +}; + +/* Exact native identities borrowed from one live WGPUDevice. The caller keeps + * its WGPUDevice reference alive while using or retaining these values. A + * Vulkan-aware host may cast the opaque values to the matching dispatchable + * Vulkan handle types; it must never destroy Dawn-owned objects or queues. */ +typedef struct webscene_dawn_native_device_v1 { + uint32_t struct_size; + uint32_t version; + WGPUAdapter adapter; + WGPUDevice device; + void* vk_physical_device; + void* vk_device; + void* vk_queue; + uint32_t queue_family; + uint32_t reserved; + uint8_t device_uuid[16]; + uint8_t driver_uuid[16]; +} webscene_dawn_native_device_v1; + +#if defined(_WIN32) +#define WEBSCENE_DAWN_NATIVE_DEVICE_EXPORT __declspec(dllimport) +#elif defined(__GNUC__) +#define WEBSCENE_DAWN_NATIVE_DEVICE_EXPORT __attribute__((visibility("default"))) +#else +#define WEBSCENE_DAWN_NATIVE_DEVICE_EXPORT +#endif + +/* result must carry sizeof(webscene_dawn_native_device_v1) and ABI version 1. + * Failure leaves the caller's result unchanged. Foreign tokens are rejected + * from a live-device registry before Dawn object memory is dereferenced. */ +WEBSCENE_DAWN_NATIVE_DEVICE_EXPORT webscene_dawn_native_device_status_v1 +websceneDawnQueryVulkanDeviceV1( + WGPUDevice device, webscene_dawn_native_device_v1* result); + +#undef WEBSCENE_DAWN_NATIVE_DEVICE_EXPORT + +#ifdef __cplusplus +} +#endif diff --git a/experiments/WebScene.NativeEngine.Probe/tests/graphics_dawn_linux_external_provider_contract_tests.cpp b/experiments/WebScene.NativeEngine.Probe/tests/graphics_dawn_linux_external_provider_contract_tests.cpp index 58777e04b..a1af4d6ce 100644 --- a/experiments/WebScene.NativeEngine.Probe/tests/graphics_dawn_linux_external_provider_contract_tests.cpp +++ b/experiments/WebScene.NativeEngine.Probe/tests/graphics_dawn_linux_external_provider_contract_tests.cpp @@ -7,8 +7,19 @@ void require(bool value){if(!value)throw std::runtime_error("Dawn Linux external } int main(){ static_assert(WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION==1); + static_assert(WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION==1); + webscene_dawn_native_device_v1 query{}; + query.struct_size=sizeof(query); + query.version=WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION; + require(websceneDawnQueryVulkanDeviceV1(nullptr,&query)== + WEBSCENE_DAWN_NATIVE_DEVICE_INVALID_ARGUMENT_V1); auto* first=reinterpret_cast(uintptr_t{1}); auto* second=reinterpret_cast(uintptr_t{2}); + require(websceneDawnQueryVulkanDeviceV1(first,&query)== + WEBSCENE_DAWN_NATIVE_DEVICE_FOREIGN_DEVICE_V1); + query.version=WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION+1; + require(websceneDawnQueryVulkanDeviceV1(first,&query)== + WEBSCENE_DAWN_NATIVE_DEVICE_INCOMPATIBLE_ABI_V1); require(valid_dawn_linux_external_binding(first,first,first)); require(!valid_dawn_linux_external_binding(nullptr,first,first)); require(!valid_dawn_linux_external_binding(first,second,first)); @@ -23,10 +34,15 @@ int main(){ device->vk_queue=reinterpret_cast(uintptr_t{5}); device->device_uuid[0]=1; device->driver_uuid[0]=2;device->dawn_queue_family=4; + device->device_lost=std::make_shared>(false); device->native_owner=native_owner; require(same_dawn_linux_external_identity(device,device)); auto copied=std::make_shared(*device); require(!same_dawn_linux_external_identity(device,copied)); + device->device_lost->store(true,std::memory_order_release); + require(!same_dawn_linux_external_identity(device,device)); + require(dawn_linux_external_device_is_lost(device)); + device->device_lost->store(false,std::memory_order_release); linux_external_image_snapshot exact; exact.device_uuid=device->device_uuid;exact.driver_uuid=device->driver_uuid; diff --git a/src/WebScene.Sdk/cmake/LinuxSDK.cmake b/src/WebScene.Sdk/cmake/LinuxSDK.cmake index 7a8fb056a..70415d01b 100644 --- a/src/WebScene.Sdk/cmake/LinuxSDK.cmake +++ b/src/WebScene.Sdk/cmake/LinuxSDK.cmake @@ -36,7 +36,8 @@ if(WEBSCENE_SDK_ENABLE_WEBGPU) add_library(webscene_sdk_webgpu INTERFACE) target_include_directories(webscene_sdk_webgpu INTERFACE "${WEBSCENE_ROOT}/experiments/WebScene.NativeEngine.Probe/native/graphics") target_compile_definitions(webscene_sdk_webgpu INTERFACE - WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1) + WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1 + WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION=1) target_link_libraries(webscene_sdk_webgpu INTERFACE webscene_core dawn::webgpu_dawn) add_library(WebScene::WebGPU ALIAS webscene_sdk_webgpu) install(DIRECTORY "${WEBSCENE_GRAPHICS_SDK_ROOT}/dawn/include/" DESTINATION include) diff --git a/src/WebScene.Sdk/cmake/WebSceneLinuxConfig.cmake b/src/WebScene.Sdk/cmake/WebSceneLinuxConfig.cmake index 69538a36f..93a0f6807 100644 --- a/src/WebScene.Sdk/cmake/WebSceneLinuxConfig.cmake +++ b/src/WebScene.Sdk/cmake/WebSceneLinuxConfig.cmake @@ -41,7 +41,7 @@ if(NOT TARGET WebScene::Core) set_target_properties(WebScene::WebGPU PROPERTIES INTERFACE_LINK_LIBRARIES "WebScene::Core;WebScene::_Dawn;Threads::Threads;${CMAKE_DL_LIBS}" INTERFACE_INCLUDE_DIRECTORIES "${WebScene_SDK_ROOT}/include/graphics" - INTERFACE_COMPILE_DEFINITIONS "WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1") + INTERFACE_COMPILE_DEFINITIONS "WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1;WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION=1") endif() add_executable(WebScene::Compiler IMPORTED GLOBAL) set_property(TARGET WebScene::Compiler PROPERTY IMPORTED_LOCATION "${WebScene_SDK_ROOT}/bin/webscene-uic") diff --git a/src/WebScene.Sdk/cmake/WebSceneLinuxSDK.cmake b/src/WebScene.Sdk/cmake/WebSceneLinuxSDK.cmake index 8db9812f1..fb35f97e8 100644 --- a/src/WebScene.Sdk/cmake/WebSceneLinuxSDK.cmake +++ b/src/WebScene.Sdk/cmake/WebSceneLinuxSDK.cmake @@ -41,7 +41,8 @@ if(WEBSCENE_SDK_WEBGPU) add_library(webscene_sdk_webgpu INTERFACE) target_include_directories(webscene_sdk_webgpu INTERFACE "${WEBSCENE_ROOT}/experiments/WebScene.NativeEngine.Probe/native/graphics") target_compile_definitions(webscene_sdk_webgpu INTERFACE - WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1) + WEBSCENE_DAWN_LINUX_EXTERNAL_FACTORY_VERSION=1 + WEBSCENE_DAWN_NATIVE_DEVICE_ABI_VERSION=1) target_link_libraries(webscene_sdk_webgpu INTERFACE webscene_core dawn::webgpu_dawn Threads::Threads) add_library(WebScene::WebGPU ALIAS webscene_sdk_webgpu) install(DIRECTORY "${WEBSCENE_GRAPHICS_SDK_ROOT}/dawn/include/" DESTINATION include)