Statistics
| Branch: | Revision:

root / hw / scsi-disk.c @ da8365db

History | View | Annotate | Download (61.2 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
#include "dma.h"
42

    
43
#ifdef __linux
44
#include <scsi/sg.h>
45
#endif
46

    
47
#define SCSI_DMA_BUF_SIZE    131072
48
#define SCSI_MAX_INQUIRY_LEN 256
49

    
50
typedef struct SCSIDiskState SCSIDiskState;
51

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

    
64
#define SCSI_DISK_F_REMOVABLE   0
65
#define SCSI_DISK_F_DPOFUA      1
66

    
67
struct SCSIDiskState
68
{
69
    SCSIDevice qdev;
70
    uint32_t features;
71
    bool media_changed;
72
    bool media_event;
73
    bool eject_request;
74
    QEMUBH *bh;
75
    char *version;
76
    char *serial;
77
    bool tray_open;
78
    bool tray_locked;
79
};
80

    
81
static int scsi_handle_rw_error(SCSIDiskReq *r, int error);
82

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

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

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

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

    
106
    DPRINTF("Cancel tag=0x%x\n", req->tag);
107
    if (r->req.aiocb) {
108
        bdrv_aio_cancel(r->req.aiocb);
109

    
110
        /* This reference was left in by scsi_*_data.  We take ownership of
111
         * it the moment scsi_req_cancel is called, independent of whether
112
         * bdrv_aio_cancel completes the request or not.  */
113
        scsi_req_unref(&r->req);
114
    }
115
    r->req.aiocb = NULL;
116
}
117

    
118
static uint32_t scsi_init_iovec(SCSIDiskReq *r, size_t size)
119
{
120
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
121

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

    
131
static void scsi_disk_save_request(QEMUFile *f, SCSIRequest *req)
132
{
133
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
134

    
135
    qemu_put_be64s(f, &r->sector);
136
    qemu_put_be32s(f, &r->sector_count);
137
    qemu_put_be32s(f, &r->buflen);
138
    if (r->buflen && r->req.cmd.mode == SCSI_XFER_TO_DEV) {
139
        qemu_put_buffer(f, r->iov.iov_base, r->iov.iov_len);
140
    }
141
}
142

    
143
static void scsi_disk_load_request(QEMUFile *f, SCSIRequest *req)
144
{
145
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
146

    
147
    qemu_get_be64s(f, &r->sector);
148
    qemu_get_be32s(f, &r->sector_count);
149
    qemu_get_be32s(f, &r->buflen);
150
    if (r->buflen) {
151
        scsi_init_iovec(r, r->buflen);
152
        if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
153
            qemu_get_buffer(f, r->iov.iov_base, r->iov.iov_len);
154
        }
155
    }
156

    
157
    qemu_iovec_init_external(&r->qiov, &r->iov, 1);
158
}
159

    
160
static void scsi_flush_complete(void * opaque, int ret)
161
{
162
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
163
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
164

    
165
    bdrv_acct_done(s->qdev.conf.bs, &r->acct);
166

    
167
    if (ret < 0) {
168
        if (scsi_handle_rw_error(r, -ret)) {
169
            goto done;
170
        }
171
    }
172

    
173
    scsi_req_complete(&r->req, GOOD);
174

    
175
done:
176
    if (!r->req.io_canceled) {
177
        scsi_req_unref(&r->req);
178
    }
179
}
180

    
181
static bool scsi_is_cmd_fua(SCSICommand *cmd)
182
{
183
    switch (cmd->buf[0]) {
184
    case READ_10:
185
    case READ_12:
186
    case READ_16:
187
    case WRITE_10:
188
    case WRITE_12:
189
    case WRITE_16:
190
        return (cmd->buf[1] & 8) != 0;
191

    
192
    case VERIFY_10:
193
    case VERIFY_12:
194
    case VERIFY_16:
195
    case WRITE_VERIFY_10:
196
    case WRITE_VERIFY_12:
197
    case WRITE_VERIFY_16:
198
        return true;
199

    
200
    case READ_6:
201
    case WRITE_6:
202
    default:
203
        return false;
204
    }
205
}
206

    
207
static void scsi_write_do_fua(SCSIDiskReq *r)
208
{
209
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
210

    
211
    if (scsi_is_cmd_fua(&r->req.cmd)) {
212
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
213
        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_flush_complete, r);
214
        return;
215
    }
216

    
217
    scsi_req_complete(&r->req, GOOD);
218
    if (!r->req.io_canceled) {
219
        scsi_req_unref(&r->req);
220
    }
221
}
222

    
223
static void scsi_dma_complete(void *opaque, int ret)
224
{
225
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
226
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
227

    
228
    if (r->req.aiocb != NULL) {
229
        r->req.aiocb = NULL;
230
        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
231
    }
232

    
233
    if (ret < 0) {
234
        if (scsi_handle_rw_error(r, -ret)) {
235
            goto done;
236
        }
237
    }
238

    
239
    r->sector += r->sector_count;
240
    r->sector_count = 0;
241
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
242
        scsi_write_do_fua(r);
243
        return;
244
    } else {
245
        scsi_req_complete(&r->req, GOOD);
246
    }
247

    
248
done:
249
    if (!r->req.io_canceled) {
250
        scsi_req_unref(&r->req);
251
    }
252
}
253

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

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

    
265
    if (ret < 0) {
266
        if (scsi_handle_rw_error(r, -ret)) {
267
            goto done;
268
        }
269
    }
270

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

    
273
    n = r->qiov.size / 512;
274
    r->sector += n;
275
    r->sector_count -= n;
276
    scsi_req_data(&r->req, r->qiov.size);
277

    
278
done:
279
    if (!r->req.io_canceled) {
280
        scsi_req_unref(&r->req);
281
    }
282
}
283

    
284
/* Actually issue a read to the block device.  */
285
static void scsi_do_read(void *opaque, int ret)
286
{
287
    SCSIDiskReq *r = opaque;
288
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
289
    uint32_t n;
290

    
291
    if (r->req.aiocb != NULL) {
292
        r->req.aiocb = NULL;
293
        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
294
    }
295

    
296
    if (ret < 0) {
297
        if (scsi_handle_rw_error(r, -ret)) {
298
            goto done;
299
        }
300
    }
301

    
302
    if (r->req.io_canceled) {
303
        return;
304
    }
305

    
306
    /* The request is used as the AIO opaque value, so add a ref.  */
307
    scsi_req_ref(&r->req);
308

    
309
    if (r->req.sg) {
310
        dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ);
311
        r->req.resid -= r->req.sg->size;
312
        r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector,
313
                                     scsi_dma_complete, r);
314
    } else {
315
        n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
316
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
317
        r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n,
318
                                      scsi_read_complete, r);
319
    }
320

    
321
done:
322
    if (!r->req.io_canceled) {
323
        scsi_req_unref(&r->req);
324
    }
325
}
326

    
327
/* Read more data from scsi device into buffer.  */
328
static void scsi_read_data(SCSIRequest *req)
329
{
330
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
331
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
332
    bool first;
333

    
334
    if (r->sector_count == (uint32_t)-1) {
335
        DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
336
        r->sector_count = 0;
337
        r->started = true;
338
        scsi_req_data(&r->req, r->iov.iov_len);
339
        return;
340
    }
341
    DPRINTF("Read sector_count=%d\n", r->sector_count);
342
    if (r->sector_count == 0) {
343
        /* This also clears the sense buffer for REQUEST SENSE.  */
344
        scsi_req_complete(&r->req, GOOD);
345
        return;
346
    }
347

    
348
    /* No data transfer may already be in progress */
349
    assert(r->req.aiocb == NULL);
350

    
351
    /* The request is used as the AIO opaque value, so add a ref.  */
352
    scsi_req_ref(&r->req);
353
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
354
        DPRINTF("Data transfer direction invalid\n");
355
        scsi_read_complete(r, -EINVAL);
356
        return;
357
    }
358

    
359
    if (s->tray_open) {
360
        scsi_read_complete(r, -ENOMEDIUM);
361
        return;
362
    }
363

    
364
    first = !r->started;
365
    r->started = true;
366
    if (first && scsi_is_cmd_fua(&r->req.cmd)) {
367
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
368
        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_do_read, r);
369
    } else {
370
        scsi_do_read(r, 0);
371
    }
372
}
373

    
374
/*
375
 * scsi_handle_rw_error has two return values.  0 means that the error
376
 * must be ignored, 1 means that the error has been processed and the
377
 * caller should not do anything else for this request.  Note that
378
 * scsi_handle_rw_error always manages its reference counts, independent
379
 * of the return value.
380
 */
381
static int scsi_handle_rw_error(SCSIDiskReq *r, int error)
382
{
383
    int is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV);
384
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
385
    BlockErrorAction action = bdrv_get_on_error(s->qdev.conf.bs, is_read);
386

    
387
    if (action == BLOCK_ERR_IGNORE) {
388
        bdrv_emit_qmp_error_event(s->qdev.conf.bs, BDRV_ACTION_IGNORE, is_read);
389
        return 0;
390
    }
