Statistics
| Branch: | Revision:

root / hw / ide.c @ b8842209

History | View | Annotate | Download (100.7 kB)

1
/*
2
 * QEMU IDE disk and CD/DVD-ROM Emulator
3
 *
4
 * Copyright (c) 2003 Fabrice Bellard
5
 * Copyright (c) 2006 Openedhand Ltd.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 */
25
#include "hw.h"
26
#include "pc.h"
27
#include "pci.h"
28
#include "scsi-disk.h"
29
#include "pcmcia.h"
30
#include "block.h"
31
#include "block_int.h"
32
#include "qemu-timer.h"
33
#include "sysemu.h"
34
#include "sh.h"
35
#include "dma.h"
36
#include "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, 0=SMART feature set enabled */
152
    put_le16(p + 85, (1 << 14) | 1);
153
    /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
154
    put_le16(p + 86, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
155
    /* 14=set to 1, 1=smart self test, 0=smart error logging */
156
    put_le16(p + 87, (1 << 14) | 0);
157
    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
158
    put_le16(p + 93, 1 | (1 << 14) | 0x2000);
159
    put_le16(p + 100, s->nb_sectors);
160
    put_le16(p + 101, s->nb_sectors >> 16);
161
    put_le16(p + 102, s->nb_sectors >> 32);
162
    put_le16(p + 103, s->nb_sectors >> 48);
163

    
164
    memcpy(s->identify_data, p, sizeof(s->identify_data));
165
    s->identify_set = 1;
166
}
167

    
168
static void ide_atapi_identify(IDEState *s)
169
{
170
    uint16_t *p;
171

    
172
    if (s->identify_set) {
173
        memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
174
        return;
175
    }
176

    
177
    memset(s->io_buffer, 0, 512);
178
    p = (uint16_t *)s->io_buffer;
179
    /* Removable CDROM, 50us response, 12 byte packets */
180
    put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));
181
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
182
    put_le16(p + 20, 3); /* buffer type */
183
    put_le16(p + 21, 512); /* cache size in sectors */
184
    put_le16(p + 22, 4); /* ecc bytes */
185
    padstr((char *)(p + 23), QEMU_VERSION, 8); /* firmware version */
186
    padstr((char *)(p + 27), "QEMU DVD-ROM", 40); /* model */
187
    put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */
188
#ifdef USE_DMA_CDROM
189
    put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */
190
    put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */
191
    put_le16(p + 62, 7);  /* single word dma0-2 supported */
192
    put_le16(p + 63, 7);  /* mdma0-2 supported */
193
    put_le16(p + 64, 0x3f); /* PIO modes supported */
194
#else
195
    put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */
196
    put_le16(p + 53, 3); /* words 64-70, 54-58 valid */
197
    put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */
198
    put_le16(p + 64, 1); /* PIO modes */
199
#endif
200
    put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */
201
    put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */
202
    put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */
203
    put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */
204

    
205
    put_le16(p + 71, 30); /* in ns */
206
    put_le16(p + 72, 30); /* in ns */
207

    
208
    put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
209
#ifdef USE_DMA_CDROM
210
    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
211
#endif
212
    memcpy(s->identify_data, p, sizeof(s->identify_data));
213
    s->identify_set = 1;
214
}
215

    
216
static void ide_cfata_identify(IDEState *s)
217
{
218
    uint16_t *p;
219
    uint32_t cur_sec;
220

    
221
    p = (uint16_t *) s->identify_data;
222
    if (s->identify_set)
223
        goto fill_buffer;
224

    
225
    memset(p, 0, sizeof(s->identify_data));
226

    
227
    cur_sec = s->cylinders * s->heads * s->sectors;
228

    
229
    put_le16(p + 0, 0x848a);                        /* CF Storage Card signature */
230
    put_le16(p + 1, s->cylinders);                /* Default cylinders */
231
    put_le16(p + 3, s->heads);                        /* Default heads */
232
    put_le16(p + 6, s->sectors);                /* Default sectors per track */
233
    put_le16(p + 7, s->nb_sectors >> 16);        /* Sectors per card */
234
    put_le16(p + 8, s->nb_sectors);                /* Sectors per card */
235
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
236
    put_le16(p + 22, 0x0004);                        /* ECC bytes */
237
    padstr((char *) (p + 23), QEMU_VERSION, 8);        /* Firmware Revision */
238
    padstr((char *) (p + 27), "QEMU MICRODRIVE", 40);/* Model number */
239
#if MAX_MULT_SECTORS > 1
240
    put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
241
#else
242
    put_le16(p + 47, 0x0000);
243
#endif
244
    put_le16(p + 49, 0x0f00);                        /* Capabilities */
245
    put_le16(p + 51, 0x0002);                        /* PIO cycle timing mode */
246
    put_le16(p + 52, 0x0001);                        /* DMA cycle timing mode */
247
    put_le16(p + 53, 0x0003);                        /* Translation params valid */
248
    put_le16(p + 54, s->cylinders);                /* Current cylinders */
249
    put_le16(p + 55, s->heads);                        /* Current heads */
250
    put_le16(p + 56, s->sectors);                /* Current sectors */
251
    put_le16(p + 57, cur_sec);                        /* Current capacity */
252
    put_le16(p + 58, cur_sec >> 16);                /* Current capacity */
253
    if (s->mult_sectors)                        /* Multiple sector setting */
254
        put_le16(p + 59, 0x100 | s->mult_sectors);
255
    put_le16(p + 60, s->nb_sectors);                /* Total LBA sectors */
256
    put_le16(p + 61, s->nb_sectors >> 16);        /* Total LBA sectors */
257
    put_le16(p + 63, 0x0203);                        /* Multiword DMA capability */
258
    put_le16(p + 64, 0x0001);                        /* Flow Control PIO support */
259
    put_le16(p + 65, 0x0096);                        /* Min. Multiword DMA cycle */
260
    put_le16(p + 66, 0x0096);                        /* Rec. Multiword DMA cycle */
261
    put_le16(p + 68, 0x00b4);                        /* Min. PIO cycle time */
262
    put_le16(p + 82, 0x400c);                        /* Command Set supported */
263
    put_le16(p + 83, 0x7068);                        /* Command Set supported */
264
    put_le16(p + 84, 0x4000);                        /* Features supported */
265
    put_le16(p + 85, 0x000c);                        /* Command Set enabled */
266
    put_le16(p + 86, 0x7044);                        /* Command Set enabled */
267
    put_le16(p + 87, 0x4000);                        /* Features enabled */
268
    put_le16(p + 91, 0x4060);                        /* Current APM level */
269
    put_le16(p + 129, 0x0002);                        /* Current features option */
270
    put_le16(p + 130, 0x0005);                        /* Reassigned sectors */
271
    put_le16(p + 131, 0x0001);                        /* Initial power mode */
272
    put_le16(p + 132, 0x0000);                        /* User signature */
273
    put_le16(p + 160, 0x8100);                        /* Power requirement */
274
    put_le16(p + 161, 0x8001);                        /* CF command set */
275

    
276
    s->identify_set = 1;
277

    
278
fill_buffer:
279
    memcpy(s->io_buffer, p, sizeof(s->identify_data));
280
}
281

    
282
static void ide_set_signature(IDEState *s)
283
{
284
    s->select &= 0xf0; /* clear head */
285
    /* put signature */
286
    s->nsector = 1;
287
    s->sector = 1;
288
    if (s->is_cdrom) {
289
        s->lcyl = 0x14;
290
        s->hcyl = 0xeb;
291
    } else if (s->bs) {
292
        s->lcyl = 0;
293
        s->hcyl = 0;
294
    } else {
295
        s->lcyl = 0xff;
296
        s->hcyl = 0xff;
297
    }
298
}
299

    
300
static inline void ide_abort_command(IDEState *s)
301
{
302
    s->status = READY_STAT | ERR_STAT;
303
    s->error = ABRT_ERR;
304
}
305

    
306
static inline void ide_dma_submit_check(IDEState *s,
307
          BlockDriverCompletionFunc *dma_cb, BMDMAState *bm)
308
{
309
    if (bm->aiocb)
310
        return;
311
    dma_cb(bm, -1);
312
}
313

    
314
/* prepare data transfer and tell what to do after */
315
static void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
316
                               EndTransferFunc *end_transfer_func)
317
{
318
    s->end_transfer_func = end_transfer_func;
319
    s->data_ptr = buf;
320
    s->data_end = buf + size;
321
    if (!(s->status & ERR_STAT))
322
        s->status |= DRQ_STAT;
323
}
324

    
325
static void ide_transfer_stop(IDEState *s)
326
{
327
    s->end_transfer_func = ide_transfer_stop;
328
    s->data_ptr = s->io_buffer;
329
    s->data_end = s->io_buffer;
330
    s->status &= ~DRQ_STAT;
331
}
332

    
333
int64_t ide_get_sector(IDEState *s)
334
{
335
    int64_t sector_num;
336
    if (s->select & 0x40) {
337
        /* lba */
338
        if (!s->lba48) {
339
            sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
340
                (s->lcyl << 8) | s->sector;
341
        } else {
342
            sector_num = ((int64_t)s->hob_hcyl << 40) |
343
                ((int64_t) s->hob_lcyl << 32) |
344
                ((int64_t) s->hob_sector << 24) |
345
                ((int64_t) s->hcyl << 16) |
346
                ((int64_t) s->lcyl << 8) | s->sector;
347
        }
348
    } else {
349
        sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
350
            (s->select & 0x0f) * s->sectors + (s->sector - 1);
351
    }
352
    return sector_num;
353
}
354

    
355
void ide_set_sector(IDEState *s, int64_t sector_num)
356
{
357
    unsigned int cyl, r;
358
    if (s->select & 0x40) {
359
        if (!s->lba48) {
360
            s->select = (s->select & 0xf0) | (sector_num >> 24);
361
            s->hcyl = (sector_num >> 16);
362
            s->lcyl = (sector_num >> 8);
363
            s->sector = (sector_num);
364
        } else {
365
            s->sector = sector_num;
366
            s->lcyl = sector_num >> 8;
367
            s->hcyl = sector_num >> 16;
368
            s->hob_sector = sector_num >> 24;
369
            s->hob_lcyl = sector_num >> 32;
370
            s->hob_hcyl = sector_num >> 40;
371
        }
372
    } else {
373
        cyl = sector_num / (s->heads * s->sectors);
374
        r = sector_num % (s->heads * s->sectors);
375
        s->hcyl = cyl >> 8;
376
        s->lcyl = cyl;
377
        s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);
378
        s->sector = (r % s->sectors) + 1;
379
    }
380
}
381

    
382
static void ide_rw_error(IDEState *s) {
383
    ide_abort_command(s);
384
    ide_set_irq(s);
385
}
386

    
387
static void ide_sector_read(IDEState *s)
388
{
389
    int64_t sector_num;
390
    int ret, n;
391

    
392
    s->status = READY_STAT | SEEK_STAT;
393
    s->error = 0; /* not needed by IDE spec, but needed by Windows */
394
    sector_num = ide_get_sector(s);
395
    n = s->nsector;
396
    if (n == 0) {
397
        /* no more sector to read from disk */
398
        ide_transfer_stop(s);
399
    } else {
400
#if defined(DEBUG_IDE)
401
        printf("read sector=%" PRId64 "\n", sector_num);
402
#endif
403
        if (n > s->req_nb_sectors)
404
            n = s->req_nb_sectors;
405
        ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
406
        if (ret != 0) {
407
            ide_rw_error(s);
408
            return;
409
        }
410
        ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);
411
        ide_set_irq(s);
412
        ide_set_sector(s, sector_num + n);
413
        s->nsector -= n;
414
    }
415
}
416

    
417

    
418
/* return 0 if buffer completed */
419
static int dma_buf_prepare(BMDMAState *bm, int is_write)
420
{
421
    IDEState *s = bmdma_active_if(bm);
422
    struct {
423
        uint32_t addr;
424
        uint32_t size;
425
    } prd;
426
    int l, len;
427

    
428
    qemu_sglist_init(&s->sg, s->nsector / (TARGET_PAGE_SIZE/512) + 1);
429
    s->io_buffer_size = 0;
430
    for(;;) {
431
        if (bm->cur_prd_len == 0) {
432
            /* end of table (with a fail safe of one page) */
433
            if (bm->cur_prd_last ||
434
                (bm->cur_addr - bm->addr) >= 4096)
435
                return s->io_buffer_size != 0;
436
            cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
437
            bm->cur_addr += 8;
438
            prd.addr = le32_to_cpu(prd.addr);
439
            prd.size = le32_to_cpu(prd.size);
440
            len = prd.size & 0xfffe;
441
            if (len == 0)
442
                len = 0x10000;
443
            bm->cur_prd_len = len;
444
            bm->cur_prd_addr = prd.addr;
445
            bm->cur_prd_last = (prd.size & 0x80000000);
446
        }
447
        l = bm->cur_prd_len;
448
        if (l > 0) {
449
            qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);
450
            bm->cur_prd_addr += l;
451
            bm->cur_prd_len -= l;
452
            s->io_buffer_size += l;
453
        }
454
    }
455
    return 1;
456
}
457

    
458
static void dma_buf_commit(IDEState *s, int is_write)
459
{
460
    qemu_sglist_destroy(&s->sg);
461
}
462

    
463
void ide_dma_error(IDEState *s)
464
{
465
    ide_transfer_stop(s);
466
    s->error = ABRT_ERR;
467
    s->status = READY_STAT | ERR_STAT;
468
    ide_set_irq(s);
469
}
470

    
471
static int ide_handle_write_error(IDEState *s, int error, int op)
472
{
473
    BlockInterfaceErrorAction action = drive_get_onerror(s->bs);
474

    
475
    if (action == BLOCK_ERR_IGNORE)
476
        return 0;
477

    
478
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
479
            || action == BLOCK_ERR_STOP_ANY) {
480
        s->bus->bmdma->unit = s->unit;
481
        s->bus->bmdma->status |= op;
482
        vm_stop(0);
483
    } else {
484
        if (op == BM_STATUS_DMA_RETRY) {
485
            dma_buf_commit(s, 0);
486
            ide_dma_error(s);
487
        } else {
488
            ide_rw_error(s);
489
        }
490
    }
491

    
492
    return 1;
493
}
494

    
495
/* return 0 if buffer completed */
496
static int dma_buf_rw(BMDMAState *bm, int is_write)
497
{
498
    IDEState *s = bmdma_active_if(bm);
499
    struct {
500
        uint32_t addr;
501
        uint32_t size;
502
    } prd;
503
    int l, len;
504

    
505
    for(;;) {
506
        l = s->io_buffer_size - s->io_buffer_index;
507
        if (l <= 0)
508
            break;
509
        if (bm->cur_prd_len == 0) {
510
            /* end of table (with a fail safe of one page) */
511
            if (bm->cur_prd_last ||
512
                (bm->cur_addr - bm->addr) >= 4096)
513
                return 0;
514
            cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);
515
            bm->cur_addr += 8;
516
            prd.addr = le32_to_cpu(prd.addr);
517
            prd.size = le32_to_cpu(prd.size);
518
            len = prd.size & 0xfffe;
519
            if (len == 0)
520
                len = 0x10000;
521
            bm->cur_prd_len = len;
522
            bm->cur_prd_addr = prd.addr;
523
            bm->cur_prd_last = (prd.size & 0x80000000);
524
        }
525
        if (l > bm->cur_prd_len)
526
            l = bm->cur_prd_len;
527
        if (l > 0) {
528
            if (is_write) {
529
                cpu_physical_memory_write(bm->cur_prd_addr,
530
                                          s->io_buffer + s->io_buffer_index, l);
531
            } else {
532
                cpu_physical_memory_read(bm->cur_prd_addr,
533
                                          s->io_buffer + s->io_buffer_index, l);
534
            }
535
            bm->cur_prd_addr += l;
536
            bm->cur_prd_len -= l;
537
            s->io_buffer_index += l;
538
        }
539
    }
540
    return 1;
