Repository navigation
Expand file tree
/
Copy pathrad1.rs
More file actions
1682 lines (1574 loc) · 67.3 KB
/
Copy pathrad1.rs
File metadata and controls
1682 lines (1574 loc) · 67.3 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
//! SGI RAD1 audio (PCI 10a9:0005): the Octane's onboard part (revision
//! 0xc0) on Bridge slot 3, and the Onyx2 BaseIO-G's MediaIO daughtercard
//! (revision 0x70, [`RAD1_REVISION_MEDIAIO`]) at PCI device 7. The register
//! offsets and fixed words live in `regs.rs`.
//!
//! The model covers the register file the
//! driver's start-up programs, the free-running UST counter and its control
//! word, the DMA descriptor words, status-DMA control and the analog output
//! enable. Behaviour that no source establishes is kept as the model
//! has it, and flagged below.
//!
//! Approximations kept from the model:
//!
//! * BAR0 is 0x2000 bytes and BAR sizing is a model property, not a
//! measurement of a physical card.
//! * The PCI class is "not defined" (0) and the card raises no interrupt:
//! the interrupt pin is 0.
//! * The start-up words, the AES3 subcode window and the descriptor bank
//! store what was written and return it. No reset values or masks are
//! established beyond zero; the few writes the model refuses (see
//! `Inner::write`) are refused because no supported guest makes them.
//! * The analog input and output run at the rates their clock generators
//! (0 and 1) are programmed for; see `Rate`. Until a guest programs
//! one, its rate is 44.1 kHz: the power-on rate is unknown.
//! * The engines move frames at the sample rate. Frames are moved when
//! something looks (a position or status read, a status completion) and,
//! while the analog output runs with host audio enabled, by a 10 ms timer,
//! so the output reaches the host steadily. The timers are the machine's
//! `hptimer`, armed by `Device::start` and removed by `Device::stop`. An input ring is filled with
//! silence: host audio input is not connected.
//! * Output plays as the model's mixer does: each ring frame is two
//! little-endian words, left then right, each a 24-bit signed sample in
//! bits \[23:0\]; the host sample is bits \[23:8\]. The channel order and the
//! use of bits \[23:8\] are the model's inference, not confirmed.
//! * The AES3 subcode channel runs at 48000/192 Hz with empty records: no
//! capture times them, the rate is inferred from the record layout.
//! * UST ticks every 960 ns, a selected board policy; the physical rate is
//! unmeasured.
//! * The sample clock, UST and status schedule run on host wall time, less
//! the time the machine was stopped; they are not tied to the emulated
//! CPU's progress.
//! * Hold-up approximation, an emulator policy with no hardware
//! counterpart: while continuous status runs, a completion more than one
//! interval late means the host held up the timer thread that also
//! delivers the clock interrupt IRIX refills the ring from, so the card's
//! clock is set back to the completion's due time (see
//! [`CardClock::absorb_stall`]). Register accesses and the timer's
//! rescheduling are held back the same way. The clock, output rate and UST
//! fall behind wall time by the hold-ups; on-time completions win 1/32 of
//! an interval back each, and at most 200 ms is held back. Time the guest
//! has read is never taken back.
//! * The relay (0x88 = 2) and DAC (0x8c = 3) mute words silence the host
//! output while the transfer runs on. That they mute is inferred from
//! when the PROM, IRIX and Linux write them; the power-on state is
//! unknown and taken as not muted. The Onyx2's MediaIO card does not
//! take them as mutes: IRIX shifts serial words out through 0x8c and 0x88
//! there and rewrites 0x8c with 2 and 3 in turn about once a second.
//! * The counter at 0x30 starts on the control word at 0x40 on the Octane
//! card: the values the Octane driver writes are 0x0e then 0x0a to enable
//! and 0x02 to disable. Reading them as hold, run and stop, and taking run
//! only after hold, is the model's; no source gives the bits' meaning. The
//! MediaIO card's driver never writes the control word and needs the
//! counter to advance, so there it runs from reset and a card reset does
//! not stop it.
//! * Registers no source gives a meaning (see the `REG_UNSOURCED_*` names)
//! store what is written and read it back.
//! * A BAR0 access the model does not recognise is logged and reads zero.
//! The model fails the bus access instead, which the PCI bus layer here
//! cannot express.
//!
//! Ported from hw/audio/sgi-rad1-audio.c in jamesbraid/qemu-sgi-origami.
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock, Weak};
use parking_lot::Mutex;
use std::time::{Duration, Instant};
use crate::config::AudioConfig;
use crate::dev::audio_dump::AudioDump;
use crate::dev::host_pcm::{CardClock, Sink, PCM_CHANNELS};
use crate::devlog::LogModule;
use crate::host_audio::{Meter, Output, Skip};
use crate::hptimer::{Timer, TimerId, TimerManager, TimerReturn};
use crate::snapshot::{field, field_bool, field_u32, field_u32s, field_u64, field_u64_vec, field_u64s, field_u8, StateTable};
use crate::traits::{Device, Saveable};
use crate::pci::{Bar, PciConfig, PciFunction, PciFunctionState};
pub const PCI_VENDOR_SGI: u16 = 0x10a9;
pub const PCI_DEVICE_RAD1: u16 = 0x0005;
pub const RAD1_REVISION: u8 = 0xc0;
/// The revision byte of the RAD1 on the Onyx2's MediaIO daughtercard: IRIX
/// lists it as "RAD revision 7.0", the Octane's onboard part as 12.0.
pub const RAD1_REVISION_MEDIAIO: u8 = 0x70;
/// "Not defined" (base class 0), as the model has it.
const PCI_CLASS_NOT_DEFINED: u32 = 0;
pub const BAR0_SIZE: u32 = 0x2000;
mod regs;
use regs::*;
const POS_WORDS: usize = ((POS_LAST - POS_FIRST) / 4 + 1) as usize;
const DMA_BANK_WORDS: usize = ((DMA_BANK_LAST - DMA_BANK_FIRST) / 4 + 1) as usize;
const SUBCODE_WORDS: usize = ((SUBCODE_LAST - SUBCODE_FIRST) / 8 + 1) as usize;
/// The descriptor RAM: 16 entries of three words from 0x400, all stored. A
/// link to an entry still all zero is in no source and stops the output (see
/// [`State::descriptor_end`]).
const DESC_RAM_ENTRY_BYTES: u32 = 12;
const DESC_RAM_ENTRIES: u32 = 16;
const DESC_RAM_LAST: u32 = DMA_BANK_FIRST + DESC_RAM_ENTRIES * DESC_RAM_ENTRY_BYTES - 4;
/// Largest ring walked; only stops a garbage control word naming gigabytes.
const DMA_MAX_BYTES: u64 = 1 << 20;
const UST_NS_PER_TICK: i64 = 960;
const NS_PER_SEC: u64 = 1_000_000_000;
/// The rate of a clock generator no guest has programmed.
const FREQ_ANALOG: u64 = 44100;
const FREQ_AES_SUB: u64 = 48000 / 192;
/// Ring bytes moved per DMA access; a whole number of frames of any type.
const CHUNK_BYTES: u64 = 1024;
/// How often the pump moves output frames to the host.
const PUMP_MS: u64 = 10;
const POS_FIELD_MASK: u32 = 0x3fff;
const UST_LATCH_MASK: u32 = 0x3_ffff;
const STATUS_CLOCK_HZ: u64 = 33_000_000;
/// A 16-bit host sample sits in bits \[23:8\] of its 24-bit ring sample.
const SAMPLE_SHIFT: u32 = 8;
/// The analog rings' words per frame.
const ANALOG_WORDS: usize = 2;
/// One ring word's 24-bit sample as a 16-bit host sample, bits \[23:8\].
fn word_to_sample(word: u32) -> i16 {
(word >> SAMPLE_SHIFT) as i16
}
/// One 16-bit host sample as a ring word: bits \[23:8\], sign-extended
/// through \[31:24\], bits \[7:0\] zero.
fn sample_to_word(sample: i16) -> u32 {
(i32::from(sample) << SAMPLE_SHIFT) as u32
}
/// Output: `ring` holds whole frames of `words_per_frame` little-endian
/// words; `pcm` receives as many stereo host frames. The first word is left,
/// the second right; further words have no host channel and are dropped.
fn frames_to_pcm(ring: &[u8], pcm: &mut [i16], words_per_frame: usize) {
let frames = pcm.len() / PCM_CHANNELS;
for f in 0..frames {
for ch in 0..PCM_CHANNELS {
let at = (f * words_per_frame + ch) * 4;
let word = u32::from_le_bytes(ring[at..at + 4].try_into().unwrap());
pcm[f * PCM_CHANNELS + ch] = word_to_sample(word);
}
}
}
/// Input: stereo host frames to ring frames of `words_per_frame` words. Left
/// fills the first word and right the second; any further word is silence.
fn pcm_to_frames(pcm: &[i16], ring: &mut [u8], words_per_frame: usize) {
let frames = pcm.len() / PCM_CHANNELS;
for f in 0..frames {
for w in 0..words_per_frame {
let word = if w < PCM_CHANNELS { sample_to_word(pcm[f * PCM_CHANNELS + w]) } else { 0 };
let at = (f * words_per_frame + w) * 4;
ring[at..at + 4].copy_from_slice(&word.to_le_bytes());
}
}
}
/// Clock generators: 0 clocks the analog input, 1 the analog output, 2 the
/// AES3 output. Generator 3 is not modelled.
const NUM_CG: usize = 4;
/// The control word's generator selects, one bit each from bit 28.
const CG_SELECT_SHIFT: u32 = 28;
/// The control word's divisor less one; bits 9 and 10 above it are flags.
const CG_DIV_MASK: u32 = 0x1ff;
/// The two master clocks a generator divides, each four times its family's
/// base rate.
const MASTER_44K: u64 = 176_400;
const MASTER_48K: u64 = 192_000;
/// A sample rate, `num / den` frames per second.
///
/// A generator divides its master clock by `div + rem / den`. The decode is
/// the public Linux RAD1 driver's (Stanislaw Skowronek's `snd_rad1_set_cg`):
/// the control word at 0xa0 holds the generator select from bit 28 and
/// `div - 1` in its low bits, the word at 0xa4 holds `rem << 16 | (0x10000 -
/// den)`, and the generator's word in 0xa8..0xb4 picks the master: bit 0 set
/// for 192 kHz, clear for 176.4 kHz. IRIX 6.5.30 programs its rates from 8
/// to 48 kHz with words of the same form, all from the 192 kHz master (the
/// tests hold the words it writes). What the flag bits 9 and 10 and the
/// other select values do is unknown; they are ignored. The new rate takes
/// effect at the control word.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Rate {
num: u64,
den: u64,
}
impl Rate {
const fn hz(hz: u64) -> Self {
Self { num: hz, den: 1 }
}
fn from_clockgen(ctrl: u32, rem_word: u32, mux: u32) -> Self {
let master = if mux & 1 != 0 { MASTER_48K } else { MASTER_44K };
let div = u64::from(ctrl & CG_DIV_MASK) + 1;
let den = 0x1_0000 - u64::from(rem_word & 0xffff);
let rem = u64::from(rem_word >> 16);
Self { num: master * den, den: div * den + rem }
}
/// Whole frames the clock has produced in `ns`.
fn frames_in(self, ns: i64) -> u64 {
(ns as u128 * u128::from(self.num) / (u128::from(self.den) * u128::from(NS_PER_SEC))) as u64
}
/// When frame `frames` ends, in ns from the clock's start.
fn ns_for(self, frames: u64) -> i64 {
(u128::from(frames) * u128::from(self.den) * u128::from(NS_PER_SEC)).div_ceil(u128::from(self.num)) as i64
}
/// The nearest whole rate, for the host stream.
fn rounded_hz(self) -> u32 {
((self.num + self.den / 2) / self.den) as u32
}
}
/// Channel types, as indices into [`State::chan`]. Only the three the
/// Octane supports are modelled.
const CH_IN: usize = 0;
const CH_OUT: usize = 1;
const CH_AES_SUB: usize = 2;
const NUM_CH: usize = 3;
/// The generator the analog output uses until 0x58 names one.
const OUT_DEFAULT_CG: usize = 1;
struct ChanInfo {
name: &'static str,
ring: RingRegs,
/// The next-descriptor index IRIX writes for this channel type.
tag: u32,
/// Bytes in one frame of the ring.
frame_bytes: u64,
enable_bit: u32,
output: bool,
/// The clock generator setting the rate; with none, `freq` is the
/// fixed rate in Hz.
clockgen: Option<usize>,
freq: u64,
/// Position register A and the shift of its frame count.
pos_a: u32,
pos_a_shift: u32,
/// Position register B, its shift, and whether it is the parent
/// channel's (so this channel leaves it alone).
pos_b: u32,
pos_b_shift: u32,
pos_b_parent: bool,
/// Offset in a status slot of this channel's DMA pointer.
slot_ptr: u64,
}
const CHAN_INFO: [ChanInfo; NUM_CH] = [
ChanInfo {
name: "analog input", ring: RING_INPUT, tag: 0, frame_bytes: 8, enable_bit: ENABLE_BIT,
output: false, clockgen: Some(0), freq: 0, pos_a: REG_POS_ANALOG_IN_A, pos_a_shift: 18, pos_b: REG_POS_ANALOG_B,
pos_b_shift: 18, pos_b_parent: false, slot_ptr: SLOT_PTR_ANALOG_IN,
},
ChanInfo {
name: "analog output", ring: RING_OUTPUT, tag: 1, frame_bytes: 8, enable_bit: ENABLE_BIT,
output: true, clockgen: Some(1), freq: 0, pos_a: REG_POS_ANALOG_OUT_A, pos_a_shift: 18, pos_b: REG_POS_ANALOG_B,
pos_b_shift: 4, pos_b_parent: false, slot_ptr: SLOT_PTR_ANALOG_OUT,
},
ChanInfo {
name: "AES3-input subcode", ring: RING_AES_SUB, tag: 6, frame_bytes: 256,
enable_bit: SUBCODE_ENABLE_BIT, output: false, clockgen: None, freq: FREQ_AES_SUB, pos_a: REG_POS_AES_SUB,
pos_a_shift: 4, pos_b: REG_POS_AES_SUB, pos_b_shift: 18, pos_b_parent: true, slot_ptr: SLOT_PTR_AES_SUB,
},
];
#[derive(Default, Clone, Copy)]
struct Chan {
running: bool,
/// Ring latched from the working registers at the enable edge.
base: u64,
len: u64,
offset: u64,
start_ns: i64,
frames: u64,
/// End of descriptor: the transfer ends with this descriptor.
eod: bool,
/// The next-descriptor index, used when `eod` is clear.
next: u32,
/// The entry `next` names holds this very descriptor: loop on it.
looping: bool,
/// A link led to a never-programmed descriptor. What the chip does then
/// is in no source: the channel moves nothing more.
stalled: bool,
}
/// One decoded descriptor.
#[derive(Clone, Copy)]
struct Desc {
base: u64,
len: u64,
eod: bool,
next: u32,
looping: bool,
}
struct State {
startup: [u32; STARTUP_OFFSETS.len()],
subcode: [u64; SUBCODE_WORDS],
dma_bank: [u32; DMA_BANK_WORDS],
sample_pos: [u32; POS_WORDS],
analog_out_en: u32,
/// The clock generator the analog output runs from (0x58 selects it).
out_cg: usize,
/// Each generator's last control and remainder words; the master select
/// (0xa8..0xb4) can arrive after the load.
cg_loaded: [Option<(u32, u32)>; NUM_CG],
/// The relay (0x88) and DAC (0x8c) mutes once written. The power-on
/// state is unknown, so before that the output is not muted.
relay_muted: Option<bool>,
dac_muted: Option<bool>,
status_dma_ctrl: u32,
status_running: bool,
chan: [Chan; NUM_CH],
/// Each clock generator's rate.
clock: [Rate; NUM_CG],
ust_count: u32,
ust_phase: i64,
ust_enabled: bool,
ust_armed: bool,
ust_last_ns: i64,
/// Bumped whenever the status schedule is replaced, so a stale timer
/// callback notices and ends.
status_gen: u64,
status_interval: u32,
status_start_ns: i64,
status_done: u64,
status_cursor: u32,
status_slots: u32,
/// The recurring timer pumping the analog output while it runs with
/// host audio enabled.
audio_timer: Option<TimerId>,
/// When `Inner::status` is due, in machine nanoseconds.
status_due: Option<u64>,
}
impl State {
fn new(now: i64, ust_free_running: bool) -> Self {
Self {
startup: [0; STARTUP_OFFSETS.len()],
subcode: [0; SUBCODE_WORDS],
dma_bank: [0; DMA_BANK_WORDS],
sample_pos: [0; POS_WORDS],
analog_out_en: 0,
out_cg: OUT_DEFAULT_CG,
cg_loaded: [None; NUM_CG],
relay_muted: None,
dac_muted: None,
status_dma_ctrl: 0,
status_running: false,
chan: [Chan::default(); NUM_CH],
clock: [Rate::hz(FREQ_ANALOG); NUM_CG],
ust_count: 0,
ust_phase: 0,
ust_enabled: ust_free_running,
ust_armed: false,
ust_last_ns: now,
status_gen: 0,
status_interval: 0,
status_start_ns: 0,
status_done: 0,
status_cursor: 0,
status_slots: 0,
audio_timer: None,
status_due: None,
}
}
/// The UST counter as it will read at `ns`, for stamping a position.
fn ust_at(&self, ns: i64) -> u32 {
let mut ticks = self.ust_phase;
if self.ust_enabled {
ticks += ns - self.ust_last_ns;
}
self.ust_count.wrapping_add(ticks.div_euclid(UST_NS_PER_TICK) as u32)
}
/// A channel's sample rate.
fn rate(&self, idx: usize) -> Rate {
match self.cg_of(idx) {
Some(cg) => self.clock[cg],
None => Rate::hz(CHAN_INFO[idx].freq),
}
}
/// The clock generator pacing a channel; 0x58 chooses the output's.
fn cg_of(&self, idx: usize) -> Option<usize> {
if idx == CH_OUT { Some(self.out_cg) } else { CHAN_INFO[idx].clockgen }
}
/// Whether the guest has muted the analog output's relay or DAC.
fn muted(&self) -> bool {
self.relay_muted == Some(true) || self.dac_muted == Some(true)
}
fn pos(&mut self, reg: u32) -> &mut u32 {
&mut self.sample_pos[((reg - POS_FIRST) / 4) as usize]
}
fn add_field(reg: &mut u32, shift: u32, frames: u32) {
let mask = POS_FIELD_MASK << shift;
let field = ((*reg >> shift).wrapping_add(frames)) & POS_FIELD_MASK;
*reg = (*reg & !mask) | (field << shift);
}
/// Credit frames to a channel's position registers. Both count frames.
/// A holds the count at its shift and, at shift 18, the low 18 bits of
/// the UST at the frame boundary; B is a 14-bit count the driver's start
/// polls for change.
fn advance_pos(&mut self, idx: usize, frames: u32) {
let info = &CHAN_INFO[idx];
let c = self.chan[idx];
Self::add_field(self.pos(info.pos_a), info.pos_a_shift, frames);
if info.pos_a_shift == 18 {
let boundary = c.start_ns + self.rate(idx).ns_for(c.frames);
let ust = self.ust_at(boundary);
let a = self.pos(info.pos_a);
*a = (*a & !UST_LATCH_MASK) | (ust & UST_LATCH_MASK);
}
if !info.pos_b_parent {
Self::add_field(self.pos(info.pos_b), info.pos_b_shift, frames);
}
}
fn bank(&self, reg: u32) -> u32 {
self.dma_bank[((reg - DMA_BANK_FIRST) / 4) as usize]
}
/// Advance the UST counter to `now`. It counts only while enabled.
fn ust_update(&mut self, now: i64) {
if self.ust_enabled && now > self.ust_last_ns {
let total = now - self.ust_last_ns + self.ust_phase;
self.ust_count = self.ust_count.wrapping_add((total / UST_NS_PER_TICK) as u32);
self.ust_phase = total % UST_NS_PER_TICK;
}
self.ust_last_ns = now;
}
/// Whether the descriptor set `ring` is programmed for a transfer with
/// control word `limit`: an address, the control word, and set B equal
/// to set A. The status ring's whole-memory limit needs no set B.
fn ring_valid(&self, ring: &RingRegs, is_status: bool, limit: u32) -> bool {
if (self.bank(ring[0]) == 0 && self.bank(ring[1]) == 0) || self.bank(ring[2]) != limit {
return false;
}
if is_status && limit == CTRL_START_STATUS_ONESHOT {
return true;
}
self.bank(ring[0]) == self.bank(ring[3])
&& self.bank(ring[1]) == self.bank(ring[4])
&& self.bank(ring[5]) == limit
}
fn ring_running(&self, ring: &RingRegs) -> bool {
if *ring == RING_INPUT {
self.chan[CH_IN].running
} else if *ring == RING_OUTPUT {
self.chan[CH_OUT].running
} else if *ring == RING_AES_SUB {
self.chan[CH_AES_SUB].running
} else {
self.status_running
}
}
/// The words of descriptor RAM entry `index`.
fn desc_entry(&self, index: u32) -> (u32, u32, u32) {
let at = DMA_BANK_FIRST + index * DESC_RAM_ENTRY_BYTES;
(self.bank(at), self.bank(at + 4), self.bank(at + 8))
}
/// Whether the analog output's working registers hold a transfer: an
/// address and a length.
fn out_programmed(&self) -> bool {
let ring = &RING_OUTPUT;
(self.bank(ring[0]) != 0 || self.bank(ring[1]) != 0)
&& (self.bank(ring[2]) >> CTRL_LEN_SHIFT) & CTRL_LEN_MASK != 0
}
/// Decode a descriptor for channel `idx`, or say why it cannot run. A
/// partial frame is refused: what hardware does with one is unknown.
fn decode_desc(&self, idx: usize, words: (u32, u32, u32)) -> Option<Desc> {
let info = &CHAN_INFO[idx];
let (lo, hi, ctrl) = words;
let base = (u64::from(hi) << 32) | u64::from(lo);
let neg = (ctrl >> CTRL_LEN_SHIFT) & CTRL_LEN_MASK;
let units = 0u32.wrapping_sub(neg) & CTRL_LEN_MASK;
let mut len = u64::from(units) * DMA_UNIT_BYTES;
let next = (ctrl >> CTRL_NEXT_SHIFT) & CTRL_NEXT_MASK;
// Only the analog output's end-of-descriptor form is established.
let eod = info.output && ctrl & CTRL_EOD != 0;
if base == 0 || len == 0 {
crate::dlog!(LogModule::Rad1, "rad1: {} enabled with no ring programmed (address {base:#x}, control {ctrl:#x})", info.name);
return None;
}
if len > DMA_MAX_BYTES {
crate::dlog!(LogModule::Rad1, "rad1: {} ring length {len:#x} exceeds the modelled cap; clamping", info.name);
len = DMA_MAX_BYTES;
}
if !len.is_multiple_of(info.frame_bytes) {
crate::dlog!(LogModule::Rad1, "rad1: {} ring length {len:#x} is not a whole number of frames", info.name);
return None;
}
if !eod && !info.output && next != info.tag {
crate::dlog!(LogModule::Rad1, "rad1: {} control word {ctrl:#x} carries tag {next}, not the channel type {}", info.name, info.tag);
}
let looping = info.output && !eod && self.desc_entry(next) == words;
Some(Desc { base, len, eod, next, looping })
}
/// The enable edge: latch the working descriptor and start. A ring that
/// is not programmed, or not a whole number of frames, starts nothing.
fn chan_start(&mut self, idx: usize, now: i64) {
let info = &CHAN_INFO[idx];
let words = (self.bank(info.ring[0]), self.bank(info.ring[1]), self.bank(info.ring[2]));
let Some(d) = self.decode_desc(idx, words) else { return };
self.chan[idx] = Chan {
running: true,
base: d.base,
len: d.len,
offset: 0,
start_ns: now,
frames: 0,
eod: d.eod,
next: d.next,
looping: d.looping,
stalled: false,
};
}
/// The channel has played its descriptor to the end; returns whether it
/// goes on. End of descriptor stops it and clears the enable bit;
/// otherwise the entry the index names is loaded, and a never-programmed
/// one is reported and left standing.
fn descriptor_end(&mut self, idx: usize) -> bool {
let c = self.chan[idx];
if c.eod {
self.chan[idx].running = false;
if idx == CH_OUT {
self.analog_out_en &= !ENABLE_BIT;
}
return false;
}
if c.looping || idx != CH_OUT {
self.chan[idx].offset = 0;
return true;
}
let words = self.desc_entry(c.next);
let linked = if words == (0, 0, 0) { None } else { self.decode_desc(idx, words) };
match linked {
Some(d) => {
self.chan[idx] = Chan {
base: d.base,
len: d.len,
offset: 0,
eod: d.eod,
next: d.next,
looping: d.looping,
..c
};
true
}
None => {
crate::dlog!(
LogModule::Rad1,
"rad1: {} links to descriptor {} which was never programmed (unsupported); output stopped",
CHAN_INFO[idx].name,
c.next
);
self.chan[idx].stalled = true;
false
}
}
}
}
/// The onboard RAD audio function. The timer callbacks hold a weak
/// reference to the same state.
pub struct Rad1 {
inner: Arc<Inner>,
}
impl Deref for Rad1 {
type Target = Inner;
fn deref(&self) -> &Inner {
&self.inner
}
}
impl Rad1 {
pub fn new(tm: &Arc<TimerManager>) -> Self {
Self { inner: Arc::new_cyclic(|me| Inner::new(me.clone(), tm, RAD1_REVISION)) }
}
/// The RAD1 on the Onyx2's MediaIO daughtercard. Its PCI revision byte
/// differs from the Octane's, and 0x88 and 0x8c do not mute it; the rest
/// of the model is the same.
pub fn mediaio(tm: &Arc<TimerManager>) -> Self {
Self { inner: Arc::new_cyclic(|me| Inner::new(me.clone(), tm, RAD1_REVISION_MEDIAIO)) }
}
}
impl Rad1 {
/// Name the card's state lock in the lock registry, which holds only a
/// weak reference to it.
pub fn register_locks(&self) {
let me = Arc::downgrade(&self.inner);
crate::locks::register_lock("rad1::state", move || me.upgrade().is_some_and(|i| i.state.is_locked()));
}
}
/// Lock order: `tick_pass`, then `state`, then `stopped_at` (a leaf, taken by
/// `now`; both in [`CardClock`]). Rings and status slots are moved with
/// `state` held: the DMA goes down through the Bridge and HEART, which never
/// call back into the card, and a catch-up moves at most two revolutions of a
/// ring.
pub struct Inner {
pci: PciFunctionState,
state: Mutex<State>,
/// The sample clock, its stops and hold-ups, and the timer bookkeeping
/// shared with other audio cards; reached through `Deref`.
clock: CardClock,
timers: Arc<TimerManager>,
/// The next status completion, in machine nanoseconds.
status: Timer,
/// `[audio]` settings once host output is enabled; `None` (tests,
/// `no_audio`) keeps the output channel running silently.
audio_cfg: Mutex<Option<AudioConfig>>,
sink: Mutex<Option<Sink>>,
/// What the analog channels moved and skipped (`audio status`).
meter: Arc<Meter>,
/// Opens the host stream; tests put their own ring behind it.
open_host: fn(&Inner, &AudioConfig) -> Option<Output>,
/// Whether the host stream is full, so each run of dropped output is
/// logged once.
host_full: AtomicBool,
/// Whether 0x88 and 0x8c mute the output: the Octane's card only.
mute_words: bool,
/// Whether the counter at 0x30 runs from reset, with no control write:
/// the MediaIO card only. Its driver never writes the control word, yet
/// requires the counter to advance.
ust_free_running: bool,
me: Weak<Inner>,
}
/// The host stream, at the analog output's power-on rate until the guest
/// sets another.
fn open_host_output(_card: &Inner, cfg: &AudioConfig) -> Option<Output> {
crate::host_audio::open_output(cfg, "Octane audio", PCM_CHANNELS, FREQ_ANALOG as u32, "IRIS_OCTANE_AUDIO_CAPTURE")
}
impl Deref for Inner {
type Target = CardClock;
fn deref(&self) -> &CardClock {
&self.clock
}
}
impl Inner {
fn new(me: Weak<Inner>, tm: &Arc<TimerManager>, revision: u8) -> Self {
let ust_free_running = revision == RAD1_REVISION_MEDIAIO;
Self {
pci: PciFunctionState::new(PciConfig::new(
PCI_VENDOR_SGI,
PCI_DEVICE_RAD1,
PCI_CLASS_NOT_DEFINED,
revision,
[Bar::Mem(BAR0_SIZE), Bar::Unused, Bar::Unused, Bar::Unused, Bar::Unused, Bar::Unused],
0,
)),
state: Mutex::new(State::new(0, ust_free_running)),
clock: CardClock::new(tm.clock().clone()),
timers: tm.clone(),
status: Timer::new(tm, &me, |i: &Inner, due| i.status_timer_tick(due)),
audio_cfg: Mutex::new(None),
sink: Mutex::new(None),
meter: Meter::new(if ust_free_running { "RAD1 (MediaIO)" } else { "RAD1" }, &["analog in", "analog out"]),
open_host: open_host_output,
host_full: AtomicBool::new(false),
mute_words: revision != RAD1_REVISION_MEDIAIO,
ust_free_running,
me,
}
}
/// Play the analog output through the host with `audio`'s settings. While
/// the output runs, a timer keeps its frames moving between the guest's
/// own looks.
///
/// The host stream opens when the machine starts, before the guest
/// runs, so a host slow to open or to take its first samples is ready
/// before the guest plays.
///
/// The card's clock runs on wall time: frames falling due faster than
/// the host stream takes them are dropped. The stream opens whether or
/// not the host has a sound device at that moment, and follows one
/// that appears later.
pub fn enable_output(&self, audio: AudioConfig) {
*self.audio_cfg.lock() = Some(audio);
let mut s = self.state.lock();
self.arm_audio(&mut s);
}
/// Whether timers may be armed: started.
fn timers_live(&self) -> Option<&Arc<TimerManager>> {
self.armed.load(Ordering::SeqCst).then_some(&self.timers)
}
/// Run the output pump exactly while the analog output channel runs with
/// host audio enabled. Called with the state lock held after anything
/// that can start or stop the channel.
fn arm_audio(&self, s: &mut State) {
let want = s.chan[CH_OUT].running && self.audio_cfg.lock().is_some();
match (want, s.audio_timer) {
(true, None) => {
let Some(tm) = self.timers_live() else { return };
let me = self.me.clone();
let period = Duration::from_millis(PUMP_MS);
s.audio_timer = Some(tm.add_recurring(Instant::now() + period, period, (), move |_| {
let Some(i) = me.upgrade() else { return TimerReturn::Delete };
i.pump()
}));
}
(false, Some(id)) => {
s.audio_timer = None;
self.timers.remove(id);
}
_ => {}
}
}
/// One tick of the output timer: move the frames the sample clock has
/// produced, and end the timer when the channel has stopped.
fn pump(&self) -> TimerReturn {
let _pass = self.tick_pass.lock();
if !self.armed.load(Ordering::SeqCst) {
return TimerReturn::Continue;
}
// Status completions move the output while they run; a pump read
// inside a hold-up would keep the late completion from absorbing it.
let now = (!self.state.lock().status_running).then(|| self.now());
let mut s = self.state.lock();
if let Some(now) = now {
self.sync_chan(&mut s, CH_OUT, now);
}
if s.chan[CH_OUT].running {
TimerReturn::Continue
} else {
s.audio_timer = None;
TimerReturn::Delete
}
}
/// Open the output sink, once, when host output is enabled.
fn open_sink(&self) {
let mut sink = self.sink.lock();
if sink.is_some() {
return;
}
let Some(cfg) = self.audio_cfg.lock().clone() else {
return;
};
let now = Instant::now();
let host = (self.open_host)(self, &cfg);
crate::dlog!(LogModule::Rad1, "rad1: host audio open took {:.1} ms ({})", now.elapsed().as_secs_f64() * 1e3, if host.is_some() { "open" } else { "failed" });
*sink = Some(Sink { host, dump: AudioDump::from_env(), tap: None });
}
/// Times the host stream ran dry while the card was playing.
pub fn underruns(&self) -> u64 {
self.sink.lock().as_ref().and_then(|sk| sk.host.as_ref()).map_or(0, |o| o.stats().underruns)
}
/// Frames due that the chain end or DMA failure will never move: dropped
/// once, and counted in the channel so they are not owed again.
fn lost(&self, s: &mut State, idx: usize, frames: u64) {
s.chan[idx].frames += frames;
self.meter.skipped(idx, Skip::Dry, frames);
}
/// Hold the timers off guest memory while the machine is stopped. Once
/// this returns no timer callback is under way.
fn pause(&self) {
self.disarm();
self.status.stop();
drop(self.tick_pass.lock());
}
/// Bring the timers back. The first start opens the
/// host stream (see [`Inner::enable_output`]).
fn resume(&self) {
self.open_sink();
self.armed.store(true, Ordering::SeqCst);
let mut s = self.state.lock();
self.arm_audio(&mut s);
if s.status_running {
self.arm_status(&mut s);
}
self.status.start();
}
/// Remove the output pump; it comes back with [`Inner::resume`].
fn disarm(&self) {
self.armed.store(false, Ordering::SeqCst);
let mut s = self.state.lock();
if let Some(id) = s.audio_timer.take() {
self.timers.remove(id);
}
}
/// Back to the power-on state.
pub fn reset(&self) {
let now = self.now();
let mut s = self.state.lock();
let gen = s.status_gen + 1;
if let Some(id) = s.audio_timer.take() {
self.timers.remove(id);
}
self.status.cancel();
*s = State::new(now, self.ust_free_running);
s.status_gen = gen;
}
fn startup_index(off: u32) -> Option<usize> {
STARTUP_OFFSETS.iter().position(|&o| o == off)
}
fn is_descriptor(off: u32) -> bool {
RINGS.iter().any(|r| r.contains(&off)) || (DMA_BANK_FIRST..=DESC_RAM_LAST).contains(&off)
}
fn subcode_access(off: u32, width: usize) -> bool {
let word = off & !7;
// The model also takes 8-byte accesses; this bus layer's widest is 4.
width == 4
&& off & 3 == 0
&& (SUBCODE_FIRST..=SUBCODE_LAST).contains(&word)
&& word != SUBCODE_GAP_A
&& word != SUBCODE_GAP_B
}
fn read(&self, off: u32, width: usize) -> u32 {
let mut s = self.state.lock();
let now = self.clock_now(&s);
if width == 4 {
if let Some(i) = Self::startup_index(off) {
return s.startup[i];
}
}
if Self::subcode_access(off, width) {
let w = s.subcode[((off - SUBCODE_FIRST) / 8) as usize];
return (w >> ((off & 4) * 8)) as u32;
}
if width == 4 && off & 3 == 0 {
if Self::is_descriptor(off) {
return s.bank(off);
}
if (POS_FIRST..=POS_LAST).contains(&off) {
self.sync_all(&mut s, now);
return s.sample_pos[((off - POS_FIRST) / 4) as usize];
}
if off == REG_ANALOG_OUT_EN {
// The enable bit clears when a one-shot transfer ends.
self.sync_chan(&mut s, CH_OUT, now);
return s.analog_out_en;
}
if off == REG_STATUS_DMA_CTRL {
return s.status_dma_ctrl;
}
}
if off == REG_UST_COUNTER && width == 4 {
s.ust_update(now);
return s.ust_count;
}
crate::dlog!(LogModule::Rad1, "rad1: unsupported {width}-byte BAR0 read at {off:#x}");
0
}
/// A write the model does not support is logged and dropped. The model
/// fails the bus cycle; this bus layer cannot, so a refused write leaves
/// the register unchanged.
fn write(&self, off: u32, val: u32, width: usize) {
let mut s = self.state.lock();
let now = self.clock_now(&s);
if self.write_locked(&mut s, off, val, width, now).is_none() {
crate::dlog!(LogModule::Rad1, "rad1: unsupported {width}-byte BAR0 write at {off:#x} value {val:#x}");
}
self.arm_audio(&mut s);
}
/// `None` when the write is unsupported.
fn write_locked(&self, s: &mut State, off: u32, val: u32, width: usize, now: i64) -> Option<()> {
if width == 4 {
if let Some(i) = Self::startup_index(off) {
let refused = match off {
REG_ADAT_IN_CTRL => REFUSED_ADAT_IN,
REG_AES_INPUT_CTRL => REFUSED_AES_IN,
REG_ADAT_OUT_CTRL | REG_AES_OUT_CTRL => REFUSED_DIGITAL_OUT,
_ => 0,
};
if val & refused != 0 {
return None;
}
if off == REG_ANALOG_INPUT_CTRL {
// The analog input's interface word: bit 0 runs it.
if val & ENABLE_BIT != 0
&& !s.chan[CH_IN].running
&& !s.ring_valid(&RING_INPUT, false, CTRL_START_ANALOG_IN)
{
return None;
}
self.enable_write(s, CH_IN, val, now);
} else if off == REG_AES_INPUT_CTRL {
// AES3 input control: bit 2 runs the input subcode channel.
if val & SUBCODE_ENABLE_BIT != 0
&& !s.chan[CH_AES_SUB].running
&& !s.ring_valid(&RING_AES_SUB, false, CTRL_START_AES_SUB)
{
return None;
}
self.enable_write(s, CH_AES_SUB, val, now);
}
s.startup[i] = val;
match off {
REG_CLOCKGEN_CTRL => self.clockgen_write(s, val, now),
REG_CLOCKGEN_MUX_FIRST..=REG_CLOCKGEN_MUX_LAST => {
let cg = NUM_CG - 1 - ((off - REG_CLOCKGEN_MUX_FIRST) / 4) as usize;
self.clockgen_reselect(s, cg, now);
}
REG_GPIO_A if self.mute_words => match val {
RELAY_RELEASE => s.relay_muted = Some(false),
RELAY_MUTE => s.relay_muted = Some(true),
_ => {}
},
REG_GPIO_B if self.mute_words => match val {
DAC_MUTE => s.dac_muted = Some(true),
DAC_UNMUTE => s.dac_muted = Some(false),
_ => {}
},
_ => {}
}
return Some(());
}
}
if Self::subcode_access(off, width) {
let word = &mut s.subcode[((off - SUBCODE_FIRST) / 8) as usize];
let shift = (off & 4) * 8;
*word = (*word & !(0xffff_ffffu64 << shift)) | (u64::from(val) << shift);
return Some(());
}
if width == 4 && off & 3 == 0 {
if let Some(ring) = RINGS.iter().find(|r| r.contains(&off)) {
if !s.ring_running(ring) {
s.dma_bank[((off - DMA_BANK_FIRST) / 4) as usize] = val;
return Some(());
}
} else if (DMA_BANK_FIRST..=DESC_RAM_LAST).contains(&off) {
// A descriptor RAM entry no supported ring's registers
// cover: stored for a link to load.
s.dma_bank[((off - DMA_BANK_FIRST) / 4) as usize] = val;
return Some(());
} else if off == REG_ANALOG_OUT_EN {
return self.analog_out_write(s, val, now);
} else if off == REG_STATUS_DMA_CTRL {
self.status_ctrl_write(s, val, now)?;
s.status_dma_ctrl = val;
return Some(());
}
}
// The values are the drivers'; hold, run and stop are the model's
// reading of them (see the module notes).
if off == REG_UST_CONTROL && width == 4 {
self.sync_all(s, now);
match val {
UST_CTRL_HOLD => {
s.ust_update(now);
s.ust_enabled = false;
s.ust_armed = true;
return Some(());
}