rsemu 0.0.4

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
Documentation
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
//! The two controller ports at `$4016` and `$4017`.
//!
//! Sources: the NESdev wiki, [Standard
//! controller](https://www.nesdev.org/wiki/Standard_controller), [Controller
//! port registers](https://www.nesdev.org/wiki/Controller_port_registers) and
//! [Input devices](https://www.nesdev.org/wiki/Input_devices).
//!
//! # What the hardware is
//!
//! Almost nothing. Each port carries a clock line, a latch line and a data
//! line. Inside a standard controller a 4021 shift register samples all eight
//! buttons in parallel while the latch line is high and shifts one bit out on
//! every subsequent clock. The console drives both latch lines from bit 0 of
//! `$4016` and clocks a port's register by *reading* that port.
//!
//! ```text
//!   $4016 write   bit 0 -> OUT0, the latch (strobe) line of both ports
//!   $4016 read    bit 0 <- controller 1 serial data; bits 7-5 open bus
//!   $4017 read    bit 0 <- controller 2 serial data; bits 7-5 open bus
//! ```
//!
//! Three consequences follow, and software depends on all three:
//!
//! * **While the strobe is high the register reloads continuously**, so every
//!   read of `$4016` returns the A button and nothing advances.
//! * **The bit order is the register's output order**: A, B, Select, Start, Up,
//!   Down, Left, Right — which is why [`buttons`] numbers A as bit 7.
//! * **After the eighth read an official NES pad returns 1 forever** (until the
//!   next strobe), because the 4021's serial input is tied high. A Famicom's
//!   hardwired pads return 0 instead. The NES behaviour is the one modelled;
//!   `AccuracyCoin` and most late software rely on it to count the pads.
//!
//! # `$4017` is shared with the APU
//!
//! On the real chip `$4017` is the controller-2 port on a **read** and the APU
//! frame counter on a **write**. `core::space` routes a whole mapping to one
//! device, so a machine description can give `$4017` to the APU or to this
//! device but not to both, and the shipped NES machines give it to the APU —
//! losing the frame counter is much worse than losing player two. [`PORT2`] is
//! published regardless, so a machine that wants controller 2 more than it
//! wants the frame IRQ can map it. Splitting the address properly wants a
//! read/write-split mapping in `core::space`, which is a framework change and
//! not this device's to make.
//!
//! # Where the buttons come from
//!
//! Through [`pads`], the build's named pad ports — the same shape as
//! [`crate::host::chardev::ports`], and for the same reason: a *name* is the
//! only thing that can travel from a machine description into a device
//! constructor. The host (or a test) opens the port by name and stores a byte;
//! the device reads it when the guest strobes. Input crossing into the machine
//! by exactly one narrow, named seam is what makes it recordable
//! (`CLAUDE.md`, determinism).
//!
//! The table is the *build's* — [`core::hosts`](crate::core::hosts) — not the
//! process's, so two consoles in one process each have their own `player1`.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;

use crate::core::device::{Device, DeviceClass, PropertySpec, RealizeCtx, ResetKind};
use crate::core::error::{BusError, Result};
use crate::core::props::{Props, ValueKind};
use crate::core::sched::{AccessKind, LazyHandle};
use crate::core::space::{
    AccessConstraints, MemAttrs, MemOps, MemResult, Region as MmioRegion, RegionRef,
};
use crate::core::state::{ChunkReader, ChunkWriter, Sink, Source};
use crate::core::sync::{AtomicU8, AtomicU64, LockRank, Mutex, Ordering};
use crate::core::value::{Endian, Width};
use crate::machine::realize::Instance;

/// The class name a machine description would use.
const CLASS_NAME: &str = "nes.ports";

/// The snapshot chunk version. Bump with the encoding, never on its own.
const STATE_VERSION: u32 = 1;

/// The name of the region that decodes `$4016`.
pub const PORT1: &str = "port1";

/// The name of the region that decodes `$4017` — see the [module docs](self)
/// for why the shipped machines do not map it.
pub const PORT2: &str = "port2";

/// The pad port a machine gets when its description names none.
pub const DEFAULT_PAD_PORT: &str = "nes-pads";

/// Which bits of a `$4016`/`$4017` read the port does *not* drive.
///
/// Bits 7-5 are not connected to the controller at all: they float, and what
/// floats is whatever the master last left on the data bus — for an ordinary
/// `LDA $4016` that is `$40`, the high byte of the address it just put out
/// (NESdev, "Open bus behavior"). Bits 4-0 belong to the port, and on an
/// NES-001 only D0, D3 and D4 have anything on them.
const OPEN_BUS_BITS: u8 = 0xe0;

