core.c 78.5 KB
Newer Older
B
bellard 已提交
1
/*
2
 * QEMU IDE disk and CD/DVD-ROM Emulator
3
 *
B
bellard 已提交
4
 * Copyright (c) 2003 Fabrice Bellard
5
 * Copyright (c) 2006 Openedhand Ltd.
6
 *
B
bellard 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
P
Peter Maydell 已提交
25
#include "qemu/osdep.h"
G
Gerd Hoffmann 已提交
26
#include <hw/hw.h>
P
Paolo Bonzini 已提交
27
#include <hw/i386/pc.h>
28
#include <hw/pci/pci.h>
P
Paolo Bonzini 已提交
29
#include <hw/isa/isa.h>
30 31
#include "qemu/error-report.h"
#include "qemu/timer.h"
32 33
#include "sysemu/sysemu.h"
#include "sysemu/dma.h"
P
Paolo Bonzini 已提交
34
#include "hw/block/block.h"
35
#include "sysemu/block-backend.h"
G
Gerd Hoffmann 已提交
36 37

#include <hw/ide/internal.h>
B
Brian Wheeler 已提交
38

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

K
Kevin Wolf 已提交
59
static int ide_handle_rw_error(IDEState *s, int error, int op);
60
static void ide_dummy_transfer_stop(IDEState *s);
B
bellard 已提交
61

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

B
bellard 已提交
74 75
static void put_le16(uint16_t *p, unsigned int v)
{
B
bellard 已提交
76
    *p = cpu_to_le16(v);
B
bellard 已提交
77 78
}

J
John Snow 已提交
79 80 81 82 83 84 85 86 87 88 89
static void ide_identify_size(IDEState *s)
{
    uint16_t *p = (uint16_t *)s->identify_data;
    put_le16(p + 60, s->nb_sectors);
    put_le16(p + 61, s->nb_sectors >> 16);
    put_le16(p + 100, s->nb_sectors);
    put_le16(p + 101, s->nb_sectors >> 16);
    put_le16(p + 102, s->nb_sectors >> 32);
    put_le16(p + 103, s->nb_sectors >> 48);
}

B
bellard 已提交
90 91 92 93
static void ide_identify(IDEState *s)
{
    uint16_t *p;
    unsigned int oldsize;
C
Christoph Hellwig 已提交
94
    IDEDevice *dev = s->unit ? s->bus->slave : s->bus->master;
B
bellard 已提交
95

96
    p = (uint16_t *)s->identify_data;
97
    if (s->identify_set) {
98
        goto fill_buffer;
99
    }
100
    memset(p, 0, sizeof(s->identify_data));
101

B
bellard 已提交
102
    put_le16(p + 0, 0x0040);
103
    put_le16(p + 1, s->cylinders);
B
bellard 已提交
104 105 106
    put_le16(p + 3, s->heads);
    put_le16(p + 4, 512 * s->sectors); /* XXX: retired, remove ? */
    put_le16(p + 5, 512); /* XXX: retired, remove ? */
107
    put_le16(p + 6, s->sectors);
108
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
B
bellard 已提交
109 110 111
    put_le16(p + 20, 3); /* XXX: retired, remove ? */
    put_le16(p + 21, 512); /* cache size in sectors */
    put_le16(p + 22, 4); /* ecc bytes */
G
Gerd Hoffmann 已提交
112
    padstr((char *)(p + 23), s->version, 8); /* firmware version */
F
Floris Bos 已提交
113
    padstr((char *)(p + 27), s->drive_model_str, 40); /* model */
114
#if MAX_MULT_SECTORS > 1
B
bellard 已提交
115
    put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
B
bellard 已提交
116
#endif
B
bellard 已提交
117
    put_le16(p + 48, 1); /* dword I/O */
118
    put_le16(p + 49, (1 << 11) | (1 << 9) | (1 << 8)); /* DMA and LBA supported */
B
bellard 已提交
119 120
    put_le16(p + 51, 0x200); /* PIO transfer cycle */
    put_le16(p + 52, 0x200); /* DMA transfer cycle */
121
    put_le16(p + 53, 1 | (1 << 1) | (1 << 2)); /* words 54-58,64-70,88 are valid */
B
bellard 已提交
122 123 124
    put_le16(p + 54, s->cylinders);
    put_le16(p + 55, s->heads);
    put_le16(p + 56, s->sectors);
B
bellard 已提交
125
    oldsize = s->cylinders * s->heads * s->sectors;
B
bellard 已提交
126 127
    put_le16(p + 57, oldsize);
    put_le16(p + 58, oldsize >> 16);
B
bellard 已提交
128
    if (s->mult_sectors)
B
bellard 已提交
129
        put_le16(p + 59, 0x100 | s->mult_sectors);
J
John Snow 已提交
130 131
    /* *(p + 60) := nb_sectors       -- see ide_identify_size */
    /* *(p + 61) := nb_sectors >> 16 -- see ide_identify_size */
132
    put_le16(p + 62, 0x07); /* single word dma0-2 supported */
133
    put_le16(p + 63, 0x07); /* mdma0-2 supported */
134
    put_le16(p + 64, 0x03); /* pio3-4 supported */
135 136 137 138
    put_le16(p + 65, 120);
    put_le16(p + 66, 120);
    put_le16(p + 67, 120);
    put_le16(p + 68, 120);
C
Christoph Hellwig 已提交
139 140 141
    if (dev && dev->conf.discard_granularity) {
        put_le16(p + 69, (1 << 14)); /* determinate TRIM behavior */
    }
142 143 144 145 146 147 148

    if (s->ncq_queues) {
        put_le16(p + 75, s->ncq_queues - 1);
        /* NCQ supported */
        put_le16(p + 76, (1 << 8));
    }

149 150
    put_le16(p + 80, 0xf0); /* ata3 -> ata6 supported */
    put_le16(p + 81, 0x16); /* conforms to ata5 */
151 152
    /* 14=NOP supported, 5=WCACHE supported, 0=SMART supported */
    put_le16(p + 82, (1 << 14) | (1 << 5) | 1);
B
bellard 已提交
153 154
    /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
    put_le16(p + 83, (1 << 14) | (1 << 13) | (1 <<12) | (1 << 10));
F
Floris Bos 已提交
155 156 157 158 159 160
    /* 14=set to 1, 8=has WWN, 1=SMART self test, 0=SMART error logging */
    if (s->wwn) {
        put_le16(p + 84, (1 << 14) | (1 << 8) | 0);
    } else {
        put_le16(p + 84, (1 << 14) | 0);
    }
161
    /* 14 = NOP supported, 5=WCACHE enabled, 0=SMART feature set enabled */
162 163 164 165 166
    if (blk_enable_write_cache(s->blk)) {
        put_le16(p + 85, (1 << 14) | (1 << 5) | 1);
    } else {
        put_le16(p + 85, (1 << 14) | 1);
    }
B
bellard 已提交
167
    /* 13=flush_cache_ext,12=flush_cache,10=lba48 */
168
    put_le16(p + 86, (1 << 13) | (1 <<12) | (1 << 10));
F
Floris Bos 已提交
169 170 171 172 173 174
    /* 14=set to 1, 8=has WWN, 1=SMART self test, 0=SMART error logging */
    if (s->wwn) {
        put_le16(p + 87, (1 << 14) | (1 << 8) | 0);
    } else {
        put_le16(p + 87, (1 << 14) | 0);
    }
175 176
    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
    put_le16(p + 93, 1 | (1 << 14) | 0x2000);
J
John Snow 已提交
177 178 179 180
    /* *(p + 100) := nb_sectors       -- see ide_identify_size */
    /* *(p + 101) := nb_sectors >> 16 -- see ide_identify_size */
    /* *(p + 102) := nb_sectors >> 32 -- see ide_identify_size */
    /* *(p + 103) := nb_sectors >> 48 -- see ide_identify_size */
C
Christoph Hellwig 已提交
181

182 183
    if (dev && dev->conf.physical_block_size)
        put_le16(p + 106, 0x6000 | get_physical_block_exp(&dev->conf));
F
Floris Bos 已提交
184 185 186 187 188 189 190
    if (s->wwn) {
        /* LE 16-bit words 111-108 contain 64-bit World Wide Name */
        put_le16(p + 108, s->wwn >> 48);
        put_le16(p + 109, s->wwn >> 32);
        put_le16(p + 110, s->wwn >> 16);
        put_le16(p + 111, s->wwn);
    }
C
Christoph Hellwig 已提交
191 192 193
    if (dev && dev->conf.discard_granularity) {
        put_le16(p + 169, 1); /* TRIM support */
    }
194

J
John Snow 已提交
195
    ide_identify_size(s);
196
    s->identify_set = 1;
197 198 199

fill_buffer:
    memcpy(s->io_buffer, p, sizeof(s->identify_data));
B
bellard 已提交
200 201 202 203 204 205
}

static void ide_atapi_identify(IDEState *s)
{
    uint16_t *p;

206
    p = (uint16_t *)s->identify_data;
207
    if (s->identify_set) {
208
        goto fill_buffer;
209
    }
210
    memset(p, 0, sizeof(s->identify_data));
211

B
bellard 已提交
212
    /* Removable CDROM, 50us response, 12 byte packets */
B
bellard 已提交
213
    put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));
214
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
B
bellard 已提交
215 216 217
    put_le16(p + 20, 3); /* buffer type */
    put_le16(p + 21, 512); /* cache size in sectors */
    put_le16(p + 22, 4); /* ecc bytes */
G
Gerd Hoffmann 已提交
218
    padstr((char *)(p + 23), s->version, 8); /* firmware version */
F
Floris Bos 已提交
219
    padstr((char *)(p + 27), s->drive_model_str, 40); /* model */
B
bellard 已提交
220
    put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */
221 222 223
#ifdef USE_DMA_CDROM
    put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */
    put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */
224
    put_le16(p + 62, 7);  /* single word dma0-2 supported */
225 226
    put_le16(p + 63, 7);  /* mdma0-2 supported */
#else
B
bellard 已提交
227 228 229
    put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */
    put_le16(p + 53, 3); /* words 64-70, 54-58 valid */
    put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */
230
#endif
231
    put_le16(p + 64, 3); /* pio3-4 supported */
B
bellard 已提交
232 233 234 235
    put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */
    put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */
    put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */
    put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */
236

B
bellard 已提交
237 238
    put_le16(p + 71, 30); /* in ns */
    put_le16(p + 72, 30); /* in ns */
B
bellard 已提交
239

A
Alexander Graf 已提交
240 241 242 243 244 245
    if (s->ncq_queues) {
        put_le16(p + 75, s->ncq_queues - 1);
        /* NCQ supported */
        put_le16(p + 76, (1 << 8));
    }

B
bellard 已提交
246
    put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
247 248 249 250 251
    if (s->wwn) {
        put_le16(p + 84, (1 << 8)); /* supports WWN for words 108-111 */
        put_le16(p + 87, (1 << 8)); /* WWN enabled */
    }

252 253 254
#ifdef USE_DMA_CDROM
    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */
#endif
255 256 257 258 259 260 261 262 263

    if (s->wwn) {
        /* LE 16-bit words 111-108 contain 64-bit World Wide Name */
        put_le16(p + 108, s->wwn >> 48);
        put_le16(p + 109, s->wwn >> 32);
        put_le16(p + 110, s->wwn >> 16);
        put_le16(p + 111, s->wwn);
    }

264
    s->identify_set = 1;
265 266 267

fill_buffer:
    memcpy(s->io_buffer, p, sizeof(s->identify_data));
B
bellard 已提交
268 269
}

J
John Snow 已提交
270 271 272 273 274 275 276 277 278
static void ide_cfata_identify_size(IDEState *s)
{
    uint16_t *p = (uint16_t *)s->identify_data;
    put_le16(p + 7, s->nb_sectors >> 16);  /* Sectors per card */
    put_le16(p + 8, s->nb_sectors);        /* Sectors per card */
    put_le16(p + 60, s->nb_sectors);       /* Total LBA sectors */
    put_le16(p + 61, s->nb_sectors >> 16); /* Total LBA sectors */
}

279 280 281 282 283
static void ide_cfata_identify(IDEState *s)
{
    uint16_t *p;
    uint32_t cur_sec;

284 285
    p = (uint16_t *)s->identify_data;
    if (s->identify_set) {
286
        goto fill_buffer;
287
    }
288 289 290 291 292 293 294 295
    memset(p, 0, sizeof(s->identify_data));

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

    put_le16(p + 0, 0x848a);			/* CF Storage Card signature */
    put_le16(p + 1, s->cylinders);		/* Default cylinders */
    put_le16(p + 3, s->heads);			/* Default heads */
    put_le16(p + 6, s->sectors);		/* Default sectors per track */
J
John Snow 已提交
296 297
    /* *(p + 7) := nb_sectors >> 16 -- see ide_cfata_identify_size */
    /* *(p + 8) := nb_sectors       -- see ide_cfata_identify_size */
298
    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */
299
    put_le16(p + 22, 0x0004);			/* ECC bytes */
G
Gerd Hoffmann 已提交
300
    padstr((char *) (p + 23), s->version, 8);	/* Firmware Revision */
F
Floris Bos 已提交
301
    padstr((char *) (p + 27), s->drive_model_str, 40);/* Model number */
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
#if MAX_MULT_SECTORS > 1
    put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);
