MOS6526.java

/**
 * CIA timer to produce interrupts ------------------------------- begin                : Wed Jun 7 2000 copyright : (C)
 * 2000 by Simon White email                : s_a_white@email.com
 * <p>
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either version 2 of the License or (at your option) any later
 * version.
 *
 * @author Ken Händel
 *
 */
package libsidplay.components.mos6526;

import libsidplay.common.CIAChipModel;
import libsidplay.common.Event;
import libsidplay.common.Event.Phase;
import libsidplay.common.EventScheduler;
import libsidplay.components.pla.Bank;

import java.util.Arrays;

/**
 * This class is heavily based on the ciacore/ciatimer source code from VICE. The CIA state machine is lifted as-is. Big
 * thanks to the VICE project!
 *
 * @author Antti Lankila
 */
public abstract class MOS6526 extends Bank {

    /**
     * Serial CNT pipeline and direction-change interrupt behaviour.
     * Adapted from libsidplayfp SerialPort (Leandro Nini / VICE Project),
     * revision 72fee4871ae19987533f35e0f7719ae054d04282, GPL-2.0-or-later.
     * This models the normal CIA serial behaviour, not the 4485-specific variant.
     */
    private final class SerialPort extends Event {
        /**
         * Number of CNT transitions remaining for the current byte.
         */
        private int count;
        private boolean loaded;
        private boolean pending;
        private int cnt;
        /**
         * Fast serial transmit/receive shift registers and the number of received bits.
         */
        private int outputShift, inputShift, inputBits;
        /**
         * Previous external CNT level, used to detect rising receive-clock edges.
         */
        private boolean inputCnt = true;
        private int cntHistory;
        private long lastSync;
        private boolean forceFinish;

        /**
         * Scheduled CNT transition time, in scheduler half-cycles.
         */
        private long flipCntTime;
        private final Event flipCntEvent = Event.of("CIA Serial CNT", event -> flipCnt());

        /**
         * An overlapping Timer A underflow keeps the CNT pipeline occupied,
         * but does not create another physical transition.
         */
        private final Event flipBusyEvent = Event.of("CIA Serial CNT busy", event -> { });

        /**
         * SDR writes reach the internal serial logic one cycle later.
         */
        private final Event startSdrEvent = Event.of("CIA Serial SDR load", event -> {
            if (loaded) {
                pending = true;
            } else {
                loaded = true;
            }
        });

        private SerialPort() {
            super("CIA Serial Port interrupt");
        }

        @Override
        public void event() {
            interruptSource.trigger(INTERRUPT_SP);
        }

        private void reset() {
            context.cancel(this);
            context.cancel(flipCntEvent);
            context.cancel(flipBusyEvent);
            context.cancel(startSdrEvent);
            count = 0;
            outputShift = inputShift = inputBits = 0;
            inputCnt = true;
            loaded = false;
            pending = false;
            cnt = 1;
            cntHistory = 0;
            forceFinish = false;
            flipCntTime = 0;
            lastSync = context.getTime(Phase.PHI1);
        }

        private void startSdr() {
            context.schedule(startSdrEvent, 1);
        }

        /**
         * Advance the eight-bit CNT history without an idle per-cycle event.
         */
        private void syncCntHistory() {
            final long now = context.getTime(Phase.PHI1);
            final long elapsed = now - lastSync;
            lastSync = now;
            if (elapsed >= 8) {
                cntHistory = cnt == 0 ? 0 : 0xff;
            } else if (elapsed > 0) {
                final int shift = (int) elapsed;
                cntHistory = ((cntHistory << shift) | (cnt * ((1 << shift) - 1))) & 0xff;
            }
        }

        /**
         * PHI1 and PHI2 times together recover the scheduler's half-cycle clock.
         */
        private long halfCycleTime() {
            return context.getTime(Phase.PHI1) + context.getTime(Phase.PHI2);
        }

        private void scheduleInterrupt() {
            context.cancel(this);
            context.schedule(this, 2);
        }

        private void handle() {
            if (loaded && count == 0) {
                count = 16;
                outputShift = regs[SDR] & 255;
            }
            if (count == 0) {
                return;
            }
            if (context.isPending(flipBusyEvent) || context.isPending(flipCntEvent)) {
                context.cancel(flipBusyEvent);
                context.schedule(flipBusyEvent, 2);
            } else {
                flipCntTime = halfCycleTime() + 4;
                context.schedule(flipCntEvent, 2);
            }
        }

        private void flipCnt() {
            if (count == 0) {
                return;
            }
            syncCntHistory();
            cnt ^= 1;
            if (cnt == 0) {
                driveSerialBit((outputShift & 0x80) != 0);
                outputShift = (outputShift << 1) & 255;
            } else {
                serialClockHigh();
            }
            if (--count == 1) {
                scheduleInterrupt();
                loaded = pending;
                pending = false;
            }
        }

        private void switchSerialDirection(final boolean input) {
            syncCntHistory();
            if (count > 1 && count < 15 || count == 15 && (cntHistory & 0x04) == 0) {
                scheduleInterrupt();
            }
            if (input) {
                forceFinish = (cntHistory & 0x06) != 0x06;
                if (!forceFinish && count != 2 && context.isPending(flipCntEvent)
                        && flipCntTime - halfCycleTime() == 1) {
                    forceFinish = true;
                }
            } else if (forceFinish) {
                scheduleInterrupt();
                forceFinish = false;
            }

            if (input && (!serialOutput || cnt == 0)) {
                serialOutput = true;
                serialPins(true, true);
            }
            cnt = 1;
            cntHistory |= 1;
            context.cancel(flipCntEvent);
            context.cancel(flipBusyEvent);
            count = 0;
            outputShift = inputShift = inputBits = 0;
            inputCnt = true;
            loaded = false;
            pending = false;
            // A direction change is not a chip reset: preserve the delayed
            // interrupt and an SDR write already in flight.
        }
    }

