Statistics
| Branch: | Revision:

root / hw / scsi-disk.c @ f01b5931

History | View | Annotate | Download (42.5 kB)

1
/*
2
 * SCSI Device emulation
3
 *
4
 * Copyright (c) 2006 CodeSourcery.
5
 * Based on code by Fabrice Bellard
6
 *
7
 * Written by Paul Brook
8
 * Modifications:
9
 *  2009-Dec-12 Artyom Tarasenko : implemented stamdard inquiry for the case
10
 *                                 when the allocation length of CDB is smaller
11
 *                                 than 36.
12
 *  2009-Oct-13 Artyom Tarasenko : implemented the block descriptor in the
13
 *                                 MODE SENSE response.
14
 *
15
 * This code is licensed under the LGPL.
16
 *
17
 * Note that this file only handles the SCSI architecture model and device
18
 * commands.  Emulation of interface/link layer protocols is handled by
19
 * the host adapter emulator.
20
 */
21

    
22
//#define DEBUG_SCSI
23

    
24
#ifdef DEBUG_SCSI
25
#define DPRINTF(fmt, ...) \
26
do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
27
#else
28
#define DPRINTF(fmt, ...) do {} while(0)
29
#endif
30

    
31
#define BADF(fmt, ...) \
32
do { fprintf(stderr, "scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
33

    
34
#include "qemu-common.h"
35
#include "qemu-error.h"
36
#include "scsi.h"
37
#include "scsi-defs.h"
38
#include "sysemu.h"
39
#include "blockdev.h"
40
#include "block_int.h"
41

    
42
#define SCSI_DMA_BUF_SIZE    131072
43
#define SCSI_MAX_INQUIRY_LEN 256
44

    
45
#define SCSI_REQ_STATUS_RETRY           0x01
46
#define SCSI_REQ_STATUS_RETRY_TYPE_MASK 0x06
47
#define SCSI_REQ_STATUS_RETRY_READ      0x00
48
#define SCSI_REQ_STATUS_RETRY_WRITE     0x02
49
#define SCSI_REQ_STATUS_RETRY_FLUSH     0x04
50

    
51
typedef struct SCSIDiskState SCSIDiskState;
52

    
53
typedef struct SCSIDiskReq {
54
    SCSIRequest req;
55
    /* Both sector and sector_count are in terms of qemu 512 byte blocks.  */
56
    uint64_t sector;
57
    uint32_t sector_count;
58
    uint32_t buflen;
59
    struct iovec iov;
60
    QEMUIOVector qiov;
61
    uint32_t status;
62
    BlockAcctCookie acct;
63
} SCSIDiskReq;
64

    
65
struct SCSIDiskState
66
{
67
    SCSIDevice qdev;
68
    BlockDriverState *bs;
69
    /* The qemu block layer uses a fixed 512 byte sector size.
70
       This is the number of 512 byte blocks in a single scsi sector.  */
71
    int cluster_size;
72
    uint32_t removable;
73
    uint64_t max_lba;
74
    bool media_changed;
75
    QEMUBH *bh;
76
    char *version;
77
    char *serial;
78
    bool tray_open;
79
    bool tray_locked;
80
};
81

    
82
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type);
83
static int scsi_disk_emulate_command(SCSIDiskReq *r);
84

    
85
static void scsi_free_request(SCSIRequest *req)
86
{
87
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
88

    
89
    if (r->iov.iov_base) {
90
        qemu_vfree(r->iov.iov_base);
91
    }
92
}
93

    
94
/* Helper function for command completion with sense.  */
95
static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense)
96
{
97
    DPRINTF("Command complete tag=0x%x sense=%d/%d/%d\n",
98
            r->req.tag, sense.key, sense.asc, sense.ascq);
99
    scsi_req_build_sense(&r->req, sense);
100
    scsi_req_complete(&r->req, CHECK_CONDITION);
101
}
102

    
103
/* Cancel a pending data transfer.  */
104
static void scsi_cancel_io(SCSIRequest *req)
105
{
106
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
107

    
108
    DPRINTF("Cancel tag=0x%x\n", req->tag);
109
    if (r->req.aiocb) {
110
        bdrv_aio_cancel(r->req.aiocb);
111
    }
112
    r->req.aiocb = NULL;
113
}
114

    
115
static uint32_t scsi_init_iovec(SCSIDiskReq *r)
116
{
117
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
118

    
119
    if (!r->iov.iov_base) {
120
        r->buflen = SCSI_DMA_BUF_SIZE;
121
        r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
122
    }
123
    r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);
124
    qemu_iovec_init_external(&r->qiov, &r->iov, 1);
125
    return r->qiov.size / 512;
126
}
127

    
128
static void scsi_read_complete(void * opaque, int ret)
129
{
130
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
131
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
132
    int n;
133

    
134
    if (r->req.aiocb != NULL) {
135
        r->req.aiocb = NULL;
136
        bdrv_acct_done(s->bs, &r->acct);
137
    }
138

    
139
    if (ret) {
140
        if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
141
            return;
142
        }
143
    }
144

    
145
    DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
146

    
147
    n = r->qiov.size / 512;
148
    r->sector += n;
149
    r->sector_count -= n;
150
    scsi_req_data(&r->req, r->qiov.size);
151
}
152

    
153
static void scsi_flush_complete(void * opaque, int ret)
154
{
155
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
156
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
157

    
158
    if (r->req.aiocb != NULL) {
159
        r->req.aiocb = NULL;
160
        bdrv_acct_done(s->bs, &r->acct);
161
    }
162

    
163
    if (ret < 0) {
164
        if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_FLUSH)) {
165
            return;
166
        }
167
    }
168

    
169
    scsi_req_complete(&r->req, GOOD);
170
}
171

    
172
/* Read more data from scsi device into buffer.  */
173
static void scsi_read_data(SCSIRequest *req)
174
{
175
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
176
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
177
    uint32_t n;
178

    
179
    if (r->sector_count == (uint32_t)-1) {
180
        DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
181
        r->sector_count = 0;
182
        scsi_req_data(&r->req, r->iov.iov_len);
183
        return;
184
    }
185
    DPRINTF("Read sector_count=%d\n", r->sector_count);
186
    if (r->sector_count == 0) {
187
        /* This also clears the sense buffer for REQUEST SENSE.  */
188
        scsi_req_complete(&r->req, GOOD);
189
        return;
190
    }
191

    
192
    /* No data transfer may already be in progress */
193
    assert(r->req.aiocb == NULL);
194

    
195
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
196
        DPRINTF("Data transfer direction invalid\n");
197
        scsi_read_complete(r, -EINVAL);
198
        return;
199
    }
