Statistics
| Branch: | Revision:

root / hw / scsi-disk.c @ b6c251ab

History | View | Annotate | Download (44 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 scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
571
                                   uint8_t *outbuf)
572
{
573
    scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
574
    return -1;
575
}
576

    
577
static int scsi_get_event_status_notification(SCSIDiskState *s,
578
                                              SCSIDiskReq *r, uint8_t *outbuf)
579
{
580
    scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
581
    return -1;
582
}
583

    
584
static int scsi_get_configuration(SCSIDiskState *s, SCSIDiskReq *r,
585
                                  uint8_t *outbuf)
586
{
587
    if (s->qdev.type != TYPE_ROM) {
588
        return -1;
589
    }
590
    memset(outbuf, 0, 8);
591
    /* ??? This should probably return much more information.  For now
592
       just return the basic header indicating the CD-ROM profile.  */
593
    outbuf[7] = 8; /* CD-ROM */
594
    return 8;
595
}
596

    
597
static int scsi_emulate_mechanism_status(SCSIDiskState *s, uint8_t *outbuf)
598
{
599
    if (s->qdev.type != TYPE_ROM) {
600
        return -1;
601
    }
602
    memset(outbuf, 0, 8);
603
    outbuf[5] = 1; /* CD-ROM */
604
    return 8;
605
}
606

    
607
static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
608
                           int page_control)
