xref: /qemu/hw/ide/core.c (revision 99a0949b720a0936da2052cb9a46db04ffc6db29)
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/hw.h>
26 #include <hw/pc.h>
27 #include <hw/pci.h>
28 #include <hw/scsi-disk.h>
29 #include <hw/sh.h>
30 #include "block.h"
31 #include "block_int.h"
32 #include "qemu-timer.h"
33 #include "sysemu.h"
34 #include "dma.h"
35 
36 #include <hw/ide/internal.h>
37 
38 static int smart_attributes[][5] = {
39     /* id,  flags, val, wrst, thrsh */
40     { 0x01, 0x03, 0x64, 0x64, 0x06}, /* raw read */
41     { 0x03, 0x03, 0x64, 0x64, 0x46}, /* spin up */
42     { 0x04, 0x02, 0x64, 0x64, 0x14}, /* start stop count */
43     { 0x05, 0x03, 0x64, 0x64, 0x36}, /* remapped sectors */
44     { 0x00, 0x00, 0x00, 0x00, 0x00}
45 };
46 
47 /* XXX: DVDs that could fit on a CD will be reported as a CD */
48 static inline int media_present(IDEState *s)
49 {
50     return (s->nb_sectors > 0);
51 }
52 
53 static inline int media_is_dvd(IDEState *s)
54 {
55     return (media_present(s) && s->nb_sectors > CD_MAX_SECTORS);
56 }
57 
58 static inline int media_is_cd(IDEState *s)
59 {
60     return (media_present(s) && s->nb_sectors <= CD_MAX_SECTORS);
61 }
62 
63 static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb);
64 static void ide_dma_restart(IDEState *s);
65 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret);
66 
67 static void padstr(char *str, const char *src, int len)
68 {
69     int i, v;
70     for(i = 0; i < len; i++) {
71         if (*src)
72             v = *src++;
73         else
74             v = ' ';
75         str[i^1] = v;
76     }
77 }
78 
79 static void padstr8(uint8_t *buf, int buf_size, const char *src)
80 {
81     int i;
82     for(i = 0; i < buf_size; i++) {
83         if (*src)
84             buf[i] = *src++;
85         else
86             buf[i] = ' ';
87     }
88 }
89 
90 static void put_le16(uint16_t *p, unsigned int v)
91 {
92     *p = cpu_to_le16(v);
93 }
94 
95 static void ide_identify(IDEState *s)
96 {
97     uint16_t *p;
98     unsigned int oldsize;
99 
100     if (s->identify_set) {
101 	memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
102 	return;
103     }
104 
105     memset(s->io_buffer, 0, 512);
106     p = (uint16_t *)s->io_buffer;
107     put_le16(p + 0, 0x0040);
108     put_le16(p + 1, s->cylinders);
109     put_le16(p + 3, s->heads);
110     put_le16(p + 4, 512 * s->sectors); /* XXX: retired, remove ? */
111     put_le16(p + 5, 512); /* XXX: retired, remove ? */
112     put_le16(p + 6, s->sectors);
113     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
114     put_le16(p + 20, 3); /* XXX: retired, remove ? */
115     put_le16(p + 21, 512); /* cache size in sectors */
116     put_le16(p + 22, 4); /* ecc bytes */
117     padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */
118     padstr((char *)(p + 27), "QEMU HARDDISK", 40); /* model */
119 #if MAX_MULT_SECTORS > 1
120     put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
121 #endif
122     put_le16(p + 48, 1); /* dword I/O */
123     put_le16(p + 49, (1 << 11) | (1 << 9) | (1 << 8)); /* DMA and LBA supported */
124     put_le16(p + 51, 0x200); /* PIO transfer cycle */
125     put_le16(p + 52, 0x200); /* DMA transfer cycle */
126     put_le16(p + 53, 1 | (1 << 1) | (1 << 2)); /* words 54-58,64-70,88 are valid */
127     put_le16(p + 54, s->cylinders);
128     put_le16(p + 55, s->heads);
129     put_le16(p + 56, s->sectors);
130     oldsize = s->cylinders * s->heads * s->sectors;
131     put_le16(p + 57, oldsize);
132     put_le16(p + 58, oldsize >> 16);
133     if (s->mult_sectors)
134         put_le16(p + 59, 0x100 | s->mult_sectors);
135     put_le16(p + 60, s->nb_sectors);
136     put_le16(p + 61, s->nb_sectors >> 16);
137     put_le16(p + 62, 0x07); /* single word dma0-2 supported */
138     put_le16(p + 63, 0x07); /* mdma0-2 supported */
139     put_le16(p + 65, 120);
140     put_le16(p + 66, 120);
141     put_le16(p + 67, 120);
142     put_le16(p + 68, 120);
143     put_le16(p + 80, 0xf0); /* ata3 -> ata6 supported */
144     put_le16(p + 81, 0x16); /* conforms to ata5 */
145     /* 14=NOP supported, 0=SMART supported */
146     put_le16(p + 82, (1 << 14) | 1);
147     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
148     put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
149     /* 14=set to 1, 1=SMART self test, 0=SMART error logging */
150     put_le16(p + 84, (1 << 14) | 0);
151     /* 14 = NOP supported, 5=WCACHE enabled, 0=SMART feature set enabled */
152     if (bdrv_enable_write_cache(s->bs))
153          put_le16(p + 85, (1 << 14) | (1 << 5) | 1);
154     else
155          put_le16(p + 85, (1 << 14) | 1);
156     /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
157     put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
158     /* 14=set to 1, 1=smart self test, 0=smart error logging */
159     put_le16(p + 87, (1 << 14) | 0);
160     put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
161     put_le16(p + 93, 1 | (1 << 14) | 0x2000);
162     put_le16(p + 100, s->nb_sectors);
163     put_le16(p + 101, s->nb_sectors >> 16);
164     put_le16(p + 102, s->nb_sectors >> 32);
165     put_le16(p + 103, s->nb_sectors >> 48);
166 
167     memcpy(s->identify_data, p, sizeof(s->identify_data));
168     s->identify_set = 1;
169 }
170 
171 static void ide_atapi_identify(IDEState *s)
172 {
173     uint16_t *p;
174 
175     if (s->identify_set) {
176 	memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
177 	return;
178     }
179 
180     memset(s->io_buffer, 0, 512);
181     p = (uint16_t *)s->io_buffer;
182     /* Removable CDROM, 50us response, 12 byte packets */
183     put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));
184     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
185     put_le16(p + 20, 3); /* buffer type */
186     put_le16(p + 21, 512); /* cache size in sectors */
187     put_le16(p + 22, 4); /* ecc bytes */
188     padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */
189     padstr((char *)(p + 27), "QEMU DVD-ROM", 40); /* model */
190     put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */
191 #ifdef USE_DMA_CDROM
192     put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */
193     put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */
194     put_le16(p + 62, 7);  /* single word dma0-2 supported */
195     put_le16(p + 63, 7);  /* mdma0-2 supported */
196     put_le16(p + 64, 0x3f); /* PIO modes supported */
197 #else
198     put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */
199     put_le16(p + 53, 3); /* words 64-70, 54-58 valid */
200     put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */
201     put_le16(p + 64, 1); /* PIO modes */
202 #endif
203     put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */
204     put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */
205     put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */
206     put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */
207 
208     put_le16(p + 71, 30); /* in ns */
209     put_le16(p + 72, 30); /* in ns */
210 
211     put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
212 #ifdef USE_DMA_CDROM
213     put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
214 #endif
215     memcpy(s->identify_data, p, sizeof(s->identify_data));
216     s->identify_set = 1;
217 }
218 
219 static void ide_cfata_identify(IDEState *s)
220 {
221     uint16_t *p;
222     uint32_t cur_sec;
223 
224     p = (uint16_t *) s->identify_data;
225     if (s->identify_set)
226         goto fill_buffer;
227 
228     memset(p, 0, sizeof(s->identify_data));
229 
230     cur_sec = s->cylinders * s->heads * s->sectors;
231 
232     put_le16(p + 0, 0x848a);			/* CF Storage Card signature */
233     put_le16(p + 1, s->cylinders);		/* Default cylinders */
234     put_le16(p + 3, s->heads);			/* Default heads */
235     put_le16(p + 6, s->sectors);		/* Default sectors per track */
236     put_le16(p + 7, s->nb_sectors >> 16);	/* Sectors per card */
237     put_le16(p + 8, s->nb_sectors);		/* Sectors per card */
238     padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
239     put_le16(p + 22, 0x0004);			/* ECC bytes */
240     padstr((char *) (p + 23), QEMU_VERSION, 8);	/* Firmware Revision */
241     padstr((char *) (p + 27), "QEMU MICRODRIVE", 40);/* Model number */
242 #if MAX_MULT_SECTORS > 1
243     put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
244 #else
245     put_le16(p + 47, 0x0000);
246 #endif
247     put_le16(p + 49, 0x0f00);			/* Capabilities */
248     put_le16(p + 51, 0x0002);			/* PIO cycle timing mode */
249     put_le16(p + 52, 0x0001);			/* DMA cycle timing mode */
250     put_le16(p + 53, 0x0003);			/* Translation params valid */
251     put_le16(p + 54, s->cylinders);		/* Current cylinders */
252     put_le16(p + 55, s->heads);			/* Current heads */
253     put_le16(p + 56, s->sectors);		/* Current sectors */
254     put_le16(p + 57, cur_sec);			/* Current capacity */
255     put_le16(p + 58, cur_sec >> 16);		/* Current capacity */
256     if (s->mult_sectors)			/* Multiple sector setting */
257         put_le16(p + 59, 0x100 | s->mult_sectors);
258     put_le16(p + 60, s->nb_sectors);		/* Total LBA sectors */
259     put_le16(p + 61, s->nb_sectors >> 16);	/* Total LBA sectors */
260     put_le16(p + 63, 0x0203);			/* Multiword DMA capability */
261     put_le16(p + 64, 0x0001);			/* Flow Control PIO support */
262     put_le16(p + 65, 0x0096);			/* Min. Multiword DMA cycle */
263     put_le16(p + 66, 0x0096);			/* Rec. Multiword DMA cycle */
264     put_le16(p + 68, 0x00b4);			/* Min. PIO cycle time */
265     put_le16(p + 82, 0x400c);			/* Command Set supported */
266     put_le16(p + 83, 0x7068);			/* Command Set supported */
267     put_le16(p + 84, 0x4000);			/* Features supported */
268     put_le16(p + 85, 0x000c);			/* Command Set enabled */
269     put_le16(p + 86, 0x7044);			/* Command Set enabled */
270     put_le16(p + 87, 0x4000);			/* Features enabled */
271     put_le16(p + 91, 0x4060);			/* Current APM level */
272     put_le16(p + 129, 0x0002);			/* Current features option */
273     put_le16(p + 130, 0x0005);			/* Reassigned sectors */
274     put_le16(p + 131, 0x0001);			/* Initial power mode */
275     put_le16(p + 132, 0x0000);			/* User signature */
276     put_le16(p + 160, 0x8100);			/* Power requirement */
277     put_le16(p + 161, 0x8001);			/* CF command set */
278 
279     s->identify_set = 1;
280 
281 fill_buffer:
282     memcpy(s->io_buffer, p, sizeof(s->identify_data));
283 }
284 
285 static void ide_set_signature(IDEState *s)
286 {
287     s->select &= 0xf0; /* clear head */
288     /* put signature */
289     s->nsector = 1;
290     s->sector = 1;
291     if (s->is_cdrom) {
292         s->lcyl = 0x14;
293         s->hcyl = 0xeb;
294     } else if (s->bs) {
295         s->lcyl = 0;
296         s->hcyl = 0;
297     } else {
298         s->lcyl = 0xff;
299         s->hcyl = 0xff;
300     }
301 }
302 
303 static inline void ide_abort_command(IDEState *s)
304 {
305     s->status = READY_STAT | ERR_STAT;
306     s->error = ABRT_ERR;
307 }
308 
309 static inline void ide_dma_submit_check(IDEState *s,
310           BlockDriverCompletionFunc *dma_cb, BMDMAState *bm)
311 {
312     if (bm->aiocb)
313 	return;
314     dma_cb(bm, -1);
315 }
316 
317 /* prepare data transfer and tell what to do after */
318 static void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
319                                EndTransferFunc *end_transfer_func)
320 {
321     s->end_transfer_func = end_transfer_func;
322     s->data_ptr = buf;
323     s->data_end = buf + size;
324     if (!(s->status & ERR_STAT))
325         s->status |= DRQ_STAT;
326 }
327 
328 static void ide_transfer_stop(IDEState *s)
329 {
330     s->end_transfer_func = ide_transfer_stop;
331     s->data_ptr = s->io_buffer;
332     s->data_end = s->io_buffer;
333     s->status &= ~DRQ_STAT;
334 }
335 
336 int64_t ide_get_sector(IDEState *s)
337 {
338     int64_t sector_num;
339     if (s->select & 0x40) {
340         /* lba */
341 	if (!s->lba48) {
342 	    sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
343 		(s->lcyl << 8) | s->sector;
344 	} else {
345 	    sector_num = ((int64_t)s->hob_hcyl << 40) |
346 		((int64_t) s->hob_lcyl << 32) |
347 		((int64_t) s->hob_sector << 24) |
348 		((int64_t) s->hcyl << 16) |
349 		((int64_t) s->lcyl << 8) | s->sector;
350 	}
351     } else {
352         sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
353             (s->select & 0x0f) * s->sectors + (s->sector - 1);
354     }
355     return sector_num;
356 }
357 
358 void ide_set_sector(IDEState *s, int64_t sector_num)
359 {
360     unsigned int cyl, r;
361     if (s->select & 0x40) {
362 	if (!s->lba48) {
363             s->select = (s->select & 0xf0) | (sector_num >> 24);
364             s->hcyl = (sector_num >> 16);
365             s->lcyl = (sector_num >> 8);
366             s->sector = (sector_num);
367 	} else {
368 	    s->sector = sector_num;
369 	    s->lcyl = sector_num >> 8;
370 	    s->hcyl = sector_num >> 16;
371 	    s->hob_sector = sector_num >> 24;
372 	    s->hob_lcyl = sector_num >> 32;
373 	    s->hob_hcyl = sector_num >> 40;
374 	}
375     } else {
376         cyl = sector_num / (s->heads * s->sectors);
377         r = sector_num % (s->heads * s->sectors);
378         s->hcyl = cyl >> 8;
379         s->lcyl = cyl;
380         s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);
381         s->sector = (r % s->sectors) + 1;
382     }
383 }
384 
385 static void ide_rw_error(IDEState *s) {
386     ide_abort_command(s);
387     ide_set_irq(s->bus);
388 }
389 
390 static void ide_sector_read(IDEState *s)
391 {
392     int64_t sector_num;
393     int ret, n;
394 
395     s->status = READY_STAT | SEEK_STAT;
396     s->error = 0; /* not needed by IDE spec, but needed by Windows */
397     sector_num = ide_get_sector(s);
398     n = s->nsector;
399     if (n == 0) {
400         /* no more sector to read from disk */
401         ide_transfer_stop(s);
402     } else {
403 #if defined(DEBUG_IDE)
404         printf("read sector=%" PRId64 "\n", sector_num);
405 #endif
406         if (n > s->req_nb_sectors)
407             n = s->req_nb_sectors;
408         ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
409         if (ret != 0) {
410             ide_rw_error(s);
411             return;
412         }
413         ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);
414         ide_set_irq(s->bus);
415         ide_set_sector(s, sector_num + n);
416         s->nsector -= n;
417     }
418 }
419 
420 
421 /* return 0 if buffer completed */
422 static int dma_buf_prepare(BMDMAState *bm, int is_write)
423 {
424     IDEState *s = bmdma_active_if(bm);
425     struct {
426         uint32_t addr;
427         uint32_t size;
428     } prd;
429     int l, len;
430 
431     qemu_sglist_init(&s->sg, s->nsector / (TARGET_PAGE_SIZE/512) + 1);
432     s->io_buffer_size = 0;
433     for(;;) {
434         if (bm->cur_prd_len == 0) {
435             /* end of table (with a fail safe of one page) */
436             if (bm->cur_prd_last ||
437                 (bm->cur_addr - bm->addr) >= 4096)
438                 return s->io_buffer_size != 0;
439             cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
440             bm->cur_addr += 8;
441             prd.addr = le32_to_cpu(prd.addr);
442             prd.size = le32_to_cpu(prd.size);
443             len = prd.size & 0xfffe;
444             if (len == 0)
445                 len = 0x10000;
446             bm->cur_prd_len = len;
447             bm->cur_prd_addr = prd.addr;
448             bm->cur_prd_last = (prd.size & 0x80000000);
449         }
450         l = bm->cur_prd_len;
451         if (l > 0) {
452             qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);
453             bm->cur_prd_addr += l;
454             bm->cur_prd_len -= l;
455             s->io_buffer_size += l;
456         }
457     }
458     return 1;
459 }
460 
461 static void dma_buf_commit(IDEState *s, int is_write)
462 {
463     qemu_sglist_destroy(&s->sg);
464 }
465 
466 void ide_dma_error(IDEState *s)
467 {
468     ide_transfer_stop(s);
469     s->error = ABRT_ERR;
470     s->status = READY_STAT | ERR_STAT;
471     ide_set_irq(s->bus);
472 }
473 
474 static int ide_handle_write_error(IDEState *s, int error, int op)
475 {
476     BlockInterfaceErrorAction action = drive_get_onerror(s->bs);
477 
478     if (action == BLOCK_ERR_IGNORE)
479         return 0;
480 
481     if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
482             || action == BLOCK_ERR_STOP_ANY) {
483         s->bus->bmdma->unit = s->unit;
484         s->bus->bmdma->status |= op;
485         vm_stop(0);
486     } else {
487         if (op == BM_STATUS_DMA_RETRY) {
488             dma_buf_commit(s, 0);
489             ide_dma_error(s);
490         } else {
491             ide_rw_error(s);
492         }
493     }
494 
495     return 1;
496 }
497 
498 /* return 0 if buffer completed */
499 static int dma_buf_rw(BMDMAState *bm, int is_write)
500 {
501     IDEState *s = bmdma_active_if(bm);
502     struct {
503         uint32_t addr;
504         uint32_t size;
505     } prd;
506     int l, len;
507 
508     for(;;) {
509         l = s->io_buffer_size - s->io_buffer_index;
510         if (l <= 0)
511             break;
512         if (bm->cur_prd_len == 0) {
513             /* end of table (with a fail safe of one page) */
514             if (bm->cur_prd_last ||
515                 (bm->cur_addr - bm->addr) >= 4096)
516                 return 0;
517             cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
518             bm->cur_addr += 8;
519             prd.addr = le32_to_cpu(prd.addr);
520             prd.size = le32_to_cpu(prd.size);
521             len = prd.size & 0xfffe;
522             if (len == 0)
523                 len = 0x10000;
524             bm->cur_prd_len = len;
525             bm->cur_prd_addr = prd.addr;
526             bm->cur_prd_last = (prd.size & 0x80000000);
527         }
528         if (l > bm->cur_prd_len)
529             l = bm->cur_prd_len;
530         if (l > 0) {
531             if (is_write) {
532                 cpu_physical_memory_write(bm->cur_prd_addr,
533                                           s->io_buffer + s->io_buffer_index, l);
534             } else {
535                 cpu_physical_memory_read(bm->cur_prd_addr,
536                                           s->io_buffer + s->io_buffer_index, l);
537             }
538             bm->cur_prd_addr += l;
539             bm->cur_prd_len -= l;
540             s->io_buffer_index += l;
541         }
542     }
543     return 1;
544 }
545 
546 static void ide_read_dma_cb(void *opaque, int ret)
547 {
548     BMDMAState *bm = opaque;
549     IDEState *s = bmdma_active_if(bm);
550     int n;
551     int64_t sector_num;
552 
553     if (ret < 0) {
554         dma_buf_commit(s, 1);
555 	ide_dma_error(s);
556 	return;
557     }
558 
559     n = s->io_buffer_size >> 9;
560     sector_num = ide_get_sector(s);
561     if (n > 0) {
562         dma_buf_commit(s, 1);
563         sector_num += n;
564         ide_set_sector(s, sector_num);
565         s->nsector -= n;
566     }
567 
568     /* end of transfer ? */
569     if (s->nsector == 0) {
570         s->status = READY_STAT | SEEK_STAT;
571         ide_set_irq(s->bus);
572     eot:
573         bm->status &= ~BM_STATUS_DMAING;
574         bm->status |= BM_STATUS_INT;
575         bm->dma_cb = NULL;
576         bm->unit = -1;
577         bm->aiocb = NULL;
578         return;
579     }
580 
581     /* launch next transfer */
582     n = s->nsector;
583     s->io_buffer_index = 0;
584     s->io_buffer_size = n * 512;
585     if (dma_buf_prepare(bm, 1) == 0)
586         goto eot;
587 #ifdef DEBUG_AIO
588     printf("aio_read: sector_num=%" PRId64 " n=%d\n", sector_num, n);
589 #endif
590     bm->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num, ide_read_dma_cb, bm);
591     ide_dma_submit_check(s, ide_read_dma_cb, bm);
592 }
593 
594 static void ide_sector_read_dma(IDEState *s)
595 {
596     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
597     s->io_buffer_index = 0;
598     s->io_buffer_size = 0;
599     s->is_read = 1;
600     ide_dma_start(s, ide_read_dma_cb);
601 }
602 
603 static void ide_sector_write_timer_cb(void *opaque)
604 {
605     IDEState *s = opaque;
606     ide_set_irq(s->bus);
607 }
608 
609 static void ide_sector_write(IDEState *s)
610 {
611     int64_t sector_num;
612     int ret, n, n1;
613 
614     s->status = READY_STAT | SEEK_STAT;
615     sector_num = ide_get_sector(s);
616 #if defined(DEBUG_IDE)
617     printf("write sector=%" PRId64 "\n", sector_num);
618 #endif
619     n = s->nsector;
620     if (n > s->req_nb_sectors)
621         n = s->req_nb_sectors;
622     ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
623 
624     if (ret != 0) {
625         if (ide_handle_write_error(s, -ret, BM_STATUS_PIO_RETRY))
626             return;
627     }
628 
629     s->nsector -= n;
630     if (s->nsector == 0) {
631         /* no more sectors to write */
632         ide_transfer_stop(s);
633     } else {
634         n1 = s->nsector;
635         if (n1 > s->req_nb_sectors)
636             n1 = s->req_nb_sectors;
637         ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write);
638     }
639     ide_set_sector(s, sector_num + n);
640 
641 #ifdef TARGET_I386
642     if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {
643         /* It seems there is a bug in the Windows 2000 installer HDD
644            IDE driver which fills the disk with empty logs when the
645            IDE write IRQ comes too early. This hack tries to correct
646            that at the expense of slower write performances. Use this
647            option _only_ to install Windows 2000. You must disable it
648            for normal use. */
649         qemu_mod_timer(s->sector_write_timer,
650                        qemu_get_clock(vm_clock) + (get_ticks_per_sec() / 1000));
651     } else
652 #endif
653     {
654         ide_set_irq(s->bus);
655     }
656 }
657 
658 static void ide_dma_restart_bh(void *opaque)
659 {
660     BMDMAState *bm = opaque;
661 
662     qemu_bh_delete(bm->bh);
663     bm->bh = NULL;
664 
665     if (bm->status & BM_STATUS_DMA_RETRY) {
666         bm->status &= ~BM_STATUS_DMA_RETRY;
667         ide_dma_restart(bmdma_active_if(bm));
668     } else if (bm->status & BM_STATUS_PIO_RETRY) {
669         bm->status &= ~BM_STATUS_PIO_RETRY;
670         ide_sector_write(bmdma_active_if(bm));
671     }
672 }
673 
674 void ide_dma_restart_cb(void *opaque, int running, int reason)
675 {
676     BMDMAState *bm = opaque;
677 
678     if (!running)
679         return;
680 
681     if (!bm->bh) {
682         bm->bh = qemu_bh_new(ide_dma_restart_bh, bm);
683         qemu_bh_schedule(bm->bh);
684     }
685 }
686 
687 static void ide_write_dma_cb(void *opaque, int ret)
688 {
689     BMDMAState *bm = opaque;
690     IDEState *s = bmdma_active_if(bm);
691     int n;
692     int64_t sector_num;
693 
694     if (ret < 0) {
695         if (ide_handle_write_error(s, -ret,  BM_STATUS_DMA_RETRY))
696             return;
697     }
698 
699     n = s->io_buffer_size >> 9;
700     sector_num = ide_get_sector(s);
701     if (n > 0) {
702         dma_buf_commit(s, 0);
703         sector_num += n;
704         ide_set_sector(s, sector_num);
705         s->nsector -= n;
706     }
707 
708     /* end of transfer ? */
709     if (s->nsector == 0) {
710         s->status = READY_STAT | SEEK_STAT;
711         ide_set_irq(s->bus);
712     eot:
713         bm->status &= ~BM_STATUS_DMAING;
714         bm->status |= BM_STATUS_INT;
715         bm->dma_cb = NULL;
716         bm->unit = -1;
717         bm->aiocb = NULL;
718         return;
719     }
720 
721     n = s->nsector;
722     s->io_buffer_size = n * 512;
723     /* launch next transfer */
724     if (dma_buf_prepare(bm, 0) == 0)
725         goto eot;
726 #ifdef DEBUG_AIO
727     printf("aio_write: sector_num=%" PRId64 " n=%d\n", sector_num, n);
728 #endif
729     bm->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num, ide_write_dma_cb, bm);
730     ide_dma_submit_check(s, ide_write_dma_cb, bm);
731 }
732 
733 static void ide_sector_write_dma(IDEState *s)
734 {
735     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
736     s->io_buffer_index = 0;
737     s->io_buffer_size = 0;
738     s->is_read = 0;
739     ide_dma_start(s, ide_write_dma_cb);
740 }
741 
742 void ide_atapi_cmd_ok(IDEState *s)
743 {
744     s->error = 0;
745     s->status = READY_STAT | SEEK_STAT;
746     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
747     ide_set_irq(s->bus);
748 }
749 
750 void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
751 {
752 #ifdef DEBUG_IDE_ATAPI
753     printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc);
754 #endif
755     s->error = sense_key << 4;
756     s->status = READY_STAT | ERR_STAT;
757     s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
758     s->sense_key = sense_key;
759     s->asc = asc;
760     ide_set_irq(s->bus);
761 }
762 
763 static void ide_atapi_cmd_check_status(IDEState *s)
764 {
765 #ifdef DEBUG_IDE_ATAPI
766     printf("atapi_cmd_check_status\n");
767 #endif
768     s->error = MC_ERR | (SENSE_UNIT_ATTENTION << 4);
769     s->status = ERR_STAT;
770     s->nsector = 0;
771     ide_set_irq(s->bus);
772 }
773 
774 static void ide_flush_cb(void *opaque, int ret)
775 {
776     IDEState *s = opaque;
777 
778     /* XXX: how do we signal I/O errors here? */
779 
780     s->status = READY_STAT | SEEK_STAT;
781     ide_set_irq(s->bus);
782 }
783 
784 static inline void cpu_to_ube16(uint8_t *buf, int val)
785 {
786     buf[0] = val >> 8;
787     buf[1] = val & 0xff;
788 }
789 
790 static inline void cpu_to_ube32(uint8_t *buf, unsigned int val)
791 {
792     buf[0] = val >> 24;
793     buf[1] = val >> 16;
794     buf[2] = val >> 8;
795     buf[3] = val & 0xff;
796 }
797 
798 static inline int ube16_to_cpu(const uint8_t *buf)
799 {
800     return (buf[0] << 8) | buf[1];
801 }
802 
803 static inline int ube32_to_cpu(const uint8_t *buf)
804 {
805     return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
806 }
807 
808 static void lba_to_msf(uint8_t *buf, int lba)
809 {
810     lba += 150;
811     buf[0] = (lba / 75) / 60;
812     buf[1] = (lba / 75) % 60;
813     buf[2] = lba % 75;
814 }
815 
816 static void cd_data_to_raw(uint8_t *buf, int lba)
817 {
818     /* sync bytes */
819     buf[0] = 0x00;
820     memset(buf + 1, 0xff, 10);
821     buf[11] = 0x00;
822     buf += 12;
823     /* MSF */
824     lba_to_msf(buf, lba);
825     buf[3] = 0x01; /* mode 1 data */
826     buf += 4;
827     /* data */
828     buf += 2048;
829     /* XXX: ECC not computed */
830     memset(buf, 0, 288);
831 }
832 
833 static int cd_read_sector(BlockDriverState *bs, int lba, uint8_t *buf,
834                            int sector_size)
835 {
836     int ret;
837 
838     switch(sector_size) {
839     case 2048:
840         ret = bdrv_read(bs, (int64_t)lba << 2, buf, 4);
841         break;
842     case 2352:
843         ret = bdrv_read(bs, (int64_t)lba << 2, buf + 16, 4);
844         if (ret < 0)
845             return ret;
846         cd_data_to_raw(buf, lba);
847         break;
848     default:
849         ret = -EIO;
850         break;
851     }
852     return ret;
853 }
854 
855 void ide_atapi_io_error(IDEState *s, int ret)
856 {
857     /* XXX: handle more errors */
858     if (ret == -ENOMEDIUM) {
859         ide_atapi_cmd_error(s, SENSE_NOT_READY,
860                             ASC_MEDIUM_NOT_PRESENT);
861     } else {
862         ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
863                             ASC_LOGICAL_BLOCK_OOR);
864     }
865 }
866 
867 /* The whole ATAPI transfer logic is handled in this function */
868 static void ide_atapi_cmd_reply_end(IDEState *s)
869 {
870     int byte_count_limit, size, ret;
871 #ifdef DEBUG_IDE_ATAPI
872     printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",
873            s->packet_transfer_size,
874            s->elementary_transfer_size,
875            s->io_buffer_index);
876 #endif
877     if (s->packet_transfer_size <= 0) {
878         /* end of transfer */
879         ide_transfer_stop(s);
880         s->status = READY_STAT | SEEK_STAT;
881         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
882         ide_set_irq(s->bus);
883 #ifdef DEBUG_IDE_ATAPI
884         printf("status=0x%x\n", s->status);
885 #endif
886     } else {
887         /* see if a new sector must be read */
888         if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {
889             ret = cd_read_sector(s->bs, s->lba, s->io_buffer, s->cd_sector_size);
890             if (ret < 0) {
891                 ide_transfer_stop(s);
892                 ide_atapi_io_error(s, ret);
893                 return;
894             }
895             s->lba++;
896             s->io_buffer_index = 0;
897         }
898         if (s->elementary_transfer_size > 0) {
899             /* there are some data left to transmit in this elementary
900                transfer */
901             size = s->cd_sector_size - s->io_buffer_index;
902             if (size > s->elementary_transfer_size)
903                 size = s->elementary_transfer_size;
904             ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
905                                size, ide_atapi_cmd_reply_end);
906             s->packet_transfer_size -= size;
907             s->elementary_transfer_size -= size;
908             s->io_buffer_index += size;
909         } else {
910             /* a new transfer is needed */
911             s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
912             byte_count_limit = s->lcyl | (s->hcyl << 8);
913 #ifdef DEBUG_IDE_ATAPI
914             printf("byte_count_limit=%d\n", byte_count_limit);
915 #endif
916             if (byte_count_limit == 0xffff)
917                 byte_count_limit--;
918             size = s->packet_transfer_size;
919             if (size > byte_count_limit) {
920                 /* byte count limit must be even if this case */
921                 if (byte_count_limit & 1)
922                     byte_count_limit--;
923                 size = byte_count_limit;
924             }
925             s->lcyl = size;
926             s->hcyl = size >> 8;
927             s->elementary_transfer_size = size;
928             /* we cannot transmit more than one sector at a time */
929             if (s->lba != -1) {
930                 if (size > (s->cd_sector_size - s->io_buffer_index))
931                     size = (s->cd_sector_size - s->io_buffer_index);
932             }
933             ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
934                                size, ide_atapi_cmd_reply_end);
935             s->packet_transfer_size -= size;
936             s->elementary_transfer_size -= size;
937             s->io_buffer_index += size;
938             ide_set_irq(s->bus);
939 #ifdef DEBUG_IDE_ATAPI
940             printf("status=0x%x\n", s->status);
941 #endif
942         }
943     }
944 }
945 
946 /* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
947 static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
948 {
949     if (size > max_size)
950         size = max_size;
951     s->lba = -1; /* no sector read */
952     s->packet_transfer_size = size;
953     s->io_buffer_size = size;    /* dma: send the reply data as one chunk */
954     s->elementary_transfer_size = 0;
955     s->io_buffer_index = 0;
956 
957     if (s->atapi_dma) {
958     	s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
959 	ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
960     } else {
961     	s->status = READY_STAT | SEEK_STAT;
962     	ide_atapi_cmd_reply_end(s);
963     }
964 }
965 
966 /* start a CD-CDROM read command */
967 static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
968                                    int sector_size)
969 {
970     s->lba = lba;
971     s->packet_transfer_size = nb_sectors * sector_size;
972     s->elementary_transfer_size = 0;
973     s->io_buffer_index = sector_size;
974     s->cd_sector_size = sector_size;
975 
976     s->status = READY_STAT | SEEK_STAT;
977     ide_atapi_cmd_reply_end(s);
978 }
979 
980 /* ATAPI DMA support */
981 
982 /* XXX: handle read errors */
983 static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret)
984 {
985     BMDMAState *bm = opaque;
986     IDEState *s = bmdma_active_if(bm);
987     int data_offset, n;
988 
989     if (ret < 0) {
990         ide_atapi_io_error(s, ret);
991         goto eot;
992     }
993 
994     if (s->io_buffer_size > 0) {
995 	/*
996 	 * For a cdrom read sector command (s->lba != -1),
997 	 * adjust the lba for the next s->io_buffer_size chunk
998 	 * and dma the current chunk.
999 	 * For a command != read (s->lba == -1), just transfer
1000 	 * the reply data.
1001 	 */
1002 	if (s->lba != -1) {
1003 	    if (s->cd_sector_size == 2352) {
1004 		n = 1;
1005 		cd_data_to_raw(s->io_buffer, s->lba);
1006 	    } else {
1007 		n = s->io_buffer_size >> 11;
1008 	    }
1009 	    s->lba += n;
1010 	}
1011         s->packet_transfer_size -= s->io_buffer_size;
1012         if (dma_buf_rw(bm, 1) == 0)
1013             goto eot;
1014     }
1015 
1016     if (s->packet_transfer_size <= 0) {
1017         s->status = READY_STAT | SEEK_STAT;
1018         s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1019         ide_set_irq(s->bus);
1020     eot:
1021         bm->status &= ~BM_STATUS_DMAING;
1022         bm->status |= BM_STATUS_INT;
1023         bm->dma_cb = NULL;
1024         bm->unit = -1;
1025         bm->aiocb = NULL;
1026         return;
1027     }
1028 
1029     s->io_buffer_index = 0;
1030     if (s->cd_sector_size == 2352) {
1031         n = 1;
1032         s->io_buffer_size = s->cd_sector_size;
1033         data_offset = 16;
1034     } else {
1035         n = s->packet_transfer_size >> 11;
1036         if (n > (IDE_DMA_BUF_SECTORS / 4))
1037             n = (IDE_DMA_BUF_SECTORS / 4);
1038         s->io_buffer_size = n * 2048;
1039         data_offset = 0;
1040     }
1041 #ifdef DEBUG_AIO
1042     printf("aio_read_cd: lba=%u n=%d\n", s->lba, n);
1043 #endif
1044     bm->iov.iov_base = (void *)(s->io_buffer + data_offset);
1045     bm->iov.iov_len = n * 4 * 512;
1046     qemu_iovec_init_external(&bm->qiov, &bm->iov, 1);
1047     bm->aiocb = bdrv_aio_readv(s->bs, (int64_t)s->lba << 2, &bm->qiov,
1048                                n * 4, ide_atapi_cmd_read_dma_cb, bm);
1049     if (!bm->aiocb) {
1050         /* Note: media not present is the most likely case */
1051         ide_atapi_cmd_error(s, SENSE_NOT_READY,
1052                             ASC_MEDIUM_NOT_PRESENT);
1053         goto eot;
1054     }
1055 }
1056 
1057 /* start a CD-CDROM read command with DMA */
1058 /* XXX: test if DMA is available */
1059 static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
1060                                    int sector_size)
1061 {
1062     s->lba = lba;
1063     s->packet_transfer_size = nb_sectors * sector_size;
1064     s->io_buffer_index = 0;
1065     s->io_buffer_size = 0;
1066     s->cd_sector_size = sector_size;
1067 
1068     /* XXX: check if BUSY_STAT should be set */
1069     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
1070     ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
1071 }
1072 
1073 static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors,
1074                                int sector_size)
1075 {
1076 #ifdef DEBUG_IDE_ATAPI
1077     printf("read %s: LBA=%d nb_sectors=%d\n", s->atapi_dma ? "dma" : "pio",
1078 	lba, nb_sectors);
1079 #endif
1080     if (s->atapi_dma) {
1081         ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size);
1082     } else {
1083         ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size);
1084     }
1085 }
1086 
1087 static inline uint8_t ide_atapi_set_profile(uint8_t *buf, uint8_t *index,
1088                                             uint16_t profile)
1089 {
1090     uint8_t *buf_profile = buf + 12; /* start of profiles */
1091 
1092     buf_profile += ((*index) * 4); /* start of indexed profile */
1093     cpu_to_ube16 (buf_profile, profile);
1094     buf_profile[2] = ((buf_profile[0] == buf[6]) && (buf_profile[1] == buf[7]));
1095 
1096     /* each profile adds 4 bytes to the response */
1097     (*index)++;
1098     buf[11] += 4; /* Additional Length */
1099 
1100     return 4;
1101 }
1102 
1103 static int ide_dvd_read_structure(IDEState *s, int format,
1104                                   const uint8_t *packet, uint8_t *buf)
1105 {
1106     switch (format) {
1107         case 0x0: /* Physical format information */
1108             {
1109                 int layer = packet[6];
1110                 uint64_t total_sectors;
1111 
1112                 if (layer != 0)
1113                     return -ASC_INV_FIELD_IN_CMD_PACKET;
1114 
1115                 bdrv_get_geometry(s->bs, &total_sectors);
1116                 total_sectors >>= 2;
1117                 if (total_sectors == 0)
1118                     return -ASC_MEDIUM_NOT_PRESENT;
1119 
1120                 buf[4] = 1;   /* DVD-ROM, part version 1 */
1121                 buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
1122                 buf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
1123                 buf[7] = 0;   /* default densities */
1124 
1125                 /* FIXME: 0x30000 per spec? */
1126                 cpu_to_ube32(buf + 8, 0); /* start sector */
1127                 cpu_to_ube32(buf + 12, total_sectors - 1); /* end sector */
1128                 cpu_to_ube32(buf + 16, total_sectors - 1); /* l0 end sector */
1129 
1130                 /* Size of buffer, not including 2 byte size field */
1131                 cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1132 
1133                 /* 2k data + 4 byte header */
1134                 return (2048 + 4);
1135             }
1136 
1137         case 0x01: /* DVD copyright information */
1138             buf[4] = 0; /* no copyright data */
1139             buf[5] = 0; /* no region restrictions */
1140 
1141             /* Size of buffer, not including 2 byte size field */
1142             cpu_to_be16wu((uint16_t *)buf, 4 + 2);
1143 
1144             /* 4 byte header + 4 byte data */
1145             return (4 + 4);
1146 
1147         case 0x03: /* BCA information - invalid field for no BCA info */
1148             return -ASC_INV_FIELD_IN_CMD_PACKET;
1149 
1150         case 0x04: /* DVD disc manufacturing information */
1151             /* Size of buffer, not including 2 byte size field */
1152             cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1153 
1154             /* 2k data + 4 byte header */
1155             return (2048 + 4);
1156 
1157         case 0xff:
1158             /*
1159              * This lists all the command capabilities above.  Add new ones
1160              * in order and update the length and buffer return values.
1161              */
1162 
1163             buf[4] = 0x00; /* Physical format */
1164             buf[5] = 0x40; /* Not writable, is readable */
1165             cpu_to_be16wu((uint16_t *)(buf + 6), 2048 + 4);
1166 
1167             buf[8] = 0x01; /* Copyright info */
1168             buf[9] = 0x40; /* Not writable, is readable */
1169             cpu_to_be16wu((uint16_t *)(buf + 10), 4 + 4);
1170 
1171             buf[12] = 0x03; /* BCA info */
1172             buf[13] = 0x40; /* Not writable, is readable */
1173             cpu_to_be16wu((uint16_t *)(buf + 14), 188 + 4);
1174 
1175             buf[16] = 0x04; /* Manufacturing info */
1176             buf[17] = 0x40; /* Not writable, is readable */
1177             cpu_to_be16wu((uint16_t *)(buf + 18), 2048 + 4);
1178 
1179             /* Size of buffer, not including 2 byte size field */
1180             cpu_to_be16wu((uint16_t *)buf, 16 + 2);
1181 
1182             /* data written + 4 byte header */
1183             return (16 + 4);
1184 
1185         default: /* TODO: formats beyond DVD-ROM requires */
1186             return -ASC_INV_FIELD_IN_CMD_PACKET;
1187     }
1188 }
1189 
1190 static void ide_atapi_cmd(IDEState *s)
1191 {
1192     const uint8_t *packet;
1193     uint8_t *buf;
1194     int max_len;
1195 
1196     packet = s->io_buffer;
1197     buf = s->io_buffer;
1198 #ifdef DEBUG_IDE_ATAPI
1199     {
1200         int i;
1201         printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
1202         for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
1203             printf(" %02x", packet[i]);
1204         }
1205         printf("\n");
1206     }
1207 #endif
1208     /* If there's a UNIT_ATTENTION condition pending, only
1209        REQUEST_SENSE and INQUIRY commands are allowed to complete. */
1210     if (s->sense_key == SENSE_UNIT_ATTENTION &&
1211 	s->io_buffer[0] != GPCMD_REQUEST_SENSE &&
1212 	s->io_buffer[0] != GPCMD_INQUIRY) {
1213 	ide_atapi_cmd_check_status(s);
1214 	return;
1215     }
1216     switch(s->io_buffer[0]) {
1217     case GPCMD_TEST_UNIT_READY:
1218         if (bdrv_is_inserted(s->bs) && !s->cdrom_changed) {
1219             ide_atapi_cmd_ok(s);
1220         } else {
1221             s->cdrom_changed = 0;
1222             ide_atapi_cmd_error(s, SENSE_NOT_READY,
1223                                 ASC_MEDIUM_NOT_PRESENT);
1224         }
1225         break;
1226     case GPCMD_MODE_SENSE_6:
1227     case GPCMD_MODE_SENSE_10:
1228         {
1229             int action, code;
1230             if (packet[0] == GPCMD_MODE_SENSE_10)
1231                 max_len = ube16_to_cpu(packet + 7);
1232             else
1233                 max_len = packet[4];
1234             action = packet[2] >> 6;
1235             code = packet[2] & 0x3f;
1236             switch(action) {
1237             case 0: /* current values */
1238                 switch(code) {
1239                 case 0x01: /* error recovery */
1240                     cpu_to_ube16(&buf[0], 16 + 6);
1241                     buf[2] = 0x70;
1242                     buf[3] = 0;
1243                     buf[4] = 0;
1244                     buf[5] = 0;
1245                     buf[6] = 0;
1246                     buf[7] = 0;
1247 
1248                     buf[8] = 0x01;
1249                     buf[9] = 0x06;
1250                     buf[10] = 0x00;
1251                     buf[11] = 0x05;
1252                     buf[12] = 0x00;
1253                     buf[13] = 0x00;
1254                     buf[14] = 0x00;
1255                     buf[15] = 0x00;
1256                     ide_atapi_cmd_reply(s, 16, max_len);
1257                     break;
1258                 case 0x2a:
1259                     cpu_to_ube16(&buf[0], 28 + 6);
1260                     buf[2] = 0x70;
1261                     buf[3] = 0;
1262                     buf[4] = 0;
1263                     buf[5] = 0;
1264                     buf[6] = 0;
1265                     buf[7] = 0;
1266 
1267                     buf[8] = 0x2a;
1268                     buf[9] = 0x12;
1269                     buf[10] = 0x00;
1270                     buf[11] = 0x00;
1271 
1272                     /* Claim PLAY_AUDIO capability (0x01) since some Linux
1273                        code checks for this to automount media. */
1274                     buf[12] = 0x71;
1275                     buf[13] = 3 << 5;
1276                     buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
1277                     if (bdrv_is_locked(s->bs))
1278                         buf[6] |= 1 << 1;
1279                     buf[15] = 0x00;
1280                     cpu_to_ube16(&buf[16], 706);
1281                     buf[18] = 0;
1282                     buf[19] = 2;
1283                     cpu_to_ube16(&buf[20], 512);
1284                     cpu_to_ube16(&buf[22], 706);
1285                     buf[24] = 0;
1286                     buf[25] = 0;
1287                     buf[26] = 0;
1288                     buf[27] = 0;
1289                     ide_atapi_cmd_reply(s, 28, max_len);
1290                     break;
1291                 default:
1292                     goto error_cmd;
1293                 }
1294                 break;
1295             case 1: /* changeable values */
1296                 goto error_cmd;
1297             case 2: /* default values */
1298                 goto error_cmd;
1299             default:
1300             case 3: /* saved values */
1301                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1302                                     ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
1303                 break;
1304             }
1305         }
1306         break;
1307     case GPCMD_REQUEST_SENSE:
1308         max_len = packet[4];
1309         memset(buf, 0, 18);
1310         buf[0] = 0x70 | (1 << 7);
1311         buf[2] = s->sense_key;
1312         buf[7] = 10;
1313         buf[12] = s->asc;
1314         if (s->sense_key == SENSE_UNIT_ATTENTION)
1315             s->sense_key = SENSE_NONE;
1316         ide_atapi_cmd_reply(s, 18, max_len);
1317         break;
1318     case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
1319         if (bdrv_is_inserted(s->bs)) {
1320             bdrv_set_locked(s->bs, packet[4] & 1);
1321             ide_atapi_cmd_ok(s);
1322         } else {
1323             ide_atapi_cmd_error(s, SENSE_NOT_READY,
1324                                 ASC_MEDIUM_NOT_PRESENT);
1325         }
1326         break;
1327     case GPCMD_READ_10:
1328     case GPCMD_READ_12:
1329         {
1330             int nb_sectors, lba;
1331 
1332             if (packet[0] == GPCMD_READ_10)
1333                 nb_sectors = ube16_to_cpu(packet + 7);
1334             else
1335                 nb_sectors = ube32_to_cpu(packet + 6);
1336             lba = ube32_to_cpu(packet + 2);
1337             if (nb_sectors == 0) {
1338                 ide_atapi_cmd_ok(s);
1339                 break;
1340             }
1341             ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1342         }
1343         break;
1344     case GPCMD_READ_CD:
1345         {
1346             int nb_sectors, lba, transfer_request;
1347 
1348             nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8];
1349             lba = ube32_to_cpu(packet + 2);
1350             if (nb_sectors == 0) {
1351                 ide_atapi_cmd_ok(s);
1352                 break;
1353             }
1354             transfer_request = packet[9];
1355             switch(transfer_request & 0xf8) {
1356             case 0x00:
1357                 /* nothing */
1358                 ide_atapi_cmd_ok(s);
1359                 break;
1360             case 0x10:
1361                 /* normal read */
1362                 ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1363                 break;
1364             case 0xf8:
1365                 /* read all data */
1366                 ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
1367                 break;
1368             default:
1369                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1370                                     ASC_INV_FIELD_IN_CMD_PACKET);
1371                 break;
1372             }
1373         }
1374         break;
1375     case GPCMD_SEEK:
1376         {
1377             unsigned int lba;
1378             uint64_t total_sectors;
1379 
1380             bdrv_get_geometry(s->bs, &total_sectors);
1381             total_sectors >>= 2;
1382             if (total_sectors == 0) {
1383                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1384                                     ASC_MEDIUM_NOT_PRESENT);
1385                 break;
1386             }
1387             lba = ube32_to_cpu(packet + 2);
1388             if (lba >= total_sectors) {
1389                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1390                                     ASC_LOGICAL_BLOCK_OOR);
1391                 break;
1392             }
1393             ide_atapi_cmd_ok(s);
1394         }
1395         break;
1396     case GPCMD_START_STOP_UNIT:
1397         {
1398             int start, eject, err = 0;
1399             start = packet[4] & 1;
1400             eject = (packet[4] >> 1) & 1;
1401 
1402             if (eject) {
1403                 err = bdrv_eject(s->bs, !start);
1404             }
1405 
1406             switch (err) {
1407             case 0:
1408                 ide_atapi_cmd_ok(s);
1409                 break;
1410             case -EBUSY:
1411                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1412                                     ASC_MEDIA_REMOVAL_PREVENTED);
1413                 break;
1414             default:
1415                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1416                                     ASC_MEDIUM_NOT_PRESENT);
1417                 break;
1418             }
1419         }
1420         break;
1421     case GPCMD_MECHANISM_STATUS:
1422         {
1423             max_len = ube16_to_cpu(packet + 8);
1424             cpu_to_ube16(buf, 0);
1425             /* no current LBA */
1426             buf[2] = 0;
1427             buf[3] = 0;
1428             buf[4] = 0;
1429             buf[5] = 1;
1430             cpu_to_ube16(buf + 6, 0);
1431             ide_atapi_cmd_reply(s, 8, max_len);
1432         }
1433         break;
1434     case GPCMD_READ_TOC_PMA_ATIP:
1435         {
1436             int format, msf, start_track, len;
1437             uint64_t total_sectors;
1438 
1439             bdrv_get_geometry(s->bs, &total_sectors);
1440             total_sectors >>= 2;
1441             if (total_sectors == 0) {
1442                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1443                                     ASC_MEDIUM_NOT_PRESENT);
1444                 break;
1445             }
1446             max_len = ube16_to_cpu(packet + 7);
1447             format = packet[9] >> 6;
1448             msf = (packet[1] >> 1) & 1;
1449             start_track = packet[6];
1450             switch(format) {
1451             case 0:
1452                 len = cdrom_read_toc(total_sectors, buf, msf, start_track);
1453                 if (len < 0)
1454                     goto error_cmd;
1455                 ide_atapi_cmd_reply(s, len, max_len);
1456                 break;
1457             case 1:
1458                 /* multi session : only a single session defined */
1459                 memset(buf, 0, 12);
1460                 buf[1] = 0x0a;
1461                 buf[2] = 0x01;
1462                 buf[3] = 0x01;
1463                 ide_atapi_cmd_reply(s, 12, max_len);
1464                 break;
1465             case 2:
1466                 len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
1467                 if (len < 0)
1468                     goto error_cmd;
1469                 ide_atapi_cmd_reply(s, len, max_len);
1470                 break;
1471             default:
1472             error_cmd:
1473                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1474                                     ASC_INV_FIELD_IN_CMD_PACKET);
1475                 break;
1476             }
1477         }
1478         break;
1479     case GPCMD_READ_CDVD_CAPACITY:
1480         {
1481             uint64_t total_sectors;
1482 
1483             bdrv_get_geometry(s->bs, &total_sectors);
1484             total_sectors >>= 2;
1485             if (total_sectors == 0) {
1486                 ide_atapi_cmd_error(s, SENSE_NOT_READY,
1487                                     ASC_MEDIUM_NOT_PRESENT);
1488                 break;
1489             }
1490             /* NOTE: it is really the number of sectors minus 1 */
1491             cpu_to_ube32(buf, total_sectors - 1);
1492             cpu_to_ube32(buf + 4, 2048);
1493             ide_atapi_cmd_reply(s, 8, 8);
1494         }
1495         break;
1496     case GPCMD_READ_DVD_STRUCTURE:
1497         {
1498             int media = packet[1];
1499             int format = packet[7];
1500             int ret;
1501 
1502             max_len = ube16_to_cpu(packet + 8);
1503 
1504             if (format < 0xff) {
1505                 if (media_is_cd(s)) {
1506                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1507                                         ASC_INCOMPATIBLE_FORMAT);
1508                     break;
1509                 } else if (!media_present(s)) {
1510                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1511                                         ASC_INV_FIELD_IN_CMD_PACKET);
1512                     break;
1513                 }
1514             }
1515 
1516             memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
1517                    IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
1518 
1519             switch (format) {
1520                 case 0x00 ... 0x7f:
1521                 case 0xff:
1522                     if (media == 0) {
1523                         ret = ide_dvd_read_structure(s, format, packet, buf);
1524 
1525                         if (ret < 0)
1526                             ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, -ret);
1527                         else
1528                             ide_atapi_cmd_reply(s, ret, max_len);
1529 
1530                         break;
1531                     }
1532                     /* TODO: BD support, fall through for now */
1533 
1534                 /* Generic disk structures */
1535                 case 0x80: /* TODO: AACS volume identifier */
1536                 case 0x81: /* TODO: AACS media serial number */
1537                 case 0x82: /* TODO: AACS media identifier */
1538                 case 0x83: /* TODO: AACS media key block */
1539                 case 0x90: /* TODO: List of recognized format layers */
1540                 case 0xc0: /* TODO: Write protection status */
1541                 default:
1542                     ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1543                                         ASC_INV_FIELD_IN_CMD_PACKET);
1544                     break;
1545             }
1546         }
1547         break;
1548     case GPCMD_SET_SPEED:
1549         ide_atapi_cmd_ok(s);
1550         break;
1551     case GPCMD_INQUIRY:
1552         max_len = packet[4];
1553         buf[0] = 0x05; /* CD-ROM */
1554         buf[1] = 0x80; /* removable */
1555         buf[2] = 0x00; /* ISO */
1556         buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
1557         buf[4] = 31; /* additional length */
1558         buf[5] = 0; /* reserved */
1559         buf[6] = 0; /* reserved */
1560         buf[7] = 0; /* reserved */
1561         padstr8(buf + 8, 8, "QEMU");
1562         padstr8(buf + 16, 16, "QEMU DVD-ROM");
1563         padstr8(buf + 32, 4, QEMU_VERSION);
1564         ide_atapi_cmd_reply(s, 36, max_len);
1565         break;
1566     case GPCMD_GET_CONFIGURATION:
1567         {
1568             uint32_t len;
1569             uint8_t index = 0;
1570 
1571             /* only feature 0 is supported */
1572             if (packet[2] != 0 || packet[3] != 0) {
1573                 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1574                                     ASC_INV_FIELD_IN_CMD_PACKET);
1575                 break;
1576             }
1577 
1578             /* XXX: could result in alignment problems in some architectures */
1579             max_len = ube16_to_cpu(packet + 7);
1580 
1581             /*
1582              * XXX: avoid overflow for io_buffer if max_len is bigger than
1583              *      the size of that buffer (dimensioned to max number of
1584              *      sectors to transfer at once)
1585              *
1586              *      Only a problem if the feature/profiles grow.
1587              */
1588             if (max_len > 512) /* XXX: assume 1 sector */
1589                 max_len = 512;
1590 
1591             memset(buf, 0, max_len);
1592             /*
1593              * the number of sectors from the media tells us which profile
1594              * to use as current.  0 means there is no media
1595              */
1596             if (media_is_dvd(s))
1597                 cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
1598             else if (media_is_cd(s))
1599                 cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
1600 
1601             buf[10] = 0x02 | 0x01; /* persistent and current */
1602             len = 12; /* headers: 8 + 4 */
1603             len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
1604             len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
1605             cpu_to_ube32(buf, len - 4); /* data length */
1606 
1607             ide_atapi_cmd_reply(s, len, max_len);
1608             break;
1609         }
1610     default:
1611         ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1612                             ASC_ILLEGAL_OPCODE);
1613         break;
1614     }
1615 }
1616 
1617 static void ide_cfata_metadata_inquiry(IDEState *s)
1618 {
1619     uint16_t *p;
1620     uint32_t spd;
1621 
1622     p = (uint16_t *) s->io_buffer;
1623     memset(p, 0, 0x200);
1624     spd = ((s->mdata_size - 1) >> 9) + 1;
1625 
1626     put_le16(p + 0, 0x0001);			/* Data format revision */
1627     put_le16(p + 1, 0x0000);			/* Media property: silicon */
1628     put_le16(p + 2, s->media_changed);		/* Media status */
1629     put_le16(p + 3, s->mdata_size & 0xffff);	/* Capacity in bytes (low) */
1630     put_le16(p + 4, s->mdata_size >> 16);	/* Capacity in bytes (high) */
1631     put_le16(p + 5, spd & 0xffff);		/* Sectors per device (low) */
1632     put_le16(p + 6, spd >> 16);			/* Sectors per device (high) */
1633 }
1634 
1635 static void ide_cfata_metadata_read(IDEState *s)
1636 {
1637     uint16_t *p;
1638 
1639     if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
1640         s->status = ERR_STAT;
1641         s->error = ABRT_ERR;
1642         return;
1643     }
1644 
1645     p = (uint16_t *) s->io_buffer;
1646     memset(p, 0, 0x200);
1647 
1648     put_le16(p + 0, s->media_changed);		/* Media status */
1649     memcpy(p + 1, s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
1650                     MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
1651                                     s->nsector << 9), 0x200 - 2));
1652 }
1653 
1654 static void ide_cfata_metadata_write(IDEState *s)
1655 {
1656     if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
1657         s->status = ERR_STAT;
1658         s->error = ABRT_ERR;
1659         return;
1660     }
1661 
1662     s->media_changed = 0;
1663 
1664     memcpy(s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
1665                     s->io_buffer + 2,
1666                     MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
1667                                     s->nsector << 9), 0x200 - 2));
1668 }
1669 
1670 /* called when the inserted state of the media has changed */
1671 static void cdrom_change_cb(void *opaque)
1672 {
1673     IDEState *s = opaque;
1674     uint64_t nb_sectors;
1675 
1676     bdrv_get_geometry(s->bs, &nb_sectors);
1677     s->nb_sectors = nb_sectors;
1678 
1679     s->sense_key = SENSE_UNIT_ATTENTION;
1680     s->asc = ASC_MEDIUM_MAY_HAVE_CHANGED;
1681     s->cdrom_changed = 1;
1682     ide_set_irq(s->bus);
1683 }
1684 
1685 static void ide_cmd_lba48_transform(IDEState *s, int lba48)
1686 {
1687     s->lba48 = lba48;
1688 
1689     /* handle the 'magic' 0 nsector count conversion here. to avoid
1690      * fiddling with the rest of the read logic, we just store the
1691      * full sector count in ->nsector and ignore ->hob_nsector from now
1692      */
1693     if (!s->lba48) {
1694 	if (!s->nsector)
1695 	    s->nsector = 256;
1696     } else {
1697 	if (!s->nsector && !s->hob_nsector)
1698 	    s->nsector = 65536;
1699 	else {
1700 	    int lo = s->nsector;
1701 	    int hi = s->hob_nsector;
1702 
1703 	    s->nsector = (hi << 8) | lo;
1704 	}
1705     }
1706 }
1707 
1708 static void ide_clear_hob(IDEBus *bus)
1709 {
1710     /* any write clears HOB high bit of device control register */
1711     bus->ifs[0].select &= ~(1 << 7);
1712     bus->ifs[1].select &= ~(1 << 7);
1713 }
1714 
1715 void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
1716 {
1717     IDEBus *bus = opaque;
1718     IDEState *s;
1719     int n;
1720     int lba48 = 0;
1721 
1722 #ifdef DEBUG_IDE
1723     printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
1724 #endif
1725 
1726     addr &= 7;
1727 
1728     /* ignore writes to command block while busy with previous command */
1729     if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
1730         return;
1731 
1732     switch(addr) {
1733     case 0:
1734         break;
1735     case 1:
1736 	ide_clear_hob(bus);
1737         /* NOTE: data is written to the two drives */
1738 	bus->ifs[0].hob_feature = bus->ifs[0].feature;
1739 	bus->ifs[1].hob_feature = bus->ifs[1].feature;
1740         bus->ifs[0].feature = val;
1741         bus->ifs[1].feature = val;
1742         break;
1743     case 2:
1744 	ide_clear_hob(bus);
1745 	bus->ifs[0].hob_nsector = bus->ifs[0].nsector;
1746 	bus->ifs[1].hob_nsector = bus->ifs[1].nsector;
1747         bus->ifs[0].nsector = val;
1748         bus->ifs[1].nsector = val;
1749         break;
1750     case 3:
1751 	ide_clear_hob(bus);
1752 	bus->ifs[0].hob_sector = bus->ifs[0].sector;
1753 	bus->ifs[1].hob_sector = bus->ifs[1].sector;
1754         bus->ifs[0].sector = val;
1755         bus->ifs[1].sector = val;
1756         break;
1757     case 4:
1758 	ide_clear_hob(bus);
1759 	bus->ifs[0].hob_lcyl = bus->ifs[0].lcyl;
1760 	bus->ifs[1].hob_lcyl = bus->ifs[1].lcyl;
1761         bus->ifs[0].lcyl = val;
1762         bus->ifs[1].lcyl = val;
1763         break;
1764     case 5:
1765 	ide_clear_hob(bus);
1766 	bus->ifs[0].hob_hcyl = bus->ifs[0].hcyl;
1767 	bus->ifs[1].hob_hcyl = bus->ifs[1].hcyl;
1768         bus->ifs[0].hcyl = val;
1769         bus->ifs[1].hcyl = val;
1770         break;
1771     case 6:
1772 	/* FIXME: HOB readback uses bit 7 */
1773         bus->ifs[0].select = (val & ~0x10) | 0xa0;
1774         bus->ifs[1].select = (val | 0x10) | 0xa0;
1775         /* select drive */
1776         bus->unit = (val >> 4) & 1;
1777         break;
1778     default:
1779     case 7:
1780         /* command */
1781 #if defined(DEBUG_IDE)
1782         printf("ide: CMD=%02x\n", val);
1783 #endif
1784         s = idebus_active_if(bus);
1785         /* ignore commands to non existant slave */
1786         if (s != bus->ifs && !s->bs)
1787             break;
1788 
1789         /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */
1790         if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)
1791             break;
1792 
1793         switch(val) {
1794         case WIN_IDENTIFY:
1795             if (s->bs && !s->is_cdrom) {
1796                 if (!s->is_cf)
1797                     ide_identify(s);
1798                 else
1799                     ide_cfata_identify(s);
1800                 s->status = READY_STAT | SEEK_STAT;
1801                 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
1802             } else {
1803                 if (s->is_cdrom) {
1804                     ide_set_signature(s);
1805                 }
1806                 ide_abort_command(s);
1807             }
1808             ide_set_irq(s->bus);
1809             break;
1810         case WIN_SPECIFY:
1811         case WIN_RECAL:
1812             s->error = 0;
1813             s->status = READY_STAT | SEEK_STAT;
1814             ide_set_irq(s->bus);
1815             break;
1816         case WIN_SETMULT:
1817             if (s->is_cf && s->nsector == 0) {
1818                 /* Disable Read and Write Multiple */
1819                 s->mult_sectors = 0;
1820                 s->status = READY_STAT | SEEK_STAT;
1821             } else if ((s->nsector & 0xff) != 0 &&
1822                 ((s->nsector & 0xff) > MAX_MULT_SECTORS ||
1823                  (s->nsector & (s->nsector - 1)) != 0)) {
1824                 ide_abort_command(s);
1825             } else {
1826                 s->mult_sectors = s->nsector & 0xff;
1827                 s->status = READY_STAT | SEEK_STAT;
1828             }
1829             ide_set_irq(s->bus);
1830             break;
1831         case WIN_VERIFY_EXT:
1832 	    lba48 = 1;
1833         case WIN_VERIFY:
1834         case WIN_VERIFY_ONCE:
1835             /* do sector number check ? */
1836 	    ide_cmd_lba48_transform(s, lba48);
1837             s->status = READY_STAT | SEEK_STAT;
1838             ide_set_irq(s->bus);
1839             break;
1840 	case WIN_READ_EXT:
1841 	    lba48 = 1;
1842         case WIN_READ:
1843         case WIN_READ_ONCE:
1844             if (!s->bs)
1845                 goto abort_cmd;
1846 	    ide_cmd_lba48_transform(s, lba48);
1847             s->req_nb_sectors = 1;
1848             ide_sector_read(s);
1849             break;
1850 	case WIN_WRITE_EXT:
1851 	    lba48 = 1;
1852         case WIN_WRITE:
1853         case WIN_WRITE_ONCE:
1854         case CFA_WRITE_SECT_WO_ERASE:
1855         case WIN_WRITE_VERIFY:
1856 	    ide_cmd_lba48_transform(s, lba48);
1857             s->error = 0;
1858             s->status = SEEK_STAT | READY_STAT;
1859             s->req_nb_sectors = 1;
1860             ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);
1861             s->media_changed = 1;
1862             break;
1863 	case WIN_MULTREAD_EXT:
1864 	    lba48 = 1;
1865         case WIN_MULTREAD:
1866             if (!s->mult_sectors)
1867                 goto abort_cmd;
1868 	    ide_cmd_lba48_transform(s, lba48);
1869             s->req_nb_sectors = s->mult_sectors;
1870             ide_sector_read(s);
1871             break;
1872         case WIN_MULTWRITE_EXT:
1873 	    lba48 = 1;
1874         case WIN_MULTWRITE:
1875         case CFA_WRITE_MULTI_WO_ERASE:
1876             if (!s->mult_sectors)
1877                 goto abort_cmd;
1878 	    ide_cmd_lba48_transform(s, lba48);
1879             s->error = 0;
1880             s->status = SEEK_STAT | READY_STAT;
1881             s->req_nb_sectors = s->mult_sectors;
1882             n = s->nsector;
1883             if (n > s->req_nb_sectors)
1884                 n = s->req_nb_sectors;
1885             ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);
1886             s->media_changed = 1;
1887             break;
1888 	case WIN_READDMA_EXT:
1889 	    lba48 = 1;
1890         case WIN_READDMA:
1891         case WIN_READDMA_ONCE:
1892             if (!s->bs)
1893                 goto abort_cmd;
1894 	    ide_cmd_lba48_transform(s, lba48);
1895             ide_sector_read_dma(s);
1896             break;
1897 	case WIN_WRITEDMA_EXT:
1898 	    lba48 = 1;
1899         case WIN_WRITEDMA:
1900         case WIN_WRITEDMA_ONCE:
1901             if (!s->bs)
1902                 goto abort_cmd;
1903 	    ide_cmd_lba48_transform(s, lba48);
1904             ide_sector_write_dma(s);
1905             s->media_changed = 1;
1906             break;
1907         case WIN_READ_NATIVE_MAX_EXT:
1908 	    lba48 = 1;
1909         case WIN_READ_NATIVE_MAX:
1910 	    ide_cmd_lba48_transform(s, lba48);
1911             ide_set_sector(s, s->nb_sectors - 1);
1912             s->status = READY_STAT | SEEK_STAT;
1913             ide_set_irq(s->bus);
1914             break;
1915         case WIN_CHECKPOWERMODE1:
1916         case WIN_CHECKPOWERMODE2:
1917             s->nsector = 0xff; /* device active or idle */
1918             s->status = READY_STAT | SEEK_STAT;
1919             ide_set_irq(s->bus);
1920             break;
1921         case WIN_SETFEATURES:
1922             if (!s->bs)
1923                 goto abort_cmd;
1924             /* XXX: valid for CDROM ? */
1925             switch(s->feature) {
1926             case 0xcc: /* reverting to power-on defaults enable */
1927             case 0x66: /* reverting to power-on defaults disable */
1928             case 0x02: /* write cache enable */
1929             case 0x82: /* write cache disable */
1930             case 0xaa: /* read look-ahead enable */
1931             case 0x55: /* read look-ahead disable */
1932             case 0x05: /* set advanced power management mode */
1933             case 0x85: /* disable advanced power management mode */
1934             case 0x69: /* NOP */
1935             case 0x67: /* NOP */
1936             case 0x96: /* NOP */
1937             case 0x9a: /* NOP */
1938             case 0x42: /* enable Automatic Acoustic Mode */
1939             case 0xc2: /* disable Automatic Acoustic Mode */
1940                 s->status = READY_STAT | SEEK_STAT;
1941                 ide_set_irq(s->bus);
1942                 break;
1943             case 0x03: { /* set transfer mode */
1944 		uint8_t val = s->nsector & 0x07;
1945 
1946 		switch (s->nsector >> 3) {
1947 		    case 0x00: /* pio default */
1948 		    case 0x01: /* pio mode */
1949 			put_le16(s->identify_data + 62,0x07);
1950 			put_le16(s->identify_data + 63,0x07);
1951 			put_le16(s->identify_data + 88,0x3f);
1952 			break;
1953                     case 0x02: /* sigle word dma mode*/
1954 			put_le16(s->identify_data + 62,0x07 | (1 << (val + 8)));
1955 			put_le16(s->identify_data + 63,0x07);
1956 			put_le16(s->identify_data + 88,0x3f);
1957 			break;
1958 		    case 0x04: /* mdma mode */
1959 			put_le16(s->identify_data + 62,0x07);
1960 			put_le16(s->identify_data + 63,0x07 | (1 << (val + 8)));
1961 			put_le16(s->identify_data + 88,0x3f);
1962 			break;
1963 		    case 0x08: /* udma mode */
1964 			put_le16(s->identify_data + 62,0x07);
1965 			put_le16(s->identify_data + 63,0x07);
1966 			put_le16(s->identify_data + 88,0x3f | (1 << (val + 8)));
1967 			break;
1968 		    default:
1969 			goto abort_cmd;
1970 		}
1971                 s->status = READY_STAT | SEEK_STAT;
1972                 ide_set_irq(s->bus);
1973                 break;
1974 	    }
1975             default:
1976                 goto abort_cmd;
1977             }
1978             break;
1979         case WIN_FLUSH_CACHE:
1980         case WIN_FLUSH_CACHE_EXT:
1981             if (s->bs)
1982                 bdrv_aio_flush(s->bs, ide_flush_cb, s);
1983             else
1984                 ide_flush_cb(s, 0);
1985             break;
1986         case WIN_STANDBY:
1987         case WIN_STANDBY2:
1988         case WIN_STANDBYNOW1:
1989         case WIN_STANDBYNOW2:
1990         case WIN_IDLEIMMEDIATE:
1991         case CFA_IDLEIMMEDIATE:
1992         case WIN_SETIDLE1:
1993         case WIN_SETIDLE2:
1994         case WIN_SLEEPNOW1:
1995         case WIN_SLEEPNOW2:
1996             s->status = READY_STAT;
1997             ide_set_irq(s->bus);
1998             break;
1999         case WIN_SEEK:
2000             if(s->is_cdrom)
2001                 goto abort_cmd;
2002             /* XXX: Check that seek is within bounds */
2003             s->status = READY_STAT | SEEK_STAT;
2004             ide_set_irq(s->bus);
2005             break;
2006             /* ATAPI commands */
2007         case WIN_PIDENTIFY:
2008             if (s->is_cdrom) {
2009                 ide_atapi_identify(s);
2010                 s->status = READY_STAT | SEEK_STAT;
2011                 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
2012             } else {
2013                 ide_abort_command(s);
2014             }
2015             ide_set_irq(s->bus);
2016             break;
2017         case WIN_DIAGNOSE:
2018             ide_set_signature(s);
2019             if (s->is_cdrom)
2020                 s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet
2021                                 * devices to return a clear status register
2022                                 * with READY_STAT *not* set. */
2023             else
2024                 s->status = READY_STAT | SEEK_STAT;
2025             s->error = 0x01; /* Device 0 passed, Device 1 passed or not
2026                               * present.
2027                               */
2028             ide_set_irq(s->bus);
2029             break;
2030         case WIN_SRST:
2031             if (!s->is_cdrom)
2032                 goto abort_cmd;
2033             ide_set_signature(s);
2034             s->status = 0x00; /* NOTE: READY is _not_ set */
2035             s->error = 0x01;
2036             break;
2037         case WIN_PACKETCMD:
2038             if (!s->is_cdrom)
2039                 goto abort_cmd;
2040             /* overlapping commands not supported */
2041             if (s->feature & 0x02)
2042                 goto abort_cmd;
2043             s->status = READY_STAT | SEEK_STAT;
2044             s->atapi_dma = s->feature & 1;
2045             s->nsector = 1;
2046             ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
2047                                ide_atapi_cmd);
2048             break;
2049         /* CF-ATA commands */
2050         case CFA_REQ_EXT_ERROR_CODE:
2051             if (!s->is_cf)
2052                 goto abort_cmd;
2053             s->error = 0x09;    /* miscellaneous error */
2054             s->status = READY_STAT | SEEK_STAT;
2055             ide_set_irq(s->bus);
2056             break;
2057         case CFA_ERASE_SECTORS:
2058         case CFA_WEAR_LEVEL:
2059             if (!s->is_cf)
2060                 goto abort_cmd;
2061             if (val == CFA_WEAR_LEVEL)
2062                 s->nsector = 0;
2063             if (val == CFA_ERASE_SECTORS)
2064                 s->media_changed = 1;
2065             s->error = 0x00;
2066             s->status = READY_STAT | SEEK_STAT;
2067             ide_set_irq(s->bus);
2068             break;
2069         case CFA_TRANSLATE_SECTOR:
2070             if (!s->is_cf)
2071                 goto abort_cmd;
2072             s->error = 0x00;
2073             s->status = READY_STAT | SEEK_STAT;
2074             memset(s->io_buffer, 0, 0x200);
2075             s->io_buffer[0x00] = s->hcyl;			/* Cyl MSB */
2076             s->io_buffer[0x01] = s->lcyl;			/* Cyl LSB */
2077             s->io_buffer[0x02] = s->select;			/* Head */
2078             s->io_buffer[0x03] = s->sector;			/* Sector */
2079             s->io_buffer[0x04] = ide_get_sector(s) >> 16;	/* LBA MSB */
2080             s->io_buffer[0x05] = ide_get_sector(s) >> 8;	/* LBA */
2081             s->io_buffer[0x06] = ide_get_sector(s) >> 0;	/* LBA LSB */
2082             s->io_buffer[0x13] = 0x00;				/* Erase flag */
2083             s->io_buffer[0x18] = 0x00;				/* Hot count */
2084             s->io_buffer[0x19] = 0x00;				/* Hot count */
2085             s->io_buffer[0x1a] = 0x01;				/* Hot count */
2086             ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2087             ide_set_irq(s->bus);
2088             break;
2089         case CFA_ACCESS_METADATA_STORAGE:
2090             if (!s->is_cf)
2091                 goto abort_cmd;
2092             switch (s->feature) {
2093             case 0x02:	/* Inquiry Metadata Storage */
2094                 ide_cfata_metadata_inquiry(s);
2095                 break;
2096             case 0x03:	/* Read Metadata Storage */
2097                 ide_cfata_metadata_read(s);
2098                 break;
2099             case 0x04:	/* Write Metadata Storage */
2100                 ide_cfata_metadata_write(s);
2101                 break;
2102             default:
2103                 goto abort_cmd;
2104             }
2105             ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2106             s->status = 0x00; /* NOTE: READY is _not_ set */
2107             ide_set_irq(s->bus);
2108             break;
2109         case IBM_SENSE_CONDITION:
2110             if (!s->is_cf)
2111                 goto abort_cmd;
2112             switch (s->feature) {
2113             case 0x01:  /* sense temperature in device */
2114                 s->nsector = 0x50;      /* +20 C */
2115                 break;
2116             default:
2117                 goto abort_cmd;
2118             }
2119             s->status = READY_STAT | SEEK_STAT;
2120             ide_set_irq(s->bus);
2121             break;
2122 
2123 	case WIN_SMART:
2124 	    if (s->is_cdrom)
2125 		goto abort_cmd;
2126 	    if (s->hcyl != 0xc2 || s->lcyl != 0x4f)
2127 		goto abort_cmd;
2128 	    if (!s->smart_enabled && s->feature != SMART_ENABLE)
2129 		goto abort_cmd;
2130 	    switch (s->feature) {
2131 	    case SMART_DISABLE:
2132 		s->smart_enabled = 0;
2133 		s->status = READY_STAT | SEEK_STAT;
2134 		ide_set_irq(s->bus);
2135 		break;
2136 	    case SMART_ENABLE:
2137 		s->smart_enabled = 1;
2138 		s->status = READY_STAT | SEEK_STAT;
2139 		ide_set_irq(s->bus);
2140 		break;
2141 	    case SMART_ATTR_AUTOSAVE:
2142 		switch (s->sector) {
2143 		case 0x00:
2144 		    s->smart_autosave = 0;
2145 		    break;
2146 		case 0xf1:
2147 		    s->smart_autosave = 1;
2148 		    break;
2149 		default:
2150 		    goto abort_cmd;
2151 		}
2152 		s->status = READY_STAT | SEEK_STAT;
2153 		ide_set_irq(s->bus);
2154 		break;
2155 	    case SMART_STATUS:
2156 		if (!s->smart_errors) {
2157 		    s->hcyl = 0xc2;
2158 		    s->lcyl = 0x4f;
2159 		} else {
2160 		    s->hcyl = 0x2c;
2161 		    s->lcyl = 0xf4;
2162 		}
2163 		s->status = READY_STAT | SEEK_STAT;
2164 		ide_set_irq(s->bus);
2165 		break;
2166 	    case SMART_READ_THRESH:
2167 		memset(s->io_buffer, 0, 0x200);
2168 		s->io_buffer[0] = 0x01; /* smart struct version */
2169 		for (n=0; n<30; n++) {
2170 		    if (smart_attributes[n][0] == 0)
2171 			break;
2172 		    s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2173 		    s->io_buffer[2+1+(n*12)] = smart_attributes[n][4];
2174 		}
2175 		for (n=0; n<511; n++) /* checksum */
2176 		    s->io_buffer[511] += s->io_buffer[n];
2177 		s->io_buffer[511] = 0x100 - s->io_buffer[511];
2178 		s->status = READY_STAT | SEEK_STAT;
2179 		ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2180 		ide_set_irq(s->bus);
2181 		break;
2182 	    case SMART_READ_DATA:
2183 		memset(s->io_buffer, 0, 0x200);
2184 		s->io_buffer[0] = 0x01; /* smart struct version */
2185 		for (n=0; n<30; n++) {
2186 		    if (smart_attributes[n][0] == 0)
2187 			break;
2188 		    s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2189 		    s->io_buffer[2+1+(n*12)] = smart_attributes[n][1];
2190 		    s->io_buffer[2+3+(n*12)] = smart_attributes[n][2];
2191 		    s->io_buffer[2+4+(n*12)] = smart_attributes[n][3];
2192 		}
2193 		s->io_buffer[362] = 0x02 | (s->smart_autosave?0x80:0x00);
2194 		if (s->smart_selftest_count == 0) {
2195 		    s->io_buffer[363] = 0;
2196 		} else {
2197 		    s->io_buffer[363] =
2198 			s->smart_selftest_data[3 +
2199 					       (s->smart_selftest_count - 1) *
2200 					       24];
2201 		}
2202 		s->io_buffer[364] = 0x20;
2203 		s->io_buffer[365] = 0x01;
2204 		/* offline data collection capacity: execute + self-test*/
2205 		s->io_buffer[367] = (1<<4 | 1<<3 | 1);
2206 		s->io_buffer[368] = 0x03; /* smart capability (1) */
2207 		s->io_buffer[369] = 0x00; /* smart capability (2) */
2208 		s->io_buffer[370] = 0x01; /* error logging supported */
2209 		s->io_buffer[372] = 0x02; /* minutes for poll short test */
2210 		s->io_buffer[373] = 0x36; /* minutes for poll ext test */
2211 		s->io_buffer[374] = 0x01; /* minutes for poll conveyance */
2212 
2213 		for (n=0; n<511; n++)
2214 		    s->io_buffer[511] += s->io_buffer[n];
2215 		s->io_buffer[511] = 0x100 - s->io_buffer[511];
2216 		s->status = READY_STAT | SEEK_STAT;
2217 		ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2218 		ide_set_irq(s->bus);
2219 		break;
2220 	    case SMART_READ_LOG:
2221 		switch (s->sector) {
2222 		case 0x01: /* summary smart error log */
2223 		    memset(s->io_buffer, 0, 0x200);
2224 		    s->io_buffer[0] = 0x01;
2225 		    s->io_buffer[1] = 0x00; /* no error entries */
2226 		    s->io_buffer[452] = s->smart_errors & 0xff;
2227 		    s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;
2228 
2229 		    for (n=0; n<511; n++)
2230 			s->io_buffer[511] += s->io_buffer[n];
2231 		    s->io_buffer[511] = 0x100 - s->io_buffer[511];
2232 		    break;
2233 		case 0x06: /* smart self test log */
2234 		    memset(s->io_buffer, 0, 0x200);
2235 		    s->io_buffer[0] = 0x01;
2236 		    if (s->smart_selftest_count == 0) {
2237 			s->io_buffer[508] = 0;
2238 		    } else {
2239 			s->io_buffer[508] = s->smart_selftest_count;
2240 			for (n=2; n<506; n++)
2241 			    s->io_buffer[n] = s->smart_selftest_data[n];
2242 		    }
2243 		    for (n=0; n<511; n++)
2244 			s->io_buffer[511] += s->io_buffer[n];
2245 		    s->io_buffer[511] = 0x100 - s->io_buffer[511];
2246 		    break;
2247 		default:
2248 		    goto abort_cmd;
2249 		}
2250 		s->status = READY_STAT | SEEK_STAT;
2251 		ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2252 		ide_set_irq(s->bus);
2253 		break;
2254 	    case SMART_EXECUTE_OFFLINE:
2255 		switch (s->sector) {
2256 		case 0: /* off-line routine */
2257 		case 1: /* short self test */
2258 		case 2: /* extended self test */
2259 		    s->smart_selftest_count++;
2260 		    if(s->smart_selftest_count > 21)
2261 			s->smart_selftest_count = 0;
2262 		    n = 2 + (s->smart_selftest_count - 1) * 24;
2263 		    s->smart_selftest_data[n] = s->sector;
2264 		    s->smart_selftest_data[n+1] = 0x00; /* OK and finished */
2265 		    s->smart_selftest_data[n+2] = 0x34; /* hour count lsb */
2266 		    s->smart_selftest_data[n+3] = 0x12; /* hour count msb */
2267 		    s->status = READY_STAT | SEEK_STAT;
2268 		    ide_set_irq(s->bus);
2269 		    break;
2270 		default:
2271 		    goto abort_cmd;
2272 		}
2273 		break;
2274 	    default:
2275 		goto abort_cmd;
2276 	    }
2277 	    break;
2278         default:
2279         abort_cmd:
2280             ide_abort_command(s);
2281             ide_set_irq(s->bus);
2282             break;
2283         }
2284     }
2285 }
2286 
2287 uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
2288 {
2289     IDEBus *bus = opaque;
2290     IDEState *s = idebus_active_if(bus);
2291     uint32_t addr;
2292     int ret, hob;
2293 
2294     addr = addr1 & 7;
2295     /* FIXME: HOB readback uses bit 7, but it's always set right now */
2296     //hob = s->select & (1 << 7);
2297     hob = 0;
2298     switch(addr) {
2299     case 0:
2300         ret = 0xff;
2301         break;
2302     case 1:
2303         if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2304             (s != bus->ifs && !s->bs))
2305             ret = 0;
2306         else if (!hob)
2307             ret = s->error;
2308 	else
2309 	    ret = s->hob_feature;
2310         break;
2311     case 2:
2312         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2313             ret = 0;
2314         else if (!hob)
2315             ret = s->nsector & 0xff;
2316 	else
2317 	    ret = s->hob_nsector;
2318         break;
2319     case 3:
2320         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2321             ret = 0;
2322         else if (!hob)
2323             ret = s->sector;
2324 	else
2325 	    ret = s->hob_sector;
2326         break;
2327     case 4:
2328         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2329             ret = 0;
2330         else if (!hob)
2331             ret = s->lcyl;
2332 	else
2333 	    ret = s->hob_lcyl;
2334         break;
2335     case 5:
2336         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2337             ret = 0;
2338         else if (!hob)
2339             ret = s->hcyl;
2340 	else
2341 	    ret = s->hob_hcyl;
2342         break;
2343     case 6:
2344         if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2345             ret = 0;
2346         else
2347             ret = s->select;
2348         break;
2349     default:
2350     case 7:
2351         if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2352             (s != bus->ifs && !s->bs))
2353             ret = 0;
2354         else
2355             ret = s->status;
2356         qemu_irq_lower(bus->irq);
2357         break;
2358     }
2359 #ifdef DEBUG_IDE
2360     printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
2361 #endif
2362     return ret;
2363 }
2364 
2365 uint32_t ide_status_read(void *opaque, uint32_t addr)
2366 {
2367     IDEBus *bus = opaque;
2368     IDEState *s = idebus_active_if(bus);
2369     int ret;
2370 
2371     if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2372         (s != bus->ifs && !s->bs))
2373         ret = 0;
2374     else
2375         ret = s->status;
2376 #ifdef DEBUG_IDE
2377     printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
2378 #endif
2379     return ret;
2380 }
2381 
2382 void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
2383 {
2384     IDEBus *bus = opaque;
2385     IDEState *s;
2386     int i;
2387 
2388 #ifdef DEBUG_IDE
2389     printf("ide: write control addr=0x%x val=%02x\n", addr, val);
2390 #endif
2391     /* common for both drives */
2392     if (!(bus->cmd & IDE_CMD_RESET) &&
2393         (val & IDE_CMD_RESET)) {
2394         /* reset low to high */
2395         for(i = 0;i < 2; i++) {
2396             s = &bus->ifs[i];
2397             s->status = BUSY_STAT | SEEK_STAT;
2398             s->error = 0x01;
2399         }
2400     } else if ((bus->cmd & IDE_CMD_RESET) &&
2401                !(val & IDE_CMD_RESET)) {
2402         /* high to low */
2403         for(i = 0;i < 2; i++) {
2404             s = &bus->ifs[i];
2405             if (s->is_cdrom)
2406                 s->status = 0x00; /* NOTE: READY is _not_ set */
2407             else
2408                 s->status = READY_STAT | SEEK_STAT;
2409             ide_set_signature(s);
2410         }
2411     }
2412 
2413     bus->cmd = val;
2414 }
2415 
2416 void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
2417 {
2418     IDEBus *bus = opaque;
2419     IDEState *s = idebus_active_if(bus);
2420     uint8_t *p;
2421 
2422     /* PIO data access allowed only when DRQ bit is set */
2423     if (!(s->status & DRQ_STAT))
2424         return;
2425 
2426     p = s->data_ptr;
2427     *(uint16_t *)p = le16_to_cpu(val);
2428     p += 2;
2429     s->data_ptr = p;
2430     if (p >= s->data_end)
2431         s->end_transfer_func(s);
2432 }
2433 
2434 uint32_t ide_data_readw(void *opaque, uint32_t addr)
2435 {
2436     IDEBus *bus = opaque;
2437     IDEState *s = idebus_active_if(bus);
2438     uint8_t *p;
2439     int ret;
2440 
2441     /* PIO data access allowed only when DRQ bit is set */
2442     if (!(s->status & DRQ_STAT))
2443         return 0;
2444 
2445     p = s->data_ptr;
2446     ret = cpu_to_le16(*(uint16_t *)p);
2447     p += 2;
2448     s->data_ptr = p;
2449     if (p >= s->data_end)
2450         s->end_transfer_func(s);
2451     return ret;
2452 }
2453 
2454 void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
2455 {
2456     IDEBus *bus = opaque;
2457     IDEState *s = idebus_active_if(bus);
2458     uint8_t *p;
2459 
2460     /* PIO data access allowed only when DRQ bit is set */
2461     if (!(s->status & DRQ_STAT))
2462         return;
2463 
2464     p = s->data_ptr;
2465     *(uint32_t *)p = le32_to_cpu(val);
2466     p += 4;
2467     s->data_ptr = p;
2468     if (p >= s->data_end)
2469         s->end_transfer_func(s);
2470 }
2471 
2472 uint32_t ide_data_readl(void *opaque, uint32_t addr)
2473 {
2474     IDEBus *bus = opaque;
2475     IDEState *s = idebus_active_if(bus);
2476     uint8_t *p;
2477     int ret;
2478 
2479     /* PIO data access allowed only when DRQ bit is set */
2480     if (!(s->status & DRQ_STAT))
2481         return 0;
2482 
2483     p = s->data_ptr;
2484     ret = cpu_to_le32(*(uint32_t *)p);
2485     p += 4;
2486     s->data_ptr = p;
2487     if (p >= s->data_end)
2488         s->end_transfer_func(s);
2489     return ret;
2490 }
2491 
2492 static void ide_dummy_transfer_stop(IDEState *s)
2493 {
2494     s->data_ptr = s->io_buffer;
2495     s->data_end = s->io_buffer;
2496     s->io_buffer[0] = 0xff;
2497     s->io_buffer[1] = 0xff;
2498     s->io_buffer[2] = 0xff;
2499     s->io_buffer[3] = 0xff;
2500 }
2501 
2502 void ide_reset(IDEState *s)
2503 {
2504     IDEBus *bus = s->bus;
2505 
2506     if (s->is_cf)
2507         s->mult_sectors = 0;
2508     else
2509         s->mult_sectors = MAX_MULT_SECTORS;
2510     bus->unit = s->unit;
2511     s->select = 0xa0;
2512     s->status = READY_STAT | SEEK_STAT;
2513     ide_set_signature(s);
2514     /* init the transfer handler so that 0xffff is returned on data
2515        accesses */
2516     s->end_transfer_func = ide_dummy_transfer_stop;
2517     ide_dummy_transfer_stop(s);
2518     s->media_changed = 0;
2519 }
2520 
2521 void ide_init_drive(IDEState *s, DriveInfo *dinfo)
2522 {
2523     int cylinders, heads, secs;
2524     uint64_t nb_sectors;
2525 
2526     if (dinfo && dinfo->bdrv) {
2527         s->bs = dinfo->bdrv;
2528         bdrv_get_geometry(s->bs, &nb_sectors);
2529         bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);
2530         s->cylinders = cylinders;
2531         s->heads = heads;
2532         s->sectors = secs;
2533         s->nb_sectors = nb_sectors;
2534         /* The SMART values should be preserved across power cycles
2535            but they aren't.  */
2536         s->smart_enabled = 1;
2537         s->smart_autosave = 1;
2538         s->smart_errors = 0;
2539         s->smart_selftest_count = 0;
2540         if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
2541             s->is_cdrom = 1;
2542             bdrv_set_change_cb(s->bs, cdrom_change_cb, s);
2543         }
2544         strncpy(s->drive_serial_str, drive_get_serial(s->bs),
2545                 sizeof(s->drive_serial_str));
2546     }
2547     if (strlen(s->drive_serial_str) == 0)
2548         snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
2549                  "QM%05d", s->drive_serial);
2550     ide_reset(s);
2551 }
2552 
2553 void ide_init2(IDEBus *bus, DriveInfo *hd0, DriveInfo *hd1,
2554                qemu_irq irq)
2555 {
2556     IDEState *s;
2557     static int drive_serial = 1;
2558     int i;
2559 
2560     for(i = 0; i < 2; i++) {
2561         s = bus->ifs + i;
2562         s->bus = bus;
2563         s->unit = i;
2564         s->drive_serial = drive_serial++;
2565         s->io_buffer = qemu_blockalign(s->bs, IDE_DMA_BUF_SECTORS*512 + 4);
2566         s->smart_selftest_data = qemu_blockalign(s->bs, 512);
2567         s->sector_write_timer = qemu_new_timer(vm_clock,
2568                                                ide_sector_write_timer_cb, s);
2569         if (i == 0)
2570             ide_init_drive(s, hd0);
2571         if (i == 1)
2572             ide_init_drive(s, hd1);
2573     }
2574     bus->irq = irq;
2575 }
2576 
2577 void ide_init_ioport(IDEBus *bus, int iobase, int iobase2)
2578 {
2579     register_ioport_write(iobase, 8, 1, ide_ioport_write, bus);
2580     register_ioport_read(iobase, 8, 1, ide_ioport_read, bus);
2581     if (iobase2) {
2582         register_ioport_read(iobase2, 1, 1, ide_status_read, bus);
2583         register_ioport_write(iobase2, 1, 1, ide_cmd_write, bus);
2584     }
2585 
2586     /* data ports */
2587     register_ioport_write(iobase, 2, 2, ide_data_writew, bus);
2588     register_ioport_read(iobase, 2, 2, ide_data_readw, bus);
2589     register_ioport_write(iobase, 4, 4, ide_data_writel, bus);
2590     register_ioport_read(iobase, 4, 4, ide_data_readl, bus);
2591 }
2592 
2593 /* save per IDE drive data */
2594 void ide_save(QEMUFile* f, IDEState *s)
2595 {
2596     qemu_put_be32(f, s->mult_sectors);
2597     qemu_put_be32(f, s->identify_set);
2598     if (s->identify_set) {
2599         qemu_put_buffer(f, (const uint8_t *)s->identify_data, 512);
2600     }
2601     qemu_put_8s(f, &s->feature);
2602     qemu_put_8s(f, &s->error);
2603     qemu_put_be32s(f, &s->nsector);
2604     qemu_put_8s(f, &s->sector);
2605     qemu_put_8s(f, &s->lcyl);
2606     qemu_put_8s(f, &s->hcyl);
2607     qemu_put_8s(f, &s->hob_feature);
2608     qemu_put_8s(f, &s->hob_nsector);
2609     qemu_put_8s(f, &s->hob_sector);
2610     qemu_put_8s(f, &s->hob_lcyl);
2611     qemu_put_8s(f, &s->hob_hcyl);
2612     qemu_put_8s(f, &s->select);
2613     qemu_put_8s(f, &s->status);
2614     qemu_put_8s(f, &s->lba48);
2615 
2616     qemu_put_8s(f, &s->sense_key);
2617     qemu_put_8s(f, &s->asc);
2618     qemu_put_8s(f, &s->cdrom_changed);
2619     /* XXX: if a transfer is pending, we do not save it yet */
2620 }
2621 
2622 /* load per IDE drive data */
2623 void ide_load(QEMUFile* f, IDEState *s, int version_id)
2624 {
2625     s->mult_sectors=qemu_get_be32(f);
2626     s->identify_set=qemu_get_be32(f);
2627     if (s->identify_set) {
2628         qemu_get_buffer(f, (uint8_t *)s->identify_data, 512);
2629     }
2630     qemu_get_8s(f, &s->feature);
2631     qemu_get_8s(f, &s->error);
2632     qemu_get_be32s(f, &s->nsector);
2633     qemu_get_8s(f, &s->sector);
2634     qemu_get_8s(f, &s->lcyl);
2635     qemu_get_8s(f, &s->hcyl);
2636     qemu_get_8s(f, &s->hob_feature);
2637     qemu_get_8s(f, &s->hob_nsector);
2638     qemu_get_8s(f, &s->hob_sector);
2639     qemu_get_8s(f, &s->hob_lcyl);
2640     qemu_get_8s(f, &s->hob_hcyl);
2641     qemu_get_8s(f, &s->select);
2642     qemu_get_8s(f, &s->status);
2643     qemu_get_8s(f, &s->lba48);
2644 
2645     qemu_get_8s(f, &s->sense_key);
2646     qemu_get_8s(f, &s->asc);
2647     if (version_id == 3) {
2648         qemu_get_8s(f, &s->cdrom_changed);
2649     } else {
2650         if (s->sense_key == SENSE_UNIT_ATTENTION &&
2651                        s->asc == ASC_MEDIUM_MAY_HAVE_CHANGED)
2652             s->cdrom_changed = 1;
2653     }
2654     /* XXX: if a transfer is pending, we do not save it yet */
2655 }
2656 
2657 void idebus_save(QEMUFile* f, IDEBus *bus)
2658 {
2659     qemu_put_8s(f, &bus->cmd);
2660     qemu_put_8s(f, &bus->unit);
2661 }
2662 
2663 void idebus_load(QEMUFile* f, IDEBus *bus, int version_id)
2664 {
2665     qemu_get_8s(f, &bus->cmd);
2666     qemu_get_8s(f, &bus->unit);
2667 }
2668 
2669 /***********************************************************/
2670 /* PCI IDE definitions */
2671 
2672 static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb)
2673 {
2674     BMDMAState *bm = s->bus->bmdma;
2675     if(!bm)
2676         return;
2677     bm->unit = s->unit;
2678     bm->dma_cb = dma_cb;
2679     bm->cur_prd_last = 0;
2680     bm->cur_prd_addr = 0;
2681     bm->cur_prd_len = 0;
2682     bm->sector_num = ide_get_sector(s);
2683     bm->nsector = s->nsector;
2684     if (bm->status & BM_STATUS_DMAING) {
2685         bm->dma_cb(bm, 0);
2686     }
2687 }
2688 
2689 static void ide_dma_restart(IDEState *s)
2690 {
2691     BMDMAState *bm = s->bus->bmdma;
2692     ide_set_sector(s, bm->sector_num);
2693     s->io_buffer_index = 0;
2694     s->io_buffer_size = 0;
2695     s->nsector = bm->nsector;
2696     bm->cur_addr = bm->addr;
2697     bm->dma_cb = ide_write_dma_cb;
2698     ide_dma_start(s, bm->dma_cb);
2699 }
2700 
2701 void ide_dma_cancel(BMDMAState *bm)
2702 {
2703     if (bm->status & BM_STATUS_DMAING) {
2704         bm->status &= ~BM_STATUS_DMAING;
2705         /* cancel DMA request */
2706         bm->unit = -1;
2707         bm->dma_cb = NULL;
2708         if (bm->aiocb) {
2709 #ifdef DEBUG_AIO
2710             printf("aio_cancel\n");
2711 #endif
2712             bdrv_aio_cancel(bm->aiocb);
2713             bm->aiocb = NULL;
2714         }
2715     }
2716 }
2717 
2718