    /**
     * These are the credits.
     */
    private static final String CREDITS = "MOS6526 (CIA) Emulation:\n"
            + "\tCopyright (©) 2001-2004 Simon White <sidplay2@yahoo.com>\n" + "\tCopyright (©) 2009 VICE Project\n"
            + "\tCopyright (©) 2009-2010 Antti S. Lankila\n";

    /**
     * Interrupt flag: no interrupt.
     */
    private static final byte INTERRUPT_NONE = 0;

    /**
     * Interrupt flag: underflow Timer A.
     */
    private static final byte INTERRUPT_UNDERFLOW_A = 1 << 0;

    /**
     * Interrupt flag: underflow Timer B.
     */
    private static final byte INTERRUPT_UNDERFLOW_B = 1 << 1;

    /**
     * Interrupt flag: alarm clock.
     */
    private static final byte INTERRUPT_ALARM = 1 << 2;

    /**
     * Interrupt flag: serial port.
     */
    private static final byte INTERRUPT_SP = 1 << 3;

    /**
     * Interrupt flag: external flag.
     */
    private static final byte INTERRUPT_FLAG = 1 << 4;

    //
    // CIA registers:
    //

    public static final int PRA = 0;

    public static final int PRB = 1;

    protected static final int DDRA = 2;

    protected static final int DDRB = 3;

    private static final int TAL = 4;

    private static final int TAH = 5;

    private static final int TBL = 6;

    private static final int TBH = 7;

    private static final int TOD_TEN = 8;

    private static final int TOD_SEC = 9;

    private static final int TOD_MIN = 10;

    private static final int TOD_HR = 11;

    private static final int SDR = 12;

    public static final int ICR = 13;

    protected static final int CRA = 14;

    protected static final int CRB = 15;

    protected abstract class InterruptSource extends Event {
        protected static final byte INTERRUPT_REQUEST = (byte) (1 << 7);

        /**
         * Clock when ICR was read last.
         */
        private long lastClear;

        /**
         * Interrupt control register.
         */
        protected byte icr;

        /**
         * Interrupt data register.
         */
        protected byte idr;

        /**
         * Delayed interrupt data register.
         */
        protected byte idrTemp;

        /**
         * Have we already scheduled CIA -> CPU interrupt transition?
         */
        private boolean scheduled;

        /**
         * Is the IRQ/NMI pin currently asserted?
         */
        private boolean asserted;

        private final Event updateIdrEvent = new Event("CIA update ICR") {
            @Override
            public void event() {
                idr = idrTemp;

                if (ack0()) {
                    context.schedule(this, 1, Phase.PHI1);
                    idrTemp = 0;
                }
            }
        };

        private final Event setIrqEvent = new Event("CIA set IRQ") {
            @Override
            public void event() {
                setInterruptRequest();
                setIrq();
            }
        };

        private final Event clearIrqEvent = new Event("CIA clear IRQ") {
            @Override
            public void event() {
                if (asserted) {
                    interrupt(false);
                    asserted = false;
                }
            }
        };

        public InterruptSource() {
            super("CIA Interrupt");
        }

        private boolean interruptTriggered() {
            return (idr & INTERRUPT_REQUEST) != 0;
        }

        private boolean interruptMasked(final byte interruptMask) {
            return ((interruptMask != INTERRUPT_NONE ? interruptMask : idr) & icr) != 0;
        }

        /**
         * Was ICR acknowledged during the previous cycle?
         */
        protected final boolean ack0() {
            return context.getTime(Phase.PHI2) == lastClear + 1;
        }

        /**
         * Was ICR acknowledged two cycles ago?
         */
        private boolean ackMinus1() {
            return context.getTime(Phase.PHI2) == lastClear + 2;
        }

        /**
         * Set the ICR master interrupt bit in both visible and delayed state.
         */
        protected final void setInterruptRequest() {
            idr |= INTERRUPT_REQUEST;
            idrTemp |= INTERRUPT_REQUEST;
        }

        /**
         * Is the delayed IRQ assertion used by the 6526A still pending?
         */
        protected final boolean delayedIrqPending() {
            return context.isPending(setIrqEvent);
        }

        /**
         * @return true for MOS6526A / 8521 ("new CIA")
         */
        protected abstract boolean isNewCIA();

        protected abstract void triggerInterrupt();

        /**
         * Record an interrupt source and check whether it is enabled.
         */
        protected final boolean isTriggered(final byte interruptMask) {
            idr |= interruptMask;
            idrTemp |= interruptMask;
            return interruptMasked(interruptMask);
        }

        protected abstract void trigger(byte interruptMask);

        protected final void schedule(final int delay) {
            if (!scheduled) {
                context.schedule(this, delay, Phase.PHI1);
                scheduled = true;
            }
        }

        protected final void scheduleIrq() {
            if (!context.isPending(setIrqEvent)) {
                context.schedule(setIrqEvent, 1, Phase.PHI1);
            }
        }

        private void setIrq() {
            if (!ack0() && !asserted) {
                interrupt(true);
                asserted = true;
            }
        }

        /**
         * Clear interrupt state.
         *
         * @return old interrupt state
         */
        protected byte clear() {
            lastClear = context.getTime(Phase.PHI2);

            /*
             * Reading ICR acknowledges a pending external assertion.
             */
            context.cancel(setIrqEvent);
            context.schedule(clearIrqEvent, 0, Phase.PHI1);

            if (!context.isPending(updateIdrEvent)) {
                context.schedule(updateIdrEvent, 1, Phase.PHI1);
                idrTemp = 0;
            }

            return idr;
        }