391

    
392
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
393
            || action == BLOCK_ERR_STOP_ANY) {
394

    
395
        bdrv_emit_qmp_error_event(s->qdev.conf.bs, BDRV_ACTION_STOP, is_read);
396
        vm_stop(RUN_STATE_IO_ERROR);
397
        bdrv_iostatus_set_err(s->qdev.conf.bs, error);
398
        scsi_req_retry(&r->req);
399
    } else {
400
        switch (error) {
401
        case ENOMEDIUM:
402
            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
403
            break;
404
        case ENOMEM:
405
            scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
406
            break;
407
        case EINVAL:
408
            scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
409
            break;
410
        default:
411
            scsi_check_condition(r, SENSE_CODE(IO_ERROR));
412
            break;
413
        }
414
        bdrv_emit_qmp_error_event(s->qdev.conf.bs, BDRV_ACTION_REPORT, is_read);
415
    }
416
    return 1;
417
}
418

    
419
static void scsi_write_complete(void * opaque, int ret)
420
{
421
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
422
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
423
    uint32_t n;
424

    
425
    if (r->req.aiocb != NULL) {
426
        r->req.aiocb = NULL;
427
        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
428
    }
429

    
430
    if (ret < 0) {
431
        if (scsi_handle_rw_error(r, -ret)) {
432
            goto done;
433
        }
434
    }
435

    
436
    n = r->qiov.size / 512;
437
    r->sector += n;
438
    r->sector_count -= n;
439
    if (r->sector_count == 0) {
440
        scsi_write_do_fua(r);
441
        return;
442
    } else {
443
        scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
444
        DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);
445
        scsi_req_data(&r->req, r->qiov.size);
446
    }
447

    
448
done:
449
    if (!r->req.io_canceled) {
450
        scsi_req_unref(&r->req);
451
    }
452
}
453

    
454
static void scsi_write_data(SCSIRequest *req)
455
{
456
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
457
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
458
    uint32_t n;
459

    
460
    /* No data transfer may already be in progress */
461
    assert(r->req.aiocb == NULL);
462

    
463
    /* The request is used as the AIO opaque value, so add a ref.  */
464
    scsi_req_ref(&r->req);
465
    if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
466
        DPRINTF("Data transfer direction invalid\n");
467
        scsi_write_complete(r, -EINVAL);
468
        return;
469
    }
470

    
471
    if (!r->req.sg && !r->qiov.size) {
472
        /* Called for the first time.  Ask the driver to send us more data.  */
473
        r->started = true;
474
        scsi_write_complete(r, 0);
475
        return;
476
    }
477
    if (s->tray_open) {
478
        scsi_write_complete(r, -ENOMEDIUM);
479
        return;
480
    }
481

    
482
    if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
483
        r->req.cmd.buf[0] == VERIFY_16) {
484
        if (r->req.sg) {
485
            scsi_dma_complete(r, 0);
486
        } else {
487
            scsi_write_complete(r, 0);
488
        }
489
        return;
490
    }
491

    
492
    if (r->req.sg) {
493
        dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_WRITE);
494
        r->req.resid -= r->req.sg->size;
495
        r->req.aiocb = dma_bdrv_write(s->qdev.conf.bs, r->req.sg, r->sector,
496
                                      scsi_dma_complete, r);
497
    } else {
498
        n = r->qiov.size / 512;
499
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
500
        r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, r->sector, &r->qiov, n,
501
                                       scsi_write_complete, r);
502
    }
503
}
504

    
505
/* Return a pointer to the data buffer.  */
506
static uint8_t *scsi_get_buf(SCSIRequest *req)
507
{
508
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
509

    
510
    return (uint8_t *)r->iov.iov_base;
511
}
512

    
513
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
514
{
515
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
516
    int buflen = 0;
517

    
518
    if (req->cmd.buf[1] & 0x2) {
519
        /* Command support data - optional, not implemented */
520
        BADF("optional INQUIRY command support request not implemented\n");
521
        return -1;
522
    }
523

    
524
    if (req->cmd.buf[1] & 0x1) {
525
        /* Vital product data */
526
        uint8_t page_code = req->cmd.buf[2];
527
        if (req->cmd.xfer < 4) {
528
            BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "
529
                 "less than 4\n", page_code, req->cmd.xfer);
530
            return -1;
531
        }
532

    
533
        outbuf[buflen++] = s->qdev.type & 0x1f;
534
        outbuf[buflen++] = page_code ; // this page
535
        outbuf[buflen++] = 0x00;
536

    
537
        switch (page_code) {
538
        case 0x00: /* Supported page codes, mandatory */
539
        {
540
            int pages;
541
            DPRINTF("Inquiry EVPD[Supported pages] "
542
                    "buffer size %zd\n", req->cmd.xfer);
543
            pages = buflen++;
544
            outbuf[buflen++] = 0x00; // list of supported pages (this page)
545
            if (s->serial) {
546
                outbuf[buflen++] = 0x80; // unit serial number
547
            }
548
            outbuf[buflen++] = 0x83; // device identification
549
            if (s->qdev.type == TYPE_DISK) {
550
                outbuf[buflen++] = 0xb0; // block limits
551
                outbuf[buflen++] = 0xb2; // thin provisioning
552
            }
553
            outbuf[pages] = buflen - pages - 1; // number of pages
554
            break;
555
        }
556
        case 0x80: /* Device serial number, optional */
557
        {
558
            int l;
559

    
560
            if (!s->serial) {
561
                DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
562
                return -1;
563
            }
564

    
565
            l = strlen(s->serial);
566
            if (l > 20) {
567
                l = 20;
568
            }
569

    
570
            DPRINTF("Inquiry EVPD[Serial number] "
571
                    "buffer size %zd\n", req->cmd.xfer);
572
            outbuf[buflen++] = l;
573
            memcpy(outbuf+buflen, s->serial, l);
574
            buflen += l;
575
            break;
576
        }
577

    
578
        case 0x83: /* Device identification page, mandatory */
579
        {
580
            const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs);
581
            int max_len = s->serial ? 20 : 255 - 8;
582
            int id_len = strlen(str);
583

    
584
            if (id_len > max_len) {
585
                id_len = max_len;
586
            }
587
            DPRINTF("Inquiry EVPD[Device identification] "
588
                    "buffer size %zd\n", req->cmd.xfer);
589

    
590
            outbuf[buflen++] = 4 + id_len;
591
            outbuf[buflen++] = 0x2; // ASCII
592
            outbuf[buflen++] = 0;   // not officially assigned
593
            outbuf[buflen++] = 0;   // reserved
594
            outbuf[buflen++] = id_len; // length of data following
595

    
596
            memcpy(outbuf+buflen, str, id_len);
597
            buflen += id_len;
598
            break;
599
        }
600
        case 0xb0: /* block limits */
601
        {
602
            unsigned int unmap_sectors =
603
                    s->qdev.conf.discard_granularity / s->qdev.blocksize;
604
            unsigned int min_io_size =
605
                    s->qdev.conf.min_io_size / s->qdev.blocksize;
606
            unsigned int opt_io_size =
607
                    s->qdev.conf.opt_io_size / s->qdev.blocksize;
608

    
609
            if (s->qdev.type == TYPE_ROM) {
610
                DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
611
                        page_code);
612
                return -1;
613
            }
614
            /* required VPD size with unmap support */
615
            outbuf[3] = buflen = 0x3c;
616

    
617
            memset(outbuf + 4, 0, buflen - 4);
618

    
619
            /* optimal transfer length granularity */
620
            outbuf[6] = (min_io_size >> 8) & 0xff;
621
            outbuf[7] = min_io_size & 0xff;
622

    
623
            /* optimal transfer length */
624
            outbuf[12] = (opt_io_size >> 24) & 0xff;
625
            outbuf[13] = (opt_io_size >> 16) & 0xff;
626
            outbuf[14] = (opt_io_size >> 8) & 0xff;
627
            outbuf[15] = opt_io_size & 0xff;
628

    
629
            /* optimal unmap granularity */
630
            outbuf[28] = (unmap_sectors >> 24) & 0xff;
631
            outbuf[29] = (unmap_sectors >> 16) & 0xff;
632
            outbuf[30] = (unmap_sectors >> 8) & 0xff;
633
            outbuf[31] = unmap_sectors & 0xff;
634
            break;
635
        }
636
        case 0xb2: /* thin provisioning */
637
        {
638
            outbuf[3] = buflen = 8;
639
            outbuf[4] = 0;
640
            outbuf[5] = 0x60; /* write_same 10/16 supported */
641
            outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
642
            outbuf[7] = 0;
643
            break;
644
        }
645
        default:
646
            BADF("Error: unsupported Inquiry (EVPD[%02X]) "
647
                 "buffer size %zd\n", page_code, req->cmd.xfer);
648
            return -1;
649
        }
650
        /* done with EVPD */
651
        return buflen;
652
    }
653

    
654
    /* Standard INQUIRY data */