200

    
201
    if (s->tray_open) {
202
        scsi_read_complete(r, -ENOMEDIUM);
203
    }
204
    n = scsi_init_iovec(r);
205
    bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
206
    r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
207
                              scsi_read_complete, r);
208
    if (r->req.aiocb == NULL) {
209
        scsi_read_complete(r, -EIO);
210
    }
211
}
212

    
213
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)
214
{
215
    int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);
216
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
217
    BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);
218

    
219
    if (action == BLOCK_ERR_IGNORE) {
220
        bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);
221
        return 0;
222
    }
223

    
224
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
225
            || action == BLOCK_ERR_STOP_ANY) {
226

    
227
        type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;
228
        r->status |= SCSI_REQ_STATUS_RETRY | type;
229

    
230
        bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);
231
        vm_stop(RUN_STATE_IO_ERROR);
232
        bdrv_iostatus_set_err(s->bs, error);
233
    } else {
234
        switch (error) {
235
        case ENOMEDIUM:
236
            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
237
            break;
238
        case ENOMEM:
239
            scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
240
            break;
241
        case EINVAL:
242
            scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
243
            break;
244
        default:
245
            scsi_check_condition(r, SENSE_CODE(IO_ERROR));
246
            break;
247
        }
248
        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
249
    }
250
    return 1;
251
}
252

    
253
static void scsi_write_complete(void * opaque, int ret)
254
{
255
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
256
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
257
    uint32_t n;
258

    
259
    if (r->req.aiocb != NULL) {
260
        r->req.aiocb = NULL;
261
        bdrv_acct_done(s->bs, &r->acct);
262
    }
263

    
264
    if (ret) {
265
        if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) {
266
            return;
267
        }
268
    }
269

    
270
    n = r->qiov.size / 512;
271
    r->sector += n;
272
    r->sector_count -= n;
273
    if (r->sector_count == 0) {
274
        scsi_req_complete(&r->req, GOOD);
275
    } else {
276
        scsi_init_iovec(r);
277
        DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);
278
        scsi_req_data(&r->req, r->qiov.size);
279
    }
280
}
281

    
282
static void scsi_write_data(SCSIRequest *req)
283
{
284
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
285
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
286
    uint32_t n;
287

    
288
    /* No data transfer may already be in progress */
289
    assert(r->req.aiocb == NULL);
290

    
291
    if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
292
        DPRINTF("Data transfer direction invalid\n");
293
        scsi_write_complete(r, -EINVAL);
294
        return;
295
    }
296

    
297
    n = r->qiov.size / 512;
298
    if (n) {
299
        if (s->tray_open) {
300
            scsi_write_complete(r, -ENOMEDIUM);
301
        }
302
        bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
303
        r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,
304
                                       scsi_write_complete, r);
305
        if (r->req.aiocb == NULL) {
306
            scsi_write_complete(r, -ENOMEM);
307
        }
308
    } else {
309
        /* Called for the first time.  Ask the driver to send us more data.  */
310
        scsi_write_complete(r, 0);
311
    }
312
}
313

    
314
static void scsi_dma_restart_bh(void *opaque)
315
{
316
    SCSIDiskState *s = opaque;
317
    SCSIRequest *req;
318
    SCSIDiskReq *r;
319

    
320
    qemu_bh_delete(s->bh);
321
    s->bh = NULL;
322

    
323
    QTAILQ_FOREACH(req, &s->qdev.requests, next) {
324
        r = DO_UPCAST(SCSIDiskReq, req, req);
325
        if (r->status & SCSI_REQ_STATUS_RETRY) {
326
            int status = r->status;
327
            int ret;
328

    
329
            r->status &=
330
                ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK);
331

    
332
            switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) {
333
            case SCSI_REQ_STATUS_RETRY_READ:
334
                scsi_read_data(&r->req);
335
                break;
336
            case SCSI_REQ_STATUS_RETRY_WRITE:
337
                scsi_write_data(&r->req);
338
                break;
339
            case SCSI_REQ_STATUS_RETRY_FLUSH:
340
                ret = scsi_disk_emulate_command(r);
341
                if (ret == 0) {
342
                    scsi_req_complete(&r->req, GOOD);
343
                }
344
            }
345
        }
346
    }
