Statistics
| Branch: | Revision:

root / hw / ide / core.c @ 4a91d3b3

History | View | Annotate | Download (65.2 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/hw.h>
26
#include <hw/pc.h>
27
#include <hw/pci.h>
28
#include <hw/isa.h>
29
#include "qemu-error.h"
30
#include "qemu-timer.h"
31
#include "sysemu.h"
32
#include "dma.h"
33
#include "blockdev.h"
34
#include "block_int.h"
35

    
36
#include <hw/ide/internal.h>
37

    
38
/* These values were based on a Seagate ST3500418AS but have been modified
39
   to make more sense in QEMU */
40
static const int smart_attributes[][12] = {
41
    /* id,  flags, hflags, val, wrst, raw (6 bytes), threshold */
42
    /* raw read error rate*/
43
    { 0x01, 0x03, 0x00, 0x64, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06},
44
    /* spin up */
45
    { 0x03, 0x03, 0x00, 0x64, 0x64, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
46
    /* start stop count */
47
    { 0x04, 0x02, 0x00, 0x64, 0x64, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14},
48
    /* remapped sectors */
49
    { 0x05, 0x03, 0x00, 0x64, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24},
50
    /* power on hours */
51
    { 0x09, 0x03, 0x00, 0x64, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
52
    /* power cycle count */
53
    { 0x0c, 0x03, 0x00, 0x64, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
54
    /* airflow-temperature-celsius */
55
    { 190,  0x03, 0x00, 0x45, 0x45, 0x1f, 0x00, 0x1f, 0x1f, 0x00, 0x00, 0x32},
56
    /* end of list */
57
    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
58
};
59

    
60
static int ide_handle_rw_error(IDEState *s, int error, int op);
61
static void ide_dummy_transfer_stop(IDEState *s);
62

    
63
static void padstr(char *str, const char *src, int len)
64
{
65
    int i, v;
66
    for(i = 0; i < len; i++) {
67
        if (*src)
68
            v = *src++;
69
        else
70
            v = ' ';
71
        str[i^1] = v;
72
    }
73
}
74

    
75
static void put_le16(uint16_t *p, unsigned int v)
76
{
77
    *p = cpu_to_le16(v);
78
}
79

    
80
static void ide_identify(IDEState *s)
81
{
82
    uint16_t *p;
83
    unsigned int oldsize;
84
    IDEDevice *dev = s->unit ? s->bus->slave : s->bus->master;
85

    
86
    if (s->identify_set) {
87
        memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
88
        return;
89
    }
90

    
91
    memset(s->io_buffer, 0, 512);
92
    p = (uint16_t *)s->io_buffer;
93
    put_le16(p + 0, 0x0040);
94
    put_le16(p + 1, s->cylinders);
95
    put_le16(p + 3, s->heads);
96
    put_le16(p + 4, 512 * s->sectors); /* XXX: retired, remove ? */
97
    put_le16(p + 5, 512); /* XXX: retired, remove ? */
98
    put_le16(p + 6, s->sectors);
99
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
100
    put_le16(p + 20, 3); /* XXX: retired, remove ? */
101
    put_le16(p + 21, 512); /* cache size in sectors */
102
    put_le16(p + 22, 4); /* ecc bytes */
103
    padstr((char *)(p + 23), s->version, 8); /* firmware version */
104
    padstr((char *)(p + 27), "QEMU HARDDISK", 40); /* model */
105
#if MAX_MULT_SECTORS > 1
106
    put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
107
#endif
108
    put_le16(p + 48, 1); /* dword I/O */
109
    put_le16(p + 49, (1 << 11) | (1 << 9) | (1 << 8)); /* DMA and LBA supported */
110
    put_le16(p + 51, 0x200); /* PIO transfer cycle */
111
    put_le16(p + 52, 0x200); /* DMA transfer cycle */
112
    put_le16(p + 53, 1 | (1 << 1) | (1 << 2)); /* words 54-58,64-70,88 are valid */
113
    put_le16(p + 54, s->cylinders);
114
    put_le16(p + 55, s->heads);
115
    put_le16(p + 56, s->sectors);
116
    oldsize = s->cylinders * s->heads * s->sectors;
117
    put_le16(p + 57, oldsize);
118
    put_le16(p + 58, oldsize >> 16);
119
    if (s->mult_sectors)
120
        put_le16(p + 59, 0x100 | s->mult_sectors);
121
    put_le16(p + 60, s->nb_sectors);
122
    put_le16(p + 61, s->nb_sectors >> 16);
123
    put_le16(p + 62, 0x07); /* single word dma0-2 supported */
124
    put_le16(p + 63, 0x07); /* mdma0-2 supported */
125
    put_le16(p + 64, 0x03); /* pio3-4 supported */
126
    put_le16(p + 65, 120);
127
    put_le16(p + 66, 120);
128
    put_le16(p + 67, 120);
129
    put_le16(p + 68, 120);
130
    if (dev && dev->conf.discard_granularity) {
131
        put_le16(p + 69, (1 << 14)); /* determinate TRIM behavior */
132
    }
133

    
134
    if (s->ncq_queues) {
135
        put_le16(p + 75, s->ncq_queues - 1);
136
        /* NCQ supported */
137
        put_le16(p + 76, (1 << 8));
138
    }
139

    
140
    put_le16(p + 80, 0xf0); /* ata3 -> ata6 supported */
141
    put_le16(p + 81, 0x16); /* conforms to ata5 */
142
    /* 14=NOP supported, 5=WCACHE supported, 0=SMART supported */
143
    put_le16(p + 82, (1 << 14) | (1 << 5) | 1);
144
    /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
145
    put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
146
    /* 14=set to 1, 1=SMART self test, 0=SMART error logging */
147
    put_le16(p + 84, (1 << 14) | 0);
148
    /* 14 = NOP supported, 5=WCACHE enabled, 0=SMART feature set enabled */
149
    if (bdrv_enable_write_cache(s->bs))
150
         put_le16(p + 85, (1 << 14) | (1 << 5) | 1);
151
    else
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
    if (dev && dev->conf.physical_block_size)
165
        put_le16(p + 106, 0x6000 | get_physical_block_exp(&dev->conf));
166
    if (dev && dev->conf.discard_granularity) {
167
        put_le16(p + 169, 1); /* TRIM support */
168
    }
169

    
170
    memcpy(s->identify_data, p, sizeof(s->identify_data));
171
    s->identify_set = 1;
172
}
173

    
174
static void ide_atapi_identify(IDEState *s)
175
{
176
    uint16_t *p;
177

    
178
    if (s->identify_set) {
179
        memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));
180
        return;
181
    }
182

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

    
210
    put_le16(p + 71, 30); /* in ns */
211
    put_le16(p + 72, 30); /* in ns */
212

    
213
    if (s->ncq_queues) {
214
        put_le16(p + 75, s->ncq_queues - 1);
215
        /* NCQ supported */
216
        put_le16(p + 76, (1 << 8));
217
    }
218

    
219
    put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
220
#ifdef USE_DMA_CDROM
221
    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
222
#endif
223
    memcpy(s->identify_data, p, sizeof(s->identify_data));
224
    s->identify_set = 1;
225
}
226

    
227
static void ide_cfata_identify(IDEState *s)
228
{
229
    uint16_t *p;
230
    uint32_t cur_sec;
231

    
232
    p = (uint16_t *) s->identify_data;
233
    if (s->identify_set)
234
        goto fill_buffer;
235

    
236
    memset(p, 0, sizeof(s->identify_data));
237

    
238
    cur_sec = s->cylinders * s->heads * s->sectors;
239

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

    
287
    s->identify_set = 1;
288

    
289
fill_buffer:
290
    memcpy(s->io_buffer, p, sizeof(s->identify_data));
291
}
292

    
293
static void ide_set_signature(IDEState *s)
294
{
295
    s->select &= 0xf0; /* clear head */
296
    /* put signature */
297
    s->nsector = 1;
298
    s->sector = 1;
299
    if (s->drive_kind == IDE_CD) {
300
        s->lcyl = 0x14;
301
        s->hcyl = 0xeb;
302
    } else if (s->bs) {
303
        s->lcyl = 0;
304
        s->hcyl = 0;
305
    } else {
306
        s->lcyl = 0xff;
307
        s->hcyl = 0xff;
308
    }
309
}
310

    
311
typedef struct TrimAIOCB {
312
    BlockDriverAIOCB common;
313
    QEMUBH *bh;
314
    int ret;
315
} TrimAIOCB;
316

    
317
static void trim_aio_cancel(BlockDriverAIOCB *acb)
318
{
319
    TrimAIOCB *iocb = container_of(acb, TrimAIOCB, common);
320

    
321
    qemu_bh_delete(iocb->bh);
322
    iocb->bh = NULL;
323
    qemu_aio_release(iocb);
324
}
325

    
326
static AIOPool trim_aio_pool = {
327
    .aiocb_size         = sizeof(TrimAIOCB),
328
    .cancel             = trim_aio_cancel,
329
};
330

    
331
static void ide_trim_bh_cb(void *opaque)
332
{
333
    TrimAIOCB *iocb = opaque;
334

    
335
    iocb->common.cb(iocb->common.opaque, iocb->ret);
336

    
337
    qemu_bh_delete(iocb->bh);
338
    iocb->bh = NULL;
339

    
340
    qemu_aio_release(iocb);
341
}
342

    
343
BlockDriverAIOCB *ide_issue_trim(BlockDriverState *bs,
344
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
345
        BlockDriverCompletionFunc *cb, void *opaque)
346
{
347
    TrimAIOCB *iocb;
348
    int i, j, ret;
349

    
350
    iocb = qemu_aio_get(&trim_aio_pool, bs, cb, opaque);
351
    iocb->bh = qemu_bh_new(ide_trim_bh_cb, iocb);
352
    iocb->ret = 0;
353

    
354
    for (j = 0; j < qiov->niov; j++) {
355
        uint64_t *buffer = qiov->iov[j].iov_base;
356

    
357
        for (i = 0; i < qiov->iov[j].iov_len / 8; i++) {
358
            /* 6-byte LBA + 2-byte range per entry */
359
            uint64_t entry = le64_to_cpu(buffer[i]);
360
            uint64_t sector = entry & 0x0000ffffffffffffULL;
361
            uint16_t count = entry >> 48;
362

    
363
            if (count == 0) {
364
                break;
365
            }
366

    
367
            ret = bdrv_discard(bs, sector, count);
368
            if (!iocb->ret) {
369
                iocb->ret = ret;
370
            }
371
        }
372
    }
373

    
374
    qemu_bh_schedule(iocb->bh);
375

    
376
    return &iocb->common;
377
}
378

    
379
static inline void ide_abort_command(IDEState *s)
380
{
381
    s->status = READY_STAT | ERR_STAT;
382
    s->error = ABRT_ERR;
383
}
384

    
385
/* prepare data transfer and tell what to do after */
386
void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
387
                        EndTransferFunc *end_transfer_func)
388
{
389
    s->end_transfer_func = end_transfer_func;
390
    s->data_ptr = buf;
391
    s->data_end = buf + size;
392
    if (!(s->status & ERR_STAT)) {
393
        s->status |= DRQ_STAT;
394
    }
395
    s->bus->dma->ops->start_transfer(s->bus->dma);
396
}
397

    
398
void ide_transfer_stop(IDEState *s)
399
{
400
    s->end_transfer_func = ide_transfer_stop;
401
    s->data_ptr = s->io_buffer;
402
    s->data_end = s->io_buffer;
403
    s->status &= ~DRQ_STAT;
404
}
405

    
406
int64_t ide_get_sector(IDEState *s)
407
{
408
    int64_t sector_num;
409
    if (s->select & 0x40) {
410
        /* lba */
411
        if (!s->lba48) {
412
            sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
413
                (s->lcyl << 8) | s->sector;
414
        } else {
415
            sector_num = ((int64_t)s->hob_hcyl << 40) |
416
                ((int64_t) s->hob_lcyl << 32) |
417
                ((int64_t) s->hob_sector << 24) |
418
                ((int64_t) s->hcyl << 16) |
419
                ((int64_t) s->lcyl << 8) | s->sector;
420
        }
421
    } else {
422
        sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
423
            (s->select & 0x0f) * s->sectors + (s->sector - 1);
424
    }
425
    return sector_num;
426
}
427

    
428
void ide_set_sector(IDEState *s, int64_t sector_num)
429
{
430
    unsigned int cyl, r;
431
    if (s->select & 0x40) {
432
        if (!s->lba48) {
433
            s->select = (s->select & 0xf0) | (sector_num >> 24);
434
            s->hcyl = (sector_num >> 16);
435
            s->lcyl = (sector_num >> 8);
436
            s->sector = (sector_num);
437
        } else {
438
            s->sector = sector_num;
439
            s->lcyl = sector_num >> 8;
440
            s->hcyl = sector_num >> 16;
441
            s->hob_sector = sector_num >> 24;
442
            s->hob_lcyl = sector_num >> 32;
443
            s->hob_hcyl = sector_num >> 40;
444
        }
445
    } else {
446
        cyl = sector_num / (s->heads * s->sectors);
447
        r = sector_num % (s->heads * s->sectors);
448
        s->hcyl = cyl >> 8;
449
        s->lcyl = cyl;
450
        s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);
451
        s->sector = (r % s->sectors) + 1;
452
    }
453
}
454

    
455
static void ide_rw_error(IDEState *s) {
456
    ide_abort_command(s);
457
    ide_set_irq(s->bus);
458
}
459

    
460
void ide_sector_read(IDEState *s)
461
{
462
    int64_t sector_num;
463
    int ret, n;
464

    
465
    s->status = READY_STAT | SEEK_STAT;
466
    s->error = 0; /* not needed by IDE spec, but needed by Windows */
467
    sector_num = ide_get_sector(s);
468
    n = s->nsector;
469
    if (n == 0) {
470
        /* no more sector to read from disk */
471
        ide_transfer_stop(s);
472
    } else {
473
#if defined(DEBUG_IDE)
474
        printf("read sector=%" PRId64 "\n", sector_num);
475
#endif
476
        if (n > s->req_nb_sectors)
477
            n = s->req_nb_sectors;
478

    
479
        bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
480
        ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
481
        bdrv_acct_done(s->bs, &s->acct);
482
        if (ret != 0) {
483
            if (ide_handle_rw_error(s, -ret,
484
                BM_STATUS_PIO_RETRY | BM_STATUS_RETRY_READ))
485
            {
486
                return;
487
            }
488
        }
489
        ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);
490
        ide_set_irq(s->bus);
491
        ide_set_sector(s, sector_num + n);
492
        s->nsector -= n;
493
    }
