Rotation.java

/**
 * rotation.c
 * <p>
 * Written by Andreas Boose <viceteam@t-online.de>
 * <p>
 * This file is part of VICE, the Versatile Commodore Emulator. See README for a copyright notice.
 * <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.
 * <p>
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * <p>
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
 * @author Ken Händel
 *
 **/
package libsidplay.components.c1541;

import libsidplay.components.c1541.VIA6522DC.Mode;

/**
 *
 * Disk rotation.
 *
 * @author Ken Händel
 *
 */
public abstract class Rotation {
    /**
     * Speed (in microbits per drive clock) of the disk in the 4 speed zones.
     * <p>
     * The drive contains a 16.00 MHz crystal, and these values are established by dividing by 16, 15, 14 and 13 and
     * then by 4.
     */
    protected static final int[] ROT_SPEED_BPC = {250000, 266667, 285714, 307692};

    /**
     * 1541 reference clocks per drive CPU clock. The drive electronics run from 16 MHz while the 6502 runs at 1 MHz.
     */
    private static final int REFERENCE_CLOCKS_PER_CPU_CLOCK = 16;

    /**
     * Number of 16 MHz reference clocks in one revolution at 300 RPM.
     */
    private static final int REFERENCE_CLOCKS_PER_REVOLUTION = 3_200_000;

    /**
     * Drive CPU clock frequency.
     */
    private int clockMHz = 1;
    /**
     * Set the CPU clock used to convert drive cycles to physical rotation time.
     *
     * @param frequency drive CPU frequency in MHz (1 or 2)
     */
    protected final void setClockMHz(int frequency) {
        clockMHz = frequency;
    }

    /**
     * Fractional time within the next physical cell, in reference clocks times the revolution's cell weight.
     */
    private long accum;

    /**
     * Time, when the disk motor has been turned on.
     */
    private long rotationLastClk;

    /** Reference clocks already simulated past the current CPU cycle boundary. */
    private int referenceAdvance;
    /**
     * Current bit count (0..7) of a byte that have been read or written.
     */
    private int bitCounter;
    /**
     * Current disk speed zone.
     */
    private int speedZone;
    /**
     * Last 10 bits that have passed under the read/write head.
     */
    private int lastReadData;
    /**
     * Shift register for writing data.
     */
    private byte lastWriteData;
    /**
     * VICE switches from its fast rotation path to the circuit-level GCR path after raw GCR data has been written. In
     * the fast path the selected density and the track length happen to imply one revolution in about 200000 cycles.
     * That assumption stops being valid as soon as software writes a raw track at a density that does not match the
     * nominal track length.
     */
    private boolean complicatedImage;

    /*
     * State of the VICE-style 1541 read/write clock divider used by the complex
     * GCR path. UE7 divides the 16 MHz reference clock according to PB5/PB6 and
     * UF4 provides the four-phase bit-cell counter.
     */
    private int ue7Dcba;
    private int ue7Counter;
    private int uf4Counter;

    /* Flux filter/random-flux state used by VICE's GCR circuit simulation. */
    private int filterCounter;
    private int filterState;
    private int filterLastState;
    private int randomFluxCountdown;
    private int xorShift32;

    /**
     * The GCR image.
     */
    private final GCR gcr;
    private GCR.Recording recording;
    private long recordingClocks;

    /**
     * Disk rotation support.
     */
    public Rotation() {
        // Create Group Code Recording support
        gcr = new GCR();
    }

    public final void reset() {
        finishRecording();
        speedZone = 0;
        ue7Dcba = 0;
        ue7Counter = 0;
        uf4Counter = 0;
        filterCounter = 0;
        filterState = 0;
        filterLastState = 0;
        randomFluxCountdown = 0;
        xorShift32 = 0x1234abcd;
        accum = 0;
        bitCounter = 0;
        rotationBegins();
        gcr.reset();
    }