609
{
610
    BlockDriverState *bdrv = s->bs;
611
    int cylinders, heads, secs;
612
    uint8_t *p = *p_outbuf;
613

    
614
    /*
615
     * If Changeable Values are requested, a mask denoting those mode parameters
616
     * that are changeable shall be returned. As we currently don't support
617
     * parameter changes via MODE_SELECT all bits are returned set to zero.
618
     * The buffer was already menset to zero by the caller of this function.
619
     */
620
    switch (page) {
621
    case MODE_PAGE_HD_GEOMETRY:
622
        if (s->qdev.type == TYPE_ROM) {
623
            return -1;
624
        }
625
        p[0] = 4;
626
        p[1] = 0x16;
627
        if (page_control == 1) { /* Changeable Values */
628
            break;
629
        }
630
        /* if a geometry hint is available, use it */
631
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
632
        p[2] = (cylinders >> 16) & 0xff;
633
        p[3] = (cylinders >> 8) & 0xff;
634
        p[4] = cylinders & 0xff;
635
        p[5] = heads & 0xff;
636
        /* Write precomp start cylinder, disabled */
637
        p[6] = (cylinders >> 16) & 0xff;
638
        p[7] = (cylinders >> 8) & 0xff;
639
        p[8] = cylinders & 0xff;
640
        /* Reduced current start cylinder, disabled */
641
        p[9] = (cylinders >> 16) & 0xff;
642
        p[10] = (cylinders >> 8) & 0xff;
643
        p[11] = cylinders & 0xff;
644
        /* Device step rate [ns], 200ns */
645
        p[12] = 0;
646
        p[13] = 200;
647
        /* Landing zone cylinder */
648
        p[14] = 0xff;
649
        p[15] =  0xff;
650
        p[16] = 0xff;
651
        /* Medium rotation rate [rpm], 5400 rpm */
652
        p[20] = (5400 >> 8) & 0xff;
653
        p[21] = 5400 & 0xff;
654
        break;
655

    
656
    case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
657
        if (s->qdev.type == TYPE_ROM) {
658
            return -1;
659
        }
660
        p[0] = 5;
661
        p[1] = 0x1e;
662
        if (page_control == 1) { /* Changeable Values */
663
            break;
664
        }
665
        /* Transfer rate [kbit/s], 5Mbit/s */
666
        p[2] = 5000 >> 8;
667
        p[3] = 5000 & 0xff;
668
        /* if a geometry hint is available, use it */
669
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
670
        p[4] = heads & 0xff;
671
        p[5] = secs & 0xff;
672
        p[6] = s->cluster_size * 2;
673
        p[8] = (cylinders >> 8) & 0xff;
674
        p[9] = cylinders & 0xff;
675
        /* Write precomp start cylinder, disabled */
676
        p[10] = (cylinders >> 8) & 0xff;
677
        p[11] = cylinders & 0xff;
678
        /* Reduced current start cylinder, disabled */
679
        p[12] = (cylinders >> 8) & 0xff;
680
        p[13] = cylinders & 0xff;
681
        /* Device step rate [100us], 100us */
682
        p[14] = 0;
683
        p[15] = 1;
684
        /* Device step pulse width [us], 1us */
685
        p[16] = 1;
686
        /* Device head settle delay [100us], 100us */
687
        p[17] = 0;
688
        p[18] = 1;
689
        /* Motor on delay [0.1s], 0.1s */
690
        p[19] = 1;
691
        /* Motor off delay [0.1s], 0.1s */
692
        p[20] = 1;
693
        /* Medium rotation rate [rpm], 5400 rpm */
694
        p[28] = (5400 >> 8) & 0xff;
695
        p[29] = 5400 & 0xff;
696
        break;
697

    
698
    case MODE_PAGE_CACHING:
699
        p[0] = 8;
700
        p[1] = 0x12;
701
        if (page_control == 1) { /* Changeable Values */
702
            break;
703
        }
704
        if (bdrv_enable_write_cache(s->bs)) {
705
            p[2] = 4; /* WCE */
706
        }
707
        break;
708

    
709
    case MODE_PAGE_CAPABILITIES:
710
        if (s->qdev.type != TYPE_ROM) {
711
            return -1;
712
        }
713
        p[0] = 0x2a;
714
        p[1] = 0x14;
715
        if (page_control == 1) { /* Changeable Values */
716
            break;
717
        }
718
        p[2] = 3; // CD-R & CD-RW read
719
        p[3] = 0; // Writing not supported
720
        p[4] = 0x7f; /* Audio, composite, digital out,
721
                        mode 2 form 1&2, multi session */
722
        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
723
                        RW corrected, C2 errors, ISRC,
724
                        UPC, Bar code */
725
        p[6] = 0x2d | (s->tray_locked ? 2 : 0);
726
        /* Locking supported, jumper present, eject, tray */
727
        p[7] = 0; /* no volume & mute control, no
728
                     changer */
729
        p[8] = (50 * 176) >> 8; // 50x read speed
730
        p[9] = (50 * 176) & 0xff;
731
        p[10] = 0 >> 8; // No volume
732
        p[11] = 0 & 0xff;
733
        p[12] = 2048 >> 8; // 2M buffer
734
        p[13] = 2048 & 0xff;
735
        p[14] = (16 * 176) >> 8; // 16x read speed current
736
        p[15] = (16 * 176) & 0xff;
737
        p[18] = (16 * 176) >> 8; // 16x write speed
738
        p[19] = (16 * 176) & 0xff;
739
        p[20] = (16 * 176) >> 8; // 16x write speed current
740
        p[21] = (16 * 176) & 0xff;
741
        break;
742

    
743
    default:
744
        return -1;
745
    }
746

    
747
    *p_outbuf += p[1] + 2;
748
    return p[1] + 2;
749
}
750

    
751
static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
752
{
753
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
754
    uint64_t nb_sectors;
755
    int page, dbd, buflen, ret, page_control;
756
    uint8_t *p;
757
    uint8_t dev_specific_param;
758

    
759
    dbd = r->req.cmd.buf[1]  & 0x8;
760
    page = r->req.cmd.buf[2] & 0x3f;
761
    page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
762
    DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
763
        (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
764
    memset(outbuf, 0, r->req.cmd.xfer);
765
    p = outbuf;
766

    
767
    if (bdrv_is_read_only(s->bs)) {
768
        dev_specific_param = 0x80; /* Readonly.  */
769
    } else {
770
        dev_specific_param = 0x00;
771
    }
772

    
773
    if (r->req.cmd.buf[0] == MODE_SENSE) {
774
        p[1] = 0; /* Default media type.  */
775
        p[2] = dev_specific_param;
776
        p[3] = 0; /* Block descriptor length.  */
777
        p += 4;
778
    } else { /* MODE_SENSE_10 */
779
        p[2] = 0; /* Default media type.  */
780
        p[3] = dev_specific_param;
781
        p[6] = p[7] = 0; /* Block descriptor length.  */
782
        p += 8;
783
    }
784

    
785
    bdrv_get_geometry(s->bs, &nb_sectors);
786
    if (!dbd && nb_sectors) {
787
        if (r->req.cmd.buf[0] == MODE_SENSE) {
788
            outbuf[3] = 8; /* Block descriptor length  */
789
        } else { /* MODE_SENSE_10 */
790
            outbuf[7] = 8; /* Block descriptor length  */
791
        }
792
        nb_sectors /= s->cluster_size;
793
        if (nb_sectors > 0xffffff) {
794
            nb_sectors = 0;
795
        }
796
        p[0] = 0; /* media density code */
797
        p[1] = (nb_sectors >> 16) & 0xff;
798
        p[2] = (nb_sectors >> 8) & 0xff;
799
        p[3] = nb_sectors & 0xff;
800
        p[4] = 0; /* reserved */
801
        p[5] = 0; /* bytes 5-7 are the sector size in bytes */
802
        p[6] = s->cluster_size * 2;
803
        p[7] = 0;
804
        p += 8;
805
    }
806

    
807
    if (page_control == 3) {
808
        /* Saved Values */
809
        scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
810
        return -1;
811
    }
812

    
813
    if (page == 0x3f) {
814
        for (page = 0; page <= 0x3e; page++) {
815
            mode_sense_page(s, page, &p, page_control);
816
        }
817
    } else {
818
        ret = mode_sense_page(s, page, &p, page_control);
819
        if (ret == -1) {
820
            return -1;
821
        }
822
    }
823

    
824
    buflen = p - outbuf;
825
    /*
826
     * The mode data length field specifies the length in bytes of the
827
     * following data that is available to be transferred. The mode data
828
     * length does not include itself.
829
     */
830
    if (r->req.cmd.buf[0] == MODE_SENSE) {
831
        outbuf[0] = buflen - 1;
832
    } else { /* MODE_SENSE_10 */
833
        outbuf[0] = ((buflen - 2) >> 8) & 0xff;
834
        outbuf[1] = (buflen - 2) & 0xff;
835
    }
836
    if (buflen > r->req.cmd.xfer) {
837
        buflen = r->req.cmd.xfer;
838
    }
839
    return buflen;
840
}
841

    
842
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
843
{
844
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
845
    int start_track, format, msf, toclen;
846
    uint64_t nb_sectors;
847

    
848
    msf = req->cmd.buf[1] & 2;
849
    format = req->cmd.buf[2] & 0xf;
850
    start_track = req->cmd.buf[6];
851
    bdrv_get_geometry(s->bs, &nb_sectors);
852
    DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
853
    nb_sectors /= s->cluster_size;
854
    switch (format) {
855
    case 0:
856
        toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
857
        break;
858
    case 1:
859
        /* multi session : only a single session defined */
860
        toclen = 12;
861
        memset(outbuf, 0, 12);
862
        outbuf[1] = 0x0a;
863
        outbuf[2] = 0x01;
864
        outbuf[3] = 0x01;
865
        break;
866
    case 2:
867
        toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
868
        break;
869
    default:
870
        return -1;
871
    }
872
    if (toclen > req->cmd.xfer) {
873
        toclen = req->cmd.xfer;
874
    }
875
    return toclen;
876
}
877

    
878
static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
879
{
880
    SCSIRequest *req = &r->req;
881
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
882
    bool start = req->cmd.buf[4] & 1;
883
    bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
884

    
885
    if (s->qdev.type == TYPE_ROM && loej) {
886
        if (!start && !s->tray_open && s->tray_locked) {
887
            scsi_check_condition(r,
888
                                 bdrv_is_inserted(s->bs)
889
                                 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
890
                                 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
891
            return -1;
892
        }
893
        bdrv_eject(s->bs, !start);
894
        s->tray_open = !start;
895
    }
896
    return 0;
897
}
898

    
899
static int scsi_disk_emulate_command(SCSIDiskReq *r)
900
{
901
    SCSIRequest *req = &r->req;
902
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
903
    uint64_t nb_sectors;
904
    uint8_t *outbuf;
905
    int buflen = 0;
906

    
907
    if (!r->iov.iov_base) {
908
        /*
909
         * FIXME: we shouldn't return anything bigger than 4k, but the code
910
         * requires the buffer to be as big as req->cmd.xfer in several
911
         * places.  So, do not allow CDBs with a very large ALLOCATION
912
         * LENGTH.  The real fix would be to modify scsi_read_data and
913
         * dma_buf_read, so that they return data beyond the buflen
914
         * as all zeros.
915
         */
916
        if (req->cmd.xfer > 65536) {
917
            goto illegal_request;
918
        }
919
        r->buflen = MAX(4096, req->cmd.xfer);
920
        r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);
921
    }
922

    
923
    outbuf = r->iov.iov_base;
924
    switch (req->cmd.buf[0]) {
925
    case TEST_UNIT_READY:
926
        if (s->tray_open || !bdrv_is_inserted(s->bs)) {
927
            goto not_ready;
928
        }
929
        break;
930
    case INQUIRY:
931
        buflen = scsi_disk_emulate_inquiry(req, outbuf);
932
        if (buflen < 0) {
933
            goto illegal_request;
934
        }
935
        break;
936
    case MODE_SENSE:
937
    case MODE_SENSE_10:
938
        buflen = scsi_disk_emulate_mode_sense(r, outbuf);
939
        if (buflen < 0) {
940
            goto illegal_request;
941
        }
942
        break;
943
    case READ_TOC:
944
        buflen = scsi_disk_emulate_read_toc(req, outbuf);
945
        if (buflen < 0) {
946
            goto illegal_request;
947
        }
948
        break;
949
    case RESERVE:
950
        if (req->cmd.buf[1] & 1) {
951
            goto illegal_request;
952
        }
953
        break;
954
    case RESERVE_10:
955
        if (req->cmd.buf[1] & 3) {
956
            goto illegal_request;
957
        }
958
        break;
959
    case RELEASE:
960
        if (req->cmd.buf[1] & 1) {
961
            goto illegal_request;
962
        }
963
        break;
964
    case RELEASE_10:
965
        if (req->cmd.buf[1] & 3) {
966
            goto illegal_request;
967
        }
968
        break;
969
    case START_STOP:
970
        if (scsi_disk_emulate_start_stop(r) < 0) {
971
            return -1;
972
        }
973
        break;
974
    case ALLOW_MEDIUM_REMOVAL:
975
        s->tray_locked = req->cmd.buf[4] & 1;
976
        bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1);
977
        break;
978
    case READ_CAPACITY_10:
979
        /* The normal LEN field for this command is zero.  */
980
        memset(outbuf, 0, 8);
981
        bdrv_get_geometry(s->bs, &nb_sectors);
982
        if (!nb_sectors) {
983
            goto not_ready;
984
        }
985
        nb_sectors /= s->cluster_size;
986
        /* Returned value is the address of the last sector.  */
987
        nb_sectors--;
988
        /* Remember the new size for read/write sanity checking. */
989
        s->max_lba = nb_sectors;
990
        /* Clip to 2TB, instead of returning capacity modulo 2TB. */
991
        if (nb_sectors > UINT32_MAX) {
992
            nb_sectors = UINT32_MAX;
993
        }
994
        outbuf[0] = (nb_sectors >> 24) & 0xff;
995
        outbuf[1] = (nb_sectors >> 16) & 0xff;
996
        outbuf[2] = (nb_sectors >> 8) & 0xff;
997
        outbuf[3] = nb_sectors & 0xff;
998
        outbuf[4] = 0;
999
        outbuf[5] = 0;
1000
        outbuf[6] = s->cluster_size * 2;
1001
        outbuf[7] = 0;
1002
        buflen = 8;
1003
        break;
1004
    case MECHANISM_STATUS:
1005
        buflen = scsi_emulate_mechanism_status(s, outbuf);
1006
        if (buflen < 0) {
1007
            goto illegal_request;
1008
        }
1009
        break;
1010
    case GET_CONFIGURATION:
1011
        buflen = scsi_get_configuration(s, r, outbuf);
1012
        if (buflen < 0) {
1013
            goto illegal_request;
1014
        }
1015
        break;
1016
    case GET_EVENT_STATUS_NOTIFICATION:
1017
        buflen = scsi_get_event_status_notification(s, r, outbuf);
1018
        if (buflen < 0) {
1019
            goto illegal_request;
1020
        }
1021
        break;
1022
    case READ_DVD_STRUCTURE:
1023
        buflen = scsi_read_dvd_structure(s, r, outbuf);
1024
        if (buflen < 0) {
1025
            goto illegal_request;
1026
        }
1027
        break;
1028
    case SERVICE_ACTION_IN_16:
1029
        /* Service Action In subcommands. */
1030
        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
1031
            DPRINTF("SAI READ CAPACITY(16)\n");
1032
            memset(outbuf, 0, req->cmd.xfer);
1033
            bdrv_get_geometry(s->bs, &nb_sectors);
1034
            if (!nb_sectors) {
1035
                goto not_ready;
1036
            }
1037
            nb_sectors /= s->cluster_size;
1038
            /* Returned value is the address of the last sector.  */
1039
            nb_sectors--;
1040
            /* Remember the new size for read/write sanity checking. */
1041
            s->max_lba = nb_sectors;
1042
            outbuf[0] = (nb_sectors >> 56) & 0xff;
1043
            outbuf[1] = (nb_sectors >> 48) & 0xff;
1044
            outbuf[2] = (nb_sectors >> 40) & 0xff;
1045
            outbuf[3] = (nb_sectors >> 32) & 0xff;
1046
            outbuf[4] = (nb_sectors >> 24) & 0xff;
1047
            outbuf[5] = (nb_sectors >> 16) & 0xff;
1048
            outbuf[6] = (nb_sectors >> 8) & 0xff;
1049
            outbuf[7] = nb_sectors & 0xff;
1050
            outbuf[8] = 0;
1051
            outbuf[9] = 0;
1052
            outbuf[10] = s->cluster_size * 2;
1053
            outbuf[11] = 0;
1054
            outbuf[12] = 0;
1055
            outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1056

    
1057
            /* set TPE bit if the format supports discard */
1058
            if (s->qdev.conf.discard_granularity) {
1059
                outbuf[14] = 0x80;
1060
            }
1061

    
1062
            /* Protection, exponent and lowest lba field left blank. */
1063
            buflen = req->cmd.xfer;
1064
            break;
1065
        }
1066
        DPRINTF("Unsupported Service Action In\n");
1067
        goto illegal_request;
1068
    case VERIFY_10:
1069
        break;
1070
    default:
1071
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1072
        return -1;
1073
    }
