2
0

inplace.rs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. //! Title memory as the card's own memory: a host heap opened on memory
  2. //! the title already has, and a buffer placed in it, so that shaders read
  3. //! and write the title's bytes themselves and no host copy stands between
  4. //! (the console's one memory). This file holds the two openings Direct3D
  5. //! has, a probe that says what this PC's driver makes of them
  6. //! (`VICTORY_INPLACE_PROBE`), and a census of which title memory could be
  7. //! opened.
  8. //!
  9. //! What the Direct3D runtime and the kernel answer, measured on this PC
  10. //! with the software adapter (the rules are theirs, not the adapter's;
  11. //! what the card's driver adds is what the probe is for):
  12. //!
  13. //! - `OpenExistingHeapFromAddress` takes the base address of a whole
  14. //! `VirtualAlloc` allocation and nothing inside it; every page must be
  15. //! committed and have one protection. Opening locks every page into the
  16. //! PC's memory at once (256 MiB never touched: 70 ms and 256 MB of
  17. //! working set).
  18. //! - `OpenExistingHeapFromAddress1` (`ID3D12Device13`) takes any committed
  19. //! part of an allocation, with the same rule for its pages; parts may
  20. //! overlap, and the whole may be opened beside them. It also takes a
  21. //! committed view of a section.
  22. //! - `OpenExistingHeapFromFileMapping` takes a section made with
  23. //! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem`
  24. //! makes the title's page pool today). The heap is the section, not a
  25. //! view of it: views may be unmapped, mapped elsewhere or made
  26. //! read-only, and the section's handle closed, with the heap alive.
  27. //! Opening it locks nothing (256 MiB: 0.2 ms, no working set).
  28. //! - The heap is a custom heap in the PC's memory (write-back pages, pool
  29. //! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it
  30. //! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken.
  31. //! A texture must be row-major with one level. Tile mappings into such
  32. //! a heap are refused and REMOVE THE DEVICE: never call them.
  33. //! - While a heap opened from an address stands, the title cannot
  34. //! decommit, release or protect the pages in it (`VirtualFree` and
  35. //! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages
  36. //! outside the opened part are free to change.
  37. use std::collections::BTreeMap;
  38. use std::ffi::c_void;
  39. use std::sync::Mutex;
  40. use std::sync::atomic::{AtomicU64, Ordering};
  41. use windows::Win32::Foundation::HANDLE;
  42. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  43. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  44. use windows::Win32::Graphics::Direct3D12::*;
  45. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  46. use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
  47. use windows::core::{Interface, s};
  48. use windows_sys::Win32::System::Memory as mem;
  49. /// The unit heaps and placed buffers are cut on, and the console's page.
  50. const K64: usize = 64 << 10;
  51. /// The host's write watching (not in windows-sys' memory module).
  52. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  53. /// `VICTORY_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of
  54. /// its own at the first sweep, and the census 30 and 150 seconds later;
  55. /// 2 also opens one part of the title's own memory for a moment at the
  56. /// first census.
  57. pub(crate) fn probe_level() -> u8 {
  58. static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  59. *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
  60. }
  61. /// `VICTORY_INPLACE`: 0 (unset) off. 1: a window of title memory outside
  62. /// buffers that lies in private memory committed whole is not copied: a
  63. /// part of the title's allocation is opened as a host heap and the window
  64. /// is a buffer placed over it ([`place_for`]). 2: title buffers too,
  65. /// except the big ones in the card's memory.
  66. ///
  67. /// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View
  68. /// memory (the page pool) is turned down here: its section is made
  69. /// reserved, which the host refuses, and what a view shows changes when
  70. /// the title maps pages.
  71. ///
  72. /// What it assumes, for 2: nothing reads title memory that a submission
  73. /// not yet run writes through such a buffer. With every submission waited
  74. /// for (the default) that holds; with `VICTORY_LATE_WAIT` it does not,
  75. /// since the flights' rules know shader writes only by the ranges copies
  76. /// declare. Do not combine 2 with late wait.
  77. ///
  78. /// shortcut: while a window is in place the title cannot decommit, free
  79. /// or protect its pages (the call fails with error 87; the probe shows
  80. /// it). The title's heaps are allocated once and kept, and nothing of the
  81. /// kind was seen; [`title_memory_freeing`] is there for the runtime to
  82. /// call before such a call once it takes them over.
  83. pub(crate) fn level() -> u8 {
  84. static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  85. *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0))
  86. }
  87. /// The most title memory in place at once, in bytes
  88. /// (`VICTORY_INPLACE_MB`, 4096): opening locks the pages into the PC's
  89. /// memory, also those the title never touched.
  90. fn most() -> u64 {
  91. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  92. *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(4096) << 20)
  93. }
  94. /// In place now: windows and their bytes, title buffers and their bytes;
  95. /// then, since the start: asks turned down because the memory is a view
  96. /// or not private memory committed whole, because the host refused,
  97. /// because of [`most`]; and what was let go because its memory changed.
  98. static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
  99. /// A buffer placed over title memory, and its heap.
  100. pub(crate) struct Placed {
  101. pub(crate) buffer: ID3D12Resource,
  102. pub(crate) heap: ID3D12Heap,
  103. /// The host GPU address of the title memory's first byte.
  104. pub(crate) gpu: u64,
  105. /// Bytes from the buffer's first byte to the title memory's first.
  106. pub(crate) bias: u64,
  107. }
  108. /// Opens the 64 KiB pages that hold title memory `[start, start + len)`
  109. /// as a heap of their own and places one buffer over all of them. `Err`
  110. /// with nothing if the memory is not private memory committed whole
  111. /// (nothing was asked of the host), with the host's error if it refused.
  112. pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> {
  113. let at = start & !(K64 as u64 - 1);
  114. let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at;
  115. if !private_whole(at as usize, bytes as usize) {
  116. return Err(None);
  117. }
  118. let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?;
  119. let buffer = place(device, &heap, 0, bytes).map_err(Some)?;
  120. // SAFETY: a live buffer.
  121. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at);
  122. Ok(Placed { buffer, heap, gpu, bias: start - at })
  123. }
  124. /// Title memory `[start, start + len)` in place, for a window outside
  125. /// buffers or a title buffer, if [`level`] asks for it and the memory can
  126. /// be opened; `None` leaves the caller to make a copy, as before.
  127. pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> {
  128. if level() < if window { 1 } else { 2 } {
  129. return None;
  130. }
  131. // View memory: known from the runtime without asking Windows.
  132. if cover(start as usize, len as usize) != Cover::None {
  133. STATS[4].fetch_add(1, Ordering::Relaxed);
  134. return None;
  135. }
  136. if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() {
  137. STATS[6].fetch_add(1, Ordering::Relaxed);
  138. return None;
  139. }
  140. let host = crate::host::host()?;
  141. match place_part(&host.device, start, len) {
  142. Ok(placed) => {
  143. let at = if window { 0 } else { 2 };
  144. STATS[at].fetch_add(1, Ordering::Relaxed);
  145. STATS[at + 1].fetch_add(len, Ordering::Relaxed);
  146. Some(placed)
  147. }
  148. Err(None) => {
  149. STATS[4].fetch_add(1, Ordering::Relaxed);
  150. None
  151. }
  152. Err(Some(e)) => {
  153. if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 {
  154. tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead");
  155. }
  156. None
  157. }
  158. }
  159. }
  160. /// What [`place_for`] gave is gone.
  161. pub(crate) fn gone(window: bool, bytes: u64) {
  162. let at = if window { 0 } else { 2 };
  163. STATS[at].fetch_sub(1, Ordering::Relaxed);
  164. STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed);
  165. }
  166. /// Title memory `[at, at + len)` is about to show something else, or the
  167. /// title is about to decommit, free or protect it: what is in place there
  168. /// is let go (the tables forget it; its heap goes when the last list and
  169. /// slot that hold it do). Called for memory the runtime maps anew; for
  170. /// the runtime to call before the title's own `VirtualFree` once it takes
  171. /// that call over.
  172. pub fn title_memory_freeing(at: usize, len: usize) {
  173. if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 {
  174. return;
  175. }
  176. let gone = crate::shadow::in_place_let_go(at as u64, len as u64);
  177. STATS[7].fetch_add(gone, Ordering::Relaxed);
  178. }
  179. /// The line of what is in place, every ten seconds while [`level`] is on.
  180. fn say() {
  181. static LAST: AtomicU64 = AtomicU64::new(0);
  182. let now = crate::host::now_ms();
  183. let last = LAST.load(Ordering::Relaxed);
  184. if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() {
  185. return;
  186. }
  187. let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect();
  188. tracing::info!(
  189. "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \
  190. {} refused by the host, {} over VICTORY_INPLACE_MB; {} let go because their memory changed",
  191. s[0],
  192. s[1] >> 20,
  193. s[2],
  194. s[3] >> 20,
  195. s[4],
  196. s[5],
  197. s[6],
  198. s[7]
  199. );
  200. }
  201. /// What a heap is opened on.
  202. pub(crate) enum From {
  203. /// A whole `VirtualAlloc` allocation, by its base address.
  204. Region(usize),
  205. /// A committed part of one: address and bytes.
  206. Part(usize, usize),
  207. /// A section made with `SEC_COMMIT`, by its handle.
  208. Section(usize),
  209. }
  210. /// Opens a heap on memory the process has.
  211. pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result<ID3D12Heap> {
  212. // SAFETY: the calls take an address or a handle and check both
  213. // themselves; a refusal is an error code.
  214. unsafe {
  215. match from {
  216. From::Region(at) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void),
  217. From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes),
  218. From::Section(handle) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)),
  219. }
  220. }
  221. }
  222. fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
  223. D3D12_RESOURCE_DESC {
  224. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  225. Width: size.max(1),
  226. Height: 1,
  227. DepthOrArraySize: 1,
  228. MipLevels: 1,
  229. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  230. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  231. Flags: flags,
  232. ..Default::default()
  233. }
  234. }
  235. /// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an
  236. /// opened heap, which shaders may read and write, in the common state.
  237. pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> {
  238. let mut placed: Option<ID3D12Resource> = None;
  239. // The heap is cross-adapter shared, so the buffer must say so too.
  240. let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  241. // SAFETY: plain creation in a live heap.
  242. unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? };
  243. placed.ok_or_else(windows::core::Error::empty)
  244. }
  245. // The title's views of its physical pages, as the runtime maps them: the
  246. // census needs them to say which view memory is one run of a section (one
  247. // placed buffer could show it) and which is scattered pages.
  248. struct Views {
  249. /// By address: bytes, the section's handle, the offset in it.
  250. views: BTreeMap<usize, (usize, usize, u64)>,
  251. /// Sections by handle: bytes, and whether made committed.
  252. sections: Vec<(usize, u64, bool)>,
  253. /// Our own view of a whole section, by its handle (0: the host gave
  254. /// none), made when first asked for ([`beside`]) and kept.
  255. whole: Vec<(usize, usize)>,
  256. }
  257. static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() });
  258. fn views() -> std::sync::MutexGuard<'static, Views> {
  259. VIEWS.lock().unwrap_or_else(|e| e.into_inner())
  260. }
  261. /// The runtime made a section of `bytes` for physical pages; `committed`
  262. /// if with `SEC_COMMIT` (only such a section can be opened as a heap).
  263. pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
  264. let mut v = views();
  265. v.sections.retain(|s| s.0 != section);
  266. // A handle's number given out again: the view was of the section that
  267. // had it before (it stays mapped: someone may be writing through it).
  268. v.whole.retain(|w| w.0 != section);
  269. v.sections.push((section, bytes, committed));
  270. }
  271. /// The runtime lets go of a section, and of its handle: no view the title
  272. /// sees is of it any more, and [`beside`]'s view goes.
  273. pub fn title_memory_section_gone(section: usize) {
  274. let whole = {
  275. let mut v = views();
  276. let at = v.whole.iter().position(|w| w.0 == section);
  277. at.map(|i| v.whole.swap_remove(i).1)
  278. };
  279. if let Some(base) = whole.filter(|&base| base != 0) {
  280. // SAFETY: a view of ours. Who writes through it found the section
  281. // in a view the title saw and holds off its unmapping
  282. // (`crate::watch::title_memory_reading`), which came before this.
  283. unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) };
  284. }
  285. }
  286. /// The runtime mapped `[at, at + len)` as a view of `section` from
  287. /// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
  288. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
  289. views().views.insert(at, (len, section, offset));
  290. }
  291. /// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]):
  292. /// the views that touch it are forgotten (the runtime tells again those it
  293. /// maps anew).
  294. pub(crate) fn views_gone(at: usize, len: usize) {
  295. let mut v = views();
  296. if v.views.is_empty() {
  297. return;
  298. }
  299. let end = at.saturating_add(len);
  300. let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base);
  301. let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect();
  302. for base in gone {
  303. v.views.remove(&base);
  304. }
  305. }
  306. /// How the views cover `[at, at + len)`.
  307. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  308. pub(crate) enum Cover {
  309. /// No view holds its first byte.
  310. None,
  311. /// Views hold a part of it only.
  312. Holes,
  313. /// Views hold all of it, from more than one place.
  314. Scattered,
  315. /// All of it is one run of one section: the section and the offset of
  316. /// `at` in it.
  317. Run(usize, u64),
  318. }
  319. fn cover_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Cover {
  320. let end = at + len.max(1);
  321. let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else {
  322. return Cover::None;
  323. };
  324. let first = (section, offset + (at - base) as u64);
  325. let (mut reached, mut one) = (base + bytes, true);
  326. while reached < end {
  327. let Some(&(bytes, s, o)) = views.get(&reached) else {
  328. return Cover::Holes;
  329. };
  330. one &= s == first.0 && o == first.1 + (reached - at) as u64;
  331. reached += bytes;
  332. }
  333. if one { Cover::Run(first.0, first.1) } else { Cover::Scattered }
  334. }
  335. /// [`Cover`] of `[at, at + len)` by the title's views as they are now.
  336. pub(crate) fn cover(at: usize, len: usize) -> Cover {
  337. cover_in(&views().views, at, len)
  338. }
  339. /// Another address of the title memory `[at, at + len)`, if it is a view of
  340. /// the title's pages, all of it one run of a section: in a view of ours of
  341. /// the whole section, which is never guarded (`crate::watch`) nor changed.
  342. ///
  343. /// The section's pages are reserved and the runtime commits each before it
  344. /// shows it, which holds for every view of the section. The caller holds
  345. /// `crate::watch::title_memory_reading`: until it lets go the title sees
  346. /// the same pages at `at`.
  347. pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
  348. let mut v = views();
  349. let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
  350. return None;
  351. };
  352. let base = match v.whole.iter().find(|w| w.0 == section) {
  353. Some(w) => w.1,
  354. None => {
  355. let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?;
  356. // SAFETY: the whole of a section the runtime made; a view the
  357. // title sees is of it, so its handle is open.
  358. let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize;
  359. if base == 0 {
  360. tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own");
  361. }
  362. v.whole.push((section, base));
  363. base
  364. }
  365. };
  366. (base != 0).then(|| base + offset as usize)
  367. }
  368. /// Whether `[at, at + len)` is private memory, all committed and
  369. /// read-write: what [`From::Part`] takes. One question to Windows (it
  370. /// walks the page tables to the end of the pages that share the first
  371. /// one's state: a millisecond in the title's big blocks, so ask when a
  372. /// copy is made, not when it is used).
  373. pub(crate) fn private_whole(at: usize, len: usize) -> bool {
  374. // SAFETY: plain data filled in by the query.
  375. let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  376. // SAFETY: a valid out pointer of the right size.
  377. let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) };
  378. n != 0
  379. && info.State == mem::MEM_COMMIT
  380. && info.Type == mem::MEM_PRIVATE
  381. && info.Protect == mem::PAGE_READWRITE
  382. && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len)
  383. }
  384. fn hr<T>(result: &windows::core::Result<T>) -> String {
  385. match result {
  386. Ok(_) => "ok".to_owned(),
  387. Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()),
  388. }
  389. }
  390. /// A queue, a list and a fence of the probe's own on `device`: nothing of
  391. /// the host's submissions is touched.
  392. struct Rig {
  393. device: ID3D12Device,
  394. queue: ID3D12CommandQueue,
  395. allocator: ID3D12CommandAllocator,
  396. list: ID3D12GraphicsCommandList,
  397. fence: ID3D12Fence,
  398. done: u64,
  399. event: HANDLE,
  400. }
  401. impl Drop for Rig {
  402. fn drop(&mut self) {
  403. // SAFETY: our event.
  404. unsafe {
  405. let _ = windows::Win32::Foundation::CloseHandle(self.event);
  406. }
  407. }
  408. }
  409. impl Rig {
  410. fn new(device: &ID3D12Device) -> windows::core::Result<Rig> {
  411. // SAFETY: plain creation of objects of our own.
  412. unsafe {
  413. let queue: ID3D12CommandQueue =
  414. device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?;
  415. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  416. let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  417. list.Close()?;
  418. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  419. let event = CreateEventW(None, false, false, None)?;
  420. Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event })
  421. }
  422. }
  423. /// Records with `record`, runs it and waits (ten seconds at most).
  424. fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> {
  425. // SAFETY: our own list and queue, one run at a time.
  426. unsafe {
  427. self.allocator.Reset()?;
  428. self.list.Reset(&self.allocator, None)?;
  429. record(&self.list);
  430. self.list.Close()?;
  431. self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
  432. self.done += 1;
  433. self.queue.Signal(&self.fence, self.done)?;
  434. self.fence.SetEventOnCompletion(self.done, self.event)?;
  435. if WaitForSingleObject(self.event, 10_000).0 != 0 {
  436. return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL));
  437. }
  438. self.device.GetDeviceRemovedReason()
  439. }
  440. }
  441. fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> {
  442. let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
  443. let mut buffer: Option<ID3D12Resource> = None;
  444. // SAFETY: plain creation.
  445. unsafe {
  446. self.device
  447. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)?
  448. };
  449. buffer.ok_or_else(windows::core::Error::empty)
  450. }
  451. /// What the GPU reads of `size` bytes of `resource` from `offset`.
  452. fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result<Vec<u8>> {
  453. let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?;
  454. // SAFETY: two live buffers, the range inside both.
  455. self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?;
  456. let mut data = std::ptr::null_mut();
  457. // SAFETY: the mapping holds `size` bytes until unmapped.
  458. unsafe {
  459. back.Map(0, None, Some(&mut data))?;
  460. let bytes = std::slice::from_raw_parts(data.cast::<u8>(), size).to_vec();
  461. back.Unmap(0, None);
  462. Ok(bytes)
  463. }
  464. }
  465. /// The GPU writes `bytes` at `offset` of `resource` (a copy).
  466. fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> {
  467. let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?;
  468. let mut data = std::ptr::null_mut();
  469. // SAFETY: the mapping holds the buffer's bytes until unmapped.
  470. unsafe {
  471. up.Map(0, None, Some(&mut data))?;
  472. std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len());
  473. up.Unmap(0, None);
  474. }
  475. // SAFETY: two live buffers, the range inside both.
  476. self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) })
  477. }
  478. /// A compute shader stores, through a root unordered-access view at
  479. /// `gpu`, the sum of the buffer's first two words in its third.
  480. fn shade(&mut self, gpu: u64) -> windows::core::Result<()> {
  481. 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";
  482. let mut code: Option<ID3DBlob> = None;
  483. // SAFETY: the source and names live through the call; then the
  484. // blob's own bytes, which hold the root signature too.
  485. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe {
  486. D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?;
  487. let code = code.ok_or_else(windows::core::Error::empty)?;
  488. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  489. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  490. let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  491. pRootSignature: std::mem::transmute_copy(&root),
  492. CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() },
  493. ..Default::default()
  494. })?;
  495. (root, pso)
  496. };
  497. // SAFETY: an open list of ours; the view names a live buffer.
  498. self.run(|list| unsafe {
  499. list.SetComputeRootSignature(&root);
  500. list.SetPipelineState(&pso);
  501. list.SetComputeRootUnorderedAccessView(0, gpu);
  502. list.Dispatch(1, 1, 1);
  503. })
  504. }
  505. /// Milliseconds the card takes to copy `bytes` of `from` into its own
  506. /// memory, the best of three.
  507. fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result<f64> {
  508. let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
  509. let mut to: Option<ID3D12Resource> = None;
  510. // SAFETY: plain creation.
  511. unsafe {
  512. self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)?
  513. };
  514. let to = to.ok_or_else(windows::core::Error::empty)?;
  515. let mut best = f64::MAX;
  516. for _ in 0..3 {
  517. let started = std::time::Instant::now();
  518. // SAFETY: two live buffers of `bytes` bytes or more.
  519. self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?;
  520. best = best.min(started.elapsed().as_secs_f64() * 1000.0);
  521. }
  522. Ok(best)
  523. }
  524. }
  525. fn fill(at: *mut u8, len: usize, seed: u8) {
  526. for i in 0..len {
  527. // SAFETY: the caller's own committed memory of `len` bytes.
  528. unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) };
  529. }
  530. }
  531. fn same(at: *const u8, bytes: &[u8]) -> bool {
  532. // SAFETY: the caller's own committed memory of that length.
  533. unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes }
  534. }
  535. /// The process's working set in MB.
  536. fn working_set_mb() -> u64 {
  537. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  538. let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() };
  539. // SAFETY: our own process and a sized structure.
  540. unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) };
  541. counters.WorkingSetSize as u64 >> 20
  542. }
  543. /// What the probe found. The lines are the whole account; the flags are
  544. /// what the stages build on.
  545. #[derive(Default)]
  546. pub(crate) struct Probe {
  547. pub(crate) lines: Vec<String>,
  548. /// A part of private, write-watched memory opens, a buffer in it shows
  549. /// the memory's bytes to the GPU, also those the CPU wrote afterwards.
  550. pub(crate) part_reads: bool,
  551. /// What the GPU writes there (a copy, and a shader through unordered
  552. /// access) the CPU reads at the memory's address.
  553. pub(crate) part_writes: bool,
  554. /// The same two for a committed section, through a view of it.
  555. pub(crate) section_reads: bool,
  556. pub(crate) section_writes: bool,
  557. /// The section's heap outlives the view: the GPU's write with no view
  558. /// mapped shows in a view mapped afterwards.
  559. pub(crate) section_outlives_views: bool,
  560. /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool)
  561. /// was refused.
  562. pub(crate) reserved_section_refused: bool,
  563. }
  564. /// Tries the openings on memory of the probe's own, made the way `xmem`
  565. /// makes title memory, with a queue of its own on `device`; `memory`
  566. /// gives the card's memory account (`Host::video_memory`) where there is
  567. /// one. Nothing of the title's is touched. `mb` is the size of the cost
  568. /// measurement (0 leaves it out).
  569. pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe {
  570. let mut p = Probe::default();
  571. let mut rig = match Rig::new(device) {
  572. Ok(rig) => rig,
  573. Err(e) => {
  574. p.lines.push(format!("no queue of its own: {e}"));
  575. return p;
  576. }
  577. };
  578. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
  579. // SAFETY: a plain query that fills our structure.
  580. let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) };
  581. p.lines.push(format!(
  582. "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}",
  583. device.cast::<ID3D12Device3>().is_ok(),
  584. device.cast::<ID3D12Device13>().is_ok(),
  585. options.CrossAdapterRowMajorTextureSupported.as_bool(),
  586. options.ResourceHeapTier.0
  587. ));
  588. // SAFETY: memory of the probe's own, made and released here; every
  589. // address used lies inside it.
  590. unsafe {
  591. private(&mut p, &mut rig);
  592. section(&mut p, &mut rig);
  593. if mb > 0 {
  594. cost(&mut p, &mut rig, memory, mb);
  595. }
  596. }
  597. p.lines.push(format!(
  598. "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \
  599. a reserved section is refused {} (the pool must be made committed to be opened)",
  600. p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused
  601. ));
  602. p
  603. }
  604. fn describe(heap: &ID3D12Heap) -> String {
  605. // SAFETY: a plain query.
  606. let d = unsafe { heap.GetDesc() };
  607. format!(
  608. "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)",
  609. d.SizeInBytes >> 10,
  610. d.Properties.Type.0,
  611. d.Properties.CPUPageProperty.0,
  612. d.Properties.MemoryPoolPreference.0,
  613. d.Alignment,
  614. d.Flags.0
  615. )
  616. }
  617. /// Private memory, reserved as `xmem` reserves the title's heaps
  618. /// (committed, read-write, write-watched): a part of it opened.
  619. unsafe fn private(p: &mut Probe, rig: &mut Rig) {
  620. const SIZE: usize = 64 * K64;
  621. // SAFETY (the whole function): the allocation below, `SIZE` bytes.
  622. unsafe {
  623. let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>();
  624. if base.is_null() {
  625. p.lines.push("private memory: none to try with".to_owned());
  626. return;
  627. }
  628. // The part: 16 pages from the 16th on.
  629. let (at, bytes) = (base.add(16 * K64), 16 * K64);
  630. let whole = open(&rig.device, From::Region(base as usize));
  631. p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole)));
  632. drop(whole);
  633. let opened = open(&rig.device, From::Part(at as usize, bytes));
  634. p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened)));
  635. if let Ok(heap) = &opened {
  636. p.lines.push(format!(" {}", describe(heap)));
  637. let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64);
  638. p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed)));
  639. if let Ok(buffer) = &placed {
  640. let memory = at.add(K64);
  641. fill(memory, 4 * K64, 1);
  642. let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got));
  643. fill(memory, 4 * K64, 77);
  644. let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got));
  645. p.part_reads = first && second;
  646. p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}"));
  647. mem::ResetWriteWatch(base.cast(), SIZE);
  648. let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect();
  649. let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new);
  650. let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32);
  651. let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0;
  652. memory.cast::<[u32; 3]>().write([40, 2, 0]);
  653. let shaded = rig.shade(buffer.GetGPUVirtualAddress());
  654. let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42;
  655. p.part_writes = copied && shader;
  656. p.lines.push(format!(
  657. " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \
  658. write watching saw {} of the copy's 16 pages{}",
  659. hr(&shaded),
  660. if watched { count } else { 0 },
  661. if watched { "" } else { " (the asking failed)" }
  662. ));
  663. }
  664. // What the title can still do with the pages while the heap stands.
  665. let mut old = 0;
  666. let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0;
  667. if protect_in {
  668. mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old);
  669. }
  670. let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
  671. let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
  672. p.lines.push(format!(
  673. " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \
  674. (false inside means the heap must go before the title frees or guards those pages)"
  675. ));
  676. drop(placed);
  677. }
  678. drop(opened);
  679. let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0;
  680. p.lines.push(format!(" released after the heap went: {freed}"));
  681. }
  682. }
  683. /// A section and a view of it in a placeholder, as `xmem` maps physical
  684. /// pages: reserved (as it is made today) and committed.
  685. unsafe fn section(p: &mut Probe, rig: &mut Rig) {
  686. const SIZE: usize = 32 * K64;
  687. // SAFETY (the whole function): the sections, placeholder and views
  688. // made below.
  689. unsafe {
  690. let process = windows_sys::Win32::System::Threading::GetCurrentProcess();
  691. let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
  692. let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null());
  693. if !reserved.is_null() {
  694. let opened = open(&rig.device, From::Section(reserved as usize));
  695. p.reserved_section_refused = opened.is_err();
  696. p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened)));
  697. drop(opened);
  698. windows_sys::Win32::Foundation::CloseHandle(reserved);
  699. }
  700. let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null());
  701. 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>();
  702. if handle.is_null() || hole.is_null() {
  703. p.lines.push("a committed section: none to try with".to_owned());
  704. return;
  705. }
  706. // Pages 4..12 of the section at the placeholder's start.
  707. mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER);
  708. 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);
  709. let opened = open(&rig.device, From::Section(handle as usize));
  710. p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened)));
  711. let mut unmapped = false;
  712. if let (Ok(heap), false) = (&opened, view.Value.is_null()) {
  713. p.lines.push(format!(" {}", describe(heap)));
  714. // The section's page 5 is the view's second page.
  715. let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64);
  716. p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed)));
  717. if let Ok(buffer) = &placed {
  718. let memory = hole.add(K64);
  719. fill(memory, 2 * K64, 3);
  720. p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got));
  721. let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x33).collect();
  722. p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new);
  723. // The guard of `watch.rs`: the view read-only.
  724. let mut old = 0;
  725. let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0;
  726. let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x44).collect();
  727. let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new);
  728. // The view goes; the GPU writes; another view shows it.
  729. unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0;
  730. let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x55).collect();
  731. let stored = rig.store(buffer, 0, &new).is_ok();
  732. let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64);
  733. p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new);
  734. p.lines.push(format!(
  735. " 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}, \
  736. 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 {}",
  737. p.section_reads, p.section_writes, p.section_outlives_views
  738. ));
  739. if !other.Value.is_null() {
  740. mem::UnmapViewOfFile(other);
  741. }
  742. }
  743. }
  744. drop(opened);
  745. if !unmapped && !view.Value.is_null() {
  746. mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER);
  747. }
  748. windows_sys::Win32::Foundation::CloseHandle(handle);
  749. // The placeholder was split in two: each half is released.
  750. mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE);
  751. mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE);
  752. }
  753. }
  754. /// What opening costs, on `mb` MB each of private memory never touched
  755. /// and of a committed section never touched: the time, the working set,
  756. /// the card's account of the PC's memory shared with it; and how fast the
  757. /// card copies out of such a heap against a shared buffer of today's kind.
  758. unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) {
  759. let bytes = mb << 20;
  760. let shared = || memory().map_or(0, |m| m[3] >> 20);
  761. let ms = |speed: Option<f64>| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}"));
  762. // SAFETY (the whole function): the allocation and the section below.
  763. unsafe {
  764. let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>();
  765. if !base.is_null() {
  766. let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now());
  767. let opened = open(&rig.device, From::Part(base as usize, bytes));
  768. let took = started.elapsed().as_secs_f64() * 1000.0;
  769. let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok());
  770. let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok());
  771. p.lines.push(format!(
  772. "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \
  773. the card copies it out in {} ms",
  774. hr(&opened),
  775. working_set_mb(),
  776. shared(),
  777. ms(speed)
  778. ));
  779. drop((placed, opened));
  780. mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
  781. }
  782. let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
  783. 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());
  784. if !handle.is_null() {
  785. let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now());
  786. let opened = open(&rig.device, From::Section(handle as usize));
  787. let took = started.elapsed().as_secs_f64() * 1000.0;
  788. let (set_opened, account_opened) = (working_set_mb(), shared());
  789. let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok());
  790. let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok());
  791. p.lines.push(format!(
  792. "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; \
  793. shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms",
  794. hr(&opened),
  795. working_set_mb(),
  796. shared(),
  797. ms(speed)
  798. ));
  799. drop((placed, opened));
  800. windows_sys::Win32::Foundation::CloseHandle(handle);
  801. }
  802. // Today's kind of host copy, for the comparison.
  803. let heap = D3D12_HEAP_PROPERTIES {
  804. Type: D3D12_HEAP_TYPE_CUSTOM,
  805. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  806. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  807. ..Default::default()
  808. };
  809. let mut buffer: Option<ID3D12Resource> = None;
  810. let made = rig.device.CreateCommittedResource(
  811. &heap,
  812. D3D12_HEAP_FLAG_NONE,
  813. &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
  814. D3D12_RESOURCE_STATE_COMMON,
  815. None,
  816. &mut buffer,
  817. );
  818. if let (Ok(()), Some(buffer)) = (made, buffer) {
  819. let speed = rig.copy_ms(&buffer, bytes as u64).ok();
  820. 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)));
  821. }
  822. }
  823. }
  824. // The census: which of the title memory that has host copies today could
  825. // be opened, and by which opening.
  826. /// Counts and bytes by kind, in the order of [`KINDS`].
  827. #[derive(Default, Clone, Copy)]
  828. struct Tally([(u64, u64); 6]);
  829. const KINDS: [&str; 6] = [
  830. "private, committed whole (a part can be opened)",
  831. "view memory, one run of a section (one placed buffer)",
  832. "view memory, scattered pages",
  833. "view memory with unmapped pages",
  834. "private but not committed whole, or guarded",
  835. "other",
  836. ];
  837. fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize {
  838. match cover(at, len) {
  839. Cover::Run(..) => return 1,
  840. Cover::Scattered => return 2,
  841. Cover::Holes => return 3,
  842. Cover::None => {}
  843. }
  844. let end = at + len;
  845. if known.iter().any(|&(from, to)| from <= at && end <= to) {
  846. return 0;
  847. }
  848. // SAFETY: plain data filled in by the query.
  849. let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  850. // SAFETY: a valid out pointer of the right size.
  851. let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) };
  852. if n == 0 {
  853. return 5;
  854. }
  855. let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize);
  856. if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE {
  857. known.push((info.BaseAddress as usize, reach));
  858. return if reach >= end { 0 } else { 4 };
  859. }
  860. match info.Type {
  861. mem::MEM_PRIVATE => 4,
  862. mem::MEM_MAPPED => 3,
  863. _ => 5,
  864. }
  865. }
  866. /// The census lines for `spans` (start, bytes, whether a window outside
  867. /// buffers).
  868. fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> {
  869. let mut known = Vec::new();
  870. let (mut buffers, mut windows) = (Tally::default(), Tally::default());
  871. for &(start, len, window) in spans {
  872. let kind = kind_of(start as usize, len as usize, &mut known);
  873. let tally = if window { &mut windows } else { &mut buffers };
  874. tally.0[kind].0 += 1;
  875. tally.0[kind].1 += len;
  876. }
  877. let mut lines = Vec::new();
  878. for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] {
  879. let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1));
  880. lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20));
  881. for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) {
  882. if n > 0 {
  883. lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20));
  884. }
  885. }
  886. }
  887. let v = views();
  888. let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::<u64>());
  889. let pages = v.views.values().filter(|view| view.0 == K64).count();
  890. let big = v.views.values().map(|view| view.0).max().unwrap_or(0);
  891. lines.push(format!(
  892. "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB",
  893. bytes >> 20,
  894. big >> 20
  895. ));
  896. for &(_, bytes, committed) in &v.sections {
  897. lines.push(format!(
  898. "census, a section of {} MB, {}",
  899. bytes >> 20,
  900. if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" }
  901. ));
  902. }
  903. lines
  904. }
  905. /// With [`probe_level`] 2: one part of the title's own private memory
  906. /// (the start of the biggest such title buffer, 4 MiB at most) is opened
  907. /// for a moment, a buffer placed, 64 KiB read by the GPU and compared
  908. /// with what the CPU reads there (the title may be writing it meanwhile:
  909. /// the count of equal bytes is given), and all of it released. While the
  910. /// heap stands (milliseconds) a `VirtualFree` of the title's on those
  911. /// pages would fail.
  912. fn real_part(spans: &[(u64, u64, bool)]) -> Vec<String> {
  913. let Some(host) = crate::host::host() else {
  914. return Vec::new();
  915. };
  916. let mut known = Vec::new();
  917. let found = spans
  918. .iter()
  919. .filter(|s| !s.2 && s.1 >= 2 * K64 as u64)
  920. .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0)
  921. .max_by_key(|s| s.1);
  922. let Some(&(start, len, _)) = found else {
  923. return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()];
  924. };
  925. let at = (start as usize).next_multiple_of(K64);
  926. let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1);
  927. if bytes == 0 || !private_whole(at, bytes) {
  928. return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()];
  929. }
  930. let mut lines = Vec::new();
  931. let (set, started) = (working_set_mb(), std::time::Instant::now());
  932. let opened = open(&host.device, From::Part(at, bytes));
  933. lines.push(format!(
  934. "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB",
  935. bytes >> 10,
  936. hr(&opened),
  937. started.elapsed().as_secs_f64() * 1000.0,
  938. working_set_mb()
  939. ));
  940. if let Ok(heap) = &opened {
  941. let placed = place(&host.device, heap, 0, bytes as u64);
  942. lines.push(format!(" a buffer placed over it: {}", hr(&placed)));
  943. if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) {
  944. let mut before = vec![0u8; K64];
  945. crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false);
  946. let got = rig.fetch(buffer, 0, K64);
  947. let mut after = vec![0u8; K64];
  948. crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false);
  949. match got {
  950. Ok(got) => {
  951. let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count();
  952. let zeros = got.iter().filter(|&&b| b == 0).count();
  953. lines.push(format!(
  954. " 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)"
  955. ));
  956. }
  957. Err(e) => lines.push(format!(" the GPU's read failed: {e}")),
  958. }
  959. }
  960. }
  961. lines
  962. }
  963. /// Called once a second by the thread that submits, before a submission
  964. /// (`host::sweep`): with [`probe_level`], the probe at the first call, the
  965. /// census (on a thread of its own: it asks Windows about every copy) 30
  966. /// and 150 seconds later.
  967. pub(crate) fn tick() {
  968. if level() > 0 {
  969. say();
  970. }
  971. if probe_level() == 0 {
  972. return;
  973. }
  974. static STARTED: AtomicU64 = AtomicU64::new(0);
  975. static DONE: AtomicU64 = AtomicU64::new(0);
  976. let now = crate::host::now_ms().max(1);
  977. let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) {
  978. Ok(_) => {
  979. let Some(host) = crate::host::host() else {
  980. return;
  981. };
  982. let mb = std::env::var("VICTORY_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize);
  983. let took = std::time::Instant::now();
  984. let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024));
  985. for line in &probe.lines {
  986. tracing::info!("in place probe: {line}");
  987. }
  988. tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0);
  989. now
  990. }
  991. Err(started) => started,
  992. };
  993. let due = match DONE.load(Ordering::Relaxed) {
  994. 0 => now >= started + 30_000,
  995. 1 => now >= started + 150_000,
  996. _ => false,
  997. };
  998. if due {
  999. let which = DONE.fetch_add(1, Ordering::Relaxed);
  1000. std::thread::spawn(move || {
  1001. let spans = crate::shadow::spans();
  1002. for line in census_of(&spans) {
  1003. tracing::info!("in place {line}");
  1004. }
  1005. if which == 0 && probe_level() >= 2 {
  1006. for line in real_part(&spans) {
  1007. tracing::info!("in place probe: {line}");
  1008. }
  1009. }
  1010. });
  1011. }
  1012. }
  1013. #[cfg(test)]
  1014. mod tests {
  1015. use super::*;
  1016. /// Views as the runtime tells them: a range inside one view, or over
  1017. /// views that continue each other in one section, is one run; over
  1018. /// views from elsewhere it is scattered; over a gap it has holes.
  1019. #[test]
  1020. fn views_say_what_one_placed_buffer_could_show() {
  1021. let mut views = BTreeMap::new();
  1022. let at = 0x7_0000_0000usize;
  1023. views.insert(at, (4 * K64, 9, 16 * K64 as u64));
  1024. // Continues the first in the section.
  1025. views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64));
  1026. // Follows in address, from elsewhere in the section.
  1027. views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64));
  1028. // After a gap of one page.
  1029. views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64));
  1030. assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64));
  1031. assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64));
  1032. assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered);
  1033. assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes);
  1034. assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None);
  1035. assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None);
  1036. }
  1037. /// What the runtime forgets when memory is mapped anew.
  1038. #[test]
  1039. fn remapped_memory_forgets_its_views() {
  1040. let at = 0x7_4000_0000usize;
  1041. title_memory_view(at, 4 * K64, 77, 0);
  1042. title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64);
  1043. assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0));
  1044. // One page inside the first view goes: the whole view is forgotten
  1045. // (the runtime maps and tells again what stays of it).
  1046. views_gone(at + K64, K64);
  1047. assert_eq!(cover(at, K64), Cover::None);
  1048. assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64));
  1049. views_gone(at + 4 * K64, K64);
  1050. assert_eq!(cover(at + 4 * K64, K64), Cover::None);
  1051. }
  1052. /// Only private memory committed whole, read-write, is taken for a part.
  1053. #[test]
  1054. fn only_private_memory_committed_whole_is_a_part() {
  1055. // SAFETY: an allocation of the test's own.
  1056. unsafe {
  1057. let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::<u8>();
  1058. assert!(!base.is_null());
  1059. assert!(!private_whole(base as usize, K64), "reserved only");
  1060. mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE);
  1061. assert!(private_whole(base as usize, 4 * K64));
  1062. assert!(private_whole(base as usize + K64, 2 * K64));
  1063. assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half");
  1064. let mut old = 0;
  1065. mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old);
  1066. assert!(!private_whole(base as usize, 2 * K64), "a guarded page");
  1067. mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
  1068. }
  1069. }
  1070. pub(crate) fn warp() -> Option<ID3D12Device> {
  1071. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  1072. use windows::Win32::Graphics::Dxgi::*;
  1073. // SAFETY: plain DXGI queries and device creation on the software
  1074. // adapter; a card is never opened.
  1075. unsafe {
  1076. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  1077. let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
  1078. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  1079. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  1080. return None;
  1081. }
  1082. let mut device: Option<ID3D12Device> = None;
  1083. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  1084. device
  1085. }
  1086. }
  1087. /// The probe, whole, on the software adapter: the same calls the card
  1088. /// gets. The runtime's and the kernel's rules hold there; the card's
  1089. /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds.
  1090. #[test]
  1091. fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() {
  1092. let _turn = crate::indirect::tests::warp_turn();
  1093. let Some(device) = warp() else { return };
  1094. if device.cast::<ID3D12Device13>().is_err() {
  1095. eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened");
  1096. return;
  1097. }
  1098. let probe = probe(&device, &|| None, 4);
  1099. for line in &probe.lines {
  1100. eprintln!("in place probe: {line}");
  1101. }
  1102. assert!(probe.part_reads, "the GPU reads private memory in place");
  1103. assert!(probe.part_writes, "GPU writes land in private memory");
  1104. assert!(probe.section_reads && probe.section_writes, "a committed section in place");
  1105. assert!(probe.section_outlives_views, "the section's heap does not depend on views");
  1106. assert!(probe.reserved_section_refused, "a reserved section is refused");
  1107. }
  1108. /// Stage 1's own call on the software adapter: a title buffer that
  1109. /// begins and ends off the 64 KiB lines is placed over its pages, the
  1110. /// GPU reads the buffer's bytes at the offset the views use, and its
  1111. /// write lands at the title's address. Memory that is not committed
  1112. /// whole is turned down without asking the host.
  1113. #[test]
  1114. fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() {
  1115. let _turn = crate::indirect::tests::warp_turn();
  1116. let Some(device) = warp() else { return };
  1117. if device.cast::<ID3D12Device13>().is_err() {
  1118. return;
  1119. }
  1120. // SAFETY: an allocation of the test's own.
  1121. unsafe {
  1122. let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>();
  1123. let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5);
  1124. let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}"));
  1125. assert_eq!(placed.bias, 0x1230);
  1126. assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230);
  1127. assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer");
  1128. let mut rig = Rig::new(&device).unwrap();
  1129. fill(start as *mut u8, len as usize, 7);
  1130. let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap();
  1131. assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes");
  1132. rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap();
  1133. assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address");
  1134. drop(placed);
  1135. // Half of it decommitted: turned down, the host not asked.
  1136. // The heap lets go of the pages a moment after its last
  1137. // reference, if the adapter is busy with other tests' work.
  1138. let gone = (0..500).any(|_| {
  1139. let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0;
  1140. if !done {
  1141. std::thread::sleep(std::time::Duration::from_millis(10));
  1142. }
  1143. done
  1144. });
  1145. assert!(gone, "the heap keeps the pages");
  1146. assert!(matches!(place_part(&device, start, len), Err(None)));
  1147. mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
  1148. }
  1149. }
  1150. /// The census names each kind of memory.
  1151. #[test]
  1152. fn census_tells_private_memory_from_views() {
  1153. // SAFETY: an allocation of the test's own.
  1154. unsafe {
  1155. let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64;
  1156. let view = 0x7_8000_0000u64;
  1157. title_memory_view(view as usize, 2 * K64, 5, 0);
  1158. title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64);
  1159. let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]);
  1160. let text = lines.join("\n");
  1161. assert!(text.contains("census, title buffers: 2 of"), "{text}");
  1162. assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}");
  1163. assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}");
  1164. assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}");
  1165. views_gone(view as usize, 3 * K64);
  1166. mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE);
  1167. }
  1168. }
  1169. }