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