        /**
         * Clear pending interrupts but do not signal to CPU we lost them. It is assumed that all components get reset()
         * calls in a synchronous manner.
         */
        public void reset() {
            lastClear = 0;
            icr = idr = idrTemp = 0;

            context.cancel(this);
            context.cancel(updateIdrEvent);
            context.cancel(setIrqEvent);
            context.cancel(clearIrqEvent);

            scheduled = false;
            asserted = false;
        }

        /**
         * Set/clear interrupt control mask bits.
         *
         * @param interruptMask control mask bits
         */
        public void set(final byte interruptMask) {
            if ((interruptMask & INTERRUPT_REQUEST) != 0) {
                icr |= interruptMask & ~INTERRUPT_REQUEST;
            } else {
                icr &= ~interruptMask;
            }

            if (interruptMasked(INTERRUPT_NONE)) {
                if (!interruptTriggered()) {
                    /*
                     * Enabling an already-pending source raises IR later than
                     * a source that becomes pending normally.
                     *
                     * 6526A: one cycle, except immediately after an ICR read.
                     * 6526 : two cycles.
                     */
                    if (!isNewCIA() || !ack0()) {
                        trigger(INTERRUPT_NONE);
                    }
                }
            } else if (!isNewCIA() && ackMinus1() && scheduled) {
                /*
                 * Old-6526 mask-cancel race: a mask write can cancel an IRQ
                 * which is still in the delayed-assert pipeline when ICR was
                 * read two cycles earlier.
                 */
                context.cancel(this);
                scheduled = false;
            }
        }

        /**
         * Signal interrupt to CPU.
         */
        @Override
        public final void event() {
            if (!interruptTriggered()) {
                triggerInterrupt();
                setIrq();
            }
            scheduled = false;
        }
    }

    /**
     * InterruptSource that acts like new CIA
     *
     * @author Antti Lankila
     */
    protected final class InterruptSource6526A extends InterruptSource {
        @Override
        protected boolean isNewCIA() {
            return true;
        }

        @Override
        protected void triggerInterrupt() {
            /*
             * Normally the 6526A sets D7 in the same cycle as the source flag.
             * If ICR was read in the previous cycle, both D7 and the external
             * IRQ/NMI assertion are delayed by one cycle.
             */
            if (ack0()) {
                scheduleIrq();
            } else {
                setInterruptRequest();
            }
        }

        @Override
        protected void trigger(final byte interruptMask) {
            if (isTriggered(interruptMask)) {
                schedule(0);
            }
        }

        @Override
        protected byte clear() {
            /*
             * A 6526A ICR read one cycle before a delayed IRQ assertion sees
             * D7 already set, and cancels the pending external assertion.
             */
            if (delayedIrqPending() && (idr & 0x1f) != 0) {
                setInterruptRequest();
            }
            return super.clear();
        }
    }

    /**
     * InterruptSource that acts like old CIA
     *
     * @author Antti Lankila
     */
    protected final class InterruptSource6526 extends InterruptSource {
        /**
         * Old-6526 Timer-B bug marker. The source remains pending internally, but the next ICR read must hide and clear
         * Timer B.
         */
        private boolean timerBBug;

        @Override
        protected boolean isNewCIA() {
            return false;
        }

        @Override
        protected void triggerInterrupt() {
            idr |= INTERRUPT_REQUEST;
        }

        @Override
        protected void trigger(final byte interruptMask) {
            if (isTriggered(interruptMask)) {
                schedule(1);
            }

            /*
             * Timer B underflow one cycle after an ICR read raises the IRQ
             * normally, but the next ICR read loses the Timer-B source bit.
             * Keep the source pending until that read; clearing it here is too
             * early and changes intervening mask-write behaviour.
             */
            if (interruptMask == INTERRUPT_UNDERFLOW_B) {
                timerBBug = ack0();
            }
        }

        @Override
        protected byte clear() {
            if (timerBBug) {
                idr &= ~INTERRUPT_UNDERFLOW_B;
                idrTemp &= ~INTERRUPT_UNDERFLOW_B;
                timerBBug = false;
            }

            final byte oldIdr = super.clear();
            idr &= INTERRUPT_REQUEST;
            return oldIdr;
        }

        @Override
        public void reset() {
            super.reset();
            timerBBug = false;
        }
    }

    /**
     * CIA interrupt controller.
     */
    protected final InterruptSource interruptSource;

    /**
     * This class implements a Timer A or B of a MOS6526 chip.
     *
     * @author Ken Händel
     *
     */
    protected abstract class Timer extends Event {

        protected static final int CIAT_CR_START = 0x01;
        protected static final int CIAT_STEP = 0x04;
        protected static final int CIAT_CR_ONESHOT = 0x08;
        protected static final int CIAT_CR_FLOAD = 0x10;
        protected static final int CIAT_PHI2IN = 0x20;
        protected static final int CIAT_CR_MASK = CIAT_CR_START | CIAT_CR_ONESHOT | CIAT_CR_FLOAD | CIAT_PHI2IN;

        protected static final int CIAT_COUNT2 = 0x100;
        protected static final int CIAT_COUNT3 = 0x200;

        protected static final int CIAT_ONESHOT0 = 0x08 << 8;
        protected static final int CIAT_ONESHOT = 0x08 << 16;
        protected static final int CIAT_LOAD1 = 0x10 << 8;
        protected static final int CIAT_LOAD = 0x10 << 16;

        protected static final int CIAT_OUT = 0x80000000;

