Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_io/
dma.rs

1//! DMA controller.
2//!
3//! The PS1 has 7 DMA channels (MDEC in, MDEC out, GPU, CD-ROM, SPU,
4//! expansion, ordering-table clear). Each channel has an address, a size and
5//! a control register at fixed 16-byte strides, plus a global enable and a
6//! global interrupt register. The addresses and bit layouts live in
7//! [`psx_hw::dma`].
8
9use crate::periph::{OrderingTableClearDma, SpuDma};
10use psx_hw::dma as reg;
11
12/// Channel index 0..=6 in the order the DMA controller presents them.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14#[repr(u8)]
15pub enum Channel {
16    /// RAM→MDEC: run-length coefficient data *into* the decoder. This is
17    /// the direction the name refers to, not the direction of transfer to
18    /// RAM -- channel 0 feeds the MDEC, channel 1 drains it.
19    MdecIn = 0,
20    /// MDEC→RAM: decoded macroblocks *out of* the decoder, 256 pixels
21    /// (16x16) per macroblock at 15bpp.
22    MdecOut = 1,
23    /// RAM↔GPU.
24    Gpu = 2,
25    /// CD-ROM drive → RAM.
26    #[doc(alias = "CDROM")]
27    Cd = 3,
28    /// SPU ↔ RAM.
29    Spu = 4,
30    /// Expansion port.
31    #[doc(alias = "PIO")]
32    Expansion = 5,
33    /// Ordering-table clear: writes a reverse-linked empty ordering table.
34    #[doc(alias = "OTC")]
35    OrderingTableClear = 6,
36}
37
38#[allow(non_upper_case_globals)]
39impl Channel {
40    /// Renamed to [`Channel::Cd`].
41    #[deprecated(note = "renamed to `Channel::Cd`")]
42    pub const Cdrom: Channel = Channel::Cd;
43}
44
45impl Channel {
46    /// Address of this channel's register block.
47    #[inline(always)]
48    pub const fn register_base(self) -> u32 {
49        reg::CHANNEL_BASE + reg::CHANNEL_STRIDE * (self as u32)
50    }
51
52    /// Bit position of this channel's enable flag in the global enable
53    /// register.
54    #[doc(alias = "DPCR")]
55    #[inline(always)]
56    pub const fn enable_bit(self) -> u32 {
57        3 + 4 * (self as u32)
58    }
59}
60
61/// Size word for manual or linked-list sync: a 16-bit word count
62/// (linked-list mode ignores it, but silicon wants it written).
63#[doc(alias = "BCR")]
64#[inline(always)]
65pub const fn size_words(words: u16) -> u32 {
66    words as u32
67}
68
69/// Size word for block sync: `block_count` blocks of `block_size` words.
70///
71/// A zero field means 0x1_0000 on silicon, so a zero count is a 65,536-block
72/// transfer, not an empty one. The same goes for a count the controller has
73/// already counted down: silicon decrements the block field as blocks finish
74/// and leaves 0 behind, so the value is spent by the kick it armed. Store a
75/// fresh one before every block-sync kick ([`start`] does).
76#[doc(alias = "BCR")]
77#[inline(always)]
78pub const fn size_blocks(block_size: u16, block_count: u16) -> u32 {
79    (block_size as u32) | ((block_count as u32) << 16)
80}
81
82/// The three per-channel register values that describe one transfer.
83///
84/// [`start`] stores them in the order silicon expects: address, size, then
85/// control (which starts the transfer when it carries `CHCR_START`).
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Transfer {
88    /// RAM address the channel reads from or writes to.
89    #[doc(alias = "MADR")]
90    pub address: u32,
91    /// Word or block count; see [`size_words`] and [`size_blocks`].
92    #[doc(alias = "BCR")]
93    pub size: u32,
94    /// Control word ([`psx_hw::dma`]'s `CHCR_*` bits): direction, step, sync
95    /// mode, start.
96    #[doc(alias = "CHCR")]
97    pub control: u32,
98}
99
100/// Program channel `ch` with `transfer` and start it.
101///
102/// The same three stores every SDK driver makes: address, size, a
103/// compiler-only barrier that publishes ordinary RAM stores made before the
104/// call (it emits no instruction), then control. The caller still enables
105/// the channel ([`enable_channel`]) and waits for completion ([`wait_done`]).
106///
107/// All three are stored on every call, and that is load-bearing for block
108/// sync: silicon counts the size register's block field down to 0 as the
109/// transfer runs, so a second kick that relied on the first call's size would
110/// run 65,536 blocks. Call `start` again, with the size, for each block kick.
111///
112/// # Safety
113///
114/// From the control store until the channel goes idle ([`wait_done`]
115/// returns `true`, or [`abort`] stops it), the DMA controller reads or writes
116/// RAM with no regard for Rust's borrow rules. The caller must guarantee that
117/// for that whole window:
118///
119/// - every word the transfer can **write** (a device-to-RAM channel, such
120///   as MDEC-out, CD-ROM, GPU readback or the ordering-table clear) lies in
121///   memory the caller owns exclusively, with no live Rust reference to it;
122/// - every word the transfer can **read** (a RAM-to-device channel, or each
123///   node of a linked list and the nodes its tags link to) is live,
124///   initialised and not written by anyone else;
125/// - the extent is the one `size` and the sync mode describe, remembering
126///   that a zero block count means 65,536 blocks;
127/// - the channel is idle when this is called (silicon ignores a control
128///   write to a busy channel, so the old transfer would keep running).
129#[inline(always)]
130pub unsafe fn start(ch: Channel, transfer: Transfer) {
131    crate::diag::dma_kick(ch as u32);
132    #[cfg(feature = "console-diag")]
133    if matches!(ch, Channel::Gpu)
134        && transfer.control & psx_hw::dma::CHCR_SYNC_LINKED == psx_hw::dma::CHCR_SYNC_LINKED
135    {
136        crate::diag::ll_scan(transfer.address);
137    }
138    // SAFETY: the caller upholds this function's contract for the transfer
139    // these three stores arm and start.
140    unsafe {
141        raw::set_address(ch, transfer.address);
142        raw::set_size(ch, transfer.size);
143    }
144    compiler_barrier();
145    // SAFETY: as above.
146    unsafe { raw::set_control(ch, transfer.control) };
147}
148
149/// Compiler-only barrier: ordinary RAM accesses are not moved across it in
150/// either direction, so stores before it land before an MMIO store after it
151/// and accesses after it follow an MMIO read before it.
152///
153/// The pinned MIPS-I backend lowers even a single-thread compiler fence to
154/// `SYNC`, which the R3000 lacks, so the target uses an empty `asm!` with its
155/// default memory clobber. Do not add `nomem` or `readonly`: both would drop
156/// the guarantee.
157#[inline(always)]
158pub fn compiler_barrier() {
159    #[cfg(target_arch = "mips")]
160    // SAFETY: an empty asm block; it only constrains compiler ordering.
161    unsafe {
162        core::arch::asm!("", options(nostack, preserves_flags));
163    }
164    #[cfg(not(target_arch = "mips"))]
165    core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
166}
167
168/// Single-register writes for silicon probes and drivers that need a store
169/// order other than [`start`]'s.
170pub mod raw {
171    use super::{reg, Channel};
172
173    /// Write the channel's RAM address register.
174    ///
175    /// # Safety
176    ///
177    /// The value arms the next transfer on `ch`: the caller takes on
178    /// [`super::start`]'s contract for whatever transfer later starts with it.
179    ///
180    /// With the `present-queue` feature, a store to the GPU channel first
181    /// runs an armed direct-access guard (`gpu::arm_direct_access_guard`),
182    /// so it never re-arms the channel under a queued walk. Every GPU DMA
183    /// start, [`super::start`] included, goes through here.
184    #[doc(alias = "MADR")]
185    #[inline(always)]
186    pub unsafe fn set_address(ch: Channel, addr: u32) {
187        #[cfg(feature = "present-queue")]
188        if matches!(ch, Channel::Gpu) {
189            crate::gpu::run_direct_access_guard();
190        }
191        // SAFETY: a store to this channel's address register; see the contract above.
192        unsafe { crate::write_u32(ch.register_base() + reg::MADR, addr) }
193    }
194
195    /// Write the channel's size register.
196    ///
197    /// # Safety
198    ///
199    /// As [`set_address`]: the count sets the extent of the next transfer.
200    ///
201    /// In block sync (`CHCR_SYNC_BLOCK`) silicon decrements the block count as
202    /// blocks finish, so this store arms exactly one kick: write it again
203    /// before each later block-sync kick, or the second runs 65,536 blocks.
204    #[doc(alias = "BCR")]
205    #[inline(always)]
206    pub unsafe fn set_size(ch: Channel, value: u32) {
207        // SAFETY: a store to this channel's size register; see the contract above.
208        unsafe { crate::write_u32(ch.register_base() + reg::BCR, value) }
209    }
210
211    /// Write the channel's control register. With `CHCR_START` set this
212    /// starts a transfer from whatever the address and size registers hold.
213    /// For a block-sync kick that holds only once per size store, because the
214    /// transfer spends the block count (see [`set_size`]).
215    ///
216    /// # Safety
217    ///
218    /// A value with `CHCR_START` set must satisfy [`super::start`]'s contract
219    /// for the transfer it starts. A value without it (such as 0, an abort)
220    /// starts nothing.
221    #[doc(alias = "CHCR")]
222    #[inline(always)]
223    pub unsafe fn set_control(ch: Channel, value: u32) {
224        // SAFETY: a store to this channel's control register; see the contract above.
225        unsafe { crate::write_u32(ch.register_base() + reg::CHCR, value) }
226    }
227}
228
229/// Write the channel's RAM address register.
230///
231/// # Safety
232///
233/// The value arms or starts a transfer on `ch`; see [`start`]'s contract.
234#[deprecated(
235    note = "a safe address store lets safe code aim DMA anywhere in RAM; use the unsafe `dma::start`, or `dma::raw::set_address` for probes"
236)]
237#[inline(always)]
238pub unsafe fn set_madr(ch: Channel, addr: u32) {
239    // SAFETY: forwarded contract.
240    unsafe { raw::set_address(ch, addr) }
241}
242
243/// Read the channel's RAM address register.
244#[doc(alias = "MADR")]
245#[inline(always)]
246pub fn address(ch: Channel) -> u32 {
247    // SAFETY: a side-effect-free read of this channel's address register.
248    unsafe { crate::read_u32(ch.register_base() + reg::MADR) }
249}
250
251/// Write the size register in manual / linked-list mode: just a 16-bit word
252/// count.
253///
254/// # Safety
255///
256/// The value arms or starts a transfer on `ch`; see [`start`]'s contract.
257#[deprecated(
258    note = "use the unsafe `dma::start` with `dma::size_words`, or `dma::raw::set_size` for probes"
259)]
260#[inline(always)]
261pub unsafe fn set_bcr_manual(ch: Channel, words: u16) {
262    // SAFETY: forwarded contract.
263    unsafe { raw::set_size(ch, size_words(words)) }
264}
265
266/// Write the control register. Starts the transfer if `CHCR_START` is set.
267///
268/// # Safety
269///
270/// The value arms or starts a transfer on `ch`; see [`start`]'s contract.
271#[deprecated(
272    note = "a safe control store starts DMA from safe code; use the unsafe `dma::start`, `dma::abort` to stop a channel, or `dma::raw::set_control` for probes"
273)]
274#[inline(always)]
275pub unsafe fn set_chcr(ch: Channel, value: u32) {
276    // SAFETY: forwarded contract.
277    unsafe { raw::set_control(ch, value) }
278}
279
280/// Read the channel's control register.
281#[doc(alias = "CHCR")]
282#[inline(always)]
283pub fn control(ch: Channel) -> u32 {
284    // SAFETY: a side-effect-free read of this channel's control register.
285    unsafe { crate::read_u32(ch.register_base() + reg::CHCR) }
286}
287
288/// True while the channel is busy with an in-flight transfer.
289#[inline(always)]
290pub fn is_busy(ch: Channel) -> bool {
291    control(ch) & reg::CHCR_START != 0
292}
293
294/// Enable a channel without disturbing the others.
295///
296/// The read-modify-write of the global enable register runs with CPU
297/// interrupts masked: with the `present-queue` feature the VBlank handler
298/// sets the GPU channel's bit in the same register, and a handler that ran
299/// between this read and write would have its bit overwritten.
300pub fn enable_channel(ch: Channel) {
301    crate::irq::without_interrupts(|| {
302        // SAFETY: a side-effect-free read of the global enable register.
303        let enabled = unsafe { crate::read_u32(reg::DPCR) };
304        // SAFETY: sets one channel's enable bit and keeps the rest; enabling a
305        // channel starts no transfer.
306        unsafe { crate::write_u32(reg::DPCR, enabled | (1 << ch.enable_bit())) }
307    });
308}
309
310impl OrderingTableClearDma {
311    /// Ordering-table clear: writes `buf` as a reverse-linked chain the
312    /// GPU-DMA walker consumes. The hardware starts from the last word and
313    /// steps backward, writing a terminator at the first transfer and then
314    /// predecessor pointers.
315    ///
316    /// Convenience wrapper: programs the channel and blocks until done.
317    /// Returns false if the channel wedged, or if `buf` is longer than the
318    /// 16-bit word count can express.
319    #[doc(alias = "ClearOTagR")]
320    pub fn clear_table(&mut self, buf: &mut [u32]) -> bool {
321        clear_table(buf)
322    }
323}
324
325/// [`OrderingTableClearDma::clear_table`] on a token the caller does not hold.
326#[deprecated(note = "use `OrderingTableClearDma::clear_table` with the token")]
327#[inline(always)]
328pub fn clear_ordering_table(buf: &mut [u32]) -> bool {
329    // SAFETY: a token is a logic guard, not a memory-safety one (see
330    // `crate::periph`), and the old function never took one.
331    unsafe { OrderingTableClearDma::steal() }.clear_table(buf)
332}
333
334fn clear_table(buf: &mut [u32]) -> bool {
335    let Ok(words) = u16::try_from(buf.len()) else {
336        // Truncating to 16 bits would clear only the tail of the table
337        // and leave the head pointing into words the DMA never touched.
338        return false;
339    };
340    let Some(last) = buf.last_mut() else {
341        return true;
342    };
343    let last_addr = last as *mut u32 as u32;
344    // Abort whatever the channel was doing before arming it. On silicon a
345    // transfer that never completes leaves START latched, and a write to
346    // the control register while the channel is still busy is ignored: one
347    // stuck kick then poisons every later transfer on that channel, which is
348    // how a single wedge turned into "the DMA moves nothing, forever" across
349    // the CD reader, the ordering-table clear, and the boot uploads.
350    abort(Channel::OrderingTableClear);
351    enable_channel(Channel::OrderingTableClear);
352    // Ordering-table clear: direction backward (step -4), manual sync,
353    // trigger bit.
354    // SAFETY: the channel was just aborted, so it is idle. The transfer
355    // writes `words` words stepping back from `last_addr`, which is exactly
356    // `buf`, borrowed exclusively until this function returns. It cannot
357    // outlive that borrow, and this does not rest on what an abort does:
358    // DMA6 has only CHCR bits 24, 28 and 30 writable, so it always runs in
359    // burst mode (SyncMode 0) without chopping, and psx-spx ("DMA Channels",
360    // "CPU Operation during DMA") documents that any RAM or I/O read stalls
361    // the CPU until such a transfer is finished, allowing only I/O reads
362    // within 3 cycles of the CHCR write. The wait below reads CHCR until it
363    // reads idle or its budget ends, so by the time it returns the transfer
364    // has finished or, wedged with START latched, never ran.
365    unsafe {
366        start(
367            Channel::OrderingTableClear,
368            Transfer {
369                address: last_addr,
370                size: size_words(words),
371                control: reg::CHCR_STEP_BACKWARD
372                    | reg::CHCR_SYNC_MANUAL
373                    | reg::CHCR_START
374                    | reg::CHCR_TRIGGER,
375            },
376        )
377    };
378    // A wedge is aborted, which leaves the controller usable for the next
379    // caller rather than handing back a channel that will swallow its kick.
380    wait_or_abort(Channel::OrderingTableClear, DEFAULT_SPINS)
381}
382
383impl SpuDma {
384    /// Copy `words` to the SPU over DMA channel 4, in blocks of `block_words`
385    /// words, and wait for the channel to finish.
386    ///
387    /// Enables the channel without disturbing the others, starts a block-sync
388    /// transfer, and ends it with [`wait_or_abort`], so the SPU has taken
389    /// every word or the channel has been aborted by the time this returns.
390    /// The caller has already put the SPU in its DMA-write transfer mode.
391    ///
392    /// Returns `false` without starting anything when `words` is empty (a zero
393    /// block count means 65,536 blocks on silicon), when `block_words` is 0 or
394    /// does not divide the length, or when the block count does not fit the
395    /// 16-bit field; and `false` when the channel wedged and was aborted.
396    pub fn write_blocks(&mut self, words: &[u32], block_words: u16) -> bool {
397        let block = usize::from(block_words);
398        if words.is_empty() || block == 0 || !words.len().is_multiple_of(block) {
399            return false;
400        }
401        let Ok(block_count) = u16::try_from(words.len() / block) else {
402            return false;
403        };
404        enable_channel(Channel::Spu);
405        // SAFETY: the transfer reads `block_words * block_count` words from
406        // `words`, which is exactly the slice (a whole number of non-empty
407        // blocks, checked above), borrowed until this function returns. The
408        // wait below, or its abort on a wedge, ends the transfer before then.
409        unsafe {
410            start(
411                Channel::Spu,
412                Transfer {
413                    address: words.as_ptr() as u32,
414                    size: size_blocks(block_words, block_count),
415                    control: reg::CHCR_TO_DEVICE | reg::CHCR_SYNC_BLOCK | reg::CHCR_START,
416                },
417            )
418        };
419        wait_or_abort(Channel::Spu, DEFAULT_SPINS)
420    }
421}
422
423/// Spin budget for one DMA completion wait. Comfortably longer than the
424/// largest legitimate transfer (a full-screen VRAM upload) and short
425/// enough that a wedged channel returns control inside a frame.
426pub const DEFAULT_SPINS: u32 = 500_000;
427
428/// Clear `ch`'s control register, dropping its START bit, so the channel can
429/// be re-armed: on silicon a CHCR write to a channel whose START is still
430/// latched is ignored, which is how one wedged kick used to poison every
431/// later transfer on the channel.
432///
433/// psx-spx documents only that START clears when a transfer completes, not
434/// that clearing it stops one in progress. Code whose memory safety needs a
435/// transfer to have stopped must not rely on this call for it; see
436/// [`OrderingTableClearDma::clear_table`] for a bound that does not.
437pub fn abort(ch: Channel) {
438    // SAFETY: a control word of 0 has no START bit, so it starts nothing.
439    unsafe { raw::set_control(ch, 0) };
440}
441
442/// Bounded completion wait. `false` means the channel was still busy
443/// when the budget ran out, i.e. the transfer is wedged and the caller
444/// must not assume its data landed.
445pub fn wait_done(ch: Channel, spins: u32) -> bool {
446    let mut waited = 0u32;
447    let which = ch as u32;
448    crate::diag::wait_begin(crate::diag::site::DMA_DONE + which, which);
449    while is_busy(ch) {
450        if waited >= spins {
451            crate::diag::wait_timeout(crate::diag::site::DMA_DONE + which, which, spins);
452            return false;
453        }
454        waited += 1;
455    }
456    crate::diag::wait_end();
457    true
458}
459
460/// End a transfer started with [`start`]: [`wait_done`]; if the budget runs
461/// out, [`abort`] the channel and wait again, within the same budget, for it
462/// to read idle; then a compiler barrier so the caller's next RAM access to
463/// the buffer is not moved before the completion read (the barrier emits no
464/// instruction). `false` means the data did not all land.
465///
466/// The second wait is there because clearing START is not documented to stop
467/// a running transfer (see [`abort`]). What it leaves assumed: a channel that
468/// still reads busy after both budgets is wedged and moving no data, as the
469/// CD channel's console wedges were (START latched, MADR frozen). Burst-mode
470/// channels without chopping need no assumption; see
471/// [`OrderingTableClearDma::clear_table`].
472pub fn wait_or_abort(ch: Channel, spins: u32) -> bool {
473    let done = wait_done(ch, spins);
474    if !done {
475        abort(ch);
476        let _ = wait_done(ch, spins);
477    }
478    compiler_barrier();
479    done
480}
481
482#[cfg(test)]
483mod tests {
484    extern crate std;
485    use super::*;
486
487    #[test]
488    fn block_size_packs_size_low_and_count_high() {
489        assert_eq!(size_blocks(16, 3), 0x0003_0010);
490        assert_eq!(size_blocks(0xffff, 0xffff), 0xffff_ffff);
491        assert_eq!(size_words(0x1234), 0x1234);
492    }
493
494    #[test]
495    fn channel_blocks_sit_at_sixteen_byte_strides() {
496        assert_eq!(Channel::MdecIn.register_base(), reg::CHANNEL_BASE);
497        assert_eq!(
498            Channel::Gpu.register_base(),
499            reg::CHANNEL_BASE + 2 * reg::CHANNEL_STRIDE
500        );
501        assert_eq!(
502            Channel::OrderingTableClear.register_base(),
503            reg::CHANNEL_BASE + 6 * reg::CHANNEL_STRIDE
504        );
505        assert_eq!(Channel::OrderingTableClear.enable_bit(), 27);
506    }
507
508    #[test]
509    fn an_spu_write_refuses_a_shape_it_cannot_describe_before_touching_the_channel() {
510        // SAFETY: a test-local token on the host; every call below returns
511        // before any register is touched.
512        let mut dma = unsafe { SpuDma::steal() };
513        let words = std::vec![0u32; 12];
514        // Nothing to send: a zero block count would be 65,536 blocks.
515        assert!(!dma.write_blocks(&[], 4));
516        // No block size, or one that leaves a partial block.
517        assert!(!dma.write_blocks(&words, 0));
518        assert!(!dma.write_blocks(&words, 5));
519        // More blocks than the 16-bit count holds.
520        let long = std::vec![0u32; 65_536];
521        assert!(!dma.write_blocks(&long, 1));
522    }
523
524    #[test]
525    fn the_clear_refuses_a_table_it_cannot_describe_before_touching_the_channel() {
526        // SAFETY: a test-local token on the host; both calls return before any
527        // register is touched.
528        let mut dma = unsafe { OrderingTableClearDma::steal() };
529        // An empty table has nothing to clear.
530        assert!(dma.clear_table(&mut []));
531        // 65,536 words does not fit the 16-bit count: refused whole, not
532        // truncated to its tail.
533        let mut long = std::vec![0u32; 65_536];
534        assert!(!dma.clear_table(&mut long));
535    }
536}