Repository navigation
Expand file tree
/
Copy pathmips_cache_v2.rs
More file actions
7350 lines (6701 loc) · 340 KB
/
Copy pathmips_cache_v2.rs
File metadata and controls
7350 lines (6701 loc) · 340 KB
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
// MIPS R4000 Cache Implementation - Version 2
//
// This is a complete rewrite to properly support R4000 cache semantics:
// - Unified cache object containing L1-I, L1-D, and L2
// - Proper VIPT (Virtually Indexed, Physically Tagged) support
// - R4000-compliant tag format with PState bits
// - L2 can signal back to L1 for evictions
use crate::traits::{BusRead64, BusDevice, Resettable, BUS_OK, BUS_BUSY, BUS_ERR, BUS_VCE};
use crate::snapshot::{u32_slice_to_toml, u64_slice_to_toml, load_u32_slice, load_u64_slice, get_field, toml_bool, toml_u32, toml_u64, hex_u32, hex_u64};
use crate::cpu::mips_exec::{DecodedInstr, ExecStatus, EXEC_COMPLETE, EXEC_RETRY, exec_exception_const, EXC_VCEI, EXC_VCED, EXC_IBE, FLAG_NOT_DECODED, FLAG_IMM_IS_NEXT, EXEC_CACHE_ERR};
use crate::devlog::{LogModule, CACHE_LOG_HIT, CACHE_LOG_MISS, CACHE_LOG_OP, devlog_is_active, devlog_mask};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::cell::{Cell, UnsafeCell};
use bitfield::bitfield;
/// tcache, switchable at run time: `$tc` while the cache is transparent,
/// `$real` (the cache holds the data) otherwise. Without the `tcache` feature
/// this is `$real` alone, so such a build compiles exactly as before.
macro_rules! tc_or {
($s:expr, $tc:expr, $real:expr) => {{
#[cfg(feature = "tcache")]
{ if $s.tc_live() { $tc } else { $real } }
#[cfg(not(feature = "tcache"))]
{ $real }
}};
}
/// Result of a cache instruction fetch, shared by `MipsCache::fetch` and `fetch_instr_impl`.
/// `status == EXEC_COMPLETE` means hit; `instr` points to the DecodedInstr slot (valid for
/// the lifetime of the cache). Any other status is an exception/retry; `instr` is null.
pub struct FetchInstrResult {
pub status: ExecStatus,
pub instr: *const DecodedInstr,
}
unsafe impl Send for FetchInstrResult {}
impl FetchInstrResult {
#[inline(always)]
pub fn hit(instr: *const DecodedInstr) -> Self {
Self { status: EXEC_COMPLETE, instr }
}
#[inline(always)]
pub fn exception(status: ExecStatus) -> Self {
Self { status, instr: std::ptr::null() }
}
/// A failed fetch: the bus says `BUS_ERR` (DBE), but a fetch raises IBE.
#[inline(always)]
pub fn fault(status: ExecStatus) -> Self {
Self::exception(if status == BUS_ERR { exec_exception_const(EXC_IBE) } else { status })
}
}
// =============================================================================
// R4400 Architecture Cache Constants
// =============================================================================
/// Compile-time count-trailing-zeros for usize (stable Rust lacks const trailing_zeros).
const fn ctz(n: usize) -> u32 {
let mut i = 0u32;
let mut v = n;
while v & 1 == 0 { v >>= 1; i += 1; }
i
}
/// Cache kind discriminant — used as a const generic `u8` parameter on `Cache`.
#[repr(u8)]
enum CacheKind { Insn = 0, Data = 1, L2 = 2 }
// Cache geometry is const-generic, not a cargo feature: each CPU model is its own
// monomorphisation, so every index/mask below still folds to a literal.
// Re-export cache operation constants for convenience
pub use crate::cpu::mips_isa::{
CACH_PI, CACH_PD, CACH_SI, CACH_SD,
C_IINV, C_IWBINV, C_ILT, C_IST, C_CDX,
C_HINV, C_HWBINV, C_FILL, C_HWB, C_HSV,
};
// R10000 reassigns cache operations 5, 6 and 7. Where an R4000 has
// Hit_Invalidate, Hit_Writeback_Invalidate and Hit_Writeback, an R10000 has a
// cache barrier and index-addressed load/store of the cache *data* array.
// Confirmed against NetBSD's mips/include/cache_r10k.h, and against the IP28
// PROM, whose secondary-cache SRAM test issues C_R10K_ISD(SD) — which this
// emulator was executing as a hit-writeback, so nothing was ever stored.
pub const C_R10K_CBARRIER: u32 = 5 << 2;
pub const C_R10K_ILD: u32 = 6 << 2;
pub const C_R10K_ISD: u32 = 7 << 2;
/// What one CACHE encoding (target in bits 1:0, operation in 4:2) does on a
/// model.
struct CacheOp {
/// The operand is translated before the operation: a hit operation, and
/// on the R10000 family every operation but Cache Barrier.
translates: bool,
/// The operation stores TagHi:TagLo into the cache.
stores_tag: bool,
/// The operation loads TagHi:TagLo from the cache.
loads_tag: bool,
/// The operation loads CP0 ECC with the selected doubleword's check bits.
loads_ecc: bool,
}
impl CacheOp {
const fn decode(r10k: bool, cache_op: u32) -> CacheOp {
let op = cache_op & 0x1C;
let sel = cache_op & 3;
// The R10000 index operations that name a cache entry rather than an
// address. They still translate their operand, as every R10000 CACHE
// operand is translated (NEC U12754EJ1V0UMJ1 pp. 70, 72), except a
// Cache Barrier, which names no line.
let primary_data = r10k
&& (op == C_R10K_ILD || op == C_R10K_ISD)
&& (sel == CACH_PI || sel == CACH_PD);
let index_op = r10k
&& ((op == C_R10K_CBARRIER && sel == CACH_PI)
|| (op == C_R10K_ILD && (sel == CACH_PI || sel == CACH_PD || sel == CACH_SD))
|| (op == C_R10K_ISD && (sel == CACH_SI || sel == CACH_SD)));
let hit_op = op == C_CDX || op == C_HINV || op == C_HWBINV || op == C_HWB || op == C_HSV;
let cache_barrier = op == C_R10K_CBARRIER && sel == CACH_PI;
CacheOp {
translates: if r10k { !cache_barrier } else { hit_op },
stores_tag: op == C_IST || ((index_op || primary_data) && op == C_R10K_ISD),
loads_tag: op == C_ILT || (index_op && op == C_R10K_ILD),
// Index_Load_Tag also loads CP0 ECC with the selected doubleword's
// check bits (R4000 UM A-42); the R10000 does this on
// Index_Load_Data.
loads_ecc: (r10k && op == C_R10K_ILD) || (cfg!(feature = "cache-ecc") && !r10k && op == C_ILT),
}
}
}
/// Which CACHE encodings (bit n = `cache_op` n) do each thing on a model, so
/// `exec_cache` tests a bit of a compile-time constant instead of re-deriving
/// the decision with compares on every operation.
pub struct CacheOpMasks {
pub translates: u32,
pub stores_tag: u32,
pub loads_tag: u32,
pub loads_ecc: u32,
}
impl CacheOpMasks {
const fn for_model(r10k: bool) -> CacheOpMasks {
let mut m = CacheOpMasks { translates: 0, stores_tag: 0, loads_tag: 0, loads_ecc: 0 };
let mut cache_op = 0;
while cache_op < 32 {
let op = CacheOp::decode(r10k, cache_op);
let bit = 1 << cache_op;
if op.translates { m.translates |= bit; }
if op.stores_tag { m.stores_tag |= bit; }
if op.loads_tag { m.loads_tag |= bit; }
if op.loads_ecc { m.loads_ecc |= bit; }
cache_op += 1;
}
m
}
}
/// Decode a raw cache_op field (5-bit: op\[4:2\] | target\[1:0\]) to a human-readable name.
/// Matches the disassembler mnemonic convention used by gas/objdump.
pub fn cache_op_name(op: u32) -> &'static str {
let target = op & 0x3;
let operation = op & 0x1C;
match (operation, target) {
(C_IINV, CACH_PI) => "Index_Invalidate(PI)",
(C_IWBINV, CACH_PD) => "Index_WBInvalidate(PD)",
(C_IINV, CACH_SI) => "Index_Invalidate(SI)",
(C_IWBINV, CACH_SD) => "Index_WBInvalidate(SD)",
(C_ILT, CACH_PI) => "Index_Load_Tag(PI)",
(C_ILT, CACH_PD) => "Index_Load_Tag(PD)",
(C_ILT, CACH_SI) => "Index_Load_Tag(SI)",
(C_ILT, CACH_SD) => "Index_Load_Tag(SD)",
(C_IST, CACH_PI) => "Index_Store_Tag(PI)",
(C_IST, CACH_PD) => "Index_Store_Tag(PD)",
(C_IST, CACH_SI) => "Index_Store_Tag(SI)",
(C_IST, CACH_SD) => "Index_Store_Tag(SD)",
(C_CDX, CACH_PD) => "Create_Dirty_Excl(PD)",
(C_CDX, CACH_SD) => "Create_Dirty_Excl(SD)",
(C_HINV, CACH_PI) => "Hit_Invalidate(PI)",
(C_HINV, CACH_PD) => "Hit_Invalidate(PD)",
(C_HINV, CACH_SI) => "Hit_Invalidate(SI)",
(C_HINV, CACH_SD) => "Hit_Invalidate(SD)",
(C_FILL, CACH_PI) => "Fill(PI)",
(C_HWBINV, CACH_PD) => "Hit_WBInvalidate(PD)",
(C_HWBINV, CACH_SI) => "Hit_WBInvalidate(SI)",
(C_HWBINV, CACH_SD) => "Hit_WBInvalidate(SD)",
(C_HWB, CACH_PD) => "Hit_WB(PD)",
(C_HWB, CACH_SD) => "Hit_WB(SD)",
(C_HSV, CACH_SI) => "Hit_Set_Virtual(SI)",
(C_HSV, CACH_SD) => "Hit_Set_Virtual(SD)",
_ => "Unknown",
}
}
// =============================================================================
// R4000 Cache Tag Format (per MIPS R4000 book)
// =============================================================================
// L1 Instruction Cache Tag — single u64 encodes both address and valid state.
//
// Encoding:
// ptag = 0 → invalid (Default)
// ptag = (phys_addr & !0xFFF) | 1 → valid; line base address in bits [35:1], valid flag in bit 0
//
// Bit 0 of a page-aligned physical address is always 0, so it is free to use as a valid sentinel.
// This lets matches_phys() be a single branchless compare with no separate bool load:
// self.ptag == (phys_addr & !0xFFF) | 1
//
// On-wire (CP0 TagLo) format: [31:8] raw_ptag [7:6] pstate
// Conversion: From<u32>/Into<u32> for snapshot save/load only (shifts happen there, not on hot path).
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct L1ITag {
/// Encoded tag: 0 = invalid; `(phys_line_base & !0xFFF) | 1` = valid.
pub ptag: u64,
}
impl L1ITag {
/// Construct a valid tag for the given physical address.
#[inline(always)]
pub fn valid(phys_addr: u64) -> Self { Self { ptag: (phys_addr & !0xFFF) | 1 } }
/// True iff this tag is valid and covers the same physical line as `phys_addr`.
/// Branchless: one AND+OR on phys_addr, one 64-bit compare. No separate bool load or branch.
#[inline(always)]
pub fn matches_phys(&self, phys_addr: u64) -> bool {
self.ptag == (phys_addr & !0xFFF) | 1
}
/// True iff this tag is valid (for non-hot-path use only).
#[inline(always)]
pub fn is_valid(&self) -> bool { self.ptag & 1 != 0 }
/// Physical line base address (bits \[11:0\] are zero). Only meaningful if is_valid().
#[inline(always)]
pub fn line_addr(&self) -> u64 { self.ptag & !0xFFF }
}
impl From<u32> for L1ITag {
// Deserialize from CP0 TagLo wire format: raw_ptag in bits [31:8], pstate in [7:6].
fn from(v: u32) -> Self {
let raw_ptag = (v >> 8) & L1_PTAG_MASK;
let valid = (v >> 6) & 3 != 0;
let line = (raw_ptag as u64) << L1_PTAG_SHIFT;
Self { ptag: if valid { line | 1 } else { 0 } }
}
}
impl From<L1ITag> for u32 {
fn from(t: L1ITag) -> Self {
let raw_ptag = (t.line_addr() >> L1_PTAG_SHIFT) as u32 & L1_PTAG_MASK;
(raw_ptag << 8) | (if t.is_valid() { 2 << 6 } else { 0 })
}
}
// L1 Data Cache Tag — ptag encodes both address and validity, cs/dirty are cold-path fields.
//
// Encoding:
// ptag = 0 → invalid (Default)
// ptag = (phys_addr & !0xFFF) | 1 → valid; line base in bits [35:1], valid sentinel in bit 0
//
// Bit 0 of a page-aligned address is always 0, so it is free as a valid sentinel.
// matches_phys() is a single branchless compare — no cs load, no branch.
// cs is only read on cold paths (writeback decisions, CACHE instruction, debug).
// cs and ptag validity are kept in sync: both set on fill, both cleared on invalidate.
//
// cs = Cache State byte: 0=Invalid, 1=Shared, 2=CleanExclusive, 3=DirtyExclusive
// dirty = write-back bit — separate byte for branch-free set on every write
//
// On-wire format is the physical D-cache line tag, R4400 manual Figure 11-4:
// [27] W (write-back) [25:24] CS [23:0] PTag
// W' and P are parity over fields we do not model, so they stay zero.
// Conversion: From<u32>/Into<u32> for snapshot save/load only.
/// Geometry the jitv2 inline load/store path needs as codegen immediates.
/// `supported == false` means the cache cannot serve the inline path at all
/// (no cache, or a shape the first implementation does not cover, e.g. R5000's
/// 2-way L1-D — see docs/jit-inline-memory.md §4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JitDcGeometry {
pub supported: bool,
/// `addr >> line_shift & num_lines_mask` = tag index.
pub line_shift: u32,
pub num_lines_mask: u64,
/// `virt_addr & data_mask` = byte offset into the data array.
pub data_mask: u64,
/// L2 present at all (`HAS_L2`). When false the inline tcache store skips
/// the decoded-instruction invalidation entirely, matching
/// `tc_invalidate_l2_code`'s own early return.
pub has_l2: bool,
/// `phys >> l2_line_shift & l2_num_lines_mask` = L2 tag index.
pub l2_line_shift: u32,
pub l2_num_lines_mask: u64,
/// L1-D associativity: 1 (R4400) or 2 (R5000). With `ways == 2` the
/// emitted guard probes both ways and, on a hit, updates the per-set LRU
/// bit exactly as `ensure_l1d_line` does.
pub ways: u32,
/// `set | (way << num_lines_shift)` = extended tag index. Only meaningful
/// when `ways > 1`.
pub num_lines_shift: u32,
/// No L1-D model at all: loads and stores go straight to memory, so under
/// tcache the inline path is the ppmem-window half alone, with no tag
/// probe, no LRU and no dirty bit (the R10000's shadow cache). The other
/// fields are then unused.
pub tagless: bool,
/// Inline stores bump the page generation with an atomic add: other writers
/// are active, and a plain add landing after theirs would move the counter
/// backwards and let stale code publish.
pub atomic_gen: bool,
/// The ppmem window's `window_shift`: its bitmap's region size, baked
/// into the mapped test on every guest load and store.
pub window_shift: u32,
}
impl JitDcGeometry {
pub const fn unsupported() -> Self {
Self {
supported: false, line_shift: 0, num_lines_mask: 0, data_mask: 0,
has_l2: false, l2_line_shift: 0, l2_num_lines_mask: 0,
ways: 1, num_lines_shift: 0, tagless: false, atomic_gen: false,
window_shift: crate::ppmem::BITMAP_SHIFT,
}
}
}
/// `#[repr(C)]`: jitv2's inline load/store fast path addresses `ptag` and
/// `dirty` directly from compiled code at fixed byte offsets within the tag
/// array (docs/jit-inline-memory.md §3.1), the same requirement `MipsCore`
/// documents for itself. Offsets are taken with `offset_of!` at codegen time,
/// never hardcoded — but the layout must at least be stable and declared.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct L1DTag {
/// Encoded tag: 0 = invalid; `(phys_line_base & !0xFFF) | 1` = valid.
pub ptag: u64,
pub cs: u8,
pub dirty: bool,
}
impl L1DTag {
/// Construct a valid tag for the given physical address and cache state.
#[inline(always)]
pub fn valid(phys_addr: u64, cs: u8, dirty: bool) -> Self {
Self {
ptag: (phys_addr & !0xFFF) | 1,
cs,
dirty,
}
}
/// True iff this tag is valid and covers the same physical line as `phys_addr`.
/// Branchless: one AND+OR on phys_addr, one 64-bit compare. No cs load, no branch.
///
/// A line carrying [`Self::SLOW`] never matches here, by design: that is
/// how it reaches the miss path. Anything that must find the line
/// regardless (CACHE hit ops, write-back and invalidation scans) uses
/// [`Self::matches_line`].
#[inline(always)]
pub fn matches_phys(&self, phys_addr: u64) -> bool {
self.ptag == (phys_addr & !0xFFF) | 1
}
/// Bit 1 of `ptag`: send every access to this line through the miss path.
///
/// Parity forcing (Status.CE) and forced-parity lines need a check on
/// each access, and the hit path cannot afford one. A marked line fails
/// the exact compare in `matches_phys`, in the interpreter and in jitv2's
/// inline guard alike, so the check lives in the miss path at no cost to
/// anything else. Bit 1 of a page-aligned address is free, like bit 0.
pub const SLOW: u64 = 2;
/// [`Self::matches_phys`], ignoring the [`Self::SLOW`] mark.
#[inline]
pub fn matches_line(&self, phys_addr: u64) -> bool {
self.ptag & !Self::SLOW == (phys_addr & !0xFFF) | 1
}
/// True iff this tag is valid (for non-hot-path use only).
#[inline(always)]
pub fn is_valid(&self) -> bool { self.ptag & 1 != 0 }
/// Physical line base address (bits \[11:0\] are zero). Only meaningful if is_valid().
#[inline(always)]
pub fn line_addr(&self) -> u64 { self.ptag & !0xFFF }
}
impl From<u32> for L1DTag {
fn from(v: u32) -> Self {
let raw_ptag = v & L1_PTAG_MASK;
let cs = ((v >> L1D_TAG_CS_SHIFT) & 0x3) as u8;
let line = (raw_ptag as u64) << L1_PTAG_SHIFT;
Self {
ptag: if cs != 0 { line | 1 } else { 0 },
cs,
dirty: (v >> L1D_TAG_W_SHIFT) & 1 != 0,
}
}
}
impl From<L1DTag> for u32 {
fn from(t: L1DTag) -> Self {
let raw_ptag = (t.line_addr() >> L1_PTAG_SHIFT) as u32 & L1_PTAG_MASK;
raw_ptag | ((t.cs as u32 & 0x3) << L1D_TAG_CS_SHIFT)
| ((t.dirty as u32) << L1D_TAG_W_SHIFT)
}
}
/// Convert a tag word from before `dc_tag_format`, which put `PTag` at `[31:8]`
/// so that `W` overlapped its bit 19, physical address bit 31. A v0 word is
/// ambiguous there, `phys_bit31 | dirty`, and this resolves it in favour of
/// dirty: the format predates every machine with memory at or above
/// `0x8000_0000`, so no v0 tag can mean an address up there.
pub fn migrate_l1d_tag_word_v0(word: u32) -> u32 {
let raw_ptag = (word >> 8) & L1_PTAG_MASK & !(1 << 19);
let cs = (word >> 6) & 0x3;
let w = (word >> 27) & 1;
raw_ptag | (cs << L1D_TAG_CS_SHIFT) | (w << L1D_TAG_W_SHIFT)
}
/// Even parity over `v`: the bit that makes the total count of ones even.
#[inline]
pub fn even_parity(v: u32) -> u32 { v.count_ones() & 1 }
/// R4000 secondary-cache tag check matrix, UM Figure 16-4. Entry `i` selects
/// the tag bits (CS:PIdx:STag, `[24:0]` as in Figure 11-6) that check bit `i`
/// covers. Every tag bit has a distinct weight-3 syndrome; see
/// `l2_tag_ecc_matrix_is_the_manuals`.
const L2_TAG_ECC_MASKS: [u32; 7] = [
0x1ff1111, 0x045222f, 0x10a40ff, 0x09184f0, 0x0620f42, 0x114ff04, 0x0a8f888,
];
/// The 7 check bits the R4400 generates for a secondary tag.
///
/// Not stored: the hardware computes them whenever a tag is written and
/// ignores the ECC field of TagLo on `Index_Store_Tag` (UM p. 93), so
/// computing them when the tag is read back gives the same value with nothing
/// to keep in sync.
pub fn l2_tag_ecc(tag: u32) -> u32 {
L2_TAG_ECC_MASKS.iter().enumerate()
.fold(0, |ecc, (i, &m)| ecc | even_parity(tag & m) << i)
}
/// R4000 secondary-cache data check matrix, UM Figure 16-1: entry `i` selects
/// the data bits check bit `i` covers. Pinned by
/// `l2_data_ecc_matrix_is_the_manuals`.
const L2_DATA_ECC_MASKS: [u64; 8] = [
0x145011110ff014ff, 0x24ff2222f000249f, 0x4c9f444400ff44d0, 0x84d08888ff0f8c50,
0x0931f0ff11110b21, 0x0b22ff002222fa32, 0xfa24000f4444ff24, 0xff280ff088880928,
];
/// The 8 check bits the R4400 computes for a secondary-cache doubleword.
pub fn l2_data_ecc(v: u64) -> u8 {
L2_DATA_ECC_MASKS.iter().enumerate()
.fold(0, |ecc, (i, &m)| ecc | (((v & m).count_ones() & 1) as u8) << i)
}
/// R4400/R5000 Index_Store_Tag: the TagLo a later Index_Load_Tag returns,
/// without its check bits. A tag is only as wide as its fields, so this is
/// what a cache keeping raw TagLo words must store to read back what the
/// full model does (see `CpuCache::cache_op`, which keeps them as fields):
///
/// - primary: PTag\[31:8\] and PState\[7:6\]. An invalid line keeps nothing. Any
/// valid I-cache state reads back as 2; on the R5000, which has no Shared
/// state, a stored 1 reads back as 2.
/// - secondary (R4400): STag\[31:13\], SState\[12:10\] (reserved 1-3 read back as
/// 0), PIdx\[9:7\].
pub fn r4k_store_taglo(r5k: bool, sel: u32, taglo: u32) -> u32 {
if matches!(sel, CACH_SI | CACH_SD) {
let state = match (taglo >> 10) & 7 { s @ 4..=7 => s, _ => 0 };
return (taglo & 0xFFFF_E000) | state << 10 | (taglo & 0x380);
}
let pstate = match (taglo >> 6) & 3 {
0 => return 0,
_ if sel == CACH_PI => 2,
1 if r5k => 2,
p => p,
};
(taglo & 0xFFFF_FF00) | pstate << 6
}
/// [`r4k_store_taglo`]'s word as Index_Load_Tag returns it: with the check
/// bits the hardware generates (TagLo\[0\] P on a primary, TagLo\[6:0\] ECC on
/// the R4400 secondary).
pub fn r4k_load_taglo(r5k: bool, sel: u32, stored: u32) -> u32 {
if matches!(sel, CACH_SI | CACH_SD) {
let fields = (stored >> 10 & 7) << 22 | (stored >> 7 & 7) << 19 | stored >> 13;
return stored | l2_tag_ecc(fields);
}
let pstate = (stored >> 6) & 3;
let p = even_parity(stored >> 8)
^ if r5k { 0 } else if sel == CACH_PI { (pstate != 0) as u32 } else { even_parity(pstate) };
stored | p
}
// L2 Cache Tag
// [31:25] ECC - Error correction code; not stored, see `l2_tag_ecc`
// [24:22] CS - Cache State (0=Invalid, 4=CleanExcl, 5=DirtyExcl, 6=Shared, 7=DirtyShared)
// [21:19] PIdx - Virtual address bits [14:12] (primary cache aliasing)
// [18:0] PTag - Physical address bits [35:17]
bitfield! {
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub struct L2Tag(u32);
impl Debug;
pub u32, ptag, set_ptag: 18, 0; // Physical tag bits [35:17]
pub u32, pidx, set_pidx: 21, 19; // Virtual index bits [14:12] for VIPT aliasing
pub u32, cs, set_cs: 24, 22; // Cache State (3-bit)
/// tcache: this L2 line's `l2.instrs` slots hold valid decoded
/// instructions for this physical line.
///
/// Under tcache, L2 *data* is bypassed entirely — nothing is copied in or
/// written back — but on R4400 the decode slots live in `l2.instrs`
/// indexed by physical address, so L1I fills still need L2 to hold them.
/// A line filled on behalf of L1D therefore has valid tags but *no* valid
/// instructions, and an L1I fill must not mistake it for a usable hit.
/// Set only by an instruction-origin fill; see `fill_l2_line`'s
/// `fill_instructions` argument.
pub bool, has_code, set_has_code: 25;
}
// Address reconstruction constants
/// PTag for L1 covers phys addr bits \[35:12\]; index supplies bits \[11:0\]
pub const L1_PTAG_SHIFT: u32 = 12;
pub const L1_PTAG_MASK: u32 = 0x00FF_FFFF; // 24-bit field
pub const L1_INDEX_MASK: u64 = 0xFFF;
/// Serialized L1D tag field positions, R4400 manual Figure 11-4. PTag occupies
/// \[23:0\], so CS and W sit above it and nothing overlaps.
pub const L1D_TAG_CS_SHIFT: u32 = 24;
pub const L1D_TAG_W_SHIFT: u32 = 27;
/// PTag for L2 covers phys addr bits \[35:17\]; index supplies bits \[16:0\]
pub const L2_PTAG_SHIFT: u32 = 17;
pub const L2_PTAG_MASK: u32 = 0x0007_FFFF; // 19-bit field
pub const L2_INDEX_MASK: u64 = 0x1FFFF;
/// PIdx comes from virtual address bits \[14:12\]
pub const L2_PIDX_VADDR_SHIFT: u32 = 12;
pub const L2_PIDX_VADDR_MASK: u32 = 0x7; // 3-bit field
// L1 D-Cache CS (Cache State) values
pub const L1D_CS_INVALID: u32 = 0;
pub const L1D_CS_SHARED: u32 = 1;
pub const L1D_CS_CLEAN_EXCLUSIVE: u32 = 2;
pub const L1D_CS_DIRTY_EXCLUSIVE: u32 = 3;
// L2 CS (Cache State) values
pub const L2_CS_INVALID: u32 = 0;
pub const L2_CS_CLEAN_EXCLUSIVE: u32 = 4;
pub const L2_CS_DIRTY_EXCLUSIVE: u32 = 5;
pub const L2_CS_SHARED: u32 = 6;
pub const L2_CS_DIRTY_SHARED: u32 = 7;
/// Reconstruct the physical base address from an L1I cache tag and an address in the same line.
/// Uses `line_addr()` to strip the valid sentinel bit before OR-ing in the offset.
#[inline]
pub fn l1_tag_to_phys(tag: L1ITag, index_addr: u64) -> u64 {
tag.line_addr() | (index_addr & L1_INDEX_MASK)
}
/// Same as `l1_tag_to_phys` for the L1D tag.
#[inline]
pub fn l1d_tag_to_phys(tag: L1DTag, index_addr: u64) -> u64 {
tag.line_addr() | (index_addr & L1_INDEX_MASK)
}
/// Reconstruct the physical base address from an L2 cache tag and the address used to index
/// the cache line. `index_addr` contributes the low 17 bits.
#[inline]
pub fn l2_tag_to_phys(tag: L2Tag, index_addr: u64) -> u64 {
(tag.ptag() as u64) << L2_PTAG_SHIFT | (index_addr & L2_INDEX_MASK)
}
impl From<u32> for L2Tag { fn from(v: u32) -> Self { L2Tag(v) } }
impl From<L2Tag> for u32 { fn from(t: L2Tag) -> Self { t.0 } }
// =============================================================================
// Cache Operations Interface (for CACHE instruction)
// =============================================================================
// Cache operation is encoded in bits [20:16] of CACHE instruction (rt field)
// Format: [20:18] = operation, [17:16] = cache target
// We decode this u32 internally to determine what to do
// =============================================================================
// Main Cache Interface
// =============================================================================
/// Main cache interface - supports both memory access and cache operations
///
/// This trait combines:
/// - Instruction fetch from L1-I cache
/// - Data read/write through L1-D cache (VIPT)
/// - Cache operations for CACHE instruction support
/// - Load-Linked / Store-Conditional support
/// Per-model settings that are not cache behaviour: ISA level, CP0/CP1 identity, TLB size.
/// Const, so every use folds at monomorphisation instead of costing a runtime check.
/// tcache instrumentation: how often the transparency gate was consulted and
/// how often it said yes. Developer builds only; printed by `tc_stats()`.
#[cfg(all(feature = "tcache", feature = "developer"))]
pub static TC_PROBES: AtomicU64 = AtomicU64::new(0);
#[cfg(all(feature = "tcache", feature = "developer"))]
pub static TC_HITS: AtomicU64 = AtomicU64::new(0);
/// tcache: (probes, hits) since process start.
#[cfg(all(feature = "tcache", feature = "developer"))]
pub fn tc_stats() -> (u64, u64) {
(TC_PROBES.load(Ordering::Relaxed), TC_HITS.load(Ordering::Relaxed))
}
pub trait CpuModel: MipsCache {
/// MIPS IV opcodes decode rather than raising Reserved Instruction.
const MIPS4: bool;
/// CP0 PRId reset value.
const PRID: u32;
/// CP1 FIR reset value.
const FIR: u32;
/// JTLB entries.
const TLB_ENTRIES: usize;
/// Implemented virtual address bits.
///
/// 40 on the R4x00/R5000, **44 on the R10000**. This is not cosmetic: it
/// sets the width of XContext's BadVPN2 field and therefore where its
/// Region and PTEBase fields sit, which is how a 64-bit kernel finds the
/// page-table entry for a faulting address.
const VA_BITS: u32 = 40;
/// Implemented physical address bits: 36 on the R4x00/R5000, 40 on the
/// R10000. LLAddr holds `PA[PA_BITS-1:4]`.
const PA_BITS: u32 = 36;
/// The bits of LLAddr that exist.
const LLADDR_MASK: u64 = (1 << (Self::PA_BITS - 4)) - 1;
/// Name as the guest and the benchmark report see it.
const NAME: &'static str;
/// "full" for the model whose arrays loads, stores and fetches consult;
/// "shadow" for one that keeps only what CACHE ops observe. Recorded in
/// snapshots: a full cache's state does not load into a shadow one.
const CACHE_KIND: &'static str = "full";
/// Cache ops 5/6/7 carry their R10000 meanings rather than their R4000 ones.
/// The executor needs this: `Index_Store_Data` takes its value from TagLo
/// and `Index_Load_Data` returns into it, neither of which is true of the
/// R4000 hit operations that share those encodings.
const R10K_CACHE_OPS: bool = false;
/// What each CACHE encoding does on this model, derived from
/// [`Self::R10K_CACHE_OPS`].
const CACHE_OPS: CacheOpMasks = CacheOpMasks::for_model(Self::R10K_CACHE_OPS);
/// The part is in the R10000 family, which shares one programming model:
/// FrameMask, and 44 virtual and 40 physical address bits.
/// Established for the R10000. The R12000 is inferred to match: its manual's
/// list of changes from the R10000 has no TLB or CP0 change. The R14000 is
/// a model choice that gives it the same TLB.
const R10K_FAMILY: bool = Self::R10K_CACHE_OPS;
/// A partial LWR keeps bits 63:32 of the destination. Observed on the
/// R10000; whether the later parts do the same is not established, so they
/// keep the sign extension for now.
const PARTIAL_LWR_KEEPS_UPPER: bool = Self::R10K_FAMILY;
/// With FR set, a single or word result (arithmetic, MOV.S, the
/// conditional moves whether or not they move, MTC1, LWC1) zeroes bits
/// 63:32 of the destination. The architecture leaves them undefined; the R10000
/// sets them to zero (R10000 UM v2.0 pp. 306, 313), and the NEC
/// VR10000/VR12000 manual repeats it for results (p. 279). That page calls
/// an untaken conditional move's upper half undefined, so zeroing it on the
/// R12000 and R14000 is a model choice. The other parts keep the old upper word.
const SINGLE_CLEARS_UPPER: bool = Self::R10K_FAMILY;
/// A conversion to an integer format that cannot hold the result (NaN,
/// infinity, out of range) takes Unimplemented Operation instead of
/// raising Invalid with the 2^31-1 / 2^63-1 default result. Every part
/// IRIS models does: an Indy R4400 rev 6.0 traps CVT.W.S of 2^31 and of
/// +infinity with Cause.E (`cpu-tests/oracle/r4400-rev6.0-run5-clean.log`),
/// the VR5000 manual lists an out-of-range word conversion as a cause of
/// the exception (9.4.6), "R10000 took an unimplemented exception
/// whenever a conversion from an FP value would result in a value that
/// cannot be represented in the target format", and the R12000 kept it
/// except for a denormal source with FCSR.FS set, which it flushes to
/// zero (NEC VR10000 Series User's Manual U10278EJ4V0UM, Appendix B.4,
/// p. 350). The R14000 is inferred to match. The kernel's FP emulator
/// delivers the architectural Invalid result.
const CVT_UNREPRESENTABLE_UNIMPLEMENTED: bool = true;
/// CVT.L and the other long conversions take Unimplemented Operation for
/// a result outside [-2^N, 2^N) instead of the format's own range, for
/// this N; 63 means the format's own range. The VR5000 takes it outside
/// [-2^53, 2^53) (manual 9.4.6: "greater than 2^53-1 ... or less than
/// -2^53"); the R4400 is inferred to match, as it does for the long
/// sources below. "In the R10000, the conversion allows only up to 51
/// bits; otherwise an Unimplemented Operation exception is taken"
/// (R10000 UM v2.0, p. 312), read as 51 bits of magnitude beside the
/// sign. The R12000's manual has neither sentence, so the R12000 and
/// later use the full range. The cache models override this for the
/// R10000 itself, which `R10K_FAMILY` cannot tell from its successors.
const CVT_L_RANGE_BITS: u32 = if Self::R10K_FAMILY { 63 } else { 53 };
/// CVT.S.L and CVT.D.L take Unimplemented Operation for a source outside
/// [-2^N, 2^N), for this N; 63 means every long converts. The VR5000
/// takes it outside [-2^52, 2^52) (manual 9.4.6: "greater than 2^52-1
/// ... or less than -2^52"). An Indy R4400 rev 6.0 and an R5000 rev 1.0
/// both convert 2^40+1 and trap 2^53+1 and 2^62
/// (`cpu-tests/tests/fpu/fpu_vectors.c`, `fpu/vec_cvt_from_l`), which
/// fits the manual's bound. The R10000 family converts every long.
const CVT_FROM_L_RANGE_BITS: u32 = if Self::R10K_FAMILY { 63 } else { 52 };
/// An uncached store the system refuses completes instead of raising a
/// Data Bus Error. The R10000 sends it as a write request, which gets no
/// response, and Bus Error comes only from an error response to a read or
/// upgrade request or from uncorrectable read data (R10000 UM pp. 104, 316).
/// The R12000 manual documents the same path and the later parts are taken
/// to match. An uncached SC succeeding is a model choice. Loads and fetches
/// still fault.
const POSTS_UNCACHED_STORES: bool = Self::R10K_FAMILY;
/// Bits `Index_Store_Tag` keeps for the secondary cache: all of them, except
/// on the R10000 family, whose reserved tag bits read as zero (R10000 UM
/// p. 270, figure 11-31). Kept are MRU (bit 63), the physical tag (TagHi 3:0
/// and TagLo 31:14), state, virtual index and ECC; TagLo bits 9, 12 and 13
/// and TagHi 30:4 read as zero.
const SECONDARY_TAG_MASK: u64 = if Self::R10K_FAMILY { 0x8000_000f_ffff_cdff } else { u64::MAX };
}
pub trait MipsCache: Send + Sync {
/// Share the L1-I hit/fetch counters with the status display. No-op where absent.
fn set_l1i_counters(&mut self, _hit: Arc<AtomicU64>, _fetch: Arc<AtomicU64>) {}
/// tcache: point the cache at ppmem's window and mapped-region bitmap, so
/// cacheable RAM accesses read/write RAM directly instead of copying line
/// data (docs/tcache-design.md). Default no-op — a cache with no
/// transparent path simply ignores it.
///
/// # Safety
/// `base` must be ppmem's window base and `bitmap` a live `u64` that
/// outlives this cache.
unsafe fn set_tcache_window(&self, _base: *mut u8) {}
/// The cached view this cache reads memory through
/// (`PpMemSpace::add_cached_view`), as `sp` and its number, so valid
/// lines can hold their pages there. Set with the window, before the CPU
/// runs. No-op where the cache holds no lines.
///
/// # Safety
/// `sp` must outlive the cache.
unsafe fn set_cached_view(&self, _sp: *const crate::ppmem::PpMemSpace, _view: usize) {}
/// The ppmem window's `window_shift`, when it is not the 4GB window's.
fn set_tcache_shift(&self, _shift: u32) {}
/// tcache: the window's fine table (`PpMemSpace::fine_table`), which the
/// cache tests on a miss in the region bitmap before taking the bus.
/// Default no-op: such a cache takes the bus.
///
/// # Safety
/// `table` must hold `regions` bits and outlive this cache.
unsafe fn set_tcache_fine(&self, _table: *const std::sync::atomic::AtomicU64, _regions: u64) {}
/// tcache: pointer to this cache's key for the window pointers it keeps,
/// for `PpMemSpace::add_key_sink`. Null when it keeps none.
fn tcache_key_ptr(&self) -> *mut u64 { std::ptr::null_mut() }
/// Whether `fetch` of cacheable RAM only reads: no line fill, no LRU or
/// tag change, no exception. Then a caller that does not need the
/// instruction (jitv2 entering compiled code) may leave the fetch out.
/// Default `false`: a model that keeps instruction-cache state does.
fn fetch_is_pure(&self) -> bool { false }
/// Write every dirty line back to memory, so RAM holds everything.
/// Default no-op: a cache that holds no data has nothing to write.
fn writeback_all(&self) {}
/// tcache: pointer to this cache's inline mapped-region bitmap, for
/// `MappedMemory::set_bitmap_sink2`. Null when the cache has no such field.
fn tcache_bitmap_ptr(&self) -> *mut u64 { std::ptr::null_mut() }
/// tcache: base of the ppmem window this cache reads/writes through
/// (`tc_base + phys`). Null until `set_transparent_base` runs.
fn tcache_base_ptr(&self) -> *mut u8 { std::ptr::null_mut() }
/// tcache: base of the jitv2 per-page generation array (`[AtomicU64]`,
/// indexed by `phys >> 12`). An inline store through the ppmem window
/// must bump this or self-modifying code stops invalidating compiled
/// regions — see `tc_bump_gen`. Null when jitv2/ppmem is not wired up.
#[cfg(feature = "jitv2")]
fn tcache_gen_ptr(&self) -> *mut u8 { std::ptr::null_mut() }
// ---- jitv2 inline load/store fast path (docs/jit-inline-memory.md) ----
//
// Raw bases the JIT's compiled code indexes directly, mirrored into
// `MipsCore` by `install_jit_mem_ptrs` so compiled code can reach them at
// a fixed offset off `core_ptr`. Backing storage is a boxed slice with a
// stable address, so caching the pointer is sound — but any path that can
// reallocate it (snapshot restore, reconfigure) MUST re-install.
//
// Default null: a null `jit_dc_tags` is the signal that this cache cannot
// support the inline path, and codegen must not emit it.
/// Base of the L2 tag array (`[L2Tag]`, one `u32` each). The inline
/// tcache store path uses it to clear `has_code` for the written line,
/// mirroring `tc_invalidate_l2_code`. Null when there is no L2.
fn jit_l2_tags_ptr(&self) -> *mut u8 { std::ptr::null_mut() }
/// Base of the L1-D tag array (`[L1DTag]`). Null if unsupported.
fn jit_dc_tags_ptr(&self) -> *mut u8 { std::ptr::null_mut() }
/// Number of L1-D tag entries, and the line shift used to index them.
/// Codegen needs these as immediates; they are const-generic on the cache
/// type and differ between R4400 and R5000.
fn jit_dc_geometry(&self) -> JitDcGeometry { JitDcGeometry::unsupported() }
/// Base of the L1-D per-set LRU bitmap (`[u64]`, one bit per set), for the
/// 2-way inline path's hit-side LRU update. Null on a direct-mapped model,
/// where there is no LRU state at all.
fn jit_dc_lru_ptr(&self) -> *mut u8 { std::ptr::null_mut() }
/// tcache + jitv2: hand the cache ppmem's generation-window base, so window
/// writes bump the per-page counter jitv2 validates compiled code against.
/// Default no-op.
///
/// # Safety
/// `gen_base` must be ppmem's gen window base and outlive this cache.
#[cfg(feature = "jitv2")]
unsafe fn set_tcache_gen_window(&self, _gen_base: *mut AtomicU64) {}
/// L1/L2 geometry, so CP0 Config reports this model rather than a build-time constant.
const IC_SIZE: usize;
const IC_LINE: usize;
const IC_WAYS: usize;
const DC_SIZE: usize;
const DC_LINE: usize;
const DC_WAYS: usize;
const L2_SIZE: usize;
const L2_LINE: usize;
/// Fetch instruction from L1 instruction cache.
/// Returns `FetchInstrResult::hit(ptr)` on success, `FetchInstrResult::exception(status)` on error.
/// The caller must call `decode_into` on the slot before use.
fn fetch(&self, virt_addr: u64, phys_addr: u64) -> FetchInstrResult;
/// Read data using virtual and physical addresses.
/// Uses virtual address for index, physical address for tag (VIPT).
/// SIZE must be 1, 2, 4, or 8 bytes (const generic, zero runtime branch).
/// Returns BusRead64 with data zero-extended to u64 on success.
/// status may be BUS_OK, BUS_BUSY, BUS_ERR, or BUS_VCE (cache only).
fn read<const SIZE: usize>(&self, virt_addr: u64, phys_addr: u64) -> BusRead64;
/// Write SIZE bytes directly — no RMW, no mask computation.
/// SIZE must be 1, 2, 4, or 8 (const generic).
/// val is zero-extended; only the low SIZE*8 bits are used.
/// phys_addr must be SIZE-aligned. Returns BUS_OK, BUS_BUSY, BUS_ERR, or BUS_VCE.
fn write<const SIZE: usize>(&self, virt_addr: u64, phys_addr: u64, val: u64) -> u32;
/// Would the JIT's inline load/store fast path have handled this access
/// without calling out to Rust? Side-effect-free predicate, `jitstats`
/// only — it exists to size and tune the inline emit before (and while)
/// building it, and doubles as the executable spec of what that emit must
/// check.
///
/// `STORE` selects the store predicate, which is strictly narrower: a
/// store may only proceed inline on an already-dirty line, because the
/// clean->dirty transition is a read-modify-write on the tag that is not
/// worth emitting (the first store to a line calls out; the rest inline).
///
/// The stages, in the order compiled code would test them:
/// 1. L1D tag matches `phys_addr` (one 64-bit compare)
/// 2. store only: that line is dirty
/// 3. tcache only: `phys_addr` is in a transparent (mapped RAM) region
///
/// The nutlb hit that must precede all of this is counted separately, in
/// the executor — the cache layer never sees translation outcomes.
#[cfg(feature = "jitstats")]
fn jit_probe<const STORE: bool>(&self, _virt_addr: u64, _phys_addr: u64) -> bool { false }
/// Arbitrary-mask doubleword write — escape hatch for SDL/SDR partial stores.
/// phys_addr must be 8-byte aligned. val/mask are in MIPS big-endian doubleword space.
/// Returns BUS_OK, BUS_BUSY, BUS_ERR, or BUS_VCE.
fn write64_masked(&self, virt_addr: u64, phys_addr: u64, val: u64, mask: u64) -> u32;
/// Execute a cache operation (CACHE instruction)
///
/// cache_op: Combined operation and cache target from bits \[20:16\] of CACHE instruction
/// - Bits \[20:18\]: Operation (C_IINV, C_ILT, C_IST, C_CDX, C_HINV, C_HWBINV/C_FILL, C_HWB, C_HSV)
/// - Bits \[17:16\]: Cache target (CACH_PI, CACH_PD, CACH_SI, CACH_SD)
/// virt_addr: Virtual address from instruction (used for index operations)
/// phys_addr: Physical address (used for hit operations and tags)
///
/// For Index_Load_Tag operations, returns the tag value in TagLo CP0 register format
/// For other operations, returns 0
/// Perform a CACHE operation. For `Index_Load_Tag` the return is the
/// tag as software sees it, full width — an R10000 secondary tag does not
/// fit in 32 bits.
fn cache_op(&self, cache_op: u32, virt_addr: u64, phys_addr: u64) -> u64;
/// CP0 `ECC` ($26) on the way in to a cache-data store.
///
/// On an R10000 the check bits ride with the data: `Index_Store_Data`
/// takes them from this register and `Index_Load_Data` returns them
/// there. Models that do not keep them ignore both of these.
fn set_cache_ecc(&self, _v: u32) {}
/// The translated physical address of the CACHE operand about to be
/// passed to `cache_op`. The R10000's secondary set and way come from it
/// rather than from the virtual address (NEC U12754EJ1V0UMJ1 pp. 14-15).
/// Taken by the next `cache_op`, which falls back to the virtual address
/// if none was set. Models that index by the virtual address ignore it.
fn set_cache_op_pa(&self, _pa: u64) {}
/// The Status bits that govern cache error checking: CE (store the ECC
/// register as check bits instead of computing them) and whether errors
/// are detected at all (neither DE nor ERL set). Pushed by the executor on
/// every Status change. Models that keep no check bits ignore it.
fn set_error_control(&self, _ce: bool, _detect: bool) {}
/// CacheErr for the Cache Error exception the last access reported
/// (`EXEC_CACHE_ERR`).
fn take_cache_err(&self) -> u32 { 0 }
/// A Cache Error raised by the CACHE instruction just executed (an I-cache
/// write-back of a line with bad parity), as an exception status, or 0.
/// Reading it clears it.
fn take_op_status(&self) -> u32 { 0 }
/// CP0 `ECC` after the last cache operation.
fn cache_op_ecc(&self) -> u32 { 0 }
/// Write back dirty L1-D (and, if present, L2) lines covering
/// `[phys_addr, phys_addr + size)` to memory, without invalidating them.
///
/// `virt_addr`, if given, is the virtual address corresponding to
/// `phys_addr` (same page offset) — L1-D is VIPT, so a real virtual
/// address lets each line be found directly, the same way a normal
/// access would. When `virt_addr` is `None` (phys-only), every possible
/// virtual alias of each physical line is checked instead (L1-D indexes
/// on more bits than the page offset guarantees are VA==PA, so a purely
/// physical address cannot rule any alias out) — this may write back
/// lines that happen to tag-match but do not actually belong to the
/// running program's mapping, which is fine for a diagnostic/flush op.
///
/// Returns the number of dirty lines actually written back (L1-D + L2).
fn writeback(&self, _virt_addr: Option<u64>, _phys_addr: u64, _size: u64) -> usize { 0 }
/// Get cache configuration for a specific cache target
/// cache_target: CACH_PI (0), CACH_PD (1), CACH_SI (2), or CACH_SD (3)
/// Returns (size in bytes, line size in bytes)
fn get_config(&self, cache_target: u32) -> (usize, usize);
/// Get physical memory bus device for direct access
fn downstream(&self) -> Arc<dyn BusDevice>;
/// Check and clear Load-Linked bit if address matches
fn check_and_clear_llbit(&self, phys_addr: u64);
/// Get Load-Linked bit state
fn get_llbit(&self) -> bool;
/// Set Load-Linked bit state
fn set_llbit(&self, val: bool);
/// Atomically store `new` to the RAM word at `phys` if it still holds
/// `old`. `None`: this model cannot, or `phys` is not RAM it can reach
/// directly, and the caller stores the ordinary way. Only models that keep
/// no data of their own can serve several CPUs.
fn cas_ram32(&self, _phys: u64, _old: u32, _new: u32) -> Option<bool> { None }
/// The doubleword form of [`Self::cas_ram32`].
fn cas_ram64(&self, _phys: u64, _old: u64, _new: u64) -> Option<bool> { None }
/// Get Load-Linked address
fn get_lladdr(&self) -> u64;
/// Set Load-Linked address
fn set_lladdr(&self, addr: u64);
/// Debug probe a virtual+physical address (optional, for debugging)
fn debug_probe(&self, _cache_name: &str, _virt_addr: u64, _phys_addr: u64) -> String {
"Debug not implemented for this cache type".to_string()
}
/// Debug dump a cache line by index (optional, for debugging)
fn debug_dump_line(&self, _cache_name: &str, _idx: usize) -> String {
"Debug not implemented for this cache type".to_string()
}
/// R5K/Triton: set L2 enable state from CONFIG_SE bit. No-op on R4K.
/// When transitioning disabled→enabled, all L2 lines are invalidated.
fn set_l2_enabled(&mut self, _enabled: bool) {}
/// Restore power-on state — invalidate all cache lines (tags → 0).
fn power_on(&self) {}
/// Serialize full cache state (tags, data, LL/SC) to a TOML value.
fn save_cache_state(&self) -> toml::Value {
toml::Value::Table(Default::default())
}
/// Restore full cache state from a TOML value.
fn load_cache_state(&self, _v: &toml::Value) -> Result<(), String> {
Ok(())
}
}
// =============================================================================
// Passthrough Cache - No caching, for testing
// =============================================================================
/// Passthrough cache that performs no caching - all accesses go directly to memory
/// Useful for testing and debugging
pub struct PassthroughCacheOf<const MIPS4: bool> {
downstream: Arc<dyn BusDevice>,
llbit: UnsafeCell<bool>,
lladdr: UnsafeCell<u64>,
/// Scratch slot for fetch() — no actual caching, just a place to decode into.
fetch_scratch: UnsafeCell<DecodedInstr>,
}
// Safety: Single-threaded access only (CPU thread)
unsafe impl<const MIPS4: bool> Send for PassthroughCacheOf<MIPS4> {}
unsafe impl<const MIPS4: bool> Sync for PassthroughCacheOf<MIPS4> {}