541
}
542

    
543
static void ide_read_dma_cb(void *opaque, int ret)
544
{
545
    BMDMAState *bm = opaque;
546
    IDEState *s = bmdma_active_if(bm);
547
    int n;
548
    int64_t sector_num;
549

    
550
    if (ret < 0) {
551
        dma_buf_commit(s, 1);
552
        ide_dma_error(s);
553
        return;
554
    }
555

    
556
    n = s->io_buffer_size >> 9;
557
    sector_num = ide_get_sector(s);
558
    if (n > 0) {
559
        dma_buf_commit(s, 1);
560
        sector_num += n;
561
        ide_set_sector(s, sector_num);
562
        s->nsector -= n;
563
    }
564

    
565
    /* end of transfer ? */
566
    if (s->nsector == 0) {
567
        s->status = READY_STAT | SEEK_STAT;
568
        ide_set_irq(s);
569
    eot:
570
        bm->status &= ~BM_STATUS_DMAING;
571
        bm->status |= BM_STATUS_INT;
572
        bm->dma_cb = NULL;
573
        bm->unit = -1;
574
        bm->aiocb = NULL;
575
        return;
576
    }
577

    
578
    /* launch next transfer */
579
    n = s->nsector;
580
    s->io_buffer_index = 0;
581
    s->io_buffer_size = n * 512;
582
    if (dma_buf_prepare(bm, 1) == 0)
583
        goto eot;
584
#ifdef DEBUG_AIO
585
    printf("aio_read: sector_num=%" PRId64 " n=%d\n", sector_num, n);
586
#endif
587
    bm->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num, ide_read_dma_cb, bm);
588
    ide_dma_submit_check(s, ide_read_dma_cb, bm);
589
}
590

    
591
static void ide_sector_read_dma(IDEState *s)
592
{
593
    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
594
    s->io_buffer_index = 0;
595
    s->io_buffer_size = 0;
596
    s->is_read = 1;
597
    ide_dma_start(s, ide_read_dma_cb);
598
}
599

    
600
static void ide_sector_write_timer_cb(void *opaque)
601
{
602
    IDEState *s = opaque;
603
    ide_set_irq(s);
604
}
605

    
606
static void ide_sector_write(IDEState *s)
607
{
608
    int64_t sector_num;
609
    int ret, n, n1;
610

    
611
    s->status = READY_STAT | SEEK_STAT;
612
    sector_num = ide_get_sector(s);
613
#if defined(DEBUG_IDE)
614
    printf("write sector=%" PRId64 "\n", sector_num);
615
#endif
616
    n = s->nsector;
617
    if (n > s->req_nb_sectors)
618
        n = s->req_nb_sectors;
619
    ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
620

    
621
    if (ret != 0) {
622
        if (ide_handle_write_error(s, -ret, BM_STATUS_PIO_RETRY))
623
            return;
624
    }
625

    
626
    s->nsector -= n;
627
    if (s->nsector == 0) {
628
        /* no more sectors to write */
629
        ide_transfer_stop(s);
630
    } else {
631
        n1 = s->nsector;
632
        if (n1 > s->req_nb_sectors)
633
            n1 = s->req_nb_sectors;
634
        ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write);
635
    }
636
    ide_set_sector(s, sector_num + n);
637

    
638
#ifdef TARGET_I386
639
    if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {
640
        /* It seems there is a bug in the Windows 2000 installer HDD
641
           IDE driver which fills the disk with empty logs when the
642
           IDE write IRQ comes too early. This hack tries to correct
643
           that at the expense of slower write performances. Use this
644
           option _only_ to install Windows 2000. You must disable it
645
           for normal use. */
646
        qemu_mod_timer(s->sector_write_timer, 
647
                       qemu_get_clock(vm_clock) + (ticks_per_sec / 1000));
648
    } else 
649
#endif
650
    {
651
        ide_set_irq(s);
652
    }
653
}
654

    
655
static void ide_dma_restart_bh(void *opaque)
656
{
657
    BMDMAState *bm = opaque;
658

    
659
    qemu_bh_delete(bm->bh);
660
    bm->bh = NULL;
661

    
662
    if (bm->status & BM_STATUS_DMA_RETRY) {
663
        bm->status &= ~BM_STATUS_DMA_RETRY;
664
        ide_dma_restart(bmdma_active_if(bm));
665
    } else if (bm->status & BM_STATUS_PIO_RETRY) {
666
        bm->status &= ~BM_STATUS_PIO_RETRY;
667
        ide_sector_write(bmdma_active_if(bm));
668
    }
669
}
670

    
671
void ide_dma_restart_cb(void *opaque, int running, int reason)
672
{
673
    BMDMAState *bm = opaque;
674

    
675
    if (!running)
676
        return;
677

    
678
    if (!bm->bh) {
679
        bm->bh = qemu_bh_new(ide_dma_restart_bh, bm);
680
        qemu_bh_schedule(bm->bh);
681
    }
682
}
683

    
684
static void ide_write_dma_cb(void *opaque, int ret)
685
{
686
    BMDMAState *bm = opaque;
687
    IDEState *s = bmdma_active_if(bm);
688
    int n;
689
    int64_t sector_num;
690

    
691
    if (ret < 0) {
692
        if (ide_handle_write_error(s, -ret,  BM_STATUS_DMA_RETRY))
693
            return;
694
    }
695

    
696
    n = s->io_buffer_size >> 9;
697
    sector_num = ide_get_sector(s);
698
    if (n > 0) {
699
        dma_buf_commit(s, 0);
700
        sector_num += n;
701
        ide_set_sector(s, sector_num);
702
        s->nsector -= n;
703
    }
704

    
705
    /* end of transfer ? */
706
    if (s->nsector == 0) {
707
        s->status = READY_STAT | SEEK_STAT;
708
        ide_set_irq(s);
709
    eot:
710
        bm->status &= ~BM_STATUS_DMAING;
711
        bm->status |= BM_STATUS_INT;
712
        bm->dma_cb = NULL;
713
        bm->unit = -1;
714
        bm->aiocb = NULL;
715
        return;
716
    }
717

    
718
    n = s->nsector;
719
    s->io_buffer_size = n * 512;
720
    /* launch next transfer */
721
    if (dma_buf_prepare(bm, 0) == 0)
722
        goto eot;
723
#ifdef DEBUG_AIO
724
    printf("aio_write: sector_num=%" PRId64 " n=%d\n", sector_num, n);
725
#endif
726
    bm->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num, ide_write_dma_cb, bm);
727
    ide_dma_submit_check(s, ide_write_dma_cb, bm);
728
}
729

    
730
static void ide_sector_write_dma(IDEState *s)
731
{
732
    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
733
    s->io_buffer_index = 0;
734
    s->io_buffer_size = 0;
735
    s->is_read = 0;
736
    ide_dma_start(s, ide_write_dma_cb);
737
}
738

    
739
void ide_atapi_cmd_ok(IDEState *s)
740
{
741
    s->error = 0;
742
    s->status = READY_STAT | SEEK_STAT;
743
    s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
744
    ide_set_irq(s);
745
}
746

    
747
void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
748
{
749
#ifdef DEBUG_IDE_ATAPI
750
    printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc);
751
#endif
752
    s->error = sense_key << 4;
753
    s->status = READY_STAT | ERR_STAT;
754
    s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
755
    s->sense_key = sense_key;
756
    s->asc = asc;
757
    ide_set_irq(s);
758
}
759

    
760
static void ide_atapi_cmd_check_status(IDEState *s)
761
{
762
#ifdef DEBUG_IDE_ATAPI
763
    printf("atapi_cmd_check_status\n");
764
#endif
765
    s->error = MC_ERR | (SENSE_UNIT_ATTENTION << 4);
766
    s->status = ERR_STAT;
767
    s->nsector = 0;
768
    ide_set_irq(s);
769
}
770

    
771
static inline void cpu_to_ube16(uint8_t *buf, int val)
772
{
773
    buf[0] = val >> 8;
774
    buf[1] = val & 0xff;
775
}
776

    
777
static inline void cpu_to_ube32(uint8_t *buf, unsigned int val)
778
{
779
    buf[0] = val >> 24;
780
    buf[1] = val >> 16;
781
    buf[2] = val >> 8;
782
    buf[3] = val & 0xff;
783
}
784

    
785
static inline int ube16_to_cpu(const uint8_t *buf)
786
{
787
    return (buf[0] << 8) | buf[1];
788
}
789

    
790
static inline int ube32_to_cpu(const uint8_t *buf)
791
{
792
    return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
793
}
794

    
795
static void lba_to_msf(uint8_t *buf, int lba)
796
{
797
    lba += 150;
798
    buf[0] = (lba / 75) / 60;
799
    buf[1] = (lba / 75) % 60;
800
    buf[2] = lba % 75;
801
}
802

    
803
static void cd_data_to_raw(uint8_t *buf, int lba)
804
{
805
    /* sync bytes */
806
    buf[0] = 0x00;
807
    memset(buf + 1, 0xff, 10);
808
    buf[11] = 0x00;
809
    buf += 12;
810
    /* MSF */
811
    lba_to_msf(buf, lba);
812
    buf[3] = 0x01; /* mode 1 data */
813
    buf += 4;
814
    /* data */
815
    buf += 2048;
816
    /* XXX: ECC not computed */
817
    memset(buf, 0, 288);
818
}
819

    
820
static int cd_read_sector(BlockDriverState *bs, int lba, uint8_t *buf,
821
                           int sector_size)
822
{
823
    int ret;
824

    
825
    switch(sector_size) {
826
    case 2048:
827
        ret = bdrv_read(bs, (int64_t)lba << 2, buf, 4);
828
        break;
829
    case 2352:
830
        ret = bdrv_read(bs, (int64_t)lba << 2, buf + 16, 4);
831
        if (ret < 0)
832
            return ret;
833
        cd_data_to_raw(buf, lba);
834
        break;
835
    default:
836
        ret = -EIO;
837
        break;
838
    }
839
    return ret;
840
}
841

    
842
void ide_atapi_io_error(IDEState *s, int ret)
843
{
844
    /* XXX: handle more errors */
845
    if (ret == -ENOMEDIUM) {
846
        ide_atapi_cmd_error(s, SENSE_NOT_READY,
847
                            ASC_MEDIUM_NOT_PRESENT);
848
    } else {
849
        ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
850
                            ASC_LOGICAL_BLOCK_OOR);
851
    }
852
}
853

    
854
/* The whole ATAPI transfer logic is handled in this function */
855
static void ide_atapi_cmd_reply_end(IDEState *s)
856
{
857
    int byte_count_limit, size, ret;
858
#ifdef DEBUG_IDE_ATAPI
859
    printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",
860
           s->packet_transfer_size,
861
           s->elementary_transfer_size,
862
           s->io_buffer_index);
863
#endif
864
    if (s->packet_transfer_size <= 0) {
865
        /* end of transfer */
866
        ide_transfer_stop(s);
867
        s->status = READY_STAT | SEEK_STAT;
868
        s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
869
        ide_set_irq(s);
870
#ifdef DEBUG_IDE_ATAPI
871
        printf("status=0x%x\n", s->status);
872
#endif
873
    } else {
874
        /* see if a new sector must be read */
875
        if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {
876
            ret = cd_read_sector(s->bs, s->lba, s->io_buffer, s->cd_sector_size);
877
            if (ret < 0) {
878
                ide_transfer_stop(s);
879
                ide_atapi_io_error(s, ret);
880
                return;
881
            }
882
            s->lba++;
883
            s->io_buffer_index = 0;
884
        }
885
        if (s->elementary_transfer_size > 0) {
886
            /* there are some data left to transmit in this elementary
887
               transfer */
888
            size = s->cd_sector_size - s->io_buffer_index;
889
            if (size > s->elementary_transfer_size)
890
                size = s->elementary_transfer_size;
891
            ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
892
                               size, ide_atapi_cmd_reply_end);
893
            s->packet_transfer_size -= size;
894
            s->elementary_transfer_size -= size;
895
            s->io_buffer_index += size;
896
        } else {
897
            /* a new transfer is needed */
898
            s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
899
            byte_count_limit = s->lcyl | (s->hcyl << 8);
900
#ifdef DEBUG_IDE_ATAPI
901
            printf("byte_count_limit=%d\n", byte_count_limit);
902
#endif
903
            if (byte_count_limit == 0xffff)
904
                byte_count_limit--;
905
            size = s->packet_transfer_size;
906
            if (size > byte_count_limit) {
907
                /* byte count limit must be even if this case */
908
                if (byte_count_limit & 1)
909
                    byte_count_limit--;
910
                size = byte_count_limit;
911
            }
912
            s->lcyl = size;
913
            s->hcyl = size >> 8;
914
            s->elementary_transfer_size = size;
915
            /* we cannot transmit more than one sector at a time */
916
            if (s->lba != -1) {
917
                if (size > (s->cd_sector_size - s->io_buffer_index))
918
                    size = (s->cd_sector_size - s->io_buffer_index);
919
            }
920
            ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
921
                               size, ide_atapi_cmd_reply_end);
922
            s->packet_transfer_size -= size;
923
            s->elementary_transfer_size -= size;
924
            s->io_buffer_index += size;
925
            ide_set_irq(s);
926
#ifdef DEBUG_IDE_ATAPI
927
            printf("status=0x%x\n", s->status);
928
#endif
929
        }
930
    }
931
}
932

    
933
/* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
934
static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
935
{
936
    if (size > max_size)
937
        size = max_size;
938
    s->lba = -1; /* no sector read */
939
    s->packet_transfer_size = size;
940
    s->io_buffer_size = size;    /* dma: send the reply data as one chunk */
941
    s->elementary_transfer_size = 0;
942
    s->io_buffer_index = 0;
943

    
944
    if (s->atapi_dma) {
945
            s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
946
        ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
947
    } else {
948
            s->status = READY_STAT | SEEK_STAT;
949
            ide_atapi_cmd_reply_end(s);
950
    }
951
}
952

    
953
/* start a CD-CDROM read command */
954
static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,
955
                                   int sector_size)
956
{
957
    s->lba = lba;
958
    s->packet_transfer_size = nb_sectors * sector_size;
959
    s->elementary_transfer_size = 0;
960
    s->io_buffer_index = sector_size;
961
    s->cd_sector_size = sector_size;
962

    
963
    s->status = READY_STAT | SEEK_STAT;
964
    ide_atapi_cmd_reply_end(s);
965
}
966

    
967
/* ATAPI DMA support */
968

    
969
/* XXX: handle read errors */
970
static void ide_atapi_cmd_read_dma_cb(void *opaque, int ret)
971
{
972
    BMDMAState *bm = opaque;
973
    IDEState *s = bmdma_active_if(bm);
974
    int data_offset, n;
975

    
976
    if (ret < 0) {
977
        ide_atapi_io_error(s, ret);
978
        goto eot;
979
    }
980

    
981
    if (s->io_buffer_size > 0) {
982
        /*
983
         * For a cdrom read sector command (s->lba != -1),
984
         * adjust the lba for the next s->io_buffer_size chunk
985
         * and dma the current chunk.
986
         * For a command != read (s->lba == -1), just transfer
987
         * the reply data.
988
         */
989
        if (s->lba != -1) {
990
            if (s->cd_sector_size == 2352) {
991
                n = 1;
992
                cd_data_to_raw(s->io_buffer, s->lba);
993
            } else {
994
                n = s->io_buffer_size >> 11;
995
            }
996
            s->lba += n;
997
        }
998
        s->packet_transfer_size -= s->io_buffer_size;
999
        if (dma_buf_rw(bm, 1) == 0)
1000
            goto eot;
1001
    }
1002

    
1003
    if (s->packet_transfer_size <= 0) {
1004
        s->status = READY_STAT | SEEK_STAT;
1005
        s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
1006
        ide_set_irq(s);
1007
    eot:
1008
        bm->status &= ~BM_STATUS_DMAING;
1009
        bm->status |= BM_STATUS_INT;
1010
        bm->dma_cb = NULL;
1011
        bm->unit = -1;
1012
        bm->aiocb = NULL;
1013
        return;
1014
    }
1015

    
1016
    s->io_buffer_index = 0;
1017
    if (s->cd_sector_size == 2352) {
1018
        n = 1;
1019
        s->io_buffer_size = s->cd_sector_size;
1020
        data_offset = 16;
1021
    } else {
1022
        n = s->packet_transfer_size >> 11;
1023
        if (n > (IDE_DMA_BUF_SECTORS / 4))
1024
            n = (IDE_DMA_BUF_SECTORS / 4);
1025
        s->io_buffer_size = n * 2048;
1026
        data_offset = 0;
1027
    }
1028
#ifdef DEBUG_AIO
1029
    printf("aio_read_cd: lba=%u n=%d\n", s->lba, n);
1030
#endif
1031
    bm->iov.iov_base = (void *)(s->io_buffer + data_offset);
1032
    bm->iov.iov_len = n * 4 * 512;
1033
    qemu_iovec_init_external(&bm->qiov, &bm->iov, 1);
1034
    bm->aiocb = bdrv_aio_readv(s->bs, (int64_t)s->lba << 2, &bm->qiov,
1035
                               n * 4, ide_atapi_cmd_read_dma_cb, bm);
1036
    if (!bm->aiocb) {
1037
        /* Note: media not present is the most likely case */
1038
        ide_atapi_cmd_error(s, SENSE_NOT_READY,
1039
                            ASC_MEDIUM_NOT_PRESENT);
1040
        goto eot;
1041
    }
1042
}
1043

    
1044
/* start a CD-CDROM read command with DMA */
1045
/* XXX: test if DMA is available */
1046
static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
1047
                                   int sector_size)
