Statistics
| Branch: | Revision:

root / hw / scsi-disk.c @ ce512ee1

History | View | Annotate | Download (34 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 licenced 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

    
41
#define SCSI_DMA_BUF_SIZE    131072
42
#define SCSI_MAX_INQUIRY_LEN 256
43

    
44
#define SCSI_REQ_STATUS_RETRY 0x01
45

    
46
typedef struct SCSIDiskState SCSIDiskState;
47

    
48
typedef struct SCSIDiskReq {
49
    SCSIRequest req;
50
    /* ??? We should probably keep track of whether the data transfer is
51
       a read or a write.  Currently we rely on the host getting it right.  */
52
    /* Both sector and sector_count are in terms of qemu 512 byte blocks.  */
53
    uint64_t sector;
54
    uint32_t sector_count;
55
    struct iovec iov;
56
    QEMUIOVector qiov;
57
    uint32_t status;
58
} SCSIDiskReq;
59

    
60
struct SCSIDiskState
61
{
62
    SCSIDevice qdev;
63
    BlockDriverState *bs;
64
    /* The qemu block layer uses a fixed 512 byte sector size.
65
       This is the number of 512 byte blocks in a single scsi sector.  */
66
    int cluster_size;
67
    uint64_t max_lba;
68
    QEMUBH *bh;
69
    char *version;
70
    char *serial;
71
};
72

    
73
static SCSIDiskReq *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun)
74
{
75
    SCSIRequest *req;
76
    SCSIDiskReq *r;
77

    
78
    req = scsi_req_alloc(sizeof(SCSIDiskReq), d, tag, lun);
79
    r = DO_UPCAST(SCSIDiskReq, req, req);
80
    r->iov.iov_base = qemu_memalign(512, SCSI_DMA_BUF_SIZE);
81
    return r;
82
}
83

    
84
static void scsi_remove_request(SCSIDiskReq *r)
85
{
86
    qemu_vfree(r->iov.iov_base);
87
    scsi_req_free(&r->req);
88
}
89

    
90
static SCSIDiskReq *scsi_find_request(SCSIDiskState *s, uint32_t tag)
91
{
92
    return DO_UPCAST(SCSIDiskReq, req, scsi_req_find(&s->qdev, tag));
93
}
94

    
95
static void scsi_req_set_status(SCSIRequest *req, int status, int sense_code)
96
{
97
    req->status = status;
98
    scsi_dev_set_sense(req->dev, sense_code);
99
}
100

    
101
/* Helper function for command completion.  */
102
static void scsi_command_complete(SCSIDiskReq *r, int status, int sense)
103
{
104
    DPRINTF("Command complete tag=0x%x status=%d sense=%d\n",
105
            r->req.tag, status, sense);
106
    scsi_req_set_status(&r->req, status, sense);
107
    scsi_req_complete(&r->req);
108
    scsi_remove_request(r);
109
}
110

    
111
/* Cancel a pending data transfer.  */
112
static void scsi_cancel_io(SCSIDevice *d, uint32_t tag)
113
{
114
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
115
    SCSIDiskReq *r;
116
    DPRINTF("Cancel tag=0x%x\n", tag);
117
    r = scsi_find_request(s, tag);
118
    if (r) {
119
        if (r->req.aiocb)
120
            bdrv_aio_cancel(r->req.aiocb);
121
        r->req.aiocb = NULL;
122
        scsi_remove_request(r);
123
    }
124
}
125

    
126
static void scsi_read_complete(void * opaque, int ret)
127
{
128
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
129

    
130
    r->req.aiocb = NULL;
131

    
132
    if (ret) {
133
        DPRINTF("IO error\n");
134
        r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, 0);
135
        scsi_command_complete(r, CHECK_CONDITION, NO_SENSE);
136
        return;
137
    }
138
    DPRINTF("Data ready tag=0x%x len=%" PRId64 "\n", r->req.tag, r->iov.iov_len);
139

    
140
    r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, r->iov.iov_len);
141
}
142

    
143
/* Read more data from scsi device into buffer.  */
144
static void scsi_read_data(SCSIDevice *d, uint32_t tag)
145
{
146
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
147
    SCSIDiskReq *r;
148
    uint32_t n;
149

    
150
    r = scsi_find_request(s, tag);
151
    if (!r) {
152
        BADF("Bad read tag 0x%x\n", tag);
153
        /* ??? This is the wrong error.  */
154
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
155
        return;
156
    }
157
    if (r->sector_count == (uint32_t)-1) {
158
        DPRINTF("Read buf_len=%" PRId64 "\n", r->iov.iov_len);
159
        r->sector_count = 0;
160
        r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, r->iov.iov_len);
161
        return;
162
    }
163
    DPRINTF("Read sector_count=%d\n", r->sector_count);
164
    if (r->sector_count == 0) {
165
        scsi_command_complete(r, GOOD, NO_SENSE);
166
        return;
167
    }
168

    
169
    n = r->sector_count;
170
    if (n > SCSI_DMA_BUF_SIZE / 512)
171
        n = SCSI_DMA_BUF_SIZE / 512;
172

    
173
    r->iov.iov_len = n * 512;
174
    qemu_iovec_init_external(&r->qiov, &r->iov, 1);
175
    r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
176
                              scsi_read_complete, r);
177
    if (r->req.aiocb == NULL)