    /**
     * Mark whether the image already requires VICE's complex GCR rotation path. D64 starts in the fast path and is
     * promoted automatically after the first raw write. G64 can be marked complex immediately by the disk controller.
     */
    protected final void setComplicatedImage(final boolean complicatedImage) {
        this.complicatedImage = complicatedImage;
    }

    protected final void setSpeedZone(final int zone) {
        speedZone = zone & 0x3;
        ue7Dcba = speedZone;
    }

    protected final void rotationBegins() {
        rotationLastClk = cpuClk();
        referenceAdvance = 0;
    }

    /** Select a surface, preserving physical angle when either surface has nonuniform recorded timing. */
    protected final void selectHalfTrack(DiskImage image, int halfTrack, int side, int oldSize, int newSize) {
        boolean wasVariable = gcr.hasTrackTiming();
        long oldWeight = gcr.getRevolutionWeight(oldSize);
        long position = (long) gcr.getHeadWeight() * REFERENCE_CLOCKS_PER_REVOLUTION + accum;
        if (image != null) {
            image.selectHalfTrack(halfTrack, side, oldSize, newSize);
        } else {
            gcr.setHalfTrack(halfTrack + side * 84, oldSize, newSize);
        }
        if (wasVariable || gcr.hasTrackTiming()) {
            long newWeight = gcr.getRevolutionWeight(newSize);
            // The maximum supported surface keeps this rational rescaling within a signed long.
            position = position * newWeight / oldWeight;
            position %= newWeight * REFERENCE_CLOCKS_PER_REVOLUTION;
            int headWeight = gcr.setHeadWeight((int) (position / REFERENCE_CLOCKS_PER_REVOLUTION));
            accum = position - (long) headWeight * REFERENCE_CLOCKS_PER_REVOLUTION;
        }
    }

    /** Finish a G64 write gate and restore the physical angle in its newly recorded layout. */
    protected final void finishRecording() {
        if (recording != null) {
            long oldWeight = gcr.getRevolutionWeight(getCurrentTrackSize());
            long position = (long) gcr.getHeadWeight() * REFERENCE_CLOCKS_PER_REVOLUTION + accum;
            GCR.Recording finished = recording;
            recording = null;
            finished.finish(recordingClocks);
            long newWeight = gcr.getRevolutionWeight(getCurrentTrackSize());
            position = position * newWeight / oldWeight;
            position %= newWeight * REFERENCE_CLOCKS_PER_REVOLUTION;
            int headWeight = gcr.setHeadWeight((int) (position / REFERENCE_CLOCKS_PER_REVOLUTION));
            accum = position - (long) headWeight * REFERENCE_CLOCKS_PER_REVOLUTION;
        }
    }

    protected GCR.Recording beginRecording(long phase) {
        return null;
    }

    /**
     * Rotate the disk according to a system clock. While rotating, calculate read/write data on the platter and note
     * the presence and absence of SYNC. The caller must check the precondition if the drive motor is on.
     */
    protected final void rotateDisk() {
        rotateDisk(0);
    }

    /**
     * Sample near the end of PHI2. The 6502 needs 100 ns data setup at 1 MHz,
     * 50 ns at 2 MHz; round up to two/one ticks of the 16 MHz reference clock.
     */
    protected final void rotateDiskForRead() {
        rotateDisk((REFERENCE_CLOCKS_PER_CPU_CLOCK - 2) / clockMHz);
    }

    private void rotateDisk(int advance) {
        if (complicatedImage) {
            rotateDiskComplex(advance);
        } else {
            rotateDiskSimple();
        }
    }

    /**
     * Fast path used by VICE for uncomplicated sector images. This is the historic JSIDPlay2 implementation: the
     * selected density directly determines how many raw GCR bits pass the head. It is valid while the raw track layout
     * matches the density zone.
     */
    private void rotateDiskSimple() {

        /*
         * VICE: once a raw write occurred, the simple density*track-size shortcut is
         * no longer valid. Future reads/writes use the GCR circuit path, where platter
         * rotation is fixed by RPM and the density selector only clocks the electronics.
         */
        complicatedImage = true;
    }

