Statistics
| Branch: | Revision:

root / hw / scsi-disk.c @ 380f640f

History | View | Annotate | Download (31.2 kB)

1
/*
2
 * SCSI Device emulation
3
 *
4
 * Copyright (c) 2006 CodeSourcery.
5
 * Based on code by Fabrice Bellard
6
 *
7
 * Written by Paul Brook
8
 * Modifications:
9
 *  2009-Dec-12 Artyom Tarasenko : implemented stamdard inquiry for the case
10
 *                                 when the allocation length of CDB is smaller
11
 *                                 than 36.
12
 *  2009-Oct-13 Artyom Tarasenko : implemented the block descriptor in the
13
 *                                 MODE SENSE response.
14
 *
15
 * This code is 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
#include <qemu-common.h>
23
#include <sysemu.h>
24
//#define DEBUG_SCSI
25

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

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

    
36
#include "qemu-common.h"
37
#include "block.h"
38
#include "scsi.h"
39
#include "scsi-defs.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
    /* The qemu block layer uses a fixed 512 byte sector size.
64
       This is the number of 512 byte blocks in a single scsi sector.  */
65
    int cluster_size;
66
    uint64_t max_lba;
67
    QEMUBH *bh;
68
    char *version;
69
};
70

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

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

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

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

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

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

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

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

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

    
136
    r->req.bus->complete(r->req.bus, SCSI_REASON_DATA, r->req.tag, r->iov.iov_len);
137
}
138

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

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

    
165
    n = r->sector_count;
166
    if (n > SCSI_DMA_BUF_SIZE / 512)
167
        n = SCSI_DMA_BUF_SIZE / 512;
168

    
169
    r->iov.iov_len = n * 512;
170
    qemu_iovec_init_external(&r->qiov, &r->iov, 1);
171
    r->req.aiocb = bdrv_aio_readv(s->qdev.dinfo->bdrv, r->sector, &r->qiov, n,
172
                              scsi_read_complete, r);
173
    if (r->req.aiocb == NULL)
174
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
175
    r->sector += n;
176
    r->sector_count -= n;
177
}
178

    
179
static int scsi_handle_write_error(SCSIDiskReq *r, int error)
180
{
181
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
182
    BlockInterfaceErrorAction action =
183
        drive_get_on_error(s->qdev.dinfo->bdrv, 0);
184

    
185
    if (action == BLOCK_ERR_IGNORE) {
186
        bdrv_mon_event(s->qdev.dinfo->bdrv, BDRV_ACTION_IGNORE, 0);
187
        return 0;
188
    }
189

    
190
    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
191
            || action == BLOCK_ERR_STOP_ANY) {
192
        r->status |= SCSI_REQ_STATUS_RETRY;
193
        vm_stop(0);
194
        bdrv_mon_event(s->qdev.dinfo->bdrv, BDRV_ACTION_STOP, 0);
195
    } else {
196
        scsi_command_complete(r, CHECK_CONDITION,
197
                HARDWARE_ERROR);
198
        bdrv_mon_event(s->qdev.dinfo->bdrv, BDRV_ACTION_REPORT, 0);
199
    }
200

    
201
    return 1;
