Files
EonaCat.XSBox/crates/graphics/src/inplace.rs
T
EonaCat fe8e2cb5e7
Rust validation / Windows x64 build and tests (push) Waiting to run
Rust validation / Formatting (push) Failing after 28s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s
Initial version
2026-12-04 21:32:34 +01:00

1704 lines
65 KiB
Rust

use std::collections::BTreeMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU64, Ordering};
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
use windows::core::{Interface, s};
use windows_sys::Win32::System::Memory as mem;
const K64: usize = 64 << 10;
const MEM_WRITE_WATCH: u32 = 0x20_0000;
pub(crate) fn probe_level() -> u8 {
static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*LEVEL.get_or_init(|| std::env::var("EONACAT_XS_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
}
pub(crate) fn level() -> u8 {
static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*LEVEL.get_or_init(|| std::env::var("EONACAT_XS_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
}
pub(crate) fn view_on() -> u8 {
static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("EONACAT_XS_INPLACE_VIEW").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
}
fn most() -> u64 {
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*MOST.get_or_init(|| std::env::var("EONACAT_XS_INPLACE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(4096) << 20)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Openability {
Private,
View { section: usize, offset: u64 },
Refused(NotOpenable),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum NotOpenable {
Unmapped,
Scattered,
Holes,
}
pub(crate) fn openability(start: u64, len: u64) -> Openability {
let len = len.max(1);
match cover(start as usize, len as usize) {
Cover::Run(section, offset) => Openability::View { section, offset },
Cover::Scattered => Openability::Refused(NotOpenable::Scattered),
Cover::Holes => Openability::Refused(NotOpenable::Holes),
Cover::None => {
if private_whole(start as usize, len as usize) {
Openability::Private
} else {
Openability::Refused(NotOpenable::Unmapped)
}
}
}
}
static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
pub(crate) struct Placed {
pub(crate) buffer: ID3D12Resource,
pub(crate) heap: ID3D12Heap,
pub(crate) gpu: u64,
pub(crate) bias: u64,
pub(crate) keep: Option<std::sync::Arc<SectionView>>,
}
pub(crate) struct SectionView {
base: usize,
}
impl SectionView {
pub(crate) fn map(section: usize, offset: u64, bytes: usize) -> Option<std::sync::Arc<SectionView>> {
let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, bytes) }.Value as usize;
if base == 0 {
tracing::warn!(section = format_args!("{section:#x}"), offset, bytes, error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own");
return None;
}
Some(std::sync::Arc::new(SectionView { base }))
}
pub(crate) fn base(&self) -> usize {
self.base
}
}
impl Drop for SectionView {
fn drop(&mut self) {
unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: self.base as *mut c_void }) };
}
}
unsafe impl Send for SectionView {}
unsafe impl Sync for SectionView {}
pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> {
let at = start & !(K64 as u64 - 1);
let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at;
if !private_whole(at as usize, bytes as usize) {
return Err(None);
}
let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?;
let buffer = place(device, &heap, 0, bytes).map_err(Some)?;
let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at);
Ok(Placed { buffer, heap, gpu, bias: start - at, keep: None })
}
pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> {
let level = level();
if level >= 3 || level < if window { 1 } else { 2 } {
return None;
}
place_private(start, len, window).ok()
}
fn place_private(start: u64, len: u64, window: bool) -> Result<Placed, crate::residency::NoDirect> {
match openability(start, len) {
Openability::Private => {}
Openability::View { section, offset } => {
STATS[4].fetch_add(1, Ordering::Relaxed);
crate::residency::direct_refused(len, crate::residency::NoDirect::NotOpenable);
if STATS[4].load(Ordering::Relaxed) <= 8 {
tracing::debug!(
start = format_args!("{start:#x}"),
len,
section = format_args!("{section:#x}"),
offset,
"title memory is a view of a section run: not opened by this stage"
);
}
return Err(crate::residency::NoDirect::NotOpenable);
}
Openability::Refused(why) => {
STATS[4].fetch_add(1, Ordering::Relaxed);
crate::residency::direct_refused(len, crate::residency::NoDirect::NotOpenable);
if STATS[4].load(Ordering::Relaxed) <= 8 {
tracing::debug!(start = format_args!("{start:#x}"), len, ?why, "title memory cannot be opened: a copy instead");
}
return Err(crate::residency::NoDirect::NotOpenable);
}
}
if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() {
STATS[6].fetch_add(1, Ordering::Relaxed);
crate::residency::direct_refused(len, crate::residency::NoDirect::Cap);
return Err(crate::residency::NoDirect::Cap);
}
let Some(host) = crate::host::host() else {
crate::residency::direct_refused(len, crate::residency::NoDirect::HostUnavailable);
return Err(crate::residency::NoDirect::HostUnavailable);
};
if !part_opening(&host.device) {
crate::residency::direct_refused(len, crate::residency::NoDirect::HostUnavailable);
return Err(crate::residency::NoDirect::HostUnavailable);
}
match place_part(&host.device, start, len) {
Ok(placed) => {
counted(window, len);
Ok(placed)
}
Err(None) => {
STATS[4].fetch_add(1, Ordering::Relaxed);
crate::residency::direct_refused(len, crate::residency::NoDirect::NotOpenable);
Err(crate::residency::NoDirect::NotOpenable)
}
Err(Some(e)) => {
crate::residency::direct_refused(len, crate::residency::NoDirect::HostRefused);
if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 {
tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead");
}
Err(crate::residency::NoDirect::HostRefused)
}
}
}
pub(crate) fn part_opening(device: &ID3D12Device) -> bool {
static CAPABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*CAPABLE.get_or_init(|| device.cast::<ID3D12Device13>().is_ok())
}
const REGION_MOST: u64 = 512 << 20;
struct Region {
start: u64,
end: u64,
heap: ID3D12Heap,
view: std::sync::Arc<SectionView>,
}
static REGIONS: std::sync::Mutex<Vec<Region>> = std::sync::Mutex::new(Vec::new());
fn region_for(device: &ID3D12Device, at: u64, end: u64) -> Result<(ID3D12Heap, std::sync::Arc<SectionView>, u64), (crate::residency::NoDirect, String)> {
use crate::residency::NoDirect;
let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(r) = regions.iter().find(|r| r.start <= at && end <= r.end) {
return Ok((r.heap.clone(), r.view.clone(), r.start));
}
let Some(stretch) = native_stretch(at as usize, (end - at) as usize) else {
return Err((NoDirect::NotOpenable, format!("not one run of one section: {:?}", cover(at as usize, (end - at) as usize))));
};
let (first, run_bytes, run_offset) = (stretch.first, stretch.bytes, stretch.offset);
let run_section = stretch.section as usize;
let (area_start, area_bytes, section_offset) = if run_bytes as u64 <= REGION_MOST {
(first as u64, run_bytes as u64, run_offset)
} else {
let Cover::Run(section, offset) = cover(at as usize, (end - at) as usize) else {
return Err((NoDirect::NotOpenable, "not one run of one section".to_owned()));
};
debug_assert_eq!(section, run_section);
(at, end - at, offset)
};
let area_bytes = area_bytes as usize;
let Some(view) = SectionView::map(run_section, section_offset, area_bytes) else {
return Err((NoDirect::HostRefused, "no view of the run".to_owned()));
};
if !committed(view.base(), area_bytes) {
return Err((NoDirect::NotOpenable, "pages of the run are not committed".to_owned()));
}
let heap = match open(device, From::Part(view.base(), area_bytes)) {
Ok(heap) => heap,
Err(e) => return Err((NoDirect::HostRefused, format!("refused by the host: {e}"))),
};
regions.push(Region { start: area_start, end: area_start + area_bytes as u64, heap: heap.clone(), view: view.clone() });
Ok((heap, view, area_start))
}
fn forget_regions(at: usize, len: usize) {
let (at, end) = (at as u64, (at as u64).saturating_add(len as u64));
let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner());
regions.retain(|r| r.end <= at || r.start >= end);
}
fn place_view_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, (crate::residency::NoDirect, String)> {
use crate::residency::NoDirect;
let at = start & !(K64 as u64 - 1);
let end = (start + len.max(1)).next_multiple_of(K64 as u64);
let bytes = end - at;
let (heap, view, region_start) = region_for(device, at, end)?;
let buffer = match place(device, &heap, at - region_start, bytes) {
Ok(buffer) => buffer,
Err(e) => return Err((NoDirect::HostRefused, format!("no buffer placed in the heap: {e}"))),
};
let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at);
Ok(Placed { buffer, heap, gpu, bias: start - at, keep: Some(view) })
}
fn place_view_checked(start: u64, len: u64, window: bool) -> Result<Placed, crate::residency::NoDirect> {
use crate::residency::NoDirect;
let at = start & !(K64 as u64 - 1);
let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at;
if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + bytes > most() {
STATS[6].fetch_add(1, Ordering::Relaxed);
crate::residency::direct_refused(bytes, NoDirect::Cap);
return Err(NoDirect::Cap);
}
let Some(host) = crate::host::host() else {
crate::residency::direct_refused(bytes, NoDirect::HostUnavailable);
return Err(NoDirect::HostUnavailable);
};
if !part_opening(&host.device) {
crate::residency::direct_refused(bytes, NoDirect::HostUnavailable);
return Err(NoDirect::HostUnavailable);
}
match place_view_part(&host.device, start, len) {
Ok(placed) => {
counted(window, len);
Ok(placed)
}
Err((why, message)) => {
let stat = if matches!(why, NoDirect::HostRefused) { 5 } else { 4 };
let n = STATS[stat].fetch_add(1, Ordering::Relaxed) + 1;
if n <= 8 || n.is_power_of_two() {
tracing::warn!(start = format_args!("{start:#x}"), len, window, %message, "title memory not in place: a copy instead");
}
crate::residency::direct_refused(len, why);
Err(why)
}
}
}
pub(crate) fn place_view_big(start: u64, len: u64, window: bool) -> Option<Placed> {
static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let min = *MIN.get_or_init(|| view_big_min(std::env::var("EONACAT_XS_INPLACE_VIEW_BIG").ok().as_deref()));
if !view_big_enough(min, len) {
return None;
}
match place_view_checked(start, len, window) {
Ok(placed) => {
tracing::info!(start = format_args!("{start:#x}"), len, window, "EONACAT_XS_INPLACE_VIEW_BIG: title memory in place, no copy");
Some(placed)
}
Err(_) => None,
}
}
fn view_big_min(v: Option<&str>) -> u64 {
v.and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
}
fn view_big_enough(min: u64, len: u64) -> bool {
min != 0 && len >= min
}
fn fallback_paths(level: u8, view: u8, window: bool) -> (bool, bool) {
let view = view >= if window { 1 } else { 2 };
let private = level >= 3;
(view, private)
}
pub(crate) fn place_fallback(start: u64, len: u64, window: bool) -> Option<Placed> {
let (view, private) = fallback_paths(level(), view_on(), window);
if view && let Ok(placed) = place_view_checked(start, len, window) {
return Some(placed);
}
if private && let Ok(placed) = place_private(start, len, window) {
return Some(placed);
}
None
}
pub(crate) fn land_level() -> u8 {
static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*LEVEL.get_or_init(|| std::env::var("EONACAT_XS_LAND_IN_PLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
}
static LAND: [AtomicU64; 13] = [const { AtomicU64::new(0) }; 13];
mod land_stat {
pub(super) const BUFFERS: usize = 0;
pub(super) const BUFFER_BYTES: usize = 1;
pub(super) const WINDOWS: usize = 2;
pub(super) const WINDOW_BYTES: usize = 3;
pub(super) const VIEW: usize = 4;
pub(super) const NOT_OPENABLE: usize = 5;
pub(super) const CAP: usize = 6;
pub(super) const HOST_REFUSED: usize = 7;
pub(super) const HOST_UNAVAILABLE: usize = 8;
pub(super) const OTHER_CLASS: usize = 9;
pub(super) const SKIPPED_BYTES: usize = 10;
pub(super) const SKIPPED_RANGES: usize = 11;
pub(super) const ASKED: usize = 12;
}
fn lands_in_place(classes: impl IntoIterator<Item = usize>) -> bool {
use crate::shadow::mem_class::{COHERENT, NONCOHERENT};
let mut any = false;
for class in classes {
if class != COHERENT && class != NONCOHERENT {
return false;
}
any = true;
}
any
}
pub(crate) fn place_landing(start: u64, len: u64, window: bool) -> Option<Placed> {
use crate::residency::NoDirect;
let level = land_level();
if level == 0 {
return None;
}
let count = |which: usize, n: u64| LAND[which].fetch_add(n, Ordering::Relaxed);
if !lands_in_place(crate::shadow::class_pieces(start, len.max(1)).into_iter().map(|(_, _, class)| class)) {
count(land_stat::OTHER_CLASS, 1);
return None;
}
count(land_stat::ASKED, 1);
let placed = match openability(start, len) {
Openability::Private => place_private(start, len, window),
Openability::View { .. } if level >= 2 => place_view_checked(start, len, window),
Openability::View { .. } => {
count(land_stat::VIEW, 1);
return None;
}
Openability::Refused(_) => Err(NoDirect::NotOpenable),
};
match placed {
Ok(placed) => {
if window {
count(land_stat::WINDOWS, 1);
count(land_stat::WINDOW_BYTES, len);
} else {
count(land_stat::BUFFERS, 1);
count(land_stat::BUFFER_BYTES, len);
}
Some(placed)
}
Err(why) => {
count(
match why {
NoDirect::NotOpenable => land_stat::NOT_OPENABLE,
NoDirect::Cap => land_stat::CAP,
NoDirect::HostRefused => land_stat::HOST_REFUSED,
NoDirect::HostUnavailable => land_stat::HOST_UNAVAILABLE,
},
1,
);
None
}
}
}
pub(crate) fn land_skipped(bytes: u64, ranges: u64) {
LAND[land_stat::SKIPPED_BYTES].fetch_add(bytes, Ordering::Relaxed);
LAND[land_stat::SKIPPED_RANGES].fetch_add(ranges, Ordering::Relaxed);
}
pub(crate) fn land_log(frames: f64) {
if land_level() == 0 || frames <= 0.0 {
return;
}
let s: Vec<f64> = LAND.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
let mb = |v: f64| v / (1 << 20) as f64;
use land_stat::*;
tracing::info!(
"title memory the GPU writes and the CPU reads back, in place (EONACAT_XS_LAND_IN_PLACE={}), per frame: {:.1} buffers {:.2} MB \
and {:.1} windows {:.2} MB placed of {:.1} asks; turned down: {:.1} view memory (level 1), {:.1} not openable, {:.1} over \
EONACAT_XS_INPLACE_MB, {:.1} refused by the host, {:.1} no host or no ID3D12Device13; {:.1} asks over other memory left as \
before; the landing skipped {:.2} MB in {:.1} ranges; in place now: {} buffers {} MB, {} windows {} MB",
land_level(),
s[BUFFERS],
mb(s[BUFFER_BYTES]),
s[WINDOWS],
mb(s[WINDOW_BYTES]),
s[ASKED],
s[VIEW],
s[NOT_OPENABLE],
s[CAP],
s[HOST_REFUSED],
s[HOST_UNAVAILABLE],
s[OTHER_CLASS],
mb(s[SKIPPED_BYTES]),
s[SKIPPED_RANGES],
STATS[2].load(Ordering::Relaxed),
STATS[3].load(Ordering::Relaxed) >> 20,
STATS[0].load(Ordering::Relaxed),
STATS[1].load(Ordering::Relaxed) >> 20,
);
}
pub(crate) fn counted(window: bool, bytes: u64) {
let at = if window { 0 } else { 2 };
STATS[at].fetch_add(1, Ordering::Relaxed);
STATS[at + 1].fetch_add(bytes, Ordering::Relaxed);
}
pub(crate) fn gone(window: bool, bytes: u64) {
let at = if window { 0 } else { 2 };
STATS[at].fetch_sub(1, Ordering::Relaxed);
STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed);
}
pub(crate) fn holds_any() -> bool {
STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) != 0 || crate::port::holds_any()
}
pub fn title_memory_freeing(at: usize, len: usize) {
forget_regions(at, len);
crate::port::forget(at, len);
if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 {
return;
}
let gone = crate::shadow::in_place_let_go(at as u64, len as u64);
STATS[7].fetch_add(gone, Ordering::Relaxed);
}
fn say() {
static LAST: AtomicU64 = AtomicU64::new(0);
let now = crate::host::now_ms();
let last = LAST.load(Ordering::Relaxed);
if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() {
return;
}
let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect();
tracing::info!(
"title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} not private memory committed whole or not one section run, \
{} refused by the host, {} over EONACAT_XS_INPLACE_MB; {} let go because their memory changed",
s[0],
s[1] >> 20,
s[2],
s[3] >> 20,
s[4],
s[5],
s[6],
s[7]
);
}
pub(crate) enum From {
Region(usize),
Part(usize, usize),
Section(usize),
}
pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result<ID3D12Heap> {
unsafe {
match from {
From::Region(at) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void),
From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes),
From::Section(handle) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)),
}
}
}
fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size.max(1),
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
..Default::default()
}
}
pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> {
let mut placed: Option<ID3D12Resource> = None;
let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? };
placed.ok_or_else(windows::core::Error::empty)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SectionIdentity {
handle: usize,
generation: u64,
native_importable: bool,
}
struct Views {
views: BTreeMap<usize, (usize, usize, u64)>,
identities: BTreeMap<usize, SectionIdentity>,
pages: BTreeMap<(usize, u64), Vec<usize>>,
pages_twice: usize,
sections: Vec<(usize, u64, bool, u64)>,
next_generation: u64,
whole: Vec<(usize, usize)>,
}
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
views: BTreeMap::new(),
identities: BTreeMap::new(),
pages: BTreeMap::new(),
pages_twice: 0,
sections: Vec::new(),
next_generation: 0,
whole: Vec::new(),
});
static VIEWS_MIN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX);
static VIEWS_MAX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
static PAGES_TWICE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn sync_view_bounds(v: &Views) {
let min = v.views.first_key_value().map_or(usize::MAX, |(&base, _)| base);
let max = v.views.last_key_value().map_or(0, |(&base, &(bytes, _, _))| base.saturating_add(bytes));
VIEWS_MIN.store(min, Ordering::Release);
VIEWS_MAX.store(max, Ordering::Release);
PAGES_TWICE.store(v.pages_twice, Ordering::Release);
}
fn views() -> std::sync::RwLockReadGuard<'static, Views> {
VIEWS.read().unwrap_or_else(|e| e.into_inner())
}
fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> {
VIEWS.write().unwrap_or_else(|e| e.into_inner())
}
pub fn title_memory_section(section: usize, bytes: u64, native_importable: bool) {
let mut v = views_mut();
v.sections.retain(|s| s.0 != section);
v.whole.retain(|w| w.0 != section);
v.next_generation = v.next_generation.wrapping_add(1).max(1);
let generation = v.next_generation;
v.sections.push((section, bytes, native_importable, generation));
}
pub fn title_memory_section_gone(section: usize) {
crate::alias_rt::section_gone(section);
crate::port::section_gone(section);
let whole = {
let mut v = views_mut();
v.sections.retain(|s| s.0 != section);
let at = v.whole.iter().position(|w| w.0 == section);
at.map(|i| v.whole.swap_remove(i).1)
};
if let Some(base) = whole.filter(|&base| base != 0) {
unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) };
}
}
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
{
let mut v = views_mut();
v.views.insert(at, (len, section, offset));
let identity = v
.sections
.iter()
.find(|s| s.0 == section)
.map(|s| SectionIdentity {
handle: section,
generation: s.3,
native_importable: s.2,
})
.unwrap_or(SectionIdentity {
handle: section,
generation: 0,
native_importable: false,
});
v.identities.insert(at, identity);
for k in 0..len.div_ceil(K64) {
let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default();
shown.push(at + k * K64);
let twice = shown.len() == 2;
v.pages_twice += usize::from(twice);
}
sync_view_bounds(&v);
}
crate::watch::views_mapped(section, offset, len);
}
pub(crate) fn views_gone(at: usize, len: usize) {
crate::heap_hooks::views_gone(at, len);
let mut v = views_mut();
if v.views.is_empty() {
return;
}
let end = at.saturating_add(len);
let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base);
let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect();
for base in gone {
let Some((bytes, section, offset)) = v.views.remove(&base) else {
continue;
};
v.identities.remove(&base);
for k in 0..bytes.div_ceil(K64) {
let key = (section, offset + (k * K64) as u64);
if let Some(pages) = v.pages.get_mut(&key) {
let page = base + k * K64;
let before = pages.len();
pages.retain(|&shown| shown != page);
let after = pages.len();
if after == 0 {
v.pages.remove(&key);
}
v.pages_twice = v.pages_twice.saturating_sub(usize::from(before >= 2 && after < 2));
}
}
}
sync_view_bounds(&v);
}
pub(crate) fn shown_elsewhere(start: usize, end: usize) -> Vec<(usize, Vec<usize>)> {
shown_elsewhere_in([(start, end)])
}
pub(crate) fn shown_elsewhere_in(spans: impl IntoIterator<Item = (usize, usize)>) -> Vec<(usize, Vec<usize>)> {
if PAGES_TWICE.load(Ordering::Acquire) == 0 {
return Vec::new();
}
let min = VIEWS_MIN.load(Ordering::Acquire);
let max = VIEWS_MAX.load(Ordering::Acquire);
if min >= max {
return Vec::new();
}
let v = views();
let mut out = Vec::new();
if v.pages_twice == 0 {
return out;
}
for (start, end) in spans {
if start >= end || end <= min || start >= max {
continue;
}
let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base);
for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) {
let from = start.max(base) & !(K64 - 1);
for page in (from..end.min(base + bytes)).step_by(K64) {
let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else {
continue;
};
if (2..=crate::watch::MANY_VIEWS).contains(&shown.len()) {
out.push((page, shown.iter().copied().filter(|&at| at != page).collect()));
}
}
}
}
out
}
pub(crate) fn aliased_section_pages(start: usize, len: usize) -> Option<(usize, u64, Vec<u32>)> {
if len == 0 || PAGES_TWICE.load(Ordering::Acquire) == 0 {
return None;
}
let end = start.checked_add(len)?;
if end <= VIEWS_MIN.load(Ordering::Acquire) || start >= VIEWS_MAX.load(Ordering::Acquire) {
return None;
}
let v = views();
if v.pages_twice == 0 {
return None;
}
let page_start = start & !(K64 - 1);
let page_end = start.checked_add(len)?.next_multiple_of(K64);
let count = (page_end - page_start) / K64;
let mut pages = Vec::with_capacity(count);
let mut section_id: Option<usize> = None;
let mut any_aliased = false;
for at in (page_start..page_end).step_by(K64) {
let (&base, &(_bytes, section, offset)) = v
.views
.range(..=at)
.next_back()
.filter(|(base, view)| at < *base + view.0)?;
match section_id {
None => section_id = Some(section),
Some(prev) if prev != section => return None,
Some(_) => {}
}
let page_off = offset + (at - base) as u64;
if !any_aliased && v.pages.get(&(section, page_off)).is_some_and(|shown| shown.len() >= 2) {
any_aliased = true;
}
pages.push((page_off / K64 as u64) as u32);
}
if !any_aliased {
return None;
}
let section = section_id?;
let section_bytes = v.sections.iter().find(|s| s.0 == section).map(|s| s.1)?;
Some((section, section_bytes, pages))
}
pub(crate) fn pages_of(page: usize) -> Vec<usize> {
let v = views();
let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else {
return Vec::new();
};
let within = page.wrapping_sub(base);
if within >= bytes || !within.is_multiple_of(K64) {
return Vec::new();
}
v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default()
}
pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> {
if len == 0 {
return Vec::new();
}
let v = views();
let end = offset.saturating_add(len as u64);
let mut pages: Vec<usize> = Vec::new();
let mut at = offset - offset % K64 as u64;
while at < end {
if let Some(shown) = v.pages.get(&(section, at))
&& shown.len() <= crate::watch::MANY_VIEWS
{
pages.extend(shown.iter().copied());
}
match at.checked_add(K64 as u64) {
Some(next) => at = next,
None => break,
}
}
pages.sort_unstable();
pages.dedup();
let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len());
for page in pages {
match runs.last_mut() {
Some((first, bytes)) if *first + *bytes == page => *bytes += K64,
_ => runs.push((page, K64)),
}
}
runs
}
pub(crate) fn shown_bytes(at: usize, len: usize) -> Option<u64> {
let end = at.saturating_add(len);
let v = views();
let first = v.views.range(..=at).next_back();
let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1)));
let (mut there, mut any) = (0u64, false);
for (&base, view) in first.into_iter().chain(rest) {
let (from, to) = (base.max(at), base.saturating_add(view.0).min(end));
if from < to {
there += (to - from) as u64;
any = true;
}
}
any.then_some(there)
}
pub(crate) fn shown_runs(at: usize, len: usize) -> Vec<(usize, usize)> {
let end = at.saturating_add(len);
let v = views();
let first = v.views.range(..=at).next_back();
let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1)));
let mut runs: Vec<(usize, usize)> = Vec::new();
for (&base, view) in first.into_iter().chain(rest) {
let (from, to) = (base.max(at), base.saturating_add(view.0).min(end));
if from >= to {
continue;
}
match runs.last_mut() {
Some((run, bytes)) if *run + *bytes == from => *bytes += to - from,
_ => runs.push((from, to - from)),
}
}
runs
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(crate) enum Cover {
None,
Holes,
Scattered,
Run(usize, u64),
}
fn cover_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Cover {
let end = at + len.max(1);
let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else {
return Cover::None;
};
let first = (section, offset + (at - base) as u64);
let (mut reached, mut one) = (base + bytes, true);
while reached < end {
let Some(&(bytes, s, o)) = views.get(&reached) else {
return Cover::Holes;
};
one &= s == first.0 && o == first.1 + (reached - at) as u64;
reached += bytes;
}
if one { Cover::Run(first.0, first.1) } else { Cover::Scattered }
}
pub(crate) fn cover(at: usize, len: usize) -> Cover {
cover_in(&views().views, at, len)
}
pub(crate) fn cover_layout(at: usize, len: usize) -> String {
let v = views();
let end = at + len;
let mut runs: Vec<(usize, usize, usize, u64)> = Vec::new();
let start = v.views.range(..=at).next_back().map_or(at, |(&b, _)| b);
for (&base, &(bytes, section, offset)) in v.views.range(start..end) {
if base + bytes <= at {
continue;
}
match runs.last_mut() {
Some(r) if r.0 + r.1 == base && r.2 == section && r.3 + r.1 as u64 == offset => r.1 += bytes,
_ => runs.push((base, bytes, section, offset)),
}
}
let shown: Vec<String> = runs.iter().take(24).map(|r| format!("{:#x}+{:#x}=s{:#x}@{:#x}", r.0, r.1, r.2, r.3)).collect();
format!("{} runs: {}", runs.len(), shown.join(" "))
}
fn stretch_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Option<(usize, usize, usize, u64)> {
let Cover::Run(section, offset) = cover_in(views, at, len) else {
return None;
};
let delta = at as i128 - offset as i128;
let follows = |a: usize, s: usize, o: u64| s == section && a as i128 - o as i128 == delta;
let (&first, &(n, _, _)) = views.range(..=at).next_back()?;
let mut start = first;
for (&a, &(n, s, o)) in views.range(..first).rev() {
if a + n != start || !follows(a, s, o) {
break;
}
start = a;
}
let mut stop = first + n;
for (&a, &(n, s, o)) in views.range(first + 1..) {
if a != stop || !follows(a, s, o) {
break;
}
stop = a + n;
}
Some((start, stop - start, section, (start as i128 - delta) as u64))
}
pub(crate) struct NativeStretch {
pub(crate) first: usize,
pub(crate) bytes: usize,
pub(crate) section: windows_sys::Win32::Foundation::HANDLE,
pub(crate) offset: u64,
}
impl Drop for NativeStretch {
fn drop(&mut self) {
unsafe { windows_sys::Win32::Foundation::CloseHandle(self.section) };
}
}
fn importable_stretch_in(v: &Views, at: usize, len: usize) -> Option<(usize, usize, usize, u64)> {
let found @ (first, bytes, section, _) = stretch_in(&v.views, at, len)?;
let identity = *v.identities.get(&first)?;
let current = v
.sections
.iter()
.find(|s| s.0 == section && s.3 == identity.generation)?;
if identity.handle != section || !identity.native_importable || !current.2 {
return None;
}
let stop = first.checked_add(bytes)?;
if v
.views
.range(first..stop)
.any(|(&base, _)| v.identities.get(&base) != Some(&identity))
{
return None;
}
Some(found)
}
pub(crate) fn native_stretch(at: usize, len: usize) -> Option<NativeStretch> {
let v = views();
let (first, bytes, section, offset) = importable_stretch_in(&v, at, len)?;
let process = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcess() };
let mut duplicate: windows_sys::Win32::Foundation::HANDLE = std::ptr::null_mut();
let copied = unsafe {
windows_sys::Win32::Foundation::DuplicateHandle(
process,
section as _,
process,
&mut duplicate,
0,
0,
windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS,
)
};
if copied == 0 {
return None;
}
Some(NativeStretch {
first,
bytes,
section: duplicate,
offset,
})
}
pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
let end = at.saturating_add(len.max(1));
if end <= VIEWS_MIN.load(Ordering::Acquire) || at >= VIEWS_MAX.load(Ordering::Acquire) {
return None;
}
let known = {
let v = views();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset))
};
if let Some((base, offset)) = known {
return (base != 0).then(|| base + offset as usize);
}
let mut v = views_mut();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
let base = match v.whole.iter().find(|w| w.0 == section) {
Some(w) => w.1,
None => {
let &(_, bytes, _, _) = v.sections.iter().find(|s| s.0 == section)?;
let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize;
if base == 0 {
tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own");
}
v.whole.push((section, base));
base
}
};
(base != 0).then(|| base + offset as usize)
}
pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> {
if page.saturating_add(K64) <= VIEWS_MIN.load(Ordering::Acquire) || page >= VIEWS_MAX.load(Ordering::Acquire) {
return None;
}
for asked in [false, true] {
{
let v = views();
let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?;
let within = page.wrapping_sub(base);
if within >= bytes || !within.is_multiple_of(K64) {
return None;
}
let offset = offset + within as u64;
if let Some(whole) = v.whole.iter().find(|w| w.0 == section) {
let mut shown = [0; 8];
let all = v.pages.get(&(section, offset))?;
shown.get_mut(..all.len())?.copy_from_slice(all);
return (whole.1 != 0).then(|| (whole.1 + offset as usize, shown));
}
}
if asked || beside(page, K64).is_none() {
return None;
}
}
None
}
pub(crate) fn committed(at: usize, len: usize) -> bool {
let mut here = at;
while here < at.saturating_add(len) {
let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { mem::VirtualQuery(here as *const c_void, &mut info, size_of_val(&info)) } == 0 || info.State != mem::MEM_COMMIT {
return false;
}
here = (info.BaseAddress as usize).saturating_add(info.RegionSize);
}
true
}
pub(crate) fn private_whole(at: usize, len: usize) -> bool {
let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) };
n != 0
&& info.State == mem::MEM_COMMIT
&& info.Type == mem::MEM_PRIVATE
&& info.Protect == mem::PAGE_READWRITE
&& (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len)
}
fn hr<T>(result: &windows::core::Result<T>) -> String {
match result {
Ok(_) => "ok".to_owned(),
Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()),
}
}
pub(crate) struct Rig {
device: ID3D12Device,
queue: ID3D12CommandQueue,
allocator: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
fence: ID3D12Fence,
done: u64,
event: HANDLE,
}
impl Drop for Rig {
fn drop(&mut self) {
unsafe {
let _ = windows::Win32::Foundation::CloseHandle(self.event);
}
}
}
impl Rig {
pub(crate) fn new(device: &ID3D12Device) -> windows::core::Result<Rig> {
unsafe {
let queue: ID3D12CommandQueue =
device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?;
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
list.Close()?;
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let event = CreateEventW(None, false, false, None)?;
Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event })
}
}
fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> {
unsafe {
self.allocator.Reset()?;
self.list.Reset(&self.allocator, None)?;
record(&self.list);
self.list.Close()?;
crate::host::before_send(&self.queue);
self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
self.done += 1;
self.queue.Signal(&self.fence, self.done)?;
self.fence.SetEventOnCompletion(self.done, self.event)?;
if WaitForSingleObject(self.event, 10_000).0 != 0 {
return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL));
}
self.device.GetDeviceRemovedReason()
}
}
fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> {
let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
let mut buffer: Option<ID3D12Resource> = None;
unsafe {
self.device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)?
};
buffer.ok_or_else(windows::core::Error::empty)
}
pub(crate) fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result<Vec<u8>> {
let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?;
self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?;
let mut data = std::ptr::null_mut();
unsafe {
back.Map(0, None, Some(&mut data))?;
let bytes = std::slice::from_raw_parts(data.cast::<u8>(), size).to_vec();
back.Unmap(0, None);
Ok(bytes)
}
}
pub(crate) fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> {
let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?;
let mut data = std::ptr::null_mut();
unsafe {
up.Map(0, None, Some(&mut data))?;
std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len());
up.Unmap(0, None);
}
self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) })
}
fn shade(&mut self, gpu: u64) -> windows::core::Result<()> {
const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n";
let mut code: Option<ID3DBlob> = None;
let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe {
D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?;
let code = code.ok_or_else(windows::core::Error::empty)?;
let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() },
..Default::default()
})?;
(root, pso)
};
self.run(|list| unsafe {
list.SetComputeRootSignature(&root);
list.SetPipelineState(&pso);
list.SetComputeRootUnorderedAccessView(0, gpu);
list.Dispatch(1, 1, 1);
})
}
fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result<f64> {
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let mut to: Option<ID3D12Resource> = None;
unsafe {
self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)?
};
let to = to.ok_or_else(windows::core::Error::empty)?;
let mut best = f64::MAX;
for _ in 0..3 {
let started = std::time::Instant::now();
self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?;
best = best.min(started.elapsed().as_secs_f64() * 1000.0);
}
Ok(best)
}
}
fn fill(at: *mut u8, len: usize, seed: u8) {
for i in 0..len {
unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) };
}
}
fn same(at: *const u8, bytes: &[u8]) -> bool {
unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes }
}
fn working_set_mb() -> u64 {
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() };
unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) };
counters.WorkingSetSize as u64 >> 20
}
#[derive(Default)]
pub(crate) struct Probe {
pub(crate) lines: Vec<String>,
pub(crate) part_reads: bool,
pub(crate) part_writes: bool,
pub(crate) section_reads: bool,
pub(crate) section_writes: bool,
pub(crate) section_outlives_views: bool,
pub(crate) reserved_section_refused: bool,
}
pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe {
let mut p = Probe::default();
let mut rig = match Rig::new(device) {
Ok(rig) => rig,
Err(e) => {
p.lines.push(format!("no queue of its own: {e}"));
return p;
}
};
let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) };
p.lines.push(format!(
"the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}",
device.cast::<ID3D12Device3>().is_ok(),
device.cast::<ID3D12Device13>().is_ok(),
options.CrossAdapterRowMajorTextureSupported.as_bool(),
options.ResourceHeapTier.0
));
unsafe {
private(&mut p, &mut rig);
section(&mut p, &mut rig);
if mb > 0 {
cost(&mut p, &mut rig, memory, mb);
}
}
p.lines.push(format!(
"VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \
a reserved section is refused {} (the pool must be made committed to be opened)",
p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused
));
p
}
fn describe(heap: &ID3D12Heap) -> String {
let d = unsafe { heap.GetDesc() };
format!(
"heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)",
d.SizeInBytes >> 10,
d.Properties.Type.0,
d.Properties.CPUPageProperty.0,
d.Properties.MemoryPoolPreference.0,
d.Alignment,
d.Flags.0
)
}
unsafe fn private(p: &mut Probe, rig: &mut Rig) {
const SIZE: usize = 64 * K64;
unsafe {
let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>();
if base.is_null() {
p.lines.push("private memory: none to try with".to_owned());
return;
}
let (at, bytes) = (base.add(16 * K64), 16 * K64);
let whole = open(&rig.device, From::Region(base as usize));
p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole)));
drop(whole);
let opened = open(&rig.device, From::Part(at as usize, bytes));
p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened)));
if let Ok(heap) = &opened {
p.lines.push(format!(" {}", describe(heap)));
let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64);
p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed)));
if let Ok(buffer) = &placed {
let memory = at.add(K64);
fill(memory, 4 * K64, 1);
let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got));
fill(memory, 4 * K64, 77);
let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got));
p.part_reads = first && second;
p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}"));
mem::ResetWriteWatch(base.cast(), SIZE);
let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect();
let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new);
let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32);
let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0;
memory.cast::<[u32; 3]>().write([40, 2, 0]);
let shaded = rig.shade(buffer.GetGPUVirtualAddress());
let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42;
p.part_writes = copied && shader;
p.lines.push(format!(
" the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \
write watching saw {} of the copy's 16 pages{}",
hr(&shaded),
if watched { count } else { 0 },
if watched { "" } else { " (the asking failed)" }
));
}
let mut old = 0;
let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0;
if protect_in {
mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old);
}
let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
p.lines.push(format!(
" with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \
(false inside means the heap must go before the title frees or guards those pages)"
));
drop(placed);
}
drop(opened);
let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0;
p.lines.push(format!(" released after the heap went: {freed}"));
}
}
unsafe fn section(p: &mut Probe, rig: &mut Rig) {
const SIZE: usize = 32 * K64;
unsafe {
let process = windows_sys::Win32::System::Threading::GetCurrentProcess();
let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null());
if !reserved.is_null() {
let opened = open(&rig.device, From::Section(reserved as usize));
p.reserved_section_refused = opened.is_err();
p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened)));
drop(opened);
windows_sys::Win32::Foundation::CloseHandle(reserved);
}
let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null());
let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::<u8>();
if handle.is_null() || hole.is_null() {
p.lines.push("a committed section: none to try with".to_owned());
return;
}
mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER);
let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0);
let opened = open(&rig.device, From::Section(handle as usize));
p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened)));
let mut unmapped = false;
if let (Ok(heap), false) = (&opened, view.Value.is_null()) {
p.lines.push(format!(" {}", describe(heap)));
let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64);
p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed)));
if let Ok(buffer) = &placed {
let memory = hole.add(K64);
fill(memory, 2 * K64, 3);
p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got));
let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x33).collect();
p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new);
let mut old = 0;
let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0;
let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x44).collect();
let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new);
unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0;
let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x55).collect();
let stored = rig.store(buffer, 0, &new).is_ok();
let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64);
p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new);
p.lines.push(format!(
" the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \
and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}",
p.section_reads, p.section_writes, p.section_outlives_views
));
if !other.Value.is_null() {
mem::UnmapViewOfFile(other);
}
}
}
drop(opened);
if !unmapped && !view.Value.is_null() {
mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER);
}
windows_sys::Win32::Foundation::CloseHandle(handle);
mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE);
mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE);
}
}
unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) {
let bytes = mb << 20;
let shared = || memory().map_or(0, |m| m[3] >> 20);
let ms = |speed: Option<f64>| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}"));
unsafe {
let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>();
if !base.is_null() {
let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now());
let opened = open(&rig.device, From::Part(base as usize, bytes));
let took = started.elapsed().as_secs_f64() * 1000.0;
let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok());
let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok());
p.lines.push(format!(
"cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \
the card copies it out in {} ms",
hr(&opened),
working_set_mb(),
shared(),
ms(speed)
));
drop((placed, opened));
mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
}
let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null());
if !handle.is_null() {
let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now());
let opened = open(&rig.device, From::Section(handle as usize));
let took = started.elapsed().as_secs_f64() * 1000.0;
let (set_opened, account_opened) = (working_set_mb(), shared());
let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok());
let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok());
p.lines.push(format!(
"cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \
shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms",
hr(&opened),
working_set_mb(),
shared(),
ms(speed)
));
drop((placed, opened));
windows_sys::Win32::Foundation::CloseHandle(handle);
}
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
};
let mut buffer: Option<ID3D12Resource> = None;
let made = rig.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
&buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COMMON,
None,
&mut buffer,
);
if let (Ok(()), Some(buffer)) = (made, buffer) {
let speed = rig.copy_ms(&buffer, bytes as u64).ok();
p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed)));
}
}
}
#[derive(Default, Clone, Copy)]
struct Tally([(u64, u64); 6]);
const KINDS: [&str; 6] = [
"private, committed whole (a part can be opened)",
"view memory, one run of a section (one placed buffer)",
"view memory, scattered pages",
"view memory with unmapped pages",
"private but not committed whole, or guarded",
"other",
];
fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize {
match cover(at, len) {
Cover::Run(..) => return 1,
Cover::Scattered => return 2,
Cover::Holes => return 3,
Cover::None => {}
}
let end = at + len;
if known.iter().any(|&(from, to)| from <= at && end <= to) {
return 0;
}
let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) };
if n == 0 {
return 5;
}
let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize);
if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE {
known.push((info.BaseAddress as usize, reach));
return if reach >= end { 0 } else { 4 };
}
match info.Type {
mem::MEM_PRIVATE => 4,
mem::MEM_MAPPED => 3,
_ => 5,
}
}
fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> {
let mut known = Vec::new();
let (mut buffers, mut windows) = (Tally::default(), Tally::default());
for &(start, len, window) in spans {
let kind = kind_of(start as usize, len as usize, &mut known);
let tally = if window { &mut windows } else { &mut buffers };
tally.0[kind].0 += 1;
tally.0[kind].1 += len;
}
let mut lines = Vec::new();
for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] {
let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1));
lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20));
for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) {
if n > 0 {
lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20));
}
}
}
let v = views();
let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::<u64>());
let pages = v.views.values().filter(|view| view.0 == K64).count();
let big = v.views.values().map(|view| view.0).max().unwrap_or(0);
lines.push(format!(
"census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB",
bytes >> 20,
big >> 20
));
for &(_, bytes, native_importable, _) in &v.sections {
lines.push(format!(
"census, a section of {} MB, {}",
bytes >> 20,
if native_importable {
"eligible to be opened as one native heap"
} else {
"excluded from native heap imports by its backing"
}
));
}
lines
}
fn real_part(spans: &[(u64, u64, bool)]) -> Vec<String> {
let Some(host) = crate::host::host() else {
return Vec::new();
};
let mut known = Vec::new();
let found = spans
.iter()
.filter(|s| !s.2 && s.1 >= 2 * K64 as u64)
.filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0)
.max_by_key(|s| s.1);
let Some(&(start, len, _)) = found else {
return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()];
};
let at = (start as usize).next_multiple_of(K64);
let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1);
if bytes == 0 || !private_whole(at, bytes) {
return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()];
}
let mut lines = Vec::new();
let (set, started) = (working_set_mb(), std::time::Instant::now());
let opened = open(&host.device, From::Part(at, bytes));
lines.push(format!(
"the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB",
bytes >> 10,
hr(&opened),
started.elapsed().as_secs_f64() * 1000.0,
working_set_mb()
));
if let Ok(heap) = &opened {
let placed = place(&host.device, heap, 0, bytes as u64);
lines.push(format!(" a buffer placed over it: {}", hr(&placed)));
if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) {
let mut before = vec![0u8; K64];
crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false);
let got = rig.fetch(buffer, 0, K64);
let mut after = vec![0u8; K64];
crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false);
match got {
Ok(got) => {
let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count();
let zeros = got.iter().filter(|&&b| b == 0).count();
lines.push(format!(
" the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)"
));
}
Err(e) => lines.push(format!(" the GPU's read failed: {e}")),
}
}
}
lines
}
pub(crate) fn tick() {
if level() > 0 {
say();
}
if probe_level() == 0 {
return;
}
static STARTED: AtomicU64 = AtomicU64::new(0);
static DONE: AtomicU64 = AtomicU64::new(0);
let now = crate::host::now_ms().max(1);
let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => {
let Some(host) = crate::host::host() else {
return;
};
let mb = std::env::var("EONACAT_XS_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize);
let took = std::time::Instant::now();
let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024));
for line in &probe.lines {
tracing::info!("in place probe: {line}");
}
tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0);
now
}
Err(started) => started,
};
let due = match DONE.load(Ordering::Relaxed) {
0 => now >= started + 30_000,
1 => now >= started + 150_000,
_ => false,
};
if due {
let which = DONE.fetch_add(1, Ordering::Relaxed);
std::thread::spawn(move || {
let spans = crate::shadow::spans();
for line in census_of(&spans) {
tracing::info!("in place {line}");
}
if which == 0 && probe_level() >= 2 {
for line in real_part(&spans) {
tracing::info!("in place probe: {line}");
}
}
});
}
}