347
}
348

    
349
static void scsi_dma_restart_cb(void *opaque, int running, RunState state)
350
{
351
    SCSIDiskState *s = opaque;
352

    
353
    if (!running) {
354
        return;
355
    }
356
    if (!s->bh) {
357
        s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
358
        qemu_bh_schedule(s->bh);
359
    }
360
}
361

    
362
/* Return a pointer to the data buffer.  */
363
static uint8_t *scsi_get_buf(SCSIRequest *req)
364
{
365
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
366

    
367
    return (uint8_t *)r->iov.iov_base;
368
}
369

    
370
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
371
{
372
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
373
    int buflen = 0;
374

    
375
    if (req->cmd.buf[1] & 0x2) {
376
        /* Command support data - optional, not implemented */
377
        BADF("optional INQUIRY command support request not implemented\n");
378
        return -1;
379
    }
380

    
381
    if (req->cmd.buf[1] & 0x1) {
382
        /* Vital product data */
383
        uint8_t page_code = req->cmd.buf[2];
384
        if (req->cmd.xfer < 4) {
385
            BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "
386
                 "less than 4\n", page_code, req->cmd.xfer);
387
            return -1;
388
        }
389

    
390
        if (s->qdev.type == TYPE_ROM) {
391
            outbuf[buflen++] = 5;
392
        } else {
393
            outbuf[buflen++] = 0;
394
        }
395
        outbuf[buflen++] = page_code ; // this page
396
        outbuf[buflen++] = 0x00;
397

    
398
        switch (page_code) {
399
        case 0x00: /* Supported page codes, mandatory */
400
        {
401
            int pages;
402
            DPRINTF("Inquiry EVPD[Supported pages] "
403
                    "buffer size %zd\n", req->cmd.xfer);
404
            pages = buflen++;
405
            outbuf[buflen++] = 0x00; // list of supported pages (this page)
406
            if (s->serial) {
407
                outbuf[buflen++] = 0x80; // unit serial number
408
            }
409
            outbuf[buflen++] = 0x83; // device identification
410
            if (s->qdev.type == TYPE_DISK) {
411
                outbuf[buflen++] = 0xb0; // block limits
412
                outbuf[buflen++] = 0xb2; // thin provisioning
413
            }
414
            outbuf[pages] = buflen - pages - 1; // number of pages
415
            break;
416
        }
417
        case 0x80: /* Device serial number, optional */
418
        {
419
            int l;
420

    
421
            if (!s->serial) {
422
                DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
423
                return -1;
424
            }
425

    
426
            l = strlen(s->serial);
427
            if (l > req->cmd.xfer) {
428
                l = req->cmd.xfer;
429
            }
430
            if (l > 20) {
431
                l = 20;
432
            }
433

    
434
            DPRINTF("Inquiry EVPD[Serial number] "
435
                    "buffer size %zd\n", req->cmd.xfer);
436
            outbuf[buflen++] = l;
437
            memcpy(outbuf+buflen, s->serial, l);
438
            buflen += l;
439
            break;
440
        }
441

    
442
        case 0x83: /* Device identification page, mandatory */
443
        {
444
            int max_len = 255 - 8;
445
            int id_len = strlen(bdrv_get_device_name(s->bs));
446

    
447
            if (id_len > max_len) {
448
                id_len = max_len;
449
            }
450
            DPRINTF("Inquiry EVPD[Device identification] "
451
                    "buffer size %zd\n", req->cmd.xfer);
452

    
453
            outbuf[buflen++] = 4 + id_len;
454
            outbuf[buflen++] = 0x2; // ASCII
455
            outbuf[buflen++] = 0;   // not officially assigned
456
            outbuf[buflen++] = 0;   // reserved
457
            outbuf[buflen++] = id_len; // length of data following
458

    
459
            memcpy(outbuf+buflen, bdrv_get_device_name(s->bs), id_len);
460
            buflen += id_len;
461
            break;
462
        }
463
        case 0xb0: /* block limits */
464
        {
465
            unsigned int unmap_sectors =
466
                    s->qdev.conf.discard_granularity / s->qdev.blocksize;
467
            unsigned int min_io_size =
468
                    s->qdev.conf.min_io_size / s->qdev.blocksize;
469
            unsigned int opt_io_size =
470
                    s->qdev.conf.opt_io_size / s->qdev.blocksize;
471

    
472
            if (s->qdev.type == TYPE_ROM) {
473
                DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
474
                        page_code);
475
                return -1;
476
            }
477
            /* required VPD size with unmap support */
478
            outbuf[3] = buflen = 0x3c;
479

    
480
            memset(outbuf + 4, 0, buflen - 4);
481

    
482
            /* optimal transfer length granularity */
483
            outbuf[6] = (min_io_size >> 8) & 0xff;
484
            outbuf[7] = min_io_size & 0xff;
485

    
486
            /* optimal transfer length */
487
            outbuf[12] = (opt_io_size >> 24) & 0xff;
488
            outbuf[13] = (opt_io_size >> 16) & 0xff;
489
            outbuf[14] = (opt_io_size >> 8) & 0xff;
490
            outbuf[15] = opt_io_size & 0xff;
491

    
492
            /* optimal unmap granularity */
493
            outbuf[28] = (unmap_sectors >> 24) & 0xff;
494
            outbuf[29] = (unmap_sectors >> 16) & 0xff;
495
            outbuf[30] = (unmap_sectors >> 8) & 0xff;
496
            outbuf[31] = unmap_sectors & 0xff;
497
            break;
498
        }
499
        case 0xb2: /* thin provisioning */
500
        {
501
            outbuf[3] = buflen = 8;
502
            outbuf[4] = 0;
503
            outbuf[5] = 0x40; /* write same with unmap supported */
504
            outbuf[6] = 0;
505
            outbuf[7] = 0;
506
            break;
507
        }
508
        default:
509
            BADF("Error: unsupported Inquiry (EVPD[%02X]) "
510
                 "buffer size %zd\n", page_code, req->cmd.xfer);
511
            return -1;
512
        }
513
        /* done with EVPD */
514
        return buflen;
515
    }
516

    
517
    /* Standard INQUIRY data */
518
    if (req->cmd.buf[2] != 0) {
519
        BADF("Error: Inquiry (STANDARD) page or code "
520
             "is non-zero [%02X]\n", req->cmd.buf[2]);
521
        return -1;
522
    }
523

    
524
    /* PAGE CODE == 0 */
525
    if (req->cmd.xfer < 5) {
526
        BADF("Error: Inquiry (STANDARD) buffer size %zd "
527
             "is less than 5\n", req->cmd.xfer);
528
        return -1;
529
    }
530

    
531
    buflen = req->cmd.xfer;
532
    if (buflen > SCSI_MAX_INQUIRY_LEN) {
533
        buflen = SCSI_MAX_INQUIRY_LEN;
534
    }
535
    memset(outbuf, 0, buflen);
536

    
537
    outbuf[0] = s->qdev.type & 0x1f;
538
    if (s->qdev.type == TYPE_ROM) {
539
        outbuf[1] = 0x80;
540
        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);
541
    } else {
542
        outbuf[1] = s->removable ? 0x80 : 0;
543
        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);
544
    }
545
    memcpy(&outbuf[8], "QEMU    ", 8);
546
    memset(&outbuf[32], 0, 4);
547
    memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
548
    /*
549
     * We claim conformance to SPC-3, which is required for guests
550
     * to ask for modern features like READ CAPACITY(16) or the
551
     * block characteristics VPD page by default.  Not all of SPC-3
552
     * is actually implemented, but we're good enough.
553
     */
554
    outbuf[2] = 5;
555
    outbuf[3] = 2; /* Format 2 */
556

    
557
    if (buflen > 36) {
558
        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
559
    } else {
560
        /* If the allocation length of CDB is too small,
561
               the additional length is not adjusted */
562
        outbuf[4] = 36 - 5;
563
    }
564

    
565
    /* Sync data transfer and TCQ.  */
566
    outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);
567
    return buflen;
