psx_gpu/ot.rs
1//! Ordering Table: depth-sorted linked-list of GPU primitives.
2//!
3//! The PS1 has no Z-buffer. Games sort primitives back-to-front
4//! (painter's algorithm) by inserting them into an OT slot indexed
5//! by depth. Each OT slot is the head of a linked list; primitives
6//! prepend themselves so the most-recently-inserted draws first
7//! within a slot.
8//!
9//! Once a frame's primitives are inserted, the whole OT is shipped
10//! to GPU GP0 via DMA channel 2 in linked-list mode. The DMA walker
11//! follows the `next` pointers embedded in each packet's first word
12//! until it hits `0x00FFFFFF` (end of chain).
13//!
14//! Each 32-bit OT entry (and primitive header) is:
15//!
16//! ```text
17//! bits 0..=23: address of next packet (24-bit, masked into RAM)
18//! bits 24..=31: word count of this packet's data, at most
19//! `crate::chain::MAX_NODE_WORDS` (16) on silicon
20//! ```
21//!
22//! An "empty OT" has every entry pointing at its predecessor,
23//! ending in `0x00FFFFFF`. Submitting such an OT sends nothing to
24//! GP0. As primitives are added, their packets chain in.
25
26use core::marker::PhantomData;
27use core::ptr;
28use psx_io::periph::OrderingTableClearDma;
29
30const OT_ADDR_MASK: u32 = psx_hw::dma::linked_list::ADDRESS_MASK;
31const OT_END: u32 = psx_hw::dma::linked_list::END;
32const OT_MAX_EXTRA_HOPS: usize = 131_072;
33/// A staged-tag bit that tagged-stream insertion ignores: the stream inserts
34/// keep only the word count and the slot from a staged tag.
35#[deprecated(note = "has no effect: the scoped texture-window coalescing that read it was removed")]
36pub const TAG_SCOPED_TEXTURE_WINDOW: u32 = 1 << 16;
37/// Whether DMA can read `packet`: on the console, main RAM (any mirror or
38/// segment) and not the scratchpad, whose low 24 bits would name a RAM
39/// address instead. Host builds accept any address.
40fn is_dma_reachable(packet: *mut u32) -> bool {
41 if cfg!(target_arch = "mips") {
42 let physical = psx_hw::memory::to_physical(packet.addr() as u32);
43 physical < psx_hw::memory::ram::MIRROR_END
44 } else {
45 true
46 }
47}
48
49/// Fixed-size OT. `N` depth slots. Typical values: 256, 1024, 4096.
50#[repr(C, align(4))]
51pub struct OrderingTable<const N: usize> {
52 entries: [u32; N],
53}
54
55impl<const N: usize> OrderingTable<N> {
56 /// Create a table with every slot being a chain terminator.
57 /// Call [`clear`](Self::clear) before submitting -- that wires
58 /// up the inter-slot chain so DMA walks across all `N` slots.
59 pub const fn new() -> Self {
60 const { assert!(N > 0, "an ordering table needs at least one slot") };
61 Self {
62 entries: [OT_END; N],
63 }
64 }
65
66 /// Reset every slot for a fresh frame. Entry `[0]` is the
67 /// terminator (farthest from camera); each higher slot points
68 /// to the slot below. Submission starts at `[N-1]` so the
69 /// DMA walker visits `[N-1] → [N-2] → … → [0] → end`.
70 #[doc(alias = "ClearOTagR")]
71 pub fn clear(&mut self) {
72 // CPU clear by default: the OTC DMA is one of the channels the
73 // CL2 silicon probes showed can wedge busy-forever on real
74 // hardware, and a wedged boot-time clear freezes the engine at
75 // its first frame with no diagnostic. N stores per frame is a
76 // measurable but small cost; callers that trust their DMA can
77 // opt back in via [`Self::clear_with_dma`].
78 self.clear_software();
79 }
80
81 /// [`clear`](Self::clear) through the ordering-table-clear DMA channel
82 /// (channel 6) instead of the CPU.
83 ///
84 /// The wait is bounded: if the channel wedges, which the CL2 silicon
85 /// probes saw it do, or the table is longer than a 16-bit word count,
86 /// the CPU clear runs instead, so the table is always valid. Host
87 /// builds always clear with the CPU.
88 #[doc(alias = "ClearOTagR")]
89 pub fn clear_with_dma(&mut self, dma: &mut OrderingTableClearDma) {
90 #[cfg(not(target_arch = "mips"))]
91 let _ = &dma;
92 #[cfg(target_arch = "mips")]
93 if dma.clear_table(&mut self.entries) {
94 return;
95 }
96 self.clear_software();
97 }
98
99 #[cfg(not(target_arch = "mips"))]
100 fn clear_software(&mut self) {
101 // Slot 0 is the sentinel; chain walks stop here. Each other slot links
102 // the one below it, by the low 24 bits of its address.
103 let base = self.entries.as_mut_ptr().expose_provenance() as u32;
104 self.entries[0] = OT_END;
105 for i in 1..N {
106 self.entries[i] = base.wrapping_add(4 * (i as u32 - 1)) & OT_ADDR_MASK;
107 }
108 }
109
110 #[cfg(target_arch = "mips")]
111 fn clear_software(&mut self) {
112 // The PS1 RAM window occupies only the low 2 MiB of the DMA address
113 // domain, so advancing a low-24-bit OT address across this table
114 // cannot wrap. Schedule eight dependent pointer values per branch;
115 // this preserves the exact OTC chain while avoiding the scalar
116 // pointer-mask and branch cost for every one of the 2,048 Quake slots.
117 let entries = self.entries.as_mut_ptr();
118 // SAFETY: `entries` points at the `N` (at least one) words `self` owns.
119 unsafe { ptr::write(entries, OT_END) };
120 let bulk_words = (N.saturating_sub(1) / 8) * 8;
121 // SAFETY: one past entry 0 stays inside `entries`, or one past its end.
122 let mut cursor = unsafe { entries.add(1) };
123 // SAFETY: `bulk_words` is at most `N - 1`, so this stays inside `entries` or one past
124 // it.
125 let bulk_end = unsafe { cursor.add(bulk_words) };
126 let mut previous = entries.expose_provenance() as u32 & OT_ADDR_MASK;
127 if bulk_words != 0 {
128 // SAFETY: the loop stores `bulk_words` words from `entries + 1`, all inside the
129 // table, and touches no other memory or the stack.
130 unsafe {
131 core::arch::asm!(
132 ".set noreorder",
133 "2:",
134 "sw $9, 0($8)",
135 "addiu $9, $9, 4",
136 "sw $9, 4($8)",
137 "addiu $9, $9, 4",
138 "sw $9, 8($8)",
139 "addiu $9, $9, 4",
140 "sw $9, 12($8)",
141 "addiu $9, $9, 4",
142 "sw $9, 16($8)",
143 "addiu $9, $9, 4",
144 "sw $9, 20($8)",
145 "addiu $9, $9, 4",
146 "sw $9, 24($8)",
147 "addiu $9, $9, 4",
148 "sw $9, 28($8)",
149 "addiu $9, $9, 4",
150 "addiu $8, $8, 32",
151 "bne $8, $10, 2b",
152 "nop",
153 ".set reorder",
154 inout("$8") cursor,
155 inout("$9") previous,
156 in("$10") bulk_end,
157 options(nostack),
158 );
159 }
160 }
161 // SAFETY: one past the last entry of `entries`, the loop bound.
162 while cursor < unsafe { entries.add(N) } {
163 // SAFETY: `cursor` is below `entries + N`, inside the table.
164 unsafe { ptr::write(cursor, previous) };
165 // SAFETY: stays at most one past the end of `entries`.
166 cursor = unsafe { cursor.add(1) };
167 previous = previous.wrapping_add(4);
168 }
169 }
170
171 /// Prepend a primitive packet into the depth-`z` slot. `packet_ptr`
172 /// must point at the packet's tag word (first `u32`); `words` is
173 /// the count of data words that follow the tag, at most
174 /// [`crate::chain::MAX_NODE_WORDS`].
175 ///
176 /// # Safety
177 /// Caller guarantees that `[packet_ptr .. packet_ptr + 1 + words]`
178 /// is live, writable, 4-byte-aligned RAM for the duration of the
179 /// OT submission. Primitives returned by the builders in
180 /// [`crate::prim`] satisfy this.
181 ///
182 /// # Panics
183 /// If `words` exceeds [`crate::chain::MAX_NODE_WORDS`]: silicon loses words
184 /// from a longer node.
185 pub(crate) unsafe fn link(&mut self, z: usize, packet_ptr: *mut u32, words: u8) {
186 assert!(
187 words as usize <= crate::chain::MAX_NODE_WORDS,
188 "GPU DMA node longer than MAX_NODE_WORDS"
189 );
190 let z = z.min(N - 1);
191 // SAFETY: `z` was clamped below `N`; the packet contract is forwarded.
192 unsafe { self.link_unchecked(z, packet_ptr, words) };
193 }
194
195 /// Prepend a primitive packet into an already-clamped depth slot.
196 ///
197 /// # Safety
198 /// Same packet lifetime/alignment requirements as [`link`](Self::link).
199 /// In addition, `z` must be less than `N`.
200 #[inline(always)]
201 pub(crate) unsafe fn link_unchecked(&mut self, z: usize, packet_ptr: *mut u32, words: u8) {
202 debug_assert!(words as usize <= crate::chain::MAX_NODE_WORDS);
203 // SAFETY: forwarded contract; a word count below 256 fills the top byte only.
204 unsafe { self.link_tag_high_unchecked(z, packet_ptr, (words as u32) << 24) };
205 }
206
207 /// Prepend a primitive whose packet-word count is already stored in the
208 /// high byte of `tag_high` into an already-clamped depth slot.
209 ///
210 /// # Safety
211 /// Same requirements as [`link_unchecked`](Self::link_unchecked).
212 /// The low 24 bits of `tag_high` must be zero.
213 #[inline(always)]
214 pub(crate) unsafe fn link_tag_high_unchecked(
215 &mut self,
216 z: usize,
217 packet_ptr: *mut u32,
218 tag_high: u32,
219 ) {
220 debug_assert!(z < N);
221 debug_assert_eq!(tag_high & OT_ADDR_MASK, 0);
222 debug_assert!((tag_high >> 24) as usize <= crate::chain::MAX_NODE_WORDS);
223 debug_assert!(is_dma_reachable(packet_ptr), "GPU DMA reads main RAM only");
224 // SAFETY: the caller guarantees `z < N`.
225 let entry = unsafe { self.entries.get_unchecked_mut(z) };
226 let old_head = *entry & OT_ADDR_MASK;
227 // SAFETY: the caller guarantees a live, writable, aligned tag word.
228 unsafe { ptr::write_volatile(packet_ptr, tag_high | old_head) };
229 *entry = packet_ptr.expose_provenance() as u32 & OT_ADDR_MASK;
230 }
231
232 /// Insert an array of compact raw packet commands in caller order.
233 ///
234 /// Each command is two machine words: a packet pointer followed by a
235 /// packed word containing the OT slot in bits 0..15 and the GPU packet
236 /// word count in bits 24..31. Commands are consumed first-to-last, so the
237 /// OT's prepend semantics deliberately reverse commands which share a
238 /// slot. This matches repeated classic `addPrim` calls exactly.
239 ///
240 /// Use [`Self::link_packed_commands_reverse_unchecked`] when same-slot
241 /// submission order must instead be preserved.
242 ///
243 /// # Safety
244 /// `commands` must point to `command_count * 2` readable machine words in
245 /// the documented layout. Every packet pointer must meet the lifetime,
246 /// alignment, and writability requirements of [`Self::link_unchecked`],
247 /// every encoded slot must be less than `N`, and every word count at most
248 /// [`crate::chain::MAX_NODE_WORDS`].
249 #[inline]
250 pub(crate) unsafe fn link_packed_commands_unchecked(
251 &mut self,
252 commands: *const usize,
253 command_count: usize,
254 ) {
255 if command_count == 0 {
256 return;
257 }
258 debug_assert!(N > 0);
259
260 #[cfg(target_arch = "mips")]
261 {
262 // SAFETY: the caller guarantees `command_count * 2` readable words at `commands`.
263 let command_end = unsafe { commands.add(command_count.saturating_mul(2)) };
264 let entries = self.entries.as_mut_ptr();
265 // SAFETY: the loop reads the caller's command words and writes each packet's tag
266 // and its slot entry, all covered by this function's contract; it uses only the
267 // clobbered registers.
268 unsafe {
269 core::arch::asm!(
270 ".set noreorder",
271 "lui $15, 0x00ff",
272 "ori $15, $15, 0xffff",
273 "2:",
274 "lw $11, 0($8)",
275 "lw $12, 4($8)",
276 "addiu $8, $8, 8",
277 "sll $14, $11, 8",
278 "andi $13, $12, 0xffff",
279 "srl $14, $14, 8",
280 "srl $12, $12, 24",
281 "sll $13, $13, 2",
282 "sll $12, $12, 24",
283 "addu $13, $10, $13",
284 "lw $9, 0($13)",
285 "nop",
286 "and $9, $9, $15",
287 "or $9, $9, $12",
288 "sw $9, 0($11)",
289 "sw $14, 0($13)",
290 "bne $8, $16, 2b",
291 "nop",
292 ".set reorder",
293 inout("$8") commands => _,
294 in("$10") entries,
295 in("$16") command_end,
296 lateout("$9") _,
297 lateout("$11") _,
298 lateout("$12") _,
299 lateout("$13") _,
300 lateout("$14") _,
301 lateout("$15") _,
302 options(nostack),
303 );
304 }
305 }
306
307 #[cfg(not(target_arch = "mips"))]
308 {
309 for index in 0..command_count {
310 // SAFETY: `index < command_count`, inside the caller's command array.
311 let command = unsafe { commands.add(index * 2) };
312 // SAFETY: the first word of each command is its packet pointer.
313 let packet_ptr =
314 ptr::with_exposed_provenance_mut::<u32>(unsafe { ptr::read(command) });
315 // SAFETY: the second word of each command is its slot and word count.
316 let slot_words = unsafe { ptr::read(command.add(1)) } as u32;
317 let slot = (slot_words & u16::MAX as u32) as usize;
318 debug_assert!(slot < N);
319 // SAFETY: the caller guarantees the packet and the slot meet
320 // `link_tag_high_unchecked`'s contract.
321 unsafe { self.link_tag_high_unchecked(slot, packet_ptr, slot_words & 0xff00_0000) };
322 }
323 }
324 }
325
326 /// Insert a reverse-ordered array of compact raw packet commands.
327 ///
328 /// Each command is exactly two machine words: a packet pointer followed by a
329 /// packed word containing the OT slot in bits 0..15 and the GPU packet
330 /// word count in bits 24..31. Commands are consumed last-to-first, which
331 /// preserves their original submission order despite OT insertion being
332 /// prepend-only.
333 ///
334 /// On PS1 this is one tightly scheduled MIPS loop, matching the direct OT
335 /// linking used by late commercial engines while retaining the caller's
336 /// exact same-slot packet order. Host builds use the scalar equivalent so
337 /// command-stream tests exercise identical semantics.
338 ///
339 /// # Safety
340 /// `commands` must point to `command_count * 2` readable machine words in the
341 /// documented layout. Every encoded packet pointer must meet the lifetime,
342 /// alignment, and writability requirements of [`Self::link_unchecked`],
343 /// every encoded slot must be less than `N`, and every word count at most
344 /// [`crate::chain::MAX_NODE_WORDS`].
345 #[inline]
346 pub(crate) unsafe fn link_packed_commands_reverse_unchecked(
347 &mut self,
348 commands: *const usize,
349 command_count: usize,
350 ) {
351 if command_count == 0 {
352 return;
353 }
354 debug_assert!(N > 0);
355
356 #[cfg(target_arch = "mips")]
357 {
358 // SAFETY: the caller guarantees `command_count * 2` readable words at `commands`.
359 let command_end = unsafe { commands.add(command_count.saturating_mul(2)) };
360 let entries = self.entries.as_mut_ptr();
361 // SAFETY: the loop reads the caller's command words and writes each packet's tag
362 // and its slot entry, all covered by this function's contract; it uses only the
363 // clobbered registers.
364 unsafe {
365 core::arch::asm!(
366 ".set noreorder",
367 "lui $15, 0x00ff",
368 "ori $15, $15, 0xffff",
369 "2:",
370 "addiu $8, $8, -8",
371 "lw $11, 0($8)",
372 "lw $12, 4($8)",
373 // Fill the packet-pointer load delay while making its
374 // low-24-bit OT representation. Fill the metadata load
375 // delay before reading its slot.
376 "sll $14, $11, 8",
377 "andi $13, $12, 0xffff",
378 "srl $14, $14, 8",
379 "srl $12, $12, 24",
380 "sll $13, $13, 2",
381 "sll $12, $12, 24",
382 "addu $13, $10, $13",
383 "lw $9, 0($13)",
384 "nop",
385 "and $9, $9, $15",
386 "or $9, $9, $12",
387 "sw $9, 0($11)",
388 "sw $14, 0($13)",
389 "bne $8, $16, 2b",
390 "nop",
391 ".set reorder",
392 inout("$8") command_end => _,
393 in("$10") entries,
394 in("$16") commands,
395 lateout("$9") _,
396 lateout("$11") _,
397 lateout("$12") _,
398 lateout("$13") _,
399 lateout("$14") _,
400 lateout("$15") _,
401 options(nostack),
402 );
403 }
404 }
405
406 #[cfg(not(target_arch = "mips"))]
407 {
408 let mut index = command_count;
409 while index != 0 {
410 index -= 1;
411 // SAFETY: `index < command_count`, inside the caller's command array.
412 let command = unsafe { commands.add(index * 2) };
413 // SAFETY: the first word of each command is its packet pointer.
414 let packet_ptr =
415 ptr::with_exposed_provenance_mut::<u32>(unsafe { ptr::read(command) });
416 // SAFETY: the second word of each command is its slot and word count.
417 let slot_words = unsafe { ptr::read(command.add(1)) } as u32;
418 let slot = (slot_words & u16::MAX as u32) as usize;
419 debug_assert!(slot < N);
420 // SAFETY: the caller guarantees the packet and the slot meet
421 // `link_tag_high_unchecked`'s contract.
422 unsafe { self.link_tag_high_unchecked(slot, packet_ptr, slot_words & 0xff00_0000) };
423 }
424 }
425 }
426
427 /// Insert a contiguous stream of classic tagged GPU packets.
428 ///
429 /// Before this call, each packet tag stores its GPU data-word count in
430 /// bits 24..31 and its target OT slot in bits 0..15. Packets are walked
431 /// from `first` to `end` and prepended in that order, exactly matching a
432 /// sequence of classic `addPrim` calls. A slot value of `0xffff` skips the
433 /// packet, which lets callers keep separately ordered HUD packets in the
434 /// same arena.
435 ///
436 /// This format lets C and retained-mode renderers stage depth keys in the
437 /// packet tags without a cross-language call or a separate command array
438 /// per primitive. The final link pass remains owned by PSoXide.
439 ///
440 /// # Safety
441 /// `first..end` must be a writable, contiguous sequence of complete GPU
442 /// packets. Every packet's word count must describe the next packet
443 /// exactly and be at most [`crate::chain::MAX_NODE_WORDS`], and every
444 /// non-sentinel slot must be less than `N`.
445 #[inline]
446 pub(crate) unsafe fn link_tagged_packet_stream_unchecked(
447 &mut self,
448 first: *mut u32,
449 end: *mut u32,
450 ) {
451 if first >= end {
452 return;
453 }
454 debug_assert!(N > 0);
455
456 #[cfg(all(target_arch = "mips", feature = "asm-kernels"))]
457 {
458 // SAFETY: forwarded contract; the kernel walks `first..end` by each packet's own
459 // word count and writes only packet tags and in-range slot entries.
460 unsafe {
461 crate::asm_kernels::psx_gpu_link_tagged_stream(
462 first,
463 end,
464 self.entries.as_mut_ptr(),
465 )
466 };
467 }
468
469 #[cfg(all(target_arch = "mips", not(feature = "asm-kernels")))]
470 {
471 let entries = self.entries.as_mut_ptr();
472 // Sixteen instructions per packet, two RAM loads. Every OT slot
473 // already holds a 24-bit address with a zero top byte (`clear`,
474 // `link_unchecked*` and this loop all store masked packet
475 // addresses), so the old head needs no mask before the packet's
476 // word count is OR-ed in.
477 // SAFETY: the loop walks `first..end` by each packet's own word count, which the
478 // caller guarantees is exact, and writes only packet tags and in-range slot
479 // entries.
480 unsafe {
481 core::arch::asm!(
482 ".set noreorder",
483 // Persistent constants: low-24-bit DMA address mask, the
484 // screen-packet sentinel staged by retained callers, and
485 // the word-count byte mask.
486 "lui $15, 0x00ff",
487 "ori $15, $15, 0xffff",
488 "ori $17, $0, 0xffff",
489 "lui $18, 0xff00",
490 "2:",
491 "lw $9, 0($8)",
492 // The packet's 24-bit address fills the tag load delay.
493 "and $11, $8, $15",
494 // tag>>22 is the packet byte count excluding its tag;
495 // add four bytes while filling the sentinel branch slot.
496 "srl $10, $9, 22",
497 "andi $13, $9, 0xffff",
498 "addu $10, $8, $10",
499 "beq $13, $17, 3f",
500 "addiu $10, $10, 4",
501 // Prepend the packet to its already-bounded OT slot; the
502 // word-count mask fills the OT-head load delay.
503 "sll $13, $13, 2",
504 "addu $13, $12, $13",
505 "lw $14, 0($13)",
506 "and $9, $9, $18",
507 "or $14, $14, $9",
508 "sw $14, 0($8)",
509 "sw $11, 0($13)",
510 "3:",
511 "bne $10, $16, 2b",
512 "move $8, $10",
513 ".set reorder",
514 inout("$8") first => _,
515 in("$12") entries,
516 in("$16") end,
517 lateout("$9") _,
518 lateout("$10") _,
519 lateout("$11") _,
520 lateout("$13") _,
521 lateout("$14") _,
522 lateout("$15") _,
523 lateout("$17") _,
524 lateout("$18") _,
525 options(nostack),
526 );
527 }
528 }
529
530 #[cfg(not(target_arch = "mips"))]
531 {
532 let mut packet = first;
533 while packet < end {
534 // SAFETY: `packet` is below `end`, at a packet tag the caller vouches for.
535 let staged_tag = unsafe { ptr::read(packet) };
536 let words = (staged_tag >> 24) as usize;
537 let slot = (staged_tag & u16::MAX as u32) as usize;
538 // SAFETY: the tag's word count is exact, so this is the next packet or `end`.
539 let next = unsafe { packet.add(words + 1) };
540 if slot != u16::MAX as usize {
541 debug_assert!(slot < N);
542 // SAFETY: the caller guarantees a writable packet and an in-range slot.
543 unsafe { self.link_tag_high_unchecked(slot, packet, staged_tag & 0xff00_0000) };
544 }
545 packet = next;
546 }
547 debug_assert_eq!(packet, end);
548 }
549 }
550
551 /// Insert a tagged packet stream while quantising every non-sentinel OT
552 /// slot by a compile-time right shift.
553 ///
554 /// This preserves the packet sequence and every raw depth calculation,
555 /// but lets a caller back the final DMA chain with a smaller ordering
556 /// table. A staged slot of `0xffff` remains the screen-packet sentinel and
557 /// is skipped before the shift. For example, `SLOT_SHIFT = 3` maps the
558 /// classic 0..2047 depth range onto 256 slots.
559 ///
560 /// # Safety
561 ///
562 /// The packet lifetime and layout requirements match
563 /// [`Self::link_tagged_packet_stream_unchecked`]. Every shifted slot must
564 /// be less than `N`, and `SLOT_SHIFT` must be less than 16.
565 #[inline]
566 pub(crate) unsafe fn link_tagged_packet_stream_shifted_unchecked<const SLOT_SHIFT: u32>(
567 &mut self,
568 first: *mut u32,
569 end: *mut u32,
570 ) {
571 if first >= end {
572 return;
573 }
574 debug_assert!(N > 0);
575 debug_assert!(SLOT_SHIFT < 16);
576
577 #[cfg(target_arch = "mips")]
578 {
579 let entries = self.entries.as_mut_ptr();
580 // The `link_tagged_packet_stream_unchecked` loop with the slot
581 // shift after the sentinel test.
582 // SAFETY: the loop walks the caller's exact packet sequence and writes only tags
583 // and slot entries, which `SLOT_SHIFT` keeps below `N` per the contract.
584 unsafe {
585 core::arch::asm!(
586 ".set noreorder",
587 "lui $15, 0x00ff",
588 "ori $15, $15, 0xffff",
589 "ori $17, $0, 0xffff",
590 "lui $18, 0xff00",
591 "2:",
592 "lw $9, 0($8)",
593 "and $11, $8, $15",
594 "srl $10, $9, 22",
595 "andi $13, $9, 0xffff",
596 "addu $10, $8, $10",
597 "beq $13, $17, 3f",
598 "addiu $10, $10, 4",
599 "srl $13, $13, {slot_shift}",
600 "sll $13, $13, 2",
601 "addu $13, $12, $13",
602 "lw $14, 0($13)",
603 "and $9, $9, $18",
604 "or $14, $14, $9",
605 "sw $14, 0($8)",
606 "sw $11, 0($13)",
607 "3:",
608 "bne $10, $16, 2b",
609 "move $8, $10",
610 ".set reorder",
611 slot_shift = const SLOT_SHIFT,
612 inout("$8") first => _,
613 in("$12") entries,
614 in("$16") end,
615 lateout("$9") _,
616 lateout("$10") _,
617 lateout("$11") _,
618 lateout("$13") _,
619 lateout("$14") _,
620 lateout("$15") _,
621 lateout("$17") _,
622 lateout("$18") _,
623 options(nostack),
624 );
625 }
626 }
627
628 #[cfg(not(target_arch = "mips"))]
629 {
630 let mut packet = first;
631 while packet < end {
632 // SAFETY: `packet` is below `end`, at a packet tag the caller vouches for.
633 let staged_tag = unsafe { ptr::read(packet) };
634 let words = (staged_tag >> 24) as usize;
635 let slot = (staged_tag & u16::MAX as u32) as usize;
636 // SAFETY: the tag's word count is exact, so this is the next packet or `end`.
637 let next = unsafe { packet.add(words + 1) };
638 if slot != u16::MAX as usize {
639 let shifted_slot = slot >> SLOT_SHIFT;
640 debug_assert!(shifted_slot < N);
641 // SAFETY: the caller guarantees a writable packet and an in-range shifted
642 // slot.
643 unsafe {
644 self.link_tag_high_unchecked(shifted_slot, packet, staged_tag & 0xff00_0000)
645 };
646 }
647 packet = next;
648 }
649 debug_assert_eq!(packet, end);
650 }
651 }
652
653 /// Prepend a raw packet to slot `z` (clamped to `N - 1`).
654 ///
655 /// # Safety
656 ///
657 /// As [`OtFrame::add_raw`](crate::frame::OtFrame::add_raw).
658 #[deprecated(note = "use `OtFrame::add_raw`, through `frame()` or `resume_frame()`")]
659 #[inline(always)]
660 pub unsafe fn insert(&mut self, z: usize, packet_ptr: *mut u32, words: u8) {
661 // SAFETY: forwarded contract.
662 unsafe { self.link(z, packet_ptr, words) }
663 }
664
665 /// Prepend a raw packet to slot `z` without the clamp or length check.
666 ///
667 /// # Safety
668 ///
669 /// As [`OtFrame::add_raw_unchecked`](crate::frame::OtFrame::add_raw_unchecked).
670 #[deprecated(note = "use `OtFrame::add_raw_unchecked`, through `frame()` or `resume_frame()`")]
671 #[inline(always)]
672 pub unsafe fn insert_unchecked(&mut self, z: usize, packet_ptr: *mut u32, words: u8) {
673 // SAFETY: forwarded contract.
674 unsafe { self.link_unchecked(z, packet_ptr, words) }
675 }
676
677 /// Add packed two-word commands, last to first.
678 ///
679 /// # Safety
680 ///
681 /// As [`OtFrame::add_packed_commands_reverse_unchecked`](crate::frame::OtFrame::add_packed_commands_reverse_unchecked).
682 #[deprecated(
683 note = "use `OtFrame::add_packed_commands_reverse_unchecked`, through `frame()` or `resume_frame()`"
684 )]
685 #[inline(always)]
686 pub unsafe fn insert_packed_commands_reverse_unchecked(
687 &mut self,
688 commands: *const usize,
689 command_count: usize,
690 ) {
691 // SAFETY: forwarded contract.
692 unsafe { self.link_packed_commands_reverse_unchecked(commands, command_count) }
693 }
694
695 /// Add a contiguous stream of packets whose tags carry their slot.
696 ///
697 /// # Safety
698 ///
699 /// As [`OtFrame::add_tagged_packet_stream_unchecked`](crate::frame::OtFrame::add_tagged_packet_stream_unchecked).
700 #[deprecated(
701 note = "use `OtFrame::add_tagged_packet_stream_unchecked`, through `frame()` or `resume_frame()`"
702 )]
703 #[inline(always)]
704 pub unsafe fn insert_tagged_packet_stream_unchecked(&mut self, first: *mut u32, end: *mut u32) {
705 // SAFETY: forwarded contract.
706 unsafe { self.link_tagged_packet_stream_unchecked(first, end) }
707 }
708
709 /// End this table's DMA walk with GP0(1Fh), so the GPU raises
710 /// [`crate::is_draw_done`] once everything in the table is drawn.
711 ///
712 /// Links slot 0, the last one walked, to [`crate::chain::DRAW_DONE_NODE`];
713 /// packets inserted at slot 0 afterwards still draw before it. Call it
714 /// after every [`clear`](Self::clear) and before anything is inserted at
715 /// slot 0. Pair the submission with [`crate::arm_draw_done`].
716 ///
717 /// Host builds leave the table as it is: the shared node lives outside
718 /// the table's address window, which [`packets`](Self::packets)
719 /// relies on.
720 ///
721 /// # Panics
722 /// If slot 0 is not empty.
723 pub fn end_with_draw_done(&mut self) {
724 #[cfg(target_arch = "mips")]
725 // SAFETY: the shared node is immutable static RAM for the whole run.
726 unsafe {
727 self.end_with_node(crate::chain::DRAW_DONE_NODE.as_ptr())
728 };
729 }
730
731 /// Continue this table's walk into `head`, the first node of a chain
732 /// that ends the list itself: a command recording
733 /// (`psx_io::gpu::begin_recording_raw`) closed on [`crate::chain::DRAW_DONE_NODE`],
734 /// say, for a frame published to `psx_rt::present`.
735 ///
736 /// # Safety
737 ///
738 /// `head` must point at a 4-byte-aligned node tag in RAM, and every node
739 /// reachable from it must meet [`crate::chain::submit_async_raw`]'s
740 /// contract (at most [`crate::chain::MAX_NODE_WORDS`] payload words each, live
741 /// and unmodified) until every walk of this table has finished.
742 ///
743 /// # Panics
744 ///
745 /// If slot 0 is not empty: call it right after [`clear`](Self::clear),
746 /// before anything is inserted at slot 0.
747 #[inline]
748 pub unsafe fn end_with_chain(&mut self, head: *const u32) {
749 // SAFETY: forwarded contract.
750 unsafe { self.end_with_node(head) }
751 }
752
753 /// Link slot 0 to `node`, a node whose own link ends the list.
754 ///
755 /// # Safety
756 /// `node` must stay live and unmodified while the table is submitted.
757 pub(crate) unsafe fn end_with_node(&mut self, node: *const u32) {
758 assert!(
759 self.entries[0] == OT_END,
760 "end_with_draw_done needs an empty slot 0: call it right after clear"
761 );
762 self.entries[0] = node.expose_provenance() as u32 & OT_ADDR_MASK;
763 }
764
765 /// Pointer to the slot where DMA starts (`[N-1]`). Passed to
766 /// [`crate::chain::submit_raw`] as the linked-list entry point.
767 #[inline]
768 pub fn submit_head(&self) -> *const u32 {
769 // From the whole array, so the pointer may reach every entry.
770 self.entries.as_ptr().wrapping_add(N - 1)
771 }
772
773 /// Submit the whole table to GPU via DMA channel 2 linked-list
774 /// mode and wait for completion.
775 ///
776 /// # Safety
777 ///
778 /// As [`crate::chain::submit_raw`] for the chain this table heads:
779 /// every packet linked into it must be live and unmodified, and the
780 /// table must not have moved since it was cleared.
781 #[deprecated(
782 note = "nothing proves the linked packets are alive; use `OrderingTable::frame` and `OtFrame::submit`"
783 )]
784 pub unsafe fn submit(&self) {
785 // SAFETY: forwarded contract.
786 unsafe { crate::chain::start_walk(self.submit_head()) };
787 crate::chain::wait_walk();
788 }
789
790 /// Kick the table's DMA walk without waiting for it to finish; pair
791 /// it with [`crate::chain::wait`].
792 ///
793 /// # Safety
794 ///
795 /// As [`crate::chain::submit_async_raw`]: the table and every
796 /// packet it chains must stay live, unmoved and unmodified until that
797 /// wait returns.
798 #[deprecated(
799 note = "returns mid-walk with the table still mutable; use `OtFrame::submit_with`, `FrameStorage::draw_async` or `FramePair`"
800 )]
801 pub unsafe fn submit_async(&self) {
802 // SAFETY: forwarded contract.
803 unsafe { crate::chain::start_walk(self.submit_head()) };
804 }
805
806 /// Walk the linked chain in DMA submission order, producing one
807 /// `(packet_ptr, words)` pair per primitive packet.
808 ///
809 /// Used by the editor's host-side preview to convert an OT into a
810 /// `psx-gpu-render` command log without DMAing through real
811 /// hardware. The hardware DMA walker follows the same links in
812 /// the same order, so the iterator yields what the GPU would consume.
813 ///
814 /// A link holds only the low 24 bits of an address, as on the console.
815 /// A link into this table is read through the table; any other link is
816 /// read as an exposed address with the table's upper address bits,
817 /// which every packet in console RAM shares.
818 ///
819 /// # Safety
820 /// Every chained packet must be live for the lifetime of the
821 /// returned iterator, exactly the invariant a submission requires, and
822 /// its address must have been exposed, as every insert does.
823 pub unsafe fn packets(&self) -> Packets<'_> {
824 let table = self.entries.as_ptr();
825 Packets {
826 table,
827 table_low: table.addr() as u32 & OT_ADDR_MASK,
828 table_bytes: N * 4,
829 next: self.entries[N - 1] & OT_ADDR_MASK,
830 base_high: table.addr() & !(OT_ADDR_MASK as usize),
831 last_packet: OT_END,
832 remaining_hops: N.saturating_add(OT_MAX_EXTRA_HOPS),
833 _table: PhantomData,
834 }
835 }
836}
837
838/// Walks an [`OrderingTable`]'s chain in DMA submission order.
839///
840/// Each `next()` returns the pointer to a packet and the number of
841/// data words that follow its tag (so the full packet occupies
842/// `1 + words` u32s starting at the returned pointer). The terminal
843/// `0x00FFFFFF` marker stops iteration cleanly.
844#[derive(Debug)]
845pub struct Packets<'a> {
846 /// The table's first entry, with the table's provenance.
847 table: *const u32,
848 /// Low 24 bits of `table`'s address, as links name it.
849 table_low: u32,
850 /// Size of the table in bytes.
851 table_bytes: usize,
852 next: u32,
853 base_high: usize,
854 last_packet: u32,
855 remaining_hops: usize,
856 _table: PhantomData<&'a [u32]>,
857}
858
859impl Packets<'_> {
860 /// The word `link` names: a table entry through the table, anything
861 /// else through its exposed address.
862 fn resolve(&self, link: u32) -> *const u32 {
863 let offset = link.wrapping_sub(self.table_low) as usize;
864 if offset < self.table_bytes {
865 self.table.wrapping_byte_add(offset)
866 } else {
867 ptr::with_exposed_provenance(self.base_high | link as usize)
868 }
869 }
870}
871
872impl Iterator for Packets<'_> {
873 type Item = (*const u32, u8);
874
875 fn next(&mut self) -> Option<Self::Item> {
876 // Walk the chain, skipping empty stepping-stones -- OT slots
877 // that hold `words=0` because they were never targeted by an
878 // `insert`. The DMA hardware silently no-ops through those
879 // and only forwards entries with actual packet data, so this
880 // iterator presents the same view to the cmd-log adapter.
881 loop {
882 if self.next == OT_END {
883 return None;
884 }
885 if self.remaining_hops == 0 || self.next == self.last_packet {
886 self.next = OT_END;
887 return None;
888 }
889 self.remaining_hops -= 1;
890 let link = self.next;
891 let ptr = self.resolve(link);
892 // SAFETY: ptr was reached by walking the chain that
893 // `packets`'s caller swore was live; tag word is
894 // always present in any chained slot.
895 let tag = unsafe { ptr::read_volatile(ptr) };
896 let words = ((tag >> 24) & 0xff) as u8;
897 self.next = tag & OT_ADDR_MASK;
898 if words > 0 {
899 self.last_packet = link;
900 return Some((ptr, words));
901 }
902 }
903 }
904}
905
906/// Shows the slot count, not the `N` link words.
907impl<const N: usize> core::fmt::Debug for OrderingTable<N> {
908 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
909 f.debug_struct("OrderingTable")
910 .field("slots", &N)
911 .finish_non_exhaustive()
912 }
913}
914
915impl<const N: usize> Default for OrderingTable<N> {
916 fn default() -> Self {
917 Self::new()
918 }
919}
920
921#[cfg(all(test, not(target_arch = "mips")))]
922mod tests {
923 use super::*;
924
925 #[repr(C)]
926 struct PackedCommand {
927 /// The packet's exposed address.
928 packet: usize,
929 slot_words: usize,
930 }
931
932 #[test]
933 fn packed_reverse_insert_preserves_submission_order_within_slots() {
934 let mut ot: OrderingTable<8> = OrderingTable::new();
935 ot.clear();
936 let mut a = [0u32; 2];
937 let mut b = [0u32; 2];
938 let mut c = [0u32; 2];
939 let commands = [
940 PackedCommand {
941 packet: a.as_mut_ptr().expose_provenance(),
942 slot_words: 4 | (1 << 24),
943 },
944 PackedCommand {
945 packet: b.as_mut_ptr().expose_provenance(),
946 slot_words: 4 | (1 << 24),
947 },
948 PackedCommand {
949 packet: c.as_mut_ptr().expose_provenance(),
950 slot_words: 2 | (1 << 24),
951 },
952 ];
953
954 // SAFETY: the packets are locals that outlive every use of the table in this test, and
955 // their slots and word counts fit the table.
956 unsafe {
957 ot.link_packed_commands_reverse_unchecked(
958 commands.as_ptr().cast::<usize>(),
959 commands.len(),
960 );
961 }
962
963 // SAFETY: every packet linked into the table is a local still alive here.
964 let mut iter = unsafe { ot.packets() };
965 assert_eq!(iter.next().unwrap().0, a.as_ptr());
966 assert_eq!(iter.next().unwrap().0, b.as_ptr());
967 assert_eq!(iter.next().unwrap().0, c.as_ptr());
968 assert!(iter.next().is_none());
969 }
970
971 #[test]
972 fn packed_forward_insert_matches_repeated_prepend_semantics() {
973 let mut ot: OrderingTable<8> = OrderingTable::new();
974 ot.clear();
975 let mut a = [0u32; 2];
976 let mut b = [0u32; 2];
977 let commands = [
978 PackedCommand {
979 packet: a.as_mut_ptr().expose_provenance(),
980 slot_words: 4 | (1 << 24),
981 },
982 PackedCommand {
983 packet: b.as_mut_ptr().expose_provenance(),
984 slot_words: 4 | (1 << 24),
985 },
986 ];
987
988 // SAFETY: the packets are locals that outlive every use of the table in this test, and
989 // their slots and word counts fit the table.
990 unsafe {
991 ot.link_packed_commands_unchecked(commands.as_ptr().cast::<usize>(), commands.len());
992 }
993
994 // SAFETY: every packet linked into the table is a local still alive here.
995 let mut iter = unsafe { ot.packets() };
996 assert_eq!(iter.next().unwrap().0, b.as_ptr());
997 assert_eq!(iter.next().unwrap().0, a.as_ptr());
998 assert!(iter.next().is_none());
999 }
1000
1001 #[test]
1002 fn tagged_packet_stream_matches_prepend_and_skips_sentinel_packets() {
1003 let mut ot: OrderingTable<8> = OrderingTable::new();
1004 ot.clear();
1005 let mut packets = [
1006 (1 << 24) | 4,
1007 0xaaaa_aaaa,
1008 (2 << 24) | u16::MAX as u32,
1009 0xbbbb_bbbb,
1010 0xcccc_cccc,
1011 (1 << 24) | 4,
1012 0xdddd_dddd,
1013 ];
1014
1015 let first = packets.as_mut_ptr();
1016 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1017 // their slots and word counts fit the table.
1018 unsafe {
1019 ot.link_tagged_packet_stream_unchecked(first, first.add(packets.len()));
1020 }
1021
1022 // SAFETY: every packet linked into the table is a local still alive here.
1023 let mut iter = unsafe { ot.packets() };
1024 // SAFETY: index 5 is inside `packets`.
1025 assert_eq!(iter.next().unwrap().0, unsafe { packets.as_ptr().add(5) });
1026 assert_eq!(iter.next().unwrap().0, packets.as_ptr());
1027 assert!(iter.next().is_none());
1028 assert_eq!(packets[2] & 0x00ff_ffff, u16::MAX as u32);
1029 }
1030
1031 #[test]
1032 fn shifted_tagged_stream_quantises_slots_after_the_sentinel_test() {
1033 let mut ot: OrderingTable<4> = OrderingTable::new();
1034 ot.clear();
1035 let mut packets = [
1036 (1 << 24) | 31,
1037 0xaaaa_aaaa,
1038 (1 << 24) | u16::MAX as u32,
1039 0xbbbb_bbbb,
1040 (1 << 24) | 24,
1041 0xcccc_cccc,
1042 ];
1043
1044 // SAFETY: `packets` is one contiguous run of complete packets whose slots fit the
1045 // table.
1046 unsafe {
1047 {
1048 let first = packets.as_mut_ptr();
1049 ot.link_tagged_packet_stream_shifted_unchecked::<3>(
1050 first,
1051 first.add(packets.len()),
1052 );
1053 }
1054 }
1055
1056 // SAFETY: every packet linked into the table is a local still alive here.
1057 let mut iter = unsafe { ot.packets() };
1058 // SAFETY: index 4 is inside `packets`.
1059 assert_eq!(iter.next().unwrap().0, unsafe { packets.as_ptr().add(4) });
1060 assert_eq!(iter.next().unwrap().0, packets.as_ptr());
1061 assert!(iter.next().is_none());
1062 assert_eq!(packets[2] & OT_ADDR_MASK, u16::MAX as u32);
1063 }
1064
1065 /// Build a primitive packet by hand (one tag word + N data words),
1066 /// insert it, and walk the chain. The iterator must report the
1067 /// same `(ptr, words)` pair we inserted.
1068 #[test]
1069 fn packets_walks_a_single_inserted_primitive() {
1070 let mut ot: OrderingTable<8> = OrderingTable::new();
1071 ot.clear();
1072 // Packet layout: [tag, w0, w1, w2] -- 3 data words after the tag.
1073 let mut packet: [u32; 4] = [0; 4];
1074 packet[1] = 0xaaaa_bbbb;
1075 packet[2] = 0xcccc_dddd;
1076 packet[3] = 0xeeee_ffff;
1077 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1078 // their slots and word counts fit the table.
1079 unsafe {
1080 ot.link(2, packet.as_mut_ptr(), 3);
1081 }
1082
1083 // SAFETY: every packet linked into the table is a local still alive here.
1084 let mut iter = unsafe { ot.packets() };
1085 let entry = iter.next().expect("one entry");
1086 assert_eq!(entry.0 as usize, packet.as_ptr() as usize);
1087 assert_eq!(entry.1, 3);
1088 assert!(iter.next().is_none());
1089 }
1090
1091 /// Two primitives in different slots -- chain walks both; later
1092 /// inserts (lower slot) come first because `clear()` chains
1093 /// high-to-low and the DMA head is `[N-1]`.
1094 #[test]
1095 fn packets_walks_multiple_slots_in_dma_order() {
1096 let mut ot: OrderingTable<8> = OrderingTable::new();
1097 ot.clear();
1098 let mut a: [u32; 2] = [0, 0xa];
1099 let mut b: [u32; 2] = [0, 0xb];
1100 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1101 // their slots and word counts fit the table.
1102 unsafe {
1103 // a is in a deeper (further from camera) slot than b, so b
1104 // should appear first when walking from the head.
1105 ot.link(2, a.as_mut_ptr(), 1);
1106 ot.link(5, b.as_mut_ptr(), 1);
1107 }
1108
1109 // SAFETY: every packet linked into the table is a local still alive here.
1110 let mut iter = unsafe { ot.packets() };
1111 // DMA walker starts at [N-1] = [7] and chains down to [0].
1112 // b lives in slot 5, a in slot 2 -- both should appear, b first.
1113 let first = iter.next().expect("first entry").0 as usize;
1114 let second = iter.next().expect("second entry").0 as usize;
1115 assert!(iter.next().is_none());
1116 assert_eq!(first, b.as_ptr() as usize);
1117 assert_eq!(second, a.as_ptr() as usize);
1118 }
1119
1120 #[test]
1121 fn insert_takes_a_full_fifo_of_words() {
1122 let mut ot: OrderingTable<4> = OrderingTable::new();
1123 ot.clear();
1124 let mut packet = [0u32; 1 + crate::chain::MAX_NODE_WORDS];
1125 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1126 // their slots and word counts fit the table.
1127 unsafe { ot.link(1, packet.as_mut_ptr(), crate::chain::MAX_NODE_WORDS as u8) };
1128 assert_eq!(packet[0] >> 24, crate::chain::MAX_NODE_WORDS as u32);
1129 }
1130
1131 #[test]
1132 #[should_panic(expected = "longer than MAX_NODE_WORDS")]
1133 fn insert_refuses_a_node_longer_than_the_fifo() {
1134 let mut ot: OrderingTable<4> = OrderingTable::new();
1135 ot.clear();
1136 let mut packet = [0u32; 2 + crate::chain::MAX_NODE_WORDS];
1137 // SAFETY: the call panics on the word count before it touches the packet.
1138 unsafe {
1139 ot.link(
1140 1,
1141 packet.as_mut_ptr(),
1142 crate::chain::MAX_NODE_WORDS as u8 + 1,
1143 )
1144 };
1145 }
1146
1147 /// The draw-done node is the last thing walked, after every slot and
1148 /// after packets inserted at slot 0 once it is linked.
1149 #[test]
1150 fn end_with_node_puts_the_node_after_every_packet() {
1151 let mut ot: OrderingTable<4> = OrderingTable::new();
1152 ot.clear();
1153 let node = [(1u32 << 24) | OT_END, 0x1f00_0000];
1154 let mut far: [u32; 2] = [0, 0xf];
1155 let mut near: [u32; 2] = [0, 0xe];
1156 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1157 // their slots and word counts fit the table.
1158 unsafe {
1159 ot.end_with_node(node.as_ptr());
1160 ot.link(0, far.as_mut_ptr(), 1);
1161 ot.link(3, near.as_mut_ptr(), 1);
1162 }
1163 let walked: [usize; 3] = {
1164 // SAFETY: every packet linked into the table is a local still alive here.
1165 let mut iter = unsafe { ot.packets() };
1166 let order = [
1167 iter.next().expect("near").0 as usize,
1168 iter.next().expect("far").0 as usize,
1169 iter.next().expect("node").0 as usize,
1170 ];
1171 assert!(iter.next().is_none());
1172 order
1173 };
1174 assert_eq!(
1175 walked,
1176 [
1177 near.as_ptr() as usize,
1178 far.as_ptr() as usize,
1179 node.as_ptr() as usize
1180 ]
1181 );
1182 }
1183
1184 #[test]
1185 #[should_panic(expected = "empty slot 0")]
1186 fn end_with_node_refuses_a_used_slot_0() {
1187 let mut ot: OrderingTable<4> = OrderingTable::new();
1188 ot.clear();
1189 let node = [(1u32 << 24) | OT_END, 0x1f00_0000];
1190 let mut packet: [u32; 2] = [0, 0xf];
1191 // SAFETY: the packet and the node are locals that outlive the table's use.
1192 unsafe {
1193 ot.link(0, packet.as_mut_ptr(), 1);
1194 ot.end_with_node(node.as_ptr());
1195 }
1196 }
1197
1198 #[test]
1199 fn the_shared_draw_done_node_is_one_gp0_1f_word_then_the_end() {
1200 // SAFETY: the node is two words of immutable static data.
1201 let node = unsafe { core::slice::from_raw_parts(crate::chain::DRAW_DONE_NODE.as_ptr(), 2) };
1202 assert_eq!(node[0] >> 24, 1);
1203 assert_eq!(node[0] & OT_ADDR_MASK, OT_END);
1204 assert_eq!(node[1], psx_hw::gpu::gp0::REQUEST_IRQ);
1205 assert_eq!(node[1] >> 24, 0x1f);
1206 }
1207
1208 /// Multiple primitives in the same slot chain via the most-
1209 /// recently-inserted-first rule.
1210 #[test]
1211 fn packets_chains_primitives_within_one_slot() {
1212 let mut ot: OrderingTable<4> = OrderingTable::new();
1213 ot.clear();
1214 let mut first: [u32; 2] = [0, 0x1111];
1215 let mut second: [u32; 2] = [0, 0x2222];
1216 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1217 // their slots and word counts fit the table.
1218 unsafe {
1219 ot.link(1, first.as_mut_ptr(), 1);
1220 ot.link(1, second.as_mut_ptr(), 1);
1221 }
1222
1223 // SAFETY: every packet linked into the table is a local still alive here.
1224 let mut iter = unsafe { ot.packets() };
1225 // `second` was inserted last and prepends to the chain head;
1226 // it walks first.
1227 let head = iter.next().expect("first").0 as usize;
1228 let tail = iter.next().expect("second").0 as usize;
1229 assert!(iter.next().is_none());
1230 assert_eq!(head, second.as_ptr() as usize);
1231 assert_eq!(tail, first.as_ptr() as usize);
1232 }
1233
1234 /// Re-inserting the same packet is an invalid OT chain because
1235 /// the packet only has one tag word to store its next pointer.
1236 /// The host iterator should fail closed instead of spinning
1237 /// forever while previewing a malformed frame.
1238 #[test]
1239 fn packets_stops_on_duplicate_packet_in_same_slot() {
1240 let mut ot: OrderingTable<4> = OrderingTable::new();
1241 ot.clear();
1242 let mut packet: [u32; 2] = [0, 0xaa00_0000];
1243 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1244 // their slots and word counts fit the table.
1245 unsafe {
1246 ot.link(1, packet.as_mut_ptr(), 1);
1247 ot.link(1, packet.as_mut_ptr(), 1);
1248 }
1249
1250 // SAFETY: every packet linked into the table is a local still alive here.
1251 let mut iter = unsafe { ot.packets() };
1252 let entry = iter.next().expect("first duplicate packet");
1253 assert_eq!(entry.0 as usize, packet.as_ptr() as usize);
1254 assert_eq!(entry.1, 1);
1255 assert!(iter.next().is_none());
1256 }
1257
1258 /// A duplicate packet can also form a two-hop cycle through an
1259 /// empty OT slot when it is inserted into different slots. This
1260 /// catches the editor-preview failure mode where the cmd-log walk
1261 /// could peg the host thread.
1262 #[test]
1263 fn packets_stops_on_duplicate_packet_through_empty_slot() {
1264 let mut ot: OrderingTable<4> = OrderingTable::new();
1265 ot.clear();
1266 let mut packet: [u32; 2] = [0, 0xbb00_0000];
1267 // SAFETY: the packets are locals that outlive every use of the table in this test, and
1268 // their slots and word counts fit the table.
1269 unsafe {
1270 ot.link(1, packet.as_mut_ptr(), 1);
1271 ot.link(2, packet.as_mut_ptr(), 1);
1272 }
1273
1274 // SAFETY: every packet linked into the table is a local still alive here.
1275 let mut iter = unsafe { ot.packets() };
1276 let entry = iter.next().expect("first duplicate packet");
1277 assert_eq!(entry.0 as usize, packet.as_ptr() as usize);
1278 assert_eq!(entry.1, 1);
1279 assert!(iter.next().is_none());
1280 }
1281}