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