/// Controller button bits, in the shift register's output order.
///
/// Bit 7 is what the *first* read after a strobe returns. That is the order the
/// hardware shifts in and the order every NES read routine assembles, so it is
/// the order the host seam speaks.
pub mod buttons {
    /// The A button — the first bit out.
    pub const A: u8 = 0x80;
    /// The B button.
    pub const B: u8 = 0x40;
    /// Select.
    pub const SELECT: u8 = 0x20;
    /// Start.
    pub const START: u8 = 0x10;
    /// D-pad up.
    pub const UP: u8 = 0x08;
    /// D-pad down.
    pub const DOWN: u8 = 0x04;
    /// D-pad left.
    pub const LEFT: u8 = 0x02;
    /// D-pad right — the last bit out.
    pub const RIGHT: u8 = 0x01;
    /// Nothing held.
    pub const NONE: u8 = 0x00;
}

// ---------------------------------------------------------------------------
// the host seam
// ---------------------------------------------------------------------------

/// What the host holds: the current button state of one console's two pads.
///
/// Level, not events. The console samples this whenever the guest strobes, so a
/// button is "held" for as long as the host leaves the bit set — which is also
/// what makes the seam replayable: the state at each sample is the whole of the
/// input.
#[derive(Debug, Default)]
pub struct Pad {
    /// Controller 1 and controller 2, in [`buttons`] order.
    ///
    /// Atomics rather than a lock: the host thread writes and the emulation
    /// thread reads, on the guest's hot path, and there is nothing to keep
    /// consistent between the two bytes.
    held: [AtomicU8; 2],
}

impl Pad {
    /// A pad port with nothing held.
    #[must_use]
    pub fn new() -> Pad {
        Pad::default()
    }

    /// Set what controller `port` (0 or 1) is holding.
    ///
    /// Out-of-range ports are ignored: a host that asks for controller 5 has a
    /// bug, but dropping the press is better than panicking inside a frame.
    pub fn set(&self, port: usize, held: u8) {
        if let Some(cell) = self.held.get(port) {
            cell.store(held, Ordering::Relaxed);
        }
    }

    /// What controller `port` is holding. Nothing, for a port that does not
    /// exist.
    #[must_use]
    pub fn get(&self, port: usize) -> u8 {
        self.held
            .get(port)
            .map_or(buttons::NONE, |c| c.load(Ordering::Relaxed))
    }
}

/// The build's named pad ports.
///
/// See the [module docs](self) for why a name is the only thing that can travel
/// from a machine description into a device constructor, and
/// [`core::hosts`](crate::core::hosts) for the table this is a view onto.
pub mod pads {
    use super::Pad;
    use alloc::string::String;
    use alloc::sync::Arc;
    use alloc::vec::Vec;

    use crate::core::error::Result;
    use crate::core::hosts::{HostKind, HostObjects};
    use crate::core::props::Props;

    /// The kind a pad port is filed under in a build's
    /// [`HostObjects`].
    pub const KIND: HostKind = HostKind::new("pad");

    /// The a pad port `name` refers to in `hosts`, creating it on first mention.
    ///
    /// The **host** side of the rendezvous: called before the host starts
    /// pressing buttons, or after the build to pick up what a device opened.
    ///
    /// # Errors
    ///
    /// [`crate::Error::Config`] if another kind of host object is already open
    /// under that name, which is a collision between two host modules rather
    /// than anything a machine file can cause.
    pub fn open(hosts: &HostObjects, name: &str) -> Result<Arc<Pad>> {
        hosts.open(KIND, name, Pad::new)
    }

    /// The a pad port `name` refers to in the build these properties are being read
    /// for, creating it on first mention.
    ///
    /// The **device** side, called from `new(props)` — acquiring a host object
    /// is allocation, and [`core::hosts`](crate::core::hosts) argues why. A
    /// `Props` that belongs to no build gets a private one, so a device a unit
    /// test constructed directly still works and simply meets nobody.
    ///
    /// # Errors
    ///
    /// As [`open`].
    pub fn attach(props: &Props, name: &str) -> Result<Arc<Pad>> {
        props.host(KIND, name, Pad::new)
    }

    /// The a pad port called `name`, if it has been opened.
    ///
    /// # Errors
    ///
    /// As [`open`].
    pub fn get(hosts: &HostObjects, name: &str) -> Result<Option<Arc<Pad>>> {
        hosts.get(KIND, name)
    }

