All files / src intel-fdc.js

47.84% Statements 377/788
35.66% Branches 168/471
75.6% Functions 62/82
48.69% Lines 355/729

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 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801                                                      37x                                                                                                               37x                                   37x                     37x                                           37x                                   37x                                                 37x                             37x                     37x 37x               37x                             37x                       37x                                                                   37x                                 410x                   265x 265x 243x   265x 265x 265x 265x 265x   265x 265x 265x 265x 265x   265x 265x 265x 265x 265x 265x   265x 265x   265x 265x 265x 265x 265x   265x 265x   265x   265x 508x   265x               360x               360x         358x 358x 358x 358x 358x 358x 358x         360x 360x   360x   360x       1442x               24x   5x   19x 19x 19x 19x                                         3x       217x               211x   91x 91x   119x 119x                   1x     1x 1x 1x   1x               119x 119x     119x   17x 17x                       17x         17x                                                                   17x 10x 10x   17x 17x       60x         134x       119x 119x         119x                         119x   119x   119x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             100x 100x 9x   100x       556x 556x 20x   556x       138x 138x 138x       114x       57x 57x 2x   57x                                               932x 932x 932x       91x 91x 1x       91x     91x 91x 91x     91x 91x     91x 91x     91x   54x 54x   37x         138x 138x       119x 119x   119x       77x 77x 77x 51x   77x     42x 42x 42x 42x 14x   42x               1x 1x 1x                                         144x 144x 122x 122x   22x 22x               22x 22x                           6x       21x             415x 415x       415x 415x 374x   415x 34x 34x 34x   34x   415x 41x 41x   415x             421x     421x 421x 421x                   11x 11x   11x       11x 8x 6x   8x 6x     11x 11x   11x 11x   11x 11x     11x 1x 1x     10x 10x 10x 4x 10x       10x   10x   10x       10x       41x       9x 9x     32x 32x   32x 32x       42x   42x     6x       10x 10x   10x 6x   6x 4x   4x   10x 1x   9x         9x 9x                                                                             33x 33x 33x                           9x 9x 9x 9x 9x                       88x 88x     88x   88x       88x 88x 88x       6x 6x       88x 88x 88x                       88x 88x     88x       176x       134x       129x       241x         88x         134x   134x 39x 39x   134x   88x   88x   88x     134x       134x 134x 134x 134x 134x 134x       88x   88x         37x 37x 37x 37x 37x     14x 14x 14x 14x   25x   25x 25x   1x 1x 1x                             11x 11x                                                 61x 61x 61x   61x 61x   12x 49x     49x 49x         9x 9x   9x   9x 9x                           61x                                 421x 421x 421x         421x       86x 86x       12x         31x 31x 31x   31x 31x                                                   46x 46x                                             90x         28x 28x 28x 28x 28x 28x   28x 28x 28x           28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x     28x 53x       28x 28x 28x 25x     28x 28x   28x                               18x 18x               250x           238x 238x      
// 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 { Disc, IbmDiscFormat } from "./disc.js";
 
// eslint-disable-next-line no-unused-vars
import { attachDriveNoise, BaseDiscDrive, DiscDrive } from "./disc-drive.js";
// eslint-disable-next-line no-unused-vars
import { Scheduler } from "./scheduler.js";
import { hexbyte, hexword } from "./hex.js";
 
// TODOs remaining for intel-fdc and related functionality
// - support loading other disc formats
// - support "writeback" to SSD (at least); tested with
//   - google drive - broken currently :'()
//   - download disc image DONE
// - ideally support "writeback" to high fidelity output formats
// - UI elements for visualisation
 
/**
 * Register indices.
 *
 * @readonly
 * @enum {Number}
 */
const Registers = Object.freeze({
    internalPointer: 0x00,
    internalCountMsbCopy: 0x00,
    internalParamCount: 0x01,
    internalSeekRetryCount: 0x01,
    internalParamDataMarker: 0x02,
    internalParam_5: 0x03,
    internalParam_4: 0x04,
    internalParam_3: 0x05,
    currentSector: 0x06,
    internalParam_2: 0x06,
    internalParam_1: 0x07,
    internalHeaderPointer: 0x08,
    internalMsCountHi: 0x08,
    internalMsCountLo: 0x09,
    internalSeekCount: 0x0a,
    internalIdSector: 0x0a,
    internalSeekTarget_1: 0x0b,
    internalDynamicDispatch: 0x0b,
    internalSeekTarget_2: 0x0c,
    internalIdTrack: 0x0c,
    headStepRate: 0x0d,
    headSettleTime: 0x0e,
    headLoadUnload: 0x0f,
    badTrack_1Drive_0: 0x10,
    badTrack_2Drive_0: 0x11,
    trackDrive_0: 0x12,
    internalCountLsb: 0x13,
    internalCountMsb: 0x14,
    internalDriveInCopy: 0x15,
    internalWriteRunData: 0x15,
    internalGap2Skip: 0x15,
    internalResult: 0x16,
    mode: 0x17,
    internalStatus: 0x17,
    badTrack_1Drive_1: 0x18,
    badTrack_2Drive_1: 0x19,
    trackDrive_1: 0x1a,
    internalDriveInLatched: 0x1b,
    internalIndexPulseCount: 0x1c,
    internalData: 0x1d,
    internalParameter: 0x1e,
    internalCommand: 0x1f,
 
    mmioDriveIn: 0x22,
    mmioDriveOut: 0x23,
    mmioClocks: 0x24,
    mmioData: 0x25,
});
 
/**
 * Drive output bitmask.
 *
 * @readonly
 * @enum {Number}
 */
const DriveOut = Object.freeze({
    select_1: 0x80,
    select_0: 0x40,
    side: 0x20,
    lowHeadCurrent: 0x10,
    loadHead: 0x08,
    direction: 0x04,
    step: 0x02,
    writeEnable: 0x01,
    selectFlags: 0xc0,
});
 
/**
 * Floppy disc controller mode.
 *
 * @readonly
 * @enum {Number}
 */
const FdcMode = Object.freeze({
    singleActuator: 0x02,
    noDma: 0x01,
});
 
/**
 * Register address.
 *
 * @readonly
 * @enum {Number}
 */
const Address = Object.freeze({
    // Read.
    status: 0,
    result: 1,
    unknown_read_2: 2,
    unknown_read_3: 3,
 
    // Write.
    command: 0,
    parameter: 1,
    reset: 2,
 
    // Read / write.
    data: 4,
});
 
/**
 * Result bitmask.
 *
 * @readonly
 * @enum {Number}
 */
const Result = Object.freeze({
    ok: 0x00,
    clockError: 0x08,
    lateDma: 0x0a,
    idCrcError: 0x0c,
    dataCrcError: 0x0e,
    driveNotReady: 0x10,
    writeProtected: 0x12,
    sectorNotFound: 0x18,
    flagDeletedData: 0x20,
});
 
/**
 * Command number.
 *
 * @readonly
 * @enum {Number}
 */
const Command = Object.freeze({
    scanData: 0,
    scanDataAndDeleted: 1,
    writeData: 2,
    writeDeletedData: 3,
    readData: 4,
    readDataAndDeleted: 5,
    readId: 6,
    verify: 7,
    format: 8,
    unused_9: 9,
    seek: 10,
    readDriveStatus: 11,
    unused_12: 12,
    specify: 13,
    writeSpecialRegister: 14,
    readSpecialRegister: 15,
});
 
/**
 * Status flags
 *
 * @readonly
 * @enum {Number}
 */
const StatusFlag = Object.freeze({
    busy: 0x80,
    commandFull: 0x40,
    paramFull: 0x20,
    resultReady: 0x10,
    nmi: 0x08,
    needData: 0x04,
});
 
/**
 * Parameter acceptance state machine.
 *
 * @readonly
 * @enum {Number}
 */
const ParamAccept = Object.freeze({
    none: 0,
    command: 1,
    specify: 2,
});
 
/**
 * The Model B does not wire the drives' Ready lines to the 8271. Its own logic (ICs 83 to 86)
 * makes a selected drive ready on the second index pulse after selection and drops it as soon
 * as 8192 counts of a 31.25 kHz clock pass without one: 262 ms, a disc below about 230 rpm.
 */