        /**
         * CRA/CRB control register / state.
         */
        protected int state;

        /**
         * Copy of regs[CRA/B]
         */
        protected byte lastControlValue;

        /**
         * Current timer value.
         */
        protected short timer;
        /**
         * Timer start value (Latch).
         */
        protected short latch;
        /**
         * PB6/PB7 Flipflop to signal underflows.
         */
        protected boolean pbToggle;

        /**
         * This is a tri-state:
         * <p>
         * when -1: cia is completely stopped when 0: cia 1-clock events are ticking. otherwise: cycleskipevent is
         * ticking, and the value is the first phi1 clock of skipping.
         */
        protected long ciaEventPauseTime;

        /**
         * Create a new timer.
         *
         * @param eventName The name of the new timer.
         */
        public Timer(final String eventName) {
            super(eventName);
        }

        /**
         * Set CRA/CRB control register.
         *
         * @param cr Control register value
         */
        public final void setControlRegister(final byte cr) {
            state &= ~CIAT_CR_MASK;
            state |= cr & CIAT_CR_MASK ^ CIAT_PHI2IN;
            lastControlValue = cr;
        }

        /**
         * Get current timer value.
         *
         * @return current timer value
         */
        public final int getTimer() {
            return timer;
        }

        /**
         * Get PB6/PB7 Flipflop state.
         *
         * @return PB6/PB7 flipflop state
         */
        public final boolean getPbToggle() {
            return pbToggle;
        }

        /**
         * Set PB6/PB7 Flipflop state.
         *
         * @param state PB6/PB7 flipflop state
         */
        public final void setPbToggle(final boolean state) {
            pbToggle = state;
        }

        /**
         * Set high byte of Timer start value (Latch).
         *
         * @param high high byte of latch
         */
        public final void setLatchHigh(final byte high) {
            latch = (short) (latch & 0xff | (high & 0xff) << 8);
            if ((state & CIAT_LOAD) != 0 || (state & CIAT_CR_START) == 0) {
                timer = latch;
            }
        }

        /**
         * Set low byte of Timer start value (Latch).
         *
         * @param low low byte of latch
         */
        public final void setLatchLow(final byte low) {
            latch = (short) (latch & 0xff00 | low & 0xff);
            if ((state & CIAT_LOAD) != 0) {
                timer = (short) (timer & 0xff00 | low & 0xff);
            }
        }

        /**
         * Reset timer.
         */
        public final void reset() {
            context.cancel(this);
            timer = latch = (short) 0xffff;
            pbToggle = false;
            state = 0;
            ciaEventPauseTime = 0;
            context.schedule(this, 1, Phase.PHI1);
        }

        /**
         * Perform cycle skipping manually.
         * <p>
         * Clocks the CIA up to the state it should be in and stops all events.
         */
        public final void syncWithCpu() {
            if (ciaEventPauseTime > 0) {
                context.cancel(cycleSkippingEvent);
                final long elapsed = context.getTime(Phase.PHI2) - ciaEventPauseTime;
                /*
                 * It's possible for CIA to determine that it wants to go to sleep starting from
                 * the next cycle and then have its plans aborted by CPU. Thus, we must avoid
                 * modifying the CIA state if the first sleep clock was still in the future.
                 */
                if (elapsed >= 0) {
                    timer -= elapsed;
                    clock();
                }
            }
            if (ciaEventPauseTime == 0) {
                context.cancel(this);
            }
            ciaEventPauseTime = -1;
        }

        /**
         * Counterpart of syncWithCpu(), starts the event ticking if it is necessary. No clock() call or anything such
         * is permissible here!
         */
        public final void wakeUpAfterSyncWithCpu() {
            ciaEventPauseTime = 0;
            context.schedule(this, 0, Phase.PHI1);
        }

        /**
         * Timer ticking event.
         */
        @Override
        public void event() {
            clock();
            reschedule();
        }

        /**
         * Perform scheduled cycle skipping, and resume.
         */
        private final Event cycleSkippingEvent = Event.of("Skip CIA clock decrement cycles", event -> {
            final long elapsed = context.getTime(Phase.PHI1) - ciaEventPauseTime;
            ciaEventPauseTime = 0;
            timer -= elapsed;
            Timer.this.event();
        });

        /**
         * Execute one CIA state transition.
         */
        public void clock() {
            if (timer != 0 && (state & CIAT_COUNT3) != 0) {
                timer--;
            }

            /* ciatimer.c block start */
            int adj = state & (CIAT_CR_START | CIAT_CR_ONESHOT | CIAT_PHI2IN);
            if ((state & (CIAT_CR_START | CIAT_PHI2IN)) == (CIAT_CR_START | CIAT_PHI2IN)) {
                adj |= CIAT_COUNT2;
            }
            if ((state & CIAT_COUNT2) != 0 || (state & (CIAT_STEP | CIAT_CR_START)) == (CIAT_STEP | CIAT_CR_START)) {
                adj |= CIAT_COUNT3;
            }
            /*
             * CR_FLOAD -> LOAD1, CR_ONESHOT -> ONESHOT0, LOAD1 -> LOAD, ONESHOT0 -> ONESHOT
             */
            adj |= (state & (CIAT_CR_FLOAD | CIAT_CR_ONESHOT | CIAT_LOAD1 | CIAT_ONESHOT0)) << 8;
            state = adj;
            /* ciatimer.c block end */

            if (timer == 0 && (state & CIAT_COUNT3) != 0) {
                state |= CIAT_LOAD | CIAT_OUT;

                if ((state & (CIAT_ONESHOT | CIAT_ONESHOT0)) != 0) {
                    state &= ~(CIAT_CR_START | CIAT_COUNT2);
                }

                // By setting bits 2&3 of the control register,
                // PB6/PB7 will be toggled between high and low at each
                // underflow.
                final boolean toggle = (lastControlValue & 0x06) == 6;
                pbToggle = toggle && !pbToggle;

                // Implementation of the serial port
                serialPort();

                // Timer A signals underflow handling: IRQ/B-count
                underFlow();
            }

            if ((state & CIAT_LOAD) != 0) {
                timer = latch;
                state &= ~CIAT_COUNT3;
            }
        }

