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