202
}
203

    
204
static void scsi_write_complete(void * opaque, int ret)
205
{
206
    SCSIDiskReq *r = (SCSIDiskReq *)opaque;
207
    uint32_t len;
208
    uint32_t n;
209

    
210
    r->req.aiocb = NULL;
211

    
212
    if (ret) {
213
        if (scsi_handle_write_error(r, -ret))
214
            return;
215
    }
216

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

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

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

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

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

    
267
    if (r->req.aiocb)
268
        BADF("Data transfer already in progress\n");
269

    
270
    scsi_write_request(r);
271

    
272
    return 0;
273
}
274

    
275
static void scsi_dma_restart_bh(void *opaque)
276
{
277
    SCSIDiskState *s = opaque;
278
    SCSIRequest *req;
279
    SCSIDiskReq *r;
280

    
281
    qemu_bh_delete(s->bh);
282
    s->bh = NULL;
283

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

    
293
static void scsi_dma_restart_cb(void *opaque, int running, int reason)
294
{
295
    SCSIDiskState *s = opaque;
296

    
297
    if (!running)
298
        return;
299

    
300
    if (!s->bh) {
301
        s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
302
        qemu_bh_schedule(s->bh);
303
    }
304
}
305

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

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

    
320
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
321
{
322
    BlockDriverState *bdrv = req->dev->dinfo->bdrv;
323
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
324
    int buflen = 0;
325

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

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

    
341
        if (bdrv_get_type_hint(bdrv) == BDRV_TYPE_CDROM) {
342
            outbuf[buflen++] = 5;
343
        } else {
344
            outbuf[buflen++] = 0;
345
        }
346
        outbuf[buflen++] = page_code ; // this page
347
        outbuf[buflen++] = 0x00;
348

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

    
359
        case 0x80: /* Device serial number, optional */
360
        {
361
            const char *serial = req->dev->dinfo->serial ?
362
                req->dev->dinfo->serial : "0";
363
            int l = strlen(serial);
364

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

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

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

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

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

    
394
            memcpy(outbuf+buflen, bdrv_get_device_name(bdrv), id_len);
395
            buflen += id_len;
396
            break;
397
        }
398
        default:
399
            BADF("Error: unsupported Inquiry (EVPD[%02X]) "
400
                 "buffer size %zd\n", page_code, req->cmd.xfer);
401
            return -1;
402
        }
403
        /* done with EVPD */
404
        return buflen;
405
    }
406

    
407
    /* Standard INQUIRY data */
408
    if (req->cmd.buf[2] != 0) {
409
        BADF("Error: Inquiry (STANDARD) page or code "
410
             "is non-zero [%02X]\n", req->cmd.buf[2]);
411
        return -1;
412
    }
413

    
414
    /* PAGE CODE == 0 */
415
    if (req->cmd.xfer < 5) {
416
        BADF("Error: Inquiry (STANDARD) buffer size %zd "
417
             "is less than 5\n", req->cmd.xfer);
418
        return -1;
419
    }
420

    
421
    buflen = req->cmd.xfer;
422
    if (buflen > SCSI_MAX_INQUIRY_LEN)
423
        buflen = SCSI_MAX_INQUIRY_LEN;
424

    
425
    memset(outbuf, 0, buflen);
426

    
427
    if (req->lun || req->cmd.buf[1] >> 5) {
428
        outbuf[0] = 0x7f;        /* LUN not supported */
429
        return buflen;
430
    }
431

    
432
    if (bdrv_get_type_hint(bdrv) == BDRV_TYPE_CDROM) {
433
        outbuf[0] = 5;
434
        outbuf[1] = 0x80;
435
        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);
436
    } else {
437
        outbuf[0] = 0;
438
        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);
439
    }
440
    memcpy(&outbuf[8], "QEMU    ", 8);
441
    memcpy(&outbuf[32], s->version ? s->version : QEMU_VERSION, 4);
442
    /* Identify device as SCSI-3 rev 1.
443
       Some later commands are also implemented. */
444
    outbuf[2] = 3;
445
    outbuf[3] = 2; /* Format 2 */
446

    
447
    if (buflen > 36) {
448
        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
449
    } else {
450
        /* If the allocation length of CDB is too small,
451
               the additional length is not adjusted */
452
        outbuf[4] = 36 - 5;
453
    }
454

    
455
    /* Sync data transfer and TCQ.  */
456
    outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);
457
    return buflen;