1074
    return buflen;
1075

    
1076
not_ready:
1077
    if (s->tray_open || !bdrv_is_inserted(s->bs)) {
1078
        scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1079
    } else {
1080
        scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1081
    }
1082
    return -1;
1083

    
1084
illegal_request:
1085
    if (r->req.status == -1) {
1086
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1087
    }
1088
    return -1;
1089
}
1090

    
1091
/* Execute a scsi command.  Returns the length of the data expected by the
1092
   command.  This will be Positive for data transfers from the device
1093
   (eg. disk reads), negative for transfers to the device (eg. disk writes),
1094
   and zero if the command does not transfer any data.  */
1095

    
1096
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
1097
{
1098
    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1099
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1100
    int32_t len;
1101
    uint8_t command;
1102
    int rc;
1103

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

    
1107
#ifdef DEBUG_SCSI
1108
    {
1109
        int i;
1110
        for (i = 1; i < r->req.cmd.len; i++) {
1111
            printf(" 0x%02x", buf[i]);
1112
        }
1113
        printf("\n");
1114
    }
1115
#endif
1116

    
1117
    switch (command) {
1118
    case TEST_UNIT_READY:
1119
    case INQUIRY:
1120
    case MODE_SENSE:
1121
    case MODE_SENSE_10:
1122
    case RESERVE:
1123
    case RESERVE_10:
1124
    case RELEASE:
1125
    case RELEASE_10:
1126
    case START_STOP:
1127
    case ALLOW_MEDIUM_REMOVAL:
1128
    case READ_CAPACITY_10:
1129
    case READ_TOC:
1130
    case READ_DVD_STRUCTURE:
1131
    case GET_CONFIGURATION:
1132
    case GET_EVENT_STATUS_NOTIFICATION:
1133
    case MECHANISM_STATUS:
1134
    case SERVICE_ACTION_IN_16:
1135
    case VERIFY_10:
1136
        rc = scsi_disk_emulate_command(r);
1137
        if (rc < 0) {
1138
            return 0;
1139
        }
1140

    
1141
        r->iov.iov_len = rc;
1142
        break;
1143
    case SYNCHRONIZE_CACHE:
1144
        bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1145
        r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);
1146
        if (r->req.aiocb == NULL) {
1147
            scsi_flush_complete(r, -EIO);
1148
        }
1149
        return 0;
1150
    case READ_6:
1151
    case READ_10:
1152
    case READ_12:
1153
    case READ_16:
1154
        len = r->req.cmd.xfer / s->qdev.blocksize;
1155
        DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
1156
        if (r->req.cmd.lba > s->max_lba) {
1157
            goto illegal_lba;
1158
        }
1159
        r->sector = r->req.cmd.lba * s->cluster_size;
1160
        r->sector_count = len * s->cluster_size;
1161
        break;
1162
    case WRITE_6:
1163
    case WRITE_10:
1164
    case WRITE_12:
1165
    case WRITE_16:
1166
    case WRITE_VERIFY_10:
1167
    case WRITE_VERIFY_12:
1168
    case WRITE_VERIFY_16:
1169
        len = r->req.cmd.xfer / s->qdev.blocksize;
1170
        DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
1171
                (command & 0xe) == 0xe ? "And Verify " : "",
1172
                r->req.cmd.lba, len);