const ReadyTimeoutTicks = 8192 * 64;
const ReadyIndexPulses = 2;
 
/**
 * Index pulse state machine.
 *
 * @readonly
 * @enum {Number}
 */
const IndexPulse = Object.freeze({
    none: 1,
    timeout: 2,
    spindown: 3,
    startReadId: 4,
    startFormat: 5,
    stopFormat: 6,
});
 
/**
 * Timer state machine.
 *
 * @readonly
 * @enum {Number}
 */
const TimerState = Object.freeze({
    none: 0,
    seekStep: 1,
    postSeek: 2,
});
 
/**
 * Overall state machine.
 *
 * @readonly
 * @enum {Number}
 */
const State = Object.freeze({
    null: 0,
    idle: 1,
    syncingForIdWait: 2,
    syncingForId: 3,
    checkIdMarker: 4,
    inId: 5,
    inIdCrc: 6,
    syncingForData: 7,
    checkDataMarker: 8,
    inData: 9,
    inDataCrc: 10,
    skipGap_2: 11,
    writeRun: 12,
    writeDataMark: 13,
    writeSectorData: 14,
    writeCrc_2: 15,
    writeCrc_3: 16,
    dynamicDispatch: 17,
    formatWriteIdMarker: 18,
    formatIdCrc_2: 19,
    formatIdCrc_3: 20,
    formatWriteDataMarker: 21,
    formatDataCrc_2: 22,
    formatDataCrc_3: 23,
    formatGap_4: 24,
});
 
/**
 * Callback state machine.
 *
 * @readonly
 * @enum {Number}
 */
const Call = Object.freeze({
    uninitialised: 0,
    unchanged: 1,
    seek: 2,
    readId: 3,
    read: 4,
    write: 5,
    format: 6,
    formatGap1OrGap3FFs: 7,
    formatGap1orGap300s: 8,
    formatGap2_FFs: 9,
    formatGap2_00s: 10,
    formatData: 11,
});
 
export class IntelFdc {
    static get NumRegisters() {
        return 32;
    }
 
    /**
     * @param {Cpu6502} cpu
     * @param {Scheduler} scheduler
     * @param {BaseDiscDrive[] | undefined} drives
     * @param {*} debugFlags
     */
    constructor(cpu, scheduler, drives, debugFlags) {
        this._cpu = cpu;
        if (drives) this._drives = drives;
        else this._drives = [new DiscDrive(0, scheduler), new DiscDrive(1, scheduler)];
        /** @type {BaseDiscDrive} */
        this._currentDrive = null;
        this._scheduler = scheduler;
        this._ready = false;
        this._readyPulses = 0;
        this._lastIndexEpoch = -Infinity;
 
        this._paramCallback = ParamAccept.none;
        this._indexPulseCallback = IndexPulse.none;
        this._timerState = TimerState.none;
        this._callContext = Call.uninitialised;
        this._didSeekStep = false;
 
        this._regs = new Uint8Array(IntelFdc.NumRegisters);
        this._isResultReady = false;
        this._status = 0;
        this._mmioData = 0;
        this._mmioClocks = 0;
        this._driveOut = 0;
 
        this._shiftRegister = 0;
        this._numShifts = 0;
 
        this._state = State.null;
        this._stateCount = 0;
        this._stateIsIndexPulse = false;
        this._crc = 0;
        this._onDiscCrc = 0;
 
        this._logCommands = debugFlags ? !!debugFlags.logFdcCommands : false;
        this._logStateChanges = debugFlags ? !!debugFlags.logFdcStateChanges : false;
 
        this._timerTask = scheduler.newTask(() => this._timerFired());
 
        const callback = (pulses, count) => this._pulsesCallback(pulses, count);
        for (const drive of this._drives) drive.setPulsesCallback(callback);
 
        this.powerOnReset();
    }
 
    _commandAbort() {
        // If we're aborting a command in the middle of writing data, it usually
        // doesn't leave a clean byte end on the disc. This is not particularly
        // important to emulate at all, but it does help create new copy protection
        // schemes under emulation.
        Iif (this._driveOut & DriveOut.writeEnable) {
            this._currentDrive.writePulses(IbmDiscFormat.fmTo2usPulses(0xff, 0xff));
        }
 
        // Lower any NMI assertion. This is particularly important for error $0A,
        // aka. late DMA, which will abort the command while NMI is asserted. We
        // therefore need to de-assert NMI so that the NMI for command completion
        // isn't lost.
        this._cpu.setNmi(NmiSource.fdc, false);
    }
 
    powerOnReset() {
        // The reset line does most things.
        this.reset();
        this._regs.fill(0);
        this._isResultReady = false;
        this._mmioData = 0;
        this._mmioClocks = 0;
        this._stateCount = 0;
        this._stateIsIndexPulse = false;
    }
 
    reset() {
        // Abort any in-progress command.
        this._commandAbort();
        this._clearCallbacks();
        // Deselect any drive; ensures spin-down.
        this._setDriveOut(0);
        // On a real machine, status appears to be cleared but result and data not.
        this._statusLower(this.internalStatus);
    }
 
    get internalStatus() {
        return this._regs[Registers.internalStatus];
    }
 
    /**
     * @param {Number} addr hardware address
     * @returns {Number} byte at the given hardware address
     */
    read(addr) {
        switch (addr & 0x07) {
            case Address.status:
                return this._status;
            case Address.result: {
                const result = this._result;
                this._resultConsumed();
                this._statusLower(StatusFlag.nmi);
                return result;
            }
            case Address.data:
            case Address.data + 1:
            case Address.data + 2:
            case Address.data + 3:
                this._statusLower(StatusFlag.needData | StatusFlag.nmi);
                return this._regs[Registers.internalData];
            // Register address 2 and 3 are not documented as having anything
            // wired up for reading, BUT on a model B, they appear to give the MSB and
            // LSB of the sector byte counter in internal registers 19 ($13) and 20 ($14).
            case Address.unknown_read_2:
                return this._regs[Registers.internalCountMsb];
            case Address.unknown_read_3:
                return this._regs[Registers.internalCountLsb];
            default:
                throw new Error(`"Unexpected read of addr ${hexword(addr)}"`);
        }
    }
 
    _log(message) {
        console.log(`8271: ${message}`);
    }
 
    _logCommand(message) {
        Iif (this._logCommands) this._log(message);
    }
 
    /**
     * @param {Number} addr hardware address
     * @param {Number} val byte to write
     */
    write(addr, val) {
        switch (addr & 7) {
            case Address.command:
                this._commandWritten(val);
                break;
            case Address.parameter:
                this._paramWritten(val);
                break;
            case Address.data:
            case Address.data + 1:
            case Address.data + 2:
            case Address.data + 3:
                this._statusLower(StatusFlag.needData | StatusFlag.nmi);
                this._regs[Registers.internalData] = val;
                break;
            case Address.reset:
                //On a real 8271, crazy things happen if you write 2 or especially 4 to this register.
                Iif (val !== 0 && val !== 1) {
                    this._log("funky reset");
                }
                Eif (val === 1) {
                    this._logCommand("reset");
                    this.reset();
                }
                break;
            case 3:
            default:
                this._log(`Not supported: ${hexword(addr)}=${hexbyte(val)}`);
        }
    }
 