458
}
459

    
460
static int mode_sense_page(SCSIRequest *req, int page, uint8_t *p)
461
{
462
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
463
    BlockDriverState *bdrv = req->dev->dinfo->bdrv;
464
    int cylinders, heads, secs;
465

    
466
    switch (page) {
467
    case 4: /* Rigid disk device geometry page. */
468
        p[0] = 4;
469
        p[1] = 0x16;
470
        /* if a geometry hint is available, use it */
471
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
472
        p[2] = (cylinders >> 16) & 0xff;
473
        p[3] = (cylinders >> 8) & 0xff;
474
        p[4] = cylinders & 0xff;
475
        p[5] = heads & 0xff;
476
        /* Write precomp start cylinder, disabled */
477
        p[6] = (cylinders >> 16) & 0xff;
478
        p[7] = (cylinders >> 8) & 0xff;
479
        p[8] = cylinders & 0xff;
480
        /* Reduced current start cylinder, disabled */
481
        p[9] = (cylinders >> 16) & 0xff;
482
        p[10] = (cylinders >> 8) & 0xff;
483
        p[11] = cylinders & 0xff;
484
        /* Device step rate [ns], 200ns */
485
        p[12] = 0;
486
        p[13] = 200;
487
        /* Landing zone cylinder */
488
        p[14] = 0xff;
489
        p[15] =  0xff;
490
        p[16] = 0xff;
491
        /* Medium rotation rate [rpm], 5400 rpm */
492
        p[20] = (5400 >> 8) & 0xff;
493
        p[21] = 5400 & 0xff;
494
        return 0x16;
495

    
496
    case 5: /* Flexible disk device geometry page. */
497
        p[0] = 5;
498
        p[1] = 0x1e;
499
        /* Transfer rate [kbit/s], 5Mbit/s */
500
        p[2] = 5000 >> 8;
501
        p[3] = 5000 & 0xff;
502
        /* if a geometry hint is available, use it */
503
        bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
504
        p[4] = heads & 0xff;
505
        p[5] = secs & 0xff;
506
        p[6] = s->cluster_size * 2;
507
        p[8] = (cylinders >> 8) & 0xff;
508
        p[9] = cylinders & 0xff;
509
        /* Write precomp start cylinder, disabled */
510
        p[10] = (cylinders >> 8) & 0xff;
511
        p[11] = cylinders & 0xff;
512
        /* Reduced current start cylinder, disabled */
513
        p[12] = (cylinders >> 8) & 0xff;
514
        p[13] = cylinders & 0xff;
515
        /* Device step rate [100us], 100us */
516
        p[14] = 0;
517
        p[15] = 1;
518
        /* Device step pulse width [us], 1us */
519
        p[16] = 1;
520
        /* Device head settle delay [100us], 100us */
521
        p[17] = 0;
522
        p[18] = 1;
523
        /* Motor on delay [0.1s], 0.1s */
524
        p[19] = 1;
525
        /* Motor off delay [0.1s], 0.1s */
526
        p[20] = 1;
527
        /* Medium rotation rate [rpm], 5400 rpm */
528
        p[28] = (5400 >> 8) & 0xff;
529
        p[29] = 5400 & 0xff;
530
        return 0x1e;
531

    
532
    case 8: /* Caching page.  */
533
        p[0] = 8;
534
        p[1] = 0x12;
535
        if (bdrv_enable_write_cache(s->qdev.dinfo->bdrv)) {
536
            p[2] = 4; /* WCE */
537
        }
538
        return 20;
539

    
540
    case 0x2a: /* CD Capabilities and Mechanical Status page. */
541
        if (bdrv_get_type_hint(bdrv) != BDRV_TYPE_CDROM)
542
            return 0;
543
        p[0] = 0x2a;
544
        p[1] = 0x14;
545
        p[2] = 3; // CD-R & CD-RW read
546
        p[3] = 0; // Writing not supported
547
        p[4] = 0x7f; /* Audio, composite, digital out,
548
                        mode 2 form 1&2, multi session */
549
        p[5] = 0xff; /* CD DA, DA accurate, RW supported,
550
                        RW corrected, C2 errors, ISRC,
551
                        UPC, Bar code */
552
        p[6] = 0x2d | (bdrv_is_locked(s->qdev.dinfo->bdrv)? 2 : 0);
553
        /* Locking supported, jumper present, eject, tray */
554
        p[7] = 0; /* no volume & mute control, no
555
                     changer */
556
        p[8] = (50 * 176) >> 8; // 50x read speed
557
        p[9] = (50 * 176) & 0xff;
558
        p[10] = 0 >> 8; // No volume
559
        p[11] = 0 & 0xff;
560
        p[12] = 2048 >> 8; // 2M buffer
561
        p[13] = 2048 & 0xff;
562
        p[14] = (16 * 176) >> 8; // 16x read speed current
563
        p[15] = (16 * 176) & 0xff;
564
        p[18] = (16 * 176) >> 8; // 16x write speed
565
        p[19] = (16 * 176) & 0xff;
566
        p[20] = (16 * 176) >> 8; // 16x write speed current
567
        p[21] = (16 * 176) & 0xff;
568
        return 22;
569

    
570
    default:
571
        return 0;
572
    }
573
}
574

    
575
static int scsi_disk_emulate_mode_sense(SCSIRequest *req, uint8_t *outbuf)
576
{
577
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
578
    BlockDriverState *bdrv = req->dev->dinfo->bdrv;
579
    uint64_t nb_sectors;
580
    int page, dbd, buflen;
581
    uint8_t *p;
582

    
583
    dbd = req->cmd.buf[1]  & 0x8;
584
    page = req->cmd.buf[2] & 0x3f;
585
    DPRINTF("Mode Sense (page %d, len %zd)\n", page, req->cmd.xfer);
586
    memset(outbuf, 0, req->cmd.xfer);
587
    p = outbuf;
588

    
589
    p[1] = 0; /* Default media type.  */
590
    p[3] = 0; /* Block descriptor length.  */
591
    if (bdrv_get_type_hint(bdrv) == BDRV_TYPE_CDROM ||
592
        bdrv_is_read_only(bdrv)) {
593
        p[2] = 0x80; /* Readonly.  */
594
    }
595
    p += 4;
596

    
597
    bdrv_get_geometry(bdrv, &nb_sectors);
598
    if ((~dbd) & nb_sectors) {
599
        outbuf[3] = 8; /* Block descriptor length  */
600
        nb_sectors /= s->cluster_size;
601
        nb_sectors--;
602
        if (nb_sectors > 0xffffff)
603
            nb_sectors = 0xffffff;
604
        p[0] = 0; /* media density code */
605
        p[1] = (nb_sectors >> 16) & 0xff;
606
        p[2] = (nb_sectors >> 8) & 0xff;
607
        p[3] = nb_sectors & 0xff;
608
        p[4] = 0; /* reserved */
609
        p[5] = 0; /* bytes 5-7 are the sector size in bytes */
610
        p[6] = s->cluster_size * 2;
611
        p[7] = 0;
612
        p += 8;
613
    }
614

    
615
    switch (page) {
616
    case 0x04:
617
    case 0x05:
618
    case 0x08:
619
    case 0x2a:
620
        p += mode_sense_page(req, page, p);
621
        break;
622
    case 0x3f:
623
        p += mode_sense_page(req, 0x08, p);
624
        p += mode_sense_page(req, 0x2a, p);
625
        break;
626
    }
627

    
628
    buflen = p - outbuf;
629
    outbuf[0] = buflen - 4;
630
    if (buflen > req->cmd.xfer)
631
        buflen = req->cmd.xfer;
632
    return buflen;
633
}
634

    
635
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
636
{
637
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
638
    BlockDriverState *bdrv = req->dev->dinfo->bdrv;
639
    int start_track, format, msf, toclen;
640
    uint64_t nb_sectors;
641

    
642
    msf = req->cmd.buf[1] & 2;
643
    format = req->cmd.buf[2] & 0xf;
644
    start_track = req->cmd.buf[6];
645
    bdrv_get_geometry(bdrv, &nb_sectors);
646
    DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
647
    nb_sectors /= s->cluster_size;
648
    switch (format) {
649
    case 0:
650
        toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
651
        break;
652
    case 1:
653
        /* multi session : only a single session defined */
654
        toclen = 12;
655
        memset(outbuf, 0, 12);
656
        outbuf[1] = 0x0a;
657
        outbuf[2] = 0x01;
658
        outbuf[3] = 0x01;
659
        break;
660
    case 2:
661
        toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
662
        break;
663
    default:
664
        return -1;
665
    }
666
    if (toclen > req->cmd.xfer)
667
        toclen = req->cmd.xfer;
668
    return toclen;
669
}
670

    
671
static int scsi_disk_emulate_command(SCSIRequest *req, uint8_t *outbuf)
672
{
673
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
674
    BlockDriverState *bdrv = req->dev->dinfo->bdrv;
675
    uint64_t nb_sectors;
676
    int buflen = 0;
677

    
678
    switch (req->cmd.buf[0]) {
679
    case TEST_UNIT_READY:
680
        if (!bdrv_is_inserted(bdrv))
681
            goto not_ready;
682
        break;
683
    case REQUEST_SENSE:
684
        if (req->cmd.xfer < 4)
685
            goto illegal_request;
686
        memset(outbuf, 0, 4);
687
        buflen = 4;
688
        if (req->dev->sense.key == NOT_READY && req->cmd.xfer >= 18) {
689
            memset(outbuf, 0, 18);
690
            buflen = 18;
691
            outbuf[7] = 10;
692
            /* asc 0x3a, ascq 0: Medium not present */
693
            outbuf[12] = 0x3a;
694
            outbuf[13] = 0;
695
        }
696
        outbuf[0] = 0xf0;
697
        outbuf[1] = 0;
698
        outbuf[2] = req->dev->sense.key;
699
        scsi_dev_clear_sense(req->dev);
700
        break;
701
    case INQUIRY:
702
        buflen = scsi_disk_emulate_inquiry(req, outbuf);
703
        if (buflen < 0)
704
            goto illegal_request;
705
        break;
706
    case MODE_SENSE:
707
    case MODE_SENSE_10:
708
        buflen = scsi_disk_emulate_mode_sense(req, outbuf);
709
        if (buflen < 0)
710
            goto illegal_request;
711
        break;
712
    case READ_TOC:
713
        buflen = scsi_disk_emulate_read_toc(req, outbuf);
714
        if (buflen < 0)
715
            goto illegal_request;
716
        break;
717
    case RESERVE:
718
        if (req->cmd.buf[1] & 1)
719
            goto illegal_request;
720
        break;
721
    case RESERVE_10:
722
        if (req->cmd.buf[1] & 3)
723
            goto illegal_request;
724
        break;
725
    case RELEASE:
726
        if (req->cmd.buf[1] & 1)
727
            goto illegal_request;
728
        break;
729
    case RELEASE_10:
730
        if (req->cmd.buf[1] & 3)
731
            goto illegal_request;
732
        break;
733
    case START_STOP:
734
        if (bdrv_get_type_hint(bdrv) == BDRV_TYPE_CDROM && (req->cmd.buf[4] & 2)) {
735
            /* load/eject medium */
736
            bdrv_eject(bdrv, !(req->cmd.buf[4] & 1));
737
        }
738
        break;
739
    case ALLOW_MEDIUM_REMOVAL:
740
        bdrv_set_locked(bdrv, req->cmd.buf[4] & 1);
741
        break;
742
    case READ_CAPACITY:
743
        /* The normal LEN field for this command is zero.  */
744
        memset(outbuf, 0, 8);
745
        bdrv_get_geometry(bdrv, &nb_sectors);
746
        if (!nb_sectors)
747
            goto not_ready;
748
        nb_sectors /= s->cluster_size;
749
        /* Returned value is the address of the last sector.  */
750
        nb_sectors--;
751
        /* Remember the new size for read/write sanity checking. */
752
        s->max_lba = nb_sectors;
753
        /* Clip to 2TB, instead of returning capacity modulo 2TB. */
754
        if (nb_sectors > UINT32_MAX)
755
            nb_sectors = UINT32_MAX;
756
        outbuf[0] = (nb_sectors >> 24) & 0xff;
757
        outbuf[1] = (nb_sectors >> 16) & 0xff;
758
        outbuf[2] = (nb_sectors >> 8) & 0xff;
759
        outbuf[3] = nb_sectors & 0xff;
760
        outbuf[4] = 0;
761
        outbuf[5] = 0;
762
        outbuf[6] = s->cluster_size * 2;
763
        outbuf[7] = 0;
764
        buflen = 8;
765
        break;
766
    case SYNCHRONIZE_CACHE:
767
        bdrv_flush(bdrv);
768
        break;
769
    case GET_CONFIGURATION:
770
        memset(outbuf, 0, 8);
771
        /* ??? This should probably return much more information.  For now
772
           just return the basic header indicating the CD-ROM profile.  */
773
        outbuf[7] = 8; // CD-ROM
774
        buflen = 8;
775
        break;
776
    case SERVICE_ACTION_IN:
777
        /* Service Action In subcommands. */
778
        if ((req->cmd.buf[1] & 31) == 0x10) {
779
            DPRINTF("SAI READ CAPACITY(16)\n");
780
            memset(outbuf, 0, req->cmd.xfer);
781
            bdrv_get_geometry(bdrv, &nb_sectors);
782
            if (!nb_sectors)
783
                goto not_ready;
784
            nb_sectors /= s->cluster_size;
785
            /* Returned value is the address of the last sector.  */
786
            nb_sectors--;
787
            /* Remember the new size for read/write sanity checking. */
788
            s->max_lba = nb_sectors;
789
            outbuf[0] = (nb_sectors >> 56) & 0xff;
790
            outbuf[1] = (nb_sectors >> 48) & 0xff;
791
            outbuf[2] = (nb_sectors >> 40) & 0xff;
792
            outbuf[3] = (nb_sectors >> 32) & 0xff;
793
            outbuf[4] = (nb_sectors >> 24) & 0xff;
794
            outbuf[5] = (nb_sectors >> 16) & 0xff;
795
            outbuf[6] = (nb_sectors >> 8) & 0xff;
796
            outbuf[7] = nb_sectors & 0xff;
797
            outbuf[8] = 0;
798
            outbuf[9] = 0;
799
            outbuf[10] = s->cluster_size * 2;
800
            outbuf[11] = 0;
801
            /* Protection, exponent and lowest lba field left blank. */
802
            buflen = req->cmd.xfer;
803
            break;
804
        }
805
        DPRINTF("Unsupported Service Action In\n");
806
        goto illegal_request;
807
    case REPORT_LUNS:
808
        if (req->cmd.xfer < 16)
809
            goto illegal_request;
810
        memset(outbuf, 0, 16);
811
        outbuf[3] = 8;
812
        buflen = 16;
813
        break;
814
    case VERIFY:
815
        break;
816
    default:
817
        goto illegal_request;
818
    }
819
    scsi_req_set_status(req, GOOD, NO_SENSE);
820
    return buflen;
821

    
822
not_ready:
823
    scsi_req_set_status(req, CHECK_CONDITION, NOT_READY);
824
    return 0;
825

    
826
illegal_request:
827
    scsi_req_set_status(req, CHECK_CONDITION, ILLEGAL_REQUEST);
828
    return 0;
829
}
830

    
831
/* Execute a scsi command.  Returns the length of the data expected by the
832
   command.  This will be Positive for data transfers from the device
833
   (eg. disk reads), negative for transfers to the device (eg. disk writes),
834
   and zero if the command does not transfer any data.  */