    /**
     * VICE-style GCR path used after a raw write. The platter advances according to a physical 300 RPM revolution,
     * independently of PB5/PB6. The selected speed zone only drives the UE7/UF4 decoder clock. This is the distinction
     * exercised by drive/rpm/rpm3.prg.
     */
    private void rotateDiskComplex(int advance) {
        final long clk = cpuClk();
        long cpuCycles = clk - rotationLastClk;
        rotationLastClk = clk;

        /* VICE keeps at most two revolutions worth of catch-up work. */
        while (cpuCycles > 400_000L * clockMHz) {
            cpuCycles -= 200_000L * clockMHz;
        }

        long elapsed = cpuCycles * REFERENCE_CLOCKS_PER_CPU_CLOCK / clockMHz;
        long clocks = elapsed + advance - referenceAdvance;
        if (clocks <= 0) {
            referenceAdvance -= (int) elapsed;
            return;
        }
        referenceAdvance = advance;
        rotateDiskComplexGcr(clocks);
    }

    private void rotateDiskComplexGcr(long referenceCycles) {
        if (recording != null && (getReadWriteMode() == Mode.READ || isWriteProtected())) {
            finishRecording();
        }
        final long revolutionWeight = gcr.getRevolutionWeight(getCurrentTrackSize());
        if (getReadWriteMode() == Mode.WRITE && !isWriteProtected() && recording == null) {
            long phase = ((long) gcr.getHeadWeight() * REFERENCE_CLOCKS_PER_REVOLUTION + accum) / revolutionWeight;
            recording = beginRecording(phase);
            recordingClocks = 0;
        }

        if (getReadWriteMode() == Mode.READ) {
            while (referenceCycles > 0) {
                long cellThreshold = (long) gcr.getBitCellWeight() * REFERENCE_CLOCKS_PER_REVOLUTION;
                long todo = nextComplexStep(referenceCycles, revolutionWeight, cellThreshold, true);

                /* 2.5us flux filter, following current VICE rotation_1541_gcr(). */
                filterCounter += (int) todo;
                if (filterCounter >= 40 && filterLastState != filterState) {
                    filterLastState = filterState;
                    ue7Counter = ue7Dcba;
                    uf4Counter = 0;
                    randomFluxCountdown = randomFluxDelay(31, 289);
                } else if (randomFluxCountdown > 0) {
                    randomFluxCountdown -= (int) todo;
                    if (randomFluxCountdown <= 0) {
                        ue7Counter = ue7Dcba;
                        uf4Counter = 0;
                        randomFluxCountdown = randomFluxDelay(367, 33);
                    }
                }

                clockDecoder(todo, false, false);

                /* Recorded cell weights divide one 300 RPM revolution independently of decoder density. */
                accum += revolutionWeight * todo;
                if (accum >= cellThreshold) {
                    accum -= cellThreshold;
                    if (gcr.readNextBit(getCurrentTrackSize()) != 0) {
                        /* VICE primes the filter to one reference tick before acceptance. */
                        filterCounter = 39;
                        filterState ^= 1;
                    }
                }

                referenceCycles -= todo;
            }
        } else {
            final boolean protectedWrite = isWriteProtected();
            while (referenceCycles > 0) {
                long cellThreshold = (long) gcr.getBitCellWeight() * REFERENCE_CLOCKS_PER_REVOLUTION;
                long todo = nextComplexStep(referenceCycles, revolutionWeight, cellThreshold, false);

                /* Keep the physical-revolution phase in step as VICE does. */
                accum += revolutionWeight * todo;
                if (accum >= cellThreshold) {
                    accum -= cellThreshold;
                    if (protectedWrite || recording != null) {
                        // The platter moves at its physical RPM while the encoder supplies new cells separately.
                        gcr.readNextBit(getCurrentTrackSize());
                    }
                }

                if (recording != null) recordingClocks += todo;
                clockDecoder(todo, true, protectedWrite);

                referenceCycles -= todo;
            }
        }
    }

