Statistics
| Branch: | Revision:

root / hw / ide / core.c @ f5654039

History | View | Annotate | Download (65.6 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(RUN_STATE_IO_ERROR);
532
        bdrv_iostatus_set_err(s->bs, error);
533
    } else {
534
        if (op & BM_STATUS_DMA_RETRY) {
535
            dma_buf_commit(s, 0);
536
            ide_dma_error(s);
537
        } else {
538
            ide_rw_error(s);
539
        }
540
        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
541
    }
542

    
543
    return 1;
544
}
545

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
780
    s->media_changed = 0;
781

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

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

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

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

    
811
static void ide_cd_eject_request_cb(void *opaque, bool force)
812
{
813
    IDEState *s = opaque;
814

    
815
    s->events.eject_request = true;
816
    if (force) {
817
        s->tray_locked = false;
818
    }
819
    ide_set_irq(s->bus);
820
}
821

    
822
static void ide_cmd_lba48_transform(IDEState *s, int lba48)
823
{
824
    s->lba48 = lba48;
825

    
826
    /* handle the 'magic' 0 nsector count conversion here. to avoid
827
     * fiddling with the rest of the read logic, we just store the
828
     * full sector count in ->nsector and ignore ->hob_nsector from now
829
     */
830
    if (!s->lba48) {
831
        if (!s->nsector)
832
            s->nsector = 256;
833
    } else {
834
        if (!s->nsector && !s->hob_nsector)
835
            s->nsector = 65536;
836
        else {
837
            int lo = s->nsector;
838
            int hi = s->hob_nsector;
839

    
840
            s->nsector = (hi << 8) | lo;
841
        }
842
    }
843
}
844

    
845
static void ide_clear_hob(IDEBus *bus)
846
{
847
    /* any write clears HOB high bit of device control register */
848
    bus->ifs[0].select &= ~(1 << 7);
849
    bus->ifs[1].select &= ~(1 << 7);
850
}
851

    
852
void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
853
{
854
    IDEBus *bus = opaque;
855

    
856
#ifdef DEBUG_IDE
857
    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
858
#endif
859

    
860
    addr &= 7;
861

    
862
    /* ignore writes to command block while busy with previous command */
863
    if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
864
        return;
865

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

    
920
#define HD_OK (1u << IDE_HD)
921
#define CD_OK (1u << IDE_CD)
922
#define CFA_OK (1u << IDE_CFATA)
923
#define HD_CFA_OK (HD_OK | CFA_OK)
924
#define ALL_OK (HD_OK | CD_OK | CFA_OK)
925

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

    
987
static bool ide_cmd_permitted(IDEState *s, uint32_t cmd)
988
{
989
    return cmd < ARRAY_SIZE(ide_cmd_table)
990
        && (ide_cmd_table[cmd] & (1u << s->drive_kind));
991
}
992

    
993
void ide_exec_cmd(IDEBus *bus, uint32_t val)
994
{
995
    IDEState *s;
996
    int n;
997
    int lba48 = 0;
998

    
999
#if defined(DEBUG_IDE)
1000
    printf("ide: CMD=%02x\n", val);
1001
#endif
1002
    s = idebus_active_if(bus);
1003
    /* ignore commands to non existant slave */
1004
    if (s != bus->ifs && !s->bs)
1005
        return;
1006

    
1007
    /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */
1008
    if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)
1009
        return;
1010

    
1011
    if (!ide_cmd_permitted(s, val)) {
1012
        goto abort_cmd;
1013
    }
1014

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

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

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

    
1427
                for (n=0; n<511; n++) 
1428
                s->io_buffer[511] += s->io_buffer[n];
1429
                s->io_buffer[511] = 0x100 - s->io_buffer[511];
1430
                s->status = READY_STAT | SEEK_STAT;
1431
                ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
1432
                ide_set_irq(s->bus);
1433
                break;
1434
        case SMART_READ_LOG:
1435
                switch (s->sector) {
1436
                case 0x01: /* summary smart error log */
1437
                memset(s->io_buffer, 0, 0x200);
1438
                s->io_buffer[0] = 0x01;
1439
                s->io_buffer[1] = 0x00; /* no error entries */
1440
                s->io_buffer[452] = s->smart_errors & 0xff;
1441
                s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;
1442

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

    
1501
uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
1502
{
1503
    IDEBus *bus = opaque;
1504
    IDEState *s = idebus_active_if(bus);
1505
    uint32_t addr;
1506
    int ret, hob;
1507

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

    
1579
uint32_t ide_status_read(void *opaque, uint32_t addr)
1580
{
1581
    IDEBus *bus = opaque;
1582
    IDEState *s = idebus_active_if(bus);
1583
    int ret;
1584

    
1585
    if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||
1586
        (s != bus->ifs && !s->bs))
1587
        ret = 0;
1588
    else
1589
        ret = s->status;
1590
#ifdef DEBUG_IDE
1591
    printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
1592
#endif
1593
    return ret;
1594
}
1595

    
1596
void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
1597
{
1598
    IDEBus *bus = opaque;
1599
    IDEState *s;
1600
    int i;
1601

    
1602
#ifdef DEBUG_IDE
1603
    printf("ide: write control addr=0x%x val=%02x\n", addr, val);
1604
#endif
1605
    /* common for both drives */
1606
    if (!(bus->cmd & IDE_CMD_RESET) &&
1607
        (val & IDE_CMD_RESET)) {
1608
        /* reset low to high */
1609
        for(i = 0;i < 2; i++) {
1610
            s = &bus->ifs[i];
1611
            s->status = BUSY_STAT | SEEK_STAT;
1612
            s->error = 0x01;
1613
        }
1614
    } else if ((bus->cmd & IDE_CMD_RESET) &&
1615
               !(val & IDE_CMD_RESET)) {
1616
        /* high to low */
1617
        for(i = 0;i < 2; i++) {
1618
            s = &bus->ifs[i];
1619
            if (s->drive_kind == IDE_CD)
1620
                s->status = 0x00; /* NOTE: READY is _not_ set */
1621
            else
1622
                s->status = READY_STAT | SEEK_STAT;
1623
            ide_set_signature(s);
1624
        }
1625
    }
1626

    
1627
    bus->cmd = val;
1628
}
1629

    
1630
/*
1631
 * Returns true if the running PIO transfer is a PIO out (i.e. data is
1632
 * transferred from the device to the guest), false if it's a PIO in
1633
 */
1634
static bool ide_is_pio_out(IDEState *s)
1635
{
1636
    if (s->end_transfer_func == ide_sector_write ||
1637
        s->end_transfer_func == ide_atapi_cmd) {
1638
        return false;
1639
    } else if (s->end_transfer_func == ide_sector_read ||
1640
               s->end_transfer_func == ide_transfer_stop ||
1641
               s->end_transfer_func == ide_atapi_cmd_reply_end ||
1642
               s->end_transfer_func == ide_dummy_transfer_stop) {
1643
        return true;
1644
    }
1645

    
1646
    abort();
1647
}
1648

    
1649
void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
1650
{
1651
    IDEBus *bus = opaque;
1652
    IDEState *s = idebus_active_if(bus);
1653
    uint8_t *p;
1654

    
1655
    /* PIO data access allowed only when DRQ bit is set. The result of a write
1656
     * during PIO out is indeterminate, just ignore it. */
1657
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
1658
        return;
1659
    }
1660

    
1661
    p = s->data_ptr;
1662
    *(uint16_t *)p = le16_to_cpu(val);
1663
    p += 2;
1664
    s->data_ptr = p;
1665
    if (p >= s->data_end)
1666
        s->end_transfer_func(s);
1667
}
1668

    
1669
uint32_t ide_data_readw(void *opaque, uint32_t addr)
1670
{
1671
    IDEBus *bus = opaque;
1672
    IDEState *s = idebus_active_if(bus);
1673
    uint8_t *p;
1674
    int ret;
1675

    
1676
    /* PIO data access allowed only when DRQ bit is set. The result of a read
1677
     * during PIO in is indeterminate, return 0 and don't move forward. */
1678
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
1679
        return 0;
1680
    }
1681

    
1682
    p = s->data_ptr;
1683
    ret = cpu_to_le16(*(uint16_t *)p);
1684
    p += 2;
1685
    s->data_ptr = p;
1686
    if (p >= s->data_end)
1687
        s->end_transfer_func(s);
1688
    return ret;
1689
}
1690

    
1691
void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
1692
{
1693
    IDEBus *bus = opaque;
1694
    IDEState *s = idebus_active_if(bus);
1695
    uint8_t *p;
1696

    
1697
    /* PIO data access allowed only when DRQ bit is set. The result of a write
1698
     * during PIO out is indeterminate, just ignore it. */
1699
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
1700
        return;
1701
    }