1173
        if (r->req.cmd.lba > s->max_lba) {
1174
            goto illegal_lba;
1175
        }
1176
        r->sector = r->req.cmd.lba * s->cluster_size;
1177
        r->sector_count = len * s->cluster_size;
1178
        break;
1179
    case MODE_SELECT:
1180
        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1181
        /* We don't support mode parameter changes.
1182
           Allow the mode parameter header + block descriptors only. */
1183
        if (r->req.cmd.xfer > 12) {
1184
            goto fail;
1185
        }
1186
        break;
1187
    case MODE_SELECT_10:
1188
        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1189
        /* We don't support mode parameter changes.
1190
           Allow the mode parameter header + block descriptors only. */
1191
        if (r->req.cmd.xfer > 16) {
1192
            goto fail;
1193
        }
1194
        break;
1195
    case SEEK_6:
1196
    case SEEK_10:
1197
        DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,
1198
                r->req.cmd.lba);
1199
        if (r->req.cmd.lba > s->max_lba) {
1200
            goto illegal_lba;
1201
        }
1202
        break;
1203
    case WRITE_SAME_16:
1204
        len = r->req.cmd.xfer / s->qdev.blocksize;
1205

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

    
1209
        if (r->req.cmd.lba > s->max_lba) {
1210
            goto illegal_lba;
1211
        }