#else
    put_le16(p + 47, 0x0000);
#endif
    put_le16(p + 49, 0x0f00);			/* Capabilities */
    put_le16(p + 51, 0x0002);			/* PIO cycle timing mode */
    put_le16(p + 52, 0x0001);			/* DMA cycle timing mode */
    put_le16(p + 53, 0x0003);			/* Translation params valid */
    put_le16(p + 54, s->cylinders);		/* Current cylinders */
    put_le16(p + 55, s->heads);			/* Current heads */
    put_le16(p + 56, s->sectors);		/* Current sectors */
    put_le16(p + 57, cur_sec);			/* Current capacity */
    put_le16(p + 58, cur_sec >> 16);		/* Current capacity */
    if (s->mult_sectors)			/* Multiple sector setting */
        put_le16(p + 59, 0x100 | s->mult_sectors);
J
John Snow 已提交
318 319
    /* *(p + 60) := nb_sectors       -- see ide_cfata_identify_size */
    /* *(p + 61) := nb_sectors >> 16 -- see ide_cfata_identify_size */
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    put_le16(p + 63, 0x0203);			/* Multiword DMA capability */
    put_le16(p + 64, 0x0001);			/* Flow Control PIO support */
    put_le16(p + 65, 0x0096);			/* Min. Multiword DMA cycle */
    put_le16(p + 66, 0x0096);			/* Rec. Multiword DMA cycle */
    put_le16(p + 68, 0x00b4);			/* Min. PIO cycle time */
    put_le16(p + 82, 0x400c);			/* Command Set supported */
    put_le16(p + 83, 0x7068);			/* Command Set supported */
    put_le16(p + 84, 0x4000);			/* Features supported */
    put_le16(p + 85, 0x000c);			/* Command Set enabled */
    put_le16(p + 86, 0x7044);			/* Command Set enabled */
    put_le16(p + 87, 0x4000);			/* Features enabled */
    put_le16(p + 91, 0x4060);			/* Current APM level */
    put_le16(p + 129, 0x0002);			/* Current features option */
    put_le16(p + 130, 0x0005);			/* Reassigned sectors */
    put_le16(p + 131, 0x0001);			/* Initial power mode */
    put_le16(p + 132, 0x0000);			/* User signature */
    put_le16(p + 160, 0x8100);			/* Power requirement */
    put_le16(p + 161, 0x8001);			/* CF command set */

J
John Snow 已提交
339
    ide_cfata_identify_size(s);
340 341 342 343 344 345
    s->identify_set = 1;

fill_buffer:
    memcpy(s->io_buffer, p, sizeof(s->identify_data));
}

B
bellard 已提交
346 347 348 349 350 351
static void ide_set_signature(IDEState *s)
{
    s->select &= 0xf0; /* clear head */
    /* put signature */
    s->nsector = 1;
    s->sector = 1;
352
    if (s->drive_kind == IDE_CD) {
B
bellard 已提交
353 354
        s->lcyl = 0x14;
        s->hcyl = 0xeb;
355
    } else if (s->blk) {
B
bellard 已提交
356 357 358 359 360 361 362 363
        s->lcyl = 0;
        s->hcyl = 0;
    } else {
        s->lcyl = 0xff;
        s->hcyl = 0xff;
    }
}

C
Christoph Hellwig 已提交
364
typedef struct TrimAIOCB {
365
    BlockAIOCB common;
366
    BlockBackend *blk;
C
Christoph Hellwig 已提交
367 368
    QEMUBH *bh;
    int ret;
369
    QEMUIOVector *qiov;
370
    BlockAIOCB *aiocb;
371
    int i, j;
C
Christoph Hellwig 已提交
372 373
} TrimAIOCB;

374
static void trim_aio_cancel(BlockAIOCB *acb)
C
Christoph Hellwig 已提交
375 376 377
{
    TrimAIOCB *iocb = container_of(acb, TrimAIOCB, common);

378
    /* Exit the loop so ide_issue_trim_cb will not continue  */
379 380 381
    iocb->j = iocb->qiov->niov - 1;
    iocb->i = (iocb->qiov->iov[iocb->j].iov_len / 8) - 1;

382
    iocb->ret = -ECANCELED;
383 384

    if (iocb->aiocb) {
385
        blk_aio_cancel_async(iocb->aiocb);
386
        iocb->aiocb = NULL;
387
    }
C
Christoph Hellwig 已提交
388 389
}

S
Stefan Hajnoczi 已提交
390
static const AIOCBInfo trim_aiocb_info = {
C
Christoph Hellwig 已提交
391
    .aiocb_size         = sizeof(TrimAIOCB),
392
    .cancel_async       = trim_aio_cancel,
C
Christoph Hellwig 已提交
393 394 395 396 397 398 399 400 401 402
};

static void ide_trim_bh_cb(void *opaque)
{
    TrimAIOCB *iocb = opaque;

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

    qemu_bh_delete(iocb->bh);
    iocb->bh = NULL;
403
    qemu_aio_unref(iocb);
C
Christoph Hellwig 已提交
404 405
}

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
static void ide_issue_trim_cb(void *opaque, int ret)
{
    TrimAIOCB *iocb = opaque;
    if (ret >= 0) {
        while (iocb->j < iocb->qiov->niov) {
            int j = iocb->j;
            while (++iocb->i < iocb->qiov->iov[j].iov_len / 8) {
                int i = iocb->i;
                uint64_t *buffer = iocb->qiov->iov[j].iov_base;

                /* 6-byte LBA + 2-byte range per entry */
                uint64_t entry = le64_to_cpu(buffer[i]);
                uint64_t sector = entry & 0x0000ffffffffffffULL;
                uint16_t count = entry >> 48;

                if (count == 0) {
                    continue;
                }

                /* Got an entry! Submit and exit.  */
426 427
                iocb->aiocb = blk_aio_discard(iocb->blk, sector, count,
                                              ide_issue_trim_cb, opaque);
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
                return;
            }

            iocb->j++;
            iocb->i = -1;
        }
    } else {
        iocb->ret = ret;
    }

    iocb->aiocb = NULL;
    if (iocb->bh) {
        qemu_bh_schedule(iocb->bh);
    }
}

444
BlockAIOCB *ide_issue_trim(BlockBackend *blk,
C
Christoph Hellwig 已提交
445
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
446
        BlockCompletionFunc *cb, void *opaque)
C
Christoph Hellwig 已提交
447 448 449
{
    TrimAIOCB *iocb;

450
    iocb = blk_aio_get(&trim_aiocb_info, blk, cb, opaque);
451
    iocb->blk = blk;
C
Christoph Hellwig 已提交
452 453
    iocb->bh = qemu_bh_new(ide_trim_bh_cb, iocb);
    iocb->ret = 0;
454 455 456 457
    iocb->qiov = qiov;
    iocb->i = -1;
    iocb->j = 0;
    ide_issue_trim_cb(iocb, 0);
C
Christoph Hellwig 已提交
458 459 460
    return &iocb->common;
}

461
void ide_abort_command(IDEState *s)
B
bellard 已提交
462
{
P
Paolo Bonzini 已提交
463
    ide_transfer_stop(s);
B
bellard 已提交
464 465 466 467 468
    s->status = READY_STAT | ERR_STAT;
    s->error = ABRT_ERR;
}

/* prepare data transfer and tell what to do after */
K
Kevin Wolf 已提交
469 470
void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
                        EndTransferFunc *end_transfer_func)
B
bellard 已提交
471 472 473 474
{
    s->end_transfer_func = end_transfer_func;
    s->data_ptr = buf;
    s->data_end = buf + size;
475
    if (!(s->status & ERR_STAT)) {
476
        s->status |= DRQ_STAT;
477
    }
478 479 480
    if (s->bus->dma->ops->start_transfer) {
        s->bus->dma->ops->start_transfer(s->bus->dma);
    }
B
bellard 已提交
481 482
}

483 484 485 486 487 488 489
static void ide_cmd_done(IDEState *s)
{
    if (s->bus->dma->ops->cmd_done) {
        s->bus->dma->ops->cmd_done(s->bus->dma);
    }
}

K
Kevin Wolf 已提交
490
void ide_transfer_stop(IDEState *s)
B
bellard 已提交
491 492 493 494 495
{
    s->end_transfer_func = ide_transfer_stop;
    s->data_ptr = s->io_buffer;
    s->data_end = s->io_buffer;
    s->status &= ~DRQ_STAT;
496
    ide_cmd_done(s);
B
bellard 已提交
497 498
}

G
Gerd Hoffmann 已提交
499
int64_t ide_get_sector(IDEState *s)
B
bellard 已提交
500 501 502 503
{
    int64_t sector_num;
    if (s->select & 0x40) {
        /* lba */
B
bellard 已提交
504 505 506 507 508 509 510 511 512 513
	if (!s->lba48) {
	    sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
		(s->lcyl << 8) | s->sector;
	} else {
	    sector_num = ((int64_t)s->hob_hcyl << 40) |
		((int64_t) s->hob_lcyl << 32) |
		((int64_t) s->hob_sector << 24) |
		((int64_t) s->hcyl << 16) |
		((int64_t) s->lcyl << 8) | s->sector;
	}
B
bellard 已提交
514 515
    } else {
        sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
B
bellard 已提交
516
            (s->select & 0x0f) * s->sectors + (s->sector - 1);
B
bellard 已提交
517 518 519 520
    }
    return sector_num;
}

G
Gerd Hoffmann 已提交
521
void ide_set_sector(IDEState *s, int64_t sector_num)
B
bellard 已提交
522 523 524
{
    unsigned int cyl, r;
    if (s->select & 0x40) {
B
bellard 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537
	if (!s->lba48) {
            s->select = (s->select & 0xf0) | (sector_num >> 24);
            s->hcyl = (sector_num >> 16);
            s->lcyl = (sector_num >> 8);
            s->sector = (sector_num);
	} else {
	    s->sector = sector_num;
	    s->lcyl = sector_num >> 8;
	    s->hcyl = sector_num >> 16;
	    s->hob_sector = sector_num >> 24;
	    s->hob_lcyl = sector_num >> 32;
	    s->hob_hcyl = sector_num >> 40;
	}
B
bellard 已提交
538 539 540 541 542
    } else {
        cyl = sector_num / (s->heads * s->sectors);
        r = sector_num % (s->heads * s->sectors);
        s->hcyl = cyl >> 8;
        s->lcyl = cyl;
543
        s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f);
B
bellard 已提交
544 545 546 547
        s->sector = (r % s->sectors) + 1;
    }
}

548 549
static void ide_rw_error(IDEState *s) {
    ide_abort_command(s);
550
    ide_set_irq(s->bus);
551 552
}

553 554 555 556 557
static bool ide_sect_range_ok(IDEState *s,
                              uint64_t sector, uint64_t nb_sectors)
{
    uint64_t total_sectors;

558
    blk_get_geometry(s->blk, &total_sectors);
559 560 561 562 563 564
    if (sector > total_sectors || nb_sectors > total_sectors - sector) {
        return false;
    }
    return true;
}

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
static void ide_buffered_readv_cb(void *opaque, int ret)
{
    IDEBufferedRequest *req = opaque;
    if (!req->orphaned) {
        if (!ret) {
            qemu_iovec_from_buf(req->original_qiov, 0, req->iov.iov_base,
                                req->original_qiov->size);
        }
        req->original_cb(req->original_opaque, ret);
    }
    QLIST_REMOVE(req, list);
    qemu_vfree(req->iov.iov_base);
    g_free(req);
}

#define MAX_BUFFERED_REQS 16

BlockAIOCB *ide_buffered_readv(IDEState *s, int64_t sector_num,
                               QEMUIOVector *iov, int nb_sectors,
                               BlockCompletionFunc *cb, void *opaque)
{
    BlockAIOCB *aioreq;
    IDEBufferedRequest *req;
    int c = 0;

    QLIST_FOREACH(req, &s->buffered_requests, list) {
        c++;
    }
    if (c > MAX_BUFFERED_REQS) {
        return blk_abort_aio_request(s->blk, cb, opaque, -EIO);
    }

    req = g_new0(IDEBufferedRequest, 1);
    req->original_qiov = iov;
    req->original_cb = cb;
    req->original_opaque = opaque;
    req->iov.iov_base = qemu_blockalign(blk_bs(s->blk), iov->size);
    req->iov.iov_len = iov->size;
    qemu_iovec_init_external(&req->qiov, &req->iov, 1);

    aioreq = blk_aio_readv(s->blk, sector_num, &req->qiov, nb_sectors,
                           ide_buffered_readv_cb, req);

    QLIST_INSERT_HEAD(&s->buffered_requests, req, list);
    return aioreq;
}

P
Paolo Bonzini 已提交
612 613
static void ide_sector_read(IDEState *s);

614 615 616 617 618 619 620 621
static void ide_sector_read_cb(void *opaque, int ret)
{
    IDEState *s = opaque;
    int n;

    s->pio_aiocb = NULL;
    s->status &= ~BUSY_STAT;

622 623 624
    if (ret == -ECANCELED) {
        return;
    }
625
    if (ret != 0) {
626 627
        if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO |
                                IDE_RETRY_READ)) {
628 629 630 631
            return;
        }
    }