494
}
495

    
496
static void dma_buf_commit(IDEState *s, int is_write)
497
{
498
    qemu_sglist_destroy(&s->sg);
499
}
500

    
501
void ide_set_inactive(IDEState *s)
502
{
503
    s->bus->dma->aiocb = NULL;
504
    s->bus->dma->ops->set_inactive(s->bus->dma);
505
}
506

    
507
void ide_dma_error(IDEState *s)
508
{
509
    ide_transfer_stop(s);
510
    s->error = ABRT_ERR;
511
    s->status = READY_STAT | ERR_STAT;
512
    ide_set_inactive(s);
513
    ide_set_irq(s->bus);
514
}
515

    
516
static int ide_handle_rw_error(IDEState *s, int error, int op)
517
{
518
    int is_read = (op & BM_STATUS_RETRY_READ);
519
    BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);
520

    
521
    if (action == BLOCK_ERR_IGNORE) {
522
        bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);
523
        return 0;
524
    }
525

    
526
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
527
            || action == BLOCK_ERR_STOP_ANY) {
528
        s->bus->dma->ops->set_unit(s->bus->dma, s->unit);
529
        s->bus->error_status = op;
530
        bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);
531
        vm_stop(RSTATE_IO_ERROR);
532
    } else {
533
        if (op & BM_STATUS_DMA_RETRY) {
534
            dma_buf_commit(s, 0);
535
            ide_dma_error(s);
536
        } else {
537
            ide_rw_error(s);
538
        }
539
        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
540
    }
541

    
542
    return 1;
543
}
544

    
545
void ide_dma_cb(void *opaque, int ret)
546
{
547
    IDEState *s = opaque;
548
    int n;
549
    int64_t sector_num;
550

    
551
handle_rw_error:
552
    if (ret < 0) {
553
        int op = BM_STATUS_DMA_RETRY;
554

    
555
        if (s->dma_cmd == IDE_DMA_READ)
556
            op |= BM_STATUS_RETRY_READ;
557
        else if (s->dma_cmd == IDE_DMA_TRIM)
558
            op |= BM_STATUS_RETRY_TRIM;
559

    
560
        if (ide_handle_rw_error(s, -ret, op)) {
561
            return;
562
        }
563
    }
564

    
565
    n = s->io_buffer_size >> 9;
566
    sector_num = ide_get_sector(s);
567
    if (n > 0) {
568
        dma_buf_commit(s, ide_cmd_is_read(s));
569
        sector_num += n;
570
        ide_set_sector(s, sector_num);
571
        s->nsector -= n;
572
    }
573

    
574
    /* end of transfer ? */
575
    if (s->nsector == 0) {
576
        s->status = READY_STAT | SEEK_STAT;
577
        ide_set_irq(s->bus);
578
        goto eot;
579
    }
580

    
581
    /* launch next transfer */
582
    n = s->nsector;
583
    s->io_buffer_index = 0;
584
    s->io_buffer_size = n * 512;
585
    if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {
586
        /* The PRDs were too short. Reset the Active bit, but don't raise an
587
         * interrupt. */
588
        goto eot;
589
    }
590

    
591
#ifdef DEBUG_AIO
592
    printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",
593
           sector_num, n, s->dma_cmd);
594
#endif
595

    
596
    switch (s->dma_cmd) {
597
    case IDE_DMA_READ:
598
        s->bus->dma->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,
599
                                           ide_dma_cb, s);
600
        break;
601
    case IDE_DMA_WRITE:
602
        s->bus->dma->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,
603
                                            ide_dma_cb, s);
604
        break;
605
    case IDE_DMA_TRIM:
606
        s->bus->dma->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,
607
                                         ide_issue_trim, ide_dma_cb, s, true);
608
        break;
609
    }
610

    
611
    if (!s->bus->dma->aiocb) {
612
        ret = -1;
613
        goto handle_rw_error;
614
    }
615
    return;
616

    
617
eot:
618
    if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
619
        bdrv_acct_done(s->bs, &s->acct);
620
    }
621
    ide_set_inactive(s);
622
}
623

    
624
static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd)
625
{
626
    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
627
    s->io_buffer_index = 0;
628
    s->io_buffer_size = 0;
629
    s->dma_cmd = dma_cmd;
630

    
631
    switch (dma_cmd) {
632
    case IDE_DMA_READ:
633
        bdrv_acct_start(s->bs, &s->acct, s->nsector * BDRV_SECTOR_SIZE,
634
                        BDRV_ACCT_READ);
635
        break;
636
    case IDE_DMA_WRITE:
637
        bdrv_acct_start(s->bs, &s->acct, s->nsector * BDRV_SECTOR_SIZE,
638
                        BDRV_ACCT_WRITE);
639
        break;
640
    default:
641
        break;
642
    }
643

    
644
    s->bus->dma->ops->start_dma(s->bus->dma, s, ide_dma_cb);
645
}
646

    
647
static void ide_sector_write_timer_cb(void *opaque)
648
{
649
    IDEState *s = opaque;
650
    ide_set_irq(s->bus);
651
}
652

    
653
void ide_sector_write(IDEState *s)
654
{
655
    int64_t sector_num;
656
    int ret, n, n1;
657

    
658
    s->status = READY_STAT | SEEK_STAT;
659
    sector_num = ide_get_sector(s);
660
#if defined(DEBUG_IDE)
661
    printf("write sector=%" PRId64 "\n", sector_num);
662
#endif
663
    n = s->nsector;
664
    if (n > s->req_nb_sectors)
665
        n = s->req_nb_sectors;
666

    
667
    bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
668
    ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
669
    bdrv_acct_done(s->bs, &s->acct);
670

    
671
    if (ret != 0) {
672
        if (ide_handle_rw_error(s, -ret, BM_STATUS_PIO_RETRY))
673
            return;
674
    }
675

    
676
    s->nsector -= n;
677
    if (s->nsector == 0) {
678
        /* no more sectors to write */
679
        ide_transfer_stop(s);
680
    } else {
681
        n1 = s->nsector;
682
        if (n1 > s->req_nb_sectors)
683
            n1 = s->req_nb_sectors;
684
        ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write);
685
    }
686
    ide_set_sector(s, sector_num + n);