1702

    
1703
    p = s->data_ptr;
1704
    *(uint32_t *)p = le32_to_cpu(val);
1705
    p += 4;
1706
    s->data_ptr = p;
1707
    if (p >= s->data_end)
1708
        s->end_transfer_func(s);
1709
}
1710

    
1711
uint32_t ide_data_readl(void *opaque, uint32_t addr)
1712
{
1713
    IDEBus *bus = opaque;
1714
    IDEState *s = idebus_active_if(bus);
1715
    uint8_t *p;
1716
    int ret;
1717

    
1718
    /* PIO data access allowed only when DRQ bit is set. The result of a read
1719
     * during PIO in is indeterminate, return 0 and don't move forward. */
1720
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
1721
        return 0;
1722
    }
1723

    
1724
    p = s->data_ptr;
1725
    ret = cpu_to_le32(*(uint32_t *)p);
1726
    p += 4;
1727
    s->data_ptr = p;
1728
    if (p >= s->data_end)
1729
        s->end_transfer_func(s);
1730
    return ret;
1731
}
1732

    
1733
static void ide_dummy_transfer_stop(IDEState *s)
1734
{
1735
    s->data_ptr = s->io_buffer;
1736
    s->data_end = s->io_buffer;
1737
    s->io_buffer[0] = 0xff;
1738
    s->io_buffer[1] = 0xff;
1739
    s->io_buffer[2] = 0xff;
1740
    s->io_buffer[3] = 0xff;
1741
}
1742

    
1743
static void ide_reset(IDEState *s)
1744
{
1745
#ifdef DEBUG_IDE
1746
    printf("ide: reset\n");
1747
#endif
1748
    if (s->drive_kind == IDE_CFATA)
1749
        s->mult_sectors = 0;
1750
    else
1751
        s->mult_sectors = MAX_MULT_SECTORS;
1752
    /* ide regs */
1753
    s->feature = 0;
1754
    s->error = 0;
1755
    s->nsector = 0;
1756
    s->sector = 0;
1757
    s->lcyl = 0;
1758
    s->hcyl = 0;
1759

    
1760
    /* lba48 */
1761
    s->hob_feature = 0;
1762
    s->hob_sector = 0;
1763
    s->hob_nsector = 0;
1764
    s->hob_lcyl = 0;
1765
    s->hob_hcyl = 0;
1766

    
1767
    s->select = 0xa0;
1768
    s->status = READY_STAT | SEEK_STAT;
1769

    
1770
    s->lba48 = 0;
1771

    
1772
    /* ATAPI specific */
1773
    s->sense_key = 0;
1774
    s->asc = 0;
1775
    s->cdrom_changed = 0;
1776
    s->packet_transfer_size = 0;
1777
    s->elementary_transfer_size = 0;
1778
    s->io_buffer_index = 0;
1779
    s->cd_sector_size = 0;
1780
    s->atapi_dma = 0;
1781
    /* ATA DMA state */
1782
    s->io_buffer_size = 0;
1783
    s->req_nb_sectors = 0;
1784

    
1785
    ide_set_signature(s);
1786
    /* init the transfer handler so that 0xffff is returned on data
1787
       accesses */
1788
    s->end_transfer_func = ide_dummy_transfer_stop;
1789
    ide_dummy_transfer_stop(s);
1790
    s->media_changed = 0;
1791
}
1792

    
1793
void ide_bus_reset(IDEBus *bus)
1794
{
1795
    bus->unit = 0;
1796
    bus->cmd = 0;
1797
    ide_reset(&bus->ifs[0]);
1798
    ide_reset(&bus->ifs[1]);
1799
    ide_clear_hob(bus);
1800

    
1801
    /* pending async DMA */
1802
    if (bus->dma->aiocb) {
1803
#ifdef DEBUG_AIO
1804
        printf("aio_cancel\n");
1805
#endif
1806
        bdrv_aio_cancel(bus->dma->aiocb);
1807
        bus->dma->aiocb = NULL;
1808
    }
1809

    
1810
    /* reset dma provider too */
1811
    bus->dma->ops->reset(bus->dma);
1812
}
1813

    
1814
static bool ide_cd_is_tray_open(void *opaque)
1815
{
1816
    return ((IDEState *)opaque)->tray_open;
1817
}
1818

    
1819
static bool ide_cd_is_medium_locked(void *opaque)
1820
{
1821
    return ((IDEState *)opaque)->tray_locked;
1822
}
1823

    
1824
static const BlockDevOps ide_cd_block_ops = {
1825
    .change_media_cb = ide_cd_change_cb,
1826
    .eject_request_cb = ide_cd_eject_request_cb,
1827
    .is_tray_open = ide_cd_is_tray_open,
1828
    .is_medium_locked = ide_cd_is_medium_locked,
1829
};
1830

    
1831
int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,
1832
                   const char *version, const char *serial)