632 633
    block_acct_done(blk_get_stats(s->blk), &s->acct);

634 635 636 637 638 639 640
    n = s->nsector;
    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
    }

    ide_set_sector(s, ide_get_sector(s) + n);
    s->nsector -= n;
641 642 643
    /* Allow the guest to read the io_buffer */
    ide_transfer_start(s, s->io_buffer, n * BDRV_SECTOR_SIZE, ide_sector_read);
    ide_set_irq(s->bus);
644 645
}

P
Paolo Bonzini 已提交
646
static void ide_sector_read(IDEState *s)
B
bellard 已提交
647 648
{
    int64_t sector_num;
649
    int n;
B
bellard 已提交
650 651

    s->status = READY_STAT | SEEK_STAT;
652
    s->error = 0; /* not needed by IDE spec, but needed by Windows */
B
bellard 已提交
653 654
    sector_num = ide_get_sector(s);
    n = s->nsector;
655

B
bellard 已提交
656 657
    if (n == 0) {
        ide_transfer_stop(s);
658 659 660 661 662 663 664 665 666
        return;
    }

    s->status |= BUSY_STAT;

    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
    }

B
bellard 已提交
667
#if defined(DEBUG_IDE)
668
    printf("sector=%" PRId64 "\n", sector_num);
B
bellard 已提交
669
#endif
670

671 672
    if (!ide_sect_range_ok(s, sector_num, n)) {
        ide_rw_error(s);
673
        block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_READ);
674 675 676
        return;
    }

677 678 679 680
    s->iov.iov_base = s->io_buffer;
    s->iov.iov_len  = n * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&s->qiov, &s->iov, 1);

681
    block_acct_start(blk_get_stats(s->blk), &s->acct,
682
                     n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
683 684
    s->pio_aiocb = ide_buffered_readv(s, sector_num, &s->qiov, n,
                                      ide_sector_read_cb, s);
B
bellard 已提交
685 686
}

687
void dma_buf_commit(IDEState *s, uint32_t tx_bytes)
688
{
689 690 691
    if (s->bus->dma->ops->commit_buf) {
        s->bus->dma->ops->commit_buf(s->bus->dma, tx_bytes);
    }
692
    s->io_buffer_offset += tx_bytes;
693
    qemu_sglist_destroy(&s->sg);
694 695
}

696
void ide_set_inactive(IDEState *s, bool more)
K
Kevin Wolf 已提交
697
{
698
    s->bus->dma->aiocb = NULL;
699
    s->bus->retry_unit = -1;
700 701
    s->bus->retry_sector_num = 0;
    s->bus->retry_nsector = 0;
702
    if (s->bus->dma->ops->set_inactive) {
703
        s->bus->dma->ops->set_inactive(s->bus->dma, more);
704
    }
705
    ide_cmd_done(s);
K
Kevin Wolf 已提交
706 707
}

G
Gerd Hoffmann 已提交
708
void ide_dma_error(IDEState *s)
709
{
710
    dma_buf_commit(s, 0);
P
Paolo Bonzini 已提交
711
    ide_abort_command(s);
712
    ide_set_inactive(s, false);
713
    ide_set_irq(s->bus);
714 715
}

K
Kevin Wolf 已提交
716
static int ide_handle_rw_error(IDEState *s, int error, int op)
717
{
718
    bool is_read = (op & IDE_RETRY_READ) != 0;
719
    BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
720

W
Wenchao Xia 已提交
721
    if (action == BLOCK_ERROR_ACTION_STOP) {
722
        assert(s->bus->retry_unit == s->unit);
723
        s->bus->error_status = op;
W
Wenchao Xia 已提交
724
    } else if (action == BLOCK_ERROR_ACTION_REPORT) {
725
        block_acct_failed(blk_get_stats(s->blk), &s->acct);
726
        if (op & IDE_RETRY_DMA) {
727
            ide_dma_error(s);
728
        } else {
729
            ide_rw_error(s);
730
        }
731
    }
732
    blk_error_action(s->blk, action, is_read, error);
W
Wenchao Xia 已提交
733
    return action != BLOCK_ERROR_ACTION_IGNORE;
734 735
}

P
Paolo Bonzini 已提交
736
static void ide_dma_cb(void *opaque, int ret)
B
bellard 已提交
737
{
738
    IDEState *s = opaque;
739 740
    int n;
    int64_t sector_num;
K
Kevin Wolf 已提交
741
    bool stay_active = false;
742

743 744 745
    if (ret == -ECANCELED) {
        return;
    }
746
    if (ret < 0) {
747
        int op = IDE_RETRY_DMA;
748

749
        if (s->dma_cmd == IDE_DMA_READ)
750
            op |= IDE_RETRY_READ;
C
Christoph Hellwig 已提交
751
        else if (s->dma_cmd == IDE_DMA_TRIM)
752
            op |= IDE_RETRY_TRIM;
C
Christoph Hellwig 已提交
753

754
        if (ide_handle_rw_error(s, -ret, op)) {
K
Kevin Wolf 已提交
755 756
            return;
        }
757 758
    }

759
    n = s->io_buffer_size >> 9;
K
Kevin Wolf 已提交
760 761 762 763 764 765 766 767
    if (n > s->nsector) {
        /* The PRDs were longer than needed for this request. Shorten them so
         * we don't get a negative remainder. The Active bit must remain set
         * after the request completes. */
        n = s->nsector;
        stay_active = true;
    }

768 769
    sector_num = ide_get_sector(s);
    if (n > 0) {
J
John Snow 已提交
770 771
        assert(n * 512 == s->sg.size);
        dma_buf_commit(s, s->sg.size);
772 773 774 775 776 777 778
        sector_num += n;
        ide_set_sector(s, sector_num);
        s->nsector -= n;
    }

    /* end of transfer ? */
    if (s->nsector == 0) {
B
bellard 已提交
779
        s->status = READY_STAT | SEEK_STAT;
780
        ide_set_irq(s->bus);
781
        goto eot;
B
bellard 已提交
782
    }
783 784 785

    /* launch next transfer */
    n = s->nsector;
786
    s->io_buffer_index = 0;
787
    s->io_buffer_size = n * 512;
J
John Snow 已提交
788
    if (s->bus->dma->ops->prepare_buf(s->bus->dma, s->io_buffer_size) < 512) {
789 790
        /* The PRDs were too short. Reset the Active bit, but don't raise an
         * interrupt. */
791
        s->status = READY_STAT | SEEK_STAT;
792
        dma_buf_commit(s, 0);
793
        goto eot;
794
    }
795

796
#ifdef DEBUG_AIO
797 798
    printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",
           sector_num, n, s->dma_cmd);
799
#endif
800

801 802
    if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) &&
        !ide_sect_range_ok(s, sector_num, n)) {
803
        ide_dma_error(s);
804
        block_acct_invalid(blk_get_stats(s->blk), s->acct.type);
805 806 807
        return;
    }

808 809
    switch (s->dma_cmd) {
    case IDE_DMA_READ:
810 811
        s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, sector_num,
                                          ide_dma_cb, s);
812 813
        break;
    case IDE_DMA_WRITE:
814 815
        s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, sector_num,
                                           ide_dma_cb, s);
816
        break;
C
Christoph Hellwig 已提交
817
    case IDE_DMA_TRIM:
818 819 820
        s->bus->dma->aiocb = dma_blk_io(s->blk, &s->sg, sector_num,
                                        ide_issue_trim, ide_dma_cb, s,
                                        DMA_DIRECTION_TO_DEVICE);
C
Christoph Hellwig 已提交
821
        break;
822 823 824 825
    }
    return;

eot:
826
    if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
827
        block_acct_done(blk_get_stats(s->blk), &s->acct);
828
    }
829
    ide_set_inactive(s, stay_active);
B
bellard 已提交
830 831
}

832
static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd)
B
bellard 已提交
833
{
834
    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
B
bellard 已提交
835
    s->io_buffer_size = 0;
836
    s->dma_cmd = dma_cmd;
837 838 839

    switch (dma_cmd) {
    case IDE_DMA_READ:
840
        block_acct_start(blk_get_stats(s->blk), &s->acct,
841
                         s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
842 843
        break;
    case IDE_DMA_WRITE:
844
        block_acct_start(blk_get_stats(s->blk), &s->acct,
845
                         s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
846 847 848 849 850
        break;
    default:
        break;
    }

P
Paolo Bonzini 已提交
851 852 853
    ide_start_dma(s, ide_dma_cb);
}

854
void ide_start_dma(IDEState *s, BlockCompletionFunc *cb)
P
Paolo Bonzini 已提交
855
{
856
    s->io_buffer_index = 0;
857
    s->bus->retry_unit = s->unit;
858 859
    s->bus->retry_sector_num = ide_get_sector(s);
    s->bus->retry_nsector = s->nsector;
P
Paolo Bonzini 已提交
860 861 862
    if (s->bus->dma->ops->start_dma) {
        s->bus->dma->ops->start_dma(s->bus->dma, s, cb);
    }
B
bellard 已提交
863 864
}

P
Paolo Bonzini 已提交
865 866
static void ide_sector_write(IDEState *s);

867 868 869
static void ide_sector_write_timer_cb(void *opaque)
{
    IDEState *s = opaque;
870
    ide_set_irq(s->bus);
871 872
}

873
static void ide_sector_write_cb(void *opaque, int ret)
B
bellard 已提交
874
{
875 876
    IDEState *s = opaque;
    int n;
877

878 879 880
    if (ret == -ECANCELED) {
        return;
    }
881

882 883 884
    s->pio_aiocb = NULL;
    s->status &= ~BUSY_STAT;

885
    if (ret != 0) {
886
        if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO)) {
887
            return;
888
        }
889 890
    }

891 892
    block_acct_done(blk_get_stats(s->blk), &s->acct);

893 894 895 896
    n = s->nsector;
    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
    }
B
bellard 已提交
897
    s->nsector -= n;
898

899
    ide_set_sector(s, ide_get_sector(s) + n);
B
bellard 已提交
900
    if (s->nsector == 0) {
T
ths 已提交
901
        /* no more sectors to write */
B
bellard 已提交
902 903
        ide_transfer_stop(s);
    } else {
904 905
        int n1 = s->nsector;
        if (n1 > s->req_nb_sectors) {
B
bellard 已提交
906
            n1 = s->req_nb_sectors;
907 908 909
        }
        ide_transfer_start(s, s->io_buffer, n1 * BDRV_SECTOR_SIZE,
                           ide_sector_write);
B
bellard 已提交
910
    }
911

912 913 914 915 916 917 918
    if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {
        /* It seems there is a bug in the Windows 2000 installer HDD
           IDE driver which fills the disk with empty logs when the
           IDE write IRQ comes too early. This hack tries to correct
           that at the expense of slower write performances. Use this
           option _only_ to install Windows 2000. You must disable it
           for normal use. */
919 920
        timer_mod(s->sector_write_timer,
                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + (get_ticks_per_sec() / 1000));
B
Blue Swirl 已提交
921
    } else {
922
        ide_set_irq(s->bus);
923
    }
B
bellard 已提交
924 925
}

P
Paolo Bonzini 已提交
926
static void ide_sector_write(IDEState *s)
927 928 929 930 931 932 933 934 935 936 937 938 939 940
{
    int64_t sector_num;
    int n;

    s->status = READY_STAT | SEEK_STAT | BUSY_STAT;
    sector_num = ide_get_sector(s);
#if defined(DEBUG_IDE)
    printf("sector=%" PRId64 "\n", sector_num);
#endif
    n = s->nsector;
    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
    }

941 942
    if (!ide_sect_range_ok(s, sector_num, n)) {
        ide_rw_error(s);
943
        block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
944 945 946
        return;
    }

947 948 949 950
    s->iov.iov_base = s->io_buffer;
    s->iov.iov_len  = n * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&s->qiov, &s->iov, 1);

951
    block_acct_start(blk_get_stats(s->blk), &s->acct,
952
                     n * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
953 954
    s->pio_aiocb = blk_aio_writev(s->blk, sector_num, &s->qiov, n,
                                  ide_sector_write_cb, s);
955 956
}

C
Christoph Hellwig 已提交
957 958 959 960
static void ide_flush_cb(void *opaque, int ret)
{
    IDEState *s = opaque;

P
Paolo Bonzini 已提交
961 962
    s->pio_aiocb = NULL;

963 964 965
    if (ret == -ECANCELED) {
        return;
    }
K
Kevin Wolf 已提交
966 967
    if (ret < 0) {
        /* XXX: What sector number to set here? */
968
        if (ide_handle_rw_error(s, -ret, IDE_RETRY_FLUSH)) {
K
Kevin Wolf 已提交
969 970 971
            return;
        }
    }
C
Christoph Hellwig 已提交
972

973 974
    if (s->blk) {
        block_acct_done(blk_get_stats(s->blk), &s->acct);
975
    }
C
Christoph Hellwig 已提交
976
    s->status = READY_STAT | SEEK_STAT;
977
    ide_cmd_done(s);
C
Christoph Hellwig 已提交
978 979 980
    ide_set_irq(s->bus);
}

