1use core::marker::PhantomData;
56use psx_io::periph::{Cd, GpuDma, MdecDma, OrderingTableClearDma, SpuDma};
57
58const DMA_IDLE_SPINS: u32 = 1_000_000;
61
62const KICK_RETRIES: u32 = 4;
65
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct QuiesceReport {
69 pub busy_at_entry: bool,
71 pub retries: u32,
74 pub spins: u32,
76 pub timed_out: bool,
78}
79
80trait Bus {
82 fn dma_busy(&mut self) -> bool;
84 fn irq_off(&mut self) -> bool;
86 fn irq_restore(&mut self, was_enabled: bool);
88}
89
90fn spin_until_idle(bus: &mut impl Bus, limit: u32, spins: &mut u32) -> bool {
92 let mut n = 0u32;
93 while bus.dma_busy() {
94 n += 1;
95 *spins = spins.saturating_add(1);
96 if n >= limit {
97 return false;
98 }
99 }
100 true
101}
102
103fn run_when_dma_idle<B: Bus, R>(
109 bus: &mut B,
110 limit: u32,
111 run: impl FnOnce(QuiesceReport) -> R,
112) -> (R, QuiesceReport) {
113 let mut report = QuiesceReport {
114 busy_at_entry: bus.dma_busy(),
115 ..QuiesceReport::default()
116 };
117 let mut tries = 0u32;
118 loop {
119 let idle = spin_until_idle(bus, limit, &mut report.spins);
120 let was = bus.irq_off();
121 if !idle {
122 report.timed_out = true;
124 let r = run(report);
125 bus.irq_restore(was);
126 return (r, report);
127 }
128 if !bus.dma_busy() {
129 let r = run(report);
130 bus.irq_restore(was);
131 return (r, report);
132 }
133 if tries >= KICK_RETRIES {
134 report.timed_out = !spin_until_idle(bus, limit, &mut report.spins);
135 let r = run(report);
136 bus.irq_restore(was);
137 return (r, report);
138 }
139 bus.irq_restore(was);
140 tries += 1;
141 report.retries += 1;
142 }
143}
144
145pub struct DmaOwners<'a> {
152 _gpu: &'a mut GpuDma,
153 _otc: &'a mut OrderingTableClearDma,
154 _mdec: &'a mut MdecDma,
155 _spu: &'a mut SpuDma,
156 _cd: &'a mut Cd,
157}
158
159impl<'a> DmaOwners<'a> {
160 pub fn new(
165 gpu: &'a mut GpuDma,
166 otc: &'a mut OrderingTableClearDma,
167 mdec: &'a mut MdecDma,
168 spu: &'a mut SpuDma,
169 cd: &'a mut Cd,
170 ) -> Self {
171 Self {
172 _gpu: gpu,
173 _otc: otc,
174 _mdec: mdec,
175 _spu: spu,
176 _cd: cd,
177 }
178 }
179}
180
181pub struct Quiesced<'a> {
185 _owners: DmaOwners<'a>,
186 report: QuiesceReport,
187 _not_send: PhantomData<*mut ()>,
188}
189
190impl Quiesced<'_> {
191 pub fn report(&self) -> QuiesceReport {
193 self.report
194 }
195
196 #[doc(alias = "FlushCache")]
201 pub fn flush_icache(&mut self) {
202 raw::flush_all();
203 }
204
205 pub fn flush_icache_range(&mut self, start: u32, end: u32) {
210 if end.wrapping_sub(start) >= 0x1000 {
211 raw::flush_all();
212 } else {
213 raw::flush_range(start, end);
214 }
215 }
216}
217
218pub fn with_dma_quiesced<R>(owners: DmaOwners<'_>, f: impl FnOnce(&mut Quiesced<'_>) -> R) -> R {
256 let mut bus = HwBus;
257 let (r, report) = run_when_dma_idle(&mut bus, DMA_IDLE_SPINS, |report| {
258 let mut quiesced = Quiesced {
259 _owners: owners,
260 report,
261 _not_send: PhantomData,
262 };
263 diag_enter();
264 f(&mut quiesced)
265 });
266 diag_exit(report);
267 r
268}
269
270#[inline(never)]
276#[doc(alias = "FlushCache")]
277pub fn flush_instruction_cache() {
278 with_internal_owners(|q| q.flush_icache());
279}
280
281#[inline(never)]
284pub fn flush_instruction_cache_range(start: u32, end: u32) {
285 with_internal_owners(|q| q.flush_icache_range(start, end));
286}
287
288fn with_internal_owners(f: impl FnOnce(&mut Quiesced<'_>)) {
290 let (mut gpu, mut otc, mut mdec, mut spu, mut cd) = unsafe {
294 (
295 GpuDma::steal(),
296 OrderingTableClearDma::steal(),
297 MdecDma::steal(),
298 SpuDma::steal(),
299 Cd::steal(),
300 )
301 };
302 with_dma_quiesced(
303 DmaOwners::new(&mut gpu, &mut otc, &mut mdec, &mut spu, &mut cd),
304 f,
305 );
306}
307
308#[deprecated(note = "renamed to `flush_instruction_cache`")]
310#[inline(always)]
311pub fn flush_i_cache() {
312 flush_instruction_cache()
313}
314
315#[cfg(target_arch = "mips")]
320#[allow(
321 dead_code,
322 reason = "only the stop-panel reads these two; the handler always uses the bit"
323)]
324pub(crate) const RUNNING_SETTING: u32 = psx_hw::memory::cache_control::RUNNING;
325
326#[cfg(target_arch = "mips")]
328#[allow(
329 dead_code,
330 reason = "only the stop-panel reads these two; the handler always uses the bit"
331)]
332pub(crate) const ISOLATE_CACHE_BIT: u32 = 1 << 16;
333
334#[cfg(target_arch = "mips")]
336#[allow(
337 dead_code,
338 reason = "only the stop-panel reads these two; the handler always uses the bit"
339)]
340pub(crate) const CONTROL_ADDRESS: u32 = psx_hw::memory::cache_control::ADDR;
341
342#[cfg(target_arch = "mips")]
343struct HwBus;
344
345#[cfg(target_arch = "mips")]
346impl Bus for HwBus {
347 fn dma_busy(&mut self) -> bool {
348 use psx_io::dma::{is_busy, Channel};
349 is_busy(Channel::Gpu)
350 || is_busy(Channel::Cd)
351 || is_busy(Channel::Spu)
352 || is_busy(Channel::MdecIn)
353 || is_busy(Channel::MdecOut)
354 || is_busy(Channel::OrderingTableClear)
355 || is_busy(Channel::Expansion)
356 }
357
358 fn irq_off(&mut self) -> bool {
359 unsafe { crate::critical_section::acquire() }.was_enabled()
361 }
362
363 fn irq_restore(&mut self, was_enabled: bool) {
364 unsafe {
366 crate::critical_section::release(crate::critical_section::RestoreState::from_enabled(
367 was_enabled,
368 ));
369 }
370 }
371}
372
373#[cfg(not(target_arch = "mips"))]
375struct HwBus;
376
377#[cfg(not(target_arch = "mips"))]
378impl Bus for HwBus {
379 fn dma_busy(&mut self) -> bool {
380 false
381 }
382
383 fn irq_off(&mut self) -> bool {
384 unsafe { crate::critical_section::acquire() }.was_enabled()
386 }
387
388 fn irq_restore(&mut self, was_enabled: bool) {
389 unsafe {
391 crate::critical_section::release(crate::critical_section::RestoreState::from_enabled(
392 was_enabled,
393 ));
394 }
395 }
396}
397
398#[inline(always)]
400fn diag_enter() {
401 #[cfg(all(feature = "console-diag", target_arch = "mips"))]
402 {
403 use psx_io::dma::{control, Channel};
404 let chcr = [
405 control(Channel::MdecIn),
406 control(Channel::MdecOut),
407 control(Channel::Gpu),
408 control(Channel::Cd),
409 control(Channel::Spu),
410 control(Channel::Expansion),
411 control(Channel::OrderingTableClear),
412 ];
413 let sr: u32;
414 unsafe {
416 core::arch::asm!("mfc0 {t}, $12", "nop", t = out(reg) sr, options(nostack, nomem));
417 }
418 let cc = unsafe { psx_io::read_u32(CONTROL_ADDRESS) };
420 psx_io::diag::flush_enter(chcr, psx_io::gpu::status().bits(), sr, cc);
421 }
422}
423
424#[inline(always)]
426fn diag_exit(report: QuiesceReport) {
427 psx_io::diag::flush_exit(
428 report.busy_at_entry,
429 report.retries,
430 report.spins,
431 report.timed_out,
432 );
433}
434
435mod raw {
438 #[cfg(target_arch = "mips")]
439 use psx_hw::memory::cache_control;
440
441 #[cfg(target_arch = "mips")]
444 core::arch::global_asm!(
445 r#"
446 .set noreorder
447 .section .text.__psx_rt_flush_i_cache,"ax",@progbits
448 .globl __psx_rt_flush_i_cache
449 .type __psx_rt_flush_i_cache,@function
450 .p2align 2
451__psx_rt_flush_i_cache:
452 lui $t0, %hi(.Lpsx_rt_flush_uncached)
453 addiu $t0, $t0, %lo(.Lpsx_rt_flush_uncached)
454 lui $t1, 0xA000
455 or $t0, $t0, $t1
456 jr $t0
457 nop
458.Lpsx_rt_flush_uncached:
459 mfc0 $t2, $12
460 lui $t3, {port_hi}
461 mtc0 $zero, $12
462 lui $t4, {flush_hi}
463 ori $t4, $t4, {flush_lo}
464 sw $t4, {port_lo}($t3)
465 lui $t4, 0x0001
466 mtc0 $t4, $12
467 nop
468 nop
469 addu $t5, $zero, $zero
470 li $t6, 0x1000
471.Lpsx_rt_flush_line:
472 addiu $t5, $t5, 16
473 bne $t5, $t6, .Lpsx_rt_flush_line
474 sw $zero, -16($t5)
475 mtc0 $zero, $12
476 nop
477 nop
478 lui $t4, {running_hi}
479 ori $t4, $t4, {running_lo}
480 sw $t4, {port_lo}($t3)
481 mtc0 $t2, $12
482 nop
483 jr $ra
484 nop
485 .size __psx_rt_flush_i_cache, . - __psx_rt_flush_i_cache
486 .set reorder
487 "#,
488 port_hi = const cache_control::ADDR >> 16,
489 port_lo = const cache_control::ADDR & 0xFFFF,
490 flush_hi = const cache_control::FLUSH >> 16,
491 flush_lo = const cache_control::FLUSH & 0xFFFF,
492 running_hi = const cache_control::RUNNING >> 16,
493 running_lo = const cache_control::RUNNING & 0xFFFF,
494 );
495
496 #[cfg(target_arch = "mips")]
501 core::arch::global_asm!(
502 r#"
503 .set noreorder
504 .section .text.__psx_rt_flush_i_cache_range,"ax",@progbits
505 .globl __psx_rt_flush_i_cache_range
506 .type __psx_rt_flush_i_cache_range,@function
507 .p2align 2
508__psx_rt_flush_i_cache_range:
509 lui $t0, %hi(.Lpsx_rt_flush_range_uncached)
510 addiu $t0, $t0, %lo(.Lpsx_rt_flush_range_uncached)
511 lui $t1, 0xA000
512 or $t0, $t0, $t1
513 jr $t0
514 nop
515.Lpsx_rt_flush_range_uncached:
516 mfc0 $t2, $12
517 lui $t3, {port_hi}
518 mtc0 $zero, $12
519 lui $t4, {flush_hi}
520 ori $t4, $t4, {flush_lo}
521 sw $t4, {port_lo}($t3)
522 lui $t4, 0x0001
523 mtc0 $t4, $12
524 andi $t5, $a0, 0x0FF0
525 addiu $t6, $a1, -1
526 srl $t6, $t6, 4
527 srl $t7, $a0, 4
528 subu $t6, $t6, $t7
529 addiu $t6, $t6, 1
530.Lpsx_rt_flush_range_line:
531 sw $zero, 0($t5)
532 addiu $t5, $t5, 16
533 addiu $t6, $t6, -1
534 bnez $t6, .Lpsx_rt_flush_range_line
535 andi $t5, $t5, 0x0FFF
536 mtc0 $zero, $12
537 nop
538 nop
539 lui $t4, {running_hi}
540 ori $t4, $t4, {running_lo}
541 sw $t4, {port_lo}($t3)
542 mtc0 $t2, $12
543 nop
544 jr $ra
545 nop
546 .size __psx_rt_flush_i_cache_range, . - __psx_rt_flush_i_cache_range
547 .set reorder
548 "#,
549 port_hi = const cache_control::ADDR >> 16,
550 port_lo = const cache_control::ADDR & 0xFFFF,
551 flush_hi = const cache_control::FLUSH >> 16,
552 flush_lo = const cache_control::FLUSH & 0xFFFF,
553 running_hi = const cache_control::RUNNING >> 16,
554 running_lo = const cache_control::RUNNING & 0xFFFF,
555 );
556
557 #[cfg(target_arch = "mips")]
558 extern "C" {
559 fn __psx_rt_flush_i_cache_range(start: u32, end: u32);
560 fn __psx_rt_flush_i_cache();
561 }
562
563 #[cfg(target_arch = "mips")]
567 #[inline(always)]
568 pub(super) fn flush_all() {
569 unsafe { __psx_rt_flush_i_cache() }
574 }
575
576 #[cfg(target_arch = "mips")]
580 #[inline(always)]
581 pub(super) fn flush_range(start: u32, end: u32) {
582 unsafe { __psx_rt_flush_i_cache_range(start, end) }
584 }
585
586 #[cfg(not(target_arch = "mips"))]
588 pub(super) fn flush_all() {}
589
590 #[cfg(not(target_arch = "mips"))]
592 pub(super) fn flush_range(_start: u32, _end: u32) {}
593}
594
595#[cfg(test)]
596mod tests {
597 extern crate std;
598
599 use super::*;
600 use std::vec::Vec;
601
602 struct Script {
605 busy_polls: u32,
606 kicks_on_mask: u32,
607 kick_len: u32,
608 wedged: bool,
609 enabled: bool,
610 masked_polls: u32,
611 unmasked_polls: u32,
612 polls: u32,
613 }
614
615 impl Script {
616 fn idle() -> Self {
617 Self {
618 busy_polls: 0,
619 kicks_on_mask: 0,
620 kick_len: 3,
621 wedged: false,
622 enabled: true,
623 masked_polls: 0,
624 unmasked_polls: 0,
625 polls: 0,
626 }
627 }
628 }
629
630 impl Bus for Script {
631 fn dma_busy(&mut self) -> bool {
632 self.polls += 1;
633 if self.enabled {
634 self.unmasked_polls += 1;
635 } else {
636 self.masked_polls += 1;
637 }
638 if self.wedged {
639 return true;
640 }
641 if self.busy_polls > 0 {
642 self.busy_polls -= 1;
643 return true;
644 }
645 false
646 }
647
648 fn irq_off(&mut self) -> bool {
649 let was = self.enabled;
650 self.enabled = false;
651 if self.kicks_on_mask > 0 {
652 self.kicks_on_mask -= 1;
653 self.busy_polls = self.kick_len;
654 }
655 was
656 }
657
658 fn irq_restore(&mut self, was_enabled: bool) {
659 self.enabled = was_enabled;
660 }
661 }
662
663 struct Shared<'a>(&'a core::cell::RefCell<Script>);
666
667 impl Bus for Shared<'_> {
668 fn dma_busy(&mut self) -> bool {
669 self.0.borrow_mut().dma_busy()
670 }
671 fn irq_off(&mut self) -> bool {
672 self.0.borrow_mut().irq_off()
673 }
674 fn irq_restore(&mut self, was_enabled: bool) {
675 self.0.borrow_mut().irq_restore(was_enabled)
676 }
677 }
678
679 fn gate(bus: Script, limit: u32) -> (u32, QuiesceReport, Script) {
682 let bus = core::cell::RefCell::new(bus);
683 let runs = core::cell::Cell::new(0u32);
684 let (_, report) = run_when_dma_idle(&mut Shared(&bus), limit, |r| {
685 let b = bus.borrow();
686 assert!(!b.enabled, "the flush must run with interrupts masked");
687 assert!(
688 r.timed_out || b.busy_polls == 0,
689 "the flush must not run while a channel is busy"
690 );
691 runs.set(runs.get() + 1);
692 });
693 (runs.get(), report, bus.into_inner())
694 }
695
696 #[test]
697 fn an_idle_bus_flushes_once_with_interrupts_masked() {
698 let (runs, report, bus) = gate(Script::idle(), 100);
699 assert_eq!(runs, 1);
700 assert_eq!(report, QuiesceReport::default());
701 assert!(bus.enabled, "interrupts are back on afterwards");
702 }
703
704 #[test]
705 fn a_walk_is_waited_out_with_interrupts_on() {
706 let mut bus = Script::idle();
707 bus.busy_polls = 7;
708 let (runs, report, bus) = gate(bus, 100);
709 assert_eq!(runs, 1);
710 assert!(report.busy_at_entry);
711 assert_eq!(
712 report.spins, 6,
713 "the entry probe saw 1 of 7 busy reads, the wait the other 6"
714 );
715 assert!(!report.timed_out);
716 assert_eq!(report.retries, 0);
717 assert_eq!(bus.masked_polls, 1, "inside the window it only re-checks");
718 }
719
720 #[test]
721 fn a_walk_kicked_between_the_check_and_the_mask_is_waited_out_again() {
722 let mut bus = Script::idle();
723 bus.kicks_on_mask = 1;
724 let (runs, report, bus) = gate(bus, 100);
725 assert_eq!(runs, 1);
726 assert_eq!(report.retries, 1);
727 assert!(!report.timed_out);
728 assert_eq!(bus.busy_polls, 0);
729 assert!(bus.enabled);
730 }
731
732 #[test]
733 fn kicks_that_keep_coming_end_in_a_wait_inside_the_window() {
734 let mut bus = Script::idle();
735 bus.kicks_on_mask = 1000;
736 let (runs, report, bus) = gate(bus, 100);
737 assert_eq!(runs, 1);
738 assert_eq!(report.retries, KICK_RETRIES);
739 assert!(!report.timed_out, "the walk ended inside the window");
740 assert_eq!(bus.busy_polls, 0);
741 assert!(bus.masked_polls > 1);
742 }
743
744 #[test]
745 fn a_wedged_channel_is_bounded_counted_and_the_flush_still_runs() {
746 let mut bus = Script::idle();
747 bus.wedged = true;
748 let (runs, report, bus) = gate(bus, 50);
749 assert_eq!(runs, 1);
750 assert!(report.timed_out);
751 assert!(report.spins <= 50);
752 assert!(bus.polls <= 50 + 3, "no unbounded polling: {}", bus.polls);
753 assert!(bus.enabled);
754 }
755
756 #[test]
757 fn a_wedged_channel_behind_endless_kicks_is_still_bounded() {
758 let mut bus = Script::idle();
759 bus.kicks_on_mask = u32::MAX;
760 bus.kick_len = u32::MAX; let (runs, report, bus) = gate(bus, 20);
762 assert_eq!(runs, 1);
763 assert!(report.timed_out);
764 assert!(bus.polls < 20 * (KICK_RETRIES + 3), "polls: {}", bus.polls);
765 }
766
767 #[test]
768 fn interrupt_state_is_restored_exactly() {
769 let mut bus = Script::idle();
770 bus.enabled = false;
771 bus.busy_polls = 3;
772 let (runs, _, bus) = gate(bus, 100);
773 assert_eq!(runs, 1);
774 assert!(
775 !bus.enabled,
776 "a caller that had interrupts off keeps them off"
777 );
778 }
779
780 #[test]
781 fn the_public_api_runs_on_the_host() {
782 flush_instruction_cache();
783 flush_instruction_cache_range(0x8001_0000, 0x8001_0010);
784 flush_instruction_cache_range(0x8001_0000, 0x8001_2000);
785 }
786
787 #[test]
791 fn nothing_else_in_the_sdk_names_the_cache_control_register_or_isc() {
792 fn visit(dir: &std::path::Path, hits: &mut Vec<std::string::String>) {
793 for entry in std::fs::read_dir(dir).unwrap() {
794 let path = entry.unwrap().path();
795 if path.is_dir() {
796 if path.file_name().is_some_and(|n| n == "target") {
797 continue;
798 }
799 visit(&path, hits);
800 } else if path.extension().is_some_and(|e| e == "rs") {
801 let text = std::fs::read_to_string(&path).unwrap();
802 let is_this_file = path.ends_with("psx-rt/src/cache.rs");
803 for needle in ["cache_control", "FFFE0130", "FFFE_0130", "IsC"] {
804 if text.contains(needle) && !is_this_file {
805 hits.push(std::format!("{}: {needle}", path.display()));
806 }
807 }
808 }
809 }
810 }
811 let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
812 let mut hits = Vec::new();
813 visit(&crates, &mut hits);
814 assert!(hits.is_empty(), "outside psx-rt/src/cache.rs: {hits:#?}");
815 }
816}