178
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
179
    r->sector += n;
180
    r->sector_count -= n;
181
}
182

    
183
static int scsi_handle_write_error(SCSIDiskReq *r, int error)
184
{
185
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
186
    BlockErrorAction action = bdrv_get_on_error(s->bs, 0);
187

    
188
    if (action == BLOCK_ERR_IGNORE) {
189
        bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, 0);
190
        return 0;
191
    }
192

    
193
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
194
            || action == BLOCK_ERR_STOP_ANY) {
195
        r->status |= SCSI_REQ_STATUS_RETRY;
196
        bdrv_mon_event(s->bs, BDRV_ACTION_STOP, 0);
197
        vm_stop(0);
198
    } else {
199
        scsi_command_complete(r, CHECK_CONDITION,
200
                HARDWARE_ERROR);
201
        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, 0);
202
    }
203

    
204
    return 1;
205
}
206

    
207
static void scsi_write_complete(void * opaque, int ret)
208
{
209
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
210
    uint32_t len;
211
    uint32_t n;
212

    
213
    r->req.aiocb = NULL;
214

    
215
    if (ret) {
216
        if (scsi_handle_write_error(r, -ret))
217
            return;
218
    }
219

    
220
    n = r->iov.iov_len / 512;
221
    r->sector += n;
222
    r->sector_count -= n;
223
    if (r->sector_count == 0) {
224
        scsi_command_complete(r, GOOD, NO_SENSE);
225
    } else {
226
        len = r->sector_count * 512;
227
        if (len > SCSI_DMA_BUF_SIZE) {
228
            len = SCSI_DMA_BUF_SIZE;
229
        }
230
        r->iov.iov_len = len;
231
        DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, len);
232
        r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, len);
233
    }
234
}
235

    
236
static void scsi_write_request(SCSIDiskReq *r)
237
{
238
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
239
    uint32_t n;
240

    
241
    n = r->iov.iov_len / 512;
242
    if (n) {
243
        qemu_iovec_init_external(&r->qiov, &r->iov, 1);
244
        r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,
245
                                   scsi_write_complete, r);
246
        if (r->req.aiocb == NULL)
247
            scsi_command_complete(r, CHECK_CONDITION,
248
                                  HARDWARE_ERROR);
249
    } else {
250
        /* Invoke completion routine to fetch data from host.  */
251
        scsi_write_complete(r, 0);
252
    }
253
}
254

    
255
/* Write data to a scsi device.  Returns nonzero on failure.
256
   The transfer may complete asynchronously.  */
257
static int scsi_write_data(SCSIDevice *d, uint32_t tag)
258
{
259
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
260
    SCSIDiskReq *r;
261

    
262
    DPRINTF("Write data tag=0x%x\n", tag);
263
    r = scsi_find_request(s, tag);
264
    if (!r) {
265
        BADF("Bad write tag 0x%x\n", tag);
266
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
267
        return 1;
268
    }
269

    
270
    if (r->req.aiocb)
271
        BADF("Data transfer already in progress\n");
272

    
273
    scsi_write_request(r);
274

    
275
    return 0;
276
}
277

    
278
static void scsi_dma_restart_bh(void *opaque)
279
{
280
    SCSIDiskState *s = opaque;
281
    SCSIRequest *req;
282
    SCSIDiskReq *r;
283

    
284
    qemu_bh_delete(s->bh);
285
    s->bh = NULL;
286

    
287
    QTAILQ_FOREACH(req, &s->qdev.requests, next) {
288
        r = DO_UPCAST(SCSIDiskReq, req, req);
289
        if (r->status & SCSI_REQ_STATUS_RETRY) {
290
            r->status &= ~SCSI_REQ_STATUS_RETRY;
291
            scsi_write_request(r); 
292
        }
293
    }
294
}
295

    
296
static void scsi_dma_restart_cb(void *opaque, int running, int reason)
297
{
298
    SCSIDiskState *s = opaque;
299

    
300
    if (!running)
301
        return;
302

    
303
    if (!s->bh) {
304
        s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
305
        qemu_bh_schedule(s->bh);
306
    }
307
}
308

    
309
/* Return a pointer to the data buffer.  */
310
static uint8_t *scsi_get_buf(SCSIDevice *d, uint32_t tag)
311
{
312
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
313
    SCSIDiskReq *r;
314

    
315
    r = scsi_find_request(s, tag);
316
    if (!r) {
317
        BADF("Bad buffer tag 0x%x\n", tag);
318
        return NULL;
319
    }
320
    return (uint8_t *)r->iov.iov_base;
321
}
322

    
323
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
324
{
325
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
326
    int buflen = 0;
327

    
328
    if (req->cmd.buf[1] & 0x2) {
329
        /* Command support data - optional, not implemented */
330
        BADF("optional INQUIRY command support request not implemented\n");
331
        return -1;
332
    }
333

    
334
    if (req->cmd.buf[1] & 0x1) {
335
        /* Vital product data */
336
        uint8_t page_code = req->cmd.buf[2];
337
        if (req->cmd.xfer < 4) {
338
            BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "
339
                 "less than 4\n", page_code, req->cmd.xfer);
340
            return -1;
341
        }
342

    
343
        if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
344
            outbuf[buflen++] = 5;
345
        } else {
346
            outbuf[buflen++] = 0;
347
        }
348
        outbuf[buflen++] = page_code ; // this page