    /**
     * Choose the largest safe VICE-style reference-clock step without crossing a platter-cell, divider, filter or
     * random-flux event.
     */
    private long nextComplexStep(final long remaining, final long revolutionWeight, final long cellThreshold,
                                 final boolean reading) {
        long todo = 1;
        final long delta = cellThreshold - accum;

        if (delta > 0 && (revolutionWeight << 1) <= delta) {
            todo = delta / revolutionWeight;
            todo = Math.min(todo, remaining);
            todo = Math.min(todo, 16 - ue7Counter);

            if (reading) {
                if (filterCounter < 40) {
                    todo = Math.min(todo, 40 - filterCounter);
                }
                if (randomFluxCountdown > 0) {
                    todo = Math.min(todo, randomFluxCountdown);
                }
            }
        }

        return Math.max(1, todo);
    }

    /**
     * Clock the UE7/UF4 data separator. PB5/PB6 select the divider here, while platter position is advanced separately
     * by rotateDiskComplexGcr().
     */
    private void clockDecoder(final long clocks, final boolean writing, final boolean protectedWrite) {
        ue7Counter += (int) clocks;
        if (ue7Counter != 16) {
            return;
        }

        ue7Counter = ue7Dcba;
        uf4Counter = uf4Counter + 1 & 0xf;
        if ((uf4Counter & 0x3) != 2) {
            return;
        }

        lastReadData = lastReadData << 1 & 0x3fe | (uf4Counter + 0x1c >> 4 & 0x01);

        if (writing) {
            if (!protectedWrite) {
                setDirty();
                if (recording != null) {
                    recording.writeBit((lastWriteData & 0x80) != 0, speedZone, recordingClocks);
                } else {
                    gcr.writeNextBit((lastWriteData & 0x80) != 0, getCurrentTrackSize());
                    /* Retain the historic fixed-cell writer for sector and NIB-family images. */
                    accum = (long) gcr.getRevolutionWeight(getCurrentTrackSize()) * 2;
                }
            }
            lastWriteData <<= 1;

            if (++bitCounter == 8) {
                bitCounter = 0;
                lastWriteData = writeData();
            }
            return;
        }

        lastWriteData <<= 1;
        if (lastReadData == 0x3ff) {
            bitCounter = 0;
        } else if (++bitCounter == 8) {
            bitCounter = 0;
            lastWriteData = (byte) lastReadData;
            readData((byte) lastReadData);
        }
    }

    private int randomFluxDelay(final int modulo, final int base) {
        return (int) ((Integer.toUnsignedLong(nextXorShift32()) >>> 16) % modulo) + base;
    }

    private int nextXorShift32() {
        xorShift32 ^= xorShift32 << 13;
        xorShift32 ^= xorShift32 >>> 17;
        xorShift32 ^= xorShift32 << 5;
        return xorShift32;
    }

    /**
     * SYNC is detected whenever the last 10 bits are 1, and we aren't writing, or the disk wasn't just being changed.
     *
     * @return 0 when found, 0x80 when not.
     */
    protected final byte syncFound() {
        if (getReadWriteMode() == Mode.WRITE || isDiskChangeInProgress()) {
            return (byte) 0x80;
        }

        return lastReadData == 0x3ff ? (byte) 0 : (byte) 0x80;
    }

    /**
     * Group Code Recording support.
     *
     * @return the GCR support
     */
    protected final GCR getGCR() {
        return gcr;
    }

    protected abstract long cpuClk();

    protected abstract Mode getReadWriteMode();

    protected abstract void readData(byte readData);

    protected abstract byte writeData();

    protected abstract int getCurrentTrackSize();

    protected abstract void setDirty();

    protected abstract boolean isWriteProtected();

    protected abstract boolean isDiskChangeInProgress();

    protected abstract boolean isSpindleSpeedBased();
}