1048
{
1049
    s->lba = lba;
1050
    s->packet_transfer_size = nb_sectors * sector_size;
1051
    s->io_buffer_index = 0;
1052
    s->io_buffer_size = 0;
1053
    s->cd_sector_size = sector_size;
1054

    
1055
    /* XXX: check if BUSY_STAT should be set */
1056
    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
1057
    ide_dma_start(s, ide_atapi_cmd_read_dma_cb);
1058
}
1059

    
1060
static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors,
1061
                               int sector_size)
1062
{
1063
#ifdef DEBUG_IDE_ATAPI
1064
    printf("read %s: LBA=%d nb_sectors=%d\n", s->atapi_dma ? "dma" : "pio",
1065
        lba, nb_sectors);
1066
#endif
1067
    if (s->atapi_dma) {
1068
        ide_atapi_cmd_read_dma(s, lba, nb_sectors, sector_size);
1069
    } else {
1070
        ide_atapi_cmd_read_pio(s, lba, nb_sectors, sector_size);
1071
    }
1072
}
1073

    
1074
static inline uint8_t ide_atapi_set_profile(uint8_t *buf, uint8_t *index,
1075
                                            uint16_t profile)
1076
{
1077
    uint8_t *buf_profile = buf + 12; /* start of profiles */
1078

    
1079
    buf_profile += ((*index) * 4); /* start of indexed profile */
1080
    cpu_to_ube16 (buf_profile, profile);
1081
    buf_profile[2] = ((buf_profile[0] == buf[6]) && (buf_profile[1] == buf[7]));
1082

    
1083
    /* each profile adds 4 bytes to the response */
1084
    (*index)++;
1085
    buf[11] += 4; /* Additional Length */
1086

    
1087
    return 4;
1088
}
1089

    
1090
static int ide_dvd_read_structure(IDEState *s, int format,
1091
                                  const uint8_t *packet, uint8_t *buf)
1092
{
1093
    switch (format) {
1094
        case 0x0: /* Physical format information */
1095
            {
1096
                int layer = packet[6];
1097
                uint64_t total_sectors;
1098

    
1099
                if (layer != 0)
1100
                    return -ASC_INV_FIELD_IN_CMD_PACKET;
1101

    
1102
                bdrv_get_geometry(s->bs, &total_sectors);
1103
                total_sectors >>= 2;
1104
                if (total_sectors == 0)
1105
                    return -ASC_MEDIUM_NOT_PRESENT;
1106

    
1107
                buf[4] = 1;   /* DVD-ROM, part version 1 */
1108
                buf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
1109
                buf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
1110
                buf[7] = 0;   /* default densities */
1111

    
1112
                /* FIXME: 0x30000 per spec? */
1113
                cpu_to_ube32(buf + 8, 0); /* start sector */
1114
                cpu_to_ube32(buf + 12, total_sectors - 1); /* end sector */
1115
                cpu_to_ube32(buf + 16, total_sectors - 1); /* l0 end sector */
1116

    
1117
                /* Size of buffer, not including 2 byte size field */
1118
                cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1119

    
1120
                /* 2k data + 4 byte header */
1121
                return (2048 + 4);
1122
            }
1123

    
1124
        case 0x01: /* DVD copyright information */
1125
            buf[4] = 0; /* no copyright data */
1126
            buf[5] = 0; /* no region restrictions */
1127

    
1128
            /* Size of buffer, not including 2 byte size field */
1129
            cpu_to_be16wu((uint16_t *)buf, 4 + 2);
1130

    
1131
            /* 4 byte header + 4 byte data */
1132
            return (4 + 4);
1133

    
1134
        case 0x03: /* BCA information - invalid field for no BCA info */
1135
            return -ASC_INV_FIELD_IN_CMD_PACKET;
1136

    
1137
        case 0x04: /* DVD disc manufacturing information */
1138
            /* Size of buffer, not including 2 byte size field */
1139
            cpu_to_be16wu((uint16_t *)buf, 2048 + 2);
1140

    
1141
            /* 2k data + 4 byte header */
1142
            return (2048 + 4);
1143

    
1144
        case 0xff:
1145
            /*
1146
             * This lists all the command capabilities above.  Add new ones
1147
             * in order and update the length and buffer return values.
1148
             */
1149

    
1150
            buf[4] = 0x00; /* Physical format */
1151
            buf[5] = 0x40; /* Not writable, is readable */
1152
            cpu_to_be16wu((uint16_t *)(buf + 6), 2048 + 4);
1153

    
1154
            buf[8] = 0x01; /* Copyright info */
1155
            buf[9] = 0x40; /* Not writable, is readable */
1156
            cpu_to_be16wu((uint16_t *)(buf + 10), 4 + 4);
1157

    
1158
            buf[12] = 0x03; /* BCA info */
1159
            buf[13] = 0x40; /* Not writable, is readable */
1160
            cpu_to_be16wu((uint16_t *)(buf + 14), 188 + 4);
1161

    
1162
            buf[16] = 0x04; /* Manufacturing info */
1163
            buf[17] = 0x40; /* Not writable, is readable */
1164
            cpu_to_be16wu((uint16_t *)(buf + 18), 2048 + 4);
1165

    
1166
            /* Size of buffer, not including 2 byte size field */
1167
            cpu_to_be16wu((uint16_t *)buf, 16 + 2);
1168

    
1169
            /* data written + 4 byte header */
1170
            return (16 + 4);
1171

    
1172
        default: /* TODO: formats beyond DVD-ROM requires */
1173
            return -ASC_INV_FIELD_IN_CMD_PACKET;
1174
    }
1175
}
1176

    
1177
static void ide_atapi_cmd(IDEState *s)
1178
{
1179
    const uint8_t *packet;
1180
    uint8_t *buf;
1181
    int max_len;
1182

    
1183
    packet = s->io_buffer;
1184
    buf = s->io_buffer;
1185
#ifdef DEBUG_IDE_ATAPI
1186
    {
1187
        int i;
1188
        printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
1189
        for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
1190
            printf(" %02x", packet[i]);
1191
        }
1192
        printf("\n");
1193
    }
1194
#endif
1195
    /* If there's a UNIT_ATTENTION condition pending, only
1196
       REQUEST_SENSE and INQUIRY commands are allowed to complete. */
1197
    if (s->sense_key == SENSE_UNIT_ATTENTION &&
1198
        s->io_buffer[0] != GPCMD_REQUEST_SENSE &&
1199
        s->io_buffer[0] != GPCMD_INQUIRY) {
1200
        ide_atapi_cmd_check_status(s);
1201
        return;
1202
    }
1203
    switch(s->io_buffer[0]) {
1204
    case GPCMD_TEST_UNIT_READY:
1205
        if (bdrv_is_inserted(s->bs) && !s->cdrom_changed) {
1206
            ide_atapi_cmd_ok(s);
1207
        } else {
1208
            s->cdrom_changed = 0;
1209
            ide_atapi_cmd_error(s, SENSE_NOT_READY,
1210
                                ASC_MEDIUM_NOT_PRESENT);
1211
        }
1212
        break;
1213
    case GPCMD_MODE_SENSE_6:
1214
    case GPCMD_MODE_SENSE_10:
1215
        {
1216
            int action, code;
1217
            if (packet[0] == GPCMD_MODE_SENSE_10)
1218
                max_len = ube16_to_cpu(packet + 7);
1219
            else
1220
                max_len = packet[4];
1221
            action = packet[2] >> 6;
1222
            code = packet[2] & 0x3f;
1223
            switch(action) {
1224
            case 0: /* current values */
1225
                switch(code) {
1226
                case 0x01: /* error recovery */
1227
                    cpu_to_ube16(&buf[0], 16 + 6);
1228
                    buf[2] = 0x70;
1229
                    buf[3] = 0;
1230
                    buf[4] = 0;
1231
                    buf[5] = 0;
1232
                    buf[6] = 0;
1233
                    buf[7] = 0;
1234

    
1235
                    buf[8] = 0x01;
1236
                    buf[9] = 0x06;
1237
                    buf[10] = 0x00;
1238
                    buf[11] = 0x05;
1239
                    buf[12] = 0x00;
1240
                    buf[13] = 0x00;
1241
                    buf[14] = 0x00;
1242
                    buf[15] = 0x00;
1243
                    ide_atapi_cmd_reply(s, 16, max_len);
1244
                    break;
1245
                case 0x2a:
1246
                    cpu_to_ube16(&buf[0], 28 + 6);
1247
                    buf[2] = 0x70;
1248
                    buf[3] = 0;
1249
                    buf[4] = 0;
1250
                    buf[5] = 0;
1251
                    buf[6] = 0;
1252
                    buf[7] = 0;
1253

    
1254
                    buf[8] = 0x2a;
1255
                    buf[9] = 0x12;
1256
                    buf[10] = 0x00;
1257
                    buf[11] = 0x00;
1258

    
1259
                    /* Claim PLAY_AUDIO capability (0x01) since some Linux
1260
                       code checks for this to automount media. */
1261
                    buf[12] = 0x71;
1262
                    buf[13] = 3 << 5;
1263
                    buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
1264
                    if (bdrv_is_locked(s->bs))
1265
                        buf[6] |= 1 << 1;
1266
                    buf[15] = 0x00;
1267
                    cpu_to_ube16(&buf[16], 706);
1268
                    buf[18] = 0;
1269
                    buf[19] = 2;
1270
                    cpu_to_ube16(&buf[20], 512);
1271
                    cpu_to_ube16(&buf[22], 706);
1272
                    buf[24] = 0;
1273
                    buf[25] = 0;
1274
                    buf[26] = 0;
1275
                    buf[27] = 0;
1276
                    ide_atapi_cmd_reply(s, 28, max_len);
1277
                    break;
1278
                default:
1279
                    goto error_cmd;
1280
                }
1281
                break;
1282
            case 1: /* changeable values */
1283
                goto error_cmd;
1284
            case 2: /* default values */
1285
                goto error_cmd;
1286
            default:
1287
            case 3: /* saved values */
1288
                ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1289
                                    ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
1290
                break;
1291
            }
1292
        }
1293
        break;
1294
    case GPCMD_REQUEST_SENSE:
1295
        max_len = packet[4];
1296
        memset(buf, 0, 18);
1297
        buf[0] = 0x70 | (1 << 7);
1298
        buf[2] = s->sense_key;
1299
        buf[7] = 10;
1300
        buf[12] = s->asc;
1301
        if (s->sense_key == SENSE_UNIT_ATTENTION)
1302
            s->sense_key = SENSE_NONE;
1303
        ide_atapi_cmd_reply(s, 18, max_len);
1304
        break;
1305
    case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
1306
        if (bdrv_is_inserted(s->bs)) {
1307
            bdrv_set_locked(s->bs, packet[4] & 1);
1308
            ide_atapi_cmd_ok(s);
1309
        } else {
1310
            ide_atapi_cmd_error(s, SENSE_NOT_READY,
1311
                                ASC_MEDIUM_NOT_PRESENT);
1312
        }
1313
        break;
1314
    case GPCMD_READ_10:
1315
    case GPCMD_READ_12:
1316
        {
1317
            int nb_sectors, lba;
1318

    
1319
            if (packet[0] == GPCMD_READ_10)
1320
                nb_sectors = ube16_to_cpu(packet + 7);
1321
            else
1322
                nb_sectors = ube32_to_cpu(packet + 6);
1323
            lba = ube32_to_cpu(packet + 2);
1324
            if (nb_sectors == 0) {
1325
                ide_atapi_cmd_ok(s);
1326
                break;
1327
            }
1328
            ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1329
        }
1330
        break;
1331
    case GPCMD_READ_CD:
1332
        {
1333
            int nb_sectors, lba, transfer_request;
1334

    
1335
            nb_sectors = (packet[6] << 16) | (packet[7] << 8) | packet[8];
1336
            lba = ube32_to_cpu(packet + 2);
1337
            if (nb_sectors == 0) {
1338
                ide_atapi_cmd_ok(s);
1339
                break;
1340
            }
1341
            transfer_request = packet[9];
1342
            switch(transfer_request & 0xf8) {
1343
            case 0x00:
1344
                /* nothing */
1345
                ide_atapi_cmd_ok(s);
1346
                break;
1347
            case 0x10:
1348
                /* normal read */
1349
                ide_atapi_cmd_read(s, lba, nb_sectors, 2048);
1350
                break;
1351
            case 0xf8:
1352
                /* read all data */
1353
                ide_atapi_cmd_read(s, lba, nb_sectors, 2352);
1354
                break;
1355
            default:
1356
                ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1357
                                    ASC_INV_FIELD_IN_CMD_PACKET);
1358
                break;
1359
            }
1360
        }
1361
        break;
1362
    case GPCMD_SEEK:
1363
        {
1364
            unsigned int lba;
1365
            uint64_t total_sectors;
1366

    
1367
            bdrv_get_geometry(s->bs, &total_sectors);
1368
            total_sectors >>= 2;
1369
            if (total_sectors == 0) {
1370
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
1371
                                    ASC_MEDIUM_NOT_PRESENT);
1372
                break;
1373
            }
1374
            lba = ube32_to_cpu(packet + 2);
1375
            if (lba >= total_sectors) {
1376
                ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1377
                                    ASC_LOGICAL_BLOCK_OOR);
1378
                break;
1379
            }
1380
            ide_atapi_cmd_ok(s);
1381
        }
1382
        break;
1383
    case GPCMD_START_STOP_UNIT:
1384
        {
1385
            int start, eject, err = 0;
1386
            start = packet[4] & 1;
1387
            eject = (packet[4] >> 1) & 1;
1388

    
1389
            if (eject) {
1390
                err = bdrv_eject(s->bs, !start);
1391
            }
1392

    
1393
            switch (err) {
1394
            case 0:
1395
                ide_atapi_cmd_ok(s);
1396
                break;
1397
            case -EBUSY:
1398
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
1399
                                    ASC_MEDIA_REMOVAL_PREVENTED);
1400
                break;
1401
            default:
1402
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
1403
                                    ASC_MEDIUM_NOT_PRESENT);
1404
                break;
1405
            }
1406
        }
1407
        break;
1408
    case GPCMD_MECHANISM_STATUS:
1409
        {
1410
            max_len = ube16_to_cpu(packet + 8);
1411
            cpu_to_ube16(buf, 0);
1412
            /* no current LBA */
1413
            buf[2] = 0;
1414
            buf[3] = 0;
1415
            buf[4] = 0;
1416
            buf[5] = 1;
1417
            cpu_to_ube16(buf + 6, 0);
1418
            ide_atapi_cmd_reply(s, 8, max_len);
1419
        }
1420
        break;
1421
    case GPCMD_READ_TOC_PMA_ATIP:
1422
        {
1423
            int format, msf, start_track, len;
1424
            uint64_t total_sectors;
1425

    
1426
            bdrv_get_geometry(s->bs, &total_sectors);
1427
            total_sectors >>= 2;
1428
            if (total_sectors == 0) {
1429
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
1430
                                    ASC_MEDIUM_NOT_PRESENT);
1431
                break;
1432
            }
1433
            max_len = ube16_to_cpu(packet + 7);