P
Paolo Bonzini 已提交
981
static void ide_flush_cache(IDEState *s)
K
Kevin Wolf 已提交
982
{
983
    if (s->blk == NULL) {
K
Kevin Wolf 已提交
984
        ide_flush_cb(s, 0);
985 986 987
        return;
    }

A
Andreas Färber 已提交
988
    s->status |= BUSY_STAT;
989 990
    block_acct_start(blk_get_stats(s->blk), &s->acct, 0, BLOCK_ACCT_FLUSH);
    s->pio_aiocb = blk_aio_flush(s->blk, ide_flush_cb, s);
K
Kevin Wolf 已提交
991 992
}

993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
static void ide_cfata_metadata_inquiry(IDEState *s)
{
    uint16_t *p;
    uint32_t spd;

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

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

static void ide_cfata_metadata_read(IDEState *s)
{
    uint16_t *p;

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

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

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

static void ide_cfata_metadata_write(IDEState *s)
{
    if (((s->hcyl << 16) | s->lcyl) << 9 > s->mdata_size + 2) {
        s->status = ERR_STAT;
        s->error = ABRT_ERR;
        return;
    }

    s->media_changed = 0;

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

T
ths 已提交
1046
/* called when the inserted state of the media has changed */
1047
static void ide_cd_change_cb(void *opaque, bool load)
T
ths 已提交
1048 1049
{
    IDEState *s = opaque;
1050
    uint64_t nb_sectors;
T
ths 已提交
1051

1052
    s->tray_open = !load;
1053
    blk_get_geometry(s->blk, &nb_sectors);
T
ths 已提交
1054
    s->nb_sectors = nb_sectors;
1055

1056 1057 1058 1059
    /*
     * First indicate to the guest that a CD has been removed.  That's
     * done on the next command the guest sends us.
     *
1060
     * Then we set UNIT_ATTENTION, by which the guest will
1061 1062
     * detect a new CD in the drive.  See ide_atapi_cmd() for details.
     */
G
Gleb Natapov 已提交
1063
    s->cdrom_changed = 1;
1064
    s->events.new_media = true;
P
Paolo Bonzini 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    s->events.eject_request = false;
    ide_set_irq(s->bus);
}

static void ide_cd_eject_request_cb(void *opaque, bool force)
{
    IDEState *s = opaque;

    s->events.eject_request = true;
    if (force) {
        s->tray_locked = false;
    }
1077
    ide_set_irq(s->bus);
T
ths 已提交
1078 1079
}

B
bellard 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
static void ide_cmd_lba48_transform(IDEState *s, int lba48)
{
    s->lba48 = lba48;

    /* handle the 'magic' 0 nsector count conversion here. to avoid
     * fiddling with the rest of the read logic, we just store the
     * full sector count in ->nsector and ignore ->hob_nsector from now
     */
    if (!s->lba48) {
	if (!s->nsector)
	    s->nsector = 256;
    } else {
	if (!s->nsector && !s->hob_nsector)
	    s->nsector = 65536;
	else {
	    int lo = s->nsector;
	    int hi = s->hob_nsector;

	    s->nsector = (hi << 8) | lo;
	}
    }
}

G
Gerd Hoffmann 已提交
1103
static void ide_clear_hob(IDEBus *bus)
B
bellard 已提交
1104 1105
{
    /* any write clears HOB high bit of device control register */
G
Gerd Hoffmann 已提交
1106 1107
    bus->ifs[0].select &= ~(1 << 7);
    bus->ifs[1].select &= ~(1 << 7);
B
bellard 已提交
1108 1109
}

G
Gerd Hoffmann 已提交
1110
void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)
1111
{
G
Gerd Hoffmann 已提交
1112
    IDEBus *bus = opaque;
B
bellard 已提交
1113 1114 1115 1116

#ifdef DEBUG_IDE
    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
#endif
B
bellard 已提交
1117

B
bellard 已提交
1118
    addr &= 7;
1119 1120

    /* ignore writes to command block while busy with previous command */
G
Gerd Hoffmann 已提交
1121
    if (addr != 7 && (idebus_active_if(bus)->status & (BUSY_STAT|DRQ_STAT)))
1122 1123
        return;

B
bellard 已提交
1124 1125 1126 1127
    switch(addr) {
    case 0:
        break;
    case 1:
G
Gerd Hoffmann 已提交
1128
	ide_clear_hob(bus);
1129
        /* NOTE: data is written to the two drives */
G
Gerd Hoffmann 已提交
1130 1131 1132 1133
	bus->ifs[0].hob_feature = bus->ifs[0].feature;
	bus->ifs[1].hob_feature = bus->ifs[1].feature;
        bus->ifs[0].feature = val;
        bus->ifs[1].feature = val;
B
bellard 已提交
1134 1135
        break;
    case 2:
G
Gerd Hoffmann 已提交
1136 1137 1138 1139 1140
	ide_clear_hob(bus);
	bus->ifs[0].hob_nsector = bus->ifs[0].nsector;
	bus->ifs[1].hob_nsector = bus->ifs[1].nsector;
        bus->ifs[0].nsector = val;
        bus->ifs[1].nsector = val;
B
bellard 已提交
1141 1142
        break;
    case 3:
G
Gerd Hoffmann 已提交
1143 1144 1145 1146 1147
	ide_clear_hob(bus);
	bus->ifs[0].hob_sector = bus->ifs[0].sector;
	bus->ifs[1].hob_sector = bus->ifs[1].sector;
        bus->ifs[0].sector = val;
        bus->ifs[1].sector = val;
B
bellard 已提交
1148 1149
        break;
    case 4:
G
Gerd Hoffmann 已提交
1150 1151 1152 1153 1154
	ide_clear_hob(bus);
	bus->ifs[0].hob_lcyl = bus->ifs[0].lcyl;
	bus->ifs[1].hob_lcyl = bus->ifs[1].lcyl;
        bus->ifs[0].lcyl = val;
        bus->ifs[1].lcyl = val;
B
bellard 已提交
1155 1156
        break;
    case 5:
G
Gerd Hoffmann 已提交
1157 1158 1159 1160 1161
	ide_clear_hob(bus);
	bus->ifs[0].hob_hcyl = bus->ifs[0].hcyl;
	bus->ifs[1].hob_hcyl = bus->ifs[1].hcyl;
        bus->ifs[0].hcyl = val;
        bus->ifs[1].hcyl = val;
B
bellard 已提交
1162 1163
        break;
    case 6:
B
bellard 已提交
1164
	/* FIXME: HOB readback uses bit 7 */
G
Gerd Hoffmann 已提交
1165 1166
        bus->ifs[0].select = (val & ~0x10) | 0xa0;
        bus->ifs[1].select = (val | 0x10) | 0xa0;
B
bellard 已提交
1167
        /* select drive */
G
Gerd Hoffmann 已提交
1168
        bus->unit = (val >> 4) & 1;
B
bellard 已提交
1169 1170 1171 1172
        break;
    default:
    case 7:
        /* command */
1173 1174 1175 1176 1177
        ide_exec_cmd(bus, val);
        break;
    }
}

J
John Snow 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
static void ide_reset(IDEState *s)
{
#ifdef DEBUG_IDE
    printf("ide: reset\n");
#endif

    if (s->pio_aiocb) {
        blk_aio_cancel(s->pio_aiocb);
        s->pio_aiocb = NULL;
    }

    if (s->drive_kind == IDE_CFATA)
        s->mult_sectors = 0;
    else
        s->mult_sectors = MAX_MULT_SECTORS;
    /* ide regs */
    s->feature = 0;
    s->error = 0;
    s->nsector = 0;
    s->sector = 0;
    s->lcyl = 0;
    s->hcyl = 0;

    /* lba48 */
    s->hob_feature = 0;
    s->hob_sector = 0;
    s->hob_nsector = 0;
    s->hob_lcyl = 0;
    s->hob_hcyl = 0;

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

    s->lba48 = 0;

    /* ATAPI specific */
    s->sense_key = 0;
    s->asc = 0;
    s->cdrom_changed = 0;
    s->packet_transfer_size = 0;
    s->elementary_transfer_size = 0;
    s->io_buffer_index = 0;
    s->cd_sector_size = 0;
    s->atapi_dma = 0;
    s->tray_locked = 0;
    s->tray_open = 0;
    /* ATA DMA state */
    s->io_buffer_size = 0;
    s->req_nb_sectors = 0;

    ide_set_signature(s);
    /* init the transfer handler so that 0xffff is returned on data
       accesses */
    s->end_transfer_func = ide_dummy_transfer_stop;
    ide_dummy_transfer_stop(s);
    s->media_changed = 0;
}

1236 1237 1238 1239 1240
static bool cmd_nop(IDEState *s, uint8_t cmd)
{
    return true;
}

1241 1242 1243 1244
static bool cmd_data_set_management(IDEState *s, uint8_t cmd)
{
    switch (s->feature) {
    case DSM_TRIM:
1245
        if (s->blk) {
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
            ide_sector_start_dma(s, IDE_DMA_TRIM);
            return false;
        }
        break;
    }

    ide_abort_command(s);
    return true;
}

1256 1257
static bool cmd_identify(IDEState *s, uint8_t cmd)
{
1258
    if (s->blk && s->drive_kind != IDE_CD) {
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
        if (s->drive_kind != IDE_CFATA) {
            ide_identify(s);
        } else {
            ide_cfata_identify(s);
        }
        s->status = READY_STAT | SEEK_STAT;
        ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
        ide_set_irq(s->bus);
        return false;
    } else {
        if (s->drive_kind == IDE_CD) {
            ide_set_signature(s);
        }
        ide_abort_command(s);
    }

    return true;
}

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
static bool cmd_verify(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_VERIFY_EXT);

    /* do sector number check ? */
    ide_cmd_lba48_transform(s, lba48);

    return true;
}

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
static bool cmd_set_multiple_mode(IDEState *s, uint8_t cmd)
{
    if (s->drive_kind == IDE_CFATA && s->nsector == 0) {
        /* Disable Read and Write Multiple */
        s->mult_sectors = 0;
    } else if ((s->nsector & 0xff) != 0 &&
        ((s->nsector & 0xff) > MAX_MULT_SECTORS ||
         (s->nsector & (s->nsector - 1)) != 0)) {
        ide_abort_command(s);
    } else {
        s->mult_sectors = s->nsector & 0xff;
    }

    return true;
}

static bool cmd_read_multiple(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_MULTREAD_EXT);

1308
    if (!s->blk || !s->mult_sectors) {
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);
    s->req_nb_sectors = s->mult_sectors;
    ide_sector_read(s);
    return false;
}

static bool cmd_write_multiple(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_MULTWRITE_EXT);
    int n;

1324
    if (!s->blk || !s->mult_sectors) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);

    s->req_nb_sectors = s->mult_sectors;
    n = MIN(s->nsector, s->req_nb_sectors);

    s->status = SEEK_STAT | READY_STAT;
    ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);

    s->media_changed = 1;

    return false;
}

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
static bool cmd_read_pio(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_READ_EXT);

    if (s->drive_kind == IDE_CD) {
        ide_set_signature(s); /* odd, but ATA4 8.27.5.2 requires it */
        ide_abort_command(s);
        return true;
    }

1352
    if (!s->blk) {
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);
    s->req_nb_sectors = 1;
    ide_sector_read(s);

    return false;
}

static bool cmd_write_pio(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_WRITE_EXT);

1368
    if (!s->blk) {
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);

    s->req_nb_sectors = 1;
    s->status = SEEK_STAT | READY_STAT;
    ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);

    s->media_changed = 1;

    return false;
}

1384 1385 1386 1387
static bool cmd_read_dma(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_READDMA_EXT);

1388
    if (!s->blk) {
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);
    ide_sector_start_dma(s, IDE_DMA_READ);

    return false;
}

static bool cmd_write_dma(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_WRITEDMA_EXT);

1403
    if (!s->blk) {
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);
    ide_sector_start_dma(s, IDE_DMA_WRITE);

    s->media_changed = 1;

    return false;
}

1416 1417 1418 1419 1420 1421
static bool cmd_flush_cache(IDEState *s, uint8_t cmd)
{
    ide_flush_cache(s);
    return false;
}

1422 1423 1424 1425 1426 1427
static bool cmd_seek(IDEState *s, uint8_t cmd)
{
    /* XXX: Check that seek is within bounds */
    return true;
}

1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
static bool cmd_read_native_max(IDEState *s, uint8_t cmd)
{
    bool lba48 = (cmd == WIN_READ_NATIVE_MAX_EXT);

    /* Refuse if no sectors are addressable (e.g. medium not inserted) */
    if (s->nb_sectors == 0) {
        ide_abort_command(s);
        return true;
    }

    ide_cmd_lba48_transform(s, lba48);
    ide_set_sector(s, s->nb_sectors - 1);

    return true;
}

1444 1445 1446 1447 1448 1449
static bool cmd_check_power_mode(IDEState *s, uint8_t cmd)
{
    s->nsector = 0xff; /* device active or idle */
    return true;
}

