IECBus.java

/*
 * iecbus.c - IEC bus handling.
 *
 * Written by
 *  Andreas Boose <viceteam@t-online.de>
 *
 * 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.iec;

import libsidplay.common.Event.Phase;
import libsidplay.components.c1541.FloppyDrive;
import libsidplay.components.c1541.FloppyType;
import libsidplay.components.mos6526.MOS6526;

import java.util.Arrays;

/**
 * IEC Bus Implementation.
 *
 * @author Ken Händel
 *
 */
public class IECBus {
    /**
     * Number of IEC devices.
     */
    public static final int IECBUS_NUM = 16;

    private static final int CLOCK = 0x40, DATA = 0x80;

    private long driveClockChangedAt;
    private long driveDataChangedAt;

    protected byte[] drvBus = new byte[IECBUS_NUM];
    protected byte[] drvData = new byte[IECBUS_NUM];
    protected byte drvPort;
    protected byte cpuBus;
    protected byte cpuPort;

    /**
     * Floppy Disk Drives connected to the bus.
     */
    protected FloppyDrive[] drives;
    /**
     * Drive CIAs connected to fast serial SP/CNT pins, indexed by IEC device number.
     */
    private final MOS6526[] fastCias = new MOS6526[16];
    /**
     * Whether each drive drives the shared fast serial pins.
     */
    private final boolean[] fastOutput = new boolean[16];
    /**
     * SP data and CNT clock levels driven by each device; true means released/high.
     */
    private final boolean[] fastSp = new boolean[16], fastCnt = new boolean[16];

    /**
     * Connect or disconnect a drive's fast serial CIA.
     *
     * @param id  IEC device number
     * @param cia connected CIA, or null to disconnect the device
     */
    public void connectFastSerial(int id, MOS6526 cia) {
        fastCias[id] = cia;
        fastSp[id] = fastCnt[id] = true;
        fastOutput[id] = false;
        updateFastSerial();
    }
    /**
     * Set whether a drive transmits or receives on the fast serial pins.
     *
     * @param id     IEC device number
     * @param output true for a transmitting drive
     */
    public void setFastSerialDirection(int id, boolean output) {
        fastOutput[id] = output;
        updateFastSerial();
    }
    /**
     * Update one drive's fast serial output pins.
     *
     * @param id  IEC device number
     * @param sp  serial data level, true for high
     * @param cnt serial clock level, true for high
     */
    public void writeFastSerial(int id, boolean sp, boolean cnt) {
        fastSp[id] = sp;
        fastCnt[id] = cnt;
        updateFastSerial();
    }
    /**
     * Resolve the wired-AND SP/CNT levels and deliver them to receiving drive CIAs.
     */
    private void updateFastSerial() {
        boolean sp = true, cnt = true;
        for (int i = 0; i < 16; i++) {
            if (fastCias[i] != null && fastOutput[i]) {
                sp &= fastSp[i];
                cnt &= fastCnt[i];
            }
        }
        for (int i = 0; i < 16; i++) {
            if (fastCias[i] != null && !fastOutput[i]) {
                fastCias[i].setSerialInput(sp, cnt);
            }
        }
    }

    /**
     * Serial devices connected to the bus.
     */
    protected SerialIECDevice[] serialDevices;

    public IECBus() {
        drives = new FloppyDrive[0];
        serialDevices = new SerialIECDevice[0];
        reset();
    }

    /**
     * Reset bus state.
     */
    public final void reset() {
        Arrays.fill(fastOutput, false);
        Arrays.fill(fastSp, true);
        Arrays.fill(fastCnt, true);
        Arrays.fill(drvBus, (byte) 0xff);
        Arrays.fill(drvData, (byte) 0xff);
        cpuBus = (byte) 0xff;
        cpuPort = (byte) 0xff;
        drvPort = (byte) 0x85;
        clearDriveReadHistory();
        updateFastSerial();
    }

    /**
     * Set Floppy Disk Drives.
     *
     * @param drvs Floppies
     */
    public final void setFloppies(final FloppyDrive[] drvs) {
        this.drives = drvs;
        clearDriveReadHistory();
    }

    /**
     * Set Serial Devices.
     *
     * @param devices Serial Devices
     */
    public final void setSerialDevices(final SerialIECDevice[] devices) {
        serialDevices = devices;
    }

    /** The IEC timing calibration is for a single powered 1541-II. */
    public final boolean hasDirect1541II() {
        if (drives.length != 1 || drives[0].getFloppyType() != FloppyType.C1541_II || !drives[0].isPowerOn()) {
            return false;
        }
        for (final SerialIECDevice serialDevice : serialDevices) {
            if (serialDevice.enabled) {
                return false;
            }
        }
        return true;
    }

    /** CIA2's complemented PA4 release changes the C64's CLOCK output from low to high. */
    public final boolean c64ReleasesClock(final byte data) {
        return (data & 0x10) != 0 && (cpuBus & CLOCK) == 0;
    }