    /// Forget `name`, reporting whether there was one.
    ///
    /// Anything still holding the `Arc` keeps working; this only removes the
    /// table's own reference, so a later [`open`] of the same name is a fresh
    /// one.
    pub fn close(hosts: &HostObjects, name: &str) -> bool {
        hosts.close(KIND, name)
    }

    /// Every open name, in order.
    #[must_use]
    pub fn names(hosts: &HostObjects) -> Vec<String> {
        hosts.names(KIND)
    }
}

// ---------------------------------------------------------------------------
// the device
// ---------------------------------------------------------------------------

/// The latch and the two shift registers — everything `$4016` writes touch.
///
/// `Default` is power-on: the strobe line low and the registers holding
/// whatever the last latch left. Zero is the reproducible choice, and
/// determinism is the non-negotiable one (`ROADMAP.md` §0).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct Regs {
    /// OUT0. While set, both registers reload from the pads continuously.
    strobe: bool,
    /// The two shift registers, MSB first: bit 7 is the next bit out.
    ///
    /// Shifting in a 1 at the bottom is what gives an official NES pad its
    /// "1 forever after the eighth read" behaviour, for free and for the same
    /// reason the hardware has it — the 4021's serial input is tied high.
    shift: [u8; 2],
    /// The CPU cycle the latch line last went high on.
    ///
    /// The 4021 is transparent while the line is high, but the console only
    /// *drives* it on **put** cycles — the second half of an APU cycle — so a
    /// pulse that is high across nothing but a get cycle never reaches the
    /// pads at all. Holding the cycle here is what lets the falling edge ask
    /// whether any put happened in between.
    raised_at: u64,
}

/// What the device and its two memory ports both hold.
struct Shared {
    /// Where the buttons come from.
    pad: Arc<Pad>,
    /// The port's own registers. `DEVICE`-ranked and never held across an
    /// outward call — there are none to make.
    regs: Mutex<Regs>,
    /// Which CPU cycles are puts: cycle `c` is a get iff `c - 1 + phase` is
    /// even. Must agree with the APU's `put-phase` and the DMA unit's.
    phase: u64,
    /// The CPU cycle this device has been caught up to.
    ///
    /// The ports have no state that advances on its own; what they need the
    /// clock for is the *phase* of the cycle an access lands on, which is not
    /// something a memory operation is told.
    cycle: AtomicU64,
    /// The catch-up handle, so an access can ask what cycle it is on.
    lazy: Mutex<Option<LazyHandle>>,
}

/// Whether CPU cycle `cycle` is a get cycle.
#[inline]
const fn is_get(cycle: u64, phase: u64) -> bool {
    (cycle.wrapping_sub(1).wrapping_add(phase)) & 1 == 0
}

impl fmt::Debug for Shared {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Shared")
            .field("regs", &self.regs)
            .field("cycle", &self.cycle.load(Ordering::Relaxed))
            .finish()
    }
}

impl Shared {
    /// Reload both registers from the pads, as a high latch line does.
    fn latch(&self, regs: &mut Regs) {
        regs.shift = [self.pad.get(0), self.pad.get(1)];
    }

    /// One read of a port, as a byte on the CPU data bus.
    ///
    /// `advance` is false for a debug read: a monitor looking at `$4016` must
    /// not clock the controller (`ROADMAP.md` §15, invariant 5).
    fn read_port(&self, port: usize, bus: u8, advance: bool) -> u8 {
        let mut regs = self.regs.lock();
        if regs.strobe {
            // Latched continuously while the line is high, so every read is the
            // A button and nothing shifts.
            self.latch(&mut regs);
        }
        let bit = regs.shift[port] >> 7;
        if advance && !regs.strobe {
            regs.shift[port] = (regs.shift[port] << 1) | 1;
        }
        (bus & OPEN_BUS_BITS) | bit
    }

