Am29F040B.java

package libsidplay.components.cart.supported.core;

import libsidplay.common.EventScheduler;
import libsidplay.components.cart.supported.core.Flash040Core.Flash040Context;

import java.util.Arrays;

/**
 * EasyFlash's AMD flash chip. Command decoding is independent of an erase that
 * has been suspended, so autoselect and programming can return to that erase.
 * Timings and polling follow AMD publication 21445, revision E:
 * https://instrumentation.obs.carnegiescience.edu/ccd/parts/AM29F040B.pdf
 * Typical operation times are deterministic; suspend uses the 20 us maximum.
 */
final class Am29F040B {
    private enum Command {
        READ, UNLOCK_1, UNLOCK_2, PROGRAM, ERASE_UNLOCK_1, ERASE_UNLOCK_2,
        ERASE_SELECT, AUTOSELECT, PROGRAM_ERROR
    }

    private enum Operation { NONE, PROGRAM, SELECTING, SECTOR_ERASE, CHIP_ERASE }

    private final Flash040Core core;
    private final Flash040Context chip;
    private final EventScheduler scheduler;
    private Command command = Command.READ;
    private Operation operation = Operation.NONE;
    private int selectedSectors;
    private int pendingSectors;
    private boolean suspended;
    private long deadline;
    private long sectorCycles;
    private long eraseRemaining;
    private long suspendDeadline;
    private int programAddress;
    private int programData;
    private boolean programFailed;
    private int toggleBits;

    Am29F040B(Flash040Core core, Flash040Context chip, EventScheduler scheduler) {
        this.core = core;
        this.chip = chip;
        this.scheduler = scheduler;
    }

    private long cycles(double seconds) {
        double frequency = scheduler.getCyclesPerSecond();
        if (!(frequency > 0)) {
            throw new IllegalStateException("Flash timing requires the CPU clock frequency");
        }
        return (long) Math.ceil(seconds * frequency);
    }

    private boolean selected(int address) {
        return (selectedSectors & (1 << (address >>> 16))) != 0;
    }

    private void schedule() {
        long next = suspendDeadline == 0 ? deadline : Math.min(deadline, suspendDeadline);
        core.alarmUnset(chip.eraseAlarm);
        core.alarmSet(chip.eraseAlarm, next);
    }

    void store(int address, byte data) {
        int value = data & 0xff;
        long now = core.maincpuClk();
        switch (operation) {
            case PROGRAM:
            case CHIP_ERASE:
                return;
            case SELECTING:
                if (value == 0x30) {
                    selectedSectors |= 1 << (address >>> 16);
                    pendingSectors = selectedSectors;
                    deadline = now + cycles(50e-6);
                    schedule();
                } else if (value == 0xb0) {
                    core.alarmUnset(chip.eraseAlarm);
                    operation = Operation.NONE;
                    suspended = true;
                    eraseRemaining = sectorCycles;
                } else {
                    reset();
                }
                return;
            case SECTOR_ERASE:
                if (value == 0xb0 && suspendDeadline == 0) {
                    suspendDeadline = now + cycles(20e-6);
                    schedule();
                }
                return;
            default:
                break;
        }

        // The fourth programming cycle is always payload, including F0.
        if (command == Command.PROGRAM) {
            command = Command.READ;
            if (suspended && selected(address)) {
                return;
            }
            programAddress = address;
            programData = value;
            programFailed = (chip.flashData[address] & value & 0xff) != value;
            operation = Operation.PROGRAM;
            deadline = now + cycles(programFailed ? 300e-6 : 7e-6);
            schedule();
            return;
        }
        if (value == 0xf0) {
            command = Command.READ;
            programFailed = false;
            return;
        }
        switch (command) {
            case READ:
                if (suspended && value == 0x30) {
                    suspended = false;
                    operation = Operation.SECTOR_ERASE;
                    deadline = now + eraseRemaining;
                    schedule();
                } else if ((address & 0x7ff) == 0x555 && value == 0xaa) {
                    command = Command.UNLOCK_1;
                }
                break;
            case UNLOCK_1:
                command = (address & 0x7ff) == 0x2aa && value == 0x55
                        ? Command.UNLOCK_2 : Command.READ;
                break;
            case UNLOCK_2:
                command = Command.READ;
                if ((address & 0x7ff) == 0x555) {
                    if (value == 0x90) command = Command.AUTOSELECT;
                    else if (value == 0xa0) command = Command.PROGRAM;
                    else if (value == 0x80 && !suspended) command = Command.ERASE_UNLOCK_1;
                }
                break;
            case ERASE_UNLOCK_1:
                command = (address & 0x7ff) == 0x555 && value == 0xaa
                        ? Command.ERASE_UNLOCK_2 : Command.READ;
                break;
            case ERASE_UNLOCK_2:
                command = (address & 0x7ff) == 0x2aa && value == 0x55
                        ? Command.ERASE_SELECT : Command.READ;
                break;
            case ERASE_SELECT:
                command = Command.READ;
                if ((address & 0x7ff) == 0x555 && value == 0x10) {
                    operation = Operation.CHIP_ERASE;
                    deadline = now + cycles(8);
                    schedule();
                } else if (value == 0x30) {
                    selectedSectors = 1 << (address >>> 16);
                    pendingSectors = selectedSectors;
                    sectorCycles = cycles(1);
                    operation = Operation.SELECTING;
                    deadline = now + cycles(50e-6);
                    schedule();
                }
                break;
            default:
                // Autoselect and failed programming require F0 before new commands.
                break;
        }
    }

