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