-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrsp.rs
4190 lines (3432 loc) · 190 KB
/
rsp.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(non_upper_case_globals)]
use std::mem;
use std::sync::{mpsc, Arc, Mutex, RwLock};
use std::thread;
#[cfg(all(target_arch="x86_64", target_feature="sse2"))]
use core::arch::x86_64::*;
use avx512f_wrapper::*;
#[allow(unused_imports)]
use tracing::{trace, debug, error, info, warn};
use crate::*;
use cpu::{InstructionDecode, InstructionFault};
use hle::Hle;
use mips::{InterruptUpdate, InterruptUpdateMode, IMask_SP};
use rcp::DmaInfo;
use rdp::Rdp;
/// COP0 "registers"
const Cop0_DmaCache : usize = 0; // IMEM or DMEM address for a DMA transfer
const Cop0_DmaDram : usize = 1; // RDRAM address for a DMA
const Cop0_DmaReadLength : usize = 2;
const Cop0_DmaWriteLength: usize = 3;
const Cop0_Status : usize = 4;
const Cop0_DmaFull : usize = 5;
const Cop0_DmaBusy : usize = 6;
const Cop0_Semaphore : usize = 7;
const Cop0_CmdStart : usize = 8;
const Cop0_CmdEnd : usize = 9;
const Cop0_CmdCurrent : usize = 10;
const Cop0_CmdStatus : usize = 11;
const Cop0_CmdClock : usize = 12;
const _Cop0_CmdBusy : usize = 13;
const _Cop0_CmdPipeBusy : usize = 14;
const _Cop0_CmdTMemBusy : usize = 15;
const Cop2_VCO: usize = 0;
const Cop2_VCC: usize = 1;
const Cop2_VCE: usize = 2;
/// N64 Reality Signal Processor
/// Resides on the die of the RCP.
pub struct Rsp {
comms: SystemCommunication,
core: Arc<Mutex<RspCpuCore>>,
shared_state: Arc<RwLock<RspSharedState>>,
wakeup_tx: Option<mpsc::Sender<u32>>,
broke_rx: Option<mpsc::Receiver<bool>>,
// access to RspCpuCore memory
mem: Arc<RwLock<Vec<u32>>>,
dma_completed_rx: mpsc::Receiver<DmaInfo>,
dma_completed_tx: mpsc::Sender<DmaInfo>,
// these are copies of state in RspCpuCore so we don't need a lock
halted: bool,
broke: bool,
// hacky fix for M_AUDTASK in commercial games
current_task: Arc<AtomicU32>,
}
#[derive(Debug, Default)]
pub struct RspSharedState {
exited: bool,
intbreak: bool,
halted_self: bool,
dma_cache: u32,
dma_dram: u32,
dma_read_length: u32,
dma_write_length: u32,
dma_busy: bool,
dma_full: Option<DmaInfo>,
dma_total_size: u32,
semaphore: bool,
// current or most recent DMA, and the data that is readable in the DMA registers
dma_current_cache: u32,
dma_current_dram: u32,
dma_current_read_length: u32,
dma_current_write_length: u32,
// signals
signals: u32,
}
struct RspCpuCore {
comms: SystemCommunication,
num_steps: u64,
// registers
pc: u32,
current_instruction_pc: u32, // actual PC of the currently executing instruction
// only valid inside step()
next_instruction: u32, // emulates delay slot (prefetch, next instruction)
next_instruction_pc: u32, // for printing correct delay slot addresses
is_delay_slot: bool, // true if the currently executing instruction is in a delay slot
next_is_delay_slot: bool, // set to true on branching instructions
gpr: [u32; 32],
ccr: [u32; 4],
v: [__m128i; 32], // 32 128-bit VU registers
vacc: __wm512i, // 8x48bit (in 64-bit lanes) accumulators
vacc_mask: __wm512i, // always 0xFFFF_FFFF_FFFF_FFFF
v256_ones: __m256i, // 8x32bit 0x0000_0001
rotate_base: __m128i,
inst: InstructionDecode,
inst_e: u8, // used by COP2 math instructions, not SWC/LWC
inst_vt: usize,
inst_vs: usize,
inst_vd: usize,
instruction_table: [CpuInstruction; 64],
special_table: [CpuInstruction; 64],
regimm_table: [CpuInstruction; 32],
cop2_table: [CpuInstruction; 64],
// rcp and rsq tables
rcp_high: bool,
rcp_input: u16,
rcp_table: [u16; 512],
rsq_table: [u16; 512],
div_result: u32,
// multiple reader single writer memory
mem: Arc<RwLock<Vec<u32>>>,
shared_state: Arc<RwLock<RspSharedState>>,
broke_tx: Option<mpsc::Sender<bool>>,
dma_completed_tx: mpsc::Sender<DmaInfo>,
// running state
halted: bool,
halted_self: bool,
broke: bool,
// access to the RDP
rdp: Arc<Mutex<Rdp>>,
// HLE
process_task: bool,
audio_task_start: Option<std::time::Instant>,
current_task: Arc<AtomicU32>,
}
type CpuInstruction = fn(&mut RspCpuCore) -> Result<(), InstructionFault>;
impl Rsp {
pub fn new(comms: SystemCommunication, rdp: Arc<Mutex<Rdp>>) -> Rsp {
let mem = Arc::new(RwLock::new(vec![0u32; 2*1024]));
let shared_state = Arc::new(RwLock::new(RspSharedState::default()));
// dma_completed channel is created here and sent with every DmaInfo message
let (dma_completed_tx, dma_completed_rx) = mpsc::channel();
let current_task = Arc::new(AtomicU32::new(0));
let core = Arc::new(Mutex::new(RspCpuCore::new(comms.clone(), mem.clone(), shared_state.clone(), rdp, dma_completed_tx.clone(), current_task.clone())));
Rsp {
comms,
core,
mem,
wakeup_tx: None,
broke_rx: None,
dma_completed_rx,
dma_completed_tx,
shared_state,
halted: true,
broke: false,
current_task,
}
}
pub fn start(&mut self) {
// create the awake channel
let (wakeup_tx, wakeup_rx) = mpsc::channel();
self.wakeup_tx = Some(wakeup_tx);
// create the broke signal channel
let (broke_tx, broke_rx) = mpsc::channel();
self.broke_rx = Some(broke_rx);
let core = Arc::clone(&self.core);
{
let mut c = core.lock().unwrap();
c.broke_tx = Some(broke_tx);
}
let mut hle: Option<Hle> = if let Some(ref hle_command_buffer) = self.comms.hle_command_buffer {
Some(Hle::new(self.comms.clone(), hle_command_buffer.clone()))
} else {
None
};
self.shared_state.write().unwrap().exited = false;
thread::spawn(move || {
let mut _started_time = std::time::Instant::now();
//let mut task_time = std::time::Instant::now();
//let mut audio_task = false;
'main_loop: loop {
let mut c = core.lock().unwrap();
// halted can only be set while we don't have a lock, so check here
if c.halted {
//.info!(target: "RSP", "RSP core halted (broke={}), waiting for wakeup", c.broke);
//if audio_task {
// let task_duration = std::time::Instant::now() - task_time;
// println!("audio task took {} s", task_duration.as_secs_f64());
// audio_task = false;
//}
// drop the lock on the core and wait for a wakeup signal
drop(c);
// wait forever for a signal
match wakeup_rx.recv().unwrap() {
0 => {}, // normal wakeup
1 => { // exit thread
break 'main_loop;
}
_ => panic!("invalid"),
}
// running!
let mut c = core.lock().unwrap();
_started_time = std::time::Instant::now();
c.num_steps = 0;
c.halted = false;
c.broke = false;
// prefetch the next instruction, as the CPU may have (probably!) changed IMEM
c.pc = c.next_instruction_pc;
let _ = c.prefetch();
// OSTasks are only set when the RSP is halted, so whenever we wake up we can check and perform tasks
if c.process_task {
c.process_task = false;
// Task type is the first element of the OSTask structure, which is at 0xFC0
let task_type = c.read_u32(0x0FC0).unwrap();
debug!(target: "RSP", "processing task type {}", task_type);
c.current_task.store(task_type, Ordering::Relaxed);
// restart task time
//task_time = std::time::Instant::now();
match task_type {
1 => { // M_GFXTASK
let dl_start = c.read_u32(0x0FF0).unwrap(); // OSTask->data_ptr
if dl_start != 0 { // for gfx tasks, the DL list start pointer must be valid
let dl_length = c.read_u32(0x0FF4).unwrap(); // OSTask->data_size
// pass along the microcode address so that the HLE can detect which software is running
let ucode_address = c.read_u32(0x0FD0).unwrap(); // OSTask->ucode;
// free the lock on core while running the DL
drop(c);
if let Some(ref mut h) = hle {
h.process_display_list(dl_start, dl_length, ucode_address);
}
// reclaim lock
let mut c = core.lock().unwrap();
// set SIG2 (SP_STATUS_TASKDONE)
{
let mut shared_state = c.shared_state.write().unwrap();
shared_state.signals |= 1 << 2;
}
// and break, which usually triggers SP interrupt
let _ = c.special_break().unwrap();
// RSP isn't running
c.halted = true;
{
let mut rdp = c.rdp.lock().unwrap();
rdp.write_u32(0x04, 0x0010_000C as usize).unwrap(); // write CLR_FREEZE bit
}
} else {
todo!();
}
},
2 => { // M_AUDTASK -- run via LLE
c.audio_task_start = Some(std::time::Instant::now());
},
// All other tasks types are LLE'd
_ => {
if task_type < 8 {
debug!(target: "RSP", "found task type {}", task_type);
}
},
}
}
} else {
// run for some cycles or until break
for _ in 0..40 {
let _ = c.step(); // TODO handle errors
if c.broke || c.halted_self {
c.current_task.store(0, Ordering::Relaxed);
if let Some(audio_start_time) = std::mem::replace(&mut c.audio_task_start, None) {
trace!(target: "RSP", "Audio task took {:.6}", audio_start_time.elapsed().as_secs_f64());
}
c.halted = true; // signal the core is halted before dropping the lock
break;
}
}
}
}
// main loop has exited, mark exit on the shared state
let c = core.lock().unwrap();
let mut shared_state = c.shared_state.write().unwrap();
shared_state.exited = true;
});
}
pub fn stop(&mut self) {
info!(target: "RSP", "stop");
// send the exit signal to the running thread
self.wakeup_tx.as_mut().unwrap().send(1).unwrap(); // 1 = exit code
loop {
// repeatedly halt the CPU since it could be receiving wakeups
// so run and check until the thread has exited
let mut c = self.core.lock().unwrap();
if !c.halted {
c.halted = true;
c.halted_self = false;
}
let shared_state = self.shared_state.read().unwrap();
if shared_state.exited {
break;
}
}
}
pub fn reset(&mut self) {
info!(target: "RSP", "reset");
if !self.shared_state.read().unwrap().exited {
warn!(target: "RSP", "reset without calling stop()");
}
// clear all messages
if let Some(broke_rx) = &self.broke_rx {
while broke_rx.try_recv().is_ok() {}
}
while self.dma_completed_rx.try_recv().is_ok() {}
// set current state to halted
self.halted = true;
self.broke = false;
// reset shared state
*self.shared_state.write().unwrap() = RspSharedState::default();
// reset rsp core
let _ = self.core.lock().unwrap().reset();
}
pub fn wait_audio_task_idle(&mut self) {
if !self.is_broke() {
if self.current_task.load(Ordering::Relaxed) == 2 { // M_AUDTASK
warn!(target: "RSP", "waiting for audio task to complete (RSP core running too slow)");
while !self.is_broke() {}
}
}
}
pub fn step(&mut self) {
let _ = self.is_broke(); // update interrupts
if let Ok(_old_dma_info) = self.dma_completed_rx.try_recv() {
//println!("dma completed after {} s", _old_dma_info.duration());
// we got a completed DMA, so if one is pending start it immediately
let mut shared_state = self.shared_state.write().unwrap();
shared_state.dma_busy = false;
if let Some(dma_info) = mem::replace(&mut shared_state.dma_full, None) {
shared_state.dma_current_cache = (shared_state.dma_cache & 0x1000) | (((shared_state.dma_cache & !0x07) + shared_state.dma_total_size) & 0x0FFF);
shared_state.dma_current_dram = (shared_state.dma_dram & !0x07) + shared_state.dma_total_size;
shared_state.dma_current_read_length = 0xFF8;
shared_state.dma_current_write_length = 0xFF8;
shared_state.dma_busy = true;
self.comms.start_dma_tx.as_ref().unwrap().send(dma_info).unwrap();
self.comms.break_cpu();
}
}
}
pub fn is_broke(&mut self) -> bool {
// update the local BREAK status
if let Some(broke_rx) = &self.broke_rx {
while let Ok(set) = broke_rx.try_recv() {
self.broke = false;
if set {
self.broke = true;
self.halted = true;
}
}
}
self.broke
}
fn read_register(&mut self, offset: usize) -> Result<u32, ReadWriteFault> {
//info!(target: "RSP", "read32 register offset=${:08X}", offset);
let value = match offset {
// SP_DMA_CACHE
0x4_0000 => {
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_current_cache
},
// SP_DMA_DRAM
0x4_0004 => {
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_current_dram
},
// SP_DMA_READ_LENGTH
0x4_0008 => {
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_current_read_length
},
// SP_DMA_WRITE_LENGTH
0x4_000C => {
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_current_write_length
},
// SP_STATUS
0x4_0010 => {
trace!(target: "RSP", "read SP_STATUS at {}", self.comms.total_cpu_steps.get() as u64);
// update self.broke
let _ = self.is_broke();
// update self.halted on self-halting RSP
if !self.halted {
let shared_state = self.shared_state.read().unwrap();
if shared_state.halted_self {
drop(shared_state);
self.halted = true;
// clear both shared_state and core states
{
let mut shared_state = self.shared_state.write().unwrap();
shared_state.halted_self = false;
}
{
let mut core = self.core.lock().unwrap();
core.halted_self = false;
}
}
}
let shared_state = self.shared_state.read().unwrap();
((self.halted as u32) << 0)
| ((self.broke as u32) << 1)
| ((shared_state.dma_busy as u32) << 2)
| ((shared_state.dma_full.is_some() as u32) << 3)
| ((shared_state.intbreak as u32) << 6)
| (shared_state.signals << 7)
},
// SP_DMA_FULL
0x4_0014 => {
//debug!(target: "RSP", "read SP_DMA_FULL");
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_full.is_some() as u32
},
// SP_DMA_BUSY
0x4_0018 => {
//debug!(target: "RSP", "read SP_DMA_BUSY");
let shared_state = self.shared_state.read().unwrap();
shared_state.dma_busy as u32
},
// SP_SEMAPHORE
0x4_001C => {
let mut shared_state = self.shared_state.write().unwrap();
if !shared_state.semaphore {
shared_state.semaphore = true;
0
} else {
1
}
},
// SP_PC
0x8_0000 => {
//debug!(target: "RSP", "read SP_PC");
let core = self.core.lock().unwrap();
core.next_instruction_pc
},
_ => {
error!(target: "RSP", "unknown register read offset=${:08X}", offset);
0
},
};
Ok(value)
}
fn write_register(&mut self, mut value: u32, offset: usize) {
match offset {
// SP_DMA_CACHE
0x4_0000 => {
//debug!(target: "RSP", "DMA RSP address set to ${:04X} via CPU", value & 0x1FFF);
let mut shared_state = self.shared_state.write().unwrap();
shared_state.dma_cache = value & 0x1FFF;
},
// SP_DMA_DRAM
0x4_0004 => {
//debug!(target: "RSP", "DMA DRAM address set to ${:04X} via CPU", value & 0x00FF_FFFF);
let mut shared_state = self.shared_state.write().unwrap();
shared_state.dma_dram = value & 0x00FF_FFFF;
},
// SP_DMA_READ_LENGTH
0x4_0008 => {
//debug!(target: "RSP", "DMA read length set to ${:04X} via CPU", value);
let mut shared_state = self.shared_state.write().unwrap();
shared_state.dma_read_length = value;
let length = ((value & 0x0FFF) | 0x07) + 1;
let count = ((value >> 12) & 0xFF) + 1;
let skip = (value >> 20) & 0xFFF;
shared_state.dma_total_size = count * length + (count - 1) * skip;
let dma_info = DmaInfo {
initiator : "RSP-READ(CPU)",
source_address: (shared_state.dma_dram) & !0x07,
dest_address : (shared_state.dma_cache | 0x0400_0000) & !0x07,
count : count,
length : length,
source_stride : skip,
dest_mask : 0x0000_0FFF,
dest_bits : 0x0400_0000 | (shared_state.dma_cache & 0x1000),
completed : Some(self.dma_completed_tx.clone()),
..Default::default()
};
if shared_state.dma_busy {
if shared_state.dma_full.is_none() {
shared_state.dma_full = Some(dma_info);
}
} else {
// update the addresses as if the dma has been completed
shared_state.dma_current_cache = (shared_state.dma_cache & 0x1000) | (((shared_state.dma_cache & !0x07) + shared_state.dma_total_size) & 0x0FFF);
shared_state.dma_current_dram = (shared_state.dma_dram & !0x07) + shared_state.dma_total_size;
shared_state.dma_current_read_length = 0xFF8;
shared_state.dma_current_write_length = 0xFF8;
shared_state.dma_busy = true;
self.comms.start_dma_tx.as_ref().unwrap().send(dma_info).unwrap();
self.comms.break_cpu();
}
},
// SP_DMA_WRITE_LENGTH
0x4_000C => {
//debug!(target: "RSP", "DMA write length set to ${:04X}", value);
let mut shared_state = self.shared_state.write().unwrap();
shared_state.dma_write_length = value;
let length = ((value & 0x0FFF) | 0x07) + 1;
let count = ((value >> 12) & 0xFF) + 1;
let skip = (value >> 20) & 0xFFF;
shared_state.dma_total_size = count * length + (count - 1) * skip;
let dma_info = DmaInfo {
initiator : "RSP-WRITE(CPU)",
source_address: (shared_state.dma_cache | 0x0400_0000) & !0x07,
dest_address : (shared_state.dma_dram) & !0x07,
count : count,
length : length,
dest_stride : skip,
source_mask : 0x0000_0FFF,
source_bits : 0x0400_0000 | (shared_state.dma_cache & 0x1000),
completed : Some(self.dma_completed_tx.clone()),
..Default::default()
};
if shared_state.dma_busy {
if shared_state.dma_full.is_none() {
shared_state.dma_full = Some(dma_info);
}
} else {
// update the addresses as if the dma has been completed
shared_state.dma_current_cache = (shared_state.dma_cache & 0x1000) | (((shared_state.dma_cache & !0x07) + shared_state.dma_total_size) & 0x0FFF);
shared_state.dma_current_dram = (shared_state.dma_dram & !0x07) + shared_state.dma_total_size;
shared_state.dma_current_read_length = 0xFF8;
shared_state.dma_current_write_length = 0xFF8;
shared_state.dma_busy = true;
self.comms.start_dma_tx.as_ref().unwrap().send(dma_info).unwrap();
self.comms.break_cpu();
}
},
// SP_STATUS
0x4_0010 => {
//debug!(target: "RSP", "write SP_STATUS value=${:08X}", value);
// CLR_BROKE: clear the broke flag
if (value & 0x04) != 0 {
self.broke = false; // set local copy
if let Some(broke_rx) = &self.broke_rx {
// clear the broke_rx channel (which should never have more than 1 in it
// because a break halts the cpu). I imagine if you set set CLR_BROKE
// while the CPU is running (you wrote CLR_HALT previously), this might
// cause a break signal to get lost. hopefully that's not a problem.
loop {
if let Err(_) = broke_rx.try_recv() {
break;
}
}
}
}
// if CLR_HALT and SET_HALT are both set, neither happen
if (value & 0x03) == 0x03 { value &= !0x03; }
// CLR_HALT: clear halt flag and start RSP
if (value & 0x01) != 0 {
// sum up the first 44 bytes of imem
//.let mut sum: u32 = 0;
//.for i in 0..44 {
//. if let Ok(v) = self.read_u8(0x1000 + i) {
//. sum = sum.wrapping_add(v as u32);
//. }
//.}
//.info!(target: "RSP", "sum of IMEM at start: ${:08X} (if this value is 0x9E2, it is a bootcode program)", sum);
//.{
//. let core = self.core.lock().unwrap();
//. info!(target: "RSP", "starting RSP at PC=${:08X}", core.next_instruction_pc);
//.}
// set local copy
self.halted = false;
// send wakeup signal
if let Some(wakeup_tx) = &self.wakeup_tx {
wakeup_tx.send(0).unwrap(); // 0 = wakeup and execute
}
}
// SET_HALT: halt the RSP
if (value & 0x02) != 0 {
// TODO it might be worth converting this to a mpsc channel as well,
// depending on if anything uses SET_HALT often enough to causes stalls
info!(target: "RSP", "CPU has halted the RSP");
let mut c = self.core.lock().unwrap();
c.halted = true;
c.halted_self = false;
let mut shared_state = self.shared_state.write().unwrap();
shared_state.halted_self = false;
self.halted = true;
}
// if both SET_INTBREAK and CLR_INTBREAK are set, do nothing
if (value & 0x180) == 0x180 { value &= !0x180; }
// SET_INTBREAK: enable the interrupt on BREAK signal
if (value & 0x100) != 0 {
let mut shared_state = self.shared_state.write().unwrap();
shared_state.intbreak = true;
}
// CLR_INTBREAK: disable the interrupt on break signal
if (value & 0x80) != 0 {
let mut shared_state = self.shared_state.write().unwrap();
shared_state.intbreak = false;
}
// If both SET and CLR_INTR are set, do nothing
if (value & 0x18) == 0x18 {
value &= !0x18;
}
// SET_INTR: manually trigger SP interrupt
if (value & 0x10) != 0 {
self.comms.mi_interrupts_tx.as_ref().unwrap().send(InterruptUpdate(IMask_SP, InterruptUpdateMode::SetInterrupt)).unwrap();
self.comms.break_cpu();
}
// CLR_INTR: ack SP interrupt
if (value & 0x08) != 0 {
self.comms.mi_interrupts_tx.as_ref().unwrap().send(InterruptUpdate(IMask_SP, InterruptUpdateMode::ClearInterrupt)).unwrap();
}
// loop over the signals
value >>= 9; // signals start at bit 9
if value != 0 {
let mut shared_state = self.shared_state.write().unwrap();
for i in 0..16 {
// i loops over 8 signals each CLEAR then SET bits
// so signal number is i/2, and SET when i is odd, otherwise clear
if (value & (1 << i)) == 0 { continue; }
// toggle the odd bit and if it is also set, do nothing
// (you cannot clear and set a signal at the same time)
if (value & (1 << (i ^ 0x01))) != 0 { continue; }
let signo = i >> 1;
// if the signal is set and clear, do nothing
if (i & 0x01) == 0 { // CLEAR signal
//info!(target: "RSP", "CPU clearing signal {}", signo);
shared_state.signals &= !(1 << signo);
} else { // SET signal
//info!(target: "RSP", "CPU setting signal {}", signo);
shared_state.signals |= 1 << signo;
}
}
}
},
// SP_SEMAPHORE
0x4_001C => {
let mut shared_state = self.shared_state.write().unwrap();
shared_state.semaphore = false;
},
// SP_PC
0x8_0000 => {
trace!(target: "RSP", "write SP_PC value=${:08X}", value);
let mut core = self.core.lock().unwrap();
core.pc = value & 0x0FFC;
let _ = core.prefetch(); // ignore errors here, since core.pc should never be invalid
},
_ => {
warn!(target: "RSP", "unknown write32 register value=${:08X} offset=${:08X}", value, offset);
}
};
}
}
impl Addressable for Rsp {
fn read_u32(&mut self, offset: usize) -> Result<u32, ReadWriteFault> {
trace!(target: "RSP", "read32 offset=${:08X}", offset);
match offset & 0x000F_0000 {
0x0000_0000..=0x0003_FFFF => {
let mem_offset = (offset & 0x1FFF) >> 2; // 8KiB, repeated
let mem = self.mem.read().unwrap();
Ok(mem[mem_offset as usize])
},
0x0004_0000..=0x000B_FFFF => self.read_register(offset & 0x000F_FFFF),
_ => panic!("invalid RSP read"),
}
}
// SD on RSP memory is broken, only write the upper word
fn write_u64(&mut self, value: u64, offset: usize) -> Result<WriteReturnSignal, ReadWriteFault> {
if (offset & 0xF_0000) < 0x4_0000 {
let mem_offset = (offset & 0x1FFF) >> 2; // 8KiB, repeated
let mut mem = self.mem.write().unwrap();
mem[mem_offset as usize] = (value >> 32) as u32;
Ok(WriteReturnSignal::None)
} else {
todo!("TODO");
}
}
fn write_u32(&mut self, value: u32, offset: usize) -> Result<WriteReturnSignal, ReadWriteFault> {
trace!(target: "RSP", "write32 value=${:08X} offset=${:08X}", value, offset);
match offset & 0x000F_0000 {
0x0000_0000..=0x0003_FFFF => {
let mem_offset = (offset & 0x1FFF) >> 2; // 8KiB, repeated
if mem_offset < (0x1000>>2) {
//const TASK_TYPE: usize = 0xFC0 >> 2;
//const DL_START: usize = 0xFF0 >> 2;
//const DL_LEN: usize = 0xFF4 >> 2;
//match mem_offset {
// DL_START => {
// info!(target: "RSPMEM", "wrote value=${:08X} to offset ${:08X} (DL start)", value, offset);
// },
// DL_LEN => {
// info!(target: "RSPMEM", "wrote value=${:08X} to offset ${:08X} (DL length)", value, offset);
// },
// TASK_TYPE => {
// info!(target: "RSPMEM", "wrote value=${:08X} to offset ${:08X} (TaskType)", value, offset);
// },
// _ => {},
//}
} else {
//info!(target: "RSPMEM", "write value=${:08X} offset=${:08X}", value, offset);
}
let mut mem = self.mem.write().unwrap();
mem[mem_offset as usize] = value;
},
0x0004_0000..=0x000B_FFFF => self.write_register(value, offset & 0x000F_FFFF),
_ => panic!("invalid RSP write"),
};
Ok(WriteReturnSignal::None)
}
fn write_u16(&mut self, value: u32, offset: usize) -> Result<WriteReturnSignal, ReadWriteFault> {
// SH incorrectly overwrites other bytes with zeroes
let offset = offset & !0x01;
let shift = 16 - ((offset & 0x02) << 3);
self.write_u32(value << shift, offset & !0x02)
}
fn write_u8(&mut self, value: u32, offset: usize) -> Result<WriteReturnSignal, ReadWriteFault> {
// SB incorrectly overwrites other bytes with zeroes
let shift = 24 - ((offset & 0x03) << 3);
self.write_u32(value << shift, offset & !0x03)
}
fn read_block(&mut self, offset: usize, length: u32) -> Result<Vec<u32>, ReadWriteFault> {
// wrap offset into local memory
let mut offset = offset & 0x1FF8;
if offset < 0x2000 { // I/DRAM
let mem = self.mem.read().unwrap();
let (dram, iram) = mem.split_at(0x1000 >> 2);
let which_mem = if (offset & 0x1000) != 0 { iram } else { dram };
offset &= 0xFF8; // drop the high bit
let (_, right) = which_mem.split_at(offset >> 2);
if (length >> 2) as usize <= right.len() {
let (left, _) = right.split_at((length >> 2) as usize);
Ok(left.to_owned())
} else {
// start with all the data from the right chunk
let mut ret = right.to_owned();
// and read the rest from the beginning of ram
let mut length = length - ret.len() as u32 * 4;
while length > 0 {
let amount_to_copy = std::cmp::min(0x1000, length);
let (left, _) = which_mem.split_at((amount_to_copy >> 2) as usize);
ret.extend_from_slice(&left);
length -= amount_to_copy;
}
Ok(ret)
}
} else {
todo!("DMA out of ${offset:8X}");
}
}
fn write_block(&mut self, offset: usize, block: &[u32], length: u32) -> Result<WriteReturnSignal, ReadWriteFault> {
if (block.len() * 4) as u32 != length { todo!(); }
// wrap offset into local memory
let mut offset = offset & 0x1FF8;
if offset < 0x2000 { // I/DRAM
{
let mut mem = self.mem.write().unwrap();
let (dram, iram) = mem.split_at_mut(0x1000 >> 2);
let which_mem = if (offset & 0x1000) != 0 { iram } else { dram };
offset &= 0xFF8; // drop the high bit
let (_, right) = which_mem.split_at_mut(offset >> 2);
if block.len() <= right.len() {
let (left, _) = right.split_at_mut(block.len());
left.copy_from_slice(block);
} else {
right.copy_from_slice(&block[0..right.len()]);
let leftover_words = block.len() - right.len();
let (left, _) = which_mem.split_at_mut(leftover_words);
left.copy_from_slice(&block[(block.len()-leftover_words)..block.len()]);
}
}
// if the TaskType (0x0FC0) value has changed, inform the core
// TODO: we should check what ucode is loaded before doing this
// TODO: if hle_enabled...
if 0x0FC0 >= offset && 0x0FC0 < (offset + block.len() << 2) {
let mut c = self.core.lock().unwrap();
c.process_task = true;
}
Ok(WriteReturnSignal::None)
} else {
todo!("DMA into ${offset:8X}");
}
}
}
use RspCpuCore as Cpu; // shorthand so I can copy code from cpu.rs :)
impl RspCpuCore {
fn new(comms: SystemCommunication, mem: Arc<RwLock<Vec<u32>>>, shared_state: Arc<RwLock<RspSharedState>>,
rdp: Arc<Mutex<Rdp>>, dma_completed_tx: mpsc::Sender<DmaInfo>, current_task: Arc<AtomicU32>) -> Self {
// initialize the reciprocal table.. the algorithm is widely available but I'll include the Ares license here as well, since it's used in n64-systemtest
// The generation of the RCP and RSP tables was ported from Ares: https://github.com/ares-emulator/ares/blob/acd2130a4d4c9e7208f61e0ff762895f7c9b8dc6/ares/n64/rsp/rsp.cpp#L102
// which uses the following license:
// Copyright (c) 2004-2021 ares team, Near et al
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
let mut rcp_table = [0xFFFFu16; 512];
for i in 1..512 {
rcp_table[i] = ((((1u64 << 34) / ((i as u64) + 512)) + 1) >> 8) as u16;
}
// this algorithm comes from n64-systemtest, so: Copyright (c) 2021 lemmy-64 under the MIT license
let mut rsq_table = [0u16; 512];
let alg_start_time = std::time::Instant::now();
for i in 0..512 {
let a = (if i < 256 { i + 256 } else { ((i - 256) << 1) + 512 }) as u64;
let mut b = 1u64 << 17;
rsq_table[i] = {
// find the largest b where b < 1.0 / sqrt(a)
let mut inc = 512;
while inc != 0 {
while (a * (b + inc) * (b + inc)) < (1u64 << 44) { b += inc; }
inc >>= 1;
}
(b >> 1) as u16
};
}
let alg_time = alg_start_time.elapsed();
info!(target: "RSP", "RSQ table generation took {:.2?}", alg_time);
let mut core = RspCpuCore {
comms,
num_steps: 0,
pc: 0,
current_instruction_pc: 0,
next_instruction: 0,
next_instruction_pc: 0,
is_delay_slot: false,
next_is_delay_slot: false,
gpr: [0u32; 32],
ccr: [0u32; 4],
rcp_high: false,
rcp_input: 0,
rcp_table,
rsq_table,
div_result: 0u32,
v: [unsafe { _mm_setzero_si128() }; 32],
vacc: _wmm512_setzero_si512(),
vacc_mask: _wmm512_set1_epi64(0xFFFF_FFFF_FFFF_FFFFu64 as i64),
v256_ones: unsafe { _mm256_set1_epi32(1) },
rotate_base: unsafe { _mm_set_epi8(31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16) },
inst: InstructionDecode::default(),
inst_e: 0,
inst_vt: 0,