349
        outbuf[buflen++] = 0x00;
350

    
351
        switch (page_code) {
352
        case 0x00: /* Supported page codes, mandatory */
353
            DPRINTF("Inquiry EVPD[Supported pages] "
354
                    "buffer size %zd\n", req->cmd.xfer);
355
            outbuf[buflen++] = 4;    // number of pages
356
            outbuf[buflen++] = 0x00; // list of supported pages (this page)
357
            outbuf[buflen++] = 0x80; // unit serial number
358
            outbuf[buflen++] = 0x83; // device identification
359
            outbuf[buflen++] = 0xb0; // block device characteristics
360
            break;
361

    
362
        case 0x80: /* Device serial number, optional */
363
        {
364
            int l = strlen(s->serial);
365

    
366
            if (l > req->cmd.xfer)
367
                l = req->cmd.xfer;
368
            if (l > 20)
369
                l = 20;
370

    
371
            DPRINTF("Inquiry EVPD[Serial number] "
372
                    "buffer size %zd\n", req->cmd.xfer);
373
            outbuf[buflen++] = l;
374
            memcpy(outbuf+buflen, s->serial, l);
375
            buflen += l;
376
            break;
377
        }
378

    
379
        case 0x83: /* Device identification page, mandatory */
380
        {
381
            int max_len = 255 - 8;
382
            int id_len = strlen(bdrv_get_device_name(s->bs));
383

    
384
            if (id_len > max_len)
385
                id_len = max_len;
386
            DPRINTF("Inquiry EVPD[Device identification] "
387
                    "buffer size %zd\n", req->cmd.xfer);
388

    
389
            outbuf[buflen++] = 3 + id_len;
390
            outbuf[buflen++] = 0x2; // ASCII
391
            outbuf[buflen++] = 0;   // not officially assigned
392
            outbuf[buflen++] = 0;   // reserved
393
            outbuf[buflen++] = id_len; // length of data following
394

    
395
            memcpy(outbuf+buflen, bdrv_get_device_name(s->bs), id_len);
396
            buflen += id_len;
397
            break;
398
        }
399
        case 0xb0: /* block device characteristics */
400
        {
401
            unsigned int min_io_size =
402
                    s->qdev.conf.min_io_size / s->qdev.blocksize;
403
            unsigned int opt_io_size =
404
                    s->qdev.conf.opt_io_size / s->qdev.blocksize;
405

    
406
            /* required VPD size with unmap support */
407
            outbuf[3] = buflen = 0x3c;
408

    
409
            memset(outbuf + 4, 0, buflen - 4);
410

    
411
            /* optimal transfer length granularity */
412
            outbuf[6] = (min_io_size >> 8) & 0xff;
413
            outbuf[7] = min_io_size & 0xff;
414

    
415
            /* optimal transfer length */
416
            outbuf[12] = (opt_io_size >> 24) & 0xff;
417
            outbuf[13] = (opt_io_size >> 16) & 0xff;
418
            outbuf[14] = (opt_io_size >> 8) & 0xff;
419
            outbuf[15] = opt_io_size & 0xff;
420
            break;
421
        }
422
        default:
423
            BADF("Error: unsupported Inquiry (EVPD[%02X]) "
424
                 "buffer size %zd\n", page_code, req->cmd.xfer);
425
            return -1;
426
        }
427
        /* done with EVPD */
428
        return buflen;
429
    }
430

    
431
    /* Standard INQUIRY data */
432
    if (req->cmd.buf[2] != 0) {
433
        BADF("Error: Inquiry (STANDARD) page or code "
434
             "is non-zero [%02X]\n", req->cmd.buf[2]);
435
        return -1;
436
    }
437

    
438
    /* PAGE CODE == 0 */
439
    if (req->cmd.xfer < 5) {
440
        BADF("Error: Inquiry (STANDARD) buffer size %zd "
441
             "is less than 5\n", req->cmd.xfer);
442
        return -1;
443
    }
444

    
445
    buflen = req->cmd.xfer;
446
    if (buflen > SCSI_MAX_INQUIRY_LEN)
447
        buflen = SCSI_MAX_INQUIRY_LEN;
448

    
449
    memset(outbuf, 0, buflen);
450

    
451
    if (req->lun || req->cmd.buf[1] >> 5) {
452
        outbuf[0] = 0x7f;        /* LUN not supported */
453
        return buflen;
454
    }
455

    
456
    if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {
457
        outbuf[0] = 5;
458
        outbuf[1] = 0x80;
459
        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);
460
    } else {
461
        outbuf[0] = 0;
462
        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);
463
    }
464
    memcpy(&outbuf[8], "QEMU    ", 8);
465
    memset(&outbuf[32], 0, 4);
466
    memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
467
    /*
468
     * We claim conformance to SPC-3, which is required for guests
469
     * to ask for modern features like READ CAPACITY(16) or the
470
     * block characteristics VPD page by default.  Not all of SPC-3
471
     * is actually implemented, but we're good enough.
472
     */
473
    outbuf[2] = 5;
474
    outbuf[3] = 2; /* Format 2 */
475

    
476
    if (buflen > 36) {
477
        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
478
    } else {
479
        /* If the allocation length of CDB is too small,
480
               the additional length is not adjusted */
481
        outbuf[4] = 36 - 5;
482
    }