1833
{
1834
    int cylinders, heads, secs;
1835
    uint64_t nb_sectors;
1836

    
1837
    s->bs = bs;
1838
    s->drive_kind = kind;
1839

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

    
1889
    ide_reset(s);
1890
    bdrv_iostatus_enable(bs);
1891
    return 0;
1892
}
1893

    
1894
static void ide_init1(IDEBus *bus, int unit)
1895
{
1896
    static int drive_serial = 1;
1897
    IDEState *s = &bus->ifs[unit];
1898

    
1899
    s->bus = bus;
1900
    s->unit = unit;
1901
    s->drive_serial = drive_serial++;
1902
    /* we need at least 2k alignment for accessing CDROMs using O_DIRECT */
1903
    s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4;
1904
    s->io_buffer = qemu_memalign(2048, s->io_buffer_total_len);
1905
    memset(s->io_buffer, 0, s->io_buffer_total_len);
1906

    
1907
    s->smart_selftest_data = qemu_blockalign(s->bs, 512);
1908
    memset(s->smart_selftest_data, 0, 512);
1909

    
1910
    s->sector_write_timer = qemu_new_timer_ns(vm_clock,
1911
                                           ide_sector_write_timer_cb, s);
1912
}
1913

    
1914
static void ide_nop_start(IDEDMA *dma, IDEState *s,
1915
                          BlockDriverCompletionFunc *cb)