    /** Rebase the receive sample when the drive is reset or replaced. */
    public final void clearDriveReadHistory() {
        driveClockChangedAt = Long.MIN_VALUE;
        driveDataChangedAt = Long.MIN_VALUE;
    }

    // triggered by CIA

    /**
     * Read from IEC bus.
     *
     * @return bus value
     */
    public final byte readFromIECBus() {
        clockSerialDevices();
        return cpuPort;
    }

    /** Sample the directly connected drive's CLOCK and DATA at their exclusive PHI2 deadlines. */
    public final byte readFromIECBus(final long deadline, final long dataRiseDeadline) {
        clockSerialDevices();
        int drive = drvBus[drives[0].getID()];
        final long dataDeadline = (drive & DATA) == 0 ? deadline : dataRiseDeadline;
        // The look-ahead and receive delay together span less than one drive clock.
        // Fold back a pending transition before resolving the C64's own pull-downs.
        if (driveClockChangedAt >= deadline) {
            drive ^= CLOCK;
        }
        if (driveDataChangedAt >= dataDeadline) {
            drive ^= DATA;
        }
        return resolveSerialDevices((byte) (cpuBus & drive));
    }

    private void clockSerialDevices() {
        for (final SerialIECDevice serialDevice : serialDevices) {
            serialDevice.clock();
        }
    }

    // triggered by CIA

    /**
     * Write to IEC bus.
     *
     * @param data write value
     */
    public final void writeToIECBus(final byte data) {
        clockSerialDevices();
        final byte oldCpuBus = cpuBus;
        cpuBus = (byte) ((data & 0xff) << 2 & 0x80 | (data & 0xff) << 2 & 0x40 | (data & 0xff) << 1 & 0x10);

        if (((oldCpuBus ^ cpuBus) & 0x10) != 0) {
            for (final FloppyDrive drive : drives) {
                if (drive.isPowerOn()) {
                    drive.attention((cpuBus & 0x10) == 0);
                }
            }
        }
        for (final FloppyDrive drive : drives) {
            if (drive.isPowerOn()) {
                setDriveBus(drive.getID());
            }
        }
        updatePorts();
    }

    // triggered by SerialIECDevices
    public final byte deviceRead() {
        return drvPort;
    }

    // triggered by SerialIECDevices
    public final void deviceWrite(final int deviceNum, final byte data) {
        drvBus[deviceNum] = data;
        if (drives.length == 1 && drives[0].getID() == deviceNum) {
            clearDriveReadHistory();
        }
        updatePorts();
    }

    // triggered by VIA6522BC
    public final void updateDrive(final int deviceNum, final byte byt) {
        drvData[deviceNum] = (byte) ~byt;
        setDriveBus(deviceNum, true);
        updatePorts();
    }

    protected final void setDriveBus(final int deviceNum) {
        setDriveBus(deviceNum, false);
    }

    private void setDriveBus(final int deviceNum, final boolean viaWrite) {
        FloppyDrive device = null;
        for (final FloppyDrive drive : drives) {
            if (drive.getID() == deviceNum) {
                device = drive;
                break;
            }
        }
        final boolean ciaBus = device != null && device.getFloppyType() == FloppyType.C1581;
        int acknowledge = ciaBus ? drvData[deviceNum] | cpuBus : ~drvData[deviceNum] ^ cpuBus;
        final byte previous = drvBus[deviceNum];
        drvBus[deviceNum] = (byte) ((drvData[deviceNum] & 0xff) << 3 & 0x40
                | (drvData[deviceNum] & 0xff) << 6 & (acknowledge & 0xff) << 3 & 0x80);
        final int changed = (previous ^ drvBus[deviceNum]) & (CLOCK | DATA);
        if (changed != 0 && drives.length == 1 && device != null && device.getFloppyType() == FloppyType.C1541_II) {
            // A host-driven ATN change can supersede a pending VIA DATA transition.
            final long cycle = viaWrite ? device.getEventScheduler().getTime(Phase.PHI2) : Long.MIN_VALUE;
            if ((changed & CLOCK) != 0) {
                driveClockChangedAt = driveClockChangedAt == cycle ? Long.MIN_VALUE : cycle;
            }
            if ((changed & DATA) != 0) {
                driveDataChangedAt = driveDataChangedAt == cycle ? Long.MIN_VALUE : cycle;
            }
        }
    }

    protected final void updatePorts() {
        cpuPort = resolveSerialDevices(cpuBus);
        for (final FloppyDrive drive : drives) {
            cpuPort &= drvBus[drive.getID()];
        }
        drvPort = (byte) ((cpuPort & 0xff) >> 4 & 0x4 | (cpuPort & 0xff) >> 7 | (cpuBus & 0xff) << 3 & 0x80);
    }

    private byte resolveSerialDevices(byte pins) {
        for (final SerialIECDevice serialDevice : serialDevices) {
            pins &= drvBus[serialDevice.getID()];
        }
        return pins;
    }

}