        /**
         * Reschedule CIA event at the earliest interesting time. If the CIA timer is stopped or is programmed to just
         * count down, the events are paused.
         */
        private void reschedule() {
            /*
             * There are only two subcases to consider.
             *
             * - are we counting, and if so, are we going to continue counting? - have we
             * stopped, and are there no conditions to force a new beginning?
             *
             * Additionally, there are many flags that are present only in a passing
             * manner, but which we need to let cycle through the CIA state machine.
             */
            final int unwanted = CIAT_OUT | CIAT_CR_FLOAD | CIAT_LOAD1 | CIAT_LOAD;
            if ((state & unwanted) != 0) {
                context.schedule(this, 1);
                return;
            }

            if ((state & CIAT_COUNT3) != 0) {
                /*
                 * Test the conditions that keep COUNT2 and thus COUNT3 alive and also ensure
                 * that all of them are set indicating steady state operation.
                 */

                final int wanted = CIAT_CR_START | CIAT_PHI2IN | CIAT_COUNT2 | CIAT_COUNT3;
                if ((timer & 0xffff) > 2 && (state & wanted) == wanted) {
                    /*
                     * we executed this cycle; therefore, the pauseTime is +1. If we are called to
                     * execute on the very next clock, we need to get 0 because there's another
                     * timer-- in it.
                     */
                    ciaEventPauseTime = context.getTime(Phase.PHI1) + 1;
                    /* execute event slightly before the next underflow. */
                    context.schedule(cycleSkippingEvent, timer - 1 & 0xffff);
                    return;
                }

                /* play safe, keep on ticking. */
                context.schedule(this, 1);
                return;

            } else {
                /*
                 * Test conditions that result in CIA activity in next clocks. If none, stop.
                 */
                final int unwanted1 = CIAT_CR_START | CIAT_PHI2IN;
                final int unwanted2 = CIAT_CR_START | CIAT_STEP;

                if ((state & unwanted1) == unwanted1 || (state & unwanted2) == unwanted2) {
                    context.schedule(this, 1);
                    return;
                }

                ciaEventPauseTime = -1;
                return;
            }
        }

        //
        // Abstract methods
        //

        /**
         * Handle the serial port.
         */
        public abstract void serialPort();

        /**
         * Signal timer underflow.
         */
        public abstract void underFlow();
    }

    /**
     * This is the timer A of this CIA.
     *
     * @author Ken Händel
     *
     */
    private final class TimerA extends Timer {
        /**
         * Create a timer A.
         */
        public TimerA() {
            super("CIA A");
        }

        @Override
        public void serialPort() {
            if ((regs[CRA] & 0x40) != 0) {
                serialPort.handle();
            }
        }

        /**
         * This event exists solely to break the ambiguity of what scheduling on top of PHI1 causes, because there is no
         * ordering between events on the same phase. Thus, it is scheduled in PHI2 to ensure the b.event() is run once
         * before the value changes.
         * <UL>
         * <LI>PHI1 a.event() (which calls underFlow())
         * <LI>PHI1 b.event()
         * <LI>PHI2 bTick.event()
         * <LI>PHI1 a.event()
         * <LI>PHI1 b.event()
         * </UL>
         */
        private final Event bTick = Event.of("CIA B counts A", event -> {
            /* we pretend that we are CPU doing a writing to ctrl register */
            b.syncWithCpu();
            b.state |= Timer.CIAT_STEP;
            b.wakeUpAfterSyncWithCpu();
        });

        /**
         * Signal underflows of Timer A to Timer B.
         */
        @Override
        public void underFlow() {
            interruptSource.trigger(INTERRUPT_UNDERFLOW_A);
            if ((regs[CRB] & 0x41) == 0x41) {
                if ((b.state & Timer.CIAT_CR_START) != 0
                        && ((regs[CRB] & 0x20) == 0 || cntInput)) {
                    context.schedule(bTick, 0, Phase.PHI2);
                }
            }
        }
    }

    /**
     * This is the timer B of this CIA.
     *
     * @author Ken Händel
     *
     */
    private final class TimerB extends Timer {
        /**
         * Create timer B.
         */
        public TimerB() {
            super("CIA B");
        }

        @Override
        public void serialPort() {
            // nothing to do
        }

        @Override
        public void underFlow() {
            interruptSource.trigger(INTERRUPT_UNDERFLOW_B);
        }
    }

    /**
     * Timers A and B.
     */
    protected final Timer a, b;

    /**
     * These are all CIA registers.
     */
    protected byte[] regs = new byte[0x10];

    //
    // Serial Data Registers
    //

    private final SerialPort serialPort;
    /**
     * Event context.
     */
    protected final EventScheduler context;

    //
    // Time Of Day
    //

    protected boolean m_todlatched;

    protected boolean m_todstopped;

    protected byte[] m_todclock = new byte[4], m_todalarm = new byte[4], m_todlatch = new byte[4];

    /**
     * CPU clocks per second.
     */
    private long m_todTicksPerSecond = 985248;

    /**
     * External TOD input frequency, normally 50 Hz PAL / 60 Hz NTSC.
     */
    private int m_todPowerFrequency = 50;