687

    
688
    if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {
689
        /* It seems there is a bug in the Windows 2000 installer HDD
690
           IDE driver which fills the disk with empty logs when the
691
           IDE write IRQ comes too early. This hack tries to correct
692
           that at the expense of slower write performances. Use this
693
           option _only_ to install Windows 2000. You must disable it
694
           for normal use. */
695
        qemu_mod_timer(s->sector_write_timer,
696
                       qemu_get_clock_ns(vm_clock) + (get_ticks_per_sec() / 1000));
697
    } else {
698
        ide_set_irq(s->bus);
699
    }
700
}
701

    
702
static void ide_flush_cb(void *opaque, int ret)
703
{
704
    IDEState *s = opaque;
705

    
706
    if (ret < 0) {
707
        /* XXX: What sector number to set here? */
708
        if (ide_handle_rw_error(s, -ret, BM_STATUS_RETRY_FLUSH)) {
709
            return;
710
        }
711
    }
712

    
713
    bdrv_acct_done(s->bs, &s->acct);
714
    s->status = READY_STAT | SEEK_STAT;
715
    ide_set_irq(s->bus);
716
}
717

    
718
void ide_flush_cache(IDEState *s)
719
{
720
    BlockDriverAIOCB *acb;
721

    
722
    if (s->bs == NULL) {
723
        ide_flush_cb(s, 0);
724
        return;
725
    }
726

    
727
    bdrv_acct_start(s->bs, &s->acct, 0, BDRV_ACCT_FLUSH);
728
    acb = bdrv_aio_flush(s->bs, ide_flush_cb, s);
729
    if (acb == NULL) {
730
        ide_flush_cb(s, -EIO);
731
    }
732
}
733

    
734
static void ide_cfata_metadata_inquiry(IDEState *s)
735
{
736
    uint16_t *p;
737
    uint32_t spd;
738

    
739
    p = (uint16_t *) s->io_buffer;
740
    memset(p, 0, 0x200);
741
    spd = ((s->mdata_size - 1) >> 9) + 1;
742

    
743
    put_le16(p + 0, 0x0001);                        /* Data format revision */
744
    put_le16(p + 1, 0x0000);                        /* Media property: silicon */
745
    put_le16(p + 2, s->media_changed);                /* Media status */
746
    put_le16(p + 3, s->mdata_size & 0xffff);        /* Capacity in bytes (low) */
747
    put_le16(p + 4, s->mdata_size >> 16);        /* Capacity in bytes (high) */
748
    put_le16(p + 5, spd & 0xffff);                /* Sectors per device (low) */
749
    put_le16(p + 6, spd >> 16);                        /* Sectors per device (high) */
750
}
751

    
752
static void ide_cfata_metadata_read(IDEState *s)
753
{
754
    uint16_t *p;
755

    
756
    if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
757
        s->status = ERR_STAT;
758
        s->error = ABRT_ERR;
759
        return;
760
    }
761

    
762
    p = (uint16_t *) s->io_buffer;
763
    memset(p, 0, 0x200);
764

    
765
    put_le16(p + 0, s->media_changed);                /* Media status */
766
    memcpy(p + 1, s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
767
                    MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
768
                                    s->nsector << 9), 0x200 - 2));
769
}
770

    
771
static void ide_cfata_metadata_write(IDEState *s)
772
{
773
    if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
774
        s->status = ERR_STAT;
775
        s->error = ABRT_ERR;
776
        return;
777
    }
778

    
779
    s->media_changed = 0;
780

    
781
    memcpy(s->mdata_storage + (((s->hcyl << 16) | s->lcyl) << 9),
782
                    s->io_buffer + 2,
783
                    MIN(MIN(s->mdata_size - (((s->hcyl << 16) | s->lcyl) << 9),
784
                                    s->nsector << 9), 0x200 - 2));
785
}
786

    
787
/* called when the inserted state of the media has changed */
788
static void ide_cd_change_cb(void *opaque, bool load)
789
{
790
    IDEState *s = opaque;
791
    uint64_t nb_sectors;
792

    
793
    s->tray_open = !load;
794
    bdrv_get_geometry(s->bs, &nb_sectors);
795
    s->nb_sectors = nb_sectors;
796

    
797
    /*
798
     * First indicate to the guest that a CD has been removed.  That's
799
     * done on the next command the guest sends us.
800
     *
801
     * Then we set SENSE_UNIT_ATTENTION, by which the guest will
802
     * detect a new CD in the drive.  See ide_atapi_cmd() for details.
803
     */
804
    s->cdrom_changed = 1;
805
    s->events.new_media = true;
806
    ide_set_irq(s->bus);
807
}
808

    
809
static void ide_cmd_lba48_transform(IDEState *s, int lba48)
810
{
811
    s->lba48 = lba48;
812

    
813
    /* handle the 'magic' 0 nsector count conversion here. to avoid
814
     * fiddling with the rest of the read logic, we just store the
815
     * full sector count in ->nsector and ignore ->hob_nsector from now
816
     */
817
    if (!s->lba48) {
818
        if (!s->nsector)
819
            s->nsector = 256;
820
    } else {
821
        if (!s->nsector && !s->hob_nsector)
822
            s->nsector = 65536;
823
        else {
824
            int lo = s->nsector;
825
            int hi = s->hob_nsector;
826

    
827
            s->nsector = (hi << 8) | lo;
828
        }
829
    }
830
}
831

    
832
static void ide_clear_hob(IDEBus *bus)
833
{
834
    /* any write clears HOB high bit of device control register */
835
    bus->ifs[0].select &= ~(1 << 7);
836
    bus->ifs[1].select &= ~(1 << 7);
837
}
838

    
839
void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
840
{
841
    IDEBus *bus = opaque;
842

    
843
#ifdef DEBUG_IDE
844
    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
845
#endif
846

    
847
    addr &= 7;
848

    
849
    /* ignore writes to command block while busy with previous command */
850
    if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
851
        return;
852

    
853
    switch(addr) {
854
    case 0:
855
        break;
856
    case 1:
857
        ide_clear_hob(bus);
858
        /* NOTE: data is written to the two drives */
859
        bus->ifs[0].hob_feature = bus->ifs[0].feature;
860
        bus->ifs[1].hob_feature = bus->ifs[1].feature;
861
        bus->ifs[0].feature = val;
862
        bus->ifs[1].feature = val;
863
        break;
864
    case 2:
865
        ide_clear_hob(bus);
866
        bus->ifs[0].hob_nsector = bus->ifs[0].nsector;
867
        bus->ifs[1].hob_nsector = bus->ifs[1].nsector;
868
        bus->ifs[0].nsector = val;
869
        bus->ifs[1].nsector = val;
870
        break;
871
    case 3:
872
        ide_clear_hob(bus);
873
        bus->ifs[0].hob_sector = bus->ifs[0].sector;
874
        bus->ifs[1].hob_sector = bus->ifs[1].sector;
875
        bus->ifs[0].sector = val;
876
        bus->ifs[1].sector = val;
877
        break;
878
    case 4:
879
        ide_clear_hob(bus);
880
        bus->ifs[0].hob_lcyl = bus->ifs[0].lcyl;
881
        bus->ifs[1].hob_lcyl = bus->ifs[1].lcyl;
882
        bus->ifs[0].lcyl = val;
883
        bus->ifs[1].lcyl = val;
884
        break;
885
    case 5:
886
        ide_clear_hob(bus);
887
        bus->ifs[0].hob_hcyl = bus->ifs[0].hcyl;
888
        bus->ifs[1].hob_hcyl = bus->ifs[1].hcyl;
889
        bus->ifs[0].hcyl = val;
890
        bus->ifs[1].hcyl = val;
891
        break;
892
    case 6:
893
        /* FIXME: HOB readback uses bit 7 */
894
        bus->ifs[0].select = (val & ~0x10) | 0xa0;
895
        bus->ifs[1].select = (val | 0x10) | 0xa0;
896
        /* select drive */
897
        bus->unit = (val >> 4) & 1;
898
        break;
899
    default:
900
    case 7:
901
        /* command */
902
        ide_exec_cmd(bus, val);
903
        break;
904
    }
905
}
906

    
907
#define HD_OK (1u << IDE_HD)
908
#define CD_OK (1u << IDE_CD)
909
#define CFA_OK (1u << IDE_CFATA)
910
#define HD_CFA_OK (HD_OK | CFA_OK)
911
#define ALL_OK (HD_OK | CD_OK | CFA_OK)
912

    
913
/* See ACS-2 T13/2015-D Table B.2 Command codes */
914
static const uint8_t ide_cmd_table[0x100] = {
915
    /* NOP not implemented, mandatory for CD */
916
    [CFA_REQ_EXT_ERROR_CODE]            = CFA_OK,
917
    [WIN_DSM]                           = ALL_OK,
918
    [WIN_DEVICE_RESET]                  = CD_OK,
919
    [WIN_RECAL]                         = HD_CFA_OK,
920
    [WIN_READ]                          = ALL_OK,
921
    [WIN_READ_ONCE]                     = ALL_OK,
922
    [WIN_READ_EXT]                      = HD_CFA_OK,
923
    [WIN_READDMA_EXT]                   = HD_CFA_OK,
924
    [WIN_READ_NATIVE_MAX_EXT]           = HD_CFA_OK,
925
    [WIN_MULTREAD_EXT]                  = HD_CFA_OK,
926
    [WIN_WRITE]                         = HD_CFA_OK,
927
    [WIN_WRITE_ONCE]                    = HD_CFA_OK,
928
    [WIN_WRITE_EXT]                     = HD_CFA_OK,
929
    [WIN_WRITEDMA_EXT]                  = HD_CFA_OK,
930
    [CFA_WRITE_SECT_WO_ERASE]           = CFA_OK,
931
    [WIN_MULTWRITE_EXT]                 = HD_CFA_OK,
932
    [WIN_WRITE_VERIFY]                  = HD_CFA_OK,
933
    [WIN_VERIFY]                        = HD_CFA_OK,
934
    [WIN_VERIFY_ONCE]                   = HD_CFA_OK,
935
    [WIN_VERIFY_EXT]                    = HD_CFA_OK,
936
    [WIN_SEEK]                          = HD_CFA_OK,
937
    [CFA_TRANSLATE_SECTOR]              = CFA_OK,
938
    [WIN_DIAGNOSE]                      = ALL_OK,
939
    [WIN_SPECIFY]                       = HD_CFA_OK,
940
    [WIN_STANDBYNOW2]                   = ALL_OK,
941
    [WIN_IDLEIMMEDIATE2]                = ALL_OK,
942
    [WIN_STANDBY2]                      = ALL_OK,
943
    [WIN_SETIDLE2]                      = ALL_OK,
944
    [WIN_CHECKPOWERMODE2]               = ALL_OK,
945
    [WIN_SLEEPNOW2]                     = ALL_OK,
946
    [WIN_PACKETCMD]                     = CD_OK,
947
    [WIN_PIDENTIFY]                     = CD_OK,
948
    [WIN_SMART]                         = HD_CFA_OK,
949
    [CFA_ACCESS_METADATA_STORAGE]       = CFA_OK,
950
    [CFA_ERASE_SECTORS]                 = CFA_OK,
951
    [WIN_MULTREAD]                      = HD_CFA_OK,
952
    [WIN_MULTWRITE]                     = HD_CFA_OK,
953
    [WIN_SETMULT]                       = HD_CFA_OK,
954
    [WIN_READDMA]                       = HD_CFA_OK,
955
    [WIN_READDMA_ONCE]                  = HD_CFA_OK,
956
    [WIN_WRITEDMA]                      = HD_CFA_OK,
957
    [WIN_WRITEDMA_ONCE]                 = HD_CFA_OK,
958
    [CFA_WRITE_MULTI_WO_ERASE]          = CFA_OK,
959
    [WIN_STANDBYNOW1]                   = ALL_OK,
960
    [WIN_IDLEIMMEDIATE]                 = ALL_OK,
961
    [WIN_STANDBY]                       = ALL_OK,
962
    [WIN_SETIDLE1]                      = ALL_OK,
963
    [WIN_CHECKPOWERMODE1]               = ALL_OK,
964
    [WIN_SLEEPNOW1]                     = ALL_OK,
965
    [WIN_FLUSH_CACHE]                   = ALL_OK,
966
    [WIN_FLUSH_CACHE_EXT]               = HD_CFA_OK,
967
    [WIN_IDENTIFY]                      = ALL_OK,
968
    [WIN_SETFEATURES]                   = ALL_OK,
969
    [IBM_SENSE_CONDITION]               = CFA_OK,
970
    [CFA_WEAR_LEVEL]                    = CFA_OK,
971
    [WIN_READ_NATIVE_MAX]               = ALL_OK,
972
};
973

    
974
static bool ide_cmd_permitted(IDEState *s, uint32_t cmd)
975
{
976
    return cmd < ARRAY_SIZE(ide_cmd_table)
977
        && (ide_cmd_table[cmd] & (1u << s->drive_kind));
978
}
979

    
980
void ide_exec_cmd(IDEBus *bus, uint32_t val)
981
{
982
    IDEState *s;
983
    int n;
984
    int lba48 = 0;
985

    
986
#if defined(DEBUG_IDE)
987
    printf("ide: CMD=%02x\n", val);
988
#endif
989
    s = idebus_active_if(bus);
990
    /* ignore commands to non existant slave */
991
    if (s != bus->ifs && !s->bs)
992
        return;
993

    
994
    /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */
995
    if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)