    /// A write of `value` to `$4016`, on CPU cycle `cycle`.
    ///
    /// The 4021 is *transparent* while the latch line is high, not
    /// edge-triggered: it tracks the buttons the whole time and freezes them on
    /// the falling edge. So the pads are sampled both while the line is high
    /// and on the write that takes it low — otherwise a game that strobes,
    /// waits and then releases would read the buttons as they were at the
    /// rising edge.
    ///
    /// **But the console only drives OUT0 on put cycles.** A pulse raised on a
    /// get and dropped on the next put reaches the pads; one raised on a put
    /// and dropped on the next get never does, and the registers keep whatever
    /// they had. `DEC $4016` is a six-cycle instruction whose two writes land
    /// on consecutive cycles, which is exactly how AccuracyCoin's "Controller
    /// Strobing" tests 3 and 4 tell the two apart.
    fn write_strobe(&self, value: u8, cycle: u64) {
        let mut regs = self.regs.lock();
        let was = regs.strobe;
        regs.strobe = value & 1 != 0;
        if regs.strobe {
            if !was {
                regs.raised_at = cycle;
            }
            // Nothing is sampled *by the write*: the line has only just gone
            // high, and the pads see it on the next put. A program that holds
            // the strobe and reads gets its latch from `read_port`, which is
            // where "transparent while high" is modelled; one that holds it and
            // then drops it gets it from the falling edge below.
            return;
        }
        if was {
            // The falling edge. The line was high across cycles
            // `raised_at + 1 ..= cycle`; the pads saw it only if one of those
            // was a put.
            let raised = regs.raised_at;
            let saw_put = cycle > raised + 1 || !is_get(cycle, self.phase);
            if saw_put {
                self.latch(&mut regs);
            }
        }
    }

    /// Catch up to the cycle this access is on, and report it.
    fn sync(&self, attrs: MemAttrs) -> u64 {
        let handle = self.lazy.lock().clone();
        if let Some(handle) = handle {
            let kind = if attrs.debug {
                AccessKind::Debug
            } else {
                AccessKind::Guest
            };
            if let Ok(tick) = handle.sync(kind) {
                self.cycle.store(tick, Ordering::Relaxed);
            }
        }
        self.cycle.load(Ordering::Relaxed)
    }
}

/// The NES's two controller ports.
///
/// Cloneable handles onto one piece of hardware: [`Device::region`] hands out
/// the two one-byte apertures while the machine keeps the device.
#[derive(Debug)]
pub struct NesPorts {
    shared: Arc<Shared>,
    /// `$4016`, built once at construction so two `map` statements naming it
    /// get one region.
    port1: RegionRef,
    /// `$4017`.
    port2: RegionRef,
    /// The pad port's name, for diagnostics.
    port_name: String,
}

impl NesPorts {
    /// Validate properties and allocate. Performs no outward action.
    ///
    /// Properties: `pads`, the name of the host pad port to read
    /// ([`DEFAULT_PAD_PORT`] if absent).
    ///
    /// # Errors
    ///
    /// [`crate::Error::Property`] for an unknown or ill-typed property.
    pub fn new(props: &Props) -> Result<NesPorts> {
        let mut r = props.reader();
        let name: String = r.or("pads", String::from(DEFAULT_PAD_PORT))?;
        let phase = r.or_range::<u64>("put-phase", 0, 0..=1)?;
        r.finish()?;
        Ok(NesPorts::with_pad_phase(
            pads::attach(props, &name)?,
            name,
            phase,
        ))
    }

    /// Build one against a pad port held directly, for a caller assembling a
    /// NES without the DSL.
    #[must_use]
    pub fn with_pad(pad: Arc<Pad>, port_name: String) -> NesPorts {
        NesPorts::with_pad_phase(pad, port_name, 0)
    }

    /// The same, with the console's get/put phase.
    #[must_use]
    pub fn with_pad_phase(pad: Arc<Pad>, port_name: String, phase: u64) -> NesPorts {
        let shared = Arc::new(Shared {
            pad,
            regs: Mutex::with_rank(LockRank::DEVICE, Regs::default()),
            phase: phase & 1,
            cycle: AtomicU64::new(0),
            lazy: Mutex::new(None),
        });
        let port = |index: usize, name: &'static str| {
            Arc::new(MmioRegion::io(
                name,
                1,
                Arc::new(PortWindow {
                    shared: Arc::clone(&shared),
                    index,
                }) as Arc<dyn MemOps>,
            )) as RegionRef
        };
        NesPorts {
            port1: port(0, "nes.ports.4016"),
            port2: port(1, "nes.ports.4017"),
            shared,
            port_name,
        }
    }

    /// The pad port this device reads its buttons from.
    #[must_use]
    pub fn pad(&self) -> &Arc<Pad> {
        &self.shared.pad
    }

    /// The name that pad port is registered under.
    #[must_use]
    pub fn pad_name(&self) -> &str {
        &self.port_name
    }
}

