VIA6522DC.java

/*
 * via2d.c - VIA2 emulation in the 1541, 1541II, 1571 and 2031 disk drive.
 *
 * Written by
 *  Andreas Boose <viceteam@t-online.de>
 *  André Fachat <fachat@physik.tu-chemnitz.de>
 *  Daniel Sladic <sladic@eecg.toronto.edu>
 *  Ettore Perazzoli <ettore@comm2000.it>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  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.
 *
 *  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.
 *
 *  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.
 *
 */
package libsidplay.components.c1541;

import libsidplay.common.Event;
import libsidplay.components.mos6510.MOS6510;

import java.io.File;
import java.io.IOException;

/**
 * Handling of the Disk Controller.
 *
 * @author Ken Händel
 *
 */
public abstract class VIA6522DC extends VIACore implements DriveController {
    /**
     * Number of cycles before an attached disk becomes visible to the R/W head. This is mostly to make routines that
     * auto-detect disk changes happy.
     *
     */
    private static final int DRIVE_ATTACH_DELAY = 3 * 600000;
    /**
     * Number of cycles the writing protection is activated on detaching.
     */
    private static final int DRIVE_DETACH_DELAY = 3 * 200000;
    /**
     * Number of cycles the after a disk can be inserted after a disk has been detached.
     */
    private static final int DRIVE_ATTACH_DETACH_DELAY = 3 * 400000;

    /**
     * Current mode read or write.
     *
     * @author Ken Händel
     *
     */
    enum Mode {
        READ, WRITE
    }

    /**
     * Tick when the disk image was attached.
     */
    private long attachClk;
    /**
     * Tick when the disk image was detached.
     */
    private long detachClk;
    /**
     * Tick when the disk image was attached, but an old image was just detached.
     */
    private long attachDetachClk;
    /**
     * Byte to read from r/w head.
     */
    private byte gcrRead;
    /**
     * GCR value being written to the disk.
     */
    private byte gcrWrite;
    /**
     * Are we in read or write mode?
     */
    private Mode readWriteMode;
    /**
     * Activates the byte-ready line.
     */
    private int byteReadyActive;
    /**
     * BYTE READY has reached the drive CPU SO input and has not yet been sampled.
     */
    private boolean byteReadyEdge;
    /**
     * Current BYTE READY handshake level.
     */
    private boolean byteReadyLevel;
    /**
     * Drive CPU.
     */
    private final MOS6510 cpu;
    /**
     * Does the current GCR data need to be written to disk?
     */
    private boolean gcrDataDirty;
    /**
     * Current half-track on which the R/W head is positioned. Start at track 1 so media can be attached before reset.
     */
    private int currentHalfTrack = 2;

    /**
     * Minimum time for a physical half-track step, in 1 MHz drive clocks.
     */
    private static final long HEAD_STEP_CYCLES = 3000;

    /**
     * Selected physical head (0 or 1), with each GCR surface in its own 42-track bank.
     */
    private int side;
    /**
     * Drive CPU frequency in MHz, used to preserve physical delays across 1571 clock changes.
     */
    private int clockMHz = 1;
    /**
     * Destination of the pending physical head motion.
     */
    private int requestedHalfTrack = currentHalfTrack;
    /**
     * Whether a physical half-track step is scheduled.
     */
    private boolean headStepPending;
    /**
     * Absolute drive CPU cycle of the pending half-track step.
     */
    private long headStepDeadline;

    /**
     * Perform one physical half-track step and continue toward the requested position.
     */
    private final Event headStep = Event.of("1541 head step", event -> {
        headStepPending = false;
        if (!isMotorOn() || requestedHalfTrack == currentHalfTrack) {
            return;
        }
        rotateDisk();
        moveHead(requestedHalfTrack > currentHalfTrack);
        scheduleHeadStep();
    });

    private void scheduleHeadStep() {
        if (!headStepPending && requestedHalfTrack != currentHalfTrack) {
            headStepPending = true;
            headStepDeadline = cpuClk() + HEAD_STEP_CYCLES * clockMHz;
            alarmSet(headStep, headStepDeadline);
        }
    }

    private void cancelHeadMotion() {
        alarmUnset(headStep);
        headStepPending = false;
        requestedHalfTrack = currentHalfTrack;
    }

    /**
     * Disk rotation.
     */
    private final Rotation rot;
    /**
     * Attached disk image.
     */
    private DiskImage image;
    /**
     * Floppy device number (8-11).
     */
    private final int id;