1450 1451 1452 1453
static bool cmd_set_features(IDEState *s, uint8_t cmd)
{
    uint16_t *identify_data;

1454
    if (!s->blk) {
1455 1456 1457 1458 1459 1460 1461
        ide_abort_command(s);
        return true;
    }

    /* XXX: valid for CDROM ? */
    switch (s->feature) {
    case 0x02: /* write cache enable */
1462
        blk_set_enable_write_cache(s->blk, true);
1463 1464 1465 1466
        identify_data = (uint16_t *)s->identify_data;
        put_le16(identify_data + 85, (1 << 14) | (1 << 5) | 1);
        return true;
    case 0x82: /* write cache disable */
1467
        blk_set_enable_write_cache(s->blk, false);
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
        identify_data = (uint16_t *)s->identify_data;
        put_le16(identify_data + 85, (1 << 14) | 1);
        ide_flush_cache(s);
        return false;
    case 0xcc: /* reverting to power-on defaults enable */
    case 0x66: /* reverting to power-on defaults disable */
    case 0xaa: /* read look-ahead enable */
    case 0x55: /* read look-ahead disable */
    case 0x05: /* set advanced power management mode */
    case 0x85: /* disable advanced power management mode */
    case 0x69: /* NOP */
    case 0x67: /* NOP */
    case 0x96: /* NOP */
    case 0x9a: /* NOP */
    case 0x42: /* enable Automatic Acoustic Mode */
    case 0xc2: /* disable Automatic Acoustic Mode */
        return true;
    case 0x03: /* set transfer mode */
        {
            uint8_t val = s->nsector & 0x07;
            identify_data = (uint16_t *)s->identify_data;

            switch (s->nsector >> 3) {
            case 0x00: /* pio default */
            case 0x01: /* pio mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x02: /* sigle word dma mode*/
                put_le16(identify_data + 62, 0x07 | (1 << (val + 8)));
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x04: /* mdma mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07 | (1 << (val + 8)));
                put_le16(identify_data + 88, 0x3f);
                break;
            case 0x08: /* udma mode */
                put_le16(identify_data + 62, 0x07);
                put_le16(identify_data + 63, 0x07);
                put_le16(identify_data + 88, 0x3f | (1 << (val + 8)));
                break;
            default:
                goto abort_cmd;
            }
            return true;
        }
    }

abort_cmd:
    ide_abort_command(s);
    return true;
}

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

/*** ATAPI commands ***/

static bool cmd_identify_packet(IDEState *s, uint8_t cmd)
{
    ide_atapi_identify(s);
    s->status = READY_STAT | SEEK_STAT;
    ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
    ide_set_irq(s->bus);
    return false;
}

static bool cmd_exec_dev_diagnostic(IDEState *s, uint8_t cmd)
{
    ide_set_signature(s);

    if (s->drive_kind == IDE_CD) {
        s->status = 0; /* ATAPI spec (v6) section 9.10 defines packet
                        * devices to return a clear status register
                        * with READY_STAT *not* set. */
1544
        s->error = 0x01;
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    } else {
        s->status = READY_STAT | SEEK_STAT;
        /* The bits of the error register are not as usual for this command!
         * They are part of the regular output (this is why ERR_STAT isn't set)
         * Device 0 passed, Device 1 passed or not present. */
        s->error = 0x01;
        ide_set_irq(s->bus);
    }

    return false;
}

static bool cmd_device_reset(IDEState *s, uint8_t cmd)
{
    ide_set_signature(s);
    s->status = 0x00; /* NOTE: READY is _not_ set */
    s->error = 0x01;

    return false;
}

static bool cmd_packet(IDEState *s, uint8_t cmd)
{
    /* overlapping commands not supported */
    if (s->feature & 0x02) {
        ide_abort_command(s);
        return true;
    }

    s->status = READY_STAT | SEEK_STAT;
    s->atapi_dma = s->feature & 1;
    s->nsector = 1;
    ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
                       ide_atapi_cmd);
    return false;
}

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

/*** CF-ATA commands ***/

static bool cmd_cfa_req_ext_error_code(IDEState *s, uint8_t cmd)
{
    s->error = 0x09;    /* miscellaneous error */
    s->status = READY_STAT | SEEK_STAT;
    ide_set_irq(s->bus);

    return false;
}

static bool cmd_cfa_erase_sectors(IDEState *s, uint8_t cmd)
{
    /* WIN_SECURITY_FREEZE_LOCK has the same ID as CFA_WEAR_LEVEL and is
     * required for Windows 8 to work with AHCI */

    if (cmd == CFA_WEAR_LEVEL) {
        s->nsector = 0;
    }

    if (cmd == CFA_ERASE_SECTORS) {
        s->media_changed = 1;
    }

    return true;
}

static bool cmd_cfa_translate_sector(IDEState *s, uint8_t cmd)
{
    s->status = READY_STAT | SEEK_STAT;

    memset(s->io_buffer, 0, 0x200);
    s->io_buffer[0x00] = s->hcyl;                   /* Cyl MSB */
    s->io_buffer[0x01] = s->lcyl;                   /* Cyl LSB */
    s->io_buffer[0x02] = s->select;                 /* Head */
    s->io_buffer[0x03] = s->sector;                 /* Sector */
    s->io_buffer[0x04] = ide_get_sector(s) >> 16;   /* LBA MSB */
    s->io_buffer[0x05] = ide_get_sector(s) >> 8;    /* LBA */
    s->io_buffer[0x06] = ide_get_sector(s) >> 0;    /* LBA LSB */
    s->io_buffer[0x13] = 0x00;                      /* Erase flag */
    s->io_buffer[0x18] = 0x00;                      /* Hot count */
    s->io_buffer[0x19] = 0x00;                      /* Hot count */
    s->io_buffer[0x1a] = 0x01;                      /* Hot count */

    ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
    ide_set_irq(s->bus);

    return false;
}

static bool cmd_cfa_access_metadata_storage(IDEState *s, uint8_t cmd)
{
    switch (s->feature) {
    case 0x02:  /* Inquiry Metadata Storage */
        ide_cfata_metadata_inquiry(s);
        break;
    case 0x03:  /* Read Metadata Storage */
        ide_cfata_metadata_read(s);
        break;
    case 0x04:  /* Write Metadata Storage */
        ide_cfata_metadata_write(s);
        break;
    default:
        ide_abort_command(s);
        return true;
    }

    ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
    s->status = 0x00; /* NOTE: READY is _not_ set */
    ide_set_irq(s->bus);

    return false;
}

static bool cmd_ibm_sense_condition(IDEState *s, uint8_t cmd)
{
    switch (s->feature) {
    case 0x01:  /* sense temperature in device */
        s->nsector = 0x50;      /* +20 C */
        break;
    default:
        ide_abort_command(s);
        return true;
    }

    return true;
}

1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

/*** SMART commands ***/

static bool cmd_smart(IDEState *s, uint8_t cmd)
{
    int n;

    if (s->hcyl != 0xc2 || s->lcyl != 0x4f) {
        goto abort_cmd;
    }

    if (!s->smart_enabled && s->feature != SMART_ENABLE) {
        goto abort_cmd;
    }

    switch (s->feature) {
    case SMART_DISABLE:
        s->smart_enabled = 0;
        return true;

    case SMART_ENABLE:
        s->smart_enabled = 1;
        return true;

    case SMART_ATTR_AUTOSAVE:
        switch (s->sector) {
        case 0x00:
            s->smart_autosave = 0;
            break;
        case 0xf1:
            s->smart_autosave = 1;
            break;
        default:
            goto abort_cmd;
        }
        return true;

    case SMART_STATUS:
        if (!s->smart_errors) {
            s->hcyl = 0xc2;
            s->lcyl = 0x4f;
        } else {
            s->hcyl = 0x2c;
            s->lcyl = 0xf4;
        }
        return true;

    case SMART_READ_THRESH:
        memset(s->io_buffer, 0, 0x200);
        s->io_buffer[0] = 0x01; /* smart struct version */

        for (n = 0; n < ARRAY_SIZE(smart_attributes); n++) {
            s->io_buffer[2 + 0 + (n * 12)] = smart_attributes[n][0];
            s->io_buffer[2 + 1 + (n * 12)] = smart_attributes[n][11];
        }

        /* checksum */
        for (n = 0; n < 511; n++) {
            s->io_buffer[511] += s->io_buffer[n];
        }
        s->io_buffer[511] = 0x100 - s->io_buffer[511];

        s->status = READY_STAT | SEEK_STAT;
        ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
        ide_set_irq(s->bus);
        return false;

    case SMART_READ_DATA:
        memset(s->io_buffer, 0, 0x200);
        s->io_buffer[0] = 0x01; /* smart struct version */

        for (n = 0; n < ARRAY_SIZE(smart_attributes); n++) {
            int i;
            for (i = 0; i < 11; i++) {
                s->io_buffer[2 + i + (n * 12)] = smart_attributes[n][i];
            }
        }

        s->io_buffer[362] = 0x02 | (s->smart_autosave ? 0x80 : 0x00);
        if (s->smart_selftest_count == 0) {
            s->io_buffer[363] = 0;
        } else {
            s->io_buffer[363] =
                s->smart_selftest_data[3 +
                           (s->smart_selftest_count - 1) *
                           24];
        }
        s->io_buffer[364] = 0x20;
        s->io_buffer[365] = 0x01;
        /* offline data collection capacity: execute + self-test*/
        s->io_buffer[367] = (1 << 4 | 1 << 3 | 1);
        s->io_buffer[368] = 0x03; /* smart capability (1) */
        s->io_buffer[369] = 0x00; /* smart capability (2) */
        s->io_buffer[370] = 0x01; /* error logging supported */
        s->io_buffer[372] = 0x02; /* minutes for poll short test */
        s->io_buffer[373] = 0x36; /* minutes for poll ext test */
        s->io_buffer[374] = 0x01; /* minutes for poll conveyance */

        for (n = 0; n < 511; n++) {
            s->io_buffer[511] += s->io_buffer[n];
        }
        s->io_buffer[511] = 0x100 - s->io_buffer[511];

        s->status = READY_STAT | SEEK_STAT;
        ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
        ide_set_irq(s->bus);
        return false;

    case SMART_READ_LOG:
        switch (s->sector) {
        case 0x01: /* summary smart error log */
            memset(s->io_buffer, 0, 0x200);
            s->io_buffer[0] = 0x01;
            s->io_buffer[1] = 0x00; /* no error entries */
            s->io_buffer[452] = s->smart_errors & 0xff;
            s->io_buffer[453] = (s->smart_errors & 0xff00) >> 8;

            for (n = 0; n < 511; n++) {
                s->io_buffer[511] += s->io_buffer[n];
            }
            s->io_buffer[511] = 0x100 - s->io_buffer[511];
            break;
        case 0x06: /* smart self test log */
            memset(s->io_buffer, 0, 0x200);
            s->io_buffer[0] = 0x01;
            if (s->smart_selftest_count == 0) {
                s->io_buffer[508] = 0;
            } else {
                s->io_buffer[508] = s->smart_selftest_count;
                for (n = 2; n < 506; n++)  {
                    s->io_buffer[n] = s->smart_selftest_data[n];
                }
            }

            for (n = 0; n < 511; n++) {
                s->io_buffer[511] += s->io_buffer[n];
            }
            s->io_buffer[511] = 0x100 - s->io_buffer[511];
            break;
        default:
            goto abort_cmd;
        }
        s->status = READY_STAT | SEEK_STAT;
        ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);
        ide_set_irq(s->bus);
        return false;

    case SMART_EXECUTE_OFFLINE:
        switch (s->sector) {
        case 0: /* off-line routine */
        case 1: /* short self test */
        case 2: /* extended self test */
            s->smart_selftest_count++;
            if (s->smart_selftest_count > 21) {
1825
                s->smart_selftest_count = 1;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
            }
            n = 2 + (s->smart_selftest_count - 1) * 24;
            s->smart_selftest_data[n] = s->sector;
            s->smart_selftest_data[n + 1] = 0x00; /* OK and finished */
            s->smart_selftest_data[n + 2] = 0x34; /* hour count lsb */
            s->smart_selftest_data[n + 3] = 0x12; /* hour count msb */
            break;
        default:
            goto abort_cmd;
        }
        return true;
    }

abort_cmd:
    ide_abort_command(s);
    return true;
}

1844 1845 1846 1847 1848 1849
#define HD_OK (1u << IDE_HD)
#define CD_OK (1u << IDE_CD)
#define CFA_OK (1u << IDE_CFATA)
#define HD_CFA_OK (HD_OK | CFA_OK)
#define ALL_OK (HD_OK | CD_OK | CFA_OK)

K
Kevin Wolf 已提交
1850 1851 1852
/* Set the Disk Seek Completed status bit during completion */
#define SET_DSC (1u << 8)