1434
            format = packet[9] >> 6;
1435
            msf = (packet[1] >> 1) & 1;
1436
            start_track = packet[6];
1437
            switch(format) {
1438
            case 0:
1439
                len = cdrom_read_toc(total_sectors, buf, msf, start_track);
1440
                if (len < 0)
1441
                    goto error_cmd;
1442
                ide_atapi_cmd_reply(s, len, max_len);
1443
                break;
1444
            case 1:
1445
                /* multi session : only a single session defined */
1446
                memset(buf, 0, 12);
1447
                buf[1] = 0x0a;
1448
                buf[2] = 0x01;
1449
                buf[3] = 0x01;
1450
                ide_atapi_cmd_reply(s, 12, max_len);
1451
                break;
1452
            case 2:
1453
                len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);
1454
                if (len < 0)
1455
                    goto error_cmd;
1456
                ide_atapi_cmd_reply(s, len, max_len);
1457
                break;
1458
            default:
1459
            error_cmd:
1460
                ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1461
                                    ASC_INV_FIELD_IN_CMD_PACKET);
1462
                break;
1463
            }
1464
        }
1465
        break;
1466
    case GPCMD_READ_CDVD_CAPACITY:
1467
        {
1468
            uint64_t total_sectors;
1469

    
1470
            bdrv_get_geometry(s->bs, &total_sectors);
1471
            total_sectors >>= 2;
1472
            if (total_sectors == 0) {
1473
                ide_atapi_cmd_error(s, SENSE_NOT_READY,
1474
                                    ASC_MEDIUM_NOT_PRESENT);
1475
                break;
1476
            }
1477
            /* NOTE: it is really the number of sectors minus 1 */
1478
            cpu_to_ube32(buf, total_sectors - 1);
1479
            cpu_to_ube32(buf + 4, 2048);
1480
            ide_atapi_cmd_reply(s, 8, 8);
1481
        }
1482
        break;
1483
    case GPCMD_READ_DVD_STRUCTURE:
1484
        {
1485
            int media = packet[1];
1486
            int format = packet[7];
1487
            int ret;
1488

    
1489
            max_len = ube16_to_cpu(packet + 8);
1490

    
1491
            if (format < 0xff) {
1492
                if (media_is_cd(s)) {
1493
                    ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1494
                                        ASC_INCOMPATIBLE_FORMAT);
1495
                    break;
1496
                } else if (!media_present(s)) {
1497
                    ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1498
                                        ASC_INV_FIELD_IN_CMD_PACKET);
1499
                    break;
1500
                }
1501
            }
1502

    
1503
            memset(buf, 0, max_len > IDE_DMA_BUF_SECTORS * 512 + 4 ?
1504
                   IDE_DMA_BUF_SECTORS * 512 + 4 : max_len);
1505

    
1506
            switch (format) {
1507
                case 0x00 ... 0x7f:
1508
                case 0xff:
1509
                    if (media == 0) {
1510
                        ret = ide_dvd_read_structure(s, format, packet, buf);
1511

    
1512
                        if (ret < 0)
1513
                            ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, -ret);
1514
                        else
1515
                            ide_atapi_cmd_reply(s, ret, max_len);
1516

    
1517
                        break;
1518
                    }
1519
                    /* TODO: BD support, fall through for now */
1520

    
1521
                /* Generic disk structures */
1522
                case 0x80: /* TODO: AACS volume identifier */
1523
                case 0x81: /* TODO: AACS media serial number */
1524
                case 0x82: /* TODO: AACS media identifier */
1525
                case 0x83: /* TODO: AACS media key block */
1526
                case 0x90: /* TODO: List of recognized format layers */
1527
                case 0xc0: /* TODO: Write protection status */
1528
                default:
1529
                    ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1530
                                        ASC_INV_FIELD_IN_CMD_PACKET);
1531
                    break;
1532
            }
1533
        }
1534
        break;
1535
    case GPCMD_SET_SPEED:
1536
        ide_atapi_cmd_ok(s);
1537
        break;
1538
    case GPCMD_INQUIRY:
1539
        max_len = packet[4];
1540
        buf[0] = 0x05; /* CD-ROM */
1541
        buf[1] = 0x80; /* removable */
1542
        buf[2] = 0x00; /* ISO */
1543
        buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */
1544
        buf[4] = 31; /* additional length */
1545
        buf[5] = 0; /* reserved */
1546
        buf[6] = 0; /* reserved */
1547
        buf[7] = 0; /* reserved */
1548
        padstr8(buf + 8, 8, "QEMU");
1549
        padstr8(buf + 16, 16, "QEMU DVD-ROM");
1550
        padstr8(buf + 32, 4, QEMU_VERSION);
1551
        ide_atapi_cmd_reply(s, 36, max_len);
1552
        break;
1553
    case GPCMD_GET_CONFIGURATION:
1554
        {
1555
            uint32_t len;
1556
            uint8_t index = 0;
1557

    
1558
            /* only feature 0 is supported */
1559
            if (packet[2] != 0 || packet[3] != 0) {
1560
                ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1561
                                    ASC_INV_FIELD_IN_CMD_PACKET);
1562
                break;
1563
            }
1564

    
1565
            /* XXX: could result in alignment problems in some architectures */
1566
            max_len = ube16_to_cpu(packet + 7);
1567

    
1568
            /*
1569
             * XXX: avoid overflow for io_buffer if max_len is bigger than
1570
             *      the size of that buffer (dimensioned to max number of
1571
             *      sectors to transfer at once)
1572
             *
1573
             *      Only a problem if the feature/profiles grow.
1574
             */
1575
            if (max_len > 512) /* XXX: assume 1 sector */
1576
                max_len = 512;
1577

    
1578
            memset(buf, 0, max_len);
1579
            /* 
1580
             * the number of sectors from the media tells us which profile
1581
             * to use as current.  0 means there is no media
1582
             */
1583
            if (media_is_dvd(s))
1584
                cpu_to_ube16(buf + 6, MMC_PROFILE_DVD_ROM);
1585
            else if (media_is_cd(s))
1586
                cpu_to_ube16(buf + 6, MMC_PROFILE_CD_ROM);
1587

    
1588
            buf[10] = 0x02 | 0x01; /* persistent and current */
1589
            len = 12; /* headers: 8 + 4 */
1590
            len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_DVD_ROM);
1591
            len += ide_atapi_set_profile(buf, &index, MMC_PROFILE_CD_ROM);
1592
            cpu_to_ube32(buf, len - 4); /* data length */
1593

    
1594
            ide_atapi_cmd_reply(s, len, max_len);
1595
            break;
1596
        }
1597
    default:
1598
        ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
1599
                            ASC_ILLEGAL_OPCODE);
1600
        break;
1601
    }
1602
}
1603

    
1604
static void ide_cfata_metadata_inquiry(IDEState *s)
1605
{
1606
    uint16_t *p;
1607
    uint32_t spd;
1608

    
1609
    p = (uint16_t *) s->io_buffer;
1610
    memset(p, 0, 0x200);
1611
    spd = ((s->mdata_size - 1) >> 9) + 1;
1612

    
1613
    put_le16(p + 0, 0x0001);                        /* Data format revision */
1614
    put_le16(p + 1, 0x0000);                        /* Media property: silicon */
1615
    put_le16(p + 2, s->media_changed);                /* Media status */
1616
    put_le16(p + 3, s->mdata_size & 0xffff);        /* Capacity in bytes (low) */
1617
    put_le16(p + 4, s->mdata_size >> 16);        /* Capacity in bytes (high) */
1618
    put_le16(p + 5, spd & 0xffff);                /* Sectors per device (low) */
1619
    put_le16(p + 6, spd >> 16);                        /* Sectors per device (high) */
1620
}
1621

    
1622
static void ide_cfata_metadata_read(IDEState *s)
1623
{
1624
    uint16_t *p;
1625

    
1626
    if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
1627
        s->status = ERR_STAT;
1628
        s->error = ABRT_ERR;
1629
        return;
1630
    }
1631

    
1632
    p = (uint16_t *) s->io_buffer;
1633
    memset(p, 0, 0x200);
1634

    
1635
    put_le16(p + 0, s->media_changed);                /* Media status */
1636
    memcpy(p + 1, s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
1637
                    MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
1638
                                    s->nsector << 9), 0x200 - 2));
1639
}
1640

    
1641
static void ide_cfata_metadata_write(IDEState *s)
1642
{
1643
    if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
1644
        s->status = ERR_STAT;
1645
        s->error = ABRT_ERR;
1646
        return;
1647
    }
1648

    
1649
    s->media_changed = 0;
1650

    
1651
    memcpy(s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
1652
                    s->io_buffer + 2,
1653
                    MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
1654
                                    s->nsector << 9), 0x200 - 2));
1655
}
1656

    
1657
/* called when the inserted state of the media has changed */
1658
static void cdrom_change_cb(void *opaque)
1659
{
1660
    IDEState *s = opaque;
1661
    uint64_t nb_sectors;
1662

    
1663
    bdrv_get_geometry(s->bs, &nb_sectors);
1664
    s->nb_sectors = nb_sectors;
1665

    
1666
    s->sense_key = SENSE_UNIT_ATTENTION;
1667
    s->asc = ASC_MEDIUM_MAY_HAVE_CHANGED;
1668
    s->cdrom_changed = 1;
1669
    ide_set_irq(s);
1670
}
1671

    
1672
static void ide_cmd_lba48_transform(IDEState *s, int lba48)
1673
{
1674
    s->lba48 = lba48;
1675

    
1676
    /* handle the 'magic' 0 nsector count conversion here. to avoid
1677
     * fiddling with the rest of the read logic, we just store the
1678
     * full sector count in ->nsector and ignore ->hob_nsector from now
1679
     */
1680
    if (!s->lba48) {
1681
        if (!s->nsector)
1682
            s->nsector = 256;
1683
    } else {
1684
        if (!s->nsector && !s->hob_nsector)
1685
            s->nsector = 65536;
1686
        else {
1687
            int lo = s->nsector;
1688
            int hi = s->hob_nsector;
1689

    
1690
            s->nsector = (hi << 8) | lo;
1691
        }
1692
    }
1693
}
1694

    
1695
static void ide_clear_hob(IDEBus *bus)
1696
{
1697
    /* any write clears HOB high bit of device control register */
1698
    bus->ifs[0].select &= ~(1 << 7);
1699
    bus->ifs[1].select &= ~(1 << 7);
1700
}
1701

    
1702
void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
1703
{
1704
    IDEBus *bus = opaque;
1705
    IDEState *s;
1706
    int n;
1707
    int lba48 = 0;
1708

    
1709
#ifdef DEBUG_IDE
1710
    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
1711
#endif
1712

    
1713
    addr &= 7;
1714

    
1715
    /* ignore writes to command block while busy with previous command */
1716
    if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
1717
        return;
1718

    
1719
    switch(addr) {
1720
    case 0:
1721
        break;
1722
    case 1:
1723
        ide_clear_hob(bus);
1724
        /* NOTE: data is written to the two drives */
1725
        bus->ifs[0].hob_feature = bus->ifs[0].feature;
1726
        bus->ifs[1].hob_feature = bus->ifs[1].feature;
1727
        bus->ifs[0].feature = val;
1728
        bus->ifs[1].feature = val;
1729
        break;
1730
    case 2:
1731
        ide_clear_hob(bus);
1732
        bus->ifs[0].hob_nsector = bus->ifs[0].nsector;
1733
        bus->ifs[1].hob_nsector = bus->ifs[1].nsector;
1734
        bus->ifs[0].nsector = val;
1735
        bus->ifs[1].nsector = val;
1736
        break;
1737
    case 3:
1738
        ide_clear_hob(bus);
1739
        bus->ifs[0].hob_sector = bus->ifs[0].sector;
1740
        bus->ifs[1].hob_sector = bus->ifs[1].sector;
1741
        bus->ifs[0].sector = val;
1742
        bus->ifs[1].sector = val;
1743
        break;
1744
    case 4:
1745
        ide_clear_hob(bus);
1746
        bus->ifs[0].hob_lcyl = bus->ifs[0].lcyl;
1747
        bus->ifs[1].hob_lcyl = bus->ifs[1].lcyl;
1748
        bus->ifs[0].lcyl = val;
1749
        bus->ifs[1].lcyl = val;
1750
        break;
1751
    case 5:
1752
        ide_clear_hob(bus);
1753
        bus->ifs[0].hob_hcyl = bus->ifs[0].hcyl;
1754
        bus->ifs[1].hob_hcyl = bus->ifs[1].hcyl;
1755
        bus->ifs[0].hcyl = val;
1756
        bus->ifs[1].hcyl = val;
1757
        break;
1758
    case 6:
1759
        /* FIXME: HOB readback uses bit 7 */
1760
        bus->ifs[0].select = (val & ~0x10) | 0xa0;
1761
        bus->ifs[1].select = (val | 0x10) | 0xa0;
1762
        /* select drive */
1763
        bus->unit = (val >> 4) & 1;
1764
        break;
1765
    default:
1766
    case 7:
1767
        /* command */
1768
#if defined(DEBUG_IDE)
1769
        printf("ide: CMD=%02x\n", val);
1770
#endif
1771
        s = idebus_active_if(bus);
1772
        /* ignore commands to non existant slave */
1773
        if (s != bus->ifs && !s->bs)
1774
            break;
1775

    
1776
        /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */
1777
        if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)
1778
            break;
1779

    
1780
        switch(val) {
1781
        case WIN_IDENTIFY:
1782
            if (s->bs && !s->is_cdrom) {
1783
                if (!s->is_cf)
1784
                    ide_identify(s);
1785
                else
1786
                    ide_cfata_identify(s);
1787
                s->status = READY_STAT | SEEK_STAT;
1788
                ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
1789
            } else {
1790
                if (s->is_cdrom) {
1791
                    ide_set_signature(s);
1792
                }
1793
                ide_abort_command(s);
1794
            }
1795
            ide_set_irq(s);
1796
            break;
1797
        case WIN_SPECIFY:
1798
        case WIN_RECAL:
1799
            s->error = 0;
1800
            s->status = READY_STAT | SEEK_STAT;
1801
            ide_set_irq(s);
1802
            break;
1803
        case WIN_SETMULT:
1804
            if (s->is_cf && s->nsector == 0) {
1805
                /* Disable Read and Write Multiple */
1806
                s->mult_sectors = 0;
1807
                s->status = READY_STAT | SEEK_STAT;
1808
            } else if ((s->nsector & 0xff) != 0 &&
1809
                ((s->nsector & 0xff) > MAX_MULT_SECTORS ||
1810
                 (s->nsector & (s->nsector - 1)) != 0)) {
1811
                ide_abort_command(s);
1812
            } else {
1813
                s->mult_sectors = s->nsector & 0xff;
1814
                s->status = READY_STAT | SEEK_STAT;
1815
            }
1816
            ide_set_irq(s);
1817
            break;
1818
        case WIN_VERIFY_EXT:
1819
            lba48 = 1;
1820
        case WIN_VERIFY:
1821
        case WIN_VERIFY_ONCE:
1822
            /* do sector number check ? */
1823
            ide_cmd_lba48_transform(s, lba48);
1824
            s->status = READY_STAT | SEEK_STAT;
1825
            ide_set_irq(s);
1826
            break;
1827
        case WIN_READ_EXT:
1828
            lba48 = 1;
1829
        case WIN_READ:
1830
        case WIN_READ_ONCE:
1831
            if (!s->bs)
1832
                goto abort_cmd;
1833
            ide_cmd_lba48_transform(s, lba48);
1834
            s->req_nb_sectors = 1;
1835
            ide_sector_read(s);
1836
            break;
1837
        case WIN_WRITE_EXT:
1838
            lba48 = 1;
1839
        case WIN_WRITE:
1840
        case WIN_WRITE_ONCE:
1841
        case CFA_WRITE_SECT_WO_ERASE:
1842
        case WIN_WRITE_VERIFY:
1843
            ide_cmd_lba48_transform(s, lba48);
1844
            s->error = 0;
1845
            s->status = SEEK_STAT | READY_STAT;
1846
            s->req_nb_sectors = 1;
1847
            ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);
1848
            s->media_changed = 1;
1849
            break;
1850
        case WIN_MULTREAD_EXT:
1851
            lba48 = 1;
1852
        case WIN_MULTREAD:
1853
            if (!s->mult_sectors)
1854
                goto abort_cmd;
1855
            ide_cmd_lba48_transform(s, lba48);
1856
            s->req_nb_sectors = s->mult_sectors;
1857
            ide_sector_read(s);
1858
            break;
1859
        case WIN_MULTWRITE_EXT:
1860
            lba48 = 1;
1861
        case WIN_MULTWRITE:
1862
        case CFA_WRITE_MULTI_WO_ERASE:
1863
            if (!s->mult_sectors)
1864
                goto abort_cmd;
1865
            ide_cmd_lba48_transform(s, lba48);
1866
            s->error = 0;
1867
            s->status = SEEK_STAT | READY_STAT;
1868
            s->req_nb_sectors = s->mult_sectors;
1869
            n = s->nsector;
1870
            if (n > s->req_nb_sectors)
1871
                n = s->req_nb_sectors;
1872
            ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);