    _checkIndexPulse() {
        const wasIndexPulse = this._stateIsIndexPulse;
        this._stateIsIndexPulse = this._index;
 
        // Looking for pulse going high
        if (!this._stateIsIndexPulse || wasIndexPulse) return;
 
        this._noteIndexPulse();
        switch (this._indexPulseCallback) {
            case IndexPulse.none:
                break;
            case IndexPulse.timeout:
                // If we see too many index pulses without the progress of a sector, the command times out with 0x18.
                // Interestingly enough, something like an e.g. 8192 byte sector read /times out because such a crazy
                // read hits the default 3 index pulse limit.
                if (--this._regs[Registers.internalIndexPulseCount] === 0) {
                    this._finishCommand(Result.sectorNotFound);
                }
                break;
            case IndexPulse.spindown:
                Iif (--this._regs[Registers.internalIndexPulseCount] === 0) {
                    this._logCommand("automatic head unload");
                    this._spinDown();
                    this._indexPulseCallback = IndexPulse.none;
                }
                break;
            case IndexPulse.startFormat:
                // Note that format doesn't set an index pulse timeout. No matter how
                // large the format sector size request, even 16384, the command never
                // exits due to 2 index pulses counted. This differs from read _and_
                // write. Format will exit on the next index pulse after all the sectors
                // have been written.
                // Disc Duplicator III needs this to work correctly when deformatting
                // tracks.
                if (this._regs[Registers.internalParam_4] !== 0) {
                    throw new Error("format GAP5 not supported");
                }
                // Decrement GAP3 as the CRC generator emits a third byte as 0xff.
                this._regs[Registers.internalParam_2]--;
                this._regs[Registers.internalDynamicDispatch] = 4;
                // This will start writing immediately because we check index pulse callbacks
                // before we process read/write state.
                this._indexPulseCallback = IndexPulse.none;
                // param_5 is GAP1.
                this._writeFFsAnd00s(Call.formatGap1OrGap3FFs, this._regs[Registers.internalParam_5]);
                break;
            case IndexPulse.stopFormat:
                this._checkCompletion();
                break;
            case IndexPulse.startReadId:
                this._startIndexPulseTimeout();
                this._startSyncingForHeader();
                break;
            default:
                throw new Error(`Unexpected index pulse callback ${this._indexPulseCallback}`);
        }
    }
 
    _noteIndexPulse() {
        if (this._indexPulsesStopped) {
            this._ready = false;
            this._readyPulses = 0;
        }
        this._lastIndexEpoch = this._scheduler.epoch;
        if (++this._readyPulses >= ReadyIndexPulses) this._ready = true;
    }
 
    get _indexPulsesStopped() {
        return this._scheduler.epoch - this._lastIndexEpoch >= ReadyTimeoutTicks;
    }
 
    /** The Beeb's ready latch as it stands, which the timeout clears without waiting for a pulse. */
    get _driveReady() {
        return this._ready && !this._indexPulsesStopped;
    }
 
    _pulsesCallback(pulses, count) {
        Iif (count !== 32) throw new Error("Expected FM pulses only");
        this._checkIndexPulse();
 
        // All writing occurs here.
        // NOTE: a nice 8271 quirk: if the write gate is open outside a command, it
        // still writes to disc, often effectively creating weak bits.
        Iif (this._driveOut & DriveOut.writeEnable) {
            const clocks = this._mmioClocks;
            const data = this._mmioData;
            const pulses = IbmDiscFormat.fmTo2usPulses(clocks, data);
            if (clocks !== 0xff && clocks !== IbmDiscFormat.markClockPattern)
                this._log(`writing unusual clocks=${hexbyte(clocks)} data=${hexbyte(data)}`);
            this._currentDrive.writePulses(pulses);
        }
 
        // The external data register is always copied across to the bit processor's
        // MMIO data register. If a write command is in a state where it needed to
        // provide a data byte internally (i.e. a GAP byte, marker, etc.), it
        // overrides by re-writing the MMIO data register in the state machine below.
        this._mmioData = this._regs[Registers.internalData];
 
        switch (this._state) {
            case State.idle:
                break;
            case State.syncingForIdWait:
            case State.syncingForId:
            case State.checkIdMarker:
            case State.inId:
            case State.inIdCrc:
            case State.skipGap_2:
            case State.syncingForData:
            case State.checkDataMarker:
            case State.inData:
            case State.inDataCrc: {
                for (let i = 0; i < 16; ++i) {
                    const bit = !!(pulses & 0xc0000000);
                    pulses = (pulses << 2) & 0xffffffff;
                    this._shiftDataBit(bit);
                }
                break;
            }
            case State.writeRun:
            case State.writeDataMark:
            case State.dynamicDispatch:
            case State.writeSectorData:
            case State.writeCrc_2:
            case State.writeCrc_3:
            case State.formatWriteIdMarker:
            case State.formatIdCrc_2:
            case State.formatIdCrc_3:
            case State.formatWriteDataMarker:
            case State.formatDataCrc_2:
            case State.formatDataCrc_3:
            case State.formatGap_4:
                this._byteCallbackWriting();
                break;
            default:
                throw new Error(`Unknown state ${this._state}`);
        }
    }
 
    _shiftDataBit(bit) {
        const state = this._state;
        switch (state) {
            case State.syncingForIdWait:
                this._stateCount++;
                // THe controller seems to need recovery time after a sector header before
                // it can sync to another one. Measuring the "read sector IDs" command, 0x1b,
                // it needs 4 bytes to recover prior to the 2 byte sync.
                if (this._stateCount === 4 * 8 * 2) {
                    this._startSyncingForHeader();
                }
                break;
            case State.syncingForId:
            case State.syncingForData: {
                const stateCount = this._stateCount;
                // Need to see bit pattern of 1010101010... to gather sync. This
                // represents a string of 1 clock bits followed by 0 data bits.
                if (bit === !(stateCount & 1)) {
                    this._stateCount++;
                } else if (stateCount >= 32 && stateCount & 1) {
                    // Here we hit a 1 data bit while in sync, so it's the start of a marker byte.
                    if (!bit) {
                        throw new Error("Assertion failed; was expecting a one bit");
                    }
                    this._setState(state === State.syncingForId ? State.checkIdMarker : State.checkDataMarker);
                    this._shiftRegister = 3;
                    this._numShifts = 2;
                } else {
                    // Restart sync.
                    this._stateCount = bit ? 1 : 0;
                }
                break;
            }
            case State.checkIdMarker:
            case State.inId:
            case State.inIdCrc:
            case State.checkDataMarker:
            case State.inData:
            case State.inDataCrc:
            case State.skipGap_2: {
                const shiftRegister = ((this._shiftRegister << 1) & 0xffffffff) | (bit ? 1 : 0);
                this._shiftRegister = shiftRegister;
                this._numShifts++;
                if (this._numShifts !== 16) break;
                const clockByte = IntelFdc.extractBits(shiftRegister);
                const dataByte = IntelFdc.extractBits(shiftRegister << 1);
                if (
                    clockByte !== 0xff &&
                    state !== State.checkIdMarker &&
                    state !== State.checkDataMarker &&
                    state !== State.skipGap_2
                ) {
                    // Nothing. From testing the 8271 doesn't deliver bytes with missing
                    // clock bits in the middle of a synced byte stream.
                } else {
                    this._byteCallbackReading(dataByte, clockByte);
                }
                this._shiftRegister = 0;
                this._numShifts = 0;
                break;
            }
            case State.idle:
            case State.writeRun:
                break;
            default:
                throw new Error(`"Unexpected state ${state}"`);
        }
    }
 
    static extractBits(bits) {
        let byte = 0;
        if (bits & 0x8000) byte |= 0x80;
        if (bits & 0x2000) byte |= 0x40;
        if (bits & 0x0800) byte |= 0x20;
        if (bits & 0x0200) byte |= 0x10;
        if (bits & 0x0080) byte |= 0x08;
        if (bits & 0x0020) byte |= 0x04;
        if (bits & 0x0008) byte |= 0x02;
        if (bits & 0x0002) byte |= 0x01;
        return byte;
    }
 
    _checkDataLossOk() {
        let ok = true;
 
        // Abort if DMA transfer is selected. This is not supported in a BBC.
        if (!(this._regs[Registers.mode] & FdcMode.noDma)) ok = false;
 
        // Abort command if it's any type of scan. The 8271 requires DMA to be wired
        // up for scan commands, which is not done in the BBC application.
        const command = this._internalCommand;
        if (command === Command.scanData || command === Command.scanDataAndDeleted) ok = false;
 
        // Abort command if previous data byte wasn't picked up.
        if (this.internalStatus & StatusFlag.needData) ok = false;
 
        if (ok) return true;
 
        this._commandAbort();
        this._finishCommand(Result.lateDma);
        return false;
    }
 