    /**
     * Creates a new instance of VIA6522DC.
     *
     * @param deviceID the C1541 device ID
     * @param cpu      drive CPU
     */
    public VIA6522DC(final int deviceID, final MOS6510 cpu) {
        super("1541Drive" + deviceID + "VIA6522DC");
        this.id = deviceID;
        this.cpu = cpu;
        // Create disk rotation support.
        rot = new Rotation() {
            @Override
            protected long cpuClk() {
                return cpu.getEventScheduler().getTime(Event.Phase.PHI2);
            }

            @Override
            protected Mode getReadWriteMode() {
                return getMode();
            }

            @Override
            protected void readData(final byte readData) {
                setLastGCRRead(readData);
                byteReady();
            }

            @Override
            protected byte writeData() {
                final byte writeData = getLastGCRWrite();
                byteReady();
                return writeData;
            }

            @Override
            protected int getCurrentTrackSize() {
                if (getImage() != null) {
                    // Use metrics of the attached disk image
                    return getImage().getHalfTrackSize(getHalfTrack(), side);
                } else {
                    // If no disk is attached, use metrics of a standard disk
                    return DiskImage.RAW_TRACK_SIZE[DiskImage.SPEED_MAP_1541[(getHalfTrack() >> 1) - 1]];
                }
            }

            @Override
            protected GCR.Recording beginRecording(long phase) {
                return image == null ? null : image.beginGCRRecording(currentHalfTrack, side, phase);
            }

            @Override
            protected void setDirty() {
                setGCRDataDirty();
            }

            @Override
            protected boolean isWriteProtected() {
                return getImage() != null && getImage().isReadOnly();
            }

            @Override
            protected boolean isDiskChangeInProgress() {
                return getAttachClk() != 0;
            }

            @Override
            protected final boolean isSpindleSpeedBased() {
                return getImage() instanceof G64;
            }
        };
    }

    @Override
    public final void reset() {
        rotateDisk();
        rot.finishRecording();
        cancelHeadMotion();
        attachClk = 0;
        detachClk = 0;
        attachDetachClk = 0;
        gcrRead = 0;
        gcrWrite = 0x55;
        byteReadyActive = 0;
        readWriteMode = Mode.READ;
        gcrDataDirty = false;

        /*
         * Reset the electronics/GCR state first. rot.reset() resets the
         * GCR data position, so the physical head position must be applied
         * afterwards.
         */
        currentHalfTrack = 2;

        super.reset();
        rot.reset();

        // VIA reset leaves PB5/PB6 high; keep the decoder density in sync.
        rot.setSpeedZone((oldpb & 0xff) >> 5 & 0x3);

        setHalfTrack(DiskImage.DIR_TRACK_1541 << 1);
        requestedHalfTrack = currentHalfTrack;
    }

    /**
     * Does this drive have a second GCR head?
     *
     * @return true for double-sided drive electronics
     */
    protected boolean supportsDoubleSided() {
        return false;
    }

    /**
     * Gets attached disk image (null if nothing attached).
     *
     * @return attached disk image
     */
    protected DiskImage getImage() {
        return image;
    }

    /**
     * Insert Disk.<BR> A previously inserted disk will be ejected first.
     *
     * @param file disk image file
     * @return attached disk image
     * @throws IOException cannot read a disk image file
     */
    public DiskImage insertDisk(final File file) throws IOException {
        DiskImage.Format format = DiskImage.detect(file);
        if (format == DiskImage.Format.D81 || format == DiskImage.Format.D71 && !supportsDoubleSided()) {
            throw new IOException("Image requires a compatible drive: " + format);
        }
        ejectDisk();
        attachClk = cpuClk();
        if (detachClk > 0) attachDetachClk = cpuClk();
        image = DiskImage.attach(rot.getGCR(), file);
        rot.setComplicatedImage(image instanceof G64);
        rot.getGCR().attach();

        /*
         * DiskImage.attach() fills the GCR tracks but does not select the
         * track underneath the current physical head.
         *
         * VICE explicitly reapplies current_half_track after attaching an image.
         */
        setHalfTrack(currentHalfTrack);

        System.out.printf("Unit %d: " + image.getClass().getSimpleName() + " disk image attached: %s.\n", id,
                file.getAbsolutePath());
        diskAttachedDetached(file.getName(), true);
        return image;
    }