996
        return;
997

    
998
    if (!ide_cmd_permitted(s, val)) {
999
        goto abort_cmd;
1000
    }
1001

    
1002
    switch(val) {
1003
    case WIN_DSM:
1004
        switch (s->feature) {
1005
        case DSM_TRIM:
1006
            if (!s->bs) {
1007
                goto abort_cmd;
1008
            }
1009
            ide_sector_start_dma(s, IDE_DMA_TRIM);
1010
            break;
1011
        default:
1012
            goto abort_cmd;
1013
        }
1014
        break;
1015
    case WIN_IDENTIFY:
1016
        if (s->bs && s->drive_kind != IDE_CD) {
1017
            if (s->drive_kind != IDE_CFATA)
1018
                ide_identify(s);
1019
            else
1020
                ide_cfata_identify(s);
1021
            s->status = READY_STAT | SEEK_STAT;
1022
            ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
1023
        } else {
1024
            if (s->drive_kind == IDE_CD) {
1025
                ide_set_signature(s);
1026
            }
1027
            ide_abort_command(s);
1028
        }
1029
        ide_set_irq(s->bus);
1030
        break;
1031
    case WIN_SPECIFY:
1032
    case WIN_RECAL:
1033
        s->error = 0;
1034
        s->status = READY_STAT | SEEK_STAT;
1035
        ide_set_irq(s->bus);
1036
        break;
1037
    case WIN_SETMULT:
1038
        if (s->drive_kind == IDE_CFATA && s->nsector == 0) {
1039
            /* Disable Read and Write Multiple */
1040
            s->mult_sectors = 0;
1041
            s->status = READY_STAT | SEEK_STAT;
1042
        } else if ((s->nsector & 0xff) != 0 &&
1043
            ((s->nsector & 0xff) > MAX_MULT_SECTORS ||
1044
             (s->nsector & (s->nsector - 1)) != 0)) {
1045
            ide_abort_command(s);
1046
        } else {
1047
            s->mult_sectors = s->nsector & 0xff;
1048
            s->status = READY_STAT | SEEK_STAT;
1049
        }
1050
        ide_set_irq(s->bus);
1051
        break;
1052
    case WIN_VERIFY_EXT:
1053
        lba48 = 1;
1054
    case WIN_VERIFY:
1055
    case WIN_VERIFY_ONCE:
1056
        /* do sector number check ? */
1057
        ide_cmd_lba48_transform(s, lba48);
1058
        s->status = READY_STAT | SEEK_STAT;
1059
        ide_set_irq(s->bus);
1060
        break;
1061
    case WIN_READ_EXT:
1062
        lba48 = 1;
1063
    case WIN_READ:
1064
    case WIN_READ_ONCE:
1065
        if (s->drive_kind == IDE_CD) {
1066
            ide_set_signature(s); /* odd, but ATA4 8.27.5.2 requires it */
1067
            goto abort_cmd;
1068
        }
1069
        ide_cmd_lba48_transform(s, lba48);
1070
        s->req_nb_sectors = 1;
1071
        ide_sector_read(s);
1072
        break;
1073
    case WIN_WRITE_EXT:
1074
        lba48 = 1;
1075
    case WIN_WRITE:
1076
    case WIN_WRITE_ONCE:
1077
    case CFA_WRITE_SECT_WO_ERASE:
1078
    case WIN_WRITE_VERIFY:
1079
        ide_cmd_lba48_transform(s, lba48);
1080
        s->error = 0;
1081
        s->status = SEEK_STAT | READY_STAT;
1082
        s->req_nb_sectors = 1;
1083
        ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);
1084
        s->media_changed = 1;
1085
        break;
1086
    case WIN_MULTREAD_EXT:
1087
        lba48 = 1;
1088
    case WIN_MULTREAD:
1089
        if (!s->mult_sectors)
1090
            goto abort_cmd;
1091
        ide_cmd_lba48_transform(s, lba48);
1092
        s->req_nb_sectors = s->mult_sectors;
1093
        ide_sector_read(s);
1094
        break;
1095
    case WIN_MULTWRITE_EXT:
1096
        lba48 = 1;
1097
    case WIN_MULTWRITE:
1098
    case CFA_WRITE_MULTI_WO_ERASE:
1099
        if (!s->mult_sectors)
1100
            goto abort_cmd;
1101
        ide_cmd_lba48_transform(s, lba48);
1102
        s->error = 0;
1103
        s->status = SEEK_STAT | READY_STAT;
1104
        s->req_nb_sectors = s->mult_sectors;
1105
        n = s->nsector;
1106
        if (n > s->req_nb_sectors)
1107
            n = s->req_nb_sectors;
1108
        ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);
1109
        s->media_changed = 1;
1110
        break;
1111
    case WIN_READDMA_EXT:
1112
        lba48 = 1;
1113
    case WIN_READDMA:
1114
    case WIN_READDMA_ONCE:
1115
        if (!s->bs)
1116
            goto abort_cmd;
1117
        ide_cmd_lba48_transform(s, lba48);
1118
        ide_sector_start_dma(s, IDE_DMA_READ);
1119
        break;
1120
    case WIN_WRITEDMA_EXT:
1121
        lba48 = 1;
1122
    case WIN_WRITEDMA:
1123
    case WIN_WRITEDMA_ONCE:
1124
        if (!s->bs)
1125
            goto abort_cmd;
1126
        ide_cmd_lba48_transform(s, lba48);
1127
        ide_sector_start_dma(s, IDE_DMA_WRITE);
1128
        s->media_changed = 1;
1129
        break;
1130
    case WIN_READ_NATIVE_MAX_EXT:
1131
        lba48 = 1;
1132
    case WIN_READ_NATIVE_MAX:
1133
        ide_cmd_lba48_transform(s, lba48);
1134
        ide_set_sector(s, s->nb_sectors - 1);
1135
        s->status = READY_STAT | SEEK_STAT;
1136
        ide_set_irq(s->bus);
1137
        break;
1138
    case WIN_CHECKPOWERMODE1:
1139
    case WIN_CHECKPOWERMODE2:
1140
        s->error = 0;
1141
        s->nsector = 0xff; /* device active or idle */
1142
        s->status = READY_STAT | SEEK_STAT;
1143
        ide_set_irq(s->bus);
1144
        break;
1145
    case WIN_SETFEATURES:
1146
        if (!s->bs)
1147
            goto abort_cmd;
1148
        /* XXX: valid for CDROM ? */