568
}
569

    
570
static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
571
                           int page_control)
572
{
573
    BlockDriverState *bdrv = s->bs;
574
    int cylinders, heads, secs;
575
    uint8_t *p = *p_outbuf;
576

    
577
    /*
578
     * If Changeable Values are requested, a mask denoting those mode parameters
579
     * that are changeable shall be returned. As we currently don't support
580
     * parameter changes via MODE_SELECT all bits are returned set to zero.
581
     * The buffer was already menset to zero by the caller of this function.
582
     */
583
    switch (page) {
584
    case MODE_PAGE_HD_GEOMETRY:
585
        if (s->qdev.type == TYPE_ROM) {
586
            return -1;
587
        }
588
        p[0] = 4;
589
        p[1] = 0x16;
590
        if (page_control == 1) { /* Changeable Values */
591
            break;
592
        }
593
        /* if a geometry hint is available, use it */
594
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
595
        p[2] = (cylinders >> 16) & 0xff;
596
        p[3] = (cylinders >> 8) & 0xff;
597
        p[4] = cylinders & 0xff;
598
        p[5] = heads & 0xff;
599
        /* Write precomp start cylinder, disabled */
600
        p[6] = (cylinders >> 16) & 0xff;
601
        p[7] = (cylinders >> 8) & 0xff;
602
        p[8] = cylinders & 0xff;
603
        /* Reduced current start cylinder, disabled */
604
        p[9] = (cylinders >> 16) & 0xff;
605
        p[10] = (cylinders >> 8) & 0xff;
606
        p[11] = cylinders & 0xff;
607
        /* Device step rate [ns], 200ns */
608
        p[12] = 0;
609
        p[13] = 200;
610
        /* Landing zone cylinder */
611
        p[14] = 0xff;
612
        p[15] =  0xff;
613
        p[16] = 0xff;
614
        /* Medium rotation rate [rpm], 5400 rpm */
615
        p[20] = (5400 >> 8) & 0xff;
616
        p[21] = 5400 & 0xff;
617
        break;
618

    
619
    case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
620
        if (s->qdev.type == TYPE_ROM) {
621
            return -1;
622
        }
623
        p[0] = 5;
624
        p[1] = 0x1e;
625
        if (page_control == 1) { /* Changeable Values */
626
            break;
627
        }
628
        /* Transfer rate [kbit/s], 5Mbit/s */
629
        p[2] = 5000 >> 8;
630
        p[3] = 5000 & 0xff;
631
        /* if a geometry hint is available, use it */
632
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
633
        p[4] = heads & 0xff;
634
        p[5] = secs & 0xff;
635
        p[6] = s->cluster_size * 2;
636
        p[8] = (cylinders >> 8) & 0xff;
637
        p[9] = cylinders & 0xff;
638
        /* Write precomp start cylinder, disabled */
639
        p[10] = (cylinders >> 8) & 0xff;
640
        p[11] = cylinders & 0xff;
641
        /* Reduced current start cylinder, disabled */
642
        p[12] = (cylinders >> 8) & 0xff;
643
        p[13] = cylinders & 0xff;
644
        /* Device step rate [100us], 100us */
645
        p[14] = 0;
646
        p[15] = 1;
647
        /* Device step pulse width [us], 1us */
648
        p[16] = 1;
649
        /* Device head settle delay [100us], 100us */
650
        p[17] = 0;
651
        p[18] = 1;
652
        /* Motor on delay [0.1s], 0.1s */
653
        p[19] = 1;
654
        /* Motor off delay [0.1s], 0.1s */
655
        p[20] = 1;
656
        /* Medium rotation rate [rpm], 5400 rpm */
657
        p[28] = (5400 >> 8) & 0xff;
658
        p[29] = 5400 & 0xff;
659
        break;
660

    
661
    case MODE_PAGE_CACHING:
662
        p[0] = 8;
663
        p[1] = 0x12;
664
        if (page_control == 1) { /* Changeable Values */
665
            break;
666
        }
667
        if (bdrv_enable_write_cache(s->bs)) {
668
            p[2] = 4; /* WCE */
669
        }
670
        break;
671

    
672
    case MODE_PAGE_CAPABILITIES:
673
        if (s->qdev.type != TYPE_ROM) {
674
            return -1;
675
        }
676
        p[0] = 0x2a;
677
        p[1] = 0x14;
678
        if (page_control == 1) { /* Changeable Values */
679
            break;
680
        }
681
        p[2] = 3; // CD-R & CD-RW read
682
        p[3] = 0; // Writing not supported
683
        p[4] = 0x7f; /* Audio, composite, digital out,
684
                        mode 2 form 1&2, multi session */
685
        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
686
                        RW corrected, C2 errors, ISRC,
687
                        UPC, Bar code */
688
        p[6] = 0x2d | (s->tray_locked ? 2 : 0);
689
        /* Locking supported, jumper present, eject, tray */
690
        p[7] = 0; /* no volume & mute control, no
691
                     changer */
692
        p[8] = (50 * 176) >> 8; // 50x read speed
693
        p[9] = (50 * 176) & 0xff;
694
        p[10] = 0 >> 8; // No volume
695
        p[11] = 0 & 0xff;
696
        p[12] = 2048 >> 8; // 2M buffer
697
        p[13] = 2048 & 0xff;
698
        p[14] = (16 * 176) >> 8; // 16x read speed current
699
        p[15] = (16 * 176) & 0xff;
700
        p[18] = (16 * 176) >> 8; // 16x write speed
701
        p[19] = (16 * 176) & 0xff;
702
        p[20] = (16 * 176) >> 8; // 16x write speed current
703
        p[21] = (16 * 176) & 0xff;
704
        break;
705

    
706
    default:
707
        return -1;
708
    }
709

    
710
    *p_outbuf += p[1] + 2;
711
    return p[1] + 2;
712
}
713

    
714
static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
715
{
716
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
717
    uint64_t nb_sectors;
718
    int page, dbd, buflen, ret, page_control;
719
    uint8_t *p;
720
    uint8_t dev_specific_param;
721

    
722
    dbd = r->req.cmd.buf[1]  & 0x8;
723
    page = r->req.cmd.buf[2] & 0x3f;
724
    page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
725
    DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
726
        (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
727
    memset(outbuf, 0, r->req.cmd.xfer);
728
    p = outbuf;
729

    
730
    if (bdrv_is_read_only(s->bs)) {
731
        dev_specific_param = 0x80; /* Readonly.  */
732
    } else {
733
        dev_specific_param = 0x00;
734
    }
735

    
736
    if (r->req.cmd.buf[0] == MODE_SENSE) {
737
        p[1] = 0; /* Default media type.  */
738
        p[2] = dev_specific_param;
739
        p[3] = 0; /* Block descriptor length.  */
740
        p += 4;
741
    } else { /* MODE_SENSE_10 */
742
        p[2] = 0; /* Default media type.  */
743
        p[3] = dev_specific_param;
744
        p[6] = p[7] = 0; /* Block descriptor length.  */
745
        p += 8;
746
    }
747

    
748
    bdrv_get_geometry(s->bs, &nb_sectors);
749
    if (!dbd && nb_sectors) {
750
        if (r->req.cmd.buf[0] == MODE_SENSE) {
751
            outbuf[3] = 8; /* Block descriptor length  */
752
        } else { /* MODE_SENSE_10 */
753
            outbuf[7] = 8; /* Block descriptor length  */
754
        }
755
        nb_sectors /= s->cluster_size;
756
        if (nb_sectors > 0xffffff) {
757
            nb_sectors = 0;
758
        }
759
        p[0] = 0; /* media density code */
760
        p[1] = (nb_sectors >> 16) & 0xff;
761
        p[2] = (nb_sectors >> 8) & 0xff;
762
        p[3] = nb_sectors & 0xff;
763
        p[4] = 0; /* reserved */
764
        p[5] = 0; /* bytes 5-7 are the sector size in bytes */
765
        p[6] = s->cluster_size * 2;
766
        p[7] = 0;
767
        p += 8;
768
    }
769

    
770
    if (page_control == 3) {
771
        /* Saved Values */
772
        scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
773
        return -1;
774
    }
775

    
776
    if (page == 0x3f) {
777
        for (page = 0; page <= 0x3e; page++) {
778
            mode_sense_page(s, page, &p, page_control);
779
        }
780
    } else {
781
        ret = mode_sense_page(s, page, &p, page_control);
782
        if (ret == -1) {
783
            return -1;
784
        }
785
    }
786

    
787
    buflen = p - outbuf;
788
    /*
789
     * The mode data length field specifies the length in bytes of the
790
     * following data that is available to be transferred. The mode data
791
     * length does not include itself.
792
     */
793
    if (r->req.cmd.buf[0] == MODE_SENSE) {
794
        outbuf[0] = buflen - 1;
795
    } else { /* MODE_SENSE_10 */
796
        outbuf[0] = ((buflen - 2) >> 8) & 0xff;
797
        outbuf[1] = (buflen - 2) & 0xff;
798
    }
799
    if (buflen > r->req.cmd.xfer) {
800
        buflen = r->req.cmd.xfer;
801
    }
802
    return buflen;
803
}
804

    
805
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
806
{
807
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
808
    int start_track, format, msf, toclen;
809
    uint64_t nb_sectors;
810

    
811
    msf = req->cmd.buf[1] & 2;
812
    format = req->cmd.buf[2] & 0xf;
813
    start_track = req->cmd.buf[6];
814
    bdrv_get_geometry(s->bs, &nb_sectors);
815
    DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
816
    nb_sectors /= s->cluster_size;
817
    switch (format) {
818
    case 0:
819
        toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
820
        break;
821
    case 1:
822
        /* multi session : only a single session defined */
823
        toclen = 12;
824
        memset(outbuf, 0, 12);
825
        outbuf[1] = 0x0a;
826
        outbuf[2] = 0x01;
827
        outbuf[3] = 0x01;
828
        break;
829
    case 2:
830
        toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
831
        break;
832
    default:
833
        return -1;
834
    }
835
    if (toclen > req->cmd.xfer) {
836
        toclen = req->cmd.xfer;
837
    }
838
    return toclen;
839
}
840

    
841
static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
842
{
843
    SCSIRequest *req = &r->req;
844
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
845
    bool start = req->cmd.buf[4] & 1;
846
    bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
847

    
848
    if (s->qdev.type == TYPE_ROM && loej) {
849
        if (!start && !s->tray_open && s->tray_locked) {
850
            scsi_check_condition(r,
851
                                 bdrv_is_inserted(s->bs)
852
                                 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
853
                                 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
854
            return -1;
855
        }
856
        bdrv_eject(s->bs, !start);
857
        s->tray_open = !start;
858
    }
859
    return 0;
860
}
861

    
862
static int scsi_disk_emulate_command(SCSIDiskReq *r)
863
{
864
    SCSIRequest *req = &r->req;
865
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
866
    uint64_t nb_sectors;
867
    uint8_t *outbuf;
868
    int buflen = 0;
869

    
870
    if (!r->iov.iov_base) {
871
        /*
872
         * FIXME: we shouldn't return anything bigger than 4k, but the code
873
         * requires the buffer to be as big as req->cmd.xfer in several
874
         * places.  So, do not allow CDBs with a very large ALLOCATION
875
         * LENGTH.  The real fix would be to modify scsi_read_data and
876
         * dma_buf_read, so that they return data beyond the buflen
877
         * as all zeros.
878
         */
879
        if (req->cmd.xfer > 65536) {
880
            goto illegal_request;
881
        }
882
        r->buflen = MAX(4096, req->cmd.xfer);
883
        r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
884
    }
885

    
886
    outbuf = r->iov.iov_base;
887
    switch (req->cmd.buf[0]) {
888
    case TEST_UNIT_READY:
889
        if (s->tray_open || !bdrv_is_inserted(s->bs)) {
890
            goto not_ready;
891
        }
892
        break;
893
    case INQUIRY:
894
        buflen = scsi_disk_emulate_inquiry(req, outbuf);
895
        if (buflen < 0) {
896
            goto illegal_request;
897
        }
898
        break;
899
    case MODE_SENSE:
900
    case MODE_SENSE_10:
901
        buflen = scsi_disk_emulate_mode_sense(r, outbuf);
902
        if (buflen < 0) {
903
            goto illegal_request;
904
        }
905
        break;
906
    case READ_TOC:
907
        buflen = scsi_disk_emulate_read_toc(req, outbuf);
908
        if (buflen < 0) {
909
            goto illegal_request;
910
        }
911
        break;
912
    case RESERVE:
913
        if (req->cmd.buf[1] & 1) {
914
            goto illegal_request;
915
        }
916
        break;
917
    case RESERVE_10:
918
        if (req->cmd.buf[1] & 3) {
919
            goto illegal_request;
920
        }
921
        break;
922
    case RELEASE:
923
        if (req->cmd.buf[1] & 1) {
924
            goto illegal_request;
925
        }
926
        break;
927
    case RELEASE_10:
928
        if (req->cmd.buf[1] & 3) {
929
            goto illegal_request;
930
        }
931
        break;
932
    case START_STOP:
933
        if (scsi_disk_emulate_start_stop(r) < 0) {
934
            return -1;
935
        }
936
        break;
937
    case ALLOW_MEDIUM_REMOVAL:
938
        s->tray_locked = req->cmd.buf[4] & 1;
939
        bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1);
940
        break;
941
    case READ_CAPACITY_10:
942
        /* The normal LEN field for this command is zero.  */
943
        memset(outbuf, 0, 8);
944
        bdrv_get_geometry(s->bs, &nb_sectors);
945
        if (!nb_sectors) {
946
            goto not_ready;
947
        }
948
        nb_sectors /= s->cluster_size;
949
        /* Returned value is the address of the last sector.  */
950
        nb_sectors--;
951
        /* Remember the new size for read/write sanity checking. */
952
        s->max_lba = nb_sectors;
953
        /* Clip to 2TB, instead of returning capacity modulo 2TB. */
954
        if (nb_sectors > UINT32_MAX) {
955
            nb_sectors = UINT32_MAX;
956
        }
957
        outbuf[0] = (nb_sectors >> 24) & 0xff;
958
        outbuf[1] = (nb_sectors >> 16) & 0xff;
959
        outbuf[2] = (nb_sectors >> 8) & 0xff;
960
        outbuf[3] = nb_sectors & 0xff;
961
        outbuf[4] = 0;
962
        outbuf[5] = 0;
963
        outbuf[6] = s->cluster_size * 2;
964
        outbuf[7] = 0;
965
        buflen = 8;
966
        break;
967
    case GET_CONFIGURATION:
968
        memset(outbuf, 0, 8);
969
        /* ??? This should probably return much more information.  For now
970
           just return the basic header indicating the CD-ROM profile.  */
971
        outbuf[7] = 8; // CD-ROM
972
        buflen = 8;
973
        break;
974
    case SERVICE_ACTION_IN_16:
975
        /* Service Action In subcommands. */
976
        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
977
            DPRINTF("SAI READ CAPACITY(16)\n");
978
            memset(outbuf, 0, req->cmd.xfer);
979
            bdrv_get_geometry(s->bs, &nb_sectors);
980
            if (!nb_sectors) {
981
                goto not_ready;
982
            }
983
            nb_sectors /= s->cluster_size;
984
            /* Returned value is the address of the last sector.  */
985
            nb_sectors--;
986
            /* Remember the new size for read/write sanity checking. */
987
            s->max_lba = nb_sectors;
988
            outbuf[0] = (nb_sectors >> 56) & 0xff;
989
            outbuf[1] = (nb_sectors >> 48) & 0xff;
990
            outbuf[2] = (nb_sectors >> 40) & 0xff;
991
            outbuf[3] = (nb_sectors >> 32) & 0xff;
992
            outbuf[4] = (nb_sectors >> 24) & 0xff;
993
            outbuf[5] = (nb_sectors >> 16) & 0xff;
994
            outbuf[6] = (nb_sectors >> 8) & 0xff;
995
            outbuf[7] = nb_sectors & 0xff;
996
            outbuf[8] = 0;
997
            outbuf[9] = 0;
998
            outbuf[10] = s->cluster_size * 2;
999
            outbuf[11] = 0;
1000
            outbuf[12] = 0;
1001
            outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1002

    
1003
            /* set TPE bit if the format supports discard */
1004
            if (s->qdev.conf.discard_granularity) {
1005
                outbuf[14] = 0x80;
1006
            }
1007

    
1008
            /* Protection, exponent and lowest lba field left blank. */
1009
            buflen = req->cmd.xfer;
1010
            break;
1011
        }
1012
        DPRINTF("Unsupported Service Action In\n");
1013
        goto illegal_request;
1014
    case VERIFY_10:
1015
        break;
1016
    default:
1017
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1018
        return -1;
1019
    }
1020
    return buflen;
1021

    
1022
not_ready:
1023
    if (s->tray_open || !bdrv_is_inserted(s->bs)) {
1024
        scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1025
    } else {
1026
        scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1027
    }
1028
    return -1;
1029

    
1030
illegal_request:
1031
    if (r->req.status == -1) {
1032
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1033
    }
1034
    return -1;
1035
}
1036

    
1037
/* Execute a scsi command.  Returns the length of the data expected by the
1038
   command.  This will be Positive for data transfers from the device
1039
   (eg. disk reads), negative for transfers to the device (eg. disk writes),
1040
   and zero if the command does not transfer any data.  */
