c159dcb6306c4e0ac57a3820634e87a62f17bdd9
[sdk/emulator/qemu.git] / hw / fdc.c
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.h"
31 #include "fdc.h"
32 #include "qemu-error.h"
33 #include "qemu-timer.h"
34 #include "isa.h"
35 #include "sysbus.h"
36 #include "qdev-addr.h"
37 #include "blockdev.h"
38
39 /********************************************************/
40 /* debug Floppy devices */
41 //#define DEBUG_FLOPPY
42
43 #ifdef DEBUG_FLOPPY
44 #define FLOPPY_DPRINTF(fmt, ...)                                \
45     do { printf("FLOPPY: " fmt , ## __VA_ARGS__); } while (0)
46 #else
47 #define FLOPPY_DPRINTF(fmt, ...)
48 #endif
49
50 #define FLOPPY_ERROR(fmt, ...)                                          \
51     do { printf("FLOPPY ERROR: %s: " fmt, __func__ , ## __VA_ARGS__); } while (0)
52
53 /********************************************************/
54 /* Floppy drive emulation                               */
55
56 #define GET_CUR_DRV(fdctrl) ((fdctrl)->cur_drv)
57 #define SET_CUR_DRV(fdctrl, drive) ((fdctrl)->cur_drv = (drive))
58
59 /* Will always be a fixed parameter for us */
60 #define FD_SECTOR_LEN          512
61 #define FD_SECTOR_SC           2   /* Sector size code */
62 #define FD_RESET_SENSEI_COUNT  4   /* Number of sense interrupts on RESET */
63
64 /* Floppy disk drive emulation */
65 typedef enum FDiskType {
66     FDRIVE_DISK_288   = 0x01, /* 2.88 MB disk           */
67     FDRIVE_DISK_144   = 0x02, /* 1.44 MB disk           */
68     FDRIVE_DISK_720   = 0x03, /* 720 kB disk            */
69     FDRIVE_DISK_USER  = 0x04, /* User defined geometry  */
70     FDRIVE_DISK_NONE  = 0x05, /* No disk                */
71 } FDiskType;
72
73 typedef enum FDriveType {
74     FDRIVE_DRV_144  = 0x00,   /* 1.44 MB 3"5 drive      */
75     FDRIVE_DRV_288  = 0x01,   /* 2.88 MB 3"5 drive      */
76     FDRIVE_DRV_120  = 0x02,   /* 1.2  MB 5"25 drive     */
77     FDRIVE_DRV_NONE = 0x03,   /* No drive connected     */
78 } FDriveType;
79
80 typedef enum FDiskFlags {
81     FDISK_DBL_SIDES  = 0x01,
82 } FDiskFlags;
83
84 typedef struct FDrive {
85     BlockDriverState *bs;
86     /* Drive status */
87     FDriveType drive;
88     uint8_t perpendicular;    /* 2.88 MB access mode    */
89     /* Position */
90     uint8_t head;
91     uint8_t track;
92     uint8_t sect;
93     /* Media */
94     FDiskFlags flags;
95     uint8_t last_sect;        /* Nb sector per track    */
96     uint8_t max_track;        /* Nb of tracks           */
97     uint16_t bps;             /* Bytes per sector       */
98     uint8_t ro;               /* Is read-only           */
99 } FDrive;
100
101 static void fd_init(FDrive *drv)
102 {
103     /* Drive */
104     drv->drive = FDRIVE_DRV_NONE;
105     drv->perpendicular = 0;
106     /* Disk */
107     drv->last_sect = 0;
108     drv->max_track = 0;
109 }
110
111 static int fd_sector_calc(uint8_t head, uint8_t track, uint8_t sect,
112                           uint8_t last_sect)
113 {
114     return (((track * 2) + head) * last_sect) + sect - 1;
115 }
116
117 /* Returns current position, in sectors, for given drive */
118 static int fd_sector(FDrive *drv)
119 {
120     return fd_sector_calc(drv->head, drv->track, drv->sect, drv->last_sect);
121 }
122
123 /* Seek to a new position:
124  * returns 0 if already on right track
125  * returns 1 if track changed
126  * returns 2 if track is invalid
127  * returns 3 if sector is invalid
128  * returns 4 if seek is disabled
129  */
130 static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
131                    int enable_seek)
132 {
133     uint32_t sector;
134     int ret;
135
136     if (track > drv->max_track ||
137         (head != 0 && (drv->flags & FDISK_DBL_SIDES) == 0)) {
138         FLOPPY_DPRINTF("try to read %d %02x %02x (max=%d %d %02x %02x)\n",
139                        head, track, sect, 1,
140                        (drv->flags & FDISK_DBL_SIDES) == 0 ? 0 : 1,
141                        drv->max_track, drv->last_sect);
142         return 2;
143     }
144     if (sect > drv->last_sect) {
145         FLOPPY_DPRINTF("try to read %d %02x %02x (max=%d %d %02x %02x)\n",
146                        head, track, sect, 1,
147                        (drv->flags & FDISK_DBL_SIDES) == 0 ? 0 : 1,
148                        drv->max_track, drv->last_sect);
149         return 3;
150     }
151     sector = fd_sector_calc(head, track, sect, drv->last_sect);
152     ret = 0;
153     if (sector != fd_sector(drv)) {
154 #if 0
155         if (!enable_seek) {
156             FLOPPY_ERROR("no implicit seek %d %02x %02x (max=%d %02x %02x)\n",
157                          head, track, sect, 1, drv->max_track, drv->last_sect);
158             return 4;
159         }
160 #endif
161         drv->head = head;
162         if (drv->track != track)
163             ret = 1;
164         drv->track = track;
165         drv->sect = sect;
166     }
167
168     return ret;
169 }
170
171 /* Set drive back to track 0 */
172 static void fd_recalibrate(FDrive *drv)
173 {
174     FLOPPY_DPRINTF("recalibrate\n");
175     drv->head = 0;
176     drv->track = 0;
177     drv->sect = 1;
178 }
179
180 /* Recognize floppy formats */
181 typedef struct FDFormat {
182     FDriveType drive;
183     FDiskType  disk;
184     uint8_t last_sect;
185     uint8_t max_track;
186     uint8_t max_head;
187     const char *str;
188 } FDFormat;
189
190 static const FDFormat fd_formats[] = {
191     /* First entry is default format */
192     /* 1.44 MB 3"1/2 floppy disks */
193     { FDRIVE_DRV_144, FDRIVE_DISK_144, 18, 80, 1, "1.44 MB 3\"1/2", },
194     { FDRIVE_DRV_144, FDRIVE_DISK_144, 20, 80, 1,  "1.6 MB 3\"1/2", },
195     { FDRIVE_DRV_144, FDRIVE_DISK_144, 21, 80, 1, "1.68 MB 3\"1/2", },
196     { FDRIVE_DRV_144, FDRIVE_DISK_144, 21, 82, 1, "1.72 MB 3\"1/2", },
197     { FDRIVE_DRV_144, FDRIVE_DISK_144, 21, 83, 1, "1.74 MB 3\"1/2", },
198     { FDRIVE_DRV_144, FDRIVE_DISK_144, 22, 80, 1, "1.76 MB 3\"1/2", },
199     { FDRIVE_DRV_144, FDRIVE_DISK_144, 23, 80, 1, "1.84 MB 3\"1/2", },
200     { FDRIVE_DRV_144, FDRIVE_DISK_144, 24, 80, 1, "1.92 MB 3\"1/2", },
201     /* 2.88 MB 3"1/2 floppy disks */
202     { FDRIVE_DRV_288, FDRIVE_DISK_288, 36, 80, 1, "2.88 MB 3\"1/2", },
203     { FDRIVE_DRV_288, FDRIVE_DISK_288, 39, 80, 1, "3.12 MB 3\"1/2", },
204     { FDRIVE_DRV_288, FDRIVE_DISK_288, 40, 80, 1,  "3.2 MB 3\"1/2", },
205     { FDRIVE_DRV_288, FDRIVE_DISK_288, 44, 80, 1, "3.52 MB 3\"1/2", },
206     { FDRIVE_DRV_288, FDRIVE_DISK_288, 48, 80, 1, "3.84 MB 3\"1/2", },
207     /* 720 kB 3"1/2 floppy disks */
208     { FDRIVE_DRV_144, FDRIVE_DISK_720,  9, 80, 1,  "720 kB 3\"1/2", },
209     { FDRIVE_DRV_144, FDRIVE_DISK_720, 10, 80, 1,  "800 kB 3\"1/2", },
210     { FDRIVE_DRV_144, FDRIVE_DISK_720, 10, 82, 1,  "820 kB 3\"1/2", },
211     { FDRIVE_DRV_144, FDRIVE_DISK_720, 10, 83, 1,  "830 kB 3\"1/2", },
212     { FDRIVE_DRV_144, FDRIVE_DISK_720, 13, 80, 1, "1.04 MB 3\"1/2", },
213     { FDRIVE_DRV_144, FDRIVE_DISK_720, 14, 80, 1, "1.12 MB 3\"1/2", },
214     /* 1.2 MB 5"1/4 floppy disks */
215     { FDRIVE_DRV_120, FDRIVE_DISK_288, 15, 80, 1,  "1.2 kB 5\"1/4", },
216     { FDRIVE_DRV_120, FDRIVE_DISK_288, 18, 80, 1, "1.44 MB 5\"1/4", },
217     { FDRIVE_DRV_120, FDRIVE_DISK_288, 18, 82, 1, "1.48 MB 5\"1/4", },
218     { FDRIVE_DRV_120, FDRIVE_DISK_288, 18, 83, 1, "1.49 MB 5\"1/4", },
219     { FDRIVE_DRV_120, FDRIVE_DISK_288, 20, 80, 1,  "1.6 MB 5\"1/4", },
220     /* 720 kB 5"1/4 floppy disks */
221     { FDRIVE_DRV_120, FDRIVE_DISK_288,  9, 80, 1,  "720 kB 5\"1/4", },
222     { FDRIVE_DRV_120, FDRIVE_DISK_288, 11, 80, 1,  "880 kB 5\"1/4", },
223     /* 360 kB 5"1/4 floppy disks */
224     { FDRIVE_DRV_120, FDRIVE_DISK_288,  9, 40, 1,  "360 kB 5\"1/4", },
225     { FDRIVE_DRV_120, FDRIVE_DISK_288,  9, 40, 0,  "180 kB 5\"1/4", },
226     { FDRIVE_DRV_120, FDRIVE_DISK_288, 10, 41, 1,  "410 kB 5\"1/4", },
227     { FDRIVE_DRV_120, FDRIVE_DISK_288, 10, 42, 1,  "420 kB 5\"1/4", },
228     /* 320 kB 5"1/4 floppy disks */
229     { FDRIVE_DRV_120, FDRIVE_DISK_288,  8, 40, 1,  "320 kB 5\"1/4", },
230     { FDRIVE_DRV_120, FDRIVE_DISK_288,  8, 40, 0,  "160 kB 5\"1/4", },
231     /* 360 kB must match 5"1/4 better than 3"1/2... */
232     { FDRIVE_DRV_144, FDRIVE_DISK_720,  9, 80, 0,  "360 kB 3\"1/2", },
233     /* end */
234     { FDRIVE_DRV_NONE, FDRIVE_DISK_NONE, -1, -1, 0, NULL, },
235 };
236
237 /* Revalidate a disk drive after a disk change */
238 static void fd_revalidate(FDrive *drv)
239 {
240     const FDFormat *parse;
241     uint64_t nb_sectors, size;
242     int i, first_match, match;
243     int nb_heads, max_track, last_sect, ro;
244
245     FLOPPY_DPRINTF("revalidate\n");
246     if (drv->bs != NULL && bdrv_is_inserted(drv->bs)) {
247         ro = bdrv_is_read_only(drv->bs);
248         bdrv_get_geometry_hint(drv->bs, &nb_heads, &max_track, &last_sect);
249         if (nb_heads != 0 && max_track != 0 && last_sect != 0) {
250             FLOPPY_DPRINTF("User defined disk (%d %d %d)",
251                            nb_heads - 1, max_track, last_sect);
252         } else {
253             bdrv_get_geometry(drv->bs, &nb_sectors);
254             match = -1;
255             first_match = -1;
256             for (i = 0;; i++) {
257                 parse = &fd_formats[i];
258                 if (parse->drive == FDRIVE_DRV_NONE)
259                     break;
260                 if (drv->drive == parse->drive ||
261                     drv->drive == FDRIVE_DRV_NONE) {
262                     size = (parse->max_head + 1) * parse->max_track *
263                         parse->last_sect;
264                     if (nb_sectors == size) {
265                         match = i;
266                         break;
267                     }
268                     if (first_match == -1)
269                         first_match = i;
270                 }
271             }
272             if (match == -1) {
273                 if (first_match == -1)
274                     match = 1;
275                 else
276                     match = first_match;
277                 parse = &fd_formats[match];
278             }
279             nb_heads = parse->max_head + 1;
280             max_track = parse->max_track;
281             last_sect = parse->last_sect;
282             drv->drive = parse->drive;
283             FLOPPY_DPRINTF("%s floppy disk (%d h %d t %d s) %s\n", parse->str,
284                            nb_heads, max_track, last_sect, ro ? "ro" : "rw");
285         }
286         if (nb_heads == 1) {
287             drv->flags &= ~FDISK_DBL_SIDES;
288         } else {
289             drv->flags |= FDISK_DBL_SIDES;
290         }
291         drv->max_track = max_track;
292         drv->last_sect = last_sect;
293         drv->ro = ro;
294     } else {
295         FLOPPY_DPRINTF("No disk in drive\n");
296         drv->last_sect = 0;
297         drv->max_track = 0;
298         drv->flags &= ~FDISK_DBL_SIDES;
299     }
300 }
301
302 /********************************************************/
303 /* Intel 82078 floppy disk controller emulation          */
304
305 static void fdctrl_reset(FDCtrl *fdctrl, int do_irq);
306 static void fdctrl_reset_fifo(FDCtrl *fdctrl);
307 static int fdctrl_transfer_handler (void *opaque, int nchan,
308                                     int dma_pos, int dma_len);
309 static void fdctrl_raise_irq(FDCtrl *fdctrl, uint8_t status0);
310
311 static uint32_t fdctrl_read_statusA(FDCtrl *fdctrl);
312 static uint32_t fdctrl_read_statusB(FDCtrl *fdctrl);
313 static uint32_t fdctrl_read_dor(FDCtrl *fdctrl);
314 static void fdctrl_write_dor(FDCtrl *fdctrl, uint32_t value);
315 static uint32_t fdctrl_read_tape(FDCtrl *fdctrl);
316 static void fdctrl_write_tape(FDCtrl *fdctrl, uint32_t value);
317 static uint32_t fdctrl_read_main_status(FDCtrl *fdctrl);
318 static void fdctrl_write_rate(FDCtrl *fdctrl, uint32_t value);
319 static uint32_t fdctrl_read_data(FDCtrl *fdctrl);
320 static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value);
321 static uint32_t fdctrl_read_dir(FDCtrl *fdctrl);
322
323 enum {
324     FD_DIR_WRITE   = 0,
325     FD_DIR_READ    = 1,
326     FD_DIR_SCANE   = 2,
327     FD_DIR_SCANL   = 3,
328     FD_DIR_SCANH   = 4,
329 };
330
331 enum {
332     FD_STATE_MULTI  = 0x01,     /* multi track flag */
333     FD_STATE_FORMAT = 0x02,     /* format flag */
334     FD_STATE_SEEK   = 0x04,     /* seek flag */
335 };
336
337 enum {
338     FD_REG_SRA = 0x00,
339     FD_REG_SRB = 0x01,
340     FD_REG_DOR = 0x02,
341     FD_REG_TDR = 0x03,
342     FD_REG_MSR = 0x04,
343     FD_REG_DSR = 0x04,
344     FD_REG_FIFO = 0x05,
345     FD_REG_DIR = 0x07,
346 };
347
348 enum {
349     FD_CMD_READ_TRACK = 0x02,
350     FD_CMD_SPECIFY = 0x03,
351     FD_CMD_SENSE_DRIVE_STATUS = 0x04,
352     FD_CMD_WRITE = 0x05,
353     FD_CMD_READ = 0x06,
354     FD_CMD_RECALIBRATE = 0x07,
355     FD_CMD_SENSE_INTERRUPT_STATUS = 0x08,
356     FD_CMD_WRITE_DELETED = 0x09,
357     FD_CMD_READ_ID = 0x0a,
358     FD_CMD_READ_DELETED = 0x0c,
359     FD_CMD_FORMAT_TRACK = 0x0d,
360     FD_CMD_DUMPREG = 0x0e,
361     FD_CMD_SEEK = 0x0f,
362     FD_CMD_VERSION = 0x10,
363     FD_CMD_SCAN_EQUAL = 0x11,
364     FD_CMD_PERPENDICULAR_MODE = 0x12,
365     FD_CMD_CONFIGURE = 0x13,
366     FD_CMD_LOCK = 0x14,
367     FD_CMD_VERIFY = 0x16,
368     FD_CMD_POWERDOWN_MODE = 0x17,
369     FD_CMD_PART_ID = 0x18,
370     FD_CMD_SCAN_LOW_OR_EQUAL = 0x19,
371     FD_CMD_SCAN_HIGH_OR_EQUAL = 0x1d,
372     FD_CMD_SAVE = 0x2e,
373     FD_CMD_OPTION = 0x33,
374     FD_CMD_RESTORE = 0x4e,
375     FD_CMD_DRIVE_SPECIFICATION_COMMAND = 0x8e,
376     FD_CMD_RELATIVE_SEEK_OUT = 0x8f,
377     FD_CMD_FORMAT_AND_WRITE = 0xcd,
378     FD_CMD_RELATIVE_SEEK_IN = 0xcf,
379 };
380
381 enum {
382     FD_CONFIG_PRETRK = 0xff, /* Pre-compensation set to track 0 */
383     FD_CONFIG_FIFOTHR = 0x0f, /* FIFO threshold set to 1 byte */
384     FD_CONFIG_POLL  = 0x10, /* Poll enabled */
385     FD_CONFIG_EFIFO = 0x20, /* FIFO disabled */
386     FD_CONFIG_EIS   = 0x40, /* No implied seeks */
387 };
388
389 enum {
390     FD_SR0_EQPMT    = 0x10,
391     FD_SR0_SEEK     = 0x20,
392     FD_SR0_ABNTERM  = 0x40,
393     FD_SR0_INVCMD   = 0x80,
394     FD_SR0_RDYCHG   = 0xc0,
395 };
396
397 enum {
398     FD_SR1_EC       = 0x80, /* End of cylinder */
399 };
400
401 enum {
402     FD_SR2_SNS      = 0x04, /* Scan not satisfied */
403     FD_SR2_SEH      = 0x08, /* Scan equal hit */
404 };
405
406 enum {
407     FD_SRA_DIR      = 0x01,
408     FD_SRA_nWP      = 0x02,
409     FD_SRA_nINDX    = 0x04,
410     FD_SRA_HDSEL    = 0x08,
411     FD_SRA_nTRK0    = 0x10,
412     FD_SRA_STEP     = 0x20,
413     FD_SRA_nDRV2    = 0x40,
414     FD_SRA_INTPEND  = 0x80,
415 };
416
417 enum {
418     FD_SRB_MTR0     = 0x01,
419     FD_SRB_MTR1     = 0x02,
420     FD_SRB_WGATE    = 0x04,
421     FD_SRB_RDATA    = 0x08,
422     FD_SRB_WDATA    = 0x10,
423     FD_SRB_DR0      = 0x20,
424 };
425
426 enum {
427 #if MAX_FD == 4
428     FD_DOR_SELMASK  = 0x03,
429 #else
430     FD_DOR_SELMASK  = 0x01,
431 #endif
432     FD_DOR_nRESET   = 0x04,
433     FD_DOR_DMAEN    = 0x08,
434     FD_DOR_MOTEN0   = 0x10,
435     FD_DOR_MOTEN1   = 0x20,
436     FD_DOR_MOTEN2   = 0x40,
437     FD_DOR_MOTEN3   = 0x80,
438 };
439
440 enum {
441 #if MAX_FD == 4
442     FD_TDR_BOOTSEL  = 0x0c,
443 #else
444     FD_TDR_BOOTSEL  = 0x04,
445 #endif
446 };
447
448 enum {
449     FD_DSR_DRATEMASK= 0x03,
450     FD_DSR_PWRDOWN  = 0x40,
451     FD_DSR_SWRESET  = 0x80,
452 };
453
454 enum {
455     FD_MSR_DRV0BUSY = 0x01,
456     FD_MSR_DRV1BUSY = 0x02,
457     FD_MSR_DRV2BUSY = 0x04,
458     FD_MSR_DRV3BUSY = 0x08,
459     FD_MSR_CMDBUSY  = 0x10,
460     FD_MSR_NONDMA   = 0x20,
461     FD_MSR_DIO      = 0x40,
462     FD_MSR_RQM      = 0x80,
463 };
464
465 enum {
466     FD_DIR_DSKCHG   = 0x80,
467 };
468
469 #define FD_MULTI_TRACK(state) ((state) & FD_STATE_MULTI)
470 #define FD_DID_SEEK(state) ((state) & FD_STATE_SEEK)
471 #define FD_FORMAT_CMD(state) ((state) & FD_STATE_FORMAT)
472
473 struct FDCtrl {
474     /* Controller's identification */
475     uint8_t version;
476     /* HW */
477     qemu_irq irq;
478     int dma_chann;
479     /* Controller state */
480     QEMUTimer *result_timer;
481     uint8_t sra;
482     uint8_t srb;
483     uint8_t dor;
484     uint8_t dor_vmstate; /* only used as temp during vmstate */
485     uint8_t tdr;
486     uint8_t dsr;
487     uint8_t msr;
488     uint8_t cur_drv;
489     uint8_t status0;
490     uint8_t status1;
491     uint8_t status2;
492     /* Command FIFO */
493     uint8_t *fifo;
494     int32_t fifo_size;
495     uint32_t data_pos;
496     uint32_t data_len;
497     uint8_t data_state;
498     uint8_t data_dir;
499     uint8_t eot; /* last wanted sector */
500     /* States kept only to be returned back */
501     /* Timers state */
502     uint8_t timer0;
503     uint8_t timer1;
504     /* precompensation */
505     uint8_t precomp_trk;
506     uint8_t config;
507     uint8_t lock;
508     /* Power down config (also with status regB access mode */
509     uint8_t pwrd;
510     /* Sun4m quirks? */
511     int sun4m;
512     /* Floppy drives */
513     uint8_t num_floppies;
514     FDrive drives[MAX_FD];
515     int reset_sensei;
516 };
517
518 typedef struct FDCtrlSysBus {
519     SysBusDevice busdev;
520     struct FDCtrl state;
521 } FDCtrlSysBus;
522
523 typedef struct FDCtrlISABus {
524     ISADevice busdev;
525     struct FDCtrl state;
526 } FDCtrlISABus;
527
528 static uint32_t fdctrl_read (void *opaque, uint32_t reg)
529 {
530     FDCtrl *fdctrl = opaque;
531     uint32_t retval;
532
533     switch (reg) {
534     case FD_REG_SRA:
535         retval = fdctrl_read_statusA(fdctrl);
536         break;
537     case FD_REG_SRB:
538         retval = fdctrl_read_statusB(fdctrl);
539         break;
540     case FD_REG_DOR:
541         retval = fdctrl_read_dor(fdctrl);
542         break;
543     case FD_REG_TDR:
544         retval = fdctrl_read_tape(fdctrl);
545         break;
546     case FD_REG_MSR:
547         retval = fdctrl_read_main_status(fdctrl);
548         break;
549     case FD_REG_FIFO:
550         retval = fdctrl_read_data(fdctrl);
551         break;
552     case FD_REG_DIR:
553         retval = fdctrl_read_dir(fdctrl);
554         break;
555     default:
556         retval = (uint32_t)(-1);
557         break;
558     }
559     FLOPPY_DPRINTF("read reg%d: 0x%02x\n", reg & 7, retval);
560
561     return retval;
562 }
563
564 static void fdctrl_write (void *opaque, uint32_t reg, uint32_t value)
565 {
566     FDCtrl *fdctrl = opaque;
567
568     FLOPPY_DPRINTF("write reg%d: 0x%02x\n", reg & 7, value);
569
570     switch (reg) {
571     case FD_REG_DOR:
572         fdctrl_write_dor(fdctrl, value);
573         break;
574     case FD_REG_TDR:
575         fdctrl_write_tape(fdctrl, value);
576         break;
577     case FD_REG_DSR:
578         fdctrl_write_rate(fdctrl, value);
579         break;
580     case FD_REG_FIFO:
581         fdctrl_write_data(fdctrl, value);
582         break;
583     default:
584         break;
585     }
586 }
587
588 static uint32_t fdctrl_read_port (void *opaque, uint32_t reg)
589 {
590     return fdctrl_read(opaque, reg & 7);
591 }
592
593 static void fdctrl_write_port (void *opaque, uint32_t reg, uint32_t value)
594 {
595     fdctrl_write(opaque, reg & 7, value);
596 }
597
598 static uint32_t fdctrl_read_mem (void *opaque, target_phys_addr_t reg)
599 {
600     return fdctrl_read(opaque, (uint32_t)reg);
601 }
602
603 static void fdctrl_write_mem (void *opaque,
604                               target_phys_addr_t reg, uint32_t value)
605 {
606     fdctrl_write(opaque, (uint32_t)reg, value);
607 }
608
609 static CPUReadMemoryFunc * const fdctrl_mem_read[3] = {
610     fdctrl_read_mem,
611     fdctrl_read_mem,
612     fdctrl_read_mem,
613 };
614
615 static CPUWriteMemoryFunc * const fdctrl_mem_write[3] = {
616     fdctrl_write_mem,
617     fdctrl_write_mem,
618     fdctrl_write_mem,
619 };
620
621 static CPUReadMemoryFunc * const fdctrl_mem_read_strict[3] = {
622     fdctrl_read_mem,
623     NULL,
624     NULL,
625 };
626
627 static CPUWriteMemoryFunc * const fdctrl_mem_write_strict[3] = {
628     fdctrl_write_mem,
629     NULL,
630     NULL,
631 };
632
633 static const VMStateDescription vmstate_fdrive = {
634     .name = "fdrive",
635     .version_id = 1,
636     .minimum_version_id = 1,
637     .minimum_version_id_old = 1,
638     .fields      = (VMStateField []) {
639         VMSTATE_UINT8(head, FDrive),
640         VMSTATE_UINT8(track, FDrive),
641         VMSTATE_UINT8(sect, FDrive),
642         VMSTATE_END_OF_LIST()
643     }
644 };
645
646 static void fdc_pre_save(void *opaque)
647 {
648     FDCtrl *s = opaque;
649
650     s->dor_vmstate = s->dor | GET_CUR_DRV(s);
651 }
652
653 static int fdc_post_load(void *opaque, int version_id)
654 {
655     FDCtrl *s = opaque;
656
657     SET_CUR_DRV(s, s->dor_vmstate & FD_DOR_SELMASK);
658     s->dor = s->dor_vmstate & ~FD_DOR_SELMASK;
659     return 0;
660 }
661
662 static const VMStateDescription vmstate_fdc = {
663     .name = "fdc",
664     .version_id = 2,
665     .minimum_version_id = 2,
666     .minimum_version_id_old = 2,
667     .pre_save = fdc_pre_save,
668     .post_load = fdc_post_load,
669     .fields      = (VMStateField []) {
670         /* Controller State */
671         VMSTATE_UINT8(sra, FDCtrl),
672         VMSTATE_UINT8(srb, FDCtrl),
673         VMSTATE_UINT8(dor_vmstate, FDCtrl),
674         VMSTATE_UINT8(tdr, FDCtrl),
675         VMSTATE_UINT8(dsr, FDCtrl),
676         VMSTATE_UINT8(msr, FDCtrl),
677         VMSTATE_UINT8(status0, FDCtrl),
678         VMSTATE_UINT8(status1, FDCtrl),
679         VMSTATE_UINT8(status2, FDCtrl),
680         /* Command FIFO */
681         VMSTATE_VARRAY_INT32(fifo, FDCtrl, fifo_size, 0, vmstate_info_uint8,
682                              uint8_t),
683         VMSTATE_UINT32(data_pos, FDCtrl),
684         VMSTATE_UINT32(data_len, FDCtrl),
685         VMSTATE_UINT8(data_state, FDCtrl),
686         VMSTATE_UINT8(data_dir, FDCtrl),
687         VMSTATE_UINT8(eot, FDCtrl),
688         /* States kept only to be returned back */
689         VMSTATE_UINT8(timer0, FDCtrl),
690         VMSTATE_UINT8(timer1, FDCtrl),
691         VMSTATE_UINT8(precomp_trk, FDCtrl),
692         VMSTATE_UINT8(config, FDCtrl),
693         VMSTATE_UINT8(lock, FDCtrl),
694         VMSTATE_UINT8(pwrd, FDCtrl),
695         VMSTATE_UINT8_EQUAL(num_floppies, FDCtrl),
696         VMSTATE_STRUCT_ARRAY(drives, FDCtrl, MAX_FD, 1,
697                              vmstate_fdrive, FDrive),
698         VMSTATE_END_OF_LIST()
699     }
700 };
701
702 static void fdctrl_external_reset_sysbus(DeviceState *d)
703 {
704     FDCtrlSysBus *sys = container_of(d, FDCtrlSysBus, busdev.qdev);
705     FDCtrl *s = &sys->state;
706
707     fdctrl_reset(s, 0);
708 }
709
710 static void fdctrl_external_reset_isa(DeviceState *d)
711 {
712     FDCtrlISABus *isa = container_of(d, FDCtrlISABus, busdev.qdev);
713     FDCtrl *s = &isa->state;
714
715     fdctrl_reset(s, 0);
716 }
717
718 static void fdctrl_handle_tc(void *opaque, int irq, int level)
719 {
720     //FDCtrl *s = opaque;
721
722     if (level) {
723         // XXX
724         FLOPPY_DPRINTF("TC pulsed\n");
725     }
726 }
727
728 /* XXX: may change if moved to bdrv */
729 int fdctrl_get_drive_type(FDCtrl *fdctrl, int drive_num)
730 {
731     return fdctrl->drives[drive_num].drive;
732 }
733
734 /* Change IRQ state */
735 static void fdctrl_reset_irq(FDCtrl *fdctrl)
736 {
737     if (!(fdctrl->sra & FD_SRA_INTPEND))
738         return;
739     FLOPPY_DPRINTF("Reset interrupt\n");
740     qemu_set_irq(fdctrl->irq, 0);
741     fdctrl->sra &= ~FD_SRA_INTPEND;
742 }
743
744 static void fdctrl_raise_irq(FDCtrl *fdctrl, uint8_t status0)
745 {
746     /* Sparc mutation */
747     if (fdctrl->sun4m && (fdctrl->msr & FD_MSR_CMDBUSY)) {
748         /* XXX: not sure */
749         fdctrl->msr &= ~FD_MSR_CMDBUSY;
750         fdctrl->msr |= FD_MSR_RQM | FD_MSR_DIO;
751         fdctrl->status0 = status0;
752         return;
753     }
754     if (!(fdctrl->sra & FD_SRA_INTPEND)) {
755         qemu_set_irq(fdctrl->irq, 1);
756         fdctrl->sra |= FD_SRA_INTPEND;
757     }
758     fdctrl->reset_sensei = 0;
759     fdctrl->status0 = status0;
760     FLOPPY_DPRINTF("Set interrupt status to 0x%02x\n", fdctrl->status0);
761 }
762
763 /* Reset controller */
764 static void fdctrl_reset(FDCtrl *fdctrl, int do_irq)
765 {
766     int i;
767
768     FLOPPY_DPRINTF("reset controller\n");
769     fdctrl_reset_irq(fdctrl);
770     /* Initialise controller */
771     fdctrl->sra = 0;
772     fdctrl->srb = 0xc0;
773     if (!fdctrl->drives[1].bs)
774         fdctrl->sra |= FD_SRA_nDRV2;
775     fdctrl->cur_drv = 0;
776     fdctrl->dor = FD_DOR_nRESET;
777     fdctrl->dor |= (fdctrl->dma_chann != -1) ? FD_DOR_DMAEN : 0;
778     fdctrl->msr = FD_MSR_RQM;
779     /* FIFO state */
780     fdctrl->data_pos = 0;
781     fdctrl->data_len = 0;
782     fdctrl->data_state = 0;
783     fdctrl->data_dir = FD_DIR_WRITE;
784     for (i = 0; i < MAX_FD; i++)
785         fd_recalibrate(&fdctrl->drives[i]);
786     fdctrl_reset_fifo(fdctrl);
787     if (do_irq) {
788         fdctrl_raise_irq(fdctrl, FD_SR0_RDYCHG);
789         fdctrl->reset_sensei = FD_RESET_SENSEI_COUNT;
790     }
791 }
792
793 static inline FDrive *drv0(FDCtrl *fdctrl)
794 {
795     return &fdctrl->drives[(fdctrl->tdr & FD_TDR_BOOTSEL) >> 2];
796 }
797
798 static inline FDrive *drv1(FDCtrl *fdctrl)
799 {
800     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (1 << 2))
801         return &fdctrl->drives[1];
802     else
803         return &fdctrl->drives[0];
804 }
805
806 #if MAX_FD == 4
807 static inline FDrive *drv2(FDCtrl *fdctrl)
808 {
809     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (2 << 2))
810         return &fdctrl->drives[2];
811     else
812         return &fdctrl->drives[1];
813 }
814
815 static inline FDrive *drv3(FDCtrl *fdctrl)
816 {
817     if ((fdctrl->tdr & FD_TDR_BOOTSEL) < (3 << 2))
818         return &fdctrl->drives[3];
819     else
820         return &fdctrl->drives[2];
821 }
822 #endif
823
824 static FDrive *get_cur_drv(FDCtrl *fdctrl)
825 {
826     switch (fdctrl->cur_drv) {
827         case 0: return drv0(fdctrl);
828         case 1: return drv1(fdctrl);
829 #if MAX_FD == 4
830         case 2: return drv2(fdctrl);
831         case 3: return drv3(fdctrl);
832 #endif
833         default: return NULL;
834     }
835 }
836
837 /* Status A register : 0x00 (read-only) */
838 static uint32_t fdctrl_read_statusA(FDCtrl *fdctrl)
839 {
840     uint32_t retval = fdctrl->sra;
841
842     FLOPPY_DPRINTF("status register A: 0x%02x\n", retval);
843
844     return retval;
845 }
846
847 /* Status B register : 0x01 (read-only) */
848 static uint32_t fdctrl_read_statusB(FDCtrl *fdctrl)
849 {
850     uint32_t retval = fdctrl->srb;
851
852     FLOPPY_DPRINTF("status register B: 0x%02x\n", retval);
853
854     return retval;
855 }
856
857 /* Digital output register : 0x02 */
858 static uint32_t fdctrl_read_dor(FDCtrl *fdctrl)
859 {
860     uint32_t retval = fdctrl->dor;
861
862     /* Selected drive */
863     retval |= fdctrl->cur_drv;
864     FLOPPY_DPRINTF("digital output register: 0x%02x\n", retval);
865
866     return retval;
867 }
868
869 static void fdctrl_write_dor(FDCtrl *fdctrl, uint32_t value)
870 {
871     FLOPPY_DPRINTF("digital output register set to 0x%02x\n", value);
872
873     /* Motors */
874     if (value & FD_DOR_MOTEN0)
875         fdctrl->srb |= FD_SRB_MTR0;
876     else
877         fdctrl->srb &= ~FD_SRB_MTR0;
878     if (value & FD_DOR_MOTEN1)
879         fdctrl->srb |= FD_SRB_MTR1;
880     else
881         fdctrl->srb &= ~FD_SRB_MTR1;
882
883     /* Drive */
884     if (value & 1)
885         fdctrl->srb |= FD_SRB_DR0;
886     else
887         fdctrl->srb &= ~FD_SRB_DR0;
888
889     /* Reset */
890     if (!(value & FD_DOR_nRESET)) {
891         if (fdctrl->dor & FD_DOR_nRESET) {
892             FLOPPY_DPRINTF("controller enter RESET state\n");
893         }
894     } else {
895         if (!(fdctrl->dor & FD_DOR_nRESET)) {
896             FLOPPY_DPRINTF("controller out of RESET state\n");
897             fdctrl_reset(fdctrl, 1);
898             fdctrl->dsr &= ~FD_DSR_PWRDOWN;
899         }
900     }
901     /* Selected drive */
902     fdctrl->cur_drv = value & FD_DOR_SELMASK;
903
904     fdctrl->dor = value;
905 }
906
907 /* Tape drive register : 0x03 */
908 static uint32_t fdctrl_read_tape(FDCtrl *fdctrl)
909 {
910     uint32_t retval = fdctrl->tdr;
911
912     FLOPPY_DPRINTF("tape drive register: 0x%02x\n", retval);
913
914     return retval;
915 }
916
917 static void fdctrl_write_tape(FDCtrl *fdctrl, uint32_t value)
918 {
919     /* Reset mode */
920     if (!(fdctrl->dor & FD_DOR_nRESET)) {
921         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
922         return;
923     }
924     FLOPPY_DPRINTF("tape drive register set to 0x%02x\n", value);
925     /* Disk boot selection indicator */
926     fdctrl->tdr = value & FD_TDR_BOOTSEL;
927     /* Tape indicators: never allow */
928 }
929
930 /* Main status register : 0x04 (read) */
931 static uint32_t fdctrl_read_main_status(FDCtrl *fdctrl)
932 {
933     uint32_t retval = fdctrl->msr;
934
935     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
936     fdctrl->dor |= FD_DOR_nRESET;
937
938     /* Sparc mutation */
939     if (fdctrl->sun4m) {
940         retval |= FD_MSR_DIO;
941         fdctrl_reset_irq(fdctrl);
942     };
943
944     FLOPPY_DPRINTF("main status register: 0x%02x\n", retval);
945
946     return retval;
947 }
948
949 /* Data select rate register : 0x04 (write) */
950 static void fdctrl_write_rate(FDCtrl *fdctrl, uint32_t value)
951 {
952     /* Reset mode */
953     if (!(fdctrl->dor & FD_DOR_nRESET)) {
954         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
955         return;
956     }
957     FLOPPY_DPRINTF("select rate register set to 0x%02x\n", value);
958     /* Reset: autoclear */
959     if (value & FD_DSR_SWRESET) {
960         fdctrl->dor &= ~FD_DOR_nRESET;
961         fdctrl_reset(fdctrl, 1);
962         fdctrl->dor |= FD_DOR_nRESET;
963     }
964     if (value & FD_DSR_PWRDOWN) {
965         fdctrl_reset(fdctrl, 1);
966     }
967     fdctrl->dsr = value;
968 }
969
970 static int fdctrl_media_changed(FDrive *drv)
971 {
972     int ret;
973
974     if (!drv->bs)
975         return 0;
976     ret = bdrv_media_changed(drv->bs);
977     if (ret) {
978         fd_revalidate(drv);
979     }
980     return ret;
981 }
982
983 /* Digital input register : 0x07 (read-only) */
984 static uint32_t fdctrl_read_dir(FDCtrl *fdctrl)
985 {
986     uint32_t retval = 0;
987
988     if (fdctrl_media_changed(drv0(fdctrl))
989      || fdctrl_media_changed(drv1(fdctrl))
990 #if MAX_FD == 4
991      || fdctrl_media_changed(drv2(fdctrl))
992      || fdctrl_media_changed(drv3(fdctrl))
993 #endif
994         )
995         retval |= FD_DIR_DSKCHG;
996     if (retval != 0) {
997         FLOPPY_DPRINTF("Floppy digital input register: 0x%02x\n", retval);
998     }
999
1000     return retval;
1001 }
1002
1003 /* FIFO state control */
1004 static void fdctrl_reset_fifo(FDCtrl *fdctrl)
1005 {
1006     fdctrl->data_dir = FD_DIR_WRITE;
1007     fdctrl->data_pos = 0;
1008     fdctrl->msr &= ~(FD_MSR_CMDBUSY | FD_MSR_DIO);
1009 }
1010
1011 /* Set FIFO status for the host to read */
1012 static void fdctrl_set_fifo(FDCtrl *fdctrl, int fifo_len, int do_irq)
1013 {
1014     fdctrl->data_dir = FD_DIR_READ;
1015     fdctrl->data_len = fifo_len;
1016     fdctrl->data_pos = 0;
1017     fdctrl->msr |= FD_MSR_CMDBUSY | FD_MSR_RQM | FD_MSR_DIO;
1018     if (do_irq)
1019         fdctrl_raise_irq(fdctrl, 0x00);
1020 }
1021
1022 /* Set an error: unimplemented/unknown command */
1023 static void fdctrl_unimplemented(FDCtrl *fdctrl, int direction)
1024 {
1025     FLOPPY_ERROR("unimplemented command 0x%02x\n", fdctrl->fifo[0]);
1026     fdctrl->fifo[0] = FD_SR0_INVCMD;
1027     fdctrl_set_fifo(fdctrl, 1, 0);
1028 }
1029
1030 /* Seek to next sector */
1031 static int fdctrl_seek_to_next_sect(FDCtrl *fdctrl, FDrive *cur_drv)
1032 {
1033     FLOPPY_DPRINTF("seek to next sector (%d %02x %02x => %d)\n",
1034                    cur_drv->head, cur_drv->track, cur_drv->sect,
1035                    fd_sector(cur_drv));
1036     /* XXX: cur_drv->sect >= cur_drv->last_sect should be an
1037        error in fact */
1038     if (cur_drv->sect >= cur_drv->last_sect ||
1039         cur_drv->sect == fdctrl->eot) {
1040         cur_drv->sect = 1;
1041         if (FD_MULTI_TRACK(fdctrl->data_state)) {
1042             if (cur_drv->head == 0 &&
1043                 (cur_drv->flags & FDISK_DBL_SIDES) != 0) {
1044                 cur_drv->head = 1;
1045             } else {
1046                 cur_drv->head = 0;
1047                 cur_drv->track++;
1048                 if ((cur_drv->flags & FDISK_DBL_SIDES) == 0)
1049                     return 0;
1050             }
1051         } else {
1052             cur_drv->track++;
1053             return 0;
1054         }
1055         FLOPPY_DPRINTF("seek to next track (%d %02x %02x => %d)\n",
1056                        cur_drv->head, cur_drv->track,
1057                        cur_drv->sect, fd_sector(cur_drv));
1058     } else {
1059         cur_drv->sect++;
1060     }
1061     return 1;
1062 }
1063
1064 /* Callback for transfer end (stop or abort) */
1065 static void fdctrl_stop_transfer(FDCtrl *fdctrl, uint8_t status0,
1066                                  uint8_t status1, uint8_t status2)
1067 {
1068     FDrive *cur_drv;
1069
1070     cur_drv = get_cur_drv(fdctrl);
1071     FLOPPY_DPRINTF("transfer status: %02x %02x %02x (%02x)\n",
1072                    status0, status1, status2,
1073                    status0 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl));
1074     fdctrl->fifo[0] = status0 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
1075     fdctrl->fifo[1] = status1;
1076     fdctrl->fifo[2] = status2;
1077     fdctrl->fifo[3] = cur_drv->track;
1078     fdctrl->fifo[4] = cur_drv->head;
1079     fdctrl->fifo[5] = cur_drv->sect;
1080     fdctrl->fifo[6] = FD_SECTOR_SC;
1081     fdctrl->data_dir = FD_DIR_READ;
1082     if (!(fdctrl->msr & FD_MSR_NONDMA)) {
1083         DMA_release_DREQ(fdctrl->dma_chann);
1084     }
1085     fdctrl->msr |= FD_MSR_RQM | FD_MSR_DIO;
1086     fdctrl->msr &= ~FD_MSR_NONDMA;
1087     fdctrl_set_fifo(fdctrl, 7, 1);
1088 }
1089
1090 /* Prepare a data transfer (either DMA or FIFO) */
1091 static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)
1092 {
1093     FDrive *cur_drv;
1094     uint8_t kh, kt, ks;
1095     int did_seek = 0;
1096
1097     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1098     cur_drv = get_cur_drv(fdctrl);
1099     kt = fdctrl->fifo[2];
1100     kh = fdctrl->fifo[3];
1101     ks = fdctrl->fifo[4];
1102     FLOPPY_DPRINTF("Start transfer at %d %d %02x %02x (%d)\n",
1103                    GET_CUR_DRV(fdctrl), kh, kt, ks,
1104                    fd_sector_calc(kh, kt, ks, cur_drv->last_sect));
1105     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
1106     case 2:
1107         /* sect too big */
1108         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1109         fdctrl->fifo[3] = kt;
1110         fdctrl->fifo[4] = kh;
1111         fdctrl->fifo[5] = ks;
1112         return;
1113     case 3:
1114         /* track too big */
1115         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
1116         fdctrl->fifo[3] = kt;
1117         fdctrl->fifo[4] = kh;
1118         fdctrl->fifo[5] = ks;
1119         return;
1120     case 4:
1121         /* No seek enabled */
1122         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1123         fdctrl->fifo[3] = kt;
1124         fdctrl->fifo[4] = kh;
1125         fdctrl->fifo[5] = ks;
1126         return;
1127     case 1:
1128         did_seek = 1;
1129         break;
1130     default:
1131         break;
1132     }
1133
1134     /* Set the FIFO state */
1135     fdctrl->data_dir = direction;
1136     fdctrl->data_pos = 0;
1137     fdctrl->msr |= FD_MSR_CMDBUSY;
1138     if (fdctrl->fifo[0] & 0x80)
1139         fdctrl->data_state |= FD_STATE_MULTI;
1140     else
1141         fdctrl->data_state &= ~FD_STATE_MULTI;
1142     if (did_seek)
1143         fdctrl->data_state |= FD_STATE_SEEK;
1144     else
1145         fdctrl->data_state &= ~FD_STATE_SEEK;
1146     if (fdctrl->fifo[5] == 00) {
1147         fdctrl->data_len = fdctrl->fifo[8];
1148     } else {
1149         int tmp;
1150         fdctrl->data_len = 128 << (fdctrl->fifo[5] > 7 ? 7 : fdctrl->fifo[5]);
1151         tmp = (fdctrl->fifo[6] - ks + 1);
1152         if (fdctrl->fifo[0] & 0x80)
1153             tmp += fdctrl->fifo[6];
1154         fdctrl->data_len *= tmp;
1155     }
1156     fdctrl->eot = fdctrl->fifo[6];
1157     if (fdctrl->dor & FD_DOR_DMAEN) {
1158         int dma_mode;
1159         /* DMA transfer are enabled. Check if DMA channel is well programmed */
1160         dma_mode = DMA_get_channel_mode(fdctrl->dma_chann);
1161         dma_mode = (dma_mode >> 2) & 3;
1162         FLOPPY_DPRINTF("dma_mode=%d direction=%d (%d - %d)\n",
1163                        dma_mode, direction,
1164                        (128 << fdctrl->fifo[5]) *
1165                        (cur_drv->last_sect - ks + 1), fdctrl->data_len);
1166         if (((direction == FD_DIR_SCANE || direction == FD_DIR_SCANL ||
1167               direction == FD_DIR_SCANH) && dma_mode == 0) ||
1168             (direction == FD_DIR_WRITE && dma_mode == 2) ||
1169             (direction == FD_DIR_READ && dma_mode == 1)) {
1170             /* No access is allowed until DMA transfer has completed */
1171             fdctrl->msr &= ~FD_MSR_RQM;
1172             /* Now, we just have to wait for the DMA controller to
1173              * recall us...
1174              */
1175             DMA_hold_DREQ(fdctrl->dma_chann);
1176             DMA_schedule(fdctrl->dma_chann);
1177             return;
1178         } else {
1179             FLOPPY_ERROR("dma_mode=%d direction=%d\n", dma_mode, direction);
1180         }
1181     }
1182     FLOPPY_DPRINTF("start non-DMA transfer\n");
1183     fdctrl->msr |= FD_MSR_NONDMA;
1184     if (direction != FD_DIR_WRITE)
1185         fdctrl->msr |= FD_MSR_DIO;
1186     /* IO based transfer: calculate len */
1187     fdctrl_raise_irq(fdctrl, 0x00);
1188
1189     return;
1190 }
1191
1192 /* Prepare a transfer of deleted data */
1193 static void fdctrl_start_transfer_del(FDCtrl *fdctrl, int direction)
1194 {
1195     FLOPPY_ERROR("fdctrl_start_transfer_del() unimplemented\n");
1196
1197     /* We don't handle deleted data,
1198      * so we don't return *ANYTHING*
1199      */
1200     fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1201 }
1202
1203 /* handlers for DMA transfers */
1204 static int fdctrl_transfer_handler (void *opaque, int nchan,
1205                                     int dma_pos, int dma_len)
1206 {
1207     FDCtrl *fdctrl;
1208     FDrive *cur_drv;
1209     int len, start_pos, rel_pos;
1210     uint8_t status0 = 0x00, status1 = 0x00, status2 = 0x00;
1211
1212     fdctrl = opaque;
1213     if (fdctrl->msr & FD_MSR_RQM) {
1214         FLOPPY_DPRINTF("Not in DMA transfer mode !\n");
1215         return 0;
1216     }
1217     cur_drv = get_cur_drv(fdctrl);
1218     if (fdctrl->data_dir == FD_DIR_SCANE || fdctrl->data_dir == FD_DIR_SCANL ||
1219         fdctrl->data_dir == FD_DIR_SCANH)
1220         status2 = FD_SR2_SNS;
1221     if (dma_len > fdctrl->data_len)
1222         dma_len = fdctrl->data_len;
1223     if (cur_drv->bs == NULL) {
1224         if (fdctrl->data_dir == FD_DIR_WRITE)
1225             fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1226         else
1227             fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1228         len = 0;
1229         goto transfer_error;
1230     }
1231     rel_pos = fdctrl->data_pos % FD_SECTOR_LEN;
1232     for (start_pos = fdctrl->data_pos; fdctrl->data_pos < dma_len;) {
1233         len = dma_len - fdctrl->data_pos;
1234         if (len + rel_pos > FD_SECTOR_LEN)
1235             len = FD_SECTOR_LEN - rel_pos;
1236         FLOPPY_DPRINTF("copy %d bytes (%d %d %d) %d pos %d %02x "
1237                        "(%d-0x%08x 0x%08x)\n", len, dma_len, fdctrl->data_pos,
1238                        fdctrl->data_len, GET_CUR_DRV(fdctrl), cur_drv->head,
1239                        cur_drv->track, cur_drv->sect, fd_sector(cur_drv),
1240                        fd_sector(cur_drv) * FD_SECTOR_LEN);
1241         if (fdctrl->data_dir != FD_DIR_WRITE ||
1242             len < FD_SECTOR_LEN || rel_pos != 0) {
1243             /* READ & SCAN commands and realign to a sector for WRITE */
1244             if (bdrv_read(cur_drv->bs, fd_sector(cur_drv),
1245                           fdctrl->fifo, 1) < 0) {
1246                 FLOPPY_DPRINTF("Floppy: error getting sector %d\n",
1247                                fd_sector(cur_drv));
1248                 /* Sure, image size is too small... */
1249                 memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1250             }
1251         }
1252         switch (fdctrl->data_dir) {
1253         case FD_DIR_READ:
1254             /* READ commands */
1255             DMA_write_memory (nchan, fdctrl->fifo + rel_pos,
1256                               fdctrl->data_pos, len);
1257             break;
1258         case FD_DIR_WRITE:
1259             /* WRITE commands */
1260             DMA_read_memory (nchan, fdctrl->fifo + rel_pos,
1261                              fdctrl->data_pos, len);
1262             if (bdrv_write(cur_drv->bs, fd_sector(cur_drv),
1263                            fdctrl->fifo, 1) < 0) {
1264                 FLOPPY_ERROR("writing sector %d\n", fd_sector(cur_drv));
1265                 fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1266                 goto transfer_error;
1267             }
1268             break;
1269         default:
1270             /* SCAN commands */
1271             {
1272                 uint8_t tmpbuf[FD_SECTOR_LEN];
1273                 int ret;
1274                 DMA_read_memory (nchan, tmpbuf, fdctrl->data_pos, len);
1275                 ret = memcmp(tmpbuf, fdctrl->fifo + rel_pos, len);
1276                 if (ret == 0) {
1277                     status2 = FD_SR2_SEH;
1278                     goto end_transfer;
1279                 }
1280                 if ((ret < 0 && fdctrl->data_dir == FD_DIR_SCANL) ||
1281                     (ret > 0 && fdctrl->data_dir == FD_DIR_SCANH)) {
1282                     status2 = 0x00;
1283                     goto end_transfer;
1284                 }
1285             }
1286             break;
1287         }
1288         fdctrl->data_pos += len;
1289         rel_pos = fdctrl->data_pos % FD_SECTOR_LEN;
1290         if (rel_pos == 0) {
1291             /* Seek to next sector */
1292             if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv))
1293                 break;
1294         }
1295     }
1296  end_transfer:
1297     len = fdctrl->data_pos - start_pos;
1298     FLOPPY_DPRINTF("end transfer %d %d %d\n",
1299                    fdctrl->data_pos, len, fdctrl->data_len);
1300     if (fdctrl->data_dir == FD_DIR_SCANE ||
1301         fdctrl->data_dir == FD_DIR_SCANL ||
1302         fdctrl->data_dir == FD_DIR_SCANH)
1303         status2 = FD_SR2_SEH;
1304     if (FD_DID_SEEK(fdctrl->data_state))
1305         status0 |= FD_SR0_SEEK;
1306     fdctrl->data_len -= len;
1307     fdctrl_stop_transfer(fdctrl, status0, status1, status2);
1308  transfer_error:
1309
1310     return len;
1311 }
1312
1313 /* Data register : 0x05 */
1314 static uint32_t fdctrl_read_data(FDCtrl *fdctrl)
1315 {
1316     FDrive *cur_drv;
1317     uint32_t retval = 0;
1318     int pos;
1319
1320     cur_drv = get_cur_drv(fdctrl);
1321     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
1322     if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) {
1323         FLOPPY_ERROR("controller not ready for reading\n");
1324         return 0;
1325     }
1326     pos = fdctrl->data_pos;
1327     if (fdctrl->msr & FD_MSR_NONDMA) {
1328         pos %= FD_SECTOR_LEN;
1329         if (pos == 0) {
1330             if (fdctrl->data_pos != 0)
1331                 if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {
1332                     FLOPPY_DPRINTF("error seeking to next sector %d\n",
1333                                    fd_sector(cur_drv));
1334                     return 0;
1335                 }
1336             if (bdrv_read(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) {
1337                 FLOPPY_DPRINTF("error getting sector %d\n",
1338                                fd_sector(cur_drv));
1339                 /* Sure, image size is too small... */
1340                 memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1341             }
1342         }
1343     }
1344     retval = fdctrl->fifo[pos];
1345     if (++fdctrl->data_pos == fdctrl->data_len) {
1346         fdctrl->data_pos = 0;
1347         /* Switch from transfer mode to status mode
1348          * then from status mode to command mode
1349          */
1350         if (fdctrl->msr & FD_MSR_NONDMA) {
1351             fdctrl_stop_transfer(fdctrl, FD_SR0_SEEK, 0x00, 0x00);
1352         } else {
1353             fdctrl_reset_fifo(fdctrl);
1354             fdctrl_reset_irq(fdctrl);
1355         }
1356     }
1357     FLOPPY_DPRINTF("data register: 0x%02x\n", retval);
1358
1359     return retval;
1360 }
1361
1362 static void fdctrl_format_sector(FDCtrl *fdctrl)
1363 {
1364     FDrive *cur_drv;
1365     uint8_t kh, kt, ks;
1366
1367     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1368     cur_drv = get_cur_drv(fdctrl);
1369     kt = fdctrl->fifo[6];
1370     kh = fdctrl->fifo[7];
1371     ks = fdctrl->fifo[8];
1372     FLOPPY_DPRINTF("format sector at %d %d %02x %02x (%d)\n",
1373                    GET_CUR_DRV(fdctrl), kh, kt, ks,
1374                    fd_sector_calc(kh, kt, ks, cur_drv->last_sect));
1375     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
1376     case 2:
1377         /* sect too big */
1378         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1379         fdctrl->fifo[3] = kt;
1380         fdctrl->fifo[4] = kh;
1381         fdctrl->fifo[5] = ks;
1382         return;
1383     case 3:
1384         /* track too big */
1385         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
1386         fdctrl->fifo[3] = kt;
1387         fdctrl->fifo[4] = kh;
1388         fdctrl->fifo[5] = ks;
1389         return;
1390     case 4:
1391         /* No seek enabled */
1392         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
1393         fdctrl->fifo[3] = kt;
1394         fdctrl->fifo[4] = kh;
1395         fdctrl->fifo[5] = ks;
1396         return;
1397     case 1:
1398         fdctrl->data_state |= FD_STATE_SEEK;
1399         break;
1400     default:
1401         break;
1402     }
1403     memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
1404     if (cur_drv->bs == NULL ||
1405         bdrv_write(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) {
1406         FLOPPY_ERROR("formatting sector %d\n", fd_sector(cur_drv));
1407         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK, 0x00, 0x00);
1408     } else {
1409         if (cur_drv->sect == cur_drv->last_sect) {
1410             fdctrl->data_state &= ~FD_STATE_FORMAT;
1411             /* Last sector done */
1412             if (FD_DID_SEEK(fdctrl->data_state))
1413                 fdctrl_stop_transfer(fdctrl, FD_SR0_SEEK, 0x00, 0x00);
1414             else
1415                 fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1416         } else {
1417             /* More to do */
1418             fdctrl->data_pos = 0;
1419             fdctrl->data_len = 4;
1420         }
1421     }
1422 }
1423
1424 static void fdctrl_handle_lock(FDCtrl *fdctrl, int direction)
1425 {
1426     fdctrl->lock = (fdctrl->fifo[0] & 0x80) ? 1 : 0;
1427     fdctrl->fifo[0] = fdctrl->lock << 4;
1428     fdctrl_set_fifo(fdctrl, 1, fdctrl->lock);
1429 }
1430
1431 static void fdctrl_handle_dumpreg(FDCtrl *fdctrl, int direction)
1432 {
1433     FDrive *cur_drv = get_cur_drv(fdctrl);
1434
1435     /* Drives position */
1436     fdctrl->fifo[0] = drv0(fdctrl)->track;
1437     fdctrl->fifo[1] = drv1(fdctrl)->track;
1438 #if MAX_FD == 4
1439     fdctrl->fifo[2] = drv2(fdctrl)->track;
1440     fdctrl->fifo[3] = drv3(fdctrl)->track;
1441 #else
1442     fdctrl->fifo[2] = 0;
1443     fdctrl->fifo[3] = 0;
1444 #endif
1445     /* timers */
1446     fdctrl->fifo[4] = fdctrl->timer0;
1447     fdctrl->fifo[5] = (fdctrl->timer1 << 1) | (fdctrl->dor & FD_DOR_DMAEN ? 1 : 0);
1448     fdctrl->fifo[6] = cur_drv->last_sect;
1449     fdctrl->fifo[7] = (fdctrl->lock << 7) |
1450         (cur_drv->perpendicular << 2);
1451     fdctrl->fifo[8] = fdctrl->config;
1452     fdctrl->fifo[9] = fdctrl->precomp_trk;
1453     fdctrl_set_fifo(fdctrl, 10, 0);
1454 }
1455
1456 static void fdctrl_handle_version(FDCtrl *fdctrl, int direction)
1457 {
1458     /* Controller's version */
1459     fdctrl->fifo[0] = fdctrl->version;
1460     fdctrl_set_fifo(fdctrl, 1, 1);
1461 }
1462
1463 static void fdctrl_handle_partid(FDCtrl *fdctrl, int direction)
1464 {
1465     fdctrl->fifo[0] = 0x41; /* Stepping 1 */
1466     fdctrl_set_fifo(fdctrl, 1, 0);
1467 }
1468
1469 static void fdctrl_handle_restore(FDCtrl *fdctrl, int direction)
1470 {
1471     FDrive *cur_drv = get_cur_drv(fdctrl);
1472
1473     /* Drives position */
1474     drv0(fdctrl)->track = fdctrl->fifo[3];
1475     drv1(fdctrl)->track = fdctrl->fifo[4];
1476 #if MAX_FD == 4
1477     drv2(fdctrl)->track = fdctrl->fifo[5];
1478     drv3(fdctrl)->track = fdctrl->fifo[6];
1479 #endif
1480     /* timers */
1481     fdctrl->timer0 = fdctrl->fifo[7];
1482     fdctrl->timer1 = fdctrl->fifo[8];
1483     cur_drv->last_sect = fdctrl->fifo[9];
1484     fdctrl->lock = fdctrl->fifo[10] >> 7;
1485     cur_drv->perpendicular = (fdctrl->fifo[10] >> 2) & 0xF;
1486     fdctrl->config = fdctrl->fifo[11];
1487     fdctrl->precomp_trk = fdctrl->fifo[12];
1488     fdctrl->pwrd = fdctrl->fifo[13];
1489     fdctrl_reset_fifo(fdctrl);
1490 }
1491
1492 static void fdctrl_handle_save(FDCtrl *fdctrl, int direction)
1493 {
1494     FDrive *cur_drv = get_cur_drv(fdctrl);
1495
1496     fdctrl->fifo[0] = 0;
1497     fdctrl->fifo[1] = 0;
1498     /* Drives position */
1499     fdctrl->fifo[2] = drv0(fdctrl)->track;
1500     fdctrl->fifo[3] = drv1(fdctrl)->track;
1501 #if MAX_FD == 4
1502     fdctrl->fifo[4] = drv2(fdctrl)->track;
1503     fdctrl->fifo[5] = drv3(fdctrl)->track;
1504 #else
1505     fdctrl->fifo[4] = 0;
1506     fdctrl->fifo[5] = 0;
1507 #endif
1508     /* timers */
1509     fdctrl->fifo[6] = fdctrl->timer0;
1510     fdctrl->fifo[7] = fdctrl->timer1;
1511     fdctrl->fifo[8] = cur_drv->last_sect;
1512     fdctrl->fifo[9] = (fdctrl->lock << 7) |
1513         (cur_drv->perpendicular << 2);
1514     fdctrl->fifo[10] = fdctrl->config;
1515     fdctrl->fifo[11] = fdctrl->precomp_trk;
1516     fdctrl->fifo[12] = fdctrl->pwrd;
1517     fdctrl->fifo[13] = 0;
1518     fdctrl->fifo[14] = 0;
1519     fdctrl_set_fifo(fdctrl, 15, 1);
1520 }
1521
1522 static void fdctrl_handle_readid(FDCtrl *fdctrl, int direction)
1523 {
1524     FDrive *cur_drv = get_cur_drv(fdctrl);
1525
1526     /* XXX: should set main status register to busy */
1527     cur_drv->head = (fdctrl->fifo[1] >> 2) & 1;
1528     qemu_mod_timer(fdctrl->result_timer,
1529                    qemu_get_clock(vm_clock) + (get_ticks_per_sec() / 50));
1530 }
1531
1532 static void fdctrl_handle_format_track(FDCtrl *fdctrl, int direction)
1533 {
1534     FDrive *cur_drv;
1535
1536     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1537     cur_drv = get_cur_drv(fdctrl);
1538     fdctrl->data_state |= FD_STATE_FORMAT;
1539     if (fdctrl->fifo[0] & 0x80)
1540         fdctrl->data_state |= FD_STATE_MULTI;
1541     else
1542         fdctrl->data_state &= ~FD_STATE_MULTI;
1543     fdctrl->data_state &= ~FD_STATE_SEEK;
1544     cur_drv->bps =
1545         fdctrl->fifo[2] > 7 ? 16384 : 128 << fdctrl->fifo[2];
1546 #if 0
1547     cur_drv->last_sect =
1548         cur_drv->flags & FDISK_DBL_SIDES ? fdctrl->fifo[3] :
1549         fdctrl->fifo[3] / 2;
1550 #else
1551     cur_drv->last_sect = fdctrl->fifo[3];
1552 #endif
1553     /* TODO: implement format using DMA expected by the Bochs BIOS
1554      * and Linux fdformat (read 3 bytes per sector via DMA and fill
1555      * the sector with the specified fill byte
1556      */
1557     fdctrl->data_state &= ~FD_STATE_FORMAT;
1558     fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1559 }
1560
1561 static void fdctrl_handle_specify(FDCtrl *fdctrl, int direction)
1562 {
1563     fdctrl->timer0 = (fdctrl->fifo[1] >> 4) & 0xF;
1564     fdctrl->timer1 = fdctrl->fifo[2] >> 1;
1565     if (fdctrl->fifo[2] & 1)
1566         fdctrl->dor &= ~FD_DOR_DMAEN;
1567     else
1568         fdctrl->dor |= FD_DOR_DMAEN;
1569     /* No result back */
1570     fdctrl_reset_fifo(fdctrl);
1571 }
1572
1573 static void fdctrl_handle_sense_drive_status(FDCtrl *fdctrl, int direction)
1574 {
1575     FDrive *cur_drv;
1576
1577     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1578     cur_drv = get_cur_drv(fdctrl);
1579     cur_drv->head = (fdctrl->fifo[1] >> 2) & 1;
1580     /* 1 Byte status back */
1581     fdctrl->fifo[0] = (cur_drv->ro << 6) |
1582         (cur_drv->track == 0 ? 0x10 : 0x00) |
1583         (cur_drv->head << 2) |
1584         GET_CUR_DRV(fdctrl) |
1585         0x28;
1586     fdctrl_set_fifo(fdctrl, 1, 0);
1587 }
1588
1589 static void fdctrl_handle_recalibrate(FDCtrl *fdctrl, int direction)
1590 {
1591     FDrive *cur_drv;
1592
1593     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1594     cur_drv = get_cur_drv(fdctrl);
1595     fd_recalibrate(cur_drv);
1596     fdctrl_reset_fifo(fdctrl);
1597     /* Raise Interrupt */
1598     fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
1599 }
1600
1601 static void fdctrl_handle_sense_interrupt_status(FDCtrl *fdctrl, int direction)
1602 {
1603     FDrive *cur_drv = get_cur_drv(fdctrl);
1604
1605     if(fdctrl->reset_sensei > 0) {
1606         fdctrl->fifo[0] =
1607             FD_SR0_RDYCHG + FD_RESET_SENSEI_COUNT - fdctrl->reset_sensei;
1608         fdctrl->reset_sensei--;
1609     } else {
1610         /* XXX: status0 handling is broken for read/write
1611            commands, so we do this hack. It should be suppressed
1612            ASAP */
1613         fdctrl->fifo[0] =
1614             FD_SR0_SEEK | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
1615     }
1616
1617     fdctrl->fifo[1] = cur_drv->track;
1618     fdctrl_set_fifo(fdctrl, 2, 0);
1619     fdctrl_reset_irq(fdctrl);
1620     fdctrl->status0 = FD_SR0_RDYCHG;
1621 }
1622
1623 static void fdctrl_handle_seek(FDCtrl *fdctrl, int direction)
1624 {
1625     FDrive *cur_drv;
1626
1627     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1628     cur_drv = get_cur_drv(fdctrl);
1629     fdctrl_reset_fifo(fdctrl);
1630     if (fdctrl->fifo[2] > cur_drv->max_track) {
1631         fdctrl_raise_irq(fdctrl, FD_SR0_ABNTERM | FD_SR0_SEEK);
1632     } else {
1633         cur_drv->track = fdctrl->fifo[2];
1634         /* Raise Interrupt */
1635         fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
1636     }
1637 }
1638
1639 static void fdctrl_handle_perpendicular_mode(FDCtrl *fdctrl, int direction)
1640 {
1641     FDrive *cur_drv = get_cur_drv(fdctrl);
1642
1643     if (fdctrl->fifo[1] & 0x80)
1644         cur_drv->perpendicular = fdctrl->fifo[1] & 0x7;
1645     /* No result back */
1646     fdctrl_reset_fifo(fdctrl);
1647 }
1648
1649 static void fdctrl_handle_configure(FDCtrl *fdctrl, int direction)
1650 {
1651     fdctrl->config = fdctrl->fifo[2];
1652     fdctrl->precomp_trk =  fdctrl->fifo[3];
1653     /* No result back */
1654     fdctrl_reset_fifo(fdctrl);
1655 }
1656
1657 static void fdctrl_handle_powerdown_mode(FDCtrl *fdctrl, int direction)
1658 {
1659     fdctrl->pwrd = fdctrl->fifo[1];
1660     fdctrl->fifo[0] = fdctrl->fifo[1];
1661     fdctrl_set_fifo(fdctrl, 1, 1);
1662 }
1663
1664 static void fdctrl_handle_option(FDCtrl *fdctrl, int direction)
1665 {
1666     /* No result back */
1667     fdctrl_reset_fifo(fdctrl);
1668 }
1669
1670 static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction)
1671 {
1672     FDrive *cur_drv = get_cur_drv(fdctrl);
1673
1674     if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) {
1675         /* Command parameters done */
1676         if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) {
1677             fdctrl->fifo[0] = fdctrl->fifo[1];
1678             fdctrl->fifo[2] = 0;
1679             fdctrl->fifo[3] = 0;
1680             fdctrl_set_fifo(fdctrl, 4, 1);
1681         } else {
1682             fdctrl_reset_fifo(fdctrl);
1683         }
1684     } else if (fdctrl->data_len > 7) {
1685         /* ERROR */
1686         fdctrl->fifo[0] = 0x80 |
1687             (cur_drv->head << 2) | GET_CUR_DRV(fdctrl);
1688         fdctrl_set_fifo(fdctrl, 1, 1);
1689     }
1690 }
1691
1692 static void fdctrl_handle_relative_seek_out(FDCtrl *fdctrl, int direction)
1693 {
1694     FDrive *cur_drv;
1695
1696     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1697     cur_drv = get_cur_drv(fdctrl);
1698     if (fdctrl->fifo[2] + cur_drv->track >= cur_drv->max_track) {
1699         cur_drv->track = cur_drv->max_track - 1;
1700     } else {
1701         cur_drv->track += fdctrl->fifo[2];
1702     }
1703     fdctrl_reset_fifo(fdctrl);
1704     /* Raise Interrupt */
1705     fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
1706 }
1707
1708 static void fdctrl_handle_relative_seek_in(FDCtrl *fdctrl, int direction)
1709 {
1710     FDrive *cur_drv;
1711
1712     SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
1713     cur_drv = get_cur_drv(fdctrl);
1714     if (fdctrl->fifo[2] > cur_drv->track) {
1715         cur_drv->track = 0;
1716     } else {
1717         cur_drv->track -= fdctrl->fifo[2];
1718     }
1719     fdctrl_reset_fifo(fdctrl);
1720     /* Raise Interrupt */
1721     fdctrl_raise_irq(fdctrl, FD_SR0_SEEK);
1722 }
1723
1724 static const struct {
1725     uint8_t value;
1726     uint8_t mask;
1727     const char* name;
1728     int parameters;
1729     void (*handler)(FDCtrl *fdctrl, int direction);
1730     int direction;
1731 } handlers[] = {
1732     { FD_CMD_READ, 0x1f, "READ", 8, fdctrl_start_transfer, FD_DIR_READ },
1733     { FD_CMD_WRITE, 0x3f, "WRITE", 8, fdctrl_start_transfer, FD_DIR_WRITE },
1734     { FD_CMD_SEEK, 0xff, "SEEK", 2, fdctrl_handle_seek },
1735     { FD_CMD_SENSE_INTERRUPT_STATUS, 0xff, "SENSE INTERRUPT STATUS", 0, fdctrl_handle_sense_interrupt_status },
1736     { FD_CMD_RECALIBRATE, 0xff, "RECALIBRATE", 1, fdctrl_handle_recalibrate },
1737     { FD_CMD_FORMAT_TRACK, 0xbf, "FORMAT TRACK", 5, fdctrl_handle_format_track },
1738     { FD_CMD_READ_TRACK, 0xbf, "READ TRACK", 8, fdctrl_start_transfer, FD_DIR_READ },
1739     { FD_CMD_RESTORE, 0xff, "RESTORE", 17, fdctrl_handle_restore }, /* part of READ DELETED DATA */
1740     { FD_CMD_SAVE, 0xff, "SAVE", 0, fdctrl_handle_save }, /* part of READ DELETED DATA */
1741     { FD_CMD_READ_DELETED, 0x1f, "READ DELETED DATA", 8, fdctrl_start_transfer_del, FD_DIR_READ },
1742     { FD_CMD_SCAN_EQUAL, 0x1f, "SCAN EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANE },
1743     { FD_CMD_VERIFY, 0x1f, "VERIFY", 8, fdctrl_unimplemented },
1744     { FD_CMD_SCAN_LOW_OR_EQUAL, 0x1f, "SCAN LOW OR EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANL },
1745     { FD_CMD_SCAN_HIGH_OR_EQUAL, 0x1f, "SCAN HIGH OR EQUAL", 8, fdctrl_start_transfer, FD_DIR_SCANH },
1746     { FD_CMD_WRITE_DELETED, 0x3f, "WRITE DELETED DATA", 8, fdctrl_start_transfer_del, FD_DIR_WRITE },
1747     { FD_CMD_READ_ID, 0xbf, "READ ID", 1, fdctrl_handle_readid },
1748     { FD_CMD_SPECIFY, 0xff, "SPECIFY", 2, fdctrl_handle_specify },
1749     { FD_CMD_SENSE_DRIVE_STATUS, 0xff, "SENSE DRIVE STATUS", 1, fdctrl_handle_sense_drive_status },
1750     { FD_CMD_PERPENDICULAR_MODE, 0xff, "PERPENDICULAR MODE", 1, fdctrl_handle_perpendicular_mode },
1751     { FD_CMD_CONFIGURE, 0xff, "CONFIGURE", 3, fdctrl_handle_configure },
1752     { FD_CMD_POWERDOWN_MODE, 0xff, "POWERDOWN MODE", 2, fdctrl_handle_powerdown_mode },
1753     { FD_CMD_OPTION, 0xff, "OPTION", 1, fdctrl_handle_option },
1754     { FD_CMD_DRIVE_SPECIFICATION_COMMAND, 0xff, "DRIVE SPECIFICATION COMMAND", 5, fdctrl_handle_drive_specification_command },
1755     { FD_CMD_RELATIVE_SEEK_OUT, 0xff, "RELATIVE SEEK OUT", 2, fdctrl_handle_relative_seek_out },
1756     { FD_CMD_FORMAT_AND_WRITE, 0xff, "FORMAT AND WRITE", 10, fdctrl_unimplemented },
1757     { FD_CMD_RELATIVE_SEEK_IN, 0xff, "RELATIVE SEEK IN", 2, fdctrl_handle_relative_seek_in },
1758     { FD_CMD_LOCK, 0x7f, "LOCK", 0, fdctrl_handle_lock },
1759     { FD_CMD_DUMPREG, 0xff, "DUMPREG", 0, fdctrl_handle_dumpreg },
1760     { FD_CMD_VERSION, 0xff, "VERSION", 0, fdctrl_handle_version },
1761     { FD_CMD_PART_ID, 0xff, "PART ID", 0, fdctrl_handle_partid },
1762     { FD_CMD_WRITE, 0x1f, "WRITE (BeOS)", 8, fdctrl_start_transfer, FD_DIR_WRITE }, /* not in specification ; BeOS 4.5 bug */
1763     { 0, 0, "unknown", 0, fdctrl_unimplemented }, /* default handler */
1764 };
1765 /* Associate command to an index in the 'handlers' array */
1766 static uint8_t command_to_handler[256];
1767
1768 static void fdctrl_write_data(FDCtrl *fdctrl, uint32_t value)
1769 {
1770     FDrive *cur_drv;
1771     int pos;
1772
1773     /* Reset mode */
1774     if (!(fdctrl->dor & FD_DOR_nRESET)) {
1775         FLOPPY_DPRINTF("Floppy controller in RESET state !\n");
1776         return;
1777     }
1778     if (!(fdctrl->msr & FD_MSR_RQM) || (fdctrl->msr & FD_MSR_DIO)) {
1779         FLOPPY_ERROR("controller not ready for writing\n");
1780         return;
1781     }
1782     fdctrl->dsr &= ~FD_DSR_PWRDOWN;
1783     /* Is it write command time ? */
1784     if (fdctrl->msr & FD_MSR_NONDMA) {
1785         /* FIFO data write */
1786         pos = fdctrl->data_pos++;
1787         pos %= FD_SECTOR_LEN;
1788         fdctrl->fifo[pos] = value;
1789         if (pos == FD_SECTOR_LEN - 1 ||
1790             fdctrl->data_pos == fdctrl->data_len) {
1791             cur_drv = get_cur_drv(fdctrl);
1792             if (bdrv_write(cur_drv->bs, fd_sector(cur_drv), fdctrl->fifo, 1) < 0) {
1793                 FLOPPY_ERROR("writing sector %d\n", fd_sector(cur_drv));
1794                 return;
1795             }
1796             if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {
1797                 FLOPPY_DPRINTF("error seeking to next sector %d\n",
1798                                fd_sector(cur_drv));
1799                 return;
1800             }
1801         }
1802         /* Switch from transfer mode to status mode
1803          * then from status mode to command mode
1804          */
1805         if (fdctrl->data_pos == fdctrl->data_len)
1806             fdctrl_stop_transfer(fdctrl, FD_SR0_SEEK, 0x00, 0x00);
1807         return;
1808     }
1809     if (fdctrl->data_pos == 0) {
1810         /* Command */
1811         pos = command_to_handler[value & 0xff];
1812         FLOPPY_DPRINTF("%s command\n", handlers[pos].name);
1813         fdctrl->data_len = handlers[pos].parameters + 1;
1814     }
1815
1816     FLOPPY_DPRINTF("%s: %02x\n", __func__, value);
1817     fdctrl->fifo[fdctrl->data_pos++] = value;
1818     if (fdctrl->data_pos == fdctrl->data_len) {
1819         /* We now have all parameters
1820          * and will be able to treat the command
1821          */
1822         if (fdctrl->data_state & FD_STATE_FORMAT) {
1823             fdctrl_format_sector(fdctrl);
1824             return;
1825         }
1826
1827         pos = command_to_handler[fdctrl->fifo[0] & 0xff];
1828         FLOPPY_DPRINTF("treat %s command\n", handlers[pos].name);
1829         (*handlers[pos].handler)(fdctrl, handlers[pos].direction);
1830     }
1831 }
1832
1833 static void fdctrl_result_timer(void *opaque)
1834 {
1835     FDCtrl *fdctrl = opaque;
1836     FDrive *cur_drv = get_cur_drv(fdctrl);
1837
1838     /* Pretend we are spinning.
1839      * This is needed for Coherent, which uses READ ID to check for
1840      * sector interleaving.
1841      */
1842     if (cur_drv->last_sect != 0) {
1843         cur_drv->sect = (cur_drv->sect % cur_drv->last_sect) + 1;
1844     }
1845     fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
1846 }
1847
1848 /* Init functions */
1849 static int fdctrl_connect_drives(FDCtrl *fdctrl)
1850 {
1851     unsigned int i;
1852     FDrive *drive;
1853
1854     for (i = 0; i < MAX_FD; i++) {
1855         drive = &fdctrl->drives[i];
1856
1857         if (drive->bs) {
1858             if (bdrv_get_on_error(drive->bs, 0) != BLOCK_ERR_STOP_ENOSPC) {
1859                 error_report("fdc doesn't support drive option werror");
1860                 return -1;
1861             }
1862             if (bdrv_get_on_error(drive->bs, 1) != BLOCK_ERR_REPORT) {
1863                 error_report("fdc doesn't support drive option rerror");
1864                 return -1;
1865             }
1866         }
1867
1868         fd_init(drive);
1869         fd_revalidate(drive);
1870         if (drive->bs) {
1871             bdrv_set_removable(drive->bs, 1);
1872         }
1873     }
1874     return 0;
1875 }
1876
1877 FDCtrl *fdctrl_init_isa(DriveInfo **fds)
1878 {
1879     ISADevice *dev;
1880
1881     dev = isa_create("isa-fdc");
1882     if (fds[0]) {
1883         qdev_prop_set_drive_nofail(&dev->qdev, "driveA", fds[0]->bdrv);
1884     }
1885     if (fds[1]) {
1886         qdev_prop_set_drive_nofail(&dev->qdev, "driveB", fds[1]->bdrv);
1887     }
1888     qdev_init_nofail(&dev->qdev);
1889     return &(DO_UPCAST(FDCtrlISABus, busdev, dev)->state);
1890 }
1891
1892 FDCtrl *fdctrl_init_sysbus(qemu_irq irq, int dma_chann,
1893                            target_phys_addr_t mmio_base, DriveInfo **fds)
1894 {
1895     FDCtrl *fdctrl;
1896     DeviceState *dev;
1897     FDCtrlSysBus *sys;
1898
1899     dev = qdev_create(NULL, "sysbus-fdc");
1900     sys = DO_UPCAST(FDCtrlSysBus, busdev.qdev, dev);
1901     fdctrl = &sys->state;
1902     fdctrl->dma_chann = dma_chann; /* FIXME */
1903     if (fds[0]) {
1904         qdev_prop_set_drive_nofail(dev, "driveA", fds[0]->bdrv);
1905     }
1906     if (fds[1]) {
1907         qdev_prop_set_drive_nofail(dev, "driveB", fds[1]->bdrv);
1908     }
1909     qdev_init_nofail(dev);
1910     sysbus_connect_irq(&sys->busdev, 0, irq);
1911     sysbus_mmio_map(&sys->busdev, 0, mmio_base);
1912
1913     return fdctrl;
1914 }
1915
1916 FDCtrl *sun4m_fdctrl_init(qemu_irq irq, target_phys_addr_t io_base,
1917                           DriveInfo **fds, qemu_irq *fdc_tc)
1918 {
1919     DeviceState *dev;
1920     FDCtrlSysBus *sys;
1921     FDCtrl *fdctrl;
1922
1923     dev = qdev_create(NULL, "SUNW,fdtwo");
1924     if (fds[0]) {
1925         qdev_prop_set_drive_nofail(dev, "drive", fds[0]->bdrv);
1926     }
1927     qdev_init_nofail(dev);
1928     sys = DO_UPCAST(FDCtrlSysBus, busdev.qdev, dev);
1929     fdctrl = &sys->state;
1930     sysbus_connect_irq(&sys->busdev, 0, irq);
1931     sysbus_mmio_map(&sys->busdev, 0, io_base);
1932     *fdc_tc = qdev_get_gpio_in(dev, 0);
1933
1934     return fdctrl;
1935 }
1936
1937 static int fdctrl_init_common(FDCtrl *fdctrl)
1938 {
1939     int i, j;
1940     static int command_tables_inited = 0;
1941
1942     /* Fill 'command_to_handler' lookup table */
1943     if (!command_tables_inited) {
1944         command_tables_inited = 1;
1945         for (i = ARRAY_SIZE(handlers) - 1; i >= 0; i--) {
1946             for (j = 0; j < sizeof(command_to_handler); j++) {
1947                 if ((j & handlers[i].mask) == handlers[i].value) {
1948                     command_to_handler[j] = i;
1949                 }
1950             }
1951         }
1952     }
1953
1954     FLOPPY_DPRINTF("init controller\n");
1955     fdctrl->fifo = qemu_memalign(512, FD_SECTOR_LEN);
1956     fdctrl->fifo_size = 512;
1957     fdctrl->result_timer = qemu_new_timer(vm_clock,
1958                                           fdctrl_result_timer, fdctrl);
1959
1960     fdctrl->version = 0x90; /* Intel 82078 controller */
1961     fdctrl->config = FD_CONFIG_EIS | FD_CONFIG_EFIFO; /* Implicit seek, polling & FIFO enabled */
1962     fdctrl->num_floppies = MAX_FD;
1963
1964     if (fdctrl->dma_chann != -1)
1965         DMA_register_channel(fdctrl->dma_chann, &fdctrl_transfer_handler, fdctrl);
1966     return fdctrl_connect_drives(fdctrl);
1967 }
1968
1969 static int isabus_fdc_init1(ISADevice *dev)
1970 {
1971     FDCtrlISABus *isa = DO_UPCAST(FDCtrlISABus, busdev, dev);
1972     FDCtrl *fdctrl = &isa->state;
1973     int iobase = 0x3f0;
1974     int isairq = 6;
1975     int dma_chann = 2;
1976     int ret;
1977
1978     register_ioport_read(iobase + 0x01, 5, 1,
1979                          &fdctrl_read_port, fdctrl);
1980     register_ioport_read(iobase + 0x07, 1, 1,
1981                          &fdctrl_read_port, fdctrl);
1982     register_ioport_write(iobase + 0x01, 5, 1,
1983                           &fdctrl_write_port, fdctrl);
1984     register_ioport_write(iobase + 0x07, 1, 1,
1985                           &fdctrl_write_port, fdctrl);
1986     isa_init_irq(&isa->busdev, &fdctrl->irq, isairq);
1987     fdctrl->dma_chann = dma_chann;
1988
1989     qdev_set_legacy_instance_id(&dev->qdev, iobase, 2);
1990     ret = fdctrl_init_common(fdctrl);
1991
1992     return ret;
1993 }
1994
1995 static int sysbus_fdc_init1(SysBusDevice *dev)
1996 {
1997     FDCtrlSysBus *sys = DO_UPCAST(FDCtrlSysBus, busdev, dev);
1998     FDCtrl *fdctrl = &sys->state;
1999     int io;
2000     int ret;
2001
2002     io = cpu_register_io_memory(fdctrl_mem_read, fdctrl_mem_write, fdctrl);
2003     sysbus_init_mmio(dev, 0x08, io);
2004     sysbus_init_irq(dev, &fdctrl->irq);
2005     qdev_init_gpio_in(&dev->qdev, fdctrl_handle_tc, 1);
2006     fdctrl->dma_chann = -1;
2007
2008     qdev_set_legacy_instance_id(&dev->qdev, io, 2);
2009     ret = fdctrl_init_common(fdctrl);
2010
2011     return ret;
2012 }
2013
2014 static int sun4m_fdc_init1(SysBusDevice *dev)
2015 {
2016     FDCtrl *fdctrl = &(FROM_SYSBUS(FDCtrlSysBus, dev)->state);
2017     int io;
2018
2019     io = cpu_register_io_memory(fdctrl_mem_read_strict,
2020                                 fdctrl_mem_write_strict, fdctrl);
2021     sysbus_init_mmio(dev, 0x08, io);
2022     sysbus_init_irq(dev, &fdctrl->irq);
2023     qdev_init_gpio_in(&dev->qdev, fdctrl_handle_tc, 1);
2024
2025     fdctrl->sun4m = 1;
2026     qdev_set_legacy_instance_id(&dev->qdev, io, 2);
2027     return fdctrl_init_common(fdctrl);
2028 }
2029
2030 static const VMStateDescription vmstate_isa_fdc ={
2031     .name = "fdc",
2032     .version_id = 2,
2033     .minimum_version_id = 2,
2034     .fields = (VMStateField []) {
2035         VMSTATE_STRUCT(state, FDCtrlISABus, 0, vmstate_fdc, FDCtrl),
2036         VMSTATE_END_OF_LIST()
2037     }
2038 };
2039
2040 static ISADeviceInfo isa_fdc_info = {
2041     .init = isabus_fdc_init1,
2042     .qdev.name  = "isa-fdc",
2043     .qdev.size  = sizeof(FDCtrlISABus),
2044     .qdev.no_user = 1,
2045     .qdev.vmsd  = &vmstate_isa_fdc,
2046     .qdev.reset = fdctrl_external_reset_isa,
2047     .qdev.props = (Property[]) {
2048         DEFINE_PROP_DRIVE("driveA", FDCtrlISABus, state.drives[0].bs),
2049         DEFINE_PROP_DRIVE("driveB", FDCtrlISABus, state.drives[1].bs),
2050         DEFINE_PROP_END_OF_LIST(),
2051     },
2052 };
2053
2054 static const VMStateDescription vmstate_sysbus_fdc ={
2055     .name = "fdc",
2056     .version_id = 2,
2057     .minimum_version_id = 2,
2058     .fields = (VMStateField []) {
2059         VMSTATE_STRUCT(state, FDCtrlSysBus, 0, vmstate_fdc, FDCtrl),
2060         VMSTATE_END_OF_LIST()
2061     }
2062 };
2063
2064 static SysBusDeviceInfo sysbus_fdc_info = {
2065     .init = sysbus_fdc_init1,
2066     .qdev.name  = "sysbus-fdc",
2067     .qdev.size  = sizeof(FDCtrlSysBus),
2068     .qdev.vmsd  = &vmstate_sysbus_fdc,
2069     .qdev.reset = fdctrl_external_reset_sysbus,
2070     .qdev.props = (Property[]) {
2071         DEFINE_PROP_DRIVE("driveA", FDCtrlSysBus, state.drives[0].bs),
2072         DEFINE_PROP_DRIVE("driveB", FDCtrlSysBus, state.drives[1].bs),
2073         DEFINE_PROP_END_OF_LIST(),
2074     },
2075 };
2076
2077 static SysBusDeviceInfo sun4m_fdc_info = {
2078     .init = sun4m_fdc_init1,
2079     .qdev.name  = "SUNW,fdtwo",
2080     .qdev.size  = sizeof(FDCtrlSysBus),
2081     .qdev.vmsd  = &vmstate_sysbus_fdc,
2082     .qdev.reset = fdctrl_external_reset_sysbus,
2083     .qdev.props = (Property[]) {
2084         DEFINE_PROP_DRIVE("drive", FDCtrlSysBus, state.drives[0].bs),
2085         DEFINE_PROP_END_OF_LIST(),
2086     },
2087 };
2088
2089 static void fdc_register_devices(void)
2090 {
2091     isa_qdev_register(&isa_fdc_info);
2092     sysbus_register_withprop(&sysbus_fdc_info);
2093     sysbus_register_withprop(&sun4m_fdc_info);
2094 }
2095
2096 device_init(fdc_register_devices)