1916
{
1917
}
1918

    
1919
static int ide_nop(IDEDMA *dma)
1920
{
1921
    return 0;
1922
}
1923

    
1924
static int ide_nop_int(IDEDMA *dma, int x)
1925
{
1926
    return 0;
1927
}
1928

    
1929
static void ide_nop_restart(void *opaque, int x, RunState y)
1930
{
1931
}
1932

    
1933
static const IDEDMAOps ide_dma_nop_ops = {
1934
    .start_dma      = ide_nop_start,
1935
    .start_transfer = ide_nop,
1936
    .prepare_buf    = ide_nop_int,
1937
    .rw_buf         = ide_nop_int,
1938
    .set_unit       = ide_nop_int,
1939
    .add_status     = ide_nop_int,
1940
    .set_inactive   = ide_nop,
1941
    .restart_cb     = ide_nop_restart,
1942
    .reset          = ide_nop,
1943
};
1944

    
1945
static IDEDMA ide_dma_nop = {
1946
    .ops = &ide_dma_nop_ops,
1947
    .aiocb = NULL,
1948
};
1949

    
1950
void ide_init2(IDEBus *bus, qemu_irq irq)
1951
{
1952
    int i;
1953

    
1954
    for(i = 0; i < 2; i++) {
1955
        ide_init1(bus, i);
1956
        ide_reset(&bus->ifs[i]);
1957
    }
1958
    bus->irq = irq;
1959
    bus->dma = &ide_dma_nop;
1960
}
1961

    
1962
/* TODO convert users to qdev and remove */
1963
void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,
1964
                                    DriveInfo *hd1, qemu_irq irq)