1873
            s->media_changed = 1;
1874
            break;
1875
        case WIN_READDMA_EXT:
1876
            lba48 = 1;
1877
        case WIN_READDMA:
1878
        case WIN_READDMA_ONCE:
1879
            if (!s->bs)
1880
                goto abort_cmd;
1881
            ide_cmd_lba48_transform(s, lba48);
1882
            ide_sector_read_dma(s);
1883
            break;
1884
        case WIN_WRITEDMA_EXT:
1885
            lba48 = 1;
1886
        case WIN_WRITEDMA:
1887
        case WIN_WRITEDMA_ONCE:
1888
            if (!s->bs)
1889
                goto abort_cmd;
1890
            ide_cmd_lba48_transform(s, lba48);
1891
            ide_sector_write_dma(s);
1892
            s->media_changed = 1;
1893
            break;
1894
        case WIN_READ_NATIVE_MAX_EXT:
1895
            lba48 = 1;
1896
        case WIN_READ_NATIVE_MAX:
1897
            ide_cmd_lba48_transform(s, lba48);
1898
            ide_set_sector(s, s->nb_sectors - 1);
1899
            s->status = READY_STAT | SEEK_STAT;
1900
            ide_set_irq(s);
1901
            break;
1902
        case WIN_CHECKPOWERMODE1:
1903
        case WIN_CHECKPOWERMODE2:
1904
            s->nsector = 0xff; /* device active or idle */
1905
            s->status = READY_STAT | SEEK_STAT;
1906
            ide_set_irq(s);
1907
            break;
1908
        case WIN_SETFEATURES:
1909
            if (!s->bs)
1910
                goto abort_cmd;
1911
            /* XXX: valid for CDROM ? */
1912
            switch(s->feature) {
1913
            case 0xcc: /* reverting to power-on defaults enable */
1914
            case 0x66: /* reverting to power-on defaults disable */
1915
            case 0x02: /* write cache enable */
1916
            case 0x82: /* write cache disable */
1917
            case 0xaa: /* read look-ahead enable */
1918
            case 0x55: /* read look-ahead disable */
1919
            case 0x05: /* set advanced power management mode */
1920
            case 0x85: /* disable advanced power management mode */
1921
            case 0x69: /* NOP */
1922
            case 0x67: /* NOP */
1923
            case 0x96: /* NOP */
1924
            case 0x9a: /* NOP */
1925
            case 0x42: /* enable Automatic Acoustic Mode */
1926
            case 0xc2: /* disable Automatic Acoustic Mode */
1927
                s->status = READY_STAT | SEEK_STAT;
1928
                ide_set_irq(s);
1929
                break;
1930
            case 0x03: { /* set transfer mode */
1931
                uint8_t val = s->nsector & 0x07;
1932

    
1933
                switch (s->nsector >> 3) {
1934
                    case 0x00: /* pio default */
1935
                    case 0x01: /* pio mode */
1936
                        put_le16(s->identify_data + 62,0x07);
1937
                        put_le16(s->identify_data + 63,0x07);
1938
                        put_le16(s->identify_data + 88,0x3f);
1939
                        break;
1940
                    case 0x02: /* sigle word dma mode*/
1941
                        put_le16(s->identify_data + 62,0x07 | (1 << (val + 8)));
1942
                        put_le16(s->identify_data + 63,0x07);
1943
                        put_le16(s->identify_data + 88,0x3f);
1944
                        break;
1945
                    case 0x04: /* mdma mode */
1946
                        put_le16(s->identify_data + 62,0x07);
1947
                        put_le16(s->identify_data + 63,0x07 | (1 << (val + 8)));
1948
                        put_le16(s->identify_data + 88,0x3f);
1949
                        break;
1950
                    case 0x08: /* udma mode */
1951
                        put_le16(s->identify_data + 62,0x07);
1952
                        put_le16(s->identify_data + 63,0x07);
1953
                        put_le16(s->identify_data + 88,0x3f | (1 << (val + 8)));
1954
                        break;
1955
                    default:
1956
                        goto abort_cmd;
1957
                }
1958
                s->status = READY_STAT | SEEK_STAT;
1959
                ide_set_irq(s);
1960
                break;
1961
            }
1962
            default:
1963
                goto abort_cmd;
1964
            }
1965
            break;
1966
        case WIN_FLUSH_CACHE:
1967
        case WIN_FLUSH_CACHE_EXT:
1968
            if (s->bs)
1969
                bdrv_flush(s->bs);
1970
            s->status = READY_STAT | SEEK_STAT;
1971
            ide_set_irq(s);
1972
            break;
1973
        case WIN_STANDBY:
1974
        case WIN_STANDBY2:
1975
        case WIN_STANDBYNOW1:
1976
        case WIN_STANDBYNOW2:
1977
        case WIN_IDLEIMMEDIATE:
1978
        case CFA_IDLEIMMEDIATE:
1979
        case WIN_SETIDLE1:
1980
        case WIN_SETIDLE2:
1981
        case WIN_SLEEPNOW1:
1982
        case WIN_SLEEPNOW2:
1983
            s->status = READY_STAT;
1984
            ide_set_irq(s);
1985
            break;
1986
        case WIN_SEEK:
1987
            if(s->is_cdrom)
1988
                goto abort_cmd;
1989
            /* XXX: Check that seek is within bounds */
1990
            s->status = READY_STAT | SEEK_STAT;
1991
            ide_set_irq(s);
1992
            break;
1993
            /* ATAPI commands */
1994
        case WIN_PIDENTIFY:
1995
            if (s->is_cdrom) {
1996
                ide_atapi_identify(s);
1997
                s->status = READY_STAT | SEEK_STAT;
1998
                ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
1999
            } else {
2000
                ide_abort_command(s);
2001
            }
2002
            ide_set_irq(s);
2003
            break;
2004
        case WIN_DIAGNOSE:
2005
            ide_set_signature(s);
2006
            if (s->is_cdrom)
2007
                s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet
2008
                                * devices to return a clear status register
2009
                                * with READY_STAT *not* set. */
2010
            else
2011
                s->status = READY_STAT | SEEK_STAT;
2012
            s->error = 0x01; /* Device 0 passed, Device 1 passed or not
2013
                              * present. 
2014
                              */
2015
            ide_set_irq(s);
2016
            break;
2017
        case WIN_SRST:
2018
            if (!s->is_cdrom)
2019
                goto abort_cmd;
2020
            ide_set_signature(s);
2021
            s->status = 0x00; /* NOTE: READY is _not_ set */
2022
            s->error = 0x01;
2023
            break;
2024
        case WIN_PACKETCMD:
2025
            if (!s->is_cdrom)
2026
                goto abort_cmd;
2027
            /* overlapping commands not supported */
2028
            if (s->feature & 0x02)
2029
                goto abort_cmd;
2030
            s->status = READY_STAT | SEEK_STAT;
2031
            s->atapi_dma = s->feature & 1;
2032
            s->nsector = 1;
2033
            ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
2034
                               ide_atapi_cmd);
2035
            break;
2036
        /* CF-ATA commands */
2037
        case CFA_REQ_EXT_ERROR_CODE:
2038
            if (!s->is_cf)
2039
                goto abort_cmd;
2040
            s->error = 0x09;    /* miscellaneous error */
2041
            s->status = READY_STAT | SEEK_STAT;
2042
            ide_set_irq(s);
2043
            break;
2044
        case CFA_ERASE_SECTORS:
2045
        case CFA_WEAR_LEVEL:
2046
            if (!s->is_cf)
2047
                goto abort_cmd;
2048
            if (val == CFA_WEAR_LEVEL)
2049
                s->nsector = 0;
2050
            if (val == CFA_ERASE_SECTORS)
2051
                s->media_changed = 1;
2052
            s->error = 0x00;
2053
            s->status = READY_STAT | SEEK_STAT;
2054
            ide_set_irq(s);
2055
            break;
2056
        case CFA_TRANSLATE_SECTOR:
2057
            if (!s->is_cf)
2058
                goto abort_cmd;
2059
            s->error = 0x00;
2060
            s->status = READY_STAT | SEEK_STAT;
2061
            memset(s->io_buffer, 0, 0x200);
2062
            s->io_buffer[0x00] = s->hcyl;                        /* Cyl MSB */
2063
            s->io_buffer[0x01] = s->lcyl;                        /* Cyl LSB */
2064
            s->io_buffer[0x02] = s->select;                        /* Head */
2065
            s->io_buffer[0x03] = s->sector;                        /* Sector */
2066
            s->io_buffer[0x04] = ide_get_sector(s) >> 16;        /* LBA MSB */
2067
            s->io_buffer[0x05] = ide_get_sector(s) >> 8;        /* LBA */
2068
            s->io_buffer[0x06] = ide_get_sector(s) >> 0;        /* LBA LSB */
2069
            s->io_buffer[0x13] = 0x00;                                /* Erase flag */
2070
            s->io_buffer[0x18] = 0x00;                                /* Hot count */
2071
            s->io_buffer[0x19] = 0x00;                                /* Hot count */
2072
            s->io_buffer[0x1a] = 0x01;                                /* Hot count */
2073
            ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2074
            ide_set_irq(s);
2075
            break;
2076
        case CFA_ACCESS_METADATA_STORAGE:
2077
            if (!s->is_cf)
2078
                goto abort_cmd;
2079
            switch (s->feature) {
2080
            case 0x02:        /* Inquiry Metadata Storage */
2081
                ide_cfata_metadata_inquiry(s);
2082
                break;
2083
            case 0x03:        /* Read Metadata Storage */
2084
                ide_cfata_metadata_read(s);
2085
                break;
2086
            case 0x04:        /* Write Metadata Storage */
2087
                ide_cfata_metadata_write(s);
2088
                break;
2089
            default:
2090
                goto abort_cmd;
2091
            }
2092
            ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2093
            s->status = 0x00; /* NOTE: READY is _not_ set */
2094
            ide_set_irq(s);
2095
            break;
2096
        case IBM_SENSE_CONDITION:
2097
            if (!s->is_cf)
2098
                goto abort_cmd;
2099
            switch (s->feature) {
2100
            case 0x01:  /* sense temperature in device */
2101
                s->nsector = 0x50;      /* +20 C */
2102
                break;
2103
            default:
2104
                goto abort_cmd;
2105
            }
2106
            s->status = READY_STAT | SEEK_STAT;
2107
            ide_set_irq(s);
2108
            break;
2109

    
2110
        case WIN_SMART:
2111
            if (s->is_cdrom)
2112
                goto abort_cmd;
2113
            if (s->hcyl != 0xc2 || s->lcyl != 0x4f)
2114
                goto abort_cmd;
2115
            if (!s->smart_enabled && s->feature != SMART_ENABLE)
2116
                goto abort_cmd;
2117
            switch (s->feature) {
2118
            case SMART_DISABLE:
2119
                s->smart_enabled = 0;
2120
                s->status = READY_STAT | SEEK_STAT;
2121
                ide_set_irq(s);
2122
                break;
2123
            case SMART_ENABLE:
2124
                s->smart_enabled = 1;
2125
                s->status = READY_STAT | SEEK_STAT;
2126
                ide_set_irq(s);
2127
                break;
2128
            case SMART_ATTR_AUTOSAVE:
2129
                switch (s->sector) {
2130
                case 0x00:
2131
                    s->smart_autosave = 0;
2132
                    break;
2133
                case 0xf1:
2134
                    s->smart_autosave = 1;
2135
                    break;
2136
                default:
2137
                    goto abort_cmd;
2138
                }
2139
                s->status = READY_STAT | SEEK_STAT;
2140
                ide_set_irq(s);
2141
                break;
2142
            case SMART_STATUS:
2143
                if (!s->smart_errors) {
2144
                    s->hcyl = 0xc2;
2145
                    s->lcyl = 0x4f;
2146
                } else {
2147
                    s->hcyl = 0x2c;
2148
                    s->lcyl = 0xf4;
2149
                }
2150
                s->status = READY_STAT | SEEK_STAT;
2151
                ide_set_irq(s);
2152
                break;
2153
            case SMART_READ_THRESH:
2154
                memset(s->io_buffer, 0, 0x200);
2155
                s->io_buffer[0] = 0x01; /* smart struct version */
2156
                for (n=0; n<30; n++) {
2157
                    if (smart_attributes[n][0] == 0)
2158
                        break;
2159
                    s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2160
                    s->io_buffer[2+1+(n*12)] = smart_attributes[n][4];
2161
                }
2162
                for (n=0; n<511; n++) /* checksum */
2163
                    s->io_buffer[511] += s->io_buffer[n];
2164
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
2165
                s->status = READY_STAT | SEEK_STAT;
2166
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2167
                ide_set_irq(s);
2168
                break;
2169
            case SMART_READ_DATA:
2170
                memset(s->io_buffer, 0, 0x200);
2171
                s->io_buffer[0] = 0x01; /* smart struct version */
2172
                for (n=0; n<30; n++) {
2173
                    if (smart_attributes[n][0] == 0)
2174
                        break;
2175
                    s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
2176
                    s->io_buffer[2+1+(n*12)] = smart_attributes[n][1];
2177
                    s->io_buffer[2+3+(n*12)] = smart_attributes[n][2];
2178
                    s->io_buffer[2+4+(n*12)] = smart_attributes[n][3];
2179
                }
2180
                s->io_buffer[362] = 0x02 | (s->smart_autosave?0x80:0x00);
2181
                if (s->smart_selftest_count == 0) {
2182
                    s->io_buffer[363] = 0;
2183
                } else {
2184
                    s->io_buffer[363] = 
2185
                        s->smart_selftest_data[3 + 
2186
                                               (s->smart_selftest_count - 1) * 
2187
                                               24];
2188
                }
2189
                s->io_buffer[364] = 0x20; 
2190
                s->io_buffer[365] = 0x01; 
2191
                /* offline data collection capacity: execute + self-test*/
2192
                s->io_buffer[367] = (1<<4 | 1<<3 | 1); 
2193
                s->io_buffer[368] = 0x03; /* smart capability (1) */
2194
                s->io_buffer[369] = 0x00; /* smart capability (2) */
2195
                s->io_buffer[370] = 0x01; /* error logging supported */
2196
                s->io_buffer[372] = 0x02; /* minutes for poll short test */
2197
                s->io_buffer[373] = 0x36; /* minutes for poll ext test */
2198
                s->io_buffer[374] = 0x01; /* minutes for poll conveyance */
2199

    
2200
                for (n=0; n<511; n++) 
2201
                    s->io_buffer[511] += s->io_buffer[n];
2202
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
2203
                s->status = READY_STAT | SEEK_STAT;
2204
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2205
                ide_set_irq(s);
2206
                break;
2207
            case SMART_READ_LOG:
2208
                switch (s->sector) {
2209
                case 0x01: /* summary smart error log */
2210
                    memset(s->io_buffer, 0, 0x200);
2211
                    s->io_buffer[0] = 0x01;
2212
                    s->io_buffer[1] = 0x00; /* no error entries */
2213
                    s->io_buffer[452] = s->smart_errors & 0xff;
2214
                    s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;
2215

    
2216
                    for (n=0; n<511; n++)
2217
                        s->io_buffer[511] += s->io_buffer[n];
2218
                    s->io_buffer[511] = 0x100 - s->io_buffer[511];
2219
                    break;
2220
                case 0x06: /* smart self test log */
2221
                    memset(s->io_buffer, 0, 0x200);
2222
                    s->io_buffer[0] = 0x01; 
2223
                    if (s->smart_selftest_count == 0) {
2224
                        s->io_buffer[508] = 0;
2225
                    } else {
2226
                        s->io_buffer[508] = s->smart_selftest_count;
2227
                        for (n=2; n<506; n++) 
2228
                            s->io_buffer[n] = s->smart_selftest_data[n];
2229
                    }                    
2230
                    for (n=0; n<511; n++)
2231
                        s->io_buffer[511] += s->io_buffer[n];
2232
                    s->io_buffer[511] = 0x100 - s->io_buffer[511];
2233
                    break;
2234
                default:
2235
                    goto abort_cmd;
2236
                }
2237
                s->status = READY_STAT | SEEK_STAT;
2238
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
2239
                ide_set_irq(s);
2240
                break;
2241
            case SMART_EXECUTE_OFFLINE:
2242
                switch (s->sector) {
2243
                case 0: /* off-line routine */
2244
                case 1: /* short self test */
2245
                case 2: /* extended self test */
2246
                    s->smart_selftest_count++;
2247
                    if(s->smart_selftest_count > 21)
2248
                        s->smart_selftest_count = 0;
2249
                    n = 2 + (s->smart_selftest_count - 1) * 24;
2250
                    s->smart_selftest_data[n] = s->sector;
2251
                    s->smart_selftest_data[n+1] = 0x00; /* OK and finished */
2252
                    s->smart_selftest_data[n+2] = 0x34; /* hour count lsb */
2253
                    s->smart_selftest_data[n+3] = 0x12; /* hour count msb */
2254
                    s->status = READY_STAT | SEEK_STAT;
2255
                    ide_set_irq(s);
2256
                    break;
2257
                default:
2258
                    goto abort_cmd;
2259
                }
2260
                break;
2261
            default:
2262
                goto abort_cmd;
2263
            }