1149
        switch(s->feature) {
1150
        case 0xcc: /* reverting to power-on defaults enable */
1151
        case 0x66: /* reverting to power-on defaults disable */
1152
        case 0x02: /* write cache enable */
1153
        case 0x82: /* write cache disable */
1154
        case 0xaa: /* read look-ahead enable */
1155
        case 0x55: /* read look-ahead disable */
1156
        case 0x05: /* set advanced power management mode */
1157
        case 0x85: /* disable advanced power management mode */
1158
        case 0x69: /* NOP */
1159
        case 0x67: /* NOP */
1160
        case 0x96: /* NOP */
1161
        case 0x9a: /* NOP */
1162
        case 0x42: /* enable Automatic Acoustic Mode */
1163
        case 0xc2: /* disable Automatic Acoustic Mode */
1164
            s->status = READY_STAT | SEEK_STAT;
1165
            ide_set_irq(s->bus);
1166
            break;
1167
        case 0x03: { /* set transfer mode */
1168
                uint8_t val = s->nsector & 0x07;
1169
            uint16_t *identify_data = (uint16_t *)s->identify_data;
1170

    
1171
                switch (s->nsector >> 3) {
1172
                case 0x00: /* pio default */
1173
                case 0x01: /* pio mode */
1174
                        put_le16(identify_data + 62,0x07);
1175
                        put_le16(identify_data + 63,0x07);
1176
                        put_le16(identify_data + 88,0x3f);
1177
                        break;
1178
                case 0x02: /* sigle word dma mode*/
1179
                        put_le16(identify_data + 62,0x07 | (1 << (val + 8)));
1180
                        put_le16(identify_data + 63,0x07);
1181
                        put_le16(identify_data + 88,0x3f);
1182
                        break;
1183
                case 0x04: /* mdma mode */
1184
                        put_le16(identify_data + 62,0x07);
1185
                        put_le16(identify_data + 63,0x07 | (1 << (val + 8)));
1186
                        put_le16(identify_data + 88,0x3f);
1187
                        break;
1188
                case 0x08: /* udma mode */
1189
                        put_le16(identify_data + 62,0x07);
1190
                        put_le16(identify_data + 63,0x07);
1191
                        put_le16(identify_data + 88,0x3f | (1 << (val + 8)));
1192
                        break;
1193
                default:
1194
                        goto abort_cmd;
1195
                }
1196
            s->status = READY_STAT | SEEK_STAT;
1197
            ide_set_irq(s->bus);
1198
            break;
1199
        }
1200
        default:
1201
            goto abort_cmd;
1202
        }
1203
        break;
1204
    case WIN_FLUSH_CACHE:
1205
    case WIN_FLUSH_CACHE_EXT:
1206
        ide_flush_cache(s);
1207
        break;
1208
    case WIN_STANDBY:
1209
    case WIN_STANDBY2:
1210
    case WIN_STANDBYNOW1:
1211
    case WIN_STANDBYNOW2:
1212
    case WIN_IDLEIMMEDIATE:
1213
    case WIN_IDLEIMMEDIATE2:
1214
    case WIN_SETIDLE1:
1215
    case WIN_SETIDLE2:
1216
    case WIN_SLEEPNOW1:
1217
    case WIN_SLEEPNOW2:
1218
        s->status = READY_STAT;
1219
        ide_set_irq(s->bus);
1220
        break;
1221
    case WIN_SEEK:
1222
        /* XXX: Check that seek is within bounds */
1223
        s->status = READY_STAT | SEEK_STAT;
1224
        ide_set_irq(s->bus);
1225
        break;
1226
        /* ATAPI commands */
1227
    case WIN_PIDENTIFY:
1228
        ide_atapi_identify(s);
1229
        s->status = READY_STAT | SEEK_STAT;
1230
        ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
1231
        ide_set_irq(s->bus);
1232
        break;
1233
    case WIN_DIAGNOSE:
1234
        ide_set_signature(s);
1235
        if (s->drive_kind == IDE_CD)
1236
            s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet
1237
                            * devices to return a clear status register
1238
                            * with READY_STAT *not* set. */
1239
        else
1240
            s->status = READY_STAT | SEEK_STAT;
1241
        s->error = 0x01; /* Device 0 passed, Device 1 passed or not
1242
                          * present.
1243
                          */
1244
        ide_set_irq(s->bus);
1245
        break;
1246
    case WIN_DEVICE_RESET:
1247
        ide_set_signature(s);
1248
        s->status = 0x00; /* NOTE: READY is _not_ set */
1249
        s->error = 0x01;
1250
        break;
1251
    case WIN_PACKETCMD:
1252
        /* overlapping commands not supported */
1253
        if (s->feature & 0x02)
1254
            goto abort_cmd;
1255
        s->status = READY_STAT | SEEK_STAT;
1256
        s->atapi_dma = s->feature & 1;
1257
        s->nsector = 1;
1258
        ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
1259
                           ide_atapi_cmd);
1260
        break;
1261
    /* CF-ATA commands */
1262
    case CFA_REQ_EXT_ERROR_CODE:
1263
        s->error = 0x09;    /* miscellaneous error */
1264
        s->status = READY_STAT | SEEK_STAT;
1265
        ide_set_irq(s->bus);
1266
        break;
1267
    case CFA_ERASE_SECTORS:
1268
    case CFA_WEAR_LEVEL:
1269
        if (val == CFA_WEAR_LEVEL)
1270
            s->nsector = 0;
1271
        if (val == CFA_ERASE_SECTORS)
1272
            s->media_changed = 1;
1273
        s->error = 0x00;
1274
        s->status = READY_STAT | SEEK_STAT;
1275
        ide_set_irq(s->bus);
1276
        break;
1277
    case CFA_TRANSLATE_SECTOR:
1278
        s->error = 0x00;
1279
        s->status = READY_STAT | SEEK_STAT;
1280
        memset(s->io_buffer, 0, 0x200);
1281
        s->io_buffer[0x00] = s->hcyl;                        /* Cyl MSB */
1282
        s->io_buffer[0x01] = s->lcyl;                        /* Cyl LSB */
1283
        s->io_buffer[0x02] = s->select;                        /* Head */
1284
        s->io_buffer[0x03] = s->sector;                        /* Sector */
1285
        s->io_buffer[0x04] = ide_get_sector(s) >> 16;        /* LBA MSB */
1286
        s->io_buffer[0x05] = ide_get_sector(s) >> 8;        /* LBA */
1287
        s->io_buffer[0x06] = ide_get_sector(s) >> 0;        /* LBA LSB */
1288
        s->io_buffer[0x13] = 0x00;                                /* Erase flag */
1289
        s->io_buffer[0x18] = 0x00;                                /* Hot count */
1290
        s->io_buffer[0x19] = 0x00;                                /* Hot count */
1291
        s->io_buffer[0x1a] = 0x01;                                /* Hot count */
1292
        ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1293
        ide_set_irq(s->bus);
1294
        break;
1295
    case CFA_ACCESS_METADATA_STORAGE:
1296
        switch (s->feature) {
1297
        case 0x02:        /* Inquiry Metadata Storage */
1298
            ide_cfata_metadata_inquiry(s);
1299
            break;
1300
        case 0x03:        /* Read Metadata Storage */
1301
            ide_cfata_metadata_read(s);
1302
            break;
1303
        case 0x04:        /* Write Metadata Storage */
1304
            ide_cfata_metadata_write(s);
1305
            break;
1306
        default:
1307
            goto abort_cmd;
1308
        }
1309
        ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1310
        s->status = 0x00; /* NOTE: READY is _not_ set */
1311
        ide_set_irq(s->bus);
1312
        break;
1313
    case IBM_SENSE_CONDITION:
1314
        switch (s->feature) {
1315
        case 0x01:  /* sense temperature in device */
1316
            s->nsector = 0x50;      /* +20 C */
1317
            break;
1318
        default:
1319
            goto abort_cmd;
1320
        }
1321
        s->status = READY_STAT | SEEK_STAT;
1322
        ide_set_irq(s->bus);
1323
        break;
1324

    
1325
    case WIN_SMART:
1326
        if (s->hcyl != 0xc2 || s->lcyl != 0x4f)
1327
                goto abort_cmd;
1328
        if (!s->smart_enabled && s->feature != SMART_ENABLE)
1329
                goto abort_cmd;
1330
        switch (s->feature) {
1331
        case SMART_DISABLE:
1332
                s->smart_enabled = 0;
1333
                s->status = READY_STAT | SEEK_STAT;
1334
                ide_set_irq(s->bus);
1335
                break;
1336
        case SMART_ENABLE:
1337
                s->smart_enabled = 1;
1338
                s->status = READY_STAT | SEEK_STAT;
1339
                ide_set_irq(s->bus);
1340
                break;
1341
        case SMART_ATTR_AUTOSAVE:
1342
                switch (s->sector) {
1343
                case 0x00:
1344
                s->smart_autosave = 0;
1345
                break;
1346
                case 0xf1:
1347
                s->smart_autosave = 1;
1348
                break;
1349
                default:
1350
                goto abort_cmd;
1351
                }
1352
                s->status = READY_STAT | SEEK_STAT;
1353
                ide_set_irq(s->bus);
1354
                break;
1355
        case SMART_STATUS:
1356
                if (!s->smart_errors) {
1357
                s->hcyl = 0xc2;
1358
                s->lcyl = 0x4f;
1359
                } else {
1360
                s->hcyl = 0x2c;
1361
                s->lcyl = 0xf4;
1362
                }
1363
                s->status = READY_STAT | SEEK_STAT;
1364
                ide_set_irq(s->bus);
1365
                break;
1366
        case SMART_READ_THRESH:
1367
                memset(s->io_buffer, 0, 0x200);
1368
                s->io_buffer[0] = 0x01; /* smart struct version */
1369
                for (n=0; n<30; n++) {
1370
                if (smart_attributes[n][0] == 0)
1371
                        break;
1372
                s->io_buffer[2+0+(n*12)] = smart_attributes[n][0];
1373
                s->io_buffer[2+1+(n*12)] = smart_attributes[n][11];
1374
                }
1375
                for (n=0; n<511; n++) /* checksum */
1376
                s->io_buffer[511] += s->io_buffer[n];
1377
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
1378
                s->status = READY_STAT | SEEK_STAT;
1379
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1380
                ide_set_irq(s->bus);
1381
                break;
1382
        case SMART_READ_DATA:
1383
                memset(s->io_buffer, 0, 0x200);
1384
                s->io_buffer[0] = 0x01; /* smart struct version */
1385
                for (n=0; n<30; n++) {
1386
                    if (smart_attributes[n][0] == 0) {
1387
                        break;
1388
                    }
1389
                    int i;
1390
                    for(i = 0; i < 11; i++) {
1391
                        s->io_buffer[2+i+(n*12)] = smart_attributes[n][i];
1392
                    }
1393
                }
1394
                s->io_buffer[362] = 0x02 | (s->smart_autosave?0x80:0x00);
1395
                if (s->smart_selftest_count == 0) {
1396
                s->io_buffer[363] = 0;
1397
                } else {
1398
                s->io_buffer[363] =
1399
                        s->smart_selftest_data[3 + 
1400
                                           (s->smart_selftest_count - 1) *
1401
                                           24];
1402
                }
1403
                s->io_buffer[364] = 0x20; 
1404
                s->io_buffer[365] = 0x01; 
1405
                /* offline data collection capacity: execute + self-test*/
1406
                s->io_buffer[367] = (1<<4 | 1<<3 | 1); 
1407
                s->io_buffer[368] = 0x03; /* smart capability (1) */
1408
                s->io_buffer[369] = 0x00; /* smart capability (2) */
1409
                s->io_buffer[370] = 0x01; /* error logging supported */
1410
                s->io_buffer[372] = 0x02; /* minutes for poll short test */
1411
                s->io_buffer[373] = 0x36; /* minutes for poll ext test */
1412
                s->io_buffer[374] = 0x01; /* minutes for poll conveyance */
1413

    
1414
                for (n=0; n<511; n++) 
1415
                s->io_buffer[511] += s->io_buffer[n];
1416
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
1417
                s->status = READY_STAT | SEEK_STAT;
1418
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1419
                ide_set_irq(s->bus);
1420
                break;
1421
        case SMART_READ_LOG:
1422
                switch (s->sector) {
1423
                case 0x01: /* summary smart error log */
1424
                memset(s->io_buffer, 0, 0x200);
1425
                s->io_buffer[0] = 0x01;
1426
                s->io_buffer[1] = 0x00; /* no error entries */
1427
                s->io_buffer[452] = s->smart_errors & 0xff;
1428
                s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;
1429

    
1430
                for (n=0; n<511; n++)
1431
                        s->io_buffer[511] += s->io_buffer[n];
1432
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
1433
                break;
1434
                case 0x06: /* smart self test log */
1435
                memset(s->io_buffer, 0, 0x200);
1436
                s->io_buffer[0] = 0x01;
1437
                if (s->smart_selftest_count == 0) {
1438
                        s->io_buffer[508] = 0;
1439
                } else {
1440
                        s->io_buffer[508] = s->smart_selftest_count;
1441
                        for (n=2; n<506; n++) 
1442
                        s->io_buffer[n] = s->smart_selftest_data[n];
1443
                }
1444
                for (n=0; n<511; n++)
1445
                        s->io_buffer[511] += s->io_buffer[n];
1446
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
1447
                break;
1448
                default:
1449
                goto abort_cmd;
1450
                }
1451
                s->status = READY_STAT | SEEK_STAT;
1452
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1453
                ide_set_irq(s->bus);
1454
                break;
1455
        case SMART_EXECUTE_OFFLINE:
1456
                switch (s->sector) {
1457
                case 0: /* off-line routine */
1458
                case 1: /* short self test */
1459
                case 2: /* extended self test */
1460
                s->smart_selftest_count++;
1461
                if(s->smart_selftest_count > 21)
1462
                        s->smart_selftest_count = 0;
1463
                n = 2 + (s->smart_selftest_count - 1) * 24;
1464
                s->smart_selftest_data[n] = s->sector;
1465
                s->smart_selftest_data[n+1] = 0x00; /* OK and finished */
1466
                s->smart_selftest_data[n+2] = 0x34; /* hour count lsb */
1467
                s->smart_selftest_data[n+3] = 0x12; /* hour count msb */
1468
                s->status = READY_STAT | SEEK_STAT;
1469
                ide_set_irq(s->bus);
1470
                break;
1471
                default:
1472
                goto abort_cmd;
1473
                }
1474
                break;
1475
        default:
1476
                goto abort_cmd;
1477
        }
