book.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. //! Who has what memory of the card, and who had it (diagnostics).
  2. //!
  3. //! A device loss names a faulting address and, from a short list, what was
  4. //! freed there. A texture gone for minutes is in "nothing named", and which
  5. //! descriptor still names it is not told at all. Here every buffer, texture
  6. //! and texture block of ours stands with its address from when it is made,
  7. //! and stays with the time it went ([`made`], [`block`]); a texture's address
  8. //! is the base in the descriptor of its first view, which the card's heaps
  9. //! hold as plain bytes (measured: `indirect::tests::descriptors_written_under_readers`).
  10. //!
  11. //! - At a device loss ([`at_loss`]): who owns the faulting address and who
  12. //! owned it, newest first, and every slot of the view heap whose
  13. //! descriptor reaches it.
  14. //! - `VICTORY_SLOT_CHECK=1`: a thread walks the view heap and says which
  15. //! slots name memory that is gone, while nothing is lost yet ([`check`]).
  16. //!
  17. //! The book is kept with device-removed data on (`VICTORY_D3D12_DRED`) or the
  18. //! check; `VICTORY_BOOK=0` keeps none.
  19. //!
  20. //! What the descriptors' bits mean is AMD's (RDNA 2 and 3); on another card
  21. //! nothing is decoded as an address we know, and nothing is said.
  22. use std::collections::{BTreeMap, HashMap, VecDeque};
  23. use std::ffi::c_void;
  24. use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
  25. use std::sync::{Mutex, OnceLock};
  26. use windows::Win32::Graphics::Direct3D12::*;
  27. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  28. use windows::core::{GUID, HRESULT, IUnknown, Interface};
  29. /// Entries of what is gone that are kept.
  30. const GONE: usize = 400_000;
  31. /// Longer than anything of ours: how far below an address its owner starts.
  32. const LONGEST: u64 = 2 << 30;
  33. /// Entries longer than this are few and looked through one by one.
  34. const LONG: u64 = 64 << 20;
  35. #[derive(Clone, Debug)]
  36. struct Entry {
  37. start: u64,
  38. size: u64,
  39. what: String,
  40. made: u64,
  41. /// What was told of it since ([`note`]).
  42. notes: String,
  43. }
  44. #[derive(Default)]
  45. struct Book {
  46. next: u64,
  47. live: HashMap<u64, Entry>,
  48. by_start: BTreeMap<(u64, u64), ()>,
  49. long: Vec<u64>,
  50. /// By the object's address, for a name given after it was made.
  51. by_object: HashMap<usize, u64>,
  52. gone: VecDeque<(Entry, u64)>,
  53. /// Objects whose address could not be told, by what they are.
  54. unknown: BTreeMap<String, u64>,
  55. }
  56. static BOOK: Mutex<Option<Book>> = Mutex::new(None);
  57. /// Root descriptors given by address lately: time, address, bytes.
  58. static ROOTS: Mutex<VecDeque<(u64, u64, u64)>> = Mutex::new(VecDeque::new());
  59. /// Tests that want the book.
  60. #[cfg(test)]
  61. static FORCED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  62. pub(crate) fn on() -> bool {
  63. #[cfg(test)]
  64. if FORCED.load(Ordering::Relaxed) {
  65. return true;
  66. }
  67. static ON: OnceLock<bool> = OnceLock::new();
  68. *ON.get_or_init(|| {
  69. std::env::var_os("VICTORY_BOOK").is_none_or(|v| v != "0")
  70. && !cfg!(test)
  71. && (crate::host::dred_any() || checks())
  72. })
  73. }
  74. /// `VICTORY_SLOT_CHECK=1`.
  75. pub(crate) fn checks() -> bool {
  76. static ON: OnceLock<bool> = OnceLock::new();
  77. *ON.get_or_init(|| std::env::var_os("VICTORY_SLOT_CHECK").is_some_and(|v| v != "0"))
  78. }
  79. fn with<T>(f: impl FnOnce(&mut Book) -> T) -> T {
  80. f(BOOK.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Book::default))
  81. }
  82. impl Book {
  83. fn add(&mut self, object: usize, start: u64, size: u64, what: String, now: u64) -> u64 {
  84. self.next += 1;
  85. let id = self.next;
  86. self.by_start.insert((start, id), ());
  87. if size > LONG {
  88. self.long.push(id);
  89. }
  90. self.live.insert(id, Entry { start, size, what, made: now, notes: String::new() });
  91. if object != 0 {
  92. self.by_object.insert(object, id);
  93. }
  94. id
  95. }
  96. fn remove(&mut self, id: u64, object: usize, now: u64) {
  97. if let Some(entry) = self.live.remove(&id) {
  98. self.by_start.remove(&(entry.start, id));
  99. if entry.size > LONG {
  100. self.long.retain(|&l| l != id);
  101. }
  102. if self.gone.len() >= GONE {
  103. self.gone.pop_front();
  104. }
  105. self.gone.push_back((entry, now));
  106. }
  107. if self.by_object.get(&object) == Some(&id) {
  108. self.by_object.remove(&object);
  109. }
  110. }
  111. /// Whether something alive holds `at`.
  112. fn alive(&self, at: u64) -> bool {
  113. let holds = |id: &u64| self.live.get(id).is_some_and(|e| at >= e.start && at - e.start < e.size);
  114. self.by_start
  115. .range((at.saturating_sub(LONG), 0)..=(at, u64::MAX))
  116. .rev()
  117. .any(|((_, id), ())| holds(id))
  118. || self.long.iter().any(holds)
  119. }
  120. /// The live entries that hold `at`, the one that starts last first.
  121. fn holders(&self, at: u64) -> Vec<&Entry> {
  122. let from = at.saturating_sub(LONGEST);
  123. self.by_start
  124. .range((from, 0)..=(at, u64::MAX))
  125. .rev()
  126. .filter_map(|((_, id), ())| self.live.get(id))
  127. .filter(|e| at - e.start < e.size)
  128. .take(8)
  129. .collect()
  130. }
  131. /// The live entry that starts last at or below `at`, and the next above.
  132. fn neighbours(&self, at: u64) -> [Option<&Entry>; 2] {
  133. let below = self.by_start.range(..=(at, u64::MAX)).next_back();
  134. let above = self.by_start.range((at + 1, 0)..).next();
  135. [below, above].map(|e| e.and_then(|((_, id), ())| self.live.get(id)))
  136. }
  137. /// What held `at` and is gone, newest first.
  138. fn gone_at(&self, at: u64, most: usize) -> Vec<&(Entry, u64)> {
  139. self.gone.iter().rev().filter(|(e, _)| at >= e.start && at - e.start < e.size).take(most).collect()
  140. }
  141. }
  142. #[repr(C)]
  143. struct Notice {
  144. methods: &'static [*const (); 3],
  145. references: AtomicU32,
  146. id: u64,
  147. object: usize,
  148. }
  149. struct Methods([*const (); 3]);
  150. // SAFETY: function addresses only.
  151. unsafe impl Sync for Methods {}
  152. static NOTICE: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]);
  153. unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
  154. // SAFETY: COM's arguments.
  155. unsafe {
  156. if out.is_null() {
  157. return HRESULT(0x8000_4003_u32 as i32);
  158. }
  159. if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) {
  160. add_ref(this);
  161. *out = this;
  162. return HRESULT(0);
  163. }
  164. *out = std::ptr::null_mut();
  165. }
  166. HRESULT(0x8000_4002_u32 as i32)
  167. }
  168. unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
  169. // SAFETY: one of ours, alive while a reference to it is.
  170. unsafe { (*this.cast::<Notice>()).references.fetch_add(1, Ordering::Relaxed) + 1 }
  171. }
  172. unsafe extern "system" fn release(this: *mut c_void) -> u32 {
  173. // SAFETY: as above; the last reference frees the box it was made as.
  174. unsafe {
  175. let left = (*this.cast::<Notice>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
  176. if left == 0 {
  177. let gone = Box::from_raw(this.cast::<Notice>());
  178. let now = crate::host::now_ms();
  179. with(|b| b.remove(gone.id, gone.object, now));
  180. }
  181. left
  182. }
  183. }
  184. /// Has the book told when `object` goes.
  185. fn watch(object: &ID3D12Object, id: u64) {
  186. const KEY: GUID = GUID::from_u128(0x2c7d1a55_9e0b_46f2_8c11_5b8e70a4d913);
  187. let raw = object.as_raw() as usize;
  188. let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE.0, references: AtomicU32::new(1), id, object: raw }));
  189. // SAFETY: a COM object of ours with one reference, which this drops; the
  190. // object takes its own.
  191. unsafe {
  192. let notice = IUnknown::from_raw(notice.cast());
  193. if object.SetPrivateDataInterface(&KEY, &notice).is_err() {
  194. std::mem::forget(notice);
  195. }
  196. }
  197. }
  198. /// A view format for a typeless one (its first with a plain type).
  199. fn viewable(format: i32) -> Option<i32> {
  200. Some(match format {
  201. 1 => 2,
  202. 5 => 6,
  203. 9 => 11,
  204. 15 => 16,
  205. 19 => 21,
  206. 23 => 24,
  207. 27 => 28,
  208. 33 => 35,
  209. 39 => 41,
  210. 44 => 46,
  211. 48 => 49,
  212. 53 => 56,
  213. 60 => 61,
  214. 70 | 73 | 76 | 79 | 82 | 94 | 97 => format + 1,
  215. 90 => 87,
  216. 92 => 88,
  217. 20 | 40 | 45 | 55 => return None, // typed depth: no shader view
  218. f => f,
  219. })
  220. }
  221. /// The address of a texture: the base its descriptor has.
  222. fn texture_address(texture: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> Option<u64> {
  223. struct Slot(ID3D12DescriptorHeap, usize);
  224. // SAFETY: a descriptor heap, used under the lock.
  225. unsafe impl Send for Slot {}
  226. static SLOT: Mutex<Option<Slot>> = Mutex::new(None);
  227. if desc.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0 {
  228. return None;
  229. }
  230. let host = crate::host::made_host()?;
  231. let mut slot = SLOT.lock().unwrap_or_else(|e| e.into_inner());
  232. if slot.is_none() {
  233. // SAFETY: plain heap creation.
  234. let heap: ID3D12DescriptorHeap = unsafe {
  235. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  236. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  237. NumDescriptors: 1,
  238. ..Default::default()
  239. })
  240. }
  241. .ok()?;
  242. // SAFETY: a live heap.
  243. let at = unsafe { heap.GetCPUDescriptorHandleForHeapStart().ptr };
  244. *slot = Some(Slot(heap, at));
  245. }
  246. let at = slot.as_ref()?.1;
  247. let format = viewable(desc.Format.0)?;
  248. let mut view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  249. Format: DXGI_FORMAT(format),
  250. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  251. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  252. ..Default::default()
  253. };
  254. match desc.Dimension {
  255. D3D12_RESOURCE_DIMENSION_TEXTURE1D => {
  256. view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
  257. view.Anonymous.Texture1D.MipLevels = 1;
  258. }
  259. D3D12_RESOURCE_DIMENSION_TEXTURE3D => {
  260. view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
  261. view.Anonymous.Texture3D.MipLevels = 1;
  262. }
  263. _ if desc.SampleDesc.Count > 1 => view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS,
  264. _ => view.Anonymous.Texture2D.MipLevels = 1,
  265. }
  266. let mut words = [0u8; 32];
  267. // SAFETY: a slot of ours, a live texture; the handle is the descriptor's
  268. // memory or the read fails.
  269. unsafe {
  270. host.device
  271. .CreateShaderResourceView(texture, Some(&view), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: at });
  272. }
  273. if !crate::host::read_into(at as *const u8, &mut words) {
  274. return None;
  275. }
  276. match decode(&words) {
  277. Names::Texture { base, .. } => Some(base),
  278. _ => None,
  279. }
  280. }
  281. /// `resource` was made; `what` it is (a name given later replaces it).
  282. pub(crate) fn made(resource: &ID3D12Resource, what: impl FnOnce() -> String) {
  283. if !on() {
  284. return;
  285. }
  286. let Ok(object) = resource.cast::<ID3D12Object>() else { return };
  287. let raw = object.as_raw() as usize;
  288. if with(|b| b.by_object.contains_key(&raw)) {
  289. return named(&object, what);
  290. }
  291. // SAFETY: a live resource.
  292. let desc = unsafe { resource.GetDesc() };
  293. let (start, size) = if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER {
  294. // SAFETY: as above.
  295. (Some(unsafe { resource.GetGPUVirtualAddress() }), desc.Width)
  296. } else {
  297. let size = crate::host::made_host()
  298. // SAFETY: a plain query.
  299. .map_or(0, |h| unsafe { h.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes);
  300. (texture_address(resource, &desc), if size == u64::MAX { 0 } else { size })
  301. };
  302. let Some(start) = start.filter(|&s| s != 0) else {
  303. return with(|b| *b.unknown.entry(format!("f{} flags {:#x}", desc.Format.0, desc.Flags.0)).or_default() += 1);
  304. };
  305. let what = what();
  306. let now = crate::host::now_ms();
  307. let id = with(|b| b.add(raw, start, size.max(1), what, now));
  308. watch(&object, id);
  309. }
  310. /// A block of texture memory, found by the texture `resource` at `offset` of it.
  311. pub(crate) fn block(heap: &ID3D12Heap, resource: &ID3D12Resource, offset: u64, bytes: u64) {
  312. if !on() {
  313. return;
  314. }
  315. let (Ok(heap), Ok(object)) = (heap.cast::<ID3D12Object>(), resource.cast::<ID3D12Object>()) else {
  316. return;
  317. };
  318. let raw = heap.as_raw() as usize;
  319. let now = crate::host::now_ms();
  320. let id = with(|b| {
  321. let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start;
  322. // Known, unless the entry is of what had the pointer before.
  323. if b.by_object
  324. .get(&raw)
  325. .and_then(|id| b.live.get(id))
  326. .is_some_and(|e| at >= e.start && at - e.start < e.size)
  327. {
  328. return None;
  329. }
  330. Some(b.add(raw, at.checked_sub(offset)?, bytes, "a block of textures".into(), now))
  331. });
  332. if let Some(id) = id {
  333. watch(&heap, id);
  334. }
  335. }
  336. /// Something to say of the object at `raw` if it is in the book.
  337. pub(crate) fn note(raw: usize, what: impl FnOnce() -> String) {
  338. if !on() {
  339. return;
  340. }
  341. let what = what();
  342. with(|b| {
  343. if let Some(id) = b.by_object.get(&raw).copied()
  344. && let Some(e) = b.live.get_mut(&id)
  345. && e.notes.len() < 600
  346. {
  347. e.notes.push_str(&what);
  348. }
  349. });
  350. }
  351. /// A name for something made before.
  352. pub(crate) fn named(object: &ID3D12Object, what: impl FnOnce() -> String) {
  353. let raw = object.as_raw() as usize;
  354. if with(|b| b.by_object.contains_key(&raw)) {
  355. let what = what();
  356. with(|b| {
  357. if let Some(id) = b.by_object.get(&raw).copied()
  358. && let Some(e) = b.live.get_mut(&id)
  359. {
  360. e.what = what;
  361. }
  362. });
  363. }
  364. }
  365. /// A root descriptor was set by address.
  366. pub(crate) fn root(gpu: u64, bytes: u64) {
  367. if on() {
  368. let mut roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner());
  369. if roots.len() >= 16_384 {
  370. roots.pop_front();
  371. }
  372. roots.push_back((crate::host::now_ms(), gpu, bytes));
  373. }
  374. }
  375. /// What a descriptor's 32 bytes name.
  376. #[derive(Debug, Clone, Copy, PartialEq)]
  377. pub(crate) enum Names {
  378. Nothing,
  379. Texture { base: u64, meta: Option<u64>, kind: u32, width: u32, height: u32 },
  380. Buffer { base: u64, stride: u32, bytes: u64 },
  381. }
  382. /// The descriptor `bytes` hold, as AMD's cards have them since RDNA 2.
  383. pub(crate) fn decode(bytes: &[u8; 32]) -> Names {
  384. let w = |i: usize| u32::from_le_bytes([bytes[4 * i], bytes[4 * i + 1], bytes[4 * i + 2], bytes[4 * i + 3]]);
  385. let kind = w(3) >> 28;
  386. if kind >= 8 {
  387. let base = (u64::from(w(0)) | u64::from(w(1) & 0xff) << 32) << 8;
  388. if base == 0 {
  389. return Names::Nothing;
  390. }
  391. // Compressed (dword 6, bit 21): where the metadata lies.
  392. let meta = (w(6) >> 21 & 1 != 0 && w(7) != 0).then(|| u64::from(w(7)) << 16 | u64::from(w(6) >> 24) << 8);
  393. let width = ((w(1) >> 30) | (w(2) & 0xfff) << 2) + 1;
  394. let height = (w(2) >> 14 & 0x3fff) + 1;
  395. return Names::Texture { base, meta, kind, width, height };
  396. }
  397. let base = u64::from(w(0)) | u64::from(w(1) & 0xffff) << 32;
  398. let stride = w(1) >> 16 & 0x3fff;
  399. let bytes = u64::from(w(2)) * u64::from(stride.max(1));
  400. if base == 0 || bytes == 0 {
  401. Names::Nothing
  402. } else {
  403. Names::Buffer { base, stride, bytes }
  404. }
  405. }
  406. /// What the book says of an address: alive, gone or never there.
  407. fn fate(at: u64) -> Fate {
  408. with(|b| {
  409. if b.alive(at) {
  410. return Fate::Alive;
  411. }
  412. match b.gone_at(at, 1).first() {
  413. Some((e, gone)) => Fate::Gone(format!(
  414. "{} at {:#x}+{:#x} made at {:.1} s, gone at {:.1} s",
  415. e.what,
  416. e.start,
  417. e.size,
  418. e.made as f64 / 1e3,
  419. *gone as f64 / 1e3
  420. )),
  421. None => Fate::Never,
  422. }
  423. })
  424. }
  425. enum Fate {
  426. Alive,
  427. Gone(String),
  428. Never,
  429. }
  430. /// The addresses a descriptor reads first.
  431. fn bases(names: Names) -> Vec<(&'static str, u64)> {
  432. match names {
  433. Names::Nothing => Vec::new(),
  434. Names::Texture { base, meta, .. } => {
  435. let mut out = vec![("texture", base)];
  436. out.extend(meta.map(|m| ("metadata", m)));
  437. out
  438. }
  439. Names::Buffer { base, bytes, .. } => vec![("buffer", base), ("buffer's end", base + bytes - 1)],
  440. }
  441. }
  442. /// Starts the thread of `VICTORY_SLOT_CHECK=1`, once.
  443. pub(crate) fn check() {
  444. static ONCE: std::sync::Once = std::sync::Once::new();
  445. if !checks() || !on() {
  446. return;
  447. }
  448. ONCE.call_once(|| {
  449. let _ = std::thread::Builder::new().name("slot check".into()).spawn(walk);
  450. });
  451. }
  452. /// Slots found, since the start: looked at, naming nothing, textures,
  453. /// buffers, naming what is gone, naming what was never there.
  454. static FOUND: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
  455. fn walk() {
  456. use Ordering::Relaxed;
  457. const CHUNK: u32 = 4096;
  458. let mut at = 0u32;
  459. // Slots said already, by slot and address.
  460. let mut said: HashMap<(u32, u64), u64> = HashMap::new();
  461. let mut suspects: Vec<(u32, [u8; 32], u64)> = Vec::new();
  462. let mut round = std::time::Instant::now();
  463. let mut never_said = 0;
  464. let mut gone_said = 0;
  465. loop {
  466. let read = crate::descriptor::host::shown_bytes(at, CHUNK);
  467. let Some((first, bytes, end)) = read else {
  468. std::thread::sleep(std::time::Duration::from_millis(500));
  469. continue;
  470. };
  471. for (i, d) in bytes.chunks_exact(32).enumerate() {
  472. let d: [u8; 32] = d.try_into().unwrap_or([0; 32]);
  473. let names = decode(&d);
  474. FOUND[0].fetch_add(1, Relaxed);
  475. FOUND[match names {
  476. Names::Nothing => 1,
  477. Names::Texture { .. } => 2,
  478. Names::Buffer { .. } => 3,
  479. }]
  480. .fetch_add(1, Relaxed);
  481. if bases(names).iter().any(|&(_, base)| !matches!(fate(base), Fate::Alive)) {
  482. suspects.push((first + i as u32, d, crate::host::now_ms()));
  483. }
  484. }
  485. // Again a moment later: a slot between two states says nothing.
  486. let now = crate::host::now_ms();
  487. let due: Vec<(u32, [u8; 32], u64)> = {
  488. let (due, later) = suspects.into_iter().partition(|s| now >= s.2 + 400);
  489. suspects = later;
  490. due
  491. };
  492. for (slot, was, since) in due {
  493. let Some((_, again, _)) = crate::descriptor::host::shown_bytes(slot, 1) else { continue };
  494. if again != was {
  495. continue;
  496. }
  497. for (part, base) in bases(decode(&was)) {
  498. let (what, text) = match fate(base) {
  499. Fate::Alive => continue,
  500. Fate::Gone(text) => (4, text),
  501. Fate::Never => (5, "nothing the book ever had".to_owned()),
  502. };
  503. FOUND[what].fetch_add(1, Relaxed);
  504. let times = said.entry((slot, base)).or_insert(0);
  505. *times += 1;
  506. let quota = if what == 4 { &mut gone_said } else { &mut never_said };
  507. if *times > 1 || *quota >= if what == 4 { 400 } else { 60 } {
  508. continue;
  509. }
  510. *quota += 1;
  511. tracing::warn!(
  512. "slot check: view slot {slot} names {part} {base:#x} ({:?}), {text}; seen since {:.1} s; {}",
  513. decode(&was),
  514. since as f64 / 1e3,
  515. crate::descriptor::host::slot_story(slot)
  516. );
  517. }
  518. }
  519. at = first + (bytes.len() / 32) as u32;
  520. if at >= end {
  521. at = 0;
  522. let f = [0, 1, 2, 3, 4, 5].map(|i| FOUND[i].swap(0, Relaxed));
  523. let (live, gone, unknown) = with(|b| (b.live.len(), b.gone.len(), b.unknown.clone()));
  524. tracing::info!(
  525. "slot check: a round of the view heap in {:.1} s: {} slots, {} null, {} textures, {} buffers; {} name what is gone, {} what the book never had; the book has {live} things alive and {gone} gone; textures without an address {unknown:?}",
  526. round.elapsed().as_secs_f64(),
  527. f[0], f[1], f[2], f[3], f[4], f[5]
  528. );
  529. round = std::time::Instant::now();
  530. std::thread::sleep(std::time::Duration::from_millis(50));
  531. }
  532. }
  533. }
  534. /// For the report of a lost device: who has and had the faulting address,
  535. /// and what names it.
  536. pub(crate) fn at_loss(va: u64) -> String {
  537. if !on() {
  538. return String::new();
  539. }
  540. let mut text = with(|b| {
  541. let one =
  542. |e: &Entry| format!("{} {:#x}+{:#x} made at {:.3} s{}", e.what, e.start, e.size, e.made as f64 / 1e3, e.notes);
  543. let mut text = String::from("; BOOK: alive there:");
  544. for e in b.holders(va) {
  545. text.push_str(&format!(" [{}]", one(e)));
  546. }
  547. for (name, e) in ["below", "above"].iter().zip(b.neighbours(va)) {
  548. if let Some(e) = e {
  549. text.push_str(&format!(" {name} [{}, {:#x} away]", one(e), e.start.abs_diff(va)));
  550. }
  551. }
  552. text.push_str("; gone there, newest first:");
  553. for (e, gone) in b.gone_at(va, 12) {
  554. text.push_str(&format!(" [{} gone at {:.3} s]", one(e), *gone as f64 / 1e3));
  555. }
  556. text.push_str(&format!("; now {:.3} s, submissions (begun, finished) {:?}, {} alive, {} gone", crate::host::now_ms() as f64 / 1e3, crate::host::submissions(), b.live.len(), b.gone.len()));
  557. text
  558. });
  559. {
  560. let roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner());
  561. let mut near: Vec<(u64, u64, u64)> = roots.iter().filter(|r| r.1 <= va && va - r.1 < 4 << 30).copied().collect();
  562. near.sort_by_key(|r| va - r.1);
  563. near.dedup_by_key(|r| r.1);
  564. for (at, gpu, bytes) in near.into_iter().take(4) {
  565. text.push_str(&format!("; root descriptor {gpu:#x}+{bytes:#x} ({:#x} below) at {:.1} s", va - gpu, at as f64 / 1e3));
  566. }
  567. }
  568. // Every slot that reaches the address, and the nearest below it.
  569. let mut reach: Vec<(u32, Names)> = Vec::new();
  570. let mut near: Vec<(u64, u32, Names)> = Vec::new();
  571. let mut at = 0;
  572. let began = std::time::Instant::now();
  573. while let Some((first, bytes, end)) = crate::descriptor::host::shown_bytes(at, 16_384) {
  574. for (i, d) in bytes.chunks_exact(32).enumerate() {
  575. let slot = first + i as u32;
  576. let names = decode(&d.try_into().unwrap_or([0; 32]));
  577. let (base, len) = match names {
  578. Names::Nothing => continue,
  579. Names::Texture { base, meta, .. } => {
  580. if meta.is_some_and(|m| va >= m && va - m < 32 << 20) {
  581. reach.push((slot, names));
  582. }
  583. let len = with(|b| {
  584. b.holders(base)
  585. .iter()
  586. .map(|e| e.start + e.size - base)
  587. .min()
  588. .or_else(|| b.gone_at(base, 1).first().map(|(e, _)| e.start + e.size - base))
  589. });
  590. (base, len.unwrap_or(64 << 20) + (64 << 10))
  591. }
  592. Names::Buffer { base, bytes, .. } => (base, bytes),
  593. };
  594. if va >= base && va - base < len {
  595. reach.push((slot, names));
  596. } else if va >= base && va - base < 4 << 30 {
  597. near.push((va - base, slot, names));
  598. if near.len() > 4096 {
  599. near.sort_by_key(|n| n.0);
  600. near.truncate(16);
  601. }
  602. }
  603. }
  604. at = first + (bytes.len() / 32) as u32;
  605. if at >= end || began.elapsed().as_secs() > 20 {
  606. break;
  607. }
  608. }
  609. text.push_str(&format!("; {} slots reach it (heap read in {:.1} s)", reach.len(), began.elapsed().as_secs_f64()));
  610. for (slot, names) in reach.iter().take(24) {
  611. let (Names::Texture { base, .. } | Names::Buffer { base, .. }) = *names else { continue };
  612. let fate = match fate(base) {
  613. Fate::Alive => "alive".to_owned(),
  614. Fate::Gone(text) => format!("GONE: {text}"),
  615. Fate::Never => "never in the book".to_owned(),
  616. };
  617. text.push_str(&format!("; slot {slot} {names:?} {fate} {}", crate::descriptor::host::slot_story(*slot)));
  618. }
  619. near.sort_by_key(|n| n.0);
  620. for (away, slot, names) in near.iter().take(8) {
  621. text.push_str(&format!("; near: slot {slot} {names:?} {away:#x} below {}", crate::descriptor::host::slot_story(*slot)));
  622. }
  623. text
  624. }
  625. #[cfg(test)]
  626. mod tests {
  627. use super::*;
  628. /// The two descriptors of the card that were read (a texture of 64x64 and
  629. /// one of 2048x2048, RX 7900 XTX) and a raw buffer's.
  630. #[test]
  631. fn descriptors_are_read_as_the_card_has_them() {
  632. let mut d = [0u8; 32];
  633. d[..16].copy_from_slice(&[0, 0xb4, 0, 2, 0, 0, 0xa0, 0xc2, 0x0f, 0xc0, 0x0f, 0, 0xac, 0x0f, 0x60, 0x91]);
  634. assert_eq!(decode(&d), Names::Texture { base: 0x2_00b4_0000, meta: None, kind: 9, width: 64, height: 64 });
  635. d[..16].copy_from_slice(&[0, 0xb4, 2, 2, 0, 0, 0xa0, 0xc2, 0xff, 0xc1, 0xff, 1, 0xac, 0x0f, 0xb0, 0x91]);
  636. assert_eq!(decode(&d), Names::Texture { base: 0x2_02b4_0000, meta: None, kind: 9, width: 2048, height: 2048 });
  637. d = [0; 32];
  638. assert_eq!(decode(&d), Names::Nothing);
  639. d[..8].copy_from_slice(&0x1_2345_6780u64.to_le_bytes());
  640. d[8..12].copy_from_slice(&400u32.to_le_bytes());
  641. assert_eq!(decode(&d), Names::Buffer { base: 0x1_2345_6780, stride: 0, bytes: 400 });
  642. d[6] = 24; // a stride
  643. assert_eq!(decode(&d), Names::Buffer { base: 0x1_2345_6780, stride: 24, bytes: 9600 });
  644. }
  645. /// Who has an address, and who had it, newest first.
  646. /// A texture of the pool and its block stand in the book while they
  647. /// live, and not after.
  648. #[test]
  649. fn a_pooled_texture_and_its_block_are_in_the_book() {
  650. let Some(host) = crate::host::host() else { return };
  651. FORCED.store(true, Ordering::Relaxed);
  652. let desc = D3D12_RESOURCE_DESC {
  653. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  654. Width: 128,
  655. Height: 256,
  656. DepthOrArraySize: 1,
  657. MipLevels: 1,
  658. Format: DXGI_FORMAT(83),
  659. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  660. ..Default::default()
  661. };
  662. // SAFETY: a valid description.
  663. let texture = unsafe { crate::pool::texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) };
  664. if let Some(texture) = texture {
  665. let at = texture_address(&texture, &desc);
  666. println!("address {at:x?}");
  667. if let Some(at) = at {
  668. let names = || with(|b| b.holders(at).iter().map(|e| e.what.clone()).collect::<Vec<_>>());
  669. let found = names();
  670. println!("held by {found:?}");
  671. assert!(found.iter().any(|n| n.contains("a texture in a block")), "{found:?}");
  672. assert!(found.iter().any(|n| n.contains("a block of textures")), "{found:?}");
  673. drop(texture);
  674. assert!(!names().iter().any(|n| n.contains("a texture in a block")));
  675. }
  676. }
  677. FORCED.store(false, Ordering::Relaxed);
  678. }
  679. #[test]
  680. fn the_book_knows_what_is_gone() {
  681. let mut b = Book::default();
  682. let block = b.add(1, 0x1000_0000, 64 << 20, "a block".into(), 5);
  683. let one = b.add(2, 0x1000_0000, 0x8000, "one".into(), 6);
  684. let two = b.add(3, 0x1000_8000, 0x8000, "two".into(), 7);
  685. let names = |b: &Book, at| b.holders(at).iter().map(|e| e.what.clone()).collect::<Vec<_>>();
  686. assert_eq!(names(&b, 0x1000_0100), ["one", "a block"]);
  687. assert_eq!(names(&b, 0x1000_8100), ["two", "a block"]);
  688. assert!(b.alive(0x1000_8100) && !b.alive(0x1000_0000 + (64 << 20)) && !b.alive(0xfff_ffff));
  689. assert!(names(&b, 0x1000_0000 + (64 << 20)).is_empty());
  690. b.remove(one, 2, 10);
  691. b.remove(block, 1, 12);
  692. assert!(names(&b, 0x1000_0100).is_empty());
  693. let gone: Vec<(String, u64)> = b.gone_at(0x1000_0100, 9).iter().map(|(e, at)| (e.what.clone(), *at)).collect();
  694. assert_eq!(gone, [("a block".to_owned(), 12), ("one".to_owned(), 10)]);
  695. assert_eq!(b.neighbours(0x1000_0100)[1].map(|e| e.what.as_str()), Some("two"));
  696. b.remove(two, 3, 13);
  697. assert!(b.neighbours(u64::MAX - 1)[0].is_none() && b.by_object.is_empty());
  698. }
  699. }