1041

    
1042
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
1043
{
1044
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1045
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1046
    int32_t len;
1047
    uint8_t command;
1048
    int rc;
1049

    
1050
    command = buf[0];
1051
    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);
1052

    
1053
#ifdef DEBUG_SCSI
1054
    {
1055
        int i;
1056
        for (i = 1; i < r->req.cmd.len; i++) {
1057
            printf(" 0x%02x", buf[i]);
1058
        }
1059
        printf("\n");
1060
    }
1061
#endif
1062

    
1063
    switch (command) {
1064
    case TEST_UNIT_READY:
1065
    case INQUIRY:
1066
    case MODE_SENSE:
1067
    case MODE_SENSE_10:
1068
    case RESERVE:
1069
    case RESERVE_10:
1070
    case RELEASE:
1071
    case RELEASE_10:
1072
    case START_STOP:
1073
    case ALLOW_MEDIUM_REMOVAL:
1074
    case READ_CAPACITY_10:
1075
    case READ_TOC:
1076
    case GET_CONFIGURATION:
1077
    case SERVICE_ACTION_IN_16:
1078
    case VERIFY_10:
1079
        rc = scsi_disk_emulate_command(r);
1080
        if (rc < 0) {
1081
            return 0;
1082
        }
1083

    
1084
        r->iov.iov_len = rc;
1085
        break;
1086
    case SYNCHRONIZE_CACHE:
1087
        bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1088
        r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);
