M93C86.java

/**
 * m93c86.c
 * <p>
 * Written by
 * Groepaz/Hitmen <groepaz@gmx.net>
 * <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.
 *
 */
package libsidplay.components.cart.supported.core;

import libsidplay.common.Event;
import libsidplay.common.EventScheduler;

import java.util.Arrays;

/**
 * M93C86 in x16 organization, as wired by GMod2 (ST DS1077).
 * Write/erase use the specified 5 ms maximum as a deterministic emulation time.
 */
public class M93C86 {
    private enum Command { NONE, SPECIAL, READ, WRITE, ERASE, WEN, WDS, WRAL, ERAL }

    private final int[] words = new int[1024];
    private final EventScheduler scheduler;
    private final Event completion;
    private boolean selected;
    private boolean clock;
    private int dataIn;
    private boolean armed;
    private int inputCount;
    private int inputShift;
    private Command command = Command.NONE;
    private int address;
    private boolean reading;
    private int readBits;
    private int dataOut;
    private boolean writeEnabled;
    private boolean busy;
    private boolean statusAvailable;
    private Command pending = Command.NONE;
    private int pendingAddress;
    private int pendingData;

    public M93C86(EventScheduler scheduler) {
        this.scheduler = scheduler;
        completion = Event.of("M93C86 write", e -> finishWrite());
        Arrays.fill(words, 0xffff);
    }

    public boolean isOutputDriving() {
        return selected && (busy || statusAvailable || reading);
    }

    /** Reading the output pin never advances the command, busy period or read stream. */
    public int m93c86_read_data() {
        if (busy) return 0;
        if (statusAvailable) return 1;
        return dataOut;
    }

    public void m93c86_write_data(int value) { dataIn = value & 1; }

    public void m93c86_write_select(int value) {
        boolean next = (value & 1) != 0;
        if (selected && !next) {
            if (!busy && armed) finishFrame();
            clearFrame();
        } else if (!selected && next) {
            clearFrame();
            // Each frame starts with CS rising while the serial clock is low.
            armed = !clock;
        }
        selected = next;
    }

    public void m93c86_write_clock(int value) {
        boolean next = (value & 1) != 0;
        if (selected && armed && next && !clock && !busy) receiveBit();
        // Pin levels matter while deselected too, including before the next CS edge.
        clock = next;
    }

    private void receiveBit() {
        if (reading) {
            if (readBits == 0) {
                address = (address + 1) & 1023;
                readBits = 16;
            }
            dataOut = (words[address] >>> --readBits) & 1;
            return;
        }
        if (inputCount == 0 && dataIn == 0) return; // Ignore leading zeroes before the start bit.
        if (inputCount >= 30) return; // An overlong frame stays invalid until CS drops.
        if (inputCount == 0) statusAvailable = false;
        inputShift = (inputShift << 1) | dataIn;
        inputCount++;
        if (inputCount == 3) {
            switch (inputShift & 3) {
                case 0: command = Command.SPECIAL; break;
                case 1: command = Command.WRITE; break;
                case 2: command = Command.READ; break;
                case 3: command = Command.ERASE; break;
            }
        }
        if (inputCount == 13) {
            address = inputShift & 1023;
            if (command == Command.SPECIAL) {
                switch (address >>> 8) {
                    case 0: command = Command.WDS; break;
                    case 1: command = Command.WRAL; break;
                    case 2: command = Command.ERAL; break;
                    case 3: command = Command.WEN; break;
                }
            } else if (command == Command.READ) {
                reading = true;
                readBits = 16;
                dataOut = 0; // Dummy bit on the last address clock, then MSB first.
            }
        }
    }

    private void finishFrame() {
        if (command == Command.WEN && inputCount == 13) writeEnabled = true;
        else if (command == Command.WDS && inputCount == 13) writeEnabled = false;
        else if (writeEnabled && ((inputCount == 29 && (command == Command.WRITE || command == Command.WRAL))
                || (inputCount == 13 && (command == Command.ERASE || command == Command.ERAL)))) {
            double frequency = scheduler.getCyclesPerSecond();
            if (!(frequency > 0)) throw new IllegalStateException("EEPROM timing requires the CPU clock frequency");
            pending = command;
            pendingAddress = address;
            pendingData = inputShift & 0xffff;
            busy = true;
            statusAvailable = true;
            long deadline = scheduler.getTime(Event.Phase.PHI1) + (long) Math.ceil(0.005 * frequency);
            scheduler.scheduleAbsolute(completion, deadline, Event.Phase.PHI1);
        }
    }

    private void finishWrite() {
        switch (pending) {
            case WRITE: words[pendingAddress] = pendingData; break;
            case ERASE: words[pendingAddress] = 0xffff; break;
            case WRAL: Arrays.fill(words, pendingData); break;
            case ERAL: Arrays.fill(words, 0xffff); break;
            default: break;
        }
        pending = Command.NONE;
        busy = false;
    }

    private void clearFrame() {
        armed = false;
        inputCount = inputShift = address = readBits = dataOut = 0;
        command = Command.NONE;
        reading = false;
    }

    /** Emulator power-on reset: completed writes survive, pending work and protocol state do not. */
    public void reset() {
        scheduler.cancel(completion);
        clearFrame();
        selected = clock = writeEnabled = busy = statusAvailable = false;
        dataIn = pendingAddress = pendingData = 0;
        pending = Command.NONE;
    }
}