    /**
     * Detach Disk.<BR> A previously inserted disk will be ejected.
     *
     * @throws IOException cannot write a disk file
     *
     */
    public void ejectDisk() throws IOException {
        if (image != null) {
            rotateDisk();
            gcrDataWriteback();
            if (gcrDataDirty || image.hasPendingGCRWrites()) {
                throw new IOException("Cannot eject disk while recorded changes could not be saved");
            }
            detachClk = cpuClk();
            int size = rot.getCurrentTrackSize();
            rot.selectHalfTrack(null, currentHalfTrack, side, size, size);
            rot.getGCR().detach();
            image.detach();
            System.out.printf("Unit %d: " + image.getClass().getSimpleName() + " disk image detached: %s.\n", id,
                    image.fileName);
            diskAttachedDetached(image.fileName, false);
            image = null;
        }
    }

    /**
     * Ticks when the disk image was attached.
     *
     * @return when the disk was attached
     */
    public long getAttachClk() {
        return attachClk;
    }

    /**
     * Reposition the read/write head to the parameterized half-track accounting for potential change in speed zone (=
     * track length).
     *
     * @param num half-track to set
     */
    protected void setHalfTrack(final int num) {
        rot.finishRecording();
        final int oldTrackSize = rot.getCurrentTrackSize();
        currentHalfTrack = num;
        selectGCRTrack(oldTrackSize);
    }

    private void selectGCRTrack(int oldSize) {
        rot.selectHalfTrack(image, currentHalfTrack, side, oldSize, rot.getCurrentTrackSize());
    }

    /**
     * Get the selected physical head.
     *
     * @return selected head (0 or 1)
     */
    @Override
    public int getSide() {
        return side;
    }

    /**
     * Flush the old surface and select the physical head.
     *
     * @param selected head selection; only bit 0 is used
     */
    public void setSide(int selected) {
        selected &= 1;
        if (selected != side) {
            rotateDisk();
            gcrDataWriteback();
            if (gcrDataDirty || image != null && image.hasPendingGCRWrites()) return;
            int oldSize = rot.getCurrentTrackSize();
            side = selected;
            selectGCRTrack(oldSize);
        }
    }

    /**
     * Rescale pending head and disk-change delays before switching the drive CPU clock.
     *
     * @param frequency new drive CPU frequency in MHz (1 or 2)
     */
    public void setClockMHz(int frequency) {
        if (frequency == clockMHz) return;
        rotateDisk();
        long now = cpuClk();
        if (headStepPending) {
            alarmUnset(headStep);
            headStepDeadline = now + Math.max(0, headStepDeadline - now) * frequency / clockMHz;
            alarmSet(headStep, headStepDeadline);
        }
        attachClk = rescaleTimestamp(attachClk, now, frequency);
        detachClk = rescaleTimestamp(detachClk, now, frequency);
        attachDetachClk = rescaleTimestamp(attachDetachClk, now, frequency);
        clockMHz = frequency;
        rot.setClockMHz(frequency);
    }

    /**
     * Preserve elapsed physical time across a CPU clock change while keeping 0 as the inactive sentinel.
     *
     * @param timestamp previous drive-cycle timestamp
     * @param now       current drive cycle
     * @param frequency new CPU frequency in MHz
     * @return rescaled timestamp, or 0 if inactive
     */
    private long rescaleTimestamp(long timestamp, long now, int frequency) {
        if (timestamp == 0) return 0;
        long adjusted = now - (now - timestamp) * frequency / clockMHz;
        return adjusted == 0 ? -1 : adjusted;
    }

    public int getHalfTrack() {
        return currentHalfTrack;
    }

    protected void moveHead(final boolean forward) {
        gcrDataWriteback();
        if (gcrDataDirty || image != null && image.hasPendingGCRWrites()) return;
        if (forward && currentHalfTrack < DiskImage.MAX_TRACKS_1541 << 1) {
            // the upper limit is track 42
            setHalfTrack(currentHalfTrack + 1);
        }
        if (!forward && currentHalfTrack > 2) {
            // the lower limit is track 1
            setHalfTrack(currentHalfTrack - 1);
        }
    }

    /**
     * Write back dirty GCR data to the attached disk image.
     */
    protected void gcrDataWriteback() {
        rot.finishRecording();
        if (image == null || !gcrDataDirty && !image.hasPendingGCRWrites()) {
            // No disk attached or not dirty, yet?
            return;
        }
        if (image.isReadOnly()) {
            System.err.println("Attempt to write to read-only disk image.");
            if (!image.hasPendingGCRWrites()) gcrDataDirty = false;
        } else {
            try {
                if (image.hasPendingGCRWrites()) {
                    image.flushPendingGCRWrites();
                } else if ((side == 0 || image instanceof D71) && (!(image instanceof D71) || (currentHalfTrack >> 1) <= 35)) {
                    image.gcrHalfTrackWriteback(currentHalfTrack, side);
                }
                gcrDataDirty = false;
            } catch (final IOException e) {
                System.err.println(e.getMessage());
                System.err.printf("Error writing T:%d to disk image.\n", currentHalfTrack >> 1);
            }
        }
    }