    byte read(int address) {
        if (operation == Operation.PROGRAM || command == Command.PROGRAM_ERROR) {
            toggleBits ^= 0x40;
            return (byte) (((programData ^ 0x80) & 0x80) | (toggleBits & 0x40)
                    | (command == Command.PROGRAM_ERROR ? 0x20 : 0));
        }
        if (operation != Operation.NONE) {
            toggleBits ^= 0x40;
            if (operation == Operation.CHIP_ERASE || selected(address)) toggleBits ^= 4;
            return (byte) ((toggleBits & 0x40)
                    | (operation == Operation.CHIP_ERASE || selected(address) ? toggleBits & 4 : 0)
                    | (operation == Operation.SELECTING ? 0 : 8));
        }
        if (command == Command.AUTOSELECT) {
            switch (address & 0xff) {
                case 0: return 0x01;
                case 1: return (byte) 0xa4;
                case 2: return 0; // EasyFlash models unprotected sectors.
                default: return chip.flashData[address];
            }
        }
        if (suspended && selected(address)) {
            toggleBits ^= 4;
            return (byte) (0x80 | (toggleBits & 0x44));
        }
        return chip.flashData[address];
    }

    void alarm() {
        core.alarmUnset(chip.eraseAlarm);
        long now = core.maincpuClk();
        switch (operation) {
            case SELECTING:
                operation = Operation.SECTOR_ERASE;
                deadline = now + sectorCycles;
                schedule();
                break;
            case PROGRAM:
                chip.flashData[programAddress] &= (byte) programData;
                chip.flashDirty = 1;
                operation = Operation.NONE;
                command = programFailed ? Command.PROGRAM_ERROR : Command.READ;
                break;
            case CHIP_ERASE:
                Arrays.fill(chip.flashData, (byte) 0xff);
                chip.flashDirty = 1;
                operation = Operation.NONE;
                break;
            case SECTOR_ERASE:
                if (deadline <= now) {
                    int sector = Integer.numberOfTrailingZeros(pendingSectors);
                    Arrays.fill(chip.flashData, sector << 16, (sector + 1) << 16, (byte) 0xff);
                    chip.flashDirty = 1;
                    pendingSectors &= ~(1 << sector);
                    if (pendingSectors == 0) {
                        selectedSectors = 0;
                        operation = Operation.NONE;
                        suspendDeadline = 0;
                        break;
                    }
                    deadline += sectorCycles;
                }
                if (suspendDeadline != 0 && suspendDeadline <= now) {
                    eraseRemaining = deadline - now;
                    suspendDeadline = 0;
                    suspended = true;
                    operation = Operation.NONE;
                } else {
                    schedule();
                }
                break;
            default:
                break;
        }
    }

    void reset() {
        core.alarmUnset(chip.eraseAlarm);
        command = Command.READ;
        operation = Operation.NONE;
        suspended = false;
        selectedSectors = pendingSectors = 0;
        deadline = sectorCycles = eraseRemaining = suspendDeadline = 0;
        programAddress = programData = toggleBits = 0;
        programFailed = false;
    }
}