1212

    
1213
        /*
1214
         * We only support WRITE SAME with the unmap bit set for now.
1215
         */
1216
        if (!(buf[1] & 0x8)) {
1217
            goto fail;
1218
        }
1219

    
1220
        rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,
1221
                          len * s->cluster_size);
1222
        if (rc < 0) {
1223
            /* XXX: better error code ?*/
1224
            goto fail;
1225
        }
1226

    
1227
        break;
1228
    case REQUEST_SENSE:
1229
        abort();
1230
    default:
1231
        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1232
        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1233
        return 0;
1234
    fail:
1235
        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1236
        return 0;
1237
    illegal_lba:
1238
        scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1239
        return 0;
1240
    }
1241
    if (r->sector_count == 0 && r->iov.iov_len == 0) {
1242
        scsi_req_complete(&r->req, GOOD);
1243
    }
1244
    len = r->sector_count * 512 + r->iov.iov_len;
1245
    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1246
        return -len;
1247
    } else {
1248
        if (!r->sector_count) {
1249
            r->sector_count = -1;
1250
        }
1251
        return len;
1252
    }
1253
}
1254

    
1255
static void scsi_disk_reset(DeviceState *dev)
1256
{
1257
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1258
    uint64_t nb_sectors;
1259

    
1260
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1261

    
1262
    bdrv_get_geometry(s->bs, &nb_sectors);
1263
    nb_sectors /= s->cluster_size;
1264
    if (nb_sectors) {
1265
        nb_sectors--;
1266
    }
1267
    s->max_lba = nb_sectors;
1268
}
1269

    
1270
static void scsi_destroy(SCSIDevice *dev)
1271
{
1272
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1273

    
1274
    scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1275
    blockdev_mark_auto_del(s->qdev.conf.bs);
1276
}
1277

    
1278
static void scsi_cd_change_media_cb(void *opaque, bool load)
1279
{
1280
    SCSIDiskState *s = opaque;
1281

    
1282
    /*
1283
     * When a CD gets changed, we have to report an ejected state and
1284
     * then a loaded state to guests so that they detect tray
1285
     * open/close and media change events.  Guests that do not use
1286
     * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1287
     * states rely on this behavior.
1288
     *
1289
     * media_changed governs the state machine used for unit attention
1290
     * report.  media_event is used by GET EVENT STATUS NOTIFICATION.
1291
     */
1292
    s->media_changed = load;
1293
    s->tray_open = !load;
1294
    s->qdev.unit_attention = SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM);