655
    if (req->cmd.buf[2] != 0) {
656
        BADF("Error: Inquiry (STANDARD) page or code "
657
             "is non-zero [%02X]\n", req->cmd.buf[2]);
658
        return -1;
659
    }
660

    
661
    /* PAGE CODE == 0 */
662
    if (req->cmd.xfer < 5) {
663
        BADF("Error: Inquiry (STANDARD) buffer size %zd "
664
             "is less than 5\n", req->cmd.xfer);
665
        return -1;
666
    }
667

    
668
    buflen = req->cmd.xfer;
669
    if (buflen > SCSI_MAX_INQUIRY_LEN) {
670
        buflen = SCSI_MAX_INQUIRY_LEN;
671
    }
672
    memset(outbuf, 0, buflen);
673

    
674
    outbuf[0] = s->qdev.type & 0x1f;
675
    outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;
676
    if (s->qdev.type == TYPE_ROM) {
677
        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);
678
    } else {
679
        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);
680
    }
681
    memcpy(&outbuf[8], "QEMU    ", 8);
682
    memset(&outbuf[32], 0, 4);
683
    memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
684
    /*
685
     * We claim conformance to SPC-3, which is required for guests
686
     * to ask for modern features like READ CAPACITY(16) or the
687
     * block characteristics VPD page by default.  Not all of SPC-3
688
     * is actually implemented, but we're good enough.
689
     */
690
    outbuf[2] = 5;
691
    outbuf[3] = 2; /* Format 2 */
692

    
693
    if (buflen > 36) {
694
        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
695
    } else {
696
        /* If the allocation length of CDB is too small,
697
               the additional length is not adjusted */
698
        outbuf[4] = 36 - 5;
699
    }
700

    
701
    /* Sync data transfer and TCQ.  */
702
    outbuf[7] = 0x10 | (req->bus->info->tcq ? 0x02 : 0);
703
    return buflen;
704
}
705

    
706
static inline bool media_is_dvd(SCSIDiskState *s)
707
{
708
    uint64_t nb_sectors;
709
    if (s->qdev.type != TYPE_ROM) {
710
        return false;
711
    }
712
    if (!bdrv_is_inserted(s->qdev.conf.bs)) {
713
        return false;
714
    }
715
    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
716
    return nb_sectors > CD_MAX_SECTORS;
717
}
718

    
719
static inline bool media_is_cd(SCSIDiskState *s)
720
{
721
    uint64_t nb_sectors;
722
    if (s->qdev.type != TYPE_ROM) {
723
        return false;
724
    }
725
    if (!bdrv_is_inserted(s->qdev.conf.bs)) {
726
        return false;
727
    }
728
    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
729
    return nb_sectors <= CD_MAX_SECTORS;
730
}
731

    
732
static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
733
                                   uint8_t *outbuf)
734
{
735
    static const int rds_caps_size[5] = {
736
        [0] = 2048 + 4,
737
        [1] = 4 + 4,
738
        [3] = 188 + 4,
739
        [4] = 2048 + 4,
740
    };
741

    
742
    uint8_t media = r->req.cmd.buf[1];
743
    uint8_t layer = r->req.cmd.buf[6];
744
    uint8_t format = r->req.cmd.buf[7];
745
    int size = -1;
746

    
747
    if (s->qdev.type != TYPE_ROM) {
748
        return -1;
749
    }
750
    if (media != 0) {
751
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
752
        return -1;
753
    }
754

    
755
    if (format != 0xff) {
756
        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
757
            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
758
            return -1;
759
        }
760
        if (media_is_cd(s)) {
761
            scsi_check_condition(r, SENSE_CODE(INCOMPATIBLE_FORMAT));
762
            return -1;
763
        }
764
        if (format >= ARRAY_SIZE(rds_caps_size)) {
765
            return -1;
766
        }
767
        size = rds_caps_size[format];
768
        memset(outbuf, 0, size);
769
    }
770

    
771
    switch (format) {
772
    case 0x00: {
773
        /* Physical format information */
774
        uint64_t nb_sectors;
775
        if (layer != 0) {
776
            goto fail;
777
        }
778
        bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
779

    
780
        outbuf[4] = 1;   /* DVD-ROM, part version 1 */
781
        outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
782
        outbuf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
783
        outbuf[7] = 0;   /* default densities */
784

    
785
        stl_be_p(&outbuf[12], (nb_sectors >> 2) - 1); /* end sector */
786
        stl_be_p(&outbuf[16], (nb_sectors >> 2) - 1); /* l0 end sector */
787
        break;
788
    }
789

    
790
    case 0x01: /* DVD copyright information, all zeros */
791
        break;
792

    
793
    case 0x03: /* BCA information - invalid field for no BCA info */
794
        return -1;
795

    
796
    case 0x04: /* DVD disc manufacturing information, all zeros */
797
        break;
798

    
799
    case 0xff: { /* List capabilities */
800
        int i;
801
        size = 4;
802
        for (i = 0; i < ARRAY_SIZE(rds_caps_size); i++) {
803
            if (!rds_caps_size[i]) {
804
                continue;
805
            }
806
            outbuf[size] = i;
807
            outbuf[size + 1] = 0x40; /* Not writable, readable */
808
            stw_be_p(&outbuf[size + 2], rds_caps_size[i]);
809
            size += 4;
810
        }
811
        break;
812
     }
813

    
814
    default:
815
        return -1;
816
    }
817

    
818
    /* Size of buffer, not including 2 byte size field */
819
    stw_be_p(outbuf, size - 2);
820
    return size;
821

    
822
fail:
823
    return -1;
824
}
825

    
826
static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf)
827
{
828
    uint8_t event_code, media_status;
829

    
830
    media_status = 0;
831
    if (s->tray_open) {
832
        media_status = MS_TRAY_OPEN;
833
    } else if (bdrv_is_inserted(s->qdev.conf.bs)) {
834
        media_status = MS_MEDIA_PRESENT;
835
    }
836

    
837
    /* Event notification descriptor */
838
    event_code = MEC_NO_CHANGE;
839
    if (media_status != MS_TRAY_OPEN) {
840
        if (s->media_event) {
841
            event_code = MEC_NEW_MEDIA;
842
            s->media_event = false;
843
        } else if (s->eject_request) {
844
            event_code = MEC_EJECT_REQUESTED;
845
            s->eject_request = false;
846
        }
847
    }
848

    
849
    outbuf[0] = event_code;
850
    outbuf[1] = media_status;
851

    
852
    /* These fields are reserved, just clear them. */
853
    outbuf[2] = 0;
854
    outbuf[3] = 0;
855
    return 4;
856
}
857

    
858
static int scsi_get_event_status_notification(SCSIDiskState *s, SCSIDiskReq *r,
859
                                              uint8_t *outbuf)
860
{
861
    int size;
862
    uint8_t *buf = r->req.cmd.buf;
863
    uint8_t notification_class_request = buf[4];
864
    if (s->qdev.type != TYPE_ROM) {
865
        return -1;
866
    }
867
    if ((buf[1] & 1) == 0) {
868
        /* asynchronous */
869
        return -1;
870
    }
871

    
872
    size = 4;
873
    outbuf[0] = outbuf[1] = 0;
874
    outbuf[3] = 1 << GESN_MEDIA; /* supported events */
875
    if (notification_class_request & (1 << GESN_MEDIA)) {
876
        outbuf[2] = GESN_MEDIA;
877
        size += scsi_event_status_media(s, &outbuf[size]);
878
    } else {
879
        outbuf[2] = 0x80;
880
    }
881
    stw_be_p(outbuf, size - 4);
882
    return size;
883
}
884

    
885
static int scsi_get_configuration(SCSIDiskState *s, uint8_t *outbuf)
886
{
887
    int current;
888

    
889
    if (s->qdev.type != TYPE_ROM) {
890
        return -1;
891
    }
892
    current = media_is_dvd(s) ? MMC_PROFILE_DVD_ROM : MMC_PROFILE_CD_ROM;
893
    memset(outbuf, 0, 40);
894
    stl_be_p(&outbuf[0], 36); /* Bytes after the data length field */
895
    stw_be_p(&outbuf[6], current);
896
    /* outbuf[8] - outbuf[19]: Feature 0 - Profile list */
897
    outbuf[10] = 0x03; /* persistent, current */
898
    outbuf[11] = 8; /* two profiles */
899
    stw_be_p(&outbuf[12], MMC_PROFILE_DVD_ROM);
900
    outbuf[14] = (current == MMC_PROFILE_DVD_ROM);
901
    stw_be_p(&outbuf[16], MMC_PROFILE_CD_ROM);
902
    outbuf[18] = (current == MMC_PROFILE_CD_ROM);
903
    /* outbuf[20] - outbuf[31]: Feature 1 - Core feature */
904
    stw_be_p(&outbuf[20], 1);
905
    outbuf[22] = 0x08 | 0x03; /* version 2, persistent, current */
906
    outbuf[23] = 8;
907
    stl_be_p(&outbuf[24], 1); /* SCSI */
908
    outbuf[28] = 1; /* DBE = 1, mandatory */
909
    /* outbuf[32] - outbuf[39]: Feature 3 - Removable media feature */
910
    stw_be_p(&outbuf[32], 3);
911
    outbuf[34] = 0x08 | 0x03; /* version 2, persistent, current */
912
    outbuf[35] = 4;
913
    outbuf[36] = 0x39; /* tray, load=1, eject=1, unlocked at powerup, lock=1 */
914
    /* TODO: Random readable, CD read, DVD read, drive serial number,
915
       power management */
916
    return 40;
917
}
918

    
919
static int scsi_emulate_mechanism_status(SCSIDiskState *s, uint8_t *outbuf)
920
{
921
    if (s->qdev.type != TYPE_ROM) {
922
        return -1;
923
    }
924
    memset(outbuf, 0, 8);
925
    outbuf[5] = 1; /* CD-ROM */
926
    return 8;
927
}
928

    
929
static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
930
                           int page_control)