1478
        break;
1479
    default:
1480
        /* should not be reachable */
1481
    abort_cmd:
1482
        ide_abort_command(s);
1483
        ide_set_irq(s->bus);
1484
        break;
1485
    }
1486
}
1487

    
1488
uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
1489
{
1490
    IDEBus *bus = opaque;
1491
    IDEState *s = idebus_active_if(bus);
1492
    uint32_t addr;
1493
    int ret, hob;
1494

    
1495
    addr = addr1 & 7;
1496
    /* FIXME: HOB readback uses bit 7, but it's always set right now */
1497
    //hob = s->select & (1 << 7);
1498
    hob = 0;
1499
    switch(addr) {
1500
    case 0:
1501
        ret = 0xff;
1502
        break;
1503
    case 1:
1504
        if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
1505
            (s != bus->ifs && !s->bs))
1506
            ret = 0;
1507
        else if (!hob)
1508
            ret = s->error;
1509
        else
1510
            ret = s->hob_feature;
1511
        break;
1512
    case 2:
1513
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
1514
            ret = 0;
1515
        else if (!hob)
1516
            ret = s->nsector & 0xff;
1517
        else
1518
            ret = s->hob_nsector;
1519
        break;
1520
    case 3:
1521
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
1522
            ret = 0;
1523
        else if (!hob)
1524
            ret = s->sector;
1525
        else
1526
            ret = s->hob_sector;
1527
        break;
1528
    case 4:
1529
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
1530
            ret = 0;
1531
        else if (!hob)
1532
            ret = s->lcyl;
1533
        else
1534
            ret = s->hob_lcyl;
1535
        break;
1536
    case 5:
1537
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
1538
            ret = 0;
1539
        else if (!hob)
1540
            ret = s->hcyl;
1541
        else
1542
            ret = s->hob_hcyl;
1543
        break;
1544
    case 6:
1545
        if (!bus->ifs[0].bs && !bus->ifs[1].bs)
1546
            ret = 0;
1547
        else
1548
            ret = s->select;
1549
        break;
1550
    default:
1551
    case 7:
1552
        if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
1553
            (s != bus->ifs && !s->bs))
1554
            ret = 0;
1555
        else
1556
            ret = s->status;
1557
        qemu_irq_lower(bus->irq);
1558
        break;
1559
    }
1560
#ifdef DEBUG_IDE
1561
    printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
1562
#endif
1563
    return ret;
1564
}
1565

    
1566
uint32_t ide_status_read(void *opaque, uint32_t addr)
1567
{
1568
    IDEBus *bus = opaque;
1569
    IDEState *s = idebus_active_if(bus);
1570
    int ret;
1571

    
1572
    if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
1573
        (s != bus->ifs && !s->bs))
1574
        ret = 0;
1575
    else
1576
        ret = s->status;
1577
#ifdef DEBUG_IDE
1578
    printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
1579
#endif
1580
    return ret;
1581
}
1582

    
1583
void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
1584
{
1585
    IDEBus *bus = opaque;
1586
    IDEState *s;
1587
    int i;
1588

    
1589
#ifdef DEBUG_IDE
1590
    printf("ide: write control addr=0x%x val=%02x\n", addr, val);
1591
#endif
1592
    /* common for both drives */
1593
    if (!(bus->cmd & IDE_CMD_RESET) &&
1594
        (val & IDE_CMD_RESET)) {
1595
        /* reset low to high */
1596
        for(i = 0;i < 2; i++) {
1597
            s = &bus->ifs[i];
1598
            s->status = BUSY_STAT | SEEK_STAT;
1599
            s->error = 0x01;
1600
        }
1601
    } else if ((bus->cmd & IDE_CMD_RESET) &&
1602
               !(val & IDE_CMD_RESET)) {
1603
        /* high to low */
1604
        for(i = 0;i < 2; i++) {
1605
            s = &bus->ifs[i];
1606
            if (s->drive_kind == IDE_CD)
1607
                s->status = 0x00; /* NOTE: READY is _not_ set */
1608
            else
1609
                s->status = READY_STAT | SEEK_STAT;
1610
            ide_set_signature(s);
1611
        }
1612
    }
1613

    
1614
    bus->cmd = val;
1615
}
1616

    
1617
/*
1618
 * Returns true if the running PIO transfer is a PIO out (i.e. data is
1619
 * transferred from the device to the guest), false if it's a PIO in
1620
 */
1621
static bool ide_is_pio_out(IDEState *s)
1622
{
1623
    if (s->end_transfer_func == ide_sector_write ||
1624
        s->end_transfer_func == ide_atapi_cmd) {
1625
        return false;
1626
    } else if (s->end_transfer_func == ide_sector_read ||
1627
               s->end_transfer_func == ide_transfer_stop ||
1628
               s->end_transfer_func == ide_atapi_cmd_reply_end ||
1629
               s->end_transfer_func == ide_dummy_transfer_stop) {
1630
        return true;
1631
    }
1632

    
1633
    abort();
1634
}
1635

    
1636
void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
1637
{
1638
    IDEBus *bus = opaque;
1639
    IDEState *s = idebus_active_if(bus);
1640
    uint8_t *p;
1641

    
1642
    /* PIO data access allowed only when DRQ bit is set. The result of a write
1643
     * during PIO out is indeterminate, just ignore it. */
1644
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
1645
        return;
1646
    }
1647

    
1648
    p = s->data_ptr;
1649
    *(uint16_t *)p = le16_to_cpu(val);
1650
    p += 2;
1651
    s->data_ptr = p;
1652
    if (p >= s->data_end)
1653
        s->end_transfer_func(s);
1654
}
1655

    
1656
uint32_t ide_data_readw(void *opaque, uint32_t addr)
1657
{
1658
    IDEBus *bus = opaque;
1659
    IDEState *s = idebus_active_if(bus);
1660
    uint8_t *p;
1661
    int ret;
1662

    
1663
    /* PIO data access allowed only when DRQ bit is set. The result of a read
1664
     * during PIO in is indeterminate, return 0 and don't move forward. */
1665
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
1666
        return 0;
1667
    }
1668

    
1669
    p = s->data_ptr;
1670
    ret = cpu_to_le16(*(uint16_t *)p);
1671
    p += 2;
1672
    s->data_ptr = p;
1673
    if (p >= s->data_end)
1674
        s->end_transfer_func(s);
1675
    return ret;
1676
}
1677

    
1678
void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
1679
{
1680
    IDEBus *bus = opaque;
1681
    IDEState *s = idebus_active_if(bus);
1682
    uint8_t *p;
1683

    
1684
    /* PIO data access allowed only when DRQ bit is set. The result of a write
1685
     * during PIO out is indeterminate, just ignore it. */
1686
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
1687
        return;
1688
    }
1689

    
1690
    p = s->data_ptr;
1691
    *(uint32_t *)p = le32_to_cpu(val);
1692
    p += 4;
1693
    s->data_ptr = p;
1694
    if (p >= s->data_end)
1695
        s->end_transfer_func(s);
1696
}
1697

    
1698
uint32_t ide_data_readl(void *opaque, uint32_t addr)
1699
{
1700
    IDEBus *bus = opaque;
1701
    IDEState *s = idebus_active_if(bus);
1702
    uint8_t *p;
1703
    int ret;
1704

    
1705
    /* PIO data access allowed only when DRQ bit is set. The result of a read
1706
     * during PIO in is indeterminate, return 0 and don't move forward. */
1707
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
1708
        return 0;
1709
    }