1295
}
1296

    
1297
static bool scsi_cd_is_tray_open(void *opaque)
1298
{
1299
    return ((SCSIDiskState *)opaque)->tray_open;
1300
}
1301

    
1302
static bool scsi_cd_is_medium_locked(void *opaque)
1303
{
1304
    return ((SCSIDiskState *)opaque)->tray_locked;
1305
}
1306

    
1307
static const BlockDevOps scsi_cd_block_ops = {
1308
    .change_media_cb = scsi_cd_change_media_cb,
1309
    .is_tray_open = scsi_cd_is_tray_open,
1310
    .is_medium_locked = scsi_cd_is_medium_locked,
1311
};
1312

    
1313
static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
1314
{
1315
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1316
    if (s->media_changed) {
1317
        s->media_changed = false;
1318
        s->qdev.unit_attention = SENSE_CODE(MEDIUM_CHANGED);
1319
    }
1320
}
1321

    
1322
static int scsi_initfn(SCSIDevice *dev, uint8_t scsi_type)
1323
{
1324
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1325
    DriveInfo *dinfo;
1326

    
1327
    if (!s->qdev.conf.bs) {
1328
        error_report("scsi-disk: drive property not set");
1329
        return -1;
1330
    }
1331
    s->bs = s->qdev.conf.bs;
1332

    
1333
    if (scsi_type == TYPE_DISK && !bdrv_is_inserted(s->bs)) {
1334
        error_report("Device needs media, but drive is empty");
1335
        return -1;
1336
    }
1337

    
1338
    if (!s->serial) {
1339
        /* try to fall back to value set with legacy -drive serial=... */
1340
        dinfo = drive_get_by_blockdev(s->bs);
1341
        if (*dinfo->serial) {
1342
            s->serial = g_strdup(dinfo->serial);
1343
        }
1344
    }
1345

    
1346
    if (!s->version) {
1347
        s->version = g_strdup(QEMU_VERSION);
1348
    }
1349

    
1350
    if (bdrv_is_sg(s->bs)) {
1351
        error_report("scsi-disk: unwanted /dev/sg*");
1352
        return -1;
1353
    }
1354

    
1355
    if (scsi_type == TYPE_ROM) {
1356
        bdrv_set_dev_ops(s->bs, &scsi_cd_block_ops, s);
1357
        s->qdev.blocksize = 2048;
1358
    } else if (scsi_type == TYPE_DISK) {
1359
        s->qdev.blocksize = s->qdev.conf.logical_block_size;
1360
    } else {
1361
        error_report("scsi-disk: Unhandled SCSI type %02x", scsi_type);
1362
        return -1;
1363
    }
1364
    s->cluster_size = s->qdev.blocksize / 512;
1365
    bdrv_set_buffer_alignment(s->bs, s->qdev.blocksize);
1366

    
1367
    s->qdev.type = scsi_type;
1368
    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
1369
    bdrv_iostatus_enable(s->bs);
1370
    add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, ",0");