2264
            break;
2265
        default:
2266
        abort_cmd:
2267
            ide_abort_command(s);
2268
            ide_set_irq(s);
2269
            break;
2270
        }
2271
    }
2272
}
2273

    
2274
uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
2275
{
2276
    IDEBus *bus = opaque;
2277
    IDEState *s = idebus_active_if(bus);
2278
    uint32_t addr;
2279
    int ret, hob;
2280

    
2281
    addr = addr1 & 7;
2282
    /* FIXME: HOB readback uses bit 7, but it's always set right now */
2283
    //hob = s->select & (1 << 7);
2284
    hob = 0;
2285
    switch(addr) {
2286
    case 0:
2287
        ret = 0xff;
2288
        break;
2289
    case 1:
2290
        if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2291
            (s != bus->ifs && !s->bs))
2292
            ret = 0;
2293
        else if (!hob)
2294
            ret = s->error;
2295
        else
2296
            ret = s->hob_feature;
2297
        break;
2298
    case 2:
2299
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2300
            ret = 0;
2301
        else if (!hob)
2302
            ret = s->nsector & 0xff;
2303
        else
2304
            ret = s->hob_nsector;
2305
        break;
2306
    case 3:
2307
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2308
            ret = 0;
2309
        else if (!hob)
2310
            ret = s->sector;
2311
        else
2312
            ret = s->hob_sector;
2313
        break;
2314
    case 4:
2315
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2316
            ret = 0;
2317
        else if (!hob)
2318
            ret = s->lcyl;
2319
        else
2320
            ret = s->hob_lcyl;
2321
        break;
2322
    case 5:
2323
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2324
            ret = 0;
2325
        else if (!hob)
2326
            ret = s->hcyl;
2327
        else
2328
            ret = s->hob_hcyl;
2329
        break;
2330
    case 6:
2331
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
2332
            ret = 0;
2333
        else
2334
            ret = s->select;
2335
        break;
2336
    default:
2337
    case 7:
2338
        if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2339
            (s != bus->ifs && !s->bs))
2340
            ret = 0;
2341
        else
2342
            ret = s->status;
2343
        qemu_irq_lower(s->irq);
2344
        break;
2345
    }
2346
#ifdef DEBUG_IDE
2347
    printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
2348
#endif
2349
    return ret;
2350
}
2351

    
2352
uint32_t ide_status_read(void *opaque, uint32_t addr)
2353
{
2354
    IDEBus *bus = opaque;
2355
    IDEState *s = idebus_active_if(bus);
2356
    int ret;
2357

    
2358
    if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
2359
        (s != bus->ifs && !s->bs))
2360
        ret = 0;
2361
    else
2362
        ret = s->status;
2363
#ifdef DEBUG_IDE
2364
    printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
2365
#endif
2366
    return ret;
2367
}
2368

    
2369
void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
2370
{
2371
    IDEBus *bus = opaque;
2372
    IDEState *s;
2373
    int i;
2374

    
2375
#ifdef DEBUG_IDE
2376
    printf("ide: write control addr=0x%x val=%02x\n", addr, val);
2377
#endif
2378
    /* common for both drives */
2379
    if (!(bus->ifs[0].cmd & IDE_CMD_RESET) &&
2380
        (val & IDE_CMD_RESET)) {
2381
        /* reset low to high */
2382
        for(i = 0;i < 2; i++) {
2383
            s = &bus->ifs[i];
2384
            s->status = BUSY_STAT | SEEK_STAT;
2385
            s->error = 0x01;
2386
        }
2387
    } else if ((bus->ifs[0].cmd & IDE_CMD_RESET) &&
2388
               !(val & IDE_CMD_RESET)) {
2389
        /* high to low */
2390
        for(i = 0;i < 2; i++) {
2391
            s = &bus->ifs[i];
2392
            if (s->is_cdrom)
2393
                s->status = 0x00; /* NOTE: READY is _not_ set */
2394
            else
2395
                s->status = READY_STAT | SEEK_STAT;
2396
            ide_set_signature(s);
2397
        }
2398
    }
2399

    
2400
    bus->ifs[0].cmd = val;
2401
    bus->ifs[1].cmd = val;
2402
}
2403

    
2404
void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
2405
{
2406
    IDEBus *bus = opaque;
2407
    IDEState *s = idebus_active_if(bus);
2408
    uint8_t *p;
2409

    
2410
    /* PIO data access allowed only when DRQ bit is set */
2411
    if (!(s->status & DRQ_STAT))
2412
        return;
2413

    
2414
    p = s->data_ptr;
2415
    *(uint16_t *)p = le16_to_cpu(val);
2416
    p += 2;
2417
    s->data_ptr = p;
2418
    if (p >= s->data_end)
2419
        s->end_transfer_func(s);
2420
}
2421

    
2422
uint32_t ide_data_readw(void *opaque, uint32_t addr)
2423
{
2424
    IDEBus *bus = opaque;
2425
    IDEState *s = idebus_active_if(bus);
2426
    uint8_t *p;
2427
    int ret;
2428

    
2429
    /* PIO data access allowed only when DRQ bit is set */
2430
    if (!(s->status & DRQ_STAT))
2431
        return 0;
2432

    
2433
    p = s->data_ptr;
2434
    ret = cpu_to_le16(*(uint16_t *)p);
2435
    p += 2;
2436
    s->data_ptr = p;
2437
    if (p >= s->data_end)
2438
        s->end_transfer_func(s);
2439
    return ret;
2440
}
2441

    
2442
void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
2443
{
2444
    IDEBus *bus = opaque;
2445
    IDEState *s = idebus_active_if(bus);
2446
    uint8_t *p;
2447

    
2448
    /* PIO data access allowed only when DRQ bit is set */
2449
    if (!(s->status & DRQ_STAT))
2450
        return;
2451

    
2452
    p = s->data_ptr;
2453
    *(uint32_t *)p = le32_to_cpu(val);
2454
    p += 4;
2455
    s->data_ptr = p;
2456
    if (p >= s->data_end)
2457
        s->end_transfer_func(s);
2458
}
2459

    
2460
uint32_t ide_data_readl(void *opaque, uint32_t addr)
2461
{
2462
    IDEBus *bus = opaque;
2463
    IDEState *s = idebus_active_if(bus);
2464
    uint8_t *p;
2465
    int ret;
2466

    
2467
    /* PIO data access allowed only when DRQ bit is set */
2468
    if (!(s->status & DRQ_STAT))
2469
        return 0;
2470

    
2471
    p = s->data_ptr;
2472
    ret = cpu_to_le32(*(uint32_t *)p);
2473
    p += 4;
2474
    s->data_ptr = p;
2475
    if (p >= s->data_end)
2476
        s->end_transfer_func(s);
2477
    return ret;
2478
}
2479

    
2480
static void ide_dummy_transfer_stop(IDEState *s)
2481
{
2482
    s->data_ptr = s->io_buffer;
2483
    s->data_end = s->io_buffer;
2484
    s->io_buffer[0] = 0xff;
2485
    s->io_buffer[1] = 0xff;
2486
    s->io_buffer[2] = 0xff;
2487
    s->io_buffer[3] = 0xff;
2488
}
2489

    
2490
void ide_reset(IDEState *s)
2491
{
2492
    IDEBus *bus = s->bus;
2493

    
2494
    if (s->is_cf)
2495
        s->mult_sectors = 0;
2496
    else
2497
        s->mult_sectors = MAX_MULT_SECTORS;
2498
    bus->unit = s->unit;
2499
    s->select = 0xa0;
2500
    s->status = READY_STAT | SEEK_STAT;
2501
    ide_set_signature(s);
2502
    /* init the transfer handler so that 0xffff is returned on data
2503
       accesses */
2504
    s->end_transfer_func = ide_dummy_transfer_stop;
2505
    ide_dummy_transfer_stop(s);
2506
    s->media_changed = 0;
2507
}
2508

    
2509
void ide_init2(IDEBus *bus, BlockDriverState *hd0, BlockDriverState *hd1,
2510
               qemu_irq irq)
2511
{
2512
    IDEState *s;
2513
    static int drive_serial = 1;
2514
    int i, cylinders, heads, secs;
2515
    uint64_t nb_sectors;
2516

    
2517
    for(i = 0; i < 2; i++) {
2518
        s = bus->ifs + i;
2519
        s->bus = bus;
2520
        s->unit = i;
2521
        s->bs = (i == 0) ? hd0 : hd1;
2522
        s->io_buffer = qemu_blockalign(s->bs, IDE_DMA_BUF_SECTORS*512 + 4);
2523
        if (s->bs) {
2524
            bdrv_get_geometry(s->bs, &nb_sectors);
2525
            bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);
2526
            s->cylinders = cylinders;
2527
            s->heads = heads;
2528
            s->sectors = secs;
2529
            s->nb_sectors = nb_sectors;
2530
            /* The SMART values should be preserved across power cycles
2531
               but they aren't.  */
2532
            s->smart_enabled = 1;
2533
            s->smart_autosave = 1;
2534
            s->smart_errors = 0;
2535
            s->smart_selftest_count = 0;
2536
            s->smart_selftest_data = qemu_blockalign(s->bs, 512);
2537
            if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
2538
                s->is_cdrom = 1;
2539
                bdrv_set_change_cb(s->bs, cdrom_change_cb, s);
2540
            }
2541
        }
2542
        s->drive_serial = drive_serial++;
2543
        strncpy(s->drive_serial_str, drive_get_serial(s->bs),
2544
                sizeof(s->drive_serial_str));
2545
        if (strlen(s->drive_serial_str) == 0)
2546
            snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
2547
                    "QM%05d", s->drive_serial);
2548
        s->irq = irq;
2549
        s->sector_write_timer = qemu_new_timer(vm_clock,
2550
                                               ide_sector_write_timer_cb, s);
2551
        ide_reset(s);
2552
    }
2553
}
2554

    
2555
void ide_init_ioport(IDEBus *bus, int iobase, int iobase2)
2556
{
2557
    register_ioport_write(iobase, 8, 1, ide_ioport_write, bus);
2558
    register_ioport_read(iobase, 8, 1, ide_ioport_read, bus);
2559
    if (iobase2) {
2560
        register_ioport_read(iobase2, 1, 1, ide_status_read, bus);
2561
        register_ioport_write(iobase2, 1, 1, ide_cmd_write, bus);
2562
    }
2563

    
2564
    /* data ports */
2565
    register_ioport_write(iobase, 2, 2, ide_data_writew, bus);
2566
    register_ioport_read(iobase, 2, 2, ide_data_readw, bus);
2567
    register_ioport_write(iobase, 4, 4, ide_data_writel, bus);
2568
    register_ioport_read(iobase, 4, 4, ide_data_readl, bus);
2569
}
2570

    
2571
/* save per IDE drive data */
2572
void ide_save(QEMUFile* f, IDEState *s)
2573
{
2574
    qemu_put_be32(f, s->mult_sectors);
2575
    qemu_put_be32(f, s->identify_set);
2576
    if (s->identify_set) {
2577
        qemu_put_buffer(f, (const uint8_t *)s->identify_data, 512);
2578
    }
2579
    qemu_put_8s(f, &s->feature);
2580
    qemu_put_8s(f, &s->error);
2581
    qemu_put_be32s(f, &s->nsector);
2582
    qemu_put_8s(f, &s->sector);
2583
    qemu_put_8s(f, &s->lcyl);
2584
    qemu_put_8s(f, &s->hcyl);
2585
    qemu_put_8s(f, &s->hob_feature);
2586
    qemu_put_8s(f, &s->hob_nsector);
2587
    qemu_put_8s(f, &s->hob_sector);
2588
    qemu_put_8s(f, &s->hob_lcyl);
2589
    qemu_put_8s(f, &s->hob_hcyl);
2590
    qemu_put_8s(f, &s->select);
2591
    qemu_put_8s(f, &s->status);
2592
    qemu_put_8s(f, &s->lba48);
2593

    
2594
    qemu_put_8s(f, &s->sense_key);
2595
    qemu_put_8s(f, &s->asc);
2596
    qemu_put_8s(f, &s->cdrom_changed);
2597
    /* XXX: if a transfer is pending, we do not save it yet */
2598
}
2599

    
2600
/* load per IDE drive data */
2601
void ide_load(QEMUFile* f, IDEState *s, int version_id)
2602
{
2603
    s->mult_sectors=qemu_get_be32(f);
2604
    s->identify_set=qemu_get_be32(f);
2605
    if (s->identify_set) {
2606
        qemu_get_buffer(f, (uint8_t *)s->identify_data, 512);
2607
    }
2608
    qemu_get_8s(f, &s->feature);
2609
    qemu_get_8s(f, &s->error);
2610
    qemu_get_be32s(f, &s->nsector);
2611
    qemu_get_8s(f, &s->sector);
2612
    qemu_get_8s(f, &s->lcyl);
2613
    qemu_get_8s(f, &s->hcyl);
2614
    qemu_get_8s(f, &s->hob_feature);
2615
    qemu_get_8s(f, &s->hob_nsector);
2616
    qemu_get_8s(f, &s->hob_sector);
2617
    qemu_get_8s(f, &s->hob_lcyl);
2618
    qemu_get_8s(f, &s->hob_hcyl);
2619
    qemu_get_8s(f, &s->select);
2620
    qemu_get_8s(f, &s->status);
2621
    qemu_get_8s(f, &s->lba48);
2622

    
2623
    qemu_get_8s(f, &s->sense_key);
2624
    qemu_get_8s(f, &s->asc);
2625
    if (version_id == 3) {
2626
        qemu_get_8s(f, &s->cdrom_changed);
2627
    } else {
2628
        if (s->sense_key == SENSE_UNIT_ATTENTION &&
2629
                       s->asc == ASC_MEDIUM_MAY_HAVE_CHANGED)
2630
            s->cdrom_changed = 1;
2631
    }
2632
    /* XXX: if a transfer is pending, we do not save it yet */
2633
}
2634

    
2635
void idebus_save(QEMUFile* f, IDEBus *bus)
2636
{
2637
    IDEState *s = idebus_active_if(bus);
2638
    qemu_put_8s(f, &s->cmd);
2639
    qemu_put_8s(f, &bus->unit);
2640
}
2641

    
2642
void idebus_load(QEMUFile* f, IDEBus *bus, int version_id)
2643
{
2644
    IDEState *s;
2645
    uint8_t cmd;
2646

    
2647
    qemu_get_8s(f, &cmd);
2648
    qemu_get_8s(f, &bus->unit);
2649
    s = idebus_active_if(bus);
2650
    s->cmd = cmd;
2651
}
2652

    
2653
/***********************************************************/
2654
/* PCI IDE definitions */
2655

    
2656
static void ide_dma_start(IDEState *s, BlockDriverCompletionFunc *dma_cb)
2657
{
2658
    BMDMAState *bm = s->bus->bmdma;
2659
    if(!bm)
2660
        return;
2661
    bm->unit = s->unit;
2662
    bm->dma_cb = dma_cb;
2663
    bm->cur_prd_last = 0;
2664
    bm->cur_prd_addr = 0;
2665
    bm->cur_prd_len = 0;
2666
    bm->sector_num = ide_get_sector(s);
2667
    bm->nsector = s->nsector;
2668
    if (bm->status & BM_STATUS_DMAING) {
2669
        bm->dma_cb(bm, 0);
2670
    }
2671
}
2672

    
2673
static void ide_dma_restart(IDEState *s)
2674
{
2675
    BMDMAState *bm = s->bus->bmdma;
2676
    ide_set_sector(s, bm->sector_num);
2677
    s->io_buffer_index = 0;
2678
    s->io_buffer_size = 0;
2679
    s->nsector = bm->nsector;
2680
    bm->cur_addr = bm->addr;
2681
    bm->dma_cb = ide_write_dma_cb;
2682
    ide_dma_start(s, bm->dma_cb);
2683
}
2684

    
2685
void ide_dma_cancel(BMDMAState *bm)
2686
{
2687
    if (bm->status & BM_STATUS_DMAING) {
2688
        bm->status &= ~BM_STATUS_DMAING;
2689
        /* cancel DMA request */
2690
        bm->unit = -1;
2691
        bm->dma_cb = NULL;
2692
        if (bm->aiocb) {
2693
#ifdef DEBUG_AIO
2694
            printf("aio_cancel\n");
2695
#endif
2696
            bdrv_aio_cancel(bm->aiocb);
2697
            bm->aiocb = NULL;
2698
        }
2699
    }
2700
}
2701

    
2702
/***********************************************************/
2703
/* MMIO based ide port
2704
 * This emulates IDE device connected directly to the CPU bus without
2705
 * dedicated ide controller, which is often seen on embedded boards.
2706
 */