1965
{
1966
    int i;
1967
    DriveInfo *dinfo;
1968

    
1969
    for(i = 0; i < 2; i++) {
1970
        dinfo = i == 0 ? hd0 : hd1;
1971
        ide_init1(bus, i);
1972
        if (dinfo) {
1973
            if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,
1974
                               dinfo->media_cd ? IDE_CD : IDE_HD, NULL,
1975
                               *dinfo->serial ? dinfo->serial : NULL) < 0) {
1976
                error_report("Can't set up IDE drive %s", dinfo->id);
1977
                exit(1);
1978
            }
1979
            bdrv_attach_dev_nofail(dinfo->bdrv, &bus->ifs[i]);
1980
        } else {
1981
            ide_reset(&bus->ifs[i]);
1982
        }
1983
    }
1984
    bus->irq = irq;
1985
    bus->dma = &ide_dma_nop;
1986
}
1987

    
1988
static const MemoryRegionPortio ide_portio_list[] = {
1989
    { 0, 8, 1, .read = ide_ioport_read, .write = ide_ioport_write },
1990
    { 0, 2, 2, .read = ide_data_readw, .write = ide_data_writew },
1991
    { 0, 4, 4, .read = ide_data_readl, .write = ide_data_writel },
1992
    PORTIO_END_OF_LIST(),
1993
};
1994

    
1995
static const MemoryRegionPortio ide_portio2_list[] = {
1996
    { 0, 1, 1, .read = ide_status_read, .write = ide_cmd_write },
1997
    PORTIO_END_OF_LIST(),
1998
};
1999

    
2000
void ide_init_ioport(IDEBus *bus, ISADevice *dev, int iobase, int iobase2)
2001
{
2002
    /* ??? Assume only ISA and PCI configurations, and that the PCI-ISA
2003
       bridge has been setup properly to always register with ISA.  */
2004
    isa_register_portio_list(dev, iobase, ide_portio_list, bus, "ide");
2005

    
2006
    if (iobase2) {
2007
        isa_register_portio_list(dev, iobase2, ide_portio2_list, bus, "ide");
2008
    }
2009
}
2010

    
2011
static bool is_identify_set(void *opaque, int version_id)
2012
{
2013
    IDEState *s = opaque;
2014

    
2015
    return s->identify_set != 0;
2016
}
2017

    
2018
static EndTransferFunc* transfer_end_table[] = {
2019
        ide_sector_read,
2020
        ide_sector_write,
2021
        ide_transfer_stop,
2022
        ide_atapi_cmd_reply_end,
2023
        ide_atapi_cmd,
2024
        ide_dummy_transfer_stop,
2025
};
2026

    
2027
static int transfer_end_table_idx(EndTransferFunc *fn)
2028
{
2029
    int i;
2030

    
2031
    for (i = 0; i < ARRAY_SIZE(transfer_end_table); i++)
2032
        if (transfer_end_table[i] == fn)
2033
            return i;
2034

    
2035
    return -1;
2036
}
2037

    
2038
static int ide_drive_post_load(void *opaque, int version_id)
2039
{
2040
    IDEState *s = opaque;
2041

    
2042
    if (version_id < 3) {
2043
        if (s->sense_key == UNIT_ATTENTION &&
2044
            s->asc == ASC_MEDIUM_MAY_HAVE_CHANGED) {
2045
            s->cdrom_changed = 1;
2046
        }
2047
    }
2048
    return 0;
2049
}
2050

    
2051
static int ide_drive_pio_post_load(void *opaque, int version_id)
2052
{
2053
    IDEState *s = opaque;
2054

    
2055
    if (s->end_transfer_fn_idx >= ARRAY_SIZE(transfer_end_table)) {
2056
        return -EINVAL;
2057
    }
2058
    s->end_transfer_func = transfer_end_table[s->end_transfer_fn_idx];
2059
    s->data_ptr = s->io_buffer + s->cur_io_buffer_offset;
2060
    s->data_end = s->data_ptr + s->cur_io_buffer_len;
2061

    
2062
    return 0;
2063
}
2064

    
2065
static void ide_drive_pio_pre_save(void *opaque)
2066
{
2067
    IDEState *s = opaque;
2068
    int idx;
2069

    
2070
    s->cur_io_buffer_offset = s->data_ptr - s->io_buffer;
2071
    s->cur_io_buffer_len = s->data_end - s->data_ptr;
2072

    
2073
    idx = transfer_end_table_idx(s->end_transfer_func);
2074
    if (idx == -1) {
2075
        fprintf(stderr, "%s: invalid end_transfer_func for DRQ_STAT\n",
2076
                        __func__);
2077
        s->end_transfer_fn_idx = 2;
2078
    } else {
2079
        s->end_transfer_fn_idx = idx;
2080
    }
2081
}
2082

    
2083
static bool ide_drive_pio_state_needed(void *opaque)
2084
{
2085
    IDEState *s = opaque;
2086

    
2087
    return ((s->status & DRQ_STAT) != 0)
2088
        || (s->bus->error_status & BM_STATUS_PIO_RETRY);
2089
}
2090

    
2091
static int ide_tray_state_post_load(void *opaque, int version_id)
2092
{
2093
    IDEState *s = opaque;
2094

    
2095
    bdrv_eject(s->bs, s->tray_open);
2096
    bdrv_lock_medium(s->bs, s->tray_locked);
2097
    return 0;
2098
}
2099

    
2100
static bool ide_tray_state_needed(void *opaque)
2101
{
2102
    IDEState *s = opaque;
2103

    
2104
    return s->tray_open || s->tray_locked;
2105
}
2106

    
2107
static bool ide_atapi_gesn_needed(void *opaque)
2108
{
2109
    IDEState *s = opaque;
2110

    
2111
    return s->events.new_media || s->events.eject_request;
2112
}
2113

    
2114
static bool ide_error_needed(void *opaque)
2115
{
2116
    IDEBus *bus = opaque;
2117

    
2118
    return (bus->error_status != 0);
2119
}
2120

    
2121
/* Fields for GET_EVENT_STATUS_NOTIFICATION ATAPI command */
2122
static const VMStateDescription vmstate_ide_atapi_gesn_state = {
2123
    .name ="ide_drive/atapi/gesn_state",
2124
    .version_id = 1,
2125
    .minimum_version_id = 1,
2126
    .minimum_version_id_old = 1,
2127
    .fields = (VMStateField []) {
2128
        VMSTATE_BOOL(events.new_media, IDEState),
2129
        VMSTATE_BOOL(events.eject_request, IDEState),
2130
        VMSTATE_END_OF_LIST()
2131
    }
2132
};
2133

    
2134
static const VMStateDescription vmstate_ide_tray_state = {
2135
    .name = "ide_drive/tray_state",
2136
    .version_id = 1,
2137
    .minimum_version_id = 1,
2138
    .minimum_version_id_old = 1,
2139
    .post_load = ide_tray_state_post_load,
2140
    .fields = (VMStateField[]) {
2141
        VMSTATE_BOOL(tray_open, IDEState),
2142
        VMSTATE_BOOL(tray_locked, IDEState),
2143
        VMSTATE_END_OF_LIST()
2144
    }
2145
};
2146

    
2147
static const VMStateDescription vmstate_ide_drive_pio_state = {
2148
    .name = "ide_drive/pio_state",
2149
    .version_id = 1,
2150
    .minimum_version_id = 1,
2151
    .minimum_version_id_old = 1,
2152
    .pre_save = ide_drive_pio_pre_save,
2153
    .post_load = ide_drive_pio_post_load,
2154
    .fields      = (VMStateField []) {
2155
        VMSTATE_INT32(req_nb_sectors, IDEState),
2156
        VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
2157
                             vmstate_info_uint8, uint8_t),
2158
        VMSTATE_INT32(cur_io_buffer_offset, IDEState),
2159
        VMSTATE_INT32(cur_io_buffer_len, IDEState),
2160
        VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
2161
        VMSTATE_INT32(elementary_transfer_size, IDEState),
2162
        VMSTATE_INT32(packet_transfer_size, IDEState),
2163
        VMSTATE_END_OF_LIST()
2164
    }