    /**
     * Is LED on?
     *
     * @return LED on
     */
    public final boolean isLEDOn() {
        return (oldpb & 0x8) != 0;
    }

    /**
     * Is the disk motor on?
     *
     * @return motor ist on
     */
    public final boolean isMotorOn() {
        return (byteReadyActive & 4) != 0;
    }

    @Override
    protected final void setCa2(final int state) {
        final int current = byteReadyActive >> 1 & 1;
        if (state != current) {
            rotateDisk();
            byteReadyActive = byteReadyActive & ~0x02 | state << 1;

            /*
             * VICE flushes a pending BYTE READY edge when SOE/CA2 changes.
             * The level itself is acknowledged separately by port accesses.
             */
            sampleByteReady();
        }
    }

    @Override
    protected final void setCb2(final int state) {
        final Mode mode = state != 0 ? Mode.READ : Mode.WRITE;
        if (mode != readWriteMode) {
            rotateDisk();
            rot.finishRecording();
            readWriteMode = mode;
        }
    }

    protected Mode getMode() {
        return readWriteMode;
    }

    @Override
    protected final void storePra(final int addr, final byte byt) {
        rotateDisk();
        gcrWrite = byt;
        byteReadyLevel = false;
    }

    /**
     * Get recently written GCR byte.
     *
     * @return GCR byte
     */
    protected final byte getLastGCRWrite() {
        return gcrWrite;
    }

    @Override
    protected final void storePrb(final byte byt) {
        rotateDisk();

        // Coils select a phase relative to the physical head, not a queue of steps.
        // Rapid phase changes can be superseded before the 3 ms movement completes.
        if ((byt & 0x04) != 0) {
            // Re-energizing opposite coils aligns the rotor by a full track.
            // Opposite coils remain ignored while the motor is already running.
            final int transition = ((byt & 3) - ((currentHalfTrack - 2) & 3)) & 3;
            final int step = transition == 3 ? -1
                    : transition == 2 && (oldpb & 4) == 0 ? 2 : transition == 1 ? 1 : 0;
            requestedHalfTrack = Math.max(2, Math.min(DiskImage.MAX_TRACKS_1541 << 1,
                    currentHalfTrack + step));
            if (requestedHalfTrack == currentHalfTrack) {
                cancelHeadMotion();
            } else {
                scheduleHeadStep();
            }
        }

        rot.setSpeedZone((byt & 0xff) >> 5 & 0x3);
        if (((oldpb ^ byt) & 0x04) != 0) {
            byteReadyActive = byteReadyActive & ~0x04 | byt & 0x04;
            /* drive motor is turned on */
            if (isMotorOn()) {
                rot.rotationBegins();
            } else {
                /*
                 * VICE delivers a pending SO edge before the motor stops.
                 */
                sampleByteReady();
                cancelHeadMotion();
            }
        }

        byteReadyLevel = false;
    }

    @Override
    protected final void storeAcr(final byte value) {
    }

    @Override
    protected final void storeSr(final byte value) {
    }

    @Override
    protected final void storeT2l(final byte value) {
    }

    @Override
    protected final byte readPra() {
        byteRead();

        /*
         * the bus is shared between the read/write modes. The schematic says that
         * during writing mode, the read circuitry is disconnected, and therefore it's
         * likely that you will read 0xff if you change the DDR.
         */
        byteReadyLevel = false;
        return readPraPins();
    }

    @Override
    protected final byte readPraPins() {
        final byte encoderDecoderValue = readWriteMode == Mode.READ ? gcrRead : (byte) 0xff;
        return (byte) (encoderDecoderValue & ~via[VIACore.VIA_DDRA] | via[VIACore.VIA_PRA] & via[VIACore.VIA_DDRA]);
    }

    /**
     * Set recently read GCR byte.
     *
     * @param lastReadData GCR byte
     */
    protected final void setLastGCRRead(final byte lastReadData) {
        gcrRead = lastReadData;
    }

    /** The 1571 keeps its existing bus timing until that board has a separate timing contract. */
    protected boolean usesLateReadSampling() {
        return true;
    }

