prep: Fix NIP reset value
[qemu/agraf.git] / hw / scsi / scsi-disk.c
blobc8d2a99593b605edfe7a0e9d6ba06a84f876df94
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-report.h"
33 #include "hw/scsi/scsi.h"
34 #include "block/scsi.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/blockdev.h"
37 #include "hw/block/block.h"
38 #include "sysemu/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 #define DEFAULT_DISCARD_GRANULARITY 4096
50 typedef struct SCSIDiskState SCSIDiskState;
52 typedef struct SCSIDiskReq {
53 SCSIRequest req;
54 /* Both sector and sector_count are in terms of qemu 512 byte blocks. */
55 uint64_t sector;
56 uint32_t sector_count;
57 uint32_t buflen;
58 bool started;
59 struct iovec iov;
60 QEMUIOVector qiov;
61 BlockAcctCookie acct;
62 } SCSIDiskReq;
64 #define SCSI_DISK_F_REMOVABLE 0
65 #define SCSI_DISK_F_DPOFUA 1
67 struct SCSIDiskState
69 SCSIDevice qdev;
70 uint32_t features;
71 bool media_changed;
72 bool media_event;
73 bool eject_request;
74 uint64_t wwn;
75 QEMUBH *bh;
76 char *version;
77 char *serial;
78 char *vendor;
79 char *product;
80 bool tray_open;
81 bool tray_locked;
84 static int scsi_handle_rw_error(SCSIDiskReq *r, int error);
86 static void scsi_free_request(SCSIRequest *req)
88 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
90 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);
181 if (r->req.io_canceled) {
182 goto done;
185 if (ret < 0) {
186 if (scsi_handle_rw_error(r, -ret)) {
187 goto done;
191 scsi_req_complete(&r->req, GOOD);
193 done:
194 if (!r->req.io_canceled) {
195 scsi_req_unref(&r->req);
199 static bool scsi_is_cmd_fua(SCSICommand *cmd)
201 switch (cmd->buf[0]) {
202 case READ_10:
203 case READ_12:
204 case READ_16:
205 case WRITE_10:
206 case WRITE_12:
207 case WRITE_16:
208 return (cmd->buf[1] & 8) != 0;
210 case VERIFY_10:
211 case VERIFY_12:
212 case VERIFY_16:
213 case WRITE_VERIFY_10:
214 case WRITE_VERIFY_12:
215 case WRITE_VERIFY_16:
216 return true;
218 case READ_6:
219 case WRITE_6:
220 default:
221 return false;
225 static void scsi_write_do_fua(SCSIDiskReq *r)
227 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
229 if (r->req.io_canceled) {
230 goto done;
233 if (scsi_is_cmd_fua(&r->req.cmd)) {
234 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
235 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
236 return;
239 scsi_req_complete(&r->req, GOOD);
241 done:
242 if (!r->req.io_canceled) {
243 scsi_req_unref(&r->req);
247 static void scsi_dma_complete_noio(void *opaque, int ret)
249 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
250 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
252 if (r->req.aiocb != NULL) {
253 r->req.aiocb = NULL;
254 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
256 if (r->req.io_canceled) {
257 goto done;
260 if (ret < 0) {
261 if (scsi_handle_rw_error(r, -ret)) {
262 goto done;
266 r->sector += r->sector_count;
267 r->sector_count = 0;
268 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
269 scsi_write_do_fua(r);
270 return;
271 } else {
272 scsi_req_complete(&r->req, GOOD);
275 done:
276 if (!r->req.io_canceled) {
277 scsi_req_unref(&r->req);
281 static void scsi_dma_complete(void *opaque, int ret)
283 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
285 assert(r->req.aiocb != NULL);
286 scsi_dma_complete_noio(opaque, ret);
289 static void scsi_read_complete(void * opaque, int ret)
291 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
292 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
293 int n;
295 assert(r->req.aiocb != NULL);
296 r->req.aiocb = NULL;
297 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
298 if (r->req.io_canceled) {
299 goto done;
302 if (ret < 0) {
303 if (scsi_handle_rw_error(r, -ret)) {
304 goto done;
308 DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
310 n = r->qiov.size / 512;
311 r->sector += n;
312 r->sector_count -= n;
313 scsi_req_data(&r->req, r->qiov.size);
315 done:
316 if (!r->req.io_canceled) {
317 scsi_req_unref(&r->req);
321 /* Actually issue a read to the block device. */
322 static void scsi_do_read(void *opaque, int ret)
324 SCSIDiskReq *r = opaque;
325 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
326 uint32_t n;
328 if (r->req.aiocb != NULL) {
329 r->req.aiocb = NULL;
330 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
332 if (r->req.io_canceled) {
333 goto done;
336 if (ret < 0) {
337 if (scsi_handle_rw_error(r, -ret)) {
338 goto done;
342 /* The request is used as the AIO opaque value, so add a ref. */
343 scsi_req_ref(&r->req);
345 if (r->req.sg) {
346 dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ);
347 r->req.resid -= r->req.sg->size;
348 r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector,
349 scsi_dma_complete, r);
350 } else {
351 n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
352 bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
353 r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n,
354 scsi_read_complete, r);
357 done:
358 if (!r->req.io_canceled) {
359 scsi_req_unref(&r->req);
363 /* Read more data from scsi device into buffer. */
364 static void scsi_read_data(SCSIRequest *req)
366 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
367 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
368 bool first;
370 DPRINTF("Read sector_count=%d\n", r->sector_count);
371 if (r->sector_count == 0) {
372 /* This also clears the sense buffer for REQUEST SENSE. */
373 scsi_req_complete(&r->req, GOOD);
374 return;
377 /* No data transfer may already be in progress */
378 assert(r->req.aiocb == NULL);
380 /* The request is used as the AIO opaque value, so add a ref. */
381 scsi_req_ref(&r->req);
382 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
383 DPRINTF("Data transfer direction invalid\n");
384 scsi_read_complete(r, -EINVAL);
385 return;
388 if (s->tray_open) {
389 scsi_read_complete(r, -ENOMEDIUM);
390 return;
393 first = !r->started;
394 r->started = true;
395 if (first && scsi_is_cmd_fua(&r->req.cmd)) {
396 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
397 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_do_read, r);
398 } else {
399 scsi_do_read(r, 0);
404 * scsi_handle_rw_error has two return values. 0 means that the error
405 * must be ignored, 1 means that the error has been processed and the
406 * caller should not do anything else for this request. Note that
407 * scsi_handle_rw_error always manages its reference counts, independent
408 * of the return value.
410 static int scsi_handle_rw_error(SCSIDiskReq *r, int error)
412 bool is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV);
413 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
414 BlockErrorAction action = bdrv_get_error_action(s->qdev.conf.bs, is_read, error);
416 if (action == BDRV_ACTION_REPORT) {
417 switch (error) {
418 case ENOMEDIUM:
419 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
420 break;
421 case ENOMEM:
422 scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
423 break;
424 case EINVAL:
425 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
426 break;
427 default:
428 scsi_check_condition(r, SENSE_CODE(IO_ERROR));
429 break;
432 bdrv_error_action(s->qdev.conf.bs, action, is_read, error);
433 if (action == BDRV_ACTION_STOP) {
434 scsi_req_retry(&r->req);
436 return action != BDRV_ACTION_IGNORE;
439 static void scsi_write_complete(void * opaque, int ret)
441 SCSIDiskReq *r = (SCSIDiskReq *)opaque;
442 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
443 uint32_t n;
445 if (r->req.aiocb != NULL) {
446 r->req.aiocb = NULL;
447 bdrv_acct_done(s->qdev.conf.bs, &r->acct);
449 if (r->req.io_canceled) {
450 goto done;
453 if (ret < 0) {
454 if (scsi_handle_rw_error(r, -ret)) {
455 goto done;
459 n = r->qiov.size / 512;
460 r->sector += n;
461 r->sector_count -= n;
462 if (r->sector_count == 0) {
463 scsi_write_do_fua(r);
464 return;
465 } else {
466 scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
467 DPRINTF("Write complete tag=0x%x more=%zd\n", r->req.tag, r->qiov.size);
468 scsi_req_data(&r->req, r->qiov.size);
471 done:
472 if (!r->req.io_canceled) {
473 scsi_req_unref(&r->req);
477 static void scsi_write_data(SCSIRequest *req)
479 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
480 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
481 uint32_t n;
483 /* No data transfer may already be in progress */
484 assert(r->req.aiocb == NULL);
486 /* The request is used as the AIO opaque value, so add a ref. */
487 scsi_req_ref(&r->req);
488 if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
489 DPRINTF("Data transfer direction invalid\n");
490 scsi_write_complete(r, -EINVAL);
491 return;
494 if (!r->req.sg && !r->qiov.size) {
495 /* Called for the first time. Ask the driver to send us more data. */
496 r->started = true;
497 scsi_write_complete(r, 0);
498 return;
500 if (s->tray_open) {
501 scsi_write_complete(r, -ENOMEDIUM);
502 return;
505 if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
506 r->req.cmd.buf[0] == VERIFY_16) {
507 if (r->req.sg) {
508 scsi_dma_complete_noio(r, 0);
509 } else {
510 scsi_write_complete(r, 0);
512 return;
515 if (r->req.sg) {
516 dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_WRITE);
517 r->req.resid -= r->req.sg->size;
518 r->req.aiocb = dma_bdrv_write(s->qdev.conf.bs, r->req.sg, r->sector,
519 scsi_dma_complete, r);
520 } else {
521 n = r->qiov.size / 512;
522 bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
523 r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, r->sector, &r->qiov, n,
524 scsi_write_complete, r);
528 /* Return a pointer to the data buffer. */
529 static uint8_t *scsi_get_buf(SCSIRequest *req)
531 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
533 return (uint8_t *)r->iov.iov_base;
536 static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
538 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
539 int buflen = 0;
540 int start;
542 if (req->cmd.buf[1] & 0x1) {
543 /* Vital product data */
544 uint8_t page_code = req->cmd.buf[2];
546 outbuf[buflen++] = s->qdev.type & 0x1f;
547 outbuf[buflen++] = page_code ; // this page
548 outbuf[buflen++] = 0x00;
549 outbuf[buflen++] = 0x00;
550 start = buflen;
552 switch (page_code) {
553 case 0x00: /* Supported page codes, mandatory */
555 DPRINTF("Inquiry EVPD[Supported pages] "
556 "buffer size %zd\n", req->cmd.xfer);
557 outbuf[buflen++] = 0x00; // list of supported pages (this page)
558 if (s->serial) {
559 outbuf[buflen++] = 0x80; // unit serial number
561 outbuf[buflen++] = 0x83; // device identification
562 if (s->qdev.type == TYPE_DISK) {
563 outbuf[buflen++] = 0xb0; // block limits
564 outbuf[buflen++] = 0xb2; // thin provisioning
566 break;
568 case 0x80: /* Device serial number, optional */
570 int l;
572 if (!s->serial) {
573 DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
574 return -1;
577 l = strlen(s->serial);
578 if (l > 20) {
579 l = 20;
582 DPRINTF("Inquiry EVPD[Serial number] "
583 "buffer size %zd\n", req->cmd.xfer);
584 memcpy(outbuf+buflen, s->serial, l);
585 buflen += l;
586 break;
589 case 0x83: /* Device identification page, mandatory */
591 const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs);
592 int max_len = s->serial ? 20 : 255 - 8;
593 int id_len = strlen(str);
595 if (id_len > max_len) {
596 id_len = max_len;
598 DPRINTF("Inquiry EVPD[Device identification] "
599 "buffer size %zd\n", req->cmd.xfer);
601 outbuf[buflen++] = 0x2; // ASCII
602 outbuf[buflen++] = 0; // not officially assigned
603 outbuf[buflen++] = 0; // reserved
604 outbuf[buflen++] = id_len; // length of data following
605 memcpy(outbuf+buflen, str, id_len);
606 buflen += id_len;
608 if (s->wwn) {
609 outbuf[buflen++] = 0x1; // Binary
610 outbuf[buflen++] = 0x3; // NAA
611 outbuf[buflen++] = 0; // reserved
612 outbuf[buflen++] = 8;
613 stq_be_p(&outbuf[buflen], s->wwn);
614 buflen += 8;
616 break;
618 case 0xb0: /* block limits */
620 unsigned int unmap_sectors =
621 s->qdev.conf.discard_granularity / s->qdev.blocksize;
622 unsigned int min_io_size =
623 s->qdev.conf.min_io_size / s->qdev.blocksize;
624 unsigned int opt_io_size =
625 s->qdev.conf.opt_io_size / s->qdev.blocksize;
627 if (s->qdev.type == TYPE_ROM) {
628 DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
629 page_code);
630 return -1;
632 /* required VPD size with unmap support */
633 buflen = 0x40;
634 memset(outbuf + 4, 0, buflen - 4);
636 /* optimal transfer length granularity */
637 outbuf[6] = (min_io_size >> 8) & 0xff;
638 outbuf[7] = min_io_size & 0xff;
640 /* optimal transfer length */
641 outbuf[12] = (opt_io_size >> 24) & 0xff;
642 outbuf[13] = (opt_io_size >> 16) & 0xff;
643 outbuf[14] = (opt_io_size >> 8) & 0xff;
644 outbuf[15] = opt_io_size & 0xff;
646 /* optimal unmap granularity */
647 outbuf[28] = (unmap_sectors >> 24) & 0xff;
648 outbuf[29] = (unmap_sectors >> 16) & 0xff;
649 outbuf[30] = (unmap_sectors >> 8) & 0xff;
650 outbuf[31] = unmap_sectors & 0xff;
651 break;
653 case 0xb2: /* thin provisioning */
655 buflen = 8;
656 outbuf[4] = 0;
657 outbuf[5] = 0xe0; /* unmap & write_same 10/16 all supported */
658 outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
659 outbuf[7] = 0;
660 break;
662 default:
663 return -1;
665 /* done with EVPD */
666 assert(buflen - start <= 255);
667 outbuf[start - 1] = buflen - start;
668 return buflen;
671 /* Standard INQUIRY data */
672 if (req->cmd.buf[2] != 0) {
673 return -1;
676 /* PAGE CODE == 0 */
677 buflen = req->cmd.xfer;
678 if (buflen > SCSI_MAX_INQUIRY_LEN) {
679 buflen = SCSI_MAX_INQUIRY_LEN;
682 outbuf[0] = s->qdev.type & 0x1f;
683 outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;
685 strpadcpy((char *) &outbuf[16], 16, s->product, ' ');
686 strpadcpy((char *) &outbuf[8], 8, s->vendor, ' ');
688 memset(&outbuf[32], 0, 4);
689 memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
691 * We claim conformance to SPC-3, which is required for guests
692 * to ask for modern features like READ CAPACITY(16) or the
693 * block characteristics VPD page by default. Not all of SPC-3
694 * is actually implemented, but we're good enough.
696 outbuf[2] = 5;
697 outbuf[3] = 2 | 0x10; /* Format 2, HiSup */
699 if (buflen > 36) {
700 outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
701 } else {
702 /* If the allocation length of CDB is too small,
703 the additional length is not adjusted */
704 outbuf[4] = 36 - 5;
707 /* Sync data transfer and TCQ. */
708 outbuf[7] = 0x10 | (req->bus->info->tcq ? 0x02 : 0);
709 return buflen;
712 static inline bool media_is_dvd(SCSIDiskState *s)
714 uint64_t nb_sectors;
715 if (s->qdev.type != TYPE_ROM) {
716 return false;
718 if (!bdrv_is_inserted(s->qdev.conf.bs)) {
719 return false;
721 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
722 return nb_sectors > CD_MAX_SECTORS;
725 static inline bool media_is_cd(SCSIDiskState *s)
727 uint64_t nb_sectors;
728 if (s->qdev.type != TYPE_ROM) {
729 return false;
731 if (!bdrv_is_inserted(s->qdev.conf.bs)) {
732 return false;
734 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
735 return nb_sectors <= CD_MAX_SECTORS;
738 static int scsi_read_disc_information(SCSIDiskState *s, SCSIDiskReq *r,
739 uint8_t *outbuf)
741 uint8_t type = r->req.cmd.buf[1] & 7;
743 if (s->qdev.type != TYPE_ROM) {
744 return -1;
747 /* Types 1/2 are only defined for Blu-Ray. */
748 if (type != 0) {
749 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
750 return -1;
753 memset(outbuf, 0, 34);
754 outbuf[1] = 32;
755 outbuf[2] = 0xe; /* last session complete, disc finalized */
756 outbuf[3] = 1; /* first track on disc */
757 outbuf[4] = 1; /* # of sessions */
758 outbuf[5] = 1; /* first track of last session */
759 outbuf[6] = 1; /* last track of last session */
760 outbuf[7] = 0x20; /* unrestricted use */
761 outbuf[8] = 0x00; /* CD-ROM or DVD-ROM */
762 /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
763 /* 12-23: not meaningful for CD-ROM or DVD-ROM */
764 /* 24-31: disc bar code */
765 /* 32: disc application code */
766 /* 33: number of OPC tables */
768 return 34;
771 static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
772 uint8_t *outbuf)
774 static const int rds_caps_size[5] = {
775 [0] = 2048 + 4,
776 [1] = 4 + 4,
777 [3] = 188 + 4,
778 [4] = 2048 + 4,
781 uint8_t media = r->req.cmd.buf[1];
782 uint8_t layer = r->req.cmd.buf[6];
783 uint8_t format = r->req.cmd.buf[7];
784 int size = -1;
786 if (s->qdev.type != TYPE_ROM) {
787 return -1;
789 if (media != 0) {
790 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
791 return -1;
794 if (format != 0xff) {
795 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
796 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
797 return -1;
799 if (media_is_cd(s)) {
800 scsi_check_condition(r, SENSE_CODE(INCOMPATIBLE_FORMAT));
801 return -1;
803 if (format >= ARRAY_SIZE(rds_caps_size)) {
804 return -1;
806 size = rds_caps_size[format];
807 memset(outbuf, 0, size);
810 switch (format) {
811 case 0x00: {
812 /* Physical format information */
813 uint64_t nb_sectors;
814 if (layer != 0) {
815 goto fail;
817 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
819 outbuf[4] = 1; /* DVD-ROM, part version 1 */
820 outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
821 outbuf[6] = 1; /* one layer, read-only (per MMC-2 spec) */
822 outbuf[7] = 0; /* default densities */
824 stl_be_p(&outbuf[12], (nb_sectors >> 2) - 1); /* end sector */
825 stl_be_p(&outbuf[16], (nb_sectors >> 2) - 1); /* l0 end sector */
826 break;
829 case 0x01: /* DVD copyright information, all zeros */
830 break;
832 case 0x03: /* BCA information - invalid field for no BCA info */
833 return -1;
835 case 0x04: /* DVD disc manufacturing information, all zeros */
836 break;
838 case 0xff: { /* List capabilities */
839 int i;
840 size = 4;
841 for (i = 0; i < ARRAY_SIZE(rds_caps_size); i++) {
842 if (!rds_caps_size[i]) {
843 continue;
845 outbuf[size] = i;
846 outbuf[size + 1] = 0x40; /* Not writable, readable */
847 stw_be_p(&outbuf[size + 2], rds_caps_size[i]);
848 size += 4;
850 break;
853 default:
854 return -1;
857 /* Size of buffer, not including 2 byte size field */
858 stw_be_p(outbuf, size - 2);
859 return size;
861 fail:
862 return -1;
865 static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf)
867 uint8_t event_code, media_status;
869 media_status = 0;
870 if (s->tray_open) {
871 media_status = MS_TRAY_OPEN;
872 } else if (bdrv_is_inserted(s->qdev.conf.bs)) {
873 media_status = MS_MEDIA_PRESENT;
876 /* Event notification descriptor */
877 event_code = MEC_NO_CHANGE;
878 if (media_status != MS_TRAY_OPEN) {
879 if (s->media_event) {
880 event_code = MEC_NEW_MEDIA;
881 s->media_event = false;
882 } else if (s->eject_request) {
883 event_code = MEC_EJECT_REQUESTED;
884 s->eject_request = false;
888 outbuf[0] = event_code;
889 outbuf[1] = media_status;
891 /* These fields are reserved, just clear them. */
892 outbuf[2] = 0;
893 outbuf[3] = 0;
894 return 4;
897 static int scsi_get_event_status_notification(SCSIDiskState *s, SCSIDiskReq *r,
898 uint8_t *outbuf)
900 int size;
901 uint8_t *buf = r->req.cmd.buf;
902 uint8_t notification_class_request = buf[4];
903 if (s->qdev.type != TYPE_ROM) {
904 return -1;
906 if ((buf[1] & 1) == 0) {
907 /* asynchronous */
908 return -1;
911 size = 4;
912 outbuf[0] = outbuf[1] = 0;
913 outbuf[3] = 1 << GESN_MEDIA; /* supported events */
914 if (notification_class_request & (1 << GESN_MEDIA)) {
915 outbuf[2] = GESN_MEDIA;
916 size += scsi_event_status_media(s, &outbuf[size]);
917 } else {
918 outbuf[2] = 0x80;
920 stw_be_p(outbuf, size - 4);
921 return size;
924 static int scsi_get_configuration(SCSIDiskState *s, uint8_t *outbuf)
926 int current;
928 if (s->qdev.type != TYPE_ROM) {
929 return -1;
931 current = media_is_dvd(s) ? MMC_PROFILE_DVD_ROM : MMC_PROFILE_CD_ROM;
932 memset(outbuf, 0, 40);
933 stl_be_p(&outbuf[0], 36); /* Bytes after the data length field */
934 stw_be_p(&outbuf[6], current);
935 /* outbuf[8] - outbuf[19]: Feature 0 - Profile list */
936 outbuf[10] = 0x03; /* persistent, current */
937 outbuf[11] = 8; /* two profiles */
938 stw_be_p(&outbuf[12], MMC_PROFILE_DVD_ROM);
939 outbuf[14] = (current == MMC_PROFILE_DVD_ROM);
940 stw_be_p(&outbuf[16], MMC_PROFILE_CD_ROM);
941 outbuf[18] = (current == MMC_PROFILE_CD_ROM);
942 /* outbuf[20] - outbuf[31]: Feature 1 - Core feature */
943 stw_be_p(&outbuf[20], 1);
944 outbuf[22] = 0x08 | 0x03; /* version 2, persistent, current */
945 outbuf[23] = 8;
946 stl_be_p(&outbuf[24], 1); /* SCSI */
947 outbuf[28] = 1; /* DBE = 1, mandatory */
948 /* outbuf[32] - outbuf[39]: Feature 3 - Removable media feature */
949 stw_be_p(&outbuf[32], 3);
950 outbuf[34] = 0x08 | 0x03; /* version 2, persistent, current */
951 outbuf[35] = 4;
952 outbuf[36] = 0x39; /* tray, load=1, eject=1, unlocked at powerup, lock=1 */
953 /* TODO: Random readable, CD read, DVD read, drive serial number,
954 power management */
955 return 40;
958 static int scsi_emulate_mechanism_status(SCSIDiskState *s, uint8_t *outbuf)
960 if (s->qdev.type != TYPE_ROM) {
961 return -1;
963 memset(outbuf, 0, 8);
964 outbuf[5] = 1; /* CD-ROM */
965 return 8;
968 static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
969 int page_control)
971 static const int mode_sense_valid[0x3f] = {
972 [MODE_PAGE_HD_GEOMETRY] = (1 << TYPE_DISK),
973 [MODE_PAGE_FLEXIBLE_DISK_GEOMETRY] = (1 << TYPE_DISK),
974 [MODE_PAGE_CACHING] = (1 << TYPE_DISK) | (1 << TYPE_ROM),
975 [MODE_PAGE_R_W_ERROR] = (1 << TYPE_DISK) | (1 << TYPE_ROM),
976 [MODE_PAGE_AUDIO_CTL] = (1 << TYPE_ROM),
977 [MODE_PAGE_CAPABILITIES] = (1 << TYPE_ROM),
980 uint8_t *p = *p_outbuf + 2;
981 int length;
983 if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
984 return -1;
988 * If Changeable Values are requested, a mask denoting those mode parameters
989 * that are changeable shall be returned. As we currently don't support
990 * parameter changes via MODE_SELECT all bits are returned set to zero.
991 * The buffer was already menset to zero by the caller of this function.
993 * The offsets here are off by two compared to the descriptions in the
994 * SCSI specs, because those include a 2-byte header. This is unfortunate,
995 * but it is done so that offsets are consistent within our implementation
996 * of MODE SENSE and MODE SELECT. MODE SELECT has to deal with both
997 * 2-byte and 4-byte headers.
999 switch (page) {
1000 case MODE_PAGE_HD_GEOMETRY:
1001 length = 0x16;
1002 if (page_control == 1) { /* Changeable Values */
1003 break;
1005 /* if a geometry hint is available, use it */
1006 p[0] = (s->qdev.conf.cyls >> 16) & 0xff;
1007 p[1] = (s->qdev.conf.cyls >> 8) & 0xff;
1008 p[2] = s->qdev.conf.cyls & 0xff;
1009 p[3] = s->qdev.conf.heads & 0xff;
1010 /* Write precomp start cylinder, disabled */
1011 p[4] = (s->qdev.conf.cyls >> 16) & 0xff;
1012 p[5] = (s->qdev.conf.cyls >> 8) & 0xff;
1013 p[6] = s->qdev.conf.cyls & 0xff;
1014 /* Reduced current start cylinder, disabled */
1015 p[7] = (s->qdev.conf.cyls >> 16) & 0xff;
1016 p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
1017 p[9] = s->qdev.conf.cyls & 0xff;
1018 /* Device step rate [ns], 200ns */
1019 p[10] = 0;
1020 p[11] = 200;
1021 /* Landing zone cylinder */
1022 p[12] = 0xff;
1023 p[13] = 0xff;
1024 p[14] = 0xff;
1025 /* Medium rotation rate [rpm], 5400 rpm */
1026 p[18] = (5400 >> 8) & 0xff;
1027 p[19] = 5400 & 0xff;
1028 break;
1030 case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
1031 length = 0x1e;
1032 if (page_control == 1) { /* Changeable Values */
1033 break;
1035 /* Transfer rate [kbit/s], 5Mbit/s */
1036 p[0] = 5000 >> 8;
1037 p[1] = 5000 & 0xff;
1038 /* if a geometry hint is available, use it */
1039 p[2] = s->qdev.conf.heads & 0xff;
1040 p[3] = s->qdev.conf.secs & 0xff;
1041 p[4] = s->qdev.blocksize >> 8;
1042 p[6] = (s->qdev.conf.cyls >> 8) & 0xff;
1043 p[7] = s->qdev.conf.cyls & 0xff;
1044 /* Write precomp start cylinder, disabled */
1045 p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
1046 p[9] = s->qdev.conf.cyls & 0xff;
1047 /* Reduced current start cylinder, disabled */
1048 p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
1049 p[11] = s->qdev.conf.cyls & 0xff;
1050 /* Device step rate [100us], 100us */
1051 p[12] = 0;
1052 p[13] = 1;
1053 /* Device step pulse width [us], 1us */
1054 p[14] = 1;
1055 /* Device head settle delay [100us], 100us */
1056 p[15] = 0;
1057 p[16] = 1;
1058 /* Motor on delay [0.1s], 0.1s */
1059 p[17] = 1;
1060 /* Motor off delay [0.1s], 0.1s */
1061 p[18] = 1;
1062 /* Medium rotation rate [rpm], 5400 rpm */
1063 p[26] = (5400 >> 8) & 0xff;
1064 p[27] = 5400 & 0xff;
1065 break;
1067 case MODE_PAGE_CACHING:
1068 length = 0x12;
1069 if (page_control == 1 || /* Changeable Values */
1070 bdrv_enable_write_cache(s->qdev.conf.bs)) {
1071 p[0] = 4; /* WCE */
1073 break;
1075 case MODE_PAGE_R_W_ERROR:
1076 length = 10;
1077 if (page_control == 1) { /* Changeable Values */
1078 break;
1080 p[0] = 0x80; /* Automatic Write Reallocation Enabled */
1081 if (s->qdev.type == TYPE_ROM) {
1082 p[1] = 0x20; /* Read Retry Count */
1084 break;
1086 case MODE_PAGE_AUDIO_CTL:
1087 length = 14;
1088 break;
1090 case MODE_PAGE_CAPABILITIES:
1091 length = 0x14;
1092 if (page_control == 1) { /* Changeable Values */
1093 break;
1096 p[0] = 0x3b; /* CD-R & CD-RW read */
1097 p[1] = 0; /* Writing not supported */
1098 p[2] = 0x7f; /* Audio, composite, digital out,
1099 mode 2 form 1&2, multi session */
1100 p[3] = 0xff; /* CD DA, DA accurate, RW supported,
1101 RW corrected, C2 errors, ISRC,
1102 UPC, Bar code */
1103 p[4] = 0x2d | (s->tray_locked ? 2 : 0);
1104 /* Locking supported, jumper present, eject, tray */
1105 p[5] = 0; /* no volume & mute control, no
1106 changer */
1107 p[6] = (50 * 176) >> 8; /* 50x read speed */
1108 p[7] = (50 * 176) & 0xff;
1109 p[8] = 2 >> 8; /* Two volume levels */
1110 p[9] = 2 & 0xff;
1111 p[10] = 2048 >> 8; /* 2M buffer */
1112 p[11] = 2048 & 0xff;
1113 p[12] = (16 * 176) >> 8; /* 16x read speed current */
1114 p[13] = (16 * 176) & 0xff;
1115 p[16] = (16 * 176) >> 8; /* 16x write speed */
1116 p[17] = (16 * 176) & 0xff;
1117 p[18] = (16 * 176) >> 8; /* 16x write speed current */
1118 p[19] = (16 * 176) & 0xff;
1119 break;
1121 default:
1122 return -1;
1125 assert(length < 256);
1126 (*p_outbuf)[0] = page;
1127 (*p_outbuf)[1] = length;
1128 *p_outbuf += length + 2;
1129 return length + 2;
1132 static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
1134 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1135 uint64_t nb_sectors;
1136 bool dbd;
1137 int page, buflen, ret, page_control;
1138 uint8_t *p;
1139 uint8_t dev_specific_param;
1141 dbd = (r->req.cmd.buf[1] & 0x8) != 0;
1142 page = r->req.cmd.buf[2] & 0x3f;
1143 page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
1144 DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
1145 (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
1146 memset(outbuf, 0, r->req.cmd.xfer);
1147 p = outbuf;
1149 if (s->qdev.type == TYPE_DISK) {
1150 dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0;
1151 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1152 dev_specific_param |= 0x80; /* Readonly. */
1154 } else {
1155 /* MMC prescribes that CD/DVD drives have no block descriptors,
1156 * and defines no device-specific parameter. */
1157 dev_specific_param = 0x00;
1158 dbd = true;
1161 if (r->req.cmd.buf[0] == MODE_SENSE) {
1162 p[1] = 0; /* Default media type. */
1163 p[2] = dev_specific_param;
1164 p[3] = 0; /* Block descriptor length. */
1165 p += 4;
1166 } else { /* MODE_SENSE_10 */
1167 p[2] = 0; /* Default media type. */
1168 p[3] = dev_specific_param;
1169 p[6] = p[7] = 0; /* Block descriptor length. */
1170 p += 8;
1173 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1174 if (!dbd && nb_sectors) {
1175 if (r->req.cmd.buf[0] == MODE_SENSE) {
1176 outbuf[3] = 8; /* Block descriptor length */
1177 } else { /* MODE_SENSE_10 */
1178 outbuf[7] = 8; /* Block descriptor length */
1180 nb_sectors /= (s->qdev.blocksize / 512);
1181 if (nb_sectors > 0xffffff) {
1182 nb_sectors = 0;
1184 p[0] = 0; /* media density code */
1185 p[1] = (nb_sectors >> 16) & 0xff;
1186 p[2] = (nb_sectors >> 8) & 0xff;
1187 p[3] = nb_sectors & 0xff;
1188 p[4] = 0; /* reserved */
1189 p[5] = 0; /* bytes 5-7 are the sector size in bytes */
1190 p[6] = s->qdev.blocksize >> 8;
1191 p[7] = 0;
1192 p += 8;
1195 if (page_control == 3) {
1196 /* Saved Values */
1197 scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
1198 return -1;
1201 if (page == 0x3f) {
1202 for (page = 0; page <= 0x3e; page++) {
1203 mode_sense_page(s, page, &p, page_control);
1205 } else {
1206 ret = mode_sense_page(s, page, &p, page_control);
1207 if (ret == -1) {
1208 return -1;
1212 buflen = p - outbuf;
1214 * The mode data length field specifies the length in bytes of the
1215 * following data that is available to be transferred. The mode data
1216 * length does not include itself.
1218 if (r->req.cmd.buf[0] == MODE_SENSE) {
1219 outbuf[0] = buflen - 1;
1220 } else { /* MODE_SENSE_10 */
1221 outbuf[0] = ((buflen - 2) >> 8) & 0xff;
1222 outbuf[1] = (buflen - 2) & 0xff;
1224 return buflen;
1227 static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
1229 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1230 int start_track, format, msf, toclen;
1231 uint64_t nb_sectors;
1233 msf = req->cmd.buf[1] & 2;
1234 format = req->cmd.buf[2] & 0xf;
1235 start_track = req->cmd.buf[6];
1236 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1237 DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
1238 nb_sectors /= s->qdev.blocksize / 512;
1239 switch (format) {
1240 case 0:
1241 toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
1242 break;
1243 case 1:
1244 /* multi session : only a single session defined */
1245 toclen = 12;
1246 memset(outbuf, 0, 12);
1247 outbuf[1] = 0x0a;
1248 outbuf[2] = 0x01;
1249 outbuf[3] = 0x01;
1250 break;
1251 case 2:
1252 toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
1253 break;
1254 default:
1255 return -1;
1257 return toclen;
1260 static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
1262 SCSIRequest *req = &r->req;
1263 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1264 bool start = req->cmd.buf[4] & 1;
1265 bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
1266 int pwrcnd = req->cmd.buf[4] & 0xf0;
1268 if (pwrcnd) {
1269 /* eject/load only happens for power condition == 0 */
1270 return 0;
1273 if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) {
1274 if (!start && !s->tray_open && s->tray_locked) {
1275 scsi_check_condition(r,
1276 bdrv_is_inserted(s->qdev.conf.bs)
1277 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
1278 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
1279 return -1;
1282 if (s->tray_open != !start) {
1283 bdrv_eject(s->qdev.conf.bs, !start);
1284 s->tray_open = !start;
1287 return 0;
1290 static void scsi_disk_emulate_read_data(SCSIRequest *req)
1292 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1293 int buflen = r->iov.iov_len;
1295 if (buflen) {
1296 DPRINTF("Read buf_len=%d\n", buflen);
1297 r->iov.iov_len = 0;
1298 r->started = true;
1299 scsi_req_data(&r->req, buflen);
1300 return;
1303 /* This also clears the sense buffer for REQUEST SENSE. */
1304 scsi_req_complete(&r->req, GOOD);
1307 static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,
1308 uint8_t *inbuf, int inlen)
1310 uint8_t mode_current[SCSI_MAX_MODE_LEN];
1311 uint8_t mode_changeable[SCSI_MAX_MODE_LEN];
1312 uint8_t *p;
1313 int len, expected_len, changeable_len, i;
1315 /* The input buffer does not include the page header, so it is
1316 * off by 2 bytes.
1318 expected_len = inlen + 2;
1319 if (expected_len > SCSI_MAX_MODE_LEN) {
1320 return -1;
1323 p = mode_current;
1324 memset(mode_current, 0, inlen + 2);
1325 len = mode_sense_page(s, page, &p, 0);
1326 if (len < 0 || len != expected_len) {
1327 return -1;
1330 p = mode_changeable;
1331 memset(mode_changeable, 0, inlen + 2);
1332 changeable_len = mode_sense_page(s, page, &p, 1);
1333 assert(changeable_len == len);
1335 /* Check that unchangeable bits are the same as what MODE SENSE
1336 * would return.
1338 for (i = 2; i < len; i++) {
1339 if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) {
1340 return -1;
1343 return 0;
1346 static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)
1348 switch (page) {
1349 case MODE_PAGE_CACHING:
1350 bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0);
1351 break;
1353 default:
1354 break;
1358 static int mode_select_pages(SCSIDiskReq *r, uint8_t *p, int len, bool change)
1360 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1362 while (len > 0) {
1363 int page, subpage, page_len;
1365 /* Parse both possible formats for the mode page headers. */
1366 page = p[0] & 0x3f;
1367 if (p[0] & 0x40) {
1368 if (len < 4) {
1369 goto invalid_param_len;
1371 subpage = p[1];
1372 page_len = lduw_be_p(&p[2]);
1373 p += 4;
1374 len -= 4;
1375 } else {
1376 if (len < 2) {
1377 goto invalid_param_len;
1379 subpage = 0;
1380 page_len = p[1];
1381 p += 2;
1382 len -= 2;
1385 if (subpage) {
1386 goto invalid_param;
1388 if (page_len > len) {
1389 goto invalid_param_len;
1392 if (!change) {
1393 if (scsi_disk_check_mode_select(s, page, p, page_len) < 0) {
1394 goto invalid_param;
1396 } else {
1397 scsi_disk_apply_mode_select(s, page, p);
1400 p += page_len;
1401 len -= page_len;
1403 return 0;
1405 invalid_param:
1406 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1407 return -1;
1409 invalid_param_len:
1410 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1411 return -1;
1414 static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
1416 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1417 uint8_t *p = inbuf;
1418 int cmd = r->req.cmd.buf[0];
1419 int len = r->req.cmd.xfer;
1420 int hdr_len = (cmd == MODE_SELECT ? 4 : 8);
1421 int bd_len;
1422 int pass;
1424 /* We only support PF=1, SP=0. */
1425 if ((r->req.cmd.buf[1] & 0x11) != 0x10) {
1426 goto invalid_field;
1429 if (len < hdr_len) {
1430 goto invalid_param_len;
1433 bd_len = (cmd == MODE_SELECT ? p[3] : lduw_be_p(&p[6]));
1434 len -= hdr_len;
1435 p += hdr_len;
1436 if (len < bd_len) {
1437 goto invalid_param_len;
1439 if (bd_len != 0 && bd_len != 8) {
1440 goto invalid_param;
1443 len -= bd_len;
1444 p += bd_len;
1446 /* Ensure no change is made if there is an error! */
1447 for (pass = 0; pass < 2; pass++) {
1448 if (mode_select_pages(r, p, len, pass == 1) < 0) {
1449 assert(pass == 0);
1450 return;
1453 if (!bdrv_enable_write_cache(s->qdev.conf.bs)) {
1454 /* The request is used as the AIO opaque value, so add a ref. */
1455 scsi_req_ref(&r->req);
1456 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1457 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
1458 return;
1461 scsi_req_complete(&r->req, GOOD);
1462 return;
1464 invalid_param:
1465 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1466 return;
1468 invalid_param_len:
1469 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1470 return;
1472 invalid_field:
1473 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1476 static inline bool check_lba_range(SCSIDiskState *s,
1477 uint64_t sector_num, uint32_t nb_sectors)
1480 * The first line tests that no overflow happens when computing the last
1481 * sector. The second line tests that the last accessed sector is in
1482 * range.
1484 * Careful, the computations should not underflow for nb_sectors == 0,
1485 * and a 0-block read to the first LBA beyond the end of device is
1486 * valid.
1488 return (sector_num <= sector_num + nb_sectors &&
1489 sector_num + nb_sectors <= s->qdev.max_lba + 1);
1492 typedef struct UnmapCBData {
1493 SCSIDiskReq *r;
1494 uint8_t *inbuf;
1495 int count;
1496 } UnmapCBData;
1498 static void scsi_unmap_complete(void *opaque, int ret)
1500 UnmapCBData *data = opaque;
1501 SCSIDiskReq *r = data->r;
1502 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1503 uint64_t sector_num;
1504 uint32_t nb_sectors;
1506 r->req.aiocb = NULL;
1507 if (r->req.io_canceled) {
1508 goto done;
1511 if (ret < 0) {
1512 if (scsi_handle_rw_error(r, -ret)) {
1513 goto done;
1517 if (data->count > 0) {
1518 sector_num = ldq_be_p(&data->inbuf[0]);
1519 nb_sectors = ldl_be_p(&data->inbuf[8]) & 0xffffffffULL;
1520 if (!check_lba_range(s, sector_num, nb_sectors)) {
1521 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1522 goto done;
1525 r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1526 sector_num * (s->qdev.blocksize / 512),
1527 nb_sectors * (s->qdev.blocksize / 512),
1528 scsi_unmap_complete, data);
1529 data->count--;
1530 data->inbuf += 16;
1531 return;
1534 scsi_req_complete(&r->req, GOOD);
1536 done:
1537 if (!r->req.io_canceled) {
1538 scsi_req_unref(&r->req);
1540 g_free(data);
1543 static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf)
1545 uint8_t *p = inbuf;
1546 int len = r->req.cmd.xfer;
1547 UnmapCBData *data;
1549 if (len < 8) {
1550 goto invalid_param_len;
1552 if (len < lduw_be_p(&p[0]) + 2) {
1553 goto invalid_param_len;
1555 if (len < lduw_be_p(&p[2]) + 8) {
1556 goto invalid_param_len;
1558 if (lduw_be_p(&p[2]) & 15) {
1559 goto invalid_param_len;
1562 data = g_new0(UnmapCBData, 1);
1563 data->r = r;
1564 data->inbuf = &p[8];
1565 data->count = lduw_be_p(&p[2]) >> 4;
1567 /* The matching unref is in scsi_unmap_complete, before data is freed. */
1568 scsi_req_ref(&r->req);
1569 scsi_unmap_complete(data, 0);
1570 return;
1572 invalid_param_len:
1573 scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1576 static void scsi_disk_emulate_write_data(SCSIRequest *req)
1578 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1580 if (r->iov.iov_len) {
1581 int buflen = r->iov.iov_len;
1582 DPRINTF("Write buf_len=%d\n", buflen);
1583 r->iov.iov_len = 0;
1584 scsi_req_data(&r->req, buflen);
1585 return;
1588 switch (req->cmd.buf[0]) {
1589 case MODE_SELECT:
1590 case MODE_SELECT_10:
1591 /* This also clears the sense buffer for REQUEST SENSE. */
1592 scsi_disk_emulate_mode_select(r, r->iov.iov_base);
1593 break;
1595 case UNMAP:
1596 scsi_disk_emulate_unmap(r, r->iov.iov_base);
1597 break;
1599 default:
1600 abort();
1604 static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
1606 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1607 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1608 uint64_t nb_sectors;
1609 uint8_t *outbuf;
1610 int buflen;
1612 switch (req->cmd.buf[0]) {
1613 case INQUIRY:
1614 case MODE_SENSE:
1615 case MODE_SENSE_10:
1616 case RESERVE:
1617 case RESERVE_10:
1618 case RELEASE:
1619 case RELEASE_10:
1620 case START_STOP:
1621 case ALLOW_MEDIUM_REMOVAL:
1622 case GET_CONFIGURATION:
1623 case GET_EVENT_STATUS_NOTIFICATION:
1624 case MECHANISM_STATUS:
1625 case REQUEST_SENSE:
1626 break;
1628 default:
1629 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1630 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1631 return 0;
1633 break;
1637 * FIXME: we shouldn't return anything bigger than 4k, but the code
1638 * requires the buffer to be as big as req->cmd.xfer in several
1639 * places. So, do not allow CDBs with a very large ALLOCATION
1640 * LENGTH. The real fix would be to modify scsi_read_data and
1641 * dma_buf_read, so that they return data beyond the buflen
1642 * as all zeros.
1644 if (req->cmd.xfer > 65536) {
1645 goto illegal_request;
1647 r->buflen = MAX(4096, req->cmd.xfer);
1649 if (!r->iov.iov_base) {
1650 r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
1653 buflen = req->cmd.xfer;
1654 outbuf = r->iov.iov_base;
1655 memset(outbuf, 0, r->buflen);
1656 switch (req->cmd.buf[0]) {
1657 case TEST_UNIT_READY:
1658 assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));
1659 break;
1660 case INQUIRY:
1661 buflen = scsi_disk_emulate_inquiry(req, outbuf);
1662 if (buflen < 0) {
1663 goto illegal_request;
1665 break;
1666 case MODE_SENSE:
1667 case MODE_SENSE_10:
1668 buflen = scsi_disk_emulate_mode_sense(r, outbuf);
1669 if (buflen < 0) {
1670 goto illegal_request;
1672 break;
1673 case READ_TOC:
1674 buflen = scsi_disk_emulate_read_toc(req, outbuf);
1675 if (buflen < 0) {
1676 goto illegal_request;
1678 break;
1679 case RESERVE:
1680 if (req->cmd.buf[1] & 1) {
1681 goto illegal_request;
1683 break;
1684 case RESERVE_10:
1685 if (req->cmd.buf[1] & 3) {
1686 goto illegal_request;
1688 break;
1689 case RELEASE:
1690 if (req->cmd.buf[1] & 1) {
1691 goto illegal_request;
1693 break;
1694 case RELEASE_10:
1695 if (req->cmd.buf[1] & 3) {
1696 goto illegal_request;
1698 break;
1699 case START_STOP:
1700 if (scsi_disk_emulate_start_stop(r) < 0) {
1701 return 0;
1703 break;
1704 case ALLOW_MEDIUM_REMOVAL:
1705 s->tray_locked = req->cmd.buf[4] & 1;
1706 bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);
1707 break;
1708 case READ_CAPACITY_10:
1709 /* The normal LEN field for this command is zero. */
1710 memset(outbuf, 0, 8);
1711 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1712 if (!nb_sectors) {
1713 scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1714 return 0;
1716 if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {
1717 goto illegal_request;
1719 nb_sectors /= s->qdev.blocksize / 512;
1720 /* Returned value is the address of the last sector. */
1721 nb_sectors--;
1722 /* Remember the new size for read/write sanity checking. */
1723 s->qdev.max_lba = nb_sectors;
1724 /* Clip to 2TB, instead of returning capacity modulo 2TB. */
1725 if (nb_sectors > UINT32_MAX) {
1726 nb_sectors = UINT32_MAX;
1728 outbuf[0] = (nb_sectors >> 24) & 0xff;
1729 outbuf[1] = (nb_sectors >> 16) & 0xff;
1730 outbuf[2] = (nb_sectors >> 8) & 0xff;
1731 outbuf[3] = nb_sectors & 0xff;
1732 outbuf[4] = 0;
1733 outbuf[5] = 0;
1734 outbuf[6] = s->qdev.blocksize >> 8;
1735 outbuf[7] = 0;
1736 break;
1737 case REQUEST_SENSE:
1738 /* Just return "NO SENSE". */
1739 buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,
1740 (req->cmd.buf[1] & 1) == 0);
1741 if (buflen < 0) {
1742 goto illegal_request;
1744 break;
1745 case MECHANISM_STATUS:
1746 buflen = scsi_emulate_mechanism_status(s, outbuf);
1747 if (buflen < 0) {
1748 goto illegal_request;
1750 break;
1751 case GET_CONFIGURATION:
1752 buflen = scsi_get_configuration(s, outbuf);
1753 if (buflen < 0) {
1754 goto illegal_request;
1756 break;
1757 case GET_EVENT_STATUS_NOTIFICATION:
1758 buflen = scsi_get_event_status_notification(s, r, outbuf);
1759 if (buflen < 0) {
1760 goto illegal_request;
1762 break;
1763 case READ_DISC_INFORMATION:
1764 buflen = scsi_read_disc_information(s, r, outbuf);
1765 if (buflen < 0) {
1766 goto illegal_request;
1768 break;
1769 case READ_DVD_STRUCTURE:
1770 buflen = scsi_read_dvd_structure(s, r, outbuf);
1771 if (buflen < 0) {
1772 goto illegal_request;
1774 break;
1775 case SERVICE_ACTION_IN_16:
1776 /* Service Action In subcommands. */
1777 if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
1778 DPRINTF("SAI READ CAPACITY(16)\n");
1779 memset(outbuf, 0, req->cmd.xfer);
1780 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1781 if (!nb_sectors) {
1782 scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1783 return 0;
1785 if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {
1786 goto illegal_request;
1788 nb_sectors /= s->qdev.blocksize / 512;
1789 /* Returned value is the address of the last sector. */
1790 nb_sectors--;
1791 /* Remember the new size for read/write sanity checking. */
1792 s->qdev.max_lba = nb_sectors;
1793 outbuf[0] = (nb_sectors >> 56) & 0xff;
1794 outbuf[1] = (nb_sectors >> 48) & 0xff;
1795 outbuf[2] = (nb_sectors >> 40) & 0xff;
1796 outbuf[3] = (nb_sectors >> 32) & 0xff;
1797 outbuf[4] = (nb_sectors >> 24) & 0xff;
1798 outbuf[5] = (nb_sectors >> 16) & 0xff;
1799 outbuf[6] = (nb_sectors >> 8) & 0xff;
1800 outbuf[7] = nb_sectors & 0xff;
1801 outbuf[8] = 0;
1802 outbuf[9] = 0;
1803 outbuf[10] = s->qdev.blocksize >> 8;
1804 outbuf[11] = 0;
1805 outbuf[12] = 0;
1806 outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1808 /* set TPE bit if the format supports discard */
1809 if (s->qdev.conf.discard_granularity) {
1810 outbuf[14] = 0x80;
1813 /* Protection, exponent and lowest lba field left blank. */
1814 break;
1816 DPRINTF("Unsupported Service Action In\n");
1817 goto illegal_request;
1818 case SYNCHRONIZE_CACHE:
1819 /* The request is used as the AIO opaque value, so add a ref. */
1820 scsi_req_ref(&r->req);
1821 bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1822 r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
1823 return 0;
1824 case SEEK_10:
1825 DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
1826 if (r->req.cmd.lba > s->qdev.max_lba) {
1827 goto illegal_lba;
1829 break;
1830 case MODE_SELECT:
1831 DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1832 break;
1833 case MODE_SELECT_10:
1834 DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1835 break;
1836 case UNMAP:
1837 DPRINTF("Unmap (len %lu)\n", (long)r->req.cmd.xfer);
1838 break;
1839 case WRITE_SAME_10:
1840 case WRITE_SAME_16:
1841 nb_sectors = scsi_data_cdb_length(r->req.cmd.buf);
1842 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1843 scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1844 return 0;
1846 if (!check_lba_range(s, r->req.cmd.lba, nb_sectors)) {
1847 goto illegal_lba;
1851 * We only support WRITE SAME with the unmap bit set for now.
1853 if (!(req->cmd.buf[1] & 0x8)) {
1854 goto illegal_request;
1857 /* The request is used as the AIO opaque value, so add a ref. */
1858 scsi_req_ref(&r->req);
1859 r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1860 r->req.cmd.lba * (s->qdev.blocksize / 512),
1861 nb_sectors * (s->qdev.blocksize / 512),
1862 scsi_aio_complete, r);
1863 return 0;
1864 default:
1865 DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1866 scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1867 return 0;
1869 assert(!r->req.aiocb);
1870 r->iov.iov_len = MIN(r->buflen, req->cmd.xfer);
1871 if (r->iov.iov_len == 0) {
1872 scsi_req_complete(&r->req, GOOD);
1874 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1875 assert(r->iov.iov_len == req->cmd.xfer);
1876 return -r->iov.iov_len;
1877 } else {
1878 return r->iov.iov_len;
1881 illegal_request:
1882 if (r->req.status == -1) {
1883 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1885 return 0;
1887 illegal_lba:
1888 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1889 return 0;
1892 /* Execute a scsi command. Returns the length of the data expected by the
1893 command. This will be Positive for data transfers from the device
1894 (eg. disk reads), negative for transfers to the device (eg. disk writes),
1895 and zero if the command does not transfer any data. */
1897 static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
1899 SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1900 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1901 uint32_t len;
1902 uint8_t command;
1904 command = buf[0];
1906 if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1907 scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1908 return 0;
1911 len = scsi_data_cdb_length(r->req.cmd.buf);
1912 switch (command) {
1913 case READ_6:
1914 case READ_10:
1915 case READ_12:
1916 case READ_16:
1917 DPRINTF("Read (sector %" PRId64 ", count %u)\n", r->req.cmd.lba, len);
1918 if (r->req.cmd.buf[1] & 0xe0) {
1919 goto illegal_request;
1921 if (!check_lba_range(s, r->req.cmd.lba, len)) {
1922 goto illegal_lba;
1924 r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1925 r->sector_count = len * (s->qdev.blocksize / 512);
1926 break;
1927 case WRITE_6:
1928 case WRITE_10:
1929 case WRITE_12:
1930 case WRITE_16:
1931 case WRITE_VERIFY_10:
1932 case WRITE_VERIFY_12:
1933 case WRITE_VERIFY_16:
1934 if (bdrv_is_read_only(s->qdev.conf.bs)) {
1935 scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1936 return 0;
1938 /* fallthrough */
1939 case VERIFY_10:
1940 case VERIFY_12:
1941 case VERIFY_16:
1942 DPRINTF("Write %s(sector %" PRId64 ", count %u)\n",
1943 (command & 0xe) == 0xe ? "And Verify " : "",
1944 r->req.cmd.lba, len);
1945 if (r->req.cmd.buf[1] & 0xe0) {
1946 goto illegal_request;
1948 if (!check_lba_range(s, r->req.cmd.lba, len)) {
1949 goto illegal_lba;
1951 r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1952 r->sector_count = len * (s->qdev.blocksize / 512);
1953 break;
1954 default:
1955 abort();
1956 illegal_request:
1957 scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1958 return 0;
1959 illegal_lba:
1960 scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1961 return 0;
1963 if (r->sector_count == 0) {
1964 scsi_req_complete(&r->req, GOOD);
1966 assert(r->iov.iov_len == 0);
1967 if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1968 return -r->sector_count * 512;
1969 } else {
1970 return r->sector_count * 512;
1974 static void scsi_disk_reset(DeviceState *dev)
1976 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1977 uint64_t nb_sectors;
1979 scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1981 bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1982 nb_sectors /= s->qdev.blocksize / 512;
1983 if (nb_sectors) {
1984 nb_sectors--;
1986 s->qdev.max_lba = nb_sectors;
1989 static void scsi_destroy(SCSIDevice *dev)
1991 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1993 scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1994 blockdev_mark_auto_del(s->qdev.conf.bs);
1997 static void scsi_disk_resize_cb(void *opaque)
1999 SCSIDiskState *s = opaque;
2001 /* SPC lists this sense code as available only for
2002 * direct-access devices.
2004 if (s->qdev.type == TYPE_DISK) {
2005 scsi_device_report_change(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
2009 static void scsi_cd_change_media_cb(void *opaque, bool load)
2011 SCSIDiskState *s = opaque;
2014 * When a CD gets changed, we have to report an ejected state and
2015 * then a loaded state to guests so that they detect tray
2016 * open/close and media change events. Guests that do not use
2017 * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
2018 * states rely on this behavior.
2020 * media_changed governs the state machine used for unit attention
2021 * report. media_event is used by GET EVENT STATUS NOTIFICATION.
2023 s->media_changed = load;
2024 s->tray_open = !load;
2025 scsi_device_set_ua(&s->qdev, SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM));
2026 s->media_event = true;
2027 s->eject_request = false;
2030 static void scsi_cd_eject_request_cb(void *opaque, bool force)
2032 SCSIDiskState *s = opaque;
2034 s->eject_request = true;
2035 if (force) {
2036 s->tray_locked = false;
2040 static bool scsi_cd_is_tray_open(void *opaque)
2042 return ((SCSIDiskState *)opaque)->tray_open;
2045 static bool scsi_cd_is_medium_locked(void *opaque)
2047 return ((SCSIDiskState *)opaque)->tray_locked;
2050 static const BlockDevOps scsi_disk_removable_block_ops = {
2051 .change_media_cb = scsi_cd_change_media_cb,
2052 .eject_request_cb = scsi_cd_eject_request_cb,
2053 .is_tray_open = scsi_cd_is_tray_open,
2054 .is_medium_locked = scsi_cd_is_medium_locked,
2056 .resize_cb = scsi_disk_resize_cb,
2059 static const BlockDevOps scsi_disk_block_ops = {
2060 .resize_cb = scsi_disk_resize_cb,
2063 static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
2065 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2066 if (s->media_changed) {
2067 s->media_changed = false;
2068 scsi_device_set_ua(&s->qdev, SENSE_CODE(MEDIUM_CHANGED));
2072 static int scsi_initfn(SCSIDevice *dev)
2074 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2076 if (!s->qdev.conf.bs) {
2077 error_report("drive property not set");
2078 return -1;
2081 if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&
2082 !bdrv_is_inserted(s->qdev.conf.bs)) {
2083 error_report("Device needs media, but drive is empty");
2084 return -1;
2087 blkconf_serial(&s->qdev.conf, &s->serial);
2088 if (dev->type == TYPE_DISK
2089 && blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
2090 return -1;
2093 if (s->qdev.conf.discard_granularity == -1) {
2094 s->qdev.conf.discard_granularity =
2095 MAX(s->qdev.conf.logical_block_size, DEFAULT_DISCARD_GRANULARITY);
2098 if (!s->version) {
2099 s->version = g_strdup(qemu_get_version());
2101 if (!s->vendor) {
2102 s->vendor = g_strdup("QEMU");
2105 if (bdrv_is_sg(s->qdev.conf.bs)) {
2106 error_report("unwanted /dev/sg*");
2107 return -1;
2110 if (s->features & (1 << SCSI_DISK_F_REMOVABLE)) {
2111 bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s);
2112 } else {
2113 bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s);
2115 bdrv_set_buffer_alignment(s->qdev.conf.bs, s->qdev.blocksize);
2117 bdrv_iostatus_enable(s->qdev.conf.bs);
2118 add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL);
2119 return 0;
2122 static int scsi_hd_initfn(SCSIDevice *dev)
2124 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2125 s->qdev.blocksize = s->qdev.conf.logical_block_size;
2126 s->qdev.type = TYPE_DISK;
2127 if (!s->product) {
2128 s->product = g_strdup("QEMU HARDDISK");
2130 return scsi_initfn(&s->qdev);
2133 static int scsi_cd_initfn(SCSIDevice *dev)
2135 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2136 s->qdev.blocksize = 2048;
2137 s->qdev.type = TYPE_ROM;
2138 s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2139 if (!s->product) {
2140 s->product = g_strdup("QEMU CD-ROM");
2142 return scsi_initfn(&s->qdev);
2145 static int scsi_disk_initfn(SCSIDevice *dev)
2147 DriveInfo *dinfo;
2149 if (!dev->conf.bs) {
2150 return scsi_initfn(dev); /* ... and die there */
2153 dinfo = drive_get_by_blockdev(dev->conf.bs);
2154 if (dinfo->media_cd) {
2155 return scsi_cd_initfn(dev);
2156 } else {
2157 return scsi_hd_initfn(dev);
2161 static const SCSIReqOps scsi_disk_emulate_reqops = {
2162 .size = sizeof(SCSIDiskReq),
2163 .free_req = scsi_free_request,
2164 .send_command = scsi_disk_emulate_command,
2165 .read_data = scsi_disk_emulate_read_data,
2166 .write_data = scsi_disk_emulate_write_data,
2167 .get_buf = scsi_get_buf,
2170 static const SCSIReqOps scsi_disk_dma_reqops = {
2171 .size = sizeof(SCSIDiskReq),
2172 .free_req = scsi_free_request,
2173 .send_command = scsi_disk_dma_command,
2174 .read_data = scsi_read_data,
2175 .write_data = scsi_write_data,
2176 .cancel_io = scsi_cancel_io,
2177 .get_buf = scsi_get_buf,
2178 .load_request = scsi_disk_load_request,
2179 .save_request = scsi_disk_save_request,
2182 static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
2183 [TEST_UNIT_READY] = &scsi_disk_emulate_reqops,
2184 [INQUIRY] = &scsi_disk_emulate_reqops,
2185 [MODE_SENSE] = &scsi_disk_emulate_reqops,
2186 [MODE_SENSE_10] = &scsi_disk_emulate_reqops,
2187 [START_STOP] = &scsi_disk_emulate_reqops,
2188 [ALLOW_MEDIUM_REMOVAL] = &scsi_disk_emulate_reqops,
2189 [READ_CAPACITY_10] = &scsi_disk_emulate_reqops,
2190 [READ_TOC] = &scsi_disk_emulate_reqops,
2191 [READ_DVD_STRUCTURE] = &scsi_disk_emulate_reqops,
2192 [READ_DISC_INFORMATION] = &scsi_disk_emulate_reqops,
2193 [GET_CONFIGURATION] = &scsi_disk_emulate_reqops,
2194 [GET_EVENT_STATUS_NOTIFICATION] = &scsi_disk_emulate_reqops,
2195 [MECHANISM_STATUS] = &scsi_disk_emulate_reqops,
2196 [SERVICE_ACTION_IN_16] = &scsi_disk_emulate_reqops,
2197 [REQUEST_SENSE] = &scsi_disk_emulate_reqops,
2198 [SYNCHRONIZE_CACHE] = &scsi_disk_emulate_reqops,
2199 [SEEK_10] = &scsi_disk_emulate_reqops,
2200 [MODE_SELECT] = &scsi_disk_emulate_reqops,
2201 [MODE_SELECT_10] = &scsi_disk_emulate_reqops,
2202 [UNMAP] = &scsi_disk_emulate_reqops,
2203 [WRITE_SAME_10] = &scsi_disk_emulate_reqops,
2204 [WRITE_SAME_16] = &scsi_disk_emulate_reqops,
2206 [READ_6] = &scsi_disk_dma_reqops,
2207 [READ_10] = &scsi_disk_dma_reqops,
2208 [READ_12] = &scsi_disk_dma_reqops,
2209 [READ_16] = &scsi_disk_dma_reqops,
2210 [VERIFY_10] = &scsi_disk_dma_reqops,
2211 [VERIFY_12] = &scsi_disk_dma_reqops,
2212 [VERIFY_16] = &scsi_disk_dma_reqops,
2213 [WRITE_6] = &scsi_disk_dma_reqops,
2214 [WRITE_10] = &scsi_disk_dma_reqops,
2215 [WRITE_12] = &scsi_disk_dma_reqops,
2216 [WRITE_16] = &scsi_disk_dma_reqops,
2217 [WRITE_VERIFY_10] = &scsi_disk_dma_reqops,
2218 [WRITE_VERIFY_12] = &scsi_disk_dma_reqops,
2219 [WRITE_VERIFY_16] = &scsi_disk_dma_reqops,
2222 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
2223 uint8_t *buf, void *hba_private)
2225 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2226 SCSIRequest *req;
2227 const SCSIReqOps *ops;
2228 uint8_t command;
2230 command = buf[0];
2231 ops = scsi_disk_reqops_dispatch[command];
2232 if (!ops) {
2233 ops = &scsi_disk_emulate_reqops;
2235 req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
2237 #ifdef DEBUG_SCSI
2238 DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
2240 int i;
2241 for (i = 1; i < req->cmd.len; i++) {
2242 printf(" 0x%02x", buf[i]);
2244 printf("\n");
2246 #endif
2248 return req;
2251 #ifdef __linux__
2252 static int get_device_type(SCSIDiskState *s)
2254 BlockDriverState *bdrv = s->qdev.conf.bs;
2255 uint8_t cmd[16];
2256 uint8_t buf[36];
2257 uint8_t sensebuf[8];
2258 sg_io_hdr_t io_header;
2259 int ret;
2261 memset(cmd, 0, sizeof(cmd));
2262 memset(buf, 0, sizeof(buf));
2263 cmd[0] = INQUIRY;
2264 cmd[4] = sizeof(buf);
2266 memset(&io_header, 0, sizeof(io_header));
2267 io_header.interface_id = 'S';
2268 io_header.dxfer_direction = SG_DXFER_FROM_DEV;
2269 io_header.dxfer_len = sizeof(buf);
2270 io_header.dxferp = buf;
2271 io_header.cmdp = cmd;
2272 io_header.cmd_len = sizeof(cmd);
2273 io_header.mx_sb_len = sizeof(sensebuf);
2274 io_header.sbp = sensebuf;
2275 io_header.timeout = 6000; /* XXX */
2277 ret = bdrv_ioctl(bdrv, SG_IO, &io_header);
2278 if (ret < 0 || io_header.driver_status || io_header.host_status) {
2279 return -1;
2281 s->qdev.type = buf[0];
2282 if (buf[1] & 0x80) {
2283 s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2285 return 0;
2288 static int scsi_block_initfn(SCSIDevice *dev)
2290 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2291 int sg_version;
2292 int rc;
2294 if (!s->qdev.conf.bs) {
2295 error_report("scsi-block: drive property not set");
2296 return -1;
2299 /* check we are using a driver managing SG_IO (version 3 and after) */
2300 if (bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 ||
2301 sg_version < 30000) {
2302 error_report("scsi-block: scsi generic interface too old");
2303 return -1;
2306 /* get device type from INQUIRY data */
2307 rc = get_device_type(s);
2308 if (rc < 0) {
2309 error_report("scsi-block: INQUIRY failed");
2310 return -1;
2313 /* Make a guess for the block size, we'll fix it when the guest sends.
2314 * READ CAPACITY. If they don't, they likely would assume these sizes
2315 * anyway. (TODO: check in /sys).
2317 if (s->qdev.type == TYPE_ROM || s->qdev.type == TYPE_WORM) {
2318 s->qdev.blocksize = 2048;
2319 } else {
2320 s->qdev.blocksize = 512;
2322 return scsi_initfn(&s->qdev);
2325 static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
2326 uint32_t lun, uint8_t *buf,
2327 void *hba_private)
2329 SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2331 switch (buf[0]) {
2332 case READ_6:
2333 case READ_10:
2334 case READ_12:
2335 case READ_16:
2336 case VERIFY_10:
2337 case VERIFY_12:
2338 case VERIFY_16:
2339 case WRITE_6:
2340 case WRITE_10:
2341 case WRITE_12:
2342 case WRITE_16:
2343 case WRITE_VERIFY_10:
2344 case WRITE_VERIFY_12:
2345 case WRITE_VERIFY_16:
2346 /* If we are not using O_DIRECT, we might read stale data from the
2347 * host cache if writes were made using other commands than these
2348 * ones (such as WRITE SAME or EXTENDED COPY, etc.). So, without
2349 * O_DIRECT everything must go through SG_IO.
2351 if (bdrv_get_flags(s->qdev.conf.bs) & BDRV_O_NOCACHE) {
2352 break;
2355 /* MMC writing cannot be done via pread/pwrite, because it sometimes
2356 * involves writing beyond the maximum LBA or to negative LBA (lead-in).
2357 * And once you do these writes, reading from the block device is
2358 * unreliable, too. It is even possible that reads deliver random data
2359 * from the host page cache (this is probably a Linux bug).
2361 * We might use scsi_disk_dma_reqops as long as no writing commands are
2362 * seen, but performance usually isn't paramount on optical media. So,
2363 * just make scsi-block operate the same as scsi-generic for them.
2365 if (s->qdev.type != TYPE_ROM) {
2366 return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun,
2367 hba_private);
2371 return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun,
2372 hba_private);
2374 #endif
2376 #define DEFINE_SCSI_DISK_PROPERTIES() \
2377 DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf), \
2378 DEFINE_PROP_STRING("ver", SCSIDiskState, version), \
2379 DEFINE_PROP_STRING("serial", SCSIDiskState, serial), \
2380 DEFINE_PROP_STRING("vendor", SCSIDiskState, vendor), \
2381 DEFINE_PROP_STRING("product", SCSIDiskState, product)
2383 static Property scsi_hd_properties[] = {
2384 DEFINE_SCSI_DISK_PROPERTIES(),
2385 DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2386 SCSI_DISK_F_REMOVABLE, false),
2387 DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2388 SCSI_DISK_F_DPOFUA, false),
2389 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2390 DEFINE_BLOCK_CHS_PROPERTIES(SCSIDiskState, qdev.conf),
2391 DEFINE_PROP_END_OF_LIST(),
2394 static const VMStateDescription vmstate_scsi_disk_state = {
2395 .name = "scsi-disk",
2396 .version_id = 1,
2397 .minimum_version_id = 1,
2398 .minimum_version_id_old = 1,
2399 .fields = (VMStateField[]) {
2400 VMSTATE_SCSI_DEVICE(qdev, SCSIDiskState),
2401 VMSTATE_BOOL(media_changed, SCSIDiskState),
2402 VMSTATE_BOOL(media_event, SCSIDiskState),
2403 VMSTATE_BOOL(eject_request, SCSIDiskState),
2404 VMSTATE_BOOL(tray_open, SCSIDiskState),
2405 VMSTATE_BOOL(tray_locked, SCSIDiskState),
2406 VMSTATE_END_OF_LIST()
2410 static void scsi_hd_class_initfn(ObjectClass *klass, void *data)
2412 DeviceClass *dc = DEVICE_CLASS(klass);
2413 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2415 sc->init = scsi_hd_initfn;
2416 sc->destroy = scsi_destroy;
2417 sc->alloc_req = scsi_new_request;
2418 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2419 dc->fw_name = "disk";
2420 dc->desc = "virtual SCSI disk";
2421 dc->reset = scsi_disk_reset;
2422 dc->props = scsi_hd_properties;
2423 dc->vmsd = &vmstate_scsi_disk_state;
2426 static const TypeInfo scsi_hd_info = {
2427 .name = "scsi-hd",
2428 .parent = TYPE_SCSI_DEVICE,
2429 .instance_size = sizeof(SCSIDiskState),
2430 .class_init = scsi_hd_class_initfn,
2433 static Property scsi_cd_properties[] = {
2434 DEFINE_SCSI_DISK_PROPERTIES(),
2435 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2436 DEFINE_PROP_END_OF_LIST(),
2439 static void scsi_cd_class_initfn(ObjectClass *klass, void *data)
2441 DeviceClass *dc = DEVICE_CLASS(klass);
2442 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2444 sc->init = scsi_cd_initfn;
2445 sc->destroy = scsi_destroy;
2446 sc->alloc_req = scsi_new_request;
2447 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2448 dc->fw_name = "disk";
2449 dc->desc = "virtual SCSI CD-ROM";
2450 dc->reset = scsi_disk_reset;
2451 dc->props = scsi_cd_properties;
2452 dc->vmsd = &vmstate_scsi_disk_state;
2455 static const TypeInfo scsi_cd_info = {
2456 .name = "scsi-cd",
2457 .parent = TYPE_SCSI_DEVICE,
2458 .instance_size = sizeof(SCSIDiskState),
2459 .class_init = scsi_cd_class_initfn,
2462 #ifdef __linux__
2463 static Property scsi_block_properties[] = {
2464 DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.bs),
2465 DEFINE_PROP_INT32("bootindex", SCSIDiskState, qdev.conf.bootindex, -1),
2466 DEFINE_PROP_END_OF_LIST(),
2469 static void scsi_block_class_initfn(ObjectClass *klass, void *data)
2471 DeviceClass *dc = DEVICE_CLASS(klass);
2472 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2474 sc->init = scsi_block_initfn;
2475 sc->destroy = scsi_destroy;
2476 sc->alloc_req = scsi_block_new_request;
2477 dc->fw_name = "disk";
2478 dc->desc = "SCSI block device passthrough";
2479 dc->reset = scsi_disk_reset;
2480 dc->props = scsi_block_properties;
2481 dc->vmsd = &vmstate_scsi_disk_state;
2484 static const TypeInfo scsi_block_info = {
2485 .name = "scsi-block",
2486 .parent = TYPE_SCSI_DEVICE,
2487 .instance_size = sizeof(SCSIDiskState),
2488 .class_init = scsi_block_class_initfn,
2490 #endif
2492 static Property scsi_disk_properties[] = {
2493 DEFINE_SCSI_DISK_PROPERTIES(),
2494 DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2495 SCSI_DISK_F_REMOVABLE, false),
2496 DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2497 SCSI_DISK_F_DPOFUA, false),
2498 DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2499 DEFINE_PROP_END_OF_LIST(),
2502 static void scsi_disk_class_initfn(ObjectClass *klass, void *data)
2504 DeviceClass *dc = DEVICE_CLASS(klass);
2505 SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2507 sc->init = scsi_disk_initfn;
2508 sc->destroy = scsi_destroy;
2509 sc->alloc_req = scsi_new_request;
2510 sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2511 dc->fw_name = "disk";
2512 dc->desc = "virtual SCSI disk or CD-ROM (legacy)";
2513 dc->reset = scsi_disk_reset;
2514 dc->props = scsi_disk_properties;
2515 dc->vmsd = &vmstate_scsi_disk_state;
2518 static const TypeInfo scsi_disk_info = {
2519 .name = "scsi-disk",
2520 .parent = TYPE_SCSI_DEVICE,
2521 .instance_size = sizeof(SCSIDiskState),
2522 .class_init = scsi_disk_class_initfn,
2525 static void scsi_disk_register_types(void)
2527 type_register_static(&scsi_hd_info);
2528 type_register_static(&scsi_cd_info);
2529 #ifdef __linux__
2530 type_register_static(&scsi_block_info);
2531 #endif
2532 type_register_static(&scsi_disk_info);
2535 type_init(scsi_disk_register_types)