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