1853
/* See ACS-2 T13/2015-D Table B.2 Command codes */
K
Kevin Wolf 已提交
1854 1855 1856 1857 1858
static const struct {
    /* Returns true if the completion code should be run */
    bool (*handler)(IDEState *s, uint8_t cmd);
    int flags;
} ide_cmd_table[0x100] = {
1859
    /* NOP not implemented, mandatory for CD */
1860
    [CFA_REQ_EXT_ERROR_CODE]      = { cmd_cfa_req_ext_error_code, CFA_OK },
J
John Snow 已提交
1861
    [WIN_DSM]                     = { cmd_data_set_management, HD_CFA_OK },
1862
    [WIN_DEVICE_RESET]            = { cmd_device_reset, CD_OK },
1863
    [WIN_RECAL]                   = { cmd_nop, HD_CFA_OK | SET_DSC},
1864
    [WIN_READ]                    = { cmd_read_pio, ALL_OK },
J
John Snow 已提交
1865
    [WIN_READ_ONCE]               = { cmd_read_pio, HD_CFA_OK },
1866
    [WIN_READ_EXT]                = { cmd_read_pio, HD_CFA_OK },
1867
    [WIN_READDMA_EXT]             = { cmd_read_dma, HD_CFA_OK },
1868
    [WIN_READ_NATIVE_MAX_EXT]     = { cmd_read_native_max, HD_CFA_OK | SET_DSC },
1869
    [WIN_MULTREAD_EXT]            = { cmd_read_multiple, HD_CFA_OK },
1870 1871 1872
    [WIN_WRITE]                   = { cmd_write_pio, HD_CFA_OK },
    [WIN_WRITE_ONCE]              = { cmd_write_pio, HD_CFA_OK },
    [WIN_WRITE_EXT]               = { cmd_write_pio, HD_CFA_OK },
1873
    [WIN_WRITEDMA_EXT]            = { cmd_write_dma, HD_CFA_OK },
1874
    [CFA_WRITE_SECT_WO_ERASE]     = { cmd_write_pio, CFA_OK },
1875
    [WIN_MULTWRITE_EXT]           = { cmd_write_multiple, HD_CFA_OK },
1876
    [WIN_WRITE_VERIFY]            = { cmd_write_pio, HD_CFA_OK },
1877 1878 1879
    [WIN_VERIFY]                  = { cmd_verify, HD_CFA_OK | SET_DSC },
    [WIN_VERIFY_ONCE]             = { cmd_verify, HD_CFA_OK | SET_DSC },
    [WIN_VERIFY_EXT]              = { cmd_verify, HD_CFA_OK | SET_DSC },
1880
    [WIN_SEEK]                    = { cmd_seek, HD_CFA_OK | SET_DSC },
1881
    [CFA_TRANSLATE_SECTOR]        = { cmd_cfa_translate_sector, CFA_OK },
1882
    [WIN_DIAGNOSE]                = { cmd_exec_dev_diagnostic, ALL_OK },
1883
    [WIN_SPECIFY]                 = { cmd_nop, HD_CFA_OK | SET_DSC },
J
John Snow 已提交
1884 1885 1886 1887 1888 1889
    [WIN_STANDBYNOW2]             = { cmd_nop, HD_CFA_OK },
    [WIN_IDLEIMMEDIATE2]          = { cmd_nop, HD_CFA_OK },
    [WIN_STANDBY2]                = { cmd_nop, HD_CFA_OK },
    [WIN_SETIDLE2]                = { cmd_nop, HD_CFA_OK },
    [WIN_CHECKPOWERMODE2]         = { cmd_check_power_mode, HD_CFA_OK | SET_DSC },
    [WIN_SLEEPNOW2]               = { cmd_nop, HD_CFA_OK },
1890 1891
    [WIN_PACKETCMD]               = { cmd_packet, CD_OK },
    [WIN_PIDENTIFY]               = { cmd_identify_packet, CD_OK },
1892
    [WIN_SMART]                   = { cmd_smart, HD_CFA_OK | SET_DSC },
1893 1894
    [CFA_ACCESS_METADATA_STORAGE] = { cmd_cfa_access_metadata_storage, CFA_OK },
    [CFA_ERASE_SECTORS]           = { cmd_cfa_erase_sectors, CFA_OK | SET_DSC },
1895 1896 1897
    [WIN_MULTREAD]                = { cmd_read_multiple, HD_CFA_OK },
    [WIN_MULTWRITE]               = { cmd_write_multiple, HD_CFA_OK },
    [WIN_SETMULT]                 = { cmd_set_multiple_mode, HD_CFA_OK | SET_DSC },
1898 1899 1900 1901
    [WIN_READDMA]                 = { cmd_read_dma, HD_CFA_OK },
    [WIN_READDMA_ONCE]            = { cmd_read_dma, HD_CFA_OK },
    [WIN_WRITEDMA]                = { cmd_write_dma, HD_CFA_OK },
    [WIN_WRITEDMA_ONCE]           = { cmd_write_dma, HD_CFA_OK },
1902
    [CFA_WRITE_MULTI_WO_ERASE]    = { cmd_write_multiple, CFA_OK },
J
John Snow 已提交
1903 1904 1905 1906 1907 1908
    [WIN_STANDBYNOW1]             = { cmd_nop, HD_CFA_OK },
    [WIN_IDLEIMMEDIATE]           = { cmd_nop, HD_CFA_OK },
    [WIN_STANDBY]                 = { cmd_nop, HD_CFA_OK },
    [WIN_SETIDLE1]                = { cmd_nop, HD_CFA_OK },
    [WIN_CHECKPOWERMODE1]         = { cmd_check_power_mode, HD_CFA_OK | SET_DSC },
    [WIN_SLEEPNOW1]               = { cmd_nop, HD_CFA_OK },
1909 1910
    [WIN_FLUSH_CACHE]             = { cmd_flush_cache, ALL_OK },
    [WIN_FLUSH_CACHE_EXT]         = { cmd_flush_cache, HD_CFA_OK },
1911
    [WIN_IDENTIFY]                = { cmd_identify, ALL_OK },
1912
    [WIN_SETFEATURES]             = { cmd_set_features, ALL_OK | SET_DSC },
1913 1914
    [IBM_SENSE_CONDITION]         = { cmd_ibm_sense_condition, CFA_OK | SET_DSC },
    [CFA_WEAR_LEVEL]              = { cmd_cfa_erase_sectors, HD_CFA_OK | SET_DSC },
J
John Snow 已提交
1915
    [WIN_READ_NATIVE_MAX]         = { cmd_read_native_max, HD_CFA_OK | SET_DSC },
1916 1917 1918 1919 1920
};

static bool ide_cmd_permitted(IDEState *s, uint32_t cmd)
{
    return cmd < ARRAY_SIZE(ide_cmd_table)
K
Kevin Wolf 已提交
1921
        && (ide_cmd_table[cmd].flags & (1u << s->drive_kind));
1922
}
1923 1924 1925 1926

void ide_exec_cmd(IDEBus *bus, uint32_t val)
{
    IDEState *s;
K
Kevin Wolf 已提交
1927
    bool complete;
1928

B
bellard 已提交
1929
#if defined(DEBUG_IDE)
1930
    printf("ide: CMD=%02x\n", val);
B
bellard 已提交
1931
#endif
1932
    s = idebus_active_if(bus);
D
Dong Xu Wang 已提交
1933
    /* ignore commands to non existent slave */
1934
    if (s != bus->ifs && !s->blk) {
1935
        return;
1936
    }
B
bellard 已提交
1937

J
John Snow 已提交
1938 1939 1940 1941 1942 1943 1944
    /* Only RESET is allowed while BSY and/or DRQ are set,
     * and only to ATAPI devices. */
    if (s->status & (BUSY_STAT|DRQ_STAT)) {
        if (val != WIN_DEVICE_RESET || s->drive_kind != IDE_CD) {
            return;
        }
    }
1945

1946
    if (!ide_cmd_permitted(s, val)) {
K
Kevin Wolf 已提交
1947 1948 1949
        ide_abort_command(s);
        ide_set_irq(s->bus);
        return;
1950 1951
    }

K
Kevin Wolf 已提交
1952 1953
    s->status = READY_STAT | BUSY_STAT;
    s->error = 0;
1954
    s->io_buffer_offset = 0;
K
Kevin Wolf 已提交
1955

K
Kevin Wolf 已提交
1956 1957 1958 1959
    complete = ide_cmd_table[val].handler(s, val);
    if (complete) {
        s->status &= ~BUSY_STAT;
        assert(!!s->error == !!(s->status & ERR_STAT));
K
Kevin Wolf 已提交
1960

K
Kevin Wolf 已提交
1961 1962
        if ((ide_cmd_table[val].flags & SET_DSC) && !s->error) {
            s->status |= SEEK_STAT;
K
Kevin Wolf 已提交
1963 1964
        }

1965
        ide_cmd_done(s);
1966 1967
        ide_set_irq(s->bus);
    }
B
bellard 已提交
1968 1969
}

G
Gerd Hoffmann 已提交
1970
uint32_t ide_ioport_read(void *opaque, uint32_t addr1)
B
bellard 已提交
1971
{
G
Gerd Hoffmann 已提交
1972 1973
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
1974
    uint32_t addr;
B
bellard 已提交
1975
    int ret, hob;
B
bellard 已提交
1976 1977

    addr = addr1 & 7;
B
bellard 已提交
1978 1979 1980
    /* FIXME: HOB readback uses bit 7, but it's always set right now */
    //hob = s->select & (1 << 7);
    hob = 0;
B
bellard 已提交
1981 1982 1983 1984 1985
    switch(addr) {
    case 0:
        ret = 0xff;
        break;
    case 1:
1986 1987
        if ((!bus->ifs[0].blk && !bus->ifs[1].blk) ||
            (s != bus->ifs && !s->blk)) {
1988
            ret = 0;
1989
        } else if (!hob) {
1990
            ret = s->error;
1991
        } else {
B
bellard 已提交
1992
	    ret = s->hob_feature;
1993
        }
B
bellard 已提交
1994 1995
        break;
    case 2:
1996
        if (!bus->ifs[0].blk && !bus->ifs[1].blk) {
1997
            ret = 0;
1998
        } else if (!hob) {
1999
            ret = s->nsector & 0xff;
2000
        } else {
B
bellard 已提交
2001
	    ret = s->hob_nsector;
2002
        }
B
bellard 已提交
2003 2004
        break;
    case 3:
2005
        if (!bus->ifs[0].blk && !bus->ifs[1].blk) {
2006
            ret = 0;
2007
        } else if (!hob) {
2008
            ret = s->sector;
2009
        } else {
B
bellard 已提交
2010
	    ret = s->hob_sector;
2011
        }
B
bellard 已提交
2012 2013
        break;
    case 4:
2014
        if (!bus->ifs[0].blk && !bus->ifs[1].blk) {
2015
            ret = 0;
2016
        } else if (!hob) {
2017
            ret = s->lcyl;
2018
        } else {
B
bellard 已提交
2019
	    ret = s->hob_lcyl;
2020
        }
B
bellard 已提交
2021 2022
        break;
    case 5:
2023
        if (!bus->ifs[0].blk && !bus->ifs[1].blk) {
2024
            ret = 0;
2025
        } else if (!hob) {
2026
            ret = s->hcyl;
2027
        } else {
B
bellard 已提交
2028
	    ret = s->hob_hcyl;
2029
        }
B
bellard 已提交
2030 2031
        break;
    case 6:
2032
        if (!bus->ifs[0].blk && !bus->ifs[1].blk) {
2033
            ret = 0;
2034
        } else {
B
bellard 已提交
2035
            ret = s->select;
2036
        }
B
bellard 已提交
2037 2038 2039
        break;
    default:
    case 7:
2040 2041
        if ((!bus->ifs[0].blk && !bus->ifs[1].blk) ||
            (s != bus->ifs && !s->blk)) {
2042
            ret = 0;
2043
        } else {
2044
            ret = s->status;
2045
        }
2046
        qemu_irq_lower(bus->irq);
B
bellard 已提交
2047 2048 2049 2050 2051 2052 2053 2054
        break;
    }
#ifdef DEBUG_IDE
    printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
#endif
    return ret;
}

G
Gerd Hoffmann 已提交
2055
uint32_t ide_status_read(void *opaque, uint32_t addr)
B
bellard 已提交
2056
{
G
Gerd Hoffmann 已提交
2057 2058
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
2059
    int ret;
B
bellard 已提交
2060

2061 2062
    if ((!bus->ifs[0].blk && !bus->ifs[1].blk) ||
        (s != bus->ifs && !s->blk)) {
B
bellard 已提交
2063
        ret = 0;
2064
    } else {
B
bellard 已提交
2065
        ret = s->status;
2066
    }
B
bellard 已提交
2067 2068 2069 2070 2071 2072
#ifdef DEBUG_IDE
    printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
#endif
    return ret;
}

G
Gerd Hoffmann 已提交
2073
void ide_cmd_write(void *opaque, uint32_t addr, uint32_t val)
B
bellard 已提交
2074
{
G
Gerd Hoffmann 已提交
2075
    IDEBus *bus = opaque;
B
bellard 已提交
2076 2077 2078 2079 2080 2081 2082
    IDEState *s;
    int i;

#ifdef DEBUG_IDE
    printf("ide: write control addr=0x%x val=%02x\n", addr, val);
#endif
    /* common for both drives */
2083
    if (!(bus->cmd & IDE_CMD_RESET) &&
B
bellard 已提交
2084 2085 2086
        (val & IDE_CMD_RESET)) {
        /* reset low to high */
        for(i = 0;i < 2; i++) {
G
Gerd Hoffmann 已提交
2087
            s = &bus->ifs[i];
B
bellard 已提交
2088 2089 2090
            s->status = BUSY_STAT | SEEK_STAT;
            s->error = 0x01;
        }
2091
    } else if ((bus->cmd & IDE_CMD_RESET) &&
B
bellard 已提交
2092 2093 2094
               !(val & IDE_CMD_RESET)) {
        /* high to low */
        for(i = 0;i < 2; i++) {
G
Gerd Hoffmann 已提交
2095
            s = &bus->ifs[i];
2096
            if (s->drive_kind == IDE_CD)
B
bellard 已提交
2097 2098
                s->status = 0x00; /* NOTE: READY is _not_ set */
            else
2099
                s->status = READY_STAT | SEEK_STAT;
B
bellard 已提交
2100 2101 2102 2103
            ide_set_signature(s);
        }
    }

2104
    bus->cmd = val;
B
bellard 已提交
2105 2106
}

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
/*
 * Returns true if the running PIO transfer is a PIO out (i.e. data is
 * transferred from the device to the guest), false if it's a PIO in
 */
