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