1371
    return 0;
1372
}
1373

    
1374
static int scsi_hd_initfn(SCSIDevice *dev)
1375
{
1376
    return scsi_initfn(dev, TYPE_DISK);
1377
}
1378

    
1379
static int scsi_cd_initfn(SCSIDevice *dev)
1380
{
1381
    return scsi_initfn(dev, TYPE_ROM);
1382
}
1383

    
1384
static int scsi_disk_initfn(SCSIDevice *dev)
1385
{
1386
    DriveInfo *dinfo;
1387
    uint8_t scsi_type;
1388

    
1389
    if (!dev->conf.bs) {
1390
        scsi_type = TYPE_DISK;  /* will die in scsi_initfn() */
1391
    } else {
1392
        dinfo = drive_get_by_blockdev(dev->conf.bs);
1393
        scsi_type = dinfo->media_cd ? TYPE_ROM : TYPE_DISK;
1394
    }
1395

    
1396
    return scsi_initfn(dev, scsi_type);
1397
}
1398

    
1399
static SCSIReqOps scsi_disk_reqops = {
1400
    .size         = sizeof(SCSIDiskReq),
1401
    .free_req     = scsi_free_request,
1402
    .send_command = scsi_send_command,
1403
    .read_data    = scsi_read_data,
1404
    .write_data   = scsi_write_data,
1405
    .cancel_io    = scsi_cancel_io,
1406
    .get_buf      = scsi_get_buf,
1407
};
1408

    
1409
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
1410
                                     uint32_t lun, void *hba_private)
