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