835

    
836
static int32_t scsi_send_command(SCSIDevice *d, uint32_t tag,
837
                                 uint8_t *buf, int lun)
838
{
839
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
840
    uint64_t lba;
841
    uint32_t len;
842
    int cmdlen;
843
    int is_write;
844
    uint8_t command;
845
    uint8_t *outbuf;
846
    SCSIDiskReq *r;
847
    int rc;
848

    
849
    command = buf[0];
850
    r = scsi_find_request(s, tag);
851
    if (r) {
852
        BADF("Tag 0x%x already in use\n", tag);
853
        scsi_cancel_io(d, tag);
854
    }
855
    /* ??? Tags are not unique for different luns.  We only implement a
856
       single lun, so this should not matter.  */
857
    r = scsi_new_request(d, tag, lun);
858
    outbuf = (uint8_t *)r->iov.iov_base;
859
    is_write = 0;
860
    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
861
    switch (command >> 5) {
862
    case 0:
863
        lba = (uint64_t) buf[3] | ((uint64_t) buf[2] << 8) |
864
              (((uint64_t) buf[1] & 0x1f) << 16);
865
        len = buf[4];
866
        cmdlen = 6;
867
        break;
868
    case 1:
869
    case 2:
870
        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
871
              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
872
        len = buf[8] | (buf[7] << 8);
873
        cmdlen = 10;
874
        break;
875
    case 4:
876
        lba = (uint64_t) buf[9] | ((uint64_t) buf[8] << 8) |
877
              ((uint64_t) buf[7] << 16) | ((uint64_t) buf[6] << 24) |
878
              ((uint64_t) buf[5] << 32) | ((uint64_t) buf[4] << 40) |
879
              ((uint64_t) buf[3] << 48) | ((uint64_t) buf[2] << 56);
880
        len = buf[13] | (buf[12] << 8) | (buf[11] << 16) | (buf[10] << 24);
881
        cmdlen = 16;
882
        break;
883
    case 5:
884
        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
885
              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
886
        len = buf[9] | (buf[8] << 8) | (buf[7] << 16) | (buf[6] << 24);
887
        cmdlen = 12;
888
        break;
889
    default:
890
        BADF("Unsupported command length, command %x\n", command);
891
        goto fail;
892
    }
893
#ifdef DEBUG_SCSI
894
    {
895
        int i;
896
        for (i = 1; i < cmdlen; i++) {
897
            printf(" 0x%02x", buf[i]);
898
        }
899
        printf("\n");
900
    }
901
#endif
902

    
903
    if (scsi_req_parse(&r->req, buf) != 0) {
904
        BADF("Unsupported command length, command %x\n", command);
905
        goto fail;
906
    }
907
    assert(r->req.cmd.len == cmdlen);
908
    assert(r->req.cmd.lba == lba);
909

    
910
    if (lun || buf[1] >> 5) {
911
        /* Only LUN 0 supported.  */
912
        DPRINTF("Unimplemented LUN %d\n", lun ? lun : buf[1] >> 5);
913
        if (command != REQUEST_SENSE && command != INQUIRY)
914
            goto fail;
915
    }
916
    switch (command) {
917
    case TEST_UNIT_READY:
918
    case REQUEST_SENSE:
919
    case INQUIRY:
920
    case MODE_SENSE:
921
    case MODE_SENSE_10:
922
    case RESERVE:
923
    case RESERVE_10:
924
    case RELEASE:
925
    case RELEASE_10:
926
    case START_STOP:
927
    case ALLOW_MEDIUM_REMOVAL:
928
    case READ_CAPACITY:
929
    case SYNCHRONIZE_CACHE:
930
    case READ_TOC:
931
    case GET_CONFIGURATION:
932
    case SERVICE_ACTION_IN:
933
    case REPORT_LUNS:
934
    case VERIFY:
935
        rc = scsi_disk_emulate_command(&r->req, outbuf);
936
        if (rc > 0) {
937
            r->iov.iov_len = rc;
938
        } else {
939
            scsi_req_complete(&r->req);
940
            scsi_remove_request(r);
941
            return 0;
942
        }
943
        break;
944
    case READ_6:
945
    case READ_10:
946
    case READ_12:
947
    case READ_16:
948
        DPRINTF("Read (sector %" PRId64 ", count %d)\n", lba, len);
949
        if (lba > s->max_lba)
950
            goto illegal_lba;
951
        r->sector = lba * s->cluster_size;
952
        r->sector_count = len * s->cluster_size;
953
        break;
954
    case WRITE_6:
955
    case WRITE_10:
956
    case WRITE_12:
957
    case WRITE_16:
958
        DPRINTF("Write (sector %" PRId64 ", count %d)\n", lba, len);
959
        if (lba > s->max_lba)
960
            goto illegal_lba;
961
        r->sector = lba * s->cluster_size;
962
        r->sector_count = len * s->cluster_size;
963
        is_write = 1;
964
        break;
965
    default:
966
        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
967
    fail:
968
        scsi_command_complete(r, CHECK_CONDITION, ILLEGAL_REQUEST);
969
        return 0;
970
    illegal_lba:
971
        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);
972
        return 0;
973
    }
