Repository navigation
Expand file tree
/
Copy pathmachine.rs
More file actions
3388 lines (3124 loc) · 160 KB
/
Copy pathmachine.rs
File metadata and controls
3388 lines (3124 loc) · 160 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
use std::sync::Arc;
use parking_lot::Mutex;
use std::sync::atomic::AtomicU64;
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::sync::mpsc;
use std::thread;
use crate::config::{GraphicsBoard, MachineConfig, MachineProfile, NetworkConfig, ScsiDeviceConfig};
use crate::machine_state::GuestState;
use crate::traits::{BusDevice, Device, Resettable, Saveable, MachineEvent, MachineFatal};
use crate::locks::LockMonitor;
use crate::dev::eeprom_93c56::Eeprom93c56;
use crate::physical::Physical;
use crate::ip22_bus::{Ip22Bus, Ip22Devices};
// Helper for passing *mut Physical into a Send+Sync closure (MEMCFG callback).
// Safety: Physical is Send+Sync, and the Arc keeps it alive for the callback's lifetime.
use crate::physical::RamBank;
use crate::dev::prom::Prom;
use crate::dev::mc::MemoryController;
/// The processors an Indy or `indigo2_ip22` shipped with, the default first.
/// The R10000 Indigo2 is the IP28 board.
pub const CPUS: &[&Part] = &[&parts::R4400_150, &parts::R5000_180_EARLY];
/// The IP28's.
pub const IP28_CPUS: &[&Part] = &[&parts::R10000_195_EARLY];
use crate::cpu::mips_tlb::MipsTlb;
use crate::cpu::mips_exec::{MipsExecutor, MipsCpu, MipsCpuConfig, MipsCpuDebugAdapter};
use crate::gdb_stub::CpuDebug;
use crate::cpu::parts::{self, Part};
use crate::cpu::mips_cache_v2::MipsCache;
use crate::dev::hpc3::Hpc3;
use crate::dev::ioc::{Ioc, GioSlot, GIO_SLOT_MAP, profile_idx};
use crate::monitor::Monitor;
use crate::dev::ng1::rex3::Rex3;
use crate::snapshot::{Snapshot, Manifest, SCHEMA_VERSION, ChunksManifest, DiskRef, Gr2Chunk, MgrasChunk, enabled_features};
use crate::chunk_store::{ChunkStore, get_chunks_as_words, put_words_as_chunks};
use crate::hptimer::TimerManager;
use crate::workstation::{MachineRef, MachineSlot, SystemController, Workstation};
/// The profile of the machine this process is running, set by
/// [`crate::workstation::build`] so [`emulator_name`] can pick a model word
/// that matches it. Stored as the `MachineProfile` discriminant; `u8::MAX`
/// means no machine has been built yet.
static EMULATOR_PROFILE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
/// Record the profile of the machine being built (see [`emulator_name`]).
pub fn set_emulator_profile(profile: MachineProfile) {
EMULATOR_PROFILE.store(profile as u8, std::sync::atomic::Ordering::Relaxed);
}
fn emulator_profile() -> Option<MachineProfile> {
let raw = EMULATOR_PROFILE.load(std::sync::atomic::Ordering::Relaxed);
MachineProfile::EVERY.into_iter().find(|p| *p as u8 == raw)
}
/// The words an `I` in the expansion may stand for, per machine. Each list
/// names the machine as the user configured it, so the title never calls an
/// Indigo2 an Indy or an O2 anything but IP32. Without a profile only the
/// model-neutral words remain.
fn emulator_name_thirds(profile: Option<MachineProfile>) -> &'static [&'static str] {
match profile {
Some(MachineProfile::IndyIp24) => &["IRIX", "Iris", "IPsomething", "Indy", "IP24"],
Some(MachineProfile::Indigo2Ip22) => &["IRIX", "Iris", "IPsomething", "Indigo2", "IP22"],
Some(MachineProfile::Indigo2Ip28) => &["IRIX", "Iris", "IPsomething", "Indigo2", "IP28"],
Some(MachineProfile::O2Ip32) => &["IRIX", "Iris", "IPsomething", "IP32"],
Some(MachineProfile::OctaneIp30) => &["IRIX", "Iris", "IPsomething", "IP30"],
Some(MachineProfile::Origin200Ip29) => &["IRIX", "Iris", "IPsomething", "IP29"],
Some(MachineProfile::Origin2000Ip27 | MachineProfile::Onyx2Ip27) => &["IRIX", "Iris", "IPsomething", "IP27"],
Some(MachineProfile::FuelIp34) => &["IRIX", "Iris", "IPsomething", "IP34"],
Some(MachineProfile::TezroIp53) => &["IRIX", "Iris", "IP53"],
Some(MachineProfile::Origin3200Ip35 | MachineProfile::Onyx3000Ip35) => &["IRIX", "Iris", "IPsomething", "IP35"],
None => &["IRIX", "Iris", "IPsomething"],
}
}
/// The emulator's name for banners and window titles. Three runs in four it
/// is the canonical one; otherwise an expansion of IRIS rolled once per
/// process, whose third word is chosen to match the machine profile that
/// `set_emulator_profile` recorded (so a GUI that starts a different machine
/// later gets the same roll with the right model word).
pub fn emulator_name() -> String {
/// `None` for the canonical name, else the roll (first, third, fourth).
static ROLL: std::sync::OnceLock<Option<(usize, u64, usize)>> = std::sync::OnceLock::new();
const FIRSTS: [&str; 9] = ["Irresponsible", "Incredible", "Insufferable", "Infuriating", "Inaccurate", "Incomplete", "Interactive", "Indomitable", "Irresistible"];
const FOURTHS: [&str; 4] = ["Simulator", "System", "Substitute", "Sandbox"];
let roll = ROLL.get_or_init(|| {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64;
if now % 4 != 0 {
return None;
}
Some((((now / 4) % FIRSTS.len() as u64) as usize, now / 64, ((now / 256) % FOURTHS.len() as u64) as usize))
});
match *roll {
None => "Irresponsible Rust IRIX Simulator".to_string(),
Some((first, third_roll, fourth)) => {
let thirds = emulator_name_thirds(emulator_profile());
let third = thirds[(third_roll % thirds.len() as u64) as usize];
format!("{} Rust {} {}", FIRSTS[first], third, FOURTHS[fourth])
}
}
}
pub struct Machine {
cpu: Arc<dyn crate::cpu::mips_exec::CpuDevice>,
/// Where this machine has memory.
memory: Arc<crate::memory_map::MemoryMap>,
/// The physical bus and the Indy's or Indigo2's devices on it.
board: Arc<Ip22Bus>,
mc: MemoryController,
hpc3: Hpc3,
monitor: Arc<Monitor>,
/// TCP port the monitor serves on 127.0.0.1 (`cfg.monitor_port`).
monitor_port: u16,
/// Sender for async machine events (HardReset, PowerOff) from devices.
pub event_tx: mpsc::SyncSender<MachineEvent>,
event_rx: Option<mpsc::Receiver<MachineEvent>>,
/// Reliable, unbounded terminal-device-fault path.
fatal_rx: Option<mpsc::Receiver<MachineFatal>>,
/// First terminal device failure. A failed machine cannot restart.
fatal_fault: Option<MachineFatal>,
timer_manager: Arc<TimerManager>,
/// When `cfg.ci` is set, the channel-A backend is replaced by this
/// in-process one so the CI control socket can drive the console.
ci_serial: Option<Arc<crate::dev::serial_host::CiSerialBackend>>,
/// The shared `--serial-log` sink, kept so `stop` can flush a final
/// partial line (wall-timestamp mode holds one until its newline).
serial_log: Option<Arc<crate::dev::serial_log::SerialLog>>,
/// Most recent snapshot restored via `ci_restore`. `rollback` reuses this
/// name as the fallback path if the in-memory checkpoint is absent.
last_restore: Option<String>,
/// In-memory copy of the just-loaded state, taken at the end of every
/// successful `ci_restore`. Lets `ci_rollback` skip disk IO and TOML
/// re-parsing — paste back the cached `toml::Value`s and `memcpy` the
/// bank/framebuffer buffers. Cleared on any explicit `load_snapshot`
/// outside the CI path.
last_restore_checkpoint: Option<RollbackCheckpoint>,
/// Path of the configured scratch SCSI volume, if any. The CI socket reads
/// and writes this file directly (with the machine briefly stopped) to
/// inject/exfiltrate files without going through the network. None when no
/// SCSI device has `scratch = true` set in the config.
scratch_path: Option<std::path::PathBuf>,
/// Disk provenance captured at construction (configured path + host file
/// size per SCSI id). Written into snapshot manifests and validated on
/// restore so captured state never lands on a different base disk.
disks: Vec<DiskRef>,
/// Configured nvram file path, recorded in snapshot manifests.
nvram_path: String,
/// Host-forced Newport resolution from `[graphics] resolution` at construction.
display_resolution: crate::dev::ng1::vc2_timings::NewportResolution,
/// Whether Newport is active (not headless and Newport is selected).
newport_active: bool,
/// Indigo2 IP22 fullhouse layout (`!guinness`).
fullhouse: bool,
/// Pointer slot shared by every holder of a raw `*mut Machine` — the
/// monitor's `SystemController`, the `machine-events` thread and the CI
/// server. Created on first use by `machine_slot` and nulled in `Drop`, so
/// a handle that outlives this Machine sees "machine is not running"
/// instead of freed memory.
controller_slot: Option<MachineSlot>,
controller_registered: bool,
/// Where the machine is in its start/stop lifecycle. Never `Running`:
/// `status` derives that from the CPU's own running flag, so an
/// execution-control command cannot leave it stale. See
/// [`crate::machine_state`].
lifecycle: GuestState,
}
#[cfg(feature = "wgpu")]
type ResidentCheckpoint = (toml::Value, (Vec<u32>, Vec<u32>));
type MgrasCheckpoint = (String, Vec<(String, Vec<u32>)>);
type Gr2Checkpoint = crate::dev::gr2::Gr2SnapshotParts;
/// In-memory snapshot of the just-restored guest state. Populated at the end
/// of `ci_restore`; consumed by `ci_rollback`. Trades ~270 MB of RSS for
/// disk-IO-free rollback.
struct RollbackCheckpoint {
/// Snapshot directory (saves/<name>/) — re-used by rollback to reflink
/// the COW overlays back into place.
overlay_dir: std::path::PathBuf,
/// Per-SCSI-id dirty sector lists from cow.toml at the time of restore.
overlay_sets: Vec<(usize, Vec<u64>)>,
/// Same, for the second (fullhouse) SCSI controller — kept in a
/// separate list/subdirectory (see `capture_rollback_checkpoint`) since
/// controller 0 and controller 1 can each have a device at the same id.
overlay_sets1: Vec<(usize, Vec<u64>)>,
/// Native-endian RAM bank words. `bank_words[i].len() ==
/// banks[i].size_bytes / 4` for present banks; populated for all four.
bank_words: [Vec<u32>; 4],
/// Framebuffer contents (RGB, aux). `None` when running headless.
framebuffers: Option<(Vec<u32>, Vec<u32>)>,
#[cfg(feature = "wgpu")]
resident_head1_framebuffers: Option<(Vec<u32>, Vec<u32>)>,
/// Parsed device save_state TOMLs. Holding `toml::Value` directly skips
/// the ~80 ms cpu.toml string-parse cost on every rollback.
cpu: toml::Value,
mc: toml::Value,
ioc: toml::Value,
scc: toml::Value,
pit: toml::Value,
ps2: toml::Value,
rtc: toml::Value,
eeprom: toml::Value,
scsi: toml::Value,
/// Second SCSI controller's state — fullhouse only. `None` on guinness.
scsi1: Option<toml::Value>,
seeq: toml::Value,
hpc3: toml::Value,
rex3: Option<toml::Value>,
rex3_head1: Option<toml::Value>,
mgras: Option<MgrasCheckpoint>,
gr2: Option<Gr2Checkpoint>,
}
/// Parse a `cow.toml`/`cow1.toml`-shaped table (`{"scsi<id>": [dirty
/// sectors...]}`) into `(id, dirty_sectors)` pairs. Shared by rollback
/// capture and snapshot load so the two paths can't drift.
/// Inverse of `parse_cow_table`: build a `{"scsi<id>": [dirty sectors...]}`
/// table from `export_overlays`'s output.
pub(crate) fn build_cow_table(overlays: Vec<(usize, Vec<u64>)>) -> toml::Value {
let mut tbl = toml::map::Map::new();
for (id, dirty) in overlays {
let arr: Vec<toml::Value> = dirty.into_iter().map(|v| toml::Value::Integer(v as i64)).collect();
tbl.insert(format!("scsi{}", id), toml::Value::Array(arr));
}
toml::Value::Table(tbl)
}
pub(crate) fn parse_cow_table(cow_toml: &toml::Value) -> Vec<(usize, Vec<u64>)> {
let mut sets = Vec::new();
if let Some(tbl) = cow_toml.as_table() {
for (k, v) in tbl {
let Some(id_str) = k.strip_prefix("scsi") else { continue };
let Ok(id) = id_str.parse::<usize>() else { continue };
let Some(arr) = v.as_array() else { continue };
let dirty: Vec<u64> = arr.iter()
.filter_map(|x| x.as_integer().map(|i| i as u64))
.collect();
sets.push((id, dirty));
}
}
sets
}
/// Full-machine in-memory checkpoint captured from *live* running state
/// (unlike `RollbackCheckpoint`, which is specifically "the state right
/// after the most recent `ci_restore` from a named snapshot on disk" and
/// re-reads that snapshot's `cow.toml` to reflink SCSI overlays back into
/// place on rollback). Used by the interactive monitor's `j2 trace <n>` /
/// `j2 replay` (`SystemController::execute_command`) to get a real,
/// byte-exact rewind point — including device state, not just CPU
/// registers — for comparing an interpreter-only reference run against a
/// real-JIT-dispatch run of the same instruction window.
///
/// Deliberately does **not** capture SCSI controller or COW-overlay dirty-
/// sector state — there is no "just loaded from snapshot X" name to
/// reference here (this captures live, mid-session state, not a disk
/// snapshot restore), and building a live-capture equivalent of
/// `RollbackCheckpoint`'s overlay handling is real, correctness-sensitive
/// work (get it wrong and it's disk corruption, not just a debugging
/// inconvenience) that early-boot PROM debugging — the actual motivating
/// use case — doesn't need at all (PROM hasn't touched SCSI yet). Restoring
/// a `LiveCheckpoint` taken after the guest has performed real disk I/O
/// will silently leave SCSI/disk state at whatever it drifted to during the
/// replayed window, not rewound — safe for CPU/JIT correctness comparisons
/// (nothing here reads disk contents), unsafe to treat as a general
/// save-state substitute once boot reaches real disk access.
pub(crate) struct LiveCheckpoint {
bank_words: [Vec<u32>; 4],
framebuffers: Option<(Vec<u32>, Vec<u32>)>,
#[cfg(feature = "wgpu")]
resident_head1_framebuffers: Option<(Vec<u32>, Vec<u32>)>,
cpu: toml::Value,
mc: toml::Value,
ioc: toml::Value,
scc: toml::Value,
pit: toml::Value,
ps2: toml::Value,
rtc: toml::Value,
eeprom: toml::Value,
seeq: toml::Value,
hpc3: toml::Value,
rex3: Option<toml::Value>,
rex3_head1: Option<toml::Value>,
mgras: Option<MgrasCheckpoint>,
gr2: Option<Gr2Checkpoint>,
}
/// The test device, the ultra64 dev board and the second Newport head all
/// decode GIO expansion slot 0, so the test device cannot share a machine
/// with either. Panics rather than exiting: `Machine::new`
/// already panics on bad input, and a host that embeds IRIS catches that
/// (`iris-gui`'s worker wraps construction in `catch_unwind`) — killing the
/// application over a configuration mistake is not a choice a library gets to
/// make for its caller.
fn check_testdev_slot_free(ultra64_present: bool, head1_present: bool) {
if ultra64_present {
panic!("--test-device and the ultra64 dev board both claim GIO slot 0");
}
if head1_present {
panic!("--test-device and the second graphics head (graphics.heads = 2) both claim GIO slot 0");
}
}
/// A virtio device's GIO slot must not be one another device decodes: the
/// Ultra64 board, `--test-device` and the second Newport head take slot 0. Panics for the same reason `check_testdev_slot_free` does.
fn check_virtio_slot_free(section: &str, slot: crate::dev::ioc::GioSlot, ultra64: bool, testdev: bool, head1: bool) {
use crate::dev::ioc::GioSlot;
match slot {
GioSlot::Exp0 if ultra64 || testdev || head1 => {
panic!("[{section}] slot = \"exp0\" is taken by the ultra64 board, --test-device or the second graphics head; use \"exp1\"")
}
_ => {}
}
}
/// One Newport head's monitor commands under numbered names: `rex1`,
/// `vc21`, `xmap1`, `cmap1`, `bt4451`, `dcb1`, `disp1` for the second head.
/// Both boards name their commands alike and the monitor gives a name to the
/// first device that has it, so the plain names reach the first head; it has
/// the `0` names as well.
struct HeadCommands { rex: Arc<Rex3>, head: u8 }
impl HeadCommands {
/// `rex1` on head 1 is the board's `rex`.
fn plain<'a>(&self, cmd: &'a str) -> Option<&'a str> {
let digit = (b'0' + self.head) as char;
cmd.strip_suffix(digit)
}
}
impl Device for HeadCommands {
fn step(&self, _cycles: u64) {}
fn stop(&self) {}
fn start(&self) {}
fn is_running(&self) -> bool { self.rex.is_running() }
fn get_clock(&self) -> u64 { 0 }
fn register_commands(&self) -> Vec<(String, String)> {
self.rex.register_commands().into_iter()
.map(|(c, _)| (format!("{c}{}", self.head), format!("`{c}` on Newport head {}", self.head)))
.collect()
}
fn execute_command(&self, cmd: &str, args: &[&str], writer: Box<dyn std::io::Write + Send>) -> Result<(), String> {
let plain = self.plain(cmd).ok_or("Command not found")?;
self.rex.execute_command(plain, args, writer)
}
}
impl Machine {
/// Build the Indy or Indigo2 `cfg` describes. Panics if its PROM cannot
/// be loaded; [`try_new`](Self::try_new) returns the error instead.
pub fn new(cfg: MachineConfig) -> Self {
Self::register_host_services();
Self::new_with_testdev(cfg, None)
}
/// `new`, but construction errors are returned to the caller instead of panicking.
pub fn try_new(cfg: MachineConfig) -> Result<Self, String> {
Self::register_host_services();
Self::try_new_with_testdev(cfg, None)
}
fn register_host_services() {
// Host calls (iris-hostcall): the self-test service is always there
// when the feature is built in, so a guest can prove the trap works.
#[cfg(feature = "hostcall")]
iris_hostcall::register(iris_hostcall::SELFTEST, Box::new(iris_hostcall::SelfTest));
#[cfg(feature = "hostgl")]
iris_hostgl::register();
}
/// `new`, with the bare-metal test device supplied by the caller rather
/// than built from `cfg.test_device_dump`. Passing one enables it — the
/// device *is* the request, so `cfg.test_device` need not also be set.
///
/// Exists for hosts that link IRIS as a library and need the guest's
/// console and exit code delivered in-process instead of to stdout and
/// `process::exit` (`crate::bench_runner`, `TestDevice::new_embedded`).
pub fn new_with_testdev(
cfg: MachineConfig,
testdev_override: Option<Arc<crate::dev::testdev::TestDevice>>,
) -> Self {
Self::try_new_with_testdev(cfg, testdev_override)
.unwrap_or_else(|error| panic!("machine construction failed: {error}"))
}
/// [`new_with_testdev`](Self::new_with_testdev), returning construction errors.
pub fn try_new_with_testdev(
cfg: MachineConfig,
testdev_override: Option<Arc<crate::dev::testdev::TestDevice>>,
) -> Result<Self, String> {
let prom = Prom::for_profile(cfg.machine.profile, &cfg.prom)?;
Self::try_with_prom(cfg, testdev_override, prom)
}
fn try_with_prom(
mut cfg: MachineConfig,
testdev_override: Option<Arc<crate::dev::testdev::TestDevice>>,
prom: Prom,
) -> Result<Self, String> {
cfg.validate_newport_raster_gate()?;
// The rig takes any part: `MachineConfig::cpu_part` looks at this.
cfg.test_device |= testdev_override.is_some();
// Capture config flags that are needed after the local `cfg` binding
// is shadowed later in this function.
let ci_enabled = cfg.ci;
let perf = cfg.perf.clone();
#[cfg(feature = "jitv2")]
let (jitv2_threads, jitv2_threads_reason) = cfg.jitv2_pool_size();
#[cfg(feature = "jitv2")]
let jitv2_compile = cfg.jitv2.compile;
let display_resolution = cfg.graphics.resolution;
let newport_active = !cfg.headless && cfg.graphics_board() == GraphicsBoard::Newport;
let monitor_port = cfg.monitor_port.unwrap_or(crate::monitor::DEFAULT_PORT);
let cfg_cpu_model = cfg.cpu_part().expect("validate() accepted the cpu");
let guinness = cfg.machine.profile.guinness();
// 0. EEPROMs. Real IP22 hardware has two distinct 93-series serial
// EEPROM chips, not one shared part: a CPU-daughtercard chip wired to
// the MC (REG_EEROM @ 0x1fa00030 — CPU boot config, incl. CACHSZ_REG),
// and a motherboard chip wired to HPC3 (MISC_EEPROM_DATA @
// 0x1fbb0008 — NVRAM/env vars/MAC, see Eeprom93c56::backdoor_set_mac).
let eeprom_mc = Arc::new(Mutex::new(Eeprom93c56::new()));
let eeprom_hpc3 = Arc::new(Mutex::new(Eeprom93c56::with_path(crate::devlog::LogModule::Nveeprom, cfg.nveeprom.clone())));
// CACHSZ_REG (word 0x11): secondary cache size in 4KB pages. The PROM reads
// it when Config.SC reports no probed L2, which is exactly the case for a
// model that has no secondary cache. The EEPROM powers up erased (0xFFFF),
// so such a model MUST write 0 here — otherwise the PROM believes in a
// 256 MB L2 and IRIX spends the boot flushing a cache that does not exist.
// Keyed on the configured CPU, not on a cargo feature: the model is a
// runtime choice, so a feature gate here silently stopped firing.
let model_has_l2 = cfg_cpu_model.l2_kb > 0;
if !model_has_l2 {
eeprom_mc.lock().set_cachsz(0);
}
// 1. Create all devices first
// Memory Controller
let mc_banks: [u32; 4] = cfg.banks[..4].try_into().expect("the MC has four banks");
let mc = MemoryController::new_for_profile(
eeprom_mc.clone(), guinness, mc_banks, cfg.machine.profile.ip28());
// IP28: IRIX takes the CPU speed from the PROM's `cpufreq` (194, i.e.
// a 195 MHz R10000) instead of measuring it, and times with it: UST
// assumes Count at half that, and the RPSS cycle counter the MC clock
// at the CPU clock (Config.EC is 0, a 1:1 system-clock ratio) over the
// divider it programs. The generic 33 MHz Count and 50 MHz MC made
// UST run at a third of real time (Quake in slow motion) and the
// cycle counter at a quarter.
let count_hz = cfg.clock.count_hz(cfg_cpu_model);
if cfg.machine.profile.ip28() {
// The R10000's Count ticks at half the pipeline clock.
mc.set_clock_hz(2 * count_hz);
}
// RAM banks sized per config. addr_mask is initialized to mem_size-1;
// remap_banks() updates it via set_addr_mask() when MEMCFG0/1 are written during POST.
let banks = [
RamBank::new(cfg.banks[0].max(1) as usize),
RamBank::new(cfg.banks[1].max(1) as usize),
RamBank::new(cfg.banks[2].max(1) as usize),
RamBank::new(cfg.banks[3].max(1) as usize),
];
// PROM (1MB at 0x1FC00000), loaded by the caller.
let prom_port = prom.get_port();
// Shared atomics — created first so all devices and the display thread use the same Arc.
// (CPU cycle counter is no longer among these: it lives inline on
// MipsCore.hot.cycles now, wired into devices via set_cpu_cycles
// after the executor/CPU exist — see Hot::cycles's doc comment.)
let heartbeat = Arc::new(AtomicU64::new(0)); // activity bits: see crate::status::hb
let fasttick_count = Arc::new(AtomicU64::new(0)); // CP0 Compare match counter
// What every graphics board's status bar reads; the CPU feeds its
// fetch counters and the cycle counter is wired in below.
let status = crate::status::MachineStatus::new(heartbeat.clone(), fasttick_count.clone());
let [decoded_count, l1i_hit_count, l1i_fetch_count, uncached_fetch_count] = status.fetch_counters();
let (fatal_tx, fatal_rx) = mpsc::channel::<MachineFatal>();
// HPC3 (512KB at 0x1FB80000). The SCC's channels start wired to
// nothing; each gets its host end below.
#[cfg(feature = "ci_clock")]
let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::counting()));
#[cfg(not(feature = "ci_clock"))]
let timer_manager = Arc::new(TimerManager::new());
let ioc = Ioc::new_for_profile(&timer_manager, guinness, cfg.machine.profile.ip28());
ioc.ps2().set_layout(cfg.keyboard);
// One sink for both serial paths, so the CI and TCP logs are the same
// bytes (timestamps included). Opened once, before any peripheral
// `start()` clones the current backend Arc into the RX/TX threads.
let tag = if guinness { "Indy" } else { "Indigo2" };
let serial_log = crate::dev::serial_host::open_log(&cfg, tag);
// Channel B (tty1) is the SGI serial console: in CI mode the
// in-process backend the control socket drives directly, otherwise
// TCP on `serial_port_b`, either teed to `serial_log`. Channel A
// (tty2) serves TCP on `serial_port_a` outside CI mode, so several
// `--ci` instances can run side by side.
let [port_a, port_b] = cfg.serial_ports();
let ci_serial = ci_enabled.then(|| Arc::new(crate::dev::serial_host::CiSerialBackend::new()));
let label = format!("{tag} serial channel B");
let (console, _) = crate::dev::serial_host::serial_line(
&crate::dev::serial_host::SerialLine {
label: &label,
tcp_port: Some(port_b),
tcp_setting: "serial_port_b",
socket: cfg.serial_socket_b.as_deref(),
socket_setting: "serial_socket_b",
},
serial_log.clone(),
ci_serial.as_ref(),
);
ioc.scc().set_backend_b(console);
let label = format!("{tag} serial channel A");
let log_a = crate::dev::serial_host::open_log_at(&cfg, cfg.serial_log_a.as_deref(), &label);
let (channel_a, _) = crate::dev::serial_host::serial_line(
&crate::dev::serial_host::SerialLine {
label: &label,
tcp_port: (!ci_enabled).then_some(port_a),
tcp_setting: "serial_port_a",
socket: cfg.serial_socket_a.as_deref(),
socket_setting: "serial_socket_a",
},
log_a,
None,
);
ioc.scc().set_backend_a(channel_a);
ioc.set_heartbeat(heartbeat.clone());
ioc.set_clock_ticks(fasttick_count.clone(), status.cpu(0).board_tick_rate());
// Attach SCSI devices from config: each `[scsi.KEY]` table puts a
// target on a controller (`ScsiDeviceConfig::placement`). The disks
// recorded here, and the scratch volume's path for the CI socket,
// come back with it. Disk provenance for snapshot manifests is
// captured while the MachineConfig `cfg` is still in scope (it is
// shadowed by the CPU config below): the slot (controller * 16 + id,
// see `config::scsi_slot`), the configured path and the host file
// size.
// The buses are filled before the controllers exist and handed to them.
let scsi_buses = Hpc3::new_scsi_buses(guinness);
let attached = match crate::scsi::attach_from_config(&cfg, None, &|c| Hpc3::route_scsi(&scsi_buses, c)) {
Ok(a) => a,
Err(e) => {
eprintln!("iris: fatal: {e}");
std::process::exit(1);
}
};
let hpc3 = Hpc3::with_net(eeprom_hpc3.clone(), ioc.clone(), guinness, heartbeat.clone(), cfg.network(), cfg.no_audio, cfg.audio.clone(), cfg.nvram.clone(), cfg.rtc_offset, cfg.scsi_deferred_int, scsi_buses, &timer_manager);
// Backdoor-inject the configured (or default) Ethernet station
// address before the CPU ever runs, since real hardware always has
// one burned in and there is no user-facing way to set one. Both
// NVRAM (Indy) and the motherboard EEPROM (Indigo2) are persisted to
// disk (see cfg.nvram / cfg.nveeprom), so both only patch while the
// `eaddr` slot is still blank — never clobbers a MAC the guest
// already `setenv`'d (Indy) or that a prior run already saved
// (Indigo2). A settings block that is still blank apart from that
// address then gets the PROM's own defaults (`sgi_nvram`): the PROM
// reads the volume for the boot tune before it repairs a bad block,
// so a blank one would make the first boot silent.
if guinness {
hpc3.rtc().backdoor_set_mac_if_blank(cfg.network().mac);
hpc3.rtc().initialize_nvram_if_erased(crate::dev::sgi_nvram::REV_IP22);
} else {
let mut eeprom = eeprom_hpc3.lock();
eeprom.backdoor_set_mac_if_blank(cfg.network().mac);
let rev = if cfg.machine.profile.ip28() { crate::dev::sgi_nvram::REV_IP28 } else { crate::dev::sgi_nvram::REV_IP22 };
eeprom.initialize_if_erased(rev);
}
// A DaynaPort is built where the gateway is, by Hpc3; a target that
// will not attach ends the run (see `attach_from_config`).
let daynaports = || -> Result<(), String> {
for d in &attached.daynaports {
let at = crate::config::scsi_label(d.controller, d.id);
match hpc3.add_scsi_daynaport(d.controller, d.id as usize, d.params) {
Ok(()) => println!(
"iris: DaynaPort SCSI/Link at {at} — MAC {}, gateway {} (guest {}/{})",
crate::net::mac_str(&d.params.mac),
d.params.subnet.gateway_ip, d.params.subnet.client_ip, d.params.subnet.netmask),
Err(e) => crate::scsi::attach_failed(format!("could not attach DaynaPort to {at}: {e}"), &at)?,
}
}
Ok(())
};
if let Err(e) = daynaports() {
eprintln!("iris: fatal: {e}");
std::process::exit(1);
}
let scratch_path = attached.scratch;
// The Indy and Indigo2 have always listed CD-ROMs beside the disks.
let disk_provenance: Vec<DiskRef> = attached.tables.iter()
.map(|t| DiskRef { id: t.slot, path: t.path.clone(), size_bytes: t.size_bytes })
.collect();
let nvram_provenance = cfg.nvram.clone();
#[cfg(feature = "wgpu")]
let resident_gpu = if newport_active
&& cfg.graphics.raster == crate::config::RasterUnit::Wgpu
{
if std::env::var_os("IRIS_REX3_GPU").is_some() {
return Err(
"IRIS_REX3_GPU and production Newport graphics.raster = \"wgpu\" are mutually exclusive"
.into(),
);
}
let options = crate::wgpu::GpuOptions {
backend: cfg.graphics.gpu_backend.clone(),
..Default::default()
};
let gpu = crate::wgpu::Gpu::new(&options)
.map_err(|error| format!("create Newport resident GPU: {error}"))?;
if !matches!(gpu.caps.backend, wgpu::Backend::Vulkan | wgpu::Backend::Dx12) {
return Err(format!(
"Newport resident GPU resolved graphics.gpu_backend = {:?} to unsupported {:?}; \
use Vulkan or D3D12",
cfg.graphics.gpu_backend, gpu.caps.backend
));
}
gpu.check().map_err(|error| format!("initialize Newport resident GPU: {error}"))?;
eprintln!("iris: Newport resident GPU enabled without CPU fallback: {}", gpu.caps);
Some(gpu)
} else {
None
};
#[cfg(feature = "wgpu")]
let resident_mode = match cfg.graphics.newport_wgpu_mode() {
crate::config::NewportWgpuMode::Direct =>
crate::dev::ng1::rex3::ResidentDisplayMode::DirectWgpu,
crate::config::NewportWgpuMode::Readback =>
crate::dev::ng1::rex3::ResidentDisplayMode::ReadbackCompatibility,
};
// REX3 Graphics — Newport only; skipped in headless mode or when non-Newport board selected.
let rex3: Option<Arc<Rex3>> = if cfg.headless || cfg.graphics_board() != crate::config::GraphicsBoard::Newport {
None
} else {
let r = Rex3::new(status.clone());
#[cfg(feature = "wgpu")]
let r = {
let mut r = r;
if let Some(gpu) = &resident_gpu {
r.activate_resident_gpu_for_runtime(Arc::clone(gpu), resident_mode)
.map_err(|error| format!("activate primary Newport resident GPU: {error}"))?;
}
r
};
let r = Arc::new(r);
r.set_fatal_sender(fatal_tx.clone());
let wiring = GIO_SLOT_MAP[profile_idx(guinness)][GioSlot::Gfx as usize];
r.set_vblank_irq(ioc.irq_line(wiring.retrace));
r.set_fifo_full_irq(ioc.irq_line(wiring.fifo_full));
Some(r)
};
let rex3_head1: Option<Arc<Rex3>> = if cfg.headless || cfg.graphics.heads < 2 {
None
} else {
let r = Rex3::new(status.clone());
#[cfg(feature = "wgpu")]
let r = {
let mut r = r;
if let Some(gpu) = &resident_gpu {
r.activate_resident_gpu_for_runtime(Arc::clone(gpu), resident_mode)
.map_err(|error| format!("activate secondary Newport resident GPU: {error}"))?;
}
r
};
let r = Arc::new(r);
r.set_fatal_sender(fatal_tx.clone());
r.set_head_index(1);
// An Indy baseboard older than revision 4 does not take a second
// board: the PROM and IRIX both skip the probe below it.
if guinness { ioc.set_board_rev(4); }
// Expansion slot 0, the one place IRIX looks for a second board.
// On an Indy the slot has one interrupt pin for both sources.
let wiring = GIO_SLOT_MAP[profile_idx(guinness)][GioSlot::Exp0 as usize];
if wiring.retrace == wiring.fifo_full {
let [retrace, fifo] = crate::irq::IrqLine::wired_or(ioc.irq_line(wiring.retrace));
r.set_vblank_irq(retrace);
r.set_fifo_full_irq(fifo);
} else {
r.set_vblank_irq(ioc.irq_line(wiring.retrace));
r.set_fifo_full_irq(ioc.irq_line(wiring.fifo_full));
}
Some(r)
};
// GR2 (XZ / Extreme) in the GIO gfx slot. Created even when headless:
// selecting the board is explicit, and the PROM needs it to probe.
let gr2: Option<Arc<crate::dev::gr2::Gr2>> = match cfg.graphics_board() {
crate::config::GraphicsBoard::Xz | crate::config::GraphicsBoard::Extreme => {
use crate::dev::gr2::{Gr2, Gr2Variant};
let variant = if cfg.graphics_board() == crate::config::GraphicsBoard::Extreme { Gr2Variant::Extreme } else { Gr2Variant::Xz };
let g = Gr2::new(variant, status.clone());
// GR2 retrace is GIO interrupt 2 (LIO_GIO_2): on Indigo2 through
// the EXTIO SG_RETRACE fan-out, on Indy the direct line. It is a
// latch the guest clears (see Ioc::write8/int2_write8), so only
// the rising edge is driven from here.
let line = if guinness { crate::dev::ioc::IocInterrupt::VerticalRetrace } else { crate::dev::ioc::IocInterrupt::GioSgRetrace };
if guinness { ioc.set_gen_cntl_retrace_ack(true); }
let ioc_r = ioc.clone();
// true = vertical blank starts, false = it ends. On Indigo2,
// EXTIO SG_STAT_0 is the board's vertical status level (low in
// blank); the PROM and the kernel retrace handler poll it.
g.set_retrace_callback(Arc::new(move |vblank| {
if vblank { crate::pf_instant!(crate::perfetto::events::GR2_VBLANK); }
if vblank { ioc_r.set_interrupt(line, true); }
if !guinness { ioc_r.set_ext_io_level(crate::dev::ioc::ext_io_regs::SG_STAT_0, !vblank); }
}));
Some(g)
}
_ => None,
};
// IMPACT graphics in the GIO graphics slot.
let mgras: Option<Arc<crate::dev::mgras::Mgras>> = match cfg.graphics_board() {
crate::config::GraphicsBoard::SolidImpact
| crate::config::GraphicsBoard::HighImpact
| crate::config::GraphicsBoard::MaxImpact => {
Some(crate::dev::mgras::Mgras::with_raster(cfg.graphics_board(), {
use crate::dev::ioc::IocInterrupt::{GioSgFifo, GioSgGraphics, GioSgRetrace};
[ioc.irq_line(GioSgFifo), ioc.irq_line(GioSgGraphics), ioc.irq_line(GioSgRetrace)]
}, status.clone(), cfg.graphics.raster, &cfg.graphics.gpu_backend).unwrap_or_else(|e| {
eprintln!("mgras: {e}");
std::process::exit(1)
}))
}
_ => None,
};
// N64 development board (Ultra64) — GIO slot 0 at 0x1F400000
let ultra64: Option<Arc<crate::dev::ultra64::Ultra64>> = if cfg.ultra64.enabled && rex3_head1.is_some() {
eprintln!("ultra64: disabled, the second graphics head is in its GIO slot (graphics.heads = 2)");
None
} else if cfg.ultra64.enabled {
match crate::dev::ultra64::Ultra64::new(ioc.irq_line(crate::dev::ioc::IocInterrupt::GioExp0)) {
Ok(dev) => Some(Arc::new(dev)),
Err(e) => {
eprintln!("ultra64: failed to initialize ({e}); running without N64 dev board");
None
}
}
} else {
None
};
// VINO (Video-In, No Out) — GIO64 at 0x1F080000
let vino = crate::dev::vino::Vino::new();
vino.set_irq(ioc.irq_line(crate::dev::ioc::IocInterrupt::VideoVsync));
// 2. Create Physical Bus with devices
// `cfg` is shadowed by MipsCpuConfig further down; grab this first.
let cheritest_hook = cfg.cheritest_dump_hook;
// Bare-metal test device (--test-device): default off, and refused
// alongside the ultra64 dev board, which claims the same GIO slot.
let testdev = if let Some(dev) = testdev_override {
check_testdev_slot_free(ultra64.is_some(), rex3_head1.is_some());
Some(dev)
} else if cfg.test_device {
check_testdev_slot_free(ultra64.is_some(), rex3_head1.is_some());
let path = cfg.test_device_dump.clone()
.unwrap_or_else(|| crate::dev::testdev::DEFAULT_DUMP_PATH.to_string());
eprintln!("iris: test device enabled at {:#010x}, dumps to {}",
crate::dev::testdev::TEST_DEV_BASE, path);
let run = cfg.test_device_run_config()
.expect("test_device_run_config: validate() should have caught this");
Some(Arc::new(crate::dev::testdev::TestDevice::with_run_config(path, run)))
} else {
None
};
let phys = Physical::new(banks.into());
// virtio devices: GIO expansion slot 0 or 1, on the line the IOC gives
// that slot (the Indy's two direct pins, or the Indigo2's EXT_IO
// fan-out). They master the bus through `phys`.
let virtio_mmio = |section: &str, name: &str, slot: crate::config::VirtioGioSlot, core| {
use crate::config::VirtioGioSlot;
use crate::dev::ioc::{GioSlot, IocInterrupt, GIO_SLOT_BASES, GIO_SLOT_MAP, profile_idx};
let slot = match slot {
VirtioGioSlot::Exp0 => GioSlot::Exp0,
VirtioGioSlot::Exp1 => GioSlot::Exp1,
};
check_virtio_slot_free(section, slot, ultra64.is_some(), testdev.is_some(), rex3_head1.is_some());
let source = match (guinness, slot) {
(true, GioSlot::Exp0) => IocInterrupt::GioExp0,
(true, _) => IocInterrupt::GioExp1,
(false, s) => GIO_SLOT_MAP[profile_idx(false)][s as usize].retrace,
};
let base = GIO_SLOT_BASES[slot as usize];
eprintln!("iris: {name} at {base:#010x}");
let dev = crate::dev::virtio::mmio::VirtioMmio::new(
core,
ioc.irq_line(source),
Arc::new(crate::dev::virtio::BusMemory(phys.clone())),
);
(Arc::new(dev), base)
};
let virtio = cfg.virtio_serial.enabled.then(|| {
virtio_mmio(
"virtio_serial",
"virtio-serial",
cfg.virtio_serial.slot,
crate::dev::virtio::console::from_config(&cfg.virtio_serial),
)
});
let virtio_9p = cfg.virtio_9p.enabled.then(|| {
virtio_mmio(
"virtio_9p",
"virtio-9p",
cfg.virtio_9p.slot,
crate::dev::virtio::p9::from_config(&cfg.virtio_9p),
)
});
let board = Arc::new(Ip22Bus::new(phys.clone(), Ip22Devices {
rex3: rex3.clone(),
rex3_head1: rex3_head1.clone(),
gr2: gr2.clone(),
mgras: mgras.clone(),
ultra64,
testdev,
virtio,
virtio_9p,
vino,
mc: mc.clone(),
hpc3: hpc3.clone(),
prom: prom_port,
}, cfg.machine.profile.ip28()));
// Connect Physical to MC (for VDMA)
mc.set_phys(phys.clone());
mc.set_dma_irq(ioc.irq_line(crate::dev::ioc::IocInterrupt::McDma));
// Wire MEMCFG callback: when MC writes MEMCFG0/1, remap the banks. Runs
// on the one CPU's thread, so there is no other to park.
let world = Arc::new(crate::cpu::smp::World::new());
{
let (board, world) = (Arc::downgrade(&board), world.clone());
mc.set_memcfg_callback(Box::new(move |addrs| {
if board.upgrade().is_some_and(|board| board.remap_banks(addrs)) {
world.layout_changed();
}
}));
}
// Fire initial remap using MC's boot-time MEMCFG values
{
let (memcfg0, memcfg1) = mc.get_memcfg();
let addrs = mc.parse_memcfg(memcfg0, memcfg1);
board.remap_banks(addrs);
}
// Connect HPC3 to System Memory (via Physical)
hpc3.set_phys(phys.clone());
// Connect VINO to System Memory, install a video source, start DMA.
// Source kind + broadcast standard come from `[vino]` in iris.toml.
board.vino.set_phys(phys.clone());
if let Some(mgras) = &board.mgras { mgras.set_phys(phys.clone()); }
// Host GL frames composite straight into the IMPACT framebuffer.
#[cfg(feature = "hostgl")]
if let Some(mgras) = &board.mgras {
iris_hostcall::set_display(Arc::new(crate::dev::mgras::ImpactScreen(mgras.clone())));
}
let standard = match cfg.vino.standard {
crate::config::VinoStandard::Ntsc => crate::video_source::VideoStandard::Ntsc,
crate::config::VinoStandard::Pal => crate::video_source::VideoStandard::Pal,
};
let source: Option<Arc<dyn crate::video_source::VideoSource>> = match cfg.vino.source {
crate::config::VinoSource::Camera => {
{
let idx = cfg.vino.camera_index;
match crate::dev::camera::CameraSource::new_with_index(standard, idx) {
Ok(c) => Some(Arc::new(c)),
Err(e) => {
eprintln!("VINO: camera {} unavailable ({}); using black source", idx, e);
Some(Arc::new(crate::video_source::BlackSource::new(standard)))
}
}
}
}
crate::config::VinoSource::TestPattern =>
Some(Arc::new(crate::video_source::TestPatternSource::new(standard))),
crate::config::VinoSource::Black =>
Some(Arc::new(crate::video_source::BlackSource::new(standard))),
// Video-In disabled: no source, no DMA thread. VINO stays mapped.
crate::config::VinoSource::Off => None,
};
if let Some(source) = source {
let adjusted: Arc<dyn crate::video_source::VideoSource> =
Arc::new(crate::video_source::CdmcAdjustedSource::new(source, board.vino.clone()));
board.vino.set_source(adjusted);
board.vino.start();
}
// 5. CPU config + TLB + Executor. The model is a runtime choice, but each
// family monomorphises its own CPU (`crate::cpu::build`) — no per-model branch on the hot path.
let sysad: Arc<dyn BusDevice> = phys.clone();
let memory = Arc::new(crate::ip22_bus::memory_map(cfg.machine.profile.ip28()));
macro_rules! build_cpu { ($cache:ty) => {{
let cfg = MipsCpuConfig::for_model::<$cache>(memory.clone()).with_prid(cfg_cpu_model.prid());
let tlb = MipsTlb::new(cfg.tlb_entries);
let mut executor: MipsExecutor<MipsTlb, $cache> = MipsExecutor::new(sysad.clone(), tlb, &cfg);
// The MC decodes 32 physical address bits; see `MipsExecutor::phys_mask`.
executor.phys_mask = u32::MAX as u64;
// Load default symbol maps if they exist
{
let mut symbols = executor.symbols.lock();
if let Ok(count) = symbols.load("prom.map") {
println!("Loaded {} symbols from prom.map", count);
}
if let Ok(count) = symbols.load("unix.map") {
println!("Loaded {} symbols from unix.map", count);
}
}
// CP0 Count runs at half the chip's clock unless the user overrode
// it via `[clock] fixed_mhz` or the CLI. Must happen
// before the core starts executing.
executor.core.set_count_hz(count_hz);
// Inject the shared fasttick_count Arc into the executor core before wrapping in MipsCpu.
// (cycles has no equivalent here — it's inline on MipsCore.hot now.)
executor.core.fasttick_count = fasttick_count;
executor.decoded_count = decoded_count;
executor.uncached_fetch_count = Arc::clone(&uncached_fetch_count);
executor.cache.set_l1i_counters(Arc::clone(&l1i_hit_count), Arc::clone(&l1i_fetch_count));
// Re-sync raw pointers after Arc injection (the Arcs above replaced the ones captured in new()).
executor.rebind_atomic_ptrs();
// Give the core the machine's hptimer manager: CP0 Compare writes
// arm a one-shot on it that raises IP7 from the timer thread. Safe
// to hand over before the move into MipsCpu below — nothing gets
// armed (no raw pointer captured) until the CPU actually executes a
// Compare write, by which time the core sits at its final address
// inside the executor's Arc<Mutex<..>>.
executor.core.set_timer_manager(timer_manager.clone());
Arc::new(MipsCpu::new(executor)) as Arc<dyn crate::cpu::mips_exec::CpuDevice>
}}}
let shadow = cfg.machine.cache.is_shadow(cfg_cpu_model);
let cpu: Arc<dyn crate::cpu::mips_exec::CpuDevice> =
crate::with_cpu!(cfg_cpu_model, shadow, false, C => build_cpu!(C));
// The developer status bar shows the CPU's Count rate.
status.set_count_hz(cpu.count_hz_atomic());
world.set_slots(vec![cpu.park_slot()]);
// The CPU's pool flushes through this world too: a CPU belongs to one.
#[cfg(feature = "jitv2")]
cpu.share_jitv2(cpu.jitv2(), world.clone(), 0, 0);
// Connect CPU to MC and IOC for signaling
let cpu_device: Arc<dyn Device> = cpu.clone().as_device();
mc.set_cpu(Arc::downgrade(&cpu_device));
ioc.set_interrupts(cpu.interrupts_ptr());
// ppmem: the CPU's cache and the JIT read RAM through a cached view of
// the window that is the CPU's own, so what the cache holds stays out
// of every other master's sight (`PpMemSpace::add_cached_view`). Its
// bitmap is published straight into the CPU's inline fields, the
// executor's and the cache's, which are at their final addresses by
// now; the only writer is this CPU thread's MEMCFG path. A cache with
// no bitmap field (the full cache without tcache) returns null, which
// the view skips. Physical's direct paths keep the shared window.
{
use crate::ppmem::MappedMemory;
if let Some(sp) = phys.ppmem_space() {
let v = sp
.add_cached_view(&[cpu.ppmem_bitmap_ptr(), cpu.tcache_bitmap_ptr()])
.expect("ppmem: the CPU's cached view");
unsafe { cpu.set_tcache_window(sp.view_base(v)) };
unsafe { cpu.set_cached_view(sp, v) };
// The decode cache keys its window pointers on the maps.
unsafe { sp.add_key_sink(v, cpu.tcache_key_ptr()) };
// Window writes bypass BusDevice, so the cache needs the gen
// window to bump page counters itself — otherwise jitv2 keeps
// running compiled code for pages the guest has modified.
#[cfg(feature = "jitv2")]
unsafe { cpu.set_tcache_gen_window(sp.gen_window_base()) };
}
}