483

    
484
    /* Sync data transfer and TCQ.  */
485
    outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);
486
    return buflen;
487
}
488

    
489
static int mode_sense_page(SCSIRequest *req, int page, uint8_t *p)
490
{
491
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
492
    BlockDriverState *bdrv = s->bs;
493
    int cylinders, heads, secs;
494

    
495
    switch (page) {
496
    case 4: /* Rigid disk device geometry page. */
497
        p[0] = 4;
498
        p[1] = 0x16;
499
        /* if a geometry hint is available, use it */
500
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
501
        p[2] = (cylinders >> 16) & 0xff;
502
        p[3] = (cylinders >> 8) & 0xff;
503
        p[4] = cylinders & 0xff;
504
        p[5] = heads & 0xff;
505
        /* Write precomp start cylinder, disabled */
506
        p[6] = (cylinders >> 16) & 0xff;
507
        p[7] = (cylinders >> 8) & 0xff;
508
        p[8] = cylinders & 0xff;
509
        /* Reduced current start cylinder, disabled */
510
        p[9] = (cylinders >> 16) & 0xff;
511
        p[10] = (cylinders >> 8) & 0xff;
512
        p[11] = cylinders & 0xff;
513
        /* Device step rate [ns], 200ns */
514
        p[12] = 0;
515
        p[13] = 200;
516
        /* Landing zone cylinder */
517
        p[14] = 0xff;
518
        p[15] =  0xff;
519
        p[16] = 0xff;
520
        /* Medium rotation rate [rpm], 5400 rpm */
521
        p[20] = (5400 >> 8) & 0xff;
522
        p[21] = 5400 & 0xff;
523
        return 0x16;
524

    
525
    case 5: /* Flexible disk device geometry page. */
526
        p[0] = 5;
527
        p[1] = 0x1e;
528
        /* Transfer rate [kbit/s], 5Mbit/s */
529
        p[2] = 5000 >> 8;
530
        p[3] = 5000 & 0xff;
531
        /* if a geometry hint is available, use it */
532
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
533
        p[4] = heads & 0xff;
534
        p[5] = secs & 0xff;
535
        p[6] = s->cluster_size * 2;
536
        p[8] = (cylinders >> 8) & 0xff;
537
        p[9] = cylinders & 0xff;
538
        /* Write precomp start cylinder, disabled */
539
        p[10] = (cylinders >> 8) & 0xff;
540
        p[11] = cylinders & 0xff;
541
        /* Reduced current start cylinder, disabled */
542
        p[12] = (cylinders >> 8) & 0xff;
543
        p[13] = cylinders & 0xff;
544
        /* Device step rate [100us], 100us */
545
        p[14] = 0;
546
        p[15] = 1;
547
        /* Device step pulse width [us], 1us */
548
        p[16] = 1;
549
        /* Device head settle delay [100us], 100us */
550
        p[17] = 0;
551
        p[18] = 1;
552
        /* Motor on delay [0.1s], 0.1s */
553
        p[19] = 1;
554
        /* Motor off delay [0.1s], 0.1s */
555
        p[20] = 1;
556
        /* Medium rotation rate [rpm], 5400 rpm */
557
        p[28] = (5400 >> 8) & 0xff;
558
        p[29] = 5400 & 0xff;
559
        return 0x1e;
560

    
561
    case 8: /* Caching page.  */
562
        p[0] = 8;
563
        p[1] = 0x12;
564
        if (bdrv_enable_write_cache(s->bs)) {
565
            p[2] = 4; /* WCE */
566
        }
567
        return 20;
568

    
569
    case 0x2a: /* CD Capabilities and Mechanical Status page. */
570
        if (bdrv_get_type_hint(bdrv) != BDRV_TYPE_CDROM)
571
            return 0;
572
        p[0] = 0x2a;
573
        p[1] = 0x14;
574
        p[2] = 3; // CD-R & CD-RW read
575
        p[3] = 0; // Writing not supported
576
        p[4] = 0x7f; /* Audio, composite, digital out,
577
                        mode 2 form 1&2, multi session */
578
        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
579
                        RW corrected, C2 errors, ISRC,
580
                        UPC, Bar code */
581
        p[6] = 0x2d | (bdrv_is_locked(s->bs)? 2 : 0);
582
        /* Locking supported, jumper present, eject, tray */
583
        p[7] = 0; /* no volume & mute control, no
584
                     changer */
585
        p[8] = (50 * 176) >> 8; // 50x read speed
586
        p[9] = (50 * 176) & 0xff;
587
        p[10] = 0 >> 8; // No volume
588
        p[11] = 0 & 0xff;
589
        p[12] = 2048 >> 8; // 2M buffer
590
        p[13] = 2048 & 0xff;
591
        p[14] = (16 * 176) >> 8; // 16x read speed current
592
        p[15] = (16 * 176) & 0xff;
593
        p[18] = (16 * 176) >> 8; // 16x write speed
594
        p[19] = (16 * 176) & 0xff;
595
        p[20] = (16 * 176) >> 8; // 16x write speed current
596
        p[21] = (16 * 176) & 0xff;
597
        return 22;
598

    
599
    default:
600
        return 0;
601
    }
602
}
603

    
604
static int scsi_disk_emulate_mode_sense(SCSIRequest *req, uint8_t *outbuf)
605
{
606
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
607
    uint64_t nb_sectors;
608
    int page, dbd, buflen;
609
    uint8_t *p;
610
    uint8_t dev_specific_param;
611

    
612
    dbd = req->cmd.buf[1]  & 0x8;
613
    page = req->cmd.buf[2] & 0x3f;
614
    DPRINTF("Mode Sense (page %d, len %zd)\n", page, req->cmd.xfer);
615
    memset(outbuf, 0, req->cmd.xfer);
616
    p = outbuf;
617

    
618
    if (bdrv_is_read_only(s->bs)) {
619
        dev_specific_param = 0x80; /* Readonly.  */
620
    } else {
621
        dev_specific_param = 0x00;
622
    }
623

    
624
    if (req->cmd.buf[0] == MODE_SENSE) {
625
        p[1] = 0; /* Default media type.  */
626
        p[2] = dev_specific_param;
627
        p[3] = 0; /* Block descriptor length.  */
628
        p += 4;
629
    } else { /* MODE_SENSE_10 */
630
        p[2] = 0; /* Default media type.  */
631
        p[3] = dev_specific_param;
632
        p[6] = p[7] = 0; /* Block descriptor length.  */
633
        p += 8;
634
    }
635

    
636
    bdrv_get_geometry(s->bs, &nb_sectors);
637
    if ((~dbd) & nb_sectors) {
638
        if (req->cmd.buf[0] == MODE_SENSE) {
639
            outbuf[3] = 8; /* Block descriptor length  */
640
        } else { /* MODE_SENSE_10 */
641
            outbuf[7] = 8; /* Block descriptor length  */
642
        }
643
        nb_sectors /= s->cluster_size;
644
        nb_sectors--;
645
        if (nb_sectors > 0xffffff)
646
            nb_sectors = 0xffffff;
647
        p[0] = 0; /* media density code */
648
        p[1] = (nb_sectors >> 16) & 0xff;
649
        p[2] = (nb_sectors >> 8) & 0xff;
650
        p[3] = nb_sectors & 0xff;
651
        p[4] = 0; /* reserved */
652
        p[5] = 0; /* bytes 5-7 are the sector size in bytes */
653
        p[6] = s->cluster_size * 2;
654
        p[7] = 0;
655
        p += 8;
656
    }
657

    
658
    switch (page) {
659
    case 0x04:
660
    case 0x05:
661
    case 0x08:
662
    case 0x2a:
663
        p += mode_sense_page(req, page, p);
664
        break;
665
    case 0x3f:
666
        p += mode_sense_page(req, 0x08, p);
667
        p += mode_sense_page(req, 0x2a, p);
668
        break;
669
    }
670

    
671
    buflen = p - outbuf;
672
    /*
673
     * The mode data length field specifies the length in bytes of the
674
     * following data that is available to be transferred. The mode data
675
     * length does not include itself.
676
     */
677
    if (req->cmd.buf[0] == MODE_SENSE) {
678
        outbuf[0] = buflen - 1;
679
    } else { /* MODE_SENSE_10 */
680
        outbuf[0] = ((buflen - 2) >> 8) & 0xff;
681
        outbuf[1] = (buflen - 2) & 0xff;
682
    }
683
    if (buflen > req->cmd.xfer)
684
        buflen = req->cmd.xfer;
685
    return buflen;
686
}
687

    
688
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
689
{
690
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
691
    int start_track, format, msf, toclen;
692
    uint64_t nb_sectors;
693

    
694
    msf = req->cmd.buf[1] & 2;
695
    format = req->cmd.buf[2] & 0xf;
696
    start_track = req->cmd.buf[6];
697
    bdrv_get_geometry(s->bs, &nb_sectors);
698
    DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
699
    nb_sectors /= s->cluster_size;
700
    switch (format) {
701
    case 0:
702
        toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
703
        break;
704
    case 1:
705
        /* multi session : only a single session defined */
706
        toclen = 12;
707
        memset(outbuf, 0, 12);
708
        outbuf[1] = 0x0a;
709
        outbuf[2] = 0x01;
710
        outbuf[3] = 0x01;
711
        break;
712
    case 2:
713
        toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
714
        break;
715
    default:
716
        return -1;
717
    }
718
    if (toclen > req->cmd.xfer)
719
        toclen = req->cmd.xfer;
720
    return toclen;
721
}
722

    
723
static int scsi_disk_emulate_command(SCSIRequest *req, uint8_t *outbuf)
724
{
725
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
726
    uint64_t nb_sectors;
727
    int buflen = 0;
728

    
729
    switch (req->cmd.buf[0]) {
730
    case TEST_UNIT_READY:
731
        if (!bdrv_is_inserted(s->bs))
732
            goto not_ready;
733
        break;
734
    case REQUEST_SENSE:
735
        if (req->cmd.xfer < 4)
736
            goto illegal_request;
737
        memset(outbuf, 0, 4);
738
        buflen = 4;
739
        if (req->dev->sense.key == NOT_READY && req->cmd.xfer >= 18) {
740
            memset(outbuf, 0, 18);
741
            buflen = 18;
742
            outbuf[7] = 10;
743
            /* asc 0x3a, ascq 0: Medium not present */
744
            outbuf[12] = 0x3a;
745
            outbuf[13] = 0;
746
        }
747
        outbuf[0] = 0xf0;
748
        outbuf[1] = 0;
749
        outbuf[2] = req->dev->sense.key;
750
        scsi_dev_clear_sense(req->dev);
751
        break;
752
    case INQUIRY:
753
        buflen = scsi_disk_emulate_inquiry(req, outbuf);
754
        if (buflen < 0)
755
            goto illegal_request;
756
        break;
757
    case MODE_SENSE:
758
    case MODE_SENSE_10:
759
        buflen = scsi_disk_emulate_mode_sense(req, outbuf);
760
        if (buflen < 0)
761
            goto illegal_request;
762
        break;
763
    case READ_TOC:
764
        buflen = scsi_disk_emulate_read_toc(req, outbuf);
765
        if (buflen < 0)
766
            goto illegal_request;
767
        break;
768
    case RESERVE:
769
        if (req->cmd.buf[1] & 1)
770
            goto illegal_request;
771
        break;
772
    case RESERVE_10:
773
        if (req->cmd.buf[1] & 3)
774
            goto illegal_request;
775
        break;
776
    case RELEASE:
777
        if (req->cmd.buf[1] & 1)
778
            goto illegal_request;
779
        break;
780
    case RELEASE_10:
781
        if (req->cmd.buf[1] & 3)
782
            goto illegal_request;
783
        break;
784
    case START_STOP:
785
        if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM && (req->cmd.buf[4] & 2)) {
786
            /* load/eject medium */
787
            bdrv_eject(s->bs, !(req->cmd.buf[4] & 1));
788
        }
789
        break;
790
    case ALLOW_MEDIUM_REMOVAL:
791
        bdrv_set_locked(s->bs, req->cmd.buf[4] & 1);
792
        break;
793
    case READ_CAPACITY:
794
        /* The normal LEN field for this command is zero.  */
795
        memset(outbuf, 0, 8);
796
        bdrv_get_geometry(s->bs, &nb_sectors);
797
        if (!nb_sectors)
798
            goto not_ready;
799
        nb_sectors /= s->cluster_size;
800
        /* Returned value is the address of the last sector.  */
801
        nb_sectors--;
802
        /* Remember the new size for read/write sanity checking. */
803
        s->max_lba = nb_sectors;
804
        /* Clip to 2TB, instead of returning capacity modulo 2TB. */
805
        if (nb_sectors > UINT32_MAX)
806
            nb_sectors = UINT32_MAX;
807
        outbuf[0] = (nb_sectors >> 24) & 0xff;
808
        outbuf[1] = (nb_sectors >> 16) & 0xff;
809
        outbuf[2] = (nb_sectors >> 8) & 0xff;
810
        outbuf[3] = nb_sectors & 0xff;
811
        outbuf[4] = 0;
812
        outbuf[5] = 0;
813
        outbuf[6] = s->cluster_size * 2;
814
        outbuf[7] = 0;
815
        buflen = 8;
816
        break;
817
    case SYNCHRONIZE_CACHE:
818
        bdrv_flush(s->bs);
819
        break;
820
    case GET_CONFIGURATION:
821
        memset(outbuf, 0, 8);
822
        /* ??? This should probably return much more information.  For now
823
           just return the basic header indicating the CD-ROM profile.  */
824
        outbuf[7] = 8; // CD-ROM
825
        buflen = 8;
826
        break;
827
    case SERVICE_ACTION_IN:
828
        /* Service Action In subcommands. */
829
        if ((req->cmd.buf[1] & 31) == 0x10) {
830
            DPRINTF("SAI READ CAPACITY(16)\n");
831
            memset(outbuf, 0, req->cmd.xfer);
832
            bdrv_get_geometry(s->bs, &nb_sectors);
833
            if (!nb_sectors)
834
                goto not_ready;
835
            nb_sectors /= s->cluster_size;
836
            /* Returned value is the address of the last sector.  */
837
            nb_sectors--;
838
            /* Remember the new size for read/write sanity checking. */
839
            s->max_lba = nb_sectors;
840
            outbuf[0] = (nb_sectors >> 56) & 0xff;
841
            outbuf[1] = (nb_sectors >> 48) & 0xff;
842
            outbuf[2] = (nb_sectors >> 40) & 0xff;
843
            outbuf[3] = (nb_sectors >> 32) & 0xff;
844
            outbuf[4] = (nb_sectors >> 24) & 0xff;
845
            outbuf[5] = (nb_sectors >> 16) & 0xff;
846
            outbuf[6] = (nb_sectors >> 8) & 0xff;
847
            outbuf[7] = nb_sectors & 0xff;
848
            outbuf[8] = 0;
849
            outbuf[9] = 0;
850
            outbuf[10] = s->cluster_size * 2;
851
            outbuf[11] = 0;
852
            outbuf[12] = 0;
853
            outbuf[13] = get_physical_block_exp(&s->qdev.conf);
854
            /* Protection, exponent and lowest lba field left blank. */
855
            buflen = req->cmd.xfer;
856
            break;
857
        }
858
        DPRINTF("Unsupported Service Action In\n");
859
        goto illegal_request;
860
    case REPORT_LUNS:
861
        if (req->cmd.xfer < 16)
862
            goto illegal_request;
863
        memset(outbuf, 0, 16);
864
        outbuf[3] = 8;
865
        buflen = 16;
866
        break;
867
    case VERIFY:
868
        break;
869
    default:
870
        goto illegal_request;
871
    }
