Repository navigation
Expand file tree
/
Copy pathheart.rs
More file actions
1309 lines (1215 loc) · 49 KB
/
Copy pathheart.rs
File metadata and controls
1309 lines (1215 loc) · 49 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
//! HEART, the Octane's processor and memory controller: the bank
//! descriptors that place SDRAM, the 64 interrupt bits that drive the
//! R10000's interrupt pins, a 52-bit counter, a MicroLAN master for the
//! processor module's ID part, and the XIO widget (widget 8) the Crossbow's
//! other widgets reach memory and interrupts through.
//!
//! It is a functional model rather than a register-exact HEART: accesses it
//! does not support are recorded (see [`Heart::unsupported`]) and the guest
//! sees a fixed answer. Each approximation is said where it lives.
//! Register offsets follow OpenBSD's `xheartreg.h` and Linux's
//! `asm/sgi/heart.h`.
//!
//! The processor sees HEART's registers at [`PIU_BASE`] and its widget
//! registers at the start of widget 8's small window; `Ip30Bus` maps
//! both to this device, which takes the full physical address. Memory is
//! `heart_mem::HeartRam`, which a descriptor write reaches through
//! [`Heart::on_memcfg`].
//!
//! Ported from hw/misc/sgi-heart.c in jamesbraid/qemu-sgi-origami.
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::sync::Arc;
use parking_lot::Mutex;
use crate::cpu::smp::{current_cpu, ParkSlot, HOLD_HEART, MAX_CPUS};
use crate::dev::w1;
use crate::devlog::LogModule;
use crate::snapshot::{field, field_bool, field_u32, field_u32s, field_u64, field_u64s, StateTable};
use crate::traits::{BusDevice, BusRead16, BusRead32, BusRead64, BusRead8, Saveable, BUS_ERR, BUS_OK};
/// HEART's processor-interface registers.
pub const PIU_BASE: u64 = 0x0ff0_0000;
pub const PIU_SIZE: u64 = 0x0006_0008;
/// HEART's own widget registers, at the start of widget 8's small window.
pub const WIDGET_BASE: u64 = 0x1800_0000;
pub const WIDGET_REG_SIZE: u64 = 0x1000;
pub const BANKS: usize = 4;
const COUNT_MASK: u64 = (1 << 52) - 1;
/// The counter's PIU offset.
const COUNTER: u32 = 0x20000;
/// The `heart` log shows one counter read in this many.
const COUNTER_SAMPLE: u64 = 256;
/// The counter ticks at 12.5 MHz.
const COUNT_NS: u64 = 80;
const LEVEL_MASKS: [u64; 5] = [
0x0000_0000_0000_ffff,
0x0000_0000_ffff_0000,
0x0003_ffff_0000_0000,
0x0004_0000_0000_0000,
0xfff8_0000_0000_0000,
];
/// HEART's levels 0 to 4 are the CPU's IP2 to IP6: Cause bits 10 to 14.
const CAUSE_SHIFT: u32 = 10;
/// Mode register bits the model looks at.
const MODE_INTERRUPT_ENABLE: u64 = 1 << 13;
/// Software reset, of the whole machine.
const MODE_SOFT_RESET: u64 = 1 << 22;
/// Processor n stops being served while bit `60 + n` is set, and continues
/// where it stopped when it clears.
const MODE_PROC_DISABLE_SHIFT: u32 = 60;
const MODE_ECC_GENERATE: u64 = 1 << 19;
const MODE_ECC_DOUBLE: u64 = 1 << 20;
const MODE_ECC_FORCE_WRITE: u64 = 1 << 21;
/// The memory-error interrupt bit, which only reaches the CPU while the
/// mode register enables it.
const ECC_PENDING: u64 = 1 << 63;
const ONEWIRE_DONE: u64 = 2;
const ONEWIRE_LEVEL: u64 = 1;
/// HEART's registers. Everything is behind one lock: no register access
/// calls out except to drive the CPU's interrupt word, a leaf atomic.
struct Regs {
mode: u64,
sdram_mode: u64,
mem_refresh: u64,
mem_req_arb: u64,
flow_cell: [u64; 2],
clock_divider: u64,
compare: u32,
descriptor: [u32; 8],
mask: [u64; 4],
pending: u64,
ecc_cause: u64,
ecc_address: u64,
ecc_data: u64,
/// The counter is `saved_count` plus the ticks since `epoch_ns` on the
/// machine clock, which holds still while the machine is stopped.
saved_count: u64,
epoch_ns: u64,
/// The largest count handed out: CPU threads on different sockets read the host clock a few
/// hundred ns apart, but one counter never goes back.
last_count: std::cell::Cell<u64>,
widget_control: u32,
widget_request_timeout: u32,
widget_error_mask: u32,
onewire_control: u64,
onewire_deadline_ns: u64,
onewire_level: bool,
onewire_busy: bool,
/// The levels last driven onto each processor's IP2..IP6.
out: [u8; MAX_CPUS],
}
impl Regs {
fn new(now: u64) -> Self {
Self {
mode: 0,
sdram_mode: 0,
mem_refresh: 0,
mem_req_arb: 0,
flow_cell: [0; 2],
clock_divider: 0,
compare: 0,
descriptor: [0; 8],
mask: [0; 4],
pending: 0,
ecc_cause: 0,
ecc_address: 0,
ecc_data: 0,
saved_count: 0,
epoch_ns: now,
last_count: std::cell::Cell::new(0),
widget_control: 0,
widget_request_timeout: 0,
widget_error_mask: 0,
onewire_control: 0,
onewire_deadline_ns: 0,
onewire_level: false,
onewire_busy: false,
out: [0; MAX_CPUS],
}
}
fn counter(&self, now: u64) -> u64 {
let count = (self.saved_count + now.saturating_sub(self.epoch_ns) / COUNT_NS).max(self.last_count.get());
self.last_count.set(count);
count & COUNT_MASK
}
/// What processor `cpu`'s IP2..IP6 should be: its mask over the pending
/// bits, one output per level. An inter-processor interrupt needs nothing
/// more: the sender sets the destination's bit, which only its mask has.
fn levels(&self, cpu: usize) -> u8 {
let mut enabled = self.pending & self.mask[cpu];
let mut out = 0u8;
for (i, m) in LEVEL_MASKS.iter().enumerate().take(4) {
if enabled & m != 0 {
out |= 1 << i;
}
}
if self.mode & MODE_INTERRUPT_ENABLE == 0 {
enabled &= !ECC_PENDING;
}
if enabled & LEVEL_MASKS[4] != 0 {
out |= 1 << 4;
}
out
}
fn banks(&self) -> [u32; BANKS] {
[self.descriptor[0], self.descriptor[1], self.descriptor[2], self.descriptor[3]]
}
}
/// What a machine fixes about its HEART.
#[derive(Clone, Debug)]
pub struct HeartConfig {
/// Each bank's capacity in bytes, for the monitor.
pub banks: [u64; BANKS],
/// The widget identification word's revision field.
pub widget_revision: u8,
/// The whole identification word, when the machine pins it; 0 builds it
/// from the revision.
pub widget_id_64: u64,
/// Processors populated, from 0 up: the status register's active bits, and
/// the outputs driven.
pub cpus: u8,
}
impl HeartConfig {
/// The Octane: HEART revision D (4) and its identification word.
pub fn octane(banks: [u64; BANKS]) -> Self {
Self { banks, widget_revision: 4, widget_id_64: 0x4c00_106d, cpus: 1 }
}
}
/// Nanoseconds from some fixed point, for the counter and the MicroLAN slot
/// timing: the machine clock's [`reader`](crate::clock::Clock::reader).
pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
pub struct Heart {
regs: Mutex<Regs>,
cfg: HeartConfig,
clock: Clock,
/// Each CPU's interrupt word (`MipsCore`'s), once the machine has it.
cpu_irq: [AtomicPtr<AtomicU64>; MAX_CPUS],
/// Where the MODE register's disable bits hold each CPU.
cpu_park: Mutex<[Option<Arc<ParkSlot>>; MAX_CPUS]>,
/// The guest asked for a software reset.
reset_hook: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
/// Where descriptor writes go: the machine points it at
/// `Ip30Bus::remap_banks`.
memcfg_hook: Mutex<Option<Box<dyn Fn([u32; BANKS]) + Send + Sync>>>,
/// The processor module's MicroLAN: the PM10 board record.
mlan: Mutex<w1::Bus>,
/// Accesses this model does not support, first 64 distinct, for the
/// monitor: `(offset, size, write)`.
unsupported: Mutex<Vec<(u32, u8, bool)>>,
/// `unsupported` holds 64: a further access costs one relaxed load.
unsupported_full: AtomicBool,
/// Packets that reached HEART's interrupt register, for the monitor.
pub packets: AtomicU64,
/// Counter reads while the `heart` log is on, for its sampling.
counter_reads: AtomicU64,
}
impl Heart {
pub fn new(cfg: HeartConfig, clock: Clock) -> Self {
let now = clock();
Self {
regs: Mutex::new(Regs::new(now)),
cfg,
clock,
cpu_irq: std::array::from_fn(|_| AtomicPtr::new(std::ptr::null_mut())),
cpu_park: Mutex::new(Default::default()),
reset_hook: Mutex::new(None),
memcfg_hook: Mutex::new(None),
mlan: Mutex::new(w1::Bus::new()),
unsupported: Mutex::new(Vec::new()),
unsupported_full: AtomicBool::new(false),
packets: AtomicU64::new(0),
counter_reads: AtomicU64::new(0),
}
}
pub fn config(&self) -> &HeartConfig {
&self.cfg
}
/// Where HEART's levels go: the CPU's interrupt word
/// (`MipsCpu::interrupts_ptr`). HEART's five outputs, levels 0 to 4,
/// are the CPU's IP2 to IP6 (Cause bits 10 to 14); HEART touches no
/// other bit. The word must outlive this HEART.
pub fn set_interrupts(&self, word: *const AtomicU64) {
self.set_cpu_interrupts(0, word);
}
/// [`Self::set_interrupts`] for processor `cpu`.
pub fn set_cpu_interrupts(&self, cpu: usize, word: *const AtomicU64) {
let r = self.regs.lock();
self.cpu_irq[cpu].store(word as *mut AtomicU64, Ordering::Release);
// Publish the levels as they stand into the new word.
self.drive(cpu, 0x1f, r.out[cpu]);
}
/// Where the MODE register's disable bits hold processor `cpu`.
pub fn set_cpu_park(&self, cpu: usize, slot: Arc<ParkSlot>) {
self.cpu_park.lock()[cpu] = Some(slot);
}
/// Call `f` when the guest sets the software-reset bit. On the writing
/// CPU's thread, outside HEART's lock.
pub fn on_soft_reset(&self, f: Box<dyn Fn() + Send + Sync>) {
*self.reset_hook.lock() = Some(f);
}
/// Hold or release the CPUs whose disable bits changed from `old` to `new`.
/// Under the register lock: the slots are leaves.
fn apply_disables(&self, old: u64, new: u64) {
let changed = (old ^ new) >> MODE_PROC_DISABLE_SHIFT;
if changed == 0 {
return;
}
let park = self.cpu_park.lock();
for (cpu, slot) in park.iter().enumerate() {
let Some(slot) = slot else { continue };
if changed & (1 << cpu) != 0 {
if new >> (MODE_PROC_DISABLE_SHIFT + cpu as u32) & 1 != 0 {
slot.hold(HOLD_HEART);
} else {
slot.release(HOLD_HEART);
}
}
}
}
/// The status register: which processors are populated, and HEART's widget id.
fn status(&self) -> u64 {
let active = (1u64 << self.cfg.cpus) - 1;
(active << 4) | 8
}
/// Call `f` with the four bank descriptors whenever the guest (or a
/// reset) changes one. Called outside HEART's lock, on the thread that
/// wrote the register.
pub fn on_memcfg(&self, f: Box<dyn Fn([u32; BANKS]) + Send + Sync>) {
*self.memcfg_hook.lock() = Some(f);
}
/// The bank descriptors as they stand.
pub fn memcfg(&self) -> [u32; BANKS] {
self.regs.lock().banks()
}
/// Put the processor module's MicroLAN on HEART's master.
pub fn set_microlan(&self, bus: w1::Bus) {
*self.mlan.lock() = bus;
}
pub fn unsupported(&self) -> Vec<(u32, u8, bool)> {
self.unsupported.lock().clone()
}
pub fn register_locks(self: &Arc<Self>) {
crate::locks::register_mutex_fn("heart::regs", self, |h| h.regs.is_locked());
crate::locks::register_mutex_fn("heart::mlan", self, |h| h.mlan.is_locked());
}
fn note(&self, off: u32, size: usize, write: bool) {
if self.unsupported_full.load(Ordering::Relaxed) {
return;
}
let mut u = self.unsupported.lock();
if !u.iter().any(|&(o, s, w)| o == off && s as usize == size && w == write) {
if trace() {
eprintln!("ip30: HEART: unsupported {size}-byte {} at {off:#x}", if write { "write" } else { "read" });
}
u.push((off, size as u8, write));
if u.len() == 64 {
self.unsupported_full.store(true, Ordering::Relaxed);
}
}
}
fn memcfg_changed(&self, banks: [u32; BANKS]) {
if let Some(f) = self.memcfg_hook.lock().as_ref() {
f(banks);
}
}
/// Set the outputs in `changed` to `levels` in the CPU's word, as the
/// IOC does on the Indy. Under the register lock: the word is a leaf.
fn drive(&self, cpu: usize, changed: u8, levels: u8) {
let p = self.cpu_irq[cpu].load(Ordering::Acquire);
if p.is_null() || changed == 0 {
return;
}
// SAFETY: `set_interrupts`'s contract: the word outlives HEART.
let word = unsafe { &*p };
let set = ((changed & levels) as u64) << CAUSE_SHIFT;
let clear = ((changed & !levels) as u64) << CAUSE_SHIFT;
if set != 0 {
word.fetch_or(set, Ordering::SeqCst);
#[cfg(feature = "idle-pause")]
crate::cpu::idle_park::wake();
}
if clear != 0 {
word.fetch_and(!clear, Ordering::SeqCst);
}
}
/// Drive the CPU's pins to what the registers now say.
fn update_irq(&self, r: &mut Regs) {
for cpu in 0..self.cfg.cpus as usize {
let new = r.levels(cpu);
if new != r.out[cpu] {
let changed = new ^ r.out[cpu];
r.out[cpu] = new;
self.drive(cpu, changed, new);
}
}
}
/// The level IPn (n = 2..6) is at, for tests and the monitor.
pub fn pin(&self, n: u32) -> bool {
assert!((2..=6).contains(&n), "HEART drives IP2 to IP6, not IP{n}");
self.regs.lock().out[0] & (1 << (n - 2)) != 0
}
pub fn pending(&self) -> u64 {
self.regs.lock().pending
}
// ── MicroLAN ───────────────────────────────────────
/// One bit slot, started by a write of the command register: the part
/// answers at once (`w1::slot`), and the done bit follows after pulse +
/// sample, counted as microseconds (the silicon's units are not known).
fn onewire_start(&self, r: &mut Regs, command: u64) {
let (pulse, sample) = w1::slot::fields(command);
r.onewire_control = command & !(ONEWIRE_DONE | ONEWIRE_LEVEL);
r.onewire_level = w1::slot::slot(&mut self.mlan.lock(), pulse, sample);
r.onewire_busy = true;
r.onewire_deadline_ns = (self.clock)() + (pulse + sample) as u64 * 1000;
}
fn onewire_refresh(&self, r: &mut Regs) {
if r.onewire_busy && (self.clock)() >= r.onewire_deadline_ns {
r.onewire_busy = false;
r.onewire_control |= ONEWIRE_DONE;
if r.onewire_level {
r.onewire_control |= ONEWIRE_LEVEL;
}
}
}
// ── processor-interface registers ───────────────────
/// A PIU register read of `size` bytes (4 or 8; HEART refuses narrower
/// accesses, `None`). Unsupported offsets read as zero and are recorded.
pub fn piu_read(&self, off: u32, size: usize) -> Option<u64> {
if size != 4 && size != 8 {
return None;
}
let mut r = self.regs.lock();
if (0x20..0x40).contains(&off) {
let n = ((off - 0x20) / 4) as usize;
if size == 4 {
return Some(r.descriptor[n] as u64);
}
if n & 1 == 0 {
return Some(((r.descriptor[n] as u64) << 32) | r.descriptor[n + 1] as u64);
}
}
if (off == 0xb8 && size == 8) || (off == 0xbc && size == 4) {
self.onewire_refresh(&mut r);
return Some(r.onewire_control);
}
if size == 8 {
let v = match off {
0x00 => Some(r.mode),
0x08 => Some(r.sdram_mode),
0x10 => Some(r.mem_refresh),
0x18 => Some(r.mem_req_arb),
0x50 => Some(r.flow_cell[0]),
0x58 => Some(r.flow_cell[1]),
0x80 => Some(self.status()),
0x98 => Some(r.ecc_address),
0xa0 => Some(r.ecc_data),
0xb0 => Some(r.clock_divider),
0x10000 | 0x10008 | 0x10010 | 0x10018 => Some(r.mask[((off - 0x10000) / 8) as usize]),
0x10030 => Some(r.pending),
// The reader's own mask: a CPU services what it enabled.
0x10038 => Some(r.pending & r.mask[current_cpu()]),
0x10040 => Some(r.ecc_cause),
COUNTER => Some(r.counter((self.clock)())),
0x30000 => Some(r.compare as u64),
// Who is asking.
0x50000 => Some(current_cpu() as u64),
_ => None,
};
if let Some(v) = v {
return Some(v);
}
}
drop(r);
self.note(off, size, false);
Some(0)
}
/// A PIU register write; false is a refused width. Unsupported offsets
/// are recorded and otherwise ignored.
pub fn piu_write(&self, off: u32, size: usize, val: u64) -> bool {
if size != 4 && size != 8 {
return false;
}
let mut r = self.regs.lock();
if (0x20..0x40).contains(&off) {
let n = ((off - 0x20) / 4) as usize;
if size == 4 || n & 1 == 0 {
if size == 4 {
r.descriptor[n] = val as u32;
} else {
r.descriptor[n] = (val >> 32) as u32;
r.descriptor[n + 1] = val as u32;
}
let banks = r.banks();
drop(r);
// On the CPU thread: the window may only be remapped there.
self.memcfg_changed(banks);
return true;
}
}
if (off == 0xb8 && size == 8) || (off == 0xbc && size == 4) {
self.onewire_start(&mut r, val);
return true;
}
if size == 8 {
match off {
0x00 => {
// ECC generation and forced writes plant errors in
// memory, which this model does not do.
if val & (MODE_ECC_GENERATE | MODE_ECC_DOUBLE | MODE_ECC_FORCE_WRITE) != 0 {
if trace() {
eprintln!("ip30: HEART: mode {val:#x} asks for ECC error injection");
}
drop(r);
self.note(off, size, true);
r = self.regs.lock();
}
let old = std::mem::replace(&mut r.mode, val);
self.apply_disables(old, val);
self.update_irq(&mut r);
if val & !old & MODE_SOFT_RESET != 0 {
drop(r);
if let Some(f) = self.reset_hook.lock().as_ref() {
f();
}
}
return true;
}
0x08 => r.sdram_mode = val,
0x10 => r.mem_refresh = val,
0x18 => r.mem_req_arb = val,
0x50 => r.flow_cell[0] = val,
0x58 => r.flow_cell[1] = val,
0xb0 => r.clock_divider = val,
0x10040 => r.ecc_cause &= !val,
// Stored, not compared: the model raises no timer vector.
0x30000 => r.compare = (val & 0xff_ffff) as u32,
0x10000 | 0x10008 | 0x10010 | 0x10018 => {
r.mask[((off - 0x10000) / 8) as usize] = val;
self.update_irq(&mut r);
}
0x10020 => {
r.pending |= val;
self.update_irq(&mut r);
}
0x10028 => {
r.pending &= !val;
self.update_irq(&mut r);
}
_ => {
drop(r);
self.note(off, size, true);
}
}
return true;
}
drop(r);
self.note(off, size, true);
true
}
// ── widget registers ───────────────────────────────
/// HEART's widget registers as the processor and other widgets see
/// them, `None` for an access this model refuses.
pub fn widget_read(&self, off: u32, size: usize) -> Option<u64> {
let r = self.regs.lock();
match (off, size) {
(0x00, 8) | (0x04, 4) => Some(if self.cfg.widget_id_64 != 0 {
if size == 4 {
self.cfg.widget_id_64 & 0xffff_ffff
} else {
self.cfg.widget_id_64
}
} else {
((self.cfg.widget_revision as u64) << 28) | (0xc001 << 12) | (0x0036 << 1)
}),
(0x24, 4) => Some(r.widget_control as u64),
(0x28, 8) | (0x2c, 4) => Some(r.widget_request_timeout as u64),
(0x14 | 0x1c | 0x44, 4) => Some(0),
(0x60 | 0x70 | 0x78 | 0x90, 8) => Some(0),
(0x68, 8) => Some(r.widget_error_mask as u64),
_ => {
drop(r);
self.note(0x1000_0000 | off, size, false);
None
}
}
}
pub fn widget_write(&self, off: u32, size: usize, val: u64) -> bool {
let mut r = self.regs.lock();
match (off, size) {
(0x24, 4) => r.widget_control = val as u32,
(0x28, 8) | (0x2c, 4) => r.widget_request_timeout = val as u32,
// The error-command word, taken only as a zero write. IRIX
// 6.5.30's bus-error probe clears it with a 64-bit store to the
// slot (OpenBSD's map puts the 64-bit slot at +0x40, the word in
// its low half at +0x44); that is the same zero write.
(0x44, 4) | (0x40, 8) if val == 0 => {}
// Nothing here produces widget errors, so status stays zero.
(0x60, 8) => {}
(0x68, 8) => r.widget_error_mask = val as u32,
_ => {
drop(r);
self.note(0x1000_0000 | off, size, true);
return false;
}
}
true
}
/// An interrupt packet: a doubleword write of `value` to HEART's widget
/// offset 0x80, bits 7:0 the vector and bit 8 set or clear. Anything
/// else there is refused.
pub fn packet_write(&self, off: u64, size: usize, value: u64) -> bool {
if off != 0x80 || size != 8 || value & !0x1ff != 0 || value & 0xff >= 64 {
self.note(0x2000_0000 | off as u32, size, true);
return false;
}
self.set_vector((value & 0xff) as u8, value & 0x100 != 0);
true
}
fn set_vector(&self, vector: u8, set: bool) {
crate::dlog!(LogModule::Heart, "heart: vector {vector} {}", if set { "raised" } else { "lowered" });
self.packets.fetch_add(1, Ordering::Relaxed);
let mut r = self.regs.lock();
if set {
r.pending |= 1 << vector;
} else {
r.pending &= !(1 << vector);
}
self.update_irq(&mut r);
}
/// The counter, for the monitor.
pub fn counter(&self) -> u64 {
self.regs.lock().counter((self.clock)())
}
/// The register block `addr` (a full physical address) falls in: the
/// processor interface (true) or the widget registers, with the offset.
#[inline]
fn block(addr: u64) -> Option<(bool, u32)> {
if (PIU_BASE..PIU_BASE + PIU_SIZE).contains(&addr) {
Some((true, (addr - PIU_BASE) as u32))
} else if (WIDGET_BASE..WIDGET_BASE + WIDGET_REG_SIZE).contains(&addr) {
Some((false, (addr - WIDGET_BASE) as u32))
} else {
None
}
}
fn bus_read(&self, addr: u64, size: usize) -> Option<u64> {
let (piu, off) = Self::block(addr)?;
let v = if piu { self.piu_read(off, size) } else { self.widget_read(off, size) };
if crate::devlog::devlog_is_active(LogModule::Heart) {
if !(piu && off & !7 == COUNTER) {
crate::devlog::devlog().write(LogModule::Heart, format_args!("heart: read {} {off:#x} /{size} -> {}",
if piu { "piu" } else { "widget" }, v.map_or("bus error".to_string(), |v| format!("{v:#x}"))));
} else if self.counter_reads.fetch_add(1, Ordering::Relaxed) % COUNTER_SAMPLE == 0 {
// The counter is read too often to log every read; one in
// COUNTER_SAMPLE, with the host's clock, shows its rate.
crate::devlog::devlog().write(LogModule::Heart, format_args!("heart: counter read -> {:#x} at host {} ns (1 in {COUNTER_SAMPLE})",
v.unwrap_or(0), (self.clock)()));
}
}
v
}
fn bus_write(&self, addr: u64, size: usize, val: u64) -> u32 {
let Some((piu, off)) = Self::block(addr) else { return BUS_ERR };
crate::dlog!(LogModule::Heart, "heart: write {} {off:#x} /{size} {val:#x}", if piu { "piu" } else { "widget" });
let ok = if piu { self.piu_write(off, size, val) } else { self.widget_write(off, size, val) };
if ok {
BUS_OK
} else {
BUS_ERR
}
}
}
/// HEART as the target of interrupts: line `n` is ISR bit `n`, the vector
/// (0 to 63) a widget's interrupt packet carries or a device wired to HEART
/// raises. A true level is a set packet, false the matching clear. ISR is
/// not an OR of its inputs: two sources on one vector share the bit, as on
/// the hardware. A line beyond 63 cannot be carried by a packet and is
/// dropped. Safe from any thread; it drives the CPU's interrupt word, a
/// leaf, under HEART's own lock, and calls nothing else.
impl crate::irq::InterruptController for Heart {
fn set_line(&self, line: u32, level: bool) {
if line < 64 {
self.set_vector(line as u8, level);
} else {
self.note(0x2000_0080, 8, true);
}
}
}
/// The two register blocks, at full physical addresses: the processor
/// interface at [`PIU_BASE`] and the widget registers at [`WIDGET_BASE`].
/// Anything else in the slots `Ip30Bus` gives HEART is a bus error.
impl BusDevice for Heart {
fn read8(&self, addr: u64) -> BusRead8 {
self.bus_read(addr, 1).map_or(BusRead8::err(), |v| BusRead8::ok(v as u8))
}
fn read16(&self, addr: u64) -> BusRead16 {
self.bus_read(addr, 2).map_or(BusRead16::err(), |v| BusRead16::ok(v as u16))
}
fn read32(&self, addr: u64) -> BusRead32 {
self.bus_read(addr, 4).map_or(BusRead32::err(), |v| BusRead32::ok(v as u32))
}
fn read64(&self, addr: u64) -> BusRead64 {
self.bus_read(addr, 8).map_or(BusRead64::err(), BusRead64::ok)
}
fn write8(&self, addr: u64, val: u8) -> u32 {
self.bus_write(addr, 1, val as u64)
}
fn write16(&self, addr: u64, val: u16) -> u32 {
self.bus_write(addr, 2, val as u64)
}
fn write32(&self, addr: u64, val: u32) -> u32 {
self.bus_write(addr, 4, val as u64)
}
fn write64(&self, addr: u64, val: u64) -> u32 {
self.bus_write(addr, 8, val)
}
}
/// Reset: every register to zero, the counter from zero, the MicroLAN
/// master idle. Memory keeps its contents; with no descriptor valid none of
/// it is reachable until the PROM (or the machine) sets them again.
impl crate::traits::Resettable for Heart {
fn power_on(&self) {
let now = (self.clock)();
let mut r = self.regs.lock();
let at = now;
let out = r.out;
let old_mode = r.mode;
*r = Regs::new(now);
r.out = out;
// Every processor is served again.
self.apply_disables(old_mode, 0);
self.update_irq(&mut r);
let banks = r.banks();
drop(r);
self.memcfg_changed(banks);
}
}
fn trace() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("IRIS_IP30_TRACE").is_some())
}
/// HEART has no thread. Its counter holds while the machine is stopped
/// because the machine clock does.
impl crate::traits::Device for Heart {
fn step(&self, _cycles: u64) {}
fn stop(&self) {}
fn start(&self) {}
fn is_running(&self) -> bool {
true
}
fn get_clock(&self) -> u64 {
0
}
fn register_commands(&self) -> Vec<(String, String)> {
vec![("heart".into(), "HEART: heart [status|unsupported]".into())]
}
fn execute_command(&self, cmd: &str, args: &[&str], mut w: Box<dyn std::io::Write + Send>) -> Result<(), String> {
if cmd != "heart" {
return Err("Command not found".into());
}
let out = match args.first().copied().unwrap_or("status") {
"status" => {
let r = self.regs.lock();
let mut s = format!(
"mode {:#x} pending {:#018x} mask0 {:#018x} out IP2-6 {:05b} counter {:#x} packets {}\n",
r.mode,
r.pending,
r.mask[0],
r.out[0],
r.counter((self.clock)()),
self.packets.load(Ordering::Relaxed)
);
let park = self.cpu_park.lock();
for cpu in 1..self.cfg.cpus as usize {
s.push_str(&format!("cpu {cpu}: mask {:#018x} out IP2-6 {:05b}\n", r.mask[cpu], r.out[cpu]));
}
if self.cfg.cpus > 1 {
for (cpu, slot) in park.iter().enumerate().take(self.cfg.cpus as usize) {
if let Some(slot) = slot {
let disabled = r.mode >> (MODE_PROC_DISABLE_SHIFT + cpu as u32) & 1 != 0;
s.push_str(&format!("cpu {cpu}: {} holds {:#x}{}\n",
if slot.is_parked() { "parked" } else { "running" },
slot.holds(),
if disabled { " (disabled in MODE)" } else { "" }));
}
}
}
drop(park);
for (i, d) in r.descriptor[..BANKS].iter().enumerate() {
s.push_str(&format!("bank {i}: descriptor {d:#010x}, {} MiB installed\n", self.cfg.banks[i] >> 20));
}
s
}
"unsupported" => self
.unsupported()
.iter()
.map(|(o, s, w)| format!("{} {s} bytes at {o:#x}\n", if *w { "write" } else { "read" }))
.collect(),
other => return Err(format!("heart: unknown subcommand {other}")),
};
w.write_all(out.as_bytes()).map_err(|e| e.to_string())
}
}
// HEART's state for a snapshot: its registers, the counter and the
// MicroLAN. The counter runs on the host clock: it is saved as its value
// and how far into its tick it was, and resumes from there at the load, as
// the CPU's Count does, so the guest sees no jump. A MicroLAN slot in
// progress keeps its deadline in machine time, which a restore puts back first. After a load HEART drives every
// processor's pins from the loaded registers, holds or releases the
// processors its mode disables, and has memory placed from the loaded
// descriptors.
impl Saveable for Heart {
fn save_state(&self) -> toml::Value {
let now = (self.clock)();
let r = self.regs.lock();
let elapsed = now.saturating_sub(r.epoch_ns);
StateTable::new()
.u64s("words", &[
r.mode, r.sdram_mode, r.mem_refresh, r.mem_req_arb, r.clock_divider, r.pending,
r.ecc_cause, r.ecc_address, r.ecc_data, r.onewire_control,
])
.u64s("flow_cell", &r.flow_cell)
.u32("compare", r.compare)
.u32s("descriptor", &r.descriptor)
.u64s("mask", &r.mask)
.u64("count", r.counter(now))
.u64("phase", elapsed % COUNT_NS)
.u32s("widget", &[r.widget_control, r.widget_request_timeout, r.widget_error_mask])
.u64("onewire_at", r.onewire_deadline_ns)
.bool("onewire_level", r.onewire_level)
.bool("onewire_busy", r.onewire_busy)
.value("microlan", self.mlan.lock().save_state())
.build()
}
/// Called with the machine stopped and HEART powered on.
fn load_state(&self, v: &toml::Value) -> Result<(), String> {
let [mode, sdram_mode, mem_refresh, mem_req_arb, clock_divider, pending, ecc_cause,
ecc_address, ecc_data, onewire_control] = field_u64s::<10>(v, "words")?;
let [widget_control, widget_request_timeout, widget_error_mask] = field_u32s::<3>(v, "widget")?;
let phase = field_u64(v, "phase")?;
self.mlan.lock().load_state(field(v, "microlan")?).map_err(|e| format!("MicroLAN: {e}"))?;
let now = (self.clock)();
let mut r = self.regs.lock();
let old_mode = r.mode;
let out = r.out;
*r = Regs {
mode, sdram_mode, mem_refresh, mem_req_arb, clock_divider, pending, ecc_cause,
ecc_address, ecc_data, onewire_control,
flow_cell: field_u64s(v, "flow_cell")?,
compare: field_u32(v, "compare")?,
descriptor: field_u32s(v, "descriptor")?,
mask: field_u64s(v, "mask")?,
saved_count: field_u64(v, "count")?,
last_count: std::cell::Cell::new(0),
// A clock still inside its first tick cannot carry the phase.
epoch_ns: now.checked_sub(phase).unwrap_or(now),
widget_control, widget_request_timeout, widget_error_mask,
onewire_deadline_ns: field_u64(v, "onewire_at")?,
onewire_level: field_bool(v, "onewire_level")?,
onewire_busy: field_bool(v, "onewire_busy")?,
out,
};
// Clear what HEART drove before the load, then drive the loaded levels.
let driven = std::mem::replace(&mut r.out, [0; MAX_CPUS]);
for (cpu, &levels) in driven.iter().enumerate().take(self.cfg.cpus as usize) {
self.drive(cpu, levels, 0);
}
self.apply_disables(old_mode, r.mode);
self.update_irq(&mut r);
let banks = r.banks();
drop(r);
self.memcfg_changed(banks);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::irq::InterruptController;
use crate::traits::Resettable;
struct Fixture {
heart: Heart,
clock: crate::clock::Clock,
}
impl Fixture {
fn step_us(&self, us: u64) {
self.clock.step(us * 1000);
}
}
fn heart() -> Fixture {
let clock = crate::clock::Clock::stepped();
let heart = Heart::new(HeartConfig::octane([128 << 20, 0, 0, 0]), clock.reader());
Fixture { heart, clock }
}
fn wq(h: &Heart, off: u32, v: u64) {
assert!(h.piu_write(off, 8, v));
}
fn rq(h: &Heart, off: u32) -> u64 {
h.piu_read(off, 8).unwrap()
}
/// HEART holds raw pointers to `words`, so they stay together: taking a
/// test's HEART out alone would leave it writing into freed memory.
struct TwoCpus {
h: Heart,
words: Box<[AtomicU64; 2]>,
slots: [Arc<ParkSlot>; 2],
}
fn two_cpu_heart() -> TwoCpus {
let mut cfg = HeartConfig::octane([128 << 20, 0, 0, 0]);
cfg.cpus = 2;
let h = Heart::new(cfg, Arc::new(|| 0));
let words = Box::new([AtomicU64::new(0), AtomicU64::new(0)]);
let slots = [Arc::new(ParkSlot::new(0, &words[0])), Arc::new(ParkSlot::new(1, &words[1]))];
for cpu in 0..2 {
h.set_cpu_interrupts(cpu, &words[cpu]);
h.set_cpu_park(cpu, slots[cpu].clone());
}
TwoCpus { h, words, slots }
}
/// Runs `f` on a thread that is CPU `cpu`, as HEART sees it.
fn as_cpu<R: Send>(cpu: u8, f: impl FnOnce() -> R + Send) -> R {
std::thread::scope(|s| {
s.spawn(move || {
crate::cpu::smp::set_current_cpu(cpu);
f()
})
.join()
.unwrap()
})
}
const LEVEL2_IP4_CAUSE: u64 = 1 << 12;
#[test]
fn each_cpu_reads_its_own_number_and_all_see_the_fitted_ones() {
let TwoCpus { h, .. } = &two_cpu_heart();
assert_eq!(as_cpu(0, || rq(&h, 0x50000)), 0);
assert_eq!(as_cpu(1, || rq(&h, 0x50000)), 1);
assert_eq!(as_cpu(1, || rq(&h, 0x80)), 0x38);
}
#[test]
fn one_fitted_cpu_reads_as_it_always_did() {
let f = heart();
assert_eq!(rq(&f.heart, 0x80), 0x18);
assert_eq!(rq(&f.heart, 0x50000), 0);
}
#[test]
fn an_ipi_interrupts_only_its_destination() {
let TwoCpus { h, words, .. } = &two_cpu_heart();
let ipi = |cpu: u32| 1u64 << (46 + cpu);
wq(&h, 0x10000, ipi(0));
wq(&h, 0x10008, ipi(1));
as_cpu(0, || wq(&h, 0x10020, ipi(1)));
assert_eq!(words[0].load(Ordering::SeqCst) & LEVEL2_IP4_CAUSE, 0);
assert_ne!(words[1].load(Ordering::SeqCst) & LEVEL2_IP4_CAUSE, 0);
as_cpu(1, || wq(&h, 0x10028, ipi(1)));
assert_eq!(words[1].load(Ordering::SeqCst) & LEVEL2_IP4_CAUSE, 0);
}
#[test]
fn imsr_is_masked_by_the_reader() {
let TwoCpus { h, .. } = &two_cpu_heart();
wq(&h, 0x10000, 0b01);
wq(&h, 0x10008, 0b10);
wq(&h, 0x10020, 0b11);
assert_eq!(as_cpu(0, || rq(&h, 0x10038)), 0b01);
assert_eq!(as_cpu(1, || rq(&h, 0x10038)), 0b10);
}
#[test]
fn a_disable_bit_holds_its_cpu_and_clearing_it_lets_go() {
let TwoCpus { h, words, slots } = &two_cpu_heart();
let park = crate::cpu::smp::HOST_PARK_BIT;
wq(&h, 0, 1 << 61);
assert_ne!(words[1].load(Ordering::SeqCst) & park, 0);
assert_eq!(words[0].load(Ordering::SeqCst) & park, 0);
assert_eq!(slots[1].holds(), HOLD_HEART);
wq(&h, 0, 0);
assert_eq!(words[1].load(Ordering::SeqCst) & park, 0);
}
#[test]