931
{
932
    static const int mode_sense_valid[0x3f] = {
933
        [MODE_PAGE_HD_GEOMETRY]            = (1 << TYPE_DISK),
934
        [MODE_PAGE_FLEXIBLE_DISK_GEOMETRY] = (1 << TYPE_DISK),
935
        [MODE_PAGE_CACHING]                = (1 << TYPE_DISK) | (1 << TYPE_ROM),
936
        [MODE_PAGE_R_W_ERROR]              = (1 << TYPE_DISK) | (1 << TYPE_ROM),
937
        [MODE_PAGE_AUDIO_CTL]              = (1 << TYPE_ROM),
938
        [MODE_PAGE_CAPABILITIES]           = (1 << TYPE_ROM),
939
    };
940

    
941
    BlockDriverState *bdrv = s->qdev.conf.bs;
942
    int cylinders, heads, secs;
943
    uint8_t *p = *p_outbuf;
944

    
945
    if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
946
        return -1;
947
    }
948

    
949
    p[0] = page;
950

    
951
    /*
952
     * If Changeable Values are requested, a mask denoting those mode parameters
953
     * that are changeable shall be returned. As we currently don't support
954
     * parameter changes via MODE_SELECT all bits are returned set to zero.
955
     * The buffer was already menset to zero by the caller of this function.
956
     */
957
    switch (page) {
958
    case MODE_PAGE_HD_GEOMETRY:
959
        p[1] = 0x16;
960
        if (page_control == 1) { /* Changeable Values */
961
            break;
962
        }
963
        /* if a geometry hint is available, use it */
964
        bdrv_guess_geometry(bdrv, &cylinders, &heads, &secs);
965
        p[2] = (cylinders >> 16) & 0xff;
966
        p[3] = (cylinders >> 8) & 0xff;
967
        p[4] = cylinders & 0xff;
968
        p[5] = heads & 0xff;
969
        /* Write precomp start cylinder, disabled */
970
        p[6] = (cylinders >> 16) & 0xff;
971
        p[7] = (cylinders >> 8) & 0xff;
972
        p[8] = cylinders & 0xff;
973
        /* Reduced current start cylinder, disabled */
974
        p[9] = (cylinders >> 16) & 0xff;
975
        p[10] = (cylinders >> 8) & 0xff;
976
        p[11] = cylinders & 0xff;
977
        /* Device step rate [ns], 200ns */
978
        p[12] = 0;
979
        p[13] = 200;
980
        /* Landing zone cylinder */
981
        p[14] = 0xff;
982
        p[15] =  0xff;
983
        p[16] = 0xff;
984
        /* Medium rotation rate [rpm], 5400 rpm */
985
        p[20] = (5400 >> 8) & 0xff;
986
        p[21] = 5400 & 0xff;
987
        break;
988

    
989
    case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
990
        p[1] = 0x1e;
991
        if (page_control == 1) { /* Changeable Values */
992
            break;
993
        }
994
        /* Transfer rate [kbit/s], 5Mbit/s */
995
        p[2] = 5000 >> 8;
996
        p[3] = 5000 & 0xff;
997
        /* if a geometry hint is available, use it */
998
        bdrv_guess_geometry(bdrv, &cylinders, &heads, &secs);
999
        p[4] = heads & 0xff;
1000
        p[5] = secs & 0xff;
1001
        p[6] = s->qdev.blocksize >> 8;
1002
        p[8] = (cylinders >> 8) & 0xff;
1003
        p[9] = cylinders & 0xff;
1004
        /* Write precomp start cylinder, disabled */
1005
        p[10] = (cylinders >> 8) & 0xff;
1006
        p[11] = cylinders & 0xff;
1007
        /* Reduced current start cylinder, disabled */
1008
        p[12] = (cylinders >> 8) & 0xff;
1009
        p[13] = cylinders & 0xff;
1010
        /* Device step rate [100us], 100us */
1011
        p[14] = 0;
1012
        p[15] = 1;
1013
        /* Device step pulse width [us], 1us */
1014
        p[16] = 1;
1015
        /* Device head settle delay [100us], 100us */
1016
        p[17] = 0;
1017
        p[18] = 1;
1018
        /* Motor on delay [0.1s], 0.1s */
1019
        p[19] = 1;
1020
        /* Motor off delay [0.1s], 0.1s */
1021
        p[20] = 1;
1022
        /* Medium rotation rate [rpm], 5400 rpm */
1023
        p[28] = (5400 >> 8) & 0xff;
1024
        p[29] = 5400 & 0xff;
1025
        break;
1026

    
1027
    case MODE_PAGE_CACHING:
1028
        p[0] = 8;
1029
        p[1] = 0x12;
1030
        if (page_control == 1) { /* Changeable Values */
1031
            break;
1032
        }
1033
        if (bdrv_enable_write_cache(s->qdev.conf.bs)) {
1034
            p[2] = 4; /* WCE */
1035
        }
1036
        break;
1037

    
1038
    case MODE_PAGE_R_W_ERROR:
1039
        p[1] = 10;
1040
        p[2] = 0x80; /* Automatic Write Reallocation Enabled */
1041
        if (s->qdev.type == TYPE_ROM) {
1042
            p[3] = 0x20; /* Read Retry Count */
1043
        }
1044
        break;
1045

    
1046
    case MODE_PAGE_AUDIO_CTL:
1047
        p[1] = 14;
1048
        break;
1049

    
1050
    case MODE_PAGE_CAPABILITIES:
1051
        p[1] = 0x14;
1052
        if (page_control == 1) { /* Changeable Values */
1053
            break;
1054
        }
1055

    
1056
        p[2] = 0x3b; /* CD-R & CD-RW read */
1057
        p[3] = 0; /* Writing not supported */
1058
        p[4] = 0x7f; /* Audio, composite, digital out,
1059
                        mode 2 form 1&2, multi session */
1060
        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
1061
                        RW corrected, C2 errors, ISRC,
1062
                        UPC, Bar code */
1063
        p[6] = 0x2d | (s->tray_locked ? 2 : 0);
1064
        /* Locking supported, jumper present, eject, tray */
1065
        p[7] = 0; /* no volume & mute control, no
1066
                     changer */
1067
        p[8] = (50 * 176) >> 8; /* 50x read speed */
1068
        p[9] = (50 * 176) & 0xff;
1069
        p[10] = 2 >> 8; /* Two volume levels */
1070
        p[11] = 2 & 0xff;
1071
        p[12] = 2048 >> 8; /* 2M buffer */
1072
        p[13] = 2048 & 0xff;
1073
        p[14] = (16 * 176) >> 8; /* 16x read speed current */
1074
        p[15] = (16 * 176) & 0xff;
1075
        p[18] = (16 * 176) >> 8; /* 16x write speed */
1076
        p[19] = (16 * 176) & 0xff;
1077
        p[20] = (16 * 176) >> 8; /* 16x write speed current */
1078
        p[21] = (16 * 176) & 0xff;
1079
        break;
1080

    
1081
    default:
1082
        return -1;
1083
    }
1084

    
1085
    *p_outbuf += p[1] + 2;
1086
    return p[1] + 2;
