8d2c51d781bdf7c2ee6cf7e4fac3e69715a943c9
[qemu] / hw / ide.c
1 /*
2  * QEMU IDE disk and CD/DVD-ROM Emulator
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  * Copyright (c) 2006 Openedhand Ltd.
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 #include "hw.h"
26 #include "pc.h"
27 #include "pci.h"
28 #include "scsi-disk.h"
29 #include "pcmcia.h"
30 #include "block.h"
31 #include "block_int.h"
32 #include "qemu-timer.h"
33 #include "sysemu.h"
34 #include "ppc_mac.h"
35 #include "mac_dbdma.h"
36 #include "sh.h"
37 #include "dma.h"
38
39 typedef struct IDEBus IDEBus;
40 typedef struct IDEState IDEState;
41 typedef struct BMDMAState BMDMAState;
42
43 /* debug IDE devices */
44 //#define DEBUG_IDE
45 //#define DEBUG_IDE_ATAPI
46 //#define DEBUG_AIO
47 #define USE_DMA_CDROM
48
49 /* Bits of HD_STATUS */
50 #define ERR_STAT                0x01
51 #define INDEX_STAT              0x02
52 #define ECC_STAT                0x04    /* Corrected error */
53 #define DRQ_STAT                0x08
54 #define SEEK_STAT               0x10
55 #define SRV_STAT                0x10
56 #define WRERR_STAT              0x20
57 #define READY_STAT              0x40
58 #define BUSY_STAT               0x80
59
60 /* Bits for HD_ERROR */
61 #define MARK_ERR                0x01    /* Bad address mark */
62 #define TRK0_ERR                0x02    /* couldn't find track 0 */
63 #define ABRT_ERR                0x04    /* Command aborted */
64 #define MCR_ERR                 0x08    /* media change request */
65 #define ID_ERR                  0x10    /* ID field not found */
66 #define MC_ERR                  0x20    /* media changed */
67 #define ECC_ERR                 0x40    /* Uncorrectable ECC error */
68 #define BBD_ERR                 0x80    /* pre-EIDE meaning:  block marked bad */
69 #define ICRC_ERR                0x80    /* new meaning:  CRC error during transfer */
70
71 /* Bits of HD_NSECTOR */
72 #define CD                      0x01
73 #define IO                      0x02
74 #define REL                     0x04
75 #define TAG_MASK                0xf8
76
77 #define IDE_CMD_RESET           0x04
78 #define IDE_CMD_DISABLE_IRQ     0x02
79
80 /* ATA/ATAPI Commands pre T13 Spec */
81 #define WIN_NOP                         0x00
82 /*
83  *      0x01->0x02 Reserved
84  */
85 #define CFA_REQ_EXT_ERROR_CODE          0x03 /* CFA Request Extended Error Code */
86 /*
87  *      0x04->0x07 Reserved
88  */
89 #define WIN_SRST                        0x08 /* ATAPI soft reset command */
90 #define WIN_DEVICE_RESET                0x08
91 /*
92  *      0x09->0x0F Reserved
93  */
94 #define WIN_RECAL                       0x10
95 #define WIN_RESTORE                     WIN_RECAL
96 /*
97  *      0x10->0x1F Reserved
98  */
99 #define WIN_READ                        0x20 /* 28-Bit */
100 #define WIN_READ_ONCE                   0x21 /* 28-Bit without retries */
101 #define WIN_READ_LONG                   0x22 /* 28-Bit */
102 #define WIN_READ_LONG_ONCE              0x23 /* 28-Bit without retries */
103 #define WIN_READ_EXT                    0x24 /* 48-Bit */
104 #define WIN_READDMA_EXT                 0x25 /* 48-Bit */
105 #define WIN_READDMA_QUEUED_EXT          0x26 /* 48-Bit */
106 #define WIN_READ_NATIVE_MAX_EXT         0x27 /* 48-Bit */
107 /*
108  *      0x28
109  */
110 #define WIN_MULTREAD_EXT                0x29 /* 48-Bit */
111 /*
112  *      0x2A->0x2F Reserved
113  */
114 #define WIN_WRITE                       0x30 /* 28-Bit */
115 #define WIN_WRITE_ONCE                  0x31 /* 28-Bit without retries */
116 #define WIN_WRITE_LONG                  0x32 /* 28-Bit */
117 #define WIN_WRITE_LONG_ONCE             0x33 /* 28-Bit without retries */
118 #define WIN_WRITE_EXT                   0x34 /* 48-Bit */
119 #define WIN_WRITEDMA_EXT                0x35 /* 48-Bit */
120 #define WIN_WRITEDMA_QUEUED_EXT         0x36 /* 48-Bit */
121 #define WIN_SET_MAX_EXT                 0x37 /* 48-Bit */
122 #define CFA_WRITE_SECT_WO_ERASE         0x38 /* CFA Write Sectors without erase */
123 #define WIN_MULTWRITE_EXT               0x39 /* 48-Bit */
124 /*
125  *      0x3A->0x3B Reserved
126  */
127 #define WIN_WRITE_VERIFY                0x3C /* 28-Bit */
128 /*
129  *      0x3D->0x3F Reserved
130  */
131 #define WIN_VERIFY                      0x40 /* 28-Bit - Read Verify Sectors */
132 #define WIN_VERIFY_ONCE                 0x41 /* 28-Bit - without retries */
133 #define WIN_VERIFY_EXT                  0x42 /* 48-Bit */
134 /*
135  *      0x43->0x4F Reserved
136  */
137 #define WIN_FORMAT                      0x50
138 /*
139  *      0x51->0x5F Reserved
140  */
141 #define WIN_INIT                        0x60
142 /*
143  *      0x61->0x5F Reserved
144  */
145 #define WIN_SEEK                        0x70 /* 0x70-0x7F Reserved */
146 #define CFA_TRANSLATE_SECTOR            0x87 /* CFA Translate Sector */
147 #define WIN_DIAGNOSE                    0x90
148 #define WIN_SPECIFY                     0x91 /* set drive geometry translation */
149 #define WIN_DOWNLOAD_MICROCODE          0x92
150 #define WIN_STANDBYNOW2                 0x94
151 #define CFA_IDLEIMMEDIATE               0x95 /* force drive to become "ready" */
152 #define WIN_STANDBY2                    0x96
153 #define WIN_SETIDLE2                    0x97
154 #define WIN_CHECKPOWERMODE2             0x98
155 #define WIN_SLEEPNOW2                   0x99
156 /*
157  *      0x9A VENDOR
158  */
159 #define WIN_PACKETCMD                   0xA0 /* Send a packet command. */
160 #define WIN_PIDENTIFY                   0xA1 /* identify ATAPI device   */
161 #define WIN_QUEUED_SERVICE              0xA2
162 #define WIN_SMART                       0xB0 /* self-monitoring and reporting */
163 #define CFA_ACCESS_METADATA_STORAGE     0xB8
164 #define CFA_ERASE_SECTORS               0xC0 /* microdrives implement as NOP */
165 #define WIN_MULTREAD                    0xC4 /* read sectors using multiple mode*/
166 #define WIN_MULTWRITE                   0xC5 /* write sectors using multiple mode */
167 #define WIN_SETMULT                     0xC6 /* enable/disable multiple mode */
168 #define WIN_READDMA_QUEUED              0xC7 /* read sectors using Queued DMA transfers */
169 #define WIN_READDMA                     0xC8 /* read sectors using DMA transfers */
170 #define WIN_READDMA_ONCE                0xC9 /* 28-Bit - without retries */
171 #define WIN_WRITEDMA                    0xCA /* write sectors using DMA transfers */
172 #define WIN_WRITEDMA_ONCE               0xCB /* 28-Bit - without retries */
173 #define WIN_WRITEDMA_QUEUED             0xCC /* write sectors using Queued DMA transfers */
174 #define CFA_WRITE_MULTI_WO_ERASE        0xCD /* CFA Write multiple without erase */
175 #define WIN_GETMEDIASTATUS              0xDA
176 #define WIN_ACKMEDIACHANGE              0xDB /* ATA-1, ATA-2 vendor */
177 #define WIN_POSTBOOT                    0xDC
178 #define WIN_PREBOOT                     0xDD
179 #define WIN_DOORLOCK                    0xDE /* lock door on removable drives */
180 #define WIN_DOORUNLOCK                  0xDF /* unlock door on removable drives */
181 #define WIN_STANDBYNOW1                 0xE0
182 #define WIN_IDLEIMMEDIATE               0xE1 /* force drive to become "ready" */
183 #define WIN_STANDBY                     0xE2 /* Set device in Standby Mode */
184 #define WIN_SETIDLE1                    0xE3
185 #define WIN_READ_BUFFER                 0xE4 /* force read only 1 sector */
186 #define WIN_CHECKPOWERMODE1             0xE5
187 #define WIN_SLEEPNOW1                   0xE6
188 #define WIN_FLUSH_CACHE                 0xE7
189 #define WIN_WRITE_BUFFER                0xE8 /* force write only 1 sector */
190 #define WIN_WRITE_SAME                  0xE9 /* read ata-2 to use */
191         /* SET_FEATURES 0x22 or 0xDD */
192 #define WIN_FLUSH_CACHE_EXT             0xEA /* 48-Bit */
193 #define WIN_IDENTIFY                    0xEC /* ask drive to identify itself    */
194 #define WIN_MEDIAEJECT                  0xED
195 #define WIN_IDENTIFY_DMA                0xEE /* same as WIN_IDENTIFY, but DMA */
196 #define WIN_SETFEATURES                 0xEF /* set special drive features */
197 #define EXABYTE_ENABLE_NEST             0xF0
198 #define IBM_SENSE_CONDITION             0xF0 /* measure disk temperature */
199 #define WIN_SECURITY_SET_PASS           0xF1
200 #define WIN_SECURITY_UNLOCK             0xF2
201 #define WIN_SECURITY_ERASE_PREPARE      0xF3
202 #define WIN_SECURITY_ERASE_UNIT         0xF4
203 #define WIN_SECURITY_FREEZE_LOCK        0xF5
204 #define CFA_WEAR_LEVEL                  0xF5 /* microdrives implement as NOP */
205 #define WIN_SECURITY_DISABLE            0xF6
206 #define WIN_READ_NATIVE_MAX             0xF8 /* return the native maximum address */
207 #define WIN_SET_MAX                     0xF9
208 #define DISABLE_SEAGATE                 0xFB
209
210 /* set to 1 set disable mult support */
211 #define MAX_MULT_SECTORS 16
212
213 #define IDE_DMA_BUF_SECTORS 256
214
215 #if (IDE_DMA_BUF_SECTORS < MAX_MULT_SECTORS)
216 #error "IDE_DMA_BUF_SECTORS must be bigger or equal to MAX_MULT_SECTORS"
217 #endif
218
219 /* ATAPI defines */
220
221 #define ATAPI_PACKET_SIZE 12
222
223 /* The generic packet command opcodes for CD/DVD Logical Units,
224  * From Table 57 of the SFF8090 Ver. 3 (Mt. Fuji) draft standard. */
225 #define GPCMD_BLANK                         0xa1
226 #define GPCMD_CLOSE_TRACK                   0x5b
227 #define GPCMD_FLUSH_CACHE                   0x35
228 #define GPCMD_FORMAT_UNIT                   0x04
229 #define GPCMD_GET_CONFIGURATION             0x46
230 #define GPCMD_GET_EVENT_STATUS_NOTIFICATION 0x4a
231 #define GPCMD_GET_PERFORMANCE               0xac
232 #define GPCMD_INQUIRY                       0x12
233 #define GPCMD_LOAD_UNLOAD                   0xa6
234 #define GPCMD_MECHANISM_STATUS              0xbd
235 #define GPCMD_MODE_SELECT_10                0x55
236 #define GPCMD_MODE_SENSE_10                 0x5a
237 #define GPCMD_PAUSE_RESUME                  0x4b
238 #define GPCMD_PLAY_AUDIO_10                 0x45
239 #define GPCMD_PLAY_AUDIO_MSF                0x47
240 #define GPCMD_PLAY_AUDIO_TI                 0x48
241 #define GPCMD_PLAY_CD                       0xbc
242 #define GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL  0x1e
243 #define GPCMD_READ_10                       0x28
244 #define GPCMD_READ_12                       0xa8
245 #define GPCMD_READ_CDVD_CAPACITY            0x25
246 #define GPCMD_READ_CD                       0xbe
247 #define GPCMD_READ_CD_MSF                   0xb9
248 #define GPCMD_READ_DISC_INFO                0x51
249 #define GPCMD_READ_DVD_STRUCTURE            0xad
250 #define GPCMD_READ_FORMAT_CAPACITIES        0x23
251 #define GPCMD_READ_HEADER                   0x44
252 #define GPCMD_READ_TRACK_RZONE_INFO         0x52
253 #define GPCMD_READ_SUBCHANNEL               0x42
254 #define GPCMD_READ_TOC_PMA_ATIP             0x43
255 #define GPCMD_REPAIR_RZONE_TRACK            0x58
256 #define GPCMD_REPORT_KEY                    0xa4
257 #define GPCMD_REQUEST_SENSE                 0x03
258 #define GPCMD_RESERVE_RZONE_TRACK           0x53
259 #define GPCMD_SCAN                          0xba
260 #define GPCMD_SEEK                          0x2b
261 #define GPCMD_SEND_DVD_STRUCTURE            0xad
262 #define GPCMD_SEND_EVENT                    0xa2
263 #define GPCMD_SEND_KEY                      0xa3
264 #define GPCMD_SEND_OPC                      0x54
265 #define GPCMD_SET_READ_AHEAD                0xa7
266 #define GPCMD_SET_STREAMING                 0xb6
267 #define GPCMD_START_STOP_UNIT               0x1b
268 #define GPCMD_STOP_PLAY_SCAN                0x4e
269 #define GPCMD_TEST_UNIT_READY               0x00
270 #define GPCMD_VERIFY_10                     0x2f
271 #define GPCMD_WRITE_10                      0x2a
272 #define GPCMD_WRITE_AND_VERIFY_10           0x2e
273 /* This is listed as optional in ATAPI 2.6, but is (curiously)
274  * missing from Mt. Fuji, Table 57.  It _is_ mentioned in Mt. Fuji
275  * Table 377 as an MMC command for SCSi devices though...  Most ATAPI
276  * drives support it. */
277 #define GPCMD_SET_SPEED                     0xbb
278 /* This seems to be a SCSI specific CD-ROM opcode
279  * to play data at track/index */
280 #define GPCMD_PLAYAUDIO_TI                  0x48
281 /*
282  * From MS Media Status Notification Support Specification. For
283  * older drives only.
284  */
285 #define GPCMD_GET_MEDIA_STATUS              0xda
286 #define GPCMD_MODE_SENSE_6                  0x1a
287
288 /* Mode page codes for mode sense/set */
289 #define GPMODE_R_W_ERROR_PAGE           0x01
290 #define GPMODE_WRITE_PARMS_PAGE         0x05
291 #define GPMODE_AUDIO_CTL_PAGE           0x0e
292 #define GPMODE_POWER_PAGE               0x1a
293 #define GPMODE_FAULT_FAIL_PAGE          0x1c
294 #define GPMODE_TO_PROTECT_PAGE          0x1d
295 #define GPMODE_CAPABILITIES_PAGE        0x2a
296 #define GPMODE_ALL_PAGES                0x3f
297 /* Not in Mt. Fuji, but in ATAPI 2.6 -- depricated now in favor
298  * of MODE_SENSE_POWER_PAGE */
299 #define GPMODE_CDROM_PAGE               0x0d
300
301 /*
302  * Based on values from <linux/cdrom.h> but extending CD_MINS
303  * to the maximum common size allowed by the Orange's Book ATIP
304  *
305  * 90 and 99 min CDs are also available but using them as the
306  * upper limit reduces the effectiveness of the heuristic to
307  * detect DVDs burned to less than 25% of their maximum capacity
308  */
309
310 /* Some generally useful CD-ROM information */
311 #define CD_MINS                       80 /* max. minutes per CD */
312 #define CD_SECS                       60 /* seconds per minute */
313 #define CD_FRAMES                     75 /* frames per second */
314 #define CD_FRAMESIZE                2048 /* bytes per frame, "cooked" mode */
315 #define CD_MAX_BYTES       (CD_MINS * CD_SECS * CD_FRAMES * CD_FRAMESIZE)
316 #define CD_MAX_SECTORS     (CD_MAX_BYTES / 512)
317
318 /*
319  * The MMC values are not IDE specific and might need to be moved
320  * to a common header if they are also needed for the SCSI emulation
321  */
322
323 /* Profile list from MMC-6 revision 1 table 91 */
324 #define MMC_PROFILE_NONE                0x0000
325 #define MMC_PROFILE_CD_ROM              0x0008
326 #define MMC_PROFILE_CD_R                0x0009
327 #define MMC_PROFILE_CD_RW               0x000A
328 #define MMC_PROFILE_DVD_ROM             0x0010
329 #define MMC_PROFILE_DVD_R_SR            0x0011
330 #define MMC_PROFILE_DVD_RAM             0x0012
331 #define MMC_PROFILE_DVD_RW_RO           0x0013
332 #define MMC_PROFILE_DVD_RW_SR           0x0014
333 #define MMC_PROFILE_DVD_R_DL_SR         0x0015
334 #define MMC_PROFILE_DVD_R_DL_JR         0x0016
335 #define MMC_PROFILE_DVD_RW_DL           0x0017
336 #define MMC_PROFILE_DVD_DDR             0x0018
337 #define MMC_PROFILE_DVD_PLUS_RW         0x001A
338 #define MMC_PROFILE_DVD_PLUS_R          0x001B
339 #define MMC_PROFILE_DVD_PLUS_RW_DL      0x002A
340 #define MMC_PROFILE_DVD_PLUS_R_DL       0x002B
341 #define MMC_PROFILE_BD_ROM              0x0040
342 #define MMC_PROFILE_BD_R_SRM            0x0041
343 #define MMC_PROFILE_BD_R_RRM            0x0042
344 #define MMC_PROFILE_BD_RE               0x0043
345 #define MMC_PROFILE_HDDVD_ROM           0x0050
346 #define MMC_PROFILE_HDDVD_R             0x0051
347 #define MMC_PROFILE_HDDVD_RAM           0x0052
348 #define MMC_PROFILE_HDDVD_RW            0x0053
349 #define MMC_PROFILE_HDDVD_R_DL          0x0058
350 #define MMC_PROFILE_HDDVD_RW_DL         0x005A
351 #define MMC_PROFILE_INVALID             0xFFFF
352
353 #define ATAPI_INT_REASON_CD             0x01 /* 0 = data transfer */
354 #define ATAPI_INT_REASON_IO             0x02 /* 1 = transfer to the host */
355 #define ATAPI_INT_REASON_REL            0x04
356 #define ATAPI_INT_REASON_TAG            0xf8
357
358 /* same constants as bochs */
359 #define ASC_ILLEGAL_OPCODE                   0x20
360 #define ASC_LOGICAL_BLOCK_OOR                0x21
361 #define ASC_INV_FIELD_IN_CMD_PACKET          0x24
362 #define ASC_MEDIUM_MAY_HAVE_CHANGED          0x28
363 #define ASC_INCOMPATIBLE_FORMAT              0x30
364 #define ASC_MEDIUM_NOT_PRESENT               0x3a
365 #define ASC_SAVING_PARAMETERS_NOT_SUPPORTED  0x39
366 #define ASC_MEDIA_REMOVAL_PREVENTED          0x53
367
368 #define CFA_NO_ERROR            0x00
369 #define CFA_MISC_ERROR          0x09
370 #define CFA_INVALID_COMMAND     0x20
371 #define CFA_INVALID_ADDRESS     0x21
372 #define CFA_ADDRESS_OVERFLOW    0x2f
373
374 #define SENSE_NONE            0
375 #define SENSE_NOT_READY       2
376 #define SENSE_ILLEGAL_REQUEST 5
377 #define SENSE_UNIT_ATTENTION  6
378
379 #define SMART_READ_DATA       0xd0
380 #define SMART_READ_THRESH     0xd1
381 #define SMART_ATTR_AUTOSAVE   0xd2
382 #define SMART_SAVE_ATTR       0xd3
383 #define SMART_EXECUTE_OFFLINE 0xd4
384 #define SMART_READ_LOG        0xd5
385 #define SMART_WRITE_LOG       0xd6
386 #define SMART_ENABLE          0xd8
387 #define SMART_DISABLE         0xd9
388 #define SMART_STATUS          0xda
389
390 static int smart_attributes[][5] = {
391     /* id,  flags, val, wrst, thrsh */
392     { 0x01, 0x03, 0x64, 0x64, 0x06}, /* raw read */
393     { 0x03, 0x03, 0x64, 0x64, 0x46}, /* spin up */
394     { 0x04, 0x02, 0x64, 0x64, 0x14}, /* start stop count */
395     { 0x05, 0x03, 0x64, 0x64, 0x36}, /* remapped sectors */
396     { 0x00, 0x00, 0x00, 0x00, 0x00}
397 };
398
399
400
401 typedef void EndTransferFunc(IDEState *);
402
403 /* NOTE: IDEState represents in fact one drive */
404 struct IDEState {
405     IDEBus *bus;
406     uint8_t unit;
407     /* ide config */
408     int is_cdrom;
409     int is_cf;
410     int cylinders, heads, sectors;
411     int64_t nb_sectors;
412     int mult_sectors;
413     int identify_set;
414     uint16_t identify_data[256];
415     qemu_irq irq;
416     int drive_serial;
417     char drive_serial_str[21];
418     /* ide regs */
419     uint8_t feature;
420     uint8_t error;
421     uint32_t nsector;
422     uint8_t sector;
423     uint8_t lcyl;
424     uint8_t hcyl;
425     /* other part of tf for lba48 support */
426     uint8_t hob_feature;
427     uint8_t hob_nsector;
428     uint8_t hob_sector;
429     uint8_t hob_lcyl;
430     uint8_t hob_hcyl;
431
432     uint8_t select;
433     uint8_t status;
434
435     /* 0x3f6 command, only meaningful for drive 0 */
436     uint8_t cmd;
437     /* set for lba48 access */
438     uint8_t lba48;
439     BlockDriverState *bs;
440     /* ATAPI specific */
441     uint8_t sense_key;
442     uint8_t asc;
443     uint8_t cdrom_changed;
444     int packet_transfer_size;
445     int elementary_transfer_size;
446     int io_buffer_index;
447     int lba;
448     int cd_sector_size;
449     int atapi_dma; /* true if dma is requested for the packet cmd */
450     /* ATA DMA state */
451     int io_buffer_size;
452     QEMUSGList sg;
453     /* PIO transfer handling */
454     int req_nb_sectors; /* number of sectors per interrupt */
455     EndTransferFunc *end_transfer_func;
456     uint8_t *data_ptr;
457     uint8_t *data_end;
458     uint8_t *io_buffer;
459     QEMUTimer *sector_write_timer; /* only used for win2k install hack */
460     uint32_t irq_count; /* counts IRQs when using win2k install hack */
461     /* CF-ATA extended error */
462     uint8_t ext_error;
463     /* CF-ATA metadata storage */
464     uint32_t mdata_size;
465     uint8_t *mdata_storage;
466     int media_changed;
467     /* for pmac */
468     int is_read;
469     /* SMART */
470     uint8_t smart_enabled;
471     uint8_t smart_autosave;
472     int smart_errors;
473     uint8_t smart_selftest_count;
474     uint8_t *smart_selftest_data;
475 };
476
477 struct IDEBus {
478     BusState qbus;
479     BMDMAState *bmdma;
480     IDEState ifs[2];
481     uint8_t unit;
482 };
483
484 /* XXX: DVDs that could fit on a CD will be reported as a CD */
485 static inline int media_present(IDEState *s)
486 {
487     return (s->nb_sectors > 0);
488 }
489
490 static inline int media_is_dvd(IDEState *s)
491 {
492     return (media_present(s) && s->nb_sectors > CD_MAX_SECTORS);
493 }
494
495 static inline int media_is_cd(IDEState *s)
496 {
497     return (media_present(s) && s->nb_sectors <= CD_MAX_SECTORS);
498 }
499
500 #define BM_STATUS_DMAING 0x01
501 #define BM_STATUS_ERROR  0x02
502 #define BM_STATUS_INT    0x04
503 #define BM_STATUS_DMA_RETRY  0x08
504 #define BM_STATUS_PIO_RETRY  0x10
505
506 #define BM_CMD_START     0x01
507 #define BM_CMD_READ      0x08
508
509 #define IDE_TYPE_PIIX3   0
510 #define IDE_TYPE_CMD646  1
511 #define IDE_TYPE_PIIX4   2
512
513 /* CMD646 specific */
514 #define MRDMODE         0x71
515 #define   MRDMODE_INTR_CH0      0x04
516 #define   MRDMODE_INTR_CH1      0x08
517 #define   MRDMODE_BLK_CH0       0x10
518 #define   MRDMODE_BLK_CH1       0x20
519 #define UDIDETCR0       0x73
520 #define UDIDETCR1       0x7B
521
522 struct BMDMAState {
523     uint8_t cmd;
524     uint8_t status;
525     uint32_t addr;
526
527     struct PCIIDEState *pci_dev;
528     IDEBus *bus;
529     /* current transfer state */
530     uint32_t cur_addr;
531     uint32_t cur_prd_last;
532     uint32_t cur_prd_addr;
533     uint32_t cur_prd_len;
534     uint8_t unit;
535     BlockDriverCompletionFunc *dma_cb;
536     BlockDriverAIOCB *aiocb;
537     struct iovec iov;
538     QEMUIOVector qiov;
539     int64_t sector_num;
540     uint32_t nsector;
541     QEMUBH *bh;
542 };
543
544 typedef struct PCIIDEState {
545     PCIDevice dev;
546     IDEBus bus[2];
547     BMDMAState bmdma[2];
548     int type; /* see IDE_TYPE_xxx */
549 } PCIIDEState;
550
551 static inline IDEState *bmdma_active_if(BMDMAState *bmdma)
552 {
553     assert(bmdma->unit != -1);
554     return bmdma->bus->ifs + bmdma->unit;
555 }
556
557 static inline IDEState *idebus_active_if(IDEBus *bus)
558 {
559     return bus->ifs + bus->unit;
560 }
561
562 static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb);
563 static void ide_dma_restart(IDEState *s);
564 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret);
565
566 static void padstr(char *str, const char *src, int len)
567 {
568     int i, v;
569     for(i = 0; i < len; i++) {
570         if (*src)
571             v = *src++;
572         else
573             v = ' ';
574         str[i^1] = v;
575     }
576 }
577
578 static void padstr8(uint8_t *buf, int buf_size, const char *src)
579 {
580     int i;
581     for(i = 0; i < buf_size; i++) {
582         if (*src)
583             buf[i] = *src++;
584         else
585             buf[i] = ' ';
586     }
587 }
588
589 static void put_le16(uint16_t *p, unsigned int v)
590 {
591     *p = cpu_to_le16(v);
592 }
593
594 static void ide_identify(IDEState *s)
595 {
596     uint16_t *p;
597     unsigned int oldsize;
598
599     if (s->identify_set) {
600         memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
601         return;
602     }
603
604     memset(s->io_buffer, 0, 512);
605     p = (uint16_t *)s->io_buffer;
606     put_le16(p + 0, 0x0040);
607     put_le16(p + 1, s->cylinders);
608     put_le16(p + 3, s->heads);
609     put_le16(p + 4, 512 * s->sectors); /* XXX: retired, remove ? */
610     put_le16(p + 5, 512); /* XXX: retired, remove ? */
611     put_le16(p + 6, s->sectors);
612     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
613     put_le16(p + 20, 3); /* XXX: retired, remove ? */
614     put_le16(p + 21, 512); /* cache size in sectors */
615     put_le16(p + 22, 4); /* ecc bytes */
616     padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */
617     padstr((char *)(p + 27), "QEMU HARDDISK", 40); /* model */
618 #if MAX_MULT_SECTORS > 1
619     put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
620 #endif
621     put_le16(p + 48, 1); /* dword I/O */
622     put_le16(p + 49, (1 << 11) | (1 << 9) | (1 << 8)); /* DMA and LBA supported */
623     put_le16(p + 51, 0x200); /* PIO transfer cycle */
624     put_le16(p + 52, 0x200); /* DMA transfer cycle */
625     put_le16(p + 53, 1 | (1 << 1) | (1 << 2)); /* words 54-58,64-70,88 are valid */
626     put_le16(p + 54, s->cylinders);
627     put_le16(p + 55, s->heads);
628     put_le16(p + 56, s->sectors);
629     oldsize = s->cylinders * s->heads * s->sectors;
630     put_le16(p + 57, oldsize);
631     put_le16(p + 58, oldsize >> 16);
632     if (s->mult_sectors)
633         put_le16(p + 59, 0x100 | s->mult_sectors);
634     put_le16(p + 60, s->nb_sectors);
635     put_le16(p + 61, s->nb_sectors >> 16);
636     put_le16(p + 62, 0x07); /* single word dma0-2 supported */
637     put_le16(p + 63, 0x07); /* mdma0-2 supported */
638     put_le16(p + 65, 120);
639     put_le16(p + 66, 120);
640     put_le16(p + 67, 120);
641     put_le16(p + 68, 120);
642     put_le16(p + 80, 0xf0); /* ata3 -> ata6 supported */
643     put_le16(p + 81, 0x16); /* conforms to ata5 */
644     /* 14=NOP supported, 0=SMART supported */
645     put_le16(p + 82, (1 << 14) | 1);
646     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
647     put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
648     /* 14=set to 1, 1=SMART self test, 0=SMART error logging */
649     put_le16(p + 84, (1 << 14) | 0);
650     /* 14 = NOP supported, 0=SMART feature set enabled */
651     put_le16(p + 85, (1 << 14) | 1);
652     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
653     put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
654     /* 14=set to 1, 1=smart self test, 0=smart error logging */
655     put_le16(p + 87, (1 << 14) | 0);
656     put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
657     put_le16(p + 93, 1 | (1 << 14) | 0x2000);
658     put_le16(p + 100, s->nb_sectors);
659     put_le16(p + 101, s->nb_sectors >> 16);
660     put_le16(p + 102, s->nb_sectors >> 32);
661     put_le16(p + 103, s->nb_sectors >> 48);
662
663     memcpy(s->identify_data, p, sizeof(s->identify_data));
664     s->identify_set = 1;
665 }
666
667 static void ide_atapi_identify(IDEState *s)
668 {
669     uint16_t *p;
670
671     if (s->identify_set) {
672         memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
673         return;
674     }
675
676     memset(s->io_buffer, 0, 512);
677     p = (uint16_t *)s->io_buffer;
678     /* Removable CDROM, 50us response, 12 byte packets */
679     put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));
680     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
681     put_le16(p + 20, 3); /* buffer type */
682     put_le16(p + 21, 512); /* cache size in sectors */
683     put_le16(p + 22, 4); /* ecc bytes */
684     padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */
685     padstr((char *)(p + 27), "QEMU DVD-ROM", 40); /* model */
686     put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */
687 #ifdef USE_DMA_CDROM
688     put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */
689     put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */
690     put_le16(p + 62, 7);  /* single word dma0-2 supported */
691     put_le16(p + 63, 7);  /* mdma0-2 supported */
692     put_le16(p + 64, 0x3f); /* PIO modes supported */
693 #else
694     put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */
695     put_le16(p + 53, 3); /* words 64-70, 54-58 valid */
696     put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */
697     put_le16(p + 64, 1); /* PIO modes */
698 #endif
699     put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */
700     put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */
701     put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */
702     put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */
703
704     put_le16(p + 71, 30); /* in ns */
705     put_le16(p + 72, 30); /* in ns */
706
707     put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
708 #ifdef USE_DMA_CDROM
709     put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
710 #endif
711     memcpy(s->identify_data, p, sizeof(s->identify_data));
712     s->identify_set = 1;
713 }
714
715 static void ide_cfata_identify(IDEState *s)
716 {
717     uint16_t *p;
718     uint32_t cur_sec;
719
720     p = (uint16_t *) s->identify_data;
721     if (s->identify_set)
722         goto fill_buffer;
723
724     memset(p, 0, sizeof(s->identify_data));
725
726     cur_sec = s->cylinders * s->heads * s->sectors;
727
728     put_le16(p + 0, 0x848a);                    /* CF Storage Card signature */
729     put_le16(p + 1, s->cylinders);              /* Default cylinders */
730     put_le16(p + 3, s->heads);                  /* Default heads */
731     put_le16(p + 6, s->sectors);                /* Default sectors per track */
732     put_le16(p + 7, s->nb_sectors >> 16);       /* Sectors per card */
733     put_le16(p + 8, s->nb_sectors);             /* Sectors per card */
734     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
735     put_le16(p + 22, 0x0004);                   /* ECC bytes */
736     padstr((char *) (p + 23), QEMU_VERSION, 8); /* Firmware Revision */
737     padstr((char *) (p + 27), "QEMU MICRODRIVE", 40);/* Model number */
738 #if MAX_MULT_SECTORS > 1
739     put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
740 #else
741     put_le16(p + 47, 0x0000);
742 #endif
743     put_le16(p + 49, 0x0f00);                   /* Capabilities */
744     put_le16(p + 51, 0x0002);                   /* PIO cycle timing mode */
745     put_le16(p + 52, 0x0001);                   /* DMA cycle timing mode */
746     put_le16(p + 53, 0x0003);                   /* Translation params valid */
747     put_le16(p + 54, s->cylinders);             /* Current cylinders */
748     put_le16(p + 55, s->heads);                 /* Current heads */
749     put_le16(p + 56, s->sectors);               /* Current sectors */
750     put_le16(p + 57, cur_sec);                  /* Current capacity */
751     put_le16(p + 58, cur_sec >> 16);            /* Current capacity */
752     if (s->mult_sectors)                        /* Multiple sector setting */
753         put_le16(p + 59, 0x100 | s->mult_sectors);
754     put_le16(p + 60, s->nb_sectors);            /* Total LBA sectors */
755     put_le16(p + 61, s->nb_sectors >> 16);      /* Total LBA sectors */
756     put_le16(p + 63, 0x0203);                   /* Multiword DMA capability */
757     put_le16(p + 64, 0x0001);                   /* Flow Control PIO support */
758     put_le16(p + 65, 0x0096);                   /* Min. Multiword DMA cycle */
759     put_le16(p + 66, 0x0096);                   /* Rec. Multiword DMA cycle */
760     put_le16(p + 68, 0x00b4);                   /* Min. PIO cycle time */
761     put_le16(p + 82, 0x400c);                   /* Command Set supported */
762     put_le16(p + 83, 0x7068);                   /* Command Set supported */
763     put_le16(p + 84, 0x4000);                   /* Features supported */
764     put_le16(p + 85, 0x000c);                   /* Command Set enabled */
765     put_le16(p + 86, 0x7044);                   /* Command Set enabled */
766     put_le16(p + 87, 0x4000);                   /* Features enabled */
767     put_le16(p + 91, 0x4060);                   /* Current APM level */
768     put_le16(p + 129, 0x0002);                  /* Current features option */
769     put_le16(p + 130, 0x0005);                  /* Reassigned sectors */
770     put_le16(p + 131, 0x0001);                  /* Initial power mode */
771     put_le16(p + 132, 0x0000);                  /* User signature */
772     put_le16(p + 160, 0x8100);                  /* Power requirement */
773     put_le16(p + 161, 0x8001);                  /* CF command set */
774
775     s->identify_set = 1;
776
777 fill_buffer:
778     memcpy(s->io_buffer, p, sizeof(s->identify_data));
779 }
780
781 static void ide_set_signature(IDEState *s)
782 {
783     s->select &= 0xf0; /* clear head */
784     /* put signature */
785     s->nsector = 1;
786     s->sector = 1;
787     if (s->is_cdrom) {
788         s->lcyl = 0x14;
789         s->hcyl = 0xeb;
790     } else if (s->bs) {
791         s->lcyl = 0;
792         s->hcyl = 0;
793     } else {
794         s->lcyl = 0xff;
795         s->hcyl = 0xff;
796     }
797 }
798
799 static inline void ide_abort_command(IDEState *s)
800 {
801     s->status = READY_STAT | ERR_STAT;
802     s->error = ABRT_ERR;
803 }
804
805 static inline void ide_dma_submit_check(IDEState *s,
806           BlockDriverCompletionFunc *dma_cb, BMDMAState *bm)
807 {
808     if (bm->aiocb)
809         return;
810     dma_cb(bm, -1);
811 }
812
813 static inline void ide_set_irq(IDEState *s)
814 {
815     BMDMAState *bm = s->bus->bmdma;
816     if (!(s->cmd & IDE_CMD_DISABLE_IRQ)) {
817         if (bm) {
818             bm->status |= BM_STATUS_INT;
819         }
820         qemu_irq_raise(s->irq);
821     }
822 }
823
824 /* prepare data transfer and tell what to do after */
825 static void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
826                                EndTransferFunc *end_transfer_func)
827 {
828     s->end_transfer_func = end_transfer_func;
829     s->data_ptr = buf;
830     s->data_end = buf + size;
831     if (!(s->status & ERR_STAT))
832         s->status |= DRQ_STAT;
833 }
834
835 static void ide_transfer_stop(IDEState *s)
836 {
837     s->end_transfer_func = ide_transfer_stop;
838     s->data_ptr = s->io_buffer;
839     s->data_end = s->io_buffer;
840     s->status &= ~DRQ_STAT;
841 }
842
843 static int64_t ide_get_sector(IDEState *s)
844 {
845     int64_t sector_num;
846     if (s->select & 0x40) {
847         /* lba */
848         if (!s->lba48) {
849             sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
850                 (s->lcyl << 8) | s->sector;
851         } else {
852             sector_num = ((int64_t)s->hob_hcyl << 40) |
853                 ((int64_t) s->hob_lcyl << 32) |
854                 ((int64_t) s->hob_sector << 24) |
855                 ((int64_t) s->hcyl << 16) |
856                 ((int64_t) s->lcyl << 8) | s->sector;
857         }
858     } else {
859         sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
860             (s->select & 0x0f) * s->sectors + (s->sector - 1);
861     }
862     return sector_num;
863 }
864
865 static void ide_set_sector(IDEState *s, int64_t sector_num)
866 {
867     unsigned int cyl, r;
868     if (s->select & 0x40) {
869         if (!s->lba48) {
870             s->select = (s->select & 0xf0) | (sector_num >> 24);
871             s->hcyl = (sector_num >> 16);
872             s->lcyl = (sector_num >> 8);
873             s->sector = (sector_num);
874         } else {
875             s->sector = sector_num;
876             s->lcyl = sector_num >> 8;
877             s->hcyl = sector_num >> 16;
878             s->hob_sector = sector_num >> 24;
879             s->hob_lcyl = sector_num >> 32;
880             s->hob_hcyl = sector_num >> 40;
881         }
882     } else {
883         cyl = sector_num / (s->heads * s->sectors);
884         r = sector_num % (s->heads * s->sectors);
885         s->hcyl = cyl >> 8;
886         s->lcyl = cyl;
887         s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);
888         s->sector = (r % s->sectors) + 1;
889     }
890 }
891
892 static void ide_rw_error(IDEState *s) {
893     ide_abort_command(s);
894     ide_set_irq(s);
895 }
896
897 static void ide_sector_read(IDEState *s)
898 {
899     int64_t sector_num;
900     int ret, n;
901
902     s->status = READY_STAT | SEEK_STAT;
903     s->error = 0; /* not needed by IDE spec, but needed by Windows */
904     sector_num = ide_get_sector(s);
905     n = s->nsector;
906     if (n == 0) {
907         /* no more sector to read from disk */
908         ide_transfer_stop(s);
909     } else {
910 #if defined(DEBUG_IDE)
911         printf("read sector=%" PRId64 "\n", sector_num);
912 #endif
913         if (n > s->req_nb_sectors)
914             n = s->req_nb_sectors;
915         ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
916         if (ret != 0) {
917             ide_rw_error(s);
918             return;
919         }
920         ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);
921         ide_set_irq(s);
922         ide_set_sector(s, sector_num + n);
923         s->nsector -= n;
924     }
925 }
926
927
928 /* return 0 if buffer completed */
929 static int dma_buf_prepare(BMDMAState *bm, int is_write)
930 {
931     IDEState *s = bmdma_active_if(bm);
932     struct {
933         uint32_t addr;
934         uint32_t size;
935     } prd;
936     int l, len;
937
938     qemu_sglist_init(&s->sg, s->nsector / (TARGET_PAGE_SIZE/512) + 1);
939     s->io_buffer_size = 0;
940     for(;;) {
941         if (bm->cur_prd_len == 0) {
942             /* end of table (with a fail safe of one page) */
943             if (bm->cur_prd_last ||
944                 (bm->cur_addr - bm->addr) >= 4096)
945                 return s->io_buffer_size != 0;
946             cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
947             bm->cur_addr += 8;
948             prd.addr = le32_to_cpu(prd.addr);
949             prd.size = le32_to_cpu(prd.size);
950             len = prd.size & 0xfffe;
951             if (len == 0)
952                 len = 0x10000;
953             bm->cur_prd_len = len;
954             bm->cur_prd_addr = prd.addr;
955             bm->cur_prd_last = (prd.size & 0x80000000);
956         }
957         l = bm->cur_prd_len;
958         if (l > 0) {
959             qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);
960             bm->cur_prd_addr += l;
961             bm->cur_prd_len -= l;
962             s->io_buffer_size += l;
963         }
964     }
965     return 1;
966 }
967
968 static void dma_buf_commit(IDEState *s, int is_write)
969 {
970     qemu_sglist_destroy(&s->sg);
971 }
972
973 static void ide_dma_error(IDEState *s)
974 {
975     ide_transfer_stop(s);
976     s->error = ABRT_ERR;
977     s->status = READY_STAT | ERR_STAT;
978     ide_set_irq(s);
979 }
980
981 static int ide_handle_write_error(IDEState *s, int error, int op)
982 {
983     BlockInterfaceErrorAction action = drive_get_onerror(s->bs);
984
985     if (action == BLOCK_ERR_IGNORE)
986         return 0;
987
988     if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
989             || action == BLOCK_ERR_STOP_ANY) {
990         s->bus->bmdma->unit = s->unit;
991         s->bus->bmdma->status |= op;
992         vm_stop(0);
993     } else {
994         if (op == BM_STATUS_DMA_RETRY) {
995             dma_buf_commit(s, 0);
996             ide_dma_error(s);
997         } else {
998             ide_rw_error(s);
999         }
1000     }
1001
1002     return 1;
1003 }
1004
1005 /* return 0 if buffer completed */
1006 static int dma_buf_rw(BMDMAState *bm, int is_write)
1007 {
1008     IDEState *s = bmdma_active_if(bm);
1009     struct {
1010         uint32_t addr;
1011         uint32_t size;
1012     } prd;
1013     int l, len;
1014
1015     for(;;) {
1016         l = s->io_buffer_size - s->io_buffer_index;
1017         if (l <= 0)
1018             break;
1019         if (bm->cur_prd_len == 0) {
1020             /* end of table (with a fail safe of one page) */
1021             if (bm->cur_prd_last ||
1022                 (bm->cur_addr - bm->addr) >= 4096)
1023                 return 0;
1024             cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
1025             bm->cur_addr += 8;
1026             prd.addr = le32_to_cpu(prd.addr);
1027             prd.size = le32_to_cpu(prd.size);
1028             len = prd.size & 0xfffe;
1029             if (len == 0)
1030                 len = 0x10000;
1031             bm->cur_prd_len = len;
1032             bm->cur_prd_addr = prd.addr;
1033             bm->cur_prd_last = (prd.size & 0x80000000);
1034         }
1035         if (l > bm->cur_prd_len)
1036             l = bm->cur_prd_len;
1037         if (l > 0) {
1038             if (is_write) {
1039                 cpu_physical_memory_write(bm->cur_prd_addr,
1040                                           s->io_buffer + s->io_buffer_index, l);
1041             } else {
1042                 cpu_physical_memory_read(bm->cur_prd_addr,
1043                                           s->io_buffer + s->io_buffer_index, l);
1044             }
1045             bm->cur_prd_addr += l;
1046             bm->cur_prd_len -= l;
1047             s->io_buffer_index += l;
1048         }
1049     }
1050     return 1;
1051 }
1052
1053 static void ide_read_dma_cb(void *opaque, int ret)
1054 {
1055     BMDMAState *bm = opaque;
1056     IDEState *s = bmdma_active_if(bm);
1057     int n;
1058     int64_t sector_num;
1059
1060     if (ret < 0) {
1061         dma_buf_commit(s, 1);
1062         ide_dma_error(s);
1063         return;
1064     }
1065
1066     n = s->io_buffer_size >> 9;
1067     sector_num = ide_get_sector(s);
1068     if (n > 0) {
1069         dma_buf_commit(s, 1);
1070         sector_num += n;
1071         ide_set_sector(s, sector_num);
1072         s->nsector -= n;
1073     }
1074
1075     /* end of transfer ? */
1076     if (s->nsector == 0) {
1077         s->status = READY_STAT | SEEK_STAT;
1078         ide_set_irq(s);
1079     eot:
1080         bm->status &= ~BM_STATUS_DMAING;
1081         bm->status |= BM_STATUS_INT;
1082         bm->dma_cb = NULL;
1083         bm->unit = -1;
1084         bm->aiocb = NULL;
1085         return;
1086     }
1087
1088     /* launch next transfer */
1089     n = s->nsector;
1090     s->io_buffer_index = 0;
1091     s->io_buffer_size = n * 512;
1092     if (dma_buf_prepare(bm, 1) == 0)
1093         goto eot;
1094 #ifdef DEBUG_AIO
1095     printf("aio_read: sector_num=%" PRId64 " n=%d\n", sector_num, n);
1096 #endif
1097     bm->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num, ide_read_dma_cb, bm);
1098     ide_dma_submit_check(s, ide_read_dma_cb, bm);
1099 }
1100
1101 static void ide_sector_read_dma(IDEState *s)
1102 {
1103     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
1104     s->io_buffer_index = 0;
1105     s->io_buffer_size = 0;
1106     s->is_read = 1;
1107     ide_dma_start(s, ide_read_dma_cb);
1108 }
1109
1110 static void ide_sector_write_timer_cb(void *opaque)
1111 {
1112     IDEState *s = opaque;
1113     ide_set_irq(s);
1114 }
1115
1116 static void ide_sector_write(IDEState *s)
1117 {
1118     int64_t sector_num;
1119     int ret, n, n1;
1120
1121     s->status = READY_STAT | SEEK_STAT;
1122     sector_num = ide_get_sector(s);
1123 #if defined(DEBUG_IDE)
1124     printf("write sector=%" PRId64 "\n", sector_num);
1125 #endif
1126     n = s->nsector;
1127     if (n > s->req_nb_sectors)
1128         n = s->req_nb_sectors;
1129     ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
1130
1131     if (ret != 0) {
1132         if (ide_handle_write_error(s, -ret, BM_STATUS_PIO_RETRY))
1133             return;
1134     }
1135
1136     s->nsector -= n;
1137     if (s->nsector == 0) {
1138         /* no more sectors to write */
1139         ide_transfer_stop(s);
1140     } else {
1141         n1 = s->nsector;
1142         if (n1 > s->req_nb_sectors)
1143             n1 = s->req_nb_sectors;
1144         ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write);
1145     }
1146     ide_set_sector(s, sector_num + n);
1147
1148 #ifdef TARGET_I386
1149     if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {
1150         /* It seems there is a bug in the Windows 2000 installer HDD
1151            IDE driver which fills the disk with empty logs when the
1152            IDE write IRQ comes too early. This hack tries to correct
1153            that at the expense of slower write performances. Use this
1154            option _only_ to install Windows 2000. You must disable it
1155            for normal use. */
1156         qemu_mod_timer(s->sector_write_timer, 
1157                        qemu_get_clock(vm_clock) + (ticks_per_sec / 1000));
1158     } else 
1159 #endif
1160     {
1161         ide_set_irq(s);
1162     }
1163 }
1164
1165 static void ide_dma_restart_bh(void *opaque)
1166 {
1167     BMDMAState *bm = opaque;
1168
1169     qemu_bh_delete(bm->bh);
1170     bm->bh = NULL;
1171
1172     if (bm->status & BM_STATUS_DMA_RETRY) {
1173         bm->status &= ~BM_STATUS_DMA_RETRY;
1174         ide_dma_restart(bmdma_active_if(bm));
1175     } else if (bm->status & BM_STATUS_PIO_RETRY) {
1176         bm->status &= ~BM_STATUS_PIO_RETRY;
1177         ide_sector_write(bmdma_active_if(bm));
1178     }
1179 }
1180
1181 static void ide_dma_restart_cb(void *opaque, int running, int reason)
1182 {
1183     BMDMAState *bm = opaque;
1184
1185     if (!running)
1186         return;
1187
1188     if (!bm->bh) {
1189         bm->bh = qemu_bh_new(ide_dma_restart_bh, bm);
1190         qemu_bh_schedule(bm->bh);
1191     }
1192 }
1193
1194 static void ide_write_dma_cb(void *opaque, int ret)
1195 {
1196     BMDMAState *bm = opaque;
1197     IDEState *s = bmdma_active_if(bm);
1198     int n;
1199     int64_t sector_num;
1200
1201     if (ret < 0) {
1202         if (ide_handle_write_error(s, -ret,  BM_STATUS_DMA_RETRY))
1203             return;
1204     }
1205
1206     n = s->io_buffer_size >> 9;
1207     sector_num = ide_get_sector(s);
1208     if (n > 0) {
1209         dma_buf_commit(s, 0);
1210         sector_num += n;
1211         ide_set_sector(s, sector_num);
1212         s->nsector -= n;
1213     }
1214
1215     /* end of transfer ? */
1216     if (s->nsector == 0) {
1217         s->status = READY_STAT | SEEK_STAT;
1218         ide_set_irq(s);
1219     eot:
1220         bm->status &= ~BM_STATUS_DMAING;
1221         bm->status |= BM_STATUS_INT;
1222         bm->dma_cb = NULL;
1223         bm->unit = -1;
1224         bm->aiocb = NULL;
1225         return;
1226     }
1227
1228     n = s->nsector;
1229     s->io_buffer_size = n * 512;
1230     /* launch next transfer */
1231     if (dma_buf_prepare(bm, 0) == 0)
1232         goto eot;
1233 #ifdef DEBUG_AIO
1234     printf("aio_write: sector_num=%" PRId64 " n=%d\n", sector_num, n);
1235 #endif
1236     bm->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num, ide_write_dma_cb, bm);
1237     ide_dma_submit_check(s, ide_write_dma_cb, bm);
1238 }
1239
1240 static void ide_sector_write_dma(IDEState *s)
1241 {
1242     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
1243     s->io_buffer_index = 0;
1244     s->io_buffer_size = 0;
1245     s->is_read = 0;
1246     ide_dma_start(s, ide_write_dma_cb);
1247 }
1248
1249 static void ide_atapi_cmd_ok(IDEState *s)
1250 {
1251     s->error = 0;
1252     s->status = READY_STAT | SEEK_STAT;
1253     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1254     ide_set_irq(s);
1255 }
1256
1257 static void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
1258 {
1259 #ifdef DEBUG_IDE_ATAPI
1260     printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc);
1261 #endif
1262     s->error = sense_key << 4;
1263     s->status = READY_STAT | ERR_STAT;
1264     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1265     s->sense_key = sense_key;
1266     s->asc = asc;
1267     ide_set_irq(s);
1268 }
1269
1270 static void ide_atapi_cmd_check_status(IDEState *s)
1271 {
1272 #ifdef DEBUG_IDE_ATAPI
1273     printf("atapi_cmd_check_status\n");
1274 #endif
1275     s->error = MC_ERR | (SENSE_UNIT_ATTENTION << 4);
1276     s->status = ERR_STAT;
1277     s->nsector = 0;
1278     ide_set_irq(s);
1279 }
1280
1281 static inline void cpu_to_ube16(uint8_t *buf, int val)
1282 {
1283     buf[0] = val >> 8;
1284     buf[1] = val & 0xff;
1285 }
1286
1287 static inline void cpu_to_ube32(uint8_t *buf, unsigned int val)
1288 {
1289     buf[0] = val >> 24;
1290     buf[1] = val >> 16;
1291     buf[2] = val >> 8;
1292     buf[3] = val & 0xff;
1293 }
1294
1295 static inline int ube16_to_cpu(const uint8_t *buf)
1296 {
1297     return (buf[0] << 8) | buf[1];
1298 }
1299
1300 static inline int ube32_to_cpu(const uint8_t *buf)
1301 {
1302     return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1303 }
1304
1305 static void lba_to_msf(uint8_t *buf, int lba)
1306 {
1307     lba += 150;
1308     buf[0] = (lba / 75) / 60;
1309     buf[1] = (lba / 75) % 60;
1310     buf[2] = lba % 75;
1311 }
1312
1313 static void cd_data_to_raw(uint8_t *buf, int lba)
1314 {
1315     /* sync bytes */
1316     buf[0] = 0x00;
1317     memset(buf + 1, 0xff, 10);
1318     buf[11] = 0x00;
1319     buf += 12;
1320     /* MSF */
1321     lba_to_msf(buf, lba);
1322     buf[3] = 0x01; /* mode 1 data */
1323     buf += 4;
1324     /* data */
1325     buf += 2048;
1326     /* XXX: ECC not computed */
1327     memset(buf, 0, 288);
1328 }
1329
1330 static int cd_read_sector(BlockDriverState *bs, int lba, uint8_t *buf,
1331                            int sector_size)
1332 {
1333     int ret;
1334
1335     switch(sector_size) {
1336     case 2048:
1337         ret = bdrv_read(bs, (int64_t)lba << 2, buf, 4);
1338         break;
1339     case 2352:
1340         ret = bdrv_read(bs, (int64_t)lba << 2, buf + 16, 4);
1341         if (ret < 0)
1342             return ret;
1343         cd_data_to_raw(buf, lba);
1344         break;
1345     default:
1346         ret = -EIO;
1347         break;
1348     }
1349     return ret;
1350 }
1351
1352 static void ide_atapi_io_error(IDEState *s, int ret)
1353 {
1354     /* XXX: handle more errors */
1355     if (ret == -ENOMEDIUM) {
1356         ide_atapi_cmd_error(s, SENSE_NOT_READY,
1357                             ASC_MEDIUM_NOT_PRESENT);
1358     } else {
1359         ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1360                             ASC_LOGICAL_BLOCK_OOR);
1361     }
1362 }
1363
1364 /* The whole ATAPI transfer logic is handled in this function */
1365 static void ide_atapi_cmd_reply_end(IDEState *s)
1366 {
1367     int byte_count_limit, size, ret;
1368 #ifdef DEBUG_IDE_ATAPI
1369     printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",
1370            s->packet_transfer_size,
1371            s->elementary_transfer_size,
1372            s->io_buffer_index);
1373 #endif
1374     if (s->packet_transfer_size <= 0) {
1375         /* end of transfer */
1376         ide_transfer_stop(s);
1377         s->status = READY_STAT | SEEK_STAT;
1378         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1379         ide_set_irq(s);
1380 #ifdef DEBUG_IDE_ATAPI
1381         printf("status=0x%x\n", s->status);
1382 #endif
1383     } else {
1384         /* see if a new sector must be read */
1385         if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {
1386             ret = cd_read_sector(s->bs, s->lba, s->io_buffer, s->cd_sector_size);
1387             if (ret < 0) {
1388                 ide_transfer_stop(s);
1389                 ide_atapi_io_error(s, ret);
1390                 return;
1391             }
1392             s->lba++;
1393             s->io_buffer_index = 0;
1394         }
1395         if (s->elementary_transfer_size > 0) {
1396             /* there are some data left to transmit in this elementary
1397                transfer */
1398             size = s->cd_sector_size - s->io_buffer_index;
1399             if (size > s->elementary_transfer_size)
1400                 size = s->elementary_transfer_size;
1401             ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
1402                                size, ide_atapi_cmd_reply_end);
1403             s->packet_transfer_size -= size;
1404             s->elementary_transfer_size -= size;
1405             s->io_buffer_index += size;
1406         } else {
1407             /* a new transfer is needed */
1408             s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
1409             byte_count_limit = s->lcyl | (s->hcyl << 8);
1410 #ifdef DEBUG_IDE_ATAPI
1411             printf("byte_count_limit=%d\n", byte_count_limit);
1412 #endif
1413             if (byte_count_limit == 0xffff)
1414                 byte_count_limit--;
1415             size = s->packet_transfer_size;
1416             if (size > byte_count_limit) {
1417                 /* byte count limit must be even if this case */
1418                 if (byte_count_limit & 1)
1419                     byte_count_limit--;
1420                 size = byte_count_limit;
1421             }
1422             s->lcyl = size;
1423             s->hcyl = size >> 8;
1424             s->elementary_transfer_size = size;
1425             /* we cannot transmit more than one sector at a time */
1426             if (s->lba != -1) {
1427                 if (size > (s->cd_sector_size - s->io_buffer_index))
1428                     size = (s->cd_sector_size - s->io_buffer_index);
1429             }
1430             ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
1431                                size, ide_atapi_cmd_reply_end);
1432             s->packet_transfer_size -= size;
1433             s->elementary_transfer_size -= size;
1434             s->io_buffer_index += size;
1435             ide_set_irq(s);
1436 #ifdef DEBUG_IDE_ATAPI
1437             printf("status=0x%x\n", s->status);
1438 #endif
1439         }
1440     }
1441 }
1442
1443 /* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
1444 static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
1445 {
1446     if (size > max_size)
1447         size = max_size;
1448     s->lba = -1; /* no sector read */
1449     s->packet_transfer_size = size;
1450     s->io_buffer_size = size;    /* dma: send the reply data as one chunk */
1451     s->elementary_transfer_size = 0;
1452     s->io_buffer_index = 0;
1453
1454     if (s->atapi_dma) {
1455         s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
1456         ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
1457     } else {
1458         s->status = READY_STAT | SEEK_STAT;
1459         ide_atapi_cmd_reply_end(s);
1460     }
1461 }
1462
1463 /* start a CD-CDROM read command */
1464 static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
1465                                    int sector_size)
1466 {
1467     s->lba = lba;
1468     s->packet_transfer_size = nb_sectors * sector_size;
1469     s->elementary_transfer_size = 0;
1470     s->io_buffer_index = sector_size;
1471     s->cd_sector_size = sector_size;
1472
1473     s->status = READY_STAT | SEEK_STAT;
1474     ide_atapi_cmd_reply_end(s);
1475 }
1476
1477 /* ATAPI DMA support */
1478
1479 /* XXX: handle read errors */
1480 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret)
1481 {
1482     BMDMAState *bm = opaque;
1483     IDEState *s = bmdma_active_if(bm);
1484     int data_offset, n;
1485
1486     if (ret < 0) {
1487         ide_atapi_io_error(s, ret);
1488         goto eot;
1489     }
1490
1491     if (s->io_buffer_size > 0) {
1492         /*
1493          * For a cdrom read sector command (s->lba != -1),
1494          * adjust the lba for the next s->io_buffer_size chunk
1495          * and dma the current chunk.
1496          * For a command != read (s->lba == -1), just transfer
1497          * the reply data.
1498          */
1499         if (s->lba != -1) {
1500             if (s->cd_sector_size == 2352) {
1501                 n = 1;
1502                 cd_data_to_raw(s->io_buffer, s->lba);
1503             } else {
1504                 n = s->io_buffer_size >> 11;
1505             }
1506             s->lba += n;
1507         }
1508         s->packet_transfer_size -= s->io_buffer_size;
1509         if (dma_buf_rw(bm, 1) == 0)
1510             goto eot;
1511     }
1512
1513     if (s->packet_transfer_size <= 0) {
1514         s->status = READY_STAT | SEEK_STAT;
1515         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1516         ide_set_irq(s);
1517     eot:
1518         bm->status &= ~BM_STATUS_DMAING;
1519         bm->status |= BM_STATUS_INT;
1520         bm->dma_cb = NULL;
1521         bm->unit = -1;
1522         bm->aiocb = NULL;
1523         return;
1524     }
1525
1526     s->io_buffer_index = 0;
1527     if (s->cd_sector_size == 2352) {
1528         n = 1;
1529         s->io_buffer_size = s->cd_sector_size;
1530         data_offset = 16;
1531     } else {
1532         n = s->packet_transfer_size >> 11;
1533         if (n > (IDE_DMA_BUF_SECTORS / 4))
1534             n = (IDE_DMA_BUF_SECTORS / 4);
1535         s->io_buffer_size = n * 2048;
1536         data_offset = 0;
1537     }
1538 #ifdef DEBUG_AIO
1539     printf("aio_read_cd: lba=%u n=%d\n", s->lba, n);
1540 #endif
1541     bm->iov.iov_base = (void *)(s->io_buffer + data_offset);
1542     bm->iov.iov_len = n * 4 * 512;
1543     qemu_iovec_init_external(&bm->qiov, &bm->iov, 1);
1544     bm->aiocb = bdrv_aio_readv(s->bs, (int64_t)s->lba << 2, &bm->qiov,
1545                                n * 4, ide_atapi_cmd_read_dma_cb, bm);
1546     if (!bm->aiocb) {
1547         /* Note: media not present is the most likely case */
1548         ide_atapi_cmd_error(s, SENSE_NOT_READY,
1549                             ASC_MEDIUM_NOT_PRESENT);
1550         goto eot;
1551     }
1552 }
1553
1554 /* start a CD-CDROM read command with DMA */
1555 /* XXX: test if DMA is available */
1556 static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
1557                                    int sector_size)
1558 {
1559     s->lba = lba;
1560     s->packet_transfer_size = nb_sectors * sector_size;
1561     s->io_buffer_index = 0;
1562     s->io_buffer_size = 0;
1563     s->cd_sector_size = sector_size;
1564
1565     /* XXX: check if BUSY_STAT should be set */
1566     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
1567     ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
1568 }
1569
1570 static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors,
1571                                int sector_size)
1572 {
1573 #ifdef DEBUG_IDE_ATAPI
1574     printf("read %s: LBA=%d nb_sectors=%d\n", s->atapi_dma ? "dma" : "pio",
1575         lba, nb_sectors);
1576 #endif
1577     if (s->atapi_dma) {
1578         ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size);
1579     } else {
1580         ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size);
1581     }
1582 }
1583
1584 static inline uint8_t ide_atapi_set_profile(uint8_t *buf, uint8_t *index,
1585                                             uint16_t profile)
1586 {
1587     uint8_t *buf_profile = buf + 12; /* start of profiles */
1588
1589     buf_profile += ((*index) * 4); /* start of indexed profile */
1590     cpu_to_ube16 (buf_profile, profile);
1591     buf_profile[2] = ((buf_profile[0] == buf[6]) && (buf_profile[1] == buf[7]));
1592
1593     /* each profile adds 4 bytes to the response */
1594     (*index)++;
1595     buf[11] += 4; /* Additional Length */
1596
1597     return 4;
1598 }
1599
1600 static int ide_dvd_read_structure(IDEState *s, int format,
1601                                   const uint8_t *packet, uint8_t *buf)
1602 {
1603     switch (format) {
1604         case 0x0: /* Physical format information */
1605             {
1606                 int layer = packet[6];
1607                 uint64_t total_sectors;
1608
1609                 if (layer != 0)
1610                     return -ASC_INV_FIELD_IN_CMD_PACKET;
1611
1612                 bdrv_get_geometry(s->bs, &total_sectors);
1613                 total_sectors >>= 2;
1614                 if (total_sectors == 0)
1615                     return -ASC_MEDIUM_NOT_PRESENT;
1616
1617                 buf[4] = 1;   /* DVD-ROM, part version 1 */
1618                 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
1619                 buf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
1620                 buf[7] = 0;   /* default densities */
1621
1622                 /* FIXME: 0x30000 per spec? */
1623                 cpu_to_ube32(buf + 8, 0); /* start sector */
1624                 cpu_to_ube32(buf + 12, total_sectors - 1); /* end sector */
1625                 cpu_to_ube32(buf + 16, total_sectors - 1); /* l0 end sector */
1626
1627                 /* Size of buffer, not including 2 byte size field */
1628                 cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1629
1630                 /* 2k data + 4 byte header */
1631                 return (2048 + 4);
1632             }
1633
1634         case 0x01: /* DVD copyright information */
1635             buf[4] = 0; /* no copyright data */
1636             buf[5] = 0; /* no region restrictions */
1637
1638             /* Size of buffer, not including 2 byte size field */
1639             cpu_to_be16wu((uint16_t *)buf, 4 + 2);
1640
1641             /* 4 byte header + 4 byte data */
1642             return (4 + 4);
1643
1644         case 0x03: /* BCA information - invalid field for no BCA info */
1645             return -ASC_INV_FIELD_IN_CMD_PACKET;
1646
1647         case 0x04: /* DVD disc manufacturing information */
1648             /* Size of buffer, not including 2 byte size field */
1649             cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1650
1651             /* 2k data + 4 byte header */
1652             return (2048 + 4);
1653
1654         case 0xff:
1655             /*
1656              * This lists all the command capabilities above.  Add new ones
1657              * in order and update the length and buffer return values.
1658              */
1659
1660             buf[4] = 0x00; /* Physical format */
1661             buf[5] = 0x40; /* Not writable, is readable */
1662             cpu_to_be16wu((uint16_t *)(buf + 6), 2048 + 4);
1663
1664             buf[8] = 0x01; /* Copyright info */
1665             buf[9] = 0x40; /* Not writable, is readable */
1666             cpu_to_be16wu((uint16_t *)(buf + 10), 4 + 4);
1667
1668             buf[12] = 0x03; /* BCA info */
1669             buf[13] = 0x40; /* Not writable, is readable */
1670             cpu_to_be16wu((uint16_t *)(buf + 14), 188 + 4);
1671
1672             buf[16] = 0x04; /* Manufacturing info */
1673             buf[17] = 0x40; /* Not writable, is readable */
1674             cpu_to_be16wu((uint16_t *)(buf + 18), 2048 + 4);
1675
1676             /* Size of buffer, not including 2 byte size field */
1677             cpu_to_be16wu((uint16_t *)buf, 16 + 2);
1678
1679             /* data written + 4 byte header */
1680             return (16 + 4);
1681
1682         default: /* TODO: formats beyond DVD-ROM requires */
1683             return -ASC_INV_FIELD_IN_CMD_PACKET;
1684     }
1685 }
1686
1687 static void ide_atapi_cmd(IDEState *s)
1688 {
1689     const uint8_t *packet;
1690     uint8_t *buf;
1691     int max_len;
1692
1693     packet = s->io_buffer;
1694     buf = s->io_buffer;
1695 #ifdef DEBUG_IDE_ATAPI
1696     {
1697         int i;
1698         printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
1699         for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
1700             printf(" %02x", packet[i]);
1701         }
1702         printf("\n");
1703     }
1704 #endif
1705     /* If there's a UNIT_ATTENTION condition pending, only
1706        REQUEST_SENSE and INQUIRY commands are allowed to complete. */
1707     if (s->sense_key == SENSE_UNIT_ATTENTION &&
1708         s->io_buffer[0] != GPCMD_REQUEST_SENSE &&
1709         s->io_buffer[0] != GPCMD_INQUIRY) {
1710         ide_atapi_cmd_check_status(s);
1711         return;
1712     }
1713     switch(s->io_buffer[0]) {
1714     case GPCMD_TEST_UNIT_READY:
1715         if (bdrv_is_inserted(s->bs) && !s->cdrom_changed) {
1716             ide_atapi_cmd_ok(s);
1717         } else {
1718             s->cdrom_changed = 0;
1719             ide_atapi_cmd_error(s, SENSE_NOT_READY,
1720                                 ASC_MEDIUM_NOT_PRESENT);
1721         }
1722         break;
1723     case GPCMD_MODE_SENSE_6:
1724     case GPCMD_MODE_SENSE_10:
1725         {
1726             int action, code;
1727             if (packet[0] == GPCMD_MODE_SENSE_10)
1728                 max_len = ube16_to_cpu(packet + 7);
1729             else
1730                 max_len = packet[4];
1731             action = packet[2] >> 6;
1732             code = packet[2] & 0x3f;
1733             switch(action) {
1734             case 0: /* current values */
1735                 switch(code) {
1736                 case 0x01: /* error recovery */
1737                     cpu_to_ube16(&buf[0], 16 + 6);
1738                     buf[2] = 0x70;
1739                     buf[3] = 0;
1740                     buf[4] = 0;
1741                     buf[5] = 0;
1742                     buf[6] = 0;
1743                     buf[7] = 0;
1744
1745                     buf[8] = 0x01;
1746                     buf[9] = 0x06;
1747                     buf[10] = 0x00;
1748                     buf[11] = 0x05;
1749                     buf[12] = 0x00;
1750                     buf[13] = 0x00;
1751                     buf[14] = 0x00;
1752                     buf[15] = 0x00;
1753                     ide_atapi_cmd_reply(s, 16, max_len);
1754                     break;
1755                 case 0x2a:
1756                     cpu_to_ube16(&buf[0], 28 + 6);
1757                     buf[2] = 0x70;
1758                     buf[3] = 0;
1759                     buf[4] = 0;
1760                     buf[5] = 0;
1761                     buf[6] = 0;
1762                     buf[7] = 0;
1763
1764                     buf[8] = 0x2a;
1765                     buf[9] = 0x12;
1766                     buf[10] = 0x00;
1767                     buf[11] = 0x00;
1768
1769                     /* Claim PLAY_AUDIO capability (0x01) since some Linux
1770                        code checks for this to automount media. */
1771                     buf[12] = 0x71;
1772                     buf[13] = 3 << 5;
1773                     buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
1774                     if (bdrv_is_locked(s->bs))
1775                         buf[6] |= 1 << 1;
1776                     buf[15] = 0x00;
1777                     cpu_to_ube16(&buf[16], 706);
1778                     buf[18] = 0;
1779                     buf[19] = 2;
1780                     cpu_to_ube16(&buf[20], 512);
1781                     cpu_to_ube16(&buf[22], 706);
1782                     buf[24] = 0;
1783                     buf[25] = 0;
1784                     buf[26] = 0;
1785                     buf[27] = 0;
1786                     ide_atapi_cmd_reply(s, 28, max_len);
1787                     break;
1788                 default:
1789                     goto error_cmd;
1790                 }
1791                 break;
1792             case 1: /* changeable values */
1793                 goto error_cmd;
1794             case 2: /* default values */
1795                 goto error_cmd;
1796             default:
1797             case 3: /* saved values */
1798                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1799                                     ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
1800                 break;
1801             }
1802         }
1803         break;
1804     case GPCMD_REQUEST_SENSE:
1805         max_len = packet[4];
1806         memset(buf, 0, 18);
1807         buf[0] = 0x70 | (1 << 7);
1808         buf[2] = s->sense_key;
1809         buf[7] = 10;
1810         buf[12] = s->asc;
1811         if (s->sense_key == SENSE_UNIT_ATTENTION)
1812             s->sense_key = SENSE_NONE;
1813         ide_atapi_cmd_reply(s, 18, max_len);
1814         break;
1815     case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
1816         if (bdrv_is_inserted(s->bs)) {
1817             bdrv_set_locked(s->bs, packet[4] & 1);
1818             ide_atapi_cmd_ok(s);
1819         } else {
1820             ide_atapi_cmd_error(s, SENSE_NOT_READY,
1821                                 ASC_MEDIUM_NOT_PRESENT);
1822         }
1823         break;
1824     case GPCMD_READ_10:
1825     case GPCMD_READ_12:
1826         {
1827             int nb_sectors, lba;
1828
1829             if (packet[0] == GPCMD_READ_10)
1830                 nb_sectors = ube16_to_cpu(packet + 7);
1831             else
1832                 nb_sectors = ube32_to_cpu(packet + 6);
1833             lba = ube32_to_cpu(packet + 2);
1834             if (nb_sectors == 0) {
1835                 ide_atapi_cmd_ok(s);
1836                 break;
1837             }
1838             ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1839         }
1840         break;
1841     case GPCMD_READ_CD:
1842         {
1843             int nb_sectors, lba, transfer_request;
1844
1845             nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8];
1846             lba = ube32_to_cpu(packet + 2);
1847             if (nb_sectors == 0) {
1848                 ide_atapi_cmd_ok(s);
1849                 break;
1850             }
1851             transfer_request = packet[9];
1852             switch(transfer_request & 0xf8) {
1853             case 0x00:
1854                 /* nothing */
1855                 ide_atapi_cmd_ok(s);
1856                 break;
1857             case 0x10:
1858                 /* normal read */
1859                 ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1860                 break;
1861             case 0xf8:
1862                 /* read all data */
1863                 ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
1864                 break;
1865             default:
1866                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1867                                     ASC_INV_FIELD_IN_CMD_PACKET);
1868                 break;
1869             }
1870         }
1871         break;
1872     case GPCMD_SEEK:
1873         {
1874             unsigned int lba;
1875             uint64_t total_sectors;
1876
1877             bdrv_get_geometry(s->bs, &total_sectors);
1878             total_sectors >>= 2;
1879             if (total_sectors == 0) {
1880                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1881                                     ASC_MEDIUM_NOT_PRESENT);
1882                 break;
1883             }
1884             lba = ube32_to_cpu(packet + 2);
1885             if (lba >= total_sectors) {
1886                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1887                                     ASC_LOGICAL_BLOCK_OOR);
1888                 break;
1889             }
1890             ide_atapi_cmd_ok(s);
1891         }
1892         break;
1893     case GPCMD_START_STOP_UNIT:
1894         {
1895             int start, eject, err = 0;
1896             start = packet[4] & 1;
1897             eject = (packet[4] >> 1) & 1;
1898
1899             if (eject) {
1900                 err = bdrv_eject(s->bs, !start);
1901             }
1902
1903             switch (err) {
1904             case 0:
1905                 ide_atapi_cmd_ok(s);
1906                 break;
1907             case -EBUSY:
1908                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1909                                     ASC_MEDIA_REMOVAL_PREVENTED);
1910                 break;
1911             default:
1912                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1913                                     ASC_MEDIUM_NOT_PRESENT);
1914                 break;
1915             }
1916         }
1917         break;
1918     case GPCMD_MECHANISM_STATUS:
1919         {
1920             max_len = ube16_to_cpu(packet + 8);
1921             cpu_to_ube16(buf, 0);
1922             /* no current LBA */
1923             buf[2] = 0;
1924             buf[3] = 0;
1925             buf[4] = 0;
1926             buf[5] = 1;
1927             cpu_to_ube16(buf + 6, 0);
1928             ide_atapi_cmd_reply(s, 8, max_len);
1929         }
1930         break;
1931     case GPCMD_READ_TOC_PMA_ATIP:
1932         {
1933             int format, msf, start_track, len;
1934             uint64_t total_sectors;
1935
1936             bdrv_get_geometry(s->bs, &total_sectors);
1937             total_sectors >>= 2;
1938             if (total_sectors == 0) {
1939                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1940                                     ASC_MEDIUM_NOT_PRESENT);
1941                 break;
1942             }
1943             max_len = ube16_to_cpu(packet + 7);
1944             format = packet[9] >> 6;
1945             msf = (packet[1] >> 1) & 1;
1946             start_track = packet[6];
1947             switch(format) {
1948             case 0:
1949                 len = cdrom_read_toc(total_sectors, buf, msf, start_track);
1950                 if (len < 0)
1951                     goto error_cmd;
1952                 ide_atapi_cmd_reply(s, len, max_len);
1953                 break;
1954             case 1:
1955                 /* multi session : only a single session defined */
1956                 memset(buf, 0, 12);
1957                 buf[1] = 0x0a;
1958                 buf[2] = 0x01;
1959                 buf[3] = 0x01;
1960                 ide_atapi_cmd_reply(s, 12, max_len);
1961                 break;
1962             case 2:
1963                 len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
1964                 if (len < 0)
1965                     goto error_cmd;
1966                 ide_atapi_cmd_reply(s, len, max_len);
1967                 break;
1968             default:
1969             error_cmd:
1970                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1971                                     ASC_INV_FIELD_IN_CMD_PACKET);
1972                 break;
1973             }
1974         }
1975         break;
1976     case GPCMD_READ_CDVD_CAPACITY:
1977         {
1978             uint64_t total_sectors;
1979
1980             bdrv_get_geometry(s->bs, &total_sectors);
1981             total_sectors >>= 2;
1982             if (total_sectors == 0) {
1983                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1984                                     ASC_MEDIUM_NOT_PRESENT);
1985                 break;
1986             }
1987             /* NOTE: it is really the number of sectors minus 1 */
1988             cpu_to_ube32(buf, total_sectors - 1);
1989             cpu_to_ube32(buf + 4, 2048);
1990             ide_atapi_cmd_reply(s, 8, 8);
1991         }
1992         break;
1993     case GPCMD_READ_DVD_STRUCTURE:
1994         {
1995             int media = packet[1];
1996             int format = packet[7];
1997             int ret;
1998
1999             max_len = ube16_to_cpu(packet + 8);
2000
2001             if (format < 0xff) {
2002                 if (media_is_cd(s)) {
2003                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2004                                         ASC_INCOMPATIBLE_FORMAT);
2005                     break;
2006                 } else if (!media_present(s)) {
2007                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2008                                         ASC_INV_FIELD_IN_CMD_PACKET);
2009                     break;
2010                 }
2011             }
2012
2013             memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
2014                    IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
2015
2016             switch (format) {
2017                 case 0x00 ... 0x7f:
2018                 case 0xff:
2019                     if (media == 0) {
2020                         ret = ide_dvd_read_structure(s, format, packet, buf);
2021
2022                         if (ret < 0)
2023                             ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, -ret);
2024                         else
2025                             ide_atapi_cmd_reply(s, ret, max_len);
2026
2027                         break;
2028                     }
2029                     /* TODO: BD support, fall through for now */
2030
2031                 /* Generic disk structures */
2032                 case 0x80: /* TODO: AACS volume identifier */
2033                 case 0x81: /* TODO: AACS media serial number */
2034                 case 0x82: /* TODO: AACS media identifier */
2035                 case 0x83: /* TODO: AACS media key block */
2036                 case 0x90: /* TODO: List of recognized format layers */
2037                 case 0xc0: /* TODO: Write protection status */
2038                 default:
2039                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2040                                         ASC_INV_FIELD_IN_CMD_PACKET);
2041                     break;
2042             }
2043         }
2044         break;
2045     case GPCMD_SET_SPEED:
2046         ide_atapi_cmd_ok(s);
2047         break;
2048     case GPCMD_INQUIRY:
2049         max_len = packet[4];
2050         buf[0] = 0x05; /* CD-ROM */
2051         buf[1] = 0x80; /* removable */
2052         buf[2] = 0x00; /* ISO */
2053         buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
2054         buf[4] = 31; /* additional length */
2055         buf[5] = 0; /* reserved */
2056         buf[6] = 0; /* reserved */
2057         buf[7] = 0; /* reserved */
2058         padstr8(buf + 8, 8, "QEMU");
2059         padstr8(buf + 16, 16, "QEMU DVD-ROM");
2060         padstr8(buf + 32, 4, QEMU_VERSION);
2061         ide_atapi_cmd_reply(s, 36, max_len);
2062         break;
2063     case GPCMD_GET_CONFIGURATION:
2064         {
2065             uint32_t len;
2066             uint8_t index = 0;
2067
2068             /* only feature 0 is supported */
2069             if (packet[2] != 0 || packet[3] != 0) {
2070                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2071                                     ASC_INV_FIELD_IN_CMD_PACKET);
2072                 break;
2073             }
2074
2075             /* XXX: could result in alignment problems in some architectures */
2076             max_len = ube16_to_cpu(packet + 7);
2077
2078             /*
2079              * XXX: avoid overflow for io_buffer if max_len is bigger than
2080              *      the size of that buffer (dimensioned to max number of
2081              *      sectors to transfer at once)
2082              *
2083              *      Only a problem if the feature/profiles grow.
2084              */
2085             if (max_len > 512) /* XXX: assume 1 sector */
2086                 max_len = 512;
2087
2088             memset(buf, 0, max_len);
2089             /* 
2090              * the number of sectors from the media tells us which profile
2091              * to use as current.  0 means there is no media
2092              */
2093             if (media_is_dvd(s))
2094                 cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
2095             else if (media_is_cd(s))
2096                 cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
2097
2098             buf[10] = 0x02 | 0x01; /* persistent and current */
2099             len = 12; /* headers: 8 + 4 */
2100             len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
2101             len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
2102             cpu_to_ube32(buf, len - 4); /* data length */
2103
2104             ide_atapi_cmd_reply(s, len, max_len);
2105             break;
2106         }
2107     default:
2108         ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2109                             ASC_ILLEGAL_OPCODE);
2110         break;
2111     }
2112 }
2113
2114 static void ide_cfata_metadata_inquiry(IDEState *s)
2115 {
2116     uint16_t *p;
2117     uint32_t spd;
2118
2119     p = (uint16_t *) s->io_buffer;
2120     memset(p, 0, 0x200);
2121     spd = ((s->mdata_size - 1) >> 9) + 1;
2122
2123     put_le16(p + 0, 0x0001);                    /* Data format revision */
2124     put_le16(p + 1, 0x0000);                    /* Media property: silicon */
2125     put_le16(p + 2, s->media_changed);          /* Media status */
2126     put_le16(p + 3, s->mdata_size & 0xffff);    /* Capacity in bytes (low) */
2127     put_le16(p + 4, s->mdata_size >> 16);       /* Capacity in bytes (high) */
2128     put_le16(p + 5, spd & 0xffff);              /* Sectors per device (low) */
2129     put_le16(p + 6, spd >> 16);                 /* Sectors per device (high) */
2130 }
2131
2132 static void ide_cfata_metadata_read(IDEState *s)
2133 {
2134     uint16_t *p;
2135
2136     if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
2137         s->status = ERR_STAT;
2138         s->error = ABRT_ERR;
2139         return;
2140     }
2141
2142     p = (uint16_t *) s->io_buffer;
2143     memset(p, 0, 0x200);
2144
2145     put_le16(p + 0, s->media_changed);          /* Media status */
2146     memcpy(p + 1, s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
2147                     MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
2148                                     s->nsector << 9), 0x200 - 2));
2149 }
2150
2151 static void ide_cfata_metadata_write(IDEState *s)
2152 {
2153     if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
2154         s->status = ERR_STAT;
2155         s->error = ABRT_ERR;
2156         return;
2157     }
2158
2159     s->media_changed = 0;
2160
2161     memcpy(s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
2162                     s->io_buffer + 2,
2163                     MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
2164                                     s->nsector << 9), 0x200 - 2));
2165 }
2166
2167 /* called when the inserted state of the media has changed */
2168 static void cdrom_change_cb(void *opaque)
2169 {
2170     IDEState *s = opaque;
2171     uint64_t nb_sectors;
2172
2173     bdrv_get_geometry(s->bs, &nb_sectors);
2174     s->nb_sectors = nb_sectors;
2175
2176     s->sense_key = SENSE_UNIT_ATTENTION;
2177     s->asc = ASC_MEDIUM_MAY_HAVE_CHANGED;
2178     s->cdrom_changed = 1;
2179     ide_set_irq(s);
2180 }
2181
2182 static void ide_cmd_lba48_transform(IDEState *s, int lba48)
2183 {
2184     s->lba48 = lba48;
2185
2186     /* handle the 'magic' 0 nsector count conversion here. to avoid
2187      * fiddling with the rest of the read logic, we just store the
2188      * full sector count in ->nsector and ignore ->hob_nsector from now
2189      */
2190     if (!s->lba48) {
2191         if (!s->nsector)
2192             s->nsector = 256;
2193     } else {
2194         if (!s->nsector && !s->hob_nsector)
2195             s->nsector = 65536;
2196         else {
2197             int lo = s->nsector;
2198             int hi = s->hob_nsector;
2199
2200             s->nsector = (hi << 8) | lo;
2201         }
2202     }
2203 }
2204
2205 static void ide_clear_hob(IDEBus *bus)
2206 {
2207     /* any write clears HOB high bit of device control register */
2208     bus->ifs[0].select &= ~(1 << 7);
2209     bus->ifs[1].select &= ~(1 << 7);
2210 }
2211
2212 static void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
2213 {
2214     IDEBus *bus = opaque;
2215     IDEState *s;
2216     int n;
2217     int lba48 = 0;
2218
2219 #ifdef DEBUG_IDE
2220     printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
2221 #endif
2222
2223     addr &= 7;
2224
2225     /* ignore writes to command block while busy with previous command */
2226     if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
2227         return;
2228
2229     switch(addr) {
2230     case 0:
2231         break;
2232     case 1:
2233         ide_clear_hob(bus);
2234         /* NOTE: data is written to the two drives */
2235         bus->ifs[0].hob_feature = bus->ifs[0].feature;
2236         bus->ifs[1].hob_feature = bus->ifs[1].feature;
2237         bus->ifs[0].feature = val;
2238         bus->ifs[1].feature = val;
2239         break;
2240     case 2:
2241         ide_clear_hob(bus);
2242         bus->ifs[0].hob_nsector = bus->ifs[0].nsector;
2243         bus->ifs[1].hob_nsector = bus->ifs[1].nsector;
2244         bus->ifs[0].nsector = val;
2245         bus->ifs[1].nsector = val;
2246         break;
2247     case 3:
2248         ide_clear_hob(bus);
2249         bus->ifs[0].hob_sector = bus->ifs[0].sector;
2250         bus->ifs[1].hob_sector = bus->ifs[1].sector;
2251         bus->ifs[0].sector = val;
2252         bus->ifs[1].sector = val;
2253         break;
2254     case 4:
2255         ide_clear_hob(bus);
2256         bus->ifs[0].hob_lcyl = bus->ifs[0].lcyl;
2257         bus->ifs[1].hob_lcyl = bus->ifs[1].lcyl;
2258         bus->ifs[0].lcyl = val;
2259         bus->ifs[1].lcyl = val;
2260         break;
2261     case 5:
2262         ide_clear_hob(bus);
2263         bus->ifs[0].hob_hcyl = bus->ifs[0].hcyl;
2264         bus->ifs[1].hob_hcyl = bus->ifs[1].hcyl;
2265         bus->ifs[0].hcyl = val;
2266         bus->ifs[1].hcyl = val;
2267         break;
2268     case 6:
2269         /* FIXME: HOB readback uses bit 7 */
2270         bus->ifs[0].select = (val & ~0x10) | 0xa0;
2271         bus->ifs[1].select = (val | 0x10) | 0xa0;
2272         /* select drive */
2273         bus->unit = (val >> 4) & 1;
2274         break;
2275     default:
2276     case 7:
2277         /* command */
2278 #if defined(DEBUG_IDE)
2279         printf("ide: CMD=%02x\n", val);
2280 #endif
2281         s = idebus_active_if(bus);
2282         /* ignore commands to non existant slave */
2283         if (s != bus->ifs && !s->bs)
2284             break;
2285
2286         /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */
2287         if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)
2288             break;
2289
2290         switch(val) {
2291         case WIN_IDENTIFY:
2292             if (s->bs && !s->is_cdrom) {
2293                 if (!s->is_cf)
2294                     ide_identify(s);
2295                 else
2296                     ide_cfata_identify(s);
2297                 s->status = READY_STAT | SEEK_STAT;
2298                 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
2299             } else {
2300                 if (s->is_cdrom) {
2301                     ide_set_signature(s);
2302                 }
2303                 ide_abort_command(s);
2304             }
2305             ide_set_irq(s);
2306             break;
2307         case WIN_SPECIFY:
2308         case WIN_RECAL:
2309             s->error = 0;
2310             s->status = READY_STAT | SEEK_STAT;
2311             ide_set_irq(s);
2312             break;
2313         case WIN_SETMULT:
2314             if (s->is_cf && s->nsector == 0) {
2315                 /* Disable Read and Write Multiple */
2316                 s->mult_sectors = 0;
2317                 s->status = READY_STAT | SEEK_STAT;
2318             } else if ((s->nsector & 0xff) != 0 &&
2319                 ((s->nsector & 0xff) > MAX_MULT_SECTORS ||
2320                  (s->nsector & (s->nsector - 1)) != 0)) {
2321                 ide_abort_command(s);
2322             } else {
2323                 s->mult_sectors = s->nsector & 0xff;
2324                 s->status = READY_STAT | SEEK_STAT;
2325             }
2326             ide_set_irq(s);
2327             break;
2328         case WIN_VERIFY_EXT:
2329             lba48 = 1;
2330         case WIN_VERIFY:
2331         case WIN_VERIFY_ONCE:
2332             /* do sector number check ? */
2333             ide_cmd_lba48_transform(s, lba48);
2334             s->status = READY_STAT | SEEK_STAT;
2335             ide_set_irq(s);
2336             break;
2337         case WIN_READ_EXT:
2338             lba48 = 1;
2339         case WIN_READ:
2340         case WIN_READ_ONCE:
2341             if (!s->bs)
2342                 goto abort_cmd;
2343             ide_cmd_lba48_transform(s, lba48);
2344             s->req_nb_sectors = 1;
2345             ide_sector_read(s);
2346             break;
2347         case WIN_WRITE_EXT:
2348             lba48 = 1;
2349         case WIN_WRITE:
2350         case WIN_WRITE_ONCE:
2351         case CFA_WRITE_SECT_WO_ERASE:
2352         case WIN_WRITE_VERIFY:
2353             ide_cmd_lba48_transform(s, lba48);
2354             s->error = 0;
2355             s->status = SEEK_STAT | READY_STAT;
2356             s->req_nb_sectors = 1;
2357             ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);
2358             s->media_changed = 1;
2359             break;
2360         case WIN_MULTREAD_EXT:
2361             lba48 = 1;
2362         case WIN_MULTREAD:
2363             if (!s->mult_sectors)
2364                 goto abort_cmd;
2365             ide_cmd_lba48_transform(s, lba48);
2366             s->req_nb_sectors = s->mult_sectors;
2367             ide_sector_read(s);
2368             break;
2369         case WIN_MULTWRITE_EXT:
2370             lba48 = 1;
2371         case WIN_MULTWRITE:
2372         case CFA_WRITE_MULTI_WO_ERASE:
2373             if (!s->mult_sectors)
2374                 goto abort_cmd;
2375             ide_cmd_lba48_transform(s, lba48);
2376             s->error = 0;
2377             s->status = SEEK_STAT | READY_STAT;
2378             s->req_nb_sectors = s->mult_sectors;
2379             n = s->nsector;
2380             if (n > s->req_nb_sectors)
2381                 n = s->req_nb_sectors;
2382             ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);
2383             s->media_changed = 1;
2384             break;
2385         case WIN_READDMA_EXT:
2386             lba48 = 1;
2387         case WIN_READDMA:
2388         case WIN_READDMA_ONCE:
2389             if (!s->bs)
2390                 goto abort_cmd;
2391             ide_cmd_lba48_transform(s, lba48);
2392             ide_sector_read_dma(s);
2393             break;
2394         case WIN_WRITEDMA_EXT:
2395             lba48 = 1;
2396         case WIN_WRITEDMA:
2397         case WIN_WRITEDMA_ONCE:
2398             if (!s->bs)
2399                 goto abort_cmd;
2400             ide_cmd_lba48_transform(s, lba48);
2401             ide_sector_write_dma(s);
2402             s->media_changed = 1;
2403             break;
2404         case WIN_READ_NATIVE_MAX_EXT:
2405             lba48 = 1;
2406         case WIN_READ_NATIVE_MAX:
2407             ide_cmd_lba48_transform(s, lba48);
2408             ide_set_sector(s, s->nb_sectors - 1);
2409             s->status = READY_STAT | SEEK_STAT;
2410             ide_set_irq(s);
2411             break;
2412         case WIN_CHECKPOWERMODE1:
2413         case WIN_CHECKPOWERMODE2:
2414             s->nsector = 0xff; /* device active or idle */
2415             s->status = READY_STAT | SEEK_STAT;
2416             ide_set_irq(s);
2417             break;
2418         case WIN_SETFEATURES:
2419             if (!s->bs)
2420                 goto abort_cmd;
2421             /* XXX: valid for CDROM ? */
2422             switch(s->feature) {
2423             case 0xcc: /* reverting to power-on defaults enable */
2424             case 0x66: /* reverting to power-on defaults disable */
2425             case 0x02: /* write cache enable */
2426             case 0x82: /* write cache disable */
2427             case 0xaa: /* read look-ahead enable */
2428             case 0x55: /* read look-ahead disable */
2429             case 0x05: /* set advanced power management mode */
2430             case 0x85: /* disable advanced power management mode */
2431             case 0x69: /* NOP */
2432             case 0x67: /* NOP */
2433             case 0x96: /* NOP */
2434             case 0x9a: /* NOP */
2435             case 0x42: /* enable Automatic Acoustic Mode */
2436             case 0xc2: /* disable Automatic Acoustic Mode */
2437                 s->status = READY_STAT | SEEK_STAT;
2438                 ide_set_irq(s);
2439                 break;
2440             case 0x03: { /* set transfer mode */
2441                 uint8_t val = s->nsector & 0x07;
2442
2443                 switch (s->nsector >> 3) {
2444                     case 0x00: /* pio default */
2445                     case 0x01: /* pio mode */
2446                         put_le16(s->identify_data + 62,0x07);
2447                         put_le16(s->identify_data + 63,0x07);
2448                         put_le16(s->identify_data + 88,0x3f);
2449                         break;
2450                     case 0x02: /* sigle word dma mode*/
2451                         put_le16(s->identify_data + 62,0x07 | (1 << (val + 8)));
2452                         put_le16(s->identify_data + 63,0x07);
2453                         put_le16(s->identify_data + 88,0x3f);
2454                         break;
2455                     case 0x04: /* mdma mode */
2456                         put_le16(s->identify_data + 62,0x07);
2457                         put_le16(s->identify_data + 63,0x07 | (1 << (val + 8)));
2458                         put_le16(s->identify_data + 88,0x3f);
2459                         break;
2460                     case 0x08: /* udma mode */
2461                         put_le16(s->identify_data + 62,0x07);
2462                         put_le16(s->identify_data + 63,0x07);
2463                         put_le16(s->identify_data + 88,0x3f | (1 << (val + 8)));
2464                         break;
2465                     default:
2466                         goto abort_cmd;
2467                 }
2468                 s->status = READY_STAT | SEEK_STAT;
2469                 ide_set_irq(s);
2470                 break;
2471             }
2472             default:
2473                 goto abort_cmd;
2474             }
2475             break;
2476         case WIN_FLUSH_CACHE:
2477         case WIN_FLUSH_CACHE_EXT:
2478             if (s->bs)
2479                 bdrv_flush(s->bs);
2480             s->status = READY_STAT | SEEK_STAT;
2481             ide_set_irq(s);
2482             break;
2483         case WIN_STANDBY:
2484         case WIN_STANDBY2:
2485         case WIN_STANDBYNOW1:
2486         case WIN_STANDBYNOW2:
2487         case WIN_IDLEIMMEDIATE:
2488         case CFA_IDLEIMMEDIATE:
2489         case WIN_SETIDLE1:
2490         case WIN_SETIDLE2:
2491         case WIN_SLEEPNOW1:
2492         case WIN_SLEEPNOW2:
2493             s->status = READY_STAT;
2494             ide_set_irq(s);
2495             break;
2496         case WIN_SEEK:
2497             if(s->is_cdrom)
2498                 goto abort_cmd;
2499             /* XXX: Check that seek is within bounds */
2500             s->status = READY_STAT | SEEK_STAT;
2501             ide_set_irq(s);
2502             break;
2503             /* ATAPI commands */
2504         case WIN_PIDENTIFY:
2505             if (s->is_cdrom) {
2506                 ide_atapi_identify(s);
2507                 s->status = READY_STAT | SEEK_STAT;
2508                 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
2509             } else {
2510                 ide_abort_command(s);
2511             }
2512             ide_set_irq(s);
2513             break;
2514         case WIN_DIAGNOSE:
2515             ide_set_signature(s);
2516             if (s->is_cdrom)
2517                 s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet
2518                                 * devices to return a clear status register
2519                                 * with READY_STAT *not* set. */
2520             else
2521                 s->status = READY_STAT | SEEK_STAT;
2522             s->error = 0x01; /* Device 0 passed, Device 1 passed or not
2523                               * present. 
2524                               */
2525             ide_set_irq(s);
2526             break;
2527         case WIN_SRST:
2528             if (!s->is_cdrom)
2529                 goto abort_cmd;
2530             ide_set_signature(s);
2531             s->status = 0x00; /* NOTE: READY is _not_ set */
2532             s->error = 0x01;
2533             break;
2534         case WIN_PACKETCMD:
2535             if (!s->is_cdrom)
2536                 goto abort_cmd;
2537             /* overlapping commands not supported */
2538             if (s->feature & 0x02)
2539                 goto abort_cmd;
2540             s->status = READY_STAT | SEEK_STAT;
2541             s->atapi_dma = s->feature & 1;
2542             s->nsector = 1;
2543             ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
2544                                ide_atapi_cmd);
2545             break;
2546         /* CF-ATA commands */
2547         case CFA_REQ_EXT_ERROR_CODE:
2548             if (!s->is_cf)
2549                 goto abort_cmd;
2550             s->error = 0x09;    /* miscellaneous error */
2551             s->status = READY_STAT | SEEK_STAT;
2552             ide_set_irq(s);
2553             break;
2554         case CFA_ERASE_SECTORS:
2555         case CFA_WEAR_LEVEL:
2556             if (!s->is_cf)
2557                 goto abort_cmd;
2558             if (val == CFA_WEAR_LEVEL)
2559                 s->nsector = 0;
2560             if (val == CFA_ERASE_SECTORS)
2561                 s->media_changed = 1;
2562             s->error = 0x00;
2563             s->status = READY_STAT | SEEK_STAT;
2564             ide_set_irq(s);
2565             break;
2566         case CFA_TRANSLATE_SECTOR:
2567             if (!s->is_cf)
2568                 goto abort_cmd;
2569             s->error = 0x00;
2570             s->status = READY_STAT | SEEK_STAT;
2571             memset(s->io_buffer, 0, 0x200);
2572             s->io_buffer[0x00] = s->hcyl;                       /* Cyl MSB */
2573             s->io_buffer[0x01] = s->lcyl;                       /* Cyl LSB */
2574             s->io_buffer[0x02] = s->select;                     /* Head */
2575             s->io_buffer[0x03] = s->sector;                     /* Sector */
2576             s->io_buffer[0x04] = ide_get_sector(s) >> 16;       /* LBA MSB */
2577             s->io_buffer[0x05] = ide_get_sector(s) >> 8;        /* LBA */
2578             s->io_buffer[0x06] = ide_get_sector(s) >> 0;        /* LBA LSB */
2579             s->io_buffer[0x13] = 0x00;                          /* Erase flag */
2580             s->io_buffer[0x18] = 0x00;                          /* Hot count */
2581             s->io_buffer[0x19] = 0x00;                          /* Hot count */
2582             s->io_buffer[0x1a] = 0x01;                          /* Hot count */
2583             ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2584             ide_set_irq(s);
2585             break;
2586         case CFA_ACCESS_METADATA_STORAGE:
2587             if (!s->is_cf)
2588                 goto abort_cmd;
2589             switch (s->feature) {
2590             case 0x02:  /* Inquiry Metadata Storage */
2591                 ide_cfata_metadata_inquiry(s);
2592                 break;
2593             case 0x03:  /* Read Metadata Storage */
2594                 ide_cfata_metadata_read(s);
2595                 break;
2596             case 0x04:  /* Write Metadata Storage */
2597                 ide_cfata_metadata_write(s);
2598                 break;
2599             default:
2600                 goto abort_cmd;
2601             }
2602             ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2603             s->status = 0x00; /* NOTE: READY is _not_ set */
2604             ide_set_irq(s);
2605             break;
2606         case IBM_SENSE_CONDITION:
2607             if (!s->is_cf)
2608                 goto abort_cmd;
2609             switch (s->feature) {
2610             case 0x01:  /* sense temperature in device */
2611                 s->nsector = 0x50;      /* +20 C */
2612                 break;
2613             default:
2614                 goto abort_cmd;
2615             }
2616             s->status = READY_STAT | SEEK_STAT;
2617             ide_set_irq(s);
2618             break;
2619
2620         case WIN_SMART:
2621             if (s->is_cdrom)
2622                 goto abort_cmd;
2623             if (s->hcyl != 0xc2 || s->lcyl != 0x4f)
2624                 goto abort_cmd;
2625             if (!s->smart_enabled && s->feature != SMART_ENABLE)
2626                 goto abort_cmd;
2627             switch (s->feature) {
2628             case SMART_DISABLE:
2629                 s->smart_enabled = 0;
2630                 s->status = READY_STAT | SEEK_STAT;
2631                 ide_set_irq(s);
2632                 break;
2633             case SMART_ENABLE:
2634                 s->smart_enabled = 1;
2635                 s->status = READY_STAT | SEEK_STAT;
2636                 ide_set_irq(s);
2637                 break;
2638             case SMART_ATTR_AUTOSAVE:
2639                 switch (s->sector) {
2640                 case 0x00:
2641                     s->smart_autosave = 0;
2642                     break;
2643                 case 0xf1:
2644                     s->smart_autosave = 1;
2645                     break;
2646                 default:
2647                     goto abort_cmd;
2648                 }
2649                 s->status = READY_STAT | SEEK_STAT;
2650                 ide_set_irq(s);
2651                 break;
2652             case SMART_STATUS:
2653                 if (!s->smart_errors) {
2654                     s->hcyl = 0xc2;
2655                     s->lcyl = 0x4f;
2656                 } else {
2657                     s->hcyl = 0x2c;
2658                     s->lcyl = 0xf4;
2659                 }
2660                 s->status = READY_STAT | SEEK_STAT;
2661                 ide_set_irq(s);
2662                 break;
2663             case SMART_READ_THRESH:
2664                 memset(s->io_buffer, 0, 0x200);
2665                 s->io_buffer[0] = 0x01; /* smart struct version */
2666                 for (n=0; n<30; n++) {
2667                     if (smart_attributes[n][0] == 0)
2668                         break;
2669                     s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2670                     s->io_buffer[2+1+(n*12)] = smart_attributes[n][4];
2671                 }
2672                 for (n=0; n<511; n++) /* checksum */
2673                     s->io_buffer[511] += s->io_buffer[n];
2674                 s->io_buffer[511] = 0x100 - s->io_buffer[511];
2675                 s->status = READY_STAT | SEEK_STAT;
2676                 ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2677                 ide_set_irq(s);
2678                 break;
2679             case SMART_READ_DATA:
2680                 memset(s->io_buffer, 0, 0x200);
2681                 s->io_buffer[0] = 0x01; /* smart struct version */
2682                 for (n=0; n<30; n++) {
2683                     if (smart_attributes[n][0] == 0)
2684                         break;
2685                     s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2686                     s->io_buffer[2+1+(n*12)] = smart_attributes[n][1];
2687                     s->io_buffer[2+3+(n*12)] = smart_attributes[n][2];
2688                     s->io_buffer[2+4+(n*12)] = smart_attributes[n][3];
2689                 }
2690                 s->io_buffer[362] = 0x02 | (s->smart_autosave?0x80:0x00);
2691                 if (s->smart_selftest_count == 0) {
2692                     s->io_buffer[363] = 0;
2693                 } else {
2694                     s->io_buffer[363] = 
2695                         s->smart_selftest_data[3 + 
2696                                                (s->smart_selftest_count - 1) * 
2697                                                24];
2698                 }
2699                 s->io_buffer[364] = 0x20; 
2700                 s->io_buffer[365] = 0x01; 
2701                 /* offline data collection capacity: execute + self-test*/
2702                 s->io_buffer[367] = (1<<4 | 1<<3 | 1); 
2703                 s->io_buffer[368] = 0x03; /* smart capability (1) */
2704                 s->io_buffer[369] = 0x00; /* smart capability (2) */
2705                 s->io_buffer[370] = 0x01; /* error logging supported */
2706                 s->io_buffer[372] = 0x02; /* minutes for poll short test */
2707                 s->io_buffer[373] = 0x36; /* minutes for poll ext test */
2708                 s->io_buffer[374] = 0x01; /* minutes for poll conveyance */
2709
2710                 for (n=0; n<511; n++) 
2711                     s->io_buffer[511] += s->io_buffer[n];
2712                 s->io_buffer[511] = 0x100 - s->io_buffer[511];
2713                 s->status = READY_STAT | SEEK_STAT;
2714                 ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2715                 ide_set_irq(s);
2716                 break;
2717             case SMART_READ_LOG:
2718                 switch (s->sector) {
2719                 case 0x01: /* summary smart error log */
2720                     memset(s->io_buffer, 0, 0x200);
2721                     s->io_buffer[0] = 0x01;
2722                     s->io_buffer[1] = 0x00; /* no error entries */
2723                     s->io_buffer[452] = s->smart_errors & 0xff;
2724                     s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;
2725
2726                     for (n=0; n<511; n++)
2727                         s->io_buffer[511] += s->io_buffer[n];
2728                     s->io_buffer[511] = 0x100 - s->io_buffer[511];
2729                     break;
2730                 case 0x06: /* smart self test log */
2731                     memset(s->io_buffer, 0, 0x200);
2732                     s->io_buffer[0] = 0x01; 
2733                     if (s->smart_selftest_count == 0) {
2734                         s->io_buffer[508] = 0;
2735                     } else {
2736                         s->io_buffer[508] = s->smart_selftest_count;
2737                         for (n=2; n<506; n++) 
2738                             s->io_buffer[n] = s->smart_selftest_data[n];
2739                     }               
2740                     for (n=0; n<511; n++)
2741                         s->io_buffer[511] += s->io_buffer[n];
2742                     s->io_buffer[511] = 0x100 - s->io_buffer[511];
2743                     break;
2744                 default:
2745                     goto abort_cmd;
2746                 }
2747                 s->status = READY_STAT | SEEK_STAT;
2748                 ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2749                 ide_set_irq(s);
2750                 break;
2751             case SMART_EXECUTE_OFFLINE:
2752                 switch (s->sector) {
2753                 case 0: /* off-line routine */
2754                 case 1: /* short self test */
2755                 case 2: /* extended self test */
2756                     s->smart_selftest_count++;
2757                     if(s->smart_selftest_count > 21)
2758                         s->smart_selftest_count = 0;
2759                     n = 2 + (s->smart_selftest_count - 1) * 24;
2760                     s->smart_selftest_data[n] = s->sector;
2761                     s->smart_selftest_data[n+1] = 0x00; /* OK and finished */
2762                     s->smart_selftest_data[n+2] = 0x34; /* hour count lsb */
2763                     s->smart_selftest_data[n+3] = 0x12; /* hour count msb */
2764                     s->status = READY_STAT | SEEK_STAT;
2765                     ide_set_irq(s);
2766                     break;
2767                 default:
2768                     goto abort_cmd;
2769                 }
2770                 break;
2771             default:
2772                 goto abort_cmd;
2773             }
2774             break;
2775         default:
2776         abort_cmd:
2777             ide_abort_command(s);
2778             ide_set_irq(s);
2779             break;
2780         }
2781     }
2782 }
2783
2784 static uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
2785 {
2786     IDEBus *bus = opaque;
2787     IDEState *s = idebus_active_if(bus);
2788     uint32_t addr;
2789     int ret, hob;
2790
2791     addr = addr1 & 7;
2792     /* FIXME: HOB readback uses bit 7, but it's always set right now */
2793     //hob = s->select & (1 << 7);
2794     hob = 0;
2795     switch(addr) {
2796     case 0:
2797         ret = 0xff;
2798         break;
2799     case 1:
2800         if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2801             (s != bus->ifs && !s->bs))
2802             ret = 0;
2803         else if (!hob)
2804             ret = s->error;
2805         else
2806             ret = s->hob_feature;
2807         break;
2808     case 2:
2809         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2810             ret = 0;
2811         else if (!hob)
2812             ret = s->nsector & 0xff;
2813         else
2814             ret = s->hob_nsector;
2815         break;
2816     case 3:
2817         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2818             ret = 0;
2819         else if (!hob)
2820             ret = s->sector;
2821         else
2822             ret = s->hob_sector;
2823         break;
2824     case 4:
2825         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2826             ret = 0;
2827         else if (!hob)
2828             ret = s->lcyl;
2829         else
2830             ret = s->hob_lcyl;
2831         break;
2832     case 5:
2833         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2834             ret = 0;
2835         else if (!hob)
2836             ret = s->hcyl;
2837         else
2838             ret = s->hob_hcyl;
2839         break;
2840     case 6:
2841         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2842             ret = 0;
2843         else
2844             ret = s->select;
2845         break;
2846     default:
2847     case 7:
2848         if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2849             (s != bus->ifs && !s->bs))
2850             ret = 0;
2851         else
2852             ret = s->status;
2853         qemu_irq_lower(s->irq);
2854         break;
2855     }
2856 #ifdef DEBUG_IDE
2857     printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
2858 #endif
2859     return ret;
2860 }
2861
2862 static uint32_t ide_status_read(void *opaque, uint32_t addr)
2863 {
2864     IDEBus *bus = opaque;
2865     IDEState *s = idebus_active_if(bus);
2866     int ret;
2867
2868     if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2869         (s != bus->ifs && !s->bs))
2870         ret = 0;
2871     else
2872         ret = s->status;
2873 #ifdef DEBUG_IDE
2874     printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
2875 #endif
2876     return ret;
2877 }
2878
2879 static void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
2880 {
2881     IDEBus *bus = opaque;
2882     IDEState *s;
2883     int i;
2884
2885 #ifdef DEBUG_IDE
2886     printf("ide: write control addr=0x%x val=%02x\n", addr, val);
2887 #endif
2888     /* common for both drives */
2889     if (!(bus->ifs[0].cmd & IDE_CMD_RESET) &&
2890         (val & IDE_CMD_RESET)) {
2891         /* reset low to high */
2892         for(i = 0;i < 2; i++) {
2893             s = &bus->ifs[i];
2894             s->status = BUSY_STAT | SEEK_STAT;
2895             s->error = 0x01;
2896         }
2897     } else if ((bus->ifs[0].cmd & IDE_CMD_RESET) &&
2898                !(val & IDE_CMD_RESET)) {
2899         /* high to low */
2900         for(i = 0;i < 2; i++) {
2901             s = &bus->ifs[i];
2902             if (s->is_cdrom)
2903                 s->status = 0x00; /* NOTE: READY is _not_ set */
2904             else
2905                 s->status = READY_STAT | SEEK_STAT;
2906             ide_set_signature(s);
2907         }
2908     }
2909
2910     bus->ifs[0].cmd = val;
2911     bus->ifs[1].cmd = val;
2912 }
2913
2914 static void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
2915 {
2916     IDEBus *bus = opaque;
2917     IDEState *s = idebus_active_if(bus);
2918     uint8_t *p;
2919
2920     /* PIO data access allowed only when DRQ bit is set */
2921     if (!(s->status & DRQ_STAT))
2922         return;
2923
2924     p = s->data_ptr;
2925     *(uint16_t *)p = le16_to_cpu(val);
2926     p += 2;
2927     s->data_ptr = p;
2928     if (p >= s->data_end)
2929         s->end_transfer_func(s);
2930 }
2931
2932 static uint32_t ide_data_readw(void *opaque, uint32_t addr)
2933 {
2934     IDEBus *bus = opaque;
2935     IDEState *s = idebus_active_if(bus);
2936     uint8_t *p;
2937     int ret;
2938
2939     /* PIO data access allowed only when DRQ bit is set */
2940     if (!(s->status & DRQ_STAT))
2941         return 0;
2942
2943     p = s->data_ptr;
2944     ret = cpu_to_le16(*(uint16_t *)p);
2945     p += 2;
2946     s->data_ptr = p;
2947     if (p >= s->data_end)
2948         s->end_transfer_func(s);
2949     return ret;
2950 }
2951
2952 static void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
2953 {
2954     IDEBus *bus = opaque;
2955     IDEState *s = idebus_active_if(bus);
2956     uint8_t *p;
2957
2958     /* PIO data access allowed only when DRQ bit is set */
2959     if (!(s->status & DRQ_STAT))
2960         return;
2961
2962     p = s->data_ptr;
2963     *(uint32_t *)p = le32_to_cpu(val);
2964     p += 4;
2965     s->data_ptr = p;
2966     if (p >= s->data_end)
2967         s->end_transfer_func(s);
2968 }
2969
2970 static uint32_t ide_data_readl(void *opaque, uint32_t addr)
2971 {
2972     IDEBus *bus = opaque;
2973     IDEState *s = idebus_active_if(bus);
2974     uint8_t *p;
2975     int ret;
2976
2977     /* PIO data access allowed only when DRQ bit is set */
2978     if (!(s->status & DRQ_STAT))
2979         return 0;
2980
2981     p = s->data_ptr;
2982     ret = cpu_to_le32(*(uint32_t *)p);
2983     p += 4;
2984     s->data_ptr = p;
2985     if (p >= s->data_end)
2986         s->end_transfer_func(s);
2987     return ret;
2988 }
2989
2990 static void ide_dummy_transfer_stop(IDEState *s)
2991 {
2992     s->data_ptr = s->io_buffer;
2993     s->data_end = s->io_buffer;
2994     s->io_buffer[0] = 0xff;
2995     s->io_buffer[1] = 0xff;
2996     s->io_buffer[2] = 0xff;
2997     s->io_buffer[3] = 0xff;
2998 }
2999
3000 static void ide_reset(IDEState *s)
3001 {
3002     IDEBus *bus = s->bus;
3003
3004     if (s->is_cf)
3005         s->mult_sectors = 0;
3006     else
3007         s->mult_sectors = MAX_MULT_SECTORS;
3008     bus->unit = s->unit;
3009     s->select = 0xa0;
3010     s->status = READY_STAT | SEEK_STAT;
3011     ide_set_signature(s);
3012     /* init the transfer handler so that 0xffff is returned on data
3013        accesses */
3014     s->end_transfer_func = ide_dummy_transfer_stop;
3015     ide_dummy_transfer_stop(s);
3016     s->media_changed = 0;
3017 }
3018
3019 static void ide_init2(IDEBus *bus,
3020                       BlockDriverState *hd0, BlockDriverState *hd1,
3021                       qemu_irq irq)
3022 {
3023     IDEState *s;
3024     static int drive_serial = 1;
3025     int i, cylinders, heads, secs;
3026     uint64_t nb_sectors;
3027
3028     for(i = 0; i < 2; i++) {
3029         s = bus->ifs + i;
3030         s->bus = bus;
3031         s->unit = i;
3032         s->bs = (i == 0) ? hd0 : hd1;
3033         s->io_buffer = qemu_blockalign(s->bs, IDE_DMA_BUF_SECTORS*512 + 4);
3034         if (s->bs) {
3035             bdrv_get_geometry(s->bs, &nb_sectors);
3036             bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);
3037             s->cylinders = cylinders;
3038             s->heads = heads;
3039             s->sectors = secs;
3040             s->nb_sectors = nb_sectors;
3041             /* The SMART values should be preserved across power cycles
3042                but they aren't.  */
3043             s->smart_enabled = 1;
3044             s->smart_autosave = 1;
3045             s->smart_errors = 0;
3046             s->smart_selftest_count = 0;
3047             s->smart_selftest_data = qemu_blockalign(s->bs, 512);
3048             if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
3049                 s->is_cdrom = 1;
3050                 bdrv_set_change_cb(s->bs, cdrom_change_cb, s);
3051             }
3052         }
3053         s->drive_serial = drive_serial++;
3054         strncpy(s->drive_serial_str, drive_get_serial(s->bs),
3055                 sizeof(s->drive_serial_str));
3056         if (strlen(s->drive_serial_str) == 0)
3057             snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
3058                     "QM%05d", s->drive_serial);
3059         s->irq = irq;
3060         s->sector_write_timer = qemu_new_timer(vm_clock,
3061                                                ide_sector_write_timer_cb, s);
3062         ide_reset(s);
3063     }
3064 }
3065
3066 static void ide_init_ioport(IDEBus *bus, int iobase, int iobase2)
3067 {
3068     register_ioport_write(iobase, 8, 1, ide_ioport_write, bus);
3069     register_ioport_read(iobase, 8, 1, ide_ioport_read, bus);
3070     if (iobase2) {
3071         register_ioport_read(iobase2, 1, 1, ide_status_read, bus);
3072         register_ioport_write(iobase2, 1, 1, ide_cmd_write, bus);
3073     }
3074
3075     /* data ports */
3076     register_ioport_write(iobase, 2, 2, ide_data_writew, bus);
3077     register_ioport_read(iobase, 2, 2, ide_data_readw, bus);
3078     register_ioport_write(iobase, 4, 4, ide_data_writel, bus);
3079     register_ioport_read(iobase, 4, 4, ide_data_readl, bus);
3080 }
3081
3082 /* save per IDE drive data */
3083 static void ide_save(QEMUFile* f, IDEState *s)
3084 {
3085     qemu_put_be32(f, s->mult_sectors);
3086     qemu_put_be32(f, s->identify_set);
3087     if (s->identify_set) {
3088         qemu_put_buffer(f, (const uint8_t *)s->identify_data, 512);
3089     }
3090     qemu_put_8s(f, &s->feature);
3091     qemu_put_8s(f, &s->error);
3092     qemu_put_be32s(f, &s->nsector);
3093     qemu_put_8s(f, &s->sector);
3094     qemu_put_8s(f, &s->lcyl);
3095     qemu_put_8s(f, &s->hcyl);
3096     qemu_put_8s(f, &s->hob_feature);
3097     qemu_put_8s(f, &s->hob_nsector);
3098     qemu_put_8s(f, &s->hob_sector);
3099     qemu_put_8s(f, &s->hob_lcyl);
3100     qemu_put_8s(f, &s->hob_hcyl);
3101     qemu_put_8s(f, &s->select);
3102     qemu_put_8s(f, &s->status);
3103     qemu_put_8s(f, &s->lba48);
3104
3105     qemu_put_8s(f, &s->sense_key);
3106     qemu_put_8s(f, &s->asc);
3107     qemu_put_8s(f, &s->cdrom_changed);
3108     /* XXX: if a transfer is pending, we do not save it yet */
3109 }
3110
3111 /* load per IDE drive data */
3112 static void ide_load(QEMUFile* f, IDEState *s, int version_id)
3113 {
3114     s->mult_sectors=qemu_get_be32(f);
3115     s->identify_set=qemu_get_be32(f);
3116     if (s->identify_set) {
3117         qemu_get_buffer(f, (uint8_t *)s->identify_data, 512);
3118     }
3119     qemu_get_8s(f, &s->feature);
3120     qemu_get_8s(f, &s->error);
3121     qemu_get_be32s(f, &s->nsector);
3122     qemu_get_8s(f, &s->sector);
3123     qemu_get_8s(f, &s->lcyl);
3124     qemu_get_8s(f, &s->hcyl);
3125     qemu_get_8s(f, &s->hob_feature);
3126     qemu_get_8s(f, &s->hob_nsector);
3127     qemu_get_8s(f, &s->hob_sector);
3128     qemu_get_8s(f, &s->hob_lcyl);
3129     qemu_get_8s(f, &s->hob_hcyl);
3130     qemu_get_8s(f, &s->select);
3131     qemu_get_8s(f, &s->status);
3132     qemu_get_8s(f, &s->lba48);
3133
3134     qemu_get_8s(f, &s->sense_key);
3135     qemu_get_8s(f, &s->asc);
3136     if (version_id == 3) {
3137         qemu_get_8s(f, &s->cdrom_changed);
3138     } else {
3139         if (s->sense_key == SENSE_UNIT_ATTENTION &&
3140                        s->asc == ASC_MEDIUM_MAY_HAVE_CHANGED)
3141             s->cdrom_changed = 1;
3142     }
3143     /* XXX: if a transfer is pending, we do not save it yet */
3144 }
3145
3146 static void idebus_save(QEMUFile* f, IDEBus *bus)
3147 {
3148     IDEState *s = idebus_active_if(bus);
3149     qemu_put_8s(f, &s->cmd);
3150     qemu_put_8s(f, &bus->unit);
3151 }
3152
3153 static void idebus_load(QEMUFile* f, IDEBus *bus, int version_id)
3154 {
3155     IDEState *s;
3156     uint8_t cmd;
3157
3158     qemu_get_8s(f, &cmd);
3159     qemu_get_8s(f, &bus->unit);
3160     s = idebus_active_if(bus);
3161     s->cmd = cmd;
3162 }
3163
3164 /***********************************************************/
3165 /* ISA IDE definitions */
3166
3167 void isa_ide_init(int iobase, int iobase2, qemu_irq irq,
3168                   BlockDriverState *hd0, BlockDriverState *hd1)
3169 {
3170     IDEBus *bus;
3171
3172     bus = qemu_mallocz(sizeof(*bus));
3173
3174     ide_init2(bus, hd0, hd1, irq);
3175     ide_init_ioport(bus, iobase, iobase2);
3176 }
3177
3178 /***********************************************************/
3179 /* PCI IDE definitions */
3180
3181 static void cmd646_update_irq(PCIIDEState *d);
3182
3183 static void ide_map(PCIDevice *pci_dev, int region_num,
3184                     uint32_t addr, uint32_t size, int type)
3185 {
3186     PCIIDEState *d = (PCIIDEState *)pci_dev;
3187     IDEBus *bus;
3188
3189     if (region_num <= 3) {
3190         bus = &d->bus[(region_num >> 1)];
3191         if (region_num & 1) {
3192             register_ioport_read(addr + 2, 1, 1, ide_status_read, bus);
3193             register_ioport_write(addr + 2, 1, 1, ide_cmd_write, bus);
3194         } else {
3195             register_ioport_write(addr, 8, 1, ide_ioport_write, bus);
3196             register_ioport_read(addr, 8, 1, ide_ioport_read, bus);
3197
3198             /* data ports */
3199             register_ioport_write(addr, 2, 2, ide_data_writew, bus);
3200             register_ioport_read(addr, 2, 2, ide_data_readw, bus);
3201             register_ioport_write(addr, 4, 4, ide_data_writel, bus);
3202             register_ioport_read(addr, 4, 4, ide_data_readl, bus);
3203         }
3204     }
3205 }
3206
3207 static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb)
3208 {
3209     BMDMAState *bm = s->bus->bmdma;
3210     if(!bm)
3211         return;
3212     bm->unit = s->unit;
3213     bm->dma_cb = dma_cb;
3214     bm->cur_prd_last = 0;
3215     bm->cur_prd_addr = 0;
3216     bm->cur_prd_len = 0;
3217     bm->sector_num = ide_get_sector(s);
3218     bm->nsector = s->nsector;
3219     if (bm->status & BM_STATUS_DMAING) {
3220         bm->dma_cb(bm, 0);
3221     }
3222 }
3223
3224 static void ide_dma_restart(IDEState *s)
3225 {
3226     BMDMAState *bm = s->bus->bmdma;
3227     ide_set_sector(s, bm->sector_num);
3228     s->io_buffer_index = 0;
3229     s->io_buffer_size = 0;
3230     s->nsector = bm->nsector;
3231     bm->cur_addr = bm->addr;
3232     bm->dma_cb = ide_write_dma_cb;
3233     ide_dma_start(s, bm->dma_cb);
3234 }
3235
3236 static void ide_dma_cancel(BMDMAState *bm)
3237 {
3238     if (bm->status & BM_STATUS_DMAING) {
3239         bm->status &= ~BM_STATUS_DMAING;
3240         /* cancel DMA request */
3241         bm->unit = -1;
3242         bm->dma_cb = NULL;
3243         if (bm->aiocb) {
3244 #ifdef DEBUG_AIO
3245             printf("aio_cancel\n");
3246 #endif
3247             bdrv_aio_cancel(bm->aiocb);
3248             bm->aiocb = NULL;
3249         }
3250     }
3251 }
3252
3253 static void bmdma_cmd_writeb(void *opaque, uint32_t addr, uint32_t val)
3254 {
3255     BMDMAState *bm = opaque;
3256 #ifdef DEBUG_IDE
3257     printf("%s: 0x%08x\n", __func__, val);
3258 #endif
3259     if (!(val & BM_CMD_START)) {
3260         /* XXX: do it better */
3261         ide_dma_cancel(bm);
3262         bm->cmd = val & 0x09;
3263     } else {
3264         if (!(bm->status & BM_STATUS_DMAING)) {
3265             bm->status |= BM_STATUS_DMAING;
3266             /* start dma transfer if possible */
3267             if (bm->dma_cb)
3268                 bm->dma_cb(bm, 0);
3269         }
3270         bm->cmd = val & 0x09;
3271     }
3272 }
3273
3274 static uint32_t bmdma_readb(void *opaque, uint32_t addr)
3275 {
3276     BMDMAState *bm = opaque;
3277     PCIIDEState *pci_dev;
3278     uint32_t val;
3279
3280     switch(addr & 3) {
3281     case 0:
3282         val = bm->cmd;
3283         break;
3284     case 1:
3285         pci_dev = bm->pci_dev;
3286         if (pci_dev->type == IDE_TYPE_CMD646) {
3287             val = pci_dev->dev.config[MRDMODE];
3288         } else {
3289             val = 0xff;
3290         }
3291         break;
3292     case 2:
3293         val = bm->status;
3294         break;
3295     case 3:
3296         pci_dev = bm->pci_dev;
3297         if (pci_dev->type == IDE_TYPE_CMD646) {
3298             if (bm == &pci_dev->bmdma[0])
3299                 val = pci_dev->dev.config[UDIDETCR0];
3300             else
3301                 val = pci_dev->dev.config[UDIDETCR1];
3302         } else {
3303             val = 0xff;
3304         }
3305         break;
3306     default:
3307         val = 0xff;
3308         break;
3309     }
3310 #ifdef DEBUG_IDE
3311     printf("bmdma: readb 0x%02x : 0x%02x\n", addr, val);
3312 #endif
3313     return val;
3314 }
3315
3316 static void bmdma_writeb(void *opaque, uint32_t addr, uint32_t val)
3317 {
3318     BMDMAState *bm = opaque;
3319     PCIIDEState *pci_dev;
3320 #ifdef DEBUG_IDE
3321     printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);
3322 #endif
3323     switch(addr & 3) {
3324     case 1:
3325         pci_dev = bm->pci_dev;
3326         if (pci_dev->type == IDE_TYPE_CMD646) {
3327             pci_dev->dev.config[MRDMODE] =
3328                 (pci_dev->dev.config[MRDMODE] & ~0x30) | (val & 0x30);
3329             cmd646_update_irq(pci_dev);
3330         }
3331         break;
3332     case 2:
3333         bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06);
3334         break;
3335     case 3:
3336         pci_dev = bm->pci_dev;
3337         if (pci_dev->type == IDE_TYPE_CMD646) {
3338             if (bm == &pci_dev->bmdma[0])
3339                 pci_dev->dev.config[UDIDETCR0] = val;
3340             else
3341                 pci_dev->dev.config[UDIDETCR1] = val;
3342         }
3343         break;
3344     }
3345 }
3346
3347 static uint32_t bmdma_addr_readb(void *opaque, uint32_t addr)
3348 {
3349     BMDMAState *bm = opaque;
3350     uint32_t val;
3351     val = (bm->addr >> ((addr & 3) * 8)) & 0xff;
3352 #ifdef DEBUG_IDE
3353     printf("%s: 0x%08x\n", __func__, val);
3354 #endif
3355     return val;
3356 }
3357
3358 static void bmdma_addr_writeb(void *opaque, uint32_t addr, uint32_t val)
3359 {
3360     BMDMAState *bm = opaque;
3361     int shift = (addr & 3) * 8;
3362 #ifdef DEBUG_IDE
3363     printf("%s: 0x%08x\n", __func__, val);
3364 #endif
3365     bm->addr &= ~(0xFF << shift);
3366     bm->addr |= ((val & 0xFF) << shift) & ~3;
3367     bm->cur_addr = bm->addr;
3368 }
3369
3370 static uint32_t bmdma_addr_readw(void *opaque, uint32_t addr)
3371 {
3372     BMDMAState *bm = opaque;
3373     uint32_t val;
3374     val = (bm->addr >> ((addr & 3) * 8)) & 0xffff;
3375 #ifdef DEBUG_IDE
3376     printf("%s: 0x%08x\n", __func__, val);
3377 #endif
3378     return val;
3379 }
3380
3381 static void bmdma_addr_writew(void *opaque, uint32_t addr, uint32_t val)
3382 {
3383     BMDMAState *bm = opaque;
3384     int shift = (addr & 3) * 8;
3385 #ifdef DEBUG_IDE
3386     printf("%s: 0x%08x\n", __func__, val);
3387 #endif
3388     bm->addr &= ~(0xFFFF << shift);
3389     bm->addr |= ((val & 0xFFFF) << shift) & ~3;
3390     bm->cur_addr = bm->addr;
3391 }
3392
3393 static uint32_t bmdma_addr_readl(void *opaque, uint32_t addr)
3394 {
3395     BMDMAState *bm = opaque;
3396     uint32_t val;
3397     val = bm->addr;
3398 #ifdef DEBUG_IDE
3399     printf("%s: 0x%08x\n", __func__, val);
3400 #endif
3401     return val;
3402 }
3403
3404 static void bmdma_addr_writel(void *opaque, uint32_t addr, uint32_t val)
3405 {
3406     BMDMAState *bm = opaque;
3407 #ifdef DEBUG_IDE
3408     printf("%s: 0x%08x\n", __func__, val);
3409 #endif
3410     bm->addr = val & ~3;
3411     bm->cur_addr = bm->addr;
3412 }
3413
3414 static void bmdma_map(PCIDevice *pci_dev, int region_num,
3415                     uint32_t addr, uint32_t size, int type)
3416 {
3417     PCIIDEState *d = (PCIIDEState *)pci_dev;
3418     int i;
3419
3420     for(i = 0;i < 2; i++) {
3421         BMDMAState *bm = &d->bmdma[i];
3422         d->bus[i].bmdma = bm;
3423         bm->pci_dev = DO_UPCAST(PCIIDEState, dev, pci_dev);
3424         bm->bus = d->bus+i;
3425         qemu_add_vm_change_state_handler(ide_dma_restart_cb, bm);
3426
3427         register_ioport_write(addr, 1, 1, bmdma_cmd_writeb, bm);
3428
3429         register_ioport_write(addr + 1, 3, 1, bmdma_writeb, bm);
3430         register_ioport_read(addr, 4, 1, bmdma_readb, bm);
3431
3432         register_ioport_write(addr + 4, 4, 1, bmdma_addr_writeb, bm);
3433         register_ioport_read(addr + 4, 4, 1, bmdma_addr_readb, bm);
3434         register_ioport_write(addr + 4, 4, 2, bmdma_addr_writew, bm);
3435         register_ioport_read(addr + 4, 4, 2, bmdma_addr_readw, bm);
3436         register_ioport_write(addr + 4, 4, 4, bmdma_addr_writel, bm);
3437         register_ioport_read(addr + 4, 4, 4, bmdma_addr_readl, bm);
3438         addr += 8;
3439     }
3440 }
3441
3442 static void pci_ide_save(QEMUFile* f, void *opaque)
3443 {
3444     PCIIDEState *d = opaque;
3445     int i;
3446
3447     pci_device_save(&d->dev, f);
3448
3449     for(i = 0; i < 2; i++) {
3450         BMDMAState *bm = &d->bmdma[i];
3451         uint8_t ifidx;
3452         qemu_put_8s(f, &bm->cmd);
3453         qemu_put_8s(f, &bm->status);
3454         qemu_put_be32s(f, &bm->addr);
3455         qemu_put_sbe64s(f, &bm->sector_num);
3456         qemu_put_be32s(f, &bm->nsector);
3457         ifidx = bm->unit + 2*i;
3458         qemu_put_8s(f, &ifidx);
3459         /* XXX: if a transfer is pending, we do not save it yet */
3460     }
3461
3462     /* per IDE interface data */
3463     for(i = 0; i < 2; i++) {
3464         idebus_save(f, &d->bus[i]);
3465     }
3466
3467     /* per IDE drive data */
3468     for(i = 0; i < 2; i++) {
3469         ide_save(f, &d->bus[i].ifs[0]);
3470         ide_save(f, &d->bus[i].ifs[1]);
3471     }
3472 }
3473
3474 static int pci_ide_load(QEMUFile* f, void *opaque, int version_id)
3475 {
3476     PCIIDEState *d = opaque;
3477     int ret, i;
3478
3479     if (version_id != 2 && version_id != 3)
3480         return -EINVAL;
3481     ret = pci_device_load(&d->dev, f);
3482     if (ret < 0)
3483         return ret;
3484
3485     for(i = 0; i < 2; i++) {
3486         BMDMAState *bm = &d->bmdma[i];
3487         uint8_t ifidx;
3488         qemu_get_8s(f, &bm->cmd);
3489         qemu_get_8s(f, &bm->status);
3490         qemu_get_be32s(f, &bm->addr);
3491         qemu_get_sbe64s(f, &bm->sector_num);
3492         qemu_get_be32s(f, &bm->nsector);
3493         qemu_get_8s(f, &ifidx);
3494         bm->unit = ifidx & 1;
3495         /* XXX: if a transfer is pending, we do not save it yet */
3496     }
3497
3498     /* per IDE interface data */
3499     for(i = 0; i < 2; i++) {
3500         idebus_load(f, &d->bus[i], version_id);
3501     }
3502
3503     /* per IDE drive data */
3504     for(i = 0; i < 2; i++) {
3505         ide_load(f, &d->bus[i].ifs[0], version_id);
3506         ide_load(f, &d->bus[i].ifs[1], version_id);
3507     }
3508     return 0;
3509 }
3510
3511 /* XXX: call it also when the MRDMODE is changed from the PCI config
3512    registers */
3513 static void cmd646_update_irq(PCIIDEState *d)
3514 {
3515     int pci_level;
3516     pci_level = ((d->dev.config[MRDMODE] & MRDMODE_INTR_CH0) &&
3517                  !(d->dev.config[MRDMODE] & MRDMODE_BLK_CH0)) ||
3518         ((d->dev.config[MRDMODE] & MRDMODE_INTR_CH1) &&
3519          !(d->dev.config[MRDMODE] & MRDMODE_BLK_CH1));
3520     qemu_set_irq(d->dev.irq[0], pci_level);
3521 }
3522
3523 /* the PCI irq level is the logical OR of the two channels */
3524 static void cmd646_set_irq(void *opaque, int channel, int level)
3525 {
3526     PCIIDEState *d = opaque;
3527     int irq_mask;
3528
3529     irq_mask = MRDMODE_INTR_CH0 << channel;
3530     if (level)
3531         d->dev.config[MRDMODE] |= irq_mask;
3532     else
3533         d->dev.config[MRDMODE] &= ~irq_mask;
3534     cmd646_update_irq(d);
3535 }
3536
3537 static void cmd646_reset(void *opaque)
3538 {
3539     PCIIDEState *d = opaque;
3540     unsigned int i;
3541
3542     for (i = 0; i < 2; i++)
3543         ide_dma_cancel(&d->bmdma[i]);
3544 }
3545
3546 /* CMD646 PCI IDE controller */
3547 void pci_cmd646_ide_init(PCIBus *bus, BlockDriverState **hd_table,
3548                          int secondary_ide_enabled)
3549 {
3550     PCIIDEState *d;
3551     uint8_t *pci_conf;
3552     qemu_irq *irq;
3553
3554     d = (PCIIDEState *)pci_register_device(bus, "CMD646 IDE",
3555                                            sizeof(PCIIDEState),
3556                                            -1,
3557                                            NULL, NULL);
3558     d->type = IDE_TYPE_CMD646;
3559     pci_conf = d->dev.config;
3560     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_CMD);
3561     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_CMD_646);
3562
3563     pci_conf[0x08] = 0x07; // IDE controller revision
3564     pci_conf[0x09] = 0x8f;
3565
3566     pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);
3567     pci_conf[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL; // header_type
3568
3569     pci_conf[0x51] = 0x04; // enable IDE0
3570     if (secondary_ide_enabled) {
3571         /* XXX: if not enabled, really disable the seconday IDE controller */
3572         pci_conf[0x51] |= 0x08; /* enable IDE1 */
3573     }
3574
3575     pci_register_bar((PCIDevice *)d, 0, 0x8,
3576                            PCI_ADDRESS_SPACE_IO, ide_map);
3577     pci_register_bar((PCIDevice *)d, 1, 0x4,
3578                            PCI_ADDRESS_SPACE_IO, ide_map);
3579     pci_register_bar((PCIDevice *)d, 2, 0x8,
3580                            PCI_ADDRESS_SPACE_IO, ide_map);
3581     pci_register_bar((PCIDevice *)d, 3, 0x4,
3582                            PCI_ADDRESS_SPACE_IO, ide_map);
3583     pci_register_bar((PCIDevice *)d, 4, 0x10,
3584                            PCI_ADDRESS_SPACE_IO, bmdma_map);
3585
3586     pci_conf[0x3d] = 0x01; // interrupt on pin 1
3587
3588     irq = qemu_allocate_irqs(cmd646_set_irq, d, 2);
3589     ide_init2(&d->bus[0], hd_table[0], hd_table[1], irq[0]);
3590     ide_init2(&d->bus[1], hd_table[2], hd_table[3], irq[1]);
3591
3592     register_savevm("ide", 0, 3, pci_ide_save, pci_ide_load, d);
3593     qemu_register_reset(cmd646_reset, d);
3594     cmd646_reset(d);
3595 }
3596
3597 static void piix3_reset(void *opaque)
3598 {
3599     PCIIDEState *d = opaque;
3600     uint8_t *pci_conf = d->dev.config;
3601     int i;
3602
3603     for (i = 0; i < 2; i++)
3604         ide_dma_cancel(&d->bmdma[i]);
3605
3606     pci_conf[0x04] = 0x00;
3607     pci_conf[0x05] = 0x00;
3608     pci_conf[0x06] = 0x80; /* FBC */
3609     pci_conf[0x07] = 0x02; // PCI_status_devsel_medium
3610     pci_conf[0x20] = 0x01; /* BMIBA: 20-23h */
3611 }
3612
3613 /* hd_table must contain 4 block drivers */
3614 /* NOTE: for the PIIX3, the IRQs and IOports are hardcoded */
3615 void pci_piix3_ide_init(PCIBus *bus, BlockDriverState **hd_table, int devfn,
3616                         qemu_irq *pic)
3617 {
3618     PCIIDEState *d;
3619     uint8_t *pci_conf;
3620     int i;
3621
3622     /* register a function 1 of PIIX3 */
3623     d = (PCIIDEState *)pci_register_device(bus, "PIIX3 IDE",
3624                                            sizeof(PCIIDEState),
3625                                            devfn,
3626                                            NULL, NULL);
3627     d->type = IDE_TYPE_PIIX3;
3628
3629     pci_conf = d->dev.config;
3630     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
3631     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371SB_1);
3632     pci_conf[0x09] = 0x80; // legacy ATA mode
3633     pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);
3634     pci_conf[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL; // header_type
3635
3636     qemu_register_reset(piix3_reset, d);
3637     piix3_reset(d);
3638
3639     pci_register_bar((PCIDevice *)d, 4, 0x10,
3640                            PCI_ADDRESS_SPACE_IO, bmdma_map);
3641
3642     ide_init2(&d->bus[0], hd_table[0], hd_table[1], isa_reserve_irq(14));
3643     ide_init2(&d->bus[1], hd_table[2], hd_table[3], isa_reserve_irq(15));
3644     ide_init_ioport(&d->bus[0], 0x1f0, 0x3f6);
3645     ide_init_ioport(&d->bus[1], 0x170, 0x376);
3646
3647     for (i = 0; i < 4; i++)
3648         if (hd_table[i])
3649             hd_table[i]->private = &d->dev;
3650
3651     register_savevm("ide", 0, 3, pci_ide_save, pci_ide_load, d);
3652 }
3653
3654 /* hd_table must contain 4 block drivers */
3655 /* NOTE: for the PIIX4, the IRQs and IOports are hardcoded */
3656 void pci_piix4_ide_init(PCIBus *bus, BlockDriverState **hd_table, int devfn,
3657                         qemu_irq *pic)
3658 {
3659     PCIIDEState *d;
3660     uint8_t *pci_conf;
3661
3662     /* register a function 1 of PIIX4 */
3663     d = (PCIIDEState *)pci_register_device(bus, "PIIX4 IDE",
3664                                            sizeof(PCIIDEState),
3665                                            devfn,
3666                                            NULL, NULL);
3667     d->type = IDE_TYPE_PIIX4;
3668
3669     pci_conf = d->dev.config;
3670     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
3671     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB);
3672     pci_conf[0x09] = 0x80; // legacy ATA mode
3673     pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);
3674     pci_conf[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL; // header_type
3675
3676     qemu_register_reset(piix3_reset, d);
3677     piix3_reset(d);
3678
3679     pci_register_bar((PCIDevice *)d, 4, 0x10,
3680                            PCI_ADDRESS_SPACE_IO, bmdma_map);
3681
3682     /*
3683      * These should call isa_reserve_irq() instead when MIPS supports it
3684      */
3685     ide_init2(&d->bus[0], hd_table[0], hd_table[1], pic[14]);
3686     ide_init2(&d->bus[1], hd_table[2], hd_table[3], pic[15]);
3687     ide_init_ioport(&d->bus[0], 0x1f0, 0x3f6);
3688     ide_init_ioport(&d->bus[1], 0x170, 0x376);
3689
3690     register_savevm("ide", 0, 3, pci_ide_save, pci_ide_load, d);
3691 }
3692
3693 #if defined(TARGET_PPC)
3694 /***********************************************************/
3695 /* MacIO based PowerPC IDE */
3696
3697 typedef struct MACIOIDEState {
3698     IDEBus bus;
3699     BlockDriverAIOCB *aiocb;
3700 } MACIOIDEState;
3701
3702 static void pmac_ide_atapi_transfer_cb(void *opaque, int ret)
3703 {
3704     DBDMA_io *io = opaque;
3705     MACIOIDEState *m = io->opaque;
3706     IDEState *s = idebus_active_if(&m->bus);
3707
3708     if (ret < 0) {
3709         m->aiocb = NULL;
3710         qemu_sglist_destroy(&s->sg);
3711         ide_atapi_io_error(s, ret);
3712         io->dma_end(opaque);
3713         return;
3714     }
3715
3716     if (s->io_buffer_size > 0) {
3717         m->aiocb = NULL;
3718         qemu_sglist_destroy(&s->sg);
3719
3720         s->packet_transfer_size -= s->io_buffer_size;
3721
3722         s->io_buffer_index += s->io_buffer_size;
3723         s->lba += s->io_buffer_index >> 11;
3724         s->io_buffer_index &= 0x7ff;
3725     }
3726
3727     if (s->packet_transfer_size <= 0)
3728         ide_atapi_cmd_ok(s);
3729
3730     if (io->len == 0) {
3731         io->dma_end(opaque);
3732         return;
3733     }
3734
3735     /* launch next transfer */
3736
3737     s->io_buffer_size = io->len;
3738
3739     qemu_sglist_init(&s->sg, io->len / TARGET_PAGE_SIZE + 1);
3740     qemu_sglist_add(&s->sg, io->addr, io->len);
3741     io->addr += io->len;
3742     io->len = 0;
3743
3744     m->aiocb = dma_bdrv_read(s->bs, &s->sg,
3745                              (int64_t)(s->lba << 2) + (s->io_buffer_index >> 9),
3746                              pmac_ide_atapi_transfer_cb, io);
3747     if (!m->aiocb) {
3748         qemu_sglist_destroy(&s->sg);
3749         /* Note: media not present is the most likely case */
3750         ide_atapi_cmd_error(s, SENSE_NOT_READY,
3751                             ASC_MEDIUM_NOT_PRESENT);
3752         io->dma_end(opaque);
3753         return;
3754     }
3755 }
3756
3757 static void pmac_ide_transfer_cb(void *opaque, int ret)
3758 {
3759     DBDMA_io *io = opaque;
3760     MACIOIDEState *m = io->opaque;
3761     IDEState *s = idebus_active_if(&m->bus);
3762     int n;
3763     int64_t sector_num;
3764
3765     if (ret < 0) {
3766         m->aiocb = NULL;
3767         qemu_sglist_destroy(&s->sg);
3768         ide_dma_error(s);
3769         io->dma_end(io);
3770         return;
3771     }
3772
3773     sector_num = ide_get_sector(s);
3774     if (s->io_buffer_size > 0) {
3775         m->aiocb = NULL;
3776         qemu_sglist_destroy(&s->sg);
3777         n = (s->io_buffer_size + 0x1ff) >> 9;
3778         sector_num += n;
3779         ide_set_sector(s, sector_num);
3780         s->nsector -= n;
3781     }
3782
3783     /* end of transfer ? */
3784     if (s->nsector == 0) {
3785         s->status = READY_STAT | SEEK_STAT;
3786         ide_set_irq(s);
3787     }
3788
3789     /* end of DMA ? */
3790
3791     if (io->len == 0) {
3792         io->dma_end(io);
3793         return;
3794     }
3795
3796     /* launch next transfer */
3797
3798     s->io_buffer_index = 0;
3799     s->io_buffer_size = io->len;
3800
3801     qemu_sglist_init(&s->sg, io->len / TARGET_PAGE_SIZE + 1);
3802     qemu_sglist_add(&s->sg, io->addr, io->len);
3803     io->addr += io->len;
3804     io->len = 0;
3805
3806     if (s->is_read)
3807         m->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,
3808                                  pmac_ide_transfer_cb, io);
3809     else
3810         m->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,
3811                                   pmac_ide_transfer_cb, io);
3812     if (!m->aiocb)
3813         pmac_ide_transfer_cb(io, -1);
3814 }
3815
3816 static void pmac_ide_transfer(DBDMA_io *io)
3817 {
3818     MACIOIDEState *m = io->opaque;
3819     IDEState *s = idebus_active_if(&m->bus);
3820
3821     s->io_buffer_size = 0;
3822     if (s->is_cdrom) {
3823         pmac_ide_atapi_transfer_cb(io, 0);
3824         return;
3825     }
3826
3827     pmac_ide_transfer_cb(io, 0);
3828 }
3829
3830 static void pmac_ide_flush(DBDMA_io *io)
3831 {
3832     MACIOIDEState *m = io->opaque;
3833
3834     if (m->aiocb)
3835         qemu_aio_flush();
3836 }
3837
3838 /* PowerMac IDE memory IO */
3839 static void pmac_ide_writeb (void *opaque,
3840                              target_phys_addr_t addr, uint32_t val)
3841 {
3842     MACIOIDEState *d = opaque;
3843
3844     addr = (addr & 0xFFF) >> 4;
3845     switch (addr) {
3846     case 1 ... 7:
3847         ide_ioport_write(&d->bus, addr, val);
3848         break;
3849     case 8:
3850     case 22:
3851         ide_cmd_write(&d->bus, 0, val);
3852         break;
3853     default:
3854         break;
3855     }
3856 }
3857
3858 static uint32_t pmac_ide_readb (void *opaque,target_phys_addr_t addr)
3859 {
3860     uint8_t retval;
3861     MACIOIDEState *d = opaque;
3862
3863     addr = (addr & 0xFFF) >> 4;
3864     switch (addr) {
3865     case 1 ... 7:
3866         retval = ide_ioport_read(&d->bus, addr);
3867         break;
3868     case 8:
3869     case 22:
3870         retval = ide_status_read(&d->bus, 0);
3871         break;
3872     default:
3873         retval = 0xFF;
3874         break;
3875     }
3876     return retval;
3877 }
3878
3879 static void pmac_ide_writew (void *opaque,
3880                              target_phys_addr_t addr, uint32_t val)
3881 {
3882     MACIOIDEState *d = opaque;
3883
3884     addr = (addr & 0xFFF) >> 4;
3885 #ifdef TARGET_WORDS_BIGENDIAN
3886     val = bswap16(val);
3887 #endif
3888     if (addr == 0) {
3889         ide_data_writew(&d->bus, 0, val);
3890     }
3891 }
3892
3893 static uint32_t pmac_ide_readw (void *opaque,target_phys_addr_t addr)
3894 {
3895     uint16_t retval;
3896     MACIOIDEState *d = opaque;
3897
3898     addr = (addr & 0xFFF) >> 4;
3899     if (addr == 0) {
3900         retval = ide_data_readw(&d->bus, 0);
3901     } else {
3902         retval = 0xFFFF;
3903     }
3904 #ifdef TARGET_WORDS_BIGENDIAN
3905     retval = bswap16(retval);
3906 #endif
3907     return retval;
3908 }
3909
3910 static void pmac_ide_writel (void *opaque,
3911                              target_phys_addr_t addr, uint32_t val)
3912 {
3913     MACIOIDEState *d = opaque;
3914
3915     addr = (addr & 0xFFF) >> 4;
3916 #ifdef TARGET_WORDS_BIGENDIAN
3917     val = bswap32(val);
3918 #endif
3919     if (addr == 0) {
3920         ide_data_writel(&d->bus, 0, val);
3921     }
3922 }
3923
3924 static uint32_t pmac_ide_readl (void *opaque,target_phys_addr_t addr)
3925 {
3926     uint32_t retval;
3927     MACIOIDEState *d = opaque;
3928
3929     addr = (addr & 0xFFF) >> 4;
3930     if (addr == 0) {
3931         retval = ide_data_readl(&d->bus, 0);
3932     } else {
3933         retval = 0xFFFFFFFF;
3934     }
3935 #ifdef TARGET_WORDS_BIGENDIAN
3936     retval = bswap32(retval);
3937 #endif
3938     return retval;
3939 }
3940
3941 static CPUWriteMemoryFunc * const pmac_ide_write[] = {
3942     pmac_ide_writeb,
3943     pmac_ide_writew,
3944     pmac_ide_writel,
3945 };
3946
3947 static CPUReadMemoryFunc * const pmac_ide_read[] = {
3948     pmac_ide_readb,
3949     pmac_ide_readw,
3950     pmac_ide_readl,
3951 };
3952
3953 static void pmac_ide_save(QEMUFile *f, void *opaque)
3954 {
3955     MACIOIDEState *d = opaque;
3956     unsigned int i;
3957
3958     /* per IDE interface data */
3959     idebus_save(f, &d->bus);
3960
3961     /* per IDE drive data */
3962     for(i = 0; i < 2; i++) {
3963         ide_save(f, &d->bus.ifs[i]);
3964     }
3965 }
3966
3967 static int pmac_ide_load(QEMUFile *f, void *opaque, int version_id)
3968 {
3969     MACIOIDEState *d = opaque;
3970     unsigned int i;
3971
3972     if (version_id != 1 && version_id != 3)
3973         return -EINVAL;
3974
3975     /* per IDE interface data */
3976     idebus_load(f, &d->bus, version_id);
3977
3978     /* per IDE drive data */
3979     for(i = 0; i < 2; i++) {
3980         ide_load(f, &d->bus.ifs[i], version_id);
3981     }
3982     return 0;
3983 }
3984
3985 static void pmac_ide_reset(void *opaque)
3986 {
3987     MACIOIDEState *d = opaque;
3988
3989     ide_reset(d->bus.ifs +0);
3990     ide_reset(d->bus.ifs +1);
3991 }
3992
3993 /* hd_table must contain 4 block drivers */
3994 /* PowerMac uses memory mapped registers, not I/O. Return the memory
3995    I/O index to access the ide. */
3996 int pmac_ide_init (BlockDriverState **hd_table, qemu_irq irq,
3997                    void *dbdma, int channel, qemu_irq dma_irq)
3998 {
3999     MACIOIDEState *d;
4000     int pmac_ide_memory;
4001
4002     d = qemu_mallocz(sizeof(MACIOIDEState));
4003     ide_init2(&d->bus, hd_table[0], hd_table[1], irq);
4004
4005     if (dbdma)
4006         DBDMA_register_channel(dbdma, channel, dma_irq, pmac_ide_transfer, pmac_ide_flush, d);
4007
4008     pmac_ide_memory = cpu_register_io_memory(pmac_ide_read,
4009                                              pmac_ide_write, d);
4010     register_savevm("ide", 0, 3, pmac_ide_save, pmac_ide_load, d);
4011     qemu_register_reset(pmac_ide_reset, d);
4012     pmac_ide_reset(d);
4013
4014     return pmac_ide_memory;
4015 }
4016 #endif /* TARGET_PPC */
4017
4018 /***********************************************************/
4019 /* MMIO based ide port
4020  * This emulates IDE device connected directly to the CPU bus without
4021  * dedicated ide controller, which is often seen on embedded boards.
4022  */
4023
4024 typedef struct {
4025     IDEBus *bus;
4026     int shift;
4027 } MMIOState;
4028
4029 static uint32_t mmio_ide_read (void *opaque, target_phys_addr_t addr)
4030 {
4031     MMIOState *s = (MMIOState*)opaque;
4032     IDEBus *bus = s->bus;
4033     addr >>= s->shift;
4034     if (addr & 7)
4035         return ide_ioport_read(bus, addr);
4036     else
4037         return ide_data_readw(bus, 0);
4038 }
4039
4040 static void mmio_ide_write (void *opaque, target_phys_addr_t addr,
4041         uint32_t val)
4042 {
4043     MMIOState *s = (MMIOState*)opaque;
4044     IDEBus *bus = s->bus;
4045     addr >>= s->shift;
4046     if (addr & 7)
4047         ide_ioport_write(bus, addr, val);
4048     else
4049         ide_data_writew(bus, 0, val);
4050 }
4051
4052 static CPUReadMemoryFunc * const mmio_ide_reads[] = {
4053     mmio_ide_read,
4054     mmio_ide_read,
4055     mmio_ide_read,
4056 };
4057
4058 static CPUWriteMemoryFunc * const mmio_ide_writes[] = {
4059     mmio_ide_write,
4060     mmio_ide_write,
4061     mmio_ide_write,
4062 };
4063
4064 static uint32_t mmio_ide_status_read (void *opaque, target_phys_addr_t addr)
4065 {
4066     MMIOState *s= (MMIOState*)opaque;
4067     IDEBus *bus = s->bus;
4068     return ide_status_read(bus, 0);
4069 }
4070
4071 static void mmio_ide_cmd_write (void *opaque, target_phys_addr_t addr,
4072         uint32_t val)
4073 {
4074     MMIOState *s = (MMIOState*)opaque;
4075     IDEBus *bus = s->bus;
4076     ide_cmd_write(bus, 0, val);
4077 }
4078
4079 static CPUReadMemoryFunc * const mmio_ide_status[] = {
4080     mmio_ide_status_read,
4081     mmio_ide_status_read,
4082     mmio_ide_status_read,
4083 };
4084
4085 static CPUWriteMemoryFunc * const mmio_ide_cmd[] = {
4086     mmio_ide_cmd_write,
4087     mmio_ide_cmd_write,
4088     mmio_ide_cmd_write,
4089 };
4090
4091 void mmio_ide_init (target_phys_addr_t membase, target_phys_addr_t membase2,
4092                     qemu_irq irq, int shift,
4093                     BlockDriverState *hd0, BlockDriverState *hd1)
4094 {
4095     MMIOState *s = qemu_mallocz(sizeof(MMIOState));
4096     IDEBus *bus = qemu_mallocz(sizeof(*bus));
4097     int mem1, mem2;
4098
4099     ide_init2(bus, hd0, hd1, irq);
4100
4101     s->bus = bus;
4102     s->shift = shift;
4103
4104     mem1 = cpu_register_io_memory(mmio_ide_reads, mmio_ide_writes, s);
4105     mem2 = cpu_register_io_memory(mmio_ide_status, mmio_ide_cmd, s);
4106     cpu_register_physical_memory(membase, 16 << shift, mem1);
4107     cpu_register_physical_memory(membase2, 2 << shift, mem2);
4108 }
4109
4110 /***********************************************************/
4111 /* CF-ATA Microdrive */
4112
4113 #define METADATA_SIZE   0x20
4114
4115 /* DSCM-1XXXX Microdrive hard disk with CF+ II / PCMCIA interface.  */
4116 typedef struct {
4117     IDEBus bus;
4118     PCMCIACardState card;
4119     uint32_t attr_base;
4120     uint32_t io_base;
4121
4122     /* Card state */
4123     uint8_t opt;
4124     uint8_t stat;
4125     uint8_t pins;
4126
4127     uint8_t ctrl;
4128     uint16_t io;
4129     int cycle;
4130 } MicroDriveState;
4131
4132 /* Register bitfields */
4133 enum md_opt {
4134     OPT_MODE_MMAP       = 0,
4135     OPT_MODE_IOMAP16    = 1,
4136     OPT_MODE_IOMAP1     = 2,
4137     OPT_MODE_IOMAP2     = 3,
4138     OPT_MODE            = 0x3f,
4139     OPT_LEVIREQ         = 0x40,
4140     OPT_SRESET          = 0x80,
4141 };
4142 enum md_cstat {
4143     STAT_INT            = 0x02,
4144     STAT_PWRDWN         = 0x04,
4145     STAT_XE             = 0x10,
4146     STAT_IOIS8          = 0x20,
4147     STAT_SIGCHG         = 0x40,
4148     STAT_CHANGED        = 0x80,
4149 };
4150 enum md_pins {
4151     PINS_MRDY           = 0x02,
4152     PINS_CRDY           = 0x20,
4153 };
4154 enum md_ctrl {
4155     CTRL_IEN            = 0x02,
4156     CTRL_SRST           = 0x04,
4157 };
4158
4159 static inline void md_interrupt_update(MicroDriveState *s)
4160 {
4161     if (!s->card.slot)
4162         return;
4163
4164     qemu_set_irq(s->card.slot->irq,
4165                     !(s->stat & STAT_INT) &&    /* Inverted */
4166                     !(s->ctrl & (CTRL_IEN | CTRL_SRST)) &&
4167                     !(s->opt & OPT_SRESET));
4168 }
4169
4170 static void md_set_irq(void *opaque, int irq, int level)
4171 {
4172     MicroDriveState *s = (MicroDriveState *) opaque;
4173     if (level)
4174         s->stat |= STAT_INT;
4175     else
4176         s->stat &= ~STAT_INT;
4177
4178     md_interrupt_update(s);
4179 }
4180
4181 static void md_reset(MicroDriveState *s)
4182 {
4183     s->opt = OPT_MODE_MMAP;
4184     s->stat = 0;
4185     s->pins = 0;
4186     s->cycle = 0;
4187     s->ctrl = 0;
4188     ide_reset(s->bus.ifs);
4189 }
4190
4191 static uint8_t md_attr_read(void *opaque, uint32_t at)
4192 {
4193     MicroDriveState *s = (MicroDriveState *) opaque;
4194     if (at < s->attr_base) {
4195         if (at < s->card.cis_len)
4196             return s->card.cis[at];
4197         else
4198             return 0x00;
4199     }
4200
4201     at -= s->attr_base;
4202
4203     switch (at) {
4204     case 0x00:  /* Configuration Option Register */
4205         return s->opt;
4206     case 0x02:  /* Card Configuration Status Register */
4207         if (s->ctrl & CTRL_IEN)
4208             return s->stat & ~STAT_INT;
4209         else
4210             return s->stat;
4211     case 0x04:  /* Pin Replacement Register */
4212         return (s->pins & PINS_CRDY) | 0x0c;
4213     case 0x06:  /* Socket and Copy Register */
4214         return 0x00;
4215 #ifdef VERBOSE
4216     default:
4217         printf("%s: Bad attribute space register %02x\n", __FUNCTION__, at);
4218 #endif
4219     }
4220
4221     return 0;
4222 }
4223
4224 static void md_attr_write(void *opaque, uint32_t at, uint8_t value)
4225 {
4226     MicroDriveState *s = (MicroDriveState *) opaque;
4227     at -= s->attr_base;
4228
4229     switch (at) {
4230     case 0x00:  /* Configuration Option Register */
4231         s->opt = value & 0xcf;
4232         if (value & OPT_SRESET)
4233             md_reset(s);
4234         md_interrupt_update(s);
4235         break;
4236     case 0x02:  /* Card Configuration Status Register */
4237         if ((s->stat ^ value) & STAT_PWRDWN)
4238             s->pins |= PINS_CRDY;
4239         s->stat &= 0x82;
4240         s->stat |= value & 0x74;
4241         md_interrupt_update(s);
4242         /* Word 170 in Identify Device must be equal to STAT_XE */
4243         break;
4244     case 0x04:  /* Pin Replacement Register */
4245         s->pins &= PINS_CRDY;
4246         s->pins |= value & PINS_MRDY;
4247         break;
4248     case 0x06:  /* Socket and Copy Register */
4249         break;
4250     default:
4251         printf("%s: Bad attribute space register %02x\n", __FUNCTION__, at);
4252     }
4253 }
4254
4255 static uint16_t md_common_read(void *opaque, uint32_t at)
4256 {
4257     MicroDriveState *s = (MicroDriveState *) opaque;
4258     IDEState *ifs;
4259     uint16_t ret;
4260     at -= s->io_base;
4261
4262     switch (s->opt & OPT_MODE) {
4263     case OPT_MODE_MMAP:
4264         if ((at & ~0x3ff) == 0x400)
4265             at = 0;
4266         break;
4267     case OPT_MODE_IOMAP16:
4268         at &= 0xf;
4269         break;
4270     case OPT_MODE_IOMAP1:
4271         if ((at & ~0xf) == 0x3f0)
4272             at -= 0x3e8;
4273         else if ((at & ~0xf) == 0x1f0)
4274             at -= 0x1f0;
4275         break;
4276     case OPT_MODE_IOMAP2:
4277         if ((at & ~0xf) == 0x370)
4278             at -= 0x368;
4279         else if ((at & ~0xf) == 0x170)
4280             at -= 0x170;
4281     }
4282
4283     switch (at) {
4284     case 0x0:   /* Even RD Data */
4285     case 0x8:
4286         return ide_data_readw(&s->bus, 0);
4287
4288         /* TODO: 8-bit accesses */
4289         if (s->cycle)
4290             ret = s->io >> 8;
4291         else {
4292             s->io = ide_data_readw(&s->bus, 0);
4293             ret = s->io & 0xff;
4294         }
4295         s->cycle = !s->cycle;
4296         return ret;
4297     case 0x9:   /* Odd RD Data */
4298         return s->io >> 8;
4299     case 0xd:   /* Error */
4300         return ide_ioport_read(&s->bus, 0x1);
4301     case 0xe:   /* Alternate Status */
4302         ifs = idebus_active_if(&s->bus);
4303         if (ifs->bs)
4304             return ifs->status;
4305         else
4306             return 0;
4307     case 0xf:   /* Device Address */
4308         ifs = idebus_active_if(&s->bus);
4309         return 0xc2 | ((~ifs->select << 2) & 0x3c);
4310     default:
4311         return ide_ioport_read(&s->bus, at);
4312     }
4313
4314     return 0;
4315 }
4316
4317 static void md_common_write(void *opaque, uint32_t at, uint16_t value)
4318 {
4319     MicroDriveState *s = (MicroDriveState *) opaque;
4320     at -= s->io_base;
4321
4322     switch (s->opt & OPT_MODE) {
4323     case OPT_MODE_MMAP:
4324         if ((at & ~0x3ff) == 0x400)
4325             at = 0;
4326         break;
4327     case OPT_MODE_IOMAP16:
4328         at &= 0xf;
4329         break;
4330     case OPT_MODE_IOMAP1:
4331         if ((at & ~0xf) == 0x3f0)
4332             at -= 0x3e8;
4333         else if ((at & ~0xf) == 0x1f0)
4334             at -= 0x1f0;
4335         break;
4336     case OPT_MODE_IOMAP2:
4337         if ((at & ~0xf) == 0x370)
4338             at -= 0x368;
4339         else if ((at & ~0xf) == 0x170)
4340             at -= 0x170;
4341     }
4342
4343     switch (at) {
4344     case 0x0:   /* Even WR Data */
4345     case 0x8:
4346         ide_data_writew(&s->bus, 0, value);
4347         break;
4348
4349         /* TODO: 8-bit accesses */
4350         if (s->cycle)
4351             ide_data_writew(&s->bus, 0, s->io | (value << 8));
4352         else
4353             s->io = value & 0xff;
4354         s->cycle = !s->cycle;
4355         break;
4356     case 0x9:
4357         s->io = value & 0xff;
4358         s->cycle = !s->cycle;
4359         break;
4360     case 0xd:   /* Features */
4361         ide_ioport_write(&s->bus, 0x1, value);
4362         break;
4363     case 0xe:   /* Device Control */
4364         s->ctrl = value;
4365         if (value & CTRL_SRST)
4366             md_reset(s);
4367         md_interrupt_update(s);
4368         break;
4369     default:
4370         if (s->stat & STAT_PWRDWN) {
4371             s->pins |= PINS_CRDY;
4372             s->stat &= ~STAT_PWRDWN;
4373         }
4374         ide_ioport_write(&s->bus, at, value);
4375     }
4376 }
4377
4378 static void md_save(QEMUFile *f, void *opaque)
4379 {
4380     MicroDriveState *s = (MicroDriveState *) opaque;
4381     int i;
4382
4383     qemu_put_8s(f, &s->opt);
4384     qemu_put_8s(f, &s->stat);
4385     qemu_put_8s(f, &s->pins);
4386
4387     qemu_put_8s(f, &s->ctrl);
4388     qemu_put_be16s(f, &s->io);
4389     qemu_put_byte(f, s->cycle);
4390
4391     idebus_save(f, &s->bus);
4392
4393     for (i = 0; i < 2; i ++)
4394         ide_save(f, &s->bus.ifs[i]);
4395 }
4396
4397 static int md_load(QEMUFile *f, void *opaque, int version_id)
4398 {
4399     MicroDriveState *s = (MicroDriveState *) opaque;
4400     int i;
4401
4402     if (version_id != 0 && version_id != 3)
4403         return -EINVAL;
4404
4405     qemu_get_8s(f, &s->opt);
4406     qemu_get_8s(f, &s->stat);
4407     qemu_get_8s(f, &s->pins);
4408
4409     qemu_get_8s(f, &s->ctrl);
4410     qemu_get_be16s(f, &s->io);
4411     s->cycle = qemu_get_byte(f);
4412
4413     idebus_load(f, &s->bus, version_id);
4414
4415     for (i = 0; i < 2; i ++)
4416         ide_load(f, &s->bus.ifs[i], version_id);
4417
4418     return 0;
4419 }
4420
4421 static const uint8_t dscm1xxxx_cis[0x14a] = {
4422     [0x000] = CISTPL_DEVICE,    /* 5V Device Information */
4423     [0x002] = 0x03,             /* Tuple length = 4 bytes */
4424     [0x004] = 0xdb,             /* ID: DTYPE_FUNCSPEC, non WP, DSPEED_150NS */
4425     [0x006] = 0x01,             /* Size = 2K bytes */
4426     [0x008] = CISTPL_ENDMARK,
4427
4428     [0x00a] = CISTPL_DEVICE_OC, /* Additional Device Information */
4429     [0x00c] = 0x04,             /* Tuple length = 4 byest */
4430     [0x00e] = 0x03,             /* Conditions: Ext = 0, Vcc 3.3V, MWAIT = 1 */
4431     [0x010] = 0xdb,             /* ID: DTYPE_FUNCSPEC, non WP, DSPEED_150NS */
4432     [0x012] = 0x01,             /* Size = 2K bytes */
4433     [0x014] = CISTPL_ENDMARK,
4434
4435     [0x016] = CISTPL_JEDEC_C,   /* JEDEC ID */
4436     [0x018] = 0x02,             /* Tuple length = 2 bytes */
4437     [0x01a] = 0xdf,             /* PC Card ATA with no Vpp required */
4438     [0x01c] = 0x01,
4439
4440     [0x01e] = CISTPL_MANFID,    /* Manufacture ID */
4441     [0x020] = 0x04,             /* Tuple length = 4 bytes */
4442     [0x022] = 0xa4,             /* TPLMID_MANF = 00a4 (IBM) */
4443     [0x024] = 0x00,
4444     [0x026] = 0x00,             /* PLMID_CARD = 0000 */
4445     [0x028] = 0x00,
4446
4447     [0x02a] = CISTPL_VERS_1,    /* Level 1 Version */
4448     [0x02c] = 0x12,             /* Tuple length = 23 bytes */
4449     [0x02e] = 0x04,             /* Major Version = JEIDA 4.2 / PCMCIA 2.1 */
4450     [0x030] = 0x01,             /* Minor Version = 1 */
4451     [0x032] = 'I',
4452     [0x034] = 'B',
4453     [0x036] = 'M',
4454     [0x038] = 0x00,
4455     [0x03a] = 'm',
4456     [0x03c] = 'i',
4457     [0x03e] = 'c',
4458     [0x040] = 'r',
4459     [0x042] = 'o',
4460     [0x044] = 'd',
4461     [0x046] = 'r',
4462     [0x048] = 'i',
4463     [0x04a] = 'v',
4464     [0x04c] = 'e',
4465     [0x04e] = 0x00,
4466     [0x050] = CISTPL_ENDMARK,
4467
4468     [0x052] = CISTPL_FUNCID,    /* Function ID */
4469     [0x054] = 0x02,             /* Tuple length = 2 bytes */
4470     [0x056] = 0x04,             /* TPLFID_FUNCTION = Fixed Disk */
4471     [0x058] = 0x01,             /* TPLFID_SYSINIT: POST = 1, ROM = 0 */
4472
4473     [0x05a] = CISTPL_FUNCE,     /* Function Extension */
4474     [0x05c] = 0x02,             /* Tuple length = 2 bytes */
4475     [0x05e] = 0x01,             /* TPLFE_TYPE = Disk Device Interface */
4476     [0x060] = 0x01,             /* TPLFE_DATA = PC Card ATA Interface */
4477
4478     [0x062] = CISTPL_FUNCE,     /* Function Extension */
4479     [0x064] = 0x03,             /* Tuple length = 3 bytes */
4480     [0x066] = 0x02,             /* TPLFE_TYPE = Basic PC Card ATA Interface */
4481     [0x068] = 0x08,             /* TPLFE_DATA: Rotating, Unique, Single */
4482     [0x06a] = 0x0f,             /* TPLFE_DATA: Sleep, Standby, Idle, Auto */
4483
4484     [0x06c] = CISTPL_CONFIG,    /* Configuration */
4485     [0x06e] = 0x05,             /* Tuple length = 5 bytes */
4486     [0x070] = 0x01,             /* TPCC_RASZ = 2 bytes, TPCC_RMSZ = 1 byte */
4487     [0x072] = 0x07,             /* TPCC_LAST = 7 */
4488     [0x074] = 0x00,             /* TPCC_RADR = 0200 */
4489     [0x076] = 0x02,
4490     [0x078] = 0x0f,             /* TPCC_RMSK = 200, 202, 204, 206 */
4491
4492     [0x07a] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4493     [0x07c] = 0x0b,             /* Tuple length = 11 bytes */
4494     [0x07e] = 0xc0,             /* TPCE_INDX = Memory Mode, Default, Iface */
4495     [0x080] = 0xc0,             /* TPCE_IF = Memory, no BVDs, no WP, READY */
4496     [0x082] = 0xa1,             /* TPCE_FS = Vcc only, no I/O, Memory, Misc */
4497     [0x084] = 0x27,             /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
4498     [0x086] = 0x55,             /* NomV: 5.0 V */
4499     [0x088] = 0x4d,             /* MinV: 4.5 V */
4500     [0x08a] = 0x5d,             /* MaxV: 5.5 V */
4501     [0x08c] = 0x4e,             /* Peakl: 450 mA */
4502     [0x08e] = 0x08,             /* TPCE_MS = 1 window, 1 byte, Host address */
4503     [0x090] = 0x00,             /* Window descriptor: Window length = 0 */
4504     [0x092] = 0x20,             /* TPCE_MI: support power down mode, RW */
4505
4506     [0x094] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4507     [0x096] = 0x06,             /* Tuple length = 6 bytes */
4508     [0x098] = 0x00,             /* TPCE_INDX = Memory Mode, no Default */
4509     [0x09a] = 0x01,             /* TPCE_FS = Vcc only, no I/O, no Memory */
4510     [0x09c] = 0x21,             /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
4511     [0x09e] = 0xb5,             /* NomV: 3.3 V */
4512     [0x0a0] = 0x1e,
4513     [0x0a2] = 0x3e,             /* Peakl: 350 mA */
4514
4515     [0x0a4] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4516     [0x0a6] = 0x0d,             /* Tuple length = 13 bytes */
4517     [0x0a8] = 0xc1,             /* TPCE_INDX = I/O and Memory Mode, Default */
4518     [0x0aa] = 0x41,             /* TPCE_IF = I/O and Memory, no BVD, no WP */
4519     [0x0ac] = 0x99,             /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
4520     [0x0ae] = 0x27,             /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
4521     [0x0b0] = 0x55,             /* NomV: 5.0 V */
4522     [0x0b2] = 0x4d,             /* MinV: 4.5 V */
4523     [0x0b4] = 0x5d,             /* MaxV: 5.5 V */
4524     [0x0b6] = 0x4e,             /* Peakl: 450 mA */
4525     [0x0b8] = 0x64,             /* TPCE_IO = 16-byte boundary, 16/8 accesses */
4526     [0x0ba] = 0xf0,             /* TPCE_IR =  MASK, Level, Pulse, Share */
4527     [0x0bc] = 0xff,             /* IRQ0..IRQ7 supported */
4528     [0x0be] = 0xff,             /* IRQ8..IRQ15 supported */
4529     [0x0c0] = 0x20,             /* TPCE_MI = support power down mode */
4530
4531     [0x0c2] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4532     [0x0c4] = 0x06,             /* Tuple length = 6 bytes */
4533     [0x0c6] = 0x01,             /* TPCE_INDX = I/O and Memory Mode */
4534     [0x0c8] = 0x01,             /* TPCE_FS = Vcc only, no I/O, no Memory */
4535     [0x0ca] = 0x21,             /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
4536     [0x0cc] = 0xb5,             /* NomV: 3.3 V */
4537     [0x0ce] = 0x1e,
4538     [0x0d0] = 0x3e,             /* Peakl: 350 mA */
4539
4540     [0x0d2] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4541     [0x0d4] = 0x12,             /* Tuple length = 18 bytes */
4542     [0x0d6] = 0xc2,             /* TPCE_INDX = I/O Primary Mode */
4543     [0x0d8] = 0x41,             /* TPCE_IF = I/O and Memory, no BVD, no WP */
4544     [0x0da] = 0x99,             /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
4545     [0x0dc] = 0x27,             /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
4546     [0x0de] = 0x55,             /* NomV: 5.0 V */
4547     [0x0e0] = 0x4d,             /* MinV: 4.5 V */
4548     [0x0e2] = 0x5d,             /* MaxV: 5.5 V */
4549     [0x0e4] = 0x4e,             /* Peakl: 450 mA */
4550     [0x0e6] = 0xea,             /* TPCE_IO = 1K boundary, 16/8 access, Range */
4551     [0x0e8] = 0x61,             /* Range: 2 fields, 2 bytes addr, 1 byte len */
4552     [0x0ea] = 0xf0,             /* Field 1 address = 0x01f0 */
4553     [0x0ec] = 0x01,
4554     [0x0ee] = 0x07,             /* Address block length = 8 */
4555     [0x0f0] = 0xf6,             /* Field 2 address = 0x03f6 */
4556     [0x0f2] = 0x03,
4557     [0x0f4] = 0x01,             /* Address block length = 2 */
4558     [0x0f6] = 0xee,             /* TPCE_IR = IRQ E, Level, Pulse, Share */
4559     [0x0f8] = 0x20,             /* TPCE_MI = support power down mode */
4560
4561     [0x0fa] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4562     [0x0fc] = 0x06,             /* Tuple length = 6 bytes */
4563     [0x0fe] = 0x02,             /* TPCE_INDX = I/O Primary Mode, no Default */
4564     [0x100] = 0x01,             /* TPCE_FS = Vcc only, no I/O, no Memory */
4565     [0x102] = 0x21,             /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
4566     [0x104] = 0xb5,             /* NomV: 3.3 V */
4567     [0x106] = 0x1e,
4568     [0x108] = 0x3e,             /* Peakl: 350 mA */
4569
4570     [0x10a] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4571     [0x10c] = 0x12,             /* Tuple length = 18 bytes */
4572     [0x10e] = 0xc3,             /* TPCE_INDX = I/O Secondary Mode, Default */
4573     [0x110] = 0x41,             /* TPCE_IF = I/O and Memory, no BVD, no WP */
4574     [0x112] = 0x99,             /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
4575     [0x114] = 0x27,             /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
4576     [0x116] = 0x55,             /* NomV: 5.0 V */
4577     [0x118] = 0x4d,             /* MinV: 4.5 V */
4578     [0x11a] = 0x5d,             /* MaxV: 5.5 V */
4579     [0x11c] = 0x4e,             /* Peakl: 450 mA */
4580     [0x11e] = 0xea,             /* TPCE_IO = 1K boundary, 16/8 access, Range */
4581     [0x120] = 0x61,             /* Range: 2 fields, 2 byte addr, 1 byte len */
4582     [0x122] = 0x70,             /* Field 1 address = 0x0170 */
4583     [0x124] = 0x01,
4584     [0x126] = 0x07,             /* Address block length = 8 */
4585     [0x128] = 0x76,             /* Field 2 address = 0x0376 */
4586     [0x12a] = 0x03,
4587     [0x12c] = 0x01,             /* Address block length = 2 */
4588     [0x12e] = 0xee,             /* TPCE_IR = IRQ E, Level, Pulse, Share */
4589     [0x130] = 0x20,             /* TPCE_MI = support power down mode */
4590
4591     [0x132] = CISTPL_CFTABLE_ENTRY,     /* 16-bit PC Card Configuration */
4592     [0x134] = 0x06,             /* Tuple length = 6 bytes */
4593     [0x136] = 0x03,             /* TPCE_INDX = I/O Secondary Mode */
4594     [0x138] = 0x01,             /* TPCE_FS = Vcc only, no I/O, no Memory */
4595     [0x13a] = 0x21,             /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
4596     [0x13c] = 0xb5,             /* NomV: 3.3 V */
4597     [0x13e] = 0x1e,
4598     [0x140] = 0x3e,             /* Peakl: 350 mA */
4599
4600     [0x142] = CISTPL_NO_LINK,   /* No Link */
4601     [0x144] = 0x00,             /* Tuple length = 0 bytes */
4602
4603     [0x146] = CISTPL_END,       /* Tuple End */
4604 };
4605
4606 static int dscm1xxxx_attach(void *opaque)
4607 {
4608     MicroDriveState *md = (MicroDriveState *) opaque;
4609     md->card.attr_read = md_attr_read;
4610     md->card.attr_write = md_attr_write;
4611     md->card.common_read = md_common_read;
4612     md->card.common_write = md_common_write;
4613     md->card.io_read = md_common_read;
4614     md->card.io_write = md_common_write;
4615
4616     md->attr_base = md->card.cis[0x74] | (md->card.cis[0x76] << 8);
4617     md->io_base = 0x0;
4618
4619     md_reset(md);
4620     md_interrupt_update(md);
4621
4622     md->card.slot->card_string = "DSCM-1xxxx Hitachi Microdrive";
4623     return 0;
4624 }
4625
4626 static int dscm1xxxx_detach(void *opaque)
4627 {
4628     MicroDriveState *md = (MicroDriveState *) opaque;
4629     md_reset(md);
4630     return 0;
4631 }
4632
4633 PCMCIACardState *dscm1xxxx_init(BlockDriverState *bdrv)
4634 {
4635     MicroDriveState *md = (MicroDriveState *) qemu_mallocz(sizeof(MicroDriveState));
4636     md->card.state = md;
4637     md->card.attach = dscm1xxxx_attach;
4638     md->card.detach = dscm1xxxx_detach;
4639     md->card.cis = dscm1xxxx_cis;
4640     md->card.cis_len = sizeof(dscm1xxxx_cis);
4641
4642     ide_init2(&md->bus, bdrv, NULL, qemu_allocate_irqs(md_set_irq, md, 1)[0]);
4643     md->bus.ifs[0].is_cf = 1;
4644     md->bus.ifs[0].mdata_size = METADATA_SIZE;
4645     md->bus.ifs[0].mdata_storage = (uint8_t *) qemu_mallocz(METADATA_SIZE);
4646
4647     register_savevm("microdrive", -1, 3, md_save, md_load, md);
4648
4649     return &md->card;
4650 }