    @Override
    protected final byte readPrb() {
        if (isMotorOn()) {
            if (usesLateReadSampling()) rot.rotateDiskForRead();
            else rot.rotateDisk();
        }
        // A moving head cannot lock onto a sector sync mark. Rotation continues.
        final byte sync = headStepPending ? (byte) 0x80 : rot.syncFound();
        byteReadyLevel = false;
        return portBPins(sync);
    }

    @Override
    protected final byte readPrbPins() {
        // No disk rotation or BYTE READY acknowledgement when sampling pins.
        return portBPins(headStepPending ? (byte) 0x80 : rot.syncFound());
    }

    private byte portBPins(byte sync) {
        return (byte) ((sync | writeProtectSense() | 0x6f) & ~via[VIACore.VIA_DDRB]
                | via[VIACore.VIA_PRB] & via[VIACore.VIA_DDRB]);
    }

    /**
     * Latch a completed disk byte.
     * <p>
     * The modern VICE simple-D64 path does not write V immediately here. Instead it latches BYTE READY as an edge/level
     * pair. The drive CPU samples the edge at the SO-sensitive points (BVC/BVS/PHP), while VIA accesses acknowledge the
     * level.
     */
    private void byteReady() {
        if (!isByteReadyActive()) {
            return;
        }

        byteReadyEdge = true;

        /*
         * Keep the existing CA1 behavior, but make it a real level transition:
         * another CA1 edge is not generated until a port access acknowledges it.
         */
        if (!byteReadyLevel) {
            byteReadyLevel = true;
            signal(VIACore.VIA_SIG_CA1, VIACore.VIA_SIG_RISE);
        }
    }

    /**
     * Sample and consume a pending BYTE READY edge at the CPU SO input.
     */
    protected final void sampleByteReady() {
        if (byteReadyEdge) {
            byteReadyEdge = false;
            cpu.setFlagV(true);
        }
    }

    /**
     * CLV and other instructions which explicitly clear V discard an SO edge which arrived before that V write.
     */
    protected final void clearByteReadyEdge() {
        byteReadyEdge = false;
    }

    /**
     * Is byte ready to be processed?
     *
     * @return byte ready active
     */
    protected final boolean isByteReadyLevel() {
        return byteReadyLevel;
    }

    protected final boolean isByteReadyActive() {
        return (byteReadyActive & 2) != 0;
    }

    /**
     * Rotate the disk if the motor is on.
     */
    protected final void rotateDisk() {
        if (isMotorOn()) {
            rot.rotateDisk();
        }
    }

    protected void setGCRDataDirty() {
        this.gcrDataDirty = true;
    }

    /**
     * Read GCR data by rotating the disk, if disk attachment/detachment is in progress, just delay and read zero.
     */
    private void byteRead() {
        if (attachClk != 0) {
            if (cpuClk() - attachClk < DRIVE_ATTACH_DELAY * clockMHz) {
                gcrRead = 0;
            } else {
                attachClk = 0;
            }
        } else if (attachDetachClk != 0) {
            if (cpuClk() - attachDetachClk < DRIVE_ATTACH_DETACH_DELAY * clockMHz) {
                gcrRead = 0;
            } else {
                attachDetachClk = 0;
            }
        } else {
            rotateDisk();
        }
    }

    /**
     * Implements write protect sense, in respect to the disk currently being attached/detached.
     *
     * @return 0x0 (write protected), 0x10 (read/write)
     */
    private byte writeProtectSense() {
        /*
         * Clear the writing protection bit for the time the disk is pulled out on detaching.
         */
        if (detachClk != 0) {
            if (cpuClk() - detachClk < DRIVE_DETACH_DELAY * clockMHz) {
                return 0x0;
            }
            detachClk = 0;
        }
        /*
         * Set the writing protection bit for the minimum time until a new disk can be
         * inserted.
         */
        if (attachDetachClk != 0) {
            if (cpuClk() - attachDetachClk < DRIVE_ATTACH_DETACH_DELAY * clockMHz) {
                return 0x10;
            }
            attachDetachClk = 0;
        }
        /*
         * Clear the writing protection bit for the time the disk is put in on attachment.
         */
        if (attachClk != 0) {
            if (cpuClk() - attachClk < DRIVE_ATTACH_DELAY * clockMHz) {
                return 0x0;
            }
            attachClk = 0;
        }

        if (image == null || !image.isReadOnly()) {
            // No disk in drive or write protection is off.
            return 0x10;
        } else {
            // Write protection is on
            return 0x0;
        }
    }

    public abstract void diskAttachedDetached(String imageName, boolean attached);

}