1411
{
1412
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
1413
    SCSIRequest *req;
1414

    
1415
    req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
1416
    return req;
1417
}
1418

    
1419
#define DEFINE_SCSI_DISK_PROPERTIES()                           \
1420
    DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),          \
1421
    DEFINE_PROP_STRING("ver",  SCSIDiskState, version),         \
1422
    DEFINE_PROP_STRING("serial",  SCSIDiskState, serial)
1423

    
1424
static SCSIDeviceInfo scsi_disk_info[] = {
1425
    {
1426
        .qdev.name    = "scsi-hd",
1427
        .qdev.fw_name = "disk",
1428
        .qdev.desc    = "virtual SCSI disk",
1429
        .qdev.size    = sizeof(SCSIDiskState),
1430
        .qdev.reset   = scsi_disk_reset,
1431
        .init         = scsi_hd_initfn,
1432
        .destroy      = scsi_destroy,
1433
        .alloc_req    = scsi_new_request,
1434
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1435
        .qdev.props   = (Property[]) {
1436
            DEFINE_SCSI_DISK_PROPERTIES(),
1437
            DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
1438
            DEFINE_PROP_END_OF_LIST(),
1439
        }
1440
    },{
1441
        .qdev.name    = "scsi-cd",
1442
        .qdev.fw_name = "disk",
1443
        .qdev.desc    = "virtual SCSI CD-ROM",
1444
        .qdev.size    = sizeof(SCSIDiskState),
1445
        .qdev.reset   = scsi_disk_reset,
1446
        .init         = scsi_cd_initfn,
1447
        .destroy      = scsi_destroy,
1448
        .alloc_req    = scsi_new_request,
1449
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1450
        .qdev.props   = (Property[]) {
1451
            DEFINE_SCSI_DISK_PROPERTIES(),
1452
            DEFINE_PROP_END_OF_LIST(),
1453
        },
1454
    },{
1455
        .qdev.name    = "scsi-disk", /* legacy -device scsi-disk */
1456
        .qdev.fw_name = "disk",
1457
        .qdev.desc    = "virtual SCSI disk or CD-ROM (legacy)",
1458
        .qdev.size    = sizeof(SCSIDiskState),
1459
        .qdev.reset   = scsi_disk_reset,
1460
        .init         = scsi_disk_initfn,
1461
        .destroy      = scsi_destroy,
1462
        .alloc_req    = scsi_new_request,
1463
        .unit_attention_reported = scsi_disk_unit_attention_reported,
1464
        .qdev.props   = (Property[]) {
1465
            DEFINE_SCSI_DISK_PROPERTIES(),
1466
            DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
1467
            DEFINE_PROP_END_OF_LIST(),
1468
        }
1469
    }
1470
};
1471

    
1472
static void scsi_disk_register_devices(void)
1473
{
1474
    int i;
1475

    
1476
    for (i = 0; i < ARRAY_SIZE(scsi_disk_info); i++) {
1477
        scsi_qdev_register(&scsi_disk_info[i]);
1478
    }
1479
}
1480
device_init(scsi_disk_register_devices)