xref: /openbmc/qemu/hw/block/fdc.c (revision c3ae40e12cd7a41d2620ca2b771f6e167c0632d6)
1 /*
2  * QEMU Floppy disk emulator (Intel 82078)
3  *
4  * Copyright (c) 2003, 2007 Jocelyn Mayer
5  * Copyright (c) 2008 Hervé Poussineau
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 /*
26  * The controller is used in Sun4m systems in a slightly different
27  * way. There are changes in DOR register and DMA is not available.
28  */
29 
30 #include "qemu/osdep.h"
31 #include "hw/hw.h"
32 #include "hw/block/fdc.h"
33 #include "qemu/error-report.h"
34 #include "qemu/timer.h"
35 #include "hw/isa/isa.h"
36 #include "hw/sysbus.h"
37 #include "sysemu/block-backend.h"
38 #include "sysemu/blockdev.h"
39 #include "sysemu/sysemu.h"
40 #include "qemu/log.h"
41 
42 /********************************************************/
43 /* debug Floppy devices */
44 //#define DEBUG_FLOPPY
45 
46 #ifdef DEBUG_FLOPPY
47 #define FLOPPY_DPRINTF(fmt, ...)                                \
48     do { printf("FLOPPY: " fmt , ## __VA_ARGS__); } while (0)
49 #else
50 #define FLOPPY_DPRINTF(fmt, ...)
51 #endif
52 
53 /********************************************************/
54 /* Floppy drive emulation                               */
55 
56 typedef enum FDriveRate {
57     FDRIVE_RATE_500K = 0x00,  /* 500 Kbps */
58     FDRIVE_RATE_300K = 0x01,  /* 300 Kbps */
59     FDRIVE_RATE_250K = 0x02,  /* 250 Kbps */
60     FDRIVE_RATE_1M   = 0x03,  /*   1 Mbps */
61 } FDriveRate;
62 
63 typedef enum FDriveSize {
64     FDRIVE_SIZE_UNKNOWN,
65     FDRIVE_SIZE_350,
66     FDRIVE_SIZE_525,
67 } FDriveSize;
68 
69 typedef struct FDFormat {
70     FloppyDriveType drive;
71     uint8_t last_sect;
72     uint8_t max_track;
73     uint8_t max_head;
74     FDriveRate rate;
75 } FDFormat;
76 
77 /* In many cases, the total sector size of a format is enough to uniquely
78  * identify it. However, there are some total sector collisions between
79  * formats of different physical size, and these are noted below by
80  * highlighting the total sector size for entries with collisions. */
81 static const FDFormat fd_formats[] = {
82     /* First entry is default format */
83     /* 1.44 MB 3"1/2 floppy disks */
84     { FLOPPY_DRIVE_TYPE_144, 18, 80, 1, FDRIVE_RATE_500K, }, /* 3.5" 2880 */
85     { FLOPPY_DRIVE_TYPE_144, 20, 80, 1, FDRIVE_RATE_500K, }, /* 3.5" 3200 */
86     { FLOPPY_DRIVE_TYPE_144, 21, 80, 1, FDRIVE_RATE_500K, },
87     { FLOPPY_DRIVE_TYPE_144, 21, 82, 1, FDRIVE_RATE_500K, },
88     { FLOPPY_DRIVE_TYPE_144, 21, 83, 1, FDRIVE_RATE_500K, },
89     { FLOPPY_DRIVE_TYPE_144, 22, 80, 1, FDRIVE_RATE_500K, },
90     { FLOPPY_DRIVE_TYPE_144, 23, 80, 1, FDRIVE_RATE_500K, },
91     { FLOPPY_DRIVE_TYPE_144, 24, 80, 1, FDRIVE_RATE_500K, },
92     /* 2.88 MB 3"1/2 floppy disks */
93     { FLOPPY_DRIVE_TYPE_288, 36, 80, 1, FDRIVE_RATE_1M, },
94     { FLOPPY_DRIVE_TYPE_288, 39, 80, 1, FDRIVE_RATE_1M, },
95     { FLOPPY_DRIVE_TYPE_288, 40, 80, 1, FDRIVE_RATE_1M, },
96     { FLOPPY_DRIVE_TYPE_288, 44, 80, 1, FDRIVE_RATE_1M, },
97     { FLOPPY_DRIVE_TYPE_288, 48, 80, 1, FDRIVE_RATE_1M, },
98     /* 720 kB 3"1/2 floppy disks */
99     { FLOPPY_DRIVE_TYPE_144,  9, 80, 1, FDRIVE_RATE_250K, }, /* 3.5" 1440 */
100     { FLOPPY_DRIVE_TYPE_144, 10, 80, 1, FDRIVE_RATE_250K, },
101     { FLOPPY_DRIVE_TYPE_144, 10, 82, 1, FDRIVE_RATE_250K, },
102     { FLOPPY_DRIVE_TYPE_144, 10, 83, 1, FDRIVE_RATE_250K, },
103     { FLOPPY_DRIVE_TYPE_144, 13, 80, 1, FDRIVE_RATE_250K, },
104     { FLOPPY_DRIVE_TYPE_144, 14, 80, 1, FDRIVE_RATE_250K, },
105     /* 1.2 MB 5"1/4 floppy disks */
106     { FLOPPY_DRIVE_TYPE_120, 15, 80, 1, FDRIVE_RATE_500K, },
107     { FLOPPY_DRIVE_TYPE_120, 18, 80, 1, FDRIVE_RATE_500K, }, /* 5.25" 2880 */
108     { FLOPPY_DRIVE_TYPE_120, 18, 82, 1, FDRIVE_RATE_500K, },
109     { FLOPPY_DRIVE_TYPE_120, 18, 83, 1, FDRIVE_RATE_500K, },
110     { FLOPPY_DRIVE_TYPE_120, 20, 80, 1, FDRIVE_RATE_500K, }, /* 5.25" 3200 */
111     /* 720 kB 5"1/4 floppy disks */
112     { FLOPPY_DRIVE_TYPE_120,  9, 80, 1, FDRIVE_RATE_250K, }, /* 5.25" 1440 */
113     { FLOPPY_DRIVE_TYPE_120, 11, 80, 1, FDRIVE_RATE_250K, },
114     /* 360 kB 5"1/4 floppy disks */
115     { FLOPPY_DRIVE_TYPE_120,  9, 40, 1, FDRIVE_RATE_300K, }, /* 5.25" 720 */
116     { FLOPPY_DRIVE_TYPE_120,  9, 40, 0, FDRIVE_RATE_300K, },
117     { FLOPPY_DRIVE_TYPE_120, 10, 41, 1, FDRIVE_RATE_300K, },
118     { FLOPPY_DRIVE_TYPE_120, 10, 42, 1, FDRIVE_RATE_300K, },
119     /* 320 kB 5"1/4 floppy disks */
120     { FLOPPY_DRIVE_TYPE_120,  8, 40, 1, FDRIVE_RATE_250K, },
121     { FLOPPY_DRIVE_TYPE_120,  8, 40, 0, FDRIVE_RATE_250K, },
122     /* 360 kB must match 5"1/4 better than 3"1/2... */
123     { FLOPPY_DRIVE_TYPE_144,  9, 80, 0, FDRIVE_RATE_250K, }, /* 3.5" 720 */
124     /* end */
125     { FLOPPY_DRIVE_TYPE_NONE, -1, -1, 0, 0, },
126 };
127 
128 static FDriveSize drive_size(FloppyDriveType drive)
129 {
130     switch (drive) {
131     case FLOPPY_DRIVE_TYPE_120:
132         return FDRIVE_SIZE_525;
133     case FLOPPY_DRIVE_TYPE_144:
134     case FLOPPY_DRIVE_TYPE_288:
135         return FDRIVE_SIZE_350;
136     default:
137         return FDRIVE_SIZE_UNKNOWN;
138     }
139 }
140 
141 #define GET_CUR_DRV(fdctrl) ((fdctrl)->cur_drv)
142 #define SET_CUR_DRV(fdctrl, drive) ((fdctrl)->cur_drv = (drive))
143 
144 /* Will always be a fixed parameter for us */
145 #define FD_SECTOR_LEN          512
146 #define FD_SECTOR_SC           2   /* Sector size code */
147 #define FD_RESET_SENSEI_COUNT  4   /* Number of sense interrupts on RESET */
148 
149 typedef struct FDCtrl FDCtrl;
150 
151 /* Floppy disk drive emulation */
152 typedef enum FDiskFlags {
153     FDISK_DBL_SIDES  = 0x01,
154 } FDiskFlags;
155 
156 typedef struct FDrive {
157     FDCtrl *fdctrl;
158     BlockBackend *blk;
159     /* Drive status */
160     FloppyDriveType drive;    /* CMOS drive type        */
161     uint8_t perpendicular;    /* 2.88 MB access mode    */
162     /* Position */
163     uint8_t head;
164     uint8_t track;
165     uint8_t sect;
166     /* Media */
167     FloppyDriveType disk;     /* Current disk type      */
168     FDiskFlags flags;
169     uint8_t last_sect;        /* Nb sector per track    */
170     uint8_t max_track;        /* Nb of tracks           */
171     uint16_t bps;             /* Bytes per sector       */
172     uint8_t ro;               /* Is read-only           */
173     uint8_t media_changed;    /* Is media changed       */
174     uint8_t media_rate;       /* Data rate of medium    */
175 
176     bool media_validated;     /* Have we validated the media? */
177 } FDrive;
178 
179 
180 static FloppyDriveType get_fallback_drive_type(FDrive *drv);
181 
182 /* Hack: FD_SEEK is expected to work on empty drives. However, QEMU
183  * currently goes through some pains to keep seeks within the bounds
184  * established by last_sect and max_track. Correcting this is difficult,
185  * as refactoring FDC code tends to expose nasty bugs in the Linux kernel.
186  *
187  * For now: allow empty drives to have large bounds so we can seek around,
188  * with the understanding that when a diskette is inserted, the bounds will
189  * properly tighten to match the geometry of that inserted medium.
190  */
191 static void fd_empty_seek_hack(FDrive *drv)
192 {
193     drv->last_sect = 0xFF;
194     drv->max_track = 0xFF;
195 }
196 
197 static void fd_init(FDrive *drv)
198 {
199     /* Drive */
200     drv->perpendicular = 0;
201     /* Disk */
202     drv->disk = FLOPPY_DRIVE_TYPE_NONE;
203     drv->last_sect = 0;
204     drv->max_track = 0;
205     drv->ro = true;
206     drv->media_changed = 1;
207 }
208 
209 #define NUM_SIDES(drv) ((drv)->flags & FDISK_DBL_SIDES ? 2 : 1)
210 
211 static int fd_sector_calc(uint8_t head, uint8_t track, uint8_t sect,
212                           uint8_t last_sect, uint8_t num_sides)
213 {
214     return (((track * num_sides) + head) * last_sect) + sect - 1;
215 }
216 
217 /* Returns current position, in sectors, for given drive */
218 static int fd_sector(FDrive *drv)
219 {
220     return fd_sector_calc(drv->head, drv->track, drv->sect, drv->last_sect,
221                           NUM_SIDES(drv));
222 }
223 
224 /* Seek to a new position:
225  * returns 0 if already on right track
226  * returns 1 if track changed
227  * returns 2 if track is invalid
228  * returns 3 if sector is invalid
229  * returns 4 if seek is disabled
230  */
231 static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
232                    int enable_seek)
233 {
234     uint32_t sector;
235     int ret;
236 
237     if (track > drv->max_track ||
238         (head != 0 && (drv->flags & FDISK_DBL_SIDES) == 0)) {
239         FLOPPY_DPRINTF("try to read %d %02x %02x (max=%d %d %02x %02x)\n",
240                        head, track, sect, 1,
241                        (drv->flags & FDISK_DBL_SIDES) == 0 ? 0 : 1,
242                        drv->max_track, drv->last_sect);
243         return 2;
244     }
245     if (sect > drv->last_sect) {
246         FLOPPY_DPRINTF("try to read %d %02x %02x (max=%d %d %02x %02x)\n",
247                        head, track, sect, 1,
248                        (drv->flags & FDISK_DBL_SIDES) == 0 ? 0 : 1,
249                        drv->max_track, drv->last_sect);
250         return 3;
251     }
252     sector = fd_sector_calc(head, track, sect, drv->last_sect, NUM_SIDES(drv));
253     ret = 0;
254     if (sector != fd_sector(drv)) {
255 #if 0
256         if (!enable_seek) {
257             FLOPPY_DPRINTF("error: no implicit seek %d %02x %02x"
258                            " (max=%d %02x %02x)\n",
259                            head, track, sect, 1, drv->max_track,
260                            drv->last_sect);
261             return 4;
262         }
263 #endif
264         drv->head = head;
265         if (drv->track != track) {
266             if (drv->blk != NULL && blk_is_inserted(drv->blk)) {
267                 drv->media_changed = 0;
268             }
269             ret = 1;
270         }
271         drv->track = track;
272         drv->sect = sect;
273     }
274 
275     if (drv->blk == NULL || !blk_is_inserted(drv->blk)) {
276         ret = 2;
277     }
278 
279     return ret;
280 }
281 
282 /* Set drive back to track 0 */
283 static void fd_recalibrate(FDrive *drv)
284 {
285     FLOPPY_DPRINTF("recalibrate\n");
286     fd_seek(drv, 0, 0, 1, 1);
287 }
288 
289 /**
290  * Determine geometry based on inserted diskette.
291  * Will not operate on an empty drive.
292  *
293  * @return: 0 on success, -1 if the drive is empty.
294  */
295 static int pick_geometry(FDrive *drv)
296 {
297     BlockBackend *blk = drv->blk;
298     const FDFormat *parse;
299     uint64_t nb_sectors, size;
300     int i;
301     int match, size_match, type_match;
302     bool magic = drv->drive == FLOPPY_DRIVE_TYPE_AUTO;
303 
304     /* We can only pick a geometry if we have a diskette. */
305     if (!drv->blk || !blk_is_inserted(drv->blk) ||
306         drv->drive == FLOPPY_DRIVE_TYPE_NONE)
307     {
308         return -1;
309     }
310 
311     /* We need to determine the likely geometry of the inserted medium.
312      * In order of preference, we look for:
313      * (1) The same drive type and number of sectors,
314      * (2) The same diskette size and number of sectors,
315      * (3) The same drive type.
316      *
317      * In all cases, matches that occur higher in the drive table will take
318      * precedence over matches that occur later in the table.
319      */
320     blk_get_geometry(blk, &nb_sectors);
321     match = size_match = type_match = -1;
322     for (i = 0; ; i++) {
323         parse = &fd_formats[i];
324         if (parse->drive == FLOPPY_DRIVE_TYPE_NONE) {
325             break;
326         }
327         size = (parse->max_head + 1) * parse->max_track * parse->last_sect;
328         if (nb_sectors == size) {
329             if (magic || parse->drive == drv->drive) {
330                 /* (1) perfect match -- nb_sectors and drive type */
331                 goto out;
332             } else if (drive_size(parse->drive) == drive_size(drv->drive)) {
333                 /* (2) size match -- nb_sectors and physical medium size */
334                 match = (match == -1) ? i : match;
335             } else {
336                 /* This is suspicious -- Did the user misconfigure? */
337                 size_match = (size_match == -1) ? i : size_match;
338             }
339         } else if (type_match == -1) {
340             if ((parse->drive == drv->drive) ||
341                 (magic && (parse->drive == get_fallback_drive_type(drv)))) {
342                 /* (3) type match -- nb_sectors mismatch, but matches the type
343                  *     specified explicitly by the user, or matches the fallback
344                  *     default type when using the drive autodetect mechanism */
345                 type_match = i;
346             }
347         }
348     }
349 
350     /* No exact match found */
351     if (match == -1) {
352         if (size_match != -1) {
353             parse = &fd_formats[size_match];
354             FLOPPY_DPRINTF("User requested floppy drive type '%s', "
355                            "but inserted medium appears to be a "
356                            "%d sector '%s' type\n",
357                            FloppyDriveType_lookup[drv->drive],
358                            nb_sectors,
359                            FloppyDriveType_lookup[parse->drive]);
360         }
361         match = type_match;
362     }
363 
364     /* No match of any kind found -- fd_format is misconfigured, abort. */
365     if (match == -1) {
366         error_setg(&error_abort, "No candidate geometries present in table "
367                    " for floppy drive type '%s'",
368                    FloppyDriveType_lookup[drv->drive]);
369     }
370 
371     parse = &(fd_formats[match]);
372 
373  out:
374     if (parse->max_head == 0) {
375         drv->flags &= ~FDISK_DBL_SIDES;
376     } else {
377         drv->flags |= FDISK_DBL_SIDES;
378     }
379     drv->max_track = parse->max_track;
380     drv->last_sect = parse->last_sect;
381     drv->disk = parse->drive;
382     drv->media_rate = parse->rate;
383     return 0;
384 }
385 
386 static void pick_drive_type(FDrive *drv)
387 {
388     if (drv->drive != FLOPPY_DRIVE_TYPE_AUTO) {
389         return;
390     }
391 
392     if (pick_geometry(drv) == 0) {
393         drv->drive = drv->disk;
394     } else {
395         drv->drive = get_fallback_drive_type(drv);
396     }
397 
398     g_assert(drv->drive != FLOPPY_DRIVE_TYPE_AUTO);
399 }
400 
401 /* Revalidate a disk drive after a disk change */
402 static void fd_revalidate(FDrive *drv)
403 {
404     int rc;
405 
406     FLOPPY_DPRINTF("revalidate\n");
407     if (drv->blk != NULL) {
408         drv->ro = blk_is_read_only(drv->blk);
409         if (!blk_is_inserted(drv->blk)) {
410             FLOPPY_DPRINTF("No disk in drive\n");
411             drv->disk = FLOPPY_DRIVE_TYPE_NONE;
412             fd_empty_seek_hack(drv);
413         } else if (!drv->media_validated) {
414             rc = pick_geometry(drv);
415             if (rc) {
416                 FLOPPY_DPRINTF("Could not validate floppy drive media");
417             } else {
418                 drv->media_validated = true;
419                 FLOPPY_DPRINTF("Floppy disk (%d h %d t %d s) %s\n",
420                                (drv->flags & FDISK_DBL_SIDES) ? 2 : 1,
421                                drv->max_track, drv->last_sect,
422                                drv->ro ? "ro" : "rw");
423             }
424         }
425     } else {
426         FLOPPY_DPRINTF("No drive connected\n");
427         drv->last_sect = 0;
428         drv->max_track = 0;
429         drv->flags &= ~FDISK_DBL_SIDES;
430         drv->drive = FLOPPY_DRIVE_TYPE_NONE;
431         drv->disk = FLOPPY_DRIVE_TYPE_NONE;
432     }
433 }
434 
435 /********************************************************/
436 /* Intel 82078 floppy disk controller emulation          */
437 
438 static void fdctrl_reset(FDCtrl *fdctrl, int do_irq);
439 static void fdctrl_to_command_phase(FDCtrl *fdctrl);
440 static int fdctrl_transfer_handler (void *opaque, int nchan,
441                                     int dma_pos, int dma_len);
442 static void fdctrl_raise_irq(FDCtrl *fdctrl);
443 static FDrive *get_cur_drv(FDCtrl *fdctrl);
444 
445 static uint32_t fdctrl_read_statusA(FDCtrl *fdctrl);
446 static uint32_t fdctrl_read_statusB(FDCtrl *fdctrl);
447 static uint32_t fdctrl_read_dor(FDCtrl *fdctrl);
448 static void fdctrl_write_dor(FDCtrl *fdctrl, uint32_t value);
449 static uint32_t fdctrl_read_tape(FDCtrl *fdctrl);
450 static void fdctrl_write_tape(FDCtrl *fdctrl, uint32_t value);
451 static uint32_t fdctrl_read_main_status(FDCtrl *fdctrl);
452 static void fdctrl_write_rate(FDCtrl *fdctrl, uint32_t value);
453 static uint32_t fdctrl_read_data(FDCtrl *fdctrl);
454 static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value);
455 static uint32_t fdctrl_read_dir(FDCtrl *fdctrl);
456 static void fdctrl_write_ccr(FDCtrl *fdctrl, uint32_t value);
457 
458 enum {
459     FD_DIR_WRITE   = 0,
460     FD_DIR_READ    = 1,
461     FD_DIR_SCANE   = 2,
462     FD_DIR_SCANL   = 3,
463     FD_DIR_SCANH   = 4,
464     FD_DIR_VERIFY  = 5,
465 };
466 
467 enum {
468     FD_STATE_MULTI  = 0x01,	/* multi track flag */
469     FD_STATE_FORMAT = 0x02,	/* format flag */
470 };
471 
472 enum {
473     FD_REG_SRA = 0x00,
474     FD_REG_SRB = 0x01,
475     FD_REG_DOR = 0x02,
476     FD_REG_TDR = 0x03,
477     FD_REG_MSR = 0x04,
478     FD_REG_DSR = 0x04,
479     FD_REG_FIFO = 0x05,
480     FD_REG_DIR = 0x07,
481     FD_REG_CCR = 0x07,
482 };
483 
484 enum {
485     FD_CMD_READ_TRACK = 0x02,
486     FD_CMD_SPECIFY = 0x03,
487     FD_CMD_SENSE_DRIVE_STATUS = 0x04,
488     FD_CMD_WRITE = 0x05,
489     FD_CMD_READ = 0x06,
490     FD_CMD_RECALIBRATE = 0x07,
491     FD_CMD_SENSE_INTERRUPT_STATUS = 0x08,
492     FD_CMD_WRITE_DELETED = 0x09,
493     FD_CMD_READ_ID = 0x0a,
494     FD_CMD_READ_DELETED = 0x0c,
495     FD_CMD_FORMAT_TRACK = 0x0d,
496     FD_CMD_DUMPREG = 0x0e,
497     FD_CMD_SEEK = 0x0f,
498     FD_CMD_VERSION = 0x10,
499     FD_CMD_SCAN_EQUAL = 0x11,
500     FD_CMD_PERPENDICULAR_MODE = 0x12,
501     FD_CMD_CONFIGURE = 0x13,
502     FD_CMD_LOCK = 0x14,
503     FD_CMD_VERIFY = 0x16,
504     FD_CMD_POWERDOWN_MODE = 0x17,
505     FD_CMD_PART_ID = 0x18,
506     FD_CMD_SCAN_LOW_OR_EQUAL = 0x19,
507     FD_CMD_SCAN_HIGH_OR_EQUAL = 0x1d,
508     FD_CMD_SAVE = 0x2e,
509     FD_CMD_OPTION = 0x33,
510     FD_CMD_RESTORE = 0x4e,
511     FD_CMD_DRIVE_SPECIFICATION_COMMAND = 0x8e,
512     FD_CMD_RELATIVE_SEEK_OUT = 0x8f,
513     FD_CMD_FORMAT_AND_WRITE = 0xcd,
514     FD_CMD_RELATIVE_SEEK_IN = 0xcf,
515 };
516 
517 enum {
518     FD_CONFIG_PRETRK = 0xff, /* Pre-compensation set to track 0 */
519     FD_CONFIG_FIFOTHR = 0x0f, /* FIFO threshold set to 1 byte */
520     FD_CONFIG_POLL  = 0x10, /* Poll enabled */
521     FD_CONFIG_EFIFO = 0x20, /* FIFO disabled */
522     FD_CONFIG_EIS   = 0x40, /* No implied seeks */
523 };
524 
525 enum {
526     FD_SR0_DS0      = 0x01,
527     FD_SR0_DS1      = 0x02,
528     FD_SR0_HEAD     = 0x04,
529     FD_SR0_EQPMT    = 0x10,
530     FD_SR0_SEEK     = 0x20,
531     FD_SR0_ABNTERM  = 0x40,
532     FD_SR0_INVCMD   = 0x80,
533     FD_SR0_RDYCHG   = 0xc0,
534 };
535 
536 enum {
537     FD_SR1_MA       = 0x01, /* Missing address mark */
538     FD_SR1_NW       = 0x02, /* Not writable */
539     FD_SR1_EC       = 0x80, /* End of cylinder */
540 };
541 
542 enum {
543     FD_SR2_SNS      = 0x04, /* Scan not satisfied */
544     FD_SR2_SEH      = 0x08, /* Scan equal hit */
545 };
546 
547 enum {
548     FD_SRA_DIR      = 0x01,
549     FD_SRA_nWP      = 0x02,
550     FD_SRA_nINDX    = 0x04,
551     FD_SRA_HDSEL    = 0x08,
552     FD_SRA_nTRK0    = 0x10,
553     FD_SRA_STEP     = 0x20,
554     FD_SRA_nDRV2    = 0x40,
555     FD_SRA_INTPEND  = 0x80,
556 };
557 
558 enum {
559     FD_SRB_MTR0     = 0x01,
560     FD_SRB_MTR1     = 0x02,
561     FD_SRB_WGATE    = 0x04,
562     FD_SRB_RDATA    = 0x08,
563     FD_SRB_WDATA    = 0x10,
564     FD_SRB_DR0      = 0x20,
565 };
566 
567 enum {
568 #if MAX_FD == 4
569     FD_DOR_SELMASK  = 0x03,
570 #else
571     FD_DOR_SELMASK  = 0x01,
572 #endif
573     FD_DOR_nRESET   = 0x04,
574     FD_DOR_DMAEN    = 0x08,
575     FD_DOR_MOTEN0   = 0x10,
576     FD_DOR_MOTEN1   = 0x20,
577     FD_DOR_MOTEN2   = 0x40,
578     FD_DOR_MOTEN3   = 0x80,
579 };
580 
581 enum {
582 #if MAX_FD == 4
583     FD_TDR_BOOTSEL  = 0x0c,
584 #else
585     FD_TDR_BOOTSEL  = 0x04,
586 #endif
587 };
588 
589 enum {
590     FD_DSR_DRATEMASK= 0x03,
591     FD_DSR_PWRDOWN  = 0x40,
592     FD_DSR_SWRESET  = 0x80,
593 };
594 
595 enum {
596     FD_MSR_DRV0BUSY = 0x01,
597     FD_MSR_DRV1BUSY = 0x02,
598     FD_MSR_DRV2BUSY = 0x04,
599     FD_MSR_DRV3BUSY = 0x08,
600     FD_MSR_CMDBUSY  = 0x10,
601     FD_MSR_NONDMA   = 0x20,
602     FD_MSR_DIO      = 0x40,
603     FD_MSR_RQM      = 0x80,
604 };
605 
606 enum {
607     FD_DIR_DSKCHG   = 0x80,
608 };
609 
610 /*
611  * See chapter 5.0 "Controller phases" of the spec:
612  *
613  * Command phase:
614  * The host writes a command and its parameters into the FIFO. The command
615  * phase is completed when all parameters for the command have been supplied,
616  * and execution phase is entered.
617  *
618  * Execution phase:
619  * Data transfers, either DMA or non-DMA. For non-DMA transfers, the FIFO
620  * contains the payload now, otherwise it's unused. When all bytes of the
621  * required data have been transferred, the state is switched to either result
622  * phase (if the command produces status bytes) or directly back into the
623  * command phase for the next command.
624  *
625  * Result phase:
626  * The host reads out the FIFO, which contains one or more result bytes now.
627  */
628 enum {
629     /* Only for migration: reconstruct phase from registers like qemu 2.3 */
630     FD_PHASE_RECONSTRUCT    = 0,
631 
632     FD_PHASE_COMMAND        = 1,
633     FD_PHASE_EXECUTION      = 2,
634     FD_PHASE_RESULT         = 3,
635 };
636 
637 #define FD_MULTI_TRACK(state) ((state) & FD_STATE_MULTI)
638 #define FD_FORMAT_CMD(state) ((state) & FD_STATE_FORMAT)
639 
640 struct FDCtrl {
641     MemoryRegion iomem;
642     qemu_irq irq;
643     /* Controller state */
644     QEMUTimer *result_timer;
645     int dma_chann;
646     uint8_t phase;
647     /* Controller's identification */
648     uint8_t version;
649     /* HW */
650     uint8_t sra;
651     uint8_t srb;
652     uint8_t dor;
653     uint8_t dor_vmstate; /* only used as temp during vmstate */
654     uint8_t tdr;
655     uint8_t dsr;
656     uint8_t msr;
657     uint8_t cur_drv;
658     uint8_t status0;
659     uint8_t status1;
660     uint8_t status2;
661     /* Command FIFO */
662     uint8_t *fifo;
663     int32_t fifo_size;
664     uint32_t data_pos;
665     uint32_t data_len;
666     uint8_t data_state;
667     uint8_t data_dir;
668     uint8_t eot; /* last wanted sector */
669     /* States kept only to be returned back */
670     /* precompensation */
671     uint8_t precomp_trk;
672     uint8_t config;
673     uint8_t lock;
674     /* Power down config (also with status regB access mode */
675     uint8_t pwrd;
676     /* Floppy drives */
677     uint8_t num_floppies;
678     FDrive drives[MAX_FD];
679     int reset_sensei;
680     uint32_t check_media_rate;
681     FloppyDriveType fallback; /* type=auto failure fallback */
682     /* Timers state */
683     uint8_t timer0;
684     uint8_t timer1;
685 };
686 
687 static FloppyDriveType get_fallback_drive_type(FDrive *drv)
688 {
689     return drv->fdctrl->fallback;
690 }
691 
692 #define TYPE_SYSBUS_FDC "base-sysbus-fdc"
693 #define SYSBUS_FDC(obj) OBJECT_CHECK(FDCtrlSysBus, (obj), TYPE_SYSBUS_FDC)
694 
695 typedef struct FDCtrlSysBus {
696     /*< private >*/
697     SysBusDevice parent_obj;
698     /*< public >*/
699 
700     struct FDCtrl state;
701 } FDCtrlSysBus;
702 
703 #define ISA_FDC(obj) OBJECT_CHECK(FDCtrlISABus, (obj), TYPE_ISA_FDC)
704 
705 typedef struct FDCtrlISABus {
706     ISADevice parent_obj;
707 
708     uint32_t iobase;
709     uint32_t irq;
710     uint32_t dma;
711     struct FDCtrl state;
712     int32_t bootindexA;
713     int32_t bootindexB;
714 } FDCtrlISABus;
715 
716 static uint32_t fdctrl_read (void *opaque, uint32_t reg)
717 {
718     FDCtrl *fdctrl = opaque;
719     uint32_t retval;
720 
721     reg &= 7;
722     switch (reg) {
723     case FD_REG_SRA:
724         retval = fdctrl_read_statusA(fdctrl);
725         break;
726     case FD_REG_SRB:
727         retval = fdctrl_read_statusB(fdctrl);
728         break;
729     case FD_REG_DOR:
730         retval = fdctrl_read_dor(fdctrl);
731         break;
732     case FD_REG_TDR:
733         retval = fdctrl_read_tape(fdctrl);
734         break;
735     case FD_REG_MSR:
736         retval = fdctrl_read_main_status(fdctrl);
737         break;
738     case FD_REG_FIFO:
739         retval = fdctrl_read_data(fdctrl);
740         break;
741     case FD_REG_DIR:
742         retval = fdctrl_read_dir(fdctrl);
743         break;
744     default:
745         retval = (uint32_t)(-1);
746         break;
747     }
748     FLOPPY_DPRINTF("read reg%d: 0x%02x\n", reg & 7, retval);
749 
750     return retval;
751 }
752 
753 static void fdctrl_write (void *opaque, uint32_t reg, uint32_t value)
754 {
755     FDCtrl *fdctrl = opaque;
756 
757     FLOPPY_DPRINTF("write reg%d: 0x%02x\n", reg & 7, value);
758 
759     reg &= 7;
760     switch (reg) {
761     case FD_REG_DOR:
762         fdctrl_write_dor(fdctrl, value);
763         break;
764     case FD_REG_TDR:
765         fdctrl_write_tape(fdctrl, value);
766         break;
767     case FD_REG_DSR:
768         fdctrl_write_rate(fdctrl, value);
769         break;
770     case FD_REG_FIFO:
771         fdctrl_write_data(fdctrl, value);
772         break;
773     case FD_REG_CCR:
774         fdctrl_write_ccr(fdctrl, value);
775         break;
776     default:
777         break;
778     }
779 }
780 
781 static uint64_t fdctrl_read_mem (void *opaque, hwaddr reg,
782                                  unsigned ize)
783 {
784     return fdctrl_read(opaque, (uint32_t)reg);
785 }
786 
787 static void fdctrl_write_mem (void *opaque, hwaddr reg,
788                               uint64_t value, unsigned size)
789 {
790     fdctrl_write(opaque, (uint32_t)reg, value);
791 }
792 
793 static const MemoryRegionOps fdctrl_mem_ops = {
794     .read = fdctrl_read_mem,
795     .write = fdctrl_write_mem,
796     .endianness = DEVICE_NATIVE_ENDIAN,
797 };
798 
799 static const MemoryRegionOps fdctrl_mem_strict_ops = {
800     .read = fdctrl_read_mem,
801     .write = fdctrl_write_mem,
802     .endianness = DEVICE_NATIVE_ENDIAN,
803     .valid = {
804         .min_access_size = 1,
805         .max_access_size = 1,
806     },
807 };
808 
809 static bool fdrive_media_changed_needed(void *opaque)
810 {
811     FDrive *drive = opaque;
812 
813     return (drive->blk != NULL && drive->media_changed != 1);
814 }
815 
816 static const VMStateDescription vmstate_fdrive_media_changed = {
817     .name = "fdrive/media_changed",
818     .version_id = 1,
819     .minimum_version_id = 1,
820     .needed = fdrive_media_changed_needed,
821     .fields = (VMStateField[]) {
822         VMSTATE_UINT8(media_changed, FDrive),
823         VMSTATE_END_OF_LIST()
824     }
825 };
826 
827 static bool fdrive_media_rate_needed(void *opaque)
828 {
829     FDrive *drive = opaque;
830 
831     return drive->fdctrl->check_media_rate;
832 }
833 
834 static const VMStateDescription vmstate_fdrive_media_rate = {
835     .name = "fdrive/media_rate",
836     .version_id = 1,
837     .minimum_version_id = 1,
838     .needed = fdrive_media_rate_needed,
839     .fields = (VMStateField[]) {
840         VMSTATE_UINT8(media_rate, FDrive),
841         VMSTATE_END_OF_LIST()
842     }
843 };
844 
845 static bool fdrive_perpendicular_needed(void *opaque)
846 {
847     FDrive *drive = opaque;
848 
849     return drive->perpendicular != 0;
850 }
851 
852 static const VMStateDescription vmstate_fdrive_perpendicular = {
853     .name = "fdrive/perpendicular",
854     .version_id = 1,
855     .minimum_version_id = 1,
856     .needed = fdrive_perpendicular_needed,
857     .fields = (VMStateField[]) {
858         VMSTATE_UINT8(perpendicular, FDrive),
859         VMSTATE_END_OF_LIST()
860     }
861 };
862 
863 static int fdrive_post_load(void *opaque, int version_id)
864 {
865     fd_revalidate(opaque);
866     return 0;
867 }
868 
869 static const VMStateDescription vmstate_fdrive = {
870     .name = "fdrive",
871     .version_id = 1,
872     .minimum_version_id = 1,
873     .post_load = fdrive_post_load,
874     .fields = (VMStateField[]) {
875         VMSTATE_UINT8(head, FDrive),
876         VMSTATE_UINT8(track, FDrive),
877         VMSTATE_UINT8(sect, FDrive),
878         VMSTATE_END_OF_LIST()
879     },
880     .subsections = (const VMStateDescription*[]) {
881         &vmstate_fdrive_media_changed,
882         &vmstate_fdrive_media_rate,
883         &vmstate_fdrive_perpendicular,
884         NULL
885     }
886 };
887 
888 /*
889  * Reconstructs the phase from register values according to the logic that was
890  * implemented in qemu 2.3. This is the default value that is used if the phase
891  * subsection is not present on migration.
892  *
893  * Don't change this function to reflect newer qemu versions, it is part of
894  * the migration ABI.
895  */
896 static int reconstruct_phase(FDCtrl *fdctrl)
897 {
898     if (fdctrl->msr & FD_MSR_NONDMA) {
899         return FD_PHASE_EXECUTION;
900     } else if ((fdctrl->msr & FD_MSR_RQM) == 0) {
901         /* qemu 2.3 disabled RQM only during DMA transfers */
902         return FD_PHASE_EXECUTION;
903     } else if (fdctrl->msr & FD_MSR_DIO) {
904         return FD_PHASE_RESULT;
905     } else {
906         return FD_PHASE_COMMAND;
907     }
908 }
909 
910 static void fdc_pre_save(void *opaque)
911 {
912     FDCtrl *s = opaque;
913 
914     s->dor_vmstate = s->dor | GET_CUR_DRV(s);
915 }
916 
917 static int fdc_pre_load(void *opaque)
918 {
919     FDCtrl *s = opaque;
920     s->phase = FD_PHASE_RECONSTRUCT;
921     return 0;
922 }
923 
924 static int fdc_post_load(void *opaque, int version_id)
925 {
926     FDCtrl *s = opaque;
927 
928     SET_CUR_DRV(s, s->dor_vmstate & FD_DOR_SELMASK);
929     s->dor = s->dor_vmstate & ~FD_DOR_SELMASK;
930 
931     if (s->phase == FD_PHASE_RECONSTRUCT) {
932         s->phase = reconstruct_phase(s);
933     }
934 
935     return 0;
936 }
937 
938 static bool fdc_reset_sensei_needed(void *opaque)
939 {
940     FDCtrl *s = opaque;
941 
942     return s->reset_sensei != 0;
943 }
944 
945 static const VMStateDescription vmstate_fdc_reset_sensei = {
946     .name = "fdc/reset_sensei",
947     .version_id = 1,
948     .minimum_version_id = 1,
949     .needed = fdc_reset_sensei_needed,
950     .fields = (VMStateField[]) {
951         VMSTATE_INT32(reset_sensei, FDCtrl),
952         VMSTATE_END_OF_LIST()
953     }
954 };
955 
956 static bool fdc_result_timer_needed(void *opaque)
957 {
958     FDCtrl *s = opaque;
959 
960     return timer_pending(s->result_timer);
961 }
962 
963 static const VMStateDescription vmstate_fdc_result_timer = {
964     .name = "fdc/result_timer",
965     .version_id = 1,
966     .minimum_version_id = 1,
967     .needed = fdc_result_timer_needed,
968     .fields = (VMStateField[]) {
969         VMSTATE_TIMER_PTR(result_timer, FDCtrl),
970         VMSTATE_END_OF_LIST()
971     }
972 };
973 
974 static bool fdc_phase_needed(void *opaque)
975 {
976     FDCtrl *fdctrl = opaque;
977 
978     return reconstruct_phase(fdctrl) != fdctrl->phase;
979 }
980 
981 static const VMStateDescription vmstate_fdc_phase = {
982     .name = "fdc/phase",
983     .version_id = 1,
984     .minimum_version_id = 1,
985     .needed = fdc_phase_needed,
986     .fields = (VMStateField[]) {
987         VMSTATE_UINT8(phase, FDCtrl),
988         VMSTATE_END_OF_LIST()
989     }
990 };
991 
992 static const VMStateDescription vmstate_fdc = {
993     .name = "fdc",
994     .version_id = 2,
995     .minimum_version_id = 2,
996     .pre_save = fdc_pre_save,
997     .pre_load = fdc_pre_load,
998     .post_load = fdc_post_load,
999     .fields = (VMStateField[]) {
1000         /* Controller State */
1001         VMSTATE_UINT8(sra, FDCtrl),
1002         VMSTATE_UINT8(srb, FDCtrl),
1003         VMSTATE_UINT8(dor_vmstate, FDCtrl),
1004         VMSTATE_UINT8(tdr, FDCtrl),
1005         VMSTATE_UINT8(dsr, FDCtrl),
1006         VMSTATE_UINT8(msr, FDCtrl),
1007         VMSTATE_UINT8(status0, FDCtrl),
1008         VMSTATE_UINT8(status1, FDCtrl),
1009         VMSTATE_UINT8(status2, FDCtrl),
1010         /* Command FIFO */
1011         VMSTATE_VARRAY_INT32(fifo, FDCtrl, fifo_size, 0, vmstate_info_uint8,
1012                              uint8_t),
1013         VMSTATE_UINT32(data_pos, FDCtrl),
1014         VMSTATE_UINT32(data_len, FDCtrl),
1015         VMSTATE_UINT8(data_state, FDCtrl),
1016         VMSTATE_UINT8(data_dir, FDCtrl),
1017         VMSTATE_UINT8(eot, FDCtrl),
1018         /* States kept only to be returned back */
1019         VMSTATE_UINT8(timer0, FDCtrl),
1020         VMSTATE_UINT8(timer1, FDCtrl),
1021         VMSTATE_UINT8(precomp_trk, FDCtrl),
1022         VMSTATE_UINT8(config, FDCtrl),
1023         VMSTATE_UINT8(lock, FDCtrl),
1024         VMSTATE_UINT8(pwrd, FDCtrl),
1025         VMSTATE_UINT8_EQUAL(num_floppies, FDCtrl),
1026         VMSTATE_STRUCT_ARRAY(drives, FDCtrl, MAX_FD, 1,
1027                              vmstate_fdrive, FDrive),
1028         VMSTATE_END_OF_LIST()
1029     },
1030     .subsections = (const VMStateDescription*[]) {
1031         &vmstate_fdc_reset_sensei,
1032         &vmstate_fdc_result_timer,
1033         &vmstate_fdc_phase,
1034         NULL
1035     }
1036 };
1037 
1038 static void fdctrl_external_reset_sysbus(DeviceState *d)
1039 {
1040     FDCtrlSysBus *sys = SYSBUS_FDC(d);
1041     FDCtrl *s = &sys->state;
1042 
1043     fdctrl_reset(s, 0);
1044 }
1045 
1046 static void fdctrl_external_reset_isa(DeviceState *d)
1047 {
1048     FDCtrlISABus *isa = ISA_FDC(d);
1049     FDCtrl *s = &isa->state;
1050 
1051     fdctrl_reset(s, 0);
1052 }
1053 
1054 static void fdctrl_handle_tc(void *opaque, int irq, int level)
1055 {
1056     //FDCtrl *s = opaque;
1057 
1058     if (level) {
1059         // XXX
1060         FLOPPY_DPRINTF("TC pulsed\n");
1061     }
1062 }
1063 
1064 /* Change IRQ state */
1065 static void fdctrl_reset_irq(FDCtrl *fdctrl)
1066 {
1067     fdctrl->status0 = 0;
1068     if (!(fdctrl->sra & FD_SRA_INTPEND))
1069         return;
1070     FLOPPY_DPRINTF("Reset interrupt\n");
1071     qemu_set_irq(fdctrl->irq, 0);
1072     fdctrl->sra &= ~FD_SRA_INTPEND;
1073 }
1074 
1075 static void fdctrl_raise_irq(FDCtrl *fdctrl)
1076 {
1077     if (!(fdctrl->sra & FD_SRA_INTPEND)) {
1078         qemu_set_irq(fdctrl->irq, 1);
1079         fdctrl->sra |= FD_SRA_INTPEND;
1080     }
1081 
1082     fdctrl->reset_sensei = 0;
1083     FLOPPY_DPRINTF("Set interrupt status to 0x%02x\n", fdctrl->status0);
1084 }
1085 
1086 /* Reset controller */
1087 static void fdctrl_reset(FDCtrl *fdctrl, int do_irq)
1088 {
1089     int i;
1090 
1091     FLOPPY_DPRINTF("reset controller\n");
1092     fdctrl_reset_irq(fdctrl);
1093     /* Initialise controller */
1094     fdctrl->sra = 0;
1095     fdctrl->srb = 0xc0;
1096     if (!fdctrl->drives[1].blk) {
1097         fdctrl->sra |= FD_SRA_nDRV2;
1098     }
1099     fdctrl->cur_drv = 0;
1100     fdctrl->dor = FD_DOR_nRESET;
1101     fdctrl->dor |= (fdctrl->dma_chann != -1) ? FD_DOR_DMAEN : 0;
1102     fdctrl->msr = FD_MSR_RQM;
1103     fdctrl->reset_sensei = 0;
1104     timer_del(fdctrl->result_timer);
1105     /* FIFO state */
1106     fdctrl->data_pos = 0;
1107     fdctrl->data_len = 0;
1108     fdctrl->data_state = 0;
1109     fdctrl->data_dir = FD_DIR_WRITE;
1110     for (i = 0; i < MAX_FD; i++)
1111         fd_recalibrate(&fdctrl->drives[i]);
1112     fdctrl_to_command_phase(fdctrl);
1113     if (do_irq) {
1114         fdctrl->status0 |= FD_SR0_RDYCHG;
1115         fdctrl_raise_irq(fdctrl);
1116         fdctrl->reset_sensei = FD_RESET_SENSEI_COUNT;
1117     }
1118 }
1119 
1120 static inline FDrive *drv0(FDCtrl *fdctrl)
1121 {
1122     return &fdctrl->drives[(fdctrl->tdr & FD_TDR_BOOTSEL) >> 2];
1123 }
1124 
1125 static inline FDrive *drv1(FDCtrl *fdctrl)
1126 {
1127     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (1 << 2))
1128         return &fdctrl->drives[1];
1129     else
1130         return &fdctrl->drives[0];
1131 }
1132 
1133 #if MAX_FD == 4
1134 static inline FDrive *drv2(FDCtrl *fdctrl)
1135 {
1136     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (2 << 2))
1137         return &fdctrl->drives[2];
1138     else
1139         return &fdctrl->drives[1];
1140 }
1141 
1142 static inline FDrive *drv3(FDCtrl *fdctrl)
1143 {
1144     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (3 << 2))
1145         return &fdctrl->drives[3];
1146     else
1147         return &fdctrl->drives[2];
1148 }
1149 #endif
1150 
1151 static FDrive *get_cur_drv(FDCtrl *fdctrl)
1152 {
1153     switch (fdctrl->cur_drv) {
1154         case 0: return drv0(fdctrl);
1155         case 1: return drv1(fdctrl);
1156 #if MAX_FD == 4
1157         case 2: return drv2(fdctrl);
1158         case 3: return drv3(fdctrl);
1159 #endif
1160         default: return NULL;
1161     }
1162 }
1163 
1164 /* Status A register : 0x00 (read-only) */
1165 static uint32_t fdctrl_read_statusA(FDCtrl *fdctrl)
1166 {
1167     uint32_t retval = fdctrl->sra;
1168 
1169     FLOPPY_DPRINTF("status register A: 0x%02x\n", retval);
1170 
1171     return retval;
1172 }
1173 
1174 /* Status B register : 0x01 (read-only) */
1175 static uint32_t fdctrl_read_statusB(FDCtrl *fdctrl)
1176 {
1177     uint32_t retval = fdctrl->srb;
1178 
1179     FLOPPY_DPRINTF("status register B: 0x%02x\n", retval);
1180 
1181     return retval;
1182 }
1183 
1184 /* Digital output register : 0x02 */
1185 static uint32_t fdctrl_read_dor(FDCtrl *fdctrl)
1186 {
1187     uint32_t retval = fdctrl->dor;
1188 
1189     /* Selected drive */
1190     retval |= fdctrl->cur_drv;
1191     FLOPPY_DPRINTF("digital output register: 0x%02x\n", retval);
1192 
1193     return retval;
1194 }
1195 
1196 static void fdctrl_write_dor(FDCtrl *fdctrl, uint32_t value)
1197 {
1198     FLOPPY_DPRINTF("digital output register set to 0x%02x\n", value);
1199 
1200     /* Motors */
1201     if (value & FD_DOR_MOTEN0)
1202         fdctrl->srb |= FD_SRB_MTR0;
1203     else
1204         fdctrl->srb &= ~FD_SRB_MTR0;
1205     if (value & FD_DOR_MOTEN1)
1206         fdctrl->srb |= FD_SRB_MTR1;
1207     else
1208         fdctrl->srb &= ~FD_SRB_MTR1;
1209 
1210     /* Drive */
1211     if (value & 1)
1212         fdctrl->srb |= FD_SRB_DR0;
1213     else
1214         fdctrl->srb &= ~FD_SRB_DR0;
1215 
1216     /* Reset */
1217     if (!(value & FD_DOR_nRESET)) {
1218         if (fdctrl->dor & FD_DOR_nRESET) {
1219             FLOPPY_DPRINTF("controller enter RESET state\n");
1220         }
1221     } else {
1222         if (!(fdctrl->dor & FD_DOR_nRESET)) {
1223             FLOPPY_DPRINTF("controller out of RESET state\n");
1224             fdctrl_reset(fdctrl, 1);
1225             fdctrl->dsr &= ~FD_DSR_PWRDOWN;
1226         }
1227     }
1228     /* Selected drive */
1229     fdctrl->cur_drv = value & FD_DOR_SELMASK;
1230 
1231     fdctrl->dor = value;
1232 }
1233 
1234 /* Tape drive register : 0x03 */
1235 static uint32_t fdctrl_read_tape(FDCtrl *fdctrl)
1236 {
1237     uint32_t retval = fdctrl->tdr;
1238 
1239     FLOPPY_DPRINTF("tape drive register: 0x%02x\n", retval);
1240 
1241     return retval;
1242 }
1243 
1244 static void fdctrl_write_tape(FDCtrl *fdctrl, uint32_t value)
1245 {
1246     /* Reset mode */
1247     if (!(fdctrl->dor & FD_DOR_nRESET)) {
1248         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
1249         return;
1250     }
1251     FLOPPY_DPRINTF("tape drive register set to 0x%02x\n", value);
1252     /* Disk boot selection indicator */
1253     fdctrl->tdr = value & FD_TDR_BOOTSEL;
1254     /* Tape indicators: never allow */
1255 }
1256 
1257 /* Main status register : 0x04 (read) */
1258 static uint32_t fdctrl_read_main_status(FDCtrl *fdctrl)
1259 {
1260     uint32_t retval = fdctrl->msr;
1261 
1262     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
1263     fdctrl->dor |= FD_DOR_nRESET;
1264 
1265     FLOPPY_DPRINTF("main status register: 0x%02x\n", retval);
1266 
1267     return retval;
1268 }
1269 
1270 /* Data select rate register : 0x04 (write) */
1271 static void fdctrl_write_rate(FDCtrl *fdctrl, uint32_t value)
1272 {
1273     /* Reset mode */
1274     if (!(fdctrl->dor & FD_DOR_nRESET)) {
1275         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
1276         return;
1277     }
1278     FLOPPY_DPRINTF("select rate register set to 0x%02x\n", value);
1279     /* Reset: autoclear */
1280     if (value & FD_DSR_SWRESET) {
1281         fdctrl->dor &= ~FD_DOR_nRESET;
1282         fdctrl_reset(fdctrl, 1);
1283         fdctrl->dor |= FD_DOR_nRESET;
1284     }
1285     if (value & FD_DSR_PWRDOWN) {
1286         fdctrl_reset(fdctrl, 1);
1287     }
1288     fdctrl->dsr = value;
1289 }
1290 
1291 /* Configuration control register: 0x07 (write) */
1292 static void fdctrl_write_ccr(FDCtrl *fdctrl, uint32_t value)
1293 {
1294     /* Reset mode */
1295     if (!(fdctrl->dor & FD_DOR_nRESET)) {
1296         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
1297         return;
1298     }
1299     FLOPPY_DPRINTF("configuration control register set to 0x%02x\n", value);
1300 
1301     /* Only the rate selection bits used in AT mode, and we
1302      * store those in the DSR.
1303      */
1304     fdctrl->dsr = (fdctrl->dsr & ~FD_DSR_DRATEMASK) |
1305                   (value & FD_DSR_DRATEMASK);
1306 }
1307 
1308 static int fdctrl_media_changed(FDrive *drv)
1309 {
1310     return drv->media_changed;
1311 }
1312 
1313 /* Digital input register : 0x07 (read-only) */
1314 static uint32_t fdctrl_read_dir(FDCtrl *fdctrl)
1315 {
1316     uint32_t retval = 0;
1317 
1318     if (fdctrl_media_changed(get_cur_drv(fdctrl))) {
1319         retval |= FD_DIR_DSKCHG;
1320     }
1321     if (retval != 0) {
1322         FLOPPY_DPRINTF("Floppy digital input register: 0x%02x\n", retval);
1323     }
1324 
1325     return retval;
1326 }
1327 
1328 /* Clear the FIFO and update the state for receiving the next command */
1329 static void fdctrl_to_command_phase(FDCtrl *fdctrl)
1330 {
1331     fdctrl->phase = FD_PHASE_COMMAND;
1332     fdctrl->data_dir = FD_DIR_WRITE;
1333     fdctrl->data_pos = 0;
1334     fdctrl->data_len = 1; /* Accept command byte, adjust for params later */
1335     fdctrl->msr &= ~(FD_MSR_CMDBUSY | FD_MSR_DIO);
1336     fdctrl->msr |= FD_MSR_RQM;
1337 }
1338 
1339 /* Update the state to allow the guest to read out the command status.
1340  * @fifo_len is the number of result bytes to be read out. */
1341 static void fdctrl_to_result_phase(FDCtrl *fdctrl, int fifo_len)
1342 {
1343     fdctrl->phase = FD_PHASE_RESULT;
1344     fdctrl->data_dir = FD_DIR_READ;
1345     fdctrl->data_len = fifo_len;
1346     fdctrl->data_pos = 0;
1347     fdctrl->msr |= FD_MSR_CMDBUSY | FD_MSR_RQM | FD_MSR_DIO;
1348 }
1349 
1350 /* Set an error: unimplemented/unknown command */
1351 static void fdctrl_unimplemented(FDCtrl *fdctrl, int direction)
1352 {
1353     qemu_log_mask(LOG_UNIMP, "fdc: unimplemented command 0x%02x\n",
1354                   fdctrl->fifo[0]);
1355     fdctrl->fifo[0] = FD_SR0_INVCMD;
1356     fdctrl_to_result_phase(fdctrl, 1);
1357 }
1358 
1359 /* Seek to next sector
1360  * returns 0 when end of track reached (for DBL_SIDES on head 1)
1361  * otherwise returns 1
1362  */
1363 static int fdctrl_seek_to_next_sect(FDCtrl *fdctrl, FDrive *cur_drv)
1364 {
1365     FLOPPY_DPRINTF("seek to next sector (%d %02x %02x => %d)\n",
1366                    cur_drv->head, cur_drv->track, cur_drv->sect,
1367                    fd_sector(cur_drv));
1368     /* XXX: cur_drv->sect >= cur_drv->last_sect should be an
1369        error in fact */
1370     uint8_t new_head = cur_drv->head;
1371     uint8_t new_track = cur_drv->track;
1372     uint8_t new_sect = cur_drv->sect;
1373 
1374     int ret = 1;
1375 
1376     if (new_sect >= cur_drv->last_sect ||
1377         new_sect == fdctrl->eot) {
1378         new_sect = 1;
1379         if (FD_MULTI_TRACK(fdctrl->data_state)) {
1380             if (new_head == 0 &&
1381                 (cur_drv->flags & FDISK_DBL_SIDES) != 0) {
1382                 new_head = 1;
1383             } else {
1384                 new_head = 0;
1385                 new_track++;
1386                 fdctrl->status0 |= FD_SR0_SEEK;
1387                 if ((cur_drv->flags & FDISK_DBL_SIDES) == 0) {
1388                     ret = 0;
1389                 }
1390             }
1391         } else {
1392             fdctrl->status0 |= FD_SR0_SEEK;
1393             new_track++;
1394             ret = 0;
1395         }
1396         if (ret == 1) {
1397             FLOPPY_DPRINTF("seek to next track (%d %02x %02x => %d)\n",
1398                     new_head, new_track, new_sect, fd_sector(cur_drv));
1399         }
1400     } else {
1401         new_sect++;
1402     }
1403     fd_seek(cur_drv, new_head, new_track, new_sect, 1);
1404     return ret;
1405 }
1406 
1407 /* Callback for transfer end (stop or abort) */
1408 static void fdctrl_stop_transfer(FDCtrl *fdctrl, uint8_t status0,
1409                                  uint8_t status1, uint8_t status2)
1410 {
1411     FDrive *cur_drv;
1412     cur_drv = get_cur_drv(fdctrl);
1413 
1414     fdctrl->status0 &= ~(FD_SR0_DS0 | FD_SR0_DS1 | FD_SR0_HEAD);
1415     fdctrl->status0 |= GET_CUR_DRV(fdctrl);
1416     if (cur_drv->head) {
1417         fdctrl->status0 |= FD_SR0_HEAD;
1418     }
1419     fdctrl->status0 |= status0;
1420 
1421     FLOPPY_DPRINTF("transfer status: %02x %02x %02x (%02x)\n",
1422                    status0, status1, status2, fdctrl->status0);
1423     fdctrl->fifo[0] = fdctrl->status0;
1424     fdctrl->fifo[1] = status1;
1425     fdctrl->fifo[2] = status2;
1426     fdctrl->fifo[3] = cur_drv->track;
1427     fdctrl->fifo[4] = cur_drv->head;
1428     fdctrl->fifo[5] = cur_drv->sect;
1429     fdctrl->fifo[6] = FD_SECTOR_SC;
1430     fdctrl->data_dir = FD_DIR_READ;
1431     if (!(fdctrl->msr & FD_MSR_NONDMA)) {
1432         DMA_release_DREQ(fdctrl->dma_chann);
1433     }
1434     fdctrl->msr |= FD_MSR_RQM | FD_MSR_DIO;
1435     fdctrl->msr &= ~FD_MSR_NONDMA;
1436 
1437     fdctrl_to_result_phase(fdctrl, 7);
1438     fdctrl_raise_irq(fdctrl);
1439 }
1440 
1441 /* Prepare a data transfer (either DMA or FIFO) */
1442 static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)
1443 {
1444     FDrive *cur_drv;
1445     uint8_t kh, kt, ks;
1446 
1447     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1448     cur_drv = get_cur_drv(fdctrl);
1449     kt = fdctrl->fifo[2];
1450     kh = fdctrl->fifo[3];
1451     ks = fdctrl->fifo[4];
1452     FLOPPY_DPRINTF("Start transfer at %d %d %02x %02x (%d)\n",
1453                    GET_CUR_DRV(fdctrl), kh, kt, ks,
1454                    fd_sector_calc(kh, kt, ks, cur_drv->last_sect,
1455                                   NUM_SIDES(cur_drv)));
1456     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
1457     case 2:
1458         /* sect too big */
1459         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1460         fdctrl->fifo[3] = kt;
1461         fdctrl->fifo[4] = kh;
1462         fdctrl->fifo[5] = ks;
1463         return;
1464     case 3:
1465         /* track too big */
1466         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
1467         fdctrl->fifo[3] = kt;
1468         fdctrl->fifo[4] = kh;
1469         fdctrl->fifo[5] = ks;
1470         return;
1471     case 4:
1472         /* No seek enabled */
1473         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1474         fdctrl->fifo[3] = kt;
1475         fdctrl->fifo[4] = kh;
1476         fdctrl->fifo[5] = ks;
1477         return;
1478     case 1:
1479         fdctrl->status0 |= FD_SR0_SEEK;
1480         break;
1481     default:
1482         break;
1483     }
1484 
1485     /* Check the data rate. If the programmed data rate does not match
1486      * the currently inserted medium, the operation has to fail. */
1487     if (fdctrl->check_media_rate &&
1488         (fdctrl->dsr & FD_DSR_DRATEMASK) != cur_drv->media_rate) {
1489         FLOPPY_DPRINTF("data rate mismatch (fdc=%d, media=%d)\n",
1490                        fdctrl->dsr & FD_DSR_DRATEMASK, cur_drv->media_rate);
1491         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
1492         fdctrl->fifo[3] = kt;
1493         fdctrl->fifo[4] = kh;
1494         fdctrl->fifo[5] = ks;
1495         return;
1496     }
1497 
1498     /* Set the FIFO state */
1499     fdctrl->data_dir = direction;
1500     fdctrl->data_pos = 0;
1501     assert(fdctrl->msr & FD_MSR_CMDBUSY);
1502     if (fdctrl->fifo[0] & 0x80)
1503         fdctrl->data_state |= FD_STATE_MULTI;
1504     else
1505         fdctrl->data_state &= ~FD_STATE_MULTI;
1506     if (fdctrl->fifo[5] == 0) {
1507         fdctrl->data_len = fdctrl->fifo[8];
1508     } else {
1509         int tmp;
1510         fdctrl->data_len = 128 << (fdctrl->fifo[5] > 7 ? 7 : fdctrl->fifo[5]);
1511         tmp = (fdctrl->fifo[6] - ks + 1);
1512         if (fdctrl->fifo[0] & 0x80)
1513             tmp += fdctrl->fifo[6];
1514         fdctrl->data_len *= tmp;
1515     }
1516     fdctrl->eot = fdctrl->fifo[6];
1517     if (fdctrl->dor & FD_DOR_DMAEN) {
1518         int dma_mode;
1519         /* DMA transfer are enabled. Check if DMA channel is well programmed */
1520         dma_mode = DMA_get_channel_mode(fdctrl->dma_chann);
1521         dma_mode = (dma_mode >> 2) & 3;
1522         FLOPPY_DPRINTF("dma_mode=%d direction=%d (%d - %d)\n",
1523                        dma_mode, direction,
1524                        (128 << fdctrl->fifo[5]) *
1525                        (cur_drv->last_sect - ks + 1), fdctrl->data_len);
1526         if (((direction == FD_DIR_SCANE || direction == FD_DIR_SCANL ||
1527               direction == FD_DIR_SCANH) && dma_mode == 0) ||
1528             (direction == FD_DIR_WRITE && dma_mode == 2) ||
1529             (direction == FD_DIR_READ && dma_mode == 1) ||
1530             (direction == FD_DIR_VERIFY)) {
1531             /* No access is allowed until DMA transfer has completed */
1532             fdctrl->msr &= ~FD_MSR_RQM;
1533             if (direction != FD_DIR_VERIFY) {
1534                 /* Now, we just have to wait for the DMA controller to
1535                  * recall us...
1536                  */
1537                 DMA_hold_DREQ(fdctrl->dma_chann);
1538                 DMA_schedule();
1539             } else {
1540                 /* Start transfer */
1541                 fdctrl_transfer_handler(fdctrl, fdctrl->dma_chann, 0,
1542                                         fdctrl->data_len);
1543             }
1544             return;
1545         } else {
1546             FLOPPY_DPRINTF("bad dma_mode=%d direction=%d\n", dma_mode,
1547                            direction);
1548         }
1549     }
1550     FLOPPY_DPRINTF("start non-DMA transfer\n");
1551     fdctrl->msr |= FD_MSR_NONDMA | FD_MSR_RQM;
1552     if (direction != FD_DIR_WRITE)
1553         fdctrl->msr |= FD_MSR_DIO;
1554     /* IO based transfer: calculate len */
1555     fdctrl_raise_irq(fdctrl);
1556 }
1557 
1558 /* Prepare a transfer of deleted data */
1559 static void fdctrl_start_transfer_del(FDCtrl *fdctrl, int direction)
1560 {
1561     qemu_log_mask(LOG_UNIMP, "fdctrl_start_transfer_del() unimplemented\n");
1562 
1563     /* We don't handle deleted data,
1564      * so we don't return *ANYTHING*
1565      */
1566     fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1567 }
1568 
1569 /* handlers for DMA transfers */
1570 static int fdctrl_transfer_handler (void *opaque, int nchan,
1571                                     int dma_pos, int dma_len)
1572 {
1573     FDCtrl *fdctrl;
1574     FDrive *cur_drv;
1575     int len, start_pos, rel_pos;
1576     uint8_t status0 = 0x00, status1 = 0x00, status2 = 0x00;
1577 
1578     fdctrl = opaque;
1579     if (fdctrl->msr & FD_MSR_RQM) {
1580         FLOPPY_DPRINTF("Not in DMA transfer mode !\n");
1581         return 0;
1582     }
1583     cur_drv = get_cur_drv(fdctrl);
1584     if (fdctrl->data_dir == FD_DIR_SCANE || fdctrl->data_dir == FD_DIR_SCANL ||
1585         fdctrl->data_dir == FD_DIR_SCANH)
1586         status2 = FD_SR2_SNS;
1587     if (dma_len > fdctrl->data_len)
1588         dma_len = fdctrl->data_len;
1589     if (cur_drv->blk == NULL) {
1590         if (fdctrl->data_dir == FD_DIR_WRITE)
1591             fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1592         else
1593             fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1594         len = 0;
1595         goto transfer_error;
1596     }
1597     rel_pos = fdctrl->data_pos % FD_SECTOR_LEN;
1598     for (start_pos = fdctrl->data_pos; fdctrl->data_pos < dma_len;) {
1599         len = dma_len - fdctrl->data_pos;
1600         if (len + rel_pos > FD_SECTOR_LEN)
1601             len = FD_SECTOR_LEN - rel_pos;
1602         FLOPPY_DPRINTF("copy %d bytes (%d %d %d) %d pos %d %02x "
1603                        "(%d-0x%08x 0x%08x)\n", len, dma_len, fdctrl->data_pos,
1604                        fdctrl->data_len, GET_CUR_DRV(fdctrl), cur_drv->head,
1605                        cur_drv->track, cur_drv->sect, fd_sector(cur_drv),
1606                        fd_sector(cur_drv) * FD_SECTOR_LEN);
1607         if (fdctrl->data_dir != FD_DIR_WRITE ||
1608             len < FD_SECTOR_LEN || rel_pos != 0) {
1609             /* READ & SCAN commands and realign to a sector for WRITE */
1610             if (blk_read(cur_drv->blk, fd_sector(cur_drv),
1611                          fdctrl->fifo, 1) < 0) {
1612                 FLOPPY_DPRINTF("Floppy: error getting sector %d\n",
1613                                fd_sector(cur_drv));
1614                 /* Sure, image size is too small... */
1615                 memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1616             }
1617         }
1618         switch (fdctrl->data_dir) {
1619         case FD_DIR_READ:
1620             /* READ commands */
1621             DMA_write_memory (nchan, fdctrl->fifo + rel_pos,
1622                               fdctrl->data_pos, len);
1623             break;
1624         case FD_DIR_WRITE:
1625             /* WRITE commands */
1626             if (cur_drv->ro) {
1627                 /* Handle readonly medium early, no need to do DMA, touch the
1628                  * LED or attempt any writes. A real floppy doesn't attempt
1629                  * to write to readonly media either. */
1630                 fdctrl_stop_transfer(fdctrl,
1631                                      FD_SR0_ABNTERM | FD_SR0_SEEK, FD_SR1_NW,
1632                                      0x00);
1633                 goto transfer_error;
1634             }
1635 
1636             DMA_read_memory (nchan, fdctrl->fifo + rel_pos,
1637                              fdctrl->data_pos, len);
1638             if (blk_write(cur_drv->blk, fd_sector(cur_drv),
1639                           fdctrl->fifo, 1) < 0) {
1640                 FLOPPY_DPRINTF("error writing sector %d\n",
1641                                fd_sector(cur_drv));
1642                 fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1643                 goto transfer_error;
1644             }
1645             break;
1646         case FD_DIR_VERIFY:
1647             /* VERIFY commands */
1648             break;
1649         default:
1650             /* SCAN commands */
1651             {
1652                 uint8_t tmpbuf[FD_SECTOR_LEN];
1653                 int ret;
1654                 DMA_read_memory (nchan, tmpbuf, fdctrl->data_pos, len);
1655                 ret = memcmp(tmpbuf, fdctrl->fifo + rel_pos, len);
1656                 if (ret == 0) {
1657                     status2 = FD_SR2_SEH;
1658                     goto end_transfer;
1659                 }
1660                 if ((ret < 0 && fdctrl->data_dir == FD_DIR_SCANL) ||
1661                     (ret > 0 && fdctrl->data_dir == FD_DIR_SCANH)) {
1662                     status2 = 0x00;
1663                     goto end_transfer;
1664                 }
1665             }
1666             break;
1667         }
1668         fdctrl->data_pos += len;
1669         rel_pos = fdctrl->data_pos % FD_SECTOR_LEN;
1670         if (rel_pos == 0) {
1671             /* Seek to next sector */
1672             if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv))
1673                 break;
1674         }
1675     }
1676  end_transfer:
1677     len = fdctrl->data_pos - start_pos;
1678     FLOPPY_DPRINTF("end transfer %d %d %d\n",
1679                    fdctrl->data_pos, len, fdctrl->data_len);
1680     if (fdctrl->data_dir == FD_DIR_SCANE ||
1681         fdctrl->data_dir == FD_DIR_SCANL ||
1682         fdctrl->data_dir == FD_DIR_SCANH)
1683         status2 = FD_SR2_SEH;
1684     fdctrl->data_len -= len;
1685     fdctrl_stop_transfer(fdctrl, status0, status1, status2);
1686  transfer_error:
1687 
1688     return len;
1689 }
1690 
1691 /* Data register : 0x05 */
1692 static uint32_t fdctrl_read_data(FDCtrl *fdctrl)
1693 {
1694     FDrive *cur_drv;
1695     uint32_t retval = 0;
1696     uint32_t pos;
1697 
1698     cur_drv = get_cur_drv(fdctrl);
1699     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
1700     if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) {
1701         FLOPPY_DPRINTF("error: controller not ready for reading\n");
1702         return 0;
1703     }
1704 
1705     /* If data_len spans multiple sectors, the current position in the FIFO
1706      * wraps around while fdctrl->data_pos is the real position in the whole
1707      * request. */
1708     pos = fdctrl->data_pos;
1709     pos %= FD_SECTOR_LEN;
1710 
1711     switch (fdctrl->phase) {
1712     case FD_PHASE_EXECUTION:
1713         assert(fdctrl->msr & FD_MSR_NONDMA);
1714         if (pos == 0) {
1715             if (fdctrl->data_pos != 0)
1716                 if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {
1717                     FLOPPY_DPRINTF("error seeking to next sector %d\n",
1718                                    fd_sector(cur_drv));
1719                     return 0;
1720                 }
1721             if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1)
1722                 < 0) {
1723                 FLOPPY_DPRINTF("error getting sector %d\n",
1724                                fd_sector(cur_drv));
1725                 /* Sure, image size is too small... */
1726                 memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1727             }
1728         }
1729 
1730         if (++fdctrl->data_pos == fdctrl->data_len) {
1731             fdctrl->msr &= ~FD_MSR_RQM;
1732             fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1733         }
1734         break;
1735 
1736     case FD_PHASE_RESULT:
1737         assert(!(fdctrl->msr & FD_MSR_NONDMA));
1738         if (++fdctrl->data_pos == fdctrl->data_len) {
1739             fdctrl->msr &= ~FD_MSR_RQM;
1740             fdctrl_to_command_phase(fdctrl);
1741             fdctrl_reset_irq(fdctrl);
1742         }
1743         break;
1744 
1745     case FD_PHASE_COMMAND:
1746     default:
1747         abort();
1748     }
1749 
1750     retval = fdctrl->fifo[pos];
1751     FLOPPY_DPRINTF("data register: 0x%02x\n", retval);
1752 
1753     return retval;
1754 }
1755 
1756 static void fdctrl_format_sector(FDCtrl *fdctrl)
1757 {
1758     FDrive *cur_drv;
1759     uint8_t kh, kt, ks;
1760 
1761     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1762     cur_drv = get_cur_drv(fdctrl);
1763     kt = fdctrl->fifo[6];
1764     kh = fdctrl->fifo[7];
1765     ks = fdctrl->fifo[8];
1766     FLOPPY_DPRINTF("format sector at %d %d %02x %02x (%d)\n",
1767                    GET_CUR_DRV(fdctrl), kh, kt, ks,
1768                    fd_sector_calc(kh, kt, ks, cur_drv->last_sect,
1769                                   NUM_SIDES(cur_drv)));
1770     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
1771     case 2:
1772         /* sect too big */
1773         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1774         fdctrl->fifo[3] = kt;
1775         fdctrl->fifo[4] = kh;
1776         fdctrl->fifo[5] = ks;
1777         return;
1778     case 3:
1779         /* track too big */
1780         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
1781         fdctrl->fifo[3] = kt;
1782         fdctrl->fifo[4] = kh;
1783         fdctrl->fifo[5] = ks;
1784         return;
1785     case 4:
1786         /* No seek enabled */
1787         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1788         fdctrl->fifo[3] = kt;
1789         fdctrl->fifo[4] = kh;
1790         fdctrl->fifo[5] = ks;
1791         return;
1792     case 1:
1793         fdctrl->status0 |= FD_SR0_SEEK;
1794         break;
1795     default:
1796         break;
1797     }
1798     memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1799     if (cur_drv->blk == NULL ||
1800         blk_write(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) {
1801         FLOPPY_DPRINTF("error formatting sector %d\n", fd_sector(cur_drv));
1802         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1803     } else {
1804         if (cur_drv->sect == cur_drv->last_sect) {
1805             fdctrl->data_state &= ~FD_STATE_FORMAT;
1806             /* Last sector done */
1807             fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1808         } else {
1809             /* More to do */
1810             fdctrl->data_pos = 0;
1811             fdctrl->data_len = 4;
1812         }
1813     }
1814 }
1815 
1816 static void fdctrl_handle_lock(FDCtrl *fdctrl, int direction)
1817 {
1818     fdctrl->lock = (fdctrl->fifo[0] & 0x80) ? 1 : 0;
1819     fdctrl->fifo[0] = fdctrl->lock << 4;
1820     fdctrl_to_result_phase(fdctrl, 1);
1821 }
1822 
1823 static void fdctrl_handle_dumpreg(FDCtrl *fdctrl, int direction)
1824 {
1825     FDrive *cur_drv = get_cur_drv(fdctrl);
1826 
1827     /* Drives position */
1828     fdctrl->fifo[0] = drv0(fdctrl)->track;
1829     fdctrl->fifo[1] = drv1(fdctrl)->track;
1830 #if MAX_FD == 4
1831     fdctrl->fifo[2] = drv2(fdctrl)->track;
1832     fdctrl->fifo[3] = drv3(fdctrl)->track;
1833 #else
1834     fdctrl->fifo[2] = 0;
1835     fdctrl->fifo[3] = 0;
1836 #endif
1837     /* timers */
1838     fdctrl->fifo[4] = fdctrl->timer0;
1839     fdctrl->fifo[5] = (fdctrl->timer1 << 1) | (fdctrl->dor & FD_DOR_DMAEN ? 1 : 0);
1840     fdctrl->fifo[6] = cur_drv->last_sect;
1841     fdctrl->fifo[7] = (fdctrl->lock << 7) |
1842         (cur_drv->perpendicular << 2);
1843     fdctrl->fifo[8] = fdctrl->config;
1844     fdctrl->fifo[9] = fdctrl->precomp_trk;
1845     fdctrl_to_result_phase(fdctrl, 10);
1846 }
1847 
1848 static void fdctrl_handle_version(FDCtrl *fdctrl, int direction)
1849 {
1850     /* Controller's version */
1851     fdctrl->fifo[0] = fdctrl->version;
1852     fdctrl_to_result_phase(fdctrl, 1);
1853 }
1854 
1855 static void fdctrl_handle_partid(FDCtrl *fdctrl, int direction)
1856 {
1857     fdctrl->fifo[0] = 0x41; /* Stepping 1 */
1858     fdctrl_to_result_phase(fdctrl, 1);
1859 }
1860 
1861 static void fdctrl_handle_restore(FDCtrl *fdctrl, int direction)
1862 {
1863     FDrive *cur_drv = get_cur_drv(fdctrl);
1864 
1865     /* Drives position */
1866     drv0(fdctrl)->track = fdctrl->fifo[3];
1867     drv1(fdctrl)->track = fdctrl->fifo[4];
1868 #if MAX_FD == 4
1869     drv2(fdctrl)->track = fdctrl->fifo[5];
1870     drv3(fdctrl)->track = fdctrl->fifo[6];
1871 #endif
1872     /* timers */
1873     fdctrl->timer0 = fdctrl->fifo[7];
1874     fdctrl->timer1 = fdctrl->fifo[8];
1875     cur_drv->last_sect = fdctrl->fifo[9];
1876     fdctrl->lock = fdctrl->fifo[10] >> 7;
1877     cur_drv->perpendicular = (fdctrl->fifo[10] >> 2) & 0xF;
1878     fdctrl->config = fdctrl->fifo[11];
1879     fdctrl->precomp_trk = fdctrl->fifo[12];
1880     fdctrl->pwrd = fdctrl->fifo[13];
1881     fdctrl_to_command_phase(fdctrl);
1882 }
1883 
1884 static void fdctrl_handle_save(FDCtrl *fdctrl, int direction)
1885 {
1886     FDrive *cur_drv = get_cur_drv(fdctrl);
1887 
1888     fdctrl->fifo[0] = 0;
1889     fdctrl->fifo[1] = 0;
1890     /* Drives position */
1891     fdctrl->fifo[2] = drv0(fdctrl)->track;
1892     fdctrl->fifo[3] = drv1(fdctrl)->track;
1893 #if MAX_FD == 4
1894     fdctrl->fifo[4] = drv2(fdctrl)->track;
1895     fdctrl->fifo[5] = drv3(fdctrl)->track;
1896 #else
1897     fdctrl->fifo[4] = 0;
1898     fdctrl->fifo[5] = 0;
1899 #endif
1900     /* timers */
1901     fdctrl->fifo[6] = fdctrl->timer0;
1902     fdctrl->fifo[7] = fdctrl->timer1;
1903     fdctrl->fifo[8] = cur_drv->last_sect;
1904     fdctrl->fifo[9] = (fdctrl->lock << 7) |
1905         (cur_drv->perpendicular << 2);
1906     fdctrl->fifo[10] = fdctrl->config;
1907     fdctrl->fifo[11] = fdctrl->precomp_trk;
1908     fdctrl->fifo[12] = fdctrl->pwrd;
1909     fdctrl->fifo[13] = 0;
1910     fdctrl->fifo[14] = 0;
1911     fdctrl_to_result_phase(fdctrl, 15);
1912 }
1913 
1914 static void fdctrl_handle_readid(FDCtrl *fdctrl, int direction)
1915 {
1916     FDrive *cur_drv = get_cur_drv(fdctrl);
1917 
1918     cur_drv->head = (fdctrl->fifo[1] >> 2) & 1;
1919     timer_mod(fdctrl->result_timer,
1920                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + (get_ticks_per_sec() / 50));
1921 }
1922 
1923 static void fdctrl_handle_format_track(FDCtrl *fdctrl, int direction)
1924 {
1925     FDrive *cur_drv;
1926 
1927     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1928     cur_drv = get_cur_drv(fdctrl);
1929     fdctrl->data_state |= FD_STATE_FORMAT;
1930     if (fdctrl->fifo[0] & 0x80)
1931         fdctrl->data_state |= FD_STATE_MULTI;
1932     else
1933         fdctrl->data_state &= ~FD_STATE_MULTI;
1934     cur_drv->bps =
1935         fdctrl->fifo[2] > 7 ? 16384 : 128 << fdctrl->fifo[2];
1936 #if 0
1937     cur_drv->last_sect =
1938         cur_drv->flags & FDISK_DBL_SIDES ? fdctrl->fifo[3] :
1939         fdctrl->fifo[3] / 2;
1940 #else
1941     cur_drv->last_sect = fdctrl->fifo[3];
1942 #endif
1943     /* TODO: implement format using DMA expected by the Bochs BIOS
1944      * and Linux fdformat (read 3 bytes per sector via DMA and fill
1945      * the sector with the specified fill byte
1946      */
1947     fdctrl->data_state &= ~FD_STATE_FORMAT;
1948     fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1949 }
1950 
1951 static void fdctrl_handle_specify(FDCtrl *fdctrl, int direction)
1952 {
1953     fdctrl->timer0 = (fdctrl->fifo[1] >> 4) & 0xF;
1954     fdctrl->timer1 = fdctrl->fifo[2] >> 1;
1955     if (fdctrl->fifo[2] & 1)
1956         fdctrl->dor &= ~FD_DOR_DMAEN;
1957     else
1958         fdctrl->dor |= FD_DOR_DMAEN;
1959     /* No result back */
1960     fdctrl_to_command_phase(fdctrl);
1961 }
1962 
1963 static void fdctrl_handle_sense_drive_status(FDCtrl *fdctrl, int direction)
1964 {
1965     FDrive *cur_drv;
1966 
1967     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1968     cur_drv = get_cur_drv(fdctrl);
1969     cur_drv->head = (fdctrl->fifo[1] >> 2) & 1;
1970     /* 1 Byte status back */
1971     fdctrl->fifo[0] = (cur_drv->ro << 6) |
1972         (cur_drv->track == 0 ? 0x10 : 0x00) |
1973         (cur_drv->head << 2) |
1974         GET_CUR_DRV(fdctrl) |
1975         0x28;
1976     fdctrl_to_result_phase(fdctrl, 1);
1977 }
1978 
1979 static void fdctrl_handle_recalibrate(FDCtrl *fdctrl, int direction)
1980 {
1981     FDrive *cur_drv;
1982 
1983     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1984     cur_drv = get_cur_drv(fdctrl);
1985     fd_recalibrate(cur_drv);
1986     fdctrl_to_command_phase(fdctrl);
1987     /* Raise Interrupt */
1988     fdctrl->status0 |= FD_SR0_SEEK;
1989     fdctrl_raise_irq(fdctrl);
1990 }
1991 
1992 static void fdctrl_handle_sense_interrupt_status(FDCtrl *fdctrl, int direction)
1993 {
1994     FDrive *cur_drv = get_cur_drv(fdctrl);
1995 
1996     if (fdctrl->reset_sensei > 0) {
1997         fdctrl->fifo[0] =
1998             FD_SR0_RDYCHG + FD_RESET_SENSEI_COUNT - fdctrl->reset_sensei;
1999         fdctrl->reset_sensei--;
2000     } else if (!(fdctrl->sra & FD_SRA_INTPEND)) {
2001         fdctrl->fifo[0] = FD_SR0_INVCMD;
2002         fdctrl_to_result_phase(fdctrl, 1);
2003         return;
2004     } else {
2005         fdctrl->fifo[0] =
2006                 (fdctrl->status0 & ~(FD_SR0_HEAD | FD_SR0_DS1 | FD_SR0_DS0))
2007                 | GET_CUR_DRV(fdctrl);
2008     }
2009 
2010     fdctrl->fifo[1] = cur_drv->track;
2011     fdctrl_to_result_phase(fdctrl, 2);
2012     fdctrl_reset_irq(fdctrl);
2013     fdctrl->status0 = FD_SR0_RDYCHG;
2014 }
2015 
2016 static void fdctrl_handle_seek(FDCtrl *fdctrl, int direction)
2017 {
2018     FDrive *cur_drv;
2019 
2020     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
2021     cur_drv = get_cur_drv(fdctrl);
2022     fdctrl_to_command_phase(fdctrl);
2023     /* The seek command just sends step pulses to the drive and doesn't care if
2024      * there is a medium inserted of if it's banging the head against the drive.
2025      */
2026     fd_seek(cur_drv, cur_drv->head, fdctrl->fifo[2], cur_drv->sect, 1);
2027     /* Raise Interrupt */
2028     fdctrl->status0 |= FD_SR0_SEEK;
2029     fdctrl_raise_irq(fdctrl);
2030 }
2031 
2032 static void fdctrl_handle_perpendicular_mode(FDCtrl *fdctrl, int direction)
2033 {
2034     FDrive *cur_drv = get_cur_drv(fdctrl);
2035 
2036     if (fdctrl->fifo[1] & 0x80)
2037         cur_drv->perpendicular = fdctrl->fifo[1] & 0x7;
2038     /* No result back */
2039     fdctrl_to_command_phase(fdctrl);
2040 }
2041 
2042 static void fdctrl_handle_configure(FDCtrl *fdctrl, int direction)
2043 {
2044     fdctrl->config = fdctrl->fifo[2];
2045     fdctrl->precomp_trk =  fdctrl->fifo[3];
2046     /* No result back */
2047     fdctrl_to_command_phase(fdctrl);
2048 }
2049 
2050 static void fdctrl_handle_powerdown_mode(FDCtrl *fdctrl, int direction)
2051 {
2052     fdctrl->pwrd = fdctrl->fifo[1];
2053     fdctrl->fifo[0] = fdctrl->fifo[1];
2054     fdctrl_to_result_phase(fdctrl, 1);
2055 }
2056 
2057 static void fdctrl_handle_option(FDCtrl *fdctrl, int direction)
2058 {
2059     /* No result back */
2060     fdctrl_to_command_phase(fdctrl);
2061 }
2062 
2063 static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction)
2064 {
2065     FDrive *cur_drv = get_cur_drv(fdctrl);
2066     uint32_t pos;
2067 
2068     pos = fdctrl->data_pos - 1;
2069     pos %= FD_SECTOR_LEN;
2070     if (fdctrl->fifo[pos] & 0x80) {
2071         /* Command parameters done */
2072         if (fdctrl->fifo[pos] & 0x40) {
2073             fdctrl->fifo[0] = fdctrl->fifo[1];
2074             fdctrl->fifo[2] = 0;
2075             fdctrl->fifo[3] = 0;
2076             fdctrl_to_result_phase(fdctrl, 4);
2077         } else {
2078             fdctrl_to_command_phase(fdctrl);
2079         }
2080     } else if (fdctrl->data_len > 7) {
2081         /* ERROR */
2082         fdctrl->fifo[0] = 0x80 |
2083             (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
2084         fdctrl_to_result_phase(fdctrl, 1);
2085     }
2086 }
2087 
2088 static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
2089 {
2090     FDrive *cur_drv;
2091 
2092     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
2093     cur_drv = get_cur_drv(fdctrl);
2094     if (fdctrl->fifo[2] + cur_drv->track >= cur_drv->max_track) {
2095         fd_seek(cur_drv, cur_drv->head, cur_drv->max_track - 1,
2096                 cur_drv->sect, 1);
2097     } else {
2098         fd_seek(cur_drv, cur_drv->head,
2099                 cur_drv->track + fdctrl->fifo[2], cur_drv->sect, 1);
2100     }
2101     fdctrl_to_command_phase(fdctrl);
2102     /* Raise Interrupt */
2103     fdctrl->status0 |= FD_SR0_SEEK;
2104     fdctrl_raise_irq(fdctrl);
2105 }
2106 
2107 static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
2108 {
2109     FDrive *cur_drv;
2110 
2111     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
2112     cur_drv = get_cur_drv(fdctrl);
2113     if (fdctrl->fifo[2] > cur_drv->track) {
2114         fd_seek(cur_drv, cur_drv->head, 0, cur_drv->sect, 1);
2115     } else {
2116         fd_seek(cur_drv, cur_drv->head,
2117                 cur_drv->track - fdctrl->fifo[2], cur_drv->sect, 1);
2118     }
2119     fdctrl_to_command_phase(fdctrl);
2120     /* Raise Interrupt */
2121     fdctrl->status0 |= FD_SR0_SEEK;
2122     fdctrl_raise_irq(fdctrl);
2123 }
2124 
2125 /*
2126  * Handlers for the execution phase of each command
2127  */
2128 typedef struct FDCtrlCommand {
2129     uint8_t value;
2130     uint8_t mask;
2131     const char* name;
2132     int parameters;
2133     void (*handler)(FDCtrl *fdctrl, int direction);
2134     int direction;
2135 } FDCtrlCommand;
2136 
2137 static const FDCtrlCommand handlers[] = {
2138     { FD_CMD_READ, 0x1f, "READ", 8, fdctrl_start_transfer, FD_DIR_READ },
2139     { FD_CMD_WRITE, 0x3f, "WRITE", 8, fdctrl_start_transfer, FD_DIR_WRITE },
2140     { FD_CMD_SEEK, 0xff, "SEEK", 2, fdctrl_handle_seek },
2141     { FD_CMD_SENSE_INTERRUPT_STATUS, 0xff, "SENSE INTERRUPT STATUS", 0, fdctrl_handle_sense_interrupt_status },
2142     { FD_CMD_RECALIBRATE, 0xff, "RECALIBRATE", 1, fdctrl_handle_recalibrate },
2143     { FD_CMD_FORMAT_TRACK, 0xbf, "FORMAT TRACK", 5, fdctrl_handle_format_track },
2144     { FD_CMD_READ_TRACK, 0xbf, "READ TRACK", 8, fdctrl_start_transfer, FD_DIR_READ },
2145     { FD_CMD_RESTORE, 0xff, "RESTORE", 17, fdctrl_handle_restore }, /* part of READ DELETED DATA */
2146     { FD_CMD_SAVE, 0xff, "SAVE", 0, fdctrl_handle_save }, /* part of READ DELETED DATA */
2147     { FD_CMD_READ_DELETED, 0x1f, "READ DELETED DATA", 8, fdctrl_start_transfer_del, FD_DIR_READ },
2148     { FD_CMD_SCAN_EQUAL, 0x1f, "SCAN EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANE },
2149     { FD_CMD_VERIFY, 0x1f, "VERIFY", 8, fdctrl_start_transfer, FD_DIR_VERIFY },
2150     { FD_CMD_SCAN_LOW_OR_EQUAL, 0x1f, "SCAN LOW OR EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANL },
2151     { FD_CMD_SCAN_HIGH_OR_EQUAL, 0x1f, "SCAN HIGH OR EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANH },
2152     { FD_CMD_WRITE_DELETED, 0x3f, "WRITE DELETED DATA", 8, fdctrl_start_transfer_del, FD_DIR_WRITE },
2153     { FD_CMD_READ_ID, 0xbf, "READ ID", 1, fdctrl_handle_readid },
2154     { FD_CMD_SPECIFY, 0xff, "SPECIFY", 2, fdctrl_handle_specify },
2155     { FD_CMD_SENSE_DRIVE_STATUS, 0xff, "SENSE DRIVE STATUS", 1, fdctrl_handle_sense_drive_status },
2156     { FD_CMD_PERPENDICULAR_MODE, 0xff, "PERPENDICULAR MODE", 1, fdctrl_handle_perpendicular_mode },
2157     { FD_CMD_CONFIGURE, 0xff, "CONFIGURE", 3, fdctrl_handle_configure },
2158     { FD_CMD_POWERDOWN_MODE, 0xff, "POWERDOWN MODE", 2, fdctrl_handle_powerdown_mode },
2159     { FD_CMD_OPTION, 0xff, "OPTION", 1, fdctrl_handle_option },
2160     { FD_CMD_DRIVE_SPECIFICATION_COMMAND, 0xff, "DRIVE SPECIFICATION COMMAND", 5, fdctrl_handle_drive_specification_command },
2161     { FD_CMD_RELATIVE_SEEK_OUT, 0xff, "RELATIVE SEEK OUT", 2, fdctrl_handle_relative_seek_out },
2162     { FD_CMD_FORMAT_AND_WRITE, 0xff, "FORMAT AND WRITE", 10, fdctrl_unimplemented },
2163     { FD_CMD_RELATIVE_SEEK_IN, 0xff, "RELATIVE SEEK IN", 2, fdctrl_handle_relative_seek_in },
2164     { FD_CMD_LOCK, 0x7f, "LOCK", 0, fdctrl_handle_lock },
2165     { FD_CMD_DUMPREG, 0xff, "DUMPREG", 0, fdctrl_handle_dumpreg },
2166     { FD_CMD_VERSION, 0xff, "VERSION", 0, fdctrl_handle_version },
2167     { FD_CMD_PART_ID, 0xff, "PART ID", 0, fdctrl_handle_partid },
2168     { FD_CMD_WRITE, 0x1f, "WRITE (BeOS)", 8, fdctrl_start_transfer, FD_DIR_WRITE }, /* not in specification ; BeOS 4.5 bug */
2169     { 0, 0, "unknown", 0, fdctrl_unimplemented }, /* default handler */
2170 };
2171 /* Associate command to an index in the 'handlers' array */
2172 static uint8_t command_to_handler[256];
2173 
2174 static const FDCtrlCommand *get_command(uint8_t cmd)
2175 {
2176     int idx;
2177 
2178     idx = command_to_handler[cmd];
2179     FLOPPY_DPRINTF("%s command\n", handlers[idx].name);
2180     return &handlers[idx];
2181 }
2182 
2183 static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value)
2184 {
2185     FDrive *cur_drv;
2186     const FDCtrlCommand *cmd;
2187     uint32_t pos;
2188 
2189     /* Reset mode */
2190     if (!(fdctrl->dor & FD_DOR_nRESET)) {
2191         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
2192         return;
2193     }
2194     if (!(fdctrl->msr & FD_MSR_RQM) || (fdctrl->msr & FD_MSR_DIO)) {
2195         FLOPPY_DPRINTF("error: controller not ready for writing\n");
2196         return;
2197     }
2198     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
2199 
2200     FLOPPY_DPRINTF("%s: %02x\n", __func__, value);
2201 
2202     /* If data_len spans multiple sectors, the current position in the FIFO
2203      * wraps around while fdctrl->data_pos is the real position in the whole
2204      * request. */
2205     pos = fdctrl->data_pos++;
2206     pos %= FD_SECTOR_LEN;
2207     fdctrl->fifo[pos] = value;
2208 
2209     if (fdctrl->data_pos == fdctrl->data_len) {
2210         fdctrl->msr &= ~FD_MSR_RQM;
2211     }
2212 
2213     switch (fdctrl->phase) {
2214     case FD_PHASE_EXECUTION:
2215         /* For DMA requests, RQM should be cleared during execution phase, so
2216          * we would have errored out above. */
2217         assert(fdctrl->msr & FD_MSR_NONDMA);
2218 
2219         /* FIFO data write */
2220         if (pos == FD_SECTOR_LEN - 1 ||
2221             fdctrl->data_pos == fdctrl->data_len) {
2222             cur_drv = get_cur_drv(fdctrl);
2223             if (blk_write(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1)
2224                 < 0) {
2225                 FLOPPY_DPRINTF("error writing sector %d\n",
2226                                fd_sector(cur_drv));
2227                 break;
2228             }
2229             if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {
2230                 FLOPPY_DPRINTF("error seeking to next sector %d\n",
2231                                fd_sector(cur_drv));
2232                 break;
2233             }
2234         }
2235 
2236         /* Switch to result phase when done with the transfer */
2237         if (fdctrl->data_pos == fdctrl->data_len) {
2238             fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
2239         }
2240         break;
2241 
2242     case FD_PHASE_COMMAND:
2243         assert(!(fdctrl->msr & FD_MSR_NONDMA));
2244         assert(fdctrl->data_pos < FD_SECTOR_LEN);
2245 
2246         if (pos == 0) {
2247             /* The first byte specifies the command. Now we start reading
2248              * as many parameters as this command requires. */
2249             cmd = get_command(value);
2250             fdctrl->data_len = cmd->parameters + 1;
2251             if (cmd->parameters) {
2252                 fdctrl->msr |= FD_MSR_RQM;
2253             }
2254             fdctrl->msr |= FD_MSR_CMDBUSY;
2255         }
2256 
2257         if (fdctrl->data_pos == fdctrl->data_len) {
2258             /* We have all parameters now, execute the command */
2259             fdctrl->phase = FD_PHASE_EXECUTION;
2260 
2261             if (fdctrl->data_state & FD_STATE_FORMAT) {
2262                 fdctrl_format_sector(fdctrl);
2263                 break;
2264             }
2265 
2266             cmd = get_command(fdctrl->fifo[0]);
2267             FLOPPY_DPRINTF("Calling handler for '%s'\n", cmd->name);
2268             cmd->handler(fdctrl, cmd->direction);
2269         }
2270         break;
2271 
2272     case FD_PHASE_RESULT:
2273     default:
2274         abort();
2275     }
2276 }
2277 
2278 static void fdctrl_result_timer(void *opaque)
2279 {
2280     FDCtrl *fdctrl = opaque;
2281     FDrive *cur_drv = get_cur_drv(fdctrl);
2282 
2283     /* Pretend we are spinning.
2284      * This is needed for Coherent, which uses READ ID to check for
2285      * sector interleaving.
2286      */
2287     if (cur_drv->last_sect != 0) {
2288         cur_drv->sect = (cur_drv->sect % cur_drv->last_sect) + 1;
2289     }
2290     /* READ_ID can't automatically succeed! */
2291     if (fdctrl->check_media_rate &&
2292         (fdctrl->dsr & FD_DSR_DRATEMASK) != cur_drv->media_rate) {
2293         FLOPPY_DPRINTF("read id rate mismatch (fdc=%d, media=%d)\n",
2294                        fdctrl->dsr & FD_DSR_DRATEMASK, cur_drv->media_rate);
2295         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
2296     } else {
2297         fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
2298     }
2299 }
2300 
2301 static void fdctrl_change_cb(void *opaque, bool load)
2302 {
2303     FDrive *drive = opaque;
2304 
2305     drive->media_changed = 1;
2306     drive->media_validated = false;
2307     fd_revalidate(drive);
2308 }
2309 
2310 static const BlockDevOps fdctrl_block_ops = {
2311     .change_media_cb = fdctrl_change_cb,
2312 };
2313 
2314 /* Init functions */
2315 static void fdctrl_connect_drives(FDCtrl *fdctrl, Error **errp)
2316 {
2317     unsigned int i;
2318     FDrive *drive;
2319 
2320     for (i = 0; i < MAX_FD; i++) {
2321         drive = &fdctrl->drives[i];
2322         drive->fdctrl = fdctrl;
2323 
2324         if (drive->blk) {
2325             if (blk_get_on_error(drive->blk, 0) != BLOCKDEV_ON_ERROR_ENOSPC) {
2326                 error_setg(errp, "fdc doesn't support drive option werror");
2327                 return;
2328             }
2329             if (blk_get_on_error(drive->blk, 1) != BLOCKDEV_ON_ERROR_REPORT) {
2330                 error_setg(errp, "fdc doesn't support drive option rerror");
2331                 return;
2332             }
2333         }
2334 
2335         fd_init(drive);
2336         if (drive->blk) {
2337             blk_set_dev_ops(drive->blk, &fdctrl_block_ops, drive);
2338             pick_drive_type(drive);
2339         }
2340         fd_revalidate(drive);
2341     }
2342 }
2343 
2344 ISADevice *fdctrl_init_isa(ISABus *bus, DriveInfo **fds)
2345 {
2346     DeviceState *dev;
2347     ISADevice *isadev;
2348 
2349     isadev = isa_try_create(bus, TYPE_ISA_FDC);
2350     if (!isadev) {
2351         return NULL;
2352     }
2353     dev = DEVICE(isadev);
2354 
2355     if (fds[0]) {
2356         qdev_prop_set_drive(dev, "driveA", blk_by_legacy_dinfo(fds[0]),
2357                             &error_fatal);
2358     }
2359     if (fds[1]) {
2360         qdev_prop_set_drive(dev, "driveB", blk_by_legacy_dinfo(fds[1]),
2361                             &error_fatal);
2362     }
2363     qdev_init_nofail(dev);
2364 
2365     return isadev;
2366 }
2367 
2368 void fdctrl_init_sysbus(qemu_irq irq, int dma_chann,
2369                         hwaddr mmio_base, DriveInfo **fds)
2370 {
2371     FDCtrl *fdctrl;
2372     DeviceState *dev;
2373     SysBusDevice *sbd;
2374     FDCtrlSysBus *sys;
2375 
2376     dev = qdev_create(NULL, "sysbus-fdc");
2377     sys = SYSBUS_FDC(dev);
2378     fdctrl = &sys->state;
2379     fdctrl->dma_chann = dma_chann; /* FIXME */
2380     if (fds[0]) {
2381         qdev_prop_set_drive(dev, "driveA", blk_by_legacy_dinfo(fds[0]),
2382                             &error_fatal);
2383     }
2384     if (fds[1]) {
2385         qdev_prop_set_drive(dev, "driveB", blk_by_legacy_dinfo(fds[1]),
2386                             &error_fatal);
2387     }
2388     qdev_init_nofail(dev);
2389     sbd = SYS_BUS_DEVICE(dev);
2390     sysbus_connect_irq(sbd, 0, irq);
2391     sysbus_mmio_map(sbd, 0, mmio_base);
2392 }
2393 
2394 void sun4m_fdctrl_init(qemu_irq irq, hwaddr io_base,
2395                        DriveInfo **fds, qemu_irq *fdc_tc)
2396 {
2397     DeviceState *dev;
2398     FDCtrlSysBus *sys;
2399 
2400     dev = qdev_create(NULL, "SUNW,fdtwo");
2401     if (fds[0]) {
2402         qdev_prop_set_drive(dev, "drive", blk_by_legacy_dinfo(fds[0]),
2403                             &error_fatal);
2404     }
2405     qdev_init_nofail(dev);
2406     sys = SYSBUS_FDC(dev);
2407     sysbus_connect_irq(SYS_BUS_DEVICE(sys), 0, irq);
2408     sysbus_mmio_map(SYS_BUS_DEVICE(sys), 0, io_base);
2409     *fdc_tc = qdev_get_gpio_in(dev, 0);
2410 }
2411 
2412 static void fdctrl_realize_common(FDCtrl *fdctrl, Error **errp)
2413 {
2414     int i, j;
2415     static int command_tables_inited = 0;
2416 
2417     if (fdctrl->fallback == FLOPPY_DRIVE_TYPE_AUTO) {
2418         error_setg(errp, "Cannot choose a fallback FDrive type of 'auto'");
2419     }
2420 
2421     /* Fill 'command_to_handler' lookup table */
2422     if (!command_tables_inited) {
2423         command_tables_inited = 1;
2424         for (i = ARRAY_SIZE(handlers) - 1; i >= 0; i--) {
2425             for (j = 0; j < sizeof(command_to_handler); j++) {
2426                 if ((j & handlers[i].mask) == handlers[i].value) {
2427                     command_to_handler[j] = i;
2428                 }
2429             }
2430         }
2431     }
2432 
2433     FLOPPY_DPRINTF("init controller\n");
2434     fdctrl->fifo = qemu_memalign(512, FD_SECTOR_LEN);
2435     fdctrl->fifo_size = 512;
2436     fdctrl->result_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
2437                                              fdctrl_result_timer, fdctrl);
2438 
2439     fdctrl->version = 0x90; /* Intel 82078 controller */
2440     fdctrl->config = FD_CONFIG_EIS | FD_CONFIG_EFIFO; /* Implicit seek, polling & FIFO enabled */
2441     fdctrl->num_floppies = MAX_FD;
2442 
2443     if (fdctrl->dma_chann != -1) {
2444         DMA_register_channel(fdctrl->dma_chann, &fdctrl_transfer_handler, fdctrl);
2445     }
2446     fdctrl_connect_drives(fdctrl, errp);
2447 }
2448 
2449 static const MemoryRegionPortio fdc_portio_list[] = {
2450     { 1, 5, 1, .read = fdctrl_read, .write = fdctrl_write },
2451     { 7, 1, 1, .read = fdctrl_read, .write = fdctrl_write },
2452     PORTIO_END_OF_LIST(),
2453 };
2454 
2455 static void isabus_fdc_realize(DeviceState *dev, Error **errp)
2456 {
2457     ISADevice *isadev = ISA_DEVICE(dev);
2458     FDCtrlISABus *isa = ISA_FDC(dev);
2459     FDCtrl *fdctrl = &isa->state;
2460     Error *err = NULL;
2461 
2462     isa_register_portio_list(isadev, isa->iobase, fdc_portio_list, fdctrl,
2463                              "fdc");
2464 
2465     isa_init_irq(isadev, &fdctrl->irq, isa->irq);
2466     fdctrl->dma_chann = isa->dma;
2467 
2468     qdev_set_legacy_instance_id(dev, isa->iobase, 2);
2469     fdctrl_realize_common(fdctrl, &err);
2470     if (err != NULL) {
2471         error_propagate(errp, err);
2472         return;
2473     }
2474 }
2475 
2476 static void sysbus_fdc_initfn(Object *obj)
2477 {
2478     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
2479     FDCtrlSysBus *sys = SYSBUS_FDC(obj);
2480     FDCtrl *fdctrl = &sys->state;
2481 
2482     fdctrl->dma_chann = -1;
2483 
2484     memory_region_init_io(&fdctrl->iomem, obj, &fdctrl_mem_ops, fdctrl,
2485                           "fdc", 0x08);
2486     sysbus_init_mmio(sbd, &fdctrl->iomem);
2487 }
2488 
2489 static void sun4m_fdc_initfn(Object *obj)
2490 {
2491     SysBusDevice *sbd = SYS_BUS_DEVICE(obj);
2492     FDCtrlSysBus *sys = SYSBUS_FDC(obj);
2493     FDCtrl *fdctrl = &sys->state;
2494 
2495     fdctrl->dma_chann = -1;
2496 
2497     memory_region_init_io(&fdctrl->iomem, obj, &fdctrl_mem_strict_ops,
2498                           fdctrl, "fdctrl", 0x08);
2499     sysbus_init_mmio(sbd, &fdctrl->iomem);
2500 }
2501 
2502 static void sysbus_fdc_common_initfn(Object *obj)
2503 {
2504     DeviceState *dev = DEVICE(obj);
2505     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
2506     FDCtrlSysBus *sys = SYSBUS_FDC(obj);
2507     FDCtrl *fdctrl = &sys->state;
2508 
2509     qdev_set_legacy_instance_id(dev, 0 /* io */, 2); /* FIXME */
2510 
2511     sysbus_init_irq(sbd, &fdctrl->irq);
2512     qdev_init_gpio_in(dev, fdctrl_handle_tc, 1);
2513 }
2514 
2515 static void sysbus_fdc_common_realize(DeviceState *dev, Error **errp)
2516 {
2517     FDCtrlSysBus *sys = SYSBUS_FDC(dev);
2518     FDCtrl *fdctrl = &sys->state;
2519 
2520     fdctrl_realize_common(fdctrl, errp);
2521 }
2522 
2523 FloppyDriveType isa_fdc_get_drive_type(ISADevice *fdc, int i)
2524 {
2525     FDCtrlISABus *isa = ISA_FDC(fdc);
2526 
2527     return isa->state.drives[i].drive;
2528 }
2529 
2530 static const VMStateDescription vmstate_isa_fdc ={
2531     .name = "fdc",
2532     .version_id = 2,
2533     .minimum_version_id = 2,
2534     .fields = (VMStateField[]) {
2535         VMSTATE_STRUCT(state, FDCtrlISABus, 0, vmstate_fdc, FDCtrl),
2536         VMSTATE_END_OF_LIST()
2537     }
2538 };
2539 
2540 static Property isa_fdc_properties[] = {
2541     DEFINE_PROP_UINT32("iobase", FDCtrlISABus, iobase, 0x3f0),
2542     DEFINE_PROP_UINT32("irq", FDCtrlISABus, irq, 6),
2543     DEFINE_PROP_UINT32("dma", FDCtrlISABus, dma, 2),
2544     DEFINE_PROP_DRIVE("driveA", FDCtrlISABus, state.drives[0].blk),
2545     DEFINE_PROP_DRIVE("driveB", FDCtrlISABus, state.drives[1].blk),
2546     DEFINE_PROP_BIT("check_media_rate", FDCtrlISABus, state.check_media_rate,
2547                     0, true),
2548     DEFINE_PROP_DEFAULT("fdtypeA", FDCtrlISABus, state.drives[0].drive,
2549                         FLOPPY_DRIVE_TYPE_AUTO, qdev_prop_fdc_drive_type,
2550                         FloppyDriveType),
2551     DEFINE_PROP_DEFAULT("fdtypeB", FDCtrlISABus, state.drives[1].drive,
2552                         FLOPPY_DRIVE_TYPE_AUTO, qdev_prop_fdc_drive_type,
2553                         FloppyDriveType),
2554     DEFINE_PROP_DEFAULT("fallback", FDCtrlISABus, state.fallback,
2555                         FLOPPY_DRIVE_TYPE_288, qdev_prop_fdc_drive_type,
2556                         FloppyDriveType),
2557     DEFINE_PROP_END_OF_LIST(),
2558 };
2559 
2560 static void isabus_fdc_class_init(ObjectClass *klass, void *data)
2561 {
2562     DeviceClass *dc = DEVICE_CLASS(klass);
2563 
2564     dc->realize = isabus_fdc_realize;
2565     dc->fw_name = "fdc";
2566     dc->reset = fdctrl_external_reset_isa;
2567     dc->vmsd = &vmstate_isa_fdc;
2568     dc->props = isa_fdc_properties;
2569     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2570 }
2571 
2572 static void isabus_fdc_instance_init(Object *obj)
2573 {
2574     FDCtrlISABus *isa = ISA_FDC(obj);
2575 
2576     device_add_bootindex_property(obj, &isa->bootindexA,
2577                                   "bootindexA", "/floppy@0",
2578                                   DEVICE(obj), NULL);
2579     device_add_bootindex_property(obj, &isa->bootindexB,
2580                                   "bootindexB", "/floppy@1",
2581                                   DEVICE(obj), NULL);
2582 }
2583 
2584 static const TypeInfo isa_fdc_info = {
2585     .name          = TYPE_ISA_FDC,
2586     .parent        = TYPE_ISA_DEVICE,
2587     .instance_size = sizeof(FDCtrlISABus),
2588     .class_init    = isabus_fdc_class_init,
2589     .instance_init = isabus_fdc_instance_init,
2590 };
2591 
2592 static const VMStateDescription vmstate_sysbus_fdc ={
2593     .name = "fdc",
2594     .version_id = 2,
2595     .minimum_version_id = 2,
2596     .fields = (VMStateField[]) {
2597         VMSTATE_STRUCT(state, FDCtrlSysBus, 0, vmstate_fdc, FDCtrl),
2598         VMSTATE_END_OF_LIST()
2599     }
2600 };
2601 
2602 static Property sysbus_fdc_properties[] = {
2603     DEFINE_PROP_DRIVE("driveA", FDCtrlSysBus, state.drives[0].blk),
2604     DEFINE_PROP_DRIVE("driveB", FDCtrlSysBus, state.drives[1].blk),
2605     DEFINE_PROP_DEFAULT("fdtypeA", FDCtrlSysBus, state.drives[0].drive,
2606                         FLOPPY_DRIVE_TYPE_AUTO, qdev_prop_fdc_drive_type,
2607                         FloppyDriveType),
2608     DEFINE_PROP_DEFAULT("fdtypeB", FDCtrlSysBus, state.drives[1].drive,
2609                         FLOPPY_DRIVE_TYPE_AUTO, qdev_prop_fdc_drive_type,
2610                         FloppyDriveType),
2611     DEFINE_PROP_DEFAULT("fallback", FDCtrlISABus, state.fallback,
2612                         FLOPPY_DRIVE_TYPE_144, qdev_prop_fdc_drive_type,
2613                         FloppyDriveType),
2614     DEFINE_PROP_END_OF_LIST(),
2615 };
2616 
2617 static void sysbus_fdc_class_init(ObjectClass *klass, void *data)
2618 {
2619     DeviceClass *dc = DEVICE_CLASS(klass);
2620 
2621     dc->props = sysbus_fdc_properties;
2622     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2623 }
2624 
2625 static const TypeInfo sysbus_fdc_info = {
2626     .name          = "sysbus-fdc",
2627     .parent        = TYPE_SYSBUS_FDC,
2628     .instance_init = sysbus_fdc_initfn,
2629     .class_init    = sysbus_fdc_class_init,
2630 };
2631 
2632 static Property sun4m_fdc_properties[] = {
2633     DEFINE_PROP_DRIVE("drive", FDCtrlSysBus, state.drives[0].blk),
2634     DEFINE_PROP_DEFAULT("fdtype", FDCtrlSysBus, state.drives[0].drive,
2635                         FLOPPY_DRIVE_TYPE_AUTO, qdev_prop_fdc_drive_type,
2636                         FloppyDriveType),
2637     DEFINE_PROP_DEFAULT("fallback", FDCtrlISABus, state.fallback,
2638                         FLOPPY_DRIVE_TYPE_144, qdev_prop_fdc_drive_type,
2639                         FloppyDriveType),
2640     DEFINE_PROP_END_OF_LIST(),
2641 };
2642 
2643 static void sun4m_fdc_class_init(ObjectClass *klass, void *data)
2644 {
2645     DeviceClass *dc = DEVICE_CLASS(klass);
2646 
2647     dc->props = sun4m_fdc_properties;
2648     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
2649 }
2650 
2651 static const TypeInfo sun4m_fdc_info = {
2652     .name          = "SUNW,fdtwo",
2653     .parent        = TYPE_SYSBUS_FDC,
2654     .instance_init = sun4m_fdc_initfn,
2655     .class_init    = sun4m_fdc_class_init,
2656 };
2657 
2658 static void sysbus_fdc_common_class_init(ObjectClass *klass, void *data)
2659 {
2660     DeviceClass *dc = DEVICE_CLASS(klass);
2661 
2662     dc->realize = sysbus_fdc_common_realize;
2663     dc->reset = fdctrl_external_reset_sysbus;
2664     dc->vmsd = &vmstate_sysbus_fdc;
2665 }
2666 
2667 static const TypeInfo sysbus_fdc_type_info = {
2668     .name          = TYPE_SYSBUS_FDC,
2669     .parent        = TYPE_SYS_BUS_DEVICE,
2670     .instance_size = sizeof(FDCtrlSysBus),
2671     .instance_init = sysbus_fdc_common_initfn,
2672     .abstract      = true,
2673     .class_init    = sysbus_fdc_common_class_init,
2674 };
2675 
2676 static void fdc_register_types(void)
2677 {
2678     type_register_static(&isa_fdc_info);
2679     type_register_static(&sysbus_fdc_type_info);
2680     type_register_static(&sysbus_fdc_info);
2681     type_register_static(&sun4m_fdc_info);
2682 }
2683 
2684 type_init(fdc_register_types)
2685