This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
fdc.js
3214 lines (3041 loc) · 138 KB
/
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
/**
* @fileoverview Implements the PCx86 Floppy Drive Controller (FDC) component
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/shared/lib/defines.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
if (typeof module !== "undefined") {
var Str = require("../../shared/lib/strlib");
var Web = require("../../shared/lib/weblib");
var DiskAPI = require("../../shared/lib/diskapi");
var Component = require("../../shared/lib/component");
var State = require("../../shared/lib/state");
var PCx86 = require("./defines");
var Messages = require("./messages");
var ChipSet = require("./chipset");
var Disk = require("./disk");
var Panel = require("./panel");
}
/*
* FDC Terms (see FDC.TERMS)
*
* C Cylinder Number the current or selected cylinder number
*
* D Data the data pattern to be written to a sector
*
* DS Drive Select the selected driver number encoded the same as bits 0 and 1 of the Digital Output
* Register (DOR); eg, DS0, DS1, DS2, or DS3
*
* DTL Data Length when N is 00, DTL is the data length to be read from or written to a sector
*
* EOT End Of Track the final sector number on a cylinder
*
* GPL Gap Length the length of gap 3 (spacing between sectors excluding the VCO synchronous field)
*
* H Head Address the head number, either 0 or 1, as specified in the ID field
*
* HD Head the selected head number, 0 or 1 (H = HD in all command words)
*
* HLT Head Load Time the head load time in the selected drive (2 to 256 milliseconds in 2-millisecond
* increments for the 1.2M-byte drive and 4 to 512 milliseconds in 4 millisecond increments
* for the 320K-byte drive)
*
* HUT Head Unload Time the head unload time after a read or write operation (0 to 240 milliseconds in
* 16-millisecond increments for the 1.2M-byte drive and 0 to 480 milliseconds in
* 32-millisecond increments for the 320K-byte drive)
*
* MF FM or MFM Mode 0 selects FM mode and 1 selects MFM (MFM is selected only if it is implemented)
*
* MT Multitrack 1 selects multitrack operation (both HD0 and HD1 will be read or written)
*
* N Number the number of data bytes written in a sector
*
* NCN New Cylinder Number the new cylinder number for a SEEK operation
*
* ND Non-Data Mode indicates an operation in the non-data mode
*
* PCN Present Cylinder Number the cylinder number at the completion of a SENSE INTERRUPT STATUS command
* (present position of the head)
*
* R Record the sector number to be read or written
*
* SC Sectors Per Cylinder the number of sectors per cylinder
*
* SK Skip this stands for skip deleted-data address mark
*
* SRT Stepping Rate this 4 bit byte indicates the stepping rate for the diskette drive as follows:
* 1.2M-Byte Diskette Drive: 1111=1ms, 1110=2ms, 1101=3ms
* 320K-Byte Diskette Drive: 1111=2ms, 1110=4ms, 1101=6ms
*
* STP STP Scan Test if STP is 1, the data in contiguous sectors is compared with the data sent
* by the processor during a scan operation; if STP is 2, then alternate sections
* are read and compared
*/
/**
* @typedef {Object} DriveType
* @property {number} heads
* @property {number} tracks
* @property {boolean} boot
*/
/**
* @typedef {Object} DriveInfo
* @property {number} iDrive
* @property {string} name
* @property {number} nCylinders
* @property {number} nHeads
* @property {number} nSectors
* @property {number} cbSector
* @property {boolean} fBusy
* @property {boolean} fLocal
* @property {boolean} fBootable
* @property {boolean} fRemovable
* @property {boolean} fWritable
* @property {number} nDiskCylinders
* @property {number} nDiskHeads
* @property {number} nDiskSectors
* @property {number} bHead
* @property {number} bCylinder
* @property {number} bCylinderSeek
* @property {number} bSector
* @property {number} bSectorEnd
* @property {number} nBytes
* @property {number} iByte
*/
/**
* class FDC
* @property {Array.<DriveInfo>} aDrives
* @property {Array.<DriveType>|null} aDriveTypes
* @unrestricted (allows the class to define properties, both dot and named, outside of the constructor)
*/
class FDC extends Component {
/**
* FDC(parmsFDC)
*
* The FDC component simulates a NEC µPD765A or Intel 8272A compatible floppy disk controller, and has one
* component-specific property:
*
* autoMount: one or more JSON-encoded objects, each containing 'name' and 'path' properties
* drives: an array of DriveType objects, each containing 'heads', 'tracks', and 'boot' properties
* sortBy: "name" to sort disks by name, "path" to sort by path, or "none" to leave as-is (default is "name")
*
* Regarding early diskette drives: the IBM PC Model 5150 originally shipped with single-sided drives,
* and therefore supported only 160Kb diskettes. That's the only diskette format PC-DOS 1.00 supported, too.
*
* At some point, 5150's started shipping with double-sided drives, but I'm not sure whether the ROMs changed;
* they probably did NOT change, because the original ROM BIOS already supported drives with multiple heads.
* However, what the ROM BIOS did NOT do was provide any indication of drive type, which as far as I can tell,
* meant you had to simply read/write/format tracks with the second head and check for errors.
*
* Presumably at the same time double-sided drives started shipping, PC-DOS 1.10 shipped, which added
* support for 320Kb diskettes. And the FORMAT command changed as well, defaulting to a double-sided format
* operation UNLESS you specified "FORMAT /1". If I run PC-DOS 1.10 and try to simulate a single-sided drive
* (by setting drive.nHeads = 1 in initDrive), FORMAT will balk with "Track 0 bad - disk unusable". I have to
* wonder if everyone with single-sided drives who upgraded to PC-DOS 1.10 also got that error, forcing them
* to always specify "FORMAT /1", or if I'm doing something wrong wrt single-sided drive simulation.
*
* I've noticed that if I turn FDC messages on ("m fdc on"), and then run "FORMAT B:/1", the command still
* tries to format head 1/track 0, followed by head 0/track 0, and then the FDC is reset, and the format operation
* proceeds with only head 0 for all tracks 0 through 39. FORMAT successfully creates a 160Kb single-sided diskette,
* but why it also tries to initially format track 0 using the second head remains a bit of a mystery.
*
* @this {FDC}
* @param {Object} parmsFDC
*/
constructor(parmsFDC)
{
/*
* TODO: Indicate the type of diskette image being loaded (this might help folks understand what's going
* on when they try to load a diskette image that's larger than what the selected operating system supports).
*/
super("FDC", parmsFDC, Messages.FDC);
this['dmaRead'] = FDC.prototype.doDMARead;
this['dmaWrite'] = FDC.prototype.doDMAWrite;
this['dmaFormat'] = FDC.prototype.doDMAFormat;
this.aDriveTypes = null;
/*
* We don't eval() sDriveTypes until initBus() is called, so that we can check for any machine overrides;
* note that the override, if any, must be named 'floppyDrives' to avoid conflicting with the HDC's 'drives'
* setting.
*/
this.sDriveTypes = parmsFDC['drives'];
/*
* We record any 'autoMount' object now, but we no longer parse it until initBus(), because the Computer's
* getMachineParm() service may have an override for us.
*/
this.configMount = this.parseConfig(parmsFDC['autoMount']);
/*
* This establishes "name" as the default; if we decide we'd prefer "none" to be the default (ie, the order
* to use when no sortBy value is specified), we can just drop the '|| "name"', because an undefined value is
* just as falsey as null.
*
* The code that actually performs the sorting (in setBinding()) first checks that sortBy is not falsey, and
* then assumes that the non-falsey value must be either "path" or "name", and since it explicitly checks for
* "path" first, any non-sensical value will be treated as "name" (which is fine, since that's our current default).
*/
this.sortBy = parmsFDC['sortBy'] || "name";
if (this.sortBy == "none") this.sortBy = null;
/*
* The following array keeps track of every disk image we've ever mounted. Each entry in the
* array is another array whose elements are:
*
* [0]: name of disk
* [1]: path of disk
* [2]: array of deltas, uninitialized until the disk is unmounted and/or all state is saved
*
* See functions addDiskHistory() and updateDiskHistory().
*/
this.aDiskHistory = [];
/*
* Support for local disk images is currently limited to desktop browsers with FileReader support;
* when this flag is set, setBinding() allows local disk bindings and informs initBus() to update the
* "listDisks" binding accordingly.
*/
this.fLocalDisks = (!Web.isMobile() && window && 'FileReader' in window);
/*
* If the HDC component is configured for removable discs (ie, if it's configured as a CD-ROM drive),
* it may prefer to overload our drive control for easier disc selection, in which case this will contain
* drive name properties mapped to external disc lists.
*/
this.driveActive = null;
this.externalDrives = {};
this.externalActive = null;
/*
* The remainder of FDC initialization now takes place in our initBus() handler, largely because we
* want initController() to have access to the ChipSet component, so that it can query switches and/or CMOS
* settings that determine the number of drives and their characteristics (eg, 40-track vs. 80-track),
* which it can then pass on to initDrive().
*/
this.fAutoScroll = false;
this['exports'] = {
'loadDisk': this.loadSelectedDisk,
'wait': this.waitDrives
};
}
/**
* setBinding(sHTMLType, sBinding, control, sValue)
*
* @this {FDC}
* @param {string} sHTMLType is the type of the HTML control (eg, "button", "list", "text", "submit", "textarea", "canvas")
* @param {string} sBinding is the value of the 'binding' parameter stored in the HTML control's "data-value" attribute (eg, "listDisks")
* @param {HTMLElement} control is the HTML control DOM object (eg, HTMLButtonElement)
* @param {string} [sValue] optional data value
* @return {boolean} true if binding was successful, false if unrecognized binding request
*/
setBinding(sHTMLType, sBinding, control, sValue)
{
let fdc = this;
/*
* TODO: Making copies of control that are simply cast to different types seems silly, but it doesn't
* really cost anything and it's cleaner than doing a lot MORE type overrides inline. However, it still
* doesn't solve all my problems: controlForm should really be cast as HTMLFormElement, but JavaScript
* inspections refuse to believe there's an 'onsubmit' property on an HTMLFormElement that I can override.
*/
let controlForm = /** @type {Object} */ (control);
let controlSelect = /** @type {HTMLSelectElement} */ (control);
switch (sBinding) {
case "listDisks":
this.bindings[sBinding] = controlSelect;
/*
* Since binding is a one-time initialization operation, it's also the perfect time to
* perform whatever sorting (if any) is indicated by the FDC component's "sortBy" property.
*
* And since setBinding() is called before initBus(), that means any "special" disk entries
* will be added after the sorting, so we won't be "burying" those entries somewhere in the
* middle.
*/
if (this.sortBy) {
let i, aOptions = [];
/*
* NOTE: All this monkeying around with copying the elements from control.options to aOptions
* and then back again is necessary because control.options isn't a *real* Array (at least not
* in all browsers); consequently, it may have no sort() method. It has a length property,
* along with numeric properties 0 to length-1, but it's still probably just an Object, not
* an Array.
*
* Also note that changing the order of the control's options would ordinarily mean that the
* control's selectedIndex may now be incorrect, but in our case, it doesn't matter, because
* we have a special function, displayDiskette(), that will be called at LEAST once during
* initialization, ensuring that selectedIndex is set correctly.
*/
for (i = 0; i < controlSelect.options.length; i++) {
aOptions.push(controlSelect.options[i]);
}
aOptions.sort(function(a, b) {
/*
* I've switched to localeCompare() because it offers case-insensitivity by default;
* I'm still a little concerned that we could somehow end up with list elements whose text
* and/or value properties are undefined (because calling a method on an undefined variable
* will throw an exception), but maybe I'm being overly paranoid....
*/
if (fdc.sortBy != "path") {
return a.text.localeCompare(b.text);
} else {
return a.value.localeCompare(b.value);
}
});
for (i = 0; i < aOptions.length; i++) {
try {
/*
* TODO: Determine why this line blows up in IE8; are the properties of an options object not settable in IE8?
*/
controlSelect.options[i] = aOptions[i];
} catch(e) {
break;
}
}
}
controlSelect.onchange = function onChangeListDisks(event) {
fdc.updateSelectedDiskette();
};
return true;
case "descDisk":
case "listDrives":
this.bindings[sBinding] = controlSelect;
/*
* I tried going with onclick instead of onchange, so that if you wanted to confirm what's
* loaded in a particular drive, you could click the drive control without having to change it.
* However, that doesn't seem to work for all browsers, so I've reverted to onchange.
*/
controlSelect.onchange = function onChangeListDrives(event) {
let iDrive = Str.parseInt(controlSelect.value, 10);
if (iDrive != null) fdc.displayDiskette(iDrive, true);
};
return true;
case "loadDisk":
this.bindings[sBinding] = control;
control.onclick = function onClickLoadDisk(event) {
if (!fdc.externalActive) {
fdc.loadSelectedDisk();
} else {
let externalDrive = fdc.externalDrives[fdc.externalActive];
externalDrive.controller.loadSelectedDisk(externalDrive.drive.iDrive, externalDrive.controlDisks);
}
};
return true;
case "saveDisk":
/*
* Yes, technically, this feature does not require "Local disk support" (which is really a reference
* to FileReader support), but since fLocalDisks is also false for all mobile devices, and since there
* is an "orthogonality" to disabling both features in tandem, let's just let it slide, OK?
*/
if (!this.fLocalDisks) {
if (DEBUG) this.log("Local disk support not available");
/*
* We could also simply remove the control; eg:
*
* control.parentNode.removeChild(@type {Node} (control));
*
* but as long as the parentNode remains, with its accompanying style, the visual layout of the machine
* could look odd. So let's change the parent's style instead.
*/
control.parentNode.style.display = "none";
return false;
}
this.bindings[sBinding] = control;
control.onclick = function onClickSaveDisk(event) {
let controlDrives = fdc.bindings["listDrives"];
if (controlDrives && controlDrives.options && fdc.aDrives) {
let iDriveSelected = Str.parseInt(controlDrives.value, 10) || 0;
let drive = fdc.aDrives[iDriveSelected];
if (drive) {
/*
* Note the similarity (and hence factoring opportunity) between this code and the HDC's
* "saveHD*" binding.
*/
let disk = drive.disk;
if (disk) {
if (DEBUG) fdc.println("saving diskette " + disk.sDiskPath + "...");
let sAlert = Web.downloadFile(disk.encodeAsBinary(), "octet-stream", true, disk.sDiskFile.replace(".json", ".img"));
Component.alertUser(sAlert);
} else {
fdc.notice("No diskette loaded in drive.");
}
} else {
fdc.notice("No diskette drive selected.");
}
}
};
return true;
case "mountDisk":
if (!this.fLocalDisks) {
if (DEBUG) this.log("Local disk support not available");
/*
* We could also simply hide the control; eg:
*
* controlForm.style.display = "none";
*
* but removing the control altogether seems better.
*/
controlForm.parentNode.removeChild(/** @type {Node} */ (controlForm));
return false;
}
this.bindings[sBinding] = controlForm;
/*
* Enable "Mount" button only if a file is actually selected
*/
controlForm.onchange = function onChangeMountDisk() {
let fieldset = controlForm.children[0];
let files = fieldset.children[0].files;
let submit = fieldset.children[1];
submit.disabled = !files.length;
};
controlForm.onsubmit = function onSubmitMountDisk(event) {
let file = event.currentTarget[1].files[0];
if (file) {
let sDiskPath = file.name;
let sDiskName = Str.getBaseName(sDiskPath, true);
fdc.loadSelectedDrive(sDiskName, sDiskPath, file);
}
/*
* Prevent reloading of web page after form submission
*/
return false;
};
return true;
default:
break;
}
return false;
}
/**
* initBus(cmp, bus, cpu, dbg)
*
* @this {FDC}
* @param {Computer} cmp
* @param {BusX86} bus
* @param {CPUx86} cpu
* @param {DebuggerX86} dbg
*/
initBus(cmp, bus, cpu, dbg)
{
this.bus = bus;
this.cpu = cpu;
this.dbg = dbg;
this.cmp = cmp;
let aDriveTypes = cmp.getMachineParm('floppyDrives');
if (aDriveTypes) {
if (typeof aDriveTypes == "string") {
this.sDriveTypes = aDriveTypes;
} else {
this.aDriveTypes = aDriveTypes;
this.sDriveTypes = "";
}
}
if (this.sDriveTypes) {
try {
/*
* We must take care when parsing user-supplied JSON-encoded drive data.
*/
this.aDriveTypes = eval("(" + this.sDriveTypes + ")");
this.sDriveTypes = "";
} catch (e) {
Component.error("FDC drive configuration error: " + e.message + " (" + this.sDriveTypes + ")");
}
}
this.chipset = cmp.getMachineComponent("ChipSet");
this.parseConfig(this.cmp.getMachineParm('autoMount'), this.configMount);
this.panel = cmp.getMachineComponent("Panel");
/*
* If we didn't need auto-mount support, we could defer controller initialization until we received a powerUp() notification,
* at which point reset() would call initController(), or restore() would restore the controller; in that case, all we'd need
* to do here is call setReady().
*/
this.initController();
bus.addPortInputTable(this, FDC.aPortInput);
bus.addPortOutputTable(this, FDC.aPortOutput);
this.addDiskette("None", "", true);
if (this.fLocalDisks) this.addDiskette("Local Disk", "?");
this.addDiskette("Remote Disk", "??");
if (!this.autoMount()) this.setReady();
}
/**
* setLED(color)
*
* @this {FDC}
* @param {string} [color]
*/
setLED(color)
{
if (this.panel) {
this.panel.setLED("fdcState", color);
}
}
/**
* parseConfig(config, configMerge)
*
* @this {FDC}
* @param {Object|string|undefined} config
* @param {Object} [configMerge]
* @return {Object}
*/
parseConfig(config, configMerge)
{
if (config) {
if (typeof config == "string") {
try {
/*
* We must take care when parsing user-supplied JSON-encoded diskette data.
*/
config = /** @type {Object} */ (eval("(" + config + ")"));
} catch (e) {
Component.error("FDC auto-mount error: " + e.message + " (" + config + ")");
config = {};
}
}
} else {
config = {};
}
for (let sDrive in config) {
if (configMerge) configMerge[sDrive] = config[sDrive];
}
return config;
}
/**
* powerUp(data, fRepower)
*
* @this {FDC}
* @param {Object|null} data
* @param {boolean} [fRepower]
* @return {boolean} true if successful, false if failure
*/
powerUp(data, fRepower)
{
if (!fRepower) {
if (!data) {
this.reset(true);
if (this.cmp.fReload) {
/*
* If the computer's fReload flag is set, we're required to toss all currently
* loaded disks and remount all disks specified in the auto-mount configuration.
*/
this.unloadAllDrives(true);
this.autoMount(true);
}
} else {
if (!this.restore(data)) return false;
}
this.resetDriveList();
}
return true;
}
/**
* powerDown(fSave, fShutdown)
*
* @this {FDC}
* @param {boolean} [fSave]
* @param {boolean} [fShutdown]
* @return {Object|boolean} component state if fSave; otherwise, true if successful, false if failure
*/
powerDown(fSave, fShutdown)
{
return fSave? this.save() : true;
}
/**
* reset()
*
* NOTE: initController() establishes the maximum possible number of drives, but it's not until
* initController() interrogates the current SW1 settings that we will have an ACTUAL number of drives
* (nDrives), at which point we can also update the contents of the "listDrives" HTML control, if any.
*
* @this {FDC}
* @param {boolean} [fPowerUp] (this isn't set by a computer reset(), only by our powerUp() handler)
*/
reset(fPowerUp)
{
/*
* NOTE: The controller is also initialized by the constructor, to assist with auto-mount support,
* so think about whether we can skip powerUp initialization.
*/
this.initController();
/*
* Don't bother resetting the drive list if we're being called by powerUp(), because powerUp() will.
*/
if (!fPowerUp) this.resetDriveList();
}
/**
* addDrive(drive, controller, controlDisks)
*
* @this {FDC}
* @param {DriveInfo} drive
* @param {Component} controller
* @param {HTMLSelectElement} controlDisks
*/
addDrive(drive, controller, controlDisks)
{
this.externalDrives[drive.name] = {drive, controller, controlDisks};
}
/**
* resetDriveList()
*
* @this {FDC}
*/
resetDriveList()
{
/*
* Populate the HTML controls to match the actual (well, um, specified) number of floppy drives.
*/
let controlDrives;
if ((controlDrives = this.bindings['listDrives'])) {
while (controlDrives.firstChild) {
controlDrives.removeChild(controlDrives.firstChild);
}
let iDrive = 0;
controlDrives.value = "";
while (iDrive < this.nDrives) {
let controlOption = document.createElement("option");
controlOption.value = iDrive.toString();
controlOption.text = String.fromCharCode(0x41 + iDrive) + ":";
controlDrives.appendChild(controlOption);
/*
* Add a second element for the drive that will automatically "write-protect" the selected diskette.
*/
controlOption = document.createElement("option");
controlOption.value = iDrive.toString();
controlOption.text = String.fromCharCode(0x41 + iDrive) + "*";
controlOption.title = "write-protected"; // NOTE: this "tooltip" attribute does not work on all browsers (eg, Chrome)
controlDrives.appendChild(controlOption);
iDrive++;
}
for (let name in this.externalDrives) {
let controlOption = document.createElement("option");
controlOption.value = iDrive.toString();
controlOption.text = name;
controlDrives.appendChild(controlOption);
iDrive++;
}
if (this.nDrives > 0) {
controlDrives.value = "0";
this.displayDiskette(0, false);
}
}
}
/**
* save()
*
* This implements save support for the FDC component.
*
* @this {FDC}
* @return {Object}
*/
save()
{
let state = new State(this);
state.set(0, this.saveController());
return state.data();
}
/**
* restore(data)
*
* This implements restore support for the FDC component.
*
* @this {FDC}
* @param {Object} data
* @return {boolean} true if successful, false if failure
*/
restore(data)
{
return this.initController(data[0]);
}
/**
* initController(data)
*
* @this {FDC}
* @param {Array} [data]
* @return {boolean} true if successful, false if failure
*/
initController(data)
{
let i = 0, iDrive;
let fSuccess = true;
if (!data) {
data = [0, 0, FDC.REG_STATUS.RQM, new Array(9), 0, 0, 0, []];
}
/*
* Selected drive (from regOutput), which can only be selected if its motor is on (see regOutput).
*/
this.iDrive = data[i++];
i++; // unused slot (if reused, bias by +4, since it was formerly a unit #)
/*
* Defaults to FDC.REG_STATUS.RQM set (ready for command) and FDC.REG_STATUS.READ_DATA clear (data direction
* is from processor to the FDC Data Register).
*/
this.regStatus = data[i++];
/*
* There can be up to 9 command bytes, and 7 result bytes, so 9 data registers are sufficient for communicating
* in both directions (hence, the new Array(9) default above).
*/
this.regDataArray = data[i++];
/*
* Determines the next data byte to be received.
*/
this.regDataIndex = data[i++];
/*
* Determines the next data byte to be sent (internally, we use regDataIndex to read data bytes, up to this total).
*/
this.regDataTotal = data[i++];
this.regOutput = data[i++];
let dataDrives = data[i++];
/*
* Initialize the disk history (if available) before initializing the drives, so that any disk deltas can be
* applied to disk images that are already loaded.
*/
let aDiskHistory = data[i++];
if (aDiskHistory != null) this.aDiskHistory = aDiskHistory;
/*
* Default to the maximum number of drives unless ChipSet can give us a specific number of drives.
*/
this.nDrives = this.aDriveTypes? this.aDriveTypes.length : (this.chipset? this.chipset.getDIPFloppyDrives() : 4);
/*
* I would prefer to allocate only nDrives, but as discussed in the handling of the FDC.REG_DATA.CMD.SENSE_INT
* command, we're faced with situations where the controller must respond to any drive in the range 0-3, regardless
* how many drives are actually installed. We still rely upon nDrives to determine the number of drives displayed
* to the user, however.
*/
if (this.aDrives === undefined) {
this.aDrives = new Array(4);
}
for (iDrive = 0; iDrive < this.aDrives.length; iDrive++) {
let fInit = false;
let drive = this.aDrives[iDrive];
if (drive === undefined) {
/*
* The first time each drive is initialized, we query its capacity (based on switches or CMOS) and set
* the drive's physical limits accordingly (ie, max tracks, max heads, and max sectors/track).
*/
fInit = true;
drive = this.aDrives[iDrive] = {};
let nKb = (this.chipset? this.chipset.getDIPFloppyDriveSize(iDrive) : 0);
switch(nKb) {
case 160:
case 180:
drive.nHeads = 1; // required for single-sided drives only (all others default to double-sided)
/* falls through */
case 320:
case 360:
/* falls through */
default: // drives that don't have a recognized capacity default to 360
drive.nCylinders = 40;
drive.nSectors = 9; // drives capable of writing 8 sectors/track can also write 9 sectors/track
break;
case 720:
drive.nCylinders = 80;
drive.nSectors = 9;
break;
case 1200:
drive.nCylinders = 80;
drive.nSectors = 15;
break;
case 1440:
drive.nCylinders = 80;
drive.nSectors = 18;
break;
}
}
if (!this.initDrive(drive, iDrive, this.aDriveTypes? this.aDriveTypes[iDrive] : null, dataDrives[iDrive], fInit)) {
fSuccess = false;
}
}
/*
* regInput and regControl (port 0x3F7) were not present on controllers prior to MODEL_5170, which is why
* we don't include initializers for them in the default data array; we could eliminate them on older models,
* but we don't have access to the model info right now, and there's no real cost to always including them
* in the FDC state.
*
* The bigger compatibility question is whether to always include hooks for them (see aPortInput and aPortOutput).
*/
this.regInput = data[i++] || 0; // TODO: Determine if we should default to FDC.REG_INPUT.DISK_CHANGE instead of 0
this.regControl = data[i] || FDC.REG_CONTROL.RATE500K; // default to maximum data rate
if (this.messageEnabled()) this.printf("FDC initialized for %d drive(s)\n", this.aDrives.length);
return fSuccess;
}
/**
* saveController()
*
* @this {FDC}
* @return {Array}
*/
saveController()
{
let i = 0;
let data = [];
data[i++] = this.iDrive;
data[i++] = 0;
data[i++] = this.regStatus;
data[i++] = this.regDataArray;
data[i++] = this.regDataIndex;
data[i++] = this.regDataTotal;
data[i++] = this.regOutput;
data[i++] = this.saveDrives();
data[i++] = this.saveDeltas();
data[i++] = this.regInput;
data[i] = this.regControl;
return data;
}
/**
* initDrive(drive, iDrive, driveType, data, fInit)
*
* TODO: Consider a separate Drive class that both FDC and HDC can use, since there's a lot of commonality
* between the drive objects created by both controllers. This will clean up overall drive management and allow
* us to factor out some common Drive methods (eg, advanceSector()).
*
* @this {FDC}
* @param {DriveInfo} drive
* @param {number} iDrive
* @param {DriveType|null} driveType
* @param {Array|undefined} data
* @param {boolean} fInit
* @return {boolean} true if successful, false if failure
*/
initDrive(drive, iDrive, driveType, data, fInit)
{
let i = 0;
let fSuccess = true;
drive.iDrive = iDrive;
drive.fBusy = drive.fLocal = false;
drive.fnCallReady = null;
let nHeads = driveType && driveType['heads'];
drive.fBootable = driveType && driveType['boot'];
if (drive.fBootable == null) drive.fBootable = true;
if (fInit) {
drive.fWritable = true;
if (nHeads) this.status("drive %d configured with %d head%s", iDrive, nHeads, nHeads > 1? 's' : '');
if (!drive.fBootable) this.status("drive %d configured as non-bootable", iDrive);
}
if (data === undefined) {
/*
* We set a default of two heads (MODEL_5150 PCs originally shipped with single-sided drives,
* but the ROM BIOS appears to have always supported both drive types).
*/
data = [FDC.REG_DATA.RES.RESET, true, 0, nHeads || 2, 0];
}
if (typeof data[1] == "boolean") {
/*
* Note that when no data is provided (eg, when the controller is being reinitialized), we now take
* care to preserve any drive defaults that initController() already obtained for us, falling back to
* bare minimums only when all else fails.
*/
data[1] = [
FDC.DEFAULT_DRIVE_NAME, // a[0]
drive.nCylinders || 40, // a[1]
drive.nHeads || data[3],// a[2]
drive.nSectors || 9, // a[3]
drive.cbSector || 512, // a[4]
data[1], // a[5]
drive.nDiskCylinders, // a[6]
drive.nDiskHeads, // a[7]
drive.nDiskSectors // a[8]
];
}
/*
* resCode used to be an FDC global, but in order to insulate FDC state from the operation of various functions
* that operate on drive objects (eg, readData and writeData), I've made it a per-drive variable. This choice,
* similar to my choice for handling PCN, may be contrary to how the actual hardware works, but I prefer this
* approach, as long as it doesn't expose any incompatibilities that any software actually cares about.
*/
drive.resCode = data[i++];
/*
* Some additional drive properties/defaults that are largely for the Disk component's benefit.
*/
let a = data[i++];
drive.name = a[0];
drive.nCylinders = a[1]; // cylinders
drive.nHeads = a[2]; // heads/cylinders
drive.nSectors = a[3]; // sectors/track
drive.cbSector = a[4]; // bytes/sector
drive.fRemovable = a[5];
/*
* If we have current media parameters, restore them; otherwise, default to the drive's physical parameters.
*/
if ((drive.nDiskCylinders = a[6])) {
drive.nDiskHeads = a[7];
drive.nDiskSectors = a[8];
} else {
drive.nDiskCylinders = drive.nCylinders;
drive.nDiskHeads = drive.nHeads;
drive.nDiskSectors = drive.nSectors;
}
/*
* The next group of properties are set by various FDC command sequences.
*
* We initialize this.iDrive (above) and drive.bHead and drive.bCylinder (below) to zero, but leave the rest undefined,
* awaiting their first FDC command. We do this because the initial SENSE_INT command returns a PCN, which will also
* be undefined unless we have at least zeroed both the current drive and the "present" cylinder on that drive.
*
* Alternatively, I could make PCN a global FDC variable. That may be closer to how the actual hardware operates,
* but I'm using per-drive variables so that the FDC component can be a good client to both the CPU and other components.
*
* COMPATIBILITY ALERT: The MODEL_5170 BIOS ("DSKETTE_SETUP") attempts to discern the drive type (double-density vs.
* high-capacity) by "slapping" the heads around -- "litrally" (it uses a constant named "TRK_SLAP" equal to 48).
* After seeking to "TRK_SLAP", the BIOS performs a series of seeks, looking for the precise point where the heads
* return to track 0.
*
* Here's how it works: the BIOS seeks to track 48 (which is fine on an 80-track 1.2Mb high-capacity drive, but 9 tracks
* too far on a 40-track 360Kb double-density drive), then seeks to track 10, and then seeks in single-track increments
* up to 10 more times until the SENSE_DRIVE command returns ST3 with the TRACK0 bit set.
*
* This implies that SEEK isn't really seeking to a specified cylinder, but rather it is calculating a delta from
* the previous cylinder to the specified cylinder, and stepping over that number of tracks. Which means that SEEK
* is updating a "logical" cylinder number, not the "physical" (actual) cylinder number. Presumably a RECALIBRATE
* command will bring the logical and physical values into sync, but once an out-of-bounds cylinder is requested, they
* will be out of sync.
*
* To simulate this, bCylinder is now treated as the "physical" cylinder (since that's how it's ALWAYS been used here),
* and bCylinderSeek will now track (pun intended) the "logical" cylinder that's programmed via SEEK commands.
*/
drive.bHead = data[i++];
drive.bCylinderSeek = data[i++]; // the data[] slot where we used to store drive.nHeads (or -1)
drive.bCylinder = data[i++];
if (drive.bCylinderSeek >= 100) { // verify that the saved bCylinderSeek is valid, otherwise sync it with bCylinder
drive.bCylinderSeek -= 100;
} else {
drive.bCylinderSeek -= drive.bCylinder;
}
drive.bSector = data[i++];
drive.bSectorEnd = data[i++]; // aka EOT
drive.nBytes = data[i++];
/*
* The next group of properties are managed by worker functions (eg, doRead()) to maintain state across DMA requests.
*/
drive.iByte = data[i++]; // location of the next byte to be accessed in the current sector
drive.sector = null;
/*
* We no longer reinitialize drive.disk, in order to retain previously mounted diskette across resets;
* however, we do ensure that sDiskPath is initialized to a default that displayDiskette() can deal with.
*/
if (!drive.disk) drive.sDiskPath = "";
let deltas = data[i++];
if (deltas == 102) deltas = false; // v1.02 backward-compatibility
if (typeof deltas == "boolean") {
let fLocal = deltas;