static bool ide_is_pio_out(IDEState *s)
{
    if (s->end_transfer_func == ide_sector_write ||
        s->end_transfer_func == ide_atapi_cmd) {
        return false;
    } else if (s->end_transfer_func == ide_sector_read ||
               s->end_transfer_func == ide_transfer_stop ||
               s->end_transfer_func == ide_atapi_cmd_reply_end ||
               s->end_transfer_func == ide_dummy_transfer_stop) {
        return true;
    }

    abort();
}

G
Gerd Hoffmann 已提交
2126
void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)
B
bellard 已提交
2127
{
G
Gerd Hoffmann 已提交
2128 2129
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
2130 2131
    uint8_t *p;

2132 2133 2134
    /* PIO data access allowed only when DRQ bit is set. The result of a write
     * during PIO out is indeterminate, just ignore it. */
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
2135
        return;
2136
    }
2137

B
bellard 已提交
2138
    p = s->data_ptr;
2139 2140 2141 2142
    if (p + 2 > s->data_end) {
        return;
    }

B
bellard 已提交
2143
    *(uint16_t *)p = le16_to_cpu(val);
B
bellard 已提交
2144 2145
    p += 2;
    s->data_ptr = p;
2146 2147
    if (p >= s->data_end) {
        s->status &= ~DRQ_STAT;
B
bellard 已提交
2148
        s->end_transfer_func(s);
2149
    }
B
bellard 已提交
2150 2151
}

G
Gerd Hoffmann 已提交
2152
uint32_t ide_data_readw(void *opaque, uint32_t addr)
B
bellard 已提交
2153
{
G
Gerd Hoffmann 已提交
2154 2155
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
2156 2157
    uint8_t *p;
    int ret;
2158

2159 2160 2161
    /* PIO data access allowed only when DRQ bit is set. The result of a read
     * during PIO in is indeterminate, return 0 and don't move forward. */
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
2162
        return 0;
2163
    }
2164

B
bellard 已提交
2165
    p = s->data_ptr;
2166 2167 2168 2169
    if (p + 2 > s->data_end) {
        return 0;
    }

B
bellard 已提交
2170
    ret = cpu_to_le16(*(uint16_t *)p);
B
bellard 已提交
2171 2172
    p += 2;
    s->data_ptr = p;
2173 2174
    if (p >= s->data_end) {
        s->status &= ~DRQ_STAT;
B
bellard 已提交
2175
        s->end_transfer_func(s);
2176
    }
B
bellard 已提交
2177 2178 2179
    return ret;
}

G
Gerd Hoffmann 已提交
2180
void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
B
bellard 已提交
2181
{
G
Gerd Hoffmann 已提交
2182 2183
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
2184 2185
    uint8_t *p;

2186 2187 2188
    /* PIO data access allowed only when DRQ bit is set. The result of a write
     * during PIO out is indeterminate, just ignore it. */
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
2189
        return;
2190
    }
2191

B
bellard 已提交
2192
    p = s->data_ptr;
2193 2194 2195 2196
    if (p + 4 > s->data_end) {
        return;
    }

B
bellard 已提交
2197
    *(uint32_t *)p = le32_to_cpu(val);
B
bellard 已提交
2198 2199
    p += 4;
    s->data_ptr = p;
2200 2201
    if (p >= s->data_end) {
        s->status &= ~DRQ_STAT;
B
bellard 已提交
2202
        s->end_transfer_func(s);
2203
    }
B
bellard 已提交
2204 2205
}

G
Gerd Hoffmann 已提交
2206
uint32_t ide_data_readl(void *opaque, uint32_t addr)
B
bellard 已提交
2207
{
G
Gerd Hoffmann 已提交
2208 2209
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
B
bellard 已提交
2210 2211
    uint8_t *p;
    int ret;
2212

2213 2214 2215
    /* PIO data access allowed only when DRQ bit is set. The result of a read
     * during PIO in is indeterminate, return 0 and don't move forward. */
    if (!(s->status & DRQ_STAT) || !ide_is_pio_out(s)) {
2216
        return 0;
2217
    }
2218

B
bellard 已提交
2219
    p = s->data_ptr;
2220 2221 2222 2223
    if (p + 4 > s->data_end) {
        return 0;
    }

B
bellard 已提交
2224
    ret = cpu_to_le32(*(uint32_t *)p);
B
bellard 已提交
2225 2226
    p += 4;
    s->data_ptr = p;
2227 2228
    if (p >= s->data_end) {
        s->status &= ~DRQ_STAT;
B
bellard 已提交
2229
        s->end_transfer_func(s);
2230
    }
B
bellard 已提交
2231 2232 2233
    return ret;
}

2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
static void ide_dummy_transfer_stop(IDEState *s)
{
    s->data_ptr = s->io_buffer;
    s->data_end = s->io_buffer;
    s->io_buffer[0] = 0xff;
    s->io_buffer[1] = 0xff;
    s->io_buffer[2] = 0xff;
    s->io_buffer[3] = 0xff;
}

B
Blue Swirl 已提交
2244 2245 2246 2247 2248 2249 2250
void ide_bus_reset(IDEBus *bus)
{
    bus->unit = 0;
    bus->cmd = 0;
    ide_reset(&bus->ifs[0]);
    ide_reset(&bus->ifs[1]);
    ide_clear_hob(bus);
2251 2252 2253 2254 2255 2256

    /* pending async DMA */
    if (bus->dma->aiocb) {
#ifdef DEBUG_AIO
        printf("aio_cancel\n");
#endif
2257
        blk_aio_cancel(bus->dma->aiocb);
2258 2259 2260 2261
        bus->dma->aiocb = NULL;
    }

    /* reset dma provider too */
P
Paolo Bonzini 已提交
2262 2263 2264
    if (bus->dma->ops->reset) {
        bus->dma->ops->reset(bus->dma);
    }
B
Blue Swirl 已提交
2265 2266
}

2267 2268 2269 2270 2271
static bool ide_cd_is_tray_open(void *opaque)
{
    return ((IDEState *)opaque)->tray_open;
}

2272 2273 2274 2275 2276
static bool ide_cd_is_medium_locked(void *opaque)
{
    return ((IDEState *)opaque)->tray_locked;
}

J
John Snow 已提交
2277 2278 2279 2280 2281 2282 2283 2284 2285
static void ide_resize_cb(void *opaque)
{
    IDEState *s = opaque;
    uint64_t nb_sectors;

    if (!s->identify_set) {
        return;
    }

2286
    blk_get_geometry(s->blk, &nb_sectors);
J
John Snow 已提交
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
    s->nb_sectors = nb_sectors;

    /* Update the identify data buffer. */
    if (s->drive_kind == IDE_CFATA) {
        ide_cfata_identify_size(s);
    } else {
        /* IDE_CD uses a different set of callbacks entirely. */
        assert(s->drive_kind != IDE_CD);
        ide_identify_size(s);
    }
}

2299
static const BlockDevOps ide_cd_block_ops = {
2300
    .change_media_cb = ide_cd_change_cb,
P
Paolo Bonzini 已提交
2301
    .eject_request_cb = ide_cd_eject_request_cb,
2302
    .is_tray_open = ide_cd_is_tray_open,
2303
    .is_medium_locked = ide_cd_is_medium_locked,
2304 2305
};

J
John Snow 已提交
2306 2307 2308 2309
static const BlockDevOps ide_hd_block_ops = {
    .resize_cb = ide_resize_cb,
};

2310
int ide_init_drive(IDEState *s, BlockBackend *blk, IDEDriveKind kind,
F
Floris Bos 已提交
2311
                   const char *version, const char *serial, const char *model,
2312 2313 2314
                   uint64_t wwn,
                   uint32_t cylinders, uint32_t heads, uint32_t secs,
                   int chs_trans)
2315 2316 2317
{
    uint64_t nb_sectors;

2318
    s->blk = blk;
2319 2320
    s->drive_kind = kind;

2321
    blk_get_geometry(blk, &nb_sectors);
2322 2323 2324
    s->cylinders = cylinders;
    s->heads = heads;
    s->sectors = secs;
2325
    s->chs_trans = chs_trans;
2326
    s->nb_sectors = nb_sectors;
F
Floris Bos 已提交
2327
    s->wwn = wwn;
2328 2329 2330 2331 2332 2333
    /* The SMART values should be preserved across power cycles
       but they aren't.  */
    s->smart_enabled = 1;
    s->smart_autosave = 1;
    s->smart_errors = 0;
    s->smart_selftest_count = 0;
2334
    if (kind == IDE_CD) {
2335 2336
        blk_set_dev_ops(blk, &ide_cd_block_ops, s);
        blk_set_guest_block_size(blk, 2048);
2337
    } else {
2338
        if (!blk_is_inserted(s->blk)) {
2339 2340 2341
            error_report("Device needs media, but drive is empty");
            return -1;
        }
2342
        if (blk_is_read_only(blk)) {
2343 2344 2345
            error_report("Can't use a read-only drive");
            return -1;
        }
2346
        blk_set_dev_ops(blk, &ide_hd_block_ops, s);
2347
    }
2348
    if (serial) {
2349
        pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), serial);
2350
    } else {
2351 2352
        snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),
                 "QM%05d", s->drive_serial);
2353
    }
F
Floris Bos 已提交
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
    if (model) {
        pstrcpy(s->drive_model_str, sizeof(s->drive_model_str), model);
    } else {
        switch (kind) {
        case IDE_CD:
            strcpy(s->drive_model_str, "QEMU DVD-ROM");
            break;
        case IDE_CFATA:
            strcpy(s->drive_model_str, "QEMU MICRODRIVE");
            break;
        default:
            strcpy(s->drive_model_str, "QEMU HARDDISK");
            break;
        }
    }

G
Gerd Hoffmann 已提交
2370 2371 2372
    if (version) {
        pstrcpy(s->version, sizeof(s->version), version);
    } else {
2373
        pstrcpy(s->version, sizeof(s->version), qemu_hw_version());
G
Gerd Hoffmann 已提交
2374
    }
2375

2376
    ide_reset(s);
2377
    blk_iostatus_enable(blk);
2378
    return 0;
2379 2380
}

2381
static void ide_init1(IDEBus *bus, int unit)
2382 2383 2384 2385 2386 2387 2388
{
    static int drive_serial = 1;
    IDEState *s = &bus->ifs[unit];

    s->bus = bus;
    s->unit = unit;
    s->drive_serial = drive_serial++;
2389
    /* we need at least 2k alignment for accessing CDROMs using O_DIRECT */
2390
    s->io_buffer_total_len = IDE_DMA_BUF_SECTORS*512 + 4;
K
Kevin Wolf 已提交
2391 2392 2393
    s->io_buffer = qemu_memalign(2048, s->io_buffer_total_len);
    memset(s->io_buffer, 0, s->io_buffer_total_len);

2394
    s->smart_selftest_data = blk_blockalign(s->blk, 512);
K
Kevin Wolf 已提交
2395 2396
    memset(s->smart_selftest_data, 0, 512);

2397
    s->sector_write_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
2398
                                           ide_sector_write_timer_cb, s);
2399 2400
}

2401 2402 2403 2404 2405
static int ide_nop_int(IDEDMA *dma, int x)
{
    return 0;
}

2406 2407 2408 2409
static void ide_nop(IDEDMA *dma)
{
}

J
John Snow 已提交
2410
static int32_t ide_nop_int32(IDEDMA *dma, int32_t l)
2411 2412 2413 2414
{
    return 0;
}

2415
static const IDEDMAOps ide_dma_nop_ops = {
2416
    .prepare_buf    = ide_nop_int32,
2417
    .restart_dma    = ide_nop,
2418 2419 2420
    .rw_buf         = ide_nop_int,
};

2421 2422
static void ide_restart_dma(IDEState *s, enum ide_dma_cmd dma_cmd)
{
2423
    s->unit = s->bus->retry_unit;
2424 2425
    ide_set_sector(s, s->bus->retry_sector_num);
    s->nsector = s->bus->retry_nsector;
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
    s->bus->dma->ops->restart_dma(s->bus->dma);
    s->io_buffer_size = 0;
    s->dma_cmd = dma_cmd;
    ide_start_dma(s, ide_dma_cb);
}