    _byteCallbackReading(dataByte, clockByte) {
        const command = this._internalCommand;
        if (this._irqCallbacks) {
            if (!this._checkDataLossOk()) return;
            this._regs[Registers.internalData] = dataByte;
            this._statusRaise(StatusFlag.nmi | StatusFlag.needData);
        }
 
        switch (this._state) {
            case State.skipGap_2:
                // The controller requires a minimum byte count of 12 before sync then
                // sector data. 2 bytes of sync are needed, so absolute minimum gap here is
                // 14. The controller formats to 17 (not user controllable).
 
                // The controller enforced gap skip is 11 bytes of read, as per the
                // ROM. The practical count of 12 is likely because the controller takes
                // some number of microseconds to start the sync detector after this
                // counter expires.
                if (--this._regs[Registers.internalGap2Skip]) break;
                if (this._callContext === Call.read) this._setState(State.syncingForData);
                else if (this._callContext === Call.write) this._doWriteRun(Call.write, 0x00);
                else throw new Error(`Unexpected call context ${this._callContext}`);
                break;
            case State.checkIdMarker:
                if (clockByte === IbmDiscFormat.markClockPattern && dataByte === IbmDiscFormat.idMarkDataPattern) {
                    this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), dataByte);
                    if (command === Command.readId) this._startIrqCallbacks();
                    this._setState(State.inId);
                } else {
                    this._startSyncingForHeader();
                }
                break;
            case State.inId:
                this._crc = IbmDiscFormat.crcAddByte(this._crc, dataByte);
                this._writeRegister(this._regs[Registers.internalHeaderPointer], dataByte);
                this._regs[Registers.internalHeaderPointer]--;
                if ((this._regs[Registers.internalHeaderPointer] & 0x07) === 0) {
                    this._onDiscCrc = 0;
                    this._stopIrqCallbacks();
                    this._setState(State.inIdCrc);
                }
                break;
            case State.inIdCrc:
                this._onDiscCrc = ((this._onDiscCrc << 8) | dataByte) & 0xffffffff;
                if (++this._stateCount === 2) {
                    // On a real 8271, an ID CRC error seems to end things decisively
                    // even if a subsequent ok ID would match.
                    if (!this._checkCrc(Result.idCrcError)) {
                        break;
                    }
                    // This is a test for the READ ID command.
                    if (this._regs[Registers.internalCommand] === 0x18) {
                        this._checkCompletion();
                    } else if (this._regs[Registers.internalIdTrack] !== this._regs[Registers.internalParam_1]) {
                        // Upon any mismatch of found track vs. expected track, the drive will try
                        // twice more on the next two tracks.
                        if (++this._regs[Registers.internalSeekRetryCount] === 3) {
                            this._finishCommand(Result.sectorNotFound);
                        } else {
                            this._logCommand("stepping due to track mismatch");
                            this._doSeek(Call.unchanged);
                        }
                    } else if (this._regs[Registers.internalIdSector] === this._regs[Registers.internalParam_2]) {
                        this._regs[Registers.internalGap2Skip] = 11;
                        if (this._callContext === Call.write) {
                            // Set up for the first 5 bytes of the 0x00 sync.
                            this._regs[Registers.internalCountMsb] = 0;
                            this._regs[Registers.internalCountLsb] = 5;
                        }
                        this._setState(State.skipGap_2);
                    } else {
                        this._setState(State.syncingForIdWait);
                    }
                }
                break;
            case State.checkDataMarker:
                if (
                    clockByte === IbmDiscFormat.markClockPattern &&
                    (dataByte === IbmDiscFormat.dataMarkDataPattern ||
                        dataByte === IbmDiscFormat.deletedDataMarkDataPattern)
                ) {
                    let doIrqs = true;
                    if (dataByte === IbmDiscFormat.deletedDataMarkDataPattern) {
                        if ((this._regs[Registers.internalCommand] & 0x0f) === 0) doIrqs = false;
                        this._setResult(Result.flagDeletedData);
                    }
                    // No IRQ callbacks if 'verify'.
                    if (this._regs[Registers.internalCommand] === 0x1c) doIrqs = false;
                    if (doIrqs) this._startIrqCallbacks();
                    this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), dataByte);
                    this._setState(State.inData);
                } else {
                    this._finishCommand(Result.clockError);
                }
                break;
            case State.inData: {
                this._crc = IbmDiscFormat.crcAddByte(this._crc, dataByte);
                if (this._decrementCounter()) {
                    this._onDiscCrc = 0;
                    this._setState(State.inDataCrc);
                }
                break;
            }
            case State.inDataCrc:
                this._onDiscCrc = ((this._onDiscCrc << 8) | dataByte) & 0xffffffff;
                if (++this._stateCount === 2) {
                    if (!this._checkCrc(Result.dataCrcError)) break;
                    this._checkCompletion();
                }
                break;
            default:
                throw new Error(`Unexpected state ${this._state}`);
        }
    }
 
    _callbackWriteRun() {
        if (!this._decrementCounter()) {
            this._mmioData = this._regs[Registers.internalWriteRunData];
            this._crc = IbmDiscFormat.crcAddByte(this._crc, this._mmioData);
            return;
        }
        switch (this._callContext) {
            case Call.write:
                this._mmioData = 0;
                this._startIrqCallbacks();
                this._setState(State.writeDataMark);
                break;
            case Call.formatGap1OrGap3FFs:
                // Flip from writing ffs to 00s.
                this._regs[Registers.internalCountLsb] = 5;
                this._doWriteRun(Call.formatGap1orGap300s, 0x00);
                break;
            case Call.formatGap1orGap300s:
                this._mmioData = 0x00;
                this._startIrqCallbacks();
                this._setState(State.formatWriteIdMarker);
                break;
            case Call.formatGap2_FFs:
                // Flip from writing ffs to 00s.
                this._regs[Registers.internalCountLsb] = 5;
                this._doWriteRun(Call.formatGap2_00s, 0x00);
                break;
            case Call.formatGap2_00s:
                this._mmioData = 0;
                this._setState(State.formatWriteDataMarker);
                break;
            case Call.formatData:
                this._mmioData = (this._crc >>> 8) & 0xff;
                this._setState(State.formatDataCrc_2);
                break;
            default:
                throw new Error(`Unexpected call context ${this._callContext}`);
        }
    }
 
    _callbackDynamicDispatch() {
        const routine = this._regs[Registers.internalDynamicDispatch]++;
        switch (routine) {
            // Routines 0 - 2 used for write sector.
            case 0:
                this._crc = IbmDiscFormat.crcAddByte(this._crc, this._mmioData);
                break;
            case 1:
                this._mmioData = (this._crc >>> 8) & 0xff;
                this._setState(State.writeCrc_2);
                break;
            case 2:
                this._checkCompletion();
                break;
            // Routines 4 - 11 used for format.
            // 4 - 7 write the 4 user-supplied sector header bytes.
            case 4:
                this._mmioClocks = 0xff;
            // fallthrough
            case 5:
            case 6:
            case 7:
                if (routine === 6) this._stopIrqCallbacks();
                this._crc = IbmDiscFormat.crcAddByte(this._crc, this._mmioData);
                break;
            // write the sector header CRC
            case 8:
                this._mmioData = (this._crc >>> 8) & 0xff;
                this._setState(State.formatIdCrc_2);
                break;
            // write GAP2
            case 9:
                // This value 10 is GAP2 0xff length minus 1. The CRC generator emits a third
                // byte of 0xff.
                // The other -1 here is because we will we set the count registers ourselves. In the ROM,
                // LSB is written here but not MSB.
                this._regs[Registers.internalCountLsb] = 10;
                this._writeFFsAnd00s(Call.formatGap2_FFs, -1);
                break;
            case 10:
                this._resetSectorByteCount();
                this._doWriteRun(Call.formatData, 0xe5);
                break;
            // 11 is after the sector data CRC is written.
            case 11:
                this._mmioData = 0xff;
                if ((--this._regs[Registers.internalParam_3] & 0x1f) === 0) {
                    // Format sectors done. Write GAP4 until end of track.
                    // Reset param 3 to 1, to ensure immediate exit in the command exit
                    // path in intel_fdc_check_completion().
                    this._regs[Registers.internalParam_3] = 1;
                    this._indexPulseCallback = IndexPulse.stopFormat;
                    this._setState(State.formatGap_4);
                } else {
                    // Format sectors not done. Next one. Reset state machine index, param2 is GAP3.
                    this._regs[Registers.internalDynamicDispatch] = 4;
                    this._writeFFsAnd00s(Call.formatGap1OrGap3FFs, this._regs[Registers.internalParam_2]);
                }
                break;
            default:
                throw new Error(`Dodgy routine number ${routine}`);
        }
    }
 
    _byteCallbackWriting() {
        if (this._irqCallbacks) {
            if (!this._checkDataLossOk()) return;
            this._statusRaise(StatusFlag.nmi | StatusFlag.needData);
        }
 
        switch (this._state) {
            case State.writeRun:
                this._callbackWriteRun();
                break;
            case State.writeDataMark:
                this._mmioData = this._regs[Registers.internalParamDataMarker];
                this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), this._mmioData);
                this._mmioClocks = IbmDiscFormat.markClockPattern;
                this._resetSectorByteCount(); /////
                // This strange decrement is how the ROM does it.
                this._regs[Registers.internalCountLsb]--;
                this._setState(State.writeSectorData);
                break;
            case State.writeSectorData:
                this._mmioClocks = 0xff;
                this._crc = IbmDiscFormat.crcAddByte(this._crc, this._mmioData);
                if (this._decrementCounter()) {
                    this._regs[Registers.internalDynamicDispatch] = 0;
                    this._setState(State.dynamicDispatch);
                }
                break;
            case State.writeCrc_2:
                this._mmioData = this._crc & 0xff;
                this._setState(State.writeCrc_3);
                break;
            case State.writeCrc_3:
                this._mmioData = 0xff;
                this._setState(State.dynamicDispatch);
                break;
            case State.dynamicDispatch:
                this._callbackDynamicDispatch();
                break;
            case State.formatWriteIdMarker:
                this._mmioData = IbmDiscFormat.idMarkDataPattern;
                this._mmioClocks = IbmDiscFormat.markClockPattern;
                this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), this._mmioData);
                this._setState(State.dynamicDispatch);
                break;
            case State.formatIdCrc_2:
                this._mmioData = this._crc & 0xff;
                this._setState(State.formatIdCrc_3);
                break;
            case State.formatIdCrc_3:
                this._mmioData = 0xff;
                this._setState(State.dynamicDispatch);
                break;
            case State.formatWriteDataMarker:
                this._mmioData = IbmDiscFormat.dataMarkDataPattern;
                this._mmioClocks = IbmDiscFormat.markClockPattern;
                this._crc = IbmDiscFormat.crcAddByte(IbmDiscFormat.crcInit(false), this._mmioData);
                this._setState(State.dynamicDispatch);
                break;
            case State.formatDataCrc_2:
                this._mmioData = this._crc & 0xff;
                this._setState(State.formatDataCrc_3);
                break;
            case State.formatDataCrc_3:
                this._mmioData = 0xff;
                this._setState(State.dynamicDispatch);
                break;
            case State.formatGap_4:
                // GAP 4 writes until the index pulse, handled in the callback there.
                this._mmioData = 0xff;
                break;
            default:
                throw new Error(`Bad write state ${this._state}`);
        }
    }
 
    _resetSectorByteCount() {
        this._regs[Registers.internalCountMsb] = this._regs[Registers.internalCountMsbCopy];
        this._regs[Registers.internalCountLsb] = 0x80;
    }
 
    _checkCompletion() {
        if (!this._checkDriveReady()) return;
 
        // Lower write enable.
        this._driveOutLower(DriveOut.writeEnable);
        this._clearCallbacks();
 
        // One less sector to go. Specifying 0 sectors seems to result in 32 read, due
        // to underflow of the 5-bit counter. On commands other than read id, any underflow
        // has other side effects such as modifying the sector size.
        if ((--this._regs[Registers.internalParam_3] & 0x1f) === 0) {
            this._finishCommand(Result.ok);
        } else {
            // This looks strange as it is set up to be just an increment (R4==1 in sector
            // operations). but it's what the 8271 ROM does.
            this._regs[Registers.internalParam_2] += this._regs[Registers.internalParam_4] & 0x3f;
            // This is also what the 8271 ROM does, just re-dispatches the current command.
            this._doCommandDispatch();
        }
    }
 
    /**
     * @param {Result|Number} error error if invalid
     */
    _checkCrc(error) {
        if (this._crc === this._onDiscCrc) return true;
        this._finishCommand(error);
        return false;
    }
 
    _statusRaise(statusFlags) {
        this._regs[Registers.internalStatus] |= statusFlags;
        if (statusFlags & StatusFlag.nmi) {
            this._updateNmi();
        }
        this._updateExternalStatus();
    }
 
    _statusLower(statusFlags) {
        this._regs[Registers.internalStatus] &= ~statusFlags;
        if (statusFlags & StatusFlag.nmi) {
            this._updateNmi();
        }
        this._updateExternalStatus();
    }
 
    _setResult(result) {
        this._regs[Registers.internalResult] = result;
        this._isResultReady = true;
        this._updateExternalStatus();
    }
 
    get _result() {
        return this._regs[Registers.internalResult];
    }
 
    _updateNmi() {
        const level = !!(this.internalStatus & StatusFlag.nmi);
        if (level && this._cpu.nmiAsserted(NmiSource.fdc)) {
            this._log("edge triggered NMI already high");
        }
        this._cpu.setNmi(NmiSource.fdc, level);
    }
 
    _updateExternalStatus() {
        // EMU NOTE: currently, the emulation responds instantly to getting commands
        // started, accepting parameters, transitioning between states, etc.
        // This is inaccurate.
        // The real 8271 is an asynchronously running general purpose microcontroller,
        // where each instruction takes 2us+ and processing between states uses a
        // large and variable number of instructions.
        // Some food for though, latency timings on a BBC + 8271, including setup:
        // WRITE SPECIAL REGISTER:                   211us
        // WRITE SPECIAL REGISTER (0 param version): 157us
        // READ DRIVE STATUS:                        188us
        // write $35 to parameter register:           31us
        // write 3rd SPECIFY parameter:               27us
        // EMU NOTE: command register full and parameter register full are set by the host's write
        // and cleared when the 8271's microcontroller accepts the byte; see Chris Evans's ROM
        // reverse engineering, https://scarybeastsecurity.blogspot.com/2020/11/reverse-engineering-forgotten-1970s.html
        // On the real chip acceptance takes the tens of microseconds listed above; here it happens
        // in the same write, so neither bit is ever reported. Software only polls for them to
        // clear, so nothing waits on them being set, and the latency is left unmodelled rather
        // than guessed from two measurements. The mode register shares this byte; result ready
        // is kept by the external register logic.
        let status = this.internalStatus & (StatusFlag.busy | StatusFlag.nmi | StatusFlag.needData);
        if (this._isResultReady) status |= StatusFlag.resultReady;
        this._status = status;
    }
 
    _commandWritten(command) {
        const status = this.internalStatus;
        if (status & StatusFlag.busy) {
            this._log(`command ${hexbyte(command)} while busy with ${hexbyte(this._regs[Registers.internalCommand])}`);
        }
 
        // Set command.
        this._regs[Registers.internalCommand] = command;
 
        // Set busy, lower command full in status, result to 0.
        this._statusRaise(StatusFlag.busy);
        this._statusLower(StatusFlag.commandFull);
        this._setResult(0);
 
        // Default parameters. This supports the 1x128 byte sector commands.
        this._regs[Registers.internalParam_3] = 1;
        this._regs[Registers.internalParam_4] = 1;
 
        // Calculate parameters expected. Taken from the logic in the 8271 ROM.
        const numParams = command & 0x18 ? command & 0x3 : 5;
        this._regs[Registers.internalParamCount] = numParams;
 
        // Are we waiting for parameters?
        if (numParams) {
            // Parameters write from R7 downwards.
            this._regs[Registers.internalPointer] = Registers.internalParam_1;
            this._paramCallback = ParamAccept.command;
        } else {
            this._startCommand();
        }
    }
 
    _resultConsumed() {
        this._isResultReady = false;
        this._updateExternalStatus();
    }
 
    _paramWritten(param) {
        this._regs[Registers.internalParameter] = param;
        this._resultConsumed();
 
        switch (this._paramCallback) {
            case ParamAccept.none:
                break;
            case ParamAccept.command: {
                this._writeRegister(this._regs[Registers.internalPointer], param);
                --this._regs[Registers.internalPointer];
                if (--this._regs[Registers.internalParamCount] === 0) {
                    this._startCommand();
                }
                break;
            }
            case ParamAccept.specify: {
                this._logCommand(`specify param ${hexbyte(param)}`);
                this._writeRegister(this._regs[Registers.internalPointer], param);
                ++this._regs[Registers.internalPointer];
                if (--this._regs[Registers.internalParamCount] === 0) {
                    this._finishSimpleCommand();
                }
                break;
            }
            default:
                throw new Error(`Unexpected param callback ${this._paramCallback}`);
        }
    }
 
    _readRegister(reg) {
        reg &= 0x3f;
        Eif (reg < IntelFdc.NumRegisters) {
            return this._regs[reg];
        }
        reg &= 0x07;
        switch (reg) {
            case Registers.mmioDriveIn & 0x07:
                return this._driveIn;
            case Registers.mmioDriveOut & 0x07:
                // DFS-1.2 reads drive out in normal operation.
                return this._driveOut;
            case Registers.mmioClocks & 0x07:
                return this._mmioClocks;
            case Registers.mmioData & 0x07:
                return this._mmioData;
            default:
                this._log(`direct read from MMIO register ${hexbyte(reg)}`);
                break;
        }
        return 0;
    }
 
    _writeRegister(reg, val) {
        reg &= 0x3f;
        if (reg < IntelFdc.NumRegisters) {
            this._regs[reg] = val;
            return;
        }
        reg &= 0x07;
        switch (reg) {
            case Registers.mmioDriveOut & 0x07:
                // Bit 0x20 is important as it's used to select the side of the disc for
                // double-sided discs.
                // Bit 0x08 is important as it provides manual head load / unload control,
                // which includes motor spin up / down.
                // The parameter also includes drive select bits which override those in
                // the command.
                this._setDriveOut(val);
                break;
            case Registers.mmioClocks & 0x07:
                this._mmioClocks = val;
                break;
            case Registers.mmioData & 0x07:
                this._mmioData = val;
                break;
            default:
                this._log(`direct write to MMIO register ${hexbyte(reg)}`);
                break;
        }
    }
 
    _driveOutRaise(bits) {
        this._setDriveOut(bits | this._driveOut);
    }
 
    _driveOutLower(bits) {
        this._setDriveOut(this._driveOut & ~bits);
    }
 
    /**
     * @param {DriveOut|Number} driveOut
     */
    _setDriveOut(driveOut) {
        if (this._currentDrive) this._currentDrive.stopSpinning();
        this._currentDrive = null;
 
        // Note: unclear what to do if both drives are selected. We select no drive
        // for now, to avoid shenanigans.
        const selectBits = driveOut & DriveOut.selectFlags;
        if (selectBits === DriveOut.select_0) this._currentDrive = this._drives[0];
        else Iif (selectBits === DriveOut.select_1) this._currentDrive = this._drives[1];
 
        if (selectBits !== (this._driveOut & DriveOut.selectFlags)) {
            this._ready = false;
            this._readyPulses = 0;
            this._lastIndexEpoch = -Infinity;
            // Edges are counted from the new drive's level, not the old one's
            this._stateIsIndexPulse = this._index;
        }
        if (this._currentDrive) {
            if (driveOut & DriveOut.loadHead) this._currentDrive.startSpinning();
            this._currentDrive.selectSide(!!(driveOut & DriveOut.side));
        }
        this._driveOut = driveOut;
    }
 
    /**
     * @param {State|Number} state
     */
    _setState(state) {
        Iif (this._state !== state && this._logStateChanges) {
            this._log(`State ${this._state} -> ${state}`);
        }
        this._state = state;
        this._stateCount = 0;
        Iif (state === State.syncingForId || state === State.syncingForData) {
            this._shiftRegister = 0;
            this._numShifts = 0;
        }
    }
 
    /**
     * @param {Call|Number} callContext
     */
    _doSeek(callContext) {
        Eif (callContext !== Call.unchanged) this._callContext = callContext;
        let newTrack = this._regs[Registers.internalParam_1] + this._regs[Registers.internalSeekRetryCount];
        const trackRegOffset =
            this._driveOut & DriveOut.select_1 ? Registers.badTrack_1Drive_1 : Registers.badTrack_1Drive_0;
        // Add one to requested track for each bad track covered. */
        // EMU NOTE: this is based on a disassembly of the real 8271 ROM and yes,
        // integer overflow does occur!
        if (newTrack > 0) {
            if (this._regs[trackRegOffset + 0] <= newTrack) {
                newTrack = (newTrack + 1) & 0xff;
            }
            if (this._regs[trackRegOffset + 1] <= newTrack) {
                newTrack = (newTrack + 1) & 0xff;
            }
        }
        this._regs[Registers.internalSeekTarget_1] = newTrack;
        this._regs[Registers.internalSeekTarget_2] = newTrack;
        // Set low head current in drive output depending on track.
        Iif (newTrack >= 43) this._driveOut |= DriveOut.lowHeadCurrent;
        else this._driveOut &= ~DriveOut.lowHeadCurrent;
        // Work out seek direction and total number of steps. Pretend current track is 255 if a seek to 0.
        const curTrack = newTrack === 0 ? 255 : this._regs[trackRegOffset + 2];
        this._didSeekStep = false;
 
        // Skip to head load if there's no seek.
        if (newTrack === curTrack) {
            this._doLoadHead();
            return;
        }
 
        const steps = newTrack - curTrack;
        this._regs[Registers.internalSeekCount] = Math.abs(steps);
        if (steps > 0) this._driveOut |= DriveOut.direction;
        else this._driveOut &= ~DriveOut.direction;
        Eif (this._currentDrive) this._currentDrive.notifySeekAmount(steps, this._stepRateMs());
 
        // Seek pulses on the 8271 are about 10us, so let's just lower the output bit and make them unobservable
        // as we suspect they are on a real machine.
        this._driveOut &= ~DriveOut.step;
        // Current track registers are updated here before the actual step sequence.
        this._regs[trackRegOffset + 2] = this._regs[Registers.internalSeekTarget_2];
        // Update both track registers if "single actuator" flag is set.
        Iif (this._regs[Registers.mode] & FdcMode.singleActuator) {
            this._regs[Registers.trackDrive_0] = this._regs[Registers.internalSeekTarget_2];
            this._regs[Registers.trackDrive_1] = this._regs[Registers.internalSeekTarget_2];
        }
        this._doSeekStep();
    }
 
    _doSeekStep() {
        if (
            (this._trk0 && this._regs[Registers.internalSeekTarget_2] === 0) || // Seek to 0 done, TRK0 detected
            this._regs[Registers.internalSeekCount] === 0
        ) {
            this._doLoadHead();
            return;
        }
        //  We're going to actually step, so we'll need settle if the head is already loaded.
        this._didSeekStep = true;
        this._regs[Registers.internalSeekCount]--;
 
        Eif (this._currentDrive) this._currentDrive.seekOneTrack(this._driveOut & DriveOut.direction ? 1 : -1);
        this._setTimerMs(TimerState.seekStep, this._stepRateMs());
    }
 
    _stepRateMs() {
        const stepRate = this._regs[Registers.headStepRate];
        // Zero leaves the rate to the drive. Let's say 3ms.
        if (stepRate === 0) return 3;
        // The datasheet is ambiguous about whether the units are 1ms or 2ms for 5.25" drives. 1ms might
        // be your best guess from the datasheet, but timing on a real machine, it appears to be 2ms.
        return stepRate * 2;
    }
 
    _doLoadHead() {
        if (this._didSeekStep && this._currentDrive) this._currentDrive.notifySeekEnd();
        let postSeekTimeMs = 0;
        // The head load time replaces the settle time if there is both.
        if (!(this._driveOut & DriveOut.loadHead)) {
            this._driveOutRaise(DriveOut.loadHead);
            // Head load units are 4ms, doubled for 5.25" drives like the step and settle times.
            postSeekTimeMs = 8 * (this._regs[Registers.headLoadUnload] & 0xf);
        } else Eif (this._didSeekStep) {
            // All references state the units are 2ms for 5.25" drives.
            postSeekTimeMs = 2 * this._regs[Registers.headSettleTime];
        }
        if (postSeekTimeMs) {
            this._setTimerMs(TimerState.postSeek, postSeekTimeMs);
        } else {
            this._postSeekDispatch();
        }
    }
 
    _postSeekDispatch() {
        this._timerState = TimerState.none;
        Eif (!this._checkDriveReady()) return;
        switch (this._callContext) {
            case Call.seek:
                this._finishCommand(Result.ok);
                break;
            case Call.readId:
                this._indexPulseCallback = IndexPulse.startReadId;
                break;
            case Call.format:
                this._setupSectorSize();
                this._indexPulseCallback = IndexPulse.startFormat;
                this._checkWriteProtect();
                break;
            case Call.read:
            case Call.write:
                this._setupSectorSize();
                this._startIndexPulseTimeout();
                this._startSyncingForHeader();
                if (this._callContext === Call.write) this._checkWriteProtect();
                break;
            default:
                throw new Error(`Surprising call context post seek ${this._callContext}`);
        }
    }
 
    get _sectorSize() {
        const size = this._regs[Registers.internalParam_3] >>> 5;
        return 128 << size;
    }
 
    _setupSectorSize() {
        const msb = (this._sectorSize >>> 7) - 1;
        this._regs[Registers.internalCountLsb] = 0x80;
        this._regs[Registers.internalCountMsb] = msb;
        // Note the is R0, i.e. R0 is trashed here.
        this._regs[Registers.internalCountMsbCopy] = msb;
    }
 
    _setTimerMs(state, timerMs) {
        this._timerTask.cancel();
        this._timerState = state;
        this._timerTask.schedule(timerMs * 2000);
    }
 
    _startIndexPulseTimeout() {
        this._regs[Registers.internalIndexPulseCount] = 3;
        this._indexPulseCallback = IndexPulse.timeout;
    }
 
    _startSyncingForHeader() {
        this._regs[Registers.internalHeaderPointer] = 0x0c;
        this._setState(State.syncingForId);
    }
 
    _checkDriveReady() {
        this._doReadDriveStatus();
        const mask = this._driveOut & DriveOut.select_1 ? 0x40 : 0x04;
        Eif (!(this._regs[Registers.internalDriveInLatched] & mask)) {
            this._finishCommand(Result.driveNotReady);
            return false;
        }
        return true;
    }
 
    _checkWriteProtect() {
        if (this._regs[Registers.internalDriveInLatched] & 0x08) {
            this._finishCommand(Result.writeProtected);
        }
    }
 
    _startCommand() {
        let commandReg = this._regs[Registers.internalCommand];
        const origCommand = commandReg;
 
        // This update R21 and R27. R27 is later referenced for checking the write protect bit.
        this._doReadDriveStatus();
 
        this._paramCallback = ParamAccept.none;
 
        // Select the drive before logging so that head position is reported.
        // The MMIO clocks register really is used as a temporary storage for this.
        const selectBits = commandReg & DriveOut.selectFlags;
        this._mmioClocks = selectBits;
        if (selectBits !== (this._driveOut & DriveOut.selectFlags)) {
            // A change of drive select bits clears all drive out bits other than side select.
            // For example, the newly selected drive won't have the load head signal
            // active. This spins down any previously selected drive.
            const newSelectBits = selectBits | (this._driveOut & DriveOut.side);
            this._setDriveOut(newSelectBits);
        }
 
        // Mask out drive select bits from the command register, and parameter count.
        commandReg &= ~(DriveOut.selectFlags | 0x03);
        this._regs[Registers.internalCommand] = commandReg;
        this._logCommand(
            `command ${hexbyte(origCommand & 0x3f)} ` +
                `sel ${hexbyte(selectBits)} ` +
                `params ${hexbyte(this._regs[Registers.internalParam_1])} ` +
                `${hexbyte(this._regs[Registers.internalParam_2])} ` +
                `${hexbyte(this._regs[Registers.internalParam_3])} ` +
                `${hexbyte(this._regs[Registers.internalParam_4])} ` +
                `${hexbyte(this._regs[Registers.internalParam_5])} ` +
                `ptrk ${this._currentDrive ? this._currentDrive.track : -1} ` +
                `hpos ${this._currentDrive ? this._currentDrive.headPosition : -1}`,
        );
 
        const command = this._internalCommand;
        Iif (command === Command.scanData || command === Command.scanDataAndDeleted) {
            this._log("scan sectors doesn't work in a beeb");
        }
        this._doCommandDispatch();
    }
 
    get _internalCommand() {
        return (this._regs[Registers.internalCommand] & ~(DriveOut.selectFlags | 0x03)) >>> 2;
    }
 
    get _currentDiscIsSpinning() {
        return this._currentDrive ? this._currentDrive.spinning : false;
    }
 
    get _trk0() {
        return this._currentDrive ? this._currentDrive.track === 0 : false;
    }
 
    get _index() {
        return this._currentDrive ? this._currentDrive.indexPulse : false;
    }
 
    get _wrProt() {
        // A real drive would likely return `true` if no disc was inserted.
        return this._currentDrive ? this._currentDrive.writeProtect : false;
    }
 
    get _driveIn() {
        // Note: on @scarybeasts machine, bit 7 and bit 0 appear to be always set.
        let driveIn = 0x81;
        // RDY0 and RDY1 are the Beeb's latch, which outlives a brief stop of the motor
        if (this._driveReady) {
            Eif (this._driveOut & DriveOut.select_0) driveIn |= 0x04;
            Iif (this._driveOut & DriveOut.select_1) driveIn |= 0x40;
        }
        if (this._currentDiscIsSpinning) {
            // TRK0
            if (this._trk0) driveIn |= 0x02;
            // WR PROT
            Iif (this._wrProt) driveIn |= 0x08;
            // INDEX
            if (this._index) driveIn |= 0x10;
        }
 
        return driveIn;
    }
 
    _doReadDriveStatus() {
        let driveIn = this._driveIn;
        this._regs[Registers.internalDriveInCopy] = driveIn;
        this._regs[Registers.internalDriveInLatched] |= 0xbb;
        driveIn &= this._regs[Registers.internalDriveInLatched];
        this._regs[Registers.internalDriveInLatched] = driveIn;
        return driveIn;
    }
 
    _doCommandDispatch() {
        const command = this._internalCommand;
 
        switch (command) {
            case Command.unused_9:
            case Command.unused_12:
                throw new Error("Unused 8271 command");
            case Command.readDriveStatus: {
                const status = this._doReadDriveStatus();
                this._setResult(status);
                this._regs[Registers.internalDriveInLatched] = this._regs[Registers.internalDriveInCopy];
                this._finishSimpleCommand();
                break;
            }
            case Command.specify:
                this._regs[Registers.internalPointer] = this._regs[Registers.internalParam_1];
                this._regs[Registers.internalParamCount] = 3;
                this._paramCallback = ParamAccept.specify;
                break;
            case Command.writeSpecialRegister:
                this._writeRegister(this._regs[Registers.internalParam_1], this._regs[Registers.internalParam_2]);
                // WRITE_SPECIAL_REGISTER tidies up in a much simpler way than other commands.
                this._lowerBusyAndLog();
                break;
            case Command.readSpecialRegister:
                this._setResult(this._readRegister(this._regs[Registers.internalParam_1]));
                this._finishSimpleCommand();
                break;
            case Command.readId:
                // First dispatch for the command, we go through the seek / wait for index /
                // etc. rigamarole. The command is re-dispatched for the second and further
                // headers, where we just straight to searching for header sync.
                // This can also be used as an undocumented mode of READ_ID where a
                // non-zero value to the second parameter will skip syncing to the index
                // pulse.
                if (this._regs[Registers.internalParam_2] === 0) {
                    this._doSeek(Call.readId);
                } else {
                    this._startSyncingForHeader();
                }
                break;
            case Command.seek:
                this._doSeek(Call.seek);
                break;
            case Command.readData:
            case Command.readDataAndDeleted:
            case Command.verify:
            case Command.scanData:
            case Command.scanDataAndDeleted:
                this._doSeek(Call.read);
                break;
            case Command.writeData:
                this._regs[Registers.internalParamDataMarker] = IbmDiscFormat.dataMarkDataPattern;
                this._doSeek(Call.write);
                break;
            case Command.writeDeletedData:
                this._regs[Registers.internalParamDataMarker] = IbmDiscFormat.deletedDataMarkDataPattern;
                this._doSeek(Call.write);
                break;
            case Command.format:
                this._doSeek(Call.format);
                break;
            default:
                throw new Error(`Unexpected command ${command}`);
        }
    }
 
    _finishSimpleCommand() {
        this._lowerBusyAndLog();
        this._stopIrqCallbacks();
        this._clearCallbacks();
 
        const headUnloadCount = this._regs[Registers.headLoadUnload] >>> 4;
        if (headUnloadCount === 0) {
            // Unload immediately.
            this._spinDown();
        } else Iif (headUnloadCount === 0xf) {
            // Never automatically unload.
        } else {
            this._regs[Registers.internalIndexPulseCount] = headUnloadCount;
            this._indexPulseCallback = IndexPulse.spindown;
        }
    }
 
    _finishCommand(result) {
        Eif (result !== Result.ok) {
            this._driveOutLower(DriveOut.direction | DriveOut.step | DriveOut.writeEnable);
        }
        this._setResult(result | this._result);
        // Raise command completion IRQ.
        this._statusRaise(StatusFlag.nmi);
        this._finishSimpleCommand();
    }
 
    get _irqCallbacks() {
        return (this._regs[Registers.internalStatus] & 0x30) === 0x30;
    }
 
    _startIrqCallbacks() {
        // These bits don't affect the external status, so no need to re-calculate.
        this._regs[Registers.internalStatus] |= 0x30;
    }
 
    _stopIrqCallbacks() {
        // These bits don't affect the external status, so no need to re-calculate.
        this._regs[Registers.internalStatus] &= ~0x30;
    }
 
    _decrementCounter() {
        if (--this._regs[Registers.internalCountLsb]) return false;
        // Javascript's clamping for Uint8Array happens on assignment; so I can do if (--regs[x] !== 0xff) here.
        --this._regs[Registers.internalCountMsb];
        if (this._regs[Registers.internalCountMsb] !== 0xff) {
            this._regs[Registers.internalCountLsb] = 0x80;
            return false;
        }
        this._regs[Registers.internalCountMsb] = 0;
        this._stopIrqCallbacks();
        return true;
    }
 
    _clearCallbacks() {
        this._paramCallback = ParamAccept.none;
        this._indexPulseCallback = IndexPulse.none;
        Iif (this._timerState !== TimerState.none) {
            this._timerTask.cancel();
            this._timerState = TimerState.none;
        }
        // Think of this as the read/write callback from the bit processor.
        this._setState(State.idle);
    }
 
    _lowerBusyAndLog() {
        this._statusLower(StatusFlag.busy);
        this._logCommand(`status ${hexbyte(this._status)} result ${hexbyte(this._result)}`);
    }
 
    _spinDown() {
        this._driveOutLower(DriveOut.selectFlags | DriveOut.loadHead);
    }
 
    _timerFired() {
        // Counting milliseconds is done with r8 and r9, which are left at zero after a busy wait.
        this._regs[Registers.internalMsCountHi] = 0;
        this._regs[Registers.internalMsCountLo] = 0;
        switch (this._timerState) {
            case TimerState.seekStep:
                this._doSeekStep();
                break;
            case TimerState.postSeek:
                this._postSeekDispatch();
                break;
        }
    }
 
    _doWriteRun(callContext, byte) {
        this._mmioData = byte & 0xff;
        this._mmioClocks = 0xff;
        this._crc = IbmDiscFormat.crcAddByte(this._crc, this._mmioData);
        this._regs[Registers.internalWriteRunData] = this._mmioData;
        this._driveOutRaise(DriveOut.writeEnable);
        this._callContext = callContext;
        this._setState(State.writeRun);
    }
 
    _writeFFsAnd00s(callContext, numFFs) {
        if (numFFs !== -1) {
            this._regs[Registers.internalCountLsb] = numFFs;
            this._regs[Registers.internalCountMsb] = 0;
        }
        this._doWriteRun(callContext, 0xff);
    }
 
    snapshotState() {
        const scheduler = this._timerTask.scheduler;
        return {
            regs: this._regs.slice(),
            status: this._status,
            isResultReady: this._isResultReady,
            mmioData: this._mmioData,
            mmioClocks: this._mmioClocks,
            driveOut: this._driveOut,
            shiftRegister: this._shiftRegister,
            numShifts: this._numShifts,
            state: this._state,
            stateCount: this._stateCount,
            stateIsIndexPulse: this._stateIsIndexPulse,
            crc: this._crc,
            onDiscCrc: this._onDiscCrc,
            paramCallback: this._paramCallback,
            indexPulseCallback: this._indexPulseCallback,
            timerState: this._timerState,
            callContext: this._callContext,
            didSeekStep: this._didSeekStep,
            ready: this._ready,
            readyPulses: this._readyPulses,
            sinceIndexPulse: Number.isFinite(this._lastIndexEpoch) ? scheduler.epoch - this._lastIndexEpoch : null,
            timerTaskOffset: this._timerTask.scheduled() ? this._timerTask.expireEpoch - scheduler.epoch : null,
            drives: this._drives.map((d) => d.snapshotState()),
        };
    }
 
    restoreState(state) {
        this._regs.set(state.regs);
        this._status = state.status;
        this._isResultReady = state.isResultReady;
        this._mmioData = state.mmioData;
        this._mmioClocks = state.mmioClocks;
        this._driveOut = state.driveOut;
        // A snapshot from before the latch existed comes up ready, with a pulse as good as now.
        this._ready = state.ready ?? true;
        this._readyPulses = state.readyPulses ?? ReadyIndexPulses;
        this._lastIndexEpoch =
            state.sinceIndexPulse === undefined
                ? this._scheduler.epoch
                : state.sinceIndexPulse === null
                  ? -Infinity
                  : this._scheduler.epoch - state.sinceIndexPulse;
        this._shiftRegister = state.shiftRegister;
        this._numShifts = state.numShifts;
        this._state = state.state;
        this._stateCount = state.stateCount;
        this._stateIsIndexPulse = state.stateIsIndexPulse;
        this._crc = state.crc;
        this._onDiscCrc = state.onDiscCrc;
        this._paramCallback = state.paramCallback;
        this._indexPulseCallback = state.indexPulseCallback;
        this._timerState = state.timerState;
        this._callContext = state.callContext;
        this._didSeekStep = state.didSeekStep;
 
        // Restore drives
        for (let i = 0; i < this._drives.length; i++) {
            this._drives[i].restoreState(state.drives[i]);
        }
 
        // Derive _currentDrive from _driveOut
        this._currentDrive = null;
        const selectBits = this._driveOut & DriveOut.selectFlags;
        if (selectBits === DriveOut.select_0) this._currentDrive = this._drives[0];
        else Iif (selectBits === DriveOut.select_1) this._currentDrive = this._drives[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 NoiseAwareIntelFdc extends IntelFdc {
    constructor(cpu, ddNoise, scheduler, debugFlags) {
        super(cpu, scheduler, undefined, debugFlags);
        attachDriveNoise(this.drives, ddNoise);
    }
}