/// One of the two one-byte windows onto a [`NesPorts`].
#[derive(Debug)]
struct PortWindow {
    shared: Arc<Shared>,
    /// 0 for `$4016`, 1 for `$4017`.
    index: usize,
}

impl MemOps for PortWindow {
    fn read(&self, offset: u64, dst: &mut [u8], attrs: MemAttrs) -> MemResult {
        let ([byte], 0) = (dst, offset) else {
            return Err(BusError::BadAccess);
        };
        *byte = self.shared.read_port(self.index, attrs.bus, !attrs.debug);
        Ok(())
    }

    fn write(&self, offset: u64, src: &[u8], attrs: MemAttrs) -> MemResult {
        let ([value], 0) = (src, offset) else {
            return Err(BusError::BadAccess);
        };
        if attrs.debug {
            // A debug write would latch the pads for real; the monitor has to
            // go through the device's own API to say it meant it.
            return Ok(());
        }
        // Only `$4016` carries OUT0. A write to `$4017` is the APU frame
        // counter's, and the port hardware ignores it — see the module docs.
        if self.index == 0 {
            let cycle = self.shared.sync(attrs);
            self.shared.write_strobe(*value, cycle);
        }
        Ok(())
    }

    fn constraints(&self) -> AccessConstraints {
        AccessConstraints::word(Width::U8, Endian::Little)
    }
}

impl Device for NesPorts {
    fn class(&self) -> &'static DeviceClass {
        &PORTS_CLASS
    }

    fn realize(&self, _ctx: &mut RealizeCtx<'_>) -> Result<()> {
        // Nothing outward. The ports drive no line and are placed by `map`
        // statements like every other aperture.
        Ok(())
    }

    /// Yes — not because anything here advances on its own, but because the
    /// **phase** of the CPU cycle an access lands on decides whether a `$4016`
    /// write reaches the pads, and a memory operation is not told what cycle it
    /// is on. Registering as lazily-advanced is how a device asks.
    fn is_lazy(&self) -> bool {
        true
    }

    fn current_tick(&self) -> u64 {
        self.shared.cycle.load(Ordering::Relaxed)
    }

    fn advance_to(&self, tick: u64) {
        self.shared.cycle.store(tick, Ordering::Relaxed);
    }

    fn attach_lazy(&self, handle: LazyHandle) {
        *self.shared.lazy.lock() = Some(handle);
    }

    fn reset(&self, _kind: ResetKind) {
        // Both kinds: /RES clears the output latch, and the shift registers
        // hold nothing a reset would preserve. What the *host* is holding is
        // not the machine's state and is deliberately untouched — releasing
        // the player's thumb on reset would be a strange thing to model.
        *self.shared.regs.lock() = Regs::default();
    }

    fn save(&self, w: &mut ChunkWriter<'_>) -> Result<()> {
        let regs = *self.shared.regs.lock();
        w.write_bool(regs.strobe)?;
        w.write_u8(regs.shift[0])?;
        w.write_u8(regs.shift[1])?;
        // Appended: the cycle the latch line went high on, which decides
        // whether a one-cycle pulse ever reached the pads.
        w.write_u64(regs.raised_at)
    }

    fn load(&self, r: &mut ChunkReader<'_>) -> Result<()> {
        let strobe = r.read_bool()?;
        let first = r.read_u8()?;
        let second = r.read_u8()?;
        let raised_at = r.read_u64().unwrap_or(0);
        *self.shared.regs.lock() = Regs {
            strobe,
            shift: [first, second],
            raised_at,
        };
        Ok(())
    }

    /// One of the two ports, by name.
    ///
    /// The empty name gets nothing: a device with two identical one-byte
    /// apertures has no "the" region, and quietly handing back `$4016` would
    /// leave a machine that looked complete with player two unmapped.
    fn region(&self, name: &str) -> Option<RegionRef> {
        match name {
            PORT1 => Some(Arc::clone(&self.port1)),
            PORT2 => Some(Arc::clone(&self.port2)),
            _ => None,
        }
    }
}

/// The machine layer's half: the ports take no clock, no space and no pin, so
/// binding them is nothing at all.
///
/// The `impl` still has to exist — a class with no [`Instance`] publishes no
/// regions to the machine graph, and `map cpubus 0x4016 = ports.port1` would be
/// told the class publishes none.
impl Instance for NesPorts {}

/// The properties [`PORTS_CLASS`] accepts.
static PORTS_PROPERTIES: &[PropertySpec] = &[
    PropertySpec {
        name: "pads",
        kind: ValueKind::Str,
        required: false,
        summary: "the host pad port to read buttons from, by name (default \"nes-pads\")",
    },
    PropertySpec {
        name: "put-phase",
        kind: ValueKind::Uint,
        required: false,
        summary: "which CPU cycles are puts (0 or 1); must match the APU's",
    },
];