2707

    
2708
typedef struct {
2709
    IDEBus *bus;
2710
    int shift;
2711
} MMIOState;
2712

    
2713
static uint32_t mmio_ide_read (void *opaque, target_phys_addr_t addr)
2714
{
2715
    MMIOState *s = (MMIOState*)opaque;
2716
    IDEBus *bus = s->bus;
2717
    addr >>= s->shift;
2718
    if (addr & 7)
2719
        return ide_ioport_read(bus, addr);
2720
    else
2721
        return ide_data_readw(bus, 0);
2722
}
2723

    
2724
static void mmio_ide_write (void *opaque, target_phys_addr_t addr,
2725
        uint32_t val)
2726
{
2727
    MMIOState *s = (MMIOState*)opaque;
2728
    IDEBus *bus = s->bus;
2729
    addr >>= s->shift;
2730
    if (addr & 7)
2731
        ide_ioport_write(bus, addr, val);
2732
    else
2733
        ide_data_writew(bus, 0, val);
2734
}
2735

    
2736
static CPUReadMemoryFunc * const mmio_ide_reads[] = {
2737
    mmio_ide_read,
2738
    mmio_ide_read,
2739
    mmio_ide_read,
2740
};
2741

    
2742
static CPUWriteMemoryFunc * const mmio_ide_writes[] = {
2743
    mmio_ide_write,
2744
    mmio_ide_write,
2745
    mmio_ide_write,
2746
};
2747

    
2748
static uint32_t mmio_ide_status_read (void *opaque, target_phys_addr_t addr)
2749
{
2750
    MMIOState *s= (MMIOState*)opaque;
2751
    IDEBus *bus = s->bus;
2752
    return ide_status_read(bus, 0);
2753
}
2754

    
2755
static void mmio_ide_cmd_write (void *opaque, target_phys_addr_t addr,
2756
        uint32_t val)
2757
{
2758
    MMIOState *s = (MMIOState*)opaque;
2759
    IDEBus *bus = s->bus;
2760
    ide_cmd_write(bus, 0, val);
2761
}
2762

    
2763
static CPUReadMemoryFunc * const mmio_ide_status[] = {
2764
    mmio_ide_status_read,
2765
    mmio_ide_status_read,
2766
    mmio_ide_status_read,
2767
};
2768

    
2769
static CPUWriteMemoryFunc * const mmio_ide_cmd[] = {
2770
    mmio_ide_cmd_write,
2771
    mmio_ide_cmd_write,
2772
    mmio_ide_cmd_write,
2773
};
2774

    
2775
void mmio_ide_init (target_phys_addr_t membase, target_phys_addr_t membase2,
2776
                    qemu_irq irq, int shift,
2777
                    BlockDriverState *hd0, BlockDriverState *hd1)
