GMod2.java

package libsidplay.components.cart.supported;

import libsidplay.common.Event;
import libsidplay.components.cart.Cartridge;
import libsidplay.components.cart.supported.core.Flash040Core;
import libsidplay.components.cart.supported.core.M93C86;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;

import static java.nio.charset.StandardCharsets.US_ASCII;

/**
 * <PRE>
 * "GMod2" Cartridge (<a href="http://wiki.icomp.de/wiki/GMod2">GMod2</a>)
 * <p>
 * - this cart comes in 7 sizes, 8Kb, 16Kb, 32Kb, 64Kb, 128Kb, 256Kb, and 512Kb.
 * - ROM is always mapped in at $8000-$9FFF.
 * <p>
 * There is one register mapped to $DE00. The register is always active, and there is no way to disable it.
 * bit 	r/w 	Flash ROM 	EEPROM 	Expansion Port
 * 7 	rw 	1=write enable (write) 	Data output (read) 	-
 * 6 	w 	- 	Chip select (1=selected) 	EXROM (0=active)
 * 5 	w 	Bank Selection Bit#5 	Clock 	-
 * 4 	w 	Bank Selection Bit#4 	Data input 	-
 * 3 	w 	Bank Selection Bit#3 	- 	-
 * 2 	w 	Bank Selection Bit#2 	- 	-
 * 1 	w 	Bank Selection Bit#1 	- 	-
 * 0 	w 	Bank Selection Bit#0 	- 	-
 * <p>
 * <p>
 * bit7 	bit6 	mode
 * 0 	0 	regular 8K Game mode, ROM readable at $8000
 * 0 	1 	EEPROM selected, Flash inactive. EEPROM can be used via bits 4/5/7
 * 1 	0 	illegal, do not use
 * 1 	1 	Flash ROM writing enabled
 * </PRE>
 *
 * @author Ken Händel
 *
 */
public class GMod2 extends Cartridge {
    private static final int BANK_SIZE = 0x2000;
    private static final int BANK_COUNT = 64;
    private final byte[] flashData = new byte[BANK_COUNT * BANK_SIZE];
    private final Flash040Core.Flash040Context flash = new Flash040Core.Flash040Context();
    private final M93C86 eeprom;
    protected int currentRomBank;
    private int register;

    private final Flash040Core core = new Flash040Core() {
        @Override protected long maincpuClk() {
            return pla.getCPU().getEventScheduler().getTime(Event.Phase.PHI1);
        }
        @Override protected void alarmUnset(Event alarm) {
            pla.getCPU().getEventScheduler().cancel(alarm);
        }
        @Override protected void alarmSet(Event alarm, long time) {
            var scheduler = pla.getCPU().getEventScheduler();
            scheduler.cancel(alarm);
            scheduler.scheduleAbsolute(alarm, time, Event.Phase.PHI1);
        }
    };

    public GMod2(DataInputStream input, PLA pla) throws IOException {
        super(pla);
        Arrays.fill(flashData, (byte) 0xff);
        load(input);
        var scheduler = pla.getCPU().getEventScheduler();
        core.flash040coreInit(flash, scheduler, Flash040Core.Flash040Type.FLASH040_TYPE_B, flashData);
        eeprom = new M93C86(scheduler);
    }

    private void load(DataInputStream input) throws IOException {
        byte[] header = new byte[16];
        int headerLength;
        while ((headerLength = readChipHeader(input, header)) != 0) {
            if (headerLength != header.length) {
                throw new EOFException("Truncated GMod2 CHIP header");
            }
            if (!"CHIP".equals(new String(header, 0, 4, US_ASCII))) {
                throw new IOException("Invalid GMod2 CHIP signature");
            }
            long packetLength = (long) u16(header, 4) << 16 | u16(header, 6);
            int type = u16(header, 8);
            int bank = u16(header, 10);
            int address = u16(header, 12);
            int size = u16(header, 14);
            if (packetLength < header.length + size || (type != 0 && type != 2)
                    || bank >= BANK_COUNT || (address != 0x8000 && address != 0xa000) || size != BANK_SIZE) {
                throw new IOException("Invalid GMod2 CHIP record");
            }
            input.readFully(flashData, bank * BANK_SIZE, size);
            skipFully(input, packetLength - header.length - size, "Truncated GMod2 CHIP padding");
        }
    }

    private static int u16(byte[] bytes, int offset) {
        return (bytes[offset] & 0xff) << 8 | bytes[offset + 1] & 0xff;
    }

    private boolean flashEnabled() { return (register & 0xc0) == 0xc0; }
    private int flashAddress(int address) { return currentRomBank * BANK_SIZE + (address & 0x1fff); }

    private final Bank io1Bank = new Bank() {
        @Override public byte read(int address) {
            int bus = pla.getDisconnectedBusBank().read(address) & 0xff;
            return (byte) (eeprom.isOutputDriving() ? (bus & 0x7f) | eeprom.m93c86_read_data() << 7 : bus);
        }

        @Override public void write(int address, byte value) {
            register = value & 0xff;
            currentRomBank = register & 0x3f;
            // Bank bits 4/5 are also EEPROM input/clock, even during flash commands.
            eeprom.m93c86_write_data((register >>> 4) & 1);
            eeprom.m93c86_write_select((register >>> 6) & 1);
            eeprom.m93c86_write_clock((register >>> 5) & 1);
            // Flash mode alters writes only. Read/VIC mapping follows physical EXROM.
            pla.setGameExrom(true, (register & 0x40) != 0);
        }
    };

    private final Bank romlBank = new Bank() {
        @Override public byte read(int address) {
            return core.flash040CoreRead(flash, flashAddress(address));
        }
    };

    private final Bank romhBank = new Bank() {
        @Override public byte read(int address) { return pla.getDisconnectedBusBank().read(address); }
        @Override public void write(int address, byte value) {
            if (flashEnabled()) core.flash040CoreStore(flash, flashAddress(address), value);
        }
    };

    @Override public Bank getRoml() { return romlBank; }
    @Override public Bank getRomh() { return romhBank; }
    @Override public Bank getIO1() { return io1Bank; }

    @Override public void installBankHooks(Bank[] cpuReadMap, Bank[] cpuWriteMap) {
        if (flashEnabled()) {
            Arrays.fill(cpuWriteMap, 8, 13, pla.getDisconnectedBusBank());
            cpuWriteMap[13] = pla.getIOBank();
            Arrays.fill(cpuWriteMap, 14, 16, romhBank);
        }
    }

    @Override public void reset() {
        super.reset();
        core.flash040CoreReset(flash);
        eeprom.reset();
        io1Bank.write(0xde00, (byte) 0);
    }
}