-
Notifications
You must be signed in to change notification settings - Fork 68
/
intel-fdc.js
1716 lines (1579 loc) · 61.9 KB
/
intel-fdc.js
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
// Translated from beebjit by Chris Evans.
// https://github.com/scarybeasts/beebjit
// eslint-disable-next-line no-unused-vars
import { Cpu6502 } from "./6502.js";
// eslint-disable-next-line no-unused-vars
import { Disc, IbmDiscFormat } from "./disc.js";
import { DiscDrive } from "./disc-drive.js";
// eslint-disable-next-line no-unused-vars
import { Scheduler } from "./scheduler.js";
import * as utils from "./utils.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,
});
/**
* 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 {DiscDrive[] | 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 {DiscDrive} */
this._currentDrive = null;
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;
// Derived from one of the regs plus _isResultReady.
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.
if (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.
// TODO(matt) - we don't model NMIs properly here, each device should have its own nmi line
this._cpu.NMI(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 ${utils.hexword(addr)}"`);
}
}
_log(message) {
console.log(`8271: ${message}`);
}
_logCommand(message) {
if (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.
if (val !== 0 && val !== 1) {
this._log("funky reset");
}
if (val === 1) {
this._logCommand("reset");
this.reset();
}
break;
case 3:
default:
this._log(`Not supported: ${utils.hexword(addr)}=${utils.hexbyte(val)}`);
}
}
_checkIndexPulse() {
const wasIndexPulse = this._stateIsIndexPulse;
this._stateIsIndexPulse = this._index;
// Looking for pulse going high
if (!this._stateIsIndexPulse || wasIndexPulse) return;
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:
if (--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}`);
}
}
_pulsesCallback(pulses, count) {
if (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.
if (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=${utils.hexbyte(clocks)} data=${utils.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) {