2778
{
2779
    MMIOState *s = qemu_mallocz(sizeof(MMIOState));
2780
    IDEBus *bus = qemu_mallocz(sizeof(*bus));
2781
    int mem1, mem2;
2782

    
2783
    ide_init2(bus, hd0, hd1, irq);
2784

    
2785
    s->bus = bus;
2786
    s->shift = shift;
2787

    
2788
    mem1 = cpu_register_io_memory(mmio_ide_reads, mmio_ide_writes, s);
2789
    mem2 = cpu_register_io_memory(mmio_ide_status, mmio_ide_cmd, s);
2790
    cpu_register_physical_memory(membase, 16 << shift, mem1);
2791
    cpu_register_physical_memory(membase2, 2 << shift, mem2);
2792
}
2793

    
2794
/***********************************************************/
2795
/* CF-ATA Microdrive */
2796

    
2797
#define METADATA_SIZE        0x20
2798

    
2799
/* DSCM-1XXXX Microdrive hard disk with CF+ II / PCMCIA interface.  */
2800
typedef struct {
2801
    IDEBus bus;
2802
    PCMCIACardState card;
2803
    uint32_t attr_base;
2804
    uint32_t io_base;
2805

    
2806
    /* Card state */
2807
    uint8_t opt;
2808
    uint8_t stat;
2809
    uint8_t pins;
2810

    
2811
    uint8_t ctrl;
2812
    uint16_t io;
2813
    int cycle;
2814
} MicroDriveState;
2815

    
2816
/* Register bitfields */
2817
enum md_opt {
2818
    OPT_MODE_MMAP        = 0,
2819
    OPT_MODE_IOMAP16        = 1,
2820
    OPT_MODE_IOMAP1        = 2,
2821
    OPT_MODE_IOMAP2        = 3,
2822
    OPT_MODE                = 0x3f,
2823
    OPT_LEVIREQ                = 0x40,
2824
    OPT_SRESET                = 0x80,
2825
};
2826
enum md_cstat {
2827
    STAT_INT                = 0x02,
2828
    STAT_PWRDWN                = 0x04,
2829
    STAT_XE                = 0x10,
2830
    STAT_IOIS8                = 0x20,
2831
    STAT_SIGCHG                = 0x40,
2832
    STAT_CHANGED        = 0x80,
2833
};
2834
enum md_pins {
2835
    PINS_MRDY                = 0x02,
2836
    PINS_CRDY                = 0x20,
2837
};
2838
enum md_ctrl {
2839
    CTRL_IEN                = 0x02,
2840
    CTRL_SRST                = 0x04,
2841
};
2842

    
2843
static inline void md_interrupt_update(MicroDriveState *s)
2844
{
2845
    if (!s->card.slot)
2846
        return;
2847

    
2848
    qemu_set_irq(s->card.slot->irq,
2849
                    !(s->stat & STAT_INT) &&        /* Inverted */
2850
                    !(s->ctrl & (CTRL_IEN | CTRL_SRST)) &&
2851
                    !(s->opt & OPT_SRESET));
2852
}
2853

    
2854
static void md_set_irq(void *opaque, int irq, int level)
2855
{
2856
    MicroDriveState *s = (MicroDriveState *) opaque;
2857
    if (level)
2858
        s->stat |= STAT_INT;
2859
    else
2860
        s->stat &= ~STAT_INT;
2861

    
2862
    md_interrupt_update(s);
2863
}
2864

    
2865
static void md_reset(MicroDriveState *s)
2866
{
2867
    s->opt = OPT_MODE_MMAP;
2868
    s->stat = 0;
2869
    s->pins = 0;
2870
    s->cycle = 0;
2871
    s->ctrl = 0;
2872
    ide_reset(s->bus.ifs);
2873
}
2874

    
2875
static uint8_t md_attr_read(void *opaque, uint32_t at)
2876
{
2877
    MicroDriveState *s = (MicroDriveState *) opaque;
2878
    if (at < s->attr_base) {
2879
        if (at < s->card.cis_len)
2880
            return s->card.cis[at];
2881
        else
2882
            return 0x00;
2883
    }
2884

    
2885
    at -= s->attr_base;
2886

    
2887
    switch (at) {
2888
    case 0x00:        /* Configuration Option Register */
2889
        return s->opt;
2890
    case 0x02:        /* Card Configuration Status Register */
2891
        if (s->ctrl & CTRL_IEN)
2892
            return s->stat & ~STAT_INT;
2893
        else
2894
            return s->stat;
2895
    case 0x04:        /* Pin Replacement Register */
2896
        return (s->pins & PINS_CRDY) | 0x0c;
2897
    case 0x06:        /* Socket and Copy Register */
2898
        return 0x00;
2899
#ifdef VERBOSE
2900
    default:
2901
        printf("%s: Bad attribute space register %02x\n", __FUNCTION__, at);
2902
#endif
2903
    }
2904

    
2905
    return 0;
2906
}
2907

    
2908
static void md_attr_write(void *opaque, uint32_t at, uint8_t value)
2909
{
2910
    MicroDriveState *s = (MicroDriveState *) opaque;
2911
    at -= s->attr_base;
2912

    
2913
    switch (at) {
2914
    case 0x00:        /* Configuration Option Register */
2915
        s->opt = value & 0xcf;
2916
        if (value & OPT_SRESET)
2917
            md_reset(s);
2918
        md_interrupt_update(s);
2919
        break;
2920
    case 0x02:        /* Card Configuration Status Register */
2921
        if ((s->stat ^ value) & STAT_PWRDWN)
2922
            s->pins |= PINS_CRDY;
2923
        s->stat &= 0x82;
2924
        s->stat |= value & 0x74;
2925
        md_interrupt_update(s);
2926
        /* Word 170 in Identify Device must be equal to STAT_XE */
2927
        break;
2928
    case 0x04:        /* Pin Replacement Register */
2929
        s->pins &= PINS_CRDY;
2930
        s->pins |= value & PINS_MRDY;
2931
        break;
2932
    case 0x06:        /* Socket and Copy Register */
2933
        break;
2934
    default:
2935
        printf("%s: Bad attribute space register %02x\n", __FUNCTION__, at);
2936
    }
2937
}
2938

    
2939
static uint16_t md_common_read(void *opaque, uint32_t at)
2940
{
2941
    MicroDriveState *s = (MicroDriveState *) opaque;
2942
    IDEState *ifs;
2943
    uint16_t ret;
2944
    at -= s->io_base;
2945

    
2946
    switch (s->opt & OPT_MODE) {
2947
    case OPT_MODE_MMAP:
2948
        if ((at & ~0x3ff) == 0x400)
2949
            at = 0;
2950
        break;
2951
    case OPT_MODE_IOMAP16:
2952
        at &= 0xf;
2953
        break;
2954
    case OPT_MODE_IOMAP1:
2955
        if ((at & ~0xf) == 0x3f0)
2956
            at -= 0x3e8;
2957
        else if ((at & ~0xf) == 0x1f0)
2958
            at -= 0x1f0;
2959
        break;
2960
    case OPT_MODE_IOMAP2:
2961
        if ((at & ~0xf) == 0x370)
2962
            at -= 0x368;
2963
        else if ((at & ~0xf) == 0x170)
2964
            at -= 0x170;
2965
    }
2966

    
2967
    switch (at) {
2968
    case 0x0:        /* Even RD Data */
2969
    case 0x8:
2970
        return ide_data_readw(&s->bus, 0);
2971

    
2972
        /* TODO: 8-bit accesses */
2973
        if (s->cycle)
2974
            ret = s->io >> 8;
2975
        else {
2976
            s->io = ide_data_readw(&s->bus, 0);
2977
            ret = s->io & 0xff;
2978
        }
2979
        s->cycle = !s->cycle;
2980
        return ret;
2981
    case 0x9:        /* Odd RD Data */
2982
        return s->io >> 8;
2983
    case 0xd:        /* Error */
2984
        return ide_ioport_read(&s->bus, 0x1);
2985
    case 0xe:        /* Alternate Status */
2986
        ifs = idebus_active_if(&s->bus);
2987
        if (ifs->bs)
2988
            return ifs->status;
2989
        else
2990
            return 0;
2991
    case 0xf:        /* Device Address */
2992
        ifs = idebus_active_if(&s->bus);
2993
        return 0xc2 | ((~ifs->select << 2) & 0x3c);
2994
    default:
2995
        return ide_ioport_read(&s->bus, at);
2996
    }
2997

    
2998
    return 0;
2999
}
3000

    
3001
static void md_common_write(void *opaque, uint32_t at, uint16_t value)
3002
{
3003
    MicroDriveState *s = (MicroDriveState *) opaque;
3004
    at -= s->io_base;
3005

    
3006
    switch (s->opt & OPT_MODE) {
3007
    case OPT_MODE_MMAP:
3008
        if ((at & ~0x3ff) == 0x400)
3009
            at = 0;
3010
        break;
3011
    case OPT_MODE_IOMAP16:
3012
        at &= 0xf;
3013
        break;
3014
    case OPT_MODE_IOMAP1:
3015
        if ((at & ~0xf) == 0x3f0)
3016
            at -= 0x3e8;
3017
        else if ((at & ~0xf) == 0x1f0)
3018
            at -= 0x1f0;
3019
        break;
3020
    case OPT_MODE_IOMAP2:
3021
        if ((at & ~0xf) == 0x370)
3022
            at -= 0x368;
3023
        else if ((at & ~0xf) == 0x170)
3024
            at -= 0x170;
3025
    }
3026

    
3027
    switch (at) {
3028
    case 0x0:        /* Even WR Data */
3029
    case 0x8:
3030
        ide_data_writew(&s->bus, 0, value);
3031
        break;
3032

    
3033
        /* TODO: 8-bit accesses */
3034
        if (s->cycle)
3035
            ide_data_writew(&s->bus, 0, s->io | (value << 8));
3036
        else
3037
            s->io = value & 0xff;
3038
        s->cycle = !s->cycle;
3039
        break;
3040
    case 0x9:
3041
        s->io = value & 0xff;
3042
        s->cycle = !s->cycle;
3043
        break;
3044
    case 0xd:        /* Features */
3045
        ide_ioport_write(&s->bus, 0x1, value);
3046
        break;
3047
    case 0xe:        /* Device Control */
3048
        s->ctrl = value;
3049
        if (value & CTRL_SRST)
3050
            md_reset(s);
3051
        md_interrupt_update(s);
3052
        break;
3053
    default:
3054
        if (s->stat & STAT_PWRDWN) {
3055
            s->pins |= PINS_CRDY;
3056
            s->stat &= ~STAT_PWRDWN;
3057
        }
3058
        ide_ioport_write(&s->bus, at, value);
3059
    }
3060
}
3061

    
3062
static void md_save(QEMUFile *f, void *opaque)
3063
{
3064
    MicroDriveState *s = (MicroDriveState *) opaque;
3065
    int i;
3066

    
3067
    qemu_put_8s(f, &s->opt);
3068
    qemu_put_8s(f, &s->stat);
3069
    qemu_put_8s(f, &s->pins);
3070

    
3071
    qemu_put_8s(f, &s->ctrl);
3072
    qemu_put_be16s(f, &s->io);
3073
    qemu_put_byte(f, s->cycle);
3074

    
3075
    idebus_save(f, &s->bus);
3076

    
3077
    for (i = 0; i < 2; i ++)
3078
        ide_save(f, &s->bus.ifs[i]);
3079
}
3080

    
3081
static int md_load(QEMUFile *f, void *opaque, int version_id)
3082
{
3083
    MicroDriveState *s = (MicroDriveState *) opaque;
3084
    int i;
3085

    
3086
    if (version_id != 0 && version_id != 3)
3087
        return -EINVAL;
3088

    
3089
    qemu_get_8s(f, &s->opt);
3090
    qemu_get_8s(f, &s->stat);
3091
    qemu_get_8s(f, &s->pins);
3092

    
3093
    qemu_get_8s(f, &s->ctrl);
3094
    qemu_get_be16s(f, &s->io);
3095
    s->cycle = qemu_get_byte(f);
3096

    
3097
    idebus_load(f, &s->bus, version_id);
3098

    
3099
    for (i = 0; i < 2; i ++)
3100
        ide_load(f, &s->bus.ifs[i], version_id);
3101

    
3102
    return 0;
3103
}
3104

    
3105
static const uint8_t dscm1xxxx_cis[0x14a] = {
3106
    [0x000] = CISTPL_DEVICE,        /* 5V Device Information */
3107
    [0x002] = 0x03,                /* Tuple length = 4 bytes */
3108
    [0x004] = 0xdb,                /* ID: DTYPE_FUNCSPEC, non WP, DSPEED_150NS */
3109
    [0x006] = 0x01,                /* Size = 2K bytes */
3110
    [0x008] = CISTPL_ENDMARK,
3111

    
3112
    [0x00a] = CISTPL_DEVICE_OC,        /* Additional Device Information */
3113
    [0x00c] = 0x04,                /* Tuple length = 4 byest */
3114
    [0x00e] = 0x03,                /* Conditions: Ext = 0, Vcc 3.3V, MWAIT = 1 */
3115
    [0x010] = 0xdb,                /* ID: DTYPE_FUNCSPEC, non WP, DSPEED_150NS */
3116
    [0x012] = 0x01,                /* Size = 2K bytes */
3117
    [0x014] = CISTPL_ENDMARK,
3118

    
3119
    [0x016] = CISTPL_JEDEC_C,        /* JEDEC ID */
3120
    [0x018] = 0x02,                /* Tuple length = 2 bytes */
3121
    [0x01a] = 0xdf,                /* PC Card ATA with no Vpp required */
3122
    [0x01c] = 0x01,
3123

    
3124
    [0x01e] = CISTPL_MANFID,        /* Manufacture ID */
3125
    [0x020] = 0x04,                /* Tuple length = 4 bytes */
3126
    [0x022] = 0xa4,                /* TPLMID_MANF = 00a4 (IBM) */
3127
    [0x024] = 0x00,
3128
    [0x026] = 0x00,                /* PLMID_CARD = 0000 */
3129
    [0x028] = 0x00,
3130

    
3131
    [0x02a] = CISTPL_VERS_1,        /* Level 1 Version */
3132
    [0x02c] = 0x12,                /* Tuple length = 23 bytes */
3133
    [0x02e] = 0x04,                /* Major Version = JEIDA 4.2 / PCMCIA 2.1 */
3134
    [0x030] = 0x01,                /* Minor Version = 1 */
3135
    [0x032] = 'I',
3136
    [0x034] = 'B',
3137
    [0x036] = 'M',
3138
    [0x038] = 0x00,
3139
    [0x03a] = 'm',
3140
    [0x03c] = 'i',
3141
    [0x03e] = 'c',
3142
    [0x040] = 'r',
3143
    [0x042] = 'o',
3144
    [0x044] = 'd',
3145
    [0x046] = 'r',
3146
    [0x048] = 'i',
3147
    [0x04a] = 'v',
3148
    [0x04c] = 'e',
3149
    [0x04e] = 0x00,
3150
    [0x050] = CISTPL_ENDMARK,
3151

    
3152
    [0x052] = CISTPL_FUNCID,        /* Function ID */
3153
    [0x054] = 0x02,                /* Tuple length = 2 bytes */
3154
    [0x056] = 0x04,                /* TPLFID_FUNCTION = Fixed Disk */
3155
    [0x058] = 0x01,                /* TPLFID_SYSINIT: POST = 1, ROM = 0 */
3156

    
3157
    [0x05a] = CISTPL_FUNCE,        /* Function Extension */
3158
    [0x05c] = 0x02,                /* Tuple length = 2 bytes */
3159
    [0x05e] = 0x01,                /* TPLFE_TYPE = Disk Device Interface */
3160
    [0x060] = 0x01,                /* TPLFE_DATA = PC Card ATA Interface */
3161

    
3162
    [0x062] = CISTPL_FUNCE,        /* Function Extension */
3163
    [0x064] = 0x03,                /* Tuple length = 3 bytes */
3164
    [0x066] = 0x02,                /* TPLFE_TYPE = Basic PC Card ATA Interface */
3165
    [0x068] = 0x08,                /* TPLFE_DATA: Rotating, Unique, Single */
3166
    [0x06a] = 0x0f,                /* TPLFE_DATA: Sleep, Standby, Idle, Auto */
3167

    
3168
    [0x06c] = CISTPL_CONFIG,        /* Configuration */
3169
    [0x06e] = 0x05,                /* Tuple length = 5 bytes */
3170
    [0x070] = 0x01,                /* TPCC_RASZ = 2 bytes, TPCC_RMSZ = 1 byte */
3171
    [0x072] = 0x07,                /* TPCC_LAST = 7 */
3172
    [0x074] = 0x00,                /* TPCC_RADR = 0200 */
3173
    [0x076] = 0x02,
3174
    [0x078] = 0x0f,                /* TPCC_RMSK = 200, 202, 204, 206 */
3175

    
3176
    [0x07a] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3177
    [0x07c] = 0x0b,                /* Tuple length = 11 bytes */
3178
    [0x07e] = 0xc0,                /* TPCE_INDX = Memory Mode, Default, Iface */
3179
    [0x080] = 0xc0,                /* TPCE_IF = Memory, no BVDs, no WP, READY */
3180
    [0x082] = 0xa1,                /* TPCE_FS = Vcc only, no I/O, Memory, Misc */
3181
    [0x084] = 0x27,                /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
3182
    [0x086] = 0x55,                /* NomV: 5.0 V */
3183
    [0x088] = 0x4d,                /* MinV: 4.5 V */
3184
    [0x08a] = 0x5d,                /* MaxV: 5.5 V */
3185
    [0x08c] = 0x4e,                /* Peakl: 450 mA */
3186
    [0x08e] = 0x08,                /* TPCE_MS = 1 window, 1 byte, Host address */
3187
    [0x090] = 0x00,                /* Window descriptor: Window length = 0 */
3188
    [0x092] = 0x20,                /* TPCE_MI: support power down mode, RW */
3189

    
3190
    [0x094] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3191
    [0x096] = 0x06,                /* Tuple length = 6 bytes */
3192
    [0x098] = 0x00,                /* TPCE_INDX = Memory Mode, no Default */
3193
    [0x09a] = 0x01,                /* TPCE_FS = Vcc only, no I/O, no Memory */
3194
    [0x09c] = 0x21,                /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
3195
    [0x09e] = 0xb5,                /* NomV: 3.3 V */
3196
    [0x0a0] = 0x1e,
3197
    [0x0a2] = 0x3e,                /* Peakl: 350 mA */
3198

    
3199
    [0x0a4] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3200
    [0x0a6] = 0x0d,                /* Tuple length = 13 bytes */
3201
    [0x0a8] = 0xc1,                /* TPCE_INDX = I/O and Memory Mode, Default */
3202
    [0x0aa] = 0x41,                /* TPCE_IF = I/O and Memory, no BVD, no WP */
3203
    [0x0ac] = 0x99,                /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
3204
    [0x0ae] = 0x27,                /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
3205
    [0x0b0] = 0x55,                /* NomV: 5.0 V */
3206
    [0x0b2] = 0x4d,                /* MinV: 4.5 V */
3207
    [0x0b4] = 0x5d,                /* MaxV: 5.5 V */
3208
    [0x0b6] = 0x4e,                /* Peakl: 450 mA */
3209
    [0x0b8] = 0x64,                /* TPCE_IO = 16-byte boundary, 16/8 accesses */
3210
    [0x0ba] = 0xf0,                /* TPCE_IR =  MASK, Level, Pulse, Share */
3211
    [0x0bc] = 0xff,                /* IRQ0..IRQ7 supported */
3212
    [0x0be] = 0xff,                /* IRQ8..IRQ15 supported */
3213
    [0x0c0] = 0x20,                /* TPCE_MI = support power down mode */
3214

    
3215
    [0x0c2] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3216
    [0x0c4] = 0x06,                /* Tuple length = 6 bytes */
3217
    [0x0c6] = 0x01,                /* TPCE_INDX = I/O and Memory Mode */
3218
    [0x0c8] = 0x01,                /* TPCE_FS = Vcc only, no I/O, no Memory */
3219
    [0x0ca] = 0x21,                /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
3220
    [0x0cc] = 0xb5,                /* NomV: 3.3 V */
3221
    [0x0ce] = 0x1e,
3222
    [0x0d0] = 0x3e,                /* Peakl: 350 mA */
3223

    
3224
    [0x0d2] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3225
    [0x0d4] = 0x12,                /* Tuple length = 18 bytes */
3226
    [0x0d6] = 0xc2,                /* TPCE_INDX = I/O Primary Mode */
3227
    [0x0d8] = 0x41,                /* TPCE_IF = I/O and Memory, no BVD, no WP */
3228
    [0x0da] = 0x99,                /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
3229
    [0x0dc] = 0x27,                /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
3230
    [0x0de] = 0x55,                /* NomV: 5.0 V */
3231
    [0x0e0] = 0x4d,                /* MinV: 4.5 V */
3232
    [0x0e2] = 0x5d,                /* MaxV: 5.5 V */
3233
    [0x0e4] = 0x4e,                /* Peakl: 450 mA */
3234
    [0x0e6] = 0xea,                /* TPCE_IO = 1K boundary, 16/8 access, Range */
3235
    [0x0e8] = 0x61,                /* Range: 2 fields, 2 bytes addr, 1 byte len */
3236
    [0x0ea] = 0xf0,                /* Field 1 address = 0x01f0 */
3237
    [0x0ec] = 0x01,
3238
    [0x0ee] = 0x07,                /* Address block length = 8 */
3239
    [0x0f0] = 0xf6,                /* Field 2 address = 0x03f6 */
3240
    [0x0f2] = 0x03,
3241
    [0x0f4] = 0x01,                /* Address block length = 2 */
3242
    [0x0f6] = 0xee,                /* TPCE_IR = IRQ E, Level, Pulse, Share */
3243
    [0x0f8] = 0x20,                /* TPCE_MI = support power down mode */
3244

    
3245
    [0x0fa] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3246
    [0x0fc] = 0x06,                /* Tuple length = 6 bytes */
3247
    [0x0fe] = 0x02,                /* TPCE_INDX = I/O Primary Mode, no Default */
3248
    [0x100] = 0x01,                /* TPCE_FS = Vcc only, no I/O, no Memory */
3249
    [0x102] = 0x21,                /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
3250
    [0x104] = 0xb5,                /* NomV: 3.3 V */
3251
    [0x106] = 0x1e,
3252
    [0x108] = 0x3e,                /* Peakl: 350 mA */
3253

    
3254
    [0x10a] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3255
    [0x10c] = 0x12,                /* Tuple length = 18 bytes */
3256
    [0x10e] = 0xc3,                /* TPCE_INDX = I/O Secondary Mode, Default */
3257
    [0x110] = 0x41,                /* TPCE_IF = I/O and Memory, no BVD, no WP */
3258
    [0x112] = 0x99,                /* TPCE_FS = Vcc only, I/O, Interrupt, Misc */
3259
    [0x114] = 0x27,                /* NomV = 1, MinV = 1, MaxV = 1, Peakl = 1 */
3260
    [0x116] = 0x55,                /* NomV: 5.0 V */
3261
    [0x118] = 0x4d,                /* MinV: 4.5 V */
3262
    [0x11a] = 0x5d,                /* MaxV: 5.5 V */
3263
    [0x11c] = 0x4e,                /* Peakl: 450 mA */
3264
    [0x11e] = 0xea,                /* TPCE_IO = 1K boundary, 16/8 access, Range */
3265
    [0x120] = 0x61,                /* Range: 2 fields, 2 byte addr, 1 byte len */
3266
    [0x122] = 0x70,                /* Field 1 address = 0x0170 */
3267
    [0x124] = 0x01,
3268
    [0x126] = 0x07,                /* Address block length = 8 */
3269
    [0x128] = 0x76,                /* Field 2 address = 0x0376 */
3270
    [0x12a] = 0x03,
3271
    [0x12c] = 0x01,                /* Address block length = 2 */
3272
    [0x12e] = 0xee,                /* TPCE_IR = IRQ E, Level, Pulse, Share */
3273
    [0x130] = 0x20,                /* TPCE_MI = support power down mode */
3274

    
3275
    [0x132] = CISTPL_CFTABLE_ENTRY,        /* 16-bit PC Card Configuration */
3276
    [0x134] = 0x06,                /* Tuple length = 6 bytes */
3277
    [0x136] = 0x03,                /* TPCE_INDX = I/O Secondary Mode */
3278
    [0x138] = 0x01,                /* TPCE_FS = Vcc only, no I/O, no Memory */
3279
    [0x13a] = 0x21,                /* NomV = 1, MinV = 0, MaxV = 0, Peakl = 1 */
3280
    [0x13c] = 0xb5,                /* NomV: 3.3 V */
3281
    [0x13e] = 0x1e,
3282
    [0x140] = 0x3e,                /* Peakl: 350 mA */
3283

    
3284
    [0x142] = CISTPL_NO_LINK,        /* No Link */
3285
    [0x144] = 0x00,                /* Tuple length = 0 bytes */
3286

    
3287
    [0x146] = CISTPL_END,        /* Tuple End */
3288
};
3289

    
3290
static int dscm1xxxx_attach(void *opaque)
3291
{
3292
    MicroDriveState *md = (MicroDriveState *) opaque;
3293
    md->card.attr_read = md_attr_read;
3294
    md->card.attr_write = md_attr_write;
3295
    md->card.common_read = md_common_read;
3296
    md->card.common_write = md_common_write;
3297
    md->card.io_read = md_common_read;
3298
    md->card.io_write = md_common_write;
3299

    
3300
    md->attr_base = md->card.cis[0x74] | (md->card.cis[0x76] << 8);
3301
    md->io_base = 0x0;
3302

    
3303
    md_reset(md);
3304
    md_interrupt_update(md);
3305

    
3306
    md->card.slot->card_string = "DSCM-1xxxx Hitachi Microdrive";
3307
    return 0;
3308
}
3309

    
3310
static int dscm1xxxx_detach(void *opaque)
3311
{
3312
    MicroDriveState *md = (MicroDriveState *) opaque;
3313
    md_reset(md);
3314
    return 0;
3315
}
3316

    
3317
PCMCIACardState *dscm1xxxx_init(BlockDriverState *bdrv)
3318
{
3319
    MicroDriveState *md = (MicroDriveState *) qemu_mallocz(sizeof(MicroDriveState));
3320
    md->card.state = md;
3321
    md->card.attach = dscm1xxxx_attach;
3322
    md->card.detach = dscm1xxxx_detach;
3323
    md->card.cis = dscm1xxxx_cis;
3324
    md->card.cis_len = sizeof(dscm1xxxx_cis);
3325

    
3326
    ide_init2(&md->bus, bdrv, NULL, qemu_allocate_irqs(md_set_irq, md, 1)[0]);
3327
    md->bus.ifs[0].is_cf = 1;
3328
    md->bus.ifs[0].mdata_size = METADATA_SIZE;
3329
    md->bus.ifs[0].mdata_storage = (uint8_t *) qemu_mallocz(METADATA_SIZE);
3330

    
3331
    register_savevm("microdrive", -1, 3, md_save, md_load, md);
3332

    
3333
    return &md->card;
3334
}