1089
        if (r->req.aiocb == NULL) {
1090
            scsi_flush_complete(r, -EIO);
1091
        }
1092
        return 0;
1093
    case READ_6:
1094
    case READ_10:
1095
    case READ_12:
1096
    case READ_16:
1097
        len = r->req.cmd.xfer / s->qdev.blocksize;
1098
        DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
1099
        if (r->req.cmd.lba > s->max_lba) {
1100
            goto illegal_lba;
1101
        }
1102
        r->sector = r->req.cmd.lba * s->cluster_size;
1103
        r->sector_count = len * s->cluster_size;
1104
        break;
1105
    case WRITE_6:
1106
    case WRITE_10:
1107
    case WRITE_12:
1108
    case WRITE_16:
1109
    case WRITE_VERIFY_10:
1110
    case WRITE_VERIFY_12:
1111
    case WRITE_VERIFY_16:
1112
        len = r->req.cmd.xfer / s->qdev.blocksize;
1113
        DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
1114
                (command & 0xe) == 0xe ? "And Verify " : "",
1115
                r->req.cmd.lba, len);
1116
        if (r->req.cmd.lba > s->max_lba) {
1117
            goto illegal_lba;
1118
        }
1119
        r->sector = r->req.cmd.lba * s->cluster_size;
1120
        r->sector_count = len * s->cluster_size;