1087
}
1088

    
1089
static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
1090
{
1091
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1092
    uint64_t nb_sectors;
1093
    bool dbd;
1094
    int page, buflen, ret, page_control;
1095
    uint8_t *p;
1096
    uint8_t dev_specific_param;
1097

    
1098
    dbd = (r->req.cmd.buf[1] & 0x8) != 0;
1099
    page = r->req.cmd.buf[2] & 0x3f;
1100
    page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
1101
    DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
1102
        (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
1103
    memset(outbuf, 0, r->req.cmd.xfer);
1104
    p = outbuf;
1105

    
1106
    if (s->qdev.type == TYPE_DISK) {
1107
        dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0;
1108
        if (bdrv_is_read_only(s->qdev.conf.bs)) {
1109
            dev_specific_param |= 0x80; /* Readonly.  */
1110
        }
1111
    } else {
1112
        /* MMC prescribes that CD/DVD drives have no block descriptors,
1113
         * and defines no device-specific parameter.  */
1114
        dev_specific_param = 0x00;
1115
        dbd = true;
1116
    }
1117

    
1118
    if (r->req.cmd.buf[0] == MODE_SENSE) {
1119
        p[1] = 0; /* Default media type.  */
1120
        p[2] = dev_specific_param;
1121
        p[3] = 0; /* Block descriptor length.  */
1122
        p += 4;
1123
    } else { /* MODE_SENSE_10 */
1124
        p[2] = 0; /* Default media type.  */
1125
        p[3] = dev_specific_param;
1126
        p[6] = p[7] = 0; /* Block descriptor length.  */
1127
        p += 8;
1128
    }
1129

    
1130
    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1131
    if (!dbd && nb_sectors) {
1132
        if (r->req.cmd.buf[0] == MODE_SENSE) {
1133
            outbuf[3] = 8; /* Block descriptor length  */
1134
        } else { /* MODE_SENSE_10 */
1135
            outbuf[7] = 8; /* Block descriptor length  */
1136
        }
1137
        nb_sectors /= (s->qdev.blocksize / 512);
1138
        if (nb_sectors > 0xffffff) {
1139
            nb_sectors = 0;
1140
        }
1141
        p[0] = 0; /* media density code */
1142
        p[1] = (nb_sectors >> 16) & 0xff;
1143
        p[2] = (nb_sectors >> 8) & 0xff;
1144
        p[3] = nb_sectors & 0xff;
1145
        p[4] = 0; /* reserved */
1146
        p[5] = 0; /* bytes 5-7 are the sector size in bytes */
1147
        p[6] = s->qdev.blocksize >> 8;
1148
        p[7] = 0;
1149
        p += 8;
1150
    }
1151

    
1152
    if (page_control == 3) {
1153
        /* Saved Values */
1154
        scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
1155
        return -1;
1156
    }
1157

    
1158
    if (page == 0x3f) {
1159
        for (page = 0; page <= 0x3e; page++) {
1160
            mode_sense_page(s, page, &p, page_control);
1161
        }
1162
    } else {
1163
        ret = mode_sense_page(s, page, &p, page_control);
1164
        if (ret == -1) {
1165
            return -1;
1166
        }
1167
    }
1168

    
1169
    buflen = p - outbuf;
1170
    /*
1171
     * The mode data length field specifies the length in bytes of the
1172
     * following data that is available to be transferred. The mode data
1173
     * length does not include itself.
1174
     */
1175
    if (r->req.cmd.buf[0] == MODE_SENSE) {
1176
        outbuf[0] = buflen - 1;
1177
    } else { /* MODE_SENSE_10 */
1178
        outbuf[0] = ((buflen - 2) >> 8) & 0xff;
1179
        outbuf[1] = (buflen - 2) & 0xff;
1180
    }
1181
    return buflen;
1182
}
1183

    
1184
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
1185
{
1186
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1187
    int start_track, format, msf, toclen;
1188
    uint64_t nb_sectors;
1189

    
1190
    msf = req->cmd.buf[1] & 2;
1191
    format = req->cmd.buf[2] & 0xf;
1192
    start_track = req->cmd.buf[6];
1193
    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1194
    DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
1195
    nb_sectors /= s->qdev.blocksize / 512;
1196
    switch (format) {
1197
    case 0:
1198
        toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
1199
        break;
1200
    case 1:
1201
        /* multi session : only a single session defined */
1202
        toclen = 12;
1203
        memset(outbuf, 0, 12);
1204
        outbuf[1] = 0x0a;
1205
        outbuf[2] = 0x01;
1206
        outbuf[3] = 0x01;
1207
        break;
1208
    case 2:
1209
        toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
1210
        break;
1211
    default:
1212
        return -1;
1213
    }
1214
    return toclen;
1215
}
1216

    
1217
static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
1218
{
1219
    SCSIRequest *req = &r->req;
1220
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1221
    bool start = req->cmd.buf[4] & 1;
1222
    bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
1223

    
1224
    if (s->qdev.type == TYPE_ROM && loej) {
1225
        if (!start && !s->tray_open && s->tray_locked) {
1226
            scsi_check_condition(r,
1227
                                 bdrv_is_inserted(s->qdev.conf.bs)
1228
                                 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
1229
                                 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
1230
            return -1;
1231
        }
1232

    
1233
        if (s->tray_open != !start) {
1234
            bdrv_eject(s->qdev.conf.bs, !start);
1235
            s->tray_open = !start;
1236
        }
1237
    }
1238
    return 0;
1239
}
1240

    
1241
static int scsi_disk_emulate_command(SCSIDiskReq *r)
1242
{
1243
    SCSIRequest *req = &r->req;
1244
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1245
    uint64_t nb_sectors;
1246
    uint8_t *outbuf;
1247
    int buflen = 0;
1248

    
1249
    if (!r->iov.iov_base) {
1250
        /*
1251
         * FIXME: we shouldn't return anything bigger than 4k, but the code
1252
         * requires the buffer to be as big as req->cmd.xfer in several
1253
         * places.  So, do not allow CDBs with a very large ALLOCATION
1254
         * LENGTH.  The real fix would be to modify scsi_read_data and
1255
         * dma_buf_read, so that they return data beyond the buflen
1256
         * as all zeros.
1257
         */
1258
        if (req->cmd.xfer > 65536) {
1259
            goto illegal_request;
1260
        }
1261
        r->buflen = MAX(4096, req->cmd.xfer);
1262
        r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
1263
    }
1264

    
1265
    outbuf = r->iov.iov_base;
1266
    switch (req->cmd.buf[0]) {
1267
    case TEST_UNIT_READY:
1268
        assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));
1269
        break;
1270
    case INQUIRY:
1271
        buflen = scsi_disk_emulate_inquiry(req, outbuf);
1272
        if (buflen < 0) {
1273
            goto illegal_request;
1274
        }
1275
        break;
1276
    case MODE_SENSE:
1277
    case MODE_SENSE_10:
1278
        buflen = scsi_disk_emulate_mode_sense(r, outbuf);
1279
        if (buflen < 0) {
1280
            goto illegal_request;
1281
        }
1282
        break;
1283
    case READ_TOC:
1284
        buflen = scsi_disk_emulate_read_toc(req, outbuf);
1285
        if (buflen < 0) {
1286
            goto illegal_request;
1287
        }
1288
        break;
1289
    case RESERVE:
1290
        if (req->cmd.buf[1] & 1) {
1291
            goto illegal_request;
1292
        }
1293
        break;
1294
    case RESERVE_10:
1295
        if (req->cmd.buf[1] & 3) {
1296
            goto illegal_request;
1297
        }
1298
        break;
1299
    case RELEASE:
1300
        if (req->cmd.buf[1] & 1) {
1301
            goto illegal_request;
1302
        }
1303
        break;
1304
    case RELEASE_10:
1305
        if (req->cmd.buf[1] & 3) {
1306
            goto illegal_request;
1307
        }
1308
        break;
1309
    case START_STOP:
1310
        if (scsi_disk_emulate_start_stop(r) < 0) {
1311
            return -1;
1312
        }
1313
        break;
1314
    case ALLOW_MEDIUM_REMOVAL:
1315
        s->tray_locked = req->cmd.buf[4] & 1;
1316
        bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);
1317
        break;
1318
    case READ_CAPACITY_10:
1319
        /* The normal LEN field for this command is zero.  */
1320
        memset(outbuf, 0, 8);
1321
        bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1322
        if (!nb_sectors) {
1323
            scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1324
            return -1;
1325
        }
1326
        if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {
1327
            goto illegal_request;
1328
        }
1329
        nb_sectors /= s->qdev.blocksize / 512;
1330
        /* Returned value is the address of the last sector.  */
1331
        nb_sectors--;
1332
        /* Remember the new size for read/write sanity checking. */
1333
        s->qdev.max_lba = nb_sectors;
1334
        /* Clip to 2TB, instead of returning capacity modulo 2TB. */
1335
        if (nb_sectors > UINT32_MAX) {
1336
            nb_sectors = UINT32_MAX;
1337
        }
1338
        outbuf[0] = (nb_sectors >> 24) & 0xff;
1339
        outbuf[1] = (nb_sectors >> 16) & 0xff;
1340
        outbuf[2] = (nb_sectors >> 8) & 0xff;
1341
        outbuf[3] = nb_sectors & 0xff;
1342
        outbuf[4] = 0;
1343
        outbuf[5] = 0;
1344
        outbuf[6] = s->qdev.blocksize >> 8;
1345
        outbuf[7] = 0;
1346
        buflen = 8;
1347
        break;
1348
    case REQUEST_SENSE:
1349
        /* Just return "NO SENSE".  */
1350
        buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,
1351
                                  (req->cmd.buf[1] & 1) == 0);
1352
        break;
1353
    case MECHANISM_STATUS:
1354
        buflen = scsi_emulate_mechanism_status(s, outbuf);
1355
        if (buflen < 0) {
1356
            goto illegal_request;
1357
        }
1358
        break;
1359
    case GET_CONFIGURATION:
1360
        buflen = scsi_get_configuration(s, outbuf);
