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