1710

    
1711
    p = s->data_ptr;
1712
    ret = cpu_to_le32(*(uint32_t *)p);
1713
    p += 4;
1714
    s->data_ptr = p;
1715
    if (p >= s->data_end)
1716
        s->end_transfer_func(s);
1717
    return ret;
1718
}
1719

    
1720
static void ide_dummy_transfer_stop(IDEState *s)
1721
{
1722
    s->data_ptr = s->io_buffer;
1723
    s->data_end = s->io_buffer;
1724
    s->io_buffer[0] = 0xff;
1725
    s->io_buffer[1] = 0xff;
1726
    s->io_buffer[2] = 0xff;
1727
    s->io_buffer[3] = 0xff;
1728
}
1729

    
1730
static void ide_reset(IDEState *s)
1731
{
1732
#ifdef DEBUG_IDE
1733
    printf("ide: reset\n");
1734
#endif
1735
    if (s->drive_kind == IDE_CFATA)
1736
        s->mult_sectors = 0;
1737
    else
1738
        s->mult_sectors = MAX_MULT_SECTORS;
1739
    /* ide regs */
1740
    s->feature = 0;
1741
    s->error = 0;
1742
    s->nsector = 0;
1743
    s->sector = 0;
1744
    s->lcyl = 0;
1745
    s->hcyl = 0;
1746

    
1747
    /* lba48 */
1748
    s->hob_feature = 0;
1749
    s->hob_sector = 0;
1750
    s->hob_nsector = 0;
1751
    s->hob_lcyl = 0;
1752
    s->hob_hcyl = 0;
1753

    
1754
    s->select = 0xa0;
1755
    s->status = READY_STAT | SEEK_STAT;
1756

    
1757
    s->lba48 = 0;
1758

    
1759
    /* ATAPI specific */
1760
    s->sense_key = 0;
1761
    s->asc = 0;
1762
    s->cdrom_changed = 0;
1763
    s->packet_transfer_size = 0;
1764
    s->elementary_transfer_size = 0;
1765
    s->io_buffer_index = 0;
1766
    s->cd_sector_size = 0;
1767
    s->atapi_dma = 0;
1768
    /* ATA DMA state */
1769
    s->io_buffer_size = 0;
1770
    s->req_nb_sectors = 0;
1771

    
1772
    ide_set_signature(s);
1773
    /* init the transfer handler so that 0xffff is returned on data
1774
       accesses */
1775
    s->end_transfer_func = ide_dummy_transfer_stop;
1776
    ide_dummy_transfer_stop(s);
1777
    s->media_changed = 0;
1778
}
1779

    
1780
void ide_bus_reset(IDEBus *bus)
1781
{
1782
    bus->unit = 0;
1783
    bus->cmd = 0;
1784
    ide_reset(&bus->ifs[0]);
1785
    ide_reset(&bus->ifs[1]);
1786
    ide_clear_hob(bus);
1787

    
1788
    /* pending async DMA */
1789
    if (bus->dma->aiocb) {
1790
#ifdef DEBUG_AIO
1791
        printf("aio_cancel\n");
1792
#endif
1793
        bdrv_aio_cancel(bus->dma->aiocb);
1794
        bus->dma->aiocb = NULL;
1795
    }
1796

    
1797
    /* reset dma provider too */
1798
    bus->dma->ops->reset(bus->dma);
1799
}
1800

    
1801
static bool ide_cd_is_tray_open(void *opaque)
1802
{
1803
    return ((IDEState *)opaque)->tray_open;
1804
}
1805

    
1806
static bool ide_cd_is_medium_locked(void *opaque)
1807
{
1808
    return ((IDEState *)opaque)->tray_locked;
1809
}
1810

    
1811
static const BlockDevOps ide_cd_block_ops = {
1812
    .change_media_cb = ide_cd_change_cb,
1813
    .is_tray_open = ide_cd_is_tray_open,
1814
    .is_medium_locked = ide_cd_is_medium_locked,
1815
};
1816

    
1817
int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
1818
                   const char *version, const char *serial)
1819
{
1820
    int cylinders, heads, secs;
1821
    uint64_t nb_sectors;
1822

    
1823
    s->bs = bs;
1824
    s->drive_kind = kind;
1825

    
1826
    bdrv_get_geometry(bs, &nb_sectors);
1827
    bdrv_guess_geometry(bs, &cylinders, &heads, &secs);
1828
    if (cylinders < 1 || cylinders > 16383) {
1829
        error_report("cyls must be between 1 and 16383");
1830
        return -1;
1831
    }
1832
    if (heads < 1 || heads > 16) {
1833
        error_report("heads must be between 1 and 16");
1834
        return -1;
1835
    }
1836
    if (secs < 1 || secs > 63) {
1837
        error_report("secs must be between 1 and 63");
1838
        return -1;
1839
    }
1840
    s->cylinders = cylinders;
1841
    s->heads = heads;
1842
    s->sectors = secs;
1843
    s->nb_sectors = nb_sectors;
1844
    /* The SMART values should be preserved across power cycles
1845
       but they aren't.  */
1846
    s->smart_enabled = 1;
1847
    s->smart_autosave = 1;
1848
    s->smart_errors = 0;
1849
    s->smart_selftest_count = 0;
1850
    if (kind == IDE_CD) {
1851
        bdrv_set_dev_ops(bs, &ide_cd_block_ops, s);
1852
        bdrv_set_buffer_alignment(bs, 2048);
1853
    } else {
1854
        if (!bdrv_is_inserted(s->bs)) {
1855
            error_report("Device needs media, but drive is empty");
1856
            return -1;
1857
        }
1858
        if (bdrv_is_read_only(bs)) {
1859
            error_report("Can't use a read-only drive");
1860
            return -1;
1861
        }
1862
    }
1863
    if (serial) {
1864
        strncpy(s->drive_serial_str, serial, sizeof(s->drive_serial_str));
1865
    } else {
1866
        snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
1867
                 "QM%05d", s->drive_serial);
1868
    }
1869
    if (version) {
1870
        pstrcpy(s->version, sizeof(s->version), version);
1871
    } else {
1872
        pstrcpy(s->version, sizeof(s->version), QEMU_VERSION);
1873
    }
1874

    
1875
    ide_reset(s);
1876
    return 0;
1877
}
1878

    
1879
static void ide_init1(IDEBus *bus, int unit)
1880
{
1881
    static int drive_serial = 1;
1882
    IDEState *s = &bus->ifs[unit];
1883

    
1884
    s->bus = bus;
1885
    s->unit = unit;
1886
    s->drive_serial = drive_serial++;
1887
    /* we need at least 2k alignment for accessing CDROMs using O_DIRECT */
1888
    s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4;
1889
    s->io_buffer = qemu_memalign(2048, s->io_buffer_total_len);
1890
    memset(s->io_buffer, 0, s->io_buffer_total_len);
1891

    
1892
    s->smart_selftest_data = qemu_blockalign(s->bs, 512);
1893
    memset(s->smart_selftest_data, 0, 512);
1894

    
1895
    s->sector_write_timer = qemu_new_timer_ns(vm_clock,
1896
                                           ide_sector_write_timer_cb, s);
1897
}
1898

    
1899
static void ide_nop_start(IDEDMA *dma, IDEState *s,
1900
                          BlockDriverCompletionFunc *cb)
1901
{
1902
}
1903

    
1904
static int ide_nop(IDEDMA *dma)
1905
{
1906
    return 0;
1907
}
1908

    
1909
static int ide_nop_int(IDEDMA *dma, int x)
1910
{
1911
    return 0;
1912
}
1913

    
1914
static void ide_nop_restart(void *opaque, int x, RunState y)
1915
{
1916
}
1917

    
1918
static const IDEDMAOps ide_dma_nop_ops = {
1919
    .start_dma      = ide_nop_start,
1920
    .start_transfer = ide_nop,
1921
    .prepare_buf    = ide_nop_int,
1922
    .rw_buf         = ide_nop_int,
1923
    .set_unit       = ide_nop_int,
1924
    .add_status     = ide_nop_int,
1925
    .set_inactive   = ide_nop,
1926
    .restart_cb     = ide_nop_restart,
1927
    .reset          = ide_nop,
1928
};
1929

    
1930
static IDEDMA ide_dma_nop = {
1931
    .ops = &ide_dma_nop_ops,
1932
    .aiocb = NULL,
1933
};
1934

    
1935
void ide_init2(IDEBus *bus, qemu_irq irq)
1936
{
1937
    int i;
1938

    
1939
    for(i = 0; i < 2; i++) {
1940
        ide_init1(bus, i);
1941
        ide_reset(&bus->ifs[i]);
1942
    }
1943
    bus->irq = irq;
1944
    bus->dma = &ide_dma_nop;
1945
}
1946

    
1947
/* TODO convert users to qdev and remove */
1948
void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
1949
                                    DriveInfo *hd1, qemu_irq irq)
1950
{
1951
    int i;
1952
    DriveInfo *dinfo;
1953

    
1954
    for(i = 0; i < 2; i++) {
1955
        dinfo = i == 0 ? hd0 : hd1;
1956
        ide_init1(bus, i);
1957
        if (dinfo) {
1958
            if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
1959
                               dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
1960
                               *dinfo->serial ? dinfo->serial : NULL) < 0) {
1961
                error_report("Can't set up IDE drive %s", dinfo->id);
1962
                exit(1);
1963
            }
1964
            bdrv_attach_dev_nofail(dinfo->bdrv, &bus->ifs[i]);
1965
        } else {
1966
            ide_reset(&bus->ifs[i]);
1967
        }
1968
    }
1969
    bus->irq = irq;
1970
    bus->dma = &ide_dma_nop;