1361
        if (buflen < 0) {
1362
            goto illegal_request;
1363
        }
1364
        break;
1365
    case GET_EVENT_STATUS_NOTIFICATION:
1366
        buflen = scsi_get_event_status_notification(s, r, outbuf);
1367
        if (buflen < 0) {
1368
            goto illegal_request;
1369
        }
1370
        break;
1371
    case READ_DVD_STRUCTURE:
1372
        buflen = scsi_read_dvd_structure(s, r, outbuf);
1373
        if (buflen < 0) {
1374
            goto illegal_request;
1375
        }
1376
        break;
1377
    case SERVICE_ACTION_IN_16:
1378
        /* Service Action In subcommands. */
1379
        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
1380
            DPRINTF("SAI READ CAPACITY(16)\n");
1381
            memset(outbuf, 0, req->cmd.xfer);
1382
            bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1383
            if (!nb_sectors) {
1384
                scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1385
                return -1;
1386
            }
1387
            if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {
1388
                goto illegal_request;
1389
            }
1390
            nb_sectors /= s->qdev.blocksize / 512;
1391
            /* Returned value is the address of the last sector.  */
1392
            nb_sectors--;
1393
            /* Remember the new size for read/write sanity checking. */
1394
            s->qdev.max_lba = nb_sectors;
1395
            outbuf[0] = (nb_sectors >> 56) & 0xff;
1396
            outbuf[1] = (nb_sectors >> 48) & 0xff;
1397
            outbuf[2] = (nb_sectors >> 40) & 0xff;
1398
            outbuf[3] = (nb_sectors >> 32) & 0xff;
1399
            outbuf[4] = (nb_sectors >> 24) & 0xff;
1400
            outbuf[5] = (nb_sectors >> 16) & 0xff;
1401
            outbuf[6] = (nb_sectors >> 8) & 0xff;
1402
            outbuf[7] = nb_sectors & 0xff;
1403
            outbuf[8] = 0;
1404
            outbuf[9] = 0;
1405
            outbuf[10] = s->qdev.blocksize >> 8;
1406
            outbuf[11] = 0;
1407
            outbuf[12] = 0;
1408
            outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1409

    
1410
            /* set TPE bit if the format supports discard */
1411
            if (s->qdev.conf.discard_granularity) {
1412
                outbuf[14] = 0x80;
1413
            }
1414

    
1415
            /* Protection, exponent and lowest lba field left blank. */
1416
            buflen = req->cmd.xfer;
1417
            break;
1418
        }
1419
        DPRINTF("Unsupported Service Action In\n");
1420
        goto illegal_request;
1421
    default:
1422
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1423
        return -1;
1424
    }
1425
    buflen = MIN(buflen, req->cmd.xfer);
1426
    return buflen;
1427

    
1428
illegal_request:
1429
    if (r->req.status == -1) {
1430
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1431
    }
1432
    return -1;
1433
}
1434

    
1435
/* Execute a scsi command.  Returns the length of the data expected by the
1436
   command.  This will be Positive for data transfers from the device
1437
   (eg. disk reads), negative for transfers to the device (eg. disk writes),
1438
   and zero if the command does not transfer any data.  */
1439

    
1440
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
1441
{
1442
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1443
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1444
    int32_t len;
1445
    uint8_t command;
1446
    int rc;
1447

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

    
1451
#ifdef DEBUG_SCSI
1452
    {
1453
        int i;
1454
        for (i = 1; i < r->req.cmd.len; i++) {
1455
            printf(" 0x%02x", buf[i]);
1456
        }
1457
        printf("\n");
1458
    }
1459
#endif
1460

    
1461
    switch (command) {
1462
    case INQUIRY:
1463
    case MODE_SENSE:
1464
    case MODE_SENSE_10:
1465
    case RESERVE:
1466
    case RESERVE_10:
1467
    case RELEASE:
1468
    case RELEASE_10:
1469
    case START_STOP:
1470
    case ALLOW_MEDIUM_REMOVAL:
1471
    case GET_CONFIGURATION:
1472
    case GET_EVENT_STATUS_NOTIFICATION:
1473
    case MECHANISM_STATUS:
1474
    case REQUEST_SENSE:
1475
        break;
1476

    
1477
    default:
1478
        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1479
            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1480
            return 0;
1481
        }
1482
        break;
1483
    }
1484

    
1485
    switch (command) {
1486
    case TEST_UNIT_READY:
1487
    case INQUIRY:
1488
    case MODE_SENSE:
1489
    case MODE_SENSE_10:
1490
    case RESERVE:
1491
    case RESERVE_10:
1492
    case RELEASE:
1493
    case RELEASE_10:
1494
    case START_STOP:
1495
    case ALLOW_MEDIUM_REMOVAL:
1496
    case READ_CAPACITY_10:
1497
    case READ_TOC:
1498
    case READ_DVD_STRUCTURE:
1499
    case GET_CONFIGURATION:
1500
    case GET_EVENT_STATUS_NOTIFICATION:
1501
    case MECHANISM_STATUS:
1502
    case SERVICE_ACTION_IN_16:
1503
    case REQUEST_SENSE:
1504
        rc = scsi_disk_emulate_command(r);
1505
        if (rc < 0) {
1506
            return 0;
1507
        }
1508

    
1509
        r->iov.iov_len = rc;
1510
        break;
1511
    case SYNCHRONIZE_CACHE:
1512
        /* The request is used as the AIO opaque value, so add a ref.  */
1513
        scsi_req_ref(&r->req);
1514
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1515
        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_flush_complete, r);
1516
        return 0;
1517
    case READ_6:
1518
    case READ_10:
1519
    case READ_12:
1520
    case READ_16:
1521
        len = r->req.cmd.xfer / s->qdev.blocksize;
1522
        DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
1523
        if (r->req.cmd.lba > s->qdev.max_lba) {
1524
            goto illegal_lba;
1525
        }
1526
        r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1527
        r->sector_count = len * (s->qdev.blocksize / 512);
1528
        break;
1529
    case VERIFY_10:
1530
    case VERIFY_12:
1531
    case VERIFY_16:
1532
    case WRITE_6:
1533
    case WRITE_10:
1534
    case WRITE_12:
1535
    case WRITE_16:
1536
    case WRITE_VERIFY_10:
1537
    case WRITE_VERIFY_12:
1538
    case WRITE_VERIFY_16:
1539
        len = r->req.cmd.xfer / s->qdev.blocksize;
1540
        DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
1541
                (command & 0xe) == 0xe ? "And Verify " : "",
1542
                r->req.cmd.lba, len);
1543
        if (r->req.cmd.lba > s->qdev.max_lba) {
1544
            goto illegal_lba;
1545
        }
1546
        r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1547
        r->sector_count = len * (s->qdev.blocksize / 512);
1548
        break;
1549
    case MODE_SELECT:
1550
        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1551
        /* We don't support mode parameter changes.
1552
           Allow the mode parameter header + block descriptors only. */
1553
        if (r->req.cmd.xfer > 12) {
1554
            goto fail;
1555
        }
1556
        break;
1557
    case MODE_SELECT_10:
1558
        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1559
        /* We don't support mode parameter changes.
1560
           Allow the mode parameter header + block descriptors only. */
1561
        if (r->req.cmd.xfer > 16) {
1562
            goto fail;
1563
        }
1564
        break;
1565
    case SEEK_10:
1566
        DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
1567
        if (r->req.cmd.lba > s->qdev.max_lba) {
1568
            goto illegal_lba;
1569
        }
1570
        break;
1571
    case WRITE_SAME_10:
1572
        len = lduw_be_p(&buf[7]);
1573
        goto write_same;
1574
    case WRITE_SAME_16:
1575
        len = ldl_be_p(&buf[10]) & 0xffffffffULL;
1576
    write_same:
1577

    
1578
        DPRINTF("WRITE SAME() (sector %" PRId64 ", count %d)\n",
1579
                r->req.cmd.lba, len);
1580

    
1581
        if (r->req.cmd.lba > s->qdev.max_lba) {
1582
            goto illegal_lba;
1583
        }
1584

    
1585
        /*
1586
         * We only support WRITE SAME with the unmap bit set for now.
1587
         */
1588
        if (!(buf[1] & 0x8)) {
1589
            goto fail;
1590
        }
1591

    
1592
        rc = bdrv_discard(s->qdev.conf.bs,
1593
                          r->req.cmd.lba * (s->qdev.blocksize / 512),
1594
                          len * (s->qdev.blocksize / 512));
1595
        if (rc < 0) {
1596
            /* XXX: better error code ?*/
1597
            goto fail;
1598
        }
1599

    
1600
        break;
1601
    default:
1602
        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1603
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1604
        return 0;
1605
    fail:
1606
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1607
        return 0;
1608
    illegal_lba:
1609
        scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1610
        return 0;
1611
    }
1612
    if (r->sector_count == 0 && r->iov.iov_len == 0) {
1613
        scsi_req_complete(&r->req, GOOD);
1614
    }
1615
    len = r->sector_count * 512 + r->iov.iov_len;