872
    scsi_req_set_status(req, GOOD, NO_SENSE);
873
    return buflen;
874

    
875
not_ready:
876
    scsi_req_set_status(req, CHECK_CONDITION, NOT_READY);
877
    return 0;
878

    
879
illegal_request:
880
    scsi_req_set_status(req, CHECK_CONDITION, ILLEGAL_REQUEST);
881
    return 0;
882
}
883

    
884
/* Execute a scsi command.  Returns the length of the data expected by the
885
   command.  This will be Positive for data transfers from the device
886
   (eg. disk reads), negative for transfers to the device (eg. disk writes),
887
   and zero if the command does not transfer any data.  */
888

    
889
static int32_t scsi_send_command(SCSIDevice *d, uint32_t tag,
890
                                 uint8_t *buf, int lun)
891
{
892
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
893
    uint64_t lba;
894
    uint32_t len;
895
    int cmdlen;
896
    int is_write;
897
    uint8_t command;
898
    uint8_t *outbuf;
899
    SCSIDiskReq *r;
900
    int rc;
901

    
902
    command = buf[0];
903
    r = scsi_find_request(s, tag);
904
    if (r) {
905
        BADF("Tag 0x%x already in use\n", tag);
906
        scsi_cancel_io(d, tag);
907
    }
908
    /* ??? Tags are not unique for different luns.  We only implement a
909
       single lun, so this should not matter.  */
910
    r = scsi_new_request(d, tag, lun);
911
    outbuf = (uint8_t *)r->iov.iov_base;
912
    is_write = 0;
913
    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
914
    switch (command >> 5) {
915
    case 0:
916
        lba = (uint64_t) buf[3] | ((uint64_t) buf[2] << 8) |
917
              (((uint64_t) buf[1] & 0x1f) << 16);
918
        len = buf[4];
919
        cmdlen = 6;
920
        break;
921
    case 1:
922
    case 2:
923
        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
924
              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
925
        len = buf[8] | (buf[7] << 8);
926
        cmdlen = 10;
927
        break;
928
    case 4:
929
        lba = (uint64_t) buf[9] | ((uint64_t) buf[8] << 8) |
930
              ((uint64_t) buf[7] << 16) | ((uint64_t) buf[6] << 24) |
931
              ((uint64_t) buf[5] << 32) | ((uint64_t) buf[4] << 40) |
932
              ((uint64_t) buf[3] << 48) | ((uint64_t) buf[2] << 56);
933
        len = buf[13] | (buf[12] << 8) | (buf[11] << 16) | (buf[10] << 24);
934
        cmdlen = 16;
935
        break;
936
    case 5:
937
        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
938
              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
939
        len = buf[9] | (buf[8] << 8) | (buf[7] << 16) | (buf[6] << 24);
940
        cmdlen = 12;
941
        break;
942
    default:
943
        BADF("Unsupported command length, command %x\n", command);
944
        goto fail;
945
    }
946
#ifdef DEBUG_SCSI
947
    {
948
        int i;
949
        for (i = 1; i < cmdlen; i++) {
950
            printf(" 0x%02x", buf[i]);
951
        }
952
        printf("\n");
953
    }
954
#endif
955

    
956
    if (scsi_req_parse(&r->req, buf) != 0) {
957
        BADF("Unsupported command length, command %x\n", command);
958
        goto fail;
959
    }
960
    assert(r->req.cmd.len == cmdlen);
961
    assert(r->req.cmd.lba == lba);
962

    
963
    if (lun || buf[1] >> 5) {
964
        /* Only LUN 0 supported.  */
965
        DPRINTF("Unimplemented LUN %d\n", lun ? lun : buf[1] >> 5);
966
        if (command != REQUEST_SENSE && command != INQUIRY)
967
            goto fail;
968
    }
969
    switch (command) {
970
    case TEST_UNIT_READY:
971
    case REQUEST_SENSE:
972
    case INQUIRY:
973
    case MODE_SENSE:
974
    case MODE_SENSE_10:
975
    case RESERVE:
976
    case RESERVE_10:
977
    case RELEASE:
978
    case RELEASE_10:
979
    case START_STOP:
980
    case ALLOW_MEDIUM_REMOVAL:
981
    case READ_CAPACITY:
982
    case SYNCHRONIZE_CACHE:
983
    case READ_TOC:
984
    case GET_CONFIGURATION:
985
    case SERVICE_ACTION_IN:
986
    case REPORT_LUNS:
987
    case VERIFY:
988
        rc = scsi_disk_emulate_command(&r->req, outbuf);
989
        if (rc > 0) {
990
            r->iov.iov_len = rc;
991
        } else {
992
            scsi_req_complete(&r->req);
993
            scsi_remove_request(r);
994
            return 0;
995
        }
996
        break;
997
    case READ_6:
998
    case READ_10:
999
    case READ_12:
1000
    case READ_16:
1001
        DPRINTF("Read (sector %" PRId64 ", count %d)\n", lba, len);
1002
        if (lba > s->max_lba)
1003
            goto illegal_lba;
1004
        r->sector = lba * s->cluster_size;
1005
        r->sector_count = len * s->cluster_size;
1006
        break;
1007
    case WRITE_6:
1008
    case WRITE_10:
1009
    case WRITE_12:
1010
    case WRITE_16:
1011
        DPRINTF("Write (sector %" PRId64 ", count %d)\n", lba, len);
1012
        if (lba > s->max_lba)
1013
            goto illegal_lba;
1014
        r->sector = lba * s->cluster_size;
1015
        r->sector_count = len * s->cluster_size;
1016
        is_write = 1;
1017
        break;
1018
    default:
1019
        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1020
    fail:
1021
        scsi_command_complete(r, CHECK_CONDITION, ILLEGAL_REQUEST);
1022
        return 0;
1023
    illegal_lba:
1024
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
1025
        return 0;
1026
    }
1027
    if (r->sector_count == 0 && r->iov.iov_len == 0) {
1028
        scsi_command_complete(r, GOOD, NO_SENSE);
1029
    }
1030
    len = r->sector_count * 512 + r->iov.iov_len;
1031
    if (is_write) {
1032
        return -len;
1033
    } else {
1034
        if (!r->sector_count)
1035
            r->sector_count = -1;
1036
        return len;
1037
    }
1038
}
1039

    
1040
static void scsi_disk_purge_requests(SCSIDiskState *s)
1041
{
1042
    SCSIDiskReq *r;
1043

    
1044
    while (!QTAILQ_EMPTY(&s->qdev.requests)) {
1045
        r = DO_UPCAST(SCSIDiskReq, req, QTAILQ_FIRST(&s->qdev.requests));
1046
        if (r->req.aiocb) {
1047
            bdrv_aio_cancel(r->req.aiocb);
1048
        }
1049
        scsi_remove_request(r);
1050
    }
1051
}
1052

    
1053
static void scsi_disk_reset(DeviceState *dev)
1054
{
1055
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1056
    uint64_t nb_sectors;
1057

    
1058
    scsi_disk_purge_requests(s);
1059

    
1060
    bdrv_get_geometry(s->bs, &nb_sectors);
1061
    nb_sectors /= s->cluster_size;
1062
    if (nb_sectors) {
1063
        nb_sectors--;
1064
    }
1065
    s->max_lba = nb_sectors;
1066
}
1067

    
1068
static void scsi_destroy(SCSIDevice *dev)
1069
{
1070
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1071

    
1072
    scsi_disk_purge_requests(s);
1073
    blockdev_mark_auto_del(s->qdev.conf.bs);
1074
}
1075

    
1076
static int scsi_disk_initfn(SCSIDevice *dev)
1077
{
1078
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1079
    int is_cd;
1080
    DriveInfo *dinfo;
1081

    
1082
    if (!s->qdev.conf.bs) {
1083
        error_report("scsi-disk: drive property not set");
1084
        return -1;
1085
    }
1086
    s->bs = s->qdev.conf.bs;
1087
    is_cd = bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM;
1088

    
1089
    if (!is_cd && !bdrv_is_inserted(s->bs)) {
1090
        error_report("Device needs media, but drive is empty");
1091
        return -1;
1092
    }
1093

    
1094
    if (bdrv_get_on_error(s->bs, 1) != BLOCK_ERR_REPORT) {
1095
        error_report("Device doesn't support drive option rerror");
1096
        return -1;
1097
    }
1098

    
1099
    if (!s->serial) {
1100
        /* try to fall back to value set with legacy -drive serial=... */
1101
        dinfo = drive_get_by_blockdev(s->bs);
1102
        s->serial = qemu_strdup(*dinfo->serial ? dinfo->serial : "0");
1103
    }
1104

    
1105
    if (!s->version) {
1106
        s->version = qemu_strdup(QEMU_VERSION);
1107
    }
1108

    
1109
    if (bdrv_is_sg(s->bs)) {
1110
        error_report("scsi-disk: unwanted /dev/sg*");
1111
        return -1;
1112
    }
1113

    
1114
    if (is_cd) {
1115
        s->qdev.blocksize = 2048;
1116
    } else {
1117
        s->qdev.blocksize = s->qdev.conf.logical_block_size;
1118
    }
1119
    s->cluster_size = s->qdev.blocksize / 512;
1120

    
1121
    s->qdev.type = TYPE_DISK;
1122
    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
1123
    bdrv_set_removable(s->bs, is_cd);
1124
    return 0;
1125
}
1126

    
1127
static SCSIDeviceInfo scsi_disk_info = {
1128
    .qdev.name    = "scsi-disk",
1129
    .qdev.desc    = "virtual scsi disk or cdrom",
1130
    .qdev.size    = sizeof(SCSIDiskState),
1131
    .qdev.reset   = scsi_disk_reset,
1132
    .init         = scsi_disk_initfn,
1133
    .destroy      = scsi_destroy,
1134
    .send_command = scsi_send_command,
1135
    .read_data    = scsi_read_data,
1136
    .write_data   = scsi_write_data,
1137
    .cancel_io    = scsi_cancel_io,
1138
    .get_buf      = scsi_get_buf,
1139
    .qdev.props   = (Property[]) {
1140
        DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),
1141
        DEFINE_PROP_STRING("ver",  SCSIDiskState, version),
1142
        DEFINE_PROP_STRING("serial",  SCSIDiskState, serial),
1143
        DEFINE_PROP_END_OF_LIST(),
1144
    },
1145
};
1146

    
1147
static void scsi_disk_register_devices(void)
1148
{
1149
    scsi_qdev_register(&scsi_disk_info);
1150
}
1151
device_init(scsi_disk_register_devices)