/// The device class, as `nes.ports` in a machine description.
pub static PORTS_CLASS: DeviceClass = DeviceClass {
    name: CLASS_NAME,
    version: STATE_VERSION,
    summary: "NES controller ports ($4016/$4017): the OUT0 latch and two 8-bit shift registers",
    properties: PORTS_PROPERTIES,
    construct: |props| Ok(Box::new(NesPorts::new(props)?) as Box<dyn Device>),
};

/// Add [`PORTS_CLASS`] to a registry.
///
/// # Errors
///
/// [`crate::Error::Config`] if the class name is already taken.
pub fn register(registry: &mut crate::core::Registry) -> Result<()> {
    registry.add(&PORTS_CLASS)
}

/// Bind [`PORTS_CLASS`] into the machine graph.
///
/// # Errors
///
/// [`crate::Error::Config`] if the class name is already bound.
pub fn bind(bindings: &mut crate::machine::Bindings) -> Result<()> {
    bindings.bind(CLASS_NAME, |props| Ok(Arc::new(NesPorts::new(props)?)))
}

/// What the validator should know about `nes.ports`.
#[must_use]
pub fn schema() -> crate::machine::validate::ClassSchema {
    use crate::machine::validate::{ClassSchema, PropSchema};
    ClassSchema::new(CLASS_NAME)
        .prop(PropSchema::new("pads", ValueKind::Str))
        .prop(PropSchema::new("put-phase", ValueKind::Uint).range(0, 1))
        .region(PORT1)
        .region(PORT2)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Raise the latch line and drop it again, spanning a put cycle.
    ///
    /// What every read routine does — `LDA #1 / STA $4016 / LDA #0 / STA
    /// $4016` puts several cycles between the two writes — so the pads are
    /// sampled. The one-cycle pulse that does *not* sample them has its own
    /// test.
    fn strobe(p: &NesPorts) {
        p.shared.write_strobe(1, 10);
        p.shared.write_strobe(0, 14);
    }
    use crate::core::space::AddressSpace;
    use crate::core::state::{MachineShape, Migrations, StateReader, StateWriter};

    /// A device on a pad port of its own.
    ///
    /// Nothing here needs a unique name any more: a pad built this way is
    /// private to the caller, and one built from `Props` belongs to whichever
    /// build's host objects the `Props` was read against.
    fn ports(name: &str) -> NesPorts {
        NesPorts::with_pad(Arc::new(Pad::new()), String::from(name))
    }

    /// Strobe high then low, then read eight bits out of port 1.
    fn sequence(p: &NesPorts) -> u8 {
        strobe(p);
        let mut out = 0u8;
        for _ in 0..8 {
            out = (out << 1) | (p.shared.read_port(0, 0x40, true) & 1);
        }
        out
    }

    #[test]
    fn the_shift_register_reports_the_buttons_a_first() {
        let p = ports("test-order");
        p.pad().set(0, buttons::START | buttons::RIGHT);
        // Read back in the order the hardware shifts: the byte reassembles
        // exactly as it was handed in, which is the whole contract of the bit
        // order in `buttons`.
        assert_eq!(sequence(&p), buttons::START | buttons::RIGHT);

        p.pad().set(0, buttons::A);
        assert_eq!(sequence(&p), buttons::A);
        p.pad().set(0, buttons::NONE);
        assert_eq!(sequence(&p), 0);
    }

    #[test]
    fn an_official_pad_reads_one_after_the_eighth_read() {
        let p = ports("test-ninth");
        p.pad().set(0, buttons::NONE);
        strobe(&p);
        for _ in 0..8 {
            assert_eq!(p.shared.read_port(0, 0x40, true) & 1, 0);
        }
        // The 4021's serial input is tied high on an NES pad, so everything
        // after the eighth clock is a 1. Software counts pads with this.
        for _ in 0..4 {
            assert_eq!(p.shared.read_port(0, 0x40, true) & 1, 1);
        }
    }

    #[test]
    fn a_high_strobe_reloads_forever() {
        let p = ports("test-strobe");
        p.pad().set(0, buttons::A);
        p.shared.write_strobe(1, 10);
        // Latched continuously: every read is A, and nothing shifts past it.
        for _ in 0..16 {
            assert_eq!(p.shared.read_port(0, 0x40, true) & 1, 1);
        }
        // Release the strobe and what was latched is the state at the falling
        // edge, not the state at the rising one.
        p.pad().set(0, buttons::NONE);
        p.shared.write_strobe(0, 14);
        assert_eq!(
            p.shared.read_port(0, 0x40, true) & 1,
            0,
            "A was released first"
        );
    }

    #[test]
    fn the_upper_bits_are_open_bus() {
        let p = ports("test-openbus");
        p.pad().set(0, buttons::A);
        strobe(&p);
        // Bits 7-5 come from the CPU's own bus, and for a read of $4016 that
        // is the high byte of the address.
        assert_eq!(p.shared.read_port(0, 0x40, true), 0x40 | 1);
    }

    #[test]
    fn the_two_ports_are_independent() {
        let p = ports("test-two");
        p.pad().set(0, buttons::A);
        p.pad().set(1, buttons::RIGHT);
        strobe(&p);
        // Port 1 shifts A out first; port 2's A is clear and its Right is last.
        assert_eq!(p.shared.read_port(0, 0x40, true) & 1, 1);
        assert_eq!(p.shared.read_port(1, 0x40, true) & 1, 0);
        for _ in 0..6 {
            let _ = p.shared.read_port(1, 0x40, true);
        }
        assert_eq!(
            p.shared.read_port(1, 0x40, true) & 1,
            1,
            "Right, the eighth bit"
        );
    }

    #[test]
    fn a_debug_read_does_not_clock_the_controller() {
        let p = ports("test-debug");
        p.pad().set(0, buttons::A);
        strobe(&p);
        for _ in 0..8 {
            assert_eq!(p.shared.read_port(0, 0x40, false), 0x40 | 1, "still A");
        }
        // And the guest's own first read still gets the first bit.
        assert_eq!(p.shared.read_port(0, 0x40, true) & 1, 1);
    }

    #[test]
    fn the_ports_answer_through_an_address_space() {
        let p = ports("test-space");
        p.pad().set(0, buttons::SELECT);
        let space = AddressSpace::new("cpu", 16);
        {
            let mut topo = space.topology();
            topo.map(p.region(PORT1).expect("port1"), 0x4016)
                .expect("maps");
            topo.map(p.region(PORT2).expect("port2"), 0x4017)
                .expect("maps");
        }
        let wr = |v: u64| {
            space
                .write(0x4016, Width::U8, v, MemAttrs::DEFAULT)
                .expect("writable")
        };
        let rd = || {
            space
                .read(0x4016, Width::U8, MemAttrs::DEFAULT)
                .expect("readable") as u8
        };
        wr(1);
        wr(0);
        let mut out = 0u8;
        for _ in 0..8 {
            out = (out << 1) | (rd() & 1);
        }
        assert_eq!(out, buttons::SELECT);

        // A debug read of the same port disturbs nothing.
        let before = space
            .read(0x4016, Width::U8, MemAttrs::DEBUG)
            .expect("readable");
        assert_eq!(
            space
                .read(0x4016, Width::U8, MemAttrs::DEBUG)
                .expect("readable"),
            before
        );

        // The empty region name gets nothing: there is no "the" port.
        assert!(p.region("").is_none());
    }

    #[test]
    fn state_round_trips() {
        let p = ports("test-state");
        p.pad().set(0, buttons::B | buttons::DOWN);
        strobe(&p);
        let _ = p.shared.read_port(0, 0x40, true);

        let mut shape = MachineShape::new();
        shape.add_device("ports", CLASS_NAME).expect("unique path");
        let mut writer = StateWriter::new(shape);
        let mut chunk = writer
            .chunk("ports", CLASS_NAME, STATE_VERSION)
            .expect("one chunk");
        p.save(&mut chunk).expect("saves");
        let bytes = writer.to_vec().expect("encodes");

        let other = ports("test-state-2");
        let reader = StateReader::new(&bytes).expect("decodes");
        let chunk = reader
            .load("ports", CLASS_NAME, STATE_VERSION, &Migrations::new())
            .expect("finds the chunk");
        other.load(&mut chunk.reader()).expect("loads");
        // Copied out one at a time: two `DEVICE`-ranked locks held together is
        // a lock-order violation, and `core::sync` says so in debug builds.
        let restored = *other.shared.regs.lock();
        let original = *p.shared.regs.lock();
        assert_eq!(restored, original);

        // And it keeps shifting from where the original stood.
        for _ in 0..7 {
            assert_eq!(
                other.shared.read_port(0, 0x40, true) & 1,
                p.shared.read_port(0, 0x40, true) & 1
            );
        }
    }

    #[test]
    fn a_reset_clears_the_latch_but_not_the_players_thumb() {
        let p = ports("test-reset");
        p.pad().set(0, buttons::A);
        p.shared.write_strobe(1, 10);
        p.reset(ResetKind::Cold);
        assert!(!p.shared.regs.lock().strobe);
        assert_eq!(p.pad().get(0), buttons::A, "the host still holds A");
        assert_eq!(sequence(&p), buttons::A);
    }

    #[test]
    fn the_pad_table_hands_the_same_port_to_both_ends() {
        let hosts = Arc::new(crate::core::HostObjects::new());
        let device = NesPorts::new(
            &Props::new()
                .with("pads", "player1")
                .with_hosts(Arc::clone(&hosts)),
        )
        .expect("constructs");
        assert_eq!(device.pad_name(), "player1");

        let host = pads::open(&hosts, "player1").expect("the device opened it");
        host.set(0, buttons::UP);
        assert_eq!(sequence(&device), buttons::UP);
        assert_eq!(pads::names(&hosts), ["player1"]);
        assert!(pads::get(&hosts, "player1").unwrap().is_some());
    }

    #[test]
    fn two_builds_naming_one_pad_port_get_two_pads() {
        // What the process-wide table this replaced could not do: `player1` in
        // two machines is two sets of buttons.
        let left = Arc::new(crate::core::HostObjects::new());
        let right = Arc::new(crate::core::HostObjects::new());
        let make = |hosts: &Arc<crate::core::HostObjects>| {
            NesPorts::new(
                &Props::new()
                    .with("pads", "player1")
                    .with_hosts(Arc::clone(hosts)),
            )
            .expect("constructs")
        };
        let a = make(&left);
        let b = make(&right);
        assert!(!Arc::ptr_eq(a.pad(), b.pad()));

        pads::open(&left, "player1").unwrap().set(0, buttons::UP);
        assert_eq!(sequence(&a), buttons::UP);
        assert_eq!(sequence(&b), buttons::NONE, "the other machine's pad");
    }

    #[test]
    fn a_device_built_outside_a_build_gets_a_private_pad() {
        // No host objects on these properties, so there is nothing to meet:
        // the honest answer is a pad nobody else holds, not a shared one.
        let a = NesPorts::new(&Props::new().with("pads", "player1")).expect("constructs");
        let b = NesPorts::new(&Props::new().with("pads", "player1")).expect("constructs");
        assert!(!Arc::ptr_eq(a.pad(), b.pad()));
    }

    #[test]
    fn an_unknown_property_is_refused() {
        let e = NesPorts::new(&Props::new().with("padz", "x")).expect_err("typo");
        assert!(alloc::format!("{e}").contains("padz"), "{e}");
    }

    #[test]
    fn a_one_cycle_strobe_reaches_the_pads_only_across_a_put() {
        // The console drives OUT0 on put cycles only, so a pulse raised on a
        // get and dropped on the next put is seen and one raised on a put and
        // dropped on the next get is not. `DEC $4016` writes twice on
        // consecutive cycles, which is how AccuracyCoin tells them apart.
        for (raise, expected) in [(9u64, true), (10, false)] {
            let p = NesPorts::with_pad_phase(Arc::new(Pad::new()), String::from("t"), 0);
            // Something in the shift registers to be overwritten, and a button
            // held so a latch is visible.
            p.shared.regs.lock().shift = [0x00, 0x00];
            p.pad().set(0, buttons::A);
            p.shared.write_strobe(1, raise);
            p.shared.write_strobe(0, raise + 1);
            assert_eq!(
                p.shared.regs.lock().shift[0] != 0,
                expected,
                "raised on cycle {raise}, which is a {}",
                if is_get(raise, 0) { "get" } else { "put" }
            );
        }
    }

    #[test]
    fn a_strobe_held_across_more_than_one_cycle_always_reaches_the_pads() {
        let p = NesPorts::with_pad_phase(Arc::new(Pad::new()), String::from("t2"), 0);
        p.shared.regs.lock().shift = [0x00, 0x00];
        p.pad().set(0, buttons::A);
        // Either phase: two consecutive cycles contain a put whichever it is.
        p.shared.write_strobe(1, 9);
        p.shared.write_strobe(0, 11);
        assert_ne!(p.shared.regs.lock().shift[0], 0);
    }
}