1616
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1617
        return -len;
1618
    } else {
1619
        if (!r->sector_count) {
1620
            r->sector_count = -1;
1621
        }
1622
        return len;
1623
    }
1624
}
1625

    
1626
static void scsi_disk_reset(DeviceState *dev)
1627
{
1628
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1629
    uint64_t nb_sectors;
1630

    
1631
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1632

    
1633
    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1634
    nb_sectors /= s->qdev.blocksize / 512;
1635
    if (nb_sectors) {
1636
        nb_sectors--;
1637
    }
1638
    s->qdev.max_lba = nb_sectors;
1639
}
1640

    
1641
static void scsi_destroy(SCSIDevice *dev)
1642
{
1643
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1644

    
1645
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1646
    blockdev_mark_auto_del(s->qdev.conf.bs);
1647
}
1648

    
1649
static void scsi_cd_change_media_cb(void *opaque, bool load)
1650
{
1651
    SCSIDiskState *s = opaque;
1652

    
1653
    /*
1654
     * When a CD gets changed, we have to report an ejected state and
1655
     * then a loaded state to guests so that they detect tray
1656
     * open/close and media change events.  Guests that do not use
1657
     * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1658
     * states rely on this behavior.
1659
     *
1660
     * media_changed governs the state machine used for unit attention
1661
     * report.  media_event is used by GET EVENT STATUS NOTIFICATION.
1662
     */
1663
    s->media_changed = load;
1664
    s->tray_open = !load;
1665
    s->qdev.unit_attention = SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM);
1666
    s->media_event = true;
1667
    s->eject_request = false;
1668
}
1669

    
1670
static void scsi_cd_eject_request_cb(void *opaque, bool force)
1671
{
1672
    SCSIDiskState *s = opaque;
1673

    
1674
    s->eject_request = true;
1675
    if (force) {
1676
        s->tray_locked = false;
1677
    }
1678
}
1679

    
1680
static bool scsi_cd_is_tray_open(void *opaque)
1681
{
1682
    return ((SCSIDiskState *)opaque)->tray_open;
1683
}
1684

    
1685
static bool scsi_cd_is_medium_locked(void *opaque)
1686
{
1687
    return ((SCSIDiskState *)opaque)->tray_locked;
1688
}
1689

    
1690
static const BlockDevOps scsi_cd_block_ops = {
1691
    .change_media_cb = scsi_cd_change_media_cb,
1692
    .eject_request_cb = scsi_cd_eject_request_cb,
1693
    .is_tray_open = scsi_cd_is_tray_open,
1694
    .is_medium_locked = scsi_cd_is_medium_locked,
1695
};
1696

    
1697
static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
1698
{
1699
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1700
    if (s->media_changed) {
1701
        s->media_changed = false;
1702
        s->qdev.unit_attention = SENSE_CODE(MEDIUM_CHANGED);
1703
    }
1704
}
1705

    
1706
static int scsi_initfn(SCSIDevice *dev)
1707
{
1708
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1709
    DriveInfo *dinfo;
1710

    
1711
    if (!s->qdev.conf.bs) {
1712
        error_report("drive property not set");
1713
        return -1;
1714
    }
1715

    
1716
    if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&
1717
        !bdrv_is_inserted(s->qdev.conf.bs)) {
1718
        error_report("Device needs media, but drive is empty");
1719
        return -1;
1720
    }
1721

    
1722
    if (!s->serial) {
1723
        /* try to fall back to value set with legacy -drive serial=... */
1724
        dinfo = drive_get_by_blockdev(s->qdev.conf.bs);
1725
        if (*dinfo->serial) {
1726
            s->serial = g_strdup(dinfo->serial);
1727
        }
1728
    }
1729

    
1730
    if (!s->version) {
1731
        s->version = g_strdup(QEMU_VERSION);
1732
    }
1733

    
1734
    if (bdrv_is_sg(s->qdev.conf.bs)) {
1735
        error_report("unwanted /dev/sg*");
1736
        return -1;
1737
    }
1738

    
1739
    if (s->features & (1 << SCSI_DISK_F_REMOVABLE)) {
1740
        bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_cd_block_ops, s);
1741
    }
1742
    bdrv_set_buffer_alignment(s->qdev.conf.bs, s->qdev.blocksize);
1743

    
1744
    bdrv_iostatus_enable(s->qdev.conf.bs);
1745
    add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL);
1746
    return 0;
1747
}
1748

    
1749
static int scsi_hd_initfn(SCSIDevice *dev)
1750
{
1751
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1752
    s->qdev.blocksize = s->qdev.conf.logical_block_size;
1753
    s->qdev.type = TYPE_DISK;
1754
    return scsi_initfn(&s->qdev);
1755
}
1756

    
1757
static int scsi_cd_initfn(SCSIDevice *dev)
1758
{
1759
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1760
    s->qdev.blocksize = 2048;
1761
    s->qdev.type = TYPE_ROM;
1762
    s->features |= 1 << SCSI_DISK_F_REMOVABLE;
1763
    return scsi_initfn(&s->qdev);
1764
}
1765

    
1766
static int scsi_disk_initfn(SCSIDevice *dev)
1767
{
1768
    DriveInfo *dinfo;
1769

    
1770
    if (!dev->conf.bs) {
1771
        return scsi_initfn(dev);  /* ... and die there */
1772
    }
1773

    
1774
    dinfo = drive_get_by_blockdev(dev->conf.bs);
1775
    if (dinfo->media_cd) {
1776
        return scsi_cd_initfn(dev);
1777
    } else {
1778
        return scsi_hd_initfn(dev);
1779
    }
1780
}
1781

    
1782
static const SCSIReqOps scsi_disk_reqops = {
1783
    .size         = sizeof(SCSIDiskReq),
1784
    .free_req     = scsi_free_request,
1785
    .send_command = scsi_send_command,
1786
    .read_data    = scsi_read_data,
1787
    .write_data   = scsi_write_data,
1788
    .cancel_io    = scsi_cancel_io,
1789
    .get_buf      = scsi_get_buf,
1790
    .load_request = scsi_disk_load_request,
1791
    .save_request = scsi_disk_save_request,
1792
};
1793

    
1794
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
1795
                                     uint8_t *buf, void *hba_private)
1796
{
1797
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
1798
    SCSIRequest *req;
1799

    
1800
    req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
1801
    return req;
1802
}
1803

    
1804
#ifdef __linux__
1805
static int get_device_type(SCSIDiskState *s)
1806
{
1807
    BlockDriverState *bdrv = s->qdev.conf.bs;
1808
    uint8_t cmd[16];
1809
    uint8_t buf[36];
1810
    uint8_t sensebuf[8];
1811
    sg_io_hdr_t io_header;
1812
    int ret;
1813

    
1814
    memset(cmd, 0, sizeof(cmd));
1815
    memset(buf, 0, sizeof(buf));
1816
    cmd[0] = INQUIRY;
1817
    cmd[4] = sizeof(buf);
1818

    
1819
    memset(&io_header, 0, sizeof(io_header));
1820
    io_header.interface_id = 'S';
1821
    io_header.dxfer_direction = SG_DXFER_FROM_DEV;
1822
    io_header.dxfer_len = sizeof(buf);
1823
    io_header.dxferp = buf;
1824
    io_header.cmdp = cmd;
1825
    io_header.cmd_len = sizeof(cmd);
1826
    io_header.mx_sb_len = sizeof(sensebuf);
1827
    io_header.sbp = sensebuf;
1828
    io_header.timeout = 6000; /* XXX */
1829

    
1830
    ret = bdrv_ioctl(bdrv, SG_IO, &io_header);
1831
    if (ret < 0 || io_header.driver_status || io_header.host_status) {
1832
        return -1;
1833
    }
1834
    s->qdev.type = buf[0];
1835
    if (buf[1] & 0x80) {
1836
        s->features |= 1 << SCSI_DISK_F_REMOVABLE;
1837
    }
1838
    return 0;
1839
}
1840

    
1841
static int scsi_block_initfn(SCSIDevice *dev)
1842
{
1843
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1844
    int sg_version;
1845
    int rc;
1846

    
1847
    if (!s->qdev.conf.bs) {
1848
        error_report("scsi-block: drive property not set");
1849
        return -1;
1850
    }
1851

    
1852
    /* check we are using a driver managing SG_IO (version 3 and after) */
1853
    if (bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 ||
1854
        sg_version < 30000) {
1855
        error_report("scsi-block: scsi generic interface too old");
1856
        return -1;
1857
    }
1858

    
1859
    /* get device type from INQUIRY data */
1860
    rc = get_device_type(s);
1861
    if (rc < 0) {
1862
        error_report("scsi-block: INQUIRY failed");
1863
        return -1;
1864
    }
1865

    
1866
    /* Make a guess for the block size, we'll fix it when the guest sends.
1867
     * READ CAPACITY.  If they don't, they likely would assume these sizes
1868
     * anyway. (TODO: check in /sys).
1869
     */
1870
    if (s->qdev.type == TYPE_ROM || s->qdev.type == TYPE_WORM) {
1871
        s->qdev.blocksize = 2048;
1872
    } else {
1873
        s->qdev.blocksize = 512;
1874
    }
1875
    return scsi_initfn(&s->qdev);
1876
}
1877

    
1878
static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
1879
                                           uint32_t lun, uint8_t *buf,