1971
}
1972

    
1973
static const MemoryRegionPortio ide_portio_list[] = {
1974
    { 0, 8, 1, .read = ide_ioport_read, .write = ide_ioport_write },
1975
    { 0, 2, 2, .read = ide_data_readw, .write = ide_data_writew },
1976
    { 0, 4, 4, .read = ide_data_readl, .write = ide_data_writel },
1977
    PORTIO_END_OF_LIST(),
1978
};
1979

    
1980
static const MemoryRegionPortio ide_portio2_list[] = {
1981
    { 0, 1, 1, .read = ide_status_read, .write = ide_cmd_write },
1982
    PORTIO_END_OF_LIST(),
1983
};
1984

    
1985
void ide_init_ioport(IDEBus *bus, ISADevice *dev, int iobase, int iobase2)
1986
{
1987
    /* ??? Assume only ISA and PCI configurations, and that the PCI-ISA
1988
       bridge has been setup properly to always register with ISA.  */
1989
    isa_register_portio_list(dev, iobase, ide_portio_list, bus, "ide");
1990

    
1991
    if (iobase2) {
1992
        isa_register_portio_list(dev, iobase2, ide_portio2_list, bus, "ide");
1993
    }
1994
}
1995

    
1996
static bool is_identify_set(void *opaque, int version_id)
1997
{
1998
    IDEState *s = opaque;
1999

    
2000
    return s->identify_set != 0;
2001
}
2002

    
2003
static EndTransferFunc* transfer_end_table[] = {
2004
        ide_sector_read,
2005
        ide_sector_write,
2006
        ide_transfer_stop,
2007
        ide_atapi_cmd_reply_end,
2008
        ide_atapi_cmd,
2009
        ide_dummy_transfer_stop,
2010
};
2011

    
2012
static int transfer_end_table_idx(EndTransferFunc *fn)
2013
{
2014
    int i;
2015

    
2016
    for (i = 0; i < ARRAY_SIZE(transfer_end_table); i++)
2017
        if (transfer_end_table[i] == fn)
2018
            return i;
2019

    
2020
    return -1;
2021
}
2022

    
2023
static int ide_drive_post_load(void *opaque, int version_id)
2024
{
2025
    IDEState *s = opaque;
2026

    
2027
    if (version_id < 3) {
2028
        if (s->sense_key == SENSE_UNIT_ATTENTION &&
2029
            s->asc == ASC_MEDIUM_MAY_HAVE_CHANGED) {
2030
            s->cdrom_changed = 1;
2031
        }
2032
    }
2033
    return 0;
2034
}
2035

    
2036
static int ide_drive_pio_post_load(void *opaque, int version_id)
2037
{
2038
    IDEState *s = opaque;
2039

    
2040
    if (s->end_transfer_fn_idx > ARRAY_SIZE(transfer_end_table)) {
2041
        return -EINVAL;
2042
    }
2043
    s->end_transfer_func = transfer_end_table[s->end_transfer_fn_idx];
2044
    s->data_ptr = s->io_buffer + s->cur_io_buffer_offset;
2045
    s->data_end = s->data_ptr + s->cur_io_buffer_len;
2046

    
2047
    return 0;
2048
}
2049

    
2050
static void ide_drive_pio_pre_save(void *opaque)
2051
{
2052
    IDEState *s = opaque;
2053
    int idx;
2054

    
2055
    s->cur_io_buffer_offset = s->data_ptr - s->io_buffer;
2056
    s->cur_io_buffer_len = s->data_end - s->data_ptr;
2057

    
2058
    idx = transfer_end_table_idx(s->end_transfer_func);
2059
    if (idx == -1) {
2060
        fprintf(stderr, "%s: invalid end_transfer_func for DRQ_STAT\n",
2061
                        __func__);
2062
        s->end_transfer_fn_idx = 2;
2063
    } else {
2064
        s->end_transfer_fn_idx = idx;
2065
    }
2066
}
2067

    
2068
static bool ide_drive_pio_state_needed(void *opaque)
2069
{
2070
    IDEState *s = opaque;
2071

    
2072
    return ((s->status & DRQ_STAT) != 0)
2073
        || (s->bus->error_status & BM_STATUS_PIO_RETRY);
2074
}
2075

    
2076
static int ide_tray_state_post_load(void *opaque, int version_id)
2077
{
2078
    IDEState *s = opaque;
2079

    
2080
    bdrv_eject(s->bs, s->tray_open);
2081
    bdrv_lock_medium(s->bs, s->tray_locked);
2082
    return 0;
2083
}
2084

    
2085
static bool ide_tray_state_needed(void *opaque)
2086
{
2087
    IDEState *s = opaque;
2088

    
2089
    return s->tray_open || s->tray_locked;
2090
}
2091

    
2092
static bool ide_atapi_gesn_needed(void *opaque)
2093
{
2094
    IDEState *s = opaque;
2095

    
2096
    return s->events.new_media || s->events.eject_request;
2097
}
2098

    
2099
static bool ide_error_needed(void *opaque)
2100
{
2101
    IDEBus *bus = opaque;
2102

    
2103
    return (bus->error_status != 0);
2104
}
2105

    
2106
/* Fields for GET_EVENT_STATUS_NOTIFICATION ATAPI command */
2107
static const VMStateDescription vmstate_ide_atapi_gesn_state = {
2108
    .name ="ide_drive/atapi/gesn_state",
2109
    .version_id = 1,
2110
    .minimum_version_id = 1,
2111
    .minimum_version_id_old = 1,
2112
    .fields = (VMStateField []) {
2113
        VMSTATE_BOOL(events.new_media, IDEState),
2114
        VMSTATE_BOOL(events.eject_request, IDEState),
2115
        VMSTATE_END_OF_LIST()
2116
    }
2117
};
2118

    
2119
static const VMStateDescription vmstate_ide_tray_state = {
2120
    .name = "ide_drive/tray_state",
2121
    .version_id = 1,
2122
    .minimum_version_id = 1,
2123
    .minimum_version_id_old = 1,
2124
    .post_load = ide_tray_state_post_load,
2125
    .fields = (VMStateField[]) {
2126
        VMSTATE_BOOL(tray_open, IDEState),
2127
        VMSTATE_BOOL(tray_locked, IDEState),
2128
        VMSTATE_END_OF_LIST()
2129
    }
2130
};
2131

    
2132
static const VMStateDescription vmstate_ide_drive_pio_state = {
2133
    .name = "ide_drive/pio_state",
2134
    .version_id = 1,
2135
    .minimum_version_id = 1,
2136
    .minimum_version_id_old = 1,
2137
    .pre_save = ide_drive_pio_pre_save,
2138
    .post_load = ide_drive_pio_post_load,
2139
    .fields      = (VMStateField []) {
2140
        VMSTATE_INT32(req_nb_sectors, IDEState),
2141
        VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
2142
                             vmstate_info_uint8, uint8_t),
2143
        VMSTATE_INT32(cur_io_buffer_offset, IDEState),
2144
        VMSTATE_INT32(cur_io_buffer_len, IDEState),
2145
        VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
2146
        VMSTATE_INT32(elementary_transfer_size, IDEState),
2147
        VMSTATE_INT32(packet_transfer_size, IDEState),
2148
        VMSTATE_END_OF_LIST()
2149
    }
2150
};
2151

    
2152
const VMStateDescription vmstate_ide_drive = {
2153
    .name = "ide_drive",
2154
    .version_id = 3,
2155
    .minimum_version_id = 0,
2156
    .minimum_version_id_old = 0,
2157
    .post_load = ide_drive_post_load,
2158
    .fields      = (VMStateField []) {
2159
        VMSTATE_INT32(mult_sectors, IDEState),
2160
        VMSTATE_INT32(identify_set, IDEState),
2161
        VMSTATE_BUFFER_TEST(identify_data, IDEState, is_identify_set),
2162
        VMSTATE_UINT8(feature, IDEState),
2163
        VMSTATE_UINT8(error, IDEState),
2164
        VMSTATE_UINT32(nsector, IDEState),
2165
        VMSTATE_UINT8(sector, IDEState),
2166
        VMSTATE_UINT8(lcyl, IDEState),
2167
        VMSTATE_UINT8(hcyl, IDEState),
2168
        VMSTATE_UINT8(hob_feature, IDEState),
2169
        VMSTATE_UINT8(hob_sector, IDEState),
2170
        VMSTATE_UINT8(hob_nsector, IDEState),
2171
        VMSTATE_UINT8(hob_lcyl, IDEState),
2172
        VMSTATE_UINT8(hob_hcyl, IDEState),
2173
        VMSTATE_UINT8(select, IDEState),
2174
        VMSTATE_UINT8(status, IDEState),
2175
        VMSTATE_UINT8(lba48, IDEState),
2176
        VMSTATE_UINT8(sense_key, IDEState),
2177
        VMSTATE_UINT8(asc, IDEState),
2178
        VMSTATE_UINT8_V(cdrom_changed, IDEState, 3),
2179
        VMSTATE_END_OF_LIST()
2180
    },
2181
    .subsections = (VMStateSubsection []) {
2182
        {
2183
            .vmsd = &vmstate_ide_drive_pio_state,
2184
            .needed = ide_drive_pio_state_needed,
2185
        }, {
2186
            .vmsd = &vmstate_ide_tray_state,
2187
            .needed = ide_tray_state_needed,
2188
        }, {
2189
            .vmsd = &vmstate_ide_atapi_gesn_state,
2190
            .needed = ide_atapi_gesn_needed,
2191
        }, {
2192
            /* empty */
2193
        }
2194
    }
2195
};
2196

    
2197
static const VMStateDescription vmstate_ide_error_status = {
2198
    .name ="ide_bus/error",
2199
    .version_id = 1,
2200
    .minimum_version_id = 1,
2201
    .minimum_version_id_old = 1,
2202
    .fields = (VMStateField []) {
2203
        VMSTATE_INT32(error_status, IDEBus),
2204
        VMSTATE_END_OF_LIST()
2205
    }
2206
};
2207

    
2208
const VMStateDescription vmstate_ide_bus = {
2209
    .name = "ide_bus",
2210
    .version_id = 1,
2211
    .minimum_version_id = 1,
2212
    .minimum_version_id_old = 1,
2213
    .fields      = (VMStateField []) {
2214
        VMSTATE_UINT8(cmd, IDEBus),
2215
        VMSTATE_UINT8(unit, IDEBus),
2216
        VMSTATE_END_OF_LIST()
2217
    },
2218
    .subsections = (VMStateSubsection []) {
2219
        {
2220
            .vmsd = &vmstate_ide_error_status,
2221
            .needed = ide_error_needed,
2222
        }, {
2223
            /* empty */
2224
        }
2225
    }
2226
};
2227

    
2228
void ide_drive_get(DriveInfo **hd, int max_bus)
2229
{
2230
    int i;
2231

    
2232
    if (drive_get_max_bus(IF_IDE) >= max_bus) {
2233
        fprintf(stderr, "qemu: too many IDE bus: %d\n", max_bus);
2234
        exit(1);
2235
    }
2236

    
2237
    for(i = 0; i < max_bus * MAX_IDE_DEVS; i++) {
2238
        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);
2239
    }
2240
}