    /**
     * Accumulated clocks within the current simulated mains second.
     */
    private long m_todPowerTicks;

    /**
     * Number of external power ticks within the current second.
     */
    private int m_todPowerTickCounter;

    /**
     * CIA internal 50/60 Hz -> 10 Hz divider state.
     * <p>
     * The real CIA divider has six states.
     */
    private int m_todTickCounter;

    /**
     * Deterministic PCG state used for TOD mains jitter.
     * <p>
     * A fixed seed gives us realistic jitter without making regression tests nondeterministic.
     */
    private long m_todRandomState = 0x6526C64D12345678L;

    protected final Event m_todEvent = new Event("CIA Time of Day") {
        //
        // TOD implementation taken from Vice
        //

        @Override
        public void event() {
            /*
             * Schedule the next external 50/60 Hz TOD input pulse.
             * The CIA's internal six-state divider below derives 10 Hz
             * from those individual pulses.
             */
            context.schedule(this, getNextTodPowerTick());
            boolean update = false;

            if (!m_todstopped) {
                /*
                 * The CIA divider has six states.
                 *
                 * With CRA bit 7 set (50 Hz), update after 5 power ticks.
                 * With CRA bit 7 clear (60 Hz), update after 6 power ticks.
                 *
                 * VICE models this as states 0..5 with comparison against 4/5.
                 */
                final int match =
                        (regs[CRA] & 0x80) != 0 ? 4 : 5;

                update = m_todTickCounter == match;

                if (update) {
                    m_todTickCounter = 0;
                } else if (++m_todTickCounter > 5) {
                    m_todTickCounter = 0;
                }
            }

            if (update) {
                int ts = m_todclock[0] & 0x0f;

                int sl = m_todclock[1] & 0x0f;
                int sh = m_todclock[1] >>> 4 & 0x07;

                int ml = m_todclock[2] & 0x0f;
                int mh = m_todclock[2] >>> 4 & 0x07;

                int hl = m_todclock[3] & 0x0f;
                int hh = m_todclock[3] >>> 4 & 0x01;

                int pm = m_todclock[3] & 0x80;

                /*
                 * Tenths.
                 *
                 * Notice that only exactly 0x0a causes the decimal carry.
                 * Invalid BCD values 0x0a..0x0f therefore continue through
                 * the nibble instead of being interpreted as decimal numbers.
                 */
                ts = ts + 1 & 0x0f;

                if (ts == 10) {
                    ts = 0;

                    // Seconds, low digit
                    sl = sl + 1 & 0x0f;

                    if (sl == 10) {
                        sl = 0;

                        // Seconds, high digit
                        sh = sh + 1 & 0x07;

                        if (sh == 6) {
                            sh = 0;

                            // Minutes, low digit
                            ml = ml + 1 & 0x0f;

                            if (ml == 10) {
                                ml = 0;

                                // Minutes, high digit
                                mh = mh + 1 & 0x07;

                                if (mh == 6) {
                                    mh = 0;

                                    /*
                                     * Hours.
                                     *
                                     * 09 -> 10
                                     * 12 -> 01
                                     */
                                    if (hh == 1 && hl == 2
                                            || hh == 0 && hl == 9) {
                                        hl = hh;
                                        hh ^= 1;
                                    } else {
                                        hl = hl + 1 & 0x0f;

                                        /*
                                         * Toggle AM/PM when entering 12.
                                         */
                                        if (hh == 1 && hl == 2) {
                                            pm ^= 0x80;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                m_todclock[0] = (byte) ts;
                m_todclock[1] = (byte) (sl | sh << 4);
                m_todclock[2] = (byte) (ml | mh << 4);
                m_todclock[3] = (byte) (hl | hh << 4 | pm);

                if (Arrays.equals(m_todalarm, m_todclock)) {
                    interruptSource.trigger(INTERRUPT_ALARM);
                }
            }
        }
    };

    /**
     * Create a new CIA.
     *
     * @param ctx the event context
     */
    protected MOS6526(final EventScheduler ctx, final CIAChipModel model) {
        this.context = ctx;
        this.interruptSource =
                model == CIAChipModel.MOS6526A
                        ? new InterruptSource6526A()
                        : new InterruptSource6526();

        serialPort = new SerialPort();

        a = new TimerA();
        b = new TimerB();

        reset();
    }

    //
    // Environment Interface
    //

    /**
     * Signal interrupt.
     *
     * @param state interrupt state
     */
    public abstract void interrupt(boolean state);

    /**
     * Current SP output level, held through the high phase of CNT.
     */
    private boolean serialOutput = true;
    /**
     * Drive external fast serial pins. The unmodified C64 has no IEC fast serial connection.
     *
     * @param sp  serial data level, true for high
     * @param cnt serial clock level, true for high
     */
    protected void serialPins(boolean sp, boolean cnt) {
    }

    /**
     * Raise CNT while retaining the current SP output bit.
     */
    private void serialClockHigh() {
        serialPins(serialOutput, true);
    }

    /**
     * Present the next SP bit with CNT low.
     *
     * @param bit serial output bit
     */
    private void driveSerialBit(boolean bit) {
        serialOutput = bit;
        serialPins(bit, false);
    }

    /**
     * Sample external SP/CNT pins. In receive mode, each rising CNT edge shifts one SP bit into SDR.
     *
     * @param sp  serial data level, true for high
     * @param cnt serial clock level, true for high
     */
    public final void setSerialInput(boolean sp, boolean cnt) {
        if (!cntInput && cnt) {
            // Latch the source selection at the edge, including while the timers are asleep.
            cntStepA |= (regs[CRA] & 0x21) == 0x21;
            cntStepB |= (regs[CRB] & 0x61) == 0x21;
            if ((cntStepA || cntStepB) && !context.isPending(cntTimerEvent)) {
                context.schedule(cntTimerEvent, 0, Phase.PHI2);
            }
        }
        cntInput = cnt;
        if (!serialPort.inputCnt && cnt && (regs[CRA] & 0x40) == 0) {
            serialPort.inputShift = ((serialPort.inputShift << 1) | (sp ? 1 : 0)) & 255;
            if (++serialPort.inputBits == 8) {
                regs[SDR] = (byte) serialPort.inputShift;
                serialPort.inputBits = 0;
                interruptSource.trigger(INTERRUPT_SP);
            }
        }
        serialPort.inputCnt = cnt;
    }

    private boolean cntInput = true;
    private boolean cntStepA, cntStepB;

    /** External CNT clocks enter the same timer pipeline as a cascaded underflow. */
    private final Event cntTimerEvent = Event.of("CIA external CNT timer clock", event -> clockCntTimers());

    private void clockCntTimers() {
        if (cntStepA) stepTimer(a);
        if (cntStepB) stepTimer(b);
        cntStepA = cntStepB = false;
    }

    private void stepTimer(Timer timer) {
        timer.syncWithCpu();
        timer.state |= Timer.CIAT_STEP;
        timer.wakeUpAfterSyncWithCpu();
    }

    public abstract void pulse();

    public abstract byte readPRA();

    public abstract byte readPRB();

    public abstract void writePRA(final byte data, final boolean ddrChange);

    public abstract void writePRB(byte data);

    /**
     * External interrupt control.
     *
     * @param flag Interrupt flag
     */
    public void setFlag(final boolean flag) {
        if (flag) {
            interruptSource.trigger(INTERRUPT_FLAG);
        }
    }

    //
    // Component Standard Calls
    //

    /**
     * Reset CIA.
     */
    public void reset() {
        final boolean releaseSerialOutput = (regs[CRA] & 0x40) != 0
                && (!serialOutput || serialPort.cnt == 0);
        context.cancel(cntTimerEvent);
        context.cancel(((TimerA) a).bTick);
        cntInput = true;
        cntStepA = cntStepB = false;
        serialOutput = true;
        a.reset();
        b.reset();
        serialPort.reset();
        interruptSource.reset();
        Arrays.fill(regs, (byte) 0);

        // Reset tod
        Arrays.fill(m_todclock, (byte) 0);
        Arrays.fill(m_todalarm, (byte) 0);
        Arrays.fill(m_todlatch, (byte) 0);

        m_todlatched = false;
        m_todstopped = true;
        m_todclock[TOD_HR - TOD_TEN] = 1; // the most common value
        m_todPowerTicks = 0;
        m_todPowerTickCounter = 0;
        m_todTickCounter = 0;

        context.schedule(m_todEvent, 0, Phase.PHI1);
        if (releaseSerialOutput) {
            serialPins(true, true);
        }
    }

    /**
     * Read CIA register.
     *
     * @param addr register address to read (lowest 4 bits)
     */
    @Override
    public final byte read(int addr) {
        addr &= 0xf;

        a.syncWithCpu();
        a.wakeUpAfterSyncWithCpu();
        b.syncWithCpu();
        b.wakeUpAfterSyncWithCpu();

        switch (addr) {
            case PRA: // Simulate a serial port
                // 0 = input 0xff = output
                return (byte) (readPRA() & (regs[PRA] | ~regs[DDRA]));
            case PRB:
                byte data = (byte) (readPRB() & (regs[PRB] | ~regs[DDRB]));
                pulse();
                // Timers can appear on the port
                if ((regs[CRA] & 0x02) != 0) {
                    data &= 0xbf;
                    if ((regs[CRA] & 0x04) != 0 ? a.getPbToggle() : (a.state & Timer.CIAT_OUT) != 0) {
                        data |= 0x40;
                    }
                }
                if ((regs[CRB] & 0x02) != 0) {
                    data &= 0x7f;
                    if ((regs[CRB] & 0x04) != 0 ? b.getPbToggle() : (b.state & Timer.CIAT_OUT) != 0) {
                        data |= 0x80;
                    }
                }
                return data;
            case TAL:
                return (byte) (a.getTimer() & 0xff);
            case TAH:
                return (byte) (a.getTimer() >> 8);
            case TBL:
                return (byte) (b.getTimer() & 0xff);
            case TBH:
                return (byte) (b.getTimer() >> 8);

            // TOD implementation taken from Vice
            // TOD clock is latched by reading Hours and released
            // upon reading Tenths of Seconds. The counter itself
            // keeps ticking all the time.
            // Also note that this latching is different from the input one.
            case TOD_TEN: // Time Of Day clock 1/10 s
            case TOD_SEC: // Time Of Day clock sec
            case TOD_MIN: // Time Of Day clock min
            case TOD_HR: // Time Of Day clock hour
                if (!m_todlatched) {
                    System.arraycopy(m_todclock, 0, m_todlatch, 0, 4);
                }
                if (addr == TOD_TEN) {
                    m_todlatched = false;
                }
                if (addr == TOD_HR) {
                    m_todlatched = true;
                }
                return m_todlatch[addr - TOD_TEN];

            case ICR:
                return interruptSource.clear();

            case CRA:
                return (byte) (regs[CRA] & 0xee | a.state & 1);
            case CRB:
                return (byte) (regs[CRB] & 0xee | b.state & 1);
            default:
                return regs[addr];
        }
    }

    /**
     * Write CIA register.
     *
     * @param addr register address to write (lowest 4 bits)
     * @param data value to write
     */
    @Override
    public final void write(int addr, byte data) {
        addr &= 0xf;

        a.syncWithCpu();
        b.syncWithCpu();

        byte oldData = regs[addr];

        /*
         * TOD registers do not store all eight written bits.
         *
         * Apply this before regs[] is updated so the register image and the
         * actual TOD/alarm values see the same value.
         */
        switch (addr) {
            case TOD_TEN:
                data &= 0x0f;
                break;

            case TOD_SEC:
            case TOD_MIN:
                data &= 0x7f;
                break;

            case TOD_HR:
                data &= 0x9f;

                /*
                 * Writing 12 to the TOD clock flips AM/PM.
                 * Do not do this when writing the alarm.
                 */
                if ((data & 0x1f) == 0x12
                        && (regs[CRB] & 0x80) == 0) {
                    data ^= 0x80;
                }
                break;

            default:
                break;
        }

        if (addr < TOD_TEN || addr > TOD_HR) {
            regs[addr] = data;
        }
        switch (addr) {
            case PRA:
                writePRA((byte) (regs[PRA] | ~regs[DDRA]), false);
                break;
            case DDRA:
                writePRA((byte) (regs[PRA] | ~regs[DDRA]), oldData != data);
                break;
            case PRB:
                pulse();
                // $FALL-THROUGH$
            case DDRB:
                writePRB((byte) (regs[PRB] | ~regs[DDRB]));
                break;
            case TAL:
                a.setLatchLow(data);
                break;
            case TBL:
                b.setLatchLow(data);
                break;
            case TAH:
                a.setLatchHigh(data);
                break;
            case TBH:
                b.setLatchHigh(data);
                break;
            case TOD_HR:
                //$FALL-THROUGH$

            case TOD_TEN:
            case TOD_SEC:
            case TOD_MIN: {
                final int todIndex = addr - TOD_TEN;
                final boolean changed;

                if ((regs[CRB] & 0x80) != 0) {
                    changed = m_todalarm[todIndex] != data;
                    m_todalarm[todIndex] = data;
                } else {
                    if (addr == TOD_TEN && m_todstopped) {
                        m_todTickCounter = 0;
                        m_todstopped = false;
                    }

                    if (addr == TOD_HR) {
                        m_todstopped = true;
                    }

                    changed = m_todclock[todIndex] != data;

                    if (changed) {
                        m_todclock[todIndex] = data;
                    }
                }

                if (changed && Arrays.equals(m_todalarm, m_todclock)) {
                    interruptSource.trigger(INTERRUPT_ALARM);
                }

                break;
            }
            case SDR:
                serialPort.startSdr();
                break;

            case ICR:
                interruptSource.set(data);
                break;

            case CRA:
            case CRB: {
                final Timer t = addr == CRA ? a : b;

                if (addr == CRA && ((data ^ oldData) & 0x40) != 0) {
                    serialPort.switchSerialDirection((data & 0x40) == 0);
                }

                final boolean start = (data & 1) != 0 && (oldData & 1) == 0;

                if (start) {
                    t.setPbToggle(true);
                }

                if (addr == CRB) {
                    t.setControlRegister((byte) (data | (data & 0x40) >> 1));
                } else {
                    t.setControlRegister(data);
                }
                break;
            }
            default:
                break;
        }

        a.wakeUpAfterSyncWithCpu();
        b.wakeUpAfterSyncWithCpu();
    }

    private long getNextTodPowerTick() {
        /*
         * Nominal number of CPU clocks per external 50/60 Hz tick.
         */
        long todTicks =
                m_todTicksPerSecond / m_todPowerFrequency;

        /*
         * Where we should ideally be within the current one-second window.
         */
        final long ideal =
                (long) m_todPowerTickCounter
                        * m_todTicksPerSecond
                        / m_todPowerFrequency;

        /*
         * VICE deliberately introduces a small amount of jitter while nudging
         * the accumulated timing back toward the ideal position.
         */
        if (m_todPowerTicks < ideal) {
            todTicks += nextTodJitter();
        } else if (m_todPowerTicks > ideal) {
            todTicks -= nextTodJitter();
        }

        m_todPowerTickCounter++;

        /*
         * Force every complete group of 50/60 ticks to equal exactly one
         * emulated second. Thus the jitter cannot cause long-term clock drift.
         */
        if (m_todPowerTickCounter >= m_todPowerFrequency) {
            todTicks =
                    m_todTicksPerSecond - m_todPowerTicks;

            m_todPowerTickCounter = 0;
            m_todPowerTicks = 0;
        } else {
            m_todPowerTicks += todTicks;
        }

        return todTicks;
    }

    /**
     * Get the credits.
     *
     * @return the credits
     */
    public static String credits() {
        return CREDITS;
    }

    /**
     * Set a day-of-time event occurrence of rate.
     */
    public final void setDayOfTimeRate(
            final double cpuFrequency,
            final int powerFrequency) {

        m_todTicksPerSecond = Math.round(cpuFrequency);
        m_todPowerFrequency = powerFrequency;
    }

    private int nextTodJitter() {
        final long oldState = m_todRandomState;

        /*
         * PCG-XSH-RR 32/64, same generator family used by VICE.
         *
         * Java long overflow is exactly what we want here: arithmetic modulo 2^64.
         */
        m_todRandomState =
                oldState * 6364136223846793005L + 1L;

        final int value =
                (int) ((oldState ^ oldState >>> 18) >>> 27);

        final int rotation =
                (int) (oldState >>> 59);

        final int random =
                Integer.rotateRight(value, rotation);

        /*
         * Equivalent to VICE lib_unsigned_rand(0, 3):
         * use the top two random bits.
         */
        return random >>> 30;
    }
}