1121
        break;
1122
    case MODE_SELECT:
1123
        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1124
        /* We don't support mode parameter changes.
1125
           Allow the mode parameter header + block descriptors only. */
1126
        if (r->req.cmd.xfer > 12) {
1127
            goto fail;
1128
        }
1129
        break;
1130
    case MODE_SELECT_10:
1131
        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1132
        /* We don't support mode parameter changes.
1133
           Allow the mode parameter header + block descriptors only. */
1134
        if (r->req.cmd.xfer > 16) {
1135
            goto fail;
1136
        }
1137
        break;
1138
    case SEEK_6:
1139
    case SEEK_10:
1140
        DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,
1141
                r->req.cmd.lba);
1142
        if (r->req.cmd.lba > s->max_lba) {
1143
            goto illegal_lba;
1144
        }
1145
        break;
1146
    case WRITE_SAME_16:
1147
        len = r->req.cmd.xfer / s->qdev.blocksize;
1148

    
1149
        DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",
1150
                r->req.cmd.lba, len);
1151

    
1152
        if (r->req.cmd.lba > s->max_lba) {
1153
            goto illegal_lba;
1154
        }
1155

    
1156
        /*
1157
         * We only support WRITE SAME with the unmap bit set for now.
1158
         */
1159
        if (!(buf[1] & 0x8)) {
1160
            goto fail;
1161
        }
1162

    
1163
        rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,
1164
                          len * s->cluster_size);
1165
        if (rc < 0) {
1166
            /* XXX: better error code ?*/
1167
            goto fail;
1168
        }
1169

    
1170
        break;
1171
    case REQUEST_SENSE:
1172
        abort();
1173
    default:
1174
        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1175
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1176
        return 0;
1177
    fail:
1178
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1179
        return 0;
1180
    illegal_lba:
1181
        scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1182
        return 0;
1183
    }
1184
    if (r->sector_count == 0 && r->iov.iov_len == 0) {
1185
        scsi_req_complete(&r->req, GOOD);
1186
    }
1187
    len = r->sector_count * 512 + r->iov.iov_len;
1188
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1189
        return -len;
1190
    } else {
1191
        if (!r->sector_count) {
1192
            r->sector_count = -1;
1193
        }
1194
        return len;
1195
    }
1196
}
1197

    
1198
static void scsi_disk_reset(DeviceState *dev)
1199
{
1200
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1201
    uint64_t nb_sectors;
1202

    
1203
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1204

    
1205
    bdrv_get_geometry(s->bs, &nb_sectors);
1206
    nb_sectors /= s->cluster_size;
1207
    if (nb_sectors) {
1208
        nb_sectors--;
1209
    }
1210
    s->max_lba = nb_sectors;
1211
}
1212

    
1213
static void scsi_destroy(SCSIDevice *dev)
1214
{
1215
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1216

    
1217
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1218
    blockdev_mark_auto_del(s->qdev.conf.bs);
1219
}
1220

    
1221
static void scsi_cd_change_media_cb(void *opaque, bool load)
1222
{
1223
    SCSIDiskState *s = opaque;
1224

    
1225
    /*
1226
     * When a CD gets changed, we have to report an ejected state and
1227
     * then a loaded state to guests so that they detect tray
1228
     * open/close and media change events.  Guests that do not use
1229
     * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1230
     * states rely on this behavior.
1231
     *
1232
     * media_changed governs the state machine used for unit attention
1233
     * report.  media_event is used by GET EVENT STATUS NOTIFICATION.
1234
     */
1235
    s->media_changed = load;
1236
    s->tray_open = !load;
1237
    s->qdev.unit_attention = SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM);
