iostatus: reorganize io error code
[qemu/ar7.git] / hw / scsi-disk.c
blob99bb02ebf88d223aac070e589b04efabf20a8e9b
1 /*
2 * SCSI Device emulation
4 * Copyright (c) 2006 CodeSourcery.
5 * Based on code by Fabrice Bellard
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.
15 * This code is licensed under the LGPL.
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.
22 //#define DEBUG_SCSI
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
31 #include "qemu-common.h"
32 #include "qemu-error.h"
33 #include "scsi.h"
34 #include "scsi-defs.h"
35 #include "sysemu.h"
36 #include "blockdev.h"
37 #include "hw/block-common.h"
38 #include "dma.h"
40 #ifdef __linux
41 #include <scsi/sg.h>
42 #endif
44 #define SCSI_DMA_BUF_SIZE 131072
45 #define SCSI_MAX_INQUIRY_LEN 256
46 #define SCSI_MAX_MODE_LEN 256
48 typedef struct SCSIDiskState SCSIDiskState;
50 typedef struct SCSIDiskReq {
51 SCSIRequest req;
52 /* Both sector and sector_count are in terms of qemu 512 byte blocks. */
53 uint64_t sector;
54 uint32_t sector_count;
55 uint32_t buflen;
56 bool started;
57 struct iovec iov;
58 QEMUIOVector qiov;
59 BlockAcctCookie acct;
60 } SCSIDiskReq;
62 #define SCSI_DISK_F_REMOVABLE 0
63 #define SCSI_DISK_F_DPOFUA 1
65 struct SCSIDiskState
67 SCSIDevice qdev;
68 uint32_t features;
69 bool media_changed;
70 bool media_event;
71 bool eject_request;
72 uint64_t wwn;
73 QEMUBH *bh;
74 char *version;
75 char *serial;
76 char *vendor;
77 char *product;
78 bool tray_open;
79 bool tray_locked;
82 static int scsi_handle_rw_error(SCSIDiskReq *r, int error);
84 static void scsi_free_request(SCSIRequest *req)
86 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
88 if (r->iov.iov_base) {
89 qemu_vfree(r->iov.iov_base);
93 /* Helper function for command completion with sense. */
94 static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense)
96 DPRINTF("Command complete tag=0x%x sense=%d/%d/%d\n",
97 r->req.tag, sense.key, sense.asc, sense.ascq);
98 scsi_req_build_sense(&r->req, sense);
99 scsi_req_complete(&r->req, CHECK_CONDITION);
102 /* Cancel a pending data transfer. */
103 static void scsi_cancel_io(SCSIRequest *req)
105 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
107 DPRINTF("Cancel tag=0x%x\n", req->tag);
108 if (r->req.aiocb) {
109 bdrv_aio_cancel(r->req.aiocb);
111 /* This reference was left in by scsi_*_data. We take ownership of
112 * it the moment scsi_req_cancel is called, independent of whether
113 * bdrv_aio_cancel completes the request or not. */
114 scsi_req_unref(&r->req);
116 r->req.aiocb = NULL;
119 static uint32_t scsi_init_iovec(SCSIDiskReq *r, size_t size)
121 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
123 if (!r->iov.iov_base) {
124 r->buflen = size;
125 r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
127 r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);
128 qemu_iovec_init_external(&r->qiov, &r->iov, 1);
129 return r->qiov.size / 512;
132 static void scsi_disk_save_request(QEMUFile *f, SCSIRequest *req)
134 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
136 qemu_put_be64s(f, &r->sector);
137 qemu_put_be32s(f, &r->sector_count);
138 qemu_put_be32s(f, &r->buflen);
139 if (r->buflen) {
140 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
141 qemu_put_buffer(f, r->iov.iov_base, r->iov.iov_len);
142 } else if (!req->retry) {
143 uint32_t len = r->iov.iov_len;
144 qemu_put_be32s(f, &len);
145 qemu_put_buffer(f, r->iov.iov_base, r->iov.iov_len);
150 static void scsi_disk_load_request(QEMUFile *f, SCSIRequest *req)
152 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
154 qemu_get_be64s(f, &r->sector);
155 qemu_get_be32s(f, &r->sector_count);
156 qemu_get_be32s(f, &r->buflen);
157 if (r->buflen) {
158 scsi_init_iovec(r, r->buflen);
159 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
160 qemu_get_buffer(f, r->iov.iov_base, r->iov.iov_len);
161 } else if (!r->req.retry) {
162 uint32_t len;
163 qemu_get_be32s(f, &len);
164 r->iov.iov_len = len;
165 assert(r->iov.iov_len <= r->buflen);
166 qemu_get_buffer(f, r->iov.iov_base, r->iov.iov_len);
170 qemu_iovec_init_external(&r->qiov, &r->iov, 1);
173 static void scsi_aio_complete(void *opaque, int ret)
175 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
176 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
178 assert(r->req.aiocb != NULL);
179 r->req.aiocb = NULL;
180 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
182 if (ret < 0) {
183 if (scsi_handle_rw_error(r, -ret)) {
184 goto done;
188 scsi_req_complete(&r->req, GOOD);
190 done:
191 if (!r->req.io_canceled) {
192 scsi_req_unref(&r->req);
196 static bool scsi_is_cmd_fua(SCSICommand *cmd)
198 switch (cmd->buf[0]) {
199 case READ_10:
200 case READ_12:
201 case READ_16:
202 case WRITE_10:
203 case WRITE_12:
204 case WRITE_16:
205 return (cmd->buf[1] & 8) != 0;
207 case VERIFY_10:
208 case VERIFY_12:
209 case VERIFY_16:
210 case WRITE_VERIFY_10:
211 case WRITE_VERIFY_12:
212 case WRITE_VERIFY_16:
213 return true;
215 case READ_6:
216 case WRITE_6:
217 default:
218 return false;
222 static void scsi_write_do_fua(SCSIDiskReq *r)
224 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
226 if (scsi_is_cmd_fua(&r->req.cmd)) {
227 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
228 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
229 return;
232 scsi_req_complete(&r->req, GOOD);
233 if (!r->req.io_canceled) {
234 scsi_req_unref(&r->req);
238 static void scsi_dma_complete(void *opaque, int ret)
240 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
241 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
243 assert(r->req.aiocb != NULL);
244 r->req.aiocb = NULL;
245 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
247 if (ret < 0) {
248 if (scsi_handle_rw_error(r, -ret)) {
249 goto done;
253 r->sector += r->sector_count;
254 r->sector_count = 0;
255 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
256 scsi_write_do_fua(r);
257 return;
258 } else {
259 scsi_req_complete(&r->req, GOOD);
262 done:
263 if (!r->req.io_canceled) {
264 scsi_req_unref(&r->req);
268 static void scsi_read_complete(void * opaque, int ret)
270 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
271 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
272 int n;
274 assert(r->req.aiocb != NULL);
275 r->req.aiocb = NULL;
276 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
278 if (ret < 0) {
279 if (scsi_handle_rw_error(r, -ret)) {
280 goto done;
284 DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
286 n = r->qiov.size / 512;
287 r->sector += n;
288 r->sector_count -= n;
289 scsi_req_data(&r->req, r->qiov.size);
291 done:
292 if (!r->req.io_canceled) {
293 scsi_req_unref(&r->req);
297 /* Actually issue a read to the block device. */
298 static void scsi_do_read(void *opaque, int ret)
300 SCSIDiskReq *r = opaque;
301 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
302 uint32_t n;
304 if (r->req.aiocb != NULL) {
305 r->req.aiocb = NULL;
306 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
309 if (ret < 0) {
310 if (scsi_handle_rw_error(r, -ret)) {
311 goto done;
315 if (r->req.io_canceled) {
316 return;
319 /* The request is used as the AIO opaque value, so add a ref. */
320 scsi_req_ref(&r->req);
322 if (r->req.sg) {
323 dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ);
324 r->req.resid -= r->req.sg->size;
325 r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector,
326 scsi_dma_complete, r);
327 } else {
328 n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
329 bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
330 r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n,
331 scsi_read_complete, r);
334 done:
335 if (!r->req.io_canceled) {
336 scsi_req_unref(&r->req);
340 /* Read more data from scsi device into buffer. */
341 static void scsi_read_data(SCSIRequest *req)
343 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
344 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
345 bool first;
347 DPRINTF("Read sector_count=%d\n", r->sector_count);
348 if (r->sector_count == 0) {
349 /* This also clears the sense buffer for REQUEST SENSE. */
350 scsi_req_complete(&r->req, GOOD);
351 return;
354 /* No data transfer may already be in progress */
355 assert(r->req.aiocb == NULL);
357 /* The request is used as the AIO opaque value, so add a ref. */
358 scsi_req_ref(&r->req);
359 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
360 DPRINTF("Data transfer direction invalid\n");
361 scsi_read_complete(r, -EINVAL);
362 return;
365 if (s->tray_open) {
366 scsi_read_complete(r, -ENOMEDIUM);
367 return;
370 first = !r->started;
371 r->started = true;
372 if (first && scsi_is_cmd_fua(&r->req.cmd)) {
373 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
374 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_do_read, r);
375 } else {
376 scsi_do_read(r, 0);
381 * scsi_handle_rw_error has two return values. 0 means that the error
382 * must be ignored, 1 means that the error has been processed and the
383 * caller should not do anything else for this request. Note that
384 * scsi_handle_rw_error always manages its reference counts, independent
385 * of the return value.
387 static int scsi_handle_rw_error(SCSIDiskReq *r, int error)
389 bool is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV);
390 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
391 BlockErrorAction action = bdrv_get_error_action(s->qdev.conf.bs, is_read, error);
393 if (action == BDRV_ACTION_REPORT) {
394 switch (error) {
395 case ENOMEDIUM:
396 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
397 break;
398 case ENOMEM:
399 scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
400 break;
401 case EINVAL:
402 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
403 break;
404 default:
405 scsi_check_condition(r, SENSE_CODE(IO_ERROR));
406 break;
409 bdrv_error_action(s->qdev.conf.bs, action, is_read, error);
410 if (action == BDRV_ACTION_STOP) {
411 scsi_req_retry(&r->req);
413 return action != BDRV_ACTION_IGNORE;
416 static void scsi_write_complete(void * opaque, int ret)
418 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
419 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
420 uint32_t n;
422 if (r->req.aiocb != NULL) {
423 r->req.aiocb = NULL;
424 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
427 if (ret < 0) {
428 if (scsi_handle_rw_error(r, -ret)) {
429 goto done;
433 n = r->qiov.size / 512;
434 r->sector += n;
435 r->sector_count -= n;
436 if (r->sector_count == 0) {
437 scsi_write_do_fua(r);
438 return;
439 } else {
440 scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
441 DPRINTF("Write complete tag=0x%x more=%zd\n", r->req.tag, r->qiov.size);
442 scsi_req_data(&r->req, r->qiov.size);
445 done:
446 if (!r->req.io_canceled) {
447 scsi_req_unref(&r->req);
451 static void scsi_write_data(SCSIRequest *req)
453 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
454 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
455 uint32_t n;
457 /* No data transfer may already be in progress */
458 assert(r->req.aiocb == NULL);
460 /* The request is used as the AIO opaque value, so add a ref. */
461 scsi_req_ref(&r->req);
462 if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
463 DPRINTF("Data transfer direction invalid\n");
464 scsi_write_complete(r, -EINVAL);
465 return;
468 if (!r->req.sg && !r->qiov.size) {
469 /* Called for the first time. Ask the driver to send us more data. */
470 r->started = true;
471 scsi_write_complete(r, 0);
472 return;
474 if (s->tray_open) {
475 scsi_write_complete(r, -ENOMEDIUM);
476 return;
479 if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
480 r->req.cmd.buf[0] == VERIFY_16) {
481 if (r->req.sg) {
482 scsi_dma_complete(r, 0);
483 } else {
484 scsi_write_complete(r, 0);
486 return;
489 if (r->req.sg) {
490 dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_WRITE);
491 r->req.resid -= r->req.sg->size;
492 r->req.aiocb = dma_bdrv_write(s->qdev.conf.bs, r->req.sg, r->sector,
493 scsi_dma_complete, r);
494 } else {
495 n = r->qiov.size / 512;
496 bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
497 r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, r->sector, &r->qiov, n,
498 scsi_write_complete, r);
502 /* Return a pointer to the data buffer. */
503 static uint8_t *scsi_get_buf(SCSIRequest *req)
505 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
507 return (uint8_t *)r->iov.iov_base;
510 static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
512 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
513 int buflen = 0;
514 int start;
516 if (req->cmd.buf[1] & 0x1) {
517 /* Vital product data */
518 uint8_t page_code = req->cmd.buf[2];
520 outbuf[buflen++] = s->qdev.type & 0x1f;
521 outbuf[buflen++] = page_code ; // this page
522 outbuf[buflen++] = 0x00;
523 outbuf[buflen++] = 0x00;
524 start = buflen;
526 switch (page_code) {
527 case 0x00: /* Supported page codes, mandatory */
529 DPRINTF("Inquiry EVPD[Supported pages] "
530 "buffer size %zd\n", req->cmd.xfer);
531 outbuf[buflen++] = 0x00; // list of supported pages (this page)
532 if (s->serial) {
533 outbuf[buflen++] = 0x80; // unit serial number
535 outbuf[buflen++] = 0x83; // device identification
536 if (s->qdev.type == TYPE_DISK) {
537 outbuf[buflen++] = 0xb0; // block limits
538 outbuf[buflen++] = 0xb2; // thin provisioning
540 break;
542 case 0x80: /* Device serial number, optional */
544 int l;
546 if (!s->serial) {
547 DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
548 return -1;
551 l = strlen(s->serial);
552 if (l > 20) {
553 l = 20;
556 DPRINTF("Inquiry EVPD[Serial number] "
557 "buffer size %zd\n", req->cmd.xfer);
558 memcpy(outbuf+buflen, s->serial, l);
559 buflen += l;
560 break;
563 case 0x83: /* Device identification page, mandatory */
565 const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs);
566 int max_len = s->serial ? 20 : 255 - 8;
567 int id_len = strlen(str);
569 if (id_len > max_len) {
570 id_len = max_len;
572 DPRINTF("Inquiry EVPD[Device identification] "
573 "buffer size %zd\n", req->cmd.xfer);
575 outbuf[buflen++] = 0x2; // ASCII
576 outbuf[buflen++] = 0; // not officially assigned
577 outbuf[buflen++] = 0; // reserved
578 outbuf[buflen++] = id_len; // length of data following
579 memcpy(outbuf+buflen, str, id_len);
580 buflen += id_len;
582 if (s->wwn) {
583 outbuf[buflen++] = 0x1; // Binary
584 outbuf[buflen++] = 0x3; // NAA
585 outbuf[buflen++] = 0; // reserved
586 outbuf[buflen++] = 8;
587 stq_be_p(&outbuf[buflen], s->wwn);
588 buflen += 8;
590 break;
592 case 0xb0: /* block limits */
594 unsigned int unmap_sectors =
595 s->qdev.conf.discard_granularity / s->qdev.blocksize;
596 unsigned int min_io_size =
597 s->qdev.conf.min_io_size / s->qdev.blocksize;
598 unsigned int opt_io_size =
599 s->qdev.conf.opt_io_size / s->qdev.blocksize;
601 if (s->qdev.type == TYPE_ROM) {
602 DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
603 page_code);
604 return -1;
606 /* required VPD size with unmap support */
607 buflen = 0x40;
608 memset(outbuf + 4, 0, buflen - 4);
610 /* optimal transfer length granularity */
611 outbuf[6] = (min_io_size >> 8) & 0xff;
612 outbuf[7] = min_io_size & 0xff;
614 /* optimal transfer length */
615 outbuf[12] = (opt_io_size >> 24) & 0xff;
616 outbuf[13] = (opt_io_size >> 16) & 0xff;
617 outbuf[14] = (opt_io_size >> 8) & 0xff;
618 outbuf[15] = opt_io_size & 0xff;
620 /* optimal unmap granularity */
621 outbuf[28] = (unmap_sectors >> 24) & 0xff;
622 outbuf[29] = (unmap_sectors >> 16) & 0xff;
623 outbuf[30] = (unmap_sectors >> 8) & 0xff;
624 outbuf[31] = unmap_sectors & 0xff;
625 break;
627 case 0xb2: /* thin provisioning */
629 buflen = 8;
630 outbuf[4] = 0;
631 outbuf[5] = 0xe0; /* unmap & write_same 10/16 all supported */
632 outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
633 outbuf[7] = 0;
634 break;
636 default:
637 return -1;
639 /* done with EVPD */
640 assert(buflen - start <= 255);
641 outbuf[start - 1] = buflen - start;
642 return buflen;
645 /* Standard INQUIRY data */
646 if (req->cmd.buf[2] != 0) {
647 return -1;
650 /* PAGE CODE == 0 */
651 buflen = req->cmd.xfer;
652 if (buflen > SCSI_MAX_INQUIRY_LEN) {
653 buflen = SCSI_MAX_INQUIRY_LEN;
655 memset(outbuf, 0, buflen);
657 outbuf[0] = s->qdev.type & 0x1f;
658 outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;
660 strpadcpy((char *) &outbuf[16], 16, s->product, ' ');
661 strpadcpy((char *) &outbuf[8], 8, s->vendor, ' ');
663 memset(&outbuf[32], 0, 4);
664 memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
666 * We claim conformance to SPC-3, which is required for guests
667 * to ask for modern features like READ CAPACITY(16) or the
668 * block characteristics VPD page by default. Not all of SPC-3
669 * is actually implemented, but we're good enough.
671 outbuf[2] = 5;
672 outbuf[3] = 2 | 0x10; /* Format 2, HiSup */
674 if (buflen > 36) {
675 outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
676 } else {
677 /* If the allocation length of CDB is too small,
678 the additional length is not adjusted */
679 outbuf[4] = 36 - 5;
682 /* Sync data transfer and TCQ. */
683 outbuf[7] = 0x10 | (req->bus->info->tcq ? 0x02 : 0);
684 return buflen;
687 static inline bool media_is_dvd(SCSIDiskState *s)
689 uint64_t nb_sectors;
690 if (s->qdev.type != TYPE_ROM) {
691 return false;
693 if (!bdrv_is_inserted(s->qdev.conf.bs)) {
694 return false;
696 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
697 return nb_sectors > CD_MAX_SECTORS;
700 static inline bool media_is_cd(SCSIDiskState *s)
702 uint64_t nb_sectors;
703 if (s->qdev.type != TYPE_ROM) {
704 return false;
706 if (!bdrv_is_inserted(s->qdev.conf.bs)) {
707 return false;
709 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
710 return nb_sectors <= CD_MAX_SECTORS;
713 static int scsi_read_disc_information(SCSIDiskState *s, SCSIDiskReq *r,
714 uint8_t *outbuf)
716 uint8_t type = r->req.cmd.buf[1] & 7;
718 if (s->qdev.type != TYPE_ROM) {
719 return -1;
722 /* Types 1/2 are only defined for Blu-Ray. */
723 if (type != 0) {
724 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
725 return -1;
728 memset(outbuf, 0, 34);
729 outbuf[1] = 32;
730 outbuf[2] = 0xe; /* last session complete, disc finalized */
731 outbuf[3] = 1; /* first track on disc */
732 outbuf[4] = 1; /* # of sessions */
733 outbuf[5] = 1; /* first track of last session */
734 outbuf[6] = 1; /* last track of last session */
735 outbuf[7] = 0x20; /* unrestricted use */
736 outbuf[8] = 0x00; /* CD-ROM or DVD-ROM */
737 /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
738 /* 12-23: not meaningful for CD-ROM or DVD-ROM */
739 /* 24-31: disc bar code */
740 /* 32: disc application code */
741 /* 33: number of OPC tables */
743 return 34;
746 static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
747 uint8_t *outbuf)
749 static const int rds_caps_size[5] = {
750 [0] = 2048 + 4,
751 [1] = 4 + 4,
752 [3] = 188 + 4,
753 [4] = 2048 + 4,
756 uint8_t media = r->req.cmd.buf[1];
757 uint8_t layer = r->req.cmd.buf[6];
758 uint8_t format = r->req.cmd.buf[7];
759 int size = -1;
761 if (s->qdev.type != TYPE_ROM) {
762 return -1;
764 if (media != 0) {
765 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
766 return -1;
769 if (format != 0xff) {
770 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
771 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
772 return -1;
774 if (media_is_cd(s)) {
775 scsi_check_condition(r, SENSE_CODE(INCOMPATIBLE_FORMAT));
776 return -1;
778 if (format >= ARRAY_SIZE(rds_caps_size)) {
779 return -1;
781 size = rds_caps_size[format];
782 memset(outbuf, 0, size);
785 switch (format) {
786 case 0x00: {
787 /* Physical format information */
788 uint64_t nb_sectors;
789 if (layer != 0) {
790 goto fail;
792 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
794 outbuf[4] = 1; /* DVD-ROM, part version 1 */
795 outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
796 outbuf[6] = 1; /* one layer, read-only (per MMC-2 spec) */
797 outbuf[7] = 0; /* default densities */
799 stl_be_p(&outbuf[12], (nb_sectors >> 2) - 1); /* end sector */
800 stl_be_p(&outbuf[16], (nb_sectors >> 2) - 1); /* l0 end sector */
801 break;
804 case 0x01: /* DVD copyright information, all zeros */
805 break;
807 case 0x03: /* BCA information - invalid field for no BCA info */
808 return -1;
810 case 0x04: /* DVD disc manufacturing information, all zeros */
811 break;
813 case 0xff: { /* List capabilities */
814 int i;
815 size = 4;
816 for (i = 0; i < ARRAY_SIZE(rds_caps_size); i++) {
817 if (!rds_caps_size[i]) {
818 continue;
820 outbuf[size] = i;
821 outbuf[size + 1] = 0x40; /* Not writable, readable */
822 stw_be_p(&outbuf[size + 2], rds_caps_size[i]);
823 size += 4;
825 break;
828 default:
829 return -1;
832 /* Size of buffer, not including 2 byte size field */
833 stw_be_p(outbuf, size - 2);
834 return size;
836 fail:
837 return -1;
840 static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf)
842 uint8_t event_code, media_status;
844 media_status = 0;
845 if (s->tray_open) {
846 media_status = MS_TRAY_OPEN;
847 } else if (bdrv_is_inserted(s->qdev.conf.bs)) {
848 media_status = MS_MEDIA_PRESENT;
851 /* Event notification descriptor */
852 event_code = MEC_NO_CHANGE;
853 if (media_status != MS_TRAY_OPEN) {
854 if (s->media_event) {
855 event_code = MEC_NEW_MEDIA;
856 s->media_event = false;
857 } else if (s->eject_request) {
858 event_code = MEC_EJECT_REQUESTED;
859 s->eject_request = false;
863 outbuf[0] = event_code;
864 outbuf[1] = media_status;
866 /* These fields are reserved, just clear them. */
867 outbuf[2] = 0;
868 outbuf[3] = 0;
869 return 4;
872 static int scsi_get_event_status_notification(SCSIDiskState *s, SCSIDiskReq *r,
873 uint8_t *outbuf)
875 int size;
876 uint8_t *buf = r->req.cmd.buf;
877 uint8_t notification_class_request = buf[4];
878 if (s->qdev.type != TYPE_ROM) {
879 return -1;
881 if ((buf[1] & 1) == 0) {
882 /* asynchronous */
883 return -1;
886 size = 4;
887 outbuf[0] = outbuf[1] = 0;
888 outbuf[3] = 1 << GESN_MEDIA; /* supported events */
889 if (notification_class_request & (1 << GESN_MEDIA)) {
890 outbuf[2] = GESN_MEDIA;
891 size += scsi_event_status_media(s, &outbuf[size]);
892 } else {
893 outbuf[2] = 0x80;
895 stw_be_p(outbuf, size - 4);
896 return size;
899 static int scsi_get_configuration(SCSIDiskState *s, uint8_t *outbuf)
901 int current;
903 if (s->qdev.type != TYPE_ROM) {
904 return -1;
906 current = media_is_dvd(s) ? MMC_PROFILE_DVD_ROM : MMC_PROFILE_CD_ROM;
907 memset(outbuf, 0, 40);
908 stl_be_p(&outbuf[0], 36); /* Bytes after the data length field */
909 stw_be_p(&outbuf[6], current);
910 /* outbuf[8] - outbuf[19]: Feature 0 - Profile list */
911 outbuf[10] = 0x03; /* persistent, current */
912 outbuf[11] = 8; /* two profiles */
913 stw_be_p(&outbuf[12], MMC_PROFILE_DVD_ROM);
914 outbuf[14] = (current == MMC_PROFILE_DVD_ROM);
915 stw_be_p(&outbuf[16], MMC_PROFILE_CD_ROM);
916 outbuf[18] = (current == MMC_PROFILE_CD_ROM);
917 /* outbuf[20] - outbuf[31]: Feature 1 - Core feature */
918 stw_be_p(&outbuf[20], 1);
919 outbuf[22] = 0x08 | 0x03; /* version 2, persistent, current */
920 outbuf[23] = 8;
921 stl_be_p(&outbuf[24], 1); /* SCSI */
922 outbuf[28] = 1; /* DBE = 1, mandatory */
923 /* outbuf[32] - outbuf[39]: Feature 3 - Removable media feature */
924 stw_be_p(&outbuf[32], 3);
925 outbuf[34] = 0x08 | 0x03; /* version 2, persistent, current */
926 outbuf[35] = 4;
927 outbuf[36] = 0x39; /* tray, load=1, eject=1, unlocked at powerup, lock=1 */
928 /* TODO: Random readable, CD read, DVD read, drive serial number,
929 power management */
930 return 40;
933 static int scsi_emulate_mechanism_status(SCSIDiskState *s, uint8_t *outbuf)
935 if (s->qdev.type != TYPE_ROM) {
936 return -1;
938 memset(outbuf, 0, 8);
939 outbuf[5] = 1; /* CD-ROM */
940 return 8;
943 static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
944 int page_control)
946 static const int mode_sense_valid[0x3f] = {
947 [MODE_PAGE_HD_GEOMETRY] = (1 << TYPE_DISK),
948 [MODE_PAGE_FLEXIBLE_DISK_GEOMETRY] = (1 << TYPE_DISK),
949 [MODE_PAGE_CACHING] = (1 << TYPE_DISK) | (1 << TYPE_ROM),
950 [MODE_PAGE_R_W_ERROR] = (1 << TYPE_DISK) | (1 << TYPE_ROM),
951 [MODE_PAGE_AUDIO_CTL] = (1 << TYPE_ROM),
952 [MODE_PAGE_CAPABILITIES] = (1 << TYPE_ROM),
955 uint8_t *p = *p_outbuf + 2;
956 int length;
958 if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
959 return -1;
963 * If Changeable Values are requested, a mask denoting those mode parameters
964 * that are changeable shall be returned. As we currently don't support
965 * parameter changes via MODE_SELECT all bits are returned set to zero.
966 * The buffer was already menset to zero by the caller of this function.
968 * The offsets here are off by two compared to the descriptions in the
969 * SCSI specs, because those include a 2-byte header. This is unfortunate,
970 * but it is done so that offsets are consistent within our implementation
971 * of MODE SENSE and MODE SELECT. MODE SELECT has to deal with both
972 * 2-byte and 4-byte headers.
974 switch (page) {
975 case MODE_PAGE_HD_GEOMETRY:
976 length = 0x16;
977 if (page_control == 1) { /* Changeable Values */
978 break;
980 /* if a geometry hint is available, use it */
981 p[0] = (s->qdev.conf.cyls >> 16) & 0xff;
982 p[1] = (s->qdev.conf.cyls >> 8) & 0xff;
983 p[2] = s->qdev.conf.cyls & 0xff;
984 p[3] = s->qdev.conf.heads & 0xff;
985 /* Write precomp start cylinder, disabled */
986 p[4] = (s->qdev.conf.cyls >> 16) & 0xff;
987 p[5] = (s->qdev.conf.cyls >> 8) & 0xff;
988 p[6] = s->qdev.conf.cyls & 0xff;
989 /* Reduced current start cylinder, disabled */
990 p[7] = (s->qdev.conf.cyls >> 16) & 0xff;
991 p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
992 p[9] = s->qdev.conf.cyls & 0xff;
993 /* Device step rate [ns], 200ns */
994 p[10] = 0;
995 p[11] = 200;
996 /* Landing zone cylinder */
997 p[12] = 0xff;
998 p[13] = 0xff;
999 p[14] = 0xff;
1000 /* Medium rotation rate [rpm], 5400 rpm */
1001 p[18] = (5400 >> 8) & 0xff;
1002 p[19] = 5400 & 0xff;
1003 break;
1005 case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
1006 length = 0x1e;
1007 if (page_control == 1) { /* Changeable Values */
1008 break;
1010 /* Transfer rate [kbit/s], 5Mbit/s */
1011 p[0] = 5000 >> 8;
1012 p[1] = 5000 & 0xff;
1013 /* if a geometry hint is available, use it */
1014 p[2] = s->qdev.conf.heads & 0xff;
1015 p[3] = s->qdev.conf.secs & 0xff;
1016 p[4] = s->qdev.blocksize >> 8;
1017 p[6] = (s->qdev.conf.cyls >> 8) & 0xff;
1018 p[7] = s->qdev.conf.cyls & 0xff;
1019 /* Write precomp start cylinder, disabled */
1020 p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
1021 p[9] = s->qdev.conf.cyls & 0xff;
1022 /* Reduced current start cylinder, disabled */
1023 p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
1024 p[11] = s->qdev.conf.cyls & 0xff;
1025 /* Device step rate [100us], 100us */
1026 p[12] = 0;
1027 p[13] = 1;
1028 /* Device step pulse width [us], 1us */
1029 p[14] = 1;
1030 /* Device head settle delay [100us], 100us */
1031 p[15] = 0;
1032 p[16] = 1;
1033 /* Motor on delay [0.1s], 0.1s */
1034 p[17] = 1;
1035 /* Motor off delay [0.1s], 0.1s */
1036 p[18] = 1;
1037 /* Medium rotation rate [rpm], 5400 rpm */
1038 p[26] = (5400 >> 8) & 0xff;
1039 p[27] = 5400 & 0xff;
1040 break;
1042 case MODE_PAGE_CACHING:
1043 length = 0x12;
1044 if (page_control == 1 || /* Changeable Values */
1045 bdrv_enable_write_cache(s->qdev.conf.bs)) {
1046 p[0] = 4; /* WCE */
1048 break;
1050 case MODE_PAGE_R_W_ERROR:
1051 length = 10;
1052 if (page_control == 1) { /* Changeable Values */
1053 break;
1055 p[0] = 0x80; /* Automatic Write Reallocation Enabled */
1056 if (s->qdev.type == TYPE_ROM) {
1057 p[1] = 0x20; /* Read Retry Count */
1059 break;
1061 case MODE_PAGE_AUDIO_CTL:
1062 length = 14;
1063 break;
1065 case MODE_PAGE_CAPABILITIES:
1066 length = 0x14;
1067 if (page_control == 1) { /* Changeable Values */
1068 break;
1071 p[0] = 0x3b; /* CD-R & CD-RW read */
1072 p[1] = 0; /* Writing not supported */
1073 p[2] = 0x7f; /* Audio, composite, digital out,
1074 mode 2 form 1&2, multi session */
1075 p[3] = 0xff; /* CD DA, DA accurate, RW supported,
1076 RW corrected, C2 errors, ISRC,
1077 UPC, Bar code */
1078 p[4] = 0x2d | (s->tray_locked ? 2 : 0);
1079 /* Locking supported, jumper present, eject, tray */
1080 p[5] = 0; /* no volume & mute control, no
1081 changer */
1082 p[6] = (50 * 176) >> 8; /* 50x read speed */
1083 p[7] = (50 * 176) & 0xff;
1084 p[8] = 2 >> 8; /* Two volume levels */
1085 p[9] = 2 & 0xff;
1086 p[10] = 2048 >> 8; /* 2M buffer */
1087 p[11] = 2048 & 0xff;
1088 p[12] = (16 * 176) >> 8; /* 16x read speed current */
1089 p[13] = (16 * 176) & 0xff;
1090 p[16] = (16 * 176) >> 8; /* 16x write speed */
1091 p[17] = (16 * 176) & 0xff;
1092 p[18] = (16 * 176) >> 8; /* 16x write speed current */
1093 p[19] = (16 * 176) & 0xff;
1094 break;
1096 default:
1097 return -1;
1100 assert(length < 256);
1101 (*p_outbuf)[0] = page;
1102 (*p_outbuf)[1] = length;
1103 *p_outbuf += length + 2;
1104 return length + 2;
1107 static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
1109 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1110 uint64_t nb_sectors;
1111 bool dbd;
1112 int page, buflen, ret, page_control;
1113 uint8_t *p;
1114 uint8_t dev_specific_param;
1116 dbd = (r->req.cmd.buf[1] & 0x8) != 0;
1117 page = r->req.cmd.buf[2] & 0x3f;
1118 page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
1119 DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
1120 (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
1121 memset(outbuf, 0, r->req.cmd.xfer);
1122 p = outbuf;
1124 if (s->qdev.type == TYPE_DISK) {
1125 dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0;
1126 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1127 dev_specific_param |= 0x80; /* Readonly. */
1129 } else {
1130 /* MMC prescribes that CD/DVD drives have no block descriptors,
1131 * and defines no device-specific parameter. */
1132 dev_specific_param = 0x00;
1133 dbd = true;
1136 if (r->req.cmd.buf[0] == MODE_SENSE) {
1137 p[1] = 0; /* Default media type. */
1138 p[2] = dev_specific_param;
1139 p[3] = 0; /* Block descriptor length. */
1140 p += 4;
1141 } else { /* MODE_SENSE_10 */
1142 p[2] = 0; /* Default media type. */
1143 p[3] = dev_specific_param;
1144 p[6] = p[7] = 0; /* Block descriptor length. */
1145 p += 8;
1148 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1149 if (!dbd && nb_sectors) {
1150 if (r->req.cmd.buf[0] == MODE_SENSE) {
1151 outbuf[3] = 8; /* Block descriptor length */
1152 } else { /* MODE_SENSE_10 */
1153 outbuf[7] = 8; /* Block descriptor length */
1155 nb_sectors /= (s->qdev.blocksize / 512);
1156 if (nb_sectors > 0xffffff) {
1157 nb_sectors = 0;
1159 p[0] = 0; /* media density code */
1160 p[1] = (nb_sectors >> 16) & 0xff;
1161 p[2] = (nb_sectors >> 8) & 0xff;
1162 p[3] = nb_sectors & 0xff;
1163 p[4] = 0; /* reserved */
1164 p[5] = 0; /* bytes 5-7 are the sector size in bytes */
1165 p[6] = s->qdev.blocksize >> 8;
1166 p[7] = 0;
1167 p += 8;
1170 if (page_control == 3) {
1171 /* Saved Values */
1172 scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
1173 return -1;
1176 if (page == 0x3f) {
1177 for (page = 0; page <= 0x3e; page++) {
1178 mode_sense_page(s, page, &p, page_control);
1180 } else {
1181 ret = mode_sense_page(s, page, &p, page_control);
1182 if (ret == -1) {
1183 return -1;
1187 buflen = p - outbuf;
1189 * The mode data length field specifies the length in bytes of the
1190 * following data that is available to be transferred. The mode data
1191 * length does not include itself.
1193 if (r->req.cmd.buf[0] == MODE_SENSE) {
1194 outbuf[0] = buflen - 1;
1195 } else { /* MODE_SENSE_10 */
1196 outbuf[0] = ((buflen - 2) >> 8) & 0xff;
1197 outbuf[1] = (buflen - 2) & 0xff;
1199 return buflen;
1202 static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
1204 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1205 int start_track, format, msf, toclen;
1206 uint64_t nb_sectors;
1208 msf = req->cmd.buf[1] & 2;
1209 format = req->cmd.buf[2] & 0xf;
1210 start_track = req->cmd.buf[6];
1211 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1212 DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
1213 nb_sectors /= s->qdev.blocksize / 512;
1214 switch (format) {
1215 case 0:
1216 toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
1217 break;
1218 case 1:
1219 /* multi session : only a single session defined */
1220 toclen = 12;
1221 memset(outbuf, 0, 12);
1222 outbuf[1] = 0x0a;
1223 outbuf[2] = 0x01;
1224 outbuf[3] = 0x01;
1225 break;
1226 case 2:
1227 toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
1228 break;
1229 default:
1230 return -1;
1232 return toclen;
1235 static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
1237 SCSIRequest *req = &r->req;
1238 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1239 bool start = req->cmd.buf[4] & 1;
1240 bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
1241 int pwrcnd = req->cmd.buf[4] & 0xf0;
1243 if (pwrcnd) {
1244 /* eject/load only happens for power condition == 0 */
1245 return 0;
1248 if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) {
1249 if (!start && !s->tray_open && s->tray_locked) {
1250 scsi_check_condition(r,
1251 bdrv_is_inserted(s->qdev.conf.bs)
1252 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
1253 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
1254 return -1;
1257 if (s->tray_open != !start) {
1258 bdrv_eject(s->qdev.conf.bs, !start);
1259 s->tray_open = !start;
1262 return 0;
1265 static void scsi_disk_emulate_read_data(SCSIRequest *req)
1267 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1268 int buflen = r->iov.iov_len;
1270 if (buflen) {
1271 DPRINTF("Read buf_len=%d\n", buflen);
1272 r->iov.iov_len = 0;
1273 r->started = true;
1274 scsi_req_data(&r->req, buflen);
1275 return;
1278 /* This also clears the sense buffer for REQUEST SENSE. */
1279 scsi_req_complete(&r->req, GOOD);
1282 static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,
1283 uint8_t *inbuf, int inlen)
1285 uint8_t mode_current[SCSI_MAX_MODE_LEN];
1286 uint8_t mode_changeable[SCSI_MAX_MODE_LEN];
1287 uint8_t *p;
1288 int len, expected_len, changeable_len, i;
1290 /* The input buffer does not include the page header, so it is
1291 * off by 2 bytes.
1293 expected_len = inlen + 2;
1294 if (expected_len > SCSI_MAX_MODE_LEN) {
1295 return -1;
1298 p = mode_current;
1299 memset(mode_current, 0, inlen + 2);
1300 len = mode_sense_page(s, page, &p, 0);
1301 if (len < 0 || len != expected_len) {
1302 return -1;
1305 p = mode_changeable;
1306 memset(mode_changeable, 0, inlen + 2);
1307 changeable_len = mode_sense_page(s, page, &p, 1);
1308 assert(changeable_len == len);
1310 /* Check that unchangeable bits are the same as what MODE SENSE
1311 * would return.
1313 for (i = 2; i < len; i++) {
1314 if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) {
1315 return -1;
1318 return 0;
1321 static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)
1323 switch (page) {
1324 case MODE_PAGE_CACHING:
1325 bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0);
1326 break;
1328 default:
1329 break;
1333 static int mode_select_pages(SCSIDiskReq *r, uint8_t *p, int len, bool change)
1335 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1337 while (len > 0) {
1338 int page, subpage, page_len;
1340 /* Parse both possible formats for the mode page headers. */
1341 page = p[0] & 0x3f;
1342 if (p[0] & 0x40) {
1343 if (len < 4) {
1344 goto invalid_param_len;
1346 subpage = p[1];
1347 page_len = lduw_be_p(&p[2]);
1348 p += 4;
1349 len -= 4;
1350 } else {
1351 if (len < 2) {
1352 goto invalid_param_len;
1354 subpage = 0;
1355 page_len = p[1];
1356 p += 2;
1357 len -= 2;
1360 if (subpage) {
1361 goto invalid_param;
1363 if (page_len > len) {
1364 goto invalid_param_len;
1367 if (!change) {
1368 if (scsi_disk_check_mode_select(s, page, p, page_len) < 0) {
1369 goto invalid_param;
1371 } else {
1372 scsi_disk_apply_mode_select(s, page, p);
1375 p += page_len;
1376 len -= page_len;
1378 return 0;
1380 invalid_param:
1381 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1382 return -1;
1384 invalid_param_len:
1385 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1386 return -1;
1389 static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
1391 uint8_t *p = inbuf;
1392 int cmd = r->req.cmd.buf[0];
1393 int len = r->req.cmd.xfer;
1394 int hdr_len = (cmd == MODE_SELECT ? 4 : 8);
1395 int bd_len;
1396 int pass;
1398 /* We only support PF=1, SP=0. */
1399 if ((r->req.cmd.buf[1] & 0x11) != 0x10) {
1400 goto invalid_field;
1403 if (len < hdr_len) {
1404 goto invalid_param_len;
1407 bd_len = (cmd == MODE_SELECT ? p[3] : lduw_be_p(&p[6]));
1408 len -= hdr_len;
1409 p += hdr_len;
1410 if (len < bd_len) {
1411 goto invalid_param_len;
1413 if (bd_len != 0 && bd_len != 8) {
1414 goto invalid_param;
1417 len -= bd_len;
1418 p += bd_len;
1420 /* Ensure no change is made if there is an error! */
1421 for (pass = 0; pass < 2; pass++) {
1422 if (mode_select_pages(r, p, len, pass == 1) < 0) {
1423 assert(pass == 0);
1424 return;
1427 scsi_req_complete(&r->req, GOOD);
1428 return;
1430 invalid_param:
1431 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1432 return;
1434 invalid_param_len:
1435 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1436 return;
1438 invalid_field:
1439 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1440 return;
1443 static inline bool check_lba_range(SCSIDiskState *s,
1444 uint64_t sector_num, uint32_t nb_sectors)
1447 * The first line tests that no overflow happens when computing the last
1448 * sector. The second line tests that the last accessed sector is in
1449 * range.
1451 * Careful, the computations should not underflow for nb_sectors == 0,
1452 * and a 0-block read to the first LBA beyond the end of device is
1453 * valid.
1455 return (sector_num <= sector_num + nb_sectors &&
1456 sector_num + nb_sectors <= s->qdev.max_lba + 1);
1459 typedef struct UnmapCBData {
1460 SCSIDiskReq *r;
1461 uint8_t *inbuf;
1462 int count;
1463 } UnmapCBData;
1465 static void scsi_unmap_complete(void *opaque, int ret)
1467 UnmapCBData *data = opaque;
1468 SCSIDiskReq *r = data->r;
1469 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1470 uint64_t sector_num;
1471 uint32_t nb_sectors;
1473 r->req.aiocb = NULL;
1474 if (ret < 0) {
1475 if (scsi_handle_rw_error(r, -ret)) {
1476 goto done;
1480 if (data->count > 0 && !r->req.io_canceled) {
1481 sector_num = ldq_be_p(&data->inbuf[0]);
1482 nb_sectors = ldl_be_p(&data->inbuf[8]) & 0xffffffffULL;
1483 if (!check_lba_range(s, sector_num, nb_sectors)) {
1484 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1485 goto done;
1488 r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1489 sector_num * (s->qdev.blocksize / 512),
1490 nb_sectors * (s->qdev.blocksize / 512),
1491 scsi_unmap_complete, data);
1492 data->count--;
1493 data->inbuf += 16;
1494 return;
1497 done:
1498 if (data->count == 0) {
1499 scsi_req_complete(&r->req, GOOD);
1501 if (!r->req.io_canceled) {
1502 scsi_req_unref(&r->req);
1504 g_free(data);
1507 static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf)
1509 uint8_t *p = inbuf;
1510 int len = r->req.cmd.xfer;
1511 UnmapCBData *data;
1513 if (len < 8) {
1514 goto invalid_param_len;
1516 if (len < lduw_be_p(&p[0]) + 2) {
1517 goto invalid_param_len;
1519 if (len < lduw_be_p(&p[2]) + 8) {
1520 goto invalid_param_len;
1522 if (lduw_be_p(&p[2]) & 15) {
1523 goto invalid_param_len;
1526 data = g_new0(UnmapCBData, 1);
1527 data->r = r;
1528 data->inbuf = &p[8];
1529 data->count = lduw_be_p(&p[2]) >> 4;
1531 /* The matching unref is in scsi_unmap_complete, before data is freed. */
1532 scsi_req_ref(&r->req);
1533 scsi_unmap_complete(data, 0);
1534 return;
1536 invalid_param_len:
1537 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1538 return;
1541 static void scsi_disk_emulate_write_data(SCSIRequest *req)
1543 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1545 if (r->iov.iov_len) {
1546 int buflen = r->iov.iov_len;
1547 DPRINTF("Write buf_len=%d\n", buflen);
1548 r->iov.iov_len = 0;
1549 scsi_req_data(&r->req, buflen);
1550 return;
1553 switch (req->cmd.buf[0]) {
1554 case MODE_SELECT:
1555 case MODE_SELECT_10:
1556 /* This also clears the sense buffer for REQUEST SENSE. */
1557 scsi_disk_emulate_mode_select(r, r->iov.iov_base);
1558 break;
1560 case UNMAP:
1561 scsi_disk_emulate_unmap(r, r->iov.iov_base);
1562 break;
1564 default:
1565 abort();
1569 static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
1571 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1572 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1573 uint64_t nb_sectors;
1574 uint8_t *outbuf;
1575 int buflen;
1577 switch (req->cmd.buf[0]) {
1578 case INQUIRY:
1579 case MODE_SENSE:
1580 case MODE_SENSE_10:
1581 case RESERVE:
1582 case RESERVE_10:
1583 case RELEASE:
1584 case RELEASE_10:
1585 case START_STOP:
1586 case ALLOW_MEDIUM_REMOVAL:
1587 case GET_CONFIGURATION:
1588 case GET_EVENT_STATUS_NOTIFICATION:
1589 case MECHANISM_STATUS:
1590 case REQUEST_SENSE:
1591 break;
1593 default:
1594 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1595 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1596 return 0;
1598 break;
1601 if (!r->iov.iov_base) {
1603 * FIXME: we shouldn't return anything bigger than 4k, but the code
1604 * requires the buffer to be as big as req->cmd.xfer in several
1605 * places. So, do not allow CDBs with a very large ALLOCATION
1606 * LENGTH. The real fix would be to modify scsi_read_data and
1607 * dma_buf_read, so that they return data beyond the buflen
1608 * as all zeros.
1610 if (req->cmd.xfer > 65536) {
1611 goto illegal_request;
1613 r->buflen = MAX(4096, req->cmd.xfer);
1614 r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
1617 buflen = req->cmd.xfer;
1618 outbuf = r->iov.iov_base;
1619 switch (req->cmd.buf[0]) {
1620 case TEST_UNIT_READY:
1621 assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));
1622 break;
1623 case INQUIRY:
1624 buflen = scsi_disk_emulate_inquiry(req, outbuf);
1625 if (buflen < 0) {
1626 goto illegal_request;
1628 break;
1629 case MODE_SENSE:
1630 case MODE_SENSE_10:
1631 buflen = scsi_disk_emulate_mode_sense(r, outbuf);
1632 if (buflen < 0) {
1633 goto illegal_request;
1635 break;
1636 case READ_TOC:
1637 buflen = scsi_disk_emulate_read_toc(req, outbuf);
1638 if (buflen < 0) {
1639 goto illegal_request;
1641 break;
1642 case RESERVE:
1643 if (req->cmd.buf[1] & 1) {
1644 goto illegal_request;
1646 break;
1647 case RESERVE_10:
1648 if (req->cmd.buf[1] & 3) {
1649 goto illegal_request;
1651 break;
1652 case RELEASE:
1653 if (req->cmd.buf[1] & 1) {
1654 goto illegal_request;
1656 break;
1657 case RELEASE_10:
1658 if (req->cmd.buf[1] & 3) {
1659 goto illegal_request;
1661 break;
1662 case START_STOP:
1663 if (scsi_disk_emulate_start_stop(r) < 0) {
1664 return 0;
1666 break;
1667 case ALLOW_MEDIUM_REMOVAL:
1668 s->tray_locked = req->cmd.buf[4] & 1;
1669 bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);
1670 break;
1671 case READ_CAPACITY_10:
1672 /* The normal LEN field for this command is zero. */
1673 memset(outbuf, 0, 8);
1674 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1675 if (!nb_sectors) {
1676 scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1677 return -1;
1679 if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {
1680 goto illegal_request;
1682 nb_sectors /= s->qdev.blocksize / 512;
1683 /* Returned value is the address of the last sector. */
1684 nb_sectors--;
1685 /* Remember the new size for read/write sanity checking. */
1686 s->qdev.max_lba = nb_sectors;
1687 /* Clip to 2TB, instead of returning capacity modulo 2TB. */
1688 if (nb_sectors > UINT32_MAX) {
1689 nb_sectors = UINT32_MAX;
1691 outbuf[0] = (nb_sectors >> 24) & 0xff;
1692 outbuf[1] = (nb_sectors >> 16) & 0xff;
1693 outbuf[2] = (nb_sectors >> 8) & 0xff;
1694 outbuf[3] = nb_sectors & 0xff;
1695 outbuf[4] = 0;
1696 outbuf[5] = 0;
1697 outbuf[6] = s->qdev.blocksize >> 8;
1698 outbuf[7] = 0;
1699 buflen = 8;
1700 break;
1701 case REQUEST_SENSE:
1702 /* Just return "NO SENSE". */
1703 buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,
1704 (req->cmd.buf[1] & 1) == 0);
1705 break;
1706 case MECHANISM_STATUS:
1707 buflen = scsi_emulate_mechanism_status(s, outbuf);
1708 if (buflen < 0) {
1709 goto illegal_request;
1711 break;
1712 case GET_CONFIGURATION:
1713 buflen = scsi_get_configuration(s, outbuf);
1714 if (buflen < 0) {
1715 goto illegal_request;
1717 break;
1718 case GET_EVENT_STATUS_NOTIFICATION:
1719 buflen = scsi_get_event_status_notification(s, r, outbuf);
1720 if (buflen < 0) {
1721 goto illegal_request;
1723 break;
1724 case READ_DISC_INFORMATION:
1725 buflen = scsi_read_disc_information(s, r, outbuf);
1726 if (buflen < 0) {
1727 goto illegal_request;
1729 break;
1730 case READ_DVD_STRUCTURE:
1731 buflen = scsi_read_dvd_structure(s, r, outbuf);
1732 if (buflen < 0) {
1733 goto illegal_request;
1735 break;
1736 case SERVICE_ACTION_IN_16:
1737 /* Service Action In subcommands. */
1738 if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
1739 DPRINTF("SAI READ CAPACITY(16)\n");
1740 memset(outbuf, 0, req->cmd.xfer);
1741 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1742 if (!nb_sectors) {
1743 scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1744 return -1;
1746 if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {
1747 goto illegal_request;
1749 nb_sectors /= s->qdev.blocksize / 512;
1750 /* Returned value is the address of the last sector. */
1751 nb_sectors--;
1752 /* Remember the new size for read/write sanity checking. */
1753 s->qdev.max_lba = nb_sectors;
1754 outbuf[0] = (nb_sectors >> 56) & 0xff;
1755 outbuf[1] = (nb_sectors >> 48) & 0xff;
1756 outbuf[2] = (nb_sectors >> 40) & 0xff;
1757 outbuf[3] = (nb_sectors >> 32) & 0xff;
1758 outbuf[4] = (nb_sectors >> 24) & 0xff;
1759 outbuf[5] = (nb_sectors >> 16) & 0xff;
1760 outbuf[6] = (nb_sectors >> 8) & 0xff;
1761 outbuf[7] = nb_sectors & 0xff;
1762 outbuf[8] = 0;
1763 outbuf[9] = 0;
1764 outbuf[10] = s->qdev.blocksize >> 8;
1765 outbuf[11] = 0;
1766 outbuf[12] = 0;
1767 outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1769 /* set TPE bit if the format supports discard */
1770 if (s->qdev.conf.discard_granularity) {
1771 outbuf[14] = 0x80;
1774 /* Protection, exponent and lowest lba field left blank. */
1775 buflen = req->cmd.xfer;
1776 break;
1778 DPRINTF("Unsupported Service Action In\n");
1779 goto illegal_request;
1780 case SYNCHRONIZE_CACHE:
1781 /* The request is used as the AIO opaque value, so add a ref. */
1782 scsi_req_ref(&r->req);
1783 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1784 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
1785 return 0;
1786 case SEEK_10:
1787 DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
1788 if (r->req.cmd.lba > s->qdev.max_lba) {
1789 goto illegal_lba;
1791 break;
1792 case MODE_SELECT:
1793 DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1794 break;
1795 case MODE_SELECT_10:
1796 DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1797 break;
1798 case UNMAP:
1799 DPRINTF("Unmap (len %lu)\n", (long)r->req.cmd.xfer);
1800 break;
1801 case WRITE_SAME_10:
1802 case WRITE_SAME_16:
1803 nb_sectors = scsi_data_cdb_length(r->req.cmd.buf);
1804 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1805 scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1806 return 0;
1808 if (!check_lba_range(s, r->req.cmd.lba, nb_sectors)) {
1809 goto illegal_lba;
1813 * We only support WRITE SAME with the unmap bit set for now.
1815 if (!(req->cmd.buf[1] & 0x8)) {
1816 goto illegal_request;
1819 /* The request is used as the AIO opaque value, so add a ref. */
1820 scsi_req_ref(&r->req);
1821 r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1822 r->req.cmd.lba * (s->qdev.blocksize / 512),
1823 nb_sectors * (s->qdev.blocksize / 512),
1824 scsi_aio_complete, r);
1825 return 0;
1826 default:
1827 DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1828 scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1829 return 0;
1831 assert(!r->req.aiocb);
1832 r->iov.iov_len = MIN(buflen, req->cmd.xfer);
1833 if (r->iov.iov_len == 0) {
1834 scsi_req_complete(&r->req, GOOD);
1836 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1837 assert(r->iov.iov_len == req->cmd.xfer);
1838 return -r->iov.iov_len;
1839 } else {
1840 return r->iov.iov_len;
1843 illegal_request:
1844 if (r->req.status == -1) {
1845 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1847 return 0;
1849 illegal_lba:
1850 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1851 return 0;
1854 /* Execute a scsi command. Returns the length of the data expected by the
1855 command. This will be Positive for data transfers from the device
1856 (eg. disk reads), negative for transfers to the device (eg. disk writes),
1857 and zero if the command does not transfer any data. */
1859 static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
1861 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1862 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1863 uint32_t len;
1864 uint8_t command;
1866 command = buf[0];
1868 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1869 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1870 return 0;
1873 len = scsi_data_cdb_length(r->req.cmd.buf);
1874 switch (command) {
1875 case READ_6:
1876 case READ_10:
1877 case READ_12:
1878 case READ_16:
1879 DPRINTF("Read (sector %" PRId64 ", count %u)\n", r->req.cmd.lba, len);
1880 if (r->req.cmd.buf[1] & 0xe0) {
1881 goto illegal_request;
1883 if (!check_lba_range(s, r->req.cmd.lba, len)) {
1884 goto illegal_lba;
1886 r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1887 r->sector_count = len * (s->qdev.blocksize / 512);
1888 break;
1889 case WRITE_6:
1890 case WRITE_10:
1891 case WRITE_12:
1892 case WRITE_16:
1893 case WRITE_VERIFY_10:
1894 case WRITE_VERIFY_12:
1895 case WRITE_VERIFY_16:
1896 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1897 scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1898 return 0;
1900 /* fallthrough */
1901 case VERIFY_10:
1902 case VERIFY_12:
1903 case VERIFY_16:
1904 DPRINTF("Write %s(sector %" PRId64 ", count %u)\n",
1905 (command & 0xe) == 0xe ? "And Verify " : "",
1906 r->req.cmd.lba, len);
1907 if (r->req.cmd.buf[1] & 0xe0) {
1908 goto illegal_request;
1910 if (!check_lba_range(s, r->req.cmd.lba, len)) {
1911 goto illegal_lba;
1913 r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1914 r->sector_count = len * (s->qdev.blocksize / 512);
1915 break;
1916 default:
1917 abort();
1918 illegal_request:
1919 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1920 return 0;
1921 illegal_lba:
1922 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1923 return 0;
1925 if (r->sector_count == 0) {
1926 scsi_req_complete(&r->req, GOOD);
1928 assert(r->iov.iov_len == 0);
1929 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1930 return -r->sector_count * 512;
1931 } else {
1932 return r->sector_count * 512;
1936 static void scsi_disk_reset(DeviceState *dev)
1938 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1939 uint64_t nb_sectors;
1941 scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1943 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1944 nb_sectors /= s->qdev.blocksize / 512;
1945 if (nb_sectors) {
1946 nb_sectors--;
1948 s->qdev.max_lba = nb_sectors;
1951 static void scsi_destroy(SCSIDevice *dev)
1953 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1955 scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1956 blockdev_mark_auto_del(s->qdev.conf.bs);
1959 static void scsi_disk_resize_cb(void *opaque)
1961 SCSIDiskState *s = opaque;
1963 /* SPC lists this sense code as available only for
1964 * direct-access devices.
1966 if (s->qdev.type == TYPE_DISK) {
1967 scsi_device_set_ua(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
1968 scsi_device_report_change(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
1972 static void scsi_cd_change_media_cb(void *opaque, bool load)
1974 SCSIDiskState *s = opaque;
1977 * When a CD gets changed, we have to report an ejected state and
1978 * then a loaded state to guests so that they detect tray
1979 * open/close and media change events. Guests that do not use
1980 * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
1981 * states rely on this behavior.
1983 * media_changed governs the state machine used for unit attention
1984 * report. media_event is used by GET EVENT STATUS NOTIFICATION.
1986 s->media_changed = load;
1987 s->tray_open = !load;
1988 scsi_device_set_ua(&s->qdev, SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM));
1989 s->media_event = true;
1990 s->eject_request = false;
1993 static void scsi_cd_eject_request_cb(void *opaque, bool force)
1995 SCSIDiskState *s = opaque;
1997 s->eject_request = true;
1998 if (force) {
1999 s->tray_locked = false;
2003 static bool scsi_cd_is_tray_open(void *opaque)
2005 return ((SCSIDiskState *)opaque)->tray_open;
2008 static bool scsi_cd_is_medium_locked(void *opaque)
2010 return ((SCSIDiskState *)opaque)->tray_locked;
2013 static const BlockDevOps scsi_disk_removable_block_ops = {
2014 .change_media_cb = scsi_cd_change_media_cb,
2015 .eject_request_cb = scsi_cd_eject_request_cb,
2016 .is_tray_open = scsi_cd_is_tray_open,
2017 .is_medium_locked = scsi_cd_is_medium_locked,
2019 .resize_cb = scsi_disk_resize_cb,
2022 static const BlockDevOps scsi_disk_block_ops = {
2023 .resize_cb = scsi_disk_resize_cb,
2026 static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
2028 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2029 if (s->media_changed) {
2030 s->media_changed = false;
2031 scsi_device_set_ua(&s->qdev, SENSE_CODE(MEDIUM_CHANGED));
2035 static int scsi_initfn(SCSIDevice *dev)
2037 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2039 if (!s->qdev.conf.bs) {
2040 error_report("drive property not set");
2041 return -1;
2044 if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&
2045 !bdrv_is_inserted(s->qdev.conf.bs)) {
2046 error_report("Device needs media, but drive is empty");
2047 return -1;
2050 blkconf_serial(&s->qdev.conf, &s->serial);
2051 if (dev->type == TYPE_DISK
2052 && blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
2053 return -1;
2056 if (!s->version) {
2057 s->version = g_strdup(qemu_get_version());
2059 if (!s->vendor) {
2060 s->vendor = g_strdup("QEMU");
2063 if (bdrv_is_sg(s->qdev.conf.bs)) {
2064 error_report("unwanted /dev/sg*");
2065 return -1;
2068 if (s->features & (1 << SCSI_DISK_F_REMOVABLE)) {
2069 bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s);
2070 } else {
2071 bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s);
2073 bdrv_set_buffer_alignment(s->qdev.conf.bs, s->qdev.blocksize);
2075 bdrv_iostatus_enable(s->qdev.conf.bs);
2076 add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL);
2077 return 0;
2080 static int scsi_hd_initfn(SCSIDevice *dev)
2082 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2083 s->qdev.blocksize = s->qdev.conf.logical_block_size;
2084 s->qdev.type = TYPE_DISK;
2085 if (!s->product) {
2086 s->product = g_strdup("QEMU HARDDISK");
2088 return scsi_initfn(&s->qdev);
2091 static int scsi_cd_initfn(SCSIDevice *dev)
2093 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2094 s->qdev.blocksize = 2048;
2095 s->qdev.type = TYPE_ROM;
2096 s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2097 if (!s->product) {
2098 s->product = g_strdup("QEMU CD-ROM");
2100 return scsi_initfn(&s->qdev);
2103 static int scsi_disk_initfn(SCSIDevice *dev)
2105 DriveInfo *dinfo;
2107 if (!dev->conf.bs) {
2108 return scsi_initfn(dev); /* ... and die there */
2111 dinfo = drive_get_by_blockdev(dev->conf.bs);
2112 if (dinfo->media_cd) {
2113 return scsi_cd_initfn(dev);
2114 } else {
2115 return scsi_hd_initfn(dev);
2119 static const SCSIReqOps scsi_disk_emulate_reqops = {
2120 .size = sizeof(SCSIDiskReq),
2121 .free_req = scsi_free_request,
2122 .send_command = scsi_disk_emulate_command,
2123 .read_data = scsi_disk_emulate_read_data,
2124 .write_data = scsi_disk_emulate_write_data,
2125 .get_buf = scsi_get_buf,
2128 static const SCSIReqOps scsi_disk_dma_reqops = {
2129 .size = sizeof(SCSIDiskReq),
2130 .free_req = scsi_free_request,
2131 .send_command = scsi_disk_dma_command,
2132 .read_data = scsi_read_data,
2133 .write_data = scsi_write_data,
2134 .cancel_io = scsi_cancel_io,
2135 .get_buf = scsi_get_buf,
2136 .load_request = scsi_disk_load_request,
2137 .save_request = scsi_disk_save_request,
2140 static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
2141 [TEST_UNIT_READY] = &scsi_disk_emulate_reqops,
2142 [INQUIRY] = &scsi_disk_emulate_reqops,
2143 [MODE_SENSE] = &scsi_disk_emulate_reqops,
2144 [MODE_SENSE_10] = &scsi_disk_emulate_reqops,
2145 [START_STOP] = &scsi_disk_emulate_reqops,
2146 [ALLOW_MEDIUM_REMOVAL] = &scsi_disk_emulate_reqops,
2147 [READ_CAPACITY_10] = &scsi_disk_emulate_reqops,
2148 [READ_TOC] = &scsi_disk_emulate_reqops,
2149 [READ_DVD_STRUCTURE] = &scsi_disk_emulate_reqops,
2150 [READ_DISC_INFORMATION] = &scsi_disk_emulate_reqops,
2151 [GET_CONFIGURATION] = &scsi_disk_emulate_reqops,
2152 [GET_EVENT_STATUS_NOTIFICATION] = &scsi_disk_emulate_reqops,
2153 [MECHANISM_STATUS] = &scsi_disk_emulate_reqops,
2154 [SERVICE_ACTION_IN_16] = &scsi_disk_emulate_reqops,
2155 [REQUEST_SENSE] = &scsi_disk_emulate_reqops,
2156 [SYNCHRONIZE_CACHE] = &scsi_disk_emulate_reqops,
2157 [SEEK_10] = &scsi_disk_emulate_reqops,
2158 [MODE_SELECT] = &scsi_disk_emulate_reqops,
2159 [MODE_SELECT_10] = &scsi_disk_emulate_reqops,
2160 [UNMAP] = &scsi_disk_emulate_reqops,
2161 [WRITE_SAME_10] = &scsi_disk_emulate_reqops,
2162 [WRITE_SAME_16] = &scsi_disk_emulate_reqops,
2164 [READ_6] = &scsi_disk_dma_reqops,
2165 [READ_10] = &scsi_disk_dma_reqops,
2166 [READ_12] = &scsi_disk_dma_reqops,
2167 [READ_16] = &scsi_disk_dma_reqops,
2168 [VERIFY_10] = &scsi_disk_dma_reqops,
2169 [VERIFY_12] = &scsi_disk_dma_reqops,
2170 [VERIFY_16] = &scsi_disk_dma_reqops,
2171 [WRITE_6] = &scsi_disk_dma_reqops,
2172 [WRITE_10] = &scsi_disk_dma_reqops,
2173 [WRITE_12] = &scsi_disk_dma_reqops,
2174 [WRITE_16] = &scsi_disk_dma_reqops,
2175 [WRITE_VERIFY_10] = &scsi_disk_dma_reqops,
2176 [WRITE_VERIFY_12] = &scsi_disk_dma_reqops,
2177 [WRITE_VERIFY_16] = &scsi_disk_dma_reqops,
2180 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
2181 uint8_t *buf, void *hba_private)
2183 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2184 SCSIRequest *req;
2185 const SCSIReqOps *ops;
2186 uint8_t command;
2188 command = buf[0];
2189 ops = scsi_disk_reqops_dispatch[command];
2190 if (!ops) {
2191 ops = &scsi_disk_emulate_reqops;
2193 req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
2195 #ifdef DEBUG_SCSI
2196 DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
2198 int i;
2199 for (i = 1; i < req->cmd.len; i++) {
2200 printf(" 0x%02x", buf[i]);
2202 printf("\n");
2204 #endif
2206 return req;
2209 #ifdef __linux__
2210 static int get_device_type(SCSIDiskState *s)
2212 BlockDriverState *bdrv = s->qdev.conf.bs;
2213 uint8_t cmd[16];
2214 uint8_t buf[36];
2215 uint8_t sensebuf[8];
2216 sg_io_hdr_t io_header;
2217 int ret;
2219 memset(cmd, 0, sizeof(cmd));
2220 memset(buf, 0, sizeof(buf));
2221 cmd[0] = INQUIRY;
2222 cmd[4] = sizeof(buf);
2224 memset(&io_header, 0, sizeof(io_header));
2225 io_header.interface_id = 'S';
2226 io_header.dxfer_direction = SG_DXFER_FROM_DEV;
2227 io_header.dxfer_len = sizeof(buf);
2228 io_header.dxferp = buf;
2229 io_header.cmdp = cmd;
2230 io_header.cmd_len = sizeof(cmd);
2231 io_header.mx_sb_len = sizeof(sensebuf);
2232 io_header.sbp = sensebuf;
2233 io_header.timeout = 6000; /* XXX */
2235 ret = bdrv_ioctl(bdrv, SG_IO, &io_header);
2236 if (ret < 0 || io_header.driver_status || io_header.host_status) {
2237 return -1;
2239 s->qdev.type = buf[0];
2240 if (buf[1] & 0x80) {
2241 s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2243 return 0;
2246 static int scsi_block_initfn(SCSIDevice *dev)
2248 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2249 int sg_version;
2250 int rc;
2252 if (!s->qdev.conf.bs) {
2253 error_report("scsi-block: drive property not set");
2254 return -1;
2257 /* check we are using a driver managing SG_IO (version 3 and after) */
2258 if (bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 ||
2259 sg_version < 30000) {
2260 error_report("scsi-block: scsi generic interface too old");
2261 return -1;
2264 /* get device type from INQUIRY data */
2265 rc = get_device_type(s);
2266 if (rc < 0) {
2267 error_report("scsi-block: INQUIRY failed");
2268 return -1;
2271 /* Make a guess for the block size, we'll fix it when the guest sends.
2272 * READ CAPACITY. If they don't, they likely would assume these sizes
2273 * anyway. (TODO: check in /sys).
2275 if (s->qdev.type == TYPE_ROM || s->qdev.type == TYPE_WORM) {
2276 s->qdev.blocksize = 2048;
2277 } else {
2278 s->qdev.blocksize = 512;
2280 return scsi_initfn(&s->qdev);
2283 static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
2284 uint32_t lun, uint8_t *buf,
2285 void *hba_private)
2287 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2289 switch (buf[0]) {
2290 case READ_6:
2291 case READ_10:
2292 case READ_12:
2293 case READ_16:
2294 case VERIFY_10:
2295 case VERIFY_12:
2296 case VERIFY_16:
2297 case WRITE_6:
2298 case WRITE_10:
2299 case WRITE_12:
2300 case WRITE_16:
2301 case WRITE_VERIFY_10:
2302 case WRITE_VERIFY_12:
2303 case WRITE_VERIFY_16:
2304 /* If we are not using O_DIRECT, we might read stale data from the
2305 * host cache if writes were made using other commands than these
2306 * ones (such as WRITE SAME or EXTENDED COPY, etc.). So, without
2307 * O_DIRECT everything must go through SG_IO.
2309 if (bdrv_get_flags(s->qdev.conf.bs) & BDRV_O_NOCACHE) {
2310 break;
2313 /* MMC writing cannot be done via pread/pwrite, because it sometimes
2314 * involves writing beyond the maximum LBA or to negative LBA (lead-in).
2315 * And once you do these writes, reading from the block device is
2316 * unreliable, too. It is even possible that reads deliver random data
2317 * from the host page cache (this is probably a Linux bug).
2319 * We might use scsi_disk_dma_reqops as long as no writing commands are
2320 * seen, but performance usually isn't paramount on optical media. So,
2321 * just make scsi-block operate the same as scsi-generic for them.
2323 if (s->qdev.type != TYPE_ROM) {
2324 return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun,
2325 hba_private);
2329 return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun,
2330 hba_private);
2332 #endif
2334 #define DEFINE_SCSI_DISK_PROPERTIES() \
2335 DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf), \
2336 DEFINE_PROP_STRING("ver", SCSIDiskState, version), \
2337 DEFINE_PROP_STRING("serial", SCSIDiskState, serial), \
2338 DEFINE_PROP_STRING("vendor", SCSIDiskState, vendor), \
2339 DEFINE_PROP_STRING("product", SCSIDiskState, product)
2341 static Property scsi_hd_properties[] = {
2342 DEFINE_SCSI_DISK_PROPERTIES(),
2343 DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2344 SCSI_DISK_F_REMOVABLE, false),
2345 DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2346 SCSI_DISK_F_DPOFUA, false),
2347 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2348 DEFINE_BLOCK_CHS_PROPERTIES(SCSIDiskState, qdev.conf),
2349 DEFINE_PROP_END_OF_LIST(),
2352 static const VMStateDescription vmstate_scsi_disk_state = {
2353 .name = "scsi-disk",
2354 .version_id = 1,
2355 .minimum_version_id = 1,
2356 .minimum_version_id_old = 1,
2357 .fields = (VMStateField[]) {
2358 VMSTATE_SCSI_DEVICE(qdev, SCSIDiskState),
2359 VMSTATE_BOOL(media_changed, SCSIDiskState),
2360 VMSTATE_BOOL(media_event, SCSIDiskState),
2361 VMSTATE_BOOL(eject_request, SCSIDiskState),
2362 VMSTATE_BOOL(tray_open, SCSIDiskState),
2363 VMSTATE_BOOL(tray_locked, SCSIDiskState),
2364 VMSTATE_END_OF_LIST()
2368 static void scsi_hd_class_initfn(ObjectClass *klass, void *data)
2370 DeviceClass *dc = DEVICE_CLASS(klass);
2371 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2373 sc->init = scsi_hd_initfn;
2374 sc->destroy = scsi_destroy;
2375 sc->alloc_req = scsi_new_request;
2376 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2377 dc->fw_name = "disk";
2378 dc->desc = "virtual SCSI disk";
2379 dc->reset = scsi_disk_reset;
2380 dc->props = scsi_hd_properties;
2381 dc->vmsd = &vmstate_scsi_disk_state;
2384 static TypeInfo scsi_hd_info = {
2385 .name = "scsi-hd",
2386 .parent = TYPE_SCSI_DEVICE,
2387 .instance_size = sizeof(SCSIDiskState),
2388 .class_init = scsi_hd_class_initfn,
2391 static Property scsi_cd_properties[] = {
2392 DEFINE_SCSI_DISK_PROPERTIES(),
2393 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2394 DEFINE_PROP_END_OF_LIST(),
2397 static void scsi_cd_class_initfn(ObjectClass *klass, void *data)
2399 DeviceClass *dc = DEVICE_CLASS(klass);
2400 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2402 sc->init = scsi_cd_initfn;
2403 sc->destroy = scsi_destroy;
2404 sc->alloc_req = scsi_new_request;
2405 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2406 dc->fw_name = "disk";
2407 dc->desc = "virtual SCSI CD-ROM";
2408 dc->reset = scsi_disk_reset;
2409 dc->props = scsi_cd_properties;
2410 dc->vmsd = &vmstate_scsi_disk_state;
2413 static TypeInfo scsi_cd_info = {
2414 .name = "scsi-cd",
2415 .parent = TYPE_SCSI_DEVICE,
2416 .instance_size = sizeof(SCSIDiskState),
2417 .class_init = scsi_cd_class_initfn,
2420 #ifdef __linux__
2421 static Property scsi_block_properties[] = {
2422 DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.bs),
2423 DEFINE_PROP_INT32("bootindex", SCSIDiskState, qdev.conf.bootindex, -1),
2424 DEFINE_PROP_END_OF_LIST(),
2427 static void scsi_block_class_initfn(ObjectClass *klass, void *data)
2429 DeviceClass *dc = DEVICE_CLASS(klass);
2430 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2432 sc->init = scsi_block_initfn;
2433 sc->destroy = scsi_destroy;
2434 sc->alloc_req = scsi_block_new_request;
2435 dc->fw_name = "disk";
2436 dc->desc = "SCSI block device passthrough";
2437 dc->reset = scsi_disk_reset;
2438 dc->props = scsi_block_properties;
2439 dc->vmsd = &vmstate_scsi_disk_state;
2442 static TypeInfo scsi_block_info = {
2443 .name = "scsi-block",
2444 .parent = TYPE_SCSI_DEVICE,
2445 .instance_size = sizeof(SCSIDiskState),
2446 .class_init = scsi_block_class_initfn,
2448 #endif
2450 static Property scsi_disk_properties[] = {
2451 DEFINE_SCSI_DISK_PROPERTIES(),
2452 DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2453 SCSI_DISK_F_REMOVABLE, false),
2454 DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2455 SCSI_DISK_F_DPOFUA, false),
2456 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2457 DEFINE_PROP_END_OF_LIST(),
2460 static void scsi_disk_class_initfn(ObjectClass *klass, void *data)
2462 DeviceClass *dc = DEVICE_CLASS(klass);
2463 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2465 sc->init = scsi_disk_initfn;
2466 sc->destroy = scsi_destroy;
2467 sc->alloc_req = scsi_new_request;
2468 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2469 dc->fw_name = "disk";
2470 dc->desc = "virtual SCSI disk or CD-ROM (legacy)";
2471 dc->reset = scsi_disk_reset;
2472 dc->props = scsi_disk_properties;
2473 dc->vmsd = &vmstate_scsi_disk_state;
2476 static TypeInfo scsi_disk_info = {
2477 .name = "scsi-disk",
2478 .parent = TYPE_SCSI_DEVICE,
2479 .instance_size = sizeof(SCSIDiskState),
2480 .class_init = scsi_disk_class_initfn,
2483 static void scsi_disk_register_types(void)
2485 type_register_static(&scsi_hd_info);
2486 type_register_static(&scsi_cd_info);
2487 #ifdef __linux__
2488 type_register_static(&scsi_block_info);
2489 #endif
2490 type_register_static(&scsi_disk_info);
2493 type_init(scsi_disk_register_types)