974
    if (r->sector_count == 0 && r->iov.iov_len == 0) {
975
        scsi_command_complete(r, GOOD, NO_SENSE);
976
    }
977
    len = r->sector_count * 512 + r->iov.iov_len;
978
    if (is_write) {
979
        return -len;
980
    } else {
981
        if (!r->sector_count)
982
            r->sector_count = -1;
983
        return len;
984
    }
985
}
986

    
987
static void scsi_destroy(SCSIDevice *dev)
988
{
989
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
990
    SCSIDiskReq *r;
991

    
992
    while (!QTAILQ_EMPTY(&s->qdev.requests)) {
993
        r = DO_UPCAST(SCSIDiskReq, req, QTAILQ_FIRST(&s->qdev.requests));
994
        scsi_remove_request(r);
995
    }
996
    drive_uninit(s->qdev.dinfo);
997
}
998

    
999
static int scsi_disk_initfn(SCSIDevice *dev)
1000
{
1001
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1002
    uint64_t nb_sectors;
1003

    
1004
    if (!s->qdev.dinfo || !s->qdev.dinfo->bdrv) {
1005
        qemu_error("scsi-disk: drive property not set\n");
1006
        return -1;
1007
    }
1008

    
1009
    if (bdrv_get_type_hint(s->qdev.dinfo->bdrv) == BDRV_TYPE_CDROM) {
1010
        s->cluster_size = 4;
1011
    } else {
1012
        s->cluster_size = 1;
1013
    }
1014
    s->qdev.blocksize = 512 * s->cluster_size;
1015
    s->qdev.type = TYPE_DISK;
1016
    bdrv_get_geometry(s->qdev.dinfo->bdrv, &nb_sectors);
1017
    nb_sectors /= s->cluster_size;
1018
    if (nb_sectors)
1019
        nb_sectors--;
1020
    s->max_lba = nb_sectors;
1021
    qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
1022
    return 0;
1023
}
1024

    
1025
static SCSIDeviceInfo scsi_disk_info = {
1026
    .qdev.name    = "scsi-disk",
1027
    .qdev.desc    = "virtual scsi disk or cdrom",
1028
    .qdev.size    = sizeof(SCSIDiskState),
1029
    .init         = scsi_disk_initfn,
1030
    .destroy      = scsi_destroy,
1031
    .send_command = scsi_send_command,
1032
    .read_data    = scsi_read_data,
1033
    .write_data   = scsi_write_data,
1034
    .cancel_io    = scsi_cancel_io,
1035
    .get_buf      = scsi_get_buf,
1036
    .qdev.props   = (Property[]) {
1037
        DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.dinfo),
1038
        DEFINE_PROP_STRING("ver",  SCSIDiskState, version),
1039
        DEFINE_PROP_END_OF_LIST(),
1040
    },
1041
};
1042

    
1043
static void scsi_disk_register_devices(void)
1044
{
1045
    scsi_qdev_register(&scsi_disk_info);
1046
}
1047
device_init(scsi_disk_register_devices)