All files / src cmos.js

96.25% Statements 154/160
95.78% Branches 91/95
88.88% Functions 40/45
95.89% Lines 140/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339                  90x               90x       61x 6x 3520x         90x     9296x       2797x     90x 328x 330x 332x       29x                 9x   1x 2x   3x 3x 3x       1x 3x                           25x 25x   25x 25x 25x 10x   7x 7x       32x 32x   5x 5x 2x 2x               1449x 1449x 1449x 1449x 1449x 1449x 1449x 4098x   1449x 1449x 1449x     1449x   1449x 1449x   1449x   1449x 1444x   1449x 34x   1449x 6x 6x           1449x 1449x       1464x       16x 14x 14x         175x 175x                             53x 53x 52x 52x 52x             52x               215x 163x 163x   215x 215x 215x 215x 215x         159x 104x 104x         4108x 4108x       3267x 3267x 3267x       1914x                   841x       29x 29x 10x 10x   19x 19x 19x 19x       919x 919x 919x 919x   919x     919x 822x 822x   97x         2489x             2391x   2352x 2325x 2325x       999x   331x   332x   332x   331x     27x     39x         10961x 10961x 10945x 10945x 10945x       10961x 10961x 10961x 10945x 10945x 968x 16x 16x   952x       29x 29x   309x 309x   305x 305x   305x 305x            
// CMOS layout: bytes 0-13 are RTC internal registers; bytes 14-63 are the 50
// bytes of user storage.  Storage byte 11 (= CMOS address 25 = 0x19) holds
// the BBC Master DFS configuration byte whose bits [1:0] are the WD1770 step
// rate (*CONFIGURE FDRIVE):  0=6ms  1=12ms  2=20ms  3=30ms.
// The correct default is FDRIVE 0 (6ms, value 0xc8).  The previous default
// 0xca had bits[1:0]=0b10 (20ms), which caused disc-streaming demos such as
// STNICC-beeb to hang on the Master 128 because the WD1770 seek overran the
// vsync window.  Confirmed by @tom-seddon (b2 emulator):
// https://github.com/mattgodbolt/jsbeeb/issues/576
const defaultCmos = Object.freeze([
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0xeb, 0x00,
    0xc9, 0xff, 0xff, 0x12, 0x00, 0x17, 0xc8, 0x1e, 0x05, 0x00, 0x35, 0xa6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
 
// A store saved before it held the whole chip: its first 48 bytes, longer if a program wrote past them.
const OldestStoreBytes = 48;
 
/** A copy of `bytes` as a whole store, the defaults filling what an older page's lacks; throws on any other shape. */
function fullStore(bytes) {
    if (!Array.isArray(bytes) || bytes.length < OldestStoreBytes || bytes.length > defaultCmos.length)
        throw new Error(`the settings are not ${OldestStoreBytes} to ${defaultCmos.length} bytes`);
    return Array.from(defaultCmos, (byte, address) => bytes[address] ?? byte);
}
 
// The RTC holds a two-digit year and MOS 3.20 prints it after a fixed century (LDA #&19 at &9880 in ROM 15);
// the ROM jsbeeb ships has that byte patched to &20 (#362), so every year it shows is 20yy.
const MosCentury = 2000;
 
function toBcd(value) {
    return parseInt(value.toString(10), 16);
}
 
function fromBcd(value) {
    return parseInt(value.toString(16), 10);
}
 
const TimeRegisters = Object.freeze({
    0: { limit: 60, get: (time) => time.getSeconds(), set: (time, value) => time.setSeconds(value) },
    2: { limit: 60, get: (time) => time.getMinutes(), set: (time, value) => time.setMinutes(value) },
    4: { limit: 24, get: (time) => time.getHours(), set: (time, value) => time.setHours(value) },
});
 
function isBcdBelow(value, limit) {
    return value >> 4 < 10 && (value & 0x0f) < 10 && fromBcd(value) < limit;
}
 
export { defaultCmos };
 
// A shared session (src/lockstep.js) runs the same machine on several computers in step, one of them hosting.
// The session clock holds the host's local time as if it were UTC and is read and set through this view, so
// every computer shows the host's time, whatever its own time zone.
function utcView(date) {
    return {
        getSeconds: () => date.getUTCSeconds(),
        getMinutes: () => date.getUTCMinutes(),
        getHours: () => date.getUTCHours(),
        getDay: () => date.getUTCDay(),
        getDate: () => date.getUTCDate(),
        getMonth: () => date.getUTCMonth(),
        getFullYear: () => date.getUTCFullYear(),
        setSeconds: (value) => date.setUTCSeconds(value),
        setMinutes: (value) => date.setUTCMinutes(value),
        setHours: (value) => date.setUTCHours(value),
        setFullYear: (year, month, day) => date.setUTCFullYear(year, month, day),
        getTime: () => date.getTime(),
    };
}
 
/**
 * CMOS persistence backed by a browser storage object, which can be unavailable, full or holding
 * something other than what was last saved.
 *
 * @param {function(): Storage} getStorage typically `() => window.localStorage`. Reading that
 *   property is itself what throws when a page is refused storage, so it happens per call, inside
 *   the try.
 * @param {function(*)} onSaveFailure called with the error the first time a save fails
 */
export function localStoragePersistence(getStorage, onSaveFailure) {
    let saveFailureReported = false;
    return {
        load() {
            try {
                const stored = getStorage().cmosRam;
                if (!stored) return null;
                return fullStore(JSON.parse(stored));
            } catch (error) {
                console.log(`Unable to read the stored CMOS settings: ${error?.message ?? error}`);
                return null;
            }
        },
        save(data) {
            try {
                getStorage().cmosRam = JSON.stringify(data);
            } catch (error) {
                console.log(`Unable to store the CMOS settings: ${error?.message ?? error}`);
                if (saveFailureReported) return;
                saveFailureReported = true;
                onSaveFailure(error);
            }
        },
    };
}
 
export class Cmos {
    constructor(persistence, cmosOverride, econet) {
        this.store = persistence ? persistence.load() : null;
        this.persistence = persistence;
        this.enabled = false;
        this.isRead = false;
        this.addressSelect = false;
        this.dataSelect = false;
        this.cmosAddr = 0;
        this.now = () => Date.now();
        // A replay repeats writes the machine made, or makes some it never will (a rewind preview), so it keeps none.
        this.replaying = () => false;
        this.utc = false;
        this.timeOffset = 0;
        // The 146818 keeps the day, month and year in separate registers and checks none of them, so bytes that
        // do not name a real day are held as written until they do.
        this.heldDate = null;
        // Likewise a seconds, minutes or hours byte that is not a time, keyed by register, while the clock runs on.
        this.heldTime = {};
        this.beforeSession = null;
        /** @type {import("./replay.js").InputLog | null} */
        this.inputLog = null;
 
        if (!this.store) {
            this.store = [...defaultCmos];
        }
        if (cmosOverride) {
            this.store = cmosOverride(this.store);
        }
        if (econet) {
            this.store[0xe] = econet.stationId;
            Iif (this.store[0xf] === 0) {
                // Catch an invalid FS configuration setting (possibly as a result of using a prior version that didn't set a default of 254 in CMOS)
                this.store[0xf] = 254;
            }
        }
        // What the machine has written, which a restore leaves alone: the settings a page loads next.
        this.kept = [...this.store];
        this.save();
    }
 
    save() {
        this.persistence?.save(this.kept);
    }
 
    keep(address, value) {
        if (!this.persistence || this.replaying()) return;
        this.kept[address] = value;
        this.save();
    }
 
    /** The settings, the offset a program set the clock to, any clock registers held as written, and the bus. */
    snapshotState() {
        const { store, timeOffset, heldDate, heldTime, enabled, isRead, addressSelect, dataSelect, cmosAddr } = this;
        return {
            store: [...store],
            timeOffset,
            heldDate: heldDate && { ...heldDate },
            heldTime: { ...heldTime },
            enabled,
            isRead,
            addressSelect,
            dataSelect,
            cmosAddr,
        };
    }
 
    /** Keeps nothing restored; a state saved with only the bus leaves the settings and clock as they are. */
    restoreState(state) {
        const { enabled, isRead, addressSelect, dataSelect, cmosAddr } = state;
        if (state.store) {
            const store = fullStore(state.store);
            const { timeOffset, heldDate, heldTime } = state;
            Object.assign(this, {
                store,
                timeOffset,
                heldDate: heldDate && { ...heldDate },
                heldTime: { ...heldTime },
            });
        }
        Object.assign(this, { enabled, isRead, addressSelect, dataSelect, cmosAddr });
    }
 
    /**
     * Joins a shared session, whose snapshot then brings in the host's chip: until the session is left
     * nothing is stored, and the clock reads `now`, the session's wall time in milliseconds.
     */
    joinSession(now) {
        if (!this.beforeSession) {
            const { persistence, store, utc, timeOffset, heldDate, heldTime } = this;
            this.beforeSession = { persistence, store, now: this.now, utc, timeOffset, heldDate, heldTime };
        }
        this.store = [...this.store];
        this.heldTime = { ...this.heldTime };
        this.persistence = null;
        this.now = now;
        this.utc = true;
    }
 
    /** Back to this machine's own settings and clock, as they were before the session. */
    leaveSession() {
        if (!this.beforeSession) return;
        Object.assign(this, this.beforeSession);
        this.beforeSession = null;
    }
 
    // Whole seconds, all the clock keeps, so that a replay is handed the second each read saw.
    clockMs() {
        const ms = Math.floor(this.now() / 1000) * 1000;
        return this.inputLog ? this.inputLog.sample("rtc", ms) : ms;
    }
 
    bbcDateTime() {
        const result = new Date(this.clockMs() + this.timeOffset);
        result.setMilliseconds(0);
        return this.utc ? utcView(result) : result;
    }
 
    calendarRegisters(current) {
        return (
            this.heldDate ?? {
                day: toBcd(current.getDate()),
                month: toBcd(current.getMonth() + 1),
                year: toBcd(current.getFullYear() % 100),
            }
        );
    }
 
    setTimeFrom(bbcTime) {
        this.timeOffset = bbcTime.getTime() - this.clockMs();
    }
 
    writeTime(register, value) {
        const { limit, set } = TimeRegisters[register];
        if (!isBcdBelow(value, limit)) {
            this.heldTime[register] = value;
            return;
        }
        delete this.heldTime[register];
        const bbcTime = this.bbcDateTime();
        set(bbcTime, fromBcd(value));
        this.setTimeFrom(bbcTime);
    }
 
    writeCalendar(field, value) {
        const bbcTime = this.bbcDateTime();
        const registers = { ...this.calendarRegisters(bbcTime), [field]: value };
        const { day, month, year } = registers;
        bbcTime.setFullYear(MosCentury + fromBcd(year), fromBcd(month) - 1, fromBcd(day));
        const isRealDay =
            toBcd(bbcTime.getDate()) === day &&
            toBcd(bbcTime.getMonth() + 1) === month &&
            toBcd(bbcTime.getFullYear() % 100) === year;
        if (isRealDay) {
            this.heldDate = null;
            this.setTimeFrom(bbcTime);
        } else {
            this.heldDate = registers;
        }
    }
 
    read() {
        if (!this.enabled) return 0xff;
        // To drive the bus we need:
        // - CMOS enabled.
        // - Address Select low.
        // - Data Select high.
        // - Read high.
 
        if (!this.addressSelect && this.dataSelect && this.isRead) {
            // The first 10 bytes of CMOS RAM store the RTC clock
            if (this.cmosAddr < 10) {
                const current = this.bbcDateTime();
                switch (this.cmosAddr) {
                    case 0:
                    case 2:
                    case 4:
                        return this.heldTime[this.cmosAddr] ?? toBcd(TimeRegisters[this.cmosAddr].get(current));
                    case 6:
                        return toBcd(current.getDay() + 1);
                    case 7:
                        return this.calendarRegisters(current).day;
                    case 8:
                        return this.calendarRegisters(current).month;
                    case 9:
                        return this.calendarRegisters(current).year;
                }
            } else {
                return this.store[this.cmosAddr] & 0xff;
            }
        }
        return 0xff;
    }
 
    /** Takes up the select and read lines as port B and IC32 drive them, making no access. */
    followLines(portBpins, IC32) {
        this.enabled = !!(portBpins & 0x40);
        if (!this.enabled) return;
        this.isRead = !!(IC32 & 2);
        this.dataSelect = !!(IC32 & 4);
        this.addressSelect = !!(portBpins & 0x80);
    }
 
    writeControl(portBpins, portApins, IC32) {
        const { dataSelect: oldDataSelect, addressSelect: oldAddressSelect } = this;
        this.followLines(portBpins, IC32);
        if (!this.enabled) return;
        if (oldAddressSelect && !this.addressSelect) this.cmosAddr = portApins & 0x3f;
        if (oldDataSelect && !this.dataSelect && !this.addressSelect && !this.isRead) {
            if (this.cmosAddr > 0xb) {
                this.store[this.cmosAddr] = portApins;
                this.keep(this.cmosAddr, portApins);
            } else {
                switch (this.cmosAddr) {
                    case 0:
                    case 2:
                    case 4:
                        this.writeTime(this.cmosAddr, portApins);
                        break;
                    case 7:
                        this.writeCalendar("day", portApins);
                        break;
                    case 8:
                        this.writeCalendar("month", portApins);
                        break;
                    case 9:
                        this.writeCalendar("year", portApins);
                        break;
                }
            }
        }
    }
}