static void ide_restart_bh(void *opaque)
{
    IDEBus *bus = opaque;
    IDEState *s;
    bool is_read;
    int error_status;

    qemu_bh_delete(bus->bh);
    bus->bh = NULL;

    error_status = bus->error_status;
    if (bus->error_status == 0) {
        return;
    }

    s = idebus_active_if(bus);
    is_read = (bus->error_status & IDE_RETRY_READ) != 0;

    /* The error status must be cleared before resubmitting the request: The
     * request may fail again, and this case can only be distinguished if the
     * called function can set a new error status. */
    bus->error_status = 0;

2455 2456 2457 2458 2459 2460 2461
    /* The HBA has generically asked to be kicked on retry */
    if (error_status & IDE_RETRY_HBA) {
        if (s->bus->dma->ops->restart) {
            s->bus->dma->ops->restart(s->bus->dma);
        }
    }

2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
    if (error_status & IDE_RETRY_DMA) {
        if (error_status & IDE_RETRY_TRIM) {
            ide_restart_dma(s, IDE_DMA_TRIM);
        } else {
            ide_restart_dma(s, is_read ? IDE_DMA_READ : IDE_DMA_WRITE);
        }
    } else if (error_status & IDE_RETRY_PIO) {
        if (is_read) {
            ide_sector_read(s);
        } else {
            ide_sector_write(s);
        }
    } else if (error_status & IDE_RETRY_FLUSH) {
        ide_flush_cache(s);
    } else {
        /*
         * We've not got any bits to tell us about ATAPI - but
         * we do have the end_transfer_func that tells us what
         * we're trying to do.
         */
        if (s->end_transfer_func == ide_atapi_cmd) {
            ide_atapi_dma_restart(s);
        }
    }
}

static void ide_restart_cb(void *opaque, int running, RunState state)
{
    IDEBus *bus = opaque;

    if (!running)
        return;

    if (!bus->bh) {
        bus->bh = qemu_bh_new(ide_restart_bh, bus);
        qemu_bh_schedule(bus->bh);
    }
}

2501 2502
void ide_register_restart_cb(IDEBus *bus)
{
2503 2504 2505
    if (bus->dma->ops->restart_dma) {
        qemu_add_vm_change_state_handler(ide_restart_cb, bus);
    }
2506 2507
}

2508 2509 2510 2511 2512
static IDEDMA ide_dma_nop = {
    .ops = &ide_dma_nop_ops,
    .aiocb = NULL,
};

2513 2514 2515 2516 2517 2518 2519
void ide_init2(IDEBus *bus, qemu_irq irq)
{
    int i;

    for(i = 0; i < 2; i++) {
        ide_init1(bus, i);
        ide_reset(&bus->ifs[i]);
2520
    }
2521
    bus->irq = irq;
2522
    bus->dma = &ide_dma_nop;
2523 2524
}

2525 2526
static const MemoryRegionPortio ide_portio_list[] = {
    { 0, 8, 1, .read = ide_ioport_read, .write = ide_ioport_write },
P
Paolo Bonzini 已提交
2527 2528
    { 0, 1, 2, .read = ide_data_readw, .write = ide_data_writew },
    { 0, 1, 4, .read = ide_data_readl, .write = ide_data_writel },
2529 2530 2531 2532 2533 2534 2535 2536 2537
    PORTIO_END_OF_LIST(),
};

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

void ide_init_ioport(IDEBus *bus, ISADevice *dev, int iobase, int iobase2)
B
bellard 已提交
2538
{
2539 2540 2541 2542
    /* ??? Assume only ISA and PCI configurations, and that the PCI-ISA
       bridge has been setup properly to always register with ISA.  */
    isa_register_portio_list(dev, iobase, ide_portio_list, bus, "ide");

2543
    if (iobase2) {
2544
        isa_register_portio_list(dev, iobase2, ide_portio2_list, bus, "ide");
B
bellard 已提交
2545 2546
    }
}
B
bellard 已提交
2547

J
Juan Quintela 已提交
2548
static bool is_identify_set(void *opaque, int version_id)
2549
{
J
Juan Quintela 已提交
2550 2551 2552 2553 2554
    IDEState *s = opaque;

    return s->identify_set != 0;
}

2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
static EndTransferFunc* transfer_end_table[] = {
        ide_sector_read,
        ide_sector_write,
        ide_transfer_stop,
        ide_atapi_cmd_reply_end,
        ide_atapi_cmd,
        ide_dummy_transfer_stop,
};

static int transfer_end_table_idx(EndTransferFunc *fn)
{
    int i;

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

    return -1;
}

J
Juan Quintela 已提交
2575
static int ide_drive_post_load(void *opaque, int version_id)
2576
{
J
Juan Quintela 已提交
2577 2578
    IDEState *s = opaque;

2579
    if (s->blk && s->identify_set) {
2580
        blk_set_enable_write_cache(s->blk, !!(s->identify_data[85] & (1 << 5)));
2581
    }
J
Juan Quintela 已提交
2582
    return 0;
2583 2584
}

2585 2586 2587 2588
static int ide_drive_pio_post_load(void *opaque, int version_id)
{
    IDEState *s = opaque;

2589
    if (s->end_transfer_fn_idx >= ARRAY_SIZE(transfer_end_table)) {
2590 2591 2592 2593 2594
        return -EINVAL;
    }
    s->end_transfer_func = transfer_end_table[s->end_transfer_fn_idx];
    s->data_ptr = s->io_buffer + s->cur_io_buffer_offset;
    s->data_end = s->data_ptr + s->cur_io_buffer_len;
2595
    s->atapi_dma = s->feature & 1; /* as per cmd_packet */
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621

    return 0;
}

static void ide_drive_pio_pre_save(void *opaque)
{
    IDEState *s = opaque;
    int idx;

    s->cur_io_buffer_offset = s->data_ptr - s->io_buffer;
    s->cur_io_buffer_len = s->data_end - s->data_ptr;

    idx = transfer_end_table_idx(s->end_transfer_func);
    if (idx == -1) {
        fprintf(stderr, "%s: invalid end_transfer_func for DRQ_STAT\n",
                        __func__);
        s->end_transfer_fn_idx = 2;
    } else {
        s->end_transfer_fn_idx = idx;
    }
}

static bool ide_drive_pio_state_needed(void *opaque)
{
    IDEState *s = opaque;

2622
    return ((s->status & DRQ_STAT) != 0)
2623
        || (s->bus->error_status & IDE_RETRY_PIO);
2624 2625
}

2626 2627 2628 2629 2630 2631 2632
static bool ide_tray_state_needed(void *opaque)
{
    IDEState *s = opaque;

    return s->tray_open || s->tray_locked;
}

2633 2634 2635 2636 2637 2638 2639
static bool ide_atapi_gesn_needed(void *opaque)
{
    IDEState *s = opaque;

    return s->events.new_media || s->events.eject_request;
}

2640 2641 2642 2643 2644 2645 2646
static bool ide_error_needed(void *opaque)
{
    IDEBus *bus = opaque;

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

2647
/* Fields for GET_EVENT_STATUS_NOTIFICATION ATAPI command */
2648
static const VMStateDescription vmstate_ide_atapi_gesn_state = {
2649 2650 2651
    .name ="ide_drive/atapi/gesn_state",
    .version_id = 1,
    .minimum_version_id = 1,
2652
    .needed = ide_atapi_gesn_needed,
2653
    .fields = (VMStateField[]) {
2654 2655
        VMSTATE_BOOL(events.new_media, IDEState),
        VMSTATE_BOOL(events.eject_request, IDEState),
2656
        VMSTATE_END_OF_LIST()
2657 2658 2659
    }
};

2660 2661 2662 2663
static const VMStateDescription vmstate_ide_tray_state = {
    .name = "ide_drive/tray_state",
    .version_id = 1,
    .minimum_version_id = 1,
2664
    .needed = ide_tray_state_needed,
2665 2666 2667 2668 2669 2670 2671
    .fields = (VMStateField[]) {
        VMSTATE_BOOL(tray_open, IDEState),
        VMSTATE_BOOL(tray_locked, IDEState),
        VMSTATE_END_OF_LIST()
    }
};

2672
static const VMStateDescription vmstate_ide_drive_pio_state = {
2673 2674 2675 2676 2677
    .name = "ide_drive/pio_state",
    .version_id = 1,
    .minimum_version_id = 1,
    .pre_save = ide_drive_pio_pre_save,
    .post_load = ide_drive_pio_post_load,
2678
    .needed = ide_drive_pio_state_needed,
2679
    .fields = (VMStateField[]) {
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
        VMSTATE_INT32(req_nb_sectors, IDEState),
        VMSTATE_VARRAY_INT32(io_buffer, IDEState, io_buffer_total_len, 1,
			     vmstate_info_uint8, uint8_t),
        VMSTATE_INT32(cur_io_buffer_offset, IDEState),
        VMSTATE_INT32(cur_io_buffer_len, IDEState),
        VMSTATE_UINT8(end_transfer_fn_idx, IDEState),
        VMSTATE_INT32(elementary_transfer_size, IDEState),
        VMSTATE_INT32(packet_transfer_size, IDEState),
        VMSTATE_END_OF_LIST()
    }
};

J
Juan Quintela 已提交
2692 2693
const VMStateDescription vmstate_ide_drive = {
    .name = "ide_drive",
2694
    .version_id = 3,
J
Juan Quintela 已提交
2695 2696
    .minimum_version_id = 0,
    .post_load = ide_drive_post_load,
2697
    .fields = (VMStateField[]) {
J
Juan Quintela 已提交
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
        VMSTATE_INT32(mult_sectors, IDEState),
        VMSTATE_INT32(identify_set, IDEState),
        VMSTATE_BUFFER_TEST(identify_data, IDEState, is_identify_set),
        VMSTATE_UINT8(feature, IDEState),
        VMSTATE_UINT8(error, IDEState),
        VMSTATE_UINT32(nsector, IDEState),
        VMSTATE_UINT8(sector, IDEState),
        VMSTATE_UINT8(lcyl, IDEState),
        VMSTATE_UINT8(hcyl, IDEState),
        VMSTATE_UINT8(hob_feature, IDEState),
        VMSTATE_UINT8(hob_sector, IDEState),
        VMSTATE_UINT8(hob_nsector, IDEState),
        VMSTATE_UINT8(hob_lcyl, IDEState),
        VMSTATE_UINT8(hob_hcyl, IDEState),
        VMSTATE_UINT8(select, IDEState),
        VMSTATE_UINT8(status, IDEState),
        VMSTATE_UINT8(lba48, IDEState),
        VMSTATE_UINT8(sense_key, IDEState),
        VMSTATE_UINT8(asc, IDEState),
        VMSTATE_UINT8_V(cdrom_changed, IDEState, 3),
        VMSTATE_END_OF_LIST()
2719
    },
2720 2721 2722 2723 2724
    .subsections = (const VMStateDescription*[]) {
        &vmstate_ide_drive_pio_state,
        &vmstate_ide_tray_state,
        &vmstate_ide_atapi_gesn_state,
        NULL
J
Juan Quintela 已提交
2725 2726 2727
    }
};

2728
static const VMStateDescription vmstate_ide_error_status = {
2729
    .name ="ide_bus/error",
2730
    .version_id = 2,
2731
    .minimum_version_id = 1,
2732
    .needed = ide_error_needed,
2733
    .fields = (VMStateField[]) {
2734
        VMSTATE_INT32(error_status, IDEBus),
2735 2736 2737
        VMSTATE_INT64_V(retry_sector_num, IDEBus, 2),
        VMSTATE_UINT32_V(retry_nsector, IDEBus, 2),
        VMSTATE_UINT8_V(retry_unit, IDEBus, 2),
2738 2739 2740 2741
        VMSTATE_END_OF_LIST()
    }
};

J
Juan Quintela 已提交
2742 2743 2744 2745
const VMStateDescription vmstate_ide_bus = {
    .name = "ide_bus",
    .version_id = 1,
    .minimum_version_id = 1,
2746
    .fields = (VMStateField[]) {
J
Juan Quintela 已提交
2747 2748 2749
        VMSTATE_UINT8(cmd, IDEBus),
        VMSTATE_UINT8(unit, IDEBus),
        VMSTATE_END_OF_LIST()
2750
    },
2751 2752 2753
    .subsections = (const VMStateDescription*[]) {
        &vmstate_ide_error_status,
        NULL
J
Juan Quintela 已提交
2754 2755
    }
};
2756

2757
void ide_drive_get(DriveInfo **hd, int n)
2758 2759
{
    int i;
2760 2761 2762
    int highest_bus = drive_get_max_bus(IF_IDE) + 1;
    int max_devs = drive_get_max_devs(IF_IDE);
    int n_buses = max_devs ? (n / max_devs) : n;
2763

2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
    /*
     * Note: The number of actual buses available is not known.
     * We compute this based on the size of the DriveInfo* array, n.
     * If it is less than max_devs * <num_real_buses>,
     * We will stop looking for drives prematurely instead of overfilling
     * the array.
     */

    if (highest_bus > n_buses) {
        error_report("Too many IDE buses defined (%d > %d)",
                     highest_bus, n_buses);
2775 2776 2777
        exit(1);
    }

2778 2779
    for (i = 0; i < n; i++) {
        hd[i] = drive_get_by_index(IF_IDE, i);
2780 2781
    }
}