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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 | 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 85x 85x 14x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 91x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 155365x 170x 85x 87x 87x 87x 87x 1777521x 1737254x 1737254x 40179x 40179x 20067x 20067x 20112x 40179x 42x 223x 174866x 14x 7x 7x 14x 7x 7x 220x 220x 206x 1779384x 1779384x 1779384x 1604518x 1779164x 1737158x 1737158x 1x 42004x 20066x 42004x 1x 1x 220x 220x 220x 71x 71x 71x 71x 88x 88x 29x 29x 29x 5x 5x 5x 5x 27x 27x 27x 88x 88x 88x 88x 42x 42x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 30x 30x 30x 30x 5x 5x 5x 11x 11x 46x 7x 46x 46x 46x 46x 46x 46x 46x 46x 46x 42x 42x 42x 4x 297x 297x 297x 133x 17x 17x 116x 116x 116x 30x 23x 3x 2x 2x 42x 42x 17x 17x 25x 25x 25x 25x 25x 24x 24x 42x 42x 91x 91x 91x 91x 2x 2x 60x 2x 58x 60x 29x 29x 71x 910136x 251x 158x 158x 158x 71x 87x 158x 71x 71x 316x 158x 158x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 87x 30x 46x 46x 46x 1x 1x 1x 1x 1x 1x 27x 27x 27x 1x 1x 1x 1x 1x 1x 11x 11x 11x 5x 5x 5x 155365x 155365x 155365x 155365x 155365x 155365x 155365x 155365x 7x 7x 9479x 125008x 125008x 5x 5x 5x 5x 20855x 20855x 20855x 5x 5x 5x 6x 6x 155365x 7x 7x 125008x 4x 4x 2x 2x 2x 444416x 223104x 223104x 13x 13x 223091x 1x 1x 223090x 13x 223090x 221312x 2469x 2469x 2469x 8x 8x 8x 444416x 444416x 22x 22x 22x 444394x 444416x 444416x 223090x 13930x 13930x 13930x 221304x 6908x 6908x 6908x 6908x 6908x 20860x 20860x 444416x 444416x 20860x 2469x 4x 42x 155471x 8637x 8637x 8637x 124x 124x 124x 124x 124x 124x 45x 45x 45x 29x 29x 29x 29x 29x 13x 13x 13x 77x 77x 77x 77x 86x 9x 9x 77x 86x 2x 2x 2x 75x 20860x 20860x 20860x 20860x 20860x 594x 11x 11x 11x 66x 66x 150x 150x 1295x 1295x 18755x 18751x 4x 18755x 66x 66x 11x 11x 6x 11x 11x 11x 11x 11x 66x 36x 66x 44x 22x 66x 11x 11x 6x 6x 6x 5x 5x 5x 5x 5x 5x 150x 150x 150x 150x 43x 43x 5x 2x 5x 5x 5x 1295x 1295x 1280x 1280x 1280x 15x 10x 10x 5x 5x 20067x 20067x 20067x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 2x 12x 12x 12x | // Translated from beebjit by Chris Evans.
// https://github.com/scarybeasts/beebjit
// eslint-disable-next-line no-unused-vars
import { Cpu6502, NmiSource } from "./6502.js";
// eslint-disable-next-line no-unused-vars
import { attachDriveNoise, BaseDiscDrive, DiscDrive } from "./disc-drive.js";
import { IbmDiscFormat } from "./disc.js";
// eslint-disable-next-line no-unused-vars
import { Scheduler } from "./scheduler.js";
import { hexbyte } from "./hex.js";
/**
* Commands.
*
* @readonly
* @enum {Number}
*/
const Command = Object.freeze({
restore: 0x00,
seek: 0x10,
stepInNoUpdate: 0x40,
stepInWithUpdate: 0x50,
stepOutNoUpdate: 0x60,
stepOutWithUpdate: 0x70,
readSector: 0x80,
readSectorMulti: 0x90,
writeSector: 0xa0,
writeSectorMulti: 0xb0,
readAddress: 0xc0,
forceInterrupt: 0xd0,
readTrack: 0xe0,
writeTrack: 0xf0,
});
/**
* Command bits.
*
* @readonly
* @enum {Number}
*/
const CommandBits = Object.freeze({
typeIIMulti: 0x10,
disableSpinUp: 0x08,
typeIVerify: 0x04,
typeIIorIIISettle: 0x04,
typeIIDeleted: 0x01,
});
/**
* Type IV (force interrupt) condition bits, taken from the command's low nibble.
*
* @readonly
* @enum {Number}
*/
const ForceInterruptBits = Object.freeze({
indexPulse: 0x04,
immediate: 0x08,
});
// The datasheet names one byte for each address mark; the WD1772 accepts the whole range
// (Jean Louis-Guerin's WD1772 specification, "Type II commands").
const isIdMark = (data) => data >= 0xfc && data <= 0xff;
const isDataMark = (data) => data === 0xfa || data === 0xfb;
const isDeletedDataMark = (data) => data === 0xf8 || data === 0xf9;
const FmIndexMark = 0xfc;
/**
* The drive control register is documented here:
* https://www.cloud9.co.uk/james/BBCMicro/Documentation/wd1770.html
*
* @readonly
* @enum {Number}
*/
const Control = Object.freeze({
reset: 0x20,
density: 0x08,
side: 0x04,
drive1: 0x02,
drive0: 0x01,
});
/**
* Status bits.
*
* @readonly
* @enum {Number}
*/
const Status = Object.freeze({
motorOn: 0x80,
writeProtected: 0x40,
typeISpinUpDone: 0x20,
typeIIorIIIDeletedMark: 0x20,
recordNotFound: 0x10,
crcError: 0x08,
typeITrack0: 0x04,
typeIIorIIILostByte: 0x04,
typeIIndex: 0x02,
typeIIorIIIDrq: 0x02,
busy: 0x01,
});
/**
* Controller state.
*
* @readonly
* @enum {Number}
*/
const State = Object.freeze({
null: 0,
idle: 1,
timerWait: 2,
spinUpWait: 3,
waitIndex: 4,
searchId: 5,
inId: 6,
searchData: 7,
inData: 8,
inReadTrack: 9,
writeSectorDelay: 10,
writeSectorLeadInFm: 11,
writeSectorLeadInMfm: 12,
writeSectorMarkerFm: 13,
writeSectorMarkerMfm: 14,
writeSectorBody: 15,
writeTrackSetup: 16,
inWriteTrack: 17,
checkMulti: 18,
done: 19,
});
/**
* Timer state.
*
* @readonly
* @enum {Number}
*/
const TimerState = Object.freeze({
none: 1,
settle: 2,
seek: 3,
done: 4,
});
/**
* Which controller, and how it is wired. The Master Compact's WD1772 steps faster than the WD1770; the
* Opus Challenger's WD1770 sits at the other half of the page and keeps INTRQ off the NMI line.
*
* @readonly
* @enum {string}
*/
export const WdFdcVariant = Object.freeze({
wd1770: "wd1770",
wd1772: "wd1772",
opusChallenger: "opusChallenger",
});
export class WdFdc {
/**
* @param {Cpu6502} cpu
* @param {Scheduler} scheduler
* @param {BaseDiscDrive[] | undefined} drives
* @param {*} debugFlags
* @param {WdFdcVariant} [variant]
*/
constructor(cpu, scheduler, drives, debugFlags, variant = WdFdcVariant.wd1770) {
this._cpu = cpu;
if (drives) this._drives = drives;
else this._drives = [new DiscDrive(0, scheduler), new DiscDrive(1, scheduler)];
this._isMaster = cpu.model.isMaster;
this._is1772 = variant === WdFdcVariant.wd1772;
this._isOpus = variant === WdFdcVariant.opusChallenger;
this._controlRegister = 0;
/** @type {Status|Number} */
this._statusRegister = 0;
this._trackRegister = 0;
this._sectorRegister = 0;
this._dataRegister = 0;
this._isIntRq = false;
this._isDrq = false;
this._doRaiseIntRq = false;
/** @type {BaseDiscDrive|null} */
this._currentDrive = null;
this._isIndexPulse = false;
this._isInterruptOnIndexPulse = false;
this._isWriteTrackCrcSecondByte = false;
this._command = 0;
this._commandType = 0;
this._isCommandSettle = false;
this._isCommandWrite = false;
this._isCommandVerify = false;
this._isCommandMulti = false;
this._isCommandDeleted = false;
this._commandStepRateMs = 0;
this._state = State.idle;
this._timerState = TimerState.none;
this._timerTask = scheduler.newTask(() => this._timerFired());
this._stateCount = 0;
this._indexPulseCount = 0;
this._markDetector = 0n;
this._dataShifter = 0;
this._dataShiftCount = 0;
this._deliverData = 0;
this._deliverIsMarker = false;
this._crc = 0;
this._onDiscTrack = 0;
this._onDiscSector = 0;
this._onDiscLength = 0;
this._onDiscCrc = 0;
this._lastMfmBit = false;
this._logCommands = debugFlags ? !!debugFlags.logFdcCommands : false;
this._logStateChanges = debugFlags ? !!debugFlags.logFdcStateChanges : false;
const callback = (pulses, count) => this._pulsesCallback(pulses, count);
for (const drive of this._drives) drive.setPulsesCallback(callback);
this.powerOnReset();
}
reset() {
// This will:
// - Spin down.
// - Raise reset, which:
// - Clears status register.
// - Sets other registers as per how a real machine behaves.
// - Clears IRQs.
this._writeControl(0);
}
powerOnReset() {
this.reset();
// The reset line doesn't seem to affect the track or data registers.
this._trackRegister = 0;
this._dataRegister = 0;
}
_updateNmi() {
this._cpu.setNmi(NmiSource.fdc, this._isDrq || (!this._isOpus && this._isIntRq));
}
/**
* @param {boolean} level
*/
_setIntRq(level) {
this._isIntRq = level;
this._updateNmi();
}
/**
* @param {boolean} level
*/
_setDrq(level) {
this._isDrq = level;
if (level) {
Iif (this._statusRegister & Status.typeIIorIIIDrq) {
this._statusRegister |= Status.typeIIorIIILostByte;
}
this._statusRegister |= Status.typeIIorIIIDrq;
} else {
this._statusRegister &= ~Status.typeIIorIIIDrq;
}
this._updateNmi();
}
_log(message) {
console.log(`WD1770: ${message}`);
}
_logCommand(message) {
Iif (this._logCommands) this._log(message);
}
_opusRemapAddr(addr) {
return addr ^ 4;
}
_opusRemapVal(addr, val) {
// Only remap control register values.
if (addr >= 4) return val;
let remapped = Control.reset;
remapped |= val & 0x01 ? Control.drive1 : Control.drive0;
Iif (val & 0x02) remapped |= Control.side;
if (!(val & 0x40)) remapped |= Control.density;
return remapped;
}
_masterRemapVal(addr, val) {
// Only remap control register values.
if (addr >= 4) return val;
let remapped = 0;
if (val & 0x04) remapped |= Control.reset;
if (val & 0x01) remapped |= Control.drive0;
if (val & 0x02) remapped |= Control.drive1;
if (val & 0x10) remapped |= Control.side;
if (val & 0x20) remapped |= Control.density;
return remapped;
}
_remapVal(addr, val) {
Iif (this._isMaster) return this._masterRemapVal(addr, val);
if (this._isOpus) return this._opusRemapVal(addr, val);
return val;
}
_remapAddr(addr) {
addr &= 0x07;
Iif (this._isMaster) return addr ^ 0x04;
if (this._isOpus) return this._opusRemapAddr(addr);
return addr;
}
/**
* @param {Number} addr hardware address
* @returns {Number} byte at the given hardware address
*/
read(addr) {
switch (this._remapAddr(addr)) {
case 4:
// Reading status register clears INTRQ.
this._setIntRq(false);
return this._statusRegister;
case 5:
return this._trackRegister;
case 6:
return this._sectorRegister;
case 7:
if (this._commandType === 2 || this._commandType === 3) {
this._setDrq(false);
}
return this._dataRegister;
case 0:
case 1:
case 2:
case 3:
break;
}
return 0xfe;
}
/**
* @param {Number} addr hardware address
* @param {Number} val byte to write
*/
write(addr, val) {
addr = this._remapAddr(addr);
val = this._remapVal(addr, val);
switch (addr) {
case 0:
case 1:
case 2:
case 3:
this._logCommand(`control register now ${hexbyte(val)}`);
Iif (this._statusRegister & Status.busy && !this._isReset(val)) {
throw new Error(`Control register updated while busy; without reset`);
}
this._writeControl(val);
break;
case 4:
// Ignore commands while in reset.
Eif (!this._isReset(this._controlRegister)) this._doCommand(val);
break;
case 5:
this._logCommand(`track register now ${val}`);
this._trackRegister = val;
break;
case 6:
// Ignore sector reg changes in reset; note that track/data registers will still be accepted.
if (!this._isReset(this._controlRegister)) {
this._logCommand(`sector register now ${val}`);
this._sectorRegister = val;
} else E{
this._logCommand(`ignoring sector write of ${val}`);
}
break;
case 7:
Iif (this._commandType === 2 || this._commandType === 3) {
this._setDrq(false);
}
this._dataRegister = val;
break;
}
}
_doCommand(val) {
Iif (!this._currentDrive) throw new Error("Command while no selected drive");
this._logCommand(
`command ${hexbyte(val)} tr ${this._trackRegister} sr ${this._sectorRegister} dr ${this._dataRegister} ` +
`cr ${hexbyte(this._controlRegister)} ` +
`ptrk ${this._currentDrive.track} hpos ${this._currentDrive.headPosition}`,
);
const command = val & 0xf0;
if (command === Command.forceInterrupt) {
this._handleForceInterrupt(val);
return;
}
Iif (this._statusRegister & Status.busy) {
// EMU NOTE: this is a very murky area. There does not appear to be a simple
// rule here. Whether a command will do anything when busy seems to depend on
// the current command, the new command and also the current place in the
// internal state machine!
this._log(`command ${hexbyte(val)} while busy with ${hexbyte(this._command)} - ignoring`);
return;
}
this._command = command;
this._isCommandSettle = false;
this._isCommandWrite = false;
this._isCommandVerify = false;
this._isCommandMulti = false;
this._isCommandDeleted = false;
this._isInterruptOnIndexPulse = false;
this._isWriteTrackCrcSecondByte = false;
switch (command) {
case Command.restore:
case Command.seek:
case Command.stepInNoUpdate:
case Command.stepInWithUpdate:
case Command.stepOutNoUpdate:
case Command.stepOutWithUpdate:
this._commandType = 1;
this._isCommandVerify = !!(val & CommandBits.typeIVerify);
this._commandStepRateMs = this._stepRateMsFor(val);
break;
case Command.readSector:
case Command.readSectorMulti:
case Command.writeSector:
case Command.writeSectorMulti:
this._commandType = 2;
this._isCommandMulti = !!(val & CommandBits.typeIIMulti);
break;
case Command.readAddress:
case Command.readTrack:
case Command.writeTrack:
this._commandType = 3;
break;
default:
throw new Error(`unimplemented command ${hexbyte(val)}`);
}
if (this._commandType === 2 || (this._commandType === 3 && val & CommandBits.typeIIorIIISettle))
this._isCommandSettle = true;
Iif (
this._command === Command.writeSector ||
this._command === Command.writeSectorMulti ||
this._command === Command.writeTrack
) {
this._isCommandWrite = true;
this._isCommandDeleted = !!(val & CommandBits.typeIIDeleted);
}
// All commands except force interrupt (handled above):
// - Clear INTRQ and DRQ.
// - Clear status register result bits.
// - Set busy.
// - Spin up if necessary and not inhibited.
this._setDrq(false);
this._setIntRq(false);
this._statusRegister = (this._statusRegister & Status.motorOn) | Status.busy;
this._indexPulseCount = 0;
Iif (this._statusRegister & Status.motorOn) {
// Short circuit spin-up if motor is on.
this._dispatchCommand();
} else {
this._statusRegister |= Status.motorOn;
this._currentDrive.startSpinning();
// Short circuit spin-up if command requests it.
// /* NOTE: disabling spin-up wait is a strange facility. It makes a lot of
// sense for a seek because the disc head can usefully get moving while the
// motor is spinning up. But other commands like a read track also seem to
// start immediately. It is unclear whether such a command would be
// unreliable on a drive that takes a while to come up to speed.
if (val & CommandBits.disableSpinUp) {
this._indexPulseCount = 6;
this._log(`command ${hexbyte(val)} spin up wait disabled, motor was off`);
this._dispatchCommand();
} else {
this._setState(State.spinUpWait);
}
}
}
/**
* @param {State|Number} state
*/
_setState(state) {
Iif (this._logStateChanges && state !== this._state) {
this._log(
`State ${this._state} -> ${state} @ tr ${this._trackRegister} ` +
`sr ${this._sectorRegister} dr ${this._dataRegister} ` +
`cr ${hexbyte(this._controlRegister)} ` +
`ptrk ${this._currentDrive.track} hpos ${this._currentDrive.headPosition}`,
);
}
this._state = state;
this._stateCount = 0;
}
_clearTimer() {
if (this._timerState !== TimerState.none) {
this._timerTask.cancel();
this._timerState = TimerState.none;
}
}
_clearState() {
this._setState(State.idle);
this._clearTimer();
this._indexPulseCount = 0;
}
_stepRateMsFor(val) {
switch (val & 0x03) {
case 0:
return 6;
case 1:
return 12;
case 2:
return this._is1772 ? 2 : 20;
case 3:
return this._is1772 ? 3 : 30;
}
}
_handleForceInterrupt(val) {
const forceInterruptBits = val & 0x0f;
// EMU NOTE: force interrupt is pretty unclear on the datasheet. From
// testing on a real 1772:
// - The command is aborted right away in all cases.
// - The command completion INTRQ / NMI is _inhibited_ for $D0. In
// particular, Watford Electronics DDFS will be unhappy unless you behave
// correctly here.
// - Force interrupt will spin up the motor and enter an idle state if
// the motor is off. The idle state behaves a little like a type 1 command
// insofar as index pulse appears to be reported in the status register.
// - Interrupt on index pulse is only active for the current command.
if (this._statusRegister & Status.busy) {
// Any pending timer belongs to the command being aborted.
this._clearTimer();
this._commandDone(false);
} else {
Iif (this._state !== State.idle) throw new Error(`Unexpected state when force interrupt: ${this._state}`);
this._indexPulseCount = 0;
this._commandType = 1;
this._statusRegister &= Status.motorOn;
if (!(this._statusRegister & Status.motorOn)) {
this._statusRegister |= Status.motorOn;
this._currentDrive.startSpinning();
}
}
if (forceInterruptBits & ForceInterruptBits.immediate) this._setIntRq(true);
this._isInterruptOnIndexPulse = !!(forceInterruptBits & ForceInterruptBits.indexPulse);
// The remaining two bits select interrupts on the ready line's transitions. The BBC ties
// the 1770's READY input active, so neither transition can ever occur.
}
_timerFired() {
Iif (!(this._statusRegister & Status.busy)) throw new Error("Should be busy");
const timerState = this._timerState;
this._timerState = TimerState.none;
switch (timerState) {
case TimerState.settle:
this._dispatchCommand();
break;
case TimerState.seek:
if (
this._command === Command.stepInNoUpdate ||
this._command === Command.stepInWithUpdate ||
this._command === Command.stepOutNoUpdate ||
this._command === Command.stepOutWithUpdate
)
this._checkVerify();
else this._doSeekStepOrVerify();
break;
case TimerState.done:
this._doneTimer();
break;
default:
throw new Error(`Unexpected timer state ${timerState}`);
}
}
/**
* @param {Control} value
*/
_isSide(value) {
return !!(value & Control.side);
}
/**
* @param {Control} value
*/
_isDoubleDensity(value) {
// Double density (MFM) is active low.
return !(value & Control.density);
}
/**
* @param {Control} value
*/
_isReset(value) {
// Reset is active low.
return !(value & Control.reset);
}
/**
* @param {Control|Number} val
*/
_writeControl(val) {
const isMotorOn = !!(this._statusRegister & Status.motorOn);
Iif (this._currentDrive && this._currentDrive.spinning) {
if (!isMotorOn) {
throw new Error(
`Unexpected motor control bit off when setting the control register to ${hexbyte(val)}`,
);
}
this._currentDrive.stopSpinning();
}
if (val & Control.drive0 || val & Control.drive1) {
this._currentDrive = this._drives[val & Control.drive0 ? 0 : 1];
} else {
this._currentDrive = null;
}
if (this._currentDrive) {
Iif (isMotorOn) this._currentDrive.startSpinning();
this._currentDrive.selectSide(this._isSide(val));
}
// Set up single or double density
for (const drive of this._drives) drive.set32usMode(this._isDoubleDensity(val));
this._controlRegister = val;
if (this._isReset(val)) {
// Go idle, etc
this._clearState();
Iif (this._currentDrive && isMotorOn) this._currentDrive.stopSpinning();
this._statusRegister = 0;
// EMU NOTE: on a real machine, the reset condition appears to hold the
// sector register at 1 but leave track / data alone (and permit changes
// to them).
this._sectorRegister = 1;
this._isIntRq = false;
this._isDrq = false;
this._updateNmi();
this._markDetector = 0n;
this._dataShifter = 0;
this._dataShiftCount = 0;
this._isIndexPulse = false;
this._lastMfmBit = false;
this._deliverData = 0;
this._deliverIsMarker = false;
}
}
_makeSeekNoise(delta) {
Eif (this._currentDrive) this._currentDrive.notifySeekAmount(delta, this._commandStepRateMs);
}
_dispatchCommand() {
Iif (!this._currentDrive) throw new Error("Unexpectedly dispatching a command with no drive set");
Iif (this._isCommandWrite && this._currentDrive.writeProtect) {
this._statusRegister |= Status.writeProtected;
this._commandDone(true);
return;
}
switch (this._command) {
case Command.restore:
this._trackRegister = 0xff;
this._logCommand(`track register now ${this._trackRegister}`);
this._dataRegister = 0;
// The head steps out from wherever it is, whatever the track register says
this._makeSeekNoise(-this._currentDrive.logicalTrack);
this._doSeekStepOrVerify();
break;
case Command.seek:
this._makeSeekNoise(this._dataRegister - this._trackRegister);
this._doSeekStepOrVerify();
break;
case Command.stepInNoUpdate:
this._makeSeekNoise(1);
this._doSeekStep(1, false);
break;
case Command.stepInWithUpdate:
this._makeSeekNoise(1);
this._doSeekStep(1, true);
break;
case Command.stepOutNoUpdate:
this._makeSeekNoise(-1);
this._doSeekStep(-1, false);
break;
case Command.stepOutWithUpdate:
this._makeSeekNoise(-1);
this._doSeekStep(-1, true);
break;
case Command.readSector:
case Command.readSectorMulti:
case Command.writeSector:
case Command.writeSectorMulti:
case Command.readAddress:
this._setState(State.searchId);
this._indexPulseCount = 0;
break;
case Command.readTrack:
this._setState(State.waitIndex);
this._indexPulseCount = 0;
break;
case Command.writeTrack:
this._setState(State.writeTrackSetup);
this._indexPulseCount = 0;
break;
default:
throw new Error(`Invalid command ${this._command} in dispatch`);
}
}
_pulsesCallback(pulses, count) {
// This callback routine is also used for seek/settle timing which not a precise 64us basis.
Iif (!this._currentDrive || !this._currentDrive.spinning || !(this._statusRegister & Status.motorOn)) {
throw new Error("Something unfortunate happened in the 1770 pulses callback");
}
const wasIndexPulse = this._isIndexPulse;
this._isIndexPulse = this._currentDrive.indexPulse;
const isIndexPulsePositiveEdge = this._isIndexPulse && !wasIndexPulse;
const isMfm = count === 16;
if (this._isInterruptOnIndexPulse && isIndexPulsePositiveEdge) this._setIntRq(true);
// EMU Note: if the chip is idle after copmletion of a type I command, this index pulse and
// track 0 bits appear maintained. They disappear on spin-down.
this._updateTypeIStatusBits();
switch (this._state) {
case State.idle:
this._pulsesCallbackIdle();
break;
case State.timerWait:
break;
case State.spinUpWait:
this._pulsesCallbackSpinUpWait();
break;
case State.waitIndex:
Eif (isIndexPulsePositiveEdge) {
this._setState(State.inReadTrack);
// Need to include this byte (directly after the index pulse) in the read
// track data. Confirmed with a real 1772 & Gotek.
this._bitstreamReceived(pulses, count, false);
}
break;
case State.searchId:
case State.inId:
case State.searchData:
case State.inData:
case State.inReadTrack:
this._bitstreamReceived(pulses, count, isIndexPulsePositiveEdge);
Iif (this._indexPulseCount >= 6) {
this._statusRegister |= Status.recordNotFound;
this._commandDone(true);
}
break;
case State.writeSectorDelay:
this._pulsesCallbackSectorDelay(isMfm);
break;
case State.writeSectorLeadInFm:
this._writeByte(isMfm, 0x00, false);
if (++this._stateCount === 6) this._setState(State.writeSectorMarkerFm);
break;
case State.writeSectorLeadInMfm:
if (this._stateCount >= 11) this._writeByte(isMfm, 0x00, false);
if (++this._stateCount === 23) this._setState(State.writeSectorMarkerMfm);
break;
case State.writeSectorMarkerFm: {
const dataByte = this._isCommandDeleted
? IbmDiscFormat.deletedDataMarkDataPattern
: IbmDiscFormat.dataMarkDataPattern;
this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), dataByte);
this._writeByte(false, dataByte, true);
this._setState(State.writeSectorBody);
break;
}
case State.writeSectorMarkerMfm:
this._pulsesCallbackWriteSectorMarkerMfm();
break;
case State.writeSectorBody:
this._pulsesCallbackWriteSectorBody(isMfm);
break;
case State.checkMulti:
Iif (this._isCommandMulti) {
this._sectorRegister++;
this._indexPulseCount = 0;
this._setState(State.searchId);
} else {
this._commandDone(true);
}
break;
case State.writeTrackSetup:
this._pulsesCallbackWriteTrackSetup();
break;
case State.inWriteTrack:
this._pulsesCallbackInWriteTrack(isMfm, isIndexPulsePositiveEdge);
break;
case State.done:
this._commandDone(true);
break;
default:
throw new Error(`Unexpected state ${this._state}`);
}
if (isIndexPulsePositiveEdge) this._indexPulseCount++;
}
_pulsesCallbackIdle() {
Iif (this._statusRegister & Status.busy) throw new Error("Unexpectedly busy in idle state");
// different sources disagree on 10 vs 9 index pulses for spin down.
Eif (this._indexPulseCount < 9) return;
this._logCommand("automatic motor off");
this._currentDrive.stopSpinning();
this._statusRegister &= ~Status.motorOn;
// In @scarybeasts's testing on a 1772 the polled type 1 status bits get cleared on spin down.
if (this._commandType === 1) {
this._statusRegister &= ~(Status.typeITrack0 | Status.typeIIndex);
}
}
_pulsesCallbackSpinUpWait() {
if (this._indexPulseCount < 6) return;
Iif (this._commandType === 1) this._statusRegister |= Status.typeISpinUpDone;
if (this._isCommandSettle) {
// The WD1770 datasheet specifies 30ms head settle, but empirical testing
// against b-em (which uses 15ms for all WD1770/2 variants) shows 15ms is
// correct for BBC hardware. Using 30ms causes disc streaming demos (e.g.
// STNICC-beeb on Master 128) to hang because sectors don't arrive before
// the first vsync IRQ. The WD1772 also uses 15ms per its datasheet.
const settleMs = 15;
this._startTimer(TimerState.settle, settleMs * 1000);
} else {
this._dispatchCommand();
}
}
_pulsesCallbackSectorDelay(isMfm) {
// Following the data sheet here for byte-for-byte behaviour.
if (this._stateCount === 0) {
this._indexPulseCount = 0;
} else if (this._stateCount === 1) {
this._setDrq(true);
} else if (this._stateCount === 10 && this._statusRegister & Status.typeIIorIIIDrq) {
this._statusRegister |= Status.typeIIorIIILostByte;
this._commandDone(true);
}
this._stateCount++;
if (this._stateCount === 12) this._setState(isMfm ? State.writeSectorLeadInMfm : State.writeSectorLeadInFm);
}
_pulsesCallbackWriteSectorMarkerMfm() {
if (this._stateCount < 3) this._writeByte(true, 0xa1, true);
if (++this._stateCount === 4) {
const dataByte = this._isCommandDeleted
? IbmDiscFormat.deletedDataMarkDataPattern
: IbmDiscFormat.dataMarkDataPattern;
this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(true), dataByte);
this._writeByte(true, dataByte, false);
this._setState(State.writeSectorBody);
}
}
_pulsesCallbackWriteSectorBody(isMfm) {
if (this._stateCount < this._onDiscLength) {
let dataByte = this._dataRegister;
if (this._statusRegister & Status.typeIIorIIIDrq) {
dataByte = 0;
this._statusRegister |= Status.typeIIorIIILostByte;
}
this._crc = IbmDiscFormat.crcAddByte(this._crc, dataByte);
this._writeByte(isMfm, dataByte, false);
if (this._stateCount !== this._onDiscLength - 1) this._setDrq(true);
} else if (this._stateCount < this._onDiscLength + 2) {
this._writeByte(isMfm, (this._crc >>> 8) & 0xff, false);
this._crc = (this._crc << 8) & 0xffff;
} else {
this._writeByte(isMfm, 0xff, false);
this._setState(State.checkMulti);
}
this._stateCount++;
}
_pulsesCallbackWriteTrackSetup() {
if (this._stateCount === 0) {
this._indexPulseCount = 0;
this._setDrq(true);
} else if (this._stateCount === 3) {
if (this._statusRegister & Status.typeIIorIIIDrq) {
this._statusRegister |= Status.typeIIorIIILostByte;
this._commandDone(true);
} else {
this._setState(State.inWriteTrack);
return;
}
}
this._stateCount++;
}
_pulsesCallbackInWriteTrack(isMfm, isIndexPulsePositiveEdge) {
if (this._stateCount === 0 && !isIndexPulsePositiveEdge) return;
if (this._stateCount > 0 && isIndexPulsePositiveEdge) {
this._commandDone(true);
return;
}
if (this._isWriteTrackCrcSecondByte) {
this._writeByte(isMfm, this._crc & 0xff, false);
this._isWriteTrackCrcSecondByte = false;
this._setDrq(true);
return;
}
let dataByte = this._dataRegister;
if (this._statusRegister & Status.typeIIorIIIDrq) {
dataByte = 0;
this._statusRegister |= Status.typeIIorIIILostByte;
}
let isMarker = false;
let isPresetCrc = false;
switch (dataByte) {
// 0xF5 and 0xF6 are documented as "not allowed" in FM mode. They
// actually write 0xA1 / 0xC2 respectively, as per MFM, but it's not
// known whether any clock bits are omitted, or whether CRC is preset,
// so bailing for now rather than guessing.
case 0xf5:
if (!isMfm) throw new Error("Unhandled 0xf5 in FM");
isMarker = true;
isPresetCrc = true;
dataByte = 0xa1;
break;
case 0xf6:
if (!isMfm) throw new Error("Unhandled 0xf6 in FM");
isMarker = true;
dataByte = 0xc2;
break;
case 0xf8:
case 0xf9:
case 0xfa:
case 0xfb:
case 0xfe:
if (!isMfm) {
isMarker = true;
isPresetCrc = true;
}
break;
case 0xfc:
if (!isMfm) isMarker = true;
break;
default:
break;
}
if (isPresetCrc) {
this._crc = IbmDiscFormat.crcInit(isMfm);
}
if (dataByte === 0xf7) {
this._writeByte(isMfm, (this._crc >>> 8) & 0xff, false);
this._isWriteTrackCrcSecondByte = true;
} else {
this._writeByte(isMfm, dataByte, isMarker);
if (isMfm && isPresetCrc) {
// Nothing.
} else {
this._crc = IbmDiscFormat.crcAddByte(this._crc, dataByte);
}
this._setDrq(true);
}
this._stateCount++;
}
_markDetectorTriggered() {
if (this._isDoubleDensity(this._controlRegister)) {
// EMU NOTE: unsure as to exactly when MFM sync bytes are spotted. Here we look for MFM 0x00 then an MFM
// sync, 0xa1 or 0xc2. The documented sequences are 12 0x00, 3x 0xa1 (sync) and 12 0x00, 3x 0xc2 (index).
const lastWord = this._markDetector & 0xffffffffn;
if (lastWord === 0xaaaa4489n) {
this._deliverData = 0xa1;
return true;
}
// Ordinary data can encode this pattern too (01 fe 29 is one such run), so it only resyncs
// where the spec says it may, in read track.
if (lastWord === 0xaaaa5224n && this._state === State.inReadTrack) {
this._deliverData = 0xc2;
return true;
}
// Tag the byte after 3 sync bytes as a marker. The byte after 3 index syncs is the index mark, which
// opens no field, so it stays untagged.
if ((this._markDetector & 0xffffffffffff0000n) === 0x4489448944890000n) {
this._deliverIsMarker = true;
}
return false;
}
// The FM mark detector appears to need 4 data bits' worth of zeros, with clock bits set to 1, to be able to trigger.
// Tried on @scarybeasts's real 1772-based machine.
if ((this._markDetector & 0x0000ffff00000000n) !== 0x0000888800000000n) return false;
const { clocks, data, iffyPulses } = IbmDiscFormat._2usPulsesToFm(Number(this._markDetector & 0xffffffffn));
// A mark reads back with the clock that write track gives it.
const markClocks = this._fmMarkerClocksFor(data);
if (iffyPulses || markClocks === undefined || clocks !== markClocks) return false;
this._deliverData = data;
this._deliverIsMarker = data !== FmIndexMark;
return true;
}
/**
* @param {boolean} bit
*/
_bitReceived(bit) {
// Always run the mark detector. For a command like "read track", the 1770
// will re-sync in the middle of the command as appropriate.
this._markDetector = ((this._markDetector << 1n) & 0xffffffffffffffffn) | (bit ? 1n : 0n);
if (this._markDetectorTriggered()) {
this._dataShifter = 0;
this._dataShiftCount = 0;
return;
}
this._dataShifter = ((this._dataShifter << 1) | (bit ? 1 : 0)) & 0xffffffff;
this._dataShiftCount++;
if (this._isDoubleDensity(this._controlRegister)) {
if (this._dataShiftCount === 16) {
this._deliverData = IbmDiscFormat._2usPulsesToMfm(this._dataShifter);
this._dataShifter = 0;
this._dataShiftCount = 0;
}
} else {
if (this._dataShiftCount === 32) {
const { data, iffyPulses } = IbmDiscFormat._2usPulsesToFm(this._dataShifter);
// If we're reading MFM as FM, the pulses won't all fall on 4us boundaries. This is fuzzy bits;
// we'll return a non-stable read.
Iif (iffyPulses) {
const { data: unstableBits } = IbmDiscFormat._2usPulsesToFm(
this._currentDrive.getQuasiRandomPulses(),
);
this._deliverData = unstableBits;
} else {
this._deliverData = data;
}
this._dataShifter = 0;
this._dataShiftCount = 0;
}
}
}
_bitstreamReceived(pulses, pulsesCount, isIndexPulsePositiveEdge) {
pulses = (pulses << (32 - pulsesCount)) & 0xffffffff;
for (let i = 0; i < pulsesCount; ++i) {
this._bitReceived(!!(pulses & 0x80000000));
pulses = (pulses << 1) & 0xffffffff;
}
this._byteReceived(isIndexPulsePositiveEdge);
}
/**
* @param {boolean} isMfm
* @param {Number} byte
* @param {boolean} isMarker
*/
_writeByte(isMfm, byte, isMarker) {
let pulses;
if (isMfm) {
if (isMarker) pulses = this._mfmMarkerFor(byte);
else {
const result = IbmDiscFormat.mfmTo2usPulses(this._lastMfmBit, byte);
this._lastMfmBit = result.lastBit;
pulses = result.pulses;
}
} else {
const clocks = isMarker ? this._fmMarkerClocksFor(byte) : 0xff;
pulses = IbmDiscFormat.fmTo2usPulses(clocks, byte);
}
this._currentDrive.writePulses(pulses);
}
_fmMarkerClocksFor(byte) {
switch (byte) {
case FmIndexMark:
return 0xd7;
case 0xf8:
case 0xf9:
case 0xfa:
case 0xfb:
case 0xfe:
return IbmDiscFormat.markClockPattern;
}
}
_mfmMarkerFor(byte) {
switch (byte) {
case 0xa1:
return IbmDiscFormat.mfmA1Sync;
case 0xc2:
return IbmDiscFormat.mfmC2Sync;
default:
throw new Error(`Bad marker byte ${hexbyte(byte)}`);
}
}
_updateTypeIStatusBits() {
if (this._commandType !== 1) return;
this._statusRegister &= ~(Status.typeITrack0 | Status.typeIIndex);
if (this._currentDrive.track === 0) this._statusRegister |= Status.typeITrack0;
if (this._currentDrive.indexPulse) this._statusRegister |= Status.typeIIndex;
}
_startTimer(timerState, waitUs) {
Iif (!(this._statusRegister & Status.busy)) throw new Error("Should be busy");
Iif (this._timerState !== TimerState.none) throw new Error("Timer started but still running");
this._timerTask.cancel();
this._timerState = timerState;
this._setState(State.timerWait);
this._timerTask.schedule(waitUs * 2);
}
_commandDone(doRaiseIntRq) {
Iif (!(this._statusRegister & Status.busy)) throw new Error("Should be busy");
this._doRaiseIntRq = doRaiseIntRq;
this._startTimer(TimerState.done, 32);
}
_doneTimer() {
this._statusRegister &= ~Status.busy;
this._clearState();
// Make sure the status are up to date.
this._updateTypeIStatusBits();
// EMU NOTE: leave DRQ alone, if it is raised, leave it raised.
if (this._doRaiseIntRq) this._setIntRq(true);
this._logCommand(`result status ${hexbyte(this._statusRegister)}`);
}
_checkVerify() {
Eif (this._currentDrive) this._currentDrive.notifySeekEnd();
Iif (this._isCommandVerify) {
this._indexPulseCount = 0;
this._setState(State.searchId);
} else {
this._commandDone(true);
}
}
_doSeekStep(stepDirection, doUpdateTr) {
this._currentDrive.seekOneTrack(stepDirection);
if (doUpdateTr) this._trackRegister += stepDirection;
// TRK0 signal may have been raised or lowered.
this._updateTypeIStatusBits();
this._startTimer(TimerState.seek, this._commandStepRateMs * 1000);
}
_doSeekStepOrVerify() {
if (this._trackRegister === this._dataRegister) {
this._checkVerify();
return;
}
const stepDirection = this._trackRegister > this._dataRegister ? -1 : 1;
if (this._currentDrive.track === 0 && stepDirection === -1) {
this._trackRegister = 0;
this._checkVerify();
return;
}
this._doSeekStep(stepDirection, true);
}
_byteReceived(isIndexPulsePositiveEdge) {
const isMfm = this._isDoubleDensity(this._controlRegister);
const isMarker = this._deliverIsMarker;
const data = this._deliverData;
this._deliverIsMarker = false;
switch (this._state) {
case State.searchId:
if (!isMarker || !isIdMark(data)) break;
this._setState(State.inId);
this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(isMfm), data);
break;
case State.inId:
this._byteReceivedInId(data);
break;
case State.searchData:
this._byteReceivedSearchData(data, isMarker);
break;
case State.inData:
this._byteReceivedInData(data);
break;
case State.inReadTrack:
if (!isIndexPulsePositiveEdge) {
this._sendDataToHost(data);
} else {
this._commandDone(true);
}
break;
default:
throw new Error(`Bad state ${this._state}`);
}
}
_byteReceivedInId(data) {
const isReadAddress = this._command === Command.readAddress;
switch (this._stateCount) {
case 0:
this._onDiscTrack = data;
if (isReadAddress) {
// The datasheet says "The Track Address of the ID field is written into the sector register"
this._sectorRegister = data;
}
break;
case 2:
this._onDiscSector = data;
break;
case 3:
// From http://info-coach.fr/atari/documents/_mydoc/WD1772-JLG.pdf, only the lower two bits affect anything.
this._onDiscLength = 128 << (data & 0x03);
break;
}
if (isReadAddress) {
// Note that unlike the 8271, the CRC bytes are sent along too.
this._sendDataToHost(data);
}
if (this._stateCount < 4) {
this._crc = IbmDiscFormat.crcAddByte(this._crc, data);
} else {
this._onDiscCrc = ((this._onDiscCrc << 8) & 0xffff) | data;
}
if (++this._stateCount !== 6) return;
const isCrcError = this._crc !== this._onDiscCrc;
if (isReadAddress) {
Iif (isCrcError) this._statusRegister |= Status.crcError;
// Unlike the 8271, read address returns just a single record. It is also not synchronized
// to the index pulse.
// EMU NOTE: the internal clock cycles the 1770 spends between delivering the last
// header byte, reporting the CRC error and dropping busy are not modelled.
// EMU NOTE: must not clear busy flag right away. The 1770 delivers the
// last header byte DRQ separately from lowering the busy flag.
this._setState(State.done);
return;
}
// The data sheet specifies no CRC error unless the fields match so check those first.
Iif (this._trackRegister !== this._onDiscTrack) {
this._setState(State.searchId);
return;
}
Iif (this._commandType === 2 && this._sectorRegister !== this._onDiscSector) {
this._setState(State.searchId);
return;
}
Iif (isCrcError) {
this._statusRegister |= Status.crcError;
// Unlike the 8271, the 1770 keeps going.
this._setState(State.searchId);
return;
}
Iif (this._commandType === 1) this._commandDone(true);
else Iif (this._isCommandWrite) this._setState(State.writeSectorDelay);
else this._setState(State.searchData);
}
_byteReceivedSearchData(data, isMarker) {
this._stateCount++;
const isMfm = this._isDoubleDensity(this._controlRegister);
const multiplier = isMfm ? 2 : 1;
// Like the 8271 the data mark is only recognized if 14 bytes have passed.
// Unlike the 8271, it gives up after a while longer.
if (this._stateCount < 14 * multiplier) return;
Iif (this._stateCount > 31 * multiplier) {
this._setState(State.searchId);
return;
}
if (!isMarker || !(isDataMark(data) || isDeletedDataMark(data))) return;
if (isDeletedDataMark(data)) {
// EMU NOTE: the datasheet is ambiguous on whether the deleted mark is
// visible in the status register immediately, or at the end of a read.
// The state machine diagram says "DAM in time" -> "Set Record Type in
// Status Bit 5". But later on it says "At the end of the Read... is
// recorded...".
// Testing on @scarybeasts's 1772, the state machine diagram is correct: the bit is
// visible in the status register immediately during the read.
// EMU NOTE: on a multi-sector read, the deleted mark bit is set, and left
// set, if _any_ deleted data sector was encountered. The datasheet would
// seem to imply that only the most recent sector type is reflected in
// the bit, but testing on @scarybeasts's 1772, the bit is set and left set even if
// a non-deleted sector is encountered subsequently.
this._statusRegister |= Status.typeIIorIIIDeletedMark;
}
this._setState(State.inData);
// CRC error is reset here. It's possible to hit a CRC error in a sector header and then find
// an OK matching sector header.
this._statusRegister &= ~Status.crcError;
this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(isMfm), data);
}
_byteReceivedInData(data) {
this._stateCount++;
if (this._stateCount <= this._onDiscLength) {
this._crc = IbmDiscFormat.crcAddByte(this._crc, data);
this._sendDataToHost(data);
return;
} else if (this._stateCount <= this._onDiscLength + 2) {
this._onDiscCrc = ((this._onDiscCrc << 8) & 0xffff) | data;
return;
}
Iif (this._crc !== this._onDiscCrc) {
this._statusRegister |= Status.crcError;
// Sector data CRC error is terminal, even for a multi-sector read.
this._commandDone(true);
return;
}
this._setState(State.checkMulti);
}
_sendDataToHost(data) {
Iif (this._commandType !== 2 && this._commandType !== 3) throw new Error("Bad command type");
this._setDrq(true);
this._dataRegister = data;
}
snapshotState() {
const scheduler = this._timerTask.scheduler;
return {
controlRegister: this._controlRegister,
statusRegister: this._statusRegister,
trackRegister: this._trackRegister,
sectorRegister: this._sectorRegister,
dataRegister: this._dataRegister,
isIntRq: this._isIntRq,
isDrq: this._isDrq,
doRaiseIntRq: this._doRaiseIntRq,
isIndexPulse: this._isIndexPulse,
isInterruptOnIndexPulse: this._isInterruptOnIndexPulse,
isWriteTrackCrcSecondByte: this._isWriteTrackCrcSecondByte,
command: this._command,
commandType: this._commandType,
isCommandSettle: this._isCommandSettle,
isCommandWrite: this._isCommandWrite,
isCommandVerify: this._isCommandVerify,
isCommandMulti: this._isCommandMulti,
isCommandDeleted: this._isCommandDeleted,
commandStepRateMs: this._commandStepRateMs,
state: this._state,
timerState: this._timerState,
stateCount: this._stateCount,
indexPulseCount: this._indexPulseCount,
// BigInt must be converted to string for JSON serialization
markDetector: this._markDetector.toString(),
dataShifter: this._dataShifter,
dataShiftCount: this._dataShiftCount,
deliverData: this._deliverData,
deliverIsMarker: this._deliverIsMarker,
crc: this._crc,
onDiscTrack: this._onDiscTrack,
onDiscSector: this._onDiscSector,
onDiscLength: this._onDiscLength,
onDiscCrc: this._onDiscCrc,
lastMfmBit: this._lastMfmBit,
timerTaskOffset: this._timerTask.scheduled() ? this._timerTask.expireEpoch - scheduler.epoch : null,
drives: this._drives.map((d) => d.snapshotState()),
};
}
restoreState(state) {
this._controlRegister = state.controlRegister;
this._statusRegister = state.statusRegister;
this._trackRegister = state.trackRegister;
this._sectorRegister = state.sectorRegister;
this._dataRegister = state.dataRegister;
this._isIntRq = state.isIntRq;
this._isDrq = state.isDrq;
this._doRaiseIntRq = state.doRaiseIntRq;
this._isIndexPulse = state.isIndexPulse;
this._isInterruptOnIndexPulse = state.isInterruptOnIndexPulse;
this._isWriteTrackCrcSecondByte = state.isWriteTrackCrcSecondByte;
this._command = state.command;
this._commandType = state.commandType;
this._isCommandSettle = state.isCommandSettle;
this._isCommandWrite = state.isCommandWrite;
this._isCommandVerify = state.isCommandVerify;
this._isCommandMulti = state.isCommandMulti;
this._isCommandDeleted = state.isCommandDeleted;
this._commandStepRateMs = state.commandStepRateMs;
this._state = state.state;
this._timerState = state.timerState;
this._stateCount = state.stateCount;
this._indexPulseCount = state.indexPulseCount;
this._markDetector = BigInt(state.markDetector);
this._dataShifter = state.dataShifter;
this._dataShiftCount = state.dataShiftCount;
this._deliverData = state.deliverData;
this._deliverIsMarker = state.deliverIsMarker;
this._crc = state.crc;
this._onDiscTrack = state.onDiscTrack;
this._onDiscSector = state.onDiscSector;
this._onDiscLength = state.onDiscLength;
this._onDiscCrc = state.onDiscCrc;
this._lastMfmBit = state.lastMfmBit;
// Restore drives
for (let i = 0; i < this._drives.length; i++) {
this._drives[i].restoreState(state.drives[i]);
}
// Derive _currentDrive from _controlRegister
this._currentDrive = null;
Iif (this._controlRegister & Control.drive0 || this._controlRegister & Control.drive1) {
this._currentDrive = this._drives[this._controlRegister & Control.drive0 ? 0 : 1];
}
// Restore timer
this._timerTask.cancel();
Iif (state.timerTaskOffset !== null) this._timerTask.schedule(state.timerTaskOffset);
this._updateNmi();
}
/// jsbeeb compatibility stuff
/**
* @param {Number} drive
* @param {Disc} disc
*/
/**
* @param {Number} drive
* @param {Disc} disc
* @param {Number} [tracksPerStep] where to leave the drive's 40/80 switch, which by default
* follows the disc, since no drive can tell what pitch the disc in it was written at
*/
loadDisc(drive, disc, tracksPerStep = disc?.is40Track ? 2 : 1) {
this._drives[drive].setDisc(disc);
this._drives[drive].tracksPerStep = tracksPerStep;
}
get motorOn() {
return [this._drives[0] ? this._drives[0].spinning : false, this._drives[0] ? this._drives[1].spinning : false];
}
get drives() {
return this._drives;
}
}
export class NoiseAwareWdFdc extends WdFdc {
constructor(cpu, ddNoise, scheduler, debugFlags) {
super(cpu, scheduler, undefined, debugFlags);
attachDriveNoise(this.drives, ddNoise);
}
}
|