device.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //! The device titles get from device creation, laid out as their inlined
  2. //! code expects: the object header, then device fields. Its table starts
  3. //! like the PC device interface (IUnknown, the object methods, then the
  4. //! device methods in PC order); console additions follow. Methods we have
  5. //! not written log their table offset and fail, so a run shows what to
  6. //! write next.
  7. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  8. use std::ffi::c_void;
  9. use crate::object::{
  10. self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This,
  11. guid, guid_text,
  12. };
  13. use crate::{
  14. descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature,
  15. };
  16. /// What D3D returns when none of the requested feature levels is supported.
  17. const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32;
  18. /// The device interface id (the same as on PC). Titles also import it as
  19. /// data.
  20. pub static IID: Iid = guid(
  21. 0x189819f1,
  22. 0x1db6,
  23. 0x4b57,
  24. [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
  25. );
  26. /// The levels the device answers to, as on PC: `ID3D12Device1` to
  27. /// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates
  28. /// its device as. Each level's table is the one before plus its methods.
  29. const LEVEL_IIDS: [Iid; 9] = [
  30. guid(
  31. 0x77acce80,
  32. 0x638e,
  33. 0x4e65,
  34. [0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e],
  35. ),
  36. guid(
  37. 0x30baa41e,
  38. 0xb15b,
  39. 0x475c,
  40. [0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28],
  41. ),
  42. guid(
  43. 0x81dadc15,
  44. 0x2bad,
  45. 0x4392,
  46. [0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98],
  47. ),
  48. guid(
  49. 0xe865df17,
  50. 0xa9ee,
  51. 0x46f9,
  52. [0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5],
  53. ),
  54. guid(
  55. 0x8b4f173b,
  56. 0x2fea,
  57. 0x4b80,
  58. [0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d],
  59. ),
  60. guid(
  61. 0xc70b221b,
  62. 0x40e4,
  63. 0x4a17,
  64. [0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc],
  65. ),
  66. guid(
  67. 0x5c014b53,
  68. 0x68a1,
  69. 0x4b9b,
  70. [0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b],
  71. ),
  72. guid(
  73. 0x728f1fa2,
  74. 0xea11,
  75. 0x4a9f,
  76. [0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9],
  77. ),
  78. guid(
  79. 0x5405c344,
  80. 0xd457,
  81. 0x444e,
  82. [0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39],
  83. ),
  84. ];
  85. fn is_device(iid: *const Iid) -> bool {
  86. object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS)
  87. }
  88. /// The interface version these layouts were checked against (2.4). Both
  89. /// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it.
  90. pub const CHECKED_VERSION: u32 = 0x0002_0004;
  91. /// Feature level 12_2, what the console hardware supports.
  92. const HIGHEST_FEATURE_LEVEL: u32 = 0xc200;
  93. #[repr(C)]
  94. pub struct Device {
  95. object: Object,
  96. /// GPU address of a null constant buffer; none yet.
  97. null_constant_buffer: u64,
  98. /// Byte 0 non-zero: calls the title would otherwise inline come to the
  99. /// table. The rest is reserved.
  100. out_of_line: [u32; 16],
  101. }
  102. const _: () = assert!(size_of::<Device>() == 0x58);
  103. /// One device per process, as on the console.
  104. pub(crate) static DEVICE: Device = Device {
  105. object: Object::new(&FUNCTIONS),
  106. null_constant_buffer: 0,
  107. out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  108. };
  109. pub(crate) fn device() -> This {
  110. (&raw const DEVICE).cast()
  111. }
  112. /// Device creation: `(adapter, parameters, iid, out)`. The parameters start
  113. /// with the interface version; the rest (ring and scratch sizes, features
  114. /// to leave out) does not matter to us yet.
  115. pub extern "system" fn create(
  116. _adapter: *const c_void,
  117. parameters: *const u32,
  118. iid: *const Iid,
  119. out: *mut This,
  120. ) -> HRESULT {
  121. if parameters.is_null() || iid.is_null() {
  122. return E_INVALIDARG;
  123. }
  124. // SAFETY: checked non-null; the title passes its parameters and an id.
  125. let (version, iid) = unsafe { (parameters.read(), &*iid) };
  126. tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device");
  127. if version != CHECKED_VERSION {
  128. tracing::warn!(
  129. version = format_args!("{version:#x}"),
  130. "device layouts were checked against {CHECKED_VERSION:#x} only"
  131. );
  132. }
  133. if !is_device(iid) {
  134. tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface");
  135. return E_NOINTERFACE;
  136. }
  137. if out.is_null() {
  138. return S_FALSE;
  139. }
  140. if *iid == LEVEL_IIDS[8] {
  141. NEWER.store(true, std::sync::atomic::Ordering::Relaxed);
  142. }
  143. object::answer(object::DEVICE, iid, Some(device()), out)
  144. }
  145. /// Set when the title creates the device as `ID3D12Device11`. Its lists and
  146. /// queues then have the newer layouts (two more methods each; see
  147. /// `list` and `queue`), although the interface version stays 2.4.
  148. /// shortcut: the creation interface is the only sign of the newer layouts
  149. /// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022);
  150. /// look for a better one if a title breaks the rule.
  151. static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  152. pub(crate) fn newer() -> bool {
  153. NEWER.load(std::sync::atomic::Ordering::Relaxed)
  154. }
  155. /// The device, or its DXGI side.
  156. extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  157. let found = if is_device(iid) {
  158. Some(this)
  159. } else if object::is(iid, &dxgi::DEVICE_IIDS) {
  160. Some(dxgi::device())
  161. } else {
  162. None
  163. };
  164. object::answer(object::DEVICE, iid, found, out)
  165. }
  166. /// What `D3D12ConfigureVirtualMemoryX` takes and fills in.
  167. #[repr(C)]
  168. pub struct VirtualMemory {
  169. flags: u32,
  170. /// GPU page table size in 4 MiB pages.
  171. page_table_pages: u32,
  172. /// Memory kept across title processes for the frame buffer.
  173. preserved_bytes: u32,
  174. /// Out: the range graphics addresses fall in.
  175. lowest: u64,
  176. highest: u64,
  177. }
  178. const _: () = assert!(size_of::<VirtualMemory>() == 0x20);
  179. /// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics
  180. /// allocation. The inputs size console structures we do not have; the
  181. /// range out is all of user space, since GPU addresses are CPU addresses.
  182. pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT {
  183. // SAFETY: the title passes its configuration (null is tolerated).
  184. let Some(config) = (unsafe { config.as_mut() }) else {
  185. return E_INVALIDARG;
  186. };
  187. tracing::info!(
  188. flags = config.flags,
  189. page_table_pages = config.page_table_pages,
  190. preserved_bytes = config.preserved_bytes,
  191. "graphics virtual memory"
  192. );
  193. (config.lowest, config.highest) = user_space();
  194. S_OK
  195. }
  196. fn user_space() -> (u64, u64) {
  197. #[cfg(windows)]
  198. {
  199. use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO};
  200. // SAFETY: plain data, filled in by the call.
  201. let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
  202. // SAFETY: a valid out pointer.
  203. unsafe { GetSystemInfo(&mut info) };
  204. (
  205. info.lpMinimumApplicationAddress as u64,
  206. info.lpMaximumApplicationAddress as u64,
  207. )
  208. }
  209. #[cfg(not(windows))]
  210. (0x1_0000, 0x7fff_fffe_ffff)
  211. }
  212. extern "system" fn node_count(_: This) -> u32 {
  213. 1
  214. }
  215. /// Feature query 2: the highest of the requested feature levels we support.
  216. #[repr(C)]
  217. struct FeatureLevels {
  218. count: u32,
  219. requested: *const u32,
  220. highest: u32,
  221. }
  222. /// Feature query 0, what an RDNA 2 GPU reports. The console's layout has
  223. /// one field more than PC's (index 11).
  224. const OPTIONS: [u32; 16] = [
  225. 1, // double-precision shader operations
  226. 1, // output-merger logic operations
  227. 2, // minimum precision: 16-bit
  228. 3, // tiled resources tier
  229. 3, // resource binding tier
  230. 1, // stencil reference from pixel shaders
  231. 1, // typed UAV loads of more formats
  232. 1, // rasterizer-ordered views
  233. 3, // conservative rasterization tier
  234. 40, // GPU address bits per resource
  235. 0, // 64 KiB standard swizzle
  236. 0, // console-only field
  237. 0, // cross-node sharing tier
  238. 0, // cross-adapter row-major textures
  239. 1, // viewport and render target index from any stage
  240. 2, // resource heap tier
  241. ];
  242. extern "system" fn check_feature_support(
  243. _: This,
  244. feature: u32,
  245. data: *mut c_void,
  246. size: u32,
  247. ) -> HRESULT {
  248. const OPTIONS_QUERY: u32 = 0;
  249. const ARCHITECTURE: u32 = 1;
  250. const FEATURE_LEVELS: u32 = 2;
  251. const FORMAT_SUPPORT: u32 = 3;
  252. const MULTISAMPLE: u32 = 4;
  253. let expected = match feature {
  254. OPTIONS_QUERY => size_of_val(&OPTIONS),
  255. ARCHITECTURE => 16,
  256. FEATURE_LEVELS => size_of::<FeatureLevels>(),
  257. FORMAT_SUPPORT => 12,
  258. MULTISAMPLE => 16,
  259. _ => {
  260. tracing::warn!(feature, size, "device feature query not implemented");
  261. return E_NOTIMPL;
  262. }
  263. };
  264. if data.is_null() || size as usize != expected {
  265. return E_INVALIDARG;
  266. }
  267. match feature {
  268. OPTIONS_QUERY => {
  269. // SAFETY: checked size and non-null.
  270. unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) };
  271. S_OK
  272. }
  273. ARCHITECTURE => {
  274. // SAFETY: checked size and non-null.
  275. let a = unsafe { &mut *data.cast::<[u32; 4]>() };
  276. if a[0] != 0 {
  277. return E_INVALIDARG; // one node only
  278. }
  279. // Not tile-based; unified, cache-coherent memory.
  280. a[1..].copy_from_slice(&[0, 1, 1]);
  281. S_OK
  282. }
  283. FORMAT_SUPPORT => {
  284. // SAFETY: checked size and non-null.
  285. let q = unsafe { &mut *data.cast::<[u32; 3]>() };
  286. // shortcut: every use of every format; answer from the host
  287. // device once there is one.
  288. q[1] = 0x7fff_ffff;
  289. q[2] = 0xffff;
  290. S_OK
  291. }
  292. MULTISAMPLE => {
  293. // SAFETY: checked size and non-null.
  294. let q = unsafe { &mut *data.cast::<[u32; 4]>() };
  295. // Format, sample count, flags in; one quality level out for the
  296. // counts the hardware has.
  297. q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8));
  298. S_OK
  299. }
  300. _ => feature_levels(data),
  301. }
  302. }
  303. fn feature_levels(data: *mut c_void) -> HRESULT {
  304. // SAFETY: the caller checked size and non-null.
  305. let query = unsafe { &mut *data.cast::<FeatureLevels>() };
  306. if query.requested.is_null() {
  307. return E_INVALIDARG;
  308. }
  309. // SAFETY: the title passes `count` levels.
  310. let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) };
  311. match requested
  312. .iter()
  313. .copied()
  314. .filter(|&l| l <= HIGHEST_FEATURE_LEVEL)
  315. .max()
  316. {
  317. Some(level) => {
  318. query.highest = level;
  319. S_OK
  320. }
  321. None => UNSUPPORTED,
  322. }
  323. }
  324. /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
  325. /// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
  326. /// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
  327. /// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown.
  328. /// Every slot exists so that a call to one we have not written logs it.
  329. static FUNCTIONS: Table<160> = {
  330. let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>());
  331. f[0] = query_interface as *const (); // 0x00
  332. f[7] = node_count as *const (); // 0x38
  333. f[8] = queue::create as *const (); // 0x40
  334. f[9] = list::create_allocator as *const (); // 0x48
  335. f[12] = list::create_list as *const (); // 0x60
  336. f[10] = pipeline::create_graphics as *const (); // 0x50
  337. f[11] = pipeline::create_compute as *const (); // 0x58
  338. f[13] = check_feature_support as *const (); // 0x68
  339. f[14] = descriptor::create_heap as *const (); // 0x70
  340. f[15] = descriptor::increment_size as *const (); // 0x78
  341. f[16] = root::create as *const (); // 0x80
  342. f[17] = descriptor::create_cbv as *const (); // 0x88
  343. f[18] = descriptor::create_srv as *const (); // 0x90
  344. f[19] = descriptor::create_uav as *const (); // 0x98
  345. f[20] = descriptor::create_rtv as *const (); // 0xa0
  346. f[21] = descriptor::create_dsv as *const (); // 0xa8
  347. f[22] = descriptor::create_sampler as *const (); // 0xb0
  348. f[23] = descriptor::copy as *const (); // 0xb8
  349. f[24] = descriptor::copy_simple as *const (); // 0xc0
  350. f[25] = resource::allocation_info as *const (); // 0xc8
  351. f[26] = resource::custom_heap_properties as *const (); // 0xd0
  352. f[27] = resource::create_committed as *const (); // 0xd8
  353. f[28] = resource::create_heap as *const (); // 0xe0
  354. f[29] = resource::create_placed as *const (); // 0xe8
  355. f[36] = fence::create as *const (); // 0x120
  356. f[38] = resource::copyable_footprints as *const (); // 0x130
  357. f[39] = query::create as *const (); // 0x138
  358. f[41] = signature::create as *const (); // 0x148
  359. f[48] = queue::create_x as *const (); // 0x180
  360. f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
  361. f[62] = pipeline::create_compute_x as *const (); // 0x1f0
  362. f[69] = object::ignore as *const (); // 0x228 debug error filter
  363. f[70] = descriptor::create_placed_srv as *const (); // 0x230
  364. f[71] = descriptor::create_placed_uav as *const (); // 0x238
  365. f[73] = list::create_list_x as *const (); // 0x248
  366. f[74] = resource::register_page_pool as *const (); // 0x250
  367. f[75] = resource::unregister_page_pool as *const (); // 0x258
  368. // CreateCommittedResourceX: its description is PC's plus DCC options,
  369. // which we have no use for (the AMD upscaler's, on Series S).
  370. f[76] = resource::create_committed as *const (); // 0x260
  371. f[78] = frame::set_interval as *const (); // 0x270
  372. f[79] = frame::schedule as *const (); // 0x278
  373. f[80] = frame::wait as *const (); // 0x280
  374. f[81] = frame::statistics as *const (); // 0x288
  375. f[86] = pipeline::create_stream as *const (); // 0x2b0
  376. f[108] = resource::allocation_info2 as *const (); // 0x360
  377. f[127] = resource::create_committed3 as *const (); // 0x3f8
  378. f[133] = resource::create_at_address as *const (); // 0x428
  379. Table(f)
  380. };
  381. #[cfg(test)]
  382. mod tests {
  383. use super::*;
  384. use crate::object::slot;
  385. fn create_as(iid: &Iid) -> (HRESULT, This) {
  386. let version = CHECKED_VERSION;
  387. let mut device = std::ptr::null();
  388. let hr = create(std::ptr::null(), &version, iid, &mut device);
  389. (hr, device)
  390. }
  391. #[test]
  392. fn creation_hands_out_the_device() {
  393. let (hr, device) = create_as(&IID);
  394. assert_eq!(hr, S_OK);
  395. assert_eq!(device, super::device());
  396. // The title tests byte 0x18 before inlining a device call.
  397. // SAFETY: the device is 0x58 bytes.
  398. assert_ne!(unsafe { device.cast::<u8>().add(0x18).read() }, 0);
  399. assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE);
  400. assert_eq!(
  401. slot::<extern "system" fn(This) -> u32>(device, 0x38)(device),
  402. 1
  403. );
  404. let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0);
  405. assert_eq!(missing(), E_NOTIMPL);
  406. }
  407. #[test]
  408. fn newer_device_levels_are_the_same_device() {
  409. // ID3D12Device11, as Grand Theft Auto VI asks for it.
  410. let (hr, device) = create_as(&LEVEL_IIDS[8]);
  411. assert_eq!((hr, device), (S_OK, super::device()));
  412. let mut same = std::ptr::null();
  413. assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK);
  414. assert_eq!(same, device);
  415. // A Device8 method we have not written fails without crashing.
  416. let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x3a0);
  417. assert_eq!(missing(), E_NOTIMPL);
  418. }
  419. #[test]
  420. fn virtual_memory_configuration_reports_user_space() {
  421. let mut config = VirtualMemory {
  422. flags: 0,
  423. page_table_pages: 7,
  424. preserved_bytes: 0,
  425. lowest: 0,
  426. highest: 0,
  427. };
  428. assert_eq!(configure_virtual_memory(&mut config), S_OK);
  429. assert!(0 < config.lowest && config.lowest < config.highest);
  430. let heap = Box::new(0u8);
  431. assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64)));
  432. assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG);
  433. }
  434. #[test]
  435. fn feature_levels_pick_the_highest_supported() {
  436. type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT;
  437. let device = device();
  438. let check = slot::<Check>(device, 0x68);
  439. let query = |levels: &[u32], size| {
  440. let mut query = FeatureLevels {
  441. count: levels.len() as u32,
  442. requested: levels.as_ptr(),
  443. highest: 0,
  444. };
  445. let hr = check(device, 2, (&raw mut query).cast(), size);
  446. (hr, query.highest)
  447. };
  448. let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000];
  449. assert_eq!(query(&levels, 0x18), (S_OK, 0xc100));
  450. assert_eq!(query(&levels, 0x10).0, E_INVALIDARG);
  451. assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED);
  452. }
  453. }