C1581.java

/*
 * 1581 wiring follows VICE memiec.c and cia1581d.c (VICE project, GPL-2.0-or-later).
 * Reference: d928b850b7ef4c1b1826a6efd175d8eaa80344d8.
 */
package libsidplay.components.c1541;

import libsidplay.common.CIAChipModel;
import libsidplay.common.Event;
import libsidplay.common.EventScheduler;
import libsidplay.components.iec.IECBus;
import libsidplay.components.mos6510.MOS6510;
import libsidplay.components.mos6526.MOS6526;

import java.util.Arrays;

/**
 * ROM-executing 2 MHz 1581. IEC traffic is handled by the drive CPU and CIA.
 */
public final class C1581 implements FloppyDrive {
    /**
     * Floppy device number (8-11).
     */
    private final int id;
    /**
     * IEC bus shared with the C64 and other drives.
     */
    private final IECBus bus;
    /**
     * Scheduler clocked at the drive CPU frequency of 2 MHz.
     */
    private final EventScheduler context = new EventScheduler();
    /**
     * 8KB drive RAM at addresses $0000-$1FFF.
     */
    private final byte[] ram = new byte[0x2000];
    /**
     * Active 32KB drive ROM at addresses $8000-$FFFF.
     */
    private final byte[] rom;
    /**
     * Stock ROM restored when the custom ROM is removed.
     */
    private final byte[] defaultRom;
    /**
     * Drive CPU executing the installed DOS ROM.
     */
    private final MOS6510 cpu;
    /**
     * CIA connected to IEC, head selection, motor control and the activity LED.
     */
    private final MOS6526 cia;
    /**
     * WD1772-compatible controller for D81 media.
     */
    private final WD1770 controller;
    /**
     * Whether the drive participates in emulation.
     */
    private boolean powerOn;
    /**
     * Last drive CPU bus value, returned for unconnected addresses.
     */
    private byte lastData;

    /**
     * Create a 2 MHz 1581 drive.
     *
     * @param bus IEC bus
     * @param id  floppy device number (8-11)
     * @param rom 32KB 1581 ROM
     * @throws IllegalArgumentException ROM has an unsupported size
     */
    public C1581(IECBus bus, int id, byte[] rom) {
        if (rom.length != 0x8000) throw new IllegalArgumentException("1581 ROM must contain 32768 bytes");
        this.bus = bus;
        this.id = id;
        this.rom = rom.clone();
        defaultRom = rom.clone();
        cpu = new MOS6510(context) {
            @Override
            protected byte cpuRead(int address) {
                if (address < 0x2000) return lastData = ram[address];
                if (address >= 0x4000 && address < 0x6000) return lastData = cia.read(address & 15);
                if (address >= 0x6000 && address < 0x8000) return lastData = controller.read(address & 3);
                if (address >= 0x8000) return lastData = C1581.this.rom[address & 0x7fff];
                return lastData;
            }

            @Override
            protected void cpuWrite(int address, byte value) {
                lastData = value;
                if (address < 0x2000) ram[address] = value;
                else if (address >= 0x4000 && address < 0x6000) cia.write(address & 15, value);
                else if (address >= 0x6000 && address < 0x8000) controller.write(address & 3, value);
            }
        };
        controller = new WD1770(() -> context.getTime(Event.Phase.PHI2), true);
        // VICE also uses its 6526 core here, despite the physical drive containing an 8520.
        cia = new MOS6526(context, CIAChipModel.MOS6526) {
            @Override
            public void interrupt(boolean state) {
                if (state) cpu.triggerIRQ();
                else cpu.clearIRQ();
            }

            @Override
            public void pulse() {
            }

            @Override
            public byte readPRA() {
                int pins = ((id - 8) << 3) | (controller.diskChange() ? 0 : 0x80);
                return (byte) ((pins & ~regs[DDRA]) | (regs[PRA] & regs[DDRA]));
            }

            @Override
            public byte readPRB() {
                return (byte) (((regs[PRB] & 0x1a | bus.deviceRead()) ^ 0x85)
                        | (controller.isWriteProtected() ? 0 : 0x40));
            }

            @Override
            public void writePRA(byte value, boolean ddrChange) {
                // PA0 selects the inverted head; PA2 is active-low motor control.
                controller.setSide((value & 1) != 0 ? 0 : 1);
                controller.setMotor((value & 4) == 0);
                controller.setLED((value & 0x40) != 0);
            }

            @Override
            public void writePRB(byte value) {
                bus.updateDrive(id, value);
                bus.setFastSerialDirection(id, (value & 0x20) != 0);
            }

            @Override
            protected void serialPins(boolean sp, boolean cnt) {
                bus.writeFastSerial(id, sp, cnt);
            }
        };
        bus.connectFastSerial(id, cia);
    }

    @Override
    public int getID() {
        return id;
    }

    @Override
    public EventScheduler getEventScheduler() {
        return context;
    }

    @Override
    public MOS6510 getCPU() {
        return cpu;
    }

    @Override
    public MOS6526 getCIA() {
        return cia;
    }

    @Override
    public byte[] getRAM() {
        return ram;
    }

    @Override
    public byte[] getROM() {
        return rom;
    }

    @Override
    public void setCustomKernalRom(byte[] customRom) {
        if (customRom != null && customRom.length != rom.length)
            throw new IllegalArgumentException("1581 ROM must contain 32768 bytes");
        System.arraycopy(customRom != null ? customRom : defaultRom, 0, rom, 0, rom.length);
    }

    @Override
    public WD1770 getDiskController() {
        return controller;
    }

    @Override
    public double getClockFrequency() {
        return 2_000_000;
    }

    @Override
    public void setPowerOn(boolean on) {
        powerOn = on;
    }

    @Override
    public boolean isPowerOn() {
        return powerOn;
    }

    @Override
    public FloppyType getFloppyType() {
        return FloppyType.C1581;
    }

    @Override
    public String getDiskName() {
        return controller.getDiskName();
    }

    @Override
    public void attention(boolean asserted) {
        cia.setFlag(asserted);
    }

    @Override
    public void reset() {
        context.reset();
        Arrays.fill(ram, (byte) 0);
        lastData = 0;
        cia.reset();
        controller.reset();
        controller.setMotor(false);
        bus.setFastSerialDirection(id, false);
        bus.writeFastSerial(id, true, true);
        bus.deviceWrite(id, (byte) 0xc0);
        cpu.triggerRST();
    }
}