From b8bb06bcacbe9c6fa6da6d598d198054a2464584 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 05:20:22 -0800 Subject: [PATCH] Windows: host pages, clocks, thread times and exit hook through Win32; pointer residency on every host Windows forms of the runtime's host facilities, through windows-sys: - the host page (GetSystemInfo), the process's page permissions (VirtualQuery: mapped_readable, mapped_writable, and refuse_unwritable, so pages the process cannot write are a copy whose GPU writes are dropped, as Metal drops them, counted in host_mappings_queried), and section views (MEM_MAPPED) as shared memory for a guest RAM's plan; - the runtime's own pages (fresh pages, the submission checks' and the in-place check's pages: VirtualAlloc/VirtualFree), so those checks run; - the shared-pointer probe over a view of a paging-file section (CreateFileMappingW SEC_COMMIT + MapViewOfFile), as a VMM's Windows guest RAM is made; - the fault-free read of caller pages (ReadProcessMemory); - a thread's CPU time (GetThreadTimes); - the host clock on the performance counter, calibrated against VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR (gpu_time.rs: host_nanos, host_domain, Calibration::reading only); - the exit guard's hook registered through the C runtime's atexit, one handler per kind, where the not(unix) arm registered nothing. The idle release of pointer imports (host_residency) is structural, decided by the device's submission checks, so its pointer form runs on every host; only its dma-buf form is unix-only. A guest RAM's dma-buf sources are absent on Windows (cfg(unix) builders; no source exists, so the RAM's dma-buf paths are uninhabited there). Buffers report exported memory through memory_exported, false where the system has no file descriptors to export. Linux and macOS: the cfg(unix) residency gates removed are always true there; in_place_check's host page now reads host_memory::host_page (sysconf), as its own copy did. Verified: a step of the Windows check iteration (gnullvm, msi job). --- crates/metal2vulkan-runtime/src/buffer.rs | 54 ++++---- .../src/buffer_descriptor.rs | 41 ++---- crates/metal2vulkan-runtime/src/copied.rs | 25 +++- crates/metal2vulkan-runtime/src/device/mod.rs | 3 - .../src/device/submit_stalls.rs | 8 +- crates/metal2vulkan-runtime/src/dma_buf.rs | 16 ++- crates/metal2vulkan-runtime/src/exit_guard.rs | 42 +++++- .../metal2vulkan-runtime/src/fresh_pages.rs | 29 ++++- crates/metal2vulkan-runtime/src/gpu_time.rs | 62 +++++++-- .../metal2vulkan-runtime/src/host_memory.rs | 122 +++++++++++++++++- crates/metal2vulkan-runtime/src/host_ram.rs | 71 +++++++++- .../src/host_shared_pointers.rs | 69 ++++++++-- .../src/in_place_check.rs | 67 ++++++---- crates/metal2vulkan-runtime/src/lib.rs | 1 - .../metal2vulkan-runtime/src/managed_copy.rs | 1 - .../metal2vulkan-runtime/src/managed_sync.rs | 2 +- crates/metal2vulkan-runtime/src/rebind.rs | 10 -- .../metal2vulkan-runtime/src/submit_check.rs | 32 ++++- crates/metal2vulkan-runtime/src/texture.rs | 18 +-- .../metal2vulkan-runtime/src/this_thread.rs | 26 ++++ .../metal2vulkan-runtime/src/work_counts.rs | 13 +- .../src/wrapped_buffer.rs | 1 - 22 files changed, 538 insertions(+), 175 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 429263180..fa3986eaf 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -37,7 +37,6 @@ use super::heap::{Heap, HeapType}; use super::host_aliases::Alias; use super::host_memory::{HeldBack, HostParts, KeepAlive, Release}; use super::host_ram::RamOnDevice; -#[cfg(unix)] use super::host_residency::{Again, Residency}; use super::managed_copy::{CallerCopy, SyncTarget}; use super::memory::{ @@ -1284,7 +1283,6 @@ impl HostPages { return None; } let pages = import.pages(ReadApart::VkBuffer); - #[cfg(unix)] if matches!(pages, ImportPages::StandIn(_)) { return None; } @@ -1613,7 +1611,6 @@ enum Objects { /// Imported until the import goes. Fixed(Imported), /// Released while idle, and imported again at the next read (`host_residency.rs`). - #[cfg(unix)] Releasable(Residency), } @@ -1621,11 +1618,9 @@ enum Objects { /// 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), - #[cfg(unix)] Held(Arc), /// The device's stand-in, which a read of a released import takes where the device cannot /// import it again ([`HostImport::pages`]). - #[cfg(unix)] StandIn(Arc), } @@ -1635,9 +1630,7 @@ impl std::ops::Deref for ImportPages<'_> { fn deref(&self) -> &Pages { match self { ImportPages::Fixed(pages) => pages, - #[cfg(unix)] ImportPages::Held(imported) => &imported.pages, - #[cfg(unix)] ImportPages::StandIn(stand_in) => &stand_in.pages, } } @@ -1673,7 +1666,6 @@ impl HostImport { /// The import of `pages`, no pages lying in it yet, which the device releases while idle and /// `again` imports again (`host_residency.rs`). - #[cfg(unix)] fn releasable( device: &Device, pages: Pages, @@ -1761,7 +1753,6 @@ impl HostImport { } /// Its residency, where the device may release it while idle. - #[cfg(unix)] pub(super) fn residency(&self) -> Option<&Residency> { match &*self.objects { Objects::Fixed(_) => None, @@ -1777,7 +1768,6 @@ impl HostImport { self.note_read_apart(reason); match &*self.objects { Objects::Fixed(imported) => ImportPages::Fixed(&imported.pages), - #[cfg(unix)] Objects::Releasable(residency) => match residency.exposed() { Some(held) => ImportPages::Held(held), None => { @@ -1796,7 +1786,6 @@ impl HostImport { pub(super) fn blit_pages(&self) -> Result<(ImportPages<'_>, Option), Error> { match &*self.objects { Objects::Fixed(imported) => Ok((ImportPages::Fixed(&imported.pages), None)), - #[cfg(unix)] Objects::Releasable(residency) => { let held = residency.for_blit()?; let hold = ImportHold::Held(Arc::clone(&held)); @@ -1810,7 +1799,6 @@ impl HostImport { fn listing(&self) -> Option> { match &*self.objects { Objects::Fixed(imported) => Some(ImportPages::Fixed(&imported.pages)), - #[cfg(unix)] Objects::Releasable(residency) => residency.listing().map(ImportPages::Held), } } @@ -1821,7 +1809,6 @@ impl HostImport { self.note_read_apart(reason); match &*self.objects { Objects::Fixed(_) => false, - #[cfg(unix)] Objects::Releasable(residency) => residency.expose(), } } @@ -1851,7 +1838,6 @@ impl HostImport { /// ([`Joining::Buffer`]): counted where it is releasable still, which it stays /// (`WorkCounts::host_imports_joined_releasable`, `host_residency.rs`). fn note_joined(&self) { - #[cfg(unix)] if self.residency().is_some_and(Residency::releasable) { (self.device.shared().counts).host_import_joined_releasable(); } @@ -1982,7 +1968,6 @@ impl Drop for HostImport { // 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. - #[cfg(unix)] Objects::Releasable(residency) => match residency.let_go() { Some(mut held) => { held.leave(left); @@ -2325,14 +2310,16 @@ impl Pages { /// 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) { - let placement = &self.memory.placement; #[cfg(unix)] - if let Some(imports) = placement - .dma_buf_pages() - .filter(|_| !placement.over_ram_chunk()) { - imports.after_free(after); - return; + 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); } @@ -2616,7 +2603,6 @@ impl HostImport { facts.push_str(&imported.pages.memory.placement.failure_facts(types)); Standing::Held } - #[cfg(unix)] Objects::Releasable(residency) => { facts.push_str(", releasable, memory "); facts.push_str(&types.of(shape.type_index)); @@ -2783,7 +2769,6 @@ pub(super) struct BufferParts { 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`). - #[cfg(unix)] pub(super) again: Option, /// A new buffer, or the same buffer on its device's next generation. pub(super) naming: Naming, @@ -3497,7 +3482,6 @@ impl Device { of_heap, drops_writes: false, mirror, - #[cfg(unix)] again: None, naming: Naming::New, }); @@ -3698,7 +3682,6 @@ impl Device { of_heap: false, drops_writes: false, mirror: None, - #[cfg(unix)] again: None, naming: Naming::New, })) @@ -3721,7 +3704,6 @@ impl Device { of_heap, drops_writes, mirror, - #[cfg(unix)] again, naming, } = parts; @@ -3737,10 +3719,7 @@ impl Device { (false, true) => None, (false, false) => Some(KeptBecause::Pointer), }; - #[cfg(unix)] let import = self.host_import(pages, again, kept); - #[cfg(not(unix))] - let import = Arc::new(HostImport::new(self, pages, kept)); self.host_lie( identity.key, (import, Joining::First), @@ -3770,7 +3749,6 @@ impl Device { /// 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. - #[cfg(unix)] fn host_import( &self, pages: Pages, @@ -4509,7 +4487,20 @@ impl Buffer { /// (`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.exported().is_none() + 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 @@ -5037,7 +5028,6 @@ impl Buffer { /// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's /// `VkBuffer`); `None` for a no-copy buffer and a heap's. - #[cfg(unix)] fn fixed_pages(&self) -> Option> { match &self.s().bytes { Bytes::Own(OwnBytes { diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 65d3cfc0a..2ca66f6cc 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -14,7 +14,6 @@ use super::buffer::{ usage, Buffer, BufferParts, HostCell, HostImport, HostPages, Lying, Modes, Naming, Owner, ReadApart, Replaces, }; -#[cfg(unix)] use super::buffer::{ImportPages, Pages}; use super::copied::NotCopied; use super::device::lock; @@ -30,7 +29,6 @@ use super::host_memory::{ ImportRequest, ImportWindow, Importer, KeepAlive, PointerImport, Release, Source, }; use super::host_ram::{RamOnDevice, Routed}; -#[cfg(unix)] use super::host_residency::Again; use super::memory::{BoundMemory, ImportFailure, Mapped, MemoryClass, Placement}; use super::read_only_view::ReadOnlyView; @@ -1048,12 +1046,9 @@ impl Device { match unsafe { self.import_by_pointer(importer, pointer, length, host, class) } { Ok(Ok((buffer, memory))) => { - #[cfg(unix)] let again = (!of_heap && !drops_writes) .then(|| Again::pointer(self, pointer, (length, window, class))) .flatten(); - #[cfg(not(unix))] - let again = None; Ok((buffer, memory, again)) } // A heap's import is dedicated to nothing, as textures placed in the @@ -1061,6 +1056,7 @@ impl Device { // binds the buffer alone, its textures in place bound in imports of their // own (`Device::dma_buf_image`). // SAFETY: as above. + #[cfg(unix)] Ok(Err((source, refusal))) => unsafe { let kept = (!of_heap, !of_heap); let window = &window; @@ -1083,6 +1079,9 @@ impl Device { 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) => { @@ -1155,7 +1154,6 @@ impl Device { of_heap, drops_writes, mirror: None, - #[cfg(unix)] again, naming, }); @@ -1528,6 +1526,7 @@ impl Device { // 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 @@ -1579,6 +1578,9 @@ impl Device { } 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 { @@ -1855,7 +1857,11 @@ impl Device { _ => 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), } } @@ -1939,7 +1945,6 @@ impl Device { let shared = self.shared(); let raw_device = shared.vk(); let pages = import.pages(ReadApart::Inside); - #[cfg(unix)] if matches!(pages, ImportPages::StandIn(_)) { return None; } @@ -2038,7 +2043,6 @@ impl Device { /// 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. - #[cfg(unix)] pub(super) fn import_pointer_again( &self, pointer: NonNull, @@ -2068,26 +2072,6 @@ impl Device { )) } - /// No dma-buf is imported on this system: there is no source to call. - /// - /// # Safety - /// - /// None: it does nothing. - #[cfg(not(unix))] - unsafe fn import_from_source( - &self, - _call: &'static str, - _importer: &Importer, - _pointer: NonNull, - _length: u64, - _window: &ImportWindow, - source: Source, - _class: MemoryClass, - _keep: bool, - ) -> Result<(HostBuffer, Placement, Option), Error> { - match source {} - } - /// 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 @@ -2494,7 +2478,6 @@ impl Device { of_heap, drops_writes: read_only, mirror: None, - #[cfg(unix)] again: None, naming, }); diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index 53e236a0e..cdb5b34aa 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -2615,7 +2615,7 @@ pub(crate) unsafe fn read_caller( /// 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; elsewhere nothing is read and the answer is `false`. +/// `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; @@ -2668,8 +2668,23 @@ pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { answer == libc::KERN_SUCCESS && read == into.len() as u64 } -/// [`read_pages`] where the system is not asked: nothing is copied. -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -pub(crate) fn read_pages(_pages: NonNull, _into: &mut [u8]) -> bool { - false +/// [`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/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 03073ee72..48c0c93e9 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -694,7 +694,6 @@ pub(super) struct DeviceShared { 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`). - #[cfg(unix)] 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`). @@ -1218,7 +1217,6 @@ impl Drop for DeviceShared { // this teardown runs on its thread. self.reaper.stop(); // What the residency thread releases holds the device: none is left. - #[cfg(unix)] 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`). @@ -3230,7 +3228,6 @@ impl Device { owners: Default::default(), live_buffers: Default::default(), carry: Default::default(), - #[cfg(unix)] residency: Default::default(), #[cfg(unix)] dma_buf_files: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/device/submit_stalls.rs b/crates/metal2vulkan-runtime/src/device/submit_stalls.rs index 5fe091e00..7b4812bf9 100644 --- a/crates/metal2vulkan-runtime/src/device/submit_stalls.rs +++ b/crates/metal2vulkan-runtime/src/device/submit_stalls.rs @@ -257,8 +257,8 @@ impl Period { } } -/// The calling thread's CPU time, in nanoseconds (`CLOCK_THREAD_CPUTIME_ID`); `None` where it -/// cannot be read. +/// The calling thread's CPU time, in nanoseconds (`CLOCK_THREAD_CPUTIME_ID`; on Windows its +/// kernel and user times, `GetThreadTimes`, in 100 ns units); `None` where it cannot be read. fn thread_cpu() -> Option { #[cfg(unix)] { @@ -274,9 +274,9 @@ fn thread_cpu() -> Option { let nanos = u64::try_from(now.tv_nsec).ok()?; Some(seconds * 1_000_000_000 + nanos) } - #[cfg(not(unix))] + #[cfg(windows)] { - None + crate::this_thread::cpu_nanos() } } diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 713eef6a3..ce3469cd1 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -123,28 +123,41 @@ //! (`Unsupported`, `HostMemory`). Counted: `WorkCounts::dma_buf_imports` (each chunk of its own, //! and each shared file's first import) and `WorkCounts::dma_buf_sparse_buffers`. +#[cfg(unix)] use super::buffer::{usage, Pages}; +#[cfg(unix)] use super::buffer_descriptor::HostBuffer; use super::device::lock; -use super::error::{internal, invalid, vulkan, Error, MemoryKind, Problem}; +use super::error::Error; +#[cfg(unix)] +use super::error::{internal, invalid, vulkan, MemoryKind, Problem}; use super::exit_guard::{self, Call}; +#[cfg(unix)] use super::host_memory::{based_size, import_refused, not_importable, ImportWindow, Importer}; +#[cfg(unix)] use super::host_residency::Again; use super::image_plan::{ImageFacts, ImagePlan}; +#[cfg(unix)] use super::in_place_check::Unmade; use super::linear_plan::{check_linear_limits, tiling_lack, viewed_formats, LinearLack}; +#[cfg(unix)] use super::memory::{self, DmaBufFor, ImportFailure, MemoryClass, Placement}; +#[cfg(unix)] use super::program_objects::ProgramObject; use super::Device; use crate::release; use ash::vk; use metal2vulkan::error::RuntimeDriverDefect; use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, SampleCountFlags}; +#[cfg(unix)] use std::ops::Range; #[cfg(unix)] use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; +#[cfg(unix)] use std::ptr::NonNull; +#[cfg(unix)] use std::sync::{Arc, Mutex, PoisonError, Weak}; +#[cfg(unix)] use std::time::Duration; /// A runtime extension (Metal has none): makes dma-bufs of the host pages a no-copy import @@ -790,7 +803,6 @@ fn dma_buf_length(_fd: BorrowedFd<'_>) -> Option { const WAIT_SLICE: Duration = Duration::from_millis(100); /// The handle type of every import of a dma-buf, and of every buffer and image made for one. -#[cfg(unix)] const DMA_BUF: vk::ExternalMemoryHandleTypeFlags = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; #[cfg(unix)] diff --git a/crates/metal2vulkan-runtime/src/exit_guard.rs b/crates/metal2vulkan-runtime/src/exit_guard.rs index 9c0da06da..5bb841fdd 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -1869,6 +1869,7 @@ pub(crate) enum After { Making, } +#[cfg(unix)] impl After { /// Its argument to the C library's exit handler: a tag, never dereferenced. fn tag(self) -> *mut std::ffi::c_void { @@ -1909,9 +1910,44 @@ fn install(after: After) { unsafe { __cxa_atexit(exit_handler, after.tag(), std::ptr::null_mut()) }; } -/// Nothing to register: the runtime is built for unix hosts, whose exit order the hook relies on. -#[cfg(not(unix))] -fn install(_: After) {} +/// Register the exit handler of `after`'s kind with the C runtime's exit handlers on Windows: +/// through `atexit`, whose handlers the C runtime's `exit` (and the end of `main`) runs in the +/// reverse order of their registration, before `ExitProcess` ends the process's other threads and +/// detaches its libraries (`DLL_PROCESS_DETACH`). `atexit` passes no argument, so each kind has a +/// handler of its own ([`exit_handler_after_calls`], [`exit_handler_after_making`]). +#[cfg(windows)] +fn install(after: After) { + INSTALLED.fetch_add(1, Ordering::Relaxed); + let handler: extern "C" fn() = match after { + After::Calls => exit_handler_after_calls, + After::Making => exit_handler_after_making, + }; + // SAFETY: the handler takes nothing and never unwinds. Registration fails only when the C + // runtime is out of memory; the process then exits unguarded, as before. + unsafe { atexit(handler) }; +} + +// The C runtime's `atexit` (``), which every Windows C runtime exports (the UCRT's and +// MinGW's): `function` is called as the process exits, in the reverse order of registration. +#[cfg(windows)] +unsafe extern "C" { + fn atexit(function: extern "C" fn()) -> std::ffi::c_int; +} + +/// The exit handler of a registration after calls, on Windows (`atexit` passes no argument): +/// the hook's run waits at most [`BOUND`], or [`MAKING_BOUND`] while a making is in progress, and +/// returns. +#[cfg(windows)] +extern "C" fn exit_handler_after_calls() { + run(After::Calls); +} + +/// The exit handler of a registration after a making, on Windows: as +/// [`exit_handler_after_calls`]. +#[cfg(windows)] +extern "C" fn exit_handler_after_making() { + run(After::Making); +} // The C++ ABI's `__cxa_atexit`, which the C library of every unix host but the GNU one's (where // `on_exit` is used) exports and `libc` does not declare for all of them: `function` is called with diff --git a/crates/metal2vulkan-runtime/src/fresh_pages.rs b/crates/metal2vulkan-runtime/src/fresh_pages.rs index 6ad35e23d..0f7614007 100644 --- a/crates/metal2vulkan-runtime/src/fresh_pages.rs +++ b/crates/metal2vulkan-runtime/src/fresh_pages.rs @@ -139,10 +139,25 @@ impl OwnPages { Some(OwnPages { pointer, length }) } - /// No pages are mapped on this system. - #[cfg(not(unix))] - pub(super) fn map(_length: u64) -> Option { - None + /// `length` bytes of new private pages, read-write, at a page: a committed allocation of + /// their own (`VirtualAlloc`), read as zero; `None` where the system makes none. + #[cfg(windows)] + pub(super) fn map(length: u64) -> Option { + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, + }; + let bytes = usize::try_from(length).ok()?; + // SAFETY: a new allocation, at an address the system picks. + let pointer = unsafe { + VirtualAlloc( + std::ptr::null(), + bytes, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + }; + let pointer = NonNull::new(pointer.cast::())?; + Some(OwnPages { pointer, length }) } /// Where the pages start. @@ -164,6 +179,12 @@ impl Drop for OwnPages { unsafe { libc::munmap(self.pointer.as_ptr().cast(), self.length as usize); } + #[cfg(windows)] + // SAFETY: as above; a release frees the allocation whole, from its base, with a size of 0. + unsafe { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + VirtualFree(self.pointer.as_ptr().cast(), 0, MEM_RELEASE); + } } } diff --git a/crates/metal2vulkan-runtime/src/gpu_time.rs b/crates/metal2vulkan-runtime/src/gpu_time.rs index 2c37ffb9e..4727db153 100644 --- a/crates/metal2vulkan-runtime/src/gpu_time.rs +++ b/crates/metal2vulkan-runtime/src/gpu_time.rs @@ -4,8 +4,9 @@ //! //! - **The host's clock.** `CLOCK_UPTIME_RAW` on macOS, the clock of `mach_absolute_time` and so //! of Metal's times and `CACurrentMediaTime`; `CLOCK_MONOTONIC_RAW` elsewhere on Unix, its -//! counterpart (monotonic, never slewed, stopped while the system sleeps). Other platforms count -//! the runtime's own monotonic clock, which no device can calibrate against. +//! counterpart (monotonic, never slewed, stopped while the system sleeps); on Windows the +//! performance counter (`QueryPerformanceCounter`, in nanoseconds of its frequency), which +//! devices calibrate against as `VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR`. //! - **GPU times.** The command buffer's first batch writes a timestamp at the top of its work //! (after a barrier its first encoder waits behind for earlier work, once every command before //! it completed, where Metal's start follows such work's end), and its last batch one after the @@ -247,7 +248,8 @@ const _: () = assert!(PLAIN * SLOTS <= SAMPLE_BUFFER_TIMESTAMPS); /// The host time now, in seconds of the clock the runtime's GPU and kernel times count (the /// module documentation): `CLOCK_UPTIME_RAW` on macOS, which `mach_absolute_time` and -/// `CACurrentMediaTime` count, and `CLOCK_MONOTONIC_RAW` elsewhere on Unix. +/// `CACurrentMediaTime` count, `CLOCK_MONOTONIC_RAW` elsewhere on Unix, and the performance +/// counter (`QueryPerformanceCounter`) on Windows. pub fn host_time() -> f64 { host_nanos() as f64 / 1e9 } @@ -258,14 +260,39 @@ pub(crate) fn host_nanos() -> u64 { { read_clock(BASE).unwrap_or(0) } - #[cfg(not(unix))] + #[cfg(windows)] { - use std::time::Instant; - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_nanos() as u64 + read_counter().and_then(counter_nanos).unwrap_or(0) } } +/// The performance counter now, in its ticks (`QueryPerformanceCounter`). +#[cfg(windows)] +fn read_counter() -> Option { + use windows_sys::Win32::System::Performance::QueryPerformanceCounter; + let mut ticks = 0i64; + // SAFETY: `ticks` is a valid value for the call to fill. + let read = unsafe { QueryPerformanceCounter(&mut ticks) }; + (read != 0).then(|| u64::try_from(ticks).ok()).flatten() +} + +/// `ticks` of the performance counter in nanoseconds, at its frequency +/// (`QueryPerformanceFrequency`, fixed at boot and read once). +#[cfg(windows)] +fn counter_nanos(ticks: u64) -> Option { + use windows_sys::Win32::System::Performance::QueryPerformanceFrequency; + static FREQUENCY: OnceLock> = OnceLock::new(); + let frequency = FREQUENCY.get_or_init(|| { + let mut frequency = 0i64; + // SAFETY: `frequency` is a valid value for the call to fill. + let read = unsafe { QueryPerformanceFrequency(&mut frequency) }; + let frequency = (read != 0).then(|| u64::try_from(frequency).ok()).flatten(); + frequency.filter(|&frequency| frequency > 0) + }); + let nanos = u128::from(ticks) * 1_000_000_000 / u128::from((*frequency)?); + u64::try_from(nanos).ok() +} + /// The host's clock. #[cfg(target_os = "macos")] const BASE: libc::clockid_t = libc::CLOCK_UPTIME_RAW; @@ -299,8 +326,8 @@ fn domain_clock(domain: vk::TimeDomainKHR) -> Option { } /// The host time domain a device's calibration uses, from those it offers: the host's clock -/// where offered, else `CLOCK_MONOTONIC_RAW`, else `CLOCK_MONOTONIC`. `None` without the -/// device's own domain or a host domain the runtime can read. +/// where offered, else `CLOCK_MONOTONIC_RAW`, else `CLOCK_MONOTONIC`; on Windows the performance +/// counter's. `None` without the device's own domain or a host domain the runtime can read. pub(crate) fn host_domain(offered: &[vk::TimeDomainKHR]) -> Option { if !offered.contains(&vk::TimeDomainKHR::DEVICE) { return None; @@ -318,9 +345,10 @@ pub(crate) fn host_domain(offered: &[vk::TimeDomainKHR]) -> Option Option { u64::try_from(page).ok().filter(|&page| page > 0) } -/// The host's page size, where the runtime knows how to ask for it: not on this system. -#[cfg(not(unix))] +/// The host's page size on Windows (`GetSystemInfo`'s `dwPageSize`). +#[cfg(windows)] pub(super) fn host_page() -> Option { - None + use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO}; + // SAFETY: an all-zero `SYSTEM_INFO` is a valid value of the plain struct for the call to fill. + let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is a valid struct to write. + unsafe { GetSystemInfo(&mut info) }; + Some(u64::from(info.dwPageSize)).filter(|&page| page > 0) } /// The refusal of host memory this device cannot import exactly. @@ -841,8 +846,15 @@ pub(super) fn mapped_readable(start: u64, end: u64) -> bool { mappings_permitted(start, end, Access::Read, &mut 0) == Some(true) } +/// [`mapped_readable`] on Windows: the regions over `[start, end)` ([`regions_allow`]), each +/// committed with a protection that reads. +#[cfg(windows)] +pub(super) fn mapped_readable(start: u64, end: u64) -> bool { + regions_allow(start, end, |info| protection_allows(info, false), &mut 0) +} + /// [`mapped_readable`] where the runtime does not ask the system for its mappings: `false`. -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] pub(super) fn mapped_readable(_start: u64, _end: u64) -> bool { false } @@ -909,9 +921,82 @@ pub(super) fn mapped_writable(start: u64, end: u64) -> bool { true } +/// [`mapped_writable`] on Windows: the regions over `[start, end)` ([`regions_allow`]), each +/// committed with a protection that writes. +#[cfg(windows)] +pub(super) fn mapped_writable(start: u64, end: u64) -> bool { + regions_allow(start, end, |info| protection_allows(info, true), &mut 0) +} + +/// Whether the regions of this process's address space over `[start, end)` cover it without a +/// gap, each committed and taken by `allows` (`VirtualQuery`, one call per region, each added +/// to `asked`); `false` where the system answers no region. +#[cfg(windows)] +pub(super) fn regions_allow( + start: u64, + end: u64, + allows: impl Fn(&windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION) -> bool, + asked: &mut u64, +) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut covered = start; + while covered < end { + let mut info = MEMORY_BASIC_INFORMATION::default(); + let size = std::mem::size_of::(); + // SAFETY: a query of this process's own address space, written into `info`. + let written = unsafe { VirtualQuery(covered as *const c_void, &mut info, size) }; + *asked += 1; + if written == 0 || info.State != MEM_COMMIT || !allows(&info) { + return false; + } + let region_end = (info.BaseAddress as u64).saturating_add(info.RegionSize as u64); + if region_end <= covered { + return false; + } + covered = region_end; + } + true +} + +/// Whether a committed region's protection reads its pages (`write`: and writes them), as the +/// CPU's loads (and stores) would: no guard page, no access only to the CPU's execution. A +/// copy-on-write view's pages write, into private copies, as a private writable mapping's do on +/// Linux. +#[cfg(windows)] +fn protection_allows( + info: &windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION, + write: bool, +) -> bool { + use windows_sys::Win32::System::Memory::{ + PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, + PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, + }; + if info.Protect & PAGE_GUARD != 0 { + return false; + } + // The access in the low byte; caching modifiers above it. + match info.Protect & 0xff { + PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY => true, + PAGE_READONLY | PAGE_EXECUTE_READ => !write, + _ => false, + } +} + +/// Whether every region over `[start, end)` is a view of a section (`MEM_MAPPED`: a file's or the +/// paging file's mapping, as a VMM's guest RAM made by `CreateFileMapping` is), committed and +/// readable, as the system answers now ([`regions_allow`]). +#[cfg(windows)] +pub(super) fn section_pages(start: u64, end: u64) -> bool { + use windows_sys::Win32::System::Memory::MEM_MAPPED; + let shared = |info: &windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION| { + info.Type == MEM_MAPPED && protection_allows(info, false) + }; + regions_allow(start, end, shared, &mut 0) +} + /// [`mapped_writable`] where the runtime does not ask the system for its mappings: `false` (and no /// copy is made here: the runtime reads no caller's page, [`mapped_readable`]). -#[cfg(not(any(target_os = "linux", target_os = "macos")))] +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] pub(super) fn mapped_writable(_start: u64, _end: u64) -> bool { false } @@ -1129,9 +1214,32 @@ pub(super) fn queried_permitted( Some(true) } -/// Refuse the window's pages unless the process can write them: no check off Linux (MoltenVK +/// Refuse the window's pages, typed, unless the process maps every one of them writable, on +/// Windows: the regions over the window, each committed with a protection that writes +/// ([`regions_allow`], one `VirtualQuery` per region at each call, each counted in `counts`, +/// `WorkCounts::host_mappings_queried`). Metal drops the GPU's writes to pages the process cannot +/// write, which an import would let through: refused, such pages are a copy whose GPU writes are +/// dropped (`copied.rs`), as on Linux. +#[cfg(windows)] +pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Result<(), Error> { + let mut asked = 0; + let end = window.start.saturating_add(window.size); + let writable = regions_allow( + window.start, + end, + |info| protection_allows(info, true), + &mut asked, + ); + counts.host_mappings_queried(asked); + match writable { + true => Ok(()), + false => Err(not_importable()), + } +} + +/// Refuse the window's pages unless the process can write them: no check on macOS (MoltenVK /// hands the range to Metal, which reads read-only pages). -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] pub(super) fn refuse_unwritable(_window: &ImportWindow, _counts: &Counters) -> Result<(), Error> { Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index cccf92aac..e9b7fb480 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -177,6 +177,7 @@ use super::program_objects::ProgramObject; use super::Device; use crate::allocations::GiveBack; use crate::device::WeakDevice; +#[cfg(unix)] use crate::dma_buf::{DmaBufRunsSource, DmaBufSource}; use crate::release; use ash::vk; @@ -191,6 +192,14 @@ use std::time::{Duration, Instant}; pub(crate) mod copy; mod kept; +/// No source of dma-bufs on this system: a RAM has none. +#[cfg(not(unix))] +type DmaBufSource = std::convert::Infallible; + +/// No source of dma-bufs of lists of runs on this system: a RAM has none. +#[cfg(not(unix))] +type DmaBufRunsSource = std::convert::Infallible; + /// The bytes of a chunk of the RAM a device imports at once; the last chunk of a range may be /// fewer. pub(crate) const CHUNK_BYTES: u64 = 64 << 20; @@ -306,6 +315,7 @@ impl HostRam { /// (the device's, or one making an object over it), with no lock of the runtime's held, and /// is kept with each import it made until that import is freed. A source that fails, or /// answers otherwise, leaves the chunk to its pointer. No Metal counterpart. + #[cfg(unix)] pub fn with_dma_buf(mut self, source: DmaBufSource) -> HostRam { self.dma_buf = Some(source); self @@ -317,6 +327,7 @@ impl HostRam { /// submission imports the RAM in chunks as long as that, as its own limits allow /// ([`Device::use_host_ram`]), so that each submission lists a few imports of the RAM, not /// one per 64 MiB. Without this call, 64 MiB, the udmabuf default. No Metal counterpart. + #[cfg(unix)] pub fn with_largest_dma_buf(mut self, bytes: u64) -> HostRam { self.largest_dma_buf = bytes; self @@ -354,6 +365,7 @@ impl HostRam { /// the RAM's pointer) it is never called. No Metal counterpart. /// /// [`BlitCommandEncoder::copy_from_host_ram`]: crate::BlitCommandEncoder::copy_from_host_ram + #[cfg(unix)] pub fn with_dma_buf_of_runs(mut self, source: DmaBufRunsSource, most_runs: usize) -> HostRam { self.dma_buf_runs = Some((source, most_runs.max(1))); self @@ -1924,12 +1936,69 @@ fn shared_memory(span: Range) -> bool { super::host_memory::shared_base_pages(span.start, span.end) } +/// Whether every region over `span` is a view of a section, as the system answers now +/// (`host_memory::section_pages`): Windows' shared memory, as a VMM's guest RAM made by +/// `CreateFileMapping` is, which a device may refuse to import by its pointer +/// (`Device::imports_shared_host_pointers`). +#[cfg(windows)] +fn shared_memory(span: Range) -> bool { + super::host_memory::section_pages(span.start, span.end) +} + /// Elsewhere no device met refuses it: none is taken as shared memory. -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] fn shared_memory(_: Range) -> bool { false } +/// The imports of a guest RAM's dma-bufs where the system has none (`dma_buf.rs` on Unix): no RAM +/// has a source, so none is ever called. +#[cfg(not(unix))] +impl Device { + /// No dma-buf of the RAM's pages is imported on this system. + /// + /// # Safety + /// + /// None: no source exists to call. + unsafe fn ram_takes_dma_bufs( + &self, + _importer: &Importer, + _page: Range, + source: &DmaBufSource, + ) -> bool { + match *source {} + } + + /// No dma-buf of the RAM's pages is imported on this system. + /// + /// # Safety + /// + /// None: no source exists to call. + unsafe fn ram_span_as_dma_buf( + &self, + _importer: &Importer, + _span: Range, + source: &DmaBufSource, + _sole: bool, + ) -> Result<(vk::Buffer, Placement), Error> { + match *source {} + } + + /// No dma-buf of the RAM's runs is imported on this system. + /// + /// # Safety + /// + /// None: no source exists to call. + unsafe fn ram_runs_as_dma_buf( + &self, + _importer: &Importer, + _runs: &[Range], + source: &DmaBufRunsSource, + ) -> Result<(vk::Buffer, Placement), Error> { + match *source {} + } +} + impl Device { /// Give the chunks the device's thread imported ahead and no object took back once the /// device's allocations come within a quarter of its limit (`allocations.rs`), and the blocks diff --git a/crates/metal2vulkan-runtime/src/host_shared_pointers.rs b/crates/metal2vulkan-runtime/src/host_shared_pointers.rs index ec890048f..cee057e52 100644 --- a/crates/metal2vulkan-runtime/src/host_shared_pointers.rs +++ b/crates/metal2vulkan-runtime/src/host_shared_pointers.rs @@ -8,7 +8,8 @@ //! of a file, `memfd`s among them, typed. NVIDIA and lavapipe imported the same memory. So the //! device is asked by doing it, once: one page of a `memfd` mapped shared, read and write (on //! Linux, as QEMU's `memory-backend-memfd,share=on` guest RAM is; anonymous shared memory on other -//! Unix systems), imported as a no-copy buffer's pages are, and released at once. +//! Unix systems; on Windows a view of a section of the paging file, as a VMM's guest RAM made by +//! `CreateFileMapping` is), imported as a no-copy buffer's pages are, and released at once. use super::error::{Error, MemoryKind}; use super::host_memory::{import_window, refused}; @@ -18,12 +19,12 @@ use std::ptr::NonNull; impl Device { /// Whether the device imports a pointer to shared memory, as a no-copy buffer's import takes - /// it (`VK_EXT_external_memory_host`): a runtime extension on Unix systems, with no Metal - /// counterpart (Metal takes any page). Found once per device by importing one page of a - /// `memfd` mapped shared, read and write (anonymous shared memory off Linux), which is - /// released at once, and answered from that after; the import is counted as a no-copy - /// buffer's is. False for a device that imports no host pointer (one without - /// `VK_EXT_external_memory_host`). + /// it (`VK_EXT_external_memory_host`): a runtime extension, with no Metal counterpart (Metal + /// takes any page). Found once per device by importing one page of a `memfd` mapped shared, + /// read and write (anonymous shared memory elsewhere on Unix, a view of a section of the + /// paging file on Windows), which is released at once, and answered from that after; the + /// import is counted as a no-copy buffer's is. False for a device that imports no host + /// pointer (one without `VK_EXT_external_memory_host`). /// /// Where it is false, a no-copy buffer over shared memory is imported only from the caller's /// dma-buf source ([`HostMemory::with_dma_buf`](crate::HostMemory::with_dma_buf)), and without @@ -83,7 +84,7 @@ impl Device { } /// Pages of shared memory mapped read and write, unmapped when it drops: of a `memfd` on Linux, -/// anonymous elsewhere. +/// anonymous elsewhere on Unix, a view of a section of the paging file on Windows. struct SharedPages { at: NonNull, length: usize, @@ -91,6 +92,7 @@ struct SharedPages { impl SharedPages { /// `length` bytes of them; `None` where they cannot be made. + #[cfg(unix)] fn new(length: u64) -> Option { let length = usize::try_from(length).ok()?; let (flags, fd) = SharedPages::backing(length)?; @@ -137,15 +139,62 @@ impl SharedPages { } /// The mapping's flags: anonymous shared memory off Linux. - #[cfg(not(target_os = "linux"))] + #[cfg(all(unix, not(target_os = "linux")))] fn backing(_length: usize) -> Option<(libc::c_int, Option)> { Some((libc::MAP_SHARED | libc::MAP_ANON, None)) } + + /// `length` bytes of them on Windows: a view, read and write, of a section of `length` bytes + /// the paging file backs, committed (`CreateFileMappingW` of no file, `SEC_COMMIT`), as a VMM's + /// guest RAM made so is; `None` where they cannot be made. The view keeps the section; its + /// handle closes here. + #[cfg(windows)] + fn new(length: u64) -> Option { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile, FILE_MAP_ALL_ACCESS, PAGE_READWRITE, SEC_COMMIT, + }; + let bytes = usize::try_from(length).ok()?; + let (high, low) = ((length >> 32) as u32, length as u32); + // SAFETY: a new unnamed section of the paging file, with the default security. + let section = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_COMMIT, + high, + low, + std::ptr::null(), + ) + }; + if section.is_null() { + return None; + } + // SAFETY: a view of the whole of the section just made, read and write. + let view = unsafe { MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, bytes) }; + // SAFETY: the section's handle, made above and closed once; the view keeps the section. + unsafe { CloseHandle(section) }; + Some(SharedPages { + at: NonNull::new(view.Value.cast())?, + length: bytes, + }) + } } impl Drop for SharedPages { fn drop(&mut self) { + #[cfg(unix)] // SAFETY: this object's own mapping, which nothing imports any more. - unsafe { libc::munmap(self.at.as_ptr().cast(), self.length) }; + unsafe { + libc::munmap(self.at.as_ptr().cast(), self.length) + }; + #[cfg(windows)] + // SAFETY: this object's own view, which nothing imports any more. + unsafe { + use windows_sys::Win32::System::Memory::{UnmapViewOfFile, MEMORY_MAPPED_VIEW_ADDRESS}; + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: self.at.as_ptr().cast(), + }) + }; } } diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index ec7e81068..206887d91 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -1465,6 +1465,18 @@ impl ClassPages { } } +/// No memory is exported as a file descriptor on this system: the class is unchecked. +#[cfg(not(unix))] +fn exported_pages( + _device: &Device, + _export: MemoryExport, + _length: u64, +) -> Result { + Err(Unmade::lasting( + "the system exports no memory as file descriptors", + )) +} + /// An exportable buffer of the runtime's own of `length` bytes, `Shared`, whose memory it exports /// as `export`'s handle type, outside the Metal address space, that declares the bytes between a /// texture's rows unobserved, as the product's buffers whose textures take an image there may @@ -1473,6 +1485,7 @@ impl ClassPages { /// allocation, to which no image is bound. A dma-buf's dedicated allocation is taken: its /// textures' images are bound to a dedicated import of its own dma-buf, as the product's are /// wherever no image binds in the memory (`texture.rs`'s `exported_dma_buf_alias`). +#[cfg(unix)] fn exported_pages( device: &Device, export: MemoryExport, @@ -1527,7 +1540,6 @@ fn imports_pointers(device: &Device) -> bool { /// pointer, which its keep-alive unmaps ([`Anonymous`]). Why not, where the device makes none, /// or does not import the pointer (dma-bufs, or a copied host buffer, `copied.rs`), the buffer /// unmade where the device imports no pointer at all (it would be a copy of the pages, announced). -#[cfg(unix)] fn pointer_pages(device: &Device, length: u64) -> Result { if !imports_pointers(device) { let why = "the device imports no host pointer (VK_EXT_external_memory_host)"; @@ -1556,7 +1568,6 @@ fn pointer_pages(device: &Device, length: u64) -> Result { /// keep-alive, not a deallocator, so the buffer's release runs at Metal's moment and waits for no /// batch submitted before it (`HostPages`'s release), and `pages` goes once the import is freed /// (`KeepAlive`). Why not, where the device refuses the buffer, `pages` dropped with the refusal. -#[cfg(unix)] fn no_copy_kept( device: &Device, memory: HostMemory, @@ -1575,17 +1586,14 @@ fn no_copy_kept( } /// Anonymous pages [`map_anonymous`] mapped, unmapped as this goes: a check buffer's keep-alive. -#[cfg(unix)] struct Anonymous { start: NonNull, length: u64, } // SAFETY: the mapping is this value's alone to unmap, from any thread, once nothing uses it. -#[cfg(unix)] unsafe impl Send for Anonymous {} -#[cfg(unix)] impl Drop for Anonymous { fn drop(&mut self) { unmap(self.start, self.length); @@ -1612,6 +1620,25 @@ fn map_anonymous(length: u64) -> Option> { NonNull::new(mapped.cast()) } +/// Anonymous private pages of `length` bytes, readable and writable, read as zero: a committed +/// allocation of its own (`VirtualAlloc`). +#[cfg(windows)] +fn map_anonymous(length: u64) -> Option> { + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, + }; + // SAFETY: a new allocation, at an address the system chooses. + let mapped = unsafe { + VirtualAlloc( + std::ptr::null(), + usize::try_from(length).ok()?, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + }; + NonNull::new(mapped.cast()) +} + /// Unmap the `length` bytes `map_anonymous` mapped at `pointer`. #[cfg(unix)] fn unmap(pointer: NonNull, length: u64) { @@ -1619,12 +1646,13 @@ fn unmap(pointer: NonNull, length: u64) { unsafe { libc::munmap(pointer.as_ptr().cast(), length as usize) }; } -/// No anonymous pages are mapped on this system: the class is unchecked. -#[cfg(not(unix))] -fn pointer_pages(_device: &Device, _length: u64) -> Result { - Err(Unmade::lasting( - "the system maps no anonymous pages for the check", - )) +/// Free the allocation `map_anonymous` made at `pointer`, whole. +#[cfg(windows)] +fn unmap(pointer: NonNull, _length: u64) { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + // SAFETY: the allocation `map_anonymous` made, which nothing uses any more; a release frees + // it whole, from its base, with a size of 0. + unsafe { VirtualFree(pointer.as_ptr().cast(), 0, MEM_RELEASE) }; } /// No dma-bufs on this system: the class is unchecked. @@ -2178,17 +2206,10 @@ impl Bytes { } } -/// The host's page size. +/// The host's page size (`host_memory::host_page`), 4096 where the system answers none that is a +/// power of two. fn host_page() -> u64 { - #[cfg(unix)] - { - // SAFETY: a query of the page size, with no argument. - let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; - if let Ok(page) = u64::try_from(page) { - if page.is_power_of_two() { - return page; - } - } - } - 4096 + crate::host_memory::host_page() + .filter(|page| page.is_power_of_two()) + .unwrap_or(4096) } diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 4e4cdd3dd..40e2b7154 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -142,7 +142,6 @@ mod host_bytes; mod host_memory; mod host_ram; mod host_residency; -#[cfg(unix)] mod host_shared_pointers; mod idle_sweep; mod image_barrier; diff --git a/crates/metal2vulkan-runtime/src/managed_copy.rs b/crates/metal2vulkan-runtime/src/managed_copy.rs index 568c777f1..cf9a94b58 100644 --- a/crates/metal2vulkan-runtime/src/managed_copy.rs +++ b/crates/metal2vulkan-runtime/src/managed_copy.rs @@ -904,7 +904,6 @@ impl Device { of_heap: false, drops_writes: false, mirror: Some(HostCopy::Caller(Arc::clone(&caller))), - #[cfg(unix)] again: None, naming, }); diff --git a/crates/metal2vulkan-runtime/src/managed_sync.rs b/crates/metal2vulkan-runtime/src/managed_sync.rs index 4c9634ec8..3e032d562 100644 --- a/crates/metal2vulkan-runtime/src/managed_sync.rs +++ b/crates/metal2vulkan-runtime/src/managed_sync.rs @@ -160,7 +160,7 @@ impl SyncCopy { /// tracked buffer whose memory is not exported. Its `VkBuffer`'s handing out is read as each /// copy is decided. pub(super) fn writes_known(&self) -> bool { - self.buffer.identity().tracked && self.buffer.exported().is_none() + self.buffer.identity().tracked && !self.buffer.memory_exported() } /// Its buffer's key. diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 731850fb3..d33f05888 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -68,7 +68,6 @@ //! dma-bufs, each such image is made again over a dma-buf of its own new pages before the rebind //! settles (`Device::dma_buf_images_again`, `dma_buf.rs`), and refused likewise where it is not. -#[cfg(unix)] use super::buffer::Imported; use super::buffer::{Buffer, Detached, HostCell, HostPages, LeftTwins, Lying, WeakBuffer}; use super::command_buffer::CommandBufferShared; @@ -784,9 +783,7 @@ pub(super) struct Taken { /// nothing of a command buffer not yet submitted: their free, and the deallocator after it, run /// in that call, and the recording that named them never runs (its pin of the pages moved). pub(super) enum ImportHold { - #[cfg(unix)] Held(Arc), - #[cfg(unix)] Waiting(Weak), } @@ -794,9 +791,7 @@ impl ImportHold { /// Held weakly from now on. fn wait(&mut self) { match self { - #[cfg(unix)] ImportHold::Held(held) => *self = ImportHold::Waiting(Arc::downgrade(held)), - #[cfg(unix)] ImportHold::Waiting(_) => {} } } @@ -804,9 +799,7 @@ impl ImportHold { /// The objects, held until the command buffer completes: `None` where they went. fn retained(self) -> Option> { match self { - #[cfg(unix)] ImportHold::Held(held) => Some(Box::new(Retained::new(held))), - #[cfg(unix)] ImportHold::Waiting(held) => held .upgrade() .map(|held| Box::new(Retained::new(held)) as Box), @@ -818,17 +811,14 @@ impl ImportHold { /// ([`ImportHold::retained`]): where its completion's release lets go of them last, the import /// gone and a deallocator or a keep-alive waiting for their free, the free goes to the device's /// free thread (`free_thread.rs`, `Imported::let_go_at_completion`). -#[cfg(unix)] struct Retained(std::mem::ManuallyDrop>); -#[cfg(unix)] impl Retained { fn new(held: Arc) -> Retained { Retained(std::mem::ManuallyDrop::new(held)) } } -#[cfg(unix)] impl Drop for Retained { fn drop(&mut self) { // SAFETY: taken once, here, as the hold goes, and never read again. diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index db501982a..46db418a3 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -1518,10 +1518,28 @@ impl Pages { }) } - /// None off Unix. - #[cfg(not(unix))] - fn map(_length: u64) -> Option { - None + /// `length` bytes of new pages on Windows: a committed allocation of their own + /// (`VirtualAlloc`); `None` where the system makes none. + #[cfg(windows)] + fn map(length: u64) -> Option { + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, + }; + let bytes = usize::try_from(length).ok()?; + // SAFETY: a new allocation, at an address the system picks. + let pointer = unsafe { + VirtualAlloc( + std::ptr::null(), + bytes, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + }; + Some(Pages { + start: NonNull::new(pointer.cast())?, + length, + imports: Cell::new(0), + }) } /// Write `byte` into every byte. @@ -1541,6 +1559,12 @@ impl Drop for Pages { unsafe { libc::munmap(self.start.as_ptr().cast(), self.length as usize); } + #[cfg(windows)] + // SAFETY: as above; a release frees the allocation whole, from its base, with a size of 0. + unsafe { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + VirtualFree(self.start.as_ptr().cast(), 0, MEM_RELEASE); + } } } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index e9a691790..222695328 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -255,7 +255,6 @@ pub(super) struct TextureState { /// Each Vulkan format's `DRM_FORMAT_MOD_LINEAR` tiling features, asked of the driver at the /// first image of that tiling planned in it (`dma_buf.rs`'s `modifier_features`): one entry /// per format at most. - #[cfg(unix)] pub(super) modifier_features: Mutex>, /// Every pixel format's `minimumLinearTextureAlignmentForPixelFormat:` answer, worked out at /// the first query of any and kept for the device's life (`texture/linear_alignment.rs`). @@ -305,7 +304,6 @@ impl TextureState { usage_answers: Mutex::new(UsageAnswers::default()), sample_moves: Mutex::new(Vec::new()), format_answers: Mutex::new(HashMap::new()), - #[cfg(unix)] modifier_features: Mutex::new(HashMap::new()), linear_alignments: std::sync::OnceLock::new(), heap_types: std::sync::OnceLock::new(), @@ -3921,9 +3919,13 @@ impl Device { Some(Ok(None)) => { return Err(internal("an exported dma-buf's image made and not bound")) } + #[cfg(unix)] Some(Ok(Some(made))) => { Ok(self.exported_dma_buf_texture_image(made, plan, descriptor, texels)) } + // No image is made over a dma-buf on this system. + #[cfg(not(unix))] + Some(Ok(Some(made))) => match made {}, }); } }; @@ -4074,18 +4076,6 @@ impl Device { (image.shared(), count) } - /// No image is made over a dma-buf on this system. - #[cfg(not(unix))] - fn exported_dma_buf_texture_image( - &self, - made: ExportedImage, - _plan: ImagePlan, - _descriptor: &TextureDescriptor, - _texels: &Texels, - ) -> (Arc, AliasCount) { - match made {} - } - /// The image aliasing `texels` in their buffer's memory, the device's own, of a texture of /// Metal `usage` and declared plan `plan`, made with `descriptor` (checked as `layout`): the /// first of its plans the device makes one of ([`alias_image`](Self::alias_image)), with what diff --git a/crates/metal2vulkan-runtime/src/this_thread.rs b/crates/metal2vulkan-runtime/src/this_thread.rs index 2e119870d..dd077b875 100644 --- a/crates/metal2vulkan-runtime/src/this_thread.rs +++ b/crates/metal2vulkan-runtime/src/this_thread.rs @@ -35,3 +35,29 @@ pub(crate) fn runs(handle: &JoinHandle) -> bool { handle.thread().id() == std::thread::current().id() } } + +/// The calling thread's CPU time on Windows, in nanoseconds: its kernel and user times +/// (`GetThreadTimes`), each counted in 100 ns units; `None` where the system answers none. +#[cfg(windows)] +pub(crate) fn cpu_nanos() -> Option { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let (mut created, mut exited) = (FILETIME::default(), FILETIME::default()); + let (mut kernel, mut user) = (FILETIME::default(), FILETIME::default()); + // SAFETY: the pseudo-handle of the calling thread, and four valid `FILETIME`s to fill. + let read = unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + if read == 0 { + return None; + } + let ticks = + |time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime); + ticks(kernel).checked_add(ticks(user))?.checked_mul(100) +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index f4bbac396..6e9327d4f 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -4338,8 +4338,8 @@ impl Counters { /// The kernel was asked about `mappings` of the process's mappings, for their write /// permission, before an import of host pages (`host_memory.rs`'s `refuse_unwritable`, which - /// asks only on Linux). - #[cfg(target_os = "linux")] + /// asks on Linux and Windows). + #[cfg(any(target_os = "linux", windows))] pub(crate) fn host_mappings_queried(&self, mappings: u64) { if mappings > 0 { self.host_mappings_queried @@ -4952,7 +4952,6 @@ impl Counters { /// The driver was asked a format's `DRM_FORMAT_MOD_LINEAR` tiling features (`dma_buf.rs`'s /// `modifier_features`). - #[cfg(unix)] pub(crate) fn modifier_features_asked(&self) { self.modifier_feature_queries .fetch_add(1, Ordering::Relaxed); @@ -9423,10 +9422,10 @@ pub struct WorkCounts { pub host_releases_held_inside: u64, /// The process's mappings the kernel was asked about, for their write permission, before a /// no-copy buffer's, heap's or rebind's own import of host pages, on Linux (one `PROCMAP_QUERY` - /// each, or one line of `/proc/self/maps` where the kernel predates the query): one per mapping - /// the import's pages lie in, a view of scattered pages one per run, at each such import. A - /// buffer made over the same bytes as a live one, which lies in its import, asks about none. - /// None off Linux. + /// each, or one line of `/proc/self/maps` where the kernel predates the query) and on Windows + /// (one `VirtualQuery` each region): one per mapping the import's pages lie in, a view of + /// scattered pages one per run, at each such import. A buffer made over the same bytes as a + /// live one, which lies in its import, asks about none. None on macOS. pub host_mappings_queried: u64, /// Imports of dma-bufs of host pages a caller's source made (`HostMemory::with_dma_buf`), /// where the device refused the pages' pointer: no-copy buffers', heaps' and rebinds' alike, diff --git a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs index dd766c9f9..aa646ea57 100644 --- a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs +++ b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs @@ -321,7 +321,6 @@ impl Device { of_heap: false, drops_writes: false, mirror: None, - #[cfg(unix)] again: None, naming: Naming::New, });