1238
}
1239

    
1240
static bool scsi_cd_is_tray_open(void *opaque)
1241
{
1242
    return ((SCSIDiskState *)opaque)->tray_open;
1243
}
1244

    
1245
static bool scsi_cd_is_medium_locked(void *opaque)
1246
{
1247
    return ((SCSIDiskState *)opaque)->tray_locked;
1248
}
1249

    
1250
static const BlockDevOps scsi_cd_block_ops = {
1251
    .change_media_cb = scsi_cd_change_media_cb,
1252
    .is_tray_open = scsi_cd_is_tray_open,
1253
    .is_medium_locked = scsi_cd_is_medium_locked,
1254
};
1255

    
1256
static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
1257
{
1258
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1259
    if (s->media_changed) {
1260
        s->media_changed = false;
1261
        s->qdev.unit_attention = SENSE_CODE(MEDIUM_CHANGED);
1262
    }
1263
}
1264

    
1265
static int scsi_initfn(SCSIDevice *dev, uint8_t scsi_type)
1266
{
1267
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1268
    DriveInfo *dinfo;
1269

    
1270
    if (!s->qdev.conf.bs) {
1271
        error_report("scsi-disk: drive property not set");
1272
        return -1;
1273
    }
1274
    s->bs = s->qdev.conf.bs;
1275

    
1276
    if (scsi_type == TYPE_DISK && !bdrv_is_inserted(s->bs)) {
1277
        error_report("Device needs media, but drive is empty");
1278
        return -1;
1279
    }
1280

    
1281
    if (!s->serial) {
1282
        /* try to fall back to value set with legacy -drive serial=... */
1283
        dinfo = drive_get_by_blockdev(s->bs);
1284
        if (*dinfo->serial) {
1285
            s->serial = g_strdup(dinfo->serial);
1286
        }
1287
    }
1288

    
1289
    if (!s->version) {
1290
        s->version = g_strdup(QEMU_VERSION);
1291
    }
1292

    
1293
    if (bdrv_is_sg(s->bs)) {
1294
        error_report("scsi-disk: unwanted /dev/sg*");
1295
        return -1;
1296
    }
1297

    
1298
    if (scsi_type == TYPE_ROM) {
1299
        bdrv_set_dev_ops(s->bs, &scsi_cd_block_ops, s);
1300
        s->qdev.blocksize = 2048;
1301
    } else if (scsi_type == TYPE_DISK) {
1302
        s->qdev.blocksize = s->qdev.conf.logical_block_size;
1303
    } else {
1304
        error_report("scsi-disk: Unhandled SCSI type %02x", scsi_type);
1305
        return -1;
1306
    }
1307
    s->cluster_size = s->qdev.blocksize / 512;
1308
    bdrv_set_buffer_alignment(s->bs, s->qdev.blocksize);
1309

    
1310
    s->qdev.type = scsi_type;
1311
    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
1312
    bdrv_iostatus_enable(s->bs);
1313
    add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, ",0");
1314
    return 0;
1315
}
1316

    
1317
static int scsi_hd_initfn(SCSIDevice *dev)
1318
{
1319
    return scsi_initfn(dev, TYPE_DISK);
1320
}
1321

    
1322
static int scsi_cd_initfn(SCSIDevice *dev)
1323
{
1324
    return scsi_initfn(dev, TYPE_ROM);
1325
}
1326

    
1327
static int scsi_disk_initfn(SCSIDevice *dev)
1328
{
1329
    DriveInfo *dinfo;
1330
    uint8_t scsi_type;
1331

    
1332
    if (!dev->conf.bs) {
1333
        scsi_type = TYPE_DISK;  /* will die in scsi_initfn() */
1334
    } else {
1335
        dinfo = drive_get_by_blockdev(dev->conf.bs);
1336
        scsi_type = dinfo->media_cd ? TYPE_ROM : TYPE_DISK;
1337
    }
1338

    
1339
    return scsi_initfn(dev, scsi_type);
1340
}
1341

    
1342
static SCSIReqOps scsi_disk_reqops = {
1343
    .size         = sizeof(SCSIDiskReq),
1344
    .free_req     = scsi_free_request,
1345
    .send_command = scsi_send_command,
1346
    .read_data    = scsi_read_data,
1347
    .write_data   = scsi_write_data,
1348
    .cancel_io    = scsi_cancel_io,
1349
    .get_buf      = scsi_get_buf,
1350
};
1351

    
1352
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
1353
                                     uint32_t lun, void *hba_private)
1354
{
1355
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
1356
    SCSIRequest *req;
1357

    
1358
    req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
1359
    return req;
1360
}
1361

    
1362
#define DEFINE_SCSI_DISK_PROPERTIES()                           \
1363
    DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),          \
1364
    DEFINE_PROP_STRING("ver",  SCSIDiskState, version),         \
1365
    DEFINE_PROP_STRING("serial",  SCSIDiskState, serial)
1366

    
1367
static SCSIDeviceInfo scsi_disk_info[] = {
1368
    {
1369
        .qdev.name    = "scsi-hd",
1370
        .qdev.fw_name = "disk",
1371
        .qdev.desc    = "virtual SCSI disk",
1372
        .qdev.size    = sizeof(SCSIDiskState),
1373
        .qdev.reset   = scsi_disk_reset,
1374
        .init         = scsi_hd_initfn,
1375
        .destroy      = scsi_destroy,
1376
        .alloc_req    = scsi_new_request,
1377
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1378
        .qdev.props   = (Property[]) {
1379
            DEFINE_SCSI_DISK_PROPERTIES(),
1380
            DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
1381
            DEFINE_PROP_END_OF_LIST(),
1382
        }
1383
    },{
1384
        .qdev.name    = "scsi-cd",
1385
        .qdev.fw_name = "disk",
1386
        .qdev.desc    = "virtual SCSI CD-ROM",
1387
        .qdev.size    = sizeof(SCSIDiskState),
1388
        .qdev.reset   = scsi_disk_reset,
1389
        .init         = scsi_cd_initfn,
1390
        .destroy      = scsi_destroy,
1391
        .alloc_req    = scsi_new_request,
1392
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1393
        .qdev.props   = (Property[]) {
1394
            DEFINE_SCSI_DISK_PROPERTIES(),
1395
            DEFINE_PROP_END_OF_LIST(),
1396
        },
1397
    },{
1398
        .qdev.name    = "scsi-disk", /* legacy -device scsi-disk */
1399
        .qdev.fw_name = "disk",
1400
        .qdev.desc    = "virtual SCSI disk or CD-ROM (legacy)",
1401
        .qdev.size    = sizeof(SCSIDiskState),
1402
        .qdev.reset   = scsi_disk_reset,
1403
        .init         = scsi_disk_initfn,
1404
        .destroy      = scsi_destroy,
1405
        .alloc_req    = scsi_new_request,
1406
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1407
        .qdev.props   = (Property[]) {
1408
            DEFINE_SCSI_DISK_PROPERTIES(),
1409
            DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
1410
            DEFINE_PROP_END_OF_LIST(),
1411
        }
1412
    }
1413
};
1414

    
1415
static void scsi_disk_register_devices(void)
1416
{
1417
    int i;
1418

    
1419
    for (i = 0; i < ARRAY_SIZE(scsi_disk_info); i++) {
1420
        scsi_qdev_register(&scsi_disk_info[i]);
1421
    }
1422
}
1423
device_init(scsi_disk_register_devices)