1880
                                           void *hba_private)
1881
{
1882
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
1883

    
1884
    switch (buf[0]) {
1885
    case READ_6:
1886
    case READ_10:
1887
    case READ_12:
1888
    case READ_16:
1889
    case VERIFY_10:
1890
    case VERIFY_12:
1891
    case VERIFY_16:
1892
    case WRITE_6:
1893
    case WRITE_10:
1894
    case WRITE_12:
1895
    case WRITE_16:
1896
    case WRITE_VERIFY_10:
1897
    case WRITE_VERIFY_12:
1898
    case WRITE_VERIFY_16:
1899
        /* If we are not using O_DIRECT, we might read stale data from the
1900
         * host cache if writes were made using other commands than these
1901
         * ones (such as WRITE SAME or EXTENDED COPY, etc.).  So, without
1902
         * O_DIRECT everything must go through SG_IO.
1903
         */
1904
        if (!(s->qdev.conf.bs->open_flags & BDRV_O_NOCACHE)) {
1905
            break;
1906
        }
1907

    
1908
        /* MMC writing cannot be done via pread/pwrite, because it sometimes
1909
         * involves writing beyond the maximum LBA or to negative LBA (lead-in).
1910
         * And once you do these writes, reading from the block device is
1911
         * unreliable, too.  It is even possible that reads deliver random data
1912
         * from the host page cache (this is probably a Linux bug).
1913
         *
1914
         * We might use scsi_disk_reqops as long as no writing commands are
1915
         * seen, but performance usually isn't paramount on optical media.  So,
1916
         * just make scsi-block operate the same as scsi-generic for them.
1917
         */
1918
        if (s->qdev.type == TYPE_ROM) {
1919
            break;
1920
        }
1921
        return scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun,
1922
                              hba_private);
1923
    }
1924

    
1925
    return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun,
1926
                          hba_private);
1927
}
1928
#endif
1929

    
1930
#define DEFINE_SCSI_DISK_PROPERTIES()                           \
1931
    DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),          \
1932
    DEFINE_PROP_STRING("ver",  SCSIDiskState, version),         \
1933
    DEFINE_PROP_STRING("serial",  SCSIDiskState, serial)
1934

    
1935
static Property scsi_hd_properties[] = {
1936
    DEFINE_SCSI_DISK_PROPERTIES(),
1937
    DEFINE_PROP_BIT("removable", SCSIDiskState, features,
1938
                    SCSI_DISK_F_REMOVABLE, false),
1939
    DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
1940
                    SCSI_DISK_F_DPOFUA, false),
1941
    DEFINE_PROP_END_OF_LIST(),
1942
};
1943

    
1944
static const VMStateDescription vmstate_scsi_disk_state = {
1945
    .name = "scsi-disk",
1946
    .version_id = 1,
1947
    .minimum_version_id = 1,
1948
    .minimum_version_id_old = 1,
1949
    .fields = (VMStateField[]) {
1950
        VMSTATE_SCSI_DEVICE(qdev, SCSIDiskState),
1951
        VMSTATE_BOOL(media_changed, SCSIDiskState),
1952
        VMSTATE_BOOL(media_event, SCSIDiskState),
1953
        VMSTATE_BOOL(eject_request, SCSIDiskState),
1954
        VMSTATE_BOOL(tray_open, SCSIDiskState),
1955
        VMSTATE_BOOL(tray_locked, SCSIDiskState),
1956
        VMSTATE_END_OF_LIST()
1957
    }
1958
};
1959

    
1960
static void scsi_hd_class_initfn(ObjectClass *klass, void *data)
1961
{
1962
    DeviceClass *dc = DEVICE_CLASS(klass);
1963
    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
1964

    
1965
    sc->init         = scsi_hd_initfn;
1966
    sc->destroy      = scsi_destroy;
1967
    sc->alloc_req    = scsi_new_request;
1968
    sc->unit_attention_reported = scsi_disk_unit_attention_reported;
1969
    dc->fw_name = "disk";
1970
    dc->desc = "virtual SCSI disk";
1971
    dc->reset = scsi_disk_reset;
1972
    dc->props = scsi_hd_properties;
1973
    dc->vmsd  = &vmstate_scsi_disk_state;
1974
}
1975

    
1976
static TypeInfo scsi_hd_info = {
1977
    .name          = "scsi-hd",
1978
    .parent        = TYPE_SCSI_DEVICE,
1979
    .instance_size = sizeof(SCSIDiskState),
1980
    .class_init    = scsi_hd_class_initfn,
1981
};
1982

    
1983
static Property scsi_cd_properties[] = {
1984
    DEFINE_SCSI_DISK_PROPERTIES(),
1985
    DEFINE_PROP_END_OF_LIST(),
1986
};
1987

    
1988
static void scsi_cd_class_initfn(ObjectClass *klass, void *data)
1989
{
1990
    DeviceClass *dc = DEVICE_CLASS(klass);
1991
    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
1992

    
1993
    sc->init         = scsi_cd_initfn;
1994
    sc->destroy      = scsi_destroy;
1995
    sc->alloc_req    = scsi_new_request;
1996
    sc->unit_attention_reported = scsi_disk_unit_attention_reported;
1997
    dc->fw_name = "disk";
1998
    dc->desc = "virtual SCSI CD-ROM";
1999
    dc->reset = scsi_disk_reset;
2000
    dc->props = scsi_cd_properties;
2001
    dc->vmsd  = &vmstate_scsi_disk_state;
2002
}
2003

    
2004
static TypeInfo scsi_cd_info = {
2005
    .name          = "scsi-cd",
2006
    .parent        = TYPE_SCSI_DEVICE,
2007
    .instance_size = sizeof(SCSIDiskState),
2008
    .class_init    = scsi_cd_class_initfn,
2009
};
2010

    
2011
#ifdef __linux__
2012
static Property scsi_block_properties[] = {
2013
    DEFINE_SCSI_DISK_PROPERTIES(),
2014
    DEFINE_PROP_END_OF_LIST(),
2015
};
2016

    
2017
static void scsi_block_class_initfn(ObjectClass *klass, void *data)
2018
{
2019
    DeviceClass *dc = DEVICE_CLASS(klass);
2020
    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2021

    
2022
    sc->init         = scsi_block_initfn;
2023
    sc->destroy      = scsi_destroy;
2024
    sc->alloc_req    = scsi_block_new_request;
2025
    dc->fw_name = "disk";
2026
    dc->desc = "SCSI block device passthrough";
2027
    dc->reset = scsi_disk_reset;
2028
    dc->props = scsi_block_properties;
2029
    dc->vmsd  = &vmstate_scsi_disk_state;
2030
}
2031

    
2032
static TypeInfo scsi_block_info = {
2033
    .name          = "scsi-block",
2034
    .parent        = TYPE_SCSI_DEVICE,
2035
    .instance_size = sizeof(SCSIDiskState),
2036
    .class_init    = scsi_block_class_initfn,
2037
};
2038
#endif
2039

    
2040
static Property scsi_disk_properties[] = {
2041
    DEFINE_SCSI_DISK_PROPERTIES(),
2042
    DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2043
                    SCSI_DISK_F_REMOVABLE, false),
2044
    DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2045
                    SCSI_DISK_F_DPOFUA, false),
2046
    DEFINE_PROP_END_OF_LIST(),
2047
};
2048

    
2049
static void scsi_disk_class_initfn(ObjectClass *klass, void *data)
2050
{
2051
    DeviceClass *dc = DEVICE_CLASS(klass);
2052
    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2053

    
2054
    sc->init         = scsi_disk_initfn;
2055
    sc->destroy      = scsi_destroy;
2056
    sc->alloc_req    = scsi_new_request;
2057
    sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2058
    dc->fw_name = "disk";
2059
    dc->desc = "virtual SCSI disk or CD-ROM (legacy)";
2060
    dc->reset = scsi_disk_reset;
2061
    dc->props = scsi_disk_properties;
2062
    dc->vmsd  = &vmstate_scsi_disk_state;
2063
}
2064

    
2065
static TypeInfo scsi_disk_info = {
2066
    .name          = "scsi-disk",
2067
    .parent        = TYPE_SCSI_DEVICE,
2068
    .instance_size = sizeof(SCSIDiskState),
2069
    .class_init    = scsi_disk_class_initfn,
2070
};
2071

    
2072
static void scsi_disk_register_types(void)
2073
{
2074
    type_register_static(&scsi_hd_info);
2075
    type_register_static(&scsi_cd_info);
2076
#ifdef __linux__
2077
    type_register_static(&scsi_block_info);
2078
#endif
2079
    type_register_static(&scsi_disk_info);
2080
}
2081

    
2082
type_init(scsi_disk_register_types)