2165
};
2166

    
2167
const VMStateDescription vmstate_ide_drive = {
2168
    .name = "ide_drive",
2169
    .version_id = 3,
2170
    .minimum_version_id = 0,
2171
    .minimum_version_id_old = 0,
2172
    .post_load = ide_drive_post_load,
2173
    .fields      = (VMStateField []) {
2174
        VMSTATE_INT32(mult_sectors, IDEState),
2175
        VMSTATE_INT32(identify_set, IDEState),
2176
        VMSTATE_BUFFER_TEST(identify_data, IDEState, is_identify_set),
2177
        VMSTATE_UINT8(feature, IDEState),
2178
        VMSTATE_UINT8(error, IDEState),
2179
        VMSTATE_UINT32(nsector, IDEState),
2180
        VMSTATE_UINT8(sector, IDEState),
2181
        VMSTATE_UINT8(lcyl, IDEState),
2182
        VMSTATE_UINT8(hcyl, IDEState),
2183
        VMSTATE_UINT8(hob_feature, IDEState),
2184
        VMSTATE_UINT8(hob_sector, IDEState),
2185
        VMSTATE_UINT8(hob_nsector, IDEState),
2186
        VMSTATE_UINT8(hob_lcyl, IDEState),
2187
        VMSTATE_UINT8(hob_hcyl, IDEState),
2188
        VMSTATE_UINT8(select, IDEState),
2189
        VMSTATE_UINT8(status, IDEState),
2190
        VMSTATE_UINT8(lba48, IDEState),
2191
        VMSTATE_UINT8(sense_key, IDEState),
2192
        VMSTATE_UINT8(asc, IDEState),
2193
        VMSTATE_UINT8_V(cdrom_changed, IDEState, 3),
2194
        VMSTATE_END_OF_LIST()
2195
    },
2196
    .subsections = (VMStateSubsection []) {
2197
        {
2198
            .vmsd = &vmstate_ide_drive_pio_state,
2199
            .needed = ide_drive_pio_state_needed,
2200
        }, {
2201
            .vmsd = &vmstate_ide_tray_state,
2202
            .needed = ide_tray_state_needed,
2203
        }, {
2204
            .vmsd = &vmstate_ide_atapi_gesn_state,
2205
            .needed = ide_atapi_gesn_needed,
2206
        }, {
2207
            /* empty */
2208
        }
2209
    }
2210
};
2211

    
2212
static const VMStateDescription vmstate_ide_error_status = {
2213
    .name ="ide_bus/error",
2214
    .version_id = 1,
2215
    .minimum_version_id = 1,
2216
    .minimum_version_id_old = 1,
2217
    .fields = (VMStateField []) {
2218
        VMSTATE_INT32(error_status, IDEBus),
2219
        VMSTATE_END_OF_LIST()
2220
    }
2221
};
2222

    
2223
const VMStateDescription vmstate_ide_bus = {
2224
    .name = "ide_bus",
2225
    .version_id = 1,
2226
    .minimum_version_id = 1,
2227
    .minimum_version_id_old = 1,
2228
    .fields      = (VMStateField []) {
2229
        VMSTATE_UINT8(cmd, IDEBus),
2230
        VMSTATE_UINT8(unit, IDEBus),
2231
        VMSTATE_END_OF_LIST()
2232
    },
2233
    .subsections = (VMStateSubsection []) {
2234
        {
2235
            .vmsd = &vmstate_ide_error_status,
2236
            .needed = ide_error_needed,
2237
        }, {
2238
            /* empty */
2239
        }
2240
    }
2241
};
2242

    
2243
void ide_drive_get(DriveInfo **hd, int max_bus)
2244
{
2245
    int i;
2246

    
2247
    if (drive_get_max_bus(IF_IDE) >= max_bus) {
2248
        fprintf(stderr, "qemu: too many IDE bus: %d\n", max_bus);
2249
        exit(1);
2250
    }
2251

    
2252
    for(i = 0; i < max_bus * MAX_IDE_DEVS; i++) {
2253
        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);
2254
    }
2255
}