2
0

batch.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. //! Clamps of many executions in one pass: the arguments of every indirect
  2. //! execution between two points where they may change are bounded together,
  3. //! at the first of them.
  4. //!
  5. //! The executions that come after it are not known yet when the pass is
  6. //! recorded, so it reads what to clamp from a table of jobs in upload
  7. //! memory, which the CPU goes on filling while the list is recorded: the
  8. //! pass is as wide as the table and its threads past the count do nothing.
  9. //! An execution that asks for a record already in the table (the title's
  10. //! tile classes) reads the same clamped one.
  11. //!
  12. //! What the records charge the list's budget is as for records clamped
  13. //! alone, times the executions that read them.
  14. use windows::Win32::Graphics::Direct3D12::*;
  15. use super::{Clamp, uav_barrier};
  16. use crate::host::transition;
  17. /// The jobs of one pass.
  18. pub(crate) const JOBS: u32 = 256;
  19. /// The bytes of its table in upload memory: the count, then the jobs.
  20. pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64;
  21. /// The bytes of a clamped record's place in the scratch buffer.
  22. pub(crate) const SLOT: u32 = 32;
  23. /// The source buffers a pass can read.
  24. pub(crate) const SOURCES: usize = 4;
  25. /// The most executions charged by one job: the most a record costs (2^26)
  26. /// as often still fits 32 bits.
  27. pub(crate) const TIMES: u32 = 31;
  28. pub(crate) const SOURCE: &str = r#"
  29. #define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)"
  30. ByteAddressBuffer src0 : register(t0);
  31. ByteAddressBuffer src1 : register(t1);
  32. ByteAddressBuffer src2 : register(t2);
  33. ByteAddressBuffer src3 : register(t3);
  34. // The count, 12 bytes of nothing, then per job: source (bits 0-1), kind
  35. // (4-7), words (8-11) and the executions that read it (16-31); the
  36. // record's offset in the source; its place in the scratch buffer; nothing.
  37. ByteAddressBuffer jobs : register(t4);
  38. RWByteAddressBuffer dst_args : register(u0);
  39. RWByteAddressBuffer budget : register(u1);
  40. static const uint BUDGET = 1u << 27;
  41. static const uint GROUPS = 1u << 20;
  42. groupshared uint costs[64];
  43. groupshared uint fits[64];
  44. groupshared uint largest_asked;
  45. groupshared uint all_asked;
  46. uint load(uint source, uint at) {
  47. if (source == 0) return src0.Load(at);
  48. if (source == 1) return src1.Load(at);
  49. if (source == 2) return src2.Load(at);
  50. return src3.Load(at);
  51. }
  52. [RootSignature(RS)]
  53. [numthreads(64, 1, 1)]
  54. void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
  55. uint count = jobs.Load(0);
  56. bool active = id.x < count;
  57. uint4 job = uint4(0, 0, 0, 0);
  58. uint record[5] = {0, 0, 0, 0, 0};
  59. uint cost = 0;
  60. uint asked = 0;
  61. uint kind = 0;
  62. uint words = 0;
  63. if (gi == 0) {
  64. largest_asked = 0;
  65. all_asked = 0;
  66. }
  67. // As the clamp of one execution (`super::SOURCE`) bounds them.
  68. if (active) {
  69. job = jobs.Load4(16 + id.x * 16);
  70. kind = (job.x >> 4) & 15;
  71. words = min((job.x >> 8) & 15, 5);
  72. for (uint w = 0; w < words; w++) {
  73. record[w] = load(job.x & 3, job.y + w * 4);
  74. }
  75. if (kind <= 1) {
  76. record[0] = min(record[0], 1u << 24);
  77. record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
  78. cost = record[0] * record[1];
  79. } else if (kind == 2) {
  80. uint3 g = uint3(record[0], record[1], record[2]);
  81. g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
  82. if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
  83. g = uint3(0, 0, 0);
  84. }
  85. cost = g.x * g.y * g.z * 64u;
  86. record[0] = g.x;
  87. record[1] = g.y;
  88. record[2] = g.z;
  89. } else {
  90. asked = record[0];
  91. record[0] = min(record[0], 65535u);
  92. record[1] = min(record[1], 1u);
  93. record[2] = min(record[2], 1u);
  94. cost = record[0] * record[1] * record[2] * 128u;
  95. }
  96. cost *= job.x >> 16;
  97. }
  98. costs[gi] = cost;
  99. GroupMemoryBarrierWithGroupSync();
  100. if (active && kind > 2) {
  101. uint was;
  102. InterlockedMax(largest_asked, asked, was);
  103. InterlockedAdd(all_asked, min(asked, 1u << 24), was);
  104. }
  105. uint first = id.x - gi;
  106. uint n = count > first ? min(64u, count - first) : 0u;
  107. if (gi == 0 && n > 0) {
  108. uint before;
  109. budget.InterlockedOr(0, 0, before);
  110. [allow_uav_condition]
  111. while (before < BUDGET) {
  112. uint next = before;
  113. for (uint j = 0; j < n; j++) {
  114. uint c = costs[j];
  115. if (c > 0 && next < BUDGET) {
  116. next = (BUDGET - next <= c) ? BUDGET : (next + c);
  117. }
  118. }
  119. if (next == before) break;
  120. uint prev;
  121. budget.InterlockedCompareExchange(0, before, next, prev);
  122. if (prev == before) break;
  123. before = prev;
  124. }
  125. uint at = before;
  126. for (uint k = 0; k < n; k++) {
  127. uint c = costs[k];
  128. uint fit = 1;
  129. if (c > 0) {
  130. fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
  131. at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
  132. }
  133. fits[k] = fit;
  134. }
  135. }
  136. GroupMemoryBarrierWithGroupSync();
  137. if (gi == 0 && n > 0 && all_asked > 0) {
  138. uint was;
  139. budget.InterlockedMax(4, largest_asked, was);
  140. budget.InterlockedAdd(8, all_asked, was);
  141. }
  142. if (!active) {
  143. return;
  144. }
  145. if (fits[gi] == 0) {
  146. record[0] = 0;
  147. record[1] = 0;
  148. if (kind > 1) {
  149. record[2] = 0;
  150. }
  151. }
  152. for (uint s = 0; s < words; s++) {
  153. dst_args.Store(job.z + s * 4, record[s]);
  154. }
  155. }
  156. "#;
  157. /// The words of a record of `kind` (PC argument numbering).
  158. pub(crate) fn words(kind: u32) -> Option<u32> {
  159. super::min_stride(kind).map(|bytes| bytes / 4)
  160. }
  161. /// A job's first word.
  162. pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 {
  163. source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16)
  164. }
  165. /// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it
  166. /// keeps which record is where.
  167. #[derive(Default)]
  168. pub(crate) struct Table {
  169. /// The table in upload memory ([`TABLE`] bytes).
  170. at: usize,
  171. /// The place of the first clamped record in the scratch buffer.
  172. base: u32,
  173. /// The host copies it can read, by number ([`crate::shadow::Shadow::id`];
  174. /// 0: none).
  175. sources: [u64; SOURCES],
  176. /// How many executions each job is charged for so far.
  177. times: Vec<u32>,
  178. /// The job of a record (source, offset, kind).
  179. known: std::collections::HashMap<(u32, u32, u32), u32>,
  180. }
  181. impl Table {
  182. /// A table at `at`, with no job yet.
  183. ///
  184. /// # Safety
  185. /// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that
  186. /// live until the list that reads them is recorded and is not run
  187. /// before.
  188. pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table {
  189. // SAFETY: the caller's.
  190. unsafe { at.cast::<u32>().write_volatile(0) };
  191. Table { at: at as usize, base, sources, ..Table::default() }
  192. }
  193. /// The place in the scratch buffer of the record of `kind` at `offset`
  194. /// of the host copy `id`, once the pass has run: a job of it is added if
  195. /// there is none. `None` if the pass cannot read that copy or has no
  196. /// room for another job.
  197. pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> {
  198. let source = self.sources.iter().position(|&s| s == id)? as u32;
  199. let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?;
  200. offset.checked_add(words(kind)? * 4)?;
  201. let key = (source, offset, kind);
  202. let table = self.at as *mut u32;
  203. let place = |i: u32| u64::from(self.base + i * SLOT);
  204. if let Some(&i) = self.known.get(&key)
  205. && self.times[i as usize] < TIMES
  206. {
  207. self.times[i as usize] += 1;
  208. // SAFETY: the job's own word of the table ([`Table::new`]).
  209. unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) };
  210. return Some(place(i));
  211. }
  212. let i = self.times.len() as u32;
  213. if i == JOBS {
  214. return None;
  215. }
  216. self.times.push(1);
  217. self.known.insert(key, i);
  218. // SAFETY: inside the table: fewer than [`JOBS`] jobs before it.
  219. unsafe {
  220. let to = table.add(4 + 4 * i as usize);
  221. to.write_volatile(job(source, kind, 1));
  222. to.add(1).write_volatile(offset);
  223. to.add(2).write_volatile(self.base + i * SLOT);
  224. to.add(3).write_volatile(0);
  225. table.write_volatile(i + 1);
  226. }
  227. Some(place(i))
  228. }
  229. }
  230. /// Records the pass over the table at `jobs` (a host address) into `dst`,
  231. /// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every
  232. /// earlier shader write (the title's argument passes), before what reads
  233. /// the clamped records.
  234. pub(super) fn record(
  235. c: &Clamp,
  236. l: &ID3D12GraphicsCommandList,
  237. (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
  238. budget: u64,
  239. sources: [u64; SOURCES],
  240. jobs: u64,
  241. ) {
  242. let after = transition(
  243. dst,
  244. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  245. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  246. );
  247. // SAFETY: an open list; our root signature and pipeline; live buffers:
  248. // the sources and the table are read in the common state (promoted).
  249. unsafe {
  250. l.ResourceBarrier(&[
  251. uav_barrier(),
  252. transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
  253. ]);
  254. l.SetComputeRootSignature(&c.root);
  255. l.SetPipelineState(&c.pso);
  256. for (i, source) in sources.into_iter().enumerate() {
  257. l.SetComputeRootShaderResourceView(i as u32, source);
  258. }
  259. l.SetComputeRootShaderResourceView(SOURCES as u32, jobs);
  260. l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress());
  261. l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget);
  262. l.Dispatch(JOBS.div_ceil(64), 1, 1);
  263. // Nothing else the pass writes is read before the next full wait
  264. // (the budget, by the next pass): only the records have to be there.
  265. l.ResourceBarrier(&[after]);
  266. }
  267. }